hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 | qsc_code_num_words_quality_signal int64 | qsc_code_num_chars_quality_signal float64 | qsc_code_mean_word_length_quality_signal float64 | qsc_code_frac_words_unique_quality_signal float64 | qsc_code_frac_chars_top_2grams_quality_signal float64 | qsc_code_frac_chars_top_3grams_quality_signal float64 | qsc_code_frac_chars_top_4grams_quality_signal float64 | qsc_code_frac_chars_dupe_5grams_quality_signal float64 | qsc_code_frac_chars_dupe_6grams_quality_signal float64 | qsc_code_frac_chars_dupe_7grams_quality_signal float64 | qsc_code_frac_chars_dupe_8grams_quality_signal float64 | qsc_code_frac_chars_dupe_9grams_quality_signal float64 | qsc_code_frac_chars_dupe_10grams_quality_signal float64 | qsc_code_frac_chars_replacement_symbols_quality_signal float64 | qsc_code_frac_chars_digital_quality_signal float64 | qsc_code_frac_chars_whitespace_quality_signal float64 | qsc_code_size_file_byte_quality_signal float64 | qsc_code_num_lines_quality_signal float64 | qsc_code_num_chars_line_max_quality_signal float64 | qsc_code_num_chars_line_mean_quality_signal float64 | qsc_code_frac_chars_alphabet_quality_signal float64 | qsc_code_frac_chars_comments_quality_signal float64 | qsc_code_cate_xml_start_quality_signal float64 | qsc_code_frac_lines_dupe_lines_quality_signal float64 | qsc_code_cate_autogen_quality_signal float64 | qsc_code_frac_lines_long_string_quality_signal float64 | qsc_code_frac_chars_string_length_quality_signal float64 | qsc_code_frac_chars_long_word_length_quality_signal float64 | qsc_code_frac_lines_string_concat_quality_signal float64 | qsc_code_cate_encoded_data_quality_signal float64 | qsc_code_frac_chars_hex_words_quality_signal float64 | qsc_code_frac_lines_prompt_comments_quality_signal float64 | qsc_code_frac_lines_assert_quality_signal float64 | qsc_codepython_cate_ast_quality_signal float64 | qsc_codepython_frac_lines_func_ratio_quality_signal float64 | qsc_codepython_cate_var_zero_quality_signal bool | qsc_codepython_frac_lines_pass_quality_signal float64 | qsc_codepython_frac_lines_import_quality_signal float64 | qsc_codepython_frac_lines_simplefunc_quality_signal float64 | qsc_codepython_score_lines_no_logic_quality_signal float64 | qsc_codepython_frac_lines_print_quality_signal float64 | qsc_code_num_words int64 | qsc_code_num_chars int64 | qsc_code_mean_word_length int64 | qsc_code_frac_words_unique null | qsc_code_frac_chars_top_2grams int64 | qsc_code_frac_chars_top_3grams int64 | qsc_code_frac_chars_top_4grams int64 | qsc_code_frac_chars_dupe_5grams int64 | qsc_code_frac_chars_dupe_6grams int64 | qsc_code_frac_chars_dupe_7grams int64 | qsc_code_frac_chars_dupe_8grams int64 | qsc_code_frac_chars_dupe_9grams int64 | qsc_code_frac_chars_dupe_10grams int64 | qsc_code_frac_chars_replacement_symbols int64 | qsc_code_frac_chars_digital int64 | qsc_code_frac_chars_whitespace int64 | qsc_code_size_file_byte int64 | qsc_code_num_lines int64 | qsc_code_num_chars_line_max int64 | qsc_code_num_chars_line_mean int64 | qsc_code_frac_chars_alphabet int64 | qsc_code_frac_chars_comments int64 | qsc_code_cate_xml_start int64 | qsc_code_frac_lines_dupe_lines int64 | qsc_code_cate_autogen int64 | qsc_code_frac_lines_long_string int64 | qsc_code_frac_chars_string_length int64 | qsc_code_frac_chars_long_word_length int64 | qsc_code_frac_lines_string_concat null | qsc_code_cate_encoded_data int64 | qsc_code_frac_chars_hex_words int64 | qsc_code_frac_lines_prompt_comments int64 | qsc_code_frac_lines_assert int64 | qsc_codepython_cate_ast int64 | qsc_codepython_frac_lines_func_ratio int64 | qsc_codepython_cate_var_zero int64 | qsc_codepython_frac_lines_pass int64 | qsc_codepython_frac_lines_import int64 | qsc_codepython_frac_lines_simplefunc int64 | qsc_codepython_score_lines_no_logic int64 | qsc_codepython_frac_lines_print int64 | effective string | hits int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5aed88f1f13721ba968b60dc90195f77f82e19b1 | 15,216 | py | Python | tests/test_frame.py | balabit-deps/balabit-os-7-python-lz4 | fab61fdaef68eabee9426c0dd0af41cd59fd9314 | [
"BSD-3-Clause"
] | null | null | null | tests/test_frame.py | balabit-deps/balabit-os-7-python-lz4 | fab61fdaef68eabee9426c0dd0af41cd59fd9314 | [
"BSD-3-Clause"
] | null | null | null | tests/test_frame.py | balabit-deps/balabit-os-7-python-lz4 | fab61fdaef68eabee9426c0dd0af41cd59fd9314 | [
"BSD-3-Clause"
] | null | null | null | import lz4.frame as lz4frame
import unittest
import os
import sys
import struct
from multiprocessing.pool import ThreadPool
class TestLZ4Frame(unittest.TestCase):
def test_create_and_free_compression_context(self):
context = lz4frame.create_compression_context()
self.assertNotEqual(context, None)
def test_compress(self):
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
compressed = lz4frame.compress(input_data)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_begin_update_end(self):
context = lz4frame.create_compression_context()
self.assertNotEqual(context, None)
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
chunk_size = int((len(input_data)/2)+1)
compressed = lz4frame.compress_begin(context)
compressed += lz4frame.compress_update(context, input_data[:chunk_size])
compressed += lz4frame.compress_update(context, input_data[chunk_size:])
compressed += lz4frame.compress_end(context)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_huge_with_size(self):
context = lz4frame.create_compression_context()
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123" * 4096
chunk_size = int((len(input_data)/2)+1)
compressed = lz4frame.compress_begin(context, source_size=len(input_data))
compressed += lz4frame.compress_update(context, input_data[:chunk_size])
compressed += lz4frame.compress_update(context, input_data[chunk_size:])
compressed += lz4frame.compress_end(context)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_huge_without_size(self):
context = lz4frame.create_compression_context()
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123" * 4096
chunk_size = int((len(input_data)/2)+1)
compressed = lz4frame.compress_begin(context)
compressed += lz4frame.compress_update(context, input_data[:chunk_size])
compressed += lz4frame.compress_update(context, input_data[chunk_size:])
compressed += lz4frame.compress_end(context)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_not_defaults_1(self):
input_data = os.urandom(10 * 128 * 1024) # Read 10 * 128kb
compressed = lz4frame.compress(
input_data,
block_size=lz4frame.BLOCKSIZE_MAX256KB,
block_mode=lz4frame.BLOCKMODE_LINKED,
compression_level=lz4frame.COMPRESSIONLEVEL_MAX,
)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_not_defaults_2(self):
input_data = os.urandom(20 * 128 * 1024) # Read 20 * 128kb
compressed = lz4frame.compress(
input_data,
block_size=lz4frame.BLOCKSIZE_MAX1MB,
block_mode=lz4frame.BLOCKMODE_INDEPENDENT,
compression_level=lz4frame.COMPRESSIONLEVEL_MIN,
content_checksum=lz4frame.CONTENTCHECKSUM_DISABLED
)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_not_defaults_3(self):
input_data = os.urandom(20 * 128 * 1024) # Read 20 * 128kb
compressed = lz4frame.compress(
input_data,
block_size=lz4frame.BLOCKSIZE_MAX64KB,
block_mode=lz4frame.BLOCKMODE_LINKED,
compression_level=lz4frame.COMPRESSIONLEVEL_MINHC,
content_checksum=lz4frame.CONTENTCHECKSUM_DISABLED
)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_not_defaults_4(self):
input_data = os.urandom(20 * 128 * 1024) # Read 20 * 128kb
compressed = lz4frame.compress(
input_data,
block_size=lz4frame.BLOCKSIZE_MAX64KB,
block_mode=lz4frame.BLOCKMODE_LINKED,
compression_level=lz4frame.COMPRESSIONLEVEL_MAX,
content_checksum=lz4frame.CONTENTCHECKSUM_ENABLED
)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_begin_update_end_no_auto_flush(self):
context = lz4frame.create_compression_context()
self.assertNotEqual(context, None)
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
chunk_size = int((len(input_data)/2)+1)
compressed = lz4frame.compress_begin(context, auto_flush=0)
compressed += lz4frame.compress_update(context, input_data[:chunk_size])
compressed += lz4frame.compress_update(context, input_data[chunk_size:])
compressed += lz4frame.compress_end(context)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_begin_update_end_no_auto_flush_2(self):
input_data = os.urandom(4 * 128 * 1024) # Read 4 * 128kb
context = lz4frame.create_compression_context()
self.assertNotEqual(context, None)
compressed = lz4frame.compress_begin(context, auto_flush=0)
chunk_size = 32 * 1024 # 32 kb, half of default block size
start = 0
end = start + chunk_size
while start <= len(input_data):
compressed += lz4frame.compress_update(context, input_data[start:end])
start = end
end = start + chunk_size
compressed += lz4frame.compress_end(context)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_begin_update_end_not_defaults(self):
input_data = os.urandom(10 * 128 * 1024) # Read 10 * 128kb
context = lz4frame.create_compression_context()
self.assertNotEqual(context, None)
compressed = lz4frame.compress_begin(
context,
block_size=lz4frame.BLOCKSIZE_MAX256KB,
block_mode=lz4frame.BLOCKMODE_LINKED,
compression_level=lz4frame.COMPRESSIONLEVEL_MINHC,
auto_flush=1
)
chunk_size = 128 * 1024 # 128 kb, half of block size
start = 0
end = start + chunk_size
while start <= len(input_data):
compressed += lz4frame.compress_update(context, input_data[start:end])
start = end
end = start + chunk_size
compressed += lz4frame.compress_end(context)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_begin_update_end_no_auto_flush_not_defaults(self):
input_data = os.urandom(10 * 128 * 1024) # Read 10 * 128kb
context = lz4frame.create_compression_context()
self.assertNotEqual(context, None)
compressed = lz4frame.compress_begin(
context,
block_size=lz4frame.BLOCKSIZE_MAX256KB,
block_mode=lz4frame.BLOCKMODE_LINKED,
compression_level=lz4frame.COMPRESSIONLEVEL_MAX,
auto_flush=0
)
chunk_size = 128 * 1024 # 128 kb, half of block size
start = 0
end = start + chunk_size
while start <= len(input_data):
compressed += lz4frame.compress_update(context, input_data[start:end])
start = end
end = start + chunk_size
compressed += lz4frame.compress_end(context)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_get_frame_info(self):
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
compressed = lz4frame.compress(
input_data,
lz4frame.COMPRESSIONLEVEL_MAX,
lz4frame.BLOCKSIZE_MAX64KB,
lz4frame.CONTENTCHECKSUM_DISABLED,
lz4frame.BLOCKMODE_INDEPENDENT,
lz4frame.FRAMETYPE_FRAME
)
frame_info = lz4frame.get_frame_info(compressed)
self.assertEqual(
frame_info,
{
"blockSizeID":lz4frame.BLOCKSIZE_MAX64KB,
"blockMode":lz4frame.BLOCKMODE_INDEPENDENT,
"contentChecksumFlag":lz4frame.CONTENTCHECKSUM_DISABLED,
"frameType":lz4frame.FRAMETYPE_FRAME,
"contentSize":len(input_data)
}
)
def test_threads(self):
data = [os.urandom(128 * 1024) for i in range(100)]
def roundtrip(x):
return lz4frame.decompress(lz4frame.compress(x))
pool = ThreadPool(8)
out = pool.map(roundtrip, data)
pool.close()
self.assertEqual(data, out)
def test_compress_begin_update_end_no_auto_flush_not_defaults_threaded(self):
data = [os.urandom(3 * 256 * 1024) for i in range(100)]
def roundtrip(x):
context = lz4frame.create_compression_context()
self.assertNotEqual(context, None)
compressed = lz4frame.compress_begin(
context,
block_size=lz4frame.BLOCKSIZE_MAX256KB,
block_mode=lz4frame.BLOCKMODE_LINKED,
compression_level=lz4frame.COMPRESSIONLEVEL_MAX,
auto_flush=0
)
chunk_size = 128 * 1024 # 128 kb, half of block size
start = 0
end = start + chunk_size
while start <= len(x):
compressed += lz4frame.compress_update(context, x[start:end])
start = end
end = start + chunk_size
compressed += lz4frame.compress_end(context)
decompressed = lz4frame.decompress(compressed)
return decompressed
pool = ThreadPool(8)
out = pool.map(roundtrip, data)
pool.close()
self.assertEqual(data, out)
def test_LZ4FrameCompressor(self):
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
with lz4frame.LZ4FrameCompressor() as compressor:
compressed = compressor.compress_begin()
compressed += compressor.compress(input_data)
compressed += compressor.flush()
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_LZ4FrameCompressor_reset(self):
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
with lz4frame.LZ4FrameCompressor() as compressor:
compressed = compressor.compress_begin()
compressed += compressor.compress(input_data)
compressed += compressor.flush()
compressor.reset()
compressed = compressor.compress_begin()
compressed += compressor.compress(input_data)
compressed += compressor.flush()
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
def test_compress_without_content_size(self):
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
compressed = lz4frame.compress(input_data, content_size_header=False)
frame = lz4frame.get_frame_info(compressed)
self.assertEqual(frame['contentSize'], 0)
decompressed = lz4frame.decompress(compressed)
self.assertEqual(input_data, decompressed)
class TestLZ4FrameModern(unittest.TestCase):
def test_decompress_truncated(self):
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
for chksum in (lz4frame.CONTENTCHECKSUM_DISABLED, lz4frame.CONTENTCHECKSUM_ENABLED):
for conlen in (0, len(input_data)):
context = lz4frame.create_compression_context()
compressed = lz4frame.compress_begin(context, content_checksum=chksum, source_size=conlen)
compressed += lz4frame.compress_update(context, input_data)
compressed += lz4frame.compress_end(context)
for i in range(len(compressed)):
with self.assertRaisesRegexp(RuntimeError, r'^(LZ4F_getFrameInfo failed with code: ERROR_frameHeader_incomplete|LZ4F_freeDecompressionContext reported unclean decompressor state \(truncated frame\?\): \d+)$'):
lz4frame.decompress(compressed[:i])
def test_checksum_failure(self):
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
compressed = lz4frame.compress(input_data, content_checksum=lz4frame.CONTENTCHECKSUM_ENABLED)
with self.assertRaisesRegexp(RuntimeError, r'^LZ4F_decompress failed with code: ERROR_contentChecksum_invalid'):
last = struct.unpack('B', compressed[-1:])[0]
lz4frame.decompress(compressed[:-1] + struct.pack('B', last ^ 0x42))
# NB: blockChecksumFlag is not supported by lz4 at the moment, so some
# random 1-bit modifications of input may actually trigger valid output
# without errors. And content checksum remains the same!
def test_decompress_trailer(self):
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
compressed = lz4frame.compress(input_data)
with self.assertRaisesRegexp(ValueError, r'^Extra data: 64 trailing bytes'):
lz4frame.decompress(compressed + b'A'*64)
# This API does not support frame concatenation!
with self.assertRaisesRegexp(ValueError, r'^Extra data: \d+ trailing bytes'):
lz4frame.decompress(compressed + compressed)
def test_LZ4FrameCompressor_fails(self):
input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123"
with self.assertRaisesRegexp(RuntimeError, r'compress called after flush'):
with lz4frame.LZ4FrameCompressor() as compressor:
compressed = compressor.compress_begin()
compressed += compressor.compress(input_data)
compressed += compressor.flush()
compressed = compressor.compress(input_data)
if sys.version_info < (2, 7):
# Poor-man unittest.TestCase.skip for Python 2.6
del TestLZ4FrameModern
if __name__ == '__main__':
unittest.main()
| 47.108359 | 229 | 0.694926 | 1,439 | 15,216 | 7.114663 | 0.131341 | 0.062415 | 0.101582 | 0.062512 | 0.821156 | 0.769975 | 0.746533 | 0.732858 | 0.721137 | 0.707658 | 0 | 0.154523 | 0.230613 | 15,216 | 322 | 230 | 47.254658 | 0.719997 | 0.033715 | 0 | 0.65942 | 0 | 0 | 0.12597 | 0.105066 | 0 | 0 | 0.000272 | 0 | 0.112319 | 1 | 0.09058 | false | 0 | 0.021739 | 0.003623 | 0.126812 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
51c5f65fe44db859f27887a8ebd26e73c388159f | 28 | py | Python | measure/__init__.py | Nemu627/str-measure | 544857008b36a51f5023b38b42ded39a95137dda | [
"MIT"
] | null | null | null | measure/__init__.py | Nemu627/str-measure | 544857008b36a51f5023b38b42ded39a95137dda | [
"MIT"
] | null | null | null | measure/__init__.py | Nemu627/str-measure | 544857008b36a51f5023b38b42ded39a95137dda | [
"MIT"
] | null | null | null | from .main import get_length | 28 | 28 | 0.857143 | 5 | 28 | 4.6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.107143 | 28 | 1 | 28 | 28 | 0.92 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
cfafe7045a90f48b9d0206f84ca6aa7a7760522b | 20,751 | py | Python | pybind/slxos/v16r_1_00b/sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/__init__.py | shivharis/pybind | 4e1c6d54b9fd722ccec25546ba2413d79ce337e6 | [
"Apache-2.0"
] | null | null | null | pybind/slxos/v16r_1_00b/sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/__init__.py | shivharis/pybind | 4e1c6d54b9fd722ccec25546ba2413d79ce337e6 | [
"Apache-2.0"
] | null | null | null | pybind/slxos/v16r_1_00b/sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/__init__.py | shivharis/pybind | 4e1c6d54b9fd722ccec25546ba2413d79ce337e6 | [
"Apache-2.0"
] | 1 | 2021-11-05T22:15:42.000Z | 2021-11-05T22:15:42.000Z |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
class lif_statistics(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-nsm-operational - based on the path /sub-interface-statistics-state/bridge-domain-statistics/lif-statistics. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: lif statistics
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__rx_packets','__tx_packets','__rx_bytes','__tx_bytes','__lif_id','__lif_name',)
_yang_name = 'lif-statistics'
_rest_name = 'lif-statistics'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__rx_packets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-packets", rest_name="rx-packets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
self.__rx_bytes = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bytes", rest_name="rx-bytes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
self.__lif_name = YANGDynClass(base=unicode, is_leaf=True, yang_name="lif-name", rest_name="lif-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='string', is_config=False)
self.__lif_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lif-id", rest_name="lif-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint32', is_config=False)
self.__tx_bytes = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bytes", rest_name="tx-bytes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
self.__tx_packets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-packets", rest_name="tx-packets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'sub-interface-statistics-state', u'bridge-domain-statistics', u'lif-statistics']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'sub-interface-statistics-state', u'bridge-domain-statistics', u'lif-statistics']
def _get_rx_packets(self):
"""
Getter method for rx_packets, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/rx_packets (uint64)
YANG Description: Received Packets count in Lif
"""
return self.__rx_packets
def _set_rx_packets(self, v, load=False):
"""
Setter method for rx_packets, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/rx_packets (uint64)
If this variable is read-only (config: false) in the
source YANG file, then _set_rx_packets is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_rx_packets() directly.
YANG Description: Received Packets count in Lif
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-packets", rest_name="rx-packets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """rx_packets must be of a type compatible with uint64""",
'defined-type': "uint64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-packets", rest_name="rx-packets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)""",
})
self.__rx_packets = t
if hasattr(self, '_set'):
self._set()
def _unset_rx_packets(self):
self.__rx_packets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-packets", rest_name="rx-packets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
def _get_tx_packets(self):
"""
Getter method for tx_packets, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/tx_packets (uint64)
YANG Description: Transmitted Packets count in Lif
"""
return self.__tx_packets
def _set_tx_packets(self, v, load=False):
"""
Setter method for tx_packets, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/tx_packets (uint64)
If this variable is read-only (config: false) in the
source YANG file, then _set_tx_packets is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_tx_packets() directly.
YANG Description: Transmitted Packets count in Lif
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-packets", rest_name="tx-packets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """tx_packets must be of a type compatible with uint64""",
'defined-type': "uint64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-packets", rest_name="tx-packets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)""",
})
self.__tx_packets = t
if hasattr(self, '_set'):
self._set()
def _unset_tx_packets(self):
self.__tx_packets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-packets", rest_name="tx-packets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
def _get_rx_bytes(self):
"""
Getter method for rx_bytes, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/rx_bytes (uint64)
YANG Description: Received Bytes count in Lif
"""
return self.__rx_bytes
def _set_rx_bytes(self, v, load=False):
"""
Setter method for rx_bytes, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/rx_bytes (uint64)
If this variable is read-only (config: false) in the
source YANG file, then _set_rx_bytes is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_rx_bytes() directly.
YANG Description: Received Bytes count in Lif
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bytes", rest_name="rx-bytes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """rx_bytes must be of a type compatible with uint64""",
'defined-type': "uint64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bytes", rest_name="rx-bytes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)""",
})
self.__rx_bytes = t
if hasattr(self, '_set'):
self._set()
def _unset_rx_bytes(self):
self.__rx_bytes = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bytes", rest_name="rx-bytes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
def _get_tx_bytes(self):
"""
Getter method for tx_bytes, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/tx_bytes (uint64)
YANG Description: Transmitted Bytes count in Lif
"""
return self.__tx_bytes
def _set_tx_bytes(self, v, load=False):
"""
Setter method for tx_bytes, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/tx_bytes (uint64)
If this variable is read-only (config: false) in the
source YANG file, then _set_tx_bytes is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_tx_bytes() directly.
YANG Description: Transmitted Bytes count in Lif
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bytes", rest_name="tx-bytes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """tx_bytes must be of a type compatible with uint64""",
'defined-type': "uint64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bytes", rest_name="tx-bytes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)""",
})
self.__tx_bytes = t
if hasattr(self, '_set'):
self._set()
def _unset_tx_bytes(self):
self.__tx_bytes = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bytes", rest_name="tx-bytes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint64', is_config=False)
def _get_lif_id(self):
"""
Getter method for lif_id, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/lif_id (uint32)
YANG Description: lif index
"""
return self.__lif_id
def _set_lif_id(self, v, load=False):
"""
Setter method for lif_id, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/lif_id (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_lif_id is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_lif_id() directly.
YANG Description: lif index
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lif-id", rest_name="lif-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """lif_id must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lif-id", rest_name="lif-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint32', is_config=False)""",
})
self.__lif_id = t
if hasattr(self, '_set'):
self._set()
def _unset_lif_id(self):
self.__lif_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lif-id", rest_name="lif-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint32', is_config=False)
def _get_lif_name(self):
"""
Getter method for lif_name, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/lif_name (string)
YANG Description: lif name
"""
return self.__lif_name
def _set_lif_name(self, v, load=False):
"""
Setter method for lif_name, mapped from YANG variable /sub_interface_statistics_state/bridge_domain_statistics/lif_statistics/lif_name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_lif_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_lif_name() directly.
YANG Description: lif name
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=unicode, is_leaf=True, yang_name="lif-name", rest_name="lif-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='string', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """lif_name must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=unicode, is_leaf=True, yang_name="lif-name", rest_name="lif-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='string', is_config=False)""",
})
self.__lif_name = t
if hasattr(self, '_set'):
self._set()
def _unset_lif_name(self):
self.__lif_name = YANGDynClass(base=unicode, is_leaf=True, yang_name="lif-name", rest_name="lif-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='string', is_config=False)
rx_packets = __builtin__.property(_get_rx_packets)
tx_packets = __builtin__.property(_get_tx_packets)
rx_bytes = __builtin__.property(_get_rx_bytes)
tx_bytes = __builtin__.property(_get_tx_bytes)
lif_id = __builtin__.property(_get_lif_id)
lif_name = __builtin__.property(_get_lif_name)
_pyangbind_elements = {'rx_packets': rx_packets, 'tx_packets': tx_packets, 'rx_bytes': rx_bytes, 'tx_bytes': tx_bytes, 'lif_id': lif_id, 'lif_name': lif_name, }
| 63.072948 | 454 | 0.741555 | 2,809 | 20,751 | 5.196867 | 0.06764 | 0.042472 | 0.04987 | 0.046239 | 0.843814 | 0.8184 | 0.803535 | 0.782025 | 0.772161 | 0.767913 | 0 | 0.02818 | 0.134692 | 20,751 | 328 | 455 | 63.265244 | 0.784807 | 0.19016 | 0 | 0.447917 | 0 | 0.03125 | 0.341293 | 0.199721 | 0 | 0 | 0 | 0 | 0 | 1 | 0.109375 | false | 0 | 0.041667 | 0 | 0.270833 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
cfbb19c13f6ff1c4bfe2a7d2a90ec5e1098e96b6 | 321 | py | Python | test/example_flake8-quotes.py | shakiyam/flake8-docker | bfc63ce0e0e4f856504bc9e7fb2bc73ccf94e53b | [
"MIT"
] | null | null | null | test/example_flake8-quotes.py | shakiyam/flake8-docker | bfc63ce0e0e4f856504bc9e7fb2bc73ccf94e53b | [
"MIT"
] | null | null | null | test/example_flake8-quotes.py | shakiyam/flake8-docker | bfc63ce0e0e4f856504bc9e7fb2bc73ccf94e53b | [
"MIT"
] | null | null | null | "Remove bad quotes from docstring" # Q002
print("Remove bad quotes") # Q000
print('Change outer quotes to avoid \'escaping\' inner quotes') # Q003
# Q000 Remove bad quotes
# Q001 Remove bad quotes from multiline string
# Q002 Remove bad quotes from docstring
# Q003 Change outer quotes to avoid escaping inner quotes
| 35.666667 | 71 | 0.760125 | 47 | 321 | 5.191489 | 0.382979 | 0.184426 | 0.307377 | 0.233607 | 0.581967 | 0.352459 | 0.352459 | 0.352459 | 0 | 0 | 0 | 0.079245 | 0.174455 | 321 | 8 | 72 | 40.125 | 0.841509 | 0.654206 | 0 | 0 | 0 | 0 | 0.671533 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 0.666667 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 6 |
321637aaae7e7e2db19d2ac61a7756566645c81f | 93 | py | Python | tests/test_exception.py | sakost/kutana | 7695902803f17e1ce6109b5f9a8a7c24126d322f | [
"MIT"
] | 69 | 2018-10-05T21:42:51.000Z | 2022-03-16T17:22:21.000Z | tests/test_exception.py | sakost/kutana | 7695902803f17e1ce6109b5f9a8a7c24126d322f | [
"MIT"
] | 41 | 2018-10-20T09:18:43.000Z | 2021-11-22T12:19:44.000Z | tests/test_exception.py | sakost/kutana | 7695902803f17e1ce6109b5f9a8a7c24126d322f | [
"MIT"
] | 26 | 2018-10-20T09:13:42.000Z | 2021-12-24T17:01:02.000Z | from kutana import RequestException
def test_exception():
RequestException({}, "", {})
| 15.5 | 35 | 0.698925 | 8 | 93 | 8 | 0.875 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.16129 | 93 | 5 | 36 | 18.6 | 0.820513 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | true | 0 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3219e924b0bf97c2bf1f19d0f9799a18f6c85a24 | 7,883 | py | Python | tests/test_optimizer.py | kitasubmarine/scopt | 0da1f2fa3076e408e65e803eaaed0b8716f20b56 | [
"MIT"
] | 4 | 2021-06-10T10:03:08.000Z | 2022-03-18T13:11:25.000Z | tests/test_optimizer.py | kitasubmarine/scopt | 0da1f2fa3076e408e65e803eaaed0b8716f20b56 | [
"MIT"
] | null | null | null | tests/test_optimizer.py | kitasubmarine/scopt | 0da1f2fa3076e408e65e803eaaed0b8716f20b56 | [
"MIT"
] | 1 | 2022-03-30T04:55:14.000Z | 2022-03-30T04:55:14.000Z | import pytest
from scopt.instances import Instance
from scopt.optimizer import (
ClientModeOptimizer,
ClusterModeOptimizer,
SparkConfOptimizer,
)
class TestClusterModeOptimizer:
def test_properties(self) -> None:
optimizer = ClusterModeOptimizer(Instance(32, 248), 10)
assert optimizer.executor_cores == 5
assert optimizer.executor_per_node == 6
assert optimizer.total_executor_memory == 41
assert optimizer.executor_memory == 36
assert optimizer.executor_memory_overhead == 5
assert optimizer.driver_cores == 5
assert optimizer.driver_memory == 36
assert optimizer.driver_memory_overhead == 5
assert optimizer.executor_instances == 59
assert optimizer.default_parallelism == 590
assert optimizer.sql_shuffle_partitions == 590
def test_small_cpu_instance(self) -> None:
optimizer = ClusterModeOptimizer(Instance(4, 16), 10)
assert optimizer.executor_cores == 3
assert optimizer.executor_per_node == 1
assert optimizer.total_executor_memory == 15
assert optimizer.executor_memory == 13
assert optimizer.executor_memory_overhead == 2
assert optimizer.driver_cores == 3
assert optimizer.driver_memory == 13
assert optimizer.driver_memory_overhead == 2
assert optimizer.executor_instances == 9
assert optimizer.default_parallelism == 54
assert optimizer.sql_shuffle_partitions == 54
def test_insufficient_resource(self) -> None:
with pytest.raises(ValueError):
ClusterModeOptimizer(Instance(4, 16), 1)
class TestClientModeOptimizer:
def test_properties(self) -> None:
optimizer = ClientModeOptimizer(Instance(32, 248), 10)
assert optimizer.executor_cores == 5
assert optimizer.executor_per_node == 6
assert optimizer.total_executor_memory == 41
assert optimizer.executor_memory == 36
assert optimizer.executor_memory_overhead == 5
assert optimizer.driver_cores == 5
assert optimizer.driver_memory == 36
assert optimizer.driver_memory_overhead == 5
assert optimizer.executor_instances == 60
assert optimizer.default_parallelism == 600
assert optimizer.sql_shuffle_partitions == 600
def test_properties_specify_driver_instance(self) -> None:
optimizer = ClientModeOptimizer(Instance(32, 248), 10, Instance(4, 16))
assert optimizer.executor_cores == 5
assert optimizer.executor_per_node == 6
assert optimizer.total_executor_memory == 41
assert optimizer.executor_memory == 36
assert optimizer.executor_memory_overhead == 5
assert optimizer.driver_cores == 3
assert optimizer.driver_memory == 13
assert optimizer.driver_memory_overhead == 2
assert optimizer.executor_instances == 60
assert optimizer.default_parallelism == 600
assert optimizer.sql_shuffle_partitions == 600
def test_properties_specify_small_driver_instance(self) -> None:
optimizer = ClientModeOptimizer(Instance(4, 16), 10, Instance(32, 248))
assert optimizer.executor_cores == 3
assert optimizer.executor_per_node == 1
assert optimizer.total_executor_memory == 15
assert optimizer.executor_memory == 13
assert optimizer.executor_memory_overhead == 2
assert optimizer.driver_cores == 3
assert optimizer.driver_memory == 13
assert optimizer.driver_memory_overhead == 2
assert optimizer.executor_instances == 10
assert optimizer.default_parallelism == 60
assert optimizer.sql_shuffle_partitions == 60
class TestSparkConfOptimizer:
def test_cluster_mode(self) -> None:
optimizer = SparkConfOptimizer(Instance(32, 248), 10, 'cluster')
assert isinstance(optimizer.optimizer, ClusterModeOptimizer)
def test_client_mode(self) -> None:
optimizer = SparkConfOptimizer(
Instance(32, 248), 10, 'client', Instance(32, 248)
)
assert isinstance(optimizer.optimizer, ClientModeOptimizer)
def test_dynamic_allocation(self) -> None:
optimizer = SparkConfOptimizer(
Instance(32, 248),
num_nodes=10,
deploy_mode='client',
dynamic_allocation=True,
)
assert optimizer.specified_num_nodes
optimizer = SparkConfOptimizer(
Instance(32, 248), deploy_mode='client', dynamic_allocation=True
)
assert not optimizer.specified_num_nodes
assert optimizer.num_nodes == 2
optimizer = SparkConfOptimizer(
Instance(32, 248),
num_nodes=10,
deploy_mode='cluster',
dynamic_allocation=True,
)
assert optimizer.specified_num_nodes
optimizer = SparkConfOptimizer(
Instance(32, 248), deploy_mode='cluster', dynamic_allocation=True
)
assert not optimizer.specified_num_nodes
assert optimizer.num_nodes == 2
with pytest.raises(ValueError):
SparkConfOptimizer(
Instance(32, 248),
deploy_mode='client',
dynamic_allocation=False,
)
with pytest.raises(ValueError):
SparkConfOptimizer(
Instance(32, 248),
deploy_mode='cluster',
dynamic_allocation=False,
)
def test_as_dict(self) -> None:
optimizer = SparkConfOptimizer(Instance(32, 248), 10, 'client')
expected = {
'spark.driver.cores': 5,
'spark.driver.memory': '36g',
'spark.driver.memoryOvearhead': '5g',
'spark.executor.cores': 5,
'spark.executor.memory': '36g',
'spark.executor.memoryOvearhead': '5g',
'spark.executor.instances': 60,
'spark.default.parallelism': 600,
'spark.sql.shuffle.partitions': 600,
}
assert optimizer.as_dict() == expected
def test_as_dict_dynamic_allocation(self) -> None:
optimizer = SparkConfOptimizer(
Instance(32, 248),
10,
deploy_mode='client',
dynamic_allocation=True,
)
expected = {
'spark.driver.cores': 5,
'spark.driver.memory': '36g',
'spark.driver.memoryOvearhead': '5g',
'spark.executor.cores': 5,
'spark.executor.memory': '36g',
'spark.executor.memoryOvearhead': '5g',
'spark.default.parallelism': 600,
'spark.sql.shuffle.partitions': 600,
}
assert optimizer.as_dict() == expected
def test_as_dict_dynamic_allocation_not_specify_num_nodes(self) -> None:
optimizer = SparkConfOptimizer(
Instance(32, 248), deploy_mode='client', dynamic_allocation=True
)
expected = {
'spark.driver.cores': 5,
'spark.driver.memory': '36g',
'spark.driver.memoryOvearhead': '5g',
'spark.executor.cores': 5,
'spark.executor.memory': '36g',
'spark.executor.memoryOvearhead': '5g',
}
assert optimizer.as_dict() == expected
def test_as_list(self) -> None:
optimizer = SparkConfOptimizer(Instance(32, 248), 10, 'client')
expected = [
('spark.driver.cores', 5),
('spark.driver.memory', '36g'),
('spark.driver.memoryOvearhead', '5g'),
('spark.executor.cores', 5),
('spark.executor.memory', '36g'),
('spark.executor.memoryOvearhead', '5g'),
('spark.executor.instances', 60),
('spark.default.parallelism', 600),
('spark.sql.shuffle.partitions', 600),
]
assert optimizer.as_list() == expected
| 38.453659 | 79 | 0.631739 | 784 | 7,883 | 6.160714 | 0.104592 | 0.195652 | 0.119048 | 0.077019 | 0.855487 | 0.819876 | 0.809317 | 0.790062 | 0.763768 | 0.713872 | 0 | 0.04682 | 0.273881 | 7,883 | 204 | 80 | 38.642157 | 0.796995 | 0 | 0 | 0.631868 | 0 | 0 | 0.109984 | 0.066345 | 0 | 0 | 0 | 0 | 0.368132 | 1 | 0.071429 | false | 0 | 0.016484 | 0 | 0.104396 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
5c68dae68cf71241782c67243b48a98c9c4deb81 | 106 | py | Python | dqn/history.py | zjjott/curiosity | d6aa8ef2503e7e21e26f53e964667288337d4ed1 | [
"MIT"
] | null | null | null | dqn/history.py | zjjott/curiosity | d6aa8ef2503e7e21e26f53e964667288337d4ed1 | [
"MIT"
] | null | null | null | dqn/history.py | zjjott/curiosity | d6aa8ef2503e7e21e26f53e964667288337d4ed1 | [
"MIT"
] | null | null | null | # coding=utf-8
from __future__ import unicode_literals, absolute_import
class History(object):
pass
| 15.142857 | 56 | 0.783019 | 14 | 106 | 5.5 | 0.928571 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011111 | 0.150943 | 106 | 6 | 57 | 17.666667 | 0.844444 | 0.113208 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
5c79ddb20fa4116515c69fec257436afcbe11f22 | 19,739 | py | Python | test_autoarray/structures/grids/test_decorators.py | jonathanfrawley/PyAutoArray_copy | c21e8859bdb20737352147b9904797ac99985b73 | [
"MIT"
] | null | null | null | test_autoarray/structures/grids/test_decorators.py | jonathanfrawley/PyAutoArray_copy | c21e8859bdb20737352147b9904797ac99985b73 | [
"MIT"
] | null | null | null | test_autoarray/structures/grids/test_decorators.py | jonathanfrawley/PyAutoArray_copy | c21e8859bdb20737352147b9904797ac99985b73 | [
"MIT"
] | null | null | null | import os
import numpy as np
import pytest
import autoarray as aa
from autoarray.mock.mock import (
MockGridLikeIteratorObj,
MockGrid1DLikeObj,
MockGrid2DLikeObj,
ndarray_1d_from_grid,
ndarray_2d_from_grid,
)
class TestGrid1DToStructure:
def test__grid_1d_in__output_values_projected_format(self):
grid_2d = aa.Grid1D.manual_native(grid=[1.0, 2.0, 3.0], pixel_scales=1.0)
grid_like_object = MockGrid1DLikeObj()
array_output = grid_like_object.ndarray_1d_from_grid(grid=grid_2d)
assert isinstance(array_output, aa.Array1D)
assert (array_output.native == np.array([1.0, 1.0, 1.0])).all()
assert array_output.pixel_scales == (1.0,)
grid_like_object = MockGrid1DLikeObj(centre=(1.0, 0.0), angle=45.0)
array_output = grid_like_object.ndarray_1d_from_grid(grid=grid_2d)
assert isinstance(array_output, aa.Array1D)
assert (array_output.native == np.array([1.0, 1.0, 1.0])).all()
assert array_output.pixel_scales == (1.0,)
def test__grid_2d_in__output_values_projected_format(self):
grid_2d = aa.Grid2D.uniform(shape_native=(4, 4), pixel_scales=1.0, sub_size=1)
grid_like_object = MockGrid1DLikeObj()
array_output = grid_like_object.ndarray_1d_from_grid(grid=grid_2d)
assert isinstance(array_output, aa.Array1D)
assert (array_output.native == np.array([1.0])).all()
assert array_output.pixel_scales == (1.0,)
grid_like_object = MockGrid1DLikeObj(centre=(1.0, 0.0))
array_output = grid_like_object.ndarray_1d_from_grid(grid=grid_2d)
assert isinstance(array_output, aa.Array1D)
assert (array_output.native == np.array([1.0, 1.0, 1.0])).all()
assert array_output.pixel_scales == (1.0,)
def test__grid_2d_irregular_in__output_values_projected_format(self):
grid_2d = aa.Grid2DIrregular(grid=[[0.0, 0.0], [0.0, 1.0], [0.0, 2.0]])
grid_like_object = MockGrid1DLikeObj()
array_output = grid_like_object.ndarray_1d_from_grid(grid=grid_2d)
assert isinstance(array_output, aa.ValuesIrregular)
assert (array_output == np.array([1.0, 1.0, 1.0])).all()
class TestGrid2DToStructure:
def test__grid_1d_in__output_values_same_format(self):
mask = aa.Mask1D.manual(
mask=[True, False, False, True], pixel_scales=(1.0,), sub_size=1
)
grid_1d = aa.Grid1D.from_mask(mask=mask)
grid_like_object = MockGrid2DLikeObj()
array_output = grid_like_object.ndarray_1d_from_grid(grid=grid_1d)
assert isinstance(array_output, aa.Array1D)
assert (array_output.native == np.array([0.0, 1.0, 1.0, 0.0])).all()
grid_output = grid_like_object.ndarray_2d_from_grid(grid=grid_1d)
assert isinstance(grid_output, aa.Grid2D)
assert grid_output.native == pytest.approx(
np.array([[[0.0, 0.0], [0.0, -1.0], [0.0, 1.0], [0.0, 0.0]]]), 1.0e-4
)
def test__grid_1d_in__output_is_list__list_of_same_format(self):
mask = aa.Mask1D.manual(
mask=[True, False, False, True], pixel_scales=(1.0,), sub_size=1
)
grid_1d = aa.Grid1D.from_mask(mask=mask)
grid_like_object = MockGrid2DLikeObj()
array_output = grid_like_object.ndarray_1d_list_from_grid(grid=grid_1d)
assert isinstance(array_output[0], aa.Array1D)
assert (array_output[0].native == np.array([[0.0, 1.0, 1.0, 0.0]])).all()
assert isinstance(array_output[1], aa.Array1D)
assert (array_output[1].native == np.array([[0.0, 2.0, 2.0, 0.0]])).all()
grid_output = grid_like_object.ndarray_2d_list_from_grid(grid=grid_1d)
assert isinstance(grid_output[0], aa.Grid2D)
assert grid_output[0].native == pytest.approx(
np.array([[[0.0, 0.0], [0.0, -0.5], [0.0, 0.5], [0.0, 0.0]]]), 1.0e-4
)
assert isinstance(grid_output[1], aa.Grid2D)
assert grid_output[1].native == pytest.approx(
np.array([[[0.0, 0.0], [0.0, -1.0], [0.0, 1.0], [0.0, 0.0]]]), 1.0e-4
)
def test__grid_2d_in__output_values_same_format(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True],
[True, False, False, True],
[True, False, False, True],
[True, True, True, True],
],
pixel_scales=(1.0, 1.0),
sub_size=1,
)
grid_2d = aa.Grid2D.from_mask(mask=mask)
grid_like_object = MockGrid2DLikeObj()
array_output = grid_like_object.ndarray_1d_from_grid(grid=grid_2d)
assert isinstance(array_output, aa.Array2D)
assert (
array_output.native
== np.array(
[
[0.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 1.0, 0.0],
[0.0, 1.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
]
)
).all()
grid_output = grid_like_object.ndarray_2d_from_grid(grid=grid_2d)
assert isinstance(grid_output, aa.Grid2D)
assert (
grid_output.native
== np.array(
[
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]],
[[0.0, 0.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]],
[[0.0, 0.0], [-1.0, -1.0], [-1.0, 1.0], [0.0, 0.0]],
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]],
]
)
).all()
def test__grid_2d_in__output_is_list__list_of_same_format(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True],
[True, False, False, True],
[True, False, False, True],
[True, True, True, True],
],
pixel_scales=(1.0, 1.0),
sub_size=1,
)
grid_2d = aa.Grid2D.from_mask(mask=mask)
grid_like_object = MockGrid2DLikeObj()
array_output = grid_like_object.ndarray_1d_list_from_grid(grid=grid_2d)
assert isinstance(array_output[0], aa.Array2D)
assert (
array_output[0].native
== np.array(
[
[0.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 1.0, 0.0],
[0.0, 1.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
]
)
).all()
assert isinstance(array_output[1], aa.Array2D)
assert (
array_output[1].native
== np.array(
[
[0.0, 0.0, 0.0, 0.0],
[0.0, 2.0, 2.0, 0.0],
[0.0, 2.0, 2.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
]
)
).all()
grid_output = grid_like_object.ndarray_2d_list_from_grid(grid=grid_2d)
assert isinstance(grid_output[0], aa.Grid2D)
assert (
grid_output[0].native
== np.array(
[
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]],
[[0.0, 0.0], [0.5, -0.5], [0.5, 0.5], [0.0, 0.0]],
[[0.0, 0.0], [-0.5, -0.5], [-0.5, 0.5], [0.0, 0.0]],
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]],
]
)
).all()
assert isinstance(grid_output[1], aa.Grid2D)
assert (
grid_output[1].native
== np.array(
[
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]],
[[0.0, 0.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]],
[[0.0, 0.0], [-1.0, -1.0], [-1.0, 1.0], [0.0, 0.0]],
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]],
]
)
).all()
def test__grid_2d_irregular_in__output_values_same_format(self):
grid_like_object = MockGrid2DLikeObj()
grid_2d = aa.Grid2DIrregular(grid=[(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)])
values_output = grid_like_object.ndarray_1d_from_grid(grid=grid_2d)
assert values_output.in_list == [1.0, 1.0, 1.0]
grid_output = grid_like_object.ndarray_2d_from_grid(grid=grid_2d)
assert grid_output.in_list == [(2.0, 4.0), (6.0, 8.0), (10.0, 12.0)]
def test__grid_2d_irregular_in__output_is_list__list_of_same_format(self):
grid_like_object = MockGrid2DLikeObj()
grid_2d = aa.Grid2DIrregular(grid=[(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)])
grid_output = grid_like_object.ndarray_1d_list_from_grid(grid=grid_2d)
assert grid_output[0].in_list == [1.0, 1.0, 1.0]
assert grid_output[1].in_list == [2.0, 2.0, 2.0]
grid_output = grid_like_object.ndarray_2d_list_from_grid(grid=grid_2d)
assert grid_output[0].in_list == [(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)]
assert grid_output[1].in_list == [(2.0, 4.0), (6.0, 8.0), (10.0, 12.0)]
def test__grid_2d_iterate_in__output_values__use_iterated_array_function(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, False, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
],
pixel_scales=(1.0, 1.0),
origin=(0.001, 0.001),
)
grid_2d = aa.Grid2DIterate.from_mask(
mask=mask, fractional_accuracy=1.0, sub_steps=[2, 3]
)
grid_like_obj = MockGridLikeIteratorObj()
values = grid_like_obj.ndarray_1d_from_grid(grid=grid_2d)
mask_sub_3 = mask.mask_new_sub_size_from(mask=mask, sub_size=3)
grid_sub_3 = aa.Grid2D.from_mask(mask=mask_sub_3)
values_sub_3 = ndarray_1d_from_grid(grid=grid_sub_3, profile=None)
values_sub_3 = grid_sub_3.structure_2d_from_result(result=values_sub_3)
assert (values == values_sub_3.binned).all()
grid_2d = aa.Grid2DIterate.from_mask(
mask=mask, fractional_accuracy=0.000001, sub_steps=[2, 4, 8, 16, 32]
)
grid_like_obj = MockGridLikeIteratorObj()
values = grid_like_obj.ndarray_1d_from_grid(grid=grid_2d)
mask_sub_2 = mask.mask_new_sub_size_from(mask=mask, sub_size=2)
grid_sub_2 = aa.Grid2D.from_mask(mask=mask_sub_2)
values_sub_2 = ndarray_1d_from_grid(grid=grid_sub_2, profile=None)
values_sub_2 = grid_sub_2.structure_2d_from_result(result=values_sub_2)
assert (values == values_sub_2.binned).all()
grid_2d = aa.Grid2DIterate.from_mask(
mask=mask, fractional_accuracy=0.5, sub_steps=[2, 4]
)
iterate_obj = MockGridLikeIteratorObj()
values = iterate_obj.ndarray_1d_from_grid(grid=grid_2d)
mask_sub_2 = mask.mask_new_sub_size_from(mask=mask, sub_size=2)
grid_sub_2 = aa.Grid2D.from_mask(mask=mask_sub_2)
values_sub_2 = ndarray_1d_from_grid(grid=grid_sub_2, profile=None)
values_sub_2 = grid_sub_2.structure_2d_from_result(result=values_sub_2)
mask_sub_4 = mask.mask_new_sub_size_from(mask=mask, sub_size=4)
grid_sub_4 = aa.Grid2D.from_mask(mask=mask_sub_4)
values_sub_4 = ndarray_1d_from_grid(grid=grid_sub_4, profile=None)
values_sub_4 = grid_sub_4.structure_2d_from_result(result=values_sub_4)
assert values.native[1, 1] == values_sub_2.binned.native[1, 1]
assert values.native[2, 2] != values_sub_2.binned.native[2, 2]
assert values.native[1, 1] != values_sub_4.binned.native[1, 1]
assert values.native[2, 2] == values_sub_4.binned.native[2, 2]
def test__grid_2d_iterate_in__output_is_list_of_arrays__use_maximum_sub_size_in_all_pixels(
self
):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, False, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
],
pixel_scales=(1.0, 1.0),
origin=(0.001, 0.001),
)
grid_2d = aa.Grid2DIterate.from_mask(
mask=mask, fractional_accuracy=0.05, sub_steps=[2, 3]
)
grid_like_obj = MockGridLikeIteratorObj()
values = grid_like_obj.ndarray_1d_list_from_grid(grid=grid_2d)
mask_sub_3 = mask.mask_new_sub_size_from(mask=mask, sub_size=3)
grid_sub_3 = aa.Grid2D.from_mask(mask=mask_sub_3)
values_sub_3 = ndarray_1d_from_grid(grid=grid_sub_3, profile=None)
values_sub_3 = grid_sub_3.structure_2d_from_result(result=values_sub_3)
assert (values[0] == values_sub_3.binned).all()
def test__grid_2d_iterate_in__output_values__use_iterated_grid_function(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, False, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
],
pixel_scales=(1.0, 1.0),
origin=(0.001, 0.001),
)
grid_2d = aa.Grid2DIterate.from_mask(
mask=mask, fractional_accuracy=1.0, sub_steps=[2, 3]
)
grid_like_obj = MockGridLikeIteratorObj()
values = grid_like_obj.ndarray_2d_from_grid(grid=grid_2d)
mask_sub_3 = mask.mask_new_sub_size_from(mask=mask, sub_size=3)
grid_sub_3 = aa.Grid2D.from_mask(mask=mask_sub_3)
values_sub_3 = ndarray_2d_from_grid(grid=grid_sub_3, profile=None)
values_sub_3 = grid_sub_3.structure_2d_from_result(result=values_sub_3)
assert (values == values_sub_3.binned).all()
grid_2d = aa.Grid2DIterate.from_mask(
mask=mask, fractional_accuracy=0.000001, sub_steps=[2, 4, 8, 16, 32]
)
grid_like_obj = MockGridLikeIteratorObj()
values = grid_like_obj.ndarray_2d_from_grid(grid=grid_2d)
mask_sub_2 = mask.mask_new_sub_size_from(mask=mask, sub_size=2)
grid_sub_2 = aa.Grid2D.from_mask(mask=mask_sub_2)
values_sub_2 = ndarray_2d_from_grid(grid=grid_sub_2, profile=None)
values_sub_2 = grid_sub_2.structure_2d_from_result(result=values_sub_2)
assert (values == values_sub_2.binned).all()
grid_2d = aa.Grid2DIterate.from_mask(
mask=mask, fractional_accuracy=0.5, sub_steps=[2, 4]
)
iterate_obj = MockGridLikeIteratorObj()
values = iterate_obj.ndarray_2d_from_grid(grid=grid_2d)
mask_sub_2 = mask.mask_new_sub_size_from(mask=mask, sub_size=2)
grid_sub_2 = aa.Grid2D.from_mask(mask=mask_sub_2)
values_sub_2 = ndarray_2d_from_grid(grid=grid_sub_2, profile=None)
values_sub_2 = grid_sub_2.structure_2d_from_result(result=values_sub_2)
mask_sub_4 = mask.mask_new_sub_size_from(mask=mask, sub_size=4)
grid_sub_4 = aa.Grid2D.from_mask(mask=mask_sub_4)
values_sub_4 = ndarray_2d_from_grid(grid=grid_sub_4, profile=None)
values_sub_4 = grid_sub_4.structure_2d_from_result(result=values_sub_4)
assert values.native[1, 1, 0] == values_sub_2.binned.native[1, 1, 0]
assert values.native[2, 2, 0] != values_sub_2.binned.native[2, 2, 0]
assert values.native[1, 1, 0] != values_sub_4.binned.native[1, 1, 0]
assert values.native[2, 2, 0] == values_sub_4.binned.native[2, 2, 0]
assert values.native[1, 1, 1] == values_sub_2.binned.native[1, 1, 1]
assert values.native[2, 2, 1] != values_sub_2.binned.native[2, 2, 1]
assert values.native[1, 1, 1] != values_sub_4.binned.native[1, 1, 1]
assert values.native[2, 2, 1] == values_sub_4.binned.native[2, 2, 1]
def test__grid_2d_iterate_in__output_is_list_of_grids__use_maximum_sub_size_in_all_pixels(
self
):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, False, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
],
pixel_scales=(1.0, 1.0),
origin=(0.001, 0.001),
)
grid_2d = aa.Grid2DIterate.from_mask(
mask=mask, fractional_accuracy=0.05, sub_steps=[2, 3]
)
grid_like_obj = MockGridLikeIteratorObj()
values = grid_like_obj.ndarray_2d_list_from_grid(grid=grid_2d)
mask_sub_3 = mask.mask_new_sub_size_from(mask=mask, sub_size=3)
grid_sub_3 = aa.Grid2D.from_mask(mask=mask_sub_3)
values_sub_3 = ndarray_2d_from_grid(grid=grid_sub_3, profile=None)
values_sub_3 = grid_sub_3.structure_2d_from_result(result=values_sub_3)
assert (values[0][0] == values_sub_3.binned[0]).all()
assert (values[0][1] == values_sub_3.binned[1]).all()
def test__grid_2d_interpolate_in__output_values__interpolation_used_and_accurate(
self
):
mask = aa.Mask2D.circular_annular(
shape_native=(20, 20),
pixel_scales=(1.0, 1.0),
sub_size=1,
inner_radius=3.0,
outer_radius=8.0,
)
grid_like_obj = MockGridLikeIteratorObj()
grid_2d = aa.Grid2D.from_mask(mask=mask)
true_array = grid_like_obj.ndarray_1d_from_grid(grid=grid_2d)
grid_2d = aa.Grid2DInterpolate.from_mask(mask=mask, pixel_scales_interp=1.0)
interpolated_array = grid_like_obj.ndarray_1d_from_grid(grid=grid_2d)
assert interpolated_array.shape[0] == mask.pixels_in_mask
assert (true_array == interpolated_array).all()
grid_2d = aa.Grid2DInterpolate.from_mask(mask=mask, pixel_scales_interp=0.1)
interpolated_array = grid_like_obj.ndarray_1d_from_grid(grid=grid_2d)
assert interpolated_array.shape[0] == mask.pixels_in_mask
assert true_array[0] != interpolated_array[0]
assert np.max(true_array - interpolated_array) < 0.001
grid_2d = aa.Grid2D.from_mask(mask=mask)
true_grid = grid_like_obj.ndarray_2d_from_grid(grid=grid_2d)
grid_2d = aa.Grid2DInterpolate.from_mask(mask=mask, pixel_scales_interp=1.0)
interpolated_grid = grid_like_obj.ndarray_2d_from_grid(grid=grid_2d)
assert interpolated_grid.shape[0] == mask.pixels_in_mask
assert interpolated_grid.shape[1] == 2
assert (true_grid == interpolated_grid).all()
grid_2d = aa.Grid2DInterpolate.from_mask(mask=mask, pixel_scales_interp=0.1)
interpolated_grid = grid_like_obj.ndarray_2d_from_grid(grid=grid_2d)
assert interpolated_grid.shape[0] == mask.pixels_in_mask
assert interpolated_grid.shape[1] == 2
assert true_grid[0, 0] != interpolated_grid[0, 0]
assert np.max(true_grid[:, 0] - interpolated_grid[:, 0]) < 0.001
assert np.max(true_grid[:, 1] - interpolated_grid[:, 1]) < 0.001
| 37.243396 | 96 | 0.581691 | 2,865 | 19,739 | 3.686562 | 0.039442 | 0.050559 | 0.064192 | 0.072714 | 0.939595 | 0.919902 | 0.919144 | 0.905984 | 0.888847 | 0.844348 | 0 | 0.077357 | 0.290086 | 19,739 | 529 | 97 | 37.3138 | 0.676372 | 0 | 0 | 0.633508 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.198953 | 1 | 0.036649 | false | 0 | 0.013089 | 0 | 0.054974 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
5c9bf83d0fc0b818e626ef55214126248344952c | 17,870 | py | Python | seizure detection code/Stacked Autoencoders for Seizure Detection/tests/plot_eeg.py | aimo84/epilepsy-system | de3b26039f76ce2ceac9a74a6bc179b8f7bddb1e | [
"BSD-3-Clause"
] | 13 | 2016-12-14T07:33:21.000Z | 2022-02-05T13:05:22.000Z | seizure detection code/Stacked Autoencoders for Seizure Detection/tests/plot_eeg.py | aimo84/epilepsy-system | de3b26039f76ce2ceac9a74a6bc179b8f7bddb1e | [
"BSD-3-Clause"
] | null | null | null | seizure detection code/Stacked Autoencoders for Seizure Detection/tests/plot_eeg.py | aimo84/epilepsy-system | de3b26039f76ce2ceac9a74a6bc179b8f7bddb1e | [
"BSD-3-Clause"
] | 6 | 2016-10-11T05:42:29.000Z | 2022-03-25T08:19:06.000Z | import math
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from scipy.io import loadmat
from scipy.signal import butter, filtfilt
from sklearn import preprocessing
from pylearn2ext.epilepsiae import EpilepsiaeDatasetExtractor
def gen_idx_range(src_idx, end_idx):
# Get around indexing problem of arange()
idx = src_idx + 1
# Create ndarray of index
idx_range = np.empty(idx.size + 1, dtype=object)
for i in range(idx_range.size):
if i == 0:
idx_range[i] = np.arange(idx[i])
elif i == idx_range.size - 1:
idx_range[i] = np.arange(idx[i - 1], end_idx)
else:
idx_range[i] = np.arange(idx[i - 1], idx[i])
return idx_range
def plot_eeg_seizure(X, channel_labels, seizure_seconds, sampling_rate,
interval_seconds=100, min_X=-1024, max_X=1024, is_scale=True,
figure_width=800, figure_height=600, figure_output_path='figure'):
# Metadata of the file
n_channels = X.shape[0]
n_data = X.shape[1]
# Butterworth filter
f_nyq = sampling_rate * 0.5
Wlow = 3 / f_nyq
Whigh = 30 / f_nyq
(b, a) = butter(4, [Wlow, Whigh], btype='bandpass')
data = filtfilt(b, a, X, axis=1)
# Preprocessing
if is_scale:
scaler = preprocessing.StandardScaler()
scaler = scaler.fit(data.transpose())
data = scaler.transform(data.transpose()).transpose()
# Seizure periods
idx_end_seizure_sample = np.where(np.diff(seizure_seconds) > 1)[0]
if idx_end_seizure_sample.size == 0:
idx_seizure_sample = [np.arange(seizure_seconds.size)]
else:
idx_seizure_sample = gen_idx_range(idx_end_seizure_sample, seizure_seconds.size)
# Display data
intervals_sample = interval_seconds * sampling_rate
n_intervals = int(math.ceil(n_data / (intervals_sample * 1.0)))
for i in range(n_intervals):
start_int_idx = i * intervals_sample
end_int_idx = (i+1) * intervals_sample
start_time = start_int_idx / sampling_rate
end_time = end_int_idx / sampling_rate
print('Plot figure for interval: ' + str(start_time) + ':' + str(end_time))
if end_int_idx > n_data:
end_int_idx = n_data
display_data = data[:,start_int_idx:end_int_idx]
n_display_data = display_data.shape[1]
# Time
t = (interval_seconds * (np.arange(n_display_data, dtype=float) / n_display_data)) + (i*interval_seconds)
# Figure properties
fig_dpi = 32
fig_width = figure_width/fig_dpi
fig_height = figure_height/fig_dpi
plt.figure(figsize=(fig_width, fig_height), dpi=fig_dpi)
# Adjust axes
ax = plt.gca()
plt.xlim([start_time, end_time])
plt.xticks(np.arange(start=start_time, stop=end_time, step=interval_seconds/10), fontsize=40)
if is_scale:
dmin = -5
dmax = 5
else:
dmin = min_X
dmax = max_X
dr = (dmax - dmin) * 0.95 # Crowd them a bit.
y0 = dmin
y1 = ((n_channels-1) * dr) + dmax
plt.ylim(y0, y1)
# Plot EEG from multiple channels
segs = []
ticklocs = []
offsets = np.zeros((n_channels,2), dtype=float)
for c in range(n_channels):
segs.append(np.hstack((t[:,np.newaxis], display_data[c,:,np.newaxis])))
ticklocs.append(c*dr)
offsets[:,1] = ticklocs
lines = LineCollection(segs,
offsets=offsets,
transOffset=None)
ax.add_collection(lines)
ax.set_yticks(ticklocs)
ax.set_yticklabels(channel_labels, fontsize=30)
# Highlight seizure period
for idx in idx_seizure_sample:
seizure_interval = np.intersect1d(seizure_seconds[idx], np.arange(start=start_time, stop=end_time))
if seizure_interval.size > 0:
if seizure_seconds[idx][0] in seizure_interval:
plt.axvline(seizure_interval[0], color='red', linewidth=4, linestyle='-')
if seizure_seconds[idx][-1] in seizure_interval:
plt.axvline(seizure_interval[-1], color='red', linewidth=4, linestyle='-')
# plt.axvspan(idx[0], idx[-1], color='red', alpha=0.3)
# else:
# plt.axvspan(idx[0], end_time, color='red', alpha=0.3)
plt.xlabel('Time (s)', fontsize=40)
plt.tight_layout()
plt.savefig(figure_output_path + '/' + str(i) + '.png')
def plot_eeg_predict_seizure(X, y, channel_labels, seizure_seconds, sampling_rate,
interval_seconds=100, min_X=-1024, max_X=1024, is_scale=True,
figure_width=800, figure_height=600, figure_output_path='figure'):
# Metadata of the file
n_channels = X.shape[0]
n_data = X.shape[1]
# # Butterworth filter
# f_nyq = sampling_rate * 0.5
# Wlow = 3 / f_nyq
# Whigh = 30 / f_nyq
# (b, a) = butter(4, [Wlow, Whigh], btype='bandpass')
# data = filtfilt(b, a, X, axis=1)
data = X
predict = y
# Preprocessing
if is_scale:
scaler = preprocessing.StandardScaler()
scaler = scaler.fit(data.transpose())
data = scaler.transform(data.transpose()).transpose()
# Seizure periods
idx_end_seizure_sample = np.where(np.diff(seizure_seconds) > 1)[0]
if idx_end_seizure_sample.size == 0:
idx_seizure_sample = [np.arange(seizure_seconds.size)]
else:
idx_seizure_sample = gen_idx_range(idx_end_seizure_sample, seizure_seconds.size)
# Display data
intervals_sample = interval_seconds * sampling_rate
n_intervals = int(math.ceil(n_data / (intervals_sample * 1.0)))
for i in range(n_intervals):
start_int_idx = i * intervals_sample
end_int_idx = (i+1) * intervals_sample
start_time = start_int_idx / sampling_rate
end_time = end_int_idx / sampling_rate
print('Plot figure for interval: ' + str(start_time) + ':' + str(end_time))
if end_int_idx > n_data:
end_int_idx = n_data
display_data = data[:,start_int_idx:end_int_idx]
display_predict = predict[start_int_idx:end_int_idx]
n_display_data = display_data.shape[1]
# Time
t = (interval_seconds * (np.arange(n_display_data, dtype=float) / n_display_data)) + (i*interval_seconds)
# Figure properties
fig_dpi = 32
fig_width = figure_width/fig_dpi
fig_height = figure_height/fig_dpi
plt.figure(figsize=(fig_width, fig_height), dpi=fig_dpi)
# Adjust axes
ax = plt.gca()
plt.xlim([start_time, end_time])
plt.xticks(np.arange(start=start_time, stop=end_time, step=interval_seconds/10), fontsize=25)
if is_scale:
dmin = -5
dmax = 5
else:
dmin = min_X
dmax = max_X
dr = (dmax - dmin) * 0.95 # Crowd them a bit.
y0 = dmin
y1 = ((n_channels-1) * dr) + dmax
plt.ylim(y0, y1)
# Plot EEG from multiple channels
segs = []
ticklocs = []
offsets = np.zeros((n_channels,2), dtype=float)
for c in range(n_channels):
segs.append(np.hstack((t[:,np.newaxis], display_data[c,:,np.newaxis])))
ticklocs.append(c*dr)
offsets[:,1] = ticklocs
lines = LineCollection(segs,
offsets=offsets,
transOffset=None)
ax.add_collection(lines)
ax.set_yticks(ticklocs)
ax.set_yticklabels(channel_labels, fontsize=25)
# Highlight seizure period
for idx in idx_seizure_sample:
seizure_interval = np.intersect1d(seizure_seconds[idx], np.arange(start=start_time, stop=end_time))
if seizure_interval.size > 0:
if seizure_seconds[idx][0] in seizure_interval:
plt.axvline(seizure_interval[0], color='red', linewidth=4, linestyle='-')
if seizure_seconds[idx][-1] in seizure_interval:
plt.axvline(seizure_interval[-1], color='red', linewidth=4, linestyle='-')
# plt.axvspan(idx[0], idx[-1], color='red', alpha=0.3)
# else:
# plt.axvspan(idx[0], end_time, color='red', alpha=0.3)
plt.xlabel('Time (s)', fontsize=30)
plt.ylabel('Scalp EEG Channels', fontsize=30)
plt.tight_layout()
plt.savefig(figure_output_path + '/' + str(i) + '_eeg.png')
# Figure properties
fig_dpi = 32
fig_width = figure_width/fig_dpi
fig_height = (figure_height/3)/fig_dpi
plt.figure(figsize=(fig_width, fig_height), dpi=fig_dpi)
plt.plot(t, display_predict, linewidth=4)
ax = plt.gca()
ax.yaxis.grid(True)
plt.ylim([0, 20])
plt.yticks(np.arange(start=5, stop=20, step=5), fontsize=25)
plt.xlim([start_time, end_time])
plt.xticks(np.arange(start=start_time, stop=end_time, step=interval_seconds/10), fontsize=25)
plt.ylabel('# of Seizure Ch.', fontsize=30)
plt.xlabel('Time (s)', fontsize=30)
plt.tight_layout()
plt.savefig(figure_output_path + '/' + str(i) + '_predict.png')
def plot_eeg_predict_seizure_period(X, y, channel_labels, seizure_seconds, sampling_rate,
start_second, end_second, min_X=-1024, max_X=1024, is_scale=True,
n_X_ticks=10, channel_th_y_lim=None,
figure_width=800, figure_height=600, figure_output_path='figure'):
# Metadata of the file
n_channels = X.shape[0]
n_data = X.shape[1]
# # Butterworth filter
# f_nyq = sampling_rate * 0.5
# Wlow = 3 / f_nyq
# Whigh = 30 / f_nyq
# (b, a) = butter(4, [Wlow, Whigh], btype='bandpass')
# data = filtfilt(b, a, X, axis=1)
data = X
predict = y
# Preprocessing
if is_scale:
scaler = preprocessing.StandardScaler()
scaler = scaler.fit(data.transpose())
data = scaler.transform(data.transpose()).transpose()
# Seizure periods
idx_end_seizure_sample = np.where(np.diff(seizure_seconds) > 1)[0]
if idx_end_seizure_sample.size == 0:
idx_seizure_sample = [np.arange(seizure_seconds.size)]
else:
idx_seizure_sample = gen_idx_range(idx_end_seizure_sample, seizure_seconds.size)
# Display data
start_int_idx = (start_second-1) * sampling_rate
end_int_idx = end_second * sampling_rate
start_time = start_second
end_time = end_second
interval_seconds = end_time - start_time + 1
print('Plot figure for interval: ' + str(start_time) + ':' + str(end_time))
if end_int_idx > n_data:
end_int_idx = n_data
display_data = data[:,start_int_idx:end_int_idx]
display_predict = predict[start_int_idx:end_int_idx]
n_display_data = display_data.shape[1]
# Time
t = (interval_seconds * (np.arange(n_display_data, dtype=float) / n_display_data)) + start_second
# Figure properties
fig_dpi = 32
fig_width = figure_width/fig_dpi
fig_height = figure_height/fig_dpi
plt.figure(figsize=(fig_width, fig_height), dpi=fig_dpi)
# Adjust axes
ax = plt.gca()
plt.xlim([start_time, end_time])
plt.xticks(np.arange(start=start_time, stop=end_time, step=interval_seconds/n_X_ticks), fontsize=25)
if is_scale:
dmin = -5
dmax = 5
else:
dmin = min_X
dmax = max_X
dr = (dmax - dmin) * 0.95 # Crowd them a bit.
y0 = dmin
y1 = ((n_channels-1) * dr) + dmax
plt.ylim(y0, y1)
# Add number of channel labels
channel_labels_nums = [channel_labels[i] + ' (' + str(i+1) + ')' for i in range(channel_labels.size)]
# Plot EEG from multiple channels
segs = []
ticklocs = []
offsets = np.zeros((n_channels,2), dtype=float)
for c in range(n_channels):
segs.append(np.hstack((t[:,np.newaxis], display_data[c,:,np.newaxis])))
ticklocs.append(c*dr)
offsets[:,1] = ticklocs
lines = LineCollection(segs,
offsets=offsets,
transOffset=None)
ax.add_collection(lines)
ax.set_yticks(ticklocs)
ax.set_yticklabels(channel_labels_nums, fontsize=25)
# Highlight seizure period
for idx in idx_seizure_sample:
seizure_interval = np.intersect1d(seizure_seconds[idx], np.arange(start=start_time, stop=end_time))
if seizure_interval.size > 0:
if seizure_seconds[idx][0] in seizure_interval:
plt.axvline(seizure_interval[0], color='red', linewidth=4, linestyle='-')
if seizure_seconds[idx][-1] in seizure_interval:
plt.axvline(seizure_interval[-1], color='red', linewidth=4, linestyle='-')
# plt.axvspan(idx[0], idx[-1], color='red', alpha=0.3)
# else:
# plt.axvspan(idx[0], end_time, color='red', alpha=0.3)
plt.xlabel('Time (s)', fontsize=30)
plt.ylabel('Scalp EEG Channels', fontsize=30)
plt.tight_layout()
plt.savefig(figure_output_path + '/' + 'eeg.png')
# Figure properties
fig_dpi = 32
fig_width = figure_width/fig_dpi
fig_height = (figure_height/3)/fig_dpi
plt.figure(figsize=(fig_width, fig_height), dpi=fig_dpi)
plt.plot(t, display_predict, linewidth=4)
ax = plt.gca()
ax.yaxis.grid(True)
plt.ylim(channel_th_y_lim)
plt.yticks(np.arange(start=5, stop=20, step=5), fontsize=25)
plt.xlim([start_time, end_time])
plt.xticks(np.arange(start=start_time, stop=end_time, step=interval_seconds/10), fontsize=25)
plt.ylabel('# of Seizure Ch.', fontsize=30)
plt.xlabel('Time (s)', fontsize=30)
plt.tight_layout()
plt.savefig(figure_output_path + '/' + 'predict.png')
def plot_chbmit_eeg(file_path):
# Load data from MATLAB file
mat = loadmat(file_path)
X = mat['X']
channel_labels = np.asarray([l[0][0] for l in mat['labels']])
seizure_seconds = mat['seizure_second'][0]
sampling_rate = mat['sampling_rate'][0, 0]
plot_eeg_seizure(X=X,
channel_labels=channel_labels,
seizure_seconds=seizure_seconds,
sampling_rate=sampling_rate,
interval_seconds=100,
is_scale=True,
figure_width=1500,
figure_height=1200,
figure_output_path='../figure')
def plot_epilepsiae_eeg(data_dir, filename, metafile):
# Get seizure information
seizure_info = pd.read_table(os.path.join(data_dir, metafile), sep='\t')
seizure_info['filename'] = seizure_info['filename'].str.replace('.data', '.mat', case=False)
data_ext = EpilepsiaeDatasetExtractor(patient_id=1, files=filename,
seizure_info=seizure_info,
data_dir=data_dir)
X, raw_labels, channel_labels, \
seizure_range_idx, seizure_range_second, seizure_seconds, \
n_channels, sample_size, sampling_rate = data_ext.load_source_data(sample_size_second=1)
plot_eeg_seizure(X=X,
channel_labels=channel_labels,
seizure_seconds=seizure_seconds,
sampling_rate=sampling_rate,
interval_seconds=100,
is_scale=True,
figure_width=1500,
figure_height=1200,
figure_output_path='../figure')
if __name__ == '__main__':
plot_chbmit_eeg(file_path=os.path.join('/Users/akara/Workspace/data/chbmit',
'chb20/chb20_12_mod.mat'))
# plot_epilepsiae_eeg(data_dir='/Users/akara/Workspace/data/epilepsiae',
# filename=['rec_26402102/26402102_0003.mat'],
# metafile='RECORDS-WITH-SEIZURES.txt')
# # Load data from MATLAB file
# mat = loadmat(os.path.join(data_dir, filename))
# X = mat['signals']
# channel_labels = np.asarray(mat['elec_names'][0][1:-1].split(','))
# sampling_rate = mat['sample_freq'][0, 0]
#
# # Get seizure information
# seizure_files = pd.read_table(os.path.join(data_dir, metafile), sep='\t')
# seizure_files['filename'] = seizure_files['filename'].str.replace('.data', '.mat', case=False)
#
# start_ts = datetime.datetime.strptime(mat['start_ts'][0], '%Y-%m-%d %H:%M:%S.%f')
# match_files = seizure_files[seizure_files['filename'].str.contains(filename)]
# seizure_seconds = np.empty(0, dtype=int)
# if match_files.shape[0] > 0:
# for index, row in match_files.iterrows():
# start_seizure_idx = row['onset_sample']
# end_seizure_idx = row['offset_sample']
#
# print 'Seizure ts:', row['onset'], row['offset']
# print 'Seizure samples:', start_seizure_idx, end_seizure_idx
#
# # Store index of seizure seconds
# start_seizure_second_idx = (start_seizure_idx) / (sampling_rate * 1.0)
# end_seizure_second_idx = (end_seizure_idx) / (sampling_rate * 1.0)
# _temp_seizure_seconds = np.arange(int(math.floor(start_seizure_second_idx)),
# int(math.ceil(end_seizure_second_idx)) + 1) # Plus 1 due to the nature of np.arange
# seizure_seconds = np.append(seizure_seconds, _temp_seizure_seconds)
#
# start_seizure_ts = start_ts + datetime.timedelta(seconds=_temp_seizure_seconds[0])
# end_seizure_ts = start_ts + datetime.timedelta(seconds=_temp_seizure_seconds[-1])
# print 'Figure start seizure:', start_seizure_ts
# print 'Figure end seizure:', end_seizure_ts | 38.183761 | 127 | 0.616452 | 2,364 | 17,870 | 4.405245 | 0.109983 | 0.047052 | 0.013828 | 0.01642 | 0.789034 | 0.778759 | 0.768965 | 0.754273 | 0.745919 | 0.743326 | 0 | 0.02508 | 0.265921 | 17,870 | 468 | 128 | 38.183761 | 0.768791 | 0.182093 | 0 | 0.774086 | 0 | 0 | 0.02976 | 0.003858 | 0 | 0 | 0 | 0 | 0 | 1 | 0.019934 | false | 0.003322 | 0.033223 | 0 | 0.056478 | 0.009967 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
7a8ca82e1dcb15a11978694c953adf3695976891 | 216 | py | Python | snm/specialities/admin.py | sparesnmechs/sparesnmechs | 44a7178fcfd0c89004d9f31734405c8d0fd5cd97 | [
"MIT"
] | null | null | null | snm/specialities/admin.py | sparesnmechs/sparesnmechs | 44a7178fcfd0c89004d9f31734405c8d0fd5cd97 | [
"MIT"
] | 9 | 2021-02-27T13:13:38.000Z | 2021-06-04T11:57:12.000Z | snm/specialities/admin.py | sparesnmechs/sparesnmechs | 44a7178fcfd0c89004d9f31734405c8d0fd5cd97 | [
"MIT"
] | null | null | null | """Speciality app admin."""
from django.contrib import admin
import snm.specialities.models as models
admin.site.register(models.Speciality)
admin.site.register(models.CarMake)
admin.site.register(models.CarModel)
| 24 | 40 | 0.810185 | 29 | 216 | 6.034483 | 0.517241 | 0.154286 | 0.291429 | 0.394286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.074074 | 216 | 8 | 41 | 27 | 0.875 | 0.097222 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.4 | 0 | 0.4 | 0 | 1 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
7a8f1ebf4cb632549b5ceff05da77eba42ab75bf | 709 | py | Python | updated_Wx_viwer/DDL_creater_projectfrm_home.py | WamdamProject/DDL_generator | 5e15e5d545f6c6a9905dcf60d8ed936f7de7699e | [
"BSD-3-Clause"
] | null | null | null | updated_Wx_viwer/DDL_creater_projectfrm_home.py | WamdamProject/DDL_generator | 5e15e5d545f6c6a9905dcf60d8ed936f7de7699e | [
"BSD-3-Clause"
] | null | null | null | updated_Wx_viwer/DDL_creater_projectfrm_home.py | WamdamProject/DDL_generator | 5e15e5d545f6c6a9905dcf60d8ed936f7de7699e | [
"BSD-3-Clause"
] | null | null | null | """Subclass of frm_home, which is generated by wxFormBuilder."""
import wx
import ddl
# Implementing frm_home
class DDL_creater_projectfrm_home( ddl.frm_home ):
def __init__( self, parent ):
ddl.frm_home.__init__( self, parent )
# Handlers for frm_home events.
def filePicker_xmlfileOnFileChanged( self, event ):
# TODO: Implement filePicker_xmlfileOnFileChanged
pass
def dirPicker_DDLfilesOnDirChanged( self, event ):
# TODO: Implement dirPicker_DDLfilesOnDirChanged
pass
def button_generateOnButtonClick( self, event ):
# TODO: Implement button_generateOnButtonClick
pass
def button_cancelOnButtonClick( self, event ):
# TODO: Implement button_cancelOnButtonClick
pass
| 24.448276 | 64 | 0.77574 | 79 | 709 | 6.658228 | 0.43038 | 0.06654 | 0.098859 | 0.1673 | 0.106464 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.156559 | 709 | 28 | 65 | 25.321429 | 0.879599 | 0.414669 | 0 | 0.307692 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.035714 | 0 | 1 | 0.384615 | false | 0.307692 | 0.153846 | 0 | 0.615385 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 6 |
7a9e226ad430772f4aabe89431298b7bf1144288 | 98 | py | Python | modules/globals.py | alexp25/proiect-intersectie | 010c4639be037a2bbf7d9cfa0881d735a426f6d3 | [
"MIT"
] | null | null | null | modules/globals.py | alexp25/proiect-intersectie | 010c4639be037a2bbf7d9cfa0881d735a426f6d3 | [
"MIT"
] | null | null | null | modules/globals.py | alexp25/proiect-intersectie | 010c4639be037a2bbf7d9cfa0881d735a426f6d3 | [
"MIT"
] | null | null | null | import traceback
def print_exception(msg):
print(msg + " - " + traceback.format_exc())
| 16.333333 | 48 | 0.642857 | 11 | 98 | 5.545455 | 0.727273 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.22449 | 98 | 5 | 49 | 19.6 | 0.802632 | 0 | 0 | 0 | 0 | 0 | 0.032609 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0.333333 | 0 | 0.666667 | 0.666667 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 6 |
7aba97f70d548047e42940707abcf6eeac2a27bb | 126 | py | Python | datacatalog/linkedstores/file/__init__.py | SD2E/python-datacatalog | 51ab366639505fb6e8a14cd6b446de37080cd20d | [
"CNRI-Python"
] | null | null | null | datacatalog/linkedstores/file/__init__.py | SD2E/python-datacatalog | 51ab366639505fb6e8a14cd6b446de37080cd20d | [
"CNRI-Python"
] | 2 | 2019-07-25T15:39:04.000Z | 2019-10-21T15:31:46.000Z | datacatalog/linkedstores/file/__init__.py | SD2E/python-datacatalog | 51ab366639505fb6e8a14cd6b446de37080cd20d | [
"CNRI-Python"
] | 1 | 2019-10-15T14:33:44.000Z | 2019-10-15T14:33:44.000Z | from .store import FileRecord, FileDocument, FileStore, StoreInterface, DEFAULT_LINK_FIELDS
from .store import infer_filetype
| 42 | 91 | 0.857143 | 15 | 126 | 7 | 0.8 | 0.171429 | 0.285714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.095238 | 126 | 2 | 92 | 63 | 0.921053 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8f888f2406cab1a0a498f407b0ad2a2661e4b007 | 39 | py | Python | main.py | JirayuL/ske14 | 922686033afbb462169cbd38c76925add5cc4b7e | [
"Unlicense"
] | null | null | null | main.py | JirayuL/ske14 | 922686033afbb462169cbd38c76925add5cc4b7e | [
"Unlicense"
] | 11 | 2019-10-01T09:27:20.000Z | 2020-10-14T17:53:12.000Z | main.py | JirayuL/ske14 | 922686033afbb462169cbd38c76925add5cc4b7e | [
"Unlicense"
] | 9 | 2019-10-01T08:48:08.000Z | 2020-10-27T01:54:41.000Z | import ske14
print('Hello from ske14')
| 13 | 25 | 0.769231 | 6 | 39 | 5 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.117647 | 0.128205 | 39 | 2 | 26 | 19.5 | 0.764706 | 0 | 0 | 0 | 0 | 0 | 0.410256 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0.5 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 6 |
8f9a22bbb8b7a0e93348b34a8dac0281d0f174bc | 6,467 | py | Python | onener/transformer/auto_model.py | sansan-inc/OneNER | 4e13ff7a1a990dcbf3c7b7fb1945aacdfa30abe3 | [
"Apache-2.0"
] | 2 | 2021-10-11T05:30:44.000Z | 2021-12-16T07:46:28.000Z | onener/transformer/auto_model.py | sansan-inc/OneNER | 4e13ff7a1a990dcbf3c7b7fb1945aacdfa30abe3 | [
"Apache-2.0"
] | null | null | null | onener/transformer/auto_model.py | sansan-inc/OneNER | 4e13ff7a1a990dcbf3c7b7fb1945aacdfa30abe3 | [
"Apache-2.0"
] | null | null | null | from collections import OrderedDict
from transformers import BertConfig
from transformers import AutoConfig, PretrainedConfig
from .models.baseline_ner import BertBaselineForNer
from .models.mlp_ner import BertMlpForNer
from .models.crf_ner import BertCrfForNer
MODEL_LIST = [
"AutoModelForBaselineNer",
"AutoModelForMlpNer",
"AutoModelForCrfNer"
]
MODEL_FOR_BASELINE_NER_MAPPING = OrderedDict(
[
(BertConfig, BertBaselineForNer),
]
)
MODEL_FOR_MLP_NER_MAPPING = OrderedDict(
[
(BertConfig, BertMlpForNer),
]
)
MODEL_FOR_CRF_NER_MAPPING = OrderedDict(
[
(BertConfig, BertCrfForNer),
]
)
class AutoModelForBaselineNer:
def __init__(self):
raise EnvironmentError(
"AutoModelForTokenClassification is designed to be instantiated "
"using the `AutoModelForTokenClassification.from_pretrained(pretrained_model_name_or_path)` or "
"`AutoModelForTokenClassification.from_config(config)` methods."
)
@classmethod
def from_config(cls, config):
for config_class, model_class in MODEL_FOR_BASELINE_NER_MAPPING.items():
if isinstance(config, config_class):
return model_class(config)
raise ValueError(
"Unrecognized configuration class {} for this kind of AutoModel: {}.\n"
"Model type should be one of {}.".format(
config.__class__,
cls.__name__,
", ".join(c.__name__ for c in MODEL_FOR_MLP_NER_MAPPING.keys()),
)
)
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
config = kwargs.pop("config", None)
if not isinstance(config, PretrainedConfig):
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
for config_class, model_class in MODEL_FOR_BASELINE_NER_MAPPING.items():
if isinstance(config, config_class):
return model_class.from_pretrained(pretrained_model_name_or_path,
*model_args,
config=config,
**kwargs)
raise ValueError(
"Unrecognized configuration class {} for this kind of AutoModel: {}.\n"
"Model type should be one of {}.".format(
config.__class__,
cls.__name__,
", ".join(c.__name__ for c in MODEL_FOR_MLP_NER_MAPPING.keys()),
)
)
class AutoModelForMlpNer:
def __init__(self):
raise EnvironmentError(
"AutoModelForTokenClassification is designed to be instantiated "
"using the `AutoModelForTokenClassification.from_pretrained(pretrained_model_name_or_path)` or "
"`AutoModelForTokenClassification.from_config(config)` methods."
)
@classmethod
def from_config(cls, config):
for config_class, model_class in MODEL_FOR_MLP_NER_MAPPING.items():
if isinstance(config, config_class):
return model_class(config)
raise ValueError(
"Unrecognized configuration class {} for this kind of AutoModel: {}.\n"
"Model type should be one of {}.".format(
config.__class__,
cls.__name__,
", ".join(c.__name__ for c in MODEL_FOR_MLP_NER_MAPPING.keys()),
)
)
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
config = kwargs.pop("config", None)
if not isinstance(config, PretrainedConfig):
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
for config_class, model_class in MODEL_FOR_MLP_NER_MAPPING.items():
if isinstance(config, config_class):
return model_class.from_pretrained(pretrained_model_name_or_path,
*model_args,
config=config,
**kwargs)
raise ValueError(
"Unrecognized configuration class {} for this kind of AutoModel: {}.\n"
"Model type should be one of {}.".format(
config.__class__,
cls.__name__,
", ".join(c.__name__ for c in MODEL_FOR_MLP_NER_MAPPING.keys()),
)
)
class AutoModelForCrfNer:
def __init__(self):
raise EnvironmentError(
"AutoModelForTokenClassification is designed to be instantiated "
"using the `AutoModelForTokenClassification.from_pretrained(pretrained_model_name_or_path)` or "
"`AutoModelForTokenClassification.from_config(config)` methods."
)
@classmethod
def from_config(cls, config):
for config_class, model_class in MODEL_FOR_CRF_NER_MAPPING.items():
if isinstance(config, config_class):
return model_class(config)
raise ValueError(
"Unrecognized configuration class {} for this kind of AutoModel: {}.\n"
"Model type should be one of {}.".format(
config.__class__,
cls.__name__,
", ".join(c.__name__ for c in MODEL_FOR_CRF_NER_MAPPING.keys()),
)
)
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
config = kwargs.pop("config", None)
if not isinstance(config, PretrainedConfig):
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
for config_class, model_class in MODEL_FOR_CRF_NER_MAPPING.items():
if isinstance(config, config_class):
return model_class.from_pretrained(pretrained_model_name_or_path,
*model_args,
config=config,
**kwargs)
raise ValueError(
"Unrecognized configuration class {} for this kind of AutoModel: {}.\n"
"Model type should be one of {}.".format(
config.__class__,
cls.__name__,
", ".join(c.__name__ for c in MODEL_FOR_CRF_NER_MAPPING.keys()),
)
)
| 37.818713 | 108 | 0.598423 | 627 | 6,467 | 5.783094 | 0.111643 | 0.054606 | 0.062879 | 0.069498 | 0.871484 | 0.85273 | 0.85273 | 0.85273 | 0.85273 | 0.85273 | 0 | 0 | 0.323179 | 6,467 | 170 | 109 | 38.041176 | 0.828421 | 0 | 0 | 0.692308 | 0 | 0 | 0.208134 | 0.079635 | 0 | 0 | 0 | 0 | 0 | 1 | 0.062937 | false | 0 | 0.041958 | 0 | 0.167832 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
8fba509e6e497f7cce90fabdae3d7d3e35ad3797 | 12,319 | py | Python | QGL/BasicSequences/CR.py | ty-zhao/QGL | b3d642d1fe7e109ca2085436fc1ecadbd1671b74 | [
"Apache-2.0"
] | 33 | 2016-01-29T20:25:08.000Z | 2021-11-17T11:41:26.000Z | QGL/BasicSequences/CR.py | ty-zhao/QGL | b3d642d1fe7e109ca2085436fc1ecadbd1671b74 | [
"Apache-2.0"
] | 261 | 2016-01-22T02:35:16.000Z | 2021-07-01T17:06:46.000Z | QGL/BasicSequences/CR.py | ty-zhao/QGL | b3d642d1fe7e109ca2085436fc1ecadbd1671b74 | [
"Apache-2.0"
] | 9 | 2016-01-22T20:17:42.000Z | 2020-12-24T00:36:03.000Z | from ..PulsePrimitives import *
from ..Compiler import compile_to_hardware
from ..ChannelLibraries import EdgeFactory
from ..PulseSequencePlotter import plot_pulse_files
from .helpers import create_cal_seqs, delay_descriptor, cal_descriptor
import numpy as np
from itertools import product
from typing import Iterable, Union
def PiRabi(controlQ: Channels.LogicalChannel,
targetQ: Channels.LogicalChannel,
lengths: Iterable[Union[int,float]],
riseFall: Union[int,float] = 40e-9,
amp: Union[int,float] = 1,
phase: Union[int,float] = 0,
calRepeats: int = 2,
showPlot: bool = False) -> str:
"""
Variable length CX experiment.
Parameters
----------
controlQ : Channels.LogicalChannel
Logical channel for the control qubit
targetQ: Channels.LogicalChannel
Logical channel for the target qubit
lengths : int/float iterable
Pulse lengths of the CR pulse to sweep over (seconds). 4 ns minimum.
riseFall : float, optional
Rise/fall time of the CR pulse (seconds)
amp : float, optional
Amplitude of the CR pulse. Valid range: [0.0, 1.0].
phase : float, optional
Phase of the CR pulse (radians)
showPlot : boolean, optional
Whether to plot
Returns
-------
metafile : string
Path to a json metafile with details about the sequences and paths
to compiled machine files.
Examples
--------
>>> mf = PiRabi(q1, q2, np.linspace(20.0e-9, 200.02e-6, 101));
Compiled 210 sequences.
>>> mf
'/path/to/exp/exp-meta.json'
"""
CRchan = EdgeFactory(controlQ, targetQ)
seqs = [[Id(controlQ),
flat_top_gaussian(CRchan, riseFall, amp=amp, phase=phase, length=l),
MEAS(targetQ)*MEAS(controlQ)] for l in lengths] + \
[[X(controlQ),
flat_top_gaussian(CRchan, riseFall, amp=amp, phase=phase, length=l),
X(controlQ),
MEAS(targetQ)*MEAS(controlQ)] for l in lengths] + \
create_cal_seqs([targetQ,controlQ], calRepeats, measChans=(targetQ,controlQ))
metafile = compile_to_hardware(seqs, 'PiRabi/PiRabi',
axis_descriptor=[
delay_descriptor(np.concatenate((lengths, lengths))),
cal_descriptor((controlQ, targetQ), calRepeats)
])
if showPlot:
plot_pulse_files(metafile)
return metafile
def EchoCRLen(controlQ: Channels.LogicalChannel,
targetQ: Channels.LogicalChannel,
lengths: Iterable[Union[int,float]],
riseFall: Union[int,float] = 40e-9,
amp: Union[int,float] = 1,
phase: Union[int,float] = 0,
calRepeats: int = 2,
showPlot: bool = False,
canc_amp: Union[int,float] = 0,
canc_phase: Union[int,float] = np.pi/2) -> str:
"""
Variable length CX experiment, with echo pulse sandwiched between two CR
opposite-phase pulses. This is primarily used as a subroutine
in calibration.
Parameters
----------
controlQ : Channels.LogicalChannel
Logical channel for the control qubit
targetQ : Channels.LogicalChannel
Logical channel for the target qubit
lengths : int/float iterable
Pulse lengths of the CR pulse to sweep over (seconds)
riseFall : float, optional
Rise/fall time of the CR pulse (seconds)
amp : float, optional
Amplitude of the CR pulse. Valid range: [0.0, 1.0].
phase : float, optional
Phase of the CR pulse (radian)
calRepeats : int, optional
Number of calibrations repeats for each 2-qubit state basis state
showPlot : boolean, optional
Whether to plot
Returns
-------
metafile : string
Path to a json metafile with details about the sequences and paths
to compiled machine files
Examples
--------
>>> mf = EchoCRLen(q1, q2, np.linspace(20.0e-9, 200.02e-6, 101));
Compiled 210 sequences.
>>> mf
'/path/to/exp/exp-meta.json'
"""
seqs = [[Id(controlQ),
echoCR(controlQ, targetQ, length=l, phase=phase, amp=amp, riseFall=riseFall, canc_amp=canc_amp, canc_phase=canc_phase),
Id(controlQ),
MEAS(targetQ)*MEAS(controlQ)] for l in lengths] + \
[[X(controlQ),
echoCR(controlQ, targetQ, length=l, phase= phase, amp=amp, riseFall=riseFall, canc_amp=canc_amp, canc_phase=canc_phase),
X(controlQ),
MEAS(targetQ)*MEAS(controlQ)] for l in lengths] + \
create_cal_seqs((controlQ,targetQ), calRepeats, measChans=(targetQ,controlQ))
metafile = compile_to_hardware(seqs, 'EchoCR/EchoCR',
axis_descriptor=[
delay_descriptor(np.concatenate((lengths, lengths))),
cal_descriptor((controlQ, targetQ), calRepeats)
])
if showPlot:
plot_pulse_files(metafile)
return metafile
def EchoCRPhase(controlQ: Channels.LogicalChannel,
targetQ: Channels.LogicalChannel,
phases: Iterable[Union[int,float]],
riseFall: Union[int,float] = 40e-9,
amp: Union[int,float] = 1,
length: Union[int,float] = 100e-9,
calRepeats: int = 2,
showPlot: bool = False,
canc_amp: Union[int,float] = 0,
canc_phase: Union[int,float] = np.pi/2) -> str:
"""
Variable phase CX experiment, with echo pulse sandwiched between two CR
opposite-phase pulses. This is primarily used as a subroutine
in calibration.
Parameters
----------
controlQ : Channels.LogicalChannel
Logical channel for the control qubit
targetQ : Channels.LogicalChannel
Logical channel for the target qubit
phases : float iterable
Pulse phases of the CR pulse to sweep over (radians)
riseFall : float, optional
Rise/fall time of the CR pulse (seconds)
amp : float, optional
Amplitude of the CR pulse. Valid range: [0.0, 1.0].
length : float, optional
Duration of each of the two flat parts of the CR pulse (seconds)
calRepeats : int, optional
Number of calibrations repeats for each 2-qubit state basis state
showPlot : boolean, optional
Whether to plot
Returns
-------
metafile : string
Path to a json metafile with details about the sequences and paths
to compiled machine files
Examples
--------
>>> mf = EchoCRPhase(q1, q2, np.linspace(0.0, np.pi, 51));
Compiled 110 sequences.
>>> mf
'/path/to/exp/exp-meta.json'
"""
seqs = [[Id(controlQ),
echoCR(controlQ, targetQ, length=length, phase=ph, amp=amp, riseFall=riseFall, canc_amp=canc_amp, canc_phase=canc_phase),
X90(targetQ)*Id(controlQ),
MEAS(targetQ)*MEAS(controlQ)] for ph in phases] + \
[[X(controlQ),
echoCR(controlQ, targetQ, length=length, phase= ph, amp=amp, riseFall = riseFall, canc_amp=canc_amp, canc_phase=canc_phase),
X90(targetQ)*X(controlQ),
MEAS(targetQ)*MEAS(controlQ)] for ph in phases] + \
create_cal_seqs((controlQ, targetQ), calRepeats, measChans=(targetQ,controlQ))
axis_descriptor = [
{
'name': 'phase',
'unit': 'radians',
'points': list(phases)+list(phases),
'partition': 1
},
cal_descriptor((controlQ, targetQ), calRepeats)
]
metafile = compile_to_hardware(seqs, 'EchoCR/EchoCR',
axis_descriptor=axis_descriptor)
if showPlot:
plot_pulse_files(metafile)
return metafile
def EchoCRAmp(controlQ: Channels.LogicalChannel,
targetQ: Channels.LogicalChannel,
amps: Iterable[Union[int,float]],
riseFall: Union[int,float] = 40e-9,
length: Union[int,float] = 50e-9,
phase: Union[int,float] = 0,
calRepeats: int = 2,
showPlot: bool = False) -> str:
"""
Variable amplitude CX experiment, with echo pulse sandwiched between two
CR opposite-phase pulses.
Parameters
----------
controlQ : Channels.LogicalChannel
Logical channel for the control qubit
targetQ : Channels.LogicalChannel
Logical channel for the target qubit
amps : float iterable
Pulse amplitudes of the CR pulse to sweep over. Valid range: [0.0, 1.0]
riseFall : float, optional
Rise/fall time of the CR pulse (seconds)
length : float, optional
Duration of each of the two flat parts of the CR pulse (seconds)
phase : float, optional
Phase of the CR pulse (radians)
calRepeats : int, optional
Number of calibrations repeats for each 2-qubit state basis state
showPlot : whether to plot (boolean)
Returns
-------
metafile : path to a json metafile with details about the sequences and paths to compiled machine files
Examples
--------
>>> mf = EchoCRAmp(q1, q2, np.linspace(0.7, 0.9, 101));
Compiled 105 sequences.
>>> mf
'/path/to/exp/exp-meta.json'
"""
seqs = [[Id(controlQ),
echoCR(controlQ, targetQ, length=length, phase=phase, riseFall=riseFall,amp=a),
Id(controlQ),
MEAS(targetQ)*MEAS(controlQ)] for a in amps] + \
[[X(controlQ),
echoCR(controlQ, targetQ, length=length, phase= phase, riseFall=riseFall,amp=a),
X(controlQ),
MEAS(targetQ)*MEAS(controlQ)] for a in amps] + \
create_cal_seqs((controlQ ,targetQ), calRepeats, measChans=(targetQ,controlQ))
axis_descriptor = [
{
'name': 'amplitude',
'unit': None,
'points': list(amps)+list(amps),
'partition': 1
},
cal_descriptor((controlQ, targetQ), calRepeats)
]
metafile = compile_to_hardware(seqs, 'EchoCR/EchoCR',
axis_descriptor=axis_descriptor)
if showPlot:
plot_pulse_files(metafile)
return metafile
def CRtomo_seq(controlQ: Channels.LogicalChannel,
targetQ: Channels.LogicalChannel,
lengths: Iterable[Union[int,float]],
phase: Union[int,float],
amp: Union[int,float] = 0.8,
riseFall: Union[int,float] = 20e-9,
calRepeats: int = 2) -> str:
"""
Variable length CX experiment, for Hamiltonian tomography.
Parameters
----------
controlQ : Channels.LogicalChannel
Logical channel for the control qubit
targetQ : Channels.LogicalChannel
Logical channel for the target qubit
lengths : int/float iterable
Pulse lengths of the CR pulse to sweep over (seconds)
phase : float
Phase of the CR pulse (radians)
amps : float, optional
Pulse amplitude of the CR pulse. Valid range: [0.0, 1.0]
riseFall : float, optional
Rise/fall time of the CR pulse (seconds)
calRepeats : int, optional
Number of calibrations repeats for each 2-qubit state basis state
Returns
-------
metafile : string
Path to a json metafile with details about the sequences and paths
to compiled machine files
Examples
--------
>>> mf = CRtomo_seq(q2, q3, np.linspace(20.0e-9, 200.02e-6, 101), \
phase=0.0);
Compiled 610 sequences.
>>> mf
'/path/to/exp/exp-meta.json'
"""
CRchan = ChannelLibraries.EdgeFactory(controlQ, targetQ)
tomo_pulses = [Y90m, X90, Id]
seqs = [[Id(controlQ),
flat_top_gaussian(CRchan, amp=amp, riseFall=riseFall, length=l, phase=phase, label="CR"),
Id(controlQ)*tomo_pulse(targetQ),
MEAS(targetQ)] for l,tomo_pulse in product(lengths, tomo_pulses)] + \
[[X(controlQ),
flat_top_gaussian(CRchan, amp=amp, riseFall=riseFall, length=l, phase=phase, label="CR"),
X(controlQ)*tomo_pulse(targetQ),
MEAS(targetQ)] for l,tomo_pulse in product(lengths, tomo_pulses)] + \
create_cal_seqs((targetQ,), 2,)
metafile = compile_to_hardware(seqs, 'CR/CR',
axis_descriptor=[
delay_descriptor(np.concatenate((np.repeat(lengths,3), np.repeat(lengths,3)))),
cal_descriptor((targetQ,), 2)
])
return metafile
| 35.707246 | 137 | 0.619612 | 1,463 | 12,319 | 5.155844 | 0.121668 | 0.028636 | 0.041363 | 0.031818 | 0.865968 | 0.853507 | 0.824208 | 0.815458 | 0.815193 | 0.7558 | 0 | 0.017346 | 0.274616 | 12,319 | 344 | 138 | 35.811047 | 0.826768 | 0.40539 | 0 | 0.689189 | 0 | 0 | 0.018632 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.033784 | false | 0 | 0.054054 | 0 | 0.121622 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
8fddf4534d8e0bcb0f6d3c7c47a4ee513825156d | 192 | py | Python | nmigen_boards/extensions/__init__.py | lethalbit/nmigen-boards | aaf18252e457ff95257137da2a629820c0ff2bfa | [
"BSD-2-Clause"
] | 11 | 2021-12-10T12:23:29.000Z | 2022-03-13T08:40:20.000Z | nmigen_boards/extensions/__init__.py | lethalbit/nmigen-boards | aaf18252e457ff95257137da2a629820c0ff2bfa | [
"BSD-2-Clause"
] | 12 | 2021-12-11T18:51:29.000Z | 2022-03-12T05:08:52.000Z | nmigen_boards/extensions/__init__.py | lethalbit/nmigen-boards | aaf18252e457ff95257137da2a629820c0ff2bfa | [
"BSD-2-Clause"
] | 7 | 2021-12-12T07:20:21.000Z | 2022-03-06T06:20:55.000Z | from amaranth_boards.extensions import *
import warnings
warnings.warn("instead of nmigen_boards.extensions, use amaranth_boards.extensions",
DeprecationWarning, stacklevel=2)
| 27.428571 | 84 | 0.78125 | 21 | 192 | 7 | 0.666667 | 0.326531 | 0.326531 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006135 | 0.151042 | 192 | 6 | 85 | 32 | 0.895706 | 0 | 0 | 0 | 0 | 0 | 0.348958 | 0.265625 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
8fe4efb170d0a9968f7fbf9b9b3b793b7164cc48 | 26 | py | Python | mailgun/utils.py | haoruiqian/mailgun-py | 304fdb1d7816c16a46a1fc57e8eca56fc35f4a78 | [
"MIT"
] | null | null | null | mailgun/utils.py | haoruiqian/mailgun-py | 304fdb1d7816c16a46a1fc57e8eca56fc35f4a78 | [
"MIT"
] | null | null | null | mailgun/utils.py | haoruiqian/mailgun-py | 304fdb1d7816c16a46a1fc57e8eca56fc35f4a78 | [
"MIT"
] | null | null | null |
from settings import *
| 5.2 | 22 | 0.692308 | 3 | 26 | 6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | 26 | 4 | 23 | 6.5 | 0.947368 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8fe8906ec541fd07f0129323f455f6c44281afb2 | 12,141 | py | Python | main.py | wkd3475/hpa-simulator | 829a62af07744b21ce98440827a2e3bc78a2cdc5 | [
"MIT"
] | 1 | 2021-09-09T08:10:48.000Z | 2021-09-09T08:10:48.000Z | main.py | wkd3475/hpa-simulator | 829a62af07744b21ce98440827a2e3bc78a2cdc5 | [
"MIT"
] | null | null | null | main.py | wkd3475/hpa-simulator | 829a62af07744b21ce98440827a2e3bc78a2cdc5 | [
"MIT"
] | null | null | null | from simulator.simulator import *
from autoscaler import *
import csv
import datetime
import math
import sys
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout, QLabel, QLineEdit, QTextEdit, QPushButton)
def application_profile(num_of_pods):
return 66.5 + 52.2/num_of_pods
def run_HPA(test_env_config, hpa_config):
scaler = HPA(hpa_config)
env = Environment(test_env_config)
for i in range(100000):
state = env.next_state()
if state == False:
print("max iter : " + str(i))
break
action = scaler.get_action(state)
env.scale_to(action)
# simulator.print_result()
# env.save_result('./result/advanced.csv')
env.print_result()
def offline_q_learning(scaler, env_config, rl, mode):
env = Environment(env_config)
s = None
a = None
r_prev = None
s_prev = None
a_prev = None
for i in range(100000):
obs = env.next_state()
if obs == False:
# print("max iter : " + str(i))
break
s, r_prev = scaler.monitoring(obs)
a = scaler.get_action(s)
if rl == "q_learning":
env.scale_to(scaler.action_to_desired(a))
elif rl == "q_leanring_fixed_action":
env.scale(scaler.action_to_desired(a))
elif rl == "q_learning_trend":
env.scale_to(scaler.action_to_desired(a))
if s_prev is not None:
if mode == "train":
scaler.update(s_prev, a_prev, r_prev, s)
s_prev = s
a_prev = a
return env
def online_q_learning(scaler, env_config, rl):
scaler.epsilon = 1.0
env = Environment(env_config)
s = None
a = None
r_prev = None
s_prev = None
a_prev = None
for i in range(100000):
obs = env.next_state()
if obs == False:
# print("max iter : " + str(i))
break
s, r_prev = scaler.monitoring(obs)
a = scaler.get_action_with_noisy(s)
if rl == "q_learning":
env.scale_to(scaler.action_to_desired(a))
elif rl == "q_leanring_fixed_action":
env.scale(scaler.action_to_desired(a))
elif rl == "q_learning_trend":
env.scale_to(scaler.action_to_desired(a))
if s_prev is not None:
scaler.update(s_prev, a_prev, r_prev, s)
s_prev = s
a_prev = a
if i % 100 == 0:
scaler.epsilon_decay()
return env
def offline_sarsa(scaler, env_config, rl, mode):
env = Environment(env_config)
s = None
a = None
r_prev = None
s_prev = None
a_prev = None
obs = env.next_state()
s_prev, r_prev = scaler.monitoring(obs)
a_prev = scaler.get_action(s_prev)
for i in range(100000):
if rl == "sarsa":
env.scale_to(scaler.action_to_desired(a_prev))
obs = env.next_state()
if obs == False:
# print("max iter : " + str(i))
break
s, r_prev = scaler.monitoring(obs)
a = scaler.get_action(s)
if mode == "train":
scaler.update(s_prev, a_prev, r_prev, s, a)
s_prev = s
a_prev = a
return env
def online_sarsa(scaler, env_config, rl):
scaler.epsilon = 1.0
env = Environment(env_config)
s = None
a = None
r_prev = None
s_prev = None
a_prev = None
obs = env.next_state()
s_prev, r_prev = scaler.monitoring(obs)
a_prev = scaler.get_action_with_noisy(s_prev)
for i in range(100000):
if rl == "sarsa":
env.scale_to(scaler.action_to_desired(a_prev))
obs = env.next_state()
if obs == False:
# print("max iter : " + str(i))
break
s, r_prev = scaler.monitoring(obs)
a = scaler.get_action_with_noisy(s)
scaler.update(s_prev, a_prev, r_prev, s, a)
s_prev = s
a_prev = a
if i % 100 == 0:
scaler.epsilon_decay()
return env
def run_HPA_Q_Learning(test_env_config, train_env_config, rl_config, rl):
scaler = None
if rl == "q_learning":
scaler = HPA_Q_Learning(rl_config)
elif rl == "q_leanring_fixed_action":
scaler = HPA_Q_Learning_Fixed_Action(rl_config)
elif rl == "q_learning_trend":
scaler = HPA_Q_Learning_Trend(rl_config)
else:
print(f"no such rl algorithm : {rl}")
return
env = None
x = []
result_history = []
for j in range(1, 101):
print("train : "+str(j))
train_env = offline_q_learning(scaler, train_env_config, rl, "train")
eval_env = offline_q_learning(scaler, test_env_config, rl, "eval")
scaler.epsilon_decay()
_, _, cost, _ = eval_env.get_result()
result_history.append(cost)
x.append(j)
eval_env.print_result()
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax1.plot(x, result_history, 'r', label='total rewards')
plt.show()
print("last : "+str(j))
env = online_q_learning(scaler, test_env_config, rl)
env.plot_result()
e, r, c, u, it, A, E, C = env.get_everything()
result = [e, r, c, u]
now = datetime.datetime.now()
nowTime = now.strftime('%H_%M_%S')
filename = rl+'_'+str(test["rate"])+'_t'+nowTime
with open(f'./result/test4/{filename}.csv', 'w', newline='') as csvfile:
wr = csv.writer(csvfile)
wr.writerow(result_history)
wr.writerow(result)
wr.writerow(it)
wr.writerow(A)
wr.writerow(E)
wr.writerow(C)
def run_HPA_SARSA(test_env_config, train_env_config, rl_config, rl):
scaler = None
if rl == "sarsa":
scaler = HPA_SARSA(rl_config)
else:
print(f"no such rl algorithm : {rl}")
return
env = None
x = []
result_history = []
for j in range(1, 101):
print("train : "+str(j))
train_env = offline_sarsa(scaler, train_env_config, rl, "train")
eval_env = offline_sarsa(scaler, test_env_config, rl, "eval")
scaler.epsilon_decay()
_, _, cost, _ = eval_env.get_result()
result_history.append(cost)
x.append(j)
eval_env.print_result()
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax1.plot(x, result_history, 'r', label='total rewards')
plt.show()
print("last : "+str(j))
env = online_sarsa(scaler, test_env_config, rl)
env.plot_result()
e, r, c, u, it, A, E, C = env.get_everything()
result = [e, r, c, u]
now = datetime.datetime.now()
nowTime = now.strftime('%H_%M_%S')
filename = rl+'_'+str(test["rate"])+'_t'+nowTime
with open(f'./result/test4/{filename}.csv', 'w', newline='') as csvfile:
wr = csv.writer(csvfile)
wr.writerow(result_history)
wr.writerow(result)
wr.writerow(it)
wr.writerow(A)
wr.writerow(E)
wr.writerow(C)
def run_HPA_Q_Learning_v3(test_env_config, train_env_config, rl_config):
scaler = HPA_Q_Learning_v3(rl_config)
env = None
x = []
result_history = []
for j in range(1000):
print("train : "+str(j))
env = Environment(train_env_config)
s = None
a = None
r = None
s_prev = None
a_prev = None
for i in range(100000):
obs = env.next_state()
if obs == False:
# print("max iter : " + str(i))
break
s, r = scaler.convert_obs(obs)
a = scaler.get_action(s)
env.scale_to(a)
if i > 0:
scaler.update(s_prev, a_prev, s, r)
s_prev = s
a_prev = a
scaler.epsilon_decay()
env = Environment(test_env_config)
s = None
a = None
r = None
s_prev = None
a_prev = None
for i in range(10000):
obs = env.next_state()
if obs == False:
# print("max iter : " + str(i))
break
s, r = scaler.convert_obs(obs)
a = scaler.get_action(s)
env.scale_to(a)
s_prev = s
a_prev = a
result_history.append(env.print_result())
x.append(j)
if j % 100 == 0:
env.plot_result()
else:
env.print_result()
if j % 100 == 0:
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax1.plot(x, result_history, 'r', label='total rewards')
plt.show()
scaler.epsilon_decay()
print("last : "+str(j))
env = Environment(test_env_config)
s = None
a = None
r = None
s_prev = None
a_prev = None
for i in range(10000):
if i < 200:
env.epsilon = 0.3
else:
env.epsilon = 0
obs = env.next_state()
if obs == False:
# print("test max iter : " + str(i))
break
s, r = scaler.convert_obs(obs)
a = scaler.get_action(s)
env.scale_to(a)
if i > 0:
diff = scaler.update(s_prev, a_prev, s, r)
s_prev = s
a_prev = a
# simulator.print_result()
# env.save_result('./result/advanced.csv')
env.plot_result()
def get_history(path):
history = []
f = open(path, 'r', encoding='utf-8')
rdr =csv.reader(f)
for line in rdr:
history.append(int(line[0]))
print(f"{path} : "+str(len(history)))
return history
if __name__ == '__main__':
test = {}
test["autoscale_period"] = 15
test["rate"] = 20
test["resource_cost"] = 0.000001389
test["violation_cost"] = test["rate"] * test["resource_cost"]
test["sim_period"] = 0.1
test["timeout"] = 0.3
test["scaling_delay"] = 5
test["learning_rate"] = 0.05
test["discount_factor"] = 0.5
test["epsilon"] = 1.0
test["min"] = 1
test["max"] = 10
test_history = get_history('./data/nasa-http-data_v3_test.csv')
train_history = get_history('./data/nasa-http-data_v3_train.csv')
history = get_history('./data/nasa-http-data_v3.csv')
test_env_config = EnvConfig(
application_profile=application_profile,
traffic_history=history[2001:],
init_pods=test["min"],
timeout=test["timeout"],
autoscale_period=test["autoscale_period"],
simulation_period=test["sim_period"],
readiness_probe=test["scaling_delay"],
resource_cost=test["resource_cost"],
violation_cost=test["violation_cost"]
)
train_env_config = EnvConfig(
application_profile=application_profile,
traffic_history=history[:2001],
init_pods=test["min"],
timeout=test["timeout"],
autoscale_period=test["autoscale_period"],
simulation_period=test["sim_period"],
readiness_probe=test["scaling_delay"],
resource_cost=test["resource_cost"],
violation_cost=test["violation_cost"]
)
rl_config = RlConfig(
pods_min=test["min"],
pods_max=test["max"],
resource_cost=test["resource_cost"],
violation_cost=test["violation_cost"],
autoscaling_period=test["autoscale_period"],
learning_rate=test["learning_rate"],
discount_factor=test["discount_factor"],
epsilon=test["epsilon"]
)
target = [0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9]
for i in target:
print(f'i: {i}')
hpa_config = HpaConfig(
pods_min=1,
pods_max=10,
target_utilization=i,
scaling_tolerance=0.1
)
run_HPA(test_env_config, hpa_config)
# run_HPA_SARSA(test_env_config, train_env_config, rl_config, 'sarsa')
# run_HPA_Q_Learning(test_env_config, train_env_config, rl_config, 'q_learning')
# run_HPA_Q_Learning(test_env_config, train_env_config, rl_config, 'q_leanring_fixed_action')
# run_HPA_Q_Learning(test_env_config, train_env_config, rl_config, 'q_learning_trend')
print("rate :" + str(test["rate"]))
| 26.508734 | 107 | 0.572193 | 1,640 | 12,141 | 3.986585 | 0.115854 | 0.049556 | 0.033802 | 0.020649 | 0.78189 | 0.763383 | 0.753747 | 0.736617 | 0.710615 | 0.693178 | 0 | 0.02087 | 0.305411 | 12,141 | 457 | 108 | 26.56674 | 0.754417 | 0.055267 | 0 | 0.722543 | 0 | 0 | 0.08182 | 0.019385 | 0 | 0 | 0 | 0 | 0 | 1 | 0.028902 | false | 0 | 0.023121 | 0.00289 | 0.075145 | 0.049133 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
8ff359a442c87a941ac2563752f33b49edc657fe | 33 | py | Python | pyrism/IntegralEquations/__init__.py | 2AUK/pyrism | 7067fa7a261adc2faabcffbcb2d40d395e42a3c8 | [
"MIT"
] | 4 | 2020-10-26T14:32:08.000Z | 2021-03-26T01:23:37.000Z | pyrism/IntegralEquations/__init__.py | 2AUK/pyrism | 7067fa7a261adc2faabcffbcb2d40d395e42a3c8 | [
"MIT"
] | 1 | 2021-09-17T18:21:19.000Z | 2021-11-22T00:01:46.000Z | pyrism/IntegralEquations/__init__.py | 2AUK/pyrism | 7067fa7a261adc2faabcffbcb2d40d395e42a3c8 | [
"MIT"
] | 1 | 2022-03-08T12:00:35.000Z | 2022-03-08T12:00:35.000Z | from .IE import IntegralEquation
| 16.5 | 32 | 0.848485 | 4 | 33 | 7 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.121212 | 33 | 1 | 33 | 33 | 0.965517 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8907beeec89dc956ff0c0cd329aced9bf26e7c0f | 197 | py | Python | pulotu/util.py | blurks/pulotu | 621460f3d4dbe05367ed4814b95d192df348cb72 | [
"Apache-2.0"
] | null | null | null | pulotu/util.py | blurks/pulotu | 621460f3d4dbe05367ed4814b95d192df348cb72 | [
"Apache-2.0"
] | 1 | 2021-11-19T16:50:11.000Z | 2021-11-19T16:55:17.000Z | pulotu/util.py | blurks/pulotu | 621460f3d4dbe05367ed4814b95d192df348cb72 | [
"Apache-2.0"
] | 1 | 2021-11-22T13:28:14.000Z | 2021-11-22T13:28:14.000Z | from clld.db.meta import DBSession
from clld.db.models import common
def dataset_detail_html(request=None, context=None, **kw):
return {"ncultures": DBSession.query(common.Language).count()}
| 28.142857 | 66 | 0.766497 | 28 | 197 | 5.321429 | 0.75 | 0.107383 | 0.134228 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.106599 | 197 | 6 | 67 | 32.833333 | 0.846591 | 0 | 0 | 0 | 0 | 0 | 0.045685 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.5 | 0.25 | 1 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 6 |
64df23503affc7a357f8b899bc0cee054d8f5647 | 83 | py | Python | skypond/games/__init__.py | upkoi/skypond | 5e366a18f2c5c85ce7b092d69b28c8f8aaad8718 | [
"MIT"
] | null | null | null | skypond/games/__init__.py | upkoi/skypond | 5e366a18f2c5c85ce7b092d69b28c8f8aaad8718 | [
"MIT"
] | null | null | null | skypond/games/__init__.py | upkoi/skypond | 5e366a18f2c5c85ce7b092d69b28c8f8aaad8718 | [
"MIT"
] | 2 | 2019-06-13T18:08:01.000Z | 2019-06-17T02:42:19.000Z | from __future__ import absolute_import
from . import base
from . import four_keys
| 16.6 | 38 | 0.819277 | 12 | 83 | 5.166667 | 0.583333 | 0.322581 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.156627 | 83 | 4 | 39 | 20.75 | 0.885714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8f243ae16dde3d3157e70cc28baaed239e45d5fc | 41 | py | Python | molecules/pubchem/__init__.py | VanessaDo/cloudml-samples | ae6cd718e583944beef9d8a90db12091ac399432 | [
"Apache-2.0"
] | 3 | 2019-03-29T08:06:35.000Z | 2019-04-12T13:19:18.000Z | molecules/pubchem/__init__.py | VanessaDo/cloudml-samples | ae6cd718e583944beef9d8a90db12091ac399432 | [
"Apache-2.0"
] | 31 | 2021-03-18T23:40:24.000Z | 2022-03-11T23:45:14.000Z | molecules/pubchem/__init__.py | VanessaDo/cloudml-samples | ae6cd718e583944beef9d8a90db12091ac399432 | [
"Apache-2.0"
] | 2 | 2019-10-12T19:21:06.000Z | 2019-10-13T17:38:30.000Z | from pipeline import *
from sdf import *
| 13.666667 | 22 | 0.756098 | 6 | 41 | 5.166667 | 0.666667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.195122 | 41 | 2 | 23 | 20.5 | 0.939394 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8f54eb899b67cc089fb8ad37146879f2139b4f16 | 372,847 | py | Python | A_Grupa.py | numerical-cognition/numerical-cognition-experiment | 80e1b54c4c2e54fcdafd0ea9c656839050d5eda5 | [
"MIT"
] | null | null | null | A_Grupa.py | numerical-cognition/numerical-cognition-experiment | 80e1b54c4c2e54fcdafd0ea9c656839050d5eda5 | [
"MIT"
] | null | null | null | A_Grupa.py | numerical-cognition/numerical-cognition-experiment | 80e1b54c4c2e54fcdafd0ea9c656839050d5eda5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division
from psychopy import locale_setup
from psychopy import prefs
from psychopy import sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.2.4'
expName = 'A Grupa' # from the Builder filename that created this script
expInfo = {'participant': '', 'session': '001'}
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='D:\\Documents\\University Documents\\5. Godina\\2. Diplomski Rad\\5. Eksperiment\\1. Eksperiment (PsychoPy)\\A Grupa (Bez Pamćenja)\\A Grupa (Bez Pamćenja)_lastrun.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
frameTolerance = 0.001 # how close to onset before 'same' frame
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=[1600, 900], fullscr=True, screen=0,
winType='glfw', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[1.000,1.000,1.000], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()
# Initialize components for Routine "pocetna"
pocetnaClock = core.Clock()
dobrodosli = visual.TextStim(win=win, name='dobrodosli',
text='Dobrodošli!',
font='Arial',
pos=(0, 0), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
key_resp_0 = keyboard.Keyboard()
# Initialize components for Routine "upute_tipkovnica"
upute_tipkovnicaClock = core.Clock()
tipkovnica = visual.TextStim(win=win, name='tipkovnica',
text='Upute za tipkovnicu',
font='Arial',
pos=(0, 0.30), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
upute_za_tipke = visual.TextStim(win=win, name='upute_za_tipke',
text='U nastavku će Vam biti prikazane tipke koje ćete koristiti u ovom istraživanju.\n\n Uz svaku tipku bit će prikazano i kratko objašnjenje njene funkcije.',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_tipkovnica = visual.TextStim(win=win, name='nastavi_tipkovnica',
text='Pritisnite "NASTAVI" za upute o tipkovnici',
font='Arial',
pos=(0, -0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
tipkovnica_keys = keyboard.Keyboard()
# Initialize components for Routine "tipkovnica_nastavi"
tipkovnica_nastaviClock = core.Clock()
tipkovnica_nastavi_1 = visual.ImageStim(
win=win,
name='tipkovnica_nastavi_1', units='pix',
image='tipkovnica/nastavi.PNG', mask=None,
ori=0, pos=(0, 150), size=(1250, 444),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
nastavi_objasnjenje = visual.TextStim(win=win, name='nastavi_objasnjenje',
text='Tipka "NASTAVI" služit će Vam kako biste zabilježili svoj odgovor \n i završili trenutačni uputu, vježbu ili zadatak \n\n Nju ćete koristiti najviše u ovom istraživanju',
font='Arial',
pos=(0, -0.15), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_tipkovnica_1 = visual.TextStim(win=win, name='nastavi_tipkovnica_1',
text='Pritisnite "NASTAVI" za dalje',
font='Arial',
pos=(0, -0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
nastavi_keys = keyboard.Keyboard()
# Initialize components for Routine "tipkovnica_podesi"
tipkovnica_podesiClock = core.Clock()
podesi = visual.ImageStim(
win=win,
name='podesi', units='pix',
image='tipkovnica/podesavanje.PNG', mask=None,
ori=0, pos=(0, 150), size=(1250, 444),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
podesi_objasnjenje = visual.TextStim(win=win, name='podesi_objasnjenje',
text='Tipke za podešavanje služit će Vam da povećate ili smanjite objekte\n na željenu veličinu.\n\n NAPOMENA\n \nMožete držati tipku kako bi ubrzali proces povećanja ili smanjivanja\n',
font='Arial',
pos=(0, -0.18), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
podesi_nastavi = visual.TextStim(win=win, name='podesi_nastavi',
text='Pritisnite bilo koju tipku za podešavanje za dalje',
font='Arial',
pos=(0, -0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
podesi_keys = keyboard.Keyboard()
# Initialize components for Routine "tipkovnica_brojevi"
tipkovnica_brojeviClock = core.Clock()
brojevi = visual.ImageStim(
win=win,
name='brojevi', units='pix',
image='tipkovnica/brojevi.PNG', mask=None,
ori=0, pos=(0, 150), size=(1250, 444),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
brojevi_objasnjenje = visual.TextStim(win=win, name='brojevi_objasnjenje',
text='U nekim zadacima od Vas će se tražiti da upišete svoj odgovor u brojevnom formatu\n\nKako bi upisali svoj odgovor, koristit ćete ISKLJUČIVO ove brojeve na tipkovnici\n',
font='Arial',
pos=(0, -0.15), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
brojevi_nastavi = visual.TextStim(win=win, name='brojevi_nastavi',
text='Pritisnite bilo koji broj za dalje',
font='Arial',
pos=(0, -0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
brojevi_keys = keyboard.Keyboard()
# Initialize components for Routine "tipkovnica_brisanje"
tipkovnica_brisanjeClock = core.Clock()
brisanje = visual.ImageStim(
win=win,
name='brisanje', units='pix',
image='tipkovnica/brisanje.PNG', mask=None,
ori=0, pos=(0, 150), size=(1250, 444),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
brisanje_objasnjenje = visual.TextStim(win=win, name='brisanje_objasnjenje',
text='Ako ste upisali krivi odgovor, možete koristiti tipku za brisanje \n kako biste izbrisali svoj odgovor i upisali novi',
font='Arial',
pos=(0, -0.15), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
brisanje_nastavi = visual.TextStim(win=win, name='brisanje_nastavi',
text='Pritisnite tipku za brisanje za početak eksperimenta',
font='Arial',
pos=(0, -0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
brisanje_keys = keyboard.Keyboard()
# Initialize components for Routine "demografski_podaci"
demografski_podaciClock = core.Clock()
demog_pitanja = visual.TextStim(win=win, name='demog_pitanja',
text='default text',
font='Arial',
pos=(0, 0.30), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
primjer = visual.TextStim(win=win, name='primjer',
text='default text',
font='Arial',
pos=(0, 0.15), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
unos_demog = visual.TextStim(win=win, name='unos_demog',
text='default text',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
nastavi1 = visual.TextStim(win=win, name='nastavi1',
text='Nakon što se unjeli podatke pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
demografija_unos = keyboard.Keyboard()
# Initialize components for Routine "upute_kod"
upute_kodClock = core.Clock()
anonimnost = visual.TextStim(win=win, name='anonimnost',
text='Kako bi osigurali anonimnost Vaših podataka \n sada ćemo kreirati Vašu jedinstvenu lozinku',
font='Arial',
pos=(0, 0), height=0.04, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
nastavi2 = visual.TextStim(win=win, name='nastavi2',
text='Pritisnite "NASTAVI" kako biste kreirali lozinku',
font='Arial',
pos=(0,-0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
key_resp_2 = keyboard.Keyboard()
# Initialize components for Routine "jedinstveni_kod"
jedinstveni_kodClock = core.Clock()
lozinka_pitanja = visual.TextStim(win=win, name='lozinka_pitanja',
text='default text',
font='Arial',
pos=(0, 0.30), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
primjer1 = visual.TextStim(win=win, name='primjer1',
text='default text',
font='Arial',
pos=(0, 0.15), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
unos_koda = visual.TextStim(win=win, name='unos_koda',
text='default text',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
nastavi3 = visual.TextStim(win=win, name='nastavi3',
text='Nakon što se unjeli podatke pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
lozinka_unos = keyboard.Keyboard()
#Ovo napravi listu gdje će se pohraniti unosi za svako pitanje
kod = []
msg= ""
# Initialize components for Routine "prikaz_koda"
prikaz_kodaClock = core.Clock()
lozinka_je = visual.TextStim(win=win, name='lozinka_je',
text='Vaša jedinstvena lozinka je:',
font='Arial',
pos=(0, 0.30), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
lozinka = visual.TextStim(win=win, name='lozinka',
text='default text',
font='Arial',
pos=(0, 0.1), height=0.1, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
prepis_lozinke = visual.TextStim(win=win, name='prepis_lozinke',
text='Molimo Vas da prepišete Vašu lozinku na zamolbu za sudjelovanje',
font='Arial',
pos=(0, -0.18), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
nastavi4 = visual.TextStim(win=win, name='nastavi4',
text='Nakon što ste prepisali lozinku pritisnite "NASTAVI"',
font='Arial',
pos=(0,-0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
key_resp_3 = keyboard.Keyboard()
# Initialize components for Routine "generalne_upute"
generalne_uputeClock = core.Clock()
generalne_upute_1 = visual.TextStim(win=win, name='generalne_upute_1',
text='Generalne upute',
font='Arial',
pos=(0, 0.35), height=0.07, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
tri_upute = visual.TextStim(win=win, name='tri_upute',
text='1. Ovaj eksperiment ima 3 različita zadatka\n\n2. Prije svakog zadatka dolazi uputa i kratka vježba\n\n3. Predviđeno trajanje cijelog eksperimenta je 15 minuta',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_5 = visual.TextStim(win=win, name='nastavi_5',
text='Pritisnite "NASTAVI" za uputu o prvom zadatku',
font='Arial',
pos=(0, -0.4), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
key_resp_4 = keyboard.Keyboard()
# Initialize components for Routine "uputa_zadatak_1"
uputa_zadatak_1Clock = core.Clock()
naslov_uputa = visual.TextStim(win=win, name='naslov_uputa',
text='Uputa',
font='Arial',
pos=(0, 0.41), height=0.07, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
generalna_uputa_z1 = visual.TextStim(win=win, name='generalna_uputa_z1',
text='1. Na slici će vam biti prikazan krug.\n\n2. Vaš zadatak je da zapamtite veličinu tog kruga.\n\n3. Kada ste zapamtili veličinu kruga, pritisnuti ćete "NASTAVI"\n\n4. Na slici koja potom slijedi podesiti ćete veličinu novog kruga na istu\n veličinu kruga kojeg ste prethodno vidjeli (i zapamtili).\n\n5. Nakon što ste podesili veličinu novog kruga, procijeniti ćete koliko ste\n sigurni u svoj odgovor (na ljestvici od 1% do 100%)',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_6 = visual.TextStim(win=win, name='nastavi_6',
text='Pritisnite "NASTAVI" za vježbu prvog zadataka',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
zadatak = visual.Rect(
win=win, name='zadatak',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1.000,1.000,1.000], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-3.0, interpolate=True)
zadatak_tekst = visual.TextStim(win=win, name='zadatak_tekst',
text='ZADATAK 1',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
key_resp_5 = keyboard.Keyboard()
# Initialize components for Routine "vjezba"
vjezbaClock = core.Clock()
vjezba_0 = visual.TextStim(win=win, name='vjezba_0',
text='Vježba',
font='Arial',
pos=(0, 0.1), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
zadaci_za_vjezbu = visual.TextStim(win=win, name='zadaci_za_vjezbu',
text='U nastavku slijedi 3 zadatka za probu',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_vjezba = visual.TextStim(win=win, name='nastavi_vjezba',
text='Pritisnite "NASTAVI" za početak vježbe',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
pocetak_vjezbe = keyboard.Keyboard()
# Initialize components for Routine "vjezba_1_pamcenje"
vjezba_1_pamcenjeClock = core.Clock()
uputa_v1 = visual.TextStim(win=win, name='uputa_v1',
text='default text',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
podrazaj_v1 = visual.ImageStim(
win=win,
name='podrazaj_v1', units='pix',
image='sin', mask=None,
ori=0, pos=(0, 0), size=(480, 480),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-3.0)
nastavi_7 = visual.TextStim(win=win, name='nastavi_7',
text='Kad ste zapamtili pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
vjezba_1_ = visual.Rect(
win=win, name='vjezba_1_',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1.000,-1.000,-1.000], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
vjezba_1_text = visual.TextStim(win=win, name='vjezba_1_text',
text='VJEŽBA 1',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_vjezbe_1_ = visual.Rect(
win=win, name='br_vjezbe_1_',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1.000,-1.000,-1.000], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_vjezbe_1_text = visual.TextStim(win=win, name='br_vjezbe_1_text',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
pamcenje_slike_v1 = keyboard.Keyboard()
# Initialize components for Routine "mpi_sum"
mpi_sumClock = core.Clock()
sum = visual.NoiseStim(
win=win, name='sum',
noiseImage=None, mask=None,
ori=0, pos=(0, 0), size=(2, 2), sf=None,
phase=0.0,
color=[1,1,1], colorSpace='rgb', opacity=1, blendmode='avg', contrast=1.0,
texRes=128, filter=None,
noiseType='Binary', noiseElementSize=0.0625,
noiseBaseSf=8.0, noiseBW=1,
noiseBWO=30, noiseOri=0.0,
noiseFractalPower=0.0,noiseFilterLower=1.0,
noiseFilterUpper=8.0, noiseFilterOrder=0.0,
noiseClip=3.0, imageComponent='Phase', interpolate=False, depth=0.0)
sum.buildNoise()
# Initialize components for Routine "vjezba_1_odgovor"
vjezba_1_odgovorClock = core.Clock()
import re
raspon_v1 = range(1, 210)
imgList_v01 = list(raspon_v1)
imgList_v1 = str(imgList_v01)
imgChoice_v1 = ""
uputa_v1_1 = visual.TextStim(win=win, name='uputa_v1_1',
text='default text',
font='Arial',
pos=(0, 0.39), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
odgovor_v1 = visual.ImageStim(
win=win,
name='odgovor_v1', units='pix',
image='sin', mask=None,
ori=0, pos=(0, 0), size=(480, 480),
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-3.0)
nastavi_8 = visual.TextStim(win=win, name='nastavi_8',
text='Kada ste podesili pritisnite "NASTAVI" ',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
vjezba_1_1 = visual.Rect(
win=win, name='vjezba_1_1',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1.000,-1.000,-1.000], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
vjezba_1_text_1 = visual.TextStim(win=win, name='vjezba_1_text_1',
text='VJEŽBA 1',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_vjezbe_1_1 = visual.Rect(
win=win, name='br_vjezbe_1_1',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1.000,-1.000,-1.000], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_vjezbe_1_text_1 = visual.TextStim(win=win, name='br_vjezbe_1_text_1',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
str_gore_v1 = visual.ImageStim(
win=win,
name='str_gore_v1',
image='strelice/up.PNG', mask=None,
ori=0, pos=(0.8, 0.1), size=(0.038,0.038),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-9.0)
gore_v1 = visual.TextStim(win=win, name='gore_v1',
text='POVEĆAJ',
font='Arial',
pos=(0.8, 0.05), height=0.025, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-10.0);
str_dolje_v1 = visual.ImageStim(
win=win,
name='str_dolje_v1',
image='strelice/down.PNG', mask=None,
ori=0, pos=(0.8, -0.1), size=(0.038,0.038),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-11.0)
dolje_v1 = visual.TextStim(win=win, name='dolje_v1',
text='SMANJI',
font='Arial',
pos=(0.8, -0.05), height=0.025, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-12.0);
izbor_slike_v1 = keyboard.Keyboard()
# Initialize components for Routine "vjezba_1_sigurnost"
vjezba_1_sigurnostClock = core.Clock()
stupanj_sigurnosti_v1 = visual.TextStim(win=win, name='stupanj_sigurnosti_v1',
text='Koliko ste sigurni u svoj odgovor?',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
sigurnost_primjer_v1 = visual.TextStim(win=win, name='sigurnost_primjer_v1',
text='(NAPOMENA: procijenite na ljestvici od 1% do 100%)',
font='Arial',
pos=(0, 0.35), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
sigurnost_odgovor_v1 = visual.TextStim(win=win, name='sigurnost_odgovor_v1',
text='default text',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
nastavi_9 = visual.TextStim(win=win, name='nastavi_9',
text='Kad ste procijenili pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
vjezba_1_2 = visual.Rect(
win=win, name='vjezba_1_2',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1.000,-1.000,-1.000], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
vjezba_1_text_2 = visual.TextStim(win=win, name='vjezba_1_text_2',
text='VJEŽBA 1',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_vjezbe_1_2 = visual.Rect(
win=win, name='br_vjezbe_1_2',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1.000,-1.000,-1.000], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_vjezbe_1_text_2 = visual.TextStim(win=win, name='br_vjezbe_1_text_2',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
key_resp_8 = keyboard.Keyboard()
# Initialize components for Routine "kraj_vjezbe_1"
kraj_vjezbe_1Clock = core.Clock()
gotova_vjezba_1 = visual.TextStim(win=win, name='gotova_vjezba_1',
text='Vježba je gotova!',
font='Arial',
pos=(0, 0.1), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
priprema_za_z1 = visual.TextStim(win=win, name='priprema_za_z1',
text='U nastavku slijedi prvi zadatak',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_10 = visual.TextStim(win=win, name='nastavi_10',
text='Pritisnite "NASTAVI" za početak prvog zadataka',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
Kraj_vjezbe_1 = keyboard.Keyboard()
# Initialize components for Routine "zadatak_1_pamcenje"
zadatak_1_pamcenjeClock = core.Clock()
uputa_z1 = visual.TextStim(win=win, name='uputa_z1',
text='default text',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
podrazaj_z1 = visual.ImageStim(
win=win,
name='podrazaj_z1', units='pix',
image='sin', mask=None,
ori=0, pos=(0, 0), size=(480, 480),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-3.0)
nastavi_11 = visual.TextStim(win=win, name='nastavi_11',
text='Kad ste zapamtili pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
zadatak_1 = visual.Rect(
win=win, name='zadatak_1',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
zadatak_1_text = visual.TextStim(win=win, name='zadatak_1_text',
text='ZADATAK 1',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_zadatka_1 = visual.Rect(
win=win, name='br_zadatka_1',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_zadatka_1_tekst = visual.TextStim(win=win, name='br_zadatka_1_tekst',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
pamcenje_slike_z1 = keyboard.Keyboard()
# Initialize components for Routine "mpi_sum"
mpi_sumClock = core.Clock()
sum = visual.NoiseStim(
win=win, name='sum',
noiseImage=None, mask=None,
ori=0, pos=(0, 0), size=(2, 2), sf=None,
phase=0.0,
color=[1,1,1], colorSpace='rgb', opacity=1, blendmode='avg', contrast=1.0,
texRes=128, filter=None,
noiseType='Binary', noiseElementSize=0.0625,
noiseBaseSf=8.0, noiseBW=1,
noiseBWO=30, noiseOri=0.0,
noiseFractalPower=0.0,noiseFilterLower=1.0,
noiseFilterUpper=8.0, noiseFilterOrder=0.0,
noiseClip=3.0, imageComponent='Phase', interpolate=False, depth=0.0)
sum.buildNoise()
# Initialize components for Routine "zadatak_1_odgovor"
zadatak_1_odgovorClock = core.Clock()
import re
raspon_z1 = range(1, 210)
imgList_z01 = list(raspon_z1)
imgList_z1 = str(imgList_z01)
imgChoice_z1 = ""
uputa_z1_1 = visual.TextStim(win=win, name='uputa_z1_1',
text='default text',
font='Arial',
pos=(0, 0.39), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
odgovor_z1 = visual.ImageStim(
win=win,
name='odgovor_z1', units='pix',
image='sin', mask=None,
ori=0, pos=(0, 0), size=(480, 480),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-3.0)
nastavi_12 = visual.TextStim(win=win, name='nastavi_12',
text='Kada ste podesili pritisnite "NASTAVI" ',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
zadatak_1_1 = visual.Rect(
win=win, name='zadatak_1_1',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1.000,1.000,1.000], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
zadatak_1_text_1 = visual.TextStim(win=win, name='zadatak_1_text_1',
text='ZADATAK 1',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_zadatka_1_1 = visual.Rect(
win=win, name='br_zadatka_1_1',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_zadatka_1_text = visual.TextStim(win=win, name='br_zadatka_1_text',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
str_gore_z1 = visual.ImageStim(
win=win,
name='str_gore_z1',
image='strelice/up.PNG', mask=None,
ori=0, pos=(0.8, 0.1), size=(0.038,0.038),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-9.0)
gore_z1 = visual.TextStim(win=win, name='gore_z1',
text='POVEĆAJ',
font='Arial',
pos=(0.8, 0.05), height=0.025, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-10.0);
str_dolje_z1 = visual.ImageStim(
win=win,
name='str_dolje_z1',
image='strelice/down.PNG', mask=None,
ori=0, pos=(0.8, -0.1), size=(0.038,0.038),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-11.0)
dolje_z1 = visual.TextStim(win=win, name='dolje_z1',
text='SMANJI',
font='Arial',
pos=(0.8, -0.05), height=0.025, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-12.0);
izbor_slike_z1 = keyboard.Keyboard()
# Initialize components for Routine "zadatak_1_sigurnost"
zadatak_1_sigurnostClock = core.Clock()
stupanj_sigurnosti_z1 = visual.TextStim(win=win, name='stupanj_sigurnosti_z1',
text='Koliko ste sigurni u svoj odgovor?',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
sigurnost_primjer_z1 = visual.TextStim(win=win, name='sigurnost_primjer_z1',
text='(NAPOMENA: procijenite na ljestvici od 1% do 100%)',
font='Arial',
pos=(0, 0.35), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
sigurnost_odgovor_z1 = visual.TextStim(win=win, name='sigurnost_odgovor_z1',
text='default text',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
nastavi_13 = visual.TextStim(win=win, name='nastavi_13',
text='Kad ste procijenili pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
zadatak_1_2 = visual.Rect(
win=win, name='zadatak_1_2',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
zadatak_1_text_2 = visual.TextStim(win=win, name='zadatak_1_text_2',
text='ZADATAK 1',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_zadatka_1_2 = visual.Rect(
win=win, name='br_zadatka_1_2',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_zadatka_1_3 = visual.TextStim(win=win, name='br_zadatka_1_3',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
key_resp_9 = keyboard.Keyboard()
# Initialize components for Routine "kraj_zadatka_1"
kraj_zadatka_1Clock = core.Clock()
gotov_zadatak_1 = visual.TextStim(win=win, name='gotov_zadatak_1',
text='Uspješno ste završili prvi zadatak!',
font='Arial',
pos=(0, 0.1), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
priprema_za_z2 = visual.TextStim(win=win, name='priprema_za_z2',
text='U nastavku slijedi drugi zadatak',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_13_1 = visual.TextStim(win=win, name='nastavi_13_1',
text='Pritisnite "NASTAVI" za uputu o drugom zadatku',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
Kraj_zadatka_1 = keyboard.Keyboard()
# Initialize components for Routine "uputa_zadatak_2"
uputa_zadatak_2Clock = core.Clock()
naslov_uputa_z2 = visual.TextStim(win=win, name='naslov_uputa_z2',
text='Uputa',
font='Arial',
pos=(0, 0.41), height=0.07, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
generalna_uputa_z2 = visual.TextStim(win=win, name='generalna_uputa_z2',
text='1. Na slici će Vam biti prikazan krug i pravokutnik.\n\n2. Vaš zadatak je da podesite veličinu pravokutnika tako da u njega \n stane zadani broj krugova.\n\n4. Nakon što ste podesili veličinu pravokutnika, procijeniti ćete koliko ste\n sigurni u svoj odgovor (na ljestvici od 1% do 100%)',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_14 = visual.TextStim(win=win, name='nastavi_14',
text='Pritisnite "NASTAVI" za vježbu drugog zadataka',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
zadatak_2 = visual.Rect(
win=win, name='zadatak_2',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-3.0, interpolate=True)
zadatak_2_text = visual.TextStim(win=win, name='zadatak_2_text',
text='ZADATAK 2',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
Pocetak_vjezbe_2 = keyboard.Keyboard()
# Initialize components for Routine "vjezba"
vjezbaClock = core.Clock()
vjezba_0 = visual.TextStim(win=win, name='vjezba_0',
text='Vježba',
font='Arial',
pos=(0, 0.1), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
zadaci_za_vjezbu = visual.TextStim(win=win, name='zadaci_za_vjezbu',
text='U nastavku slijedi 3 zadatka za probu',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_vjezba = visual.TextStim(win=win, name='nastavi_vjezba',
text='Pritisnite "NASTAVI" za početak vježbe',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
pocetak_vjezbe = keyboard.Keyboard()
# Initialize components for Routine "vjezba_2_odgovor"
vjezba_2_odgovorClock = core.Clock()
import re
raspon_v2 = range(1, 600)
imgList_v02 = list(raspon_v2)
imgList_v2 = str(imgList_v02)
imgChoice_v2 = ""
uputa_v2_1 = visual.TextStim(win=win, name='uputa_v2_1',
text='default text',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
broj_objekata_v1 = visual.TextStim(win=win, name='broj_objekata_v1',
text='Zadani broj',
font='Arial',
pos=(-0.23, 0.28), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-5.0);
br_broj_objekata_v2 = visual.TextStim(win=win, name='br_broj_objekata_v2',
text='default text',
font='Arial',
pos=(-0.23, 0.18), height=0.09, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
ciljni_objekt_v2 = visual.TextStim(win=win, name='ciljni_objekt_v2',
text='Veličina kruga',
font='Arial',
pos=(0.23, 0.28), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-7.0);
ciljni_objekt_slika_v2 = visual.ImageStim(
win=win,
name='ciljni_objekt_slika_v2', units='pix',
image='krugovi/0.PNG', mask=None,
ori=0, pos=(175, 130), size=(60, 60),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-8.0)
odgovor_v2 = visual.ImageStim(
win=win,
name='odgovor_v2', units='pix',
image='sin', mask=None,
ori=0, pos=(0, -50), size=(1280, 70),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-9.0)
nastavi_15 = visual.TextStim(win=win, name='nastavi_15',
text='Kada ste podesili pritisnite "NASTAVI" ',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-10.0);
vjezba_2_1 = visual.Rect(
win=win, name='vjezba_2_1',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-11.0, interpolate=True)
vjezba_2_text_1 = visual.TextStim(win=win, name='vjezba_2_text_1',
text='VJEŽBA 2',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-12.0);
br_vjezbe_2_1 = visual.Rect(
win=win, name='br_vjezbe_2_1',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-13.0, interpolate=True)
br_vjezbe_2_text_1 = visual.TextStim(win=win, name='br_vjezbe_2_text_1',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-14.0);
str_lijevo_v2 = visual.ImageStim(
win=win,
name='str_lijevo_v2',
image='strelice/left.PNG', mask=None,
ori=0, pos=(-0.2, -0.25), size=(0.035,0.035),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-15.0)
lijevo_v2 = visual.TextStim(win=win, name='lijevo_v2',
text='SMANJI',
font='Arial',
pos=(-0.12,-0.25), height=0.025, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-16.0);
str_desno_v2 = visual.ImageStim(
win=win,
name='str_desno_v2',
image='strelice/right.PNG', mask=None,
ori=0, pos=(0.2, -0.25), size=(0.035,0.035),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-17.0)
desno_v2 = visual.TextStim(win=win, name='desno_v2',
text='POVEĆAJ',
font='Arial',
pos=(0.11,-0.25), height=0.025, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-18.0);
izbor_slike_v2 = keyboard.Keyboard()
# Initialize components for Routine "vjezba_2_sigurnost"
vjezba_2_sigurnostClock = core.Clock()
stupanj_sigurnosti_v2 = visual.TextStim(win=win, name='stupanj_sigurnosti_v2',
text='Koliko ste sigurni u svoj odgovor?',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
sigurnost_primjer_v2 = visual.TextStim(win=win, name='sigurnost_primjer_v2',
text='(NAPOMENA: procijenite na ljestvici od 1% do 100%)',
font='Arial',
pos=(0, 0.35), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
sigurnost_odgovor_v2 = visual.TextStim(win=win, name='sigurnost_odgovor_v2',
text='default text',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
nastavi_16 = visual.TextStim(win=win, name='nastavi_16',
text='Kad ste procijenili pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
vjezba_2_2 = visual.Rect(
win=win, name='vjezba_2_2',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
vjezba_2_text_2 = visual.TextStim(win=win, name='vjezba_2_text_2',
text='VJEŽBA 2',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_vjezbe_2_2 = visual.Rect(
win=win, name='br_vjezbe_2_2',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_vjezbe_2_text_2 = visual.TextStim(win=win, name='br_vjezbe_2_text_2',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
key_resp_11 = keyboard.Keyboard()
# Initialize components for Routine "kraj_vjezbe_2"
kraj_vjezbe_2Clock = core.Clock()
gotova_vjezba_2 = visual.TextStim(win=win, name='gotova_vjezba_2',
text='Vježba je gotova!',
font='Arial',
pos=(0, 0.1), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
priprema_za_z2_1 = visual.TextStim(win=win, name='priprema_za_z2_1',
text='U nastavku slijedi drugi zadatak',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_17 = visual.TextStim(win=win, name='nastavi_17',
text='Pritisnite "NASTAVI" za početak drugog zadataka',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
Kraj_vjezbe_2 = keyboard.Keyboard()
# Initialize components for Routine "zadatak_2_odgovor"
zadatak_2_odgovorClock = core.Clock()
import re
raspon_z2 = range(1, 600)
imgList_z02 = list(raspon_z2)
imgList_z2 = str(imgList_z02)
imgChoice_z2 = ""
uputa_z2_1 = visual.TextStim(win=win, name='uputa_z2_1',
text='default text',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
broj_objekata_z2 = visual.TextStim(win=win, name='broj_objekata_z2',
text='Zadani broj',
font='Arial',
pos=(-0.23, 0.28), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-5.0);
br_broj_objekata_z2 = visual.TextStim(win=win, name='br_broj_objekata_z2',
text='default text',
font='Arial',
pos=(-0.23, 0.18), height=0.09, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
ciljni_objekt_z2 = visual.TextStim(win=win, name='ciljni_objekt_z2',
text='Veličina kruga',
font='Arial',
pos=(0.23, 0.28), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-7.0);
ciljni_objekt_slika_z2 = visual.ImageStim(
win=win,
name='ciljni_objekt_slika_z2', units='pix',
image='krugovi/0.PNG', mask=None,
ori=0, pos=(175, 130), size=(60, 60),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-8.0)
odgovor_z2 = visual.ImageStim(
win=win,
name='odgovor_z2', units='pix',
image='sin', mask=None,
ori=0, pos=(0, -50), size=(1280, 70),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-9.0)
nastavi_18 = visual.TextStim(win=win, name='nastavi_18',
text='Kada ste podesili pritisnite "NASTAVI" ',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-10.0);
zadatak_2_1 = visual.Rect(
win=win, name='zadatak_2_1',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-11.0, interpolate=True)
zadatak_2_text_1 = visual.TextStim(win=win, name='zadatak_2_text_1',
text='ZADATAK 2',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-12.0);
br_zadatka_2_1 = visual.Rect(
win=win, name='br_zadatka_2_1',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-13.0, interpolate=True)
br_zadatka_2_text = visual.TextStim(win=win, name='br_zadatka_2_text',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-14.0);
str_lijevo_z2 = visual.ImageStim(
win=win,
name='str_lijevo_z2',
image='strelice/left.PNG', mask=None,
ori=0, pos=(-0.2, -0.25), size=(0.035,0.035),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-15.0)
lijevo_z2 = visual.TextStim(win=win, name='lijevo_z2',
text='SMANJI',
font='Arial',
pos=(-0.12,-0.25), height=0.025, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-16.0);
str_desno_z2 = visual.ImageStim(
win=win,
name='str_desno_z2',
image='strelice/right.PNG', mask=None,
ori=0, pos=(0.2, -0.25), size=(0.035,0.035),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-17.0)
desno_z2 = visual.TextStim(win=win, name='desno_z2',
text='POVEĆAJ',
font='Arial',
pos=(0.11,-0.25), height=0.025, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-18.0);
izbor_slike_z2 = keyboard.Keyboard()
# Initialize components for Routine "zadatak_2_sigurnost"
zadatak_2_sigurnostClock = core.Clock()
stupanj_sigurnosti_z2 = visual.TextStim(win=win, name='stupanj_sigurnosti_z2',
text='Koliko ste sigurni u svoj odgovor?',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
sigurnost_primjer_z2 = visual.TextStim(win=win, name='sigurnost_primjer_z2',
text='(NAPOMENA: procjenite na ljestvici od 1% do 100%)',
font='Arial',
pos=(0, 0.35), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
sigurnost_odgovor_z2 = visual.TextStim(win=win, name='sigurnost_odgovor_z2',
text='default text',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
nastavi_19 = visual.TextStim(win=win, name='nastavi_19',
text='Kad ste procjenili pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
zadatak_2_2 = visual.Rect(
win=win, name='zadatak_2_2',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
zadatak_2_text_2 = visual.TextStim(win=win, name='zadatak_2_text_2',
text='ZADATAK 2',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_zadatka_2_2 = visual.Rect(
win=win, name='br_zadatka_2_2',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_zadatka_2_3 = visual.TextStim(win=win, name='br_zadatka_2_3',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
key_resp_12 = keyboard.Keyboard()
# Initialize components for Routine "kraj_zadatka_2"
kraj_zadatka_2Clock = core.Clock()
gotov_zadatak_2 = visual.TextStim(win=win, name='gotov_zadatak_2',
text='Uspješno ste završili drugi zadatak!',
font='Arial',
pos=(0, 0.1), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
priprema_za_z3 = visual.TextStim(win=win, name='priprema_za_z3',
text='U nastavku sljedi zadnji zadatak',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_19_1 = visual.TextStim(win=win, name='nastavi_19_1',
text='Pritisnite "NASTAVI" za uputu o trećem zadatku',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
Kraj_zadatka_2 = keyboard.Keyboard()
# Initialize components for Routine "uputa_zadatak_3"
uputa_zadatak_3Clock = core.Clock()
naslov_uputa_z3 = visual.TextStim(win=win, name='naslov_uputa_z3',
text='Uputa',
font='Arial',
pos=(0, 0.41), height=0.07, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
generalna_uputa_z3 = visual.TextStim(win=win, name='generalna_uputa_z3',
text='1. Na slici će Vam biti prikazan krug i pravokutnik.\n\n2. Vaš zadatak je da procjenite koliko krugova stane u taj pravokutnik \n\n3. Nakon što ste procijenili broj krugova, procjeniti ćete koliko ste sigurni\n u svoj odgovor (na ljestvici od 1% do 100%)',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_20 = visual.TextStim(win=win, name='nastavi_20',
text='Pritisnite "NASTAVI" za vježbu trećeg zadataka',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
zadatak_3 = visual.Rect(
win=win, name='zadatak_3',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-3.0, interpolate=True)
zadatak_3_text = visual.TextStim(win=win, name='zadatak_3_text',
text='ZADATAK 3',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
Pocetak_vjezbe_3 = keyboard.Keyboard()
# Initialize components for Routine "vjezba"
vjezbaClock = core.Clock()
vjezba_0 = visual.TextStim(win=win, name='vjezba_0',
text='Vježba',
font='Arial',
pos=(0, 0.1), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
zadaci_za_vjezbu = visual.TextStim(win=win, name='zadaci_za_vjezbu',
text='U nastavku slijedi 3 zadatka za probu',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_vjezba = visual.TextStim(win=win, name='nastavi_vjezba',
text='Pritisnite "NASTAVI" za početak vježbe',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
pocetak_vjezbe = keyboard.Keyboard()
# Initialize components for Routine "vjezba_3_odgovor"
vjezba_3_odgovorClock = core.Clock()
uputa_v3_1 = visual.TextStim(win=win, name='uputa_v3_1',
text='Procijenite koliko krugova stane u zadani pravokutnik (UPIŠITE BROJ)',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
primjer_v3_1 = visual.TextStim(win=win, name='primjer_v3_1',
text='(NAPOMENA: Svaki pravokutnik je podešen na TOČAN broj krugova)',
font='Arial',
pos=(0, 0.35), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
ciljni_objekt_v3 = visual.TextStim(win=win, name='ciljni_objekt_v3',
text='Veličina kruga',
font='Arial',
pos=(0, 0.22), height=0.035, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-5.0);
ciljni_objekt_slika_v3 = visual.ImageStim(
win=win,
name='ciljni_objekt_slika_v3', units='pix',
image='krugovi/0.PNG', mask=None,
ori=0, pos=(0, 100), size=(60, 60),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-6.0)
odgovor_v3 = visual.ImageStim(
win=win,
name='odgovor_v3', units='pix',
image='sin', mask=None,
ori=0, pos=(0, -30), size=(1280, 70),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-7.0)
vas_odgovor_v3_1 = visual.TextStim(win=win, name='vas_odgovor_v3_1',
text='Broj krugova:',
font='Arial',
pos=(0, -0.18), height=0.035, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
br_vas_odgovor_v3 = visual.TextStim(win=win, name='br_vas_odgovor_v3',
text='default text',
font='Arial',
pos=(0, -0.28), height=0.095, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-9.0);
nastavi_21 = visual.TextStim(win=win, name='nastavi_21',
text='Kada ste podesili pritisnite "NASTAVI" ',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-10.0);
vjezba_3_1 = visual.Rect(
win=win, name='vjezba_3_1',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-11.0, interpolate=True)
vjezba_3_text_1 = visual.TextStim(win=win, name='vjezba_3_text_1',
text='VJEŽBA 3',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-12.0);
br_vjezbe_3_1 = visual.Rect(
win=win, name='br_vjezbe_3_1',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-13.0, interpolate=True)
br_vjezbe_3_text_1 = visual.TextStim(win=win, name='br_vjezbe_3_text_1',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-14.0);
izbor_broja_v3 = keyboard.Keyboard()
RT_izbor_broja_v3 = keyboard.Keyboard()
# Initialize components for Routine "vjezba_3_sigurnost"
vjezba_3_sigurnostClock = core.Clock()
stupanj_sigurnosti_v3 = visual.TextStim(win=win, name='stupanj_sigurnosti_v3',
text='Koliko ste sigurni u svoj odgovor?',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
sigurnost_primjer_v3 = visual.TextStim(win=win, name='sigurnost_primjer_v3',
text='(NAPOMENA: procijenite na ljestvici od 1% do 100%)',
font='Arial',
pos=(0, 0.35), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
sigurnost_odgovor_v3 = visual.TextStim(win=win, name='sigurnost_odgovor_v3',
text='default text',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
nastavi_22 = visual.TextStim(win=win, name='nastavi_22',
text='Kad ste procijenili pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
vjezba_3_2 = visual.Rect(
win=win, name='vjezba_3_2',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
vjezba_3_text_2 = visual.TextStim(win=win, name='vjezba_3_text_2',
text='VJEŽBA 3',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_vjezbe_3_2 = visual.Rect(
win=win, name='br_vjezbe_3_2',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_vjezbe_3_text_2 = visual.TextStim(win=win, name='br_vjezbe_3_text_2',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
key_resp_13 = keyboard.Keyboard()
# Initialize components for Routine "kraj_vjezbe_3"
kraj_vjezbe_3Clock = core.Clock()
gotova_vjezba_3 = visual.TextStim(win=win, name='gotova_vjezba_3',
text='Vježba je gotova!',
font='Arial',
pos=(0, 0.1), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
priprema_za_z3_1 = visual.TextStim(win=win, name='priprema_za_z3_1',
text='U nastavku slijedi treći zadatak',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
nastavi_23 = visual.TextStim(win=win, name='nastavi_23',
text='Pritisnite "NASTAVI" za početak trećeg zadataka',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
Kraj_vjezbe_3 = keyboard.Keyboard()
# Initialize components for Routine "zadatak_3_odgovor"
zadatak_3_odgovorClock = core.Clock()
uputa_z3_1 = visual.TextStim(win=win, name='uputa_z3_1',
text='Procijenite koliko krugova stane u zadani pravokutnik (UPIŠITE BROJ)',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=2, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
primjer_z3_1 = visual.TextStim(win=win, name='primjer_z3_1',
text='(NAPOMENA: Svaki pravokutnik je podešen na TOČAN broj krugova)',
font='Arial',
pos=(0, 0.35), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
ciljni_objekt_z3 = visual.TextStim(win=win, name='ciljni_objekt_z3',
text='Veličina kruga',
font='Arial',
pos=(0, 0.22), height=0.035, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-5.0);
ciljni_objekt_slika_z3 = visual.ImageStim(
win=win,
name='ciljni_objekt_slika_z3', units='pix',
image='krugovi/0.PNG', mask=None,
ori=0, pos=(0, 100), size=(60, 60),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-6.0)
odgovor_z3 = visual.ImageStim(
win=win,
name='odgovor_z3', units='pix',
image='sin', mask=None,
ori=0, pos=(0, -30), size=(1280, 70),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-7.0)
vas_odgovor_z3_1 = visual.TextStim(win=win, name='vas_odgovor_z3_1',
text='Broj krugova:',
font='Arial',
pos=(0, -0.18), height=0.035, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
br_vas_odgovor_z3 = visual.TextStim(win=win, name='br_vas_odgovor_z3',
text='default text',
font='Arial',
pos=(0, -0.28), height=0.09, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-9.0);
nastavi_24 = visual.TextStim(win=win, name='nastavi_24',
text='Kada ste podesili pritisnite "NASTAVI" ',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-10.0);
zadatak_3_1 = visual.Rect(
win=win, name='zadatak_3_1',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-11.0, interpolate=True)
zadatak_3_text_1 = visual.TextStim(win=win, name='zadatak_3_text_1',
text='ZADATAK 3',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-12.0);
br_zadatka_3_1 = visual.Rect(
win=win, name='br_zadatka_3_1',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-13.0, interpolate=True)
br_zadatka_3_text = visual.TextStim(win=win, name='br_zadatka_3_text',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-14.0);
izbor_broja_z3 = keyboard.Keyboard()
RT_izbor_broja_z3 = keyboard.Keyboard()
# Initialize components for Routine "zadatak_3_sigurnost"
zadatak_3_sigurnostClock = core.Clock()
stupanj_sigurnosti_z3 = visual.TextStim(win=win, name='stupanj_sigurnosti_z3',
text='Koliko ste sigurni u svoj odgovor?',
font='Arial',
pos=(0, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
sigurnost_primjer_z3 = visual.TextStim(win=win, name='sigurnost_primjer_z3',
text='(NAPOMENA: procijenite na ljestvici od 1% do 100%)',
font='Arial',
pos=(0, 0.35), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
sigurnost_odgovor_z3 = visual.TextStim(win=win, name='sigurnost_odgovor_z3',
text='default text',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
nastavi_25 = visual.TextStim(win=win, name='nastavi_25',
text='Kad ste procijenili pritisnite "NASTAVI"',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-4.0);
zadatak_3_2 = visual.Rect(
win=win, name='zadatak_3_2',
width=(0.25, 0.1)[0], height=(0.25, 0.1)[1],
ori=0, pos=(-0.77, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-5.0, interpolate=True)
zadatak_3_text_2 = visual.TextStim(win=win, name='zadatak_3_text_2',
text='ZADATAK 3',
font='Arial Black',
pos=(-0.77, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-6.0);
br_zadatka_3_2 = visual.Rect(
win=win, name='br_zadatka_3_2',
width=(0.15, 0.1)[0], height=(0.15, 0.1)[1],
ori=0, pos=(0.84, 0.41),
lineWidth=0, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[0.859,-0.780,-0.718], fillColorSpace='rgb',
opacity=1, depth=-7.0, interpolate=True)
br_zadatka_3_3 = visual.TextStim(win=win, name='br_zadatka_3_3',
text='default text',
font='Arial Black',
pos=(0.83, 0.41), height=0.03, wrapWidth=None, ori=0,
color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-8.0);
key_resp_14 = keyboard.Keyboard()
# Initialize components for Routine "kraj_i_zahvala"
kraj_i_zahvalaClock = core.Clock()
gotov_zadatak_3 = visual.TextStim(win=win, name='gotov_zadatak_3',
text='Uspješno ste završili treći zadatak!',
font='Arial',
pos=(0, 0.1), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
hvala_na_sudjelovanju = visual.TextStim(win=win, name='hvala_na_sudjelovanju',
text='S ovim zaključujemo ovaj eksperiment',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
hvala = visual.TextStim(win=win, name='hvala',
text='Hvala Vam na sudjelovanju!',
font='Arial',
pos=(0, -0.1), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
nastavi_26 = visual.TextStim(win=win, name='nastavi_26',
text='Pritisnite "NASTAVI" za završetak eksperimenta',
font='Arial',
pos=(0, -0.43), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-3.0);
Kraj_eksperimenta = keyboard.Keyboard()
# Initialize components for Routine "zavrsna"
zavrsnaClock = core.Clock()
pricekajte = visual.TextStim(win=win, name='pricekajte',
text='Molimo Vas da ostanete sjediti i pričekate\n da ostali završe',
font='Arial',
pos=(0, 0.2), height=0.05, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
citanje_zamolbe = visual.TextStim(win=win, name='citanje_zamolbe',
text='Kako Vam ne bi bilo dosadno dok čekate, pozivamo Vas da iskoristite \n ovu priliku da biste proučili zamolbu za sudjelovanje.\n\n U njoj su ukratko opisane osnovne postavke istraživanja, povijesni \n kontekst, te opća načela vezana za povjerljivost podataka. ',
font='Arial',
pos=(0, 0), height=0.03, wrapWidth=None, ori=0,
color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-1.0);
key_resp = keyboard.Keyboard()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "pocetna"-------
# update component parameters for each repeat
key_resp_0.keys = []
key_resp_0.rt = []
# keep track of which components have finished
pocetnaComponents = [dobrodosli, key_resp_0]
for thisComponent in pocetnaComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
pocetnaClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "pocetna"-------
while continueRoutine:
# get current time
t = pocetnaClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=pocetnaClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *dobrodosli* updates
if dobrodosli.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
dobrodosli.frameNStart = frameN # exact frame index
dobrodosli.tStart = t # local t and not account for scr refresh
dobrodosli.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(dobrodosli, 'tStartRefresh') # time at next scr refresh
dobrodosli.setAutoDraw(True)
# *key_resp_0* updates
waitOnFlip = False
if key_resp_0.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_0.frameNStart = frameN # exact frame index
key_resp_0.tStart = t # local t and not account for scr refresh
key_resp_0.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_0, 'tStartRefresh') # time at next scr refresh
key_resp_0.status = STARTED
# keyboard checking is just starting
win.callOnFlip(key_resp_0.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_0.status == STARTED and not waitOnFlip:
theseKeys = key_resp_0.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in pocetnaComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "pocetna"-------
for thisComponent in pocetnaComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "pocetna" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "upute_tipkovnica"-------
# update component parameters for each repeat
tipkovnica_keys.keys = []
tipkovnica_keys.rt = []
# keep track of which components have finished
upute_tipkovnicaComponents = [tipkovnica, upute_za_tipke, nastavi_tipkovnica, tipkovnica_keys]
for thisComponent in upute_tipkovnicaComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
upute_tipkovnicaClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "upute_tipkovnica"-------
while continueRoutine:
# get current time
t = upute_tipkovnicaClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=upute_tipkovnicaClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *tipkovnica* updates
if tipkovnica.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
tipkovnica.frameNStart = frameN # exact frame index
tipkovnica.tStart = t # local t and not account for scr refresh
tipkovnica.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(tipkovnica, 'tStartRefresh') # time at next scr refresh
tipkovnica.setAutoDraw(True)
# *upute_za_tipke* updates
if upute_za_tipke.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
upute_za_tipke.frameNStart = frameN # exact frame index
upute_za_tipke.tStart = t # local t and not account for scr refresh
upute_za_tipke.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(upute_za_tipke, 'tStartRefresh') # time at next scr refresh
upute_za_tipke.setAutoDraw(True)
# *nastavi_tipkovnica* updates
if nastavi_tipkovnica.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_tipkovnica.frameNStart = frameN # exact frame index
nastavi_tipkovnica.tStart = t # local t and not account for scr refresh
nastavi_tipkovnica.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_tipkovnica, 'tStartRefresh') # time at next scr refresh
nastavi_tipkovnica.setAutoDraw(True)
# *tipkovnica_keys* updates
waitOnFlip = False
if tipkovnica_keys.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
tipkovnica_keys.frameNStart = frameN # exact frame index
tipkovnica_keys.tStart = t # local t and not account for scr refresh
tipkovnica_keys.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(tipkovnica_keys, 'tStartRefresh') # time at next scr refresh
tipkovnica_keys.status = STARTED
# keyboard checking is just starting
win.callOnFlip(tipkovnica_keys.clearEvents, eventType='keyboard') # clear events on next screen flip
if tipkovnica_keys.status == STARTED and not waitOnFlip:
theseKeys = tipkovnica_keys.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in upute_tipkovnicaComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "upute_tipkovnica"-------
for thisComponent in upute_tipkovnicaComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "upute_tipkovnica" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "tipkovnica_nastavi"-------
# update component parameters for each repeat
nastavi_keys.keys = []
nastavi_keys.rt = []
# keep track of which components have finished
tipkovnica_nastaviComponents = [tipkovnica_nastavi_1, nastavi_objasnjenje, nastavi_tipkovnica_1, nastavi_keys]
for thisComponent in tipkovnica_nastaviComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
tipkovnica_nastaviClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "tipkovnica_nastavi"-------
while continueRoutine:
# get current time
t = tipkovnica_nastaviClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=tipkovnica_nastaviClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *tipkovnica_nastavi_1* updates
if tipkovnica_nastavi_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
tipkovnica_nastavi_1.frameNStart = frameN # exact frame index
tipkovnica_nastavi_1.tStart = t # local t and not account for scr refresh
tipkovnica_nastavi_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(tipkovnica_nastavi_1, 'tStartRefresh') # time at next scr refresh
tipkovnica_nastavi_1.setAutoDraw(True)
# *nastavi_objasnjenje* updates
if nastavi_objasnjenje.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_objasnjenje.frameNStart = frameN # exact frame index
nastavi_objasnjenje.tStart = t # local t and not account for scr refresh
nastavi_objasnjenje.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_objasnjenje, 'tStartRefresh') # time at next scr refresh
nastavi_objasnjenje.setAutoDraw(True)
# *nastavi_tipkovnica_1* updates
if nastavi_tipkovnica_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_tipkovnica_1.frameNStart = frameN # exact frame index
nastavi_tipkovnica_1.tStart = t # local t and not account for scr refresh
nastavi_tipkovnica_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_tipkovnica_1, 'tStartRefresh') # time at next scr refresh
nastavi_tipkovnica_1.setAutoDraw(True)
# *nastavi_keys* updates
waitOnFlip = False
if nastavi_keys.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_keys.frameNStart = frameN # exact frame index
nastavi_keys.tStart = t # local t and not account for scr refresh
nastavi_keys.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_keys, 'tStartRefresh') # time at next scr refresh
nastavi_keys.status = STARTED
# keyboard checking is just starting
win.callOnFlip(nastavi_keys.clearEvents, eventType='keyboard') # clear events on next screen flip
if nastavi_keys.status == STARTED and not waitOnFlip:
theseKeys = nastavi_keys.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in tipkovnica_nastaviComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "tipkovnica_nastavi"-------
for thisComponent in tipkovnica_nastaviComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "tipkovnica_nastavi" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "tipkovnica_podesi"-------
# update component parameters for each repeat
podesi_keys.keys = []
podesi_keys.rt = []
# keep track of which components have finished
tipkovnica_podesiComponents = [podesi, podesi_objasnjenje, podesi_nastavi, podesi_keys]
for thisComponent in tipkovnica_podesiComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
tipkovnica_podesiClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "tipkovnica_podesi"-------
while continueRoutine:
# get current time
t = tipkovnica_podesiClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=tipkovnica_podesiClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *podesi* updates
if podesi.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
podesi.frameNStart = frameN # exact frame index
podesi.tStart = t # local t and not account for scr refresh
podesi.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(podesi, 'tStartRefresh') # time at next scr refresh
podesi.setAutoDraw(True)
# *podesi_objasnjenje* updates
if podesi_objasnjenje.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
podesi_objasnjenje.frameNStart = frameN # exact frame index
podesi_objasnjenje.tStart = t # local t and not account for scr refresh
podesi_objasnjenje.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(podesi_objasnjenje, 'tStartRefresh') # time at next scr refresh
podesi_objasnjenje.setAutoDraw(True)
# *podesi_nastavi* updates
if podesi_nastavi.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
podesi_nastavi.frameNStart = frameN # exact frame index
podesi_nastavi.tStart = t # local t and not account for scr refresh
podesi_nastavi.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(podesi_nastavi, 'tStartRefresh') # time at next scr refresh
podesi_nastavi.setAutoDraw(True)
# *podesi_keys* updates
waitOnFlip = False
if podesi_keys.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
podesi_keys.frameNStart = frameN # exact frame index
podesi_keys.tStart = t # local t and not account for scr refresh
podesi_keys.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(podesi_keys, 'tStartRefresh') # time at next scr refresh
podesi_keys.status = STARTED
# keyboard checking is just starting
win.callOnFlip(podesi_keys.clearEvents, eventType='keyboard') # clear events on next screen flip
if podesi_keys.status == STARTED and not waitOnFlip:
theseKeys = podesi_keys.getKeys(keyList=['left', 'right', 'up', 'down'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in tipkovnica_podesiComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "tipkovnica_podesi"-------
for thisComponent in tipkovnica_podesiComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "tipkovnica_podesi" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "tipkovnica_brojevi"-------
# update component parameters for each repeat
brojevi_keys.keys = []
brojevi_keys.rt = []
# keep track of which components have finished
tipkovnica_brojeviComponents = [brojevi, brojevi_objasnjenje, brojevi_nastavi, brojevi_keys]
for thisComponent in tipkovnica_brojeviComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
tipkovnica_brojeviClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "tipkovnica_brojevi"-------
while continueRoutine:
# get current time
t = tipkovnica_brojeviClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=tipkovnica_brojeviClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *brojevi* updates
if brojevi.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
brojevi.frameNStart = frameN # exact frame index
brojevi.tStart = t # local t and not account for scr refresh
brojevi.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(brojevi, 'tStartRefresh') # time at next scr refresh
brojevi.setAutoDraw(True)
# *brojevi_objasnjenje* updates
if brojevi_objasnjenje.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
brojevi_objasnjenje.frameNStart = frameN # exact frame index
brojevi_objasnjenje.tStart = t # local t and not account for scr refresh
brojevi_objasnjenje.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(brojevi_objasnjenje, 'tStartRefresh') # time at next scr refresh
brojevi_objasnjenje.setAutoDraw(True)
# *brojevi_nastavi* updates
if brojevi_nastavi.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
brojevi_nastavi.frameNStart = frameN # exact frame index
brojevi_nastavi.tStart = t # local t and not account for scr refresh
brojevi_nastavi.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(brojevi_nastavi, 'tStartRefresh') # time at next scr refresh
brojevi_nastavi.setAutoDraw(True)
# *brojevi_keys* updates
waitOnFlip = False
if brojevi_keys.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
brojevi_keys.frameNStart = frameN # exact frame index
brojevi_keys.tStart = t # local t and not account for scr refresh
brojevi_keys.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(brojevi_keys, 'tStartRefresh') # time at next scr refresh
brojevi_keys.status = STARTED
# keyboard checking is just starting
win.callOnFlip(brojevi_keys.clearEvents, eventType='keyboard') # clear events on next screen flip
if brojevi_keys.status == STARTED and not waitOnFlip:
theseKeys = brojevi_keys.getKeys(keyList=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in tipkovnica_brojeviComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "tipkovnica_brojevi"-------
for thisComponent in tipkovnica_brojeviComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "tipkovnica_brojevi" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "tipkovnica_brisanje"-------
# update component parameters for each repeat
brisanje_keys.keys = []
brisanje_keys.rt = []
# keep track of which components have finished
tipkovnica_brisanjeComponents = [brisanje, brisanje_objasnjenje, brisanje_nastavi, brisanje_keys]
for thisComponent in tipkovnica_brisanjeComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
tipkovnica_brisanjeClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "tipkovnica_brisanje"-------
while continueRoutine:
# get current time
t = tipkovnica_brisanjeClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=tipkovnica_brisanjeClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *brisanje* updates
if brisanje.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
brisanje.frameNStart = frameN # exact frame index
brisanje.tStart = t # local t and not account for scr refresh
brisanje.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(brisanje, 'tStartRefresh') # time at next scr refresh
brisanje.setAutoDraw(True)
# *brisanje_objasnjenje* updates
if brisanje_objasnjenje.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
brisanje_objasnjenje.frameNStart = frameN # exact frame index
brisanje_objasnjenje.tStart = t # local t and not account for scr refresh
brisanje_objasnjenje.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(brisanje_objasnjenje, 'tStartRefresh') # time at next scr refresh
brisanje_objasnjenje.setAutoDraw(True)
# *brisanje_nastavi* updates
if brisanje_nastavi.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
brisanje_nastavi.frameNStart = frameN # exact frame index
brisanje_nastavi.tStart = t # local t and not account for scr refresh
brisanje_nastavi.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(brisanje_nastavi, 'tStartRefresh') # time at next scr refresh
brisanje_nastavi.setAutoDraw(True)
# *brisanje_keys* updates
waitOnFlip = False
if brisanje_keys.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
brisanje_keys.frameNStart = frameN # exact frame index
brisanje_keys.tStart = t # local t and not account for scr refresh
brisanje_keys.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(brisanje_keys, 'tStartRefresh') # time at next scr refresh
brisanje_keys.status = STARTED
# keyboard checking is just starting
win.callOnFlip(brisanje_keys.clearEvents, eventType='keyboard') # clear events on next screen flip
if brisanje_keys.status == STARTED and not waitOnFlip:
theseKeys = brisanje_keys.getKeys(keyList=['backspace'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in tipkovnica_brisanjeComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "tipkovnica_brisanje"-------
for thisComponent in tipkovnica_brisanjeComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "tipkovnica_brisanje" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials_1 = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('podrazaji\\demografija.xlsx'),
seed=None, name='trials_1')
thisExp.addLoop(trials_1) # add the loop to the experiment
thisTrial_1 = trials_1.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_1.rgb)
if thisTrial_1 != None:
for paramName in thisTrial_1:
exec('{} = thisTrial_1[paramName]'.format(paramName))
for thisTrial_1 in trials_1:
currentLoop = trials_1
# abbreviate parameter names if possible (e.g. rgb = thisTrial_1.rgb)
if thisTrial_1 != None:
for paramName in thisTrial_1:
exec('{} = thisTrial_1[paramName]'.format(paramName))
# ------Prepare to start Routine "demografski_podaci"-------
# update component parameters for each repeat
demog_pitanja.setText(demografski_pitanja)
primjer.setText(demografija_primjer)
demografija_unos.keys = []
demografija_unos.rt = []
screen_text0 = ""
# keep track of which components have finished
demografski_podaciComponents = [demog_pitanja, primjer, unos_demog, nastavi1, demografija_unos]
for thisComponent in demografski_podaciComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
demografski_podaciClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "demografski_podaci"-------
while continueRoutine:
# get current time
t = demografski_podaciClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=demografski_podaciClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *demog_pitanja* updates
if demog_pitanja.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
demog_pitanja.frameNStart = frameN # exact frame index
demog_pitanja.tStart = t # local t and not account for scr refresh
demog_pitanja.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(demog_pitanja, 'tStartRefresh') # time at next scr refresh
demog_pitanja.setAutoDraw(True)
# *primjer* updates
if primjer.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
primjer.frameNStart = frameN # exact frame index
primjer.tStart = t # local t and not account for scr refresh
primjer.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(primjer, 'tStartRefresh') # time at next scr refresh
primjer.setAutoDraw(True)
# *unos_demog* updates
if unos_demog.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
unos_demog.frameNStart = frameN # exact frame index
unos_demog.tStart = t # local t and not account for scr refresh
unos_demog.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(unos_demog, 'tStartRefresh') # time at next scr refresh
unos_demog.setAutoDraw(True)
if unos_demog.status == STARTED: # only update if drawing
unos_demog.setText(screen_text0, log=False)
# *nastavi1* updates
if nastavi1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi1.frameNStart = frameN # exact frame index
nastavi1.tStart = t # local t and not account for scr refresh
nastavi1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi1, 'tStartRefresh') # time at next scr refresh
nastavi1.setAutoDraw(True)
# *demografija_unos* updates
waitOnFlip = False
if demografija_unos.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
demografija_unos.frameNStart = frameN # exact frame index
demografija_unos.tStart = t # local t and not account for scr refresh
demografija_unos.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(demografija_unos, 'tStartRefresh') # time at next scr refresh
demografija_unos.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(demografija_unos.clock.reset) # t=0 on next screen flip
win.callOnFlip(demografija_unos.clearEvents, eventType='keyboard') # clear events on next screen flip
if demografija_unos.status == STARTED and not waitOnFlip:
theseKeys = demografija_unos.getKeys(keyList=['space', 'backspace', 'Z', 'M', 'z', 'm', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
demografija_unos.keys.append(theseKeys.name) # storing all keys
demografija_unos.rt.append(theseKeys.rt)
#Ako pritisnemo "backspace", napisan izraz backspace se briše
if("backspace" in demografija_unos.keys):
demografija_unos.keys.remove ("backspace")
#Ako postoji više od jednog slova ili elementa, posljednji element koji se
#utipkao se briše
if(len(demografija_unos.keys) > 0):
demografija_unos.keys.pop()
#Ista stvar kao i iznad samo za space
elif("space" in demografija_unos.keys):
demografija_unos.keys.remove("space")
#Ako su istipkana dva slova, onda se prebacuje u screen_text varijablu
#ako je više ili manje od dva, onda se ne pohranjuje
#Ovo je prisila da unesu svoje vrijednoti (da ne bi ostalo prazno)
if(len(demografija_unos.keys) >= 1):
screen_text0 = "".join(demografija_unos.keys)
#Ovo prebacuje vrijednosti iz varijable u excel
thisExp.addData("demografija", screen_text0)
#nakon što su utipkali dva slova, space prekida rutinu
continueRoutine = False
#ovo spaja stringove zajedno tako da nemaju navodnike
screen_text0 = "".join(demografija_unos.keys)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in demografski_podaciComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "demografski_podaci"-------
for thisComponent in demografski_podaciComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if demografija_unos.keys in ['', [], None]: # No response was made
demografija_unos.keys = None
trials_1.addData('demografija_unos.keys',demografija_unos.keys)
if demografija_unos.keys != None: # we had a response
trials_1.addData('demografija_unos.rt', demografija_unos.rt)
# the Routine "demografski_podaci" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'trials_1'
# ------Prepare to start Routine "upute_kod"-------
# update component parameters for each repeat
key_resp_2.keys = []
key_resp_2.rt = []
# keep track of which components have finished
upute_kodComponents = [anonimnost, nastavi2, key_resp_2]
for thisComponent in upute_kodComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
upute_kodClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "upute_kod"-------
while continueRoutine:
# get current time
t = upute_kodClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=upute_kodClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *anonimnost* updates
if anonimnost.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
anonimnost.frameNStart = frameN # exact frame index
anonimnost.tStart = t # local t and not account for scr refresh
anonimnost.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(anonimnost, 'tStartRefresh') # time at next scr refresh
anonimnost.setAutoDraw(True)
# *nastavi2* updates
if nastavi2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi2.frameNStart = frameN # exact frame index
nastavi2.tStart = t # local t and not account for scr refresh
nastavi2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi2, 'tStartRefresh') # time at next scr refresh
nastavi2.setAutoDraw(True)
# *key_resp_2* updates
waitOnFlip = False
if key_resp_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_2.frameNStart = frameN # exact frame index
key_resp_2.tStart = t # local t and not account for scr refresh
key_resp_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_2, 'tStartRefresh') # time at next scr refresh
key_resp_2.status = STARTED
# keyboard checking is just starting
if key_resp_2.status == STARTED and not waitOnFlip:
theseKeys = key_resp_2.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in upute_kodComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "upute_kod"-------
for thisComponent in upute_kodComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "upute_kod" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials_2 = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('podrazaji\\algoritam.xlsx'),
seed=None, name='trials_2')
thisExp.addLoop(trials_2) # add the loop to the experiment
thisTrial_2 = trials_2.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_2.rgb)
if thisTrial_2 != None:
for paramName in thisTrial_2:
exec('{} = thisTrial_2[paramName]'.format(paramName))
for thisTrial_2 in trials_2:
currentLoop = trials_2
# abbreviate parameter names if possible (e.g. rgb = thisTrial_2.rgb)
if thisTrial_2 != None:
for paramName in thisTrial_2:
exec('{} = thisTrial_2[paramName]'.format(paramName))
# ------Prepare to start Routine "jedinstveni_kod"-------
# update component parameters for each repeat
lozinka_pitanja.setText(algoritam1)
primjer1.setText(primjeri)
lozinka_unos.keys = []
lozinka_unos.rt = []
#Formiranje varijable u kojoj se pospremaju rezultati tipkanja
#Ona mora biti prazna tako da je možemo puniti u svakoj rutini
screen_text = ""
# keep track of which components have finished
jedinstveni_kodComponents = [lozinka_pitanja, primjer1, unos_koda, nastavi3, lozinka_unos]
for thisComponent in jedinstveni_kodComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
jedinstveni_kodClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "jedinstveni_kod"-------
while continueRoutine:
# get current time
t = jedinstveni_kodClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=jedinstveni_kodClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *lozinka_pitanja* updates
if lozinka_pitanja.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
lozinka_pitanja.frameNStart = frameN # exact frame index
lozinka_pitanja.tStart = t # local t and not account for scr refresh
lozinka_pitanja.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(lozinka_pitanja, 'tStartRefresh') # time at next scr refresh
lozinka_pitanja.setAutoDraw(True)
# *primjer1* updates
if primjer1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
primjer1.frameNStart = frameN # exact frame index
primjer1.tStart = t # local t and not account for scr refresh
primjer1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(primjer1, 'tStartRefresh') # time at next scr refresh
primjer1.setAutoDraw(True)
# *unos_koda* updates
if unos_koda.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
unos_koda.frameNStart = frameN # exact frame index
unos_koda.tStart = t # local t and not account for scr refresh
unos_koda.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(unos_koda, 'tStartRefresh') # time at next scr refresh
unos_koda.setAutoDraw(True)
if unos_koda.status == STARTED: # only update if drawing
unos_koda.setText(screen_text, log=False)
# *nastavi3* updates
if nastavi3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi3.frameNStart = frameN # exact frame index
nastavi3.tStart = t # local t and not account for scr refresh
nastavi3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi3, 'tStartRefresh') # time at next scr refresh
nastavi3.setAutoDraw(True)
# *lozinka_unos* updates
waitOnFlip = False
if lozinka_unos.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
lozinka_unos.frameNStart = frameN # exact frame index
lozinka_unos.tStart = t # local t and not account for scr refresh
lozinka_unos.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(lozinka_unos, 'tStartRefresh') # time at next scr refresh
lozinka_unos.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(lozinka_unos.clock.reset) # t=0 on next screen flip
if lozinka_unos.status == STARTED and not waitOnFlip:
theseKeys = lozinka_unos.getKeys(keyList=['space', 'backspace', 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'š', 'đ', 'ž', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'č', 'ć', 'y', 'x', 'c', 'v', 'b', 'n', 'm', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'num_0'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
lozinka_unos.keys.append(theseKeys.name) # storing all keys
lozinka_unos.rt.append(theseKeys.rt)
#Ako pritisnemo "backspace", napisan izraz backspace se briše
if("backspace" in lozinka_unos.keys):
lozinka_unos.keys.remove ("backspace")
#Ako postoji više od jednog slova ili elementa, posljednji element koji se
#utipkao se briše
if(len(lozinka_unos.keys) > 0):
lozinka_unos.keys.pop()
#Ista stvar kao i iznad samo za space
elif("space" in lozinka_unos.keys):
lozinka_unos.keys.remove("space")
#Ako su istipkana dva slova, onda se prebacuje u screen_text varijablu
#ako je više ili manje od dva, onda se ne pohranjuje
#Ovo je prisila da unesu svoje vrijednoti (da ne bi ostalo prazno)
if(len(lozinka_unos.keys) == 2):
screen_text = "".join(lozinka_unos.keys)
#Ovo prebacuje vrijednosti iz varijable u excel
thisExp.addData("lozinka", screen_text)
#nakon što su utipkali dva slova, space prekida rutinu
continueRoutine = False
#ovo spaja stringove zajedno tako da nemaju navodnike
screen_text = "".join(lozinka_unos.keys)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in jedinstveni_kodComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "jedinstveni_kod"-------
for thisComponent in jedinstveni_kodComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if lozinka_unos.keys in ['', [], None]: # No response was made
lozinka_unos.keys = None
trials_2.addData('lozinka_unos.keys',lozinka_unos.keys)
if lozinka_unos.keys != None: # we had a response
trials_2.addData('lozinka_unos.rt', lozinka_unos.rt)
#Nakon unesenog odgovora (za svako pitanje), ovo ispod ga doda na listu
kod.append(screen_text)
# the Routine "jedinstveni_kod" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'trials_2'
# ------Prepare to start Routine "prikaz_koda"-------
# update component parameters for each repeat
#Ovo spaja stringove u listi "kod" u jedan string
#Najbitniji dio koda koji sam do sada napisao :)
msg = "".join(str(x) for x in kod)
key_resp_3.keys = []
key_resp_3.rt = []
# keep track of which components have finished
prikaz_kodaComponents = [lozinka_je, lozinka, prepis_lozinke, nastavi4, key_resp_3]
for thisComponent in prikaz_kodaComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
prikaz_kodaClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "prikaz_koda"-------
while continueRoutine:
# get current time
t = prikaz_kodaClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=prikaz_kodaClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *lozinka_je* updates
if lozinka_je.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
lozinka_je.frameNStart = frameN # exact frame index
lozinka_je.tStart = t # local t and not account for scr refresh
lozinka_je.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(lozinka_je, 'tStartRefresh') # time at next scr refresh
lozinka_je.setAutoDraw(True)
# *lozinka* updates
if lozinka.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
lozinka.frameNStart = frameN # exact frame index
lozinka.tStart = t # local t and not account for scr refresh
lozinka.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(lozinka, 'tStartRefresh') # time at next scr refresh
lozinka.setAutoDraw(True)
if lozinka.status == STARTED: # only update if drawing
lozinka.setText(msg, log=False)
# *prepis_lozinke* updates
if prepis_lozinke.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
prepis_lozinke.frameNStart = frameN # exact frame index
prepis_lozinke.tStart = t # local t and not account for scr refresh
prepis_lozinke.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(prepis_lozinke, 'tStartRefresh') # time at next scr refresh
prepis_lozinke.setAutoDraw(True)
# *nastavi4* updates
if nastavi4.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi4.frameNStart = frameN # exact frame index
nastavi4.tStart = t # local t and not account for scr refresh
nastavi4.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi4, 'tStartRefresh') # time at next scr refresh
nastavi4.setAutoDraw(True)
# *key_resp_3* updates
waitOnFlip = False
if key_resp_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_3.frameNStart = frameN # exact frame index
key_resp_3.tStart = t # local t and not account for scr refresh
key_resp_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_3, 'tStartRefresh') # time at next scr refresh
key_resp_3.status = STARTED
# keyboard checking is just starting
if key_resp_3.status == STARTED and not waitOnFlip:
theseKeys = key_resp_3.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in prikaz_kodaComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "prikaz_koda"-------
for thisComponent in prikaz_kodaComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "prikaz_koda" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "generalne_upute"-------
# update component parameters for each repeat
key_resp_4.keys = []
key_resp_4.rt = []
# keep track of which components have finished
generalne_uputeComponents = [generalne_upute_1, tri_upute, nastavi_5, key_resp_4]
for thisComponent in generalne_uputeComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
generalne_uputeClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "generalne_upute"-------
while continueRoutine:
# get current time
t = generalne_uputeClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=generalne_uputeClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *generalne_upute_1* updates
if generalne_upute_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
generalne_upute_1.frameNStart = frameN # exact frame index
generalne_upute_1.tStart = t # local t and not account for scr refresh
generalne_upute_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(generalne_upute_1, 'tStartRefresh') # time at next scr refresh
generalne_upute_1.setAutoDraw(True)
# *tri_upute* updates
if tri_upute.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
tri_upute.frameNStart = frameN # exact frame index
tri_upute.tStart = t # local t and not account for scr refresh
tri_upute.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(tri_upute, 'tStartRefresh') # time at next scr refresh
tri_upute.setAutoDraw(True)
# *nastavi_5* updates
if nastavi_5.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_5.frameNStart = frameN # exact frame index
nastavi_5.tStart = t # local t and not account for scr refresh
nastavi_5.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_5, 'tStartRefresh') # time at next scr refresh
nastavi_5.setAutoDraw(True)
# *key_resp_4* updates
waitOnFlip = False
if key_resp_4.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_4.frameNStart = frameN # exact frame index
key_resp_4.tStart = t # local t and not account for scr refresh
key_resp_4.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_4, 'tStartRefresh') # time at next scr refresh
key_resp_4.status = STARTED
# keyboard checking is just starting
win.callOnFlip(key_resp_4.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_4.status == STARTED and not waitOnFlip:
theseKeys = key_resp_4.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in generalne_uputeComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "generalne_upute"-------
for thisComponent in generalne_uputeComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "generalne_upute" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "uputa_zadatak_1"-------
# update component parameters for each repeat
key_resp_5.keys = []
key_resp_5.rt = []
# keep track of which components have finished
uputa_zadatak_1Components = [naslov_uputa, generalna_uputa_z1, nastavi_6, zadatak, zadatak_tekst, key_resp_5]
for thisComponent in uputa_zadatak_1Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
uputa_zadatak_1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "uputa_zadatak_1"-------
while continueRoutine:
# get current time
t = uputa_zadatak_1Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=uputa_zadatak_1Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *naslov_uputa* updates
if naslov_uputa.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
naslov_uputa.frameNStart = frameN # exact frame index
naslov_uputa.tStart = t # local t and not account for scr refresh
naslov_uputa.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(naslov_uputa, 'tStartRefresh') # time at next scr refresh
naslov_uputa.setAutoDraw(True)
# *generalna_uputa_z1* updates
if generalna_uputa_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
generalna_uputa_z1.frameNStart = frameN # exact frame index
generalna_uputa_z1.tStart = t # local t and not account for scr refresh
generalna_uputa_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(generalna_uputa_z1, 'tStartRefresh') # time at next scr refresh
generalna_uputa_z1.setAutoDraw(True)
# *nastavi_6* updates
if nastavi_6.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_6.frameNStart = frameN # exact frame index
nastavi_6.tStart = t # local t and not account for scr refresh
nastavi_6.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_6, 'tStartRefresh') # time at next scr refresh
nastavi_6.setAutoDraw(True)
# *zadatak* updates
if zadatak.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak.frameNStart = frameN # exact frame index
zadatak.tStart = t # local t and not account for scr refresh
zadatak.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak, 'tStartRefresh') # time at next scr refresh
zadatak.setAutoDraw(True)
# *zadatak_tekst* updates
if zadatak_tekst.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_tekst.frameNStart = frameN # exact frame index
zadatak_tekst.tStart = t # local t and not account for scr refresh
zadatak_tekst.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_tekst, 'tStartRefresh') # time at next scr refresh
zadatak_tekst.setAutoDraw(True)
# *key_resp_5* updates
waitOnFlip = False
if key_resp_5.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_5.frameNStart = frameN # exact frame index
key_resp_5.tStart = t # local t and not account for scr refresh
key_resp_5.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_5, 'tStartRefresh') # time at next scr refresh
key_resp_5.status = STARTED
# keyboard checking is just starting
win.callOnFlip(key_resp_5.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_5.status == STARTED and not waitOnFlip:
theseKeys = key_resp_5.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in uputa_zadatak_1Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "uputa_zadatak_1"-------
for thisComponent in uputa_zadatak_1Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "uputa_zadatak_1" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "vjezba"-------
# update component parameters for each repeat
pocetak_vjezbe.keys = []
pocetak_vjezbe.rt = []
# keep track of which components have finished
vjezbaComponents = [vjezba_0, zadaci_za_vjezbu, nastavi_vjezba, pocetak_vjezbe]
for thisComponent in vjezbaComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezbaClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba"-------
while continueRoutine:
# get current time
t = vjezbaClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezbaClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *vjezba_0* updates
if vjezba_0.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_0.frameNStart = frameN # exact frame index
vjezba_0.tStart = t # local t and not account for scr refresh
vjezba_0.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_0, 'tStartRefresh') # time at next scr refresh
vjezba_0.setAutoDraw(True)
# *zadaci_za_vjezbu* updates
if zadaci_za_vjezbu.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadaci_za_vjezbu.frameNStart = frameN # exact frame index
zadaci_za_vjezbu.tStart = t # local t and not account for scr refresh
zadaci_za_vjezbu.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadaci_za_vjezbu, 'tStartRefresh') # time at next scr refresh
zadaci_za_vjezbu.setAutoDraw(True)
# *nastavi_vjezba* updates
if nastavi_vjezba.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_vjezba.frameNStart = frameN # exact frame index
nastavi_vjezba.tStart = t # local t and not account for scr refresh
nastavi_vjezba.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_vjezba, 'tStartRefresh') # time at next scr refresh
nastavi_vjezba.setAutoDraw(True)
# *pocetak_vjezbe* updates
waitOnFlip = False
if pocetak_vjezbe.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
pocetak_vjezbe.frameNStart = frameN # exact frame index
pocetak_vjezbe.tStart = t # local t and not account for scr refresh
pocetak_vjezbe.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(pocetak_vjezbe, 'tStartRefresh') # time at next scr refresh
pocetak_vjezbe.status = STARTED
# keyboard checking is just starting
win.callOnFlip(pocetak_vjezbe.clearEvents, eventType='keyboard') # clear events on next screen flip
if pocetak_vjezbe.status == STARTED and not waitOnFlip:
theseKeys = pocetak_vjezbe.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezbaComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba"-------
for thisComponent in vjezbaComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "vjezba" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials_3 = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('podrazaji\\eksperimentalni_podrazaji_v1.xlsx'),
seed=None, name='trials_3')
thisExp.addLoop(trials_3) # add the loop to the experiment
thisTrial_3 = trials_3.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_3.rgb)
if thisTrial_3 != None:
for paramName in thisTrial_3:
exec('{} = thisTrial_3[paramName]'.format(paramName))
for thisTrial_3 in trials_3:
currentLoop = trials_3
# abbreviate parameter names if possible (e.g. rgb = thisTrial_3.rgb)
if thisTrial_3 != None:
for paramName in thisTrial_3:
exec('{} = thisTrial_3[paramName]'.format(paramName))
# ------Prepare to start Routine "vjezba_1_pamcenje"-------
# update component parameters for each repeat
zadana_slika_v1= re.sub("[^0-9]", "", vjezba_v1)
ovaj_broj_v1 = str(trials_3.thisN + 1)
ukupan_broj_v1 = str(trials_3.nTotal)
ostatak_v1 = ovaj_broj_v1 + " / " + ukupan_broj_v1
uputa_v1.setText('Zapamtite veličinu prikazanog kruga')
podrazaj_v1.setImage(vjezba_v1)
br_vjezbe_1_text.setText(ostatak_v1
)
pamcenje_slike_v1.keys = []
pamcenje_slike_v1.rt = []
# keep track of which components have finished
vjezba_1_pamcenjeComponents = [uputa_v1, podrazaj_v1, nastavi_7, vjezba_1_, vjezba_1_text, br_vjezbe_1_, br_vjezbe_1_text, pamcenje_slike_v1]
for thisComponent in vjezba_1_pamcenjeComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezba_1_pamcenjeClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba_1_pamcenje"-------
while continueRoutine:
# get current time
t = vjezba_1_pamcenjeClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezba_1_pamcenjeClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *uputa_v1* updates
if uputa_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
uputa_v1.frameNStart = frameN # exact frame index
uputa_v1.tStart = t # local t and not account for scr refresh
uputa_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(uputa_v1, 'tStartRefresh') # time at next scr refresh
uputa_v1.setAutoDraw(True)
# *podrazaj_v1* updates
if podrazaj_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
podrazaj_v1.frameNStart = frameN # exact frame index
podrazaj_v1.tStart = t # local t and not account for scr refresh
podrazaj_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(podrazaj_v1, 'tStartRefresh') # time at next scr refresh
podrazaj_v1.setAutoDraw(True)
# *nastavi_7* updates
if nastavi_7.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_7.frameNStart = frameN # exact frame index
nastavi_7.tStart = t # local t and not account for scr refresh
nastavi_7.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_7, 'tStartRefresh') # time at next scr refresh
nastavi_7.setAutoDraw(True)
# *vjezba_1_* updates
if vjezba_1_.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_1_.frameNStart = frameN # exact frame index
vjezba_1_.tStart = t # local t and not account for scr refresh
vjezba_1_.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_1_, 'tStartRefresh') # time at next scr refresh
vjezba_1_.setAutoDraw(True)
# *vjezba_1_text* updates
if vjezba_1_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_1_text.frameNStart = frameN # exact frame index
vjezba_1_text.tStart = t # local t and not account for scr refresh
vjezba_1_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_1_text, 'tStartRefresh') # time at next scr refresh
vjezba_1_text.setAutoDraw(True)
# *br_vjezbe_1_* updates
if br_vjezbe_1_.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_1_.frameNStart = frameN # exact frame index
br_vjezbe_1_.tStart = t # local t and not account for scr refresh
br_vjezbe_1_.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_1_, 'tStartRefresh') # time at next scr refresh
br_vjezbe_1_.setAutoDraw(True)
# *br_vjezbe_1_text* updates
if br_vjezbe_1_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_1_text.frameNStart = frameN # exact frame index
br_vjezbe_1_text.tStart = t # local t and not account for scr refresh
br_vjezbe_1_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_1_text, 'tStartRefresh') # time at next scr refresh
br_vjezbe_1_text.setAutoDraw(True)
# *pamcenje_slike_v1* updates
waitOnFlip = False
if pamcenje_slike_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
pamcenje_slike_v1.frameNStart = frameN # exact frame index
pamcenje_slike_v1.tStart = t # local t and not account for scr refresh
pamcenje_slike_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(pamcenje_slike_v1, 'tStartRefresh') # time at next scr refresh
pamcenje_slike_v1.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(pamcenje_slike_v1.clock.reset) # t=0 on next screen flip
win.callOnFlip(pamcenje_slike_v1.clearEvents, eventType='keyboard') # clear events on next screen flip
if pamcenje_slike_v1.status == STARTED and not waitOnFlip:
theseKeys = pamcenje_slike_v1.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
pamcenje_slike_v1.keys = theseKeys.name # just the last key pressed
pamcenje_slike_v1.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezba_1_pamcenjeComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba_1_pamcenje"-------
for thisComponent in vjezba_1_pamcenjeComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
#save numeric version e.g. 15 = size 1 and orientation 5
trials_3.addData('zadana_slika_v1_PNG', vjezba_v1)
#save numeric version e.g. 15 = size 1 and orientation 5
trials_3.addData('zadana_slika_v1', zadana_slika_v1)
# check responses
if pamcenje_slike_v1.keys in ['', [], None]: # No response was made
pamcenje_slike_v1.keys = None
trials_3.addData('pamcenje_slike_v1.keys',pamcenje_slike_v1.keys)
if pamcenje_slike_v1.keys != None: # we had a response
trials_3.addData('pamcenje_slike_v1.rt', pamcenje_slike_v1.rt)
# the Routine "vjezba_1_pamcenje" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "mpi_sum"-------
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
mpi_sumComponents = [sum]
for thisComponent in mpi_sumComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
mpi_sumClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "mpi_sum"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = mpi_sumClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=mpi_sumClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *sum* updates
if sum.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sum.frameNStart = frameN # exact frame index
sum.tStart = t # local t and not account for scr refresh
sum.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sum, 'tStartRefresh') # time at next scr refresh
sum.setAutoDraw(True)
if sum.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > sum.tStartRefresh + 1.0-frameTolerance:
# keep track of stop time/frame for later
sum.tStop = t # not accounting for scr refresh
sum.frameNStop = frameN # exact frame index
win.timeOnFlip(sum, 'tStopRefresh') # time at next scr refresh
sum.setAutoDraw(False)
if sum.status == STARTED:
if sum._needBuild:
sum.buildNoise()
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in mpi_sumComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "mpi_sum"-------
for thisComponent in mpi_sumComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# ------Prepare to start Routine "vjezba_1_odgovor"-------
# update component parameters for each repeat
raspon_v1 = range(1, 210)
imgList_v01 = list(raspon_v1)
imgList_v1 = str(imgList_v01)
imgChoice_v1 = ""
#generate a random number between 1 and 5 for the starting image to be presented as
imgStart_v1 = randint(1, 2)
uputa_v1_1.setText('Podesite veličinu ovog kruga da odgovara veličini prethodnog kruga\n')
br_vjezbe_1_text_1.setText(ostatak_v1
)
izbor_slike_v1.keys = []
izbor_slike_v1.rt = []
# keep track of which components have finished
vjezba_1_odgovorComponents = [uputa_v1_1, odgovor_v1, nastavi_8, vjezba_1_1, vjezba_1_text_1, br_vjezbe_1_1, br_vjezbe_1_text_1, str_gore_v1, gore_v1, str_dolje_v1, dolje_v1, izbor_slike_v1]
for thisComponent in vjezba_1_odgovorComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezba_1_odgovorClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba_1_odgovor"-------
while continueRoutine:
# get current time
t = vjezba_1_odgovorClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezba_1_odgovorClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
import re
raspon_v1 = range(1, 210)
imgList_v01 = list(raspon_v1)
imgList_v1 = str(imgList_v01)
imgChoice_v10 = str(imgStart_v1)
if imgChoice_v10 in imgList_v1:
imgChoice_v1 = "krugovi/"+imgChoice_v10 +".png"
odabrana_slika_v1= re.sub("[^0-9]", "", imgChoice_v1)
#decrease size with left button
if event.getKeys(['down']):
if imgStart_v1>1:
imgStart_v1=imgStart_v1-1
else:
imgStart_V1=1
#increase size with right button
if event.getKeys(['up']):
if imgStart_v1<210:
imgStart_v1=imgStart_v1+1
else:
imgStart_v1=210
# *uputa_v1_1* updates
if uputa_v1_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
uputa_v1_1.frameNStart = frameN # exact frame index
uputa_v1_1.tStart = t # local t and not account for scr refresh
uputa_v1_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(uputa_v1_1, 'tStartRefresh') # time at next scr refresh
uputa_v1_1.setAutoDraw(True)
# *odgovor_v1* updates
if odgovor_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
odgovor_v1.frameNStart = frameN # exact frame index
odgovor_v1.tStart = t # local t and not account for scr refresh
odgovor_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(odgovor_v1, 'tStartRefresh') # time at next scr refresh
odgovor_v1.setAutoDraw(True)
if odgovor_v1.status == STARTED: # only update if drawing
odgovor_v1.setImage(imgChoice_v1, log=False)
# *nastavi_8* updates
if nastavi_8.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_8.frameNStart = frameN # exact frame index
nastavi_8.tStart = t # local t and not account for scr refresh
nastavi_8.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_8, 'tStartRefresh') # time at next scr refresh
nastavi_8.setAutoDraw(True)
# *vjezba_1_1* updates
if vjezba_1_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_1_1.frameNStart = frameN # exact frame index
vjezba_1_1.tStart = t # local t and not account for scr refresh
vjezba_1_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_1_1, 'tStartRefresh') # time at next scr refresh
vjezba_1_1.setAutoDraw(True)
# *vjezba_1_text_1* updates
if vjezba_1_text_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_1_text_1.frameNStart = frameN # exact frame index
vjezba_1_text_1.tStart = t # local t and not account for scr refresh
vjezba_1_text_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_1_text_1, 'tStartRefresh') # time at next scr refresh
vjezba_1_text_1.setAutoDraw(True)
# *br_vjezbe_1_1* updates
if br_vjezbe_1_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_1_1.frameNStart = frameN # exact frame index
br_vjezbe_1_1.tStart = t # local t and not account for scr refresh
br_vjezbe_1_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_1_1, 'tStartRefresh') # time at next scr refresh
br_vjezbe_1_1.setAutoDraw(True)
# *br_vjezbe_1_text_1* updates
if br_vjezbe_1_text_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_1_text_1.frameNStart = frameN # exact frame index
br_vjezbe_1_text_1.tStart = t # local t and not account for scr refresh
br_vjezbe_1_text_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_1_text_1, 'tStartRefresh') # time at next scr refresh
br_vjezbe_1_text_1.setAutoDraw(True)
# *str_gore_v1* updates
if str_gore_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
str_gore_v1.frameNStart = frameN # exact frame index
str_gore_v1.tStart = t # local t and not account for scr refresh
str_gore_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(str_gore_v1, 'tStartRefresh') # time at next scr refresh
str_gore_v1.setAutoDraw(True)
# *gore_v1* updates
if gore_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
gore_v1.frameNStart = frameN # exact frame index
gore_v1.tStart = t # local t and not account for scr refresh
gore_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(gore_v1, 'tStartRefresh') # time at next scr refresh
gore_v1.setAutoDraw(True)
# *str_dolje_v1* updates
if str_dolje_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
str_dolje_v1.frameNStart = frameN # exact frame index
str_dolje_v1.tStart = t # local t and not account for scr refresh
str_dolje_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(str_dolje_v1, 'tStartRefresh') # time at next scr refresh
str_dolje_v1.setAutoDraw(True)
# *dolje_v1* updates
if dolje_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
dolje_v1.frameNStart = frameN # exact frame index
dolje_v1.tStart = t # local t and not account for scr refresh
dolje_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(dolje_v1, 'tStartRefresh') # time at next scr refresh
dolje_v1.setAutoDraw(True)
# *izbor_slike_v1* updates
waitOnFlip = False
if izbor_slike_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
izbor_slike_v1.frameNStart = frameN # exact frame index
izbor_slike_v1.tStart = t # local t and not account for scr refresh
izbor_slike_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(izbor_slike_v1, 'tStartRefresh') # time at next scr refresh
izbor_slike_v1.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(izbor_slike_v1.clock.reset) # t=0 on next screen flip
win.callOnFlip(izbor_slike_v1.clearEvents, eventType='keyboard') # clear events on next screen flip
if izbor_slike_v1.status == STARTED and not waitOnFlip:
theseKeys = izbor_slike_v1.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
izbor_slike_v1.keys = theseKeys.name # just the last key pressed
izbor_slike_v1.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezba_1_odgovorComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba_1_odgovor"-------
for thisComponent in vjezba_1_odgovorComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
#save data
#comment the code below if you do not want the data to be stored, or uncomment each line
#saves .png file name of image choice e.g. stims/1_5.png
trials_3.addData('imgChoice_v1', imgChoice_v1)
#save numeric version e.g. 15 = size 1 and orientation 5
trials_3.addData('odabrana_slika_v1', odabrana_slika_v1)
# check responses
if izbor_slike_v1.keys in ['', [], None]: # No response was made
izbor_slike_v1.keys = None
trials_3.addData('izbor_slike_v1.keys',izbor_slike_v1.keys)
if izbor_slike_v1.keys != None: # we had a response
trials_3.addData('izbor_slike_v1.rt', izbor_slike_v1.rt)
# the Routine "vjezba_1_odgovor" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "vjezba_1_sigurnost"-------
# update component parameters for each repeat
screen_text_v1 = ""
br_vjezbe_1_text_2.setText(ostatak_v1
)
key_resp_8.keys = []
key_resp_8.rt = []
# keep track of which components have finished
vjezba_1_sigurnostComponents = [stupanj_sigurnosti_v1, sigurnost_primjer_v1, sigurnost_odgovor_v1, nastavi_9, vjezba_1_2, vjezba_1_text_2, br_vjezbe_1_2, br_vjezbe_1_text_2, key_resp_8]
for thisComponent in vjezba_1_sigurnostComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezba_1_sigurnostClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba_1_sigurnost"-------
while continueRoutine:
# get current time
t = vjezba_1_sigurnostClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezba_1_sigurnostClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
if("backspace" in key_resp_8.keys):
key_resp_8.keys.remove ("backspace")
if(len(key_resp_8.keys) > 0):
key_resp_8.keys.pop()
elif("space" in key_resp_8.keys):
key_resp_8.keys.remove("space")
if(len(key_resp_8.keys) >= 1):
screen_text_v1 = "".join(key_resp_8.keys)
thisExp.addData("stupnjevi_sigurnosti", screen_text_v1)
continueRoutine = False
screen_text_v1 = "".join(key_resp_8.keys) + "%"
# *stupanj_sigurnosti_v1* updates
if stupanj_sigurnosti_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
stupanj_sigurnosti_v1.frameNStart = frameN # exact frame index
stupanj_sigurnosti_v1.tStart = t # local t and not account for scr refresh
stupanj_sigurnosti_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(stupanj_sigurnosti_v1, 'tStartRefresh') # time at next scr refresh
stupanj_sigurnosti_v1.setAutoDraw(True)
# *sigurnost_primjer_v1* updates
if sigurnost_primjer_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_primjer_v1.frameNStart = frameN # exact frame index
sigurnost_primjer_v1.tStart = t # local t and not account for scr refresh
sigurnost_primjer_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_primjer_v1, 'tStartRefresh') # time at next scr refresh
sigurnost_primjer_v1.setAutoDraw(True)
# *sigurnost_odgovor_v1* updates
if sigurnost_odgovor_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_odgovor_v1.frameNStart = frameN # exact frame index
sigurnost_odgovor_v1.tStart = t # local t and not account for scr refresh
sigurnost_odgovor_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_odgovor_v1, 'tStartRefresh') # time at next scr refresh
sigurnost_odgovor_v1.setAutoDraw(True)
if sigurnost_odgovor_v1.status == STARTED: # only update if drawing
sigurnost_odgovor_v1.setText(screen_text_v1, log=False)
# *nastavi_9* updates
if nastavi_9.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_9.frameNStart = frameN # exact frame index
nastavi_9.tStart = t # local t and not account for scr refresh
nastavi_9.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_9, 'tStartRefresh') # time at next scr refresh
nastavi_9.setAutoDraw(True)
# *vjezba_1_2* updates
if vjezba_1_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_1_2.frameNStart = frameN # exact frame index
vjezba_1_2.tStart = t # local t and not account for scr refresh
vjezba_1_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_1_2, 'tStartRefresh') # time at next scr refresh
vjezba_1_2.setAutoDraw(True)
# *vjezba_1_text_2* updates
if vjezba_1_text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_1_text_2.frameNStart = frameN # exact frame index
vjezba_1_text_2.tStart = t # local t and not account for scr refresh
vjezba_1_text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_1_text_2, 'tStartRefresh') # time at next scr refresh
vjezba_1_text_2.setAutoDraw(True)
# *br_vjezbe_1_2* updates
if br_vjezbe_1_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_1_2.frameNStart = frameN # exact frame index
br_vjezbe_1_2.tStart = t # local t and not account for scr refresh
br_vjezbe_1_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_1_2, 'tStartRefresh') # time at next scr refresh
br_vjezbe_1_2.setAutoDraw(True)
# *br_vjezbe_1_text_2* updates
if br_vjezbe_1_text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_1_text_2.frameNStart = frameN # exact frame index
br_vjezbe_1_text_2.tStart = t # local t and not account for scr refresh
br_vjezbe_1_text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_1_text_2, 'tStartRefresh') # time at next scr refresh
br_vjezbe_1_text_2.setAutoDraw(True)
# *key_resp_8* updates
waitOnFlip = False
if key_resp_8.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_8.frameNStart = frameN # exact frame index
key_resp_8.tStart = t # local t and not account for scr refresh
key_resp_8.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_8, 'tStartRefresh') # time at next scr refresh
key_resp_8.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_8.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_8.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_8.status == STARTED and not waitOnFlip:
theseKeys = key_resp_8.getKeys(keyList=['space', 'backspace', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_8.keys.append(theseKeys.name) # storing all keys
key_resp_8.rt.append(theseKeys.rt)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezba_1_sigurnostComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba_1_sigurnost"-------
for thisComponent in vjezba_1_sigurnostComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if key_resp_8.keys in ['', [], None]: # No response was made
key_resp_8.keys = None
trials_3.addData('key_resp_8.keys',key_resp_8.keys)
if key_resp_8.keys != None: # we had a response
trials_3.addData('key_resp_8.rt', key_resp_8.rt)
# the Routine "vjezba_1_sigurnost" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'trials_3'
# ------Prepare to start Routine "kraj_vjezbe_1"-------
# update component parameters for each repeat
Kraj_vjezbe_1.keys = []
Kraj_vjezbe_1.rt = []
# keep track of which components have finished
kraj_vjezbe_1Components = [gotova_vjezba_1, priprema_za_z1, nastavi_10, Kraj_vjezbe_1]
for thisComponent in kraj_vjezbe_1Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
kraj_vjezbe_1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "kraj_vjezbe_1"-------
while continueRoutine:
# get current time
t = kraj_vjezbe_1Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=kraj_vjezbe_1Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *gotova_vjezba_1* updates
if gotova_vjezba_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
gotova_vjezba_1.frameNStart = frameN # exact frame index
gotova_vjezba_1.tStart = t # local t and not account for scr refresh
gotova_vjezba_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(gotova_vjezba_1, 'tStartRefresh') # time at next scr refresh
gotova_vjezba_1.setAutoDraw(True)
# *priprema_za_z1* updates
if priprema_za_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
priprema_za_z1.frameNStart = frameN # exact frame index
priprema_za_z1.tStart = t # local t and not account for scr refresh
priprema_za_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(priprema_za_z1, 'tStartRefresh') # time at next scr refresh
priprema_za_z1.setAutoDraw(True)
# *nastavi_10* updates
if nastavi_10.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_10.frameNStart = frameN # exact frame index
nastavi_10.tStart = t # local t and not account for scr refresh
nastavi_10.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_10, 'tStartRefresh') # time at next scr refresh
nastavi_10.setAutoDraw(True)
# *Kraj_vjezbe_1* updates
waitOnFlip = False
if Kraj_vjezbe_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Kraj_vjezbe_1.frameNStart = frameN # exact frame index
Kraj_vjezbe_1.tStart = t # local t and not account for scr refresh
Kraj_vjezbe_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Kraj_vjezbe_1, 'tStartRefresh') # time at next scr refresh
Kraj_vjezbe_1.status = STARTED
# keyboard checking is just starting
win.callOnFlip(Kraj_vjezbe_1.clearEvents, eventType='keyboard') # clear events on next screen flip
if Kraj_vjezbe_1.status == STARTED and not waitOnFlip:
theseKeys = Kraj_vjezbe_1.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in kraj_vjezbe_1Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "kraj_vjezbe_1"-------
for thisComponent in kraj_vjezbe_1Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "kraj_vjezbe_1" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials_4 = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('podrazaji\\eksperimentalni_podrazaji_z1.xlsx'),
seed=None, name='trials_4')
thisExp.addLoop(trials_4) # add the loop to the experiment
thisTrial_4 = trials_4.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_4.rgb)
if thisTrial_4 != None:
for paramName in thisTrial_4:
exec('{} = thisTrial_4[paramName]'.format(paramName))
for thisTrial_4 in trials_4:
currentLoop = trials_4
# abbreviate parameter names if possible (e.g. rgb = thisTrial_4.rgb)
if thisTrial_4 != None:
for paramName in thisTrial_4:
exec('{} = thisTrial_4[paramName]'.format(paramName))
# ------Prepare to start Routine "zadatak_1_pamcenje"-------
# update component parameters for each repeat
zadana_slika_z1= re.sub("[^0-9]", "", zadatak_z1)
ovaj_broj_z1 = str(trials_4.thisN + 1)
ukupan_broj_z1 = str(trials_4.nTotal)
ostatak_z1 = ovaj_broj_z1 + " / " + ukupan_broj_z1
uputa_z1.setText('Zapamtite veličinu prikazanog kruga')
podrazaj_z1.setImage(zadatak_z1)
br_zadatka_1_tekst.setText(ostatak_z1
)
pamcenje_slike_z1.keys = []
pamcenje_slike_z1.rt = []
# keep track of which components have finished
zadatak_1_pamcenjeComponents = [uputa_z1, podrazaj_z1, nastavi_11, zadatak_1, zadatak_1_text, br_zadatka_1, br_zadatka_1_tekst, pamcenje_slike_z1]
for thisComponent in zadatak_1_pamcenjeComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
zadatak_1_pamcenjeClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "zadatak_1_pamcenje"-------
while continueRoutine:
# get current time
t = zadatak_1_pamcenjeClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=zadatak_1_pamcenjeClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *uputa_z1* updates
if uputa_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
uputa_z1.frameNStart = frameN # exact frame index
uputa_z1.tStart = t # local t and not account for scr refresh
uputa_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(uputa_z1, 'tStartRefresh') # time at next scr refresh
uputa_z1.setAutoDraw(True)
# *podrazaj_z1* updates
if podrazaj_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
podrazaj_z1.frameNStart = frameN # exact frame index
podrazaj_z1.tStart = t # local t and not account for scr refresh
podrazaj_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(podrazaj_z1, 'tStartRefresh') # time at next scr refresh
podrazaj_z1.setAutoDraw(True)
# *nastavi_11* updates
if nastavi_11.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_11.frameNStart = frameN # exact frame index
nastavi_11.tStart = t # local t and not account for scr refresh
nastavi_11.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_11, 'tStartRefresh') # time at next scr refresh
nastavi_11.setAutoDraw(True)
# *zadatak_1* updates
if zadatak_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_1.frameNStart = frameN # exact frame index
zadatak_1.tStart = t # local t and not account for scr refresh
zadatak_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_1, 'tStartRefresh') # time at next scr refresh
zadatak_1.setAutoDraw(True)
# *zadatak_1_text* updates
if zadatak_1_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_1_text.frameNStart = frameN # exact frame index
zadatak_1_text.tStart = t # local t and not account for scr refresh
zadatak_1_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_1_text, 'tStartRefresh') # time at next scr refresh
zadatak_1_text.setAutoDraw(True)
# *br_zadatka_1* updates
if br_zadatka_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_1.frameNStart = frameN # exact frame index
br_zadatka_1.tStart = t # local t and not account for scr refresh
br_zadatka_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_1, 'tStartRefresh') # time at next scr refresh
br_zadatka_1.setAutoDraw(True)
# *br_zadatka_1_tekst* updates
if br_zadatka_1_tekst.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_1_tekst.frameNStart = frameN # exact frame index
br_zadatka_1_tekst.tStart = t # local t and not account for scr refresh
br_zadatka_1_tekst.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_1_tekst, 'tStartRefresh') # time at next scr refresh
br_zadatka_1_tekst.setAutoDraw(True)
# *pamcenje_slike_z1* updates
waitOnFlip = False
if pamcenje_slike_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
pamcenje_slike_z1.frameNStart = frameN # exact frame index
pamcenje_slike_z1.tStart = t # local t and not account for scr refresh
pamcenje_slike_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(pamcenje_slike_z1, 'tStartRefresh') # time at next scr refresh
pamcenje_slike_z1.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(pamcenje_slike_z1.clock.reset) # t=0 on next screen flip
win.callOnFlip(pamcenje_slike_z1.clearEvents, eventType='keyboard') # clear events on next screen flip
if pamcenje_slike_z1.status == STARTED and not waitOnFlip:
theseKeys = pamcenje_slike_z1.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
pamcenje_slike_z1.keys = theseKeys.name # just the last key pressed
pamcenje_slike_z1.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in zadatak_1_pamcenjeComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "zadatak_1_pamcenje"-------
for thisComponent in zadatak_1_pamcenjeComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
#save numeric version e.g. 15 = size 1 and orientation 5
trials_4.addData('zadana_slika_z1_PNG', zadatak_z1)
#save numeric version e.g. 15 = size 1 and orientation 5
trials_4.addData('zadana_slika_z1', zadana_slika_z1)
# check responses
if pamcenje_slike_z1.keys in ['', [], None]: # No response was made
pamcenje_slike_z1.keys = None
trials_4.addData('pamcenje_slike_z1.keys',pamcenje_slike_z1.keys)
if pamcenje_slike_z1.keys != None: # we had a response
trials_4.addData('pamcenje_slike_z1.rt', pamcenje_slike_z1.rt)
# the Routine "zadatak_1_pamcenje" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "mpi_sum"-------
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
mpi_sumComponents = [sum]
for thisComponent in mpi_sumComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
mpi_sumClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "mpi_sum"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = mpi_sumClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=mpi_sumClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *sum* updates
if sum.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sum.frameNStart = frameN # exact frame index
sum.tStart = t # local t and not account for scr refresh
sum.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sum, 'tStartRefresh') # time at next scr refresh
sum.setAutoDraw(True)
if sum.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > sum.tStartRefresh + 1.0-frameTolerance:
# keep track of stop time/frame for later
sum.tStop = t # not accounting for scr refresh
sum.frameNStop = frameN # exact frame index
win.timeOnFlip(sum, 'tStopRefresh') # time at next scr refresh
sum.setAutoDraw(False)
if sum.status == STARTED:
if sum._needBuild:
sum.buildNoise()
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in mpi_sumComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "mpi_sum"-------
for thisComponent in mpi_sumComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# ------Prepare to start Routine "zadatak_1_odgovor"-------
# update component parameters for each repeat
raspon_z1 = range(1, 210)
imgList_z01 = list(raspon_z1)
imgList_z1 = str(imgList_z01)
imgChoice_z1 = ""
#generate a random number between 1 and 5 for the starting image to be presented as
imgStart_z1 = randint(1, 2)
uputa_z1_1.setText('Podesite veličinu ovog kruga da odgovara veličini prethodnog kruga\n')
br_zadatka_1_text.setText(ostatak_z1
)
izbor_slike_z1.keys = []
izbor_slike_z1.rt = []
# keep track of which components have finished
zadatak_1_odgovorComponents = [uputa_z1_1, odgovor_z1, nastavi_12, zadatak_1_1, zadatak_1_text_1, br_zadatka_1_1, br_zadatka_1_text, str_gore_z1, gore_z1, str_dolje_z1, dolje_z1, izbor_slike_z1]
for thisComponent in zadatak_1_odgovorComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
zadatak_1_odgovorClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "zadatak_1_odgovor"-------
while continueRoutine:
# get current time
t = zadatak_1_odgovorClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=zadatak_1_odgovorClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
import re
raspon_z1 = range(1, 210)
imgList_z01 = list(raspon_z1)
imgList_z1 = str(imgList_z01)
imgChoice_z10 = str(imgStart_z1)
if imgChoice_z10 in imgList_z1:
imgChoice_z1 = "krugovi/"+imgChoice_z10 +".png"
odabrana_slika_z1= re.sub("[^0-9]", "", imgChoice_z1)
#decrease size with left button
if event.getKeys(['down']):
if imgStart_z1>1:
imgStart_z1=imgStart_z1-1
else:
imgStart_z1=1
#increase size with right button
if event.getKeys(['up']):
if imgStart_z1<210:
imgStart_z1=imgStart_z1+1
else:
imgStart_z1=210
# *uputa_z1_1* updates
if uputa_z1_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
uputa_z1_1.frameNStart = frameN # exact frame index
uputa_z1_1.tStart = t # local t and not account for scr refresh
uputa_z1_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(uputa_z1_1, 'tStartRefresh') # time at next scr refresh
uputa_z1_1.setAutoDraw(True)
# *odgovor_z1* updates
if odgovor_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
odgovor_z1.frameNStart = frameN # exact frame index
odgovor_z1.tStart = t # local t and not account for scr refresh
odgovor_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(odgovor_z1, 'tStartRefresh') # time at next scr refresh
odgovor_z1.setAutoDraw(True)
if odgovor_z1.status == STARTED: # only update if drawing
odgovor_z1.setImage(imgChoice_z1, log=False)
# *nastavi_12* updates
if nastavi_12.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_12.frameNStart = frameN # exact frame index
nastavi_12.tStart = t # local t and not account for scr refresh
nastavi_12.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_12, 'tStartRefresh') # time at next scr refresh
nastavi_12.setAutoDraw(True)
# *zadatak_1_1* updates
if zadatak_1_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_1_1.frameNStart = frameN # exact frame index
zadatak_1_1.tStart = t # local t and not account for scr refresh
zadatak_1_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_1_1, 'tStartRefresh') # time at next scr refresh
zadatak_1_1.setAutoDraw(True)
# *zadatak_1_text_1* updates
if zadatak_1_text_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_1_text_1.frameNStart = frameN # exact frame index
zadatak_1_text_1.tStart = t # local t and not account for scr refresh
zadatak_1_text_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_1_text_1, 'tStartRefresh') # time at next scr refresh
zadatak_1_text_1.setAutoDraw(True)
# *br_zadatka_1_1* updates
if br_zadatka_1_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_1_1.frameNStart = frameN # exact frame index
br_zadatka_1_1.tStart = t # local t and not account for scr refresh
br_zadatka_1_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_1_1, 'tStartRefresh') # time at next scr refresh
br_zadatka_1_1.setAutoDraw(True)
# *br_zadatka_1_text* updates
if br_zadatka_1_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_1_text.frameNStart = frameN # exact frame index
br_zadatka_1_text.tStart = t # local t and not account for scr refresh
br_zadatka_1_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_1_text, 'tStartRefresh') # time at next scr refresh
br_zadatka_1_text.setAutoDraw(True)
# *str_gore_z1* updates
if str_gore_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
str_gore_z1.frameNStart = frameN # exact frame index
str_gore_z1.tStart = t # local t and not account for scr refresh
str_gore_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(str_gore_z1, 'tStartRefresh') # time at next scr refresh
str_gore_z1.setAutoDraw(True)
# *gore_z1* updates
if gore_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
gore_z1.frameNStart = frameN # exact frame index
gore_z1.tStart = t # local t and not account for scr refresh
gore_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(gore_z1, 'tStartRefresh') # time at next scr refresh
gore_z1.setAutoDraw(True)
# *str_dolje_z1* updates
if str_dolje_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
str_dolje_z1.frameNStart = frameN # exact frame index
str_dolje_z1.tStart = t # local t and not account for scr refresh
str_dolje_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(str_dolje_z1, 'tStartRefresh') # time at next scr refresh
str_dolje_z1.setAutoDraw(True)
# *dolje_z1* updates
if dolje_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
dolje_z1.frameNStart = frameN # exact frame index
dolje_z1.tStart = t # local t and not account for scr refresh
dolje_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(dolje_z1, 'tStartRefresh') # time at next scr refresh
dolje_z1.setAutoDraw(True)
# *izbor_slike_z1* updates
waitOnFlip = False
if izbor_slike_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
izbor_slike_z1.frameNStart = frameN # exact frame index
izbor_slike_z1.tStart = t # local t and not account for scr refresh
izbor_slike_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(izbor_slike_z1, 'tStartRefresh') # time at next scr refresh
izbor_slike_z1.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(izbor_slike_z1.clock.reset) # t=0 on next screen flip
win.callOnFlip(izbor_slike_z1.clearEvents, eventType='keyboard') # clear events on next screen flip
if izbor_slike_z1.status == STARTED and not waitOnFlip:
theseKeys = izbor_slike_z1.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
izbor_slike_z1.keys = theseKeys.name # just the last key pressed
izbor_slike_z1.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in zadatak_1_odgovorComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "zadatak_1_odgovor"-------
for thisComponent in zadatak_1_odgovorComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
#save data
#comment the code below if you do not want the data to be stored, or uncomment each line
#saves .png file name of image choice e.g. stims/1_5.png
trials_4.addData('imgChoice_z1', imgChoice_z1)
#save numeric version e.g. 15 = size 1 and orientation 5
trials_4.addData('odabrana_slika_z1', odabrana_slika_z1)
# check responses
if izbor_slike_z1.keys in ['', [], None]: # No response was made
izbor_slike_z1.keys = None
trials_4.addData('izbor_slike_z1.keys',izbor_slike_z1.keys)
if izbor_slike_z1.keys != None: # we had a response
trials_4.addData('izbor_slike_z1.rt', izbor_slike_z1.rt)
# the Routine "zadatak_1_odgovor" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "zadatak_1_sigurnost"-------
# update component parameters for each repeat
screen_text_z1 = ""
br_zadatka_1_3.setText(ostatak_z1
)
key_resp_9.keys = []
key_resp_9.rt = []
# keep track of which components have finished
zadatak_1_sigurnostComponents = [stupanj_sigurnosti_z1, sigurnost_primjer_z1, sigurnost_odgovor_z1, nastavi_13, zadatak_1_2, zadatak_1_text_2, br_zadatka_1_2, br_zadatka_1_3, key_resp_9]
for thisComponent in zadatak_1_sigurnostComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
zadatak_1_sigurnostClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "zadatak_1_sigurnost"-------
while continueRoutine:
# get current time
t = zadatak_1_sigurnostClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=zadatak_1_sigurnostClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
if("backspace" in key_resp_9.keys):
key_resp_9.keys.remove ("backspace")
if(len(key_resp_9.keys) > 0):
key_resp_9.keys.pop()
elif("space" in key_resp_9.keys):
key_resp_9.keys.remove("space")
if(len(key_resp_9.keys) >= 1):
screen_text_z1 = "".join(key_resp_9.keys)
thisExp.addData("stupnjevi_sigurnosti_z1", screen_text_z1)
continueRoutine = False
screen_text_z1 = "".join(key_resp_9.keys) + "%"
# *stupanj_sigurnosti_z1* updates
if stupanj_sigurnosti_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
stupanj_sigurnosti_z1.frameNStart = frameN # exact frame index
stupanj_sigurnosti_z1.tStart = t # local t and not account for scr refresh
stupanj_sigurnosti_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(stupanj_sigurnosti_z1, 'tStartRefresh') # time at next scr refresh
stupanj_sigurnosti_z1.setAutoDraw(True)
# *sigurnost_primjer_z1* updates
if sigurnost_primjer_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_primjer_z1.frameNStart = frameN # exact frame index
sigurnost_primjer_z1.tStart = t # local t and not account for scr refresh
sigurnost_primjer_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_primjer_z1, 'tStartRefresh') # time at next scr refresh
sigurnost_primjer_z1.setAutoDraw(True)
# *sigurnost_odgovor_z1* updates
if sigurnost_odgovor_z1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_odgovor_z1.frameNStart = frameN # exact frame index
sigurnost_odgovor_z1.tStart = t # local t and not account for scr refresh
sigurnost_odgovor_z1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_odgovor_z1, 'tStartRefresh') # time at next scr refresh
sigurnost_odgovor_z1.setAutoDraw(True)
if sigurnost_odgovor_z1.status == STARTED: # only update if drawing
sigurnost_odgovor_z1.setText(screen_text_z1, log=False)
# *nastavi_13* updates
if nastavi_13.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_13.frameNStart = frameN # exact frame index
nastavi_13.tStart = t # local t and not account for scr refresh
nastavi_13.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_13, 'tStartRefresh') # time at next scr refresh
nastavi_13.setAutoDraw(True)
# *zadatak_1_2* updates
if zadatak_1_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_1_2.frameNStart = frameN # exact frame index
zadatak_1_2.tStart = t # local t and not account for scr refresh
zadatak_1_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_1_2, 'tStartRefresh') # time at next scr refresh
zadatak_1_2.setAutoDraw(True)
# *zadatak_1_text_2* updates
if zadatak_1_text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_1_text_2.frameNStart = frameN # exact frame index
zadatak_1_text_2.tStart = t # local t and not account for scr refresh
zadatak_1_text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_1_text_2, 'tStartRefresh') # time at next scr refresh
zadatak_1_text_2.setAutoDraw(True)
# *br_zadatka_1_2* updates
if br_zadatka_1_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_1_2.frameNStart = frameN # exact frame index
br_zadatka_1_2.tStart = t # local t and not account for scr refresh
br_zadatka_1_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_1_2, 'tStartRefresh') # time at next scr refresh
br_zadatka_1_2.setAutoDraw(True)
# *br_zadatka_1_3* updates
if br_zadatka_1_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_1_3.frameNStart = frameN # exact frame index
br_zadatka_1_3.tStart = t # local t and not account for scr refresh
br_zadatka_1_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_1_3, 'tStartRefresh') # time at next scr refresh
br_zadatka_1_3.setAutoDraw(True)
# *key_resp_9* updates
waitOnFlip = False
if key_resp_9.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_9.frameNStart = frameN # exact frame index
key_resp_9.tStart = t # local t and not account for scr refresh
key_resp_9.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_9, 'tStartRefresh') # time at next scr refresh
key_resp_9.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_9.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_9.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_9.status == STARTED and not waitOnFlip:
theseKeys = key_resp_9.getKeys(keyList=['space', 'backspace', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_9.keys.append(theseKeys.name) # storing all keys
key_resp_9.rt.append(theseKeys.rt)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in zadatak_1_sigurnostComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "zadatak_1_sigurnost"-------
for thisComponent in zadatak_1_sigurnostComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if key_resp_9.keys in ['', [], None]: # No response was made
key_resp_9.keys = None
trials_4.addData('key_resp_9.keys',key_resp_9.keys)
if key_resp_9.keys != None: # we had a response
trials_4.addData('key_resp_9.rt', key_resp_9.rt)
# the Routine "zadatak_1_sigurnost" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'trials_4'
# ------Prepare to start Routine "kraj_zadatka_1"-------
# update component parameters for each repeat
Kraj_zadatka_1.keys = []
Kraj_zadatka_1.rt = []
# keep track of which components have finished
kraj_zadatka_1Components = [gotov_zadatak_1, priprema_za_z2, nastavi_13_1, Kraj_zadatka_1]
for thisComponent in kraj_zadatka_1Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
kraj_zadatka_1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "kraj_zadatka_1"-------
while continueRoutine:
# get current time
t = kraj_zadatka_1Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=kraj_zadatka_1Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *gotov_zadatak_1* updates
if gotov_zadatak_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
gotov_zadatak_1.frameNStart = frameN # exact frame index
gotov_zadatak_1.tStart = t # local t and not account for scr refresh
gotov_zadatak_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(gotov_zadatak_1, 'tStartRefresh') # time at next scr refresh
gotov_zadatak_1.setAutoDraw(True)
# *priprema_za_z2* updates
if priprema_za_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
priprema_za_z2.frameNStart = frameN # exact frame index
priprema_za_z2.tStart = t # local t and not account for scr refresh
priprema_za_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(priprema_za_z2, 'tStartRefresh') # time at next scr refresh
priprema_za_z2.setAutoDraw(True)
# *nastavi_13_1* updates
if nastavi_13_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_13_1.frameNStart = frameN # exact frame index
nastavi_13_1.tStart = t # local t and not account for scr refresh
nastavi_13_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_13_1, 'tStartRefresh') # time at next scr refresh
nastavi_13_1.setAutoDraw(True)
# *Kraj_zadatka_1* updates
waitOnFlip = False
if Kraj_zadatka_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Kraj_zadatka_1.frameNStart = frameN # exact frame index
Kraj_zadatka_1.tStart = t # local t and not account for scr refresh
Kraj_zadatka_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Kraj_zadatka_1, 'tStartRefresh') # time at next scr refresh
Kraj_zadatka_1.status = STARTED
# keyboard checking is just starting
if Kraj_zadatka_1.status == STARTED and not waitOnFlip:
theseKeys = Kraj_zadatka_1.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in kraj_zadatka_1Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "kraj_zadatka_1"-------
for thisComponent in kraj_zadatka_1Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "kraj_zadatka_1" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "uputa_zadatak_2"-------
# update component parameters for each repeat
Pocetak_vjezbe_2.keys = []
Pocetak_vjezbe_2.rt = []
# keep track of which components have finished
uputa_zadatak_2Components = [naslov_uputa_z2, generalna_uputa_z2, nastavi_14, zadatak_2, zadatak_2_text, Pocetak_vjezbe_2]
for thisComponent in uputa_zadatak_2Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
uputa_zadatak_2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "uputa_zadatak_2"-------
while continueRoutine:
# get current time
t = uputa_zadatak_2Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=uputa_zadatak_2Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *naslov_uputa_z2* updates
if naslov_uputa_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
naslov_uputa_z2.frameNStart = frameN # exact frame index
naslov_uputa_z2.tStart = t # local t and not account for scr refresh
naslov_uputa_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(naslov_uputa_z2, 'tStartRefresh') # time at next scr refresh
naslov_uputa_z2.setAutoDraw(True)
# *generalna_uputa_z2* updates
if generalna_uputa_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
generalna_uputa_z2.frameNStart = frameN # exact frame index
generalna_uputa_z2.tStart = t # local t and not account for scr refresh
generalna_uputa_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(generalna_uputa_z2, 'tStartRefresh') # time at next scr refresh
generalna_uputa_z2.setAutoDraw(True)
# *nastavi_14* updates
if nastavi_14.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_14.frameNStart = frameN # exact frame index
nastavi_14.tStart = t # local t and not account for scr refresh
nastavi_14.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_14, 'tStartRefresh') # time at next scr refresh
nastavi_14.setAutoDraw(True)
# *zadatak_2* updates
if zadatak_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_2.frameNStart = frameN # exact frame index
zadatak_2.tStart = t # local t and not account for scr refresh
zadatak_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_2, 'tStartRefresh') # time at next scr refresh
zadatak_2.setAutoDraw(True)
# *zadatak_2_text* updates
if zadatak_2_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_2_text.frameNStart = frameN # exact frame index
zadatak_2_text.tStart = t # local t and not account for scr refresh
zadatak_2_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_2_text, 'tStartRefresh') # time at next scr refresh
zadatak_2_text.setAutoDraw(True)
# *Pocetak_vjezbe_2* updates
waitOnFlip = False
if Pocetak_vjezbe_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Pocetak_vjezbe_2.frameNStart = frameN # exact frame index
Pocetak_vjezbe_2.tStart = t # local t and not account for scr refresh
Pocetak_vjezbe_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Pocetak_vjezbe_2, 'tStartRefresh') # time at next scr refresh
Pocetak_vjezbe_2.status = STARTED
# keyboard checking is just starting
win.callOnFlip(Pocetak_vjezbe_2.clearEvents, eventType='keyboard') # clear events on next screen flip
if Pocetak_vjezbe_2.status == STARTED and not waitOnFlip:
theseKeys = Pocetak_vjezbe_2.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in uputa_zadatak_2Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "uputa_zadatak_2"-------
for thisComponent in uputa_zadatak_2Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "uputa_zadatak_2" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "vjezba"-------
# update component parameters for each repeat
pocetak_vjezbe.keys = []
pocetak_vjezbe.rt = []
# keep track of which components have finished
vjezbaComponents = [vjezba_0, zadaci_za_vjezbu, nastavi_vjezba, pocetak_vjezbe]
for thisComponent in vjezbaComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezbaClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba"-------
while continueRoutine:
# get current time
t = vjezbaClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezbaClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *vjezba_0* updates
if vjezba_0.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_0.frameNStart = frameN # exact frame index
vjezba_0.tStart = t # local t and not account for scr refresh
vjezba_0.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_0, 'tStartRefresh') # time at next scr refresh
vjezba_0.setAutoDraw(True)
# *zadaci_za_vjezbu* updates
if zadaci_za_vjezbu.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadaci_za_vjezbu.frameNStart = frameN # exact frame index
zadaci_za_vjezbu.tStart = t # local t and not account for scr refresh
zadaci_za_vjezbu.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadaci_za_vjezbu, 'tStartRefresh') # time at next scr refresh
zadaci_za_vjezbu.setAutoDraw(True)
# *nastavi_vjezba* updates
if nastavi_vjezba.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_vjezba.frameNStart = frameN # exact frame index
nastavi_vjezba.tStart = t # local t and not account for scr refresh
nastavi_vjezba.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_vjezba, 'tStartRefresh') # time at next scr refresh
nastavi_vjezba.setAutoDraw(True)
# *pocetak_vjezbe* updates
waitOnFlip = False
if pocetak_vjezbe.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
pocetak_vjezbe.frameNStart = frameN # exact frame index
pocetak_vjezbe.tStart = t # local t and not account for scr refresh
pocetak_vjezbe.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(pocetak_vjezbe, 'tStartRefresh') # time at next scr refresh
pocetak_vjezbe.status = STARTED
# keyboard checking is just starting
win.callOnFlip(pocetak_vjezbe.clearEvents, eventType='keyboard') # clear events on next screen flip
if pocetak_vjezbe.status == STARTED and not waitOnFlip:
theseKeys = pocetak_vjezbe.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezbaComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba"-------
for thisComponent in vjezbaComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "vjezba" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials_5 = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('podrazaji\\eksperimentalni_podrazaji_v2.xlsx'),
seed=None, name='trials_5')
thisExp.addLoop(trials_5) # add the loop to the experiment
thisTrial_5 = trials_5.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_5.rgb)
if thisTrial_5 != None:
for paramName in thisTrial_5:
exec('{} = thisTrial_5[paramName]'.format(paramName))
for thisTrial_5 in trials_5:
currentLoop = trials_5
# abbreviate parameter names if possible (e.g. rgb = thisTrial_5.rgb)
if thisTrial_5 != None:
for paramName in thisTrial_5:
exec('{} = thisTrial_5[paramName]'.format(paramName))
# ------Prepare to start Routine "vjezba_2_odgovor"-------
# update component parameters for each repeat
ovaj_broj_v2 = str(trials_5.thisN + 1)
ukupan_broj_v2 = str(trials_5.nTotal)
ostatak_v2 = ovaj_broj_v2 + " / " + ukupan_broj_v2
raspon_v2 = range(1, 600)
imgList_v02 = list(raspon_v2)
imgList_v2 = str(imgList_v02)
imgChoice_v2 = ""
#generate a random number between 1 and 5 for the starting image to be presented as
imgStart_v2 = randint(278, 279)
uputa_v2_1.setText('Podesite veličinu pravokutnika da unutar njega stane zadani broj krugova')
br_broj_objekata_v2.setText(br_objekata_v2)
br_vjezbe_2_text_1.setText(ostatak_v2
)
izbor_slike_v2.keys = []
izbor_slike_v2.rt = []
# keep track of which components have finished
vjezba_2_odgovorComponents = [uputa_v2_1, broj_objekata_v1, br_broj_objekata_v2, ciljni_objekt_v2, ciljni_objekt_slika_v2, odgovor_v2, nastavi_15, vjezba_2_1, vjezba_2_text_1, br_vjezbe_2_1, br_vjezbe_2_text_1, str_lijevo_v2, lijevo_v2, str_desno_v2, desno_v2, izbor_slike_v2]
for thisComponent in vjezba_2_odgovorComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezba_2_odgovorClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba_2_odgovor"-------
while continueRoutine:
# get current time
t = vjezba_2_odgovorClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezba_2_odgovorClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
import re
raspon_v2 = range(1, 600)
imgList_v02 = list(raspon_v2)
imgList_v2 = str(imgList_v02)
imgChoice_v20 = str(imgStart_v2)
if imgChoice_v20 in imgList_v2:
imgChoice_v2 = "pravokutnici/"+imgChoice_v20 +".png"
odabrana_slika_v2= re.sub("[^0-9]", "", imgChoice_v2)
#decrease size with left button
if event.getKeys(['left']):
if imgStart_v2>1:
imgStart_v2=imgStart_v2-1
else:
imgStart_V2=1
#increase size with right button
if event.getKeys(['right']):
if imgStart_v2<600:
imgStart_v2=imgStart_v2+1
else:
imgStart_v2=600
# *uputa_v2_1* updates
if uputa_v2_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
uputa_v2_1.frameNStart = frameN # exact frame index
uputa_v2_1.tStart = t # local t and not account for scr refresh
uputa_v2_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(uputa_v2_1, 'tStartRefresh') # time at next scr refresh
uputa_v2_1.setAutoDraw(True)
# *broj_objekata_v1* updates
if broj_objekata_v1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
broj_objekata_v1.frameNStart = frameN # exact frame index
broj_objekata_v1.tStart = t # local t and not account for scr refresh
broj_objekata_v1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(broj_objekata_v1, 'tStartRefresh') # time at next scr refresh
broj_objekata_v1.setAutoDraw(True)
# *br_broj_objekata_v2* updates
if br_broj_objekata_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_broj_objekata_v2.frameNStart = frameN # exact frame index
br_broj_objekata_v2.tStart = t # local t and not account for scr refresh
br_broj_objekata_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_broj_objekata_v2, 'tStartRefresh') # time at next scr refresh
br_broj_objekata_v2.setAutoDraw(True)
# *ciljni_objekt_v2* updates
if ciljni_objekt_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
ciljni_objekt_v2.frameNStart = frameN # exact frame index
ciljni_objekt_v2.tStart = t # local t and not account for scr refresh
ciljni_objekt_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(ciljni_objekt_v2, 'tStartRefresh') # time at next scr refresh
ciljni_objekt_v2.setAutoDraw(True)
# *ciljni_objekt_slika_v2* updates
if ciljni_objekt_slika_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
ciljni_objekt_slika_v2.frameNStart = frameN # exact frame index
ciljni_objekt_slika_v2.tStart = t # local t and not account for scr refresh
ciljni_objekt_slika_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(ciljni_objekt_slika_v2, 'tStartRefresh') # time at next scr refresh
ciljni_objekt_slika_v2.setAutoDraw(True)
# *odgovor_v2* updates
if odgovor_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
odgovor_v2.frameNStart = frameN # exact frame index
odgovor_v2.tStart = t # local t and not account for scr refresh
odgovor_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(odgovor_v2, 'tStartRefresh') # time at next scr refresh
odgovor_v2.setAutoDraw(True)
if odgovor_v2.status == STARTED: # only update if drawing
odgovor_v2.setImage(imgChoice_v2, log=False)
# *nastavi_15* updates
if nastavi_15.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_15.frameNStart = frameN # exact frame index
nastavi_15.tStart = t # local t and not account for scr refresh
nastavi_15.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_15, 'tStartRefresh') # time at next scr refresh
nastavi_15.setAutoDraw(True)
# *vjezba_2_1* updates
if vjezba_2_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_2_1.frameNStart = frameN # exact frame index
vjezba_2_1.tStart = t # local t and not account for scr refresh
vjezba_2_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_2_1, 'tStartRefresh') # time at next scr refresh
vjezba_2_1.setAutoDraw(True)
# *vjezba_2_text_1* updates
if vjezba_2_text_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_2_text_1.frameNStart = frameN # exact frame index
vjezba_2_text_1.tStart = t # local t and not account for scr refresh
vjezba_2_text_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_2_text_1, 'tStartRefresh') # time at next scr refresh
vjezba_2_text_1.setAutoDraw(True)
# *br_vjezbe_2_1* updates
if br_vjezbe_2_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_2_1.frameNStart = frameN # exact frame index
br_vjezbe_2_1.tStart = t # local t and not account for scr refresh
br_vjezbe_2_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_2_1, 'tStartRefresh') # time at next scr refresh
br_vjezbe_2_1.setAutoDraw(True)
# *br_vjezbe_2_text_1* updates
if br_vjezbe_2_text_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_2_text_1.frameNStart = frameN # exact frame index
br_vjezbe_2_text_1.tStart = t # local t and not account for scr refresh
br_vjezbe_2_text_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_2_text_1, 'tStartRefresh') # time at next scr refresh
br_vjezbe_2_text_1.setAutoDraw(True)
# *str_lijevo_v2* updates
if str_lijevo_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
str_lijevo_v2.frameNStart = frameN # exact frame index
str_lijevo_v2.tStart = t # local t and not account for scr refresh
str_lijevo_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(str_lijevo_v2, 'tStartRefresh') # time at next scr refresh
str_lijevo_v2.setAutoDraw(True)
# *lijevo_v2* updates
if lijevo_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
lijevo_v2.frameNStart = frameN # exact frame index
lijevo_v2.tStart = t # local t and not account for scr refresh
lijevo_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(lijevo_v2, 'tStartRefresh') # time at next scr refresh
lijevo_v2.setAutoDraw(True)
# *str_desno_v2* updates
if str_desno_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
str_desno_v2.frameNStart = frameN # exact frame index
str_desno_v2.tStart = t # local t and not account for scr refresh
str_desno_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(str_desno_v2, 'tStartRefresh') # time at next scr refresh
str_desno_v2.setAutoDraw(True)
# *desno_v2* updates
if desno_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
desno_v2.frameNStart = frameN # exact frame index
desno_v2.tStart = t # local t and not account for scr refresh
desno_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(desno_v2, 'tStartRefresh') # time at next scr refresh
desno_v2.setAutoDraw(True)
# *izbor_slike_v2* updates
waitOnFlip = False
if izbor_slike_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
izbor_slike_v2.frameNStart = frameN # exact frame index
izbor_slike_v2.tStart = t # local t and not account for scr refresh
izbor_slike_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(izbor_slike_v2, 'tStartRefresh') # time at next scr refresh
izbor_slike_v2.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(izbor_slike_v2.clock.reset) # t=0 on next screen flip
win.callOnFlip(izbor_slike_v2.clearEvents, eventType='keyboard') # clear events on next screen flip
if izbor_slike_v2.status == STARTED and not waitOnFlip:
theseKeys = izbor_slike_v2.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
izbor_slike_v2.keys = theseKeys.name # just the last key pressed
izbor_slike_v2.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezba_2_odgovorComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba_2_odgovor"-------
for thisComponent in vjezba_2_odgovorComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials_5.addData('broj_objekata_v2', br_objekata_v2)
trials_5.addData('tocan_odgovor_v2', tocan_odgovor_v2)
#save data
#comment the code below if you do not want the data to be stored, or uncomment each line
#saves .png file name of image choice e.g. stims/1_5.png
trials_5.addData('imgChoice_v2', imgChoice_v2)
#save numeric version e.g. 15 = size 1 and orientation 5
trials_5.addData('odabrana_slika_v2', odabrana_slika_v2)
# check responses
if izbor_slike_v2.keys in ['', [], None]: # No response was made
izbor_slike_v2.keys = None
trials_5.addData('izbor_slike_v2.keys',izbor_slike_v2.keys)
if izbor_slike_v2.keys != None: # we had a response
trials_5.addData('izbor_slike_v2.rt', izbor_slike_v2.rt)
# the Routine "vjezba_2_odgovor" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "vjezba_2_sigurnost"-------
# update component parameters for each repeat
screen_text_v2 = ""
br_vjezbe_2_text_2.setText(ostatak_v2
)
key_resp_11.keys = []
key_resp_11.rt = []
# keep track of which components have finished
vjezba_2_sigurnostComponents = [stupanj_sigurnosti_v2, sigurnost_primjer_v2, sigurnost_odgovor_v2, nastavi_16, vjezba_2_2, vjezba_2_text_2, br_vjezbe_2_2, br_vjezbe_2_text_2, key_resp_11]
for thisComponent in vjezba_2_sigurnostComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezba_2_sigurnostClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba_2_sigurnost"-------
while continueRoutine:
# get current time
t = vjezba_2_sigurnostClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezba_2_sigurnostClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
if("backspace" in key_resp_11.keys):
key_resp_11.keys.remove ("backspace")
if(len(key_resp_11.keys) > 0):
key_resp_11.keys.pop()
elif("space" in key_resp_11.keys):
key_resp_11.keys.remove("space")
if(len(key_resp_11.keys) >= 1):
screen_text_v2 = "".join(key_resp_11.keys)
thisExp.addData("stupnjevi_sigurnosti_v2", screen_text_v2)
continueRoutine = False
screen_text_v2 = "".join(key_resp_11.keys) + "%"
# *stupanj_sigurnosti_v2* updates
if stupanj_sigurnosti_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
stupanj_sigurnosti_v2.frameNStart = frameN # exact frame index
stupanj_sigurnosti_v2.tStart = t # local t and not account for scr refresh
stupanj_sigurnosti_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(stupanj_sigurnosti_v2, 'tStartRefresh') # time at next scr refresh
stupanj_sigurnosti_v2.setAutoDraw(True)
# *sigurnost_primjer_v2* updates
if sigurnost_primjer_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_primjer_v2.frameNStart = frameN # exact frame index
sigurnost_primjer_v2.tStart = t # local t and not account for scr refresh
sigurnost_primjer_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_primjer_v2, 'tStartRefresh') # time at next scr refresh
sigurnost_primjer_v2.setAutoDraw(True)
# *sigurnost_odgovor_v2* updates
if sigurnost_odgovor_v2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_odgovor_v2.frameNStart = frameN # exact frame index
sigurnost_odgovor_v2.tStart = t # local t and not account for scr refresh
sigurnost_odgovor_v2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_odgovor_v2, 'tStartRefresh') # time at next scr refresh
sigurnost_odgovor_v2.setAutoDraw(True)
if sigurnost_odgovor_v2.status == STARTED: # only update if drawing
sigurnost_odgovor_v2.setText(screen_text_v2, log=False)
# *nastavi_16* updates
if nastavi_16.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_16.frameNStart = frameN # exact frame index
nastavi_16.tStart = t # local t and not account for scr refresh
nastavi_16.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_16, 'tStartRefresh') # time at next scr refresh
nastavi_16.setAutoDraw(True)
# *vjezba_2_2* updates
if vjezba_2_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_2_2.frameNStart = frameN # exact frame index
vjezba_2_2.tStart = t # local t and not account for scr refresh
vjezba_2_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_2_2, 'tStartRefresh') # time at next scr refresh
vjezba_2_2.setAutoDraw(True)
# *vjezba_2_text_2* updates
if vjezba_2_text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_2_text_2.frameNStart = frameN # exact frame index
vjezba_2_text_2.tStart = t # local t and not account for scr refresh
vjezba_2_text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_2_text_2, 'tStartRefresh') # time at next scr refresh
vjezba_2_text_2.setAutoDraw(True)
# *br_vjezbe_2_2* updates
if br_vjezbe_2_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_2_2.frameNStart = frameN # exact frame index
br_vjezbe_2_2.tStart = t # local t and not account for scr refresh
br_vjezbe_2_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_2_2, 'tStartRefresh') # time at next scr refresh
br_vjezbe_2_2.setAutoDraw(True)
# *br_vjezbe_2_text_2* updates
if br_vjezbe_2_text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_2_text_2.frameNStart = frameN # exact frame index
br_vjezbe_2_text_2.tStart = t # local t and not account for scr refresh
br_vjezbe_2_text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_2_text_2, 'tStartRefresh') # time at next scr refresh
br_vjezbe_2_text_2.setAutoDraw(True)
# *key_resp_11* updates
waitOnFlip = False
if key_resp_11.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_11.frameNStart = frameN # exact frame index
key_resp_11.tStart = t # local t and not account for scr refresh
key_resp_11.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_11, 'tStartRefresh') # time at next scr refresh
key_resp_11.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_11.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_11.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_11.status == STARTED and not waitOnFlip:
theseKeys = key_resp_11.getKeys(keyList=['space', 'backspace', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_11.keys.append(theseKeys.name) # storing all keys
key_resp_11.rt.append(theseKeys.rt)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezba_2_sigurnostComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba_2_sigurnost"-------
for thisComponent in vjezba_2_sigurnostComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if key_resp_11.keys in ['', [], None]: # No response was made
key_resp_11.keys = None
trials_5.addData('key_resp_11.keys',key_resp_11.keys)
if key_resp_11.keys != None: # we had a response
trials_5.addData('key_resp_11.rt', key_resp_11.rt)
# the Routine "vjezba_2_sigurnost" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'trials_5'
# ------Prepare to start Routine "kraj_vjezbe_2"-------
# update component parameters for each repeat
Kraj_vjezbe_2.keys = []
Kraj_vjezbe_2.rt = []
# keep track of which components have finished
kraj_vjezbe_2Components = [gotova_vjezba_2, priprema_za_z2_1, nastavi_17, Kraj_vjezbe_2]
for thisComponent in kraj_vjezbe_2Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
kraj_vjezbe_2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "kraj_vjezbe_2"-------
while continueRoutine:
# get current time
t = kraj_vjezbe_2Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=kraj_vjezbe_2Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *gotova_vjezba_2* updates
if gotova_vjezba_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
gotova_vjezba_2.frameNStart = frameN # exact frame index
gotova_vjezba_2.tStart = t # local t and not account for scr refresh
gotova_vjezba_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(gotova_vjezba_2, 'tStartRefresh') # time at next scr refresh
gotova_vjezba_2.setAutoDraw(True)
# *priprema_za_z2_1* updates
if priprema_za_z2_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
priprema_za_z2_1.frameNStart = frameN # exact frame index
priprema_za_z2_1.tStart = t # local t and not account for scr refresh
priprema_za_z2_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(priprema_za_z2_1, 'tStartRefresh') # time at next scr refresh
priprema_za_z2_1.setAutoDraw(True)
# *nastavi_17* updates
if nastavi_17.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_17.frameNStart = frameN # exact frame index
nastavi_17.tStart = t # local t and not account for scr refresh
nastavi_17.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_17, 'tStartRefresh') # time at next scr refresh
nastavi_17.setAutoDraw(True)
# *Kraj_vjezbe_2* updates
waitOnFlip = False
if Kraj_vjezbe_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Kraj_vjezbe_2.frameNStart = frameN # exact frame index
Kraj_vjezbe_2.tStart = t # local t and not account for scr refresh
Kraj_vjezbe_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Kraj_vjezbe_2, 'tStartRefresh') # time at next scr refresh
Kraj_vjezbe_2.status = STARTED
# keyboard checking is just starting
win.callOnFlip(Kraj_vjezbe_2.clearEvents, eventType='keyboard') # clear events on next screen flip
if Kraj_vjezbe_2.status == STARTED and not waitOnFlip:
theseKeys = Kraj_vjezbe_2.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in kraj_vjezbe_2Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "kraj_vjezbe_2"-------
for thisComponent in kraj_vjezbe_2Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "kraj_vjezbe_2" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials_6 = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('podrazaji\\eksperimentalni_podrazaji_z2.xlsx'),
seed=None, name='trials_6')
thisExp.addLoop(trials_6) # add the loop to the experiment
thisTrial_6 = trials_6.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_6.rgb)
if thisTrial_6 != None:
for paramName in thisTrial_6:
exec('{} = thisTrial_6[paramName]'.format(paramName))
for thisTrial_6 in trials_6:
currentLoop = trials_6
# abbreviate parameter names if possible (e.g. rgb = thisTrial_6.rgb)
if thisTrial_6 != None:
for paramName in thisTrial_6:
exec('{} = thisTrial_6[paramName]'.format(paramName))
# ------Prepare to start Routine "zadatak_2_odgovor"-------
# update component parameters for each repeat
ovaj_broj_z2 = str(trials_6.thisN + 1)
ukupan_broj_z2 = str(trials_6.nTotal)
ostatak_z2 = ovaj_broj_z2 + " / " + ukupan_broj_z2
raspon_z2 = range(1, 600)
imgList_z02 = list(raspon_z2)
imgList_z2 = str(imgList_z02)
imgChoice_z2 = ""
#generate a random number between 1 and 5 for the starting image to be presented as
imgStart_z2 = randint(278, 279)
uputa_z2_1.setText('Podesite veličinu pravokutnika da unutar njega stane zadani broj krugova')
br_broj_objekata_z2.setText(br_objekata_z2)
br_zadatka_2_text.setText(ostatak_z2
)
izbor_slike_z2.keys = []
izbor_slike_z2.rt = []
# keep track of which components have finished
zadatak_2_odgovorComponents = [uputa_z2_1, broj_objekata_z2, br_broj_objekata_z2, ciljni_objekt_z2, ciljni_objekt_slika_z2, odgovor_z2, nastavi_18, zadatak_2_1, zadatak_2_text_1, br_zadatka_2_1, br_zadatka_2_text, str_lijevo_z2, lijevo_z2, str_desno_z2, desno_z2, izbor_slike_z2]
for thisComponent in zadatak_2_odgovorComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
zadatak_2_odgovorClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "zadatak_2_odgovor"-------
while continueRoutine:
# get current time
t = zadatak_2_odgovorClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=zadatak_2_odgovorClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
import re
raspon_z2 = range(1, 600)
imgList_z02 = list(raspon_z2)
imgList_z2 = str(imgList_z02)
imgChoice_z20 = str(imgStart_z2)
if imgChoice_z20 in imgList_z2:
imgChoice_z2 = "pravokutnici/"+imgChoice_z20 +".png"
odabrana_slika_z2= re.sub("[^0-9]", "", imgChoice_z2)
#decrease size with left button
if event.getKeys(['left']):
if imgStart_z2>1:
imgStart_z2=imgStart_z2-1
else:
imgStart_z2=1
#increase size with right button
if event.getKeys(['right']):
if imgStart_z2<600:
imgStart_z2=imgStart_z2+1
else:
imgStart_z2=600
# *uputa_z2_1* updates
if uputa_z2_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
uputa_z2_1.frameNStart = frameN # exact frame index
uputa_z2_1.tStart = t # local t and not account for scr refresh
uputa_z2_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(uputa_z2_1, 'tStartRefresh') # time at next scr refresh
uputa_z2_1.setAutoDraw(True)
# *broj_objekata_z2* updates
if broj_objekata_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
broj_objekata_z2.frameNStart = frameN # exact frame index
broj_objekata_z2.tStart = t # local t and not account for scr refresh
broj_objekata_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(broj_objekata_z2, 'tStartRefresh') # time at next scr refresh
broj_objekata_z2.setAutoDraw(True)
# *br_broj_objekata_z2* updates
if br_broj_objekata_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_broj_objekata_z2.frameNStart = frameN # exact frame index
br_broj_objekata_z2.tStart = t # local t and not account for scr refresh
br_broj_objekata_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_broj_objekata_z2, 'tStartRefresh') # time at next scr refresh
br_broj_objekata_z2.setAutoDraw(True)
# *ciljni_objekt_z2* updates
if ciljni_objekt_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
ciljni_objekt_z2.frameNStart = frameN # exact frame index
ciljni_objekt_z2.tStart = t # local t and not account for scr refresh
ciljni_objekt_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(ciljni_objekt_z2, 'tStartRefresh') # time at next scr refresh
ciljni_objekt_z2.setAutoDraw(True)
# *ciljni_objekt_slika_z2* updates
if ciljni_objekt_slika_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
ciljni_objekt_slika_z2.frameNStart = frameN # exact frame index
ciljni_objekt_slika_z2.tStart = t # local t and not account for scr refresh
ciljni_objekt_slika_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(ciljni_objekt_slika_z2, 'tStartRefresh') # time at next scr refresh
ciljni_objekt_slika_z2.setAutoDraw(True)
# *odgovor_z2* updates
if odgovor_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
odgovor_z2.frameNStart = frameN # exact frame index
odgovor_z2.tStart = t # local t and not account for scr refresh
odgovor_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(odgovor_z2, 'tStartRefresh') # time at next scr refresh
odgovor_z2.setAutoDraw(True)
if odgovor_z2.status == STARTED: # only update if drawing
odgovor_z2.setImage(imgChoice_z2, log=False)
# *nastavi_18* updates
if nastavi_18.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_18.frameNStart = frameN # exact frame index
nastavi_18.tStart = t # local t and not account for scr refresh
nastavi_18.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_18, 'tStartRefresh') # time at next scr refresh
nastavi_18.setAutoDraw(True)
# *zadatak_2_1* updates
if zadatak_2_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_2_1.frameNStart = frameN # exact frame index
zadatak_2_1.tStart = t # local t and not account for scr refresh
zadatak_2_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_2_1, 'tStartRefresh') # time at next scr refresh
zadatak_2_1.setAutoDraw(True)
# *zadatak_2_text_1* updates
if zadatak_2_text_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_2_text_1.frameNStart = frameN # exact frame index
zadatak_2_text_1.tStart = t # local t and not account for scr refresh
zadatak_2_text_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_2_text_1, 'tStartRefresh') # time at next scr refresh
zadatak_2_text_1.setAutoDraw(True)
# *br_zadatka_2_1* updates
if br_zadatka_2_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_2_1.frameNStart = frameN # exact frame index
br_zadatka_2_1.tStart = t # local t and not account for scr refresh
br_zadatka_2_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_2_1, 'tStartRefresh') # time at next scr refresh
br_zadatka_2_1.setAutoDraw(True)
# *br_zadatka_2_text* updates
if br_zadatka_2_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_2_text.frameNStart = frameN # exact frame index
br_zadatka_2_text.tStart = t # local t and not account for scr refresh
br_zadatka_2_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_2_text, 'tStartRefresh') # time at next scr refresh
br_zadatka_2_text.setAutoDraw(True)
# *str_lijevo_z2* updates
if str_lijevo_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
str_lijevo_z2.frameNStart = frameN # exact frame index
str_lijevo_z2.tStart = t # local t and not account for scr refresh
str_lijevo_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(str_lijevo_z2, 'tStartRefresh') # time at next scr refresh
str_lijevo_z2.setAutoDraw(True)
# *lijevo_z2* updates
if lijevo_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
lijevo_z2.frameNStart = frameN # exact frame index
lijevo_z2.tStart = t # local t and not account for scr refresh
lijevo_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(lijevo_z2, 'tStartRefresh') # time at next scr refresh
lijevo_z2.setAutoDraw(True)
# *str_desno_z2* updates
if str_desno_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
str_desno_z2.frameNStart = frameN # exact frame index
str_desno_z2.tStart = t # local t and not account for scr refresh
str_desno_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(str_desno_z2, 'tStartRefresh') # time at next scr refresh
str_desno_z2.setAutoDraw(True)
# *desno_z2* updates
if desno_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
desno_z2.frameNStart = frameN # exact frame index
desno_z2.tStart = t # local t and not account for scr refresh
desno_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(desno_z2, 'tStartRefresh') # time at next scr refresh
desno_z2.setAutoDraw(True)
# *izbor_slike_z2* updates
waitOnFlip = False
if izbor_slike_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
izbor_slike_z2.frameNStart = frameN # exact frame index
izbor_slike_z2.tStart = t # local t and not account for scr refresh
izbor_slike_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(izbor_slike_z2, 'tStartRefresh') # time at next scr refresh
izbor_slike_z2.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(izbor_slike_z2.clock.reset) # t=0 on next screen flip
win.callOnFlip(izbor_slike_z2.clearEvents, eventType='keyboard') # clear events on next screen flip
if izbor_slike_z2.status == STARTED and not waitOnFlip:
theseKeys = izbor_slike_z2.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
izbor_slike_z2.keys = theseKeys.name # just the last key pressed
izbor_slike_z2.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in zadatak_2_odgovorComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "zadatak_2_odgovor"-------
for thisComponent in zadatak_2_odgovorComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials_6.addData('broj_objekata_z2', br_objekata_z2)
trials_6.addData('tocan_odgovor_z2', tocan_odgovor_z2)
#save data
#comment the code below if you do not want the data to be stored, or uncomment each line
#saves .png file name of image choice e.g. stims/1_5.png
trials_6.addData('imgChoice_z2', imgChoice_z2)
#save numeric version e.g. 15 = size 1 and orientation 5
trials_6.addData('odabrana_slika_z2', odabrana_slika_z2)
# check responses
if izbor_slike_z2.keys in ['', [], None]: # No response was made
izbor_slike_z2.keys = None
trials_6.addData('izbor_slike_z2.keys',izbor_slike_z2.keys)
if izbor_slike_z2.keys != None: # we had a response
trials_6.addData('izbor_slike_z2.rt', izbor_slike_z2.rt)
# the Routine "zadatak_2_odgovor" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "zadatak_2_sigurnost"-------
# update component parameters for each repeat
screen_text_z2 = ""
br_zadatka_2_3.setText(ostatak_z2
)
key_resp_12.keys = []
key_resp_12.rt = []
# keep track of which components have finished
zadatak_2_sigurnostComponents = [stupanj_sigurnosti_z2, sigurnost_primjer_z2, sigurnost_odgovor_z2, nastavi_19, zadatak_2_2, zadatak_2_text_2, br_zadatka_2_2, br_zadatka_2_3, key_resp_12]
for thisComponent in zadatak_2_sigurnostComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
zadatak_2_sigurnostClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "zadatak_2_sigurnost"-------
while continueRoutine:
# get current time
t = zadatak_2_sigurnostClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=zadatak_2_sigurnostClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
if("backspace" in key_resp_12.keys):
key_resp_12.keys.remove ("backspace")
if(len(key_resp_12.keys) > 0):
key_resp_12.keys.pop()
elif("space" in key_resp_12.keys):
key_resp_12.keys.remove("space")
if(len(key_resp_12.keys) >= 1):
screen_text_z2 = "".join(key_resp_12.keys)
thisExp.addData("stupnjevi_sigurnosti_z2", screen_text_z2)
continueRoutine = False
screen_text_z2 = "".join(key_resp_12.keys) + "%"
# *stupanj_sigurnosti_z2* updates
if stupanj_sigurnosti_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
stupanj_sigurnosti_z2.frameNStart = frameN # exact frame index
stupanj_sigurnosti_z2.tStart = t # local t and not account for scr refresh
stupanj_sigurnosti_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(stupanj_sigurnosti_z2, 'tStartRefresh') # time at next scr refresh
stupanj_sigurnosti_z2.setAutoDraw(True)
# *sigurnost_primjer_z2* updates
if sigurnost_primjer_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_primjer_z2.frameNStart = frameN # exact frame index
sigurnost_primjer_z2.tStart = t # local t and not account for scr refresh
sigurnost_primjer_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_primjer_z2, 'tStartRefresh') # time at next scr refresh
sigurnost_primjer_z2.setAutoDraw(True)
# *sigurnost_odgovor_z2* updates
if sigurnost_odgovor_z2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_odgovor_z2.frameNStart = frameN # exact frame index
sigurnost_odgovor_z2.tStart = t # local t and not account for scr refresh
sigurnost_odgovor_z2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_odgovor_z2, 'tStartRefresh') # time at next scr refresh
sigurnost_odgovor_z2.setAutoDraw(True)
if sigurnost_odgovor_z2.status == STARTED: # only update if drawing
sigurnost_odgovor_z2.setText(screen_text_z2, log=False)
# *nastavi_19* updates
if nastavi_19.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_19.frameNStart = frameN # exact frame index
nastavi_19.tStart = t # local t and not account for scr refresh
nastavi_19.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_19, 'tStartRefresh') # time at next scr refresh
nastavi_19.setAutoDraw(True)
# *zadatak_2_2* updates
if zadatak_2_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_2_2.frameNStart = frameN # exact frame index
zadatak_2_2.tStart = t # local t and not account for scr refresh
zadatak_2_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_2_2, 'tStartRefresh') # time at next scr refresh
zadatak_2_2.setAutoDraw(True)
# *zadatak_2_text_2* updates
if zadatak_2_text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_2_text_2.frameNStart = frameN # exact frame index
zadatak_2_text_2.tStart = t # local t and not account for scr refresh
zadatak_2_text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_2_text_2, 'tStartRefresh') # time at next scr refresh
zadatak_2_text_2.setAutoDraw(True)
# *br_zadatka_2_2* updates
if br_zadatka_2_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_2_2.frameNStart = frameN # exact frame index
br_zadatka_2_2.tStart = t # local t and not account for scr refresh
br_zadatka_2_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_2_2, 'tStartRefresh') # time at next scr refresh
br_zadatka_2_2.setAutoDraw(True)
# *br_zadatka_2_3* updates
if br_zadatka_2_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_2_3.frameNStart = frameN # exact frame index
br_zadatka_2_3.tStart = t # local t and not account for scr refresh
br_zadatka_2_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_2_3, 'tStartRefresh') # time at next scr refresh
br_zadatka_2_3.setAutoDraw(True)
# *key_resp_12* updates
waitOnFlip = False
if key_resp_12.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_12.frameNStart = frameN # exact frame index
key_resp_12.tStart = t # local t and not account for scr refresh
key_resp_12.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_12, 'tStartRefresh') # time at next scr refresh
key_resp_12.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_12.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_12.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_12.status == STARTED and not waitOnFlip:
theseKeys = key_resp_12.getKeys(keyList=['space', 'backspace', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_12.keys.append(theseKeys.name) # storing all keys
key_resp_12.rt.append(theseKeys.rt)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in zadatak_2_sigurnostComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "zadatak_2_sigurnost"-------
for thisComponent in zadatak_2_sigurnostComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if key_resp_12.keys in ['', [], None]: # No response was made
key_resp_12.keys = None
trials_6.addData('key_resp_12.keys',key_resp_12.keys)
if key_resp_12.keys != None: # we had a response
trials_6.addData('key_resp_12.rt', key_resp_12.rt)
# the Routine "zadatak_2_sigurnost" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'trials_6'
# ------Prepare to start Routine "kraj_zadatka_2"-------
# update component parameters for each repeat
Kraj_zadatka_2.keys = []
Kraj_zadatka_2.rt = []
# keep track of which components have finished
kraj_zadatka_2Components = [gotov_zadatak_2, priprema_za_z3, nastavi_19_1, Kraj_zadatka_2]
for thisComponent in kraj_zadatka_2Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
kraj_zadatka_2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "kraj_zadatka_2"-------
while continueRoutine:
# get current time
t = kraj_zadatka_2Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=kraj_zadatka_2Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *gotov_zadatak_2* updates
if gotov_zadatak_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
gotov_zadatak_2.frameNStart = frameN # exact frame index
gotov_zadatak_2.tStart = t # local t and not account for scr refresh
gotov_zadatak_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(gotov_zadatak_2, 'tStartRefresh') # time at next scr refresh
gotov_zadatak_2.setAutoDraw(True)
# *priprema_za_z3* updates
if priprema_za_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
priprema_za_z3.frameNStart = frameN # exact frame index
priprema_za_z3.tStart = t # local t and not account for scr refresh
priprema_za_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(priprema_za_z3, 'tStartRefresh') # time at next scr refresh
priprema_za_z3.setAutoDraw(True)
# *nastavi_19_1* updates
if nastavi_19_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_19_1.frameNStart = frameN # exact frame index
nastavi_19_1.tStart = t # local t and not account for scr refresh
nastavi_19_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_19_1, 'tStartRefresh') # time at next scr refresh
nastavi_19_1.setAutoDraw(True)
# *Kraj_zadatka_2* updates
waitOnFlip = False
if Kraj_zadatka_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Kraj_zadatka_2.frameNStart = frameN # exact frame index
Kraj_zadatka_2.tStart = t # local t and not account for scr refresh
Kraj_zadatka_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Kraj_zadatka_2, 'tStartRefresh') # time at next scr refresh
Kraj_zadatka_2.status = STARTED
# keyboard checking is just starting
win.callOnFlip(Kraj_zadatka_2.clearEvents, eventType='keyboard') # clear events on next screen flip
if Kraj_zadatka_2.status == STARTED and not waitOnFlip:
theseKeys = Kraj_zadatka_2.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in kraj_zadatka_2Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "kraj_zadatka_2"-------
for thisComponent in kraj_zadatka_2Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "kraj_zadatka_2" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "uputa_zadatak_3"-------
# update component parameters for each repeat
Pocetak_vjezbe_3.keys = []
Pocetak_vjezbe_3.rt = []
# keep track of which components have finished
uputa_zadatak_3Components = [naslov_uputa_z3, generalna_uputa_z3, nastavi_20, zadatak_3, zadatak_3_text, Pocetak_vjezbe_3]
for thisComponent in uputa_zadatak_3Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
uputa_zadatak_3Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "uputa_zadatak_3"-------
while continueRoutine:
# get current time
t = uputa_zadatak_3Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=uputa_zadatak_3Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *naslov_uputa_z3* updates
if naslov_uputa_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
naslov_uputa_z3.frameNStart = frameN # exact frame index
naslov_uputa_z3.tStart = t # local t and not account for scr refresh
naslov_uputa_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(naslov_uputa_z3, 'tStartRefresh') # time at next scr refresh
naslov_uputa_z3.setAutoDraw(True)
# *generalna_uputa_z3* updates
if generalna_uputa_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
generalna_uputa_z3.frameNStart = frameN # exact frame index
generalna_uputa_z3.tStart = t # local t and not account for scr refresh
generalna_uputa_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(generalna_uputa_z3, 'tStartRefresh') # time at next scr refresh
generalna_uputa_z3.setAutoDraw(True)
# *nastavi_20* updates
if nastavi_20.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_20.frameNStart = frameN # exact frame index
nastavi_20.tStart = t # local t and not account for scr refresh
nastavi_20.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_20, 'tStartRefresh') # time at next scr refresh
nastavi_20.setAutoDraw(True)
# *zadatak_3* updates
if zadatak_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_3.frameNStart = frameN # exact frame index
zadatak_3.tStart = t # local t and not account for scr refresh
zadatak_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_3, 'tStartRefresh') # time at next scr refresh
zadatak_3.setAutoDraw(True)
# *zadatak_3_text* updates
if zadatak_3_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_3_text.frameNStart = frameN # exact frame index
zadatak_3_text.tStart = t # local t and not account for scr refresh
zadatak_3_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_3_text, 'tStartRefresh') # time at next scr refresh
zadatak_3_text.setAutoDraw(True)
# *Pocetak_vjezbe_3* updates
waitOnFlip = False
if Pocetak_vjezbe_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Pocetak_vjezbe_3.frameNStart = frameN # exact frame index
Pocetak_vjezbe_3.tStart = t # local t and not account for scr refresh
Pocetak_vjezbe_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Pocetak_vjezbe_3, 'tStartRefresh') # time at next scr refresh
Pocetak_vjezbe_3.status = STARTED
# keyboard checking is just starting
win.callOnFlip(Pocetak_vjezbe_3.clearEvents, eventType='keyboard') # clear events on next screen flip
if Pocetak_vjezbe_3.status == STARTED and not waitOnFlip:
theseKeys = Pocetak_vjezbe_3.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in uputa_zadatak_3Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "uputa_zadatak_3"-------
for thisComponent in uputa_zadatak_3Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "uputa_zadatak_3" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "vjezba"-------
# update component parameters for each repeat
pocetak_vjezbe.keys = []
pocetak_vjezbe.rt = []
# keep track of which components have finished
vjezbaComponents = [vjezba_0, zadaci_za_vjezbu, nastavi_vjezba, pocetak_vjezbe]
for thisComponent in vjezbaComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezbaClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba"-------
while continueRoutine:
# get current time
t = vjezbaClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezbaClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *vjezba_0* updates
if vjezba_0.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_0.frameNStart = frameN # exact frame index
vjezba_0.tStart = t # local t and not account for scr refresh
vjezba_0.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_0, 'tStartRefresh') # time at next scr refresh
vjezba_0.setAutoDraw(True)
# *zadaci_za_vjezbu* updates
if zadaci_za_vjezbu.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadaci_za_vjezbu.frameNStart = frameN # exact frame index
zadaci_za_vjezbu.tStart = t # local t and not account for scr refresh
zadaci_za_vjezbu.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadaci_za_vjezbu, 'tStartRefresh') # time at next scr refresh
zadaci_za_vjezbu.setAutoDraw(True)
# *nastavi_vjezba* updates
if nastavi_vjezba.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_vjezba.frameNStart = frameN # exact frame index
nastavi_vjezba.tStart = t # local t and not account for scr refresh
nastavi_vjezba.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_vjezba, 'tStartRefresh') # time at next scr refresh
nastavi_vjezba.setAutoDraw(True)
# *pocetak_vjezbe* updates
waitOnFlip = False
if pocetak_vjezbe.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
pocetak_vjezbe.frameNStart = frameN # exact frame index
pocetak_vjezbe.tStart = t # local t and not account for scr refresh
pocetak_vjezbe.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(pocetak_vjezbe, 'tStartRefresh') # time at next scr refresh
pocetak_vjezbe.status = STARTED
# keyboard checking is just starting
win.callOnFlip(pocetak_vjezbe.clearEvents, eventType='keyboard') # clear events on next screen flip
if pocetak_vjezbe.status == STARTED and not waitOnFlip:
theseKeys = pocetak_vjezbe.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezbaComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba"-------
for thisComponent in vjezbaComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "vjezba" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials_7 = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('podrazaji\\eksperimentalni_podrazaji_v3.xlsx'),
seed=None, name='trials_7')
thisExp.addLoop(trials_7) # add the loop to the experiment
thisTrial_7 = trials_7.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_7.rgb)
if thisTrial_7 != None:
for paramName in thisTrial_7:
exec('{} = thisTrial_7[paramName]'.format(paramName))
for thisTrial_7 in trials_7:
currentLoop = trials_7
# abbreviate parameter names if possible (e.g. rgb = thisTrial_7.rgb)
if thisTrial_7 != None:
for paramName in thisTrial_7:
exec('{} = thisTrial_7[paramName]'.format(paramName))
# ------Prepare to start Routine "vjezba_3_odgovor"-------
# update component parameters for each repeat
import re
zadani_pravokutnik_v3= re.sub("[^0-9]", "", pravokutnik_v3)
ovaj_broj_v3 = str(trials_7.thisN + 1)
ukupan_broj_v3 = str(trials_7.nTotal)
ostatak_v3 = ovaj_broj_v3 + " / " + ukupan_broj_v3
screen_text_v3 = ""
odgovor_v3.setImage(pravokutnik_v3)
br_vjezbe_3_text_1.setText(ostatak_v3
)
izbor_broja_v3.keys = []
izbor_broja_v3.rt = []
RT_izbor_broja_v3.keys = []
RT_izbor_broja_v3.rt = []
# keep track of which components have finished
vjezba_3_odgovorComponents = [uputa_v3_1, primjer_v3_1, ciljni_objekt_v3, ciljni_objekt_slika_v3, odgovor_v3, vas_odgovor_v3_1, br_vas_odgovor_v3, nastavi_21, vjezba_3_1, vjezba_3_text_1, br_vjezbe_3_1, br_vjezbe_3_text_1, izbor_broja_v3, RT_izbor_broja_v3]
for thisComponent in vjezba_3_odgovorComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezba_3_odgovorClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba_3_odgovor"-------
while continueRoutine:
# get current time
t = vjezba_3_odgovorClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezba_3_odgovorClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
trials_7.addData('zadani_pravokutnik_v3_PNG', pravokutnik_v3)
trials_7.addData('zadani_pravokutnik_v3', zadani_pravokutnik_v3)
trials_7.addData('tocan_odgovor_v3', tocan_odgovor_v3)
if("backspace" in izbor_broja_v3.keys):
izbor_broja_v3.keys.remove ("backspace")
if(len(izbor_broja_v3.keys) > 0):
izbor_broja_v3.keys.pop()
elif("space" in izbor_broja_v3.keys):
izbor_broja_v3.keys.remove("space")
if(len(izbor_broja_v3.keys) >= 1):
screen_text_v3 = "".join(izbor_broja_v3.keys)
trials_7.addData("broj_krugova_odgovor_v3", screen_text_v3)
continueRoutine = False
screen_text_v3 = "".join(izbor_broja_v3.keys)
# *uputa_v3_1* updates
if uputa_v3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
uputa_v3_1.frameNStart = frameN # exact frame index
uputa_v3_1.tStart = t # local t and not account for scr refresh
uputa_v3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(uputa_v3_1, 'tStartRefresh') # time at next scr refresh
uputa_v3_1.setAutoDraw(True)
# *primjer_v3_1* updates
if primjer_v3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
primjer_v3_1.frameNStart = frameN # exact frame index
primjer_v3_1.tStart = t # local t and not account for scr refresh
primjer_v3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(primjer_v3_1, 'tStartRefresh') # time at next scr refresh
primjer_v3_1.setAutoDraw(True)
# *ciljni_objekt_v3* updates
if ciljni_objekt_v3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
ciljni_objekt_v3.frameNStart = frameN # exact frame index
ciljni_objekt_v3.tStart = t # local t and not account for scr refresh
ciljni_objekt_v3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(ciljni_objekt_v3, 'tStartRefresh') # time at next scr refresh
ciljni_objekt_v3.setAutoDraw(True)
# *ciljni_objekt_slika_v3* updates
if ciljni_objekt_slika_v3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
ciljni_objekt_slika_v3.frameNStart = frameN # exact frame index
ciljni_objekt_slika_v3.tStart = t # local t and not account for scr refresh
ciljni_objekt_slika_v3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(ciljni_objekt_slika_v3, 'tStartRefresh') # time at next scr refresh
ciljni_objekt_slika_v3.setAutoDraw(True)
# *odgovor_v3* updates
if odgovor_v3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
odgovor_v3.frameNStart = frameN # exact frame index
odgovor_v3.tStart = t # local t and not account for scr refresh
odgovor_v3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(odgovor_v3, 'tStartRefresh') # time at next scr refresh
odgovor_v3.setAutoDraw(True)
# *vas_odgovor_v3_1* updates
if vas_odgovor_v3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vas_odgovor_v3_1.frameNStart = frameN # exact frame index
vas_odgovor_v3_1.tStart = t # local t and not account for scr refresh
vas_odgovor_v3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vas_odgovor_v3_1, 'tStartRefresh') # time at next scr refresh
vas_odgovor_v3_1.setAutoDraw(True)
# *br_vas_odgovor_v3* updates
if br_vas_odgovor_v3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vas_odgovor_v3.frameNStart = frameN # exact frame index
br_vas_odgovor_v3.tStart = t # local t and not account for scr refresh
br_vas_odgovor_v3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vas_odgovor_v3, 'tStartRefresh') # time at next scr refresh
br_vas_odgovor_v3.setAutoDraw(True)
if br_vas_odgovor_v3.status == STARTED: # only update if drawing
br_vas_odgovor_v3.setText(screen_text_v3, log=False)
# *nastavi_21* updates
if nastavi_21.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_21.frameNStart = frameN # exact frame index
nastavi_21.tStart = t # local t and not account for scr refresh
nastavi_21.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_21, 'tStartRefresh') # time at next scr refresh
nastavi_21.setAutoDraw(True)
# *vjezba_3_1* updates
if vjezba_3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_3_1.frameNStart = frameN # exact frame index
vjezba_3_1.tStart = t # local t and not account for scr refresh
vjezba_3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_3_1, 'tStartRefresh') # time at next scr refresh
vjezba_3_1.setAutoDraw(True)
# *vjezba_3_text_1* updates
if vjezba_3_text_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_3_text_1.frameNStart = frameN # exact frame index
vjezba_3_text_1.tStart = t # local t and not account for scr refresh
vjezba_3_text_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_3_text_1, 'tStartRefresh') # time at next scr refresh
vjezba_3_text_1.setAutoDraw(True)
# *br_vjezbe_3_1* updates
if br_vjezbe_3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_3_1.frameNStart = frameN # exact frame index
br_vjezbe_3_1.tStart = t # local t and not account for scr refresh
br_vjezbe_3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_3_1, 'tStartRefresh') # time at next scr refresh
br_vjezbe_3_1.setAutoDraw(True)
# *br_vjezbe_3_text_1* updates
if br_vjezbe_3_text_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_3_text_1.frameNStart = frameN # exact frame index
br_vjezbe_3_text_1.tStart = t # local t and not account for scr refresh
br_vjezbe_3_text_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_3_text_1, 'tStartRefresh') # time at next scr refresh
br_vjezbe_3_text_1.setAutoDraw(True)
# *izbor_broja_v3* updates
waitOnFlip = False
if izbor_broja_v3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
izbor_broja_v3.frameNStart = frameN # exact frame index
izbor_broja_v3.tStart = t # local t and not account for scr refresh
izbor_broja_v3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(izbor_broja_v3, 'tStartRefresh') # time at next scr refresh
izbor_broja_v3.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(izbor_broja_v3.clock.reset) # t=0 on next screen flip
win.callOnFlip(izbor_broja_v3.clearEvents, eventType='keyboard') # clear events on next screen flip
if izbor_broja_v3.status == STARTED and not waitOnFlip:
theseKeys = izbor_broja_v3.getKeys(keyList=['backspace', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
izbor_broja_v3.keys.append(theseKeys.name) # storing all keys
izbor_broja_v3.rt.append(theseKeys.rt)
# *RT_izbor_broja_v3* updates
waitOnFlip = False
if RT_izbor_broja_v3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
RT_izbor_broja_v3.frameNStart = frameN # exact frame index
RT_izbor_broja_v3.tStart = t # local t and not account for scr refresh
RT_izbor_broja_v3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(RT_izbor_broja_v3, 'tStartRefresh') # time at next scr refresh
RT_izbor_broja_v3.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(RT_izbor_broja_v3.clock.reset) # t=0 on next screen flip
win.callOnFlip(RT_izbor_broja_v3.clearEvents, eventType='keyboard') # clear events on next screen flip
if RT_izbor_broja_v3.status == STARTED and not waitOnFlip:
theseKeys = RT_izbor_broja_v3.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
RT_izbor_broja_v3.keys = theseKeys.name # just the last key pressed
RT_izbor_broja_v3.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezba_3_odgovorComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba_3_odgovor"-------
for thisComponent in vjezba_3_odgovorComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials_7.addData("broj_krugova_odgovor_v3", screen_text_v3)
# check responses
if izbor_broja_v3.keys in ['', [], None]: # No response was made
izbor_broja_v3.keys = None
trials_7.addData('izbor_broja_v3.keys',izbor_broja_v3.keys)
if izbor_broja_v3.keys != None: # we had a response
trials_7.addData('izbor_broja_v3.rt', izbor_broja_v3.rt)
# check responses
if RT_izbor_broja_v3.keys in ['', [], None]: # No response was made
RT_izbor_broja_v3.keys = None
trials_7.addData('RT_izbor_broja_v3.keys',RT_izbor_broja_v3.keys)
if RT_izbor_broja_v3.keys != None: # we had a response
trials_7.addData('RT_izbor_broja_v3.rt', RT_izbor_broja_v3.rt)
# the Routine "vjezba_3_odgovor" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "vjezba_3_sigurnost"-------
# update component parameters for each repeat
screen_text_v3_1 = ""
br_vjezbe_3_text_2.setText(ostatak_v3
)
key_resp_13.keys = []
key_resp_13.rt = []
# keep track of which components have finished
vjezba_3_sigurnostComponents = [stupanj_sigurnosti_v3, sigurnost_primjer_v3, sigurnost_odgovor_v3, nastavi_22, vjezba_3_2, vjezba_3_text_2, br_vjezbe_3_2, br_vjezbe_3_text_2, key_resp_13]
for thisComponent in vjezba_3_sigurnostComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
vjezba_3_sigurnostClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "vjezba_3_sigurnost"-------
while continueRoutine:
# get current time
t = vjezba_3_sigurnostClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=vjezba_3_sigurnostClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
if("backspace" in key_resp_13.keys):
key_resp_13.keys.remove ("backspace")
if(len(key_resp_13.keys) > 0):
key_resp_13.keys.pop()
elif("space" in key_resp_13.keys):
key_resp_13.keys.remove("space")
if(len(key_resp_13.keys) >= 1):
screen_text_v3_1 = "".join(key_resp_13.keys)
thisExp.addData("stupnjevi_sigurnosti_v3", screen_text_v3_1)
continueRoutine = False
screen_text_v3_1 = "".join(key_resp_13.keys) + "%"
# *stupanj_sigurnosti_v3* updates
if stupanj_sigurnosti_v3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
stupanj_sigurnosti_v3.frameNStart = frameN # exact frame index
stupanj_sigurnosti_v3.tStart = t # local t and not account for scr refresh
stupanj_sigurnosti_v3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(stupanj_sigurnosti_v3, 'tStartRefresh') # time at next scr refresh
stupanj_sigurnosti_v3.setAutoDraw(True)
# *sigurnost_primjer_v3* updates
if sigurnost_primjer_v3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_primjer_v3.frameNStart = frameN # exact frame index
sigurnost_primjer_v3.tStart = t # local t and not account for scr refresh
sigurnost_primjer_v3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_primjer_v3, 'tStartRefresh') # time at next scr refresh
sigurnost_primjer_v3.setAutoDraw(True)
# *sigurnost_odgovor_v3* updates
if sigurnost_odgovor_v3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_odgovor_v3.frameNStart = frameN # exact frame index
sigurnost_odgovor_v3.tStart = t # local t and not account for scr refresh
sigurnost_odgovor_v3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_odgovor_v3, 'tStartRefresh') # time at next scr refresh
sigurnost_odgovor_v3.setAutoDraw(True)
if sigurnost_odgovor_v3.status == STARTED: # only update if drawing
sigurnost_odgovor_v3.setText(screen_text_v3_1, log=False)
# *nastavi_22* updates
if nastavi_22.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_22.frameNStart = frameN # exact frame index
nastavi_22.tStart = t # local t and not account for scr refresh
nastavi_22.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_22, 'tStartRefresh') # time at next scr refresh
nastavi_22.setAutoDraw(True)
# *vjezba_3_2* updates
if vjezba_3_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_3_2.frameNStart = frameN # exact frame index
vjezba_3_2.tStart = t # local t and not account for scr refresh
vjezba_3_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_3_2, 'tStartRefresh') # time at next scr refresh
vjezba_3_2.setAutoDraw(True)
# *vjezba_3_text_2* updates
if vjezba_3_text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vjezba_3_text_2.frameNStart = frameN # exact frame index
vjezba_3_text_2.tStart = t # local t and not account for scr refresh
vjezba_3_text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vjezba_3_text_2, 'tStartRefresh') # time at next scr refresh
vjezba_3_text_2.setAutoDraw(True)
# *br_vjezbe_3_2* updates
if br_vjezbe_3_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_3_2.frameNStart = frameN # exact frame index
br_vjezbe_3_2.tStart = t # local t and not account for scr refresh
br_vjezbe_3_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_3_2, 'tStartRefresh') # time at next scr refresh
br_vjezbe_3_2.setAutoDraw(True)
# *br_vjezbe_3_text_2* updates
if br_vjezbe_3_text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vjezbe_3_text_2.frameNStart = frameN # exact frame index
br_vjezbe_3_text_2.tStart = t # local t and not account for scr refresh
br_vjezbe_3_text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vjezbe_3_text_2, 'tStartRefresh') # time at next scr refresh
br_vjezbe_3_text_2.setAutoDraw(True)
# *key_resp_13* updates
waitOnFlip = False
if key_resp_13.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_13.frameNStart = frameN # exact frame index
key_resp_13.tStart = t # local t and not account for scr refresh
key_resp_13.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_13, 'tStartRefresh') # time at next scr refresh
key_resp_13.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_13.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_13.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_13.status == STARTED and not waitOnFlip:
theseKeys = key_resp_13.getKeys(keyList=['space', 'backspace', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_13.keys.append(theseKeys.name) # storing all keys
key_resp_13.rt.append(theseKeys.rt)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vjezba_3_sigurnostComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "vjezba_3_sigurnost"-------
for thisComponent in vjezba_3_sigurnostComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if key_resp_13.keys in ['', [], None]: # No response was made
key_resp_13.keys = None
trials_7.addData('key_resp_13.keys',key_resp_13.keys)
if key_resp_13.keys != None: # we had a response
trials_7.addData('key_resp_13.rt', key_resp_13.rt)
# the Routine "vjezba_3_sigurnost" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'trials_7'
# ------Prepare to start Routine "kraj_vjezbe_3"-------
# update component parameters for each repeat
Kraj_vjezbe_3.keys = []
Kraj_vjezbe_3.rt = []
# keep track of which components have finished
kraj_vjezbe_3Components = [gotova_vjezba_3, priprema_za_z3_1, nastavi_23, Kraj_vjezbe_3]
for thisComponent in kraj_vjezbe_3Components:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
kraj_vjezbe_3Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "kraj_vjezbe_3"-------
while continueRoutine:
# get current time
t = kraj_vjezbe_3Clock.getTime()
tThisFlip = win.getFutureFlipTime(clock=kraj_vjezbe_3Clock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *gotova_vjezba_3* updates
if gotova_vjezba_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
gotova_vjezba_3.frameNStart = frameN # exact frame index
gotova_vjezba_3.tStart = t # local t and not account for scr refresh
gotova_vjezba_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(gotova_vjezba_3, 'tStartRefresh') # time at next scr refresh
gotova_vjezba_3.setAutoDraw(True)
# *priprema_za_z3_1* updates
if priprema_za_z3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
priprema_za_z3_1.frameNStart = frameN # exact frame index
priprema_za_z3_1.tStart = t # local t and not account for scr refresh
priprema_za_z3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(priprema_za_z3_1, 'tStartRefresh') # time at next scr refresh
priprema_za_z3_1.setAutoDraw(True)
# *nastavi_23* updates
if nastavi_23.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_23.frameNStart = frameN # exact frame index
nastavi_23.tStart = t # local t and not account for scr refresh
nastavi_23.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_23, 'tStartRefresh') # time at next scr refresh
nastavi_23.setAutoDraw(True)
# *Kraj_vjezbe_3* updates
waitOnFlip = False
if Kraj_vjezbe_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Kraj_vjezbe_3.frameNStart = frameN # exact frame index
Kraj_vjezbe_3.tStart = t # local t and not account for scr refresh
Kraj_vjezbe_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Kraj_vjezbe_3, 'tStartRefresh') # time at next scr refresh
Kraj_vjezbe_3.status = STARTED
# keyboard checking is just starting
win.callOnFlip(Kraj_vjezbe_3.clearEvents, eventType='keyboard') # clear events on next screen flip
if Kraj_vjezbe_3.status == STARTED and not waitOnFlip:
theseKeys = Kraj_vjezbe_3.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in kraj_vjezbe_3Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "kraj_vjezbe_3"-------
for thisComponent in kraj_vjezbe_3Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "kraj_vjezbe_3" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
trials_8 = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('podrazaji\\eksperimentalni_podrazaji_z3.xlsx'),
seed=None, name='trials_8')
thisExp.addLoop(trials_8) # add the loop to the experiment
thisTrial_8 = trials_8.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_8.rgb)
if thisTrial_8 != None:
for paramName in thisTrial_8:
exec('{} = thisTrial_8[paramName]'.format(paramName))
for thisTrial_8 in trials_8:
currentLoop = trials_8
# abbreviate parameter names if possible (e.g. rgb = thisTrial_8.rgb)
if thisTrial_8 != None:
for paramName in thisTrial_8:
exec('{} = thisTrial_8[paramName]'.format(paramName))
# ------Prepare to start Routine "zadatak_3_odgovor"-------
# update component parameters for each repeat
import re
zadani_pravokutnik_z3= re.sub("[^0-9]", "", pravokutnik_z3)
ovaj_broj_z3 = str(trials_8.thisN + 1)
ukupan_broj_z3 = str(trials_8.nTotal)
ostatak_z3 = ovaj_broj_z3 + " / " + ukupan_broj_z3
screen_text_z3 = ""
odgovor_z3.setImage(pravokutnik_z3)
br_zadatka_3_text.setText(ostatak_z3
)
izbor_broja_z3.keys = []
izbor_broja_z3.rt = []
RT_izbor_broja_z3.keys = []
RT_izbor_broja_z3.rt = []
# keep track of which components have finished
zadatak_3_odgovorComponents = [uputa_z3_1, primjer_z3_1, ciljni_objekt_z3, ciljni_objekt_slika_z3, odgovor_z3, vas_odgovor_z3_1, br_vas_odgovor_z3, nastavi_24, zadatak_3_1, zadatak_3_text_1, br_zadatka_3_1, br_zadatka_3_text, izbor_broja_z3, RT_izbor_broja_z3]
for thisComponent in zadatak_3_odgovorComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
zadatak_3_odgovorClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "zadatak_3_odgovor"-------
while continueRoutine:
# get current time
t = zadatak_3_odgovorClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=zadatak_3_odgovorClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
trials_8.addData('zadani_pravokutnik_z3_PNG', pravokutnik_z3)
trials_8.addData('zadani_pravokutnik_z3', zadani_pravokutnik_z3)
trials_8.addData('tocan_odgovor_z3', tocan_odgovor_z3)
if("backspace" in izbor_broja_z3.keys):
izbor_broja_z3.keys.remove ("backspace")
if(len(izbor_broja_z3.keys) > 0):
izbor_broja_z3.keys.pop()
elif("space" in izbor_broja_z3.keys):
izbor_broja_z3.keys.remove("space")
if(len(izbor_broja_z3.keys) >= 1):
screen_text_z3 = "".join(izbor_broja_z3.keys)
trials_8.addData("broj_krugova_odgovor_z3", screen_text_z3)
continueRoutine = False
screen_text_z3 = "".join(izbor_broja_z3.keys)
# *uputa_z3_1* updates
if uputa_z3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
uputa_z3_1.frameNStart = frameN # exact frame index
uputa_z3_1.tStart = t # local t and not account for scr refresh
uputa_z3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(uputa_z3_1, 'tStartRefresh') # time at next scr refresh
uputa_z3_1.setAutoDraw(True)
# *primjer_z3_1* updates
if primjer_z3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
primjer_z3_1.frameNStart = frameN # exact frame index
primjer_z3_1.tStart = t # local t and not account for scr refresh
primjer_z3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(primjer_z3_1, 'tStartRefresh') # time at next scr refresh
primjer_z3_1.setAutoDraw(True)
# *ciljni_objekt_z3* updates
if ciljni_objekt_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
ciljni_objekt_z3.frameNStart = frameN # exact frame index
ciljni_objekt_z3.tStart = t # local t and not account for scr refresh
ciljni_objekt_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(ciljni_objekt_z3, 'tStartRefresh') # time at next scr refresh
ciljni_objekt_z3.setAutoDraw(True)
# *ciljni_objekt_slika_z3* updates
if ciljni_objekt_slika_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
ciljni_objekt_slika_z3.frameNStart = frameN # exact frame index
ciljni_objekt_slika_z3.tStart = t # local t and not account for scr refresh
ciljni_objekt_slika_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(ciljni_objekt_slika_z3, 'tStartRefresh') # time at next scr refresh
ciljni_objekt_slika_z3.setAutoDraw(True)
# *odgovor_z3* updates
if odgovor_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
odgovor_z3.frameNStart = frameN # exact frame index
odgovor_z3.tStart = t # local t and not account for scr refresh
odgovor_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(odgovor_z3, 'tStartRefresh') # time at next scr refresh
odgovor_z3.setAutoDraw(True)
# *vas_odgovor_z3_1* updates
if vas_odgovor_z3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
vas_odgovor_z3_1.frameNStart = frameN # exact frame index
vas_odgovor_z3_1.tStart = t # local t and not account for scr refresh
vas_odgovor_z3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(vas_odgovor_z3_1, 'tStartRefresh') # time at next scr refresh
vas_odgovor_z3_1.setAutoDraw(True)
# *br_vas_odgovor_z3* updates
if br_vas_odgovor_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_vas_odgovor_z3.frameNStart = frameN # exact frame index
br_vas_odgovor_z3.tStart = t # local t and not account for scr refresh
br_vas_odgovor_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_vas_odgovor_z3, 'tStartRefresh') # time at next scr refresh
br_vas_odgovor_z3.setAutoDraw(True)
if br_vas_odgovor_z3.status == STARTED: # only update if drawing
br_vas_odgovor_z3.setText(screen_text_z3, log=False)
# *nastavi_24* updates
if nastavi_24.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_24.frameNStart = frameN # exact frame index
nastavi_24.tStart = t # local t and not account for scr refresh
nastavi_24.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_24, 'tStartRefresh') # time at next scr refresh
nastavi_24.setAutoDraw(True)
# *zadatak_3_1* updates
if zadatak_3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_3_1.frameNStart = frameN # exact frame index
zadatak_3_1.tStart = t # local t and not account for scr refresh
zadatak_3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_3_1, 'tStartRefresh') # time at next scr refresh
zadatak_3_1.setAutoDraw(True)
# *zadatak_3_text_1* updates
if zadatak_3_text_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_3_text_1.frameNStart = frameN # exact frame index
zadatak_3_text_1.tStart = t # local t and not account for scr refresh
zadatak_3_text_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_3_text_1, 'tStartRefresh') # time at next scr refresh
zadatak_3_text_1.setAutoDraw(True)
# *br_zadatka_3_1* updates
if br_zadatka_3_1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_3_1.frameNStart = frameN # exact frame index
br_zadatka_3_1.tStart = t # local t and not account for scr refresh
br_zadatka_3_1.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_3_1, 'tStartRefresh') # time at next scr refresh
br_zadatka_3_1.setAutoDraw(True)
# *br_zadatka_3_text* updates
if br_zadatka_3_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_3_text.frameNStart = frameN # exact frame index
br_zadatka_3_text.tStart = t # local t and not account for scr refresh
br_zadatka_3_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_3_text, 'tStartRefresh') # time at next scr refresh
br_zadatka_3_text.setAutoDraw(True)
# *izbor_broja_z3* updates
waitOnFlip = False
if izbor_broja_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
izbor_broja_z3.frameNStart = frameN # exact frame index
izbor_broja_z3.tStart = t # local t and not account for scr refresh
izbor_broja_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(izbor_broja_z3, 'tStartRefresh') # time at next scr refresh
izbor_broja_z3.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(izbor_broja_z3.clock.reset) # t=0 on next screen flip
win.callOnFlip(izbor_broja_z3.clearEvents, eventType='keyboard') # clear events on next screen flip
if izbor_broja_z3.status == STARTED and not waitOnFlip:
theseKeys = izbor_broja_z3.getKeys(keyList=['backspace', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
izbor_broja_z3.keys.append(theseKeys.name) # storing all keys
izbor_broja_z3.rt.append(theseKeys.rt)
# *RT_izbor_broja_z3* updates
waitOnFlip = False
if RT_izbor_broja_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
RT_izbor_broja_z3.frameNStart = frameN # exact frame index
RT_izbor_broja_z3.tStart = t # local t and not account for scr refresh
RT_izbor_broja_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(RT_izbor_broja_z3, 'tStartRefresh') # time at next scr refresh
RT_izbor_broja_z3.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(RT_izbor_broja_z3.clock.reset) # t=0 on next screen flip
win.callOnFlip(RT_izbor_broja_z3.clearEvents, eventType='keyboard') # clear events on next screen flip
if RT_izbor_broja_z3.status == STARTED and not waitOnFlip:
theseKeys = RT_izbor_broja_z3.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
RT_izbor_broja_z3.keys = theseKeys.name # just the last key pressed
RT_izbor_broja_z3.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in zadatak_3_odgovorComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "zadatak_3_odgovor"-------
for thisComponent in zadatak_3_odgovorComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
trials_8.addData("broj_krugova_odgovor_z3", screen_text_z3)
# check responses
if izbor_broja_z3.keys in ['', [], None]: # No response was made
izbor_broja_z3.keys = None
trials_8.addData('izbor_broja_z3.keys',izbor_broja_z3.keys)
if izbor_broja_z3.keys != None: # we had a response
trials_8.addData('izbor_broja_z3.rt', izbor_broja_z3.rt)
# check responses
if RT_izbor_broja_z3.keys in ['', [], None]: # No response was made
RT_izbor_broja_z3.keys = None
trials_8.addData('RT_izbor_broja_z3.keys',RT_izbor_broja_z3.keys)
if RT_izbor_broja_z3.keys != None: # we had a response
trials_8.addData('RT_izbor_broja_z3.rt', RT_izbor_broja_z3.rt)
# the Routine "zadatak_3_odgovor" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "zadatak_3_sigurnost"-------
# update component parameters for each repeat
screen_text_z3_1 = ""
br_zadatka_3_3.setText(ostatak_z3
)
key_resp_14.keys = []
key_resp_14.rt = []
# keep track of which components have finished
zadatak_3_sigurnostComponents = [stupanj_sigurnosti_z3, sigurnost_primjer_z3, sigurnost_odgovor_z3, nastavi_25, zadatak_3_2, zadatak_3_text_2, br_zadatka_3_2, br_zadatka_3_3, key_resp_14]
for thisComponent in zadatak_3_sigurnostComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
zadatak_3_sigurnostClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "zadatak_3_sigurnost"-------
while continueRoutine:
# get current time
t = zadatak_3_sigurnostClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=zadatak_3_sigurnostClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
if("backspace" in key_resp_14.keys):
key_resp_14.keys.remove ("backspace")
if(len(key_resp_14.keys) > 0):
key_resp_14.keys.pop()
elif("space" in key_resp_14.keys):
key_resp_14.keys.remove("space")
if(len(key_resp_14.keys) >= 1):
screen_text_z3_1 = "".join(key_resp_14.keys)
thisExp.addData("stupnjevi_sigurnosti_z3", screen_text_z3_1)
continueRoutine = False
screen_text_z3_1 = "".join(key_resp_14.keys) + "%"
# *stupanj_sigurnosti_z3* updates
if stupanj_sigurnosti_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
stupanj_sigurnosti_z3.frameNStart = frameN # exact frame index
stupanj_sigurnosti_z3.tStart = t # local t and not account for scr refresh
stupanj_sigurnosti_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(stupanj_sigurnosti_z3, 'tStartRefresh') # time at next scr refresh
stupanj_sigurnosti_z3.setAutoDraw(True)
# *sigurnost_primjer_z3* updates
if sigurnost_primjer_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_primjer_z3.frameNStart = frameN # exact frame index
sigurnost_primjer_z3.tStart = t # local t and not account for scr refresh
sigurnost_primjer_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_primjer_z3, 'tStartRefresh') # time at next scr refresh
sigurnost_primjer_z3.setAutoDraw(True)
# *sigurnost_odgovor_z3* updates
if sigurnost_odgovor_z3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
sigurnost_odgovor_z3.frameNStart = frameN # exact frame index
sigurnost_odgovor_z3.tStart = t # local t and not account for scr refresh
sigurnost_odgovor_z3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(sigurnost_odgovor_z3, 'tStartRefresh') # time at next scr refresh
sigurnost_odgovor_z3.setAutoDraw(True)
if sigurnost_odgovor_z3.status == STARTED: # only update if drawing
sigurnost_odgovor_z3.setText(screen_text_z3_1, log=False)
# *nastavi_25* updates
if nastavi_25.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_25.frameNStart = frameN # exact frame index
nastavi_25.tStart = t # local t and not account for scr refresh
nastavi_25.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_25, 'tStartRefresh') # time at next scr refresh
nastavi_25.setAutoDraw(True)
# *zadatak_3_2* updates
if zadatak_3_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_3_2.frameNStart = frameN # exact frame index
zadatak_3_2.tStart = t # local t and not account for scr refresh
zadatak_3_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_3_2, 'tStartRefresh') # time at next scr refresh
zadatak_3_2.setAutoDraw(True)
# *zadatak_3_text_2* updates
if zadatak_3_text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
zadatak_3_text_2.frameNStart = frameN # exact frame index
zadatak_3_text_2.tStart = t # local t and not account for scr refresh
zadatak_3_text_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(zadatak_3_text_2, 'tStartRefresh') # time at next scr refresh
zadatak_3_text_2.setAutoDraw(True)
# *br_zadatka_3_2* updates
if br_zadatka_3_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_3_2.frameNStart = frameN # exact frame index
br_zadatka_3_2.tStart = t # local t and not account for scr refresh
br_zadatka_3_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_3_2, 'tStartRefresh') # time at next scr refresh
br_zadatka_3_2.setAutoDraw(True)
# *br_zadatka_3_3* updates
if br_zadatka_3_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
br_zadatka_3_3.frameNStart = frameN # exact frame index
br_zadatka_3_3.tStart = t # local t and not account for scr refresh
br_zadatka_3_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(br_zadatka_3_3, 'tStartRefresh') # time at next scr refresh
br_zadatka_3_3.setAutoDraw(True)
# *key_resp_14* updates
waitOnFlip = False
if key_resp_14.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp_14.frameNStart = frameN # exact frame index
key_resp_14.tStart = t # local t and not account for scr refresh
key_resp_14.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp_14, 'tStartRefresh') # time at next scr refresh
key_resp_14.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp_14.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp_14.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp_14.status == STARTED and not waitOnFlip:
theseKeys = key_resp_14.getKeys(keyList=['space', 'backspace', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp_14.keys.append(theseKeys.name) # storing all keys
key_resp_14.rt.append(theseKeys.rt)
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in zadatak_3_sigurnostComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "zadatak_3_sigurnost"-------
for thisComponent in zadatak_3_sigurnostComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if key_resp_14.keys in ['', [], None]: # No response was made
key_resp_14.keys = None
trials_8.addData('key_resp_14.keys',key_resp_14.keys)
if key_resp_14.keys != None: # we had a response
trials_8.addData('key_resp_14.rt', key_resp_14.rt)
# the Routine "zadatak_3_sigurnost" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'trials_8'
# ------Prepare to start Routine "kraj_i_zahvala"-------
# update component parameters for each repeat
Kraj_eksperimenta.keys = []
Kraj_eksperimenta.rt = []
# keep track of which components have finished
kraj_i_zahvalaComponents = [gotov_zadatak_3, hvala_na_sudjelovanju, hvala, nastavi_26, Kraj_eksperimenta]
for thisComponent in kraj_i_zahvalaComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
kraj_i_zahvalaClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "kraj_i_zahvala"-------
while continueRoutine:
# get current time
t = kraj_i_zahvalaClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=kraj_i_zahvalaClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *gotov_zadatak_3* updates
if gotov_zadatak_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
gotov_zadatak_3.frameNStart = frameN # exact frame index
gotov_zadatak_3.tStart = t # local t and not account for scr refresh
gotov_zadatak_3.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(gotov_zadatak_3, 'tStartRefresh') # time at next scr refresh
gotov_zadatak_3.setAutoDraw(True)
# *hvala_na_sudjelovanju* updates
if hvala_na_sudjelovanju.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
hvala_na_sudjelovanju.frameNStart = frameN # exact frame index
hvala_na_sudjelovanju.tStart = t # local t and not account for scr refresh
hvala_na_sudjelovanju.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(hvala_na_sudjelovanju, 'tStartRefresh') # time at next scr refresh
hvala_na_sudjelovanju.setAutoDraw(True)
# *hvala* updates
if hvala.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
hvala.frameNStart = frameN # exact frame index
hvala.tStart = t # local t and not account for scr refresh
hvala.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(hvala, 'tStartRefresh') # time at next scr refresh
hvala.setAutoDraw(True)
# *nastavi_26* updates
if nastavi_26.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
nastavi_26.frameNStart = frameN # exact frame index
nastavi_26.tStart = t # local t and not account for scr refresh
nastavi_26.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(nastavi_26, 'tStartRefresh') # time at next scr refresh
nastavi_26.setAutoDraw(True)
# *Kraj_eksperimenta* updates
waitOnFlip = False
if Kraj_eksperimenta.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Kraj_eksperimenta.frameNStart = frameN # exact frame index
Kraj_eksperimenta.tStart = t # local t and not account for scr refresh
Kraj_eksperimenta.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Kraj_eksperimenta, 'tStartRefresh') # time at next scr refresh
Kraj_eksperimenta.status = STARTED
# keyboard checking is just starting
win.callOnFlip(Kraj_eksperimenta.clearEvents, eventType='keyboard') # clear events on next screen flip
if Kraj_eksperimenta.status == STARTED and not waitOnFlip:
theseKeys = Kraj_eksperimenta.getKeys(keyList=['space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in kraj_i_zahvalaComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "kraj_i_zahvala"-------
for thisComponent in kraj_i_zahvalaComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "kraj_i_zahvala" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# ------Prepare to start Routine "zavrsna"-------
# update component parameters for each repeat
key_resp.keys = []
key_resp.rt = []
# keep track of which components have finished
zavrsnaComponents = [pricekajte, citanje_zamolbe, key_resp]
for thisComponent in zavrsnaComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
zavrsnaClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
continueRoutine = True
# -------Run Routine "zavrsna"-------
while continueRoutine:
# get current time
t = zavrsnaClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=zavrsnaClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *pricekajte* updates
if pricekajte.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
pricekajte.frameNStart = frameN # exact frame index
pricekajte.tStart = t # local t and not account for scr refresh
pricekajte.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(pricekajte, 'tStartRefresh') # time at next scr refresh
pricekajte.setAutoDraw(True)
# *citanje_zamolbe* updates
if citanje_zamolbe.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
citanje_zamolbe.frameNStart = frameN # exact frame index
citanje_zamolbe.tStart = t # local t and not account for scr refresh
citanje_zamolbe.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(citanje_zamolbe, 'tStartRefresh') # time at next scr refresh
citanje_zamolbe.setAutoDraw(True)
# *key_resp* updates
waitOnFlip = False
if key_resp.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
key_resp.frameNStart = frameN # exact frame index
key_resp.tStart = t # local t and not account for scr refresh
key_resp.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp, 'tStartRefresh') # time at next scr refresh
key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(key_resp.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp.status == STARTED and not waitOnFlip:
theseKeys = key_resp.getKeys(keyList=['return'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in zavrsnaComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "zavrsna"-------
for thisComponent in zavrsnaComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "zavrsna" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 48.02254 | 448 | 0.648794 | 47,695 | 372,847 | 4.918105 | 0.021218 | 0.022168 | 0.00729 | 0.011664 | 0.905716 | 0.875811 | 0.836185 | 0.775132 | 0.693762 | 0.637433 | 0 | 0.039969 | 0.256486 | 372,847 | 7,763 | 449 | 48.028726 | 0.806184 | 0.240603 | 0 | 0.523548 | 0 | 0.001948 | 0.07539 | 0.005241 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.005135 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
56e09e17fe62f69d7147e65d53b6853b08861307 | 13,135 | py | Python | python/xpath-helper/xpath_helper/filter.py | jrebecchi/xpath-helper | 6fddd89d5edb42360f1379b28513c7477a9a0ada | [
"MIT"
] | 14 | 2021-11-12T17:08:35.000Z | 2022-03-09T15:13:23.000Z | python/xpath-helper/xpath_helper/filter.py | jrebecchi/xpath-helper | 6fddd89d5edb42360f1379b28513c7477a9a0ada | [
"MIT"
] | 1 | 2022-03-09T15:19:11.000Z | 2022-03-12T06:55:28.000Z | python/xpath-helper/xpath_helper/filter.py | jrebecchi/xpath-helper | 6fddd89d5edb42360f1379b28513c7477a9a0ada | [
"MIT"
] | null | null | null | import functools
from typing import List, Optional
"""
The following Filter classes provide a simple, chainable and decomposable api
to create XPath filter expression
"""
"""
Shortcut to design any attribute name
"""
ANY_ATTRIBUTE = "*"
"""
XPath Filter containing a valid expression.
"""
class ValidExpressionFilter:
sb: List[str] = []
def __init__(self, current_path: Optional[List[str]]=None):
"""Creates an instance of ValidExpressionFilter.
Args:
currentPath (list[string]): Current filter path
"""
if (current_path != None):
self.sb = current_path
def and_operator(self, *filters: 'EmptyFilter') -> 'ValidExpressionFilter':
"""Adds one or more filter expression to the current one with the AND logical operator.
Args:
filters (list[Filter]): List of filters List of filters that will be added with the AND logical operator
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
expression = ""
if (len(self.sb) != 0):
expression += " and "
expression += "("
expression += functools.reduce(lambda acc, filter: acc + add_openrand(
filter, " and ", filter == filters[-1]), filters, "")
expression += ")"
return ValidExpressionFilter(self.sb + [expression])
def or_operator(self, *filters: 'EmptyFilter') -> 'ValidExpressionFilter':
"""Adds one or more filter expression to the current one with the OR logical operator.
Args:
filters (list[Filter]): List of filters that will be added with the OR logical operator
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
expression = ""
if (len(self.sb) != 0):
expression += " or "
expression += "("
expression += functools.reduce(lambda acc, filter: acc + add_openrand(
filter, " or ", filter == filters[-1]), filters, "")
expression += ")"
return ValidExpressionFilter(self.sb + [expression])
def __str__(self):
"""Returns the Filter as a valid XPath filter expression.
Returns:
str: the string of the corresponding XPath filter
"""
return "".join(self.sb)
def empty(self):
"""Empties the current path.
"""
self.sb = []
def is_empty(self) -> bool:
"""Returns true if filter is empty.
Returns:
bool: true if filter is empty
"""
return len(self.sb) == 0
"""
Empty XPath filter.
"""
class EmptyFilter(ValidExpressionFilter):
def __init__(self, currentPath=None):
"""Creates an instance of Filter.
Args:
currentPath (list[string]): Current filter path
"""
super().__init__(currentPath)
def has_attribute(self, attribute: str) -> ValidExpressionFilter:
"""Selects the nodes that have the attribute <code>attribute</code>.
Args:
attribute (str): attribute name
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["@" + attribute])
def attribute_contains(self, attribute: str, value: str) -> ValidExpressionFilter:
"""Selects the nodes with the attribute <code>attribute</code> containing the value <code><value</code>.
Args:
attribute (str): attribute name
value (str): attribute value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["contains(@" + attribute + ", " + replace_apostrophes(value) + ")",
])
def attribute_equals(self, attribute: str, value: str) -> ValidExpressionFilter:
"""Selects the nodes with the attribute <code>attribute</code>, whose value equals <code><value</code>.
Args:
attribute (str): attribute name
value (str | int | float): attribute value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["@" + attribute + "=" + replace_apostrophes(value) + "",
])
def attribute_not_equals(self, attribute: str, value: str) -> ValidExpressionFilter:
"""Selects the nodes with the attribute <code>attribute</code>, whose value doesn't equal <code><value</code>.
Args:
attribute (str): attribute name
value (str | int | float): attribute value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["@" + attribute + "!=" + replace_apostrophes(value)])
def attribute_less_than(self, attribute: str, value: str) -> ValidExpressionFilter:
"""Selects the nodes with the attribute <code>attribute</code>, whose value is less than <code><value<code>.
Args:
attribute (str): attribute name
value (int | float): attribute value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["@" + attribute + "<" + str(value)])
def attribute_less_than_or_equal_to(self, attribute: str, value: str) -> ValidExpressionFilter:
"""Selects the nodes with the attribute <code>attribute</code>, whose value is less than or equal to <code><value</code>.
Args:
attribute (str): attribute name
value (int | float): attribute value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["@" + attribute + "<=" + str(value)])
def attribute_greater_than(self, attribute: str, value: str) -> ValidExpressionFilter:
"""Selects the nodes with the attribute <code>attribute</code>, whose value is greater than <code><value</code>.
Args:
attribute (str): attribute name
value (int | float): attribute value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["@" + attribute + ">" + str(value)])
def attribute_greater_than_or_equal_to(self, attribute: str, value: str) -> ValidExpressionFilter:
"""Selects the nodes with the attribute <code>attribute</code>, whose value is greater than or equal to <code><value</code>.
Args:
attribute (str): attribute name
value (int | float): attribute value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["@" + attribute + ">=" + str(value)])
def value_contains(self, value: str) -> ValidExpressionFilter:
"""Selects the nodes containing the value <code><value</code>.
Args:
value (str): value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["text()[contains(., " + replace_apostrophes(value) + ")]"])
def value_equals(self, value: str) -> ValidExpressionFilter:
"""Selects the nodes whose value equals <code><value</code>.
Args:
value (str | int | float): value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["text() = " + replace_apostrophes(value)])
def value_not_equals(self, value: str) -> ValidExpressionFilter:
"""Selects the nodes with whose value doesn't equal <code><value</code>.
Args:
value (str | int | float): value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["text() !=" + replace_apostrophes(value)])
def value_less_than(self, value: str) -> ValidExpressionFilter:
"""Selects the nodes whose value is less than <code><value</code>.
Args:
value (int | float): value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["text() <" + str(value)])
def value_less_than_or_equal_to(self, value: str) -> ValidExpressionFilter:
"""Selects the nodes whose value is less than or equal to <code><value</code>.
Args:
value (int | float): value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["text() <=" + str(value)])
def value_greater_than(self, value: str) -> ValidExpressionFilter:
"""Selects the nodes whose value is greater than <code><value</code>.
Args:
value (int | float): value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["text() >" + str(value)])
def value_greater_than_or_equal_to(self, value: str) -> ValidExpressionFilter:
"""Selects the nodes whose value is greater than or equal to <code><value</code>.
Args:
value (int | float): value
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["text() >=" + str(value)])
def get(self, index: int):
"""Selects the node element who is positioned at the <code>index</code> position in its parent children list.
Args:
index (int): index of the element in the list
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + [str(index)])
def get_first(self):
"""Selects the node element who is positioned first in its parent children list.
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["1"])
def get_last(self):
"""Selects the node element who is positioned last in its parent children list.
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["last()"])
def not_operator(self, filter: ValidExpressionFilter):
"""Reverses the filter <code>filter</code>. Returns true when the filter returns false and true when the filter returns false.
Args:
filter ([type]): [description]
Returns:
ValidExpressionFilter: a new instance of ValidExpressionFilter with the newly formed expression.
"""
return ValidExpressionFilter(self.sb + ["not( " + add_openrand(filter) + " )"])
def add_openrand(filter: EmptyFilter, separator="", is_last: Optional[bool] = True) -> str:
"""Adds operand between filters
Args:
filter (Filter): a filter
separator (str, optional): " and " of " or " separator. Defaults to "".
isLast (bool, optional): True if it is the last operand. Defaults to True.
Returns:
str: opperand with and / or separator
"""
suffix: str = ""
if filter and not filter.is_empty():
expression = str(filter)
suffix = expression
if not is_last:
suffix += separator
return suffix
def replace_apostrophes(input: str) -> str:
"""Treats the presence of apostrophes so it doesn't break the XPath filter expression.
Args:
input (str | int): input
Returns:
str: XPath filter expression with apostrophes handled.
"""
if not isinstance(input, str):
return str(input)
if "'" in input:
prefix: str = ""
elements = input.split("'")
output = "concat("
for s in elements:
output += prefix + "'" + s + "'"
prefix = ',"\'",'
output += ")"
return output
else:
return "'" + input + "'"
| 36.085165 | 134 | 0.623068 | 1,378 | 13,135 | 5.883164 | 0.104499 | 0.02763 | 0.084125 | 0.082891 | 0.790675 | 0.763538 | 0.744912 | 0.715678 | 0.698409 | 0.668188 | 0 | 0.000631 | 0.276285 | 13,135 | 363 | 135 | 36.184573 | 0.852199 | 0.479711 | 0 | 0.14433 | 0 | 0 | 0.04062 | 0.007755 | 0 | 0 | 0 | 0 | 0 | 1 | 0.28866 | false | 0 | 0.020619 | 0 | 0.618557 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 6 |
853486a66909509d3692f35cf9cff1a45ee2f926 | 66 | py | Python | litex/gen/sim/__init__.py | osterwood/litex | db20cb172dc982c5879aa8080ec7aa18de181cc5 | [
"ADSL"
] | 1,501 | 2016-04-19T18:16:21.000Z | 2022-03-31T17:46:31.000Z | litex/gen/sim/__init__.py | osterwood/litex | db20cb172dc982c5879aa8080ec7aa18de181cc5 | [
"ADSL"
] | 1,135 | 2016-04-19T05:49:14.000Z | 2022-03-31T15:21:19.000Z | litex/gen/sim/__init__.py | osterwood/litex | db20cb172dc982c5879aa8080ec7aa18de181cc5 | [
"ADSL"
] | 357 | 2016-04-19T05:00:24.000Z | 2022-03-31T11:28:32.000Z | from litex.gen.sim.core import Simulator, run_simulation, passive
| 33 | 65 | 0.833333 | 10 | 66 | 5.4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.090909 | 66 | 1 | 66 | 66 | 0.9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
85b446244564d0f41c5bd7fab859a984cff08dfa | 21,075 | py | Python | joint_training/tools/hybrid_data_loader.py | hustvl/BoxCaseg | 3a74e06ee471170d1cd8fde516e6baf4052a2861 | [
"MIT"
] | 16 | 2021-03-21T05:57:38.000Z | 2022-03-30T03:29:13.000Z | joint_training/tools/hybrid_data_loader.py | hustvl/BoxCaseg | 3a74e06ee471170d1cd8fde516e6baf4052a2861 | [
"MIT"
] | null | null | null | joint_training/tools/hybrid_data_loader.py | hustvl/BoxCaseg | 3a74e06ee471170d1cd8fde516e6baf4052a2861 | [
"MIT"
] | 2 | 2021-05-05T12:44:38.000Z | 2022-02-19T11:55:23.000Z | import glob
import torch
from skimage import io, transform, color
import numpy as np
import random
import math
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from PIL import Image
import json
import os
import pdb
import random
# ==========================Train dataset transform==========================
class PDtransform(object):
def __init__(self, mid_size=320, output_size=288):
assert isinstance(mid_size, (int, tuple))
assert isinstance(output_size, (int, tuple))
self.resize = ResizeT(mid_size)
self.randomcrop = RandomCrop(output_size)
self.resize_out = ResizeT(output_size)
self.totensor = ToTensor()
def __call__(self, sample):
weakly_flag = sample['weakly']
if weakly_flag:
return self.totensor(self.resize_out(sample))
else:
return self.totensor((self.randomcrop(self.resize(sample))))
class ResizeT(object):
def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
assert len(output_size) == 2
self.output_size = output_size
def __call__(self, sample):
# sample = {'weakly': weakly_flag, 'img_name': image_name, 'img': image, 'label': label}
weakly_flag, image_name, image, label = sample['weakly'], sample['img_name'], sample['img'], sample['label']
img = transform.resize(image, (self.output_size[0], self.output_size[1]), mode='constant')
lbl = transform.resize(label, (self.output_size[0], self.output_size[1]), mode='constant', order=0,
preserve_range=True)
return {'weakly': weakly_flag, 'img_name': image_name, 'img': img, 'label': lbl}
class RandomCrop(object):
def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
assert len(output_size) == 2
self.output_size = output_size
def __call__(self, sample):
weakly_flag, image_name, image, label = sample['weakly'], sample['img_name'], sample['img'], sample['label']
if random.random() >= 0.5:
image = image[::-1]
label = label[::-1]
h, w = image.shape[:2]
new_h, new_w = self.output_size
top = np.random.randint(0, h - new_h)
left = np.random.randint(0, w - new_w)
image = image[top: top + new_h, left: left + new_w]
label = label[top: top + new_h, left: left + new_w]
return {'weakly': weakly_flag, 'img_name': image_name, 'img': image, 'label': label}
class ToTensor(object):
"""Convert ndarrays in sample to Tensors."""
def __call__(self, sample):
weakly_flag, image_name, image, label = sample['weakly'], sample['img_name'], sample['img'], sample['label']
# pascal data(weakly)
if weakly_flag:
tmpImg = np.zeros((image.shape[0], image.shape[1], 3))
tmpLbl = np.zeros(label.shape)
if np.max(label) < 1e-6:
label = label
else:
label = label / np.max(label)
if image.shape[2] == 1:
tmpImg[:, :, 0] = (image[:, :, 0] - 0.485) / 0.229
tmpImg[:, :, 1] = (image[:, :, 0] - 0.485) / 0.229
tmpImg[:, :, 2] = (image[:, :, 0] - 0.485) / 0.229
else:
tmpImg[:, :, 0] = image[:, :, 0] - 102.9801 / 255.
tmpImg[:, :, 1] = image[:, :, 1] - 115.9465 / 255.
tmpImg[:, :, 2] = image[:, :, 2] - 122.7717 / 255.
tmpLbl[:, :, 0] = label[:, :, 0]
# change the r,g,b to b,r,g from [0,255] to [0,1]
# transforms.Normalize(mean = (0.485, 0.456, 0.406), std = (0.229, 0.224, 0.225))
tmpImg = tmpImg.transpose((2, 0, 1))
tmpLbl = label.transpose((2, 0, 1))
return {'weakly': weakly_flag, 'img_name': image_name,
'img': torch.from_numpy(tmpImg), 'label': torch.from_numpy(tmpLbl)}
# DUTS-TR
else:
tmpImg = np.zeros((image.shape[0], image.shape[1], 3))
tmpLbl = np.zeros(label.shape)
image = image / np.max(image)
if np.max(label) < 1e-6:
label = label
else:
label = label / np.max(label)
if image.shape[2] == 1:
tmpImg[:, :, 0] = (image[:, :, 0] - 0.485) / 0.229
tmpImg[:, :, 1] = (image[:, :, 0] - 0.485) / 0.229
tmpImg[:, :, 2] = (image[:, :, 0] - 0.485) / 0.229
else:
tmpImg[:, :, 0] = (image[:, :, 0] - 0.485) / 0.229
tmpImg[:, :, 1] = (image[:, :, 1] - 0.456) / 0.224
tmpImg[:, :, 2] = (image[:, :, 2] - 0.406) / 0.225
tmpLbl[:, :, 0] = label[:, :, 0]
# change the r,g,b to b,r,g from [0,255] to [0,1]
# transforms.Normalize(mean = (0.485, 0.456, 0.406), std = (0.229, 0.224, 0.225))
tmpImg = tmpImg.transpose((2, 0, 1))
tmpLbl = label.transpose((2, 0, 1))
return {'weakly': weakly_flag, 'img_name': image_name,
'img': torch.from_numpy(tmpImg), 'label': torch.from_numpy(tmpLbl)}
# ==========================Test dataset transform==========================
class ResizeT_T(object):
def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
assert len(output_size) == 2
self.output_size = output_size
def __call__(self, sample):
image = sample['img']
img = transform.resize(image, (self.output_size[0], self.output_size[1]), mode='constant')
sample.update({'img': img})
return sample
class ToTensor_T(object):
"""Convert ndarrays in sample to Tensors."""
def __call__(self, sample):
image = sample['img']
tmpImg = np.zeros((image.shape[0], image.shape[1], 3))
if image.shape[2] == 1:
tmpImg[:, :, 0] = (image[:, :, 0] - 0.485) / 0.229
tmpImg[:, :, 1] = (image[:, :, 0] - 0.485) / 0.229
tmpImg[:, :, 2] = (image[:, :, 0] - 0.485) / 0.229
else:
tmpImg[:, :, 0] = image[:, :, 0] - 102.9801 / 255.
tmpImg[:, :, 1] = image[:, :, 1] - 115.9465 / 255.
tmpImg[:, :, 2] = image[:, :, 2] - 122.7717 / 255.
# change the r,g,b to b,r,g from [0,255] to [0,1]
# transforms.Normalize(mean = (0.485, 0.456, 0.406), std = (0.229, 0.224, 0.225))
tmpImg = tmpImg.transpose((2, 0, 1))
sample.update({'img': torch.from_numpy(tmpImg)})
return sample
# ====================== Train dataset ===========================
class PDTrainDataset(Dataset):
def __init__(self, json_root, image_set_root, img_name_list, lbl_name_list, transform=None):
super(PDTrainDataset, self).__init__()
# pascal_VOCSBD
self.image_set_root = image_set_root
with open(json_root, 'r') as fo:
self.json_dict = json.load(fo)
self.num_weak = len(self.json_dict['annotations'])
# DUTS-TR
self.image_name_list = img_name_list
self.label_name_list = lbl_name_list
self.num_full = len(img_name_list)
self.transform = transform
def __len__(self):
# return len(self.json_dict['annotations']) + len(self.image_name_list)
return self.num_weak + self.num_full
def get_num_wf(self):
return self.num_weak, self.num_full
def __getitem__(self, idx):
# pascal data
if idx < self.num_weak:
bbox_info = self.json_dict['annotations'][idx]
# get_type
weakly_flag = True
# # get class
# bbox_cls = bbox_info['category_id']
# get image_name
image_idx = bbox_info['image_id'] - 1
image_name = self.json_dict['images'][image_idx]['file_name']
# get_image
image_path = os.path.join(self.image_set_root, image_name)
image = io.imread(image_path)
# ori_image_shape (h, w)
ori_img_shape = image.shape[:2]
# get bbox
bbox_xywh = bbox_info['bbox'] # xywh
# convert to bbox xyxy
bbox = bbox_xywh.copy()
bbox[2] = bbox_xywh[0] + bbox_xywh[2]
bbox[3] = bbox_xywh[1] + bbox_xywh[3]
# bbox_l = bbox_broaden(bbox, ori_img_shape, self.ratio)
# box shake
bbox_l = self.bbox_broaden(bbox, ori_img_shape)
# get crop_img
crop_img = image[bbox_l[1]: bbox_l[3], bbox_l[0]: bbox_l[2], :]
# get label
label = np.zeros((image.shape[0], image.shape[1], 1), dtype=np.uint8)
label[bbox[1]: bbox[3], bbox[0]: bbox[2], :] = 255
label = label[bbox_l[1]: bbox_l[3], bbox_l[0]: bbox_l[2], :]
sample = {'weakly': weakly_flag, 'img_name': image_path, 'img': crop_img, 'label': label}
# DUTS-TR
else:
image = io.imread(self.image_name_list[idx - self.num_weak])
image_name = self.image_name_list[idx - self.num_weak]
weakly_flag = False
if len(self.label_name_list) == 0:
label_3 = np.zeros(image.shape)
else:
label_3 = io.imread(self.label_name_list[idx - self.num_weak])
label = np.zeros(label_3.shape[0:2])
if 3 == len(label_3.shape):
label = label_3[:, :, 0]
elif 2 == len(label_3.shape):
label = label_3
if 3 == len(image.shape) and 2 == len(label.shape):
label = label[:, :, np.newaxis]
elif 2 == len(image.shape) and 2 == len(label.shape):
image = image[:, :, np.newaxis]
label = label[:, :, np.newaxis]
sample = {'weakly': weakly_flag, 'img_name': image_name, 'img': image, 'label': label}
if self.transform:
sample = self.transform(sample)
# try:
# sample = self.transform(sample)
# except Exception as e:
# print(idx, weakly_flag, bbox, bbox_l, image.shape, image_name)
# print(e)
# return
return sample
def bbox_broaden(self, bbox, ori_img_shape):
# xyxy
# import pdb;pdb.set_trace()
bbox_center_x = (bbox[0] + bbox[2]) / 2.
bbox_center_y = (bbox[1] + bbox[3]) / 2.
bbox_half_w = (bbox[2] - bbox[0]) / 2.
bbox_half_h = (bbox[3] - bbox[1]) / 2.
bbox_center_x = bbox_center_x + random.uniform(-0.25, 0.25) * bbox_half_w
bbox_center_y = bbox_center_y + random.uniform(-0.25, 0.25) * bbox_half_h
ratio_x = random.uniform(0.5, 1.5)
ratio_y = random.uniform(0.5, 1.5)
xmin = int(max(0, bbox_center_x - ratio_x * bbox_half_w))
xmax = int(min(ori_img_shape[1] - 1, bbox_center_x + ratio_x * bbox_half_w))
ymin = int(max(0, bbox_center_y - ratio_y * bbox_half_h))
ymax = int(min(ori_img_shape[0] - 1, bbox_center_y + ratio_y * bbox_half_h))
# print([xmin, ymin, xmax, ymax])
return [xmin, ymin, xmax, ymax]
class CDTrainDataset(Dataset):
def __init__(self, coco_train_root, coco_train_json, img_name_list, lbl_name_list, dut_box_path=None, ratio=1.0,
transform=None, dut_shake=False):
super(CDTrainDataset, self).__init__()
# coco_set
with open(coco_train_json, 'r') as fo:
self.coco_train_json = json.load(fo)
self.coco_train_root = coco_train_root
self.coco_train_num = len(self.coco_train_json['annotations'])
# DUTS-TR
self.image_name_list = img_name_list
self.label_name_list = lbl_name_list
self.dut_shake = dut_shake
self.dut_box_path = dut_box_path
if dut_box_path:
with open(dut_box_path, 'r') as fo:
self.dut_box_ls = json.load(fo)
else:
self.dut_box_ls = None
self.transform = transform
def get_num_wf(self):
return self.coco_train_num, len(self.image_name_list)
def __len__(self):
return self.coco_train_num + len(self.image_name_list)
def __getitem__(self, idx):
# coco data
if idx < self.coco_train_num:
ann_dict = self.coco_train_json['annotations'][idx]
weakly_flag = True
# get image_name
image_id = ann_dict['image_id']
image_name = ('000000000000' + str(image_id))[-12:] + '.jpg'
# get_image
image_path = os.path.join(self.coco_train_root, image_name)
image = Image.open(image_path).convert('RGB')
image = np.array(image)
# ori_image_shape (h, w)
ori_img_shape = image.shape[:2]
# get bbox
bbox_xywh = ann_dict['bbox'] # xywh
bbox_xywh = [int(i) for i in bbox_xywh]
# avoid h==0 or w==0
bbox_xywh[2] = max(bbox_xywh[2], 1)
bbox_xywh[3] = max(bbox_xywh[3], 1)
# convert to bbox xyxy
bbox = bbox_xywh.copy()
bbox[2] = bbox_xywh[0] + bbox_xywh[2]
bbox[3] = bbox_xywh[1] + bbox_xywh[3]
# bbox_l = bbox_broaden(bbox, ori_img_shape, self.ratio)
bbox_l = self.bbox_broaden(bbox, ori_img_shape)
# get crop_img
if len(image.shape) == 3:
crop_img = image[bbox_l[1]: bbox_l[3], bbox_l[0]: bbox_l[2], :]
else:
print(image.shape, image_name)
crop_img = image[bbox_l[1]: bbox_l[3], bbox_l[0]: bbox_l[2], :]
# get label
label = np.zeros((image.shape[0], image.shape[1], 1), dtype=np.uint8)
label[bbox[1]: bbox[3], bbox[0]: bbox[2], :] = 255
label = label[bbox_l[1]: bbox_l[3], bbox_l[0]: bbox_l[2], :]
sample = {'weakly': weakly_flag, 'img_name': image_path, 'img': crop_img, 'label': label}
# DUTS-TR
else:
image = io.imread(self.image_name_list[idx - self.coco_train_num])
image_name = self.image_name_list[idx - self.coco_train_num]
weakly_flag = False
if (0 == len(self.label_name_list)):
label_3 = np.zeros(image.shape)
else:
label_3 = io.imread(self.label_name_list[idx - self.coco_train_num])
label = np.zeros(label_3.shape[0:2])
if (3 == len(label_3.shape)):
label = label_3[:, :, 0]
elif (2 == len(label_3.shape)):
label = label_3
if (3 == len(image.shape) and 2 == len(label.shape)):
label = label[:, :, np.newaxis]
elif (2 == len(image.shape) and 2 == len(label.shape)):
image = image[:, :, np.newaxis]
label = label[:, :, np.newaxis]
if self.dut_shake and self.dut_box_ls:
last_name = image_name.split('/')[-1]
bbox = self.dut_box_ls[last_name]
bbox_l = self.bbox_broaden(bbox, image.shape[:2])
# print(idx-25815, bbox, bbox_l, image.shape[:2])
# get crop_img
crop_image = image[bbox_l[1]: bbox_l[3], bbox_l[0]: bbox_l[2], :]
# get label
label = label[bbox_l[1]: bbox_l[3], bbox_l[0]: bbox_l[2], :]
# print(image.shape[:2], bbox_l)
sample = {'weakly': weakly_flag, 'img_name': image_name, 'img': crop_image, 'label': label}
else:
sample = {'weakly': weakly_flag, 'img_name': image_name, 'img': image, 'label': label}
if self.transform:
try:
sample = self.transform(sample)
except Exception as e:
print(idx, bbox, bbox_l, image.shape, image_name)
print(e)
return
return sample
def bbox_broaden(self, bbox, ori_img_shape):
# xyxy
# import pdb;pdb.set_trace()
bbox_center_x = (bbox[0] + bbox[2]) / 2.
bbox_center_y = (bbox[1] + bbox[3]) / 2.
bbox_half_w = (bbox[2] - bbox[0]) / 2.
bbox_half_h = (bbox[3] - bbox[1]) / 2.
bbox_center_x = bbox_center_x + random.uniform(-0.25, 0.25) * bbox_half_w
bbox_center_y = bbox_center_y + random.uniform(-0.25, 0.25) * bbox_half_h
ratio_x = random.uniform(0.5, 1.5)
ratio_y = random.uniform(0.5, 1.5)
xmin = int(max(0, bbox_center_x - ratio_x * bbox_half_w))
xmax = int(min(ori_img_shape[1] - 1, bbox_center_x + ratio_x * bbox_half_w))
ymin = int(max(0, bbox_center_y - ratio_y * bbox_half_h))
ymax = int(min(ori_img_shape[0] - 1, bbox_center_y + ratio_y * bbox_half_h))
if xmax == xmin:
if xmin == 0:
xmax = 1
else:
xmin -= 1
if ymax == ymin:
if ymin == 0:
ymax = 1
else:
ymin -= 1
# print([xmin, ymin, xmax, ymax])
return [xmin, ymin, xmax, ymax]
# ====================== Test dataset ===========================
class PascalDataset(Dataset):
def __init__(self, json_root, image_set_root, transform=None):
super(PascalDataset, self).__init__()
self.image_set_root = image_set_root
with open(json_root, 'r') as fo:
self.json_dict = json.load(fo)
self.transform = transform
def __len__(self):
return len(self.json_dict['annotations'])
def __getitem__(self, bbox_idx):
bbox_info = self.json_dict['annotations'][bbox_idx]
# get class
bbox_cls = bbox_info['category_id']
# get image_name
image_idx = bbox_info['image_id'] - 1
image_name = self.json_dict['images'][image_idx]['file_name']
# get_image
image_path = os.path.join(self.image_set_root, image_name)
image = io.imread(image_path)
# ori_image_shape (h, w)
ori_img_shape = image.shape[:2]
# get bbox
bbox_xywh = bbox_info['bbox'] # xywh
# convert to bbox xyxy
bbox = bbox_xywh.copy()
bbox[2] = bbox_xywh[0] + bbox_xywh[2]
bbox[3] = bbox_xywh[1] + bbox_xywh[3]
# get crop_img
crop_img = image[bbox[1]: bbox[3], bbox[0]: bbox[2], :]
sample = {'cls': bbox_cls, 'bbox': bbox, 'img_name': image_name,
'img': crop_img, 'ori_img_shape': ori_img_shape}
if self.transform:
sample = self.transform(sample)
return sample
class COCODataset(Dataset):
def __init__(self, coco_json, coco_image_set_root, transform=None):
super(COCODataset, self).__init__()
# coco
self.coco_image_set_root = coco_image_set_root
with open(coco_json, 'r') as fo:
self.coco_json_dict = json.load(fo)
self.transform = transform
def __len__(self):
return len(self.coco_json_dict['annotations'])
def __getitem__(self, idx):
ann_dict = self.coco_json_dict['annotations'][idx]
# get image_name
image_id = ann_dict['image_id']
image_name = ('000000000000' + str(image_id))[-12:] + '.jpg'
# get_image
image_path = os.path.join(self.coco_image_set_root, image_name)
image = Image.open(image_path).convert('RGB')
image = np.array(image)
# ori_image_shape (h, w)
ori_img_shape = image.shape[:2]
# get cls
bbox_cls = ann_dict['category_id']
# get bbox
bbox_xywh = ann_dict['bbox'] # xywh
bbox_xywh = [int(i) for i in bbox_xywh]
# avoid h==0 or w==0
bbox_xywh[2] = max(bbox_xywh[2], 1)
bbox_xywh[3] = max(bbox_xywh[3], 1)
# convert to bbox xyxy
bbox = bbox_xywh.copy()
bbox[2] = bbox_xywh[0] + bbox_xywh[2]
bbox[3] = bbox_xywh[1] + bbox_xywh[3]
# get crop_img
if len(image.shape) == 3:
crop_img = image[bbox[1]: bbox[3], bbox[0]: bbox[2], :]
else:
print(image.shape, image_name)
crop_img = image[bbox[1]: bbox[3], bbox[0]: bbox[2], :]
sample = {'cls': bbox_cls, 'bbox': bbox, 'img_name': image_name,
'img': crop_img, 'ori_img_shape': ori_img_shape}
if self.transform:
try:
sample = self.transform(sample)
except:
print(sample['img'].shape, sample['img_name'], bbox_xywh, idx)
return sample
if __name__ == '__main__':
pass
| 37.234982 | 116 | 0.544247 | 2,816 | 21,075 | 3.822798 | 0.072088 | 0.034278 | 0.018393 | 0.01765 | 0.816256 | 0.787924 | 0.74575 | 0.735253 | 0.720204 | 0.697353 | 0 | 0.041819 | 0.31013 | 21,075 | 565 | 117 | 37.300885 | 0.698604 | 0.096512 | 0 | 0.662269 | 0 | 0 | 0.032663 | 0 | 0 | 0 | 0 | 0 | 0.021108 | 1 | 0.068602 | false | 0.002639 | 0.036939 | 0.015831 | 0.184697 | 0.013193 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
a42e25ce8cd00b8f3f836dc7700316f5afbf6f96 | 176 | py | Python | worker/utils.py | ByK95/discount_code | 76b7babfbccaa211d842f7b0f5c55e88e7c355cb | [
"MIT"
] | null | null | null | worker/utils.py | ByK95/discount_code | 76b7babfbccaa211d842f7b0f5c55e88e7c355cb | [
"MIT"
] | null | null | null | worker/utils.py | ByK95/discount_code | 76b7babfbccaa211d842f7b0f5c55e88e7c355cb | [
"MIT"
] | null | null | null | from secrets import choice
import string
def generate_code(length):
return "".join(
[choice(string.ascii_uppercase + string.digits) for _ in range(length)]
)
| 19.555556 | 79 | 0.698864 | 22 | 176 | 5.454545 | 0.772727 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.204545 | 176 | 8 | 80 | 22 | 0.857143 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.333333 | 0.166667 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 6 |
a42e2c0542de3256d46cc491cf8cf691bfe195cd | 140 | py | Python | learning-material/snippets/base/var_string.py | RatsWar/aprende-python | 2ae708fc6cdfc2eac918ef510a4b9d9a2ef8b3ad | [
"MIT"
] | 2 | 2018-07-20T07:34:06.000Z | 2019-06-11T08:58:32.000Z | learning-material/snippets/base/var_string.py | RatsWar/aprende-python | 2ae708fc6cdfc2eac918ef510a4b9d9a2ef8b3ad | [
"MIT"
] | 1 | 2019-06-16T20:55:53.000Z | 2019-06-16T20:55:53.000Z | learning-material/snippets/base/var_string.py | RatsWar/aprende-python | 2ae708fc6cdfc2eac918ef510a4b9d9a2ef8b3ad | [
"MIT"
] | 3 | 2019-06-11T07:22:39.000Z | 2021-09-26T19:50:26.000Z | myString1 = 'Hola'
myString2 = "Hola"
print("Cadena con notación 1: ")
print(myString1)
print("Cadena con notación 2: ")
print(myString2)
| 15.555556 | 32 | 0.714286 | 18 | 140 | 5.555556 | 0.5 | 0.22 | 0.28 | 0.44 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.05 | 0.142857 | 140 | 8 | 33 | 17.5 | 0.783333 | 0 | 0 | 0 | 0 | 0 | 0.385714 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.666667 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 6 |
a441ed30bb045652b9e42b168b0409ce4a8078fb | 39 | py | Python | haversine/__init__.py | adamchainz/haversine | 3782e1264dfc3566c9d3670006168d903d396585 | [
"MIT"
] | 1 | 2019-11-22T12:13:12.000Z | 2019-11-22T12:13:12.000Z | haversine/__init__.py | MarkusShepherd/haversine | 3782e1264dfc3566c9d3670006168d903d396585 | [
"MIT"
] | null | null | null | haversine/__init__.py | MarkusShepherd/haversine | 3782e1264dfc3566c9d3670006168d903d396585 | [
"MIT"
] | null | null | null | from .haversine import Unit, haversine
| 19.5 | 38 | 0.820513 | 5 | 39 | 6.4 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.128205 | 39 | 1 | 39 | 39 | 0.941176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
f110684b165f525df5d847b72c708bbeea2b8b1d | 30 | py | Python | examples/tasks.py | corpseware/reliabilly | e8d310d43478407e2cf8b45cc746362124140385 | [
"MIT"
] | 1 | 2018-11-24T02:07:37.000Z | 2018-11-24T02:07:37.000Z | examples/tasks.py | corpseware/reliabilly | e8d310d43478407e2cf8b45cc746362124140385 | [
"MIT"
] | 1 | 2019-01-23T07:12:30.000Z | 2019-01-23T07:12:30.000Z | examples/tasks.py | corpseware/reliabilly | e8d310d43478407e2cf8b45cc746362124140385 | [
"MIT"
] | 1 | 2019-01-16T05:30:49.000Z | 2019-01-16T05:30:49.000Z | from reliabilly.tasks import * | 30 | 30 | 0.833333 | 4 | 30 | 6.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | 30 | 1 | 30 | 30 | 0.925926 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
f152fc888de6ea0cc62853a81c1c431b8d17a5f2 | 36 | py | Python | src/satextractor/monitor/__init__.py | oxfordeo/sat-extractor | 1d6841751e8b2ce65a02f5d3d608f181a31ab917 | [
"BSD-2-Clause"
] | 29 | 2021-11-02T16:07:04.000Z | 2022-03-14T00:16:27.000Z | src/satextractor/monitor/__init__.py | oxfordeo/sat-extractor | 1d6841751e8b2ce65a02f5d3d608f181a31ab917 | [
"BSD-2-Clause"
] | 16 | 2021-11-01T16:23:01.000Z | 2022-03-24T11:44:13.000Z | src/satextractor/monitor/__init__.py | oxfordeo/sat-extractor | 1d6841751e8b2ce65a02f5d3d608f181a31ab917 | [
"BSD-2-Clause"
] | 6 | 2021-11-09T01:10:30.000Z | 2022-03-14T18:04:32.000Z | from .gcp_monitor import GCPMonitor
| 18 | 35 | 0.861111 | 5 | 36 | 6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.111111 | 36 | 1 | 36 | 36 | 0.9375 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
74c305dcec59d228cd01e76638d8c6eaf40cb536 | 71 | py | Python | ghibli/api/routes/films/__init__.py | chris-verclytte/ghibli-back | 149314ab31705590051516940d38d0c84a10c8ed | [
"Apache-2.0"
] | null | null | null | ghibli/api/routes/films/__init__.py | chris-verclytte/ghibli-back | 149314ab31705590051516940d38d0c84a10c8ed | [
"Apache-2.0"
] | 2 | 2020-08-13T12:16:27.000Z | 2020-08-13T13:21:21.000Z | ghibli/api/routes/films/__init__.py | chris-verclytte/ghibli-back | 149314ab31705590051516940d38d0c84a10c8ed | [
"Apache-2.0"
] | null | null | null | """Ghibli films module"""
from .register_routes import register_routes
| 23.666667 | 44 | 0.802817 | 9 | 71 | 6.111111 | 0.777778 | 0.509091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.098592 | 71 | 2 | 45 | 35.5 | 0.859375 | 0.267606 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
74fdc3bb0a35cfc1e1e3b188713fba4c944e94d4 | 338 | py | Python | kcwidrp/tests/test_bokeh_plotting.py | MNBrod/KCWI_DRP | 9331a545879f647ed83ceb9c7d925770b254a8eb | [
"BSD-3-Clause"
] | 5 | 2020-04-09T20:05:52.000Z | 2021-08-04T18:04:28.000Z | kcwidrp/tests/test_bokeh_plotting.py | MNBrod/KCWI_DRP | 9331a545879f647ed83ceb9c7d925770b254a8eb | [
"BSD-3-Clause"
] | 80 | 2020-03-19T00:35:27.000Z | 2022-03-07T20:08:23.000Z | kcwidrp/tests/test_bokeh_plotting.py | MNBrod/KCWI_DRP | 9331a545879f647ed83ceb9c7d925770b254a8eb | [
"BSD-3-Clause"
] | 9 | 2021-01-22T02:00:32.000Z | 2022-02-08T19:43:16.000Z | import multiprocessing
from kcwidrp.core.bokeh_plotting import check_running_process
import time
def test_check_running_process():
# check that a python process is running
assert check_running_process('python') is True
# check that a non-running process is not running
assert check_running_process('abcdef') is False
| 24.142857 | 61 | 0.786982 | 48 | 338 | 5.333333 | 0.479167 | 0.273438 | 0.296875 | 0.195313 | 0.25 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.16568 | 338 | 13 | 62 | 26 | 0.907801 | 0.254438 | 0 | 0 | 0 | 0 | 0.048583 | 0 | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0.166667 | true | 0 | 0.5 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
2d095e839629e00a7e10fc61172162349add2076 | 1,573 | py | Python | src/injecta/config/YamlConfigReaderTest.py | DataSentics/injecta | 090eeac6c76c43d40be71df678222a07b0a3c783 | [
"MIT"
] | 3 | 2021-09-27T12:55:00.000Z | 2022-01-31T19:13:23.000Z | src/injecta/config/YamlConfigReaderTest.py | DataSentics/injecta | 090eeac6c76c43d40be71df678222a07b0a3c783 | [
"MIT"
] | null | null | null | src/injecta/config/YamlConfigReaderTest.py | DataSentics/injecta | 090eeac6c76c43d40be71df678222a07b0a3c783 | [
"MIT"
] | 1 | 2021-03-04T09:12:05.000Z | 2021-03-04T09:12:05.000Z | import unittest
from injecta.config.YamlConfigReader import YamlConfigReader
from injecta.lib_root import get_lib_root
class YamlConfigReaderTest(unittest.TestCase):
def setUp(self):
self.__yaml_config_reader = YamlConfigReader()
def test_basic(self):
config = self.__yaml_config_reader.read(get_lib_root() + "/config/YamlConfigReaderTest/basic/config.yaml")
parameters = config["parameters"]
self.assertFalse("imports" in config)
self.assertEqual(123, parameters["param_level1"])
self.assertEqual(456, parameters["param_level2"])
self.assertEqual(666, parameters["param_level3"])
self.assertEqual(1, parameters["merged_param"]["level1"])
self.assertEqual(2, parameters["merged_param"]["level2"])
self.assertEqual(3, parameters["merged_param"]["level3"])
self.assertEqual(111, parameters["param_to_overwrite"])
def test_search(self):
config = self.__yaml_config_reader.read(get_lib_root() + "/config/YamlConfigReaderTest/search/_config/config.yaml")
parameters = config["parameters"]
self.assertFalse("imports" in config)
self.assertEqual(123, parameters["param_level1"])
self.assertEqual(456, parameters["param_level2"])
self.assertEqual(789, parameters["param_level3"])
self.assertEqual(1, parameters["merged_param"]["level1"])
self.assertEqual(2, parameters["merged_param"]["level2"])
self.assertEqual(3, parameters["merged_param"]["level3"])
if __name__ == "__main__":
unittest.main()
| 41.394737 | 123 | 0.704387 | 171 | 1,573 | 6.222222 | 0.25731 | 0.183271 | 0.118421 | 0.097744 | 0.712406 | 0.712406 | 0.712406 | 0.712406 | 0.712406 | 0.712406 | 0 | 0.029658 | 0.164018 | 1,573 | 37 | 124 | 42.513514 | 0.779468 | 0 | 0 | 0.482759 | 0 | 0 | 0.216783 | 0.064209 | 0 | 0 | 0 | 0 | 0.517241 | 1 | 0.103448 | false | 0 | 0.172414 | 0 | 0.310345 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
2d0e850460d6130046130737f6e07742664f133a | 40 | py | Python | plainhtml/__init__.py | snapADDY/plainhtml | 7578474adf55462f27e203f6000dc03d548cb46c | [
"MIT"
] | null | null | null | plainhtml/__init__.py | snapADDY/plainhtml | 7578474adf55462f27e203f6000dc03d548cb46c | [
"MIT"
] | null | null | null | plainhtml/__init__.py | snapADDY/plainhtml | 7578474adf55462f27e203f6000dc03d548cb46c | [
"MIT"
] | null | null | null | from plainhtml.core import extract_text
| 20 | 39 | 0.875 | 6 | 40 | 5.666667 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | 40 | 1 | 40 | 40 | 0.944444 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
2d0ed7f470ade8150d22ca578a5d96a3f7dd0719 | 2,385 | py | Python | gigalixir/config.py | oleks/gigalixir-cli | d1b1c303e24be548ddc895165e34652c378f4347 | [
"MIT"
] | 52 | 2017-11-15T09:05:36.000Z | 2021-11-29T07:58:47.000Z | gigalixir/config.py | oleks/gigalixir-cli | d1b1c303e24be548ddc895165e34652c378f4347 | [
"MIT"
] | 76 | 2017-08-17T16:58:48.000Z | 2022-03-11T11:01:15.000Z | gigalixir/config.py | oleks/gigalixir-cli | d1b1c303e24be548ddc895165e34652c378f4347 | [
"MIT"
] | 50 | 2017-06-21T19:51:56.000Z | 2022-01-19T01:58:19.000Z | import requests
from . import auth
import urllib
import json
import click
from . import presenter
from six.moves.urllib.parse import quote
def get(host, app_name):
r = requests.get('%s/api/apps/%s/configs' % (host, quote(app_name.encode('utf-8'))), headers = {
'Content-Type': 'application/json',
})
if r.status_code != 200:
if r.status_code == 401:
raise auth.AuthException()
raise Exception(r.text)
else:
data = json.loads(r.text)["data"]
presenter.echo_json(data)
def create(host, app_name, key, value):
r = requests.post('%s/api/apps/%s/configs' % (host, quote(app_name.encode('utf-8'))), headers = {
'Content-Type': 'application/json',
}, json = {
"key": key,
"value": value
})
if r.status_code != 201:
if r.status_code == 401:
raise auth.AuthException()
raise Exception(r.text)
else:
data = json.loads(r.text)["data"]
presenter.echo_json(data)
def create_multiple(host, app_name, configs):
r = requests.post('%s/api/apps/%s/configs' % (host, quote(app_name.encode('utf-8'))), headers = {
'Content-Type': 'application/json',
}, json = {
"configs": configs
})
if r.status_code != 201:
if r.status_code == 401:
raise auth.AuthException()
raise Exception(r.text)
else:
data = json.loads(r.text)["data"]
presenter.echo_json(data)
def copy(host, src_app_name, dst_app_name):
r = requests.post('%s/api/apps/%s/configs/copy' % (host, quote(dst_app_name.encode('utf-8'))), headers = {
'Content-Type': 'application/json',
}, json = {
"from": src_app_name
})
if r.status_code != 200:
if r.status_code == 401:
raise auth.AuthException()
raise Exception(r.text)
else:
data = json.loads(r.text)["data"]
presenter.echo_json(data)
def delete(host, app_name, key):
r = requests.delete('%s/api/apps/%s/configs' % (host, quote(app_name.encode('utf-8'))), headers = {
'Content-Type': 'application/json',
}, json = {
"key": key,
})
if r.status_code != 200:
if r.status_code == 401:
raise auth.AuthException()
raise Exception(r.text)
else:
data = json.loads(r.text)["data"]
presenter.echo_json(data)
| 30.974026 | 110 | 0.584486 | 313 | 2,385 | 4.351438 | 0.166134 | 0.061674 | 0.066079 | 0.095448 | 0.776065 | 0.776065 | 0.776065 | 0.776065 | 0.754772 | 0.754772 | 0 | 0.019741 | 0.256604 | 2,385 | 76 | 111 | 31.381579 | 0.748449 | 0 | 0 | 0.746479 | 0 | 0 | 0.13501 | 0.048218 | 0 | 0 | 0 | 0 | 0 | 1 | 0.070423 | false | 0 | 0.098592 | 0 | 0.169014 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
2d36e8f2324c37d5f4ab2087ca071322bf450df8 | 33 | py | Python | src/uix/separator/__init__.py | Eastern-Skill7173/SharedSnippets | 399c9d61a938788e229bc6e6f6dcd38bf5ad9c0e | [
"MIT"
] | 1 | 2022-03-18T20:29:40.000Z | 2022-03-18T20:29:40.000Z | src/uix/separator/__init__.py | Eastern-Skill7173/SharedSnippets | 399c9d61a938788e229bc6e6f6dcd38bf5ad9c0e | [
"MIT"
] | null | null | null | src/uix/separator/__init__.py | Eastern-Skill7173/SharedSnippets | 399c9d61a938788e229bc6e6f6dcd38bf5ad9c0e | [
"MIT"
] | null | null | null | from .separator import Separator
| 16.5 | 32 | 0.848485 | 4 | 33 | 7 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.121212 | 33 | 1 | 33 | 33 | 0.965517 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
7461935deffa6cb4e695a6ad64264104723d430d | 97 | py | Python | Common/IO/DirInfo/IDirInfo.py | enriqueescobar-askida/Kinito.Finance | 5308748b64829ac798a858161f9b4a9e5829db44 | [
"MIT"
] | 2 | 2020-03-04T11:18:38.000Z | 2020-05-10T15:36:42.000Z | Common/IO/DirInfo/IDirInfo.py | enriqueescobar-askida/Kinito.Finance | 5308748b64829ac798a858161f9b4a9e5829db44 | [
"MIT"
] | 6 | 2020-03-30T16:42:47.000Z | 2021-12-13T20:37:21.000Z | Common/IO/DirInfo/IDirInfo.py | enriqueescobar-askida/Kinito.Finance | 5308748b64829ac798a858161f9b4a9e5829db44 | [
"MIT"
] | 1 | 2020-04-14T11:26:16.000Z | 2020-04-14T11:26:16.000Z | from Common.Objects.Interfaceable import Interfaceable
class IDirInfo(Interfaceable):
pass
| 16.166667 | 54 | 0.814433 | 10 | 97 | 7.9 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.134021 | 97 | 5 | 55 | 19.4 | 0.940476 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
746a04c6bee849e218d4492971dbebbc209ee977 | 959 | py | Python | S2l/Thesis_Ch3/Study/plotter_test_eval_metric_for_diff_teps_Exp1.py | leopauly/Observation-Learning-Simulations | 462c04a87c45aae51537b8ea5b44646afa31d3a5 | [
"MIT"
] | null | null | null | S2l/Thesis_Ch3/Study/plotter_test_eval_metric_for_diff_teps_Exp1.py | leopauly/Observation-Learning-Simulations | 462c04a87c45aae51537b8ea5b44646afa31d3a5 | [
"MIT"
] | null | null | null | S2l/Thesis_Ch3/Study/plotter_test_eval_metric_for_diff_teps_Exp1.py | leopauly/Observation-Learning-Simulations | 462c04a87c45aae51537b8ea5b44646afa31d3a5 | [
"MIT"
] | null | null | null | #### For plotting from reawrd values stored in files
import numpy as np
import matplotlib.pyplot as plt
import sys
y = np.loadtxt('./Exp1/test_eval_metric_per_step_Study.Exp1.60ps.txt', unpack=True)
y_new=[y_ for y_ in y if y_!=0]
x=range(len(y_new))
print(x,y_new)
plt.figure(1)
plt.plot(x,y_new)
plt.title('Eval metric')
plt.xlabel('steps')
plt.ylabel('Eval metric per step')
y = np.loadtxt('./Exp1/test_eval_metric_per_step_Study.Exp1.110eps.txt', unpack=True)
y_new=[y_ for y_ in y if y_!=0]
x=range(len(y_new))
print(x,y_new)
plt.figure(1)
plt.plot(x,y_new)
plt.title('Eval metric')
plt.xlabel('steps')
plt.ylabel('Eval metric per step')
y = np.loadtxt('./Exp1/test_eval_metric_per_step_Study.Exp1.160eps.txt', unpack=True)
y_new=[y_ for y_ in y if y_!=0]
x=range(len(y_new))
print(x,y_new)
plt.figure(1)
plt.plot(x,y_new)
plt.title('Eval metric')
plt.xlabel('steps')
plt.ylabel('Eval metric per step')
plt.savefig('Study_steps_Exp1')
plt.show()
| 22.833333 | 85 | 0.734098 | 191 | 959 | 3.486911 | 0.246073 | 0.072072 | 0.117117 | 0.153153 | 0.792793 | 0.792793 | 0.792793 | 0.792793 | 0.792793 | 0.792793 | 0 | 0.024306 | 0.099062 | 959 | 41 | 86 | 23.390244 | 0.746528 | 0.049009 | 0 | 0.75 | 0 | 0 | 0.313466 | 0.1766 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.09375 | 0 | 0.09375 | 0.09375 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
74751e064343736ee9ea895bf0703c2e6dce51bd | 9,892 | py | Python | rdfframes/test_queries/test_join_tow_graphs.py | qcri/RDFframe | 2a50105479051c134cc5eddc9e20d55b755ef765 | [
"MIT"
] | 13 | 2019-07-06T00:10:11.000Z | 2022-02-20T02:14:16.000Z | rdfframes/test_queries/test_join_tow_graphs.py | qcri/RDFrame | 2a50105479051c134cc5eddc9e20d55b755ef765 | [
"MIT"
] | 1 | 2019-05-20T08:51:42.000Z | 2019-05-20T08:51:42.000Z | rdfframes/test_queries/test_join_tow_graphs.py | qcri/RDFframe | 2a50105479051c134cc5eddc9e20d55b755ef765 | [
"MIT"
] | 3 | 2020-04-17T10:50:37.000Z | 2022-03-23T01:30:16.000Z | from time import time
from rdfframes.knowledge_graph import KnowledgeGraph
from rdfframes.client.http_client import HttpClientDataFormat, HttpClient
from rdfframes.client.sparql_endpoint_client import SPARQLEndpointClient
from rdfframes.utils.constants import JoinType
__author__ = "Ghadeer"
endpoint = 'http://10.161.202.101:8890/sparql/'
port = 8890
output_format = HttpClientDataFormat.PANDAS_DF
max_rows = 1000000
timeout = 12000
client = HttpClient(endpoint_url=endpoint,
port=port,
return_format=output_format,
timeout=timeout,
max_rows=max_rows
)
client = SPARQLEndpointClient(endpoint)
graph1 = KnowledgeGraph(graph_name='dbpedia')
graph2 = KnowledgeGraph(graph_name='yago',
graph_uri='http://yago-knowledge.org/',
prefixes={
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'yago': 'http://yago-knowledge.org/resource/',
'yagoinfo': 'http://yago-knowledge.org/resource/infobox/en/'
})
def join_warning(join_type):
dbpedia_actors = graph1.feature_domain_range('dbpp:starring', 'film', 'actor') \
.expand('actor', [('dbpp:birthPlace', 'actor_country'), ('dbpp:name', 'name')]) \
.filter({'actor_country': ['regex(str(?actor_country), "USA")']})#.select_cols(['name'])
yago_actors = graph2.feature_domain_range('yago:actedIn', 'actor', 'film') \
.expand('actor', [('yago:isCitizenOf', 'actor_country'), ('yagoinfo:name', 'name')]) \
.filter({'actor_country': ['= yago:United_States']})#.select_cols(['name'])
actors = dbpedia_actors.join(yago_actors, 'name', join_type=join_type)
print(actors.to_sparql())
def join_expand(join_type):
dbpedia_actors = graph1.feature_domain_range('dbpp:starring', 'film1', 'actor1') \
.expand('actor1', [('dbpp:birthPlace', 'actor_country1'), ('dbpp:name', 'name')]) \
.filter({'actor_country1': ['regex(str(?actor_country1), "USA")']})#.select_cols(['name'])
yago_actors = graph2.feature_domain_range('yago:actedIn', 'actor2', 'film2') \
.expand('actor2', [('yago:isCitizenOf', 'actor_country2'), ('yagoinfo:name', 'name')]) \
.filter({'actor_country2': ['= yago:United_States']})#.select_cols(['name'])
actors = dbpedia_actors.join(yago_actors, 'name', join_type=join_type)
print(actors.to_sparql())
def join_expand_grouped(join_type):
dbpedia_actors = graph1.feature_domain_range('dbpp:starring', 'film1', 'actor1') \
.expand('actor1', [('dbpp:birthPlace', 'actor_country1'), ('dbpp:name', 'name')]) \
.filter({'actor_country1': ['regex(str(?actor_country1), "USA")']})#.select_cols(['name'])
yago_actors = graph2.feature_domain_range('yago:actedIn', 'actor2', 'film2') \
.expand('actor2', [('yago:isCitizenOf', 'actor_country2'), ('yagoinfo:name', 'name')]) \
.filter({'actor_country2': ['= yago:United_States']}).group_by(['name']).count('film2')
actors = dbpedia_actors.join(yago_actors, 'name', join_type=join_type)
print(actors.to_sparql())
def join_grouped(join_type):
dbpedia_actors = graph1.feature_domain_range('dbpp:starring', 'film1', 'actor1') \
.expand('actor1', [('dbpp:birthPlace', 'actor_country1'), ('dbpp:name', 'name')]) \
.filter({'actor_country1': ['regex(str(?actor_country1), "USA")']}).group_by(['name']).count('film1')
yago_actors = graph2.feature_domain_range('yago:actedIn', 'actor2', 'film2') \
.expand('actor2', [('yago:isCitizenOf', 'actor_country2'), ('yagoinfo:name', 'name')]) \
.filter({'actor_country2': ['= yago:United_States']}).group_by(['name']).count('film2')
actors = dbpedia_actors.join(yago_actors, 'name', join_type=join_type)
print(actors.to_sparql())
#df = actors.execute(client, return_format=output_format)
#print(df.shape)
join_types = [JoinType.InnerJoin, JoinType.LeftOuterJoin, JoinType.RightOuterJoin, JoinType.OuterJoin]
"""
for join_type in join_types:
start = time()
join_expand(join_type)
duration = time()-start
print("Duration of {} join between 2 expandable datasets from 2 graphs = {} sec".format(join_type, duration))
for join_type in join_types:
start = time()
join_expand_grouped(join_type)
duration = time()-start
print("Duration of {} join between an expandable and grouped datasets from 2 graphs = {} sec".format(join_type, duration))
"""
for join_type in join_types:
start = time()
join_grouped(join_type)
duration = time()-start
print("Duration of {} join between 2 grouped datasets from 2 graphs = {} sec".format(join_type, duration))
"""
Inner Join
RDFFRames
PREFIX dbpp: <http://dbpedia.org/property/>
PREFIX dbpo: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX yagoinfo: <http://yago-knowledge.org/resource/infobox/en/>
PREFIX yago: <http://yago-knowledge.org/resource/>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dbpr: <http://dbpedia.org/resource/>
SELECT *
WHERE
{ GRAPH <http://dbpedia.org>
{ ?film1 dbpp:starring ?actor1 .
?actor1 dbpp:birthPlace ?actor_country1 ;
dbpp:name ?name
FILTER regex(str(?actor_country1), "USA")
}
GRAPH <http://yago-knowledge.org/>
{ ?actor2 yago:actedIn ?film2 ;
yago:isCitizenOf ?actor_country2 ;
yagoinfo:name ?name
FILTER ( ?actor_country2 = yago:United_States )
}
}
# 37569 Rows. -- 17215 msec.
Unique names = 454 Rows. -- 661 msec.
"""
"""
Left Outer Join
PREFIX dbpp: <http://dbpedia.org/property/>
PREFIX dbpo: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX yagoinfo: <http://yago-knowledge.org/resource/infobox/en/>
PREFIX yago: <http://yago-knowledge.org/resource/>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dbpr: <http://dbpedia.org/resource/>
SELECT *
WHERE
{ GRAPH <http://dbpedia.org>
{ ?film1 dbpp:starring ?actor1 .
?actor1 dbpp:birthPlace ?actor_country1 ;
dbpp:name ?name
FILTER regex(str(?actor_country1), "USA")
}
OPTIONAL
{ GRAPH <http://yago-knowledge.org/>
{ ?actor2 yago:actedIn ?film2 ;
yago:isCitizenOf ?actor_country2 ;
yagoinfo:name ?name
FILTER ( ?actor_country2 = yago:United_States )
}
}
}
38675 Rows. -- 17509 msec.
Unique names: 848 Rows. -- 844 msec.
"""
"""
Right Outer Join
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dbpp: <http://dbpedia.org/property/>
PREFIX dbpr: <http://dbpedia.org/resource/>
PREFIX dbpo: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX yago: <http://yago-knowledge.org/resource/>
PREFIX yagoinfo: <http://yago-knowledge.org/resource/infobox/en/>
SELECT DISTINCT ?name
WHERE {
GRAPH <http://yago-knowledge.org/> {
?actor2 yago:actedIn ?film2 .
?actor2 yago:isCitizenOf ?actor_country2 .
?actor2 yagoinfo:name ?name .
FILTER ( (?actor_country2 = yago:United_States ) )
}
OPTIONAL { GRAPH <http://dbpedia.org> {
?film1 dbpp:starring ?actor1 .
?actor1 dbpp:birthPlace ?actor_country1 .
?actor1 dbpp:name ?name .
FILTER ( regex(str(?actor_country1), "USA") )
}}
}
140225 Rows. -- 20522 msec.
Unique names 14,140 Rows. -- 204 msec.
"""
"""
Grouped_Expandable_Inner_Join
PREFIX dbpp: <http://dbpedia.org/property/>
PREFIX dbpo: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX yagoinfo: <http://yago-knowledge.org/resource/infobox/en/>
PREFIX yago: <http://yago-knowledge.org/resource/>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dbpr: <http://dbpedia.org/resource/>
SELECT *
WHERE
{ GRAPH <http://yago-knowledge.org/>
{ ?actor2 yago:actedIn ?film2 ;
yago:isCitizenOf ?actor_country2 ;
yagoinfo:name ?name
FILTER ( ?actor_country2 = yago:United_States )
}
GRAPH <http://dbpedia.org>
{ { SELECT DISTINCT ?name (COUNT(?film1) AS ?count)
WHERE
{ ?film1 dbpp:starring ?actor1 .
?actor1 dbpp:birthPlace ?actor_country1 ;
dbpp:name ?name
FILTER regex(str(?actor_country1), "USA")
}
GROUP BY ?name
}
}
}
"""
"""
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dbpp: <http://dbpedia.org/property/>
PREFIX dbpr: <http://dbpedia.org/resource/>
PREFIX dbpo: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX yago: <http://yago-knowledge.org/resource/>
PREFIX yagoinfo: <http://yago-knowledge.org/resource/infobox/en/>
SELECT *
FROM <http://dbpedia.org>
WHERE {
{
SELECT DISTINCT ?name (COUNT( ?film1) AS ?count)
WHERE {
?film1 dbpp:starring ?actor1 .
?actor1 dbpp:birthPlace ?actor_country1 .
?actor1 dbpp:name ?name .
FILTER ( regex(str(?actor_country1), "USA") )
} GROUP BY ?name
}
UNION
{
SELECT DISTINCT ?name (COUNT( ?film2) AS ?count)
WHERE {
?actor2 yago:actedIn ?film2 .
?actor2 yago:isCitizenOf ?actor_country2 .
?actor2 yagoinfo:name ?name .
FILTER ( (?actor_country2 = yago:United_States ) )
} GROUP BY ?name
}
}
"""
| 35.328571 | 126 | 0.639304 | 1,189 | 9,892 | 5.191758 | 0.126997 | 0.027215 | 0.045359 | 0.055079 | 0.804795 | 0.794427 | 0.789243 | 0.789243 | 0.780172 | 0.77515 | 0 | 0.03558 | 0.195916 | 9,892 | 279 | 127 | 35.455197 | 0.740508 | 0.018298 | 0 | 0.347826 | 0 | 0 | 0.302794 | 0.025331 | 0 | 0 | 0 | 0 | 0 | 1 | 0.057971 | false | 0 | 0.072464 | 0 | 0.130435 | 0.072464 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
74a06f0df8222f0a9c79ff3d7cd890a523045956 | 38 | py | Python | src/gtfs_router/raptor/__init__.py | wsp-sag/gtfs-router | ce7f9e0c469d83aa2eeca289affca94b12254f2d | [
"MIT"
] | 2 | 2021-08-18T22:13:46.000Z | 2021-09-03T23:59:23.000Z | src/gtfs_router/raptor/__init__.py | wsp-sag/gtfs-router | ce7f9e0c469d83aa2eeca289affca94b12254f2d | [
"MIT"
] | null | null | null | src/gtfs_router/raptor/__init__.py | wsp-sag/gtfs-router | ce7f9e0c469d83aa2eeca289affca94b12254f2d | [
"MIT"
] | 2 | 2021-10-20T10:15:56.000Z | 2021-12-24T01:43:01.000Z | from .raptor import raptor_assignment
| 19 | 37 | 0.868421 | 5 | 38 | 6.4 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.105263 | 38 | 1 | 38 | 38 | 0.941176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
7783d24d22acacf5e350cfabfc3ffe427a768c5b | 40,881 | py | Python | delicatessen/estimating_equations/survival.py | pzivich/Deli | 761aa51c6949334b59fffb185be4266177454b6c | [
"MIT"
] | null | null | null | delicatessen/estimating_equations/survival.py | pzivich/Deli | 761aa51c6949334b59fffb185be4266177454b6c | [
"MIT"
] | null | null | null | delicatessen/estimating_equations/survival.py | pzivich/Deli | 761aa51c6949334b59fffb185be4266177454b6c | [
"MIT"
] | null | null | null | import numpy as np
#################################################################
# Survival Estimating Equations
def ee_exponential_model(theta, t, delta):
r"""Default stacked estimating equation for a one-parameter exponential survival model. Let :math:`T_i` indicate the
time of the event and :math:`C_i` indicate the time to right censoring. Therefore, the observable data consists of
:math:`t_i = min(T_i, C_i)` and :math:`\delta_i = I(t_i = T_i)`. The estimating equation is
.. math::
\psi(t_i,\delta_i; \lambda) = \frac{\delta_i}{\lambda} - t_i
Here, :math:`\theta` is a single parameter that corresponds to the scale parameter for the exponential distribution.
The hazard from the Weibull model is parameterized as the following
.. math::
h(t) = \lambda
Note
----
All provided estimating equations are meant to be wrapped inside a user-specified function. Throughtout, these
user-defined functions are defined as ``psi``.
Parameters
----------
theta : ndarray, list, vector
Theta in the case of the exponential model consists of a single value. Furthermore, the parameter will be
non-negative. Therefore, an initial value like the ``[1, ]`` is recommended.
t : ndarray, list, vector
1-dimensional vector of n observed times. No missing data should be included (missing data may cause
unexpected behavior).
delta : ndarray, list, vector
1-dimensional vector of n event indicators, where 1 indicates an event and 0 indicates right censoring. No
missing data should be included (missing data may cause unexpected behavior).
Returns
-------
array :
Returns a 1-by-n NumPy array evaluated for the input theta.
Examples
--------
Construction of a estimating equation(s) with ``ee_exponential_model`` should be done similar to the following
>>> import numpy as np
>>> import pandas as pd
>>> from delicatessen import MEstimator
>>> from delicatessen.estimating_equations import ee_exponential_model
Some generic survival data to estimate an exponential survival model
>>> n = 100
>>> data = pd.DataFrame()
>>> data['C'] = np.random.weibull(a=1, size=n)
>>> data['C'] = np.where(data['C'] > 5, 5, data['C'])
>>> data['T'] = 0.8*np.random.weibull(a=1.0, size=n)
>>> data['delta'] = np.where(data['T'] < data['C'], 1, 0)
>>> data['t'] = np.where(data['delta'] == 1, data['T'], data['C'])
Defining psi, or the stacked estimating equations
>>> def psi(theta):
>>> return ee_exponential_model(theta=theta,
>>> t=data['t'], delta=data['delta'])
Calling the M-estimation procedure (note that `init` has 1 value).
>>> estr = MEstimator(stacked_equations=psi, init=[1.])
>>> estr.estimate(solver='lm')
Inspecting the parameter estimates, variance, and confidence intervals
>>> estr.theta
>>> estr.variance
>>> estr.confidence_intervals()
Inspecting parameter the specific parameter estimates
>>> estr.theta[0] # lambda (scale)
References
----------
"""
return (delta / theta) - t # Returning calculation for exponential distribution
def ee_weibull_model(theta, t, delta):
r"""Default stacked estimating equation for a two-parameter Weibull survival model. Let :math:`T_i` indicate the
time of the event and :math:`C_i` indicate the time to right censoring. Therefore, the observable data consists of
:math:`t_i = min(T_i, C_i)` and :math:`\delta_i = I(t_i = T_i)`. The estimating equation is
.. math::
\psi(t_i,\delta_i; \lambda, \gamma) = \frac{\delta_i}{\lambda} - t_i^{\gamma} \\
\psi(t_i,\delta_i; \lambda, \gamma) = \frac{\delta_i}{\gamma} + \delta_i \log(t_i)
- \lambda t_i^{\gamma} \log(t_i)
Here, :math:`\theta` consists of two parameters for the Weibull model: the scale (:math:`\lambda`) and the shape
(:math:`\gamma`). The hazard from the Weibull model is parameterized as the following
.. math::
h(t) = \lambda \gamma t^{\gamma - 1}
Note
----
All provided estimating equations are meant to be wrapped inside a user-specified function. Throughtout, these
user-defined functions are defined as ``psi``.
Parameters
----------
theta : ndarray, list, vector
Theta in the case of the exponential model consists of a single value. Furthermore, the parameter will be
non-negative. Therefore, an initial value like the ``[1, ]`` is recommended.
t : ndarray, list, vector
1-dimensional vector of n observed times. No missing data should be included (missing data may cause
unexpected behavior).
delta : ndarray, list, vector
1-dimensional vector of n event indicators, where 1 indicates an event and 0 indicates right censoring. No
missing data should be included (missing data may cause unexpected behavior).
Returns
-------
array :
Returns a 2-by-n NumPy array evaluated for the input theta.
Examples
--------
Construction of a estimating equation(s) with ``ee_weibull_model`` should be done similar to the following
>>> import numpy as np
>>> import pandas as pd
>>> from delicatessen import MEstimator
>>> from delicatessen.estimating_equations import ee_weibull_model
Some generic survival data to estimate a Weibull survival model
>>> n = 100
>>> data = pd.DataFrame()
>>> data['C'] = np.random.weibull(a=1, size=n)
>>> data['C'] = np.where(data['C'] > 5, 5, data['C'])
>>> data['T'] = 0.8*np.random.weibull(a=0.8, size=n)
>>> data['delta'] = np.where(data['T'] < data['C'], 1, 0)
>>> data['t'] = np.where(data['delta'] == 1, data['T'], data['C'])
Defining psi, or the stacked estimating equations
>>> def psi(theta):
>>> return ee_weibull_model(theta=theta,
>>> t=data['t'], delta=data['delta'])
Calling the M-estimation procedure (note that `init` has 1 value).
>>> estr = MEstimator(stacked_equations=psi, init=[1., 1.])
>>> estr.estimate(solver='lm')
Inspecting the parameter estimates, variance, and confidence intervals
>>> estr.theta
>>> estr.variance
>>> estr.confidence_intervals()
Inspecting parameter the specific parameter estimates
>>> estr.theta[0] # lambda (scale)
>>> estr.theta[1] # gamma (shape)
References
----------
"""
# Extracting and naming parameters for my convenience
lambd, gamma = theta[0], theta[1] # Names follow Collett
# Calculating the contributions
contribution_1 = (delta/lambd) - t**gamma # Calculating estimating equation for lambda
contribution_2 = ((delta/gamma) # Calculating estimating equation for gamma
+ (delta*np.log(t))
- (lambd * (t**gamma) * np.log(t)))
# Returning stacked estimating equations
return np.vstack((contribution_1,
contribution_2))
def ee_exponential_measure(theta, times, n, measure, scale):
r"""Default stacked estimating equation to calculate a survival measure (survival, density, risk, hazard, cumulative
hazard) given the parameters of an exponential model. Let :math:`T_i` indicate the time of the event and :math:`C_i`
indicate the time to right censoring. Therefore, the observable data consists of :math:`t_i = min(T_i, C_i)` and
:math:`\delta_i = I(t_i = T_i)`. The estimating equation for the survival function at time :math:`t` is
.. math::
\psi_S(t,\delta_i; \theta, \lambda) = \exp(- \lambda t) - \theta
and the estimating equation for the hazard function at time :math:`t` is
.. math::
\psi_h(t; \theta, \mu, \lambda) = \lambda - \theta
For the other measures, we take advantage of the following transformation between survival measures
.. math::
F(t) = 1 - S(t) \\
H(t) = -\log(S(t)) \\
f(t) = h(t) S(t)
Note
----
For proper uncertainty estimation, this estimating equation is meant to be stacked together with the corresponding
exponential model.
Parameters
----------
theta : ndarray, list, vector
theta consists of t values. The initial values should consist of the same number of elements as provided in the
``times`` argument.
times : int, float, ndarray, list, vector
A single time or 1-dimensional collection of times to calculate the measure at. The number of provided times
should consist of the same number of elements as provided in the ``theta`` argument.
n : int
Number of observations in the input data. This argument ensures that the dimensions of the estimating equation
are correct given the number of observations in the data.
measure : str
Measure to calculate. Options include survival (``'survival'``), density (``'density'``), risk or the cumulative
density (``'risk'``), hazard (``'hazard'``), or cumulative hazard (``'cumulative_hazard'``).
scale : float, int
The estimated scale parameter from the Weibull model. From ``ee_weibull_model``, will be the first element.
Returns
-------
array :
Returns a t-by-n NumPy array evaluated for the input theta
Examples
--------
Construction of a estimating equation(s) with ``ee_exponential_model`` and ``ee_exponential_measure`` should be done
similar to the following. First, we will estimate the survival at time 5.
>>> import numpy as np
>>> import pandas as pd
>>> from delicatessen import MEstimator
>>> from delicatessen.estimating_equations import ee_exponential_model, ee_exponential_measure
Some generic survival data to estimate an exponential survival model
>>> n = 100
>>> data = pd.DataFrame()
>>> data['C'] = np.random.weibull(a=1, size=n)
>>> data['C'] = np.where(data['C'] > 5, 5, data['C'])
>>> data['T'] = 0.8*np.random.weibull(a=1.0, size=n)
>>> data['delta'] = np.where(data['T'] < data['C'], 1, 0)
>>> data['t'] = np.where(data['delta'] == 1, data['T'], data['C'])
Defining psi, or the stacked estimating equations
>>> def psi(theta):
>>> exp = ee_exponential_model(theta=theta[0], t=data['t'],
>>> delta=data['delta'])
>>> pred_surv_t = ee_exponential_measure(theta=theta[1], n=data.shape[0],
>>> times=5, measure='survival',
>>> scale=theta[0])
>>> return np.vstack((exp, pred_surv_t))
Calling the M-estimation procedure (note that `init` has 2 value, one for the scale and the other for
:math:`S(t=5)`).
>>> estr = MEstimator(stacked_equations=psi, init=[1., 0.5])
>>> estr.estimate(solver='lm')
Inspecting the estimate, variance, and confidence intervals for :math:`S(t=5)`
>>> estr.theta[-1] # \hat{S}(t)
>>> estr.variance[-1, -1] # \hat{Var}(\hat{S}(t))
>>> estr.confidence_intervals()[-1, :] # 95% CI for S(t)
Next, we will consider evaluating the survival function at multiple time points (so we can easily create a plot of
the survival function and the corresponding confidence intervals)
Note
----
When calculate the survival (or other measures) at many time points, it is generally best to optimize the
exponential coefficients in a separate model, then use the pre-washed coefficients in another M-estimator with the
many time points. This helps the optimizer to converge faster in number of iterations and total run-time.
To make everything easier, we will generate a list of uniformly spaced values between the start and end points of
our desired survival function. We will also generate initial values of the same length (to help the optimizer, we
also start our starting values from near one and end near zero).
>>> resolution = 50
>>> time_spacing = list(np.linspace(0.01, 5, resolution))
>>> fast_inits = list(np.linspace(0.99, 0.01, resolution))
Defining psi, or the stacked estimating equations
>>> def psi(theta):
>>> exp = ee_exponential_model(theta=theta[0], t=data['t'],
>>> delta=data['delta'])
>>> pred_surv_t = ee_exponential_measure(theta=theta[1:], n=data.shape[0],
>>> times=time_spacing, measure='survival',
>>> scale=theta[0])
>>> return np.vstack((exp, pred_surv_t))
Calling the M-estimation procedure. As stated in the note above, we use the pre-washed covariates to help the
optimizer (since the resolution means we are estimating 50 different parameters).
>>> mestr = MEstimator(psi, init=list(estr.theta[0]) + fast_inits)
>>> mestr.estimate(solver="lm")
To plot the survival curves, we could do the following:
>>> import matplotlib.pyplot as plt
>>> ci = mestr.confidence_intervals()[1:, :] # Extracting relevant CI
>>> plt.fill_between(time_spacing, ci[:, 0], ci[:, 1], alpha=0.2)
>>> plt.plot(time_spacing, mestr.theta[1:], '-')
>>> plt.show()
References
----------
"""
# Lazy approach that just calls existing weibull measure function (exponential is a Weibull with shape=1
return ee_weibull_measure(theta=theta, times=times,
n=n, measure=measure,
scale=scale, shape=1)
def ee_weibull_measure(theta, times, n, measure, scale, shape):
r"""Default stacked estimating equation to calculate a survival measure (survival, density, risk, hazard, cumulative
hazard) given the parameters of a Weibull model. Let :math:`T_i` indicate the time of the event and :math:`C_i`
indicate the time to right censoring. Therefore, the observable data consists of :math:`t_i = min(T_i, C_i)` and
:math:`\delta_i = I(t_i = T_i)`. The estimating equation for the survival function at time :math:`t` is
.. math::
\psi_S(t; \theta, \lambda, \gamma) = \exp(- \lambda t^{\gamma}) - \theta
and the estimating equation for the hazard function at time :math:`t` is
.. math::
\psi_h(t; \theta, \mu, \beta, \gamma) = \lambda \gamma t^{\gamma - 1} - \theta
For the other measures, we take advantage of the following transformation between survival measures
.. math::
F(t) = 1 - S(t) \\
H(t) = -\log(S(t)) \\
f(t) = h(t) S(t)
Note
----
For proper uncertainty estimation, this estimating equation is meant to be stacked together with the corresponding
Weibull model.
Parameters
----------
theta : ndarray, list, vector
theta consists of t values. The initial values should consist of the same number of elements as provided in the
``times`` argument.
times : int, float, ndarray, list, vector
A single time or 1-dimensional collection of times to calculate the measure at. The number of provided times
should consist of the same number of elements as provided in the ``theta`` argument.
n : int
Number of observations in the input data. This argument ensures that the dimensions of the estimating equation
are correct given the number of observations in the data.
measure : str
Measure to calculate. Options include survival (``'survival'``), density (``'density'``), risk or the cumulative
density (``'risk'``), hazard (``'hazard'``), or cumulative hazard (``'cumulative_hazard'``).
scale : float, int
The estimated scale parameter from the Weibull model. From ``ee_weibull_model``, will be the first element.
shape :
The estimated shape parameter from the Weibull model. From ``ee_weibull_model``, will be the second (last)
element.
Returns
-------
array :
Returns a t-by-n NumPy array evaluated for the input theta
Examples
--------
Construction of a estimating equation(s) with ``ee_weibull_model`` and ``ee_weibull_measure`` should be done
similar to the following. First, we will estimate the survival at time 5.
>>> import numpy as np
>>> import pandas as pd
>>> from delicatessen import MEstimator
>>> from delicatessen.estimating_equations import ee_weibull_model, ee_weibull_measure
Some generic survival data to estimate an exponential survival model
>>> n = 100
>>> data = pd.DataFrame()
>>> data['C'] = np.random.weibull(a=1, size=n)
>>> data['C'] = np.where(data['C'] > 5, 5, data['C'])
>>> data['T'] = 0.8*np.random.weibull(a=0.8, size=n)
>>> data['delta'] = np.where(data['T'] < data['C'], 1, 0)
>>> data['t'] = np.where(data['delta'] == 1, data['T'], data['C'])
Defining psi, or the stacked estimating equations
>>> def psi(theta):
>>> exp = ee_weibull_model(theta=theta[0:2], t=data['t'],
>>> delta=data['delta'])
>>> pred_surv_t = ee_weibull_measure(theta=theta[2], n=data.shape[0],
>>> times=5, measure='survival',
>>> scale=theta[0], shape=theta[1])
>>> return np.vstack((exp, pred_surv_t))
Calling the M-estimation procedure (note that `init` has 2 value, one for the scale and the other for
:math:`S(t=5)`).
>>> estr = MEstimator(stacked_equations=psi, init=[1., 1., 0.5])
>>> estr.estimate(solver='lm')
Inspecting the estimate, variance, and confidence intervals for :math:`S(t=5)`
>>> estr.theta[-1] # \hat{S}(t)
>>> estr.variance[-1, -1] # \hat{Var}(\hat{S}(t))
>>> estr.confidence_intervals()[-1, :] # 95% CI for S(t)
Next, we will consider evaluating the survival function at multiple time points (so we can easily create a plot of
the survival function and the corresponding confidence intervals)
Note
----
When calculate the survival (or other measures) at many time points, it is generally best to optimize the Weibull
coefficients in a separate model, then use the pre-washed coefficients in another M-estimator with the many
time points. This helps the optimizer to converge faster in number of iterations and total run-time.
To make everything easier, we will generate a list of uniformly spaced values between the start and end points of
our desired survival function. We will also generate initial values of the same length (to help the optimizer, we
also start our starting values from near one and end near zero).
>>> resolution = 50
>>> time_spacing = list(np.linspace(0.01, 5, resolution))
>>> fast_inits = list(np.linspace(0.99, 0.01, resolution))
Defining psi, or the stacked estimating equations
>>> def psi(theta):
>>> exp = ee_weibull_model(theta=theta[0:2], t=data['t'],
>>> delta=data['delta'])
>>> pred_surv_t = ee_weibull_measure(theta=theta[2:], n=data.shape[0],
>>> times=time_spacing, measure='survival',
>>> scale=theta[0], shape=theta[1])
>>> return np.vstack((exp, pred_surv_t))
Calling the M-estimation procedure. As stated in the note above, we use the pre-washed covariates to help the
optimizer (since the resolution means we are estimating 50 different parameters).
>>> mestr = MEstimator(psi, init=list(estr.theta[0:2]) + fast_inits)
>>> mestr.estimate(solver="lm")
To plot the survival curves, we could do the following:
>>> import matplotlib.pyplot as plt
>>> ci = mestr.confidence_intervals()[2:, :] # Extracting relevant CI
>>> plt.fill_between(time_spacing, ci[:, 0], ci[:, 1], alpha=0.2)
>>> plt.plot(time_spacing, mestr.theta[2:], '-')
>>> plt.show()
References
----------
"""
lambd, gamma = scale, shape
def calculate_metric(time, theta_t):
# Intermediate calculations
survival_t = np.exp(-lambd * (time ** gamma))*np.ones(n) # Survival calculation from parameters
hazard_t = lambd*gamma*(time**(gamma-1))*np.ones(n) # hazard calculation from parameters
# Calculating specific measures
if measure == "survival":
metric = survival_t # S(t) = S(t)
elif measure == "risk":
metric = 1 - survival_t # F(t) = 1 - S(t)
elif measure == "cumulative_hazard":
metric = -1 * np.log(survival_t) # H(t) = -log(S(t))
elif measure == "hazard":
metric = hazard_t # h(t) = h(t)
elif measure == "density":
metric = hazard_t * survival_t # f(t) = h(t) * S(t)
else:
raise ValueError("The measure '"
+ str(measure)
+ "' is not supported. Please select one of the following: "
"survival, density, risk, hazard, cumulative_hazard.")
return (metric - theta_t).T # Calculate difference from theta, and do transpose for vstack
# Logic to allow for either a single time or multiple times
if type(times) is int or type(times) is float: # For single time,
return calculate_metric(time=times, theta_t=theta) # ... calculate the transformation and return
else: # For multiple time points,
if len(theta) != len(times): # ... check length is the same (to prevent errors)
raise ValueError("There is a mismatch between the number of "
"`theta`'s and the number of `times` provided.")
stacked_time_evals = [] # ... empty list for stacking the equations
for t, thet in zip(times, theta): # ... loop through each theta and each time
metric_t = calculate_metric(time=t, theta_t=thet) # ... ... calculate the transformation
stacked_time_evals.append(metric_t) # ... ... stack transformation into storage
return np.vstack(stacked_time_evals) # ... return a vstack of the equations
def ee_aft_weibull(theta, X, t, delta, weights=None):
r"""Default stacked estimating equation for accelerated failure time (AFT) model with a Weibull distribution. Let
:math:`T_i` indicate the time of the event and :math:`C_i` indicate the time to right censoring. Therefore, the
observable data consists of :math:`t_i = min(T_i, C_i)` and :math:`\delta_i = I(t_i = T_i)`. The estimating
equation is
.. math::
\psi(t_i,X_i,\delta_i; \lambda, \beta, \gamma) = \frac{\delta_i}{\lambda} - t_i^{\gamma} \exp(\beta X_i) \\
\psi(t_i,X_i,\delta_i; \lambda, \beta, \gamma) = \delta_i X_i - (\lambda t_i^{\gamma} \exp(\beta X_i))X_i \\
\psi(t_i,X_i,\delta_i; \lambda, \beta, \gamma) = \frac{\delta_i}{\gamma} + \delta_i \log(t) - \lambda
t_i^{\gamma} \exp(\beta X_i) \log(t)
Here, the Weibull-AFT actually consists of the following parameters: :math:`\mu, \beta, \sigma`. The above
estimating equations use the proportional hazards form of the Weibull model. For the Weibull AFT, notice the
following relation between the coefficients: :math:`\lambda = - \mu \gamma`,
:math:`\beta_{PH} = - \beta_{AFT} \gamma`, and :math:`\gamma = \exp(\sigma)`.
Here, :math:`\theta` is a 1-by-(2+b) array, where b is the distinct covariates included as part of X. For example,
if X is a 3-by-n matrix, then theta will be a 1-by-5 array. The code is general to allow for an arbitrary number of
X's (as long as there is enough support in the data).
Note
----
All provided estimating equations are meant to be wrapped inside a user-specified function. Throughtout, these
user-defined functions are defined as ``psi``.
Parameters
----------
theta : ndarray, list, vector
theta consists of 1+b+1 values. Therefore, initial values should consist of the same number as the number of
columns present in ``X`` plus 2. This can easily be accomplished generally by
``[0, ] + [0, ] * X.shape[1] + [0, ]``.
X : ndarray, list, vector
2-dimensional vector of n observed values for b variables. No missing data should be included (missing data
may cause unexpected behavior).
t : ndarray, list, vector
1-dimensional vector of n observed times. Note that times can either be events (indicated by :math:`\delta_i=1`)
or censored (indicated by :math:`\delta_i=0`). No missing data should be included (missing data may cause
unexpected behavior).
delta : ndarray, list, vector
1-dimensional vector of n values indicating whether the time was an event or censoring. No missing data should
be included (missing data may cause unexpected behavior).
weights : ndarray, list, vector, None, optional
1-dimensional vector of n weights. No missing weights should be included. Default is None, which assigns a
weight of 1 to all observations.
Returns
-------
array :
Returns a b-by-n NumPy array evaluated for the input theta. The first element of theta corresponds to the scale
parameter, the last element corresponds to the shape parameter, and the middle parameters correspond to the
model coefficients.
Examples
--------
Construction of a estimating equation(s) with ``ee_aft_weibull`` should be done similar to the following
>>> import numpy as np
>>> import pandas as pd
>>> from delicatessen import MEstimator
>>> from delicatessen.estimating_equations import ee_aft_weibull
Some generic survival data to estimate a Weibull AFT regresion model
>>> n = 100
>>> data = pd.DataFrame()
>>> data['X'] = np.random.binomial(n=1, p=0.5, size=n)
>>> data['W'] = np.random.binomial(n=1, p=0.5, size=n)
>>> data['T'] = (1/1.25 + 1/np.exp(0.5)*data['X'])*np.random.weibull(a=0.75, size=n)
>>> data['C'] = np.random.weibull(a=1, size=n)
>>> data['C'] = np.where(data['C'] > 10, 10, data['C'])
>>> data['delta'] = np.where(data['T'] < data['C'], 1, 0)
>>> data['t'] = np.where(data['delta'] == 1, data['T'], data['C'])
>>> d_obs = data[['X', 'W', 't', 'delta']].copy()
Defining psi, or the stacked estimating equations
>>> def psi(theta):
>>> return ee_aft_weibull(theta=theta, X=d_obs[['C', 'X', 'Z']],
>>> t=d_obs['t'], delta=d_obs['delta'])
Calling the M-estimation procedure (note that `init` has 2+2 values now, since ``X.shape[1] = 2``).
>>> estr = MEstimator(stacked_equations=psi, init=[0., 0., 0., 0.])
>>> estr.estimate(solver='lm')
Inspecting the parameter estimates, variance, and confidence intervals
>>> estr.theta
>>> estr.variance
>>> estr.confidence_intervals()
Inspecting parameter the specific parameter estimates
>>> estr.theta[0] # log(mu) (scale)
>>> estr.theta[1:-1] # log(beta) (scale coefficients)
>>> estr.theta[-1] # log(sigma) (shape)
References
----------
Collett D. (2015). Parametric proportional hazards models In: Modelling survival data in medical research.
CRC press. pg171-220
Collett D. (2015). Accelerated failure time and other parametric models. In: Modelling survival data in medical
research. CRC press. pg171-220
"""
# TODO expand sigma to allow for coefficients too!
X = np.asarray(X) # Convert to NumPy array
t = np.asarray(t)[:, None] # Convert to NumPy array and ensure correct shape for matrix algebra
delta = np.asarray(delta)[:, None] # Convert to NumPy array and ensure correct shape for matrix algebra
beta_dim = X.shape[1]
# Extract coefficients
sigma = np.exp(theta[-1]) # exponential so as to be nice to optimizer
mu = np.exp(-1 * theta[0] * sigma) # exponential so as to be nice to optimizer, and apply PH->AFT transform
beta = (-1 * sigma * # exponential so as to be nice to optimizer, and apply PH->AFT transform
np.asarray(theta[1:beta_dim+1])[:, None])
# Rationale: I apply some transformations for the AFT model. These transformations are to go from the proportional
# hazards form of the Weibull model to the AFT form of the Weibull model. Explicitly,
# lambda = exp(-mu * sigma)
# beta = -alpha * sigma
# gamma = exp(sigma)
# I used the proportional hazards form because the log-likelihood has written out on page 200 of Collett's
# "Modeling Survival Data in Medical Research" (3ed). I then solved for the derivative, which gives the
# 3 contributions to the score function (which is also the estimating equations here).
# Allowing for a weighted Weibull-AFT model
if weights is None: # If weights is unspecified
w = np.ones(X.shape[0]) # ... assign weight of 1 to all observations
else: # Otherwise
w = np.asarray(weights) # ... set weights as input vector
# Intermediate calculations (evaluated once to optimize run-time)
exp_coefs = np.exp(np.dot(X, beta)) # Calculates the exponential of coefficients
log_t = np.log(t) # Calculates natural log of the time contribution
# Estimating equations
contribution_1 = w*(delta/mu # Estimating equation: mu
- exp_coefs*(t**sigma)).T
contribution_2 = w*((delta # Estimating equation: beta
- mu*(t**sigma)*exp_coefs)*X).T
contribution_3 = w*(delta/sigma # Estimating equation: sigma
+ delta*log_t
- mu*(t**sigma)*exp_coefs*log_t).T
# Output b-by-n matrix
return np.vstack((contribution_1, # mu contribution
contribution_2, # beta contribution
contribution_3)) # sigma contribution
def ee_aft_weibull_measure(theta, times, X, measure, mu, beta, sigma):
r"""Default stacked estimating equation to calculate a survival measure (survival, density, risk, hazard,
cumulative hazard) given a specific covariate pattern and coefficients from a Weibull accelerated failure time
(AFT) model. Let :math:`T_i` indicate the time of the event and :math:`C_i` indicate the time to right censoring.
Therefore, the observable data consists of :math:`t_i = min(T_i, C_i)` and :math:`\delta_i = I(t_i = T_i)`. The
estimating equation for the survival function at time :math:`t` is
.. math::
\psi_S(t,X_i; \theta, \mu, \beta, \sigma) = \exp(-1 \lambda_i t^{\gamma}) - \theta
and the estimating equation for the hazard function at time :math:`t` is
.. math::
\psi_h(t,X_i; \theta, \mu, \beta, \sigma) = \lambda_i \gamma t^{\gamma - 1} - \theta
where
.. math::
\gamma = \exp(\sigma) \\
\lambda_i = \exp(-1 (\mu + X \beta) * \gamma)
For the other measures, we take advantage of the following transformation between survival meaures
.. math::
F(t) = 1 - S(t) \\
H(t) = -\log(S(t)) \\
f(t) = h(t) S(t)
Note
----
For proper uncertainty estimation, this estimating equation is meant to be stacked together with the corresponding
Weibull AFT model.
Parameters
----------
theta : ndarray, list, vector
theta consists of t values. The initial values should consist of the same number of elements as provided in the
``times`` argument.
times : int, float, ndarray, list, vector
A single time or 1-dimensional collection of times to calculate the measure at. The number of provided times
should consist of the same number of elements as provided in the ``theta`` argument.
X : ndarray, list, vector
2-dimensional vector of n observed values for b variables. No missing data should be included (missing data
may cause unexpected behavior).
measure : str
Measure to calculate. Options include survival (``'survival'``), density (``'density'``), risk or the cumulative
density (``'risk'``), hazard (``'hazard'``), or cumulative hazard (``'cumulative_hazard'``).
mu : float, int
The estimated scale parameter from the Weibull AFT. From ``ee_aft_weibull``, will be the first element.
beta :
The estimated scale coefficients from the Weibull AFT. From ``ee_aft_weibull``, will be the middle element(s).
sigma :
The estimated shape parameter from the Weibull AFT. From ``ee_aft_weibull``, will be the last element.
Returns
-------
array :
Returns a t-by-n NumPy array evaluated for the input theta
Examples
--------
Construction of a estimating equations for :math:`S(t=5)` with ``ee_aft_weibull_measure`` should be done similar to
the following
>>> import numpy as np
>>> import pandas as pd
>>> from delicatessen import MEstimator
>>> from delicatessen.estimating_equations import ee_aft_weibull, ee_aft_weibull_measure
For demonstration, we will generated generic survival data
>>> n = 100
>>> data = pd.DataFrame()
>>> data['X'] = np.random.binomial(n=1, p=0.5, size=n)
>>> data['W'] = np.random.binomial(n=1, p=0.5, size=n)
>>> data['T'] = (1/1.25 + 1/np.exp(0.5)*data['X'])*np.random.weibull(a=0.75, size=n)
>>> data['C'] = np.random.weibull(a=1, size=n)
>>> data['C'] = np.where(data['C'] > 10, 10, data['C'])
>>> data['delta'] = np.where(data['T'] < data['C'], 1, 0)
>>> data['t'] = np.where(data['delta'] == 1, data['T'], data['C'])
>>> d_obs = data[['X', 'W', 't', 'delta']].copy()
Our interest will be in the survival among those with :math:`X=1,W=1`. Therefore, we will generate a copy of the
data and set the values in that copy (to keep the dimension the same across both estimating equations).
>>> d_coef = d_obs.copy()
>>> d_coef['X'] = 1
>>> d_coef['W'] = 1
Defining psi, or the stacked estimating equations
>>> def psi(theta):
>>> aft = ee_aft_weibull(theta=theta[0:4],
>>> t=d_obs['t'], delta=d_obs['delta'], X=d_obs[['X', 'W']])
>>> pred_surv_t = ee_aft_weibull_measure(theta=theta[4], X=d_coef[['X', 'W']],
>>> times=5, measure='survival',
>>> mu=theta[0], beta=theta[1:3], sigma=theta[3])
>>> return np.vstack((aft, pred_surv_t))
Calling the M-estimation procedure (note that `init` has 2+2+1 values now, since ``X.shape[1] = 2`` and we are
calculating the survival at time 5).
>>> estr = MEstimator(stacked_equations=psi, init=[0., 0., 0., 0., 0.5])
>>> estr.estimate(solver='lm')
Inspecting the estimate, variance, and confidence intervals for :math:`S(t=5)`
>>> estr.theta[-1] # \hat{S}(t)
>>> estr.variance[-1, -1] # \hat{Var}(\hat{S}(t))
>>> estr.confidence_intervals()[-1, :] # 95% CI for S(t)
Next, we will consider evaluating the survival function at multiple time points (so we can easily create a plot of
the survival function and the corresponding confidence intervals)
Note
----
When calculate the survival (or other measures) at many time points, it is generally best to optimize the Weibull
AFT coefficients in a separate model, then use the pre-washed coefficients in another M-estimator with the many
time points. This helps the optimizer to converge faster in number of iterations and total run-time.
To make everything easier, we will generate a list of uniformly spaced values between the start and end points of
our desired survival function. We will also generate initial values of the same length (to help the optimizer, we
also start our starting values from near one and end near zero).
>>> resolution = 50
>>> time_spacing = list(np.linspace(0.01, 8, resolution))
>>> fast_inits = list(np.linspace(0.99, 0.01, resolution))
Defining psi, or the stacked estimating equations
>>> def psi(theta):
>>> aft = ee_aft_weibull(theta=theta[0:4],
>>> t=d_obs['t'], delta=d_obs['delta'], X=d_obs[['X', 'W']])
>>> pred_surv_t = ee_aft_weibull_measure(theta=theta[4:], X=d_coef[['X', 'W']],
>>> times=time_spacing, measure='survival',
>>> mu=theta[0], beta=theta[1:3], sigma=theta[3])
>>> return np.vstack((aft, pred_surv_t))
Calling the M-estimation procedure. As stated in the note above, we use the pre-washed covariates to help the
optimizer (since the resolution means we are estimating 50 different parameters).
>>> estr = MEstimator(psi, init=list(estr.theta[0:4]) + fast_inits)
>>> estr.estimate(solver="lm")
To plot the survival curves, we could do the following:
>>> import matplotlib.pyplot as plt
>>> ci = estr.confidence_intervals()[4:, :] # Extracting relevant CI
>>> plt.fill_between(time_spacing, ci[:, 0], ci[:, 1], alpha=0.2)
>>> plt.plot(time_spacing, estr.theta[4:], '-')
>>> plt.show()
References
----------
Collett D. (2015). Accelerated failure time and other parametric models. In: Modelling survival data in medical
research. CRC press. pg171-220
"""
X = np.asarray(X) # Convert to NumPy array
# Extract coefficients
gamma = np.exp(sigma) # exponential to convert to regular sigma
beta = np.asarray(beta)[:, None] # Pulling out the coefficients
lambd = np.exp(-1 * (mu + np.dot(X, beta)) * gamma) # Calculating lambda
def calculate_metric(time, theta_t):
# Intermediate calculations
survival_t = np.exp(-1 * lambd * time**gamma) # Survival calculation from parameters
hazard_t = lambd * gamma * time**(gamma-1) # hazard calculation from parameters
# Calculating specific measures
if measure == "survival":
metric = survival_t # S(t) = S(t)
elif measure == "risk":
metric = 1 - survival_t # F(t) = 1 - S(t)
elif measure == "cumulative_hazard":
metric = -1 * np.log(survival_t) # H(t) = -log(S(t))
elif measure == "hazard":
metric = hazard_t # h(t) = h(t)
elif measure == "density":
metric = hazard_t * survival_t # f(t) = h(t) * S(t)
else:
raise ValueError("The measure '"
+ str(measure)
+ "' is not supported. Please select one of the following: "
"survival, density, risk, hazard, cumulative_hazard.")
return (metric - theta_t).T # Calculate difference from theta, and do transpose for vstack
# Logic to allow for either a single time or multiple times
if type(times) is int or type(times) is float: # For single time,
return calculate_metric(time=times, theta_t=theta) # ... calculate the transformation and return
else: # For multiple time points,
if len(theta) != len(times): # ... check length is the same (to prevent errors)
raise ValueError("There is a mismatch between the number of "
"`theta`'s and the number of `times` provided.")
stacked_time_evals = [] # ... empty list for stacking the equations
for t, thet in zip(times, theta): # ... loop through each theta and each time
metric_t = calculate_metric(time=t, theta_t=thet) # ... ... calculate the transformation
stacked_time_evals.append(metric_t) # ... ... stack transformation into storage
return np.vstack(stacked_time_evals) # ... return a vstack of the equations
| 46.7746 | 120 | 0.612974 | 5,527 | 40,881 | 4.470599 | 0.08178 | 0.003561 | 0.012384 | 0.00777 | 0.841232 | 0.815573 | 0.808855 | 0.802744 | 0.788053 | 0.779756 | 0 | 0.012994 | 0.265796 | 40,881 | 873 | 121 | 46.828179 | 0.810228 | 0.798342 | 0 | 0.539823 | 0 | 0 | 0.084164 | 0 | 0 | 0 | 0 | 0.001145 | 0 | 1 | 0.070796 | false | 0 | 0.00885 | 0 | 0.168142 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
779030616413339b7a01ccde7a09be4767592052 | 2,199 | py | Python | cogs/messages.py | nihaals/DabbitPrimeBot | a7c0e906a9065e3de7665a5f050c43e2cc11259d | [
"MIT"
] | null | null | null | cogs/messages.py | nihaals/DabbitPrimeBot | a7c0e906a9065e3de7665a5f050c43e2cc11259d | [
"MIT"
] | null | null | null | cogs/messages.py | nihaals/DabbitPrimeBot | a7c0e906a9065e3de7665a5f050c43e2cc11259d | [
"MIT"
] | 1 | 2019-12-19T04:14:22.000Z | 2019-12-19T04:14:22.000Z | from discord.ext import commands
import discord
class Messages():
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["recents", "last"], no_pm=True)
async def recent(self, ctx, user: discord.Member = None, channel: discord.TextChannel = None):
"""Quotes a user's most recent message in the channel given."""
if not channel:
channel = ctx.message.channel
if not user:
user = ctx.message.author
quote = None
async for message in channel.history(before=ctx.message, limit=100):
if message.author == user:
quote = message
embed = discord.Embed(description=quote.content)
embed.set_author(name=quote.author.name, icon_url=quote.author.avatar_url)
embed.set_footer(text=(quote.created_at))
await ctx.message.delete()
await ctx.send(embed=embed)
return
if not quote:
continue
embed = discord.Embed(description="No message found")
await ctx.send(embed=embed)
await ctx.message.delete()
return
@commands.command(enabled=False, hidden=True)
async def quote(self, ctx, channel: discord.TextChannel = None, id = None):
"""Quotes a user's message in the channel given."""
if not channel:
channel = ctx.message.channel
quote = None
async for message in channel.history(before=ctx.message, limit=100):
if message.author == user:
quote = message
embed = discord.Embed(description=quote.content)
embed.set_author(name=quote.author.name, icon_url=quote.author.avatar_url)
embed.set_footer(text=(quote.created_at))
await ctx.message.delete()
await ctx.send(embed=embed)
return
if not quote:
continue
embed = discord.Embed(description="No message found")
await ctx.send(embed=embed)
await ctx.message.delete()
return
def setup(bot):
bot.add_cog(Messages(bot)) | 39.981818 | 98 | 0.582992 | 255 | 2,199 | 4.964706 | 0.266667 | 0.07109 | 0.053712 | 0.088468 | 0.728278 | 0.703002 | 0.703002 | 0.703002 | 0.703002 | 0.703002 | 0 | 0.004019 | 0.321055 | 2,199 | 55 | 99 | 39.981818 | 0.843938 | 0 | 0 | 0.734694 | 0 | 0 | 0.020614 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.040816 | false | 0 | 0.040816 | 0 | 0.183673 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
bb38e852b0f84cca940780bdafe71e6d9bab8034 | 4,127 | py | Python | tests/test_interpreter.py | martinbagic/aegis-exercise | 2bef0828dea456f2f66c9288daf095e4dceca40c | [
"MIT"
] | 1 | 2020-03-01T18:47:09.000Z | 2020-03-01T18:47:09.000Z | tests/test_interpreter.py | valenzano-lab/aegis | 30685d44b90f5d3c35a7a2b5d2202809eca59f2a | [
"MIT"
] | null | null | null | tests/test_interpreter.py | valenzano-lab/aegis | 30685d44b90f5d3c35a7a2b5d2202809eca59f2a | [
"MIT"
] | 3 | 2020-03-03T11:59:00.000Z | 2021-07-18T10:14:47.000Z | import pytest
import numpy as np
from aegis.modules.interpreter import Interpreter
e = Interpreter.exp_base
be = Interpreter.binary_exp_base
@pytest.mark.parametrize(
"BITS_PER_LOCUS,loci,expected",
[
# 1 individual 3 loci
(4, [[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]], [[0, 1 / 15, 2 / 15]]),
# 2 individuals 1 locus
(4, [[[0, 1, 0, 0]], [[1, 1, 1, 0]]], [[4 / 15], [14 / 15]]),
# 1 individual 1 locus
(4, [[[1, 0, 0, 0]]], 8 / 15),
(4, [[[1, 0, 0, 1]]], 9 / 15),
(4, [[[1, 0, 1, 0]]], 10 / 15),
(4, [[[1, 1, 0, 0]]], 12 / 15),
(4, [[[1, 1, 1, 1]]], 1),
(5, [[[0, 0, 0, 0, 0]]], 0),
(5, [[[0, 0, 0, 0, 1]]], 1 / 31),
(5, [[[0, 0, 0, 1, 0]]], 2 / 31),
(5, [[[0, 0, 1, 0, 0]]], 4 / 31),
(5, [[[0, 1, 0, 0, 0]]], 8 / 31),
(5, [[[1, 0, 0, 0, 0]]], 16 / 31),
(5, [[[1, 0, 0, 0, 1]]], 17 / 31),
(5, [[[1, 1, 1, 1, 1]]], 1),
],
)
def test_binary(BITS_PER_LOCUS, loci, expected):
interpreter = Interpreter(BITS_PER_LOCUS)
result = interpreter._binary(np.array(loci))
assert (expected == result).all()
@pytest.mark.parametrize(
"BITS_PER_LOCUS,loci,expected",
[
# 1 individual 3 loci
(4, [[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1]]], [[0, 0, 1 / 7]]),
# 2 individuals 1 locus
(4, [[[0, 1, 0, 1]], [[1, 1, 0, 1]]], [[2 / 7], [6 / 7]]),
# 1 individual 1 locus
(4, [[[0, 0, 0, 0]]], 0),
(4, [[[0, 1, 1, 0]]], 0),
(4, [[[0, 1, 1, 1]]], 3 / 7),
(4, [[[1, 0, 0, 0]]], 0),
(4, [[[1, 0, 0, 1]]], 4 / 7),
],
)
def test_binary_switch(BITS_PER_LOCUS, loci, expected):
interpreter = Interpreter(BITS_PER_LOCUS)
result = interpreter._binary_switch(np.array(loci))
assert (expected == result).all()
@pytest.mark.parametrize(
"BITS_PER_LOCUS,loci,expected",
[
# 1 individual 3 loci
(4, [[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1]]], [[0, 1 / 4, 2 / 4]]),
# 2 individuals 1 locus
(4, [[[0, 1, 0, 1]], [[1, 1, 0, 1]]], [[2 / 4], [3 / 4]]),
# 1 individual 1 locus
(4, [[[0, 0, 0, 0]]], 0),
(4, [[[0, 1, 1, 0]]], 2 / 4),
(4, [[[0, 1, 1, 1]]], 3 / 4),
(4, [[[1, 0, 0, 0]]], 1 / 4),
(4, [[[1, 0, 0, 1]]], 2 / 4),
],
)
def test_uniform(BITS_PER_LOCUS, loci, expected):
interpreter = Interpreter(BITS_PER_LOCUS)
result = interpreter._uniform(np.array(loci))
assert (expected == result).all()
@pytest.mark.parametrize(
"BITS_PER_LOCUS,loci,expected",
[
# 1 individual 3 loci
(
4,
[[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1]]],
[[e ** 4, e ** 3, e ** 2]],
),
# 2 individuals 1 locus
(4, [[[0, 1, 0, 1]], [[1, 1, 0, 1]]], [[e ** 2], [e ** 1]]),
# 1 individual 1 locus
(4, [[[0, 0, 0, 0]]], e ** 4),
(4, [[[0, 1, 1, 0]]], e ** 2),
(4, [[[0, 1, 1, 1]]], e ** 1),
(4, [[[1, 0, 0, 0]]], e ** 3),
(4, [[[1, 0, 0, 1]]], e ** 2),
],
)
def test_exp(BITS_PER_LOCUS, loci, expected):
interpreter = Interpreter(BITS_PER_LOCUS)
result = interpreter._exp(np.array(loci))
assert (expected == result).all()
@pytest.mark.parametrize(
"BITS_PER_LOCUS,loci,expected",
[
# 1 individual 3 loci
(
4,
[[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1]]],
[[be ** 0, be ** (1 / 15), be ** (3 / 15)]],
),
# 2 individuals 1 locus
(4, [[[0, 1, 0, 1]], [[1, 1, 0, 1]]], [[be ** (5 / 15)], [be ** (13 / 15)]]),
# 1 individual 1 locus
(4, [[[0, 0, 0, 0]]], be ** (0 / 15)),
(4, [[[0, 1, 1, 0]]], be ** (6 / 15)),
(4, [[[0, 1, 1, 1]]], be ** (7 / 15)),
(4, [[[1, 0, 0, 0]]], be ** (8 / 15)),
(4, [[[1, 0, 0, 1]]], be ** (9 / 15)),
],
)
def test_binary_exp(BITS_PER_LOCUS, loci, expected):
interpreter = Interpreter(BITS_PER_LOCUS)
result = interpreter._binary_exp(np.array(loci))
assert (expected == result).all()
| 31.992248 | 85 | 0.419918 | 637 | 4,127 | 2.646782 | 0.076923 | 0.105575 | 0.092527 | 0.075919 | 0.811388 | 0.746738 | 0.710558 | 0.701068 | 0.677343 | 0.635824 | 0 | 0.155714 | 0.321541 | 4,127 | 128 | 86 | 32.242188 | 0.446429 | 0.076084 | 0 | 0.326733 | 0 | 0 | 0.036871 | 0.036871 | 0 | 0 | 0 | 0 | 0.049505 | 1 | 0.049505 | false | 0 | 0.029703 | 0 | 0.079208 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
bb5620273bb480a16509560dd4dbdc90bd70bb3b | 14,908 | py | Python | explore/circadian-efficacy/src/calculate_edge_circa_score.py | dhimmel/hetmech | 4c7dc77054a02d7da4c30c2a9b0eca391cf5b6b5 | [
"BSD-3-Clause"
] | 10 | 2017-08-20T17:12:57.000Z | 2019-03-26T21:42:28.000Z | explore/circadian-efficacy/src/calculate_edge_circa_score.py | greenelab/hetmech | ca460f70a247ef456c930c7e64df24f59dc2b338 | [
"BSD-3-Clause"
] | 121 | 2017-03-16T19:20:31.000Z | 2021-01-21T16:15:55.000Z | explore/circadian-efficacy/src/calculate_edge_circa_score.py | dhimmel/hetmech | 4c7dc77054a02d7da4c30c2a9b0eca391cf5b6b5 | [
"BSD-3-Clause"
] | 7 | 2017-03-27T23:02:11.000Z | 2019-03-27T15:47:52.000Z | # created by Yun Hao @GreeneLab2019
#!/usr/bin/env python
import numpy as np
import pandas as pd
import requests
## This function calculates the edge circadian score of a drug-disease pair without returning the score details of each path. It is faster, and requires less memory
def calculate_edge_circa_score(query_drug, query_disease, query_tissue, circa_df, query_metapath = 'database', min_path_count = 1, amp_threshold = 0.1, fdr_threshold = 0.05):
'''
--Input
query_drug: drugbank ID
query_disease: disease ontology ID
query_tissue: list of tissue name (must match names used in CircaDB)
circa_df: dataframe that contains CircaDB data ('data/circa_db_mapped.tsv')
query_metapath: list of metapaths that will be included in the calculation (default only includes all metapaths)
min_path_len: minimum number of paths bewteen query drug and query disease needed to generate a non-negative score (default 5)
amp_threshold: amplitude threshold to define circadian gene (default 0.1)
fdr_threshold: FDR threshold to define circadian gene (default 0.05)
-- Output:
list: Edge circadian score
String: reason why score cannot be calculated for query drug-disease pair (if any)
float: number of metapaths that contain gene
float: number of paths that contain gene in CircaDB
'''
# number of query tissues
tissue_len = len(query_tissue)
# get hetionet ID of the drug and the disease
drug_search = requests.get('https://search-api.het.io/v1/nodes/?search=' + query_drug).json()
disease_search = requests.get('https://search-api.het.io/v1/nodes/?search=' + query_disease).json()
# check whether the drug and the disease are in hetionet
if len(drug_search['results']) == 0 and len(disease_search['results']) == 0:
circa_edge_ratio = np.tile(float('nan'), tissue_len)
total_meta_count = total_path_count = float('nan')
note = 'query drug and disease not in hetionet'
elif len(drug_search['results']) == 0:
circa_edge_ratio = np.tile(float('nan'), tissue_len)
total_meta_count = total_path_count = float('nan')
note = 'query drug not in hetionet'
elif len(disease_search['results']) == 0:
circa_edge_ratio = np.tile(float('nan'), tissue_len)
total_meta_count = total_path_count = float('nan')
note = 'query disease not in hetionet'
else:
# get drug ID, disease ID, metapath ID
drug_id = drug_search['results'][0]['id']
disease_id = disease_search['results'][0]['id']
gene_metapath = []
# use metapaths in the database (sparse)
if query_metapath == 'database':
# get metapaths that connect the drug and the disease
meta_search = requests.get('http://search-api.het.io/v1/query-metapaths/?source=' + str(drug_id) + '&target=' + str(disease_id)).json()
if len(meta_search['path_counts']) > 0:
for i in range(0, len(meta_search['path_counts'])):
i_metapath = meta_search['path_counts'][i]['metapath_abbreviation']
if 'G' in i_metapath:
gene_metapath.append(i_metapath)
# use pre-defined metapaths
else:
for i in range(0, len(query_metapath)):
if 'G' in query_metapath[i]:
gene_metapath.append(query_metapath[i])
# check whether drug and disease are connected by genes in hetionet
if len(gene_metapath) == 0:
circa_edge_ratio = np.tile(float('nan'), tissue_len)
total_meta_count = total_path_count = float('nan')
note = 'query drug and disease not connected by genes in hetionet'
else:
total_edge_score = np.zeros(tissue_len)
circa_edge_score = np.zeros(tissue_len)
total_meta_count = 0
total_path_count = 0
query_amp = [x + '_amp' for x in query_tissue]
query_fdr = [x + '_fdr' for x in query_tissue]
for j in range(0, len(gene_metapath)):
path_search = requests.get('http://search-api.het.io/v1/query-paths/?source=' + str(drug_id) + '&target=' + str(disease_id) + '&metapath=' + gene_metapath[j] + '&max-paths=-1').json()
if len(path_search['paths']) == 0:
continue
elif path_search['query']['metapath_adjusted_p_value'] == 1:
continue
else:
total_meta_count = total_meta_count + 1
# get max circadian score of the path
gene_path_loc = [int(index/2) for index, value in enumerate(gene_metapath[j]) if value == 'G']
for k in range(0, len(path_search['paths'])):
# get circadian score of the gene
path_gene_circa_amp = np.zeros(tissue_len)
path_gene_circa_fdr = np.zeros(tissue_len) + 1
path_gene_circa_count = 0
for l in range(0, len(gene_path_loc)):
# get entrez ID of genes in the path
loc_id = gene_path_loc[l]
gene_node_id = path_search['paths'][k]['node_ids'][loc_id]
gene_id = int(path_search['nodes'][str(gene_node_id)]['properties']['identifier'])
gene_circa_amp = circa_df[query_amp][circa_df['gene_id'] == gene_id]
gene_circa_fdr = circa_df[query_fdr][circa_df['gene_id'] == gene_id]
# check whether the gene is in circaDB
if len(gene_circa_amp) == 0:
continue
else:
path_gene_circa_count = path_gene_circa_count + 1
for m in range(0, tissue_len):
tmp_amp = float(gene_circa_amp.iloc[:,m])
if tmp_amp > path_gene_circa_amp[m]:
path_gene_circa_amp[m] = tmp_amp
path_gene_circa_fdr[m] = float(gene_circa_fdr.iloc[:,m])
if path_gene_circa_count > 0:
# get path importance score
total_path_count = total_path_count + 1
path_score = path_search['paths'][k]['score']
total_edge_score = total_edge_score + path_score
# check whether the gene is circadian
for n in range(0, tissue_len):
if path_gene_circa_amp[n] >= amp_threshold and path_gene_circa_fdr[n] < fdr_threshold:
circa_edge_score[n] = circa_edge_score[n] + path_score
# calculate proportion of circadian paths
if total_meta_count == 0:
circa_edge_ratio = np.tile(float('nan'), tissue_len)
total_path_count = float('nan')
note = 'query drug and disease not connected by genes in hetionet'
else:
if total_path_count == 0:
circa_edge_ratio = np.tile(float('nan'), tissue_len)
note = 'query drug and disease connected by genes not in CircaDB'
elif total_path_count < min_path_count:
circa_edge_ratio = np.tile(float('nan'), tissue_len)
note = 'query drug and disease connected by too few paths'
else:
circa_edge_ratio = circa_edge_score/total_edge_score
note = 'NaN'
return circa_edge_ratio, note, total_meta_count, total_path_count
## This function calculates the edge circadian score of a drug-disease pair, and then return the score details of each path. It is slower, and requires more memory
def detail_edge_circa_score(query_drug, query_disease, query_tissue, circa_df, query_metapath = 'database', min_path_count = 1, amp_threshold = 0.1, fdr_threshold = 0.05):
'''
--Input
query_drug: drugbank ID
query_disease: disease ontology ID
query_tissue: list of tissue name (must match names used in CircaDB)
circa_df: dataframe that contains CircaDB data ('data/circa_db_mapped.tsv')
query_metapath: list of metapaths that will be included in the calculation (default only includes all metapaths)
min_path_len: minimum number of paths bewteen query drug and query disease needed to generate a non-negative score (default 5)
amp_threshold: amplitude threshold to define circadian gene (default 0.1)
fdr_threshold: FDR threshold to define circadian gene (default 0.05)
-- Output
dictionary contains the following item:
edge_circa_score
total_meta_count: number of metapaths that contain gene
total_path_count: number of paths that contain gene in CircaDB
note: reason why score cannot be calculated for query drug-disease pair (if any)
score_details: a dataframe that contains score details of each path
'''
# number of query tissues
tissue_len = len(query_tissue)
# get hetionet ID of the drug and the disease
drug_search = requests.get('https://search-api.het.io/v1/nodes/?search=' + query_drug).json()
disease_search = requests.get('https://search-api.het.io/v1/nodes/?search=' + query_disease).json()
null_output = {'edge_circa_score': dict((query_tissue[x], float('nan')) for x in range(0, len(query_tissue))),
'total_meta_count': float('nan'),
'total_path_count': float('nan'),
'note': 'NaN',
'score_details': 'NaN'
}
# check whether the drug and the disease are in hetionet
if len(drug_search['results']) == 0 and len(disease_search['results']) == 0:
output = null_output
output['note'] = 'query drug and disease not in hetionet'
elif len(drug_search['results']) == 0:
output = null_output
output['note'] = 'query drug not in hetionet'
elif len(disease_search['results']) == 0:
output = null_output
output['note'] = 'query disease not in hetionet'
else:
# get drug ID, disease ID, metapath ID
drug_id = drug_search['results'][0]['id']
disease_id = disease_search['results'][0]['id']
gene_metapath = []
# use metapaths in the database (sparse)
if query_metapath == 'database':
# get metapaths that connect the drug and the disease
meta_search = requests.get('http://search-api.het.io/v1/query-metapaths/?source=' + str(drug_id) + '&target=' + str(disease_id)).json()
if len(meta_search['path_counts']) > 0:
for i in range(0, len(meta_search['path_counts'])):
i_metapath = meta_search['path_counts'][i]['metapath_abbreviation']
if 'G' in i_metapath:
gene_metapath.append(i_metapath)
# use pre-defined metapaths
else:
for i in range(0, len(query_metapath)):
if 'G' in query_metapath[i]:
gene_metapath.append(query_metapath[i])
# check whether drug and disease are connected by genes in hetionet
if len(gene_metapath) == 0:
output = null_output
output['note'] = 'query drug and disease not connected by genes in hetionet'
else:
total_edge_score = np.zeros(tissue_len)
circa_edge_score = np.zeros(tissue_len)
total_meta_count = 0
total_path_count = 0
score_details = []
query_amp = [x + '_amp' for x in query_tissue]
query_fdr = [x + '_fdr' for x in query_tissue]
for j in range(0, len(gene_metapath)):
path_search = requests.get('http://search-api.het.io/v1/query-paths/?source=' + str(drug_id) + '&target=' + str(disease_id) + '&metapath=' + gene_metapath[j] + '&max-paths=-1').json()
if len(path_search['paths']) == 0:
continue
elif path_search['query']['metapath_adjusted_p_value'] == 1:
continue
else:
total_meta_count = total_meta_count + 1
# get max circadian score of the path
gene_path_loc = [int(index/2) for index, value in enumerate(gene_metapath[j]) if value == 'G']
for k in range(0, len(path_search['paths'])):
# get circadian score of the gene
path_gene_circa_amp = np.zeros(tissue_len)
path_gene_circa_fdr = np.zeros(tissue_len) + 1
path_gene_circa_count = 0
path_gene_name = []
for l in range(0, len(gene_path_loc)):
# get entrez ID of genes in the path
loc_id = gene_path_loc[l]
gene_node_id = path_search['paths'][k]['node_ids'][loc_id]
gene_id = int(path_search['nodes'][str(gene_node_id)]['properties']['identifier'])
gene_name = path_search['nodes'][str(gene_node_id)]['properties']['name']
path_gene_name.append(gene_name)
gene_circa_amp = circa_df[query_amp][circa_df['gene_id'] == gene_id]
gene_circa_fdr = circa_df[query_fdr][circa_df['gene_id'] == gene_id]
# check whether the gene is in circaDB
if len(gene_circa_amp) == 0:
continue
else:
path_gene_circa_count = path_gene_circa_count + 1
for m in range(0, tissue_len):
tmp_amp = float(gene_circa_amp.iloc[:,m])
if tmp_amp > path_gene_circa_amp[m]:
tmp_tissue = query_tissue[m]
path_gene_circa_amp[m] = tmp_amp
path_gene_circa_fdr[m] = float(gene_circa_fdr.iloc[:,m])
circa_tissues = []
non_circa_tissues = []
if path_gene_circa_count > 0:
gene_in_circa = True
# get path importance score
total_path_count = total_path_count + 1
path_score = path_search['paths'][k]['score']
total_edge_score = total_edge_score + path_score
# check whether the gene is circadian
for n in range(0, tissue_len):
if path_gene_circa_amp[n] >= amp_threshold and path_gene_circa_fdr[n] < fdr_threshold:
circa_edge_score[n] = circa_edge_score[n] + path_score
circa_tissues.append(query_tissue[n])
else:
non_circa_tissues.append(query_tissue[n])
else:
gene_in_circa = False
circa_tissues = non_circa_tissues = ['NaN']
# fill in score details
node_ids = path_search['paths'][k]['node_ids']
node_names = []
for ni in node_ids:
ni_name = str(path_search['nodes'][str(ni)]['properties']['name'])
node_names.append(ni_name)
rel_ids = path_search['paths'][k]['rel_ids']
rel_types = []
for ri in rel_ids:
ri_name = str(path_search['relationships'][str(ri)]['rel_type'])
rel_types.append(ri_name)
path_details = {'source_node': node_names[0],
'target_node': node_names[-1],
'metapath': gene_metapath[j],
'node_ids': ','.join([str(x) for x in node_ids]),
'node_names': ','.join(node_names),
'rel_ids': ','.join([str(x) for x in rel_ids]),
'rel_names': ','.join(rel_types),
'gene_symbol': ','.join(str(x) for x in path_gene_name),
'whether_in_circadb': gene_in_circa,
'circadian_tissue': ','.join(circa_tissues),
'non_circadian_tissue': ','.join(non_circa_tissues),
'importance_score': path_search['paths'][k]['score']
}
score_details.append(path_details)
# calculate proportion of circadian paths
output = null_output
output['total_meta_count'] = total_meta_count
output['total_path_count'] = total_path_count
if total_meta_count == 0:
output['note'] = 'query drug and disease not connected by genes in hetionet'
else:
if total_path_count == 0:
output['note'] = 'query drug and disease connected by genes not in CircaDB'
elif total_path_count < min_path_count:
output['note'] = 'query drug and disease connected by too few paths'
else:
edge_circa_score = circa_edge_score/total_edge_score
output['edge_circa_score'] = dict((query_tissue[x], edge_circa_score[x]) for x in range(0, len(query_tissue)))
detail_df = pd.DataFrame(score_details)
detail_cols = ['source_node','target_node','metapath','node_ids','node_names','rel_ids','rel_names','gene_symbol','whether_in_circadb','circadian_tissue','non_circadian_tissue','importance_score']
output['score_details'] = detail_df[detail_cols]
return output
| 43.847059 | 201 | 0.689361 | 2,246 | 14,908 | 4.32057 | 0.089047 | 0.029678 | 0.029472 | 0.013603 | 0.863561 | 0.843982 | 0.809151 | 0.79864 | 0.766488 | 0.766488 | 0 | 0.008353 | 0.196941 | 14,908 | 339 | 202 | 43.976401 | 0.802205 | 0.225852 | 0 | 0.69869 | 0 | 0 | 0.185711 | 0.008006 | 0 | 0 | 0 | 0 | 0 | 1 | 0.008734 | false | 0 | 0.021834 | 0 | 0.039301 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
701cc2d5e3b618fb1973006806e81f9cff46f2bf | 17,713 | py | Python | drf_auth/tests/api_views_tests.py | TheArtling/django-drf-auth | 732183fae6cb129a1bf5c0c619fbd76e366ab392 | [
"MIT"
] | null | null | null | drf_auth/tests/api_views_tests.py | TheArtling/django-drf-auth | 732183fae6cb129a1bf5c0c619fbd76e366ab392 | [
"MIT"
] | null | null | null | drf_auth/tests/api_views_tests.py | TheArtling/django-drf-auth | 732183fae6cb129a1bf5c0c619fbd76e366ab392 | [
"MIT"
] | null | null | null | """Tests for the API views of the drf_auth app."""
import json
from django.contrib.auth.models import AnonymousUser
from django.test import TestCase
from mixer.backend.django import mixer
from mock import MagicMock, patch
from rest_framework.test import APIRequestFactory, force_authenticate
from .. import api_views
from .. import exceptions
from .. import models
class FacebookLoginAPIViewTestCase(TestCase):
longMessage = True
def test_cancel_facebook_login(self):
req = APIRequestFactory().post('/', data={})
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'Should return 400 if no data is given (i.e. login was'
' cancelled).'))
@patch('drf_auth.api_views.get_app_access_token')
def test_bad_settings(self, get_app_access_token_mock):
"""
Should raise exception when we cannot get an app access token.
This is our fault (bad settings), so we don't show an error to the
user, we raise an exception and get a notification email and fix the
settings on the server.
"""
mock_resp = MagicMock()
mock_resp.status_code = 400
get_app_access_token_mock.return_value = mock_resp
req = APIRequestFactory().post('/', data={'fake': 'data'})
self.assertRaises(
exceptions.AccessTokenException,
api_views.FacebookLoginAPIView().as_view(),
req, version='v1'
)
@patch('drf_auth.api_views.get_app_access_token')
def test_facebook_api_down(self, get_app_access_token_mock):
mock_resp = MagicMock()
mock_resp.status_code = 500
get_app_access_token_mock.return_value = mock_resp
req = APIRequestFactory().post('/', data={'fake': 'data'})
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'If Facebook returned not 200 and not 400, something is wrong'
' with their API and we should return 400 and show an error'
' message to the user (i.e. `Please try again later`).'))
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_debug_token_not_valid(self, get_app_access_token_mock,
get_debug_token_mock):
mock_resp = MagicMock()
mock_resp.status_code = 200
get_app_access_token_mock.return_value = mock_resp
mock_resp2 = MagicMock()
mock_resp2.status_code = 400
get_debug_token_mock.return_value = mock_resp2
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'If Facebook returned anything other than 200, something is either'
' wrong with their API or the user has submitted a wrong access'
' (probably an attacker). We should return 400 and show an error'
' message to the user (i.e. `Please try again again or contact'
' us`).'))
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_user_data_not_acessible(self, get_app_access_token_mock,
get_debug_token_mock, get_user_data_mock):
mock_resp = MagicMock()
mock_resp.status_code = 200
get_app_access_token_mock.return_value = mock_resp
mock_resp2 = MagicMock()
mock_resp2.status_code = 200
mock_resp2.content = json.dumps({'data': {'user_id': '123'}})
get_debug_token_mock.return_value = mock_resp2
mock_resp3 = MagicMock()
mock_resp3.status_code = 400
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'If Facebook returned anything other than 200, something is'
' wrong with their API. We should return 400 and show an error'
' message to the user (i.e. `Please try again again or contact'
' us`).'))
def _create_mocks(self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, facebook_email):
mock_resp = MagicMock()
mock_resp.status_code = 200
get_app_access_token_mock.return_value = mock_resp
mock_resp2 = MagicMock()
mock_resp2.status_code = 200
mock_resp2.content = json.dumps({'data': {'user_id': '123'}})
get_debug_token_mock.return_value = mock_resp2
mock_resp3 = MagicMock()
mock_resp3.status_code = 200
if facebook_email is None:
mock_resp3.content = json.dumps({})
else:
mock_resp3.content = json.dumps({'email': facebook_email})
get_user_data_mock.return_value = mock_resp3
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_django_user_with_fb_email_already_exists(
self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock):
user = mixer.blend('auth.User', email='fb@example.com')
self._create_mocks(
get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, user.email)
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'If we already have a user with email `fb@example.com` and'
' Facebook returns that same email to us, then we shall show an'
' error message and ask the user to login to his existing account'
' and connect to Facebook from there.'))
self.assertTrue(
'You have already created an account' in resp.data[
'non_field_errors'][0])
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_case1_disconnect_user(
self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock):
user = mixer.blend('auth.User', email='user@example.com')
mixer.blend('drf_auth.Facebook', user=user, facebook_user_id='123')
self._create_mocks(
get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, 'user@example.com')
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
force_authenticate(req, user)
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 200, msg=(
'If the user is logged in and triggers the Facebook connect and'
' they are already connected, then we delete the Facebook'
' connection'))
self.assertEqual(resp.data, 'Facebook connection deleted')
fb_user = models.Facebook.objects.all()
self.assertEqual(fb_user.count(), 0)
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_case2_authed_user_already_connected_with_other_account(
self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock):
user = mixer.blend('auth.User', email='user@example.com')
user2 = mixer.blend('auth.User', email='user2@example.com')
mixer.blend('drf_auth.Facebook', user=user2, facebook_user_id='123')
self._create_mocks(
get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, 'user@example.com')
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
force_authenticate(req, user)
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'If the user is logged in and triggers the Facebook connect and'
' they are already connected with another Django account, then we'
' show an error and ask to disconnect the other account, first.'))
self.assertTrue(
'You have already connected' in resp.data['non_field_errors'][0])
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_case3_login_existing_facebook_user(
self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock):
user = mixer.blend('auth.User', email='user@example.com')
mixer.blend('drf_auth.Facebook', user=user, facebook_user_id='123')
self._create_mocks(
get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, 'user@example.com')
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
req.user = AnonymousUser()
req.session = self.client.session
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 200, msg=(
'If the user logs in with Facebook and has done it before, they'
' should be logged in'))
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_case4_new_facebook_user_but_email_already_exists(
self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock):
mixer.blend('auth.User', email='fb@example.com')
self._create_mocks(
get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, 'fb@example.com')
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
req.user = AnonymousUser()
req.session = self.client.session
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'If the user tries to login via Facebook but has already logged'
' in via email before (with the same email they use at Facebook),'
' we need to show an error and ask the user to login via email'
' and then connect to Facebook.'
))
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_case5_new_user_with_facebook_email(
self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock):
self._create_mocks(
get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, 'fb@example.com')
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
req.user = AnonymousUser()
req.session = self.client.session
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 200, msg=(
'Should create new Django & Facebook instance.'))
fb_user = models.Facebook.objects.all()
self.assertEqual(fb_user.count(), 1)
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_case6_new_user_without_facebook_email(
self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock):
self._create_mocks(
get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, None)
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
req.user = AnonymousUser()
req.session = self.client.session
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 200, msg=(
'Should create new Django & Facebook instance.'))
fb_user = models.Facebook.objects.all()
self.assertEqual(fb_user.count(), 1)
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_case7_authed_user_connects_to_facebook(
self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock):
user = mixer.blend('auth.User')
self._create_mocks(
get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, 'fb@example.com')
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
force_authenticate(req, user)
req.session = self.client.session
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 200, msg=(
'Should create new Facebook instance connected to this user.'))
fb_user = models.Facebook.objects.all()
self.assertEqual(fb_user.count(), 1)
self.assertEqual(fb_user[0].user, user)
@patch('drf_auth.api_views.get_user_data')
@patch('drf_auth.api_views.get_debug_token')
@patch('drf_auth.api_views.get_app_access_token')
def test_account_disabled(
self, get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock):
user = mixer.blend(
'auth.User', email='fb@example.com', is_active=False)
mixer.blend('drf_auth.Facebook', user=user, facebook_user_id='123')
self._create_mocks(
get_app_access_token_mock, get_debug_token_mock,
get_user_data_mock, user.email)
data = {'authResponse': {'accessToken': '123'}}
req = APIRequestFactory().post('/', data=data, format='json')
req.user = AnonymousUser()
req.session = self.client.session
resp = api_views.FacebookLoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'Should show error about acount not being active.'))
self.assertTrue(
'Account is disabled' in resp.data['non_field_errors'][0])
class LoginAPIViewTestCase(TestCase):
longMessage = True
def test_view(self):
user = mixer.blend('auth.User', is_active=False)
user.set_password('test')
user.save()
data = {}
req = APIRequestFactory().post('/', data=data)
resp = api_views.LoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'Should return 400 if no data is given'))
data = {'email': user.email, 'password': 'wrong'}
req = APIRequestFactory().post('/', data=data)
resp = api_views.LoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'Should return 400 if wrong password is given'))
data = {'email': user.email, 'password': 'test'}
req = APIRequestFactory().post('/', data=data)
resp = api_views.LoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'Should return 400 if user is inactive'))
user.is_active = True
user.save()
data = {'email': user.email, 'password': 'test'}
req = APIRequestFactory().post('/', data=data)
req.session = self.client.session
resp = api_views.LoginAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 200, msg=(
'Should return 200 if user has logged in'))
class LogoutAPIViewTestCase(TestCase):
longMessage = True
def test_view(self):
user = mixer.blend('auth.User')
req = APIRequestFactory().post('/')
req.session = self.client.session
force_authenticate(req, user)
resp = api_views.LogoutAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 200, msg=(
'Should be callable by anyone'))
class FinishSignupAPIViewTestCase(TestCase):
longMessage = True
def test_view(self):
user = mixer.blend('auth.User', email='')
data = {}
req = APIRequestFactory().post('/', data=data)
force_authenticate(req, user)
resp = api_views.FinishSignupAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 400, msg=(
'Should return 400 if no data is given'))
data = {'email': 'test@example.com'}
req = APIRequestFactory().post('/', data=data)
force_authenticate(req, user)
resp = api_views.FinishSignupAPIView().as_view()(req, version='v1')
self.assertEqual(resp.status_code, 200, msg=(
'Should return 200 if new email could be saved'))
user.refresh_from_db()
self.assertEqual(user.email, 'test@example.com')
| 46.859788 | 79 | 0.653362 | 2,280 | 17,713 | 4.791667 | 0.098684 | 0.041739 | 0.053822 | 0.063799 | 0.806773 | 0.787185 | 0.774462 | 0.763478 | 0.74984 | 0.745812 | 0 | 0.017641 | 0.23192 | 17,713 | 377 | 80 | 46.984085 | 0.785373 | 0.01513 | 0 | 0.692537 | 0 | 0 | 0.244092 | 0.069059 | 0 | 0 | 0 | 0 | 0.092537 | 1 | 0.053731 | false | 0.014925 | 0.026866 | 0 | 0.104478 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
7055fbe2f61f8dfee63144daa54b7f3756278dcc | 120 | py | Python | mlapp/utils/exceptions/user_exceptions.py | kerenleibovich/mlapp | 0b8dfaba7a7070ab68cb29ff61dd1c7dd8076693 | [
"Apache-2.0"
] | 33 | 2021-02-26T10:41:09.000Z | 2021-11-07T12:35:32.000Z | mlapp/utils/exceptions/user_exceptions.py | kerenleibovich/mlapp | 0b8dfaba7a7070ab68cb29ff61dd1c7dd8076693 | [
"Apache-2.0"
] | 17 | 2021-03-04T15:37:21.000Z | 2021-04-06T12:00:13.000Z | mlapp/utils/exceptions/user_exceptions.py | kerenleibovich/mlapp | 0b8dfaba7a7070ab68cb29ff61dd1c7dd8076693 | [
"Apache-2.0"
] | 9 | 2021-03-03T20:02:41.000Z | 2021-10-05T13:03:56.000Z | from mlapp.utils.exceptions.base_exceptions import UserException
class MissingModelException(UserException):
pass
| 20 | 64 | 0.841667 | 12 | 120 | 8.333333 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.108333 | 120 | 5 | 65 | 24 | 0.934579 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
7057a598a58b00c3ad76d5d7d188ad7613941f17 | 41 | py | Python | fastai2/tabular/all.py | bearpelican/fastai2 | 445fa28e42b8d6205adc135527c22883fcfbef41 | [
"Apache-2.0"
] | null | null | null | fastai2/tabular/all.py | bearpelican/fastai2 | 445fa28e42b8d6205adc135527c22883fcfbef41 | [
"Apache-2.0"
] | null | null | null | fastai2/tabular/all.py | bearpelican/fastai2 | 445fa28e42b8d6205adc135527c22883fcfbef41 | [
"Apache-2.0"
] | 1 | 2020-08-20T14:20:47.000Z | 2020-08-20T14:20:47.000Z | from .core import *
from .model import *
| 13.666667 | 20 | 0.707317 | 6 | 41 | 4.833333 | 0.666667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.195122 | 41 | 2 | 21 | 20.5 | 0.878788 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
56174dbb21b162781312d07324fb7e0ab1d66bc3 | 21 | py | Python | Lib/site-packages/pyocr/__init__.py | adzhou/Python27 | a7113b69d54a04cc780143241c2f1fe81939ad3a | [
"bzip2-1.0.6"
] | 1 | 2017-08-07T14:52:02.000Z | 2017-08-07T14:52:02.000Z | Lib/site-packages/pyocr/__init__.py | adzhou/Python27 | a7113b69d54a04cc780143241c2f1fe81939ad3a | [
"bzip2-1.0.6"
] | null | null | null | Lib/site-packages/pyocr/__init__.py | adzhou/Python27 | a7113b69d54a04cc780143241c2f1fe81939ad3a | [
"bzip2-1.0.6"
] | null | null | null | from .pyocr import *
| 10.5 | 20 | 0.714286 | 3 | 21 | 5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.190476 | 21 | 1 | 21 | 21 | 0.882353 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
5621941731ba57d157251b2307d12c8ff2cc7864 | 22,570 | py | Python | test/test_components_repository_repository.py | dmyers87/skelebot | 954552fc5f465eb2a887f5c96a27f11ad423cd71 | [
"MIT"
] | null | null | null | test/test_components_repository_repository.py | dmyers87/skelebot | 954552fc5f465eb2a887f5c96a27f11ad423cd71 | [
"MIT"
] | null | null | null | test/test_components_repository_repository.py | dmyers87/skelebot | 954552fc5f465eb2a887f5c96a27f11ad423cd71 | [
"MIT"
] | null | null | null | from unittest import TestCase, main, mock
from schema import SchemaError
import copy
import argparse
import skelebot as sb
class TestRepository(TestCase):
artifcatory = None
s3 = None
s3_subfolder = None
artifactoryDict = {
"url": "test",
"repo": "test",
"path": "path"
}
s3Dict = {
"bucket": "my-bucket",
"region": "us-east-1",
"profile": "test"
}
artifactDict = {
"name": "test",
"file": "test"
}
def setUp(self):
artifact = sb.components.repository.repository.Artifact("test", "test.pkl")
artifact2 = sb.components.repository.repository.Artifact("test2", "test2.pkl")
artifact3 = sb.components.repository.repository.Artifact("test3", "test3.pkl", singular=True)
artifactoryRepo = sb.components.repository.artifactoryRepo.ArtifactoryRepo("artifactory.test.com", "ml", "test")
s3Repo = sb.components.repository.s3Repo.S3Repo("my-bucket", "us-east-1", "test")
s3Repo_path = sb.components.repository.s3Repo.S3Repo("my-bucket/sub/folder", "us-east-1", "test")
self.artifactory = sb.components.repository.repository.Repository([artifact, artifact2, artifact3], s3=None, artifactory=artifactoryRepo)
self.s3 = sb.components.repository.repository.Repository([artifact, artifact2, artifact3], s3=s3Repo, artifactory=None)
self.s3_subfolder = sb.components.repository.repository.Repository([artifact, artifact3], s3=s3Repo_path, artifactory=None)
def test_repository_load(self):
artifact = sb.components.repository.repository.Artifact("test", "test.pkl")
sb.components.repository.repository.Repository.load({"artifacts": [], "s3": self.s3Dict})
sb.components.repository.repository.Repository.load({"artifacts": [], "artifactory": self.artifactoryDict})
try:
sb.components.repository.repository.Repository.load({"artifacts": []})
self.fail("Exception Not Thrown")
except SchemaError as exc:
self.assertEqual(str(exc), "Repository must contain 's3' or 'artifactory' config")
def test_addParsers_artifactory(self):
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
subparsers = parser.add_subparsers(dest="job")
subparsers = self.artifactory.addParsers(subparsers)
self.assertNotEqual(subparsers.choices["push"], None)
self.assertNotEqual(subparsers.choices["pull"], None)
def test_addParsers_s3(self):
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
subparsers = parser.add_subparsers(dest="job")
subparsers = self.s3.addParsers(subparsers)
self.assertNotEqual(subparsers.choices["push"], None)
self.assertNotEqual(subparsers.choices["pull"], None)
@mock.patch('skelebot.components.repository.artifactoryRepo.input')
@mock.patch('os.rename')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_push_conflict_artifactory(self, mock_artifactory, mock_rename, mock_input):
mock_input.return_value = "abc"
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=False, artifact='test', user=None, token=None)
expectedException = "This artifact version already exists. Please bump the version or use the force parameter (-f) to overwrite the artifact."
try:
self.artifactory.execute(config, args)
self.fail("Exception Not Thrown")
except Exception as exc:
self.assertEqual(str(exc), expectedException)
mock_artifactory.assert_called_with("artifactory.test.com/ml/test/test_v1.0.0.pkl", auth=('abc', 'abc'))
@mock.patch('boto3.Session')
def test_execute_push_conflict_s3(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_client.list_objects_v2.return_value = {"Contents": [{"Key": "test_v1.0.0.pkl"}]}
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=False, artifact='test', user='sean', token='abc123')
expectedException = "This artifact version already exists. Please bump the version or use the force parameter (-f) to overwrite the artifact."
try:
self.s3.execute(config, args)
self.fail("Exception Not Thrown")
except Exception as exc:
self.assertEqual(str(exc), expectedException)
mock_client.list_objects_v2.assert_called_with(Bucket="my-bucket", Prefix="test_v1.0.0.pkl")
@mock.patch('shutil.copyfile')
@mock.patch('os.remove')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_push_error_artifactory(self, mock_artifactory, mock_remove, mock_copy):
mock_path = mock.MagicMock()
mock_path.deploy_file = mock.MagicMock(side_effect=KeyError('foo'))
mock_artifactory.return_value = mock_path
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=True, artifact='test', user='sean', token='abc123')
with self.assertRaises(KeyError):
self.artifactory.execute(config, args)
mock_artifactory.assert_called_with("artifactory.test.com/ml/test/test_v1.0.0.pkl", auth=('sean', 'abc123'))
mock_copy.assert_called_with("test.pkl", "test_v1.0.0.pkl")
mock_remove.assert_called_with("test_v1.0.0.pkl")
@mock.patch('shutil.copyfile')
@mock.patch('os.remove')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_push_artifactory(self, mock_artifactory, mock_remove, mock_copy):
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=True, artifact='test', user='sean', token='abc123')
self.artifactory.execute(config, args)
mock_artifactory.assert_called_with("artifactory.test.com/ml/test/test_v1.0.0.pkl", auth=('sean', 'abc123'))
mock_copy.assert_called_with("test.pkl", "test_v1.0.0.pkl")
mock_remove.assert_called_with("test_v1.0.0.pkl")
@mock.patch('shutil.copyfile')
@mock.patch('os.remove')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_push_artifactory_singular(self, mock_artifactory, mock_remove, mock_copy):
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=True, artifact='test3', user='sean', token='abc123')
self.artifactory.execute(config, args)
mock_artifactory.assert_called_with("artifactory.test.com/ml/test/test3.pkl", auth=('sean', 'abc123'))
mock_copy.assert_called_with("test3.pkl", "test3.pkl")
mock_remove.assert_called_with("test3.pkl")
@mock.patch('boto3.Session')
def test_execute_push_s3(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=True, artifact='test', user='sean', token='abc123')
self.s3.execute(config, args)
mock_client.upload_file.assert_called_with("test.pkl", "my-bucket", "test_v1.0.0.pkl")
@mock.patch('boto3.Session')
def test_execute_push_s3_singular(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=True, artifact='test3', user='sean', token='abc123')
self.s3.execute(config, args)
mock_client.upload_file.assert_called_with("test3.pkl", "my-bucket", "test3.pkl")
@mock.patch('shutil.copyfile')
@mock.patch('os.remove')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_push_artifactory_all(self, mock_artifactory, mock_remove, mock_copy):
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=True, artifact='ALL', user='sean', token='abc123')
self.artifactory.execute(config, args)
mock_artifactory.assert_has_calls([
mock.call("artifactory.test.com/ml/test/test_v1.0.0.pkl", auth=('sean', 'abc123')),
mock.call("artifactory.test.com/ml/test/test2_v1.0.0.pkl", auth=('sean', 'abc123'))
], any_order=True)
mock_copy.assert_has_calls([
mock.call("test.pkl", "test_v1.0.0.pkl"),
mock.call("test2.pkl", "test2_v1.0.0.pkl")
], any_order=True)
mock_remove.assert_has_calls([
mock.call("test_v1.0.0.pkl"),
mock.call("test2_v1.0.0.pkl")
], any_order=True)
@mock.patch('boto3.Session')
def test_execute_push_s3_all(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=True, artifact='ALL', user='sean', token='abc124')
self.s3.execute(config, args)
mock_client.upload_file.assert_has_calls([
mock.call("test.pkl", "my-bucket", "test_v1.0.0.pkl"),
mock.call("test2.pkl", "my-bucket", "test2_v1.0.0.pkl")
], any_order=True)
@mock.patch('boto3.Session')
def test_execute_push_s3_subfolder(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="push", force=True, artifact='test', user='sean', token='abc123')
self.s3_subfolder.execute(config, args)
mock_client.upload_file.assert_called_with("test.pkl", "my-bucket", "sub/folder/test_v1.0.0.pkl")
@mock.patch('skelebot.components.repository.artifactoryRepo.input')
@mock.patch('builtins.open')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_pull_artifactory(self, mock_artifactory, mock_open, mock_input):
mock_input.return_value = "abc"
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="pull", version='0.1.0', artifact='test', user=None, token=None, override=False)
self.artifactory.execute(config, args)
mock_artifactory.assert_called_with("artifactory.test.com/ml/test/test_v0.1.0.pkl", auth=("abc", "abc"))
mock_open.assert_called_with("test_v0.1.0.pkl", "wb")
@mock.patch('skelebot.components.repository.artifactoryRepo.input')
@mock.patch('builtins.open')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_pull_artifactory_singular(self, mock_artifactory, mock_open, mock_input):
mock_input.return_value = "abc"
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="pull", version='0.1.0', artifact='test3', user=None, token=None, override=False)
self.artifactory.execute(config, args)
mock_artifactory.assert_called_with("artifactory.test.com/ml/test/test3.pkl", auth=("abc", "abc"))
mock_open.assert_called_with("test3.pkl", "wb")
@mock.patch('boto3.Session')
def test_execute_pull_s3(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="pull", version='0.1.0', artifact='test', user=None, token=None, override=False)
self.s3.execute(config, args)
mock_client.download_file.assert_called_with("my-bucket", "test_v0.1.0.pkl", "test_v0.1.0.pkl")
@mock.patch('boto3.Session')
def test_execute_pull_s3_subfolder(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="pull", version='0.1.0', artifact='test', user=None, token=None, override=False)
self.s3_subfolder.execute(config, args)
mock_client.download_file.assert_called_with("my-bucket", "sub/folder/test_v0.1.0.pkl", "test_v0.1.0.pkl")
@mock.patch('boto3.Session')
def test_execute_pull_s3_subfolder_singular(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="pull", version='0.1.0', artifact='test3', user=None, token=None, override=False)
self.s3_subfolder.execute(config, args)
mock_client.download_file.assert_called_with("my-bucket", "sub/folder/test3.pkl", "test3.pkl")
@mock.patch('skelebot.components.repository.artifactoryRepo.input')
@mock.patch('builtins.open')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_pull_lcv_artifactory(self, mock_artifactory, mock_open, mock_input):
mock_apath = mock_artifactory.return_value
mock_input.return_value = "abc"
mock_apath.__iter__.return_value = ["test_v1.1.0", "test_v0.2.4", "test_v1.0.0", "test_v2.0.1"]
config = sb.objects.config.Config(version="1.0.9")
args = argparse.Namespace(job="pull", version='LATEST', artifact='test', user=None, token=None, override=False)
self.artifactory.execute(config, args)
mock_artifactory.assert_called_with("artifactory.test.com/ml/test/test_v1.0.0.pkl", auth=("abc", "abc"))
mock_open.assert_called_with("test_v1.0.0.pkl", "wb")
@mock.patch('boto3.Session')
def test_execute_pull_lcv_s3(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_client.list_objects_v2.return_value = {"Contents": [{"Key": "test_v1.1.0.pkl"},{"Key": "test_v1.0.5.pkl"},{"Key": "test_v1.0.0.pkl"}]}
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.9")
args = argparse.Namespace(job="pull", version='LATEST', artifact='test', user=None, token=None, override=False)
self.s3.execute(config, args)
mock_client.list_objects_v2.assert_called_with(Bucket="my-bucket", Prefix="test_v1")
mock_client.download_file.assert_called_with("my-bucket", "test_v1.0.5.pkl", "test_v1.0.5.pkl")
@mock.patch('skelebot.components.repository.artifactoryRepo.input')
@mock.patch('builtins.open')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_pull_lcv_not_found_artifactory(self, mock_artifactory, mock_open, mock_input):
mock_apath = mock_artifactory.return_value
mock_input.return_value = "abc"
mock_apath.__iter__.return_value = ["test_v1.1.0", "test_v0.2.4", "test_v1.0.0", "test_v2.0.1"]
config = sb.objects.config.Config(version="3.0.9")
args = argparse.Namespace(job="pull", version='LATEST', artifact='test', user=None, token=None, override=False)
try:
self.artifactory.execute(config, args)
self.fail("Exception Not Thrown")
except RuntimeError as err:
self.assertEqual(str(err), "No Compatible Version Found")
@mock.patch('boto3.Session')
def test_execute_pull_lcv_not_found_s3(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_client.list_objects_v2.return_value = {"Contents": [{"Key": "test_v1.1.0.pkl"},{"Key": "test_v1.0.5.pkl"},{"Key": "test_v1.0.0.pkl"}]}
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="2.0.9")
args = argparse.Namespace(job="pull", version='LATEST', artifact='test', user=None, token=None, override=False)
try:
self.s3.execute(config, args)
self.fail("Exception Not Thrown")
except RuntimeError as err:
self.assertEqual(str(err), "No Compatible Version Found")
@mock.patch('skelebot.components.repository.artifactoryRepo.input')
@mock.patch('builtins.open')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_pull_override_and_lcv_artifactory(self, mock_artifactory, mock_open, mock_input):
mock_apath = mock_artifactory.return_value
mock_input.return_value = "abc"
mock_apath.__iter__.return_value = ["test_v1.1.0", "test_v0.2.4", "test_v1.0.0", "test_v2.0.1"]
config = sb.objects.config.Config(version="0.6.9")
args = argparse.Namespace(job="pull", version='LATEST', artifact='test', user=None, token=None, override=True)
self.artifactory.execute(config, args)
mock_artifactory.assert_called_with("artifactory.test.com/ml/test/test_v0.2.4.pkl", auth=("abc", "abc"))
mock_open.assert_called_with("test.pkl", "wb")
@mock.patch('boto3.Session')
def test_execute_pull_override_and_lcv_s3(self, mock_boto3_session):
mock_client = mock.Mock()
mock_session = mock.Mock()
mock_client.list_objects_v2.return_value = {"Contents": [{"Key": "test_v1.1.0.pkl"},{"Key": "test_v1.0.5.pkl"},{"Key": "test_v1.0.0.pkl"}]}
mock_session.client.return_value = mock_client
mock_boto3_session.return_value = mock_session
config = sb.objects.config.Config(version="1.0.3")
args = argparse.Namespace(job="pull", version='LATEST', artifact='test', user=None, token=None, override=True)
self.s3.execute(config, args)
mock_client.download_file.assert_called_with("my-bucket", "test_v1.0.0.pkl", "test.pkl")
@mock.patch('skelebot.components.repository.artifactoryRepo.input')
@mock.patch('artifactory.ArtifactoryPath')
def test_execute_pull_not_found(self, mock_artifactory, mock_input):
mock_input.return_value = "abc"
path = mock_artifactory.return_value
path.exists.return_value = False
config = sb.objects.config.Config(version="1.0.0")
args = argparse.Namespace(job="pull", version='0.1.0', artifact='test', user=None, token=None, override=False)
self.artifactory.execute(config, args)
mock_artifactory.assert_called_with("artifactory.test.com/ml/test/test_v0.1.0.pkl", auth=("abc", "abc"))
def test_validate_valid(self):
try:
sb.components.repository.artifactoryRepo.ArtifactoryRepo.validate(self.artifactoryDict)
except:
self.fail("Validation Raised Exception Unexpectedly")
try:
sb.components.repository.s3Repo.S3Repo.validate(self.s3Dict)
except:
self.fail("Validation Raised Exception Unexpectedly")
try:
sb.components.repository.repository.Artifact.validate(self.artifactDict)
except:
self.fail("Validation Raised Exception Unexpectedly")
def test_validate_missing(self):
s3Dict = copy.deepcopy(self.s3Dict)
del s3Dict['bucket']
del s3Dict['region']
del s3Dict['profile']
try:
sb.components.repository.s3Repo.S3Repo.validate(s3Dict)
except SchemaError as error:
self.assertEqual(error.code, "Missing keys: 'bucket', 'region'")
artifactoryDict = copy.deepcopy(self.artifactoryDict)
del artifactoryDict['url']
del artifactoryDict['repo']
del artifactoryDict['path']
try:
sb.components.repository.artifactoryRepo.ArtifactoryRepo.validate(artifactoryDict)
except SchemaError as error:
self.assertEqual(error.code, "Missing keys: 'path', 'repo', 'url'")
artifactDict = copy.deepcopy(self.artifactDict)
del artifactDict['name']
del artifactDict['file']
try:
sb.components.repository.repository.Artifact.validate(artifactDict)
except SchemaError as error:
self.assertEqual(error.code, "Missing keys: 'file', 'name'")
def validate_error_s3(self, attr, reset, expected):
s3Dict = copy.deepcopy(self.s3Dict)
s3Dict[attr] = reset
try:
sb.components.repository.s3Repo.S3Repo.validate(s3Dict)
except SchemaError as error:
self.assertEqual(error.code, "S3 '{attr}' must be a {expected}".format(attr=attr, expected=expected))
def validate_error_artifactory(self, attr, reset, expected):
artifactoryDict = copy.deepcopy(self.artifactoryDict)
artifactoryDict[attr] = reset
try:
sb.components.repository.artifactoryRepo.ArtifactoryRepo.validate(artifactoryDict)
except SchemaError as error:
self.assertEqual(error.code, "Artifactory '{attr}' must be a {expected}".format(attr=attr, expected=expected))
def validate_error_artifact(self, attr, reset, expected):
artifactDict = copy.deepcopy(self.artifactDict)
artifactDict[attr] = reset
try:
sb.components.repository.repository.Artifact.validate(artifactDict)
except SchemaError as error:
self.assertEqual(error.code, "Artifact '{attr}' must be a {expected}".format(attr=attr, expected=expected))
def test_invalid(self):
self.validate_error_s3('bucket', 123, 'String')
self.validate_error_s3('region', 123, 'String')
self.validate_error_s3('profile', 123, 'String')
self.validate_error_artifactory('url', 123, 'String')
self.validate_error_artifactory('repo', 123, 'String')
self.validate_error_artifactory('path', 123, 'String')
self.validate_error_artifact('name', 123, 'String')
self.validate_error_artifact('file', 123, 'String')
if __name__ == '__main__':
main()
| 46.155419 | 150 | 0.67922 | 2,858 | 22,570 | 5.176697 | 0.06648 | 0.005948 | 0.031362 | 0.011828 | 0.898479 | 0.861034 | 0.829605 | 0.789997 | 0.775194 | 0.750186 | 0 | 0.0243 | 0.183163 | 22,570 | 488 | 151 | 46.25 | 0.778206 | 0 | 0 | 0.611979 | 0 | 0.005208 | 0.184626 | 0.052548 | 0 | 0 | 0 | 0 | 0.127604 | 1 | 0.083333 | false | 0 | 0.013021 | 0 | 0.114583 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
5629347eea0cb1770d3e713c2564df784c268a73 | 121 | py | Python | Programming I Python/Chapter 6/functions but separated/midrange.py | eebr99/Python-Projects | 016f72b3f13793cb73c333c6eaab313eddfae9e7 | [
"MIT"
] | null | null | null | Programming I Python/Chapter 6/functions but separated/midrange.py | eebr99/Python-Projects | 016f72b3f13793cb73c333c6eaab313eddfae9e7 | [
"MIT"
] | null | null | null | Programming I Python/Chapter 6/functions but separated/midrange.py | eebr99/Python-Projects | 016f72b3f13793cb73c333c6eaab313eddfae9e7 | [
"MIT"
] | null | null | null | #this program calculates the midrange
def midrange(Max, Min):
midrange = (Max + Min) / 2
return midrange
| 17.285714 | 38 | 0.644628 | 15 | 121 | 5.2 | 0.666667 | 0.282051 | 0.358974 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011364 | 0.272727 | 121 | 6 | 39 | 20.166667 | 0.875 | 0.297521 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 6 |
5647557819f10d5a7948b5d49bbabcf9ca1fcbc6 | 105 | py | Python | models/__init__.py | PINTO0309/multi-mono-sf | 563d65f34624c9281571e8b8b6f1f25599a94a34 | [
"Apache-2.0"
] | 69 | 2021-05-06T01:31:54.000Z | 2022-03-30T02:52:53.000Z | models/__init__.py | PINTO0309/multi-mono-sf | 563d65f34624c9281571e8b8b6f1f25599a94a34 | [
"Apache-2.0"
] | 7 | 2021-05-11T06:39:44.000Z | 2022-02-28T10:13:53.000Z | models/__init__.py | PINTO0309/multi-mono-sf | 563d65f34624c9281571e8b8b6f1f25599a94a34 | [
"Apache-2.0"
] | 11 | 2021-05-09T13:34:46.000Z | 2021-11-24T09:33:49.000Z | from . import model_monosceneflow
MonoSceneFlow_Multi = model_monosceneflow.MonoSceneFlow_Multi
| 11.666667 | 64 | 0.819048 | 10 | 105 | 8.2 | 0.5 | 0.439024 | 0.756098 | 0.878049 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.152381 | 105 | 8 | 65 | 13.125 | 0.921348 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
8e6b78011f1026b62968951fd19d01c52385b665 | 121,771 | py | Python | tests/test_run.py | SalishSeaCast/SalishSeaCmd | 71b3eb92752fbecc5f3bbd7cd95eb50a934f4f85 | [
"Apache-2.0"
] | 1 | 2020-06-23T16:08:33.000Z | 2020-06-23T16:08:33.000Z | tests/test_run.py | SalishSeaCast/SalishSeaCmd | 71b3eb92752fbecc5f3bbd7cd95eb50a934f4f85 | [
"Apache-2.0"
] | 6 | 2021-02-10T02:00:17.000Z | 2022-03-11T22:46:08.000Z | tests/test_run.py | SalishSeaCast/SalishSeaCmd | 71b3eb92752fbecc5f3bbd7cd95eb50a934f4f85 | [
"Apache-2.0"
] | null | null | null | # Copyright 2013-2021 The Salish Sea MEOPAR Contributors
# and The University of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SalishSeaCmd run sub-command plug-in unit tests
"""
import os
import shlex
import subprocess
import tempfile
import textwrap
from io import StringIO
from pathlib import Path
from unittest.mock import call, Mock, patch
import cliff.app
import f90nml
import pytest
import yaml
import salishsea_cmd.run
@pytest.fixture
def run_cmd():
import salishsea_cmd.run
return salishsea_cmd.run.Run(Mock(spec=cliff.app.App), [])
class TestParser:
"""Unit tests for `salishsea run` sub-command command-line parser."""
def test_get_parser(self, run_cmd):
parser = run_cmd.get_parser("salishsea run")
assert parser.prog == "salishsea run"
def test_parsed_args_defaults(self, run_cmd):
parser = run_cmd.get_parser("salishsea run")
parsed_args = parser.parse_args(["foo", "baz"])
assert parsed_args.desc_file == Path("foo")
assert parsed_args.results_dir == Path("baz")
assert not parsed_args.cedar_broadwell
assert not parsed_args.deflate
assert parsed_args.max_deflate_jobs == 4
assert not parsed_args.nocheck_init
assert not parsed_args.no_submit
assert not parsed_args.separate_deflate
assert parsed_args.waitjob == "0"
assert not parsed_args.quiet
@pytest.mark.parametrize(
"flag, attr",
[
("--cedar-broadwell", "cedar_broadwell"),
("--deflate", "deflate"),
("--nocheck-initial-conditions", "nocheck_init"),
("--no-submit", "no_submit"),
("--separate-deflate", "separate_deflate"),
("-q", "quiet"),
("--quiet", "quiet"),
],
)
def test_parsed_args_boolean_flags(self, flag, attr, run_cmd):
parser = run_cmd.get_parser("salishsea run")
parsed_args = parser.parse_args(["foo", "baz", flag])
assert getattr(parsed_args, attr)
@patch("salishsea_cmd.run.log")
@patch("salishsea_cmd.run.run", return_value="job submitted message")
class TestTakeAction:
"""Unit tests for `salishsea run` sub-command take_action() method."""
def test_take_action(self, m_run, m_log, run_cmd):
parsed_args = Mock(
desc_file="desc file",
results_dir="results dir",
cedar_broadwell=False,
deflate=False,
max_deflate_jobs=4,
nocheck_init=False,
no_submit=False,
separate_deflate=False,
waitjob=0,
quiet=False,
)
run_cmd.run(parsed_args)
m_run.assert_called_once_with(
"desc file",
"results dir",
cedar_broadwell=False,
deflate=False,
max_deflate_jobs=4,
nocheck_init=False,
no_submit=False,
separate_deflate=False,
waitjob=0,
quiet=False,
)
m_log.info.assert_called_once_with("job submitted message")
def test_take_action_quiet(self, m_run, m_log, run_cmd):
parsed_args = Mock(desc_file="desc file", results_dir="results dir", quiet=True)
run_cmd.run(parsed_args)
assert not m_log.info.called
@patch("salishsea_cmd.run._submit_separate_deflate_jobs")
@patch("salishsea_cmd.run._submit_job")
@patch("salishsea_cmd.run._build_deflate_script", return_value="deflate script")
@patch("salishsea_cmd.run._build_tmp_run_dir")
@patch("salishsea_cmd.run._calc_run_segments")
@patch("salishsea_cmd.run._write_segment_namrun_namelist")
@patch("salishsea_cmd.run._write_segment_desc_file", return_value=({}, ""))
class TestRun:
"""Unit tests for `salishsea run` run() function."""
@pytest.mark.parametrize(
"sep_xios_server, xios_servers, system, queue_job_cmd, submit_job_msg",
[
(False, 0, "beluga", "sbatch", "Submitted batch job 43"),
(True, 4, "beluga", "sbatch", "Submitted batch job 43"),
(False, 0, "cedar", "sbatch", "Submitted batch job 43"),
(True, 4, "cedar", "sbatch", "Submitted batch job 43"),
(False, 0, "delta", "qsub -q mpi", "43.admin.default.domain"),
(True, 4, "delta", "qsub -q mpi", "43.admin.default.domain"),
(False, 0, "graham", "sbatch", "Submitted batch job 43"),
(True, 4, "graham", "sbatch", "Submitted batch job 43"),
(False, 0, "salish", "qsub", "43.master"),
(True, 4, "salish", "qsub", "43.master"),
(False, 0, "sigma", "qsub -q mpi", "43.admin.default.domain"),
(True, 4, "sigma", "qsub -q mpi", "43.admin.default.domain"),
(False, 0, "sockeye", "qsub", "43.pbsha"),
(True, 4, "sockeye", "qsub", "43.pbsha"),
(False, 0, "orcinus", "qsub", "43.orca2.ibb"),
(True, 4, "orcinus", "qsub", "43.orca2.ibb"),
(False, 0, "seawolf1", "qsub", "431.orca2.ibb"),
(True, 4, "seawolf1", "qsub", "431.orca2.ibb"),
(False, 0, "seawolf2", "qsub", "432.orca2.ibb"),
(True, 4, "seawolf2", "qsub", "432.orca2.ibb"),
(False, 0, "seawolf3", "qsub", "433.orca2.ibb"),
(True, 4, "seawolf3", "qsub", "433.orca2.ibb"),
],
)
def test_run_submit(
self,
m_wsdf,
m_wsnn,
m_crs,
m_btrd,
m_bds,
m_sj,
m_ssdj,
sep_xios_server,
xios_servers,
system,
queue_job_cmd,
submit_job_msg,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
p_results_dir = tmpdir.ensure_dir("results_dir")
m_crs.return_value = (
[
(
{
"output": {
"separate XIOS server": sep_xios_server,
"XIOS servers": xios_servers,
}
},
Path("SalishSea.yaml"),
Path(str(p_run_dir)),
{},
)
],
0,
)
m_btrd.return_value = (
Path(str(p_run_dir)),
Path(str(p_run_dir), "SalishSeaNEMO.sh"),
)
m_sj.return_value = submit_job_msg
with patch("salishsea_cmd.run.SYSTEM", system):
submit_job_msg = salishsea_cmd.run.run(
Path("SalishSea.yaml"), Path(str(p_results_dir))
)
m_sj.assert_called_once_with(
Path(str(p_run_dir), "SalishSeaNEMO.sh"), queue_job_cmd, waitjob="0"
)
assert submit_job_msg == submit_job_msg
@pytest.mark.parametrize(
"sep_xios_server, xios_servers, system, queue_job_cmd, submit_job_msg",
[
(False, 0, "beluga", "sbatch", "Submitted batch job 43"),
(True, 4, "beluga", "sbatch", "Submitted batch job 43"),
(False, 0, "cedar", "sbatch", "Submitted batch job 43"),
(True, 4, "cedar", "sbatch", "Submitted batch job 43"),
(False, 0, "delta", "qsub -q mpi", "43.admin.default.domain"),
(True, 4, "delta", "qsub -q mpi", "43.admin.default.domain"),
(False, 0, "graham", "sbatch", "Submitted batch job 43"),
(True, 4, "graham", "sbatch", "Submitted batch job 43"),
(False, 0, "salish", "qsub", "43.master"),
(True, 4, "salish", "qsub", "43.master"),
(False, 0, "sigma", "qsub -q mpi", "43.admin.default.domain"),
(True, 4, "sigma", "qsub -q mpi", "43.admin.default.domain"),
(False, 0, "sockeye", "qsub", "43.pbsha"),
(True, 4, "sockeye", "qsub", "43.pbsha"),
(False, 0, "orcinus", "qsub", "43.orca2.ibb"),
(True, 4, "orcinus", "qsub", "43.orca2.ibb"),
(False, 0, "seawolf1", "qsub", "431.orca2.ibb"),
(True, 4, "seawolf1", "qsub", "431.orca2.ibb"),
(False, 0, "seawolf2", "qsub", "432.orca2.ibb"),
(True, 4, "seawolf2", "qsub", "432.orca2.ibb"),
(False, 0, "seawolf3", "qsub", "433.orca2.ibb"),
(True, 4, "seawolf3", "qsub", "433.orca2.ibb"),
],
)
def test_run_waitjob(
self,
m_wsdf,
m_wsnn,
m_crs,
m_btrd,
m_bds,
m_sj,
m_ssdj,
sep_xios_server,
xios_servers,
system,
queue_job_cmd,
submit_job_msg,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
p_results_dir = tmpdir.ensure_dir("results_dir")
m_crs.return_value = (
[
(
{
"output": {
"separate XIOS server": sep_xios_server,
"XIOS servers": xios_servers,
}
},
Path("SalishSea.yaml"),
Path(str(p_run_dir)),
{},
)
],
0,
)
m_btrd.return_value = (
Path(str(p_run_dir)),
Path(str(p_run_dir), "SalishSeaNEMO.sh"),
)
m_sj.return_value = submit_job_msg
with patch("salishsea_cmd.run.SYSTEM", system):
submit_job_msg = salishsea_cmd.run.run(
Path("SalishSea.yaml"), Path(str(p_results_dir)), waitjob="42"
)
m_sj.assert_called_once_with(
Path(str(p_run_dir), "SalishSeaNEMO.sh"), queue_job_cmd, waitjob="42"
)
assert submit_job_msg == submit_job_msg
@pytest.mark.parametrize("sep_xios_server, xios_servers", [(False, 0), (True, 4)])
def test_run_no_submit(
self,
m_wsdf,
m_wsnn,
m_crs,
m_btrd,
m_bds,
m_sj,
m_ssdj,
sep_xios_server,
xios_servers,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
p_results_dir = tmpdir.ensure_dir("results_dir")
m_crs.return_value = (
[
(
{
"output": {
"separate XIOS server": sep_xios_server,
"XIOS servers": xios_servers,
}
},
Path("SalishSea.yaml"),
Path(str(p_run_dir)),
{},
)
],
0,
)
m_btrd.return_value = (
Path(str(p_run_dir)),
Path(str(p_run_dir), "SalishSeaNEMO.sh"),
)
with patch("salishsea_cmd.run.SYSTEM", "orcinus"):
submit_job_msg = salishsea_cmd.run.run(
Path("SalishSea.yaml"), Path(str(p_results_dir)), no_submit=True
)
assert not m_sj.called
assert submit_job_msg is None
@pytest.mark.parametrize("sep_xios_server, xios_servers", [(False, 0), (True, 4)])
def test_run_no_submit_w_separate_deflate(
self,
m_wsdf,
m_wsnn,
m_crs,
m_btrd,
m_bds,
m_sj,
m_ssdj,
sep_xios_server,
xios_servers,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
p_results_dir = tmpdir.ensure_dir("results_dir")
m_crs.return_value = (
[
(
{
"output": {
"separate XIOS server": sep_xios_server,
"XIOS servers": xios_servers,
}
},
Path("SalishSea.yaml"),
Path(str(p_run_dir)),
{},
)
],
0,
)
m_btrd.return_value = (
Path(str(p_run_dir)),
Path(str(p_run_dir), "SalishSeaNEMO.sh"),
)
with patch("salishsea_cmd.run.SYSTEM", "orcinus"):
submit_job_msg = salishsea_cmd.run.run(
Path("SalishSea.yaml"),
Path(str(p_results_dir)),
no_submit=True,
separate_deflate=True,
)
assert not m_sj.called
assert submit_job_msg is None
@pytest.mark.parametrize(
"sep_xios_server, xios_servers, system, queue_job_cmd, submit_job_msg",
[
(False, 0, "beluga", "sbatch", "Submitted batch job 43"),
(True, 4, "beluga", "sbatch", "Submitted batch job 43"),
(False, 0, "cedar", "sbatch", "Submitted batch job 43"),
(True, 4, "cedar", "sbatch", "Submitted batch job 43"),
(False, 0, "delta", "qsub -q mpi", "43.admin.default.domain"),
(True, 4, "delta", "qsub -q mpi", "43.admin.default.domain"),
(False, 0, "graham", "sbatch", "Submitted batch job 43"),
(True, 4, "graham", "sbatch", "Submitted batch job 43"),
(False, 0, "salish", "qsub", "43.master"),
(True, 4, "salish", "qsub", "43.master"),
(False, 0, "sigma", "qsub -q mpi", "43.admin.default.domain"),
(True, 4, "sigma", "qsub -q mpi", "43.admin.default.domain"),
(False, 0, "sockeye", "qsub", "43.pbsha"),
(True, 4, "sockeye", "qsub", "43.pbsha"),
(False, 0, "orcinus", "qsub", "43.orca2.ibb"),
(True, 4, "orcinus", "qsub", "43.orca2.ibb"),
(False, 0, "seawolf1", "qsub", "431.orca2.ibb"),
(True, 4, "seawolf1", "qsub", "431.orca2.ibb"),
(False, 0, "seawolf2", "qsub", "432.orca2.ibb"),
(True, 4, "seawolf2", "qsub", "432.orca2.ibb"),
(False, 0, "seawolf3", "qsub", "433.orca2.ibb"),
(True, 4, "seawolf3", "qsub", "433.orca2.ibb"),
],
)
def test_run_separate_deflate(
self,
m_wsdf,
m_wsnn,
m_crs,
m_btrd,
m_bds,
m_sj,
m_ssdj,
sep_xios_server,
xios_servers,
system,
queue_job_cmd,
submit_job_msg,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
p_results_dir = tmpdir.ensure_dir("results_dir")
m_crs.return_value = (
[
(
{
"output": {
"separate XIOS server": sep_xios_server,
"XIOS servers": xios_servers,
}
},
Path("SalishSea.yaml"),
Path(str(p_run_dir)),
{},
)
],
0,
)
m_btrd.return_value = (
Path(str(p_run_dir)),
Path(str(p_run_dir), "SalishSeaNEMO.sh"),
)
m_sj.return_value = submit_job_msg
with patch("salishsea_cmd.run.SYSTEM", system):
submit_job_msg = salishsea_cmd.run.run(
Path("SalishSea.yaml"), Path(str(p_results_dir)), separate_deflate=True
)
m_sj.assert_called_once_with(
Path(str(p_run_dir), "SalishSeaNEMO.sh"), queue_job_cmd, waitjob="0"
)
assert m_ssdj.called
assert submit_job_msg == submit_job_msg
@pytest.mark.parametrize(
"sep_xios_server, xios_servers, system, queue_job_cmd, job_msgs, submit_job_msg",
[
(
False,
0,
"beluga",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
True,
4,
"beluga",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
False,
0,
"cedar",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
True,
4,
"cedar",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
False,
0,
"delta",
"qsub -q mpi",
("43.admin.default.domain", "44.admin.default.domain"),
"43.admin.default.domain",
),
(
True,
4,
"delta",
"qsub -q mpi",
("43.admin.default.domain", "44.admin.default.domain"),
"43.admin.default.domain",
),
(
False,
0,
"graham",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
True,
4,
"graham",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(False, 0, "salish", "qsub", ("43.master", "44.master"), "43.master"),
(True, 4, "salish", "qsub", ("43.master", "44.master"), "43.master"),
(
False,
0,
"sigma",
"qsub -q mpi",
("43.admin.default.domain", "44.admin.default.domain"),
"43.admin.default.domain",
),
(
True,
4,
"sigma",
"qsub -q mpi",
("43.admin.default.domain", "44.admin.default.domain"),
"43.admin.default.domain",
),
(
False,
0,
"sockeye",
"qsub",
("43.pbsha.ib.sockeye", "44.pbsha.ib.sockeye"),
"43.pbsha.ib.sockeye",
),
(
True,
4,
"sockeye",
"qsub",
("43.pbsha.ib.sockeye", "44.pbsha.ib.sockeye"),
"43.pbsha.ib.sockeye",
),
(
False,
0,
"orcinus",
"qsub",
("43.orca2.ibb", "44.orca2.ibb"),
"43.orca2.ibb",
),
(
True,
4,
"orcinus",
"qsub",
("43.orca2.ibb", "44.orca2.ibb"),
"43.orca2.ibb",
),
],
)
def test_segmented_run_restart_dirs(
self,
m_wsdf,
m_wsnn,
m_crs,
m_btrd,
m_bds,
m_sj,
m_ssdj,
sep_xios_server,
xios_servers,
system,
queue_job_cmd,
job_msgs,
submit_job_msg,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
p_results_dir = tmpdir.ensure_dir("results_dir")
m_crs.return_value = (
[
(
yaml.safe_load(
StringIO(
"""
run_id: 1_sensitivity
segmented run:
start date: 2014-11-25
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: 1
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
),
"SalishSea_1.yaml",
Path("results_dir_1"),
{
"namrun": {
"nn_it000": 152634,
"nn_itend": 152634 + 2160 * 10 - 1,
"nn_date0": 20141115,
}
},
),
(
yaml.safe_load(
StringIO(
"""
run_id: 2_sensitivity
segmented run:
start date: 2014-11-25
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: 1
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
),
"SalishSea_2.yaml",
Path("results_dir_2"),
{
"namrun": {
"nn_it000": 152634 + 2160 * 10,
"nn_itend": 152634 + 2160 * 17 - 1,
"nn_date0": 20141125,
}
},
),
],
1,
)
m_btrd.return_value = (
Path(str(p_run_dir)),
Path(str(p_run_dir), "SalishSeaNEMO.sh"),
)
m_sj.side_effect = job_msgs
with patch("salishsea_cmd.run.SYSTEM", system):
submit_job_msg = salishsea_cmd.run.run(
Path("SalishSea.yaml"), Path(str(p_results_dir))
)
assert m_wsdf.call_args_list[1][0][2] == Path("results_dir_1")
@pytest.mark.parametrize(
"sep_xios_server, xios_servers, system, queue_job_cmd, job_msgs, submit_job_msg",
[
(
False,
0,
"beluga",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
True,
4,
"beluga",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
False,
0,
"cedar",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
True,
4,
"cedar",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
False,
0,
"delta",
"qsub -q mpi",
("43.admin.default.domain", "44.admin.default.domain"),
"43.admin.default.domain",
),
(
True,
4,
"delta",
"qsub -q mpi",
("43.admin.default.domain", "44.admin.default.domain"),
"43.admin.default.domain",
),
(
False,
0,
"graham",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(
True,
4,
"graham",
"sbatch",
("Submitted batch job 43", "Submitted batch job 44"),
"Submitted batch job 43",
),
(False, 0, "salish", "qsub", ("43.master", "44.master"), "43.master"),
(True, 4, "salish", "qsub", ("43.master", "44.master"), "43.master"),
(
False,
0,
"sigma",
"qsub -q mpi",
("43.admin.default.domain", "44.admin.default.domain"),
"43.admin.default.domain",
),
(
True,
4,
"sigma",
"qsub -q mpi",
("43.admin.default.domain", "44.admin.default.domain"),
"43.admin.default.domain",
),
(
True,
4,
"sockeye",
"qsub",
("43.pbsha.ib.sockeye", "44.pbsha.ib.sockeye"),
"43.pbsha.ib.sockeye",
),
(
False,
0,
"orcinus",
"qsub",
("43.orca2.ibb", "44.orca2.ibb"),
"43.orca2.ibb",
),
(
False,
0,
"orcinus",
"qsub",
("43.orca2.ibb", "44.orca2.ibb"),
"43.orca2.ibb",
),
(
True,
4,
"orcinus",
"qsub",
("43.orca2.ibb", "44.orca2.ibb"),
"43.orca2.ibb",
),
],
)
def test_segmented_run_submits(
self,
m_wsdf,
m_wsnn,
m_crs,
m_btrd,
m_bds,
m_sj,
m_ssdj,
sep_xios_server,
xios_servers,
system,
queue_job_cmd,
job_msgs,
submit_job_msg,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
p_results_dir = tmpdir.ensure_dir("results_dir")
m_crs.return_value = (
[
(
yaml.safe_load(
StringIO(
"""
run_id: 0_sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
),
"SalishSea_0.yaml",
Path("results_dir_0"),
{
"namrun": {
"nn_it000": 152634,
"nn_itend": 152634 + 2160 * 10 - 1,
"nn_date0": 20141115,
}
},
),
(
yaml.safe_load(
StringIO(
"""
run_id: 1_sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
),
"SalishSea_1.yaml",
Path("results_dir_1"),
{
"namrun": {
"nn_it000": 152634 + 2160 * 10,
"nn_itend": 152634 + 2160 * 17 - 1,
"nn_date0": 20141125,
}
},
),
],
0,
)
m_btrd.return_value = (
Path(str(p_run_dir)),
Path(str(p_run_dir), "SalishSeaNEMO.sh"),
)
m_sj.side_effect = job_msgs
with patch("salishsea_cmd.run.SYSTEM", system):
submit_job_msg = salishsea_cmd.run.run(
Path("SalishSea.yaml"), Path(str(p_results_dir))
)
assert m_sj.call_args_list == [
call(Path(str(p_run_dir), "SalishSeaNEMO.sh"), queue_job_cmd, waitjob="0"),
call(
Path(str(p_run_dir), "SalishSeaNEMO.sh"),
queue_job_cmd,
waitjob=job_msgs[0],
),
]
expected = "Submitted jobs"
for job_msg in job_msgs:
expected = " ".join((expected, job_msg.split()[-1]))
assert submit_job_msg == expected
@patch("salishsea_cmd.run.load_run_desc")
@patch("salishsea_cmd.run.f90nml.read", return_value={"namdom": {"rn_rdt": 40.0}})
class TestCalcRunSegments:
"""Unit tests for _calc_run_segments() function."""
def test_not_segmented_run(self, m_f90nml_read, m_lrd):
m_lrd.return_value = {}
run_segments, first_seg_no = salishsea_cmd.run._calc_run_segments(
Path("SalishSea.yaml"), Path("results_dir")
)
assert run_segments == [
(m_lrd(), Path("SalishSea.yaml"), Path("results_dir"), {})
]
assert first_seg_no == 0
def test_no_run_id(self, m_f90nml_read, m_lrd):
m_lrd.return_value = yaml.safe_load(
StringIO(
"""
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
)
with pytest.raises(SystemExit):
salishsea_cmd.run._calc_run_segments(
Path("SalishSea.yaml"), Path("results_dir")
)
def test_no_start_date(self, m_f90nml_read, m_lrd):
m_lrd.return_value = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
segmented run:
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
)
with pytest.raises(SystemExit):
salishsea_cmd.run._calc_run_segments(
Path("SalishSea.yaml"), Path("results_dir")
)
def test_no_start_time_step(self, m_f90nml_read, m_lrd):
m_lrd.return_value = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
segmented run:
start date: 2014-11-15
end date: 2014-12-02
days per segment: 10
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
)
with pytest.raises(SystemExit):
salishsea_cmd.run._calc_run_segments(
Path("SalishSea.yaml"), Path("results_dir")
)
def test_no_end_date(self, m_f90nml_read, m_lrd):
m_lrd.return_value = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
days per segment: 10
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
)
with pytest.raises(SystemExit):
salishsea_cmd.run._calc_run_segments(
Path("SalishSea.yaml"), Path("results_dir")
)
def test_no_days_per_segment(self, m_f90nml_read, m_lrd):
m_lrd.return_value = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
)
with pytest.raises(SystemExit):
salishsea_cmd.run._calc_run_segments(
Path("SalishSea.yaml"), Path("results_dir")
)
def test_no_first_segment_number(self, m_f90nml_read, m_lrd):
m_lrd.return_value = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
)
with pytest.raises(SystemExit):
salishsea_cmd.run._calc_run_segments(
Path("SalishSea.yaml"), Path("results_dir")
)
def test_no_namdom_namelist(self, m_f90nml_read, m_lrd):
m_lrd.return_value = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
"""
)
)
with pytest.raises(SystemExit):
salishsea_cmd.run._calc_run_segments(
Path("SalishSea.yaml"), Path("results_dir")
)
@pytest.mark.parametrize("first_seg_no", (0, 3))
def test_run_segments(self, m_f90nml_read, m_lrd, first_seg_no):
m_lrd.return_value = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: {first_seg_no}
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
""".format(
first_seg_no=first_seg_no
)
)
)
run_segments, first_seg_no_ = salishsea_cmd.run._calc_run_segments(
Path("SalishSea.yaml"), Path("results_dir")
)
expected = [
(
yaml.safe_load(
StringIO(
"""
run_id: {seg_no}_sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: {seg_no}
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
""".format(
seg_no=first_seg_no
)
)
),
"SalishSea_{seg_no}.yaml".format(seg_no=first_seg_no),
Path("results_dir_{seg_no}".format(seg_no=first_seg_no)),
{
"namrun": {
"nn_it000": 152634,
"nn_itend": 152634 + 2160 * 10 - 1,
"nn_date0": 20141115,
}
},
),
(
yaml.safe_load(
StringIO(
"""
run_id: {seg_no}_sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
first segment number: {first_seg_no}
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
""".format(
first_seg_no=first_seg_no, seg_no=first_seg_no + 1
)
)
),
"SalishSea_{seg_no}.yaml".format(seg_no=first_seg_no + 1),
Path("results_dir_{seg_no}".format(seg_no=first_seg_no + 1)),
{
"namrun": {
"nn_it000": 152634 + 2160 * 10,
"nn_itend": 152634 + 2160 * 18 - 1,
"nn_date0": 20141125,
}
},
),
]
assert run_segments == expected
assert first_seg_no_ == first_seg_no
def test_final_run_segment(self, m_f90nml_read, m_lrd):
m_lrd.return_value = yaml.safe_load(
StringIO(
textwrap.dedent(
"""\
run_id: SKOG_2016_BASE
segmented run:
start date: 2016-04-30
start time step: 2730241
end date: 2016-12-31
days per segment: 30
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SalishSeaCast/hindcast-sys/SS-run-sets/v201812/namelist.domain
"""
)
)
)
run_segments, first_seg_no = salishsea_cmd.run._calc_run_segments(
Path("BR5_12SKOG2016.yaml"), Path("SKOG_C")
)
expected = (
yaml.safe_load(
StringIO(
textwrap.dedent(
"""\
run_id: 8_SKOG_2016_BASE
segmented run:
start date: 2016-04-30
start time step: 2730241
end date: 2016-12-31
days per segment: 30
first segment number: 0
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SalishSeaCast/hindcast-sys/SS-run-sets/v201812/namelist.domain
"""
)
)
),
"BR5_12SKOG2016_8.yaml",
Path("SKOG_C_8"),
{
"namrun": {
"nn_it000": 3248641,
"nn_itend": 3261600,
"nn_date0": 20161226,
}
},
)
assert run_segments[-1] == expected
class TestCalcNSegments:
"""Unit tests for _calc_n_segments() function."""
@pytest.mark.parametrize(
"run_desc, expected",
[
(
{
"segmented run": {
"start date": "2014-11-21",
"end date": "2014-11-22",
"days per segment": 1,
}
},
2,
),
(
{
"segmented run": {
"start date": "2014-11-15",
"end date": "2014-11-16",
"days per segment": 10,
}
},
1,
),
(
{
"segmented run": {
"start date": "2014-11-15",
"end date": "2014-11-24",
"days per segment": 10,
}
},
1,
),
(
{
"segmented run": {
"start date": "2014-11-15",
"end date": "2014-11-25",
"days per segment": 10,
}
},
2,
),
(
{
"segmented run": {
"start date": "2014-11-15",
"end date": "2014-12-02",
"days per segment": 10,
}
},
2,
),
(
{
"segmented run": {
"start date": "2016-04-30",
"end date": "2016-12-31",
"days per segment": 30,
}
},
9,
),
],
)
def test_calc_n_segments(self, run_desc, expected):
assert salishsea_cmd.run._calc_n_segments(run_desc) == expected
@pytest.mark.parametrize(
"run_desc",
[
{"segmented run": {"end date": "2014-11-16", "days per segment": 10}},
{"segmented run": {"start date": "2014-11-15", "days per segment": 10}},
{"segmented run": {"start date": "2014-11-15", "end date": "2014-11-25"}},
],
)
def test_bad_run_desc(self, run_desc):
with pytest.raises(SystemExit):
salishsea_cmd.run._calc_n_segments(run_desc)
class TestWriteSegmentNamerunNamelist:
"""Unit tests for _write_segment_namerun_namelist() function."""
def test_no_namrun_namelist(self):
run_desc = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
walltime: 12:00:00
namelists:
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
)
with tempfile.TemporaryDirectory() as tmp_run_desc_dir:
with pytest.raises(SystemExit):
salishsea_cmd.run._write_segment_namrun_namelist(
run_desc, {}, Path(tmp_run_desc_dir)
)
def test_write_segment_namrun_namelist(self, tmp_path):
namelist_time = tmp_path / "namelist.time"
namelist_time.write_text(
"""
&namrun
nn_it000 = 0
nn_itend = 0
nn_date0 = 0
&end
"""
)
run_desc = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
"""
)
)
run_desc["segmented run"]["namelists"]["namrun"] = os.fspath(namelist_time)
namelist_namrun_patch = {
"namrun": {
"nn_it000": 152634,
"nn_itend": 152634 + 2160 * 10 - 1,
"nn_date0": 20141115,
}
}
with tempfile.TemporaryDirectory() as tmp_run_desc_dir:
segment_namrun = salishsea_cmd.run._write_segment_namrun_namelist(
run_desc, namelist_namrun_patch, Path(tmp_run_desc_dir)
)
assert segment_namrun == Path(tmp_run_desc_dir, "namelist.time")
nml = f90nml.read(segment_namrun)
assert nml["namrun"]["nn_it000"] == 152634
assert nml["namrun"]["nn_itend"] == 152634 + 2160 * 10 - 1
assert nml["namrun"]["nn_date0"] == 20141115
class TestWriteSegmentDescFile:
"""Unit test for _write_segment_desc_file() function."""
def test_run_desc_file(self, tmp_path):
run_desc = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
walltime: 24:00:00
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
namelists:
namelist_cfg:
- ./namelist.time
restart:
restart.nc: $PROJECT/$USER/MEOPAR/results/14nov14/SalishSea_00152633_restart.nc
restart_trc.nc: $PROJECT/$USER/MEOPAR/results/14nov14/SalishSea_00152633_restart_trc.nc
"""
)
)
with tempfile.TemporaryDirectory() as tmp_run_desc_dir:
segment_namrun = Path(tmp_run_desc_dir, "namelist.time")
segment_namrun.write_text(
"""
&namrun
nn_it000 = 174234
nn_itend = 189353
nn_date0 = 20141125
&end
"""
)
run_desc, segment_desc_file = salishsea_cmd.run._write_segment_desc_file(
run_desc,
"SalishSea_1.yaml",
Path("results_dir_0"),
segment_namrun,
Path(tmp_run_desc_dir),
)
assert segment_desc_file == Path(tmp_run_desc_dir, "SalishSea_1.yaml")
assert Path(tmp_run_desc_dir, "SalishSea_1.yaml").exists()
def test_namrun_namelist_path(self, tmp_path):
run_desc = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
walltime: 24:00:00
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
namelists:
namelist_cfg:
- ./namelist.time
restart:
restart.nc: $PROJECT/$USER/MEOPAR/results/14nov14/SalishSea_00152633_restart.nc
restart_trc.nc: $PROJECT/$USER/MEOPAR/results/14nov14/SalishSea_00152633_restart_trc.nc
"""
)
)
with tempfile.TemporaryDirectory() as tmp_run_desc_dir:
segment_namrun = Path(tmp_run_desc_dir, "namelist.time")
segment_namrun.write_text(
"""
&namrun
nn_it000 = 174234
nn_itend = 189353
nn_date0 = 20141125
&end
"""
)
run_desc, segment_desc_file = salishsea_cmd.run._write_segment_desc_file(
run_desc,
"SalishSea_1.yaml",
Path("results_dir_0"),
segment_namrun,
Path(tmp_run_desc_dir),
)
assert run_desc["namelists"]["namelist_cfg"][0] == os.fspath(segment_namrun)
@pytest.mark.parametrize("nemo_exp", ("SalishSea", "SKOG"))
def test_segment_0_restart_files_path(self, nemo_exp, tmp_path):
run_desc = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
walltime: 24:00:00
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
namelists:
namelist_cfg:
- ./namelist.time
restart:
restart.nc: $PROJECT/$USER/MEOPAR/results/14nov14/{nemo_exp}_00152633_restart.nc
restart_trc.nc: $PROJECT/$USER/MEOPAR/results/14nov14/{nemo_exp}_00152633_restart_trc.nc
""".format(
nemo_exp=nemo_exp
)
)
)
with tempfile.TemporaryDirectory() as tmp_run_desc_dir:
segment_namrun = Path(tmp_run_desc_dir, "namelist.time")
segment_namrun.write_text(
"""
&namrun
nn_it000 = 174234
nn_itend = 189353
nn_date0 = 20141125
&end
"""
)
run_desc, segment_desc_file = salishsea_cmd.run._write_segment_desc_file(
run_desc,
"SalishSea_1.yaml",
None,
segment_namrun,
Path(tmp_run_desc_dir),
)
expected = "$PROJECT/$USER/MEOPAR/results/14nov14/{nemo_exp}_00152633_restart.nc".format(
nemo_exp=nemo_exp
)
assert run_desc["restart"]["restart.nc"] == expected
expected = "$PROJECT/$USER/MEOPAR/results/14nov14/{nemo_exp}_00152633_restart_trc.nc".format(
nemo_exp=nemo_exp
)
assert run_desc["restart"]["restart_trc.nc"] == expected
@pytest.mark.parametrize("nemo_exp", ("SalishSea", "SKOG"))
def test_restart_files_path(self, nemo_exp, tmp_path):
run_desc = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
walltime: 24:00:00
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
namelists:
namelist_cfg:
- ./namelist.time
restart:
restart.nc: $PROJECT/$USER/MEOPAR/results/14nov14/{nemo_exp}_00152633_restart.nc
restart_trc.nc: $PROJECT/$USER/MEOPAR/results/14nov14/{nemo_exp}_00152633_restart_trc.nc
""".format(
nemo_exp=nemo_exp
)
)
)
with tempfile.TemporaryDirectory() as tmp_run_desc_dir:
segment_namrun = Path(tmp_run_desc_dir, "namelist.time")
segment_namrun.write_text(
"""
&namrun
nn_it000 = 174234
nn_itend = 189353
nn_date0 = 20141125
&end
"""
)
run_desc, segment_desc_file = salishsea_cmd.run._write_segment_desc_file(
run_desc,
"SalishSea_1.yaml",
Path("$PROJECT/$USER/MEOPAR/results/results_dir_0"),
segment_namrun,
Path(tmp_run_desc_dir),
)
expected = "$PROJECT/$USER/MEOPAR/results/results_dir_0/{nemo_exp}_00174233_restart.nc".format(
nemo_exp=nemo_exp
)
assert run_desc["restart"]["restart.nc"] == expected
expected = "$PROJECT/$USER/MEOPAR/results/results_dir_0/{nemo_exp}_00174233_restart_trc.nc".format(
nemo_exp=nemo_exp
)
assert run_desc["restart"]["restart_trc.nc"] == expected
def test_no_segment_walltime(self, tmp_path):
run_desc = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
walltime: 24:00:00
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
namelists:
namelist_cfg:
- ./namelist.time
restart:
restart.nc: $PROJECT/$USER/MEOPAR/results/14nov14/SalishSea_00152633_restart.nc
restart_trc.nc: $PROJECT/$USER/MEOPAR/results/14nov14/SalishSea_00152633_restart_trc.nc
"""
)
)
with tempfile.TemporaryDirectory() as tmp_run_desc_dir:
segment_namrun = Path(tmp_run_desc_dir, "namelist.time")
segment_namrun.write_text(
"""
&namrun
nn_it000 = 174234
nn_itend = 189353
nn_date0 = 20141125
&end
"""
)
with pytest.raises(SystemExit):
salishsea_cmd.run._write_segment_desc_file(
run_desc,
"SalishSea_1.yaml",
Path("$PROJECT/$USER/MEOPAR/results/results_dir_0"),
segment_namrun,
Path(tmp_run_desc_dir),
)
def test_segment_walltime(self, tmp_path):
run_desc = yaml.safe_load(
StringIO(
"""
run_id: sensitivity
walltime: 24:00:00
segmented run:
start date: 2014-11-15
start time step: 152634
end date: 2014-12-02
days per segment: 10
segment walltime: 12:00:00
namelists:
namrun: ./namelist.time
namdom: $PROJECT/SS-run-sets/v201812/namelist.domain
namelists:
namelist_cfg:
- ./namelist.time
restart:
restart.nc: $PROJECT/$USER/MEOPAR/results/14nov14/SalishSea_00152633_restart.nc
restart_trc.nc: $PROJECT/$USER/MEOPAR/results/14nov14/SalishSea_00152633_restart_trc.nc
"""
)
)
with tempfile.TemporaryDirectory() as tmp_run_desc_dir:
segment_namrun = Path(tmp_run_desc_dir, "namelist.time")
segment_namrun.write_text(
"""
&namrun
nn_it000 = 174234
nn_itend = 189353
nn_date0 = 20141125
&end
"""
)
run_desc, segment_desc_file = salishsea_cmd.run._write_segment_desc_file(
run_desc,
"SalishSea_1.yaml",
Path("$PROJECT/$USER/MEOPAR/results/results_dir_0"),
segment_namrun,
Path(tmp_run_desc_dir),
)
assert run_desc["walltime"] == 43200
@patch("salishsea_cmd.run.log", autospec=True)
@patch("salishsea_cmd.run._build_deflate_script", return_value="deflate script")
@patch("salishsea_cmd.run._build_batch_script", return_value="batch script")
@patch("salishsea_cmd.run.get_n_processors", return_value=144)
@patch("salishsea_cmd.run.api.prepare")
@pytest.mark.parametrize("sep_xios_server, xios_servers", [(False, 0), (True, 4)])
class TestBuildTmpRunDir:
"""Unit tests for _build_tmp_run_dir() function."""
def test_build_tmp_run_dir(
self,
m_prepare,
m_gnp,
m_bbs,
m_bds,
m_log,
sep_xios_server,
xios_servers,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
m_prepare.return_value = Path(str(p_run_dir))
run_desc = {
"output": {
"separate XIOS server": sep_xios_server,
"XIOS servers": xios_servers,
}
}
run_dir, batch_file = salishsea_cmd.run._build_tmp_run_dir(
run_desc,
Path("SalishSea.yaml"),
Path("results_dir"),
cedar_broadwell=False,
deflate=False,
max_deflate_jobs=4,
separate_deflate=False,
nocheck_init=False,
quiet=False,
)
assert p_run_dir.join("SalishSeaNEMO.sh").check(file=True)
assert run_dir == Path(str(p_run_dir))
assert batch_file == Path(str(p_run_dir)) / "SalishSeaNEMO.sh"
def test_build_tmp_run_dir_quiet(
self,
m_prepare,
m_gnp,
m_bbs,
m_bds,
m_log,
sep_xios_server,
xios_servers,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
m_prepare.return_value = Path(str(p_run_dir))
run_desc = {
"output": {
"separate XIOS server": sep_xios_server,
"XIOS servers": xios_servers,
}
}
run_dir, batch_file = salishsea_cmd.run._build_tmp_run_dir(
run_desc,
Path("SalishSea.yaml"),
Path("results_dir"),
cedar_broadwell=False,
deflate=False,
max_deflate_jobs=4,
separate_deflate=False,
nocheck_init=False,
quiet=True,
)
assert not m_log.info.called
assert p_run_dir.join("SalishSeaNEMO.sh").check(file=True)
assert run_dir == Path(str(p_run_dir))
assert batch_file == Path(str(p_run_dir)) / "SalishSeaNEMO.sh"
def test_build_tmp_run_dir_separate_deflate(
self,
m_prepare,
m_gnp,
m_bbs,
m_bds,
m_log,
sep_xios_server,
xios_servers,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
m_prepare.return_value = Path(str(p_run_dir))
run_desc = {
"output": {
"separate XIOS server": sep_xios_server,
"XIOS servers": xios_servers,
}
}
run_dir, batch_file = salishsea_cmd.run._build_tmp_run_dir(
run_desc,
Path("SalishSea.yaml"),
Path("results_dir"),
cedar_broadwell=False,
deflate=False,
max_deflate_jobs=4,
separate_deflate=True,
nocheck_init=False,
quiet=False,
)
assert p_run_dir.join("SalishSeaNEMO.sh").check(file=True)
assert p_run_dir.join("deflate_grid.sh").check(file=True)
assert p_run_dir.join("deflate_ptrc.sh").check(file=True)
assert p_run_dir.join("deflate_dia.sh").check(file=True)
assert run_dir == Path(str(p_run_dir))
assert batch_file == Path(str(p_run_dir)) / "SalishSeaNEMO.sh"
@patch("salishsea_cmd.run.subprocess.run")
@pytest.mark.parametrize(
"queue_job_cmd, depend_flag, depend_option, submit_job_msg",
[
("sbatch", "-d", "afterok", "Submitted batch job 43"),
("qsub", "-W", "depend=afterok", "43.orca2.ibb"),
("qsub -q mpi", "-W", "depend=afterok", "43.admin.default.domain"),
],
)
class TestSubmitJob:
"""Unit tests for _submit_job() function."""
def test_submit_job(
self, m_run, queue_job_cmd, depend_flag, depend_option, submit_job_msg
):
submit_job_msg = salishsea_cmd.run._submit_job(
Path("run_dir", "SalishSeaNEMO.sh"), queue_job_cmd, "0"
)
m_run.assert_called_once_with(
shlex.split(
"{queue_job_cmd} {run_dir}/SalishSeaNEMO.sh".format(
queue_job_cmd=queue_job_cmd, run_dir=Path("run_dir")
)
),
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
)
assert submit_job_msg == submit_job_msg
def test_submit_job_w_waitjob(
self, m_run, queue_job_cmd, depend_flag, depend_option, submit_job_msg
):
submit_job_msg = salishsea_cmd.run._submit_job(
Path("run_dir", "SalishSeaNEMO.sh"), queue_job_cmd, 42
)
m_run.assert_called_once_with(
shlex.split(
"{queue_job_cmd} {depend_flag} {depend_option}:42 {run_dir}/SalishSeaNEMO.sh".format(
queue_job_cmd=queue_job_cmd,
depend_flag=depend_flag,
depend_option=depend_option,
run_dir=Path("run_dir"),
)
),
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
)
assert submit_job_msg == submit_job_msg
@patch("salishsea_cmd.run.log", autospec=True)
@patch("salishsea_cmd.run.subprocess.run")
@pytest.mark.parametrize(
"submit_job_msg, queue_job_cmd, depend_flag, depend_option",
[
("Submitted batch job 43", "sbatch", "-d", "afterok"),
("43.orca2.ibb", "qsub", "-W", "depend=afterok"),
("43.admin.default.domain", "qsub -q mpi", "-W", "depend=afterok"),
],
)
class TestSubmitSeparateDeflateJobs:
"""Unit tests for _submit_separate_deflate_jobs() function."""
def test_submit_separate_deflate_jobs(
self,
m_run,
m_log,
submit_job_msg,
queue_job_cmd,
depend_flag,
depend_option,
tmpdir,
):
p_run_dir = tmpdir.ensure_dir("run_dir")
salishsea_cmd.run._submit_separate_deflate_jobs(
Path(str(p_run_dir)) / "SalishSeaNEMO.sh", submit_job_msg, queue_job_cmd
)
assert m_run.call_args_list == [
call(
shlex.split(
"{queue_job_cmd} {depend_flag} {depend_option}:{job_id} {run_dir}/deflate_grid.sh".format(
queue_job_cmd=queue_job_cmd,
depend_flag=depend_flag,
depend_option=depend_option,
job_id=submit_job_msg.split()[-1],
run_dir=str(p_run_dir),
)
),
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
),
call(
shlex.split(
"{queue_job_cmd} {depend_flag} {depend_option}:{job_id} {run_dir}/deflate_ptrc.sh".format(
queue_job_cmd=queue_job_cmd,
depend_flag=depend_flag,
depend_option=depend_option,
job_id=submit_job_msg.split()[-1],
run_dir=str(p_run_dir),
)
),
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
),
call(
shlex.split(
"{queue_job_cmd} {depend_flag} {depend_option}:{job_id} {run_dir}/deflate_dia.sh".format(
queue_job_cmd=queue_job_cmd,
depend_flag=depend_flag,
depend_option=depend_option,
job_id=submit_job_msg.split()[-1],
run_dir=str(p_run_dir),
)
),
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
),
]
class TestBuildBatchScript:
"""Unit test for _build_batch_script() function."""
@pytest.mark.parametrize(
"account, deflate", [("rrg-allen", True), ("rrg-allen", False)]
)
def test_beluga(self, account, deflate):
desc_file = StringIO(
"run_id: foo\n" "walltime: 01:02:03\n" "email: me@example.com"
)
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", "beluga"):
script = salishsea_cmd.run._build_batch_script(
run_desc,
Path("SalishSea.yaml"),
nemo_processors=42,
xios_processors=1,
max_deflate_jobs=4,
results_dir=Path("results_dir"),
run_dir=Path("tmp_run_dir"),
deflate=deflate,
separate_deflate=False,
cedar_broadwell=False,
)
expected = textwrap.dedent(
"""\
#!/bin/bash
#SBATCH --job-name=foo
#SBATCH --nodes=2
#SBATCH --ntasks-per-node=40
#SBATCH --mem=92G
#SBATCH --time=1:02:03
#SBATCH --mail-user=me@example.com
#SBATCH --mail-type=ALL
#SBATCH --account={account}
# stdout and stderr file paths/names
#SBATCH --output=results_dir/stdout
#SBATCH --error=results_dir/stderr
RUN_ID="foo"
RUN_DESC="tmp_run_dir/SalishSea.yaml"
WORK_DIR="tmp_run_dir"
RESULTS_DIR="results_dir"
COMBINE="${{HOME}}/.local/bin/salishsea combine"
""".format(
account=account
)
)
if deflate:
expected += textwrap.dedent(
"""\
DEFLATE="${HOME}/.local/bin/salishsea deflate"
"""
)
expected += textwrap.dedent(
"""\
GATHER="${HOME}/.local/bin/salishsea gather"
module load StdEnv/2020
module load netcdf-fortran-mpi/4.5.2
module load python/3.9.6
mkdir -p ${RESULTS_DIR}
cd ${WORK_DIR}
echo "working dir: $(pwd)"
echo "Starting run at $(date)"
mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe
MPIRUN_EXIT_CODE=$?
echo "Ended run at $(date)"
echo "Results combining started at $(date)"
${COMBINE} ${RUN_DESC} --debug
echo "Results combining ended at $(date)"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
echo "Results deflation started at $(date)"
module load nco/4.9.5
${DEFLATE} *_ptrc_T*.nc *_prod_T*.nc *_carp_T*.nc *_grid_[TUVW]*.nc \\
*_turb_T*.nc *_dia[12n]_T*.nc FVCOM*.nc Slab_[UV]*.nc *_mtrc_T*.nc \\
--jobs 4 --debug
echo "Results deflation ended at $(date)"
"""
)
expected += textwrap.dedent(
"""\
echo "Results gathering started at $(date)"
${GATHER} ${RESULTS_DIR} --debug
echo "Results gathering ended at $(date)"
chmod go+rx ${RESULTS_DIR}
chmod g+rw ${RESULTS_DIR}/*
chmod o+r ${RESULTS_DIR}/*
echo "Deleting run directory" >>${RESULTS_DIR}/stdout
rmdir $(pwd)
echo "Finished at $(date)" >>${RESULTS_DIR}/stdout
exit ${MPIRUN_EXIT_CODE}
"""
)
assert script == expected
@pytest.mark.parametrize(
"cedar_broadwell, constraint, nodes, ntasks, mem, deflate",
[(True, "broadwell", 2, 32, "0", True), (False, "skylake", 1, 48, "0", True)],
)
def test_cedar(self, cedar_broadwell, constraint, nodes, ntasks, mem, deflate):
desc_file = StringIO(
"run_id: foo\n" "walltime: 01:02:03\n" "email: me@example.com"
)
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", "cedar"):
script = salishsea_cmd.run._build_batch_script(
run_desc,
Path("SalishSea.yaml"),
nemo_processors=42,
xios_processors=1,
max_deflate_jobs=4,
results_dir=Path("results_dir"),
run_dir=Path("tmp_run_dir"),
deflate=deflate,
separate_deflate=False,
cedar_broadwell=cedar_broadwell,
)
expected = textwrap.dedent(
"""\
#!/bin/bash
#SBATCH --job-name=foo
#SBATCH --constraint={constraint}
#SBATCH --nodes={nodes}
#SBATCH --ntasks-per-node={ntasks}
#SBATCH --mem={mem}
#SBATCH --time=1:02:03
#SBATCH --mail-user=me@example.com
#SBATCH --mail-type=ALL
#SBATCH --account=rrg-allen
# stdout and stderr file paths/names
#SBATCH --output=results_dir/stdout
#SBATCH --error=results_dir/stderr
RUN_ID="foo"
RUN_DESC="tmp_run_dir/SalishSea.yaml"
WORK_DIR="tmp_run_dir"
RESULTS_DIR="results_dir"
COMBINE="${{HOME}}/.local/bin/salishsea combine"
""".format(
constraint=constraint, nodes=nodes, ntasks=ntasks, mem=mem
)
)
if deflate:
expected += textwrap.dedent(
"""\
DEFLATE="${HOME}/.local/bin/salishsea deflate"
"""
)
expected += textwrap.dedent(
"""\
GATHER="${HOME}/.local/bin/salishsea gather"
module load StdEnv/2020
module load netcdf-fortran-mpi/4.5.2
module load python/3.9.6
mkdir -p ${RESULTS_DIR}
cd ${WORK_DIR}
echo "working dir: $(pwd)"
echo "Starting run at $(date)"
mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe
MPIRUN_EXIT_CODE=$?
echo "Ended run at $(date)"
echo "Results combining started at $(date)"
${COMBINE} ${RUN_DESC} --debug
echo "Results combining ended at $(date)"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
echo "Results deflation started at $(date)"
module load nco/4.9.5
${DEFLATE} *_ptrc_T*.nc *_prod_T*.nc *_carp_T*.nc *_grid_[TUVW]*.nc \\
*_turb_T*.nc *_dia[12n]_T*.nc FVCOM*.nc Slab_[UV]*.nc *_mtrc_T*.nc \\
--jobs 4 --debug
echo "Results deflation ended at $(date)"
"""
)
expected += textwrap.dedent(
"""\
echo "Results gathering started at $(date)"
${GATHER} ${RESULTS_DIR} --debug
echo "Results gathering ended at $(date)"
chmod go+rx ${RESULTS_DIR}
chmod g+rw ${RESULTS_DIR}/*
chmod o+r ${RESULTS_DIR}/*
echo "Deleting run directory" >>${RESULTS_DIR}/stdout
rmdir $(pwd)
echo "Finished at $(date)" >>${RESULTS_DIR}/stdout
exit ${MPIRUN_EXIT_CODE}
"""
)
assert script == expected
@pytest.mark.parametrize(
"account, deflate", [("def-allen", True), ("def-allen", False)]
)
def test_graham(self, account, deflate):
desc_file = StringIO(
"run_id: foo\n" "walltime: 01:02:03\n" "email: me@example.com"
)
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", "graham"):
script = salishsea_cmd.run._build_batch_script(
run_desc,
Path("SalishSea.yaml"),
nemo_processors=42,
xios_processors=1,
max_deflate_jobs=4,
results_dir=Path("results_dir"),
run_dir=Path("tmp_run_dir"),
deflate=deflate,
separate_deflate=False,
cedar_broadwell=False,
)
expected = textwrap.dedent(
"""\
#!/bin/bash
#SBATCH --job-name=foo
#SBATCH --nodes=2
#SBATCH --ntasks-per-node=32
#SBATCH --mem=0
#SBATCH --time=1:02:03
#SBATCH --mail-user=me@example.com
#SBATCH --mail-type=ALL
#SBATCH --account={account}
# stdout and stderr file paths/names
#SBATCH --output=results_dir/stdout
#SBATCH --error=results_dir/stderr
RUN_ID="foo"
RUN_DESC="tmp_run_dir/SalishSea.yaml"
WORK_DIR="tmp_run_dir"
RESULTS_DIR="results_dir"
COMBINE="${{HOME}}/.local/bin/salishsea combine"
""".format(
account=account
)
)
if deflate:
expected += textwrap.dedent(
"""\
DEFLATE="${HOME}/.local/bin/salishsea deflate"
"""
)
expected += textwrap.dedent(
"""\
GATHER="${HOME}/.local/bin/salishsea gather"
module load StdEnv/2020
module load netcdf-fortran-mpi/4.5.2
module load python/3.9.6
mkdir -p ${RESULTS_DIR}
cd ${WORK_DIR}
echo "working dir: $(pwd)"
echo "Starting run at $(date)"
mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe
MPIRUN_EXIT_CODE=$?
echo "Ended run at $(date)"
echo "Results combining started at $(date)"
${COMBINE} ${RUN_DESC} --debug
echo "Results combining ended at $(date)"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
echo "Results deflation started at $(date)"
module load nco/4.9.5
${DEFLATE} *_ptrc_T*.nc *_prod_T*.nc *_carp_T*.nc *_grid_[TUVW]*.nc \\
*_turb_T*.nc *_dia[12n]_T*.nc FVCOM*.nc Slab_[UV]*.nc *_mtrc_T*.nc \\
--jobs 4 --debug
echo "Results deflation ended at $(date)"
"""
)
expected += textwrap.dedent(
"""\
echo "Results gathering started at $(date)"
${GATHER} ${RESULTS_DIR} --debug
echo "Results gathering ended at $(date)"
chmod go+rx ${RESULTS_DIR}
chmod g+rw ${RESULTS_DIR}/*
chmod o+r ${RESULTS_DIR}/*
echo "Deleting run directory" >>${RESULTS_DIR}/stdout
rmdir $(pwd)
echo "Finished at $(date)" >>${RESULTS_DIR}/stdout
exit ${MPIRUN_EXIT_CODE}
"""
)
assert script == expected
@pytest.mark.parametrize(
"system, deflate",
[("delta", True), ("delta", False), ("sigma", True), ("sigma", False)],
)
def test_optimum(self, system, deflate):
desc_file = StringIO(
"run_id: foo\n" "walltime: 01:02:03\n" "email: me@example.com"
)
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", system):
script = salishsea_cmd.run._build_batch_script(
run_desc,
Path("SalishSea.yaml"),
nemo_processors=278,
xios_processors=1,
max_deflate_jobs=4,
results_dir=Path("results_dir"),
run_dir=Path("tmp_run_dir"),
deflate=deflate,
separate_deflate=False,
cedar_broadwell=False,
)
expected = textwrap.dedent(
"""\
#!/bin/bash
#PBS -N foo
#PBS -S /bin/bash
#PBS -l walltime=1:02:03
# email when the job [b]egins and [e]nds, or is [a]borted
#PBS -m bea
#PBS -M me@example.com
#PBS -l nodes=14:ppn=20
# memory per processor
#PBS -l pmem=2000mb
# stdout and stderr file paths/names
#PBS -o results_dir/stdout
#PBS -e results_dir/stderr
RUN_ID="foo"
RUN_DESC="tmp_run_dir/SalishSea.yaml"
WORK_DIR="tmp_run_dir"
RESULTS_DIR="results_dir"
COMBINE="${PBS_O_HOME}/bin/salishsea combine"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
DEFLATE="${PBS_O_HOME}/bin/salishsea deflate"
"""
)
expected += textwrap.dedent(
"""\
GATHER="${PBS_O_HOME}/bin/salishsea gather"
module load OpenMPI/2.1.6/GCC/SYSTEM
mkdir -p ${RESULTS_DIR}
cd ${WORK_DIR}
echo "working dir: $(pwd)"
echo "Starting run at $(date)"
mpiexec -hostfile $(openmpi_nodefile) --bind-to core -np 278 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe
MPIRUN_EXIT_CODE=$?
echo "Ended run at $(date)"
echo "Results combining started at $(date)"
module load GCC/8.3
module load OpenMPI/2.1.6/GCC/8.3
module load ZLIB/1.2/11
module load use.paustin
module load HDF5/1.08/20
module load NETCDF/4.6/1
${COMBINE} ${RUN_DESC} --debug
echo "Results combining ended at $(date)"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
echo "Results deflation started at $(date)"
${DEFLATE} *_ptrc_T*.nc *_prod_T*.nc *_carp_T*.nc *_grid_[TUVW]*.nc \\
*_turb_T*.nc *_dia[12n]_T*.nc FVCOM*.nc Slab_[UV]*.nc *_mtrc_T*.nc \\
--jobs 4 --debug
echo "Results deflation ended at $(date)"
"""
)
expected += textwrap.dedent(
"""\
echo "Results gathering started at $(date)"
${GATHER} ${RESULTS_DIR} --debug
echo "Results gathering ended at $(date)"
chmod go+rx ${RESULTS_DIR}
chmod g+rw ${RESULTS_DIR}/*
chmod o+r ${RESULTS_DIR}/*
echo "Deleting run directory" >>${RESULTS_DIR}/stdout
rmdir $(pwd)
echo "Finished at $(date)" >>${RESULTS_DIR}/stdout
exit ${MPIRUN_EXIT_CODE}
"""
)
assert script == expected
@pytest.mark.parametrize(
"system, deflate",
(
("orcinus", True),
("seawolf1", False),
("seawolf2", False),
("seawolf3", False),
),
)
def test_orcinus(self, system, deflate):
desc_file = StringIO(
"run_id: foo\n" "walltime: 01:02:03\n" "email: me@example.com"
)
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", system):
script = salishsea_cmd.run._build_batch_script(
run_desc,
Path("SalishSea.yaml"),
nemo_processors=42,
xios_processors=1,
max_deflate_jobs=4,
results_dir=Path("results_dir"),
run_dir=Path("tmp_run_dir"),
deflate=deflate,
separate_deflate=False,
cedar_broadwell=False,
)
expected = textwrap.dedent(
"""\
#!/bin/bash
#PBS -N foo
#PBS -S /bin/bash
#PBS -l walltime=1:02:03
# email when the job [b]egins and [e]nds, or is [a]borted
#PBS -m bea
#PBS -M me@example.com
#PBS -l partition=QDR
#PBS -l nodes=4:ppn=12
# memory per processor
#PBS -l pmem=2000mb
# stdout and stderr file paths/names
#PBS -o results_dir/stdout
#PBS -e results_dir/stderr
RUN_ID="foo"
RUN_DESC="tmp_run_dir/SalishSea.yaml"
WORK_DIR="tmp_run_dir"
RESULTS_DIR="results_dir"
COMBINE="${PBS_O_HOME}/.local/bin/salishsea combine"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
DEFLATE="${PBS_O_HOME}/.local/bin/salishsea deflate"
"""
)
expected += textwrap.dedent(
"""\
GATHER="${PBS_O_HOME}/.local/bin/salishsea gather"
module load intel
module load intel/14.0/netcdf-4.3.3.1_mpi
module load intel/14.0/netcdf-fortran-4.4.0_mpi
module load intel/14.0/hdf5-1.8.15p1_mpi
module load intel/14.0/nco-4.5.2
module load python/3.5.0
module load git
mkdir -p ${RESULTS_DIR}
cd ${WORK_DIR}
echo "working dir: $(pwd)"
echo "Starting run at $(date)"
mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe
MPIRUN_EXIT_CODE=$?
echo "Ended run at $(date)"
echo "Results combining started at $(date)"
${COMBINE} ${RUN_DESC} --debug
echo "Results combining ended at $(date)"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
echo "Results deflation started at $(date)"
${DEFLATE} *_ptrc_T*.nc *_prod_T*.nc *_carp_T*.nc *_grid_[TUVW]*.nc \\
*_turb_T*.nc *_dia[12n]_T*.nc FVCOM*.nc Slab_[UV]*.nc *_mtrc_T*.nc \\
--jobs 4 --debug
echo "Results deflation ended at $(date)"
"""
)
expected += textwrap.dedent(
"""\
echo "Results gathering started at $(date)"
${GATHER} ${RESULTS_DIR} --debug
echo "Results gathering ended at $(date)"
chmod go+rx ${RESULTS_DIR}
chmod g+rw ${RESULTS_DIR}/*
chmod o+r ${RESULTS_DIR}/*
echo "Deleting run directory" >>${RESULTS_DIR}/stdout
rmdir $(pwd)
echo "Finished at $(date)" >>${RESULTS_DIR}/stdout
exit ${MPIRUN_EXIT_CODE}
"""
)
assert script == expected
@pytest.mark.parametrize("deflate", [True, False])
def test_salish(self, deflate):
desc_file = StringIO(
"run_id: foo\n" "walltime: 01:02:03\n" "email: me@example.com"
)
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", "salish"):
script = salishsea_cmd.run._build_batch_script(
run_desc,
Path("SalishSea.yaml"),
nemo_processors=7,
xios_processors=1,
max_deflate_jobs=4,
results_dir=Path("results_dir"),
run_dir=Path("tmp_run_dir"),
deflate=deflate,
separate_deflate=False,
cedar_broadwell=False,
)
expected = textwrap.dedent(
"""\
#!/bin/bash
#PBS -N foo
#PBS -S /bin/bash
#PBS -l walltime=1:02:03
# email when the job [b]egins and [e]nds, or is [a]borted
#PBS -m bea
#PBS -M me@example.com
#PBS -l procs=8
# total memory for job
#PBS -l mem=64gb
# stdout and stderr file paths/names
#PBS -o results_dir/stdout
#PBS -e results_dir/stderr
RUN_ID="foo"
RUN_DESC="tmp_run_dir/SalishSea.yaml"
WORK_DIR="tmp_run_dir"
RESULTS_DIR="results_dir"
COMBINE="${HOME}/.local/bin/salishsea combine"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
DEFLATE="${HOME}/.local/bin/salishsea deflate"
"""
)
expected += textwrap.dedent(
"""\
GATHER="${HOME}/.local/bin/salishsea gather"
mkdir -p ${RESULTS_DIR}
cd ${WORK_DIR}
echo "working dir: $(pwd)"
echo "Starting run at $(date)"
/usr/bin/mpirun --bind-to none -np 7 ./nemo.exe : --bind-to none -np 1 ./xios_server.exe
MPIRUN_EXIT_CODE=$?
echo "Ended run at $(date)"
echo "Results combining started at $(date)"
${COMBINE} ${RUN_DESC} --debug
echo "Results combining ended at $(date)"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
echo "Results deflation started at $(date)"
${DEFLATE} *_ptrc_T*.nc *_prod_T*.nc *_carp_T*.nc *_grid_[TUVW]*.nc \\
*_turb_T*.nc *_dia[12n]_T*.nc FVCOM*.nc Slab_[UV]*.nc *_mtrc_T*.nc \\
--jobs 4 --debug
echo "Results deflation ended at $(date)"
"""
)
expected += textwrap.dedent(
"""\
echo "Results gathering started at $(date)"
${GATHER} ${RESULTS_DIR} --debug
echo "Results gathering ended at $(date)"
chmod go+rx ${RESULTS_DIR}
chmod g+rw ${RESULTS_DIR}/*
chmod o+r ${RESULTS_DIR}/*
echo "Deleting run directory" >>${RESULTS_DIR}/stdout
rmdir $(pwd)
echo "Finished at $(date)" >>${RESULTS_DIR}/stdout
exit ${MPIRUN_EXIT_CODE}
"""
)
assert script == expected
@pytest.mark.parametrize("deflate", [True, False])
def test_sockeye(self, deflate):
desc_file = StringIO(
"run_id: foo\n" "walltime: 01:02:03\n" "email: me@example.com"
)
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", "sockeye"):
script = salishsea_cmd.run._build_batch_script(
run_desc,
Path("SalishSea.yaml"),
nemo_processors=42,
xios_processors=1,
max_deflate_jobs=4,
results_dir=Path("results_dir"),
run_dir=Path("tmp_run_dir"),
deflate=deflate,
separate_deflate=False,
cedar_broadwell=False,
)
expected = textwrap.dedent(
"""\
#!/bin/bash
#PBS -N foo
#PBS -S /bin/bash
#PBS -l walltime=1:02:03
# email when the job [b]egins and [e]nds, or is [a]borted
#PBS -m bea
#PBS -M me@example.com
#PBS -A st-sallen1-1
#PBS -l select=2:ncpus=40:mpiprocs=40:mem=64gb
# stdout and stderr file paths/names
#PBS -o results_dir/stdout
#PBS -e results_dir/stderr
RUN_ID="foo"
RUN_DESC="tmp_run_dir/SalishSea.yaml"
WORK_DIR="tmp_run_dir"
RESULTS_DIR="results_dir"
COMBINE="${PBS_O_HOME}/.local/bin/salishsea combine"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
DEFLATE="${PBS_O_HOME}/.local/bin/salishsea deflate"
"""
)
expected += textwrap.dedent(
"""\
GATHER="${PBS_O_HOME}/.local/bin/salishsea gather"
module load gcc/5.4.0
module load openmpi/3.1.5
module load netcdf-fortran/4.4.5
module load python/3.7.3
module load py-setuptools/41.0.1-py3.7.3
mkdir -p ${RESULTS_DIR}
cd ${WORK_DIR}
echo "working dir: $(pwd)"
echo "Starting run at $(date)"
mpirun --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe
MPIRUN_EXIT_CODE=$?
echo "Ended run at $(date)"
echo "Results combining started at $(date)"
${COMBINE} ${RUN_DESC} --debug
echo "Results combining ended at $(date)"
"""
)
if deflate:
expected += textwrap.dedent(
"""\
echo "Results deflation started at $(date)"
${DEFLATE} *_ptrc_T*.nc *_prod_T*.nc *_carp_T*.nc *_grid_[TUVW]*.nc \\
*_turb_T*.nc *_dia[12n]_T*.nc FVCOM*.nc Slab_[UV]*.nc *_mtrc_T*.nc \\
--jobs 4 --debug
echo "Results deflation ended at $(date)"
"""
)
expected += textwrap.dedent(
"""\
echo "Results gathering started at $(date)"
${GATHER} ${RESULTS_DIR} --debug
echo "Results gathering ended at $(date)"
chmod go+rx ${RESULTS_DIR}
chmod g+rw ${RESULTS_DIR}/*
chmod o+r ${RESULTS_DIR}/*
echo "Deleting run directory" >>${RESULTS_DIR}/stdout
rmdir $(pwd)
echo "Finished at $(date)" >>${RESULTS_DIR}/stdout
exit ${MPIRUN_EXIT_CODE}
"""
)
assert script == expected
@patch("salishsea_cmd.run.log", autospec=True)
class TestSbatchDirectives:
"""Unit tests for _sbatch_directives() function."""
def test_unknown_system(self, m_logger):
desc_file = StringIO(
"run_id: foo\n" "walltime: 01:02:03\n" "account: def-sverdrup\n"
)
run_desc = yaml.safe_load(desc_file)
with pytest.raises(SystemExit):
salishsea_cmd.run._sbatch_directives(
run_desc,
43,
cedar_broadwell=False,
email="me@example.com",
results_dir=Path("foo"),
)
assert m_logger.error.called
def test_beluga_sbatch_directives(self, m_logger):
desc_file = StringIO("run_id: foo\n" "walltime: 01:02:03\n")
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", "beluga"):
slurm_directives = salishsea_cmd.run._sbatch_directives(
run_desc,
n_processors=43,
cedar_broadwell=False,
email="me@example.com",
results_dir=Path("foo"),
)
expected = (
"#SBATCH --job-name=foo\n"
"#SBATCH --nodes=2\n"
"#SBATCH --ntasks-per-node=40\n"
"#SBATCH --mem=92G\n"
"#SBATCH --time=1:02:03\n"
"#SBATCH --mail-user=me@example.com\n"
"#SBATCH --mail-type=ALL\n"
"#SBATCH --account=rrg-allen\n"
"# stdout and stderr file paths/names\n"
"#SBATCH --output=foo/stdout\n"
"#SBATCH --error=foo/stderr\n"
)
assert slurm_directives == expected
assert m_logger.info.called
@pytest.mark.parametrize(
"system, account, cedar_broadwell, constraint, nodes, ntasks, mem",
[
("cedar", "rrg-allen", True, "broadwell", 2, 32, "0"),
("cedar", "rrg-allen", False, "skylake", 1, 48, "0"),
],
)
def test_cedar_sbatch_directives(
self, m_logger, system, account, cedar_broadwell, constraint, nodes, ntasks, mem
):
desc_file = StringIO("run_id: foo\n" "walltime: 01:02:03\n")
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", "cedar"):
slurm_directives = salishsea_cmd.run._sbatch_directives(
run_desc, 43, cedar_broadwell, "me@example.com", Path("foo")
)
expected = (
"#SBATCH --job-name=foo\n"
"#SBATCH --constraint={constraint}\n"
"#SBATCH --nodes={nodes}\n"
"#SBATCH --ntasks-per-node={ntasks}\n"
"#SBATCH --mem={mem}\n"
"#SBATCH --time=1:02:03\n"
"#SBATCH --mail-user=me@example.com\n"
"#SBATCH --mail-type=ALL\n"
"#SBATCH --account={account}\n"
"# stdout and stderr file paths/names\n"
"#SBATCH --output=foo/stdout\n"
"#SBATCH --error=foo/stderr\n"
).format(
constraint=constraint, nodes=nodes, ntasks=ntasks, mem=mem, account=account
)
assert slurm_directives == expected
assert m_logger.info.called
def test_graham_sbatch_directives(self, m_logger):
desc_file = StringIO("run_id: foo\n" "walltime: 01:02:03\n")
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", "graham"):
slurm_directives = salishsea_cmd.run._sbatch_directives(
run_desc,
n_processors=43,
cedar_broadwell=False,
email="me@example.com",
results_dir=Path("foo"),
)
expected = (
"#SBATCH --job-name=foo\n"
"#SBATCH --nodes=2\n"
"#SBATCH --ntasks-per-node=32\n"
"#SBATCH --mem=0\n"
"#SBATCH --time=1:02:03\n"
"#SBATCH --mail-user=me@example.com\n"
"#SBATCH --mail-type=ALL\n"
"#SBATCH --account=def-allen\n"
"# stdout and stderr file paths/names\n"
"#SBATCH --output=foo/stdout\n"
"#SBATCH --error=foo/stderr\n"
)
assert slurm_directives == expected
assert m_logger.info.called
@pytest.mark.parametrize("system", ("beluga", "cedar", "graham"))
def test_account_directive_from_yaml(self, m_logger, system):
desc_file = StringIO(
"run_id: foo\n" "walltime: 01:02:03\n" "account: def-sverdrup\n"
)
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", system):
slurm_directives = salishsea_cmd.run._sbatch_directives(
run_desc,
43,
cedar_broadwell=False,
email="me@example.com",
results_dir=Path("foo"),
)
assert "#SBATCH --account=def-sverdrup\n" in slurm_directives
assert not m_logger.info.called
class TestPbsDirectives:
"""Unit tests for `salishsea run` _pbs_directives() function."""
@pytest.mark.parametrize(
"system, procs_per_node, procs_directives",
(
(
"delta",
20,
"#PBS -l nodes=3:ppn=20\n# memory per processor\n#PBS -l pmem=2000mb",
),
(
"orcinus",
0,
"#PBS -l partition=QDR\n#PBS -l procs=42\n# memory per processor\n#PBS -l pmem=2000mb",
),
(
"salish",
0,
"#PBS -l procs=42\n# total memory for job\n#PBS -l mem=64gb",
),
(
"sigma",
20,
"#PBS -l nodes=3:ppn=20\n# memory per processor\n#PBS -l pmem=2000mb",
),
(
"sockeye",
32,
"#PBS -A st-sallen1-1\n#PBS -l select=2:ncpus=32:mpiprocs=32:mem=64gb",
),
),
)
def test_pbs_directives_run(self, system, procs_per_node, procs_directives):
run_desc = yaml.safe_load(
StringIO(
textwrap.dedent(
"""\
run_id: foo
walltime: 01:02:03
"""
)
)
)
with patch("salishsea_cmd.run.SYSTEM", system):
pbs_directives = salishsea_cmd.run._pbs_directives(
run_desc, 42, "me@example.com", Path("foo"), procs_per_node
)
expected = textwrap.dedent(
"""\
#PBS -N foo
#PBS -S /bin/bash
#PBS -l walltime=1:02:03
# email when the job [b]egins and [e]nds, or is [a]borted
#PBS -m bea
#PBS -M me@example.com
{procs_directives}
# stdout and stderr file paths/names
#PBS -o foo/stdout
#PBS -e foo/stderr
"""
).format(procs_directives=procs_directives)
assert pbs_directives == expected
@pytest.mark.parametrize(
"system, procs_per_node, procs_directives",
(
(
"delta",
20,
"#PBS -l nodes=3:ppn=20\n# memory per processor\n#PBS -l pmem=2000mb",
),
(
"orcinus",
0,
"#PBS -l partition=QDR\n#PBS -l procs=42\n# memory per processor\n#PBS -l pmem=2000mb",
),
(
"salish",
0,
"#PBS -l procs=42\n# total memory for job\n#PBS -l mem=64gb",
),
(
"sigma",
20,
"#PBS -l nodes=3:ppn=20\n# memory per processor\n#PBS -l pmem=2000mb",
),
(
"sockeye",
32,
"#PBS -A st-sallen1-1\n#PBS -l select=2:ncpus=32:mpiprocs=32:mem=64gb",
),
),
)
def test_pbs_directives_run_no_stderr_stdout(
self, system, procs_per_node, procs_directives
):
run_desc = yaml.safe_load(
StringIO(
textwrap.dedent(
"""\
run_id: foo
walltime: 01:02:03
"""
)
)
)
with patch("salishsea_cmd.run.SYSTEM", system):
pbs_directives = salishsea_cmd.run._pbs_directives(
run_desc,
42,
"me@example.com",
Path("foo"),
procs_per_node,
stderr_stdout=False,
)
expected = textwrap.dedent(
"""\
#PBS -N foo
#PBS -S /bin/bash
#PBS -l walltime=1:02:03
# email when the job [b]egins and [e]nds, or is [a]borted
#PBS -m bea
#PBS -M me@example.com
{procs_directives}
"""
).format(procs_directives=procs_directives)
assert pbs_directives == expected
def test_pbs_directives_deflate(self):
run_desc = yaml.safe_load(
StringIO(
textwrap.dedent(
"""\
run_id: foo
walltime: 01:02:03
"""
)
)
)
pbs_directives = salishsea_cmd.run._pbs_directives(
run_desc,
1,
"me@example.com",
Path("foo"),
pmem="2500mb",
deflate=True,
result_type="ptrc",
)
expected = textwrap.dedent(
"""\
#PBS -N ptrc_foo_deflate
#PBS -S /bin/bash
#PBS -l walltime=1:02:03
# email when the job [b]egins and [e]nds, or is [a]borted
#PBS -m bea
#PBS -M me@example.com
#PBS -l procs=1
# memory per processor
#PBS -l pmem=2500mb
# stdout and stderr file paths/names
#PBS -o foo/stdout_deflate_ptrc
#PBS -e foo/stderr_deflate_ptrc
"""
)
assert pbs_directives == expected
@pytest.mark.parametrize(
"walltime, expected_walltime", [("01:02:03", "1:02:03"), ("1:02:03", "1:02:03")]
)
def test_walltime(self, walltime, expected_walltime):
"""Ensure correct handling of walltime w/ leading zero in YAML desc file
re: issue#16
"""
run_desc = yaml.safe_load(
StringIO(
textwrap.dedent(
"""\
run_id: foo
walltime: {walltime}
"""
).format(walltime=walltime)
)
)
pbs_directives = salishsea_cmd.run._pbs_directives(
run_desc, 42, "me@example.com", Path("")
)
expected = "walltime={expected}".format(expected=expected_walltime)
assert expected in pbs_directives
def test_sockeye_account_directive(self):
run_desc = yaml.safe_load(
StringIO(
textwrap.dedent(
"""\
run_id: foo
walltime: 01:02:03
"""
)
)
)
with patch("salishsea_cmd.run.SYSTEM", "sockeye"):
pbs_directives = salishsea_cmd.run._pbs_directives(
run_desc, 43, email="me@example.com", results_dir=Path("foo")
)
assert "#PBS -A st-sallen1-1\n" in pbs_directives
@pytest.mark.parametrize(
"system",
("delta", "orcinus", "salish", "seawolf1", "seawolf2", "seawolf3", "sigma"),
)
def test_not_sockeye_no_account_directive_from_yaml(self, system):
run_desc = yaml.safe_load(
StringIO(
textwrap.dedent(
"""\
run_id: foo
walltime: 01:02:03
"""
)
)
)
with patch("salishsea_cmd.run.SYSTEM", system):
pbs_directives = salishsea_cmd.run._pbs_directives(
run_desc, 43, email="me@example.com", results_dir=Path("foo")
)
assert "#PBS -A" not in pbs_directives
class TestDefinitions:
"""Unit tests for _definitions function."""
@pytest.mark.parametrize(
"system, home, deflate",
[
("beluga", "${HOME}/.local", True),
("beluga", "${HOME}/.local", False),
("cedar", "${HOME}/.local", True),
("cedar", "${HOME}/.local", False),
("delta", "${PBS_O_HOME}", True),
("delta", "${PBS_O_HOME}", False),
("graham", "${HOME}/.local", True),
("graham", "${HOME}/.local", False),
("orcinus", "${PBS_O_HOME}/.local", True),
("orcinus", "${PBS_O_HOME}/.local", False),
("salish", "${HOME}/.local", True),
("salish", "${HOME}/.local", False),
("seawolf1", "${PBS_O_HOME}/.local", True),
("seawolf1", "${PBS_O_HOME}/.local", False),
("seawolf2", "${PBS_O_HOME}/.local", True),
("seawolf2", "${PBS_O_HOME}/.local", False),
("seawolf3", "${PBS_O_HOME}/.local", True),
("seawolf3", "${PBS_O_HOME}/.local", False),
("sigma", "${PBS_O_HOME}", True),
("sigma", "${PBS_O_HOME}", False),
("sockeye", "${PBS_O_HOME}/.local", True),
("sockeye", "${PBS_O_HOME}/.local", False),
],
)
def test_definitions(self, system, home, deflate):
desc_file = StringIO("run_id: foo\n")
run_desc = yaml.safe_load(desc_file)
with patch("salishsea_cmd.run.SYSTEM", system):
defns = salishsea_cmd.run._definitions(
run_desc,
Path("SS-run-sets", "SalishSea.yaml"),
Path("tmp_run_dir"),
Path("results_dir"),
deflate,
)
expected = (
'RUN_ID="foo"\n'
'RUN_DESC="tmp_run_dir/SalishSea.yaml"\n'
'WORK_DIR="tmp_run_dir"\n'
'RESULTS_DIR="results_dir"\n'
'COMBINE="{home}/bin/salishsea combine"\n'
).format(home=home)
if deflate:
expected += 'DEFLATE="{home}/bin/salishsea deflate"\n'.format(home=home)
expected += 'GATHER="{home}/bin/salishsea gather"\n'.format(home=home)
assert defns == expected
class TestModules:
"""Unit tests for _modules function."""
def test_unknown_system(self):
modules = salishsea_cmd.run._modules()
assert modules == ""
@pytest.mark.parametrize("system", ["beluga", "cedar", "graham"])
def test_beluga_cedar_graham(self, system):
with patch("salishsea_cmd.run.SYSTEM", system):
modules = salishsea_cmd.run._modules()
expected = textwrap.dedent(
"""\
module load StdEnv/2020
module load netcdf-fortran-mpi/4.5.2
module load python/3.9.6
"""
)
assert modules == expected
@pytest.mark.parametrize("system", ("orcinus", "seawolf1", "seawolf2", "seawolf3"))
def test_orcinus(self, system):
with patch("salishsea_cmd.run.SYSTEM", system):
modules = salishsea_cmd.run._modules()
expected = textwrap.dedent(
"""\
module load intel
module load intel/14.0/netcdf-4.3.3.1_mpi
module load intel/14.0/netcdf-fortran-4.4.0_mpi
module load intel/14.0/hdf5-1.8.15p1_mpi
module load intel/14.0/nco-4.5.2
module load python/3.5.0
module load git
"""
)
assert modules == expected
@pytest.mark.parametrize("system", ["delta", "sigma"])
def test_optimum(self, system):
with patch("salishsea_cmd.run.SYSTEM", system):
modules = salishsea_cmd.run._modules()
expected = textwrap.dedent(
"""\
module load OpenMPI/2.1.6/GCC/SYSTEM
"""
)
assert modules == expected
def test_sockeye(self):
with patch("salishsea_cmd.run.SYSTEM", "sockeye"):
modules = salishsea_cmd.run._modules()
expected = textwrap.dedent(
"""\
module load gcc/5.4.0
module load openmpi/3.1.5
module load netcdf-fortran/4.4.5
module load python/3.7.3
module load py-setuptools/41.0.1-py3.7.3
"""
)
assert modules == expected
class TestExecute:
"""Unit test for _execute function."""
@pytest.mark.parametrize(
"system, mpirun_cmd",
[
("beluga", "mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe"),
("cedar", "mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe"),
(
"delta",
"mpiexec -hostfile $(openmpi_nodefile) --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
),
("graham", "mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe"),
("orcinus", "mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe"),
("salish", "/usr/bin/mpirun --bind-to none -np 42 ./nemo.exe : --bind-to none -np 1 ./xios_server.exe"),
(
"sigma",
"mpiexec -hostfile $(openmpi_nodefile) --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
),
(
"sockeye",
"mpirun --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
),
],
)
def test_execute_with_deflate(self, system, mpirun_cmd):
with patch("salishsea_cmd.run.SYSTEM", system):
script = salishsea_cmd.run._execute(
nemo_processors=42,
xios_processors=1,
deflate=True,
max_deflate_jobs=4,
separate_deflate=False,
)
expected = textwrap.dedent(
"""\
mkdir -p ${{RESULTS_DIR}}
cd ${{WORK_DIR}}
echo "working dir: $(pwd)"
echo "Starting run at $(date)"
{mpirun_cmd}
MPIRUN_EXIT_CODE=$?
echo "Ended run at $(date)"
echo "Results combining started at $(date)"
""".format(
mpirun_cmd=mpirun_cmd
)
)
if system in {"delta", "sigma"}:
expected += textwrap.dedent(
"""\
module load GCC/8.3
module load OpenMPI/2.1.6/GCC/8.3
module load ZLIB/1.2/11
module load use.paustin
module load HDF5/1.08/20
module load NETCDF/4.6/1
"""
)
expected += textwrap.dedent(
"""\
${COMBINE} ${RUN_DESC} --debug
echo "Results combining ended at $(date)"
echo "Results deflation started at $(date)"
"""
)
if system in {"beluga", "cedar", "graham"}:
expected += textwrap.dedent(
"""\
module load nco/4.9.5
"""
)
expected += textwrap.dedent(
"""\
${DEFLATE} *_ptrc_T*.nc *_prod_T*.nc *_carp_T*.nc *_grid_[TUVW]*.nc \\
*_turb_T*.nc *_dia[12n]_T*.nc FVCOM*.nc Slab_[UV]*.nc *_mtrc_T*.nc \\
--jobs 4 --debug
echo "Results deflation ended at $(date)"
"""
)
expected += textwrap.dedent(
"""\
echo "Results gathering started at $(date)"
${GATHER} ${RESULTS_DIR} --debug
echo "Results gathering ended at $(date)"
"""
)
assert script == expected
@pytest.mark.parametrize(
"system, mpirun_cmd, deflate, separate_deflate",
[
(
"beluga",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
False,
True,
),
(
"beluga",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
False,
False,
),
(
"beluga",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
True,
True,
),
(
"cedar",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
False,
True,
),
(
"cedar",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
False,
False,
),
("cedar", "mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe", True, True),
(
"delta",
"mpiexec -hostfile $(openmpi_nodefile) --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
False,
True,
),
(
"delta",
"mpiexec -hostfile $(openmpi_nodefile) --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
False,
False,
),
(
"delta",
"mpiexec -hostfile $(openmpi_nodefile) --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
True,
True,
),
(
"graham",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
False,
True,
),
(
"graham",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
False,
False,
),
(
"graham",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
True,
True,
),
(
"orcinus",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
False,
True,
),
(
"orcinus",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
False,
False,
),
(
"orcinus",
"mpirun -np 42 ./nemo.exe : -np 1 ./xios_server.exe",
True,
True,
),
(
"salish",
"/usr/bin/mpirun --bind-to none -np 42 ./nemo.exe : --bind-to none -np 1 ./xios_server.exe",
False,
True,
),
(
"salish",
"/usr/bin/mpirun --bind-to none -np 42 ./nemo.exe : --bind-to none -np 1 ./xios_server.exe",
False,
False,
),
(
"salish",
"/usr/bin/mpirun --bind-to none -np 42 ./nemo.exe : --bind-to none -np 1 ./xios_server.exe",
True,
True,
),
(
"sigma",
"mpiexec -hostfile $(openmpi_nodefile) --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
False,
True,
),
(
"sigma",
"mpiexec -hostfile $(openmpi_nodefile) --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
False,
False,
),
(
"sigma",
"mpiexec -hostfile $(openmpi_nodefile) --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
True,
True,
),
(
"sockeye",
"mpirun --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
False,
True,
),
(
"sockeye",
"mpirun --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
False,
False,
),
(
"sockeye",
"mpirun --bind-to core -np 42 ./nemo.exe : --bind-to core -np 1 ./xios_server.exe",
True,
True,
),
],
)
def test_execute_without_deflate(
self, system, mpirun_cmd, deflate, separate_deflate
):
with patch("salishsea_cmd.run.SYSTEM", system):
script = salishsea_cmd.run._execute(
nemo_processors=42,
xios_processors=1,
deflate=deflate,
max_deflate_jobs=4,
separate_deflate=separate_deflate,
)
expected = textwrap.dedent(
"""\
mkdir -p ${{RESULTS_DIR}}
cd ${{WORK_DIR}}
echo "working dir: $(pwd)"
echo "Starting run at $(date)"
{mpirun_cmd}
MPIRUN_EXIT_CODE=$?
echo "Ended run at $(date)"
echo "Results combining started at $(date)"
""".format(
mpirun_cmd=mpirun_cmd
)
)
if system in {"delta", "sigma"}:
expected += textwrap.dedent(
"""\
module load GCC/8.3
module load OpenMPI/2.1.6/GCC/8.3
module load ZLIB/1.2/11
module load use.paustin
module load HDF5/1.08/20
module load NETCDF/4.6/1
"""
)
expected += textwrap.dedent(
"""\
${COMBINE} ${RUN_DESC} --debug
echo "Results combining ended at $(date)"
echo "Results gathering started at $(date)"
${GATHER} ${RESULTS_DIR} --debug
echo "Results gathering ended at $(date)"
"""
)
assert script == expected
class TestCleanup:
"""Unit test for _cleanup() function."""
def test_cleanup(self):
script = salishsea_cmd.run._cleanup()
expected = textwrap.dedent(
"""\
echo "Deleting run directory" >>${RESULTS_DIR}/stdout
rmdir $(pwd)
echo "Finished at $(date)" >>${RESULTS_DIR}/stdout
exit ${MPIRUN_EXIT_CODE}
"""
)
assert script == expected
@pytest.mark.parametrize(
"pattern, result_type, pmem",
[
("*_grid_[TUVW]*.nc", "grid", "2000mb"),
("*_ptrc_T*.nc", "ptrc", "2500mb"),
("*_dia[12]_T.nc", "dia", "2000mb"),
],
)
class TestBuildDeflateScript:
"""Unit test for _build_deflate_script() function."""
def test_build_deflate_script_orcinus(self, pattern, result_type, pmem, tmpdir):
run_desc = {
"run_id": "19sep14_hindcast",
"walltime": "3:00:00",
"email": "test@example.com",
}
p_results_dir = tmpdir.ensure_dir("results_dir")
with patch("salishsea_cmd.run.SYSTEM", "orcinus"):
script = salishsea_cmd.run._build_deflate_script(
run_desc, pattern, result_type, Path(str(p_results_dir))
)
expected = """#!/bin/bash
#PBS -N {result_type}_19sep14_hindcast_deflate
#PBS -S /bin/bash
#PBS -l walltime=3:00:00
# email when the job [b]egins and [e]nds, or is [a]borted
#PBS -m bea
#PBS -M test@example.com
#PBS -l partition=QDR
#PBS -l procs=1
# memory per processor
#PBS -l pmem={pmem}
# stdout and stderr file paths/names
#PBS -o {results_dir}/stdout_deflate_{result_type}
#PBS -e {results_dir}/stderr_deflate_{result_type}
RESULTS_DIR="{results_dir}"
DEFLATE="${{PBS_O_HOME}}/.local/bin/salishsea deflate"
module load intel
module load intel/14.0/netcdf-4.3.3.1_mpi
module load intel/14.0/netcdf-fortran-4.4.0_mpi
module load intel/14.0/hdf5-1.8.15p1_mpi
module load intel/14.0/nco-4.5.2
module load python/3.5.0
module load git
cd ${{RESULTS_DIR}}
echo "Results deflation started at $(date)"
${{DEFLATE}} {pattern} --jobs 1 --debug
DEFLATE_EXIT_CODE=$?
echo "Results deflation ended at $(date)"
chmod g+rw ${{RESULTS_DIR}}/*
chmod o+r ${{RESULTS_DIR}}/*
exit ${{DEFLATE_EXIT_CODE}}
""".format(
result_type=result_type,
results_dir=str(p_results_dir),
pattern=pattern,
pmem=pmem,
)
expected = expected.splitlines()
for i, line in enumerate(script.splitlines()):
assert line.strip() == expected[i].strip()
def test_build_deflate_script_pmem(self, pattern, result_type, pmem, tmpdir):
run_desc = {
"run_id": "19sep14_hindcast",
"walltime": "3:00:00",
"email": "test@example.com",
}
p_results_dir = tmpdir.ensure_dir("results_dir")
script = salishsea_cmd.run._build_deflate_script(
run_desc, pattern, result_type, Path(str(p_results_dir))
)
if result_type == "ptrc":
assert "#PBS -l pmem=2500mb" in script
else:
assert "#PBS -l pmem=2000mb" in script
| 34.505809 | 130 | 0.468264 | 12,293 | 121,771 | 4.429675 | 0.041731 | 0.032137 | 0.031678 | 0.018364 | 0.87898 | 0.854923 | 0.843997 | 0.82589 | 0.814669 | 0.796232 | 0 | 0.044829 | 0.418375 | 121,771 | 3,528 | 131 | 34.51559 | 0.724024 | 0.013271 | 0 | 0.638768 | 0 | 0.011709 | 0.228231 | 0.046397 | 0 | 0 | 0 | 0 | 0.042931 | 1 | 0.029488 | false | 0 | 0.006071 | 0 | 0.043799 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
8e78cd3e65c8759db595476abcad4e4cfa3d613a | 13,811 | py | Python | baseline/src/parallel_wavegan/datasets/audio_world_dataset.py | SolomidHero/vcc20_baseline_cyclevae | 983f4852cefc525013b2168429934a5c46d45484 | [
"MIT"
] | 131 | 2020-03-11T11:04:30.000Z | 2022-02-10T12:45:39.000Z | baseline/src/parallel_wavegan/datasets/audio_world_dataset.py | SolomidHero/vcc20_baseline_cyclevae | 983f4852cefc525013b2168429934a5c46d45484 | [
"MIT"
] | 9 | 2020-05-27T22:01:17.000Z | 2022-03-08T13:05:23.000Z | baseline/src/parallel_wavegan/datasets/audio_world_dataset.py | SolomidHero/vcc20_baseline_cyclevae | 983f4852cefc525013b2168429934a5c46d45484 | [
"MIT"
] | 18 | 2020-03-15T15:31:15.000Z | 2021-06-16T02:56:36.000Z | # -*- coding: utf-8 -*-
# Copyright 2020 Wu Yi-Chiao (Nagoya University)
# Modified from a ParallelWaveGAN repo by Tomoki Hayashi (Nagoya University)
# (https://github.com/kan-bayashi/ParallelWaveGAN)
# MIT License (https://opensource.org/licenses/MIT)
"""Dataset modules."""
import logging
from multiprocessing import Manager
import numpy as np
from torch.utils.data import Dataset
from parallel_wavegan.utils import read_txt, check_filename
from parallel_wavegan.utils import read_hdf5
from sklearn.preprocessing import StandardScaler
import soundfile as sf
def _validate_length(x, y, hop_size=None):
"""VALIDATE LENGTH
Args:
x (ndarray): numpy.ndarray with x.shape[0] = len_x
y (ndarray): numpy.ndarray with y.shape[0] = len_y
hop_size (int): upsampling factor
Returns:
(ndarray): length adjusted x with same length y
(ndarray): length adjusted y with same length x
"""
if hop_size is None:
if x.shape[0] < y.shape[0]:
y = y[:x.shape[0]]
if x.shape[0] > y.shape[0]:
x = x[:y.shape[0]]
assert len(x) == len(y)
else:
if x.shape[0] > y.shape[0] * hop_size:
x = x[:y.shape[0] * hop_size]
if x.shape[0] < y.shape[0] * hop_size:
mod_y = y.shape[0] * hop_size - x.shape[0]
mod_y_frame = mod_y // hop_size + 1
y = y[:-mod_y_frame]
x = x[:y.shape[0] * hop_size]
assert len(x) == len(y) * hop_size
return x, y
class AudioWorldDataset(Dataset):
"""PyTorch compatible audio and world dataset."""
def __init__(self,
stats,
audio_list,
world_list,
audio_load_fn=sf.read,
world_load_fn=lambda x: read_hdf5(x, "world"),
hop_size=110,
audio_length_threshold=None,
world_length_threshold=None,
return_filename=False,
allow_cache=False,
mean_path="/world/mean",
scale_path="/world/scale",
):
"""Initialize dataset.
Args:
stats (str): Filename of the statistic hdf5 file.
audio_list (str): Filename of the list of audio files.
world_list (str): Filename of the list of world feature files.
audio_load_fn (func): Function to load audio file.
world_load_fn (func): Function to load world feature file.
hop_size (int): Hope size of world feature
audio_length_threshold (int): Threshold to remove short audio files.
world_length_threshold (int): Threshold to remove short world feature files.
return_filename (bool): Whether to return the filename with arrays.
allow_cache (bool): Whether to allow cache of the loaded files.
mean_path (str): The data path (channel) of the mean in the statistic hdf5 file.
scale_path (str): The data path (channel) of the scale in the statistic hdf5 file.
"""
# load audio and world file list
audio_files = read_txt(audio_list)
world_files = read_txt(world_list)
# check filename
assert check_filename(audio_files, world_files)
# filter by threshold
if audio_length_threshold is not None:
audio_lengths = [audio_load_fn(f).shape[0] for f in audio_files]
idxs = [idx for idx in range(len(audio_files)) if audio_lengths[idx] > audio_length_threshold]
if len(audio_files) != len(idxs):
logging.warning(f"Some files are filtered by audio length threshold "
f"({len(audio_files)} -> {len(idxs)}).")
audio_files = [audio_files[idx] for idx in idxs]
world_files = [world_files[idx] for idx in idxs]
if world_length_threshold is not None:
world_lengths = [world_load_fn(f).shape[0] for f in world_files]
idxs = [idx for idx in range(len(world_files)) if world_lengths[idx] > world_length_threshold]
if len(world_files) != len(idxs):
logging.warning(f"Some files are filtered by world length threshold "
f"({len(world_files)} -> {len(idxs)}).")
audio_files = [audio_files[idx] for idx in idxs]
world_files = [world_files[idx] for idx in idxs]
# assert the number of files
assert len(audio_files) != 0, f"Not found any audio files in ${audio_list}."
assert len(audio_files) == len(world_files), \
f"Number of audio and world files are different ({len(audio_files)} vs {len(world_files)})."
self.audio_files = audio_files
self.world_files = world_files
self.audio_load_fn = audio_load_fn
self.world_load_fn = world_load_fn
self.return_filename = return_filename
self.allow_cache = allow_cache
self.hop_size = hop_size
if allow_cache:
# NOTE(kan-bayashi): Manager is need to share memory in dataloader with num_workers > 0
self.manager = Manager()
self.caches = self.manager.list()
self.caches += [() for _ in range(len(audio_files))]
# define feature pre-processing funtion
scaler = StandardScaler()
scaler.mean_ = read_hdf5(stats, mean_path)
scaler.scale_ = read_hdf5(stats, scale_path)
# for version 0.23.0, this information is needed
scaler.n_features_in_ = scaler.mean_.shape[0]
self.feat_transform = lambda x: scaler.transform(x)
def __getitem__(self, idx):
"""Get specified idx items.
Args:
idx (int): Index of the item.
Returns:
str: Audio filename (only in return_filename = True).
str: Feature filename (only in return_filename = True).
ndarray: Audio signal (T,).
ndarray: Feature (T', C).
"""
if self.allow_cache and len(self.caches[idx]) != 0:
return self.caches[idx]
audio, fs = self.audio_load_fn(self.audio_files[idx])
world = self.world_load_fn(self.world_files[idx])
# make the audio length and feature length are matched
audio, world = _validate_length(audio, world, self.hop_size)
# audio & feature pre-processing
audio = audio.astype(np.float32)
world = self.feat_transform(world)
if self.return_filename:
if self.allow_cache:
self.caches[idx] = self.audio_files[idx], self.world_files[idx], audio, world
return self.audio_files[idx], self.world_files[idx], audio, world
else:
if self.allow_cache:
self.caches[idx] = audio, world
return audio, world
def __len__(self):
"""Return dataset length.
Returns:
int: The length of dataset.
"""
return len(self.audio_files)
class AudioDataset(Dataset):
"""PyTorch compatible audio dataset."""
def __init__(self,
audio_list,
audio_length_threshold=None,
audio_load_fn=sf.read,
return_filename=False,
allow_cache=False,
):
"""Initialize dataset.
Args:
audio_list (str): Filename of the list of audio files.
audio_load_fn (func): Function to load audio file.
audio_length_threshold (int): Threshold to remove short audio files.
return_filename (bool): Whether to return the filename with arrays.
allow_cache (bool): Whether to allow cache of the loaded files.
"""
# load audio and world file list
audio_files = read_txt(audio_list)
# filter by threshold
if audio_length_threshold is not None:
audio_lengths = [audio_load_fn(f).shape[0] for f in audio_files]
idxs = [idx for idx in range(len(audio_files)) if audio_lengths[idx] > audio_length_threshold]
if len(audio_files) != len(idxs):
logging.warning(f"some files are filtered by audio length threshold "
f"({len(audio_files)} -> {len(idxs)}).")
audio_files = [audio_files[idx] for idx in idxs]
# assert the number of files
assert len(audio_files) != 0, f"Not found any audio files in ${audio_list}."
self.audio_files = audio_files
self.audio_load_fn = audio_load_fn
self.return_filename = return_filename
self.allow_cache = allow_cache
if allow_cache:
# NOTE(kan-bayashi): Manager is need to share memory in dataloader with num_workers > 0
self.manager = Manager()
self.caches = self.manager.list()
self.caches += [() for _ in range(len(audio_files))]
def __getitem__(self, idx):
"""Get specified idx items.
Args:
idx (int): Index of the item.
Returns:
str: Filename (only in return_filename = True).
ndarray: Audio (T,).
"""
if self.allow_cache and len(self.caches[idx]) != 0:
return self.caches[idx]
audio, fs = self.audio_load_fn(self.audio_files[idx])
# audio pre-processing
audio = audio.astype(np.float32)
if self.return_filename:
if self.allow_cache:
self.caches[idx] = self.audio_files[idx], audio
return self.audio_files[idx], audio
else:
if self.allow_cache:
self.caches[idx] = audio
return audio
def __len__(self):
"""Return dataset length.
Returns:
int: The length of dataset.
"""
return len(self.audio_files)
class WorldDataset(Dataset):
"""PyTorch compatible world dataset."""
def __init__(self,
stats,
world_list,
world_length_threshold=None,
world_load_fn=lambda x: read_hdf5(x, "world"),
return_filename=False,
allow_cache=False,
hop_size=120,
fs=24000,
mean_path="/world/mean",
scale_path="/world/scale",
):
"""Initialize dataset.
Args:
stats (str): Filename of the statistic hdf5 file.
world_list (str): Filename of the list of feature files.
world_load_fn (func): Function to load world feature file.
world_length_threshold (int): Threshold to remove short world feature files.
return_filename (bool): Whether to return the filename with arrays.
return_dfactors (bool): Whether to return the dilated factors with arrays.
allow_cache (bool): Whether to allow cache of the loaded files.
hop_size (int): Hope size of world feature
fs (int): Sampling rate
mean_path (str): The data path (channel) of the mean in the statistic hdf5 file.
scale_path (str): The data path (channel) of the scale in the statistic hdf5 file.
"""
# load audio and world file list
world_files = read_txt(world_list)
# filter by threshold
if world_length_threshold is not None:
world_lengths = [world_load_fn(f).shape[0] for f in world_files]
idxs = [idx for idx in range(len(world_files)) if world_lengths[idx] > world_length_threshold]
if len(world_files) != len(idxs):
logging.warning(f"Some files are filtered by world length threshold "
f"({len(world_files)} -> {len(idxs)}).")
world_files = [world_files[idx] for idx in idxs]
# assert the number of files
assert len(world_files) != 0, f"Not found any world files in ${world_list}."
self.world_files = world_files
self.world_load_fn = world_load_fn
self.return_filename = return_filename
self.allow_cache = allow_cache
self.fs = fs
self.hop_size = hop_size
if allow_cache:
# NOTE(kan-bayashi): Manager is need to share memory in dataloader with num_workers > 0
self.manager = Manager()
self.caches = self.manager.list()
self.caches += [() for _ in range(len(world_files))]
# define feature pre-processing funtion
scaler = StandardScaler()
scaler.mean_ = read_hdf5(stats, mean_path)
scaler.scale_ = read_hdf5(stats, scale_path)
# for version 0.23.0, this information is needed
scaler.n_features_in_ = scaler.mean_.shape[0]
self.feat_transform = lambda x: scaler.transform(x)
def __getitem__(self, idx):
"""Get specified idx items.
Args:
idx (int): Index of the item.
Returns:
str: Filename (only in return_filename = True).
ndarray: Feature (T', C).
"""
if self.allow_cache and len(self.caches[idx]) != 0:
return self.caches[idx]
world = self.world_load_fn(self.world_files[idx])
# feature pre-processing
world = self.feat_transform(world)
if self.return_filename:
if self.allow_cache:
self.caches[idx] = self.world_files[idx], world
return self.world_files[idx], world
else:
if self.allow_cache:
self.caches[idx] = world
return world
def __len__(self):
"""Return dataset length.
Returns:
int: The length of dataset.
"""
return len(self.world_files)
| 38.363889 | 106 | 0.591268 | 1,755 | 13,811 | 4.464387 | 0.105983 | 0.052329 | 0.016847 | 0.01404 | 0.813146 | 0.788385 | 0.740268 | 0.715763 | 0.693427 | 0.65769 | 0 | 0.007761 | 0.318949 | 13,811 | 359 | 107 | 38.470752 | 0.825218 | 0.301716 | 0 | 0.734043 | 0 | 0 | 0.06872 | 0 | 0 | 0 | 0 | 0 | 0.037234 | 1 | 0.053191 | false | 0 | 0.042553 | 0 | 0.180851 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
8e8af7eff15ebd9f6b013ee914575257aa3bdd81 | 20 | py | Python | OtherLanguages/Python/lerc/__init__.py | zakjan/lerc | 3f523fee2b5764f2029e035c41a2325b6360a29d | [
"Apache-2.0"
] | 157 | 2015-12-17T22:21:39.000Z | 2021-12-18T09:01:30.000Z | OtherLanguages/Python/lerc/__init__.py | zakjan/lerc | 3f523fee2b5764f2029e035c41a2325b6360a29d | [
"Apache-2.0"
] | 71 | 2015-12-18T02:29:05.000Z | 2022-03-12T01:24:39.000Z | OtherLanguages/Python/lerc/__init__.py | zakjan/lerc | 3f523fee2b5764f2029e035c41a2325b6360a29d | [
"Apache-2.0"
] | 55 | 2015-12-18T00:54:07.000Z | 2021-12-28T19:52:26.000Z | from ._lerc import * | 20 | 20 | 0.75 | 3 | 20 | 4.666667 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.15 | 20 | 1 | 20 | 20 | 0.823529 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
d912cb94d284b1c8139d0c5ce4904050a6506fef | 39 | py | Python | phylogeny/__init__.py | mroctavious/Phylogeny | 014461b5ec6323f42cf1c913f6a9bdba42e3bc05 | [
"MIT"
] | 2 | 2020-01-17T17:19:15.000Z | 2021-04-18T22:27:59.000Z | phylogeny/__init__.py | mroctavious/Phylogeny | 014461b5ec6323f42cf1c913f6a9bdba42e3bc05 | [
"MIT"
] | null | null | null | phylogeny/__init__.py | mroctavious/Phylogeny | 014461b5ec6323f42cf1c913f6a9bdba42e3bc05 | [
"MIT"
] | 2 | 2018-08-30T20:57:37.000Z | 2020-09-09T06:29:02.000Z | from .core import DistanceMatrix, Tree
| 19.5 | 38 | 0.820513 | 5 | 39 | 6.4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.128205 | 39 | 1 | 39 | 39 | 0.941176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
d928a9c10ed3f105090d8a898e1e8488d0ba1f0c | 39 | py | Python | bartpy/linops/__init__.py | pehses/bartpy | 83ba894707f8aae2edc156bd9c31ac478a4bd966 | [
"BSD-3-Clause"
] | 4 | 2021-08-15T12:57:49.000Z | 2022-02-17T03:38:49.000Z | bartpy/linops/__init__.py | mrirecon/bartpy | 4043e28d4a98ad6d518d8aacce687b50df34789a | [
"BSD-3-Clause"
] | 2 | 2021-12-15T16:15:53.000Z | 2022-03-20T17:18:04.000Z | bartpy/linops/__init__.py | mrirecon/bartpy | 4043e28d4a98ad6d518d8aacce687b50df34789a | [
"BSD-3-Clause"
] | 5 | 2021-07-12T11:15:10.000Z | 2022-03-20T16:36:43.000Z | from .linop import *
from .ops import * | 19.5 | 20 | 0.717949 | 6 | 39 | 4.666667 | 0.666667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.179487 | 39 | 2 | 21 | 19.5 | 0.875 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
d944e4c63df526e56966754d61580df7a7c23c2a | 118 | py | Python | vox_parser/__init__.py | insidemirage/schematic-tools | b0dbe02a0bc13c354c40d67f32d38c6753add4c0 | [
"MIT"
] | null | null | null | vox_parser/__init__.py | insidemirage/schematic-tools | b0dbe02a0bc13c354c40d67f32d38c6753add4c0 | [
"MIT"
] | null | null | null | vox_parser/__init__.py | insidemirage/schematic-tools | b0dbe02a0bc13c354c40d67f32d38c6753add4c0 | [
"MIT"
] | null | null | null | from .parser import VoxelParser
from .parser_exceptions import *
from .default_palette import *
from .models import *
| 23.6 | 32 | 0.805085 | 15 | 118 | 6.2 | 0.533333 | 0.215054 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.135593 | 118 | 4 | 33 | 29.5 | 0.911765 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
794df136f39b9e2cfa450f252b3c4e9dff9be930 | 1,139 | py | Python | scripts/fp_quan/run_fixedp_quan.py | deep-fry/mayo | 7211a11fdb9bb0a036d496a3eba16c96db122f89 | [
"MIT"
] | 110 | 2018-06-07T17:52:29.000Z | 2022-03-28T08:04:02.000Z | scripts/fp_quan/run_fixedp_quan.py | kypomon/mayo | 7211a11fdb9bb0a036d496a3eba16c96db122f89 | [
"MIT"
] | 6 | 2019-10-17T12:00:29.000Z | 2021-10-21T13:41:22.000Z | scripts/fp_quan/run_fixedp_quan.py | kypomon/mayo | 7211a11fdb9bb0a036d496a3eba16c96db122f89 | [
"MIT"
] | 22 | 2018-07-05T01:30:49.000Z | 2021-10-19T06:15:40.000Z | import yaml
import os
import subprocess
mayo_dir = "../../"
gpus = [0, 1]
model='mobilenet_v1'
cmd_formatter = './my datasets/imagenet.yaml models/override/{}.yaml models/override/quantize/fixed_incremental.yaml trainers/cifarnet.yaml system.checkpoint.load=pretrained train.learning_rate._initial=0.01 train.learning_rate.decay_steps=10 system.max_epochs=30 system.checkpoint.save.interval=1 system.num_gpus=2 system.visible_gpus=[{},{}] train.learning_rate._default_batch_size=256 system.batch_size_per_gpu=128 reset-num-epochs ttrain'
eval_cmd_formatter = './my datasets/imagenet.yaml models/override/{}.yaml models/override/quantize/fixed_incremental.yaml trainers/cifarnet.yaml system.checkpoint.load=pretrained train.learning_rate._initial=0.01 train.learning_rate.decay_steps=10 system.max_epochs=30 system.checkpoint.save.interval=1 system.num_gpus=2 system.visible_gpus=[{},{}] eval-all'
cmd = cmd_formatter.format(model, gpus[0], gpus[1])
subprocess.call(cmd, cwd=mayo_dir, shell=True)
subprocess.call(eval_cmd, cwd=mayo_dir, shell=True)
subprocess.call("cp eval_all.csv eval_all{}.csv".format(model), cwd=mayo_dir, shell=True) | 81.357143 | 442 | 0.808604 | 176 | 1,139 | 5.034091 | 0.352273 | 0.073363 | 0.095937 | 0.05079 | 0.727991 | 0.706546 | 0.706546 | 0.706546 | 0.625282 | 0.625282 | 0 | 0.026977 | 0.05619 | 1,139 | 14 | 443 | 81.357143 | 0.797209 | 0 | 0 | 0 | 0 | 0.166667 | 0.707895 | 0.54386 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
799a23fcf4235f59dc063becf77f8a0c4c92ce7c | 163,536 | py | Python | odoo_hubspot/models/importtohubspot.py | sagar-organiztion/custom_repo2 | 30687143b3b6a7820305075d15fd15fbd61141d1 | [
"Apache-2.0"
] | null | null | null | odoo_hubspot/models/importtohubspot.py | sagar-organiztion/custom_repo2 | 30687143b3b6a7820305075d15fd15fbd61141d1 | [
"Apache-2.0"
] | null | null | null | odoo_hubspot/models/importtohubspot.py | sagar-organiztion/custom_repo2 | 30687143b3b6a7820305075d15fd15fbd61141d1 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
import logging
import re
from odoo.exceptions import ValidationError
from odoo import _, api, fields, models, modules, SUPERUSER_ID, tools
from datetime import datetime
import datetime
import requests
import json
import urllib
import html2text
import urllib.request
import os
import base64
_logger = logging.getLogger(__name__)
_image_dataurl = re.compile(r'(data:image/[a-z]+?);base64,([a-z0-9+/]{3,}=*)([\'"])', re.I)
class HubspotImportIntegration(models.Model):
_name = 'hubspot.import.integration'
field_name = fields.Char('Hubspot')
start = fields.Datetime('Start from')
end = fields.Datetime('Till')
import_company = fields.Boolean('Import companies', store=True)
import_contact = fields.Boolean('Import contacts', store=True)
import_deal = fields.Boolean('Import deals', store=True)
import_ticket = fields.Boolean('Import tickets', store=True)
custom_date_range = fields.Boolean(string='Custom Date Range Sync')
company_last_offfssset = fields.Char("Company offset")
contact_last_offsetss = fields.Char("Contact Offset")
ticket_last_offsetss = fields.Char("Ticket Offset")
def read_file(self, file_name):
try:
lines = []
if file_name == 'contacts':
lines = ['aapt_ar_','business_unit','demo',
'did_they_go_to_a_new_school_district_company_','iacp','lead_type','napt',
'no_longer_at_school_district_company','planned_retirement_date','population',
'product_i_m_interested_in','purchased_list_july','purchasing_influence','remove','reports_to',
'request_a_demo','role','s247_secondary_company','state_or_province',
'state_or_region','surveillance_247_area_code','surveillance_247_district_name',
'surveillance_247_district_website_domain','territory','what_school_district_company_did_they_go_',
'what_type_of_support','why_not_at_school_district_company_','years_with_company',
'zoom_webinar_attendance_average_duration','zoom_webinar_attendance_count','zoom_webinar_joinlink',
'zoom_webinar_registration_count','aasbo_az_','address2','asta_al_','casbo_ca_',
'casto_ca_','full_name','accounting_contact_full_name','cgcs','accounting_email','cptc_cn_',
'crtc_wa_','purchasing_contact_full_name','cspta_co_','purchasing_email','ctaa',
'division_cf_contact','fpta_ctd','gapt_ga_','last_rma_email_date',
'gcapt_tx_','famtec_customer','iapt_il_','famtec_sales_rep','iapt_id_',
'bus_garage','ipta_ia_','kspta_ks_','mapt_mi_','mapt_mo_','mnapt_mn_','n247_dvr_total','as_of_date',
'msboa_mn_','cameras','napt_na_','external_camera','ncpta_nc_','ncst','special_instructions',
'area_code','nsba_na_','job_title_secondary','nsta_mid','nsta_summer','unique_identifier',
'nsta_national','solution_currently_installed','oapt_oh_','oapt_ok_','oasbo_on_','oasbo_osba',
'opta_or_','osbma_oh_','sbx','scapt_sc_','sesptc','stai_in_','stn','taa_az_','tapt_tn_','tapt_tx_',
'transfinder','tsd','uapt_ut_','vapt_va_','wapt_wa_','wpta_wy_','wsba_wi_','wvapt_wv_',
'chapter_meeting_1','sts_of_nj']
elif file_name == 'companies':
lines = [
'bid_potential','bid_status','business_vertical','business_vertical_other_','camera_system',
'camera_system_other_','cameras','competitor','contract_expires','contracted_services',
'dealer_sold_through','e360_cameras','external_camera','fleet_maintenance_system',
'fleet_maintenance_system_other_','fleet_size_s247','gps','gps_vendor','gps_vendor_other_','how_many_lots_',
'issr','n247_bus_saleman','n247s_lifecycle_stage','netsuite_refresh','company_type',
'number_of_sales_personnel','number_of_special_needs_students_transported',
'of_buses','of_cameras_per_bus','of_students_total','of_students_transported',
'parent_portal','parent_portal_other_','parent_portal_system','preferred_camera_vendor','preferred_camera_vendor_cloned_',
'previous_camera_system','products','prospect_status_s247','purchase_date','purchased_list_july','remove','rfp_date_posted',
'routing','routing_solution','routing_solution_other_','rsm','s247_contact_email',
's247_county','s247_first_name','s247_last_name','s247_lead_contact','s247_pre_post_salutation','s247_title',
'sales_rep','school_year_budget_begins','school_year_start','service_agreement',
'sic_code','stop_arm_camera_s_','student_count','student_information_system','student_information_system_other_',
'student_tracking','student_tracking_system','student_tracking_system_other_','surveillance_247_company_domain',
'surveillance_247_district','system','td_fleet_monitor','territory','touchdown',
'touchdown_cloud_services_amount','touchdown_cloud_services_renewal_date','touchdown_install_date','wireless_s247',
'internal_id','new_id','lot_1_address','status','fleet_size','lot_2_address','netsuite_customer','netsuite_status',
'bid_awarded_year','bus_garage','n247_dvr_total','special_instructions','area_code','vendor',
'dealer_sub_type','unique_identifier','opportunity_number','contractor','minitrack','erie_1_boces','bid_reference',
]
elif file_name == 'deals':
lines = [
'deal_entered_current_deal_stage', 'dealers_quoting_this_deal', 'end_user', 'isr',
'lost_reason_notes', 'n247s_lifecycle_stage', 'opportunity_link', 'product_s_considered',
'sales_order', 'state', 'opportunity_number'
]
elif file_name == 'tickets':
lines = ['assigned_company', 'cs_number', 'product', 'pw_resolution', 'rn_number', 's247_resolution',
's247_product', 'touchdown']
property_url = ''
for line in lines:
property_url = property_url + '&properties=' + line
return property_url
except Exception as e:
raise ValidationError(str(e))
def add_properties(self, odoo_obj, hubspot_obj, name, model):
try:
m2m_list = []
date_fields = ['contract_expires', 'school_year_budget_begins', 'school_year_start',
'touchdown_cloud_services_renewal_date', 'touchdown_install_date', 'date_of_birth',
'planned_retirement_date', 'last_rma_email_date', 'request_a_demo',
'closedate', 'first_conversion_date', 'recent_conversion_date',
'first_contact_createdate', 'first_deal_created_date', 'notes_last_updated',
'hs_last_booked_meeting_date', 'notes_last_contacted', 'hs_last_logged_call_date',
'hs_lastmodifieddate', 'hs_last_open_task_date', 'hs_last_sales_activity_timestamp',
'hubspot_owner_assigneddate', 'recent_deal_close_date',
'hs_analytics_first_timestamp', 'hs_analytics_last_timestamp',
'hs_analytics_first_visit_timestamp', 'hs_analytics_last_visit_timestamp',
]
if name == 'contacts':
m2m_list = [
'asta_al_', 'aasbo_az_', 'aapt_ar_',
'wvapt_wv_', 'wsba_wi_', 'wpta_wy_', 'wapt_wa_', 'vapt_va_', 'uapt_ut_',
'tsd', 'transfinder', 'tapt_tx_', 'tapt_tn_', 'taa_az_', 'sts_of_nj', 'stn',
'stai_in_', 'sesptc', 'scapt_sc_', 'sbx', 'osbma_oh_', 'opta_or_', 'oasbo_osba',
'oasbo_on_', 'oapt_ok_', 'oapt_oh_', 'nsta_summer', 'nsta_national', 'nsta_mid',
'nsba_na_', 'ncst', 'ncpta_nc_', 'napt_na_', 'napt', 'msboa_mn_', 'mnapt_mn_',
'mapt_mo_', 'mapt_mi_', 'kspta_ks_', 'ipta_ia_', 'iapt_il_', 'iapt_id_', 'gcapt_tx_',
'gapt_ga_', 'fpta_ctd', 'ctaa', 'cspta_co_', 'crtc_wa_', 'cptc_cn_', 'chapter_meeting_1',
'cgcs', 'casto_ca_', 'casbo_ca_', 'business_unit', 'buying_role', 'what_type_of_support'
]
elif name == 'companies':
m2m_list = ['system', 'dealer_sold_through', 'camera_system', 'how_many_lots_', 'competitor',
'previous_camera_system']
elif name == 'deals':
m2m_list = ['dealers_quoting_this_deal', 'product_s_considered']
elif name == 'tickets':
m2m_list = ['s247_product']
else:
print("hello")
lines = []
if name == 'contacts':
lines = ['aapt_ar_', 'business_unit', 'demo',
'did_they_go_to_a_new_school_district_company_', 'iacp', 'lead_type',
'napt',
'no_longer_at_school_district_company', 'planned_retirement_date', 'population',
'product_i_m_interested_in', 'purchased_list_july', 'purchasing_influence', 'remove', 'reports_to',
'request_a_demo', 'role', 's247_secondary_company',
'state_or_province',
'state_or_region', 'surveillance_247_area_code', 'surveillance_247_district_name',
'surveillance_247_district_website_domain', 'territory',
'what_school_district_company_did_they_go_',
'what_type_of_support', 'why_not_at_school_district_company_', 'years_with_company',
'zoom_webinar_attendance_average_duration', 'zoom_webinar_attendance_count',
'zoom_webinar_joinlink',
'zoom_webinar_registration_count', 'aasbo_az_', 'address2', 'asta_al_', 'casbo_ca_',
'casto_ca_', 'accounting_contact_full_name', 'cgcs', 'accounting_email', 'cptc_cn_',
'crtc_wa_', 'purchasing_contact_full_name', 'cspta_co_', 'purchasing_email', 'ctaa',
'division_cf_contact', 'fpta_ctd', 'gapt_ga_', 'last_rma_email_date',
'gcapt_tx_', 'famtec_customer', 'iapt_il_', 'famtec_sales_rep', 'iapt_id_',
'bus_garage', 'ipta_ia_', 'kspta_ks_', 'mapt_mi_', 'mapt_mo_', 'mnapt_mn_', 'n247_dvr_total',
'as_of_date',
'msboa_mn_', 'cameras', 'napt_na_', 'external_camera', 'ncpta_nc_', 'ncst', 'special_instructions',
'area_code', 'nsba_na_', 'job_title_secondary', 'nsta_mid', 'nsta_summer', 'unique_identifier',
'nsta_national', 'solution_currently_installed', 'oapt_oh_', 'oapt_ok_', 'oasbo_on_', 'oasbo_osba',
'opta_or_', 'osbma_oh_', 'sbx', 'scapt_sc_', 'sesptc', 'stai_in_', 'stn', 'taa_az_', 'tapt_tn_',
'tapt_tx_',
'transfinder', 'tsd', 'uapt_ut_', 'vapt_va_', 'wapt_wa_', 'wpta_wy_', 'wsba_wi_', 'wvapt_wv_',
'chapter_meeting_1', 'sts_of_nj']
elif name == 'companies':
lines = [
'bid_potential', 'bid_status', 'business_vertical', 'business_vertical_other_', 'camera_system',
'camera_system_other_', 'cameras', 'competitor', 'contract_expires',
'contracted_services',
'dealer_sold_through', 'e360_cameras', 'external_camera', 'fleet_maintenance_system',
'fleet_maintenance_system_other_', 'fleet_size_s247', 'gps', 'gps_vendor', 'gps_vendor_other_',
'how_many_lots_',
'issr', 'n247_bus_saleman', 'n247s_lifecycle_stage', 'netsuite_refresh', 'company_type',
'number_of_sales_personnel', 'number_of_special_needs_students_transported',
'of_buses', 'of_cameras_per_bus', 'of_students_total',
'of_students_transported',
'parent_portal', 'parent_portal_other_', 'parent_portal_system', 'preferred_camera_vendor',
'preferred_camera_vendor_cloned_',
'previous_camera_system', 'products', 'prospect_status_s247', 'purchase_date', 'purchased_list_july',
'remove', 'rfp_date_posted',
'routing', 'routing_solution', 'routing_solution_other_', 'rsm', 's247_contact_email',
's247_county', 's247_first_name', 's247_last_name', 's247_lead_contact', 's247_pre_post_salutation',
's247_title',
'sales_rep', 'school_year_budget_begins', 'school_year_start', 'service_agreement',
'sic_code', 'stop_arm_camera_s_', 'student_count', 'student_information_system',
'student_information_system_other_',
'student_tracking', 'student_tracking_system', 'student_tracking_system_other_',
'surveillance_247_company_domain',
'surveillance_247_district', 'system', 'td_fleet_monitor', 'territory',
'touchdown',
'touchdown_cloud_services_amount', 'touchdown_cloud_services_renewal_date', 'touchdown_install_date',
'wireless_s247',
'internal_id', 'new_id', 'lot_1_address', 'status', 'fleet_size', 'lot_2_address', 'netsuite_customer',
'netsuite_status',
'bid_awarded_year', 'bus_garage', 'n247_dvr_total', 'special_instructions', 'area_code',
'vendor',
'dealer_sub_type', 'unique_identifier', 'opportunity_number', 'contractor', 'minitrack', 'erie_1_boces',
'bid_reference', 'about_us', 'closedate', 'description', 'facebook_company_page',
'facebookfans', 'first_conversion_event_name', 'first_conversion_date',
'hs_analytics_first_touch_converting_campaign', 'hs_ideal_customer_profile', 'is_public', 'nadp',
'hs_num_contacts_with_buying_roles', 'hs_num_decision_makers', 'numberofemployees',
'num_conversion_events', 'hs_num_open_deals', 'hs_analytics_num_page_views', 'hs_analytics_num_visits',
'num_contacted_notes', 'recent_conversion_event_name', 'recent_conversion_date',
'engagements_last_meeting_booked_source', 'total_revenue', 'founded_year',
# 'hs_analytics_last_touch_converting_campaign', 'engagements_last_meeting_booked_medium',
'hs_num_child_companies', 'recent_deal_amount', 'total_money_raised', 'hs_total_deal_value'
'hs_total_deal_value', 'number_of_buses', 'hubspot_team_id'
]
# 'wireless''customer_rating'
elif name == 'deals':
lines = [
'deal_entered_current_deal_stage', 'dealers_quoting_this_deal', 'end_user', 'isr',
'lost_reason_notes', 'n247s_lifecycle_stage', 'opportunity_link', 'product_s_considered',
'sales_order', 'state', 'opportunity_number'
]
elif name == 'tickets':
lines = ['assigned_company', 'cs_number', 'product', 'pw_resolution', 'rn_number', 's247_resolution',
's247_product', 'touchdown']
else:
print("Hellossss")
for line in lines:
if hubspot_obj.get(line):
if line in m2m_list:
odoo_obj.update({
line: [[6, 0, self.add_m2m_values(hubspot_obj[line]['value'], line, model)]]
})
else:
if line in date_fields:
date_convert = hubspot_obj[line]['value']
date_value = datetime.datetime.fromtimestamp(int(date_convert[:-3]))
odoo_obj.update({
line: date_value
})
else:
if hubspot_obj[line]['value'] != 'false':
state_fields = ['state_or_province', 'state_or_region']
if line in state_fields:
odoo_state = self.env['res.country.state'].search([('name', '=', hubspot_obj[line]['value'])])
odoo_obj.update({
line: odoo_state.id if odoo_state else None
})
else:
odoo_obj.update({
line: hubspot_obj[line]['value'] if hubspot_obj[line]['value'] else None
})
except Exception as e:
raise ValidationError(str(e))
def add_m2m_values(self, values, line, model):
try:
value_ids = []
fields = [
'asta_al_', 'aasbo_az_', 'aapt_ar_',
'wvapt_wv_', 'wsba_wi_', 'wpta_wy_', 'wapt_wa_', 'vapt_va_', 'uapt_ut_',
'tsd', 'transfinder', 'tapt_tx_', 'tapt_tn_', 'taa_az_', 'sts_of_nj', 'stn',
'stai_in_', 'sesptc', 'scapt_sc_', 'sbx', 'osbma_oh_', 'opta_or_', 'oasbo_osba',
'oasbo_on_', 'oapt_ok_', 'oapt_oh_', 'nsta_summer', 'nsta_national', 'nsta_mid',
'nsba_na_', 'ncst', 'ncpta_nc_', 'napt_na_', 'napt', 'msboa_mn_', 'mnapt_mn_',
'mapt_mo_', 'mapt_mi_', 'kspta_ks_', 'ipta_ia_', 'iapt_il_', 'iapt_id_', 'gcapt_tx_',
'gapt_ga_', 'fpta_ctd', 'ctaa', 'cspta_co_', 'crtc_wa_', 'cptc_cn_', 'chapter_meeting_1',
'cgcs', 'casto_ca_', 'casbo_ca_']
if model == 'res.partner' and line in fields:
for value in values.split(';'):
odoo_value = self.env['res.partner_years'].search([('name', '=', value)])
if not odoo_value:
odoo_value = self.env['res.partner_years'].create({
'name': value,
})
self.env.cr.commit()
value_ids.append(odoo_value.id)
else:
for value in values.split(';'):
odoo_value = self.env[str(model) + '_' + str(line)].search([('name', '=', value)])
if not odoo_value:
odoo_value = self.env[str(model) + '_' + str(line)].create({
'name': value,
})
self.env.cr.commit()
value_ids.append(odoo_value.id)
return value_ids
except Exception as e:
raise ValidationError(str(e))
def import_contacts(self):
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
hubspot_ids = []
if not hubspot_keys:
raise ValidationError('Please! Enter Hubspot key...')
else:
try:
get_all_contacts_url = "https://api.hubapi.com/contacts/v1/lists/all/contacts/all?"
if self.contact_last_offsetss:
parameter_dict = {'hapikey': hubspot_keys, 'limit': 250, 'vidOffset': int(self.contact_last_offsetss)}
else:
parameter_dict = {'hapikey': hubspot_keys, 'limit': 250}
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
has_more = True
properties = self.read_file('contacts')
while has_more:
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_all_contacts_url + parameters + properties
r = requests.get(url=get_url, headers=headers)
response_dict = json.loads(r.text)
hubspot_ids.extend(self.create_contacts(response_dict['contacts'], hubspot_keys))
has_more = response_dict['has-more']
parameter_dict['vidOffset'] = response_dict['vid-offset']
self.contact_last_offsetss = response_dict['vid-offset']
# return hubspot_ids
except Exception as e:
_logger.error(e)
raise ValidationError(_(str(e)))
def create_contacts(self, contacts, hubspot_keys):
try:
hubspot_ids = []
get_single_contact_url = "https://api.hubapi.com/contacts/v1/contact/vid/"
get_single_company_url = "https://api.hubapi.com/companies/v2/companies/"
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
for contact in contacts:
odoo_company = None
odoo_country = None
state_id = None
contact_url = get_single_contact_url + str(contact['vid']) + '/profile?hapikey=' + hubspot_keys
r = requests.get(url=contact_url, headers=headers)
profile = json.loads(r.text)['properties']
if 'associatedcompanyid' in profile and not profile['associatedcompanyid']['value'] == '':
odoo_company = self.env['res.partner'].search([('hubspot_id', '=', str(profile['associatedcompanyid']['value']))])
if not odoo_company:
get_url = get_single_company_url + str(profile['associatedcompanyid']['value']) + '?hapikey=' + hubspot_keys
company_response = requests.get(url=get_url, headers=headers)
company_profile = json.loads(company_response.content.decode('utf-8'))['properties']
if 'country' in company_profile.keys():
odoo_country = self.env['res.country'].search([('name', '=', company_profile['country']['value'])]).id
if company_profile.get('state', None):
state = company_profile['state']
if state.get('value', None):
state_code = state['value']
odoo_state = self.env['res.country.state'].search(
[('code', '=', state_code), ('country_id', '=', odoo_country)]
)
if len(odoo_state) == 1:
state_id = odoo_state.id
company_values = {
'name': company_profile['name']['value'] if 'name' in company_profile.keys() else '',
'website': company_profile['website']['value'] if 'website' in company_profile.keys() else '',
'street': company_profile['address']['value'] if 'address' in company_profile.keys() else '',
'city': company_profile['city']['value'] if 'city' in company_profile.keys() else '',
'phone': company_profile['phone']['value'] if 'phone' in company_profile.keys() else '',
'zip': company_profile['zip']['value'] if 'zip' in company_profile.keys() else '',
'country_id': odoo_country if odoo_country else None,
'hubspot_id': str(profile['associatedcompanyid']['value']),
'is_company': True,
}
self.add_properties(company_values, company_profile, 'companies', 'res.partner')
odoo_company = self.env['res.partner'].create(company_values)
first_name = profile['firstname']['value'] if 'firstname' in profile else ''
last_name = profile['lastname']['value'] if 'lastname' in profile else ''
name = first_name + ' ' + last_name
odoo_partner = self.env['res.partner'].search([('hubspot_id', '=', str(contact['vid']))])
contact_values = {
'name': name,
'email': profile['email']['value'] if 'email' in profile.keys() else '',
'website': profile['website']['value'] if 'website' in profile.keys() else '',
'city': profile['city']['value'] if 'city' in profile.keys() else '',
'zip': profile['zip']['value'] if 'zip' in profile.keys() else '',
'parent_id': odoo_company.id if odoo_company else None,
'hubspot_id': str(contact['vid']),
'phone': profile['phone']['value'] if 'phone' in profile.keys() else '',
'country_id': odoo_country if odoo_country else None,
'state_id': state_id,
}
self.add_properties(contact_values, profile, 'contacts', 'res.partner')
if not odoo_partner:
new_contact = self.env['res.partner'].create(contact_values)
else:
odoo_partner.write(contact_values)
self.env.cr.commit()
hubspot_ids.append(contact['vid'])
return hubspot_ids
except Exception as e:
_logger.error(e)
raise ValidationError(_(str(e)))
def import_companies(self):
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
hubspot_ids = []
if not hubspot_keys:
raise ValidationError('Please! Enter Hubspot key...')
else:
try:
get_all_companies_url = "https://api.hubapi.com/companies/v2/companies/paged?"
if self.company_last_offfssset:
parameter_dict = {'hapikey': hubspot_keys, 'limit': 250, 'offset': int(self.company_last_offfssset)}
else:
parameter_dict = {'hapikey': hubspot_keys, 'limit': 250}
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
properties = self.read_file('companies')
has_more = True
while has_more:
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_all_companies_url + parameters + properties
r = requests.get(url=get_url, headers=headers)
response_dict = json.loads(r.text)
hubspot_ids.extend(self.create_companies(response_dict['companies'], hubspot_keys))
has_more = response_dict['has-more']
parameter_dict['offset'] = response_dict['offset']
self.company_last_offfssset = response_dict['offset']
except Exception as e:
raise ValidationError(_(str(e)))
def create_companies(self, companies, hubspot_keys):
try:
hubspot_ids = []
get_single_company_url = "https://api.hubapi.com/companies/v2/companies/"
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
for company in companies:
odoo_country = None
state_id = None
get_url = get_single_company_url + str(company['companyId']) + '?hapikey=' + hubspot_keys
company_response = requests.get(url=get_url, headers=headers)
company_data = json.loads(company_response.content.decode('utf-8'))
if 'properties' in company_data:
company_profile = company_data['properties']
odoo_company = self.env['res.partner'].search([('hubspot_id', '=', str(company['companyId']))])
if 'country' in company_profile.keys():
odoo_country = self.env['res.country'].search([('name', '=', company_profile['country']['value'])]).id
if company_profile.get('state', None):
state = company_profile['state']
if state.get('value', None):
state_code = state['value']
odoo_state = self.env['res.country.state'].search(
[('code', '=', state_code), ('country_id', '=', odoo_country)]
)
if len(odoo_state) == 1:
state_id = odoo_state.id
company_values = {
'name': company_profile['name']['value'] if 'name' in company_profile.keys() else '',
'website': company_profile['website']['value'] if 'website' in company_profile.keys() else '',
'street': company_profile['address']['value'] if 'address' in company_profile.keys() else '',
'city': company_profile['city']['value'] if 'city' in company_profile.keys() else '',
'phone': company_profile['phone']['value'] if 'phone' in company_profile.keys() else '',
'zip': company_profile['zip']['value'] if 'zip' in company_profile.keys() else '',
'country_id': odoo_country if odoo_country else None,
'state_id': state_id,
'hubspot_id': str(company['companyId']),
'is_company': True,
}
self.add_properties(company_values, company_profile, 'companies', 'res.partner')
if not odoo_company:
self.env['res.partner'].create(company_values)
else:
odoo_company.write(company_values)
self.env.cr.commit()
hubspot_ids.append(company['companyId'])
return hubspot_ids
except Exception as e:
raise ValidationError((str(e)))
def import_deals(self,):
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
hubspot_ids = []
if not hubspot_keys:
raise ValidationError('Please! Enter Hubspot key...')
else:
try:
get_all_deals_url = "https://api.hubapi.com/deals/v1/deal/paged?"
deal_properties = "&includeAssociations=true&properties=dealstage&properties=dealname" \
"&properties=hs_createdate&properties=hubspot_owner_id&properties=dealtype" \
"&properties=closedate&properties=amount&properties=hs_lastmodifieddate"
parameter_dict = {'hapikey': hubspot_keys, 'limit': 250}
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
has_more = True
while has_more:
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_all_deals_url + parameters + deal_properties
r = requests.get(url=get_url, headers=headers)
response_dict = json.loads(r.text)
hubspot_ids.extend(self.create_deals(response_dict['deals'], hubspot_keys))
has_more = response_dict['hasMore']
parameter_dict['offset'] = response_dict['offset']
# return hubspot_ids
except Exception as e:
_logger.error(e)
raise ValidationError(_(str(e)))
def create_deals(self, deals, hubspot_keys):
try:
hubspot_ids = []
close_date = None
deal_stage = None
i = 0
for deal in deals:
contacts = []
companies = []
if len(deal['associations']['associatedVids']) > 0:
contacts = self.get_contacts(deal['associations']['associatedVids'], hubspot_keys)
if len(deal['associations']['associatedCompanyIds']) > 0:
companies = self.get_companies(deal['associations']['associatedCompanyIds'], hubspot_keys)
odoo_deal = self.env['crm.lead'].search([('hubspot_id', '=', str(deal['dealId']))])
# if 'dealstage' in deal['properties'].keys():
# deal_stage = self.env['crm.stage'].search([('name', '=', deal['properties']['dealstage']['value'])])
# if not deal_stage:
# deal_stage = self.env['crm.stage'].create({
# 'name': deal['properties']['dealstage']['value'],
# 'display_name': deal['properties']['dealstage']['value'],
# })
if 'closedate' in deal['properties'].keys():
if deal['properties']['closedate']['value'] != "":
close_date = datetime.datetime.fromtimestamp(int(deal['properties']['closedate']['value'][:-3]))
deal_values = {
'hubspot_id': str(deal['dealId']),
'name': deal['properties']['dealname']['value'],
'expected_revenue': deal['properties']['amount']['value'] if 'amount' in deal[
'properties'].keys() else None,
# 'stage_id': deal_stage.id if deal_stage else self.env['crm.stage'].search(
# [('name', '=', 'New')]).id,
'date_closed': close_date if close_date else None,
'hs_deal_contacts': [[6, 0, contacts]] if contacts else None,
'hs_deal_companies': companies[0] if companies else None,
'type': 'opportunity'
}
self.add_properties(deal_values, deal, 'deals', 'crm.lead')
if not odoo_deal:
self.env['crm.lead'].create(deal_values)
else:
odoo_deal.write(deal_values)
self.env.cr.commit()
hubspot_ids.append(deal['dealId'])
return hubspot_ids
except Exception as e:
raise ValidationError(_(str(e)))
def get_contacts(self, contactsIds, hubspot_keys):
contact_list = []
get_single_contact_url = "https://api.hubapi.com/contacts/v1/contact/vid/"
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
for contactId in contactsIds:
contact_url = get_single_contact_url + str(contactId) + '/profile?hapikey=' + hubspot_keys
r = requests.get(url=contact_url, headers=headers)
profile = json.loads(r.text)['properties']
first_name = profile['firstname']['value'] if 'firstname' in profile else ''
last_name = profile['lastname']['value'] if 'lastname' in profile else ''
name = first_name + ' ' + last_name
odoo_partner = self.env['res.partner'].search([('hubspot_id', '=', str(contactId))])
if not odoo_partner:
odoo_partner = self.env['res.partner'].create({
'name': name,
'email': profile['email']['value'] if 'email' in profile.keys() else '',
'website': profile['website']['value'] if 'website' in profile.keys() else '',
'city': profile['city']['value'] if 'city' in profile.keys() else '',
'zip': profile['zip']['value'] if 'zip' in profile.keys() else '',
'hubspot_id': str(contactId),
'phone': profile['phone']['value'] if 'phone' in profile.keys() else '',
})
else:
odoo_partner.write({
'name': name,
'email': profile['email']['value'] if 'email' in profile.keys() else '',
'website': profile['website']['value'] if 'website' in profile.keys() else '',
'city': profile['city']['value'] if 'city' in profile.keys() else '',
'zip': profile['zip']['value'] if 'zip' in profile.keys() else '',
'hubspot_id': str(contactId),
'phone': profile['phone']['value'] if 'phone' in profile.keys() else '',
})
contact_list.append(odoo_partner.id)
return contact_list
def get_companies(self, companiesIds, hubspot_keys):
company_list = []
get_single_company_url = "https://api.hubapi.com/companies/v2/companies/"
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
for companyId in companiesIds:
odoo_country = None
get_url = get_single_company_url + str(companyId) + '?hapikey=' + hubspot_keys
company_response = requests.get(url=get_url, headers=headers)
company_profile = json.loads(company_response.content.decode('utf-8'))['properties']
odoo_company = self.env['res.partner'].search([('hubspot_id', '=', str(companyId))])
if 'country' in company_profile.keys():
odoo_country = self.env['res.country'].search([('name', '=', company_profile['country']['value'])]).id
if not odoo_company:
odoo_company = self.env['res.partner'].create({
'name': company_profile['name']['value'] if 'name' in company_profile.keys() else '',
'website': company_profile['website']['value'] if 'website' in company_profile.keys() else '',
'street': company_profile['address']['value'] if 'address' in company_profile.keys() else '',
'city': company_profile['city']['value'] if 'city' in company_profile.keys() else '',
'phone': company_profile['phone']['value'] if 'phone' in company_profile.keys() else '',
'zip': company_profile['zip']['value'] if 'zip' in company_profile.keys() else '',
'country_id': odoo_country if odoo_country else None,
'hubspot_id': str(companyId),
'is_company': True,
})
else:
odoo_company.write({
'name': company_profile['name']['value'] if 'name' in company_profile.keys() else '',
'website': company_profile['website']['value'] if 'website' in company_profile.keys() else '',
'street': company_profile['address']['value'] if 'address' in company_profile.keys() else '',
'city': company_profile['city']['value'] if 'city' in company_profile.keys() else '',
'phone': company_profile['phone']['value'] if 'phone' in company_profile.keys() else '',
'zip': company_profile['zip']['value'] if 'zip' in company_profile.keys() else '',
'country_id': odoo_country if odoo_country else None,
'hubspot_id': str(companyId),
'is_company': True,
})
company_list.append(odoo_company.id)
return company_list
def import_tickets(self):
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
hubspot_ids = []
if not hubspot_keys:
raise ValidationError('Please! Enter Hubspot key...')
else:
try:
get_all_tickets_url = "https://api.hubapi.com/crm-objects/v1/objects/tickets/paged?"
data = "&properties=subject&properties=content&properties=hs_pipeline" \
"&properties=hs_pipeline_stage&properties=hs_ticket_priority" \
"&properties=hs_ticket_category&properties=hubspot_owner_id" \
"&properties=source_type&properties=hs_createdate&properties=createdate" \
"&properties=hs_lastmodifieddate"
if self.ticket_last_offsetss:
parameter_dict = {'hapikey': hubspot_keys, 'limit': 250, 'offset': int(self.ticket_last_offsetss)}
else:
parameter_dict = {'hapikey': hubspot_keys, 'limit': 250}
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
properties = self.read_file('tickets')
has_more = True
while has_more:
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_all_tickets_url + parameters + data + properties
r = requests.get(url=get_url, headers=headers)
response_dict = json.loads(r.text)
hubspot_ids.extend(self.create_tickets(response_dict['objects'], hubspot_keys))
has_more = response_dict['hasMore']
parameter_dict['offset'] = response_dict['offset']
self.ticket_last_offsetss = response_dict['offset']
# return hubspot_ids
except Exception as e:
_logger.error(e)
raise ValidationError(_(str(e)))
def create_tickets(self, tickets, hubspot_keys):
try:
hubspot_ids = []
get_association_url = 'https://api.hubapi.com/crm-associations/v1/associations/'
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
for ticket in tickets:
contacts = []
companies = []
tag_ids = []
priority = None
get_ticket_contact_url = get_association_url + str(ticket['objectId']) + '/HUBSPOT_DEFINED/16?hapikey=' + hubspot_keys
contact_response = requests.get(url=get_ticket_contact_url, headers=headers)
contact_info = json.loads(contact_response.content.decode('utf-8'))['results']
contacts = self.get_contacts(contact_info, hubspot_keys)
get_ticket_company_url = get_association_url + str(
ticket['objectId']) + '/HUBSPOT_DEFINED/26?hapikey=' + hubspot_keys
company_response = requests.get(url=get_ticket_company_url, headers=headers)
company_info = json.loads(company_response.content.decode('utf-8'))['results']
companies = self.get_companies(company_info, hubspot_keys)
if 'source_type' in ticket['properties']:
odoo_type = self.env['helpdesk.ticket.type'].search([('name', '=', ticket['properties']['source_type']['value'])])
if not odoo_type:
odoo_type = self.env['helpdesk.ticket.type'].create({
'name': ticket['properties']['source_type']['value'],
})
odoo_stage = None
# if 'hs_pipeline_stage' in ticket['properties']:
# odoo_stage = self.env['helpdesk.stage'].search([('name', '=', ticket['properties']['hs_pipeline_stage']['value'])])
# if not odoo_stage:
# odoo_stage = self.env['helpdesk.stage'].create({
# 'name': ticket['properties']['hs_pipeline_stage']['value'],
# })
if 'hs_ticket_category' in ticket['properties']:
tags = ticket['properties']['hs_ticket_category']['value'].split(';')
for tag in tags:
odoo_tag = self.env['helpdesk.tag'].search([('name', '=', tag)])
if not odoo_tag:
odoo_tag = self.env['helpdesk.tag'].create({
'name': tag,
})
tag_ids.append(odoo_tag.id)
if 'hs_ticket_priority' in ticket['properties']:
if ticket['properties']['hs_ticket_priority']['value'] == 'LOW':
priority = '1'
elif ticket['properties']['hs_ticket_priority']['value'] == 'MEDIUM':
priority = '2'
elif ticket['properties']['hs_ticket_priority']['value'] == 'HIGH':
priority = '3'
else:
priority = '0'
odoo_ticket = self.env['helpdesk.ticket'].search([('hubspot_id', '=', str(ticket['objectId']))])
ticket_values = {
'hubspot_id': str(ticket['objectId']),
'name': ticket['properties']['subject']['value'] if 'subject' in ticket['properties'] else " ",
'priority': priority,
# 'stage_id': odoo_stage.id if odoo_stage else None,
'ticket_type_id': odoo_type.id,
'tag_ids': [[6, 0, tag_ids]],
'hs_ticket_contacts': [[6, 0, contacts]] if contacts else None,
'hs_ticket_company': companies[0] if companies else None,
}
self.add_properties(ticket_values, ticket['properties'], 'tickets', 'helpdesk.ticket')
if not odoo_ticket:
self.env['helpdesk.ticket'].create(ticket_values)
else:
odoo_ticket.write(ticket_values)
self.env.cr.commit()
hubspot_ids.append(ticket['objectId'])
return hubspot_ids
except Exception as e:
raise ValidationError(_(str(e)))
def get_company_engagements(self):
try:
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
companies = self.env['res.partner'].search([('hubspot_id', '!=', False),
('is_company', '=', True),
('engagement_done', '=', True)]
)
for odoo_company in companies:
get_associated_engagement_url = "https://api.hubapi.com/engagements/v1/engagements/associated/" \
"COMPANY/{0}/paged?".format(odoo_company.hubspot_id)
parameter_dict = {'hapikey': hubspot_keys, 'limit': 100}
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
has_more = True
while has_more:
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_associated_engagement_url + parameters
response = requests.get(url=get_url, headers=headers)
res_data = json.loads(response.content.decode("utf-8"))
engagements = res_data['results']
for engagement in engagements:
engagement_data = engagement['engagement']
odoo_message = self.env['mail.message'].search([('engagement_id', '=', engagement_data['id'])])
odoo_activity = self.env['mail.activity'].search([('engagement_id', '=', engagement_data['id'])])
if odoo_message or odoo_activity:
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_company.name,
'description': 'Record already exists',
'skip': False,
'model': 'Company-res.partner',
})
self.env.cr.commit()
continue
association_data = engagement['associations']
meta_data = engagement['metadata']
if engagement_data['type'] in ['EMAIL', 'INCOMING_EMAIL']:
if not meta_data.get('from'):
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'description': 'Coming engagement email type has no \'from\' that is why skipped',
'skip': True,
'model': 'res.partner',
})
self.env.cr.commit()
continue
try:
print('Creating Email Engagement against the company', odoo_company.name)
author = self.env['res.partner'].search([('email', '=', meta_data['from']['email'])])
if len(author) > 1:
author = author[0]
odoo_comment = self.env['mail.message'].create({
'engagement_id': engagement_data['id'],
'message_type': 'email',
'body': meta_data['text'],
'create_date': datetime.datetime.fromtimestamp(
int(str(engagement_data['createdAt'])[:-3])),
'display_name': author.name if author.name else None,
'email_from': meta_data['from'],
# comment.author.email if comment.author.email else None,
'author_id': author.id if author else None,
'model': 'res.partner',
'res_id': odoo_company.id
})
self.env.cr.commit()
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_company.name,
'description': 'Email: New Created',
'skip': False,
'model': 'Company-res.partner',
})
self.env.cr.commit()
except Exception as e:
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_company.name,
'description': 'EMAIL: Skipped because of error while creating(' + str(e) + ')',
'skip': True,
'model': 'Company-res.partner',
})
self.env.cr.commit()
pass
# elif engagement_data['type'] == 'NOTE':
# try:
# print('Creating Note Engagement against the company', odoo_company.name)
# author_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'notification',
# 'body': engagement_data['bodyPreview'] if engagement_data.get('bodyPreview') else None,
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'res.partner',
# 'res_id': odoo_company.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'Note: New Created',
# 'skip': False,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'NOTE: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# pass
# elif engagement_data['type'] == 'TASK':
# try:
# print('Creating TASK Engagement against the company', odoo_company.name)
# if meta_data['status'] != 'COMPLETED':
# print(odoo_company.name)
# user_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Todo')])
# partner_model = self.env['ir.model'].search([('model', '=', 'res.partner')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_company.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['subject'],
# 'hubspot_status': meta_data['status'],
# 'note': meta_data['body'] if meta_data.get('body') else None,
# 'forObjectType': meta_data['forObjectType'],
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['completionDate'])[:-3])) if meta_data.get(
# 'completionDate') else datetime.datetime.now(),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'Task: New Created',
# 'skip': False,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# else:
# print('message created for task', odoo_company.name)
# author_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'comment',
# # 'from': odoo_contact.email,
# 'body': meta_data['body'] if meta_data.get('body') else meta_data['subject'],
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'res.partner',
# 'res_id': odoo_company.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'Task: New Created(Completed)',
# 'skip': False,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'TASK: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# pass
# elif engagement_data['type'] == 'CALL':
# try:
# print('Creating Call Engagement against the company', odoo_company.name)
# if meta_data['status'] != 'COMPLETED':
# print(odoo_company.name)
# user_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Call')])
# partner_model = self.env['ir.model'].search([('model', '=', 'res.partner')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_company.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['subject'] if meta_data.get('subject') else meta_data[
# 'body'] if meta_data.get('body') else None,
# 'hubspot_status': meta_data['status'],
# 'note': html2text.html2text(meta_data['body']) if meta_data.get('body') else None,
# 'toNumber': meta_data['toNumber'] if meta_data.get('toNumber') else None,
# 'fromNumber': meta_data['fromNumber'] if meta_data.get('fromNumber') else None,
# 'durationMilliseconds': str(meta_data['durationMilliseconds']) if meta_data.get(
# 'durationMilliseconds') else None,
# 'recordingUrl': meta_data['recordingUrl'] if meta_data.get(
# 'recordingUrl') else None,
# 'disposition': meta_data['disposition'] if meta_data.get('disposition') else None,
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['completionDate'])[:-3])) if meta_data.get(
# 'completionDate') else datetime.datetime.now(),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'Call: New Created',
# 'skip': False,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# else:
# print('message created for call', odoo_company.name)
# author_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'message_type': 'comment',
# 'engagement_id': engagement_data['id'],
# 'body': meta_data['body'] if meta_data.get('body') else meta_data[
# 'subject'] if meta_data.get('subject') else None,
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'res.partner',
# 'res_id': odoo_company.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'Call: New Created(Completed)',
# 'skip': False,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'CALL: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# pass
#
# elif engagement_data['type'] == 'MEETING':
# try:
# print('Creating Meeting Engagement against the company', odoo_company.name)
# end_time = datetime.datetime.fromtimestamp(int(str(meta_data['endTime'])[:-3]))
# if end_time > datetime.datetime.now():
# print(odoo_company.name)
# user_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Meeting')])
# partner_model = self.env['ir.model'].search([('model', '=', 'res.partner')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_company.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['title'] if meta_data.get('title') else meta_data[
# 'body'] if meta_data.get('body') else None,
# 'note': meta_data['body'] if meta_data.get('body') else None,
# 'startTime': datetime.datetime.fromtimestamp(
# int(str(meta_data['startTime'])[:-3])) if meta_data.get(
# 'startTime') else datetime.datetime.now(),
# 'endTime': datetime.datetime.fromtimestamp(
# int(str(meta_data['endTime'])[:-3])) if meta_data.get(
# 'endTime') else datetime.datetime.now(),
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['endTime'])[:-3])) if meta_data.get(
# 'endTime') else datetime.datetime.now(),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'Meeting: New Created',
# 'skip': False,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# else:
# print('message created for call', odoo_company.name)
# author_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'comment',
# 'body': meta_data['body'] if meta_data.get('body') else meta_data['title'],
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'res.partner',
# 'res_id': odoo_company.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'Meeting: New Created(Completed)',
# 'skip': False,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_company.name,
# 'description': 'MEETING: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Company-res.partner',
# })
# self.env.cr.commit()
# pass
has_more = res_data['hasMore']
parameter_dict['offset'] = res_data['offset']
odoo_company.write({
'engagement_done': False,
})
self.env.cr.commit()
except Exception as e:
pass
def get_lead_engagements(self):
try:
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
leads = self.env['crm.lead'].search([('hubspot_id', '!=', False),
('type', '=', 'opportunity'),
('engagement_done', '=', True)])
for odoo_lead in leads:
get_associated_engagement_url = "https://api.hubapi.com/engagements/v1/engagements/associated/" \
"DEAL/{0}/paged?".format(odoo_lead.hubspot_id)
parameter_dict = {'hapikey': hubspot_keys, 'limit': 100}
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
has_more = True
while has_more:
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_associated_engagement_url + parameters
response = requests.get(url=get_url, headers=headers)
res_data = json.loads(response.content.decode("utf-8"))
engagements = res_data['results']
for engagement in engagements:
engagement_data = engagement['engagement']
odoo_message = self.env['mail.message'].search([('engagement_id', '=', engagement_data['id'])])
odoo_activity = self.env['mail.activity'].search([('engagement_id', '=', engagement_data['id'])])
if odoo_message or odoo_activity:
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_lead.name,
'description': 'Record already exists',
'skip': False,
'model': 'Deal-crm.lead',
})
self.env.cr.commit()
continue
association_data = engagement['associations']
meta_data = engagement['metadata']
if engagement_data['type'] in ['EMAIL', 'INCOMING_EMAIL']:
if not meta_data.get('from'):
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_lead.name,
'description': 'Coming engagement email type has no \'from\' that is why skipped',
'skip': True,
'model': 'Deal-crm.lead',
})
self.env.cr.commit()
continue
try:
author = self.env['res.partner'].search([('email', '=', meta_data['from']['email'])])
if len(author) > 1:
author = author[0]
odoo_comment = self.env['mail.message'].create({
'engagement_id': engagement_data['id'],
'message_type': 'email',
'body': meta_data['text'] if meta_data.get('text') else '',
'create_date': datetime.datetime.fromtimestamp(
int(str(engagement_data['createdAt'])[:-3])),
'display_name': author.name if author.name else None,
'email_from': meta_data['from'],
# comment.author.email if comment.author.email else None,
'author_id': author.id if author else None,
'model': 'crm.lead',
'res_id': odoo_lead.id
})
self.env.cr.commit()
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_lead.name,
'description': 'Email: New Created',
'skip': False,
'model': 'Deal-crm.lead',
})
self.env.cr.commit()
except Exception as e:
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_lead.name,
'description': 'EMAIL: Skipped because of error while creating(' + str(e) + ')',
'skip': True,
'model': 'Deal-crm.lead',
})
self.env.cr.commit()
pass
# elif engagement_data['type'] == 'NOTE':
# try:
# print('Creating Note Engagement against the company', odoo_lead.name)
# author_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
#
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'notification',
# 'body': engagement_data['bodyPreview'] if engagement_data.get('bodyPreview') else None,
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'crm.lead',
# 'res_id': odoo_lead.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'Note: New Created',
# 'skip': False,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'NOTE: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# pass
# elif engagement_data['type'] == 'TASK':
# try:
# print('Creating TASK Engagement against the lead', odoo_lead.name)
# if meta_data['status'] != 'COMPLETED':
# print(odoo_lead.name)
# user_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Todo')])
# partner_model = self.env['ir.model'].search([('model', '=', 'crm.lead')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_lead.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['subject'],
# 'hubspot_status': meta_data['status'],
# 'note': meta_data['body'] if meta_data.get('body') else None,
# 'forObjectType': meta_data['forObjectType'],
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['completionDate'])[:-3])) if meta_data.get(
# 'completionDate') else datetime.datetime.now(),
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'Task: New Created',
# 'skip': False,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# else:
# print('message created for task', odoo_lead.name)
# author_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
#
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'comment',
# # 'from': odoo_contact.email,
# 'body': meta_data['body'] if meta_data.get('body') else meta_data['subject'],
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'crm.lead',
# 'res_id': odoo_lead.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'Task: New Created(Completed)',
# 'skip': False,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'TASK: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# pass
# elif engagement_data['type'] == 'CALL':
# try:
# print('Creating Call Engagement against the lead', odoo_lead.name)
# if meta_data['status'] != 'COMPLETED':
# print(odoo_lead.name)
# user_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Call')])
# partner_model = self.env['ir.model'].search([('model', '=', 'crm.lead')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_lead.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['subject'] if meta_data.get('subject') else meta_data[
# 'body'] if meta_data.get('body') else None,
# 'hubspot_status': meta_data['status'],
# 'note': html2text.html2text(meta_data['body']) if meta_data.get('body') else None,
# 'toNumber': meta_data['toNumber'] if meta_data.get('toNumber') else None,
# 'fromNumber': meta_data['fromNumber'] if meta_data.get('fromNumber') else None,
# 'durationMilliseconds': str(meta_data['durationMilliseconds']) if meta_data.get(
# 'durationMilliseconds') else None,
# 'recordingUrl': meta_data['recordingUrl'] if meta_data.get(
# 'recordingUrl') else None,
# 'disposition': meta_data['disposition'] if meta_data.get('disposition') else None,
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['completionDate'])[:-3])) if meta_data.get(
# 'completionDate') else datetime.datetime.now(),
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'Call: New Created',
# 'skip': False,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# else:
# print('message created for call', odoo_lead.name)
# author_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
#
# odoo_comment = self.env['mail.message'].create({
# 'message_type': 'comment',
# 'engagement_id': engagement_data['id'],
# 'body': meta_data['body'] if meta_data.get('body') else meta_data[
# 'subject'] if meta_data.get('subject') else None,
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'crm.lead',
# 'res_id': odoo_lead.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'Call: New Created(Completed)',
# 'skip': False,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'CALL: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# pass
#
# elif engagement_data['type'] == 'MEETING':
# try:
# print('Creating Meeting Engagement against the lead', odoo_lead.name)
# end_time = datetime.datetime.fromtimestamp(int(str(meta_data['endTime'])[:-3]))
# if end_time > datetime.datetime.now():
# print(odoo_lead.name)
# user_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Meeting')])
# partner_model = self.env['ir.model'].search([('model', '=', 'crm.lead')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_lead.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['title'] if meta_data.get('title') else meta_data[
# 'body'] if meta_data.get('body') else None,
# 'note': meta_data['body'] if meta_data.get('body') else None,
# 'startTime': datetime.datetime.fromtimestamp(
# int(str(meta_data['startTime'])[:-3])) if meta_data.get(
# 'startTime') else datetime.datetime.now(),
# 'endTime': datetime.datetime.fromtimestamp(
# int(str(meta_data['endTime'])[:-3])) if meta_data.get(
# 'endTime') else datetime.datetime.now(),
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['endTime'])[:-3])) if meta_data.get(
# 'endTime') else datetime.datetime.now(),
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'Meeting: New Created',
# 'skip': False,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# else:
# print('message created for call', odoo_lead.name)
# author_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
#
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'comment',
# 'body': meta_data['body'] if meta_data.get('body') else meta_data['title'],
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'crm.lead',
# 'res_id': odoo_lead.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'Meeting: New Created(Completed)',
# 'skip': False,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_lead.name,
# 'description': 'MEETING: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Deal-crm.lead',
# })
# self.env.cr.commit()
# pass
has_more = res_data['hasMore']
parameter_dict['offset'] = res_data['offset']
odoo_lead.write({
'engagement_done': False,
})
self.env.cr.commit()
except Exception as e:
pass
def get_ticket_engagements(self):
try:
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
tickets = self.env['helpdesk.ticket'].search([('hubspot_id', '!=', False),
('engagement_done', '=', True)])
for odoo_ticket in tickets:
get_associated_engagement_url = "https://api.hubapi.com/engagements/v1/engagements/associated/" \
"TICKET/{0}/paged?".format(odoo_ticket.hubspot_id)
parameter_dict = {'hapikey': hubspot_keys, 'limit': 100}
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
has_more = True
while has_more:
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_associated_engagement_url + parameters
response = requests.get(url=get_url, headers=headers)
res_data = json.loads(response.content.decode("utf-8"))
engagements = res_data['results']
for engagement in engagements:
engagement_data = engagement['engagement']
odoo_message = self.env['mail.message'].search([('engagement_id', '=', engagement_data['id'])])
odoo_activity = self.env['mail.activity'].search([('engagement_id', '=', engagement_data['id'])])
if odoo_message or odoo_activity:
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_ticket.name,
'description': 'Record already exists',
'skip': False,
'model': 'Ticket-helpdesk.ticket',
})
self.env.cr.commit()
continue
association_data = engagement['associations']
meta_data = engagement['metadata']
if engagement_data['type'] in ['EMAIL', 'INCOMING_EMAIL']:
if not meta_data.get('from'):
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_ticket.name,
'description': 'Coming engagement email type has no \'from\' that is why skipped',
'skip': True,
'model': 'Ticket-helpdesk.ticket',
})
self.env.cr.commit()
continue
try:
author = self.env['res.partner'].search([('email', '=', meta_data['from']['email'])])
if len(author) > 1:
author = author[0]
odoo_comment = self.env['mail.message'].create({
'engagement_id': engagement_data['id'],
'message_type': 'email',
'body': meta_data['text'] if meta_data.get('text') else '',
'create_date': datetime.datetime.fromtimestamp(
int(str(engagement_data['createdAt'])[:-3])),
'display_name': author.name if author.name else None,
'email_from': meta_data['from'],
# comment.author.email if comment.author.email else None,
'author_id': author.id if author else None,
'model': 'helpdesk.ticket',
'res_id': odoo_ticket.id
})
self.env.cr.commit()
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_ticket.name,
'description': 'Email: New Created',
'skip': False,
'model': 'Ticket-helpdesk.ticket',
})
self.env.cr.commit()
except Exception as e:
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_ticket.name,
'description': 'EMAIL: Skipped because of error while creating(' + str(e) + ')',
'skip': True,
'model': 'Ticket-helpdesk.ticket',
})
self.env.cr.commit()
pass
# elif engagement_data['type'] == 'NOTE':
# try:
# print('Creating Note Engagement against the company', odoo_ticket.name)
# author_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
#
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'notification',
# 'body': engagement_data['bodyPreview'] if engagement_data.get('bodyPreview') else None,
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'helpdesk.ticket',
# 'res_id': odoo_ticket.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'Note: New Created',
# 'skip': False,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'NOTE: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# pass
# elif engagement_data['type'] == 'TASK':
# try:
# print('Creating TASK Engagement against the lead', odoo_ticket.name)
# if meta_data['status'] != 'COMPLETED':
# print(odoo_ticket.name)
# user_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Todo')])
# partner_model = self.env['ir.model'].search([('model', '=', 'helpdesk.ticket')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_ticket.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['subject'],
# 'hubspot_status': meta_data['status'],
# 'note': meta_data['body'] if meta_data.get('body') else None,
# 'forObjectType': meta_data['forObjectType'],
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['completionDate'])[:-3])) if meta_data.get(
# 'completionDate') else datetime.datetime.now(),
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'Task: New Created',
# 'skip': False,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# else:
# print('message created for task', odoo_ticket.name)
# author_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'comment',
# # 'from': odoo_contact.email,
# 'body': meta_data['body'] if meta_data.get('body') else meta_data['subject'],
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'helpdesk.ticket',
# 'res_id': odoo_ticket.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'Task: New Created(Completed)',
# 'skip': False,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'TASK: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# pass
# elif engagement_data['type'] == 'CALL':
# try:
# print('Creating Call Engagement against the lead', odoo_ticket.name)
# if meta_data['status'] != 'COMPLETED':
# print(odoo_ticket.name)
# user_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Call')])
# partner_model = self.env['ir.model'].search([('model', '=', 'helpdesk.ticket')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_ticket.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['subject'] if meta_data.get('subject') else meta_data[
# 'body'] if meta_data.get('body') else None,
# 'hubspot_status': meta_data['status'],
# 'note': html2text.html2text(meta_data['body']) if meta_data.get('body') else None,
# 'toNumber': meta_data['toNumber'] if meta_data.get('toNumber') else None,
# 'fromNumber': meta_data['fromNumber'] if meta_data.get('fromNumber') else None,
# 'durationMilliseconds': str(meta_data['durationMilliseconds']) if meta_data.get(
# 'durationMilliseconds') else None,
# 'recordingUrl': meta_data['recordingUrl'] if meta_data.get(
# 'recordingUrl') else None,
# 'disposition': meta_data['disposition'] if meta_data.get('disposition') else None,
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['completionDate'])[:-3])) if meta_data.get(
# 'completionDate') else datetime.datetime.now(),
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'Call: New Created',
# 'skip': False,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# else:
# print('message created for call', odoo_ticket.name)
# author_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'message_type': 'comment',
# 'engagement_id': engagement_data['id'],
# 'body': meta_data['body'] if meta_data.get('body') else meta_data[
# 'subject'] if meta_data.get('subject') else None,
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'helpdesk.ticket',
# 'res_id': odoo_ticket.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'Call: New Created(Completed)',
# 'skip': False,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'CALL: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# pass
#
# elif engagement_data['type'] == 'MEETING':
# try:
# print('Creating Meeting Engagement against the lead', odoo_ticket.name)
# end_time = datetime.datetime.fromtimestamp(int(str(meta_data['endTime'])[:-3]))
# if end_time > datetime.datetime.now():
# print(odoo_ticket.name)
# user_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Meeting')])
# partner_model = self.env['ir.model'].search([('model', '=', 'helpdesk.ticket')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_ticket.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['title'] if meta_data.get('title') else meta_data[
# 'body'] if meta_data.get('body') else None,
# 'note': meta_data['body'] if meta_data.get('body') else None,
# 'startTime': datetime.datetime.fromtimestamp(
# int(str(meta_data['startTime'])[:-3])) if meta_data.get(
# 'startTime') else datetime.datetime.now(),
# 'endTime': datetime.datetime.fromtimestamp(
# int(str(meta_data['endTime'])[:-3])) if meta_data.get(
# 'endTime') else datetime.datetime.now(),
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['endTime'])[:-3])) if meta_data.get(
# 'endTime') else datetime.datetime.now(),
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'Meeting: New Created',
# 'skip': False,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# else:
# print('message created for call', odoo_ticket.name)
# author_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'comment',
# 'body': meta_data['body'] if meta_data.get('body') else meta_data['title'],
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'helpdesk.ticket',
# 'res_id': odoo_ticket.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'Meeting: New Created(Completed)',
# 'skip': False,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_ticket.name,
# 'description': 'MEETING: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Ticket-helpdesk.ticket',
# })
# self.env.cr.commit()
# pass
has_more = res_data['hasMore']
parameter_dict['offset'] = res_data['offset']
odoo_ticket.write({
'engagement_done': False,
})
self.env.cr.commit()
except Exception as e:
pass
def get_contact_engagements(self):
try:
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
contacts = self.env['res.partner'].search([('hubspot_id', '!=', False),
('is_company', '=', False),
('engagement_done', '=', True)])
for odoo_contact in contacts:
get_associated_engagement_url = "https://api.hubapi.com/engagements/v1/engagements/associated/" \
"CONTACT/{0}/paged?".format(odoo_contact.hubspot_id)
parameter_dict = {'hapikey': hubspot_keys, 'limit': 100}
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
has_more = True
while has_more:
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_associated_engagement_url + parameters
response = requests.get(url=get_url, headers=headers)
res_data = json.loads(response.content.decode("utf-8"))
engagements = res_data['results']
for engagement in engagements:
engagement_data = engagement['engagement']
odoo_message = self.env['mail.message'].search([('engagement_id', '=', engagement_data['id'])])
odoo_activity = self.env['mail.activity'].search([('engagement_id', '=', engagement_data['id'])])
if odoo_message or odoo_activity:
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_contact.name,
'description': 'Record already exists',
'skip': False,
'model': 'Contact-res.partner',
})
self.env.cr.commit()
continue
association_data = engagement['associations']
meta_data = engagement['metadata']
if engagement_data['type'] in ['EMAIL', 'INCOMING_EMAIL']:
if not meta_data.get('from'):
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_contact.name,
'description': 'Coming engagement email type has no \'from\' that is why skipped',
'skip': True,
'model': 'Contact-res.partner',
})
self.env.cr.commit()
continue
try:
author = self.env['res.partner'].search([('email', '=', meta_data['from']['email'])])
if len(author) > 1:
author = author[0]
odoo_comment = self.env['mail.message'].create({
'engagement_id': engagement_data['id'],
'message_type': 'email',
'body': meta_data['text'] if meta_data.get('text') else '',
'create_date': datetime.datetime.fromtimestamp(
int(str(engagement_data['createdAt'])[:-3])),
'display_name': author.name if author.name else None,
'email_from': meta_data['from'],
# comment.author.email if comment.author.email else None,
'author_id': author.id if author else None,
'model': 'res.partner',
'res_id': odoo_contact.id
})
self.env.cr.commit()
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_contact.name,
'description': 'Email: New Created',
'skip': False,
'model': 'Contact-res.partner',
})
self.env.cr.commit()
except Exception as e:
self.env['log.handling'].create({
'record_id': engagement_data['id'],
'odoo_record_name': odoo_contact.name,
'description': 'EMAIL: Skipped because of error while creating(' + str(e) + ')',
'skip': True,
'model': 'Contact-res.partner',
})
self.env.cr.commit()
continue
# elif engagement_data['type'] == 'NOTE':
# try:
# print(odoo_contact.name)
# author_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'notification',
# 'body': engagement_data['bodyPreview'] if engagement_data.get('bodyPreview') else None,
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'res.partner',
# 'res_id': odoo_contact.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'Note: New Created',
# 'skip': False,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'NOTE: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# continue
# elif engagement_data['type'] == 'TASK':
# try:
# if meta_data['status'] != 'COMPLETED':
# print(odoo_contact.name)
# user_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Todo')])
# partner_model = self.env['ir.model'].search([('model', '=', 'res.partner')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_contact.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['subject'],
# 'hubspot_status': meta_data['status'],
# 'note': meta_data['body'] if meta_data.get('body') else None,
# 'forObjectType': meta_data['forObjectType'],
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['completionDate'])[:-3])) if meta_data.get(
# 'completionDate') else datetime.datetime.now(),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'Task: New Created',
# 'skip': False,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# else:
# print('message created for task', odoo_contact.name)
# author_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'comment',
# # 'from': odoo_contact.email,
# 'body': meta_data['body'] if meta_data.get('body') else meta_data['subject'],
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'res.partner',
# 'res_id': odoo_contact.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'Task: New Created(Completed)',
# 'skip': False,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'TASK: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# continue
# elif engagement_data['type'] == 'CALL':
# try:
# if meta_data['status'] != 'COMPLETED':
# print(odoo_contact.name)
# user_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Call')])
# partner_model = self.env['ir.model'].search([('model', '=', 'res.partner')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_contact.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['subject'] if meta_data.get('subject') else meta_data[
# 'body'] if meta_data.get('body') else None,
# 'hubspot_status': meta_data['status'],
# 'note': html2text.html2text(meta_data['body']) if meta_data.get('body') else None,
# 'toNumber': meta_data['toNumber'] if meta_data.get('toNumber') else None,
# 'fromNumber': meta_data['fromNumber'] if meta_data.get('fromNumber') else None,
# 'durationMilliseconds': str(meta_data['durationMilliseconds']) if meta_data.get(
# 'durationMilliseconds') else None,
# 'recordingUrl': meta_data['recordingUrl'] if meta_data.get(
# 'recordingUrl') else None,
# 'disposition': meta_data['disposition'] if meta_data.get('disposition') else None,
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['completionDate'])[:-3])) if meta_data.get(
# 'completionDate') else datetime.datetime.now(),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'Call: New Created',
# 'skip': False,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# else:
# print('message created for call', odoo_contact.name)
# author_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'message_type': 'comment',
# 'engagement_id': engagement_data['id'],
# 'body': html2text.html2text(meta_data['body']) if meta_data.get('body') else
# meta_data['subject'],
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'res.partner',
# 'res_id': odoo_contact.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'Call: New Created(Completed)',
# 'skip': False,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'CALL: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# continue
# elif engagement_data['type'] == 'MEETING':
# try:
# end_time = datetime.datetime.fromtimestamp(int(str(meta_data['endTime'])[:-3]))
# if end_time > datetime.datetime.now():
# print(odoo_contact.name)
# user_id = self.env['res.users'].search(
# [('hubspot_id', '=', engagement_data['ownerId'])])
# activity_type = self.env['mail.activity.type'].search([('name', '=', 'Meeting')])
# partner_model = self.env['ir.model'].search([('model', '=', 'res.partner')])
# self.env['mail.activity'].create({
# 'engagement_id': engagement_data['id'],
# 'res_id': odoo_contact.id,
# 'activity_type_id': activity_type.id,
# 'summary': meta_data['title'] if meta_data.get('title') else meta_data[
# 'body'] if meta_data.get('body') else None,
# 'note': meta_data['body'] if meta_data.get('body') else None,
# 'startTime': datetime.datetime.fromtimestamp(
# int(str(meta_data['startTime'])[:-3])) if meta_data.get(
# 'startTime') else datetime.datetime.now(),
# 'endTime': datetime.datetime.fromtimestamp(
# int(str(meta_data['endTime'])[:-3])) if meta_data.get(
# 'endTime') else datetime.datetime.now(),
# 'res_model_id': partner_model.id,
# 'date_deadline': datetime.datetime.fromtimestamp(
# int(str(meta_data['endTime'])[:-3])) if meta_data.get(
# 'endTime') else datetime.datetime.now(),
# 'user_id': user_id.id if user_id else self.env.user.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'Meeting: New Created',
# 'skip': False,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# else:
# print('message created for call', odoo_contact.name)
# author_id = self.env['res.users'].search([('hubspot_id', '=', engagement_data['ownerId'])]).partner_id
# odoo_comment = self.env['mail.message'].create({
# 'engagement_id': engagement_data['id'],
# 'message_type': 'comment',
# 'body': meta_data['body'] if meta_data.get('body') else meta_data['title'],
# 'create_date': datetime.datetime.fromtimestamp(
# int(str(engagement_data['createdAt'])[:-3])),
# 'display_name': author_id.name if author_id.name else None,
# 'author_id': author_id.id,
# 'model': 'res.partner',
# 'res_id': odoo_contact.id
# })
# self.env.cr.commit()
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'Meeting: New Created(Completed)',
# 'skip': False,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# except Exception as e:
# self.env['log.handling'].create({
# 'record_id': engagement_data['id'],
# 'odoo_record_name': odoo_contact.name,
# 'description': 'MEETING: Skipped because of error while creating(' + str(e) + ')',
# 'skip': True,
# 'model': 'Contact-res.partner',
# })
# self.env.cr.commit()
# continue
has_more = res_data['hasMore']
parameter_dict['offset'] = res_data['offset']
odoo_contact.write({
'engagement_done': False,
})
self.env.cr.commit()
except:
pass
def create_owners(self):
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
if not hubspot_keys:
raise ValidationError('Please! Enter Hubspot key...')
else:
try:
get_all_owners_url = "https://api.hubapi.com/owners/v2/owners?"
parameter_dict = {'hapikey': hubspot_keys}
headers = {
'Accept': 'application/json',
'connection': 'keep-Alive'
}
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_all_owners_url + parameters
r = requests.get(url=get_url, headers=headers)
owners = json.loads(r.text)
for owner in owners:
odoo_user = self.env['res.users'].search([('email', '=', owner['email'])])
if not odoo_user:
first_name = owner['firstName'] if owner['firstName'] else ''
last_name = owner['lastName'] if owner['lastName'] else ''
name = first_name + ' ' + last_name
self.env['res.users'].create({
'name': name,
'login': owner['email'] if owner['email'] else None,
'email': owner['email'] if owner['email'] else None,
})
else:
odoo_user.write({
'hubspot_id': owner['ownerId']
})
self.env.cr.commit()
except Exception as e:
_logger.error(e)
raise ValidationError(_(str(e)))
def get_lead_attachments(self):
try:
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
leads = self.env['crm.lead'].search(
[('hubspot_id', '!=', False)]
)
for odoo_lead in leads:
url = 'https://api.hubapi.com/engagements/v1/engagements/associated/DEAL/{0}/paged?hapikey={1}'.format(
odoo_lead.hubspot_id, hubspot_keys)
response = requests.get(url)
res_data = json.loads(response.content.decode("utf-8"))
engagements = res_data['results']
for engagement in engagements:
attachments = engagement['attachments']
if len(attachments):
for attachment in attachments:
try:
odoo_attachment = self.env['ir.attachment'].search(
[('hubspot_id', '=', str(attachment['id']))]
)
attachment_url = 'https://api.hubapi.com/filemanager/api/v2/files/{0}/?hapikey={1}'.format(
attachment['id'], hubspot_keys
)
response = requests.get(attachment_url)
res_data = json.loads(response.content.decode("utf-8"))
file_name = 'default'
if res_data.get('name'):
file_name = res_data['name']
file_url = res_data.get('url', None)
if not os.path.isdir('engagement_files'):
os.mkdir('engagement_files')
if file_url:
try:
file_res = urllib.request.urlretrieve(file_url,
'engagement_files/' + file_name + '.' +
res_data['extension'])
except Exception as e:
if e.code == 404:
with open('lead.txt', 'a+') as file:
file.write('\n')
file.write('{} -> {} \n{}'.format(
odoo_lead.name, file_name, file_url)
)
if odoo_attachment:
continue
f = open('engagement_files/' + file_name + '.' + res_data['extension'], "rb")
data = data = base64.b64encode(f.read())
self.env['ir.attachment'].create({'name': file_name + '.' + res_data['extension'],
'datas': data,
'res_model': 'crm.lead',
'res_id': odoo_lead.id, })
f.close()
os.remove('engagement_files/' + file_name + '.' + res_data['extension'])
self.env.cr.commit()
print(odoo_lead.name)
except Exception as e:
pass
except Exception as e:
pass
def get_contact_attachments(self):
try:
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
contacts = self.env['res.partner'].search(
[('hubspot_id', '!=', False), ('company_type', '=', 'person')]
)
for odoo_contact in contacts:
url = 'https://api.hubapi.com/engagements/v1/engagements/associated/CONTACT/{0}/paged?hapikey={1}'.format(
odoo_contact.hubspot_id, hubspot_keys)
response = requests.get(url)
res_data = json.loads(response.content.decode("utf-8"))
engagements = res_data['results']
for engagement in engagements:
attachments = engagement['attachments']
if len(attachments):
for attachment in attachments:
try:
odoo_attachment = self.env['ir.attachment'].search(
[('hubspot_id', '=', str(attachment['id']))]
)
attachment_url = 'https://api.hubapi.com/filemanager/api/v2/files/{0}/?hapikey={1}'.format(
attachment['id'], hubspot_keys
)
response = requests.get(attachment_url)
res_data = json.loads(response.content.decode("utf-8"))
file_name = 'default'
if res_data.get('name'):
file_name = res_data['name']
file_url = None
file_url = res_data.get('url', None)
if not os.path.isdir('engagement_files'):
os.mkdir('engagement_files')
if file_url:
try:
urllib.request.urlretrieve(file_url, 'engagement_files/' + file_name + '.' + res_data['extension'])
except Exception as e:
if e.code == 404:
with open('contact.txt', 'a+') as file:
file.write('\n')
file.write('{} -> {} \n{}'.format(
odoo_contact.name, file_name, file_url)
)
if odoo_attachment:
continue
a = 1
f = open('engagement_files/' + file_name + '.' + res_data['extension'], "rb")
data = data = base64.b64encode(f.read())
self.env['ir.attachment'].create({'name': file_name + '.' + res_data['extension'],
'datas': data,
'res_model': 'res.partner',
'res_id': odoo_contact.id, })
f.close()
os.remove('engagement_files/' + file_name + '.' + res_data['extension'])
self.env.cr.commit()
print(odoo_contact.name)
if odoo_attachment:
continue
except Exception as e:
pass
except Exception as e:
pass
def get_company_attachments(self):
try:
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
companies = self.env['res.partner'].search(
[('hubspot_id', '!=', False), ('company_type', '=', 'company')]
)
for odoo_company in companies:
url = 'https://api.hubapi.com/engagements/v1/engagements/associated/COMPANY/{0}/paged?hapikey={1}'.format(
odoo_company.hubspot_id, hubspot_keys)
# url = 'https://api.hubapi.com/engagements/v1/engagements/paged?hapikey={}'.format(API_KEY)
response = requests.get(url)
res_data = json.loads(response.content.decode("utf-8"))
engagements = res_data['results']
for engagement in engagements:
attachments = engagement['attachments']
if len(attachments):
for attachment in attachments:
try:
odoo_attachment = self.env['ir.attachment'].search(
[('hubspot_id', '=', str(attachment['id']))]
)
attachment_url = 'https://api.hubapi.com/filemanager/api/v2/files/{0}/?hapikey={1}'.format(
attachment['id'], hubspot_keys
)
response = requests.get(attachment_url)
res_data = json.loads(response.content.decode("utf-8"))
file_name = 'default'
if res_data.get('name'):
file_name = res_data['name']
file_url = res_data.get('url', None)
if not os.path.isdir('engagement_files'):
os.mkdir('engagement_files')
if file_url:
try:
urllib.request.urlretrieve(file_url,
'engagement_files/' + file_name + '.' + res_data['extension'])
except Exception as e:
if e.code == 404:
with open('company.txt', 'a+') as file:
file.write('\n')
file.write('{} -> {} \n{}'.format(
odoo_company.name, file_name, file_url)
)
if odoo_attachment:
continue
a = 1
f = open('engagement_files/' + file_name + '.' + res_data['extension'], "rb")
data = base64.b64encode(f.read())
self.env['ir.attachment'].create({'name': file_name + '.' + res_data['extension'],
'datas': data,
'res_model': 'res.partner',
'res_id': odoo_company.id, })
f.close()
os.remove('engagement_files/' + file_name + '.' + res_data['extension'])
self.env.cr.commit()
print(odoo_company.name)
if odoo_attachment:
continue
except Exception as e:
pass
except Exception as e:
pass
def get_ticket_attachments(self):
try:
icpsudo = self.env['ir.config_parameter'].sudo()
hubspot_keys = icpsudo.get_param('odoo_hubspot.hubspot_key')
tickets = self.env['helpdesk.ticket'].search([('hubspot_id', '!=', False)])
for odoo_ticket in tickets:
url = 'https://api.hubapi.com/engagements/v1/engagements/associated/TICKET/{0}/paged?hapikey={1}'.format(
odoo_ticket.hubspot_id, hubspot_keys)
# url = 'https://api.hubapi.com/engagements/v1/engagements/paged?hapikey={}'.format(API_KEY)
response = requests.get(url)
res_data = json.loads(response.content.decode("utf-8"))
engagements = res_data['results']
for engagement in engagements:
attachments = engagement['attachments']
if len(attachments):
for attachment in attachments:
try:
odoo_attachment = self.env['ir.attachment'].search(
[('hubspot_id', '=', str(attachment['id']))]
)
# if odoo_attachment:
# continue
attachment_url = 'https://api.hubapi.com/filemanager/api/v2/files/{0}/?hapikey={1}'.format(
attachment['id'], hubspot_keys
)
response = requests.get(attachment_url)
res_data = json.loads(response.content.decode("utf-8"))
file_name = 'default'
if res_data.get('name'):
file_name = res_data['name']
file_url = res_data.get('url', None)
if not os.path.isdir('engagement_files'):
os.mkdir('engagement_files')
if file_url:
try:
file_res = urllib.request.urlretrieve(file_url,
'engagement_files/' + file_name + '.' + res_data['extension'])
except Exception as e:
if e.code == 404:
with open('ticket.txt', 'a+') as file:
file.write('\n')
file.write('{} -> {} \n{}'.format(
odoo_ticket.name, file_name, file_url)
)
if odoo_attachment:
continue
a = 1
f = open('engagement_files/' + file_name + '.' + res_data['extension'], "rb")
data = data = base64.b64encode(f.read())
self.env['ir.attachment'].create({'name': file_name + '.' + res_data['extension'],
'datas': data,
'res_model': 'helpdesk.ticket',
'res_id': odoo_ticket.id, })
f.close()
os.remove('engagement_files/' + file_name + '.' + res_data['extension'])
self.env.cr.commit()
print(odoo_ticket.name)
if odoo_attachment:
continue
except Exception as e:
pass
except Exception as e:
pass
| 67.437526 | 144 | 0.417162 | 13,029 | 163,536 | 4.983805 | 0.046281 | 0.036545 | 0.03154 | 0.024717 | 0.893261 | 0.881803 | 0.865725 | 0.855284 | 0.840946 | 0.831829 | 0 | 0.004552 | 0.469413 | 163,536 | 2,424 | 145 | 67.465347 | 0.743794 | 0.315062 | 0 | 0.6773 | 0 | 0.033383 | 0.182413 | 0.038908 | 0 | 0 | 0 | 0.000413 | 0 | 1 | 0.01632 | false | 0.011128 | 0.017062 | 0 | 0.048961 | 0.005193 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
79ad9c7db0036734cd151b5f3bbaa199fc17709d | 403 | py | Python | __init__.py | ChristopherHoffman/3d-print-log-cura-plugin | 1b7bccdcbdce7ae6c11ac92e0f8f8ab20d9f82ee | [
"MIT"
] | 5 | 2021-02-12T12:55:46.000Z | 2022-01-28T09:00:52.000Z | __init__.py | ChristopherHoffman/3d-print-log-cura-plugin | 1b7bccdcbdce7ae6c11ac92e0f8f8ab20d9f82ee | [
"MIT"
] | 2 | 2021-05-14T11:56:42.000Z | 2022-03-07T12:04:14.000Z | __init__.py | ChristopherHoffman/3d-print-log-cura-plugin | 1b7bccdcbdce7ae6c11ac92e0f8f8ab20d9f82ee | [
"MIT"
] | 1 | 2022-01-28T09:01:04.000Z | 2022-01-28T09:01:04.000Z | from . import PrintLogUploader
from . import PrintLogSettingDefinitionsModel
from PyQt5.QtQml import qmlRegisterType
def getMetaData():
return {}
def register(app):
qmlRegisterType(PrintLogSettingDefinitionsModel.PrintLogSettingDefinitionsModel,
"PrintLogUploader", 1, 0, "PrintLogSettingDefinitionsModel")
return {"extension": PrintLogUploader.PrintLogUploader()}
| 25.1875 | 84 | 0.766749 | 28 | 403 | 11.035714 | 0.535714 | 0.064725 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.00885 | 0.158809 | 403 | 15 | 85 | 26.866667 | 0.902655 | 0 | 0 | 0 | 0 | 0 | 0.138958 | 0.076923 | 0 | 0 | 0 | 0 | 0 | 1 | 0.222222 | false | 0 | 0.333333 | 0.111111 | 0.777778 | 0 | 1 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 6 |
79c71be83b25746a962ff76818e062128c61ee38 | 24 | py | Python | pmbrl/envs/__init__.py | paul-kinghorn/rl-inference | 007dba5836b79417aaa0aa6216492745aa9e1bb3 | [
"MIT"
] | 20 | 2020-04-16T18:13:39.000Z | 2022-02-25T01:20:39.000Z | pmbrl/envs/__init__.py | paul-kinghorn/rl-inference | 007dba5836b79417aaa0aa6216492745aa9e1bb3 | [
"MIT"
] | null | null | null | pmbrl/envs/__init__.py | paul-kinghorn/rl-inference | 007dba5836b79417aaa0aa6216492745aa9e1bb3 | [
"MIT"
] | 8 | 2020-04-23T05:39:46.000Z | 2021-08-29T20:21:44.000Z |
from .env import GymEnv | 12 | 23 | 0.791667 | 4 | 24 | 4.75 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 24 | 2 | 23 | 12 | 0.95 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
79cd7d6d1cca4c08bfbde8c6ede81f42fb6d81a8 | 28 | py | Python | ImmoKaa/__init__.py | gandreassi/ImmoKaa | 904115e5a6f91ca78b41aebdaf4ffe3934a4c318 | [
"MIT"
] | 1 | 2021-06-08T09:12:00.000Z | 2021-06-08T09:12:00.000Z | ImmoKaa/__init__.py | gandreassi/ImmoKaa | 904115e5a6f91ca78b41aebdaf4ffe3934a4c318 | [
"MIT"
] | null | null | null | ImmoKaa/__init__.py | gandreassi/ImmoKaa | 904115e5a6f91ca78b41aebdaf4ffe3934a4c318 | [
"MIT"
] | null | null | null | from .scraper import scraper | 28 | 28 | 0.857143 | 4 | 28 | 6 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.107143 | 28 | 1 | 28 | 28 | 0.96 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8dae379ae3e08e4c4b53c218c782f0b7044a8599 | 13,444 | py | Python | accera/python/samples/MatrixMultiplication.py | lisaong/Accera | 56967249356ab2fefd80baebf5ac259e958a7dbd | [
"MIT"
] | null | null | null | accera/python/samples/MatrixMultiplication.py | lisaong/Accera | 56967249356ab2fefd80baebf5ac259e958a7dbd | [
"MIT"
] | null | null | null | accera/python/samples/MatrixMultiplication.py | lisaong/Accera | 56967249356ab2fefd80baebf5ac259e958a7dbd | [
"MIT"
] | null | null | null | ####################################################################################################
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root for license information.
####################################################################################################
from typing import Sequence, NamedTuple
from accera import Target, Array, Scalar, Nest, fuse
class Options(NamedTuple):
ForceCacheBMatrix: bool = False
BCacheSizeThreshold: int = 128**2
KUnroll: int = 4
NumRowsInKernel: int = 6
NumColumnsInKernelScaleFactor: int = 2
BMatrixTileSize: Sequence[int] = [128, 256]
PackBFuncName: str = ""
PackBBufferSizeFuncName: str = ""
UseBiasFusion: bool = True
UseAlphaScalingFusion: bool = False
def MLAS_with_bias_and_alpha_scaling(
A: Array,
B: Array,
C: Array,
Y: Array,
transA=False,
transB=False,
alpha=1.0,
beta=1.0,
opts=Options(),
target=Target.HOST
):
"""Y = alpha * A * B + beta * C
Optimized schedule is WIP
"""
if not all(len(arr.shape) >= 2 and # check rank
len(arr.shape) == len(A.shape) and # rank's the same for all args
arr.shape[:-2] == A.shape[:-2] # stacks are the same sizes
for arr in [A, B, Y]):
raise RuntimeError("Invalid shapes for arguments")
def trans_no_trans(val: int, trans: bool):
trans_val = -1 if val == -2 else -2
return trans_val if trans else val
stack = A.shape[:-2]
_M_A, _K_A = A.shape[trans_no_trans(-2, transA)], A.shape[trans_no_trans(-1, transA)]
_K_B, _N_B = B.shape[trans_no_trans(-2, transB)], B.shape[trans_no_trans(-1, transB)]
_M_Y, _N_Y = A.shape[trans_no_trans(-2, transA)], B.shape[trans_no_trans(-1, transB)]
if Y.shape != stack + [_M_Y, _N_Y]:
raise RuntimeError("Incompatible shapes for arguments")
if C:
if len(C.shape) == len(Y.shape):
if C.shape != Y.shape:
raise RuntimeError("Incompatible shapes for arguments")
elif len(C.shape) == (len(Y.shape) - 1):
if C.shape != Y.shape[:-3] + Y.shape[-1:]:
raise RuntimeError("Incompatible shapes for arguments")
else:
raise RuntimeError("Incompatible shapes for arguments")
M = _M_Y
N = _N_Y
K = _K_A
output_rows = M
output_cols = N
inner_dim = K
# Schedule constants
column_block = opts.BMatrixTileSize[1]
inner_dim_block = opts.BMatrixTileSize[0]
num_rows_in_kernel = opts.NumRowsInKernel
num_cols_in_kernel = opts.NumColumnsInKernelScaleFactor * (
target.vector_bytes // 4
) # target.vector_bytes // 4 is how many 32-bit float elements can fit into the vector register
# Apply a simple stretching to the kernel size to fit the output shape
if num_cols_in_kernel > output_cols:
while num_cols_in_kernel > output_cols:
num_rows_in_kernel *= 2
num_cols_in_kernel //= 2
elif num_rows_in_kernel > output_rows:
while num_rows_in_kernel > output_rows:
num_rows_in_kernel //= 2
num_cols_in_kernel *= 2
# now clamp
num_rows_in_kernel = int(min(num_rows_in_kernel, output_rows))
num_cols_in_kernel = int(min(num_cols_in_kernel, output_cols))
# Apply a simple stretching to the block sizes to use as much of
# the original columnBlock x innerDimensionBlock area as possible
while column_block > output_cols:
if (column_block // 2) < num_cols_in_kernel:
# Don't shrink the column block smaller than num_cols_in_kernel
break
column_block //= 2
inner_dim_block *= 2
while inner_dim_block > inner_dim:
inner_dim_block //= 2
column_block *= 2
# Now clamp
column_block = int(min(column_block, output_cols))
inner_dim_block = int(min(inner_dim_block, inner_dim))
bias_nest = Nest(shape=Y.shape)
bias_idxs = bias_nest.get_indices()
bias_stack_idxs, bias_i, bias_j = tuple(bias_idxs[:-2]), *bias_idxs[-2:]
bias_y_idxs = bias_idxs
bias_c_idxs = bias_stack_idxs + (bias_j, )
if C is not None:
@bias_nest.iteration_logic
def _():
Y[bias_y_idxs] = Scalar(beta) * C[bias_c_idxs]
else:
@bias_nest.iteration_logic
def _():
Y[bias_y_idxs] = Scalar(0.0)
bias_schedule = bias_nest.create_schedule()
accumulated = Array(role=Array.Role.TEMP, element_type=A.element_type, shape=(1, ))
zero_accum_nest = Nest(shape=Y.shape)
@zero_accum_nest.iteration_logic
def _():
accumulated[0] = 0.0
zero_accum_schedule = zero_accum_nest.create_schedule()
compute_nest = Nest(shape=tuple(stack + [M, N, K]))
compute_idxs = compute_nest.get_indices()
compute_stack_idxs, compute_i, compute_j, compute_k = tuple(compute_idxs[:-3]), *compute_idxs[-3:]
# This is only until we have proper caching introspection
compute_A_idxs = compute_stack_idxs + \
(compute_i, compute_k) if not transA else (compute_k, compute_i)
compute_B_idxs = compute_stack_idxs + \
(compute_k, compute_j) if not transB else (compute_j, compute_k)
@compute_nest.iteration_logic
def _():
accumulated[0] += A[compute_A_idxs] * B[compute_B_idxs]
compute_schedule = compute_nest.create_schedule()
scale_nest = Nest(shape=Y.shape)
scale_idxs = scale_nest.get_indices()
scale_y_idxs = scale_idxs
@scale_nest.iteration_logic
def _():
Y[scale_y_idxs] += Scalar(alpha) * accumulated[0]
scale_schedule = scale_nest.create_schedule()
fused0 = fuse((
zero_accum_schedule,
compute_schedule,
scale_schedule,
), partial=len(stack) + 2)
idxs_f0 = fused0.get_indices()
f0, stack_f0, i_f0, j_f0, k_f0 = idxs_f0[0], tuple(idxs_f0[1:-3]), *idxs_f0[-3:]
fused0.reorder(*stack_f0, i_f0, j_f0, f0, k_f0)
fused1 = fuse((bias_schedule, fused0), partial=len(stack) + 2)
idxs_f1 = fused1.get_indices()
f1, stack_f1, i_f1, j_f1, f0_f1, k_f1 = idxs_f1[0], tuple(idxs_f1[1:-4]), *idxs_f1[-4:]
fused_Y_idxs = stack_f1 + (i_f1, j_f1)
fused_A_idxs = stack_f1 + (i_f1, k_f1) if not transA else (k_f1, i_f1)
fused_B_idxs = stack_f1 + (k_f1, j_f1) if not transB else (j_f1, k_f1)
jj = fused1.split(j_f1, column_block)
fused1.reorder(*stack_f1, j_f1, i_f1, f1, jj, f0_f1, k_f1)
fused_plan = fused1.create_plan(target)
if opts.PackBFuncName and opts.PackBBufferSizeFuncName:
fused_plan.emit_runtime_init_pack(B, opts.PackBFuncName, opts.PackBBufferSizeFuncName)
elif opts.ForceCacheBMatrix or (K * N) > opts.BCacheSizeThreshold:
fused_plan.cache(B, jj)
fused_plan.unroll(f0_f1)
fused_plan.vectorize(k_f1)
return fused_plan, (A, B, C, Y) if C else (A, B, Y)
def MLAS_with_bias(
A: Array,
B: Array,
C: Array,
Y: Array,
transA=False,
transB=False,
alpha=1.0,
beta=1.0,
opts=Options(),
target=Target.HOST
):
if opts.UseAlphaScalingFusion:
return MLAS_with_bias_and_alpha_scaling(A, B, C, Y, transA, transB, alpha, beta, opts)
if not all(len(arr.shape) >= 2 and # check rank
len(arr.shape) == len(A.shape) and # rank's the same for all args
arr.shape[:-2] == A.shape[:-2] # stacks are the same sizes
for arr in [A, B, Y]):
raise RuntimeError("Invalid shapes for arguments")
def trans_no_trans(val: int, trans: bool):
trans_val = -1 if val == -2 else -2
return trans_val if trans else val
stack = A.shape[:-2]
_M_A, _K_A = A.shape[trans_no_trans(-2, transA)], A.shape[trans_no_trans(-1, transA)]
_K_B, _N_B = B.shape[trans_no_trans(-2, transB)], B.shape[trans_no_trans(-1, transB)]
_M_Y, _N_Y = A.shape[trans_no_trans(-2, transA)], B.shape[trans_no_trans(-1, transB)]
if Y.shape != stack + [_M_Y, _N_Y]:
raise RuntimeError("Incompatible shapes for arguments")
if C:
if len(C.shape) == len(Y.shape):
if C.shape != Y.shape:
raise RuntimeError("Incompatible shapes for arguments")
elif len(C.shape) == (len(Y.shape) - 1):
if C.shape != Y.shape[:-3] + Y.shape[-1:]:
raise RuntimeError("Incompatible shapes for arguments")
else:
raise RuntimeError("Incompatible shapes for arguments")
M = _M_Y
N = _N_Y
K = _K_A
output_rows = M
output_cols = N
inner_dim = K
# Schedule constants
column_block = opts.BMatrixTileSize[1]
inner_dim_block = opts.BMatrixTileSize[0]
num_rows_in_kernel = opts.NumRowsInKernel
num_cols_in_kernel = opts.NumColumnsInKernelScaleFactor * (
target.vector_bytes // 4
) # target.vector_bytes // 4 is how many 32-bit float elements can fit into the vector register
# Apply a simple stretching to the kernel size to fit the output shape
if num_cols_in_kernel > output_cols:
while num_cols_in_kernel > output_cols:
num_rows_in_kernel *= 2
num_cols_in_kernel //= 2
elif num_rows_in_kernel > output_rows:
while num_rows_in_kernel > output_rows:
num_rows_in_kernel //= 2
num_cols_in_kernel *= 2
# now clamp
num_rows_in_kernel = int(min(num_rows_in_kernel, output_rows))
num_cols_in_kernel = int(min(num_cols_in_kernel, output_cols))
# Apply a simple stretching to the block sizes to use as much of
# the original columnBlock x innerDimensionBlock area as possible
while column_block > output_cols:
if (column_block // 2) < num_cols_in_kernel:
# Don't shrink the column block smaller than num_cols_in_kernel
break
column_block //= 2
inner_dim_block *= 2
while inner_dim_block > inner_dim:
inner_dim_block //= 2
column_block *= 2
# Now clamp
column_block = int(min(column_block, output_cols))
inner_dim_block = int(min(inner_dim_block, inner_dim))
bias_nest = Nest(shape=Y.shape)
bias_idxs = bias_nest.get_indices()
bias_stack_idxs, bias_i, bias_j = tuple(bias_idxs[:-2]), *bias_idxs[-2:]
bias_y_idxs = bias_idxs
bias_c_idxs = bias_stack_idxs + (bias_j, )
if C is not None:
@bias_nest.iteration_logic
def _():
Y[bias_y_idxs] = Scalar(beta) * C[bias_c_idxs]
else:
@bias_nest.iteration_logic
def _():
Y[bias_y_idxs] = Scalar(0.0)
bias_schedule = bias_nest.create_schedule()
compute_nest = Nest(shape=tuple(stack + [M, N, K]))
compute_idxs = compute_nest.get_indices()
compute_stack_idxs, compute_i, compute_j, compute_k = tuple(compute_idxs[:-3]), *compute_idxs[-3:]
# This is only until we have proper caching introspection
compute_Y_idxs = compute_stack_idxs + (compute_i, compute_j)
compute_A_idxs = compute_stack_idxs + \
(compute_i, compute_k) if not transA else (compute_k, compute_i)
compute_B_idxs = compute_stack_idxs + \
(compute_k, compute_j) if not transB else (compute_j, compute_k)
@compute_nest.iteration_logic
def _():
Y[compute_Y_idxs] += Scalar(alpha) * \
A[compute_A_idxs] * B[compute_B_idxs]
compute_schedule = compute_nest.create_schedule()
fused_schedule = fuse((bias_schedule, compute_schedule), partial=len(stack) + 2)
fused_idxs = fused_schedule.get_indices()
f, fused_stack_idxs, fused_i, fused_j, k = fused_idxs[0], tuple(fused_idxs[1:-3]), *fused_idxs[-3:]
fused_Y_idxs = fused_stack_idxs + (fused_i, fused_j)
fused_A_idxs = fused_stack_idxs + \
(fused_i, k) if not transA else (k, fused_i)
fused_B_idxs = fused_stack_idxs + \
(k, fused_j) if not transB else (fused_j, k)
jj = fused_schedule.split(fused_j, column_block)
kk = fused_schedule.split(k, inner_dim_block)
kkk = fused_schedule.split(kk, opts.KUnroll)
jjj = fused_schedule.split(jj, num_cols_in_kernel)
jjjj = fused_schedule.split(
jjj, target.vector_bytes // 4
) # (target.vector_bytes // 4) is how many 32-bit float elements can fit into the vector register
ii = fused_schedule.split(fused_i, num_rows_in_kernel)
fused_schedule.reorder(*fused_stack_idxs, fused_j, f, k, fused_i, jj, kk, kkk, ii, jjj, jjjj)
fused_plan = fused_schedule.create_plan(target)
if opts.PackBFuncName and opts.PackBBufferSizeFuncName:
fused_plan.emit_runtime_init_pack(B, opts.PackBFuncName, opts.PackBBufferSizeFuncName)
elif opts.ForceCacheBMatrix or (K * N) > opts.BCacheSizeThreshold:
fused_plan.cache(B, jj)
fused_plan.cache(Y, ii)
fused_plan.unroll(jjj)
fused_plan.unroll(ii)
fused_plan.vectorize(jjjj)
return fused_plan, (A, B, C, Y) if C else (A, B, Y)
def MLAS(
A: Array,
B: Array,
C: Array,
transA=False,
transB=False,
alpha=1.0,
beta=1.0,
zero_C=False,
bias: Array = None,
opts=Options(),
target=Target.HOST
):
"""Emits a Gemm-like function that performs matrix multiplication
with the form Y = alpha * A * B + beta * C"""
if (zero_C or bias) and opts.UseBiasFusion:
return MLAS_with_bias(A, B, bias, C, transA, transB, alpha, beta, opts, target)
raise RuntimeError("Unexpected")
| 34.560411 | 104 | 0.64698 | 1,964 | 13,444 | 4.14053 | 0.106925 | 0.033448 | 0.021028 | 0.035047 | 0.771889 | 0.737826 | 0.717659 | 0.704009 | 0.700074 | 0.700074 | 0 | 0.017709 | 0.23557 | 13,444 | 388 | 105 | 34.649485 | 0.773572 | 0.105995 | 0 | 0.711744 | 0 | 0 | 0.02804 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.046263 | false | 0 | 0.007117 | 0 | 0.113879 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
8db2fa16564d76415ef446a113902b5c0f2d8432 | 107 | py | Python | tests/test_torrent_name_analyzer.py | opacam/torrent-name-analyzer | 3d6a8c05577925c4d8017a8151f725d9752771d7 | [
"MIT"
] | 1 | 2020-07-08T14:01:36.000Z | 2020-07-08T14:01:36.000Z | tests/test_torrent_name_analyzer.py | opacam/torrent-name-analyzer | 3d6a8c05577925c4d8017a8151f725d9752771d7 | [
"MIT"
] | null | null | null | tests/test_torrent_name_analyzer.py | opacam/torrent-name-analyzer | 3d6a8c05577925c4d8017a8151f725d9752771d7 | [
"MIT"
] | null | null | null | from torrent_name_analyzer import __version__
def test_version():
assert __version__ == '2020.05.19'
| 17.833333 | 45 | 0.766355 | 14 | 107 | 5.071429 | 0.857143 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.087912 | 0.149533 | 107 | 5 | 46 | 21.4 | 0.692308 | 0 | 0 | 0 | 0 | 0 | 0.093458 | 0 | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0.333333 | true | 0 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8df0420ac4a10736c52818b382ddd67078e77d76 | 28 | py | Python | NSI/__init__.py | yzerlaut/Waking_State_Index | 728fcbd5ab2047db591223d3231fdea2427a7fb4 | [
"MIT"
] | null | null | null | NSI/__init__.py | yzerlaut/Waking_State_Index | 728fcbd5ab2047db591223d3231fdea2427a7fb4 | [
"MIT"
] | null | null | null | NSI/__init__.py | yzerlaut/Waking_State_Index | 728fcbd5ab2047db591223d3231fdea2427a7fb4 | [
"MIT"
] | null | null | null | from . import IO, functions
| 14 | 27 | 0.75 | 4 | 28 | 5.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.178571 | 28 | 1 | 28 | 28 | 0.913043 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8df6fc301eaaa225fd92b3186a943f0efd34d18b | 45 | py | Python | examples/pytorch/swin/Swin-Transformer-Quantization/__init__.py | hieuhoang/FasterTransformer | 440695ccac874574b1d2e1121788e8fa674b4381 | [
"Apache-2.0"
] | null | null | null | examples/pytorch/swin/Swin-Transformer-Quantization/__init__.py | hieuhoang/FasterTransformer | 440695ccac874574b1d2e1121788e8fa674b4381 | [
"Apache-2.0"
] | null | null | null | examples/pytorch/swin/Swin-Transformer-Quantization/__init__.py | hieuhoang/FasterTransformer | 440695ccac874574b1d2e1121788e8fa674b4381 | [
"Apache-2.0"
] | null | null | null | from SwinTransformer.config import get_config | 45 | 45 | 0.911111 | 6 | 45 | 6.666667 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.066667 | 45 | 1 | 45 | 45 | 0.952381 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
309a4d3cf7a8cc63708a4089d74722e77fb3e56e | 179 | py | Python | src/HABApp/openhab/definitions/rest/__init__.py | DerOetzi/HABApp | a123fbfa9928ebb3cda9a84f6984dcba593c8236 | [
"Apache-2.0"
] | 44 | 2018-12-13T08:46:44.000Z | 2022-03-07T03:23:21.000Z | src/HABApp/openhab/definitions/rest/__init__.py | DerOetzi/HABApp | a123fbfa9928ebb3cda9a84f6984dcba593c8236 | [
"Apache-2.0"
] | 156 | 2019-03-02T20:53:31.000Z | 2022-03-23T13:13:58.000Z | src/HABApp/openhab/definitions/rest/__init__.py | DerOetzi/HABApp | a123fbfa9928ebb3cda9a84f6984dcba593c8236 | [
"Apache-2.0"
] | 18 | 2019-03-08T07:13:21.000Z | 2022-03-22T19:52:31.000Z | from .items import OpenhabItemDefinition
from .things import OpenhabThingChannelDefinition, OpenhabThingDefinition
from .links import ItemChannelLinkDefinition, LinkNotFoundError
| 44.75 | 73 | 0.893855 | 14 | 179 | 11.428571 | 0.714286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.078212 | 179 | 3 | 74 | 59.666667 | 0.969697 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
30b069c5d004b2f2416ddca2f6a21dcedd12ba9d | 127 | py | Python | AutoSummarization/controllers/summary.py | PaulChenAU/AutomaticSummarizationBck | fa7fc5474615720d2beab934471ee4cc1cdf9bbe | [
"MIT"
] | null | null | null | AutoSummarization/controllers/summary.py | PaulChenAU/AutomaticSummarizationBck | fa7fc5474615720d2beab934471ee4cc1cdf9bbe | [
"MIT"
] | null | null | null | AutoSummarization/controllers/summary.py | PaulChenAU/AutomaticSummarizationBck | fa7fc5474615720d2beab934471ee4cc1cdf9bbe | [
"MIT"
] | null | null | null | # -*- coding:utf-8 -*-
# __author__=''
from AutoSummarization.models.entities import Summary
def get_summary(data):
pass
| 15.875 | 53 | 0.708661 | 15 | 127 | 5.666667 | 0.933333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.009259 | 0.149606 | 127 | 7 | 54 | 18.142857 | 0.777778 | 0.267717 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0.333333 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
eb8393aac21f8eb8abdfa2a679b5f0ee808a2031 | 120 | py | Python | glue/external/echo/__init__.py | HPLegion/glue | 1843787ccb4de852dfe103ff58473da13faccf5f | [
"BSD-3-Clause"
] | 550 | 2015-01-08T13:51:06.000Z | 2022-03-31T11:54:47.000Z | glue/external/echo/__init__.py | HPLegion/glue | 1843787ccb4de852dfe103ff58473da13faccf5f | [
"BSD-3-Clause"
] | 1,362 | 2015-01-03T19:15:52.000Z | 2022-03-30T13:23:11.000Z | glue/external/echo/__init__.py | HPLegion/glue | 1843787ccb4de852dfe103ff58473da13faccf5f | [
"BSD-3-Clause"
] | 142 | 2015-01-08T13:08:00.000Z | 2022-03-18T13:25:57.000Z | import warnings
from echo import *
warnings.warn('glue.external.echo is deprecated, import from echo directly instead')
| 30 | 84 | 0.808333 | 17 | 120 | 5.705882 | 0.647059 | 0.28866 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.116667 | 120 | 3 | 85 | 40 | 0.915094 | 0 | 0 | 0 | 0 | 0 | 0.558333 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
ebcc9e73b97eeed6e8ede716ba46c2e01d44eb47 | 87 | py | Python | honeybot/hbotapi/generate.py | hailenwashere/honeybot | 95a6cd54283db1dcd4b33b9d281a7f6e1056ec09 | [
"MIT"
] | 60 | 2019-06-04T13:57:38.000Z | 2021-10-19T10:17:56.000Z | honeybot/hbotapi/generate.py | hailenwashere/honeybot | 95a6cd54283db1dcd4b33b9d281a7f6e1056ec09 | [
"MIT"
] | 70 | 2019-06-04T13:59:53.000Z | 2021-10-05T10:14:16.000Z | honeybot/hbotapi/generate.py | hailenwashere/honeybot | 95a6cd54283db1dcd4b33b9d281a7f6e1056ec09 | [
"MIT"
] | 95 | 2019-06-04T15:13:42.000Z | 2021-08-09T17:15:35.000Z | import os
import importlib.util
def gen_pluginsinfo():
print("to be redone ...")
| 12.428571 | 29 | 0.689655 | 12 | 87 | 4.916667 | 0.916667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.183908 | 87 | 6 | 30 | 14.5 | 0.830986 | 0 | 0 | 0 | 0 | 0 | 0.183908 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | true | 0 | 0.5 | 0 | 0.75 | 0.25 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
ebda66a678d969099c74f20c31cda1a9461596d3 | 61 | py | Python | example.py | natemara/aloft.py | be1e9a785aa0932bd7c761714977e70d2409181c | [
"MIT"
] | 3 | 2017-05-26T20:17:12.000Z | 2018-06-29T04:04:12.000Z | example.py | natemara/aloft.py | be1e9a785aa0932bd7c761714977e70d2409181c | [
"MIT"
] | null | null | null | example.py | natemara/aloft.py | be1e9a785aa0932bd7c761714977e70d2409181c | [
"MIT"
] | 2 | 2020-04-19T17:32:49.000Z | 2021-02-15T16:38:34.000Z | from aloft.api import winds_aloft
print(winds_aloft('den'))
| 15.25 | 33 | 0.786885 | 10 | 61 | 4.6 | 0.7 | 0.434783 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.098361 | 61 | 3 | 34 | 20.333333 | 0.836364 | 0 | 0 | 0 | 0 | 0 | 0.04918 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0.5 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 6 |
ccef1345df6e027806e7225e19ab2f312324189b | 7,268 | py | Python | tests/test_smt_outcome.py | vwegmayr/entrack | ba3cb68121b8a56faf765d97baaff98bb574dc6b | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2020-03-05T15:21:42.000Z | 2020-03-05T15:21:42.000Z | tests/test_smt_outcome.py | vwegmayr/entrack | ba3cb68121b8a56faf765d97baaff98bb574dc6b | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2020-11-02T10:02:50.000Z | 2020-11-02T10:02:50.000Z | tests/test_smt_outcome.py | vwegmayr/entrack | ba3cb68121b8a56faf765d97baaff98bb574dc6b | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | import unittest
import os
import json
from modules.hooks import write_smt_txt, write_smt_num
class Test_SMT_Text_Outcome(unittest.TestCase):
@classmethod
def setUpClass(self):
self.outcome_path = "tests/sumatra_outcome.json"
def tearDown(self):
if os.path.exists(self.outcome_path):
os.remove(self.outcome_path)
def test_create_new_outcome(self):
write_smt_txt("Awesome", "tests")
self.assertTrue(os.path.exists(self.outcome_path))
def test_new_outcome_is_dict(self):
write_smt_txt("Awesome", "tests")
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertIsInstance(outcome, dict)
def test_new_outcome_keys(self):
write_smt_txt("Awesome", "tests")
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(len(outcome), 2)
self.assertIn("text_outcome", outcome)
self.assertIn("numeric_outcome", outcome)
def test_new_outcome_content(self):
write_smt_txt("Awesome", "tests")
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["text_outcome"], "| Awesome")
def test_appending_content_with_linebreak(self):
write_smt_txt("Awesome", "tests")
write_smt_txt("Great", "tests")
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["text_outcome"],
"| Awesome\n| Great")
def test_appending_content_inline(self):
write_smt_txt("Awesome", "tests")
write_smt_txt("Great", "tests", inline=True)
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["text_outcome"],
"| Awesome Great")
def test_create_with_int_metric(self):
write_smt_txt(22, "tests", metric="xy")
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["text_outcome"],
"| xy: 22")
def test_create_with_float_metric(self):
write_smt_txt(1.239, "tests", metric="xy")
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["text_outcome"],
"| xy: 1.24")
def test_append_with_metric_inline(self):
write_smt_txt("Awesome", "tests")
write_smt_txt(22, "tests", metric="xy", inline=True)
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["text_outcome"],
"| Awesome xy: 22")
class Test_SMT_Numerical_Outcome(unittest.TestCase):
@classmethod
def setUpClass(self):
self.outcome_path = "tests/sumatra_outcome.json"
def tearDown(self):
if os.path.exists(self.outcome_path):
os.remove(self.outcome_path)
def test_create(self):
write_smt_num(x=0, y=42, metric="accuracy",
smt_outcome_path=self.outcome_path)
self.assertTrue(os.path.exists(self.outcome_path))
def test_new_outcome_keys(self):
write_smt_num(x=0, y=42, metric="accuracy",
smt_outcome_path=self.outcome_path)
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertIn("numeric_outcome", outcome)
self.assertIn("accuracy", outcome["numeric_outcome"])
self.assertIn("x", outcome["numeric_outcome"]["accuracy"])
self.assertIn("y", outcome["numeric_outcome"]["accuracy"])
self.assertIn("x_label", outcome["numeric_outcome"]["accuracy"])
def test_new_outcome_values(self):
write_smt_num(x=0, y=42, metric="accuracy",
smt_outcome_path=self.outcome_path)
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x"], [0])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["y"], [42])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x_label"], "")
def test_new_outcome_values_with_x_label(self):
write_smt_num(x=0, y=42, metric="accuracy", x_label="steps",
smt_outcome_path=self.outcome_path)
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x"], [0])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["y"], [42])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x_label"],
"steps")
def test_append(self):
write_smt_num(x=0, y=42, metric="accuracy",
smt_outcome_path=self.outcome_path)
write_smt_num(x=1, y=43, metric="accuracy",
smt_outcome_path=self.outcome_path)
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x"], [0, 1])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["y"], [42, 43])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x_label"], "")
def test_append_with_new_label(self):
write_smt_num(x=0, y=42, metric="accuracy",
smt_outcome_path=self.outcome_path)
write_smt_num(x=1, y=43, metric="accuracy", x_label="steps",
smt_outcome_path=self.outcome_path)
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x"], [0, 1])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["y"], [42, 43])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x_label"],
"steps")
def test_append_new_metric(self):
write_smt_num(x=0, y=42, metric="accuracy",
smt_outcome_path=self.outcome_path)
write_smt_num(x=1, y=0.1, metric="F1",
smt_outcome_path=self.outcome_path)
with open(self.outcome_path, "r") as outcome_file:
outcome = json.load(outcome_file)
self.assertIn("F1", outcome["numeric_outcome"])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x"], [0])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["y"], [42])
self.assertEqual(outcome["numeric_outcome"]["accuracy"]["x_label"], "")
self.assertEqual(outcome["numeric_outcome"]["F1"]["x"], [1])
self.assertEqual(outcome["numeric_outcome"]["F1"]["y"], [0.1])
self.assertEqual(outcome["numeric_outcome"]["F1"]["x_label"], "") | 41.531429 | 84 | 0.61186 | 876 | 7,268 | 4.813927 | 0.083333 | 0.109557 | 0.113825 | 0.123785 | 0.875504 | 0.846099 | 0.820251 | 0.785392 | 0.779464 | 0.779464 | 0 | 0.013797 | 0.252064 | 7,268 | 175 | 85 | 41.531429 | 0.761957 | 0 | 0 | 0.664234 | 0 | 0 | 0.143486 | 0.007154 | 0 | 0 | 0 | 0 | 0.262774 | 1 | 0.145985 | false | 0 | 0.029197 | 0 | 0.189781 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
15d790e574a30d0df2fdc6ca650b919051c1e2c0 | 38 | py | Python | p1/analyzer/__init__.py | gbuenoandrade/MC855-2S2017-GROUP4 | 6023d08140b2faee56c67731244ac4352b8c2ed7 | [
"MIT"
] | null | null | null | p1/analyzer/__init__.py | gbuenoandrade/MC855-2S2017-GROUP4 | 6023d08140b2faee56c67731244ac4352b8c2ed7 | [
"MIT"
] | null | null | null | p1/analyzer/__init__.py | gbuenoandrade/MC855-2S2017-GROUP4 | 6023d08140b2faee56c67731244ac4352b8c2ed7 | [
"MIT"
] | null | null | null | from analyzer.analyzer import Analyzer | 38 | 38 | 0.894737 | 5 | 38 | 6.8 | 0.6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.078947 | 38 | 1 | 38 | 38 | 0.971429 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
c60a4a0163c41220efef8d3b5f0257a086837c0d | 288 | py | Python | misago/core/threadstore.py | HenryChenV/iJiangNan | 68f156d264014939f0302222e16e3125119dd3e3 | [
"MIT"
] | 1 | 2017-07-25T03:04:36.000Z | 2017-07-25T03:04:36.000Z | misago/core/threadstore.py | HenryChenV/iJiangNan | 68f156d264014939f0302222e16e3125119dd3e3 | [
"MIT"
] | null | null | null | misago/core/threadstore.py | HenryChenV/iJiangNan | 68f156d264014939f0302222e16e3125119dd3e3 | [
"MIT"
] | null | null | null | from threading import local
_thread_local = local()
def get(key, default=None):
return _thread_local.__dict__.get(key, default)
def set(key, value):
_thread_local.__dict__[key] = value
return _thread_local.__dict__[key]
def clear():
_thread_local.__dict__.clear()
| 16 | 51 | 0.725694 | 39 | 288 | 4.692308 | 0.384615 | 0.300546 | 0.327869 | 0.229508 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 288 | 17 | 52 | 16.941176 | 0.7625 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0.111111 | 0.111111 | 0.666667 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 6 |
c611839dc06ebd27d45f57f265f058175e51d76e | 194 | py | Python | freenit/project/project/models/role.py | mekanix/freenit-backend | edacd70490c763ea5ed787b2e57f0ba4fba0d56b | [
"BSD-2-Clause"
] | null | null | null | freenit/project/project/models/role.py | mekanix/freenit-backend | edacd70490c763ea5ed787b2e57f0ba4fba0d56b | [
"BSD-2-Clause"
] | null | null | null | freenit/project/project/models/role.py | mekanix/freenit-backend | edacd70490c763ea5ed787b2e57f0ba4fba0d56b | [
"BSD-2-Clause"
] | 1 | 2019-11-18T16:15:43.000Z | 2019-11-18T16:15:43.000Z | from freenit.models.TYPE.role import Role as BaseRole
from freenit.models.TYPE.role import UserRoles as BaseUserRoles
class Role(BaseRole):
pass
class UserRoles(BaseUserRoles):
pass
| 17.636364 | 63 | 0.783505 | 26 | 194 | 5.846154 | 0.461538 | 0.144737 | 0.223684 | 0.276316 | 0.407895 | 0.407895 | 0 | 0 | 0 | 0 | 0 | 0 | 0.154639 | 194 | 10 | 64 | 19.4 | 0.926829 | 0 | 0 | 0.333333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 6 |
d68deaccf931c7714f62428c712df4bda603c425 | 341 | py | Python | pystibmivb/__init__.py | helldog136/pystibmivb | 1e8bea727b1d324a154cbf79849f6ea5bce68b61 | [
"CC-BY-4.0"
] | 3 | 2020-05-28T07:18:54.000Z | 2021-03-03T17:14:23.000Z | pystibmivb/__init__.py | helldog136/pystibmivb | 1e8bea727b1d324a154cbf79849f6ea5bce68b61 | [
"CC-BY-4.0"
] | 11 | 2020-05-28T11:45:04.000Z | 2020-06-17T06:14:20.000Z | pystibmivb/__init__.py | helldog136/pystibmivb | 1e8bea727b1d324a154cbf79849f6ea5bce68b61 | [
"CC-BY-4.0"
] | 1 | 2020-06-02T21:10:27.000Z | 2020-06-02T21:10:27.000Z | """Initialize the package."""
from pystibmivb.client import AbstractSTIBAPIClient, STIBAPIClient, STIBAPIAuthClient
from pystibmivb.service import STIBService, InvalidLineFilterException, NoScheduleFromAPIException, STIBStop
from pystibmivb.service import ShapefileService, InvalidStopNameException
from .domain import *
NAME = "pystibmivb" | 48.714286 | 108 | 0.856305 | 29 | 341 | 10.068966 | 0.655172 | 0.143836 | 0.143836 | 0.184932 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.082111 | 341 | 7 | 109 | 48.714286 | 0.932907 | 0.067449 | 0 | 0 | 0 | 0 | 0.031949 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.8 | 0 | 0.8 | 0 | 1 | 0 | 1 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
d6c185383c3c6221f67a12d0c2acd96e516f47ae | 75 | py | Python | TransForm_Kit/Quantization/models/__init__.py | Abraham-Xu/TF2 | a5bc18acb7743dc5b6e85cfbefa8b88c3785ce78 | [
"Apache-2.0"
] | 144 | 2019-08-28T01:10:20.000Z | 2022-03-23T08:47:57.000Z | TransForm_Kit/Quantization/models/__init__.py | Abraham-Xu/TF2 | a5bc18acb7743dc5b6e85cfbefa8b88c3785ce78 | [
"Apache-2.0"
] | 19 | 2019-09-10T01:46:34.000Z | 2021-12-02T09:05:14.000Z | TransForm_Kit/Quantization/debug/models/__init__.py | TF2-Engine/TF2 | 1a3ce4c63675a30156bfcf3a1b9682154ef13183 | [
"Apache-2.0"
] | 63 | 2019-08-28T08:28:50.000Z | 2022-01-19T01:44:30.000Z | from .GoogLeNet import *
from .SSD import *
from .SSD.SSD import build_ssd
| 18.75 | 30 | 0.76 | 12 | 75 | 4.666667 | 0.416667 | 0.357143 | 0.464286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.16 | 75 | 3 | 31 | 25 | 0.888889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
d6e5e146e3e6a681720a72d8fc7371bdc1eb0b10 | 2,597 | py | Python | homie/mocks/mqtt.py | fermuch/microhomie | f318a94b149e95195ae206f016bbfe37b5b8cbe2 | [
"MIT"
] | null | null | null | homie/mocks/mqtt.py | fermuch/microhomie | f318a94b149e95195ae206f016bbfe37b5b8cbe2 | [
"MIT"
] | null | null | null | homie/mocks/mqtt.py | fermuch/microhomie | f318a94b149e95195ae206f016bbfe37b5b8cbe2 | [
"MIT"
] | null | null | null | import sys
import network
# only native python (not esp32-loba) can reach this code.
# Micropython doesn't have typing module.
if sys.implementation.name not in ('micropython'):
from typing import Optional, Callable, Tuple
class Mqtt:
def __init__(
self,
name: str,
server: str,
user: Optional[str] = "",
password: Optional[str] = "",
port: Optional[int] = 1883,
autoreconnect: Optional[bool] = False,
clientid: Optional[str] = "mpy_mqtt_client",
cleansession: Optional[bool] = False,
keepalive: Optional[int] = 120,
lwt_topic: Optional[str] = None,
lwt_msg: Optional[str] = None,
lwt_retain: Optional[bool] = 0,
lwt_qos: Optional[0, 1, 2] = 0,
cert: Optional[str] = None,
connected_cb: Optional[Callable[[str], None]] = lambda x: None,
disconnected_cb: Optional[Callable[[str], None]] = lambda x: None,
subscribed_cb: Optional[Callable[[str, str], None]] = lambda x, y: None,
unsubscribed_cb: Optional[Callable[[str, str], None]] = lambda x, y: None,
published_cb: Optional[Callable[[str, bool], None]] = lambda x, y: None,
data_cb: Optional[Callable[[str, int, [str, bytes]], None]] = lambda x, y, z: None
):
pass
def config(
self,
user: Optional[str] = "",
password: Optional[str] = "",
port: Optional[int] = 1883,
autoreconnect: Optional[bool] = False,
clientid: Optional[str] = "mpy_mqtt_client",
cleansession: Optional[bool] = False,
keepalive: Optional[int] = 120,
lwt_topic: Optional[str] = None,
lwt_msg: Optional[str] = None,
lwt_retain: Optional[bool] = 0,
lwt_qos: Optional[0, 1, 2] = 0,
cert: Optional[str] = None,
connected_cb: Optional[Callable[[str], None]] = lambda x: None,
disconnected_cb: Optional[Callable[[str], None]] = lambda x: None,
subscribed_cb: Optional[Callable[[str, str], None]] = lambda x, y: None,
unsubscribed_cb: Optional[Callable[[str, str], None]] = lambda x, y: None,
published_cb: Optional[Callable[[str, bool], None]] = lambda x, y: None,
data_cb: Optional[Callable[[str, int, [str, bytes]], None]] = lambda x, y, z: None
) -> None:
pass
def status(self) -> Tuple[[int, str]]:
pass
def subscribe(
self,
topic: str,
qos: Optional[0, 1, 2] = 0
) -> bool:
pass
def unsubscribe(self, topic: str) -> bool:
pass
def publish(self, topic: str, msg: [str, bytes], qos: [0, 1, 2] = 0) -> bool:
pass
def stop(self) -> None:
pass
def start(self) -> None:
pass
def free(self) -> None:
pass
network.mqtt = Mqtt | 31.670732 | 86 | 0.627647 | 346 | 2,597 | 4.630058 | 0.228324 | 0.061174 | 0.134831 | 0.157303 | 0.734707 | 0.734707 | 0.72784 | 0.709114 | 0.709114 | 0.709114 | 0 | 0.016823 | 0.221794 | 2,597 | 82 | 87 | 31.670732 | 0.775854 | 0.036966 | 0 | 0.685714 | 0 | 0 | 0.016407 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.128571 | false | 0.157143 | 0.042857 | 0 | 0.185714 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 6 |
ba502984813c49ecee586b44a1a5e8fcbf9ab0aa | 157 | py | Python | deep_patient_cohorts/__init__.py | Semantic-Health/deep-patient-cohorts | e0f49bd5434bd22a81c09272e727b59e09154a22 | [
"MIT"
] | 2 | 2021-03-31T04:54:01.000Z | 2021-09-30T22:00:13.000Z | deep_patient_cohorts/__init__.py | Semantic-Health/deep-patient-cohorts | e0f49bd5434bd22a81c09272e727b59e09154a22 | [
"MIT"
] | 64 | 2020-09-08T21:56:28.000Z | 2022-03-24T23:11:39.000Z | deep_patient_cohorts/__init__.py | Semantic-Health/deep-patient-cohorts | e0f49bd5434bd22a81c09272e727b59e09154a22 | [
"MIT"
] | 3 | 2020-09-12T01:23:46.000Z | 2022-03-03T06:05:35.000Z | __version__ = "0.1.0"
from deep_patient_cohorts.common.utils import ABSTAIN, NEGATIVE, POSITIVE
from deep_patient_cohorts.noisy_labeler import NoisyLabeler
| 31.4 | 73 | 0.847134 | 22 | 157 | 5.636364 | 0.727273 | 0.129032 | 0.241935 | 0.354839 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.020979 | 0.089172 | 157 | 4 | 74 | 39.25 | 0.846154 | 0 | 0 | 0 | 0 | 0 | 0.031847 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.666667 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
ba6edd8ea759fb19ebd54a1583d820f17250064a | 54,018 | py | Python | stage/test_gcp_stages.py | anubandhan/datacollector-tests | 301c024c66d68353735256b262b681dd05ba16cc | [
"Apache-2.0"
] | null | null | null | stage/test_gcp_stages.py | anubandhan/datacollector-tests | 301c024c66d68353735256b262b681dd05ba16cc | [
"Apache-2.0"
] | 1 | 2019-04-24T11:06:38.000Z | 2019-04-24T11:06:38.000Z | stage/test_gcp_stages.py | anubandhan/datacollector-tests | 301c024c66d68353735256b262b681dd05ba16cc | [
"Apache-2.0"
] | 2 | 2019-05-24T06:34:37.000Z | 2020-03-30T11:48:18.000Z | # Copyright 2017 StreamSets Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import json
import logging
import math
import time
import uuid
from datetime import datetime
from string import ascii_letters, ascii_lowercase
from time import sleep
from google.cloud.bigquery import Dataset, SchemaField, Table
from streamsets.testframework.markers import gcp, sdc_min_version
from streamsets.testframework.utils import get_random_string
logger = logging.getLogger(__name__)
DEFAULT_COLUMN_FAMILY_NAME = 'cf' # for Google Bigtable
# For Google pub/sub
MSG_DATA = 'Hello World from SDC and DPM!'
SNAPSHOT_TIMEOUT_SEC = 120
# For Google BigQuery, data to insert- needs to be in the sorted order by name.
bytes_column = base64.b64encode("dataAsBytes".encode('utf-8'))
ROWS_TO_INSERT = [(None, 'null ID', 12.3456, '99999999999999999999999999999.999999999', True,
'2019-02-05', '2019-02-05 23:59:59.999', '2007-05-28 07:52:31.123 UTC', '08:39:01.123',
bytes_column),
(1, 'full record', 12.3456, '99999999999999999999999999999.999999999', True,
'2019-02-05', '2019-02-05 23:59:59.999', '2007-05-28 07:52:31.123 UTC', '08:39:01.123',
bytes_column),
(2, 'null float', None, '99999999999999999999999999999.999999999', True,
'2019-02-05', '2019-02-05 23:59:59.999', '2007-05-28 07:52:31.123 UTC', '08:39:01.123',
bytes_column),
(3, 'null numeric', 12.3456, None, True,
'2019-02-05', '2019-02-05 23:59:59.999', '2007-05-28 07:52:31.123 UTC', '08:39:01.123',
bytes_column),
(4, 'null boolean', 12.3456, '99999999999999999999999999999.999999999', None,
'2019-02-05', '2019-02-05 23:59:59.999', '2007-05-28 07:52:31.123 UTC', '08:39:01.123',
bytes_column),
(5, 'null date', 12.3456, '99999999999999999999999999999.999999999', True,
None, '2019-02-05 23:59:59.999', '2007-05-28 07:52:31.123 UTC', '08:39:01.123', bytes_column),
(6, 'null datetime', 12.3456, '99999999999999999999999999999.999999999', True,
'2019-02-05', None, '2007-05-28 07:52:31.123 UTC', '08:39:01.123', bytes_column),
(7, 'null timestamp', 12.3456, '99999999999999999999999999999.999999999', True,
'2019-02-05', '2019-02-05 23:59:59.999', None, '08:39:01.123', bytes_column),
(8, 'null time', 12.3456, '99999999999999999999999999999.999999999', True,
'2019-02-05', '2019-02-05 23:59:59.999', '2007-05-28 07:52:31.123 UTC', None, bytes_column),
(9, 'null bytes', 12.3456, '99999999999999999999999999999.999999999', True,
'2019-02-05', '2019-02-05 23:59:59.999', '2007-05-28 07:52:31.123 UTC', '08:39:01.123', None)]
ROWS_TO_INSERT_2 = [(11, 'full record 2', 12.3456, '99999999999999999999999999999.999999995', True,
'2019-02-05', '2019-02-05 23:59:59.995', '2007-05-28 07:52:31.125 UTC', '08:39:01.125',
bytes_column),
(12, 'full record 3', None, '99999999999999999999999999999.999999995', True,
'2019-02-05', '2019-02-05 23:59:59.995', '2007-05-28 07:52:31.125 UTC', '08:39:01.125',
bytes_column),
(13, 'full record 4', 12.3456, '99999999999999999999999999999.999999995', True,
'2019-02-05', '2019-02-05 23:59:59.995', '2007-05-28 07:52:31.125 UTC', '08:39:01.125',
bytes_column),
(14, 'full record 5', 12.3456, '99999999999999999999999999999.999999995', False,
'2019-02-05', '2019-02-05 23:59:59.995', '2007-05-28 07:52:31.125 UTC', '08:39:01.125',
bytes_column),
(15, 'full record 6', 12.3456, '99999999999999999999999999999.999999995', True,
'2019-02-05', '2019-02-05 23:59:59.995', '2007-05-28 07:52:31.125 UTC', '08:39:01.125',
bytes_column),
(16, 'full record 7', 12.3456, '99999999999999999999999999999.999999995', True,
'2019-02-05', '2019-02-05 23:59:59.995', '2007-05-28 07:52:31.125 UTC', '08:39:01.125',
bytes_column),
(17, 'full record 8', 12.3456, '99999999999999999999999999999.999999995', True,
'2019-02-05', '2019-02-05 23:59:59.995', '2007-05-28 07:52:31.125 UTC', '08:39:01.125',
bytes_column),
(18, 'full record 9', 12.3456, '99999999999999999999999999999.999999995', True,
'2019-02-05', '2019-02-05 23:59:59.995', '2007-05-28 07:52:31.125 UTC', '08:39:01.125',
bytes_column),
(19, 'full record 10', 12.3456, '99999999999999999999999999999.999999995', True,
'2019-02-05', '2019-02-05 23:59:59.995', '2007-05-28 07:52:31.125 UTC', '08:39:01.125',
bytes_column)]
ROWS_EXPECTED = [('Cristiano Ronaldo', 32),
('David Beckham', 32),
('Gerard Pique', 30),
('Lionel Messi', 30),
('Mario Gotze', 25),
('Neymar', 25),
('Pele', 76),
('Ronaldinho', 40),
('Ronaldo', 40),
('Zinedine Zidane', 42)]
CSV_DATA_TO_INSERT = ['full_name,age'] + [','.join(str(element) for element in row) for row in ROWS_EXPECTED]
@gcp
@sdc_min_version('2.7.2.0')
def test_google_bigquery_destination(sdc_builder, sdc_executor, gcp):
"""
Send data to Google BigQuery from Dev Raw Data Source and
confirm that Google BigQuery destination successfully recieves them using Google BigQuery client.
This is achieved by using a deduplicator which assures that there is only one ingest to Google BigQuery.
The pipeline looks like:
dev_raw_data_source >> record_deduplicator >> google_bigquery
record_deduplicator >> trash
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
dev_raw_data_source.set_attributes(data_format='DELIMITED',
header_line='WITH_HEADER',
raw_data='\n'.join(CSV_DATA_TO_INSERT))
dataset_name = get_random_string(ascii_letters, 5)
table_name = get_random_string(ascii_letters, 5)
google_bigquery = pipeline_builder.add_stage('Google BigQuery', type='destination')
google_bigquery.set_attributes(dataset=dataset_name,
table_name=table_name)
record_deduplicator = pipeline_builder.add_stage('Record Deduplicator')
trash = pipeline_builder.add_stage('Trash')
dev_raw_data_source >> record_deduplicator >> google_bigquery
record_deduplicator >> trash
pipeline = pipeline_builder.build(title='Google BigQuery Destination').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
bigquery_client = gcp.bigquery_client
schema = [SchemaField('full_name', 'STRING', mode='required'),
SchemaField('age', 'INTEGER', mode='required')]
dataset_ref = Dataset(bigquery_client.dataset(dataset_name))
try:
logger.info('Creating dataset %s using Google BigQuery client ...', dataset_name)
dataset = bigquery_client.create_dataset(dataset_ref)
table = bigquery_client.create_table(Table(dataset_ref.table(table_name), schema=schema))
logger.info('Starting BigQuery Destination pipeline and waiting for it to produce records ...')
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_batch_count(1)
logger.info('Stopping BigQuery Destination pipeline and getting the count of records produced in total ...')
sdc_executor.stop_pipeline(pipeline)
# Verify by reading records using Google BigQuery client
data_from_bigquery = [tuple(row.values()) for row in bigquery_client.list_rows(table)]
data_from_bigquery.sort()
logger.debug('read_data = {}'.format(data_from_bigquery))
assert ROWS_EXPECTED == data_from_bigquery
finally:
bigquery_client.delete_dataset(dataset_ref, delete_contents=True)
@gcp
@sdc_min_version('2.7.2.0')
def test_google_bigquery_destination_multiple_types(sdc_builder, sdc_executor, gcp):
"""Simple big query destination test with INSERT operation.
The pipeline inserts 1000 records of multiple types.
A type converter is included to transform decimal to float.
The pipeline should look like:
dev_data_generator >> field_type_converter >> google_bigquery
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_data_generator = pipeline_builder.add_stage('Dev Data Generator')
dev_data_generator.fields_to_generate = [
{'field': 'field1', 'type': 'STRING'},
{'field': 'field2', 'type': 'DATETIME'},
{'field': 'field3', 'type': 'INTEGER'},
{'field': 'field4', 'precision': 10, 'scale': 2, 'type': 'DECIMAL'},
{'field': 'field5', 'type': 'DOUBLE'}
]
batch_size = 10000
dev_data_generator.set_attributes(delay_between_batches=0, batch_size=batch_size)
dataset_name = get_random_string(ascii_letters, 5)
table_name = get_random_string(ascii_letters, 5)
google_bigquery = pipeline_builder.add_stage('Google BigQuery', type='destination')
google_bigquery.set_attributes(dataset=dataset_name,
table_name=table_name,
stage_on_record_error='TO_ERROR')
# Create Field Type Converter
conversions = [{'fields': ['/field4'],
'targetType': 'FLOAT'}]
field_type_converter = pipeline_builder.add_stage('Field Type Converter')
field_type_converter.set_attributes(conversion_method='BY_FIELD',
field_type_converter_configs=conversions)
dev_data_generator >> field_type_converter >> google_bigquery
pipeline = pipeline_builder.build(title="BigQuery Destination multiple types")
sdc_executor.add_pipeline(pipeline.configure_for_environment(gcp))
# FLOAT64 is used because there is a bug with NUMERIC, in bigquery Client
bigquery_client = gcp.bigquery_client
schema = [SchemaField('field1', 'STRING', mode='required'),
SchemaField('field2', 'DATETIME', mode='required'),
SchemaField('field3', 'INTEGER', mode='required'),
SchemaField('field4', 'FLOAT64', mode='required'),
SchemaField('field5', 'FLOAT', mode='required')
]
dataset_ref = Dataset(bigquery_client.dataset(dataset_name))
try:
logger.info('Creating dataset %s using Google BigQuery client ...', dataset_name)
dataset = bigquery_client.create_dataset(dataset_ref)
table = bigquery_client.create_table(Table(dataset_ref.table(table_name), schema=schema))
logger.info('Starting BigQuery Destination pipeline and waiting for it to produce records ...')
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_output_records_count(batch_size, timeout_sec=3600)
snapshot = sdc_executor.capture_snapshot(pipeline).snapshot
logger.info('Stopping BigQuery Destination pipeline and getting the count of records produced in total ...')
sdc_executor.stop_pipeline(pipeline)
# Verify by reading records using Google BigQuery client
data_from_bigquery = [row for row in bigquery_client.list_rows(table)]
assert len(data_from_bigquery) > batch_size
stage = snapshot[google_bigquery.instance_name]
assert len(stage.error_records) == 0
finally:
logger.info('Dropping table %s in Google Big Query database ...', table_name)
bigquery_client.delete_dataset(dataset_ref, delete_contents=True)
@gcp
@sdc_min_version('3.11.0')
def test_google_bigquery_destination_empty_table_name_error(sdc_builder, sdc_executor, gcp):
"""Test that BigQuery API does not return a NullPointerException if asked for an empty table name
Pipeline:
dev_raw_data_source >> google_bigquery
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
json_data = {'table': ''}
# Dev Raw Data Source
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
dev_raw_data_source.set_attributes(
data_format = 'JSON',
raw_data = json.dumps(json_data),
stop_after_first_batch = True
)
# Google BigQuery Destination
dataset_name = 'dont_care'
table_name = '${record:value(\'/table\')}'
google_bigquery = pipeline_builder.add_stage('Google BigQuery', type = 'destination')
google_bigquery.set_attributes(dataset = dataset_name,
table_name = table_name,
stage_on_record_error = 'TO_ERROR')
# Implement pipeline topology
dev_raw_data_source >> google_bigquery
pipeline = pipeline_builder.build(title="BigQuery Destination empty table name")
sdc_executor.add_pipeline(pipeline.configure_for_environment(gcp))
snapshot = sdc_executor.capture_snapshot(pipeline, start_pipeline = True).snapshot
stage = snapshot[google_bigquery.instance_name]
# Verify that we have exactly one record
assert len(stage.error_records) == 1
# Verify that the error is indeed a BIGQUERY_18 (table name is empty or expression evaluates to empty)
assert stage.error_records[0].header['errorCode'] == 'BIGQUERY_18'
@gcp
@sdc_min_version('2.7.0.0')
def test_google_bigquery_origin(sdc_builder, sdc_executor, gcp):
"""
Create data using Google BigQuery client
and then check if Google BigQuery origin receives them using snapshot.
The pipeline looks like:
google_bigquery >> trash
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
dataset_name = get_random_string(ascii_letters, 5)
table_name = get_random_string(ascii_letters, 5)
google_bigquery = pipeline_builder.add_stage('Google BigQuery', type='origin')
query_str = f'SELECT * FROM {dataset_name}.{table_name} ORDER BY id'
google_bigquery.set_attributes(query=query_str)
trash = pipeline_builder.add_stage('Trash')
google_bigquery >> trash
pipeline = pipeline_builder.build(title='Google BigQuery').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
bigquery_client = gcp.bigquery_client
schema = [SchemaField('id', 'INTEGER', mode='NULLABLE'),
SchemaField('name', 'STRING', mode='NULLABLE'),
SchemaField('floatVal', 'FLOAT', mode='NULLABLE'),
SchemaField('numericVal', 'NUMERIC', mode='NULLABLE'),
SchemaField('booleanVal', 'BOOLEAN', mode='NULLABLE'),
SchemaField('dateVal', 'DATE', mode='NULLABLE'),
SchemaField('datetimeVal', 'DATETIME', mode='NULLABLE'),
SchemaField('timestampVal', 'TIMESTAMP', mode='NULLABLE'),
SchemaField('timeVal', 'TIME', mode='NULLABLE'),
SchemaField('bytesVal', 'BYTES', mode='NULLABLE')]
dataset_ref = Dataset(bigquery_client.dataset(dataset_name))
try:
# Using Google bigquery client, create dataset, table and data inside table
logger.info('Creating dataset %s using Google bigquery client ...', dataset_name)
dataset = bigquery_client.create_dataset(dataset_ref)
table = bigquery_client.create_table(Table(dataset_ref.table(table_name), schema=schema))
errors = bigquery_client.insert_rows(table, ROWS_TO_INSERT)
assert not errors
# Start pipeline and verify correct rows are received using snaphot.
logger.info('Starting pipeline and snapshot')
snapshot = sdc_executor.capture_snapshot(pipeline, start_pipeline=True).snapshot
if sdc_executor.get_pipeline_status(pipeline) == 'RUNNING':
sdc_executor.stop_pipeline(pipeline)
get_value_by_index = lambda x: list(x[0].field.values())[x[1]].value
rows_from_snapshot = [(int(get_value_by_index((record, 0)))
if get_value_by_index((record, 0)) is not None else None,
get_value_by_index((record, 1)),
float(get_value_by_index((record, 2)))
if get_value_by_index((record, 2)) is not None else None,
str(get_value_by_index((record, 3)))
if get_value_by_index((record, 3)) is not None else None,
get_value_by_index((record, 4)),
get_value_by_index((record, 5)).strftime("%Y-%m-%d")
if get_value_by_index((record, 5)) is not None else None,
get_value_by_index((record, 6)).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
if get_value_by_index((record, 6)) is not None else None,
'{} UTC'.format(get_value_by_index((record, 7)).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
if get_value_by_index((record, 7)) is not None else None,
get_value_by_index((record, 8)).strftime('%H:%M:%S.%f')[:-3]
if get_value_by_index((record, 8)) is not None else None,
get_value_by_index((record, 9)) if get_value_by_index((record, 9)) is not None else None)
for record in snapshot[google_bigquery].output]
assert rows_from_snapshot == ROWS_TO_INSERT
finally:
bigquery_client.delete_dataset(dataset_ref, delete_contents=True)
@gcp
@sdc_min_version('2.7.0.0')
def test_google_bigquery_origin_stop_resume(sdc_builder, sdc_executor, gcp):
"""
Create data using Google BigQuery client
and then check if Google BigQuery origin receives them using snapshot.
Stop the pipeline, add more data, and check the second batch.
The pipeline looks like:
google_bigquery >> trash
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
dataset_name = get_random_string(ascii_letters, 5)
table_name = get_random_string(ascii_letters, 5)
google_bigquery = pipeline_builder.add_stage('Google BigQuery', type='origin')
query_str = f'SELECT * FROM {dataset_name}.{table_name} ORDER BY id'
google_bigquery.set_attributes(query=query_str)
trash = pipeline_builder.add_stage('Trash')
google_bigquery >> trash
pipeline = pipeline_builder.build(title='Google BigQuery').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
bigquery_client = gcp.bigquery_client
schema = [SchemaField('id', 'INTEGER', mode='NULLABLE'),
SchemaField('name', 'STRING', mode='NULLABLE'),
SchemaField('floatVal', 'FLOAT', mode='NULLABLE'),
SchemaField('numericVal', 'NUMERIC', mode='NULLABLE'),
SchemaField('booleanVal', 'BOOLEAN', mode='NULLABLE'),
SchemaField('dateVal', 'DATE', mode='NULLABLE'),
SchemaField('datetimeVal', 'DATETIME', mode='NULLABLE'),
SchemaField('timestampVal', 'TIMESTAMP', mode='NULLABLE'),
SchemaField('timeVal', 'TIME', mode='NULLABLE'),
SchemaField('bytesVal', 'BYTES', mode='NULLABLE')]
dataset_ref = Dataset(bigquery_client.dataset(dataset_name))
try:
# Using Google bigquery client, create dataset, table and data inside table
logger.info('Creating dataset %s using Google bigquery client ...', dataset_name)
dataset = bigquery_client.create_dataset(dataset_ref)
table = bigquery_client.create_table(Table(dataset_ref.table(table_name), schema=schema))
errors = bigquery_client.insert_rows(table, ROWS_TO_INSERT)
assert not errors
# Start pipeline and verify correct rows are received using snaphot.
logger.info('Starting pipeline and snapshot')
snapshot = sdc_executor.capture_snapshot(pipeline, start_pipeline=True).snapshot
if sdc_executor.get_pipeline_status(pipeline) == 'RUNNING':
sdc_executor.stop_pipeline(pipeline)
get_value_by_index = lambda x: list(x[0].field.values())[x[1]].value
rows_from_snapshot = [(int(get_value_by_index((record, 0)))
if get_value_by_index((record, 0)) is not None else None,
get_value_by_index((record, 1)),
float(get_value_by_index((record, 2)))
if get_value_by_index((record, 2)) is not None else None,
str(get_value_by_index((record, 3)))
if get_value_by_index((record, 3)) is not None else None,
get_value_by_index((record, 4)),
get_value_by_index((record, 5)).strftime("%Y-%m-%d")
if get_value_by_index((record, 5)) is not None else None,
get_value_by_index((record, 6)).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
if get_value_by_index((record, 6)) is not None else None,
'{} UTC'.format(get_value_by_index((record, 7)).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
if get_value_by_index((record, 7)) is not None else None,
get_value_by_index((record, 8)).strftime('%H:%M:%S.%f')[:-3]
if get_value_by_index((record, 8)) is not None else None,
get_value_by_index((record, 9))
if get_value_by_index((record, 9)) is not None else None)
for record in snapshot[google_bigquery].output]
assert rows_from_snapshot == ROWS_TO_INSERT
errors = bigquery_client.insert_rows(table, ROWS_TO_INSERT_2)
assert not errors
snapshot_2 = sdc_executor.capture_snapshot(pipeline, start_pipeline=True, batches=2).snapshot
if sdc_executor.get_pipeline_status(pipeline) == 'RUNNING':
sdc_executor.stop_pipeline(pipeline)
get_value_by_index = lambda x: list(x[0].field.values())[x[1]].value
rows_from_snapshot = [(int(get_value_by_index((record, 0)))
if get_value_by_index((record, 0)) is not None else None,
get_value_by_index((record, 1)),
float(get_value_by_index((record, 2)))
if get_value_by_index((record, 2)) is not None else None,
str(get_value_by_index((record, 3)))
if get_value_by_index((record, 3)) is not None else None,
get_value_by_index((record, 4)),
get_value_by_index((record, 5)).strftime("%Y-%m-%d")
if get_value_by_index((record, 5)) is not None else None,
get_value_by_index((record, 6)).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
if get_value_by_index((record, 6)) is not None else None,
'{} UTC'.format(get_value_by_index((record, 7)).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
if get_value_by_index((record, 7)) is not None else None,
get_value_by_index((record, 8)).strftime('%H:%M:%S.%f')[:-3]
if get_value_by_index((record, 8)) is not None else None,
get_value_by_index((record, 9))
if get_value_by_index((record, 9)) is not None else None)
for batch in snapshot_2.snapshot_batches
for record in batch.stage_outputs[google_bigquery.instance_name].output]
assert rows_from_snapshot == ROWS_TO_INSERT + ROWS_TO_INSERT_2
finally:
bigquery_client.delete_dataset(dataset_ref, delete_contents=True)
# SDC-10836. Google BigQuery is not respecting batchSize and at the same time is duplicating records
@gcp
@sdc_min_version('2.7.0.0')
def test_google_bigquery_origin_batch_handling(sdc_builder, sdc_executor, gcp):
"""Verify proper batch handling by the BigQuery origin.
In this test, we write 8 records to BigQuery with a batch size of 3, verifying that each batch is of
size 3 and that 8 total records are captured. The small numbers are used because of the limitations
described in SDC-8765.
"""
MAX_BATCH_SIZE = 3
TOTAL_RECORDS = 8
dataset_name = get_random_string(ascii_letters, 5)
table_name = get_random_string(ascii_letters, 5)
query_str = f'SELECT * FROM {dataset_name}.{table_name} ORDER BY number'
pipeline_builder = sdc_builder.get_pipeline_builder()
google_bigquery = pipeline_builder.add_stage('Google BigQuery', type='origin')
google_bigquery.set_attributes(query=query_str, max_batch_size_in_records=MAX_BATCH_SIZE)
trash = pipeline_builder.add_stage('Trash')
google_bigquery >> trash
pipeline = pipeline_builder.build().configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
bigquery_client = gcp.bigquery_client
schema = [SchemaField('number', 'STRING', mode='required'),
SchemaField('value', 'STRING', mode='required')]
data = [dict(number=str(i), value=get_random_string()) for i in range(TOTAL_RECORDS)]
dataset = Dataset(bigquery_client.dataset(dataset_name))
try:
# Using Google bigquery client, create dataset, table and data inside table.
logger.info('Creating dataset %s using Google bigquery client ...', dataset_name)
bigquery_client.create_dataset(dataset)
table = bigquery_client.create_table(Table(dataset.table(table_name), schema=schema))
errors = bigquery_client.insert_rows(table, data)
assert not errors
# Ceiling division is needed to capture all the complete batches along with the last partial one.
snapshot = sdc_executor.capture_snapshot(pipeline,
start_pipeline=True,
batches=math.ceil(TOTAL_RECORDS / MAX_BATCH_SIZE)).snapshot
# Assert that the batch size is being respected in each batch (including the last). In this case,
# we'd expect batch sizes of 3, 3, and 2.
for i, batch in enumerate(snapshot.snapshot_batches, start=1):
# for 8 records, we'd expect batch sizes of 3, 3, and 2.
assert (len(batch.stage_outputs[google_bigquery.instance_name].output) == MAX_BATCH_SIZE
if i * MAX_BATCH_SIZE <= TOTAL_RECORDS
else TOTAL_RECORDS % MAX_BATCH_SIZE)
all_records = [record.field
for batch in snapshot.snapshot_batches
for record in batch.stage_outputs[google_bigquery.instance_name].output]
assert all_records == data
finally:
bigquery_client.delete_dataset(dataset, delete_contents=True)
@gcp
@sdc_min_version('2.7.0.0')
def test_google_pubsub_subscriber(sdc_builder, sdc_executor, gcp):
"""Publish messages using Google pub/sub client and then check if Google pub/sub
subscriber receives them using snapshot.
The pipeline looks like:
google_pubsub_subscriber >> trash
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
subscription_id = get_random_string(ascii_letters, 5)
topic_name = get_random_string(ascii_letters, 5)
google_pubsub_subscriber = pipeline_builder.add_stage('Google Pub Sub Subscriber', type='origin')
google_pubsub_subscriber.set_attributes(batch_wait_time_in_ms=20000,
data_format='TEXT',
max_batch_size_in_records=10,
num_pipeline_runners=1,
subscriber_thread_pool_size=1,
subscription_id=subscription_id)
trash = pipeline_builder.add_stage('Trash')
google_pubsub_subscriber >> trash
pipeline = pipeline_builder.build(title='Google Pub Sub Subscriber Pipeline').configure_for_environment(gcp)
pubsub_publisher_client = gcp.pubsub_publisher_client
pubsub_subscriber_client = gcp.pubsub_subscriber_client
project_id = gcp.project_id
topic_path = pubsub_publisher_client.topic_path(project_id, topic_name)
subscription_path = pubsub_subscriber_client.subscription_path(project_id, subscription_id)
try:
# Using Google pub/sub client, create topic and subscription
logger.info('Creating topic %s using Google pub/sub client ...', topic_name)
topic = pubsub_publisher_client.create_topic(topic_path)
subscription = pubsub_subscriber_client.create_subscription(subscription_path, topic_path)
# Start pipeline and verify messages are received using snapshot.
logger.info('Starting pipeline and snapshot')
sdc_executor.add_pipeline(pipeline)
snapshot_pipeline_command = sdc_executor.capture_snapshot(pipeline, start_pipeline=True, wait=False)
logger.info('Publishing messages to topic %s using Google pub/sub client ...', topic_name)
encoded_msg_data = MSG_DATA.encode()
num = 10
for _ in range(num):
pubsub_publisher_client.publish(topic_path, encoded_msg_data)
logger.debug('Finish the snapshot and verify')
snapshot = snapshot_pipeline_command.wait_for_finished(timeout_sec=SNAPSHOT_TIMEOUT_SEC).snapshot
sdc_executor.stop_pipeline(pipeline)
rows_from_snapshot = [record.field['text'].value
for record in snapshot[google_pubsub_subscriber].output]
logger.debug(rows_from_snapshot)
assert rows_from_snapshot == [MSG_DATA] * num
finally:
pubsub_subscriber_client.delete_subscription(subscription_path)
pubsub_publisher_client.delete_topic(topic_path)
@gcp
@sdc_min_version('2.7.0.0')
def test_google_pubsub_publisher(sdc_builder, sdc_executor, gcp):
"""
Send simple text messages to Google pub/sub from Dev Raw Data Source and
confirm that Google pub/sub successfully reads them using Google pub/sub client from gcp.
The pipeline looks like:
dev_raw_data_source >> google_pubsub_publisher
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
dev_raw_data_source.data_format = 'TEXT'
dev_raw_data_source.raw_data = MSG_DATA
subscription_id = get_random_string(ascii_letters, 5)
topic_name = get_random_string(ascii_letters, 5)
google_pubsub_publisher = pipeline_builder.add_stage('Google Pub Sub Publisher', type='destination')
google_pubsub_publisher.set_attributes(topic_id=topic_name, data_format='TEXT')
dev_raw_data_source >> google_pubsub_publisher
pipeline = pipeline_builder.build(title='Google Pub Sub Publisher Pipeline').configure_for_environment(gcp)
pipeline.rate_limit = 1
pubsub_publisher_client = gcp.pubsub_publisher_client
pubsub_subscriber_client = gcp.pubsub_subscriber_client
project_id = gcp.project_id
topic_path = pubsub_publisher_client.topic_path(project_id, topic_name)
subscription_path = pubsub_subscriber_client.subscription_path(project_id, subscription_id)
try:
# Using Google pub/sub client, create topic and subscription
logger.info('Creating topic %s using Google pub/sub client ...', topic_name)
topic = pubsub_publisher_client.create_topic(topic_path)
subscription = pubsub_subscriber_client.create_subscription(subscription_path, topic_path)
# Send messages using pipeline to Google pub/sub publisher Destination.
logger.info('Starting Publisher pipeline and waiting for it to produce records ...')
sdc_executor.add_pipeline(pipeline)
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_batch_count(10)
logger.info('Stopping Publisher pipeline and getting the count of records produced in total ...')
sdc_executor.stop_pipeline(pipeline)
history = sdc_executor.get_pipeline_history(pipeline)
msgs_sent_count = history.latest.metrics.counter('pipeline.batchOutputRecords.counter').count
logger.info('No. of messages sent in the pipeline = %s ...', msgs_sent_count)
msgs_to_be_received = msgs_sent_count
results = []
def callback(message):
nonlocal msgs_to_be_received
msgs_to_be_received = msgs_to_be_received - 1
results.append(message)
message.ack()
# Open the subscription, passing the callback.
future = pubsub_subscriber_client.subscribe(subscription_path, callback)
timeout = 5 # in seconds
start_time = time.time()
while time.time() < start_time + timeout and msgs_to_be_received > 0:
sleep(0.5)
logger.info('To be received messages %d...', msgs_to_be_received)
future.cancel() # cancel the feature there by stopping subscribers
# Verify
msgs_received = [message.data.decode().rstrip('\n') for message in results]
assert msgs_received == [dev_raw_data_source.raw_data] * msgs_sent_count
finally:
pubsub_subscriber_client.delete_subscription(subscription_path)
pubsub_publisher_client.delete_topic(topic_path)
@gcp
@sdc_min_version('2.7.0.0')
def test_google_bigtable_destination(sdc_builder, sdc_executor, gcp):
"""
Send text to Google bigtable from Dev Raw Data Source and
confirm that Google bigtable successfully reads them using happybase connection from gcp.
The pipeline looks like:
dev_raw_data_source >> google_bigtable
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
# Data with 3 distinct TransactionIDs
data = ['TransactionID,Type,UserID', '0003420301,01,1001', '0003420302,02,1002', '0003420303,03,1003',
'0003420301,04,1004', '0003420302,05,1005', '0003420303,06,1006']
dev_raw_data_source.set_attributes(data_format='DELIMITED',
header_line='WITH_HEADER',
raw_data='\n'.join(data))
table_name = get_random_string(ascii_letters, 5)
google_bigtable = pipeline_builder.add_stage('Google Bigtable', type='destination')
# Field paths, name of columns, storage types
fields_list = [{'source': '/TransactionID', 'storageType': 'TEXT', 'column': 'TransactionID'},
{'source': '/Type', 'storageType': 'TEXT', 'column': 'Type'},
{'source': '/UserID', 'storageType': 'TEXT', 'column': 'UserID'}]
google_bigtable.set_attributes(create_table_and_column_families=True,
default_column_family_name=DEFAULT_COLUMN_FAMILY_NAME,
explicit_column_family_mapping=False,
fields=fields_list,
row_key='/TransactionID',
table_name=table_name)
dev_raw_data_source >> google_bigtable
pipeline = pipeline_builder.build(title='Google Bigtable').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
pipeline.rate_limit = 1
instance = gcp.bigtable_instance
table = instance.table(table_name)
try:
# Produce Google Bigtable records using pipeline.
logger.info('Starting Big table pipeline and waiting for it to produce records ...')
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_batch_count(1)
logger.info('Stopping Big table pipeline and getting the count of records produced in total ...')
sdc_executor.stop_pipeline(pipeline)
logger.info('Reading contents from table %s ...', table_name)
partial_rows = table.read_rows()
partial_rows.consume_all()
read_data = [(f'{row.cells["cf"]["TransactionID".encode()][0].value.decode()},'
f'{row.cells["cf"]["Type".encode()][0].value.decode()},'
f'{row.cells["cf"]["UserID".encode()][0].value.decode()}')
for row_key, row in partial_rows.rows.items()]
logger.debug('read_data = {}'.format(read_data))
# Verify: Note we expect only 3 rows since there are only 3 distinct TransactionIDs in data.
# The result expected is the latest inserted data which are the last 3 rows.
# Reason is in Google Bigtable, each row is indexed by a single row key resulting in
# each row/column intersection can contain multiple cells at different timestamps,
# providing a record of how the stored data has been altered over time.
assert data[4:] == read_data
finally:
table.delete()
@gcp
@sdc_min_version('2.7.2.0')
def test_google_bigtable_destination_multiple_types(sdc_builder, sdc_executor, gcp):
"""Simple big table destination test with INSERT operation.
The pipeline inserts 1000 records of multiple types.
The pipeline should look like:
dev_data_generator >> record_deduplicator >> google_bigquery
record_deduplicator >> trash
record_deduplicator is added to avoid duplications
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_data_generator = pipeline_builder.add_stage('Dev Data Generator')
dev_data_generator.fields_to_generate = [
{'field': 'field1', 'type': 'STRING'},
{'field': 'field2', 'type': 'INTEGER'}
]
batch_size = 10000
dev_data_generator.set_attributes(delay_between_batches=0, batch_size=batch_size)
dataset_name = get_random_string(ascii_letters, 5)
table_name = get_random_string(ascii_letters, 5)
google_bigtable = pipeline_builder.add_stage('Google Bigtable', type='destination')
# Field paths, name of columns, storage types
fields_list = [{'source': '/field1', 'storageType': 'TEXT', 'column': 'field1'},
{'source': '/field2', 'storageType': 'BINARY', 'column': 'field2'}
]
google_bigtable.set_attributes(create_table_and_column_families=True,
default_column_family_name=DEFAULT_COLUMN_FAMILY_NAME,
explicit_column_family_mapping=False,
fields=fields_list,
row_key='/field1',
table_name=table_name)
record_deduplicator = pipeline_builder.add_stage('Record Deduplicator')
record_deduplicator.set_attributes(compare='SPECIFIED_FIELDS',
fields_to_compare = ['/field1'])
trash = pipeline_builder.add_stage('Trash')
dev_data_generator >> record_deduplicator >> google_bigtable
record_deduplicator >> trash
pipeline = pipeline_builder.build(title='Google Bigtable Mult Types').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
pipeline.rate_limit = 1
instance = gcp.bigtable_instance
table = instance.table(table_name)
try:
# Produce Google Bigtable records using pipeline.
logger.info('Starting Big table pipeline and waiting for it to produce records ...')
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_output_records_count(batch_size, timeout_sec=3600)
snapshot = sdc_executor.capture_snapshot(pipeline).snapshot
logger.info('Stopping Big tabñe Destination pipeline and getting the count of records produced in total ...')
sdc_executor.stop_pipeline(pipeline)
logger.info('Reading contents from table %s ...', table_name)
partial_rows = table.read_rows()
partial_rows.consume_all()
read_data = [row for row in partial_rows.rows.items()]
# Verify quantity of records greater than batch_size
assert len(read_data) > batch_size
# Verify no errors were generated
stage = snapshot[google_bigtable.instance_name]
assert len(stage.error_records) == 0
finally:
table.delete()
@gcp
@sdc_min_version('3.0.0.0')
def test_google_storage_origin(sdc_builder, sdc_executor, gcp):
"""
Write data to Google cloud storage using Storage Client
and then check if Google Storage Origin receives them using snapshot.
The pipeline looks like:
google_cloud_storage_origin >> trash
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
bucket_name = get_random_string(ascii_lowercase, 10)
storage_client = gcp.storage_client
google_cloud_storage = pipeline_builder.add_stage('Google Cloud Storage', type='origin')
google_cloud_storage.set_attributes(bucket=bucket_name,
common_prefix='gcs-test',
prefix_pattern='**/*.txt',
data_format='TEXT')
trash = pipeline_builder.add_stage('Trash')
google_cloud_storage >> trash
pipeline = pipeline_builder.build(title='Google Cloud Storage').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
created_bucket = storage_client.create_bucket(bucket_name)
try:
data = [get_random_string(ascii_letters, length=100) for _ in range(10)]
blob = created_bucket.blob('gcs-test/a/b/c/d/e/sdc-test.txt')
blob.upload_from_string('\n'.join(data))
logger.info('Starting GCS Origin pipeline and waiting for it to produce a snapshot ...')
snapshot = sdc_executor.capture_snapshot(pipeline, start_pipeline=True).snapshot
sdc_executor.stop_pipeline(pipeline)
rows_from_snapshot = [record.field['text']
for record in snapshot[google_cloud_storage].output]
logger.debug(rows_from_snapshot)
assert rows_from_snapshot == data
finally:
created_bucket.delete(force=True)
@gcp
@sdc_min_version('3.0.0.0')
def test_google_storage_destination(sdc_builder, sdc_executor, gcp):
"""
Send data to Google cloud storage from Dev Raw Data Source and
confirm that Storage client successfully reads them.
The pipeline looks like:
dev_raw_data_source >> google_cloud_storage
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
bucket_name = get_random_string(ascii_lowercase, 10)
storage_client = gcp.storage_client
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
data = [get_random_string(ascii_letters, length=100) for _ in range(10)]
dev_raw_data_source.set_attributes(data_format='TEXT',
stop_after_first_batch=True,
raw_data='\n'.join(data))
google_cloud_storage = pipeline_builder.add_stage('Google Cloud Storage', type='destination')
google_cloud_storage.set_attributes(bucket=bucket_name,
common_prefix='gcs-test',
partition_prefix='${YYYY()}/${MM()}/${DD()}/${hh()}/${mm()}',
data_format='TEXT')
dev_raw_data_source >> google_cloud_storage
pipeline = pipeline_builder.build(title='Google Cloud Storage').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
created_bucket = storage_client.create_bucket(bucket_name)
try:
logger.info('Starting GCS Destination pipeline and waiting for it to produce records'
' and transition to finished...')
sdc_executor.start_pipeline(pipeline).wait_for_finished()
blob_iter = created_bucket.list_blobs(max_results=1, prefix='gcs-test')
blobs = [blob for blob in blob_iter]
assert len(blobs) == 1
blob = blobs[0]
# Decode the byte array returned by storage client
contents = blob.download_as_string().decode('ascii')
# Strip out the lines which are empty (essentially the last line)
lines = [line for line in contents.split('\n') if len(line) > 0]
assert lines == data
finally:
created_bucket.delete(force=True)
@gcp
@sdc_min_version('3.0.0.0')
def test_google_storage_destination_error(sdc_builder, sdc_executor, gcp):
"""
Send data to Google cloud storage from Dev Raw Data Source
bucket is not created and
confirm that ten error records are generated.
The pipeline looks like:
dev_raw_data_source >> google_cloud_storage
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
data = [get_random_string(ascii_letters, length=100) for _ in range(10)]
dev_raw_data_source.set_attributes(data_format='TEXT',
stop_after_first_batch=True,
raw_data='\n'.join(data))
google_cloud_storage = pipeline_builder.add_stage('Google Cloud Storage', type='destination')
google_cloud_storage.set_attributes(bucket='X',
common_prefix='gcs-test',
partition_prefix='${YYYY()}/${MM()}/${DD()}/${hh()}/${mm()}',
data_format='TEXT',
stage_on_record_error='TO_ERROR')
dev_raw_data_source >> google_cloud_storage
pipeline = pipeline_builder.build(title='Google Cloud Storage').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
logger.info('Starting GCS Destination pipeline and waiting for it to produce records'
' and transition to finished...')
snapshot = sdc_executor.capture_snapshot(pipeline, start_pipeline=True).snapshot
sdc_executor.get_pipeline_status(pipeline).wait_for_status('FINISHED')
stage = snapshot[google_cloud_storage.instance_name]
assert len(stage.error_records) == 10
for _ in range(0, 10):
assert 'CONTAINER_0001' == stage.error_records[_].header['errorCode']
@gcp
@sdc_min_version('3.0.0.0')
def test_google_storage_destination_error_output_google_sub_pub(sdc_builder, sdc_executor, gcp):
"""
Send data to Google cloud storage from Dev Raw Data Source
bucket is not created and
confirm that ten error records are generated.
Send the errors to google PUB SUB.
Retrieve the messages and check the code error.
The pipeline looks like:
dev_raw_data_source >> google_cloud_storage
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
subscription_id = get_random_string(ascii_letters, 5)
topic_name = get_random_string(ascii_letters, 5)
pubsub_subscriber_client = gcp.pubsub_subscriber_client
pubsub_publisher_client = gcp.pubsub_publisher_client
project_id = gcp.project_id
topic_path = pubsub_publisher_client.topic_path(project_id, topic_name)
subscription_path = pubsub_subscriber_client.subscription_path(project_id, subscription_id)
# Using Google pub/sub client, create topic and subscription
logger.info('Creating topic %s using Google pub/sub client ...', topic_name)
topic = pubsub_publisher_client.create_topic(topic_path)
subscription = pubsub_subscriber_client.create_subscription(subscription_path, topic_path)
# Pipeline error configured to google pub sub topic and project
write_to_google_pub_sub = pipeline_builder.add_error_stage('Write to Google Pub Sub')
write_to_google_pub_sub.set_attributes(topic_id=topic_name,
project_id=project_id)
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
data = [get_random_string(ascii_letters, length=100) for _ in range(10)]
dev_raw_data_source.set_attributes(data_format='TEXT',
stop_after_first_batch=True,
raw_data='\n'.join(data))
google_cloud_storage = pipeline_builder.add_stage('Google Cloud Storage', type='destination')
bucket_name = get_random_string(ascii_letters, 5)
# Bucket name does not exists.
google_cloud_storage.set_attributes(bucket=bucket_name,
common_prefix='gcs-test',
partition_prefix='${YYYY()}/${MM()}/${DD()}/${hh()}/${mm()}',
data_format='TEXT',
stage_on_record_error='TO_ERROR')
dev_raw_data_source >> google_cloud_storage
pipeline = pipeline_builder.build(title='Google Cloud Storage').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
logger.info('Starting GCS Destination pipeline and waiting for it to produce records'
' and transition to finished...')
snapshot = sdc_executor.capture_snapshot(pipeline, start_pipeline=True).snapshot
sdc_executor.get_pipeline_status(pipeline).wait_for_status('FINISHED')
stage = snapshot[google_cloud_storage.instance_name]
assert len(stage.error_records) == 10
for _ in range(0, 10):
assert 'CONTAINER_0001' == stage.error_records[_].header['errorCode']
msgs_to_be_received = 10
results = []
def callback(message):
nonlocal msgs_to_be_received
msgs_to_be_received = msgs_to_be_received - 1
results.append(message)
message.ack()
# Open the subscription, passing the callback.
future = pubsub_subscriber_client.subscribe(subscription_path, callback)
timeout = 5 # in seconds
start_time = time.time()
while time.time() < start_time + timeout and msgs_to_be_received > 0:
sleep(0.5)
logger.info('To be received messages %d...', msgs_to_be_received)
future.cancel() # cancel the feature there by stopping subscribers
# Verify
msgs_received = [json.loads(message.data.decode(encoding='UTF-8', errors='ignore'))['header']['errorCode'] for
message in results]
assert msgs_received == ['CONTAINER_0001'] * 10
pubsub_subscriber_client.delete_subscription(subscription_path)
pubsub_publisher_client.delete_topic(topic_path)
@gcp
@sdc_min_version('3.0.0.0')
def test_google_storage_origin_stop_resume(sdc_builder, sdc_executor, gcp):
"""
Write data to Google cloud storage using Storage Client
and then check if Google Storage Origin receives them using snapshot.
Stop the pipeline, add more data, resume the pipline and check the new data.
The pipeline looks like:
google_cloud_storage_origin >> trash
"""
pipeline_builder = sdc_builder.get_pipeline_builder()
bucket_name = get_random_string(ascii_lowercase, 10)
storage_client = gcp.storage_client
google_cloud_storage = pipeline_builder.add_stage('Google Cloud Storage', type='origin')
google_cloud_storage.set_attributes(bucket=bucket_name,
common_prefix='gcs-test',
prefix_pattern='**/*.txt',
data_format='TEXT')
trash = pipeline_builder.add_stage('Trash')
google_cloud_storage >> trash
pipeline = pipeline_builder.build(title='Google Cloud Storage').configure_for_environment(gcp)
sdc_executor.add_pipeline(pipeline)
created_bucket = storage_client.create_bucket(bucket_name)
try:
data = [get_random_string(ascii_letters, length=100) for _ in range(10)]
blob = created_bucket.blob('gcs-test/a/b/c/d/e/sdc-test-1.txt')
blob.upload_from_string('\n'.join(data))
logger.info('Starting GCS Origin pipeline and waiting for it to produce a snapshot ...')
snapshot = sdc_executor.capture_snapshot(pipeline, start_pipeline=True).snapshot
sdc_executor.stop_pipeline(pipeline)
rows_from_snapshot = [record.field['text']
for record in snapshot[google_cloud_storage].output]
logger.debug(rows_from_snapshot)
assert rows_from_snapshot == data
data = [get_random_string(ascii_letters, length=100) for _ in range(10)]
blob = created_bucket.blob('gcs-test/a/b/c/d/e/sdc-test-1.txt')
blob.upload_from_string('\n'.join(data))
logger.info('Starting Second Time GCS Origin pipeline and waiting for it to produce a snapshot ...')
snapshot = sdc_executor.capture_snapshot(pipeline, start_pipeline=True).snapshot
sdc_executor.stop_pipeline(pipeline)
rows_from_snapshot = [record.field['text']
for record in snapshot[google_cloud_storage].output]
logger.debug(rows_from_snapshot)
assert rows_from_snapshot == data
finally:
created_bucket.delete(force=True)
| 47.218531 | 120 | 0.656485 | 6,720 | 54,018 | 5.020833 | 0.085714 | 0.036011 | 0.016894 | 0.025341 | 0.799585 | 0.779105 | 0.764938 | 0.739301 | 0.721014 | 0.692916 | 0 | 0.054396 | 0.244474 | 54,018 | 1,143 | 121 | 47.259843 | 0.772322 | 0.126995 | 0 | 0.703356 | 0 | 0.002685 | 0.173744 | 0.026397 | 0 | 0 | 0 | 0 | 0.038926 | 1 | 0.022819 | false | 0 | 0.016107 | 0 | 0.038926 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
ba87876163435c85897e9d07e7e9b23378b2f5a4 | 21 | py | Python | dis_snek/api/__init__.py | Astrea49/dis_snek | c899a6f1caa3c2a45323dbe50ed8ed62676be9d6 | [
"MIT"
] | 64 | 2021-10-12T15:31:36.000Z | 2022-03-29T18:25:47.000Z | dis_snek/api/__init__.py | Astrea49/dis_snek | c899a6f1caa3c2a45323dbe50ed8ed62676be9d6 | [
"MIT"
] | 166 | 2021-10-10T16:27:52.000Z | 2022-03-30T09:04:54.000Z | dis_snek/api/__init__.py | Astrea49/dis_snek | c899a6f1caa3c2a45323dbe50ed8ed62676be9d6 | [
"MIT"
] | 34 | 2021-10-10T13:26:41.000Z | 2022-03-23T13:59:35.000Z | from . import events
| 10.5 | 20 | 0.761905 | 3 | 21 | 5.333333 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.190476 | 21 | 1 | 21 | 21 | 0.941176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
24549b3d3ffc311983a1822b07809161570fbc24 | 70 | py | Python | starter_code/api_keys.py | ArazOha/Python-API_Challenge | 9ffbfefad0dbd7f33fb6e5e40ce73cccb90d4812 | [
"ADSL"
] | null | null | null | starter_code/api_keys.py | ArazOha/Python-API_Challenge | 9ffbfefad0dbd7f33fb6e5e40ce73cccb90d4812 | [
"ADSL"
] | null | null | null | starter_code/api_keys.py | ArazOha/Python-API_Challenge | 9ffbfefad0dbd7f33fb6e5e40ce73cccb90d4812 | [
"ADSL"
] | null | null | null | # OpenWeatherMap API Key
api_key = "190be5452c571dbedf41d9fed281cedd"
| 23.333333 | 44 | 0.842857 | 6 | 70 | 9.666667 | 0.666667 | 0.206897 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.253968 | 0.1 | 70 | 2 | 45 | 35 | 0.666667 | 0.314286 | 0 | 0 | 0 | 0 | 0.695652 | 0.695652 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
79ec0c9d8de75acf36b2582edf48ad2295fe174e | 42 | py | Python | TransE/config/__init__.py | sorokine/NeuralTripleTranslation | 9a58a8981ac6ca196668a88e46515951f1a7e5de | [
"Apache-2.0"
] | 47 | 2018-07-06T01:00:37.000Z | 2021-12-05T08:05:35.000Z | TransE/config/__init__.py | sorokine/NeuralTripleTranslation | 9a58a8981ac6ca196668a88e46515951f1a7e5de | [
"Apache-2.0"
] | 6 | 2018-10-29T09:35:58.000Z | 2022-01-02T14:06:59.000Z | TransE/config/__init__.py | sorokine/NeuralTripleTranslation | 9a58a8981ac6ca196668a88e46515951f1a7e5de | [
"Apache-2.0"
] | 14 | 2018-07-08T06:13:08.000Z | 2021-06-18T06:21:56.000Z | from . import Config
from Config import *
| 14 | 20 | 0.761905 | 6 | 42 | 5.333333 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.190476 | 42 | 2 | 21 | 21 | 0.941176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
79f611629f79b04e2e3d542927541938931bc174 | 17,373 | py | Python | data/data_loader_dad.py | AdamLohSg/GTA | bf6a745a6e28e365466e76360a15ca10ce61e009 | [
"Apache-2.0"
] | null | null | null | data/data_loader_dad.py | AdamLohSg/GTA | bf6a745a6e28e365466e76360a15ca10ce61e009 | [
"Apache-2.0"
] | null | null | null | data/data_loader_dad.py | AdamLohSg/GTA | bf6a745a6e28e365466e76360a15ca10ce61e009 | [
"Apache-2.0"
] | null | null | null | import os
import pickle
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from utils.timefeatures import time_features
import warnings
warnings.filterwarnings('ignore')
class Dataset_ETT_hour(Dataset):
def __init__(self, root_path, flag='train', size=None,
features='S', data_path='ETTh1.csv',
target='OT', scale=True, inverse=False, timeenc=0, freq='h', cols=None):
# size [seq_len, label_len, pred_len]
# info
if size == None:
self.seq_len = 24*4*4
self.label_len = 24*4
self.pred_len = 24*4
else:
self.seq_len = size[0]
self.label_len = size[1]
self.pred_len = size[2]
# init
assert flag in ['train', 'test', 'val']
type_map = {'train':0, 'val':1, 'test':2}
self.set_type = type_map[flag]
self.features = features
self.target = target
self.scale = scale
self.inverse = inverse
self.timeenc = timeenc
self.freq = freq
self.root_path = root_path
self.data_path = data_path
self.__read_data__()
def __read_data__(self):
self.scaler = StandardScaler()
df_raw = pd.read_csv(os.path.join(self.root_path,
self.data_path))
border1s = [0, 12*30*24 - self.seq_len, 12*30*24+4*30*24 - self.seq_len]
border2s = [12*30*24, 12*30*24+4*30*24, 12*30*24+8*30*24]
border1 = border1s[self.set_type]
border2 = border2s[self.set_type]
if self.features=='M' or self.features=='MS':
cols_data = df_raw.columns[1:]
df_data = df_raw[cols_data]
elif self.features=='S':
df_data = df_raw[[self.target]]
if self.scale:
train_data = df_data[border1s[0]:border2s[0]]
self.scaler.fit(train_data.values)
data = self.scaler.transform(df_data.values)
else:
data = df_data.values
df_stamp = df_raw[['date']][border1:border2]
df_stamp['date'] = pd.to_datetime(df_stamp.date)
data_stamp = time_features(df_stamp, timeenc=self.timeenc, freq=self.freq)
self.data_x = data[border1:border2]
if self.inverse:
self.data_y = df_data.values[border1:border2]
else:
self.data_y = data[border1:border2]
self.data_stamp = data_stamp
def __getitem__(self, index):
s_begin = index
s_end = s_begin + self.seq_len
r_begin = s_end - self.label_len
r_end = r_begin + self.label_len + self.pred_len
seq_x = self.data_x[s_begin:s_end]
if self.inverse:
seq_y = np.concatenate([self.data_x[r_begin:r_begin+self.label_len], self.data_y[r_begin+self.label_len:r_end]], 0)
else:
seq_y = self.data_y[r_begin:r_end]
seq_x_mark = self.data_stamp[s_begin:s_end]
seq_y_mark = self.data_stamp[r_begin:r_end]
return seq_x, seq_y, seq_x_mark, seq_y_mark
def __len__(self):
return len(self.data_x) - self.seq_len- self.pred_len + 1
def inverse_transform(self, data):
return self.scaler.inverse_transform(data)
class NASA_Anomaly(Dataset):
def __init__(self, root_path, flag='train', size=None,
features='M', data_path='SMAP',
target=0, scale=True):
# size [seq_len, label_len pred_len]
# info
if size == None:
self.seq_len = 8*60
self.label_len = 2*60
self.pred_len = 2*60
else:
self.seq_len = size[0]
self.label_len = size[1]
self.pred_len = size[2]
# init
assert flag in ['train', 'test', 'val']
type_map = {'train':0, 'val':1, 'test':2}
self.set_type = type_map[flag]
self.flag = flag
self.features = features
self.target = target
self.scale = scale
self.root_path = root_path
self.data_path = data_path
self.__read_data__()
def get_data_dim(self, dataset):
if dataset == 'SMAP':
return 25
elif dataset == 'MSL':
return 55
elif str(dataset).startswith('machine'):
return 38
else:
raise ValueError('unknown dataset '+str(dataset))
def __read_data__(self):
"""
get data from pkl files
return shape: (([train_size, x_dim], [train_size] or None), ([test_size, x_dim], [test_size]))
"""
x_dim = self.get_data_dim(self.data_path)
if self.flag == 'train':
f = open(os.path.join(self.root_path, self.data_path, '{}_train.pkl'.format(self.data_path)), "rb")
data = pickle.load(f).reshape((-1, x_dim))
f.close()
elif self.flag in ['val', 'test']:
try:
f = open(os.path.join(self.root_path, self.data_path, '{}_test.pkl'.format(self.data_path)), "rb")
data = pickle.load(f).reshape((-1, x_dim))
f.close()
except (KeyError, FileNotFoundError):
data = None
try:
f = open(os.path.join(self.root_path, self.data_path, '{}_test_label.pkl'.format(self.data_path)), "rb")
label = pickle.load(f).reshape((-1))
f.close()
except (KeyError, FileNotFoundError):
label = None
assert len(data) == len(label), "length of test data shoube the same as label"
if self.scale:
data = self.preprocess(data)
df_stamp = pd.DataFrame(columns=['date'])
date = pd.date_range(start='1/1/2015', periods=len(data), freq='4s')
df_stamp['date'] = date
df_stamp['month'] = df_stamp.date.apply(lambda row:row.month,1)
df_stamp['day'] = df_stamp.date.apply(lambda row:row.day,1)
df_stamp['weekday'] = df_stamp.date.apply(lambda row:row.weekday(),1)
df_stamp['hour'] = df_stamp.date.apply(lambda row:row.hour,1)
df_stamp['minute'] = df_stamp.date.apply(lambda row:row.minute,1)
# df_stamp['minute'] = df_stamp.minute.map(lambda x:x//10)
df_stamp['second'] = df_stamp.date.apply(lambda row:row.second,1)
data_stamp = df_stamp.drop(['date'],1).values
if self.flag == 'train':
if self.features=='M':
self.data_x = data
self.data_y = data
elif self.features=='S':
df_data = data[:, [self.target]]
self.data_x = df_data
self.data_y = df_data
else:
border1s = [0, 0, 0]
border2s = [None, len(data)//4, len(data)]
border1 = border1s[self.set_type]
border2 = border2s[self.set_type]
if self.features=='M':
self.data_x = data[border1:border2]
self.data_y = data[border1:border2]
self.label = label[border1:border2]
elif self.features=='S':
df_data = data[:, [self.target]]
self.data_x = df_data[border1:border2]
self.data_y = df_data[border1:border2]
self.label = label[border1:border2]
self.data_stamp = data_stamp
def preprocess(self, df):
"""returns normalized and standardized data.
"""
df = np.asarray(df, dtype=np.float32)
if len(df.shape) == 1:
raise ValueError('Data must be a 2-D array')
if np.any(sum(np.isnan(df)) != 0):
print('Data contains null values. Will be replaced with 0')
df = np.nan_to_num()
# normalize data
df = MinMaxScaler().fit_transform(df)
print('Data normalized')
return df
def __getitem__(self, index):
s_begin = index
s_end = s_begin + self.seq_len
r_begin = s_end - self.label_len
r_end = s_end + self.pred_len
seq_x = self.data_x[s_begin:s_end]
seq_y = self.data_y[r_begin:r_end]
seq_x_mark = self.data_stamp[s_begin:s_end]
seq_y_mark = self.data_stamp[r_begin:r_end]
if self.flag == 'train':
return seq_x, seq_y, seq_x_mark, seq_y_mark
else:
seq_label = self.label[s_end:r_end]
return seq_x, seq_y, seq_x_mark, seq_y_mark, seq_label
def __len__(self):
return len(self.data_x) - self.seq_len - self.pred_len + 1
class WADI(Dataset):
def __init__(self, root_path, flag='train', size=None,
features='M', data_path='WADI_14days_downsampled.csv',
target='1_AIT_001_PV', scale=True):
# size [seq_len, label_len pred_len]
# info
if size == None:
self.seq_len = 8*60
self.label_len = 2*60
self.pred_len = 2*60
else:
self.seq_len = size[0]
self.label_len = size[1]
self.pred_len = size[2]
# init
assert flag in ['train', 'test', 'val']
self.flag = flag
type_map = {'train':0, 'val':1, 'test':2}
self.set_type = type_map[flag]
self.features = features
self.target = target
self.scale = scale
self.root_path = root_path
self.data_path = data_path
self.__read_data__()
def __read_data__(self):
scaler = MinMaxScaler()
if self.flag == 'train':
df_raw = pd.read_csv(os.path.join(self.root_path,
'WADI_14days_downsampled.csv'))
if self.features=='M':
cols_data = df_raw.columns[1:]
df_data = df_raw[cols_data]
elif self.features=='S':
df_data = df_raw[[self.target]]
df_stamp = df_raw[['date']]
if self.scale:
data = scaler.fit_transform(df_data.values)
else:
data = df_data.values
self.data_x = data
self.data_y = data
else:
df_raw = pd.read_csv(os.path.join(self.root_path,
'WADI_attackdata_downsampled.csv'))
border1s = [0, 0, 0]
border2s = [None, len(df_raw)//4, len(df_raw)]
border1 = border1s[self.set_type]
border2 = border2s[self.set_type]
df_stamp = df_raw[['date']][border1:border2]
if self.features=='M':
cols_data = df_raw.columns[1:-1]
df_data = df_raw[cols_data]
label = df_raw['label'].values
elif self.features=='S':
df_data = df_raw[[self.target]]
label = df_raw['label'].values
if self.scale:
data = scaler.fit_transform(df_data.values)
else:
data = df_data.values
self.data_x = data[border1:border2]
self.data_y = data[border1:border2]
self.label = label[border1:border2]
df_stamp['date'] = pd.to_datetime(df_stamp.date)
df_stamp['month'] = df_stamp.date.apply(lambda row:row.month,1)
df_stamp['day'] = df_stamp.date.apply(lambda row:row.day,1)
df_stamp['weekday'] = df_stamp.date.apply(lambda row:row.weekday(),1)
df_stamp['hour'] = df_stamp.date.apply(lambda row:row.hour,1)
df_stamp['minute'] = df_stamp.date.apply(lambda row:row.minute,1)
# df_stamp['minute'] = df_stamp.minute.map(lambda x:x//10)
df_stamp['second'] = df_stamp.date.apply(lambda row:row.second,1)
df_stamp['second'] = df_stamp.second.map(lambda x:x//10)
data_stamp = df_stamp.drop(['date'],1).values
self.data_stamp = data_stamp
def __getitem__(self, index):
s_begin = index
s_end = s_begin + self.seq_len
r_begin = s_end - self.label_len
r_end = s_end + self.pred_len
seq_x = self.data_x[s_begin:s_end]
seq_y = self.data_y[r_begin:r_end]
seq_x_mark = self.data_stamp[s_begin:s_end]
seq_y_mark = self.data_stamp[r_begin:r_end]
if self.flag == 'train':
return seq_x, seq_y, seq_x_mark, seq_y_mark
else:
seq_label = self.label[s_end:r_end]
return seq_x, seq_y, seq_x_mark, seq_y_mark, seq_label
def __len__(self):
return len(self.data_x) - self.seq_len - self.pred_len + 1
class SWaT(Dataset):
def __init__(self, root_path, flag='train', size=None,
features='M', data_path='SWaT_normaldata_downsampled.csv',
target='FIT_101', scale=True):
# size [seq_len, label_len pred_len]
# info
if size == None:
self.seq_len = 8*60
self.label_len = 2*60
self.pred_len = 2*60
else:
self.seq_len = size[0]
self.label_len = size[1]
self.pred_len = size[2]
# init
assert flag in ['train', 'test', 'val']
self.flag = flag
type_map = {'train':0, 'val':1, 'test':2}
self.set_type = type_map[flag]
self.features = features
self.target = target
self.scale = scale
self.root_path = root_path
self.data_path = data_path
self.__read_data__()
def __read_data__(self):
scaler = MinMaxScaler()
if self.flag == 'train':
df_raw = pd.read_csv(os.path.join(self.root_path,
'SWaT_normaldata_downsampled.csv'))
if self.features=='M':
cols_data = df_raw.columns[1:]
df_data = df_raw[cols_data]
elif self.features=='S':
df_data = df_raw[[self.target]]
df_stamp = df_raw[[' Timestamp']]
if self.scale:
data = scaler.fit_transform(df_data.values)
else:
data = df_data.values
self.data_x = data
self.data_y = data
else:
df_raw = pd.read_csv(os.path.join(self.root_path,
'SWaT_attackdata_downsampled.csv'))
border1s = [0, 0, 0]
border2s = [None, len(df_raw)//4, len(df_raw)]
border1 = border1s[self.set_type]
border2 = border2s[self.set_type]
df_stamp = df_raw[[' Timestamp']][border1:border2]
if self.features=='M':
cols_data = df_raw.columns[1:-1]
df_data = df_raw[cols_data]
label = df_raw['Normal/Attack'].values
elif self.features=='S':
df_data = df_raw[[self.target]]
label = df_raw['Normal/Attack'].values
if self.scale:
data = scaler.fit_transform(df_data.values)
else:
data = df_data.values
self.data_x = data[border1:border2]
self.data_y = data[border1:border2]
self.label = label[border1:border2]
df_stamp[' Timestamp'] = pd.to_datetime(df_stamp[' Timestamp'])
df_stamp['month'] = df_stamp[' Timestamp'].apply(lambda row:row.month,1)
df_stamp['day'] = df_stamp[' Timestamp'].apply(lambda row:row.day,1)
df_stamp['weekday'] = df_stamp[' Timestamp'].apply(lambda row:row.weekday(),1)
df_stamp['hour'] = df_stamp[' Timestamp'].apply(lambda row:row.hour,1)
df_stamp['minute'] = df_stamp[' Timestamp'].apply(lambda row:row.minute,1)
# df_stamp['minute'] = df_stamp.minute.map(lambda x:x//10)
df_stamp['second'] = df_stamp[' Timestamp'].apply(lambda row:row.second,1)
df_stamp['second'] = df_stamp.second.map(lambda x:x//10)
data_stamp = df_stamp.drop([' Timestamp'],1).values
self.data_stamp = data_stamp
def __getitem__(self, index):
s_begin = index
s_end = s_begin + self.seq_len
r_begin = s_end - self.label_len
r_end = s_end + self.pred_len
seq_x = self.data_x[s_begin:s_end]
seq_y = self.data_y[r_begin:r_end]
seq_x_mark = self.data_stamp[s_begin:s_end]
seq_y_mark = self.data_stamp[r_begin:r_end]
if self.flag == 'train':
return seq_x, seq_y, seq_x_mark, seq_y_mark
else:
seq_label = self.label[s_end:r_end]
return seq_x, seq_y, seq_x_mark, seq_y_mark, seq_label
def __len__(self):
return len(self.data_x) - self.seq_len - self.pred_len + 1
if __name__ == '__main__':
flag = 'test'
dataset = NASA_Anomaly(root_path='./data/', data_path='MSL', flag=flag, size=(60, 30, 1))
print(flag, len(dataset))
# data_loader = DataLoader(
# dataset,
# batch_size=32,
# shuffle=True,
# num_workers=2,
# drop_last=True)
# for (x, y, x_stamp, y_stamp, label) in data_loader:
# print(x.size(), y.size(), x_stamp.size(), y_stamp.size(), label.size())
# break | 36.19375 | 127 | 0.553042 | 2,338 | 17,373 | 3.845595 | 0.085971 | 0.049049 | 0.02002 | 0.034034 | 0.786342 | 0.751752 | 0.734067 | 0.720721 | 0.702814 | 0.696919 | 0 | 0.023069 | 0.326311 | 17,373 | 480 | 128 | 36.19375 | 0.74513 | 0.046682 | 0 | 0.737127 | 0 | 0 | 0.056054 | 0.010787 | 0 | 0 | 0 | 0 | 0.01355 | 1 | 0.051491 | false | 0 | 0.02439 | 0.01355 | 0.130081 | 0.00813 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
79fe4f082f325c68521a966c8a350bc04bf4e1e5 | 31 | py | Python | uwuizer/__init__.py | Philinphiladelphia/uwu | 531843b8663d3342ccaf0089bfe8734d95fdecb9 | [
"MIT"
] | null | null | null | uwuizer/__init__.py | Philinphiladelphia/uwu | 531843b8663d3342ccaf0089bfe8734d95fdecb9 | [
"MIT"
] | null | null | null | uwuizer/__init__.py | Philinphiladelphia/uwu | 531843b8663d3342ccaf0089bfe8734d95fdecb9 | [
"MIT"
] | null | null | null | from uwuizer.main import owoize | 31 | 31 | 0.870968 | 5 | 31 | 5.4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.096774 | 31 | 1 | 31 | 31 | 0.964286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
031430379692b96bcdeec4f4add4efc73c7e2bf7 | 42 | py | Python | boltzmann/training/__init__.py | maccallumlab/BoltzmannGenerator | f6aba2e3602891c2acae92a894716ab9da7fb654 | [
"MIT"
] | 9 | 2019-10-02T03:37:49.000Z | 2021-04-23T09:18:36.000Z | boltzmann/training/__init__.py | maccallumlab/BoltzmannGenerator | f6aba2e3602891c2acae92a894716ab9da7fb654 | [
"MIT"
] | null | null | null | boltzmann/training/__init__.py | maccallumlab/BoltzmannGenerator | f6aba2e3602891c2acae92a894716ab9da7fb654 | [
"MIT"
] | 4 | 2019-10-23T16:30:54.000Z | 2020-07-24T20:03:10.000Z | from .particlefilter import ParticleFilter | 42 | 42 | 0.904762 | 4 | 42 | 9.5 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.071429 | 42 | 1 | 42 | 42 | 0.974359 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
036a6a17f0787f59c458c6996bc9952cca02a1d4 | 79 | py | Python | solvers/common/less_than_op.py | andrinmeier/solvers | 01c5ba29d6c880a9c22cb897ad0e7e006ab1816b | [
"MIT"
] | null | null | null | solvers/common/less_than_op.py | andrinmeier/solvers | 01c5ba29d6c880a9c22cb897ad0e7e006ab1816b | [
"MIT"
] | 1 | 2022-03-31T14:10:33.000Z | 2022-03-31T20:11:51.000Z | solvers/common/less_than_op.py | andrinmeier/solvers | 01c5ba29d6c880a9c22cb897ad0e7e006ab1816b | [
"MIT"
] | null | null | null | class LessThanOp:
def eval(self, left, right):
return left < right
| 19.75 | 32 | 0.632911 | 10 | 79 | 5 | 0.8 | 0.36 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.278481 | 79 | 3 | 33 | 26.333333 | 0.877193 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0 | 0.333333 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 6 |
300ffc340a9c97848bc0a4be9147dbbc896c25e5 | 89 | py | Python | convnet3d/callbacks/__init__.py | yecharlie/convnet3d | 0b2771eec149b196ef59b58d09eef71c9b201d40 | [
"MIT"
] | 6 | 2020-03-12T10:28:41.000Z | 2021-11-18T16:17:20.000Z | convnet3d/callbacks/__init__.py | yecharlie/convnet3d | 0b2771eec149b196ef59b58d09eef71c9b201d40 | [
"MIT"
] | null | null | null | convnet3d/callbacks/__init__.py | yecharlie/convnet3d | 0b2771eec149b196ef59b58d09eef71c9b201d40 | [
"MIT"
] | 1 | 2019-08-01T02:50:05.000Z | 2019-08-01T02:50:05.000Z | from .common import RedirectModel # noqa: F401
from .eval import Evaluate # noqa: F401
| 29.666667 | 47 | 0.752809 | 12 | 89 | 5.583333 | 0.666667 | 0.238806 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.082192 | 0.179775 | 89 | 2 | 48 | 44.5 | 0.835616 | 0.235955 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
302d136695065c5b9afe54219caa8c711d4af846 | 36 | py | Python | Taekwon/Python/baseGrammar/codeup024.py | sonnysorry/codingtest | 478e0168e3209eb97b6b16910027bf12ccc3ccd0 | [
"MIT"
] | 2 | 2021-09-27T19:10:36.000Z | 2021-11-09T05:40:39.000Z | Taekwon/Python/baseGrammar/codeup024.py | sonnysorry/codingtest | 478e0168e3209eb97b6b16910027bf12ccc3ccd0 | [
"MIT"
] | 1 | 2021-11-15T14:56:54.000Z | 2021-11-15T14:56:54.000Z | Taekwon/Python/baseGrammar/codeup024.py | sonnysorry/codingtest | 478e0168e3209eb97b6b16910027bf12ccc3ccd0 | [
"MIT"
] | null | null | null | a, b = input().split()
print(a + b)
| 12 | 22 | 0.527778 | 7 | 36 | 2.714286 | 0.714286 | 0.210526 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.194444 | 36 | 2 | 23 | 18 | 0.655172 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 0.5 | 1 | 1 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 6 |
3044e88d8599bf8ef7c9cdfc731d3d1efab25e63 | 158 | py | Python | fasttext/__init__.py | Chenweihua405/fastText.py | 2e21e38ca1ebcbb658e884c68206ed6f2182a666 | [
"BSD-3-Clause"
] | 101 | 2016-08-08T07:18:57.000Z | 2021-11-02T05:55:15.000Z | fasttext/__init__.py | Chenweihua405/fastText.py | 2e21e38ca1ebcbb658e884c68206ed6f2182a666 | [
"BSD-3-Clause"
] | 1 | 2016-08-11T19:14:23.000Z | 2016-08-11T21:41:14.000Z | fasttext/__init__.py | Chenweihua405/fastText.py | 2e21e38ca1ebcbb658e884c68206ed6f2182a666 | [
"BSD-3-Clause"
] | 13 | 2016-08-10T21:55:28.000Z | 2021-11-09T10:37:54.000Z | from .fasttext import skipgram
from .fasttext import cbow
from .fasttext import load_model
from .fasttext import supervised
import os
__VERSION__ = '0.8.3'
| 17.555556 | 32 | 0.797468 | 23 | 158 | 5.26087 | 0.565217 | 0.396694 | 0.595041 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.022222 | 0.14557 | 158 | 8 | 33 | 19.75 | 0.874074 | 0 | 0 | 0 | 0 | 0 | 0.031646 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.833333 | 0 | 0.833333 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
06232d7881b6ee0569e27c4c274ee8bcfe5a6ffa | 39 | py | Python | visitor/tests/__init__.py | realmbit/django-visitor | c93fab7ff109eaa1b4d4de5371b02c549b5226fe | [
"BSD-3-Clause"
] | null | null | null | visitor/tests/__init__.py | realmbit/django-visitor | c93fab7ff109eaa1b4d4de5371b02c549b5226fe | [
"BSD-3-Clause"
] | null | null | null | visitor/tests/__init__.py | realmbit/django-visitor | c93fab7ff109eaa1b4d4de5371b02c549b5226fe | [
"BSD-3-Clause"
] | 1 | 2018-08-16T06:46:45.000Z | 2018-08-16T06:46:45.000Z | from visitor.tests.test_models import * | 39 | 39 | 0.846154 | 6 | 39 | 5.333333 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.076923 | 39 | 1 | 39 | 39 | 0.888889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
0626af8510b67b8c2c74799e778b33f02bd1c85d | 23 | py | Python | python/sketch/__init__.py | kodingkoning/sketch | 2126d5adf850e9a956e80aecf49071bcb9f050f9 | [
"MIT"
] | 1 | 2020-10-30T14:58:29.000Z | 2020-10-30T14:58:29.000Z | python/sketch/__init__.py | kodingkoning/sketch | 2126d5adf850e9a956e80aecf49071bcb9f050f9 | [
"MIT"
] | null | null | null | python/sketch/__init__.py | kodingkoning/sketch | 2126d5adf850e9a956e80aecf49071bcb9f050f9 | [
"MIT"
] | null | null | null | import hll
import bbmh
| 7.666667 | 11 | 0.826087 | 4 | 23 | 4.75 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.173913 | 23 | 2 | 12 | 11.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
06751051fa67a471016b96503025f50b84e9ec88 | 2,001 | py | Python | tests/test_unit_transport_database.py | IBM/python-itoolk | 36054a7ebdd8f5556c548d4c315e00e3c8d04904 | [
"MIT"
] | 11 | 2019-01-09T12:31:04.000Z | 2021-08-29T05:26:35.000Z | tests/test_unit_transport_database.py | IBM/python-itoolk | 36054a7ebdd8f5556c548d4c315e00e3c8d04904 | [
"MIT"
] | 50 | 2018-12-21T18:52:25.000Z | 2021-05-25T13:38:15.000Z | tests/test_unit_transport_database.py | IBM/python-itoolk | 36054a7ebdd8f5556c548d4c315e00e3c8d04904 | [
"MIT"
] | 9 | 2018-12-25T00:02:19.000Z | 2022-02-22T00:58:13.000Z | import pytest
from itoolkit import iToolKit, TransportClosedException
from itoolkit.transport import DatabaseTransport
def test_database_transport_callproc(database_callproc):
transport = DatabaseTransport(database_callproc)
tk = iToolKit()
out = transport.call(tk)
assert isinstance(out, (bytes, str))
cursor = database_callproc.cursor()
cursor.callproc.assert_called_once()
cursor.__iter__.assert_called_once()
def test_database_transport_execute(database_execute):
transport = DatabaseTransport(database_execute)
tk = iToolKit()
out = transport.call(tk)
assert isinstance(out, (bytes, str))
cursor = database_execute.cursor()
cursor.execute.assert_called_once()
cursor.__iter__.assert_called_once()
def test_database_transport_execute_schema(database_execute):
schema = 'MYSCHEMA'
transport = DatabaseTransport(database_execute, schema=schema)
tk = iToolKit()
out = transport.call(tk)
assert isinstance(out, (bytes, str))
cursor = database_execute.cursor()
cursor.execute.assert_called_once()
cursor.__iter__.assert_called_once()
assert len(cursor.execute.call_args[0]) > 0
assert schema in cursor.execute.call_args[0][0]
def test_database_transport_callproc_schema(database_execute):
schema = 'MYSCHEMA'
transport = DatabaseTransport(database_execute, schema=schema)
tk = iToolKit()
out = transport.call(tk)
assert isinstance(out, (bytes, str))
cursor = database_execute.cursor()
cursor.execute.assert_called_once()
cursor.__iter__.assert_called_once()
assert len(cursor.execute.call_args[0]) > 0
assert schema in cursor.execute.call_args[0][0]
def test_database_transport_call_raises_when_closed(database_execute):
schema = 'MYSCHEMA'
transport = DatabaseTransport(database_execute, schema=schema)
transport.close()
with pytest.raises(TransportClosedException):
tk = iToolKit()
out = transport.call(tk)
| 27.040541 | 70 | 0.743628 | 230 | 2,001 | 6.165217 | 0.147826 | 0.116361 | 0.090268 | 0.084626 | 0.77292 | 0.744711 | 0.724965 | 0.724965 | 0.724965 | 0.724965 | 0 | 0.004776 | 0.162919 | 2,001 | 73 | 71 | 27.410959 | 0.841791 | 0 | 0 | 0.708333 | 0 | 0 | 0.011994 | 0 | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0.104167 | false | 0 | 0.0625 | 0 | 0.166667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
06b17bc26e52c98ea0e7595ef65bcc2ffbffbadb | 32,965 | py | Python | apps/fifth_edition/tests/test_combat_info_view_get.py | tylerfrenchx13/django-dnd | b0c78c51aebeed4195fd91a3e55c313c645f9c3b | [
"MIT"
] | 4 | 2019-01-30T03:39:06.000Z | 2022-02-22T08:11:53.000Z | apps/fifth_edition/tests/test_combat_info_view_get.py | tylerfrenchx13/django-dnd | b0c78c51aebeed4195fd91a3e55c313c645f9c3b | [
"MIT"
] | 13 | 2019-05-10T04:22:14.000Z | 2020-04-06T02:54:32.000Z | apps/fifth_edition/tests/test_combat_info_view_get.py | tylerfrenchx13/django-dnd | b0c78c51aebeed4195fd91a3e55c313c645f9c3b | [
"MIT"
] | 3 | 2019-02-06T19:26:43.000Z | 2021-03-18T23:48:41.000Z | from apps.fifth_edition.models import CombatInfo
from django.test import TestCase
from rest_framework.test import APIClient
from random import randint
class TestCombatInfoViewGET(TestCase):
"""
Test class to verify functionality of the CombatInfoViewGET API view.
"""
def setUp(self):
"""
Method to create required test data
:return: None
"""
# Create a set of Characters, with varying data
for num in range(1, 6):
if num == 1:
score_data = {
"armor_class": 15,
"initiative": 2,
"speed": 30,
"total_hit_points": 20,
"current_hit_points": 17,
"temporary_hit_points": 2,
"hit_dice_total": 1,
"hit_dice": "d8",
"death_save_success": 1,
"death_save_failure": 2
}
else:
score_data = {
"armor_class": randint(1, 30),
"initiative": randint(1, 30),
"speed": randint(1, 30),
"total_hit_points": randint(1, 30),
"current_hit_points": randint(1, 30),
"temporary_hit_points": randint(1, 30),
"hit_dice_total": randint(1, 30),
"hit_dice": "d8",
"death_save_success": randint(1, 30),
"death_save_failure": randint(1, 30)
}
CombatInfo.objects.create(**score_data)
def tearDown(self):
"""
Method to remove extraneous test data generated as a side effect of individual tests
:return: None
"""
pass
def test_combat_info_get_info_no_params_successful_except_hit_dice(self):
"""
Unit test to verify that a direct request, with no query parameters works properly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertEqual(len(results), 5)
self.assertIn("armor_class", results[0])
self.assertIn("initiative", results[0])
self.assertIn("speed", results[0])
self.assertIn("total_hit_points", results[0])
self.assertIn("current_hit_points", results[0])
self.assertIn("temporary_hit_points", results[0])
self.assertIn("hit_dice_total", results[0])
self.assertIn("hit_dice", results[0])
self.assertIn("death_save_success", results[0])
self.assertIn("death_save_failure", results[0])
def test_combat_info_get_info_query_by_armor_class_exact_successful(self):
"""
Unit test to verify that querying by armor class, exact, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?armor_class=15", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_fifteen = CombatInfo.objects.filter(armor_class=15).count()
self.assertTrue(len(results) == str_fifteen)
def test_combat_info_get_info_query_by_armor_class_doesnt_exist_successful(self):
"""
Unit test to verify that querying by armor class, doesnt exist, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?armor_class=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_armor_class_above_successful(self):
"""
Unit test to verify that querying by a armor_class_above works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?armor_class_above=15", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_gt_fifteen = CombatInfo.objects.filter(armor_class__gte=15).count()
self.assertTrue(len(results) == str_gt_fifteen)
def test_combat_info_get_info_query_by_armor_class_above_no_results(self):
"""
Unit test to verify that querying by a armor_class_above that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?armor_class_above=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_armor_class_below_successful(self):
"""
Unit test to verify that querying by a armor_class_below works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?armor_class_below=20", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_lt_fifteen = CombatInfo.objects.filter(armor_class__lte=20).count()
self.assertTrue(len(results) == str_lt_fifteen)
def test_combat_info_get_info_query_by_armor_class_below_no_results(self):
"""
Unit test to verify that querying by a armor_class_below that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?armor_class_below=0", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
#initiative
def test_combat_info_get_info_query_by_initiative_exact_successful(self):
"""
Unit test to verify that querying by initiative, exact, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?initiative=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_fifteen = CombatInfo.objects.filter(initiative=2).count()
self.assertTrue(len(results) == str_fifteen)
def test_combat_info_get_info_query_by_initiative_doesnt_exist_successful(self):
"""
Unit test to verify that querying by initiative, doesnt exist, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?initiative=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_initiative_above_successful(self):
"""
Unit test to verify that querying by a initiative_above works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?initiative_above=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_gt_fifteen = CombatInfo.objects.filter(initiative__gte=2).count()
self.assertTrue(len(results) == str_gt_fifteen)
def test_combat_info_get_info_query_by_initiative_above_no_results(self):
"""
Unit test to verify that querying by a initiative_above that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?initiative_above=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_initiative_below_successful(self):
"""
Unit test to verify that querying by a initiative_below works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?initiative_below=20", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_lt_fifteen = CombatInfo.objects.filter(initiative__lte=20).count()
self.assertTrue(len(results) == str_lt_fifteen)
def test_combat_info_get_info_query_by_initiative_below_no_results(self):
"""
Unit test to verify that querying by a initiative_below that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?initiative_below=0", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
#speed
def test_combat_info_get_info_query_by_speed_exact_successful(self):
"""
Unit test to verify that querying by speed, exact, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?speed=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_fifteen = CombatInfo.objects.filter(speed=2).count()
self.assertTrue(len(results) == str_fifteen)
def test_combat_info_get_info_query_by_speed_doesnt_exist_successful(self):
"""
Unit test to verify that querying by speed, doesnt exist, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?speed=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_speed_above_successful(self):
"""
Unit test to verify that querying by a speed_above works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?speed_above=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_gt_fifteen = CombatInfo.objects.filter(speed__gte=2).count()
self.assertTrue(len(results) == str_gt_fifteen)
def test_combat_info_get_info_query_by_speed_above_no_results(self):
"""
Unit test to verify that querying by a speed_above that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?speed_above=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_speed_below_successful(self):
"""
Unit test to verify that querying by a speed_below works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?speed_below=20", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_lt_fifteen = CombatInfo.objects.filter(speed__lte=20).count()
self.assertTrue(len(results) == str_lt_fifteen)
def test_combat_info_get_info_query_by_speed_below_no_results(self):
"""
Unit test to verify that querying by a speed_below that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?speed_below=0", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
#total_hit_points
def test_combat_info_get_info_query_by_total_hit_points_exact_successful(self):
"""
Unit test to verify that querying by total_hit_points, exact, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?total_hit_points=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_fifteen = CombatInfo.objects.filter(total_hit_points=2).count()
self.assertTrue(len(results) == str_fifteen)
def test_combat_info_get_info_query_by_total_hit_points_doesnt_exist_successful(self):
"""
Unit test to verify that querying by total_hit_points, doesnt exist, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?total_hit_points=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_total_hit_points_above_successful(self):
"""
Unit test to verify that querying by a total_hit_points_above works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?total_hit_points_above=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_gt_fifteen = CombatInfo.objects.filter(total_hit_points__gte=2).count()
self.assertTrue(len(results) == str_gt_fifteen)
def test_combat_info_get_info_query_by_total_hit_points_above_no_results(self):
"""
Unit test to verify that querying by a total_hit_points_above that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?total_hit_points_above=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_total_hit_points_below_successful(self):
"""
Unit test to verify that querying by a total_hit_points_below works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?total_hit_points_below=20", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_lt_fifteen = CombatInfo.objects.filter(total_hit_points__lte=20).count()
self.assertTrue(len(results) == str_lt_fifteen)
def test_combat_info_get_info_query_by_total_hit_points_below_no_results(self):
"""
Unit test to verify that querying by a total_hit_points_below that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?total_hit_points_below=0", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
#current_hit_points
def test_combat_info_get_info_query_by_current_hit_points_exact_successful(self):
"""
Unit test to verify that querying by current_hit_points, exact, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?current_hit_points=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_fifteen = CombatInfo.objects.filter(current_hit_points=2).count()
self.assertTrue(len(results) == str_fifteen)
def test_combat_info_get_info_query_by_current_hit_points_doesnt_exist_successful(self):
"""
Unit test to verify that querying by current_hit_points, doesnt exist, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?current_hit_points=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_current_hit_points_above_successful(self):
"""
Unit test to verify that querying by a current_hit_points_above works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?current_hit_points_above=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_gt_fifteen = CombatInfo.objects.filter(current_hit_points__gte=2).count()
self.assertTrue(len(results) == str_gt_fifteen)
def test_combat_info_get_info_query_by_current_hit_points_above_no_results(self):
"""
Unit test to verify that querying by a current_hit_points_above that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?current_hit_points_above=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_current_hit_points_below_successful(self):
"""
Unit test to verify that querying by a current_hit_points_below works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?current_hit_points_below=20", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_lt_fifteen = CombatInfo.objects.filter(current_hit_points__lte=20).count()
self.assertTrue(len(results) == str_lt_fifteen)
def test_combat_info_get_info_query_by_current_hit_points_below_no_results(self):
"""
Unit test to verify that querying by a current_hit_points_below that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?current_hit_points_below=0", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
#temporary_hit_points
def test_combat_info_get_info_query_by_temporary_hit_points_exact_successful(self):
"""
Unit test to verify that querying by temporary_hit_points, exact, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?temporary_hit_points=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_fifteen = CombatInfo.objects.filter(temporary_hit_points=2).count()
self.assertTrue(len(results) == str_fifteen)
def test_combat_info_get_info_query_by_temporary_hit_points_doesnt_exist_successful(self):
"""
Unit test to verify that querying by temporary_hit_points, doesnt exist, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?temporary_hit_points=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_temporary_hit_points_above_successful(self):
"""
Unit test to verify that querying by a temporary_hit_points_above works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?temporary_hit_points_above=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_gt_fifteen = CombatInfo.objects.filter(temporary_hit_points__gte=2).count()
self.assertTrue(len(results) == str_gt_fifteen)
def test_combat_info_get_info_query_by_temporary_hit_points_above_no_results(self):
"""
Unit test to verify that querying by a temporary_hit_points_above that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?temporary_hit_points_above=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_temporary_hit_points_below_successful(self):
"""
Unit test to verify that querying by a temporary_hit_points_below works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?temporary_hit_points_below=20", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_lt_fifteen = CombatInfo.objects.filter(temporary_hit_points__lte=20).count()
self.assertTrue(len(results) == str_lt_fifteen)
def test_combat_info_get_info_query_by_temporary_hit_points_below_no_results(self):
"""
Unit test to verify that querying by a temporary_hit_points_below that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?temporary_hit_points_below=0", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
#hit_dice_total
def test_combat_info_get_info_query_by_hit_dice_total_exact_successful(self):
"""
Unit test to verify that querying by hit_dice_total, exact, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?hit_dice_total=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_fifteen = CombatInfo.objects.filter(hit_dice_total=2).count()
self.assertTrue(len(results) == str_fifteen)
def test_combat_info_get_info_query_by_hit_dice_total_doesnt_exist_successful(self):
"""
Unit test to verify that querying by hit_dice_total, doesnt exist, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?hit_dice_total=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_hit_dice_total_above_successful(self):
"""
Unit test to verify that querying by a hit_dice_total_above works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?hit_dice_total_above=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_gt_fifteen = CombatInfo.objects.filter(hit_dice_total__gte=2).count()
self.assertTrue(len(results) == str_gt_fifteen)
def test_combat_info_get_info_query_by_hit_dice_total_above_no_results(self):
"""
Unit test to verify that querying by a hit_dice_total_above that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?hit_dice_total_above=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_hit_dice_total_below_successful(self):
"""
Unit test to verify that querying by a hit_dice_total_below works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?hit_dice_total_below=20", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_lt_fifteen = CombatInfo.objects.filter(hit_dice_total__lte=20).count()
self.assertTrue(len(results) == str_lt_fifteen)
def test_combat_info_get_info_query_by_hit_dice_total_below_no_results(self):
"""
Unit test to verify that querying by a hit_dice_total_below that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?hit_dice_total_below=0", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
#death_save_success
def test_combat_info_get_info_query_by_death_save_success_exact_successful(self):
"""
Unit test to verify that querying by death_save_success, exact, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_success=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_fifteen = CombatInfo.objects.filter(death_save_success=2).count()
self.assertTrue(len(results) == str_fifteen)
def test_combat_info_get_info_query_by_death_save_success_doesnt_exist_successful(self):
"""
Unit test to verify that querying by death_save_success, doesnt exist, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_success=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_death_save_success_above_successful(self):
"""
Unit test to verify that querying by a death_save_success_above works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_success_above=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_gt_fifteen = CombatInfo.objects.filter(death_save_success__gte=2).count()
self.assertTrue(len(results) == str_gt_fifteen)
def test_combat_info_get_info_query_by_death_save_success_above_no_results(self):
"""
Unit test to verify that querying by a death_save_success_above that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_success_above=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_death_save_success_below_successful(self):
"""
Unit test to verify that querying by a death_save_success_below works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_success_below=20", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_lt_fifteen = CombatInfo.objects.filter(death_save_success__lte=20).count()
self.assertTrue(len(results) == str_lt_fifteen)
def test_combat_info_get_info_query_by_death_save_success_below_no_results(self):
"""
Unit test to verify that querying by a death_save_success_below that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_success_below=0", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
#death_save_failure
def test_combat_info_get_info_query_by_death_save_failure_exact_successful(self):
"""
Unit test to verify that querying by death_save_failure, exact, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_failure=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_fifteen = CombatInfo.objects.filter(death_save_failure=2).count()
self.assertTrue(len(results) == str_fifteen)
def test_combat_info_get_info_query_by_death_save_failure_doesnt_exist_successful(self):
"""
Unit test to verify that querying by death_save_failure, doesnt exist, works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_failure=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_death_save_failure_above_successful(self):
"""
Unit test to verify that querying by a death_save_failure_above works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_failure_above=2", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_gt_fifteen = CombatInfo.objects.filter(death_save_failure__gte=2).count()
self.assertTrue(len(results) == str_gt_fifteen)
def test_combat_info_get_info_query_by_death_save_failure_above_no_results(self):
"""
Unit test to verify that querying by a death_save_failure_above that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_failure_above=31", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0)
def test_combat_info_get_info_query_by_death_save_failure_below_successful(self):
"""
Unit test to verify that querying by a death_save_failure_below works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_failure_below=20", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
str_lt_fifteen = CombatInfo.objects.filter(death_save_failure__lte=20).count()
self.assertTrue(len(results) == str_lt_fifteen)
def test_combat_info_get_info_query_by_death_save_failure_below_no_results(self):
"""
Unit test to verify that querying by a death_save_failure_below that doesn't exist works correctly
:return: None
"""
client = APIClient()
response = client.get("/api/combat-info?death_save_failure_below=0", format="json")
# Assert status code
self.assertEqual(response.status_code, 200)
results = response.data["results"]
self.assertTrue(len(results) == 0) | 33.603466 | 108 | 0.656484 | 4,040 | 32,965 | 5.082921 | 0.031436 | 0.053567 | 0.034819 | 0.045532 | 0.950329 | 0.944534 | 0.929584 | 0.922523 | 0.922523 | 0.918773 | 0 | 0.01486 | 0.246747 | 32,965 | 981 | 109 | 33.603466 | 0.81213 | 0.208464 | 0 | 0.55335 | 0 | 0 | 0.127433 | 0.084584 | 0 | 0 | 0 | 0 | 0.297767 | 1 | 0.141439 | false | 0.002481 | 0.009926 | 0 | 0.153846 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
ebf4c9bbac6bd2176a1c90d28a654b8c736ef75d | 43,621 | py | Python | functionTerms/hydrogenBondTerms.py | XingchengLin/openawsem | a9f155d72e359b76d350e6d4c2ee476410ebe4c6 | [
"MIT"
] | 15 | 2019-11-01T21:43:43.000Z | 2022-01-05T15:53:15.000Z | functionTerms/hydrogenBondTerms.py | XingchengLin/openawsem | a9f155d72e359b76d350e6d4c2ee476410ebe4c6 | [
"MIT"
] | 10 | 2019-02-06T17:07:45.000Z | 2021-10-19T02:20:41.000Z | functionTerms/hydrogenBondTerms.py | XingchengLin/openawsem | a9f155d72e359b76d350e6d4c2ee476410ebe4c6 | [
"MIT"
] | 8 | 2018-12-30T18:01:47.000Z | 2021-05-27T21:07:17.000Z | from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
import numpy as np
se_map_1_letter = {'A': 0, 'P': 1, 'K': 2, 'N': 3, 'R': 4,
'F': 5, 'D': 6, 'Q': 7, 'E': 8, 'G': 9,
'I': 10, 'H': 11, 'L': 12, 'C': 13, 'M': 14,
'S': 15, 'T': 16, 'Y': 17, 'V': 18, 'W': 19}
def isChainStart(residueId, chain_starts, n=2):
# return true if residue is near chain starts.
# n=0 means always return False
# n=1 means only return True if residue is the the first residue of a chain.
# n=2 means return True if residue is the first or the one nearest to the first residue of a chain.
atBegin = False
for i in range(n):
if (residueId-i) in chain_starts:
atBegin = True
return atBegin
def isChainEnd(residueId, chain_ends, n=2):
# return true if residue is near chain ends.
# n=0 means always return False
# n=1 means only return True if residue is the the last residue of a chain.
# n=2 means return True if residue is the last or the one nearest to the last residue of a chain.
atEnd = False
for i in range(n):
if (residueId+i) in chain_ends:
atEnd = True
return atEnd
def isChainEdge(residueId, chain_starts, chain_ends, n=2):
# n is how far away from the two ends count as in chain edge.
return (isChainStart(residueId, chain_starts, n) or isChainEnd(residueId, chain_ends, n))
# atBegin = False
# atEnd = False
# for i in range(n):
# if (residueId-i) in chain_starts:
# atBegin = True
# for i in range(n):
# if (residueId+i) in chain_ends:
# atEnd = True
# return (atBegin or atEnd)
def inWhichChain(residueId, chain_ends):
chain_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for i, end_of_chain_resId in enumerate(chain_ends):
if end_of_chain_resId < residueId:
pass
else:
return chain_table[i]
def read_beta_parameters():
### directly copied from Nick Schafer's
# os.chdir(parameter_directory)
in_anti_HB = open("anti_HB", 'r').readlines()
in_anti_NHB = open("anti_NHB", 'r').readlines()
in_para_HB = open("para_HB", 'r').readlines()
in_para_one = open("para_one", 'r').readlines()
in_anti_one = open("anti_one", 'r').readlines()
p_par = np.zeros((20))
p_anti = np.zeros((20))
p_antihb = np.zeros((20,20,2))
p_antinhb = np.zeros((20,20,2))
p_parhb = np.zeros((20,20,2))
for i in range(20):
p_par[i] = float(in_para_one[i].strip())
p_anti[i] = float(in_anti_one[i].strip())
for j in range(20):
p_antihb[i][j][0] = float(in_anti_HB[i].strip().split()[j])
p_antinhb[i][j][0] = float(in_anti_NHB[i].strip().split()[j])
p_parhb[i][j][0] = float(in_para_HB[i].strip().split()[j])
for i in range(20):
for j in range(20):
p_antihb[i][j][1] = float(in_anti_HB[i+21].strip().split()[j])
p_antinhb[i][j][1] = float(in_anti_NHB[i+21].strip().split()[j])
p_parhb[i][j][1] = float(in_para_HB[i+21].strip().split()[j])
return p_par, p_anti, p_antihb, p_antinhb, p_parhb
def get_lambda_by_index(i, j, lambda_i):
lambda_table = [[1.37, 1.36, 1.17],
[3.89, 3.50, 3.52],
[0.00, 3.47, 3.62]]
if abs(j-i) >= 4 and abs(j-i) < 18:
return lambda_table[lambda_i][0]
elif abs(j-i) >= 18 and abs(j-i) < 45:
return lambda_table[lambda_i][1]
elif abs(j-i) >= 45:
return lambda_table[lambda_i][2]
else:
return 0
def get_alpha_by_index(i, j, alpha_i):
alpha_table = [[1.30, 1.30, 1.30],
[1.32, 1.32, 1.32],
[1.22, 1.22, 1.22],
[0.00, 0.33, 0.33],
[0.00, 1.01, 1.01]]
if abs(j-i) >= 4 and abs(j-i) < 18:
return alpha_table[alpha_i][0]
elif abs(j-i) >= 18 and abs(j-i) < 45:
return alpha_table[alpha_i][1]
elif abs(j-i) >= 45:
return alpha_table[alpha_i][2]
else:
return 0
def get_pap_gamma_APH(donor_idx, acceptor_idx, chain_i, chain_j, gamma_APH):
# if chain_i == chain_j and abs(j-i) < 13 or abs(j-i) > 16:
# if abs(j-i) < 13 or abs(j-i) > 16:
# if i-j < 13 or i-j > 16:
# if (donor_idx - acceptor_idx >= 13 and donor_idx - acceptor_idx <= 16) or chain_i != chain_j:
if (donor_idx - acceptor_idx >= 13 and donor_idx - acceptor_idx <= 16) and chain_i == chain_j:
return gamma_APH
else:
return 0
def get_pap_gamma_AP(donor_idx, acceptor_idx, chain_i, chain_j, gamma_AP, ssweight):
if ssweight[donor_idx][1] == 1 and ssweight[acceptor_idx][1] == 1:
additional_scale = 1.5
else:
additional_scale = 1.0
# if (donor_idx - acceptor_idx >= 17):
if (donor_idx - acceptor_idx >= 17) or chain_i != chain_j:
return additional_scale * gamma_AP
else:
return 0
def get_pap_gamma_P(donor_idx, acceptor_idx, chain_i, chain_j, gamma_P, ssweight):
if ssweight[donor_idx][1] == 1 and ssweight[acceptor_idx][1] == 1:
additional_scale = 1.5
else:
additional_scale = 1.0
if (donor_idx - acceptor_idx >= 9) or chain_i != chain_j:
return additional_scale * gamma_P
else:
return 0
def get_Lambda_2(i, j, p_par, p_anti, p_antihb, p_antinhb, p_parhb, a):
Lambda = get_lambda_by_index(i, j, 1)
Lambda += -0.5*get_alpha_by_index(i, j, 0)*p_antihb[a[i], a[j]][0]
Lambda += -0.25*get_alpha_by_index(i, j, 1)*(p_antinhb[a[i+1], a[j-1]][0] + p_antinhb[a[i-1], a[j+1]][0])
Lambda += -get_alpha_by_index(i, j, 2)*(p_anti[a[i]] + p_anti[a[j]])
return Lambda
def get_Lambda_3(i, j, p_par, p_anti, p_antihb, p_antinhb, p_parhb, a):
Lambda = get_lambda_by_index(i, j, 2)
Lambda += -get_alpha_by_index(i, j, 3)*p_parhb[a[i+1], a[j]][0]
Lambda += -get_alpha_by_index(i, j, 4)*p_par[a[i+1]]
Lambda += -get_alpha_by_index(i, j, 3)*p_par[a[j]]
return Lambda
# def beta_term_1(oa, k_beta=4.184):
# print("beta_1 term ON")
# nres, n, h, ca, o, res_type = oa.nres, oa.n, oa.h, oa.ca, oa.o, oa.res_type
# # print(lambda_1)
# r_ON = .298
# sigma_NO = .068
# r_OH = .206
# sigma_HO = .076
# lambda_1 = np.zeros((nres, nres))
# for i in range(nres):
# for j in range(nres):
# lambda_1[i][j] = get_lambda_by_index(i, j, 0)
# theta_ij = f"exp(-(r_Oi_Nj-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oi_Hj-{r_OH})^2/(2*{sigma_HO}^2))"
# beta_string_1 = f"-{k_beta}*lambda_1(res_i,res_j)*theta_ij;theta_ij={theta_ij};r_Oi_Nj=distance(a1,d1);r_Oi_Hj=distance(a1,d2);"
# beta_1 = CustomHbondForce(beta_string_1)
# beta_1.addPerDonorParameter("res_i")
# beta_1.addPerAcceptorParameter("res_j")
# beta_1.addTabulatedFunction("lambda_1", Discrete2DFunction(nres, nres, lambda_1.T.flatten()))
# # print(lambda_1)
# # print(len(oa.o), nres)
# for i in range(nres):
# if oa.o[i]!= -1:
# beta_1.addAcceptor(oa.o[i], -1, -1, [i])
# if oa.n[i]!=-1 and oa.h[i]!=-1:
# beta_1.addDonor(oa.n[i], oa.h[i], -1, [i])
# beta_1.setNonbondedMethod(CustomHbondForce.CutoffNonPeriodic)
# beta_1.setCutoffDistance(1.0)
# beta_1.setForceGroup(23)
# # beta_2.setForceGroup(24)
# # beta_3.setForceGroup(25)
# return beta_1
def convert_units(k):
if isinstance(k, float) or isinstance(k, int):
k = k # just for backward comptable
elif isinstance(k, Quantity):
k = k.value_in_unit(kilojoule_per_mole) # convert to kilojoule_per_mole, openMM default uses kilojoule_per_mole as energy.
else:
print(f"Unknown input, {k}, {type(k)}")
return k
def beta_term_1(oa, k=0.5*kilocalories_per_mole, forceGroup=27):
print("beta_1 term ON")
k_beta = convert_units(k) * oa.k_awsem
nres, n, h, ca, o, res_type = oa.nres, oa.n, oa.h, oa.ca, oa.o, oa.res_type
# print(lambda_1)
r_ON = .298
sigma_NO = .068
r_OH = .206
sigma_HO = .076
lambda_1 = np.zeros((nres, nres))
for i in range(nres):
for j in range(nres):
lambda_1[i][j] = get_lambda_by_index(i, j, 0)
theta_ij = f"exp(-(r_Oi_Nj-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oi_Hj-{r_OH})^2/(2*{sigma_HO}^2))"
mu_1 = 10 # nm^-1
# mu_2 = 5 # nm^-1
rcHB = 1.2 # in nm
# v1i ensures the hydrogen bonding does not occur when five residue segment is shorter than 12 A
# v1i = f"0.5*(1+tanh({mu_1}*(distance(a2,a3)-{rcHB})))"
v1i = "1"
beta_string_1 = f"-{k_beta}*lambda_1(res_i,res_j)*theta_ij*v1i;theta_ij={theta_ij};v1i={v1i};r_Oi_Nj=distance(a1,d1);r_Oi_Hj=distance(a1,d2);"
beta_1 = CustomHbondForce(beta_string_1)
beta_1.addPerDonorParameter("res_i")
beta_1.addPerAcceptorParameter("res_j")
beta_1.addTabulatedFunction("lambda_1", Discrete2DFunction(nres, nres, lambda_1.T.flatten()))
# print(lambda_1)
# print(len(oa.o), nres)
for i in range(nres):
if oa.o[i]!= -1:
ca_i_minus_2 = oa.ca[0] if i <= 2 else oa.ca[i-2]
ca_i_plus_2 = oa.ca[-1] if i+2 >= nres else oa.ca[i+2]
# beta_1.addAcceptor(oa.o[i], ca_i_minus_2, ca_i_plus_2, [i])
beta_1.addAcceptor(oa.o[i], -1, -1, [i])
if oa.n[i]!=-1 and oa.h[i]!=-1:
beta_1.addDonor(oa.n[i], oa.h[i], -1, [i])
beta_1.setNonbondedMethod(CustomHbondForce.CutoffNonPeriodic)
beta_1.setCutoffDistance(1.0)
beta_1.setForceGroup(forceGroup)
# beta_2.setForceGroup(24)
# beta_3.setForceGroup(25)
return beta_1
def beta_term_2(oa, k=0.5*kilocalories_per_mole, forceGroup=27):
print("beta_2 term ON")
k_beta = convert_units(k) * oa.k_awsem
nres, n, h, ca, o, res_type = oa.nres, oa.n, oa.h, oa.ca, oa.o, oa.res_type
# print(lambda_1)
r_ON = .298
sigma_NO = .068
r_OH = .206
sigma_HO = .076
eta_beta_1 = 10.0
eta_beta_2 = 5.0
# r_HB_c = 0.4
r_HB_c = 1.2
p_par, p_anti, p_antihb, p_antinhb, p_parhb = read_beta_parameters()
# for lookup table.
a = []
for ii in range(oa.nres):
a.append(se_map_1_letter[oa.seq[ii]])
lambda_2 = np.zeros((nres, nres))
for i in range(nres):
for j in range(nres):
if isChainEdge(i, oa.chain_starts, oa.chain_ends, n=1) or \
isChainEdge(j, oa.chain_starts, oa.chain_ends, n=1):
continue
lambda_2[i][j] = get_Lambda_2(i, j, p_par, p_anti, p_antihb, p_antinhb, p_parhb, a)
theta_ij = f"exp(-(r_Oi_Nj-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oi_Hj-{r_OH})^2/(2*{sigma_HO}^2))"
theta_ji = f"exp(-(r_Oj_Ni-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oj_Hi-{r_OH})^2/(2*{sigma_HO}^2))"
beta_string_2 = f"-{k_beta}*lambda_2(res_i,res_j)*theta_ij*theta_ji;\
theta_ij={theta_ij};r_Oi_Nj=distance(a1,d1);r_Oi_Hj=distance(a1,d2);\
theta_ji={theta_ji};r_Oj_Ni=distance(d3,a2);r_Oj_Hi=distance(d3,a3);"
beta_2 = CustomHbondForce(beta_string_2)
beta_2.addPerDonorParameter("res_i")
beta_2.addPerAcceptorParameter("res_j")
beta_2.addTabulatedFunction("lambda_2", Discrete2DFunction(nres, nres, lambda_2.T.flatten()))
# print(lambda_1)
# print(len(oa.o), nres)
for i in range(nres):
if o[i]!= -1 and n[i]!=-1 and h[i]!=-1:
beta_2.addAcceptor(o[i], n[i], h[i], [i])
beta_2.addDonor(n[i], h[i], o[i], [i])
beta_2.setNonbondedMethod(CustomHbondForce.CutoffNonPeriodic)
beta_2.setCutoffDistance(1.0)
# beta_1.setForceGroup(23)
beta_2.setForceGroup(forceGroup)
# beta_3.setForceGroup(25)
return beta_2
def beta_term_3(oa, k=0.5*kilocalories_per_mole, forceGroup=27):
print("beta_3 term ON")
k_beta = convert_units(k) * oa.k_awsem
nres, n, h, ca, o, res_type = oa.nres, oa.n, oa.h, oa.ca, oa.o, oa.res_type
# print(lambda_1)
r_ON = .298
sigma_NO = .068
r_OH = .206
sigma_HO = .076
eta_beta_1 = 10.0
eta_beta_2 = 5.0
# r_HB_c = 0.4
r_HB_c = 1.2
p_par, p_anti, p_antihb, p_antinhb, p_parhb = read_beta_parameters()
# for lookup table.
a = []
for ii in range(oa.nres):
a.append(se_map_1_letter[oa.seq[ii]])
lambda_3 = np.zeros((nres, nres))
for i in range(nres):
for j in range(nres):
if isChainEdge(i, oa.chain_starts, oa.chain_ends, n=1) or \
isChainEdge(j, oa.chain_starts, oa.chain_ends, n=1):
continue
lambda_3[i][j] = get_Lambda_3(i, j, p_par, p_anti, p_antihb, p_antinhb, p_parhb, a)
theta_ij = f"exp(-(r_Oi_Nj-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oi_Hj-{r_OH})^2/(2*{sigma_HO}^2))"
theta_jip2 = f"exp(-(r_Oj_Nip2-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oj_Hip2-{r_OH})^2/(2*{sigma_HO}^2))"
beta_string_3 = f"-{k_beta}*lambda_3(res_i,res_j)*theta_ij*theta_jip2;\
theta_ij={theta_ij};r_Oi_Nj=distance(a1,d1);r_Oi_Hj=distance(a1,d2);\
theta_jip2={theta_jip2};r_Oj_Nip2=distance(d3,a2);r_Oj_Hip2=distance(d3,a3);"
beta_3 = CustomHbondForce(beta_string_3)
beta_3.addPerDonorParameter("res_i")
beta_3.addPerAcceptorParameter("res_j")
beta_3.addTabulatedFunction("lambda_3", Discrete2DFunction(nres, nres, lambda_3.T.flatten()))
# print(lambda_1)
# print(len(oa.o), nres)
for i in range(nres):
if isChainEdge(i, oa.chain_starts, oa.chain_ends, n=2):
continue
if o[i] != -1 and n[i+2] !=-1 and h[i+2] !=-1:
beta_3.addAcceptor(o[i], n[i+2], h[i+2], [i])
if o[i] != -1 and n[i] !=-1 and h[i] !=-1:
beta_3.addDonor(n[i], h[i], o[i], [i])
beta_3.setNonbondedMethod(CustomHbondForce.CutoffNonPeriodic)
beta_3.setCutoffDistance(1.0)
# beta_1.setForceGroup(23)
# beta_2.setForceGroup(24)
beta_3.setForceGroup(forceGroup)
return beta_3
def pap_term_1(oa, k=0.5*kilocalories_per_mole, dis_i_to_i4=1.2, forceGroup=28, ssweightFileName="ssweight"):
print("pap_1 term ON")
k_pap = convert_units(k) * oa.k_awsem
# dis_i_to_i4 should be in nm, it disfavor hydrogen bond when ca_i and ca_i+4 are 1.2 nm apart away.
nres, ca = oa.nres, oa.ca
# r0 = 2.0 # nm
r0 = 0.8 # nm
eta_pap = 70 # nm^-1
gamma_aph = 1.0
gamma_ap = 0.4
gamma_p = 0.4
if not os.path.exists(ssweightFileName):
print("No ssweight given, assume all zero")
ssweight = np.zeros((nres, 2))
else:
ssweight = np.loadtxt(ssweightFileName)
gamma_1 = np.zeros((nres, nres))
gamma_2 = np.zeros((nres, nres))
for i in range(nres):
for j in range(nres):
resId1 = i
chain1 = inWhichChain(resId1, oa.chain_ends)
resId2 = j
chain2 = inWhichChain(resId2, oa.chain_ends)
gamma_1[i][j] = get_pap_gamma_APH(i, j, chain1, chain2, gamma_aph)
gamma_2[i][j] = get_pap_gamma_AP(i, j, chain1, chain2, gamma_ap, ssweight)
constraint_i_and_i4 = f"0.5*(1+tanh({eta_pap}*(distance(a1,a2)-{dis_i_to_i4})))"
pap_function = f"-{k_pap}*(gamma_1(donor_idx,acceptor_idx)+gamma_2(donor_idx,acceptor_idx))\
*0.5*(1+tanh({eta_pap}*({r0}-distance(a1,d1))))\
*0.5*(1+tanh({eta_pap}*({r0}-distance(a2,d2))))\
*{constraint_i_and_i4}"
# pap_function = f"-{k_pap}*(gamma_1(donor_idx,acceptor_idx))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a1,d1))))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a2,d2))))"
# pap_function = f"-{k_pap}*distance(a1,d1)"
pap = CustomHbondForce(pap_function)
pap.addPerDonorParameter("donor_idx")
pap.addPerAcceptorParameter("acceptor_idx")
pap.addTabulatedFunction("gamma_1", Discrete2DFunction(nres, nres, gamma_1.T.flatten()))
pap.addTabulatedFunction("gamma_2", Discrete2DFunction(nres, nres, gamma_2.T.flatten()))
# print(ca)
# count = 0;
i = 0
for i in range(nres):
if not isChainEnd(i, oa.chain_ends, n=4):
pap.addAcceptor(ca[i], ca[i+4], -1, [i])
if not isChainStart(i, oa.chain_starts, n=4):
if oa.n[i] != -1 and oa.n[i-4] != -1:
pap.addDonor(oa.n[i], oa.n[i-4], -1, [i])
pap.setNonbondedMethod(CustomHbondForce.CutoffNonPeriodic)
pap.setCutoffDistance(1.0)
# print(count)
pap.setForceGroup(forceGroup)
return pap
def pap_term_2(oa, k=0.5*kilocalories_per_mole, dis_i_to_i4=1.2, forceGroup=28, ssweightFileName="ssweight"):
print("pap_2 term ON")
k_pap = convert_units(k) * oa.k_awsem
nres, ca = oa.nres, oa.ca
# r0 = 2.0 # nm
r0 = 0.8 # nm
eta_pap = 70 # nm^-1
gamma_aph = 1.0
gamma_ap = 0.4
gamma_p = 0.4
if not os.path.exists(ssweightFileName):
print("No ssweight given, assume all zero")
ssweight = np.zeros((nres, 2))
else:
ssweight = np.loadtxt(ssweightFileName)
gamma_3 = np.zeros((nres, nres))
for i in range(nres):
for j in range(nres):
resId1 = i
chain1 = inWhichChain(resId1, oa.chain_ends)
resId2 = j
chain2 = inWhichChain(resId2, oa.chain_ends)
gamma_3[i][j] = get_pap_gamma_P(i, j, chain1, chain2, gamma_p, ssweight)
constraint_i_and_i4 = f"0.5*(1+tanh({eta_pap}*(distance(a1,a2)-{dis_i_to_i4})))"
pap_function = f"-{k_pap}*gamma_3(donor_idx,acceptor_idx)\
*0.5*(1+tanh({eta_pap}*({r0}-distance(a1,d1))))\
*0.5*(1+tanh({eta_pap}*({r0}-distance(a2,d2))))\
*{constraint_i_and_i4}"
pap = CustomHbondForce(pap_function)
pap.addPerDonorParameter("donor_idx")
pap.addPerAcceptorParameter("acceptor_idx")
pap.addTabulatedFunction("gamma_3", Discrete2DFunction(nres, nres, gamma_3.T.flatten()))
# print(oa.n)
# count = 0;
for i in range(nres):
if not isChainEnd(i, oa.chain_ends, n=4):
pap.addAcceptor(ca[i], ca[i+4], -1, [i])
# pap.addDonor(ca[i], ca[i+4], -1, [i])
if oa.n[i] != -1 and oa.n[i+4] != -1:
pap.addDonor(oa.n[i], oa.n[i+4], -1, [i])
pap.setNonbondedMethod(CustomHbondForce.CutoffNonPeriodic)
pap.setCutoffDistance(1.0)
# print(count)
pap.setForceGroup(forceGroup)
return pap
def get_helical_f(oneLetterCode, inMembrane=False):
if inMembrane:
table = {"A": 0.79, "R": 0.62, "N": 0.49, "D": 0.44, "C": 0.76, "Q": 0.61, "E": 0.57, "G": 0.57, "H": 0.63, "I": 0.81,
"L": 0.81, "K": 0.56, "M": 0.80, "F": 0.76, "P": 0.44, "S": 0.6, "T": 0.67, "W": 0.74, "Y": 0.71, "V": 0.79}
else:
table = {"A": 0.77, "R": 0.68, "N": 0.07, "D": 0.15, "C": 0.23, "Q": 0.33, "E": 0.27, "G": 0.0, "H": 0.06, "I": 0.23,
"L": 0.62, "K": 0.65, "M": 0.5, "F": 0.41, "P": 0.4, "S": 0.35, "T": 0.11, "W": 0.45, "Y": 0.17, "V": 0.14}
return table[oneLetterCode]
def helical_term(oa, k_helical=4.184, inMembrane=False, forceGroup=29):
# without density dependency.
# without z dependency for now.
k_helical *= oa.k_awsem
sigma_NO = 0.068
sigma_HO = 0.076
r_ON = 0.298
r_OH = 0.206
theta_ij = f"exp(-(r_Oi_Nip4-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oi_Hip4-{r_OH})^2/(2*{sigma_HO}^2))"
helical = CustomCompoundBondForce(3, f"-{k_helical}*(fa_i+fa_ip4)*{theta_ij};\
r_Oi_Nip4=distance(p1,p2);r_Oi_Hip4=distance(p1,p3);")
helical.addPerBondParameter("fa_i")
helical.addPerBondParameter("fa_ip4")
for i in range(oa.nres):
# if not isChainEnd(i, oa.chain_ends, n=4) and oa.res_type[i+4] == "IPR":
# print(oa.o[i], oa.n[i+4], oa.h[i+4])
if not isChainEnd(i, oa.chain_ends, n=4) and oa.res_type[i+4] != "IPR":
fa_i = get_helical_f(oa.seq[i], inMembrane=inMembrane)
fa_ip4 = get_helical_f(oa.seq[i+4], inMembrane=inMembrane)
helical.addBond([oa.o[i], oa.n[i+4], oa.h[i+4]], [fa_i, fa_ip4])
helical.setForceGroup(forceGroup)
return helical
def z_dependent_helical_term(oa, k_helical=4.184, membrane_center=0*angstrom, z_m=1.5, forceGroup=29):
# without density dependency.
k_helical *= oa.k_awsem
sigma_NO = 0.068
sigma_HO = 0.076
r_ON = 0.298
r_OH = 0.206
eta_switching = 10
membrane_center = membrane_center.value_in_unit(nanometer) # convert to nm
alpha_membrane = f"0.5*tanh({eta_switching}*((z4-{membrane_center})+{z_m}))+0.5*tanh({eta_switching}*({z_m}-(z4-{membrane_center})))"
theta_ij = f"exp(-(r_Oi_Nip4-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oi_Hip4-{r_OH})^2/(2*{sigma_HO}^2))"
helical = CustomCompoundBondForce(4, f"-{k_helical}*{theta_ij}*((fa_i+fa_ip4)*(1-alpha_membrane)+(fa_i_membrane+fa_ip4_membrane)*(alpha_membrane));\
alpha_membrane={alpha_membrane};\
r_Oi_Nip4=distance(p1,p2);r_Oi_Hip4=distance(p1,p3);")
helical.addPerBondParameter("fa_i")
helical.addPerBondParameter("fa_ip4")
helical.addPerBondParameter("fa_i_membrane")
helical.addPerBondParameter("fa_ip4_membrane")
for i in range(oa.nres):
# if not isChainEnd(i, oa.chain_ends, n=4) and oa.res_type[i+4] == "IPR":
# print(oa.o[i], oa.n[i+4], oa.h[i+4])
if not isChainEnd(i, oa.chain_ends, n=4) and oa.res_type[i+4] != "IPR":
fa_i = get_helical_f(oa.seq[i], inMembrane=False)
fa_ip4 = get_helical_f(oa.seq[i+4], inMembrane=False)
fa_i_membrane = get_helical_f(oa.seq[i], inMembrane=True)
fa_ip4_membrane = get_helical_f(oa.seq[i+4], inMembrane=True)
helical.addBond([oa.o[i], oa.n[i+4], oa.h[i+4], oa.ca[i]], [fa_i, fa_ip4, fa_i_membrane, fa_ip4_membrane])
helical.setForceGroup(forceGroup)
return helical
# def pap_term_1(oa, k_pap=4.184, dis_i_to_i4=-1):
# print("pap_1 term ON")
# nres, ca = oa.nres, oa.ca
# # r0 = 2.0 # nm
# r0 = 0.8 # nm
# eta_pap = 70 # nm^-1
# gamma_aph = 1.0
# gamma_ap = 0.4
# gamma_p = 0.4
# gamma_1 = np.zeros((nres, nres))
# gamma_2 = np.zeros((nres, nres))
# for i in range(nres):
# for j in range(nres):
# resId1 = i
# chain1 = inWhichChain(resId1, oa.chain_ends)
# resId2 = j
# chain2 = inWhichChain(resId2, oa.chain_ends)
# gamma_1[i][j] = get_pap_gamma_APH(i, j, chain1, chain2, gamma_aph)
# gamma_2[i][j] = get_pap_gamma_AP(i, j, chain1, chain2, gamma_ap)
# pap_function = f"-{k_pap}*(gamma_1(donor_idx,acceptor_idx)+gamma_2(donor_idx,acceptor_idx))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a1,d1))))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a2,d2))))"
# # pap_function = f"-{k_pap}*(gamma_1(donor_idx,acceptor_idx))\
# # *0.5*(1+tanh({eta_pap}*({r0}-distance(a1,d1))))\
# # *0.5*(1+tanh({eta_pap}*({r0}-distance(a2,d2))))"
# # pap_function = f"-{k_pap}*distance(a1,d1)"
# pap = CustomHbondForce(pap_function)
# pap.addPerDonorParameter("donor_idx")
# pap.addPerAcceptorParameter("acceptor_idx")
# pap.addTabulatedFunction("gamma_1", Discrete2DFunction(nres, nres, gamma_1.T.flatten()))
# pap.addTabulatedFunction("gamma_2", Discrete2DFunction(nres, nres, gamma_2.T.flatten()))
# # print(ca)
# # count = 0;
# i = 0
# # pap.addAcceptor(ca[0], ca[4], -1, [0])
# # pap.addAcceptor(ca[20], ca[8], -1, [4])
# # pap.addDonor(ca[20], ca[0], -1, [4])
# for i in range(nres):
# if not isChainEnd(i, oa.chain_ends, n=4):
# pap.addAcceptor(ca[i], ca[i+4], -1, [i])
# if i > 13 and not isChainStart(i, oa.chain_starts, n=4):
# pap.addDonor(oa.n[i], oa.n[i-4], -1, [i])
# pap.setNonbondedMethod(CustomHbondForce.CutoffNonPeriodic)
# pap.setCutoffDistance(1.0)
# # print(count)
# pap.setForceGroup(26)
# return pap
# def pap_term_1(oa, k_pap=4.184):
# print("pap_1 term ON")
# nres, ca = oa.nres, oa.ca
# # r0 = 2.0 # nm
# r0 = 0.8 # nm
# eta_pap = 70 # nm^-1
# gamma_aph = 1.0
# gamma_ap = 0.4
# gamma_p = 0.4
# gamma_1 = np.zeros((nres, nres))
# gamma_2 = np.zeros((nres, nres))
# for i in range(nres):
# for j in range(nres):
# resId1 = i
# chain1 = inWhichChain(resId1, oa.chain_ends)
# resId2 = j
# chain2 = inWhichChain(resId2, oa.chain_ends)
# gamma_1[i][j] = get_pap_gamma_APH(i, j, chain1, chain2, gamma_aph)
# gamma_2[i][j] = get_pap_gamma_AP(i, j, chain1, chain2, gamma_ap)
# pap_function = f"-{k_pap}*(gamma_1(donor_idx,acceptor_idx)+gamma_2(donor_idx,acceptor_idx))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a1,d1))))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a2,d2))))"
# pap_function = f"-{k_pap}*(gamma_1(donor_idx,acceptor_idx))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a1,d1))))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a2,d2))))"
# pap_function = f"-{k_pap}*distance(a1,d1)"
# pap = CustomHbondForce(pap_function)
# pap.addPerDonorParameter("donor_idx")
# pap.addPerAcceptorParameter("acceptor_idx")
# pap.addTabulatedFunction("gamma_1", Discrete2DFunction(nres, nres, gamma_1.T.flatten()))
# pap.addTabulatedFunction("gamma_2", Discrete2DFunction(nres, nres, gamma_2.T.flatten()))
# # print(ca)
# # count = 0;
# i = 0
# # pap.addAcceptor(ca[0], ca[4], -1, [0])
# # pap.addAcceptor(ca[20], ca[8], -1, [4])
# # pap.addDonor(ca[20], ca[0], -1, [4])
# for i in range(nres):
# if not isChainEnd(i, oa.chain_ends, n=4):
# pap.addAcceptor(ca[i], ca[i+4], -1, [i])
# if i > 13 and not isChainStart(i, oa.chain_starts, n=4):
# pap.addDonor(ca[i], ca[i-4], -1, [i])
# pap.setNonbondedMethod(CustomHbondForce.CutoffNonPeriodic)
# pap.setCutoffDistance(1.0)
# # print(count)
# pap.setForceGroup(26)
# return pap
def beta_term_1_old(oa, k_beta=4.184, debug=False, forceGroup=23):
print("beta_1 term ON")
nres, n, h, ca, o, res_type = oa.nres, oa.n, oa.h, oa.ca, oa.o, oa.res_type
# print(lambda_1)
r_ON = .298
sigma_NO = .068
r_OH = .206
sigma_HO = .076
eta_beta_1 = 10.0
eta_beta_2 = 5.0
# r_HB_c = 0.4
r_HB_c = 1.2
theta_ij = f"exp(-(r_Oi_Nj-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oi_Hj-{r_OH})^2/(2*{sigma_HO}^2))"
# theta_ji = f"exp(-(r_Oj_Ni-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oj_Hi-{r_OH})^2/(2*{sigma_HO}^2))"
# theta_jip2 = "exp(-(r_Oj_Nip2-r_ON)^2/(2*sigma_NO^2)-(r_Oj_Hip2-r_OH)^2/(2*sigma_HO^2))"
nu_i = f"0.5*(1+tanh({eta_beta_1}*(r_CAim2_CAip2-{r_HB_c})))"
nu_j = f"0.5*(1+tanh({eta_beta_2}*(r_CAjm2_CAjp2-{r_HB_c})))"
# Oi Nj Hj CAi-2 CAi+2 CAj-2 CAj+2
# 1 2 3 4 5 6 7
beta_string_1 = f"-k_beta*lambda_1*theta_ij*nu_i*nu_j;theta_ij={theta_ij};r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
nu_i={nu_i};nu_j={nu_j};r_CAim2_CAip2=distance(p4,p5);r_CAjm2_CAjp2=distance(p6,p7)"
# # below used for debug, set, vi vj = 0
if debug:
beta_string_1 = f"-k_beta*lambda_1*theta_ij*nu_i*nu_j;theta_ij={theta_ij};r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
nu_i=1+0*{nu_i};nu_j=1+0*{nu_j};r_CAim2_CAip2=distance(p4,p5);r_CAjm2_CAjp2=distance(p6,p7)"
# beta_string_1 = f"-k_beta*lambda_1"
# beta_string_1 = f"-k_beta"
beta_1 = CustomCompoundBondForce(7, beta_string_1)
# beta_2 = CustomCompoundBondForce(10, beta_string_2)
# beta_3 = CustomCompoundBondForce(10, beta_string_3)
# add parameters to force
beta_1.addGlobalParameter("k_beta", k_beta)
beta_1.addPerBondParameter("lambda_1")
# beta_2.addTabulatedFunction("lambda_2", Discrete2DFunction(nres, nres, lambda_2))
# beta_3.addTabulatedFunction("lambda_3", Discrete2DFunction(nres, nres, lambda_3))
for i in range(nres):
for j in range(nres):
if isChainEdge(i, oa.chain_starts, oa.chain_ends, n=2) or \
isChainEdge(j, oa.chain_starts, oa.chain_ends, n=2):
continue
if not res_type[j] == "IPR":
beta_1.addBond([o[i], n[j], h[j], ca[i-2], ca[i+2], ca[j-2], ca[j+2]], [get_lambda_by_index(i, j, 0)])
#if not res_type[i] == "IPR" and not res_type[j] == "IPR":
# beta_2.addBond([o[i], n[j], h[j], o[j], n[i], h[i], ca[i-2], ca[i+2], ca[j-2], ca[j+2]], [i, j])
#if not res_type[i+2] == "IPR" and not res_type[j] == "IPR":
# beta_3.addBond([o[i], n[j], h[j], o[j], n[i+2], h[i+2], ca[i-2], ca[i+2], ca[j-2], ca[j+2]], [i, j])
# beta_1.setForceGroup(23)
#beta_2.setForceGroup(24)
#beta_3.setForceGroup(25)
beta_1.setForceGroup(forceGroup)
return beta_1
def beta_term_2_old(oa, k_beta=4.184, debug=False, forceGroup=24):
print("beta_2 term ON");
nres, n, h, ca, o, res_type = oa.nres, oa.n, oa.h, oa.ca, oa.o, oa.res_type
# add beta potential
# setup parameters
r_ON = .298
sigma_NO = .068
r_OH = .206
sigma_HO = .076
eta_beta_1 = 10.0
eta_beta_2 = 5.0
# r_HB_c = 0.4
r_HB_c = 1.2
p_par, p_anti, p_antihb, p_antinhb, p_parhb = read_beta_parameters()
theta_ij = f"exp(-(r_Oi_Nj-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oi_Hj-{r_OH})^2/(2*{sigma_HO}^2))"
theta_ji = f"exp(-(r_Oj_Ni-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oj_Hi-{r_OH})^2/(2*{sigma_HO}^2))"
nu_i = f"0.5*(1+tanh({eta_beta_1}*(r_CAim2_CAip2-{r_HB_c})))"
nu_j = f"0.5*(1+tanh({eta_beta_2}*(r_CAjm2_CAjp2-{r_HB_c})))"
# Oi Nj Hj CAi-2 CAi+2 CAj-2 CAj+2
# 1 2 3 4 5 6 7
#beta_string_1 = "-k_beta*lambda_1(index_i,index_j)*theta_ij*nu_i*nu_j;theta_ij=%s;r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
# nu_i=%s;nu_j=%s;r_CAim2_CAip2=distance(p4,p5);r_CAjm2_CAjp2=distance(p6,p7)" % (theta_ij, nu_i, nu_j)
# Oi Nj Hj Oj Ni Hi CAi-2 CAi+2 CAj-2 CAj+2
# 1 2 3 4 5 6 7 8 9 10
beta_string_2 = f"-k_beta*lambda_2*theta_ij*theta_ji*nu_i*nu_j;\
theta_ij={theta_ij};r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
theta_ji={theta_ji};r_Oj_Ni=distance(p4,p5);r_Oj_Hi=distance(p4,p6);\
nu_i={nu_i};nu_j={nu_j};r_CAim2_CAip2=distance(p7,p8);r_CAjm2_CAjp2=distance(p9,p10)"
# # below used for debug, set, vi vj = 0
if debug:
beta_string_2 = f"-k_beta*lambda_2*theta_ij*theta_ji*nu_i*nu_j;\
theta_ij={theta_ij};r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
theta_ji={theta_ji};r_Oj_Ni=distance(p4,p5);r_Oj_Hi=distance(p4,p6);\
nu_i=1+0*{nu_i};nu_j=1+0*{nu_j};r_CAim2_CAip2=distance(p7,p8);r_CAjm2_CAjp2=distance(p9,p10)"
# Oi Nj Hj Oj Ni+2 Hi+2 CAi-2 CAi+2 CAj-2 CAj+2
# 1 2 3 4 5 6 7 8 9 10
#beta_string_3 = "-k_beta*lambda_3(index_i,index_j)*theta_ij*theta_jip2*nu_i*nu_j;\
# theta_ij=%s;r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
# theta_ji=%s;r_Oj_Ni=distance(p4,p5);r_Oj_Hi=distance(p4,p6);\
# theta_jip2=%s;r_Oj_Nip2=distance(p4,p5);r_Oj_Hip2=distance(p4,p6);\
# nu_i=%s;nu_j=%s;r_CAim2_CAip2=distance(p7,p8);r_CAjm2_CAjp2=distance(p9,p10)" % (theta_ij, theta_ji, theta_jip2, nu_i, nu_j)
#beta_1 = CustomCompoundBondForce(7, beta_string_1)
beta_2 = CustomCompoundBondForce(10, beta_string_2)
#beta_3 = CustomCompoundBondForce(10, beta_string_3)
# add parameters to force
beta_2.addGlobalParameter("k_beta", k_beta)
beta_2.addPerBondParameter("lambda_2")
# for lookup table.
a = []
for ii in range(oa.nres):
a.append(se_map_1_letter[oa.seq[ii]])
for i in range(nres):
for j in range(nres):
if isChainEdge(i, oa.chain_starts, oa.chain_ends, n=2) or \
isChainEdge(j, oa.chain_starts, oa.chain_ends, n=2):
continue
#if not res_type[j] == "IPR":
# beta_1.addBond([o[i], n[j], h[j], ca[i-2], ca[i+2], ca[j-2], ca[j+2]], [i, j])
if not res_type[i] == "IPR" and not res_type[j] == "IPR":
beta_2.addBond([o[i], n[j], h[j], o[j], n[i], h[i], ca[i-2], ca[i+2], ca[j-2], ca[j+2]], [get_Lambda_2(i, j, p_par, p_anti, p_antihb, p_antinhb, p_parhb, a)])
#if not res_type[i+2] == "IPR" and not res_type[j] == "IPR":
# beta_3.addBond([o[i], n[j], h[j], o[j], n[i+2], h[i+2], ca[i-2], ca[i+2], ca[j-2], ca[j+2]], [i, j])
#beta_1.setForceGroup(23)
beta_2.setForceGroup(forceGroup)
#beta_3.setForceGroup(25)
return beta_2
def beta_term_3_old(oa, k_beta=4.184, debug=False, forceGroup=25):
print("beta_3 term ON")
nres, n, h, ca, o, res_type = oa.nres, oa.n, oa.h, oa.ca, oa.o, oa.res_type
# add beta potential
# setup parameters
r_ON = .298
sigma_NO = .068
r_OH = .206
sigma_HO = .076
eta_beta_1 = 10.0
eta_beta_2 = 5.0
# r_HB_c = 0.4
r_HB_c = 1.2
p_par, p_anti, p_antihb, p_antinhb, p_parhb = read_beta_parameters()
theta_ij = f"exp(-(r_Oi_Nj-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oi_Hj-{r_OH})^2/(2*{sigma_HO}^2))"
theta_jip2 = f"exp(-(r_Oj_Nip2-{r_ON})^2/(2*{sigma_NO}^2)-(r_Oj_Hip2-{r_OH})^2/(2*{sigma_HO}^2))"
nu_i = f"0.5*(1+tanh({eta_beta_1}*(r_CAim2_CAip2-{r_HB_c})))"
nu_j = f"0.5*(1+tanh({eta_beta_2}*(r_CAjm2_CAjp2-{r_HB_c})))"
# Oi Nj Hj CAi-2 CAi+2 CAj-2 CAj+2
# 1 2 3 4 5 6 7
#beta_string_1 = "-k_beta*lambda_1(index_i,index_j)*theta_ij*nu_i*nu_j;theta_ij=%s;r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
# nu_i=%s;nu_j=%s;r_CAim2_CAip2=distance(p4,p5);r_CAjm2_CAjp2=distance(p6,p7)" % (theta_ij, nu_i, nu_j)
# Oi Nj Hj Oj Ni Hi CAi-2 CAi+2 CAj-2 CAj+2
# 1 2 3 4 5 6 7 8 9 10
#beta_string_2 = "-k_beta*lambda_2(index_i,index_j)*theta_ij*theta_ji*nu_i*nu_j;\
# theta_ij=%s;r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
# theta_ji=%s;r_Oj_Ni=distance(p4,p5);r_Oj_Hi=distance(p4,p6);\
# nu_i=%s;nu_j=%s;r_CAim2_CAip2=distance(p7,p8);r_CAjm2_CAjp2=distance(p9,p10)" % (theta_ij, theta_ji, nu_i, nu_j)
# Oi Nj Hj Oj Ni+2 Hi+2 CAi-2 CAi+2 CAj-2 CAj+2
# 1 2 3 4 5 6 7 8 9 10
beta_string_3 = f"-k_beta*lambda_3*theta_ij*theta_jip2*nu_i*nu_j;\
theta_ij={theta_ij};r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
theta_jip2={theta_jip2};r_Oj_Nip2=distance(p4,p5);r_Oj_Hip2=distance(p4,p6);\
nu_i={nu_i};nu_j={nu_j};r_CAim2_CAip2=distance(p7,p8);r_CAjm2_CAjp2=distance(p9,p10)"
# # below used for debug, set, vi vj = 0
if debug:
beta_string_3 = f"-k_beta*lambda_3*theta_ij*theta_jip2*nu_i*nu_j;\
theta_ij={theta_ij};r_Oi_Nj=distance(p1,p2);r_Oi_Hj=distance(p1,p3);\
theta_jip2={theta_jip2};r_Oj_Nip2=distance(p4,p5);r_Oj_Hip2=distance(p4,p6);\
nu_i=1+0*{nu_i};nu_j=1+0*{nu_j};r_CAim2_CAip2=distance(p7,p8);r_CAjm2_CAjp2=distance(p9,p10)"
beta_3 = CustomCompoundBondForce(10, beta_string_3)
# add parameters to force
beta_3.addGlobalParameter("k_beta", k_beta)
beta_3.addPerBondParameter("lambda_3")
# for lookup table.
a = []
for ii in range(oa.nres):
a.append(se_map_1_letter[oa.seq[ii]])
for i in range(nres):
for j in range(nres):
if isChainEdge(i, oa.chain_starts, oa.chain_ends, n=2) or \
isChainEdge(j, oa.chain_starts, oa.chain_ends, n=2):
continue
#if not res_type[j] == "IPR":
# beta_1.addBond([o[i], n[j], h[j], ca[i-2], ca[i+2], ca[j-2], ca[j+2]], [i, j])
#if not res_type[i] == "IPR" and not res_type[j] == "IPR":
# beta_2.addBond([o[i], n[j], h[j], o[j], n[i], h[i], ca[i-2], ca[i+2], ca[j-2], ca[j+2]], [i, j])
if not res_type[i+2] == "IPR" and not res_type[j] == "IPR":
beta_3.addBond([o[i], n[j], h[j], o[j], n[i+2], h[i+2], ca[i-2], ca[i+2], ca[j-2], ca[j+2]], [get_Lambda_3(i, j, p_par, p_anti, p_antihb, p_antinhb, p_parhb, a)])
#beta_1.setForceGroup(23)
#beta_2.setForceGroup(24)
beta_3.setForceGroup(forceGroup)
return beta_3
def pap_term_old(oa, k_pap=4.184, forceGroup=26):
print("pap term ON")
nres, ca = oa.nres, oa.ca
# r0 = 2.0 # nm
r0 = 0.8 # nm
eta_pap = 70 # nm^-1
gamma_aph = 1.0
gamma_ap = 0.4
gamma_p = 0.4
pap_function = f"-k_pap*gamma*0.5*(1+tanh({eta_pap}*({r0}-distance(p1,p2))))*0.5*(1+tanh({eta_pap}*({r0}-distance(p3,p4))))"
pap = CustomCompoundBondForce(4, pap_function)
pap.addGlobalParameter("k_pap", k_pap)
pap.addPerBondParameter("gamma")
#count = 0;
for i in range(nres):
for j in range(nres):
# anti-parallel hairpin for i from 1 to N-13 and j from i+13 to min(i+16,N)
# CAi CAj CAi+4 CAj-4
# 1 2 3 4
if i <= nres-13 and j >= i+13 and j <= min(i+16,nres):
pap.addBond([ca[i], ca[j], ca[i+4], ca[j-4]], [gamma_aph])
#count = count + 1
#print([ca[i], ca[j], ca[i+4], ca[j-4]], [gamma_aph])
# anti-parallel for i from 1 to N-17 and j from i+17 to N
# CAi CAj CAi+4 CAj-4
# 1 2 3 4
if i <= nres-17 and j >= i+17 and j <= nres:
pap.addBond([ca[i], ca[j], ca[i+4], ca[j-4]], [gamma_ap])
#count = count + 1;
#print([ca[i], ca[j], ca[i+4], ca[j-4]], [gamma_ap])
# parallel for i from 1 to N-13 and j from i+9 to N-4
# CAi CAj CAi+4 CAj+4
# 1 2 3 4
if i <= nres-13 and j >= i+9 and j < nres-4:
#print([i, j, i+4, j+4])
#print([i, j, i+4, j+4, ca[i], ca[j], ca[i+4], ca[j+4]], [gamma_p])
pap.addBond([ca[i], ca[j], ca[i+4], ca[j+4]], [gamma_p])
#count = count + 1;
# print(count)
pap.setForceGroup(forceGroup)
return pap
# def pap_term_1(oa, k_pap=4.184):
# print("pap_1 term ON")
# nres, ca = oa.nres, oa.ca
# # r0 = 2.0 # nm
# r0 = 0.8 # nm
# eta_pap = 70 # nm^-1
# gamma_aph = 1.0
# gamma_ap = 0.4
# gamma_p = 0.4
# gamma_1 = np.zeros((nres, nres))
# gamma_2 = np.zeros((nres, nres))
# for i in range(nres):
# for j in range(nres):
# resId1 = i
# chain1 = inWhichChain(resId1, oa.chain_ends)
# resId2 = j
# chain2 = inWhichChain(resId2, oa.chain_ends)
# gamma_1[i][j] = get_pap_gamma_APH(i, j, chain1, chain2, gamma_aph)
# gamma_2[i][j] = get_pap_gamma_AP(i, j, chain1, chain2, gamma_ap)
# pap_function = f"-{k_pap}*(gamma_1(donor_idx,acceptor_idx)+gamma_2(donor_idx,acceptor_idx))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a1,d1))))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a2,d2))))"
# pap_function = f"-{k_pap}*(gamma_1(donor_idx,acceptor_idx))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a1,d1))))\
# *0.5*(1+tanh({eta_pap}*({r0}-distance(a2,d2))))"
# pap_function = f"-{k_pap}*distance(a1,d1)"
# pap = CustomHbondForce(pap_function)
# pap.addPerDonorParameter("donor_idx")
# pap.addPerAcceptorParameter("acceptor_idx")
# pap.addTabulatedFunction("gamma_1", Discrete2DFunction(nres, nres, gamma_1.T.flatten()))
# pap.addTabulatedFunction("gamma_2", Discrete2DFunction(nres, nres, gamma_2.T.flatten()))
# # print(ca)
# # count = 0;
# i = 0
# # pap.addAcceptor(ca[0], ca[4], -1, [0])
# # pap.addAcceptor(ca[20], ca[8], -1, [4])
# # pap.addDonor(ca[20], ca[0], -1, [4])
# for i in range(nres):
# if not isChainEnd(i, oa.chain_ends, n=4):
# pap.addAcceptor(ca[i], ca[i+4], -1, [i])
# if i > 13 and not isChainStart(i, oa.chain_starts, n=4):
# pap.addDonor(ca[i], ca[i-4], -1, [i])
# pap.setNonbondedMethod(CustomHbondForce.CutoffNonPeriodic)
# pap.setCutoffDistance(1.0)
# # print(count)
# pap.setForceGroup(26)
# return pap
'''
# old way of getting lambda
def lambda_coefficient(oa, i, j, lambda_index):
p_par, p_anti, p_antihb, p_antinhb, p_parhb = read_beta_parameters()
parameter_i = []
# print(i,j,lambda_index)
for ii in range(oa.nres):
# print(oa.seq[i])
parameter_i.append(se_map_1_letter[oa.seq[ii]])
# print(p_antihb[parameter_i[i], parameter_i[j]][0],p_antinhb[parameter_i[i+1],parameter_i[j-1]][0],p_anti[parameter_i[i]], p_anti[parameter_i[j]])
lambda_2_extra_terms = -0.5*oa.alpha_coefficient(parameter_i[i],parameter_i[j],1)*p_antihb[parameter_i[i], parameter_i[j]][0]-0.25*oa.alpha_coefficient(parameter_i[i], parameter_i[j], 2)*(p_antinhb[parameter_i[i+1],parameter_i[j-1]][0] + p_antinhb[parameter_i[i-1],parameter_i[j+1]][0])-oa.alpha_coefficient(parameter_i[i], parameter_i[j], 3)*(p_anti[parameter_i[i]]+p_anti[parameter_i[j]])
lambda_3_extra_terms = -oa.alpha_coefficient(parameter_i[i],parameter_i[j], 4)*p_parhb[parameter_i[i+1],parameter_i[j]][0]-oa.alpha_coefficient(parameter_i[i],parameter_i[j],5)*p_par[parameter_i[i+1]]+oa.alpha_coefficient(parameter_i[i],parameter_i[j],4)*p_par[parameter_i[j]]
if abs(j-i) >= 4 and abs(j-i) < 18:
if lambda_index == 1:
return 1.37
elif lambda_index == 2:
return 3.89+lambda_2_extra_terms
elif lambda_index == 3:
return 0.0+lambda_3_extra_terms
elif abs(j-i) >= 18 and abs(j-i) < 45:
if lambda_index == 1:
return 1.36
elif lambda_index == 2:
return 3.50+lambda_2_extra_terms
elif lambda_index == 3:
return 3.47+lambda_3_extra_terms
elif abs(j-i) >= 45:
if lambda_index == 1:
return 1.17
elif lambda_index == 2:
return 3.52+lambda_2_extra_terms
elif lambda_index == 3:
return 3.62+lambda_3_extra_terms
elif abs(j-i) < 4:
return 0.0
def alpha_coefficient(oa, i,j, alpha_index):
if abs(j-i) >= 4 and abs(j-i) < 18:
if alpha_index == 1:
return 1.3
if alpha_index == 2:
return 1.32
if alpha_index == 3:
return 1.22
if alpha_index == 4:
return 0.0
if alpha_index == 5:
return 0.0
elif abs(j-i) >= 18 and abs(j-i) < 45:
if alpha_index == 1:
return 1.3
if alpha_index == 2:
return 1.32
if alpha_index == 3:
return 1.22
if alpha_index == 4:
return 0.33
if alpha_index == 5:
return 1.01
elif abs(j-i) >= 45:
if alpha_index == 1:
return 1.3
if alpha_index == 2:
return 1.32
if alpha_index == 3:
return 1.22
if alpha_index == 4:
return 0.33
if alpha_index == 5:
return 1.01
elif abs(j-i) <4:
return 0.0
'''
| 42.640274 | 394 | 0.586048 | 7,517 | 43,621 | 3.182254 | 0.048557 | 0.006271 | 0.016095 | 0.013795 | 0.86585 | 0.836754 | 0.807491 | 0.788429 | 0.771958 | 0.735337 | 0 | 0.065908 | 0.244859 | 43,621 | 1,022 | 395 | 42.681996 | 0.660291 | 0.331927 | 0 | 0.571713 | 0 | 0.045817 | 0.090388 | 0.068101 | 0 | 0 | 0 | 0 | 0 | 1 | 0.049801 | false | 0.001992 | 0.007968 | 0.001992 | 0.125498 | 0.023904 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
231bbb886d5c4ee6267c7ef6df918799ab2d4fe2 | 38,217 | py | Python | qcfoptions/bsoptions.py | austingriffith94/qcfoptions | 163bd16af0bbbb84dc20f25fb95680431c1dfe2c | [
"MIT"
] | null | null | null | qcfoptions/bsoptions.py | austingriffith94/qcfoptions | 163bd16af0bbbb84dc20f25fb95680431c1dfe2c | [
"MIT"
] | 1 | 2020-05-17T13:45:02.000Z | 2020-05-17T13:45:02.000Z | qcfoptions/bsoptions.py | austingriffith94/qcfoptions | 163bd16af0bbbb84dc20f25fb95680431c1dfe2c | [
"MIT"
] | 1 | 2020-04-28T15:26:11.000Z | 2020-04-28T15:26:11.000Z | '''
Austin Griffith
bsoptions.py
Provides an analytical solution to options via the Black Scholes methodology.
'''
import numpy as np
from scipy.stats import norm
class EuroOptions:
'''
The Black Scholes value of a European Call / Put option
Payoffs are of the form :
C = max(S - K, 0)
P = max(K - S, 0)
The delta value of a European Call / Put option measures sensitivity
of option value with respect to change in underlying asset price,
calculated from the derivative dV/dS
Deltas are of the form :
C = e**-qT N(d1)
P = -e**-qT N(-d1)
The gamma value of a European option measures sensitivity of option
delta with respect to change in underlying asset price,
calculated from the derivative d2C/dS2
Gamma is of the form :
G = e**(-qT) N'(d1) / S vol sqrt(T)
The rho value of a European Call / Put option measures sensitivity
of option value with respect to change in interest rate over the life
of the option, calculated from derivative dV/dr
Rhos are of the form :
C = e**-rT K T N(d2)
P = -e**-rT K T N(-d2)
The theta value of a European Call / Put option, measures sensitivity
of option value with respect to change in time,
calculated from derivative dV/dT
The vega value of a European Call / Put option measures sensitivity
of option value with respect to change in underlying asset volatility,
calculated from derivative dV/dσ
Vega is of the form :
V = S e**(-qT) N'(d1) sqrt(T)
Parameters
----------
spot : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying s
Spot value of underlying asset at current time, t
strike : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying k
Strike value of option, determined at initiation
riskfree : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying r
Risk free interest rate, implied constant till expiration
tau : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying T
Time till expiration for option
vol : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying vol
Volatility of underlying, implied constant till expiration in Black
Scholes model
div : number of any type (int, float8, float64 etc.) or numpy array of any type
should the user wish to have a list of values output with varying q
Continuous dividend payout, as a percentage
Notes
-----
All parameters can be individual values.
Only one of these parameters can be a numpy.array, otherwise there will be
a dimension mismatch.
'''
def __init__(self, spot, strike, riskfree, tau, vol, div):
self.s = spot
self.k = strike
self.r = riskfree
self.T = tau
self.vol = self.vol
self.q = div
self.d1, self.d2 = self._euroD()
self.optionleg, self.strikeleg = self._euroParity()
def EuroPrice(self):
'''
Returns
-------
[call,put] : list of pair of float or numpy.array values
Euro call and put prices, type depends on input value.
If all input values are individual numbers, then output will be float.
If one input value is numpy.array, then output will be numpy.array.
'''
call = max(self._euroPriceCall(), 0)
put = max(self._euroPricePut(), 0)
return([call,put])
def EuroCall(self):
'''
Returns
-------
data : dictionary float or numpy.array values
Euro call price and greeks, labeled according to the respective value.
If all input values are individual numbers, then output will be float.
If one input value is numpy.array, then output will be numpy.array.
'''
price = max(self._euroPriceCall(), 0)
delta = self._euroDeltaCall()
gamma = self._euroGamma()
vega = self._euroVega()
theta = self._euroThetaCall()
rho = self._euroRhoCall()
eur = [price, delta, gamma, vega, theta, rho]
label = ['price','delta','gamma','vega','theta','rho']
data = dict(zip(label, eur))
return(data)
def EuroPut(self):
'''
Returns
-------
data : dictionary float or numpy.array values
Euro put price and greeks, labeled according to the respective value.
If all input values are individual numbers, then output will be float.
If one input value is numpy.array, then output will be numpy.array.
'''
price = max(self._euroPricePut(), 0)
delta = self._euroDeltaPut()
gamma = self._euroGamma()
vega = self._euroVega()
theta = self._euroThetaPut()
rho = self._euroRhoPut()
eur = [price, delta, gamma, vega, theta, rho]
label = ['price','delta','gamma','vega','theta','rho']
data = dict(zip(label, eur))
return(data)
def _euroRhoCall(self):
r = self.strikeleg*self.T*norm.cdf(self.d2)
return(r)
def _euroRhoPut(self):
r = -1*self.strikeleg*self.T*norm.cdf(-1*self.d2)
return(r)
def _euroThetaCall(self):
t = self._euroDerivTheta() - self.strikeleg*norm.cdf(self.d2) + \
self.optionleg*norm.cdf(self.d1)
return(t)
def _euroThetaPut(self):
t = self._euroDerivTheta() + self.strikeleg*norm.cdf(-1*self.d2) - \
self.optionleg*norm.cdf(-1*self.d1)
return(t)
def _euroDerivTheta(self):
dt = -0.5*np.exp(-1*self.q*self.T)*norm.pdf(self.d1)*self.s*self.vol / np.sqrt(self.T)
return(dt)
def _euroPriceCall(self):
p = self.strikeleg*norm.cdf(-1*self.d2) - self.optionleg*norm.cdf(-1*self.d1)
return(p)
def _euroPricePut(self):
p = self.optionleg*norm.cdf(self.d1) - self.strikeleg*norm.cdf(self.d2)
return(p)
def _euroD(self):
d1 = (np.log(self.s / self.k) + \
(self.r - self.q + 0.5*self.vol*self.vol)*self.T) / self.vol*np.sqrt(self.T)
d2 = d1 - self.vol*np.sqrt(self.T)
return(d1, d2)
def _euroParity(self):
o_leg = np.exp(-1*self.q*self.T)*self.s
k_leg = np.exp(-1*self.r*self.T)*self.k
return(o_leg, k_leg)
def _euroGamma(self):
g = np.exp(-1*self.q*self.T)*norm.pdf(self.d1) / (self.s*self.vol*np.sqrt(self.T))
return(g)
def _euroVega(self):
v = self.s*np.exp(-1*self.q*self.T)*norm.pdf(self.d1)*np.sqrt(self.T)
return(v)
def _euroDeltaCall(self):
ed = np.exp(-1*self.q*self.T)*norm.cdf(self.d1)
return(ed)
def _euroDeltaPut(self):
ed = -1*np.exp(-1*self.q*self.T)*norm.cdf(-1*self.d1)
return(ed)
class ExoticOptions:
@staticmethod
def AsianGeometric(s, k, r, T, vol, q):
'''
Calculate the Black Scholes value of Geometric Average Asian Call / Put
option with a fixed strike
Payoffs are of the form :
C = max(AVG_geo - K, 0)
P = max(K - AVG_geo, 0)
Parameters
----------
s : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying s
Spot value of underlying asset at current time, t
k : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying k
Strike value of option, determined at initiation
r : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying r
Risk free interest rate, implied constant till expiration
T : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying T
Time till expiration for option
vol : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying vol
Volatility of underlying, implied constant till expiration in Black
Scholes model
q : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying q
Continuous dividend payout, as a percentage
Notes
-----
All parameters can be individual values.
Only one of these parameters can be a numpy.array, otherwise there will be
a dimension mismatch.
Returns
-------
[call,put] : list of pair of float or numpy.array values
Asian call and put values, type depends on input value.
If all input values are individual numbers, then output will be float.
If one input value is numpy.array, then output will be numpy.array.
'''
a = 0.5*(r - q - vol*vol/6)
volG = vol/np.sqrt(3)
d1 = (np.log(s/k) + (a + 0.5*volG*volG)*T) / (volG*np.sqrt(T))
d2 = d1 - volG*np.sqrt(T)
option = s*np.exp((a - r)*T)
strike = k*np.exp(-r*T)
put = max(strike*norm.cdf(-d2) - option*norm.cdf(-d1), 0)
call = max(option*norm.cdf(d1) - strike*norm.cdf(d2), 0)
return([call,put])
@staticmethod
def AsianArithmetic(s, k, r, T, vol, q):
'''
Calculate the Black Scholes value of Arithmetic Average Asian Call / Put
option with a fixed strike
Payoffs are of the form :
C = max(AVG_arithmetic - K, 0)
P = max(K - AVG_arithmetic, 0)
Parameters
----------
s : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying s
Spot value of underlying asset at current time, t
k : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying k
Strike value of option, determined at initiation
r : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying r
Risk free interest rate, implied constant till expiration
T : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying T
Time till expiration for option
vol : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying vol
Volatility of underlying, implied constant till expiration in Black
Scholes model
q : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying q
Continuous dividend payout, as a percentage
Notes
-----
All parameters can be individual values.
Only one of these parameters can be a numpy.array, otherwise there will be
a dimension mismatch.
* want r > q, else the natural logarithm has a chance of breaking
Returns
-------
[call,put] : list of pair of float or numpy.array values
Asian call and put values, type depends on input value.
If all input values are individual numbers, then output will be float.
If one input value is numpy.array, then output will be numpy.array.
'''
m1 = s*(np.exp((r - q)*T) - 1) / ((r - q)*T)
m2l = 2*s*s*np.exp((2*r - 2*q + vol*vol)*T) / ((r - q +vol*vol)*T*T*(2*r - 2*q + vol*vol))
m2r = (2*s*s / ((r-q)*T*T))*((1/(2*(r-q) + vol*vol)) -
np.exp((r-q)*T)/(r - q - vol*vol))
m2 = m2l + m2r
volA = np.sqrt(np.log(m2/(m1*m1)) / T)
d1 = (np.log(m1/k) + 0.5*volA*volA*T) / (volA*np.sqrt(T))
d2 = d1 - volA*np.sqrt(T)
call = np.exp(-r*T)*(m1*norm.cdf(d1) - k*norm.cdf(d2))
put = np.exp(-r*T)*(k*norm.cdf(-d2) - m1*norm.cdf(-d1))
return([call,put])
@staticmethod
def Power(s, k, r, T, vol, q, n):
'''
Calculate the Black Scholes value of a traditional Power Call / Put option
with a fixed strike
Payoffs are of the form :
C = max(S**n - K, 0)
P = max(K - S**n, 0)
Parameters
----------
s : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying s
Spot value of underlying asset at current time, t
k : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying k
Strike value of option, determined at initiation
r : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying r
Risk free interest rate, implied constant till expiration
T : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying T
Time till expiration for option
vol : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying vol
Volatility of underlying, implied constant till expiration in Black
Scholes model
q : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying q
Continuous dividend payout, as a percentage
n : number of any type (int, float8, float64 etc.)
Power to which the underlying spot is raised at payoff
Notes
-----
All parameters can be individual values.
Only one of these parameters can be a numpy.array (not including 'n'),
otherwise there will be a dimension mismatch.
Returns
-------
[call,put] : list of pair of float or numpy.array values
Power call and put values, type depends on input value.
If all input values are individual numbers, then output will be float.
If one input value, other than 'n', is numpy.array, then output
will be numpy.array.
'''
d1 = (np.log(s/np.power(k,1/n)) + (r - q + vol*vol*(n - 0.5))*T) / (vol*np.sqrt(T))
d2 = d1 - n*vol*np.sqrt(T)
option = np.exp(T*(n-1)*(r + 0.5*n*vol*vol))*np.power(s,n)
strike = k*np.exp(-r*T)
put = strike*norm.cdf(-d2) - option*norm.cdf(-d1)
call = option*norm.cdf(d1) - strike*norm.cdf(d2)
return([call,put])
@staticmethod
def PowerStrike(s, k, r, T, vol, q, n):
'''
Calculate the Black Scholes value of Power Call / Put option with a
fixed strike to the power n
Payoffs are of the form :
C = max(S**n - K**n, 0)
P = max(K**n - S**n, 0)
Parameters
----------
s : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying s
Spot value of underlying asset at current time, t
k : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying k
Strike value of option, determined at initiation
r : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying r
Risk free interest rate, implied constant till expiration
T : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying T
Time till expiration for option
vol : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying vol
Volatility of underlying, implied constant till expiration in Black
Scholes model
q : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying q
Continuous dividend payout, as a percentage
n : number of any type (int, float8, float64 etc.)
Power to which the underlying spot is raised at payoff
Notes
-----
All parameters can be individual values.
Only one of these parameters can be a numpy.array (not including 'n'),
otherwise there will be a dimension mismatch.
Returns
-------
[call,put] : list of pair of float or numpy.array values
Power call and put values, type depends on input value.
If all input values are individual numbers, then output will be float.
If one input value, other than 'n', is numpy.array, then output
will be numpy.array.
'''
d1 = (np.log(s/np.power(k,1/n)) + (r - q + vol*vol*(n - 0.5))*T) / (vol*np.sqrt(T))
d2 = d1 - n*vol*np.sqrt(T)
option = np.exp(T*(n-1)*(r + 0.5*n*vol*vol))*np.power(s,n)
strike = np.power(k,n)*np.exp(-r*T)
put = strike*norm.cdf(-d2) - option*norm.cdf(-d1)
call = option*norm.cdf(d1) - strike*norm.cdf(d2)
return([call,put])
@staticmethod
def Margrabe(s, s2, T, vol, vol2, q, q2, corr):
'''
Calculate the Black Scholes value of the Margrabe Option
Payoff is of the form :
O = max(S_1 - S_2, 0)
Parameters
----------
s1 and s2 : number of any type (int, float8, float64 etc.), numpy array of
any type should the user wish to have a list of values output with
varying s
Spot value of underlying assets 1 and 2 at current time, t
T : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying T
Time till expiration for option
vol1 and vol2 : number of any type (int, float8, float64 etc.), numpy array
of any type should the user wish to have a list of values output with
varying vol
Volatility of underlying for assets 1 and 2, implied constant till
expiration in Black Scholes model
q1 and q2 : number of any type (int, float8, float64 etc.), numpy array of
any type should the user wish to have a list of values output with
varying q
Continuous dividend payout for assets 1 and 2, as a percentage
corr : number of any type (int, float8, float64 etc.), numpy array of any
type should the user wish to have a list of values output with varying
corr
Correlation between the motion of the underlying (relationship between
the Weiner process of asset 1 and 2)
Notes
-----
All parameters can be individual values.
At most, only one pair of these parameters can be a numpy.array,
otherwise there will be a dimension mismatch.
Returns
-------
price : float or numpy.array value
Margrabe price, type depends on input value.
If all input values are individual numbers, then output will be float.
If one pair of input values are a numpy.array,
then output will be numpy.array.
'''
volMix = np.sqrt(vol*vol + vol2*vol2 - vol*vol2*corr)
d1 = (np.log(s/s2) + (q2 - q + 0.5*(volMix**2))*T) / (volMix*np.sqrt(T))
d2 = d1 - volMix*np.sqrt(T)
option = np.exp(-q*T)*s*norm.cdf(d1)
option2 = np.exp(-q2*T)*s2*norm.cdf(d2)
price = option - option2
return(price)
@staticmethod
def Lookback(s, M, r, T, vol, q):
'''
Calculate the Black Scholes value of floating strike
Lookback Call / Put option
Payoffs are of the form :
C = S_T - min(m,m_T)
P = max(M,M_T) - S_T
where 'm' is the current minimum, or starting strike at initiation, and
'm_T' is the minimum over the remaining life of the option
similarly, 'M' is the current maximum, or starting strike at initiation, and
'M_T' is the maximum over the remaining life of the option
Parameters
----------
s : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying s
Spot value of underlying asset at current time, t
M : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying k
Strike value of option, determined by minimum value of underlying
over the life of the option
r : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying r
Risk free interest rate, implied constant till expiration
T : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying T
Time till expiration for option
vol : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying vol
Volatility of underlying, implied constant till expiration in Black
Scholes model
q : number of any type (int, float8, float64 etc.), numpy array of any type
should the user wish to have a list of values output with varying q
Continuous dividend payout, as a percentage
Notes
-----
All parameters can be individual values.
Only one of these parameters can be a numpy.array, otherwise there will be
a dimension mismatch.
Returns
-------
[call,put] : list of pair of float or numpy.array values
Lookback call and put values, type depends on input value.
If all input values are individual numbers, then output will be float.
If one input value is numpy.array, then output will be numpy.array.
'''
B = 2*(r - q) / (vol*vol)
x = (np.log(s/M) + (r - q - 0.5*vol*vol)*T) / (vol*np.sqrt(T))
y = (-np.log(s/M) - (r - q + 0.5*vol*vol)*T) / (vol*np.sqrt(T))
option = s*np.exp(-q*T)
minimum = M*np.exp(-r*T)
left = np.exp(-r*T)*np.power(s/M,-B)
right = np.exp(-q*T)
call = (option*norm.cdf(x + vol*np.sqrt(T)) -
minimum*norm.cdf(x) +
(s/B)*(left*norm.cdf(y + B*vol*np.sqrt(T)) -
right*norm.cdf(y)))
put = (-option*norm.cdf(-x - vol*np.sqrt(T)) +
minimum*norm.cdf(-x) -
(s/B)*(left*norm.cdf(-y - B*vol*np.sqrt(T)) -
right*norm.cdf(-y)))
return([call,put])
class BarrierOptions:
'''
Provides an analytical solution to barrier options using
the Black Scholes methodology. Due to the underlying calculus'
assumptions, the risk-free rate and implied volatility of the
underlying are held constant from t0 to t1.
f(u) : the density function of the natural logarithm of
the risk-neutral underlying asset return
g(u) : the density function of the natural logarithm of
the risk-neutral underlying asset return when the
underlying asset price starts above/below the barrier
crosses the barrier but ends up above/below the barrier
at expiration
The _I functions are set values used as the analytical
solution to the barrier options. Since a barrier option
is marked by a set of logic conditions being met, these
can be manipulated via an alpha and beta scalar to account
for each barrier option's requirements. Each barrier is
a linear combination of this set of analytical solutions.
I1 - I2 : call payoff integrated over f(u) between the
strike and barrier
I1 - I3 : call payoff integrated over the probability density
of the terminal asset price conditional on NOT crossing
the barrier
I2 - I4 :
I3 : call payoff integrated over g(u) conditional on crossing
the barrier
I4 : call payoff integrated over the density function of
the natural logarithm under risk-neutral assumptions
between the barrier and infinity
I5 : rebate for "In" options
I6 : reabte for "Out" options
Parameters
----------
spot : number of any type (int, float8, float64 etc.)
Spot value of underlying asset at current time, t
strike : number of any type (int, float8, float64 etc.)
Strike value of option, determined at initiation
riskfree : number of any type (int, float8, float64 etc.)
Risk free interest rate, implied constant till expiration
barrier : number of any type (int, float8, float64 etc.)
Barrier value of option, determined at initiation
tau : number of any type (int, float8, float64 etc.)
Time till expiration for option, can be interpreted as 'T - t' should
the option already be initiated, and be 't' time from time = 0
vol : number of any type (int, float8, float64 etc.)
Volatility of underlying, implied constant till expiration in Black
Scholes model
div : number of any type (int, float8, float64 etc.)
Continuous dividend payout, as a percentage
rebate : number of any type (int, float8, float64 etc.)
Rebate of barrier option, if there is no rebate provision, set = 0
Default value is 0
'''
def __init__(self, spot, strike, riskfree, barrier, tau, vol, div, rebate=0):
self.s = spot
self.k = strike
self.r = riskfree
self.Z = barrier
self.T = tau
self.vol = vol
self.q = div
self.R = rebate
self.L = self._lambdaDrift()
def _lambdaDrift(self):
'''
Lambda constant calculated from the risk-netural
drift of the underlying
Returns
-------
l : float
The lambda constant used in each of barrier option
analytical solutions
'''
m = self._mu()
l = 1 + (m / (self.vol*self.vol))
return(l)
def _mu(self):
'''
The underlying's risk-netural drift term,
referred to as 'Mu'
Returns
-------
mu : float
The drift term used in the barrier option
analytical solutions
'''
mu = (self.r - self.q - self.vol*self.vol*0.5)
return(mu)
def _x1val(self):
x = np.log(self.s / self.Z) / (self.vol*np.sqrt(self.T)) + self.L*self.vol*np.sqrt(self.T)
return(x)
def _xval(self):
x = np.log(self.s / self.k) / (self.vol*np.sqrt(self.T)) + self.L*self.vol*np.sqrt(self.T)
return(x)
def _y1val(self):
y = np.log(self.Z / self.s) / (self.vol*np.sqrt(self.T)) + self.L*self.vol*np.sqrt(self.T)
return(y)
def _yval(self):
y = np.log(np.square(self.Z) / (self.s*self.k)) / (self.vol*np.sqrt(self.T)) + self.L*self.vol*np.sqrt(self.T)
return(y)
def _zval(self):
z = np.log(self.Z / self.s) / (self.vol*np.sqrt(self.T)) + self._bval()*self.vol*np.sqrt(self.T)
return(z)
def _aval(self):
a = self._mu() / (self.vol*self.vol)
return(a)
def _bval(self):
b = np.sqrt(self._mu()**2 + 2*self.r*self.vol*self.vol) / (self.vol*self.vol)
return(b)
def _I1(self, alpha : int, beta : int):
'''
Parameters
----------
alpha : int
Scalar to represent either a call or put
beta : int
Scalar to represent whether the asset price
starts above or below the barrier
Returns
-------
partial : float
The I1 partial analytical solution for the barrier option
'''
xval = self._xval()
partial = alpha*self.s*norm.cdf(alpha*xval) - alpha*self.k*np.exp(-1*self.r*self.T)*norm.cdf(alpha*xval - alpha*self.vol*np.sqrt(self.T))
return(partial)
def _I2(self, alpha : int, beta : int):
'''
Parameters
----------
alpha : int
Scalar to represent either a call or put
beta : int
Scalar to represent whether the asset price
starts above or below the barrier
Returns
-------
partial : float
The I2 partial analytical solution for the barrier option
'''
xval = self._x1val()
partial = alpha*self.s*norm.cdf(alpha*xval) - alpha*self.k*np.exp(-1*self.r*self.T)*norm.cdf(alpha*xval - alpha*self.vol*np.sqrt(self.T))
return(partial)
def _I3(self, alpha : int, beta : int):
'''
Parameters
----------
alpha : int
Scalar to represent either a call or put
beta : int
Scalar to represent whether the asset price
starts above or below the barrier
Returns
-------
partial : float
The I3 partial analytical solution for the barrier option
'''
yval = self._yval()
partial = alpha*self.s*np.power(self.Z / self.s, 2*self.L)*norm.cdf(beta*yval) - \
alpha*self.k*np.exp(-1*self.r*self.T)*np.power(self.Z / self.s, 2*self.L - 2)*norm.cdf(beta*yval - beta*self.vol*np.sqrt(self.T))
return(partial)
def _I4(self, alpha : int, beta : int):
'''
Parameters
----------
alpha : int
Scalar to represent either a call or put
beta : int
Scalar to represent whether the asset price
starts above or below the barrier
Returns
-------
partial : float
The I4 partial analytical solution for the barrier option
'''
yval = self._y1val()
partial = alpha*self.s*np.power(self.Z / self.s, 2*self.L)*norm.cdf(beta*yval) - \
alpha*self.k*np.exp(-1*self.r*self.T)*np.power(self.Z / self.s, 2*self.L - 2)*norm.cdf(beta*yval - beta*self.vol*np.sqrt(self.T))
return(partial)
def _I5(self, beta : int):
x = self._x1val()
y = self._y1val()
partial = self.R*np.exp(-1*self.r*self.T) * \
(norm.cdf(beta*x - beta*self.vol*np.sqrt(self.T)) - \
np.power(self.Z / self.s, 2*self.L - 2)*norm.cdf(beta*y - beta*self.vol*np.sqrt(self.T)))
return(partial)
def _I6(self, beta : int):
a = self._aval()
b = self._bval()
z = self._zval()
partial = self.R * (np.power(self.Z / self.s, a - b)*norm.cdf(beta*z) - \
np.power(self.Z / self.s, a - b)*norm.cdf(beta*z - 2*beta*b*self.vol*np.sqrt(self.T)))
return(partial)
def DownOutPut(self):
'''
Calculate the Down-and-Out PUT option
Returns
-------
price : float
Price value of barrier option.
'''
a = -1
b = 1
if self.k > self.Z and self.s >= self.Z:
price = self._I1(a,b) - self._I2(a,b) + self._I3(a,b) - self._I4(a,b) + self._I6(b)
elif self.k < self.Z and self.s >= self.Z:
price = self._I6(b)
else:
price = 0.0
return(max(price, 0.0))
def DownOutCall(self):
'''
Calculate the Down-and-Out CALL option, for any barrier
Returns
-------
price : float
Price value of barrier option.
'''
a = 1
b = 1
if self.k > self.Z and self.s >= self.Z:
price = self._I1(a,b) - self._I3(a,b) + self._I6(b)
elif self.k < self.Z and self.s >= self.Z:
price = self._I2(a,b) - self._I4(a,b) + self._I6(b)
else:
price = 0.0
return(max(price, 0.0))
def UpOutCall(self):
'''
Calculate the Up-and-Out CALL option
Returns
-------
price : float
Price value of barrier option.
'''
a = 1
b = -1
if self.k > self.Z and self.s <= self.Z:
price = self._I1(a,b) - self._I2(a,b) + self._I3(a,b) - self._I4(a,b) + self._I6(b)
elif self.k < self.Z and self.s <= self.Z:
price = self._I6(b)
else:
price = 0.0
return(max(price, 0.0))
def UpOutPut(self):
'''
Calculate the Up-and-Out PUT option
Returns
-------
price : float
Price value of barrier option.
'''
a = -1
b = -1
if self.k < self.Z and self.s <= self.Z:
price = self._I1(a,b) - self._I3(a,b) + self._I6(b)
elif self.k > self.Z and self.s <= self.Z:
price = self._I2(a,b) - self._I4(a,b) + self._I6(b)
else:
price = 0.0
return(max(price, 0.0))
def DownInCall(self):
'''
Calculate the Down-and-In CALL option
Returns
-------
price : float
Price value of barrier option.
'''
a = 1
b = 1
if self.k > self.Z:
price = self._I3(a,b) + self._I5(b)
elif self.k < self.Z:
price = self._I1(a,b) - self._I2(a,b) + self._I4(a,b) + self._I5(b)
else:
price = 0.0
return(max(price, 0.0))
def DownInPut(self):
'''
Calculate the Down-and-In PUT option
Returns
-------
price : float
Price value of barrier option.
'''
a = -1
b = 1
if self.k > self.Z:
price = self._I2(a,b) - self._I3(a,b) + self._I4(a,b) + self._I5(b)
elif self.k < self.Z:
price = self._I1(a,b) + self._I5(b)
else:
price = 0.0
return(max(price, 0.0))
def UpInCall(self):
'''
Calculate the Up-and-In Call option
Returns
-------
price : float
Price value of barrier option.
'''
a = 1
b = -1
if self.k > self.Z:
price = self._I1(a,b) + self._I5(b)
elif self.k < self.Z:
price = self._I2(a,b) - self._I3(a,b) + self._I4(a,b) + self._I5(b)
else:
price = 0.0
return(max(price, 0.0))
def UpInPut(self):
'''
Calculate the Up-and-In Put option
Returns
-------
price : float
Price value of barrier option.
'''
a = -1
b = -1
if self.k > self.Z:
price = self._I1(a,b) - self._I2(a,b) + self._I4(a,b) + self._I5(b)
elif self.k < self.Z:
price = self._I3(a,b) + self._I5(b)
else:
price = 0.0
return(max(price, 0.0))
if __name__ == '__main__':
opt1 = [1, 2, 0.02, 1.5, 5, 0.05, 0.01, 0.01]
bro = BarrierOptions(*opt1)
a = bro.DownInCall() | 37.541257 | 146 | 0.552712 | 5,373 | 38,217 | 3.905081 | 0.068118 | 0.021924 | 0.039462 | 0.03646 | 0.814126 | 0.786531 | 0.753265 | 0.736012 | 0.714279 | 0.692641 | 0 | 0.019966 | 0.351283 | 38,217 | 1,018 | 147 | 37.541257 | 0.826355 | 0.526101 | 0 | 0.449511 | 0 | 0 | 0.004755 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.153094 | false | 0 | 0.006515 | 0 | 0.169381 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
88ba8f9efb62a36756ea40ec7449e94a8d5e0020 | 155 | py | Python | utils/dummy_adapter.py | Atihinen/serial2sqlite | df8bbe422453d9c84d9f8cde1c424baa53d778c7 | [
"MIT"
] | null | null | null | utils/dummy_adapter.py | Atihinen/serial2sqlite | df8bbe422453d9c84d9f8cde1c424baa53d778c7 | [
"MIT"
] | null | null | null | utils/dummy_adapter.py | Atihinen/serial2sqlite | df8bbe422453d9c84d9f8cde1c424baa53d778c7 | [
"MIT"
] | null | null | null | from random import randint
class DummyAdapter(object):
def __init__(self, *args):
pass
def read_int(self):
return randint(0, 100) | 19.375 | 30 | 0.651613 | 20 | 155 | 4.8 | 0.85 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.034783 | 0.258065 | 155 | 8 | 31 | 19.375 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0.166667 | 0.166667 | 0.166667 | 0.833333 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 6 |
00178b738cd8a48248caefce2afbf3b61b27cc96 | 1,539 | py | Python | src/ethereum_test/decorators.py | lightclient/test-filler | f8b8e38c62a7682c9e08ee83cecf71d2b10fc5fc | [
"MIT"
] | null | null | null | src/ethereum_test/decorators.py | lightclient/test-filler | f8b8e38c62a7682c9e08ee83cecf71d2b10fc5fc | [
"MIT"
] | 1 | 2021-11-27T06:07:47.000Z | 2021-11-27T06:07:47.000Z | src/ethereum_test/decorators.py | lightclient/test-filler | f8b8e38c62a7682c9e08ee83cecf71d2b10fc5fc | [
"MIT"
] | null | null | null | """
Decorators for expanding filler definitions.
"""
from typing import Any, Callable, Mapping, cast
from .fill import fill_state_test
from .fork import forks_from
from .state_test import StateTest
from .types import Fixture
def test_from(
fork: str,
) -> Callable[
[Callable[[], StateTest]], Callable[[str], Mapping[str, Fixture]]
]:
"""
Decorator that takes a test generator and fills it for all forks after the
specified fork.
"""
fork = fork.capitalize()
def decorator(
fn: Callable[[], StateTest]
) -> Callable[[str], Mapping[str, Fixture]]:
def inner(engine) -> Mapping[str, Fixture]:
return fill_state_test(fn(), forks_from(fork), engine)
cast(Any, inner).__filler_metadata__ = {
"fork": fork,
"name": fn.__name__.lstrip("test_"),
}
return inner
return decorator
def test_only(
fork: str,
) -> Callable[
[Callable[[], StateTest]], Callable[[str], Mapping[str, Fixture]]
]:
"""
Decorator that takes a test generator and fills it only for the specified
fork.
"""
fork = fork.capitalize()
def decorator(
fn: Callable[[], StateTest]
) -> Callable[[str], Mapping[str, Fixture]]:
def inner(engine) -> Mapping[str, Fixture]:
return fill_state_test(fn(), [fork], engine)
cast(Any, inner).__filler_metadata__ = {
"fork": fork,
"name": fn.__name__.lstrip("test_"),
}
return inner
return decorator
| 24.046875 | 78 | 0.608187 | 174 | 1,539 | 5.201149 | 0.247126 | 0.066298 | 0.112707 | 0.123757 | 0.744751 | 0.744751 | 0.744751 | 0.744751 | 0.744751 | 0.744751 | 0 | 0 | 0.263158 | 1,539 | 63 | 79 | 24.428571 | 0.79806 | 0.139701 | 0 | 0.717949 | 0 | 0 | 0.020344 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.153846 | false | 0 | 0.128205 | 0.051282 | 0.435897 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.