hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
958k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f72a3383995074634d5dafb504c727c501dbf175
3,484
py
Python
tests/manage/rgw/test_bucket_deletion.py
prsurve/ocs-ci
a8e229755e1f9d43c8c71e5ba693cb14bfb38aed
[ "MIT" ]
null
null
null
tests/manage/rgw/test_bucket_deletion.py
prsurve/ocs-ci
a8e229755e1f9d43c8c71e5ba693cb14bfb38aed
[ "MIT" ]
null
null
null
tests/manage/rgw/test_bucket_deletion.py
prsurve/ocs-ci
a8e229755e1f9d43c8c71e5ba693cb14bfb38aed
[ "MIT" ]
null
null
null
import logging import botocore import pytest from flaky import flaky from ocs_ci.ocs.bucket_utils import retrieve_test_objects_to_pod, sync_object_directory from ocs_ci.framework import config from ocs_ci.framework.pytest_customization.marks import acceptance, tier1, tier3 from ocs_ci.ocs.exceptions import CommandFailed from ocs_ci.ocs.ocp import OCP from ocs_ci.ocs.resources.objectbucket import OBC logger = logging.getLogger(__name__) class TestBucketDeletion: """ Test deletion of RGW buckets """ @pytest.mark.parametrize( argnames="amount,interface", argvalues=[ pytest.param( *[3, "RGW-OC"], marks=[tier1, acceptance, pytest.mark.polarion_id("2248")], ), ], ) def test_bucket_delete(self, rgw_bucket_factory, amount, interface): """ Test deletion of buckets using OC commands """ for bucket in rgw_bucket_factory(amount, interface): logger.info(f"Deleting bucket: {bucket.name}") bucket.delete() @pytest.mark.parametrize( argnames="interface", argvalues=[ pytest.param( *["RGW-OC"], marks=[tier1, pytest.mark.polarion_id("OCS-2249")] ), ], ) @flaky def test_bucket_delete_with_objects( self, rgw_bucket_factory, interface, awscli_pod ): """ Negative test with deletion of bucket has objects stored in. """ bucket = rgw_bucket_factory(1, interface)[0] bucketname = bucket.name obc_obj = OBC(bucketname) try: data_dir = "/data" full_object_path = f"s3://{bucketname}" retrieve_test_objects_to_pod(awscli_pod, data_dir) sync_object_directory(awscli_pod, data_dir, full_object_path, obc_obj) logger.info(f"Deleting bucket: {bucketname}") if interface == "S3": try: s3_del = obc_obj.s3_resource.Bucket(bucketname).delete() assert ( not s3_del ), "Unexpected issue: Successfully deleted a bucket containing objects via S3" except botocore.exceptions.ClientError as err: assert "BucketNotEmpty" in str( err ), "Couldn't verify delete non-empty OBC with s3" logger.info(f"Delete non-empty OBC {bucketname} failed as expected") finally: bucket.delete() @pytest.mark.parametrize( argnames="interface", argvalues=[ pytest.param( *["RGW-OC"], marks=[tier3, pytest.mark.polarion_id("OCS-2244")] ), ], ) def test_nonexist_bucket_delete(self, interface): """ Negative test with deletion of a non-existent OBC. """ name = "test_nonexist_bucket_name" if interface == "RGW-OC": try: oc_del = OCP( kind="obc", namespace=config.ENV_DATA["cluster_namespace"] ).delete(resource_name=name) assert oc_del, "Unexpected oc delete non-exist OBC succeed" except CommandFailed as err: assert "NotFound" in str( err ), "Couldn't verify delete non-exist OBC with oc" logger.info(f"Delete non-exist OBC {name} failed as expected")
34.156863
98
0.581803
import logging import botocore import pytest from flaky import flaky from ocs_ci.ocs.bucket_utils import retrieve_test_objects_to_pod, sync_object_directory from ocs_ci.framework import config from ocs_ci.framework.pytest_customization.marks import acceptance, tier1, tier3 from ocs_ci.ocs.exceptions import CommandFailed from ocs_ci.ocs.ocp import OCP from ocs_ci.ocs.resources.objectbucket import OBC logger = logging.getLogger(__name__) class TestBucketDeletion: @pytest.mark.parametrize( argnames="amount,interface", argvalues=[ pytest.param( *[3, "RGW-OC"], marks=[tier1, acceptance, pytest.mark.polarion_id("2248")], ), ], ) def test_bucket_delete(self, rgw_bucket_factory, amount, interface): for bucket in rgw_bucket_factory(amount, interface): logger.info(f"Deleting bucket: {bucket.name}") bucket.delete() @pytest.mark.parametrize( argnames="interface", argvalues=[ pytest.param( *["RGW-OC"], marks=[tier1, pytest.mark.polarion_id("OCS-2249")] ), ], ) @flaky def test_bucket_delete_with_objects( self, rgw_bucket_factory, interface, awscli_pod ): bucket = rgw_bucket_factory(1, interface)[0] bucketname = bucket.name obc_obj = OBC(bucketname) try: data_dir = "/data" full_object_path = f"s3://{bucketname}" retrieve_test_objects_to_pod(awscli_pod, data_dir) sync_object_directory(awscli_pod, data_dir, full_object_path, obc_obj) logger.info(f"Deleting bucket: {bucketname}") if interface == "S3": try: s3_del = obc_obj.s3_resource.Bucket(bucketname).delete() assert ( not s3_del ), "Unexpected issue: Successfully deleted a bucket containing objects via S3" except botocore.exceptions.ClientError as err: assert "BucketNotEmpty" in str( err ), "Couldn't verify delete non-empty OBC with s3" logger.info(f"Delete non-empty OBC {bucketname} failed as expected") finally: bucket.delete() @pytest.mark.parametrize( argnames="interface", argvalues=[ pytest.param( *["RGW-OC"], marks=[tier3, pytest.mark.polarion_id("OCS-2244")] ), ], ) def test_nonexist_bucket_delete(self, interface): name = "test_nonexist_bucket_name" if interface == "RGW-OC": try: oc_del = OCP( kind="obc", namespace=config.ENV_DATA["cluster_namespace"] ).delete(resource_name=name) assert oc_del, "Unexpected oc delete non-exist OBC succeed" except CommandFailed as err: assert "NotFound" in str( err ), "Couldn't verify delete non-exist OBC with oc" logger.info(f"Delete non-exist OBC {name} failed as expected")
true
true
f72a33b918735569e106f2221c7a10a6e1392d92
1,864
py
Python
tests/test_transforms_resize_modulo_pad_crop.py
civodlu/trw
b9a1cf045f61d6df9c65c014ef63b4048972dcdc
[ "MIT" ]
3
2019-07-04T01:20:41.000Z
2020-01-27T02:36:12.000Z
tests/test_transforms_resize_modulo_pad_crop.py
civodlu/trw
b9a1cf045f61d6df9c65c014ef63b4048972dcdc
[ "MIT" ]
null
null
null
tests/test_transforms_resize_modulo_pad_crop.py
civodlu/trw
b9a1cf045f61d6df9c65c014ef63b4048972dcdc
[ "MIT" ]
2
2020-10-19T13:46:06.000Z
2021-12-27T02:18:10.000Z
import unittest import trw import torch import numpy as np class TestTransformsResizeModuloPadCrop(unittest.TestCase): def test_crop_mode_torch(self): batch = { 'images': torch.rand([2, 3, 64, 64], dtype=torch.float32) } tfm = trw.transforms.TransformResizeModuloCropPad(60) transformed = tfm(batch) assert transformed['images'].shape == (2, 3, 60, 60) def test_crop_mode_torch_multiples(self): # test with multiple of `multiples_of` shape batch = { 'images': torch.rand([2, 3, 64, 64], dtype=torch.float32) } tfm = trw.transforms.TransformResizeModuloCropPad(10) transformed = tfm(batch) assert transformed['images'].shape == (2, 3, 60, 60) def test_crop_mode_torch_different_shape(self): batch = { 'images': torch.rand([2, 3, 64, 64], dtype=torch.float32), 'images2': torch.rand([2, 1, 64, 64], dtype=torch.float32) } batch['images'][0, 0, 32, 32] = 42.0 batch['images2'][0, 0, 32, 32] = 42.0 tfm = trw.transforms.TransformResizeModuloCropPad(60) transformed = tfm(batch) # make sure we can handle different shapes of the same dimension assert transformed['images'].shape == (2, 3, 60, 60) assert transformed['images2'].shape == (2, 1, 60, 60) # make sure the crop/pad are the same for the different images indices = np.where(batch['images'].numpy() == 42) assert (batch['images2'][indices] == 42.0).all() def test_pad_mode_torch(self): batch = { 'images': torch.rand([2, 3, 65, 65], dtype=torch.float32) } tfm = trw.transforms.TransformResizeModuloCropPad(32, mode='pad') transformed = tfm(batch) assert transformed['images'].shape == (2, 3, 96, 96)
34.518519
73
0.603541
import unittest import trw import torch import numpy as np class TestTransformsResizeModuloPadCrop(unittest.TestCase): def test_crop_mode_torch(self): batch = { 'images': torch.rand([2, 3, 64, 64], dtype=torch.float32) } tfm = trw.transforms.TransformResizeModuloCropPad(60) transformed = tfm(batch) assert transformed['images'].shape == (2, 3, 60, 60) def test_crop_mode_torch_multiples(self): batch = { 'images': torch.rand([2, 3, 64, 64], dtype=torch.float32) } tfm = trw.transforms.TransformResizeModuloCropPad(10) transformed = tfm(batch) assert transformed['images'].shape == (2, 3, 60, 60) def test_crop_mode_torch_different_shape(self): batch = { 'images': torch.rand([2, 3, 64, 64], dtype=torch.float32), 'images2': torch.rand([2, 1, 64, 64], dtype=torch.float32) } batch['images'][0, 0, 32, 32] = 42.0 batch['images2'][0, 0, 32, 32] = 42.0 tfm = trw.transforms.TransformResizeModuloCropPad(60) transformed = tfm(batch) assert transformed['images'].shape == (2, 3, 60, 60) assert transformed['images2'].shape == (2, 1, 60, 60) indices = np.where(batch['images'].numpy() == 42) assert (batch['images2'][indices] == 42.0).all() def test_pad_mode_torch(self): batch = { 'images': torch.rand([2, 3, 65, 65], dtype=torch.float32) } tfm = trw.transforms.TransformResizeModuloCropPad(32, mode='pad') transformed = tfm(batch) assert transformed['images'].shape == (2, 3, 96, 96)
true
true
f72a348b9cd34cfd35f617a68b5a5d79dd7ba065
1,758
py
Python
biokit/services/coding_sequences/gc_content_second_position.py
JLSteenwyk/BioKIT
9ca31d8003dc845bf56b2c56c87820c0b05021c4
[ "MIT" ]
8
2021-10-03T21:08:33.000Z
2021-12-02T17:15:32.000Z
biokit/services/coding_sequences/gc_content_second_position.py
JLSteenwyk/BioKIT
9ca31d8003dc845bf56b2c56c87820c0b05021c4
[ "MIT" ]
null
null
null
biokit/services/coding_sequences/gc_content_second_position.py
JLSteenwyk/BioKIT
9ca31d8003dc845bf56b2c56c87820c0b05021c4
[ "MIT" ]
5
2021-10-05T06:25:03.000Z
2022-01-04T11:01:09.000Z
import re from .base import CodingSequence from ...helpers.files import read_and_parse_fasta_seqio class GCContentSecondPosition(CodingSequence): def __init__(self, args) -> None: super().__init__(**self.process_args(args)) def run(self): # create biopython object of sequences records = read_and_parse_fasta_seqio(self.fasta) if self.verbose: for record in records: second_position_char = [] second_position_char = self.get_second_position_char( record, second_position_char ) _, matches = self.find_matches("".join(second_position_char)) print( f"{record.id}\t{round(len(matches)/len(second_position_char), 4)}" ) else: second_position_char = [] for record in records: second_position_char = [] second_position_char = self.get_second_position_char( record, second_position_char ) _, matches = self.find_matches("".join(second_position_char)) print(f"{round(len(matches)/len(second_position_char), 4)}") def process_args(self, args): return dict(fasta=args.fasta, verbose=args.verbose) def find_matches(self, seq: str): regex_pattern = re.compile("[GgCc]") matches = regex_pattern.findall(seq) return seq, matches def get_second_position_char(self, record, second_position_char: list): length_of_coding_seq = len(record._seq) for i in range(0, length_of_coding_seq, 3): second_position_char.append(record._seq[i:i + 3][1]) return second_position_char
32.555556
86
0.612628
import re from .base import CodingSequence from ...helpers.files import read_and_parse_fasta_seqio class GCContentSecondPosition(CodingSequence): def __init__(self, args) -> None: super().__init__(**self.process_args(args)) def run(self): records = read_and_parse_fasta_seqio(self.fasta) if self.verbose: for record in records: second_position_char = [] second_position_char = self.get_second_position_char( record, second_position_char ) _, matches = self.find_matches("".join(second_position_char)) print( f"{record.id}\t{round(len(matches)/len(second_position_char), 4)}" ) else: second_position_char = [] for record in records: second_position_char = [] second_position_char = self.get_second_position_char( record, second_position_char ) _, matches = self.find_matches("".join(second_position_char)) print(f"{round(len(matches)/len(second_position_char), 4)}") def process_args(self, args): return dict(fasta=args.fasta, verbose=args.verbose) def find_matches(self, seq: str): regex_pattern = re.compile("[GgCc]") matches = regex_pattern.findall(seq) return seq, matches def get_second_position_char(self, record, second_position_char: list): length_of_coding_seq = len(record._seq) for i in range(0, length_of_coding_seq, 3): second_position_char.append(record._seq[i:i + 3][1]) return second_position_char
true
true
f72a34a439b3448174e70d31de729aeadbb9686e
187
py
Python
PCTC/2018 R2/Q5.py
object-oriented-human/competitive
9e761020e887d8980a39a64eeaeaa39af0ecd777
[ "MIT" ]
1
2022-02-21T15:43:01.000Z
2022-02-21T15:43:01.000Z
PCTC/2018 R2/Q5.py
foooop/competitive
9e761020e887d8980a39a64eeaeaa39af0ecd777
[ "MIT" ]
null
null
null
PCTC/2018 R2/Q5.py
foooop/competitive
9e761020e887d8980a39a64eeaeaa39af0ecd777
[ "MIT" ]
null
null
null
d = dict() l = [] for i in range(int(input())): x, y = input().split() d[y] = x l.append(y) l.sort() for i in range(len(l)): if d[l[i]] == "Percy": print(i+1) break
13.357143
29
0.481283
d = dict() l = [] for i in range(int(input())): x, y = input().split() d[y] = x l.append(y) l.sort() for i in range(len(l)): if d[l[i]] == "Percy": print(i+1) break
true
true
f72a34a70be9391c0ff557e2faf72cca8765883e
2,747
py
Python
challenge.py
DaneliaSanchz/challenge-python-07
73b11936bf8fff81f99c271b2bf1c244706af207
[ "MIT" ]
null
null
null
challenge.py
DaneliaSanchz/challenge-python-07
73b11936bf8fff81f99c271b2bf1c244706af207
[ "MIT" ]
null
null
null
challenge.py
DaneliaSanchz/challenge-python-07
73b11936bf8fff81f99c271b2bf1c244706af207
[ "MIT" ]
null
null
null
DATA = [ { 'name': 'Facundo', 'age': 72, 'organization': 'Platzi', 'position': 'Technical Mentor', 'language': 'python', }, { 'name': 'Luisana', 'age': 33, 'organization': 'Globant', 'position': 'UX Designer', 'language': 'javascript', }, { 'name': 'Héctor', 'age': 19, 'organization': 'Platzi', 'position': 'Associate', 'language': 'ruby', }, { 'name': 'Gabriel', 'age': 20, 'organization': 'Platzi', 'position': 'Associate', 'language': 'javascript', }, { 'name': 'Mariandrea', 'age': 30, 'organization': 'Platzi', 'position': 'QA Manager', 'language': 'java', }, { 'name': 'Karo', 'age': 23, 'organization': 'Everis', 'position': 'Backend Developer', 'language': 'python', }, { 'name': 'Ariel', 'age': 32, 'organization': 'Rappi', 'position': 'Support', 'language': '', }, { 'name': 'Juan', 'age': 17, 'organization': '', 'position': 'Student', 'language': 'go', }, { 'name': 'Pablo', 'age': 32, 'organization': 'Master', 'position': 'Human Resources Manager', 'language': 'python', }, { 'name': 'Lorena', 'age': 56, 'organization': 'Python Organization', 'position': 'Language Maker', 'language': 'python', }, ] def homeless(data): person = data.copy() if data['organization'] == '': person['homeless'] = True else: person['homeless'] = False return person def old(data): person = data.copy() if data['age'] > 30: person['old'] = True else: person['old'] = 'False' return person def run(): all_python_devs = list(filter(lambda dev: dev['language'] == 'python' , DATA)) all_Platzi_workers = list(filter(lambda worker: worker['organization'] == 'Platzi', DATA)) adults = list(filter(lambda person: person['age'] > 18, DATA)) workers = list(map(homeless, DATA)) old_people = list(map(old, DATA)) print('Python devs: ') for dev in all_python_devs: print(dev['name']) print('\n\n') print('Platzi workers: ') for worker in all_Platzi_workers: print(worker['name']) print('\n\n') print('Adults: ') for adult in adults: print(adult['name']) print('\n\n') print(workers) print('\n\n') print(old_people) print('\n\n') # Remember: when possible, use lambdas if __name__ == '__main__': run()
21.801587
94
0.486713
DATA = [ { 'name': 'Facundo', 'age': 72, 'organization': 'Platzi', 'position': 'Technical Mentor', 'language': 'python', }, { 'name': 'Luisana', 'age': 33, 'organization': 'Globant', 'position': 'UX Designer', 'language': 'javascript', }, { 'name': 'Héctor', 'age': 19, 'organization': 'Platzi', 'position': 'Associate', 'language': 'ruby', }, { 'name': 'Gabriel', 'age': 20, 'organization': 'Platzi', 'position': 'Associate', 'language': 'javascript', }, { 'name': 'Mariandrea', 'age': 30, 'organization': 'Platzi', 'position': 'QA Manager', 'language': 'java', }, { 'name': 'Karo', 'age': 23, 'organization': 'Everis', 'position': 'Backend Developer', 'language': 'python', }, { 'name': 'Ariel', 'age': 32, 'organization': 'Rappi', 'position': 'Support', 'language': '', }, { 'name': 'Juan', 'age': 17, 'organization': '', 'position': 'Student', 'language': 'go', }, { 'name': 'Pablo', 'age': 32, 'organization': 'Master', 'position': 'Human Resources Manager', 'language': 'python', }, { 'name': 'Lorena', 'age': 56, 'organization': 'Python Organization', 'position': 'Language Maker', 'language': 'python', }, ] def homeless(data): person = data.copy() if data['organization'] == '': person['homeless'] = True else: person['homeless'] = False return person def old(data): person = data.copy() if data['age'] > 30: person['old'] = True else: person['old'] = 'False' return person def run(): all_python_devs = list(filter(lambda dev: dev['language'] == 'python' , DATA)) all_Platzi_workers = list(filter(lambda worker: worker['organization'] == 'Platzi', DATA)) adults = list(filter(lambda person: person['age'] > 18, DATA)) workers = list(map(homeless, DATA)) old_people = list(map(old, DATA)) print('Python devs: ') for dev in all_python_devs: print(dev['name']) print('\n\n') print('Platzi workers: ') for worker in all_Platzi_workers: print(worker['name']) print('\n\n') print('Adults: ') for adult in adults: print(adult['name']) print('\n\n') print(workers) print('\n\n') print(old_people) print('\n\n') if __name__ == '__main__': run()
true
true
f72a34fcaec6d61776028925ec6417f22ff909c9
30,977
py
Python
flask/lib/python3.4/site-packages/babel/messages/catalog.py
ddayguerrero/blogme
e6ee6a47310c382648eefd96634630c3bceb864f
[ "MIT" ]
null
null
null
flask/lib/python3.4/site-packages/babel/messages/catalog.py
ddayguerrero/blogme
e6ee6a47310c382648eefd96634630c3bceb864f
[ "MIT" ]
null
null
null
flask/lib/python3.4/site-packages/babel/messages/catalog.py
ddayguerrero/blogme
e6ee6a47310c382648eefd96634630c3bceb864f
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ babel.messages.catalog ~~~~~~~~~~~~~~~~~~~~~~ Data structures for message catalogs. :copyright: (c) 2013 by the Babel Team. :license: BSD, see LICENSE for more details. """ import re import time from cgi import parse_header from datetime import datetime, time as time_ from difflib import get_close_matches from email import message_from_string from copy import copy from babel import __version__ as VERSION from babel.core import Locale from babel.dates import format_datetime from babel.messages.plurals import get_plural from babel.util import odict, distinct, LOCALTZ, FixedOffsetTimezone from babel._compat import string_types, number_types, PY2, cmp __all__ = ['Message', 'Catalog', 'TranslationError'] PYTHON_FORMAT = re.compile(r'''(?x) \% (?:\(([\w]*)\))? ( [-#0\ +]?(?:\*|[\d]+)? (?:\.(?:\*|[\d]+))? [hlL]? ) ([diouxXeEfFgGcrs%]) ''') def _parse_datetime_header(value): match = re.match(r'^(?P<datetime>.*?)(?P<tzoffset>[+-]\d{4})?$', value) tt = time.strptime(match.group('datetime'), '%Y-%m-%d %H:%M') ts = time.mktime(tt) dt = datetime.fromtimestamp(ts) # Separate the offset into a sign component, hours, and # minutes tzoffset = match.group('tzoffset') if tzoffset is not None: plus_minus_s, rest = tzoffset[0], tzoffset[1:] hours_offset_s, mins_offset_s = rest[:2], rest[2:] # Make them all integers plus_minus = int(plus_minus_s + '1') hours_offset = int(hours_offset_s) mins_offset = int(mins_offset_s) # Calculate net offset net_mins_offset = hours_offset * 60 net_mins_offset += mins_offset net_mins_offset *= plus_minus # Create an offset object tzoffset = FixedOffsetTimezone(net_mins_offset) # Store the offset in a datetime object dt = dt.replace(tzinfo=tzoffset) return dt class Message(object): """Representation of a single message in a catalog.""" def __init__(self, id, string=u'', locations=(), flags=(), auto_comments=(), user_comments=(), previous_id=(), lineno=None, context=None): """Create the message object. :param id: the message ID, or a ``(singular, plural)`` tuple for pluralizable messages :param string: the translated message string, or a ``(singular, plural)`` tuple for pluralizable messages :param locations: a sequence of ``(filenname, lineno)`` tuples :param flags: a set or sequence of flags :param auto_comments: a sequence of automatic comments for the message :param user_comments: a sequence of user comments for the message :param previous_id: the previous message ID, or a ``(singular, plural)`` tuple for pluralizable messages :param lineno: the line number on which the msgid line was found in the PO file, if any :param context: the message context """ self.id = id if not string and self.pluralizable: string = (u'', u'') self.string = string self.locations = list(distinct(locations)) self.flags = set(flags) if id and self.python_format: self.flags.add('python-format') else: self.flags.discard('python-format') self.auto_comments = list(distinct(auto_comments)) self.user_comments = list(distinct(user_comments)) if isinstance(previous_id, string_types): self.previous_id = [previous_id] else: self.previous_id = list(previous_id) self.lineno = lineno self.context = context def __repr__(self): return '<%s %r (flags: %r)>' % (type(self).__name__, self.id, list(self.flags)) def __cmp__(self, obj): """Compare Messages, taking into account plural ids""" def values_to_compare(): if isinstance(obj, Message): plural = self.pluralizable obj_plural = obj.pluralizable if plural and obj_plural: return self.id[0], obj.id[0] elif plural: return self.id[0], obj.id elif obj_plural: return self.id, obj.id[0] return self.id, obj.id this, other = values_to_compare() return cmp(this, other) def __gt__(self, other): return self.__cmp__(other) > 0 def __lt__(self, other): return self.__cmp__(other) < 0 def __ge__(self, other): return self.__cmp__(other) >= 0 def __le__(self, other): return self.__cmp__(other) <= 0 def __eq__(self, other): return self.__cmp__(other) == 0 def __ne__(self, other): return self.__cmp__(other) != 0 def clone(self): return Message(*map(copy, (self.id, self.string, self.locations, self.flags, self.auto_comments, self.user_comments, self.previous_id, self.lineno, self.context))) def check(self, catalog=None): """Run various validation checks on the message. Some validations are only performed if the catalog is provided. This method returns a sequence of `TranslationError` objects. :rtype: ``iterator`` :param catalog: A catalog instance that is passed to the checkers :see: `Catalog.check` for a way to perform checks for all messages in a catalog. """ from babel.messages.checkers import checkers errors = [] for checker in checkers: try: checker(catalog, self) except TranslationError as e: errors.append(e) return errors @property def fuzzy(self): """Whether the translation is fuzzy. >>> Message('foo').fuzzy False >>> msg = Message('foo', 'foo', flags=['fuzzy']) >>> msg.fuzzy True >>> msg <Message 'foo' (flags: ['fuzzy'])> :type: `bool`""" return 'fuzzy' in self.flags @property def pluralizable(self): """Whether the message is plurizable. >>> Message('foo').pluralizable False >>> Message(('foo', 'bar')).pluralizable True :type: `bool`""" return isinstance(self.id, (list, tuple)) @property def python_format(self): """Whether the message contains Python-style parameters. >>> Message('foo %(name)s bar').python_format True >>> Message(('foo %(name)s', 'foo %(name)s')).python_format True :type: `bool`""" ids = self.id if not isinstance(ids, (list, tuple)): ids = [ids] return any(PYTHON_FORMAT.search(id) for id in ids) class TranslationError(Exception): """Exception thrown by translation checkers when invalid message translations are encountered.""" DEFAULT_HEADER = u"""\ # Translations template for PROJECT. # Copyright (C) YEAR ORGANIZATION # This file is distributed under the same license as the PROJECT project. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. #""" if PY2: def _parse_header(header_string): # message_from_string only works for str, not for unicode headers = message_from_string(header_string.encode('utf8')) decoded_headers = {} for name, value in headers.items(): name = name.decode('utf8') value = value.decode('utf8') decoded_headers[name] = value return decoded_headers else: _parse_header = message_from_string class Catalog(object): """Representation of a message catalog.""" def __init__(self, locale=None, domain=None, header_comment=DEFAULT_HEADER, project=None, version=None, copyright_holder=None, msgid_bugs_address=None, creation_date=None, revision_date=None, last_translator=None, language_team=None, charset=None, fuzzy=True): """Initialize the catalog object. :param locale: the locale identifier or `Locale` object, or `None` if the catalog is not bound to a locale (which basically means it's a template) :param domain: the message domain :param header_comment: the header comment as string, or `None` for the default header :param project: the project's name :param version: the project's version :param copyright_holder: the copyright holder of the catalog :param msgid_bugs_address: the email address or URL to submit bug reports to :param creation_date: the date the catalog was created :param revision_date: the date the catalog was revised :param last_translator: the name and email of the last translator :param language_team: the name and email of the language team :param charset: the encoding to use in the output (defaults to utf-8) :param fuzzy: the fuzzy bit on the catalog header """ self.domain = domain if locale: locale = Locale.parse(locale) self.locale = locale self._header_comment = header_comment self._messages = odict() self.project = project or 'PROJECT' self.version = version or 'VERSION' self.copyright_holder = copyright_holder or 'ORGANIZATION' self.msgid_bugs_address = msgid_bugs_address or 'EMAIL@ADDRESS' self.last_translator = last_translator or 'FULL NAME <EMAIL@ADDRESS>' """Name and email address of the last translator.""" self.language_team = language_team or 'LANGUAGE <LL@li.org>' """Name and email address of the language team.""" self.charset = charset or 'utf-8' if creation_date is None: creation_date = datetime.now(LOCALTZ) elif isinstance(creation_date, datetime) and not creation_date.tzinfo: creation_date = creation_date.replace(tzinfo=LOCALTZ) self.creation_date = creation_date if revision_date is None: revision_date = 'YEAR-MO-DA HO:MI+ZONE' elif isinstance(revision_date, datetime) and not revision_date.tzinfo: revision_date = revision_date.replace(tzinfo=LOCALTZ) self.revision_date = revision_date self.fuzzy = fuzzy self.obsolete = odict() # Dictionary of obsolete messages self._num_plurals = None self._plural_expr = None def _get_header_comment(self): comment = self._header_comment year = datetime.now(LOCALTZ).strftime('%Y') if hasattr(self.revision_date, 'strftime'): year = self.revision_date.strftime('%Y') comment = comment.replace('PROJECT', self.project) \ .replace('VERSION', self.version) \ .replace('YEAR', year) \ .replace('ORGANIZATION', self.copyright_holder) if self.locale: comment = comment.replace('Translations template', '%s translations' % self.locale.english_name) return comment def _set_header_comment(self, string): self._header_comment = string header_comment = property(_get_header_comment, _set_header_comment, doc="""\ The header comment for the catalog. >>> catalog = Catalog(project='Foobar', version='1.0', ... copyright_holder='Foo Company') >>> print(catalog.header_comment) #doctest: +ELLIPSIS # Translations template for Foobar. # Copyright (C) ... Foo Company # This file is distributed under the same license as the Foobar project. # FIRST AUTHOR <EMAIL@ADDRESS>, .... # The header can also be set from a string. Any known upper-case variables will be replaced when the header is retrieved again: >>> catalog = Catalog(project='Foobar', version='1.0', ... copyright_holder='Foo Company') >>> catalog.header_comment = '''\\ ... # The POT for my really cool PROJECT project. ... # Copyright (C) 1990-2003 ORGANIZATION ... # This file is distributed under the same license as the PROJECT ... # project. ... #''' >>> print(catalog.header_comment) # The POT for my really cool Foobar project. # Copyright (C) 1990-2003 Foo Company # This file is distributed under the same license as the Foobar # project. # :type: `unicode` """) def _get_mime_headers(self): headers = [] headers.append(('Project-Id-Version', '%s %s' % (self.project, self.version))) headers.append(('Report-Msgid-Bugs-To', self.msgid_bugs_address)) headers.append(('POT-Creation-Date', format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ', locale='en'))) if isinstance(self.revision_date, (datetime, time_) + number_types): headers.append(('PO-Revision-Date', format_datetime(self.revision_date, 'yyyy-MM-dd HH:mmZ', locale='en'))) else: headers.append(('PO-Revision-Date', self.revision_date)) headers.append(('Last-Translator', self.last_translator)) if self.locale is not None: headers.append(('Language', str(self.locale))) if (self.locale is not None) and ('LANGUAGE' in self.language_team): headers.append(('Language-Team', self.language_team.replace('LANGUAGE', str(self.locale)))) else: headers.append(('Language-Team', self.language_team)) if self.locale is not None: headers.append(('Plural-Forms', self.plural_forms)) headers.append(('MIME-Version', '1.0')) headers.append(('Content-Type', 'text/plain; charset=%s' % self.charset)) headers.append(('Content-Transfer-Encoding', '8bit')) headers.append(('Generated-By', 'Babel %s\n' % VERSION)) return headers def _set_mime_headers(self, headers): for name, value in headers: name = name.lower() if name == 'project-id-version': parts = value.split(' ') self.project = u' '.join(parts[:-1]) self.version = parts[-1] elif name == 'report-msgid-bugs-to': self.msgid_bugs_address = value elif name == 'last-translator': self.last_translator = value elif name == 'language-team': self.language_team = value elif name == 'content-type': mimetype, params = parse_header(value) if 'charset' in params: self.charset = params['charset'].lower() elif name == 'plural-forms': _, params = parse_header(' ;' + value) self._num_plurals = int(params.get('nplurals', 2)) self._plural_expr = params.get('plural', '(n != 1)') elif name == 'pot-creation-date': self.creation_date = _parse_datetime_header(value) elif name == 'po-revision-date': # Keep the value if it's not the default one if 'YEAR' not in value: self.revision_date = _parse_datetime_header(value) mime_headers = property(_get_mime_headers, _set_mime_headers, doc="""\ The MIME headers of the catalog, used for the special ``msgid ""`` entry. The behavior of this property changes slightly depending on whether a locale is set or not, the latter indicating that the catalog is actually a template for actual translations. Here's an example of the output for such a catalog template: >>> from babel.dates import UTC >>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC) >>> catalog = Catalog(project='Foobar', version='1.0', ... creation_date=created) >>> for name, value in catalog.mime_headers: ... print('%s: %s' % (name, value)) Project-Id-Version: Foobar 1.0 Report-Msgid-Bugs-To: EMAIL@ADDRESS POT-Creation-Date: 1990-04-01 15:30+0000 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME <EMAIL@ADDRESS> Language-Team: LANGUAGE <LL@li.org> MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel ... And here's an example of the output when the locale is set: >>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC) >>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0', ... creation_date=created, revision_date=revised, ... last_translator='John Doe <jd@example.com>', ... language_team='de_DE <de@example.com>') >>> for name, value in catalog.mime_headers: ... print('%s: %s' % (name, value)) Project-Id-Version: Foobar 1.0 Report-Msgid-Bugs-To: EMAIL@ADDRESS POT-Creation-Date: 1990-04-01 15:30+0000 PO-Revision-Date: 1990-08-03 12:00+0000 Last-Translator: John Doe <jd@example.com> Language: de_DE Language-Team: de_DE <de@example.com> Plural-Forms: nplurals=2; plural=(n != 1) MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel ... :type: `list` """) @property def num_plurals(self): """The number of plurals used by the catalog or locale. >>> Catalog(locale='en').num_plurals 2 >>> Catalog(locale='ga').num_plurals 3 :type: `int`""" if self._num_plurals is None: num = 2 if self.locale: num = get_plural(self.locale)[0] self._num_plurals = num return self._num_plurals @property def plural_expr(self): """The plural expression used by the catalog or locale. >>> Catalog(locale='en').plural_expr '(n != 1)' >>> Catalog(locale='ga').plural_expr '(n==1 ? 0 : n==2 ? 1 : 2)' :type: `string_types`""" if self._plural_expr is None: expr = '(n != 1)' if self.locale: expr = get_plural(self.locale)[1] self._plural_expr = expr return self._plural_expr @property def plural_forms(self): """Return the plural forms declaration for the locale. >>> Catalog(locale='en').plural_forms 'nplurals=2; plural=(n != 1)' >>> Catalog(locale='pt_BR').plural_forms 'nplurals=2; plural=(n > 1)' :type: `str`""" return 'nplurals=%s; plural=%s' % (self.num_plurals, self.plural_expr) def __contains__(self, id): """Return whether the catalog has a message with the specified ID.""" return self._key_for(id) in self._messages def __len__(self): """The number of messages in the catalog. This does not include the special ``msgid ""`` entry.""" return len(self._messages) def __iter__(self): """Iterates through all the entries in the catalog, in the order they were added, yielding a `Message` object for every entry. :rtype: ``iterator``""" buf = [] for name, value in self.mime_headers: buf.append('%s: %s' % (name, value)) flags = set() if self.fuzzy: flags |= set(['fuzzy']) yield Message(u'', '\n'.join(buf), flags=flags) for key in self._messages: yield self._messages[key] def __repr__(self): locale = '' if self.locale: locale = ' %s' % self.locale return '<%s %r%s>' % (type(self).__name__, self.domain, locale) def __delitem__(self, id): """Delete the message with the specified ID.""" self.delete(id) def __getitem__(self, id): """Return the message with the specified ID. :param id: the message ID """ return self.get(id) def __setitem__(self, id, message): """Add or update the message with the specified ID. >>> catalog = Catalog() >>> catalog[u'foo'] = Message(u'foo') >>> catalog[u'foo'] <Message u'foo' (flags: [])> If a message with that ID is already in the catalog, it is updated to include the locations and flags of the new message. >>> catalog = Catalog() >>> catalog[u'foo'] = Message(u'foo', locations=[('main.py', 1)]) >>> catalog[u'foo'].locations [('main.py', 1)] >>> catalog[u'foo'] = Message(u'foo', locations=[('utils.py', 5)]) >>> catalog[u'foo'].locations [('main.py', 1), ('utils.py', 5)] :param id: the message ID :param message: the `Message` object """ assert isinstance(message, Message), 'expected a Message object' key = self._key_for(id, message.context) current = self._messages.get(key) if current: if message.pluralizable and not current.pluralizable: # The new message adds pluralization current.id = message.id current.string = message.string current.locations = list(distinct(current.locations + message.locations)) current.auto_comments = list(distinct(current.auto_comments + message.auto_comments)) current.user_comments = list(distinct(current.user_comments + message.user_comments)) current.flags |= message.flags message = current elif id == '': # special treatment for the header message self.mime_headers = _parse_header(message.string).items() self.header_comment = '\n'.join([('# %s' % c).rstrip() for c in message.user_comments]) self.fuzzy = message.fuzzy else: if isinstance(id, (list, tuple)): assert isinstance(message.string, (list, tuple)), \ 'Expected sequence but got %s' % type(message.string) self._messages[key] = message def add(self, id, string=None, locations=(), flags=(), auto_comments=(), user_comments=(), previous_id=(), lineno=None, context=None): """Add or update the message with the specified ID. >>> catalog = Catalog() >>> catalog.add(u'foo') <Message ...> >>> catalog[u'foo'] <Message u'foo' (flags: [])> This method simply constructs a `Message` object with the given arguments and invokes `__setitem__` with that object. :param id: the message ID, or a ``(singular, plural)`` tuple for pluralizable messages :param string: the translated message string, or a ``(singular, plural)`` tuple for pluralizable messages :param locations: a sequence of ``(filenname, lineno)`` tuples :param flags: a set or sequence of flags :param auto_comments: a sequence of automatic comments :param user_comments: a sequence of user comments :param previous_id: the previous message ID, or a ``(singular, plural)`` tuple for pluralizable messages :param lineno: the line number on which the msgid line was found in the PO file, if any :param context: the message context """ message = Message(id, string, list(locations), flags, auto_comments, user_comments, previous_id, lineno=lineno, context=context) self[id] = message return message def check(self): """Run various validation checks on the translations in the catalog. For every message which fails validation, this method yield a ``(message, errors)`` tuple, where ``message`` is the `Message` object and ``errors`` is a sequence of `TranslationError` objects. :rtype: ``iterator`` """ for message in self._messages.values(): errors = message.check(catalog=self) if errors: yield message, errors def get(self, id, context=None): """Return the message with the specified ID and context. :param id: the message ID :param context: the message context, or ``None`` for no context """ return self._messages.get(self._key_for(id, context)) def delete(self, id, context=None): """Delete the message with the specified ID and context. :param id: the message ID :param context: the message context, or ``None`` for no context """ key = self._key_for(id, context) if key in self._messages: del self._messages[key] def update(self, template, no_fuzzy_matching=False): """Update the catalog based on the given template catalog. >>> from babel.messages import Catalog >>> template = Catalog() >>> template.add('green', locations=[('main.py', 99)]) <Message ...> >>> template.add('blue', locations=[('main.py', 100)]) <Message ...> >>> template.add(('salad', 'salads'), locations=[('util.py', 42)]) <Message ...> >>> catalog = Catalog(locale='de_DE') >>> catalog.add('blue', u'blau', locations=[('main.py', 98)]) <Message ...> >>> catalog.add('head', u'Kopf', locations=[('util.py', 33)]) <Message ...> >>> catalog.add(('salad', 'salads'), (u'Salat', u'Salate'), ... locations=[('util.py', 38)]) <Message ...> >>> catalog.update(template) >>> len(catalog) 3 >>> msg1 = catalog['green'] >>> msg1.string >>> msg1.locations [('main.py', 99)] >>> msg2 = catalog['blue'] >>> msg2.string u'blau' >>> msg2.locations [('main.py', 100)] >>> msg3 = catalog['salad'] >>> msg3.string (u'Salat', u'Salate') >>> msg3.locations [('util.py', 42)] Messages that are in the catalog but not in the template are removed from the main collection, but can still be accessed via the `obsolete` member: >>> 'head' in catalog False >>> list(catalog.obsolete.values()) [<Message 'head' (flags: [])>] :param template: the reference catalog, usually read from a POT file :param no_fuzzy_matching: whether to use fuzzy matching of message IDs """ messages = self._messages remaining = messages.copy() self._messages = odict() # Prepare for fuzzy matching fuzzy_candidates = [] if not no_fuzzy_matching: fuzzy_candidates = dict([ (self._key_for(msgid), messages[msgid].context) for msgid in messages if msgid and messages[msgid].string ]) fuzzy_matches = set() def _merge(message, oldkey, newkey): message = message.clone() fuzzy = False if oldkey != newkey: fuzzy = True fuzzy_matches.add(oldkey) oldmsg = messages.get(oldkey) if isinstance(oldmsg.id, string_types): message.previous_id = [oldmsg.id] else: message.previous_id = list(oldmsg.id) else: oldmsg = remaining.pop(oldkey, None) message.string = oldmsg.string if isinstance(message.id, (list, tuple)): if not isinstance(message.string, (list, tuple)): fuzzy = True message.string = tuple( [message.string] + ([u''] * (len(message.id) - 1)) ) elif len(message.string) != self.num_plurals: fuzzy = True message.string = tuple(message.string[:len(oldmsg.string)]) elif isinstance(message.string, (list, tuple)): fuzzy = True message.string = message.string[0] message.flags |= oldmsg.flags if fuzzy: message.flags |= set([u'fuzzy']) self[message.id] = message for message in template: if message.id: key = self._key_for(message.id, message.context) if key in messages: _merge(message, key, key) else: if no_fuzzy_matching is False: # do some fuzzy matching with difflib if isinstance(key, tuple): matchkey = key[0] # just the msgid, no context else: matchkey = key matches = get_close_matches(matchkey.lower().strip(), fuzzy_candidates.keys(), 1) if matches: newkey = matches[0] newctxt = fuzzy_candidates[newkey] if newctxt is not None: newkey = newkey, newctxt _merge(message, newkey, key) continue self[message.id] = message for msgid in remaining: if no_fuzzy_matching or msgid not in fuzzy_matches: self.obsolete[msgid] = remaining[msgid] # Allow the updated catalog's header to be rewritten based on the # template's header self.header_comment = template.header_comment # Make updated catalog's POT-Creation-Date equal to the template # used to update the catalog self.creation_date = template.creation_date def _key_for(self, id, context=None): """The key for a message is just the singular ID even for pluralizable messages, but is a ``(msgid, msgctxt)`` tuple for context-specific messages. """ key = id if isinstance(key, (list, tuple)): key = id[0] if context is not None: key = (key, context) return key
37.776829
80
0.569067
import re import time from cgi import parse_header from datetime import datetime, time as time_ from difflib import get_close_matches from email import message_from_string from copy import copy from babel import __version__ as VERSION from babel.core import Locale from babel.dates import format_datetime from babel.messages.plurals import get_plural from babel.util import odict, distinct, LOCALTZ, FixedOffsetTimezone from babel._compat import string_types, number_types, PY2, cmp __all__ = ['Message', 'Catalog', 'TranslationError'] PYTHON_FORMAT = re.compile(r'''(?x) \% (?:\(([\w]*)\))? ( [-#0\ +]?(?:\*|[\d]+)? (?:\.(?:\*|[\d]+))? [hlL]? ) ([diouxXeEfFgGcrs%]) ''') def _parse_datetime_header(value): match = re.match(r'^(?P<datetime>.*?)(?P<tzoffset>[+-]\d{4})?$', value) tt = time.strptime(match.group('datetime'), '%Y-%m-%d %H:%M') ts = time.mktime(tt) dt = datetime.fromtimestamp(ts) fset = match.group('tzoffset') if tzoffset is not None: plus_minus_s, rest = tzoffset[0], tzoffset[1:] hours_offset_s, mins_offset_s = rest[:2], rest[2:] plus_minus = int(plus_minus_s + '1') hours_offset = int(hours_offset_s) mins_offset = int(mins_offset_s) net_mins_offset = hours_offset * 60 net_mins_offset += mins_offset net_mins_offset *= plus_minus tzoffset = FixedOffsetTimezone(net_mins_offset) dt = dt.replace(tzinfo=tzoffset) return dt class Message(object): def __init__(self, id, string=u'', locations=(), flags=(), auto_comments=(), user_comments=(), previous_id=(), lineno=None, context=None): self.id = id if not string and self.pluralizable: string = (u'', u'') self.string = string self.locations = list(distinct(locations)) self.flags = set(flags) if id and self.python_format: self.flags.add('python-format') else: self.flags.discard('python-format') self.auto_comments = list(distinct(auto_comments)) self.user_comments = list(distinct(user_comments)) if isinstance(previous_id, string_types): self.previous_id = [previous_id] else: self.previous_id = list(previous_id) self.lineno = lineno self.context = context def __repr__(self): return '<%s %r (flags: %r)>' % (type(self).__name__, self.id, list(self.flags)) def __cmp__(self, obj): def values_to_compare(): if isinstance(obj, Message): plural = self.pluralizable obj_plural = obj.pluralizable if plural and obj_plural: return self.id[0], obj.id[0] elif plural: return self.id[0], obj.id elif obj_plural: return self.id, obj.id[0] return self.id, obj.id this, other = values_to_compare() return cmp(this, other) def __gt__(self, other): return self.__cmp__(other) > 0 def __lt__(self, other): return self.__cmp__(other) < 0 def __ge__(self, other): return self.__cmp__(other) >= 0 def __le__(self, other): return self.__cmp__(other) <= 0 def __eq__(self, other): return self.__cmp__(other) == 0 def __ne__(self, other): return self.__cmp__(other) != 0 def clone(self): return Message(*map(copy, (self.id, self.string, self.locations, self.flags, self.auto_comments, self.user_comments, self.previous_id, self.lineno, self.context))) def check(self, catalog=None): from babel.messages.checkers import checkers errors = [] for checker in checkers: try: checker(catalog, self) except TranslationError as e: errors.append(e) return errors @property def fuzzy(self): return 'fuzzy' in self.flags @property def pluralizable(self): return isinstance(self.id, (list, tuple)) @property def python_format(self): ids = self.id if not isinstance(ids, (list, tuple)): ids = [ids] return any(PYTHON_FORMAT.search(id) for id in ids) class TranslationError(Exception): DEFAULT_HEADER = u"""\ # Translations template for PROJECT. # Copyright (C) YEAR ORGANIZATION # This file is distributed under the same license as the PROJECT project. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. #""" if PY2: def _parse_header(header_string): headers = message_from_string(header_string.encode('utf8')) decoded_headers = {} for name, value in headers.items(): name = name.decode('utf8') value = value.decode('utf8') decoded_headers[name] = value return decoded_headers else: _parse_header = message_from_string class Catalog(object): def __init__(self, locale=None, domain=None, header_comment=DEFAULT_HEADER, project=None, version=None, copyright_holder=None, msgid_bugs_address=None, creation_date=None, revision_date=None, last_translator=None, language_team=None, charset=None, fuzzy=True): self.domain = domain if locale: locale = Locale.parse(locale) self.locale = locale self._header_comment = header_comment self._messages = odict() self.project = project or 'PROJECT' self.version = version or 'VERSION' self.copyright_holder = copyright_holder or 'ORGANIZATION' self.msgid_bugs_address = msgid_bugs_address or 'EMAIL@ADDRESS' self.last_translator = last_translator or 'FULL NAME <EMAIL@ADDRESS>' self.language_team = language_team or 'LANGUAGE <LL@li.org>' self.charset = charset or 'utf-8' if creation_date is None: creation_date = datetime.now(LOCALTZ) elif isinstance(creation_date, datetime) and not creation_date.tzinfo: creation_date = creation_date.replace(tzinfo=LOCALTZ) self.creation_date = creation_date if revision_date is None: revision_date = 'YEAR-MO-DA HO:MI+ZONE' elif isinstance(revision_date, datetime) and not revision_date.tzinfo: revision_date = revision_date.replace(tzinfo=LOCALTZ) self.revision_date = revision_date self.fuzzy = fuzzy self.obsolete = odict() self._num_plurals = None self._plural_expr = None def _get_header_comment(self): comment = self._header_comment year = datetime.now(LOCALTZ).strftime('%Y') if hasattr(self.revision_date, 'strftime'): year = self.revision_date.strftime('%Y') comment = comment.replace('PROJECT', self.project) \ .replace('VERSION', self.version) \ .replace('YEAR', year) \ .replace('ORGANIZATION', self.copyright_holder) if self.locale: comment = comment.replace('Translations template', '%s translations' % self.locale.english_name) return comment def _set_header_comment(self, string): self._header_comment = string header_comment = property(_get_header_comment, _set_header_comment, doc="""\ The header comment for the catalog. >>> catalog = Catalog(project='Foobar', version='1.0', ... copyright_holder='Foo Company') >>> print(catalog.header_comment) #doctest: +ELLIPSIS # Translations template for Foobar. # Copyright (C) ... Foo Company # This file is distributed under the same license as the Foobar project. # FIRST AUTHOR <EMAIL@ADDRESS>, .... # The header can also be set from a string. Any known upper-case variables will be replaced when the header is retrieved again: >>> catalog = Catalog(project='Foobar', version='1.0', ... copyright_holder='Foo Company') >>> catalog.header_comment = '''\\ ... # The POT for my really cool PROJECT project. ... # Copyright (C) 1990-2003 ORGANIZATION ... # This file is distributed under the same license as the PROJECT ... # project. ... #''' >>> print(catalog.header_comment) # The POT for my really cool Foobar project. # Copyright (C) 1990-2003 Foo Company # This file is distributed under the same license as the Foobar # project. # :type: `unicode` """) def _get_mime_headers(self): headers = [] headers.append(('Project-Id-Version', '%s %s' % (self.project, self.version))) headers.append(('Report-Msgid-Bugs-To', self.msgid_bugs_address)) headers.append(('POT-Creation-Date', format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ', locale='en'))) if isinstance(self.revision_date, (datetime, time_) + number_types): headers.append(('PO-Revision-Date', format_datetime(self.revision_date, 'yyyy-MM-dd HH:mmZ', locale='en'))) else: headers.append(('PO-Revision-Date', self.revision_date)) headers.append(('Last-Translator', self.last_translator)) if self.locale is not None: headers.append(('Language', str(self.locale))) if (self.locale is not None) and ('LANGUAGE' in self.language_team): headers.append(('Language-Team', self.language_team.replace('LANGUAGE', str(self.locale)))) else: headers.append(('Language-Team', self.language_team)) if self.locale is not None: headers.append(('Plural-Forms', self.plural_forms)) headers.append(('MIME-Version', '1.0')) headers.append(('Content-Type', 'text/plain; charset=%s' % self.charset)) headers.append(('Content-Transfer-Encoding', '8bit')) headers.append(('Generated-By', 'Babel %s\n' % VERSION)) return headers def _set_mime_headers(self, headers): for name, value in headers: name = name.lower() if name == 'project-id-version': parts = value.split(' ') self.project = u' '.join(parts[:-1]) self.version = parts[-1] elif name == 'report-msgid-bugs-to': self.msgid_bugs_address = value elif name == 'last-translator': self.last_translator = value elif name == 'language-team': self.language_team = value elif name == 'content-type': mimetype, params = parse_header(value) if 'charset' in params: self.charset = params['charset'].lower() elif name == 'plural-forms': _, params = parse_header(' ;' + value) self._num_plurals = int(params.get('nplurals', 2)) self._plural_expr = params.get('plural', '(n != 1)') elif name == 'pot-creation-date': self.creation_date = _parse_datetime_header(value) elif name == 'po-revision-date': if 'YEAR' not in value: self.revision_date = _parse_datetime_header(value) mime_headers = property(_get_mime_headers, _set_mime_headers, doc="""\ The MIME headers of the catalog, used for the special ``msgid ""`` entry. The behavior of this property changes slightly depending on whether a locale is set or not, the latter indicating that the catalog is actually a template for actual translations. Here's an example of the output for such a catalog template: >>> from babel.dates import UTC >>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC) >>> catalog = Catalog(project='Foobar', version='1.0', ... creation_date=created) >>> for name, value in catalog.mime_headers: ... print('%s: %s' % (name, value)) Project-Id-Version: Foobar 1.0 Report-Msgid-Bugs-To: EMAIL@ADDRESS POT-Creation-Date: 1990-04-01 15:30+0000 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME <EMAIL@ADDRESS> Language-Team: LANGUAGE <LL@li.org> MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel ... And here's an example of the output when the locale is set: >>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC) >>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0', ... creation_date=created, revision_date=revised, ... last_translator='John Doe <jd@example.com>', ... language_team='de_DE <de@example.com>') >>> for name, value in catalog.mime_headers: ... print('%s: %s' % (name, value)) Project-Id-Version: Foobar 1.0 Report-Msgid-Bugs-To: EMAIL@ADDRESS POT-Creation-Date: 1990-04-01 15:30+0000 PO-Revision-Date: 1990-08-03 12:00+0000 Last-Translator: John Doe <jd@example.com> Language: de_DE Language-Team: de_DE <de@example.com> Plural-Forms: nplurals=2; plural=(n != 1) MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel ... :type: `list` """) @property def num_plurals(self): if self._num_plurals is None: num = 2 if self.locale: num = get_plural(self.locale)[0] self._num_plurals = num return self._num_plurals @property def plural_expr(self): if self._plural_expr is None: expr = '(n != 1)' if self.locale: expr = get_plural(self.locale)[1] self._plural_expr = expr return self._plural_expr @property def plural_forms(self): return 'nplurals=%s; plural=%s' % (self.num_plurals, self.plural_expr) def __contains__(self, id): return self._key_for(id) in self._messages def __len__(self): return len(self._messages) def __iter__(self): buf = [] for name, value in self.mime_headers: buf.append('%s: %s' % (name, value)) flags = set() if self.fuzzy: flags |= set(['fuzzy']) yield Message(u'', '\n'.join(buf), flags=flags) for key in self._messages: yield self._messages[key] def __repr__(self): locale = '' if self.locale: locale = ' %s' % self.locale return '<%s %r%s>' % (type(self).__name__, self.domain, locale) def __delitem__(self, id): self.delete(id) def __getitem__(self, id): return self.get(id) def __setitem__(self, id, message): assert isinstance(message, Message), 'expected a Message object' key = self._key_for(id, message.context) current = self._messages.get(key) if current: if message.pluralizable and not current.pluralizable: # The new message adds pluralization current.id = message.id current.string = message.string current.locations = list(distinct(current.locations + message.locations)) current.auto_comments = list(distinct(current.auto_comments + message.auto_comments)) current.user_comments = list(distinct(current.user_comments + message.user_comments)) current.flags |= message.flags message = current elif id == '': # special treatment for the header message self.mime_headers = _parse_header(message.string).items() self.header_comment = '\n'.join([(' in message.user_comments]) self.fuzzy = message.fuzzy else: if isinstance(id, (list, tuple)): assert isinstance(message.string, (list, tuple)), \ 'Expected sequence but got %s' % type(message.string) self._messages[key] = message def add(self, id, string=None, locations=(), flags=(), auto_comments=(), user_comments=(), previous_id=(), lineno=None, context=None): message = Message(id, string, list(locations), flags, auto_comments, user_comments, previous_id, lineno=lineno, context=context) self[id] = message return message def check(self): for message in self._messages.values(): errors = message.check(catalog=self) if errors: yield message, errors def get(self, id, context=None): return self._messages.get(self._key_for(id, context)) def delete(self, id, context=None): key = self._key_for(id, context) if key in self._messages: del self._messages[key] def update(self, template, no_fuzzy_matching=False): messages = self._messages remaining = messages.copy() self._messages = odict() # Prepare for fuzzy matching fuzzy_candidates = [] if not no_fuzzy_matching: fuzzy_candidates = dict([ (self._key_for(msgid), messages[msgid].context) for msgid in messages if msgid and messages[msgid].string ]) fuzzy_matches = set() def _merge(message, oldkey, newkey): message = message.clone() fuzzy = False if oldkey != newkey: fuzzy = True fuzzy_matches.add(oldkey) oldmsg = messages.get(oldkey) if isinstance(oldmsg.id, string_types): message.previous_id = [oldmsg.id] else: message.previous_id = list(oldmsg.id) else: oldmsg = remaining.pop(oldkey, None) message.string = oldmsg.string if isinstance(message.id, (list, tuple)): if not isinstance(message.string, (list, tuple)): fuzzy = True message.string = tuple( [message.string] + ([u''] * (len(message.id) - 1)) ) elif len(message.string) != self.num_plurals: fuzzy = True message.string = tuple(message.string[:len(oldmsg.string)]) elif isinstance(message.string, (list, tuple)): fuzzy = True message.string = message.string[0] message.flags |= oldmsg.flags if fuzzy: message.flags |= set([u'fuzzy']) self[message.id] = message for message in template: if message.id: key = self._key_for(message.id, message.context) if key in messages: _merge(message, key, key) else: if no_fuzzy_matching is False: # do some fuzzy matching with difflib if isinstance(key, tuple): matchkey = key[0] # just the msgid, no context else: matchkey = key matches = get_close_matches(matchkey.lower().strip(), fuzzy_candidates.keys(), 1) if matches: newkey = matches[0] newctxt = fuzzy_candidates[newkey] if newctxt is not None: newkey = newkey, newctxt _merge(message, newkey, key) continue self[message.id] = message for msgid in remaining: if no_fuzzy_matching or msgid not in fuzzy_matches: self.obsolete[msgid] = remaining[msgid] # Allow the updated catalog's header to be rewritten based on the self.header_comment = template.header_comment # Make updated catalog's POT-Creation-Date equal to the template self.creation_date = template.creation_date def _key_for(self, id, context=None): key = id if isinstance(key, (list, tuple)): key = id[0] if context is not None: key = (key, context) return key
true
true
f72a350db1ba57a29e227da4a2688911fa9f59a9
1,600
py
Python
app/api/db_config.py
gatemadavid/iReporter2
31ee2295a10c074bbf3b5b857240ec65ca9689e9
[ "MIT" ]
null
null
null
app/api/db_config.py
gatemadavid/iReporter2
31ee2295a10c074bbf3b5b857240ec65ca9689e9
[ "MIT" ]
null
null
null
app/api/db_config.py
gatemadavid/iReporter2
31ee2295a10c074bbf3b5b857240ec65ca9689e9
[ "MIT" ]
null
null
null
import psycopg2 import psycopg2.extras import os url = os.getenv('DATABASE_URL') def connection(url): conn = psycopg2.connect(url) return conn def init_db(): con = connection(url) return con def create_tables(): conn = connection(url) curr = conn.cursor() queries = tables() for query in queries: curr.execute(query) conn.commit() def tables(): users_table = '''CREATE TABLE IF NOT EXISTS users( id serial PRIMARY KEY, firstname char(20) NOT NULL, lastname char(20) NOT NULL, email char(50) NOT NULL, username char(20) NOT NULL, phone char(14) NOT NULL, isAdmin BOOLEAN DEFAULT False, password char(100) NOT NULL, registered DATE NOT NULL DEFAULT CURRENT_DATE) ''' incidents_table = '''CREATE TABLE IF NOT EXISTS incidents( id serial PRIMARY KEY, title char(100) NOT NULL, incident char(50) NOT NULL, location char(100) NOT NULL, status char(30) DEFAULT 'Draft', description char(200) NOT NULL, images char(100) NOT NULL, createdBy char(100) NOT NULL, createdOn DATE NOT NULL DEFAULT CURRENT_DATE) ''' queries = [users_table, incidents_table] return queries def destroy_tables(): conn = connection(url) curr = conn.cursor() users_table = ''' DROP TABLE IF EXISTS users CASCADE''' incidents_table = ''' DROP TABLE IF EXISTS incidents CASCADE''' queries = [users_table, incidents_table] for query in queries: curr.execute(query) conn.commit()
25.396825
67
0.636875
import psycopg2 import psycopg2.extras import os url = os.getenv('DATABASE_URL') def connection(url): conn = psycopg2.connect(url) return conn def init_db(): con = connection(url) return con def create_tables(): conn = connection(url) curr = conn.cursor() queries = tables() for query in queries: curr.execute(query) conn.commit() def tables(): users_table = '''CREATE TABLE IF NOT EXISTS users( id serial PRIMARY KEY, firstname char(20) NOT NULL, lastname char(20) NOT NULL, email char(50) NOT NULL, username char(20) NOT NULL, phone char(14) NOT NULL, isAdmin BOOLEAN DEFAULT False, password char(100) NOT NULL, registered DATE NOT NULL DEFAULT CURRENT_DATE) ''' incidents_table = '''CREATE TABLE IF NOT EXISTS incidents( id serial PRIMARY KEY, title char(100) NOT NULL, incident char(50) NOT NULL, location char(100) NOT NULL, status char(30) DEFAULT 'Draft', description char(200) NOT NULL, images char(100) NOT NULL, createdBy char(100) NOT NULL, createdOn DATE NOT NULL DEFAULT CURRENT_DATE) ''' queries = [users_table, incidents_table] return queries def destroy_tables(): conn = connection(url) curr = conn.cursor() users_table = ''' DROP TABLE IF EXISTS users CASCADE''' incidents_table = ''' DROP TABLE IF EXISTS incidents CASCADE''' queries = [users_table, incidents_table] for query in queries: curr.execute(query) conn.commit()
true
true
f72a355540cc984f158300eaacfdbb6e9b3587e6
2,682
py
Python
apps/points/models.py
stasm/akupunktura
5cf8b98dbb01a65db48c8f582f1592c680c47eba
[ "BSD-3-Clause" ]
1
2015-05-14T19:10:29.000Z
2015-05-14T19:10:29.000Z
apps/points/models.py
stasm/akupunktura
5cf8b98dbb01a65db48c8f582f1592c680c47eba
[ "BSD-3-Clause" ]
null
null
null
apps/points/models.py
stasm/akupunktura
5cf8b98dbb01a65db48c8f582f1592c680c47eba
[ "BSD-3-Clause" ]
null
null
null
from datetime import datetime from django.db import models from django.contrib.auth.models import User class PointManager(models.Manager): """Manager for Pressure Points.""" def recently_added(self, count=10): return self.order_by('-time_added')[:count] class City(models.Model): """City the Pressure Point belong to.""" name = models.CharField(max_length=200) slug = models.SlugField() lat = models.FloatField() lon = models.FloatField() def __unicode__(self): return self.name class Point(models.Model): """Pressure Point model. The pressure points are the core concept of the app. They're small cases that the community shares, discusses about and eventually, take action upon in order to improve the quality of life. """ title = models.CharField(max_length=200) lat = models.FloatField() lon = models.FloatField() description = models.TextField() # descriptive address or directions on how to find the Point directions = models.TextField() time_added = models.DateTimeField() # simple voting mechanism (like/dislike) thumbsup = models.IntegerField() thumbsdown = models.IntegerField() # foreign keys poster = models.ForeignKey(User) city = models.ForeignKey(City) # managers objects = PointManager() def __unicode__(self): return "%s x %s" % (self.lat, self.lon) class Photo(models.Model): """Photo objects illustrating Pressure Points.""" time_added = models.DateTimeField() thumbnail = models.ImageField(upload_to='upload/thumbnails', blank=True) original = models.ImageField(upload_to='upload/original') is_main = models.BooleanField() poster = models.ForeignKey(User) point = models.ForeignKey(Point, related_name='photos') def save(self, *args, **kwargs): if self.id is None: self.thumbnail = self.original super(Photo, self).save(*args, **kwargs) class FeatureManager(models.Manager): """Manager for Feature objects.""" def current(self): now = datetime.now() return self.filter(start_time__lt=now, end_time__gt=now) class Feature(models.Model): """Pressure Point features on the home page.""" start_time = models.DateTimeField() end_time = models.DateTimeField() point = models.ForeignKey(Point, related_name='features') objects = FeatureManager() class Resolution(models.Model): """Resolution objects describe how a Pressure Point was closed.""" description = models.TextField() time_resolved = models.DateTimeField() point = models.OneToOneField(Point, related_name='resolution')
30.827586
76
0.690902
from datetime import datetime from django.db import models from django.contrib.auth.models import User class PointManager(models.Manager): def recently_added(self, count=10): return self.order_by('-time_added')[:count] class City(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() lat = models.FloatField() lon = models.FloatField() def __unicode__(self): return self.name class Point(models.Model): title = models.CharField(max_length=200) lat = models.FloatField() lon = models.FloatField() description = models.TextField() directions = models.TextField() time_added = models.DateTimeField() thumbsup = models.IntegerField() thumbsdown = models.IntegerField() poster = models.ForeignKey(User) city = models.ForeignKey(City) objects = PointManager() def __unicode__(self): return "%s x %s" % (self.lat, self.lon) class Photo(models.Model): time_added = models.DateTimeField() thumbnail = models.ImageField(upload_to='upload/thumbnails', blank=True) original = models.ImageField(upload_to='upload/original') is_main = models.BooleanField() poster = models.ForeignKey(User) point = models.ForeignKey(Point, related_name='photos') def save(self, *args, **kwargs): if self.id is None: self.thumbnail = self.original super(Photo, self).save(*args, **kwargs) class FeatureManager(models.Manager): def current(self): now = datetime.now() return self.filter(start_time__lt=now, end_time__gt=now) class Feature(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() point = models.ForeignKey(Point, related_name='features') objects = FeatureManager() class Resolution(models.Model): description = models.TextField() time_resolved = models.DateTimeField() point = models.OneToOneField(Point, related_name='resolution')
true
true
f72a35b4e1de51ead743b2099fba5d0628b7e0b3
214
py
Python
app/api.py
jecklgamis/flask-example-app
025f60d812acae1eb33263de3339ac8e37096a54
[ "Apache-2.0" ]
6
2019-11-25T08:46:03.000Z
2021-12-28T07:30:50.000Z
app/api.py
jecklgamis/flask-example-app
025f60d812acae1eb33263de3339ac8e37096a54
[ "Apache-2.0" ]
null
null
null
app/api.py
jecklgamis/flask-example-app
025f60d812acae1eb33263de3339ac8e37096a54
[ "Apache-2.0" ]
1
2021-12-26T21:36:51.000Z
2021-12-26T21:36:51.000Z
from flask import Blueprint bp = Blueprint('api', __name__, url_prefix='/api') from flask import jsonify @bp.route('/', methods=['GET']) def index(): return jsonify({"message": "This is the /api endpoint"})
21.4
60
0.682243
from flask import Blueprint bp = Blueprint('api', __name__, url_prefix='/api') from flask import jsonify @bp.route('/', methods=['GET']) def index(): return jsonify({"message": "This is the /api endpoint"})
true
true
f72a37822a8c5d59218999e0dc281e80546e9c72
5,010
py
Python
cmatch.py
kitneylab/cmatch
6c804c2ca58f5e8ccde68c14182bebcb43ad69b4
[ "MIT" ]
null
null
null
cmatch.py
kitneylab/cmatch
6c804c2ca58f5e8ccde68c14182bebcb43ad69b4
[ "MIT" ]
null
null
null
cmatch.py
kitneylab/cmatch
6c804c2ca58f5e8ccde68c14182bebcb43ad69b4
[ "MIT" ]
null
null
null
#!/usr/bin/env python import json import logging import os from os import path from pathlib import Path import time from reconstruction import reconstruct from futils import timeit from tqdm import tqdm from matching import Library, Sequence, match_library import plac # Logging configuration current_file = path.basename(__file__).split(".")[0] @timeit def match_libs(seq, libs, threshold=0.5): """ Match libs with the sequence """ result = [] for lib in tqdm(libs): pop = {} pop["library"] = lib["name"] # See algo1_lycopene for the parameter below in the template # threshold = lib["score_threshold"] candidates = match_library(seq, Library(lib), threshold, direction53=True) cl = [] for candidate in candidates: for c in candidate: cl.append( { "name": c.name, "score": c.score, "start": c.start, "length": c.length, "end": c.end, } ) pop["candidates"] = cl result.append(pop) return result def get_sequences(dir_dict): """ Return list of sequences """ SEQUENCES_EXTENSION = dir_dict["extension"] SEQUENCES_PATH = dir_dict["sequences_path"] seq_dir_names = dir_dict["seq_dir_names"] sequences = [] for seq_dir in seq_dir_names: seqs = Path(path.join(SEQUENCES_PATH, seq_dir)).rglob( "*{0}".format(SEQUENCES_EXTENSION) ) sequences.append(seqs) return sequences def get_slices_libs(template): """ Get slices libraries Args: template (dict): Template JSON data as a dict structure Returns: dict of slices libraries """ slices_libs = {} for sli in template["template_slices"]: libs = [] for pos in sli["template_slice"]: lib = template["template"]["structure"][pos - 1]["library_source"] libs.append(template["component_sources"][lib]) slices_libs[sli["name"]] = libs return slices_libs @timeit def iter_all_seq( input_sequences, template_json_file, match_output_filename, reconstruction_output_filename, threshold=0.99, ): """ Iterate over sequences Args: input_sequences (dict): Input dictionary with info about the input sequences: output_filename (str): Output filename Example: input_sequences = { 'extension' = ".seq" 'sequences_path' = "/data/Imperial/src/lyc-basic-ass-ind/" 'seq_dir_names' = ["output"] } """ # Get sequences to match sequences = get_sequences(input_sequences) # Get the filenames in a list and not this freakin generator seq_filenames = [] for seq in sequences: for filename in seq: seq_filenames.append(filename) # Loop over the sequences r = [] for filename in seq_filenames: sq = Sequence(filename) json_to_output = {} json_to_output["target"] = sq.name # Logging logging.info(f"Target sequence: {sq.name}") with open(template_json_file) as json_file: template = json.load(json_file) # Get libs from template template["template"] libs = get_slices_libs(template) libs_to_match = libs["construct"] # name of the fake primer # Match sequence matches = match_libs(sq, libs_to_match, threshold=threshold) json_to_output["matches"] = matches r.append(json_to_output) # Write output result in JSON file with open(match_output_filename, "w") as filename: json.dump(r, filename, indent=2, separators=(",", ":")) def match(template, threshold=0.99, *targets): """ Match """ # Load JSON template with open(template) as json_file: template = json.load(json_file) r = [] # Matching for target in targets: sq = Sequence(target) json_to_output = {} json_to_output["target"] = sq.name libs = get_slices_libs(template) libs_to_match = libs["construct"] # name of the fake primer matches = match_libs(sq, libs_to_match, threshold=threshold) json_to_output["matches"] = matches r.append(json_to_output) s = json.dumps(r, indent=2, separators=(",", ":")) reconstruction_result = reconstruct(r) ss = json.dumps(reconstruction_result, indent=2, separators=(",", ":")) return ss @plac.pos("template", "JSON construct template. Example: consruct_template.json") @plac.pos("targets", f"Target sequence files. Example: Sanger008.seq", type=str) @plac.opt("threshold", "Threshold", type=float) def main(template, threshold=0.99, *targets): """ cMatch command line tool """ result = match(template, threshold, *targets) print(result) if __name__ == "__main__": plac.call(main)
26.368421
85
0.612774
import json import logging import os from os import path from pathlib import Path import time from reconstruction import reconstruct from futils import timeit from tqdm import tqdm from matching import Library, Sequence, match_library import plac current_file = path.basename(__file__).split(".")[0] @timeit def match_libs(seq, libs, threshold=0.5): result = [] for lib in tqdm(libs): pop = {} pop["library"] = lib["name"] candidates = match_library(seq, Library(lib), threshold, direction53=True) cl = [] for candidate in candidates: for c in candidate: cl.append( { "name": c.name, "score": c.score, "start": c.start, "length": c.length, "end": c.end, } ) pop["candidates"] = cl result.append(pop) return result def get_sequences(dir_dict): SEQUENCES_EXTENSION = dir_dict["extension"] SEQUENCES_PATH = dir_dict["sequences_path"] seq_dir_names = dir_dict["seq_dir_names"] sequences = [] for seq_dir in seq_dir_names: seqs = Path(path.join(SEQUENCES_PATH, seq_dir)).rglob( "*{0}".format(SEQUENCES_EXTENSION) ) sequences.append(seqs) return sequences def get_slices_libs(template): slices_libs = {} for sli in template["template_slices"]: libs = [] for pos in sli["template_slice"]: lib = template["template"]["structure"][pos - 1]["library_source"] libs.append(template["component_sources"][lib]) slices_libs[sli["name"]] = libs return slices_libs @timeit def iter_all_seq( input_sequences, template_json_file, match_output_filename, reconstruction_output_filename, threshold=0.99, ): sequences = get_sequences(input_sequences) seq_filenames = [] for seq in sequences: for filename in seq: seq_filenames.append(filename) r = [] for filename in seq_filenames: sq = Sequence(filename) json_to_output = {} json_to_output["target"] = sq.name logging.info(f"Target sequence: {sq.name}") with open(template_json_file) as json_file: template = json.load(json_file) template["template"] libs = get_slices_libs(template) libs_to_match = libs["construct"] matches = match_libs(sq, libs_to_match, threshold=threshold) json_to_output["matches"] = matches r.append(json_to_output) with open(match_output_filename, "w") as filename: json.dump(r, filename, indent=2, separators=(",", ":")) def match(template, threshold=0.99, *targets): with open(template) as json_file: template = json.load(json_file) r = [] for target in targets: sq = Sequence(target) json_to_output = {} json_to_output["target"] = sq.name libs = get_slices_libs(template) libs_to_match = libs["construct"] matches = match_libs(sq, libs_to_match, threshold=threshold) json_to_output["matches"] = matches r.append(json_to_output) s = json.dumps(r, indent=2, separators=(",", ":")) reconstruction_result = reconstruct(r) ss = json.dumps(reconstruction_result, indent=2, separators=(",", ":")) return ss @plac.pos("template", "JSON construct template. Example: consruct_template.json") @plac.pos("targets", f"Target sequence files. Example: Sanger008.seq", type=str) @plac.opt("threshold", "Threshold", type=float) def main(template, threshold=0.99, *targets): result = match(template, threshold, *targets) print(result) if __name__ == "__main__": plac.call(main)
true
true
f72a37e5373aa4e623b73750d93d8aba42a35bcd
929
py
Python
jobs/pitch_deformer.py
nSimonFR/spoken_language_dataset
07c018f28be72cec3ba5e9ec07608f79a6d32031
[ "MIT" ]
23
2018-06-25T10:22:57.000Z
2021-07-09T09:53:47.000Z
jobs/pitch_deformer.py
nSimonFR/spoken_language_dataset
07c018f28be72cec3ba5e9ec07608f79a6d32031
[ "MIT" ]
3
2018-07-19T18:47:07.000Z
2021-06-01T22:11:53.000Z
jobs/pitch_deformer.py
nSimonFR/spoken_language_dataset
07c018f28be72cec3ba5e9ec07608f79a6d32031
[ "MIT" ]
6
2018-07-14T17:48:51.000Z
2020-12-24T01:31:41.000Z
from . import common from audio_toolbox import sox class PitchDeformer: SUFFIX = '.pitch@n' def __init__(self, input_files_key, output_files_key, semitones): self.input_files_key = input_files_key self.output_files_key = output_files_key self.semitones = semitones def execute(self, context): input_files = context[self.input_files_key] output_files = context[self.output_files_key] = [] for input_file in input_files: output_pattern = common.append_suffix_to_filename( input_file, PitchDeformer.SUFFIX) for index, semitone in enumerate(self.semitones): # start indexing with 1 to be compatible with sox output_file = output_pattern.replace('@n', str(index + 1)) output_files.append(output_file) sox.adjust_pitch(input_file, output_file, semitone=semitone)
33.178571
76
0.665231
from . import common from audio_toolbox import sox class PitchDeformer: SUFFIX = '.pitch@n' def __init__(self, input_files_key, output_files_key, semitones): self.input_files_key = input_files_key self.output_files_key = output_files_key self.semitones = semitones def execute(self, context): input_files = context[self.input_files_key] output_files = context[self.output_files_key] = [] for input_file in input_files: output_pattern = common.append_suffix_to_filename( input_file, PitchDeformer.SUFFIX) for index, semitone in enumerate(self.semitones): output_file = output_pattern.replace('@n', str(index + 1)) output_files.append(output_file) sox.adjust_pitch(input_file, output_file, semitone=semitone)
true
true
f72a37ebb93db977a1a827e2699a50ef563720f7
4,654
py
Python
app/user/tests/test_user_api.py
gmarshall142/appservices
2dae37dfe6693a3f61f3561cabfaff78ad7616e4
[ "MIT" ]
null
null
null
app/user/tests/test_user_api.py
gmarshall142/appservices
2dae37dfe6693a3f61f3561cabfaff78ad7616e4
[ "MIT" ]
null
null
null
app/user/tests/test_user_api.py
gmarshall142/appservices
2dae37dfe6693a3f61f3561cabfaff78ad7616e4
[ "MIT" ]
null
null
null
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse('user:create') TOKEN_URL = reverse('user:token') ME_URL = reverse('user:me') def create_user(**params): return get_user_model().objects.create_user(**params) class PublicUserApiTests(TestCase): """Test the users API (public)""" def setup(self): self.client = APIClient() def test_create_valid_user_success(self): """Test creating user with valid payload is successful""" payload = { 'email': 'test@londonappdev.com', 'password': 'testpass', 'name': 'Test name' } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload['password'])) self.assertNotIn('password', res.data) def test_user_exists(self): """Test creating a user that already exists fails""" payload = {'email': 'test@londonappdev.com', 'password': 'testpass'} create_user(**payload) res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_password_too_short(self): """Test that the password must be more than 5 characters""" payload = {'email': 'test@londonappdev.com', 'password': 'pw'} res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) user_exists = get_user_model().objects.filter( email=payload['email'] ).exists() self.assertFalse(user_exists) def test_create_token_for_user(self): """Test that a token is created for the user""" payload = {'email': 'test@londonappdev.com', 'password': 'testpass'} create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_create_token_invalid_credentials(self): """Test that token is not created if invalid credentials are given""" create_user(email='test@londeonappdev.com', password='testpass') payload = {'email': 'test@londonappdev.com', 'password': 'wrong'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_no_user(self): """Test that token is not created if user doesn't exist""" payload = {'email': 'test@londonappdev.com', 'password': 'testpass'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_missing_field(self): """Test that email and password are required""" res = self.client.post(TOKEN_URL, {'email': 'one', 'password': ''}) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) class PrivateUserApiTests(TestCase): """Test API requests that require authentication""" def setUp(self): self.user = create_user( email='test@londonappdev.com', password='testpass', name='name' ) self.client = APIClient() self.client.force_authenticate(user=self.user) def test_retrieve_profile_success(self): """Test retrieving profile for logged in used""" res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, { 'name': self.user.name, 'email': self.user.email }) def test_post_me_not_allowed(self): """Test that POST is not allowed on the me url""" res = self.client.post(ME_URL, {}) self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_update_user_profile(self): """Test updating the user profile for authenticated user""" payload = {'name': 'new name', 'password': 'newpassword123'} res = self.client.patch(ME_URL, payload) self.user.refresh_from_db() self.assertEqual(self.user.name, payload['name']) self.assertTrue(self.user.check_password(payload['password'])) self.assertEqual(res.status_code, status.HTTP_200_OK)
37.232
77
0.662226
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse('user:create') TOKEN_URL = reverse('user:token') ME_URL = reverse('user:me') def create_user(**params): return get_user_model().objects.create_user(**params) class PublicUserApiTests(TestCase): def setup(self): self.client = APIClient() def test_create_valid_user_success(self): payload = { 'email': 'test@londonappdev.com', 'password': 'testpass', 'name': 'Test name' } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload['password'])) self.assertNotIn('password', res.data) def test_user_exists(self): payload = {'email': 'test@londonappdev.com', 'password': 'testpass'} create_user(**payload) res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_password_too_short(self): payload = {'email': 'test@londonappdev.com', 'password': 'pw'} res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) user_exists = get_user_model().objects.filter( email=payload['email'] ).exists() self.assertFalse(user_exists) def test_create_token_for_user(self): payload = {'email': 'test@londonappdev.com', 'password': 'testpass'} create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_create_token_invalid_credentials(self): create_user(email='test@londeonappdev.com', password='testpass') payload = {'email': 'test@londonappdev.com', 'password': 'wrong'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_no_user(self): payload = {'email': 'test@londonappdev.com', 'password': 'testpass'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_missing_field(self): res = self.client.post(TOKEN_URL, {'email': 'one', 'password': ''}) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) class PrivateUserApiTests(TestCase): def setUp(self): self.user = create_user( email='test@londonappdev.com', password='testpass', name='name' ) self.client = APIClient() self.client.force_authenticate(user=self.user) def test_retrieve_profile_success(self): res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, { 'name': self.user.name, 'email': self.user.email }) def test_post_me_not_allowed(self): res = self.client.post(ME_URL, {}) self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_update_user_profile(self): payload = {'name': 'new name', 'password': 'newpassword123'} res = self.client.patch(ME_URL, payload) self.user.refresh_from_db() self.assertEqual(self.user.name, payload['name']) self.assertTrue(self.user.check_password(payload['password'])) self.assertEqual(res.status_code, status.HTTP_200_OK)
true
true
f72a38772dfca7924eadc81291de0091589ed69c
1,788
py
Python
samples/generated_samples/aiplatform_generated_aiplatform_v1_job_service_delete_hyperparameter_tuning_job_async.py
lclc19/python-aiplatform
d8da2e365277441abadb04328943f23345d72b0e
[ "Apache-2.0" ]
180
2020-09-23T17:21:15.000Z
2022-03-30T17:25:47.000Z
samples/generated_samples/aiplatform_generated_aiplatform_v1_job_service_delete_hyperparameter_tuning_job_async.py
lclc19/python-aiplatform
d8da2e365277441abadb04328943f23345d72b0e
[ "Apache-2.0" ]
601
2020-09-23T16:23:44.000Z
2022-03-31T19:08:23.000Z
samples/generated_samples/aiplatform_generated_aiplatform_v1_job_service_delete_hyperparameter_tuning_job_async.py
lclc19/python-aiplatform
d8da2e365277441abadb04328943f23345d72b0e
[ "Apache-2.0" ]
109
2020-09-23T16:22:04.000Z
2022-03-28T21:18:29.000Z
# -*- coding: utf-8 -*- # Copyright 2020 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 # # 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. # # Generated code. DO NOT EDIT! # # Snippet for DeleteHyperparameterTuningJob # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-aiplatform # [START aiplatform_generated_aiplatform_v1_JobService_DeleteHyperparameterTuningJob_async] from google.cloud import aiplatform_v1 async def sample_delete_hyperparameter_tuning_job(): """Snippet for delete_hyperparameter_tuning_job""" # Create a client client = aiplatform_v1.JobServiceAsyncClient() # Initialize request argument(s) request = aiplatform_v1.DeleteHyperparameterTuningJobRequest( name="projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}", ) # Make the request operation = client.delete_hyperparameter_tuning_job(request=request) print("Waiting for operation to complete...") response = await operation.result() print(response) # [END aiplatform_generated_aiplatform_v1_JobService_DeleteHyperparameterTuningJob_async]
35.76
108
0.779083
from google.cloud import aiplatform_v1 async def sample_delete_hyperparameter_tuning_job(): client = aiplatform_v1.JobServiceAsyncClient() request = aiplatform_v1.DeleteHyperparameterTuningJobRequest( name="projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}", ) operation = client.delete_hyperparameter_tuning_job(request=request) print("Waiting for operation to complete...") response = await operation.result() print(response)
true
true
f72a38aef278e33aedce4abdf04469c32de8d0bd
1,510
py
Python
minecraft/config.py
leosumi/Minecraft
4215bf0fe0b0e2fd386b1990a4589afc239879a7
[ "MIT" ]
null
null
null
minecraft/config.py
leosumi/Minecraft
4215bf0fe0b0e2fd386b1990a4589afc239879a7
[ "MIT" ]
null
null
null
minecraft/config.py
leosumi/Minecraft
4215bf0fe0b0e2fd386b1990a4589afc239879a7
[ "MIT" ]
null
null
null
import math import configparser from util import tex_coords CONFIG_PATH = "config.ini" config = configparser.ConfigParser() config.read(CONFIG_PATH) WIDTH = config.getint("window", "width") HEIGHT = config.getint("window", "height") CAPTION = config["window"]["caption"] TICKS_PER_SEC = config.getint("game", "ticks_per_sec") # Size of sectors used to ease block loading. SECTOR_SIZE = config.getint("game", "sector_size") WALKING_SPEED = config.getint("player", "walking_speed") FLYING_SPEED = config.getint("player", "flying_speed") GRAVITY = config.getfloat("world", "gravity") MAX_JUMP_HEIGHT = config.getfloat("player", "max_jump_height") # About the height of a block. # To derive the formula for calculating jump speed, first solve # v_t = v_0 + a * t # for the time at which you achieve maximum height, where a is the acceleration # due to gravity and v_t = 0. This gives: # t = - v_0 / a # Use t and the desired MAX_JUMP_HEIGHT to solve for v_0 (jump speed) in # s = s_0 + v_0 * t + (a * t^2) / 2 JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT) TERMINAL_VELOCITY = config.getint("world", "terminal_velocity") PLAYER_HEIGHT = config.getint("player", "player_height") TEXTURE_PATH = 'texture.png' GRASS = tex_coords((1, 0), (0, 1), (0, 0)) SAND = tex_coords((1, 1), (1, 1), (1, 1)) BRICK = tex_coords((2, 0), (2, 0), (2, 0)) STONE = tex_coords((2, 1), (2, 1), (2, 1)) FACES = [ ( 0, 1, 0), ( 0,-1, 0), (-1, 0, 0), ( 1, 0, 0), ( 0, 0, 1), ( 0, 0,-1), ]
29.038462
93
0.662252
import math import configparser from util import tex_coords CONFIG_PATH = "config.ini" config = configparser.ConfigParser() config.read(CONFIG_PATH) WIDTH = config.getint("window", "width") HEIGHT = config.getint("window", "height") CAPTION = config["window"]["caption"] TICKS_PER_SEC = config.getint("game", "ticks_per_sec") SECTOR_SIZE = config.getint("game", "sector_size") WALKING_SPEED = config.getint("player", "walking_speed") FLYING_SPEED = config.getint("player", "flying_speed") GRAVITY = config.getfloat("world", "gravity") MAX_JUMP_HEIGHT = config.getfloat("player", "max_jump_height") JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT) TERMINAL_VELOCITY = config.getint("world", "terminal_velocity") PLAYER_HEIGHT = config.getint("player", "player_height") TEXTURE_PATH = 'texture.png' GRASS = tex_coords((1, 0), (0, 1), (0, 0)) SAND = tex_coords((1, 1), (1, 1), (1, 1)) BRICK = tex_coords((2, 0), (2, 0), (2, 0)) STONE = tex_coords((2, 1), (2, 1), (2, 1)) FACES = [ ( 0, 1, 0), ( 0,-1, 0), (-1, 0, 0), ( 1, 0, 0), ( 0, 0, 1), ( 0, 0,-1), ]
true
true
f72a39b2dc13c27df0c09468e6d52f23ae747f9d
10,696
py
Python
packages/amplify-graphql-searchable-transformer/streaming-lambda/python_streaming_function.py
jcbdev/amplify-cli
08f7a3c45b2e98535ef325eb0a97c5bc4d3008c6
[ "Apache-2.0", "MIT" ]
null
null
null
packages/amplify-graphql-searchable-transformer/streaming-lambda/python_streaming_function.py
jcbdev/amplify-cli
08f7a3c45b2e98535ef325eb0a97c5bc4d3008c6
[ "Apache-2.0", "MIT" ]
null
null
null
packages/amplify-graphql-searchable-transformer/streaming-lambda/python_streaming_function.py
jcbdev/amplify-cli
08f7a3c45b2e98535ef325eb0a97c5bc4d3008c6
[ "Apache-2.0", "MIT" ]
null
null
null
import base64 import json import logging import os import time import traceback from urllib.parse import urlparse, quote from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest from botocore.credentials import get_credentials from botocore.endpoint import BotocoreHTTPSession from botocore.session import Session from boto3.dynamodb.types import TypeDeserializer # The following parameters are required to configure the ES cluster ES_ENDPOINT = os.environ['ES_ENDPOINT'] ES_REGION = os.environ['ES_REGION'] DEBUG = True if os.environ['DEBUG'] == "1" else False ES_USE_EXTERNAL_VERSIONING = True if os.environ['ES_USE_EXTERNAL_VERSIONING'] == "true" else False # ElasticSearch 6 deprecated having multiple mapping types in an index. Default to doc. DOC_TYPE = 'doc' ES_MAX_RETRIES = 3 # Max number of retries for exponential backoff logger = logging.getLogger() logger.setLevel(logging.DEBUG if DEBUG else logging.INFO) logger.info("Streaming to ElasticSearch") # custom encoder changes # - sets to lists class DDBTypesEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) return json.JSONEncoder.default(self, obj) # Subclass of boto's TypeDeserializer for DynamoDB to adjust for DynamoDB Stream format. class StreamTypeDeserializer(TypeDeserializer): def _deserialize_n(self, value): return float(value) def _deserialize_b(self, value): return value # Already in Base64 class ES_Exception(Exception): '''Capture status_code from request''' status_code = 0 payload = '' def __init__(self, status_code, payload): self.status_code = status_code self.payload = payload Exception.__init__( self, 'ES_Exception: status_code={}, payload={}'.format(status_code, payload)) # Low-level POST data to Amazon Elasticsearch Service generating a Sigv4 signed request def post_data_to_es(payload, region, creds, host, path, method='POST', proto='https://'): '''Post data to ES endpoint with SigV4 signed http headers''' req = AWSRequest(method=method, url=proto + host + quote(path), data=payload, headers={'Host': host, 'Content-Type': 'application/json'}) SigV4Auth(creds, 'es', region).add_auth(req) http_session = BotocoreHTTPSession() res = http_session.send(req.prepare()) if res.status_code >= 200 and res.status_code <= 299: return res._content else: raise ES_Exception(res.status_code, res._content) # High-level POST data to Amazon Elasticsearch Service with exponential backoff # according to suggested algorithm: http://docs.aws.amazon.com/general/latest/gr/api-retries.html def post_to_es(payload): '''Post data to ES cluster with exponential backoff''' # Get aws_region and credentials to post signed URL to ES es_region = ES_REGION or os.environ['AWS_REGION'] session = Session({'region': es_region}) creds = get_credentials(session) es_url = urlparse(ES_ENDPOINT) # Extract the domain name in ES_ENDPOINT es_endpoint = es_url.netloc or es_url.path # Post data with exponential backoff retries = 0 while retries < ES_MAX_RETRIES: if retries > 0: seconds = (2 ** retries) * .1 logger.debug('Waiting for %.1f seconds', seconds) time.sleep(seconds) try: es_ret_str = post_data_to_es( payload, es_region, creds, es_endpoint, '/_bulk') logger.debug('Return from ES: %s', es_ret_str) es_ret = json.loads(es_ret_str) if es_ret['errors']: logger.error( 'ES post unsuccessful, errors present, took=%sms', es_ret['took']) # Filter errors es_errors = [item for item in es_ret['items'] if item.get('index', {}).get('error')] logger.error('List of items with errors: %s', json.dumps(es_errors)) else: logger.info('ES post successful, took=%sms', es_ret['took']) break # Sending to ES was ok, break retry loop except ES_Exception as e: if (e.status_code >= 500) and (e.status_code <= 599): retries += 1 # Candidate for retry else: raise # Stop retrying, re-raise exception # Extracts the DynamoDB table from an ARN # ex: arn:aws:dynamodb:eu-west-1:123456789012:table/table-name/stream/2015-11-13T09:23:17.104 should return 'table-name' def get_table_name_from_arn(arn): return arn.split(':')[5].split('/')[1] # Compute a compound doc index from the key(s) of the object in lexicographic order: "k1=key_val1|k2=key_val2" def compute_doc_index(keys_raw, deserializer, formatIndex=False): index = [] for key in sorted(keys_raw): if formatIndex: index.append('{}={}'.format( key, deserializer.deserialize(keys_raw[key]))) else: index.append(deserializer.deserialize(keys_raw[key])) return '|'.join(map(str,index)) def _lambda_handler(event, context): logger.debug('Event: %s', event) records = event['Records'] ddb_deserializer = StreamTypeDeserializer() es_actions = [] # Items to be added/updated/removed from ES - for bulk API cnt_insert = cnt_modify = cnt_remove = 0 for record in records: # Handle both native DynamoDB Streams or Streams data from Kinesis (for manual replay) logger.debug('Record: %s', record) if record.get('eventSource') == 'aws:dynamodb': ddb = record['dynamodb'] ddb_table_name = get_table_name_from_arn(record['eventSourceARN']) doc_seq = ddb['SequenceNumber'] elif record.get('eventSource') == 'aws:kinesis': ddb = json.loads(base64.b64decode(record['kinesis']['data'])) ddb_table_name = ddb['SourceTable'] doc_seq = record['kinesis']['sequenceNumber'] else: logger.error('Ignoring non-DynamoDB event sources: %s', record.get('eventSource')) continue # Compute DynamoDB table, type and index for item doc_table = ddb_table_name.lower() doc_type = DOC_TYPE doc_table_parts = doc_table.split('-') doc_es_index_name = doc_table_parts[0] if len(doc_table_parts) > 0 else doc_table # Dispatch according to event TYPE event_name = record['eventName'].upper() # INSERT, MODIFY, REMOVE logger.debug('doc_table=%s, event_name=%s, seq=%s', doc_table, event_name, doc_seq) # Treat events from a Kinesis stream as INSERTs if event_name == 'AWS:KINESIS:RECORD': event_name = 'INSERT' is_ddb_insert_or_update = (event_name == 'INSERT') or (event_name == 'MODIFY') is_ddb_delete = event_name == 'REMOVE' image_name = 'NewImage' if is_ddb_insert_or_update else 'OldImage' if image_name not in ddb: logger.warning( 'Cannot process stream if it does not contain ' + image_name) continue logger.debug(image_name + ': %s', ddb[image_name]) # Deserialize DynamoDB type to Python types doc_fields = ddb_deserializer.deserialize({'M': ddb[image_name]}) # Sync enabled APIs do soft delete. We need to delete the record in ES if _deleted field is set if ES_USE_EXTERNAL_VERSIONING and event_name == 'MODIFY' and '_deleted' in doc_fields and doc_fields['_deleted']: is_ddb_insert_or_update = False is_ddb_delete = True # Update counters if event_name == 'INSERT': cnt_insert += 1 elif event_name == 'MODIFY': cnt_modify += 1 elif event_name == 'REMOVE': cnt_remove += 1 else: logger.warning('Unsupported event_name: %s', event_name) logger.debug('Deserialized doc_fields: %s', doc_fields) if ('Keys' in ddb): doc_id = compute_doc_index(ddb['Keys'], ddb_deserializer) else: logger.error('Cannot find keys in ddb record') # If DynamoDB INSERT or MODIFY, send 'index' to ES if is_ddb_insert_or_update: # Generate ES payload for item action = {'index': {'_index': doc_es_index_name, '_type': doc_type, '_id': doc_id}} # Add external versioning if necessary if ES_USE_EXTERNAL_VERSIONING and '_version' in doc_fields: action['index'].update([ ('version_type', 'external'), ('_version', doc_fields['_version']) ]) doc_fields.pop('_ttl', None) doc_fields.pop('_version', None) # Append ES Action line with 'index' directive es_actions.append(json.dumps(action)) # Append JSON payload es_actions.append(json.dumps(doc_fields, cls=DDBTypesEncoder)) # migration step remove old key if it exists if ('id' in doc_fields) and (event_name == 'MODIFY') : action = {'delete': {'_index': doc_es_index_name, '_type': doc_type, '_id': compute_doc_index(ddb['Keys'], ddb_deserializer, True)}} es_actions.append(json.dumps(action)) # If DynamoDB REMOVE, send 'delete' to ES elif is_ddb_delete: action = {'delete': {'_index': doc_es_index_name, '_type': doc_type, '_id': doc_id}} if ES_USE_EXTERNAL_VERSIONING and '_version' in doc_fields: action['delete'].update([ ('version_type', 'external'), ('_version', doc_fields['_version']) ]) # Action line with 'delete' directive es_actions.append(json.dumps(action)) # Prepare bulk payload es_actions.append('') # Add one empty line to force final \n es_payload = '\n'.join(es_actions) logger.info('Posting to ES: inserts=%s updates=%s deletes=%s, total_lines=%s, bytes_total=%s', cnt_insert, cnt_modify, cnt_remove, len(es_actions) - 1, len(es_payload)) post_to_es(es_payload) # Post to ES with exponential backoff # Global lambda handler - catches all exceptions to avoid dead letter in the DynamoDB Stream def lambda_handler(event, context): try: return _lambda_handler(event, context) except Exception: logger.error(traceback.format_exc())
41.457364
122
0.63089
import base64 import json import logging import os import time import traceback from urllib.parse import urlparse, quote from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest from botocore.credentials import get_credentials from botocore.endpoint import BotocoreHTTPSession from botocore.session import Session from boto3.dynamodb.types import TypeDeserializer ES_ENDPOINT = os.environ['ES_ENDPOINT'] ES_REGION = os.environ['ES_REGION'] DEBUG = True if os.environ['DEBUG'] == "1" else False ES_USE_EXTERNAL_VERSIONING = True if os.environ['ES_USE_EXTERNAL_VERSIONING'] == "true" else False DOC_TYPE = 'doc' ES_MAX_RETRIES = 3 logger = logging.getLogger() logger.setLevel(logging.DEBUG if DEBUG else logging.INFO) logger.info("Streaming to ElasticSearch") class DDBTypesEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) return json.JSONEncoder.default(self, obj) class StreamTypeDeserializer(TypeDeserializer): def _deserialize_n(self, value): return float(value) def _deserialize_b(self, value): return value # Already in Base64 class ES_Exception(Exception): status_code = 0 payload = '' def __init__(self, status_code, payload): self.status_code = status_code self.payload = payload Exception.__init__( self, 'ES_Exception: status_code={}, payload={}'.format(status_code, payload)) # Low-level POST data to Amazon Elasticsearch Service generating a Sigv4 signed request def post_data_to_es(payload, region, creds, host, path, method='POST', proto='https://'): req = AWSRequest(method=method, url=proto + host + quote(path), data=payload, headers={'Host': host, 'Content-Type': 'application/json'}) SigV4Auth(creds, 'es', region).add_auth(req) http_session = BotocoreHTTPSession() res = http_session.send(req.prepare()) if res.status_code >= 200 and res.status_code <= 299: return res._content else: raise ES_Exception(res.status_code, res._content) # High-level POST data to Amazon Elasticsearch Service with exponential backoff # according to suggested algorithm: http://docs.aws.amazon.com/general/latest/gr/api-retries.html def post_to_es(payload): # Get aws_region and credentials to post signed URL to ES es_region = ES_REGION or os.environ['AWS_REGION'] session = Session({'region': es_region}) creds = get_credentials(session) es_url = urlparse(ES_ENDPOINT) # Extract the domain name in ES_ENDPOINT es_endpoint = es_url.netloc or es_url.path # Post data with exponential backoff retries = 0 while retries < ES_MAX_RETRIES: if retries > 0: seconds = (2 ** retries) * .1 logger.debug('Waiting for %.1f seconds', seconds) time.sleep(seconds) try: es_ret_str = post_data_to_es( payload, es_region, creds, es_endpoint, '/_bulk') logger.debug('Return from ES: %s', es_ret_str) es_ret = json.loads(es_ret_str) if es_ret['errors']: logger.error( 'ES post unsuccessful, errors present, took=%sms', es_ret['took']) # Filter errors es_errors = [item for item in es_ret['items'] if item.get('index', {}).get('error')] logger.error('List of items with errors: %s', json.dumps(es_errors)) else: logger.info('ES post successful, took=%sms', es_ret['took']) break # Sending to ES was ok, break retry loop except ES_Exception as e: if (e.status_code >= 500) and (e.status_code <= 599): retries += 1 # Candidate for retry else: raise # Stop retrying, re-raise exception # Extracts the DynamoDB table from an ARN # ex: arn:aws:dynamodb:eu-west-1:123456789012:table/table-name/stream/2015-11-13T09:23:17.104 should return 'table-name' def get_table_name_from_arn(arn): return arn.split(':')[5].split('/')[1] # Compute a compound doc index from the key(s) of the object in lexicographic order: "k1=key_val1|k2=key_val2" def compute_doc_index(keys_raw, deserializer, formatIndex=False): index = [] for key in sorted(keys_raw): if formatIndex: index.append('{}={}'.format( key, deserializer.deserialize(keys_raw[key]))) else: index.append(deserializer.deserialize(keys_raw[key])) return '|'.join(map(str,index)) def _lambda_handler(event, context): logger.debug('Event: %s', event) records = event['Records'] ddb_deserializer = StreamTypeDeserializer() es_actions = [] # Items to be added/updated/removed from ES - for bulk API cnt_insert = cnt_modify = cnt_remove = 0 for record in records: # Handle both native DynamoDB Streams or Streams data from Kinesis (for manual replay) logger.debug('Record: %s', record) if record.get('eventSource') == 'aws:dynamodb': ddb = record['dynamodb'] ddb_table_name = get_table_name_from_arn(record['eventSourceARN']) doc_seq = ddb['SequenceNumber'] elif record.get('eventSource') == 'aws:kinesis': ddb = json.loads(base64.b64decode(record['kinesis']['data'])) ddb_table_name = ddb['SourceTable'] doc_seq = record['kinesis']['sequenceNumber'] else: logger.error('Ignoring non-DynamoDB event sources: %s', record.get('eventSource')) continue # Compute DynamoDB table, type and index for item doc_table = ddb_table_name.lower() doc_type = DOC_TYPE doc_table_parts = doc_table.split('-') doc_es_index_name = doc_table_parts[0] if len(doc_table_parts) > 0 else doc_table # Dispatch according to event TYPE event_name = record['eventName'].upper() # INSERT, MODIFY, REMOVE logger.debug('doc_table=%s, event_name=%s, seq=%s', doc_table, event_name, doc_seq) # Treat events from a Kinesis stream as INSERTs if event_name == 'AWS:KINESIS:RECORD': event_name = 'INSERT' is_ddb_insert_or_update = (event_name == 'INSERT') or (event_name == 'MODIFY') is_ddb_delete = event_name == 'REMOVE' image_name = 'NewImage' if is_ddb_insert_or_update else 'OldImage' if image_name not in ddb: logger.warning( 'Cannot process stream if it does not contain ' + image_name) continue logger.debug(image_name + ': %s', ddb[image_name]) # Deserialize DynamoDB type to Python types doc_fields = ddb_deserializer.deserialize({'M': ddb[image_name]}) # Sync enabled APIs do soft delete. We need to delete the record in ES if _deleted field is set if ES_USE_EXTERNAL_VERSIONING and event_name == 'MODIFY' and '_deleted' in doc_fields and doc_fields['_deleted']: is_ddb_insert_or_update = False is_ddb_delete = True # Update counters if event_name == 'INSERT': cnt_insert += 1 elif event_name == 'MODIFY': cnt_modify += 1 elif event_name == 'REMOVE': cnt_remove += 1 else: logger.warning('Unsupported event_name: %s', event_name) logger.debug('Deserialized doc_fields: %s', doc_fields) if ('Keys' in ddb): doc_id = compute_doc_index(ddb['Keys'], ddb_deserializer) else: logger.error('Cannot find keys in ddb record') # If DynamoDB INSERT or MODIFY, send 'index' to ES if is_ddb_insert_or_update: # Generate ES payload for item action = {'index': {'_index': doc_es_index_name, '_type': doc_type, '_id': doc_id}} # Add external versioning if necessary if ES_USE_EXTERNAL_VERSIONING and '_version' in doc_fields: action['index'].update([ ('version_type', 'external'), ('_version', doc_fields['_version']) ]) doc_fields.pop('_ttl', None) doc_fields.pop('_version', None) # Append ES Action line with 'index' directive es_actions.append(json.dumps(action)) # Append JSON payload es_actions.append(json.dumps(doc_fields, cls=DDBTypesEncoder)) # migration step remove old key if it exists if ('id' in doc_fields) and (event_name == 'MODIFY') : action = {'delete': {'_index': doc_es_index_name, '_type': doc_type, '_id': compute_doc_index(ddb['Keys'], ddb_deserializer, True)}} es_actions.append(json.dumps(action)) # If DynamoDB REMOVE, send 'delete' to ES elif is_ddb_delete: action = {'delete': {'_index': doc_es_index_name, '_type': doc_type, '_id': doc_id}} if ES_USE_EXTERNAL_VERSIONING and '_version' in doc_fields: action['delete'].update([ ('version_type', 'external'), ('_version', doc_fields['_version']) ]) # Action line with 'delete' directive es_actions.append(json.dumps(action)) # Prepare bulk payload es_actions.append('') # Add one empty line to force final \n es_payload = '\n'.join(es_actions) logger.info('Posting to ES: inserts=%s updates=%s deletes=%s, total_lines=%s, bytes_total=%s', cnt_insert, cnt_modify, cnt_remove, len(es_actions) - 1, len(es_payload)) post_to_es(es_payload) # Post to ES with exponential backoff # Global lambda handler - catches all exceptions to avoid dead letter in the DynamoDB Stream def lambda_handler(event, context): try: return _lambda_handler(event, context) except Exception: logger.error(traceback.format_exc())
true
true
f72a3a7ba2336005b049f9e3a57c4f4b44ad48b8
47
py
Python
docs/test-dataset/code/some-code.py
slugb0t/SODA-for-SPARC
f2dd5f5817984ca0a500dd628f8055a6a0d1ff48
[ "MIT" ]
16
2019-11-19T02:19:16.000Z
2022-01-09T04:51:50.000Z
docs/test-dataset/code/some-code.py
slugb0t/SODA-for-SPARC
f2dd5f5817984ca0a500dd628f8055a6a0d1ff48
[ "MIT" ]
6
2020-06-17T19:37:08.000Z
2021-08-03T21:01:25.000Z
docs/test-dataset/code/some-code.py
slugb0t/SODA-for-SPARC
f2dd5f5817984ca0a500dd628f8055a6a0d1ff48
[ "MIT" ]
7
2019-11-08T20:45:32.000Z
2021-09-15T22:45:18.000Z
print('Hello! This is an example python file.')
47
47
0.744681
print('Hello! This is an example python file.')
true
true
f72a3bfc43a32b945e3678a36f687019936e886c
2,966
py
Python
nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py
nicholsn/nipype
6601b00aac39d17bb9fb3a6801f5a740a6ebb1e3
[ "BSD-3-Clause" ]
1
2018-04-18T12:13:37.000Z
2018-04-18T12:13:37.000Z
nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py
ito-takuya/nipype
9099a5809487b55868cdec82a719030419cbd6ba
[ "BSD-3-Clause" ]
null
null
null
nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py
ito-takuya/nipype
9099a5809487b55868cdec82a719030419cbd6ba
[ "BSD-3-Clause" ]
1
2021-09-08T14:31:47.000Z
2021-09-08T14:31:47.000Z
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.freesurfer.utils import SurfaceSnapshots def test_SurfaceSnapshots_inputs(): input_map = dict(annot_file=dict(argstr='-annotation %s', xor=['annot_name'], ), annot_name=dict(argstr='-annotation %s', xor=['annot_file'], ), args=dict(argstr='%s', ), colortable=dict(argstr='-colortable %s', ), demean_overlay=dict(argstr='-zm', ), environ=dict(nohash=True, usedefault=True, ), hemi=dict(argstr='%s', mandatory=True, position=2, ), identity_reg=dict(argstr='-overlay-reg-identity', xor=['overlay_reg', 'identity_reg', 'mni152_reg'], ), ignore_exception=dict(nohash=True, usedefault=True, ), invert_overlay=dict(argstr='-invphaseflag 1', ), label_file=dict(argstr='-label %s', xor=['label_name'], ), label_name=dict(argstr='-label %s', xor=['label_file'], ), label_outline=dict(argstr='-label-outline', ), label_under=dict(argstr='-labels-under', ), mni152_reg=dict(argstr='-mni152reg', xor=['overlay_reg', 'identity_reg', 'mni152_reg'], ), orig_suffix=dict(argstr='-orig %s', ), overlay=dict(argstr='-overlay %s', requires=['overlay_range'], ), overlay_range=dict(argstr='%s', ), overlay_range_offset=dict(argstr='-foffset %.3f', ), overlay_reg=dict(argstr='-overlay-reg %s', xor=['overlay_reg', 'identity_reg', 'mni152_reg'], ), patch_file=dict(argstr='-patch %s', ), reverse_overlay=dict(argstr='-revphaseflag 1', ), screenshot_stem=dict(), show_color_scale=dict(argstr='-colscalebarflag 1', ), show_color_text=dict(argstr='-colscaletext 1', ), show_curv=dict(argstr='-curv', xor=['show_gray_curv'], ), show_gray_curv=dict(argstr='-gray', xor=['show_curv'], ), six_images=dict(), sphere_suffix=dict(argstr='-sphere %s', ), stem_template_args=dict(requires=['screenshot_stem'], ), subject_id=dict(argstr='%s', mandatory=True, position=1, ), subjects_dir=dict(), surface=dict(argstr='%s', mandatory=True, position=3, ), tcl_script=dict(argstr='%s', genfile=True, ), terminal_output=dict(mandatory=True, nohash=True, ), truncate_overlay=dict(argstr='-truncphaseflag 1', ), ) inputs = SurfaceSnapshots.input_spec() for key, metadata in input_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_SurfaceSnapshots_outputs(): output_map = dict(snapshots=dict(), ) outputs = SurfaceSnapshots.output_spec() for key, metadata in output_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(outputs.traits()[key], metakey), value
26.720721
78
0.631827
from nipype.testing import assert_equal from nipype.interfaces.freesurfer.utils import SurfaceSnapshots def test_SurfaceSnapshots_inputs(): input_map = dict(annot_file=dict(argstr='-annotation %s', xor=['annot_name'], ), annot_name=dict(argstr='-annotation %s', xor=['annot_file'], ), args=dict(argstr='%s', ), colortable=dict(argstr='-colortable %s', ), demean_overlay=dict(argstr='-zm', ), environ=dict(nohash=True, usedefault=True, ), hemi=dict(argstr='%s', mandatory=True, position=2, ), identity_reg=dict(argstr='-overlay-reg-identity', xor=['overlay_reg', 'identity_reg', 'mni152_reg'], ), ignore_exception=dict(nohash=True, usedefault=True, ), invert_overlay=dict(argstr='-invphaseflag 1', ), label_file=dict(argstr='-label %s', xor=['label_name'], ), label_name=dict(argstr='-label %s', xor=['label_file'], ), label_outline=dict(argstr='-label-outline', ), label_under=dict(argstr='-labels-under', ), mni152_reg=dict(argstr='-mni152reg', xor=['overlay_reg', 'identity_reg', 'mni152_reg'], ), orig_suffix=dict(argstr='-orig %s', ), overlay=dict(argstr='-overlay %s', requires=['overlay_range'], ), overlay_range=dict(argstr='%s', ), overlay_range_offset=dict(argstr='-foffset %.3f', ), overlay_reg=dict(argstr='-overlay-reg %s', xor=['overlay_reg', 'identity_reg', 'mni152_reg'], ), patch_file=dict(argstr='-patch %s', ), reverse_overlay=dict(argstr='-revphaseflag 1', ), screenshot_stem=dict(), show_color_scale=dict(argstr='-colscalebarflag 1', ), show_color_text=dict(argstr='-colscaletext 1', ), show_curv=dict(argstr='-curv', xor=['show_gray_curv'], ), show_gray_curv=dict(argstr='-gray', xor=['show_curv'], ), six_images=dict(), sphere_suffix=dict(argstr='-sphere %s', ), stem_template_args=dict(requires=['screenshot_stem'], ), subject_id=dict(argstr='%s', mandatory=True, position=1, ), subjects_dir=dict(), surface=dict(argstr='%s', mandatory=True, position=3, ), tcl_script=dict(argstr='%s', genfile=True, ), terminal_output=dict(mandatory=True, nohash=True, ), truncate_overlay=dict(argstr='-truncphaseflag 1', ), ) inputs = SurfaceSnapshots.input_spec() for key, metadata in input_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_SurfaceSnapshots_outputs(): output_map = dict(snapshots=dict(), ) outputs = SurfaceSnapshots.output_spec() for key, metadata in output_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(outputs.traits()[key], metakey), value
true
true
f72a3c91953b5858fea12c86441ca8a3375897bc
420
py
Python
examples/quantum/hydrogen.py
olivierverdier/sfepy
83aefb7b33ea17f4acb83388ba8bc7314c77616c
[ "BSD-3-Clause" ]
1
2015-07-30T13:47:23.000Z
2015-07-30T13:47:23.000Z
examples/quantum/hydrogen.py
olivierverdier/sfepy
83aefb7b33ea17f4acb83388ba8bc7314c77616c
[ "BSD-3-Clause" ]
null
null
null
examples/quantum/hydrogen.py
olivierverdier/sfepy
83aefb7b33ea17f4acb83388ba8bc7314c77616c
[ "BSD-3-Clause" ]
null
null
null
from sfepy.linalg import norm_l2_along_axis from quantum_common import common def fun_v(ts, coor, mode=None, region=None, ig=None): from numpy import sqrt if not mode == 'qp': return out = {} C = 0.5 r = norm_l2_along_axis(coor, axis=1) V = - C * 1.0 / r V.shape = (V.shape[0], 1, 1) out['V'] = V return out def define(): l = common(fun_v, n_eigs=5, tau=-1.0) return l
18.26087
53
0.597619
from sfepy.linalg import norm_l2_along_axis from quantum_common import common def fun_v(ts, coor, mode=None, region=None, ig=None): from numpy import sqrt if not mode == 'qp': return out = {} C = 0.5 r = norm_l2_along_axis(coor, axis=1) V = - C * 1.0 / r V.shape = (V.shape[0], 1, 1) out['V'] = V return out def define(): l = common(fun_v, n_eigs=5, tau=-1.0) return l
true
true
f72a3ca047444fe42cfb054b4d7ce31ac8ea8792
322
py
Python
djthia/dashboard/urls.py
carthage-college/django-djthia
a10026b305aa75e20d2ea8c5d3e7ad03c05f10f5
[ "MIT" ]
null
null
null
djthia/dashboard/urls.py
carthage-college/django-djthia
a10026b305aa75e20d2ea8c5d3e7ad03c05f10f5
[ "MIT" ]
9
2020-08-02T13:58:23.000Z
2022-02-15T15:30:58.000Z
djthia/dashboard/urls.py
carthage-college/django-djthia
a10026b305aa75e20d2ea8c5d3e7ad03c05f10f5
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """URLs for all views.""" from django.urls import path from djthia.dashboard import views urlpatterns = [ path('<str:oid>/detail/', views.detail, name='gearup_detail'), path('search/', views.search, name='gearup_search'), path('', views.home, name='dashboard_home'), ]
23
67
0.630435
from django.urls import path from djthia.dashboard import views urlpatterns = [ path('<str:oid>/detail/', views.detail, name='gearup_detail'), path('search/', views.search, name='gearup_search'), path('', views.home, name='dashboard_home'), ]
true
true
f72a3ce19ca0b74533a7945aaed6c0b03ba83aa2
33,034
py
Python
optuna/storages/rdb/storage.py
scouvreur/optuna
41716fe394aca87e5dce465443ac72ed53891a44
[ "MIT" ]
null
null
null
optuna/storages/rdb/storage.py
scouvreur/optuna
41716fe394aca87e5dce465443ac72ed53891a44
[ "MIT" ]
null
null
null
optuna/storages/rdb/storage.py
scouvreur/optuna
41716fe394aca87e5dce465443ac72ed53891a44
[ "MIT" ]
null
null
null
import alembic.command import alembic.config import alembic.migration import alembic.script from collections import defaultdict import copy from datetime import datetime import json import logging import os import six from sqlalchemy.engine import create_engine from sqlalchemy.engine import Engine # NOQA from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import SQLAlchemyError from sqlalchemy import orm import sys import threading import uuid import optuna from optuna import distributions from optuna.storages.base import BaseStorage from optuna.storages.base import DEFAULT_STUDY_NAME_PREFIX from optuna.storages.rdb import models from optuna import structs from optuna import type_checking from optuna import version if type_checking.TYPE_CHECKING: from typing import Any # NOQA from typing import Dict # NOQA from typing import List # NOQA from typing import Optional # NOQA class RDBStorage(BaseStorage): """Storage class for RDB backend. This class is not supposed to be directly accessed by library users. Args: url: URL of the storage. engine_kwargs: A dictionary of keyword arguments that is passed to :func:`sqlalchemy.engine.create_engine`. enable_cache: Flag to control whether to enable storage layer caching. If this flag is set to :obj:`True` (the default), the finished trials are cached on memory and never re-fetched from the storage. Otherwise, the trials are fetched from the storage whenever they are needed. """ def __init__(self, url, engine_kwargs=None, enable_cache=True, skip_compatibility_check=False): # type: (str, Optional[Dict[str, Any]], bool, bool) -> None engine_kwargs = engine_kwargs or {} url = self._fill_storage_url_template(url) try: self.engine = create_engine(url, **engine_kwargs) except ImportError as e: raise ImportError('Failed to import DB access module for the specified storage URL. ' 'Please install appropriate one. (The actual import error is: ' + str(e) + '.)') self.scoped_session = orm.scoped_session(orm.sessionmaker(bind=self.engine)) models.BaseModel.metadata.create_all(self.engine) self.logger = optuna.logging.get_logger(__name__) self._version_manager = _VersionManager(url, self.engine, self.scoped_session) if not skip_compatibility_check: self._version_manager.check_table_schema_compatibility() self._finished_trials_cache = _FinishedTrialsCache(enable_cache) def create_new_study_id(self, study_name=None): # type: (Optional[str]) -> int session = self.scoped_session() if study_name is None: study_name = self._create_unique_study_name(session) study = models.StudyModel(study_name=study_name, direction=structs.StudyDirection.NOT_SET) session.add(study) if not self._commit_with_integrity_check(session): raise structs.DuplicatedStudyError( "Another study with name '{}' already exists. " "Please specify a different name, or reuse the existing one " "by setting `load_if_exists` (for Python API) or " "`--skip-if-exists` flag (for CLI).".format(study_name)) self.logger.info('A new study created with name: {}'.format(study.study_name)) return study.study_id @staticmethod def _create_unique_study_name(session): # type: (orm.Session) -> str while True: study_uuid = str(uuid.uuid4()) study_name = DEFAULT_STUDY_NAME_PREFIX + study_uuid study = models.StudyModel.find_by_name(study_name, session) if study is None: break return study_name # TODO(sano): Prevent simultaneously setting different direction in distributed environments. def set_study_direction(self, study_id, direction): # type: (int, structs.StudyDirection) -> None session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) if study.direction != structs.StudyDirection.NOT_SET and study.direction != direction: raise ValueError('Cannot overwrite study direction from {} to {}.'.format( study.direction, direction)) study.direction = direction self._commit(session) def set_study_user_attr(self, study_id, key, value): # type: (int, str, Any) -> None session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) attribute = models.StudyUserAttributeModel.find_by_study_and_key(study, key, session) if attribute is None: attribute = models.StudyUserAttributeModel( study_id=study_id, key=key, value_json=json.dumps(value)) session.add(attribute) else: attribute.value_json = json.dumps(value) self._commit_with_integrity_check(session) def set_study_system_attr(self, study_id, key, value): # type: (int, str, Any) -> None session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) attribute = models.StudySystemAttributeModel.find_by_study_and_key(study, key, session) if attribute is None: attribute = models.StudySystemAttributeModel( study_id=study_id, key=key, value_json=json.dumps(value)) session.add(attribute) else: attribute.value_json = json.dumps(value) self._commit_with_integrity_check(session) def get_study_id_from_name(self, study_name): # type: (str) -> int session = self.scoped_session() study = models.StudyModel.find_or_raise_by_name(study_name, session) return study.study_id def get_study_id_from_trial_id(self, trial_id): # type: (int) -> int session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) return trial.study_id def get_study_name_from_id(self, study_id): # type: (int) -> str session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) return study.study_name def get_study_direction(self, study_id): # type: (int) -> structs.StudyDirection session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) return study.direction def get_study_user_attrs(self, study_id): # type: (int) -> Dict[str, Any] session = self.scoped_session() attributes = models.StudyUserAttributeModel.where_study_id(study_id, session) return {attr.key: json.loads(attr.value_json) for attr in attributes} def get_study_system_attrs(self, study_id): # type: (int) -> Dict[str, Any] session = self.scoped_session() attributes = models.StudySystemAttributeModel.where_study_id(study_id, session) return {attr.key: json.loads(attr.value_json) for attr in attributes} def get_trial_user_attrs(self, trial_id): # type: (int) -> Dict[str, Any] session = self.scoped_session() attributes = models.TrialUserAttributeModel.where_trial_id(trial_id, session) return {attr.key: json.loads(attr.value_json) for attr in attributes} def get_trial_system_attrs(self, trial_id): # type: (int) -> Dict[str, Any] session = self.scoped_session() attributes = models.TrialSystemAttributeModel.where_trial_id(trial_id, session) return {attr.key: json.loads(attr.value_json) for attr in attributes} # TODO(sano): Optimize this method to reduce the number of queries. def get_all_study_summaries(self): # type: () -> List[structs.StudySummary] session = self.scoped_session() study_models = models.StudyModel.all(session) trial_models = models.TrialModel.all(session) param_models = models.TrialParamModel.all(session) value_models = models.TrialValueModel.all(session) trial_user_attribute_models = models.TrialUserAttributeModel.all(session) trial_system_attribute_models = models.TrialSystemAttributeModel.all(session) study_sumarries = [] for study_model in study_models: # Filter model objects by study. study_trial_models = [t for t in trial_models if t.study_id == study_model.study_id] # Get best trial. completed_trial_models = [ t for t in study_trial_models if t.state is structs.TrialState.COMPLETE ] best_trial = None if len(completed_trial_models) > 0: if study_model.direction == structs.StudyDirection.MAXIMIZE: best_trial_model = max(completed_trial_models, key=lambda t: t.value) else: best_trial_model = min(completed_trial_models, key=lambda t: t.value) best_param_models = [ p for p in param_models if p.trial_id == best_trial_model.trial_id ] best_value_models = [ v for v in value_models if v.trial_id == best_trial_model.trial_id ] best_trial_user_models = [ u for u in trial_user_attribute_models if u.trial_id == best_trial_model.trial_id ] best_trial_system_models = [ s for s in trial_system_attribute_models if s.trial_id == best_trial_model.trial_id ] # Merge model objects related to the best trial. best_trial = self._merge_trials_orm([best_trial_model], best_param_models, best_value_models, best_trial_user_models, best_trial_system_models)[0] # Find datetime_start. datetime_start = None if len(study_trial_models) > 0: datetime_start = min([t.datetime_start for t in study_trial_models]) attributes = models.StudySystemAttributeModel.where_study_id( study_model.study_id, session) system_attrs = {attr.key: json.loads(attr.value_json) for attr in attributes} # Consolidate StudySummary. study_sumarries.append( structs.StudySummary( study_id=study_model.study_id, study_name=study_model.study_name, direction=self.get_study_direction(study_model.study_id), best_trial=best_trial, user_attrs=self.get_study_user_attrs(study_model.study_id), system_attrs=system_attrs, n_trials=len(study_trial_models), datetime_start=datetime_start)) return study_sumarries def create_new_trial_id(self, study_id): # type: (int) -> int session = self.scoped_session() trial = models.TrialModel(study_id=study_id, state=structs.TrialState.RUNNING) session.add(trial) self._commit(session) self._create_new_trial_number(trial.trial_id) return trial.trial_id def _create_new_trial_number(self, trial_id): # type: (int) -> int session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) trial_number = trial.count_past_trials(session) self.set_trial_system_attr(trial.trial_id, '_number', trial_number) return trial_number def set_trial_state(self, trial_id, state): # type: (int, structs.TrialState) -> None session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) trial.state = state if state.is_finished(): trial.datetime_complete = datetime.now() self._commit(session) def set_trial_param(self, trial_id, param_name, param_value_internal, distribution): # type: (int, str, float, distributions.BaseDistribution) -> bool session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) trial_param = \ models.TrialParamModel.find_by_trial_and_param_name(trial, param_name, session) if trial_param is not None: # Raise error in case distribution is incompatible. distributions.check_distribution_compatibility( distributions.json_to_distribution(trial_param.distribution_json), distribution) # Return False when distribution is compatible but parameter has already been set. return False param = models.TrialParamModel( trial_id=trial_id, param_name=param_name, param_value=param_value_internal, distribution_json=distributions.distribution_to_json(distribution)) param.check_and_add(session) commit_success = self._commit_with_integrity_check(session) return commit_success def get_trial_param(self, trial_id, param_name): # type: (int, str) -> float session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) trial_param = models.TrialParamModel.find_or_raise_by_trial_and_param_name( trial, param_name, session) return trial_param.param_value def set_trial_value(self, trial_id, value): # type: (int, float) -> None session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) trial.value = value self._commit(session) def set_trial_intermediate_value(self, trial_id, step, intermediate_value): # type: (int, int, float) -> bool session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) trial_value = models.TrialValueModel.find_by_trial_and_step(trial, step, session) if trial_value is not None: return False trial_value = models.TrialValueModel( trial_id=trial_id, step=step, value=intermediate_value) session.add(trial_value) commit_success = self._commit_with_integrity_check(session) return commit_success def set_trial_user_attr(self, trial_id, key, value): # type: (int, str, Any) -> None session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) attribute = models.TrialUserAttributeModel.find_by_trial_and_key(trial, key, session) if attribute is None: attribute = models.TrialUserAttributeModel( trial_id=trial_id, key=key, value_json=json.dumps(value)) session.add(attribute) else: attribute.value_json = json.dumps(value) self._commit_with_integrity_check(session) def set_trial_system_attr(self, trial_id, key, value): # type: (int, str, Any) -> None session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) if key == '_number': # `_number` attribute may be set even after a trial is finished. # This happens if the trial was created before v0.9.0, # where a trial didn't have `_number` attribute. # In this case, `check_trial_is_updatable` is skipped to avoid the `RuntimeError`. # # TODO(ohta): Remove this workaround when `number` field is added to `TrialModel`. pass else: self.check_trial_is_updatable(trial_id, trial.state) attribute = models.TrialSystemAttributeModel.find_by_trial_and_key(trial, key, session) if attribute is None: attribute = models.TrialSystemAttributeModel( trial_id=trial_id, key=key, value_json=json.dumps(value)) session.add(attribute) else: attribute.value_json = json.dumps(value) self._commit_with_integrity_check(session) def get_trial_number_from_id(self, trial_id): # type: (int) -> int trial_number = self.get_trial_system_attrs(trial_id).get('_number') if trial_number is None: # If a study is created by optuna<=0.8.0, trial number is not found. # Create new one. return self._create_new_trial_number(trial_id) return trial_number def get_trial(self, trial_id): # type: (int) -> structs.FrozenTrial cached_trial = self._finished_trials_cache.get_cached_trial(trial_id) if cached_trial is not None: return copy.deepcopy(cached_trial) session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) params = models.TrialParamModel.where_trial(trial, session) values = models.TrialValueModel.where_trial(trial, session) user_attributes = models.TrialUserAttributeModel.where_trial(trial, session) system_attributes = models.TrialSystemAttributeModel.where_trial(trial, session) frozen_trial = self._merge_trials_orm([trial], params, values, user_attributes, system_attributes)[0] self._finished_trials_cache.cache_trial_if_finished(frozen_trial) return frozen_trial def get_all_trials(self, study_id): # type: (int) -> List[structs.FrozenTrial] if self._finished_trials_cache.is_empty(): trials = self._get_all_trials_without_cache(study_id) for trial in trials: self._finished_trials_cache.cache_trial_if_finished(trial) return trials trial_ids = self._get_all_trial_ids(study_id) trials = [self.get_trial(trial_id) for trial_id in trial_ids] return trials def _get_all_trial_ids(self, study_id): # type: (int) -> List[int] session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) return models.TrialModel.get_all_trial_ids_where_study(study, session) def _get_all_trials_without_cache(self, study_id): # type: (int) -> List[structs.FrozenTrial] session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) trials = models.TrialModel.where_study(study, session) params = models.TrialParamModel.where_study(study, session) values = models.TrialValueModel.where_study(study, session) user_attributes = models.TrialUserAttributeModel.where_study(study, session) system_attributes = models.TrialSystemAttributeModel.where_study(study, session) return self._merge_trials_orm(trials, params, values, user_attributes, system_attributes) def get_n_trials(self, study_id, state=None): # type: (int, Optional[structs.TrialState]) -> int session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) return models.TrialModel.count(session, study, state) def _merge_trials_orm( self, trials, # type: List[models.TrialModel] trial_params, # type: List[models.TrialParamModel] trial_intermediate_values, # type: List[models.TrialValueModel] trial_user_attrs, # type: List[models.TrialUserAttributeModel] trial_system_attrs # type: List[models.TrialSystemAttributeModel] ): # type: (...) -> List[structs.FrozenTrial] id_to_trial = {} for trial in trials: id_to_trial[trial.trial_id] = trial id_to_params = defaultdict(list) # type: Dict[int, List[models.TrialParamModel]] for param in trial_params: id_to_params[param.trial_id].append(param) id_to_values = defaultdict(list) # type: Dict[int, List[models.TrialValueModel]] for value in trial_intermediate_values: id_to_values[value.trial_id].append(value) id_to_user_attrs = \ defaultdict(list) # type: Dict[int, List[models.TrialUserAttributeModel]] for user_attr in trial_user_attrs: id_to_user_attrs[user_attr.trial_id].append(user_attr) id_to_system_attrs = \ defaultdict(list) # type: Dict[int, List[models.TrialSystemAttributeModel]] for system_attr in trial_system_attrs: id_to_system_attrs[system_attr.trial_id].append(system_attr) temp_trials = [] for trial_id, trial in id_to_trial.items(): params = {} param_distributions = {} for param in id_to_params[trial_id]: distribution = distributions.json_to_distribution(param.distribution_json) params[param.param_name] = distribution.to_external_repr(param.param_value) param_distributions[param.param_name] = distribution intermediate_values = {} for value in id_to_values[trial_id]: intermediate_values[value.step] = value.value user_attrs = {} for user_attr in id_to_user_attrs[trial_id]: user_attrs[user_attr.key] = json.loads(user_attr.value_json) system_attrs = {} for system_attr in id_to_system_attrs[trial_id]: system_attrs[system_attr.key] = json.loads(system_attr.value_json) # `-1` is a dummy value. # It will be replaced by a proper value before returned to the caller. # # TODO(ohta): Use trial.number after TrialModel.number is added. trial_number = -1 temp_trials.append( structs.FrozenTrial( number=trial_number, state=trial.state, params=params, distributions=param_distributions, user_attrs=user_attrs, system_attrs=system_attrs, value=trial.value, intermediate_values=intermediate_values, datetime_start=trial.datetime_start, datetime_complete=trial.datetime_complete, trial_id=trial_id)) result = [] for temp_trial in temp_trials: # [NOTE] # We set actual trial numbers here to avoid calling `self.get_trial_number_from_id()` # within the above loop. # # This is because `self.get_trial_number_from_id()` may call `session.commit()` # internally, which causes unintended changes of the states of `trials`. # (see https://github.com/pfnet/optuna/pull/349#issuecomment-475086642 for details) trial_number = self.get_trial_number_from_id(temp_trial.trial_id) result.append(temp_trial._replace(number=trial_number)) return result @staticmethod def _fill_storage_url_template(template): # type: (str) -> str return template.format(SCHEMA_VERSION=models.SCHEMA_VERSION) @staticmethod def _commit_with_integrity_check(session): # type: (orm.Session) -> bool try: session.commit() except IntegrityError as e: logger = optuna.logging.get_logger(__name__) logger.debug( 'Ignoring {}. This happens due to a timing issue among threads/processes/nodes. ' 'Another one might have committed a record with the same key(s).'.format(repr(e))) session.rollback() return False return True @staticmethod def _commit(session): # type: (orm.Session) -> None try: session.commit() except SQLAlchemyError as e: session.rollback() message = \ 'An exception is raised during the commit. ' \ 'This typically happens due to invalid data in the commit, ' \ 'e.g. exceeding max length. ' \ '(The actual exception is as follows: {})'.format(repr(e)) six.reraise(structs.StorageInternalError, structs.StorageInternalError(message), sys.exc_info()[2]) def remove_session(self): # type: () -> None """Removes the current session. A session is stored in SQLAlchemy's ThreadLocalRegistry for each thread. This method closes and removes the session which is associated to the current thread. Particularly, under multi-thread use cases, it is important to call this method *from each thread*. Otherwise, all sessions and their associated DB connections are destructed by a thread that occasionally invoked the garbage collector. By default, it is not allowed to touch a SQLite connection from threads other than the thread that created the connection. Therefore, we need to explicitly close the connection from each thread. """ self.scoped_session.remove() def __del__(self): # type: () -> None # This destructor calls remove_session to explicitly close the DB connection. We need this # because DB connections created in SQLAlchemy are not automatically closed by reference # counters, so it is not guaranteed that they are released by correct threads (for more # information, please see the docstring of remove_session). if hasattr(self, 'scoped_session'): self.remove_session() def upgrade(self): # type: () -> None """Upgrade the storage schema.""" self._version_manager.upgrade() def get_current_version(self): # type: () -> str """Return the schema version currently used by this storage.""" return self._version_manager.get_current_version() def get_head_version(self): # type: () -> str """Return the latest schema version.""" return self._version_manager.get_head_version() def get_all_versions(self): # type: () -> List[str] """Return the schema version list.""" return self._version_manager.get_all_versions() class _VersionManager(object): def __init__(self, url, engine, scoped_session): # type: (str, Engine, orm.scoped_session) -> None self.url = url self.engine = engine self.scoped_session = scoped_session self._init_version_info_model() self._init_alembic() def _init_version_info_model(self): # type: () -> None session = self.scoped_session() version_info = models.VersionInfoModel.find(session) if version_info is not None: return version_info = models.VersionInfoModel( schema_version=models.SCHEMA_VERSION, library_version=version.__version__) session.add(version_info) RDBStorage._commit_with_integrity_check(session) def _init_alembic(self): # type: () -> None logging.getLogger('alembic').setLevel(logging.WARN) context = alembic.migration.MigrationContext.configure(self.engine.connect()) is_initialized = context.get_current_revision() is not None if is_initialized: # The `alembic_version` table already exists and is not empty. return if self._is_alembic_supported(): revision = self.get_head_version() else: # The storage has been created before alembic is introduced. revision = self._get_base_version() self._set_alembic_revision(revision) def _set_alembic_revision(self, revision): # type: (str) -> None context = alembic.migration.MigrationContext.configure(self.engine.connect()) script = self._create_alembic_script() context.stamp(script, revision) def check_table_schema_compatibility(self): # type: () -> None session = self.scoped_session() # NOTE: After invocation of `_init_version_info_model` method, # it is ensured that a `VersionInfoModel` entry exists. version_info = models.VersionInfoModel.find(session) assert version_info is not None current_version = self.get_current_version() head_version = self.get_head_version() if current_version == head_version: return message = 'The runtime optuna version {} is no longer compatible with the table schema ' \ '(set up by optuna {}). '.format(version.__version__, version_info.library_version) known_versions = self.get_all_versions() if current_version in known_versions: message += 'Please execute `$ optuna storage upgrade --storage $STORAGE_URL` ' \ 'for upgrading the storage.' else: message += 'Please try updating optuna to the latest version by '\ '`$ pip install -U optuna`.' raise RuntimeError(message) def get_current_version(self): # type: () -> str context = alembic.migration.MigrationContext.configure(self.engine.connect()) version = context.get_current_revision() assert version is not None return version def get_head_version(self): # type: () -> str script = self._create_alembic_script() return script.get_current_head() def _get_base_version(self): # type: () -> str script = self._create_alembic_script() return script.get_base() def get_all_versions(self): # type: () -> List[str] script = self._create_alembic_script() return [r.revision for r in script.walk_revisions()] def upgrade(self): # type: () -> None config = self._create_alembic_config() alembic.command.upgrade(config, 'head') def _is_alembic_supported(self): # type: () -> bool session = self.scoped_session() version_info = models.VersionInfoModel.find(session) if version_info is None: # `None` means this storage was created just now. return True return version_info.schema_version == models.SCHEMA_VERSION def _create_alembic_script(self): # type: () -> alembic.script.ScriptDirectory config = self._create_alembic_config() script = alembic.script.ScriptDirectory.from_config(config) return script def _create_alembic_config(self): # type: () -> alembic.config.Config alembic_dir = os.path.join(os.path.dirname(__file__), 'alembic') config = alembic.config.Config(os.path.join(os.path.dirname(__file__), 'alembic.ini')) config.set_main_option('script_location', escape_alembic_config_value(alembic_dir)) config.set_main_option('sqlalchemy.url', escape_alembic_config_value(self.url)) return config class _FinishedTrialsCache(object): def __init__(self, enabled): # type: (bool) -> None self._finished_trials = {} # type: Dict[int, structs.FrozenTrial] self._enabled = enabled self._lock = threading.Lock() def is_empty(self): # type: () -> bool if not self._enabled: return True with self._lock: return len(self._finished_trials) == 0 def cache_trial_if_finished(self, trial): # type: (structs.FrozenTrial) -> None if not self._enabled: return if trial.state.is_finished(): with self._lock: self._finished_trials[trial.trial_id] = copy.deepcopy(trial) def get_cached_trial(self, trial_id): # type: (int) -> Optional[structs.FrozenTrial] if not self._enabled: return None with self._lock: return self._finished_trials.get(trial_id) def escape_alembic_config_value(value): # type: (str) -> str # We must escape '%' in a value string because the character # is regarded as the trigger of variable expansion. # Please see the documentation of `configparser.BasicInterpolation` for more details. return value.replace('%', '%%')
36.62306
99
0.647908
import alembic.command import alembic.config import alembic.migration import alembic.script from collections import defaultdict import copy from datetime import datetime import json import logging import os import six from sqlalchemy.engine import create_engine from sqlalchemy.engine import Engine from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import SQLAlchemyError from sqlalchemy import orm import sys import threading import uuid import optuna from optuna import distributions from optuna.storages.base import BaseStorage from optuna.storages.base import DEFAULT_STUDY_NAME_PREFIX from optuna.storages.rdb import models from optuna import structs from optuna import type_checking from optuna import version if type_checking.TYPE_CHECKING: from typing import Any from typing import Dict from typing import List from typing import Optional class RDBStorage(BaseStorage): def __init__(self, url, engine_kwargs=None, enable_cache=True, skip_compatibility_check=False): engine_kwargs = engine_kwargs or {} url = self._fill_storage_url_template(url) try: self.engine = create_engine(url, **engine_kwargs) except ImportError as e: raise ImportError('Failed to import DB access module for the specified storage URL. ' 'Please install appropriate one. (The actual import error is: ' + str(e) + '.)') self.scoped_session = orm.scoped_session(orm.sessionmaker(bind=self.engine)) models.BaseModel.metadata.create_all(self.engine) self.logger = optuna.logging.get_logger(__name__) self._version_manager = _VersionManager(url, self.engine, self.scoped_session) if not skip_compatibility_check: self._version_manager.check_table_schema_compatibility() self._finished_trials_cache = _FinishedTrialsCache(enable_cache) def create_new_study_id(self, study_name=None): session = self.scoped_session() if study_name is None: study_name = self._create_unique_study_name(session) study = models.StudyModel(study_name=study_name, direction=structs.StudyDirection.NOT_SET) session.add(study) if not self._commit_with_integrity_check(session): raise structs.DuplicatedStudyError( "Another study with name '{}' already exists. " "Please specify a different name, or reuse the existing one " "by setting `load_if_exists` (for Python API) or " "`--skip-if-exists` flag (for CLI).".format(study_name)) self.logger.info('A new study created with name: {}'.format(study.study_name)) return study.study_id @staticmethod def _create_unique_study_name(session): while True: study_uuid = str(uuid.uuid4()) study_name = DEFAULT_STUDY_NAME_PREFIX + study_uuid study = models.StudyModel.find_by_name(study_name, session) if study is None: break return study_name def set_study_direction(self, study_id, direction): session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) if study.direction != structs.StudyDirection.NOT_SET and study.direction != direction: raise ValueError('Cannot overwrite study direction from {} to {}.'.format( study.direction, direction)) study.direction = direction self._commit(session) def set_study_user_attr(self, study_id, key, value): session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) attribute = models.StudyUserAttributeModel.find_by_study_and_key(study, key, session) if attribute is None: attribute = models.StudyUserAttributeModel( study_id=study_id, key=key, value_json=json.dumps(value)) session.add(attribute) else: attribute.value_json = json.dumps(value) self._commit_with_integrity_check(session) def set_study_system_attr(self, study_id, key, value): session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) attribute = models.StudySystemAttributeModel.find_by_study_and_key(study, key, session) if attribute is None: attribute = models.StudySystemAttributeModel( study_id=study_id, key=key, value_json=json.dumps(value)) session.add(attribute) else: attribute.value_json = json.dumps(value) self._commit_with_integrity_check(session) def get_study_id_from_name(self, study_name): session = self.scoped_session() study = models.StudyModel.find_or_raise_by_name(study_name, session) return study.study_id def get_study_id_from_trial_id(self, trial_id): session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) return trial.study_id def get_study_name_from_id(self, study_id): session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) return study.study_name def get_study_direction(self, study_id): session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) return study.direction def get_study_user_attrs(self, study_id): session = self.scoped_session() attributes = models.StudyUserAttributeModel.where_study_id(study_id, session) return {attr.key: json.loads(attr.value_json) for attr in attributes} def get_study_system_attrs(self, study_id): session = self.scoped_session() attributes = models.StudySystemAttributeModel.where_study_id(study_id, session) return {attr.key: json.loads(attr.value_json) for attr in attributes} def get_trial_user_attrs(self, trial_id): session = self.scoped_session() attributes = models.TrialUserAttributeModel.where_trial_id(trial_id, session) return {attr.key: json.loads(attr.value_json) for attr in attributes} def get_trial_system_attrs(self, trial_id): session = self.scoped_session() attributes = models.TrialSystemAttributeModel.where_trial_id(trial_id, session) return {attr.key: json.loads(attr.value_json) for attr in attributes} def get_all_study_summaries(self): session = self.scoped_session() study_models = models.StudyModel.all(session) trial_models = models.TrialModel.all(session) param_models = models.TrialParamModel.all(session) value_models = models.TrialValueModel.all(session) trial_user_attribute_models = models.TrialUserAttributeModel.all(session) trial_system_attribute_models = models.TrialSystemAttributeModel.all(session) study_sumarries = [] for study_model in study_models: study_trial_models = [t for t in trial_models if t.study_id == study_model.study_id] completed_trial_models = [ t for t in study_trial_models if t.state is structs.TrialState.COMPLETE ] best_trial = None if len(completed_trial_models) > 0: if study_model.direction == structs.StudyDirection.MAXIMIZE: best_trial_model = max(completed_trial_models, key=lambda t: t.value) else: best_trial_model = min(completed_trial_models, key=lambda t: t.value) best_param_models = [ p for p in param_models if p.trial_id == best_trial_model.trial_id ] best_value_models = [ v for v in value_models if v.trial_id == best_trial_model.trial_id ] best_trial_user_models = [ u for u in trial_user_attribute_models if u.trial_id == best_trial_model.trial_id ] best_trial_system_models = [ s for s in trial_system_attribute_models if s.trial_id == best_trial_model.trial_id ] best_trial = self._merge_trials_orm([best_trial_model], best_param_models, best_value_models, best_trial_user_models, best_trial_system_models)[0] datetime_start = None if len(study_trial_models) > 0: datetime_start = min([t.datetime_start for t in study_trial_models]) attributes = models.StudySystemAttributeModel.where_study_id( study_model.study_id, session) system_attrs = {attr.key: json.loads(attr.value_json) for attr in attributes} study_sumarries.append( structs.StudySummary( study_id=study_model.study_id, study_name=study_model.study_name, direction=self.get_study_direction(study_model.study_id), best_trial=best_trial, user_attrs=self.get_study_user_attrs(study_model.study_id), system_attrs=system_attrs, n_trials=len(study_trial_models), datetime_start=datetime_start)) return study_sumarries def create_new_trial_id(self, study_id): session = self.scoped_session() trial = models.TrialModel(study_id=study_id, state=structs.TrialState.RUNNING) session.add(trial) self._commit(session) self._create_new_trial_number(trial.trial_id) return trial.trial_id def _create_new_trial_number(self, trial_id): session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) trial_number = trial.count_past_trials(session) self.set_trial_system_attr(trial.trial_id, '_number', trial_number) return trial_number def set_trial_state(self, trial_id, state): session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) trial.state = state if state.is_finished(): trial.datetime_complete = datetime.now() self._commit(session) def set_trial_param(self, trial_id, param_name, param_value_internal, distribution): session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) trial_param = \ models.TrialParamModel.find_by_trial_and_param_name(trial, param_name, session) if trial_param is not None: distributions.check_distribution_compatibility( distributions.json_to_distribution(trial_param.distribution_json), distribution) return False param = models.TrialParamModel( trial_id=trial_id, param_name=param_name, param_value=param_value_internal, distribution_json=distributions.distribution_to_json(distribution)) param.check_and_add(session) commit_success = self._commit_with_integrity_check(session) return commit_success def get_trial_param(self, trial_id, param_name): session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) trial_param = models.TrialParamModel.find_or_raise_by_trial_and_param_name( trial, param_name, session) return trial_param.param_value def set_trial_value(self, trial_id, value): session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) trial.value = value self._commit(session) def set_trial_intermediate_value(self, trial_id, step, intermediate_value): session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) trial_value = models.TrialValueModel.find_by_trial_and_step(trial, step, session) if trial_value is not None: return False trial_value = models.TrialValueModel( trial_id=trial_id, step=step, value=intermediate_value) session.add(trial_value) commit_success = self._commit_with_integrity_check(session) return commit_success def set_trial_user_attr(self, trial_id, key, value): session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) self.check_trial_is_updatable(trial_id, trial.state) attribute = models.TrialUserAttributeModel.find_by_trial_and_key(trial, key, session) if attribute is None: attribute = models.TrialUserAttributeModel( trial_id=trial_id, key=key, value_json=json.dumps(value)) session.add(attribute) else: attribute.value_json = json.dumps(value) self._commit_with_integrity_check(session) def set_trial_system_attr(self, trial_id, key, value): session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) if key == '_number': # In this case, `check_trial_is_updatable` is skipped to avoid the `RuntimeError`. # # TODO(ohta): Remove this workaround when `number` field is added to `TrialModel`. pass else: self.check_trial_is_updatable(trial_id, trial.state) attribute = models.TrialSystemAttributeModel.find_by_trial_and_key(trial, key, session) if attribute is None: attribute = models.TrialSystemAttributeModel( trial_id=trial_id, key=key, value_json=json.dumps(value)) session.add(attribute) else: attribute.value_json = json.dumps(value) self._commit_with_integrity_check(session) def get_trial_number_from_id(self, trial_id): # type: (int) -> int trial_number = self.get_trial_system_attrs(trial_id).get('_number') if trial_number is None: # If a study is created by optuna<=0.8.0, trial number is not found. # Create new one. return self._create_new_trial_number(trial_id) return trial_number def get_trial(self, trial_id): # type: (int) -> structs.FrozenTrial cached_trial = self._finished_trials_cache.get_cached_trial(trial_id) if cached_trial is not None: return copy.deepcopy(cached_trial) session = self.scoped_session() trial = models.TrialModel.find_or_raise_by_id(trial_id, session) params = models.TrialParamModel.where_trial(trial, session) values = models.TrialValueModel.where_trial(trial, session) user_attributes = models.TrialUserAttributeModel.where_trial(trial, session) system_attributes = models.TrialSystemAttributeModel.where_trial(trial, session) frozen_trial = self._merge_trials_orm([trial], params, values, user_attributes, system_attributes)[0] self._finished_trials_cache.cache_trial_if_finished(frozen_trial) return frozen_trial def get_all_trials(self, study_id): # type: (int) -> List[structs.FrozenTrial] if self._finished_trials_cache.is_empty(): trials = self._get_all_trials_without_cache(study_id) for trial in trials: self._finished_trials_cache.cache_trial_if_finished(trial) return trials trial_ids = self._get_all_trial_ids(study_id) trials = [self.get_trial(trial_id) for trial_id in trial_ids] return trials def _get_all_trial_ids(self, study_id): # type: (int) -> List[int] session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) return models.TrialModel.get_all_trial_ids_where_study(study, session) def _get_all_trials_without_cache(self, study_id): # type: (int) -> List[structs.FrozenTrial] session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) trials = models.TrialModel.where_study(study, session) params = models.TrialParamModel.where_study(study, session) values = models.TrialValueModel.where_study(study, session) user_attributes = models.TrialUserAttributeModel.where_study(study, session) system_attributes = models.TrialSystemAttributeModel.where_study(study, session) return self._merge_trials_orm(trials, params, values, user_attributes, system_attributes) def get_n_trials(self, study_id, state=None): # type: (int, Optional[structs.TrialState]) -> int session = self.scoped_session() study = models.StudyModel.find_or_raise_by_id(study_id, session) return models.TrialModel.count(session, study, state) def _merge_trials_orm( self, trials, # type: List[models.TrialModel] trial_params, # type: List[models.TrialParamModel] trial_intermediate_values, # type: List[models.TrialValueModel] trial_user_attrs, # type: List[models.TrialUserAttributeModel] trial_system_attrs # type: List[models.TrialSystemAttributeModel] ): # type: (...) -> List[structs.FrozenTrial] id_to_trial = {} for trial in trials: id_to_trial[trial.trial_id] = trial id_to_params = defaultdict(list) # type: Dict[int, List[models.TrialParamModel]] for param in trial_params: id_to_params[param.trial_id].append(param) id_to_values = defaultdict(list) # type: Dict[int, List[models.TrialValueModel]] for value in trial_intermediate_values: id_to_values[value.trial_id].append(value) id_to_user_attrs = \ defaultdict(list) # type: Dict[int, List[models.TrialUserAttributeModel]] for user_attr in trial_user_attrs: id_to_user_attrs[user_attr.trial_id].append(user_attr) id_to_system_attrs = \ defaultdict(list) # type: Dict[int, List[models.TrialSystemAttributeModel]] for system_attr in trial_system_attrs: id_to_system_attrs[system_attr.trial_id].append(system_attr) temp_trials = [] for trial_id, trial in id_to_trial.items(): params = {} param_distributions = {} for param in id_to_params[trial_id]: distribution = distributions.json_to_distribution(param.distribution_json) params[param.param_name] = distribution.to_external_repr(param.param_value) param_distributions[param.param_name] = distribution intermediate_values = {} for value in id_to_values[trial_id]: intermediate_values[value.step] = value.value user_attrs = {} for user_attr in id_to_user_attrs[trial_id]: user_attrs[user_attr.key] = json.loads(user_attr.value_json) system_attrs = {} for system_attr in id_to_system_attrs[trial_id]: system_attrs[system_attr.key] = json.loads(system_attr.value_json) # `-1` is a dummy value. # It will be replaced by a proper value before returned to the caller. # # TODO(ohta): Use trial.number after TrialModel.number is added. trial_number = -1 temp_trials.append( structs.FrozenTrial( number=trial_number, state=trial.state, params=params, distributions=param_distributions, user_attrs=user_attrs, system_attrs=system_attrs, value=trial.value, intermediate_values=intermediate_values, datetime_start=trial.datetime_start, datetime_complete=trial.datetime_complete, trial_id=trial_id)) result = [] for temp_trial in temp_trials: # [NOTE] # We set actual trial numbers here to avoid calling `self.get_trial_number_from_id()` # within the above loop. # # This is because `self.get_trial_number_from_id()` may call `session.commit()` # internally, which causes unintended changes of the states of `trials`. # (see https://github.com/pfnet/optuna/pull/349#issuecomment-475086642 for details) trial_number = self.get_trial_number_from_id(temp_trial.trial_id) result.append(temp_trial._replace(number=trial_number)) return result @staticmethod def _fill_storage_url_template(template): # type: (str) -> str return template.format(SCHEMA_VERSION=models.SCHEMA_VERSION) @staticmethod def _commit_with_integrity_check(session): # type: (orm.Session) -> bool try: session.commit() except IntegrityError as e: logger = optuna.logging.get_logger(__name__) logger.debug( 'Ignoring {}. This happens due to a timing issue among threads/processes/nodes. ' 'Another one might have committed a record with the same key(s).'.format(repr(e))) session.rollback() return False return True @staticmethod def _commit(session): # type: (orm.Session) -> None try: session.commit() except SQLAlchemyError as e: session.rollback() message = \ 'An exception is raised during the commit. ' \ 'This typically happens due to invalid data in the commit, ' \ 'e.g. exceeding max length. ' \ '(The actual exception is as follows: {})'.format(repr(e)) six.reraise(structs.StorageInternalError, structs.StorageInternalError(message), sys.exc_info()[2]) def remove_session(self): # type: () -> None self.scoped_session.remove() def __del__(self): # type: () -> None # This destructor calls remove_session to explicitly close the DB connection. We need this # because DB connections created in SQLAlchemy are not automatically closed by reference # counters, so it is not guaranteed that they are released by correct threads (for more # information, please see the docstring of remove_session). if hasattr(self, 'scoped_session'): self.remove_session() def upgrade(self): # type: () -> None self._version_manager.upgrade() def get_current_version(self): # type: () -> str return self._version_manager.get_current_version() def get_head_version(self): # type: () -> str return self._version_manager.get_head_version() def get_all_versions(self): # type: () -> List[str] return self._version_manager.get_all_versions() class _VersionManager(object): def __init__(self, url, engine, scoped_session): # type: (str, Engine, orm.scoped_session) -> None self.url = url self.engine = engine self.scoped_session = scoped_session self._init_version_info_model() self._init_alembic() def _init_version_info_model(self): # type: () -> None session = self.scoped_session() version_info = models.VersionInfoModel.find(session) if version_info is not None: return version_info = models.VersionInfoModel( schema_version=models.SCHEMA_VERSION, library_version=version.__version__) session.add(version_info) RDBStorage._commit_with_integrity_check(session) def _init_alembic(self): # type: () -> None logging.getLogger('alembic').setLevel(logging.WARN) context = alembic.migration.MigrationContext.configure(self.engine.connect()) is_initialized = context.get_current_revision() is not None if is_initialized: # The `alembic_version` table already exists and is not empty. return if self._is_alembic_supported(): revision = self.get_head_version() else: # The storage has been created before alembic is introduced. revision = self._get_base_version() self._set_alembic_revision(revision) def _set_alembic_revision(self, revision): # type: (str) -> None context = alembic.migration.MigrationContext.configure(self.engine.connect()) script = self._create_alembic_script() context.stamp(script, revision) def check_table_schema_compatibility(self): # type: () -> None session = self.scoped_session() # NOTE: After invocation of `_init_version_info_model` method, # it is ensured that a `VersionInfoModel` entry exists. version_info = models.VersionInfoModel.find(session) assert version_info is not None current_version = self.get_current_version() head_version = self.get_head_version() if current_version == head_version: return message = 'The runtime optuna version {} is no longer compatible with the table schema ' \ '(set up by optuna {}). '.format(version.__version__, version_info.library_version) known_versions = self.get_all_versions() if current_version in known_versions: message += 'Please execute `$ optuna storage upgrade --storage $STORAGE_URL` ' \ 'for upgrading the storage.' else: message += 'Please try updating optuna to the latest version by '\ '`$ pip install -U optuna`.' raise RuntimeError(message) def get_current_version(self): # type: () -> str context = alembic.migration.MigrationContext.configure(self.engine.connect()) version = context.get_current_revision() assert version is not None return version def get_head_version(self): # type: () -> str script = self._create_alembic_script() return script.get_current_head() def _get_base_version(self): # type: () -> str script = self._create_alembic_script() return script.get_base() def get_all_versions(self): # type: () -> List[str] script = self._create_alembic_script() return [r.revision for r in script.walk_revisions()] def upgrade(self): # type: () -> None config = self._create_alembic_config() alembic.command.upgrade(config, 'head') def _is_alembic_supported(self): # type: () -> bool session = self.scoped_session() version_info = models.VersionInfoModel.find(session) if version_info is None: # `None` means this storage was created just now. return True return version_info.schema_version == models.SCHEMA_VERSION def _create_alembic_script(self): # type: () -> alembic.script.ScriptDirectory config = self._create_alembic_config() script = alembic.script.ScriptDirectory.from_config(config) return script def _create_alembic_config(self): # type: () -> alembic.config.Config alembic_dir = os.path.join(os.path.dirname(__file__), 'alembic') config = alembic.config.Config(os.path.join(os.path.dirname(__file__), 'alembic.ini')) config.set_main_option('script_location', escape_alembic_config_value(alembic_dir)) config.set_main_option('sqlalchemy.url', escape_alembic_config_value(self.url)) return config class _FinishedTrialsCache(object): def __init__(self, enabled): # type: (bool) -> None self._finished_trials = {} # type: Dict[int, structs.FrozenTrial] self._enabled = enabled self._lock = threading.Lock() def is_empty(self): # type: () -> bool if not self._enabled: return True with self._lock: return len(self._finished_trials) == 0 def cache_trial_if_finished(self, trial): # type: (structs.FrozenTrial) -> None if not self._enabled: return if trial.state.is_finished(): with self._lock: self._finished_trials[trial.trial_id] = copy.deepcopy(trial) def get_cached_trial(self, trial_id): # type: (int) -> Optional[structs.FrozenTrial] if not self._enabled: return None with self._lock: return self._finished_trials.get(trial_id) def escape_alembic_config_value(value): # type: (str) -> str # We must escape '%' in a value string because the character # is regarded as the trigger of variable expansion. # Please see the documentation of `configparser.BasicInterpolation` for more details. return value.replace('%', '%%')
true
true
f72a3dab5f6feb060e408b3588fb869452950336
1,352
py
Python
src/main.py
dex73r/ghdown
b1e72b95e10d8d7d2d41cb4e8558cb29c018ac81
[ "MIT" ]
null
null
null
src/main.py
dex73r/ghdown
b1e72b95e10d8d7d2d41cb4e8558cb29c018ac81
[ "MIT" ]
null
null
null
src/main.py
dex73r/ghdown
b1e72b95e10d8d7d2d41cb4e8558cb29c018ac81
[ "MIT" ]
null
null
null
import argparse import os import requests from git import Repo def main(): parser = argparse.ArgumentParser(description="A tool to clone github only repositories of user or group") parser.add_argument("--u", help="target of massive download", dest='target', required=True) parser.add_argument("--o", help="Directory to save repos at", dest='out', required=False) args = parser.parse_args() target = args.target if not target: print("ERROR: You need to specify target, ex: gitdown -u dex73r") return 1 output = args.out if not output: output = target pageNumber = 1 while (pageNumber > 0): url = ("https://api.github.com/users/%s/repos?page=%i&per_page=100" % (target, pageNumber)) j = requests.get(url).json() pageCount = len(j) if (pageCount < 1): pageNumber = -1 for el in j: print(el["git_url"]) gitlink = el["git_url"] out_name = os.path.join(output, el["name"]) if os.path.isdir(out_name): repo = Repo(out_name) repo.remotes.origin.pull() else: Repo.clone_from(gitlink, out_name) pageNumber = pageNumber + 1 return 1337 if __name__ == "__main__": main()
30.727273
109
0.572485
import argparse import os import requests from git import Repo def main(): parser = argparse.ArgumentParser(description="A tool to clone github only repositories of user or group") parser.add_argument("--u", help="target of massive download", dest='target', required=True) parser.add_argument("--o", help="Directory to save repos at", dest='out', required=False) args = parser.parse_args() target = args.target if not target: print("ERROR: You need to specify target, ex: gitdown -u dex73r") return 1 output = args.out if not output: output = target pageNumber = 1 while (pageNumber > 0): url = ("https://api.github.com/users/%s/repos?page=%i&per_page=100" % (target, pageNumber)) j = requests.get(url).json() pageCount = len(j) if (pageCount < 1): pageNumber = -1 for el in j: print(el["git_url"]) gitlink = el["git_url"] out_name = os.path.join(output, el["name"]) if os.path.isdir(out_name): repo = Repo(out_name) repo.remotes.origin.pull() else: Repo.clone_from(gitlink, out_name) pageNumber = pageNumber + 1 return 1337 if __name__ == "__main__": main()
true
true
f72a3ef23ff298d116c3a38c8d217d46311ba4f3
789
py
Python
socialcops/api/config.py
yutiansut/Long-Running-Jobs-Manager
ed12bebb7872b95e1f65548be4a00715f2ad47a6
[ "MIT" ]
1
2019-09-15T19:52:10.000Z
2019-09-15T19:52:10.000Z
socialcops/api/config.py
yutiansut/Long-Running-Jobs-Manager
ed12bebb7872b95e1f65548be4a00715f2ad47a6
[ "MIT" ]
null
null
null
socialcops/api/config.py
yutiansut/Long-Running-Jobs-Manager
ed12bebb7872b95e1f65548be4a00715f2ad47a6
[ "MIT" ]
1
2019-09-15T19:53:04.000Z
2019-09-15T19:53:04.000Z
import os basedir = os.path.abspath(os.path.dirname(__file__)) # Keeping track of various configurations of the Flask app class Config(object): ALLOWED_EXTENSIONS = set(['csv']) UPLOAD_FOLDER = './files/uploads/' DOWNLOAD_FOLDER = './files/downloads/' SECRET_KEY = os.environ.get('SECRET_KEY') or \ 'uUHQMFSPB9H7G4bGwzFLDetrIyb4M8tj' SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'app.db') SQLALCHEMY_TRACK_MODIFICATIONS = False REDIS_URL = os.environ.get('REDIS_URL') or 'redis://' CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL') or \ 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND') or \ 'redis://localhost:6379/0'
41.526316
72
0.695817
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): ALLOWED_EXTENSIONS = set(['csv']) UPLOAD_FOLDER = './files/uploads/' DOWNLOAD_FOLDER = './files/downloads/' SECRET_KEY = os.environ.get('SECRET_KEY') or \ 'uUHQMFSPB9H7G4bGwzFLDetrIyb4M8tj' SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'app.db') SQLALCHEMY_TRACK_MODIFICATIONS = False REDIS_URL = os.environ.get('REDIS_URL') or 'redis://' CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL') or \ 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND') or \ 'redis://localhost:6379/0'
true
true
f72a41c562cc666e7693a5618222e1ff98c66a18
1,240
py
Python
Configuration/Generator/python/QCD_Pt_3000_3500_14TeV_TuneCUETP8M1_cfi.py
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Configuration/Generator/python/QCD_Pt_3000_3500_14TeV_TuneCUETP8M1_cfi.py
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Configuration/Generator/python/QCD_Pt_3000_3500_14TeV_TuneCUETP8M1_cfi.py
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
import FWCore.ParameterSet.Config as cms from Configuration.Generator.Pythia8CommonSettings_cfi import * from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import * generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter", pythiaHepMCVerbosity = cms.untracked.bool(False), maxEventsToPrint = cms.untracked.int32(0), pythiaPylistVerbosity = cms.untracked.int32(1), filterEfficiency = cms.untracked.double(0.037), crossSection = cms.untracked.double(74310000.), comEnergy = cms.double(14000.0), # center of mass energy in GeV PythiaParameters = cms.PSet( pythia8CommonSettingsBlock, pythia8CUEP8M1SettingsBlock, processParameters = cms.vstring( 'HardQCD:all = on', 'PhaseSpace:pTHatMin = 3000.', 'PhaseSpace:pTHatMax = 3500.' ), parameterSets = cms.vstring('pythia8CommonSettings', 'pythia8CUEP8M1Settings', 'processParameters', ) ) )
45.925926
89
0.549194
import FWCore.ParameterSet.Config as cms from Configuration.Generator.Pythia8CommonSettings_cfi import * from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import * generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter", pythiaHepMCVerbosity = cms.untracked.bool(False), maxEventsToPrint = cms.untracked.int32(0), pythiaPylistVerbosity = cms.untracked.int32(1), filterEfficiency = cms.untracked.double(0.037), crossSection = cms.untracked.double(74310000.), comEnergy = cms.double(14000.0), PythiaParameters = cms.PSet( pythia8CommonSettingsBlock, pythia8CUEP8M1SettingsBlock, processParameters = cms.vstring( 'HardQCD:all = on', 'PhaseSpace:pTHatMin = 3000.', 'PhaseSpace:pTHatMax = 3500.' ), parameterSets = cms.vstring('pythia8CommonSettings', 'pythia8CUEP8M1Settings', 'processParameters', ) ) )
true
true
f72a42c2e1e5a77f302472332be6e9a10fe5c67c
15,891
py
Python
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/operations/custom_image_operations.py
CharaD7/azure-sdk-for-python
9fdf0aac0cec8a15a5bb2a0ea27dd331dbfa2f5c
[ "MIT" ]
null
null
null
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/operations/custom_image_operations.py
CharaD7/azure-sdk-for-python
9fdf0aac0cec8a15a5bb2a0ea27dd331dbfa2f5c
[ "MIT" ]
null
null
null
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/operations/custom_image_operations.py
CharaD7/azure-sdk-for-python
9fdf0aac0cec8a15a5bb2a0ea27dd331dbfa2f5c
[ "MIT" ]
null
null
null
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrestazure.azure_operation import AzureOperationPoller import uuid from .. import models class CustomImageOperations(object): """CustomImageOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. """ def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.config = config def list( self, resource_group_name, lab_name, filter=None, top=None, order_by=None, custom_headers=None, raw=False, **operation_config): """List custom images in a given lab. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param lab_name: The name of the lab. :type lab_name: str :param filter: The filter to apply on the operation. :type filter: str :param top: The maximum number of resources to return from the operation. :type top: int :param order_by: The ordering expression for the results, using OData notation. :type order_by: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`CustomImagePaged <azure.mgmt.devtestlabs.models.CustomImagePaged>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') if top is not None: query_parameters['$top'] = self._serialize.query("top", top, 'int') if order_by is not None: query_parameters['$orderBy'] = self._serialize.query("order_by", order_by, 'str') query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.CustomImagePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.CustomImagePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def get_resource( self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config): """Get custom image. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param lab_name: The name of the lab. :type lab_name: str :param name: The name of the custom image. :type name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`CustomImage <azure.mgmt.devtestlabs.models.CustomImage>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('CustomImage', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update_resource( self, resource_group_name, lab_name, name, custom_image, custom_headers=None, raw=False, **operation_config): """Create or replace an existing custom image. This operation can take a while to complete. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param lab_name: The name of the lab. :type lab_name: str :param name: The name of the custom image. :type name: str :param custom_image: :type custom_image: :class:`CustomImage <azure.mgmt.devtestlabs.models.CustomImage>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`CustomImage <azure.mgmt.devtestlabs.models.CustomImage>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(custom_image, 'CustomImage') # Construct and send request def long_running_send(): request = self._client.put(url, query_parameters) return self._client.send( request, header_parameters, body_content, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('CustomImage', response) if response.status_code == 201: deserialized = self._deserialize('CustomImage', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def delete_resource( self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config): """Delete custom image. This operation can take a while to complete. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param lab_name: The name of the lab. :type lab_name: str :param name: The name of the custom image. :type name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns None :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request def long_running_send(): request = self._client.delete(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout)
44.388268
149
0.646655
from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrestazure.azure_operation import AzureOperationPoller import uuid from .. import models class CustomImageOperations(object): def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.config = config def list( self, resource_group_name, lab_name, filter=None, top=None, order_by=None, custom_headers=None, raw=False, **operation_config): def internal_paging(next_link=None, raw=False): if not next_link: url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') if top is not None: query_parameters['$top'] = self._serialize.query("top", top, 'int') if order_by is not None: query_parameters['$orderBy'] = self._serialize.query("order_by", order_by, 'str') query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') else: url = next_link query_parameters = {} header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response deserialized = models.CustomImagePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.CustomImagePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def get_resource( self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('CustomImage', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update_resource( self, resource_group_name, lab_name, name, custom_image, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') body_content = self._serialize.body(custom_image, 'CustomImage') def long_running_send(): request = self._client.put(url, query_parameters) return self._client.send( request, header_parameters, body_content, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('CustomImage', response) if response.status_code == 201: deserialized = self._deserialize('CustomImage', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def delete_resource( self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') def long_running_send(): request = self._client.delete(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout)
true
true
f72a42f0de9fa77c288318b1b5d013ccfb8f3bf4
771
py
Python
setup.py
littleq0903/django-gcloud-storage
52e4a4a6773a5e79cf3fec19dcc1290e65942a70
[ "MIT" ]
3
2015-01-08T09:13:12.000Z
2020-11-27T16:23:09.000Z
setup.py
littleq0903/django-gcloud-storage
52e4a4a6773a5e79cf3fec19dcc1290e65942a70
[ "MIT" ]
1
2015-02-25T05:03:02.000Z
2019-02-08T07:00:35.000Z
setup.py
littleq0903/django-gcloud-storage
52e4a4a6773a5e79cf3fec19dcc1290e65942a70
[ "MIT" ]
1
2015-02-25T03:55:54.000Z
2015-02-25T03:55:54.000Z
from setuptools import setup, find_packages import django_gcs setup_options = { 'name': 'django-gcloud-storage', 'version': django_gcs.__version__, 'packages': find_packages(), 'author': 'Colin Su', 'author_email': 'littleq0903@gmail.com', 'license': 'MIT', 'description': open('./README.md').read(), 'url': 'https://github.com/littleq0903/django-gcloud-storage', 'classifiers': [ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] } setup(**setup_options)
28.555556
70
0.574578
from setuptools import setup, find_packages import django_gcs setup_options = { 'name': 'django-gcloud-storage', 'version': django_gcs.__version__, 'packages': find_packages(), 'author': 'Colin Su', 'author_email': 'littleq0903@gmail.com', 'license': 'MIT', 'description': open('./README.md').read(), 'url': 'https://github.com/littleq0903/django-gcloud-storage', 'classifiers': [ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] } setup(**setup_options)
true
true
f72a43f375f75914487974a4a07a4ec77f462c62
1,509
py
Python
src/word_processing.py
bsbhaskar/product_review_sentiments
46de372f4d410f44e487c92b9279cf13c33d4cd1
[ "MIT" ]
2
2018-06-07T21:55:33.000Z
2018-09-15T08:33:53.000Z
src/word_processing.py
bsbhaskar/product_review_sentiments
46de372f4d410f44e487c92b9279cf13c33d4cd1
[ "MIT" ]
null
null
null
src/word_processing.py
bsbhaskar/product_review_sentiments
46de372f4d410f44e487c92b9279cf13c33d4cd1
[ "MIT" ]
null
null
null
import string import spacy import pickle from nltk.stem.wordnet import WordNetLemmatizer from gensim.models import Phrases, Word2Vec from nltk.corpus import stopwords import warnings warnings.filterwarnings("ignore") class WordProcessor(): ''' This is a utility class that loads data related to processing words. ''' def __init__(self): ''' Initialize loading of keywords and vocab and custom keywords. In the future, the custom keywords will be moved to a file. ''' self.nlp = spacy.load("en") self.stop_words = set(stopwords.words('english')) custom_stop_words = set(['is','have','was','has','been','','samsung','one','amazon','sony','star','stars','middle','black','use','white','dont','night','room','way','purchased','vanns','think','got','thought','way','set','nice','son','half','line','tv','picture','screen','work','hour','day','week','month','time','work','days','months','weeks','pron']) self.stop_words = self.stop_words.union(custom_stop_words) self.punctuation = set(string.punctuation) self.lemmatize = WordNetLemmatizer() def clean_document(self, doc): ''' returns list of words from a document post word_processing ''' words = [] for word in doc.lower().split(): if ((word not in self.stop_words) and (word not in self.punctuation) and (len(word) > 1)): words.append(self.lemmatize.lemmatize(word)) return words
41.916667
361
0.640822
import string import spacy import pickle from nltk.stem.wordnet import WordNetLemmatizer from gensim.models import Phrases, Word2Vec from nltk.corpus import stopwords import warnings warnings.filterwarnings("ignore") class WordProcessor(): def __init__(self): self.nlp = spacy.load("en") self.stop_words = set(stopwords.words('english')) custom_stop_words = set(['is','have','was','has','been','','samsung','one','amazon','sony','star','stars','middle','black','use','white','dont','night','room','way','purchased','vanns','think','got','thought','way','set','nice','son','half','line','tv','picture','screen','work','hour','day','week','month','time','work','days','months','weeks','pron']) self.stop_words = self.stop_words.union(custom_stop_words) self.punctuation = set(string.punctuation) self.lemmatize = WordNetLemmatizer() def clean_document(self, doc): words = [] for word in doc.lower().split(): if ((word not in self.stop_words) and (word not in self.punctuation) and (len(word) > 1)): words.append(self.lemmatize.lemmatize(word)) return words
true
true
f72a44144e09def7c3fe812e31e7c8bfecf516d8
1,536
py
Python
auth0login/auth0backend.py
chop-dbhi/biorepo-portal
7db13c40b2b9d62af43a28e4af08c2472b98fc96
[ "BSD-2-Clause" ]
6
2016-10-26T19:51:11.000Z
2021-03-18T16:05:55.000Z
auth0login/auth0backend.py
chop-dbhi/biorepo-portal
7db13c40b2b9d62af43a28e4af08c2472b98fc96
[ "BSD-2-Clause" ]
207
2015-09-24T17:41:37.000Z
2021-05-18T18:14:08.000Z
auth0login/auth0backend.py
chop-dbhi/biorepo-portal
7db13c40b2b9d62af43a28e4af08c2472b98fc96
[ "BSD-2-Clause" ]
8
2016-04-27T19:04:50.000Z
2020-08-24T02:33:05.000Z
# auth0login/auth0backend.py from urllib import request from jose import jwt from social_core.backends.oauth import BaseOAuth2 from accounts.models import UserProfile class Auth0(BaseOAuth2): """Auth0 OAuth authentication backend""" name = 'auth0' SCOPE_SEPARATOR = ' ' ACCESS_TOKEN_METHOD = 'POST' REDIRECT_STATE = False EXTRA_DATA = [ ('picture', 'picture'), ('email', 'email') ] def authorization_url(self): return 'https://' + self.setting('DOMAIN') + '/authorize' def access_token_url(self): return 'https://' + self.setting('DOMAIN') + '/oauth/token' def get_user_id(self, details, response): """Return current user id.""" print("is this using user ID?") print("user id: {}".format(details['user_id'])) return details['user_id'] def get_user_details(self, response): # Obtain JWT and the keys to validate the signature id_token = response.get('id_token') jwks = request.urlopen('https://' + self.setting('DOMAIN') + '/.well-known/jwks.json') issuer = 'https://' + self.setting('DOMAIN') + '/' audience = self.setting('KEY') # CLIENT_ID payload = jwt.decode(id_token, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer) return {'username': payload['nickname'], 'first_name': payload['name'], 'picture': payload['picture'], 'user_id': payload['sub'], 'email': payload['email']}
34.133333
107
0.609375
from urllib import request from jose import jwt from social_core.backends.oauth import BaseOAuth2 from accounts.models import UserProfile class Auth0(BaseOAuth2): name = 'auth0' SCOPE_SEPARATOR = ' ' ACCESS_TOKEN_METHOD = 'POST' REDIRECT_STATE = False EXTRA_DATA = [ ('picture', 'picture'), ('email', 'email') ] def authorization_url(self): return 'https://' + self.setting('DOMAIN') + '/authorize' def access_token_url(self): return 'https://' + self.setting('DOMAIN') + '/oauth/token' def get_user_id(self, details, response): print("is this using user ID?") print("user id: {}".format(details['user_id'])) return details['user_id'] def get_user_details(self, response): id_token = response.get('id_token') jwks = request.urlopen('https://' + self.setting('DOMAIN') + '/.well-known/jwks.json') issuer = 'https://' + self.setting('DOMAIN') + '/' audience = self.setting('KEY') payload = jwt.decode(id_token, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer) return {'username': payload['nickname'], 'first_name': payload['name'], 'picture': payload['picture'], 'user_id': payload['sub'], 'email': payload['email']}
true
true
f72a441d3477b4777d617b49034762570f7ca082
15,410
py
Python
pydevices/MitDevices/picam.py
consorzio-rfx/mdsplus
81cdbfc759d92b101d84328e6eb7b3a6e6e22103
[ "BSD-2-Clause" ]
null
null
null
pydevices/MitDevices/picam.py
consorzio-rfx/mdsplus
81cdbfc759d92b101d84328e6eb7b3a6e6e22103
[ "BSD-2-Clause" ]
null
null
null
pydevices/MitDevices/picam.py
consorzio-rfx/mdsplus
81cdbfc759d92b101d84328e6eb7b3a6e6e22103
[ "BSD-2-Clause" ]
null
null
null
# # Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. # # 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. # # 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 HOLDER 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. # import MDSplus import ctypes def pointer(x): """Returns a ctypes pointer""" ptr = ctypes.pointer(x) return ptr def kill(proc_pid): import psutil process = psutil.Process(proc_pid) print "Process is ", process for proc in process.children(recursive=True): proc.kill() process.kill() class PICAM(MDSplus.Device): """ Device class to support Princeton Instruments cameras with the PiCam library. methods: init store """ parts = [ {'path':':COMMENT','type':'text'}, {'path':':SERIAL_NO','type':'text','options':('no_write_shot',)}, {'path':':EXPOSURE','type':'numeric','value':1,'options':('no_write_shot',)}, {'path':':NUM_FRAMES','type':'numeric','value':30,'options':('no_write_shot',)}, {'path':':ROIS','type':'numeric','options':('no_write_shot',)}, {'path':':TIMEOUT','type':'numeric','value':100000,'options':('no_write_shot',)}, {'path':':TRG_RESPONSE','type':'text', 'value':'StartOnSingleTrigger', 'options':('no_write_shot',)}, {'path':':MODEL','type':'text','options':('no_write_model','write_once',)}, {'path':':SENSOR','type':'text','options':('no_write_model','write_once',)}, {'path':':LIB_VERSION','type':'text','options':('no_write_model','write_once',)}, {'path':':SENSOR_TEMP','type':'numeric','options':('no_write_model','write_once',)}, {'path':':READOUT_TIME','type':'numeric','options':('no_write_model','write_once',)}, {'path':':FRAMES','type':'numeric','options':('no_write_model','write_once',)}, {'path':':INIT_ACTION','type':'action', 'valueExpr':"Action(Dispatch('CAMAC_SERVER','INIT',50,None),Method(None,'INIT',head))", 'options':('no_write_shot',)}] cameras = [] class camera_proc(): def __init__(self, camera): self.camera = camera self.subproc = None def init(self): """ Init method for the raspberry pi camera device. Start by deleting any running subrocesses that may be left over from previous inits, note the subprocess is stored in a class variable (ONLY one of these per server !) Read all of the settings and create a script to take the data. Note: This device supports at most 1 camera per server. Which is OK since the raspberry pis only have one camera port. """ import os import subprocess self.debugging = os.getenv('DEBUG_DEVICES') camera = str(self.serial_no.record) c_rec = None for c in PICAM.cameras: if c.camera == camera : try: if self.debugging: print "PICAM killing ", c.subproc, c.subproc.pid kill(c.subproc.pid) except Exception, e: if self.debugging: print "PICAM kill exception", e pass c_rec = c if c_rec is None: c = PICAM.camera_proc(camera) PICAM.cameras.append(c) if not c.camera == camera: c = PICAM.camera_proc(camera) PICAM.cameras.append(c) tree = self.local_tree shot = self.tree.shot path = self.local_path c.subproc = subprocess.Popen('mdstcl 2>&1', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) c.subproc.stdin.write('set tree %s /shot = %d\n'%(tree, shot,)) c.subproc.stdin.write('do/meth %s acquire\n'%(path,)) c.subproc.stdin.write('exit\n') c.subproc.stdin.flush() return 1 INIT=init def acquire(self): import os import ctypes as ctypes import numpy as np from MDSplus.mdsExceptions import DevCOMM_ERROR from MDSplus.mdsExceptions import DevBAD_PARAMETER from MDSplus.mdsExceptions import DevPY_INTERFACE_LIBRARY_NOT_FOUND try: import PythonForPicam as pfp except: raise DevPY_INTERFACE_LIBRARY_NOT_FOUND("Picam error importing PythonForPicam") self.debugging = os.getenv('DEBUG_DEVICES') exposure = float(self.exposure) exposure = pfp.piflt(exposure) num_frames = int(self.num_frames) timeout = int(self.timeout) serial_no = str(self.serial_no.record) try: if self.debugging: print "PICAM about to try to read the ROIS" rois = self.rois.data() if self.debugging: print "PICAM got the rois ", rois except Exception,e: if self.debugging: print "PICAM could not read the ROIS" rois = None print "Acquire - debugging is ", self.debugging # initialize the library pfp.Picam_InitializeLibrary() # get library version information major = pfp.piint() minor = pfp.piint() distribution = pfp.piint() release = pfp.piint() pfp.Picam_GetVersion(pointer(major),pointer(minor),pointer(distribution),pointer(release)) self.lib_version.record = 'Picam Version %d.%d.%d Released %d' % (major.value,minor.value,distribution.value,release.value,) available = ctypes.POINTER(ctypes.c_int)() availableCount = pfp.piint(); status = pfp.Picam_GetAvailableCameraIDs(ctypes.byref(available), ctypes.byref(availableCount)) camera = pfp.PicamHandle() cameras_type = pfp.PicamCameraID*availableCount.value cameras_pointer = ctypes.POINTER(cameras_type) cameras = ctypes.cast(available, cameras_pointer) found = False for c in cameras.contents: if self.debugging: print "checking ",c.serial_number if c.serial_number == serial_no: status = pfp.Picam_OpenCamera(pointer(c),ctypes.addressof(camera)) if not status == "PicamError_None": raise DevCOMM_ERROR("PiCam - could not open camera serial no %d - %s"% (serial_no,status,)) found = True if not found: raise DevBAD_PARAMETER("PiCam - Could not find camera %d"%serial_no) # Picam_OpenCamera(ctypes.addressof(camera)) PicamID = pfp.PicamCameraID() pfp.Picam_GetCameraID(camera, pointer(PicamID)) self.model.record = str(PicamID.model) self.sensor.record = str(PicamID.sensor_name) trigger_response = str(self.trg_response.record) if trigger_response == 'NoResponse': trigger_resp = pfp.PicamTriggerResponse_NoResponse elif trigger_response == 'ReadoutPerTrigger': trigger_resp = pfp.PicamTriggerResponse_ReadoutPerTrigger elif trigger_response == 'ShiftPerTrigger': trigger_resp = pfp.PicamTriggerResponse_ShiftPerTrigger elif trigger_response == 'ExposeDuringTriggerPulse': trigger_resp = pfp.PicamTriggerResponse_ExposeDuringTriggerPulse elif trigger_response == 'StartOnSingleTrigger': trigger_resp = pfp.PicamTriggerResponse_StartOnSingleTrigger else: raise DevBAD_PARAMETER("PiCam - TRG_RESPONSE must be one of ('NoResponse','ReadoutPerTrigger','ShiftPerTrigger','ExposeDuringTriggerPulse', 'StartOnSingleTrigger')") if self.debugging: print "Picam_SetParameterIntegerValue(camera, PicamParameter_TriggerResponse,",trigger_resp,")" pfp.Picam_SetParameterIntegerValue( camera, pfp.PicamParameter_TriggerResponse, trigger_resp ) pfp.Picam_SetParameterIntegerValue( camera, pfp.PicamParameter_TriggerDetermination, pfp.PicamTriggerDetermination_PositivePolarity ) pfp.Picam_SetParameterIntegerValue( camera, pfp.PicamParameter_OutputSignal, pfp.PicamOutputSignal_Exposing ) # set the exposure if self.debugging: print "Picam_SetParameterFloatingPointValue( camera, PicamParameter_ExposureTime, ",exposure,")" pfp.Picam_SetParameterFloatingPointValue( camera, pfp.PicamParameter_ExposureTime, exposure ) failCount = pfp.piint() paramsFailed = pfp.piint() if self.debugging: print "Picam_CommitParameters(camera, pointer(paramsFailed), ctypes.byref(failCount))" pfp.Picam_CommitParameters(camera, pointer(paramsFailed), ctypes.byref(failCount)) if self.debugging: print "failcount is ", failCount pfp.Picam_DestroyParameters(pointer(paramsFailed)) width = pfp.piint(0) pfp.Picam_GetParameterIntegerValue( camera, ctypes.c_int(pfp.PicamParameter_SensorActiveWidth), ctypes.byref(width) ); width = width.value # if there are rois set the rois if rois is not None: if self.debugging: print "PICAM have rois" shape = rois.shape if shape[1] == 6 : if self.debugging: print "PICAM it is nx6" Rois = pfp.PicamRois(shape[0]) for i in range(shape[0]): Rois.roi_array[i].x = rois[i,0] Rois.roi_array[i].width = rois[i,1] Rois.roi_array[i].x_binning = rois[i,2] Rois.roi_array[i].y = rois[i,3] Rois.roi_array[i].height = rois[i,4] Rois.roi_array[i].y_binning = rois[i,5] width = rois[i,1] if self.debugging: print "PICAM The Rois are: ", Rois status = pfp.Picam_SetParameterRoisValue(camera, pfp.PicamParameter_Rois, pointer(Rois)) if not status == "PicamError_None": raise DevCOMM_ERROR("PiCam - error setting ROI- %s"% status) failCount = pfp.piint() paramsFailed = pfp.piint() status = pfp.Picam_CommitParameters(camera, pointer(paramsFailed), ctypes.byref(failCount)) if not status == "PicamError_None": raise DevCOMM_ERROR("PiCam - error committing ROI Parameter Change %s" % status) if not failCount.value == 0: raise DevCOMM_ERROR("PiCam - ROI commit failure count > 0", failCount) pfp.Picam_DestroyParameters(pointer(paramsFailed)) else: raise DevBAD_PARAMETER("PiCAM Rois must be 6xN array") errors = pfp.PicamAcquisitionErrorsMask() readout_count = pfp.pi64s(num_frames) readout_time_out = pfp.piint(-1) available = pfp.PicamAvailableData(0, 0) if self.debugging: print "about to call Picam_Acquire" status = pfp.Picam_Acquire(camera, readout_count, readout_time_out, ctypes.byref(available), ctypes.byref(errors)) if not status == "PicamError_None": print "Picam_Acquire returned ",status raise DevCOMM_ERROR("PiCam - non zero return from Picam_Acquire - %s" % status) if self.debugging: print "back from aquire" temperature = pfp.piflt(0.0) status = pfp.Picam_GetParameterFloatingPointValue( camera, ctypes.c_int(pfp.PicamParameter_SensorTemperatureReading), ctypes.byref(temperature) ) if status == "PicamError_None" : self.sensor_temp.record = temperature.value if self.debugging : print "PICAM read back sensor temperature ", temperature else: print "PICAM could not read back sensor temperature ", status readout_time = pfp.piflt(0.0) status = pfp.Picam_GetParameterFloatingPointValue( camera, ctypes.c_int(pfp.PicamParameter_ReadoutTimeCalculation), ctypes.byref(readout_time) ) if status == "PicamError_None" : self.readout_time.record = readout_time.value if self.debugging : print "PICAM read back ReadoutTimeCalculation ", readout_time else: print "PICAM could not read back readout time ", status readoutstride = pfp.piint(0) status = pfp.Picam_GetParameterIntegerValue( camera, ctypes.c_int(pfp.PicamParameter_ReadoutStride), ctypes.byref(readoutstride) ) if self.debugging: print "Picam_GetParameterIntegerValue( camera, ctypes.c_int(PicamParameter_ReadoutStride),",readoutstride," )", status if not status == "PicamError_None" : raise DevCOMM_ERROR("PiCam - could not read readout stride - %s"% status) sz = readout_count.value*readoutstride.value/2 if self.debugging: print "sz is ",sz, " num_frames is ", num_frames, "readout_count is ", readout_count, " readoutstride is ", readoutstride DataArrayType = pfp.pi16u*sz """ Create pointer type for the above array type """ DataArrayPointerType = ctypes.POINTER(pfp.pi16u*sz) if self.debugging: print "PICAM - cast the read data into the pointer type" """ Create an instance of the pointer type, and point it to initial readout contents (memory address?) """ DataPointer = ctypes.cast(available.initial_readout,DataArrayPointerType) if self.debugging: print "PICAM now deference the pointer" """ Create a separate array with readout contents """ data = DataPointer.contents if self.debugging: print "PICAM - now make an np.empty of shorts (%d)"%sz ans = np.empty(sz,np.short) if self.debugging: print "PICAM - fill it in " ans[:] = data if self.debugging: print "PICAM reshape the data to be (%d, %d, %d)"%(num_frames, readoutstride.value/2/width, width) ans = ans.reshape((num_frames, readoutstride.value/2/width, width)) self.frames.record = ans if self.debugging: print "un initialize the library" pfp.Picam_UninitializeLibrary() return 1 ACQUIRE=acquire
44.028571
177
0.635237
import MDSplus import ctypes def pointer(x): """Returns a ctypes pointer""" ptr = ctypes.pointer(x) return ptr def kill(proc_pid): import psutil process = psutil.Process(proc_pid) print "Process is ", process for proc in process.children(recursive=True): proc.kill() process.kill() class PICAM(MDSplus.Device): """ Device class to support Princeton Instruments cameras with the PiCam library. methods: init store """ parts = [ {'path':':COMMENT','type':'text'}, {'path':':SERIAL_NO','type':'text','options':('no_write_shot',)}, {'path':':EXPOSURE','type':'numeric','value':1,'options':('no_write_shot',)}, {'path':':NUM_FRAMES','type':'numeric','value':30,'options':('no_write_shot',)}, {'path':':ROIS','type':'numeric','options':('no_write_shot',)}, {'path':':TIMEOUT','type':'numeric','value':100000,'options':('no_write_shot',)}, {'path':':TRG_RESPONSE','type':'text', 'value':'StartOnSingleTrigger', 'options':('no_write_shot',)}, {'path':':MODEL','type':'text','options':('no_write_model','write_once',)}, {'path':':SENSOR','type':'text','options':('no_write_model','write_once',)}, {'path':':LIB_VERSION','type':'text','options':('no_write_model','write_once',)}, {'path':':SENSOR_TEMP','type':'numeric','options':('no_write_model','write_once',)}, {'path':':READOUT_TIME','type':'numeric','options':('no_write_model','write_once',)}, {'path':':FRAMES','type':'numeric','options':('no_write_model','write_once',)}, {'path':':INIT_ACTION','type':'action', 'valueExpr':"Action(Dispatch('CAMAC_SERVER','INIT',50,None),Method(None,'INIT',head))", 'options':('no_write_shot',)}] cameras = [] class camera_proc(): def __init__(self, camera): self.camera = camera self.subproc = None def init(self): """ Init method for the raspberry pi camera device. Start by deleting any running subrocesses that may be left over from previous inits, note the subprocess is stored in a class variable (ONLY one of these per server !) Read all of the settings and create a script to take the data. Note: This device supports at most 1 camera per server. Which is OK since the raspberry pis only have one camera port. """ import os import subprocess self.debugging = os.getenv('DEBUG_DEVICES') camera = str(self.serial_no.record) c_rec = None for c in PICAM.cameras: if c.camera == camera : try: if self.debugging: print "PICAM killing ", c.subproc, c.subproc.pid kill(c.subproc.pid) except Exception, e: if self.debugging: print "PICAM kill exception", e pass c_rec = c if c_rec is None: c = PICAM.camera_proc(camera) PICAM.cameras.append(c) if not c.camera == camera: c = PICAM.camera_proc(camera) PICAM.cameras.append(c) tree = self.local_tree shot = self.tree.shot path = self.local_path c.subproc = subprocess.Popen('mdstcl 2>&1', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) c.subproc.stdin.write('set tree %s /shot = %d\n'%(tree, shot,)) c.subproc.stdin.write('do/meth %s acquire\n'%(path,)) c.subproc.stdin.write('exit\n') c.subproc.stdin.flush() return 1 INIT=init def acquire(self): import os import ctypes as ctypes import numpy as np from MDSplus.mdsExceptions import DevCOMM_ERROR from MDSplus.mdsExceptions import DevBAD_PARAMETER from MDSplus.mdsExceptions import DevPY_INTERFACE_LIBRARY_NOT_FOUND try: import PythonForPicam as pfp except: raise DevPY_INTERFACE_LIBRARY_NOT_FOUND("Picam error importing PythonForPicam") self.debugging = os.getenv('DEBUG_DEVICES') exposure = float(self.exposure) exposure = pfp.piflt(exposure) num_frames = int(self.num_frames) timeout = int(self.timeout) serial_no = str(self.serial_no.record) try: if self.debugging: print "PICAM about to try to read the ROIS" rois = self.rois.data() if self.debugging: print "PICAM got the rois ", rois except Exception,e: if self.debugging: print "PICAM could not read the ROIS" rois = None print "Acquire - debugging is ", self.debugging pfp.Picam_InitializeLibrary() major = pfp.piint() minor = pfp.piint() distribution = pfp.piint() release = pfp.piint() pfp.Picam_GetVersion(pointer(major),pointer(minor),pointer(distribution),pointer(release)) self.lib_version.record = 'Picam Version %d.%d.%d Released %d' % (major.value,minor.value,distribution.value,release.value,) available = ctypes.POINTER(ctypes.c_int)() availableCount = pfp.piint(); status = pfp.Picam_GetAvailableCameraIDs(ctypes.byref(available), ctypes.byref(availableCount)) camera = pfp.PicamHandle() cameras_type = pfp.PicamCameraID*availableCount.value cameras_pointer = ctypes.POINTER(cameras_type) cameras = ctypes.cast(available, cameras_pointer) found = False for c in cameras.contents: if self.debugging: print "checking ",c.serial_number if c.serial_number == serial_no: status = pfp.Picam_OpenCamera(pointer(c),ctypes.addressof(camera)) if not status == "PicamError_None": raise DevCOMM_ERROR("PiCam - could not open camera serial no %d - %s"% (serial_no,status,)) found = True if not found: raise DevBAD_PARAMETER("PiCam - Could not find camera %d"%serial_no) PicamID = pfp.PicamCameraID() pfp.Picam_GetCameraID(camera, pointer(PicamID)) self.model.record = str(PicamID.model) self.sensor.record = str(PicamID.sensor_name) trigger_response = str(self.trg_response.record) if trigger_response == 'NoResponse': trigger_resp = pfp.PicamTriggerResponse_NoResponse elif trigger_response == 'ReadoutPerTrigger': trigger_resp = pfp.PicamTriggerResponse_ReadoutPerTrigger elif trigger_response == 'ShiftPerTrigger': trigger_resp = pfp.PicamTriggerResponse_ShiftPerTrigger elif trigger_response == 'ExposeDuringTriggerPulse': trigger_resp = pfp.PicamTriggerResponse_ExposeDuringTriggerPulse elif trigger_response == 'StartOnSingleTrigger': trigger_resp = pfp.PicamTriggerResponse_StartOnSingleTrigger else: raise DevBAD_PARAMETER("PiCam - TRG_RESPONSE must be one of ('NoResponse','ReadoutPerTrigger','ShiftPerTrigger','ExposeDuringTriggerPulse', 'StartOnSingleTrigger')") if self.debugging: print "Picam_SetParameterIntegerValue(camera, PicamParameter_TriggerResponse,",trigger_resp,")" pfp.Picam_SetParameterIntegerValue( camera, pfp.PicamParameter_TriggerResponse, trigger_resp ) pfp.Picam_SetParameterIntegerValue( camera, pfp.PicamParameter_TriggerDetermination, pfp.PicamTriggerDetermination_PositivePolarity ) pfp.Picam_SetParameterIntegerValue( camera, pfp.PicamParameter_OutputSignal, pfp.PicamOutputSignal_Exposing ) if self.debugging: print "Picam_SetParameterFloatingPointValue( camera, PicamParameter_ExposureTime, ",exposure,")" pfp.Picam_SetParameterFloatingPointValue( camera, pfp.PicamParameter_ExposureTime, exposure ) failCount = pfp.piint() paramsFailed = pfp.piint() if self.debugging: print "Picam_CommitParameters(camera, pointer(paramsFailed), ctypes.byref(failCount))" pfp.Picam_CommitParameters(camera, pointer(paramsFailed), ctypes.byref(failCount)) if self.debugging: print "failcount is ", failCount pfp.Picam_DestroyParameters(pointer(paramsFailed)) width = pfp.piint(0) pfp.Picam_GetParameterIntegerValue( camera, ctypes.c_int(pfp.PicamParameter_SensorActiveWidth), ctypes.byref(width) ); width = width.value if rois is not None: if self.debugging: print "PICAM have rois" shape = rois.shape if shape[1] == 6 : if self.debugging: print "PICAM it is nx6" Rois = pfp.PicamRois(shape[0]) for i in range(shape[0]): Rois.roi_array[i].x = rois[i,0] Rois.roi_array[i].width = rois[i,1] Rois.roi_array[i].x_binning = rois[i,2] Rois.roi_array[i].y = rois[i,3] Rois.roi_array[i].height = rois[i,4] Rois.roi_array[i].y_binning = rois[i,5] width = rois[i,1] if self.debugging: print "PICAM The Rois are: ", Rois status = pfp.Picam_SetParameterRoisValue(camera, pfp.PicamParameter_Rois, pointer(Rois)) if not status == "PicamError_None": raise DevCOMM_ERROR("PiCam - error setting ROI- %s"% status) failCount = pfp.piint() paramsFailed = pfp.piint() status = pfp.Picam_CommitParameters(camera, pointer(paramsFailed), ctypes.byref(failCount)) if not status == "PicamError_None": raise DevCOMM_ERROR("PiCam - error committing ROI Parameter Change %s" % status) if not failCount.value == 0: raise DevCOMM_ERROR("PiCam - ROI commit failure count > 0", failCount) pfp.Picam_DestroyParameters(pointer(paramsFailed)) else: raise DevBAD_PARAMETER("PiCAM Rois must be 6xN array") errors = pfp.PicamAcquisitionErrorsMask() readout_count = pfp.pi64s(num_frames) readout_time_out = pfp.piint(-1) available = pfp.PicamAvailableData(0, 0) if self.debugging: print "about to call Picam_Acquire" status = pfp.Picam_Acquire(camera, readout_count, readout_time_out, ctypes.byref(available), ctypes.byref(errors)) if not status == "PicamError_None": print "Picam_Acquire returned ",status raise DevCOMM_ERROR("PiCam - non zero return from Picam_Acquire - %s" % status) if self.debugging: print "back from aquire" temperature = pfp.piflt(0.0) status = pfp.Picam_GetParameterFloatingPointValue( camera, ctypes.c_int(pfp.PicamParameter_SensorTemperatureReading), ctypes.byref(temperature) ) if status == "PicamError_None" : self.sensor_temp.record = temperature.value if self.debugging : print "PICAM read back sensor temperature ", temperature else: print "PICAM could not read back sensor temperature ", status readout_time = pfp.piflt(0.0) status = pfp.Picam_GetParameterFloatingPointValue( camera, ctypes.c_int(pfp.PicamParameter_ReadoutTimeCalculation), ctypes.byref(readout_time) ) if status == "PicamError_None" : self.readout_time.record = readout_time.value if self.debugging : print "PICAM read back ReadoutTimeCalculation ", readout_time else: print "PICAM could not read back readout time ", status readoutstride = pfp.piint(0) status = pfp.Picam_GetParameterIntegerValue( camera, ctypes.c_int(pfp.PicamParameter_ReadoutStride), ctypes.byref(readoutstride) ) if self.debugging: print "Picam_GetParameterIntegerValue( camera, ctypes.c_int(PicamParameter_ReadoutStride),",readoutstride," )", status if not status == "PicamError_None" : raise DevCOMM_ERROR("PiCam - could not read readout stride - %s"% status) sz = readout_count.value*readoutstride.value/2 if self.debugging: print "sz is ",sz, " num_frames is ", num_frames, "readout_count is ", readout_count, " readoutstride is ", readoutstride DataArrayType = pfp.pi16u*sz """ Create pointer type for the above array type """ DataArrayPointerType = ctypes.POINTER(pfp.pi16u*sz) if self.debugging: print "PICAM - cast the read data into the pointer type" """ Create an instance of the pointer type, and point it to initial readout contents (memory address?) """ DataPointer = ctypes.cast(available.initial_readout,DataArrayPointerType) if self.debugging: print "PICAM now deference the pointer" """ Create a separate array with readout contents """ data = DataPointer.contents if self.debugging: print "PICAM - now make an np.empty of shorts (%d)"%sz ans = np.empty(sz,np.short) if self.debugging: print "PICAM - fill it in " ans[:] = data if self.debugging: print "PICAM reshape the data to be (%d, %d, %d)"%(num_frames, readoutstride.value/2/width, width) ans = ans.reshape((num_frames, readoutstride.value/2/width, width)) self.frames.record = ans if self.debugging: print "un initialize the library" pfp.Picam_UninitializeLibrary() return 1 ACQUIRE=acquire
false
true
f72a4476249a5b91384f4535c7234e7f722e0b67
19,874
py
Python
tests/test_cognitoidp/test_cognitoidp.py
alexsult/moto
ed861ecae1039a048a6350a4ff832ef094cdf2c2
[ "Apache-2.0" ]
null
null
null
tests/test_cognitoidp/test_cognitoidp.py
alexsult/moto
ed861ecae1039a048a6350a4ff832ef094cdf2c2
[ "Apache-2.0" ]
5
2018-04-25T21:04:20.000Z
2018-11-02T19:59:27.000Z
tests/test_cognitoidp/test_cognitoidp.py
alexsult/moto
ed861ecae1039a048a6350a4ff832ef094cdf2c2
[ "Apache-2.0" ]
null
null
null
from __future__ import unicode_literals import boto3 import json import os import uuid from jose import jws from moto import mock_cognitoidp import sure # noqa @mock_cognitoidp def test_create_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) value = str(uuid.uuid4()) result = conn.create_user_pool( PoolName=name, LambdaConfig={ "PreSignUp": value } ) result["UserPool"]["Id"].should_not.be.none result["UserPool"]["Id"].should.match(r'[\w-]+_[0-9a-zA-Z]+') result["UserPool"]["Name"].should.equal(name) result["UserPool"]["LambdaConfig"]["PreSignUp"].should.equal(value) @mock_cognitoidp def test_list_user_pools(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) conn.create_user_pool(PoolName=name) result = conn.list_user_pools(MaxResults=10) result["UserPools"].should.have.length_of(1) result["UserPools"][0]["Name"].should.equal(name) @mock_cognitoidp def test_describe_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_details = conn.create_user_pool( PoolName=name, LambdaConfig={ "PreSignUp": value } ) result = conn.describe_user_pool(UserPoolId=user_pool_details["UserPool"]["Id"]) result["UserPool"]["Name"].should.equal(name) result["UserPool"]["LambdaConfig"]["PreSignUp"].should.equal(value) @mock_cognitoidp def test_delete_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.list_user_pools(MaxResults=10)["UserPools"].should.have.length_of(1) conn.delete_user_pool(UserPoolId=user_pool_id) conn.list_user_pools(MaxResults=10)["UserPools"].should.have.length_of(0) @mock_cognitoidp def test_create_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) @mock_cognitoidp def test_describe_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result = conn.describe_user_pool_domain(Domain=domain) result["DomainDescription"]["Domain"].should.equal(domain) result["DomainDescription"]["UserPoolId"].should.equal(user_pool_id) result["DomainDescription"]["AWSAccountId"].should_not.be.none @mock_cognitoidp def test_delete_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result = conn.delete_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) result = conn.describe_user_pool_domain(Domain=domain) # This is a surprising behavior of the real service: describing a missing domain comes # back with status 200 and a DomainDescription of {} result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) result["DomainDescription"].keys().should.have.length_of(0) @mock_cognitoidp def test_create_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=client_name, CallbackURLs=[value], ) result["UserPoolClient"]["UserPoolId"].should.equal(user_pool_id) result["UserPoolClient"]["ClientId"].should_not.be.none result["UserPoolClient"]["ClientName"].should.equal(client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(value) @mock_cognitoidp def test_list_user_pool_clients(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_client(UserPoolId=user_pool_id, ClientName=client_name) result = conn.list_user_pool_clients(UserPoolId=user_pool_id, MaxResults=10) result["UserPoolClients"].should.have.length_of(1) result["UserPoolClients"][0]["ClientName"].should.equal(client_name) @mock_cognitoidp def test_describe_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=client_name, CallbackURLs=[value], ) result = conn.describe_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) result["UserPoolClient"]["ClientName"].should.equal(client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(value) @mock_cognitoidp def test_update_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") old_client_name = str(uuid.uuid4()) new_client_name = str(uuid.uuid4()) old_value = str(uuid.uuid4()) new_value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=old_client_name, CallbackURLs=[old_value], ) result = conn.update_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ClientName=new_client_name, CallbackURLs=[new_value], ) result["UserPoolClient"]["ClientName"].should.equal(new_client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(new_value) @mock_cognitoidp def test_delete_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), ) conn.delete_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) caught = False try: conn.describe_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) except conn.exceptions.ResourceNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_create_identity_provider(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) result["IdentityProvider"]["UserPoolId"].should.equal(user_pool_id) result["IdentityProvider"]["ProviderName"].should.equal(provider_name) result["IdentityProvider"]["ProviderType"].should.equal(provider_type) result["IdentityProvider"]["ProviderDetails"]["thing"].should.equal(value) @mock_cognitoidp def test_list_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={}, ) result = conn.list_identity_providers( UserPoolId=user_pool_id, MaxResults=10, ) result["Providers"].should.have.length_of(1) result["Providers"][0]["ProviderName"].should.equal(provider_name) result["Providers"][0]["ProviderType"].should.equal(provider_type) @mock_cognitoidp def test_describe_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) result = conn.describe_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ) result["IdentityProvider"]["UserPoolId"].should.equal(user_pool_id) result["IdentityProvider"]["ProviderName"].should.equal(provider_name) result["IdentityProvider"]["ProviderType"].should.equal(provider_type) result["IdentityProvider"]["ProviderDetails"]["thing"].should.equal(value) @mock_cognitoidp def test_delete_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) conn.delete_identity_provider(UserPoolId=user_pool_id, ProviderName=provider_name) caught = False try: conn.describe_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ) except conn.exceptions.ResourceNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_admin_create_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.admin_create_user( UserPoolId=user_pool_id, Username=username, UserAttributes=[ {"Name": "thing", "Value": value} ], ) result["User"]["Username"].should.equal(username) result["User"]["UserStatus"].should.equal("FORCE_CHANGE_PASSWORD") result["User"]["Attributes"].should.have.length_of(1) result["User"]["Attributes"][0]["Name"].should.equal("thing") result["User"]["Attributes"][0]["Value"].should.equal(value) result["User"]["Enabled"].should.equal(True) @mock_cognitoidp def test_admin_get_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, UserAttributes=[ {"Name": "thing", "Value": value} ], ) result = conn.admin_get_user(UserPoolId=user_pool_id, Username=username) result["Username"].should.equal(username) result["UserAttributes"].should.have.length_of(1) result["UserAttributes"][0]["Name"].should.equal("thing") result["UserAttributes"][0]["Value"].should.equal(value) @mock_cognitoidp def test_admin_get_missing_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] caught = False try: conn.admin_get_user(UserPoolId=user_pool_id, Username=username) except conn.exceptions.UserNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_list_users(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) result = conn.list_users(UserPoolId=user_pool_id) result["Users"].should.have.length_of(1) result["Users"][0]["Username"].should.equal(username) @mock_cognitoidp def test_admin_disable_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) result = conn.admin_disable_user(UserPoolId=user_pool_id, Username=username) list(result.keys()).should.equal(["ResponseMetadata"]) # No response expected conn.admin_get_user(UserPoolId=user_pool_id, Username=username) \ ["Enabled"].should.equal(False) @mock_cognitoidp def test_admin_enable_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) conn.admin_disable_user(UserPoolId=user_pool_id, Username=username) result = conn.admin_enable_user(UserPoolId=user_pool_id, Username=username) list(result.keys()).should.equal(["ResponseMetadata"]) # No response expected conn.admin_get_user(UserPoolId=user_pool_id, Username=username) \ ["Enabled"].should.equal(True) @mock_cognitoidp def test_admin_delete_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) conn.admin_delete_user(UserPoolId=user_pool_id, Username=username) caught = False try: conn.admin_get_user(UserPoolId=user_pool_id, Username=username) except conn.exceptions.UserNotFoundException: caught = True caught.should.be.true def authentication_flow(conn): username = str(uuid.uuid4()) temporary_password = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] user_attribute_name = str(uuid.uuid4()) user_attribute_value = str(uuid.uuid4()) client_id = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), ReadAttributes=[user_attribute_name] )["UserPoolClient"]["ClientId"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, TemporaryPassword=temporary_password, UserAttributes=[{ 'Name': user_attribute_name, 'Value': user_attribute_value }] ) result = conn.admin_initiate_auth( UserPoolId=user_pool_id, ClientId=client_id, AuthFlow="ADMIN_NO_SRP_AUTH", AuthParameters={ "USERNAME": username, "PASSWORD": temporary_password }, ) # A newly created user is forced to set a new password result["ChallengeName"].should.equal("NEW_PASSWORD_REQUIRED") result["Session"].should_not.be.none # This sets a new password and logs the user in (creates tokens) new_password = str(uuid.uuid4()) result = conn.respond_to_auth_challenge( Session=result["Session"], ClientId=client_id, ChallengeName="NEW_PASSWORD_REQUIRED", ChallengeResponses={ "USERNAME": username, "NEW_PASSWORD": new_password } ) result["AuthenticationResult"]["IdToken"].should_not.be.none result["AuthenticationResult"]["AccessToken"].should_not.be.none return { "user_pool_id": user_pool_id, "client_id": client_id, "id_token": result["AuthenticationResult"]["IdToken"], "access_token": result["AuthenticationResult"]["AccessToken"], "username": username, "password": new_password, "additional_fields": { user_attribute_name: user_attribute_value } } @mock_cognitoidp def test_authentication_flow(): conn = boto3.client("cognito-idp", "us-west-2") authentication_flow(conn) @mock_cognitoidp def test_token_legitimacy(): conn = boto3.client("cognito-idp", "us-west-2") path = "../../moto/cognitoidp/resources/jwks-public.json" with open(os.path.join(os.path.dirname(__file__), path)) as f: json_web_key = json.loads(f.read())["keys"][0] outputs = authentication_flow(conn) id_token = outputs["id_token"] access_token = outputs["access_token"] client_id = outputs["client_id"] issuer = "https://cognito-idp.us-west-2.amazonaws.com/{}".format(outputs["user_pool_id"]) id_claims = json.loads(jws.verify(id_token, json_web_key, "RS256")) id_claims["iss"].should.equal(issuer) id_claims["aud"].should.equal(client_id) access_claims = json.loads(jws.verify(access_token, json_web_key, "RS256")) access_claims["iss"].should.equal(issuer) access_claims["aud"].should.equal(client_id) for k, v in outputs["additional_fields"].items(): access_claims[k].should.equal(v) @mock_cognitoidp def test_change_password(): conn = boto3.client("cognito-idp", "us-west-2") outputs = authentication_flow(conn) # Take this opportunity to test change_password, which requires an access token. newer_password = str(uuid.uuid4()) conn.change_password( AccessToken=outputs["access_token"], PreviousPassword=outputs["password"], ProposedPassword=newer_password, ) # Log in again, which should succeed without a challenge because the user is no # longer in the force-new-password state. result = conn.admin_initiate_auth( UserPoolId=outputs["user_pool_id"], ClientId=outputs["client_id"], AuthFlow="ADMIN_NO_SRP_AUTH", AuthParameters={ "USERNAME": outputs["username"], "PASSWORD": newer_password, }, ) result["AuthenticationResult"].should_not.be.none @mock_cognitoidp def test_forgot_password(): conn = boto3.client("cognito-idp", "us-west-2") result = conn.forgot_password(ClientId=str(uuid.uuid4()), Username=str(uuid.uuid4())) result["CodeDeliveryDetails"].should_not.be.none @mock_cognitoidp def test_confirm_forgot_password(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_id = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), )["UserPoolClient"]["ClientId"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, TemporaryPassword=str(uuid.uuid4()), ) conn.confirm_forgot_password( ClientId=client_id, Username=username, ConfirmationCode=str(uuid.uuid4()), Password=str(uuid.uuid4()), )
33.013289
93
0.690601
from __future__ import unicode_literals import boto3 import json import os import uuid from jose import jws from moto import mock_cognitoidp import sure @mock_cognitoidp def test_create_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) value = str(uuid.uuid4()) result = conn.create_user_pool( PoolName=name, LambdaConfig={ "PreSignUp": value } ) result["UserPool"]["Id"].should_not.be.none result["UserPool"]["Id"].should.match(r'[\w-]+_[0-9a-zA-Z]+') result["UserPool"]["Name"].should.equal(name) result["UserPool"]["LambdaConfig"]["PreSignUp"].should.equal(value) @mock_cognitoidp def test_list_user_pools(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) conn.create_user_pool(PoolName=name) result = conn.list_user_pools(MaxResults=10) result["UserPools"].should.have.length_of(1) result["UserPools"][0]["Name"].should.equal(name) @mock_cognitoidp def test_describe_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_details = conn.create_user_pool( PoolName=name, LambdaConfig={ "PreSignUp": value } ) result = conn.describe_user_pool(UserPoolId=user_pool_details["UserPool"]["Id"]) result["UserPool"]["Name"].should.equal(name) result["UserPool"]["LambdaConfig"]["PreSignUp"].should.equal(value) @mock_cognitoidp def test_delete_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.list_user_pools(MaxResults=10)["UserPools"].should.have.length_of(1) conn.delete_user_pool(UserPoolId=user_pool_id) conn.list_user_pools(MaxResults=10)["UserPools"].should.have.length_of(0) @mock_cognitoidp def test_create_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) @mock_cognitoidp def test_describe_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result = conn.describe_user_pool_domain(Domain=domain) result["DomainDescription"]["Domain"].should.equal(domain) result["DomainDescription"]["UserPoolId"].should.equal(user_pool_id) result["DomainDescription"]["AWSAccountId"].should_not.be.none @mock_cognitoidp def test_delete_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result = conn.delete_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) result = conn.describe_user_pool_domain(Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) result["DomainDescription"].keys().should.have.length_of(0) @mock_cognitoidp def test_create_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=client_name, CallbackURLs=[value], ) result["UserPoolClient"]["UserPoolId"].should.equal(user_pool_id) result["UserPoolClient"]["ClientId"].should_not.be.none result["UserPoolClient"]["ClientName"].should.equal(client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(value) @mock_cognitoidp def test_list_user_pool_clients(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_client(UserPoolId=user_pool_id, ClientName=client_name) result = conn.list_user_pool_clients(UserPoolId=user_pool_id, MaxResults=10) result["UserPoolClients"].should.have.length_of(1) result["UserPoolClients"][0]["ClientName"].should.equal(client_name) @mock_cognitoidp def test_describe_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=client_name, CallbackURLs=[value], ) result = conn.describe_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) result["UserPoolClient"]["ClientName"].should.equal(client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(value) @mock_cognitoidp def test_update_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") old_client_name = str(uuid.uuid4()) new_client_name = str(uuid.uuid4()) old_value = str(uuid.uuid4()) new_value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=old_client_name, CallbackURLs=[old_value], ) result = conn.update_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ClientName=new_client_name, CallbackURLs=[new_value], ) result["UserPoolClient"]["ClientName"].should.equal(new_client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(new_value) @mock_cognitoidp def test_delete_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), ) conn.delete_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) caught = False try: conn.describe_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) except conn.exceptions.ResourceNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_create_identity_provider(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) result["IdentityProvider"]["UserPoolId"].should.equal(user_pool_id) result["IdentityProvider"]["ProviderName"].should.equal(provider_name) result["IdentityProvider"]["ProviderType"].should.equal(provider_type) result["IdentityProvider"]["ProviderDetails"]["thing"].should.equal(value) @mock_cognitoidp def test_list_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={}, ) result = conn.list_identity_providers( UserPoolId=user_pool_id, MaxResults=10, ) result["Providers"].should.have.length_of(1) result["Providers"][0]["ProviderName"].should.equal(provider_name) result["Providers"][0]["ProviderType"].should.equal(provider_type) @mock_cognitoidp def test_describe_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) result = conn.describe_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ) result["IdentityProvider"]["UserPoolId"].should.equal(user_pool_id) result["IdentityProvider"]["ProviderName"].should.equal(provider_name) result["IdentityProvider"]["ProviderType"].should.equal(provider_type) result["IdentityProvider"]["ProviderDetails"]["thing"].should.equal(value) @mock_cognitoidp def test_delete_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) conn.delete_identity_provider(UserPoolId=user_pool_id, ProviderName=provider_name) caught = False try: conn.describe_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ) except conn.exceptions.ResourceNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_admin_create_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.admin_create_user( UserPoolId=user_pool_id, Username=username, UserAttributes=[ {"Name": "thing", "Value": value} ], ) result["User"]["Username"].should.equal(username) result["User"]["UserStatus"].should.equal("FORCE_CHANGE_PASSWORD") result["User"]["Attributes"].should.have.length_of(1) result["User"]["Attributes"][0]["Name"].should.equal("thing") result["User"]["Attributes"][0]["Value"].should.equal(value) result["User"]["Enabled"].should.equal(True) @mock_cognitoidp def test_admin_get_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, UserAttributes=[ {"Name": "thing", "Value": value} ], ) result = conn.admin_get_user(UserPoolId=user_pool_id, Username=username) result["Username"].should.equal(username) result["UserAttributes"].should.have.length_of(1) result["UserAttributes"][0]["Name"].should.equal("thing") result["UserAttributes"][0]["Value"].should.equal(value) @mock_cognitoidp def test_admin_get_missing_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] caught = False try: conn.admin_get_user(UserPoolId=user_pool_id, Username=username) except conn.exceptions.UserNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_list_users(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) result = conn.list_users(UserPoolId=user_pool_id) result["Users"].should.have.length_of(1) result["Users"][0]["Username"].should.equal(username) @mock_cognitoidp def test_admin_disable_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) result = conn.admin_disable_user(UserPoolId=user_pool_id, Username=username) list(result.keys()).should.equal(["ResponseMetadata"]) conn.admin_get_user(UserPoolId=user_pool_id, Username=username) \ ["Enabled"].should.equal(False) @mock_cognitoidp def test_admin_enable_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) conn.admin_disable_user(UserPoolId=user_pool_id, Username=username) result = conn.admin_enable_user(UserPoolId=user_pool_id, Username=username) list(result.keys()).should.equal(["ResponseMetadata"]) conn.admin_get_user(UserPoolId=user_pool_id, Username=username) \ ["Enabled"].should.equal(True) @mock_cognitoidp def test_admin_delete_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) conn.admin_delete_user(UserPoolId=user_pool_id, Username=username) caught = False try: conn.admin_get_user(UserPoolId=user_pool_id, Username=username) except conn.exceptions.UserNotFoundException: caught = True caught.should.be.true def authentication_flow(conn): username = str(uuid.uuid4()) temporary_password = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] user_attribute_name = str(uuid.uuid4()) user_attribute_value = str(uuid.uuid4()) client_id = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), ReadAttributes=[user_attribute_name] )["UserPoolClient"]["ClientId"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, TemporaryPassword=temporary_password, UserAttributes=[{ 'Name': user_attribute_name, 'Value': user_attribute_value }] ) result = conn.admin_initiate_auth( UserPoolId=user_pool_id, ClientId=client_id, AuthFlow="ADMIN_NO_SRP_AUTH", AuthParameters={ "USERNAME": username, "PASSWORD": temporary_password }, ) result["ChallengeName"].should.equal("NEW_PASSWORD_REQUIRED") result["Session"].should_not.be.none new_password = str(uuid.uuid4()) result = conn.respond_to_auth_challenge( Session=result["Session"], ClientId=client_id, ChallengeName="NEW_PASSWORD_REQUIRED", ChallengeResponses={ "USERNAME": username, "NEW_PASSWORD": new_password } ) result["AuthenticationResult"]["IdToken"].should_not.be.none result["AuthenticationResult"]["AccessToken"].should_not.be.none return { "user_pool_id": user_pool_id, "client_id": client_id, "id_token": result["AuthenticationResult"]["IdToken"], "access_token": result["AuthenticationResult"]["AccessToken"], "username": username, "password": new_password, "additional_fields": { user_attribute_name: user_attribute_value } } @mock_cognitoidp def test_authentication_flow(): conn = boto3.client("cognito-idp", "us-west-2") authentication_flow(conn) @mock_cognitoidp def test_token_legitimacy(): conn = boto3.client("cognito-idp", "us-west-2") path = "../../moto/cognitoidp/resources/jwks-public.json" with open(os.path.join(os.path.dirname(__file__), path)) as f: json_web_key = json.loads(f.read())["keys"][0] outputs = authentication_flow(conn) id_token = outputs["id_token"] access_token = outputs["access_token"] client_id = outputs["client_id"] issuer = "https://cognito-idp.us-west-2.amazonaws.com/{}".format(outputs["user_pool_id"]) id_claims = json.loads(jws.verify(id_token, json_web_key, "RS256")) id_claims["iss"].should.equal(issuer) id_claims["aud"].should.equal(client_id) access_claims = json.loads(jws.verify(access_token, json_web_key, "RS256")) access_claims["iss"].should.equal(issuer) access_claims["aud"].should.equal(client_id) for k, v in outputs["additional_fields"].items(): access_claims[k].should.equal(v) @mock_cognitoidp def test_change_password(): conn = boto3.client("cognito-idp", "us-west-2") outputs = authentication_flow(conn) newer_password = str(uuid.uuid4()) conn.change_password( AccessToken=outputs["access_token"], PreviousPassword=outputs["password"], ProposedPassword=newer_password, ) result = conn.admin_initiate_auth( UserPoolId=outputs["user_pool_id"], ClientId=outputs["client_id"], AuthFlow="ADMIN_NO_SRP_AUTH", AuthParameters={ "USERNAME": outputs["username"], "PASSWORD": newer_password, }, ) result["AuthenticationResult"].should_not.be.none @mock_cognitoidp def test_forgot_password(): conn = boto3.client("cognito-idp", "us-west-2") result = conn.forgot_password(ClientId=str(uuid.uuid4()), Username=str(uuid.uuid4())) result["CodeDeliveryDetails"].should_not.be.none @mock_cognitoidp def test_confirm_forgot_password(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_id = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), )["UserPoolClient"]["ClientId"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, TemporaryPassword=str(uuid.uuid4()), ) conn.confirm_forgot_password( ClientId=client_id, Username=username, ConfirmationCode=str(uuid.uuid4()), Password=str(uuid.uuid4()), )
true
true
f72a47612f3599e9c27c19fedb85a488b08046a6
1,760
py
Python
tests/test_buildsets.py
MichalMilewicz/tungsten-ci-dashboard
67ca8e39855009ab7b4d603b691ea910ee6efbbc
[ "Apache-2.0" ]
null
null
null
tests/test_buildsets.py
MichalMilewicz/tungsten-ci-dashboard
67ca8e39855009ab7b4d603b691ea910ee6efbbc
[ "Apache-2.0" ]
null
null
null
tests/test_buildsets.py
MichalMilewicz/tungsten-ci-dashboard
67ca8e39855009ab7b4d603b691ea910ee6efbbc
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import unittest from unittest.mock import MagicMock, patch from dashboard.exceptions import PageOutOfRange from dashboard.history import BuildSetsPaginated class TestBuildSets(unittest.TestCase): @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_create_buildsets_history_object(self, get_for_pipeline): buildsets = BuildSetsPaginated(pipeline="foo", per_page=20) self.assertEqual(buildsets.per_page, 20) @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_create_query(self, get_for_pipeline): BuildSetsPaginated(pipeline="foo", per_page=20) get_for_pipeline.assert_called_with("foo") @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_fetch_raises_when_page_is_out_of_range(self, get_for_pipeline): get_for_pipeline.return_value = [ 'first_element', 'second_element', 'third_element'] buildsets = BuildSetsPaginated(pipeline="foo", per_page=20) with self.assertRaises(PageOutOfRange): buildsets.fetch_page(2) @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_fetch_set_correct_page(self, get_for_pipeline): data = ['first_element', 'second_element', 'third_element'] query = self._query_mock(data) get_for_pipeline.return_value = query buildset = BuildSetsPaginated(pipeline="foo", per_page=20) buildset.fetch_page(page=1) self.assertEqual(buildset.page, data) query.page.assert_called_with(1, 20) def _query_mock(self, data): query = MagicMock() query.__len__ = lambda x: len(data) query.page = MagicMock() query.page.return_value = data return query
34.509804
76
0.715909
import unittest from unittest.mock import MagicMock, patch from dashboard.exceptions import PageOutOfRange from dashboard.history import BuildSetsPaginated class TestBuildSets(unittest.TestCase): @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_create_buildsets_history_object(self, get_for_pipeline): buildsets = BuildSetsPaginated(pipeline="foo", per_page=20) self.assertEqual(buildsets.per_page, 20) @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_create_query(self, get_for_pipeline): BuildSetsPaginated(pipeline="foo", per_page=20) get_for_pipeline.assert_called_with("foo") @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_fetch_raises_when_page_is_out_of_range(self, get_for_pipeline): get_for_pipeline.return_value = [ 'first_element', 'second_element', 'third_element'] buildsets = BuildSetsPaginated(pipeline="foo", per_page=20) with self.assertRaises(PageOutOfRange): buildsets.fetch_page(2) @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_fetch_set_correct_page(self, get_for_pipeline): data = ['first_element', 'second_element', 'third_element'] query = self._query_mock(data) get_for_pipeline.return_value = query buildset = BuildSetsPaginated(pipeline="foo", per_page=20) buildset.fetch_page(page=1) self.assertEqual(buildset.page, data) query.page.assert_called_with(1, 20) def _query_mock(self, data): query = MagicMock() query.__len__ = lambda x: len(data) query.page = MagicMock() query.page.return_value = data return query
true
true
f72a484fe9c2c76a51236db7ad5259bebcb0d8f6
4,602
py
Python
dataservice/api/outcome/resources.py
ConnorBarnhill/kf-api-dataservice
547df467a307788882469a25c947a14965a26336
[ "Apache-2.0" ]
6
2018-01-25T13:49:24.000Z
2020-03-07T16:25:09.000Z
dataservice/api/outcome/resources.py
ConnorBarnhill/kf-api-dataservice
547df467a307788882469a25c947a14965a26336
[ "Apache-2.0" ]
369
2018-01-17T15:22:18.000Z
2022-03-10T19:14:56.000Z
dataservice/api/outcome/resources.py
ConnorBarnhill/kf-api-dataservice
547df467a307788882469a25c947a14965a26336
[ "Apache-2.0" ]
3
2018-04-11T14:18:37.000Z
2018-10-31T19:09:48.000Z
from flask import abort, request from marshmallow import ValidationError from webargs.flaskparser import use_args from dataservice.extensions import db from dataservice.api.common.pagination import paginated, Pagination from dataservice.api.outcome.models import Outcome from dataservice.api.outcome.schemas import OutcomeSchema from dataservice.api.common.views import CRUDView from dataservice.api.common.schemas import filter_schema_factory class OutcomeListAPI(CRUDView): """ Outcome REST API """ endpoint = 'outcomes_list' rule = '/outcomes' schemas = {'Outcome': OutcomeSchema} @paginated @use_args(filter_schema_factory(OutcomeSchema), locations=('query',)) def get(self, filter_params, after, limit): """ Get all outcomes --- description: Get all outcomes template: path: get_list.yml properties: resource: Outcome """ # Get study id and remove from model filter params study_id = filter_params.pop('study_id', None) q = Outcome.query.filter_by(**filter_params) # Filter by study from dataservice.api.participant.models import Participant if study_id: q = (q.join(Participant.outcomes) .filter(Participant.study_id == study_id)) return (OutcomeSchema(many=True) .jsonify(Pagination(q, after, limit))) def post(self): """ Create a new outcome --- template: path: new_resource.yml properties: resource: Outcome """ body = request.get_json(force=True) # Deserialize try: o = OutcomeSchema(strict=True).load(body).data # Request body not valid except ValidationError as e: abort(400, 'could not create outcome: {}'.format(e.messages)) # Add to and save in database db.session.add(o) db.session.commit() return OutcomeSchema(201, 'outcome {} created' .format(o.kf_id)).jsonify(o), 201 class OutcomeAPI(CRUDView): """ Outcome REST API """ endpoint = 'outcomes' rule = '/outcomes/<string:kf_id>' schemas = {'Outcome': OutcomeSchema} def get(self, kf_id): """ Get a outcome by id --- template: path: get_by_id.yml properties: resource: Outcome """ # Get one o = Outcome.query.get(kf_id) # Not found in database if o is None: abort(404, 'could not find {} `{}`' .format('outcome', kf_id)) return OutcomeSchema().jsonify(o) def patch(self, kf_id): """ Update an existing outcome Allows partial update of resource --- template: path: update_by_id.yml properties: resource: Outcome """ # Check if outcome exists o = Outcome.query.get(kf_id) # Not found in database if o is None: abort(404, 'could not find {} `{}`'.format('outcome', kf_id)) # Partial update - validate but allow missing required fields body = request.get_json(force=True) or {} # Validation only try: o = OutcomeSchema(strict=True).load(body, instance=o, partial=True).data # Request body not valid except ValidationError as e: abort(400, 'could not update outcome: {}'.format(e.messages)) # Save to database db.session.add(o) db.session.commit() return OutcomeSchema(200, 'outcome {} updated' .format(o.kf_id)).jsonify(o), 200 def delete(self, kf_id): """ Delete outcome by id Deletes a outcome given a Kids First id --- template: path: delete_by_id.yml properties: resource: Outcome """ # Check if outcome exists o = Outcome.query.get(kf_id) # Not found in database if o is None: abort(404, 'could not find {} `{}`'.format('outcome', kf_id)) # Save in database db.session.delete(o) db.session.commit() return OutcomeSchema(200, 'outcome {} deleted' .format(o.kf_id)).jsonify(o), 200
27.556886
73
0.548457
from flask import abort, request from marshmallow import ValidationError from webargs.flaskparser import use_args from dataservice.extensions import db from dataservice.api.common.pagination import paginated, Pagination from dataservice.api.outcome.models import Outcome from dataservice.api.outcome.schemas import OutcomeSchema from dataservice.api.common.views import CRUDView from dataservice.api.common.schemas import filter_schema_factory class OutcomeListAPI(CRUDView): endpoint = 'outcomes_list' rule = '/outcomes' schemas = {'Outcome': OutcomeSchema} @paginated @use_args(filter_schema_factory(OutcomeSchema), locations=('query',)) def get(self, filter_params, after, limit): study_id = filter_params.pop('study_id', None) q = Outcome.query.filter_by(**filter_params) from dataservice.api.participant.models import Participant if study_id: q = (q.join(Participant.outcomes) .filter(Participant.study_id == study_id)) return (OutcomeSchema(many=True) .jsonify(Pagination(q, after, limit))) def post(self): body = request.get_json(force=True) try: o = OutcomeSchema(strict=True).load(body).data except ValidationError as e: abort(400, 'could not create outcome: {}'.format(e.messages)) db.session.add(o) db.session.commit() return OutcomeSchema(201, 'outcome {} created' .format(o.kf_id)).jsonify(o), 201 class OutcomeAPI(CRUDView): endpoint = 'outcomes' rule = '/outcomes/<string:kf_id>' schemas = {'Outcome': OutcomeSchema} def get(self, kf_id): o = Outcome.query.get(kf_id) if o is None: abort(404, 'could not find {} `{}`' .format('outcome', kf_id)) return OutcomeSchema().jsonify(o) def patch(self, kf_id): o = Outcome.query.get(kf_id) if o is None: abort(404, 'could not find {} `{}`'.format('outcome', kf_id)) body = request.get_json(force=True) or {} try: o = OutcomeSchema(strict=True).load(body, instance=o, partial=True).data except ValidationError as e: abort(400, 'could not update outcome: {}'.format(e.messages)) db.session.add(o) db.session.commit() return OutcomeSchema(200, 'outcome {} updated' .format(o.kf_id)).jsonify(o), 200 def delete(self, kf_id): o = Outcome.query.get(kf_id) if o is None: abort(404, 'could not find {} `{}`'.format('outcome', kf_id)) db.session.delete(o) db.session.commit() return OutcomeSchema(200, 'outcome {} deleted' .format(o.kf_id)).jsonify(o), 200
true
true
f72a48ddc595ceca85ebaf70bdc5761b2632240d
630
py
Python
level.py
FernandoCamousseigt/testapp
d7466584f5eb5c96463178c21ede571d6ea33510
[ "MIT" ]
null
null
null
level.py
FernandoCamousseigt/testapp
d7466584f5eb5c96463178c21ede571d6ea33510
[ "MIT" ]
null
null
null
level.py
FernandoCamousseigt/testapp
d7466584f5eb5c96463178c21ede571d6ea33510
[ "MIT" ]
null
null
null
def choose_level(n_pregunta, p_level): # Construir lógica para escoger el nivel ################################################## #pass if n_pregunta <= int(p_level): level = "basicas" elif n_pregunta <= 2 * p_level: level = "intermedias" else: level = "avanzadas" ################################################## return level if __name__ == '__main__': # verificar resultados print(choose_level(2, 2)) # básicas print(choose_level(3, 2)) # intermedias print(choose_level(7, 2)) # avanzadas print(choose_level(4, 3)) # intermedias
27.391304
54
0.509524
def choose_level(n_pregunta, p_level):
true
true
f72a4969cc9a1aedd1ca60e296ba23ac682ec15b
3,433
py
Python
verde/tests/test_scipy.py
djhoese/verde
ad14acf94717ee5c6672559f40576f65989753a5
[ "BSD-3-Clause" ]
null
null
null
verde/tests/test_scipy.py
djhoese/verde
ad14acf94717ee5c6672559f40576f65989753a5
[ "BSD-3-Clause" ]
null
null
null
verde/tests/test_scipy.py
djhoese/verde
ad14acf94717ee5c6672559f40576f65989753a5
[ "BSD-3-Clause" ]
null
null
null
""" Test the scipy based interpolator. """ import warnings import pytest import pandas as pd import numpy as np import numpy.testing as npt from ..scipygridder import ScipyGridder from ..coordinates import grid_coordinates from ..datasets.synthetic import CheckerBoard def test_scipy_gridder_same_points(): "See if the gridder recovers known points." region = (1000, 5000, -8000, -7000) synth = CheckerBoard(region=region) data = synth.scatter(size=1000, random_state=0) coords = (data.easting, data.northing) # The interpolation should be perfect on top of the data points for method in ["nearest", "linear", "cubic"]: grd = ScipyGridder(method=method) grd.fit(coords, data.scalars) predicted = grd.predict(coords) npt.assert_allclose(predicted, data.scalars) npt.assert_allclose(grd.score(coords, data.scalars), 1) def test_scipy_gridder(): "See if the gridder recovers known points." synth = CheckerBoard(region=(1000, 5000, -8000, -6000)) data = synth.scatter(size=20000, random_state=0) coords = (data.easting, data.northing) pt_coords = (3000, -7000) true_data = synth.predict(pt_coords) # nearest will never be too close to the truth grd = ScipyGridder("cubic").fit(coords, data.scalars) npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=2) grd = ScipyGridder("linear").fit(coords, data.scalars) npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=1) def test_scipy_gridder_region(): "See if the region is gotten from the data is correct." region = (1000, 5000, -8000, -6000) synth = CheckerBoard(region=region) # Test using xarray objects grid = synth.grid() coords = grid_coordinates(region, grid.scalars.shape) grd = ScipyGridder().fit(coords, grid.scalars) npt.assert_allclose(grd.region_, region) # Test using pandas objects data = pd.DataFrame( { "easting": coords[0].ravel(), "northing": coords[1].ravel(), "scalars": grid.scalars.values.ravel(), } ) grd = ScipyGridder().fit((data.easting, data.northing), data.scalars) npt.assert_allclose(grd.region_, region) def test_scipy_gridder_extra_args(): "Passing in extra arguments to scipy" data = CheckerBoard().scatter(random_state=100) coords = (data.easting, data.northing) grd = ScipyGridder(method="linear", extra_args=dict(rescale=True)) grd.fit(coords, data.scalars) predicted = grd.predict(coords) npt.assert_allclose(predicted, data.scalars) def test_scipy_gridder_fails(): "fit should fail for invalid method name" data = CheckerBoard().scatter(random_state=0) grd = ScipyGridder(method="some invalid method name") with pytest.raises(ValueError): grd.fit((data.easting, data.northing), data.scalars) def test_scipy_gridder_warns(): "Check that a warning is issued when using weights." data = CheckerBoard().scatter(random_state=100) weights = np.ones_like(data.scalars) grd = ScipyGridder() msg = "ScipyGridder does not support weights and they will be ignored." with warnings.catch_warnings(record=True) as warn: grd.fit((data.easting, data.northing), data.scalars, weights=weights) assert len(warn) == 1 assert issubclass(warn[-1].category, UserWarning) assert str(warn[-1].message) == msg
36.136842
77
0.696767
import warnings import pytest import pandas as pd import numpy as np import numpy.testing as npt from ..scipygridder import ScipyGridder from ..coordinates import grid_coordinates from ..datasets.synthetic import CheckerBoard def test_scipy_gridder_same_points(): region = (1000, 5000, -8000, -7000) synth = CheckerBoard(region=region) data = synth.scatter(size=1000, random_state=0) coords = (data.easting, data.northing) for method in ["nearest", "linear", "cubic"]: grd = ScipyGridder(method=method) grd.fit(coords, data.scalars) predicted = grd.predict(coords) npt.assert_allclose(predicted, data.scalars) npt.assert_allclose(grd.score(coords, data.scalars), 1) def test_scipy_gridder(): synth = CheckerBoard(region=(1000, 5000, -8000, -6000)) data = synth.scatter(size=20000, random_state=0) coords = (data.easting, data.northing) pt_coords = (3000, -7000) true_data = synth.predict(pt_coords) grd = ScipyGridder("cubic").fit(coords, data.scalars) npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=2) grd = ScipyGridder("linear").fit(coords, data.scalars) npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=1) def test_scipy_gridder_region(): region = (1000, 5000, -8000, -6000) synth = CheckerBoard(region=region) grid = synth.grid() coords = grid_coordinates(region, grid.scalars.shape) grd = ScipyGridder().fit(coords, grid.scalars) npt.assert_allclose(grd.region_, region) data = pd.DataFrame( { "easting": coords[0].ravel(), "northing": coords[1].ravel(), "scalars": grid.scalars.values.ravel(), } ) grd = ScipyGridder().fit((data.easting, data.northing), data.scalars) npt.assert_allclose(grd.region_, region) def test_scipy_gridder_extra_args(): data = CheckerBoard().scatter(random_state=100) coords = (data.easting, data.northing) grd = ScipyGridder(method="linear", extra_args=dict(rescale=True)) grd.fit(coords, data.scalars) predicted = grd.predict(coords) npt.assert_allclose(predicted, data.scalars) def test_scipy_gridder_fails(): data = CheckerBoard().scatter(random_state=0) grd = ScipyGridder(method="some invalid method name") with pytest.raises(ValueError): grd.fit((data.easting, data.northing), data.scalars) def test_scipy_gridder_warns(): data = CheckerBoard().scatter(random_state=100) weights = np.ones_like(data.scalars) grd = ScipyGridder() msg = "ScipyGridder does not support weights and they will be ignored." with warnings.catch_warnings(record=True) as warn: grd.fit((data.easting, data.northing), data.scalars, weights=weights) assert len(warn) == 1 assert issubclass(warn[-1].category, UserWarning) assert str(warn[-1].message) == msg
true
true
f72a4a1445d38081650f42268e4ec5cd183fd71f
776
py
Python
test/azure/Expected/AcceptanceTests/Lro/lro/__init__.py
tasherif-msft/autorest.python
5b0121bcfa802aedaeda36990e8bcaa2b7e26b14
[ "MIT" ]
null
null
null
test/azure/Expected/AcceptanceTests/Lro/lro/__init__.py
tasherif-msft/autorest.python
5b0121bcfa802aedaeda36990e8bcaa2b7e26b14
[ "MIT" ]
null
null
null
test/azure/Expected/AcceptanceTests/Lro/lro/__init__.py
tasherif-msft/autorest.python
5b0121bcfa802aedaeda36990e8bcaa2b7e26b14
[ "MIT" ]
null
null
null
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from ._auto_rest_long_running_operation_test_service import AutoRestLongRunningOperationTestService from ._version import VERSION __version__ = VERSION __all__ = ['AutoRestLongRunningOperationTestService'] try: from ._patch import patch_sdk # type: ignore patch_sdk() except ImportError: pass
38.8
99
0.641753
from ._auto_rest_long_running_operation_test_service import AutoRestLongRunningOperationTestService from ._version import VERSION __version__ = VERSION __all__ = ['AutoRestLongRunningOperationTestService'] try: from ._patch import patch_sdk patch_sdk() except ImportError: pass
true
true
f72a4bc72168d2050ab7b6bbeddb4ba77db329b8
5,324
py
Python
python_modules/libraries/dagster-mssql/dagster_mssql/utils.py
nc-sika/dagster
ee56ee6ee26eb25cb03dd229716ed9af2cad0538
[ "Apache-2.0" ]
null
null
null
python_modules/libraries/dagster-mssql/dagster_mssql/utils.py
nc-sika/dagster
ee56ee6ee26eb25cb03dd229716ed9af2cad0538
[ "Apache-2.0" ]
null
null
null
python_modules/libraries/dagster-mssql/dagster_mssql/utils.py
nc-sika/dagster
ee56ee6ee26eb25cb03dd229716ed9af2cad0538
[ "Apache-2.0" ]
null
null
null
import logging import time import urllib from contextlib import contextmanager import pyodbc import sqlalchemy as db from dagster import Field, IntSource, StringSource, check from dagster.core.storage.sql import get_alembic_config, handle_schema_errors from sqlalchemy.ext.compiler import compiles MSSQL_POOL_RECYCLE = 3600 class DagsterMSSQLException(Exception): pass def mssql_config(): return { "mssql_url": Field(StringSource, is_required=False), "mssql_db": Field( { "username": StringSource, "password": StringSource, "hostname": StringSource, "db_name": StringSource, "port": Field(IntSource, is_required=False, default_value=1433), "driver": Field(StringSource, is_required=False, default_value="{ODBC Driver 17 for SQL Server}"), "driver_opts": Field(StringSource, is_required=False, default_value="") }, is_required=False, ), "should_autocreate_tables": Field(bool, is_required=False, default_value=True), } def mssql_url_from_config(config_value): if config_value.get("mssql_url"): check.invariant( not "mssql_db" in config_value, "mssql storage config must have exactly one of `mssql_url` or `mssql_db`", ) return config_value["mssql_url"] else: check.invariant( "mssql_db" in config_value, "mssql storage config must have exactly one of `mssql_url` or `mssql_db`", ) return get_conn_string(**config_value["mssql_db"]) def get_conn_string(username, password, hostname, db_name, port="1433", driver="{ODBC Driver 17 for SQL Server}", driver_opts=""): params = urllib.parse.quote_plus(f"DRIVER={driver};" f"SERVER={hostname};" f"DATABASE={db_name};" f"UID={username};" f"PWD={password};" f"PORT={port};" f"{driver_opts}") return f"mssql+pyodbc:///?odbc_connect={params}" def retry_mssql_creation_fn(fn, retry_limit=5, retry_wait=0.2): # Retry logic to recover from the case where two processes are creating # tables at the same time using sqlalchemy check.callable_param(fn, "fn") check.int_param(retry_limit, "retry_limit") check.numeric_param(retry_wait, "retry_wait") while True: try: return fn() except ( pyodbc.ProgrammingError, pyodbc.IntegrityError, db.exc.ProgrammingError, db.exc.IntegrityError, ) as exc: logging.warning("Retrying failed database creation") if retry_limit == 0: raise DagsterMSSQLException("too many retries for DB creation") from exc time.sleep(retry_wait) retry_limit -= 1 def retry_mssql_connection_fn(fn, retry_limit=5, retry_wait=0.2): """Reusable retry logic for any MSSQL connection functions that may fail. Intended to be used anywhere we connect to MSSQL, to gracefully handle transient connection issues. """ check.callable_param(fn, "fn") check.int_param(retry_limit, "retry_limit") check.numeric_param(retry_wait, "retry_wait") while True: try: return fn() except ( pyodbc.DatabaseError, pyodbc.OperationalError, db.exc.DatabaseError, db.exc.OperationalError, ) as exc: logging.warning("Retrying failed database connection") if retry_limit == 0: raise DagsterMSSQLException("too many retries for DB connection") from exc time.sleep(retry_wait) retry_limit -= 1 def wait_for_connection(conn_string, retry_limit=5, retry_wait=0.2): retry_mssql_connection_fn( lambda: pyodbc.connect(conn_string), retry_limit=retry_limit, retry_wait=retry_wait, ) return True def mssql_alembic_config(dunder_file): return get_alembic_config( dunder_file, config_path="../alembic/alembic.ini", script_path="../alembic/" ) @contextmanager def create_mssql_connection(engine, dunder_file, storage_type_desc=None): check.inst_param(engine, "engine", db.engine.Engine) check.str_param(dunder_file, "dunder_file") check.opt_str_param(storage_type_desc, "storage_type_desc", "") if storage_type_desc: storage_type_desc += " " else: storage_type_desc = "" conn = None try: # Retry connection to gracefully handle transient connection issues conn = retry_mssql_connection_fn(engine.connect) with handle_schema_errors( conn, mssql_alembic_config(dunder_file), msg="MSSQL {}storage requires migration".format(storage_type_desc), ): yield conn finally: if conn: conn.close() @compiles(db.types.TIMESTAMP, "mssql") def compile_timestamp_mssql(_element, _compiler, **_kw): return f"DATETIME2" @compiles(db.DateTime, "mssql") def compile_datetime_mssql(_element, _compiler, **_kw): return f"DATETIME2"
32.072289
114
0.628475
import logging import time import urllib from contextlib import contextmanager import pyodbc import sqlalchemy as db from dagster import Field, IntSource, StringSource, check from dagster.core.storage.sql import get_alembic_config, handle_schema_errors from sqlalchemy.ext.compiler import compiles MSSQL_POOL_RECYCLE = 3600 class DagsterMSSQLException(Exception): pass def mssql_config(): return { "mssql_url": Field(StringSource, is_required=False), "mssql_db": Field( { "username": StringSource, "password": StringSource, "hostname": StringSource, "db_name": StringSource, "port": Field(IntSource, is_required=False, default_value=1433), "driver": Field(StringSource, is_required=False, default_value="{ODBC Driver 17 for SQL Server}"), "driver_opts": Field(StringSource, is_required=False, default_value="") }, is_required=False, ), "should_autocreate_tables": Field(bool, is_required=False, default_value=True), } def mssql_url_from_config(config_value): if config_value.get("mssql_url"): check.invariant( not "mssql_db" in config_value, "mssql storage config must have exactly one of `mssql_url` or `mssql_db`", ) return config_value["mssql_url"] else: check.invariant( "mssql_db" in config_value, "mssql storage config must have exactly one of `mssql_url` or `mssql_db`", ) return get_conn_string(**config_value["mssql_db"]) def get_conn_string(username, password, hostname, db_name, port="1433", driver="{ODBC Driver 17 for SQL Server}", driver_opts=""): params = urllib.parse.quote_plus(f"DRIVER={driver};" f"SERVER={hostname};" f"DATABASE={db_name};" f"UID={username};" f"PWD={password};" f"PORT={port};" f"{driver_opts}") return f"mssql+pyodbc:///?odbc_connect={params}" def retry_mssql_creation_fn(fn, retry_limit=5, retry_wait=0.2): check.callable_param(fn, "fn") check.int_param(retry_limit, "retry_limit") check.numeric_param(retry_wait, "retry_wait") while True: try: return fn() except ( pyodbc.ProgrammingError, pyodbc.IntegrityError, db.exc.ProgrammingError, db.exc.IntegrityError, ) as exc: logging.warning("Retrying failed database creation") if retry_limit == 0: raise DagsterMSSQLException("too many retries for DB creation") from exc time.sleep(retry_wait) retry_limit -= 1 def retry_mssql_connection_fn(fn, retry_limit=5, retry_wait=0.2): check.callable_param(fn, "fn") check.int_param(retry_limit, "retry_limit") check.numeric_param(retry_wait, "retry_wait") while True: try: return fn() except ( pyodbc.DatabaseError, pyodbc.OperationalError, db.exc.DatabaseError, db.exc.OperationalError, ) as exc: logging.warning("Retrying failed database connection") if retry_limit == 0: raise DagsterMSSQLException("too many retries for DB connection") from exc time.sleep(retry_wait) retry_limit -= 1 def wait_for_connection(conn_string, retry_limit=5, retry_wait=0.2): retry_mssql_connection_fn( lambda: pyodbc.connect(conn_string), retry_limit=retry_limit, retry_wait=retry_wait, ) return True def mssql_alembic_config(dunder_file): return get_alembic_config( dunder_file, config_path="../alembic/alembic.ini", script_path="../alembic/" ) @contextmanager def create_mssql_connection(engine, dunder_file, storage_type_desc=None): check.inst_param(engine, "engine", db.engine.Engine) check.str_param(dunder_file, "dunder_file") check.opt_str_param(storage_type_desc, "storage_type_desc", "") if storage_type_desc: storage_type_desc += " " else: storage_type_desc = "" conn = None try: conn = retry_mssql_connection_fn(engine.connect) with handle_schema_errors( conn, mssql_alembic_config(dunder_file), msg="MSSQL {}storage requires migration".format(storage_type_desc), ): yield conn finally: if conn: conn.close() @compiles(db.types.TIMESTAMP, "mssql") def compile_timestamp_mssql(_element, _compiler, **_kw): return f"DATETIME2" @compiles(db.DateTime, "mssql") def compile_datetime_mssql(_element, _compiler, **_kw): return f"DATETIME2"
true
true
f72a4bffa2fd94ea50df6697d9321a5dbb611f66
5,120
py
Python
instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py
willarmiros/opentelemetry-python-contrib
0d34ef26b75f9a3bc275bf828b5a806d39ba1a40
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py
willarmiros/opentelemetry-python-contrib
0d34ef26b75f9a3bc275bf828b5a806d39ba1a40
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py
willarmiros/opentelemetry-python-contrib
0d34ef26b75f9a3bc275bf828b5a806d39ba1a40
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
# Copyright The OpenTelemetry 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. """ This library allows tracing HTTP elasticsearch made by the `elasticsearch <https://elasticsearch-py.readthedocs.io/en/master/>`_ library. Usage ----- .. code-block:: python from opentelemetry.instrumentation.elasticsearch import ElasticsearchInstrumentor import elasticsearch # instrument elasticsearch ElasticsearchInstrumentor().instrument() # Using elasticsearch as normal now will automatically generate spans es = elasticsearch.Elasticsearch() es.index(index='my-index', doc_type='my-type', id=1, body={'my': 'data', 'timestamp': datetime.now()}) es.get(index='my-index', doc_type='my-type', id=1) API --- Elasticsearch instrumentation prefixes operation names with the string "Elasticsearch". This can be changed to a different string by either setting the `OTEL_PYTHON_ELASTICSEARCH_NAME_PREFIX` environment variable or by passing the prefix as an argument to the instrumentor. For example, .. code-block:: python ElasticsearchInstrumentor("my-custom-prefix").instrument() """ from logging import getLogger from os import environ from typing import Collection import elasticsearch import elasticsearch.exceptions from wrapt import wrap_function_wrapper as _wrap from opentelemetry.instrumentation.elasticsearch.package import _instruments from opentelemetry.instrumentation.elasticsearch.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import SpanKind, get_tracer logger = getLogger(__name__) # Values to add as tags from the actual # payload returned by Elasticsearch, if any. _ATTRIBUTES_FROM_RESULT = [ "found", "timed_out", "took", ] _DEFALT_OP_NAME = "request" class ElasticsearchInstrumentor(BaseInstrumentor): """An instrumentor for elasticsearch See `BaseInstrumentor` """ def __init__(self, span_name_prefix=None): if not span_name_prefix: span_name_prefix = environ.get( "OTEL_PYTHON_ELASTICSEARCH_NAME_PREFIX", "Elasticsearch", ) self._span_name_prefix = span_name_prefix.strip() super().__init__() def instrumentation_dependencies(self) -> Collection[str]: return _instruments def _instrument(self, **kwargs): """ Instruments elasticsarch module """ tracer_provider = kwargs.get("tracer_provider") tracer = get_tracer(__name__, __version__, tracer_provider) _wrap( elasticsearch, "Transport.perform_request", _wrap_perform_request(tracer, self._span_name_prefix), ) def _uninstrument(self, **kwargs): unwrap(elasticsearch.Transport, "perform_request") def _wrap_perform_request(tracer, span_name_prefix): # pylint: disable=R0912 def wrapper(wrapped, _, args, kwargs): method = url = None try: method, url, *_ = args except IndexError: logger.warning( "expected perform_request to receive two positional arguments. " "Got %d", len(args), ) op_name = span_name_prefix + (url or method or _DEFALT_OP_NAME) params = kwargs.get("params", {}) body = kwargs.get("body", None) with tracer.start_as_current_span( op_name, kind=SpanKind.CLIENT, ) as span: if span.is_recording(): attributes = { SpanAttributes.DB_SYSTEM: "elasticsearch", } if url: attributes["elasticsearch.url"] = url if method: attributes["elasticsearch.method"] = method if body: attributes[SpanAttributes.DB_STATEMENT] = str(body) if params: attributes["elasticsearch.params"] = str(params) for key, value in attributes.items(): span.set_attribute(key, value) rv = wrapped(*args, **kwargs) if isinstance(rv, dict) and span.is_recording(): for member in _ATTRIBUTES_FROM_RESULT: if member in rv: span.set_attribute( "elasticsearch.{0}".format(member), str(rv[member]), ) return rv return wrapper
32.820513
106
0.659766
from logging import getLogger from os import environ from typing import Collection import elasticsearch import elasticsearch.exceptions from wrapt import wrap_function_wrapper as _wrap from opentelemetry.instrumentation.elasticsearch.package import _instruments from opentelemetry.instrumentation.elasticsearch.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import SpanKind, get_tracer logger = getLogger(__name__) _ATTRIBUTES_FROM_RESULT = [ "found", "timed_out", "took", ] _DEFALT_OP_NAME = "request" class ElasticsearchInstrumentor(BaseInstrumentor): def __init__(self, span_name_prefix=None): if not span_name_prefix: span_name_prefix = environ.get( "OTEL_PYTHON_ELASTICSEARCH_NAME_PREFIX", "Elasticsearch", ) self._span_name_prefix = span_name_prefix.strip() super().__init__() def instrumentation_dependencies(self) -> Collection[str]: return _instruments def _instrument(self, **kwargs): tracer_provider = kwargs.get("tracer_provider") tracer = get_tracer(__name__, __version__, tracer_provider) _wrap( elasticsearch, "Transport.perform_request", _wrap_perform_request(tracer, self._span_name_prefix), ) def _uninstrument(self, **kwargs): unwrap(elasticsearch.Transport, "perform_request") def _wrap_perform_request(tracer, span_name_prefix): def wrapper(wrapped, _, args, kwargs): method = url = None try: method, url, *_ = args except IndexError: logger.warning( "expected perform_request to receive two positional arguments. " "Got %d", len(args), ) op_name = span_name_prefix + (url or method or _DEFALT_OP_NAME) params = kwargs.get("params", {}) body = kwargs.get("body", None) with tracer.start_as_current_span( op_name, kind=SpanKind.CLIENT, ) as span: if span.is_recording(): attributes = { SpanAttributes.DB_SYSTEM: "elasticsearch", } if url: attributes["elasticsearch.url"] = url if method: attributes["elasticsearch.method"] = method if body: attributes[SpanAttributes.DB_STATEMENT] = str(body) if params: attributes["elasticsearch.params"] = str(params) for key, value in attributes.items(): span.set_attribute(key, value) rv = wrapped(*args, **kwargs) if isinstance(rv, dict) and span.is_recording(): for member in _ATTRIBUTES_FROM_RESULT: if member in rv: span.set_attribute( "elasticsearch.{0}".format(member), str(rv[member]), ) return rv return wrapper
true
true
f72a4c06bbd80f8c7dad227a0878c7eb28b2829d
7,421
py
Python
examples/ex_binding_textures.py
SebastianRodriguezR/grafica
c87d6d1906a4cf49520ef213f1e4ba6e1ead8c4e
[ "MIT" ]
12
2021-08-17T12:57:39.000Z
2022-03-28T02:52:30.000Z
examples/ex_binding_textures.py
SebastianRodriguezR/grafica
c87d6d1906a4cf49520ef213f1e4ba6e1ead8c4e
[ "MIT" ]
null
null
null
examples/ex_binding_textures.py
SebastianRodriguezR/grafica
c87d6d1906a4cf49520ef213f1e4ba6e1ead8c4e
[ "MIT" ]
13
2021-08-17T03:23:21.000Z
2022-03-20T21:40:16.000Z
# coding=utf-8 """Using 2 different textures in the same Fragment Shader""" import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import grafica.transformations as tr import grafica.basic_shapes as bs import grafica.easy_shaders as es from grafica.assets_path import getAssetPath from grafica.gpu_shape import GPUShape, SIZE_IN_BYTES __author__ = "Sebastián Olmos" __license__ = "MIT" # We extend the functionality of a GPUShape with an additional texture. class TexGPUShape(GPUShape): def __init__(self): """VAO, VBO, EBO and texture handlers to GPU memory""" super().__init__() self.texture2 = None def __str__(self): return super().__str__() + " tex=" + str(self.texture2) def clear(self): """Freeing GPU memory""" super().clear() if self.texture2 != None: glDeleteTextures(1, [self.texture2]) # Shader that handles two textures class DoubleTextureTransformShaderProgram: def __init__(self): vertex_shader = """ #version 330 uniform mat4 transform; in vec3 position; in vec2 texCoords; out vec2 outTexCoords; void main() { gl_Position = transform * vec4(position, 1.0f); outTexCoords = texCoords; } """ fragment_shader = """ #version 330 // gl_FragCoord contains the (x,y) fragment coordinates of the window. // We also set the origin to the upper left corner layout(origin_upper_left) in vec4 gl_FragCoord; in vec2 outTexCoords; out vec4 outColor; uniform sampler2D upTexture; uniform sampler2D downTexture; uniform float mousePosY; void main() { vec4 finalColor; if ( gl_FragCoord.y > mousePosY){ finalColor = texture(downTexture, outTexCoords); } else { finalColor = texture(upTexture, outTexCoords); } outColor = finalColor; } """ # Binding artificial vertex array object for validation VAO = glGenVertexArrays(1) glBindVertexArray(VAO) # Compiling our shader program self.shaderProgram = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) def setupVAO(self, gpuShape): glBindVertexArray(gpuShape.vao) glBindBuffer(GL_ARRAY_BUFFER, gpuShape.vbo) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gpuShape.ebo) # 3d vertices + 2d texture coordinates => 3*4 + 2*4 = 20 bytes position = glGetAttribLocation(self.shaderProgram, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) texCoords = glGetAttribLocation(self.shaderProgram, "texCoords") glVertexAttribPointer(texCoords, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(3 * SIZE_IN_BYTES)) glEnableVertexAttribArray(texCoords) # Unbinding current vao glBindVertexArray(0) def drawCall(self, gpuShape, mode=GL_TRIANGLES): assert isinstance(gpuShape, TexGPUShape) glBindVertexArray(gpuShape.vao) # Binding the first texture glActiveTexture(GL_TEXTURE0 + 0) glBindTexture(GL_TEXTURE_2D, gpuShape.texture) # Binding the second texture glActiveTexture(GL_TEXTURE0 + 1) glBindTexture(GL_TEXTURE_2D, gpuShape.texture2) glDrawElements(mode, gpuShape.size, GL_UNSIGNED_INT, None) # Unbind the current VAO glBindVertexArray(0) # A class to store the application control class Controller: def __init__(self): self.fillPolygon = True self.mousePos = (0.0, 0.0) # global controller as communication with the callback function controller = Controller() def on_key(window, key, scancode, action, mods): if action != glfw.PRESS: return global controller if key == glfw.KEY_SPACE: controller.fillPolygon = not controller.fillPolygon elif key == glfw.KEY_ESCAPE: glfw.set_window_should_close(window, True) else: print('Unknown key') def cursor_pos_callback(window, x, y): global controller controller.mousePos = (x,y) if __name__ == "__main__": # Initialize glfw if not glfw.init(): sys.exit(1) width = 600 height = 600 window = glfw.create_window(width, height, "Double binding", None, None) if not window: glfw.terminate() glfw.set_window_should_close(window, True) glfw.make_context_current(window) # Connecting the callback function 'on_key' to handle keyboard events glfw.set_key_callback(window, on_key) glfw.set_cursor_pos_callback(window, cursor_pos_callback) # A simple shader program with position and texture coordinates as inputs. pipeline = DoubleTextureTransformShaderProgram() # Telling OpenGL to use our shader program # Setting up the clear screen color glClearColor(0.25, 0.25, 0.25, 1.0) # Creating shapes on GPU memory shape = bs.createTextureQuad(1, 1) gpuShape = TexGPUShape().initBuffers() pipeline.setupVAO(gpuShape) gpuShape.fillBuffers(shape.vertices, shape.indices, GL_STATIC_DRAW) gpuShape.texture = es.textureSimpleSetup( getAssetPath("torres-del-paine-sq.jpg"), GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR) gpuShape.texture2 = es.textureSimpleSetup( getAssetPath("red_woodpecker.jpg"), GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR) currentMousePos = [width/2, height/2] while not glfw.window_should_close(window): # Using GLFW to check for input events glfw.poll_events() if (controller.fillPolygon): glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) theta = 0.3 * np.sin(glfw.get_time()) # Clearing the screen in both, color and depth glClear(GL_COLOR_BUFFER_BIT) glUseProgram(pipeline.shaderProgram) # Drawing the shapes glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, np.matmul( tr.shearing(0,theta,0,0,0,0), tr.uniformScale(1.5) ) ) # Binding samplers to both texture units glUniform1i(glGetUniformLocation(pipeline.shaderProgram, "upTexture"), 0) glUniform1i(glGetUniformLocation(pipeline.shaderProgram, "downTexture"), 1) # Sending the mouse vertical location to our shader glUniform1f(glGetUniformLocation(pipeline.shaderProgram, "mousePosY"), controller.mousePos[1]) pipeline.drawCall(gpuShape) # Once the render is done, buffers are swapped, showing only the complete scene. glfw.swap_buffers(window) # freeing GPU memory gpuShape.clear() glfw.terminate()
30.413934
106
0.650721
import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import grafica.transformations as tr import grafica.basic_shapes as bs import grafica.easy_shaders as es from grafica.assets_path import getAssetPath from grafica.gpu_shape import GPUShape, SIZE_IN_BYTES __author__ = "Sebastián Olmos" __license__ = "MIT" class TexGPUShape(GPUShape): def __init__(self): super().__init__() self.texture2 = None def __str__(self): return super().__str__() + " tex=" + str(self.texture2) def clear(self): super().clear() if self.texture2 != None: glDeleteTextures(1, [self.texture2]) class DoubleTextureTransformShaderProgram: def __init__(self): vertex_shader = """ #version 330 uniform mat4 transform; in vec3 position; in vec2 texCoords; out vec2 outTexCoords; void main() { gl_Position = transform * vec4(position, 1.0f); outTexCoords = texCoords; } """ fragment_shader = """ #version 330 // gl_FragCoord contains the (x,y) fragment coordinates of the window. // We also set the origin to the upper left corner layout(origin_upper_left) in vec4 gl_FragCoord; in vec2 outTexCoords; out vec4 outColor; uniform sampler2D upTexture; uniform sampler2D downTexture; uniform float mousePosY; void main() { vec4 finalColor; if ( gl_FragCoord.y > mousePosY){ finalColor = texture(downTexture, outTexCoords); } else { finalColor = texture(upTexture, outTexCoords); } outColor = finalColor; } """ VAO = glGenVertexArrays(1) glBindVertexArray(VAO) self.shaderProgram = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) def setupVAO(self, gpuShape): glBindVertexArray(gpuShape.vao) glBindBuffer(GL_ARRAY_BUFFER, gpuShape.vbo) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gpuShape.ebo) position = glGetAttribLocation(self.shaderProgram, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) texCoords = glGetAttribLocation(self.shaderProgram, "texCoords") glVertexAttribPointer(texCoords, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(3 * SIZE_IN_BYTES)) glEnableVertexAttribArray(texCoords) glBindVertexArray(0) def drawCall(self, gpuShape, mode=GL_TRIANGLES): assert isinstance(gpuShape, TexGPUShape) glBindVertexArray(gpuShape.vao) glActiveTexture(GL_TEXTURE0 + 0) glBindTexture(GL_TEXTURE_2D, gpuShape.texture) glActiveTexture(GL_TEXTURE0 + 1) glBindTexture(GL_TEXTURE_2D, gpuShape.texture2) glDrawElements(mode, gpuShape.size, GL_UNSIGNED_INT, None) glBindVertexArray(0) class Controller: def __init__(self): self.fillPolygon = True self.mousePos = (0.0, 0.0) controller = Controller() def on_key(window, key, scancode, action, mods): if action != glfw.PRESS: return global controller if key == glfw.KEY_SPACE: controller.fillPolygon = not controller.fillPolygon elif key == glfw.KEY_ESCAPE: glfw.set_window_should_close(window, True) else: print('Unknown key') def cursor_pos_callback(window, x, y): global controller controller.mousePos = (x,y) if __name__ == "__main__": if not glfw.init(): sys.exit(1) width = 600 height = 600 window = glfw.create_window(width, height, "Double binding", None, None) if not window: glfw.terminate() glfw.set_window_should_close(window, True) glfw.make_context_current(window) glfw.set_key_callback(window, on_key) glfw.set_cursor_pos_callback(window, cursor_pos_callback) pipeline = DoubleTextureTransformShaderProgram() glClearColor(0.25, 0.25, 0.25, 1.0) shape = bs.createTextureQuad(1, 1) gpuShape = TexGPUShape().initBuffers() pipeline.setupVAO(gpuShape) gpuShape.fillBuffers(shape.vertices, shape.indices, GL_STATIC_DRAW) gpuShape.texture = es.textureSimpleSetup( getAssetPath("torres-del-paine-sq.jpg"), GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR) gpuShape.texture2 = es.textureSimpleSetup( getAssetPath("red_woodpecker.jpg"), GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR) currentMousePos = [width/2, height/2] while not glfw.window_should_close(window): glfw.poll_events() if (controller.fillPolygon): glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) theta = 0.3 * np.sin(glfw.get_time()) glClear(GL_COLOR_BUFFER_BIT) glUseProgram(pipeline.shaderProgram) glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, np.matmul( tr.shearing(0,theta,0,0,0,0), tr.uniformScale(1.5) ) ) glUniform1i(glGetUniformLocation(pipeline.shaderProgram, "upTexture"), 0) glUniform1i(glGetUniformLocation(pipeline.shaderProgram, "downTexture"), 1) glUniform1f(glGetUniformLocation(pipeline.shaderProgram, "mousePosY"), controller.mousePos[1]) pipeline.drawCall(gpuShape) glfw.swap_buffers(window) gpuShape.clear() glfw.terminate()
true
true
f72a4c25bda8e56afb5812475a76671822928e38
4,267
py
Python
src/run_evaluation.py
liushulinle/CRACSpell
faff01521b08032c4efa89bbb2dc942a6327bc53
[ "MIT" ]
2
2022-03-23T07:17:02.000Z
2022-03-24T07:09:04.000Z
src/run_evaluation.py
liushulinle/CRASpell
e0b495ed8424be7fdbd7fc3ef8c2919ab195b0e4
[ "MIT" ]
null
null
null
src/run_evaluation.py
liushulinle/CRASpell
e0b495ed8424be7fdbd7fc3ef8c2919ab195b0e4
[ "MIT" ]
null
null
null
import sys, os import numpy as np import tensorflow as tf from bert_tagging import DataProcessor, BertTagging import modeling import optimization import time from tagging_eval import score_f tf.logging.set_verbosity(tf.logging.ERROR) DEBUG = False def evaluate(FLAGS, label_list=None): gpuid = FLAGS.gpuid max_sen_len = FLAGS.max_sen_len test_file = FLAGS.test_path out_dir = FLAGS.output_dir model_dir = FLAGS.model_dir batch_size = FLAGS.batch_size bert_config_path = './conf/bert_config.json' vocob_file = './conf/vocab.txt' os.environ["CUDA_VISIBLE_DEVICES"] = gpuid # data processor data_processor = DataProcessor(test_file, max_sen_len, vocob_file, out_dir, label_list=None, is_training=False) test_num = data_processor.num_examples test_data = data_processor.build_data_generator(batch_size) iterator = test_data.make_one_shot_iterator() input_ids, input_mask, segment_ids, lmask, label_ids, masked_sample = iterator.get_next() #load model model = BertTagging(bert_config_path, num_class=len(data_processor.get_label_list()), max_sen_len=max_sen_len) (pred_loss, pred_result, gold_result, gold_mask, r_loss) = model.create_model(input_ids, input_mask, segment_ids, lmask, label_ids, batch_size=batch_size, masked_sample=masked_sample, is_training=False) tf_config = tf.ConfigProto(log_device_placement=False) tf_config.gpu_options.allow_growth = True sess = tf.Session(config=tf_config) ckpt = tf.train.get_checkpoint_state(model_dir) saver = tf.train.Saver() saver.restore(sess, ckpt.model_checkpoint_path) label_list = data_processor.label_list ans = [] all_inputs, all_golds, all_preds = [], [], [] all_py_inputs, all_py_golds, all_py_preds = [], [], [] all_fusion_preds = [] all_inputs_sent, all_golds_sent, all_preds_sent = [], [], [] for step in range(test_num // batch_size): inputs, loss_value, preds, golds, gmask = sess.run([input_ids, pred_loss, pred_result, gold_result, gold_mask]) for k in range(batch_size): gsent, psent, isent = [], [], [] for j in range(max_sen_len): if gmask[k][j] == 0: continue all_golds.append(golds[k][j]) all_preds.append(preds[k][j]) all_inputs.append(inputs[k][j]) gsent.append(label_list[golds[k][j]]) psent.append(label_list[preds[k][j]]) isent.append(label_list[inputs[k][j]]) all_golds_sent.append(gsent) all_preds_sent.append(psent) all_inputs_sent.append(isent) if DEBUG and step > 5: break fout = open('%s/pred_sent.txt' % out_dir, 'w', encoding='utf-8') fout.writelines('## input/gold/pred TAB ... ...\n') for k in range(len(all_inputs_sent)): for j in range(len(all_inputs_sent[k])): ic = all_inputs_sent[k][j] pc = all_preds_sent[k][j] gc = all_golds_sent[k][j] fout.writelines('%s/%s/%s\t' % (ic, gc, pc)) fout.writelines('\n') fout.close() all_golds = [label_list[k] for k in all_golds] all_preds = [label_list[k] for k in all_preds] all_inputs = [label_list[k] for k in all_inputs] print ('ALL LEN:%d' % len(all_preds)) print('zi result:') p, r, f = score_f((all_inputs, all_golds, all_preds), only_check=False, out_dir=out_dir) return f if __name__ == '__main__': flags = tf.flags ## Required parameters flags.DEFINE_string("gpuid", '0', "The gpu NO. ") ## Optional flags.DEFINE_string("test_path", '', "train path ") flags.DEFINE_string("output_dir", '', "out dir ") flags.DEFINE_string("model_dir", '', "out dir ") flags.DEFINE_integer("batch_size", '1', "out dir ") flags.DEFINE_integer("max_sen_len", 64, 'max_sen_len') flags.mark_flag_as_required('gpuid') flags.mark_flag_as_required('test_path') flags.mark_flag_as_required('output_dir') flags.mark_flag_as_required('max_sen_len') FLAGS = flags.FLAGS print ('Confings:') print ('\tgpuid=', FLAGS.gpuid) print ('\ttest_path=', FLAGS.test_path) print ('\toutput_dir=', FLAGS.output_dir) evaluate(FLAGS, FLAGS.test_path)
38.098214
206
0.668854
import sys, os import numpy as np import tensorflow as tf from bert_tagging import DataProcessor, BertTagging import modeling import optimization import time from tagging_eval import score_f tf.logging.set_verbosity(tf.logging.ERROR) DEBUG = False def evaluate(FLAGS, label_list=None): gpuid = FLAGS.gpuid max_sen_len = FLAGS.max_sen_len test_file = FLAGS.test_path out_dir = FLAGS.output_dir model_dir = FLAGS.model_dir batch_size = FLAGS.batch_size bert_config_path = './conf/bert_config.json' vocob_file = './conf/vocab.txt' os.environ["CUDA_VISIBLE_DEVICES"] = gpuid data_processor = DataProcessor(test_file, max_sen_len, vocob_file, out_dir, label_list=None, is_training=False) test_num = data_processor.num_examples test_data = data_processor.build_data_generator(batch_size) iterator = test_data.make_one_shot_iterator() input_ids, input_mask, segment_ids, lmask, label_ids, masked_sample = iterator.get_next() model = BertTagging(bert_config_path, num_class=len(data_processor.get_label_list()), max_sen_len=max_sen_len) (pred_loss, pred_result, gold_result, gold_mask, r_loss) = model.create_model(input_ids, input_mask, segment_ids, lmask, label_ids, batch_size=batch_size, masked_sample=masked_sample, is_training=False) tf_config = tf.ConfigProto(log_device_placement=False) tf_config.gpu_options.allow_growth = True sess = tf.Session(config=tf_config) ckpt = tf.train.get_checkpoint_state(model_dir) saver = tf.train.Saver() saver.restore(sess, ckpt.model_checkpoint_path) label_list = data_processor.label_list ans = [] all_inputs, all_golds, all_preds = [], [], [] all_py_inputs, all_py_golds, all_py_preds = [], [], [] all_fusion_preds = [] all_inputs_sent, all_golds_sent, all_preds_sent = [], [], [] for step in range(test_num // batch_size): inputs, loss_value, preds, golds, gmask = sess.run([input_ids, pred_loss, pred_result, gold_result, gold_mask]) for k in range(batch_size): gsent, psent, isent = [], [], [] for j in range(max_sen_len): if gmask[k][j] == 0: continue all_golds.append(golds[k][j]) all_preds.append(preds[k][j]) all_inputs.append(inputs[k][j]) gsent.append(label_list[golds[k][j]]) psent.append(label_list[preds[k][j]]) isent.append(label_list[inputs[k][j]]) all_golds_sent.append(gsent) all_preds_sent.append(psent) all_inputs_sent.append(isent) if DEBUG and step > 5: break fout = open('%s/pred_sent.txt' % out_dir, 'w', encoding='utf-8') fout.writelines('## input/gold/pred TAB ... ...\n') for k in range(len(all_inputs_sent)): for j in range(len(all_inputs_sent[k])): ic = all_inputs_sent[k][j] pc = all_preds_sent[k][j] gc = all_golds_sent[k][j] fout.writelines('%s/%s/%s\t' % (ic, gc, pc)) fout.writelines('\n') fout.close() all_golds = [label_list[k] for k in all_golds] all_preds = [label_list[k] for k in all_preds] all_inputs = [label_list[k] for k in all_inputs] print ('ALL LEN:%d' % len(all_preds)) print('zi result:') p, r, f = score_f((all_inputs, all_golds, all_preds), only_check=False, out_dir=out_dir) return f if __name__ == '__main__': flags = tf.flags ing("gpuid", '0', "The gpu NO. ") .DEFINE_string("test_path", '', "train path ") flags.DEFINE_string("output_dir", '', "out dir ") flags.DEFINE_string("model_dir", '', "out dir ") flags.DEFINE_integer("batch_size", '1', "out dir ") flags.DEFINE_integer("max_sen_len", 64, 'max_sen_len') flags.mark_flag_as_required('gpuid') flags.mark_flag_as_required('test_path') flags.mark_flag_as_required('output_dir') flags.mark_flag_as_required('max_sen_len') FLAGS = flags.FLAGS print ('Confings:') print ('\tgpuid=', FLAGS.gpuid) print ('\ttest_path=', FLAGS.test_path) print ('\toutput_dir=', FLAGS.output_dir) evaluate(FLAGS, FLAGS.test_path)
true
true
f72a4c3a75bd42077f335838511586ea852c2671
3,899
py
Python
run.py
ntraut/example
5b7501ee7c8ad4e7c61b3ff8e9b1d3c0380c33de
[ "Apache-2.0" ]
13
2017-04-03T12:09:35.000Z
2021-06-07T09:40:31.000Z
run.py
ntraut/example
5b7501ee7c8ad4e7c61b3ff8e9b1d3c0380c33de
[ "Apache-2.0" ]
13
2016-08-02T18:56:13.000Z
2020-05-15T10:39:19.000Z
run.py
ntraut/example
5b7501ee7c8ad4e7c61b3ff8e9b1d3c0380c33de
[ "Apache-2.0" ]
31
2016-07-28T22:32:58.000Z
2022-01-05T09:13:03.000Z
#!/usr/bin/env python3 import argparse import os import subprocess import nibabel import numpy from glob import glob __version__ = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'version')).read() def run(command, env={}): merged_env = os.environ merged_env.update(env) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, env=merged_env) while True: line = process.stdout.readline() line = str(line, 'utf-8')[:-1] print(line) if line == '' and process.poll() != None: break if process.returncode != 0: raise Exception("Non zero return code: %d"%process.returncode) parser = argparse.ArgumentParser(description='Example BIDS App entrypoint script.') parser.add_argument('bids_dir', help='The directory with the input dataset ' 'formatted according to the BIDS standard.') parser.add_argument('output_dir', help='The directory where the output files ' 'should be stored. If you are running group level analysis ' 'this folder should be prepopulated with the results of the' 'participant level analysis.') parser.add_argument('analysis_level', help='Level of the analysis that will be performed. ' 'Multiple participant level analyses can be run independently ' '(in parallel) using the same output_dir.', choices=['participant', 'group']) parser.add_argument('--participant_label', help='The label(s) of the participant(s) that should be analyzed. The label ' 'corresponds to sub-<participant_label> from the BIDS spec ' '(so it does not include "sub-"). If this parameter is not ' 'provided all subjects should be analyzed. Multiple ' 'participants can be specified with a space separated list.', nargs="+") parser.add_argument('--skip_bids_validator', help='Whether or not to perform BIDS dataset validation', action='store_true') parser.add_argument('-v', '--version', action='version', version='BIDS-App example version {}'.format(__version__)) args = parser.parse_args() if not args.skip_bids_validator: run('bids-validator %s'%args.bids_dir) subjects_to_analyze = [] # only for a subset of subjects if args.participant_label: subjects_to_analyze = args.participant_label # for all subjects else: subject_dirs = glob(os.path.join(args.bids_dir, "sub-*")) subjects_to_analyze = [subject_dir.split("-")[-1] for subject_dir in subject_dirs] # running participant level if args.analysis_level == "participant": # find all T1s and skullstrip them for subject_label in subjects_to_analyze: for T1_file in glob(os.path.join(args.bids_dir, "sub-%s"%subject_label, "anat", "*_T1w.nii*")) + glob(os.path.join(args.bids_dir,"sub-%s"%subject_label,"ses-*","anat", "*_T1w.nii*")): out_file = os.path.split(T1_file)[-1].replace("_T1w.", "_brain.") cmd = "bet %s %s"%(T1_file, os.path.join(args.output_dir, out_file)) print(cmd) run(cmd) # running group level elif args.analysis_level == "group": brain_sizes = [] for subject_label in subjects_to_analyze: for brain_file in glob(os.path.join(args.output_dir, "sub-%s*.nii*"%subject_label)): data = nibabel.load(brain_file).get_data() # calcualte average mask size in voxels brain_sizes.append((data != 0).sum()) with open(os.path.join(args.output_dir, "avg_brain_size.txt"), 'w') as fp: fp.write("Average brain size is %g voxels"%numpy.array(brain_sizes).mean())
44.816092
152
0.633496
import argparse import os import subprocess import nibabel import numpy from glob import glob __version__ = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'version')).read() def run(command, env={}): merged_env = os.environ merged_env.update(env) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, env=merged_env) while True: line = process.stdout.readline() line = str(line, 'utf-8')[:-1] print(line) if line == '' and process.poll() != None: break if process.returncode != 0: raise Exception("Non zero return code: %d"%process.returncode) parser = argparse.ArgumentParser(description='Example BIDS App entrypoint script.') parser.add_argument('bids_dir', help='The directory with the input dataset ' 'formatted according to the BIDS standard.') parser.add_argument('output_dir', help='The directory where the output files ' 'should be stored. If you are running group level analysis ' 'this folder should be prepopulated with the results of the' 'participant level analysis.') parser.add_argument('analysis_level', help='Level of the analysis that will be performed. ' 'Multiple participant level analyses can be run independently ' '(in parallel) using the same output_dir.', choices=['participant', 'group']) parser.add_argument('--participant_label', help='The label(s) of the participant(s) that should be analyzed. The label ' 'corresponds to sub-<participant_label> from the BIDS spec ' '(so it does not include "sub-"). If this parameter is not ' 'provided all subjects should be analyzed. Multiple ' 'participants can be specified with a space separated list.', nargs="+") parser.add_argument('--skip_bids_validator', help='Whether or not to perform BIDS dataset validation', action='store_true') parser.add_argument('-v', '--version', action='version', version='BIDS-App example version {}'.format(__version__)) args = parser.parse_args() if not args.skip_bids_validator: run('bids-validator %s'%args.bids_dir) subjects_to_analyze = [] if args.participant_label: subjects_to_analyze = args.participant_label else: subject_dirs = glob(os.path.join(args.bids_dir, "sub-*")) subjects_to_analyze = [subject_dir.split("-")[-1] for subject_dir in subject_dirs] if args.analysis_level == "participant": for subject_label in subjects_to_analyze: for T1_file in glob(os.path.join(args.bids_dir, "sub-%s"%subject_label, "anat", "*_T1w.nii*")) + glob(os.path.join(args.bids_dir,"sub-%s"%subject_label,"ses-*","anat", "*_T1w.nii*")): out_file = os.path.split(T1_file)[-1].replace("_T1w.", "_brain.") cmd = "bet %s %s"%(T1_file, os.path.join(args.output_dir, out_file)) print(cmd) run(cmd) elif args.analysis_level == "group": brain_sizes = [] for subject_label in subjects_to_analyze: for brain_file in glob(os.path.join(args.output_dir, "sub-%s*.nii*"%subject_label)): data = nibabel.load(brain_file).get_data() brain_sizes.append((data != 0).sum()) with open(os.path.join(args.output_dir, "avg_brain_size.txt"), 'w') as fp: fp.write("Average brain size is %g voxels"%numpy.array(brain_sizes).mean())
true
true
f72a4c44918d4818263c7f5a892eaf25465b4fda
4,108
py
Python
homeassistant/components/azure_devops/__init__.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
6
2016-11-25T06:36:27.000Z
2021-11-16T11:20:23.000Z
homeassistant/components/azure_devops/__init__.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
58
2020-08-03T07:33:02.000Z
2022-03-31T06:02:05.000Z
homeassistant/components/azure_devops/__init__.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
14
2018-08-19T16:28:26.000Z
2021-09-02T18:26:53.000Z
"""Support for Azure DevOps.""" import logging from typing import Any, Dict from aioazuredevops.client import DevOpsClient import aiohttp from homeassistant.components.azure_devops.const import ( CONF_ORG, CONF_PAT, CONF_PROJECT, DATA_AZURE_DEVOPS_CLIENT, DOMAIN, ) from homeassistant.config_entries import ConfigEntry from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import ConfigType, HomeAssistantType _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Set up the Azure DevOps components.""" return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up Azure DevOps from a config entry.""" client = DevOpsClient() try: if entry.data[CONF_PAT] is not None: await client.authorize(entry.data[CONF_PAT], entry.data[CONF_ORG]) if not client.authorized: _LOGGER.warning( "Could not authorize with Azure DevOps. You may need to update your token" ) hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth"}, data=entry.data, ) ) return False await client.get_project(entry.data[CONF_ORG], entry.data[CONF_PROJECT]) except aiohttp.ClientError as exception: _LOGGER.warning(exception) raise ConfigEntryNotReady from exception instance_key = f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}" hass.data.setdefault(instance_key, {})[DATA_AZURE_DEVOPS_CLIENT] = client # Setup components hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: """Unload Azure DevOps config entry.""" del hass.data[f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}"] return await hass.config_entries.async_forward_entry_unload(entry, "sensor") class AzureDevOpsEntity(Entity): """Defines a base Azure DevOps entity.""" def __init__(self, organization: str, project: str, name: str, icon: str) -> None: """Initialize the Azure DevOps entity.""" self._name = name self._icon = icon self._available = True self.organization = organization self.project = project @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def icon(self) -> str: """Return the mdi icon of the entity.""" return self._icon @property def available(self) -> bool: """Return True if entity is available.""" return self._available async def async_update(self) -> None: """Update Azure DevOps entity.""" if await self._azure_devops_update(): self._available = True else: if self._available: _LOGGER.debug( "An error occurred while updating Azure DevOps sensor.", exc_info=True, ) self._available = False async def _azure_devops_update(self) -> None: """Update Azure DevOps entity.""" raise NotImplementedError() class AzureDevOpsDeviceEntity(AzureDevOpsEntity): """Defines a Azure DevOps device entity.""" @property def device_info(self) -> Dict[str, Any]: """Return device information about this Azure DevOps instance.""" return { "identifiers": { ( DOMAIN, self.organization, self.project, ) }, "manufacturer": self.organization, "name": self.project, "entry_type": "service", }
31.358779
94
0.619523
import logging from typing import Any, Dict from aioazuredevops.client import DevOpsClient import aiohttp from homeassistant.components.azure_devops.const import ( CONF_ORG, CONF_PAT, CONF_PROJECT, DATA_AZURE_DEVOPS_CLIENT, DOMAIN, ) from homeassistant.config_entries import ConfigEntry from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import ConfigType, HomeAssistantType _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: client = DevOpsClient() try: if entry.data[CONF_PAT] is not None: await client.authorize(entry.data[CONF_PAT], entry.data[CONF_ORG]) if not client.authorized: _LOGGER.warning( "Could not authorize with Azure DevOps. You may need to update your token" ) hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth"}, data=entry.data, ) ) return False await client.get_project(entry.data[CONF_ORG], entry.data[CONF_PROJECT]) except aiohttp.ClientError as exception: _LOGGER.warning(exception) raise ConfigEntryNotReady from exception instance_key = f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}" hass.data.setdefault(instance_key, {})[DATA_AZURE_DEVOPS_CLIENT] = client hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: del hass.data[f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}"] return await hass.config_entries.async_forward_entry_unload(entry, "sensor") class AzureDevOpsEntity(Entity): def __init__(self, organization: str, project: str, name: str, icon: str) -> None: self._name = name self._icon = icon self._available = True self.organization = organization self.project = project @property def name(self) -> str: return self._name @property def icon(self) -> str: return self._icon @property def available(self) -> bool: return self._available async def async_update(self) -> None: if await self._azure_devops_update(): self._available = True else: if self._available: _LOGGER.debug( "An error occurred while updating Azure DevOps sensor.", exc_info=True, ) self._available = False async def _azure_devops_update(self) -> None: raise NotImplementedError() class AzureDevOpsDeviceEntity(AzureDevOpsEntity): @property def device_info(self) -> Dict[str, Any]: return { "identifiers": { ( DOMAIN, self.organization, self.project, ) }, "manufacturer": self.organization, "name": self.project, "entry_type": "service", }
true
true
f72a4c55620436228ce86fa539585fab1397d008
2,698
py
Python
dprs/get_contents_file_list.py
kaan-keskin/debian-package-repository-statistics
ef70f4a9914b8baa4799a36217832a5cbdc8b7d3
[ "MIT" ]
1
2022-03-21T19:08:43.000Z
2022-03-21T19:08:43.000Z
dprs/get_contents_file_list.py
kaan-keskin/debian-package-repository-statistics
ef70f4a9914b8baa4799a36217832a5cbdc8b7d3
[ "MIT" ]
null
null
null
dprs/get_contents_file_list.py
kaan-keskin/debian-package-repository-statistics
ef70f4a9914b8baa4799a36217832a5cbdc8b7d3
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Extensible library for opening URLs # https://docs.python.org/3/library/urllib.request.html import urllib.request from urllib.error import URLError from dprs.default_variables import DEFAULT_MIRROR_URL from dprs.exceptions import MirrorURLNotAccessible def get_contents_file_list(mirror_url: str = DEFAULT_MIRROR_URL) -> list: """ This function returns a list of dictionaries extracted from Contents-*.gz file in the given Debian Package Repository Address. Arguments: mirror_url: Debian Package Repository Address Returns: list: List of dictionaries with the following structure: [ { "architecture": "amd64", "filename": "Contents-amd64.gz", "url": http://ftp.uk.debian.org/debian/dists/stable/main/Contents-amd64.gz" }, { "architecture": "arm64", "filename": "Contents-arm64.gz", "url": http://ftp.uk.debian.org/debian/dists/stable/main/Contents-arm64.gz" }, { "architecture": "i386", "filename": "Contents-i386.gz", "url": http://ftp.uk.debian.org/debian/dists/stable/main/Contents-i386.gz" }, ... ] """ try: with urllib.request.urlopen(mirror_url) as url_opener_response: raw_html = url_opener_response.read() except URLError: # TODO: Add more functionality. Doing nothing for now! raise MirrorURLNotAccessible("Debian Package Repository URL is not accessible!") html = raw_html.decode() """ HTML content will be similar to the following structure: ... <a href="Contents-all.gz">Contents-all.gz</a> <a href="Contents-amd64.gz">Contents-amd64.gz</a> <a href="Contents-arm64.gz">Contents-arm64.gz</a> <a href="Contents-i386.gz">Contents-i386.gz</a> ... <a href="Contents-udeb-all.gz">Contents-udeb-all.gz</a> <a href="Contents-udeb-amd64.gz">Contents-udeb-amd64.gz</a> <a href="Contents-udeb-arm64.gz">Contents-udeb-arm64.gz</a> <a href="Contents-udeb-i386.gz">Contents-udeb-i386.gz</a> ... """ contents_file_list = [] for line in html.split("\r\n"): if line.startswith("<a href=\"Contents-"): filename = line[line.find("Contents-"):line.find(".gz")+3] architecture = filename[filename.rfind("-") + 1:filename.rfind(".gz")] url = f"{mirror_url}{filename}" if mirror_url.endswith("/") else f"{mirror_url}/{filename}" contents_file_list.append(dict(architecture=architecture, filename=filename, url=url)) return contents_file_list
38.542857
103
0.627502
import urllib.request from urllib.error import URLError from dprs.default_variables import DEFAULT_MIRROR_URL from dprs.exceptions import MirrorURLNotAccessible def get_contents_file_list(mirror_url: str = DEFAULT_MIRROR_URL) -> list: try: with urllib.request.urlopen(mirror_url) as url_opener_response: raw_html = url_opener_response.read() except URLError: raise MirrorURLNotAccessible("Debian Package Repository URL is not accessible!") html = raw_html.decode() contents_file_list = [] for line in html.split("\r\n"): if line.startswith("<a href=\"Contents-"): filename = line[line.find("Contents-"):line.find(".gz")+3] architecture = filename[filename.rfind("-") + 1:filename.rfind(".gz")] url = f"{mirror_url}{filename}" if mirror_url.endswith("/") else f"{mirror_url}/{filename}" contents_file_list.append(dict(architecture=architecture, filename=filename, url=url)) return contents_file_list
true
true
f72a4c7097a99eefb13c041d6192064e857a4dfb
1,277
py
Python
tests/conftest.py
benbenti/fuzzyclustering
f67224105528d82f6d950ec7692a50d927ca0621
[ "MIT" ]
null
null
null
tests/conftest.py
benbenti/fuzzyclustering
f67224105528d82f6d950ec7692a50d927ca0621
[ "MIT" ]
3
2021-04-22T15:20:32.000Z
2021-04-22T15:21:41.000Z
tests/conftest.py
benbenti/fuzzyclustering
f67224105528d82f6d950ec7692a50d927ca0621
[ "MIT" ]
null
null
null
import pytest import random import numpy as np from numpy.random import rand import lib.algorithms as al @pytest.fixture(scope="session") def unif_1D(): """ Test case: one dimension, samples evenly distributed. """ data = np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] ] ) return data @pytest.fixture(scope="session") def rng(): return random.Random() @pytest.fixture def dataset(rng): n_samples = rng.randint(100, 1000) n_features = rng.randint(10, 100) feature_range = rng.randint(1, 10) return (rand(n_samples, n_features) - 1/2) * feature_range @pytest.fixture def nc(rng): return rng.randint(2, 50) @pytest.fixture def FC_random(rng, dataset, nc): p = 1 + rng.random() * 2 return al.FuzzyClustering(dataset, p, nc) # @pytest.fixture # def FCP_random(rng, dataset, nc): # p = rng.random() # return al.FuzzyClusteringPoly(dataset, p, nc) # @pytest.fixture # def FCRS_random(rng, dataset, nc): # p = rng.random() * 5 # return al.FuzzyClusteringRegulSh(dataset, p, nc) # @pytest.fixture # def FCRQ_random(rng, dataset, nc): # p = rng.random() * 5 # return al.FuzzyClusteringRegulQuad(dataset, p, nc)
24.557692
62
0.617071
import pytest import random import numpy as np from numpy.random import rand import lib.algorithms as al @pytest.fixture(scope="session") def unif_1D(): data = np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] ] ) return data @pytest.fixture(scope="session") def rng(): return random.Random() @pytest.fixture def dataset(rng): n_samples = rng.randint(100, 1000) n_features = rng.randint(10, 100) feature_range = rng.randint(1, 10) return (rand(n_samples, n_features) - 1/2) * feature_range @pytest.fixture def nc(rng): return rng.randint(2, 50) @pytest.fixture def FC_random(rng, dataset, nc): p = 1 + rng.random() * 2 return al.FuzzyClustering(dataset, p, nc)
true
true
f72a4c86c1a569849d3b8f3e318a9e9d83312722
3,322
py
Python
2 semester/PP/10_2/Code/3.py
kurpenok/Labs
069c92b7964a1445d093313b38ebdc56318d2a73
[ "MIT" ]
null
null
null
2 semester/PP/10_2/Code/3.py
kurpenok/Labs
069c92b7964a1445d093313b38ebdc56318d2a73
[ "MIT" ]
null
null
null
2 semester/PP/10_2/Code/3.py
kurpenok/Labs
069c92b7964a1445d093313b38ebdc56318d2a73
[ "MIT" ]
null
null
null
from math import sqrt, sin, pi class Liked: def __init__(self, *args) -> None: self.data = [] for arg in args: for line in arg: self.data.append(line) def likes(self) -> dict: self.emojis = [":)", ";)", ")", ":(", ";(", "("] output = dict() for line in self.data: for emoji in self.emojis: count = line.count(emoji) if count: if emoji in output: output[emoji] += count else: output[emoji] = count return output class MiMiMi(Liked): def __init__(self, *args) -> None: super().__init__(*args) def likes(self) -> dict: self.emojis = [":)", ";)", ")", ":(", ";(", "("] output = dict() for line in self.data: if ["cat", "kitten"] in line: for emoji in self.emojis: count = line.count(emoji) if count: if emoji in output: output[emoji] += count else: output[emoji] = count return output class Mosquito: def __init__(self, age: int) -> None: self.age = age def __str__(self) -> str: return f"Mosquito, {self.age} age" class MaleMosquito(Mosquito): def __init__(self, age: int, lives: str) -> None: self.age = age self.lives = lives def __str__(self) -> str: return f"I hear and see everything {self.lives}" class FemaleMosquito(Mosquito): def __init__(self, age: int, feed: str) -> None: self.age = age self.feed = feed def __str__(self) -> str: return f"The thin squeak of a mosquito after eating {self.feed}" class MosquitoLarva(Mosquito): def __str__(self) -> str: return f"" class Oscillations: def __init__(self, a: int) -> None: self.a = a class SpringPendulum(Oscillations): def __init__(self, a: int, m: int, k: int) -> None: self.a = a self.m = m self.k = k def period(self) -> float: return 2 * pi * sqrt(self.m / self.k) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" class MathPendulum(Oscillations): def __init__(self, a: int, l: int, g: int) -> None: self.a = a self.l = l self.g = g def period(self) -> float: return 2 * pi * sqrt(self.l / self.g) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" class EMPendulum(Oscillations): def __init__(self, a: int, l: int, c: int) -> None: self.a = a self.l = l self.c = c def period(self) -> float: return 2 * pi * sqrt(self.l * self.c) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" if __name__ == "__main__": liked = Liked(["Hi, Kuat! :)", "Well ;)", "How are you?))"]) print(liked.likes())
24.248175
72
0.494883
from math import sqrt, sin, pi class Liked: def __init__(self, *args) -> None: self.data = [] for arg in args: for line in arg: self.data.append(line) def likes(self) -> dict: self.emojis = [":)", ";)", ")", ":(", ";(", "("] output = dict() for line in self.data: for emoji in self.emojis: count = line.count(emoji) if count: if emoji in output: output[emoji] += count else: output[emoji] = count return output class MiMiMi(Liked): def __init__(self, *args) -> None: super().__init__(*args) def likes(self) -> dict: self.emojis = [":)", ";)", ")", ":(", ";(", "("] output = dict() for line in self.data: if ["cat", "kitten"] in line: for emoji in self.emojis: count = line.count(emoji) if count: if emoji in output: output[emoji] += count else: output[emoji] = count return output class Mosquito: def __init__(self, age: int) -> None: self.age = age def __str__(self) -> str: return f"Mosquito, {self.age} age" class MaleMosquito(Mosquito): def __init__(self, age: int, lives: str) -> None: self.age = age self.lives = lives def __str__(self) -> str: return f"I hear and see everything {self.lives}" class FemaleMosquito(Mosquito): def __init__(self, age: int, feed: str) -> None: self.age = age self.feed = feed def __str__(self) -> str: return f"The thin squeak of a mosquito after eating {self.feed}" class MosquitoLarva(Mosquito): def __str__(self) -> str: return f"" class Oscillations: def __init__(self, a: int) -> None: self.a = a class SpringPendulum(Oscillations): def __init__(self, a: int, m: int, k: int) -> None: self.a = a self.m = m self.k = k def period(self) -> float: return 2 * pi * sqrt(self.m / self.k) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" class MathPendulum(Oscillations): def __init__(self, a: int, l: int, g: int) -> None: self.a = a self.l = l self.g = g def period(self) -> float: return 2 * pi * sqrt(self.l / self.g) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" class EMPendulum(Oscillations): def __init__(self, a: int, l: int, c: int) -> None: self.a = a self.l = l self.c = c def period(self) -> float: return 2 * pi * sqrt(self.l * self.c) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" if __name__ == "__main__": liked = Liked(["Hi, Kuat! :)", "Well ;)", "How are you?))"]) print(liked.likes())
true
true
f72a4cbccdd5ee4e79941efbf501b57e0fc9d10f
6,514
py
Python
test.py
jssprz/video_captioning_with_visual_syntactic_embedding
0687772b22c56f448dabbe46932422363964abd4
[ "MIT" ]
23
2021-01-04T07:09:40.000Z
2022-01-12T22:54:33.000Z
test.py
jssprz/video_captioning_with_visual_syntactic_embedding
0687772b22c56f448dabbe46932422363964abd4
[ "MIT" ]
7
2021-01-14T07:48:22.000Z
2022-02-01T04:30:05.000Z
test.py
jssprz/video_captioning_with_visual_syntactic_embedding
0687772b22c56f448dabbe46932422363964abd4
[ "MIT" ]
7
2021-03-20T15:03:53.000Z
2022-03-09T09:18:10.000Z
import os import argparse import pickle from utils import decode_from_tokens from vocabulary import Vocabulary from configuration_file import ConfigurationFile from model.encoder import SCNEncoder from model.decoder import SemSynANDecoder import h5py import torch import numpy as np if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate captions por test samples') parser.add_argument('-chckpt', '--checkpoint_path', type=str, default='pretrain/chckpt.pt', help='Set the path to pre-trained model (default is pretrain/chckpt.pt).') parser.add_argument('-data', '--dataset_folder', type=str, default='data/MSVD', help='Set the path to dataset folder (default is data/MSVD).') parser.add_argument('-out', '--output_folder', type=str, default='results/MSVD', help='Set the path to output folder (default is results/MSVD).') args = parser.parse_args() # load vocabulary with open(os.path.join(args.dataset_folder, 'corpus.pkl'), "rb") as f: corpus = pickle.load(f) idx2word_dict = corpus[4] vocab = Vocabulary.from_idx2word_dict(idx2word_dict, False) print('Size of vocabulary: {}'.format(len(vocab))) # Pretrained Embedding pretrained_embedding = torch.Tensor(corpus[5]) cnn_feature_size = 2048 c3d_feature_size = 4096 i3d_feature_size = 400 eco_feature_size = 1536 res_eco_features_size = 3584 cnn_global_size = 512 projected_size = 512 hidden_size = 1024 # Number of hidden layer units of the cyclic network mid_size = 128 # The middle of the boundary detection layer represents the dimension n_tags = 300 global_tagger_hidden_size = 1024 specific_tagger_hidden_size = 128 hidden_size = 1024 embedding_size = 300 #1024 rnn_in_size = 300 #1024 rnn_hidden_size = 1024 config = ConfigurationFile(os.path.join(args.dataset_folder, 'config.ini'), 'sem-syn-cn-max') # Models encoder = SCNEncoder(cnn_feature_size=cnn_feature_size, c3d_feature_size=c3d_feature_size, i3d_feature_size=i3d_feature_size, eco_feature_size=eco_feature_size, res_eco_features_size=res_eco_features_size, n_tags=n_tags, hidden_size=hidden_size, global_tagger_hidden_size=global_tagger_hidden_size, specific_tagger_hidden_size=specific_tagger_hidden_size, n_layers=config.encoder_num_layers, input_dropout_p=config.encoder_dropout_p, rnn_dropout_p=config.encoder_dropout_p, bidirectional=config.encoder_bidirectional, rnn_cell=config.encoder_rnn_cell, device='cpu') decoder = SemSynANDecoder(in_seq_length=config.max_frames, out_seq_length=config.max_words, n_feats=res_eco_features_size + cnn_global_size, # n_feats=cnn_feature_size+c3d_feature_size, n_tags=n_tags + 400, #+ 174, n_pos_emb=512, embedding_size=embedding_size, pretrained_embedding=pretrained_embedding, hidden_size=hidden_size, rnn_in_size=rnn_in_size, rnn_hidden_size=rnn_hidden_size, vocab=vocab, device='cpu', rnn_cell=config.decoder_rnn_cell, encoder_num_layers=config.encoder_num_layers, encoder_bidirectional=config.encoder_bidirectional, num_layers=config.decoder_num_layers, dropout_p=config.decoder_dropout_p, beam_size=config.decoder_beam_size, temperature=config.decoder_temperature, train_sample_max=config.decoder_train_sample_max, test_sample_max=config.decoder_test_sample_max, beam_search_logic=config.decoder_beam_search_logic, dataset_name=config.dataset_name) # Checkpoint checkpoint = torch.load(args.checkpoint_path, map_location='cpu') # 1. filter out unnecessary keys for encoder chckpt_dict = {k: v for k, v in checkpoint['encoder'].items() if k not in ['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias']} encoder_dict = encoder.state_dict() encoder_dict.update(chckpt_dict) encoder.load_state_dict(encoder_dict) decoder.load_state_dict(checkpoint['decoder']) #load test set features test_vidxs = sorted(list(set(corpus[2][1]))) with h5py.File(os.path.join(args.dataset_folder, config.features_path), 'r') as feats_file: print('loading visual feats...') dataset = feats_file[config.dataset_name] cnn_feats = torch.from_numpy(dataset['cnn_features'][test_vidxs]).float() c3d_feats = torch.from_numpy(dataset['c3d_features'][test_vidxs]).float() cnn_globals = torch.zeros(cnn_feats.size(0), 512) # torch.from_numpy(dataset['cnn_globals'][test_vidxs]).float() cnn_sem_globals = torch.from_numpy(dataset['cnn_sem_globals'][test_vidxs]).float() f_counts = dataset['count_features'][test_vidxs] print('visual feats loaded') res_eco_globals = torch.from_numpy(np.load(os.path.join(args.dataset_folder, 'resnext_eco.npy'))[test_vidxs]) tags_globals = torch.from_numpy(np.load(os.path.join(args.dataset_folder, 'tag_feats.npy'))[test_vidxs]) encoder.eval() decoder.eval() with torch.no_grad(): video_encoded = encoder(cnn_feats, c3d_feats, cnn_globals, cnn_sem_globals, tags_globals, res_eco_globals) logits, tokens = decoder(video_encoded, None, teacher_forcing_ratio=0) scores = logits.max(dim=2)[0].mean(dim=1) confidences, sentences = [], [] for score, seq in zip(scores, tokens): s = decode_from_tokens(seq, vocab) print(score, s) sentences.append(s) confidences.append(score) if not os.path.exists(args.output_folder): os.makedirs(args.output_folder) with open(os.path.join(args.output_folder, 'predictions.txt'), 'w') as fo: for vidx, sentence in zip(test_vidxs, sentences): fo.write(f'{vidx}\t{sentence}\n')
44.312925
129
0.646147
import os import argparse import pickle from utils import decode_from_tokens from vocabulary import Vocabulary from configuration_file import ConfigurationFile from model.encoder import SCNEncoder from model.decoder import SemSynANDecoder import h5py import torch import numpy as np if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate captions por test samples') parser.add_argument('-chckpt', '--checkpoint_path', type=str, default='pretrain/chckpt.pt', help='Set the path to pre-trained model (default is pretrain/chckpt.pt).') parser.add_argument('-data', '--dataset_folder', type=str, default='data/MSVD', help='Set the path to dataset folder (default is data/MSVD).') parser.add_argument('-out', '--output_folder', type=str, default='results/MSVD', help='Set the path to output folder (default is results/MSVD).') args = parser.parse_args() with open(os.path.join(args.dataset_folder, 'corpus.pkl'), "rb") as f: corpus = pickle.load(f) idx2word_dict = corpus[4] vocab = Vocabulary.from_idx2word_dict(idx2word_dict, False) print('Size of vocabulary: {}'.format(len(vocab))) pretrained_embedding = torch.Tensor(corpus[5]) cnn_feature_size = 2048 c3d_feature_size = 4096 i3d_feature_size = 400 eco_feature_size = 1536 res_eco_features_size = 3584 cnn_global_size = 512 projected_size = 512 hidden_size = 1024 mid_size = 128 n_tags = 300 global_tagger_hidden_size = 1024 specific_tagger_hidden_size = 128 hidden_size = 1024 embedding_size = 300 rnn_in_size = 300 rnn_hidden_size = 1024 config = ConfigurationFile(os.path.join(args.dataset_folder, 'config.ini'), 'sem-syn-cn-max') encoder = SCNEncoder(cnn_feature_size=cnn_feature_size, c3d_feature_size=c3d_feature_size, i3d_feature_size=i3d_feature_size, eco_feature_size=eco_feature_size, res_eco_features_size=res_eco_features_size, n_tags=n_tags, hidden_size=hidden_size, global_tagger_hidden_size=global_tagger_hidden_size, specific_tagger_hidden_size=specific_tagger_hidden_size, n_layers=config.encoder_num_layers, input_dropout_p=config.encoder_dropout_p, rnn_dropout_p=config.encoder_dropout_p, bidirectional=config.encoder_bidirectional, rnn_cell=config.encoder_rnn_cell, device='cpu') decoder = SemSynANDecoder(in_seq_length=config.max_frames, out_seq_length=config.max_words, n_feats=res_eco_features_size + cnn_global_size, n_tags=n_tags + 400, n_pos_emb=512, embedding_size=embedding_size, pretrained_embedding=pretrained_embedding, hidden_size=hidden_size, rnn_in_size=rnn_in_size, rnn_hidden_size=rnn_hidden_size, vocab=vocab, device='cpu', rnn_cell=config.decoder_rnn_cell, encoder_num_layers=config.encoder_num_layers, encoder_bidirectional=config.encoder_bidirectional, num_layers=config.decoder_num_layers, dropout_p=config.decoder_dropout_p, beam_size=config.decoder_beam_size, temperature=config.decoder_temperature, train_sample_max=config.decoder_train_sample_max, test_sample_max=config.decoder_test_sample_max, beam_search_logic=config.decoder_beam_search_logic, dataset_name=config.dataset_name) checkpoint = torch.load(args.checkpoint_path, map_location='cpu') chckpt_dict = {k: v for k, v in checkpoint['encoder'].items() if k not in ['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias']} encoder_dict = encoder.state_dict() encoder_dict.update(chckpt_dict) encoder.load_state_dict(encoder_dict) decoder.load_state_dict(checkpoint['decoder']) test_vidxs = sorted(list(set(corpus[2][1]))) with h5py.File(os.path.join(args.dataset_folder, config.features_path), 'r') as feats_file: print('loading visual feats...') dataset = feats_file[config.dataset_name] cnn_feats = torch.from_numpy(dataset['cnn_features'][test_vidxs]).float() c3d_feats = torch.from_numpy(dataset['c3d_features'][test_vidxs]).float() cnn_globals = torch.zeros(cnn_feats.size(0), 512) cnn_sem_globals = torch.from_numpy(dataset['cnn_sem_globals'][test_vidxs]).float() f_counts = dataset['count_features'][test_vidxs] print('visual feats loaded') res_eco_globals = torch.from_numpy(np.load(os.path.join(args.dataset_folder, 'resnext_eco.npy'))[test_vidxs]) tags_globals = torch.from_numpy(np.load(os.path.join(args.dataset_folder, 'tag_feats.npy'))[test_vidxs]) encoder.eval() decoder.eval() with torch.no_grad(): video_encoded = encoder(cnn_feats, c3d_feats, cnn_globals, cnn_sem_globals, tags_globals, res_eco_globals) logits, tokens = decoder(video_encoded, None, teacher_forcing_ratio=0) scores = logits.max(dim=2)[0].mean(dim=1) confidences, sentences = [], [] for score, seq in zip(scores, tokens): s = decode_from_tokens(seq, vocab) print(score, s) sentences.append(s) confidences.append(score) if not os.path.exists(args.output_folder): os.makedirs(args.output_folder) with open(os.path.join(args.output_folder, 'predictions.txt'), 'w') as fo: for vidx, sentence in zip(test_vidxs, sentences): fo.write(f'{vidx}\t{sentence}\n')
true
true
f72a4d13a6ccfb3a394f61f2c8c520771408032b
3,484
py
Python
app/routers/images.py
vncsna/mirror
0de84de6fa4f8a4569beed0bf2e313901d95a17d
[ "MIT" ]
null
null
null
app/routers/images.py
vncsna/mirror
0de84de6fa4f8a4569beed0bf2e313901d95a17d
[ "MIT" ]
null
null
null
app/routers/images.py
vncsna/mirror
0de84de6fa4f8a4569beed0bf2e313901d95a17d
[ "MIT" ]
null
null
null
# TODO: Add exception checking # TODO: Use wrong uuids as input import os import cv2 import shutil import numpy as np from enum import Enum from uuid import uuid4 from pathlib import Path from dotenv import load_dotenv from fastapi import APIRouter, File, UploadFile from fastapi.responses import FileResponse load_dotenv() DATABASE_IMGE = os.environ['DATABASE_IMGE'] DATABASE_TEXT = os.environ['DATABASE_TEXT'] HAAR_CLF_PATH = os.environ['HAAR_CLF_PATH'] CASCADE_CLASSIFIER = cv2.CascadeClassifier(HAAR_CLF_PATH) # --------------------------------------- class FilterName(str, Enum): blur = "blur" cover = "cover" pixelate = "pixelate" # --------------------------------------- router = APIRouter(tags=['Image']) @router.post('/image') def create_image(image: UploadFile = File(...)): uuid = uuid4() with open(f'{DATABASE_IMGE}/{uuid}.png', 'wb') as buffer: shutil.copyfileobj(image.file, buffer) return {'uuid': uuid} @router.get('/image/{uuid}') def read_image(uuid: str): filepath = Path(f'{DATABASE_IMGE}/{uuid}.png') return FileResponse(filepath) @router.put('/image/{uuid}') def update_image(uuid: str, image: UploadFile = File(...)): with open(f'{DATABASE_IMGE}/{uuid}.png', 'wb') as buffer: shutil.copyfileobj(image.file, buffer) return {'uuid': uuid} @router.delete('/image/{uuid}') def delete_image(uuid: str): filepath = Path(f'{DATABASE_IMGE}/{uuid}.png') filepath.unlink() return {'uuid': uuid} @router.get('/image/{uuid}/{filter_}') def transform_image(uuid: str, filter_: FilterName): filepath = f'{DATABASE_IMGE}/{uuid}.png' image = cv2.imread(str(filepath)) if filter_ == FilterName.blur: anonymized_image = anonymize_faces(image, blur) elif filter_ == FilterName.cover: anonymized_image = anonymize_faces(image, cover) elif filter_ == FilterName.pixelate: anonymized_image = anonymize_faces(image, pixelate) new_filepath = f'{DATABASE_IMGE}/{uuid}-{filter_}.png' cv2.imwrite(new_filepath, anonymized_image) return FileResponse(new_filepath) @router.get('/images') def read_images(): uuids = Path(f'{DATABASE_IMGE}').glob('*') uuids = [uuid.stem for uuid in uuids] return {'uuids': uuids} # --------------------------------------- def blur(img, factor=3.0): # auto determine the size of blurring kernel (h, w) = img.shape[:2] kW = int(w / factor) kH = int(h / factor) # ensure that width and height are odd kW = kW if kW % 2 != 0 else kW - 1 kH = kH if kH % 2 != 0 else kH - 1 # apply a gaussian blue to image return cv2.GaussianBlur(img, (kW, kH), 0) def cover(img): return np.zeros_like(img) def pixelate(img): height, width = img.shape[:2] # downscale image output = cv2.resize( img, (6, 6), interpolation=cv2.INTER_LINEAR) # upscale image output = cv2.resize( output, (width, height), interpolation=cv2.INTER_NEAREST) return output def anonymize_faces(img, filtr): # transform color to gray gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # detect region of interest with # a haar cascade feature classifier faces = CASCADE_CLASSIFIER.detectMultiScale(gray, 1.1, 4) # loop faces and apply filter for (x0, y0, width, height) in faces: face = img[x0:x0 + width, y0:y0 + height, :] img[x0:x0 + width, y0:y0 + height, :] = filtr(face) return img
28.325203
65
0.642078
import os import cv2 import shutil import numpy as np from enum import Enum from uuid import uuid4 from pathlib import Path from dotenv import load_dotenv from fastapi import APIRouter, File, UploadFile from fastapi.responses import FileResponse load_dotenv() DATABASE_IMGE = os.environ['DATABASE_IMGE'] DATABASE_TEXT = os.environ['DATABASE_TEXT'] HAAR_CLF_PATH = os.environ['HAAR_CLF_PATH'] CASCADE_CLASSIFIER = cv2.CascadeClassifier(HAAR_CLF_PATH) class FilterName(str, Enum): blur = "blur" cover = "cover" pixelate = "pixelate" router = APIRouter(tags=['Image']) @router.post('/image') def create_image(image: UploadFile = File(...)): uuid = uuid4() with open(f'{DATABASE_IMGE}/{uuid}.png', 'wb') as buffer: shutil.copyfileobj(image.file, buffer) return {'uuid': uuid} @router.get('/image/{uuid}') def read_image(uuid: str): filepath = Path(f'{DATABASE_IMGE}/{uuid}.png') return FileResponse(filepath) @router.put('/image/{uuid}') def update_image(uuid: str, image: UploadFile = File(...)): with open(f'{DATABASE_IMGE}/{uuid}.png', 'wb') as buffer: shutil.copyfileobj(image.file, buffer) return {'uuid': uuid} @router.delete('/image/{uuid}') def delete_image(uuid: str): filepath = Path(f'{DATABASE_IMGE}/{uuid}.png') filepath.unlink() return {'uuid': uuid} @router.get('/image/{uuid}/{filter_}') def transform_image(uuid: str, filter_: FilterName): filepath = f'{DATABASE_IMGE}/{uuid}.png' image = cv2.imread(str(filepath)) if filter_ == FilterName.blur: anonymized_image = anonymize_faces(image, blur) elif filter_ == FilterName.cover: anonymized_image = anonymize_faces(image, cover) elif filter_ == FilterName.pixelate: anonymized_image = anonymize_faces(image, pixelate) new_filepath = f'{DATABASE_IMGE}/{uuid}-{filter_}.png' cv2.imwrite(new_filepath, anonymized_image) return FileResponse(new_filepath) @router.get('/images') def read_images(): uuids = Path(f'{DATABASE_IMGE}').glob('*') uuids = [uuid.stem for uuid in uuids] return {'uuids': uuids} def blur(img, factor=3.0): (h, w) = img.shape[:2] kW = int(w / factor) kH = int(h / factor) kW = kW if kW % 2 != 0 else kW - 1 kH = kH if kH % 2 != 0 else kH - 1 return cv2.GaussianBlur(img, (kW, kH), 0) def cover(img): return np.zeros_like(img) def pixelate(img): height, width = img.shape[:2] output = cv2.resize( img, (6, 6), interpolation=cv2.INTER_LINEAR) output = cv2.resize( output, (width, height), interpolation=cv2.INTER_NEAREST) return output def anonymize_faces(img, filtr): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = CASCADE_CLASSIFIER.detectMultiScale(gray, 1.1, 4) for (x0, y0, width, height) in faces: face = img[x0:x0 + width, y0:y0 + height, :] img[x0:x0 + width, y0:y0 + height, :] = filtr(face) return img
true
true
f72a4dac3ecef7e475c42ce8919f2ec459aa9f6e
1,352
py
Python
Chapter05_Serial-IO/serialOrgan/scaleGenerator.py
ONEV2/AVR-Programming
31ac43d0ea353a6878079e15c1e1bda6a31da4c0
[ "MIT" ]
608
2015-01-01T23:22:28.000Z
2022-03-25T23:40:47.000Z
Chapter05_Serial-IO/serialOrgan/scaleGenerator.py
Omsingh24/AVR-Programming
8a9ad403ccf2f6cceef955e3813e476da3df7f62
[ "MIT" ]
41
2015-01-14T05:49:48.000Z
2022-01-22T07:07:24.000Z
Chapter05_Serial-IO/serialOrgan/scaleGenerator.py
Omsingh24/AVR-Programming
8a9ad403ccf2f6cceef955e3813e476da3df7f62
[ "MIT" ]
340
2015-01-06T18:32:28.000Z
2022-03-31T18:20:44.000Z
# scaleGenerator.py # Scales are in terms of times per cycle (period) rather # than pitch. # import math SCALE = ['C', 'Cx', 'D', 'Dx', 'E', 'F', 'Fx', 'G', 'Gx', 'A', 'Ax', 'B'] def calculateOctave(baseLength): periods = [baseLength / math.exp(x*math.log(2)/12) for x in range(0, 12)] periods = [int(round(x)) for x in periods] return( zip(SCALE, periods) ) def makePitches(basePitch, numOctaves): pitchList = [] for octave in range(0, numOctaves): for note, period in calculateOctave(basePitch / 2**octave): if period < 65500: noteString = note + str(octave) pitchList.append((noteString,period)) return(pitchList) def makeDefines(basePitch, numOctaves): pitchList = makePitches(basePitch, numOctaves) defineString = "// Scale in the key of {} \n".format(basePitch) defineString += "// Automatically generated by scaleGenerator.py \n\n" for (note, length) in pitchList: defineString += "#define {:<5}{:>6}\n".format(note, length) return(defineString) if __name__ == "__main__": ## Change these if you like BASEPITCH = 25000 OCTAVES = 8 OUTFILE = "scale16.h" ## Write it out to a file out = open(OUTFILE, "w") out.write(makeDefines(BASEPITCH, OCTAVES)) out.close()
28.765957
77
0.607988
import math SCALE = ['C', 'Cx', 'D', 'Dx', 'E', 'F', 'Fx', 'G', 'Gx', 'A', 'Ax', 'B'] def calculateOctave(baseLength): periods = [baseLength / math.exp(x*math.log(2)/12) for x in range(0, 12)] periods = [int(round(x)) for x in periods] return( zip(SCALE, periods) ) def makePitches(basePitch, numOctaves): pitchList = [] for octave in range(0, numOctaves): for note, period in calculateOctave(basePitch / 2**octave): if period < 65500: noteString = note + str(octave) pitchList.append((noteString,period)) return(pitchList) def makeDefines(basePitch, numOctaves): pitchList = makePitches(basePitch, numOctaves) defineString = "// Scale in the key of {} \n".format(basePitch) defineString += "// Automatically generated by scaleGenerator.py \n\n" for (note, length) in pitchList: defineString += "#define {:<5}{:>6}\n".format(note, length) return(defineString) if __name__ == "__main__": OCTAVES = 8 OUTFILE = "scale16.h" "w") out.write(makeDefines(BASEPITCH, OCTAVES)) out.close()
true
true
f72a4dfe4c34ef1aa9ab86723b47cf9341cad810
3,823
py
Python
scripts/o3de/tests/unit_test_project_properties.py
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
1
2021-08-04T00:43:18.000Z
2021-08-04T00:43:18.000Z
scripts/o3de/tests/unit_test_project_properties.py
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
null
null
null
scripts/o3de/tests/unit_test_project_properties.py
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
null
null
null
# # Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import pytest import pathlib from unittest.mock import patch from o3de import project_properties TEST_DEFAULT_PROJECT_DATA = { "template_name": "DefaultProject", "restricted_name": "o3de", "restricted_platform_relative_path": "Templates", "origin": "The primary repo for DefaultProject goes here: i.e. http://www.mydomain.com", "license": "What license DefaultProject uses goes here: i.e. https://opensource.org/licenses/MIT", "display_name": "Default", "summary": "A short description of DefaultProject.", "included_gems": ["Atom","Camera","EMotionFX","UI","Maestro","Input","ImGui"], "canonical_tags": [], "user_tags": [ "DefaultProject" ], "icon_path": "preview.png" } @pytest.fixture(scope='class') def init_project_json_data(request): class ProjectJsonData: def __init__(self): self.data = TEST_DEFAULT_PROJECT_DATA request.cls.project_json = ProjectJsonData() @pytest.mark.usefixtures('init_project_json_data') class TestEditProjectProperties: @pytest.mark.parametrize("project_path, project_name, project_new_name, project_origin, project_display,\ project_summary, project_icon, add_tags, delete_tags,\ replace_tags, expected_result", [ pytest.param(pathlib.PurePath('E:/TestProject'), 'test', 'test', 'editing by pytest', 'Unit Test', 'pyTest project', 'pytest.bmp', 'A B C', 'B', 'D E F', 0), pytest.param('', 'test', 'test', 'editing by pytest', 'Unit Test', 'pyTest project', 'pytest.bmp', 'A B C', 'B', 'D E F', 1) ] ) def test_edit_project_properties(self, project_path, project_name, project_new_name, project_origin, project_display, project_summary, project_icon, add_tags, delete_tags, replace_tags, expected_result): def get_project_json_data(project_name: str, project_path) -> dict: if not project_path: self.project_json.data = None return None return self.project_json.data def save_o3de_manifest(new_proj_data: dict, project_path) -> bool: self.project_json.data = new_proj_data return True with patch('o3de.manifest.get_project_json_data', side_effect=get_project_json_data) as get_project_json_data_patch, \ patch('o3de.manifest.save_o3de_manifest', side_effect=save_o3de_manifest) as save_o3de_manifest_patch: result = project_properties.edit_project_props(project_path, project_name, project_new_name, project_origin, project_display, project_summary, project_icon, add_tags, delete_tags, replace_tags) assert result == expected_result if project_path: assert self.project_json.data assert self.project_json.data.get('origin', '') == project_origin assert self.project_json.data.get('display_name', '') == project_display assert self.project_json.data.get('summary', '') == project_summary assert self.project_json.data.get('icon_path', '') == project_icon expected_tag_set = set(replace_tags.split()) project_json_tag_set = set(self.project_json.data.get('user_tags', [])) assert project_json_tag_set == expected_tag_set else: assert not self.project_json.data
46.621951
126
0.637719
import pytest import pathlib from unittest.mock import patch from o3de import project_properties TEST_DEFAULT_PROJECT_DATA = { "template_name": "DefaultProject", "restricted_name": "o3de", "restricted_platform_relative_path": "Templates", "origin": "The primary repo for DefaultProject goes here: i.e. http://www.mydomain.com", "license": "What license DefaultProject uses goes here: i.e. https://opensource.org/licenses/MIT", "display_name": "Default", "summary": "A short description of DefaultProject.", "included_gems": ["Atom","Camera","EMotionFX","UI","Maestro","Input","ImGui"], "canonical_tags": [], "user_tags": [ "DefaultProject" ], "icon_path": "preview.png" } @pytest.fixture(scope='class') def init_project_json_data(request): class ProjectJsonData: def __init__(self): self.data = TEST_DEFAULT_PROJECT_DATA request.cls.project_json = ProjectJsonData() @pytest.mark.usefixtures('init_project_json_data') class TestEditProjectProperties: @pytest.mark.parametrize("project_path, project_name, project_new_name, project_origin, project_display,\ project_summary, project_icon, add_tags, delete_tags,\ replace_tags, expected_result", [ pytest.param(pathlib.PurePath('E:/TestProject'), 'test', 'test', 'editing by pytest', 'Unit Test', 'pyTest project', 'pytest.bmp', 'A B C', 'B', 'D E F', 0), pytest.param('', 'test', 'test', 'editing by pytest', 'Unit Test', 'pyTest project', 'pytest.bmp', 'A B C', 'B', 'D E F', 1) ] ) def test_edit_project_properties(self, project_path, project_name, project_new_name, project_origin, project_display, project_summary, project_icon, add_tags, delete_tags, replace_tags, expected_result): def get_project_json_data(project_name: str, project_path) -> dict: if not project_path: self.project_json.data = None return None return self.project_json.data def save_o3de_manifest(new_proj_data: dict, project_path) -> bool: self.project_json.data = new_proj_data return True with patch('o3de.manifest.get_project_json_data', side_effect=get_project_json_data) as get_project_json_data_patch, \ patch('o3de.manifest.save_o3de_manifest', side_effect=save_o3de_manifest) as save_o3de_manifest_patch: result = project_properties.edit_project_props(project_path, project_name, project_new_name, project_origin, project_display, project_summary, project_icon, add_tags, delete_tags, replace_tags) assert result == expected_result if project_path: assert self.project_json.data assert self.project_json.data.get('origin', '') == project_origin assert self.project_json.data.get('display_name', '') == project_display assert self.project_json.data.get('summary', '') == project_summary assert self.project_json.data.get('icon_path', '') == project_icon expected_tag_set = set(replace_tags.split()) project_json_tag_set = set(self.project_json.data.get('user_tags', [])) assert project_json_tag_set == expected_tag_set else: assert not self.project_json.data
true
true
f72a4e0d8cbc89c9de5ee0df61f78d7d32bde73e
73,927
py
Python
tensorflow/contrib/lite/testing/generate_examples.py
noahl/tensorflow
b95d8cce7323d328565378e0d60d72603393f87d
[ "Apache-2.0" ]
5
2018-09-22T20:16:46.000Z
2022-02-28T10:35:19.000Z
tensorflow/contrib/lite/testing/generate_examples.py
noahl/tensorflow
b95d8cce7323d328565378e0d60d72603393f87d
[ "Apache-2.0" ]
null
null
null
tensorflow/contrib/lite/testing/generate_examples.py
noahl/tensorflow
b95d8cce7323d328565378e0d60d72603393f87d
[ "Apache-2.0" ]
2
2019-08-14T09:04:37.000Z
2022-02-02T20:08:02.000Z
# Copyright 2017 The TensorFlow 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. # ============================================================================== """Generate a series of TensorFlow graphs that become tflite test cases. Usage: generate_examples <output directory> bazel run //tensorflow/contrib/lite/testing:generate_examples """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import itertools import os import re import sys import tempfile import traceback import zipfile import numpy as np from six import StringIO from six.moves import xrange # TODO(aselle): Disable GPU for now os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # pylint: disable=g-import-not-at-top import tensorflow as tf from google.protobuf import text_format # TODO(aselle): switch to TensorFlow's resource_loader from tensorflow.contrib.lite.testing import generate_examples_report as report_lib from tensorflow.python.framework import graph_util as tf_graph_util from tensorflow.python.ops import rnn parser = argparse.ArgumentParser(description="Script to generate TFLite tests.") parser.add_argument("output_path", help="Directory where the outputs will be go.") parser.add_argument("--zip_to_output", type=str, help="Particular zip to output.", required=False) parser.add_argument("--toco", type=str, help="Path to toco tool.", required=True) parser.add_argument( "--known_bugs_are_errors", action="store_true", help=("If a particular model is affected by a known bug," " count it as a toco error.")) parser.add_argument( "--ignore_toco_errors", action="store_true", help="Raise an exception if any toco error is encountered.") parser.add_argument( "--save_graphdefs", action="store_true", help="Include intermediate graphdefs in the output zip files.") RANDOM_SEED = 342 TEST_INPUT_DEPTH = 3 # A map from regular expression to bug number. Any test failure with label # matching the expression will be considered due to the corresponding bug. KNOWN_BUGS = { # TOCO doesn't support scalars as input. r"relu.*input_shape=\[\]": "67587484", r"sigmoid.*input_shape=\[\]": "67645668", # Concat doesn't work with a single input tensor r"concat.*num_tensors=1": "67378344", # Transposition in MatMul is not supported. r"fully_connected.*transpose_.=True": "67586970", # Softmax graphs are too complex. r"softmax.*dim=0": "67749831", r"softmax.*input_shape=\[1,3,4,3\]": "67749831", # SpaceToDepth only supports float32. r"space_to_depth.*(float16|int32|uint8|int64)": "68018134", # BatchToSpaceND only supports 4D tensors. r"batch_to_space_nd.*input_shape=\[8,2,2,2,1,1\]": "70594733", # Div will use floordiv. r"div.*int32": "72051395", # TOCO require matching dimensions in strided_slice. r"strided_slice.*begin=\[0\].*end=\[1\].*": "73170889", # No support for SplitV r"split.*num_or_size_splits=\[2,2\]": "73377559", # Needs support for dimensions other than the last one in argmax. r"arg_max.*axis=0.*": "77546240", r"arg_max.*axis=1.*": "77546240", r"arg_max.*axis=2.*": "77546240", } class ExtraTocoOptions(object): """Additonal toco options besides input, output, shape.""" def __init__(self): # Whether to ignore control dependency nodes. self.drop_control_dependency = False # Allow custom ops in the toco conversion. self.allow_custom_ops = False # Rnn states that are used to support rnn / lstm cells. self.rnn_states = None def toco_options(data_types, input_arrays, output_arrays, shapes, extra_toco_options=ExtraTocoOptions()): """Create TOCO options to process a model. Args: data_types: input and inference types used by TOCO. input_arrays: names of the input tensors output_arrays: name of the output tensors shapes: shapes of the input tensors extra_toco_options: additional toco options Returns: the options in a string. """ shape_str = ":".join([",".join(str(y) for y in x) for x in shapes]) inference_type = "FLOAT" # TODO(ahentz): if we get multi-input quantization to work we need this # to change if data_types[0] == "QUANTIZED_UINT8": inference_type = "QUANTIZED_UINT8" s = (" --input_data_types=%s" % ",".join(data_types) + " --inference_type=%s" % inference_type + " --input_format=TENSORFLOW_GRAPHDEF" + " --output_format=TFLITE" + " --input_arrays=%s" % ",".join(input_arrays) + " --input_shapes=%s" % shape_str + " --output_arrays=%s" % ",".join(output_arrays)) if extra_toco_options.drop_control_dependency: s += " --drop_control_dependency" if extra_toco_options.allow_custom_ops: s += " --allow_custom_ops" if extra_toco_options.rnn_states: s += (" --rnn_states='" + extra_toco_options.rnn_states + "'") return s def write_examples(fp, examples): """Given a list `examples`, write a text format representation. The file format is csv like with a simple repeated pattern. We would ike to use proto here, but we can't yet due to interfacing with the Android team using this format. Args: fp: File-like object to write to. examples: Example dictionary consiting of keys "inputs" and "outputs" """ def write_tensor(fp, x): """Write tensor in file format supported by TFLITE example.""" fp.write("dtype,%s\n" % x.dtype) fp.write("shape," + ",".join(map(str, x.shape)) + "\n") # Output 9 digits after the point to ensure the precision is good enough. values = ["{:.9f}".format(value) for value in list(x.flatten())] fp.write("values," + ",".join(values) + "\n") fp.write("test_cases,%d\n" % len(examples)) for example in examples: fp.write("inputs,%d\n" % len(example["inputs"])) for i in example["inputs"]: write_tensor(fp, i) fp.write("outputs,%d\n" % len(example["outputs"])) for i in example["outputs"]: write_tensor(fp, i) def write_test_cases(fp, model_name, examples): """Given a dictionary of `examples`, write a text format representation. The file format is protocol-buffer-like, even though we don't use proto due to the needs of the Android team. Args: fp: File-like object to write to. model_name: Filename where the model was written to, relative to filename. examples: Example dictionary consiting of keys "inputs" and "outputs" """ fp.write("load_model: %s\n" % os.path.basename(model_name)) for example in examples: fp.write("reshape {\n") for t in example["inputs"]: fp.write(" input: \"" + ",".join(map(str, t.shape)) + "\"\n") fp.write("}\n") fp.write("invoke {\n") for t in example["inputs"]: values = ["{:.9f}".format(value) for value in list(t.flatten())] fp.write(" input: \"" + ",".join(values) + "\"\n") for t in example["outputs"]: values = ["{:.9f}".format(value) for value in list(t.flatten())] fp.write(" output: \"" + ",".join(values) + "\"\n") fp.write("}\n") _TF_TYPE_INFO = { tf.float32: (np.float32, "FLOAT"), tf.float16: (np.float16, "FLOAT"), tf.int32: (np.int32, "INT32"), tf.uint8: (np.uint8, "QUANTIZED_UINT8"), tf.int64: (np.int64, "INT64"), } def create_tensor_data(dtype, shape, min_value=-100, max_value=100): """Build tensor data spreading the range [min_value, max_value).""" if dtype in _TF_TYPE_INFO: dtype = _TF_TYPE_INFO[dtype][0] if dtype in (tf.float32, tf.float16): value = (max_value-min_value)*np.random.random_sample(shape)+min_value elif dtype in (tf.int32, tf.uint8, tf.int64): value = np.random.randint(min_value, max_value+1, shape) return value.astype(dtype) def freeze_graph(session, outputs): """Freeze the current graph. Args: session: Tensorflow sessions containing the graph outputs: List of output tensors Returns: The frozen graph_def. """ return tf_graph_util.convert_variables_to_constants( session, session.graph.as_graph_def(), [x.op.name for x in outputs]) def make_control_dep_tests(zip_path): """Make a set of tests that use control dependencies.""" test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) filter_value = tf.zeros((3, 3, TEST_INPUT_DEPTH, 8), tf.float32) assert_op = tf.assert_greater_equal(input_tensor, input_tensor - 1) with tf.control_dependencies([assert_op]): out = tf.nn.conv2d(input_tensor, filter_value, strides=(1, 1, 1, 1), padding="SAME") return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) extra_toco_options = ExtraTocoOptions() extra_toco_options.drop_control_dependency = True make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs, extra_toco_options) def toco_convert(graph_def_str, input_tensors, output_tensors, extra_toco_options): """Convert a model's graph def into a tflite model. NOTE: this currently shells out to the toco binary, but we would like convert to Python API tooling in the future. Args: graph_def_str: Graph def proto in serialized string format. input_tensors: List of input tensor tuples `(name, shape, type)`. output_tensors: List of output tensors (names). extra_toco_options: Additional toco options. Returns: output tflite model, log_txt from conversion or None, log_txt if it did not convert properly. """ data_types = [_TF_TYPE_INFO[x[2]][1] for x in input_tensors] opts = toco_options( data_types=data_types, input_arrays=[x[0] for x in input_tensors], shapes=[x[1] for x in input_tensors], output_arrays=output_tensors, extra_toco_options=extra_toco_options) with tempfile.NamedTemporaryFile() as graphdef_file, \ tempfile.NamedTemporaryFile() as output_file, \ tempfile.NamedTemporaryFile("w+") as stdout_file: graphdef_file.write(graph_def_str) graphdef_file.flush() # TODO(aselle): Switch this to subprocess at some point. cmd = ("%s --input_file=%s --output_file=%s %s > %s 2>&1" % (bin_path, graphdef_file.name, output_file.name, opts, stdout_file.name)) exit_code = os.system(cmd) log = ( cmd + "exited with code %d" % exit_code + "\n------------------\n" + stdout_file.read()) return (None if exit_code != 0 else output_file.read()), log def normalize_output_name(output_name): """Remove :0 suffix from tensor names.""" return output_name.split(":")[0] if output_name.endswith( ":0") else output_name def make_zip_of_tests(zip_path, test_parameters, make_graph, make_test_inputs, extra_toco_options=ExtraTocoOptions(), use_frozen_graph=False): """Helper to make a zip file of a bunch of TensorFlow models. This does a cartestian product of the dictionary of test_parameters and calls make_graph() for each item in the cartestian product set. If the graph is built successfully, then make_test_inputs() is called to build expected input/output value pairs. The model is then converted to tflite with toco, and the examples are serialized with the tflite model into a zip file (2 files per item in the cartesian product set). Args: zip_path: Path of zip file to write test_parameters: Dictionary mapping to lists for each parameter. e.g. `{"strides": [[1,3,3,1], [1,2,2,1]], "foo": [1.2, 1.3]}` make_graph: function that takes current parameters and returns tuple `[input1, input2, ...], [output1, output2, ...]` make_test_inputs: function taking `curr_params`, `session`, `input_tensors`, `output_tensors` and returns tuple `(input_values, output_values)`. extra_toco_options: Additional toco options. use_frozen_graph: Whether or not freeze graph before toco converter. Raises: RuntimeError: if there are toco errors that can't be ignored. """ # TODO(aselle): Make this allow multiple inputs outputs. archive = zipfile.PyZipFile(zip_path, "w") zip_manifest = [] convert_report = [] toco_errors = 0 for parameters in test_parameters: keys = parameters.keys() for curr in itertools.product(*parameters.values()): label = zip_path.replace(".zip", "") + (",".join( "%s=%r" % z for z in sorted(zip(keys, curr))).replace(" ", "")) if label[0] == "/": label = label[1:] param_dict = dict(zip(keys, curr)) def build_example(label, param_dict_real): """Build the model with parameter values set in param_dict_real. Args: label: Label of the model (i.e. the filename in the zip). param_dict_real: Parameter dictionary (arguments to the factories make_graph and make_test_inputs) Returns: (tflite_model_binary, report) where tflite_model_binary is the serialized flatbuffer as a string and report is a dictionary with keys `toco_log` (log of toco conversion), `tf_log` (log of tf conversion), `toco` (a string of success status of the conversion), `tf` (a string success status of the conversion). """ np.random.seed(RANDOM_SEED) report = {"toco": report_lib.NOTRUN, "tf": report_lib.FAILED} # Build graph report["tf_log"] = "" report["toco_log"] = "" tf.reset_default_graph() with tf.device("/cpu:0"): try: inputs, outputs = make_graph(param_dict_real) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report sess = tf.Session() try: baseline_inputs, baseline_outputs = (make_test_inputs( param_dict_real, sess, inputs, outputs)) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report report["toco"] = report_lib.FAILED report["tf"] = report_lib.SUCCESS # Convert graph to toco input_tensors = [(input_tensor.name.split(":")[0], input_tensor.get_shape(), input_tensor.dtype) for input_tensor in inputs] output_tensors = [normalize_output_name(out.name) for out in outputs] graph_def = freeze_graph( sess, tf.global_variables() + inputs + outputs) if use_frozen_graph else sess.graph_def tflite_model_binary, toco_log = toco_convert( graph_def.SerializeToString(), input_tensors, output_tensors, extra_toco_options) report["toco"] = (report_lib.SUCCESS if tflite_model_binary is not None else report_lib.FAILED) report["toco_log"] = toco_log if FLAGS.save_graphdefs: archive.writestr(label + ".pb", text_format.MessageToString(graph_def), zipfile.ZIP_DEFLATED) if tflite_model_binary: archive.writestr(label + ".bin", tflite_model_binary, zipfile.ZIP_DEFLATED) example = {"inputs": baseline_inputs, "outputs": baseline_outputs} example_fp = StringIO() write_examples(example_fp, [example]) archive.writestr(label + ".inputs", example_fp.getvalue(), zipfile.ZIP_DEFLATED) example_fp2 = StringIO() write_test_cases(example_fp2, label + ".bin", [example]) archive.writestr(label + "_tests.txt", example_fp2.getvalue(), zipfile.ZIP_DEFLATED) zip_manifest.append(label + "\n") return tflite_model_binary, report _, report = build_example(label, param_dict) if report["toco"] == report_lib.FAILED: ignore_error = False if not FLAGS.known_bugs_are_errors: for pattern, bug_number in KNOWN_BUGS.items(): if re.search(pattern, label): print("Ignored TOCO error due to bug %s" % bug_number) ignore_error = True if not ignore_error: toco_errors += 1 print("-----------------\ntoco error!\n%s\n-----------------\n" % report["toco_log"]) convert_report.append((param_dict, report)) report_io = StringIO() report_lib.make_report_table(report_io, zip_path, convert_report) archive.writestr("report.html", report_io.getvalue()) archive.writestr("manifest.txt", "".join(zip_manifest), zipfile.ZIP_DEFLATED) # Log statistics of what succeeded total_conversions = len(convert_report) tf_success = sum(1 for x in convert_report if x[1]["tf"] == report_lib.SUCCESS) toco_success = sum(1 for x in convert_report if x[1]["toco"] == report_lib.SUCCESS) percent = 0 if tf_success > 0: percent = float(toco_success) / float(tf_success) * 100. tf.logging.info(("Archive %s Considered %d graphs, %d TF evaluated graphs " " and %d TOCO converted graphs (%.1f%%"), zip_path, total_conversions, tf_success, toco_success, percent) if not FLAGS.ignore_toco_errors and toco_errors > 0: raise RuntimeError( "Found %d errors while generating toco models" % toco_errors) def make_pool_tests(pool_op_in): """Make a set of tests to do average pooling. Args: pool_op_in: TensorFlow pooling operation to test i.e. `tf.nn.avg_pool`. Returns: A function representing the true generator (after curried pool_op_in). """ pool_op = pool_op_in def f(zip_path): """Actual function that generates examples. Args: zip_path: path to write zip to. """ # Chose a set of parameters test_parameters = [{ "ksize": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], "strides": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], # TODO(aselle): should add in a degenerate shape (e.g. [1, 0, 1, 1]). "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = pool_op( input_tensor, ksize=parameters["ksize"], strides=parameters["strides"], data_format=parameters["data_format"], padding=parameters["padding"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) return f def make_l2_pool_tests(zip_path): make_pool_tests(make_l2_pool)(zip_path) def make_avg_pool_tests(zip_path): make_pool_tests(tf.nn.avg_pool)(zip_path) def make_max_pool_tests(zip_path): make_pool_tests(tf.nn.max_pool)(zip_path) def make_relu_tests(zip_path): """Make a set of tests to do relu.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_relu1_tests(zip_path): """Make a set of tests to do relu1.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Note that the following is not supported: # out = tf.maximum(-1.0, tf.minimum(input_tensor, 1.0)) out = tf.minimum(1.0, tf.maximum(input_tensor, -1.0)) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_relu6_tests(zip_path): """Make a set of tests to do relu6.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) # This function tests various TensorFLow functions that generates Const op, # including `tf.ones`, `tf.zeros` and random functions. def make_constant_tests(zip_path): """Make a set of tests to do constant ops.""" test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1], [2], [1, 1, 1, 1], [2, 2, 2, 2]], }] def build_graph(parameters): # Since Toco & Tflite can't have a single constant op in the entire graph, # this test adds a zero tensor with a constant op tensor. input1 = tf.placeholder(dtype=parameters["dtype"], name="input1", shape=parameters["input_shape"]) out = tf.ones(parameters["input_shape"], dtype=parameters["dtype"]) + input1 return [input1], [out] def build_inputs(parameters, sess, inputs, outputs): input1 = np.zeros(parameters["input_shape"], dtype=_TF_TYPE_INFO[parameters["dtype"]][0]) return [input1], sess.run(outputs, feed_dict={inputs[0]: input1}) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_binary_op_tests(zip_path, binary_operator): """Make a set of tests to do add with and without broadcast.""" # These parameters are split because we don't support broadcasting. test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[1, 3, 4, 3]], "activation": [True] }, { "dtype": [tf.float32], "input_shape_1": [[5]], "input_shape_2": [[5]], "activation": [False, True] }, { "dtype": [tf.float32], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[3]], "activation": [True] }] def build_graph(parameters): """Builds the graph given the current parameters.""" input1 = tf.placeholder( dtype=parameters["dtype"], name="input1", shape=parameters["input_shape_1"]) input2 = tf.placeholder( dtype=parameters["dtype"], name="input2", shape=parameters["input_shape_2"]) out = binary_operator(input1, input2) if parameters["activation"]: out = tf.nn.relu(out) return [input1, input2], [out] def build_inputs(parameters, sess, inputs, outputs): """Builds operand inputs for op.""" input1 = create_tensor_data(parameters["dtype"], parameters["input_shape_1"]) input2 = create_tensor_data(parameters["dtype"], parameters["input_shape_2"]) return [input1, input2], sess.run( outputs, feed_dict={ inputs[0]: input1, inputs[1]: input2 }) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_mean_tests(zip_path): """Make a set of tests to do mean.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[3, 2, 4]], "axis": [ None, 0, 1, 2, [0, 1], [0, 2], [1, 2], [0, 1, 2], [1, 0], [2, 0], [2, 1], [2, 1, 0], [2, 0, 1], -1, -2, -3, [1, -1], [0, -1], [-1, 0], [-1, -2, -3], [0, 0, 0], [2, 2, 0], [1, 0, -3, -3] ], "const_axis": [True, False], "keepdims": [True, False], }, { "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[1, 224, 224, 3]], "axis": [ None, 0, 1, 2, 3, [1, 2], [0, 3], [1, 2, 3], [0, 1, 2, 3], [3, 2, 1, 0], [3, 1, 0, 2], [2, 0], [3, 0], [3, 1], [1, 0], -1, -2, -3, -4, [0, -2], [2, 3, -1, 0], [3, 1, 2, -3], [3, -4], [2, 2, 2], [2, 2, 3], [-3, -3, -4], [-3, 2, 1] ], "const_axis": [True, False], "keepdims": [True, False], }] def build_graph(parameters): """Build the mean op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) # Get axis as either a placeholder or constants. if parameters["const_axis"]: axis = parameters["axis"] input_tensors = [input_tensor] else: if isinstance(parameters["axis"], list): shape = [len(parameters["axis"])] else: shape = [0] # shape for None or integers. axis = tf.placeholder(dtype=tf.int32, name="axis", shape=shape) input_tensors = [input_tensor, axis] out = tf.reduce_mean( input_tensor, axis=axis, keepdims=parameters["keepdims"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) ] if not parameters["const_axis"]: if parameters["axis"]: values.append(np.array(parameters["axis"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_exp_tests(zip_path): """Make a set of tests to do exp.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the exp op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.exp(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_log_softmax_tests(zip_path): """Make a set of tests to do log_softmax.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[1, 100], [4, 2], [5, 224]], }] def build_graph(parameters): """Build the log_softmax op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.log_softmax(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data( parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_maximum_tests(zip_path): """Make a set of tests to do maximum.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the maximum op testing graph.""" input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.maximum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_minimum_tests(zip_path): """Make a set of tests to do minimum.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the minimum op testing graph.""" input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.minimum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_binary_op_tests_func(binary_operator): """Return a function that does a test on a binary operator.""" return lambda zip_path: make_binary_op_tests(zip_path, binary_operator) def make_add_tests(zip_path): make_binary_op_tests(zip_path, tf.add) def make_div_tests(zip_path): make_binary_op_tests(zip_path, tf.div) def make_sub_tests(zip_path): make_binary_op_tests(zip_path, tf.subtract) def make_mul_tests(zip_path): make_binary_op_tests(zip_path, tf.multiply) def make_gather_tests(zip_path): """Make a set of tests to do gather.""" test_parameters = [{ # TODO(mgubin): add string tests when they are supported by Toco. # TODO(mgubin): add tests for Nd indices when they are supported by # TfLite. "params_dtype": [tf.float32, tf.int32], "params_shape": [[10], [1, 2, 20]], "indices_dtype": [tf.int32], "indices_shape": [[3], [5]], "axis": [0, 1], }] def build_graph(parameters): """Build the gather op testing graph.""" params = tf.placeholder( dtype=parameters["params_dtype"], name="params", shape=parameters["params_shape"]) indices = tf.placeholder( dtype=parameters["indices_dtype"], name="indices", shape=parameters["indices_shape"]) out = tf.gather(params, indices, axis=parameters["axis"]) return [params, indices], [out] def build_inputs(parameters, sess, inputs, outputs): params = create_tensor_data(parameters["params_dtype"], parameters["params_shape"]) indices = create_tensor_data(parameters["indices_dtype"], parameters["indices_shape"], 0, parameters["params_shape"][0] - 1) return [params, indices], sess.run( outputs, feed_dict=dict(zip(inputs, [params, indices]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_global_batch_norm_tests(zip_path): """Make a set of tests to do batch_norm_with_global_normalization.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2], [3, 4, 5, 4]], "epsilon": [0.1, 0.0001], "scale_after": [True, False], }] def build_graph(parameters): """Build the global batch norm testing graph.""" input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) x_norm = tf.nn.batch_norm_with_global_normalization( x, mean, variance, scale, offset, parameters["epsilon"], parameters["scale_after"]) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_fused_batch_norm_tests(zip_path): """Make a set of tests to do fused_batch_norm.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2]], "epsilon": [0.001, 0.1], }] def build_graph(parameters): """Build the testing graph for fused batch normalization.""" input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) [x_norm, _, _] = tf.nn.fused_batch_norm( x, scale, offset, mean, variance, parameters["epsilon"], data_format="NHWC", is_training=False) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_conv_tests(zip_path): """Make a set of tests to do convolution.""" test_parameters = [ { "input_shape": [[1, 3, 4, 3]], "filter_shape": [[1, 1, 3, 2]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True, False], }, { "input_shape": [[2, 14, 14, 2]], "filter_shape": [[6, 6, 2, 2]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True, False], } ] def build_graph(parameters): """Build a conv graph given `parameters`.""" input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data(np.float32, parameters["filter_shape"]) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=parameters["filter_shape"]) input_tensors = [input_tensor, filter_input] out = tf.nn.conv2d( input_tensor, filter_input, strides=parameters["strides"], dilations=parameters["dilations"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. values = [create_tensor_data(np.float32, parameters["input_shape"])] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, parameters["filter_shape"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_depthwiseconv_tests(zip_path): """Make a set of tests to do convolution.""" # Tensorflow only supports equal strides test_parameters = [ { "input_shape": [[1, 3, 4, 3], [1, 10, 10, 3]], "filter_size": [[1, 1], [1, 2], [3, 3]], "strides": [[1, 1, 1, 1], [1, 3, 3, 1]], "channel_multiplier": [1, 2], "rate": [[1, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], "constant_filter": [True, False], }, { "input_shape": [[1, 3, 4, 3]], "filter_size": [[1, 1]], "strides": [[1, 1, 2, 1]], # TF needs [1, x, x, 1] "channel_multiplier": [2], "rate": [[2, 2]], # Only [1, 1] is supported "padding": ["SAME"], "data_format": ["NHWC"], "constant_filter": [True, False], } ] def get_tensor_shapes(parameters): input_shape = parameters["input_shape"] filter_size = parameters["filter_size"] filter_shape = filter_size + [ input_shape[3], parameters["channel_multiplier"] ] return [input_shape, filter_shape] def build_graph(parameters): """Build a depthwise conv graph given `parameters`.""" input_shape, filter_shape = get_tensor_shapes(parameters) input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=input_shape) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data(np.float32, filter_shape) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=filter_shape) input_tensors = [input_tensor, filter_input] out = tf.nn.depthwise_conv2d( input_tensor, filter_input, strides=parameters["strides"], rate=parameters["rate"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. input_shape, filter_shape = get_tensor_shapes(parameters) values = [create_tensor_data(np.float32, input_shape)] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, filter_shape)) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_split_tests(zip_path): """Make a set of tests to do tf.split.""" test_parameters = [{ "input_shape": [[1, 3, 4, 6], [2, 4, 1], [6, 4], [8]], "num_or_size_splits": [1, 2, 3, 4, 5, [2, 2]], "axis": [0, 1, 2, 3, -4, -3, -2, -1], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.split( input_tensor, parameters["num_or_size_splits"], parameters["axis"]) return [input_tensor], out def build_inputs(parameters, sess, inputs, outputs): values = [create_tensor_data(np.float32, parameters["input_shape"])] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_concat_tests(zip_path): """Make a set of tests to do concatenation.""" test_parameters = [{ "base_shape": [[1, 3, 4, 3], [3, 4]], "num_tensors": [1, 2, 3, 4, 5, 6], "axis": [0, 1, 2, 3, -3, -2, -1], }] def get_shape(parameters, delta): """Return a tweaked version of 'base_shape'.""" axis = parameters["axis"] shape = parameters["base_shape"][:] if axis < 0: axis += len(shape) if axis < len(shape): shape[axis] += delta return shape def build_graph(parameters): all_tensors = [] for n in range(0, parameters["num_tensors"]): input_tensor = tf.placeholder(dtype=tf.float32, name=("input%d" % n), shape=get_shape(parameters, n)) all_tensors.append(input_tensor) out = tf.concat(all_tensors, parameters["axis"]) return all_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): all_values = [] for n in range(0, parameters["num_tensors"]): input_values = create_tensor_data(np.float32, get_shape(parameters, n)) all_values.append(input_values) return all_values, sess.run( outputs, feed_dict=dict(zip(inputs, all_values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_fully_connected_tests(zip_path): """Make a set of tests to do fully_connected.""" test_parameters = [{ "shape1": [[3, 3]], "shape2": [[3, 3]], "transpose_a": [True, False], "transpose_b": [True, False], "constant_filter": [True, False], }, { "shape1": [[4, 4], [1, 4], [4]], "shape2": [[4, 4], [4, 1], [4]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }, { "shape1": [[40, 37]], "shape2": [[37, 40]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }] def build_graph(parameters): """Build a matmul graph given `parameters`.""" input_tensor1 = tf.placeholder(dtype=tf.float32, name="input1", shape=parameters["shape1"]) # Get input_tensor2 either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: input_tensor2 = create_tensor_data(np.float32, parameters["shape2"]) input_tensors = [input_tensor1] else: input_tensor2 = tf.placeholder( dtype=tf.float32, name="input2", shape=parameters["shape2"]) input_tensors = [input_tensor1, input_tensor2] out = tf.matmul(input_tensor1, input_tensor2, transpose_a=parameters["transpose_a"], transpose_b=parameters["transpose_b"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input_values1) or 2 # tensors (input_values1, input_values2) based on whether the second input # is a constant or variable input. values = [create_tensor_data(np.float32, shape=parameters["shape1"])] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, parameters["shape2"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_l2norm_tests(zip_path): """Make a set of tests to do l2norm.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[5, 7], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], "dim": [0, 1, 2, 3, [2, 3], -2], "epsilon": [None, 1e-12, 1e-3], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) if parameters["epsilon"]: out = tf.nn.l2_normalize( input_tensor, parameters["dim"], epsilon=parameters["epsilon"]) else: out = tf.nn.l2_normalize(input_tensor, parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_local_response_norm_tests(zip_path): """Make a set of tests to do local_response_norm.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3]], "depth_radius": [None, 0, 1, 3, 4, 5], "bias": [None, 0.1, 0.3, -0.1], "alpha": [None, 1, 2, -3], "beta": [None, 0.5, 0.25, 2], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.local_response_normalization( input_tensor, depth_radius=parameters["depth_radius"], bias=parameters["bias"], alpha=parameters["alpha"], beta=parameters["beta"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_pad_tests(zip_path): """Make a set of tests to do pad.""" # TODO(nupurgarg): Add test for tf.uint8. test_parameters = [ { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 1, 2, 1], [2, 1, 1, 1]], "paddings": [[[0, 0], [0, 1], [2, 3], [0, 0]], [[0, 1], [0, 0], [0, 0], [2, 3]]], "constant_paddings": [True, False], }, # Non-4D use case. { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2], [0, 1, 2]], "paddings": [[[0, 1], [2, 3]]], "constant_paddings": [True, False], }, ] def build_graph(parameters): """Build a pad graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) # Get paddings as either a placeholder or constants. if parameters["constant_paddings"]: paddings = parameters["paddings"] input_tensors = [input_tensor] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="padding", shape=shape) input_tensors = [input_tensor, paddings] out = tf.pad(input_tensor, paddings=paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_reshape_tests(zip_path): """Make a set of tests to do reshape.""" # All shapes below are suitable for tensors with 420 elements. test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[3, 4, 5, 7], [4, 105], [21, 5, 2, 2], [420]], "output_shape": [[15, 28], [420], [1, -1, 5, 7], [-1]], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.reshape(input_tensor, shape=parameters["output_shape"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_resize_bilinear_tests(zip_path): """Make a set of tests to do resize_bilinear.""" test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1, 3, 4, 3], [1, 10, 2, 1]], "size": [[1, 1], [4, 3], [2, 2], [5, 6]], "align_corners": [None, True, False], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.image.resize_bilinear(input_tensor, size=parameters["size"], align_corners=parameters["align_corners"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_sigmoid_tests(zip_path): """Make a set of tests to do sigmoid.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [4], [], [1, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.sigmoid(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_softmax_tests(zip_path): """Make a set of tests to do softmax.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [2, 3]], "dim": [-1, 0], }, { "dtype": [tf.float32], "input_shape": [[4, 7]], "dim": [-1, 1], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.softmax(input_tensor, dim=parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_space_to_depth_tests(zip_path): """Make a set of tests to do space_to_depth.""" test_parameters = [{ "dtype": [tf.float32, tf.float16, tf.int32, tf.uint8, tf.int64], "input_shape": [[2, 12, 24, 1]], "block_size": [2, 3, 4], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.space_to_depth(input_tensor, block_size=parameters["block_size"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_space_to_batch_nd_tests(zip_path): """Make a set of tests to do space_to_batch_nd.""" # TODO(nupurgarg): Add test for uint8. test_parameters = [ { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2, 2, 3], [2, 2, 4, 1]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [0, 0]], [[0, 0], [2, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, { "dtype": [tf.float32], "input_shape": [[2, 3, 7, 3]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [2, 0]], [[1, 0], [1, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[1, 4, 4, 4, 1, 1]], "block_shape": [[2, 2, 2]], "paddings": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, ] def build_graph(parameters): """Build a space_to_batch graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get paddings either as a const or as a placeholder (tensor). if parameters["constant_paddings"]: paddings = parameters["paddings"] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="paddings", shape=shape) input_tensors.append(paddings) out = tf.space_to_batch_nd(input_tensor, block_shape, paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_batch_to_space_nd_tests(zip_path): """Make a set of tests to do batch_to_space_nd.""" test_parameters = [ { "dtype": [tf.float32, tf.int64, tf.int32], "input_shape": [[12, 3, 3, 1]], "block_shape": [[1, 4], [2, 2], [3, 4]], "crops": [[[0, 0], [0, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[8, 2, 2, 2, 1, 1]], "block_shape": [[2, 2, 2]], "crops": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, ] def build_graph(parameters): """Build a batch_to_space graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get crops either as a const or as a placeholder (tensor). if parameters["constant_crops"]: crops = parameters["crops"] else: shape = [len(parameters["crops"]), 2] crops = tf.placeholder(dtype=tf.int32, name="crops", shape=shape) input_tensors.append(crops) out = tf.batch_to_space_nd(input_tensor, block_shape, crops) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_crops"]: values.append(np.array(parameters["crops"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_transpose_tests(zip_path): """Make a set of tests to do transpose.""" # TODO(nupurgarg): Add test for uint8. test_parameters = [{ "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[2, 2, 3]], "perm": [[0, 1, 2], [0, 2, 1]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4]], "perm": [[0, 1, 2, 3], [3, 0, 1, 2]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4, 5]], "perm": [[4, 3, 2, 1, 0]], "constant_perm": [True, False], }] def build_graph(parameters): """Build a transpose graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_perm"]: perm = parameters["perm"] input_tensors = [input_tensor] else: shape = [len(parameters["perm"]), 2] perm = tf.placeholder(dtype=tf.int32, name="perm", shape=shape) input_tensors = [input_tensor, perm] out = tf.transpose(input_tensor, perm=perm) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_perm"]: values.append(np.array(parameters["perm"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_squeeze_tests(zip_path): """Make a set of tests to do squeeze.""" test_parameters = [{ "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 2, 1, 3, 1, 4, 1, 1]], "axis": [ None, [], [0, 2], [4, 7], [-1, 0, 2, 0, 7, -6], [1], [2, 3, 2], [-1, -2, -4, -6, -8], [0, 2, 4, 6, 7], [7, 6, 4, 2, 0], [6, 6], [0, 1, 2, 3, 4, 5, 6, 7], [-2, -3, 1, 0, 7, -5] ], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1]], "axis": [None, [], [0], [-1]], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 1, 1, 1, 1]], "axis": [None, [], [0], [3, 0], [-2, 0, 3, 2]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.squeeze(input_tensor, axis=parameters["axis"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_strided_slice_tests(zip_path): """Make a set of tests to do strided_slice.""" # TODO(soroosh): add test/support for uint8. test_parameters = [ # 4-D { "dtype": [tf.float32, tf.int32, tf.int64], "index_type": [tf.int32], "input_shape": [[12, 2, 2, 5]], "begin": [[0, 0, 0, 0], [1, 0, 1, 0]], "end": [[8, 2, 2, 3], [12, 2, 2, 5]], "strides": [None, [2, 1, 3, 1]], "begin_mask": [None, 1, 8], "end_mask": [None, 1, 8], "shrink_axis_mask": [None, 1, 8, 11, 15, -1], "constant_indices": [False, True], }, # TODO(b/73170889) Restore test paramaters removed in cl/191608113. # 2-D { "dtype": [tf.float32, tf.int32, tf.int64], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, 0], [1, 0]], "end": [[2, 3], [2, 2]], "strides": [None, [2, 2]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False, True], }, # Negative strides { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, -1]], "end": [[2, -3]], "strides": [[1, -1]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False], }, ] def build_graph(parameters): """Build graph for stride_slice test.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_indices"]: begin = parameters["begin"] end = parameters["end"] strides = parameters["strides"] tensors = [input_tensor] else: begin = tf.placeholder( dtype=parameters["index_type"], name="begin", shape=[len(parameters["input_shape"])]) end = tf.placeholder( dtype=parameters["index_type"], name="end", shape=[len(parameters["input_shape"])]) strides = ( tf.placeholder( dtype=parameters["index_type"], name="strides", shape=[len(parameters["input_shape"])]) if parameters["strides"] is not None else None) tensors = [input_tensor, begin, end] if strides is not None: tensors.append(strides) out = tf.strided_slice( input_tensor, begin, end, strides, begin_mask=parameters["begin_mask"], end_mask=parameters["end_mask"]) return tensors, [out] def build_inputs(parameters, sess, inputs, outputs): """Build inputs for stride_slice test.""" input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) index_type = _TF_TYPE_INFO[parameters["index_type"]][0] values = [input_values] if not parameters["constant_indices"]: begin_values = np.array(parameters["begin"]).astype(index_type) end_values = np.array(parameters["end"]).astype(index_type) stride_values = ( np.array(parameters["strides"]).astype(index_type) if parameters["strides"] is not None else None) values.append(begin_values) values.append(end_values) if stride_values is not None: values.append(stride_values) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_lstm_tests(zip_path): """Make a set of tests to do basic Lstm cell.""" test_parameters = [ { "dtype": [tf.float32], "num_batchs": [1], "time_step_size": [1], "input_vec_size": [3], "num_cells": [4], }, ] def build_graph(parameters): """Build a simple graph with BasicLSTMCell.""" num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] num_cells = parameters["num_cells"] inputs_after_split = [] for i in xrange(time_step_size): one_timestamp_input = tf.placeholder( dtype=parameters["dtype"], name="split_{}".format(i), shape=[num_batchs, input_vec_size]) inputs_after_split.append(one_timestamp_input) # Currently lstm identifier has a few limitations: only supports # forget_bias == 0, inner state activiation == tanh. # TODO(zhixianyan): Add another test with forget_bias == 1. # TODO(zhixianyan): Add another test with relu as activation. lstm_cell = tf.contrib.rnn.BasicLSTMCell( num_cells, forget_bias=0.0, state_is_tuple=True) cell_outputs, _ = rnn.static_rnn( lstm_cell, inputs_after_split, dtype=tf.float32) out = cell_outputs[-1] return inputs_after_split, [out] def build_inputs(parameters, sess, inputs, outputs): """Feed inputs, assign vairables, and freeze graph.""" with tf.variable_scope("", reuse=True): kernel = tf.get_variable("rnn/basic_lstm_cell/kernel") bias = tf.get_variable("rnn/basic_lstm_cell/bias") kernel_values = create_tensor_data( parameters["dtype"], [kernel.shape[0], kernel.shape[1]], -1, 1) bias_values = create_tensor_data(parameters["dtype"], [bias.shape[0]], 0, 1) sess.run(tf.group(kernel.assign(kernel_values), bias.assign(bias_values))) num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] input_values = [] for _ in xrange(time_step_size): tensor_data = create_tensor_data(parameters["dtype"], [num_batchs, input_vec_size], 0, 1) input_values.append(tensor_data) out = sess.run(outputs, feed_dict=dict(zip(inputs, input_values))) return input_values, out # TODO(zhixianyan): Automatically generate rnn_states for lstm cell. extra_toco_options = ExtraTocoOptions() extra_toco_options.rnn_states = ( "{state_array:rnn/BasicLSTMCellZeroState/zeros," "back_edge_source_array:rnn/basic_lstm_cell/Add_1,size:4}," "{state_array:rnn/BasicLSTMCellZeroState/zeros_1," "back_edge_source_array:rnn/basic_lstm_cell/Mul_2,size:4}") make_zip_of_tests( zip_path, test_parameters, build_graph, build_inputs, extra_toco_options, use_frozen_graph=True) def make_l2_pool(input_tensor, ksize, strides, padding, data_format): """Given an input perform a sequence of TensorFlow ops to produce l2pool.""" return tf.sqrt(tf.nn.avg_pool( tf.square(input_tensor), ksize=ksize, strides=strides, padding=padding, data_format=data_format)) def make_topk_tests(zip_path): """Make a set of tests to do topk.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[10], [5, 20]], }] def build_graph(parameters): """Build the topk op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) k = tf.constant(3, name="k") out = tf.nn.top_k(input_value, k) return [input_value], [out[1]] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_arg_max_tests(zip_path): """Make a set of tests to do arg_max.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[1, 1, 1, 3], [2, 3, 4, 5], [2, 3, 3], [5, 5], [10]], "axis": [0, 1, 2, 3], "output_type": [tf.int32, tf.int64], }] def build_graph(parameters): """Build the topk op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) axis = tf.constant(parameters["axis"], name="axis") out = tf.arg_max(input_value, axis, output_type=parameters["output_type"]) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_less_tests(zip_path): """Make a set of tests to do less.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): """Build the less op testing graph.""" input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.less(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) # Toco binary path provided by the generate rule. bin_path = None def main(unused_args): global bin_path def mkdir_if_not_exist(x): if not os.path.isdir(x): os.mkdir(x) if not os.path.isdir(x): raise RuntimeError("Failed to create dir %r" % x) opstest_path = os.path.join(FLAGS.output_path) mkdir_if_not_exist(opstest_path) out = FLAGS.zip_to_output bin_path = FLAGS.toco test_function = ("make_%s_tests" % out.replace(".zip", "")) if test_function not in globals(): raise RuntimeError("Can't find a test function to create %r. Tried %r" % (out, test_function)) # TODO(ahentz): accessing globals() is not very elegant. We should either # break this file into multiple tests or use decorator-based registration to # avoid using globals(). globals()[test_function](os.path.join(opstest_path, out)) if __name__ == "__main__": FLAGS, unparsed = parser.parse_known_args() if unparsed: print("Usage: %s <path out> <zip file to generate>") else: tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
35.904322
82
0.625063
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import itertools import os import re import sys import tempfile import traceback import zipfile import numpy as np from six import StringIO from six.moves import xrange os.environ["CUDA_VISIBLE_DEVICES"] = "-1" import tensorflow as tf from google.protobuf import text_format from tensorflow.contrib.lite.testing import generate_examples_report as report_lib from tensorflow.python.framework import graph_util as tf_graph_util from tensorflow.python.ops import rnn parser = argparse.ArgumentParser(description="Script to generate TFLite tests.") parser.add_argument("output_path", help="Directory where the outputs will be go.") parser.add_argument("--zip_to_output", type=str, help="Particular zip to output.", required=False) parser.add_argument("--toco", type=str, help="Path to toco tool.", required=True) parser.add_argument( "--known_bugs_are_errors", action="store_true", help=("If a particular model is affected by a known bug," " count it as a toco error.")) parser.add_argument( "--ignore_toco_errors", action="store_true", help="Raise an exception if any toco error is encountered.") parser.add_argument( "--save_graphdefs", action="store_true", help="Include intermediate graphdefs in the output zip files.") RANDOM_SEED = 342 TEST_INPUT_DEPTH = 3 # A map from regular expression to bug number. Any test failure with label # matching the expression will be considered due to the corresponding bug. KNOWN_BUGS = { # TOCO doesn't support scalars as input. r"relu.*input_shape=\[\]": "67587484", r"sigmoid.*input_shape=\[\]": "67645668", r"concat.*num_tensors=1": "67378344", # Transposition in MatMul is not supported. r"fully_connected.*transpose_.=True": "67586970", # Softmax graphs are too complex. r"softmax.*dim=0": "67749831", r"softmax.*input_shape=\[1,3,4,3\]": "67749831", # SpaceToDepth only supports float32. r"space_to_depth.*(float16|int32|uint8|int64)": "68018134", # BatchToSpaceND only supports 4D tensors. r"batch_to_space_nd.*input_shape=\[8,2,2,2,1,1\]": "70594733", # Div will use floordiv. r"div.*int32": "72051395", # TOCO require matching dimensions in strided_slice. r"strided_slice.*begin=\[0\].*end=\[1\].*": "73170889", # No support for SplitV r"split.*num_or_size_splits=\[2,2\]": "73377559", # Needs support for dimensions other than the last one in argmax. r"arg_max.*axis=0.*": "77546240", r"arg_max.*axis=1.*": "77546240", r"arg_max.*axis=2.*": "77546240", } class ExtraTocoOptions(object): def __init__(self): # Whether to ignore control dependency nodes. self.drop_control_dependency = False # Allow custom ops in the toco conversion. self.allow_custom_ops = False # Rnn states that are used to support rnn / lstm cells. self.rnn_states = None def toco_options(data_types, input_arrays, output_arrays, shapes, extra_toco_options=ExtraTocoOptions()): shape_str = ":".join([",".join(str(y) for y in x) for x in shapes]) inference_type = "FLOAT" # TODO(ahentz): if we get multi-input quantization to work we need this # to change if data_types[0] == "QUANTIZED_UINT8": inference_type = "QUANTIZED_UINT8" s = (" --input_data_types=%s" % ",".join(data_types) + " --inference_type=%s" % inference_type + " --input_format=TENSORFLOW_GRAPHDEF" + " --output_format=TFLITE" + " --input_arrays=%s" % ",".join(input_arrays) + " --input_shapes=%s" % shape_str + " --output_arrays=%s" % ",".join(output_arrays)) if extra_toco_options.drop_control_dependency: s += " --drop_control_dependency" if extra_toco_options.allow_custom_ops: s += " --allow_custom_ops" if extra_toco_options.rnn_states: s += (" --rnn_states='" + extra_toco_options.rnn_states + "'") return s def write_examples(fp, examples): def write_tensor(fp, x): fp.write("dtype,%s\n" % x.dtype) fp.write("shape," + ",".join(map(str, x.shape)) + "\n") # Output 9 digits after the point to ensure the precision is good enough. values = ["{:.9f}".format(value) for value in list(x.flatten())] fp.write("values," + ",".join(values) + "\n") fp.write("test_cases,%d\n" % len(examples)) for example in examples: fp.write("inputs,%d\n" % len(example["inputs"])) for i in example["inputs"]: write_tensor(fp, i) fp.write("outputs,%d\n" % len(example["outputs"])) for i in example["outputs"]: write_tensor(fp, i) def write_test_cases(fp, model_name, examples): fp.write("load_model: %s\n" % os.path.basename(model_name)) for example in examples: fp.write("reshape {\n") for t in example["inputs"]: fp.write(" input: \"" + ",".join(map(str, t.shape)) + "\"\n") fp.write("}\n") fp.write("invoke {\n") for t in example["inputs"]: values = ["{:.9f}".format(value) for value in list(t.flatten())] fp.write(" input: \"" + ",".join(values) + "\"\n") for t in example["outputs"]: values = ["{:.9f}".format(value) for value in list(t.flatten())] fp.write(" output: \"" + ",".join(values) + "\"\n") fp.write("}\n") _TF_TYPE_INFO = { tf.float32: (np.float32, "FLOAT"), tf.float16: (np.float16, "FLOAT"), tf.int32: (np.int32, "INT32"), tf.uint8: (np.uint8, "QUANTIZED_UINT8"), tf.int64: (np.int64, "INT64"), } def create_tensor_data(dtype, shape, min_value=-100, max_value=100): if dtype in _TF_TYPE_INFO: dtype = _TF_TYPE_INFO[dtype][0] if dtype in (tf.float32, tf.float16): value = (max_value-min_value)*np.random.random_sample(shape)+min_value elif dtype in (tf.int32, tf.uint8, tf.int64): value = np.random.randint(min_value, max_value+1, shape) return value.astype(dtype) def freeze_graph(session, outputs): return tf_graph_util.convert_variables_to_constants( session, session.graph.as_graph_def(), [x.op.name for x in outputs]) def make_control_dep_tests(zip_path): test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) filter_value = tf.zeros((3, 3, TEST_INPUT_DEPTH, 8), tf.float32) assert_op = tf.assert_greater_equal(input_tensor, input_tensor - 1) with tf.control_dependencies([assert_op]): out = tf.nn.conv2d(input_tensor, filter_value, strides=(1, 1, 1, 1), padding="SAME") return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) extra_toco_options = ExtraTocoOptions() extra_toco_options.drop_control_dependency = True make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs, extra_toco_options) def toco_convert(graph_def_str, input_tensors, output_tensors, extra_toco_options): data_types = [_TF_TYPE_INFO[x[2]][1] for x in input_tensors] opts = toco_options( data_types=data_types, input_arrays=[x[0] for x in input_tensors], shapes=[x[1] for x in input_tensors], output_arrays=output_tensors, extra_toco_options=extra_toco_options) with tempfile.NamedTemporaryFile() as graphdef_file, \ tempfile.NamedTemporaryFile() as output_file, \ tempfile.NamedTemporaryFile("w+") as stdout_file: graphdef_file.write(graph_def_str) graphdef_file.flush() # TODO(aselle): Switch this to subprocess at some point. cmd = ("%s --input_file=%s --output_file=%s %s > %s 2>&1" % (bin_path, graphdef_file.name, output_file.name, opts, stdout_file.name)) exit_code = os.system(cmd) log = ( cmd + "exited with code %d" % exit_code + "\n------------------\n" + stdout_file.read()) return (None if exit_code != 0 else output_file.read()), log def normalize_output_name(output_name): return output_name.split(":")[0] if output_name.endswith( ":0") else output_name def make_zip_of_tests(zip_path, test_parameters, make_graph, make_test_inputs, extra_toco_options=ExtraTocoOptions(), use_frozen_graph=False): # TODO(aselle): Make this allow multiple inputs outputs. archive = zipfile.PyZipFile(zip_path, "w") zip_manifest = [] convert_report = [] toco_errors = 0 for parameters in test_parameters: keys = parameters.keys() for curr in itertools.product(*parameters.values()): label = zip_path.replace(".zip", "") + (",".join( "%s=%r" % z for z in sorted(zip(keys, curr))).replace(" ", "")) if label[0] == "/": label = label[1:] param_dict = dict(zip(keys, curr)) def build_example(label, param_dict_real): np.random.seed(RANDOM_SEED) report = {"toco": report_lib.NOTRUN, "tf": report_lib.FAILED} # Build graph report["tf_log"] = "" report["toco_log"] = "" tf.reset_default_graph() with tf.device("/cpu:0"): try: inputs, outputs = make_graph(param_dict_real) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report sess = tf.Session() try: baseline_inputs, baseline_outputs = (make_test_inputs( param_dict_real, sess, inputs, outputs)) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report report["toco"] = report_lib.FAILED report["tf"] = report_lib.SUCCESS # Convert graph to toco input_tensors = [(input_tensor.name.split(":")[0], input_tensor.get_shape(), input_tensor.dtype) for input_tensor in inputs] output_tensors = [normalize_output_name(out.name) for out in outputs] graph_def = freeze_graph( sess, tf.global_variables() + inputs + outputs) if use_frozen_graph else sess.graph_def tflite_model_binary, toco_log = toco_convert( graph_def.SerializeToString(), input_tensors, output_tensors, extra_toco_options) report["toco"] = (report_lib.SUCCESS if tflite_model_binary is not None else report_lib.FAILED) report["toco_log"] = toco_log if FLAGS.save_graphdefs: archive.writestr(label + ".pb", text_format.MessageToString(graph_def), zipfile.ZIP_DEFLATED) if tflite_model_binary: archive.writestr(label + ".bin", tflite_model_binary, zipfile.ZIP_DEFLATED) example = {"inputs": baseline_inputs, "outputs": baseline_outputs} example_fp = StringIO() write_examples(example_fp, [example]) archive.writestr(label + ".inputs", example_fp.getvalue(), zipfile.ZIP_DEFLATED) example_fp2 = StringIO() write_test_cases(example_fp2, label + ".bin", [example]) archive.writestr(label + "_tests.txt", example_fp2.getvalue(), zipfile.ZIP_DEFLATED) zip_manifest.append(label + "\n") return tflite_model_binary, report _, report = build_example(label, param_dict) if report["toco"] == report_lib.FAILED: ignore_error = False if not FLAGS.known_bugs_are_errors: for pattern, bug_number in KNOWN_BUGS.items(): if re.search(pattern, label): print("Ignored TOCO error due to bug %s" % bug_number) ignore_error = True if not ignore_error: toco_errors += 1 print("-----------------\ntoco error!\n%s\n-----------------\n" % report["toco_log"]) convert_report.append((param_dict, report)) report_io = StringIO() report_lib.make_report_table(report_io, zip_path, convert_report) archive.writestr("report.html", report_io.getvalue()) archive.writestr("manifest.txt", "".join(zip_manifest), zipfile.ZIP_DEFLATED) # Log statistics of what succeeded total_conversions = len(convert_report) tf_success = sum(1 for x in convert_report if x[1]["tf"] == report_lib.SUCCESS) toco_success = sum(1 for x in convert_report if x[1]["toco"] == report_lib.SUCCESS) percent = 0 if tf_success > 0: percent = float(toco_success) / float(tf_success) * 100. tf.logging.info(("Archive %s Considered %d graphs, %d TF evaluated graphs " " and %d TOCO converted graphs (%.1f%%"), zip_path, total_conversions, tf_success, toco_success, percent) if not FLAGS.ignore_toco_errors and toco_errors > 0: raise RuntimeError( "Found %d errors while generating toco models" % toco_errors) def make_pool_tests(pool_op_in): pool_op = pool_op_in def f(zip_path): # Chose a set of parameters test_parameters = [{ "ksize": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], "strides": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], # TODO(aselle): should add in a degenerate shape (e.g. [1, 0, 1, 1]). "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = pool_op( input_tensor, ksize=parameters["ksize"], strides=parameters["strides"], data_format=parameters["data_format"], padding=parameters["padding"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) return f def make_l2_pool_tests(zip_path): make_pool_tests(make_l2_pool)(zip_path) def make_avg_pool_tests(zip_path): make_pool_tests(tf.nn.avg_pool)(zip_path) def make_max_pool_tests(zip_path): make_pool_tests(tf.nn.max_pool)(zip_path) def make_relu_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_relu1_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Note that the following is not supported: # out = tf.maximum(-1.0, tf.minimum(input_tensor, 1.0)) out = tf.minimum(1.0, tf.maximum(input_tensor, -1.0)) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_relu6_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) # This function tests various TensorFLow functions that generates Const op, # including `tf.ones`, `tf.zeros` and random functions. def make_constant_tests(zip_path): test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1], [2], [1, 1, 1, 1], [2, 2, 2, 2]], }] def build_graph(parameters): # Since Toco & Tflite can't have a single constant op in the entire graph, input1 = tf.placeholder(dtype=parameters["dtype"], name="input1", shape=parameters["input_shape"]) out = tf.ones(parameters["input_shape"], dtype=parameters["dtype"]) + input1 return [input1], [out] def build_inputs(parameters, sess, inputs, outputs): input1 = np.zeros(parameters["input_shape"], dtype=_TF_TYPE_INFO[parameters["dtype"]][0]) return [input1], sess.run(outputs, feed_dict={inputs[0]: input1}) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_binary_op_tests(zip_path, binary_operator): test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[1, 3, 4, 3]], "activation": [True] }, { "dtype": [tf.float32], "input_shape_1": [[5]], "input_shape_2": [[5]], "activation": [False, True] }, { "dtype": [tf.float32], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[3]], "activation": [True] }] def build_graph(parameters): input1 = tf.placeholder( dtype=parameters["dtype"], name="input1", shape=parameters["input_shape_1"]) input2 = tf.placeholder( dtype=parameters["dtype"], name="input2", shape=parameters["input_shape_2"]) out = binary_operator(input1, input2) if parameters["activation"]: out = tf.nn.relu(out) return [input1, input2], [out] def build_inputs(parameters, sess, inputs, outputs): input1 = create_tensor_data(parameters["dtype"], parameters["input_shape_1"]) input2 = create_tensor_data(parameters["dtype"], parameters["input_shape_2"]) return [input1, input2], sess.run( outputs, feed_dict={ inputs[0]: input1, inputs[1]: input2 }) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_mean_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[3, 2, 4]], "axis": [ None, 0, 1, 2, [0, 1], [0, 2], [1, 2], [0, 1, 2], [1, 0], [2, 0], [2, 1], [2, 1, 0], [2, 0, 1], -1, -2, -3, [1, -1], [0, -1], [-1, 0], [-1, -2, -3], [0, 0, 0], [2, 2, 0], [1, 0, -3, -3] ], "const_axis": [True, False], "keepdims": [True, False], }, { "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[1, 224, 224, 3]], "axis": [ None, 0, 1, 2, 3, [1, 2], [0, 3], [1, 2, 3], [0, 1, 2, 3], [3, 2, 1, 0], [3, 1, 0, 2], [2, 0], [3, 0], [3, 1], [1, 0], -1, -2, -3, -4, [0, -2], [2, 3, -1, 0], [3, 1, 2, -3], [3, -4], [2, 2, 2], [2, 2, 3], [-3, -3, -4], [-3, 2, 1] ], "const_axis": [True, False], "keepdims": [True, False], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) # Get axis as either a placeholder or constants. if parameters["const_axis"]: axis = parameters["axis"] input_tensors = [input_tensor] else: if isinstance(parameters["axis"], list): shape = [len(parameters["axis"])] else: shape = [0] # shape for None or integers. axis = tf.placeholder(dtype=tf.int32, name="axis", shape=shape) input_tensors = [input_tensor, axis] out = tf.reduce_mean( input_tensor, axis=axis, keepdims=parameters["keepdims"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) ] if not parameters["const_axis"]: if parameters["axis"]: values.append(np.array(parameters["axis"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_exp_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.exp(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_log_softmax_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[1, 100], [4, 2], [5, 224]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.log_softmax(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data( parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_maximum_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.maximum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_minimum_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.minimum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_binary_op_tests_func(binary_operator): return lambda zip_path: make_binary_op_tests(zip_path, binary_operator) def make_add_tests(zip_path): make_binary_op_tests(zip_path, tf.add) def make_div_tests(zip_path): make_binary_op_tests(zip_path, tf.div) def make_sub_tests(zip_path): make_binary_op_tests(zip_path, tf.subtract) def make_mul_tests(zip_path): make_binary_op_tests(zip_path, tf.multiply) def make_gather_tests(zip_path): test_parameters = [{ # TODO(mgubin): add string tests when they are supported by Toco. # TODO(mgubin): add tests for Nd indices when they are supported by # TfLite. "params_dtype": [tf.float32, tf.int32], "params_shape": [[10], [1, 2, 20]], "indices_dtype": [tf.int32], "indices_shape": [[3], [5]], "axis": [0, 1], }] def build_graph(parameters): params = tf.placeholder( dtype=parameters["params_dtype"], name="params", shape=parameters["params_shape"]) indices = tf.placeholder( dtype=parameters["indices_dtype"], name="indices", shape=parameters["indices_shape"]) out = tf.gather(params, indices, axis=parameters["axis"]) return [params, indices], [out] def build_inputs(parameters, sess, inputs, outputs): params = create_tensor_data(parameters["params_dtype"], parameters["params_shape"]) indices = create_tensor_data(parameters["indices_dtype"], parameters["indices_shape"], 0, parameters["params_shape"][0] - 1) return [params, indices], sess.run( outputs, feed_dict=dict(zip(inputs, [params, indices]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_global_batch_norm_tests(zip_path): test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2], [3, 4, 5, 4]], "epsilon": [0.1, 0.0001], "scale_after": [True, False], }] def build_graph(parameters): input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) x_norm = tf.nn.batch_norm_with_global_normalization( x, mean, variance, scale, offset, parameters["epsilon"], parameters["scale_after"]) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_fused_batch_norm_tests(zip_path): test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2]], "epsilon": [0.001, 0.1], }] def build_graph(parameters): input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) [x_norm, _, _] = tf.nn.fused_batch_norm( x, scale, offset, mean, variance, parameters["epsilon"], data_format="NHWC", is_training=False) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_conv_tests(zip_path): test_parameters = [ { "input_shape": [[1, 3, 4, 3]], "filter_shape": [[1, 1, 3, 2]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True, False], }, { "input_shape": [[2, 14, 14, 2]], "filter_shape": [[6, 6, 2, 2]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True, False], } ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data(np.float32, parameters["filter_shape"]) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=parameters["filter_shape"]) input_tensors = [input_tensor, filter_input] out = tf.nn.conv2d( input_tensor, filter_input, strides=parameters["strides"], dilations=parameters["dilations"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. values = [create_tensor_data(np.float32, parameters["input_shape"])] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, parameters["filter_shape"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_depthwiseconv_tests(zip_path): # Tensorflow only supports equal strides test_parameters = [ { "input_shape": [[1, 3, 4, 3], [1, 10, 10, 3]], "filter_size": [[1, 1], [1, 2], [3, 3]], "strides": [[1, 1, 1, 1], [1, 3, 3, 1]], "channel_multiplier": [1, 2], "rate": [[1, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], "constant_filter": [True, False], }, { "input_shape": [[1, 3, 4, 3]], "filter_size": [[1, 1]], "strides": [[1, 1, 2, 1]], # TF needs [1, x, x, 1] "channel_multiplier": [2], "rate": [[2, 2]], # Only [1, 1] is supported "padding": ["SAME"], "data_format": ["NHWC"], "constant_filter": [True, False], } ] def get_tensor_shapes(parameters): input_shape = parameters["input_shape"] filter_size = parameters["filter_size"] filter_shape = filter_size + [ input_shape[3], parameters["channel_multiplier"] ] return [input_shape, filter_shape] def build_graph(parameters): input_shape, filter_shape = get_tensor_shapes(parameters) input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=input_shape) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data(np.float32, filter_shape) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=filter_shape) input_tensors = [input_tensor, filter_input] out = tf.nn.depthwise_conv2d( input_tensor, filter_input, strides=parameters["strides"], rate=parameters["rate"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. input_shape, filter_shape = get_tensor_shapes(parameters) values = [create_tensor_data(np.float32, input_shape)] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, filter_shape)) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_split_tests(zip_path): test_parameters = [{ "input_shape": [[1, 3, 4, 6], [2, 4, 1], [6, 4], [8]], "num_or_size_splits": [1, 2, 3, 4, 5, [2, 2]], "axis": [0, 1, 2, 3, -4, -3, -2, -1], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.split( input_tensor, parameters["num_or_size_splits"], parameters["axis"]) return [input_tensor], out def build_inputs(parameters, sess, inputs, outputs): values = [create_tensor_data(np.float32, parameters["input_shape"])] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_concat_tests(zip_path): test_parameters = [{ "base_shape": [[1, 3, 4, 3], [3, 4]], "num_tensors": [1, 2, 3, 4, 5, 6], "axis": [0, 1, 2, 3, -3, -2, -1], }] def get_shape(parameters, delta): axis = parameters["axis"] shape = parameters["base_shape"][:] if axis < 0: axis += len(shape) if axis < len(shape): shape[axis] += delta return shape def build_graph(parameters): all_tensors = [] for n in range(0, parameters["num_tensors"]): input_tensor = tf.placeholder(dtype=tf.float32, name=("input%d" % n), shape=get_shape(parameters, n)) all_tensors.append(input_tensor) out = tf.concat(all_tensors, parameters["axis"]) return all_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): all_values = [] for n in range(0, parameters["num_tensors"]): input_values = create_tensor_data(np.float32, get_shape(parameters, n)) all_values.append(input_values) return all_values, sess.run( outputs, feed_dict=dict(zip(inputs, all_values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_fully_connected_tests(zip_path): test_parameters = [{ "shape1": [[3, 3]], "shape2": [[3, 3]], "transpose_a": [True, False], "transpose_b": [True, False], "constant_filter": [True, False], }, { "shape1": [[4, 4], [1, 4], [4]], "shape2": [[4, 4], [4, 1], [4]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }, { "shape1": [[40, 37]], "shape2": [[37, 40]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }] def build_graph(parameters): input_tensor1 = tf.placeholder(dtype=tf.float32, name="input1", shape=parameters["shape1"]) # Get input_tensor2 either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: input_tensor2 = create_tensor_data(np.float32, parameters["shape2"]) input_tensors = [input_tensor1] else: input_tensor2 = tf.placeholder( dtype=tf.float32, name="input2", shape=parameters["shape2"]) input_tensors = [input_tensor1, input_tensor2] out = tf.matmul(input_tensor1, input_tensor2, transpose_a=parameters["transpose_a"], transpose_b=parameters["transpose_b"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input_values1) or 2 # tensors (input_values1, input_values2) based on whether the second input # is a constant or variable input. values = [create_tensor_data(np.float32, shape=parameters["shape1"])] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, parameters["shape2"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_l2norm_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[5, 7], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], "dim": [0, 1, 2, 3, [2, 3], -2], "epsilon": [None, 1e-12, 1e-3], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) if parameters["epsilon"]: out = tf.nn.l2_normalize( input_tensor, parameters["dim"], epsilon=parameters["epsilon"]) else: out = tf.nn.l2_normalize(input_tensor, parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_local_response_norm_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3]], "depth_radius": [None, 0, 1, 3, 4, 5], "bias": [None, 0.1, 0.3, -0.1], "alpha": [None, 1, 2, -3], "beta": [None, 0.5, 0.25, 2], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.local_response_normalization( input_tensor, depth_radius=parameters["depth_radius"], bias=parameters["bias"], alpha=parameters["alpha"], beta=parameters["beta"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_pad_tests(zip_path): # TODO(nupurgarg): Add test for tf.uint8. test_parameters = [ { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 1, 2, 1], [2, 1, 1, 1]], "paddings": [[[0, 0], [0, 1], [2, 3], [0, 0]], [[0, 1], [0, 0], [0, 0], [2, 3]]], "constant_paddings": [True, False], }, # Non-4D use case. { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2], [0, 1, 2]], "paddings": [[[0, 1], [2, 3]]], "constant_paddings": [True, False], }, ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) # Get paddings as either a placeholder or constants. if parameters["constant_paddings"]: paddings = parameters["paddings"] input_tensors = [input_tensor] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="padding", shape=shape) input_tensors = [input_tensor, paddings] out = tf.pad(input_tensor, paddings=paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_reshape_tests(zip_path): # All shapes below are suitable for tensors with 420 elements. test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[3, 4, 5, 7], [4, 105], [21, 5, 2, 2], [420]], "output_shape": [[15, 28], [420], [1, -1, 5, 7], [-1]], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.reshape(input_tensor, shape=parameters["output_shape"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_resize_bilinear_tests(zip_path): test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1, 3, 4, 3], [1, 10, 2, 1]], "size": [[1, 1], [4, 3], [2, 2], [5, 6]], "align_corners": [None, True, False], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.image.resize_bilinear(input_tensor, size=parameters["size"], align_corners=parameters["align_corners"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_sigmoid_tests(zip_path): test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [4], [], [1, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.sigmoid(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_softmax_tests(zip_path): test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [2, 3]], "dim": [-1, 0], }, { "dtype": [tf.float32], "input_shape": [[4, 7]], "dim": [-1, 1], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.softmax(input_tensor, dim=parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_space_to_depth_tests(zip_path): test_parameters = [{ "dtype": [tf.float32, tf.float16, tf.int32, tf.uint8, tf.int64], "input_shape": [[2, 12, 24, 1]], "block_size": [2, 3, 4], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.space_to_depth(input_tensor, block_size=parameters["block_size"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_space_to_batch_nd_tests(zip_path): # TODO(nupurgarg): Add test for uint8. test_parameters = [ { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2, 2, 3], [2, 2, 4, 1]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [0, 0]], [[0, 0], [2, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, { "dtype": [tf.float32], "input_shape": [[2, 3, 7, 3]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [2, 0]], [[1, 0], [1, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[1, 4, 4, 4, 1, 1]], "block_shape": [[2, 2, 2]], "paddings": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get paddings either as a const or as a placeholder (tensor). if parameters["constant_paddings"]: paddings = parameters["paddings"] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="paddings", shape=shape) input_tensors.append(paddings) out = tf.space_to_batch_nd(input_tensor, block_shape, paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_batch_to_space_nd_tests(zip_path): test_parameters = [ { "dtype": [tf.float32, tf.int64, tf.int32], "input_shape": [[12, 3, 3, 1]], "block_shape": [[1, 4], [2, 2], [3, 4]], "crops": [[[0, 0], [0, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[8, 2, 2, 2, 1, 1]], "block_shape": [[2, 2, 2]], "crops": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get crops either as a const or as a placeholder (tensor). if parameters["constant_crops"]: crops = parameters["crops"] else: shape = [len(parameters["crops"]), 2] crops = tf.placeholder(dtype=tf.int32, name="crops", shape=shape) input_tensors.append(crops) out = tf.batch_to_space_nd(input_tensor, block_shape, crops) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_crops"]: values.append(np.array(parameters["crops"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_transpose_tests(zip_path): # TODO(nupurgarg): Add test for uint8. test_parameters = [{ "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[2, 2, 3]], "perm": [[0, 1, 2], [0, 2, 1]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4]], "perm": [[0, 1, 2, 3], [3, 0, 1, 2]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4, 5]], "perm": [[4, 3, 2, 1, 0]], "constant_perm": [True, False], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_perm"]: perm = parameters["perm"] input_tensors = [input_tensor] else: shape = [len(parameters["perm"]), 2] perm = tf.placeholder(dtype=tf.int32, name="perm", shape=shape) input_tensors = [input_tensor, perm] out = tf.transpose(input_tensor, perm=perm) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_perm"]: values.append(np.array(parameters["perm"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_squeeze_tests(zip_path): test_parameters = [{ "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 2, 1, 3, 1, 4, 1, 1]], "axis": [ None, [], [0, 2], [4, 7], [-1, 0, 2, 0, 7, -6], [1], [2, 3, 2], [-1, -2, -4, -6, -8], [0, 2, 4, 6, 7], [7, 6, 4, 2, 0], [6, 6], [0, 1, 2, 3, 4, 5, 6, 7], [-2, -3, 1, 0, 7, -5] ], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1]], "axis": [None, [], [0], [-1]], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 1, 1, 1, 1]], "axis": [None, [], [0], [3, 0], [-2, 0, 3, 2]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.squeeze(input_tensor, axis=parameters["axis"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_strided_slice_tests(zip_path): # TODO(soroosh): add test/support for uint8. test_parameters = [ # 4-D { "dtype": [tf.float32, tf.int32, tf.int64], "index_type": [tf.int32], "input_shape": [[12, 2, 2, 5]], "begin": [[0, 0, 0, 0], [1, 0, 1, 0]], "end": [[8, 2, 2, 3], [12, 2, 2, 5]], "strides": [None, [2, 1, 3, 1]], "begin_mask": [None, 1, 8], "end_mask": [None, 1, 8], "shrink_axis_mask": [None, 1, 8, 11, 15, -1], "constant_indices": [False, True], }, # TODO(b/73170889) Restore test paramaters removed in cl/191608113. # 2-D { "dtype": [tf.float32, tf.int32, tf.int64], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, 0], [1, 0]], "end": [[2, 3], [2, 2]], "strides": [None, [2, 2]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False, True], }, # Negative strides { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, -1]], "end": [[2, -3]], "strides": [[1, -1]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False], }, ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_indices"]: begin = parameters["begin"] end = parameters["end"] strides = parameters["strides"] tensors = [input_tensor] else: begin = tf.placeholder( dtype=parameters["index_type"], name="begin", shape=[len(parameters["input_shape"])]) end = tf.placeholder( dtype=parameters["index_type"], name="end", shape=[len(parameters["input_shape"])]) strides = ( tf.placeholder( dtype=parameters["index_type"], name="strides", shape=[len(parameters["input_shape"])]) if parameters["strides"] is not None else None) tensors = [input_tensor, begin, end] if strides is not None: tensors.append(strides) out = tf.strided_slice( input_tensor, begin, end, strides, begin_mask=parameters["begin_mask"], end_mask=parameters["end_mask"]) return tensors, [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) index_type = _TF_TYPE_INFO[parameters["index_type"]][0] values = [input_values] if not parameters["constant_indices"]: begin_values = np.array(parameters["begin"]).astype(index_type) end_values = np.array(parameters["end"]).astype(index_type) stride_values = ( np.array(parameters["strides"]).astype(index_type) if parameters["strides"] is not None else None) values.append(begin_values) values.append(end_values) if stride_values is not None: values.append(stride_values) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_lstm_tests(zip_path): test_parameters = [ { "dtype": [tf.float32], "num_batchs": [1], "time_step_size": [1], "input_vec_size": [3], "num_cells": [4], }, ] def build_graph(parameters): num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] num_cells = parameters["num_cells"] inputs_after_split = [] for i in xrange(time_step_size): one_timestamp_input = tf.placeholder( dtype=parameters["dtype"], name="split_{}".format(i), shape=[num_batchs, input_vec_size]) inputs_after_split.append(one_timestamp_input) # Currently lstm identifier has a few limitations: only supports # forget_bias == 0, inner state activiation == tanh. # TODO(zhixianyan): Add another test with forget_bias == 1. # TODO(zhixianyan): Add another test with relu as activation. lstm_cell = tf.contrib.rnn.BasicLSTMCell( num_cells, forget_bias=0.0, state_is_tuple=True) cell_outputs, _ = rnn.static_rnn( lstm_cell, inputs_after_split, dtype=tf.float32) out = cell_outputs[-1] return inputs_after_split, [out] def build_inputs(parameters, sess, inputs, outputs): with tf.variable_scope("", reuse=True): kernel = tf.get_variable("rnn/basic_lstm_cell/kernel") bias = tf.get_variable("rnn/basic_lstm_cell/bias") kernel_values = create_tensor_data( parameters["dtype"], [kernel.shape[0], kernel.shape[1]], -1, 1) bias_values = create_tensor_data(parameters["dtype"], [bias.shape[0]], 0, 1) sess.run(tf.group(kernel.assign(kernel_values), bias.assign(bias_values))) num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] input_values = [] for _ in xrange(time_step_size): tensor_data = create_tensor_data(parameters["dtype"], [num_batchs, input_vec_size], 0, 1) input_values.append(tensor_data) out = sess.run(outputs, feed_dict=dict(zip(inputs, input_values))) return input_values, out # TODO(zhixianyan): Automatically generate rnn_states for lstm cell. extra_toco_options = ExtraTocoOptions() extra_toco_options.rnn_states = ( "{state_array:rnn/BasicLSTMCellZeroState/zeros," "back_edge_source_array:rnn/basic_lstm_cell/Add_1,size:4}," "{state_array:rnn/BasicLSTMCellZeroState/zeros_1," "back_edge_source_array:rnn/basic_lstm_cell/Mul_2,size:4}") make_zip_of_tests( zip_path, test_parameters, build_graph, build_inputs, extra_toco_options, use_frozen_graph=True) def make_l2_pool(input_tensor, ksize, strides, padding, data_format): return tf.sqrt(tf.nn.avg_pool( tf.square(input_tensor), ksize=ksize, strides=strides, padding=padding, data_format=data_format)) def make_topk_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[10], [5, 20]], }] def build_graph(parameters): input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) k = tf.constant(3, name="k") out = tf.nn.top_k(input_value, k) return [input_value], [out[1]] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_arg_max_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[1, 1, 1, 3], [2, 3, 4, 5], [2, 3, 3], [5, 5], [10]], "axis": [0, 1, 2, 3], "output_type": [tf.int32, tf.int64], }] def build_graph(parameters): input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) axis = tf.constant(parameters["axis"], name="axis") out = tf.arg_max(input_value, axis, output_type=parameters["output_type"]) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_less_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.less(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) # Toco binary path provided by the generate rule. bin_path = None def main(unused_args): global bin_path def mkdir_if_not_exist(x): if not os.path.isdir(x): os.mkdir(x) if not os.path.isdir(x): raise RuntimeError("Failed to create dir %r" % x) opstest_path = os.path.join(FLAGS.output_path) mkdir_if_not_exist(opstest_path) out = FLAGS.zip_to_output bin_path = FLAGS.toco test_function = ("make_%s_tests" % out.replace(".zip", "")) if test_function not in globals(): raise RuntimeError("Can't find a test function to create %r. Tried %r" % (out, test_function)) globals()[test_function](os.path.join(opstest_path, out)) if __name__ == "__main__": FLAGS, unparsed = parser.parse_known_args() if unparsed: print("Usage: %s <path out> <zip file to generate>") else: tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
true
true
f72a4e3b9390c65a9d4226e4e2bfa029a474c9d9
10,627
py
Python
work_dirs/bsnet_fcos_test/bsnet_fcos_test.py
zzx0226/mmocr
50354895244339a392b4f1af5a35963883923cca
[ "Apache-2.0" ]
null
null
null
work_dirs/bsnet_fcos_test/bsnet_fcos_test.py
zzx0226/mmocr
50354895244339a392b4f1af5a35963883923cca
[ "Apache-2.0" ]
null
null
null
work_dirs/bsnet_fcos_test/bsnet_fcos_test.py
zzx0226/mmocr
50354895244339a392b4f1af5a35963883923cca
[ "Apache-2.0" ]
null
null
null
checkpoint_config = dict(interval=10) log_config = dict( interval=5, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = None resume_from = None workflow = [('train', 1)] optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='poly', power=0.9, min_lr=1e-07, by_epoch=True) total_epochs = 1500 cp_num = 8 bs_degree = 4 reconstr_points = 100 model = dict( type='BSNet_fcos', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCNv2', deform_groups=2, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='mmdet.FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=0, add_extra_convs='on_output', num_outs=5, relu_before_extra_convs=True), bbox_head=dict( type='BS_FCOSHead', bs_degree=4, cp_num=8, num_classes=1, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 16, 32, 64, 128], loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), postprocessor=dict( type='BSPostprocessor_fcos', bs_degree=4, cp_num=8, num_reconstr_points=100, alpha=1.0, beta=2.0, score_thr=0.1)), train_cfg=None, test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, classes=('text', ))) cp = 14 bs = 4 dataset_type = 'CurveDataset' data_root = '/home/atom/Research_STD/Datasets/mmocr/ctw1500' train = dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) test = dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) train_list = [ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) ] test_list = [ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ] img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) leval_prop_range_icdar2015 = ((0, 0.4), (0.3, 0.7), (0.6, 1.0)) train_pipeline_icdar2015 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ] img_scale_icdar2015 = (2260, 2260) test_pipeline_icdar2015 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='MultiScaleFlipAug', img_scale=(2260, 2260), flip=False, transforms=[ dict(type='Resize', img_scale=(1280, 800), keep_ratio=True), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] train_pipeline_ctw1500 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ] test_pipeline_ctw1500 = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=10, workers_per_gpu=6, val_dataloader=dict(samples_per_gpu=1), test_dataloader=dict(samples_per_gpu=1), train=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) ], pipeline=[ dict( type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict( type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ]), val=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ], pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ]), test=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ], pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ])) evaluation = dict(interval=20, metric='hmean-iou') work_dir = './work_dirs/bsnet_fcos_test' gpu_ids = [1]
35.423333
99
0.555472
checkpoint_config = dict(interval=10) log_config = dict( interval=5, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = None resume_from = None workflow = [('train', 1)] optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='poly', power=0.9, min_lr=1e-07, by_epoch=True) total_epochs = 1500 cp_num = 8 bs_degree = 4 reconstr_points = 100 model = dict( type='BSNet_fcos', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCNv2', deform_groups=2, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='mmdet.FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=0, add_extra_convs='on_output', num_outs=5, relu_before_extra_convs=True), bbox_head=dict( type='BS_FCOSHead', bs_degree=4, cp_num=8, num_classes=1, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 16, 32, 64, 128], loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), postprocessor=dict( type='BSPostprocessor_fcos', bs_degree=4, cp_num=8, num_reconstr_points=100, alpha=1.0, beta=2.0, score_thr=0.1)), train_cfg=None, test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, classes=('text', ))) cp = 14 bs = 4 dataset_type = 'CurveDataset' data_root = '/home/atom/Research_STD/Datasets/mmocr/ctw1500' train = dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) test = dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) train_list = [ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) ] test_list = [ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ] img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) leval_prop_range_icdar2015 = ((0, 0.4), (0.3, 0.7), (0.6, 1.0)) train_pipeline_icdar2015 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ] img_scale_icdar2015 = (2260, 2260) test_pipeline_icdar2015 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='MultiScaleFlipAug', img_scale=(2260, 2260), flip=False, transforms=[ dict(type='Resize', img_scale=(1280, 800), keep_ratio=True), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] train_pipeline_ctw1500 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ] test_pipeline_ctw1500 = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=10, workers_per_gpu=6, val_dataloader=dict(samples_per_gpu=1), test_dataloader=dict(samples_per_gpu=1), train=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) ], pipeline=[ dict( type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict( type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ]), val=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ], pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ]), test=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ], pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ])) evaluation = dict(interval=20, metric='hmean-iou') work_dir = './work_dirs/bsnet_fcos_test' gpu_ids = [1]
true
true
f72a4e46e33271ff312daf81e2aa725c8a324bb1
584
py
Python
code/heap.py
philipmassouh/RoA
ed57d9da44cd04496dfc4c43f11b3ead99d58608
[ "Apache-2.0" ]
null
null
null
code/heap.py
philipmassouh/RoA
ed57d9da44cd04496dfc4c43f11b3ead99d58608
[ "Apache-2.0" ]
null
null
null
code/heap.py
philipmassouh/RoA
ed57d9da44cd04496dfc4c43f11b3ead99d58608
[ "Apache-2.0" ]
null
null
null
def heapify(heap, root): newRoot = root leftChild = 2*root+1 rightChild = 2*root+2 if leftChild < len(heap) and heap[leftChild] > heap[newRoot]: newRoot = leftChild if rightChild < len(heap) and heap[rightChild] > heap[newRoot]: newRoot = rightChild if root!=newRoot: heap[root],heap[newRoot]=heap[newRoot],heap[root] heapify(heap,newRoot) def heapSort(heap): for i in range(len(heap), -1, -1): heapify(heap, i) answer = [] while(len(heap)>1): answer.insert(len(answer),heap[0]) heap[0],heap[-1]=heap[-1],heap[0] heap.pop() heapify(heap, 0) return answer
25.391304
64
0.679795
def heapify(heap, root): newRoot = root leftChild = 2*root+1 rightChild = 2*root+2 if leftChild < len(heap) and heap[leftChild] > heap[newRoot]: newRoot = leftChild if rightChild < len(heap) and heap[rightChild] > heap[newRoot]: newRoot = rightChild if root!=newRoot: heap[root],heap[newRoot]=heap[newRoot],heap[root] heapify(heap,newRoot) def heapSort(heap): for i in range(len(heap), -1, -1): heapify(heap, i) answer = [] while(len(heap)>1): answer.insert(len(answer),heap[0]) heap[0],heap[-1]=heap[-1],heap[0] heap.pop() heapify(heap, 0) return answer
true
true
f72a4e980f110ebf4b26838dad3e5987b3b5af11
8,123
py
Python
shalstm/qa/model.py
alisafaya/shalstm
3d85f29c82451b393975ba587d53e0db0e43fff9
[ "MIT" ]
null
null
null
shalstm/qa/model.py
alisafaya/shalstm
3d85f29c82451b393975ba587d53e0db0e43fff9
[ "MIT" ]
null
null
null
shalstm/qa/model.py
alisafaya/shalstm
3d85f29c82451b393975ba587d53e0db0e43fff9
[ "MIT" ]
null
null
null
import torch.nn as nn import torch from shalstm import SHALSTM from shalstm.utils import top_k_top_p_filtering class SHALSTMforQuestionAnswering(SHALSTM): def forward(self, input, attention_mask=None, type_ids=None, hidden=None, mems=None, return_loss=False, lm_loss=False): """ all arguments have shape (seq length, batch) padding should be on left for input, on right for targets (as in seq2seq models) - type_ids is used both for loss masking and attention masking. it should be 1 for the answer tokens and 0 otherwise. - attention_mask (attention mask) is 0 for paddings and 1 for other tokens """ x = input[:-1].to(self.device) targets = input[1:].to(self.device) seq_len, batch_size = x.shape if attention_mask is None: attention_mask = torch.ones(*x.shape) if type_ids is None: type_ids = torch.zeros(*input.shape) loss_mask = type_ids[1:].view(-1).to(self.device) # encode and dropout input h = self.encoder(x) h = self.idrop(h) # if memory is provided, trim it to fit max memory size if attention_mask is None: attn_mask = torch.full((seq_len, seq_len), -1e6, device=h.device, dtype=h.dtype) # instead of -Inf we use -1,000,000 attn_mask = torch.triu(attn_mask, diagonal=1) # concatenate memories from the previous pass if provided if mems is not None: max_mems = max(len(m) for m in mems) mem_mask = torch.zeros((seq_len, max_mems), device=h.device, dtype=h.dtype) attn_mask = torch.cat([mem_mask, attn_mask], dim=-1) else: attention_mask = attention_mask.to(self.device) attn_mask = torch.full((batch_size, seq_len, seq_len), -1e6, device=self.device, dtype=h.dtype) attn_mask = torch.triu(attn_mask, diagonal=1) for b in range(batch_size): mask = torch.where(attention_mask[:-1, b] == 0) attn_mask[b, :, mask[0]] = -1e6 attn_mask[b, mask[0], :] = -1e6 # concatenate memories from the previous pass if provided if mems is not None: max_mems = max(len(m) for m in mems) mem_mask = torch.zeros((batch_size, seq_len, max_mems), device=h.device, dtype=h.dtype) attn_mask = torch.cat([mem_mask, attn_mask], dim=-1) # iterate over blocks new_hidden, new_mems = [], [] for idx, block in enumerate(self.blocks): mem = mems[idx] if mems is not None else None hid = hidden[idx] if hidden is not None else None h, new_mem, new_hid = block(h, attn_mask, self.memory_size, memory=mem, hidden=hid) new_hidden.append(new_hid) new_mems.append(new_mem) # final dropout h = self.odrop(h) if return_loss: if not lm_loss: # calculate loss targets are provided loss = -(self.splitloss(h.view(-1, self.embed_size), input[1:].to(self.device).view(-1)).output * loss_mask).mean() # .view(*x.shape).mean(0).mean() else: # calculate loss on all tokens loss = self.ate(h.view(-1, self.embed_size), input[1:].to(self.device).view(-1)).loss return loss, h, new_hidden, new_mems else: # calculate predictions output = self.splitloss.log_prob(h.view(-1, self.embed_size)) output = output.view(*x.shape, -1) return output, h, new_hidden, new_mems def conditional_generate(self, input, attention_mask, type_ids, eos_id=2, max_length=64, use_sampling=False, top_p=0.95, temperature=1.0): """ input sequence has shape [seq length, batch size] """ prompt = torch.cat([input, torch.zeros(1, input.shape[1], dtype=torch.long)]) attention_mask = torch.cat([attention_mask, torch.ones(1, attention_mask.shape[1])]) type_ids = torch.cat([type_ids, torch.zeros(1, type_ids.shape[1])]) self.eval() sequences = torch.zeros(max_length, input.shape[1], dtype=torch.long) hidden, mems = None, None with torch.no_grad(): output, h, hidden, mems = self(prompt[:-1], attention_mask=attention_mask[:-1], type_ids=type_ids[:-1], hidden=hidden, mems=mems) prompt = prompt[-2:] attention_mask=attention_mask[-2:] type_ids=type_ids[-2:] for i in range(max_length): output, h, hidden, mems = self(prompt, attention_mask=attention_mask, type_ids=type_ids, hidden=hidden, mems=mems) if use_sampling: raise NotImplementedError token_weights = top_k_top_p_filtering(torch.exp(output.view(-1)) / temperature, top_p=top_p, filter_value=0.0) output_idx = torch.multinomial(token_weights, num_samples=1)[0] else: output_idx = torch.argmax(output, dim=-1) prompt[0, :] = output_idx sequences[i, :] = output_idx if torch.all(output_idx == eos_id): break return sequences if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--model", type=str, default="bin/base/model") parser.add_argument("--tokenizer", type=str, default="tokenizer/tokenizer.json") parser.add_argument("--device", type=str, default="cuda") args = parser.parse_args() model = SHALSTMforQuestionAnswering.from_pretrained(args.model, device=torch.device(args.device)) from tokenizer import SHALSTMTokenizer tokenizer = SHALSTMTokenizer.from_file(args.tokenizer) questions = [ "another thing there", "some length here", ] answers = [ "brother Hi how", "this answer for question one", ] input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, answers) loss, h, hidden, mems = model(input, attn_mask, type_ids, return_loss=True) warmup = 5 total_steps = 1500 optimizer = torch.optim.SGD(model.parameters(), lr=1e-2) scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=[lambda x: float(x / warmup) if x < warmup else float((total_steps - x) / total_steps)]) use_amp = False scaler = torch.cuda.amp.GradScaler(enabled=use_amp) import time starttime = time.time() model.train() for i in range(total_steps): with torch.cuda.amp.autocast(enabled=use_amp): loss, h, hidden, mems = model(input, attn_mask, type_ids, return_loss=True) scaler.scale(loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1) scaler.step(optimizer) scaler.update() scheduler.step() if i % (total_steps // 10) == 0: print(loss.item()) print("Excecution time =", (time.time() - starttime) / total_steps, "sec per batch") questions = [ "question one ?", "some length here", ] answers = [ "this answer to this one", "This is another answer for another question ", ] input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, answers) with torch.no_grad(): model.eval() output, h, hidden, mems = model(input, attn_mask, type_ids) output = torch.argmax(output, dim=-1) ids = output[input_length - 1:].t().cpu().tolist() ids = output.t().cpu().tolist() print(tokenizer.decode(ids[0])) print(tokenizer.decode(ids[1])) input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, direction='left') sequence = model.conditional_generate(input, attn_mask, type_ids, max_length=10, use_sampling=False) print("Conditional generation") print(tokenizer.decode_batch(sequence.t().cpu().tolist()))
38.866029
164
0.612582
import torch.nn as nn import torch from shalstm import SHALSTM from shalstm.utils import top_k_top_p_filtering class SHALSTMforQuestionAnswering(SHALSTM): def forward(self, input, attention_mask=None, type_ids=None, hidden=None, mems=None, return_loss=False, lm_loss=False): x = input[:-1].to(self.device) targets = input[1:].to(self.device) seq_len, batch_size = x.shape if attention_mask is None: attention_mask = torch.ones(*x.shape) if type_ids is None: type_ids = torch.zeros(*input.shape) loss_mask = type_ids[1:].view(-1).to(self.device) h = self.encoder(x) h = self.idrop(h) if attention_mask is None: attn_mask = torch.full((seq_len, seq_len), -1e6, device=h.device, dtype=h.dtype) attn_mask = torch.triu(attn_mask, diagonal=1) if mems is not None: max_mems = max(len(m) for m in mems) mem_mask = torch.zeros((seq_len, max_mems), device=h.device, dtype=h.dtype) attn_mask = torch.cat([mem_mask, attn_mask], dim=-1) else: attention_mask = attention_mask.to(self.device) attn_mask = torch.full((batch_size, seq_len, seq_len), -1e6, device=self.device, dtype=h.dtype) attn_mask = torch.triu(attn_mask, diagonal=1) for b in range(batch_size): mask = torch.where(attention_mask[:-1, b] == 0) attn_mask[b, :, mask[0]] = -1e6 attn_mask[b, mask[0], :] = -1e6 if mems is not None: max_mems = max(len(m) for m in mems) mem_mask = torch.zeros((batch_size, seq_len, max_mems), device=h.device, dtype=h.dtype) attn_mask = torch.cat([mem_mask, attn_mask], dim=-1) new_hidden, new_mems = [], [] for idx, block in enumerate(self.blocks): mem = mems[idx] if mems is not None else None hid = hidden[idx] if hidden is not None else None h, new_mem, new_hid = block(h, attn_mask, self.memory_size, memory=mem, hidden=hid) new_hidden.append(new_hid) new_mems.append(new_mem) h = self.odrop(h) if return_loss: if not lm_loss: loss = -(self.splitloss(h.view(-1, self.embed_size), input[1:].to(self.device).view(-1)).output * loss_mask).mean() else: loss = self.ate(h.view(-1, self.embed_size), input[1:].to(self.device).view(-1)).loss return loss, h, new_hidden, new_mems else: output = self.splitloss.log_prob(h.view(-1, self.embed_size)) output = output.view(*x.shape, -1) return output, h, new_hidden, new_mems def conditional_generate(self, input, attention_mask, type_ids, eos_id=2, max_length=64, use_sampling=False, top_p=0.95, temperature=1.0): prompt = torch.cat([input, torch.zeros(1, input.shape[1], dtype=torch.long)]) attention_mask = torch.cat([attention_mask, torch.ones(1, attention_mask.shape[1])]) type_ids = torch.cat([type_ids, torch.zeros(1, type_ids.shape[1])]) self.eval() sequences = torch.zeros(max_length, input.shape[1], dtype=torch.long) hidden, mems = None, None with torch.no_grad(): output, h, hidden, mems = self(prompt[:-1], attention_mask=attention_mask[:-1], type_ids=type_ids[:-1], hidden=hidden, mems=mems) prompt = prompt[-2:] attention_mask=attention_mask[-2:] type_ids=type_ids[-2:] for i in range(max_length): output, h, hidden, mems = self(prompt, attention_mask=attention_mask, type_ids=type_ids, hidden=hidden, mems=mems) if use_sampling: raise NotImplementedError token_weights = top_k_top_p_filtering(torch.exp(output.view(-1)) / temperature, top_p=top_p, filter_value=0.0) output_idx = torch.multinomial(token_weights, num_samples=1)[0] else: output_idx = torch.argmax(output, dim=-1) prompt[0, :] = output_idx sequences[i, :] = output_idx if torch.all(output_idx == eos_id): break return sequences if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--model", type=str, default="bin/base/model") parser.add_argument("--tokenizer", type=str, default="tokenizer/tokenizer.json") parser.add_argument("--device", type=str, default="cuda") args = parser.parse_args() model = SHALSTMforQuestionAnswering.from_pretrained(args.model, device=torch.device(args.device)) from tokenizer import SHALSTMTokenizer tokenizer = SHALSTMTokenizer.from_file(args.tokenizer) questions = [ "another thing there", "some length here", ] answers = [ "brother Hi how", "this answer for question one", ] input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, answers) loss, h, hidden, mems = model(input, attn_mask, type_ids, return_loss=True) warmup = 5 total_steps = 1500 optimizer = torch.optim.SGD(model.parameters(), lr=1e-2) scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=[lambda x: float(x / warmup) if x < warmup else float((total_steps - x) / total_steps)]) use_amp = False scaler = torch.cuda.amp.GradScaler(enabled=use_amp) import time starttime = time.time() model.train() for i in range(total_steps): with torch.cuda.amp.autocast(enabled=use_amp): loss, h, hidden, mems = model(input, attn_mask, type_ids, return_loss=True) scaler.scale(loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1) scaler.step(optimizer) scaler.update() scheduler.step() if i % (total_steps // 10) == 0: print(loss.item()) print("Excecution time =", (time.time() - starttime) / total_steps, "sec per batch") questions = [ "question one ?", "some length here", ] answers = [ "this answer to this one", "This is another answer for another question ", ] input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, answers) with torch.no_grad(): model.eval() output, h, hidden, mems = model(input, attn_mask, type_ids) output = torch.argmax(output, dim=-1) ids = output[input_length - 1:].t().cpu().tolist() ids = output.t().cpu().tolist() print(tokenizer.decode(ids[0])) print(tokenizer.decode(ids[1])) input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, direction='left') sequence = model.conditional_generate(input, attn_mask, type_ids, max_length=10, use_sampling=False) print("Conditional generation") print(tokenizer.decode_batch(sequence.t().cpu().tolist()))
true
true
f72a4f4af0ffe7527231500fcb530dd4fab8692b
14,981
py
Python
patrole_tempest_plugin/tests/unit/test_rbac_utils.py
openstack/patrole
fa0ee135121a5e86301ad5ee1854b3a0bd70b69b
[ "Apache-2.0" ]
14
2017-01-03T15:07:18.000Z
2020-09-17T18:07:39.000Z
patrole_tempest_plugin/tests/unit/test_rbac_utils.py
openstack/patrole
fa0ee135121a5e86301ad5ee1854b3a0bd70b69b
[ "Apache-2.0" ]
null
null
null
patrole_tempest_plugin/tests/unit/test_rbac_utils.py
openstack/patrole
fa0ee135121a5e86301ad5ee1854b3a0bd70b69b
[ "Apache-2.0" ]
12
2017-02-28T20:08:48.000Z
2020-12-30T09:31:51.000Z
# Copyright 2017 AT&T Corporation. # 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 testtools from unittest import mock from tempest.lib import exceptions as lib_exc from patrole_tempest_plugin import rbac_exceptions from patrole_tempest_plugin import rbac_utils from patrole_tempest_plugin.tests.unit import base from patrole_tempest_plugin.tests.unit import fixtures as patrole_fixtures class RBACUtilsMixinTest(base.TestCase): def setUp(self): super(RBACUtilsMixinTest, self).setUp() self.rbac_utils_fixture = self.useFixture( patrole_fixtures.RbacUtilsMixinFixture()) self.test_obj = self.rbac_utils_fixture.test_obj def test_init_roles_with_missing_admin_role(self): self.rbac_utils_fixture.set_roles('member') error_re = (".*Following roles were not found: admin. Available " "roles: member.") self.assertRaisesRegex(rbac_exceptions.RbacResourceSetupFailed, error_re, self.test_obj._init_roles) def test_init_roles_with_missing_rbac_role(self): self.rbac_utils_fixture.set_roles('admin') error_re = (".*Following roles were not found: member. Available " "roles: admin.") self.assertRaisesRegex(rbac_exceptions.RbacResourceSetupFailed, error_re, self.test_obj._init_roles) def test_override_role_to_admin_role_at_creating(self): rbac_utils_fixture = self.useFixture( patrole_fixtures.RbacUtilsMixinFixture(do_reset_mocks=False)) test_obj = rbac_utils_fixture.test_obj roles_client = rbac_utils_fixture.admin_roles_client mock_time = rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_called_once_with( rbac_utils_fixture.PROJECT_ID, rbac_utils_fixture.USER_ID, 'admin_id') test_obj.get_auth_providers()[0].clear_auth.assert_called_once_with() test_obj.get_auth_providers()[0].set_auth.assert_called_once_with() mock_time.sleep.assert_called_once_with(1) def test_override_role_to_admin_role(self): self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_called_once_with( self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'admin_id') self.test_obj.get_auth_providers()[0].clear_auth\ .assert_called_once_with() self.test_obj.get_auth_providers()[0].set_auth\ .assert_called_once_with() mock_time.sleep.assert_called_once_with(1) def test_override_role_to_admin_role_avoids_role_switch(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'admin') self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_not_called() mock_time.sleep.assert_not_called() def test_override_role_to_member_role(self): self.test_obj._override_role(True) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_has_calls([ mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'member_id') ]) self.test_obj.get_auth_providers()[0].clear_auth.assert_has_calls( [mock.call()]) self.test_obj.get_auth_providers()[0].set_auth.assert_has_calls( [mock.call()]) mock_time.sleep.assert_has_calls([mock.call(1)]) def test_override_role_to_member_role_avoids_role_switch(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'member') self.test_obj._override_role(True) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time self.assertEqual(0, roles_client.create_user_role_on_project.call_count) self.assertEqual(0, mock_time.sleep.call_count) def test_override_role_to_member_role_then_admin_role(self): self.test_obj._override_role(True) self.test_obj._override_role(False) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_has_calls([ mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'member_id'), mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'admin_id') ]) self.test_obj.get_auth_providers()[0].clear_auth.assert_has_calls( [mock.call()] * 2) self.test_obj.get_auth_providers()[0].set_auth.assert_has_calls( [mock.call()] * 2) mock_time.sleep.assert_has_calls([mock.call(1)] * 2) def test_clear_user_roles(self): # NOTE(felipemonteiro): Set the user's roles on the project to # include 'random' to coerce a role switch, or else it will be # skipped. self.rbac_utils_fixture.set_roles(['admin', 'member'], ['member', 'random']) self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client roles_client.list_user_roles_on_project.assert_called_once_with( self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID) roles_client.delete_role_from_user_on_project.\ assert_has_calls([ mock.call(mock.sentinel.project_id, mock.sentinel.user_id, 'member_id'), mock.call(mock.sentinel.project_id, mock.sentinel.user_id, 'random_id')]) def test_override_role_context_manager_simulate_pass(self): """Validate that expected override_role calls are made when switching to admin role for success path. """ mock_override_role = self.patchobject(self.test_obj, '_override_role') with self.test_obj.override_role(): # Validate `override_role` public method called private method # `_override_role` with True. mock_override_role.assert_called_once_with(True) mock_override_role.reset_mock() # Validate that `override_role` switched back to admin role after # contextmanager. mock_override_role.assert_called_once_with(False) def test_override_role_context_manager_simulate_fail(self): """Validate that expected override_role calls are made when switching to admin role for failure path (i.e. when test raises exception). """ mock_override_role = self.patchobject(self.test_obj, '_override_role') def _do_test(): with self.test_obj.override_role(): # Validate `override_role` public method called private method # `_override_role` with True. mock_override_role.assert_called_once_with(True) mock_override_role.reset_mock() # Raise exc to verify role switch works for negative case. raise lib_exc.Forbidden() # Validate that role is switched back to admin, despite test failure. with testtools.ExpectedException(lib_exc.Forbidden): _do_test() mock_override_role.assert_called_once_with(False) def test_override_role_and_validate_list(self): m_override_role = self.patchobject(self.test_obj, 'override_role') with (self.test_obj.override_role_and_validate_list( admin_resource_id='foo')) as ctx: self.assertIsInstance(ctx, rbac_utils._ValidateListContext) m_validate = self.patchobject(ctx, '_validate') m_override_role.assert_called_once_with() m_validate.assert_called_once() def test_prepare_role_inferences_mapping(self): self.test_obj.admin_roles_client.list_all_role_inference_rules.\ return_value = { "role_inferences": [ { "implies": [{"id": "reader_id", "name": "reader"}], "prior_role": {"id": "member_id", "name": "member"} }, { "implies": [{"id": "member_id", "name": "member"}], "prior_role": {"id": "admin_id", "name": "admin"} } ] } expected_role_inferences_mapping = { "member_id": {"reader_id"}, "admin_id": {"member_id", "reader_id"} } actual_role_inferences_mapping = self.test_obj.\ _prepare_role_inferences_mapping() self.assertEqual(expected_role_inferences_mapping, actual_role_inferences_mapping) def test_get_all_needed_roles(self): self.test_obj.__class__._role_inferences_mapping = { "member_id": {"reader_id"}, "admin_id": {"member_id", "reader_id"} } self.test_obj.__class__._role_map = { "admin_id": "admin", "admin": "admin_id", "member_id": "member", "member": "member_id", "reader_id": "reader", "reader": "reader_id" } for roles, expected_roles in ( (['admin'], ['admin', 'member', 'reader']), (['member'], ['member', 'reader']), (['reader'], ['reader']), (['custom_role'], ['custom_role']), (['custom_role', 'member'], ['custom_role', 'member', 'reader']), (['admin', 'member'], ['admin', 'member', 'reader']), ): expected_roles = sorted(expected_roles) actual_roles = sorted(self.test_obj.get_all_needed_roles(roles)) self.assertEqual(expected_roles, actual_roles) def test_restore_roles(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'member') roles_client = self.rbac_utils_fixture.admin_roles_client # Explicitly call setup_clients() to make sure cls._orig_roles is set # properly. Explicitly call resource_cleanup to invoke restore_roles(). self.test_obj.setup_clients() self.test_obj.resource_cleanup() # list_user_roles_on_project is called twice in setup_clients(), # restore_roles() is called twice during resource cleanup. self.assertEqual(4, roles_client.list_user_roles_on_project.call_count) self.assertEqual(['member_id'], self.test_obj._orig_roles) class ValidateListContextTest(base.TestCase): @staticmethod def _get_context(admin_resources=None, admin_resource_id=None): return rbac_utils._ValidateListContext( admin_resources=admin_resources, admin_resource_id=admin_resource_id) def test_incorrect_usage(self): # admin_resources and admin_resource_is are not assigned self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context) # both admin_resources and admin_resource_is are assigned self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context, admin_resources='foo', admin_resource_id='bar') # empty list assigned to admin_resources self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context, admin_resources=[]) # ctx.resources is not assigned ctx = self._get_context(admin_resources='foo') self.assertRaises(rbac_exceptions.RbacValidateListException, ctx._validate) def test_validate_len_negative(self): ctx = self._get_context(admin_resources=[1, 2, 3, 4]) self.assertEqual(ctx._validate_len, ctx._validate_func) self.assertEqual(4, ctx._admin_len) self.assertFalse(hasattr(ctx, '_admin_resource_id')) # the number of resources is less than admin resources ctx.resources = [1, 2, 3] self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate_len) # the resources is empty ctx.resources = [] self.assertRaises(rbac_exceptions.RbacEmptyResponseBody, ctx._validate_len) def test_validate_len(self): ctx = self._get_context(admin_resources=[1, 2, 3, 4]) # the number of resources and admin resources are same ctx.resources = [1, 2, 3, 4] self.assertIsNone(ctx._validate_len()) def test_validate_resource_negative(self): ctx = self._get_context(admin_resource_id=1) self.assertEqual(ctx._validate_resource, ctx._validate_func) self.assertEqual(1, ctx._admin_resource_id) self.assertFalse(hasattr(ctx, '_admin_len')) # there is no admin resource in the resources ctx.resources = [{'id': 2}, {'id': 3}] self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate_resource) def test_validate_resource(self): ctx = self._get_context(admin_resource_id=1) # there is admin resource in the resources ctx.resources = [{'id': 1}, {'id': 2}] self.assertIsNone(ctx._validate_resource()) def test_validate(self): ctx = self._get_context(admin_resources='foo') ctx.resources = 'bar' with mock.patch.object(ctx, '_validate_func', autospec=False) as m_validate_func: m_validate_func.side_effect = ( rbac_exceptions.RbacPartialResponseBody, None ) self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate) m_validate_func.assert_called_once() m_validate_func.reset_mock() ctx._validate() m_validate_func.assert_called_once()
43.048851
79
0.653227
import testtools from unittest import mock from tempest.lib import exceptions as lib_exc from patrole_tempest_plugin import rbac_exceptions from patrole_tempest_plugin import rbac_utils from patrole_tempest_plugin.tests.unit import base from patrole_tempest_plugin.tests.unit import fixtures as patrole_fixtures class RBACUtilsMixinTest(base.TestCase): def setUp(self): super(RBACUtilsMixinTest, self).setUp() self.rbac_utils_fixture = self.useFixture( patrole_fixtures.RbacUtilsMixinFixture()) self.test_obj = self.rbac_utils_fixture.test_obj def test_init_roles_with_missing_admin_role(self): self.rbac_utils_fixture.set_roles('member') error_re = (".*Following roles were not found: admin. Available " "roles: member.") self.assertRaisesRegex(rbac_exceptions.RbacResourceSetupFailed, error_re, self.test_obj._init_roles) def test_init_roles_with_missing_rbac_role(self): self.rbac_utils_fixture.set_roles('admin') error_re = (".*Following roles were not found: member. Available " "roles: admin.") self.assertRaisesRegex(rbac_exceptions.RbacResourceSetupFailed, error_re, self.test_obj._init_roles) def test_override_role_to_admin_role_at_creating(self): rbac_utils_fixture = self.useFixture( patrole_fixtures.RbacUtilsMixinFixture(do_reset_mocks=False)) test_obj = rbac_utils_fixture.test_obj roles_client = rbac_utils_fixture.admin_roles_client mock_time = rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_called_once_with( rbac_utils_fixture.PROJECT_ID, rbac_utils_fixture.USER_ID, 'admin_id') test_obj.get_auth_providers()[0].clear_auth.assert_called_once_with() test_obj.get_auth_providers()[0].set_auth.assert_called_once_with() mock_time.sleep.assert_called_once_with(1) def test_override_role_to_admin_role(self): self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_called_once_with( self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'admin_id') self.test_obj.get_auth_providers()[0].clear_auth\ .assert_called_once_with() self.test_obj.get_auth_providers()[0].set_auth\ .assert_called_once_with() mock_time.sleep.assert_called_once_with(1) def test_override_role_to_admin_role_avoids_role_switch(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'admin') self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_not_called() mock_time.sleep.assert_not_called() def test_override_role_to_member_role(self): self.test_obj._override_role(True) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_has_calls([ mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'member_id') ]) self.test_obj.get_auth_providers()[0].clear_auth.assert_has_calls( [mock.call()]) self.test_obj.get_auth_providers()[0].set_auth.assert_has_calls( [mock.call()]) mock_time.sleep.assert_has_calls([mock.call(1)]) def test_override_role_to_member_role_avoids_role_switch(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'member') self.test_obj._override_role(True) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time self.assertEqual(0, roles_client.create_user_role_on_project.call_count) self.assertEqual(0, mock_time.sleep.call_count) def test_override_role_to_member_role_then_admin_role(self): self.test_obj._override_role(True) self.test_obj._override_role(False) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_has_calls([ mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'member_id'), mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'admin_id') ]) self.test_obj.get_auth_providers()[0].clear_auth.assert_has_calls( [mock.call()] * 2) self.test_obj.get_auth_providers()[0].set_auth.assert_has_calls( [mock.call()] * 2) mock_time.sleep.assert_has_calls([mock.call(1)] * 2) def test_clear_user_roles(self): # include 'random' to coerce a role switch, or else it will be # skipped. self.rbac_utils_fixture.set_roles(['admin', 'member'], ['member', 'random']) self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client roles_client.list_user_roles_on_project.assert_called_once_with( self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID) roles_client.delete_role_from_user_on_project.\ assert_has_calls([ mock.call(mock.sentinel.project_id, mock.sentinel.user_id, 'member_id'), mock.call(mock.sentinel.project_id, mock.sentinel.user_id, 'random_id')]) def test_override_role_context_manager_simulate_pass(self): mock_override_role = self.patchobject(self.test_obj, '_override_role') with self.test_obj.override_role(): # Validate `override_role` public method called private method # `_override_role` with True. mock_override_role.assert_called_once_with(True) mock_override_role.reset_mock() # Validate that `override_role` switched back to admin role after # contextmanager. mock_override_role.assert_called_once_with(False) def test_override_role_context_manager_simulate_fail(self): mock_override_role = self.patchobject(self.test_obj, '_override_role') def _do_test(): with self.test_obj.override_role(): # Validate `override_role` public method called private method # `_override_role` with True. mock_override_role.assert_called_once_with(True) mock_override_role.reset_mock() # Raise exc to verify role switch works for negative case. raise lib_exc.Forbidden() # Validate that role is switched back to admin, despite test failure. with testtools.ExpectedException(lib_exc.Forbidden): _do_test() mock_override_role.assert_called_once_with(False) def test_override_role_and_validate_list(self): m_override_role = self.patchobject(self.test_obj, 'override_role') with (self.test_obj.override_role_and_validate_list( admin_resource_id='foo')) as ctx: self.assertIsInstance(ctx, rbac_utils._ValidateListContext) m_validate = self.patchobject(ctx, '_validate') m_override_role.assert_called_once_with() m_validate.assert_called_once() def test_prepare_role_inferences_mapping(self): self.test_obj.admin_roles_client.list_all_role_inference_rules.\ return_value = { "role_inferences": [ { "implies": [{"id": "reader_id", "name": "reader"}], "prior_role": {"id": "member_id", "name": "member"} }, { "implies": [{"id": "member_id", "name": "member"}], "prior_role": {"id": "admin_id", "name": "admin"} } ] } expected_role_inferences_mapping = { "member_id": {"reader_id"}, "admin_id": {"member_id", "reader_id"} } actual_role_inferences_mapping = self.test_obj.\ _prepare_role_inferences_mapping() self.assertEqual(expected_role_inferences_mapping, actual_role_inferences_mapping) def test_get_all_needed_roles(self): self.test_obj.__class__._role_inferences_mapping = { "member_id": {"reader_id"}, "admin_id": {"member_id", "reader_id"} } self.test_obj.__class__._role_map = { "admin_id": "admin", "admin": "admin_id", "member_id": "member", "member": "member_id", "reader_id": "reader", "reader": "reader_id" } for roles, expected_roles in ( (['admin'], ['admin', 'member', 'reader']), (['member'], ['member', 'reader']), (['reader'], ['reader']), (['custom_role'], ['custom_role']), (['custom_role', 'member'], ['custom_role', 'member', 'reader']), (['admin', 'member'], ['admin', 'member', 'reader']), ): expected_roles = sorted(expected_roles) actual_roles = sorted(self.test_obj.get_all_needed_roles(roles)) self.assertEqual(expected_roles, actual_roles) def test_restore_roles(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'member') roles_client = self.rbac_utils_fixture.admin_roles_client # Explicitly call setup_clients() to make sure cls._orig_roles is set # properly. Explicitly call resource_cleanup to invoke restore_roles(). self.test_obj.setup_clients() self.test_obj.resource_cleanup() # list_user_roles_on_project is called twice in setup_clients(), # restore_roles() is called twice during resource cleanup. self.assertEqual(4, roles_client.list_user_roles_on_project.call_count) self.assertEqual(['member_id'], self.test_obj._orig_roles) class ValidateListContextTest(base.TestCase): @staticmethod def _get_context(admin_resources=None, admin_resource_id=None): return rbac_utils._ValidateListContext( admin_resources=admin_resources, admin_resource_id=admin_resource_id) def test_incorrect_usage(self): # admin_resources and admin_resource_is are not assigned self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context) # both admin_resources and admin_resource_is are assigned self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context, admin_resources='foo', admin_resource_id='bar') # empty list assigned to admin_resources self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context, admin_resources=[]) # ctx.resources is not assigned ctx = self._get_context(admin_resources='foo') self.assertRaises(rbac_exceptions.RbacValidateListException, ctx._validate) def test_validate_len_negative(self): ctx = self._get_context(admin_resources=[1, 2, 3, 4]) self.assertEqual(ctx._validate_len, ctx._validate_func) self.assertEqual(4, ctx._admin_len) self.assertFalse(hasattr(ctx, '_admin_resource_id')) # the number of resources is less than admin resources ctx.resources = [1, 2, 3] self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate_len) # the resources is empty ctx.resources = [] self.assertRaises(rbac_exceptions.RbacEmptyResponseBody, ctx._validate_len) def test_validate_len(self): ctx = self._get_context(admin_resources=[1, 2, 3, 4]) # the number of resources and admin resources are same ctx.resources = [1, 2, 3, 4] self.assertIsNone(ctx._validate_len()) def test_validate_resource_negative(self): ctx = self._get_context(admin_resource_id=1) self.assertEqual(ctx._validate_resource, ctx._validate_func) self.assertEqual(1, ctx._admin_resource_id) self.assertFalse(hasattr(ctx, '_admin_len')) # there is no admin resource in the resources ctx.resources = [{'id': 2}, {'id': 3}] self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate_resource) def test_validate_resource(self): ctx = self._get_context(admin_resource_id=1) # there is admin resource in the resources ctx.resources = [{'id': 1}, {'id': 2}] self.assertIsNone(ctx._validate_resource()) def test_validate(self): ctx = self._get_context(admin_resources='foo') ctx.resources = 'bar' with mock.patch.object(ctx, '_validate_func', autospec=False) as m_validate_func: m_validate_func.side_effect = ( rbac_exceptions.RbacPartialResponseBody, None ) self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate) m_validate_func.assert_called_once() m_validate_func.reset_mock() ctx._validate() m_validate_func.assert_called_once()
true
true
f72a4f6721d4ff9bda92ac47662c4d9dcaa83260
2,333
py
Python
var/spack/repos/builtin/packages/r-gsodr/package.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2,360
2017-11-06T08:47:01.000Z
2022-03-31T14:45:33.000Z
var/spack/repos/builtin/packages/r-gsodr/package.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
13,838
2017-11-04T07:49:45.000Z
2022-03-31T23:38:39.000Z
var/spack/repos/builtin/packages/r-gsodr/package.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1,793
2017-11-04T07:45:50.000Z
2022-03-30T14:31:53.000Z
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RGsodr(RPackage): """A Global Surface Summary of the Day (GSOD) Weather Data Client for R Provides automated downloading, parsing, cleaning, unit conversion and formatting of Global Surface Summary of the Day ('GSOD') weather data from the from the USA National Centers for Environmental Information ('NCEI'). Units are converted from from United States Customary System ('USCS') units to International System of Units ('SI'). Stations may be individually checked for number of missing days defined by the user, where stations with too many missing observations are omitted. Only stations with valid reported latitude and longitude values are permitted in the final data. Additional useful elements, saturation vapour pressure ('es'), actual vapour pressure ('ea') and relative humidity ('RH') are calculated from the original data using the improved August-Roche-Magnus approximation (Alduchov & Eskridge 1996) and included in the final data set. The resulting metadata include station identification information, country, state, latitude, longitude, elevation, weather observations and associated flags. For information on the 'GSOD' data from 'NCEI', please see the 'GSOD' 'readme.txt' file available from, <https://www1.ncdc.noaa.gov/pub/data/gsod/readme.txt>.""" homepage = "https://docs.ropensci.org/GSODR/" url = "https://cloud.r-project.org/src/contrib/GSODR_2.1.1.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/GSODR" version('2.1.2', sha256='4fc1d084b6c21055d8cc17a6a6dc412261aa0d4ef4079bcd73b580a8c16bf74e') version('2.1.1', sha256='dba732e5bd1e367b9d710e6b8924f0c02fa4546202f049124dba02bc2e3329f5') depends_on('r@3.5.0:', type=('build', 'run')) depends_on('r-countrycode', type=('build', 'run')) depends_on('r-curl', type=('build', 'run')) depends_on('r-data-table@1.11.6:', type=('build', 'run')) depends_on('r-future-apply', type=('build', 'run')) depends_on('r-httr', type=('build', 'run')) depends_on('r-r-utils', type=('build', 'run'))
53.022727
95
0.724389
from spack import * class RGsodr(RPackage): homepage = "https://docs.ropensci.org/GSODR/" url = "https://cloud.r-project.org/src/contrib/GSODR_2.1.1.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/GSODR" version('2.1.2', sha256='4fc1d084b6c21055d8cc17a6a6dc412261aa0d4ef4079bcd73b580a8c16bf74e') version('2.1.1', sha256='dba732e5bd1e367b9d710e6b8924f0c02fa4546202f049124dba02bc2e3329f5') depends_on('r@3.5.0:', type=('build', 'run')) depends_on('r-countrycode', type=('build', 'run')) depends_on('r-curl', type=('build', 'run')) depends_on('r-data-table@1.11.6:', type=('build', 'run')) depends_on('r-future-apply', type=('build', 'run')) depends_on('r-httr', type=('build', 'run')) depends_on('r-r-utils', type=('build', 'run'))
true
true
f72a4ff9057e2766c21056edb0d6c1eeff32ab49
2,712
py
Python
ros/src/waypoint_loader/waypoint_loader.py
ahmedmbakr/CarND-Capstone
3585df9781f2f9e128b7498ef033029485d31567
[ "MIT" ]
null
null
null
ros/src/waypoint_loader/waypoint_loader.py
ahmedmbakr/CarND-Capstone
3585df9781f2f9e128b7498ef033029485d31567
[ "MIT" ]
null
null
null
ros/src/waypoint_loader/waypoint_loader.py
ahmedmbakr/CarND-Capstone
3585df9781f2f9e128b7498ef033029485d31567
[ "MIT" ]
null
null
null
#!/usr/bin/env python import os import csv import math from geometry_msgs.msg import Quaternion from styx_msgs.msg import Lane, Waypoint import tf import rospy CSV_HEADER = ['x', 'y', 'z', 'yaw'] MAX_DECEL = 1.0 class WaypointLoader(object): def __init__(self): rospy.init_node('waypoint_loader', log_level=rospy.DEBUG) self.pub = rospy.Publisher('/base_waypoints', Lane, queue_size=1, latch=True) top_speed_limit_kmh = 15 # It is equal to 10 MPH rospy.set_param('~velocity', top_speed_limit_kmh) self.velocity = self.kmph2mps(rospy.get_param('~velocity')) self.new_waypoint_loader(rospy.get_param('~path')) rospy.spin() def new_waypoint_loader(self, path): if os.path.isfile(path): waypoints = self.load_waypoints(path) self.publish(waypoints) rospy.loginfo('Waypoint Loded') else: rospy.logerr('%s is not a file', path) def quaternion_from_yaw(self, yaw): return tf.transformations.quaternion_from_euler(0., 0., yaw) def kmph2mps(self, velocity_kmph): return (velocity_kmph * 1000.) / (60. * 60.) def load_waypoints(self, fname): waypoints = [] with open(fname) as wfile: reader = csv.DictReader(wfile, CSV_HEADER) for wp in reader: p = Waypoint() p.pose.pose.position.x = float(wp['x']) p.pose.pose.position.y = float(wp['y']) p.pose.pose.position.z = float(wp['z']) q = self.quaternion_from_yaw(float(wp['yaw'])) p.pose.pose.orientation = Quaternion(*q) p.twist.twist.linear.x = float(self.velocity) waypoints.append(p) return self.decelerate(waypoints) def distance(self, p1, p2): x, y, z = p1.x - p2.x, p1.y - p2.y, p1.z - p2.z return math.sqrt(x*x + y*y + z*z) def decelerate(self, waypoints): last = waypoints[-1] last.twist.twist.linear.x = 0. for wp in waypoints[:-1][::-1]: dist = self.distance(wp.pose.pose.position, last.pose.pose.position) vel = math.sqrt(2 * MAX_DECEL * dist) if vel < 1.: vel = 0. wp.twist.twist.linear.x = min(vel, wp.twist.twist.linear.x) return waypoints def publish(self, waypoints): lane = Lane() lane.header.frame_id = '/world' lane.header.stamp = rospy.Time(0) lane.waypoints = waypoints self.pub.publish(lane) if __name__ == '__main__': try: WaypointLoader() except rospy.ROSInterruptException: rospy.logerr('Could not start waypoint node.')
30.133333
85
0.593658
import os import csv import math from geometry_msgs.msg import Quaternion from styx_msgs.msg import Lane, Waypoint import tf import rospy CSV_HEADER = ['x', 'y', 'z', 'yaw'] MAX_DECEL = 1.0 class WaypointLoader(object): def __init__(self): rospy.init_node('waypoint_loader', log_level=rospy.DEBUG) self.pub = rospy.Publisher('/base_waypoints', Lane, queue_size=1, latch=True) top_speed_limit_kmh = 15 rospy.set_param('~velocity', top_speed_limit_kmh) self.velocity = self.kmph2mps(rospy.get_param('~velocity')) self.new_waypoint_loader(rospy.get_param('~path')) rospy.spin() def new_waypoint_loader(self, path): if os.path.isfile(path): waypoints = self.load_waypoints(path) self.publish(waypoints) rospy.loginfo('Waypoint Loded') else: rospy.logerr('%s is not a file', path) def quaternion_from_yaw(self, yaw): return tf.transformations.quaternion_from_euler(0., 0., yaw) def kmph2mps(self, velocity_kmph): return (velocity_kmph * 1000.) / (60. * 60.) def load_waypoints(self, fname): waypoints = [] with open(fname) as wfile: reader = csv.DictReader(wfile, CSV_HEADER) for wp in reader: p = Waypoint() p.pose.pose.position.x = float(wp['x']) p.pose.pose.position.y = float(wp['y']) p.pose.pose.position.z = float(wp['z']) q = self.quaternion_from_yaw(float(wp['yaw'])) p.pose.pose.orientation = Quaternion(*q) p.twist.twist.linear.x = float(self.velocity) waypoints.append(p) return self.decelerate(waypoints) def distance(self, p1, p2): x, y, z = p1.x - p2.x, p1.y - p2.y, p1.z - p2.z return math.sqrt(x*x + y*y + z*z) def decelerate(self, waypoints): last = waypoints[-1] last.twist.twist.linear.x = 0. for wp in waypoints[:-1][::-1]: dist = self.distance(wp.pose.pose.position, last.pose.pose.position) vel = math.sqrt(2 * MAX_DECEL * dist) if vel < 1.: vel = 0. wp.twist.twist.linear.x = min(vel, wp.twist.twist.linear.x) return waypoints def publish(self, waypoints): lane = Lane() lane.header.frame_id = '/world' lane.header.stamp = rospy.Time(0) lane.waypoints = waypoints self.pub.publish(lane) if __name__ == '__main__': try: WaypointLoader() except rospy.ROSInterruptException: rospy.logerr('Could not start waypoint node.')
false
true
f72a513bd3e1dece646a2c8acb68bd929fbe4e41
225
py
Python
myapp/caculate_FFalgorithm_for_path.py
hebinjie33/HMMLB
db26a149fd3e8e96a570cfe32e9bc42a002409cc
[ "Apache-2.0" ]
null
null
null
myapp/caculate_FFalgorithm_for_path.py
hebinjie33/HMMLB
db26a149fd3e8e96a570cfe32e9bc42a002409cc
[ "Apache-2.0" ]
null
null
null
myapp/caculate_FFalgorithm_for_path.py
hebinjie33/HMMLB
db26a149fd3e8e96a570cfe32e9bc42a002409cc
[ "Apache-2.0" ]
1
2019-12-16T21:46:46.000Z
2019-12-16T21:46:46.000Z
class FFalgorithm: def __init__(self): def caculate_bandwidth(S7_PORT2,S5_PORT1,S1_PORT2,S9_PORT4,S11_PORT3,S5_PORT2,S2_PORT4,S7_PORT1,S6_PORT1,S3_PORT1,S10_PORT3,S6_PORT2,S4_PORT2): ''' link1's bandwidth '''
22.5
144
0.768889
class FFalgorithm: def __init__(self): def caculate_bandwidth(S7_PORT2,S5_PORT1,S1_PORT2,S9_PORT4,S11_PORT3,S5_PORT2,S2_PORT4,S7_PORT1,S6_PORT1,S3_PORT1,S10_PORT3,S6_PORT2,S4_PORT2): ''' link1's bandwidth '''
false
true
f72a51b526015df516689e7669b54b9e20831540
639
py
Python
tests/clims/api/serializers/models/test_work_batch.py
withrocks/commonlims
d8a925c917aa26e8205fefb3966a9f49f8f2e2f8
[ "BSD-3-Clause" ]
null
null
null
tests/clims/api/serializers/models/test_work_batch.py
withrocks/commonlims
d8a925c917aa26e8205fefb3966a9f49f8f2e2f8
[ "BSD-3-Clause" ]
null
null
null
tests/clims/api/serializers/models/test_work_batch.py
withrocks/commonlims
d8a925c917aa26e8205fefb3966a9f49f8f2e2f8
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import from sentry.testutils import TestCase from clims.api.serializers.models.workbatch import WorkBatchSerializer from clims.models.work_batch import WorkBatch class WorkBatchSerializerTest(TestCase): def test_can_serialize_task(self): model = WorkBatch(id=1, name="Test1", organization_id=1, handler="somehandler") result = WorkBatchSerializer(model).data assert result.get('handler') == 'somehandler' assert result.get('id') == 1 assert result.get('name') == 'Test1' assert result.get('organization') == 1 assert result.get('status') == 0
35.5
87
0.713615
from __future__ import absolute_import from sentry.testutils import TestCase from clims.api.serializers.models.workbatch import WorkBatchSerializer from clims.models.work_batch import WorkBatch class WorkBatchSerializerTest(TestCase): def test_can_serialize_task(self): model = WorkBatch(id=1, name="Test1", organization_id=1, handler="somehandler") result = WorkBatchSerializer(model).data assert result.get('handler') == 'somehandler' assert result.get('id') == 1 assert result.get('name') == 'Test1' assert result.get('organization') == 1 assert result.get('status') == 0
true
true
f72a51ff116cdacd733759b6eb96d4b97659306d
609
py
Python
djasana/migrations/0008_auto_20180906_1407.py
zaptim/django-asana
ab6d7166f28945292d5632ef766fc13cc2ea4cf3
[ "MIT" ]
null
null
null
djasana/migrations/0008_auto_20180906_1407.py
zaptim/django-asana
ab6d7166f28945292d5632ef766fc13cc2ea4cf3
[ "MIT" ]
null
null
null
djasana/migrations/0008_auto_20180906_1407.py
zaptim/django-asana
ab6d7166f28945292d5632ef766fc13cc2ea4cf3
[ "MIT" ]
null
null
null
# Generated by Django 2.1 on 2018-09-06 14:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djasana', '0007_auto_20180819_1518'), ] operations = [ migrations.AlterField( model_name='customfield', name='description', field=models.CharField(blank=True, max_length=2048, null=True), ), migrations.AlterField( model_name='customfield', name='enum_options', field=models.CharField(blank=True, max_length=2048, null=True), ), ]
24.36
75
0.602627
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djasana', '0007_auto_20180819_1518'), ] operations = [ migrations.AlterField( model_name='customfield', name='description', field=models.CharField(blank=True, max_length=2048, null=True), ), migrations.AlterField( model_name='customfield', name='enum_options', field=models.CharField(blank=True, max_length=2048, null=True), ), ]
true
true
f72a5265e0f02fda5da08d5bce4bd2145df5c0eb
582
py
Python
examples/2021_12_31/py_files/plotters/Paraview/timeAverage.py
jagarciap/SCSI
0972548adf17a27b78ef2865a837bf20aadca3e9
[ "MIT" ]
null
null
null
examples/2021_12_31/py_files/plotters/Paraview/timeAverage.py
jagarciap/SCSI
0972548adf17a27b78ef2865a837bf20aadca3e9
[ "MIT" ]
null
null
null
examples/2021_12_31/py_files/plotters/Paraview/timeAverage.py
jagarciap/SCSI
0972548adf17a27b78ef2865a837bf20aadca3e9
[ "MIT" ]
1
2022-01-18T10:24:39.000Z
2022-01-18T10:24:39.000Z
from paraview.simple import * firststep = 50 #names = ['0_ts*', '0-0_ts*', '0-0-0_ts*'] names = ['0_ts*', '0-0_ts*'] for name in names: acs = FindSource(name) SetActiveSource(acs) laststep = int(acs.TimestepValues[-1]) extractTimeSteps = ExtractTimeSteps(Input=acs) extractTimeSteps.TimeStepIndices = [i for i in range(firststep, laststep+1)] temporalStatistics = TemporalStatistics(Input=extractTimeSteps) renderView1 = GetActiveViewOrCreate('RenderView') temporalStatisticsDisplay = Show(temporalStatistics, renderView1) renderView1.Update()
34.235294
80
0.725086
from paraview.simple import * firststep = 50 names = ['0_ts*', '0-0_ts*'] for name in names: acs = FindSource(name) SetActiveSource(acs) laststep = int(acs.TimestepValues[-1]) extractTimeSteps = ExtractTimeSteps(Input=acs) extractTimeSteps.TimeStepIndices = [i for i in range(firststep, laststep+1)] temporalStatistics = TemporalStatistics(Input=extractTimeSteps) renderView1 = GetActiveViewOrCreate('RenderView') temporalStatisticsDisplay = Show(temporalStatistics, renderView1) renderView1.Update()
true
true
f72a52a097ae8acfd4297be79489feb161d30056
6,350
py
Python
tools/cFS-GroundSystem/GroundSystem.py
ammarrm/cFS_MSTAR
f7d59eec4a445bb8572d01a580c043ec7a33df44
[ "Apache-2.0" ]
null
null
null
tools/cFS-GroundSystem/GroundSystem.py
ammarrm/cFS_MSTAR
f7d59eec4a445bb8572d01a580c043ec7a33df44
[ "Apache-2.0" ]
null
null
null
tools/cFS-GroundSystem/GroundSystem.py
ammarrm/cFS_MSTAR
f7d59eec4a445bb8572d01a580c043ec7a33df44
[ "Apache-2.0" ]
1
2021-04-23T04:26:08.000Z
2021-04-23T04:26:08.000Z
# # GSC-18128-1, "Core Flight Executive Version 6.7" # # Copyright (c) 2006-2019 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # 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. # # cFS Ground System Version 2.0.0 # #!/usr/bin/env python3 # import shlex import subprocess import sys from pathlib import Path from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox from RoutingService import RoutingService from Ui_MainWindow import Ui_MainWindow from _version import __version__ as _version from _version import _version_string __version__ = _version ROOTDIR = Path(sys.argv[0]).resolve().parent # # CFS Ground System: Setup and manage the main window # class GroundSystem(QMainWindow, Ui_MainWindow): HDR_VER_1_OFFSET = 0 HDR_VER_2_OFFSET = 4 # # Init the class # def __init__(self): super().__init__() self.setupUi(self) self.RoutingService = None self.alert = QMessageBox() self.pushButtonStartTlm.clicked.connect(self.startTlmSystem) self.pushButtonStartCmd.clicked.connect(self.startCmdSystem) self.cbTlmHeaderVer.currentIndexChanged.connect(self.setTlmOffset) self.cbCmdHeaderVer.currentIndexChanged.connect(self.setCmdOffsets) for sb in (self.sbTlmOffset, self.sbCmdOffsetPri, self.sbCmdOffsetSec): sb.valueChanged.connect(self.saveOffsets) # Init lists self.ipAddressesList = ['All'] self.spacecraftNames = ['All'] def closeEvent(self, evnt): if self.RoutingService: self.RoutingService.stop() print("Stopped routing service") super().closeEvent(evnt) # Read the selected spacecraft from combo box on GUI def getSelectedSpacecraftAddress(self): return self.comboBoxIpAddresses.currentText().strip() # Returns the name of the selected spacecraft def getSelectedSpacecraftName(self): return self.spacecraftNames[self.ipAddressesList.index( self.getSelectedSpacecraftAddress())].strip() # # Display popup with error # def DisplayErrorMessage(self, message): print(message) self.alert.setText(message) self.alert.setIcon(QMessageBox.Warning) self.alert.exec_() # Start the telemetry system for the selected spacecraft def startTlmSystem(self): # Setup the subscription (to let the telemetry # system know the messages it will be receiving) subscription = '--sub=GroundSystem' selectedSpacecraft = self.getSelectedSpacecraftName() if selectedSpacecraft != 'All': subscription += f'.{selectedSpacecraft}.TelemetryPackets' # Open Telemetry System system_call = f'python3 {ROOTDIR}/Subsystems/tlmGUI/TelemetrySystem.py {subscription}' args = shlex.split(system_call) subprocess.Popen(args) # Start command system @staticmethod def startCmdSystem(): subprocess.Popen( ['python3', f'{ROOTDIR}/Subsystems/cmdGui/CommandSystem.py']) # Start FDL-FUL gui system def startFDLSystem(self): selectedSpacecraft = self.getSelectedSpacecraftName() if selectedSpacecraft == 'All': self.DisplayErrorMessage( 'Cannot open FDL manager.\nNo spacecraft selected.') else: subscription = f'--sub=GroundSystem.{selectedSpacecraft}' subprocess.Popen([ 'python3', f'{ROOTDIR}/Subsystems/fdlGui/FdlSystem.py', subscription ]) def setTlmOffset(self): selectedVer = self.cbTlmHeaderVer.currentText().strip() if selectedVer == "Custom": self.sbTlmOffset.setEnabled(True) else: self.sbTlmOffset.setEnabled(False) if selectedVer == "1": self.sbTlmOffset.setValue(self.HDR_VER_1_OFFSET) elif selectedVer == "2": self.sbTlmOffset.setValue(self.HDR_VER_2_OFFSET) def setCmdOffsets(self): selectedVer = self.cbCmdHeaderVer.currentText().strip() if selectedVer == "Custom": self.sbCmdOffsetPri.setEnabled(True) self.sbCmdOffsetSec.setEnabled(True) else: self.sbCmdOffsetPri.setEnabled(False) self.sbCmdOffsetSec.setEnabled(False) if selectedVer == "1": self.sbCmdOffsetPri.setValue(self.HDR_VER_1_OFFSET) elif selectedVer == "2": self.sbCmdOffsetPri.setValue(self.HDR_VER_2_OFFSET) self.sbCmdOffsetSec.setValue(self.HDR_VER_1_OFFSET) def saveOffsets(self): offsets = bytes((self.sbTlmOffset.value(), self.sbCmdOffsetPri.value(), self.sbCmdOffsetSec.value())) with open("/tmp/OffsetData", "wb") as f: f.write(offsets) # Update the combo box list in gui def updateIpList(self, ip, name): self.ipAddressesList.append(ip) self.spacecraftNames.append(name) self.comboBoxIpAddresses.addItem(ip) # Start the routing service (see RoutingService.py) def initRoutingService(self): self.RoutingService = RoutingService() self.RoutingService.signalUpdateIpList.connect(self.updateIpList) self.RoutingService.start() # # Main # if __name__ == "__main__": # Report Version Number upon startup print(_version_string) # Init app app = QApplication(sys.argv) # Init main window MainWindow = GroundSystem() # Show and put window on front MainWindow.show() MainWindow.raise_() # Start the Routing Service MainWindow.initRoutingService() MainWindow.saveOffsets() # Execute the app sys.exit(app.exec_())
32.397959
94
0.671811
import shlex import subprocess import sys from pathlib import Path from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox from RoutingService import RoutingService from Ui_MainWindow import Ui_MainWindow from _version import __version__ as _version from _version import _version_string __version__ = _version ROOTDIR = Path(sys.argv[0]).resolve().parent class GroundSystem(QMainWindow, Ui_MainWindow): HDR_VER_1_OFFSET = 0 HDR_VER_2_OFFSET = 4 def __init__(self): super().__init__() self.setupUi(self) self.RoutingService = None self.alert = QMessageBox() self.pushButtonStartTlm.clicked.connect(self.startTlmSystem) self.pushButtonStartCmd.clicked.connect(self.startCmdSystem) self.cbTlmHeaderVer.currentIndexChanged.connect(self.setTlmOffset) self.cbCmdHeaderVer.currentIndexChanged.connect(self.setCmdOffsets) for sb in (self.sbTlmOffset, self.sbCmdOffsetPri, self.sbCmdOffsetSec): sb.valueChanged.connect(self.saveOffsets) self.ipAddressesList = ['All'] self.spacecraftNames = ['All'] def closeEvent(self, evnt): if self.RoutingService: self.RoutingService.stop() print("Stopped routing service") super().closeEvent(evnt) def getSelectedSpacecraftAddress(self): return self.comboBoxIpAddresses.currentText().strip() def getSelectedSpacecraftName(self): return self.spacecraftNames[self.ipAddressesList.index( self.getSelectedSpacecraftAddress())].strip() def DisplayErrorMessage(self, message): print(message) self.alert.setText(message) self.alert.setIcon(QMessageBox.Warning) self.alert.exec_() def startTlmSystem(self): subscription = '--sub=GroundSystem' selectedSpacecraft = self.getSelectedSpacecraftName() if selectedSpacecraft != 'All': subscription += f'.{selectedSpacecraft}.TelemetryPackets' system_call = f'python3 {ROOTDIR}/Subsystems/tlmGUI/TelemetrySystem.py {subscription}' args = shlex.split(system_call) subprocess.Popen(args) @staticmethod def startCmdSystem(): subprocess.Popen( ['python3', f'{ROOTDIR}/Subsystems/cmdGui/CommandSystem.py']) def startFDLSystem(self): selectedSpacecraft = self.getSelectedSpacecraftName() if selectedSpacecraft == 'All': self.DisplayErrorMessage( 'Cannot open FDL manager.\nNo spacecraft selected.') else: subscription = f'--sub=GroundSystem.{selectedSpacecraft}' subprocess.Popen([ 'python3', f'{ROOTDIR}/Subsystems/fdlGui/FdlSystem.py', subscription ]) def setTlmOffset(self): selectedVer = self.cbTlmHeaderVer.currentText().strip() if selectedVer == "Custom": self.sbTlmOffset.setEnabled(True) else: self.sbTlmOffset.setEnabled(False) if selectedVer == "1": self.sbTlmOffset.setValue(self.HDR_VER_1_OFFSET) elif selectedVer == "2": self.sbTlmOffset.setValue(self.HDR_VER_2_OFFSET) def setCmdOffsets(self): selectedVer = self.cbCmdHeaderVer.currentText().strip() if selectedVer == "Custom": self.sbCmdOffsetPri.setEnabled(True) self.sbCmdOffsetSec.setEnabled(True) else: self.sbCmdOffsetPri.setEnabled(False) self.sbCmdOffsetSec.setEnabled(False) if selectedVer == "1": self.sbCmdOffsetPri.setValue(self.HDR_VER_1_OFFSET) elif selectedVer == "2": self.sbCmdOffsetPri.setValue(self.HDR_VER_2_OFFSET) self.sbCmdOffsetSec.setValue(self.HDR_VER_1_OFFSET) def saveOffsets(self): offsets = bytes((self.sbTlmOffset.value(), self.sbCmdOffsetPri.value(), self.sbCmdOffsetSec.value())) with open("/tmp/OffsetData", "wb") as f: f.write(offsets) def updateIpList(self, ip, name): self.ipAddressesList.append(ip) self.spacecraftNames.append(name) self.comboBoxIpAddresses.addItem(ip) def initRoutingService(self): self.RoutingService = RoutingService() self.RoutingService.signalUpdateIpList.connect(self.updateIpList) self.RoutingService.start() if __name__ == "__main__": print(_version_string) app = QApplication(sys.argv) MainWindow = GroundSystem() MainWindow.show() MainWindow.raise_() MainWindow.initRoutingService() MainWindow.saveOffsets() sys.exit(app.exec_())
true
true
f72a530516b9a3b382487caa11390d79ac8dedb8
1,185
py
Python
pyprof/alembic/versions/2021_03_12_15_41_50.py
kooichirooooo/pyprof
a2cce7ef335d02b0566a169b46f3cf976e7d9662
[ "MIT" ]
null
null
null
pyprof/alembic/versions/2021_03_12_15_41_50.py
kooichirooooo/pyprof
a2cce7ef335d02b0566a169b46f3cf976e7d9662
[ "MIT" ]
null
null
null
pyprof/alembic/versions/2021_03_12_15_41_50.py
kooichirooooo/pyprof
a2cce7ef335d02b0566a169b46f3cf976e7d9662
[ "MIT" ]
null
null
null
"""create frame and block table Revision ID: 1fc165a90d68 Revises: Create Date: 2021-03-12 15:41:50.150507 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "1fc165a90d68" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "frames", sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), sa.Column("name", sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "blocks", sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), sa.Column("frame_id", sa.Integer(), nullable=True), sa.Column("name", sa.String(length=32), nullable=True), sa.ForeignKeyConstraint( ["frame_id"], ["frames.id"], ), sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("blocks") op.drop_table("frames") # ### end Alembic commands ###
26.333333
74
0.625316
import sqlalchemy as sa from alembic import op revision = "1fc165a90d68" down_revision = None branch_labels = None depends_on = None def upgrade(): sa.PrimaryKeyConstraint("id"), ) op.create_table( "blocks", sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), sa.Column("frame_id", sa.Integer(), nullable=True), sa.Column("name", sa.String(length=32), nullable=True), sa.ForeignKeyConstraint( ["frame_id"], ["frames.id"], ), sa.PrimaryKeyConstraint("id"), )
true
true
f72a5319acea927f969baaeedae8a60444d73815
168
py
Python
ftruck/urls.py
sunlightlabs/foodtrucks
f6531a3e47c3d5975d5230e946e636d082dbc24a
[ "BSD-3-Clause" ]
null
null
null
ftruck/urls.py
sunlightlabs/foodtrucks
f6531a3e47c3d5975d5230e946e636d082dbc24a
[ "BSD-3-Clause" ]
null
null
null
ftruck/urls.py
sunlightlabs/foodtrucks
f6531a3e47c3d5975d5230e946e636d082dbc24a
[ "BSD-3-Clause" ]
null
null
null
from django.conf.urls.defaults import * urlpatterns = patterns('ftruck.views', url(r'^$', 'mainmap', name='map'), url(r'^tweets/$', 'tweets', name='tweets') )
24
46
0.630952
from django.conf.urls.defaults import * urlpatterns = patterns('ftruck.views', url(r'^$', 'mainmap', name='map'), url(r'^tweets/$', 'tweets', name='tweets') )
true
true
f72a5350a454b362d7b0b72c74c7c361977c73b5
2,289
py
Python
data/cirq_new/cirq_program/startCirq_noisy553.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/cirq_new/cirq_program/startCirq_noisy553.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/cirq_new/cirq_program/startCirq_noisy553.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=19 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=7 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.H.on(input_qubit[0])) # number=14 c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=15 c.append(cirq.H.on(input_qubit[0])) # number=16 c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=12 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=13 c.append(cirq.X.on(input_qubit[1])) # number=17 c.append(cirq.X.on(input_qubit[1])) # number=18 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2820 circuit = circuit.with_noise(cirq.depolarize(p=0.01)) simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq_noisy553.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
33.173913
77
0.68851
import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np def make_circuit(n: int, input_qubit): c = cirq.Circuit() c.append(cirq.H.on(input_qubit[0])) c.append(cirq.H.on(input_qubit[1])) c.append(cirq.H.on(input_qubit[1])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.X.on(input_qubit[1])) c.append(cirq.X.on(input_qubit[1])) c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2820 circuit = circuit.with_noise(cirq.depolarize(p=0.01)) simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq_noisy553.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
true
true
f72a536ed7d7645ecead0368a4011e2dfa79644e
20
py
Python
ckan/lib/navl/__init__.py
florianm/ckan
1cfd98d591ac70b4eb81048bcd227b6c1354b1bf
[ "Apache-2.0" ]
12
2015-08-28T16:59:07.000Z
2020-03-08T01:39:30.000Z
ckan/lib/navl/__init__.py
florianm/ckan
1cfd98d591ac70b4eb81048bcd227b6c1354b1bf
[ "Apache-2.0" ]
13
2019-05-02T21:01:28.000Z
2020-10-20T23:34:48.000Z
ckan/lib/navl/__init__.py
florianm/ckan
1cfd98d591ac70b4eb81048bcd227b6c1354b1bf
[ "Apache-2.0" ]
10
2015-05-08T04:33:20.000Z
2020-03-03T15:17:58.000Z
__license__ = 'MIT'
10
19
0.7
__license__ = 'MIT'
true
true
f72a5415b9a53ec576425cc8bb6d98e89c6da886
700
py
Python
pytreex/block/util/setglobal.py
ufal/pytreex
9633c1420e6b4adecd73baaf761d26fa49708a61
[ "Apache-2.0" ]
11
2015-06-24T08:41:44.000Z
2021-09-02T21:12:10.000Z
pytreex/block/util/setglobal.py
ufal/pytreex
9633c1420e6b4adecd73baaf761d26fa49708a61
[ "Apache-2.0" ]
4
2016-01-12T19:21:22.000Z
2019-05-10T14:46:44.000Z
pytreex/block/util/setglobal.py
ufal/pytreex
9633c1420e6b4adecd73baaf761d26fa49708a61
[ "Apache-2.0" ]
3
2016-01-22T11:54:11.000Z
2019-04-30T17:09:55.000Z
#!/usr/bin/env python # coding=utf-8 # # Block for making tree copies # from __future__ import unicode_literals from pytreex.core.block import Block __author__ = "Ondřej Dušek" __date__ = "2012" class SetGlobal(Block): def __init__(self, scenario, args): """\ Constructor, sets the arguments given to this block as global. """ Block.__init__(self, scenario, args) for arg, value in args.items(): scenario.global_args[arg] = value def process_bundle(self, doc): """\ This block does nothing with the documents, its only work is setting the global arguments in the initialization phase. """ pass
23.333333
70
0.642857
from __future__ import unicode_literals from pytreex.core.block import Block __author__ = "Ondřej Dušek" __date__ = "2012" class SetGlobal(Block): def __init__(self, scenario, args): Block.__init__(self, scenario, args) for arg, value in args.items(): scenario.global_args[arg] = value def process_bundle(self, doc): pass
true
true
f72a54c5a6aefc1b68cf97340534140cea211c6d
39,428
py
Python
modin/pandas/test/utils.py
itsliya/modin
d4ce5390816ae7eb8717bf271e1feabd3d5fabee
[ "ECL-2.0", "Apache-2.0" ]
1
2021-05-19T04:01:17.000Z
2021-05-19T04:01:17.000Z
modin/pandas/test/utils.py
itsliya/modin
d4ce5390816ae7eb8717bf271e1feabd3d5fabee
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
modin/pandas/test/utils.py
itsliya/modin
d4ce5390816ae7eb8717bf271e1feabd3d5fabee
[ "ECL-2.0", "Apache-2.0" ]
1
2022-01-29T12:12:42.000Z
2022-01-29T12:12:42.000Z
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team 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. import pytest import numpy as np import math import pandas from pandas.testing import ( assert_series_equal, assert_frame_equal, assert_index_equal, assert_extension_array_equal, ) import modin.pandas as pd from modin.utils import to_pandas from modin.config import TestDatasetSize, TrackFileLeaks from io import BytesIO import os from string import ascii_letters import csv import psutil import functools random_state = np.random.RandomState(seed=42) DATASET_SIZE_DICT = { "Small": (2 ** 2, 2 ** 3), "Normal": (2 ** 6, 2 ** 8), "Big": (2 ** 7, 2 ** 12), } # Size of test dataframes NCOLS, NROWS = DATASET_SIZE_DICT.get(TestDatasetSize.get(), DATASET_SIZE_DICT["Normal"]) # Range for values for test data RAND_LOW = 0 RAND_HIGH = 100 # Directory for storing I/O operations test data IO_OPS_DATA_DIR = os.path.join(os.path.dirname(__file__), "io_tests_data") # Input data and functions for the tests # The test data that we will test our code against test_data = { # "empty_data": {}, # "columns_only": {"col1": [], "col2": [], "col3": [], "col4": [], "col5": []}, "int_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.randint( RAND_LOW, RAND_HIGH, size=(NROWS) ) for i in range(NCOLS) }, "float_nan_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ x if (j % 4 == 0 and i > NCOLS // 2) or (j != i and i <= NCOLS // 2) else np.NaN for j, x in enumerate( random_state.uniform(RAND_LOW, RAND_HIGH, size=(NROWS)) ) ] for i in range(NCOLS) }, # "int_float_object_data": { # "col3": [1, 2, 3, 4], # "col4": [4, 5, 6, 7], # "col1": [8.0, 9.4, 10.1, 11.3], # "col2": ["a", "b", "c", "d"], # }, # "datetime_timedelta_data": { # "col3": [ # np.datetime64("2010"), # np.datetime64("2011"), # np.datetime64("2011-06-15T00:00"), # np.datetime64("2009-01-01"), # ], # "col4": [ # np.datetime64("2010"), # np.datetime64("2011"), # np.datetime64("2011-06-15T00:00"), # np.datetime64("2009-01-01"), # ], # "col1": [ # np.timedelta64(1, "M"), # np.timedelta64(2, "D"), # np.timedelta64(3, "Y"), # np.timedelta64(20, "D"), # ], # "col2": [ # np.timedelta64(1, "M"), # np.timedelta64(2, "D"), # np.timedelta64(3, "Y"), # np.timedelta64(20, "D"), # ], # }, # "all_data": { # "col3": 1.0, # "col4": np.datetime64("2011-06-15T00:00"), # "col5": np.array([3] * 4, dtype="int32"), # "col1": "foo", # "col2": True, # }, } # See details in #1403 test_data["int_data"]["index"] = test_data["int_data"].pop( "col{}".format(int(NCOLS / 2)) ) for col in test_data["float_nan_data"]: for row in range(NROWS // 2): if row % 16 == 0: test_data["float_nan_data"][col][row] = np.NaN test_data_values = list(test_data.values()) test_data_keys = list(test_data.keys()) test_bool_data = { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.choice( [True, False], size=(NROWS) ) for i in range(NCOLS) } test_data_resample = { "data": {"A": range(12), "B": range(12)}, "index": pandas.date_range("31/12/2000", periods=12, freq="H"), } test_data_with_duplicates = { "no_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): range(NROWS) for i in range(NCOLS) }, "all_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ float(i) for _ in range(NROWS) ] for i in range(NCOLS) }, "some_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ i if j % 7 == 0 else x for j, x in enumerate(range(NROWS)) ] for i in range(NCOLS) }, "has_name_column": { "name": ["one", "two", "two", "three"], "col1": [1, 2, 2, 3], "col3": [10, 20, 20, 3], "col7": [100, 201, 200, 300], }, "str_columns": { "col_str{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ "s" + str(x % 5) for x in range(NROWS) ] for i in range(NCOLS) }, } test_data_with_duplicates["float_nan"] = test_data["float_nan_data"] test_data_small = { "small": { "col0": [1, 2, 3, 4], "col1": [8.0, 9.4, 10.1, 11.3], "col2": [4, 5, 6, 7], } } test_data_diff_dtype = { "int_col": [-5, 2, 7, 16], "float_col": [np.NaN, -9.4, 10.1, np.NaN], "str_col": ["a", np.NaN, "c", "d"], "bool_col": [False, True, True, False], } test_data_small_values = list(test_data_small.values()) test_data_small_keys = list(test_data_small.keys()) test_data_with_duplicates_values = list(test_data_with_duplicates.values()) test_data_with_duplicates_keys = list(test_data_with_duplicates.keys()) test_data_categorical = { "ordered": pandas.Categorical(list("testdata"), ordered=True), "unordered": pandas.Categorical(list("testdata"), ordered=False), } test_data_categorical_values = list(test_data_categorical.values()) test_data_categorical_keys = list(test_data_categorical.keys()) numeric_dfs = [ "empty_data", "columns_only", "int_data", "float_nan_data", "with_index_column", ] no_numeric_dfs = ["datetime_timedelta_data"] # String test data test_string_data = { "separator data": [ "abC|DeF,Hik", "234,3245.67", "gSaf,qWer|Gre", "asd3,4sad|", np.NaN, ] } test_string_data_values = list(test_string_data.values()) test_string_data_keys = list(test_string_data.keys()) # List of strings test data test_string_list_data = {"simple string": [["a"], ["CdE"], ["jDf"], ["werB"]]} test_string_list_data_values = list(test_string_list_data.values()) test_string_list_data_keys = list(test_string_list_data.keys()) string_seperators = {"empty sep": "", "comma sep": ",", "None sep": None} string_sep_values = list(string_seperators.values()) string_sep_keys = list(string_seperators.keys()) string_na_rep = {"None na_rep": None, "- na_rep": "-", "nan na_rep": np.NaN} string_na_rep_values = list(string_na_rep.values()) string_na_rep_keys = list(string_na_rep.keys()) join_type = {"left": "left", "right": "right", "inner": "inner", "outer": "outer"} join_type_keys = list(join_type.keys()) join_type_values = list(join_type.values()) # Test functions for applymap test_func = { "plus one": lambda x: x + 1, "convert to string": lambda x: str(x), "square": lambda x: x * x, "identity": lambda x: x, "return false": lambda x: False, } test_func_keys = list(test_func.keys()) test_func_values = list(test_func.values()) numeric_test_funcs = ["plus one", "square"] # Test functions for query query_func = { "col1 < col2": "col1 < col2", "col3 > col4": "col3 > col4", "col1 == col2": "col1 == col2", "(col2 > col1) and (col1 < col3)": "(col2 > col1) and (col1 < col3)", } query_func_keys = list(query_func.keys()) query_func_values = list(query_func.values()) # Test agg functions for apply, agg, and aggregate agg_func = { "sum": "sum", "df sum": lambda df: df.sum(), "str": str, "sum mean": ["sum", "mean"], "sum df sum": ["sum", lambda df: df.sum()], "should raise TypeError": 1, } agg_func_keys = list(agg_func.keys()) agg_func_values = list(agg_func.values()) # For this sort of parameters pandas throws an exception. # See details in pandas issue 36036. agg_func_except = { "sum sum": ["sum", "sum"], } agg_func_except_keys = list(agg_func_except.keys()) agg_func_except_values = list(agg_func_except.values()) numeric_agg_funcs = ["sum mean", "sum sum", "sum df sum"] udf_func = { "return self": lambda df: lambda x, *args, **kwargs: type(x)(x.values), "change index": lambda df: lambda x, *args, **kwargs: pandas.Series( x.values, index=np.arange(-1, len(x.index) - 1) ), "return none": lambda df: lambda x, *args, **kwargs: None, "return empty": lambda df: lambda x, *args, **kwargs: pandas.Series(), "access self": lambda df: lambda x, other, *args, **kwargs: pandas.Series( x.values, index=other.index ), } udf_func_keys = list(udf_func.keys()) udf_func_values = list(udf_func.values()) # Test q values for quantiles quantiles = { "0.25": 0.25, "0.5": 0.5, "0.75": 0.75, "0.66": 0.66, "0.01": 0.01, "list": [0.25, 0.5, 0.75, 0.66, 0.01], } quantiles_keys = list(quantiles.keys()) quantiles_values = list(quantiles.values()) # Test indices for get, set_index, __contains__, insert indices = { "col1": "col1", "col2": "col2", "A": "A", "B": "B", "does not exist": "does not exist", } indices_keys = list(indices.keys()) indices_values = list(indices.values()) # Test functions for groupby apply groupby_apply_func = {"sum": lambda df: df.sum(), "negate": lambda df: -df} groupby_apply_func_keys = list(groupby_apply_func.keys()) groupby_apply_func_values = list(groupby_apply_func.values()) # Test functions for groupby agg groupby_agg_func = {"min": "min", "max": "max"} groupby_agg_func_keys = list(groupby_agg_func.keys()) groupby_agg_func_values = list(groupby_agg_func.values()) # Test functions for groupby transform groupby_transform_func = { "add 4": lambda df: df + 4, "negatie and minus 10": lambda df: -df - 10, } groupby_transform_func_keys = list(groupby_transform_func.keys()) groupby_transform_func_values = list(groupby_transform_func.values()) # Test functions for groupby pipe groupby_pipe_func = {"sum": lambda df: df.sum()} groupby_pipe_func_keys = list(groupby_pipe_func.keys()) groupby_pipe_func_values = list(groupby_pipe_func.values()) # END Test input data and functions # Parametrizations of common kwargs axis = { "over_rows_int": 0, "over_rows_str": "rows", "over_columns_int": 1, "over_columns_str": "columns", } axis_keys = list(axis.keys()) axis_values = list(axis.values()) bool_arg = {"True": True, "False": False, "None": None} bool_arg_keys = list(bool_arg.keys()) bool_arg_values = list(bool_arg.values()) int_arg = {"-5": -5, "-1": -1, "0": 0, "1": 1, "5": 5} int_arg_keys = list(int_arg.keys()) int_arg_values = list(int_arg.values()) # END parametrizations of common kwargs json_short_string = """[{"project": "modin"}]""" json_long_string = """{ "quiz": { "sport": { "q1": { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" } }, "maths": { "q1": { "question": "5 + 7 = ?", "options": [ "10", "11", "12", "13" ], "answer": "12" }, "q2": { "question": "12 - 8 = ?", "options": [ "1", "2", "3", "4" ], "answer": "4" } } } }""" json_long_bytes = BytesIO(json_long_string.encode(encoding="UTF-8")) json_short_bytes = BytesIO(json_short_string.encode(encoding="UTF-8")) # Text encoding types encoding_types = [ "ascii", "utf_32", "utf_32_be", "utf_32_le", "utf_16", "utf_16_be", "utf_16_le", "utf_7", "utf_8", "utf_8_sig", ] # raising of this exceptions can be caused by unexpected behavior # of I/O operation test, but can passed by eval_io function since # the type of this exceptions are the same io_ops_bad_exc = [TypeError, FileNotFoundError] # Files compression to extension mapping COMP_TO_EXT = {"gzip": "gz", "bz2": "bz2", "xz": "xz", "zip": "zip"} def categories_equals(left, right): assert (left.ordered and right.ordered) or (not left.ordered and not right.ordered) assert_extension_array_equal(left, right) def df_categories_equals(df1, df2): if not hasattr(df1, "select_dtypes"): if isinstance(df1, pandas.CategoricalDtype): return categories_equals(df1, df2) elif isinstance(getattr(df1, "dtype"), pandas.CategoricalDtype) and isinstance( getattr(df1, "dtype"), pandas.CategoricalDtype ): return categories_equals(df1.dtype, df2.dtype) else: return True categories_columns = df1.select_dtypes(include="category").columns for column in categories_columns: assert_extension_array_equal( df1[column].values, df2[column].values, check_dtype=False, ) def df_equals(df1, df2): """Tests if df1 and df2 are equal. Args: df1: (pandas or modin DataFrame or series) dataframe to test if equal. df2: (pandas or modin DataFrame or series) dataframe to test if equal. Returns: True if df1 is equal to df2. """ # Gets AttributError if modin's groupby object is not import like this from modin.pandas.groupby import DataFrameGroupBy groupby_types = (pandas.core.groupby.DataFrameGroupBy, DataFrameGroupBy) # The typing behavior of how pandas treats its index is not consistent when the # length of the DataFrame or Series is 0, so we just verify that the contents are # the same. if ( hasattr(df1, "index") and hasattr(df2, "index") and len(df1) == 0 and len(df2) == 0 ): if type(df1).__name__ == type(df2).__name__: if hasattr(df1, "name") and hasattr(df2, "name") and df1.name == df2.name: return if ( hasattr(df1, "columns") and hasattr(df2, "columns") and df1.columns.equals(df2.columns) ): return assert False if isinstance(df1, (list, tuple)) and all( isinstance(d, (pd.DataFrame, pd.Series, pandas.DataFrame, pandas.Series)) for d in df1 ): assert isinstance(df2, type(df1)), "Different type of collection" assert len(df1) == len(df2), "Different length result" return (df_equals(d1, d2) for d1, d2 in zip(df1, df2)) # Convert to pandas if isinstance(df1, (pd.DataFrame, pd.Series)): df1 = to_pandas(df1) if isinstance(df2, (pd.DataFrame, pd.Series)): df2 = to_pandas(df2) if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): if (df1.empty and not df2.empty) or (df2.empty and not df1.empty): assert False, "One of the passed frames is empty, when other isn't" elif df1.empty and df2.empty and type(df1) != type(df2): assert ( False ), f"Empty frames have different types: {type(df1)} != {type(df2)}" if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): assert_frame_equal( df1, df2, check_dtype=False, check_datetimelike_compat=True, check_index_type=False, check_column_type=False, check_categorical=False, ) df_categories_equals(df1, df2) elif isinstance(df1, pandas.Index) and isinstance(df2, pandas.Index): assert_index_equal(df1, df2) elif isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series): assert_series_equal(df1, df2, check_dtype=False, check_series_type=False) elif isinstance(df1, groupby_types) and isinstance(df2, groupby_types): for g1, g2 in zip(df1, df2): assert g1[0] == g2[0] df_equals(g1[1], g2[1]) elif ( isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series) and df1.empty and df2.empty ): assert all(df1.index == df2.index) assert df1.dtypes == df2.dtypes elif isinstance(df1, pandas.core.arrays.numpy_.PandasArray): assert isinstance(df2, pandas.core.arrays.numpy_.PandasArray) assert df1 == df2 elif isinstance(df1, np.recarray) and isinstance(df2, np.recarray): np.testing.assert_array_equal(df1, df2) else: if df1 != df2: np.testing.assert_almost_equal(df1, df2) def modin_df_almost_equals_pandas(modin_df, pandas_df): df_categories_equals(modin_df._to_pandas(), pandas_df) modin_df = to_pandas(modin_df) if hasattr(modin_df, "select_dtypes"): modin_df = modin_df.select_dtypes(exclude=["category"]) if hasattr(pandas_df, "select_dtypes"): pandas_df = pandas_df.select_dtypes(exclude=["category"]) difference = modin_df - pandas_df diff_max = difference.max() if isinstance(diff_max, pandas.Series): diff_max = diff_max.max() assert ( modin_df.equals(pandas_df) or diff_max < 0.0001 or (all(modin_df.isna().all()) and all(pandas_df.isna().all())) ) def df_is_empty(df): """Tests if df is empty. Args: df: (pandas or modin DataFrame) dataframe to test if empty. Returns: True if df is empty. """ assert df.size == 0 and df.empty assert df.shape[0] == 0 or df.shape[1] == 0 def arg_keys(arg_name, keys): """Appends arg_name to the front of all values in keys. Args: arg_name: (string) String containing argument name. keys: (list of strings) Possible inputs of argument. Returns: List of strings with arg_name append to front of keys. """ return ["{0}_{1}".format(arg_name, key) for key in keys] def name_contains(test_name, vals): """Determines if any string in vals is a substring of test_name. Args: test_name: (string) String to determine if contains substrings. vals: (list of strings) List of substrings to test for. Returns: True if a substring in vals is in test_name, else False. """ return any(val in test_name for val in vals) def check_df_columns_have_nans(df, cols): """Checks if there are NaN values in specified columns of a dataframe. :param df: Dataframe to check. :param cols: One column name or list of column names. :return: True if specified columns of dataframe contains NaNs. """ return ( pandas.api.types.is_list_like(cols) and ( any(isinstance(x, str) and x in df.columns and df[x].hasnans for x in cols) or any( isinstance(x, pd.Series) and x._parent is df and x.hasnans for x in cols ) ) ) or ( not pandas.api.types.is_list_like(cols) and cols in df.columns and df[cols].hasnans ) def eval_general( modin_df, pandas_df, operation, comparator=df_equals, __inplace__=False, check_exception_type=True, raising_exceptions=None, check_kwargs_callable=True, md_extra_kwargs=None, **kwargs, ): if raising_exceptions: assert ( check_exception_type ), "if raising_exceptions is not None or False, check_exception_type should be True" md_kwargs, pd_kwargs = {}, {} def execute_callable(fn, inplace=False, md_kwargs={}, pd_kwargs={}): try: pd_result = fn(pandas_df, **pd_kwargs) except Exception as pd_e: if check_exception_type is None: return None with pytest.raises(Exception) as md_e: # repr to force materialization repr(fn(modin_df, **md_kwargs)) if check_exception_type: assert isinstance(md_e.value, type(pd_e)) if raising_exceptions: assert not isinstance( md_e.value, tuple(raising_exceptions) ), f"not acceptable exception type: {md_e.value}" else: md_result = fn(modin_df, **md_kwargs) return (md_result, pd_result) if not __inplace__ else (modin_df, pandas_df) for key, value in kwargs.items(): if check_kwargs_callable and callable(value): values = execute_callable(value) # that means, that callable raised an exception if values is None: return else: md_value, pd_value = values else: md_value, pd_value = value, value md_kwargs[key] = md_value pd_kwargs[key] = pd_value if md_extra_kwargs: assert isinstance(md_extra_kwargs, dict) md_kwargs.update(md_extra_kwargs) values = execute_callable( operation, md_kwargs=md_kwargs, pd_kwargs=pd_kwargs, inplace=__inplace__ ) if values is not None: comparator(*values) def eval_io( fn_name, comparator=df_equals, cast_to_str=False, check_exception_type=True, raising_exceptions=io_ops_bad_exc, check_kwargs_callable=True, modin_warning=None, md_extra_kwargs=None, *args, **kwargs, ): """Evaluate I/O operation outputs equality check. Parameters ---------- fn_name: str I/O operation name ("read_csv" for example). comparator: obj Function to perform comparison. cast_to_str: bool There could be some missmatches in dtypes, so we're casting the whole frame to `str` before comparison. See issue #1931 for details. check_exception_type: bool Check or not exception types in the case of operation fail (compare exceptions types raised by Pandas and Modin). raising_exceptions: Exception or list of Exceptions Exceptions that should be raised even if they are raised both by Pandas and Modin (check evaluated only if `check_exception_type` passed as `True`). modin_warning: obj Warning that should be raised by Modin. md_extra_kwargs: dict Modin operation specific kwargs. """ def applyier(module, *args, **kwargs): result = getattr(module, fn_name)(*args, **kwargs) if cast_to_str: result = result.astype(str) return result def call_eval_general(): eval_general( pd, pandas, applyier, check_exception_type=check_exception_type, raising_exceptions=raising_exceptions, check_kwargs_callable=check_kwargs_callable, md_extra_kwargs=md_extra_kwargs, *args, **kwargs, ) if modin_warning: with pytest.warns(modin_warning): call_eval_general() else: call_eval_general() def eval_io_from_str(csv_str: str, unique_filename: str, **kwargs): """Evaluate I/O operation outputs equality check by using `csv_str` data passed as python str (csv test file will be created from `csv_str`). Parameters ---------- csv_str: str Test data for storing to csv file. unique_filename: str csv file name. """ try: with open(unique_filename, "w") as f: f.write(csv_str) eval_io( filepath_or_buffer=unique_filename, fn_name="read_csv", **kwargs, ) finally: if os.path.exists(unique_filename): try: os.remove(unique_filename) except PermissionError: pass def create_test_dfs(*args, **kwargs): post_fn = kwargs.pop("post_fn", lambda df: df) return map( post_fn, [pd.DataFrame(*args, **kwargs), pandas.DataFrame(*args, **kwargs)] ) def generate_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [0, 0, 0, 0], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def generate_multiindex_dfs(axis=1): def generate_multiindex(index): return pandas.MultiIndex.from_tuples( [("a", x) for x in index.values], names=["name1", "name2"] ) df1, df2 = generate_dfs() df1.axes[axis], df2.axes[axis] = map( generate_multiindex, [df1.axes[axis], df2.axes[axis]] ) return df1, df2 def generate_multiindex(elements_number, nlevels=2, is_tree_like=False): def generate_level(length, nlevel): src = ["bar", "baz", "foo", "qux"] return [src[i % len(src)] + f"-{nlevel}-{i}" for i in range(length)] if is_tree_like: for penalty_level in [0, 1]: lvl_len_f, lvl_len_d = math.modf( round(elements_number ** (1 / (nlevels - penalty_level)), 12) ) if lvl_len_d >= 2 and lvl_len_f == 0: break if lvl_len_d < 2 or lvl_len_f != 0: raise RuntimeError( f"Can't generate Tree-like MultiIndex with lenght: {elements_number} and number of levels: {nlevels}" ) lvl_len = int(lvl_len_d) result = pd.MultiIndex.from_product( [generate_level(lvl_len, i) for i in range(nlevels - penalty_level)], names=[f"level-{i}" for i in range(nlevels - penalty_level)], ) if penalty_level: result = pd.MultiIndex.from_tuples( [("base_level", *ml_tuple) for ml_tuple in result], names=[f"level-{i}" for i in range(nlevels)], ) return result.sort_values() else: base_level = ["first"] * (elements_number // 2 + elements_number % 2) + [ "second" ] * (elements_number // 2) primary_levels = [generate_level(elements_number, i) for i in range(1, nlevels)] arrays = [base_level] + primary_levels return pd.MultiIndex.from_tuples( list(zip(*arrays)), names=[f"level-{i}" for i in range(nlevels)] ).sort_values() def generate_none_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, None, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [None, None, None, None], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def get_unique_filename( test_name: str = "test", kwargs: dict = {}, extension: str = "csv", data_dir: str = IO_OPS_DATA_DIR, suffix: str = "", debug_mode=False, ): """Returns unique file name with specified parameters. Parameters ---------- test_name: str name of the test for which the unique file name is needed. kwargs: list of ints Unique combiantion of test parameters for creation of unique name. extension: str Extension of unique file. data_dir: str Data directory where test files will be created. suffix: str String to append to the resulted name. debug_mode: bool Get unique filename containing kwargs values. Otherwise kwargs values will be replaced with hash equivalent. Returns ------- Unique file name. """ suffix_part = f"_{suffix}" if suffix else "" extension_part = f".{extension}" if extension else "" if debug_mode: # shortcut if kwargs parameter are not provided if len(kwargs) == 0 and extension == "csv" and suffix == "": return os.path.join(data_dir, (test_name + suffix_part + f".{extension}")) assert "." not in extension, "please provide pure extension name without '.'" prohibited_chars = ['"', "\n"] non_prohibited_char = "np_char" char_counter = 0 kwargs_name = dict(kwargs) for key, value in kwargs_name.items(): for char in prohibited_chars: if isinstance(value, str) and char in value or callable(value): kwargs_name[key] = non_prohibited_char + str(char_counter) char_counter += 1 parameters_values = "_".join( [ str(value) if not isinstance(value, (list, tuple)) else "_".join([str(x) for x in value]) for value in kwargs_name.values() ] ) return os.path.join( data_dir, test_name + parameters_values + suffix_part + extension_part ) else: import uuid return os.path.join(data_dir, uuid.uuid1().hex + suffix_part + extension_part) def get_random_string(): random_string = "".join( random_state.choice([x for x in ascii_letters], size=10).tolist() ) return random_string def insert_lines_to_csv( csv_name: str, lines_positions: list, lines_type: str = "blank", encoding: str = None, **csv_reader_writer_params, ): """Insert lines to ".csv" file. Parameters ---------- csv_name: str ".csv" file that should be modified. lines_positions: list of ints Lines postions that sghould be modified (serial number of line - begins from 0, ends in <rows_number> - 1). lines_type: str Lines types that should be inserted to ".csv" file. Possible types: "blank" - empty line without any delimiters/separators, "bad" - lines with len(lines_data) > cols_number encoding: str Encoding type that should be used during file reading and writing. """ cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) if lines_type == "blank": lines_data = [] elif lines_type == "bad": cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) lines_data = [x for x in range(cols_number + 1)] else: raise ValueError( f"acceptable values for parameter are ['blank', 'bad'], actually passed {lines_type}" ) lines = [] dialect = "excel" with open(csv_name, "r", encoding=encoding, newline="") as read_file: try: dialect = csv.Sniffer().sniff(read_file.read()) read_file.seek(0) except Exception: dialect = None reader = csv.reader( read_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) counter = 0 for row in reader: if counter in lines_positions: lines.append(lines_data) else: lines.append(row) counter += 1 with open(csv_name, "w", encoding=encoding, newline="") as write_file: writer = csv.writer( write_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) writer.writerows(lines) def _get_open_files(): """ psutil open_files() can return a lot of extra information that we can allow to be different, like file position; for simplicity we care about path and fd only. """ return sorted((info.path, info.fd) for info in psutil.Process().open_files()) def check_file_leaks(func): """ A decorator that ensures that no *newly* opened file handles are left after decorated function is finished. """ if not TrackFileLeaks.get(): return func @functools.wraps(func) def check(*a, **kw): fstart = _get_open_files() try: return func(*a, **kw) finally: leaks = [] for item in _get_open_files(): try: fstart.remove(item) except ValueError: # ignore files in /proc/, as they have nothing to do with # modin reading any data (and this is what we care about) if not item[0].startswith("/proc/"): leaks.append(item) assert ( not leaks ), f"Unexpected open handles left for: {', '.join(item[0] for item in leaks)}" return check def dummy_decorator(): """A problematic decorator that does not use `functools.wraps`. This introduces unwanted local variables for inspect.currentframe. This decorator is used in test_io to test `read_csv` and `read_table` """ def wrapper(method): def wrapped_function(self, *args, **kwargs): result = method(self, *args, **kwargs) return result return wrapped_function return wrapper def generate_dataframe(row_size=NROWS, additional_col_values=None): dates = pandas.date_range("2000", freq="h", periods=row_size) data = { "col1": np.arange(row_size) * 10, "col2": [str(x.date()) for x in dates], "col3": np.arange(row_size) * 10, "col4": [str(x.time()) for x in dates], "col5": [get_random_string() for _ in range(row_size)], "col6": random_state.uniform(low=0.0, high=10000.0, size=row_size), } if additional_col_values is not None: assert isinstance(additional_col_values, (list, tuple)) data.update( { "col7": random_state.choice(additional_col_values, size=row_size), } ) return pandas.DataFrame(data) def _make_csv_file(filenames): def _csv_file_maker( filename, row_size=NROWS, force=True, delimiter=",", encoding=None, compression="infer", additional_col_values=None, remove_randomness=False, add_blank_lines=False, add_bad_lines=False, add_nan_lines=False, thousands_separator=None, decimal_separator=None, comment_col_char=None, quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True, escapechar=None, line_terminator=None, ): if os.path.exists(filename) and not force: pass else: df = generate_dataframe(row_size, additional_col_values) if remove_randomness: df = df[["col1", "col2", "col3", "col4"]] if add_nan_lines: for i in range(0, row_size, row_size // (row_size // 10)): df.loc[i] = pandas.Series() if comment_col_char: char = comment_col_char if isinstance(comment_col_char, str) else "#" df.insert( loc=0, column="col_with_comments", value=[char if (x + 2) == 0 else x for x in range(row_size)], ) if thousands_separator: for col_id in ["col1", "col3"]: df[col_id] = df[col_id].apply( lambda x: f"{x:,d}".replace(",", thousands_separator) ) df["col6"] = df["col6"].apply( lambda x: f"{x:,f}".replace(",", thousands_separator) ) filename = ( f"{filename}.{COMP_TO_EXT[compression]}" if compression != "infer" else filename ) df.to_csv( filename, sep=delimiter, encoding=encoding, compression=compression, index=False, decimal=decimal_separator if decimal_separator else ".", line_terminator=line_terminator, quoting=quoting, quotechar=quotechar, doublequote=doublequote, escapechar=escapechar, ) csv_reader_writer_params = { "delimiter": delimiter, "doublequote": doublequote, "escapechar": escapechar, "lineterminator": line_terminator if line_terminator else os.linesep, "quotechar": quotechar, "quoting": quoting, } if add_blank_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(5, row_size, row_size // (row_size // 10)) ], lines_type="blank", encoding=encoding, **csv_reader_writer_params, ) if add_bad_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(6, row_size, row_size // (row_size // 10)) ], lines_type="bad", encoding=encoding, **csv_reader_writer_params, ) filenames.append(filename) return df return _csv_file_maker def teardown_test_file(test_path): if os.path.exists(test_path): # PermissionError can occure because of issue #2533 try: os.remove(test_path) except PermissionError: pass def teardown_test_files(test_paths: list): for path in test_paths: teardown_test_file(path) def sort_index_for_equal_values(series, ascending=False): if series.index.dtype == np.float64: # HACK: workaround for pandas bug: # https://github.com/pandas-dev/pandas/issues/34455 series.index = series.index.astype("str") res = series.groupby(series, sort=False).apply( lambda df: df.sort_index(ascending=ascending) ) if res.index.nlevels > series.index.nlevels: # Sometimes GroupBy adds an extra level with 'by' to the result index. # GroupBy is very inconsistent about when it's doing this, so that's # why this clumsy if-statement is used. res.index = res.index.droplevel(0) res.name = series.name return res
31.848142
117
0.582124
import pytest import numpy as np import math import pandas from pandas.testing import ( assert_series_equal, assert_frame_equal, assert_index_equal, assert_extension_array_equal, ) import modin.pandas as pd from modin.utils import to_pandas from modin.config import TestDatasetSize, TrackFileLeaks from io import BytesIO import os from string import ascii_letters import csv import psutil import functools random_state = np.random.RandomState(seed=42) DATASET_SIZE_DICT = { "Small": (2 ** 2, 2 ** 3), "Normal": (2 ** 6, 2 ** 8), "Big": (2 ** 7, 2 ** 12), } NCOLS, NROWS = DATASET_SIZE_DICT.get(TestDatasetSize.get(), DATASET_SIZE_DICT["Normal"]) RAND_LOW = 0 RAND_HIGH = 100 IO_OPS_DATA_DIR = os.path.join(os.path.dirname(__file__), "io_tests_data") test_data = { "int_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.randint( RAND_LOW, RAND_HIGH, size=(NROWS) ) for i in range(NCOLS) }, "float_nan_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ x if (j % 4 == 0 and i > NCOLS // 2) or (j != i and i <= NCOLS // 2) else np.NaN for j, x in enumerate( random_state.uniform(RAND_LOW, RAND_HIGH, size=(NROWS)) ) ] for i in range(NCOLS) }, } _data["int_data"]["index"] = test_data["int_data"].pop( "col{}".format(int(NCOLS / 2)) ) for col in test_data["float_nan_data"]: for row in range(NROWS // 2): if row % 16 == 0: test_data["float_nan_data"][col][row] = np.NaN test_data_values = list(test_data.values()) test_data_keys = list(test_data.keys()) test_bool_data = { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.choice( [True, False], size=(NROWS) ) for i in range(NCOLS) } test_data_resample = { "data": {"A": range(12), "B": range(12)}, "index": pandas.date_range("31/12/2000", periods=12, freq="H"), } test_data_with_duplicates = { "no_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): range(NROWS) for i in range(NCOLS) }, "all_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ float(i) for _ in range(NROWS) ] for i in range(NCOLS) }, "some_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ i if j % 7 == 0 else x for j, x in enumerate(range(NROWS)) ] for i in range(NCOLS) }, "has_name_column": { "name": ["one", "two", "two", "three"], "col1": [1, 2, 2, 3], "col3": [10, 20, 20, 3], "col7": [100, 201, 200, 300], }, "str_columns": { "col_str{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ "s" + str(x % 5) for x in range(NROWS) ] for i in range(NCOLS) }, } test_data_with_duplicates["float_nan"] = test_data["float_nan_data"] test_data_small = { "small": { "col0": [1, 2, 3, 4], "col1": [8.0, 9.4, 10.1, 11.3], "col2": [4, 5, 6, 7], } } test_data_diff_dtype = { "int_col": [-5, 2, 7, 16], "float_col": [np.NaN, -9.4, 10.1, np.NaN], "str_col": ["a", np.NaN, "c", "d"], "bool_col": [False, True, True, False], } test_data_small_values = list(test_data_small.values()) test_data_small_keys = list(test_data_small.keys()) test_data_with_duplicates_values = list(test_data_with_duplicates.values()) test_data_with_duplicates_keys = list(test_data_with_duplicates.keys()) test_data_categorical = { "ordered": pandas.Categorical(list("testdata"), ordered=True), "unordered": pandas.Categorical(list("testdata"), ordered=False), } test_data_categorical_values = list(test_data_categorical.values()) test_data_categorical_keys = list(test_data_categorical.keys()) numeric_dfs = [ "empty_data", "columns_only", "int_data", "float_nan_data", "with_index_column", ] no_numeric_dfs = ["datetime_timedelta_data"] test_string_data = { "separator data": [ "abC|DeF,Hik", "234,3245.67", "gSaf,qWer|Gre", "asd3,4sad|", np.NaN, ] } test_string_data_values = list(test_string_data.values()) test_string_data_keys = list(test_string_data.keys()) test_string_list_data = {"simple string": [["a"], ["CdE"], ["jDf"], ["werB"]]} test_string_list_data_values = list(test_string_list_data.values()) test_string_list_data_keys = list(test_string_list_data.keys()) string_seperators = {"empty sep": "", "comma sep": ",", "None sep": None} string_sep_values = list(string_seperators.values()) string_sep_keys = list(string_seperators.keys()) string_na_rep = {"None na_rep": None, "- na_rep": "-", "nan na_rep": np.NaN} string_na_rep_values = list(string_na_rep.values()) string_na_rep_keys = list(string_na_rep.keys()) join_type = {"left": "left", "right": "right", "inner": "inner", "outer": "outer"} join_type_keys = list(join_type.keys()) join_type_values = list(join_type.values()) test_func = { "plus one": lambda x: x + 1, "convert to string": lambda x: str(x), "square": lambda x: x * x, "identity": lambda x: x, "return false": lambda x: False, } test_func_keys = list(test_func.keys()) test_func_values = list(test_func.values()) numeric_test_funcs = ["plus one", "square"] query_func = { "col1 < col2": "col1 < col2", "col3 > col4": "col3 > col4", "col1 == col2": "col1 == col2", "(col2 > col1) and (col1 < col3)": "(col2 > col1) and (col1 < col3)", } query_func_keys = list(query_func.keys()) query_func_values = list(query_func.values()) agg_func = { "sum": "sum", "df sum": lambda df: df.sum(), "str": str, "sum mean": ["sum", "mean"], "sum df sum": ["sum", lambda df: df.sum()], "should raise TypeError": 1, } agg_func_keys = list(agg_func.keys()) agg_func_values = list(agg_func.values()) agg_func_except = { "sum sum": ["sum", "sum"], } agg_func_except_keys = list(agg_func_except.keys()) agg_func_except_values = list(agg_func_except.values()) numeric_agg_funcs = ["sum mean", "sum sum", "sum df sum"] udf_func = { "return self": lambda df: lambda x, *args, **kwargs: type(x)(x.values), "change index": lambda df: lambda x, *args, **kwargs: pandas.Series( x.values, index=np.arange(-1, len(x.index) - 1) ), "return none": lambda df: lambda x, *args, **kwargs: None, "return empty": lambda df: lambda x, *args, **kwargs: pandas.Series(), "access self": lambda df: lambda x, other, *args, **kwargs: pandas.Series( x.values, index=other.index ), } udf_func_keys = list(udf_func.keys()) udf_func_values = list(udf_func.values()) quantiles = { "0.25": 0.25, "0.5": 0.5, "0.75": 0.75, "0.66": 0.66, "0.01": 0.01, "list": [0.25, 0.5, 0.75, 0.66, 0.01], } quantiles_keys = list(quantiles.keys()) quantiles_values = list(quantiles.values()) indices = { "col1": "col1", "col2": "col2", "A": "A", "B": "B", "does not exist": "does not exist", } indices_keys = list(indices.keys()) indices_values = list(indices.values()) groupby_apply_func = {"sum": lambda df: df.sum(), "negate": lambda df: -df} groupby_apply_func_keys = list(groupby_apply_func.keys()) groupby_apply_func_values = list(groupby_apply_func.values()) groupby_agg_func = {"min": "min", "max": "max"} groupby_agg_func_keys = list(groupby_agg_func.keys()) groupby_agg_func_values = list(groupby_agg_func.values()) groupby_transform_func = { "add 4": lambda df: df + 4, "negatie and minus 10": lambda df: -df - 10, } groupby_transform_func_keys = list(groupby_transform_func.keys()) groupby_transform_func_values = list(groupby_transform_func.values()) groupby_pipe_func = {"sum": lambda df: df.sum()} groupby_pipe_func_keys = list(groupby_pipe_func.keys()) groupby_pipe_func_values = list(groupby_pipe_func.values()) axis = { "over_rows_int": 0, "over_rows_str": "rows", "over_columns_int": 1, "over_columns_str": "columns", } axis_keys = list(axis.keys()) axis_values = list(axis.values()) bool_arg = {"True": True, "False": False, "None": None} bool_arg_keys = list(bool_arg.keys()) bool_arg_values = list(bool_arg.values()) int_arg = {"-5": -5, "-1": -1, "0": 0, "1": 1, "5": 5} int_arg_keys = list(int_arg.keys()) int_arg_values = list(int_arg.values()) json_short_string = """[{"project": "modin"}]""" json_long_string = """{ "quiz": { "sport": { "q1": { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" } }, "maths": { "q1": { "question": "5 + 7 = ?", "options": [ "10", "11", "12", "13" ], "answer": "12" }, "q2": { "question": "12 - 8 = ?", "options": [ "1", "2", "3", "4" ], "answer": "4" } } } }""" json_long_bytes = BytesIO(json_long_string.encode(encoding="UTF-8")) json_short_bytes = BytesIO(json_short_string.encode(encoding="UTF-8")) encoding_types = [ "ascii", "utf_32", "utf_32_be", "utf_32_le", "utf_16", "utf_16_be", "utf_16_le", "utf_7", "utf_8", "utf_8_sig", ] io_ops_bad_exc = [TypeError, FileNotFoundError] COMP_TO_EXT = {"gzip": "gz", "bz2": "bz2", "xz": "xz", "zip": "zip"} def categories_equals(left, right): assert (left.ordered and right.ordered) or (not left.ordered and not right.ordered) assert_extension_array_equal(left, right) def df_categories_equals(df1, df2): if not hasattr(df1, "select_dtypes"): if isinstance(df1, pandas.CategoricalDtype): return categories_equals(df1, df2) elif isinstance(getattr(df1, "dtype"), pandas.CategoricalDtype) and isinstance( getattr(df1, "dtype"), pandas.CategoricalDtype ): return categories_equals(df1.dtype, df2.dtype) else: return True categories_columns = df1.select_dtypes(include="category").columns for column in categories_columns: assert_extension_array_equal( df1[column].values, df2[column].values, check_dtype=False, ) def df_equals(df1, df2): from modin.pandas.groupby import DataFrameGroupBy groupby_types = (pandas.core.groupby.DataFrameGroupBy, DataFrameGroupBy) # The typing behavior of how pandas treats its index is not consistent when the # length of the DataFrame or Series is 0, so we just verify that the contents are # the same. if ( hasattr(df1, "index") and hasattr(df2, "index") and len(df1) == 0 and len(df2) == 0 ): if type(df1).__name__ == type(df2).__name__: if hasattr(df1, "name") and hasattr(df2, "name") and df1.name == df2.name: return if ( hasattr(df1, "columns") and hasattr(df2, "columns") and df1.columns.equals(df2.columns) ): return assert False if isinstance(df1, (list, tuple)) and all( isinstance(d, (pd.DataFrame, pd.Series, pandas.DataFrame, pandas.Series)) for d in df1 ): assert isinstance(df2, type(df1)), "Different type of collection" assert len(df1) == len(df2), "Different length result" return (df_equals(d1, d2) for d1, d2 in zip(df1, df2)) # Convert to pandas if isinstance(df1, (pd.DataFrame, pd.Series)): df1 = to_pandas(df1) if isinstance(df2, (pd.DataFrame, pd.Series)): df2 = to_pandas(df2) if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): if (df1.empty and not df2.empty) or (df2.empty and not df1.empty): assert False, "One of the passed frames is empty, when other isn't" elif df1.empty and df2.empty and type(df1) != type(df2): assert ( False ), f"Empty frames have different types: {type(df1)} != {type(df2)}" if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): assert_frame_equal( df1, df2, check_dtype=False, check_datetimelike_compat=True, check_index_type=False, check_column_type=False, check_categorical=False, ) df_categories_equals(df1, df2) elif isinstance(df1, pandas.Index) and isinstance(df2, pandas.Index): assert_index_equal(df1, df2) elif isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series): assert_series_equal(df1, df2, check_dtype=False, check_series_type=False) elif isinstance(df1, groupby_types) and isinstance(df2, groupby_types): for g1, g2 in zip(df1, df2): assert g1[0] == g2[0] df_equals(g1[1], g2[1]) elif ( isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series) and df1.empty and df2.empty ): assert all(df1.index == df2.index) assert df1.dtypes == df2.dtypes elif isinstance(df1, pandas.core.arrays.numpy_.PandasArray): assert isinstance(df2, pandas.core.arrays.numpy_.PandasArray) assert df1 == df2 elif isinstance(df1, np.recarray) and isinstance(df2, np.recarray): np.testing.assert_array_equal(df1, df2) else: if df1 != df2: np.testing.assert_almost_equal(df1, df2) def modin_df_almost_equals_pandas(modin_df, pandas_df): df_categories_equals(modin_df._to_pandas(), pandas_df) modin_df = to_pandas(modin_df) if hasattr(modin_df, "select_dtypes"): modin_df = modin_df.select_dtypes(exclude=["category"]) if hasattr(pandas_df, "select_dtypes"): pandas_df = pandas_df.select_dtypes(exclude=["category"]) difference = modin_df - pandas_df diff_max = difference.max() if isinstance(diff_max, pandas.Series): diff_max = diff_max.max() assert ( modin_df.equals(pandas_df) or diff_max < 0.0001 or (all(modin_df.isna().all()) and all(pandas_df.isna().all())) ) def df_is_empty(df): assert df.size == 0 and df.empty assert df.shape[0] == 0 or df.shape[1] == 0 def arg_keys(arg_name, keys): return ["{0}_{1}".format(arg_name, key) for key in keys] def name_contains(test_name, vals): return any(val in test_name for val in vals) def check_df_columns_have_nans(df, cols): return ( pandas.api.types.is_list_like(cols) and ( any(isinstance(x, str) and x in df.columns and df[x].hasnans for x in cols) or any( isinstance(x, pd.Series) and x._parent is df and x.hasnans for x in cols ) ) ) or ( not pandas.api.types.is_list_like(cols) and cols in df.columns and df[cols].hasnans ) def eval_general( modin_df, pandas_df, operation, comparator=df_equals, __inplace__=False, check_exception_type=True, raising_exceptions=None, check_kwargs_callable=True, md_extra_kwargs=None, **kwargs, ): if raising_exceptions: assert ( check_exception_type ), "if raising_exceptions is not None or False, check_exception_type should be True" md_kwargs, pd_kwargs = {}, {} def execute_callable(fn, inplace=False, md_kwargs={}, pd_kwargs={}): try: pd_result = fn(pandas_df, **pd_kwargs) except Exception as pd_e: if check_exception_type is None: return None with pytest.raises(Exception) as md_e: repr(fn(modin_df, **md_kwargs)) if check_exception_type: assert isinstance(md_e.value, type(pd_e)) if raising_exceptions: assert not isinstance( md_e.value, tuple(raising_exceptions) ), f"not acceptable exception type: {md_e.value}" else: md_result = fn(modin_df, **md_kwargs) return (md_result, pd_result) if not __inplace__ else (modin_df, pandas_df) for key, value in kwargs.items(): if check_kwargs_callable and callable(value): values = execute_callable(value) if values is None: return else: md_value, pd_value = values else: md_value, pd_value = value, value md_kwargs[key] = md_value pd_kwargs[key] = pd_value if md_extra_kwargs: assert isinstance(md_extra_kwargs, dict) md_kwargs.update(md_extra_kwargs) values = execute_callable( operation, md_kwargs=md_kwargs, pd_kwargs=pd_kwargs, inplace=__inplace__ ) if values is not None: comparator(*values) def eval_io( fn_name, comparator=df_equals, cast_to_str=False, check_exception_type=True, raising_exceptions=io_ops_bad_exc, check_kwargs_callable=True, modin_warning=None, md_extra_kwargs=None, *args, **kwargs, ): def applyier(module, *args, **kwargs): result = getattr(module, fn_name)(*args, **kwargs) if cast_to_str: result = result.astype(str) return result def call_eval_general(): eval_general( pd, pandas, applyier, check_exception_type=check_exception_type, raising_exceptions=raising_exceptions, check_kwargs_callable=check_kwargs_callable, md_extra_kwargs=md_extra_kwargs, *args, **kwargs, ) if modin_warning: with pytest.warns(modin_warning): call_eval_general() else: call_eval_general() def eval_io_from_str(csv_str: str, unique_filename: str, **kwargs): try: with open(unique_filename, "w") as f: f.write(csv_str) eval_io( filepath_or_buffer=unique_filename, fn_name="read_csv", **kwargs, ) finally: if os.path.exists(unique_filename): try: os.remove(unique_filename) except PermissionError: pass def create_test_dfs(*args, **kwargs): post_fn = kwargs.pop("post_fn", lambda df: df) return map( post_fn, [pd.DataFrame(*args, **kwargs), pandas.DataFrame(*args, **kwargs)] ) def generate_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [0, 0, 0, 0], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def generate_multiindex_dfs(axis=1): def generate_multiindex(index): return pandas.MultiIndex.from_tuples( [("a", x) for x in index.values], names=["name1", "name2"] ) df1, df2 = generate_dfs() df1.axes[axis], df2.axes[axis] = map( generate_multiindex, [df1.axes[axis], df2.axes[axis]] ) return df1, df2 def generate_multiindex(elements_number, nlevels=2, is_tree_like=False): def generate_level(length, nlevel): src = ["bar", "baz", "foo", "qux"] return [src[i % len(src)] + f"-{nlevel}-{i}" for i in range(length)] if is_tree_like: for penalty_level in [0, 1]: lvl_len_f, lvl_len_d = math.modf( round(elements_number ** (1 / (nlevels - penalty_level)), 12) ) if lvl_len_d >= 2 and lvl_len_f == 0: break if lvl_len_d < 2 or lvl_len_f != 0: raise RuntimeError( f"Can't generate Tree-like MultiIndex with lenght: {elements_number} and number of levels: {nlevels}" ) lvl_len = int(lvl_len_d) result = pd.MultiIndex.from_product( [generate_level(lvl_len, i) for i in range(nlevels - penalty_level)], names=[f"level-{i}" for i in range(nlevels - penalty_level)], ) if penalty_level: result = pd.MultiIndex.from_tuples( [("base_level", *ml_tuple) for ml_tuple in result], names=[f"level-{i}" for i in range(nlevels)], ) return result.sort_values() else: base_level = ["first"] * (elements_number // 2 + elements_number % 2) + [ "second" ] * (elements_number // 2) primary_levels = [generate_level(elements_number, i) for i in range(1, nlevels)] arrays = [base_level] + primary_levels return pd.MultiIndex.from_tuples( list(zip(*arrays)), names=[f"level-{i}" for i in range(nlevels)] ).sort_values() def generate_none_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, None, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [None, None, None, None], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def get_unique_filename( test_name: str = "test", kwargs: dict = {}, extension: str = "csv", data_dir: str = IO_OPS_DATA_DIR, suffix: str = "", debug_mode=False, ): suffix_part = f"_{suffix}" if suffix else "" extension_part = f".{extension}" if extension else "" if debug_mode: # shortcut if kwargs parameter are not provided if len(kwargs) == 0 and extension == "csv" and suffix == "": return os.path.join(data_dir, (test_name + suffix_part + f".{extension}")) assert "." not in extension, "please provide pure extension name without '.'" prohibited_chars = ['"', "\n"] non_prohibited_char = "np_char" char_counter = 0 kwargs_name = dict(kwargs) for key, value in kwargs_name.items(): for char in prohibited_chars: if isinstance(value, str) and char in value or callable(value): kwargs_name[key] = non_prohibited_char + str(char_counter) char_counter += 1 parameters_values = "_".join( [ str(value) if not isinstance(value, (list, tuple)) else "_".join([str(x) for x in value]) for value in kwargs_name.values() ] ) return os.path.join( data_dir, test_name + parameters_values + suffix_part + extension_part ) else: import uuid return os.path.join(data_dir, uuid.uuid1().hex + suffix_part + extension_part) def get_random_string(): random_string = "".join( random_state.choice([x for x in ascii_letters], size=10).tolist() ) return random_string def insert_lines_to_csv( csv_name: str, lines_positions: list, lines_type: str = "blank", encoding: str = None, **csv_reader_writer_params, ): cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) if lines_type == "blank": lines_data = [] elif lines_type == "bad": cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) lines_data = [x for x in range(cols_number + 1)] else: raise ValueError( f"acceptable values for parameter are ['blank', 'bad'], actually passed {lines_type}" ) lines = [] dialect = "excel" with open(csv_name, "r", encoding=encoding, newline="") as read_file: try: dialect = csv.Sniffer().sniff(read_file.read()) read_file.seek(0) except Exception: dialect = None reader = csv.reader( read_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) counter = 0 for row in reader: if counter in lines_positions: lines.append(lines_data) else: lines.append(row) counter += 1 with open(csv_name, "w", encoding=encoding, newline="") as write_file: writer = csv.writer( write_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) writer.writerows(lines) def _get_open_files(): return sorted((info.path, info.fd) for info in psutil.Process().open_files()) def check_file_leaks(func): if not TrackFileLeaks.get(): return func @functools.wraps(func) def check(*a, **kw): fstart = _get_open_files() try: return func(*a, **kw) finally: leaks = [] for item in _get_open_files(): try: fstart.remove(item) except ValueError: # ignore files in /proc/, as they have nothing to do with # modin reading any data (and this is what we care about) if not item[0].startswith("/proc/"): leaks.append(item) assert ( not leaks ), f"Unexpected open handles left for: {', '.join(item[0] for item in leaks)}" return check def dummy_decorator(): def wrapper(method): def wrapped_function(self, *args, **kwargs): result = method(self, *args, **kwargs) return result return wrapped_function return wrapper def generate_dataframe(row_size=NROWS, additional_col_values=None): dates = pandas.date_range("2000", freq="h", periods=row_size) data = { "col1": np.arange(row_size) * 10, "col2": [str(x.date()) for x in dates], "col3": np.arange(row_size) * 10, "col4": [str(x.time()) for x in dates], "col5": [get_random_string() for _ in range(row_size)], "col6": random_state.uniform(low=0.0, high=10000.0, size=row_size), } if additional_col_values is not None: assert isinstance(additional_col_values, (list, tuple)) data.update( { "col7": random_state.choice(additional_col_values, size=row_size), } ) return pandas.DataFrame(data) def _make_csv_file(filenames): def _csv_file_maker( filename, row_size=NROWS, force=True, delimiter=",", encoding=None, compression="infer", additional_col_values=None, remove_randomness=False, add_blank_lines=False, add_bad_lines=False, add_nan_lines=False, thousands_separator=None, decimal_separator=None, comment_col_char=None, quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True, escapechar=None, line_terminator=None, ): if os.path.exists(filename) and not force: pass else: df = generate_dataframe(row_size, additional_col_values) if remove_randomness: df = df[["col1", "col2", "col3", "col4"]] if add_nan_lines: for i in range(0, row_size, row_size // (row_size // 10)): df.loc[i] = pandas.Series() if comment_col_char: char = comment_col_char if isinstance(comment_col_char, str) else "#" df.insert( loc=0, column="col_with_comments", value=[char if (x + 2) == 0 else x for x in range(row_size)], ) if thousands_separator: for col_id in ["col1", "col3"]: df[col_id] = df[col_id].apply( lambda x: f"{x:,d}".replace(",", thousands_separator) ) df["col6"] = df["col6"].apply( lambda x: f"{x:,f}".replace(",", thousands_separator) ) filename = ( f"{filename}.{COMP_TO_EXT[compression]}" if compression != "infer" else filename ) df.to_csv( filename, sep=delimiter, encoding=encoding, compression=compression, index=False, decimal=decimal_separator if decimal_separator else ".", line_terminator=line_terminator, quoting=quoting, quotechar=quotechar, doublequote=doublequote, escapechar=escapechar, ) csv_reader_writer_params = { "delimiter": delimiter, "doublequote": doublequote, "escapechar": escapechar, "lineterminator": line_terminator if line_terminator else os.linesep, "quotechar": quotechar, "quoting": quoting, } if add_blank_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(5, row_size, row_size // (row_size // 10)) ], lines_type="blank", encoding=encoding, **csv_reader_writer_params, ) if add_bad_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(6, row_size, row_size // (row_size // 10)) ], lines_type="bad", encoding=encoding, **csv_reader_writer_params, ) filenames.append(filename) return df return _csv_file_maker def teardown_test_file(test_path): if os.path.exists(test_path): # PermissionError can occure because of issue #2533 try: os.remove(test_path) except PermissionError: pass def teardown_test_files(test_paths: list): for path in test_paths: teardown_test_file(path) def sort_index_for_equal_values(series, ascending=False): if series.index.dtype == np.float64: # HACK: workaround for pandas bug: # https://github.com/pandas-dev/pandas/issues/34455 series.index = series.index.astype("str") res = series.groupby(series, sort=False).apply( lambda df: df.sort_index(ascending=ascending) ) if res.index.nlevels > series.index.nlevels: # Sometimes GroupBy adds an extra level with 'by' to the result index. # GroupBy is very inconsistent about when it's doing this, so that's # why this clumsy if-statement is used. res.index = res.index.droplevel(0) res.name = series.name return res
true
true
f72a54e9a3329047951044887f34ffc35ca51dd9
310
py
Python
jukebox/urls.py
bharadhwaj/jukebox
7223e6c686ac2868c6284270564db6d557b17fc5
[ "MIT" ]
1
2018-06-12T10:51:15.000Z
2018-06-12T10:51:15.000Z
jukebox/urls.py
bharadhwaj/jukebox
7223e6c686ac2868c6284270564db6d557b17fc5
[ "MIT" ]
3
2020-06-05T18:26:16.000Z
2021-06-10T20:30:23.000Z
jukebox/urls.py
bharadhwaj/jukebox
7223e6c686ac2868c6284270564db6d557b17fc5
[ "MIT" ]
null
null
null
from django.urls import path from . import views app_name = 'links' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('vote/', views.VoteView.as_view(), name='vote'), path('votes/', views.vote, name='votes'), path('result/', views.ResultView.as_view(), name='result'), ]
28.181818
63
0.651613
from django.urls import path from . import views app_name = 'links' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('vote/', views.VoteView.as_view(), name='vote'), path('votes/', views.vote, name='votes'), path('result/', views.ResultView.as_view(), name='result'), ]
true
true
f72a55535692922be0aa294cac9b8cf77add2f60
106,671
py
Python
InplusTrader/ctaAlgo/ctaBacktesting1.py
zhengwsh/InplusTrader_Linux
5f7eb17004da0b76ceafb93cb314de7a6009cd04
[ "MIT" ]
17
2017-04-20T05:17:25.000Z
2020-09-30T08:58:03.000Z
InplusTrader/ctaAlgo/ctaBacktesting1.py
vladhj38/InplusTrader_Linux
5f7eb17004da0b76ceafb93cb314de7a6009cd04
[ "MIT" ]
1
2017-11-12T01:24:06.000Z
2019-09-19T08:50:38.000Z
InplusTrader/ctaAlgo/ctaBacktesting1.py
vladhj38/InplusTrader_Linux
5f7eb17004da0b76ceafb93cb314de7a6009cd04
[ "MIT" ]
17
2017-04-17T08:17:00.000Z
2020-10-25T01:56:49.000Z
# encoding: UTF-8 ''' 本文件中包含的是CTA模块的回测引擎,回测引擎的API和CTA引擎一致, 可以使用和实盘相同的代码进行回测。 ''' from __future__ import division from itertools import product import copy import os import sys import re import csv import time import multiprocessing import json import pymongo import threading from datetime import datetime from collections import OrderedDict from progressbar import ProgressBar from collections import deque from ctaBase import * from vtConstant import * from vtGateway import VtOrderData, VtTradeData from vtFunction import loadMongoSetting ######################################################################## class BacktestingEngine(object): """ CTA回测引擎 函数接口和策略引擎保持一样, 从而实现同一套代码从回测到实盘。 增加双合约回测功能 增加快速慢速切换功能(挂单策略建议使用快速模式) """ TICK_MODE = 'tick' BAR_MODE = 'bar' bufferSize = 1000 Version = 20170726 # ---------------------------------------------------------------------- def __init__(self, optimism=False): """Constructor""" # 本地停止单编号计数 self.stopOrderCount = 0 # stopOrderID = STOPORDERPREFIX + str(stopOrderCount) # 本地停止单字典 # key为stopOrderID,value为stopOrder对象 self.stopOrderDict = {} # 停止单撤销后不会从本字典中删除 self.workingStopOrderDict = {} # 停止单撤销后会从本字典中删除 # 回测相关 self.strategy = None # 回测策略 self.vtSymbol = None self.vtSymbol1 = None self.mode = self.BAR_MODE # 回测模式,默认为K线 self.shfe = True # 上期所 self.fast = False # 是否支持排队 self.plot = True self.plotfile = False self.optimism = False self.leverage = 0.07 # 杠杠比率 self.leverage1 = 0.07 # 杠杠比率 self.slippage = 0 # 回测时假设的滑点 self.slippage1 = 0 # 回测时假设的滑点 self.rate = 0 # 回测时假设的佣金比例(适用于百分比佣金) self.rate1 = 0 # 回测时假设的佣金比例(适用于百分比佣金) self.size = 1 # 合约大小,默认为1 self.size1 = 1 # 合约大小,默认为1 self.mPrice = 1 # 最小价格变动,默认为1 self.mPrice1 = 1 # 最小价格变动,默认为1 self.dbClient = None # 数据库客户端 self.mcClient = None # 数据库客户端 self.dbCursor = None # 数据库指针 self.dbCursor1 = None # 数据库指针 self.backtestingData = deque([]) # 回测用的数据 self.backtestingData1 = deque([]) # 回测用的数据 self.dataStartDate = None # 回测数据开始日期,datetime对象 self.dataEndDate = None # 回测数据结束日期,datetime对象 self.strategyStartDate = None # 策略启动日期(即前面的数据用于初始化),datetime对象 self.limitOrderDict = OrderedDict() # 限价单字典 self.workingLimitOrderDict = OrderedDict() # 活动限价单字典,用于进行撮合用 self.limitOrderCount = 0 # 限价单编号 self.limitOrderDict1 = OrderedDict() # 合约2限价单字典 self.workingLimitOrderDict1 = OrderedDict() # 合约2活动限价单字典,用于进行撮合用 self.tradeCount = 0 # 成交编号 self.tradeDict = OrderedDict() # 成交字典 self.tradeCount1 = 0 # 成交编号1 self.tradeDict1 = OrderedDict() # 成交字典1 self.tradeSnap = OrderedDict() # 主合约市场快照 self.tradeSnap1 = OrderedDict() # 副合约市场快照 self.trade1Snap = OrderedDict() # 主合约市场快照1 self.trade1Snap1 = OrderedDict() # 副合约市场快照1 self.i = 0 # 主合约数据准备进度 self.j = 0 # 副合约数据准备进度 self.dataClass = None self._dataClass = None self.logList = [] # 日志记录 self.orderPrice = {} # 主合约限价单价格 self.orderVolume = {} # 副合约限价单盘口 self.orderPrice1 = {} # 限价单价格 self.orderVolume1 = {} # 限价单盘口 # 当前最新数据,用于模拟成交用 self.tick = None self.tick1 = None self.lasttick = None self.lasttick1 = None self.bar = None self.bar1 = None self.lastbar = None self.lastbar1 = None self.dt = None # 最新的时间 # ---------------------------------------------------------------------- def setStartDate(self, startDate='20170501'): """设置回测的启动日期 支持两种日期模式""" if len(startDate) == 8: self.dataStartDate = datetime.strptime(startDate, '%Y%m%d') elif len(startDate) == 10: self.dataStartDate = datetime.strptime(startDate, '%Y-%m-%d') else: self.dataStartDate = datetime.strptime(startDate, '%Y-%m-%d %H:%M:%S') #'%Y%m%d %H:%M:%S' # ---------------------------------------------------------------------- def setEndDate(self, endDate='20170501'): """设置回测的结束日期 支持两种日期模式""" if len(endDate) == 8: self.dataEndDate = datetime.strptime(endDate, '%Y%m%d') elif len(endDate) == 10: self.dataEndDate = datetime.strptime(endDate, '%Y-%m-%d') else: self.dataEndDate = datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S') # ---------------------------------------------------------------------- def setBacktestingMode(self, mode): """设置回测模式""" self.mode = mode if self.mode == self.BAR_MODE: self.dataClass = CtaBarData self._dataClass = CtaBarData1 else: self.dataClass = CtaTickData self._dataClass = CtaTickData1 # ---------------------------------------------------------------------- def loadHistoryData1(self, dbName, symbol): """载入历史数据""" # symbol = 'I88tick' host, port, logging = loadMongoSetting() if not self.dbClient: self.dbClient = pymongo.MongoClient(host, port, socketKeepAlive=True) collection = self.dbClient[dbName][symbol] self.output(u'开始载入合约2数据') # 首先根据回测模式,确认要使用的数据类 if self.mode == self.BAR_MODE: dataClass = CtaBarData func = self.newBar1 else: dataClass = CtaTickData func = self.newTick1 # 载入回测数据 fltStartDate = self.dataStartDate.strftime("%Y-%m-%d %H:%M:%S") fltEndDate = self.dataEndDate.strftime("%Y-%m-%d %H:%M:%S") self.output("Start : " + str(self.dataStartDate)) self.output("End : " + str(self.dataEndDate)) if not self.dataEndDate: flt = {'datetime': {'$gte': fltStartDate}} # 数据过滤条件 else: flt = {'datetime': {'$gte': fltStartDate, '$lte': fltEndDate}} self.dbCursor1 = collection.find(flt, no_cursor_timeout=True).batch_size(self.bufferSize) self.output(u'载入完成,数据量:%s' % (self.dbCursor1.count())) self.output(u' ') # ---------------------------------------------------------------------- def loadHistoryData(self, dbName, symbol): """载入历史数据""" # symbol = 'I88tick' host, port, logging = loadMongoSetting() if not self.dbClient: self.dbClient = pymongo.MongoClient(host, port, socketKeepAlive=True) collection = self.dbClient[dbName][symbol] self.output(u'开始载入合约1数据') # 首先根据回测模式,确认要使用的数据类 if self.mode == self.BAR_MODE: dataClass = CtaBarData func = self.newBar else: dataClass = CtaTickData func = self.newTick # 载入回测数据 fltStartDate = self.dataStartDate.strftime("%Y-%m-%d %H:%M:%S") fltEndDate = self.dataEndDate.strftime("%Y-%m-%d %H:%M:%S") self.output("Start : " + str(self.dataStartDate)) self.output("End : " + str(self.dataEndDate)) if not self.dataEndDate: flt = {'datetime': {'$gte': fltStartDate}} # 数据过滤条件 else: flt = {'datetime': {'$gte': fltStartDate, '$lte': fltEndDate}} self.dbCursor = collection.find(flt, no_cursor_timeout=True).batch_size(self.bufferSize) self.output(u'载入完成,数据量:%s' % (self.dbCursor.count())) self.output(u' ') # ---------------------------------------------------------------------- def prepareData(self, dbCursor_count, dbCursor_count1): """数据准备线程""" while len(self.backtestingData) < self.bufferSize and self.j < dbCursor_count: d = self.dbCursor.next() _data = self._dataClass() data = self.dataClass() _data.__dict__ = d if self.mode == 'tick': data.vtSymbol = self.strategy.vtSymbol #'I88' data.lastPrice = _data.price # 最新成交价 data.volume = _data.volume # 最新成交量 data.openInterest = _data.open_interest # 持仓量 data.upperLimit = _data.limit_up # 涨停价 data.lowerLimit = _data.limit_down # 跌停价 data.bidPrice1 = _data.bidPrice1 data.askPrice1 = _data.askPrice1 data.bidVolume1 = _data.bidVolume1 data.askVolume1 = _data.askVolume1 data.date = _data.date # 日期 data.time = _data.time # 时间 data.datetime = datetime.strptime(_data.datetime, "%Y-%m-%d %H:%M:%S.%f") # python的datetime时间对象 elif self.mode == 'bar': data.vtSymbol = self.strategy.vtSymbol # 'I88' data.open = _data.open data.high = _data.high data.low = _data.low data.close = _data.close data.volume = _data.volume data.date = _data.date # 日期 data.time = _data.time # 时间 data.datetime = datetime.strptime(_data.datetime, "%Y-%m-%d %H:%M:%S") # python的datetime时间对象 self.backtestingData.append(data) self.j += 1 while len(self.backtestingData1) < self.bufferSize and self.i < dbCursor_count1: d1 = self.dbCursor1.next() _data = self._dataClass() data1 = self.dataClass() _data.__dict__ = d1 if self.mode == 'tick': data1.vtSymbol = self.strategy.vtSymbol1 #'I88' data1.lastPrice = _data.price # 最新成交价 data1.volume = _data.volume # 最新成交量 data1.openInterest = _data.open_interest # 持仓量 data1.upperLimit = _data.limit_up # 涨停价 data1.lowerLimit = _data.limit_down # 跌停价 data1.bidPrice1 = _data.bidPrice1 data1.askPrice1 = _data.askPrice1 data1.bidVolume1 = _data.bidVolume1 data1.askVolume1 = _data.askVolume1 data1.date = _data.date # 日期 data1.time = _data.time # 时间 data1.datetime = datetime.strptime(_data.datetime, "%Y-%m-%d %H:%M:%S.%f") # python的datetime时间对象 elif self.mode == 'bar': data1.vtSymbol = self.strategy.vtSymbol1 # 'I88' data1.open = _data.open data1.high = _data.high data1.low = _data.low data1.close = _data.close data1.volume = _data.volume data1.date = _data.date # 日期 data1.time = _data.time # 时间 data1.datetime = datetime.strptime(_data.datetime, "%Y-%m-%d %H:%M:%S") # python的datetime时间对象 self.backtestingData1.append(data1) self.i += 1 # ---------------------------------------------------------------------- def runBacktesting(self): """运行回测 判断是否双合约""" if self.strategy.vtSymbol1 == None: self.runBacktesting_one() else: self.runBacktesting_two() # ---------------------------------------------------------------------- def runBacktesting_two(self): """运行回测""" if self.mode == self.BAR_MODE: self.dataClass = CtaBarData func = self.newBar func1 = self.newBar1 func2 = self.newBar01 else: self.dataClass = CtaTickData func = self.newTick func1 = self.newTick1 func2 = self.newTick01 self.output(u'-' * 30) self.output(u'开始回测') self.strategy.inited = True self.strategy.onInit() self.output(u'策略初始化完成') self.strategy.trading = True self.strategy.onStart() self.output(u'策略启动完成') dbCursor_count = self.dbCursor.count() dbCursor_count1 = self.dbCursor1.count() self.i = 0; self.j = 0; lastData = None lastData1 = None t = None self.output(u'开始回放双合约数据') # 双合约回测 while (self.i < dbCursor_count1 and self.j < dbCursor_count) or ( self.backtestingData and self.backtestingData1): # 启动数据准备线程 t = threading.Thread(target=self.prepareData, args=(dbCursor_count, dbCursor_count1)) t.start() # 模拟撮合 while self.backtestingData and self.backtestingData1: # 考虑切片数据可能不连续,同步两个合约的数据 if self.backtestingData1[0].datetime > self.backtestingData[0].datetime: if lastData1: func2(self.backtestingData[0], lastData1) lastData = self.backtestingData.popleft() elif self.backtestingData[0].datetime > self.backtestingData1[0].datetime: if lastData: func2(lastData, self.backtestingData1[0]) lastData1 = self.backtestingData1.popleft() elif self.backtestingData and self.backtestingData1 and self.backtestingData1[0].datetime == \ self.backtestingData[0].datetime: func2(self.backtestingData[0], self.backtestingData1[0]) lastData = self.backtestingData.popleft() lastData1 = self.backtestingData1.popleft() t.join() self.strategy.onStop() self.output(u'数据回放结束') # ---------------------------------------------------------------------- def runBacktesting_one(self): """运行回测""" if self.mode == self.BAR_MODE: self.dataClass = CtaBarData func = self.newBar func1 = self.newBar1 else: self.dataClass = CtaTickData func = self.newTick self.output(u'开始回测') self.strategy.inited = True self.strategy.onInit() self.output(u'策略初始化完成') self.strategy.trading = True self.strategy.onStart() self.output(u'策略启动完成') self.output(u'开始回放单合约数据') dbCursor_count = self.dbCursor.count() self.j = 0; self.i = 0; dbCursor_count1 = 0 lastData = None lastData1 = None t = None # 单合约回测 while self.j < dbCursor_count or self.backtestingData: # 启动数据准备线程 t = threading.Thread(target=self.prepareData, args=(dbCursor_count, dbCursor_count1)) t.start() # 模拟撮合 while self.backtestingData: lastData = self.backtestingData.popleft() func(lastData) t.join() self.strategy.onStop() self.output(u'数据回放结束') # ---------------------------------------------------------------------- def newBar(self, bar): """新的K线""" self.bar = bar self.dt = bar.datetime self.crossLimitOrder() # 先撮合限价单 # self.crossStopOrder() # 再撮合停止单 self.strategy.onBar(bar) # 推送K线到策略中 # ---------------------------------------------------------------------- def newBar1(self, bar): """新的K线""" self.bar1 = bar self.dt = bar.datetime self.crossLimitOrder1() # 先撮合限价单 self.strategy.onBar(bar) # 推送K线到策略中 # ---------------------------------------------------------------------- def newBar01(self, bar, bar1): """新的Bar""" self.dt = bar.datetime self.bar = bar self.bar1 = bar1 # 低速模式(延时1个Tick撮合) self.crossBarLimitOrder1() self.crossBarLimitOrder() # 没有切片的合约不发送行情(为了和实盘一致) if bar1.datetime >= bar.datetime: self.strategy.onBar(self.bar1) if bar.datetime >= bar1.datetime: self.strategy.onBar(self.bar) self.strategy.onSpread() # 高速模式(直接撮合) if self.optimism: self.crossBarLimitOrder1() self.crossBarLimitOrder() self.lastbar = self.bar self.lastbar1 = self.bar1 # ---------------------------------------------------------------------- def newTick(self, tick): """新的Tick""" self.tick = tick self.dt = tick.datetime # 低速模式(延时1个Tick撮合) self.crossLimitOrder() self.strategy.onTick(tick) # 高速模式(直接撮合) if self.optimism: self.crossLimitOrder() self.lasttick = tick # ---------------------------------------------------------------------- def newTick1(self, tick): """新的Tick""" self.tick1 = tick self.dt = tick.datetime # 低速模式(延时1个Tick撮合) self.crossLimitOrder() self.strategy.onTick(tick) # 高速模式(直接撮合) if self.optimism: self.crossLimitOrder() self.lasttick1 = tick # ---------------------------------------------------------------------- def newTick01(self, tick, tick1): """新的Tick""" self.dt = tick.datetime self.tick = tick self.tick1 = tick1 # 低速模式(延时1个Tick撮合) self.crossLimitOrder1() self.crossLimitOrder() # 没有切片的合约不发送行情(为了和实盘一致) if tick1.datetime >= tick.datetime: self.strategy.onTick(self.tick1) if tick.datetime >= tick1.datetime: self.strategy.onTick(self.tick) # 高速模式(直接撮合) if self.optimism: self.crossLimitOrder1() self.crossLimitOrder() self.lasttick = self.tick self.lasttick1 = self.tick1 # ---------------------------------------------------------------------- def initStrategy(self, strategyClass, setting=None): """ 初始化策略 setting是策略的参数设置,如果使用类中写好的默认设置则可以不传该参数 """ self.strategy = strategyClass(self, setting) # self.strategy.name = self.strategy.className # ---------------------------------------------------------------------- def sendOrder(self, vtSymbol, orderType, price, volume, strategy): """发单""" self.limitOrderCount += 1 orderID = str(self.limitOrderCount) order = VtOrderData() order.vtSymbol = vtSymbol order.price = price order.priceType = PRICETYPE_LIMITPRICE order.totalVolume = volume order.status = STATUS_NOTTRADED # 刚提交尚未成交 order.orderID = orderID order.vtOrderID = orderID order.orderTime = str(self.dt) # CTA委托类型映射 if orderType == CTAORDER_BUY: order.direction = DIRECTION_LONG order.offset = OFFSET_OPEN elif orderType == CTAORDER_SHORT: order.direction = DIRECTION_SHORT order.offset = OFFSET_OPEN elif orderType == CTAORDER_SELL and not self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSE elif orderType == CTAORDER_SELL and self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_COVER and not self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSE elif orderType == CTAORDER_COVER and self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_SELL_TODAY: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSETODAY elif orderType == CTAORDER_COVER_TODAY: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSETODAY # 保存到限价单字典中 if vtSymbol == strategy.vtSymbol: self.workingLimitOrderDict[orderID] = order self.limitOrderDict[orderID] = order elif vtSymbol == strategy.vtSymbol1: self.workingLimitOrderDict1[orderID] = order self.limitOrderDict1[orderID] = order return orderID # ---------------------------------------------------------------------- def sendOrderFAK(self, vtSymbol, orderType, price, volume, strategy): """发单""" self.limitOrderCount += 1 orderID = str(self.limitOrderCount) order = VtOrderData() order.vtSymbol = vtSymbol order.price = price order.priceType = PRICETYPE_FAK order.totalVolume = volume order.status = STATUS_NOTTRADED # 刚提交尚未成交 order.orderID = orderID order.vtOrderID = orderID order.orderTime = str(self.dt) # CTA委托类型映射 if orderType == CTAORDER_BUY: order.direction = DIRECTION_LONG order.offset = OFFSET_OPEN elif orderType == CTAORDER_SELL and not self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSE elif orderType == CTAORDER_SELL and self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_SELL_TODAY: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSETODAY elif orderType == CTAORDER_SHORT: order.direction = DIRECTION_SHORT order.offset = OFFSET_OPEN elif orderType == CTAORDER_COVER and not self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSE elif orderType == CTAORDER_COVER and self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_COVER_TODAY: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSETODAY # 保存到限价单字典中 if vtSymbol == strategy.vtSymbol: self.workingLimitOrderDict[orderID] = order self.limitOrderDict[orderID] = order elif vtSymbol == strategy.vtSymbol1: self.workingLimitOrderDict1[orderID] = order self.limitOrderDict1[orderID] = order return orderID # ---------------------------------------------------------------------- def sendOrderFOK(self, vtSymbol, orderType, price, volume, strategy): """发单""" self.limitOrderCount += 1 orderID = str(self.limitOrderCount) order = VtOrderData() order.vtSymbol = vtSymbol order.price = price order.priceType = PRICETYPE_FOK order.totalVolume = volume order.status = STATUS_NOTTRADED # 刚提交尚未成交 order.orderID = orderID order.vtOrderID = orderID order.orderTime = str(self.dt) # CTA委托类型映射 if orderType == CTAORDER_BUY: order.direction = DIRECTION_LONG order.offset = OFFSET_OPEN elif orderType == CTAORDER_SELL and not self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSE elif orderType == CTAORDER_SELL and self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_SELL_TODAY: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSETODAY elif orderType == CTAORDER_SHORT: order.direction = DIRECTION_SHORT order.offset = OFFSET_OPEN elif orderType == CTAORDER_COVER and not self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSE elif orderType == CTAORDER_COVER and self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_COVER_TODAY: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSETODAY # 保存到限价单字典中 if vtSymbol == strategy.vtSymbol: self.workingLimitOrderDict[orderID] = order self.limitOrderDict[orderID] = order elif vtSymbol == strategy.vtSymbol1: self.workingLimitOrderDict1[orderID] = order self.limitOrderDict1[orderID] = order return orderID # ---------------------------------------------------------------------- def cancelOrder(self, vtOrderID): """撤单""" # 找到订单 if vtOrderID in self.workingLimitOrderDict: order = self.workingLimitOrderDict[vtOrderID] elif vtOrderID in self.workingLimitOrderDict1: order = self.workingLimitOrderDict1[vtOrderID] else: order = None return False # 委托回报 if order.status == STATUS_NOTTRADED: order.status = STATUS_CANCELLED order.cancelTime = str(self.dt) self.strategy.onOrder(order) else: order.status = STATUS_PARTTRADED_PARTCANCELLED order.cancelTime = str(self.dt) self.strategy.onOrder(order) # 删除数据 if vtOrderID in self.workingLimitOrderDict: self.removeOrder(vtOrderID) elif vtOrderID in self.workingLimitOrderDict1: self.removeOrder1(vtOrderID) return True # ---------------------------------------------------------------------- def sendStopOrder(self, vtSymbol, orderType, price, volume, strategy): """发停止单(本地实现)""" self.stopOrderCount += 1 stopOrderID = STOPORDERPREFIX + str(self.stopOrderCount) so = StopOrder() so.vtSymbol = vtSymbol so.price = price so.volume = volume so.strategy = strategy so.stopOrderID = stopOrderID so.status = STOPORDER_WAITING if orderType == CTAORDER_BUY: so.direction = DIRECTION_LONG so.offset = OFFSET_OPEN elif orderType == CTAORDER_SELL: so.direction = DIRECTION_SHORT so.offset = OFFSET_CLOSE elif orderType == CTAORDER_SHORT: so.direction = DIRECTION_SHORT so.offset = OFFSET_OPEN elif orderType == CTAORDER_COVER: so.direction = DIRECTION_LONG so.offset = OFFSET_CLOSE # 保存stopOrder对象到字典中 self.stopOrderDict[stopOrderID] = so self.workingStopOrderDict[stopOrderID] = so return stopOrderID # ---------------------------------------------------------------------- def cancelStopOrder(self, stopOrderID): """撤销停止单""" # 检查停止单是否存在 if stopOrderID in self.workingStopOrderDict: so = self.workingStopOrderDict[stopOrderID] so.status = STOPORDER_CANCELLED del self.workingStopOrderDict[stopOrderID] # ---------------------------------------------------------------------- def filterTradeTime(self): """过滤非交易时间""" if self.dt: hour = self.dt.hour # 丢弃非交易时间错误数据 if (hour >= 15 and hour < 20) or (hour >= 2 and hour < 8): return True # 清空隔交易日订单 elif hour == 8: self.lasttick = None self.lasttick1 = None for orderID in self.workingLimitOrderDict: self.cancelOrder(orderID) for orderID in self.workingLimitOrderDict1: self.cancelOrder(orderID) return True elif hour == 20: self.lasttick = None self.lasttick1 = None for orderID in self.workingLimitOrderDict: self.cancelOrder(orderID) for orderID in self.workingLimitOrderDict1: self.cancelOrder(orderID) return True return False # ---------------------------------------------------------------------- def calcTickVolume(self, tick, lasttick, size): """计算两边盘口的成交量""" if (not lasttick): currentVolume = tick.volume currentTurnOver = tick.turnover pOnAsk = tick.askPrice1 pOnBid = tick.bidPrice1 else: currentVolume = tick.volume - lasttick.volume currentTurnOver = tick.turnover - lasttick.turnover pOnAsk = lasttick.askPrice1 pOnBid = lasttick.bidPrice1 if lasttick and currentVolume > 0: currentPrice = currentTurnOver / currentVolume / size ratio = (currentPrice - lasttick.bidPrice1) / (lasttick.askPrice1 - lasttick.bidPrice1) ratio = max(ratio, 0) ratio = min(ratio, 1) volOnAsk = ratio * currentVolume / 2 volOnBid = (currentVolume - volOnAsk) / 2 else: volOnAsk = 0 volOnBid = 0 return volOnBid, volOnAsk, pOnBid, pOnAsk # ---------------------------------------------------------------------- def removeOrder(self, orderID): """清除订单信息""" del self.workingLimitOrderDict[orderID] if orderID in self.orderPrice: del self.orderPrice[orderID] if orderID in self.orderVolume: del self.orderVolume[orderID] # ---------------------------------------------------------------------- def removeOrder1(self, orderID): """清除订单信息""" del self.workingLimitOrderDict1[orderID] if orderID in self.orderPrice1: del self.orderPrice1[orderID] if orderID in self.orderVolume1: del self.orderVolume1[orderID] # ---------------------------------------------------------------------- def snapMarket(self, tradeID): """快照市场""" if self.mode == self.TICK_MODE: self.tradeSnap[tradeID] = copy.copy(self.tick) self.tradeSnap1[tradeID] = copy.copy(self.tick1) else: self.tradeSnap[tradeID] = copy.copy(self.bar) self.tradeSnap1[tradeID] = copy.copy(self.bar1) # ---------------------------------------------------------------------- def strategyOnTrade(self, order, volumeTraded, priceTraded): """处理成交回报""" # 推送成交数据, self.tradeCount += 1 tradeID = str(self.tradeCount) trade = VtTradeData() # 省略回测无关内容 # trade.tradeID = tradeID # trade.vtTradeID = tradeID # trade.orderID = order.orderID # trade.vtOrderID = order.orderID trade.dt = self.dt trade.vtSymbol = order.vtSymbol trade.direction = order.direction trade.offset = order.offset trade.tradeTime = self.dt.strftime('%Y%m%d %H:%M:%S.') + self.dt.strftime('%f')[:1] trade.volume = volumeTraded trade.price = priceTraded self.strategy.onTrade(copy.copy(trade)) # 快照市场,用于计算持仓盈亏,暂不支持 # self.snapMarket(tradeID) if trade.vtSymbol == self.strategy.vtSymbol: self.tradeDict[tradeID] = trade else: self.tradeDict1[tradeID] = trade # ---------------------------------------------------------------------- def crossLimitOrder(self): """基于最新数据撮合限价单""" # 缓存数据 tick = self.tick lasttick = self.lasttick bar = self.bar # 过滤数据 if self.filterTradeTime(): return # 确定撮合价格 if self.mode == self.BAR_MODE: # Bar价格撮合,目前不支持FokopenFak buyCrossPrice = bar.low # 若买入方向限价单价格高于该价格,则会成交 sellCrossPrice = bar.high # 若卖出方向限价单价格低于该价格,则会成交 else: # Tick采用对价撮合,支持Fok,Fak buyCrossPrice = tick.askPrice1 if tick.askPrice1 > 0 else tick.bidPrice1 + self.mPrice sellCrossPrice = tick.bidPrice1 if tick.bidPrice1 > 0 else tick.askPrice1 - self.mPrice # 遍历限价单字典中的所有限价单 for orderID, order in self.workingLimitOrderDict.items(): # 判断是否会成交 buyCross = order.direction == DIRECTION_LONG and order.price >= buyCrossPrice sellCross = order.direction == DIRECTION_SHORT and order.price <= sellCrossPrice # 如果可以对价撮合 if buyCross or sellCross: # 计算成交量 volumeTraded = (order.totalVolume - order.tradedVolume) if self.mode == self.TICK_MODE: volumeTraded = min(volumeTraded, tick.askVolume1) if buyCross \ else min(volumeTraded, tick.bidVolume1) volumeTraded = max(volumeTraded, 1) # 计算成交价 if orderID in self.orderPrice and order.tradedVolume == 0: priceTraded = order.price else: priceTraded = min(order.price, buyCrossPrice) if buyCross \ else max(order.price, sellCrossPrice) # 推送委托数据 order.tradedVolume += volumeTraded # 分别处理普通限价,FOK,FAK订单 if order.priceType == PRICETYPE_FOK: if order.tradedVolume < order.totalVolume: order.status = STATUS_CANCELLED volumeTraded = 0 else: order.status = STATUS_ALLTRADED elif order.priceType == PRICETYPE_FAK: if order.tradedVolume < order.totalVolume: order.status = STATUS_PARTTRADED_PARTCANCELLED else: order.status = STATUS_ALLTRADED else: if order.tradedVolume < order.totalVolume: order.status = STATUS_PARTTRADED self.orderPrice[orderID] = order.price self.orderVolume[orderID] = 0 else: order.status = STATUS_ALLTRADED # 推送委托回报 self.strategy.onOrder(order) # 推送成交回报 if volumeTraded > 0: self.strategyOnTrade(order, volumeTraded, priceTraded) # 处理完毕,删除数据 if not order.status == STATUS_PARTTRADED: self.removeOrder(orderID) # 模拟排队撮合部分,TICK模式有效(使用Tick内成交均价简单估计两边盘口的成交量) elif self.mode == self.TICK_MODE and not self.fast: # 计算估计的两边盘口的成交量 volOnBid, volOnAsk, pOnBid, pOnAsk = self.calcTickVolume(tick, lasttick, self.size) # 排队队列维护 if orderID in self.orderPrice: # 非首次进入队列 if orderID not in self.orderVolume: if order.price == sellCrossPrice and order.direction == DIRECTION_LONG: self.orderVolume[orderID] = tick.bidVolume1 elif order.price == buyCrossPrice and order.direction == DIRECTION_SHORT: self.orderVolume[orderID] = tick.askVolume1 # 首先排队进入,然后被打穿(不允许直接在买卖盘中间成交) elif order.price > sellCrossPrice and order.direction == DIRECTION_LONG: self.orderVolume[orderID] = 0 elif order.price < buyCrossPrice and order.direction == DIRECTION_SHORT: self.orderVolume[orderID] = 0 # 更新排队值 elif order.price == pOnBid and order.direction == DIRECTION_LONG: self.orderVolume[orderID] -= volOnBid elif order.price == pOnAsk and order.direction == DIRECTION_SHORT: self.orderVolume[orderID] -= volOnAsk else: # 首次进入队列 self.orderPrice[orderID] = order.price if order.direction == DIRECTION_SHORT and order.price == tick.askPrice1: self.orderVolume[orderID] = tick.askVolume1 elif order.direction == DIRECTION_LONG and order.price == tick.bidPrice1: self.orderVolume[orderID] = tick.bidVolume1 # 排队成交,注意,目前简单一次性全部成交!! if orderID in self.orderVolume and self.orderVolume[orderID] <= 0: # 推送委托数据 priceTraded = order.price volumeTraded = order.totalVolume - order.tradedVolume order.tradedVolume = order.totalVolume order.status = STATUS_ALLTRADED self.strategy.onOrder(order) # 推送成交回报 self.strategyOnTrade(order, volumeTraded, priceTraded) # 从字典中删除该限价单 self.removeOrder(orderID) else: order.tradedVolume = 0 order.status = STATUS_NOTTRADED if order.priceType == PRICETYPE_FOK or order.priceType == PRICETYPE_FAK: order.status = STATUS_CANCELLED self.removeOrder(orderID) self.strategy.onOrder(order) # ---------------------------------------------------------------------- def crossLimitOrder1(self): """基于最新数据撮合限价单""" # 缓存数据 lasttick1 = self.lasttick1 tick1 = self.tick1 bar1 = self.bar1 if self.filterTradeTime(): return # 区分K线撮合和TICK撮合模式 if self.mode == self.BAR_MODE: buyCrossPrice = bar1.low # 若买入方向限价单价格高于该价格,则会成交 sellCrossPrice = bar1.high # 若卖出方向限价单价格低于该价格,则会成交 else: # TICK对价撮合,并过滤涨跌停板 buyCrossPrice = tick1.askPrice1 if tick1.askPrice1 > 0 else tick1.bidPrice1 + self.mPrice1 sellCrossPrice = tick1.bidPrice1 if tick1.bidPrice1 > 0 else tick1.askPrice1 - self.mPrice1 # 遍历限价单字典中的所有限价单 for orderID, order in self.workingLimitOrderDict1.items(): # 判断是否对价直接成交 buyCross = order.direction == DIRECTION_LONG and order.price >= buyCrossPrice sellCross = order.direction == DIRECTION_SHORT and order.price <= sellCrossPrice # 如果直接对价成交 if buyCross or sellCross: # 计算成交量 volumeTraded = (order.totalVolume - order.tradedVolume) if self.mode == self.TICK_MODE: volumeTraded = min(volumeTraded, tick1.askVolume1) if buyCross \ else min(volumeTraded, tick1.bidVolume1) volumeTraded = max(volumeTraded, 1) # 计算成交价 if orderID in self.orderPrice1 and order.tradedVolume == 0: priceTraded = order.price else: priceTraded = min(order.price, buyCrossPrice) if buyCross else max(order.price, sellCrossPrice) # 委托回报,区分普通限价单,FOK,FAK order.tradedVolume += volumeTraded if order.priceType == PRICETYPE_FOK: if order.tradedVolume < order.totalVolume: order.status = STATUS_CANCELLED volumeTraded = 0 else: order.status = STATUS_ALLTRADED elif order.priceType == PRICETYPE_FAK: if order.tradedVolume < order.totalVolume: order.status = STATUS_PARTTRADED_PARTCANCELLED else: order.status = STATUS_ALLTRADED else: if order.tradedVolume < order.totalVolume: order.status = STATUS_PARTTRADED self.orderPrice1[orderID] = order.price self.orderVolume1[orderID] = 0 else: order.status = STATUS_ALLTRADED # 推送委托回报 self.strategy.onOrder(order) # 推送成交回报 if volumeTraded > 0: self.strategyOnTrade(order, volumeTraded, priceTraded) # 清除订单信息 if not order.status == STATUS_PARTTRADED: self.removeOrder1(orderID) # 模拟排队撮合部分,只在TICK模式有效 elif self.mode == self.TICK_MODE and not self.fast: # 计算两边盘口的成交量 volOnBid, volOnAsk, pOnBid, pOnAsk = self.calcTickVolume(tick1, lasttick1, self.size1) # 排队队列维护 if orderID in self.orderPrice1: # 非首次进入队列 if orderID not in self.orderVolume1: if order.price == sellCrossPrice and order.direction == DIRECTION_LONG: self.orderVolume1[orderID] = tick1.bidVolume1 elif order.price == buyCrossPrice and order.direction == DIRECTION_SHORT: self.orderVolume1[orderID] = tick1.askVolume1 # 首先排队进入,然后被打穿(不允许直接在买卖盘中间成交) elif order.price > sellCrossPrice and order.direction == DIRECTION_LONG: self.orderVolume1[orderID] = 0 elif order.price < buyCrossPrice and order.direction == DIRECTION_SHORT: self.orderVolume1[orderID] = 0 # 更新排队值 elif order.price == pOnBid and order.direction == DIRECTION_LONG: self.orderVolume1[orderID] -= volOnBid elif order.price == pOnAsk and order.direction == DIRECTION_SHORT: self.orderVolume1[orderID] -= volOnAsk else: # 首次进入队列 self.orderPrice1[orderID] = order.price if order.direction == DIRECTION_SHORT and order.price == tick1.askPrice1: self.orderVolume1[orderID] = tick1.askVolume1 elif order.direction == DIRECTION_LONG and order.price == tick1.bidPrice1: self.orderVolume1[orderID] = tick1.bidVolume1 # 排队成功,注意,目前模拟为一次性成交所有订单量!! if orderID in self.orderVolume1 and self.orderVolume1[orderID] <= 0: # 推送委托数据 priceTraded = order.price volumeTraded = order.totalVolume - order.tradedVolume order.tradedVolume = order.totalVolume order.status = STATUS_ALLTRADED self.strategy.onOrder(order) # 推送成交回报 self.strategyOnTrade(order, volumeTraded, priceTraded) # 从字典中删除该限价单 self.removeOrder1(orderID) else: order.tradedVolume = 0 order.status = STATUS_NOTTRADED if order.priceType == PRICETYPE_FOK or order.priceType == PRICETYPE_FAK: order.status = STATUS_CANCELLED self.removeOrder1(orderID) self.strategy.onOrder(order) # ---------------------------------------------------------------------- def crossBarLimitOrder(self): """基于最新数据撮合限价单""" # 先确定会撮合成交的价格 if self.mode == self.BAR_MODE: buyCrossPrice = self.bar.low # 若买入方向限价单价格高于该价格,则会成交 sellCrossPrice = self.bar.high # 若卖出方向限价单价格低于该价格,则会成交 buyBestCrossPrice = self.bar.open # 在当前时间点前发出的买入委托可能的最优成交价 sellBestCrossPrice = self.bar.open # 在当前时间点前发出的卖出委托可能的最优成交价 else: buyCrossPrice = self.tick.askPrice1 sellCrossPrice = self.tick.bidPrice1 buyBestCrossPrice = self.tick.askPrice1 sellBestCrossPrice = self.tick.bidPrice1 # 遍历限价单字典中的所有限价单 for orderID, order in self.workingLimitOrderDict.items(): # 判断是否会成交 buyCross = order.direction == DIRECTION_LONG and order.price >= buyCrossPrice sellCross = order.direction == DIRECTION_SHORT and order.price <= sellCrossPrice # 如果发生了成交 if buyCross or sellCross: # 推送成交数据 self.tradeCount += 1 # 成交编号自增1 tradeID = str(self.tradeCount) trade = VtTradeData() trade.vtSymbol = order.vtSymbol trade.tradeID = tradeID trade.vtTradeID = tradeID trade.orderID = order.orderID trade.vtOrderID = order.orderID trade.direction = order.direction trade.offset = order.offset # 以买入为例: # 1. 假设当根K线的OHLC分别为:100, 125, 90, 110 # 2. 假设在上一根K线结束(也是当前K线开始)的时刻,策略发出的委托为限价105 # 3. 则在实际中的成交价会是100而不是105,因为委托发出时市场的最优价格是100 if buyCross: trade.price = min(order.price, buyBestCrossPrice) self.strategy.pos += order.totalVolume else: trade.price = max(order.price, sellBestCrossPrice) self.strategy.pos -= order.totalVolume trade.volume = order.totalVolume trade.tradeTime = str(self.dt) trade.dt = self.dt self.strategy.onTrade(trade) self.tradeDict[tradeID] = trade # 推送委托数据 order.tradedVolume = order.totalVolume order.status = STATUS_ALLTRADED self.strategy.onOrder(order) # 从字典中删除该限价单 del self.workingLimitOrderDict[orderID] # ---------------------------------------------------------------------- def crossBarLimitOrder1(self): """基于最新数据撮合限价单""" # 先确定会撮合成交的价格 if self.mode == self.BAR_MODE: buyCrossPrice = self.bar.low # 若买入方向限价单价格高于该价格,则会成交 sellCrossPrice = self.bar.high # 若卖出方向限价单价格低于该价格,则会成交 buyBestCrossPrice = self.bar.open # 在当前时间点前发出的买入委托可能的最优成交价 sellBestCrossPrice = self.bar.open # 在当前时间点前发出的卖出委托可能的最优成交价 else: buyCrossPrice = self.tick.askPrice1 sellCrossPrice = self.tick.bidPrice1 buyBestCrossPrice = self.tick.askPrice1 sellBestCrossPrice = self.tick.bidPrice1 # 遍历限价单字典中的所有限价单 for orderID, order in self.workingLimitOrderDict.items(): # 判断是否会成交 buyCross = order.direction == DIRECTION_LONG and order.price >= buyCrossPrice sellCross = order.direction == DIRECTION_SHORT and order.price <= sellCrossPrice # 如果发生了成交 if buyCross or sellCross: # 推送成交数据 self.tradeCount += 1 # 成交编号自增1 tradeID = str(self.tradeCount) trade = VtTradeData() trade.vtSymbol = order.vtSymbol trade.tradeID = tradeID trade.vtTradeID = tradeID trade.orderID = order.orderID trade.vtOrderID = order.orderID trade.direction = order.direction trade.offset = order.offset # 以买入为例: # 1. 假设当根K线的OHLC分别为:100, 125, 90, 110 # 2. 假设在上一根K线结束(也是当前K线开始)的时刻,策略发出的委托为限价105 # 3. 则在实际中的成交价会是100而不是105,因为委托发出时市场的最优价格是100 if buyCross: trade.price = min(order.price, buyBestCrossPrice) self.strategy.pos += order.totalVolume else: trade.price = max(order.price, sellBestCrossPrice) self.strategy.pos -= order.totalVolume trade.volume = order.totalVolume trade.tradeTime = str(self.dt) trade.dt = self.dt self.strategy.onTrade(trade) self.tradeDict1[tradeID] = trade # 推送委托数据 order.tradedVolume = order.totalVolume order.status = STATUS_ALLTRADED self.strategy.onOrder(order) # 从字典中删除该限价单 del self.workingLimitOrderDict[orderID] # ---------------------------------------------------------------------- def crossStopOrder(self): """基于最新数据撮合停止单""" # 停止单撮合未更新 # 先确定会撮合成交的价格,这里和限价单规则相反 if self.mode == self.BAR_MODE: buyCrossPrice = self.bar.high # 若买入方向停止单价格低于该价格,则会成交 sellCrossPrice = self.bar.low # 若卖出方向限价单价格高于该价格,则会成交 bestCrossPrice = self.bar.open # 最优成交价,买入停止单不能低于,卖出停止单不能高于 else: buyCrossPrice = self.tick.lastPrice sellCrossPrice = self.tick.lastPrice bestCrossPrice = self.tick.lastPrice # 遍历停止单字典中的所有停止单 for stopOrderID, so in self.workingStopOrderDict.items(): # 判断是否会成交 buyCross = so.direction == DIRECTION_LONG and so.price <= buyCrossPrice sellCross = so.direction == DIRECTION_SHORT and so.price >= sellCrossPrice # 如果发生了成交 if buyCross or sellCross: # 推送成交数据 self.tradeCount += 1 tradeID = str(self.tradeCount) trade = VtTradeData() trade.vtSymbol = so.vtSymbol trade.tradeID = tradeID trade.vtTradeID = tradeID if buyCross: trade.price = max(bestCrossPrice, so.price) else: trade.price = min(bestCrossPrice, so.price) self.limitOrderCount += 1 orderID = str(self.limitOrderCount) trade.orderID = orderID trade.vtOrderID = orderID trade.direction = so.direction trade.offset = so.offset trade.volume = so.volume trade.tradeTime = self.dt.strftime('%Y%m%d %H:%M:%S.') + self.dt.strftime('%f')[:1] trade.dt = self.dt self.strategy.onTrade(copy.copy(trade)) self.tradeDict[tradeID] = trade self.tradeDict1[tradeID] = trade # 推送委托数据 so.status = STOPORDER_TRIGGERED order = VtOrderData() order.vtSymbol = so.vtSymbol order.symbol = so.vtSymbol order.orderID = orderID order.vtOrderID = orderID order.direction = so.direction order.offset = so.offset order.price = so.price order.totalVolume = so.volume order.tradedVolume = so.volume order.status = STATUS_ALLTRADED order.orderTime = trade.tradeTime self.strategy.onOrder(order) self.limitOrderDict[orderID] = order # 从字典中删除该限价单 del self.workingStopOrderDict[stopOrderID] # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- def insertData(self, dbName, collectionName, data): """考虑到回测中不允许向数据库插入数据,防止实盘交易中的一些代码出错""" pass # ---------------------------------------------------------------------- def writeCtaLog(self, content): """记录日志""" log = str(self.dt) + ' ' + content self.logList.append(log) # ---------------------------------------------------------------------- def output(self, content): """输出内容""" if not self.plot: return if self.plotfile: print content.encode('utf8') else: print content # ---------------------------------------------------------------------- def makeRecord(self, tradeTime, offset, direction, price, pnl): """记录成交内容""" resDict = {} resDict[u'datetime'] = tradeTime resDict[u'price'] = price resDict[u'contract0'] = self.strategy.vtSymbol resDict[u'contract1'] = self.strategy.vtSymbol resDict[u'offset'] = offset resDict[u'direction'] = direction resDict[u'pnl'] = pnl if self.strategy.vtSymbol1: resDict[u'contract1'] = self.strategy.vtSymbol1 return resDict # ---------------------------------------------------------------------- def calculateBacktestingResult(self, detial=False): """ 计算回测结果 """ self.output(u'按逐笔对冲计算回测结果') # 首先基于回测后的成交记录,计算每笔交易的盈亏 pnlDict = OrderedDict() # 每笔盈亏的记录 longTrade = deque([]) # 未平仓的多头交易 shortTrade = deque([]) # 未平仓的空头交易 longTrade1 = deque([]) # 合约2未平仓的多头交易 shortTrade1 = deque([]) # 合约2未平仓的空头交易 resList = [{"name": self.strategy.name}] # 计算滑点,一个来回包括两次 totalSlippage = self.slippage * 2 self.output(u'总交易量 : ' + str(len(self.tradeDict))) self.output(u'总交易量1 : ' + str(len(self.tradeDict1))) leg2 = True if self.tradeDict.values(): dict_trade = self.tradeDict.values() else: dict_trade = self.tradeDict1.values() leg2 = False if self.tradeDict1.values(): dict_trade1 = self.tradeDict1.values() else: dict_trade1 = self.tradeDict.values() leg2 = False for trade1 in dict_trade1: # 多头交易 if trade1.direction == DIRECTION_LONG: # 当前多头交易为平空 untraded = True while (shortTrade1 and untraded): entryTrade = shortTrade1[0] exitTrade = trade1 volume = min(entryTrade.volume, exitTrade.volume) entryTrade.volume = entryTrade.volume - volume exitTrade.volume = exitTrade.volume - volume if entryTrade.volume == 0: shortTrade1.popleft() if exitTrade.volume == 0: untraded = False if exitTrade.dt not in pnlDict: pnlDict[exitTrade.dt] = TradingResult(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, -volume, self.rate1, self.slippage1, self.size1) elif leg2: pnlDict[exitTrade.dt].add(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, -volume, self.rate1, self.slippage1, self.size1) if exitTrade.dt in pnlDict and leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL1(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) elif not leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL1(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) # 如果尚无空头交易 if untraded: longTrade1.append(trade1) # 空头交易 else: # 当前空头交易为平多 untraded = True while (untraded and longTrade1): entryTrade = longTrade1[0] exitTrade = trade1 volume = min(entryTrade.volume, exitTrade.volume) entryTrade.volume = entryTrade.volume - volume exitTrade.volume = exitTrade.volume - volume if entryTrade.volume == 0: longTrade1.popleft() if exitTrade.volume == 0: untraded = False if exitTrade.dt not in pnlDict: pnlDict[exitTrade.dt] = TradingResult(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, volume, self.rate1, self.slippage1, self.size1) elif leg2: pnlDict[exitTrade.dt].add(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, volume, self.rate1, self.slippage1, self.size1) if exitTrade.dt in pnlDict and leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL1(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) elif not leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL1(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) # 如果尚无多头交易 if untraded: shortTrade1.append(trade1) for trade in dict_trade: # 多头交易 if trade.direction == DIRECTION_LONG: # 当前多头交易为平空 untraded = True while (shortTrade and untraded): entryTrade = shortTrade[0] exitTrade = trade # 计算比例佣金 volume = min(entryTrade.volume, exitTrade.volume) entryTrade.volume = entryTrade.volume - volume exitTrade.volume = exitTrade.volume - volume if entryTrade.volume == 0: shortTrade.popleft() if exitTrade.volume == 0: untraded = False if exitTrade.dt not in pnlDict: pnlDict[exitTrade.dt] = TradingResult(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, -volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTrade.dt].add(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, -volume, self.rate, self.slippage, self.size) if exitTrade.dt in pnlDict and leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) elif not leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) pnl = pnlDict[exitTrade.dt].pnl # 记录用来可视化的成交内容 resDict = self.makeRecord(entryTrade.tradeTime, u'开', u'卖', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(exitTrade.tradeTime, u'平', u'买', exitTrade.price, pnl) resList.append(resDict) # 如果尚无空头交易 if untraded: longTrade.append(trade) # 空头交易 else: # 当前空头交易为平多 untraded = True while (longTrade and untraded): entryTrade = longTrade[0] exitTrade = trade # 计算比例佣金 volume = min(entryTrade.volume, exitTrade.volume) entryTrade.volume = entryTrade.volume - volume exitTrade.volume = exitTrade.volume - volume if entryTrade.volume == 0: longTrade.popleft() if exitTrade.volume == 0: untraded = False if exitTrade.dt not in pnlDict: pnlDict[exitTrade.dt] = TradingResult(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTrade.dt].add(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, volume, self.rate, self.slippage, self.size) if exitTrade.dt in pnlDict and leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) elif not leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) pnl = pnlDict[exitTrade.dt].pnl # 记录用来可视化的成交内容 resDict = self.makeRecord(entryTrade.tradeTime, u'开', u'买', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(exitTrade.tradeTime, u'平', u'卖', exitTrade.price, pnl) resList.append(resDict) # 如果尚无多头交易 if untraded: shortTrade.append(trade) # 计算剩余持仓盈亏 while (shortTrade): entryTrade = shortTrade.popleft() volume = entryTrade.volume if self.mode == self.TICK_MODE: exitTime = self.tick.datetime exitPrice = self.tick.askPrice1 else: exitTime = self.bar.datetime exitPrice = self.bar.close if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) pnl = pnlDict[exitTime].pnl elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) pnl = pnlDict[exitTime].pnl # 记录用来可视化的成交内容 resDict = self.makeRecord(entryTrade.tradeTime, u'开持', u'卖', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(str(exitTime), u'平持', u'买', exitPrice, pnl) resList.append(resDict) while (longTrade): entryTrade = longTrade.popleft() volume = entryTrade.volume if self.mode == self.TICK_MODE: exitTime = self.tick.datetime exitPrice = self.tick.bidPrice1 else: exitTime = self.bar.datetime exitPrice = self.bar.close if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) pnl = pnlDict[exitTime].pnl elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) pnl = pnlDict[exitTime].pnl # 记录用来可视化的成交内容 resDict = self.makeRecord(entryTrade.tradeTime, u'开持', u'买', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(str(exitTime), u'平持', u'卖', exitPrice, pnl) resList.append(resDict) while (leg2 and shortTrade1): entryTrade = shortTrade1.popleft() volume = entryTrade.volume if self.mode == self.TICK_MODE: exitTime = self.tick1.datetime exitPrice = self.tick1.askPrice1 else: exitTime = self.bar1.datetime exitPrice = self.bar1.close if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) pnl = pnlDict[exitTime].pnl else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) pnl = pnlDict[exitTime].pnl # 记录用来可视化的成交内容 resDict = self.makeRecord(entryTrade.tradeTime, u'开持', u'卖', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(str(exitTime), u'平持', u'买', exitPrice, pnl) resList.append(resDict) while (leg2 and longTrade1): entryTrade = longTrade1.popleft() volume = entryTrade.volume if self.mode == self.TICK_MODE: exitTime = self.tick1.datetime exitPrice = self.tick1.bidPrice1 else: exitTime = self.bar.datetime exitPrice = self.bar.close if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) pnl = pnlDict[exitTime].pnl # 记录用来可视化的成交内容 resDict = self.makeRecord(entryTrade.tradeTime, u'开持', u'买', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(exitTime, u'平持', u'卖', exitPrice, pnl) resList.append(resDict) # 由于双合约的问题,需要整理时间序列和结果序列 timeList = [] # 时间序列 resultList = [] # 交易结果序列 pnlDict0 = sorted(pnlDict.iteritems(), key=lambda d: d[0]) for k, v in pnlDict0: timeList.append(k) resultList.append(v) # 然后基于每笔交易的结果,我们可以计算具体的盈亏曲线和最大回撤等 timeList = [] # 时间序列 pnlList = [] # 每笔盈亏序列 capital = 0 # 资金 maxCapital = 0 # 资金最高净值 drawdown = 0 # 回撤 totalResult = 0 # 总成交数量 totalTurnover = 0 # 总成交金额(合约面值) totalCommission = 0 # 总手续费 totalSlippage = 0 # 总滑点 capitalList = [] # 盈亏汇总的时间序列 drawdownList = [] # 回撤的时间序列 winningResult = 0 # 盈利次数 losingResult = 0 # 亏损次数 totalWinning = 0 # 总盈利金额 totalLosing = 0 # 总亏损金额 for result in resultList: capital += result.pnl maxCapital = max(capital + result.posPnl, maxCapital) drawdown = round(capital + result.posPnl - maxCapital, 2) pnlList.append(result.pnl) timeList.append(result.exitDt) # 交易的时间戳使用平仓时间 capitalList.append(capital + result.posPnl) drawdownList.append(drawdown) totalResult += 1 totalTurnover += result.turnover totalCommission += result.commission totalSlippage += result.slippage if result.pnl >= 0: winningResult += 1 totalWinning += result.pnl else: losingResult += 1 totalLosing += result.pnl # 计算盈亏相关数据 if totalResult: winningRate = winningResult * 1.0 / totalResult * 100 # 胜率 else: winningRate = 0 averageWinning = 0 # 这里把数据都初始化为0 averageLosing = 0 profitLossRatio = 0 if winningResult: averageWinning = totalWinning / winningResult # 平均每笔盈利 else: averageWinning = 0 if losingResult: averageLosing = totalLosing / losingResult # 平均每笔亏损 else: averageLosing = 0 if averageLosing: profitLossRatio = -averageWinning / averageLosing # 盈亏比 else: profitLossRatio = 0 # 返回回测结果 d = {} d['capital'] = capital d['maxCapital'] = maxCapital d['drawdown'] = drawdown d['totalResult'] = totalResult d['totalTurnover'] = totalTurnover d['totalCommission'] = totalCommission d['totalSlippage'] = totalSlippage d['timeList'] = timeList d['pnlList'] = pnlList d['capitalList'] = capitalList d['drawdownList'] = drawdownList d['winningRate'] = winningRate d['averageWinning'] = averageWinning d['averageLosing'] = averageLosing d['profitLossRatio'] = profitLossRatio d['resList'] = resList return d # ---------------------------------------------------------------------- def calcPosPNL(self, tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2): """ 根据市场快照,计算每笔成交时间的持仓盈亏(按对价结算并扣除了手续费和滑点) """ # 判断是否有持仓,加快无持仓策略的计算速度 return 0 allPos0 = len(shortTrade) + len(longTrade) if allPos0 == 0: return 0 pnlDict = OrderedDict() # 每笔盈亏的记录 if tradeID in self.tradeSnap: tick = self.tradeSnap[tradeID] # 主合约行情 tick1 = self.tradeSnap1[tradeID] # 副合约行情 elif tradeID in self.trade1Snap: tick = self.trade1Snap[tradeID] # 主合约行情 tick1 = self.trade1Snap1[tradeID] # 副合约行情 else: tick = self.tradeSnap[tradeID] # 主合约行情 tick1 = self.tradeSnap1[tradeID] # 副合约行情 for entryTrade in shortTrade: volume = entryTrade.volume exitTime = tick.datetime exitPrice = tick.askPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) for entryTrade in longTrade: volume = entryTrade.volume exitTime = tick.datetime exitPrice = tick.bidPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) for entryTrade in shortTrade1: volume = entryTrade.volume exitTime = tick1.datetime exitPrice = tick1.askPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) for entryTrade in longTrade1: volume = entryTrade.volume exitTime = tick1.datetime exitPrice = tick1.bidPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) result = 0 for v in pnlDict.values(): result += v.pnl return result # ---------------------------------------------------------------------- def calcPosPNL1(self, tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2): """ 根据市场快照,计算每笔成交时间的持仓盈亏(按对价结算并扣除了手续费和滑点) """ return 0 # 判断是否有持仓,加快无持仓策略的计算速度 allPos1 = len(shortTrade1) + len(longTrade1) if allPos1 == 0: return 0 pnlDict = OrderedDict() # 每笔盈亏的记录 if tradeID in self.trade1Snap: tick = self.trade1Snap[tradeID] # 主合约行情 tick1 = self.trade1Snap1[tradeID] # 副合约行情 elif tradeID in self.tradeSnap: tick = self.tradeSnap[tradeID] # 主合约行情 tick1 = self.tradeSnap1[tradeID] # 副合约行情 else: return 0 for entryTrade in shortTrade: volume = entryTrade.volume exitTime = tick.datetime exitPrice = tick.askPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) for entryTrade in longTrade: volume = entryTrade.volume exitTime = tick.datetime exitPrice = tick.bidPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) for entryTrade in shortTrade1: volume = entryTrade.volume exitTime = tick1.datetime exitPrice = tick1.askPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) for entryTrade in longTrade1: volume = entryTrade.volume exitTime = tick1.datetime exitPrice = tick1.bidPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) result = 0 for v in pnlDict.values(): result += v.pnl return result # ---------------------------------------------------------------------- def showBacktestingResult(self): """ 显示回测结果 """ d = self.calculateBacktestingResult() timeList = d['timeList'] pnlList = d['pnlList'] capitalList = d['capitalList'] drawdownList = d['drawdownList'] resList = d['resList'] self.output(u' ') self.output('-' * 30) self.output(u'显示回测结果') # 输出 if len(resList) > 1: import codecs if os.path.exists('./ctaStrategy/opResults/'): filepath = './ctaStrategy/opResults/' else: filepath = './opResults/' settingFileName = filepath + self.strategy.name + '.json' f = codecs.open(settingFileName, 'w', 'utf-8') f.write(json.dumps(resList, indent=1, ensure_ascii=False)) f.close() if len(timeList) > 0: self.output(u'第一笔交易:\t%s' % d['timeList'][0]) self.output(u'最后一笔交易:\t%s' % d['timeList'][-1]) self.output(u'总交易次数:\t%s' % formatNumber(d['totalResult'])) self.output(u'总盈亏:\t%s' % formatNumber(d['capital'])) self.output(u'最大回撤: \t%s' % formatNumber(min(d['drawdownList']))) self.output(u'平均每笔盈利:\t%s' % formatNumber(d['capital'] / d['totalResult'])) self.output(u'平均每笔滑点:\t%s' % formatNumber(d['totalSlippage'] / d['totalResult'])) self.output(u'平均每笔佣金:\t%s' % formatNumber(d['totalCommission'] / d['totalResult'])) self.output(u'胜率\t\t%s%%' % formatNumber(d['winningRate'])) self.output(u'平均每笔盈利\t%s' % formatNumber(d['averageWinning'])) self.output(u'平均每笔亏损\t%s' % formatNumber(d['averageLosing'])) self.output(u'盈亏比:\t%s' % formatNumber(d['profitLossRatio'])) # 资金曲线插入数据库 lastTime = None lastCap = 0 lastDayCap = 0 lastDraw = 0 for (time, cap, drawdown) in zip(timeList, capitalList, drawdownList): if lastTime and time.day != lastTime.day: capData = CtaCapData() capData.name = self.strategy.name capData.datetime = lastTime capData.start = self.dataStartDate capData.date = capData.datetime.replace(hour=0, minute \ =0, second=0, microsecond=0) capData.cap = lastCap capData.pnl = lastCap - lastDayCap capData.drawdown = lastDraw self.insertCap(CAPITAL_DB_NAME, self.strategy.name, capData) lastDayCap = lastCap lastTime = time lastCap = cap lastDraw = drawdown capData = CtaCapData() capData.name = self.strategy.name capData.datetime = lastTime capData.start = self.dataStartDate capData.date = capData.datetime.replace(hour=0, minute \ =0, second=0, microsecond=0) capData.cap = lastCap capData.pnl = lastCap - lastDayCap capData.drawdown = lastDraw self.insertCap(CAPITAL_DB_NAME, self.strategy.name, capData) # 绘图 import matplotlib.pyplot as plt from matplotlib.dates import AutoDateLocator, DateFormatter plt.close() autodates = AutoDateLocator() yearsFmt = DateFormatter('%m-%d') # yearsFmt = DateFormatter('%Y-%m-%d') pCapital = plt.subplot(3, 1, 1) pCapital.set_ylabel("capital") pCapital.plot(timeList, capitalList) plt.title(self.strategy.name) plt.gcf().autofmt_xdate() # 设置x轴时间外观 plt.gcf().subplots_adjust(bottom=0.1) plt.gca().xaxis.set_major_locator(autodates) # 设置时间间隔 plt.gca().xaxis.set_major_formatter(yearsFmt) # 设置时间显示格式 pDD = plt.subplot(3, 1, 2) pDD.set_ylabel("DD") pDD.bar(range(len(drawdownList)), drawdownList) pPnl = plt.subplot(3, 1, 3) pPnl.set_ylabel("pnl") pPnl.hist(pnlList, bins=20) plt.show() # ---------------------------------------------------------------------- def insertCap(self, dbName, collectionName, d): """插入数据到数据库(这里的data可以是CtaTickData或者CtaBarData)""" host, port, logging = loadMongoSetting() if not self.dbClient: self.dbClient = pymongo.MongoClient(host, port, socketKeepAlive=True) db = self.dbClient[dbName] collection = db[collectionName] collection.ensure_index([('date', pymongo.ASCENDING)], unique=True) flt = {'date': d.date} collection.update_one(flt, {'$set': d.__dict__}, upsert=True) # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- def showBacktestingResult_nograph(self, filepath): """ 显示回测结果 """ d = self.calculateBacktestingResult() timeList = d['timeList'] pnlList = d['pnlList'] capitalList = d['capitalList'] drawdownList = d['drawdownList'] self.output(u'显示回测结果') # 输出 if len(timeList) > 0: self.output('-' * 30) self.output(u'第一笔交易:\t%s' % d['timeList'][0]) self.output(u'最后一笔交易:\t%s' % d['timeList'][-1]) self.output(u'总交易次数:\t%s' % formatNumber(d['totalResult'])) self.output(u'总盈亏:\t%s' % formatNumber(d['capital'])) self.output(u'最大回撤: \t%s' % formatNumber(min(d['drawdownList']))) self.output(u'平均每笔盈利:\t%s' % formatNumber(d['capital'] / d['totalResult'])) self.output(u'平均每笔滑点:\t%s' % formatNumber(d['totalSlippage'] / d['totalResult'])) self.output(u'平均每笔佣金:\t%s' % formatNumber(d['totalCommission'] / d['totalResult'])) self.output(u'胜率\t\t%s%%' % formatNumber(d['winningRate'])) self.output(u'平均每笔盈利\t%s' % formatNumber(d['averageWinning'])) self.output(u'平均每笔亏损\t%s' % formatNumber(d['averageLosing'])) self.output(u'盈亏比:\t%s' % formatNumber(d['profitLossRatio'])) self.output(u'显示回测结果') # 资金曲线插入数据库 lastTime = None lastCap = 0 lastDayCap = 0 lastDraw = 0 for (time, cap, drawdown) in zip(timeList, capitalList, drawdownList): if lastTime and time.day != lastTime.day: capData = CtaCapData() capData.name = self.strategy.name capData.datetime = lastTime capData.start = self.dataStartDate capData.date = capData.datetime.replace(hour=0, minute \ =0, second=0, microsecond=0) capData.cap = lastCap capData.pnl = lastCap - lastDayCap capData.drawdown = lastDraw self.insertCap(CAPITAL_DB_NAME, self.strategy.name, capData) lastDayCap = lastCap lastTime = time lastCap = cap lastDraw = drawdown # 绘图 import matplotlib matplotlib.use('Qt4Agg') import matplotlib.pyplot as plt from matplotlib.dates import AutoDateLocator, DateFormatter autodates = AutoDateLocator() yearsFmt = DateFormatter('%m-%d') pCapital = plt.subplot(3, 1, 1) pCapital.set_ylabel("capital") pCapital.plot(timeList, capitalList) plt.gcf().autofmt_xdate() # 设置x轴时间外观 plt.gcf().subplots_adjust(bottom=0.1) plt.gca().xaxis.set_major_locator(autodates) # 设置时间间隔 plt.gca().xaxis.set_major_formatter(yearsFmt) # 设置时间显示格式 pDD = plt.subplot(3, 1, 2) pDD.set_ylabel("DD") pDD.bar(range(len(drawdownList)), drawdownList) pPnl = plt.subplot(3, 1, 3) pPnl.set_ylabel("pnl") pPnl.hist(pnlList, bins=20) plt.savefig(filepath) plt.close() # ---------------------------------------------------------------------- def putStrategyEvent(self, name): """发送策略更新事件,回测中忽略""" pass # ---------------------------------------------------------------------- def confSettle(self, name): """确认结算单,回测中忽略""" pass # ---------------------------------------------------------------------- def setSlippage(self, slippage): """设置滑点""" self.slippage = slippage # ---------------------------------------------------------------------- def setSlippage1(self, slippage): """设置滑点""" self.slippage1 = slippage # ---------------------------------------------------------------------- def setSize(self, size): """设置合约大小""" self.size = size # ---------------------------------------------------------------------- def setSize1(self, size): """设置合约大小""" self.size1 = size # ---------------------------------------------------------------------- def setRate(self, rate): """设置佣金比例""" self.rate = rate # ---------------------------------------------------------------------- def setRate1(self, rate): """设置佣金比例""" self.rate1 = rate # ---------------------------------------------------------------------- def setLeverage(self, leverage): """设置杠杆比率""" self.leverage = leverage # ---------------------------------------------------------------------- def setLeverage1(self, leverage): """设置杠杆比率""" self.leverage1 = leverage # ---------------------------------------------------------------------- def setPrice(self, price): """设置合约大小""" self.mPrice = price # ---------------------------------------------------------------------- def setPrice1(self, price): """设置合约大小""" self.mPrice1 = price # ---------------------------------------------------------------------- def loadTick(self, dbName, collectionName, days): """从数据库中读取Tick数据,startDate是datetime对象""" startDate = datetime.now() d = {'datetime': {'$lte': startDate}} host, port, logging = loadMongoSetting() client = pymongo.MongoClient(host, port) collection = client[dbName][collectionName] cursor = collection.find(d).limit(days * 10 * 60 * 120) l = [] if cursor: for d in cursor: tick = CtaTickData() tick.__dict__ = d l.append(tick) return l # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- def loadBar(self, dbName, collectionName, days): """从数据库中读取Bar数据,startDate是datetime对象""" startDate = datetime.now() d = {'datetime': {'$lte': startDate}} host, port, logging = loadMongoSetting() client = pymongo.MongoClient(host, port) collection = client[dbName][collectionName] cursor = collection.find(d).limit(days * 10 * 60) l = [] if cursor: for d in cursor: bar = CtaBarData() bar.__dict__ = d l.append(bar) return l # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- def runOptimization(self, strategyClass, setting_c, optimizationSetting): """串行优化""" # 获取优化设置 settingList = optimizationSetting.generateSetting() targetName = optimizationSetting.optimizeTarget # 检查参数设置问题 if not settingList or not targetName: self.output(u'优化设置有问题,请检查') vtSymbol = setting_c['vtSymbol'] if 'vtSymbol1' in setting_c: vtSymbol1 = setting_c['vtSymbol1'] else: vtSymbol1 = None # 遍历优化 resultList = [] opResults = [] for setting in settingList: self.clearBacktestingResult() self.loadHistoryData(TICK_DB_NAME, vtSymbol) if vtSymbol1: self.loadHistoryData1(TICK_DB_NAME, vtSymbol1) self.output('-' * 30) self.output('setting: %s' % str(setting)) self.initStrategy(strategyClass, setting_c) self.strategy.onUpdate(setting) self.runBacktesting() opResult = {} d = self.calculateBacktestingResult() for key in setting: opResult[key] = setting[key] opResult['totalResult'] = d['totalResult'] opResult['capital'] = d['capital'] if d['totalResult'] > 0: opResult['maxDrawdown'] = min(d['drawdownList']) opResult['winPerT'] = d['capital'] / d['totalResult'] opResult['splipPerT'] = d['totalSlippage'] / d['totalResult'] opResult['commiPerT'] = d['totalCommission'] / d['totalResult'] else: opResult['maxDrawdown'] = 0 opResult['winPerT'] = 0 opResult['splipPerT'] = 0 opResult['commiPerT'] = 0 opResult['winningRate'] = d['winningRate'] opResult['averageWinning'] = d['averageWinning'] opResult['averageLosing'] = d['averageLosing'] opResult['profitLossRatio'] = d['profitLossRatio'] try: targetValue = d[targetName] except KeyError: targetValue = 0 resultList.append(([str(setting)], targetValue)) opResults.append(opResult) # 显示结果 if os.path.exists('./ctaStrategy/opResults/'): filepath = './ctaStrategy/opResults/' else: filepath = './opResults/' with open(filepath + self.strategy.name + '.csv', 'wb') as csvfile: fieldnames = opResult.keys() writer = csv.DictWriter(csvfile, fieldnames) writer.writeheader() for opDict in opResults: writer.writerow(opDict) resultList.sort(reverse=True, key=lambda result: result[1]) self.output('-' * 30) self.output(u'优化结果:') for result in resultList: self.output(u'%s: %s' % (result[0], result[1])) return result # ---------------------------------------------------------------------- def clearBacktestingResult(self): """清空之前回测的结果""" # 交易行情相关 self.dt = None self.backtestingData = deque([]) self.backtestingData1 = deque([]) self.tick = None self.tick1 = None self.bar = None self.bar1 = None self.lasttick = None self.lasttick1 = None self.logList = [] # 日志记录 # 清空限价单相关 self.limitOrderCount = 0 self.limitOrderDict.clear() self.limitOrderDict1.clear() self.workingLimitOrderDict.clear() self.workingLimitOrderDict1.clear() self.orderPrice = {} # 限价单价格 self.orderVolume = {} # 限价单盘口 self.orderPrice1 = {} # 限价单价格 self.orderVolume1 = {} # 限价单盘口 # 清空停止单相关 self.stopOrderCount = 0 self.stopOrderDict.clear() self.workingStopOrderDict.clear() # 清空成交相关 self.tradeCount = 0 self.tradeDict.clear() self.tradeSnap.clear() self.tradeSnap1.clear() self.tradeCount1 = 0 self.tradeDict1.clear() self.trade1Snap.clear() self.trade1Snap1.clear() ######################################################################## class TradingResult(object): """每笔交易的结果""" # ---------------------------------------------------------------------- def __init__(self, entryPrice, entryDt, exitPrice, exitDt, volume, rate, slippage, size): """Constructor""" self.entryPrice = entryPrice # 开仓价格 self.exitPrice = exitPrice # 平仓价格 self.entryDt = entryDt # 开仓时间 self.exitDt = exitDt # 平仓时间 self.volume = volume # 交易数量(+/-代表方向) self.turnover = (self.entryPrice + self.exitPrice) * size * abs(volume) # 成交金额 self.commission = self.turnover * rate # 手续费成本 self.slippage = slippage * 2 * size * abs(volume) # 滑点成本 self.pnl = ((self.exitPrice - self.entryPrice) * volume * size - self.commission - self.slippage) # 净盈亏 self.posPnl = 0 # 当时持仓盈亏 # ---------------------------------------------------------------------- def add(self, entryPrice, entryDt, exitPrice, exitDt, volume, rate, slippage, size): """Constructor""" self.entryPrice = entryPrice # 开仓价格 self.exitPrice = exitPrice # 平仓价格 self.entryDt = entryDt # 开仓时间datetime self.exitDt = exitDt # 平仓时间 self.volume += volume # 交易数量(+/-代表方向) turnover = (self.entryPrice + self.exitPrice) * size * abs(volume) self.turnover += turnover # 成交金额 commission = turnover * rate self.commission += commission # 手续费成本 slippage0 = slippage * 2 * size * abs(volume) self.slippage += slippage0 # 滑点成本 self.pnl += ((self.exitPrice - self.entryPrice) * volume * size - commission - slippage0) # 净盈亏 ######################################################################## class OptimizationSetting(object): """优化设置""" # ---------------------------------------------------------------------- def __init__(self): """Constructor""" self.paramDict = OrderedDict() self.optimizeTarget = '' # 优化目标字段 # ---------------------------------------------------------------------- def addParameter(self, name, start, end, step): """增加优化参数""" if end <= start: print u'参数起始点必须小于终止点' return if step <= 0: print u'参数步进必须大于0' return l = [] param = start while param <= end: l.append(param) param += step self.paramDict[name] = l # ---------------------------------------------------------------------- def generateSetting(self): """生成优化参数组合""" # 参数名的列表 nameList = self.paramDict.keys() paramList = self.paramDict.values() # 使用迭代工具生产参数对组合 productList = list(product(*paramList)) # 把参数对组合打包到一个个字典组成的列表中 settingList = [] for p in productList: d = dict(zip(nameList, p)) settingList.append(d) return settingList # ---------------------------------------------------------------------- def setOptimizeTarget(self, target): """设置优化目标字段""" self.optimizeTarget = target # --------------------------------------------------------------------------------------- def backtesting(setting_c, StartTime='', EndTime='', slippage=0, optimism=False, mode='T'): """读取策略配置""" # from ctaSetting import STRATEGY_CLASS from strategy import STRATEGY_CLASS from ctaBacktesting1 import BacktestingEngine vtSymbol = setting_c[u'vtSymbol'] if u'vtSymbol1' in setting_c: vtSymbol1 = setting_c[u'vtSymbol1'] else: vtSymbol1 = None className = setting_c[u'className'] with open("CTA_v_setting.json") as f: l = json.load(f) for setting in l: name = setting[u'name'] match = re.search('^' + name + '[0-9]', vtSymbol) if match: slippage = setting[u'mSlippage'] rate = setting[u'mRate'] price = setting[u'mPrice'] size = setting[u'mSize'] level = setting[u'mLevel'] if vtSymbol1: match = re.search('^' + name + '[0-9]', vtSymbol1) if match: slippage1 = setting[u'mSlippage'] rate1 = setting[u'mRate'] price1 = setting[u'mPrice'] size1 = setting[u'mSize'] level1 = setting[u'mLevel'] output_s = sys.stdout sys.stderr = output_s engine = BacktestingEngine() engine.optimism = optimism # 设置引擎的回测模式, 默认为Tick dbName = TICK_DB_NAME if mode == 'T': engine.setBacktestingMode(engine.TICK_MODE) dbName = TICK_DB_NAME elif mode == 'B': engine.setBacktestingMode(engine.BAR_MODE) dbName = MINUTE_DB_NAME elif mode == 'D': engine.setBacktestingMode(engine.BAR_MODE) dbName = DAILY_DB_NAME if not StartTime: StartTime = str(setting_c[u'StartTime']) if not EndTime: EndTime = str(setting_c[u'EndTime']) # 设置回测用的数据起始日期 engine.setStartDate(StartTime) engine.setEndDate(EndTime) # 载入历史数据到引擎中 print ' ' print ('-' * 30) engine.loadHistoryData(dbName, vtSymbol) if vtSymbol1: engine.loadHistoryData1(dbName, vtSymbol1) # 设置产品相关参数 # 合约1 engine.setSlippage(slippage) # 滑点 engine.setRate(rate) # 万1.1 engine.setSize(size) # 合约大小 engine.setPrice(price) # 最小价格变动 engine.setLeverage(level) # 合约杠杆 # 合约2 if vtSymbol1: engine.setSlippage1(slippage1) # 滑点 engine.setRate1(rate1) # 万1.1 engine.setSize1(size1) # 合约大小 engine.setPrice1(price1) # 最小价格变动 engine.setLeverage1(level1) # 合约杠杆 else: engine.setSlippage1(slippage) # 滑点 engine.setRate1(rate) # 万1.1 engine.setSize1(size) # 合约大小 engine.setPrice1(price) # 最小价格变动 engine.setLeverage1(level) # 合约杠杆 engine.initStrategy(STRATEGY_CLASS[className], setting_c) engine.runBacktesting() engine.showBacktestingResult() sys.stdout = output_s # ---------------------------------------------------------------------- def runParallelOptimization(setting_c, optimizationSetting, optimism=False, startTime='', endTime='', slippage=0, mode='T'): """并行优化参数""" # 获取优化设置 global p global currentP print('-' * 30) print(u'开始优化策略 : ' + setting_c['name']) settingList = optimizationSetting.generateSetting() print(u'总共' + str(len(settingList)) + u'个优化') targetName = optimizationSetting.optimizeTarget p = ProgressBar(maxval=len(settingList)) p.start() currentP = 0 # 检查参数设置问题 if not settingList or not targetName: print(u'优化设置有问题,请检查') # 多进程优化,启动一个对应CPU核心数量的进程池 pool = multiprocessing.Pool(processes=multiprocessing.cpu_count() - 1) l = [] for setting in settingList: l.append(pool.apply_async(optimize, args=(setting_c, setting, targetName, optimism, startTime, endTime, slippage, mode), callback=showProcessBar)) pool.close() pool.join() p.finish() # 显示结果 resultList = [res.get() for res in l] # get()函数得出每个返回结果的值 print('-' * 30) print(u'优化结果:') if os.path.exists('./strategy/opResults/'): filepath = './strategy/opResults/' else: filepath = './opResults/' with open(filepath + setting_c['name'] + '.csv', 'wb') as csvfile: fieldnames = resultList[0][1].keys() fieldnames.sort() writer = csv.DictWriter(csvfile, fieldnames) writer.writeheader() setting_t = {} value_t = -99999 for (setting, opDict) in resultList: writer.writerow(opDict) if opDict[targetName] > value_t: setting_t = setting value_t = opDict[targetName] print(str(setting_t) + ':' + str(value_t)) print(u'优化结束') print(u' ') # ---------------------------------------------------------------------- def showProcessBar(result): """显示进度条""" global p global currentP currentP += 1 p.update(currentP) # ---------------------------------------------------------------------- def getSetting(name): """获取策略基础配置""" setting_c = {} settingFileName = './CTA_setting1.json' with open(settingFileName) as f: l = json.load(f) for setting in l: if setting['name'] == name: setting_c = setting setting_c[u'backtesting'] = True return setting_c # ---------------------------------------------------------------------- def formatNumber(n): """格式化数字到字符串""" rn = round(n, 2) # 保留两位小数 return format(rn, ',') # 加上千分符 # ---------------------------------------------------------------------- def optimize(setting_c, setting, targetName, optimism, startTime='', endTime='', slippage=0, mode='T'): """多进程优化时跑在每个进程中运行的函数""" setting_c[u'backtesting'] = True # from ctaSetting import STRATEGY_CLASS from strategy import STRATEGY_CLASS from ctaBacktesting1 import BacktestingEngine vtSymbol = setting_c[u'vtSymbol'] if u'vtSymbol1' in setting_c: vtSymbol1 = setting_c[u'vtSymbol1'] else: vtSymbol1 = None className = setting_c[u'className'] if os.path.exists("CTA_v_setting.json"): fileName = "CTA_v_setting.json" else: fileName = "../CTA_v_setting.json" with open(fileName) as f: l = json.load(f) for setting_x in l: name = setting_x[u'name'] match = re.search('^' + name + '[0-9]', vtSymbol) if match: rate = setting_x[u'mRate'] price = setting_x[u'mPrice'] size = setting_x[u'mSize'] level = setting_x[u'mLevel'] if vtSymbol1: match = re.search('^' + name + '[0-9]', vtSymbol1) if match: rate1 = setting_x[u'mRate'] price1 = setting_x[u'mPrice'] size1 = setting_x[u'mSize'] level1 = setting_x[u'mLevel'] name = setting_c[u'name'] engine = BacktestingEngine() # engine.plot = False # engine.fast = True engine.plot = True engine.optimism = optimism # 设置引擎的回测模式 if mode == 'T': engine.setBacktestingMode(engine.TICK_MODE) dbName = TICK_DB_NAME elif mode == 'B': engine.setBacktestingMode(engine.BAR_MODE) dbName = MINUTE_DB_NAME elif mode == 'D': engine.setBacktestingMode(engine.BAR_MODE) dbName = DAILY_DB_NAME # 设置回测用的数据起始日期 if not startTime: startTime = str(setting_c[u'StartTime']) if not endTime: endTime = str(setting_c[u'EndTime']) engine.setStartDate(startTime) engine.setEndDate(endTime) engine.loadHistoryData(dbName, vtSymbol) if vtSymbol1: engine.loadHistoryData1(dbName, vtSymbol1) # 设置产品相关参数 engine.setSlippage(slippage) # 滑点 engine.setLeverage(level) # 合约杠杆 engine.setSize(size) # 合约大小 engine.setRate(rate) # 手续费 engine.setPrice(price) # 最小价格变动 if vtSymbol1: engine.setSize1(size1) # 合约大小 engine.setRate1(rate1) # 手续费 engine.setPrice1(price1) # 最小价格变动 else: engine.setSize1(size) # 合约大小 engine.setRate1(rate) # 手续费 engine.setPrice1(price) # 最小价格变动 engine.initStrategy(STRATEGY_CLASS[className], setting_c) engine.strategy.onUpdate(setting) engine.runBacktesting() opResult = {} d = engine.calculateBacktestingResult() try: targetValue = d[targetName] except KeyError: targetValue = 0 for key in setting: opResult[key] = setting[key] opResult['totalResult'] = d['totalResult'] opResult['capital'] = round(d['capital'], 2) if d['totalResult'] > 0: opResult['maxDrawdown'] = min(d['drawdownList']) opResult['winPerT'] = round(d['capital'] / d['totalResult'], 2) opResult['splipPerT'] = round(d['totalSlippage'] / d['totalResult'], 2) opResult['commiPerT'] = round(d['totalCommission'] / d['totalResult'], 2) else: opResult['maxDrawdown'] = 0 opResult['winPerT'] = 0 opResult['splipPerT'] = 0 opResult['commiPerT'] = 0 opResult['winningRate'] = round(d['winningRate'], 2) opResult['averageWinning'] = round(d['averageWinning'], 2) opResult['averageLosing'] = round(d['averageLosing'], 2) opResult['profitLossRatio'] = round(d['profitLossRatio'], 2) return (setting, opResult) if __name__ == '__main__': # 建议使用ipython notebook或者spyder来做回测 """读取策略配置""" begin = datetime.now() # 回测策略选择 name = 'spread' setting_c = getSetting(name) # 回测模式设置 opt = False # 回测参数设置 # 策略参数设置 # optimizationSetting = OptimizationSetting() # optimizationSetting.addParameter('wLimit', 3, 4, 1) # 3, 6, 1 # optimizationSetting.setOptimizeTarget('wLimit') # 确认检查 print(u'即将开始优化回测,请确认下面的信息正确后开始回测:') print(u'1.回测引擎是正确的稳定版本') print(u'2.(乐观\悲观)模式选择正确') print(u'3.策略逻辑正确') print(u'4.策略参数初始化无遗漏') print(u'5.策略参数传递无遗漏') print(u'6.策略单次回测交割单检查正确') print(u'7.参数扫描区间合理') print(u'8.关闭结果文件') print(u'y/n:') choice = raw_input(u'') if not choice == 'y': exit(0) # 开始回测 backtesting(setting_c, StartTime= "2017-05-19 21:01:00", EndTime = "2017-06-19 15:00:00", optimism=opt, mode='B') # runParallelOptimization(setting_c, optimizationSetting, optimism=opt, mode='T') end = datetime.now() print(u'回测用时: ' + str(end - begin)) # outfile.close
39.188464
118
0.512398
''' 本文件中包含的是CTA模块的回测引擎,回测引擎的API和CTA引擎一致, 可以使用和实盘相同的代码进行回测。 ''' from __future__ import division from itertools import product import copy import os import sys import re import csv import time import multiprocessing import json import pymongo import threading from datetime import datetime from collections import OrderedDict from progressbar import ProgressBar from collections import deque from ctaBase import * from vtConstant import * from vtGateway import VtOrderData, VtTradeData from vtFunction import loadMongoSetting atetime.strptime(startDate, '%Y%m%d') elif len(startDate) == 10: self.dataStartDate = datetime.strptime(startDate, '%Y-%m-%d') else: self.dataStartDate = datetime.strptime(startDate, '%Y-%m-%d %H:%M:%S') def setEndDate(self, endDate='20170501'): """设置回测的结束日期 支持两种日期模式""" if len(endDate) == 8: self.dataEndDate = datetime.strptime(endDate, '%Y%m%d') elif len(endDate) == 10: self.dataEndDate = datetime.strptime(endDate, '%Y-%m-%d') else: self.dataEndDate = datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S') def setBacktestingMode(self, mode): """设置回测模式""" self.mode = mode if self.mode == self.BAR_MODE: self.dataClass = CtaBarData self._dataClass = CtaBarData1 else: self.dataClass = CtaTickData self._dataClass = CtaTickData1 def loadHistoryData1(self, dbName, symbol): """载入历史数据""" host, port, logging = loadMongoSetting() if not self.dbClient: self.dbClient = pymongo.MongoClient(host, port, socketKeepAlive=True) collection = self.dbClient[dbName][symbol] self.output(u'开始载入合约2数据') if self.mode == self.BAR_MODE: dataClass = CtaBarData func = self.newBar1 else: dataClass = CtaTickData func = self.newTick1 fltStartDate = self.dataStartDate.strftime("%Y-%m-%d %H:%M:%S") fltEndDate = self.dataEndDate.strftime("%Y-%m-%d %H:%M:%S") self.output("Start : " + str(self.dataStartDate)) self.output("End : " + str(self.dataEndDate)) if not self.dataEndDate: flt = {'datetime': {'$gte': fltStartDate}} else: flt = {'datetime': {'$gte': fltStartDate, '$lte': fltEndDate}} self.dbCursor1 = collection.find(flt, no_cursor_timeout=True).batch_size(self.bufferSize) self.output(u'载入完成,数据量:%s' % (self.dbCursor1.count())) self.output(u' ') def loadHistoryData(self, dbName, symbol): """载入历史数据""" host, port, logging = loadMongoSetting() if not self.dbClient: self.dbClient = pymongo.MongoClient(host, port, socketKeepAlive=True) collection = self.dbClient[dbName][symbol] self.output(u'开始载入合约1数据') if self.mode == self.BAR_MODE: dataClass = CtaBarData func = self.newBar else: dataClass = CtaTickData func = self.newTick fltStartDate = self.dataStartDate.strftime("%Y-%m-%d %H:%M:%S") fltEndDate = self.dataEndDate.strftime("%Y-%m-%d %H:%M:%S") self.output("Start : " + str(self.dataStartDate)) self.output("End : " + str(self.dataEndDate)) if not self.dataEndDate: flt = {'datetime': {'$gte': fltStartDate}} else: flt = {'datetime': {'$gte': fltStartDate, '$lte': fltEndDate}} self.dbCursor = collection.find(flt, no_cursor_timeout=True).batch_size(self.bufferSize) self.output(u'载入完成,数据量:%s' % (self.dbCursor.count())) self.output(u' ') def prepareData(self, dbCursor_count, dbCursor_count1): """数据准备线程""" while len(self.backtestingData) < self.bufferSize and self.j < dbCursor_count: d = self.dbCursor.next() _data = self._dataClass() data = self.dataClass() _data.__dict__ = d if self.mode == 'tick': data.vtSymbol = self.strategy.vtSymbol data.lastPrice = _data.price data.volume = _data.volume data.openInterest = _data.open_interest data.upperLimit = _data.limit_up data.lowerLimit = _data.limit_down data.bidPrice1 = _data.bidPrice1 data.askPrice1 = _data.askPrice1 data.bidVolume1 = _data.bidVolume1 data.askVolume1 = _data.askVolume1 data.date = _data.date data.time = _data.time data.datetime = datetime.strptime(_data.datetime, "%Y-%m-%d %H:%M:%S.%f") elif self.mode == 'bar': data.vtSymbol = self.strategy.vtSymbol data.open = _data.open data.high = _data.high data.low = _data.low data.close = _data.close data.volume = _data.volume data.date = _data.date data.time = _data.time data.datetime = datetime.strptime(_data.datetime, "%Y-%m-%d %H:%M:%S") self.backtestingData.append(data) self.j += 1 while len(self.backtestingData1) < self.bufferSize and self.i < dbCursor_count1: d1 = self.dbCursor1.next() _data = self._dataClass() data1 = self.dataClass() _data.__dict__ = d1 if self.mode == 'tick': data1.vtSymbol = self.strategy.vtSymbol1 data1.lastPrice = _data.price data1.volume = _data.volume data1.openInterest = _data.open_interest data1.upperLimit = _data.limit_up data1.lowerLimit = _data.limit_down data1.bidPrice1 = _data.bidPrice1 data1.askPrice1 = _data.askPrice1 data1.bidVolume1 = _data.bidVolume1 data1.askVolume1 = _data.askVolume1 data1.date = _data.date data1.time = _data.time data1.datetime = datetime.strptime(_data.datetime, "%Y-%m-%d %H:%M:%S.%f") elif self.mode == 'bar': data1.vtSymbol = self.strategy.vtSymbol1 data1.open = _data.open data1.high = _data.high data1.low = _data.low data1.close = _data.close data1.volume = _data.volume data1.date = _data.date data1.time = _data.time data1.datetime = datetime.strptime(_data.datetime, "%Y-%m-%d %H:%M:%S") self.backtestingData1.append(data1) self.i += 1 def runBacktesting(self): """运行回测 判断是否双合约""" if self.strategy.vtSymbol1 == None: self.runBacktesting_one() else: self.runBacktesting_two() def runBacktesting_two(self): """运行回测""" if self.mode == self.BAR_MODE: self.dataClass = CtaBarData func = self.newBar func1 = self.newBar1 func2 = self.newBar01 else: self.dataClass = CtaTickData func = self.newTick func1 = self.newTick1 func2 = self.newTick01 self.output(u'-' * 30) self.output(u'开始回测') self.strategy.inited = True self.strategy.onInit() self.output(u'策略初始化完成') self.strategy.trading = True self.strategy.onStart() self.output(u'策略启动完成') dbCursor_count = self.dbCursor.count() dbCursor_count1 = self.dbCursor1.count() self.i = 0; self.j = 0; lastData = None lastData1 = None t = None self.output(u'开始回放双合约数据') while (self.i < dbCursor_count1 and self.j < dbCursor_count) or ( self.backtestingData and self.backtestingData1): t = threading.Thread(target=self.prepareData, args=(dbCursor_count, dbCursor_count1)) t.start() while self.backtestingData and self.backtestingData1: if self.backtestingData1[0].datetime > self.backtestingData[0].datetime: if lastData1: func2(self.backtestingData[0], lastData1) lastData = self.backtestingData.popleft() elif self.backtestingData[0].datetime > self.backtestingData1[0].datetime: if lastData: func2(lastData, self.backtestingData1[0]) lastData1 = self.backtestingData1.popleft() elif self.backtestingData and self.backtestingData1 and self.backtestingData1[0].datetime == \ self.backtestingData[0].datetime: func2(self.backtestingData[0], self.backtestingData1[0]) lastData = self.backtestingData.popleft() lastData1 = self.backtestingData1.popleft() t.join() self.strategy.onStop() self.output(u'数据回放结束') def runBacktesting_one(self): """运行回测""" if self.mode == self.BAR_MODE: self.dataClass = CtaBarData func = self.newBar func1 = self.newBar1 else: self.dataClass = CtaTickData func = self.newTick self.output(u'开始回测') self.strategy.inited = True self.strategy.onInit() self.output(u'策略初始化完成') self.strategy.trading = True self.strategy.onStart() self.output(u'策略启动完成') self.output(u'开始回放单合约数据') dbCursor_count = self.dbCursor.count() self.j = 0; self.i = 0; dbCursor_count1 = 0 lastData = None lastData1 = None t = None while self.j < dbCursor_count or self.backtestingData: t = threading.Thread(target=self.prepareData, args=(dbCursor_count, dbCursor_count1)) t.start() while self.backtestingData: lastData = self.backtestingData.popleft() func(lastData) t.join() self.strategy.onStop() self.output(u'数据回放结束') def newBar(self, bar): """新的K线""" self.bar = bar self.dt = bar.datetime self.crossLimitOrder() self.strategy.onBar(bar) def newBar1(self, bar): """新的K线""" self.bar1 = bar self.dt = bar.datetime self.crossLimitOrder1() self.strategy.onBar(bar) def newBar01(self, bar, bar1): """新的Bar""" self.dt = bar.datetime self.bar = bar self.bar1 = bar1 self.crossBarLimitOrder1() self.crossBarLimitOrder() if bar1.datetime >= bar.datetime: self.strategy.onBar(self.bar1) if bar.datetime >= bar1.datetime: self.strategy.onBar(self.bar) self.strategy.onSpread() if self.optimism: self.crossBarLimitOrder1() self.crossBarLimitOrder() self.lastbar = self.bar self.lastbar1 = self.bar1 def newTick(self, tick): """新的Tick""" self.tick = tick self.dt = tick.datetime self.crossLimitOrder() self.strategy.onTick(tick) if self.optimism: self.crossLimitOrder() self.lasttick = tick def newTick1(self, tick): """新的Tick""" self.tick1 = tick self.dt = tick.datetime self.crossLimitOrder() self.strategy.onTick(tick) if self.optimism: self.crossLimitOrder() self.lasttick1 = tick def newTick01(self, tick, tick1): """新的Tick""" self.dt = tick.datetime self.tick = tick self.tick1 = tick1 self.crossLimitOrder1() self.crossLimitOrder() if tick1.datetime >= tick.datetime: self.strategy.onTick(self.tick1) if tick.datetime >= tick1.datetime: self.strategy.onTick(self.tick) if self.optimism: self.crossLimitOrder1() self.crossLimitOrder() self.lasttick = self.tick self.lasttick1 = self.tick1 def initStrategy(self, strategyClass, setting=None): """ 初始化策略 setting是策略的参数设置,如果使用类中写好的默认设置则可以不传该参数 """ self.strategy = strategyClass(self, setting) def sendOrder(self, vtSymbol, orderType, price, volume, strategy): """发单""" self.limitOrderCount += 1 orderID = str(self.limitOrderCount) order = VtOrderData() order.vtSymbol = vtSymbol order.price = price order.priceType = PRICETYPE_LIMITPRICE order.totalVolume = volume order.status = STATUS_NOTTRADED order.orderID = orderID order.vtOrderID = orderID order.orderTime = str(self.dt) if orderType == CTAORDER_BUY: order.direction = DIRECTION_LONG order.offset = OFFSET_OPEN elif orderType == CTAORDER_SHORT: order.direction = DIRECTION_SHORT order.offset = OFFSET_OPEN elif orderType == CTAORDER_SELL and not self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSE elif orderType == CTAORDER_SELL and self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_COVER and not self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSE elif orderType == CTAORDER_COVER and self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_SELL_TODAY: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSETODAY elif orderType == CTAORDER_COVER_TODAY: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSETODAY if vtSymbol == strategy.vtSymbol: self.workingLimitOrderDict[orderID] = order self.limitOrderDict[orderID] = order elif vtSymbol == strategy.vtSymbol1: self.workingLimitOrderDict1[orderID] = order self.limitOrderDict1[orderID] = order return orderID def sendOrderFAK(self, vtSymbol, orderType, price, volume, strategy): """发单""" self.limitOrderCount += 1 orderID = str(self.limitOrderCount) order = VtOrderData() order.vtSymbol = vtSymbol order.price = price order.priceType = PRICETYPE_FAK order.totalVolume = volume order.status = STATUS_NOTTRADED order.orderID = orderID order.vtOrderID = orderID order.orderTime = str(self.dt) if orderType == CTAORDER_BUY: order.direction = DIRECTION_LONG order.offset = OFFSET_OPEN elif orderType == CTAORDER_SELL and not self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSE elif orderType == CTAORDER_SELL and self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_SELL_TODAY: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSETODAY elif orderType == CTAORDER_SHORT: order.direction = DIRECTION_SHORT order.offset = OFFSET_OPEN elif orderType == CTAORDER_COVER and not self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSE elif orderType == CTAORDER_COVER and self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_COVER_TODAY: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSETODAY if vtSymbol == strategy.vtSymbol: self.workingLimitOrderDict[orderID] = order self.limitOrderDict[orderID] = order elif vtSymbol == strategy.vtSymbol1: self.workingLimitOrderDict1[orderID] = order self.limitOrderDict1[orderID] = order return orderID def sendOrderFOK(self, vtSymbol, orderType, price, volume, strategy): """发单""" self.limitOrderCount += 1 orderID = str(self.limitOrderCount) order = VtOrderData() order.vtSymbol = vtSymbol order.price = price order.priceType = PRICETYPE_FOK order.totalVolume = volume order.status = STATUS_NOTTRADED order.orderID = orderID order.vtOrderID = orderID order.orderTime = str(self.dt) if orderType == CTAORDER_BUY: order.direction = DIRECTION_LONG order.offset = OFFSET_OPEN elif orderType == CTAORDER_SELL and not self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSE elif orderType == CTAORDER_SELL and self.shfe: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_SELL_TODAY: order.direction = DIRECTION_SHORT order.offset = OFFSET_CLOSETODAY elif orderType == CTAORDER_SHORT: order.direction = DIRECTION_SHORT order.offset = OFFSET_OPEN elif orderType == CTAORDER_COVER and not self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSE elif orderType == CTAORDER_COVER and self.shfe: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSEYESTERDAY elif orderType == CTAORDER_COVER_TODAY: order.direction = DIRECTION_LONG order.offset = OFFSET_CLOSETODAY if vtSymbol == strategy.vtSymbol: self.workingLimitOrderDict[orderID] = order self.limitOrderDict[orderID] = order elif vtSymbol == strategy.vtSymbol1: self.workingLimitOrderDict1[orderID] = order self.limitOrderDict1[orderID] = order return orderID def cancelOrder(self, vtOrderID): """撤单""" if vtOrderID in self.workingLimitOrderDict: order = self.workingLimitOrderDict[vtOrderID] elif vtOrderID in self.workingLimitOrderDict1: order = self.workingLimitOrderDict1[vtOrderID] else: order = None return False if order.status == STATUS_NOTTRADED: order.status = STATUS_CANCELLED order.cancelTime = str(self.dt) self.strategy.onOrder(order) else: order.status = STATUS_PARTTRADED_PARTCANCELLED order.cancelTime = str(self.dt) self.strategy.onOrder(order) if vtOrderID in self.workingLimitOrderDict: self.removeOrder(vtOrderID) elif vtOrderID in self.workingLimitOrderDict1: self.removeOrder1(vtOrderID) return True def sendStopOrder(self, vtSymbol, orderType, price, volume, strategy): """发停止单(本地实现)""" self.stopOrderCount += 1 stopOrderID = STOPORDERPREFIX + str(self.stopOrderCount) so = StopOrder() so.vtSymbol = vtSymbol so.price = price so.volume = volume so.strategy = strategy so.stopOrderID = stopOrderID so.status = STOPORDER_WAITING if orderType == CTAORDER_BUY: so.direction = DIRECTION_LONG so.offset = OFFSET_OPEN elif orderType == CTAORDER_SELL: so.direction = DIRECTION_SHORT so.offset = OFFSET_CLOSE elif orderType == CTAORDER_SHORT: so.direction = DIRECTION_SHORT so.offset = OFFSET_OPEN elif orderType == CTAORDER_COVER: so.direction = DIRECTION_LONG so.offset = OFFSET_CLOSE self.stopOrderDict[stopOrderID] = so self.workingStopOrderDict[stopOrderID] = so return stopOrderID def cancelStopOrder(self, stopOrderID): """撤销停止单""" if stopOrderID in self.workingStopOrderDict: so = self.workingStopOrderDict[stopOrderID] so.status = STOPORDER_CANCELLED del self.workingStopOrderDict[stopOrderID] def filterTradeTime(self): """过滤非交易时间""" if self.dt: hour = self.dt.hour if (hour >= 15 and hour < 20) or (hour >= 2 and hour < 8): return True elif hour == 8: self.lasttick = None self.lasttick1 = None for orderID in self.workingLimitOrderDict: self.cancelOrder(orderID) for orderID in self.workingLimitOrderDict1: self.cancelOrder(orderID) return True elif hour == 20: self.lasttick = None self.lasttick1 = None for orderID in self.workingLimitOrderDict: self.cancelOrder(orderID) for orderID in self.workingLimitOrderDict1: self.cancelOrder(orderID) return True return False def calcTickVolume(self, tick, lasttick, size): """计算两边盘口的成交量""" if (not lasttick): currentVolume = tick.volume currentTurnOver = tick.turnover pOnAsk = tick.askPrice1 pOnBid = tick.bidPrice1 else: currentVolume = tick.volume - lasttick.volume currentTurnOver = tick.turnover - lasttick.turnover pOnAsk = lasttick.askPrice1 pOnBid = lasttick.bidPrice1 if lasttick and currentVolume > 0: currentPrice = currentTurnOver / currentVolume / size ratio = (currentPrice - lasttick.bidPrice1) / (lasttick.askPrice1 - lasttick.bidPrice1) ratio = max(ratio, 0) ratio = min(ratio, 1) volOnAsk = ratio * currentVolume / 2 volOnBid = (currentVolume - volOnAsk) / 2 else: volOnAsk = 0 volOnBid = 0 return volOnBid, volOnAsk, pOnBid, pOnAsk def removeOrder(self, orderID): """清除订单信息""" del self.workingLimitOrderDict[orderID] if orderID in self.orderPrice: del self.orderPrice[orderID] if orderID in self.orderVolume: del self.orderVolume[orderID] def removeOrder1(self, orderID): """清除订单信息""" del self.workingLimitOrderDict1[orderID] if orderID in self.orderPrice1: del self.orderPrice1[orderID] if orderID in self.orderVolume1: del self.orderVolume1[orderID] def snapMarket(self, tradeID): """快照市场""" if self.mode == self.TICK_MODE: self.tradeSnap[tradeID] = copy.copy(self.tick) self.tradeSnap1[tradeID] = copy.copy(self.tick1) else: self.tradeSnap[tradeID] = copy.copy(self.bar) self.tradeSnap1[tradeID] = copy.copy(self.bar1) def strategyOnTrade(self, order, volumeTraded, priceTraded): """处理成交回报""" self.tradeCount += 1 tradeID = str(self.tradeCount) trade = VtTradeData() trade.dt = self.dt trade.vtSymbol = order.vtSymbol trade.direction = order.direction trade.offset = order.offset trade.tradeTime = self.dt.strftime('%Y%m%d %H:%M:%S.') + self.dt.strftime('%f')[:1] trade.volume = volumeTraded trade.price = priceTraded self.strategy.onTrade(copy.copy(trade)) if trade.vtSymbol == self.strategy.vtSymbol: self.tradeDict[tradeID] = trade else: self.tradeDict1[tradeID] = trade def crossLimitOrder(self): """基于最新数据撮合限价单""" tick = self.tick lasttick = self.lasttick bar = self.bar if self.filterTradeTime(): return if self.mode == self.BAR_MODE: buyCrossPrice = bar.low sellCrossPrice = bar.high else: buyCrossPrice = tick.askPrice1 if tick.askPrice1 > 0 else tick.bidPrice1 + self.mPrice sellCrossPrice = tick.bidPrice1 if tick.bidPrice1 > 0 else tick.askPrice1 - self.mPrice for orderID, order in self.workingLimitOrderDict.items(): buyCross = order.direction == DIRECTION_LONG and order.price >= buyCrossPrice sellCross = order.direction == DIRECTION_SHORT and order.price <= sellCrossPrice if buyCross or sellCross: volumeTraded = (order.totalVolume - order.tradedVolume) if self.mode == self.TICK_MODE: volumeTraded = min(volumeTraded, tick.askVolume1) if buyCross \ else min(volumeTraded, tick.bidVolume1) volumeTraded = max(volumeTraded, 1) if orderID in self.orderPrice and order.tradedVolume == 0: priceTraded = order.price else: priceTraded = min(order.price, buyCrossPrice) if buyCross \ else max(order.price, sellCrossPrice) order.tradedVolume += volumeTraded if order.priceType == PRICETYPE_FOK: if order.tradedVolume < order.totalVolume: order.status = STATUS_CANCELLED volumeTraded = 0 else: order.status = STATUS_ALLTRADED elif order.priceType == PRICETYPE_FAK: if order.tradedVolume < order.totalVolume: order.status = STATUS_PARTTRADED_PARTCANCELLED else: order.status = STATUS_ALLTRADED else: if order.tradedVolume < order.totalVolume: order.status = STATUS_PARTTRADED self.orderPrice[orderID] = order.price self.orderVolume[orderID] = 0 else: order.status = STATUS_ALLTRADED self.strategy.onOrder(order) if volumeTraded > 0: self.strategyOnTrade(order, volumeTraded, priceTraded) if not order.status == STATUS_PARTTRADED: self.removeOrder(orderID) elif self.mode == self.TICK_MODE and not self.fast: volOnBid, volOnAsk, pOnBid, pOnAsk = self.calcTickVolume(tick, lasttick, self.size) if orderID in self.orderPrice: if orderID not in self.orderVolume: if order.price == sellCrossPrice and order.direction == DIRECTION_LONG: self.orderVolume[orderID] = tick.bidVolume1 elif order.price == buyCrossPrice and order.direction == DIRECTION_SHORT: self.orderVolume[orderID] = tick.askVolume1 elif order.price > sellCrossPrice and order.direction == DIRECTION_LONG: self.orderVolume[orderID] = 0 elif order.price < buyCrossPrice and order.direction == DIRECTION_SHORT: self.orderVolume[orderID] = 0 elif order.price == pOnBid and order.direction == DIRECTION_LONG: self.orderVolume[orderID] -= volOnBid elif order.price == pOnAsk and order.direction == DIRECTION_SHORT: self.orderVolume[orderID] -= volOnAsk else: self.orderPrice[orderID] = order.price if order.direction == DIRECTION_SHORT and order.price == tick.askPrice1: self.orderVolume[orderID] = tick.askVolume1 elif order.direction == DIRECTION_LONG and order.price == tick.bidPrice1: self.orderVolume[orderID] = tick.bidVolume1 if orderID in self.orderVolume and self.orderVolume[orderID] <= 0: priceTraded = order.price volumeTraded = order.totalVolume - order.tradedVolume order.tradedVolume = order.totalVolume order.status = STATUS_ALLTRADED self.strategy.onOrder(order) self.strategyOnTrade(order, volumeTraded, priceTraded) self.removeOrder(orderID) else: order.tradedVolume = 0 order.status = STATUS_NOTTRADED if order.priceType == PRICETYPE_FOK or order.priceType == PRICETYPE_FAK: order.status = STATUS_CANCELLED self.removeOrder(orderID) self.strategy.onOrder(order) def crossLimitOrder1(self): """基于最新数据撮合限价单""" lasttick1 = self.lasttick1 tick1 = self.tick1 bar1 = self.bar1 if self.filterTradeTime(): return if self.mode == self.BAR_MODE: buyCrossPrice = bar1.low sellCrossPrice = bar1.high else: buyCrossPrice = tick1.askPrice1 if tick1.askPrice1 > 0 else tick1.bidPrice1 + self.mPrice1 sellCrossPrice = tick1.bidPrice1 if tick1.bidPrice1 > 0 else tick1.askPrice1 - self.mPrice1 for orderID, order in self.workingLimitOrderDict1.items(): buyCross = order.direction == DIRECTION_LONG and order.price >= buyCrossPrice sellCross = order.direction == DIRECTION_SHORT and order.price <= sellCrossPrice if buyCross or sellCross: volumeTraded = (order.totalVolume - order.tradedVolume) if self.mode == self.TICK_MODE: volumeTraded = min(volumeTraded, tick1.askVolume1) if buyCross \ else min(volumeTraded, tick1.bidVolume1) volumeTraded = max(volumeTraded, 1) if orderID in self.orderPrice1 and order.tradedVolume == 0: priceTraded = order.price else: priceTraded = min(order.price, buyCrossPrice) if buyCross else max(order.price, sellCrossPrice) order.tradedVolume += volumeTraded if order.priceType == PRICETYPE_FOK: if order.tradedVolume < order.totalVolume: order.status = STATUS_CANCELLED volumeTraded = 0 else: order.status = STATUS_ALLTRADED elif order.priceType == PRICETYPE_FAK: if order.tradedVolume < order.totalVolume: order.status = STATUS_PARTTRADED_PARTCANCELLED else: order.status = STATUS_ALLTRADED else: if order.tradedVolume < order.totalVolume: order.status = STATUS_PARTTRADED self.orderPrice1[orderID] = order.price self.orderVolume1[orderID] = 0 else: order.status = STATUS_ALLTRADED self.strategy.onOrder(order) if volumeTraded > 0: self.strategyOnTrade(order, volumeTraded, priceTraded) if not order.status == STATUS_PARTTRADED: self.removeOrder1(orderID) elif self.mode == self.TICK_MODE and not self.fast: volOnBid, volOnAsk, pOnBid, pOnAsk = self.calcTickVolume(tick1, lasttick1, self.size1) if orderID in self.orderPrice1: if orderID not in self.orderVolume1: if order.price == sellCrossPrice and order.direction == DIRECTION_LONG: self.orderVolume1[orderID] = tick1.bidVolume1 elif order.price == buyCrossPrice and order.direction == DIRECTION_SHORT: self.orderVolume1[orderID] = tick1.askVolume1 elif order.price > sellCrossPrice and order.direction == DIRECTION_LONG: self.orderVolume1[orderID] = 0 elif order.price < buyCrossPrice and order.direction == DIRECTION_SHORT: self.orderVolume1[orderID] = 0 elif order.price == pOnBid and order.direction == DIRECTION_LONG: self.orderVolume1[orderID] -= volOnBid elif order.price == pOnAsk and order.direction == DIRECTION_SHORT: self.orderVolume1[orderID] -= volOnAsk else: self.orderPrice1[orderID] = order.price if order.direction == DIRECTION_SHORT and order.price == tick1.askPrice1: self.orderVolume1[orderID] = tick1.askVolume1 elif order.direction == DIRECTION_LONG and order.price == tick1.bidPrice1: self.orderVolume1[orderID] = tick1.bidVolume1 if orderID in self.orderVolume1 and self.orderVolume1[orderID] <= 0: priceTraded = order.price volumeTraded = order.totalVolume - order.tradedVolume order.tradedVolume = order.totalVolume order.status = STATUS_ALLTRADED self.strategy.onOrder(order) self.strategyOnTrade(order, volumeTraded, priceTraded) self.removeOrder1(orderID) else: order.tradedVolume = 0 order.status = STATUS_NOTTRADED if order.priceType == PRICETYPE_FOK or order.priceType == PRICETYPE_FAK: order.status = STATUS_CANCELLED self.removeOrder1(orderID) self.strategy.onOrder(order) def crossBarLimitOrder(self): """基于最新数据撮合限价单""" if self.mode == self.BAR_MODE: buyCrossPrice = self.bar.low sellCrossPrice = self.bar.high buyBestCrossPrice = self.bar.open sellBestCrossPrice = self.bar.open else: buyCrossPrice = self.tick.askPrice1 sellCrossPrice = self.tick.bidPrice1 buyBestCrossPrice = self.tick.askPrice1 sellBestCrossPrice = self.tick.bidPrice1 for orderID, order in self.workingLimitOrderDict.items(): buyCross = order.direction == DIRECTION_LONG and order.price >= buyCrossPrice sellCross = order.direction == DIRECTION_SHORT and order.price <= sellCrossPrice if buyCross or sellCross: self.tradeCount += 1 tradeID = str(self.tradeCount) trade = VtTradeData() trade.vtSymbol = order.vtSymbol trade.tradeID = tradeID trade.vtTradeID = tradeID trade.orderID = order.orderID trade.vtOrderID = order.orderID trade.direction = order.direction trade.offset = order.offset if buyCross: trade.price = min(order.price, buyBestCrossPrice) self.strategy.pos += order.totalVolume else: trade.price = max(order.price, sellBestCrossPrice) self.strategy.pos -= order.totalVolume trade.volume = order.totalVolume trade.tradeTime = str(self.dt) trade.dt = self.dt self.strategy.onTrade(trade) self.tradeDict[tradeID] = trade order.tradedVolume = order.totalVolume order.status = STATUS_ALLTRADED self.strategy.onOrder(order) del self.workingLimitOrderDict[orderID] def crossBarLimitOrder1(self): """基于最新数据撮合限价单""" if self.mode == self.BAR_MODE: buyCrossPrice = self.bar.low sellCrossPrice = self.bar.high buyBestCrossPrice = self.bar.open sellBestCrossPrice = self.bar.open else: buyCrossPrice = self.tick.askPrice1 sellCrossPrice = self.tick.bidPrice1 buyBestCrossPrice = self.tick.askPrice1 sellBestCrossPrice = self.tick.bidPrice1 for orderID, order in self.workingLimitOrderDict.items(): buyCross = order.direction == DIRECTION_LONG and order.price >= buyCrossPrice sellCross = order.direction == DIRECTION_SHORT and order.price <= sellCrossPrice if buyCross or sellCross: self.tradeCount += 1 tradeID = str(self.tradeCount) trade = VtTradeData() trade.vtSymbol = order.vtSymbol trade.tradeID = tradeID trade.vtTradeID = tradeID trade.orderID = order.orderID trade.vtOrderID = order.orderID trade.direction = order.direction trade.offset = order.offset if buyCross: trade.price = min(order.price, buyBestCrossPrice) self.strategy.pos += order.totalVolume else: trade.price = max(order.price, sellBestCrossPrice) self.strategy.pos -= order.totalVolume trade.volume = order.totalVolume trade.tradeTime = str(self.dt) trade.dt = self.dt self.strategy.onTrade(trade) self.tradeDict1[tradeID] = trade order.tradedVolume = order.totalVolume order.status = STATUS_ALLTRADED self.strategy.onOrder(order) del self.workingLimitOrderDict[orderID] def crossStopOrder(self): """基于最新数据撮合停止单""" if self.mode == self.BAR_MODE: buyCrossPrice = self.bar.high sellCrossPrice = self.bar.low bestCrossPrice = self.bar.open else: buyCrossPrice = self.tick.lastPrice sellCrossPrice = self.tick.lastPrice bestCrossPrice = self.tick.lastPrice for stopOrderID, so in self.workingStopOrderDict.items(): buyCross = so.direction == DIRECTION_LONG and so.price <= buyCrossPrice sellCross = so.direction == DIRECTION_SHORT and so.price >= sellCrossPrice if buyCross or sellCross: self.tradeCount += 1 tradeID = str(self.tradeCount) trade = VtTradeData() trade.vtSymbol = so.vtSymbol trade.tradeID = tradeID trade.vtTradeID = tradeID if buyCross: trade.price = max(bestCrossPrice, so.price) else: trade.price = min(bestCrossPrice, so.price) self.limitOrderCount += 1 orderID = str(self.limitOrderCount) trade.orderID = orderID trade.vtOrderID = orderID trade.direction = so.direction trade.offset = so.offset trade.volume = so.volume trade.tradeTime = self.dt.strftime('%Y%m%d %H:%M:%S.') + self.dt.strftime('%f')[:1] trade.dt = self.dt self.strategy.onTrade(copy.copy(trade)) self.tradeDict[tradeID] = trade self.tradeDict1[tradeID] = trade so.status = STOPORDER_TRIGGERED order = VtOrderData() order.vtSymbol = so.vtSymbol order.symbol = so.vtSymbol order.orderID = orderID order.vtOrderID = orderID order.direction = so.direction order.offset = so.offset order.price = so.price order.totalVolume = so.volume order.tradedVolume = so.volume order.status = STATUS_ALLTRADED order.orderTime = trade.tradeTime self.strategy.onOrder(order) self.limitOrderDict[orderID] = order del self.workingStopOrderDict[stopOrderID] def insertData(self, dbName, collectionName, data): """考虑到回测中不允许向数据库插入数据,防止实盘交易中的一些代码出错""" pass def writeCtaLog(self, content): """记录日志""" log = str(self.dt) + ' ' + content self.logList.append(log) def output(self, content): """输出内容""" if not self.plot: return if self.plotfile: print content.encode('utf8') else: print content def makeRecord(self, tradeTime, offset, direction, price, pnl): """记录成交内容""" resDict = {} resDict[u'datetime'] = tradeTime resDict[u'price'] = price resDict[u'contract0'] = self.strategy.vtSymbol resDict[u'contract1'] = self.strategy.vtSymbol resDict[u'offset'] = offset resDict[u'direction'] = direction resDict[u'pnl'] = pnl if self.strategy.vtSymbol1: resDict[u'contract1'] = self.strategy.vtSymbol1 return resDict def calculateBacktestingResult(self, detial=False): """ 计算回测结果 """ self.output(u'按逐笔对冲计算回测结果') pnlDict = OrderedDict() longTrade = deque([]) shortTrade = deque([]) longTrade1 = deque([]) shortTrade1 = deque([]) resList = [{"name": self.strategy.name}] totalSlippage = self.slippage * 2 self.output(u'总交易量 : ' + str(len(self.tradeDict))) self.output(u'总交易量1 : ' + str(len(self.tradeDict1))) leg2 = True if self.tradeDict.values(): dict_trade = self.tradeDict.values() else: dict_trade = self.tradeDict1.values() leg2 = False if self.tradeDict1.values(): dict_trade1 = self.tradeDict1.values() else: dict_trade1 = self.tradeDict.values() leg2 = False for trade1 in dict_trade1: if trade1.direction == DIRECTION_LONG: untraded = True while (shortTrade1 and untraded): entryTrade = shortTrade1[0] exitTrade = trade1 volume = min(entryTrade.volume, exitTrade.volume) entryTrade.volume = entryTrade.volume - volume exitTrade.volume = exitTrade.volume - volume if entryTrade.volume == 0: shortTrade1.popleft() if exitTrade.volume == 0: untraded = False if exitTrade.dt not in pnlDict: pnlDict[exitTrade.dt] = TradingResult(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, -volume, self.rate1, self.slippage1, self.size1) elif leg2: pnlDict[exitTrade.dt].add(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, -volume, self.rate1, self.slippage1, self.size1) if exitTrade.dt in pnlDict and leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL1(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) elif not leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL1(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) if untraded: longTrade1.append(trade1) else: untraded = True while (untraded and longTrade1): entryTrade = longTrade1[0] exitTrade = trade1 volume = min(entryTrade.volume, exitTrade.volume) entryTrade.volume = entryTrade.volume - volume exitTrade.volume = exitTrade.volume - volume if entryTrade.volume == 0: longTrade1.popleft() if exitTrade.volume == 0: untraded = False if exitTrade.dt not in pnlDict: pnlDict[exitTrade.dt] = TradingResult(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, volume, self.rate1, self.slippage1, self.size1) elif leg2: pnlDict[exitTrade.dt].add(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, volume, self.rate1, self.slippage1, self.size1) if exitTrade.dt in pnlDict and leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL1(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) elif not leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL1(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) if untraded: shortTrade1.append(trade1) for trade in dict_trade: if trade.direction == DIRECTION_LONG: untraded = True while (shortTrade and untraded): entryTrade = shortTrade[0] exitTrade = trade volume = min(entryTrade.volume, exitTrade.volume) entryTrade.volume = entryTrade.volume - volume exitTrade.volume = exitTrade.volume - volume if entryTrade.volume == 0: shortTrade.popleft() if exitTrade.volume == 0: untraded = False if exitTrade.dt not in pnlDict: pnlDict[exitTrade.dt] = TradingResult(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, -volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTrade.dt].add(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, -volume, self.rate, self.slippage, self.size) if exitTrade.dt in pnlDict and leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) elif not leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) pnl = pnlDict[exitTrade.dt].pnl resDict = self.makeRecord(entryTrade.tradeTime, u'开', u'卖', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(exitTrade.tradeTime, u'平', u'买', exitTrade.price, pnl) resList.append(resDict) if untraded: longTrade.append(trade) else: untraded = True while (longTrade and untraded): entryTrade = longTrade[0] exitTrade = trade volume = min(entryTrade.volume, exitTrade.volume) entryTrade.volume = entryTrade.volume - volume exitTrade.volume = exitTrade.volume - volume if entryTrade.volume == 0: longTrade.popleft() if exitTrade.volume == 0: untraded = False if exitTrade.dt not in pnlDict: pnlDict[exitTrade.dt] = TradingResult(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTrade.dt].add(entryTrade.price, entryTrade.dt, exitTrade.price, exitTrade.dt, volume, self.rate, self.slippage, self.size) if exitTrade.dt in pnlDict and leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) elif not leg2: pnlDict[exitTrade.dt].posPnl = self.calcPosPNL(exitTrade.tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2) pnl = pnlDict[exitTrade.dt].pnl resDict = self.makeRecord(entryTrade.tradeTime, u'开', u'买', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(exitTrade.tradeTime, u'平', u'卖', exitTrade.price, pnl) resList.append(resDict) if untraded: shortTrade.append(trade) while (shortTrade): entryTrade = shortTrade.popleft() volume = entryTrade.volume if self.mode == self.TICK_MODE: exitTime = self.tick.datetime exitPrice = self.tick.askPrice1 else: exitTime = self.bar.datetime exitPrice = self.bar.close if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) pnl = pnlDict[exitTime].pnl elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) pnl = pnlDict[exitTime].pnl resDict = self.makeRecord(entryTrade.tradeTime, u'开持', u'卖', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(str(exitTime), u'平持', u'买', exitPrice, pnl) resList.append(resDict) while (longTrade): entryTrade = longTrade.popleft() volume = entryTrade.volume if self.mode == self.TICK_MODE: exitTime = self.tick.datetime exitPrice = self.tick.bidPrice1 else: exitTime = self.bar.datetime exitPrice = self.bar.close if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) pnl = pnlDict[exitTime].pnl elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) pnl = pnlDict[exitTime].pnl resDict = self.makeRecord(entryTrade.tradeTime, u'开持', u'买', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(str(exitTime), u'平持', u'卖', exitPrice, pnl) resList.append(resDict) while (leg2 and shortTrade1): entryTrade = shortTrade1.popleft() volume = entryTrade.volume if self.mode == self.TICK_MODE: exitTime = self.tick1.datetime exitPrice = self.tick1.askPrice1 else: exitTime = self.bar1.datetime exitPrice = self.bar1.close if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) pnl = pnlDict[exitTime].pnl else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) pnl = pnlDict[exitTime].pnl resDict = self.makeRecord(entryTrade.tradeTime, u'开持', u'卖', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(str(exitTime), u'平持', u'买', exitPrice, pnl) resList.append(resDict) while (leg2 and longTrade1): entryTrade = longTrade1.popleft() volume = entryTrade.volume if self.mode == self.TICK_MODE: exitTime = self.tick1.datetime exitPrice = self.tick1.bidPrice1 else: exitTime = self.bar.datetime exitPrice = self.bar.close if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) pnl = pnlDict[exitTime].pnl resDict = self.makeRecord(entryTrade.tradeTime, u'开持', u'买', entryTrade.price, pnl) resList.append(resDict) resDict = self.makeRecord(exitTime, u'平持', u'卖', exitPrice, pnl) resList.append(resDict) timeList = [] resultList = [] pnlDict0 = sorted(pnlDict.iteritems(), key=lambda d: d[0]) for k, v in pnlDict0: timeList.append(k) resultList.append(v) timeList = [] pnlList = [] capital = 0 maxCapital = 0 drawdown = 0 totalResult = 0 totalTurnover = 0 totalCommission = 0 totalSlippage = 0 capitalList = [] drawdownList = [] winningResult = 0 losingResult = 0 totalWinning = 0 totalLosing = 0 for result in resultList: capital += result.pnl maxCapital = max(capital + result.posPnl, maxCapital) drawdown = round(capital + result.posPnl - maxCapital, 2) pnlList.append(result.pnl) timeList.append(result.exitDt) capitalList.append(capital + result.posPnl) drawdownList.append(drawdown) totalResult += 1 totalTurnover += result.turnover totalCommission += result.commission totalSlippage += result.slippage if result.pnl >= 0: winningResult += 1 totalWinning += result.pnl else: losingResult += 1 totalLosing += result.pnl if totalResult: winningRate = winningResult * 1.0 / totalResult * 100 else: winningRate = 0 averageWinning = 0 averageLosing = 0 profitLossRatio = 0 if winningResult: averageWinning = totalWinning / winningResult else: averageWinning = 0 if losingResult: averageLosing = totalLosing / losingResult else: averageLosing = 0 if averageLosing: profitLossRatio = -averageWinning / averageLosing else: profitLossRatio = 0 d = {} d['capital'] = capital d['maxCapital'] = maxCapital d['drawdown'] = drawdown d['totalResult'] = totalResult d['totalTurnover'] = totalTurnover d['totalCommission'] = totalCommission d['totalSlippage'] = totalSlippage d['timeList'] = timeList d['pnlList'] = pnlList d['capitalList'] = capitalList d['drawdownList'] = drawdownList d['winningRate'] = winningRate d['averageWinning'] = averageWinning d['averageLosing'] = averageLosing d['profitLossRatio'] = profitLossRatio d['resList'] = resList return d def calcPosPNL(self, tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2): """ 根据市场快照,计算每笔成交时间的持仓盈亏(按对价结算并扣除了手续费和滑点) """ return 0 allPos0 = len(shortTrade) + len(longTrade) if allPos0 == 0: return 0 pnlDict = OrderedDict() if tradeID in self.tradeSnap: tick = self.tradeSnap[tradeID] tick1 = self.tradeSnap1[tradeID] elif tradeID in self.trade1Snap: tick = self.trade1Snap[tradeID] tick1 = self.trade1Snap1[tradeID] else: tick = self.tradeSnap[tradeID] tick1 = self.tradeSnap1[tradeID] for entryTrade in shortTrade: volume = entryTrade.volume exitTime = tick.datetime exitPrice = tick.askPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) for entryTrade in longTrade: volume = entryTrade.volume exitTime = tick.datetime exitPrice = tick.bidPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) for entryTrade in shortTrade1: volume = entryTrade.volume exitTime = tick1.datetime exitPrice = tick1.askPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) for entryTrade in longTrade1: volume = entryTrade.volume exitTime = tick1.datetime exitPrice = tick1.bidPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) result = 0 for v in pnlDict.values(): result += v.pnl return result def calcPosPNL1(self, tradeID, shortTrade, longTrade, shortTrade1, longTrade1, leg2): """ 根据市场快照,计算每笔成交时间的持仓盈亏(按对价结算并扣除了手续费和滑点) """ return 0 allPos1 = len(shortTrade1) + len(longTrade1) if allPos1 == 0: return 0 pnlDict = OrderedDict() if tradeID in self.trade1Snap: tick = self.trade1Snap[tradeID] tick1 = self.trade1Snap1[tradeID] elif tradeID in self.tradeSnap: tick = self.tradeSnap[tradeID] tick1 = self.tradeSnap1[tradeID] else: return 0 for entryTrade in shortTrade: volume = entryTrade.volume exitTime = tick.datetime exitPrice = tick.askPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate, self.slippage, self.size) for entryTrade in longTrade: volume = entryTrade.volume exitTime = tick.datetime exitPrice = tick.bidPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) elif leg2: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate, self.slippage, self.size) for entryTrade in shortTrade1: volume = entryTrade.volume exitTime = tick1.datetime exitPrice = tick1.askPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, -volume, self.rate1, self.slippage1, self.size1) for entryTrade in longTrade1: volume = entryTrade.volume exitTime = tick1.datetime exitPrice = tick1.bidPrice1 if exitTime not in pnlDict: pnlDict[exitTime] = TradingResult(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) else: pnlDict[exitTime].add(entryTrade.price, entryTrade.dt, exitPrice, exitTime, volume, self.rate1, self.slippage1, self.size1) result = 0 for v in pnlDict.values(): result += v.pnl return result def showBacktestingResult(self): """ 显示回测结果 """ d = self.calculateBacktestingResult() timeList = d['timeList'] pnlList = d['pnlList'] capitalList = d['capitalList'] drawdownList = d['drawdownList'] resList = d['resList'] self.output(u' ') self.output('-' * 30) self.output(u'显示回测结果') if len(resList) > 1: import codecs if os.path.exists('./ctaStrategy/opResults/'): filepath = './ctaStrategy/opResults/' else: filepath = './opResults/' settingFileName = filepath + self.strategy.name + '.json' f = codecs.open(settingFileName, 'w', 'utf-8') f.write(json.dumps(resList, indent=1, ensure_ascii=False)) f.close() if len(timeList) > 0: self.output(u'第一笔交易:\t%s' % d['timeList'][0]) self.output(u'最后一笔交易:\t%s' % d['timeList'][-1]) self.output(u'总交易次数:\t%s' % formatNumber(d['totalResult'])) self.output(u'总盈亏:\t%s' % formatNumber(d['capital'])) self.output(u'最大回撤: \t%s' % formatNumber(min(d['drawdownList']))) self.output(u'平均每笔盈利:\t%s' % formatNumber(d['capital'] / d['totalResult'])) self.output(u'平均每笔滑点:\t%s' % formatNumber(d['totalSlippage'] / d['totalResult'])) self.output(u'平均每笔佣金:\t%s' % formatNumber(d['totalCommission'] / d['totalResult'])) self.output(u'胜率\t\t%s%%' % formatNumber(d['winningRate'])) self.output(u'平均每笔盈利\t%s' % formatNumber(d['averageWinning'])) self.output(u'平均每笔亏损\t%s' % formatNumber(d['averageLosing'])) self.output(u'盈亏比:\t%s' % formatNumber(d['profitLossRatio'])) lastTime = None lastCap = 0 lastDayCap = 0 lastDraw = 0 for (time, cap, drawdown) in zip(timeList, capitalList, drawdownList): if lastTime and time.day != lastTime.day: capData = CtaCapData() capData.name = self.strategy.name capData.datetime = lastTime capData.start = self.dataStartDate capData.date = capData.datetime.replace(hour=0, minute \ =0, second=0, microsecond=0) capData.cap = lastCap capData.pnl = lastCap - lastDayCap capData.drawdown = lastDraw self.insertCap(CAPITAL_DB_NAME, self.strategy.name, capData) lastDayCap = lastCap lastTime = time lastCap = cap lastDraw = drawdown capData = CtaCapData() capData.name = self.strategy.name capData.datetime = lastTime capData.start = self.dataStartDate capData.date = capData.datetime.replace(hour=0, minute \ =0, second=0, microsecond=0) capData.cap = lastCap capData.pnl = lastCap - lastDayCap capData.drawdown = lastDraw self.insertCap(CAPITAL_DB_NAME, self.strategy.name, capData) import matplotlib.pyplot as plt from matplotlib.dates import AutoDateLocator, DateFormatter plt.close() autodates = AutoDateLocator() yearsFmt = DateFormatter('%m-%d') pCapital = plt.subplot(3, 1, 1) pCapital.set_ylabel("capital") pCapital.plot(timeList, capitalList) plt.title(self.strategy.name) plt.gcf().autofmt_xdate() plt.gcf().subplots_adjust(bottom=0.1) plt.gca().xaxis.set_major_locator(autodates) plt.gca().xaxis.set_major_formatter(yearsFmt) pDD = plt.subplot(3, 1, 2) pDD.set_ylabel("DD") pDD.bar(range(len(drawdownList)), drawdownList) pPnl = plt.subplot(3, 1, 3) pPnl.set_ylabel("pnl") pPnl.hist(pnlList, bins=20) plt.show() def insertCap(self, dbName, collectionName, d): """插入数据到数据库(这里的data可以是CtaTickData或者CtaBarData)""" host, port, logging = loadMongoSetting() if not self.dbClient: self.dbClient = pymongo.MongoClient(host, port, socketKeepAlive=True) db = self.dbClient[dbName] collection = db[collectionName] collection.ensure_index([('date', pymongo.ASCENDING)], unique=True) flt = {'date': d.date} collection.update_one(flt, {'$set': d.__dict__}, upsert=True) def showBacktestingResult_nograph(self, filepath): """ 显示回测结果 """ d = self.calculateBacktestingResult() timeList = d['timeList'] pnlList = d['pnlList'] capitalList = d['capitalList'] drawdownList = d['drawdownList'] self.output(u'显示回测结果') if len(timeList) > 0: self.output('-' * 30) self.output(u'第一笔交易:\t%s' % d['timeList'][0]) self.output(u'最后一笔交易:\t%s' % d['timeList'][-1]) self.output(u'总交易次数:\t%s' % formatNumber(d['totalResult'])) self.output(u'总盈亏:\t%s' % formatNumber(d['capital'])) self.output(u'最大回撤: \t%s' % formatNumber(min(d['drawdownList']))) self.output(u'平均每笔盈利:\t%s' % formatNumber(d['capital'] / d['totalResult'])) self.output(u'平均每笔滑点:\t%s' % formatNumber(d['totalSlippage'] / d['totalResult'])) self.output(u'平均每笔佣金:\t%s' % formatNumber(d['totalCommission'] / d['totalResult'])) self.output(u'胜率\t\t%s%%' % formatNumber(d['winningRate'])) self.output(u'平均每笔盈利\t%s' % formatNumber(d['averageWinning'])) self.output(u'平均每笔亏损\t%s' % formatNumber(d['averageLosing'])) self.output(u'盈亏比:\t%s' % formatNumber(d['profitLossRatio'])) self.output(u'显示回测结果') lastTime = None lastCap = 0 lastDayCap = 0 lastDraw = 0 for (time, cap, drawdown) in zip(timeList, capitalList, drawdownList): if lastTime and time.day != lastTime.day: capData = CtaCapData() capData.name = self.strategy.name capData.datetime = lastTime capData.start = self.dataStartDate capData.date = capData.datetime.replace(hour=0, minute \ =0, second=0, microsecond=0) capData.cap = lastCap capData.pnl = lastCap - lastDayCap capData.drawdown = lastDraw self.insertCap(CAPITAL_DB_NAME, self.strategy.name, capData) lastDayCap = lastCap lastTime = time lastCap = cap lastDraw = drawdown import matplotlib matplotlib.use('Qt4Agg') import matplotlib.pyplot as plt from matplotlib.dates import AutoDateLocator, DateFormatter autodates = AutoDateLocator() yearsFmt = DateFormatter('%m-%d') pCapital = plt.subplot(3, 1, 1) pCapital.set_ylabel("capital") pCapital.plot(timeList, capitalList) plt.gcf().autofmt_xdate() plt.gcf().subplots_adjust(bottom=0.1) plt.gca().xaxis.set_major_locator(autodates) plt.gca().xaxis.set_major_formatter(yearsFmt) pDD = plt.subplot(3, 1, 2) pDD.set_ylabel("DD") pDD.bar(range(len(drawdownList)), drawdownList) pPnl = plt.subplot(3, 1, 3) pPnl.set_ylabel("pnl") pPnl.hist(pnlList, bins=20) plt.savefig(filepath) plt.close() def putStrategyEvent(self, name): """发送策略更新事件,回测中忽略""" pass def confSettle(self, name): """确认结算单,回测中忽略""" pass def setSlippage(self, slippage): """设置滑点""" self.slippage = slippage def setSlippage1(self, slippage): """设置滑点""" self.slippage1 = slippage def setSize(self, size): """设置合约大小""" self.size = size def setSize1(self, size): """设置合约大小""" self.size1 = size def setRate(self, rate): """设置佣金比例""" self.rate = rate def setRate1(self, rate): """设置佣金比例""" self.rate1 = rate def setLeverage(self, leverage): """设置杠杆比率""" self.leverage = leverage def setLeverage1(self, leverage): """设置杠杆比率""" self.leverage1 = leverage def setPrice(self, price): """设置合约大小""" self.mPrice = price def setPrice1(self, price): """设置合约大小""" self.mPrice1 = price def loadTick(self, dbName, collectionName, days): """从数据库中读取Tick数据,startDate是datetime对象""" startDate = datetime.now() d = {'datetime': {'$lte': startDate}} host, port, logging = loadMongoSetting() client = pymongo.MongoClient(host, port) collection = client[dbName][collectionName] cursor = collection.find(d).limit(days * 10 * 60 * 120) l = [] if cursor: for d in cursor: tick = CtaTickData() tick.__dict__ = d l.append(tick) return l def loadBar(self, dbName, collectionName, days): """从数据库中读取Bar数据,startDate是datetime对象""" startDate = datetime.now() d = {'datetime': {'$lte': startDate}} host, port, logging = loadMongoSetting() client = pymongo.MongoClient(host, port) collection = client[dbName][collectionName] cursor = collection.find(d).limit(days * 10 * 60) l = [] if cursor: for d in cursor: bar = CtaBarData() bar.__dict__ = d l.append(bar) return l def runOptimization(self, strategyClass, setting_c, optimizationSetting): """串行优化""" settingList = optimizationSetting.generateSetting() targetName = optimizationSetting.optimizeTarget if not settingList or not targetName: self.output(u'优化设置有问题,请检查') vtSymbol = setting_c['vtSymbol'] if 'vtSymbol1' in setting_c: vtSymbol1 = setting_c['vtSymbol1'] else: vtSymbol1 = None resultList = [] opResults = [] for setting in settingList: self.clearBacktestingResult() self.loadHistoryData(TICK_DB_NAME, vtSymbol) if vtSymbol1: self.loadHistoryData1(TICK_DB_NAME, vtSymbol1) self.output('-' * 30) self.output('setting: %s' % str(setting)) self.initStrategy(strategyClass, setting_c) self.strategy.onUpdate(setting) self.runBacktesting() opResult = {} d = self.calculateBacktestingResult() for key in setting: opResult[key] = setting[key] opResult['totalResult'] = d['totalResult'] opResult['capital'] = d['capital'] if d['totalResult'] > 0: opResult['maxDrawdown'] = min(d['drawdownList']) opResult['winPerT'] = d['capital'] / d['totalResult'] opResult['splipPerT'] = d['totalSlippage'] / d['totalResult'] opResult['commiPerT'] = d['totalCommission'] / d['totalResult'] else: opResult['maxDrawdown'] = 0 opResult['winPerT'] = 0 opResult['splipPerT'] = 0 opResult['commiPerT'] = 0 opResult['winningRate'] = d['winningRate'] opResult['averageWinning'] = d['averageWinning'] opResult['averageLosing'] = d['averageLosing'] opResult['profitLossRatio'] = d['profitLossRatio'] try: targetValue = d[targetName] except KeyError: targetValue = 0 resultList.append(([str(setting)], targetValue)) opResults.append(opResult) if os.path.exists('./ctaStrategy/opResults/'): filepath = './ctaStrategy/opResults/' else: filepath = './opResults/' with open(filepath + self.strategy.name + '.csv', 'wb') as csvfile: fieldnames = opResult.keys() writer = csv.DictWriter(csvfile, fieldnames) writer.writeheader() for opDict in opResults: writer.writerow(opDict) resultList.sort(reverse=True, key=lambda result: result[1]) self.output('-' * 30) self.output(u'优化结果:') for result in resultList: self.output(u'%s: %s' % (result[0], result[1])) return result def clearBacktestingResult(self): """清空之前回测的结果""" self.dt = None self.backtestingData = deque([]) self.backtestingData1 = deque([]) self.tick = None self.tick1 = None self.bar = None self.bar1 = None self.lasttick = None self.lasttick1 = None self.logList = [] self.limitOrderCount = 0 self.limitOrderDict.clear() self.limitOrderDict1.clear() self.workingLimitOrderDict.clear() self.workingLimitOrderDict1.clear() self.orderPrice = {} self.orderVolume = {} self.orderPrice1 = {} self.orderVolume1 = {} self.stopOrderCount = 0 self.stopOrderDict.clear() self.workingStopOrderDict.clear() self.tradeCount = 0 self.tradeDict.clear() self.tradeSnap.clear() self.tradeSnap1.clear() self.tradeCount1 = 0 self.tradeDict1.clear() self.trade1Snap.clear() self.trade1Snap1.clear() cktesting() engine.showBacktestingResult() sys.stdout = output_s def runParallelOptimization(setting_c, optimizationSetting, optimism=False, startTime='', endTime='', slippage=0, mode='T'): """并行优化参数""" global p global currentP print('-' * 30) print(u'开始优化策略 : ' + setting_c['name']) settingList = optimizationSetting.generateSetting() print(u'总共' + str(len(settingList)) + u'个优化') targetName = optimizationSetting.optimizeTarget p = ProgressBar(maxval=len(settingList)) p.start() currentP = 0 if not settingList or not targetName: print(u'优化设置有问题,请检查') pool = multiprocessing.Pool(processes=multiprocessing.cpu_count() - 1) l = [] for setting in settingList: l.append(pool.apply_async(optimize, args=(setting_c, setting, targetName, optimism, startTime, endTime, slippage, mode), callback=showProcessBar)) pool.close() pool.join() p.finish() resultList = [res.get() for res in l] print('-' * 30) print(u'优化结果:') if os.path.exists('./strategy/opResults/'): filepath = './strategy/opResults/' else: filepath = './opResults/' with open(filepath + setting_c['name'] + '.csv', 'wb') as csvfile: fieldnames = resultList[0][1].keys() fieldnames.sort() writer = csv.DictWriter(csvfile, fieldnames) writer.writeheader() setting_t = {} value_t = -99999 for (setting, opDict) in resultList: writer.writerow(opDict) if opDict[targetName] > value_t: setting_t = setting value_t = opDict[targetName] print(str(setting_t) + ':' + str(value_t)) print(u'优化结束') print(u' ') def showProcessBar(result): """显示进度条""" global p global currentP currentP += 1 p.update(currentP) def getSetting(name): """获取策略基础配置""" setting_c = {} settingFileName = './CTA_setting1.json' with open(settingFileName) as f: l = json.load(f) for setting in l: if setting['name'] == name: setting_c = setting setting_c[u'backtesting'] = True return setting_c def formatNumber(n): """格式化数字到字符串""" rn = round(n, 2) return format(rn, ',') def optimize(setting_c, setting, targetName, optimism, startTime='', endTime='', slippage=0, mode='T'): """多进程优化时跑在每个进程中运行的函数""" setting_c[u'backtesting'] = True from strategy import STRATEGY_CLASS from ctaBacktesting1 import BacktestingEngine vtSymbol = setting_c[u'vtSymbol'] if u'vtSymbol1' in setting_c: vtSymbol1 = setting_c[u'vtSymbol1'] else: vtSymbol1 = None className = setting_c[u'className'] if os.path.exists("CTA_v_setting.json"): fileName = "CTA_v_setting.json" else: fileName = "../CTA_v_setting.json" with open(fileName) as f: l = json.load(f) for setting_x in l: name = setting_x[u'name'] match = re.search('^' + name + '[0-9]', vtSymbol) if match: rate = setting_x[u'mRate'] price = setting_x[u'mPrice'] size = setting_x[u'mSize'] level = setting_x[u'mLevel'] if vtSymbol1: match = re.search('^' + name + '[0-9]', vtSymbol1) if match: rate1 = setting_x[u'mRate'] price1 = setting_x[u'mPrice'] size1 = setting_x[u'mSize'] level1 = setting_x[u'mLevel'] name = setting_c[u'name'] engine = BacktestingEngine() engine.plot = True engine.optimism = optimism if mode == 'T': engine.setBacktestingMode(engine.TICK_MODE) dbName = TICK_DB_NAME elif mode == 'B': engine.setBacktestingMode(engine.BAR_MODE) dbName = MINUTE_DB_NAME elif mode == 'D': engine.setBacktestingMode(engine.BAR_MODE) dbName = DAILY_DB_NAME if not startTime: startTime = str(setting_c[u'StartTime']) if not endTime: endTime = str(setting_c[u'EndTime']) engine.setStartDate(startTime) engine.setEndDate(endTime) engine.loadHistoryData(dbName, vtSymbol) if vtSymbol1: engine.loadHistoryData1(dbName, vtSymbol1) engine.setSlippage(slippage) engine.setLeverage(level) engine.setSize(size) engine.setRate(rate) engine.setPrice(price) if vtSymbol1: engine.setSize1(size1) engine.setRate1(rate1) engine.setPrice1(price1) else: engine.setSize1(size) engine.setRate1(rate) engine.setPrice1(price) engine.initStrategy(STRATEGY_CLASS[className], setting_c) engine.strategy.onUpdate(setting) engine.runBacktesting() opResult = {} d = engine.calculateBacktestingResult() try: targetValue = d[targetName] except KeyError: targetValue = 0 for key in setting: opResult[key] = setting[key] opResult['totalResult'] = d['totalResult'] opResult['capital'] = round(d['capital'], 2) if d['totalResult'] > 0: opResult['maxDrawdown'] = min(d['drawdownList']) opResult['winPerT'] = round(d['capital'] / d['totalResult'], 2) opResult['splipPerT'] = round(d['totalSlippage'] / d['totalResult'], 2) opResult['commiPerT'] = round(d['totalCommission'] / d['totalResult'], 2) else: opResult['maxDrawdown'] = 0 opResult['winPerT'] = 0 opResult['splipPerT'] = 0 opResult['commiPerT'] = 0 opResult['winningRate'] = round(d['winningRate'], 2) opResult['averageWinning'] = round(d['averageWinning'], 2) opResult['averageLosing'] = round(d['averageLosing'], 2) opResult['profitLossRatio'] = round(d['profitLossRatio'], 2) return (setting, opResult) if __name__ == '__main__': """读取策略配置""" begin = datetime.now() name = 'spread' setting_c = getSetting(name) opt = False print(u'即将开始优化回测,请确认下面的信息正确后开始回测:') print(u'1.回测引擎是正确的稳定版本') print(u'2.(乐观\悲观)模式选择正确') print(u'3.策略逻辑正确') print(u'4.策略参数初始化无遗漏') print(u'5.策略参数传递无遗漏') print(u'6.策略单次回测交割单检查正确') print(u'7.参数扫描区间合理') print(u'8.关闭结果文件') print(u'y/n:') choice = raw_input(u'') if not choice == 'y': exit(0) backtesting(setting_c, StartTime= "2017-05-19 21:01:00", EndTime = "2017-06-19 15:00:00", optimism=opt, mode='B') end = datetime.now() print(u'回测用时: ' + str(end - begin))
false
true
f72a55db61c854785fc42c069c7252d364540690
23,064
py
Python
main.py
mpast/earth-engine-app
496fc6cfe95403a42374e439a4027c09760af964
[ "Apache-2.0" ]
2
2018-06-19T20:33:32.000Z
2018-07-13T16:03:30.000Z
main.py
mpast/earth-engine-app
496fc6cfe95403a42374e439a4027c09760af964
[ "Apache-2.0" ]
1
2020-11-15T17:56:09.000Z
2020-11-15T17:56:09.000Z
main.py
mpast/earth-engine-app
496fc6cfe95403a42374e439a4027c09760af964
[ "Apache-2.0" ]
null
null
null
from flask import Flask, render_template, request import config import os import json import ee import time import calendar import datetime import threading import logging, logging.config, yaml from pymemcache.client.hash import Client #from google.appengine.api import memcache as mc ################################################################################################## # CONSTANT DEFINITIONS ################################################################################################## EE_CREDENTIALS = ee.ServiceAccountCredentials(config.EE_ACCOUNT, config.EE_PRIVATE_KEY_FILE) HIGH_COLLECTION_ID = 'srtm90_v4' LIGHTS_COLLECTION_ID = 'NOAA/DMSP-OLS/NIGHTTIME_LIGHTS' TEMPERATURE_COLLECTION_ID = 'MODIS/MOD11A2' REDUCTION_SCALE_METERS = 20000 COUNTRIES_FILE = 'static/countries.txt' COUNTRIES_PATH = 'static/countries/' DETAILS_PATH = 'static/details/' CACHE = 0 # When use memcache SAVE = 0 # When we save data to precompute it in details folder INITIAL_MAP = '5' #logging #LOGGER_TYPE = 'file' LOGGER_TYPE = 'console' logging.config.dictConfig(yaml.load(open('logging.conf'))) logger = logging.getLogger(LOGGER_TYPE) ################################################################################################## # FUNCTIONS ################################################################################################## def json_serializer(key, value): if type(value) == str: return value, 1 return json.dumps(value), 2 def json_deserializer(key, value, flags): if flags == 1: return value if flags == 2: return json.loads(value) raise Exception('Unknown serialization format') mc = Client(('localhost', 11211), serializer = json_serializer, deserializer = json_deserializer) def createCountries(filename): file = open(filename, 'r') return file.read().splitlines() COUNTRIES_ID = createCountries(COUNTRIES_FILE) def change_dict(dct): if 'features' in dct: return dct['features'][0] return dct # Add a band containing image date as years since 1991. def CreateTimeBand(img): year = ee.Date(img.get('system:time_start')).get('year').subtract(1991) return ee.Image(year).byte().addBands(img) def CreateTimeBandTemp(img): year = ee.Date(img.get('system:time_start')).get('year').subtract(2013) return ee.Image(year).byte().addBands(img) def GetFeature(country_id): """Returns an ee.Feature for the country with the given ID.""" if CACHE: try: geojson = mc.get('geojson_' + country_id) if geojson is not None: return ee.Feature(geojson) except Exception as e: logger.debug('Error GetFeature cache: ' + str(e)) # Note: The country IDs are read from the filesystem in the initialization path = COUNTRIES_PATH + country_id + '.geo.json' path = os.path.join(os.path.split(__file__)[0], path) try: with open(path, 'r') as f: t = f.read() elem = json.loads(t, object_hook = change_dict) if CACHE: mc.set('geojson_' + country_id, elem) f.close() return ee.Feature(elem) except Exception as e: logger.debug('Error GetFeature reading file ' + path) def coordsToFeature(coords): feature = json.loads(coords, object_hook = change_dict) return ee.Feature(feature) def GetMapFromId(id): if id == '0': return GetHighMap() elif id == '1': return GetLightsMap() elif id == '2': return GetTemperatureMap() elif id == '3': return GetWaterOccurrenceMap() elif id == '4': return GetWaterChangeMap() elif id == '5': return GetForestChangeMap() elif id == '6': return GetVegetationMap() else: raise Exception("Map does not exists") ################################################################################################## # HIGH MAP ################################################################################################## def GetHighMap(): return ee.Image(HIGH_COLLECTION_ID).getMapId({ 'min': '0', 'max': '1000', 'palette': '0000ff, 008000, ff0000' }) def ComputeCountryTimeSeriesHigh(country_id, feature = None, zoom = 1): """Returns mean elevation for the country.""" img = ee.Image(HIGH_COLLECTION_ID) img = img.select('elevation') scale = 50000 if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) feature = ee.Feature(None, { 'elevation': reduction.get('elevation') }) chart_data = feature.getInfo() return chart_data['properties'] ################################################################################################## # LIGHTS MAP ################################################################################################## def GetLightsMap(): """Returns the MapID for the night-time lights trend map.""" collection = ee.ImageCollection(LIGHTS_COLLECTION_ID) collection = collection.select('stable_lights').map(CreateTimeBand) # Fit a linear trend to the nighttime lights collection. fit = collection.reduce(ee.Reducer.linearFit()) return fit.getMapId({ 'min': '0', 'max': '0.18,20,-0.18', 'bands': 'scale,offset,scale', }) def ComputeCountryTimeSeriesLights(country_id, feature = None, zoom = 1): """Returns a series of brightness over time for the country.""" collection = ee.ImageCollection(LIGHTS_COLLECTION_ID) collection = collection.select('stable_lights').sort('system:time_start') scale = REDUCTION_SCALE_METERS if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean brightness in the region in each image. def ComputeMeanLights(img): reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) return ee.Feature(None, { 'stable_lights': reduction.get('stable_lights'), 'system:time_start': img.get('system:time_start') }) chart_data = collection.map(ComputeMeanLights).getInfo() # Extract the results as a list of lists. def ExtractMeanLights(feature): if 'stable_lights' in feature['properties'] and feature['properties']['stable_lights'] is not None: return [ feature['properties']['system:time_start'], feature['properties']['stable_lights'] ] return map(ExtractMeanLights, chart_data['features']) ################################################################################################## # TEMPERATURE MAP ################################################################################################## def GetTemperatureMap(): """Returns the MapID for the temperature map""" collection = ee.ImageCollection(TEMPERATURE_COLLECTION_ID) collection = collection.select('LST_Day_1km')#.map(CreateTimeBand) fit = collection.median().toFloat().multiply(ee.Image(0.02)).subtract(ee.Image(273.15)) return fit.getMapId({ 'min': '0', 'max': '40', 'palette':'0000ff,32cd32,ffff00,ff8c00,ff0000' }) def ComputeCountryTimeSeriesTemp(country_id, feature = None, zoom = 1): """Returns a series of surface temperature over time for the country.""" collection = ee.ImageCollection(TEMPERATURE_COLLECTION_ID) collection = collection.select('LST_Day_1km') scale = 30000 if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanTemp(img): reduction = img.reduceRegion(ee.Reducer.mean(),feature.geometry(), scale) return ee.Feature(None, { 'temperature': reduction.get('LST_Day_1km'), 'system:time_start': img.get('system:time_start') }) chart_data = collection.map(ComputeMeanTemp).getInfo() def toCelsius(kelvin): scale = 0.02 return kelvin * scale - 273.15 # Extract the results as a list of lists. def ExtractMeanTemp(feature): if 'temperature' in feature['properties'] and feature['properties']['temperature'] is not None: tempInCelsius = toCelsius(feature['properties']['temperature']) return [ feature['properties']['system:time_start'], tempInCelsius ] return map(ExtractMeanTemp, chart_data['features']) ################################################################################################## # WATER OCCURRENCE MAP ################################################################################################## def GetWaterOccurrenceMap(): img = ee.Image('JRC/GSW1_0/GlobalSurfaceWater') img = img.select('occurrence') return img.getMapId({ 'min': '0', 'max': '100', 'palette': 'ff0000,0000ff' }) def ComputeCountryTimeSeriesWaterOccurence(country_id, feature = None, zoom = 1): """Returns a series of water occurrence over time for the country.""" image = ee.Image('JRC/GSW1_0/GlobalSurfaceWater') image = image.select('change_abs') scale = REDUCTION_SCALE_METERS if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanWaterOccurence(img): reduction = img.reduceRegion(ee.Reducer.histogram(), feature.geometry(), scale) return ee.Feature(None, { 'system:time_start' : img.get('system:time_start'), 'water': reduction.get('change_abs') }) chart_data = ComputeMeanWaterOccurence(image).getInfo() return chart_data['properties']['water'] ################################################################################################## # WATER CHANGE MAP ################################################################################################## def GetWaterChangeMap(): img = ee.Image('JRC/GSW1_0/GlobalSurfaceWater') img = img.select('change_abs') return img.getMapId({ 'min': '-50', 'max': '50', 'palette': 'ff0000,000000,00ff00' }) def ComputeCountryTimeSeriesWaterChange(country_id, feature = None, zoom = 1): """Returns a series of water change over time for the country.""" collection = ee.ImageCollection('JRC/GSW1_0/YearlyHistory') collection = collection.select('waterClass') scale = REDUCTION_SCALE_METERS if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanWaterChange(img): reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) return ee.Feature(None, { 'system:time_start' : img.get('system:time_start'), 'water': reduction.get('waterClass') }) chart_data = collection.map(ComputeMeanWaterChange).getInfo() # Extract the results as a list of lists. def ExtractMeanWaterChange(feature): if 'water' in feature['properties'] and feature['properties']['water'] is not None: return [ feature['properties']['system:time_start'], feature['properties']['water'] ] return map(ExtractMeanWaterChange, chart_data['features']) ################################################################################################## # FOREST CHANGE MAP ################################################################################################## def GetForestChangeMap(): img = ee.Image('UMD/hansen/global_forest_change_2015') return img.getMapId({ 'bands': 'loss, treecover2000, gain', 'max': '1, 255, 1' }) def ComputeCountryTimeSeriesForestChange(country_id, feature = None, zoom = 1): """Returns country forest change.""" collection = ee.Image('UMD/hansen/global_forest_change_2015') scale = 14000 if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanForestChange(img): reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) return ee.Feature(None, { 'treecover2000' : reduction.get('treecover2000'), 'loss': reduction.get('loss'), 'gain': reduction.get('gain') }) chart_data = ComputeMeanForestChange(collection).getInfo() # Extract the results as a list of lists. def ExtractMeanForestChange(feature): if 'loss' in feature['properties'] and feature['properties']['loss'] is not None: return [ feature['properties']['treecover2000'], feature['properties']['gain'], feature['properties']['loss'] ] return ExtractMeanForestChange(chart_data) ################################################################################################## # VEGETATION INDEX MAP ################################################################################################## def GetVegetationMap(): img = ee.Image(ee.ImageCollection('MODIS/MCD43A4_NDVI').mean()) return img.getMapId({ 'min': '0', 'max': '1', 'palette' : 'FFFFFF,CC9966,CC9900,996600,33CC00,009900,006600,000000' }) def ComputeCountryTimeSeriesVegetation(country_id, feature = None, zoom = 1): """Returns a series of vegetation over time for the country.""" collection = ee.ImageCollection('MODIS/MCD43A4_NDVI') collection = collection.select('NDVI') scale = REDUCTION_SCALE_METERS if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanVegetation(img): reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) return ee.Feature(None, { 'system:time_start' : img.get('system:time_start'), 'NDVI': reduction.get('NDVI') }) chart_data = collection.map(ComputeMeanVegetation).getInfo() # Extract the results as a list of lists. def ExtractMeanVegetation(feature): if 'NDVI' in feature['properties'] and feature['properties']['NDVI'] is not None: return [ feature['properties']['system:time_start'], feature['properties']['NDVI'] ] return map(ExtractMeanVegetation, chart_data['features']) def ComputeCountryTimeSeries(map_id, country_id, feature = None, zoom = 1): """Returns a series of the specific map over time for the country.""" if map_id == '0': return ComputeCountryTimeSeriesHigh(country_id, feature, zoom) elif map_id == '1': return ComputeCountryTimeSeriesLights(country_id, feature, zoom) elif map_id == '2': return ComputeCountryTimeSeriesTemp(country_id, feature, zoom) elif map_id == '3': return ComputeCountryTimeSeriesWaterOccurence(country_id, feature, zoom) elif map_id == '4': return ComputeCountryTimeSeriesWaterChange(country_id, feature, zoom) elif map_id == '5': return ComputeCountryTimeSeriesForestChange(country_id, feature, zoom) elif map_id == '6': return ComputeCountryTimeSeriesVegetation(country_id, feature, zoom) else: raise Exception("Map type does not exists") ################################################################################################## # APP ROUTES ################################################################################################## # API app = Flask(__name__) app.jinja_env.auto_reload = True app.config.update( DEBUG=False, TEMPLATES_AUTO_RELOAD=False ) @app.before_request def before_request(): # When you import jinja2 macros, they get cached which is annoying for local # development, so wipe the cache every request. #app.jinja_env.cache = dict() # Initialize Earth Engine ee.Initialize(EE_CREDENTIALS) #ee.Initialize() # Define root route @app.route('/') def main(): mapid = GetMapFromId(INITIAL_MAP) # Add variables to the template template_values = { 'map': INITIAL_MAP, 'mapid': mapid['mapid'], 'token': mapid['token'], 'API_KEY': config.API_KEY, 'countries' : json.dumps(COUNTRIES_ID) } # Render the template index.html return render_template('index.html', values = template_values) @app.route('/map/<id>') def get(id): mapid = GetMapFromId(id) # Add variables to the template template_values = { 'map' : id, 'mapid': mapid['mapid'], 'token': mapid['token'], 'API_KEY': config.API_KEY, 'countries' : json.dumps(COUNTRIES_ID) } # Render the template reload.html return render_template('reload.html', values = template_values) @app.route('/save/<map_id>') def saveCountryTimeSeries(map_id): error = 0 message = '' if CACHE: elems = dict() if SAVE: path = DETAILS_PATH + 'mapid_' + map_id + '.json' details_file = open(path, 'w') else: thread = threading.Thread() thread.start() for country_id in COUNTRIES_ID: key = 'details' + '_'+ map_id + '_' + country_id details = dict() try: if map_id == '0' or map_id == '3': details = ComputeCountryTimeSeries(map_id, country_id) if details is not None: mc.set(key, json.dumps(details)) elif map_id == '5': details['forestChange'] = ComputeCountryTimeSeries(map_id, country_id) if details['forestChange'] is not None: mc.set(key, json.dumps(details)) else: details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, country_id)) if details['timeSeries'] is not None: mc.set(key, json.dumps(details)) elems[country_id] = details except Exception as e: error = 1 message = str(e) logger.debug('Error saveCountryTimeSeries: ' + message) if SAVE and not error: json.dump(elems, details_file , separators = (',', ':')) details_file.close() return json.dumps({'status' : error, 'message' : message}) @app.route('/static/<map_id>') def staticCountryTimeSeries(map_id): error = 0 message = '' if SAVE: elems = dict() path = DETAILS_PATH + 'mapid_' + map_id + '.json' details_file = open(path, 'w') for country_id in COUNTRIES_ID: key = 'details' + '_'+ map_id + '_' + country_id details = dict() try: if map_id == '0' or map_id == '3': details = ComputeCountryTimeSeries(map_id, country_id) if details is not None: elems[country_id] = details elif map_id == '5': details['forestChange'] = ComputeCountryTimeSeries(map_id, country_id) if details['forestChange'] is not None: elems[country_id] = details else: details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, country_id)) if details['timeSeries'] is not None: elems[country_id] = details except Exception as e: error = 1 message = str(e) logger.debug('Error saveCountryTimeSeries: ' + message) if not error: json.dump(elems, details_file , separators = (',', ':')) details_file.close() return json.dumps({'status' : error, 'message' : message}) @app.route('/details/<map_id>/<country_id>') def GetCountryTimeSeries(map_id, country_id): if CACHE: try: key = 'details' + '_'+ map_id + '_' + country_id details = mc.get(key) if details is not None: return details except Exception as e: logger.debug('Error cache GetCountryTimeSeries: ' + str(e)) details = dict() try: if map_id == '0' or map_id == '3': details = ComputeCountryTimeSeries(map_id, country_id) if CACHE and details is not None: mc.set(key, json.dumps(details)) elif map_id == '5': details['forestChange'] = ComputeCountryTimeSeries(map_id, country_id) if CACHE and details['forestChange'] is not None: mc.set(key, json.dumps(details)) else: details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, country_id)) if CACHE and details['timeSeries'] is not None: mc.set(key, json.dumps(details)) except ee.EEException as e: # Handle exceptions from the EE client library. details['error'] = str(e) logger.debug('Error GetCountryTimeSeries: ' + details['error']) # Send the results to the browser. return json.dumps(details) @app.route('/details/<map_id>') def GetAllCountriesDetails(map_id): if CACHE: try: key = 'details' + '_' + map_id countries = mc.get(key) if countries is not None: return countries except Exception as e: logger.debug('Error cache GetAllCountriesDetails' + str(e)) countries = list() for country_id in COUNTRIES_ID: try: key = 'details' + '_'+ map_id + '_' + country_id country = mc.get(key) except Exception as e: logger.debug('Error cache GetAllCountriesDetails: ' + country_id) try: if country is None: elem = {'name' : getCountryName(country_id), 'data' : ComputeCountryTimeSeries(map_id, country_id) } else: elem = {'name' : getCountryName(country_id), 'data' : country } countries.append(json.dumps(elem)) except Exception as e: logger.debug('Error GetAllCountriesDetails, country: ' + country_id + ' : ' + str(e)) key = 'details' + '_'+ map_id mc.set(key, json.dumps(countries)) else: countries = dict() countries['error'] = 'Not implemented yet' return json.dumps(countries) @app.route('/custom/<map_id>/<zoom>', methods = ['POST']) def GetCustomSeries(map_id, zoom): """Get time series from a custom polygon""" key = list(request.form.keys())[0] details = dict() try: feature = coordsToFeature(key) if feature is not None: try: zoom = int(zoom) if map_id == '0' or map_id == '3': details = ComputeCountryTimeSeries(map_id, None, feature, zoom) elif map_id == '5': details['forestChange'] = ComputeCountryTimeSeries(map_id, None, feature, zoom) else: details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, None, feature, zoom)) except ee.EEException as e: # Handle exceptions from the EE client library. details['error'] = str(e) logger.debug('Error GetCustomSeries: ' + details['error']) except Exception as e: details['error'] = str(e) logger.debug('Error GetCustomSeries: ' + details['error']) # Send the results to the browser. return json.dumps(details) @app.route('/country/<country_id>') def getCountryName(country_id): """Get country name from country id""" if CACHE: try: key = 'name_' + country_id name = mc.get(key) if name is not None: return name except Exception as e: logger.debug('Error cache getCountryName:' + str(e)) path = COUNTRIES_PATH + country_id + '.geo.json' path = os.path.join(os.path.split(__file__)[0], path) try: with open(path, 'r') as f: t = f.read() elem = json.loads(t, object_hook = change_dict) name = elem['properties']['name'] if CACHE and name is not None: mc.set(key, name) f.close() return name except Exception as e: logger.debug('Error getCountryName reading file ' + path + ' : ' + str(e)) # Run application in selected port if __name__ == '__main__': app.run('0.0.0.0', 8080, threaded=True)
32.995708
110
0.614161
from flask import Flask, render_template, request import config import os import json import ee import time import calendar import datetime import threading import logging, logging.config, yaml from pymemcache.client.hash import Client
true
true
f72a5625c654c8cd33973153b20dd9ad97e848d4
17,876
py
Python
pyeccodes/defs/grib2/tables/25/4_0_table.py
ecmwf/pyeccodes
dce2c72d3adcc0cb801731366be53327ce13a00b
[ "Apache-2.0" ]
7
2020-04-14T09:41:17.000Z
2021-08-06T09:38:19.000Z
pyeccodes/defs/grib2/tables/24/4_0_table.py
ecmwf/pyeccodes
dce2c72d3adcc0cb801731366be53327ce13a00b
[ "Apache-2.0" ]
null
null
null
pyeccodes/defs/grib2/tables/24/4_0_table.py
ecmwf/pyeccodes
dce2c72d3adcc0cb801731366be53327ce13a00b
[ "Apache-2.0" ]
3
2020-04-30T12:44:48.000Z
2020-12-15T08:40:26.000Z
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 1, 'code': 1, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time'}, {'abbr': 2, 'code': 2, 'title': 'Derived forecasts based on all ensemble members at a horizontal ' 'level or in a horizontal layer at a point in time'}, {'abbr': 3, 'code': 3, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'rectangular area at a horizontal level or in a horizontal layer at ' 'a point in time'}, {'abbr': 4, 'code': 4, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'circular area at a horizontal level or in a horizontal layer at a ' 'point in time'}, {'abbr': 5, 'code': 5, 'title': 'Probability forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 6, 'code': 6, 'title': 'Percentile forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 7, 'code': 7, 'title': 'Analysis or forecast error at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 8, 'code': 8, 'title': 'Average, accumulation, extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval'}, {'abbr': 9, 'code': 9, 'title': 'Probability forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 10, 'code': 10, 'title': 'Percentile forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 11, 'code': 11, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval'}, {'abbr': 12, 'code': 12, 'title': 'Derived forecasts based on all ensemble members at a horizontal ' 'level or in a horizontal layer, in a continuous or non-continuous ' 'interval'}, {'abbr': 13, 'code': 13, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'rectangular area, at a horizontal level or in a horizontal layer, ' 'in a continuous or non-continuous interval'}, {'abbr': 14, 'code': 14, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'circular area, at a horizontal level or in a horizontal layer, in ' 'a continuous or non-continuous interval'}, {'abbr': 15, 'code': 15, 'title': 'Average, accumulation, extreme values, or other statistically ' 'processed values over a spatial area at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 20, 'code': 20, 'title': 'Radar product'}, {'abbr': 30, 'code': 30, 'title': 'Satellite product', 'units': 'deprecated'}, {'abbr': 31, 'code': 31, 'title': 'Satellite product'}, {'abbr': 32, 'code': 32, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for simulated (synthetic) satellite data'}, {'abbr': 33, 'code': 33, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'simulated (synthetic) satellite data'}, {'abbr': 34, 'code': 34, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval for simulated (synthetic) satellite data'}, {'abbr': 35, 'code': 35, 'title': 'Satellite product with or without associated quality values'}, {'abbr': 40, 'code': 40, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents'}, {'abbr': 41, 'code': 41, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents'}, {'abbr': 42, 'code': 42, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for atmospheric ' 'chemical constituents'}, {'abbr': 43, 'code': 43, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical ' 'constituents'}, {'abbr': 44, 'code': 44, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for aerosol'}, {'abbr': 45, 'code': 45, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'aerosol'}, {'abbr': 46, 'code': 46, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for aerosol'}, {'abbr': 47, 'code': 47, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for aerosol'}, {'abbr': 48, 'code': 48, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for optical properties of aerosol'}, {'abbr': 49, 'code': 49, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'optical properties of aerosol'}, {'abbr': 51, 'code': 51, 'title': 'Categorical forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 53, 'code': 53, 'title': 'Partitioned parameters at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 54, 'code': 54, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'partitioned parameters'}, {'abbr': 55, 'code': 55, 'title': 'Spatio-temporal changing tiles at a horizontal level or horizontal ' 'layer at a point in time'}, {'abbr': 56, 'code': 56, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'spatio-temporal changing tile parameters', 'units': 'deprecated'}, {'abbr': 57, 'code': 57, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents ' 'based on a distribution function'}, {'abbr': 58, 'code': 58, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents based on a distribution ' 'function'}, {'abbr': 59, 'code': 59, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'spatio-temporal changing tile parameters', 'units': 'corrected version of template 4.56'}, {'abbr': 60, 'code': 60, 'title': 'Individual ensemble reforecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time'}, {'abbr': 61, 'code': 61, 'title': 'Individual ensemble reforecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous time interval'}, {'abbr': 62, 'code': 62, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for spatio-temporal ' 'changing tiles at a horizontal level or horizontal layer at a ' 'point in time'}, {'abbr': 63, 'code': 63, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for spatio-temporal changing tiles'}, {'abbr': 67, 'code': 67, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for atmospheric ' 'chemical constituents based on a distribution function'}, {'abbr': 68, 'code': 68, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical constituents ' 'based on a distribution function'}, {'abbr': 70, 'code': 70, 'title': 'Post-processing analysis or forecast at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 71, 'code': 71, 'title': 'Post-processing individual ensemble forecast, control and ' 'perturbed, at a horizontal level or in a horizontal layer at a ' 'point in time'}, {'abbr': 72, 'code': 72, 'title': 'Post-processing average, accumulation, extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval'}, {'abbr': 73, 'code': 73, 'title': 'Post-processing individual ensemble forecast, control and ' 'perturbed, at a horizontal level or in a horizontal layer, in a ' 'continuous or non-continuous time interval'}, {'abbr': 76, 'code': 76, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents ' 'with source/sink'}, {'abbr': 77, 'code': 77, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents with source/sink'}, {'abbr': 78, 'code': 78, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for atmospheric chemical constituents with source/sink'}, {'abbr': 79, 'code': 79, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical constituents ' 'with source/sink'}, {'abbr': 80, 'code': 80, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for optical properties of aerosol with ' 'source/sink'}, {'abbr': 81, 'code': 81, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'optical properties of aerosol with source/sink'}, {'abbr': 82, 'code': 82, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for aerosol with source/sink'}, {'abbr': 83, 'code': 83, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for aerosol with source/sink'}, {'abbr': 91, 'code': 91, 'title': 'Categorical forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 254, 'code': 254, 'title': 'CCITT IA5 character string'}, {'abbr': 1000, 'code': 1000, 'title': 'Cross-section of analysis and forecast at a point in time'}, {'abbr': 1001, 'code': 1001, 'title': 'Cross-section of averaged or otherwise statistically processed ' 'analysis or forecast over a range of time'}, {'abbr': 1002, 'code': 1002, 'title': 'Cross-section of analysis and forecast, averaged or otherwise ' 'statistically processed over latitude or longitude'}, {'abbr': 1100, 'code': 1100, 'title': 'Hovmoller-type grid with no averaging or other statistical ' 'processing'}, {'abbr': 1101, 'code': 1101, 'title': 'Hovmoller-type grid with averaging or other statistical ' 'processing'}, {'abbr': 50001, 'code': 50001, 'title': 'Forecasting Systems with Variable Resolution in a point in time'}, {'abbr': 50011, 'code': 50011, 'title': 'Forecasting Systems with Variable Resolution in a continous or non ' 'countinous time interval'}, {'abbr': 40033, 'code': 40033, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'simulated (synthetic) satellite data'}, {'abbr': 40034, 'code': 40034, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval for simulated (synthetic) satellite data'}, {'abbr': 65535, 'code': 65535, 'title': 'Missing'})
55.688474
91
0.519579
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 1, 'code': 1, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time'}, {'abbr': 2, 'code': 2, 'title': 'Derived forecasts based on all ensemble members at a horizontal ' 'level or in a horizontal layer at a point in time'}, {'abbr': 3, 'code': 3, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'rectangular area at a horizontal level or in a horizontal layer at ' 'a point in time'}, {'abbr': 4, 'code': 4, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'circular area at a horizontal level or in a horizontal layer at a ' 'point in time'}, {'abbr': 5, 'code': 5, 'title': 'Probability forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 6, 'code': 6, 'title': 'Percentile forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 7, 'code': 7, 'title': 'Analysis or forecast error at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 8, 'code': 8, 'title': 'Average, accumulation, extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval'}, {'abbr': 9, 'code': 9, 'title': 'Probability forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 10, 'code': 10, 'title': 'Percentile forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 11, 'code': 11, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval'}, {'abbr': 12, 'code': 12, 'title': 'Derived forecasts based on all ensemble members at a horizontal ' 'level or in a horizontal layer, in a continuous or non-continuous ' 'interval'}, {'abbr': 13, 'code': 13, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'rectangular area, at a horizontal level or in a horizontal layer, ' 'in a continuous or non-continuous interval'}, {'abbr': 14, 'code': 14, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'circular area, at a horizontal level or in a horizontal layer, in ' 'a continuous or non-continuous interval'}, {'abbr': 15, 'code': 15, 'title': 'Average, accumulation, extreme values, or other statistically ' 'processed values over a spatial area at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 20, 'code': 20, 'title': 'Radar product'}, {'abbr': 30, 'code': 30, 'title': 'Satellite product', 'units': 'deprecated'}, {'abbr': 31, 'code': 31, 'title': 'Satellite product'}, {'abbr': 32, 'code': 32, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for simulated (synthetic) satellite data'}, {'abbr': 33, 'code': 33, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'simulated (synthetic) satellite data'}, {'abbr': 34, 'code': 34, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval for simulated (synthetic) satellite data'}, {'abbr': 35, 'code': 35, 'title': 'Satellite product with or without associated quality values'}, {'abbr': 40, 'code': 40, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents'}, {'abbr': 41, 'code': 41, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents'}, {'abbr': 42, 'code': 42, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for atmospheric ' 'chemical constituents'}, {'abbr': 43, 'code': 43, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical ' 'constituents'}, {'abbr': 44, 'code': 44, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for aerosol'}, {'abbr': 45, 'code': 45, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'aerosol'}, {'abbr': 46, 'code': 46, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for aerosol'}, {'abbr': 47, 'code': 47, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for aerosol'}, {'abbr': 48, 'code': 48, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for optical properties of aerosol'}, {'abbr': 49, 'code': 49, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'optical properties of aerosol'}, {'abbr': 51, 'code': 51, 'title': 'Categorical forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 53, 'code': 53, 'title': 'Partitioned parameters at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 54, 'code': 54, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'partitioned parameters'}, {'abbr': 55, 'code': 55, 'title': 'Spatio-temporal changing tiles at a horizontal level or horizontal ' 'layer at a point in time'}, {'abbr': 56, 'code': 56, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'spatio-temporal changing tile parameters', 'units': 'deprecated'}, {'abbr': 57, 'code': 57, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents ' 'based on a distribution function'}, {'abbr': 58, 'code': 58, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents based on a distribution ' 'function'}, {'abbr': 59, 'code': 59, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'spatio-temporal changing tile parameters', 'units': 'corrected version of template 4.56'}, {'abbr': 60, 'code': 60, 'title': 'Individual ensemble reforecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time'}, {'abbr': 61, 'code': 61, 'title': 'Individual ensemble reforecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous time interval'}, {'abbr': 62, 'code': 62, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for spatio-temporal ' 'changing tiles at a horizontal level or horizontal layer at a ' 'point in time'}, {'abbr': 63, 'code': 63, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for spatio-temporal changing tiles'}, {'abbr': 67, 'code': 67, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for atmospheric ' 'chemical constituents based on a distribution function'}, {'abbr': 68, 'code': 68, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical constituents ' 'based on a distribution function'}, {'abbr': 70, 'code': 70, 'title': 'Post-processing analysis or forecast at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 71, 'code': 71, 'title': 'Post-processing individual ensemble forecast, control and ' 'perturbed, at a horizontal level or in a horizontal layer at a ' 'point in time'}, {'abbr': 72, 'code': 72, 'title': 'Post-processing average, accumulation, extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval'}, {'abbr': 73, 'code': 73, 'title': 'Post-processing individual ensemble forecast, control and ' 'perturbed, at a horizontal level or in a horizontal layer, in a ' 'continuous or non-continuous time interval'}, {'abbr': 76, 'code': 76, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents ' 'with source/sink'}, {'abbr': 77, 'code': 77, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents with source/sink'}, {'abbr': 78, 'code': 78, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for atmospheric chemical constituents with source/sink'}, {'abbr': 79, 'code': 79, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical constituents ' 'with source/sink'}, {'abbr': 80, 'code': 80, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for optical properties of aerosol with ' 'source/sink'}, {'abbr': 81, 'code': 81, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'optical properties of aerosol with source/sink'}, {'abbr': 82, 'code': 82, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for aerosol with source/sink'}, {'abbr': 83, 'code': 83, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for aerosol with source/sink'}, {'abbr': 91, 'code': 91, 'title': 'Categorical forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 254, 'code': 254, 'title': 'CCITT IA5 character string'}, {'abbr': 1000, 'code': 1000, 'title': 'Cross-section of analysis and forecast at a point in time'}, {'abbr': 1001, 'code': 1001, 'title': 'Cross-section of averaged or otherwise statistically processed ' 'analysis or forecast over a range of time'}, {'abbr': 1002, 'code': 1002, 'title': 'Cross-section of analysis and forecast, averaged or otherwise ' 'statistically processed over latitude or longitude'}, {'abbr': 1100, 'code': 1100, 'title': 'Hovmoller-type grid with no averaging or other statistical ' 'processing'}, {'abbr': 1101, 'code': 1101, 'title': 'Hovmoller-type grid with averaging or other statistical ' 'processing'}, {'abbr': 50001, 'code': 50001, 'title': 'Forecasting Systems with Variable Resolution in a point in time'}, {'abbr': 50011, 'code': 50011, 'title': 'Forecasting Systems with Variable Resolution in a continous or non ' 'countinous time interval'}, {'abbr': 40033, 'code': 40033, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'simulated (synthetic) satellite data'}, {'abbr': 40034, 'code': 40034, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval for simulated (synthetic) satellite data'}, {'abbr': 65535, 'code': 65535, 'title': 'Missing'})
true
true
f72a562854148934a239bcf74e1945d7133782f2
3,310
py
Python
Chapter05/Chapter_5/Chapter_5_5.py
YMandCL/Hands-On-Deep-Learning-for-Games
0225661409c3bf59ae6b7996c254bb485ebd10cb
[ "MIT" ]
33
2018-12-29T15:39:20.000Z
2022-03-18T14:36:11.000Z
Chapter05/Chapter_5/Chapter_5_5.py
YMandCL/Hands-On-Deep-Learning-for-Games
0225661409c3bf59ae6b7996c254bb485ebd10cb
[ "MIT" ]
4
2019-05-01T08:30:47.000Z
2020-08-14T21:13:53.000Z
Chapter05/Chapter_5/Chapter_5_5.py
YMandCL/Hands-On-Deep-Learning-for-Games
0225661409c3bf59ae6b7996c254bb485ebd10cb
[ "MIT" ]
14
2019-01-13T15:52:08.000Z
2021-10-10T06:14:39.000Z
# -*- coding: utf-8 -*- # source from https://github.com/keon/deep-q-learning/blob/master/dqn.py import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam EPISODES = 1000 class DQNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 # discount rate self.epsilon = 1.0 # exploration rate self.epsilon_min = 0.01 self.epsilon_decay = 0.995 self.learning_rate = 0.001 self.model = self._build_model() def _build_model(self): # Neural Net for Deep-Q learning Model model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation='linear')) model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return model def remember(self, state, action, reward, next_state, done): self.memory.append((state, action, reward, next_state, done)) def act(self, state): if np.random.rand() <= self.epsilon: return random.randrange(self.action_size) act_values = self.model.predict(state) return np.argmax(act_values[0]) # returns action def replay(self, batch_size): minibatch = random.sample(self.memory, batch_size) for state, action, reward, next_state, done in minibatch: target = reward if not done: target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0])) target_f = self.model.predict(state) target_f[0][action] = target self.model.fit(state, target_f, epochs=1, verbose=0) if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay def load(self, name): self.model.load_weights(name) def save(self, name): self.model.save_weights(name) if __name__ == "__main__": env = gym.make('MountainCar-v0') state_size = env.observation_space.shape[0] action_size = env.action_space.n agent = DQNAgent(state_size, action_size) # agent.load("./save/cartpole-dqn.h5") done = False batch_size = 32 for e in range(EPISODES): state = env.reset() state = np.reshape(state, [1, state_size]) for time in range(500): # env.render() action = agent.act(state) env.render() next_state, reward, done, _ = env.step(action) reward = reward if not done else -10 next_state = np.reshape(next_state, [1, state_size]) agent.remember(state, action, reward, next_state, done) state = next_state if done: print("episode: {}/{}, score: {}, e: {:.2}" .format(e, EPISODES, time, agent.epsilon)) break if len(agent.memory) > batch_size: agent.replay(batch_size) # if e % 10 == 0: # agent.save("./save/cartpole-dqn.h5")
35.978261
74
0.600302
import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam EPISODES = 1000 class DQNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 self.epsilon = 1.0 self.epsilon_min = 0.01 self.epsilon_decay = 0.995 self.learning_rate = 0.001 self.model = self._build_model() def _build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation='linear')) model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return model def remember(self, state, action, reward, next_state, done): self.memory.append((state, action, reward, next_state, done)) def act(self, state): if np.random.rand() <= self.epsilon: return random.randrange(self.action_size) act_values = self.model.predict(state) return np.argmax(act_values[0]) def replay(self, batch_size): minibatch = random.sample(self.memory, batch_size) for state, action, reward, next_state, done in minibatch: target = reward if not done: target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0])) target_f = self.model.predict(state) target_f[0][action] = target self.model.fit(state, target_f, epochs=1, verbose=0) if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay def load(self, name): self.model.load_weights(name) def save(self, name): self.model.save_weights(name) if __name__ == "__main__": env = gym.make('MountainCar-v0') state_size = env.observation_space.shape[0] action_size = env.action_space.n agent = DQNAgent(state_size, action_size) done = False batch_size = 32 for e in range(EPISODES): state = env.reset() state = np.reshape(state, [1, state_size]) for time in range(500): action = agent.act(state) env.render() next_state, reward, done, _ = env.step(action) reward = reward if not done else -10 next_state = np.reshape(next_state, [1, state_size]) agent.remember(state, action, reward, next_state, done) state = next_state if done: print("episode: {}/{}, score: {}, e: {:.2}" .format(e, EPISODES, time, agent.epsilon)) break if len(agent.memory) > batch_size: agent.replay(batch_size)
true
true
f72a56bc327beb68eaff0e6ebaf52a3e7b6095e4
1,956
py
Python
fastseq/ops/ngram_repeat_block.py
nttcs-ds/fastseq
f1338f1125612df318c9d1f030a8457397ed05a6
[ "MIT" ]
346
2020-11-28T14:25:21.000Z
2022-03-25T14:50:22.000Z
fastseq/ops/ngram_repeat_block.py
nttcs-ds/fastseq
f1338f1125612df318c9d1f030a8457397ed05a6
[ "MIT" ]
22
2020-12-03T18:52:04.000Z
2022-02-26T05:19:14.000Z
fastseq/ops/ngram_repeat_block.py
nttcs-ds/fastseq
f1338f1125612df318c9d1f030a8457397ed05a6
[ "MIT" ]
35
2020-11-30T21:37:45.000Z
2022-03-23T01:54:51.000Z
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ Wrapper for ngram_repeat_block cuda extension """ from torch import nn from torch.autograd import Function import ngram_repeat_block_cuda class NGramRepeatBlockFunction(Function): """ forward inputs to ngram_repeat_block cuda extension backward method not needed. """ def forward(self, tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size): """ Args: tokens(Tensor): Input tokens(Bsz*beam, seq_len) lprobs(Tensor): likelihood probability Expected to be updated in place.(Bsz*beam, vocab_size) bsz(int): batch size step(int): current step beam_size(int): beam size no_repeat_ngram_size(int): Ngram size """ outputs = ngram_repeat_block_cuda.forward(tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size) return outputs def backward (*args): raise NotImplementedError class NGramRepeatBlock(nn.Module): """ Wrapper class for calling ngram_repeat_block cuda extension """ def __init__(self): super(NGramRepeatBlock, self).__init__() def reset_parameters(self): pass def forward(self, tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size): """ Args: tokens(Tensor): Input tokens(Bsz*beam, seq_len) lprobs(Tensor): likelihood probability, Expected to be updated in place.(Bsz*beam, vocab_size) bsz(int): batch size step(int): current step beam_size(int): beam size no_repeat_ngram_size(int): Ngram size """ assert tokens.size(0) == bsz*beam_size assert lprobs.size(0) == bsz*beam_size tokens = tokens.contiguous() lprobs = lprobs.contiguous() return NGramRepeatBlockFunction.apply(tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size)
32.6
71
0.657975
from torch import nn from torch.autograd import Function import ngram_repeat_block_cuda class NGramRepeatBlockFunction(Function): def forward(self, tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size): outputs = ngram_repeat_block_cuda.forward(tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size) return outputs def backward (*args): raise NotImplementedError class NGramRepeatBlock(nn.Module): def __init__(self): super(NGramRepeatBlock, self).__init__() def reset_parameters(self): pass def forward(self, tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size): assert tokens.size(0) == bsz*beam_size assert lprobs.size(0) == bsz*beam_size tokens = tokens.contiguous() lprobs = lprobs.contiguous() return NGramRepeatBlockFunction.apply(tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size)
true
true
f72a57059f2c092dba9f5b18eb5c0724c3267d04
3,464
py
Python
app/cito_engine/views/tools.py
twatchy/cito_engine
a62dce3c76567dd36b7efcaa70e03728b335f44e
[ "Apache-2.0" ]
null
null
null
app/cito_engine/views/tools.py
twatchy/cito_engine
a62dce3c76567dd36b7efcaa70e03728b335f44e
[ "Apache-2.0" ]
null
null
null
app/cito_engine/views/tools.py
twatchy/cito_engine
a62dce3c76567dd36b7efcaa70e03728b335f44e
[ "Apache-2.0" ]
null
null
null
"""Copyright 2014 Cyrus Dasadia 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. """ from django.shortcuts import redirect, render_to_response from django.forms.formsets import formset_factory from django.contrib.auth.decorators import login_required from django.template import RequestContext from cito_engine.forms import tools_form, events @login_required(login_url='/login/') def bulk_upload_events(request): BulkEventsFormset = formset_factory(events.EventForm, extra=0) render_vars = dict() if request.method != 'POST': return redirect('/incidents/') else: # If we got a bunch of lines for events if 'list_of_items' in request.POST: list_of_events = request.POST.get('list_of_items') severity = request.POST.get('severity') category = request.POST.get('category') team = request.POST.get('team') initial_data = [] if list_of_events: for event_summary in list_of_events.splitlines(): initial_data.append({'summary': event_summary, 'description': event_summary, 'severity': severity, 'team': team, 'category': category, }) render_vars['formset'] = BulkEventsFormset(initial=initial_data) else: render_vars['errors'] = ['List was empty!'] # We got the formset elif 'form-INITIAL_FORMS' in request.POST: render_vars['formset'] = BulkEventsFormset(request.POST) user_teams = request.user.team_set.all() if render_vars['formset'].is_valid(): for form in render_vars['formset']: if form.cleaned_data.get('team') not in user_teams: render_vars['errors'] = ['Cannot add event for %s, you are not a member of this team.' % form.cleaned_data.get('team')] return render_to_response('bulk_upload.html', render_vars, context_instance=RequestContext(request)) else: form.save() return redirect('/events/') return render_to_response('bulk_upload.html', render_vars, context_instance=RequestContext(request)) @login_required(login_url='/login/') def show_bulk_upload_form(request, upload_item): form = tools_form.BulkUploadForm() render_vars = dict() render_vars['form'] = form render_vars['box_title'] = 'Bulk add events' render_vars['page_title'] = 'Bulk add events' if upload_item == 'events': render_vars['form_action'] = '/tools/bulkupload/events/confirm/' return render_to_response('generic_form.html', render_vars, context_instance=RequestContext(request))
44.987013
112
0.618938
from django.shortcuts import redirect, render_to_response from django.forms.formsets import formset_factory from django.contrib.auth.decorators import login_required from django.template import RequestContext from cito_engine.forms import tools_form, events @login_required(login_url='/login/') def bulk_upload_events(request): BulkEventsFormset = formset_factory(events.EventForm, extra=0) render_vars = dict() if request.method != 'POST': return redirect('/incidents/') else: if 'list_of_items' in request.POST: list_of_events = request.POST.get('list_of_items') severity = request.POST.get('severity') category = request.POST.get('category') team = request.POST.get('team') initial_data = [] if list_of_events: for event_summary in list_of_events.splitlines(): initial_data.append({'summary': event_summary, 'description': event_summary, 'severity': severity, 'team': team, 'category': category, }) render_vars['formset'] = BulkEventsFormset(initial=initial_data) else: render_vars['errors'] = ['List was empty!'] elif 'form-INITIAL_FORMS' in request.POST: render_vars['formset'] = BulkEventsFormset(request.POST) user_teams = request.user.team_set.all() if render_vars['formset'].is_valid(): for form in render_vars['formset']: if form.cleaned_data.get('team') not in user_teams: render_vars['errors'] = ['Cannot add event for %s, you are not a member of this team.' % form.cleaned_data.get('team')] return render_to_response('bulk_upload.html', render_vars, context_instance=RequestContext(request)) else: form.save() return redirect('/events/') return render_to_response('bulk_upload.html', render_vars, context_instance=RequestContext(request)) @login_required(login_url='/login/') def show_bulk_upload_form(request, upload_item): form = tools_form.BulkUploadForm() render_vars = dict() render_vars['form'] = form render_vars['box_title'] = 'Bulk add events' render_vars['page_title'] = 'Bulk add events' if upload_item == 'events': render_vars['form_action'] = '/tools/bulkupload/events/confirm/' return render_to_response('generic_form.html', render_vars, context_instance=RequestContext(request))
true
true
f72a57198e6603c64c6e5c49c3cd88238e30804e
11,932
py
Python
Pseudo_Goldstone/SUN_def/SUN_def.py
dkaramit/pseudo-Goldstone_DM
70fbb4ad4be190226d230a20dfb19b804e15aae6
[ "MIT" ]
null
null
null
Pseudo_Goldstone/SUN_def/SUN_def.py
dkaramit/pseudo-Goldstone_DM
70fbb4ad4be190226d230a20dfb19b804e15aae6
[ "MIT" ]
null
null
null
Pseudo_Goldstone/SUN_def/SUN_def.py
dkaramit/pseudo-Goldstone_DM
70fbb4ad4be190226d230a20dfb19b804e15aae6
[ "MIT" ]
null
null
null
from sympy import sqrt, Symbol,symbols,conjugate,I,flatten,simplify,expand from numpy import array,arange,triu,tril,nonzero,append,unique, vectorize,sum,prod from ..util import MatrixProd,Deriv,Tuples def GetAssumptions(Sym,assL): tmpA=[] for i in assL: try: tmpA.append(Sym.assumptions0[i] ) except: tmpA.append(None ) return tmpA def Definitions(DimN, Gauge,Diag=False): global gauge, dimN dimN,gauge=DimN,Gauge global sqrt2,dimRange, mPhi2, mPhip2, v, vPhi, muH, lamH, lamHPhi, lamPhi mPhi2=array( symbols('mPhi2(1:{})(1:{})'.format(str(dimN+1),str(dimN+1)),complex=True,real=False ) ).reshape(dimN,dimN) mPhi2[dimN-1][dimN-1]=Symbol('mPhi2{}{}'.format(dimN,dimN),real=True )#this is real, due to the minimization conditions mPhip2=array( symbols('mPhip2(1:{})(1:{})'.format(str(dimN+1),str(dimN+1)),complex=True,real=False ) ).reshape(dimN,dimN) #make mPhi symmetric (faster than numpy.triu(mPhi,+1).T+numpy.triu(mPhi)) for i in range(dimN): for j in range(i+1,dimN): mPhi2[j][i]=mPhi2[i][j] #make mPhip hermitian (faster than numpyconjugate(numpy.triu(mPhi,+1).T)+numpy.triu(mPhi)) for i in range(dimN): for j in range(i+1,dimN): mPhip2[j][i]=conjugate(mPhip2[i][j]) #make the diagonal real. keep in mind that the squared elements of the diagonal are real. #So the elements can be either real or imaginary for i in range(dimN): exec( 'mPhip2[{}][{}]=Symbol( \'mPhip2{}{}\' ,real=True)'.format(str(i),str(i),str(i+1),str(i+1)) ) tmpMPHI=(triu(mPhi2)).reshape(dimN**2) ParameterSymbols= array( [ (tmpMPHI[i], GetAssumptions(tmpMPHI[i],['complex','real','positive'] ) ) \ for i in nonzero(tmpMPHI)[0]] ) tmpMPHI=(triu(mPhip2)).reshape(dimN**2) ParameterSymbols=append(ParameterSymbols, array( [ (tmpMPHI[i], GetAssumptions(tmpMPHI[i],['complex','real','positive'] ) )\ for i in nonzero(tmpMPHI)[0]] ) ) del tmpMPHI sqrt2=sqrt(2); if Diag: global Oh11,Oh12, MH,MS0,MG if gauge!='un': Fields=array( symbols('H S0 G1:{} G0 Gp Gm'.format(2*dimN) ) ) else: Fields=array( symbols('H S0 G1:{}'.format(2*dimN) ) ) MH,MS0 = symbols('MH MS0 ',real=True,positive=True) MG = symbols('MG1:{}'.format(2*dimN),real=True,positive=True) tmpMPHI=[MH,MS0]+list(MG) ParameterSymbols=append(ParameterSymbols, array( [ (tmpMPHI[i], GetAssumptions(tmpMPHI[i],['complex','real','positive'] ) ) \ for i in nonzero(tmpMPHI)[0]] )) del tmpMPHI Oh11,Oh12=symbols('Oh11 Oh12',real=True) v=Symbol('v',positive=True); vPhi=Symbol('vPhi',positive=True); muH=Symbol('muH'); lamH=Symbol('lamH',real=True,positive=True); lamHPhi=Symbol('lamHPhi',real=True,positive=None); lamPhi=Symbol('lamPhi',real=True,positive=True); ParameterSymbols=append(ParameterSymbols, array( [\ (Oh11,GetAssumptions(Oh11,['complex','real','positive'] )),\ (Oh12,GetAssumptions(Oh12,['complex','real','positive'] )),\ (v,GetAssumptions(v,['complex','real','positive'] )),\ (vPhi,GetAssumptions(vPhi,['complex','real','positive'] )),\ (lamH,GetAssumptions(lamH,['complex','real','positive'] )),\ (lamHPhi,GetAssumptions(lamHPhi,['complex','real','positive'] )),\ (lamPhi,GetAssumptions(lamPhi,['complex','real','positive'] ))])) return Fields,ParameterSymbols else: global Gp, H0, Gm, H0t, h, G0, H, Ht, Phi, Phit, chi, rho, phi, s global subsvev, subsexpand dimRange=arange(1,dimN+1); dimRangeM=range(dimN-1) Phi = symbols('Phi1:{}'.format(str(dimN+1))) Phit = symbols('Phi1:{}t'.format(str(dimN+1))) if gauge=='un': H0, H0t=symbols('H0, H0t') H = [0,H0]; Ht = [0, H0t]; else: H0,H0t,Gp,Gm,G0=symbols('H0,H0t,Gp,Gm,G0') H = [Gp,H0]; Ht = [Gm, H0t]; ##################--Declare symbols for expaned scalars phi = list(symbols('phi1:{}'.format(str(dimN)))) s = list(symbols('s1:{}'.format(str(dimN)))) h , chi, rho=symbols('h chi rho') v=Symbol('v',positive=True); vPhi=Symbol('vPhi',positive=True); muH=Symbol('muH'); lamH=Symbol('lamH',real=True,positive=True); lamHPhi=Symbol('lamHPhi',real=True,positive=None); lamPhi=Symbol('lamPhi',real=True,positive=True); ParameterSymbols=append(ParameterSymbols, array( [\ (v,GetAssumptions(v,['complex','real','positive'] )),\ (vPhi,GetAssumptions(vPhi,['complex','real','positive'] )),\ (lamH,GetAssumptions(lamH,['complex','real','positive'] )),\ (lamHPhi,GetAssumptions(lamHPhi,['complex','real','positive'] )),\ (lamPhi,GetAssumptions(lamPhi,['complex','real','positive'] ))])) #Expand the fields at their vevs if gauge=='un': subsexpand =array(\ [(H0,(h+v)/sqrt2 ),(H0t,(h+v)/sqrt2 ),\ (Phi[dimN-1],(rho+ I*chi+vPhi)/sqrt2 ),\ (Phit[dimN-1],(rho-I*chi+vPhi)/sqrt2 )]+ \ [(Phi[i], (phi[i]+I*s[i])/sqrt2 ) for i in dimRangeM]+\ [(Phit[i],(phi[i]-I*s[i])/sqrt2) for i in dimRangeM]) Fields=array(flatten([h,rho,s,chi,phi])) subsvev = array(\ [(H0,v/sqrt2 ),(H0t,v/sqrt2 ),\ (Phi[dimN-1], vPhi/sqrt2 ),\ (Phit[dimN-1],vPhi/sqrt2 )]+ \ [(Phi[i], 0) for i in dimRangeM]+\ [(Phit[i],0) for i in dimRangeM]) else: subsexpand = array(\ [(H0,(h+I*G0+v)/sqrt2 ),(H0t,(h-I*G0+v)/sqrt2 ),\ (Phi[dimN-1], (rho+I*chi+vPhi)/sqrt2 ),\ (Phit[dimN-1],(rho-I*chi+vPhi)/sqrt2 )]+ \ [(Phi[i], (phi[i]+I*s[i])/sqrt2) for i in dimRangeM]+\ [(Phit[i],(phi[i]-I*s[i])/sqrt2) for i in dimRangeM]) Fields=array(flatten([h,rho,s,chi,phi,G0,Gp,Gm])) subsvev = array(\ [(H0,v/sqrt2 ),(H0t,v/sqrt2 ),\ (G0,0),(Gm,0),(Gp,0),\ (Phi[dimN-1], vPhi/sqrt2 ),\ (Phit[dimN-1],vPhi/sqrt2 )]+ \ [(Phi[i], 0) for i in dimRangeM]+\ [(Phit[i],0) for i in dimRangeM]) return list(Fields),ParameterSymbols def GetLagrangian(AllFields=False,Diag=False): if Diag==False: mPhi2C=[[conjugate(i) for i in x] for x in mPhi2] V0=-muH**2/2*MatrixProd([H,Ht])+lamH/2*MatrixProd([H,Ht])**2+lamPhi/2*MatrixProd([Phi,Phit])**2\ +lamHPhi*MatrixProd([H,Ht])*MatrixProd([Phi,Phit] ); Vsoft=MatrixProd([Phi,mPhi2,Phi])+MatrixProd([Phit,mPhi2C,Phit])+MatrixProd([Phit,mPhip2,Phi]) V=(V0+Vsoft)#.subs(subsexpand) subsmin= [ (mPhi2[i][dimN-1], -mPhip2[dimN-1][i]/2 ) for i in range(0,dimN-1)]+ \ [(muH, sqrt(v**2*lamH + vPhi**2*lamHPhi)),\ (lamPhi,-(lamHPhi*v**2 + 2*mPhi2[dimN-1][dimN-1] + 2*mPhip2[dimN-1][dimN-1] + 2*conjugate(mPhi2[dimN-1][dimN-1]))/vPhi**2),\ (conjugate(mPhi2[dimN-1][dimN-1]),mPhi2[dimN-1][dimN-1] )] constV=simplify((V.subs(subsmin).subs(subsvev)) ) if AllFields!=False: try: CheckMinimizations(AllFields,V, constV, subsmin) except: print 'Something went wrong while checking the minimization. \nHave you passed the fields correctly? ' LMassInt = -( (V.subs(subsmin)).subs(subsexpand) -constV ); return LMassInt else: FHS=array(AllFields[:2]) FG=array(AllFields[2:2*dimN+1]) #h=H*Oh11 - Oh12*S0 hH=Oh11*FHS[0]-Oh12*FHS[1] #------------------------- #rho=H*Oh12 + Oh11*S0 RHO=Oh12*FHS[0]+Oh11*FHS[1] #-------------------------- Phit_times_Phi= (MatrixProd([FG,FG]) + (vPhi+RHO)**2)/2 if gauge=='un': HD=1/sqrt2*array([0,hH+v]) HDt=HD Gsm=array([0,0,0]) else: Gsm=array(AllFields[2*dimN+1:]) HD=array([Gsm[1],1/sqrt2*(hH+v+I*Gsm[0])]) HDt=array([Gsm[2],1/sqrt2*(hH+v-I*Gsm[0])]) subsmin= [ (mPhi2[i][dimN-1], -mPhip2[dimN-1][i]/2 ) for i in range(0,dimN-1)]+ \ [(muH, sqrt(v**2*lamH + vPhi**2*lamHPhi)),\ (lamPhi,-(lamHPhi*v**2 + 2*mPhi2[dimN-1][dimN-1] + 2*mPhip2[dimN-1][dimN-1] + 2*conjugate(mPhi2[dimN-1][dimN-1]))/vPhi**2),\ (conjugate(mPhi2[dimN-1][dimN-1]),mPhi2[dimN-1][dimN-1] )] L_int=-(lamH/2*(MatrixProd([HD,HDt])**2 )+lamPhi/2*(Phit_times_Phi**2 )\ +lamHPhi*MatrixProd([HD,HDt])*Phit_times_Phi) #Remove linear interactions (it is minimized!) Subs0=[(i,0) for i in AllFields] L_const=-lamH*v**4/8 - lamHPhi*v**2*vPhi**2/4 - lamPhi*vPhi**4/8 Linear_terms=( -Oh11*lamH*v**3/2 - Oh11*lamHPhi*v*vPhi**2/2 - Oh12*lamHPhi*v**2*vPhi/2 - Oh12*lamPhi*vPhi**3/2 )*FHS[0]\ +(-Oh11*lamHPhi*v**2*vPhi/2 - Oh11*lamPhi*vPhi**3/2 + Oh12*lamH*v**3/2 + Oh12*lamHPhi*v*vPhi**2/2)*FHS[1] #Remove 2-point interactions (the mass) P2_terms=(\ (- Oh11**2*lamHPhi*v**2/2 - 3*Oh11**2*lamPhi*vPhi**2/2 + 2*Oh11*Oh12*lamHPhi*v*vPhi - 3*Oh12**2*lamH*v**2/2 - Oh12**2*lamHPhi*vPhi**2/2 )/2*FHS[1]**2\ +( -Oh11**2*lamHPhi*v*vPhi + 3*Oh11*Oh12*lamH*v**2/2 - Oh11*Oh12*lamHPhi*v**2/2 + Oh11*Oh12*lamHPhi*vPhi**2/2 - 3*Oh11*Oh12*lamPhi*vPhi**2/2 + Oh12**2*lamHPhi*v*vPhi)*FHS[0]*FHS[1]\ +(- 3*Oh11**2*lamH*v**2/2 - Oh11**2*lamHPhi*vPhi**2/2 - 2*Oh11*Oh12*lamHPhi*v*vPhi - Oh12**2*lamHPhi*v**2/2 - 3*Oh12**2*lamPhi*vPhi**2/2)/2*FHS[0]**2 -(lamH*v**2 +lamHPhi*vPhi**2)/4*Gsm[0]**2\ -( lamH*v**2 + lamHPhi*vPhi**2)/2*Gsm[2]*Gsm[1]\ )+\ ( MatrixProd([FG,FG]))*( - lamHPhi*v**2/2 - lamPhi*vPhi**2/2 )/2 #Include the mases (it is the diagonalized Lagrangian) L_mass=-(FHS[0]**2*MH**2 + FHS[1]**2*MS0**2)/2 -sum([FG[i-1]**2*MG[i-1]**2 for i in range(1,2*dimN) ])/2 return expand(L_int-Linear_terms-P2_terms- L_const).subs(subsmin)+L_mass global tmp2 def tmp2(i): if i[0]==i[1]: f=1/2. else: f=1 return f*prod(i)*Deriv(L,i).subs(Subs0) def CheckMinimizations(AllFields,V, constV, subsmin):#uses only global subs0=[ (i,0) for i in AllFields] print 'Checking vanishing of the first derivatives of the potential...' minV=unique(map(lambda i: \ simplify(Deriv(V.subs(subsexpand),i ).subs(subs0).subs(subsmin) ),AllFields)) if (minV==0).all(): print 'The conditions are correct!' else: print 'The potential is not minimized correctlly...'
42.162544
190
0.510392
from sympy import sqrt, Symbol,symbols,conjugate,I,flatten,simplify,expand from numpy import array,arange,triu,tril,nonzero,append,unique, vectorize,sum,prod from ..util import MatrixProd,Deriv,Tuples def GetAssumptions(Sym,assL): tmpA=[] for i in assL: try: tmpA.append(Sym.assumptions0[i] ) except: tmpA.append(None ) return tmpA def Definitions(DimN, Gauge,Diag=False): global gauge, dimN dimN,gauge=DimN,Gauge global sqrt2,dimRange, mPhi2, mPhip2, v, vPhi, muH, lamH, lamHPhi, lamPhi mPhi2=array( symbols('mPhi2(1:{})(1:{})'.format(str(dimN+1),str(dimN+1)),complex=True,real=False ) ).reshape(dimN,dimN) mPhi2[dimN-1][dimN-1]=Symbol('mPhi2{}{}'.format(dimN,dimN),real=True ) mPhip2=array( symbols('mPhip2(1:{})(1:{})'.format(str(dimN+1),str(dimN+1)),complex=True,real=False ) ).reshape(dimN,dimN) for i in range(dimN): for j in range(i+1,dimN): mPhi2[j][i]=mPhi2[i][j] for i in range(dimN): for j in range(i+1,dimN): mPhip2[j][i]=conjugate(mPhip2[i][j]) for i in range(dimN): exec( 'mPhip2[{}][{}]=Symbol( \'mPhip2{}{}\' ,real=True)'.format(str(i),str(i),str(i+1),str(i+1)) ) tmpMPHI=(triu(mPhi2)).reshape(dimN**2) ParameterSymbols= array( [ (tmpMPHI[i], GetAssumptions(tmpMPHI[i],['complex','real','positive'] ) ) \ for i in nonzero(tmpMPHI)[0]] ) tmpMPHI=(triu(mPhip2)).reshape(dimN**2) ParameterSymbols=append(ParameterSymbols, array( [ (tmpMPHI[i], GetAssumptions(tmpMPHI[i],['complex','real','positive'] ) )\ for i in nonzero(tmpMPHI)[0]] ) ) del tmpMPHI sqrt2=sqrt(2); if Diag: global Oh11,Oh12, MH,MS0,MG if gauge!='un': Fields=array( symbols('H S0 G1:{} G0 Gp Gm'.format(2*dimN) ) ) else: Fields=array( symbols('H S0 G1:{}'.format(2*dimN) ) ) MH,MS0 = symbols('MH MS0 ',real=True,positive=True) MG = symbols('MG1:{}'.format(2*dimN),real=True,positive=True) tmpMPHI=[MH,MS0]+list(MG) ParameterSymbols=append(ParameterSymbols, array( [ (tmpMPHI[i], GetAssumptions(tmpMPHI[i],['complex','real','positive'] ) ) \ for i in nonzero(tmpMPHI)[0]] )) del tmpMPHI Oh11,Oh12=symbols('Oh11 Oh12',real=True) v=Symbol('v',positive=True); vPhi=Symbol('vPhi',positive=True); muH=Symbol('muH'); lamH=Symbol('lamH',real=True,positive=True); lamHPhi=Symbol('lamHPhi',real=True,positive=None); lamPhi=Symbol('lamPhi',real=True,positive=True); ParameterSymbols=append(ParameterSymbols, array( [\ (Oh11,GetAssumptions(Oh11,['complex','real','positive'] )),\ (Oh12,GetAssumptions(Oh12,['complex','real','positive'] )),\ (v,GetAssumptions(v,['complex','real','positive'] )),\ (vPhi,GetAssumptions(vPhi,['complex','real','positive'] )),\ (lamH,GetAssumptions(lamH,['complex','real','positive'] )),\ (lamHPhi,GetAssumptions(lamHPhi,['complex','real','positive'] )),\ (lamPhi,GetAssumptions(lamPhi,['complex','real','positive'] ))])) return Fields,ParameterSymbols else: global Gp, H0, Gm, H0t, h, G0, H, Ht, Phi, Phit, chi, rho, phi, s global subsvev, subsexpand dimRange=arange(1,dimN+1); dimRangeM=range(dimN-1) Phi = symbols('Phi1:{}'.format(str(dimN+1))) Phit = symbols('Phi1:{}t'.format(str(dimN+1))) if gauge=='un': H0, H0t=symbols('H0, H0t') H = [0,H0]; Ht = [0, H0t]; else: H0,H0t,Gp,Gm,G0=symbols('H0,H0t,Gp,Gm,G0') H = [Gp,H0]; Ht = [Gm, H0t]; (lamH,GetAssumptions(lamH,['complex','real','positive'] )),\ (lamHPhi,GetAssumptions(lamHPhi,['complex','real','positive'] )),\ (lamPhi,GetAssumptions(lamPhi,['complex','real','positive'] ))])) if gauge=='un': subsexpand =array(\ [(H0,(h+v)/sqrt2 ),(H0t,(h+v)/sqrt2 ),\ (Phi[dimN-1],(rho+ I*chi+vPhi)/sqrt2 ),\ (Phit[dimN-1],(rho-I*chi+vPhi)/sqrt2 )]+ \ [(Phi[i], (phi[i]+I*s[i])/sqrt2 ) for i in dimRangeM]+\ [(Phit[i],(phi[i]-I*s[i])/sqrt2) for i in dimRangeM]) Fields=array(flatten([h,rho,s,chi,phi])) subsvev = array(\ [(H0,v/sqrt2 ),(H0t,v/sqrt2 ),\ (Phi[dimN-1], vPhi/sqrt2 ),\ (Phit[dimN-1],vPhi/sqrt2 )]+ \ [(Phi[i], 0) for i in dimRangeM]+\ [(Phit[i],0) for i in dimRangeM]) else: subsexpand = array(\ [(H0,(h+I*G0+v)/sqrt2 ),(H0t,(h-I*G0+v)/sqrt2 ),\ (Phi[dimN-1], (rho+I*chi+vPhi)/sqrt2 ),\ (Phit[dimN-1],(rho-I*chi+vPhi)/sqrt2 )]+ \ [(Phi[i], (phi[i]+I*s[i])/sqrt2) for i in dimRangeM]+\ [(Phit[i],(phi[i]-I*s[i])/sqrt2) for i in dimRangeM]) Fields=array(flatten([h,rho,s,chi,phi,G0,Gp,Gm])) subsvev = array(\ [(H0,v/sqrt2 ),(H0t,v/sqrt2 ),\ (G0,0),(Gm,0),(Gp,0),\ (Phi[dimN-1], vPhi/sqrt2 ),\ (Phit[dimN-1],vPhi/sqrt2 )]+ \ [(Phi[i], 0) for i in dimRangeM]+\ [(Phit[i],0) for i in dimRangeM]) return list(Fields),ParameterSymbols def GetLagrangian(AllFields=False,Diag=False): if Diag==False: mPhi2C=[[conjugate(i) for i in x] for x in mPhi2] V0=-muH**2/2*MatrixProd([H,Ht])+lamH/2*MatrixProd([H,Ht])**2+lamPhi/2*MatrixProd([Phi,Phit])**2\ +lamHPhi*MatrixProd([H,Ht])*MatrixProd([Phi,Phit] ); Vsoft=MatrixProd([Phi,mPhi2,Phi])+MatrixProd([Phit,mPhi2C,Phit])+MatrixProd([Phit,mPhip2,Phi]) V=(V0+Vsoft) subsmin= [ (mPhi2[i][dimN-1], -mPhip2[dimN-1][i]/2 ) for i in range(0,dimN-1)]+ \ [(muH, sqrt(v**2*lamH + vPhi**2*lamHPhi)),\ (lamPhi,-(lamHPhi*v**2 + 2*mPhi2[dimN-1][dimN-1] + 2*mPhip2[dimN-1][dimN-1] + 2*conjugate(mPhi2[dimN-1][dimN-1]))/vPhi**2),\ (conjugate(mPhi2[dimN-1][dimN-1]),mPhi2[dimN-1][dimN-1] )] constV=simplify((V.subs(subsmin).subs(subsvev)) ) if AllFields!=False: try: CheckMinimizations(AllFields,V, constV, subsmin) except: print 'Something went wrong while checking the minimization. \nHave you passed the fields correctly? ' LMassInt = -( (V.subs(subsmin)).subs(subsexpand) -constV ); return LMassInt else: FHS=array(AllFields[:2]) FG=array(AllFields[2:2*dimN+1]) hH=Oh11*FHS[0]-Oh12*FHS[1] RHO=Oh12*FHS[0]+Oh11*FHS[1] Phit_times_Phi= (MatrixProd([FG,FG]) + (vPhi+RHO)**2)/2 if gauge=='un': HD=1/sqrt2*array([0,hH+v]) HDt=HD Gsm=array([0,0,0]) else: Gsm=array(AllFields[2*dimN+1:]) HD=array([Gsm[1],1/sqrt2*(hH+v+I*Gsm[0])]) HDt=array([Gsm[2],1/sqrt2*(hH+v-I*Gsm[0])]) subsmin= [ (mPhi2[i][dimN-1], -mPhip2[dimN-1][i]/2 ) for i in range(0,dimN-1)]+ \ [(muH, sqrt(v**2*lamH + vPhi**2*lamHPhi)),\ (lamPhi,-(lamHPhi*v**2 + 2*mPhi2[dimN-1][dimN-1] + 2*mPhip2[dimN-1][dimN-1] + 2*conjugate(mPhi2[dimN-1][dimN-1]))/vPhi**2),\ (conjugate(mPhi2[dimN-1][dimN-1]),mPhi2[dimN-1][dimN-1] )] L_int=-(lamH/2*(MatrixProd([HD,HDt])**2 )+lamPhi/2*(Phit_times_Phi**2 )\ +lamHPhi*MatrixProd([HD,HDt])*Phit_times_Phi) Subs0=[(i,0) for i in AllFields] L_const=-lamH*v**4/8 - lamHPhi*v**2*vPhi**2/4 - lamPhi*vPhi**4/8 Linear_terms=( -Oh11*lamH*v**3/2 - Oh11*lamHPhi*v*vPhi**2/2 - Oh12*lamHPhi*v**2*vPhi/2 - Oh12*lamPhi*vPhi**3/2 )*FHS[0]\ +(-Oh11*lamHPhi*v**2*vPhi/2 - Oh11*lamPhi*vPhi**3/2 + Oh12*lamH*v**3/2 + Oh12*lamHPhi*v*vPhi**2/2)*FHS[1] P2_terms=(\ (- Oh11**2*lamHPhi*v**2/2 - 3*Oh11**2*lamPhi*vPhi**2/2 + 2*Oh11*Oh12*lamHPhi*v*vPhi - 3*Oh12**2*lamH*v**2/2 - Oh12**2*lamHPhi*vPhi**2/2 )/2*FHS[1]**2\ +( -Oh11**2*lamHPhi*v*vPhi + 3*Oh11*Oh12*lamH*v**2/2 - Oh11*Oh12*lamHPhi*v**2/2 + Oh11*Oh12*lamHPhi*vPhi**2/2 - 3*Oh11*Oh12*lamPhi*vPhi**2/2 + Oh12**2*lamHPhi*v*vPhi)*FHS[0]*FHS[1]\ +(- 3*Oh11**2*lamH*v**2/2 - Oh11**2*lamHPhi*vPhi**2/2 - 2*Oh11*Oh12*lamHPhi*v*vPhi - Oh12**2*lamHPhi*v**2/2 - 3*Oh12**2*lamPhi*vPhi**2/2)/2*FHS[0]**2 -(lamH*v**2 +lamHPhi*vPhi**2)/4*Gsm[0]**2\ -( lamH*v**2 + lamHPhi*vPhi**2)/2*Gsm[2]*Gsm[1]\ )+\ ( MatrixProd([FG,FG]))*( - lamHPhi*v**2/2 - lamPhi*vPhi**2/2 )/2 L_mass=-(FHS[0]**2*MH**2 + FHS[1]**2*MS0**2)/2 -sum([FG[i-1]**2*MG[i-1]**2 for i in range(1,2*dimN) ])/2 return expand(L_int-Linear_terms-P2_terms- L_const).subs(subsmin)+L_mass global tmp2 def tmp2(i): if i[0]==i[1]: f=1/2. else: f=1 return f*prod(i)*Deriv(L,i).subs(Subs0) def CheckMinimizations(AllFields,V, constV, subsmin): subs0=[ (i,0) for i in AllFields] print 'Checking vanishing of the first derivatives of the potential...' minV=unique(map(lambda i: \ simplify(Deriv(V.subs(subsexpand),i ).subs(subs0).subs(subsmin) ),AllFields)) if (minV==0).all(): print 'The conditions are correct!' else: print 'The potential is not minimized correctlly...'
false
true
f72a587cdb19c1c9ab6d907b4c8b9dbcba84d995
3,925
py
Python
ros/src/twist_controller/dbw_test.py
kenji-miyake/udacity-CarND-term2-Capstone
e50e826c9700a2bc549e809e2548b1a6d686012c
[ "MIT" ]
null
null
null
ros/src/twist_controller/dbw_test.py
kenji-miyake/udacity-CarND-term2-Capstone
e50e826c9700a2bc549e809e2548b1a6d686012c
[ "MIT" ]
null
null
null
ros/src/twist_controller/dbw_test.py
kenji-miyake/udacity-CarND-term2-Capstone
e50e826c9700a2bc549e809e2548b1a6d686012c
[ "MIT" ]
null
null
null
#!/usr/bin/env python import os import csv import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport ''' You can use this file to test your DBW code against a bag recorded with a reference implementation. The bag can be found at https://s3-us-west-1.amazonaws.com/udacity-selfdrivingcar/files/reference.bag.zip To use the downloaded bag file, rename it to 'dbw_test.rosbag.bag' and place it in the CarND-Capstone/data folder. Then with roscore running, you can then use roslaunch with the dbw_test.launch file found in <project_repo>/ros/src/twist_controller/launch. This file will produce 3 csv files which you can process to figure out how your DBW node is performing on various commands. `/actual/*` are commands from the recorded bag while `/vehicle/*` are the output of your node. ''' class DBWTestNode(object): def __init__(self): rospy.init_node('dbw_test_node') rospy.Subscriber('/vehicle/steering_cmd', SteeringCmd, self.steer_cb) rospy.Subscriber('/vehicle/throttle_cmd', ThrottleCmd, self.throttle_cb) rospy.Subscriber('/vehicle/brake_cmd', BrakeCmd, self.brake_cb) rospy.Subscriber('/actual/steering_cmd', SteeringCmd, self.actual_steer_cb) rospy.Subscriber('/actual/throttle_cmd', ThrottleCmd, self.actual_throttle_cb) rospy.Subscriber('/actual/brake_cmd', BrakeCmd, self.actual_brake_cb) rospy.Subscriber('/vehicle/dbw_enabled', Bool, self.dbw_enabled_cb) self.steer = self.throttle = self.brake = None self.steer_data = [] self.throttle_data = [] self.brake_data = [] self.dbw_enabled = False base_path = os.path.dirname(os.path.abspath(__file__)) self.steerfile = os.path.join(base_path, 'steers.csv') self.throttlefile = os.path.join(base_path, 'throttles.csv') self.brakefile = os.path.join(base_path, 'brakes.csv') self.loop() def loop(self): rate = rospy.Rate(10) # 10Hz while not rospy.is_shutdown(): rate.sleep() fieldnames = ['actual', 'proposed'] with open(self.steerfile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.steer_data) with open(self.throttlefile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.throttle_data) with open(self.brakefile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.brake_data) def dbw_enabled_cb(self, msg): self.dbw_enabled = msg.data def steer_cb(self, msg): self.steer = msg.steering_wheel_angle_cmd def throttle_cb(self, msg): self.throttle = msg.pedal_cmd def brake_cb(self, msg): self.brake = msg.pedal_cmd def actual_steer_cb(self, msg): if self.dbw_enabled and self.steer is not None: self.steer_data.append({'actual': msg.steering_wheel_angle_cmd, 'proposed': self.steer}) self.steer = None def actual_throttle_cb(self, msg): if self.dbw_enabled and self.throttle is not None: self.throttle_data.append({'actual': msg.pedal_cmd, 'proposed': self.throttle}) self.throttle = None def actual_brake_cb(self, msg): if self.dbw_enabled and self.brake is not None: self.brake_data.append({'actual': msg.pedal_cmd, 'proposed': self.brake}) self.brake = None if __name__ == '__main__': DBWTestNode()
34.734513
114
0.644076
import os import csv import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport class DBWTestNode(object): def __init__(self): rospy.init_node('dbw_test_node') rospy.Subscriber('/vehicle/steering_cmd', SteeringCmd, self.steer_cb) rospy.Subscriber('/vehicle/throttle_cmd', ThrottleCmd, self.throttle_cb) rospy.Subscriber('/vehicle/brake_cmd', BrakeCmd, self.brake_cb) rospy.Subscriber('/actual/steering_cmd', SteeringCmd, self.actual_steer_cb) rospy.Subscriber('/actual/throttle_cmd', ThrottleCmd, self.actual_throttle_cb) rospy.Subscriber('/actual/brake_cmd', BrakeCmd, self.actual_brake_cb) rospy.Subscriber('/vehicle/dbw_enabled', Bool, self.dbw_enabled_cb) self.steer = self.throttle = self.brake = None self.steer_data = [] self.throttle_data = [] self.brake_data = [] self.dbw_enabled = False base_path = os.path.dirname(os.path.abspath(__file__)) self.steerfile = os.path.join(base_path, 'steers.csv') self.throttlefile = os.path.join(base_path, 'throttles.csv') self.brakefile = os.path.join(base_path, 'brakes.csv') self.loop() def loop(self): rate = rospy.Rate(10) while not rospy.is_shutdown(): rate.sleep() fieldnames = ['actual', 'proposed'] with open(self.steerfile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.steer_data) with open(self.throttlefile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.throttle_data) with open(self.brakefile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.brake_data) def dbw_enabled_cb(self, msg): self.dbw_enabled = msg.data def steer_cb(self, msg): self.steer = msg.steering_wheel_angle_cmd def throttle_cb(self, msg): self.throttle = msg.pedal_cmd def brake_cb(self, msg): self.brake = msg.pedal_cmd def actual_steer_cb(self, msg): if self.dbw_enabled and self.steer is not None: self.steer_data.append({'actual': msg.steering_wheel_angle_cmd, 'proposed': self.steer}) self.steer = None def actual_throttle_cb(self, msg): if self.dbw_enabled and self.throttle is not None: self.throttle_data.append({'actual': msg.pedal_cmd, 'proposed': self.throttle}) self.throttle = None def actual_brake_cb(self, msg): if self.dbw_enabled and self.brake is not None: self.brake_data.append({'actual': msg.pedal_cmd, 'proposed': self.brake}) self.brake = None if __name__ == '__main__': DBWTestNode()
true
true
f72a59ba76c94957d9f4a188c1bbef848032ed01
20,211
py
Python
xalpha/cons.py
Razorro/xalpha
bcecd53dc9d081deb1b8235437a4f6b74951c23d
[ "MIT" ]
null
null
null
xalpha/cons.py
Razorro/xalpha
bcecd53dc9d081deb1b8235437a4f6b74951c23d
[ "MIT" ]
null
null
null
xalpha/cons.py
Razorro/xalpha
bcecd53dc9d081deb1b8235437a4f6b74951c23d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ basic constants and utility functions """ import datetime as dt import os import time import logging import inspect from decimal import Decimal import requests from functools import wraps from simplejson.errors import JSONDecodeError import pandas as pd from pyecharts.options import ( AxisOpts, DataZoomOpts, LegendOpts, TooltipOpts, VisualMapOpts, ) from numpy import sqrt from scipy import optimize from xalpha import __path__ from .exceptions import HttpStatusError logger = logging.getLogger(__name__) # date obj of today # today = lambda: dt.datetime.combine(dt.date.today(), dt.time.min) tz_bj = dt.timezone(dt.timedelta(hours=8)) def today_obj(): """ today obj in beijing timezone with no tzinfo :return: datetime.datetime """ now = dt.datetime.now(tz=tz_bj) return now.replace(hour=0, minute=0, second=0, microsecond=0).replace(tzinfo=None) # datetime obj for yesterdate date with time set to be 0:0:0 yesterdayobj = lambda: (dt.datetime.now(tz_bj).replace(tzinfo=None) - dt.timedelta(1)) # string for yesterday, only used for indexinfo url yesterday = lambda: dt.datetime.strftime(yesterdayobj(), "%Y%m%d") # string for yesterday with dash yesterdaydash = lambda: dt.datetime.strftime(yesterdayobj(), "%Y-%m-%d") # list: all the trade date of domestic stock market in the form of string caldate = pd.read_csv(os.path.join(__path__[0], "caldate.csv")) opendate = list(caldate[caldate["is_open"] == 1]["cal_date"]) # opendate = list(ts.trade_cal()[ts.trade_cal()['isOpen']==1]['calendarDate']) opendate_set = set(opendate) # for speed checking? # fund code list which always round down for the purchase share approximation droplist = ["003318", "000311", "000601", "009989"] sqrt_days_in_year = sqrt(250.0) def calendar_selfcheck(): # 国内链接 githubusercontent.com 大概率存在问题,因此设计成联网自动更新日历大概率无用。 # 也许之后考虑一些较稳定的第三方资源托管服务 current_year = dt.datetime.now().year if str(current_year) != opendate[-1][:4]: logger.warning( "Please update xalpha via `pip install -U xalpha` to keep the trade calendar up-to-date" ) print("请更新 xalpha 版本以更新最新年份的 A 股交易日历, 否则将可能无法正确获取和处理最新的基金净值") calendar_selfcheck() region_trans = { "瑞士": "CH", "日本": "JP", "韩国": "KR", "美国": "US", "香港": "HK", "中国香港": "HK", "德国": "DE", "英国": "UK", "法国": "FR", "中国": "CN", "墨西哥": "MX", "澳大利亚": "AU", "新加坡": "SG", "印度": "IN", "台湾": "TW", "中国台湾": "TW", } # extract from xa.misc.get_tdx_holidays holidays = { "AU": [ "2020-01-01", "2020-01-27", "2020-04-10", "2020-04-13", "2020-04-25", "2020-06-08", "2020-12-24", "2020-12-25", "2020-12-28", "2020-12-31", "2021-01-01", "2021-01-26", "2021-04-02", "2021-04-05", "2021-06-14", "2021-12-24", "2021-12-27", "2021-12-28", "2021-12-31", ], "CH": [ "2020-01-01", "2020-01-02", "2020-04-10", "2020-04-13", "2020-05-01", "2020-05-21", "2020-06-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-13", "2021-05-24", "2021-12-24", "2021-12-31", ], "CN": [ "2020-01-01", "2020-01-24", "2020-01-27", "2020-01-28", "2020-01-29", "2020-01-30", "2020-01-31", "2020-04-06", "2020-05-01", "2020-05-04", "2020-05-05", "2020-06-25", "2020-06-26", "2020-10-01", "2020-10-02", "2020-10-05", "2020-10-06", "2020-10-07", "2020-10-08", "2021-01-01", "2021-02-11", "2021-02-12", "2021-02-15", "2021-02-16", "2021-02-17", "2021-04-05", "2021-05-03", "2021-05-04", "2021-05-05", "2021-06-14", "2021-09-20", "2021-09-21", "2021-10-01", "2021-10-04", "2021-10-05", "2021-10-06", "2021-10-07", ], "DE": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-01", "2020-06-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-24", "2021-12-24", "2021-12-31", ], "FR": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-12-24", "2021-12-31", ], "HK": [ "2020-01-01", "2020-01-27", "2020-01-28", "2020-04-10", "2020-04-13", "2020-04-30", "2020-05-01", "2020-06-25", "2020-07-01", "2020-10-01", "2020-10-02", "2020-10-26", "2020-12-25", "2021-01-01", "2021-02-11", "2021-02-12", "2021-02-15", "2021-04-02", "2021-04-05", "2021-04-06", "2021-05-19", "2021-06-14", "2021-07-01", "2021-09-22", "2021-10-01", "2021-10-14", "2021-12-24", "2021-12-27", "2021-12-31", ], "IN": [ "2020-02-21", "2020-03-10", "2020-04-02", "2020-04-06", "2020-04-10", "2020-04-14", "2020-05-01", "2020-05-25", "2020-10-02", "2020-11-16", "2020-11-30", "2020-12-25", "2021-01-26", "2021-03-11", "2021-03-29", "2021-04-02", "2021-04-14", "2021-04-21", "2021-05-13", "2021-07-20", "2021-08-19", "2021-09-10", "2021-10-15", "2021-11-04", "2021-11-19", ], "JP": [ "2020-01-01", "2020-01-02", "2020-01-03", "2020-01-13", "2020-02-11", "2020-02-24", "2020-03-20", "2020-04-29", "2020-05-04", "2020-05-05", "2020-05-06", "2020-07-23", "2020-07-24", "2020-08-10", "2020-09-21", "2020-09-22", "2020-11-03", "2020-11-23", "2020-12-31", "2021-01-01", "2021-01-11", "2021-02-11", "2021-02-23", "2021-04-29", "2021-05-03", "2021-05-04", "2021-05-05", "2021-07-22", "2021-07-23", "2021-08-09", "2021-09-20", "2021-09-23", "2021-11-03", "2021-11-23", "2021-12-31", ], "KR": [ "2020-01-01", "2020-01-24", "2020-01-27", "2020-04-30", "2020-05-01", "2020-05-05", "2020-09-30", "2020-10-01", "2020-10-02", "2020-10-09", "2020-12-25", "2020-12-31", "2021-01-01", "2021-02-11", "2021-02-12", "2021-03-01", "2021-05-05", "2021-05-19", "2021-09-20", "2021-09-21", "2021-09-22", "2021-12-31", ], "SG": [ "2020-01-01", "2020-01-24", "2020-04-10", "2020-05-01", "2020-05-07", "2020-05-21", "2020-07-31", "2020-08-10", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-02-11", "2021-02-12", "2021-04-02", "2021-05-13", "2021-05-26", "2021-07-20", "2021-08-09", "2021-11-04", "2021-12-24", "2021-12-31", ], "TW": [ "2020-01-01", "2020-01-21", "2020-01-22", "2020-01-23", "2020-01-24", "2020-01-27", "2020-01-28", "2020-01-29", "2020-02-28", "2020-04-02", "2020-04-03", "2020-05-01", "2020-06-25", "2020-06-26", "2020-10-01", "2020-10-02", "2020-10-09", "2021-01-01", "2021-02-08", "2021-02-09", "2021-02-10", "2021-02-11", "2021-02-12", "2021-02-15", "2021-02-16", "2021-03-01", "2021-04-02", "2021-04-05", "2021-04-30", "2021-06-14", "2021-09-20", "2021-09-21", "2021-10-11", "2021-12-31", ], "UK": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-08", "2020-05-25", "2020-08-31", "2020-12-24", "2020-12-25", "2020-12-28", "2020-12-31", "2021-01-01", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-03", "2021-05-31", "2021-08-30", "2021-12-24", "2021-12-27", "2021-12-28", "2021-12-31", "2022-01-03", ], "US": [ "2020-01-01", "2020-01-20", "2020-02-17", "2020-03-08", "2020-04-10", "2020-05-25", "2020-07-03", "2020-09-07", "2020-11-01", "2020-11-26", "2020-11-27", "2020-12-24", "2020-12-25", "2021-01-01", "2021-01-01", "2021-01-18", "2021-02-15", "2021-03-14", "2021-04-02", "2021-05-31", "2021-07-05", "2021-09-06", "2021-11-07", "2021-11-25", "2021-11-26", "2021-12-24", ], } connection_errors = ( HttpStatusError, ConnectionResetError, requests.exceptions.RequestException, requests.exceptions.ConnectionError, requests.exceptions.SSLError, JSONDecodeError, ) line_opts = { "datazoom_opts": [ DataZoomOpts(is_show=True, type_="slider", range_start=50, range_end=100), DataZoomOpts( is_show=True, type_="slider", orient="vertical", range_start=50, range_end=100, ), ], "tooltip_opts": TooltipOpts( is_show=True, trigger="axis", trigger_on="mousemove", axis_pointer_type="cross" ), } heatmap_opts = { "visualmap_opts": VisualMapOpts( min_=-1, max_=1, orient="horizontal", pos_right="middle", pos_top="bottom" ) } # pie_opts = { # "tooltip_opts": TooltipOpts(), # "legend_opts": LegendOpts(orient="vertical", pos_left="left"), # } themeriver_opts = { "xaxis_opts": AxisOpts(type_="time"), "datazoom_opts": [DataZoomOpts(range_start=60, range_end=100)], "tooltip_opts": TooltipOpts(trigger_on="mousemove", trigger="item"), "legend_opts": LegendOpts(pos_top="top"), } def xnpv(rate, cashflows): """ give the current cash value based on future cashflows :param rate: float, the preset year rate :param cashflows: a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. Cash outflows (investments) are represented with negative amounts, and cash inflows (returns) are positive amounts. :returns: a single float value which is the NPV of the given cash flows """ chron_order = sorted(cashflows, key=lambda x: x[0]) t0 = chron_order[0][0] return sum([cf / (1 + rate) ** ((t - t0).days / 365.0) for (t, cf) in chron_order]) def xirr(cashflows, guess=0.1): """ calculate the Internal Rate of Return of a series of cashflows at irregular intervals. :param cashflows: a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. Cash outflows (investments) are represented with negative amounts, and cash inflows (returns) are positive amounts. :param guess: floating number, a guess at the xirr rate solution to be used as a starting point for the numerical solution :returns: the IRR as a single floating number """ return optimize.newton(lambda r: xnpv(r, cashflows), guess) def myround(num, label=1): """ correct implementation of round with round half up, round to 2 decimals :param num: the floating number, to be rounded :param label: integer 1 or 2, 1 for round half up while 2 for always round down :returns: the float number after rounding, with two decimals """ if label == 1: res = float( Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_HALF_UP") ) elif ( label == 2 ): # for jingshunchangcheng... who just omit the overflow share behind 2 decimal res = float(Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_DOWN")) return res def convert_date(date): """ convert date into datetime object :param date: string of form '2017-01-01' or datetime object :returns: corresponding datetime object """ if isinstance(date, str): return pd.Timestamp(date) else: return date def _date_check(dtobj, check=False): if not isinstance(dtobj, dt.datetime): dtobj = dt.datetime.strptime(dtobj.replace("/", "").replace("-", ""), "%Y%m%d") if check and (dtobj.year > dt.datetime.now().year or dtobj.year < 1991): raise ValueError( "date goes beyond market range: %s" % dtobj.strftime("%Y-%m-%d") ) return dtobj def next_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj += dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj += dt.timedelta(1) return dtobj def last_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj -= dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj -= dt.timedelta(1) return dtobj def avail_dates(dtlist, future=False): """ make every day in the list the next open day :param dtlist: datetime obj list :param future: bool, default False, indicating the latest day in the list is yesterday :return: datetime obj list """ ndtlist = [] for d in dtlist: if d.strftime("%Y-%m-%d") not in opendate_set: nd = next_onday(d) else: nd = d if future is False: if (nd - yesterdayobj()).days > 0: continue ndtlist.append(nd) return ndtlist def scale_dict(d, scale=1, ulimit=100, dlimit=50, aim=None): t = sum([v for _, v in d.items()]) if t * scale > ulimit: scale = ulimit / t elif t * scale < dlimit: scale = dlimit / t if aim: scale = aim / t for k, v in d.items(): d[k] = v * scale return d def _float(n): try: n = n.replace(",", "") if n.endswith("K") or n.endswith("k"): n = float(n[:-1]) * 1000 elif n.endswith("M") or n.endswith("m"): n = float(n[:-1]) * 1000 * 1000 elif n.endswith("G") or n.endswith("g") or n.endswith("B") or n.endswith("b"): n = float(n[:-1]) * 1000 * 1000 * 1000 elif n == "-": logger.info("_float met -, taken as 0") return 0 elif n.endswith("%"): logger.info("_float met with %% as %s" % n) return float(n[:-1]) / 100 except AttributeError: pass if not n: logger.info("_float met with None as input arguments") return 0.0 return float(n) def reconnect(tries=5, timeout=12): def robustify(f): default_header = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,' 'application/signed-exchange;v=b3;q=0.9', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,ja;q=0.5', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.76', } @wraps(f) def wrapper(*args, **kws): import xalpha.provider as xp if getattr(xp, "proxy", None): kws["proxies"] = {"http": xp.proxy, "https": xp.proxy} kws["timeout"] = timeout logger.debug("Using proxy %s" % xp.proxy) if args: url = args[0] else: url = kws.get("url", "") headers = kws.get("headers", {}) if len(headers) == 0: headers.update(default_header) kws["headers"] = headers for count in range(tries): try: logger.debug("Fetching url: %s . Inside function `%s`" % (url, inspect.stack()[1].function)) r = f(*args, **kws) if getattr(r, "status_code", 200) != 200: # in case r is a json dict raise HttpStatusError return r except connection_errors as e: logger.warning("Fails at fetching url: %s. Try again." % url) if count == tries - 1: logger.error("Still wrong at fetching url: %s. after %s tries." % (url, tries)) logger.error("Fails due to %s" % e.args[0]) raise e time.sleep(0.5 * count) return wrapper return robustify rget = reconnect()(requests.get) rpost = reconnect()(requests.post) @reconnect() def rget_json(*args, **kws): r = requests.get(*args, **kws) return r.json() @reconnect() def rpost_json(*args, **kws): r = requests.post(*args, **kws) return r.json() # def rget(*args, **kws): # tries = 5 # for count in range(tries): # try: # r = requests.get(*args, **kws) # return r # except connection_errors as e: # if count == tries - 1: # print(*args, sep="\n") # print("still wrong after several tries") # raise e # time.sleep(0.5*count) # # # def rget_json(*args, **kws): # tries = 5 # for count in range(tries): # try: # r = requests.get(*args, **kws) # return r.json() # except connection_errors as e: # if count == tries - 1: # print(*args, sep="\n") # print("still wrong after several tries") # raise e # time.sleep(0.5*count) # # # def rpost(*args, **kws): # tries = 5 # for count in range(tries): # try: # r = requests.post(*args, **kws) # return r # except connection_errors as e: # if count == tries - 1: # print(*args, sep="\n") # print("still wrong after several tries") # raise e # time.sleep(0.5*count) # # # def rpost_json(*args, **kws): # tries = 5 # for count in range(tries): # try: # r = requests.post(*args, **kws) # return r.json() # except connection_errors as e: # if count == tries - 1: # print(*args, sep="\n") # print("still wrong after several tries") # raise e # time.sleep(0.5*count) ## simple subsitution for holdings.py holdings = {} holdings["501018"] = { "etfs/etfs-brent-1mth-uk": 17.51, "etfs/etfs-brent-crude": 15.04, "etfs/etfs-crude-oil": 7.34, "etfs/ipath-series-b-sp-gsci-crd-oil-tr": 0.06, "etfs/powershares-db-oil-fund": 11.6, "etfs/ubs-cmci-oil-sf-usd": 8.68, "etfs/united-states-12-month-oil": 8.14, "etfs/united-states-brent-oil-fund-lp": 15.42, "etfs/united-states-oil-fund": 9.63, } holdings["501018rt"] = { "commodities/brent-oil": {"weight": 49, "time": -1}, "commodities/crude-oil": {"weight": 45, "time": 4}, }
25.978149
112
0.502647
import datetime as dt import os import time import logging import inspect from decimal import Decimal import requests from functools import wraps from simplejson.errors import JSONDecodeError import pandas as pd from pyecharts.options import ( AxisOpts, DataZoomOpts, LegendOpts, TooltipOpts, VisualMapOpts, ) from numpy import sqrt from scipy import optimize from xalpha import __path__ from .exceptions import HttpStatusError logger = logging.getLogger(__name__) tz_bj = dt.timezone(dt.timedelta(hours=8)) def today_obj(): now = dt.datetime.now(tz=tz_bj) return now.replace(hour=0, minute=0, second=0, microsecond=0).replace(tzinfo=None) yesterdayobj = lambda: (dt.datetime.now(tz_bj).replace(tzinfo=None) - dt.timedelta(1)) yesterday = lambda: dt.datetime.strftime(yesterdayobj(), "%Y%m%d") yesterdaydash = lambda: dt.datetime.strftime(yesterdayobj(), "%Y-%m-%d") caldate = pd.read_csv(os.path.join(__path__[0], "caldate.csv")) opendate = list(caldate[caldate["is_open"] == 1]["cal_date"]) opendate_set = set(opendate) droplist = ["003318", "000311", "000601", "009989"] sqrt_days_in_year = sqrt(250.0) def calendar_selfcheck(): current_year = dt.datetime.now().year if str(current_year) != opendate[-1][:4]: logger.warning( "Please update xalpha via `pip install -U xalpha` to keep the trade calendar up-to-date" ) print("请更新 xalpha 版本以更新最新年份的 A 股交易日历, 否则将可能无法正确获取和处理最新的基金净值") calendar_selfcheck() region_trans = { "瑞士": "CH", "日本": "JP", "韩国": "KR", "美国": "US", "香港": "HK", "中国香港": "HK", "德国": "DE", "英国": "UK", "法国": "FR", "中国": "CN", "墨西哥": "MX", "澳大利亚": "AU", "新加坡": "SG", "印度": "IN", "台湾": "TW", "中国台湾": "TW", } holidays = { "AU": [ "2020-01-01", "2020-01-27", "2020-04-10", "2020-04-13", "2020-04-25", "2020-06-08", "2020-12-24", "2020-12-25", "2020-12-28", "2020-12-31", "2021-01-01", "2021-01-26", "2021-04-02", "2021-04-05", "2021-06-14", "2021-12-24", "2021-12-27", "2021-12-28", "2021-12-31", ], "CH": [ "2020-01-01", "2020-01-02", "2020-04-10", "2020-04-13", "2020-05-01", "2020-05-21", "2020-06-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-13", "2021-05-24", "2021-12-24", "2021-12-31", ], "CN": [ "2020-01-01", "2020-01-24", "2020-01-27", "2020-01-28", "2020-01-29", "2020-01-30", "2020-01-31", "2020-04-06", "2020-05-01", "2020-05-04", "2020-05-05", "2020-06-25", "2020-06-26", "2020-10-01", "2020-10-02", "2020-10-05", "2020-10-06", "2020-10-07", "2020-10-08", "2021-01-01", "2021-02-11", "2021-02-12", "2021-02-15", "2021-02-16", "2021-02-17", "2021-04-05", "2021-05-03", "2021-05-04", "2021-05-05", "2021-06-14", "2021-09-20", "2021-09-21", "2021-10-01", "2021-10-04", "2021-10-05", "2021-10-06", "2021-10-07", ], "DE": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-01", "2020-06-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-24", "2021-12-24", "2021-12-31", ], "FR": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-12-24", "2021-12-31", ], "HK": [ "2020-01-01", "2020-01-27", "2020-01-28", "2020-04-10", "2020-04-13", "2020-04-30", "2020-05-01", "2020-06-25", "2020-07-01", "2020-10-01", "2020-10-02", "2020-10-26", "2020-12-25", "2021-01-01", "2021-02-11", "2021-02-12", "2021-02-15", "2021-04-02", "2021-04-05", "2021-04-06", "2021-05-19", "2021-06-14", "2021-07-01", "2021-09-22", "2021-10-01", "2021-10-14", "2021-12-24", "2021-12-27", "2021-12-31", ], "IN": [ "2020-02-21", "2020-03-10", "2020-04-02", "2020-04-06", "2020-04-10", "2020-04-14", "2020-05-01", "2020-05-25", "2020-10-02", "2020-11-16", "2020-11-30", "2020-12-25", "2021-01-26", "2021-03-11", "2021-03-29", "2021-04-02", "2021-04-14", "2021-04-21", "2021-05-13", "2021-07-20", "2021-08-19", "2021-09-10", "2021-10-15", "2021-11-04", "2021-11-19", ], "JP": [ "2020-01-01", "2020-01-02", "2020-01-03", "2020-01-13", "2020-02-11", "2020-02-24", "2020-03-20", "2020-04-29", "2020-05-04", "2020-05-05", "2020-05-06", "2020-07-23", "2020-07-24", "2020-08-10", "2020-09-21", "2020-09-22", "2020-11-03", "2020-11-23", "2020-12-31", "2021-01-01", "2021-01-11", "2021-02-11", "2021-02-23", "2021-04-29", "2021-05-03", "2021-05-04", "2021-05-05", "2021-07-22", "2021-07-23", "2021-08-09", "2021-09-20", "2021-09-23", "2021-11-03", "2021-11-23", "2021-12-31", ], "KR": [ "2020-01-01", "2020-01-24", "2020-01-27", "2020-04-30", "2020-05-01", "2020-05-05", "2020-09-30", "2020-10-01", "2020-10-02", "2020-10-09", "2020-12-25", "2020-12-31", "2021-01-01", "2021-02-11", "2021-02-12", "2021-03-01", "2021-05-05", "2021-05-19", "2021-09-20", "2021-09-21", "2021-09-22", "2021-12-31", ], "SG": [ "2020-01-01", "2020-01-24", "2020-04-10", "2020-05-01", "2020-05-07", "2020-05-21", "2020-07-31", "2020-08-10", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-02-11", "2021-02-12", "2021-04-02", "2021-05-13", "2021-05-26", "2021-07-20", "2021-08-09", "2021-11-04", "2021-12-24", "2021-12-31", ], "TW": [ "2020-01-01", "2020-01-21", "2020-01-22", "2020-01-23", "2020-01-24", "2020-01-27", "2020-01-28", "2020-01-29", "2020-02-28", "2020-04-02", "2020-04-03", "2020-05-01", "2020-06-25", "2020-06-26", "2020-10-01", "2020-10-02", "2020-10-09", "2021-01-01", "2021-02-08", "2021-02-09", "2021-02-10", "2021-02-11", "2021-02-12", "2021-02-15", "2021-02-16", "2021-03-01", "2021-04-02", "2021-04-05", "2021-04-30", "2021-06-14", "2021-09-20", "2021-09-21", "2021-10-11", "2021-12-31", ], "UK": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-08", "2020-05-25", "2020-08-31", "2020-12-24", "2020-12-25", "2020-12-28", "2020-12-31", "2021-01-01", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-03", "2021-05-31", "2021-08-30", "2021-12-24", "2021-12-27", "2021-12-28", "2021-12-31", "2022-01-03", ], "US": [ "2020-01-01", "2020-01-20", "2020-02-17", "2020-03-08", "2020-04-10", "2020-05-25", "2020-07-03", "2020-09-07", "2020-11-01", "2020-11-26", "2020-11-27", "2020-12-24", "2020-12-25", "2021-01-01", "2021-01-01", "2021-01-18", "2021-02-15", "2021-03-14", "2021-04-02", "2021-05-31", "2021-07-05", "2021-09-06", "2021-11-07", "2021-11-25", "2021-11-26", "2021-12-24", ], } connection_errors = ( HttpStatusError, ConnectionResetError, requests.exceptions.RequestException, requests.exceptions.ConnectionError, requests.exceptions.SSLError, JSONDecodeError, ) line_opts = { "datazoom_opts": [ DataZoomOpts(is_show=True, type_="slider", range_start=50, range_end=100), DataZoomOpts( is_show=True, type_="slider", orient="vertical", range_start=50, range_end=100, ), ], "tooltip_opts": TooltipOpts( is_show=True, trigger="axis", trigger_on="mousemove", axis_pointer_type="cross" ), } heatmap_opts = { "visualmap_opts": VisualMapOpts( min_=-1, max_=1, orient="horizontal", pos_right="middle", pos_top="bottom" ) } themeriver_opts = { "xaxis_opts": AxisOpts(type_="time"), "datazoom_opts": [DataZoomOpts(range_start=60, range_end=100)], "tooltip_opts": TooltipOpts(trigger_on="mousemove", trigger="item"), "legend_opts": LegendOpts(pos_top="top"), } def xnpv(rate, cashflows): chron_order = sorted(cashflows, key=lambda x: x[0]) t0 = chron_order[0][0] return sum([cf / (1 + rate) ** ((t - t0).days / 365.0) for (t, cf) in chron_order]) def xirr(cashflows, guess=0.1): return optimize.newton(lambda r: xnpv(r, cashflows), guess) def myround(num, label=1): if label == 1: res = float( Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_HALF_UP") ) elif ( label == 2 ): res = float(Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_DOWN")) return res def convert_date(date): if isinstance(date, str): return pd.Timestamp(date) else: return date def _date_check(dtobj, check=False): if not isinstance(dtobj, dt.datetime): dtobj = dt.datetime.strptime(dtobj.replace("/", "").replace("-", ""), "%Y%m%d") if check and (dtobj.year > dt.datetime.now().year or dtobj.year < 1991): raise ValueError( "date goes beyond market range: %s" % dtobj.strftime("%Y-%m-%d") ) return dtobj def next_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj += dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj += dt.timedelta(1) return dtobj def last_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj -= dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj -= dt.timedelta(1) return dtobj def avail_dates(dtlist, future=False): ndtlist = [] for d in dtlist: if d.strftime("%Y-%m-%d") not in opendate_set: nd = next_onday(d) else: nd = d if future is False: if (nd - yesterdayobj()).days > 0: continue ndtlist.append(nd) return ndtlist def scale_dict(d, scale=1, ulimit=100, dlimit=50, aim=None): t = sum([v for _, v in d.items()]) if t * scale > ulimit: scale = ulimit / t elif t * scale < dlimit: scale = dlimit / t if aim: scale = aim / t for k, v in d.items(): d[k] = v * scale return d def _float(n): try: n = n.replace(",", "") if n.endswith("K") or n.endswith("k"): n = float(n[:-1]) * 1000 elif n.endswith("M") or n.endswith("m"): n = float(n[:-1]) * 1000 * 1000 elif n.endswith("G") or n.endswith("g") or n.endswith("B") or n.endswith("b"): n = float(n[:-1]) * 1000 * 1000 * 1000 elif n == "-": logger.info("_float met -, taken as 0") return 0 elif n.endswith("%"): logger.info("_float met with %% as %s" % n) return float(n[:-1]) / 100 except AttributeError: pass if not n: logger.info("_float met with None as input arguments") return 0.0 return float(n) def reconnect(tries=5, timeout=12): def robustify(f): default_header = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,' 'application/signed-exchange;v=b3;q=0.9', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,ja;q=0.5', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.76', } @wraps(f) def wrapper(*args, **kws): import xalpha.provider as xp if getattr(xp, "proxy", None): kws["proxies"] = {"http": xp.proxy, "https": xp.proxy} kws["timeout"] = timeout logger.debug("Using proxy %s" % xp.proxy) if args: url = args[0] else: url = kws.get("url", "") headers = kws.get("headers", {}) if len(headers) == 0: headers.update(default_header) kws["headers"] = headers for count in range(tries): try: logger.debug("Fetching url: %s . Inside function `%s`" % (url, inspect.stack()[1].function)) r = f(*args, **kws) if getattr(r, "status_code", 200) != 200: raise HttpStatusError return r except connection_errors as e: logger.warning("Fails at fetching url: %s. Try again." % url) if count == tries - 1: logger.error("Still wrong at fetching url: %s. after %s tries." % (url, tries)) logger.error("Fails due to %s" % e.args[0]) raise e time.sleep(0.5 * count) return wrapper return robustify rget = reconnect()(requests.get) rpost = reconnect()(requests.post) @reconnect() def rget_json(*args, **kws): r = requests.get(*args, **kws) return r.json() @reconnect() def rpost_json(*args, **kws): r = requests.post(*args, **kws) return r.json() { "etfs/etfs-brent-1mth-uk": 17.51, "etfs/etfs-brent-crude": 15.04, "etfs/etfs-crude-oil": 7.34, "etfs/ipath-series-b-sp-gsci-crd-oil-tr": 0.06, "etfs/powershares-db-oil-fund": 11.6, "etfs/ubs-cmci-oil-sf-usd": 8.68, "etfs/united-states-12-month-oil": 8.14, "etfs/united-states-brent-oil-fund-lp": 15.42, "etfs/united-states-oil-fund": 9.63, } holdings["501018rt"] = { "commodities/brent-oil": {"weight": 49, "time": -1}, "commodities/crude-oil": {"weight": 45, "time": 4}, }
true
true
f72a5a03842d93e765331b1fe8130fe4969fd3ea
3,462
py
Python
temperature.py
balena-io-playground/balena-edison-monitoring-artik
d02ba51cda8edcbc0decc80d0dab7f724dc46014
[ "Apache-2.0" ]
2
2020-04-25T08:46:41.000Z
2021-02-11T17:36:27.000Z
temperature.py
balena-io-playground/balena-edison-monitoring-artik
d02ba51cda8edcbc0decc80d0dab7f724dc46014
[ "Apache-2.0" ]
null
null
null
temperature.py
balena-io-playground/balena-edison-monitoring-artik
d02ba51cda8edcbc0decc80d0dab7f724dc46014
[ "Apache-2.0" ]
null
null
null
""" Temperature monitoring with Intel Edison and Samsung ARTIK Cloud """ import sys import os import time from math import log import statistics from collections import deque import artikcloud from artikcloud.rest import ApiException import pyupm_grove as grove import mraa import requests # Setting credentials from the environmental variables DEVICE_ID = os.getenv('ARTIKCLOUD_DEVICE_ID') DEVICE_TOKEN = os.getenv('ARTIKCLOUD_DEVICE_TOKEN') try: AVERAGE = int(os.getenv('AVERAGE', 5)) except: AVERAGE = 5 finally: print("INFO: averaging over {} readings".format(AVERAGE)) PERIOD = 1 # Setting up ARTIK Cloud connection artikcloud.configuration.access_token = DEVICE_TOKEN # Setting up messaging messages_api = artikcloud.MessagesApi() # Create the temperature sensor object using AIO pin 0 temp = grove.GroveTemp(0) print(temp.name()) led = mraa.Gpio(4) led.dir(mraa.DIR_OUT) def reboot_device(): """Restart application through the resin Supervisor """ params = {'apikey': os.getenv('RESIN_SUPERVISOR_API_KEY')} payload = {'appId': os.getenv('RESIN_APP_ID')} supervisor_address = os.getenv('RESIN_SUPERVISOR_ADDRESS') print("Restarting Application") r = requests.post("{}/v1/reboot".format(supervisor_address), supervisor_address, params=params, json=payload) if r.status_code == 200: sys.exit(0) def temp_convert(sensor): """Adapted from UPM source code https://github.com/intel-iot-devkit/upm/blob/4faa71d239f3549556a61df1a9c6f81c3d06bda2/src/grove/grovetemp.cxx#L54-L63 """ a = sensor.raw_value() if a < 0: return -300 m_scale, m_r0, m_b = 1.0, 100000.0, 4275.0 # Apply scale factor after error check a *= m_scale r = (1023.0-a)*m_r0/a t = 1.0/(log(r/m_r0)/m_b + 1.0/298.15)-273.15 return t # Throw away readings to settle down print("Throw-away readings to settle") for i in range(5): celsius = temp_convert(temp) print("Current temperature: {0:.2f}".format(celsius)) time.sleep(1) print("Starting proper readings") i = 0 error_count = 0 readings = deque(maxlen=AVERAGE) while True: loopstart = time.time() celsius = temp_convert(temp) readings.append(celsius) meancelsius = statistics.mean(readings) print("Current temperature: {0:.2f} (mean: {1:.2f})".format(celsius, meancelsius)) if i % 600 == 0: # Send a new message message = artikcloud.Message() message.type = "message" message.sdid = "{}".format(DEVICE_ID) message.ts = int(round(time.time() * 1000)) # timestamp, required message.data = {'Temperature': meancelsius} try: response = messages_api.send_message(message) print(response) except ApiException as error: print("API ERROR: {}".format(str(error))) error_count += 1 except: error = sys.exc_info()[0] print("ERROR: {}".format(error)) error_count += 1 else: error_count = 0 finally: if error_count > 5: reboot_device() i = 0 led.write(1) time.sleep(0.1) led.write(0) i += 1 newsleep = (loopstart + PERIOD) - time.time() if newsleep < 0: print("WARNING: loop took {}s while period is {}!".format(PERIOD - newsleep, PERIOD)) else: time.sleep(newsleep)
29.589744
121
0.644136
import sys import os import time from math import log import statistics from collections import deque import artikcloud from artikcloud.rest import ApiException import pyupm_grove as grove import mraa import requests DEVICE_ID = os.getenv('ARTIKCLOUD_DEVICE_ID') DEVICE_TOKEN = os.getenv('ARTIKCLOUD_DEVICE_TOKEN') try: AVERAGE = int(os.getenv('AVERAGE', 5)) except: AVERAGE = 5 finally: print("INFO: averaging over {} readings".format(AVERAGE)) PERIOD = 1 artikcloud.configuration.access_token = DEVICE_TOKEN messages_api = artikcloud.MessagesApi() temp = grove.GroveTemp(0) print(temp.name()) led = mraa.Gpio(4) led.dir(mraa.DIR_OUT) def reboot_device(): params = {'apikey': os.getenv('RESIN_SUPERVISOR_API_KEY')} payload = {'appId': os.getenv('RESIN_APP_ID')} supervisor_address = os.getenv('RESIN_SUPERVISOR_ADDRESS') print("Restarting Application") r = requests.post("{}/v1/reboot".format(supervisor_address), supervisor_address, params=params, json=payload) if r.status_code == 200: sys.exit(0) def temp_convert(sensor): a = sensor.raw_value() if a < 0: return -300 m_scale, m_r0, m_b = 1.0, 100000.0, 4275.0 a *= m_scale r = (1023.0-a)*m_r0/a t = 1.0/(log(r/m_r0)/m_b + 1.0/298.15)-273.15 return t print("Throw-away readings to settle") for i in range(5): celsius = temp_convert(temp) print("Current temperature: {0:.2f}".format(celsius)) time.sleep(1) print("Starting proper readings") i = 0 error_count = 0 readings = deque(maxlen=AVERAGE) while True: loopstart = time.time() celsius = temp_convert(temp) readings.append(celsius) meancelsius = statistics.mean(readings) print("Current temperature: {0:.2f} (mean: {1:.2f})".format(celsius, meancelsius)) if i % 600 == 0: message = artikcloud.Message() message.type = "message" message.sdid = "{}".format(DEVICE_ID) message.ts = int(round(time.time() * 1000)) message.data = {'Temperature': meancelsius} try: response = messages_api.send_message(message) print(response) except ApiException as error: print("API ERROR: {}".format(str(error))) error_count += 1 except: error = sys.exc_info()[0] print("ERROR: {}".format(error)) error_count += 1 else: error_count = 0 finally: if error_count > 5: reboot_device() i = 0 led.write(1) time.sleep(0.1) led.write(0) i += 1 newsleep = (loopstart + PERIOD) - time.time() if newsleep < 0: print("WARNING: loop took {}s while period is {}!".format(PERIOD - newsleep, PERIOD)) else: time.sleep(newsleep)
true
true
f72a5a2e708a8aa2bbfc8ad3b14c6e6ce0a4298f
701
py
Python
P2/dsa_shuffling_queue.py
MC-DeltaT/DSA-Practicals
5c77cac1cfee5d756b84722e563813c153486770
[ "MIT" ]
null
null
null
P2/dsa_shuffling_queue.py
MC-DeltaT/DSA-Practicals
5c77cac1cfee5d756b84722e563813c153486770
[ "MIT" ]
null
null
null
P2/dsa_shuffling_queue.py
MC-DeltaT/DSA-Practicals
5c77cac1cfee5d756b84722e563813c153486770
[ "MIT" ]
null
null
null
from dsa_queue import DSAQueue class DSAShufflingQueue(DSAQueue): def enqueue(self, obj: object) -> None: if self.is_full(): raise ValueError("Queue is full.") self._array[self._size] = obj self._size += 1 def dequeue(self) -> object: tmp = self.peek() for i in range(0, self._size - 1): self._array[i] = self._array[i + 1] self._size -= 1 return tmp def peek(self) -> object: if self.is_empty(): raise ValueError("Queue is empty.") return self._array[0] # For visualisation purposes only. def as_list(self) -> list: return list(self._array[:self.get_size()])
26.961538
50
0.574893
from dsa_queue import DSAQueue class DSAShufflingQueue(DSAQueue): def enqueue(self, obj: object) -> None: if self.is_full(): raise ValueError("Queue is full.") self._array[self._size] = obj self._size += 1 def dequeue(self) -> object: tmp = self.peek() for i in range(0, self._size - 1): self._array[i] = self._array[i + 1] self._size -= 1 return tmp def peek(self) -> object: if self.is_empty(): raise ValueError("Queue is empty.") return self._array[0] def as_list(self) -> list: return list(self._array[:self.get_size()])
true
true
f72a5b5dc1100cba5f9f50fe40bb4f01308226b6
294
py
Python
nn/optim/optimizer.py
dimaischenko/nn
a7f5887ec816e6b3bbfc57e6864ab3ae320161a6
[ "Apache-2.0" ]
null
null
null
nn/optim/optimizer.py
dimaischenko/nn
a7f5887ec816e6b3bbfc57e6864ab3ae320161a6
[ "Apache-2.0" ]
null
null
null
nn/optim/optimizer.py
dimaischenko/nn
a7f5887ec816e6b3bbfc57e6864ab3ae320161a6
[ "Apache-2.0" ]
null
null
null
class Optimizer(object): """Base abstract class for all optimizers Get network parameters and its gradients and create steps """ def __init__(self, params, grad_params): self.params = params self.grad_params = grad_params def step(self): pass
21
48
0.64966
class Optimizer(object): def __init__(self, params, grad_params): self.params = params self.grad_params = grad_params def step(self): pass
true
true
f72a5c44fcb11c06bc86b2be7515980898efe20d
2,349
py
Python
tests/conftest.py
madkote/rasa-nlu-contrib
38804da8a1debb172a3ad06a9b867a0ae8ee9b59
[ "Apache-2.0" ]
18
2019-05-07T10:28:32.000Z
2022-01-22T02:30:30.000Z
tests/conftest.py
madkote/rasa-nlu-contrib
38804da8a1debb172a3ad06a9b867a0ae8ee9b59
[ "Apache-2.0" ]
2
2019-06-14T17:57:27.000Z
2020-11-30T02:39:39.000Z
tests/conftest.py
madkote/rasa-nlu-contrib
38804da8a1debb172a3ad06a9b867a0ae8ee9b59
[ "Apache-2.0" ]
15
2019-03-18T02:21:13.000Z
2022-01-22T02:32:19.000Z
import logging import os import pytest from rasa_nlu import data_router, config from rasa_nlu.components import ComponentBuilder from rasa_nlu.model import Trainer from rasa_nlu.utils import zip_folder from rasa_nlu import training_data logging.basicConfig(level="DEBUG") CONFIG_DEFAULTS_PATH = "sample_configs/config_defaults.yml" DEFAULT_DATA_PATH = "data/examples/rasa/demo-rasa.json" TEST_MODEL_PATH = "test_models/test_model_pretrained_embeddings" # see `rasa_nlu.data_router` for details. avoids deadlock in # `deferred_from_future` function during tests data_router.DEFERRED_RUN_IN_REACTOR_THREAD = False @pytest.fixture(scope="session") def component_builder(): return ComponentBuilder() @pytest.fixture(scope="session") def spacy_nlp(component_builder, default_config): spacy_nlp_config = {'name': 'SpacyNLP'} return component_builder.create_component(spacy_nlp_config, default_config).nlp @pytest.fixture(scope="session") def ner_crf_pos_feature_config(): return { "features": [ ["low", "title", "upper", "pos", "pos2"], ["bias", "low", "suffix3", "suffix2", "upper", "title", "digit", "pos", "pos2", "pattern"], ["low", "title", "upper", "pos", "pos2"]] } @pytest.fixture(scope="session") def mitie_feature_extractor(component_builder, default_config): mitie_nlp_config = {'name': 'MitieNLP'} return component_builder.create_component(mitie_nlp_config, default_config).extractor @pytest.fixture(scope="session") def default_config(): return config.load(CONFIG_DEFAULTS_PATH) @pytest.fixture(scope="session") def zipped_nlu_model(): spacy_config_path = "sample_configs/config_pretrained_embeddings_spacy.yml" cfg = config.load(spacy_config_path) trainer = Trainer(cfg) td = training_data.load_data(DEFAULT_DATA_PATH) trainer.train(td) trainer.persist("test_models", project_name="test_model_pretrained_embeddings") model_dir_list = os.listdir(TEST_MODEL_PATH) # directory name of latest model model_dir = sorted(model_dir_list)[-1] # path of that directory model_path = os.path.join(TEST_MODEL_PATH, model_dir) zip_path = zip_folder(model_path) return zip_path
28.646341
79
0.707961
import logging import os import pytest from rasa_nlu import data_router, config from rasa_nlu.components import ComponentBuilder from rasa_nlu.model import Trainer from rasa_nlu.utils import zip_folder from rasa_nlu import training_data logging.basicConfig(level="DEBUG") CONFIG_DEFAULTS_PATH = "sample_configs/config_defaults.yml" DEFAULT_DATA_PATH = "data/examples/rasa/demo-rasa.json" TEST_MODEL_PATH = "test_models/test_model_pretrained_embeddings" data_router.DEFERRED_RUN_IN_REACTOR_THREAD = False @pytest.fixture(scope="session") def component_builder(): return ComponentBuilder() @pytest.fixture(scope="session") def spacy_nlp(component_builder, default_config): spacy_nlp_config = {'name': 'SpacyNLP'} return component_builder.create_component(spacy_nlp_config, default_config).nlp @pytest.fixture(scope="session") def ner_crf_pos_feature_config(): return { "features": [ ["low", "title", "upper", "pos", "pos2"], ["bias", "low", "suffix3", "suffix2", "upper", "title", "digit", "pos", "pos2", "pattern"], ["low", "title", "upper", "pos", "pos2"]] } @pytest.fixture(scope="session") def mitie_feature_extractor(component_builder, default_config): mitie_nlp_config = {'name': 'MitieNLP'} return component_builder.create_component(mitie_nlp_config, default_config).extractor @pytest.fixture(scope="session") def default_config(): return config.load(CONFIG_DEFAULTS_PATH) @pytest.fixture(scope="session") def zipped_nlu_model(): spacy_config_path = "sample_configs/config_pretrained_embeddings_spacy.yml" cfg = config.load(spacy_config_path) trainer = Trainer(cfg) td = training_data.load_data(DEFAULT_DATA_PATH) trainer.train(td) trainer.persist("test_models", project_name="test_model_pretrained_embeddings") model_dir_list = os.listdir(TEST_MODEL_PATH) model_dir = sorted(model_dir_list)[-1] model_path = os.path.join(TEST_MODEL_PATH, model_dir) zip_path = zip_folder(model_path) return zip_path
true
true
f72a5c88f96eb156e3a5960ef301b4efb90b71f7
7,657
py
Python
models/resnet_imagenet.py
huawei-noah/Disout
dd4a131ee27043fd3da638056808216944722336
[ "BSD-3-Clause" ]
222
2020-05-19T04:41:44.000Z
2022-03-25T20:31:01.000Z
models/resnet_imagenet.py
huawei-noah/Disout
dd4a131ee27043fd3da638056808216944722336
[ "BSD-3-Clause" ]
13
2020-05-19T09:01:40.000Z
2020-12-02T06:15:29.000Z
models/resnet_imagenet.py
huawei-noah/Disout
dd4a131ee27043fd3da638056808216944722336
[ "BSD-3-Clause" ]
40
2020-05-19T07:08:55.000Z
2022-03-14T00:21:03.000Z
#Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. #This program is free software; you can redistribute it and/or modify it under the terms of the BSD 3-Clause License. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD 3-Clause License for more details. import torch.nn as nn import math import sys sys.path.append("..") from disout import Disout,LinearScheduler dploc = [73, 77, 81, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 148, 152, 156, 160, 164, 168, 173,177, 181, 188, 192, 196, 200, 204, 208, 212] convloc =[75, 79, 90, 90, 94, 98, 106, 106, 110, 114, 122, 122, 126, 130, 138, 138, 142, 146, 154, 154, 158, 162, 171, 171, 175, 179, 190, 190, 194, 198, 206, 206, 210, 214] def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None,dist_prob=None,block_size=None,alpha=None,nr_steps=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class Bottleneck_disout(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): super(Bottleneck_disout, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.disout1=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,padding=1, bias=False) self.disout2=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.disout3=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.disout4=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out=self.disout1(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out=self.disout2(out) out = self.conv3(out) out = self.bn3(out) out=self.disout3(out) if self.downsample is not None: residual = self.downsample(x) residual=self.disout4(residual) out += residual out = self.relu(out) return out class ResNet_disout(nn.Module): def __init__(self, layers, num_classes=1000,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): super(ResNet_disout, self).__init__() self.inplanes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(Bottleneck, 64, layers[0]) self.layer2 = self._make_layer(Bottleneck, 128, layers[1], stride=2) self.layer3 = self._make_layer(Bottleneck_disout, 256, layers[2], stride=2, dist_prob=dist_prob/4,block_size=block_size,alpha=alpha,nr_steps=nr_steps) self.layer4 = self._make_layer(Bottleneck_disout, 512, layers[3], stride=2, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps) self.avgpool = nn.AvgPool2d(7, stride=1) self.fc = nn.Linear(512 * Bottleneck.expansion, num_classes) for name,m in self.named_modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m,nn.BatchNorm2d) and 'bn3'in name: m.weight.data.fill_(0) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion),) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps)) return nn.Sequential(*layers) def forward(self, x): gpu_id = str(x.get_device()) modulelist=list(self.modules()) for imodu in range(len(dploc)): modulelist[dploc[imodu]].weight_behind[gpu_id]=modulelist[convloc[imodu]].weight.data x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x def resnet50_disout(dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): model = ResNet_disout([3, 4, 6, 3],dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps) return model
39.673575
227
0.614079
import torch.nn as nn import math import sys sys.path.append("..") from disout import Disout,LinearScheduler dploc = [73, 77, 81, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 148, 152, 156, 160, 164, 168, 173,177, 181, 188, 192, 196, 200, 204, 208, 212] convloc =[75, 79, 90, 90, 94, 98, 106, 106, 110, 114, 122, 122, 126, 130, 138, 138, 142, 146, 154, 154, 158, 162, 171, 171, 175, 179, 190, 190, 194, 198, 206, 206, 210, 214] def conv3x3(in_planes, out_planes, stride=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None,dist_prob=None,block_size=None,alpha=None,nr_steps=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class Bottleneck_disout(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): super(Bottleneck_disout, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.disout1=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,padding=1, bias=False) self.disout2=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.disout3=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.disout4=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out=self.disout1(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out=self.disout2(out) out = self.conv3(out) out = self.bn3(out) out=self.disout3(out) if self.downsample is not None: residual = self.downsample(x) residual=self.disout4(residual) out += residual out = self.relu(out) return out class ResNet_disout(nn.Module): def __init__(self, layers, num_classes=1000,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): super(ResNet_disout, self).__init__() self.inplanes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(Bottleneck, 64, layers[0]) self.layer2 = self._make_layer(Bottleneck, 128, layers[1], stride=2) self.layer3 = self._make_layer(Bottleneck_disout, 256, layers[2], stride=2, dist_prob=dist_prob/4,block_size=block_size,alpha=alpha,nr_steps=nr_steps) self.layer4 = self._make_layer(Bottleneck_disout, 512, layers[3], stride=2, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps) self.avgpool = nn.AvgPool2d(7, stride=1) self.fc = nn.Linear(512 * Bottleneck.expansion, num_classes) for name,m in self.named_modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m,nn.BatchNorm2d) and 'bn3'in name: m.weight.data.fill_(0) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion),) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps)) return nn.Sequential(*layers) def forward(self, x): gpu_id = str(x.get_device()) modulelist=list(self.modules()) for imodu in range(len(dploc)): modulelist[dploc[imodu]].weight_behind[gpu_id]=modulelist[convloc[imodu]].weight.data x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x def resnet50_disout(dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): model = ResNet_disout([3, 4, 6, 3],dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps) return model
true
true
f72a5cd00105d9d13c7915d5db1087ad43337300
237
py
Python
src/fecc_object/ConstantObject.py
castor91/fecc
bc46059c0d7a428d15b95050b70dec374b4bea28
[ "MIT" ]
1
2018-02-04T14:48:15.000Z
2018-02-04T14:48:15.000Z
src/fecc_object/ConstantObject.py
castor91/fecc
bc46059c0d7a428d15b95050b70dec374b4bea28
[ "MIT" ]
null
null
null
src/fecc_object/ConstantObject.py
castor91/fecc
bc46059c0d7a428d15b95050b70dec374b4bea28
[ "MIT" ]
null
null
null
from AbstractObject import * class ConstantObject(AbstractObject): def __init__(self, value): super(ConstantObject, self).__init__(value._value) def generate(self, out_code): out_code.append(PUSH(self._value))
23.7
58
0.7173
from AbstractObject import * class ConstantObject(AbstractObject): def __init__(self, value): super(ConstantObject, self).__init__(value._value) def generate(self, out_code): out_code.append(PUSH(self._value))
true
true
f72a5d57fc6b542d719802c50c2de09ed475adb4
265
py
Python
output/models/nist_data/atomic/g_month_day/schema_instance/nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/nist_data/atomic/g_month_day/schema_instance/nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/nist_data/atomic/g_month_day/schema_instance/nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.nist_data.atomic.g_month_day.schema_instance.nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd.nistschema_sv_iv_atomic_g_month_day_pattern_2 import NistschemaSvIvAtomicGMonthDayPattern2 __all__ = [ "NistschemaSvIvAtomicGMonthDayPattern2", ]
44.166667
204
0.898113
from output.models.nist_data.atomic.g_month_day.schema_instance.nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd.nistschema_sv_iv_atomic_g_month_day_pattern_2 import NistschemaSvIvAtomicGMonthDayPattern2 __all__ = [ "NistschemaSvIvAtomicGMonthDayPattern2", ]
true
true
f72a5db6ab6073da6de701cf534352393ace0f69
3,681
py
Python
ml_source/src/blocktorch/blocktorch/pipelines/components/estimators/classifiers/logistic_regression_classifier.py
blocktorch/blocktorch
044aa269813ab22c5fd27f84272e5fb540fc522b
[ "MIT" ]
1
2021-09-23T12:23:02.000Z
2021-09-23T12:23:02.000Z
ml_source/src/blocktorch/blocktorch/pipelines/components/estimators/classifiers/logistic_regression_classifier.py
blocktorch/blocktorch
044aa269813ab22c5fd27f84272e5fb540fc522b
[ "MIT" ]
null
null
null
ml_source/src/blocktorch/blocktorch/pipelines/components/estimators/classifiers/logistic_regression_classifier.py
blocktorch/blocktorch
044aa269813ab22c5fd27f84272e5fb540fc522b
[ "MIT" ]
null
null
null
"""Logistic Regression Classifier.""" import numpy as np from sklearn.linear_model import LogisticRegression as SKLogisticRegression from skopt.space import Real from blocktorch.model_family import ModelFamily from blocktorch.pipelines.components.estimators import Estimator from blocktorch.problem_types import ProblemTypes class LogisticRegressionClassifier(Estimator): """Logistic Regression Classifier. Args: penalty ({"l1", "l2", "elasticnet", "none"}): The norm used in penalization. Defaults to "l2". C (float): Inverse of regularization strength. Must be a positive float. Defaults to 1.0. multi_class ({"auto", "ovr", "multinomial"}): If the option chosen is "ovr", then a binary problem is fit for each label. For "multinomial" the loss minimised is the multinomial loss fit across the entire probability distribution, even when the data is binary. "multinomial" is unavailable when solver="liblinear". "auto" selects "ovr" if the data is binary, or if solver="liblinear", and otherwise selects "multinomial". Defaults to "auto". solver ({"newton-cg", "lbfgs", "liblinear", "sag", "saga"}): Algorithm to use in the optimization problem. For small datasets, "liblinear" is a good choice, whereas "sag" and "saga" are faster for large ones. For multiclass problems, only "newton-cg", "sag", "saga" and "lbfgs" handle multinomial loss; "liblinear" is limited to one-versus-rest schemes. - "newton-cg", "lbfgs", "sag" and "saga" handle L2 or no penalty - "liblinear" and "saga" also handle L1 penalty - "saga" also supports "elasticnet" penalty - "liblinear" does not support setting penalty='none' Defaults to "lbfgs". n_jobs (int): Number of parallel threads used to run xgboost. Note that creating thread contention will significantly slow down the algorithm. Defaults to -1. random_seed (int): Seed for the random number generator. Defaults to 0. """ name = "Logistic Regression Classifier" hyperparameter_ranges = { "penalty": ["l2"], "C": Real(0.01, 10), } """{ "penalty": ["l2"], "C": Real(0.01, 10), }""" model_family = ModelFamily.LINEAR_MODEL """ModelFamily.LINEAR_MODEL""" supported_problem_types = [ ProblemTypes.BINARY, ProblemTypes.MULTICLASS, ProblemTypes.TIME_SERIES_BINARY, ProblemTypes.TIME_SERIES_MULTICLASS, ] """[ ProblemTypes.BINARY, ProblemTypes.MULTICLASS, ProblemTypes.TIME_SERIES_BINARY, ProblemTypes.TIME_SERIES_MULTICLASS, ]""" def __init__( self, penalty="l2", C=1.0, multi_class="auto", solver="lbfgs", n_jobs=-1, random_seed=0, **kwargs, ): parameters = { "penalty": penalty, "C": C, "n_jobs": n_jobs, "multi_class": multi_class, "solver": solver, } parameters.update(kwargs) lr_classifier = SKLogisticRegression(random_state=random_seed, **parameters) super().__init__( parameters=parameters, component_obj=lr_classifier, random_seed=random_seed ) @property def feature_importance(self): """Feature importance for fitted logistic regression classifier.""" coef_ = self._component_obj.coef_ # binary classification case if len(coef_) <= 2: return coef_[0] else: # multiclass classification case return np.linalg.norm(coef_, axis=0, ord=2)
40.01087
166
0.640315
import numpy as np from sklearn.linear_model import LogisticRegression as SKLogisticRegression from skopt.space import Real from blocktorch.model_family import ModelFamily from blocktorch.pipelines.components.estimators import Estimator from blocktorch.problem_types import ProblemTypes class LogisticRegressionClassifier(Estimator): name = "Logistic Regression Classifier" hyperparameter_ranges = { "penalty": ["l2"], "C": Real(0.01, 10), } model_family = ModelFamily.LINEAR_MODEL supported_problem_types = [ ProblemTypes.BINARY, ProblemTypes.MULTICLASS, ProblemTypes.TIME_SERIES_BINARY, ProblemTypes.TIME_SERIES_MULTICLASS, ] def __init__( self, penalty="l2", C=1.0, multi_class="auto", solver="lbfgs", n_jobs=-1, random_seed=0, **kwargs, ): parameters = { "penalty": penalty, "C": C, "n_jobs": n_jobs, "multi_class": multi_class, "solver": solver, } parameters.update(kwargs) lr_classifier = SKLogisticRegression(random_state=random_seed, **parameters) super().__init__( parameters=parameters, component_obj=lr_classifier, random_seed=random_seed ) @property def feature_importance(self): coef_ = self._component_obj.coef_ if len(coef_) <= 2: return coef_[0] else: return np.linalg.norm(coef_, axis=0, ord=2)
true
true
f72a5eb729d896a5a7b9e4172a18b461bd416d06
953
py
Python
app/programs/original/rain.py
mike-wendt/unicorn-remote
e649c069482446f08b0baf579de05f065ad7ab89
[ "MIT" ]
37
2017-07-30T16:43:22.000Z
2021-12-12T09:40:11.000Z
app/programs/original/rain.py
kfechter/unicorn-remote
39466cad9e7420b51ffa11fa7554756a934f2d24
[ "MIT" ]
7
2017-11-18T19:22:18.000Z
2021-09-08T15:59:00.000Z
app/programs/original/rain.py
kfechter/unicorn-remote
39466cad9e7420b51ffa11fa7554756a934f2d24
[ "MIT" ]
8
2018-04-21T05:31:40.000Z
2020-12-09T19:43:32.000Z
import unicornhat as unicorn import time, colorsys import random def run(params): m = [[0 for i in range(8)] for i in range(8)] while True: if 1 in m[-1]: top = [0.5 * i for i in m[-1]] elif 0.5 in m[-1]: top = [0] * 8 else: top = [random.randint(0,1) for i in range(2)] + [0,0,0,0,0,0] random.shuffle(top) for i in range(len(top)): if top[i] == 1 and top[i-1] == 1: top[i] = 0 m.append(top) del m[0] for x in range(8): for y in range(8): h = 0.6 s = 0.6 v = m[x][y] * 0.8 rgb = colorsys.hsv_to_rgb(h, s, v) r = int(rgb[0]*255.0) g = int(rgb[1]*255.0) b = int(rgb[2]*255.0) unicorn.set_pixel(8-y-1, x, r, g, b) unicorn.show() time.sleep(0.05)
28.878788
73
0.408185
import unicornhat as unicorn import time, colorsys import random def run(params): m = [[0 for i in range(8)] for i in range(8)] while True: if 1 in m[-1]: top = [0.5 * i for i in m[-1]] elif 0.5 in m[-1]: top = [0] * 8 else: top = [random.randint(0,1) for i in range(2)] + [0,0,0,0,0,0] random.shuffle(top) for i in range(len(top)): if top[i] == 1 and top[i-1] == 1: top[i] = 0 m.append(top) del m[0] for x in range(8): for y in range(8): h = 0.6 s = 0.6 v = m[x][y] * 0.8 rgb = colorsys.hsv_to_rgb(h, s, v) r = int(rgb[0]*255.0) g = int(rgb[1]*255.0) b = int(rgb[2]*255.0) unicorn.set_pixel(8-y-1, x, r, g, b) unicorn.show() time.sleep(0.05)
true
true
f72a5f267601807387faccbf297e7207c244bae9
7,613
py
Python
GPyOpt/util/general.py
komorihi/GPyOpt
5c8424f92ffaa745d3daebca3f38de2569500d6d
[ "BSD-3-Clause" ]
null
null
null
GPyOpt/util/general.py
komorihi/GPyOpt
5c8424f92ffaa745d3daebca3f38de2569500d6d
[ "BSD-3-Clause" ]
null
null
null
GPyOpt/util/general.py
komorihi/GPyOpt
5c8424f92ffaa745d3daebca3f38de2569500d6d
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from scipy.special import erfc import time from ..core.errors import InvalidConfigError def compute_integrated_acquisition(acquisition,x): ''' Used to compute the acquisition function when samples of the hyper-parameters have been generated (used in GP_MCMC model). :param acquisition: acquisition function with GpyOpt model type GP_MCMC. :param x: location where the acquisition is evaluated. ''' acqu_x = 0 for i in range(acquisition.model.num_hmc_samples): acquisition.model.model.kern[:] = acquisition.model.hmc_samples[i,:] acqu_x += acquisition.acquisition_function(x) acqu_x = acqu_x/acquisition.model.num_hmc_samples return acqu_x def compute_integrated_acquisition_withGradients(acquisition,x): ''' Used to compute the acquisition function with gradients when samples of the hyper-parameters have been generated (used in GP_MCMC model). :param acquisition: acquisition function with GpyOpt model type GP_MCMC. :param x: location where the acquisition is evaluated. ''' acqu_x = 0 d_acqu_x = 0 for i in range(acquisition.model.num_hmc_samples): acquisition.model.model.kern[:] = acquisition.model.hmc_samples[i,:] acqu_x_sample, d_acqu_x_sample = acquisition.acquisition_function_withGradients(x) acqu_x += acqu_x_sample d_acqu_x += d_acqu_x_sample acqu_x = acqu_x/acquisition.model.num_hmc_samples d_acqu_x = d_acqu_x/acquisition.model.num_hmc_samples return acqu_x, d_acqu_x def best_guess(f,X): ''' Gets the best current guess from a vector. :param f: function to evaluate. :param X: locations. ''' n = X.shape[0] xbest = np.zeros(n) for i in range(n): ff = f(X[0:(i+1)]) xbest[i] = ff[np.argmin(ff)] return xbest def samples_multidimensional_uniform(bounds,num_data): ''' Generates a multidimensional grid uniformly distributed. :param bounds: tuple defining the box constrains. :num_data: number of data points to generate. ''' dim = len(bounds) Z_rand = np.zeros(shape=(num_data,dim)) for k in range(0,dim): Z_rand[:,k] = np.random.uniform(low=bounds[k][0],high=bounds[k][1],size=num_data) return Z_rand def reshape(x,input_dim): ''' Reshapes x into a matrix with input_dim columns ''' x = np.array(x) if x.size ==input_dim: x = x.reshape((1,input_dim)) return x def get_moments(model,x): ''' Moments (mean and sdev.) of a GP model at x ''' input_dim = model.X.shape[1] x = reshape(x,input_dim) fmin = min(model.predict(model.X)[0]) m, v = model.predict(x) s = np.sqrt(np.clip(v, 0, np.inf)) return (m,s, fmin) def get_d_moments(model,x): ''' Gradients with respect to x of the moments (mean and sdev.) of the GP :param model: GPy model. :param x: location where the gradients are evaluated. ''' input_dim = model.input_dim x = reshape(x,input_dim) _, v = model.predict(x) dmdx, dvdx = model.predictive_gradients(x) dmdx = dmdx[:,:,0] dsdx = dvdx / (2*np.sqrt(v)) return (dmdx, dsdx) def get_quantiles(acquisition_par, fmin, m, s): ''' Quantiles of the Gaussian distribution useful to determine the acquisition function values :param acquisition_par: parameter of the acquisition function :param fmin: current minimum. :param m: vector of means. :param s: vector of standard deviations. ''' if isinstance(s, np.ndarray): s[s<1e-10] = 1e-10 elif s< 1e-10: s = 1e-10 u = (fmin-m-acquisition_par)/s phi = np.exp(-0.5 * u**2) / np.sqrt(2*np.pi) Phi = 0.5 * erfc(-u / np.sqrt(2)) return (phi, Phi, u) def best_value(Y,sign=1): ''' Returns a vector whose components i are the minimum (default) or maximum of Y[:i] ''' n = Y.shape[0] Y_best = np.ones(n) for i in range(n): if sign == 1: Y_best[i]=Y[:(i+1)].min() else: Y_best[i]=Y[:(i+1)].max() return Y_best def spawn(f): ''' Function for parallel evaluation of the acquisition function ''' def fun(pipe,x): pipe.send(f(x)) pipe.close() return fun def evaluate_function(f,X): ''' Returns the evaluation of a function *f* and the time per evaluation ''' num_data, dim_data = X.shape Y_eval = np.zeros((num_data, dim_data)) Y_time = np.zeros((num_data, 1)) for i in range(num_data): time_zero = time.time() Y_eval[i,:] = f(X[i,:]) Y_time[i,:] = time.time() - time_zero return Y_eval, Y_time def values_to_array(input_values): ''' Transforms a values of int, float and tuples to a column vector numpy array ''' if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) elif type(input_values)==int or type(input_values)==float or type(np.int64): values = np.atleast_2d(np.array(input_values)) else: print('Type to transform not recognized') return values def merge_values(values1,values2): ''' Merges two numpy arrays by calculating all possible combinations of rows ''' array1 = values_to_array(values1) array2 = values_to_array(values2) if array1.size == 0: return array2 if array2.size == 0: return array1 merged_array = [] for row_array1 in array1: for row_array2 in array2: merged_row = np.hstack((row_array1,row_array2)) merged_array.append(merged_row) return np.atleast_2d(merged_array) def round_optimum(x_opt,domain): """ Rounds the some value x_opt to a feasible value in the function domain. """ x_opt_rounded = x_opt.copy() counter = 0 for variable in domain: if variable.type == 'continuous': var_dim = 1 elif variable.type == 'discrete': var_dim = 1 x_opt_rounded[0,counter:(counter+var_dim)] = round_discrete(x_opt[0,counter:(counter+var_dim)],variable.domain) elif variable.type == 'categorical': var_dim = len(variable.domain) x_opt_rounded[0,counter:(counter+var_dim)] = round_categorical(x_opt[0,counter:(counter+var_dim)]) elif variable.type == 'bandit': var_dim = variable.domain.shape[1] x_opt_rounded[0,counter:(counter+var_dim)] = round_bandit(x_opt[0,counter:(counter+var_dim)],variable.domain) else: raise Exception('Wrong type of variable') counter += var_dim return x_opt_rounded def round_categorical(values): """ Rounds a categorical variable by taking setting to one the max of the given vector and to zero the rest of the entries. """ rounded_values = np.zeros(values.shape) rounded_values[np.argmax(values)] = 1 return rounded_values def round_discrete(value,domain): """ Rounds a discrete variable by selecting the closest point in the domain """ rounded_value = domain[0] for domain_value in domain: if np.abs(domain_value-value)< np.abs(rounded_value-value): rounded_value = domain_value return rounded_value def round_bandit(value,domain): """ Rounds a discrete variable by selecting the closest point in the domain """ idx = np.argmin(((domain- value)**2).sum(1)) return domain[idx,:]
29.507752
141
0.652305
import numpy as np from scipy.special import erfc import time from ..core.errors import InvalidConfigError def compute_integrated_acquisition(acquisition,x): acqu_x = 0 for i in range(acquisition.model.num_hmc_samples): acquisition.model.model.kern[:] = acquisition.model.hmc_samples[i,:] acqu_x += acquisition.acquisition_function(x) acqu_x = acqu_x/acquisition.model.num_hmc_samples return acqu_x def compute_integrated_acquisition_withGradients(acquisition,x): acqu_x = 0 d_acqu_x = 0 for i in range(acquisition.model.num_hmc_samples): acquisition.model.model.kern[:] = acquisition.model.hmc_samples[i,:] acqu_x_sample, d_acqu_x_sample = acquisition.acquisition_function_withGradients(x) acqu_x += acqu_x_sample d_acqu_x += d_acqu_x_sample acqu_x = acqu_x/acquisition.model.num_hmc_samples d_acqu_x = d_acqu_x/acquisition.model.num_hmc_samples return acqu_x, d_acqu_x def best_guess(f,X): n = X.shape[0] xbest = np.zeros(n) for i in range(n): ff = f(X[0:(i+1)]) xbest[i] = ff[np.argmin(ff)] return xbest def samples_multidimensional_uniform(bounds,num_data): dim = len(bounds) Z_rand = np.zeros(shape=(num_data,dim)) for k in range(0,dim): Z_rand[:,k] = np.random.uniform(low=bounds[k][0],high=bounds[k][1],size=num_data) return Z_rand def reshape(x,input_dim): x = np.array(x) if x.size ==input_dim: x = x.reshape((1,input_dim)) return x def get_moments(model,x): input_dim = model.X.shape[1] x = reshape(x,input_dim) fmin = min(model.predict(model.X)[0]) m, v = model.predict(x) s = np.sqrt(np.clip(v, 0, np.inf)) return (m,s, fmin) def get_d_moments(model,x): input_dim = model.input_dim x = reshape(x,input_dim) _, v = model.predict(x) dmdx, dvdx = model.predictive_gradients(x) dmdx = dmdx[:,:,0] dsdx = dvdx / (2*np.sqrt(v)) return (dmdx, dsdx) def get_quantiles(acquisition_par, fmin, m, s): if isinstance(s, np.ndarray): s[s<1e-10] = 1e-10 elif s< 1e-10: s = 1e-10 u = (fmin-m-acquisition_par)/s phi = np.exp(-0.5 * u**2) / np.sqrt(2*np.pi) Phi = 0.5 * erfc(-u / np.sqrt(2)) return (phi, Phi, u) def best_value(Y,sign=1): n = Y.shape[0] Y_best = np.ones(n) for i in range(n): if sign == 1: Y_best[i]=Y[:(i+1)].min() else: Y_best[i]=Y[:(i+1)].max() return Y_best def spawn(f): def fun(pipe,x): pipe.send(f(x)) pipe.close() return fun def evaluate_function(f,X): num_data, dim_data = X.shape Y_eval = np.zeros((num_data, dim_data)) Y_time = np.zeros((num_data, 1)) for i in range(num_data): time_zero = time.time() Y_eval[i,:] = f(X[i,:]) Y_time[i,:] = time.time() - time_zero return Y_eval, Y_time def values_to_array(input_values): if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) elif type(input_values)==int or type(input_values)==float or type(np.int64): values = np.atleast_2d(np.array(input_values)) else: print('Type to transform not recognized') return values def merge_values(values1,values2): array1 = values_to_array(values1) array2 = values_to_array(values2) if array1.size == 0: return array2 if array2.size == 0: return array1 merged_array = [] for row_array1 in array1: for row_array2 in array2: merged_row = np.hstack((row_array1,row_array2)) merged_array.append(merged_row) return np.atleast_2d(merged_array) def round_optimum(x_opt,domain): x_opt_rounded = x_opt.copy() counter = 0 for variable in domain: if variable.type == 'continuous': var_dim = 1 elif variable.type == 'discrete': var_dim = 1 x_opt_rounded[0,counter:(counter+var_dim)] = round_discrete(x_opt[0,counter:(counter+var_dim)],variable.domain) elif variable.type == 'categorical': var_dim = len(variable.domain) x_opt_rounded[0,counter:(counter+var_dim)] = round_categorical(x_opt[0,counter:(counter+var_dim)]) elif variable.type == 'bandit': var_dim = variable.domain.shape[1] x_opt_rounded[0,counter:(counter+var_dim)] = round_bandit(x_opt[0,counter:(counter+var_dim)],variable.domain) else: raise Exception('Wrong type of variable') counter += var_dim return x_opt_rounded def round_categorical(values): rounded_values = np.zeros(values.shape) rounded_values[np.argmax(values)] = 1 return rounded_values def round_discrete(value,domain): rounded_value = domain[0] for domain_value in domain: if np.abs(domain_value-value)< np.abs(rounded_value-value): rounded_value = domain_value return rounded_value def round_bandit(value,domain): idx = np.argmin(((domain- value)**2).sum(1)) return domain[idx,:]
true
true
f72a6096610e02f8d2fd5a97a6ffa630d71313b8
167
py
Python
usuario/admin.py
UNIZAR-30226-2021-05/Lector--Backend
8cc285216972f7485781ece51a88d5f02dc85013
[ "MIT" ]
null
null
null
usuario/admin.py
UNIZAR-30226-2021-05/Lector--Backend
8cc285216972f7485781ece51a88d5f02dc85013
[ "MIT" ]
null
null
null
usuario/admin.py
UNIZAR-30226-2021-05/Lector--Backend
8cc285216972f7485781ece51a88d5f02dc85013
[ "MIT" ]
null
null
null
from django.contrib import admin # Register your models here. from .models import Usuario, Preferencias admin.site.register(Usuario) admin.site.register(Preferencias)
27.833333
41
0.826347
from django.contrib import admin from .models import Usuario, Preferencias admin.site.register(Usuario) admin.site.register(Preferencias)
true
true
f72a6262313ce7497db5b2c9b1f07193731722d5
56,933
gyp
Python
node_modules/nodegit/vendor/libgit2.gyp
nodeframe/dite
bfe7d02af159b39b42a2c88fde4ce369db021c85
[ "MIT" ]
12
2016-08-19T23:21:41.000Z
2022-02-17T13:40:25.000Z
vendor/libgit2.gyp
Acidburn0zzz/nodegit
b4e85cd641ebf537edfe2f41f4687057bc517c02
[ "MIT" ]
null
null
null
vendor/libgit2.gyp
Acidburn0zzz/nodegit
b4e85cd641ebf537edfe2f41f4687057bc517c02
[ "MIT" ]
8
2015-10-24T11:57:55.000Z
2022-02-15T15:05:11.000Z
{ # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. "variables": { "target_arch%": "x86", "library%": "static_library", "openssl_enable_asm%": 0, # only supported with the Visual Studio 2012 (VC11) toolchain. "gcc_version%": 0, "is_clang%": 0, }, "targets": [ { "target_name": "libgit2", "type": "static_library", "defines": [ "GIT_THREADS", "GIT_SSH", # Node's util.h may be accidentally included so use this to guard # against compilation error. "SRC_UTIL_H_", ], "dependencies": [ "zlib", "<(module_root_dir)/vendor/http_parser/http_parser.gyp:http_parser", "libssh2", "openssl" ], "sources": [ "libgit2/src/array.h", "libgit2/src/attr.c", "libgit2/src/attr.h", "libgit2/src/attr_file.c", "libgit2/src/attr_file.h", "libgit2/src/attrcache.c", "libgit2/src/attrcache.h", "libgit2/src/bitvec.h", "libgit2/src/blame.c", "libgit2/src/blame.h", "libgit2/src/blame_git.c", "libgit2/src/blame_git.h", "libgit2/src/blob.c", "libgit2/src/blob.h", "libgit2/src/branch.c", "libgit2/src/branch.h", "libgit2/src/bswap.h", "libgit2/src/buf_text.c", "libgit2/src/buf_text.h", "libgit2/src/buffer.c", "libgit2/src/buffer.h", "libgit2/src/cache.c", "libgit2/src/cache.h", "libgit2/src/cc-compat.h", "libgit2/src/checkout.c", "libgit2/src/checkout.h", "libgit2/src/cherrypick.c", "libgit2/src/clone.c", "libgit2/src/clone.h", "libgit2/src/commit.c", "libgit2/src/commit.h", "libgit2/src/commit_list.c", "libgit2/src/commit_list.h", "libgit2/src/common.h", "libgit2/src/config.c", "libgit2/src/config.h", "libgit2/src/config_cache.c", "libgit2/src/config_file.c", "libgit2/src/config_file.h", "libgit2/src/crlf.c", "libgit2/src/date.c", "libgit2/src/delta-apply.c", "libgit2/src/delta-apply.h", "libgit2/src/delta.c", "libgit2/src/delta.h", "libgit2/src/diff.c", "libgit2/src/diff.h", "libgit2/src/diff_driver.c", "libgit2/src/diff_driver.h", "libgit2/src/diff_file.c", "libgit2/src/diff_file.h", "libgit2/src/diff_patch.c", "libgit2/src/diff_patch.h", "libgit2/src/diff_print.c", "libgit2/src/diff_stats.c", "libgit2/src/diff_tform.c", "libgit2/src/diff_xdiff.c", "libgit2/src/diff_xdiff.h", "libgit2/src/errors.c", "libgit2/src/fetch.c", "libgit2/src/fetch.h", "libgit2/src/fetchhead.c", "libgit2/src/fetchhead.h", "libgit2/src/filebuf.c", "libgit2/src/filebuf.h", "libgit2/src/fileops.c", "libgit2/src/fileops.h", "libgit2/src/filter.c", "libgit2/src/filter.h", "libgit2/src/fnmatch.c", "libgit2/src/fnmatch.h", "libgit2/src/global.c", "libgit2/src/global.h", "libgit2/src/graph.c", "libgit2/src/hash.c", "libgit2/src/hash.h", "libgit2/src/hashsig.c", "libgit2/src/hashsig.h", "libgit2/src/ident.c", "libgit2/src/ignore.c", "libgit2/src/ignore.h", "libgit2/src/index.c", "libgit2/src/index.h", "libgit2/src/indexer.c", "libgit2/src/iterator.c", "libgit2/src/iterator.h", "libgit2/src/khash.h", "libgit2/src/map.h", "libgit2/src/merge.c", "libgit2/src/merge.h", "libgit2/src/merge_file.c", "libgit2/src/merge_file.h", "libgit2/src/message.c", "libgit2/src/message.h", "libgit2/src/mwindow.c", "libgit2/src/mwindow.h", "libgit2/src/netops.c", "libgit2/src/netops.h", "libgit2/src/notes.c", "libgit2/src/notes.h", "libgit2/src/object.c", "libgit2/src/object.h", "libgit2/src/object_api.c", "libgit2/src/odb.c", "libgit2/src/odb.h", "libgit2/src/odb_loose.c", "libgit2/src/odb_mempack.c", "libgit2/src/odb_pack.c", "libgit2/src/offmap.h", "libgit2/src/oid.c", "libgit2/src/oid.h", "libgit2/src/oidmap.h", "libgit2/src/pack-objects.c", "libgit2/src/pack-objects.h", "libgit2/src/pack.c", "libgit2/src/pack.h", "libgit2/src/path.c", "libgit2/src/path.h", "libgit2/src/pathspec.c", "libgit2/src/pathspec.h", "libgit2/src/pool.c", "libgit2/src/pool.h", "libgit2/src/posix.c", "libgit2/src/posix.h", "libgit2/src/pqueue.c", "libgit2/src/pqueue.h", "libgit2/src/push.c", "libgit2/src/push.h", "libgit2/src/refdb.c", "libgit2/src/refdb.h", "libgit2/src/refdb_fs.c", "libgit2/src/refdb_fs.h", "libgit2/src/reflog.c", "libgit2/src/reflog.h", "libgit2/src/refs.c", "libgit2/src/refs.h", "libgit2/src/refspec.c", "libgit2/src/refspec.h", "libgit2/src/remote.c", "libgit2/src/remote.h", "libgit2/src/repo_template.h", "libgit2/src/repository.c", "libgit2/src/repository.h", "libgit2/src/reset.c", "libgit2/src/revert.c", "libgit2/src/revparse.c", "libgit2/src/revwalk.c", "libgit2/src/revwalk.h", "libgit2/src/settings.c", "libgit2/src/sha1_lookup.c", "libgit2/src/sha1_lookup.h", "libgit2/src/signature.c", "libgit2/src/signature.h", "libgit2/src/sortedcache.c", "libgit2/src/sortedcache.h", "libgit2/src/stash.c", "libgit2/src/status.c", "libgit2/src/status.h", "libgit2/src/strmap.c", "libgit2/src/strmap.h", "libgit2/src/strnlen.h", "libgit2/src/submodule.c", "libgit2/src/submodule.h", "libgit2/src/sysdir.c", "libgit2/src/sysdir.h", "libgit2/src/tag.c", "libgit2/src/tag.h", "libgit2/src/thread-utils.c", "libgit2/src/thread-utils.h", "libgit2/src/trace.c", "libgit2/src/trace.h", "libgit2/src/transport.c", "libgit2/src/tree-cache.c", "libgit2/src/tree-cache.h", "libgit2/src/tree.c", "libgit2/src/tree.h", "libgit2/src/tsort.c", "libgit2/src/userdiff.h", "libgit2/src/util.c", "libgit2/src/util.h", "libgit2/src/vector.c", "libgit2/src/vector.h", "libgit2/src/zstream.c", "libgit2/src/zstream.h", "libgit2/src/hash/hash_generic.c", "libgit2/src/hash/hash_generic.h", "libgit2/src/hash/hash_openssl.h", "libgit2/src/transports/cred.c", "libgit2/src/transports/cred_helpers.c", "libgit2/src/transports/git.c", "libgit2/src/transports/http.c", "libgit2/src/transports/local.c", "libgit2/src/transports/smart.c", "libgit2/src/transports/smart.h", "libgit2/src/transports/smart_pkt.c", "libgit2/src/transports/smart_protocol.c", "libgit2/src/transports/ssh.c", "libgit2/src/xdiff/xdiff.h", "libgit2/src/xdiff/xdiffi.c", "libgit2/src/xdiff/xdiffi.h", "libgit2/src/xdiff/xemit.c", "libgit2/src/xdiff/xemit.h", "libgit2/src/xdiff/xhistogram.c", "libgit2/src/xdiff/xinclude.h", "libgit2/src/xdiff/xmacros.h", "libgit2/src/xdiff/xmerge.c", "libgit2/src/xdiff/xpatience.c", "libgit2/src/xdiff/xprepare.c", "libgit2/src/xdiff/xprepare.h", "libgit2/src/xdiff/xtypes.h", "libgit2/src/xdiff/xutils.c", "libgit2/src/xdiff/xutils.h", ], "conditions": [ ["OS!='win'", { "defines": [ "GIT_SSL" ], }], ["OS=='win'", {}, { "sources": [ "libgit2/src/unix/map.c", "libgit2/src/unix/posix.h", "libgit2/src/unix/realpath.c", ] }], ["OS=='linux'", { "cflags": [ "-DGIT_SSH", "-DGIT_SSL", "-w", ], }], ["OS=='win'", { "defines": [ "GIT_WINHTTP", ], "msvs_settings": { "VCLinkerTool": { "AdditionalDependencies": [ "ws2_32.lib", ], }, # Workaround of a strange bug: # TargetMachine + static_library + x64 = nothing. "conditions": [ ["target_arch=='x64'", { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:X64", ], }, }, { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:x86", ], }, }], ], }, "msvs_disabled_warnings": [ # Conversion from 'ssize_t' to 'int32_t', possible loss of data. 4244, # Conversion from 'size_t' to 'int', possible loss of data. 4267, # Different 'volatile' qualifiers. 4090, # 'volatile void *' differs in levels of indirection from 'int'. 4047, # 'InterlockedDecrement' undefined; assuming extern returning int. 4013, ], "sources": [ "libgit2/src/win32/dir.c", "libgit2/src/win32/dir.h", "libgit2/src/win32/error.c", "libgit2/src/win32/error.h", "libgit2/src/win32/findfile.c", "libgit2/src/win32/findfile.h", "libgit2/src/win32/git2.rc", "libgit2/src/win32/map.c", "libgit2/src/win32/mingw-compat.h", "libgit2/src/win32/msvc-compat.h", "libgit2/src/win32/posix.h", "libgit2/src/win32/posix_w32.c", "libgit2/src/win32/precompiled.c", "libgit2/src/win32/precompiled.h", "libgit2/src/win32/pthread.c", "libgit2/src/win32/pthread.h", "libgit2/src/win32/reparse.h", "libgit2/src/win32/utf-conv.c", "libgit2/src/win32/utf-conv.h", "libgit2/src/win32/version.h", "libgit2/src/win32/w32_util.c", "libgit2/src/win32/w32_util.h", "libgit2/src/win32/path_w32.c", "libgit2/src/win32/path_w32.h", "libgit2/src/transports/winhttp.c", "libgit2/deps/regex/regex.c", ], }, { "libraries": [ "-lpthread", ], "sources": [ "libgit2/src/unix/map.c", "libgit2/src/unix/posix.h", "libgit2/src/unix/realpath.c", ], "cflags": [ "-Wno-missing-field-initializers", "-Wno-unused-variable", "-Wno-deprecated-declarations", ], "xcode_settings": { "WARNING_CFLAGS": [ "-Wno-missing-field-initializers", "-Wno-unused-variable", "-Wno-deprecated-declarations", "-Wno-uninitialized", ], }, }, ] ], "include_dirs": [ "libgit2/include", "libgit2/src", "libgit2/deps/regex" ], "direct_dependent_settings": { "include_dirs": [ "libgit2/include", ], }, }, { "target_name": "zlib", "type": "static_library", "sources": [ "libgit2/deps/zlib/adler32.c", "libgit2/deps/zlib/crc32.c", "libgit2/deps/zlib/crc32.h", "libgit2/deps/zlib/deflate.c", "libgit2/deps/zlib/deflate.h", "libgit2/deps/zlib/inffast.c", "libgit2/deps/zlib/inffast.h", "libgit2/deps/zlib/inffixed.h", "libgit2/deps/zlib/inflate.c", "libgit2/deps/zlib/inflate.h", "libgit2/deps/zlib/inftrees.c", "libgit2/deps/zlib/inftrees.h", "libgit2/deps/zlib/trees.c", "libgit2/deps/zlib/trees.h", "libgit2/deps/zlib/zconf.h", "libgit2/deps/zlib/zlib.h", "libgit2/deps/zlib/zutil.c", "libgit2/deps/zlib/zutil.h", ], "defines": [ "NO_VIZ", "STDC", "NO_GZIP", ], "include_dirs": [ "libgit2/include", "libgit2/deps/regex", ], "direct_dependent_settings": { "include_dirs": [ "libgit2/deps/zlib", ], }, }, { "target_name": "libssh2", "type": "static_library", "defines": [ "NETSNMP_ENABLE_IPV6" ], "sources": [ "libssh2/src/agent.c", "libssh2/src/crypt.c", "libssh2/src/keepalive.c", "libssh2/src/libgcrypt.c", "libssh2/src/openssl.c", "libssh2/src/publickey.c", "libssh2/src/sftp.c", "libssh2/src/version.c", "libssh2/src/channel.c", "libssh2/src/global.c", "libssh2/src/kex.c", "libssh2/src/mac.c", "libssh2/src/packet.c", "libssh2/src/scp.c", "libssh2/src/transport.c", "libssh2/src/comp.c", "libssh2/src/hostkey.c", "libssh2/src/knownhost.c", "libssh2/src/misc.c", "libssh2/src/pem.c", "libssh2/src/session.c", "libssh2/src/userauth.c", ], "include_dirs": [ ".", "libssh2/include", ], "dependencies": [ "openssl" ], "direct_dependent_settings": { "include_dirs": [ "libssh2/include" ] }, "conditions": [ ["OS=='win'", { "include_dirs": [ "libssh2/src", "libssh2/win32", "libssh2/include" ], "direct_dependent_settings": { "include_dirs": [ "libssh2/src", "libssh2/win32", "libssh2/include" ] } }], ] }, { "target_name": "openssl", "type": "static_library", "defines": [ #No clue what these are for. "L_ENDIAN", "PURIFY", "_REENTRANT", "NO_WINDOWS_BRAINDEATH", ], "include_dirs": [ ".", "openssl/openssl", "openssl/openssl/crypto", "openssl/openssl/crypto/asn1", "openssl/openssl/crypto/evp", "openssl/openssl/crypto/md2", "openssl/openssl/crypto/modes", "openssl/openssl/crypto/store", "openssl/openssl/include", ], "direct_dependent_settings": { "include_dirs": [ "openssl/openssl/include", "openssl/openssl/include/openssl", ] }, "sources": [ "openssl/openssl/ssl/bio_ssl.c", "openssl/openssl/ssl/d1_both.c", "openssl/openssl/ssl/d1_clnt.c", "openssl/openssl/ssl/d1_enc.c", "openssl/openssl/ssl/d1_lib.c", "openssl/openssl/ssl/d1_meth.c", "openssl/openssl/ssl/d1_pkt.c", "openssl/openssl/ssl/d1_srtp.c", "openssl/openssl/ssl/d1_srvr.c", "openssl/openssl/ssl/kssl.c", "openssl/openssl/ssl/s23_clnt.c", "openssl/openssl/ssl/s23_lib.c", "openssl/openssl/ssl/s23_meth.c", "openssl/openssl/ssl/s23_pkt.c", "openssl/openssl/ssl/s23_srvr.c", "openssl/openssl/ssl/s2_clnt.c", "openssl/openssl/ssl/s2_enc.c", "openssl/openssl/ssl/s2_lib.c", "openssl/openssl/ssl/s2_meth.c", "openssl/openssl/ssl/s2_pkt.c", "openssl/openssl/ssl/s2_srvr.c", "openssl/openssl/ssl/s3_both.c", "openssl/openssl/ssl/s3_clnt.c", "openssl/openssl/ssl/s3_enc.c", "openssl/openssl/ssl/s3_lib.c", "openssl/openssl/ssl/s3_meth.c", "openssl/openssl/ssl/s3_pkt.c", "openssl/openssl/ssl/s3_srvr.c", "openssl/openssl/ssl/s3_cbc.c", "openssl/openssl/ssl/ssl_algs.c", "openssl/openssl/ssl/ssl_asn1.c", "openssl/openssl/ssl/ssl_cert.c", "openssl/openssl/ssl/ssl_ciph.c", "openssl/openssl/ssl/ssl_err.c", "openssl/openssl/ssl/ssl_err2.c", "openssl/openssl/ssl/ssl_lib.c", "openssl/openssl/ssl/ssl_rsa.c", "openssl/openssl/ssl/ssl_sess.c", "openssl/openssl/ssl/ssl_stat.c", "openssl/openssl/ssl/ssl_txt.c", "openssl/openssl/ssl/t1_clnt.c", "openssl/openssl/ssl/t1_enc.c", "openssl/openssl/ssl/t1_lib.c", "openssl/openssl/ssl/t1_meth.c", "openssl/openssl/ssl/t1_reneg.c", "openssl/openssl/ssl/t1_srvr.c", "openssl/openssl/ssl/tls_srp.c", "openssl/openssl/crypto/aes/aes_cfb.c", "openssl/openssl/crypto/aes/aes_ctr.c", "openssl/openssl/crypto/aes/aes_ecb.c", "openssl/openssl/crypto/aes/aes_ige.c", "openssl/openssl/crypto/aes/aes_misc.c", "openssl/openssl/crypto/aes/aes_ofb.c", "openssl/openssl/crypto/aes/aes_wrap.c", "openssl/openssl/crypto/asn1/a_bitstr.c", "openssl/openssl/crypto/asn1/a_bool.c", "openssl/openssl/crypto/asn1/a_bytes.c", "openssl/openssl/crypto/asn1/a_d2i_fp.c", "openssl/openssl/crypto/asn1/a_digest.c", "openssl/openssl/crypto/asn1/a_dup.c", "openssl/openssl/crypto/asn1/a_enum.c", "openssl/openssl/crypto/asn1/a_gentm.c", "openssl/openssl/crypto/asn1/a_i2d_fp.c", "openssl/openssl/crypto/asn1/a_int.c", "openssl/openssl/crypto/asn1/a_mbstr.c", "openssl/openssl/crypto/asn1/a_object.c", "openssl/openssl/crypto/asn1/a_octet.c", "openssl/openssl/crypto/asn1/a_print.c", "openssl/openssl/crypto/asn1/a_set.c", "openssl/openssl/crypto/asn1/a_sign.c", "openssl/openssl/crypto/asn1/a_strex.c", "openssl/openssl/crypto/asn1/a_strnid.c", "openssl/openssl/crypto/asn1/a_time.c", "openssl/openssl/crypto/asn1/a_type.c", "openssl/openssl/crypto/asn1/a_utctm.c", "openssl/openssl/crypto/asn1/a_utf8.c", "openssl/openssl/crypto/asn1/a_verify.c", "openssl/openssl/crypto/asn1/ameth_lib.c", "openssl/openssl/crypto/asn1/asn1_err.c", "openssl/openssl/crypto/asn1/asn1_gen.c", "openssl/openssl/crypto/asn1/asn1_lib.c", "openssl/openssl/crypto/asn1/asn1_par.c", "openssl/openssl/crypto/asn1/asn_mime.c", "openssl/openssl/crypto/asn1/asn_moid.c", "openssl/openssl/crypto/asn1/asn_pack.c", "openssl/openssl/crypto/asn1/bio_asn1.c", "openssl/openssl/crypto/asn1/bio_ndef.c", "openssl/openssl/crypto/asn1/d2i_pr.c", "openssl/openssl/crypto/asn1/d2i_pu.c", "openssl/openssl/crypto/asn1/evp_asn1.c", "openssl/openssl/crypto/asn1/f_enum.c", "openssl/openssl/crypto/asn1/f_int.c", "openssl/openssl/crypto/asn1/f_string.c", "openssl/openssl/crypto/asn1/i2d_pr.c", "openssl/openssl/crypto/asn1/i2d_pu.c", "openssl/openssl/crypto/asn1/n_pkey.c", "openssl/openssl/crypto/asn1/nsseq.c", "openssl/openssl/crypto/asn1/p5_pbe.c", "openssl/openssl/crypto/asn1/p5_pbev2.c", "openssl/openssl/crypto/asn1/p8_pkey.c", "openssl/openssl/crypto/asn1/t_bitst.c", "openssl/openssl/crypto/asn1/t_crl.c", "openssl/openssl/crypto/asn1/t_pkey.c", "openssl/openssl/crypto/asn1/t_req.c", "openssl/openssl/crypto/asn1/t_spki.c", "openssl/openssl/crypto/asn1/t_x509.c", "openssl/openssl/crypto/asn1/t_x509a.c", "openssl/openssl/crypto/asn1/tasn_dec.c", "openssl/openssl/crypto/asn1/tasn_enc.c", "openssl/openssl/crypto/asn1/tasn_fre.c", "openssl/openssl/crypto/asn1/tasn_new.c", "openssl/openssl/crypto/asn1/tasn_prn.c", "openssl/openssl/crypto/asn1/tasn_typ.c", "openssl/openssl/crypto/asn1/tasn_utl.c", "openssl/openssl/crypto/asn1/x_algor.c", "openssl/openssl/crypto/asn1/x_attrib.c", "openssl/openssl/crypto/asn1/x_bignum.c", "openssl/openssl/crypto/asn1/x_crl.c", "openssl/openssl/crypto/asn1/x_exten.c", "openssl/openssl/crypto/asn1/x_info.c", "openssl/openssl/crypto/asn1/x_long.c", "openssl/openssl/crypto/asn1/x_name.c", "openssl/openssl/crypto/asn1/x_nx509.c", "openssl/openssl/crypto/asn1/x_pkey.c", "openssl/openssl/crypto/asn1/x_pubkey.c", "openssl/openssl/crypto/asn1/x_req.c", "openssl/openssl/crypto/asn1/x_sig.c", "openssl/openssl/crypto/asn1/x_spki.c", "openssl/openssl/crypto/asn1/x_val.c", "openssl/openssl/crypto/asn1/x_x509.c", "openssl/openssl/crypto/asn1/x_x509a.c", "openssl/openssl/crypto/bf/bf_cfb64.c", "openssl/openssl/crypto/bf/bf_ecb.c", "openssl/openssl/crypto/bf/bf_ofb64.c", "openssl/openssl/crypto/bf/bf_skey.c", "openssl/openssl/crypto/bio/b_dump.c", "openssl/openssl/crypto/bio/b_print.c", "openssl/openssl/crypto/bio/b_sock.c", "openssl/openssl/crypto/bio/bf_buff.c", "openssl/openssl/crypto/bio/bf_nbio.c", "openssl/openssl/crypto/bio/bf_null.c", "openssl/openssl/crypto/bio/bio_cb.c", "openssl/openssl/crypto/bio/bio_err.c", "openssl/openssl/crypto/bio/bio_lib.c", "openssl/openssl/crypto/bio/bss_acpt.c", "openssl/openssl/crypto/bio/bss_bio.c", "openssl/openssl/crypto/bio/bss_conn.c", "openssl/openssl/crypto/bio/bss_dgram.c", "openssl/openssl/crypto/bio/bss_fd.c", "openssl/openssl/crypto/bio/bss_file.c", "openssl/openssl/crypto/bio/bss_log.c", "openssl/openssl/crypto/bio/bss_mem.c", "openssl/openssl/crypto/bio/bss_null.c", "openssl/openssl/crypto/bio/bss_sock.c", "openssl/openssl/crypto/bn/bn_add.c", "openssl/openssl/crypto/bn/bn_blind.c", "openssl/openssl/crypto/bn/bn_const.c", "openssl/openssl/crypto/bn/bn_ctx.c", "openssl/openssl/crypto/bn/bn_depr.c", "openssl/openssl/crypto/bn/bn_div.c", "openssl/openssl/crypto/bn/bn_err.c", "openssl/openssl/crypto/bn/bn_exp.c", "openssl/openssl/crypto/bn/bn_exp2.c", "openssl/openssl/crypto/bn/bn_gcd.c", "openssl/openssl/crypto/bn/bn_gf2m.c", "openssl/openssl/crypto/bn/bn_kron.c", "openssl/openssl/crypto/bn/bn_lib.c", "openssl/openssl/crypto/bn/bn_mod.c", "openssl/openssl/crypto/bn/bn_mont.c", "openssl/openssl/crypto/bn/bn_mpi.c", "openssl/openssl/crypto/bn/bn_mul.c", "openssl/openssl/crypto/bn/bn_nist.c", "openssl/openssl/crypto/bn/bn_prime.c", "openssl/openssl/crypto/bn/bn_print.c", "openssl/openssl/crypto/bn/bn_rand.c", "openssl/openssl/crypto/bn/bn_recp.c", "openssl/openssl/crypto/bn/bn_shift.c", "openssl/openssl/crypto/bn/bn_sqr.c", "openssl/openssl/crypto/bn/bn_sqrt.c", "openssl/openssl/crypto/bn/bn_word.c", "openssl/openssl/crypto/bn/bn_x931p.c", "openssl/openssl/crypto/buffer/buf_err.c", "openssl/openssl/crypto/buffer/buf_str.c", "openssl/openssl/crypto/buffer/buffer.c", "openssl/openssl/crypto/camellia/cmll_cfb.c", "openssl/openssl/crypto/camellia/cmll_ctr.c", "openssl/openssl/crypto/camellia/cmll_ecb.c", "openssl/openssl/crypto/camellia/cmll_ofb.c", "openssl/openssl/crypto/camellia/cmll_utl.c", "openssl/openssl/crypto/cast/c_cfb64.c", "openssl/openssl/crypto/cast/c_ecb.c", "openssl/openssl/crypto/cast/c_ofb64.c", "openssl/openssl/crypto/cast/c_skey.c", "openssl/openssl/crypto/cmac/cm_ameth.c", "openssl/openssl/crypto/cmac/cm_pmeth.c", "openssl/openssl/crypto/cmac/cmac.c", "openssl/openssl/crypto/cms/cms_asn1.c", "openssl/openssl/crypto/cms/cms_att.c", "openssl/openssl/crypto/cms/cms_cd.c", "openssl/openssl/crypto/cms/cms_dd.c", "openssl/openssl/crypto/cms/cms_enc.c", "openssl/openssl/crypto/cms/cms_env.c", "openssl/openssl/crypto/cms/cms_err.c", "openssl/openssl/crypto/cms/cms_ess.c", "openssl/openssl/crypto/cms/cms_io.c", "openssl/openssl/crypto/cms/cms_lib.c", "openssl/openssl/crypto/cms/cms_pwri.c", "openssl/openssl/crypto/cms/cms_sd.c", "openssl/openssl/crypto/cms/cms_smime.c", "openssl/openssl/crypto/comp/c_rle.c", "openssl/openssl/crypto/comp/c_zlib.c", "openssl/openssl/crypto/comp/comp_err.c", "openssl/openssl/crypto/comp/comp_lib.c", "openssl/openssl/crypto/conf/conf_api.c", "openssl/openssl/crypto/conf/conf_def.c", "openssl/openssl/crypto/conf/conf_err.c", "openssl/openssl/crypto/conf/conf_lib.c", "openssl/openssl/crypto/conf/conf_mall.c", "openssl/openssl/crypto/conf/conf_mod.c", "openssl/openssl/crypto/conf/conf_sap.c", "openssl/openssl/crypto/cpt_err.c", "openssl/openssl/crypto/cryptlib.c", "openssl/openssl/crypto/cversion.c", "openssl/openssl/crypto/des/cbc_cksm.c", "openssl/openssl/crypto/des/cbc_enc.c", "openssl/openssl/crypto/des/cfb64ede.c", "openssl/openssl/crypto/des/cfb64enc.c", "openssl/openssl/crypto/des/cfb_enc.c", "openssl/openssl/crypto/des/des_old.c", "openssl/openssl/crypto/des/des_old2.c", "openssl/openssl/crypto/des/ecb3_enc.c", "openssl/openssl/crypto/des/ecb_enc.c", "openssl/openssl/crypto/des/ede_cbcm_enc.c", "openssl/openssl/crypto/des/enc_read.c", "openssl/openssl/crypto/des/enc_writ.c", "openssl/openssl/crypto/des/fcrypt.c", "openssl/openssl/crypto/des/ofb64ede.c", "openssl/openssl/crypto/des/ofb64enc.c", "openssl/openssl/crypto/des/ofb_enc.c", "openssl/openssl/crypto/des/pcbc_enc.c", "openssl/openssl/crypto/des/qud_cksm.c", "openssl/openssl/crypto/des/rand_key.c", "openssl/openssl/crypto/des/read2pwd.c", "openssl/openssl/crypto/des/rpc_enc.c", "openssl/openssl/crypto/des/set_key.c", "openssl/openssl/crypto/des/str2key.c", "openssl/openssl/crypto/des/xcbc_enc.c", "openssl/openssl/crypto/dh/dh_ameth.c", "openssl/openssl/crypto/dh/dh_asn1.c", "openssl/openssl/crypto/dh/dh_check.c", "openssl/openssl/crypto/dh/dh_depr.c", "openssl/openssl/crypto/dh/dh_err.c", "openssl/openssl/crypto/dh/dh_gen.c", "openssl/openssl/crypto/dh/dh_key.c", "openssl/openssl/crypto/dh/dh_lib.c", "openssl/openssl/crypto/dh/dh_pmeth.c", "openssl/openssl/crypto/dh/dh_prn.c", "openssl/openssl/crypto/dsa/dsa_ameth.c", "openssl/openssl/crypto/dsa/dsa_asn1.c", "openssl/openssl/crypto/dsa/dsa_depr.c", "openssl/openssl/crypto/dsa/dsa_err.c", "openssl/openssl/crypto/dsa/dsa_gen.c", "openssl/openssl/crypto/dsa/dsa_key.c", "openssl/openssl/crypto/dsa/dsa_lib.c", "openssl/openssl/crypto/dsa/dsa_ossl.c", "openssl/openssl/crypto/dsa/dsa_pmeth.c", "openssl/openssl/crypto/dsa/dsa_prn.c", "openssl/openssl/crypto/dsa/dsa_sign.c", "openssl/openssl/crypto/dsa/dsa_vrf.c", "openssl/openssl/crypto/dso/dso_beos.c", "openssl/openssl/crypto/dso/dso_dl.c", "openssl/openssl/crypto/dso/dso_dlfcn.c", "openssl/openssl/crypto/dso/dso_err.c", "openssl/openssl/crypto/dso/dso_lib.c", "openssl/openssl/crypto/dso/dso_null.c", "openssl/openssl/crypto/dso/dso_openssl.c", "openssl/openssl/crypto/dso/dso_vms.c", "openssl/openssl/crypto/dso/dso_win32.c", "openssl/openssl/crypto/ebcdic.c", "openssl/openssl/crypto/ec/ec2_mult.c", "openssl/openssl/crypto/ec/ec2_oct.c", "openssl/openssl/crypto/ec/ec2_smpl.c", "openssl/openssl/crypto/ec/ec_ameth.c", "openssl/openssl/crypto/ec/ec_asn1.c", "openssl/openssl/crypto/ec/ec_check.c", "openssl/openssl/crypto/ec/ec_curve.c", "openssl/openssl/crypto/ec/ec_cvt.c", "openssl/openssl/crypto/ec/ec_err.c", "openssl/openssl/crypto/ec/ec_key.c", "openssl/openssl/crypto/ec/ec_lib.c", "openssl/openssl/crypto/ec/ec_mult.c", "openssl/openssl/crypto/ec/ec_oct.c", "openssl/openssl/crypto/ec/ec_pmeth.c", "openssl/openssl/crypto/ec/ec_print.c", "openssl/openssl/crypto/ec/eck_prn.c", "openssl/openssl/crypto/ec/ecp_mont.c", "openssl/openssl/crypto/ec/ecp_nist.c", "openssl/openssl/crypto/ec/ecp_nistp224.c", "openssl/openssl/crypto/ec/ecp_nistp256.c", "openssl/openssl/crypto/ec/ecp_nistp521.c", "openssl/openssl/crypto/ec/ecp_nistputil.c", "openssl/openssl/crypto/ec/ecp_oct.c", "openssl/openssl/crypto/ec/ecp_smpl.c", "openssl/openssl/crypto/ecdh/ech_err.c", "openssl/openssl/crypto/ecdh/ech_key.c", "openssl/openssl/crypto/ecdh/ech_lib.c", "openssl/openssl/crypto/ecdh/ech_ossl.c", "openssl/openssl/crypto/ecdsa/ecs_asn1.c", "openssl/openssl/crypto/ecdsa/ecs_err.c", "openssl/openssl/crypto/ecdsa/ecs_lib.c", "openssl/openssl/crypto/ecdsa/ecs_ossl.c", "openssl/openssl/crypto/ecdsa/ecs_sign.c", "openssl/openssl/crypto/ecdsa/ecs_vrf.c", "openssl/openssl/crypto/engine/eng_all.c", "openssl/openssl/crypto/engine/eng_cnf.c", "openssl/openssl/crypto/engine/eng_cryptodev.c", "openssl/openssl/crypto/engine/eng_ctrl.c", "openssl/openssl/crypto/engine/eng_dyn.c", "openssl/openssl/crypto/engine/eng_err.c", "openssl/openssl/crypto/engine/eng_fat.c", "openssl/openssl/crypto/engine/eng_init.c", "openssl/openssl/crypto/engine/eng_lib.c", "openssl/openssl/crypto/engine/eng_list.c", "openssl/openssl/crypto/engine/eng_openssl.c", "openssl/openssl/crypto/engine/eng_pkey.c", "openssl/openssl/crypto/engine/eng_rdrand.c", "openssl/openssl/crypto/engine/eng_rsax.c", "openssl/openssl/crypto/engine/eng_table.c", "openssl/openssl/crypto/engine/tb_asnmth.c", "openssl/openssl/crypto/engine/tb_cipher.c", "openssl/openssl/crypto/engine/tb_dh.c", "openssl/openssl/crypto/engine/tb_digest.c", "openssl/openssl/crypto/engine/tb_dsa.c", "openssl/openssl/crypto/engine/tb_ecdh.c", "openssl/openssl/crypto/engine/tb_ecdsa.c", "openssl/openssl/crypto/engine/tb_pkmeth.c", "openssl/openssl/crypto/engine/tb_rand.c", "openssl/openssl/crypto/engine/tb_rsa.c", "openssl/openssl/crypto/engine/tb_store.c", "openssl/openssl/crypto/err/err.c", "openssl/openssl/crypto/err/err_all.c", "openssl/openssl/crypto/err/err_prn.c", "openssl/openssl/crypto/evp/bio_b64.c", "openssl/openssl/crypto/evp/bio_enc.c", "openssl/openssl/crypto/evp/bio_md.c", "openssl/openssl/crypto/evp/bio_ok.c", "openssl/openssl/crypto/evp/c_all.c", "openssl/openssl/crypto/evp/c_allc.c", "openssl/openssl/crypto/evp/c_alld.c", "openssl/openssl/crypto/evp/digest.c", "openssl/openssl/crypto/evp/e_aes.c", "openssl/openssl/crypto/evp/e_aes_cbc_hmac_sha1.c", "openssl/openssl/crypto/evp/e_bf.c", "openssl/openssl/crypto/evp/e_camellia.c", "openssl/openssl/crypto/evp/e_cast.c", "openssl/openssl/crypto/evp/e_des.c", "openssl/openssl/crypto/evp/e_des3.c", "openssl/openssl/crypto/evp/e_idea.c", "openssl/openssl/crypto/evp/e_null.c", "openssl/openssl/crypto/evp/e_old.c", "openssl/openssl/crypto/evp/e_rc2.c", "openssl/openssl/crypto/evp/e_rc4.c", "openssl/openssl/crypto/evp/e_rc4_hmac_md5.c", "openssl/openssl/crypto/evp/e_rc5.c", "openssl/openssl/crypto/evp/e_seed.c", "openssl/openssl/crypto/evp/e_xcbc_d.c", "openssl/openssl/crypto/evp/encode.c", "openssl/openssl/crypto/evp/evp_acnf.c", "openssl/openssl/crypto/evp/evp_cnf.c", "openssl/openssl/crypto/evp/evp_enc.c", "openssl/openssl/crypto/evp/evp_err.c", "openssl/openssl/crypto/evp/evp_fips.c", "openssl/openssl/crypto/evp/evp_key.c", "openssl/openssl/crypto/evp/evp_lib.c", "openssl/openssl/crypto/evp/evp_pbe.c", "openssl/openssl/crypto/evp/evp_pkey.c", "openssl/openssl/crypto/evp/m_dss.c", "openssl/openssl/crypto/evp/m_dss1.c", "openssl/openssl/crypto/evp/m_ecdsa.c", "openssl/openssl/crypto/evp/m_md2.c", "openssl/openssl/crypto/evp/m_md4.c", "openssl/openssl/crypto/evp/m_md5.c", "openssl/openssl/crypto/evp/m_mdc2.c", "openssl/openssl/crypto/evp/m_null.c", "openssl/openssl/crypto/evp/m_ripemd.c", "openssl/openssl/crypto/evp/m_sha.c", "openssl/openssl/crypto/evp/m_sha1.c", "openssl/openssl/crypto/evp/m_sigver.c", "openssl/openssl/crypto/evp/m_wp.c", "openssl/openssl/crypto/evp/names.c", "openssl/openssl/crypto/evp/p5_crpt.c", "openssl/openssl/crypto/evp/p5_crpt2.c", "openssl/openssl/crypto/evp/p_dec.c", "openssl/openssl/crypto/evp/p_enc.c", "openssl/openssl/crypto/evp/p_lib.c", "openssl/openssl/crypto/evp/p_open.c", "openssl/openssl/crypto/evp/p_seal.c", "openssl/openssl/crypto/evp/p_sign.c", "openssl/openssl/crypto/evp/p_verify.c", "openssl/openssl/crypto/evp/pmeth_fn.c", "openssl/openssl/crypto/evp/pmeth_gn.c", "openssl/openssl/crypto/evp/pmeth_lib.c", "openssl/openssl/crypto/ex_data.c", "openssl/openssl/crypto/fips_ers.c", "openssl/openssl/crypto/hmac/hm_ameth.c", "openssl/openssl/crypto/hmac/hm_pmeth.c", "openssl/openssl/crypto/hmac/hmac.c", "openssl/openssl/crypto/idea/i_cbc.c", "openssl/openssl/crypto/idea/i_cfb64.c", "openssl/openssl/crypto/idea/i_ecb.c", "openssl/openssl/crypto/idea/i_ofb64.c", "openssl/openssl/crypto/idea/i_skey.c", "openssl/openssl/crypto/krb5/krb5_asn.c", "openssl/openssl/crypto/lhash/lh_stats.c", "openssl/openssl/crypto/lhash/lhash.c", "openssl/openssl/crypto/md2/md2_dgst.c", "openssl/openssl/crypto/md2/md2_one.c", "openssl/openssl/crypto/md4/md4_dgst.c", "openssl/openssl/crypto/md4/md4_one.c", "openssl/openssl/crypto/md5/md5_dgst.c", "openssl/openssl/crypto/md5/md5_one.c", "openssl/openssl/crypto/mdc2/mdc2_one.c", "openssl/openssl/crypto/mdc2/mdc2dgst.c", "openssl/openssl/crypto/mem.c", "openssl/openssl/crypto/mem_dbg.c", "openssl/openssl/crypto/modes/cbc128.c", "openssl/openssl/crypto/modes/ccm128.c", "openssl/openssl/crypto/modes/cfb128.c", "openssl/openssl/crypto/modes/ctr128.c", "openssl/openssl/crypto/modes/cts128.c", "openssl/openssl/crypto/modes/gcm128.c", "openssl/openssl/crypto/modes/ofb128.c", "openssl/openssl/crypto/modes/xts128.c", "openssl/openssl/crypto/o_dir.c", "openssl/openssl/crypto/o_fips.c", "openssl/openssl/crypto/o_init.c", "openssl/openssl/crypto/o_str.c", "openssl/openssl/crypto/o_time.c", "openssl/openssl/crypto/objects/o_names.c", "openssl/openssl/crypto/objects/obj_dat.c", "openssl/openssl/crypto/objects/obj_err.c", "openssl/openssl/crypto/objects/obj_lib.c", "openssl/openssl/crypto/objects/obj_xref.c", "openssl/openssl/crypto/ocsp/ocsp_asn.c", "openssl/openssl/crypto/ocsp/ocsp_cl.c", "openssl/openssl/crypto/ocsp/ocsp_err.c", "openssl/openssl/crypto/ocsp/ocsp_ext.c", "openssl/openssl/crypto/ocsp/ocsp_ht.c", "openssl/openssl/crypto/ocsp/ocsp_lib.c", "openssl/openssl/crypto/ocsp/ocsp_prn.c", "openssl/openssl/crypto/ocsp/ocsp_srv.c", "openssl/openssl/crypto/ocsp/ocsp_vfy.c", "openssl/openssl/crypto/pem/pem_all.c", "openssl/openssl/crypto/pem/pem_err.c", "openssl/openssl/crypto/pem/pem_info.c", "openssl/openssl/crypto/pem/pem_lib.c", "openssl/openssl/crypto/pem/pem_oth.c", "openssl/openssl/crypto/pem/pem_pk8.c", "openssl/openssl/crypto/pem/pem_pkey.c", "openssl/openssl/crypto/pem/pem_seal.c", "openssl/openssl/crypto/pem/pem_sign.c", "openssl/openssl/crypto/pem/pem_x509.c", "openssl/openssl/crypto/pem/pem_xaux.c", "openssl/openssl/crypto/pem/pvkfmt.c", "openssl/openssl/crypto/pkcs12/p12_add.c", "openssl/openssl/crypto/pkcs12/p12_asn.c", "openssl/openssl/crypto/pkcs12/p12_attr.c", "openssl/openssl/crypto/pkcs12/p12_crpt.c", "openssl/openssl/crypto/pkcs12/p12_crt.c", "openssl/openssl/crypto/pkcs12/p12_decr.c", "openssl/openssl/crypto/pkcs12/p12_init.c", "openssl/openssl/crypto/pkcs12/p12_key.c", "openssl/openssl/crypto/pkcs12/p12_kiss.c", "openssl/openssl/crypto/pkcs12/p12_mutl.c", "openssl/openssl/crypto/pkcs12/p12_npas.c", "openssl/openssl/crypto/pkcs12/p12_p8d.c", "openssl/openssl/crypto/pkcs12/p12_p8e.c", "openssl/openssl/crypto/pkcs12/p12_utl.c", "openssl/openssl/crypto/pkcs12/pk12err.c", "openssl/openssl/crypto/pkcs7/bio_pk7.c", "openssl/openssl/crypto/pkcs7/pk7_asn1.c", "openssl/openssl/crypto/pkcs7/pk7_attr.c", "openssl/openssl/crypto/pkcs7/pk7_doit.c", "openssl/openssl/crypto/pkcs7/pk7_lib.c", "openssl/openssl/crypto/pkcs7/pk7_mime.c", "openssl/openssl/crypto/pkcs7/pk7_smime.c", "openssl/openssl/crypto/pkcs7/pkcs7err.c", "openssl/openssl/crypto/pqueue/pqueue.c", "openssl/openssl/crypto/rand/md_rand.c", "openssl/openssl/crypto/rand/rand_egd.c", "openssl/openssl/crypto/rand/rand_err.c", "openssl/openssl/crypto/rand/rand_lib.c", "openssl/openssl/crypto/rand/rand_nw.c", "openssl/openssl/crypto/rand/rand_os2.c", "openssl/openssl/crypto/rand/rand_unix.c", "openssl/openssl/crypto/rand/rand_win.c", "openssl/openssl/crypto/rand/randfile.c", "openssl/openssl/crypto/rc2/rc2_cbc.c", "openssl/openssl/crypto/rc2/rc2_ecb.c", "openssl/openssl/crypto/rc2/rc2_skey.c", "openssl/openssl/crypto/rc2/rc2cfb64.c", "openssl/openssl/crypto/rc2/rc2ofb64.c", "openssl/openssl/crypto/rc4/rc4_utl.c", "openssl/openssl/crypto/ripemd/rmd_dgst.c", "openssl/openssl/crypto/ripemd/rmd_one.c", "openssl/openssl/crypto/rsa/rsa_ameth.c", "openssl/openssl/crypto/rsa/rsa_asn1.c", "openssl/openssl/crypto/rsa/rsa_chk.c", "openssl/openssl/crypto/rsa/rsa_crpt.c", "openssl/openssl/crypto/rsa/rsa_depr.c", "openssl/openssl/crypto/rsa/rsa_eay.c", "openssl/openssl/crypto/rsa/rsa_err.c", "openssl/openssl/crypto/rsa/rsa_gen.c", "openssl/openssl/crypto/rsa/rsa_lib.c", "openssl/openssl/crypto/rsa/rsa_none.c", "openssl/openssl/crypto/rsa/rsa_null.c", "openssl/openssl/crypto/rsa/rsa_oaep.c", "openssl/openssl/crypto/rsa/rsa_pk1.c", "openssl/openssl/crypto/rsa/rsa_pmeth.c", "openssl/openssl/crypto/rsa/rsa_prn.c", "openssl/openssl/crypto/rsa/rsa_pss.c", "openssl/openssl/crypto/rsa/rsa_saos.c", "openssl/openssl/crypto/rsa/rsa_sign.c", "openssl/openssl/crypto/rsa/rsa_ssl.c", "openssl/openssl/crypto/rsa/rsa_x931.c", "openssl/openssl/crypto/seed/seed.c", "openssl/openssl/crypto/seed/seed_cbc.c", "openssl/openssl/crypto/seed/seed_cfb.c", "openssl/openssl/crypto/seed/seed_ecb.c", "openssl/openssl/crypto/seed/seed_ofb.c", "openssl/openssl/crypto/sha/sha1_one.c", "openssl/openssl/crypto/sha/sha1dgst.c", "openssl/openssl/crypto/sha/sha256.c", "openssl/openssl/crypto/sha/sha512.c", "openssl/openssl/crypto/sha/sha_dgst.c", "openssl/openssl/crypto/sha/sha_one.c", "openssl/openssl/crypto/srp/srp_lib.c", "openssl/openssl/crypto/srp/srp_vfy.c", "openssl/openssl/crypto/stack/stack.c", "openssl/openssl/crypto/store/str_err.c", "openssl/openssl/crypto/store/str_lib.c", "openssl/openssl/crypto/store/str_mem.c", "openssl/openssl/crypto/store/str_meth.c", "openssl/openssl/crypto/ts/ts_asn1.c", "openssl/openssl/crypto/ts/ts_conf.c", "openssl/openssl/crypto/ts/ts_err.c", "openssl/openssl/crypto/ts/ts_lib.c", "openssl/openssl/crypto/ts/ts_req_print.c", "openssl/openssl/crypto/ts/ts_req_utils.c", "openssl/openssl/crypto/ts/ts_rsp_print.c", "openssl/openssl/crypto/ts/ts_rsp_sign.c", "openssl/openssl/crypto/ts/ts_rsp_utils.c", "openssl/openssl/crypto/ts/ts_rsp_verify.c", "openssl/openssl/crypto/ts/ts_verify_ctx.c", "openssl/openssl/crypto/txt_db/txt_db.c", "openssl/openssl/crypto/ui/ui_compat.c", "openssl/openssl/crypto/ui/ui_err.c", "openssl/openssl/crypto/ui/ui_lib.c", "openssl/openssl/crypto/ui/ui_openssl.c", "openssl/openssl/crypto/ui/ui_util.c", "openssl/openssl/crypto/uid.c", "openssl/openssl/crypto/whrlpool/wp_dgst.c", "openssl/openssl/crypto/x509/by_dir.c", "openssl/openssl/crypto/x509/by_file.c", "openssl/openssl/crypto/x509/x509_att.c", "openssl/openssl/crypto/x509/x509_cmp.c", "openssl/openssl/crypto/x509/x509_d2.c", "openssl/openssl/crypto/x509/x509_def.c", "openssl/openssl/crypto/x509/x509_err.c", "openssl/openssl/crypto/x509/x509_ext.c", "openssl/openssl/crypto/x509/x509_lu.c", "openssl/openssl/crypto/x509/x509_obj.c", "openssl/openssl/crypto/x509/x509_r2x.c", "openssl/openssl/crypto/x509/x509_req.c", "openssl/openssl/crypto/x509/x509_set.c", "openssl/openssl/crypto/x509/x509_trs.c", "openssl/openssl/crypto/x509/x509_txt.c", "openssl/openssl/crypto/x509/x509_v3.c", "openssl/openssl/crypto/x509/x509_vfy.c", "openssl/openssl/crypto/x509/x509_vpm.c", "openssl/openssl/crypto/x509/x509cset.c", "openssl/openssl/crypto/x509/x509name.c", "openssl/openssl/crypto/x509/x509rset.c", "openssl/openssl/crypto/x509/x509spki.c", "openssl/openssl/crypto/x509/x509type.c", "openssl/openssl/crypto/x509/x_all.c", "openssl/openssl/crypto/x509v3/pcy_cache.c", "openssl/openssl/crypto/x509v3/pcy_data.c", "openssl/openssl/crypto/x509v3/pcy_lib.c", "openssl/openssl/crypto/x509v3/pcy_map.c", "openssl/openssl/crypto/x509v3/pcy_node.c", "openssl/openssl/crypto/x509v3/pcy_tree.c", "openssl/openssl/crypto/x509v3/v3_addr.c", "openssl/openssl/crypto/x509v3/v3_akey.c", "openssl/openssl/crypto/x509v3/v3_akeya.c", "openssl/openssl/crypto/x509v3/v3_alt.c", "openssl/openssl/crypto/x509v3/v3_asid.c", "openssl/openssl/crypto/x509v3/v3_bcons.c", "openssl/openssl/crypto/x509v3/v3_bitst.c", "openssl/openssl/crypto/x509v3/v3_conf.c", "openssl/openssl/crypto/x509v3/v3_cpols.c", "openssl/openssl/crypto/x509v3/v3_crld.c", "openssl/openssl/crypto/x509v3/v3_enum.c", "openssl/openssl/crypto/x509v3/v3_extku.c", "openssl/openssl/crypto/x509v3/v3_genn.c", "openssl/openssl/crypto/x509v3/v3_ia5.c", "openssl/openssl/crypto/x509v3/v3_info.c", "openssl/openssl/crypto/x509v3/v3_int.c", "openssl/openssl/crypto/x509v3/v3_lib.c", "openssl/openssl/crypto/x509v3/v3_ncons.c", "openssl/openssl/crypto/x509v3/v3_ocsp.c", "openssl/openssl/crypto/x509v3/v3_pci.c", "openssl/openssl/crypto/x509v3/v3_pcia.c", "openssl/openssl/crypto/x509v3/v3_pcons.c", "openssl/openssl/crypto/x509v3/v3_pku.c", "openssl/openssl/crypto/x509v3/v3_pmaps.c", "openssl/openssl/crypto/x509v3/v3_prn.c", "openssl/openssl/crypto/x509v3/v3_purp.c", "openssl/openssl/crypto/x509v3/v3_skey.c", "openssl/openssl/crypto/x509v3/v3_sxnet.c", "openssl/openssl/crypto/x509v3/v3_utl.c", "openssl/openssl/crypto/x509v3/v3err.c", "openssl/openssl/engines/e_4758cca.c", "openssl/openssl/engines/e_aep.c", "openssl/openssl/engines/e_atalla.c", "openssl/openssl/engines/e_capi.c", "openssl/openssl/engines/e_chil.c", "openssl/openssl/engines/e_cswift.c", "openssl/openssl/engines/e_gmp.c", "openssl/openssl/engines/e_nuron.c", "openssl/openssl/engines/e_sureware.c", "openssl/openssl/engines/e_ubsec.c" ], "sources/": [ ["exclude", "md2/.*$"], ["exclude", "store/.*$"] ], "conditions": [ ["openssl_enable_asm!=1", { "defines": [ "OPENSSL_NO_ASM" ], "sources": [ "openssl/openssl/crypto/aes/aes_cbc.c", "openssl/openssl/crypto/aes/aes_core.c", "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/bn/bn_asm.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/camellia.c", "openssl/openssl/crypto/camellia/cmll_cbc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c", "openssl/openssl/crypto/mem_clr.c", "openssl/openssl/crypto/rc4/rc4_enc.c", "openssl/openssl/crypto/rc4/rc4_skey.c", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }, { "defines": [ "AES_ASM", "BF_ASM", "BNCO_ASM", "BN_ASM", "CPUID_ASM", "DES_ASM", "LIB_BN_ASM", "OPENSSL_BN_ASM", "OPENSSL_CPUID_OBJ", "RIP_ASM", "WHIRLPOOL_ASM", "WP_ASM" ], "conditions": [ ["OS!='win' and OS!='mac' and target_arch=='ia32'", { "sources": [ "asm/x86-elf-gas/aes/aes-586.s", "asm/x86-elf-gas/aes/aesni-x86.s", "asm/x86-elf-gas/bf/bf-686.s", "asm/x86-elf-gas/bn/x86-mont.s", "asm/x86-elf-gas/bn/x86.s", "asm/x86-elf-gas/camellia/cmll-x86.s", "asm/x86-elf-gas/cast/cast-586.s", "asm/x86-elf-gas/des/crypt586.s", "asm/x86-elf-gas/des/des-586.s", "asm/x86-elf-gas/md5/md5-586.s", "asm/x86-elf-gas/rc4/rc4-586.s", "asm/x86-elf-gas/rc5/rc5-586.s", "asm/x86-elf-gas/ripemd/rmd-586.s", "asm/x86-elf-gas/sha/sha1-586.s", "asm/x86-elf-gas/sha/sha256-586.s", "asm/x86-elf-gas/sha/sha512-586.s", "asm/x86-elf-gas/whrlpool/wp-mmx.s", "asm/x86-elf-gas/x86cpuid.s", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }], ["OS!='win' and OS!='mac' and target_arch=='x64'", { "sources": [ "asm/x64-elf-gas/aes/aes-x86_64.s", "asm/x64-elf-gas/aes/aesni-x86_64.s", "asm/x64-elf-gas/aes/aesni-sha1-x86_64.s", "asm/x64-elf-gas/bn/modexp512-x86_64.s", "asm/x64-elf-gas/bn/x86_64-mont.s", "asm/x64-elf-gas/camellia/cmll-x86_64.s", "asm/x64-elf-gas/md5/md5-x86_64.s", "asm/x64-elf-gas/rc4/rc4-x86_64.s", "asm/x64-elf-gas/rc4/rc4-md5-x86_64.s", "asm/x64-elf-gas/sha/sha1-x86_64.s", "asm/x64-elf-gas/sha/sha512-x86_64.s", "asm/x64-elf-gas/whrlpool/wp-x86_64.s", "asm/x64-elf-gas/x86_64cpuid.s", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-gcc.c", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ] }], ["OS=='mac' and target_arch=='ia32'", { "sources": [ "asm/x86-macosx-gas/aes/aes-586.s", "asm/x86-macosx-gas/aes/aesni-x86.s", "asm/x86-macosx-gas/bf/bf-686.s", "asm/x86-macosx-gas/bn/x86-mont.s", "asm/x86-macosx-gas/bn/x86.s", "asm/x86-macosx-gas/camellia/cmll-x86.s", "asm/x86-macosx-gas/cast/cast-586.s", "asm/x86-macosx-gas/des/crypt586.s", "asm/x86-macosx-gas/des/des-586.s", "asm/x86-macosx-gas/md5/md5-586.s", "asm/x86-macosx-gas/rc4/rc4-586.s", "asm/x86-macosx-gas/rc5/rc5-586.s", "asm/x86-macosx-gas/ripemd/rmd-586.s", "asm/x86-macosx-gas/sha/sha1-586.s", "asm/x86-macosx-gas/sha/sha256-586.s", "asm/x86-macosx-gas/sha/sha512-586.s", "asm/x86-macosx-gas/whrlpool/wp-mmx.s", "asm/x86-macosx-gas/x86cpuid.s", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }], ["OS=='mac' and target_arch=='x64'", { "sources": [ "asm/x64-macosx-gas/aes/aes-x86_64.s", "asm/x64-macosx-gas/aes/aesni-x86_64.s", "asm/x64-macosx-gas/aes/aesni-sha1-x86_64.s", "asm/x64-macosx-gas/bn/modexp512-x86_64.s", "asm/x64-macosx-gas/bn/x86_64-mont.s", "asm/x64-macosx-gas/camellia/cmll-x86_64.s", "asm/x64-macosx-gas/md5/md5-x86_64.s", "asm/x64-macosx-gas/rc4/rc4-x86_64.s", "asm/x64-macosx-gas/rc4/rc4-md5-x86_64.s", "asm/x64-macosx-gas/sha/sha1-x86_64.s", "asm/x64-macosx-gas/sha/sha512-x86_64.s", "asm/x64-macosx-gas/whrlpool/wp-x86_64.s", "asm/x64-macosx-gas/x86_64cpuid.s", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-gcc.c", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ] }], ["OS=='win' and target_arch=='ia32'", { "sources": [ "asm/x86-win32-masm/aes/aes-586.asm", "asm/x86-win32-masm/aes/aesni-x86.asm", "asm/x86-win32-masm/bf/bf-686.asm", "asm/x86-win32-masm/bn/x86-mont.asm", "asm/x86-win32-masm/bn/x86.asm", "asm/x86-win32-masm/camellia/cmll-x86.asm", "asm/x86-win32-masm/cast/cast-586.asm", "asm/x86-win32-masm/des/crypt586.asm", "asm/x86-win32-masm/des/des-586.asm", "asm/x86-win32-masm/md5/md5-586.asm", "asm/x86-win32-masm/rc4/rc4-586.asm", "asm/x86-win32-masm/rc5/rc5-586.asm", "asm/x86-win32-masm/ripemd/rmd-586.asm", "asm/x86-win32-masm/sha/sha1-586.asm", "asm/x86-win32-masm/sha/sha256-586.asm", "asm/x86-win32-masm/sha/sha512-586.asm", "asm/x86-win32-masm/whrlpool/wp-mmx.asm", "asm/x86-win32-masm/x86cpuid.asm", "openssl/openssl/crypto/whrlpool/wp_block.c" ], "rules": [ { "rule_name": "Assemble", "extension": "asm", "inputs": [], "outputs": [ "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", ], "action": [ "ml.exe", "/Zi", "/safeseh", "/Fo", "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", "/c", "<(RULE_INPUT_PATH)", ], "process_outputs_as_sources": 0, "message": "Assembling <(RULE_INPUT_PATH) to <(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj.", } ] }], ["OS=='win' and target_arch=='x64'", { "sources": [ "asm/x64-win32-masm/aes/aes-x86_64.asm", "asm/x64-win32-masm/aes/aesni-x86_64.asm", "asm/x64-win32-masm/aes/aesni-sha1-x86_64.asm", "asm/x64-win32-masm/bn/modexp512-x86_64.asm", "asm/x64-win32-masm/bn/x86_64-mont.asm", "asm/x64-win32-masm/camellia/cmll-x86_64.asm", "asm/x64-win32-masm/md5/md5-x86_64.asm", "asm/x64-win32-masm/rc4/rc4-x86_64.asm", "asm/x64-win32-masm/rc4/rc4-md5-x86_64.asm", "asm/x64-win32-masm/sha/sha1-x86_64.asm", "asm/x64-win32-masm/sha/sha512-x86_64.asm", "asm/x64-win32-masm/whrlpool/wp-x86_64.asm", "asm/x64-win32-masm/x86_64cpuid.asm", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-win32-masm.asm", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ], "rules": [ { "rule_name": "Assemble", "extension": "asm", "inputs": [], "outputs": [ "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", ], "action": [ "ml64.exe", "/Zi", "/Fo", "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", "/c", "<(RULE_INPUT_PATH)", ], "process_outputs_as_sources": 0, "message": "Assembling <(RULE_INPUT_PATH) to <(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj.", } ] }] ] }], ["OS=='win'", { "defines": [ "MK1MF_BUILD", "WIN32_LEAN_AND_MEAN" ], "link_settings": { "libraries": [ "-lgdi32.lib", "-luser32.lib", "-lwsock32.lib", ], "conditions": [ ["_type=='shared_library'", { "libraries": [ "-ladvapi32.lib" ] }] ] } }, { "defines": [ "TERMIOS", ], "cflags": [ "-Wno-missing-field-initializers" ], }], ["is_clang==1 or gcc_version>=43", { "cflags": [ "-Wno-old-style-declaration" ], }], ["OS=='solaris'", { "defines": [ "__EXTENSIONS__" ], }], ["target_arch=='arm'", { "sources": [ "openssl/openssl/crypto/armcap.c" ], }], ], }, ] }
40.753758
112
0.572216
{ "variables": { "target_arch%": "x86", "library%": "static_library", "openssl_enable_asm%": 0, "gcc_version%": 0, "is_clang%": 0, }, "targets": [ { "target_name": "libgit2", "type": "static_library", "defines": [ "GIT_THREADS", "GIT_SSH", # against compilation error. "SRC_UTIL_H_", ], "dependencies": [ "zlib", "<(module_root_dir)/vendor/http_parser/http_parser.gyp:http_parser", "libssh2", "openssl" ], "sources": [ "libgit2/src/array.h", "libgit2/src/attr.c", "libgit2/src/attr.h", "libgit2/src/attr_file.c", "libgit2/src/attr_file.h", "libgit2/src/attrcache.c", "libgit2/src/attrcache.h", "libgit2/src/bitvec.h", "libgit2/src/blame.c", "libgit2/src/blame.h", "libgit2/src/blame_git.c", "libgit2/src/blame_git.h", "libgit2/src/blob.c", "libgit2/src/blob.h", "libgit2/src/branch.c", "libgit2/src/branch.h", "libgit2/src/bswap.h", "libgit2/src/buf_text.c", "libgit2/src/buf_text.h", "libgit2/src/buffer.c", "libgit2/src/buffer.h", "libgit2/src/cache.c", "libgit2/src/cache.h", "libgit2/src/cc-compat.h", "libgit2/src/checkout.c", "libgit2/src/checkout.h", "libgit2/src/cherrypick.c", "libgit2/src/clone.c", "libgit2/src/clone.h", "libgit2/src/commit.c", "libgit2/src/commit.h", "libgit2/src/commit_list.c", "libgit2/src/commit_list.h", "libgit2/src/common.h", "libgit2/src/config.c", "libgit2/src/config.h", "libgit2/src/config_cache.c", "libgit2/src/config_file.c", "libgit2/src/config_file.h", "libgit2/src/crlf.c", "libgit2/src/date.c", "libgit2/src/delta-apply.c", "libgit2/src/delta-apply.h", "libgit2/src/delta.c", "libgit2/src/delta.h", "libgit2/src/diff.c", "libgit2/src/diff.h", "libgit2/src/diff_driver.c", "libgit2/src/diff_driver.h", "libgit2/src/diff_file.c", "libgit2/src/diff_file.h", "libgit2/src/diff_patch.c", "libgit2/src/diff_patch.h", "libgit2/src/diff_print.c", "libgit2/src/diff_stats.c", "libgit2/src/diff_tform.c", "libgit2/src/diff_xdiff.c", "libgit2/src/diff_xdiff.h", "libgit2/src/errors.c", "libgit2/src/fetch.c", "libgit2/src/fetch.h", "libgit2/src/fetchhead.c", "libgit2/src/fetchhead.h", "libgit2/src/filebuf.c", "libgit2/src/filebuf.h", "libgit2/src/fileops.c", "libgit2/src/fileops.h", "libgit2/src/filter.c", "libgit2/src/filter.h", "libgit2/src/fnmatch.c", "libgit2/src/fnmatch.h", "libgit2/src/global.c", "libgit2/src/global.h", "libgit2/src/graph.c", "libgit2/src/hash.c", "libgit2/src/hash.h", "libgit2/src/hashsig.c", "libgit2/src/hashsig.h", "libgit2/src/ident.c", "libgit2/src/ignore.c", "libgit2/src/ignore.h", "libgit2/src/index.c", "libgit2/src/index.h", "libgit2/src/indexer.c", "libgit2/src/iterator.c", "libgit2/src/iterator.h", "libgit2/src/khash.h", "libgit2/src/map.h", "libgit2/src/merge.c", "libgit2/src/merge.h", "libgit2/src/merge_file.c", "libgit2/src/merge_file.h", "libgit2/src/message.c", "libgit2/src/message.h", "libgit2/src/mwindow.c", "libgit2/src/mwindow.h", "libgit2/src/netops.c", "libgit2/src/netops.h", "libgit2/src/notes.c", "libgit2/src/notes.h", "libgit2/src/object.c", "libgit2/src/object.h", "libgit2/src/object_api.c", "libgit2/src/odb.c", "libgit2/src/odb.h", "libgit2/src/odb_loose.c", "libgit2/src/odb_mempack.c", "libgit2/src/odb_pack.c", "libgit2/src/offmap.h", "libgit2/src/oid.c", "libgit2/src/oid.h", "libgit2/src/oidmap.h", "libgit2/src/pack-objects.c", "libgit2/src/pack-objects.h", "libgit2/src/pack.c", "libgit2/src/pack.h", "libgit2/src/path.c", "libgit2/src/path.h", "libgit2/src/pathspec.c", "libgit2/src/pathspec.h", "libgit2/src/pool.c", "libgit2/src/pool.h", "libgit2/src/posix.c", "libgit2/src/posix.h", "libgit2/src/pqueue.c", "libgit2/src/pqueue.h", "libgit2/src/push.c", "libgit2/src/push.h", "libgit2/src/refdb.c", "libgit2/src/refdb.h", "libgit2/src/refdb_fs.c", "libgit2/src/refdb_fs.h", "libgit2/src/reflog.c", "libgit2/src/reflog.h", "libgit2/src/refs.c", "libgit2/src/refs.h", "libgit2/src/refspec.c", "libgit2/src/refspec.h", "libgit2/src/remote.c", "libgit2/src/remote.h", "libgit2/src/repo_template.h", "libgit2/src/repository.c", "libgit2/src/repository.h", "libgit2/src/reset.c", "libgit2/src/revert.c", "libgit2/src/revparse.c", "libgit2/src/revwalk.c", "libgit2/src/revwalk.h", "libgit2/src/settings.c", "libgit2/src/sha1_lookup.c", "libgit2/src/sha1_lookup.h", "libgit2/src/signature.c", "libgit2/src/signature.h", "libgit2/src/sortedcache.c", "libgit2/src/sortedcache.h", "libgit2/src/stash.c", "libgit2/src/status.c", "libgit2/src/status.h", "libgit2/src/strmap.c", "libgit2/src/strmap.h", "libgit2/src/strnlen.h", "libgit2/src/submodule.c", "libgit2/src/submodule.h", "libgit2/src/sysdir.c", "libgit2/src/sysdir.h", "libgit2/src/tag.c", "libgit2/src/tag.h", "libgit2/src/thread-utils.c", "libgit2/src/thread-utils.h", "libgit2/src/trace.c", "libgit2/src/trace.h", "libgit2/src/transport.c", "libgit2/src/tree-cache.c", "libgit2/src/tree-cache.h", "libgit2/src/tree.c", "libgit2/src/tree.h", "libgit2/src/tsort.c", "libgit2/src/userdiff.h", "libgit2/src/util.c", "libgit2/src/util.h", "libgit2/src/vector.c", "libgit2/src/vector.h", "libgit2/src/zstream.c", "libgit2/src/zstream.h", "libgit2/src/hash/hash_generic.c", "libgit2/src/hash/hash_generic.h", "libgit2/src/hash/hash_openssl.h", "libgit2/src/transports/cred.c", "libgit2/src/transports/cred_helpers.c", "libgit2/src/transports/git.c", "libgit2/src/transports/http.c", "libgit2/src/transports/local.c", "libgit2/src/transports/smart.c", "libgit2/src/transports/smart.h", "libgit2/src/transports/smart_pkt.c", "libgit2/src/transports/smart_protocol.c", "libgit2/src/transports/ssh.c", "libgit2/src/xdiff/xdiff.h", "libgit2/src/xdiff/xdiffi.c", "libgit2/src/xdiff/xdiffi.h", "libgit2/src/xdiff/xemit.c", "libgit2/src/xdiff/xemit.h", "libgit2/src/xdiff/xhistogram.c", "libgit2/src/xdiff/xinclude.h", "libgit2/src/xdiff/xmacros.h", "libgit2/src/xdiff/xmerge.c", "libgit2/src/xdiff/xpatience.c", "libgit2/src/xdiff/xprepare.c", "libgit2/src/xdiff/xprepare.h", "libgit2/src/xdiff/xtypes.h", "libgit2/src/xdiff/xutils.c", "libgit2/src/xdiff/xutils.h", ], "conditions": [ ["OS!='win'", { "defines": [ "GIT_SSL" ], }], ["OS=='win'", {}, { "sources": [ "libgit2/src/unix/map.c", "libgit2/src/unix/posix.h", "libgit2/src/unix/realpath.c", ] }], ["OS=='linux'", { "cflags": [ "-DGIT_SSH", "-DGIT_SSL", "-w", ], }], ["OS=='win'", { "defines": [ "GIT_WINHTTP", ], "msvs_settings": { "VCLinkerTool": { "AdditionalDependencies": [ "ws2_32.lib", ], }, # Workaround of a strange bug: # TargetMachine + static_library + x64 = nothing. "conditions": [ ["target_arch=='x64'", { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:X64", ], }, }, { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:x86", ], }, }], ], }, "msvs_disabled_warnings": [ # Conversion from 'ssize_t' to 'int32_t', possible loss of data. 4244, # Conversion from 'size_t' to 'int', possible loss of data. 4267, # Different 'volatile' qualifiers. 4090, # 'volatile void *' differs in levels of indirection from 'int'. 4047, # 'InterlockedDecrement' undefined; assuming extern returning int. 4013, ], "sources": [ "libgit2/src/win32/dir.c", "libgit2/src/win32/dir.h", "libgit2/src/win32/error.c", "libgit2/src/win32/error.h", "libgit2/src/win32/findfile.c", "libgit2/src/win32/findfile.h", "libgit2/src/win32/git2.rc", "libgit2/src/win32/map.c", "libgit2/src/win32/mingw-compat.h", "libgit2/src/win32/msvc-compat.h", "libgit2/src/win32/posix.h", "libgit2/src/win32/posix_w32.c", "libgit2/src/win32/precompiled.c", "libgit2/src/win32/precompiled.h", "libgit2/src/win32/pthread.c", "libgit2/src/win32/pthread.h", "libgit2/src/win32/reparse.h", "libgit2/src/win32/utf-conv.c", "libgit2/src/win32/utf-conv.h", "libgit2/src/win32/version.h", "libgit2/src/win32/w32_util.c", "libgit2/src/win32/w32_util.h", "libgit2/src/win32/path_w32.c", "libgit2/src/win32/path_w32.h", "libgit2/src/transports/winhttp.c", "libgit2/deps/regex/regex.c", ], }, { "libraries": [ "-lpthread", ], "sources": [ "libgit2/src/unix/map.c", "libgit2/src/unix/posix.h", "libgit2/src/unix/realpath.c", ], "cflags": [ "-Wno-missing-field-initializers", "-Wno-unused-variable", "-Wno-deprecated-declarations", ], "xcode_settings": { "WARNING_CFLAGS": [ "-Wno-missing-field-initializers", "-Wno-unused-variable", "-Wno-deprecated-declarations", "-Wno-uninitialized", ], }, }, ] ], "include_dirs": [ "libgit2/include", "libgit2/src", "libgit2/deps/regex" ], "direct_dependent_settings": { "include_dirs": [ "libgit2/include", ], }, }, { "target_name": "zlib", "type": "static_library", "sources": [ "libgit2/deps/zlib/adler32.c", "libgit2/deps/zlib/crc32.c", "libgit2/deps/zlib/crc32.h", "libgit2/deps/zlib/deflate.c", "libgit2/deps/zlib/deflate.h", "libgit2/deps/zlib/inffast.c", "libgit2/deps/zlib/inffast.h", "libgit2/deps/zlib/inffixed.h", "libgit2/deps/zlib/inflate.c", "libgit2/deps/zlib/inflate.h", "libgit2/deps/zlib/inftrees.c", "libgit2/deps/zlib/inftrees.h", "libgit2/deps/zlib/trees.c", "libgit2/deps/zlib/trees.h", "libgit2/deps/zlib/zconf.h", "libgit2/deps/zlib/zlib.h", "libgit2/deps/zlib/zutil.c", "libgit2/deps/zlib/zutil.h", ], "defines": [ "NO_VIZ", "STDC", "NO_GZIP", ], "include_dirs": [ "libgit2/include", "libgit2/deps/regex", ], "direct_dependent_settings": { "include_dirs": [ "libgit2/deps/zlib", ], }, }, { "target_name": "libssh2", "type": "static_library", "defines": [ "NETSNMP_ENABLE_IPV6" ], "sources": [ "libssh2/src/agent.c", "libssh2/src/crypt.c", "libssh2/src/keepalive.c", "libssh2/src/libgcrypt.c", "libssh2/src/openssl.c", "libssh2/src/publickey.c", "libssh2/src/sftp.c", "libssh2/src/version.c", "libssh2/src/channel.c", "libssh2/src/global.c", "libssh2/src/kex.c", "libssh2/src/mac.c", "libssh2/src/packet.c", "libssh2/src/scp.c", "libssh2/src/transport.c", "libssh2/src/comp.c", "libssh2/src/hostkey.c", "libssh2/src/knownhost.c", "libssh2/src/misc.c", "libssh2/src/pem.c", "libssh2/src/session.c", "libssh2/src/userauth.c", ], "include_dirs": [ ".", "libssh2/include", ], "dependencies": [ "openssl" ], "direct_dependent_settings": { "include_dirs": [ "libssh2/include" ] }, "conditions": [ ["OS=='win'", { "include_dirs": [ "libssh2/src", "libssh2/win32", "libssh2/include" ], "direct_dependent_settings": { "include_dirs": [ "libssh2/src", "libssh2/win32", "libssh2/include" ] } }], ] }, { "target_name": "openssl", "type": "static_library", "defines": [ #No clue what these are for. "L_ENDIAN", "PURIFY", "_REENTRANT", "NO_WINDOWS_BRAINDEATH", ], "include_dirs": [ ".", "openssl/openssl", "openssl/openssl/crypto", "openssl/openssl/crypto/asn1", "openssl/openssl/crypto/evp", "openssl/openssl/crypto/md2", "openssl/openssl/crypto/modes", "openssl/openssl/crypto/store", "openssl/openssl/include", ], "direct_dependent_settings": { "include_dirs": [ "openssl/openssl/include", "openssl/openssl/include/openssl", ] }, "sources": [ "openssl/openssl/ssl/bio_ssl.c", "openssl/openssl/ssl/d1_both.c", "openssl/openssl/ssl/d1_clnt.c", "openssl/openssl/ssl/d1_enc.c", "openssl/openssl/ssl/d1_lib.c", "openssl/openssl/ssl/d1_meth.c", "openssl/openssl/ssl/d1_pkt.c", "openssl/openssl/ssl/d1_srtp.c", "openssl/openssl/ssl/d1_srvr.c", "openssl/openssl/ssl/kssl.c", "openssl/openssl/ssl/s23_clnt.c", "openssl/openssl/ssl/s23_lib.c", "openssl/openssl/ssl/s23_meth.c", "openssl/openssl/ssl/s23_pkt.c", "openssl/openssl/ssl/s23_srvr.c", "openssl/openssl/ssl/s2_clnt.c", "openssl/openssl/ssl/s2_enc.c", "openssl/openssl/ssl/s2_lib.c", "openssl/openssl/ssl/s2_meth.c", "openssl/openssl/ssl/s2_pkt.c", "openssl/openssl/ssl/s2_srvr.c", "openssl/openssl/ssl/s3_both.c", "openssl/openssl/ssl/s3_clnt.c", "openssl/openssl/ssl/s3_enc.c", "openssl/openssl/ssl/s3_lib.c", "openssl/openssl/ssl/s3_meth.c", "openssl/openssl/ssl/s3_pkt.c", "openssl/openssl/ssl/s3_srvr.c", "openssl/openssl/ssl/s3_cbc.c", "openssl/openssl/ssl/ssl_algs.c", "openssl/openssl/ssl/ssl_asn1.c", "openssl/openssl/ssl/ssl_cert.c", "openssl/openssl/ssl/ssl_ciph.c", "openssl/openssl/ssl/ssl_err.c", "openssl/openssl/ssl/ssl_err2.c", "openssl/openssl/ssl/ssl_lib.c", "openssl/openssl/ssl/ssl_rsa.c", "openssl/openssl/ssl/ssl_sess.c", "openssl/openssl/ssl/ssl_stat.c", "openssl/openssl/ssl/ssl_txt.c", "openssl/openssl/ssl/t1_clnt.c", "openssl/openssl/ssl/t1_enc.c", "openssl/openssl/ssl/t1_lib.c", "openssl/openssl/ssl/t1_meth.c", "openssl/openssl/ssl/t1_reneg.c", "openssl/openssl/ssl/t1_srvr.c", "openssl/openssl/ssl/tls_srp.c", "openssl/openssl/crypto/aes/aes_cfb.c", "openssl/openssl/crypto/aes/aes_ctr.c", "openssl/openssl/crypto/aes/aes_ecb.c", "openssl/openssl/crypto/aes/aes_ige.c", "openssl/openssl/crypto/aes/aes_misc.c", "openssl/openssl/crypto/aes/aes_ofb.c", "openssl/openssl/crypto/aes/aes_wrap.c", "openssl/openssl/crypto/asn1/a_bitstr.c", "openssl/openssl/crypto/asn1/a_bool.c", "openssl/openssl/crypto/asn1/a_bytes.c", "openssl/openssl/crypto/asn1/a_d2i_fp.c", "openssl/openssl/crypto/asn1/a_digest.c", "openssl/openssl/crypto/asn1/a_dup.c", "openssl/openssl/crypto/asn1/a_enum.c", "openssl/openssl/crypto/asn1/a_gentm.c", "openssl/openssl/crypto/asn1/a_i2d_fp.c", "openssl/openssl/crypto/asn1/a_int.c", "openssl/openssl/crypto/asn1/a_mbstr.c", "openssl/openssl/crypto/asn1/a_object.c", "openssl/openssl/crypto/asn1/a_octet.c", "openssl/openssl/crypto/asn1/a_print.c", "openssl/openssl/crypto/asn1/a_set.c", "openssl/openssl/crypto/asn1/a_sign.c", "openssl/openssl/crypto/asn1/a_strex.c", "openssl/openssl/crypto/asn1/a_strnid.c", "openssl/openssl/crypto/asn1/a_time.c", "openssl/openssl/crypto/asn1/a_type.c", "openssl/openssl/crypto/asn1/a_utctm.c", "openssl/openssl/crypto/asn1/a_utf8.c", "openssl/openssl/crypto/asn1/a_verify.c", "openssl/openssl/crypto/asn1/ameth_lib.c", "openssl/openssl/crypto/asn1/asn1_err.c", "openssl/openssl/crypto/asn1/asn1_gen.c", "openssl/openssl/crypto/asn1/asn1_lib.c", "openssl/openssl/crypto/asn1/asn1_par.c", "openssl/openssl/crypto/asn1/asn_mime.c", "openssl/openssl/crypto/asn1/asn_moid.c", "openssl/openssl/crypto/asn1/asn_pack.c", "openssl/openssl/crypto/asn1/bio_asn1.c", "openssl/openssl/crypto/asn1/bio_ndef.c", "openssl/openssl/crypto/asn1/d2i_pr.c", "openssl/openssl/crypto/asn1/d2i_pu.c", "openssl/openssl/crypto/asn1/evp_asn1.c", "openssl/openssl/crypto/asn1/f_enum.c", "openssl/openssl/crypto/asn1/f_int.c", "openssl/openssl/crypto/asn1/f_string.c", "openssl/openssl/crypto/asn1/i2d_pr.c", "openssl/openssl/crypto/asn1/i2d_pu.c", "openssl/openssl/crypto/asn1/n_pkey.c", "openssl/openssl/crypto/asn1/nsseq.c", "openssl/openssl/crypto/asn1/p5_pbe.c", "openssl/openssl/crypto/asn1/p5_pbev2.c", "openssl/openssl/crypto/asn1/p8_pkey.c", "openssl/openssl/crypto/asn1/t_bitst.c", "openssl/openssl/crypto/asn1/t_crl.c", "openssl/openssl/crypto/asn1/t_pkey.c", "openssl/openssl/crypto/asn1/t_req.c", "openssl/openssl/crypto/asn1/t_spki.c", "openssl/openssl/crypto/asn1/t_x509.c", "openssl/openssl/crypto/asn1/t_x509a.c", "openssl/openssl/crypto/asn1/tasn_dec.c", "openssl/openssl/crypto/asn1/tasn_enc.c", "openssl/openssl/crypto/asn1/tasn_fre.c", "openssl/openssl/crypto/asn1/tasn_new.c", "openssl/openssl/crypto/asn1/tasn_prn.c", "openssl/openssl/crypto/asn1/tasn_typ.c", "openssl/openssl/crypto/asn1/tasn_utl.c", "openssl/openssl/crypto/asn1/x_algor.c", "openssl/openssl/crypto/asn1/x_attrib.c", "openssl/openssl/crypto/asn1/x_bignum.c", "openssl/openssl/crypto/asn1/x_crl.c", "openssl/openssl/crypto/asn1/x_exten.c", "openssl/openssl/crypto/asn1/x_info.c", "openssl/openssl/crypto/asn1/x_long.c", "openssl/openssl/crypto/asn1/x_name.c", "openssl/openssl/crypto/asn1/x_nx509.c", "openssl/openssl/crypto/asn1/x_pkey.c", "openssl/openssl/crypto/asn1/x_pubkey.c", "openssl/openssl/crypto/asn1/x_req.c", "openssl/openssl/crypto/asn1/x_sig.c", "openssl/openssl/crypto/asn1/x_spki.c", "openssl/openssl/crypto/asn1/x_val.c", "openssl/openssl/crypto/asn1/x_x509.c", "openssl/openssl/crypto/asn1/x_x509a.c", "openssl/openssl/crypto/bf/bf_cfb64.c", "openssl/openssl/crypto/bf/bf_ecb.c", "openssl/openssl/crypto/bf/bf_ofb64.c", "openssl/openssl/crypto/bf/bf_skey.c", "openssl/openssl/crypto/bio/b_dump.c", "openssl/openssl/crypto/bio/b_print.c", "openssl/openssl/crypto/bio/b_sock.c", "openssl/openssl/crypto/bio/bf_buff.c", "openssl/openssl/crypto/bio/bf_nbio.c", "openssl/openssl/crypto/bio/bf_null.c", "openssl/openssl/crypto/bio/bio_cb.c", "openssl/openssl/crypto/bio/bio_err.c", "openssl/openssl/crypto/bio/bio_lib.c", "openssl/openssl/crypto/bio/bss_acpt.c", "openssl/openssl/crypto/bio/bss_bio.c", "openssl/openssl/crypto/bio/bss_conn.c", "openssl/openssl/crypto/bio/bss_dgram.c", "openssl/openssl/crypto/bio/bss_fd.c", "openssl/openssl/crypto/bio/bss_file.c", "openssl/openssl/crypto/bio/bss_log.c", "openssl/openssl/crypto/bio/bss_mem.c", "openssl/openssl/crypto/bio/bss_null.c", "openssl/openssl/crypto/bio/bss_sock.c", "openssl/openssl/crypto/bn/bn_add.c", "openssl/openssl/crypto/bn/bn_blind.c", "openssl/openssl/crypto/bn/bn_const.c", "openssl/openssl/crypto/bn/bn_ctx.c", "openssl/openssl/crypto/bn/bn_depr.c", "openssl/openssl/crypto/bn/bn_div.c", "openssl/openssl/crypto/bn/bn_err.c", "openssl/openssl/crypto/bn/bn_exp.c", "openssl/openssl/crypto/bn/bn_exp2.c", "openssl/openssl/crypto/bn/bn_gcd.c", "openssl/openssl/crypto/bn/bn_gf2m.c", "openssl/openssl/crypto/bn/bn_kron.c", "openssl/openssl/crypto/bn/bn_lib.c", "openssl/openssl/crypto/bn/bn_mod.c", "openssl/openssl/crypto/bn/bn_mont.c", "openssl/openssl/crypto/bn/bn_mpi.c", "openssl/openssl/crypto/bn/bn_mul.c", "openssl/openssl/crypto/bn/bn_nist.c", "openssl/openssl/crypto/bn/bn_prime.c", "openssl/openssl/crypto/bn/bn_print.c", "openssl/openssl/crypto/bn/bn_rand.c", "openssl/openssl/crypto/bn/bn_recp.c", "openssl/openssl/crypto/bn/bn_shift.c", "openssl/openssl/crypto/bn/bn_sqr.c", "openssl/openssl/crypto/bn/bn_sqrt.c", "openssl/openssl/crypto/bn/bn_word.c", "openssl/openssl/crypto/bn/bn_x931p.c", "openssl/openssl/crypto/buffer/buf_err.c", "openssl/openssl/crypto/buffer/buf_str.c", "openssl/openssl/crypto/buffer/buffer.c", "openssl/openssl/crypto/camellia/cmll_cfb.c", "openssl/openssl/crypto/camellia/cmll_ctr.c", "openssl/openssl/crypto/camellia/cmll_ecb.c", "openssl/openssl/crypto/camellia/cmll_ofb.c", "openssl/openssl/crypto/camellia/cmll_utl.c", "openssl/openssl/crypto/cast/c_cfb64.c", "openssl/openssl/crypto/cast/c_ecb.c", "openssl/openssl/crypto/cast/c_ofb64.c", "openssl/openssl/crypto/cast/c_skey.c", "openssl/openssl/crypto/cmac/cm_ameth.c", "openssl/openssl/crypto/cmac/cm_pmeth.c", "openssl/openssl/crypto/cmac/cmac.c", "openssl/openssl/crypto/cms/cms_asn1.c", "openssl/openssl/crypto/cms/cms_att.c", "openssl/openssl/crypto/cms/cms_cd.c", "openssl/openssl/crypto/cms/cms_dd.c", "openssl/openssl/crypto/cms/cms_enc.c", "openssl/openssl/crypto/cms/cms_env.c", "openssl/openssl/crypto/cms/cms_err.c", "openssl/openssl/crypto/cms/cms_ess.c", "openssl/openssl/crypto/cms/cms_io.c", "openssl/openssl/crypto/cms/cms_lib.c", "openssl/openssl/crypto/cms/cms_pwri.c", "openssl/openssl/crypto/cms/cms_sd.c", "openssl/openssl/crypto/cms/cms_smime.c", "openssl/openssl/crypto/comp/c_rle.c", "openssl/openssl/crypto/comp/c_zlib.c", "openssl/openssl/crypto/comp/comp_err.c", "openssl/openssl/crypto/comp/comp_lib.c", "openssl/openssl/crypto/conf/conf_api.c", "openssl/openssl/crypto/conf/conf_def.c", "openssl/openssl/crypto/conf/conf_err.c", "openssl/openssl/crypto/conf/conf_lib.c", "openssl/openssl/crypto/conf/conf_mall.c", "openssl/openssl/crypto/conf/conf_mod.c", "openssl/openssl/crypto/conf/conf_sap.c", "openssl/openssl/crypto/cpt_err.c", "openssl/openssl/crypto/cryptlib.c", "openssl/openssl/crypto/cversion.c", "openssl/openssl/crypto/des/cbc_cksm.c", "openssl/openssl/crypto/des/cbc_enc.c", "openssl/openssl/crypto/des/cfb64ede.c", "openssl/openssl/crypto/des/cfb64enc.c", "openssl/openssl/crypto/des/cfb_enc.c", "openssl/openssl/crypto/des/des_old.c", "openssl/openssl/crypto/des/des_old2.c", "openssl/openssl/crypto/des/ecb3_enc.c", "openssl/openssl/crypto/des/ecb_enc.c", "openssl/openssl/crypto/des/ede_cbcm_enc.c", "openssl/openssl/crypto/des/enc_read.c", "openssl/openssl/crypto/des/enc_writ.c", "openssl/openssl/crypto/des/fcrypt.c", "openssl/openssl/crypto/des/ofb64ede.c", "openssl/openssl/crypto/des/ofb64enc.c", "openssl/openssl/crypto/des/ofb_enc.c", "openssl/openssl/crypto/des/pcbc_enc.c", "openssl/openssl/crypto/des/qud_cksm.c", "openssl/openssl/crypto/des/rand_key.c", "openssl/openssl/crypto/des/read2pwd.c", "openssl/openssl/crypto/des/rpc_enc.c", "openssl/openssl/crypto/des/set_key.c", "openssl/openssl/crypto/des/str2key.c", "openssl/openssl/crypto/des/xcbc_enc.c", "openssl/openssl/crypto/dh/dh_ameth.c", "openssl/openssl/crypto/dh/dh_asn1.c", "openssl/openssl/crypto/dh/dh_check.c", "openssl/openssl/crypto/dh/dh_depr.c", "openssl/openssl/crypto/dh/dh_err.c", "openssl/openssl/crypto/dh/dh_gen.c", "openssl/openssl/crypto/dh/dh_key.c", "openssl/openssl/crypto/dh/dh_lib.c", "openssl/openssl/crypto/dh/dh_pmeth.c", "openssl/openssl/crypto/dh/dh_prn.c", "openssl/openssl/crypto/dsa/dsa_ameth.c", "openssl/openssl/crypto/dsa/dsa_asn1.c", "openssl/openssl/crypto/dsa/dsa_depr.c", "openssl/openssl/crypto/dsa/dsa_err.c", "openssl/openssl/crypto/dsa/dsa_gen.c", "openssl/openssl/crypto/dsa/dsa_key.c", "openssl/openssl/crypto/dsa/dsa_lib.c", "openssl/openssl/crypto/dsa/dsa_ossl.c", "openssl/openssl/crypto/dsa/dsa_pmeth.c", "openssl/openssl/crypto/dsa/dsa_prn.c", "openssl/openssl/crypto/dsa/dsa_sign.c", "openssl/openssl/crypto/dsa/dsa_vrf.c", "openssl/openssl/crypto/dso/dso_beos.c", "openssl/openssl/crypto/dso/dso_dl.c", "openssl/openssl/crypto/dso/dso_dlfcn.c", "openssl/openssl/crypto/dso/dso_err.c", "openssl/openssl/crypto/dso/dso_lib.c", "openssl/openssl/crypto/dso/dso_null.c", "openssl/openssl/crypto/dso/dso_openssl.c", "openssl/openssl/crypto/dso/dso_vms.c", "openssl/openssl/crypto/dso/dso_win32.c", "openssl/openssl/crypto/ebcdic.c", "openssl/openssl/crypto/ec/ec2_mult.c", "openssl/openssl/crypto/ec/ec2_oct.c", "openssl/openssl/crypto/ec/ec2_smpl.c", "openssl/openssl/crypto/ec/ec_ameth.c", "openssl/openssl/crypto/ec/ec_asn1.c", "openssl/openssl/crypto/ec/ec_check.c", "openssl/openssl/crypto/ec/ec_curve.c", "openssl/openssl/crypto/ec/ec_cvt.c", "openssl/openssl/crypto/ec/ec_err.c", "openssl/openssl/crypto/ec/ec_key.c", "openssl/openssl/crypto/ec/ec_lib.c", "openssl/openssl/crypto/ec/ec_mult.c", "openssl/openssl/crypto/ec/ec_oct.c", "openssl/openssl/crypto/ec/ec_pmeth.c", "openssl/openssl/crypto/ec/ec_print.c", "openssl/openssl/crypto/ec/eck_prn.c", "openssl/openssl/crypto/ec/ecp_mont.c", "openssl/openssl/crypto/ec/ecp_nist.c", "openssl/openssl/crypto/ec/ecp_nistp224.c", "openssl/openssl/crypto/ec/ecp_nistp256.c", "openssl/openssl/crypto/ec/ecp_nistp521.c", "openssl/openssl/crypto/ec/ecp_nistputil.c", "openssl/openssl/crypto/ec/ecp_oct.c", "openssl/openssl/crypto/ec/ecp_smpl.c", "openssl/openssl/crypto/ecdh/ech_err.c", "openssl/openssl/crypto/ecdh/ech_key.c", "openssl/openssl/crypto/ecdh/ech_lib.c", "openssl/openssl/crypto/ecdh/ech_ossl.c", "openssl/openssl/crypto/ecdsa/ecs_asn1.c", "openssl/openssl/crypto/ecdsa/ecs_err.c", "openssl/openssl/crypto/ecdsa/ecs_lib.c", "openssl/openssl/crypto/ecdsa/ecs_ossl.c", "openssl/openssl/crypto/ecdsa/ecs_sign.c", "openssl/openssl/crypto/ecdsa/ecs_vrf.c", "openssl/openssl/crypto/engine/eng_all.c", "openssl/openssl/crypto/engine/eng_cnf.c", "openssl/openssl/crypto/engine/eng_cryptodev.c", "openssl/openssl/crypto/engine/eng_ctrl.c", "openssl/openssl/crypto/engine/eng_dyn.c", "openssl/openssl/crypto/engine/eng_err.c", "openssl/openssl/crypto/engine/eng_fat.c", "openssl/openssl/crypto/engine/eng_init.c", "openssl/openssl/crypto/engine/eng_lib.c", "openssl/openssl/crypto/engine/eng_list.c", "openssl/openssl/crypto/engine/eng_openssl.c", "openssl/openssl/crypto/engine/eng_pkey.c", "openssl/openssl/crypto/engine/eng_rdrand.c", "openssl/openssl/crypto/engine/eng_rsax.c", "openssl/openssl/crypto/engine/eng_table.c", "openssl/openssl/crypto/engine/tb_asnmth.c", "openssl/openssl/crypto/engine/tb_cipher.c", "openssl/openssl/crypto/engine/tb_dh.c", "openssl/openssl/crypto/engine/tb_digest.c", "openssl/openssl/crypto/engine/tb_dsa.c", "openssl/openssl/crypto/engine/tb_ecdh.c", "openssl/openssl/crypto/engine/tb_ecdsa.c", "openssl/openssl/crypto/engine/tb_pkmeth.c", "openssl/openssl/crypto/engine/tb_rand.c", "openssl/openssl/crypto/engine/tb_rsa.c", "openssl/openssl/crypto/engine/tb_store.c", "openssl/openssl/crypto/err/err.c", "openssl/openssl/crypto/err/err_all.c", "openssl/openssl/crypto/err/err_prn.c", "openssl/openssl/crypto/evp/bio_b64.c", "openssl/openssl/crypto/evp/bio_enc.c", "openssl/openssl/crypto/evp/bio_md.c", "openssl/openssl/crypto/evp/bio_ok.c", "openssl/openssl/crypto/evp/c_all.c", "openssl/openssl/crypto/evp/c_allc.c", "openssl/openssl/crypto/evp/c_alld.c", "openssl/openssl/crypto/evp/digest.c", "openssl/openssl/crypto/evp/e_aes.c", "openssl/openssl/crypto/evp/e_aes_cbc_hmac_sha1.c", "openssl/openssl/crypto/evp/e_bf.c", "openssl/openssl/crypto/evp/e_camellia.c", "openssl/openssl/crypto/evp/e_cast.c", "openssl/openssl/crypto/evp/e_des.c", "openssl/openssl/crypto/evp/e_des3.c", "openssl/openssl/crypto/evp/e_idea.c", "openssl/openssl/crypto/evp/e_null.c", "openssl/openssl/crypto/evp/e_old.c", "openssl/openssl/crypto/evp/e_rc2.c", "openssl/openssl/crypto/evp/e_rc4.c", "openssl/openssl/crypto/evp/e_rc4_hmac_md5.c", "openssl/openssl/crypto/evp/e_rc5.c", "openssl/openssl/crypto/evp/e_seed.c", "openssl/openssl/crypto/evp/e_xcbc_d.c", "openssl/openssl/crypto/evp/encode.c", "openssl/openssl/crypto/evp/evp_acnf.c", "openssl/openssl/crypto/evp/evp_cnf.c", "openssl/openssl/crypto/evp/evp_enc.c", "openssl/openssl/crypto/evp/evp_err.c", "openssl/openssl/crypto/evp/evp_fips.c", "openssl/openssl/crypto/evp/evp_key.c", "openssl/openssl/crypto/evp/evp_lib.c", "openssl/openssl/crypto/evp/evp_pbe.c", "openssl/openssl/crypto/evp/evp_pkey.c", "openssl/openssl/crypto/evp/m_dss.c", "openssl/openssl/crypto/evp/m_dss1.c", "openssl/openssl/crypto/evp/m_ecdsa.c", "openssl/openssl/crypto/evp/m_md2.c", "openssl/openssl/crypto/evp/m_md4.c", "openssl/openssl/crypto/evp/m_md5.c", "openssl/openssl/crypto/evp/m_mdc2.c", "openssl/openssl/crypto/evp/m_null.c", "openssl/openssl/crypto/evp/m_ripemd.c", "openssl/openssl/crypto/evp/m_sha.c", "openssl/openssl/crypto/evp/m_sha1.c", "openssl/openssl/crypto/evp/m_sigver.c", "openssl/openssl/crypto/evp/m_wp.c", "openssl/openssl/crypto/evp/names.c", "openssl/openssl/crypto/evp/p5_crpt.c", "openssl/openssl/crypto/evp/p5_crpt2.c", "openssl/openssl/crypto/evp/p_dec.c", "openssl/openssl/crypto/evp/p_enc.c", "openssl/openssl/crypto/evp/p_lib.c", "openssl/openssl/crypto/evp/p_open.c", "openssl/openssl/crypto/evp/p_seal.c", "openssl/openssl/crypto/evp/p_sign.c", "openssl/openssl/crypto/evp/p_verify.c", "openssl/openssl/crypto/evp/pmeth_fn.c", "openssl/openssl/crypto/evp/pmeth_gn.c", "openssl/openssl/crypto/evp/pmeth_lib.c", "openssl/openssl/crypto/ex_data.c", "openssl/openssl/crypto/fips_ers.c", "openssl/openssl/crypto/hmac/hm_ameth.c", "openssl/openssl/crypto/hmac/hm_pmeth.c", "openssl/openssl/crypto/hmac/hmac.c", "openssl/openssl/crypto/idea/i_cbc.c", "openssl/openssl/crypto/idea/i_cfb64.c", "openssl/openssl/crypto/idea/i_ecb.c", "openssl/openssl/crypto/idea/i_ofb64.c", "openssl/openssl/crypto/idea/i_skey.c", "openssl/openssl/crypto/krb5/krb5_asn.c", "openssl/openssl/crypto/lhash/lh_stats.c", "openssl/openssl/crypto/lhash/lhash.c", "openssl/openssl/crypto/md2/md2_dgst.c", "openssl/openssl/crypto/md2/md2_one.c", "openssl/openssl/crypto/md4/md4_dgst.c", "openssl/openssl/crypto/md4/md4_one.c", "openssl/openssl/crypto/md5/md5_dgst.c", "openssl/openssl/crypto/md5/md5_one.c", "openssl/openssl/crypto/mdc2/mdc2_one.c", "openssl/openssl/crypto/mdc2/mdc2dgst.c", "openssl/openssl/crypto/mem.c", "openssl/openssl/crypto/mem_dbg.c", "openssl/openssl/crypto/modes/cbc128.c", "openssl/openssl/crypto/modes/ccm128.c", "openssl/openssl/crypto/modes/cfb128.c", "openssl/openssl/crypto/modes/ctr128.c", "openssl/openssl/crypto/modes/cts128.c", "openssl/openssl/crypto/modes/gcm128.c", "openssl/openssl/crypto/modes/ofb128.c", "openssl/openssl/crypto/modes/xts128.c", "openssl/openssl/crypto/o_dir.c", "openssl/openssl/crypto/o_fips.c", "openssl/openssl/crypto/o_init.c", "openssl/openssl/crypto/o_str.c", "openssl/openssl/crypto/o_time.c", "openssl/openssl/crypto/objects/o_names.c", "openssl/openssl/crypto/objects/obj_dat.c", "openssl/openssl/crypto/objects/obj_err.c", "openssl/openssl/crypto/objects/obj_lib.c", "openssl/openssl/crypto/objects/obj_xref.c", "openssl/openssl/crypto/ocsp/ocsp_asn.c", "openssl/openssl/crypto/ocsp/ocsp_cl.c", "openssl/openssl/crypto/ocsp/ocsp_err.c", "openssl/openssl/crypto/ocsp/ocsp_ext.c", "openssl/openssl/crypto/ocsp/ocsp_ht.c", "openssl/openssl/crypto/ocsp/ocsp_lib.c", "openssl/openssl/crypto/ocsp/ocsp_prn.c", "openssl/openssl/crypto/ocsp/ocsp_srv.c", "openssl/openssl/crypto/ocsp/ocsp_vfy.c", "openssl/openssl/crypto/pem/pem_all.c", "openssl/openssl/crypto/pem/pem_err.c", "openssl/openssl/crypto/pem/pem_info.c", "openssl/openssl/crypto/pem/pem_lib.c", "openssl/openssl/crypto/pem/pem_oth.c", "openssl/openssl/crypto/pem/pem_pk8.c", "openssl/openssl/crypto/pem/pem_pkey.c", "openssl/openssl/crypto/pem/pem_seal.c", "openssl/openssl/crypto/pem/pem_sign.c", "openssl/openssl/crypto/pem/pem_x509.c", "openssl/openssl/crypto/pem/pem_xaux.c", "openssl/openssl/crypto/pem/pvkfmt.c", "openssl/openssl/crypto/pkcs12/p12_add.c", "openssl/openssl/crypto/pkcs12/p12_asn.c", "openssl/openssl/crypto/pkcs12/p12_attr.c", "openssl/openssl/crypto/pkcs12/p12_crpt.c", "openssl/openssl/crypto/pkcs12/p12_crt.c", "openssl/openssl/crypto/pkcs12/p12_decr.c", "openssl/openssl/crypto/pkcs12/p12_init.c", "openssl/openssl/crypto/pkcs12/p12_key.c", "openssl/openssl/crypto/pkcs12/p12_kiss.c", "openssl/openssl/crypto/pkcs12/p12_mutl.c", "openssl/openssl/crypto/pkcs12/p12_npas.c", "openssl/openssl/crypto/pkcs12/p12_p8d.c", "openssl/openssl/crypto/pkcs12/p12_p8e.c", "openssl/openssl/crypto/pkcs12/p12_utl.c", "openssl/openssl/crypto/pkcs12/pk12err.c", "openssl/openssl/crypto/pkcs7/bio_pk7.c", "openssl/openssl/crypto/pkcs7/pk7_asn1.c", "openssl/openssl/crypto/pkcs7/pk7_attr.c", "openssl/openssl/crypto/pkcs7/pk7_doit.c", "openssl/openssl/crypto/pkcs7/pk7_lib.c", "openssl/openssl/crypto/pkcs7/pk7_mime.c", "openssl/openssl/crypto/pkcs7/pk7_smime.c", "openssl/openssl/crypto/pkcs7/pkcs7err.c", "openssl/openssl/crypto/pqueue/pqueue.c", "openssl/openssl/crypto/rand/md_rand.c", "openssl/openssl/crypto/rand/rand_egd.c", "openssl/openssl/crypto/rand/rand_err.c", "openssl/openssl/crypto/rand/rand_lib.c", "openssl/openssl/crypto/rand/rand_nw.c", "openssl/openssl/crypto/rand/rand_os2.c", "openssl/openssl/crypto/rand/rand_unix.c", "openssl/openssl/crypto/rand/rand_win.c", "openssl/openssl/crypto/rand/randfile.c", "openssl/openssl/crypto/rc2/rc2_cbc.c", "openssl/openssl/crypto/rc2/rc2_ecb.c", "openssl/openssl/crypto/rc2/rc2_skey.c", "openssl/openssl/crypto/rc2/rc2cfb64.c", "openssl/openssl/crypto/rc2/rc2ofb64.c", "openssl/openssl/crypto/rc4/rc4_utl.c", "openssl/openssl/crypto/ripemd/rmd_dgst.c", "openssl/openssl/crypto/ripemd/rmd_one.c", "openssl/openssl/crypto/rsa/rsa_ameth.c", "openssl/openssl/crypto/rsa/rsa_asn1.c", "openssl/openssl/crypto/rsa/rsa_chk.c", "openssl/openssl/crypto/rsa/rsa_crpt.c", "openssl/openssl/crypto/rsa/rsa_depr.c", "openssl/openssl/crypto/rsa/rsa_eay.c", "openssl/openssl/crypto/rsa/rsa_err.c", "openssl/openssl/crypto/rsa/rsa_gen.c", "openssl/openssl/crypto/rsa/rsa_lib.c", "openssl/openssl/crypto/rsa/rsa_none.c", "openssl/openssl/crypto/rsa/rsa_null.c", "openssl/openssl/crypto/rsa/rsa_oaep.c", "openssl/openssl/crypto/rsa/rsa_pk1.c", "openssl/openssl/crypto/rsa/rsa_pmeth.c", "openssl/openssl/crypto/rsa/rsa_prn.c", "openssl/openssl/crypto/rsa/rsa_pss.c", "openssl/openssl/crypto/rsa/rsa_saos.c", "openssl/openssl/crypto/rsa/rsa_sign.c", "openssl/openssl/crypto/rsa/rsa_ssl.c", "openssl/openssl/crypto/rsa/rsa_x931.c", "openssl/openssl/crypto/seed/seed.c", "openssl/openssl/crypto/seed/seed_cbc.c", "openssl/openssl/crypto/seed/seed_cfb.c", "openssl/openssl/crypto/seed/seed_ecb.c", "openssl/openssl/crypto/seed/seed_ofb.c", "openssl/openssl/crypto/sha/sha1_one.c", "openssl/openssl/crypto/sha/sha1dgst.c", "openssl/openssl/crypto/sha/sha256.c", "openssl/openssl/crypto/sha/sha512.c", "openssl/openssl/crypto/sha/sha_dgst.c", "openssl/openssl/crypto/sha/sha_one.c", "openssl/openssl/crypto/srp/srp_lib.c", "openssl/openssl/crypto/srp/srp_vfy.c", "openssl/openssl/crypto/stack/stack.c", "openssl/openssl/crypto/store/str_err.c", "openssl/openssl/crypto/store/str_lib.c", "openssl/openssl/crypto/store/str_mem.c", "openssl/openssl/crypto/store/str_meth.c", "openssl/openssl/crypto/ts/ts_asn1.c", "openssl/openssl/crypto/ts/ts_conf.c", "openssl/openssl/crypto/ts/ts_err.c", "openssl/openssl/crypto/ts/ts_lib.c", "openssl/openssl/crypto/ts/ts_req_print.c", "openssl/openssl/crypto/ts/ts_req_utils.c", "openssl/openssl/crypto/ts/ts_rsp_print.c", "openssl/openssl/crypto/ts/ts_rsp_sign.c", "openssl/openssl/crypto/ts/ts_rsp_utils.c", "openssl/openssl/crypto/ts/ts_rsp_verify.c", "openssl/openssl/crypto/ts/ts_verify_ctx.c", "openssl/openssl/crypto/txt_db/txt_db.c", "openssl/openssl/crypto/ui/ui_compat.c", "openssl/openssl/crypto/ui/ui_err.c", "openssl/openssl/crypto/ui/ui_lib.c", "openssl/openssl/crypto/ui/ui_openssl.c", "openssl/openssl/crypto/ui/ui_util.c", "openssl/openssl/crypto/uid.c", "openssl/openssl/crypto/whrlpool/wp_dgst.c", "openssl/openssl/crypto/x509/by_dir.c", "openssl/openssl/crypto/x509/by_file.c", "openssl/openssl/crypto/x509/x509_att.c", "openssl/openssl/crypto/x509/x509_cmp.c", "openssl/openssl/crypto/x509/x509_d2.c", "openssl/openssl/crypto/x509/x509_def.c", "openssl/openssl/crypto/x509/x509_err.c", "openssl/openssl/crypto/x509/x509_ext.c", "openssl/openssl/crypto/x509/x509_lu.c", "openssl/openssl/crypto/x509/x509_obj.c", "openssl/openssl/crypto/x509/x509_r2x.c", "openssl/openssl/crypto/x509/x509_req.c", "openssl/openssl/crypto/x509/x509_set.c", "openssl/openssl/crypto/x509/x509_trs.c", "openssl/openssl/crypto/x509/x509_txt.c", "openssl/openssl/crypto/x509/x509_v3.c", "openssl/openssl/crypto/x509/x509_vfy.c", "openssl/openssl/crypto/x509/x509_vpm.c", "openssl/openssl/crypto/x509/x509cset.c", "openssl/openssl/crypto/x509/x509name.c", "openssl/openssl/crypto/x509/x509rset.c", "openssl/openssl/crypto/x509/x509spki.c", "openssl/openssl/crypto/x509/x509type.c", "openssl/openssl/crypto/x509/x_all.c", "openssl/openssl/crypto/x509v3/pcy_cache.c", "openssl/openssl/crypto/x509v3/pcy_data.c", "openssl/openssl/crypto/x509v3/pcy_lib.c", "openssl/openssl/crypto/x509v3/pcy_map.c", "openssl/openssl/crypto/x509v3/pcy_node.c", "openssl/openssl/crypto/x509v3/pcy_tree.c", "openssl/openssl/crypto/x509v3/v3_addr.c", "openssl/openssl/crypto/x509v3/v3_akey.c", "openssl/openssl/crypto/x509v3/v3_akeya.c", "openssl/openssl/crypto/x509v3/v3_alt.c", "openssl/openssl/crypto/x509v3/v3_asid.c", "openssl/openssl/crypto/x509v3/v3_bcons.c", "openssl/openssl/crypto/x509v3/v3_bitst.c", "openssl/openssl/crypto/x509v3/v3_conf.c", "openssl/openssl/crypto/x509v3/v3_cpols.c", "openssl/openssl/crypto/x509v3/v3_crld.c", "openssl/openssl/crypto/x509v3/v3_enum.c", "openssl/openssl/crypto/x509v3/v3_extku.c", "openssl/openssl/crypto/x509v3/v3_genn.c", "openssl/openssl/crypto/x509v3/v3_ia5.c", "openssl/openssl/crypto/x509v3/v3_info.c", "openssl/openssl/crypto/x509v3/v3_int.c", "openssl/openssl/crypto/x509v3/v3_lib.c", "openssl/openssl/crypto/x509v3/v3_ncons.c", "openssl/openssl/crypto/x509v3/v3_ocsp.c", "openssl/openssl/crypto/x509v3/v3_pci.c", "openssl/openssl/crypto/x509v3/v3_pcia.c", "openssl/openssl/crypto/x509v3/v3_pcons.c", "openssl/openssl/crypto/x509v3/v3_pku.c", "openssl/openssl/crypto/x509v3/v3_pmaps.c", "openssl/openssl/crypto/x509v3/v3_prn.c", "openssl/openssl/crypto/x509v3/v3_purp.c", "openssl/openssl/crypto/x509v3/v3_skey.c", "openssl/openssl/crypto/x509v3/v3_sxnet.c", "openssl/openssl/crypto/x509v3/v3_utl.c", "openssl/openssl/crypto/x509v3/v3err.c", "openssl/openssl/engines/e_4758cca.c", "openssl/openssl/engines/e_aep.c", "openssl/openssl/engines/e_atalla.c", "openssl/openssl/engines/e_capi.c", "openssl/openssl/engines/e_chil.c", "openssl/openssl/engines/e_cswift.c", "openssl/openssl/engines/e_gmp.c", "openssl/openssl/engines/e_nuron.c", "openssl/openssl/engines/e_sureware.c", "openssl/openssl/engines/e_ubsec.c" ], "sources/": [ ["exclude", "md2/.*$"], ["exclude", "store/.*$"] ], "conditions": [ ["openssl_enable_asm!=1", { "defines": [ "OPENSSL_NO_ASM" ], "sources": [ "openssl/openssl/crypto/aes/aes_cbc.c", "openssl/openssl/crypto/aes/aes_core.c", "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/bn/bn_asm.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/camellia.c", "openssl/openssl/crypto/camellia/cmll_cbc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c", "openssl/openssl/crypto/mem_clr.c", "openssl/openssl/crypto/rc4/rc4_enc.c", "openssl/openssl/crypto/rc4/rc4_skey.c", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }, { "defines": [ "AES_ASM", "BF_ASM", "BNCO_ASM", "BN_ASM", "CPUID_ASM", "DES_ASM", "LIB_BN_ASM", "OPENSSL_BN_ASM", "OPENSSL_CPUID_OBJ", "RIP_ASM", "WHIRLPOOL_ASM", "WP_ASM" ], "conditions": [ ["OS!='win' and OS!='mac' and target_arch=='ia32'", { "sources": [ "asm/x86-elf-gas/aes/aes-586.s", "asm/x86-elf-gas/aes/aesni-x86.s", "asm/x86-elf-gas/bf/bf-686.s", "asm/x86-elf-gas/bn/x86-mont.s", "asm/x86-elf-gas/bn/x86.s", "asm/x86-elf-gas/camellia/cmll-x86.s", "asm/x86-elf-gas/cast/cast-586.s", "asm/x86-elf-gas/des/crypt586.s", "asm/x86-elf-gas/des/des-586.s", "asm/x86-elf-gas/md5/md5-586.s", "asm/x86-elf-gas/rc4/rc4-586.s", "asm/x86-elf-gas/rc5/rc5-586.s", "asm/x86-elf-gas/ripemd/rmd-586.s", "asm/x86-elf-gas/sha/sha1-586.s", "asm/x86-elf-gas/sha/sha256-586.s", "asm/x86-elf-gas/sha/sha512-586.s", "asm/x86-elf-gas/whrlpool/wp-mmx.s", "asm/x86-elf-gas/x86cpuid.s", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }], ["OS!='win' and OS!='mac' and target_arch=='x64'", { "sources": [ "asm/x64-elf-gas/aes/aes-x86_64.s", "asm/x64-elf-gas/aes/aesni-x86_64.s", "asm/x64-elf-gas/aes/aesni-sha1-x86_64.s", "asm/x64-elf-gas/bn/modexp512-x86_64.s", "asm/x64-elf-gas/bn/x86_64-mont.s", "asm/x64-elf-gas/camellia/cmll-x86_64.s", "asm/x64-elf-gas/md5/md5-x86_64.s", "asm/x64-elf-gas/rc4/rc4-x86_64.s", "asm/x64-elf-gas/rc4/rc4-md5-x86_64.s", "asm/x64-elf-gas/sha/sha1-x86_64.s", "asm/x64-elf-gas/sha/sha512-x86_64.s", "asm/x64-elf-gas/whrlpool/wp-x86_64.s", "asm/x64-elf-gas/x86_64cpuid.s", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-gcc.c", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ] }], ["OS=='mac' and target_arch=='ia32'", { "sources": [ "asm/x86-macosx-gas/aes/aes-586.s", "asm/x86-macosx-gas/aes/aesni-x86.s", "asm/x86-macosx-gas/bf/bf-686.s", "asm/x86-macosx-gas/bn/x86-mont.s", "asm/x86-macosx-gas/bn/x86.s", "asm/x86-macosx-gas/camellia/cmll-x86.s", "asm/x86-macosx-gas/cast/cast-586.s", "asm/x86-macosx-gas/des/crypt586.s", "asm/x86-macosx-gas/des/des-586.s", "asm/x86-macosx-gas/md5/md5-586.s", "asm/x86-macosx-gas/rc4/rc4-586.s", "asm/x86-macosx-gas/rc5/rc5-586.s", "asm/x86-macosx-gas/ripemd/rmd-586.s", "asm/x86-macosx-gas/sha/sha1-586.s", "asm/x86-macosx-gas/sha/sha256-586.s", "asm/x86-macosx-gas/sha/sha512-586.s", "asm/x86-macosx-gas/whrlpool/wp-mmx.s", "asm/x86-macosx-gas/x86cpuid.s", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }], ["OS=='mac' and target_arch=='x64'", { "sources": [ "asm/x64-macosx-gas/aes/aes-x86_64.s", "asm/x64-macosx-gas/aes/aesni-x86_64.s", "asm/x64-macosx-gas/aes/aesni-sha1-x86_64.s", "asm/x64-macosx-gas/bn/modexp512-x86_64.s", "asm/x64-macosx-gas/bn/x86_64-mont.s", "asm/x64-macosx-gas/camellia/cmll-x86_64.s", "asm/x64-macosx-gas/md5/md5-x86_64.s", "asm/x64-macosx-gas/rc4/rc4-x86_64.s", "asm/x64-macosx-gas/rc4/rc4-md5-x86_64.s", "asm/x64-macosx-gas/sha/sha1-x86_64.s", "asm/x64-macosx-gas/sha/sha512-x86_64.s", "asm/x64-macosx-gas/whrlpool/wp-x86_64.s", "asm/x64-macosx-gas/x86_64cpuid.s", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-gcc.c", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ] }], ["OS=='win' and target_arch=='ia32'", { "sources": [ "asm/x86-win32-masm/aes/aes-586.asm", "asm/x86-win32-masm/aes/aesni-x86.asm", "asm/x86-win32-masm/bf/bf-686.asm", "asm/x86-win32-masm/bn/x86-mont.asm", "asm/x86-win32-masm/bn/x86.asm", "asm/x86-win32-masm/camellia/cmll-x86.asm", "asm/x86-win32-masm/cast/cast-586.asm", "asm/x86-win32-masm/des/crypt586.asm", "asm/x86-win32-masm/des/des-586.asm", "asm/x86-win32-masm/md5/md5-586.asm", "asm/x86-win32-masm/rc4/rc4-586.asm", "asm/x86-win32-masm/rc5/rc5-586.asm", "asm/x86-win32-masm/ripemd/rmd-586.asm", "asm/x86-win32-masm/sha/sha1-586.asm", "asm/x86-win32-masm/sha/sha256-586.asm", "asm/x86-win32-masm/sha/sha512-586.asm", "asm/x86-win32-masm/whrlpool/wp-mmx.asm", "asm/x86-win32-masm/x86cpuid.asm", "openssl/openssl/crypto/whrlpool/wp_block.c" ], "rules": [ { "rule_name": "Assemble", "extension": "asm", "inputs": [], "outputs": [ "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", ], "action": [ "ml.exe", "/Zi", "/safeseh", "/Fo", "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", "/c", "<(RULE_INPUT_PATH)", ], "process_outputs_as_sources": 0, "message": "Assembling <(RULE_INPUT_PATH) to <(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj.", } ] }], ["OS=='win' and target_arch=='x64'", { "sources": [ "asm/x64-win32-masm/aes/aes-x86_64.asm", "asm/x64-win32-masm/aes/aesni-x86_64.asm", "asm/x64-win32-masm/aes/aesni-sha1-x86_64.asm", "asm/x64-win32-masm/bn/modexp512-x86_64.asm", "asm/x64-win32-masm/bn/x86_64-mont.asm", "asm/x64-win32-masm/camellia/cmll-x86_64.asm", "asm/x64-win32-masm/md5/md5-x86_64.asm", "asm/x64-win32-masm/rc4/rc4-x86_64.asm", "asm/x64-win32-masm/rc4/rc4-md5-x86_64.asm", "asm/x64-win32-masm/sha/sha1-x86_64.asm", "asm/x64-win32-masm/sha/sha512-x86_64.asm", "asm/x64-win32-masm/whrlpool/wp-x86_64.asm", "asm/x64-win32-masm/x86_64cpuid.asm", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-win32-masm.asm", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ], "rules": [ { "rule_name": "Assemble", "extension": "asm", "inputs": [], "outputs": [ "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", ], "action": [ "ml64.exe", "/Zi", "/Fo", "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", "/c", "<(RULE_INPUT_PATH)", ], "process_outputs_as_sources": 0, "message": "Assembling <(RULE_INPUT_PATH) to <(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj.", } ] }] ] }], ["OS=='win'", { "defines": [ "MK1MF_BUILD", "WIN32_LEAN_AND_MEAN" ], "link_settings": { "libraries": [ "-lgdi32.lib", "-luser32.lib", "-lwsock32.lib", ], "conditions": [ ["_type=='shared_library'", { "libraries": [ "-ladvapi32.lib" ] }] ] } }, { "defines": [ "TERMIOS", ], "cflags": [ "-Wno-missing-field-initializers" ], }], ["is_clang==1 or gcc_version>=43", { "cflags": [ "-Wno-old-style-declaration" ], }], ["OS=='solaris'", { "defines": [ "__EXTENSIONS__" ], }], ["target_arch=='arm'", { "sources": [ "openssl/openssl/crypto/armcap.c" ], }], ], }, ] }
true
true
f72a63ada453874531a4aa783d0ef1b05af45aff
21,710
py
Python
tests/engine/cloud/test_cloud_flows.py
tedmiston/prefect
a2cb40c28c942b1d170db42a55bab99598a4dcd6
[ "ECL-2.0", "Apache-2.0" ]
1
2020-05-10T14:32:32.000Z
2020-05-10T14:32:32.000Z
tests/engine/cloud/test_cloud_flows.py
tedmiston/prefect
a2cb40c28c942b1d170db42a55bab99598a4dcd6
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
tests/engine/cloud/test_cloud_flows.py
tedmiston/prefect
a2cb40c28c942b1d170db42a55bab99598a4dcd6
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
import datetime import sys import uuid from collections import Counter, namedtuple from unittest.mock import MagicMock import pendulum import pytest import prefect from prefect.client.client import Client, FlowRunInfoResult, TaskRunInfoResult from prefect.engine.cloud import CloudFlowRunner, CloudTaskRunner from prefect.engine.executors import LocalExecutor from prefect.engine.result_handlers import JSONResultHandler, ResultHandler from prefect.engine.state import ( Failed, Finished, Pending, Retrying, Running, Skipped, Success, TimedOut, TriggerFailed, ) from prefect.utilities.configuration import set_temporary_config pytestmark = pytest.mark.filterwarnings("ignore::UserWarning") class FlowRun: flow_id = str(uuid.uuid4()) def __init__(self, id, state=None, version=None): self.id = id self.name = "flow run name" self.state = state or Pending() self.version = version or 0 class TaskRun: def __init__( self, id, flow_run_id, task_slug, state=None, version=None, map_index=None ): self.id = id self.flow_run_id = flow_run_id self.task_id = task_slug self.task_slug = task_slug self.state = state or Pending() self.version = version or 0 self.map_index = map_index if map_index is not None else -1 @prefect.task def whats_the_time(): return prefect.context.get("scheduled_start_time") @prefect.task def plus_one(x): return x + 1 @prefect.task def invert_fail_once(x): try: return 1 / x except: if prefect.context.get("task_run_count", 0) < 2: raise else: return 100 @pytest.fixture(autouse=True) def cloud_settings(): with set_temporary_config( { "cloud.graphql": "http://my-cloud.foo", "cloud.auth_token": "token", "engine.flow_runner.default_class": "prefect.engine.cloud.CloudFlowRunner", "engine.task_runner.default_class": "prefect.engine.cloud.CloudTaskRunner", "logging.level": "DEBUG", } ): yield class MockedCloudClient(MagicMock): def __init__(self, flow_runs, task_runs, monkeypatch): super().__init__() self.flow_runs = {fr.id: fr for fr in flow_runs} self.task_runs = {tr.id: tr for tr in task_runs} self.call_count = Counter() monkeypatch.setattr( "prefect.engine.cloud.task_runner.Client", MagicMock(return_value=self) ) monkeypatch.setattr( "prefect.engine.cloud.flow_runner.Client", MagicMock(return_value=self) ) def get_flow_run_info(self, flow_run_id, *args, **kwargs): self.call_count["get_flow_run_info"] += 1 flow_run = self.flow_runs[flow_run_id] task_runs = [t for t in self.task_runs.values() if t.flow_run_id == flow_run_id] return FlowRunInfoResult( id=flow_run.id, flow_id=flow_run.flow_id, name=flow_run.name, parameters={}, context=None, version=flow_run.version, scheduled_start_time=pendulum.parse("2019-01-25T19:15:58.632412+00:00"), state=flow_run.state, task_runs=[ TaskRunInfoResult( id=tr.id, task_id=tr.task_slug, task_slug=tr.task_slug, version=tr.version, state=tr.state, ) for tr in task_runs ], ) def get_task_run_info(self, flow_run_id, task_id, map_index, *args, **kwargs): """ Return task run if found, otherwise create it """ self.call_count["get_task_run_info"] += 1 task_run = next( ( t for t in self.task_runs.values() if t.flow_run_id == flow_run_id and t.task_id == task_id and t.map_index == map_index ), None, ) if not task_run: task_run = TaskRun( id=str(uuid.uuid4()), task_slug=task_id, flow_run_id=flow_run_id, map_index=map_index, ) self.task_runs[task_run.id] = task_run return TaskRunInfoResult( id=task_run.id, task_id=task_id, task_slug=task_id, version=task_run.version, state=task_run.state, ) def set_flow_run_state(self, flow_run_id, version, state, **kwargs): self.call_count["set_flow_run_state"] += 1 self.call_count[flow_run_id] += 1 fr = self.flow_runs[flow_run_id] if fr.version == version: fr.state = state fr.version += 1 else: raise ValueError("Invalid flow run update") def set_task_run_state(self, task_run_id, version, state, **kwargs): self.call_count["set_task_run_state"] += 1 self.call_count[task_run_id] += 1 tr = self.task_runs[task_run_id] if tr.version == version: tr.state = state tr.version += 1 else: raise ValueError("Invalid task run update") return state @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_successful() @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_scheduled_start_time_is_in_context(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) flow = prefect.Flow( name="test", tasks=[whats_the_time], result_handler=ResultHandler() ) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun( id=task_run_id_1, task_slug=whats_the_time.slug, flow_run_id=flow_run_id ) ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_successful() assert isinstance(state.result[whats_the_time].result, datetime.datetime) @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow_with_final_task_set_to_fail(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun( id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id, state=Failed(), ), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_failed() assert client.task_runs[task_run_id_2].version == 0 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow_with_final_task_already_running(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun( id=task_run_id_2, task_slug=t2.slug, version=1, flow_run_id=flow_run_id, state=Running(), ), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_running() assert client.flow_runs[flow_run_id].state.is_running() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_running() assert client.task_runs[task_run_id_2].version == 1 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_three_task_flow_with_one_failing_task(monkeypatch, executor): @prefect.task def error(): 1 / 0 flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t3 = error() t2.set_upstream(t1) t3.set_upstream(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_successful() assert client.task_runs[task_run_id_2].version == 2 assert client.task_runs[task_run_id_3].state.is_failed() assert client.task_runs[task_run_id_2].version == 2 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_three_task_flow_with_first_task_retrying(monkeypatch, executor): """ If the first task retries, then the next two tasks shouldn't even make calls to Cloud because they won't pass their upstream checks """ @prefect.task(max_retries=1, retry_delay=datetime.timedelta(minutes=2)) def error(): 1 / 0 flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = error() t2 = prefect.Task() t3 = prefect.Task() t2.set_upstream(t1) t3.set_upstream(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_running() assert client.flow_runs[flow_run_id].state.is_running() assert isinstance(client.task_runs[task_run_id_1].state, Retrying) assert client.task_runs[task_run_id_1].version == 3 assert client.task_runs[task_run_id_2].state.is_pending() assert client.task_runs[task_run_id_2].version == 0 assert client.task_runs[task_run_id_3].state.is_pending() assert client.task_runs[task_run_id_2].version == 0 assert client.call_count["set_task_run_state"] == 3 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_map(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([0, 1, 2]) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id) ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t is not t1 ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_mapped() # there should be a total of 4 task runs corresponding to the mapped task assert len([tr for tr in client.task_runs.values() if tr.task_slug == t1.slug]) == 4 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_deep_map(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([0, 1, 2]) t2 = plus_one.map(t1) t3 = plus_one.map(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() # there should be a total of 4 task runs corresponding to each mapped task for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_deep_map_with_a_failure(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([-1, 0, 1]) t2 = invert_fail_once.map(t1) t3 = plus_one.map(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run(return_tasks=flow.tasks) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() # there should be a total of 4 task runs corresponding to each mapped task for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) # t2's first child task should have failed t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert t2_0.state.is_failed() # t3's first child task should have failed t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_failed() def test_deep_map_with_a_retry(monkeypatch): """ Creates a situation in which a deeply-mapped Flow encounters a one-time error in one of the middle layers. Running the flow a second time should resolve the error. DOES NOT WORK WITH DASK EXECUTORS because of the need for shared state on second run """ flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([-1, 0, 1]) t2 = invert_fail_once.map(t1) t3 = plus_one.map(t2) t2.max_retries = 1 t2.retry_delay = datetime.timedelta(seconds=100) monkeypatch.setattr("requests.Session", MagicMock()) monkeypatch.setattr("requests.post", MagicMock()) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): CloudFlowRunner(flow=flow).run(executor=LocalExecutor()) assert client.flow_runs[flow_run_id].state.is_running() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() # there should be a total of 4 task runs corresponding to each mapped task for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) # t2's first child task should be retrying t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert isinstance(t2_0.state, Retrying) # t3's first child task should be pending t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_pending() # RUN A SECOND TIME with an artificially updated start time failed_id = [ t_id for t_id, tr in client.task_runs.items() if tr.task_slug == t2.slug and tr.map_index == 0 ].pop() client.task_runs[failed_id].state.start_time = pendulum.now("UTC") with prefect.context(flow_run_id=flow_run_id): CloudFlowRunner(flow=flow).run(executor=LocalExecutor()) # t2's first child task should be successful t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert t2_0.state.is_successful() # t3's first child task should be successful t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_successful()
33.094512
89
0.643574
import datetime import sys import uuid from collections import Counter, namedtuple from unittest.mock import MagicMock import pendulum import pytest import prefect from prefect.client.client import Client, FlowRunInfoResult, TaskRunInfoResult from prefect.engine.cloud import CloudFlowRunner, CloudTaskRunner from prefect.engine.executors import LocalExecutor from prefect.engine.result_handlers import JSONResultHandler, ResultHandler from prefect.engine.state import ( Failed, Finished, Pending, Retrying, Running, Skipped, Success, TimedOut, TriggerFailed, ) from prefect.utilities.configuration import set_temporary_config pytestmark = pytest.mark.filterwarnings("ignore::UserWarning") class FlowRun: flow_id = str(uuid.uuid4()) def __init__(self, id, state=None, version=None): self.id = id self.name = "flow run name" self.state = state or Pending() self.version = version or 0 class TaskRun: def __init__( self, id, flow_run_id, task_slug, state=None, version=None, map_index=None ): self.id = id self.flow_run_id = flow_run_id self.task_id = task_slug self.task_slug = task_slug self.state = state or Pending() self.version = version or 0 self.map_index = map_index if map_index is not None else -1 @prefect.task def whats_the_time(): return prefect.context.get("scheduled_start_time") @prefect.task def plus_one(x): return x + 1 @prefect.task def invert_fail_once(x): try: return 1 / x except: if prefect.context.get("task_run_count", 0) < 2: raise else: return 100 @pytest.fixture(autouse=True) def cloud_settings(): with set_temporary_config( { "cloud.graphql": "http://my-cloud.foo", "cloud.auth_token": "token", "engine.flow_runner.default_class": "prefect.engine.cloud.CloudFlowRunner", "engine.task_runner.default_class": "prefect.engine.cloud.CloudTaskRunner", "logging.level": "DEBUG", } ): yield class MockedCloudClient(MagicMock): def __init__(self, flow_runs, task_runs, monkeypatch): super().__init__() self.flow_runs = {fr.id: fr for fr in flow_runs} self.task_runs = {tr.id: tr for tr in task_runs} self.call_count = Counter() monkeypatch.setattr( "prefect.engine.cloud.task_runner.Client", MagicMock(return_value=self) ) monkeypatch.setattr( "prefect.engine.cloud.flow_runner.Client", MagicMock(return_value=self) ) def get_flow_run_info(self, flow_run_id, *args, **kwargs): self.call_count["get_flow_run_info"] += 1 flow_run = self.flow_runs[flow_run_id] task_runs = [t for t in self.task_runs.values() if t.flow_run_id == flow_run_id] return FlowRunInfoResult( id=flow_run.id, flow_id=flow_run.flow_id, name=flow_run.name, parameters={}, context=None, version=flow_run.version, scheduled_start_time=pendulum.parse("2019-01-25T19:15:58.632412+00:00"), state=flow_run.state, task_runs=[ TaskRunInfoResult( id=tr.id, task_id=tr.task_slug, task_slug=tr.task_slug, version=tr.version, state=tr.state, ) for tr in task_runs ], ) def get_task_run_info(self, flow_run_id, task_id, map_index, *args, **kwargs): self.call_count["get_task_run_info"] += 1 task_run = next( ( t for t in self.task_runs.values() if t.flow_run_id == flow_run_id and t.task_id == task_id and t.map_index == map_index ), None, ) if not task_run: task_run = TaskRun( id=str(uuid.uuid4()), task_slug=task_id, flow_run_id=flow_run_id, map_index=map_index, ) self.task_runs[task_run.id] = task_run return TaskRunInfoResult( id=task_run.id, task_id=task_id, task_slug=task_id, version=task_run.version, state=task_run.state, ) def set_flow_run_state(self, flow_run_id, version, state, **kwargs): self.call_count["set_flow_run_state"] += 1 self.call_count[flow_run_id] += 1 fr = self.flow_runs[flow_run_id] if fr.version == version: fr.state = state fr.version += 1 else: raise ValueError("Invalid flow run update") def set_task_run_state(self, task_run_id, version, state, **kwargs): self.call_count["set_task_run_state"] += 1 self.call_count[task_run_id] += 1 tr = self.task_runs[task_run_id] if tr.version == version: tr.state = state tr.version += 1 else: raise ValueError("Invalid task run update") return state @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_successful() @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_scheduled_start_time_is_in_context(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) flow = prefect.Flow( name="test", tasks=[whats_the_time], result_handler=ResultHandler() ) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun( id=task_run_id_1, task_slug=whats_the_time.slug, flow_run_id=flow_run_id ) ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_successful() assert isinstance(state.result[whats_the_time].result, datetime.datetime) @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow_with_final_task_set_to_fail(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun( id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id, state=Failed(), ), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_failed() assert client.task_runs[task_run_id_2].version == 0 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow_with_final_task_already_running(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun( id=task_run_id_2, task_slug=t2.slug, version=1, flow_run_id=flow_run_id, state=Running(), ), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_running() assert client.flow_runs[flow_run_id].state.is_running() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_running() assert client.task_runs[task_run_id_2].version == 1 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_three_task_flow_with_one_failing_task(monkeypatch, executor): @prefect.task def error(): 1 / 0 flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t3 = error() t2.set_upstream(t1) t3.set_upstream(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_successful() assert client.task_runs[task_run_id_2].version == 2 assert client.task_runs[task_run_id_3].state.is_failed() assert client.task_runs[task_run_id_2].version == 2 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_three_task_flow_with_first_task_retrying(monkeypatch, executor): @prefect.task(max_retries=1, retry_delay=datetime.timedelta(minutes=2)) def error(): 1 / 0 flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = error() t2 = prefect.Task() t3 = prefect.Task() t2.set_upstream(t1) t3.set_upstream(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_running() assert client.flow_runs[flow_run_id].state.is_running() assert isinstance(client.task_runs[task_run_id_1].state, Retrying) assert client.task_runs[task_run_id_1].version == 3 assert client.task_runs[task_run_id_2].state.is_pending() assert client.task_runs[task_run_id_2].version == 0 assert client.task_runs[task_run_id_3].state.is_pending() assert client.task_runs[task_run_id_2].version == 0 assert client.call_count["set_task_run_state"] == 3 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_map(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([0, 1, 2]) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id) ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t is not t1 ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_mapped() assert len([tr for tr in client.task_runs.values() if tr.task_slug == t1.slug]) == 4 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_deep_map(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([0, 1, 2]) t2 = plus_one.map(t1) t3 = plus_one.map(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_deep_map_with_a_failure(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([-1, 0, 1]) t2 = invert_fail_once.map(t1) t3 = plus_one.map(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run(return_tasks=flow.tasks) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert t2_0.state.is_failed() # t3's first child task should have failed t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_failed() def test_deep_map_with_a_retry(monkeypatch): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([-1, 0, 1]) t2 = invert_fail_once.map(t1) t3 = plus_one.map(t2) t2.max_retries = 1 t2.retry_delay = datetime.timedelta(seconds=100) monkeypatch.setattr("requests.Session", MagicMock()) monkeypatch.setattr("requests.post", MagicMock()) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): CloudFlowRunner(flow=flow).run(executor=LocalExecutor()) assert client.flow_runs[flow_run_id].state.is_running() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert isinstance(t2_0.state, Retrying) # t3's first child task should be pending t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_pending() failed_id = [ t_id for t_id, tr in client.task_runs.items() if tr.task_slug == t2.slug and tr.map_index == 0 ].pop() client.task_runs[failed_id].state.start_time = pendulum.now("UTC") with prefect.context(flow_run_id=flow_run_id): CloudFlowRunner(flow=flow).run(executor=LocalExecutor()) t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert t2_0.state.is_successful() # t3's first child task should be successful t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_successful()
true
true
f72a6472f11d4bd876bdf957708a3a20931e06da
10,074
py
Python
scripts/fishnet_generator.py
dgketchum/gsflow-arcpy
966e8f48e0fee1ba534fc6a64987f67594b144f2
[ "Apache-2.0" ]
13
2018-09-12T17:42:48.000Z
2022-03-18T20:14:45.000Z
scripts/fishnet_generator.py
dgketchum/gsflow-arcpy
966e8f48e0fee1ba534fc6a64987f67594b144f2
[ "Apache-2.0" ]
35
2018-03-08T16:20:07.000Z
2020-11-05T11:59:05.000Z
scripts/fishnet_generator.py
dgketchum/gsflow-arcpy
966e8f48e0fee1ba534fc6a64987f67594b144f2
[ "Apache-2.0" ]
12
2018-08-18T20:54:56.000Z
2022-03-26T00:04:45.000Z
#-------------------------------- # Name: fishnet_generator.py # Purpose: GSFLOW fishnet generator # Notes: ArcGIS 10.2+ Version # Python: 2.7 #-------------------------------- import argparse import ConfigParser import datetime as dt from decimal import Decimal import logging import os import sys import arcpy from arcpy import env import support_functions as support def fishnet_func(config_path, overwrite_flag=False): """GSFLOW Fishnet Generator Args: config_file (str): Project config file path ovewrite_flag (bool): if True, overwrite existing files debug_flag (bool): if True, enable debug level logging Parameters ---------- config_path : str Project configuration file (.ini) path. ovewrite_flag : bool If True, overwrite existing files (the default is False). Returns ------- None """ # Initialize hru parameters class hru = support.HRUParameters(config_path) # Open input parameter config file inputs_cfg = ConfigParser.ConfigParser() try: inputs_cfg.readfp(open(config_path)) except Exception as e: logging.error( '\nERROR: Config file could not be read, ' 'is not an input file, or does not exist\n' ' config_file = {}\n' ' Exception: {}\n'.format(config_path, e)) sys.exit() # Log DEBUG to file log_file_name = 'fishnet_generator_log.txt' log_console = logging.FileHandler( filename=os.path.join(hru.log_ws, log_file_name), mode='w') log_console.setLevel(logging.DEBUG) log_console.setFormatter(logging.Formatter('%(message)s')) logging.getLogger('').addHandler(log_console) logging.info('\nGSFLOW Fishnet Generator') # Warn the user if the fishnet already exists # It might be better to not allow the user to do this at all and force them # to manually remove the file. if arcpy.Exists(hru.polygon_path) and not overwrite_flag: logging.warning('\nWARNING: The existing fishnet/grid will be ' 'over written\n {}'.format(hru.polygon_path)) raw_input('Press ENTER to continue') # Check input paths study_area_path = inputs_cfg.get('INPUTS', 'study_area_path') if not arcpy.Exists(study_area_path): logging.error( '\nERROR: Study area ({}) does not exist'.format( study_area_path)) sys.exit() # For now, study area has to be a polygon if arcpy.Describe(study_area_path).datasetType != 'FeatureClass': logging.error( '\nERROR: For now, study area must be a polygon shapefile') sys.exit() # Read Fishnet specific parameters from INI # If ref_x and ref_y are not specified, get from the study area extent try: hru.ref_x = inputs_cfg.getfloat('INPUTS', 'hru_ref_x') except: hru.ref_x = arcpy.Describe(study_area_path).extent.XMin logging.info( ' {0} parameter not set in INI, setting {0} = {1}'.format( 'ref_x', hru.ref_x)) try: hru.ref_y = inputs_cfg.getfloat('INPUTS', 'hru_ref_y') except: hru.ref_y = arcpy.Describe(study_area_path).extent.YMin logging.info( ' {0} parameter not set in INI, setting {0} = {1}'.format( 'ref_y', hru.ref_y)) try: buffer_cells = inputs_cfg.getint('INPUTS', 'hru_buffer_cells') except: buffer_cells = 2 logging.info( ' Missing INI parameter, setting {} = {}'.format( 'buffer_cells', buffer_cells)) try: snap_method = inputs_cfg.get('INPUTS', 'hru_param_snap_method') except: snap_method = 'EXPAND' logging.info( ' Missing INI parameter, setting {} = {}'.format( 'snap_method', snap_method)) snap_method_list = ['EXPAND', 'ROUND', 'SHRINK'] if snap_method not in snap_method_list: logging.error('\nERROR: {} must be: {}'.format( 'snap_method', ', '.join(snap_method_list))) sys.exit() # Log input hru parameters logging.info('\nFishnet Parameters') logging.info(' Cellsize: {}'.format(hru.cs)) logging.info(' Snap point: {} {}'.format(hru.ref_x, hru.ref_y)) logging.debug(' Buffer cells: {}'.format(buffer_cells)) # Read reference point as string for determining number of digits try: digits = abs(min( Decimal(inputs_cfg.get('INPUTS', 'hru_ref_x')).as_tuple().exponent, Decimal(inputs_cfg.get('INPUTS', 'hru_ref_y')).as_tuple().exponent)) except ConfigParser.NoOptionError: digits = 10 logging.debug(' Extent digits: {}'.format(digits)) # Check inputs if buffer_cells < 0: logging.error('\nERROR: Buffer cells must be greater than 0') sys.exit() # Build output folder if necessary fishnet_temp_ws = os.path.join(hru.param_ws, 'fishnet_temp') if not os.path.isdir(fishnet_temp_ws): os.mkdir(fishnet_temp_ws) # Output paths study_area_proj_path = os.path.join( fishnet_temp_ws, 'projected_study_area.shp') # Set ArcGIS environment variables arcpy.CheckOutExtension('Spatial') env.overwriteOutput = True env.pyramid = 'PYRAMIDS -1' # env.pyramid = 'PYRAMIDS 0' env.workspace = hru.param_ws env.scratchWorkspace = hru.scratch_ws # Get spatial reference of study_area hru.sr = arcpy.Describe(study_area_path).spatialReference # If study area spat_ref doesn't match hru_param spat_ref # Project study are to hru_param and get projected extent # Otherwise, read study_area extent directly study_area_extent = arcpy.Describe(study_area_path).extent logging.debug('\n Study area: {}'.format(study_area_path)) logging.debug(' Study area spat. ref.: {}'.format(hru.sr.name)) logging.debug(' Study area GCS: {}'.format(hru.sr.GCS.name)) logging.info(' Study Area extent: {}'.format( support.extent_string(study_area_extent))) # Check if the study area shapefile is projeted if (hru.sr.name in ['GCS_North_American_1983', 'GCS_WGS_1984'] or hru.sr.GCS.name == hru.sr.name): logging.warning( '\nWARNING: The study area shapefile does not appear to be projected.' '\n This will likely cause problems or not work at all.' '\n Projection: {}'.format(hru.sr.name)) raw_input('Press ENTER to continue\n') # Buffer extent buffer_extent = support.buffer_extent_func( study_area_extent, buffer_cells * hru.cs) logging.info(' Buffered Extent: {}'.format( support.extent_string(buffer_extent))) # Adjust study area extent to reference points # Set the number of digits of rounding based on the number digits # int the reference points hru.ref_pnt = arcpy.Point(hru.ref_x, hru.ref_y) hru.extent = support.adjust_extent_to_snap( buffer_extent, hru.ref_pnt, hru.cs, method=snap_method, digits=digits) logging.info(' Snapped Extent: {}'.format( support.extent_string(hru.extent))) # Build hru_param logging.info('\nBuilding HRU parameter fishnet') build_fishnet_func( hru.polygon_path, hru.point_path, hru.extent, hru.cs, hru.sr) # Write initial parameters to hru_param (X/Y, ROW/COL, Unique ID) # set_hru_id_func(hru.polygon_path, hru.extent, hru.cs) def build_fishnet_func(hru_polygon_path, hru_point_path, extent, cs, sr): """""" # Remove existing if arcpy.Exists(hru_polygon_path): arcpy.Delete_management(hru_polygon_path) if arcpy.Exists(hru_point_path): arcpy.Delete_management(hru_point_path) # Calculate LL/UR corner points origin_pnt = (extent.XMin, extent.YMin) yaxis_pnt = (extent.XMin, extent.YMin + cs) corner_pnt = (extent.XMax, extent.YMax) origin_str = ' '.join(map(str, origin_pnt)) yaxis_str = ' '.join(map(str, yaxis_pnt)) corner_str = ' '.join(map(str, corner_pnt)) logging.debug(' Origin: {}'.format(origin_str)) logging.debug(' Y-Axis: {}'.format(yaxis_str)) logging.debug(' Corner: {}'.format(corner_str)) # Build fishnet & labels arcpy.CreateFishnet_management( hru_polygon_path, origin_str, yaxis_str, cs, cs, '0', '0', corner_str, 'LABELS', '#', 'POLYGON') arcpy.DefineProjection_management(hru_polygon_path, sr) arcpy.DefineProjection_management(hru_point_path, sr) def arg_parse(): """""" parser = argparse.ArgumentParser( description='Fishnet Generator', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-i', '--ini', required=True, help='Project input file', metavar='PATH') parser.add_argument( '-o', '--overwrite', default=False, action="store_true", help='Force overwrite of existing files') parser.add_argument( '-d', '--debug', default=logging.INFO, const=logging.DEBUG, help='Debug level logging', action="store_const", dest="loglevel") args = parser.parse_args() # Convert input file to an absolute path if os.path.isfile(os.path.abspath(args.ini)): args.ini = os.path.abspath(args.ini) return args if __name__ == '__main__': args = arg_parse() logging.basicConfig(level=args.loglevel, format='%(message)s') logging.info('\n{}'.format('#' * 80)) log_f = '{:<20s} {}' logging.info(log_f.format( 'Run Time Stamp:', dt.datetime.now().isoformat(' '))) logging.info(log_f.format('Current Directory:', os.getcwd())) logging.info(log_f.format('Script:', os.path.basename(sys.argv[0]))) fishnet_func(config_path=args.ini, overwrite_flag=args.overwrite)
37.730337
83
0.629839
import argparse import ConfigParser import datetime as dt from decimal import Decimal import logging import os import sys import arcpy from arcpy import env import support_functions as support def fishnet_func(config_path, overwrite_flag=False): hru = support.HRUParameters(config_path) inputs_cfg = ConfigParser.ConfigParser() try: inputs_cfg.readfp(open(config_path)) except Exception as e: logging.error( '\nERROR: Config file could not be read, ' 'is not an input file, or does not exist\n' ' config_file = {}\n' ' Exception: {}\n'.format(config_path, e)) sys.exit() log_file_name = 'fishnet_generator_log.txt' log_console = logging.FileHandler( filename=os.path.join(hru.log_ws, log_file_name), mode='w') log_console.setLevel(logging.DEBUG) log_console.setFormatter(logging.Formatter('%(message)s')) logging.getLogger('').addHandler(log_console) logging.info('\nGSFLOW Fishnet Generator') if arcpy.Exists(hru.polygon_path) and not overwrite_flag: logging.warning('\nWARNING: The existing fishnet/grid will be ' 'over written\n {}'.format(hru.polygon_path)) raw_input('Press ENTER to continue') study_area_path = inputs_cfg.get('INPUTS', 'study_area_path') if not arcpy.Exists(study_area_path): logging.error( '\nERROR: Study area ({}) does not exist'.format( study_area_path)) sys.exit() if arcpy.Describe(study_area_path).datasetType != 'FeatureClass': logging.error( '\nERROR: For now, study area must be a polygon shapefile') sys.exit() try: hru.ref_x = inputs_cfg.getfloat('INPUTS', 'hru_ref_x') except: hru.ref_x = arcpy.Describe(study_area_path).extent.XMin logging.info( ' {0} parameter not set in INI, setting {0} = {1}'.format( 'ref_x', hru.ref_x)) try: hru.ref_y = inputs_cfg.getfloat('INPUTS', 'hru_ref_y') except: hru.ref_y = arcpy.Describe(study_area_path).extent.YMin logging.info( ' {0} parameter not set in INI, setting {0} = {1}'.format( 'ref_y', hru.ref_y)) try: buffer_cells = inputs_cfg.getint('INPUTS', 'hru_buffer_cells') except: buffer_cells = 2 logging.info( ' Missing INI parameter, setting {} = {}'.format( 'buffer_cells', buffer_cells)) try: snap_method = inputs_cfg.get('INPUTS', 'hru_param_snap_method') except: snap_method = 'EXPAND' logging.info( ' Missing INI parameter, setting {} = {}'.format( 'snap_method', snap_method)) snap_method_list = ['EXPAND', 'ROUND', 'SHRINK'] if snap_method not in snap_method_list: logging.error('\nERROR: {} must be: {}'.format( 'snap_method', ', '.join(snap_method_list))) sys.exit() logging.info('\nFishnet Parameters') logging.info(' Cellsize: {}'.format(hru.cs)) logging.info(' Snap point: {} {}'.format(hru.ref_x, hru.ref_y)) logging.debug(' Buffer cells: {}'.format(buffer_cells)) try: digits = abs(min( Decimal(inputs_cfg.get('INPUTS', 'hru_ref_x')).as_tuple().exponent, Decimal(inputs_cfg.get('INPUTS', 'hru_ref_y')).as_tuple().exponent)) except ConfigParser.NoOptionError: digits = 10 logging.debug(' Extent digits: {}'.format(digits)) if buffer_cells < 0: logging.error('\nERROR: Buffer cells must be greater than 0') sys.exit() fishnet_temp_ws = os.path.join(hru.param_ws, 'fishnet_temp') if not os.path.isdir(fishnet_temp_ws): os.mkdir(fishnet_temp_ws) study_area_proj_path = os.path.join( fishnet_temp_ws, 'projected_study_area.shp') arcpy.CheckOutExtension('Spatial') env.overwriteOutput = True env.pyramid = 'PYRAMIDS -1' env.workspace = hru.param_ws env.scratchWorkspace = hru.scratch_ws hru.sr = arcpy.Describe(study_area_path).spatialReference # Project study are to hru_param and get projected extent # Otherwise, read study_area extent directly study_area_extent = arcpy.Describe(study_area_path).extent logging.debug('\n Study area: {}'.format(study_area_path)) logging.debug(' Study area spat. ref.: {}'.format(hru.sr.name)) logging.debug(' Study area GCS: {}'.format(hru.sr.GCS.name)) logging.info(' Study Area extent: {}'.format( support.extent_string(study_area_extent))) # Check if the study area shapefile is projeted if (hru.sr.name in ['GCS_North_American_1983', 'GCS_WGS_1984'] or hru.sr.GCS.name == hru.sr.name): logging.warning( '\nWARNING: The study area shapefile does not appear to be projected.' '\n This will likely cause problems or not work at all.' '\n Projection: {}'.format(hru.sr.name)) raw_input('Press ENTER to continue\n') # Buffer extent buffer_extent = support.buffer_extent_func( study_area_extent, buffer_cells * hru.cs) logging.info(' Buffered Extent: {}'.format( support.extent_string(buffer_extent))) # Adjust study area extent to reference points # Set the number of digits of rounding based on the number digits # int the reference points hru.ref_pnt = arcpy.Point(hru.ref_x, hru.ref_y) hru.extent = support.adjust_extent_to_snap( buffer_extent, hru.ref_pnt, hru.cs, method=snap_method, digits=digits) logging.info(' Snapped Extent: {}'.format( support.extent_string(hru.extent))) # Build hru_param logging.info('\nBuilding HRU parameter fishnet') build_fishnet_func( hru.polygon_path, hru.point_path, hru.extent, hru.cs, hru.sr) # Write initial parameters to hru_param (X/Y, ROW/COL, Unique ID) # set_hru_id_func(hru.polygon_path, hru.extent, hru.cs) def build_fishnet_func(hru_polygon_path, hru_point_path, extent, cs, sr): # Remove existing if arcpy.Exists(hru_polygon_path): arcpy.Delete_management(hru_polygon_path) if arcpy.Exists(hru_point_path): arcpy.Delete_management(hru_point_path) # Calculate LL/UR corner points origin_pnt = (extent.XMin, extent.YMin) yaxis_pnt = (extent.XMin, extent.YMin + cs) corner_pnt = (extent.XMax, extent.YMax) origin_str = ' '.join(map(str, origin_pnt)) yaxis_str = ' '.join(map(str, yaxis_pnt)) corner_str = ' '.join(map(str, corner_pnt)) logging.debug(' Origin: {}'.format(origin_str)) logging.debug(' Y-Axis: {}'.format(yaxis_str)) logging.debug(' Corner: {}'.format(corner_str)) # Build fishnet & labels arcpy.CreateFishnet_management( hru_polygon_path, origin_str, yaxis_str, cs, cs, '0', '0', corner_str, 'LABELS', ' arcpy.DefineProjection_management(hru_polygon_path, sr) arcpy.DefineProjection_management(hru_point_path, sr) def arg_parse(): parser = argparse.ArgumentParser( description='Fishnet Generator', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-i', '--ini', required=True, help='Project input file', metavar='PATH') parser.add_argument( '-o', '--overwrite', default=False, action="store_true", help='Force overwrite of existing files') parser.add_argument( '-d', '--debug', default=logging.INFO, const=logging.DEBUG, help='Debug level logging', action="store_const", dest="loglevel") args = parser.parse_args() # Convert input file to an absolute path if os.path.isfile(os.path.abspath(args.ini)): args.ini = os.path.abspath(args.ini) return args if __name__ == '__main__': args = arg_parse() logging.basicConfig(level=args.loglevel, format='%(message)s') logging.info('\n{}'.format(' log_f = '{:<20s} {}' logging.info(log_f.format( 'Run Time Stamp:', dt.datetime.now().isoformat(' '))) logging.info(log_f.format('Current Directory:', os.getcwd())) logging.info(log_f.format('Script:', os.path.basename(sys.argv[0]))) fishnet_func(config_path=args.ini, overwrite_flag=args.overwrite)
true
true
f72a6574f160f049bb1e251b53b255e19fcb01c4
2,448
py
Python
test/functional/p2p_addrv2_relay.py
PivxLiteDev/PivxLite
648d4a193b61b1996b41e9f6c6c468875c757cdd
[ "MIT" ]
null
null
null
test/functional/p2p_addrv2_relay.py
PivxLiteDev/PivxLite
648d4a193b61b1996b41e9f6c6c468875c757cdd
[ "MIT" ]
3
2020-02-06T10:15:07.000Z
2022-01-13T00:08:49.000Z
test/functional/p2p_addrv2_relay.py
PivxLiteDev/PivxLite
648d4a193b61b1996b41e9f6c6c468875c757cdd
[ "MIT" ]
9
2020-03-10T14:14:25.000Z
2022-03-05T13:43:35.000Z
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test addrv2 relay """ import time from test_framework.messages import ( CAddress, msg_addrv2, NODE_NETWORK ) from test_framework.mininode import P2PInterface from test_framework.test_framework import PivxlTestFramework from test_framework.util import assert_equal ADDRS = [] for i in range(10): addr = CAddress() addr.time = int(time.time()) + i addr.nServices = NODE_NETWORK addr.ip = "123.123.123.{}".format(i % 256) addr.port = 8333 + i ADDRS.append(addr) class AddrReceiver(P2PInterface): addrv2_received_and_checked = False def __init__(self): super().__init__(support_addrv2 = True) def on_addrv2(self, message): for addr in message.addrs: assert_equal(addr.nServices, 1) # NODE_NETWORK assert addr.ip.startswith('123.123.123.') assert (8333 <= addr.port < 8343) self.addrv2_received_and_checked = True def wait_for_addrv2(self): self.wait_until(lambda: "addrv2" in self.last_message) class AddrTest(PivxlTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): self.log.info('Create connection that sends addrv2 messages') addr_source = self.nodes[0].add_p2p_connection(P2PInterface()) msg = msg_addrv2() self.log.info('Send too-large addrv2 message') msg.addrs = ADDRS * 101 with self.nodes[0].assert_debug_log(['addrv2 message size = 1010']): addr_source.send_and_ping(msg) self.log.info('Check that addrv2 message content is relayed and added to addrman') addr_receiver = self.nodes[0].add_p2p_connection(AddrReceiver()) msg.addrs = ADDRS with self.nodes[0].assert_debug_log([ 'Added 10 addresses from 127.0.0.1: 0 tried', 'received: addrv2 (131 bytes) peer=1', 'sending addrv2 (131 bytes) peer=2', ]): addr_source.send_and_ping(msg) self.nodes[0].setmocktime(int(time.time()) + 30 * 60) addr_receiver.wait_for_addrv2() assert addr_receiver.addrv2_received_and_checked if __name__ == '__main__': AddrTest().main()
30.987342
90
0.664216
import time from test_framework.messages import ( CAddress, msg_addrv2, NODE_NETWORK ) from test_framework.mininode import P2PInterface from test_framework.test_framework import PivxlTestFramework from test_framework.util import assert_equal ADDRS = [] for i in range(10): addr = CAddress() addr.time = int(time.time()) + i addr.nServices = NODE_NETWORK addr.ip = "123.123.123.{}".format(i % 256) addr.port = 8333 + i ADDRS.append(addr) class AddrReceiver(P2PInterface): addrv2_received_and_checked = False def __init__(self): super().__init__(support_addrv2 = True) def on_addrv2(self, message): for addr in message.addrs: assert_equal(addr.nServices, 1) assert addr.ip.startswith('123.123.123.') assert (8333 <= addr.port < 8343) self.addrv2_received_and_checked = True def wait_for_addrv2(self): self.wait_until(lambda: "addrv2" in self.last_message) class AddrTest(PivxlTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): self.log.info('Create connection that sends addrv2 messages') addr_source = self.nodes[0].add_p2p_connection(P2PInterface()) msg = msg_addrv2() self.log.info('Send too-large addrv2 message') msg.addrs = ADDRS * 101 with self.nodes[0].assert_debug_log(['addrv2 message size = 1010']): addr_source.send_and_ping(msg) self.log.info('Check that addrv2 message content is relayed and added to addrman') addr_receiver = self.nodes[0].add_p2p_connection(AddrReceiver()) msg.addrs = ADDRS with self.nodes[0].assert_debug_log([ 'Added 10 addresses from 127.0.0.1: 0 tried', 'received: addrv2 (131 bytes) peer=1', 'sending addrv2 (131 bytes) peer=2', ]): addr_source.send_and_ping(msg) self.nodes[0].setmocktime(int(time.time()) + 30 * 60) addr_receiver.wait_for_addrv2() assert addr_receiver.addrv2_received_and_checked if __name__ == '__main__': AddrTest().main()
true
true
f72a65ddec02cb6954334890b87a93ad0a175bef
257
py
Python
Akeso/Exploits/ExploitFrame.py
tamuctf/Akeso
05e6c284b45e1d1ec2d744a8508c9b03e3b5718e
[ "MIT" ]
19
2018-02-26T00:19:17.000Z
2019-12-18T04:26:45.000Z
Akeso/Exploits/ExploitFrame.py
tamuctf/Akeso
05e6c284b45e1d1ec2d744a8508c9b03e3b5718e
[ "MIT" ]
11
2018-05-07T15:11:30.000Z
2018-11-13T16:40:41.000Z
DefenseLab/Exploits/ExploitFrame.py
ameserole/Defense-Lab
05d89eecd52e76c00f6aa3ab0eaaff85fad88dbb
[ "MIT" ]
2
2019-12-11T07:28:48.000Z
2021-05-30T07:41:57.000Z
class ExploitFrame(object): """Exploit object""" def __init__(self, serviceInfo): self.serviceInfo = serviceInfo def exploit(self): raise NotImplementedError() def exploitSuccess(self): raise NotImplementedError()
21.416667
38
0.66537
class ExploitFrame(object): def __init__(self, serviceInfo): self.serviceInfo = serviceInfo def exploit(self): raise NotImplementedError() def exploitSuccess(self): raise NotImplementedError()
true
true
f72a66542ace53e924c25a5a10a82214486982d6
3,365
py
Python
SQSConnection.py
jmartipu/CrearSolicitudDispatcher
3b9c46f5f4a07fe96c98846c7f48d802203e8cee
[ "Apache-2.0" ]
null
null
null
SQSConnection.py
jmartipu/CrearSolicitudDispatcher
3b9c46f5f4a07fe96c98846c7f48d802203e8cee
[ "Apache-2.0" ]
null
null
null
SQSConnection.py
jmartipu/CrearSolicitudDispatcher
3b9c46f5f4a07fe96c98846c7f48d802203e8cee
[ "Apache-2.0" ]
null
null
null
import boto3 import botocore import Settings class SQSConnection: session = boto3.Session( aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS, aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS, ) sqs = session.client('sqs', region_name=Settings.AWS_REGION_SQS) queue_url = Settings.AWS_QUEUE_URL_IN exists = True message = '' receipt_handle = '' def __init__(self, queue_url): self.queue_url = queue_url def __enter__(self): try: self.session = boto3.Session( aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS, aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS, ) self.sqs = self.session.client('sqs', region_name=Settings.AWS_REGION_SQS) except ConnectionError: print("No se puede conectar a SQS") except Exception as e: print(e) def receive(self): try: response = self.sqs.receive_message( QueueUrl=self.queue_url, AttributeNames=[ 'ALL' ], MaxNumberOfMessages=1, MessageAttributeNames=[ 'All' ], VisibilityTimeout=20, WaitTimeSeconds=2 ) if response is not None: self.message = response['Messages'][0] self.receipt_handle = self.message['ReceiptHandle'] except botocore.exceptions.ClientError as e: # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print(e) def delete(self): try: print(self.receipt_handle) self.sqs.delete_message( QueueUrl=self.queue_url, ReceiptHandle=self.receipt_handle ) self.message = '' self.receipt_handle = '' except botocore.exceptions.ClientError as e: # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print('Error Cargando SQS') def __exit__(self, exc_type, exc_val, exc_tb): print("SQS Terminada exit") def send(self, data): try: print("inicia enviado") response = self.sqs.send_message( QueueUrl=self.queue_url, MessageAttributes=data.get('MessageAttributes'), MessageBody=data.get('Body'), ) print("termina enviado") except botocore.exceptions.ClientError as e: # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print(e)
31.157407
86
0.556612
import boto3 import botocore import Settings class SQSConnection: session = boto3.Session( aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS, aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS, ) sqs = session.client('sqs', region_name=Settings.AWS_REGION_SQS) queue_url = Settings.AWS_QUEUE_URL_IN exists = True message = '' receipt_handle = '' def __init__(self, queue_url): self.queue_url = queue_url def __enter__(self): try: self.session = boto3.Session( aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS, aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS, ) self.sqs = self.session.client('sqs', region_name=Settings.AWS_REGION_SQS) except ConnectionError: print("No se puede conectar a SQS") except Exception as e: print(e) def receive(self): try: response = self.sqs.receive_message( QueueUrl=self.queue_url, AttributeNames=[ 'ALL' ], MaxNumberOfMessages=1, MessageAttributeNames=[ 'All' ], VisibilityTimeout=20, WaitTimeSeconds=2 ) if response is not None: self.message = response['Messages'][0] self.receipt_handle = self.message['ReceiptHandle'] except botocore.exceptions.ClientError as e: error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print(e) def delete(self): try: print(self.receipt_handle) self.sqs.delete_message( QueueUrl=self.queue_url, ReceiptHandle=self.receipt_handle ) self.message = '' self.receipt_handle = '' except botocore.exceptions.ClientError as e: error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print('Error Cargando SQS') def __exit__(self, exc_type, exc_val, exc_tb): print("SQS Terminada exit") def send(self, data): try: print("inicia enviado") response = self.sqs.send_message( QueueUrl=self.queue_url, MessageAttributes=data.get('MessageAttributes'), MessageBody=data.get('Body'), ) print("termina enviado") except botocore.exceptions.ClientError as e: error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print(e)
true
true
f72a674b8b8017122951cbd31901aa9c70d1de59
10,984
py
Python
insights/parsers/systemd/unitfiles.py
haithcockce/insights-core
b2e197c6bfc25bcbe2926f07c35a80f2cf8232f5
[ "Apache-2.0" ]
121
2017-05-30T20:23:25.000Z
2022-03-23T12:52:15.000Z
insights/parsers/systemd/unitfiles.py
haithcockce/insights-core
b2e197c6bfc25bcbe2926f07c35a80f2cf8232f5
[ "Apache-2.0" ]
1,977
2017-05-26T14:36:03.000Z
2022-03-31T10:38:53.000Z
insights/parsers/systemd/unitfiles.py
haithcockce/insights-core
b2e197c6bfc25bcbe2926f07c35a80f2cf8232f5
[ "Apache-2.0" ]
244
2017-05-30T20:22:57.000Z
2022-03-26T10:09:39.000Z
""" Units Manged By Systemctl (services) ==================================== Parsers included in this module are: ListUnits - command ``/bin/systemctl list-units`` ------------------------------------------------- UnitFiles - command ``/bin/systemctl list-unit-files`` ------------------------------------------------------ """ from .. import get_active_lines from ... import Parser, parser from insights.specs import Specs from insights.parsers import SkipException @parser(Specs.systemctl_list_unit_files) class UnitFiles(Parser): """ The UnitFiles class parses the output of ``/bin/systemctl list-unit-files`` and provides information about enabled services. Output of Command:: UNIT FILE STATE mariadb.service enabled neutron-openvswitch-agent.service enabled neutron-ovs-cleanup.service enabled neutron-server.service enabled runlevel0.target disabled runlevel1.target disabled runlevel2.target enabled Raises: SkipException: When nothing is parsed. Example: >>> conf.is_on('mariadb.service') True >>> conf.is_on('runlevel0.target') False >>> conf.exists('neutron-server.service') True >>> conf.exists('runlevel1.target') True >>> 'mariadb.service' in conf.services True >>> 'runlevel0.target' in conf.services True >>> 'nonexistent-service.service' in conf.services False >>> conf.services['mariadb.service'] True >>> conf.services['runlevel1.target'] False >>> conf.services['nonexistent-service.service'] Traceback (most recent call last): File "<doctest insights.parsers.systemd.unitfiles.UnitFiles[11]>", line 1, in <module> conf.services['nonexistent-service.service'] KeyError: 'nonexistent-service.service' """ def __init__(self, *args, **kwargs): self.services = {} """dict: Dictionary of bool indicating if service is enabled, access by service name .""" self.service_list = [] """list: List of service names in order of appearance.""" self.parsed_lines = {} """dict: Dictionary of content lines access by service name.""" super(UnitFiles, self).__init__(*args, **kwargs) def parse_content(self, content): """ Main parsing class method which stores all interesting data from the content. Args: content (context.content): Parser context content """ # 'static' means 'on' to fulfill dependency of something else that is on # man systemctl - "is-enabled" knows these states valid_states = set(['enabled', 'enabled-runtime', 'linked', 'linked-runtime', 'masked', 'masked-runtime', 'static', 'indirect', 'disabled', 'generated', 'transient', 'bad', 'invalid']) # man systemctl - "is-enabled" considers these to be enabled on_states = set(['enabled', 'enabled-runtime', 'static', 'indirect', 'generated', 'transient']) for line in get_active_lines(content): parts = line.split(None) # AWK like split, strips whitespaces if len(parts) == 2 and any(part in valid_states for part in parts): service, state = parts enabled = state in on_states self.services[service] = enabled self.parsed_lines[service] = line self.service_list.append(service) if not self.services: raise SkipException def is_on(self, service_name): """ Checks if the service is enabled in systemctl. Args: service_name (str): service name including '.service' Returns: Union[bool, None]: True if service is enabled, False if it is disabled. None if the service doesn't exist. """ return self.services.get(service_name, None) def exists(self, service_name): """ Checks if the service is listed in systemctl. Args: service_name (str): service name including '.service' Returns: bool: True if service exists, False otherwise. """ return service_name in self.service_list @parser(Specs.systemctl_list_units) class ListUnits(Parser): """ The ListUnits class parses the output of ``/bin/systemctl list-units`` and provides information about all the services listed under it. Output of Command:: UNIT LOAD ACTIVE SUB DESCRIPTION sockets.target loaded active active Sockets swap.target loaded active active Swap systemd-shutdownd.socket loaded active listening Delayed Shutdown Socket neutron-dhcp-agent.service loaded active running OpenStack Neutron DHCP Agent neutron-openvswitch-agent.service loaded active running OpenStack Neutron Open vSwitch Agent ... unbound-anchor.timer loaded active waiting daily update of the root trust anchor for DNSSEC LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 161 loaded units listed. Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files'. Raises: SkipException: When nothing is parsed. Example: >>> units.get_service_details('swap.target') == {'LOAD': 'loaded', 'ACTIVE': 'active', 'SUB': 'active', 'UNIT': 'swap.target', 'DESCRIPTION': 'Swap'} True >>> units.unit_list['swap.target'] == {'LOAD': 'loaded', 'ACTIVE': 'active', 'SUB': 'active', 'UNIT': 'swap.target', 'DESCRIPTION': 'Swap'} True >>> units.is_active('swap.target') True >>> units.get_service_details('random.service') == {'LOAD': None, 'ACTIVE': None, 'SUB': None, 'UNIT': None, 'DESCRIPTION': None} True """ EMPTY_DETAILS = {'LOAD': None, 'ACTIVE': None, 'SUB': None, 'UNIT': None, 'DESCRIPTION': None} def __init__(self, *args, **kwargs): self.unit_list = {} """dict: Dictionary service detail like active, running, exited, dead""" super(ListUnits, self).__init__(*args, **kwargs) def parse_service_details(self, parts): # man systemctl - "is-enabled" knows these states valid_states = set(['invalid', 'loaded', 'inactive', 'active', 'exited', 'running', 'failed', 'mounted', 'waiting', 'plugged']) valid_units = set(['service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer', 'slice', 'scope']) service_details = {} if (len(parts) >= 4 and any(part in valid_states for part in parts) and any(unit in parts[0] for unit in valid_units)): service_details['UNIT'] = parts[0] service_details['LOAD'] = parts[1] service_details['ACTIVE'] = parts[2] service_details['SUB'] = parts[3] service_details['DESCRIPTION'] = ' '.join(parts[4:]) if len(parts) > 4 else None return service_details def parse_content(self, content): """ Main parsing class method which stores all interesting data from the content. Args: content (context.content): Parser context content """ BULLET_CHAR_U = u'\u25CF' BULLET_CHAR_B = b"\xe2\x97\x8f" for line in get_active_lines(content): # If this is a heading line, then ignore this line if line.startswith('UNIT '): continue parts = line.split(None) # AWK like split, strips whitespaces first_part = 0 if parts[0] == BULLET_CHAR_U or parts[0].encode('utf-8') == BULLET_CHAR_B or parts[0] == '*': first_part = 1 # If past the end of the list then quit if parts[first_part] in ['LOAD', 'ACTIVE', 'SUB']: break service_details = self.parse_service_details(parts[first_part:]) if service_details: self.unit_list[parts[first_part]] = service_details if not self.unit_list: raise SkipException def get_service_details(self, service_name): """ Return the service details collected by systemctl. Args: service_name (str): service name including its extension. Returns: dict: Dictionary containing details for the service. if service is not present dictonary values will be `None`:: {'LOAD': 'loaded', 'ACTIVE': 'active', 'SUB': 'running', 'UNIT': 'neutron-dhcp-agent.service'} """ return self.unit_list.get(service_name, ListUnits.EMPTY_DETAILS) def is_loaded(self, service_name): """ Return the LOAD state of service managed by systemd. Args: service_name (str): service name including its extension. Returns: bool: True if service is loaded False if not loaded """ return self.get_service_details(service_name)['LOAD'] == 'loaded' def is_active(self, service_name): """ Return the ACTIVE state of service managed by systemd. Args: service_name (str): service name including its extension. Returns: bool: True if service is active False if inactive """ return self.get_service_details(service_name)['ACTIVE'] == 'active' def is_running(self, service_name): """ Return the SUB state of service managed by systemd. Args: service_name (str): service name including its extension. Returns: bool: True if service is running False in all other states. """ return self.get_service_details(service_name)['SUB'] == 'running' def is_failed(self, service_name): """ Return the ACTIVE state of service managed by systemd. Args: service_name (str): service name including its extension. Returns: bool: True if service is failed, False in all other states. """ return self.get_service_details(service_name)['ACTIVE'] == 'failed' @property def service_names(self): """list: Returns a list of all UNIT names.""" return list(self.unit_list.keys())
37.745704
157
0.584578
from .. import get_active_lines from ... import Parser, parser from insights.specs import Specs from insights.parsers import SkipException @parser(Specs.systemctl_list_unit_files) class UnitFiles(Parser): def __init__(self, *args, **kwargs): self.services = {} self.service_list = [] self.parsed_lines = {} super(UnitFiles, self).__init__(*args, **kwargs) def parse_content(self, content): valid_states = set(['enabled', 'enabled-runtime', 'linked', 'linked-runtime', 'masked', 'masked-runtime', 'static', 'indirect', 'disabled', 'generated', 'transient', 'bad', 'invalid']) on_states = set(['enabled', 'enabled-runtime', 'static', 'indirect', 'generated', 'transient']) for line in get_active_lines(content): parts = line.split(None) if len(parts) == 2 and any(part in valid_states for part in parts): service, state = parts enabled = state in on_states self.services[service] = enabled self.parsed_lines[service] = line self.service_list.append(service) if not self.services: raise SkipException def is_on(self, service_name): return self.services.get(service_name, None) def exists(self, service_name): return service_name in self.service_list @parser(Specs.systemctl_list_units) class ListUnits(Parser): EMPTY_DETAILS = {'LOAD': None, 'ACTIVE': None, 'SUB': None, 'UNIT': None, 'DESCRIPTION': None} def __init__(self, *args, **kwargs): self.unit_list = {} super(ListUnits, self).__init__(*args, **kwargs) def parse_service_details(self, parts): valid_states = set(['invalid', 'loaded', 'inactive', 'active', 'exited', 'running', 'failed', 'mounted', 'waiting', 'plugged']) valid_units = set(['service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer', 'slice', 'scope']) service_details = {} if (len(parts) >= 4 and any(part in valid_states for part in parts) and any(unit in parts[0] for unit in valid_units)): service_details['UNIT'] = parts[0] service_details['LOAD'] = parts[1] service_details['ACTIVE'] = parts[2] service_details['SUB'] = parts[3] service_details['DESCRIPTION'] = ' '.join(parts[4:]) if len(parts) > 4 else None return service_details def parse_content(self, content): BULLET_CHAR_U = u'\u25CF' BULLET_CHAR_B = b"\xe2\x97\x8f" for line in get_active_lines(content): if line.startswith('UNIT '): continue parts = line.split(None) first_part = 0 if parts[0] == BULLET_CHAR_U or parts[0].encode('utf-8') == BULLET_CHAR_B or parts[0] == '*': first_part = 1 if parts[first_part] in ['LOAD', 'ACTIVE', 'SUB']: break service_details = self.parse_service_details(parts[first_part:]) if service_details: self.unit_list[parts[first_part]] = service_details if not self.unit_list: raise SkipException def get_service_details(self, service_name): return self.unit_list.get(service_name, ListUnits.EMPTY_DETAILS) def is_loaded(self, service_name): return self.get_service_details(service_name)['LOAD'] == 'loaded' def is_active(self, service_name): return self.get_service_details(service_name)['ACTIVE'] == 'active' def is_running(self, service_name): return self.get_service_details(service_name)['SUB'] == 'running' def is_failed(self, service_name): return self.get_service_details(service_name)['ACTIVE'] == 'failed' @property def service_names(self): return list(self.unit_list.keys())
true
true
f72a681dedfbe58c031e09445ad13611853eefec
5,987
py
Python
tests/test_public_client.py
shanefontaine/ethfinex-python
a883eb8e72d1c87156db62adbc5f95bb82fa5371
[ "MIT" ]
7
2018-12-25T09:55:40.000Z
2021-05-14T04:23:44.000Z
tests/test_public_client.py
shanefontaine/ethfinex-python
a883eb8e72d1c87156db62adbc5f95bb82fa5371
[ "MIT" ]
4
2019-03-08T09:37:35.000Z
2021-06-01T23:12:31.000Z
tests/test_public_client.py
shanefontaine/ethfinex-python
a883eb8e72d1c87156db62adbc5f95bb82fa5371
[ "MIT" ]
1
2021-04-24T01:11:01.000Z
2021-04-24T01:11:01.000Z
import pytest import time from ethfinex.public_client import PublicClient @pytest.fixture(scope='module') def client(): return PublicClient() @pytest.mark.usefixtures('client') class TestPublicClient(object): @staticmethod def teardown_method(): time.sleep(.5) # Avoid rate limit def test_get_platform_status(self, client): r = client.get_platform_status() assert type(r) is list @pytest.mark.parametrize('pair', ['tBTCUSD', 'tETHBTC']) def test_get_ticker(self, client, pair): r = client.get_ticker(pair) assert type(r) is list assert len(r) is 10 @pytest.mark.parametrize('pair, limit, start, end, sort', [ ('tBTCUSD', 120, None, None, 0), ('tBTCUSD', 120, 1514764800000, 1514765700000, 0), ('tBTCUSD', None, None, None, None), ('tBTCUSD', 10, 1514764800000, 1514765700000, 0), ('tBTCUSD', 10, 1514764800000, 1514768400000, 0), ('tBTCUSD', 10, 1514764800000, 1514768400000, 1), pytest.param('tBTCUSD', 10, 1514765700000, 1514764800000, 1, marks=pytest.mark.xfail) ]) def test_get_trades(self, client, pair, limit, start, end, sort): r = client.get_trades(pair, limit, start, end, sort) limit = 120 if not limit else limit # Check length assert len(r) == limit # Check timestamps if start and end: for entry in r: timestamp = entry[1] assert start <= timestamp <= end # Check sort if sort == 1: assert r[0][1] <= r[1][1] else: assert r[0][1] >= r[1][1] @pytest.mark.parametrize('pair, precision, length', [ ('tBTCUSD', 'P0', None), ('tBTCUSD', 'P0', 25), ('tBTCUSD', 'P0', 100), ('tBTCUSD', 'P4', None), ('tBTCUSD', 'P1', 25), ('tBTCUSD', 'P2', 25), pytest.param('tBTCUSD', 'P2', 5, marks=pytest.mark.xfail), pytest.param('tBTCUSD', None, 5, marks=pytest.mark.xfail), ]) def test_get_books(self, client, pair, precision, length): r = client.get_books(pair, precision, length) # Default length is 50. Returns double the amount length = 50 if not length else length * 2 # Check length assert len(r) == length # Check Precision price = str(r[0][0]) if precision == 'P0': digits = len(price.split(".")) # Will return either a whole number or a single decimal assert (digits == 1 or digits == 2) elif precision == 'P1': assert len(price) == 4 elif precision == 'P2': assert len(price) == 4 assert price[-1] == '0' elif precision == 'P3': assert len(price) == 4 assert price[-1] == '0' assert price[-2] == '0' elif precision == 'P4': assert len(price) == 4 assert price[-1] == '0' assert price[-2] == '0' assert price[-3] == '0' elif precision == 'R0': assert len(price == 11) @pytest.mark.parametrize('symbol, key, side, section, sort', [ ('fUSD', 'funding.size', 'long', 'hist', 0), ('fUSD', 'credits.size', 'long', 'hist', 0), # TODO: Figure out credits.size.sym # TODO: Figure out pos.size ('fUSD', 'funding.size', 'long', 'last', 0), ('fUSD', 'funding.size', 'long', 'last', 1), ('fUSD', 'credits.size', 'long', 'last', 1), pytest.param(None, None, None, None, None, marks=pytest.mark.xfail) ]) def test_get_stats(self, client, symbol, key, side, section, sort): r = client.get_stats(symbol, key, side, section, sort) # Check length if section == 'hist': assert len(r) == 120 elif section == 'last': assert len(r) == 2 # Check sort. There is no `section == 'last'` because you cannot sort # a single entry if sort == 1 and section == 'hist': assert r[0][0] <= r[1][0] elif sort != 1 and section == 'hist': assert r[0][0] >= r[1][0] @pytest.mark.parametrize('symbol, time_frame, section, limit, start, end, sort', [ ('tBTCUSD', '1m', 'hist', None, None, None, None), ('tBTCUSD', '15m', 'hist', 1, None, None, None), ('tBTCUSD', '15m', 'hist', 1, None, None, 1), ('tBTCUSD', '15m', 'hist', 1, 1514764800000, 1514765700000, 1), ('tBTCUSD', '15m', 'hist', 1, 1514764800000, 1514768400000, 1), ('tBTCUSD', '1m', 'last', None, None, None, None), ('tBTCUSD', '15m', 'last', 1, 1514764800000, 1514768400000, 1), ('tBTCUSD', '1m', 'last', 1, 1514768400000, 1514764800000, 1), pytest.param(None, None, None, None, None, None, None, marks=pytest.mark.xfail), pytest.param('tBTCUSD', '1m', 'hist', 1, 1514768400000, 1514764800000, 1, marks=pytest.mark.xfail) ]) def test_get_candles(self, client, symbol, time_frame, section, limit, start, end, sort): r = client.get_candles(symbol, time_frame, section, limit, start, end, sort) # Check length if section == 'hist' and limit != 1: assert len(r) == 120 elif section == 'hist' and limit == 1: assert len(r) == 1 elif section == 'last' and limit == 1: assert len(r) == 6 elif section == 'last' and limit == 1: assert len(r) == 1 # Check sort. There is no `section == 'last'` because you cannot sort # a single entry if sort == 1 and section == 'hist' and limit != 1: assert r[0][0] <= r[1][0] elif sort != 1 and section == 'hist' and limit != 1: assert r[0][0] >= r[1][0]
36.730061
86
0.525639
import pytest import time from ethfinex.public_client import PublicClient @pytest.fixture(scope='module') def client(): return PublicClient() @pytest.mark.usefixtures('client') class TestPublicClient(object): @staticmethod def teardown_method(): time.sleep(.5) def test_get_platform_status(self, client): r = client.get_platform_status() assert type(r) is list @pytest.mark.parametrize('pair', ['tBTCUSD', 'tETHBTC']) def test_get_ticker(self, client, pair): r = client.get_ticker(pair) assert type(r) is list assert len(r) is 10 @pytest.mark.parametrize('pair, limit, start, end, sort', [ ('tBTCUSD', 120, None, None, 0), ('tBTCUSD', 120, 1514764800000, 1514765700000, 0), ('tBTCUSD', None, None, None, None), ('tBTCUSD', 10, 1514764800000, 1514765700000, 0), ('tBTCUSD', 10, 1514764800000, 1514768400000, 0), ('tBTCUSD', 10, 1514764800000, 1514768400000, 1), pytest.param('tBTCUSD', 10, 1514765700000, 1514764800000, 1, marks=pytest.mark.xfail) ]) def test_get_trades(self, client, pair, limit, start, end, sort): r = client.get_trades(pair, limit, start, end, sort) limit = 120 if not limit else limit assert len(r) == limit if start and end: for entry in r: timestamp = entry[1] assert start <= timestamp <= end if sort == 1: assert r[0][1] <= r[1][1] else: assert r[0][1] >= r[1][1] @pytest.mark.parametrize('pair, precision, length', [ ('tBTCUSD', 'P0', None), ('tBTCUSD', 'P0', 25), ('tBTCUSD', 'P0', 100), ('tBTCUSD', 'P4', None), ('tBTCUSD', 'P1', 25), ('tBTCUSD', 'P2', 25), pytest.param('tBTCUSD', 'P2', 5, marks=pytest.mark.xfail), pytest.param('tBTCUSD', None, 5, marks=pytest.mark.xfail), ]) def test_get_books(self, client, pair, precision, length): r = client.get_books(pair, precision, length) length = 50 if not length else length * 2 assert len(r) == length price = str(r[0][0]) if precision == 'P0': digits = len(price.split(".")) assert (digits == 1 or digits == 2) elif precision == 'P1': assert len(price) == 4 elif precision == 'P2': assert len(price) == 4 assert price[-1] == '0' elif precision == 'P3': assert len(price) == 4 assert price[-1] == '0' assert price[-2] == '0' elif precision == 'P4': assert len(price) == 4 assert price[-1] == '0' assert price[-2] == '0' assert price[-3] == '0' elif precision == 'R0': assert len(price == 11) @pytest.mark.parametrize('symbol, key, side, section, sort', [ ('fUSD', 'funding.size', 'long', 'hist', 0), ('fUSD', 'credits.size', 'long', 'hist', 0), ('fUSD', 'funding.size', 'long', 'last', 0), ('fUSD', 'funding.size', 'long', 'last', 1), ('fUSD', 'credits.size', 'long', 'last', 1), pytest.param(None, None, None, None, None, marks=pytest.mark.xfail) ]) def test_get_stats(self, client, symbol, key, side, section, sort): r = client.get_stats(symbol, key, side, section, sort) if section == 'hist': assert len(r) == 120 elif section == 'last': assert len(r) == 2 if sort == 1 and section == 'hist': assert r[0][0] <= r[1][0] elif sort != 1 and section == 'hist': assert r[0][0] >= r[1][0] @pytest.mark.parametrize('symbol, time_frame, section, limit, start, end, sort', [ ('tBTCUSD', '1m', 'hist', None, None, None, None), ('tBTCUSD', '15m', 'hist', 1, None, None, None), ('tBTCUSD', '15m', 'hist', 1, None, None, 1), ('tBTCUSD', '15m', 'hist', 1, 1514764800000, 1514765700000, 1), ('tBTCUSD', '15m', 'hist', 1, 1514764800000, 1514768400000, 1), ('tBTCUSD', '1m', 'last', None, None, None, None), ('tBTCUSD', '15m', 'last', 1, 1514764800000, 1514768400000, 1), ('tBTCUSD', '1m', 'last', 1, 1514768400000, 1514764800000, 1), pytest.param(None, None, None, None, None, None, None, marks=pytest.mark.xfail), pytest.param('tBTCUSD', '1m', 'hist', 1, 1514768400000, 1514764800000, 1, marks=pytest.mark.xfail) ]) def test_get_candles(self, client, symbol, time_frame, section, limit, start, end, sort): r = client.get_candles(symbol, time_frame, section, limit, start, end, sort) if section == 'hist' and limit != 1: assert len(r) == 120 elif section == 'hist' and limit == 1: assert len(r) == 1 elif section == 'last' and limit == 1: assert len(r) == 6 elif section == 'last' and limit == 1: assert len(r) == 1 if sort == 1 and section == 'hist' and limit != 1: assert r[0][0] <= r[1][0] elif sort != 1 and section == 'hist' and limit != 1: assert r[0][0] >= r[1][0]
true
true
f72a687a337167c96e7903a7bdd07f5ced99b8a8
3,743
py
Python
src/federatedid/federated.py
dawidkski/federated-faceid
95b1f4b7da0e8baf1cac35edf3b49528c650c491
[ "MIT" ]
1
2021-12-23T14:00:36.000Z
2021-12-23T14:00:36.000Z
src/federatedid/federated.py
dawidkski/federated-faceid
95b1f4b7da0e8baf1cac35edf3b49528c650c491
[ "MIT" ]
6
2021-01-12T13:40:31.000Z
2022-03-12T00:31:27.000Z
src/federatedid/federated.py
d-kicinski/federated-faceid
95b1f4b7da0e8baf1cac35edf3b49528c650c491
[ "MIT" ]
1
2020-05-12T03:11:07.000Z
2020-05-12T03:11:07.000Z
import copy from dataclasses import dataclass from typing import List, Optional import torch from torch.nn import CrossEntropyLoss, Module from torch.utils.data import DataLoader def federated_averaging(models: List[Module]) -> Module: global_model = copy.deepcopy(models[0]) global_weights = global_model.state_dict() local_weights = [m.state_dict() for m in models] for k in global_weights.keys(): for i in range(1, len(local_weights)): global_weights[k] += local_weights[i][k] global_weights[k] = torch.div(global_weights[k], len(local_weights)) global_model.load_state_dict(global_weights) return global_model class ModelAccumulator: def __init__(self): self.model_counter: int = 0 self.global_model = None self.global_weights = None def update(self, model): local_weights = model.state_dict() if self.global_model is None: self.global_model = model self.global_weights = local_weights self.model_counter += 1 else: for k in self.global_weights.keys(): self.global_weights[k] += local_weights[k] self.model_counter += 1 def get(self): for k in self.global_weights.keys(): self.global_weights[k] = torch.div( self.global_weights[k], self.model_counter ) self.global_model.load_state_dict(self.global_weights) return self.global_model def reset(self): self.global_model = None self.global_weights = None self.model_counter = 0 @dataclass class EdgeDeviceSettings: batch_size: int epochs: int learning_rate: float learning_rate_decay: float device: str @dataclass class TrainingResult: loss: float steps: int learning_rate: float class EdgeDevice: def __init__( self, device_id: int, settings: EdgeDeviceSettings, data_loader: DataLoader ): self.device_id = device_id self._data_loader = data_loader self.setting = copy.deepcopy(settings) self._loss_func = CrossEntropyLoss() self._model: Optional[Module] = None def download(self, model: Module): self._model = copy.deepcopy(model) def upload(self) -> Module: if self._model is not None: return copy.deepcopy(self._model) else: raise ValueError("Model not found on this device!") def train(self) -> TrainingResult: if self._data_loader is None: raise ValueError("Dataset not found on this device!") self._model.train() self.setting.learning_rate = ( self.setting.learning_rate * self.setting.learning_rate_decay ) optimizer = torch.optim.SGD( params=self._model.parameters(), lr=self.setting.learning_rate ) epoch_loss = [] local_steps: int = 0 for _ in range(self.setting.epochs): batch_loss = [] for i_batch, (images, labels) in enumerate(self._data_loader): self._model.zero_grad() images = images.to(self.setting.device) labels = labels.to(self.setting.device) logits = self._model(images) loss = self._loss_func(logits, labels) loss.backward() optimizer.step() local_steps += 1 batch_loss.append(loss.item()) epoch_loss.append(sum(batch_loss) / len(batch_loss)) mean_loss = sum(epoch_loss) / len(epoch_loss) return TrainingResult( loss=mean_loss, steps=local_steps, learning_rate=self.setting.learning_rate )
29.944
87
0.627304
import copy from dataclasses import dataclass from typing import List, Optional import torch from torch.nn import CrossEntropyLoss, Module from torch.utils.data import DataLoader def federated_averaging(models: List[Module]) -> Module: global_model = copy.deepcopy(models[0]) global_weights = global_model.state_dict() local_weights = [m.state_dict() for m in models] for k in global_weights.keys(): for i in range(1, len(local_weights)): global_weights[k] += local_weights[i][k] global_weights[k] = torch.div(global_weights[k], len(local_weights)) global_model.load_state_dict(global_weights) return global_model class ModelAccumulator: def __init__(self): self.model_counter: int = 0 self.global_model = None self.global_weights = None def update(self, model): local_weights = model.state_dict() if self.global_model is None: self.global_model = model self.global_weights = local_weights self.model_counter += 1 else: for k in self.global_weights.keys(): self.global_weights[k] += local_weights[k] self.model_counter += 1 def get(self): for k in self.global_weights.keys(): self.global_weights[k] = torch.div( self.global_weights[k], self.model_counter ) self.global_model.load_state_dict(self.global_weights) return self.global_model def reset(self): self.global_model = None self.global_weights = None self.model_counter = 0 @dataclass class EdgeDeviceSettings: batch_size: int epochs: int learning_rate: float learning_rate_decay: float device: str @dataclass class TrainingResult: loss: float steps: int learning_rate: float class EdgeDevice: def __init__( self, device_id: int, settings: EdgeDeviceSettings, data_loader: DataLoader ): self.device_id = device_id self._data_loader = data_loader self.setting = copy.deepcopy(settings) self._loss_func = CrossEntropyLoss() self._model: Optional[Module] = None def download(self, model: Module): self._model = copy.deepcopy(model) def upload(self) -> Module: if self._model is not None: return copy.deepcopy(self._model) else: raise ValueError("Model not found on this device!") def train(self) -> TrainingResult: if self._data_loader is None: raise ValueError("Dataset not found on this device!") self._model.train() self.setting.learning_rate = ( self.setting.learning_rate * self.setting.learning_rate_decay ) optimizer = torch.optim.SGD( params=self._model.parameters(), lr=self.setting.learning_rate ) epoch_loss = [] local_steps: int = 0 for _ in range(self.setting.epochs): batch_loss = [] for i_batch, (images, labels) in enumerate(self._data_loader): self._model.zero_grad() images = images.to(self.setting.device) labels = labels.to(self.setting.device) logits = self._model(images) loss = self._loss_func(logits, labels) loss.backward() optimizer.step() local_steps += 1 batch_loss.append(loss.item()) epoch_loss.append(sum(batch_loss) / len(batch_loss)) mean_loss = sum(epoch_loss) / len(epoch_loss) return TrainingResult( loss=mean_loss, steps=local_steps, learning_rate=self.setting.learning_rate )
true
true
f72a688feda53838c2dd09e2907fbb42d5bc0c1c
1,667
py
Python
tests/bugs/core_3474_test.py
reevespaul/firebird-qa
98f16f425aa9ab8ee63b86172f959d63a2d76f21
[ "MIT" ]
null
null
null
tests/bugs/core_3474_test.py
reevespaul/firebird-qa
98f16f425aa9ab8ee63b86172f959d63a2d76f21
[ "MIT" ]
null
null
null
tests/bugs/core_3474_test.py
reevespaul/firebird-qa
98f16f425aa9ab8ee63b86172f959d63a2d76f21
[ "MIT" ]
null
null
null
#coding:utf-8 # # id: bugs.core_3474 # title: Regression in joins on procedures # decription: # tracker_id: CORE-3474 # min_versions: ['2.5.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0 # resources: None substitutions_1 = [('-At line.*', '')] init_script_1 = """""" db_1 = db_factory(from_backup='employee-ods12.fbk', init=init_script_1) test_script_1 = """ set list on; select e.emp_no emp_1, e.last_name name_1, p.proj_name proj_1 from employee e left join ( get_emp_proj(e.emp_no) proc join project p on p.proj_id = proc.proj_id ) on 1=1 order by 1,2,3 rows 1; select e.emp_no emp_2, e.last_name name_2, p.proj_name proj_2 from ( employee e left join get_emp_proj(e.emp_no) proc on 1=1 ) left join project p on p.proj_id = proc.proj_id order by 1,2,3 rows 1; """ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ EMP_2 2 NAME_2 Nelson PROJ_2 <null> """ expected_stderr_1 = """ Statement failed, SQLSTATE = 42S22 Dynamic SQL Error -SQL error code = -206 -Column unknown -E.EMP_NO """ @pytest.mark.version('>=3.0') def test_1(act_1: Action): act_1.expected_stdout = expected_stdout_1 act_1.expected_stderr = expected_stderr_1 act_1.execute() assert act_1.clean_expected_stderr == act_1.clean_stderr assert act_1.clean_expected_stdout == act_1.clean_stdout
24.514706
71
0.617277
import pytest from firebird.qa import db_factory, isql_act, Action substitutions_1 = [('-At line.*', '')] init_script_1 = """""" db_1 = db_factory(from_backup='employee-ods12.fbk', init=init_script_1) test_script_1 = """ set list on; select e.emp_no emp_1, e.last_name name_1, p.proj_name proj_1 from employee e left join ( get_emp_proj(e.emp_no) proc join project p on p.proj_id = proc.proj_id ) on 1=1 order by 1,2,3 rows 1; select e.emp_no emp_2, e.last_name name_2, p.proj_name proj_2 from ( employee e left join get_emp_proj(e.emp_no) proc on 1=1 ) left join project p on p.proj_id = proc.proj_id order by 1,2,3 rows 1; """ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ EMP_2 2 NAME_2 Nelson PROJ_2 <null> """ expected_stderr_1 = """ Statement failed, SQLSTATE = 42S22 Dynamic SQL Error -SQL error code = -206 -Column unknown -E.EMP_NO """ @pytest.mark.version('>=3.0') def test_1(act_1: Action): act_1.expected_stdout = expected_stdout_1 act_1.expected_stderr = expected_stderr_1 act_1.execute() assert act_1.clean_expected_stderr == act_1.clean_stderr assert act_1.clean_expected_stdout == act_1.clean_stdout
true
true
f72a6990f0aad8249f5dc016a2590edf77f57c03
4,224
py
Python
mainapp/controllers/forms.py
fabiocostapro/fiberappz
da73569fa03e0b731b5ec2c96a0ee668f8b10ef6
[ "MIT" ]
null
null
null
mainapp/controllers/forms.py
fabiocostapro/fiberappz
da73569fa03e0b731b5ec2c96a0ee668f8b10ef6
[ "MIT" ]
null
null
null
mainapp/controllers/forms.py
fabiocostapro/fiberappz
da73569fa03e0b731b5ec2c96a0ee668f8b10ef6
[ "MIT" ]
null
null
null
from wtforms import Form from wtforms import StringField, PasswordField from wtforms.fields.html5 import EmailField from wtforms import validators from mainapp.models.tables import User class UserCreateForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) name = StringField("Nome", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) cpf = StringField("Cpf", [ ]) company = StringField("Company", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) cnpj = StringField("Cnpj", [ ]) email = EmailField("E-mail", [ validators.Required(message="Preenchimento obrigatório"), validators.Email(message="Preenchimento inválido") ]) password = PasswordField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=6, max=15, message="Mínimo de 6 e máximo de 15 caracteres") ]) def validate_username(form, field): username = field.data user = User.query.filter_by(username=username).first() if user is not None: raise validators.ValidationError("Usuário já cadastrado!") class OltCreateForm(Form): name = StringField("Nome", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) ip = StringField("Ip", [ ]) port = StringField("Porta", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=3, max=5, message="Mínimo de 3 e máximo de 5 caracteres") ]) login = StringField("Login", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) password = StringField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) class UserReadForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) class LoginForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) password = PasswordField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=6, max=15, message="Mínimo de 6 e máximo de 15 caracteres") ])
45.419355
114
0.482244
from wtforms import Form from wtforms import StringField, PasswordField from wtforms.fields.html5 import EmailField from wtforms import validators from mainapp.models.tables import User class UserCreateForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) name = StringField("Nome", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) cpf = StringField("Cpf", [ ]) company = StringField("Company", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) cnpj = StringField("Cnpj", [ ]) email = EmailField("E-mail", [ validators.Required(message="Preenchimento obrigatório"), validators.Email(message="Preenchimento inválido") ]) password = PasswordField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=6, max=15, message="Mínimo de 6 e máximo de 15 caracteres") ]) def validate_username(form, field): username = field.data user = User.query.filter_by(username=username).first() if user is not None: raise validators.ValidationError("Usuário já cadastrado!") class OltCreateForm(Form): name = StringField("Nome", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) ip = StringField("Ip", [ ]) port = StringField("Porta", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=3, max=5, message="Mínimo de 3 e máximo de 5 caracteres") ]) login = StringField("Login", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) password = StringField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) class UserReadForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) class LoginForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) password = PasswordField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=6, max=15, message="Mínimo de 6 e máximo de 15 caracteres") ])
true
true
f72a6add468392d9b7eca586307a71cb8213bc22
10,197
py
Python
api/team/tests/test_update.py
BerniWittmann/beachanmeldung
9014dea5c31ea9e26f18d753d8d836741865c38e
[ "Unlicense", "MIT" ]
null
null
null
api/team/tests/test_update.py
BerniWittmann/beachanmeldung
9014dea5c31ea9e26f18d753d8d836741865c38e
[ "Unlicense", "MIT" ]
5
2020-06-05T17:31:08.000Z
2022-03-11T23:16:12.000Z
api/team/tests/test_update.py
BerniWittmann/beachanmeldung
9014dea5c31ea9e26f18d753d8d836741865c38e
[ "Unlicense", "MIT" ]
null
null
null
import json from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import timezone from django.utils.translation import activate from rest_framework.test import APIClient from rest_framework_jwt.settings import api_settings from api.accounts.models import MyUser from api.team.models import Team from api.tournaments.models import Tournament activate('en-us') jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER token_regex = '^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$' class Teams(TestCase): token = None tournament = None team = None user = None def setUp(self): self.user = MyUser.objects.create_user(email='test@byom.de', first_name='Test', last_name='User', phone='+49192481024') self.user.set_password('test123') self.user.is_verified = True self.user.is_staff = True self.user.save() payload = jwt_payload_handler(self.user) self.token = jwt_encode_handler(payload) self.tournament = Tournament.objects \ .create(name='Test Turnier', gender='mixed', start_date='2017-01-01', end_date='2017-01-02', deadline_signup='2017-01-01T00:00:00Z', deadline_edit=timezone.now() + timezone.timedelta(days=30), advertisement_url='http://www.google.de', contact_email='test@byom.de', starting_fee=60.0, number_of_places=12 ) self.team = Team.objects.create( name='TSV Ismaning', beachname='THC Eh Drin!', tournament=self.tournament, trainer=self.user, ) def test_team_update(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['beachname'], 'New Name Name') self.assertEqual(Team.objects.first().beachname, 'New Name Name') self.assertEqual(data['name'], 'TSV Ismaning 2') self.assertEqual(Team.objects.first().name, 'TSV Ismaning 2') def test_team_update_as_other_trainer(self): other_user = MyUser.objects.create_user(email='newuser@byom.de', first_name='Another', last_name='User', phone='+49192481024') other_user.set_password('test123') other_user.is_verified = True other_user.is_staff = False other_user.save() other_payload = jwt_payload_handler(other_user) other_token = jwt_encode_handler(other_payload) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + other_token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'Bad Name', 'name': 'TSV Ismaning', }) self.assertEqual(response.status_code, 403) def test_team_update_not_update_tournament(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'tournament': 3, }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['tournament']['id'], self.tournament.id) self.assertEqual(Team.objects.first().tournament, self.tournament) def test_team_update_not_update_trainer(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'trainer': 'hacker@dumb.com', }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().trainer, self.user) def test_team_update_not_update_paid(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'paid': True, }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().paid, False) def test_team_update_not_update_state(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'state': 'signed up', }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().state, 'needs approval') def test_team_name_not_unqiue(self): team2 = Team.objects.create( name='TSV Ismaning 2', beachname='THC Eh Drin! 2', tournament=self.tournament, trainer=self.user, ) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': team2.id}), { 'name': 'TSV Ismaning', 'beachname': 'THC Eh Drin!' }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': ['Name already taken'], 'key': ['name_already_taken'] }) self.assertEqual(Team.objects.last().name, team2.name) self.assertEqual(Team.objects.last().beachname, team2.beachname) def test_team_name_not_unqiue_without_beachname(self): team2 = Team.objects.create( name='TSV Ismaning 2', beachname='THC Eh Drin! 2', tournament=self.tournament, trainer=self.user, ) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': team2.id}), { 'name': 'TSV Ismaning', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': ['Name already taken'], 'key': ['name_already_taken'] }) self.assertEqual(Team.objects.last().name, team2.name) self.assertEqual(Team.objects.last().beachname, team2.beachname) def test_team_update_after_deadline_staff(self): self.tournament.deadline_edit = timezone.now() - timezone.timedelta(days=3) self.tournament.save() client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['beachname'], 'New Name Name') self.assertEqual(Team.objects.first().beachname, 'New Name Name') self.assertEqual(data['name'], 'TSV Ismaning 2') self.assertEqual(Team.objects.first().name, 'TSV Ismaning 2') def test_team_update_after_deadline_trainer(self): self.tournament.deadline_edit = timezone.now() - timezone.timedelta(days=3) self.tournament.save() self.user.is_staff = False self.user.save() client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': 'Team Update not possible after Edit-Deadline', 'key': 'after_deadline_edit', }) self.assertNotEqual(Team.objects.first().beachname, 'New Name Name') self.assertNotEqual(Team.objects.first().name, 'TSV Ismaning 2')
44.142857
83
0.531529
import json from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import timezone from django.utils.translation import activate from rest_framework.test import APIClient from rest_framework_jwt.settings import api_settings from api.accounts.models import MyUser from api.team.models import Team from api.tournaments.models import Tournament activate('en-us') jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER token_regex = '^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$' class Teams(TestCase): token = None tournament = None team = None user = None def setUp(self): self.user = MyUser.objects.create_user(email='test@byom.de', first_name='Test', last_name='User', phone='+49192481024') self.user.set_password('test123') self.user.is_verified = True self.user.is_staff = True self.user.save() payload = jwt_payload_handler(self.user) self.token = jwt_encode_handler(payload) self.tournament = Tournament.objects \ .create(name='Test Turnier', gender='mixed', start_date='2017-01-01', end_date='2017-01-02', deadline_signup='2017-01-01T00:00:00Z', deadline_edit=timezone.now() + timezone.timedelta(days=30), advertisement_url='http://www.google.de', contact_email='test@byom.de', starting_fee=60.0, number_of_places=12 ) self.team = Team.objects.create( name='TSV Ismaning', beachname='THC Eh Drin!', tournament=self.tournament, trainer=self.user, ) def test_team_update(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['beachname'], 'New Name Name') self.assertEqual(Team.objects.first().beachname, 'New Name Name') self.assertEqual(data['name'], 'TSV Ismaning 2') self.assertEqual(Team.objects.first().name, 'TSV Ismaning 2') def test_team_update_as_other_trainer(self): other_user = MyUser.objects.create_user(email='newuser@byom.de', first_name='Another', last_name='User', phone='+49192481024') other_user.set_password('test123') other_user.is_verified = True other_user.is_staff = False other_user.save() other_payload = jwt_payload_handler(other_user) other_token = jwt_encode_handler(other_payload) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + other_token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'Bad Name', 'name': 'TSV Ismaning', }) self.assertEqual(response.status_code, 403) def test_team_update_not_update_tournament(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'tournament': 3, }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['tournament']['id'], self.tournament.id) self.assertEqual(Team.objects.first().tournament, self.tournament) def test_team_update_not_update_trainer(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'trainer': 'hacker@dumb.com', }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().trainer, self.user) def test_team_update_not_update_paid(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'paid': True, }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().paid, False) def test_team_update_not_update_state(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'state': 'signed up', }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().state, 'needs approval') def test_team_name_not_unqiue(self): team2 = Team.objects.create( name='TSV Ismaning 2', beachname='THC Eh Drin! 2', tournament=self.tournament, trainer=self.user, ) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': team2.id}), { 'name': 'TSV Ismaning', 'beachname': 'THC Eh Drin!' }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': ['Name already taken'], 'key': ['name_already_taken'] }) self.assertEqual(Team.objects.last().name, team2.name) self.assertEqual(Team.objects.last().beachname, team2.beachname) def test_team_name_not_unqiue_without_beachname(self): team2 = Team.objects.create( name='TSV Ismaning 2', beachname='THC Eh Drin! 2', tournament=self.tournament, trainer=self.user, ) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': team2.id}), { 'name': 'TSV Ismaning', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': ['Name already taken'], 'key': ['name_already_taken'] }) self.assertEqual(Team.objects.last().name, team2.name) self.assertEqual(Team.objects.last().beachname, team2.beachname) def test_team_update_after_deadline_staff(self): self.tournament.deadline_edit = timezone.now() - timezone.timedelta(days=3) self.tournament.save() client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['beachname'], 'New Name Name') self.assertEqual(Team.objects.first().beachname, 'New Name Name') self.assertEqual(data['name'], 'TSV Ismaning 2') self.assertEqual(Team.objects.first().name, 'TSV Ismaning 2') def test_team_update_after_deadline_trainer(self): self.tournament.deadline_edit = timezone.now() - timezone.timedelta(days=3) self.tournament.save() self.user.is_staff = False self.user.save() client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': 'Team Update not possible after Edit-Deadline', 'key': 'after_deadline_edit', }) self.assertNotEqual(Team.objects.first().beachname, 'New Name Name') self.assertNotEqual(Team.objects.first().name, 'TSV Ismaning 2')
true
true
f72a6bc23ff8f5945f5bfef16d9ffa3a49b4878d
2,563
py
Python
setup.py
ianhuang0630/CSQ
5f1fe99a8d9da73692643b3911d675dce269a03d
[ "MIT" ]
98
2019-04-05T08:22:38.000Z
2022-03-29T06:22:17.000Z
setup.py
ianhuang0630/CSQ
5f1fe99a8d9da73692643b3911d675dce269a03d
[ "MIT" ]
19
2019-06-28T20:26:01.000Z
2022-03-03T16:26:57.000Z
setup.py
ianhuang0630/CSQ
5f1fe99a8d9da73692643b3911d675dce269a03d
[ "MIT" ]
26
2019-04-15T00:54:06.000Z
2022-02-22T23:17:24.000Z
"""Setup learnable_primitives""" from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension from itertools import dropwhile import numpy as np from os import path def collect_docstring(lines): """Return document docstring if it exists""" lines = dropwhile(lambda x: not x.startswith('"""'), lines) doc = "" for line in lines: doc += line if doc.endswith('"""\n'): break return doc[3:-4].replace("\r", "").replace("\n", " ") def collect_metadata(): meta = {} with open(path.join("learnable_primitives", "__init__.py")) as f: lines = iter(f) meta["description"] = collect_docstring(lines) for line in lines: if line.startswith("__"): key, value = map(lambda x: x.strip(), line.split("=")) meta[key[2:-2]] = value[1:-1] return meta def get_extensions(): return cythonize([ Extension( "learnable_primitives.fast_sampler._sampler", [ "learnable_primitives/fast_sampler/_sampler.pyx", "learnable_primitives/fast_sampler/sampling.cpp" ], language="c++11", libraries=["stdc++"], include_dirs=[np.get_include()], extra_compile_args=["-std=c++11", "-O3"] ) ]) def get_install_requirements(): return [ "numpy", "scikit-learn", "trimesh==2.38.42", "torch==0.4.1", "torchvision==0.1.8", "progress==1.4", "cython", "Pillow", "pyquaternion", "backports.functools_lru_cache", "sympy", "matplotlib==2.2.4", "seaborn", "mayavi" ] def setup_package(): meta = collect_metadata() setup( name="learnable_primitives", version=meta["version"], maintainer=meta["maintainer"], maintainer_email=meta["email"], url=meta["url"], license=meta["license"], classifiers=[ "Intended Audience :: Science/Research", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", ], install_requires=get_install_requirements(), ext_modules=get_extensions() ) if __name__ == "__main__": setup_package()
26.42268
70
0.55833
from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension from itertools import dropwhile import numpy as np from os import path def collect_docstring(lines): lines = dropwhile(lambda x: not x.startswith('"""'), lines) doc = "" for line in lines: doc += line if doc.endswith('"""\n'): break return doc[3:-4].replace("\r", "").replace("\n", " ") def collect_metadata(): meta = {} with open(path.join("learnable_primitives", "__init__.py")) as f: lines = iter(f) meta["description"] = collect_docstring(lines) for line in lines: if line.startswith("__"): key, value = map(lambda x: x.strip(), line.split("=")) meta[key[2:-2]] = value[1:-1] return meta def get_extensions(): return cythonize([ Extension( "learnable_primitives.fast_sampler._sampler", [ "learnable_primitives/fast_sampler/_sampler.pyx", "learnable_primitives/fast_sampler/sampling.cpp" ], language="c++11", libraries=["stdc++"], include_dirs=[np.get_include()], extra_compile_args=["-std=c++11", "-O3"] ) ]) def get_install_requirements(): return [ "numpy", "scikit-learn", "trimesh==2.38.42", "torch==0.4.1", "torchvision==0.1.8", "progress==1.4", "cython", "Pillow", "pyquaternion", "backports.functools_lru_cache", "sympy", "matplotlib==2.2.4", "seaborn", "mayavi" ] def setup_package(): meta = collect_metadata() setup( name="learnable_primitives", version=meta["version"], maintainer=meta["maintainer"], maintainer_email=meta["email"], url=meta["url"], license=meta["license"], classifiers=[ "Intended Audience :: Science/Research", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", ], install_requires=get_install_requirements(), ext_modules=get_extensions() ) if __name__ == "__main__": setup_package()
true
true
f72a6c18f2dd71bf7e6d4454aa80d63e9fbe8e63
522
py
Python
Season 06 - Files in Python/Episode 12 - Imports Error & running as Python Scripts/Episode 12 - Imports Error & running as Python Scripts.py
Pythobit/Python-tutorial
b0743eaa9c237c3578131ead1b3f2c295f11b7ee
[ "MIT" ]
3
2021-02-19T18:33:00.000Z
2021-08-03T14:56:50.000Z
Season 06 - Files in Python/Episode 12 - Imports Error & running as Python Scripts/Episode 12 - Imports Error & running as Python Scripts.py
barawalojas/Python-tutorial
3f4b2b073e421888b3d62ff634658317d9abcb9b
[ "MIT" ]
1
2021-07-10T14:37:57.000Z
2021-07-20T09:51:39.000Z
Season 06 - Files in Python/Episode 12 - Imports Error & running as Python Scripts/Episode 12 - Imports Error & running as Python Scripts.py
barawalojas/Python-tutorial
3f4b2b073e421888b3d62ff634658317d9abcb9b
[ "MIT" ]
1
2021-08-02T05:39:38.000Z
2021-08-02T05:39:38.000Z
# Imports Error & running as Python Scripts. """ IMPORT ERROR if your module is already imported, you can import it the same way, but if you want to access something inside in it, python will look into the module & give you an error because it's going to be back n forth, called `circular import` [bad thing] """ """ RUNNING AS PYTHON SCRIPTS if you want to run a specific code when you run a specific file, do this if __name__ = '__main__': print(find_in(['Rolf', 'Jose', 'Jen'], lambda x: x, 'Jose')) """
26.1
117
0.701149
true
true