hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
44a4de86e7ff78b545ac8453af5ad0882b5fb51a
61,160
cpp
C++
src/sksl/SkSLLexer.cpp
wan-nyan-wan/skia
bf2a6ff1b570821a906f11a2046215789b51d41a
[ "BSD-3-Clause" ]
null
null
null
src/sksl/SkSLLexer.cpp
wan-nyan-wan/skia
bf2a6ff1b570821a906f11a2046215789b51d41a
[ "BSD-3-Clause" ]
null
null
null
src/sksl/SkSLLexer.cpp
wan-nyan-wan/skia
bf2a6ff1b570821a906f11a2046215789b51d41a
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /***************************************************************************************** ******************** This file was generated by sksllex. Do not edit. ******************* *****************************************************************************************/ #include "src/sksl/SkSLLexer.h" namespace SkSL { using State = uint16_t; static const uint8_t INVALID_CHAR = 18; static const int8_t kMappings[127] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 4, 3, 5, 6, 7, 8, 3, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 22, 22, 23, 23, 24, 25, 26, 27, 28, 29, 30, 31, 31, 32, 33, 34, 31, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 36, 37, 35, 38, 35, 35, 39, 35, 35, 40, 3, 41, 42, 43, 3, 44, 45, 46, 47, 48, 49, 50, 51, 52, 35, 53, 54, 55, 56, 57, 58, 35, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71}; struct IndexEntry { uint16_t type : 2; uint16_t pos : 14; }; struct FullEntry { State data[72]; }; struct CompactEntry { State v0 : 6; State v1 : 9; State v2 : 9; uint8_t data[18]; }; static constexpr FullEntry kFull[] = { { 0, 2, 3, 4, 5, 7, 9, 14, 16, 19, 20, 21, 23, 26, 27, 30, 35, 41, 60, 60, 60, 60, 60, 60, 62, 63, 64, 68, 70, 74, 75, 84, 84, 84, 84, 84, 84, 84, 84, 84, 85, 86, 87, 84, 90, 100, 105, 121, 141, 153, 169, 174, 182, 84, 206, 216, 223, 249, 254, 270, 276, 348, 365, 381, 393, 84, 84, 84, 398, 399, 402, 403, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 50, 50, 50, 50, 50, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 57, 58, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57, 0, 0, 58, 0, 0, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 50, 50, 50, 50, 50, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 51, 51, 51, 51, 51, 51, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 61, 61, 61, 61, 61, 61, 61, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 57, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 106, 10, 10, 10, 10, 10, 10, 10, 10, 10, 109, 10, 10, 112, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 122, 10, 10, 10, 128, 10, 10, 10, 10, 134, 10, 10, 10, 10, 10, 138, 10, 10, 10, 10, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 142, 10, 145, 10, 10, 10, 10, 10, 10, 10, 10, 147, 10, 10, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 154, 10, 10, 10, 10, 10, 10, 10, 158, 10, 161, 10, 10, 164, 10, 10, 10, 10, 10, 166, 10, 10, 10, 10, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 185, 10, 10, 189, 192, 10, 10, 194, 10, 200, 10, 10, 10, 10, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 255, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 259, 10, 10, 266, 10, 10, 10, 10, 10, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 277, 10, 10, 10, 10, 10, 10, 10, 309, 313, 10, 10, 10, 10, 10, 10, 10, 331, 339, 10, 343, 10, 10, 10, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 283, 290, 301, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 306, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 349, 10, 10, 355, 10, 10, 10, 10, 10, 10, 10, 357, 10, 10, 10, 10, 10, 10, 360, 10, 0, 0, 0, 0, }, }; static constexpr CompactEntry kCompact[] = { {0, 0, 3, { 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 6, { 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 8, { 0, 0, 0, 0, 0, 0, 0, 192, 255, 255, 192, 255, 255, 255, 255, 255, 255, 0, }}, {0, 0, 8, { 0, 0, 0, 0, 252, 255, 0, 192, 255, 255, 192, 255, 255, 255, 255, 255, 255, 0, }}, {0, 10, 11, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 0, 10, { 0, 0, 0, 0, 252, 255, 0, 192, 255, 255, 192, 255, 255, 255, 255, 255, 255, 0, }}, {0, 10, 12, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 13, { 0, 0, 0, 0, 168, 171, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 170, 0, }}, {0, 0, 15, { 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 17, 18, { 0, 0, 2, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 22, { 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 24, 25, { 0, 0, 0, 2, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 28, 29, { 0, 0, 0, 32, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 31, { 0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 31, 32, { 0, 0, 0, 0, 168, 170, 0, 0, 48, 0, 0, 0, 3, 0, 0, 0, 0, 0, }}, {0, 33, 34, { 0, 0, 0, 34, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 34, { 0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {36, 39, 40, { 0, 0, 64, 0, 2, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 36, 37, { 168, 170, 234, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, }}, {0, 36, 38, { 168, 170, 170, 170, 171, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, }}, {0, 0, 39, { 204, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, }}, {0, 43, 47, { 0, 0, 0, 0, 168, 170, 0, 0, 48, 0, 0, 0, 3, 0, 0, 0, 0, 0, }}, {0, 43, 44, { 0, 0, 0, 0, 168, 170, 0, 0, 48, 0, 0, 0, 3, 0, 0, 0, 0, 0, }}, {0, 45, 46, { 0, 0, 0, 34, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 46, { 0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 48, 49, { 0, 0, 0, 34, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 49, { 0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 53, 54, { 0, 0, 0, 34, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 54, { 0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 59, { 0, 0, 0, 0, 252, 255, 0, 192, 63, 0, 0, 255, 15, 0, 0, 0, 0, 0, }}, {0, 57, 59, { 0, 0, 0, 0, 252, 255, 0, 192, 63, 32, 0, 255, 15, 0, 0, 32, 0, 0, }}, {0, 65, 67, { 0, 0, 0, 0, 0, 0, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 66, { 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 69, { 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 71, 72, { 0, 0, 0, 0, 0, 0, 128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 0, 73, { 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }}, {0, 76, 78, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0, }}, {0, 0, 77, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, }}, {0, 0, 79, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, }}, {0, 0, 80, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, }}, {0, 0, 81, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, }}, {0, 0, 82, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0, }}, {0, 0, 83, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, }}, {0, 88, 89, { 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0, 0, }}, {10, 91, 93, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 85, 85, 94, 85, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0, }}, {0, 10, 94, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 95, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 96, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 97, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 174, 170, 170, 170, 170, 170, 0, }}, {0, 10, 98, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 99, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 101, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 102, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 103, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 104, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 174, 170, 170, 170, 0, }}, {0, 10, 107, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {10, 92, 108, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 87, 85, 85, 89, 85, 0, }}, {0, 10, 110, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 111, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 113, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {10, 114, 116, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 85, 85, 94, 85, 0, }}, {0, 10, 115, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 117, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 118, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {0, 10, 119, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 120, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 123, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0, }}, {0, 10, 124, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 125, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 126, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 127, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 129, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 130, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 131, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 132, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 133, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0, }}, {0, 10, 135, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 136, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 174, 170, 170, 170, 170, 170, 0, }}, {0, 10, 137, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 139, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 140, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 232, 175, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 170, 0, }}, {0, 10, 143, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 144, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 146, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 148, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 149, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 150, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 151, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {0, 10, 152, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 155, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 156, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 157, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 159, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 174, 0, }}, {0, 10, 160, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0, }}, {0, 10, 162, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 163, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 165, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 167, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 168, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {10, 170, 172, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 101, 93, 85, 85, 0, }}, {0, 10, 171, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 192, 170, 170, 170, 170, 170, 170, 0, }}, {0, 0, 171, { 0, 0, 0, 0, 252, 255, 0, 192, 255, 255, 192, 255, 255, 255, 255, 255, 255, 0, }}, {0, 10, 173, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0, }}, {10, 175, 179, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 86, 85, 213, 85, 0, }}, {0, 10, 176, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 186, 170, 170, 170, 170, 0, }}, {0, 10, 177, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0, }}, {0, 10, 178, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 180, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 181, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {10, 183, 184, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 89, 85, 87, 85, 85, 0, }}, {0, 10, 186, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 187, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {0, 10, 188, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 190, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 191, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 193, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 195, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 196, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 197, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0, }}, {0, 10, 198, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 199, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 201, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 202, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 203, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 204, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 205, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {10, 207, 212, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 86, 85, 85, 93, 85, 85, 0, }}, {0, 10, 208, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 186, 0, }}, {0, 10, 209, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0, }}, {0, 10, 210, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 211, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {10, 213, 214, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 85, 86, 85, 87, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 186, 170, 170, 170, 170, 0, }}, {0, 10, 215, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 217, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 218, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0, }}, {0, 10, 219, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 220, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 221, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0, }}, {0, 10, 222, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {10, 224, 231, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 86, 85, 85, 93, 85, 85, 0, }}, {0, 10, 225, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0, }}, {0, 10, 226, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 227, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 228, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 229, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 230, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {10, 232, 238, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 86, 117, 85, 85, 0, }}, {0, 10, 233, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {0, 10, 234, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 235, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 236, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {0, 10, 237, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 239, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 240, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 241, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 242, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 243, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 244, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 245, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 246, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 247, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 234, 170, 0, }}, {0, 10, 248, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 250, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 251, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 252, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 253, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 256, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 257, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 174, 170, 170, 170, 0, }}, {0, 10, 258, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 260, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 261, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 262, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 263, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 264, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 265, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {0, 10, 267, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 174, 170, 170, 170, 170, 170, 0, }}, {0, 10, 268, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 269, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 271, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 272, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 273, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 274, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 275, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {0, 10, 278, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0, }}, {0, 10, 279, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 280, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 281, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 282, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 284, { 0, 0, 0, 0, 168, 170, 0, 128, 174, 170, 128, 170, 170, 170, 170, 170, 170, 0, }}, {0, 10, 285, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 174, 128, 170, 170, 170, 170, 170, 170, 0, }}, {0, 10, 286, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0, }}, {0, 10, 287, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 288, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0, }}, {0, 10, 289, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 171, 0, }}, {0, 10, 291, { 0, 0, 0, 0, 168, 170, 0, 128, 174, 170, 128, 170, 170, 170, 170, 170, 170, 0, }}, {10, 285, 292, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 91, 64, 85, 85, 85, 85, 85, 85, 0, }}, {0, 10, 293, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 294, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 295, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 296, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 174, 128, 170, 170, 170, 170, 170, 170, 0, }}, {0, 10, 297, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0, }}, {0, 10, 298, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 299, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0, }}, {0, 10, 300, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0, }}, {0, 10, 302, { 0, 0, 0, 0, 168, 170, 0, 128, 174, 170, 128, 170, 170, 170, 170, 170, 170, 0, }}, {0, 10, 303, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 171, 128, 170, 170, 170, 170, 170, 170, 0, }}, {0, 10, 304, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 305, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 307, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 308, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 174, 170, 170, 170, 170, 170, 0, }}, {0, 10, 310, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 234, 0, }}, {0, 10, 311, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 312, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0, }}, {0, 10, 314, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 192, 170, 170, 170, 170, 170, 170, 0, }}, {0, 10, 315, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0, }}, {0, 10, 316, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 317, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 318, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 192, 170, 170, 170, 170, 170, 170, 0, }}, {0, 10, 319, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {0, 10, 320, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 321, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0, }}, {0, 10, 322, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 323, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 192, 170, 170, 170, 170, 170, 170, 0, }}, {0, 10, 324, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 325, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0, }}, {0, 10, 326, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0, }}, {0, 10, 327, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 328, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 329, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 330, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0, }}, {10, 332, 335, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 86, 85, 85, 213, 85, 85, 0, }}, {0, 10, 333, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 334, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 336, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 337, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 338, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 340, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 341, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 342, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 92, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 344, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 345, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 346, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0, }}, {0, 10, 347, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0, }}, {0, 10, 350, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0, }}, {0, 10, 351, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 352, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 353, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 354, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 356, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 358, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0, }}, {0, 10, 359, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 361, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0, }}, {0, 10, 362, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 363, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0, }}, {0, 10, 364, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {10, 366, 378, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 85, 86, 87, 85, 0, }}, {10, 367, 373, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 86, 85, 87, 85, 0, }}, {10, 368, 372, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 89, 85, 93, 85, 85, 0, }}, {0, 10, 369, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0, }}, {0, 10, 370, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 371, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0, }}, {0, 10, 374, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 375, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 186, 170, 170, 170, 170, 0, }}, {0, 10, 376, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {0, 10, 377, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 10, 379, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 380, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {10, 382, 387, { 0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 86, 85, 85, 93, 85, 85, 0, }}, {0, 10, 383, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0, }}, {0, 10, 384, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 186, 0, }}, {0, 10, 385, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 386, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0, }}, {0, 10, 388, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 389, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0, }}, {0, 10, 390, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0, }}, {0, 10, 391, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 392, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 394, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0, }}, {0, 10, 395, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0, }}, {0, 10, 396, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0, }}, {0, 10, 397, { 0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0, }}, {0, 400, 401, { 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, }}, }; static constexpr IndexEntry kIndices[] = { {0, 0}, {1, 0}, {2, 0}, {2, 0}, {0, 0}, {2, 1}, {0, 0}, {2, 2}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 5}, {2, 8}, {0, 0}, {2, 9}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {2, 10}, {0, 0}, {2, 11}, {0, 0}, {0, 0}, {0, 0}, {2, 12}, {0, 0}, {0, 0}, {2, 13}, {2, 14}, {2, 15}, {2, 16}, {2, 16}, {2, 17}, {2, 18}, {2, 19}, {0, 0}, {2, 20}, {0, 0}, {1, 1}, {2, 21}, {2, 22}, {2, 23}, {2, 24}, {2, 24}, {2, 25}, {2, 26}, {2, 26}, {1, 2}, {1, 3}, {2, 27}, {2, 28}, {2, 28}, {0, 0}, {0, 0}, {0, 0}, {2, 29}, {2, 30}, {1, 4}, {1, 4}, {0, 0}, {0, 0}, {2, 31}, {2, 32}, {0, 0}, {0, 0}, {2, 33}, {0, 0}, {2, 34}, {0, 0}, {2, 35}, {0, 0}, {0, 0}, {2, 36}, {2, 37}, {0, 0}, {2, 38}, {2, 39}, {2, 40}, {2, 41}, {2, 42}, {0, 0}, {2, 5}, {0, 0}, {0, 0}, {2, 43}, {0, 0}, {0, 0}, {2, 44}, {2, 45}, {2, 5}, {2, 46}, {2, 47}, {2, 48}, {2, 49}, {2, 50}, {2, 51}, {2, 52}, {2, 53}, {2, 54}, {2, 55}, {2, 56}, {2, 5}, {1, 5}, {2, 57}, {2, 58}, {2, 5}, {2, 59}, {2, 60}, {2, 61}, {2, 62}, {2, 63}, {2, 64}, {2, 5}, {2, 65}, {2, 66}, {2, 67}, {2, 68}, {2, 5}, {1, 6}, {2, 69}, {2, 70}, {2, 71}, {2, 72}, {2, 73}, {2, 5}, {2, 74}, {2, 75}, {2, 76}, {2, 77}, {2, 78}, {2, 5}, {2, 79}, {2, 80}, {2, 81}, {2, 52}, {2, 82}, {2, 83}, {2, 84}, {1, 7}, {2, 85}, {2, 86}, {2, 5}, {2, 87}, {2, 45}, {2, 88}, {2, 89}, {2, 90}, {2, 91}, {2, 92}, {2, 93}, {1, 8}, {2, 94}, {2, 95}, {2, 96}, {2, 5}, {2, 97}, {2, 98}, {2, 99}, {2, 100}, {2, 101}, {2, 5}, {2, 102}, {2, 5}, {2, 103}, {2, 104}, {2, 84}, {2, 105}, {2, 106}, {2, 107}, {2, 108}, {2, 109}, {2, 110}, {2, 111}, {2, 112}, {2, 113}, {2, 5}, {2, 114}, {2, 115}, {2, 84}, {2, 116}, {2, 5}, {1, 9}, {2, 117}, {2, 118}, {2, 119}, {2, 5}, {2, 120}, {2, 121}, {2, 5}, {2, 122}, {2, 123}, {2, 124}, {2, 125}, {2, 126}, {2, 127}, {2, 128}, {2, 52}, {2, 129}, {2, 130}, {2, 131}, {2, 132}, {2, 133}, {2, 123}, {2, 134}, {2, 135}, {2, 136}, {2, 137}, {2, 138}, {2, 5}, {2, 139}, {2, 140}, {2, 141}, {2, 5}, {2, 142}, {2, 143}, {2, 144}, {2, 145}, {2, 146}, {2, 147}, {2, 5}, {2, 148}, {2, 149}, {2, 150}, {2, 151}, {2, 152}, {2, 153}, {2, 154}, {2, 52}, {2, 155}, {2, 156}, {2, 157}, {2, 158}, {2, 159}, {2, 160}, {2, 5}, {2, 161}, {2, 162}, {2, 163}, {2, 164}, {2, 165}, {2, 166}, {2, 167}, {2, 168}, {2, 169}, {2, 170}, {2, 5}, {2, 171}, {2, 172}, {2, 173}, {2, 174}, {2, 123}, {1, 10}, {2, 175}, {2, 176}, {2, 177}, {2, 99}, {2, 178}, {2, 179}, {2, 180}, {2, 181}, {2, 182}, {2, 183}, {2, 184}, {2, 185}, {2, 186}, {2, 187}, {2, 188}, {2, 189}, {2, 190}, {2, 191}, {2, 192}, {2, 193}, {2, 5}, {1, 11}, {2, 194}, {2, 195}, {2, 196}, {2, 197}, {2, 198}, {1, 12}, {2, 199}, {2, 200}, {2, 201}, {2, 202}, {2, 203}, {2, 204}, {2, 205}, {2, 206}, {2, 207}, {2, 208}, {2, 209}, {2, 210}, {2, 211}, {2, 212}, {2, 213}, {2, 214}, {2, 215}, {2, 205}, {2, 216}, {2, 217}, {2, 218}, {2, 219}, {2, 123}, {2, 220}, {2, 221}, {2, 52}, {2, 222}, {2, 223}, {2, 224}, {2, 225}, {2, 226}, {2, 227}, {2, 228}, {2, 229}, {2, 230}, {2, 231}, {2, 232}, {2, 233}, {2, 234}, {2, 235}, {2, 236}, {2, 237}, {2, 238}, {2, 239}, {2, 240}, {2, 241}, {2, 242}, {2, 5}, {2, 243}, {2, 244}, {2, 245}, {2, 188}, {2, 246}, {2, 247}, {2, 248}, {2, 5}, {2, 249}, {2, 250}, {2, 251}, {2, 252}, {2, 253}, {2, 254}, {2, 255}, {2, 256}, {2, 5}, {1, 13}, {2, 257}, {2, 258}, {2, 259}, {2, 260}, {2, 261}, {2, 52}, {2, 262}, {2, 61}, {2, 263}, {2, 264}, {2, 5}, {2, 265}, {2, 266}, {2, 267}, {2, 268}, {2, 225}, {2, 269}, {2, 270}, {2, 271}, {2, 272}, {2, 273}, {2, 274}, {2, 5}, {2, 184}, {2, 275}, {2, 276}, {2, 277}, {2, 278}, {2, 99}, {2, 279}, {2, 280}, {2, 140}, {2, 281}, {2, 282}, {2, 283}, {2, 284}, {2, 285}, {2, 140}, {2, 286}, {2, 287}, {2, 288}, {2, 289}, {2, 290}, {2, 52}, {2, 291}, {2, 292}, {2, 293}, {2, 294}, {2, 5}, {0, 0}, {2, 295}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, }; State get_transition(int transition, int state) { IndexEntry index = kIndices[state]; if (index.type == 0) { return 0; } if (index.type == 1) { return kFull[index.pos].data[transition]; } const CompactEntry& entry = kCompact[index.pos]; int value = entry.data[transition >> 2]; value >>= 2 * (transition & 3); value &= 3; State table[] = {0, entry.v0, entry.v1, entry.v2}; return table[value]; } static const int8_t kAccepts[404] = { -1, -1, 84, 84, 87, 63, 68, 87, 38, 37, 37, 37, 37, 35, 53, 77, 58, 62, 82, 39, 40, 51, 75, 49, 47, 73, 46, 50, 48, 74, 45, 1, -1, -1, 1, 52, -1, -1, 86, 85, 76, 2, 1, 1, -1, -1, 1, -1, -1, 1, 2, 3, -1, -1, 1, 3, 2, 2, -1, 2, 2, 2, 65, 83, 70, 54, 78, 72, 66, 67, 69, 71, 55, 79, 64, 87, -1, 7, -1, -1, -1, -1, -1, 13, 37, 43, 44, 57, 81, 61, 37, 37, 36, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 16, 37, 37, 37, 14, 37, 37, 37, 37, 37, 37, 24, 37, 37, 37, 37, 17, 37, 37, 37, 37, 37, 37, 15, 37, 37, 37, 37, 37, 18, 11, 37, 37, 37, 37, 37, 37, 37, 37, 37, 8, 37, 37, 37, 37, 37, 37, 36, 37, 37, 37, 37, 37, 5, 37, 37, 37, 37, 37, 25, 37, 9, 37, 37, 37, 37, 37, 36, 37, 37, 37, 37, 37, 37, 32, 37, 37, 37, 37, 6, 20, 37, 37, 37, 27, 37, 37, 22, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 31, 37, 37, 37, 34, 37, 37, 37, 37, 37, 37, 33, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 28, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 26, 37, 37, 21, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 19, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 29, 37, 37, 37, 37, 37, 37, 37, 30, 37, 37, 37, 37, 37, 37, 37, 37, 12, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 4, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 23, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 10, 41, 56, 80, 60, 42, 59, }; Token Lexer::next() { // note that we cheat here: normally a lexer needs to worry about the case // where a token has a prefix which is not itself a valid token - for instance, // maybe we have a valid token 'while', but 'w', 'wh', etc. are not valid // tokens. Our grammar doesn't have this property, so we can simplify the logic // a bit. int32_t startOffset = fOffset; if (startOffset == (int32_t)fText.length()) { return Token(Token::Kind::TK_END_OF_FILE, startOffset, 0); } State state = 1; for (;;) { if (fOffset >= (int32_t)fText.length()) { if (kAccepts[state] == -1) { return Token(Token::Kind::TK_END_OF_FILE, startOffset, 0); } break; } uint8_t c = (uint8_t)fText[fOffset]; if (c <= 8 || c >= 127) { c = INVALID_CHAR; } State newState = get_transition(kMappings[c], state); if (!newState) { break; } state = newState; ++fOffset; } Token::Kind kind = (Token::Kind)kAccepts[state]; return Token(kind, startOffset, fOffset - startOffset); } } // namespace SkSL
29.617433
99
0.303123
wan-nyan-wan
44a5d961d22e97232f26109ab917d3badb1fa340
885
hpp
C++
externals/boost/boost/beast/http/file_body.hpp
YuukiTsuchida/v8_embeded
c6e18f4e91fcc50607f8e3edc745a3afa30b2871
[ "MIT" ]
32
2019-02-27T06:57:07.000Z
2021-08-29T10:56:19.000Z
jeff/common/include/boost/beast/http/file_body.hpp
jeffphi/advent-of-code-2018
8e54bd23ebfe42fcbede315f0ab85db903551532
[ "MIT" ]
1
2018-04-18T16:33:00.000Z
2018-04-18T16:33:00.000Z
jeff/common/include/boost/beast/http/file_body.hpp
jeffphi/advent-of-code-2018
8e54bd23ebfe42fcbede315f0ab85db903551532
[ "MIT" ]
5
2019-08-20T13:45:04.000Z
2022-03-01T18:23:49.000Z
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #ifndef BOOST_BEAST_HTTP_FILE_BODY_HPP #define BOOST_BEAST_HTTP_FILE_BODY_HPP #include <boost/beast/core/file.hpp> #include <boost/beast/http/basic_file_body.hpp> #include <boost/assert.hpp> #include <boost/optional.hpp> #include <algorithm> #include <cstdio> #include <cstdint> #include <utility> namespace boost { namespace beast { namespace http { /// A message body represented by a file on the filesystem. using file_body = basic_file_body<file>; } // http } // beast } // boost #include <boost/beast/http/impl/file_body_win32.ipp> #endif
24.583333
80
0.723164
YuukiTsuchida
44a924d90f8efaa1a45f8184676a3ef0cf65cd88
5,538
cpp
C++
Samples/SpatialSound/cpp/Scenario2_CardioidSound.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,504
2019-05-07T06:56:42.000Z
2022-03-31T19:37:59.000Z
Samples/SpatialSound/cpp/Scenario2_CardioidSound.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
314
2019-05-08T16:56:30.000Z
2022-03-21T07:13:45.000Z
Samples/SpatialSound/cpp/Scenario2_CardioidSound.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,219
2019-05-07T00:47:26.000Z
2022-03-30T21:12:31.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Scenario2_CardioidSound.xaml.h" using namespace SDKTemplate; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; Scenario2_CardioidSound::Scenario2_CardioidSound() : _rootPage(MainPage::Current) { InitializeComponent(); auto hr = _cardioidSound.Initialize(L"assets//MonoSound.wav"); if (SUCCEEDED(hr)) { _timer = ref new DispatcherTimer(); _timerEventToken = _timer->Tick += ref new EventHandler<Platform::Object^>(this, &Scenario2_CardioidSound::OnTimerTick); TimeSpan timespan; timespan.Duration = 10000 / 30; _timer->Interval = timespan; EnvironmentComboBox->SelectedIndex = static_cast<int>(_cardioidSound.GetEnvironment()); _rootPage->NotifyUser("Stopped", NotifyType::StatusMessage); } else { if (hr == E_NOTIMPL) { _rootPage->NotifyUser("HRTF API is not supported on this platform. Use X3DAudio API instead - https://code.msdn.microsoft.com/XAudio2-Win32-Samples-024b3933", NotifyType::ErrorMessage); } else { throw ref new COMException(hr); } } _initialized = SUCCEEDED(hr); } Scenario2_CardioidSound::~Scenario2_CardioidSound() { if (_timerEventToken.Value != 0) { _timer->Tick -= _timerEventToken; } } void SDKTemplate::Scenario2_CardioidSound::EnvironmentComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e) { if (_initialized) { _cardioidSound.SetEnvironment(static_cast<HrtfEnvironment>(EnvironmentComboBox->SelectedIndex)); } } void SDKTemplate::Scenario2_CardioidSound::ScalingSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { UpdateScalingAndOrder(); } void SDKTemplate::Scenario2_CardioidSound::OrderSlider_ValudChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { UpdateScalingAndOrder(); } void SDKTemplate::Scenario2_CardioidSound::YawSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _yaw = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::PitchSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _pitch = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::RollSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _roll = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::PlayButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { if (_initialized) { _cardioidSound.Start(); _state = PlayState::Playing; _rootPage->NotifyUser("Playing", NotifyType::StatusMessage); } } void SDKTemplate::Scenario2_CardioidSound::StopButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { if (_initialized) { _cardioidSound.Stop(); _state = PlayState::Stopped; _rootPage->NotifyUser("Stopped", NotifyType::StatusMessage); } } void SDKTemplate::Scenario2_CardioidSound::OnTimerTick(Object^ sender, Object^ e) { // Update the sound position and orientation on every dispatcher timer tick. _cardioidSound.OnUpdate(_x, _y, _z, _pitch, _yaw, _roll); } void SDKTemplate::Scenario2_CardioidSound::UpdateScalingAndOrder() { if (_initialized) { _timer->Stop(); _cardioidSound.ConfigureApo(static_cast<float>(ScalingSlider->Value), static_cast<float>(OrderSlider->Value)); _timer->Start(); if (_state == PlayState::Playing) { _cardioidSound.Start(); } } } void SDKTemplate::Scenario2_CardioidSound::SourcePositionX_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _x = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::SourcePositionY_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _y = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::SourcePositionZ_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _z = static_cast<float>(e->NewValue); }
35.5
198
0.693933
dujianxin
44aa3fbd0c080d40d8dbf27fabe522e18fa6f5f3
4,499
cpp
C++
tools/map_maker/test_helper/src/StringTestHelper.cpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
61
2019-12-19T20:57:24.000Z
2022-03-29T15:20:51.000Z
tools/map_maker/test_helper/src/StringTestHelper.cpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
54
2020-04-05T05:32:47.000Z
2022-03-15T18:42:33.000Z
tools/map_maker/test_helper/src/StringTestHelper.cpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
31
2019-12-20T07:37:39.000Z
2022-03-16T13:06:16.000Z
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2017-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #include "ad/map/maker/test_helper/StringTestHelper.hpp" #include <stdio.h> namespace ad { namespace map { namespace maker { namespace test_helper { static bool useColorForComparison{false}; /* the color mode has to be set at least once * Either this was done by user-code (which called setColorMode) * or from testStringAndPrintDifference */ static bool colorModeInitiallySet{false}; static void setInitialColorMode() { if (!colorModeInitiallySet) { setColorMode(ColorMode::On); } } static void adustColorModeForConsole() { if (useColorForComparison) { const char *term = getenv("TERM"); if (term) { // if it starts with 'xterm' we assume that is supports color if ((term[0] == 'x') && (term[1] == 't') && (term[2] == 'e') && (term[3] == 'r') && (term[4] == 'm')) { return; } } // turn off coloring if the console doesn't support this useColorForComparison = false; } } void setColorMode(ColorMode mode) { colorModeInitiallySet = true; useColorForComparison = (mode == ColorMode::On); adustColorModeForConsole(); } void turnColorOn(const char *const color) { if (useColorForComparison) { printf("%s", color); // turn color on } } void turnColorOff() { if (useColorForComparison) { printf("\x1b[0m"); // turn to normal } } size_t getMaxLengthOfStrings(std::string const &s1, std::string const &s2) { size_t len = s1.length(); if (s2.length() < len) { len = s2.length(); } return len; } void printDifferenceOfString(std::string const &toPrint, std::string const &toCompare, const char *const color, size_t const len) { for (size_t i = 0; i < len; i++) { if (toPrint[i] != toCompare[i]) { turnColorOn(color); } printf("%c", toPrint[i]); if (toPrint[i] != toCompare[i]) { turnColorOff(); } } } void printStringDifferences(std::string const &expected, std::string const &actual) { const size_t len = getMaxLengthOfStrings(expected, actual); if (expected == actual) { return; } if (len > 0) { printf("Expected:\n"); printDifferenceOfString(expected, actual, "\x1b[32m", len); printf("\nActual:\n"); printDifferenceOfString(actual, expected, "\x1b[31m", len); } else { printf("Either exected (size: %lu) or actual (size: %lu) is empty\n", expected.size(), actual.size()); } } // make this a macro similar to gtest ASSERT_STREQ, maybe ASSERT_STREQ_PRINT_DIFF bool testStringAndPrintDifference(std::string const &expected, std::string const &actual) { if (expected != actual) { setInitialColorMode(); printStringDifferences(expected, actual); // print missing parts if strings have different sizes if (expected.length() != actual.length()) { if (expected.size() > actual.size()) { printf("\nMissing part from expected:\n"); turnColorOn("\x1b[32m"); if (actual.size() > 0) { printf("%s", &expected.c_str()[actual.size()]); } else { printf("%s", expected.c_str()); } turnColorOff(); } else { printf("\nAdditional part from actual:\n"); turnColorOn("\x1b[31m"); if (expected.size() > 0) { printf("%s", &actual.c_str()[expected.size()]); } else { printf("%s", actual.c_str()); } turnColorOff(); } printf("\n"); } return false; } return true; } bool readFile(char const *fileName, std::string &fileContent) { FILE *input = fopen(fileName, "r"); if (input == nullptr) { return false; } if (fseek(input, 0, SEEK_END) != 0) { return false; } size_t fileSize = static_cast<size_t>(ftell(input)); rewind(input); char *content = new char[fileSize + 1]; size_t readCount = fread(content, sizeof(char), fileSize, input); if (readCount != fileSize) { delete[] content; content = nullptr; return false; } content[fileSize] = 0; fileContent.assign(content); return true; } } // namespace test_helper } // namespace maker } // namespace map } // namespace ad
22.053922
107
0.58613
seowwj
44aa9cf1340691f42635075713e82bcfdb942e00
1,003
hpp
C++
Engine/Graphics/FontHandler.hpp
artur-kink/nhns
bc1ccef4e4a9cba9047051d73202ee2b1482066f
[ "Apache-2.0" ]
null
null
null
Engine/Graphics/FontHandler.hpp
artur-kink/nhns
bc1ccef4e4a9cba9047051d73202ee2b1482066f
[ "Apache-2.0" ]
null
null
null
Engine/Graphics/FontHandler.hpp
artur-kink/nhns
bc1ccef4e4a9cba9047051d73202ee2b1482066f
[ "Apache-2.0" ]
null
null
null
#ifndef _FONTHANDLER_ #define _FONTHANDLER_ #include <cstring> #include "Types.hpp" #include "Color.hpp" #include "BaseRenderTarget.hpp" #include "Utilities/FileHandler.hpp" #ifdef _PC_ #include <SFML/Graphics.hpp> #endif /** * Class used to draw fonts. * The FontHandler is designed to use only one font, * if more fonts are needed then separate FontHandlers * should be initialized. */ class FontHandler{ private: /** Name of font. */ char fontName[25]; /** Is the font loaded and ready to use. */ bool initialized; /** Size of font. */ byte fontSize; /** Font color. */ Color color; public: #ifdef _PC_ /** SFML Font implementation. */ sf::Font font; #endif FontHandler(); bool loadFont(const char* name); unsigned short getStringWidth(const char* str); void setFontSize(byte size); void setFontColor(Color color); #ifdef _PC_ void drawString(sf::RenderTarget& dst, RenderObject& obj, const char* str); #endif }; #endif
18.924528
79
0.678963
artur-kink
44ade3c2f3c34f4e78555be6d489cf5c3df1bf46
866
hpp
C++
libs/boost_1_72_0/boost/type_erasure/config.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/type_erasure/config.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/type_erasure/config.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
// Boost.TypeErasure library // // Copyright 2011 Steven Watanabe // // Distributed under the Boost Software License Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // $Id$ #ifndef BOOST_TYPE_ERASURE_CONFIG_HPP_INCLUDED #define BOOST_TYPE_ERASURE_CONFIG_HPP_INCLUDED #ifndef BOOST_TYPE_ERASURE_MAX_FUNCTIONS /** The maximum number of functions that an @ref boost::type_erasure::any "any" * can have. */ #define BOOST_TYPE_ERASURE_MAX_FUNCTIONS 50 #endif #ifndef BOOST_TYPE_ERASURE_MAX_ARITY /** The maximum number of arguments that functions in the library support. */ #define BOOST_TYPE_ERASURE_MAX_ARITY 5 #endif #ifndef BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE /** The maximum number of elements in a @ref boost::type_erasure::tuple "tuple". */ #define BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE 5 #endif #endif
28.866667
80
0.794457
henrywarhurst
44ae27d2b61165557a78299577983cafe1c8bf5b
2,339
cpp
C++
server/src/session.cpp
silverthreadk/Mafia2
275f7e9fb63a98bcb5781c4d388a63da16a63213
[ "BSL-1.0" ]
null
null
null
server/src/session.cpp
silverthreadk/Mafia2
275f7e9fb63a98bcb5781c4d388a63da16a63213
[ "BSL-1.0" ]
null
null
null
server/src/session.cpp
silverthreadk/Mafia2
275f7e9fb63a98bcb5781c4d388a63da16a63213
[ "BSL-1.0" ]
null
null
null
#include "session.h" #include <memory> #include <boost/lexical_cast.hpp> #include "room.h" #include "player.h" #include "request_handler.h" Session::Session(boost::asio::ip::tcp::socket socket, const Room& room) : socket_(std::move(socket)), room_(const_cast<Room&>(room)), player_(std::make_shared<Player>(*this, room_, boost::lexical_cast<std::string>(socket_.remote_endpoint()))) { } void Session::start() { room_.join(shared_from_this()); do_read_header(); } void Session::deliver(const Message& msg) { bool write_in_progress = !write_msgs_.empty(); write_msgs_.push_back(msg); if (!write_in_progress) { do_write(); } } void Session::do_read_header() { auto self(shared_from_this()); boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.data(), Message::kHeaderLength), [this, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec && read_msg_.decode_header()) { do_read_body(); } else { if (room_.exist(shared_from_this())) { player_->leave(); room_.leave(shared_from_this()); } } }); } void Session::do_read_body() { auto self(shared_from_this()); boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.body(), read_msg_.body_length()), [this, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { RequestHandler::handleRequest(read_msg_, player_); do_read_header(); } else { if (room_.exist(shared_from_this())) { player_->leave(); room_.leave(shared_from_this()); } } }); } void Session::do_write() { auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(write_msgs_.front().data(), write_msgs_.front().length()), [this, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { write_msgs_.pop_front(); if (!write_msgs_.empty()) { do_write(); } } else { if (room_.exist(shared_from_this())) { player_->leave(); room_.leave(shared_from_this()); } } }); }
28.52439
114
0.567336
silverthreadk
44af582b4fe1df8f558f26ca56c19b8527c8a82f
9,382
cpp
C++
fourr_kazerounian_controller/src/fourr_kazerounian_controller.cpp
unisa-acg/moveit_dp_redundancy_resolution
37f2f7bd3d786bc7d5ce0dde9d69772cd65b041e
[ "BSD-3-Clause" ]
3
2020-12-31T02:46:15.000Z
2021-05-31T12:05:58.000Z
fourr_kazerounian_controller/src/fourr_kazerounian_controller.cpp
unisa-acg/moveit_dp_redundancy_resolution
37f2f7bd3d786bc7d5ce0dde9d69772cd65b041e
[ "BSD-3-Clause" ]
null
null
null
fourr_kazerounian_controller/src/fourr_kazerounian_controller.cpp
unisa-acg/moveit_dp_redundancy_resolution
37f2f7bd3d786bc7d5ce0dde9d69772cd65b041e
[ "BSD-3-Clause" ]
2
2020-11-14T11:33:13.000Z
2021-08-12T05:36:53.000Z
/********************************************************************************* * Copyright (c) 2018, Università degli Studi di Salerno, ALTEC S.p.A. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *********************************************************************************/ /* ------------------------------------------------------------------- * * This module has been developed as part of a collaboration between * the Automatic Control Group @ UNISA and ALTEC. * * Title: fourr_kazerounian_controller.cpp * Author: Enrico Ferrentino * Org.: UNISA - Automatic Control Group * Date: Jul 16, 2018 * * This file implements a ROS node to control the 4R planar * manipulator first proposed by Kazerounian & Wang, whose * configuration is included in the ROS module * fourr_kazerounian_moveit_config. It follows the model of the * move_group_interface_tutorial. * * ------------------------------------------------------------------- */ #include <ros/ros.h> #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <moveit/move_group_interface/move_group_interface.h> #include <moveit_msgs/DisplayRobotState.h> #include <moveit_msgs/DisplayTrajectory.h> #include <moveit_visual_tools/moveit_visual_tools.h> #include <geometry_msgs/Pose.h> #include <moveit_dp_redundancy_resolution/workspace_trajectory.h> #include <moveit_dp_redundancy_resolution/dp_redundancy_resolution_capability.h> int main(int argc, char** argv) { // Initializing the node and the move_grou interface ros::init(argc, argv, "fourr_kazerounian_controller"); ros::NodeHandle node_handle; /* * The async spinner spawns a new thread in charge of calling callbacks * when needed. Uncomment the lines below if, as instance, you need to * ask for the robot state and expect an answer before the time expires. */ ros::AsyncSpinner spinner(1); spinner.start(); static const std::string PLANNING_GROUP = "fourr_planar_arm"; static const std::string NON_REDUNDANT_PLANNING_GROUP = "q2_q3_q4"; moveit::planning_interface::MoveGroupInterface move_group(PLANNING_GROUP); const robot_state::JointModelGroup* joint_model_group = move_group.getCurrentState()->getJointModelGroup(PLANNING_GROUP); ROS_INFO_NAMED("main", "Reference frame: %s", move_group.getPlanningFrame().c_str()); ROS_INFO_NAMED("main", "End effector link: %s", move_group.getEndEffectorLink().c_str()); // Loading the trajectory from the Parameter Server and creating a WorkspaceTrajectory object std::string trajectory_name; std::vector<double> time; std::vector<double> x; std::vector<double> y; std::vector<double> z; std::vector<double> roll; std::vector<double> pitch; std::vector<double> yaw; node_handle.getParam("/trajectory/name", trajectory_name); node_handle.getParam("/trajectory/time", time); node_handle.getParam("/trajectory/x", x); node_handle.getParam("/trajectory/y", y); node_handle.getParam("/trajectory/z", z); node_handle.getParam("/trajectory/roll", roll); node_handle.getParam("/trajectory/pitch", pitch); node_handle.getParam("/trajectory/yaw", yaw); moveit_dp_redundancy_resolution::WorkspaceTrajectory ws_trajectory(trajectory_name, time, x, y, z, roll, pitch, yaw); ROS_INFO_NAMED("main", "WorkspaceTrajectory object created with %lu waypoints", time.size()); namespace rvt = rviz_visual_tools; moveit_visual_tools::MoveItVisualTools visual_tools("base_link"); visual_tools.deleteAllMarkers(); visual_tools.loadRemoteControl(); visual_tools.publishPath(ws_trajectory.getWaypoints(), rvt::LIME_GREEN, rvt::SMALL); visual_tools.trigger(); //visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to start planning"); // Planning with dynamic programming redundancy resolution ros::ServiceClient dp_redundancy_resolution_service = node_handle.serviceClient<moveit_dp_redundancy_resolution_msgs::GetOptimizedJointsTrajectory>(move_group::DP_REDUNDANCY_RESOLUTION_SERVICE_NAME); moveit_dp_redundancy_resolution_msgs::GetOptimizedJointsTrajectoryRequest req; moveit_dp_redundancy_resolution_msgs::GetOptimizedJointsTrajectoryResponse res; moveit_dp_redundancy_resolution_msgs::WorkspaceTrajectory ws_trajectory_msg; ws_trajectory.getWorkspaceTrajectoryMsg(ws_trajectory_msg); req.ws_trajectory = ws_trajectory_msg; req.planning_group_name = PLANNING_GROUP; req.non_redundant_group_name = NON_REDUNDANT_PLANNING_GROUP; req.redundancy_parameter_samples = 1440; req.redundancy_parameters.push_back("joint1"); dp_redundancy_resolution_service.call(req, res); visual_tools.publishTrajectoryLine(res.solution, joint_model_group); visual_tools.trigger(); visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue planning"); // Planning to a pose goal /* * Uncomment these instructions to see how the KDL kinematics solver fails in * finding a solution for a < 6 DOF manipulator */ /* geometry_msgs::Pose target_pose1; target_pose1.position.x = 5; target_pose1.position.y = 5; target_pose1.position.z = 0.4; move_group.setPoseTarget(target_pose1); moveit::planning_interface::MoveGroupInterface::Plan my_plan; bool success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS); ROS_INFO_NAMED("main", "Visualizing plan 1 (pose goal) %s", success ? "" : "FAILED"); ROS_INFO_NAMED("main", "Visualizing plan 1 as trajectory line"); visual_tools.publishAxisLabeled(target_pose1, "pose1"); visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); visual_tools.trigger(); visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue planning"); */ // Planning to a joint space goal moveit::core::RobotStatePtr current_state = move_group.getCurrentState(); std::vector<double> joint_group_positions; current_state->copyJointGroupPositions(joint_model_group, joint_group_positions); joint_group_positions[0] = -1.0; // radians move_group.setJointValueTarget(joint_group_positions); moveit::planning_interface::MoveGroupInterface::Plan my_plan; bool success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS); ROS_INFO_NAMED("main", "Visualizing plan 2 (joint space goal) %s", success ? "" : "FAILED"); visual_tools.deleteAllMarkers(); visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); visual_tools.trigger(); visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue planning"); // Planning a joint space path starting from workspace waypoints robot_state::RobotState start_state(*move_group.getCurrentState()); geometry_msgs::Pose start_pose = ws_trajectory.getWaypoints()[0]; start_state.setFromIK(joint_model_group, start_pose); move_group.setStartState(start_state); moveit_msgs::RobotTrajectory trajectory; const double jump_threshold = 0; const double eef_step = 0.01; double fraction = move_group.computeCartesianPath(ws_trajectory.getWaypoints(), eef_step, jump_threshold, trajectory, false); ROS_INFO_NAMED("main", "Visualizing plan (%.2f%% achieved)", fraction * 100.0); visual_tools.deleteAllMarkers(); visual_tools.publishPath(ws_trajectory.getWaypoints(), rvt::LIME_GREEN, rvt::SMALL); // for (std::size_t i = 0; i < time.size(); ++i) // visual_tools.publishAxisLabeled(ws_trajectory.getWaypoints()[i], "pt" + std::to_string(i), rvt::SMALL); visual_tools.publishTrajectoryLine(trajectory, joint_model_group); visual_tools.trigger(); visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to terminate the node"); ros::shutdown(); return 0; }
42.071749
155
0.734492
unisa-acg
44b1e1418cbd084a974188fe6e79ef46286dee77
5,639
cpp
C++
src/wrapper/store/storehelper.cpp
microshine/trusted-crypto
22a6496bd390ebe2ed516a15636d911fae4c6407
[ "Apache-2.0" ]
null
null
null
src/wrapper/store/storehelper.cpp
microshine/trusted-crypto
22a6496bd390ebe2ed516a15636d911fae4c6407
[ "Apache-2.0" ]
null
null
null
src/wrapper/store/storehelper.cpp
microshine/trusted-crypto
22a6496bd390ebe2ed516a15636d911fae4c6407
[ "Apache-2.0" ]
1
2020-07-01T16:32:57.000Z
2020-07-01T16:32:57.000Z
#include "../stdafx.h" #include "storehelper.h" Handle<PkiItemCollection> Provider::getProviderItemCollection(){ LOGGER_FN(); return this->providerItemCollection; } ProviderCollection::ProviderCollection(){ LOGGER_FN(); _items = std::vector<Handle<Provider> >(); } ProviderCollection::~ProviderCollection(){ LOGGER_FN(); } Handle<Provider> ProviderCollection::items(int index){ LOGGER_FN(); return _items.at(index); } int ProviderCollection::length(){ LOGGER_FN(); return _items.size(); } void ProviderCollection::push(Handle<Provider> v){ LOGGER_FN(); _items.push_back(v); } PkiItem::PkiItem(){ LOGGER_FN(); type = new std::string(""); provider = new std::string(""); category = new std::string(""); hash = new std::string(""); uri = new std::string(""); format = new std::string(""); certSubjectName = new std::string(""); certSubjectFriendlyName = new std::string(""); certIssuerName = new std::string(""); certIssuerFriendlyName = new std::string(""); certNotBefore = new std::string(""); certNotAfter = new std::string(""); certSerial = new std::string(""); certKey = new std::string(""); certOrganizationName = new std::string(""); certSignatureAlgorithm = new std::string(""); csrSubjectName = new std::string(""); csrSubjectFriendlyName = new std::string(""); csrKey = new std::string(""); crlIssuerName = new std::string(""); crlIssuerFriendlyName = new std::string(""); crlLastUpdate = new std::string(""); crlNextUpdate = new std::string(""); keyEncrypted = false; } void PkiItem::setFormat(Handle<std::string> format){ LOGGER_FN(); this->format = format; } void PkiItem::setType(Handle<std::string> type){ LOGGER_FN(); this->type = type; } void PkiItem::setProvider(Handle<std::string> provider){ LOGGER_FN(); this->provider = provider; } void PkiItem::setCategory(Handle<std::string> category){ LOGGER_FN(); this->category = category; } void PkiItem::setURI(Handle<std::string> uri){ LOGGER_FN(); this->uri = uri; } void PkiItem::setHash(Handle<std::string> hash){ LOGGER_FN(); this->hash = hash; } void PkiItem::setSubjectName(Handle<std::string> subjectName){ LOGGER_FN(); this->certSubjectName = subjectName; this->csrSubjectName = subjectName; } void PkiItem::setSubjectFriendlyName(Handle<std::string> subjectFriendlyName){ LOGGER_FN(); this->certSubjectFriendlyName = subjectFriendlyName; this->csrSubjectFriendlyName = subjectFriendlyName; } void PkiItem::setIssuerName(Handle<std::string> issuerName){ LOGGER_FN(); this->certIssuerName = issuerName; this->crlIssuerName = issuerName; } void PkiItem::setIssuerFriendlyName(Handle<std::string> issuerFriendlyName){ LOGGER_FN(); this->certIssuerFriendlyName = issuerFriendlyName; this->crlIssuerFriendlyName = issuerFriendlyName; } void PkiItem::setSerial(Handle<std::string> serial){ LOGGER_FN(); this->certSerial = serial; } void PkiItem::setNotBefore(Handle<std::string> notBefore){ LOGGER_FN(); this->certNotBefore = notBefore; } void PkiItem::setNotAfter(Handle<std::string> notAfter){ LOGGER_FN(); this->certNotAfter = notAfter; } void PkiItem::setLastUpdate(Handle<std::string> lastUpdate){ LOGGER_FN(); this->crlLastUpdate = lastUpdate; } void PkiItem::setNextUpdate(Handle<std::string> nextUpdate){ LOGGER_FN(); this->crlNextUpdate = nextUpdate; } void PkiItem::setKey(Handle<std::string> keyid){ LOGGER_FN(); this->certKey = keyid; this->csrKey = keyid; } void PkiItem::setKeyEncypted(bool enc){ LOGGER_FN(); this->keyEncrypted = enc; } void PkiItem::setOrganizationName(Handle<std::string> organizationName){ LOGGER_FN(); this->certOrganizationName = organizationName; } void PkiItem::setSignatureAlgorithm(Handle<std::string> signatureAlgorithm){ LOGGER_FN(); this->certSignatureAlgorithm = signatureAlgorithm; } PkiItemCollection::PkiItemCollection(){ LOGGER_FN(); _items = std::vector<PkiItem>(); } PkiItemCollection::~PkiItemCollection(){ LOGGER_FN(); } Handle<PkiItem> PkiItemCollection::items(int index){ LOGGER_FN(); return new PkiItem(_items.at(index)); } int PkiItemCollection::length(){ LOGGER_FN(); return _items.size(); } void PkiItemCollection::push(Handle<PkiItem> v){ LOGGER_FN(); _items.push_back((*v.operator->())); } void PkiItemCollection::push(PkiItem &v){ LOGGER_FN(); _items.push_back(v); } Filter::Filter(){ LOGGER_FN(); types = std::vector<Handle<std::string>>(); providers = std::vector<Handle<std::string>>(); categorys = std::vector<Handle<std::string>>(); isValid = true; } void Filter::setType(Handle<std::string> type){ LOGGER_FN(); this->types.push_back(type); } void Filter::setProvider(Handle<std::string> provider){ LOGGER_FN(); this->providers.push_back(provider); } void Filter::setCategory(Handle<std::string> category){ LOGGER_FN(); this->categorys.push_back(category); } void Filter::setHash(Handle<std::string> hash){ LOGGER_FN(); this->hash = hash; } void Filter::setSubjectName(Handle<std::string> subjectName){ LOGGER_FN(); this->subjectName = subjectName; } void Filter::setSubjectFriendlyName(Handle<std::string> subjectFriendlyName){ LOGGER_FN(); this->subjectFriendlyName = subjectFriendlyName; } void Filter::setIssuerName(Handle<std::string> issuerName){ LOGGER_FN(); this->issuerName = issuerName; } void Filter::setIssuerFriendlyName(Handle<std::string> issuerFriendlyName){ LOGGER_FN(); this->issuerFriendlyName = issuerFriendlyName; } void Filter::setSerial(Handle<std::string> serial){ LOGGER_FN(); this->serial = serial; } void Filter::setIsValid(bool isValid){ LOGGER_FN(); this->isValid = isValid; }
19.311644
78
0.720695
microshine
44b4580632d37867ab5ba5420a10c8d9e90df25b
851
cpp
C++
src/main.cpp
niko-niko-ni/eme
5c3718731464f67a3a03efe7d6012375701c4538
[ "MIT" ]
3
2020-08-11T01:27:29.000Z
2021-02-10T04:31:13.000Z
src/main.cpp
niko-niko-ni/eme
5c3718731464f67a3a03efe7d6012375701c4538
[ "MIT" ]
null
null
null
src/main.cpp
niko-niko-ni/eme
5c3718731464f67a3a03efe7d6012375701c4538
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> #include "types.h" #include "symbol.h" #include "token.h" #include "lexer.h" #include "statement_parser.h" #include "ast.h" #include "ast_parser.h" int main() { try { printf("main block started. moving on to lexing...\n"); Token_Linked_List tokens = lex_file((char*)"./examples/basicstatements.eme"); printf("lexer finished. moving on to declaring list of statements...\n"); Token_Linked_List statements; printf("list of statements declared. Moving on to parsing statements...\n"); parse_statements(&statements, tokens); printf("parsed statements. printing tokens..."); print_all_tokens_after(*statements.first); Ast_Node *root = parse_statements_to_ast(statements); print_node(*root); } catch(const std::exception& e) { printf("Error: %s\n", e.what()); } }
27.451613
81
0.692127
niko-niko-ni
44bdf92af8f76917c2ef37bba53a3803c61dddf6
22,099
cc
C++
src/lib/process/tests/d_cfg_mgr_unittests.cc
gumingpo/kea-latest
ca64954cd71dd544e7c92a0aa366dfc0f79d4ce1
[ "Apache-2.0" ]
1
2017-08-24T19:55:21.000Z
2017-08-24T19:55:21.000Z
src/lib/process/tests/d_cfg_mgr_unittests.cc
Acidburn0zzz/kea
3036e88d4ff730919cd7d2fb50a961a5d33bf390
[ "Apache-2.0" ]
null
null
null
src/lib/process/tests/d_cfg_mgr_unittests.cc
Acidburn0zzz/kea
3036e88d4ff730919cd7d2fb50a961a5d33bf390
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2013-2017 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <cc/command_interpreter.h> #include <config/module_spec.h> #include <exceptions/exceptions.h> #include <dhcpsrv/parsers/dhcp_parsers.h> #include <process/testutils/d_test_stubs.h> #include <process/d_cfg_mgr.h> #include <boost/foreach.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <gtest/gtest.h> #include <sstream> using namespace std; using namespace isc; using namespace isc::config; using namespace isc::process; using namespace isc::data; using namespace boost::posix_time; namespace { /// @brief Test Class for verifying that configuration context cannot be null /// during construction. class DCtorTestCfgMgr : public DCfgMgrBase { public: /// @brief Constructor - Note that is passes in an empty configuration /// pointer to the base class constructor. DCtorTestCfgMgr() : DCfgMgrBase(DCfgContextBasePtr()) { } /// @brief Destructor virtual ~DCtorTestCfgMgr() { } /// @brief Dummy implementation as this method is abstract. virtual DCfgContextBasePtr createNewContext() { return (DCfgContextBasePtr()); } /// @brief Returns summary of configuration in the textual format. virtual std::string getConfigSummary(const uint32_t) { return (""); } }; /// @brief Test fixture class for testing DCfgMgrBase class. /// It maintains an member instance of DStubCfgMgr and derives from /// ConfigParseTest fixture, thus providing methods for converting JSON /// strings to configuration element sets, checking parse results, /// accessing the configuration context and trying to unparse. class DStubCfgMgrTest : public ConfigParseTest { public: /// @brief Constructor DStubCfgMgrTest():cfg_mgr_(new DStubCfgMgr) { } /// @brief Destructor ~DStubCfgMgrTest() { } /// @brief Convenience method which returns a DStubContextPtr to the /// configuration context. /// /// @return returns a DStubContextPtr. DStubContextPtr getStubContext() { return (boost::dynamic_pointer_cast<DStubContext> (cfg_mgr_->getContext())); } /// @brief Configuration manager instance. DStubCfgMgrPtr cfg_mgr_; }; ///@brief Tests basic construction/destruction of configuration manager. /// Verifies that: /// 1. Proper construction succeeds. /// 2. Configuration context is initialized by construction. /// 3. Destruction works properly. /// 4. Construction with a null context is not allowed. TEST(DCfgMgrBase, construction) { DCfgMgrBasePtr cfg_mgr; // Verify that configuration manager constructions without error. ASSERT_NO_THROW(cfg_mgr.reset(new DStubCfgMgr())); // Verify that the context can be retrieved and is not null. DCfgContextBasePtr context = cfg_mgr->getContext(); EXPECT_TRUE(context); // Verify that the manager can be destructed without error. EXPECT_NO_THROW(cfg_mgr.reset()); // Verify that an attempt to construct a manger with a null context fails. ASSERT_THROW(DCtorTestCfgMgr(), DCfgMgrBaseError); } ///@brief Tests fundamental aspects of configuration parsing. /// Verifies that: /// 1. A correctly formed simple configuration parses without error. /// 2. An error building the element is handled. /// 3. An error committing the element is handled. /// 4. An unknown element error is handled. TEST_F(DStubCfgMgrTest, basicParseTest) { // Create a simple configuration. string config = "{ \"test-value\": [] } "; ASSERT_TRUE(fromJSON(config)); // Verify that we can parse a simple configuration. answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(0)); // Verify that we can check a simple configuration. answer_ = cfg_mgr_->parseConfig(config_set_, true); EXPECT_TRUE(checkAnswer(0)); // Verify that an unknown element error is caught and returns a failed // parse result. SimFailure::set(SimFailure::ftElementUnknown); answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(1)); // Verify that an error is caught too when the config is checked for. SimFailure::set(SimFailure::ftElementUnknown); answer_ = cfg_mgr_->parseConfig(config_set_, true); EXPECT_TRUE(checkAnswer(1)); } ///@brief Tests ordered and non-ordered element parsing /// This test verifies that: /// 1. Non-ordered parsing parses elements in the order they are presented /// by the configuration set (as-they-come). /// 2. A parse order list with too few elements is detected. /// 3. Ordered parsing parses the elements in the order specified by the /// configuration manager's parse order list. /// 4. A parse order list with too many elements is detected. TEST_F(DStubCfgMgrTest, parseOrderTest) { // Element ids used for test. std::string charlie("charlie"); std::string bravo("bravo"); std::string alpha("alpha"); std::string string_test("string_test"); std::string uint32_test("uint32_test"); std::string bool_test("bool_test"); // Create the test configuration with the elements in "random" order. // NOTE that element sets produced by isc::data::Element::fromJSON(), // are in lexical order by element_id. This means that iterating over // such an element set, will present the elements in lexical order. Should // this change, this test will need to be modified accordingly. string config = "{" " \"string_test\": \"hoopla\", " " \"bravo\": [], " " \"uint32_test\": 55, " " \"alpha\": {}, " " \"charlie\": [], " " \"bool_test\": true " "} "; ASSERT_TRUE(fromJSON(config)); // Verify that non-ordered parsing, results in an as-they-come parse order. // Create an expected parse order. // (NOTE that iterating over Element sets produced by fromJSON() will // present the elements in lexical order. Should this change, the expected // order list below would need to be changed accordingly). ElementIdList order_expected; // scalar params should be first and lexically order_expected.push_back(bool_test); order_expected.push_back(string_test); order_expected.push_back(uint32_test); // objects second and lexically order_expected.push_back(alpha); order_expected.push_back(bravo); order_expected.push_back(charlie); // Verify that the manager has an EMPTY parse order list. (Empty list // instructs the manager to parse them as-they-come.) EXPECT_EQ(0, cfg_mgr_->getParseOrder().size()); // Parse the configuration, verify it parses without error. answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(0)); // Verify that the parsed order matches what we expected. EXPECT_TRUE(cfg_mgr_->parsed_order_ == order_expected); // Clear the manager's parse order "memory". cfg_mgr_->parsed_order_.clear(); // Create a parse order list that has too few entries. Verify that // when parsing the test config, it fails. cfg_mgr_->addToParseOrder(charlie); // Verify the parse order list is the size we expect. EXPECT_EQ(1, cfg_mgr_->getParseOrder().size()); // Verify the configuration fails. answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(1)); // Verify that the configuration parses correctly, when the parse order // is correct. Add the needed entries to the parse order cfg_mgr_->addToParseOrder(bravo); cfg_mgr_->addToParseOrder(alpha); // Verify the parse order list is the size we expect. EXPECT_EQ(3, cfg_mgr_->getParseOrder().size()); // Clear the manager's parse order "memory". cfg_mgr_->parsed_order_.clear(); // Verify the configuration parses without error. answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(0)); // Build expected order // primitives should be first and lexically order_expected.clear(); order_expected.push_back(bool_test); order_expected.push_back(string_test); order_expected.push_back(uint32_test); // objects second and by the parse order order_expected.push_back(charlie); order_expected.push_back(bravo); order_expected.push_back(alpha); // Verify that the parsed order is the order we configured. EXPECT_TRUE(cfg_mgr_->parsed_order_ == order_expected); // Create a parse order list that has too many entries. Verify that // when parsing the test config, it fails. cfg_mgr_->addToParseOrder("delta"); // Verify the parse order list is the size we expect. EXPECT_EQ(4, cfg_mgr_->getParseOrder().size()); // Verify the configuration fails. answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(1)); } /// @brief Tests that element ids supported by the base class as well as those /// added by the derived class function properly. /// This test verifies that: /// 1. Boolean parameters can be parsed and retrieved. /// 2. Uint32 parameters can be parsed and retrieved. /// 3. String parameters can be parsed and retrieved. /// 4. Map elements can be parsed and retrieved. /// 5. List elements can be parsed and retrieved. /// 6. Parsing a second configuration, updates the existing context values /// correctly. TEST_F(DStubCfgMgrTest, simpleTypesTest) { // Create a configuration with all of the parameters. string config = "{ \"bool_test\": true , " " \"uint32_test\": 77 , " " \"string_test\": \"hmmm chewy\" , " " \"map_test\" : {} , " " \"list_test\": [] }"; ASSERT_TRUE(fromJSON(config)); // Verify that the configuration parses without error. answer_ = cfg_mgr_->parseConfig(config_set_, false); ASSERT_TRUE(checkAnswer(0)); DStubContextPtr context = getStubContext(); ASSERT_TRUE(context); // Verify that the boolean parameter was parsed correctly by retrieving // its value from the context. bool actual_bool = false; EXPECT_NO_THROW(context->getParam("bool_test", actual_bool)); EXPECT_EQ(true, actual_bool); // Verify that the uint32 parameter was parsed correctly by retrieving // its value from the context. uint32_t actual_uint32 = 0; EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32)); EXPECT_EQ(77, actual_uint32); // Verify that the string parameter was parsed correctly by retrieving // its value from the context. std::string actual_string = ""; EXPECT_NO_THROW(context->getParam("string_test", actual_string)); EXPECT_EQ("hmmm chewy", actual_string); isc::data::ConstElementPtr object; EXPECT_NO_THROW(context->getObjectParam("map_test", object)); EXPECT_TRUE(object); EXPECT_NO_THROW(context->getObjectParam("list_test", object)); EXPECT_TRUE(object); // Create a configuration which "updates" all of the parameter values. string config2 = "{ \"bool_test\": false , " " \"uint32_test\": 88 , " " \"string_test\": \"ewww yuk!\" , " " \"map_test2\" : {} , " " \"list_test2\": [] }"; ASSERT_TRUE(fromJSON(config2)); // Verify that the configuration parses without error. answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(0)); context = getStubContext(); ASSERT_TRUE(context); // Verify that the boolean parameter was updated correctly by retrieving // its value from the context. actual_bool = true; EXPECT_NO_THROW(context->getParam("bool_test", actual_bool)); EXPECT_FALSE(actual_bool); // Verify that the uint32 parameter was updated correctly by retrieving // its value from the context. actual_uint32 = 0; EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32)); EXPECT_EQ(88, actual_uint32); // Verify that the string parameter was updated correctly by retrieving // its value from the context. actual_string = ""; EXPECT_NO_THROW(context->getParam("string_test", actual_string)); EXPECT_EQ("ewww yuk!", actual_string); // Verify previous objects are not there. EXPECT_THROW(context->getObjectParam("map_test", object), isc::dhcp::DhcpConfigError); EXPECT_THROW(context->getObjectParam("list_test", object), isc::dhcp::DhcpConfigError); // Verify new map object is there. EXPECT_NO_THROW(context->getObjectParam("map_test2", object)); EXPECT_TRUE(object); // Verify new list object is there. EXPECT_NO_THROW(context->getObjectParam("list_test2", object)); EXPECT_TRUE(object); } /// @brief Tests that the configuration context is preserved after failure /// during parsing causes a rollback. /// 1. Verifies configuration context rollback. TEST_F(DStubCfgMgrTest, rollBackTest) { // Create a configuration with all of the parameters. string config = "{ \"bool_test\": true , " " \"uint32_test\": 77 , " " \"string_test\": \"hmmm chewy\" , " " \"map_test\" : {} , " " \"list_test\": [] }"; ASSERT_TRUE(fromJSON(config)); // Verify that the configuration parses without error. answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(0)); DStubContextPtr context = getStubContext(); ASSERT_TRUE(context); // Verify that all of parameters have the expected values. bool actual_bool = false; EXPECT_NO_THROW(context->getParam("bool_test", actual_bool)); EXPECT_EQ(true, actual_bool); uint32_t actual_uint32 = 0; EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32)); EXPECT_EQ(77, actual_uint32); std::string actual_string = ""; EXPECT_NO_THROW(context->getParam("string_test", actual_string)); EXPECT_EQ("hmmm chewy", actual_string); isc::data::ConstElementPtr object; EXPECT_NO_THROW(context->getObjectParam("map_test", object)); EXPECT_TRUE(object); EXPECT_NO_THROW(context->getObjectParam("list_test", object)); EXPECT_TRUE(object); // Create a configuration which "updates" all of the parameter values // plus one unknown at the end. string config2 = "{ \"bool_test\": false , " " \"uint32_test\": 88 , " " \"string_test\": \"ewww yuk!\" , " " \"map_test2\" : {} , " " \"list_test2\": [] , " " \"zeta_unknown\": 33 } "; ASSERT_TRUE(fromJSON(config2)); // Force a failure on the last element SimFailure::set(SimFailure::ftElementUnknown); answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(1)); context = getStubContext(); ASSERT_TRUE(context); // Verify that all of parameters have the original values. actual_bool = false; EXPECT_NO_THROW(context->getParam("bool_test", actual_bool)); EXPECT_EQ(true, actual_bool); actual_uint32 = 0; EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32)); EXPECT_EQ(77, actual_uint32); actual_string = ""; EXPECT_NO_THROW(context->getParam("string_test", actual_string)); EXPECT_EQ("hmmm chewy", actual_string); EXPECT_NO_THROW(context->getObjectParam("map_test", object)); EXPECT_TRUE(object); EXPECT_NO_THROW(context->getObjectParam("list_test", object)); EXPECT_TRUE(object); } /// @brief Tests that the configuration context is preserved during /// check only parsing. TEST_F(DStubCfgMgrTest, checkOnly) { // Create a configuration with all of the parameters. string config = "{ \"bool_test\": true , " " \"uint32_test\": 77 , " " \"string_test\": \"hmmm chewy\" , " " \"map_test\" : {} , " " \"list_test\": [] }"; ASSERT_TRUE(fromJSON(config)); // Verify that the configuration parses without error. answer_ = cfg_mgr_->parseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(0)); DStubContextPtr context = getStubContext(); ASSERT_TRUE(context); // Verify that all of parameters have the expected values. bool actual_bool = false; EXPECT_NO_THROW(context->getParam("bool_test", actual_bool)); EXPECT_EQ(true, actual_bool); uint32_t actual_uint32 = 0; EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32)); EXPECT_EQ(77, actual_uint32); std::string actual_string = ""; EXPECT_NO_THROW(context->getParam("string_test", actual_string)); EXPECT_EQ("hmmm chewy", actual_string); isc::data::ConstElementPtr object; EXPECT_NO_THROW(context->getObjectParam("map_test", object)); EXPECT_TRUE(object); EXPECT_NO_THROW(context->getObjectParam("list_test", object)); EXPECT_TRUE(object); // Create a configuration which "updates" all of the parameter values. string config2 = "{ \"bool_test\": false , " " \"uint32_test\": 88 , " " \"string_test\": \"ewww yuk!\" , " " \"map_test2\" : {} , " " \"list_test2\": [] }"; ASSERT_TRUE(fromJSON(config2)); answer_ = cfg_mgr_->parseConfig(config_set_, true); EXPECT_TRUE(checkAnswer(0)); context = getStubContext(); ASSERT_TRUE(context); // Verify that all of parameters have the original values. actual_bool = false; EXPECT_NO_THROW(context->getParam("bool_test", actual_bool)); EXPECT_EQ(true, actual_bool); actual_uint32 = 0; EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32)); EXPECT_EQ(77, actual_uint32); actual_string = ""; EXPECT_NO_THROW(context->getParam("string_test", actual_string)); EXPECT_EQ("hmmm chewy", actual_string); EXPECT_NO_THROW(context->getObjectParam("map_test", object)); EXPECT_TRUE(object); EXPECT_NO_THROW(context->getObjectParam("list_test", object)); EXPECT_TRUE(object); } // Tests that configuration element position is returned by getParam variants. TEST_F(DStubCfgMgrTest, paramPosition) { // Create a configuration with one of each scalar types. We end them // with line feeds so we can test position value. string config = "{ \"bool_test\": true , \n" " \"uint32_test\": 77 , \n" " \"string_test\": \"hmmm chewy\" }"; ASSERT_TRUE(fromJSON(config)); // Verify that the configuration parses without error. answer_ = cfg_mgr_->parseConfig(config_set_, false); ASSERT_TRUE(checkAnswer(0)); DStubContextPtr context = getStubContext(); ASSERT_TRUE(context); // Verify that the boolean parameter was parsed correctly by retrieving // its value from the context. bool actual_bool = false; isc::data::Element::Position pos; EXPECT_NO_THROW(pos = context->getParam("bool_test", actual_bool)); EXPECT_EQ(true, actual_bool); EXPECT_EQ(1, pos.line_); // Verify that the uint32 parameter was parsed correctly by retrieving // its value from the context. uint32_t actual_uint32 = 0; EXPECT_NO_THROW(pos = context->getParam("uint32_test", actual_uint32)); EXPECT_EQ(77, actual_uint32); EXPECT_EQ(2, pos.line_); // Verify that the string parameter was parsed correctly by retrieving // its value from the context. std::string actual_string = ""; EXPECT_NO_THROW(pos = context->getParam("string_test", actual_string)); EXPECT_EQ("hmmm chewy", actual_string); EXPECT_EQ(3, pos.line_); // Verify that an optional parameter that is not defined, returns the // zero position. pos = isc::data::Element::ZERO_POSITION(); EXPECT_NO_THROW(pos = context->getParam("bogus_value", actual_string, true)); EXPECT_EQ(pos.file_, isc::data::Element::ZERO_POSITION().file_); } // This tests if some aspects of simpleParseConfig are behaving properly. // Thorough testing is only possible for specific implementations. This // is done for control agent (see CtrlAgentControllerTest tests in // src/bin/agent/tests/ctrl_agent_controller_unittest.cc for example). // Also, shell tests in src/bin/agent/ctrl_agent_process_tests.sh test // the whole CA process that uses simpleParseConfig. The alternative // would be to implement whole parser that would set the context // properly. The ROI for this is not worth the effort. TEST_F(DStubCfgMgrTest, simpleParseConfig) { using namespace isc::data; // Passing just null pointer should result in error return code answer_ = cfg_mgr_->simpleParseConfig(ConstElementPtr(), false); EXPECT_TRUE(checkAnswer(1)); // Ok, now try with a dummy, but valid json code string config = "{ \"bool_test\": true , \n" " \"uint32_test\": 77 , \n" " \"string_test\": \"hmmm chewy\" }"; ASSERT_NO_THROW(fromJSON(config)); answer_ = cfg_mgr_->simpleParseConfig(config_set_, false); EXPECT_TRUE(checkAnswer(0)); } // This test checks that the post configuration callback function is // executed by the simpleParseConfig function. TEST_F(DStubCfgMgrTest, simpleParseConfigWithCallback) { string config = "{ \"bool_test\": true , \n" " \"uint32_test\": 77 , \n" " \"string_test\": \"hmmm chewy\" }"; ASSERT_NO_THROW(fromJSON(config)); answer_ = cfg_mgr_->simpleParseConfig(config_set_, false, [this]() { isc_throw(Unexpected, "unexpected configuration error"); }); EXPECT_TRUE(checkAnswer(1)); } } // end of anonymous namespace
37.90566
79
0.675234
gumingpo
44c036da3c5ac682a871fce79885115f340c6b1b
1,816
cpp
C++
src/BejeweledIO.cpp
AlexBarnes86/Jewels
0a4ec5ced01309e3a8a77f7377d84a12306b1688
[ "MIT" ]
null
null
null
src/BejeweledIO.cpp
AlexBarnes86/Jewels
0a4ec5ced01309e3a8a77f7377d84a12306b1688
[ "MIT" ]
null
null
null
src/BejeweledIO.cpp
AlexBarnes86/Jewels
0a4ec5ced01309e3a8a77f7377d84a12306b1688
[ "MIT" ]
null
null
null
#include "BejeweledIO.h" #include <stdlib.h> ScoreIO::ScoreIO() : scoreFile("HighScores.txt") { readScores(); } vector<PlayerScore> ScoreIO::readScores() { string HighScores = "HighScores.txt"; ifstream ist(HighScores.c_str()); if(!ist) cout << "High Score File Not Found!" << endl; string temp; string name; int score; int level; while(getline(ist, temp)) { istringstream strInput(temp); strInput>>name>>level>>score; PlayerScore pscore(name, level, score); scores.push_back(pscore); cout << "Score pushed back: Name: " << name << ' ' << level << ' ' << score << endl; } ist.close(); return scores; } void ScoreIO::writeScore(PlayerScore ps) { string HighScores = "HighScores.txt"; ofstream ost(HighScores.c_str()); if(!ost) cout << "High Score File Not Found!\n" << endl; bool scoreMadeIt = false; for (unsigned int i=0; i<scores.size(); i++) { int temp = scores[i].getScore(); if(!scoreMadeIt && ps.getScore()>=temp) { cout << "Writing: " << ps.getName() << " " << ps.getLevel() << " " << ps.getScore() << endl; ost << ps.getName() << " " << ps.getLevel() << " " << ps.getScore() << endl; scoreMadeIt = true; } else { cout << "Writing: " << scores[i].getName() << " " << scores[i].getLevel() << " " << scores[i].getScore() << endl; ost << scores[i].getName() << " " << scores[i].getLevel() << " " << scores[i].getScore() << endl; } } ost.close(); } string readHelpFile(string filename) { ifstream ist(filename.c_str()); if(!ist) return "Help file not found!"; string temp; string helpFile; while(getline(ist, temp)) { helpFile+=temp+'\n'; } ist.close(); return helpFile; } PlayerScore ScoreIO::getPlayer(int idx) { return scores[idx]; }
22.146341
117
0.585903
AlexBarnes86
44c1f507a48534a5fa1674dce8129005d09e86b4
11,528
cpp
C++
llc/gpk_encoding.cpp
asm128/gpk
cbd81e2de8024176eb6401746bbbfcd0b69c3e9f
[ "Apache-2.0" ]
null
null
null
llc/gpk_encoding.cpp
asm128/gpk
cbd81e2de8024176eb6401746bbbfcd0b69c3e9f
[ "Apache-2.0" ]
1
2018-06-22T00:58:58.000Z
2018-06-22T00:58:58.000Z
llc/gpk_encoding.cpp
asm128/gpk
cbd81e2de8024176eb6401746bbbfcd0b69c3e9f
[ "Apache-2.0" ]
1
2018-07-16T20:18:03.000Z
2018-07-16T20:18:03.000Z
#include "gpk_encoding.h" #include "gpk_view_bit.h" #include "gpk_noise.h" #include "gpk_chrono.h" #include "gpk_parse.h" #include <ctime> #include <random> ::gpk::error_t gpk::saltDataSalt (const ::gpk::view_const_byte& binary, ::gpk::array_pod<byte_t> & salted) { gpk_necall(salted.resize(binary.size() * 2), "%s", "Out of memory?"); byte_t * pSalted = salted.begin(); const byte_t * pBinary = binary.begin(); for(uint32_t iBinary = 0; iBinary < binary.size(); ++iBinary) { pSalted[iBinary * 2] = pBinary[iBinary]; pSalted[iBinary * 2 + 1] = (::gpk::noise1DBase(::gpk::timeCurrentInUs()) + ::gpk::timeCurrentInUs()) & 0xFF; } return 0; } ::gpk::error_t gpk::saltDataUnsalt (const ::gpk::view_const_byte& salted, ::gpk::array_pod<byte_t> & binary) { gpk_necall(binary.resize(salted.size() / 2), "%s", "Out of memory?"); const byte_t * pSalted = salted.begin(); byte_t * pBinary = binary.begin(); for(uint32_t iBinary = 0; iBinary < binary.size(); ++iBinary) pBinary[iBinary] = pSalted[iBinary * 2]; return 0; } static ::gpk::error_t hexFromByte (uint8_t i, char* hexed) { char converted [0x20] = {}; snprintf(converted, ::gpk::size(converted) - 1, "%*.2X", 2, i); hexed[0] = converted[0]; hexed[1] = converted[1]; return 0; } static ::gpk::error_t hexToByte (const char* s, uint8_t& byte) { char temp [3] = {s[0], s[1]}; gpk_necall(::gpk::parseIntegerHexadecimal(::gpk::vcs{temp}, &byte), "%s", ""); return 0; } static ::gpk::error_t hexToByte (const char* s, byte_t& byte) { char temp [3] = {s[0], s[1]}; gpk_necall(::gpk::parseIntegerHexadecimal(::gpk::vcs{temp}, &byte), "%s", ""); return 0; } ::gpk::error_t gpk::hexEncode (const ::gpk::view_array<const ubyte_t > & in_binary, ::gpk::array_pod<char_t > & out_hexed ) { uint32_t offset = out_hexed.size(); gpk_necall(out_hexed.resize(offset + in_binary.size() * 2), "%s", "Out of memory?"); byte_t * pHexed = out_hexed.begin(); const ubyte_t * pBinary = in_binary.begin(); for(uint32_t iByte = 0; iByte < in_binary.size(); ++iByte) hexFromByte(pBinary[iByte], &pHexed[offset + iByte * 2]); return 0; } ::gpk::error_t gpk::hexDecode (const ::gpk::view_array<const char_t > & in_hexed , ::gpk::array_pod<ubyte_t > & out_binary) { uint32_t offset = out_binary.size(); uint32_t binarySize = in_hexed.size() >> 1; gpk_necall(out_binary.resize(offset + binarySize), "%s", "Out of memory?"); const byte_t * pHexed = in_hexed.begin(); ubyte_t * pBinary = out_binary.begin(); for(uint32_t iByte = 0; iByte < binarySize; ++iByte) hexToByte(&pHexed[iByte * 2], pBinary[offset + iByte]); return 0; } ::gpk::error_t gpk::hexDecode (const ::gpk::view_array<const char_t > & in_hexed , ::gpk::array_pod<byte_t > & out_binary) { uint32_t offset = out_binary.size(); uint32_t binarySize = in_hexed.size() >> 1; gpk_necall(out_binary.resize(offset + binarySize), "%s", "Out of memory?"); const byte_t * pHexed = in_hexed.begin(); byte_t * pBinary = out_binary.begin(); for(uint32_t iByte = 0; iByte < binarySize; ++iByte) hexToByte(&pHexed[iByte * 2], pBinary[offset + iByte]); return 0; } ::gpk::error_t gpk::ardellEncode (::gpk::array_pod<int32_t> & cache, const ::gpk::view_array<const byte_t>& input, uint64_t key, bool salt, ::gpk::array_pod<byte_t>& output) { // Originally written by Gary Ardell as Visual Basic code. free from all copyright restrictions. char saltValue [4] = {}; if (salt) for (int32_t i = 0; i < 4; i++) { int32_t t = 100 * (1 + saltValue[i]) * rand() * (((int32_t)time(0)) + 1); saltValue[i] = t % 256; } const int32_t keyFinal[8] = { (int32_t)(11 + (key % 233)) , (int32_t)( 7 + (key % 239)) , (int32_t)( 5 + (key % 241)) , (int32_t)( 3 + (key % 251)) }; int32_t n = salt ? input.size() + 4 : input.size(); gpk_necall(cache.resize(n), "%s", "Out of memory?"); int32_t * sn = cache.begin(); if(salt) { for(int32_t i = 0; i < 2; ++i) sn[i] = saltValue[i]; for(int32_t i = 0; i < n - 4; ++i) sn[2 + i] = input[i]; for(int32_t i = 0; i < 2; ++i) sn[2 + n + i] = saltValue[2 + i]; } else for(int32_t i = 0; i < n; ++i) sn[i] = input[i]; int32_t i; for(i = 1 ; i < n; ++i) sn[i] = sn[i] ^ sn[i - 1] ^ ((keyFinal[0] * sn[i - 1]) % 256); for(i = n - 2 ; i >= 0; --i) sn[i] = sn[i] ^ sn[i + 1] ^ (keyFinal[1] * sn[i + 1]) % 256 ; for(i = 2 ; i < n; ++i) sn[i] = sn[i] ^ sn[i - 2] ^ (keyFinal[2] * sn[i - 1]) % 256 ; for(i = n - 3 ; i >= 0; --i) sn[i] = sn[i] ^ sn[i + 2] ^ (keyFinal[3] * sn[i + 1]) % 256 ; uint32_t outputOffset = output.size(); gpk_necall(output.resize(outputOffset + n), "%s", "Out of memory?"); byte_t * outputFast = output.begin(); for( i = 0; i < n; ++i) outputFast[outputOffset + i] = (char)sn[i]; return 0; } ::gpk::error_t gpk::ardellDecode (::gpk::array_pod<int32_t> & cache, const ::gpk::view_array<const byte_t>& input, uint64_t key, bool salt, ::gpk::array_pod<byte_t>& output) { // Originally written by Gary Ardell as Visual Basic code. free from all copyright restrictions. const int32_t keyFinal[8] = { (int32_t)(11 + (key % 233)) , (int32_t)( 7 + (key % 239)) , (int32_t)( 5 + (key % 241)) , (int32_t)( 3 + (key % 251)) }; int32_t n = (int32_t)input.size(); gpk_necall(cache.resize(n), "%s", "Out of memory?"); int32_t * sn = cache.begin(); int32_t i; for(i = 0 ; i < n ; ++i) sn[i] = input[i]; for(i = 0 ; i < n - 2; ++i) sn[i] = sn[i] ^ sn[i + 2] ^ (keyFinal[3] * sn[i + 1]) % 256; for(i = n - 1 ; i >= 2 ; --i) sn[i] = sn[i] ^ sn[i - 2] ^ (keyFinal[2] * sn[i - 1]) % 256; for(i = 0 ; i < n - 1; ++i) sn[i] = sn[i] ^ sn[i + 1] ^ (keyFinal[1] * sn[i + 1]) % 256; for(i = n - 1 ; i >= 1 ; --i) sn[i] = sn[i] ^ sn[i - 1] ^ (keyFinal[0] * sn[i - 1]) % 256; uint32_t outputOffset = output.size(); const uint32_t finalStringSize = salt ? n - 4 : n; const ::gpk::view_array<const int32_t> finalValues = {salt ? &sn[2] : sn, finalStringSize}; gpk_necall(output.resize(outputOffset + finalStringSize), "%s", "Out of memory?"); byte_t * outputFast = output.begin(); const int32_t * finalValuesFast = finalValues.begin(); for( i = 0; i < (int32_t)finalStringSize; ++i) outputFast[outputOffset + i] = (char)finalValuesFast[i]; return 0; } ::gpk::error_t gpk::utf8FromCodePoint (uint32_t codePoint, ::gpk::array_pod<char_t> & hexDigits) { const uint32_t offset = hexDigits.size(); if (codePoint <= 0x7f) { hexDigits.resize(offset + 1); hexDigits[offset + 0] = static_cast<char>(codePoint); } else { if (codePoint <= 0x7FF) { hexDigits.resize(offset + 2); hexDigits[offset + 1] = static_cast<char>(0x80 | (0x3f & codePoint)); hexDigits[offset + 0] = static_cast<char>(0xC0 | (0x1f & (codePoint >> 6))); } else if (codePoint <= 0xFFFF) { hexDigits.resize(offset + 3); hexDigits[offset + 2] = static_cast<char>(0x80 | (0x3f & codePoint)); hexDigits[offset + 1] = static_cast<char>(0x80 | (0x3f & (codePoint >> 6))); hexDigits[offset + 0] = static_cast<char>(0xE0 | (0x0f & (codePoint >> 12))); } else if (codePoint <= 0x10FFFF) { hexDigits.resize(offset + 4); hexDigits[offset + 3] = static_cast<char>(0x80 | (0x3f & codePoint)); hexDigits[offset + 2] = static_cast<char>(0x80 | (0x3f & (codePoint >> 6))); hexDigits[offset + 1] = static_cast<char>(0x80 | (0x3f & (codePoint >> 12))); hexDigits[offset + 0] = static_cast<char>(0xF0 | (0x07 & (codePoint >> 18))); } } return 0; } ::gpk::error_t gpk::digest (const ::gpk::view_const_byte & input, ::gpk::array_pod<uint32_t> & digest) { uint32_t x = 0; ::gpk::array_pod<uint32_t> filtered = {}; for(uint32_t i = 0; i < input.size() - 8; ++i) { x += ::gpk::noise1DBase32(input[i]) + ::gpk::noise1DBase32(input[i + 1]) + ::gpk::noise1DBase32(input[i + 2]) + ::gpk::noise1DBase32(input[i + 3]) + ::gpk::noise1DBase32(input[i + 4]) + ::gpk::noise1DBase32(input[i + 5]) + ::gpk::noise1DBase32(input[i + 6]) + ::gpk::noise1DBase32(input[i + 7]) ; x += x ^ (x << 11); filtered.push_back(x); } for(uint32_t i = 0; i < filtered.size() - 8; ++i) { filtered[i] ^= ::gpk::noise1DBase32(filtered[i]) + ::gpk::noise1DBase32(filtered[i + 1]) + ::gpk::noise1DBase32(filtered[i + 2]) + ::gpk::noise1DBase32(filtered[i + 3]) + ::gpk::noise1DBase32(filtered[i + 4]) + ::gpk::noise1DBase32(filtered[i + 5]) + ::gpk::noise1DBase32(filtered[i + 6]) + ::gpk::noise1DBase32(filtered[i + 7]) ; } for(uint32_t i = 2; i < (filtered.size() - 32); i += 2) { for(uint32_t j = 0; j < 32; j++) filtered[j] += filtered[i + j]; } digest.append({filtered.begin(), ::gpk::min(32U, filtered.size())}); return 0; } ::gpk::error_t gpk::digest (const ::gpk::view_const_byte & input, ::gpk::array_pod<byte_t> & digest) { uint32_t x = 0; ::gpk::array_pod<uint32_t> filtered = {}; for(uint32_t i = 0; i < input.size() - 8; ++i) { x += ::gpk::noise1DBase32(input[i]) + ::gpk::noise1DBase32(input[i + 1]) + ::gpk::noise1DBase32(input[i + 2]) + ::gpk::noise1DBase32(input[i + 3]) + ::gpk::noise1DBase32(input[i + 4]) + ::gpk::noise1DBase32(input[i + 5]) + ::gpk::noise1DBase32(input[i + 6]) + ::gpk::noise1DBase32(input[i + 7]) ; x += x ^ (x << 11); filtered.push_back(x); } for(uint32_t i = 0; i < filtered.size() - 8; ++i) { filtered[i] ^= ::gpk::noise1DBase32(filtered[i]) + ::gpk::noise1DBase32(filtered[i + 1]) + ::gpk::noise1DBase32(filtered[i + 2]) + ::gpk::noise1DBase32(filtered[i + 3]) + ::gpk::noise1DBase32(filtered[i + 4]) + ::gpk::noise1DBase32(filtered[i + 5]) + ::gpk::noise1DBase32(filtered[i + 6]) + ::gpk::noise1DBase32(filtered[i + 7]) ; } for(uint32_t i = 2, count = (filtered.size() - 8); i < count; i += 2) { for(uint32_t j = 0; j < 8; j++) filtered[j] += filtered[i + j]; } char temp [32] = {}; for(uint32_t i = 0; i < ::gpk::min(filtered.size(), 8U); ++i) { snprintf(temp, ::gpk::size(temp) - 2, "%i", filtered[i]); digest.append_string(temp); } return 0; }
45.385827
201
0.523942
asm128
44c27f857b84d3171d72122c13641b9b0f5aeba5
1,400
cpp
C++
amr-wind/equation_systems/icns/source_terms/BodyForce.cpp
gdeskos/amr-wind
002a2bbb1538a25a06126504d507245b623413f6
[ "BSD-3-Clause" ]
2
2022-02-16T18:00:27.000Z
2022-03-21T18:57:14.000Z
amr-wind/equation_systems/icns/source_terms/BodyForce.cpp
gdeskos/amr-wind
002a2bbb1538a25a06126504d507245b623413f6
[ "BSD-3-Clause" ]
1
2022-02-16T21:09:49.000Z
2022-02-16T21:09:49.000Z
amr-wind/equation_systems/icns/source_terms/BodyForce.cpp
gdeskos/amr-wind
002a2bbb1538a25a06126504d507245b623413f6
[ "BSD-3-Clause" ]
1
2022-01-04T18:15:30.000Z
2022-01-04T18:15:30.000Z
#include "amr-wind/equation_systems/icns/source_terms/BodyForce.H" #include "amr-wind/CFDSim.H" #include "amr-wind/utilities/trig_ops.H" #include "AMReX_ParmParse.H" #include "AMReX_Gpu.H" namespace amr_wind { namespace pde { namespace icns { /** Body Force */ BodyForce::BodyForce(const CFDSim& sim) : m_time(sim.time()) { // Read the geostrophic wind speed vector (in m/s) amrex::ParmParse pp("BodyForce"); pp.query("type", m_type); m_type = amrex::toLower(m_type); pp.getarr("magnitude", m_body_force); if (m_type == "oscillatory") pp.get("angular_frequency", m_omega); } BodyForce::~BodyForce() = default; void BodyForce::operator()( const int lev, const amrex::MFIter& mfi, const amrex::Box& bx, const FieldState fstate, const amrex::Array4<amrex::Real>& src_term) const { const auto& time = m_time.current_time(); amrex::GpuArray<amrex::Real, AMREX_SPACEDIM> forcing{ {m_body_force[0], m_body_force[1], m_body_force[2]}}; amrex::Real coeff = (m_type == "oscillatory") ? std::cos(m_omega * time) : 1.0; amrex::ParallelFor(bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept { src_term(i, j, k, 0) += coeff * forcing[0]; src_term(i, j, k, 1) += coeff * forcing[1]; src_term(i, j, k, 2) += coeff * forcing[2]; }); } } // namespace icns } // namespace pde } // namespace amr_wind
26.923077
79
0.649286
gdeskos
44c476f120a0f728f5d117f3ae8b0b0a1bc487dd
21,386
cpp
C++
BonDriver_Proxy.cpp
epgdatacapbon/BonDriverProxy_Linux
3d778b07354820a8f60b50b07fffbc334cec15a0
[ "MIT" ]
30
2015-01-27T15:34:50.000Z
2021-01-24T12:50:04.000Z
BonDriver_Proxy.cpp
epgdatacapbon/BonDriverProxy_Linux
3d778b07354820a8f60b50b07fffbc334cec15a0
[ "MIT" ]
1
2017-01-31T06:52:10.000Z
2017-01-31T06:52:10.000Z
BonDriver_Proxy.cpp
epgdatacapbon/BonDriverProxy_Linux
3d778b07354820a8f60b50b07fffbc334cec15a0
[ "MIT" ]
16
2015-04-11T02:06:11.000Z
2022-01-28T04:02:31.000Z
#include "BonDriver_Proxy.h" namespace BonDriver_Proxy { static BOOL IsTagMatch(const char *line, const char *tag, char **value) { const int taglen = ::strlen(tag); const char *p; if (::strncmp(line, tag, taglen) != 0) return FALSE; p = line + taglen; while (*p == ' ' || *p == '\t') p++; if (value == NULL && *p == '\0') return TRUE; if (*p++ != '=') return FALSE; while (*p == ' ' || *p == '\t') p++; *value = const_cast<char *>(p); return TRUE; } static int Init() { FILE *fp; char *p, buf[512]; Dl_info info; if (::dladdr((void *)Init, &info) == 0) return -1; ::strncpy(buf, info.dli_fname, sizeof(buf) - 8); buf[sizeof(buf) - 8] = '\0'; ::strcat(buf, ".conf"); fp = ::fopen(buf, "r"); if (fp == NULL) return -2; BOOL bHost, bPort, bBonDriver, bChannelLock, bConnectTimeOut, bUseMagicPacket; BOOL bTargetHost, bTargetPort, bTargetMac; BOOL bPacketFifoSize, bTsFifoSize, bTsPacketBufSize; bHost = bPort = bBonDriver = bChannelLock = bConnectTimeOut = bUseMagicPacket = FALSE; bTargetHost = bTargetPort = bTargetMac = FALSE; bPacketFifoSize = bTsFifoSize = bTsPacketBufSize = FALSE; while (::fgets(buf, sizeof(buf), fp)) { if (buf[0] == ';') continue; p = buf + ::strlen(buf) - 1; while ((p >= buf) && (*p == '\r' || *p == '\n')) *p-- = '\0'; if (p < buf) continue; if (!bHost && IsTagMatch(buf, "ADDRESS", &p)) { ::strncpy(g_Host, p, sizeof(g_Host) - 1); g_Host[sizeof(g_Host) - 1] = '\0'; bHost = TRUE; } else if (!bPort && IsTagMatch(buf, "PORT", &p)) { ::strncpy(g_Port, p, sizeof(g_Port) - 1); g_Port[sizeof(g_Port) - 1] = '\0'; bPort = TRUE; } else if (!bBonDriver && IsTagMatch(buf, "BONDRIVER", &p)) { ::strncpy(g_BonDriver, p, sizeof(g_BonDriver) - 1); g_BonDriver[sizeof(g_BonDriver) - 1] = '\0'; bBonDriver = TRUE; } else if (!bChannelLock && IsTagMatch(buf, "CHANNEL_LOCK", &p)) { g_ChannelLock = (BYTE)::atoi(p); bChannelLock = TRUE; } else if (!bConnectTimeOut && IsTagMatch(buf, "CONNECT_TIMEOUT", &p)) { g_ConnectTimeOut = ::atoi(p); bConnectTimeOut = TRUE; } else if (!bUseMagicPacket && IsTagMatch(buf, "USE_MAGICPACKET", &p)) { g_UseMagicPacket = ::atoi(p); bUseMagicPacket = TRUE; } else if (!bTargetHost && IsTagMatch(buf, "TARGET_ADDRESS", &p)) { ::strncpy(g_TargetHost, p, sizeof(g_TargetHost) - 1); g_TargetHost[sizeof(g_TargetHost) - 1] = '\0'; bTargetHost = TRUE; } else if (!bTargetPort && IsTagMatch(buf, "TARGET_PORT", &p)) { ::strncpy(g_TargetPort, p, sizeof(g_TargetPort) - 1); g_TargetPort[sizeof(g_TargetPort) - 1] = '\0'; bTargetPort = TRUE; } else if (!bTargetMac && IsTagMatch(buf, "TARGET_MACADDRESS", &p)) { char mac[32]; ::memset(mac, 0, sizeof(mac)); ::strncpy(mac, p, sizeof(mac) - 1); BOOL bErr = FALSE; for (int i = 0; i < 6 && !bErr; i++) { BYTE b = 0; p = &mac[i * 3]; for (int j = 0; j < 2 && !bErr; j++) { if ('0' <= *p && *p <= '9') b = b * 0x10 + (*p - '0'); else if ('A' <= *p && *p <= 'F') b = b * 0x10 + (*p - 'A' + 10); else if ('a' <= *p && *p <= 'f') b = b * 0x10 + (*p - 'a' + 10); else bErr = TRUE; p++; } g_TargetMac[i] = b; } if (!bErr) bTargetMac = TRUE; } else if (!bPacketFifoSize && IsTagMatch(buf, "PACKET_FIFO_SIZE", &p)) { g_PacketFifoSize = ::atoi(p); bPacketFifoSize = TRUE; } else if (!bTsFifoSize && IsTagMatch(buf, "TS_FIFO_SIZE", &p)) { g_TsFifoSize = ::atoi(p); bTsFifoSize = TRUE; } else if (!bTsPacketBufSize && IsTagMatch(buf, "TSPACKET_BUFSIZE", &p)) { g_TsPacketBufSize = ::atoi(p); bTsPacketBufSize = TRUE; } } ::fclose(fp); if (!bHost || !bPort || !bBonDriver) return -3; if (g_UseMagicPacket) { if (!bTargetMac) return -4; if (!bTargetHost) ::strcpy(g_TargetHost, g_Host); if (!bTargetPort) ::strcpy(g_TargetPort, g_Port); } return 0; } cProxyClient::cProxyClient() : m_Error(m_c, m_m), m_SingleShot(m_c, m_m), m_fifoSend(m_c, m_m), m_fifoRecv(m_c, m_m), m_fifoTS(m_c, m_m) { m_s = INVALID_SOCKET; m_LastBuf = NULL; m_dwBufPos = 0; ::memset(m_pBuf, 0, sizeof(m_pBuf)); m_bBonDriver = m_bTuner = m_bRereased = m_bWaitCNR = FALSE; m_fSignalLevel = 0; m_dwSpace = m_dwChannel = 0x7fffffff; // INT_MAX m_hThread = 0; // m_iEndCount = -1; size_t n = 0; char *p = (char *)TUNER_NAME; for (;;) { m_TunerName[n++] = *p; m_TunerName[n++] = '\0'; if ((*p++ == '\0') || (n > (sizeof(m_TunerName) - 2))) break; } m_TunerName[sizeof(m_TunerName) - 2] = '\0'; m_TunerName[sizeof(m_TunerName) - 1] = '\0'; pthread_mutexattr_t attr; ::pthread_mutexattr_init(&attr); ::pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); ::pthread_mutex_init(&m_m, &attr); ::pthread_cond_init(&m_c, NULL); m_SingleShot.SetAutoReset(TRUE); int i; for (i = 0; i < ebResNum; i++) { m_bResEvent[i] = new cEvent(m_c, m_m); m_bResEvent[i]->SetAutoReset(TRUE); } for (i = 0; i < edwResNum; i++) { m_dwResEvent[i] = new cEvent(m_c, m_m); m_dwResEvent[i]->SetAutoReset(TRUE); } for (i = 0; i < epResNum; i++) { m_pResEvent[i] = new cEvent(m_c, m_m); m_pResEvent[i]->SetAutoReset(TRUE); } } cProxyClient::~cProxyClient() { if (!m_bRereased) { if (m_bTuner) CloseTuner(); makePacket(eRelease); } m_Error.Set(); // if (m_iEndCount != -1) // SleepLock(3); if (m_hThread != 0) ::pthread_join(m_hThread, NULL); int i; { LOCK(m_writeLock); for (i = 0; i < 8; i++) delete[] m_pBuf[i]; TsFlush(); delete m_LastBuf; } for (i = 0; i < ebResNum; i++) delete m_bResEvent[i]; for (i = 0; i < edwResNum; i++) delete m_dwResEvent[i]; for (i = 0; i < epResNum; i++) delete m_pResEvent[i]; ::pthread_cond_destroy(&m_c); ::pthread_mutex_destroy(&m_m); if (m_s != INVALID_SOCKET) ::close(m_s); } void *cProxyClient::ProcessEntry(LPVOID pv) { cProxyClient *pProxy = static_cast<cProxyClient *>(pv); DWORD &ret = pProxy->m_tRet; ret = pProxy->Process(); // pProxy->m_iEndCount++; return &ret; } DWORD cProxyClient::Process() { pthread_t hThread[2]; if (::pthread_create(&hThread[0], NULL, cProxyClient::Sender, this)) { m_Error.Set(); return 1; } if (::pthread_create(&hThread[1], NULL, cProxyClient::Receiver, this)) { m_Error.Set(); ::pthread_join(hThread[0], NULL); return 2; } // m_iEndCount = 0; m_SingleShot.Set(); cEvent *h[2] = { &m_Error, m_fifoRecv.GetEventHandle() }; for (;;) { DWORD dwRet = cEvent::MultipleWait(2, h); switch (dwRet) { case WAIT_OBJECT_0: goto end; case WAIT_OBJECT_0 + 1: { int idx; cPacketHolder *pPh = NULL; m_fifoRecv.Pop(&pPh); switch (pPh->GetCommand()) { case eSelectBonDriver: idx = ebResSelectBonDriver; goto bres; case eCreateBonDriver: idx = ebResCreateBonDriver; goto bres; case eOpenTuner: idx = ebResOpenTuner; goto bres; case ePurgeTsStream: idx = ebResPurgeTsStream; goto bres; case eSetLnbPower: idx = ebResSetLnbPower; bres: { LOCK(m_readLock); if (pPh->GetBodyLength() != sizeof(BYTE)) m_bRes[idx] = FALSE; else m_bRes[idx] = pPh->m_pPacket->payload[0]; m_bResEvent[idx]->Set(); break; } case eGetTsStream: if (pPh->GetBodyLength() >= (sizeof(DWORD) * 2)) { DWORD *pdw = (DWORD *)(pPh->m_pPacket->payload); DWORD dwSize = ntohl(*pdw); // 変なパケットは廃棄(正規のサーバに繋いでいる場合は来る事はないハズ) if ((pPh->GetBodyLength() - (sizeof(DWORD) * 2)) == dwSize) { union { DWORD dw; float f; } u; pdw = (DWORD *)(&(pPh->m_pPacket->payload[sizeof(DWORD)])); u.dw = ntohl(*pdw); m_fSignalLevel = u.f; m_bWaitCNR = FALSE; pPh->SetDeleteFlag(FALSE); TS_DATA *pData = new TS_DATA(); pData->dwSize = dwSize; pData->pbBufHead = pPh->m_pBuf; pData->pbBuf = &(pPh->m_pPacket->payload[sizeof(DWORD) * 2]); m_fifoTS.Push(pData); } } break; case eEnumTuningSpace: idx = epResEnumTuningSpace; goto pres; case eEnumChannelName: idx = epResEnumChannelName; pres: { LOCK(m_writeLock); if (m_dwBufPos >= 8) m_dwBufPos = 0; if (m_pBuf[m_dwBufPos]) delete[] m_pBuf[m_dwBufPos]; if (pPh->GetBodyLength() == sizeof(TCHAR)) m_pBuf[m_dwBufPos] = NULL; else { DWORD dw = pPh->GetBodyLength(); m_pBuf[m_dwBufPos] = (TCHAR *)(new BYTE[dw]); ::memcpy(m_pBuf[m_dwBufPos], pPh->m_pPacket->payload, dw); } { LOCK(m_readLock); m_pRes[idx] = m_pBuf[m_dwBufPos++]; m_pResEvent[idx]->Set(); } break; } case eSetChannel2: idx = edwResSetChannel2; goto dwres; case eGetTotalDeviceNum: idx = edwResGetTotalDeviceNum; goto dwres; case eGetActiveDeviceNum: idx = edwResGetActiveDeviceNum; dwres: { LOCK(m_readLock); if (pPh->GetBodyLength() != sizeof(DWORD)) m_dwRes[idx] = 0; else { DWORD *pdw = (DWORD *)(pPh->m_pPacket->payload); m_dwRes[idx] = ntohl(*pdw); } m_dwResEvent[idx]->Set(); break; } default: break; } delete pPh; break; } default: // 何かのエラー m_Error.Set(); goto end; } } end: // SleepLock(2); ::pthread_join(hThread[0], NULL); ::pthread_join(hThread[1], NULL); return 0; } int cProxyClient::ReceiverHelper(char *pDst, DWORD left) { int len, ret; fd_set rd; timeval tv; while (left > 0) { if (m_Error.IsSet()) return -1; FD_ZERO(&rd); FD_SET(m_s, &rd); tv.tv_sec = 1; tv.tv_usec = 0; if ((len = ::select((int)(m_s + 1), &rd, NULL, NULL, &tv)) == SOCKET_ERROR) { ret = -2; goto err; } if (len == 0) continue; if ((len = ::recv(m_s, pDst, left, 0)) <= 0) { ret = -3; goto err; } left -= len; pDst += len; } return 0; err: m_Error.Set(); return ret; } void *cProxyClient::Receiver(LPVOID pv) { cProxyClient *pProxy = static_cast<cProxyClient *>(pv); DWORD left, &ret = pProxy->m_tRet; char *p; cPacketHolder *pPh = NULL; const DWORD MaxPacketBufSize = g_TsPacketBufSize + (sizeof(DWORD) * 2); for (;;) { pPh = new cPacketHolder(MaxPacketBufSize); left = sizeof(stPacketHead); p = (char *)&(pPh->m_pPacket->head); if (pProxy->ReceiverHelper(p, left) != 0) { ret = 201; goto end; } if (!pPh->IsValid()) { pProxy->m_Error.Set(); ret = 202; goto end; } left = pPh->GetBodyLength(); if (left == 0) { pProxy->m_fifoRecv.Push(pPh); continue; } if (left > MaxPacketBufSize) { pProxy->m_Error.Set(); ret = 203; goto end; } p = (char *)(pPh->m_pPacket->payload); if (pProxy->ReceiverHelper(p, left) != 0) { ret = 204; goto end; } pProxy->m_fifoRecv.Push(pPh); } end: delete pPh; // pProxy->m_iEndCount++; return &ret; } void cProxyClient::makePacket(enumCommand eCmd) { cPacketHolder *p = new cPacketHolder(eCmd, 0); m_fifoSend.Push(p); } void cProxyClient::makePacket(enumCommand eCmd, LPCSTR str) { register size_t size = (::strlen(str) + 1); cPacketHolder *p = new cPacketHolder(eCmd, size); ::memcpy(p->m_pPacket->payload, str, size); m_fifoSend.Push(p); } void cProxyClient::makePacket(enumCommand eCmd, BOOL b) { cPacketHolder *p = new cPacketHolder(eCmd, sizeof(BYTE)); p->m_pPacket->payload[0] = (BYTE)b; m_fifoSend.Push(p); } void cProxyClient::makePacket(enumCommand eCmd, DWORD dw) { cPacketHolder *p = new cPacketHolder(eCmd, sizeof(DWORD)); DWORD *pos = (DWORD *)(p->m_pPacket->payload); *pos = htonl(dw); m_fifoSend.Push(p); } void cProxyClient::makePacket(enumCommand eCmd, DWORD dw1, DWORD dw2) { cPacketHolder *p = new cPacketHolder(eCmd, sizeof(DWORD) * 2); DWORD *pos = (DWORD *)(p->m_pPacket->payload); *pos++ = htonl(dw1); *pos = htonl(dw2); m_fifoSend.Push(p); } void cProxyClient::makePacket(enumCommand eCmd, DWORD dw1, DWORD dw2, BYTE b) { cPacketHolder *p = new cPacketHolder(eCmd, (sizeof(DWORD) * 2) + sizeof(BYTE)); DWORD *pos = (DWORD *)(p->m_pPacket->payload); *pos++ = htonl(dw1); *pos++ = htonl(dw2); *(BYTE *)pos = b; m_fifoSend.Push(p); } void *cProxyClient::Sender(LPVOID pv) { cProxyClient *pProxy = static_cast<cProxyClient *>(pv); DWORD &ret = pProxy->m_tRet; cEvent *h[2] = { &(pProxy->m_Error), pProxy->m_fifoSend.GetEventHandle() }; for (;;) { DWORD dwRet = cEvent::MultipleWait(2, h); switch (dwRet) { case WAIT_OBJECT_0: ret = 101; goto end; case WAIT_OBJECT_0 + 1: { cPacketHolder *pPh = NULL; pProxy->m_fifoSend.Pop(&pPh); int left = (int)pPh->m_Size; char *p = (char *)(pPh->m_pPacket); while (left > 0) { int len = ::send(pProxy->m_s, p, left, 0); if (len == SOCKET_ERROR) { pProxy->m_Error.Set(); break; } left -= len; p += len; } delete pPh; break; } default: // 何かのエラー pProxy->m_Error.Set(); ret = 102; goto end; } } end: // pProxy->m_iEndCount++; return &ret; } BOOL cProxyClient::SelectBonDriver() { { LOCK(g_Lock); makePacket(eSelectBonDriver, g_BonDriver); } if (m_bResEvent[ebResSelectBonDriver]->Wait(&m_Error) != WAIT_OBJECT_0) { LOCK(m_readLock); return m_bRes[ebResSelectBonDriver]; } return FALSE; } BOOL cProxyClient::CreateBonDriver() { makePacket(eCreateBonDriver); if (m_bResEvent[ebResCreateBonDriver]->Wait(&m_Error) != WAIT_OBJECT_0) { LOCK(m_readLock); if (m_bRes[ebResCreateBonDriver]) m_bBonDriver = TRUE; return m_bRes[ebResCreateBonDriver]; } return FALSE; } const BOOL cProxyClient::OpenTuner(void) { if (!m_bBonDriver) return FALSE; makePacket(eOpenTuner); if (m_bResEvent[ebResOpenTuner]->Wait(&m_Error) != WAIT_OBJECT_0) { LOCK(m_readLock); if (m_bRes[ebResOpenTuner]) m_bTuner = TRUE; return m_bRes[ebResOpenTuner]; } return FALSE; } void cProxyClient::CloseTuner(void) { if (!m_bTuner) return; makePacket(eCloseTuner); m_bTuner = m_bWaitCNR = FALSE; m_fSignalLevel = 0; m_dwSpace = m_dwChannel = 0x7fffffff; // INT_MAX { LOCK(m_writeLock); m_dwBufPos = 0; for (int i = 0; i < 8; i++) delete[] m_pBuf[i]; ::memset(m_pBuf, 0, sizeof(m_pBuf)); } } const BOOL cProxyClient::SetChannel(const BYTE bCh) { return TRUE; } const float cProxyClient::GetSignalLevel(void) { // イベントでやろうかと思ったけど、デッドロックを防ぐ為には発生する処理の回数の内大半では // 全く無駄なイベント処理が発生する事になるので、ポーリングでやる事にした // なお、絶妙なタイミングでのネットワーク切断等に備えて、最大でも約0.5秒までしか待たない timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10 * 1000 * 1000; for (int i = 0; m_bWaitCNR && (i < 50); i++) ::nanosleep(&ts, NULL); return m_fSignalLevel; } const DWORD cProxyClient::WaitTsStream(const DWORD dwTimeOut) { if (!m_bTuner) return WAIT_ABANDONED; if (m_fifoTS.Size() != 0) return WAIT_OBJECT_0; else return WAIT_TIMEOUT; // 手抜き } const DWORD cProxyClient::GetReadyCount(void) { if (!m_bTuner) return 0; return (DWORD)m_fifoTS.Size(); } const BOOL cProxyClient::GetTsStream(BYTE *pDst, DWORD *pdwSize, DWORD *pdwRemain) { if (!m_bTuner) return FALSE; BYTE *pSrc; if (GetTsStream(&pSrc, pdwSize, pdwRemain)) { if (*pdwSize) ::memcpy(pDst, pSrc, *pdwSize); return TRUE; } return FALSE; } const BOOL cProxyClient::GetTsStream(BYTE **ppDst, DWORD *pdwSize, DWORD *pdwRemain) { if (!m_bTuner) return FALSE; BOOL b; { LOCK(m_writeLock); if (m_fifoTS.Size() != 0) { delete m_LastBuf; m_fifoTS.Pop(&m_LastBuf); *ppDst = m_LastBuf->pbBuf; *pdwSize = m_LastBuf->dwSize; *pdwRemain = (DWORD)m_fifoTS.Size(); b = TRUE; } else { *pdwSize = 0; *pdwRemain = 0; b = FALSE; } } return b; } void cProxyClient::PurgeTsStream(void) { if (!m_bTuner) return; makePacket(ePurgeTsStream); if (m_bResEvent[ebResPurgeTsStream]->Wait(&m_Error) != WAIT_OBJECT_0) { BOOL b; { LOCK(m_readLock); b = m_bRes[ebResPurgeTsStream]; } if (b) { LOCK(m_writeLock); TsFlush(); } } } void cProxyClient::Release(void) { if (m_bTuner) CloseTuner(); makePacket(eRelease); m_bRereased = TRUE; { LOCK(g_Lock); g_InstanceList.remove(this); } delete this; } LPCTSTR cProxyClient::GetTunerName(void) { return (LPCTSTR)m_TunerName; } const BOOL cProxyClient::IsTunerOpening(void) { return FALSE; } LPCTSTR cProxyClient::EnumTuningSpace(const DWORD dwSpace) { if (!m_bTuner) return NULL; makePacket(eEnumTuningSpace, dwSpace); if (m_pResEvent[epResEnumTuningSpace]->Wait(&m_Error) != WAIT_OBJECT_0) { LOCK(m_readLock); return m_pRes[epResEnumTuningSpace]; } return NULL; } LPCTSTR cProxyClient::EnumChannelName(const DWORD dwSpace, const DWORD dwChannel) { if (!m_bTuner) return NULL; makePacket(eEnumChannelName, dwSpace, dwChannel); if (m_pResEvent[epResEnumChannelName]->Wait(&m_Error) != WAIT_OBJECT_0) { LOCK(m_readLock); return m_pRes[epResEnumChannelName]; } return NULL; } const BOOL cProxyClient::SetChannel(const DWORD dwSpace, const DWORD dwChannel) { if (!m_bTuner) goto err; // if ((m_dwSpace == dwSpace) && (m_dwChannel == dwChannel)) // return TRUE; makePacket(eSetChannel2, dwSpace, dwChannel, g_ChannelLock); DWORD dw; if (m_dwResEvent[edwResSetChannel2]->Wait(&m_Error) != WAIT_OBJECT_0) { LOCK(m_readLock); dw = m_dwRes[edwResSetChannel2]; } else dw = 0xff; switch (dw) { case 0x00: // 成功 { LOCK(m_writeLock); TsFlush(); m_dwSpace = dwSpace; m_dwChannel = dwChannel; m_fSignalLevel = 0; m_bWaitCNR = TRUE; } case 0x01: // fall-through / チャンネルロックされてる return TRUE; default: break; } err: m_fSignalLevel = 0; return FALSE; } const DWORD cProxyClient::GetCurSpace(void) { return m_dwSpace; } const DWORD cProxyClient::GetCurChannel(void) { return m_dwChannel; } const DWORD cProxyClient::GetTotalDeviceNum(void) { if (!m_bTuner) return 0; makePacket(eGetTotalDeviceNum); if (m_dwResEvent[edwResGetTotalDeviceNum]->Wait(&m_Error) != WAIT_OBJECT_0) { LOCK(m_readLock); return m_dwRes[edwResGetTotalDeviceNum]; } return 0; } const DWORD cProxyClient::GetActiveDeviceNum(void) { if (!m_bTuner) return 0; makePacket(eGetActiveDeviceNum); if (m_dwResEvent[edwResGetActiveDeviceNum]->Wait(&m_Error) != WAIT_OBJECT_0) { LOCK(m_readLock); return m_dwRes[edwResGetActiveDeviceNum]; } return 0; } const BOOL cProxyClient::SetLnbPower(const BOOL bEnable) { if (!m_bTuner) return FALSE; makePacket(eSetLnbPower, bEnable); if (m_bResEvent[ebResSetLnbPower]->Wait(&m_Error) != WAIT_OBJECT_0) { LOCK(m_readLock); return m_bRes[ebResSetLnbPower]; } return FALSE; } static SOCKET Connect(char *host, char *port) { addrinfo hints, *results, *rp; SOCKET sock; int i, bf; fd_set wd; timeval tv; ::memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; if (g_UseMagicPacket) { char sendbuf[128]; ::memset(sendbuf, 0xff, 6); for (i = 1; i <= 16; i++) ::memcpy(&sendbuf[i * 6], g_TargetMac, 6); hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_NUMERICHOST; if (::getaddrinfo(g_TargetHost, g_TargetPort, &hints, &results) != 0) { hints.ai_flags = 0; if (::getaddrinfo(g_TargetHost, g_TargetPort, &hints, &results) != 0) return INVALID_SOCKET; } for (rp = results; rp != NULL; rp = rp->ai_next) { sock = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sock == INVALID_SOCKET) continue; BOOL opt = TRUE; if (::setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (const char *)&opt, sizeof(opt)) != 0) { ::close(sock); continue; } int ret = ::sendto(sock, sendbuf, 102, 0, rp->ai_addr, (int)(rp->ai_addrlen)); ::close(sock); if (ret == 102) break; } ::freeaddrinfo(results); if (rp == NULL) return INVALID_SOCKET; } hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_NUMERICHOST; if (::getaddrinfo(host, port, &hints, &results) != 0) { hints.ai_flags = 0; if (::getaddrinfo(host, port, &hints, &results) != 0) return INVALID_SOCKET; } for (rp = results; rp != NULL; rp = rp->ai_next) { sock = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sock == INVALID_SOCKET) continue; bf = TRUE; ::ioctl(sock, FIONBIO, &bf); tv.tv_sec = g_ConnectTimeOut; tv.tv_usec = 0; FD_ZERO(&wd); FD_SET(sock, &wd); ::connect(sock, rp->ai_addr, (int)(rp->ai_addrlen)); if ((i = ::select((int)(sock + 1), 0, &wd, 0, &tv)) != SOCKET_ERROR) { // タイムアウト時間が"全体の"ではなく"個々のソケットの"になるけど、とりあえずこれで if (i != 0) { bf = FALSE; ::ioctl(sock, FIONBIO, &bf); break; } } ::close(sock); } ::freeaddrinfo(results); if (rp == NULL) return INVALID_SOCKET; return sock; } extern "C" IBonDriver *CreateBonDriver() { if (Init() != 0) return NULL; SOCKET s = Connect(g_Host, g_Port); if (s == INVALID_SOCKET) return NULL; cProxyClient *pProxy = new cProxyClient(); pProxy->setSocket(s); pthread_t ht; if (::pthread_create(&ht, NULL, cProxyClient::ProcessEntry, pProxy)) goto err; pProxy->setThreadHandle(ht); if (pProxy->WaitSingleShot() == WAIT_OBJECT_0) goto err; if (!pProxy->SelectBonDriver()) goto err; if (pProxy->CreateBonDriver()) { LOCK(g_Lock); g_InstanceList.push_back(pProxy); return pProxy; } err: delete pProxy; return NULL; } extern "C" BOOL SetBonDriver(LPCSTR p) { LOCK(g_Lock); if (::strlen(p) >= sizeof(g_BonDriver)) return FALSE; ::strcpy(g_BonDriver, p); return TRUE; } }
20.742968
136
0.634901
epgdatacapbon
44c560a2a5700361e8de3ae5bb21827a9af88b54
999
cc
C++
tests/test0009.cc
michaeljclark/glyb
5b302ded6061eea2098bc8e963adb09e5f1dab4e
[ "MIT" ]
7
2021-07-28T19:03:08.000Z
2022-02-02T23:17:11.000Z
tests/test0009.cc
michaeljclark/glyb
5b302ded6061eea2098bc8e963adb09e5f1dab4e
[ "MIT" ]
2
2021-06-15T22:34:44.000Z
2021-11-10T04:27:21.000Z
tests/test0009.cc
michaeljclark/glyb
5b302ded6061eea2098bc8e963adb09e5f1dab4e
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cerrno> #include <cstring> #define FLOAT32 "%.9g" struct atlas_ent { int bin_id, font_id, glyph; short x, y, ox, oy, w, h; }; int main(int argc, char **argv) { FILE *in = nullptr; if (argc != 2) { fprintf(stderr, "usage: %s <filename>\n", argv[0]); exit(1); } if (!(in = fopen(argv[1], "r"))) { fprintf(stderr, "error: fopen: %s, %s\n", argv[1], strerror(errno)); exit(1); } const int num_fields = 9; int ret; do { atlas_ent ent; ret = fscanf(in, "%d,%d,%d,%hd,%hd,%hd,%hd,%hd,%hd\n", &ent.bin_id, &ent.font_id, &ent.glyph, &ent.x, &ent.y, &ent.ox, &ent.oy, &ent.w, &ent.h); if (ret == num_fields) { printf("%d,%d,%d,%d,%d,%d,%d,%d,%d\n", ent.bin_id, ent.font_id, ent.glyph, ent.x, ent.y, ent.ox, ent.oy, ent.w, ent.h); } } while (ret == num_fields); fclose(in); }
22.704545
76
0.491491
michaeljclark
44c5c0645aeb629366c56177ce4382dd3b73e9f4
123
cpp
C++
Trixs/UIManager.cpp
RuurddeRonde/Trixs-raytracer
382d4e95a54274ef7fbc4f4fba7575fe6f286298
[ "MIT" ]
2
2020-08-25T00:31:17.000Z
2021-12-11T22:14:02.000Z
Trixs/UIManager.cpp
RuurddeRonde/Trixs-raytracer
382d4e95a54274ef7fbc4f4fba7575fe6f286298
[ "MIT" ]
null
null
null
Trixs/UIManager.cpp
RuurddeRonde/Trixs-raytracer
382d4e95a54274ef7fbc4f4fba7575fe6f286298
[ "MIT" ]
null
null
null
#include "UIManager.h" namespace Trixs { UIManager::UIManager(Window* window) { } UIManager::~UIManager() { } }
7.6875
37
0.642276
RuurddeRonde
44c6dedd44ad4509a3f5a9c13fc04d6f1ffbdc64
6,995
cc
C++
lite/kernels/arm/concat_compute_test.cc
xw-github/Paddle-Lite
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
[ "Apache-2.0" ]
null
null
null
lite/kernels/arm/concat_compute_test.cc
xw-github/Paddle-Lite
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
[ "Apache-2.0" ]
null
null
null
lite/kernels/arm/concat_compute_test.cc
xw-github/Paddle-Lite
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/kernels/arm/concat_compute.h" #include <gtest/gtest.h> #include <limits> #include <string> #include <vector> #include "lite/backends/arm/math/funcs.h" #include "lite/core/op_registry.h" #include "lite/core/tensor.h" namespace paddle { namespace lite { namespace kernels { namespace arm { bool infer_shape(const operators::ConcatParam& param) { std::vector<lite::DDim> input_dims; for (auto p : param.x) { input_dims.push_back(p->dims()); } size_t axis = static_cast<size_t>(param.axis); const size_t n = input_dims.size(); CHECK_GT_OR_FALSE(n, 0); auto& out_dims = input_dims[0]; size_t in_zero_dims_size = out_dims.size(); for (size_t i = 1; i < n; i++) { for (size_t j = 0; j < in_zero_dims_size; j++) { if (j == axis) { out_dims[axis] += input_dims[i][j]; } else { CHECK_EQ_OR_FALSE(out_dims[j], input_dims[i][j]); } } } if (out_dims[axis] < 0) { out_dims[axis] = -1; } // Set output dims param.output->Resize(lite::DDim(out_dims)); return true; } void concat_compute_ref(const operators::ConcatParam& param) { std::vector<lite::Tensor*> input = param.x; int axis = param.axis; infer_shape(param); lite::Tensor* output = param.output; int num = input.size(); int rows = 1; auto dim_0 = input[0]->dims(); for (int i = 0; i < axis; ++i) { rows *= dim_0[i]; } int out_rows = rows, out_cols = 0; std::vector<int> input_cols(input.size()); for (int i = 0; i < num; ++i) { int input_i_numel = input[i]->dims().size() == 0 ? 0 : 1; for (int didx = 0; didx < input[i]->dims().size(); ++didx) { input_i_numel *= input[i]->dims()[didx]; } int t_cols = input_i_numel / rows; out_cols += t_cols; input_cols[i] = t_cols; } // computation auto output_data = output->mutable_data<float>(); int col_idx = 0; for (int j = 0; j < num; ++j) { int col_len = input_cols[j]; auto input_data = input[j]->data<float>(); for (int k = 0; k < out_rows; ++k) { memcpy(output_data + k * out_cols + col_idx, input_data + k * col_len, sizeof(float) * col_len); } col_idx += col_len; } } TEST(concat_arm, init) { ConcatCompute concat; ASSERT_EQ(concat.precision(), PRECISION(kAny)); ASSERT_EQ(concat.target(), TARGET(kARM)); } TEST(concat_arm, compute_input_single) { ConcatCompute concat; operators::ConcatParam param; LOG(INFO) << "test concat start"; lite::Tensor output; lite::Tensor output_ref; lite::Tensor tensorA; DDimLite ddimA({10, 4, 3, 2}); tensorA.Resize(ddimA); for (int i = 0; i < ddimA.data()[0] * ddimA.data()[1] * ddimA.data()[2] * ddimA.data()[3]; i++) { tensorA.mutable_data<float>()[i] = i; } param.x.push_back(&tensorA); for (int cur_axis : {0, 1}) { param.output = &output; param.axis = cur_axis; CHECK(infer_shape(param)); concat.SetParam(param); LOG(INFO) << "test concat start cur_axis:" << cur_axis; concat.Run(); LOG(INFO) << "concat.Run end"; param.output = &output_ref; LOG(INFO) << "concat_compute_ref start"; concat_compute_ref(param); LOG(INFO) << "concat_compute_ref end"; auto* output_data = output.data<float>(); auto* output_ref_data = output_ref.data<float>(); for (int i = 0; i < (ddimA.data()[0]) * ddimA.data()[1] * ddimA.data()[2] * ddimA.data()[3]; i++) { // LOG(INFO) << "output[" << i << "]:" << output_data[i] << " // output_ref_data[" << i << "]:" << output_ref_data[i]; EXPECT_NEAR(output_data[i], output_ref_data[i], 1e-5); } } } TEST(concat_arm, compute_input_multi) { ConcatCompute concat; operators::ConcatParam param; LOG(INFO) << "test concat start"; // init param // x: tensorA, tensorB, tensorC, tensorD // axis: 0 lite::Tensor output; lite::Tensor output_ref; lite::Tensor tensorA; lite::Tensor tensorB; lite::Tensor tensorC; lite::Tensor tensorD; DDimLite ddimA({10, 4, 3, 2}); DDimLite ddimB({20, 4, 3, 2}); DDimLite ddimC({30, 4, 3, 2}); DDimLite ddimD({40, 4, 3, 2}); tensorA.Resize(ddimA); tensorB.Resize(ddimB); tensorC.Resize(ddimC); tensorD.Resize(ddimD); for (int i = 0; i < ddimA.data()[0] * ddimA.data()[1] * ddimA.data()[2] * ddimA.data()[3]; i++) { tensorA.mutable_data<float>()[i] = i; } for (int i = 0; i < ddimB.data()[0] * ddimB.data()[1] * ddimB.data()[2] * ddimB.data()[3]; i++) { tensorB.mutable_data<float>()[i] = i + 1; } for (int i = 0; i < ddimC.data()[0] * ddimC.data()[1] * ddimC.data()[2] * ddimC.data()[3]; i++) { tensorC.mutable_data<float>()[i] = i + 2; } for (int i = 0; i < ddimD.data()[0] * ddimD.data()[1] * ddimD.data()[2] * ddimD.data()[3]; i++) { tensorD.mutable_data<float>()[i] = i + 3; } param.x.push_back(&tensorA); param.x.push_back(&tensorB); param.x.push_back(&tensorC); param.x.push_back(&tensorD); for (int cur_axis : {0}) { param.output = &output; param.axis = cur_axis; CHECK(infer_shape(param)); concat.SetParam(param); LOG(INFO) << "test concat start cur_axis:" << cur_axis; concat.Run(); LOG(INFO) << "concat.Run end"; param.output = &output_ref; LOG(INFO) << "concat_compute_ref start"; concat_compute_ref(param); LOG(INFO) << "concat_compute_ref end"; auto* output_data = output.data<float>(); auto* output_ref_data = output_ref.data<float>(); int elem_num = (ddimA.data()[0] + ddimB.data()[0] + ddimC.data()[0] + ddimD.data()[0]) * ddimA.data()[1] * ddimA.data()[2] * ddimA.data()[3]; for (int i = 0; i < elem_num; i++) { // LOG(INFO) << "output[" << i << "]:" << output_data[i] << " // output_ref_data[" << i << "]:" << output_ref_data[i]; EXPECT_NEAR(output_data[i], output_ref_data[i], 1e-5); } } } TEST(concat, retrive_op) { auto concat = KernelRegistry::Global().Create<TARGET(kARM), PRECISION(kAny)>("concat"); ASSERT_FALSE(concat.empty()); ASSERT_TRUE(concat.front()); } } // namespace arm } // namespace kernels } // namespace lite } // namespace paddle USE_LITE_KERNEL(concat, kARM, kAny, kNCHW, def);
29.639831
79
0.599714
xw-github
44c7aaf19786548ecfced6f53e79a496434a9a8c
789
cpp
C++
945.minimum_increment_to_make_array_unique_by_sort.cpp
liangwt/leetcode
8f279343e975666a63ee531228c6836f20f199ca
[ "Apache-2.0" ]
5
2019-09-12T05:23:44.000Z
2021-11-15T11:19:39.000Z
945.minimum_increment_to_make_array_unique_by_sort.cpp
liangwt/leetcode
8f279343e975666a63ee531228c6836f20f199ca
[ "Apache-2.0" ]
18
2019-09-23T13:11:06.000Z
2019-11-09T11:20:17.000Z
945.minimum_increment_to_make_array_unique_by_sort.cpp
liangwt/leetcode
8f279343e975666a63ee531228c6836f20f199ca
[ "Apache-2.0" ]
null
null
null
#include <assert.h> #include <vector> using namespace std; class Solution { public: // 先排序,再依次遍历数组元素,若当前元素小于等于它前一个元素,则将其变为前一个数+1。 int minIncrementForUnique(vector<int> &A) { int ans = 0; int len = A.size(); sort(A.begin(), A.end()); for (int i = 1; i < len; ++i) { int r = A[i], l = A[i - 1]; if (r <= l) { ans += (l - r + 1); A[i] = l + 1; } } return ans; } }; int main() { Solution s; vector<int> A1 = {1, 2, 2}; assert(s.minIncrementForUnique(A1) == 1); vector<int> A2 = {3, 2, 1, 2, 1, 7}; assert(s.minIncrementForUnique(A2) == 6); vector<int> A3 = {}; assert(s.minIncrementForUnique(A3) == 0); }
18.348837
49
0.460076
liangwt
44c93b13d5c73e5cfdb0d23e0856f038232d5924
3,292
hpp
C++
ql/termstructures/volatility/swaption/swaptionvolcube2.hpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
76
2017-06-28T21:24:38.000Z
2021-12-19T18:07:37.000Z
ql/termstructures/volatility/swaption/swaptionvolcube2.hpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
2
2017-07-05T09:20:13.000Z
2019-10-31T12:06:51.000Z
ql/termstructures/volatility/swaption/swaptionvolcube2.hpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
34
2017-07-02T14:49:21.000Z
2021-11-26T15:32:04.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006 Ferdinando Ametrano This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file swaptionvolcube2.hpp \brief Swaption volatility cube, fit-later-interpolate-early approach */ #ifndef quantlib_swaption_volcube_fit_later_interpolate_early_h #define quantlib_swaption_volcube_fit_later_interpolate_early_h #include <ql/termstructures/volatility/swaption/swaptionvolcube.hpp> #include <ql/math/interpolations/interpolation2d.hpp> namespace QuantLib { class SwaptionVolCube2 : public SwaptionVolatilityCube{ public: /*! The swaption vol cube is made up of ordered swaption vol surface layers, each layer referring to a swap index of a given length (in years), all indexes belonging to the same family. In order to identify the family (and its market conventions) an index of whatever length from that family must be passed in as swapIndexBase. Often for short swap length the swap index family is different, e.g. the EUR case: swap vs 6M Euribor is used for length>1Y, while swap vs 3M Euribor is used for the 1Y length. The shortSwapIndexBase is used to identify this second family. */ SwaptionVolCube2( const Handle<SwaptionVolatilityStructure>& atmVolStructure, const std::vector<Period>& optionTenors, const std::vector<Period>& swapTenors, const std::vector<Spread>& strikeSpreads, const std::vector<std::vector<Handle<Quote> > >& volSpreads, const std::shared_ptr<SwapIndex>& swapIndexBase, const std::shared_ptr<SwapIndex>& shortSwapIndexBase, bool vegaWeightedSmileFit); //! \name LazyObject interface //@{ void performCalculations() const; //@} //! \name SwaptionVolatilityCube inspectors //@{ const Matrix& volSpreads(Size i) const { return volSpreadsMatrix_[i]; } std::shared_ptr<SmileSection> smileSectionImpl( const Date& optionDate, const Period& swapTenor) const; std::shared_ptr<SmileSection> smileSectionImpl( Time optionTime, Time swapLength) const; //@} private: mutable std::vector<Interpolation2D> volSpreadsInterpolator_; mutable std::vector<Matrix> volSpreadsMatrix_; }; } #endif
42.753247
79
0.655832
haozhangphd
44c9bc060a5ca54beee9f52f28b243a07395959e
183,030
hpp
C++
lib/bill/bill/sat/solver/ghack.hpp
osamamowafy/mockturtle
840ff314e9f5301686790a517c383240f1403588
[ "MIT" ]
98
2018-06-15T09:28:11.000Z
2022-03-31T15:42:48.000Z
lib/bill/bill/sat/solver/ghack.hpp
osamamowafy/mockturtle
840ff314e9f5301686790a517c383240f1403588
[ "MIT" ]
257
2018-05-09T12:14:28.000Z
2022-03-30T16:12:14.000Z
lib/bill/bill/sat/solver/ghack.hpp
osamamowafy/mockturtle
840ff314e9f5301686790a517c383240f1403588
[ "MIT" ]
75
2020-11-26T13:05:15.000Z
2021-12-24T00:28:18.000Z
/**************************************************************************************[IntTypes.h] Copyright (c) 2009-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #pragma once #ifndef Ghack_IntTypes_h #define Ghack_IntTypes_h #ifdef __sun // Not sure if there are newer versions that support C99 headers. The // needed features are implemented in the headers below though: # include <sys/int_types.h> # include <sys/int_fmtio.h> # include <sys/int_limits.h> #else # include <stdint.h> # include <inttypes.h> #endif #include <limits.h> #ifndef PRIu64 #define PRIu64 "lu" #define PRIi64 "ld" #endif //================================================================================================= #endif /****************************************************************************************[XAlloc.h] Copyright (c) 2009-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_XAlloc_h #define Ghack_XAlloc_h #include <errno.h> #include <stdlib.h> #include <stdio.h> namespace GHack { //================================================================================================= // Simple layer on top of malloc/realloc to catch out-of-memory situtaions and provide some typing: class OutOfMemoryException{}; static inline void* xrealloc(void *ptr, size_t size) { void* mem = realloc(ptr, size); if (mem == NULL && errno == ENOMEM){ throw OutOfMemoryException(); }else { return mem; } } //================================================================================================= } #endif /*******************************************************************************************[Vec.h] Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_Vec_h #define Ghack_Vec_h #include <assert.h> #include <new> namespace GHack { //================================================================================================= // Automatically resizable arrays // // NOTE! Don't use this vector on datatypes that cannot be re-located in memory (with realloc) template<class T> class vec { T* data; int sz; int cap; // Don't allow copying (error prone): vec<T>& operator = (vec<T>& other) { assert(0); return *this; } vec (vec<T>& other) { assert(0); } // Helpers for calculating next capacity: static inline int imax (int x, int y) { int mask = (y-x) >> (sizeof(int)*8-1); return (x&mask) + (y&(~mask)); } //static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; } static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; } public: // Constructors: vec() : data(NULL) , sz(0) , cap(0) { } explicit vec(int size) : data(NULL) , sz(0) , cap(0) { growTo(size); } vec(int size, const T& pad) : data(NULL) , sz(0) , cap(0) { growTo(size, pad); } ~vec() { clear(true); } // Pointer to first element: operator T* (void) { return data; } // Size operations: int size (void) const { return sz; } void shrink (int nelems) { assert(nelems <= sz); for (int i = 0; i < nelems; i++) sz--, data[sz].~T(); } void shrink_ (int nelems) { assert(nelems <= sz); sz -= nelems; } int capacity (void) const { return cap; } void capacity (int min_cap); void growTo (int size); void growTo (int size, const T& pad); void clear (bool dealloc = false); // Stack interface: void push (void) { if (sz == cap) capacity(sz+1); new (&data[sz]) T(); sz++; } void push (const T& elem) { if (sz == cap) capacity(sz+1); data[sz++] = elem; } void push_ (const T& elem) { assert(sz < cap); data[sz++] = elem; } void pop (void) { assert(sz > 0); sz--, data[sz].~T(); } // NOTE: it seems possible that overflow can happen in the 'sz+1' expression of 'push()', but // in fact it can not since it requires that 'cap' is equal to INT_MAX. This in turn can not // happen given the way capacities are calculated (below). Essentially, all capacities are // even, but INT_MAX is odd. const T& last (void) const { return data[sz-1]; } T& last (void) { return data[sz-1]; } // Vector interface: const T& operator [] (int index) const { return data[index]; } T& operator [] (int index) { return data[index]; } // Duplicatation (preferred instead): void copyTo(vec<T>& copy) const { copy.clear(); copy.growTo(sz); for (int i = 0; i < sz; i++) copy[i] = data[i]; } void moveTo(vec<T>& dest) { dest.clear(true); dest.data = data; dest.sz = sz; dest.cap = cap; data = NULL; sz = 0; cap = 0; } }; template<class T> void vec<T>::capacity(int min_cap) { if (cap >= min_cap) return; int add = imax((min_cap - cap + 1) & ~1, ((cap >> 1) + 2) & ~1); // NOTE: grow by approximately 3/2 if (add > INT_MAX - cap || (((data = (T*)::realloc(data, (cap += add) * sizeof(T))) == NULL) && errno == ENOMEM)) throw OutOfMemoryException(); } template<class T> void vec<T>::growTo(int size, const T& pad) { if (sz >= size) return; capacity(size); for (int i = sz; i < size; i++) data[i] = pad; sz = size; } template<class T> void vec<T>::growTo(int size) { if (sz >= size) return; capacity(size); for (int i = sz; i < size; i++) new (&data[i]) T(); sz = size; } template<class T> void vec<T>::clear(bool dealloc) { if (data != NULL){ for (int i = 0; i < sz; i++) data[i].~T(); sz = 0; if (dealloc) free(data), data = NULL, cap = 0; } } //================================================================================================= } #endif /*******************************************************************************************[Alg.h] Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_Alg_h #define Ghack_Alg_h namespace GHack { //================================================================================================= // Useful functions on vector-like types: //================================================================================================= // Removing and searching for elements: // template<class V, class T> static inline void remove(V& ts, const T& t) { int j = 0; for (; j < ts.size() && ts[j] != t; j++); assert(j < ts.size()); for (; j < ts.size()-1; j++) ts[j] = ts[j+1]; ts.pop(); } template<class V, class T> static inline bool find(V& ts, const T& t) { int j = 0; for (; j < ts.size() && ts[j] != t; j++); return j < ts.size(); } //================================================================================================= // Copying vectors with support for nested vector types: // // Base case: template<class T> static inline void copy(const T& from, T& to) { to = from; } // Recursive case: template<class T> static inline void copy(const vec<T>& from, vec<T>& to, bool append = false) { if (!append) to.clear(); for (int i = 0; i < from.size(); i++){ to.push(); copy(from[i], to.last()); } } template<class T> static inline void append(const vec<T>& from, vec<T>& to){ copy(from, to, true); } //================================================================================================= } #endif /*****************************************************************************************[Alloc.h] Copyright (c) 2008-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_Alloc_h #define Ghack_Alloc_h namespace GHack { //================================================================================================= // Simple Region-based memory allocator: template<class T> class RegionAllocator { T* memory; uint32_t sz; uint32_t cap; uint32_t wasted_; void capacity(uint32_t min_cap); public: // TODO: make this a class for better type-checking? typedef uint32_t Ref; enum { Ref_Undef = UINT32_MAX }; enum { Unit_Size = sizeof(uint32_t) }; explicit RegionAllocator(uint32_t start_cap = 1024*1024) : memory(NULL), sz(0), cap(0), wasted_(0){ capacity(start_cap); } ~RegionAllocator() { if (memory != NULL) ::free(memory); } uint32_t size () const { return sz; } uint32_t wasted () const { return wasted_; } Ref alloc (int size); void free (int size) { wasted_ += size; } // Deref, Load Effective Address (LEA), Inverse of LEA (AEL): T& operator[](Ref r) { assert(r >= 0 && r < sz); return memory[r]; } const T& operator[](Ref r) const { assert(r >= 0 && r < sz); return memory[r]; } T* lea (Ref r) { assert(r >= 0 && r < sz); return &memory[r]; } const T* lea (Ref r) const { assert(r >= 0 && r < sz); return &memory[r]; } Ref ael (const T* t) { assert((void*)t >= (void*)&memory[0] && (void*)t < (void*)&memory[sz-1]); return (Ref)(t - &memory[0]); } void moveTo(RegionAllocator& to) { if (to.memory != NULL) ::free(to.memory); to.memory = memory; to.sz = sz; to.cap = cap; to.wasted_ = wasted_; memory = NULL; sz = cap = wasted_ = 0; } }; template<class T> void RegionAllocator<T>::capacity(uint32_t min_cap) { if (cap >= min_cap) return; uint32_t prev_cap = cap; while (cap < min_cap){ // NOTE: Multiply by a factor (13/8) without causing overflow, then add 2 and make the // result even by clearing the least significant bit. The resulting sequence of capacities // is carefully chosen to hit a maximum capacity that is close to the '2^32-1' limit when // using 'uint32_t' as indices so that as much as possible of this space can be used. uint32_t delta = ((cap >> 1) + (cap >> 3) + 2) & ~1; cap += delta; if (cap <= prev_cap) throw OutOfMemoryException(); } //printf(" .. (%p) cap = %u\n", this, cap); assert(cap > 0); memory = (T*)xrealloc(memory, sizeof(T)*cap); } template<class T> typename RegionAllocator<T>::Ref RegionAllocator<T>::alloc(int size) { //printf("ALLOC called (this = %p, size = %d)\n", this, size); fflush(stdout); assert(size > 0); capacity(sz + size); uint32_t prev_sz = sz; sz += size; // Handle overflow: if (sz < prev_sz) throw OutOfMemoryException(); return prev_sz; } //================================================================================================= } #endif /******************************************************************************************[Heap.h] Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_Heap_h #define Ghack_Heap_h namespace GHack { //================================================================================================= // A heap implementation with support for decrease/increase key. template<class Comp> class Heap { Comp lt; // The heap is a minimum-heap with respect to this comparator vec<int> heap; // Heap of integers vec<int> indices; // Each integers position (index) in the Heap // Index "traversal" functions static inline int left (int i) { return i*2+1; } static inline int right (int i) { return (i+1)*2; } static inline int parent(int i) { return (i-1) >> 1; } void percolateUp(int i) { int x = heap[i]; int p = parent(i); while (i != 0 && lt(x, heap[p])){ heap[i] = heap[p]; indices[heap[p]] = i; i = p; p = parent(p); } heap [i] = x; indices[x] = i; } void percolateDown(int i) { int x = heap[i]; while (left(i) < heap.size()){ int child = right(i) < heap.size() && lt(heap[right(i)], heap[left(i)]) ? right(i) : left(i); if (!lt(heap[child], x)) break; heap[i] = heap[child]; indices[heap[i]] = i; i = child; } heap [i] = x; indices[x] = i; } public: Heap(const Comp& c) : lt(c) { } int size () const { return heap.size(); } bool empty () const { return heap.size() == 0; } bool inHeap (int n) const { return n < indices.size() && indices[n] >= 0; } int operator[](int index) const { assert(index < heap.size()); return heap[index]; } void decrease (int n) { assert(inHeap(n)); percolateUp (indices[n]); } void increase (int n) { assert(inHeap(n)); percolateDown(indices[n]); } // Safe variant of insert/decrease/increase: void update(int n) { if (!inHeap(n)) insert(n); else { percolateUp(indices[n]); percolateDown(indices[n]); } } void insert(int n) { indices.growTo(n+1, -1); assert(!inHeap(n)); indices[n] = heap.size(); heap.push(n); percolateUp(indices[n]); } int removeMin() { int x = heap[0]; heap[0] = heap.last(); indices[heap[0]] = 0; indices[x] = -1; heap.pop(); if (heap.size() > 1) percolateDown(0); return x; } // Rebuild the heap from scratch, using the elements in 'ns': void build(vec<int>& ns) { for (int i = 0; i < heap.size(); i++) indices[heap[i]] = -1; heap.clear(); for (int i = 0; i < ns.size(); i++){ indices[ns[i]] = i; heap.push(ns[i]); } for (int i = heap.size() / 2 - 1; i >= 0; i--) percolateDown(i); } void clear(bool dealloc = false) { for (int i = 0; i < heap.size(); i++) indices[heap[i]] = -1; heap.clear(dealloc); } }; //================================================================================================= } #endif /*******************************************************************************************[Map.h] Copyright (c) 2006-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_Map_h #define Ghack_Map_h namespace GHack { //================================================================================================= // Default hash/equals functions // template<class K> struct Hash { uint32_t operator()(const K& k) const { return hash(k); } }; template<class K> struct Equal { bool operator()(const K& k1, const K& k2) const { return k1 == k2; } }; template<class K> struct DeepHash { uint32_t operator()(const K* k) const { return hash(*k); } }; template<class K> struct DeepEqual { bool operator()(const K* k1, const K* k2) const { return *k1 == *k2; } }; static inline uint32_t hash(uint32_t x){ return x; } static inline uint32_t hash(uint64_t x){ return (uint32_t)x; } static inline uint32_t hash(int32_t x) { return (uint32_t)x; } static inline uint32_t hash(int64_t x) { return (uint32_t)x; } //================================================================================================= // Some primes // static const int nprimes = 25; static const int primes [nprimes] = { 31, 73, 151, 313, 643, 1291, 2593, 5233, 10501, 21013, 42073, 84181, 168451, 337219, 674701, 1349473, 2699299, 5398891, 10798093, 21596719, 43193641, 86387383, 172775299, 345550609, 691101253 }; //================================================================================================= // Hash table implementation of Maps // template<class K, class D, class H = Hash<K>, class E = Equal<K> > class Map { public: struct Pair { K key; D data; }; private: H hash; E equals; vec<Pair>* table; int cap; int size; // Don't allow copying (error prone): Map<K,D,H,E>& operator = (Map<K,D,H,E>& other) { assert(0); } Map (Map<K,D,H,E>& other) { assert(0); } bool checkCap(int new_size) const { return new_size > cap; } int32_t index (const K& k) const { return hash(k) % cap; } void _insert (const K& k, const D& d) { vec<Pair>& ps = table[index(k)]; ps.push(); ps.last().key = k; ps.last().data = d; } void rehash () { const vec<Pair>* old = table; int old_cap = cap; int newsize = primes[0]; for (int i = 1; newsize <= cap && i < nprimes; i++) newsize = primes[i]; table = new vec<Pair>[newsize]; cap = newsize; for (int i = 0; i < old_cap; i++){ for (int j = 0; j < old[i].size(); j++){ _insert(old[i][j].key, old[i][j].data); }} delete [] old; // printf(" --- rehashing, old-cap=%d, new-cap=%d\n", cap, newsize); } public: Map () : table(NULL), cap(0), size(0) {} Map (const H& h, const E& e) : hash(h), equals(e), table(NULL), cap(0), size(0){} ~Map () { delete [] table; } // PRECONDITION: the key must already exist in the map. const D& operator [] (const K& k) const { assert(size != 0); const D* res = NULL; const vec<Pair>& ps = table[index(k)]; for (int i = 0; i < ps.size(); i++) if (equals(ps[i].key, k)) res = &ps[i].data; assert(res != NULL); return *res; } // PRECONDITION: the key must already exist in the map. D& operator [] (const K& k) { assert(size != 0); D* res = NULL; vec<Pair>& ps = table[index(k)]; for (int i = 0; i < ps.size(); i++) if (equals(ps[i].key, k)) res = &ps[i].data; assert(res != NULL); return *res; } // PRECONDITION: the key must *NOT* exist in the map. void insert (const K& k, const D& d) { if (checkCap(size+1)) rehash(); _insert(k, d); size++; } bool peek (const K& k, D& d) const { if (size == 0) return false; const vec<Pair>& ps = table[index(k)]; for (int i = 0; i < ps.size(); i++) if (equals(ps[i].key, k)){ d = ps[i].data; return true; } return false; } bool has (const K& k) const { if (size == 0) return false; const vec<Pair>& ps = table[index(k)]; for (int i = 0; i < ps.size(); i++) if (equals(ps[i].key, k)) return true; return false; } // PRECONDITION: the key must exist in the map. void remove(const K& k) { assert(table != NULL); vec<Pair>& ps = table[index(k)]; int j = 0; for (; j < ps.size() && !equals(ps[j].key, k); j++); assert(j < ps.size()); ps[j] = ps.last(); ps.pop(); size--; } void clear () { cap = size = 0; delete [] table; table = NULL; } int elems() const { return size; } int bucket_count() const { return cap; } // NOTE: the hash and equality objects are not moved by this method: void moveTo(Map& other){ delete [] other.table; other.table = table; other.cap = cap; other.size = size; table = NULL; size = cap = 0; } // NOTE: given a bit more time, I could make a more C++-style iterator out of this: const vec<Pair>& bucket(int i) const { return table[i]; } }; //================================================================================================= } #endif /*****************************************************************************************[Queue.h] Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_Queue_h #define Ghack_Queue_h namespace GHack { //================================================================================================= template<class T> class Queue { vec<T> buf; int first; int end; public: typedef T Key; Queue() : buf(1), first(0), end(0) {} void clear (bool dealloc = false) { buf.clear(dealloc); buf.growTo(1); first = end = 0; } int size () const { return (end >= first) ? end - first : end - first + buf.size(); } const T& operator [] (int index) const { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; } T& operator [] (int index) { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; } T peek () const { assert(first != end); return buf[first]; } void pop () { assert(first != end); first++; if (first == buf.size()) first = 0; } void insert(T elem) { // INVARIANT: buf[end] is always unused buf[end++] = elem; if (end == buf.size()) end = 0; if (first == end){ // Resize: vec<T> tmp((buf.size()*3 + 1) >> 1); //**/printf("queue alloc: %d elems (%.1f MB)\n", tmp.size(), tmp.size() * sizeof(T) / 1000000.0); int i = 0; for (int j = first; j < buf.size(); j++) tmp[i++] = buf[j]; for (int j = 0 ; j < end ; j++) tmp[i++] = buf[j]; first = 0; end = buf.size(); tmp.moveTo(buf); } } }; //================================================================================================= } #endif /******************************************************************************************[Sort.h] Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_Sort_h #define Ghack_Sort_h //================================================================================================= // Some sorting algorithms for vec's namespace GHack { template<class T> struct LessThan_default { bool operator () (T x, T y) { return x < y; } }; template <class T, class LessThan> void selectionSort(T* array, int size, LessThan lt) { int i, j, best_i; T tmp; for (i = 0; i < size-1; i++){ best_i = i; for (j = i+1; j < size; j++){ if (lt(array[j], array[best_i])) best_i = j; } tmp = array[i]; array[i] = array[best_i]; array[best_i] = tmp; } } template <class T> static inline void selectionSort(T* array, int size) { selectionSort(array, size, LessThan_default<T>()); } template <class T, class LessThan> void sort(T* array, int size, LessThan lt) { if (size <= 15) selectionSort(array, size, lt); else{ T pivot = array[size / 2]; T tmp; int i = -1; int j = size; for(;;){ do i++; while(lt(array[i], pivot)); do j--; while(lt(pivot, array[j])); if (i >= j) break; tmp = array[i]; array[i] = array[j]; array[j] = tmp; } sort(array , i , lt); sort(&array[i], size-i, lt); } } template <class T> static inline void sort(T* array, int size) { sort(array, size, LessThan_default<T>()); } //================================================================================================= // For 'vec's: template <class T, class LessThan> void sort(vec<T>& v, LessThan lt) { sort((T*)v, v.size(), lt); } template <class T> void sort(vec<T>& v) { sort(v, LessThan_default<T>()); } //================================================================================================= } #endif /************************************************************************************[ParseUtils.h] Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_ParseUtils_h #define Ghack_ParseUtils_h #include <stdlib.h> #include <stdio.h> #include <math.h> namespace GHack { //------------------------------------------------------------------------------------------------- // End-of-file detection functions for StreamBuffer and char*: static inline bool isEof(const char* in) { return *in == '\0'; } //------------------------------------------------------------------------------------------------- // Generic parse functions parametrized over the input-stream type. template<class B> static void skipWhitespace(B& in) { while ((*in >= 9 && *in <= 13) || *in == 32) ++in; } template<class B> static void skipLine(B& in) { for (;;){ if (isEof(in)) return; if (*in == '\n') { ++in; return; } ++in; } } template<class B> static double parseDouble(B& in) { // only in the form X.XXXXXe-XX bool neg= false; double accu = 0.0; double currentExponent = 1; int exponent; skipWhitespace(in); if(*in == EOF) return 0; if (*in == '-') neg = true, ++in; else if (*in == '+') ++in; if (*in < '1' || *in > '9') printf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3); accu = (double)(*in - '0'); ++in; if (*in != '.') printf("PARSE ERROR! Unexpected char: %c\n", *in),exit(3); ++in; // skip dot currentExponent = 0.1; while (*in >= '0' && *in <= '9') accu = accu + currentExponent * ((double)(*in - '0')), currentExponent /= 10, ++in; if (*in != 'e') printf("PARSE ERROR! Unexpected char: %c\n", *in),exit(3); ++in; // skip dot exponent = parseInt(in); // read exponent accu *= pow(10,exponent); return neg ? -accu:accu; } template<class B> static int parseInt(B& in) { int val = 0; bool neg = false; skipWhitespace(in); if (*in == '-') neg = true, ++in; else if (*in == '+') ++in; if (*in < '0' || *in > '9') fprintf(stderr, "PARSE ERROR! Unexpected char: %c\n", *in), exit(3); while (*in >= '0' && *in <= '9') val = val*10 + (*in - '0'), ++in; return neg ? -val : val; } // String matching: in case of a match the input iterator will be advanced the corresponding // number of characters. template<class B> static bool match(B& in, const char* str) { int i; for (i = 0; str[i] != '\0'; i++) if (in[i] != str[i]) return false; in += i; return true; } // String matching: consumes characters eagerly, but does not require random access iterator. template<class B> static bool eagerMatch(B& in, const char* str) { for (; *str != '\0'; ++str, ++in) if (*str != *in) return false; return true; } //================================================================================================= } #endif /***************************************************************************************[Options.h] Copyright (c) 2008-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_Options_h #define Ghack_Options_h #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> namespace GHack { //================================================================================================== // Top-level option parse/help functions: extern void parseOptions (int& argc, char** argv, bool strict = false); extern void printUsageAndExit(int argc, char** argv, bool verbose = false); extern void setUsageHelp (const char* str); extern void setHelpPrefixStr (const char* str); //================================================================================================== // Options is an abstract class that gives the interface for all types options: class Option { protected: const char* name; const char* description; const char* category; const char* type_name; static vec<Option*>& getOptionList () { static vec<Option*> options; return options; } static const char*& getUsageString() { static const char* usage_str; return usage_str; } static const char*& getHelpPrefixString() { static const char* help_prefix_str = ""; return help_prefix_str; } struct OptionLt { bool operator()(const Option* x, const Option* y) { int test1 = strcmp(x->category, y->category); return test1 < 0 || (test1 == 0 && strcmp(x->type_name, y->type_name) < 0); } }; Option(const char* name_, const char* desc_, const char* cate_, const char* type_) : name (name_) , description(desc_) , category (cate_) , type_name (type_) { getOptionList().push(this); } public: virtual ~Option() {} virtual bool parse (const char* str) = 0; virtual void help (bool verbose = false) = 0; friend void parseOptions (int& argc, char** argv, bool strict); friend void printUsageAndExit (int argc, char** argv, bool verbose); friend void setUsageHelp (const char* str); friend void setHelpPrefixStr (const char* str); }; //================================================================================================== // Range classes with specialization for floating types: struct IntRange { int begin; int end; IntRange(int b, int e) : begin(b), end(e) {} }; struct Int64Range { int64_t begin; int64_t end; Int64Range(int64_t b, int64_t e) : begin(b), end(e) {} }; struct DoubleRange { double begin; double end; bool begin_inclusive; bool end_inclusive; DoubleRange(double b, bool binc, double e, bool einc) : begin(b), end(e), begin_inclusive(binc), end_inclusive(einc) {} }; //================================================================================================== // Double options: class DoubleOption : public Option { protected: DoubleRange range; double value; public: DoubleOption(const char* c, const char* n, const char* d, double def = double(), DoubleRange r = DoubleRange(-HUGE_VAL, false, HUGE_VAL, false)) : Option(n, d, c, "<double>"), range(r), value(def) { // FIXME: set LC_NUMERIC to "C" to make sure that strtof/strtod parses decimal point correctly. } operator double (void) const { return value; } operator double& (void) { return value; } DoubleOption& operator=(double x) { value = x; return *this; } virtual bool parse(const char* str){ const char* span = str; if (!match(span, "-") || !match(span, name) || !match(span, "=")) return false; char* end; double tmp = strtod(span, &end); if (end == NULL) return false; else if (tmp >= range.end && (!range.end_inclusive || tmp != range.end)){ fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name); exit(1); }else if (tmp <= range.begin && (!range.begin_inclusive || tmp != range.begin)){ fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name); exit(1); } value = tmp; // fprintf(stderr, "READ VALUE: %g\n", value); return true; } virtual void help (bool verbose = false){ fprintf(stderr, " -%-12s = %-8s %c%4.2g .. %4.2g%c (default: %g)\n", name, type_name, range.begin_inclusive ? '[' : '(', range.begin, range.end, range.end_inclusive ? ']' : ')', value); if (verbose){ fprintf(stderr, "\n %s\n", description); fprintf(stderr, "\n"); } } }; //================================================================================================== // Int options: class IntOption : public Option { protected: IntRange range; int32_t value; public: IntOption(const char* c, const char* n, const char* d, int32_t def = int32_t(), IntRange r = IntRange(INT32_MIN, INT32_MAX)) : Option(n, d, c, "<int32>"), range(r), value(def) {} operator int32_t (void) const { return value; } operator int32_t& (void) { return value; } IntOption& operator= (int32_t x) { value = x; return *this; } virtual bool parse(const char* str){ const char* span = str; if (!match(span, "-") || !match(span, name) || !match(span, "=")) return false; char* end; int32_t tmp = strtol(span, &end, 10); if (end == NULL) return false; else if (tmp > range.end){ fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name); exit(1); }else if (tmp < range.begin){ fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name); exit(1); } value = tmp; return true; } virtual void help (bool verbose = false){ fprintf(stderr, " -%-12s = %-8s [", name, type_name); if (range.begin == INT32_MIN) fprintf(stderr, "imin"); else fprintf(stderr, "%4d", range.begin); fprintf(stderr, " .. "); if (range.end == INT32_MAX) fprintf(stderr, "imax"); else fprintf(stderr, "%4d", range.end); fprintf(stderr, "] (default: %d)\n", value); if (verbose){ fprintf(stderr, "\n %s\n", description); fprintf(stderr, "\n"); } } }; // Leave this out for visual C++ until Microsoft implements C99 and gets support for strtoll. #ifndef _MSC_VER class Int64Option : public Option { protected: Int64Range range; int64_t value; public: Int64Option(const char* c, const char* n, const char* d, int64_t def = int64_t(), Int64Range r = Int64Range(INT64_MIN, INT64_MAX)) : Option(n, d, c, "<int64>"), range(r), value(def) {} operator int64_t (void) const { return value; } operator int64_t& (void) { return value; } Int64Option& operator= (int64_t x) { value = x; return *this; } virtual bool parse(const char* str){ const char* span = str; if (!match(span, "-") || !match(span, name) || !match(span, "=")) return false; char* end; int64_t tmp = strtoll(span, &end, 10); if (end == NULL) return false; else if (tmp > range.end){ fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name); exit(1); }else if (tmp < range.begin){ fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name); exit(1); } value = tmp; return true; } virtual void help (bool verbose = false){ fprintf(stderr, " -%-12s = %-8s [", name, type_name); if (range.begin == INT64_MIN) fprintf(stderr, "imin"); else fprintf(stderr, "%4" PRIi64, range.begin); fprintf(stderr, " .. "); if (range.end == INT64_MAX) fprintf(stderr, "imax"); else fprintf(stderr, "%4" PRIi64, range.end); fprintf(stderr, "] (default: %" PRIi64")\n", value); if (verbose){ fprintf(stderr, "\n %s\n", description); fprintf(stderr, "\n"); } } }; #endif //================================================================================================== // String option: class StringOption : public Option { const char* value; public: StringOption(const char* c, const char* n, const char* d, const char* def = NULL) : Option(n, d, c, "<string>"), value(def) {} operator const char* (void) const { return value; } operator const char*& (void) { return value; } StringOption& operator= (const char* x) { value = x; return *this; } virtual bool parse(const char* str){ const char* span = str; if (!match(span, "-") || !match(span, name) || !match(span, "=")) return false; value = span; return true; } virtual void help (bool verbose = false){ fprintf(stderr, " -%-10s = %8s\n", name, type_name); if (verbose){ fprintf(stderr, "\n %s\n", description); fprintf(stderr, "\n"); } } }; //================================================================================================== // Bool option: class BoolOption : public Option { bool value; public: BoolOption(const char* c, const char* n, const char* d, bool v) : Option(n, d, c, "<bool>"), value(v) {} operator bool (void) const { return value; } operator bool& (void) { return value; } BoolOption& operator=(bool b) { value = b; return *this; } virtual bool parse(const char* str){ const char* span = str; if (match(span, "-")){ bool b = !match(span, "no-"); if (strcmp(span, name) == 0){ value = b; return true; } } return false; } virtual void help (bool verbose = false){ fprintf(stderr, " -%s, -no-%s", name, name); for (uint32_t i = 0; i < 32 - strlen(name)*2; i++) fprintf(stderr, " "); fprintf(stderr, " "); fprintf(stderr, "(default: %s)\n", value ? "on" : "off"); if (verbose){ fprintf(stderr, "\n %s\n", description); fprintf(stderr, "\n"); } } }; //================================================================================================= } #endif /****************************************************************************************[System.h] Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_System_h #define Ghack_System_h //------------------------------------------------------------------------------------------------- namespace GHack { static inline double cpuTime(void); // CPU-time in seconds. extern double memUsed(); // Memory in mega bytes (returns 0 for unsupported architectures). extern double memUsedPeak(); // Peak-memory in mega bytes (returns 0 for unsupported architectures). } //------------------------------------------------------------------------------------------------- // Implementation of inline functions: #if defined(_MSC_VER) || defined(__MINGW32__) #include <time.h> static inline double GHack::cpuTime(void) { return (double)clock() / CLOCKS_PER_SEC; } #else #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> static inline double GHack::cpuTime(void) { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000; } #endif #endif /***********************************************************************************[SolverTypes.h] Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon CRIL - Univ. Artois, France LRI - Univ. Paris Sud, France Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of Glucose are exactly the same as Minisat on which it is based on. (see below). --------------- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_SolverTypes_h #define Ghack_SolverTypes_h #include <assert.h> namespace GHack { //================================================================================================= // Variables, literals, lifted booleans, clauses: // NOTE! Variables are just integers. No abstraction here. They should be chosen from 0..N, // so that they can be used as array indices. typedef int Var; #define var_Undef (-1) struct Lit { int x; // Use this as a constructor: friend Lit mkLit(Var var, bool sign); bool operator == (Lit p) const { return x == p.x; } bool operator != (Lit p) const { return x != p.x; } bool operator < (Lit p) const { return x < p.x; } // '<' makes p, ~p adjacent in the ordering. }; inline Lit mkLit (Var var, bool sign = false) { Lit p; p.x = var + var + (int)sign; return p; } inline Lit operator ~(Lit p) { Lit q; q.x = p.x ^ 1; return q; } inline Lit operator ^(Lit p, bool b) { Lit q; q.x = p.x ^ (unsigned int)b; return q; } inline bool sign (Lit p) { return p.x & 1; } inline int var (Lit p) { return p.x >> 1; } // Mapping Literals to and from compact integers suitable for array indexing: inline int toInt (Var v) { return v; } inline int toInt (Lit p) { return p.x; } inline Lit toLit (int i) { Lit p; p.x = i; return p; } //const Lit lit_Undef = mkLit(var_Undef, false); // }- Useful special constants. //const Lit lit_Error = mkLit(var_Undef, true ); // } const Lit lit_Undef = { -2 }; // }- Useful special constants. const Lit lit_Error = { -1 }; // } //================================================================================================= // Lifted booleans: // // NOTE: this implementation is optimized for the case when comparisons between values are mostly // between one variable and one constant. Some care had to be taken to make sure that gcc // does enough constant propagation to produce sensible code, and this appears to be somewhat // fragile unfortunately. class lbool { uint8_t value; public: constexpr explicit lbool(uint8_t v) : value(v) { } lbool() : value(0) { } explicit lbool(bool x) : value(!x) { } bool operator == (lbool b) const { return ((b.value&2) & (value&2)) | (!(b.value&2)&(value == b.value)); } bool operator != (lbool b) const { return !(*this == b); } lbool operator ^ (bool b) const { return lbool((uint8_t)(value^(uint8_t)b)); } lbool operator && (lbool b) const { uint8_t sel = (this->value << 1) | (b.value << 3); uint8_t v = (0xF7F755F4 >> sel) & 3; return lbool(v); } lbool operator || (lbool b) const { uint8_t sel = (this->value << 1) | (b.value << 3); uint8_t v = (0xFCFCF400 >> sel) & 3; return lbool(v); } friend int toInt (lbool l); friend lbool toLbool(int v); }; inline int toInt (lbool l) { return l.value; } inline lbool toLbool(int v) { return lbool((uint8_t)v); } constexpr auto l_True = GHack::lbool((uint8_t)0); constexpr auto l_False = GHack::lbool((uint8_t)1); constexpr auto l_Undef = GHack::lbool((uint8_t)2); //================================================================================================= // Clause -- a simple class for representing a clause: struct Clause; typedef RegionAllocator<uint32_t>::Ref CRef; struct Clause { int t; struct { unsigned mark : 2; unsigned learnt : 1; unsigned has_extra : 1; unsigned reloced : 1; unsigned lbd : 26; unsigned canbedel : 1; unsigned size : 32; unsigned szWithoutSelectors : 32; } header; union { Lit lit; float act; uint32_t abs; CRef rel; } data[0]; friend class ClauseAllocator; // NOTE: This constructor cannot be used directly (doesn't allocate enough memory). template<class V> Clause(const V& ps, bool use_extra, bool learnt) { header.mark = t = 0; header.learnt = learnt; header.has_extra = use_extra; header.reloced = 0; header.size = ps.size(); header.lbd = 0; header.canbedel = 1; for (int i = 0; i < ps.size(); i++) data[i].lit = ps[i]; if (header.has_extra){ if (header.learnt) data[header.size].act = 0; else calcAbstraction(); } } public: void calcAbstraction() { assert(header.has_extra); uint32_t abstraction = 0; for (int i = 0; i < size(); i++) abstraction |= 1 << (var(data[i].lit) & 31); data[header.size].abs = abstraction; } int size () const { return header.size; } void shrink (int i) { assert(i <= size()); if (header.has_extra) data[header.size-i] = data[header.size]; header.size -= i; } void pop () { shrink(1); } bool learnt () const { return header.learnt; } bool has_extra () const { return header.has_extra; } uint32_t mark () const { return header.mark; } void mark (uint32_t m) { header.mark = m; } const Lit& last () const { return data[header.size-1].lit; } bool reloced () const { return header.reloced; } CRef relocation () const { return data[0].rel; } void relocate (CRef c) { header.reloced = 1; data[0].rel = c; } // NOTE: somewhat unsafe to change the clause in-place! Must manually call 'calcAbstraction' afterwards for // subsumption operations to behave correctly. Lit& operator [] (int i) { return data[i].lit; } Lit operator [] (int i) const { return data[i].lit; } operator const Lit* (void) const { return (Lit*)data; } float& activity () { assert(header.has_extra); return data[header.size].act; } uint32_t abstraction () const { assert(header.has_extra); return data[header.size].abs; } Lit subsumes (const Clause& other) const; void strengthen (Lit p); void setLBD(int i) {header.lbd = i;} // unsigned int& lbd () { return header.lbd; } unsigned int lbd () const { return header.lbd; } void setCanBeDel(bool b) {header.canbedel = b;} bool canBeDel() {return header.canbedel;} void setSizeWithoutSelectors (unsigned int n) {header.szWithoutSelectors = n; } unsigned int sizeWithoutSelectors () const { return header.szWithoutSelectors; } }; //================================================================================================= // ClauseAllocator -- a simple class for allocating memory for clauses: const CRef CRef_Undef = RegionAllocator<uint32_t>::Ref_Undef; class ClauseAllocator : public RegionAllocator<uint32_t> { static int clauseWord32Size(int size, bool has_extra){ return (sizeof(Clause) + (sizeof(Lit) * (size + (int)has_extra))) / sizeof(uint32_t); } public: bool extra_clause_field; ClauseAllocator(uint32_t start_cap) : RegionAllocator<uint32_t>(start_cap), extra_clause_field(false){} ClauseAllocator() : extra_clause_field(false){} void moveTo(ClauseAllocator& to){ to.extra_clause_field = extra_clause_field; RegionAllocator<uint32_t>::moveTo(to); } template<class Lits> CRef alloc(const Lits& ps, bool learnt = false) { assert(sizeof(Lit) == sizeof(uint32_t)); assert(sizeof(float) == sizeof(uint32_t)); bool use_extra = learnt | extra_clause_field; CRef cid = RegionAllocator<uint32_t>::alloc(clauseWord32Size(ps.size(), use_extra)); new (lea(cid)) Clause(ps, use_extra, learnt); return cid; } // Deref, Load Effective Address (LEA), Inverse of LEA (AEL): Clause& operator[](Ref r) { return (Clause&)RegionAllocator<uint32_t>::operator[](r); } const Clause& operator[](Ref r) const { return (Clause&)RegionAllocator<uint32_t>::operator[](r); } Clause* lea (Ref r) { return (Clause*)RegionAllocator<uint32_t>::lea(r); } const Clause* lea (Ref r) const { return (Clause*)RegionAllocator<uint32_t>::lea(r); } Ref ael (const Clause* t){ return RegionAllocator<uint32_t>::ael((uint32_t*)t); } void free(CRef cid) { Clause& c = operator[](cid); RegionAllocator<uint32_t>::free(clauseWord32Size(c.size(), c.has_extra())); } void reloc(CRef& cr, ClauseAllocator& to) { Clause& c = operator[](cr); if (c.reloced()) { cr = c.relocation(); return; } cr = to.alloc(c, c.learnt()); c.relocate(cr); // Copy extra data-fields: // (This could be cleaned-up. Generalize Clause-constructor to be applicable here instead?) to[cr].mark(c.mark()); if (to[cr].learnt()) { to[cr].t = c.t; to[cr].activity() = c.activity(); to[cr].setLBD(c.lbd()); to[cr].setSizeWithoutSelectors(c.sizeWithoutSelectors()); to[cr].setCanBeDel(c.canBeDel()); } else if (to[cr].has_extra()) to[cr].calcAbstraction(); } }; //================================================================================================= // OccLists -- a class for maintaining occurence lists with lazy deletion: template<class Idx, class Vec, class Deleted> class OccLists { vec<Vec> occs; vec<char> dirty; vec<Idx> dirties; Deleted deleted; public: OccLists(const Deleted& d) : deleted(d) {} void init (const Idx& idx){ occs.growTo(toInt(idx)+1); dirty.growTo(toInt(idx)+1, 0); } // Vec& operator[](const Idx& idx){ return occs[toInt(idx)]; } Vec& operator[](const Idx& idx){ return occs[toInt(idx)]; } Vec& lookup (const Idx& idx){ if (dirty[toInt(idx)]) clean(idx); return occs[toInt(idx)]; } void cleanAll (); void clean (const Idx& idx); void smudge (const Idx& idx){ if (dirty[toInt(idx)] == 0){ dirty[toInt(idx)] = 1; dirties.push(idx); } } void clear(bool free = true){ occs .clear(free); dirty .clear(free); dirties.clear(free); } }; template<class Idx, class Vec, class Deleted> void OccLists<Idx,Vec,Deleted>::cleanAll() { for (int i = 0; i < dirties.size(); i++) // Dirties may contain duplicates so check here if a variable is already cleaned: if (dirty[toInt(dirties[i])]) clean(dirties[i]); dirties.clear(); } template<class Idx, class Vec, class Deleted> void OccLists<Idx,Vec,Deleted>::clean(const Idx& idx) { Vec& vec = occs[toInt(idx)]; int i, j; for (i = j = 0; i < vec.size(); i++) if (!deleted(vec[i])) vec[j++] = vec[i]; vec.shrink(i - j); dirty[toInt(idx)] = 0; } //================================================================================================= // CMap -- a class for mapping clauses to values: template<class T> class CMap { struct CRefHash { uint32_t operator()(CRef cr) const { return (uint32_t)cr; } }; typedef Map<CRef, T, CRefHash> HashTable; HashTable map; public: // Size-operations: void clear () { map.clear(); } int size () const { return map.elems(); } // Insert/Remove/Test mapping: void insert (CRef cr, const T& t){ map.insert(cr, t); } void growTo (CRef cr, const T& t){ map.insert(cr, t); } // NOTE: for compatibility void remove (CRef cr) { map.remove(cr); } bool has (CRef cr, T& t) { return map.peek(cr, t); } // Vector interface (the clause 'c' must already exist): const T& operator [] (CRef cr) const { return map[cr]; } T& operator [] (CRef cr) { return map[cr]; } // Iteration (not transparent at all at the moment): int bucket_count() const { return map.bucket_count(); } const vec<typename HashTable::Pair>& bucket(int i) const { return map.bucket(i); } // Move contents to other map: void moveTo(CMap& other){ map.moveTo(other.map); } // TMP debug: void debug(){ printf(" --- size = %d, bucket_count = %d\n", size(), map.bucket_count()); } }; /*_________________________________________________________________________________________________ | | subsumes : (other : const Clause&) -> Lit | | Description: | Checks if clause subsumes 'other', and at the same time, if it can be used to simplify 'other' | by subsumption resolution. | | Result: | lit_Error - No subsumption or simplification | lit_Undef - Clause subsumes 'other' | p - The literal p can be deleted from 'other' |________________________________________________________________________________________________@*/ inline Lit Clause::subsumes(const Clause& other) const { //if (other.size() < size() || (extra.abst & ~other.extra.abst) != 0) //if (other.size() < size() || (!learnt() && !other.learnt() && (extra.abst & ~other.extra.abst) != 0)) assert(!header.learnt); assert(!other.header.learnt); assert(header.has_extra); assert(other.header.has_extra); if (other.header.size < header.size || (data[header.size].abs & ~other.data[other.header.size].abs) != 0) return lit_Error; Lit ret = lit_Undef; const Lit* c = (const Lit*)(*this); const Lit* d = (const Lit*)other; for (unsigned i = 0; i < header.size; i++) { // search for c[i] or ~c[i] for (unsigned j = 0; j < other.header.size; j++) if (c[i] == d[j]) goto ok; else if (ret == lit_Undef && c[i] == ~d[j]){ ret = c[i]; goto ok; } // did not find it return lit_Error; ok:; } return ret; } inline void Clause::strengthen(Lit p) { remove(*this, p); calcAbstraction(); } //================================================================================================= } #endif /***********************************************************************************[BoundedQueue.h] Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon CRIL - Univ. Artois, France LRI - Univ. Paris Sud, France Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef BoundedQueue_h #define BoundedQueue_h //================================================================================================= namespace GHack { template <class T> class bqueue { vec<T> elems; int first; int last; unsigned long long sumofqueue; int maxsize; int queuesize; // Number of current elements (must be < maxsize !) bool expComputed; double exp,value; public: bqueue(void) : first(0), last(0), sumofqueue(0), maxsize(0), queuesize(0),expComputed(false) { } void initSize(int size) {growTo(size);exp = 2.0/(size+1);} // Init size of bounded size queue void push(T x) { expComputed = false; if (queuesize==maxsize) { assert(last==first); // The queue is full, next value to enter will replace oldest one sumofqueue -= elems[last]; if ((++last) == maxsize) last = 0; } else queuesize++; sumofqueue += x; elems[first] = x; if ((++first) == maxsize) {first = 0;last = 0;} } T peek() { assert(queuesize>0); return elems[last]; } void pop() {sumofqueue-=elems[last]; queuesize--; if ((++last) == maxsize) last = 0;} unsigned long long getsum() const {return sumofqueue;} unsigned int getavg() const {return (unsigned int)(sumofqueue/((unsigned long long)queuesize));} int maxSize() const {return maxsize;} double getavgDouble() const { double tmp = 0; for(int i=0;i<elems.size();i++) { tmp+=elems[i]; } return tmp/elems.size(); } int isvalid() const {return (queuesize==maxsize);} void growTo(int size) { elems.growTo(size); first=0; maxsize=size; queuesize = 0;last = 0; for(int i=0;i<size;i++) elems[i]=0; } double getAvgExp() { if(expComputed) return value; double a=exp; value = elems[first]; for(int i = first;i<maxsize;i++) { value+=a*((double)elems[i]); a=a*exp; } for(int i = 0;i<last;i++) { value+=a*((double)elems[i]); a=a*exp; } value = value*(1-exp)/(1-a); expComputed = true; return value; } void fastclear() {first = 0; last = 0; queuesize=0; sumofqueue=0;} // to be called after restarts... Discard the queue int size(void) { return queuesize; } void clear(bool dealloc = false) { elems.clear(dealloc); first = 0; maxsize=0; queuesize=0;sumofqueue=0;} }; } //================================================================================================= #endif /************************************************************************************[Constants.h] Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon CRIL - Univ. Artois, France LRI - Univ. Paris Sud, France Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #define DYNAMICNBLEVEL #define CONSTANTREMOVECLAUSE #define UPDATEVARACTIVITY // Constants for clauses reductions #define RATIOREMOVECLAUSES 2 // Constants for restarts #define LOWER_BOUND_FOR_BLOCKING_RESTART 10000 /****************************************************************************************[Solver.h] Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon CRIL - Univ. Artois, France LRI - Univ. Paris Sud, France Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of Glucose are exactly the same as Minisat on which it is based on. (see below). --------------- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_Solver_h #define Ghack_Solver_h namespace GHack { //================================================================================================= // Solver -- the main class: class Solver { public: // Constructor/Destructor: // Solver(); virtual ~Solver(); // Problem specification: // Var newVar (bool polarity = true, bool dvar = true); // Add a new variable with parameters specifying variable mode. bool addClause (const vec<Lit>& ps); // Add a clause to the solver. bool addEmptyClause(); // Add the empty clause, making the solver contradictory. bool addClause (Lit p); // Add a unit clause to the solver. bool addClause (Lit p, Lit q); // Add a binary clause to the solver. bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver. bool addClause_( vec<Lit>& ps); // Add a clause to the solver without making superflous internal copy. Will // change the passed vector 'ps'. // Solving: // bool simplify (); // Removes already satisfied clauses. bool solve (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions. lbool solveLimited (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions (With resource constraints). bool solve (); // Search without assumptions. bool solve (Lit p); // Search for a model that respects a single assumption. bool solve (Lit p, Lit q); // Search for a model that respects two assumptions. bool solve (Lit p, Lit q, Lit r); // Search for a model that respects three assumptions. bool okay () const; // FALSE means solver is in a conflicting state void toDimacs (FILE* f, const vec<Lit>& assumps); // Write CNF to file in DIMACS-format. void toDimacs (const char *file, const vec<Lit>& assumps); void toDimacs (FILE* f, Clause& c, vec<Var>& map, Var& max); void printLit(Lit l); void printClause(CRef c); void printInitialClause(CRef c); // Convenience versions of 'toDimacs()': void toDimacs (const char* file); void toDimacs (const char* file, Lit p); void toDimacs (const char* file, Lit p, Lit q); void toDimacs (const char* file, Lit p, Lit q, Lit r); // Variable mode: // void setPolarity (Var v, bool b); // Declare which polarity the decision heuristic should use for a variable. Requires mode 'polarity_user'. void setDecisionVar (Var v, bool b); // Declare if a variable should be eligible for selection in the decision heuristic. // Read state: // lbool value (Var x) const; // The current value of a variable. lbool value (Lit p) const; // The current value of a literal. lbool modelValue (Var x) const; // The value of a variable in the last model. The last call to solve must have been satisfiable. lbool modelValue (Lit p) const; // The value of a literal in the last model. The last call to solve must have been satisfiable. int nAssigns () const; // The current number of assigned literals. int nClauses () const; // The current number of original clauses. int nLearnts () const; // The current number of learnt clauses. int nVars () const; // The current number of variables. int nFreeVars () const; // Incremental mode void setIncrementalMode(); void initNbInitialVars(int nb); void printIncrementalStats(); // Resource contraints: // void setConfBudget(int64_t x); void setPropBudget(int64_t x); void budgetOff(); void interrupt(); // Trigger a (potentially asynchronous) interruption of the solver. void clearInterrupt(); // Clear interrupt indicator flag. // Memory managment: // virtual void garbageCollect(); void checkGarbage(double gf); void checkGarbage(); // Extra results: (read-only member variable) // vec<lbool> model; // If problem is satisfiable, this vector contains the model (if any). vec<Lit> conflict; // If problem is unsatisfiable (possibly under assumptions), // this vector represent the final conflict clause expressed in the assumptions. // Mode of operation: // int verbosity; int verbEveryConflicts; int showModel; // Constants For restarts double K; double R; double sizeLBDQueue; double sizeTrailQueue; // Constants for reduce DB int firstReduceDB; int incReduceDB; int specialIncReduceDB,I,O,G,H,Y,Z,A,e; unsigned int lbLBDFrozenClause; // Constant for reducing clause int lbSizeMinimizingClause; unsigned int lbLBDMinimizingClause; double var_decay; double clause_decay; double random_var_freq; double random_seed; int ccmin_mode; // Controls conflict clause minimization (0=none, 1=basic, 2=deep). int phase_saving; // Controls the level of phase saving (0=none, 1=limited, 2=full). bool rnd_pol; // Use random polarities for branching heuristics. bool rnd_init_act; // Initialize variable activities with a small random value. double garbage_frac; // The fraction of wasted memory allowed before a garbage collection is triggered. // Certified UNSAT ( Thanks to Marijn Heule) FILE* certifiedOutput; bool certifiedUNSAT; bool vbyte; void write_char (unsigned char c); void write_lit (int n); // Statistics: (read-only member variable) // uint64_t nbRemovedClauses,nbReducedClauses,nbDL2,nbBin,nbUn,nbReduceDB,solves, starts, decisions, rnd_decisions, propagations, conflicts,conflictsRestarts,nbstopsrestarts,nbstopsrestartssame,lastblockatrestart; uint64_t dec_vars, clauses_literals, learnts_literals, max_literals, tot_literals; protected: long curRestart; // Helper structures: // struct VarData { CRef reason; int level; }; static inline VarData mkVarData(CRef cr, int l){ VarData d = {cr, l}; return d; } struct Watcher { CRef cref; Lit blocker; Watcher(CRef cr, Lit p) : cref(cr), blocker(p) {} bool operator==(const Watcher& w) const { return cref == w.cref; } bool operator!=(const Watcher& w) const { return cref != w.cref; } }; struct WatcherDeleted { const ClauseAllocator& ca; WatcherDeleted(const ClauseAllocator& _ca) : ca(_ca) {} bool operator()(const Watcher& w) const { return ca[w.cref].mark() == 1; } }; struct VarOrderLt { const vec<double>& activity; bool operator () (Var x, Var y) const { return activity[x] > activity[y]; } VarOrderLt(const vec<double>& act) : activity(act) { } }; // Solver state: // int lastIndexRed; bool ok; // If FALSE, the constraints are already unsatisfiable. No part of the solver state may be used! double cla_inc; // Amount to bump next clause with. vec<double> activity; // A heuristic measurement of the activity of a variable. double var_inc; // Amount to bump next variable with. OccLists<Lit, vec<Watcher>, WatcherDeleted> watches; // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true). OccLists<Lit, vec<Watcher>, WatcherDeleted> watchesBin; // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true). vec<CRef> clauses; // List of problem clauses. vec<CRef> learnts,C,T; // List of learnt clauses. vec<lbool> assigns; // The current assignments. vec<char> polarity; // The preferred polarity of each variable. vec<char> decision; // Declares if a variable is eligible for selection in the decision heuristic. vec<Lit> trail; // Assignment stack; stores all assigments made in the order they were made. vec<int> nbpos; vec<int> trail_lim; // Separator indices for different decision levels in 'trail'. vec<VarData> vardata; // Stores reason and level for each variable. int qhead; // Head of queue (as index into the trail -- no more explicit propagation queue in MiniSat). int simpDB_assigns; // Number of top-level assignments since last execution of 'simplify()'. int64_t simpDB_props; // Remaining number of propagations that must be made before next execution of 'simplify()'. vec<Lit> assumptions; // Current set of assumptions provided to solve by the user. Heap<VarOrderLt> order_heap; // A priority queue of variables ordered with respect to the variable activity. double progress_estimate;// Set by 'search()'. bool remove_satisfied; // Indicates whether possibly inefficient linear scan for satisfied clauses should be performed in 'simplify'. vec<unsigned int> permDiff; // permDiff[var] contains the current conflict number... Used to count the number of LBD #ifdef UPDATEVARACTIVITY // UPDATEVARACTIVITY trick (see competition'09 companion paper) vec<Lit> lastDecisionLevel; #endif ClauseAllocator ca; int nbclausesbeforereduce; // To know when it is time to reduce clause database bqueue<unsigned int> trailQueue,lbdQueue; // Bounded queues for restarts. float sumLBD; // used to compute the global average of LBD. Restarts... int sumAssumptions; // Temporaries (to reduce allocation overhead). Each variable is prefixed by the method in which it is // used, exept 'seen' wich is used in several places. // vec<char> seen; vec<Lit> analyze_stack; vec<Lit> analyze_toclear; vec<Lit> add_tmp; unsigned int MYFLAG; double max_learnts; double learntsize_adjust_confl; int learntsize_adjust_cnt; // Resource contraints: // int64_t conflict_budget; // -1 means no budget. int64_t propagation_budget; // -1 means no budget. bool asynch_interrupt; // Variables added for incremental mode int incremental; // Use incremental SAT Solver int nbVarsInitialFormula; // nb VAR in formula without assumptions (incremental SAT) double totalTime4Sat,totalTime4Unsat; int nbSatCalls,nbUnsatCalls; vec<int> assumptionPositions,initialPositions; // Main internal methods: // void insertVarOrder (Var x); // Insert a variable in the decision order priority queue. Lit pickBranchLit (); // Return the next decision variable. void newDecisionLevel (); // Begins a new decision level. void uncheckedEnqueue (Lit p, CRef from = CRef_Undef); // Enqueue a literal. Assumes value of literal is undefined. bool enqueue (Lit p, CRef from = CRef_Undef); // Test if fact 'p' contradicts current state, enqueue otherwise. CRef propagate (); // Perform unit propagation. Returns possibly conflicting clause. void cancelUntil (int level); // Backtrack until a certain level. void analyze (CRef confl, vec<Lit>& out_learnt, vec<Lit> & selectors, int& out_btlevel,unsigned int &nblevels,unsigned int &szWithoutSelectors); // (bt = backtrack) void analyzeFinal (Lit p, vec<Lit>& out_conflict); // COULD THIS BE IMPLEMENTED BY THE ORDINARIY "analyze" BY SOME REASONABLE GENERALIZATION? bool litRedundant (Lit p, uint32_t abstract_levels); // (helper method for 'analyze()') lbool search (int& nof_conflicts); // Search for a given number of conflicts. lbool solve_ (); // Main solve method (assumptions given in 'assumptions'). void reduceDB (); // Reduce the set of learnt clauses. void removeSatisfied (vec<CRef>& cs); // Shrink 'cs' to contain only non-satisfied clauses. void rebuildOrderHeap (); // Maintaining Variable/Clause activity: // void varDecayActivity (); // Decay all variables with the specified factor. Implemented by increasing the 'bump' value instead. void varBumpActivity (Var v, double inc); // Increase a variable with the current 'bump' value. void varBumpActivity (Var v); // Increase a variable with the current 'bump' value. void claDecayActivity (); // Decay all clauses with the specified factor. Implemented by increasing the 'bump' value instead. void claBumpActivity (Clause& c); // Increase a clause with the current 'bump' value. // Operations on clauses: // void attachClause (CRef cr); // Attach a clause to watcher lists. void detachClause (CRef cr, bool strict = false); // Detach a clause to watcher lists. void removeClause (CRef cr); // Detach and free a clause. bool locked (const Clause& c) const; // Returns TRUE if a clause is a reason for some implication in the current state. bool satisfied (const Clause& c) const; // Returns TRUE if a clause is satisfied in the current state. unsigned int computeLBD(const vec<Lit> & lits,int end=-1); unsigned int computeLBD(const Clause &c); void minimisationWithBinaryResolution(vec<Lit> &out_learnt); void relocAll (ClauseAllocator& to); // Misc: // int decisionLevel () const; // Gives the current decisionlevel. uint32_t abstractLevel (Var x) const; // Used to represent an abstraction of sets of decision levels. CRef reason (Var x) const; int level (Var x) const; double progressEstimate () const; // DELETE THIS ?? IT'S NOT VERY USEFUL ... bool withinBudget () const; inline bool isSelector(Var v) {return (incremental && v>nbVarsInitialFormula);} // Static helpers: // // Returns a random float 0 <= x < 1. Seed must never be 0. static inline double drand(double& seed) { seed *= 1389796; int q = (int)(seed / 2147483647); seed -= (double)q * 2147483647; return seed / 2147483647; } // Returns a random integer 0 <= x < size. Seed must never be 0. static inline int irand(double& seed, int size) { return (int)(drand(seed) * size); } }; //================================================================================================= // Implementation of inline methods: inline CRef Solver::reason(Var x) const { return vardata[x].reason; } inline int Solver::level (Var x) const { return vardata[x].level; } inline void Solver::insertVarOrder(Var x) { if (!order_heap.inHeap(x) && decision[x]) order_heap.insert(x); } inline void Solver::varDecayActivity() { var_inc *= (1 / var_decay); } inline void Solver::varBumpActivity(Var v) { varBumpActivity(v, var_inc); } inline void Solver::varBumpActivity(Var v, double inc) { if ( (activity[v] += inc) > 1e100 ) { // Rescale: for (int i = 0; i < nVars(); i++) activity[i] *= 1e-100; var_inc *= 1e-100; } // Update order_heap with respect to new activity: if (order_heap.inHeap(v)) order_heap.decrease(v); } inline void Solver::claDecayActivity() { cla_inc *= (1 / clause_decay); } inline void Solver::claBumpActivity (Clause& c) { if ( (c.activity() += cla_inc) > 1e20 ) { // Rescale: for (int i = 0; i < learnts.size(); i++) ca[learnts[i]].activity() *= 1e-20; cla_inc *= 1e-20; } } inline void Solver::checkGarbage(void){ return checkGarbage(garbage_frac); } inline void Solver::checkGarbage(double gf){ if (ca.wasted() > ca.size() * gf) garbageCollect(); } // NOTE: enqueue does not set the ok flag! (only public methods do) inline bool Solver::enqueue (Lit p, CRef from) { return value(p) != l_Undef ? value(p) != l_False : (uncheckedEnqueue(p, from), true); } inline bool Solver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); } inline bool Solver::addEmptyClause () { add_tmp.clear(); return addClause_(add_tmp); } inline bool Solver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); } inline bool Solver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); } inline bool Solver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); } inline bool Solver::locked (const Clause& c) const { if(c.size()>2) return value(c[0]) == l_True && reason(var(c[0])) != CRef_Undef && ca.lea(reason(var(c[0]))) == &c; return (value(c[0]) == l_True && reason(var(c[0])) != CRef_Undef && ca.lea(reason(var(c[0]))) == &c) || (value(c[1]) == l_True && reason(var(c[1])) != CRef_Undef && ca.lea(reason(var(c[1]))) == &c); } inline void Solver::newDecisionLevel() { trail_lim.push(trail.size()); } inline int Solver::decisionLevel () const { return trail_lim.size(); } inline uint32_t Solver::abstractLevel (Var x) const { return 1 << (level(x) & 31); } inline lbool Solver::value (Var x) const { return assigns[x]; } inline lbool Solver::value (Lit p) const { return assigns[var(p)] ^ sign(p); } inline lbool Solver::modelValue (Var x) const { return model[x]; } inline lbool Solver::modelValue (Lit p) const { return model[var(p)] ^ sign(p); } inline int Solver::nAssigns () const { return trail.size(); } inline int Solver::nClauses () const { return clauses.size(); } inline int Solver::nLearnts () const { return learnts.size(); } inline int Solver::nVars () const { return vardata.size(); } inline int Solver::nFreeVars () const { return (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]); } inline void Solver::setPolarity (Var v, bool b) { polarity[v] = b; } inline void Solver::setDecisionVar(Var v, bool b) { if ( b && !decision[v]) dec_vars++; else if (!b && decision[v]) dec_vars--; decision[v] = b; insertVarOrder(v); } inline void Solver::setConfBudget(int64_t x){ conflict_budget = conflicts + x; } inline void Solver::setPropBudget(int64_t x){ propagation_budget = propagations + x; } inline void Solver::interrupt(){ asynch_interrupt = true; } inline void Solver::clearInterrupt(){ asynch_interrupt = false; } inline void Solver::budgetOff(){ conflict_budget = propagation_budget = -1; } inline bool Solver::withinBudget() const { return !asynch_interrupt && (conflict_budget < 0 || conflicts < (uint64_t)conflict_budget) && (propagation_budget < 0 || propagations < (uint64_t)propagation_budget); } // FIXME: after the introduction of asynchronous interrruptions the solve-versions that return a // pure bool do not give a safe interface. Either interrupts must be possible to turn off here, or // all calls to solve must return an 'lbool'. I'm not yet sure which I prefer. inline bool Solver::solve () { budgetOff(); assumptions.clear(); return solve_() == l_True; } inline bool Solver::solve (Lit p) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_() == l_True; } inline bool Solver::solve (Lit p, Lit q) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_() == l_True; } inline bool Solver::solve (Lit p, Lit q, Lit r) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_() == l_True; } inline bool Solver::solve (const vec<Lit>& assumps){ budgetOff(); assumps.copyTo(assumptions); return solve_() == l_True; } inline lbool Solver::solveLimited (const vec<Lit>& assumps){ assumps.copyTo(assumptions); return solve_(); } inline bool Solver::okay () const { return ok; } inline void Solver::toDimacs (const char* file){ vec<Lit> as; toDimacs(file, as); } inline void Solver::toDimacs (const char* file, Lit p){ vec<Lit> as; as.push(p); toDimacs(file, as); } inline void Solver::toDimacs (const char* file, Lit p, Lit q){ vec<Lit> as; as.push(p); as.push(q); toDimacs(file, as); } inline void Solver::toDimacs (const char* file, Lit p, Lit q, Lit r){ vec<Lit> as; as.push(p); as.push(q); as.push(r); toDimacs(file, as); } //================================================================================================= // Debug etc: inline void Solver::printLit(Lit l) { printf("%s%d:%c", sign(l) ? "-" : "", var(l)+1, value(l) == l_True ? '1' : (value(l) == l_False ? '0' : 'X')); } inline void Solver::printClause(CRef cr) { Clause &c = ca[cr]; for (int i = 0; i < c.size(); i++){ printLit(c[i]); printf(" "); } } inline void Solver::printInitialClause(CRef cr) { Clause &c = ca[cr]; for (int i = 0; i < c.size(); i++){ if(!isSelector(var(c[i]))) { printLit(c[i]); printf(" "); } } } //================================================================================================= } #endif /***************************************************************************************[Solver.cc] Glucose -- Copyright (c) 2013, Gilles Audemard, Laurent Simon CRIL - Univ. Artois, France LRI - Univ. Paris Sud, France Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of Glucose are exactly the same as Minisat on which it is based on. (see below). --------------- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #include <math.h> #define M mark #define Q conflicts #define P push #define B claBumpActivity namespace GHack { //================================================================================================= // Options: static const char* _cat = "CORE"; static const char* _cr = "CORE -- RESTART"; static const char* _cred = "CORE -- REDUCE"; static const char* _cm = "CORE -- MINIMIZE"; static const char* _certified = "CORE -- CERTIFIED UNSAT"; static BoolOption opt_incremental (_cat,"incremental", "Use incremental SAT solving",false); static DoubleOption opt_K (_cr, "K", "The constant used to force restart", 0.8, DoubleRange(0, false, 1, false)); static DoubleOption opt_R (_cr, "R", "The constant used to block restart", 1.4, DoubleRange(1, false, 5, false)); static IntOption opt_size_lbd_queue (_cr, "szLBDQueue", "The size of moving average for LBD (restarts)", 50, IntRange(10, INT32_MAX)); static IntOption opt_size_trail_queue (_cr, "szTrailQueue", "The size of moving average for trail (block restarts)", 5000, IntRange(10, INT32_MAX)); static IntOption opt_first_reduce_db (_cred, "firstReduceDB", "The number of conflicts before the first reduce DB", 2000, IntRange(0, INT32_MAX)); static IntOption opt_inc_reduce_db (_cred, "incReduceDB", "Increment for reduce DB", 300, IntRange(0, INT32_MAX)); static IntOption opt_spec_inc_reduce_db (_cred, "specialIncReduceDB", "Special increment for reduce DB", 1000, IntRange(0, INT32_MAX)); static IntOption opt_lb_lbd_frozen_clause (_cred, "minLBDFrozenClause", "Protect clauses if their LBD decrease and is lower than (for one turn)", 30, IntRange(0, INT32_MAX)); static IntOption opt_lb_size_minimzing_clause (_cm, "minSizeMinimizingClause", "The min size required to minimize clause", 30, IntRange(3, INT32_MAX)); static IntOption opt_lb_lbd_minimzing_clause (_cm, "minLBDMinimizingClause", "The min LBD required to minimize clause", 6, IntRange(3, INT32_MAX)); static DoubleOption opt_var_decay (_cat, "var-decay", "The variable activity decay factor", 0.8, DoubleRange(0, false, 1, false)); static DoubleOption opt_clause_decay (_cat, "cla-decay", "The clause activity decay factor", 0.999, DoubleRange(0, false, 1, false)); static DoubleOption opt_random_var_freq (_cat, "rnd-freq", "The frequency with which the decision heuristic tries to choose a random variable", 0, DoubleRange(0, true, 1, true)); static DoubleOption opt_random_seed (_cat, "rnd-seed", "Used by the random variable selection", 91648253, DoubleRange(0, false, HUGE_VAL, false)); static IntOption opt_ccmin_mode (_cat, "ccmin-mode", "Controls conflict clause minimization (0=none, 1=basic, 2=deep)", 2, IntRange(0, 2)); static IntOption opt_phase_saving (_cat, "phase-saving", "Controls the level of phase saving (0=none, 1=limited, 2=full)", 2, IntRange(0, 2)); static BoolOption opt_rnd_init_act (_cat, "rnd-init", "Randomize the initial activity", false); /* static IntOption opt_restart_first (_cat, "rfirst", "The base restart interval", 100, IntRange(1, INT32_MAX)); static DoubleOption opt_restart_inc (_cat, "rinc", "Restart interval increase factor", 2, DoubleRange(1, false, HUGE_VAL, false)); */ static DoubleOption opt_garbage_frac (_cat, "gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered", 0.20, DoubleRange(0, false, HUGE_VAL, false)); static BoolOption opt_certified (_certified, "certified", "Certified UNSAT using DRUP format", false); static StringOption opt_certified_file (_certified, "certified-output", "Certified UNSAT output file", "NULL"); static BoolOption opt_vbyte (_certified, "vbyte", "Emit proof in variable-byte encoding", false); //================================================================================================= // Constructor/Destructor: inline Solver::Solver() : // Parameters (user settable): // verbosity (0) , showModel (0) , K (opt_K) , R (opt_R) , sizeLBDQueue (opt_size_lbd_queue) , sizeTrailQueue (opt_size_trail_queue) , firstReduceDB (opt_first_reduce_db) , incReduceDB (opt_inc_reduce_db) , specialIncReduceDB (opt_spec_inc_reduce_db) , lbLBDFrozenClause (opt_lb_lbd_frozen_clause) , lbSizeMinimizingClause (opt_lb_size_minimzing_clause) , lbLBDMinimizingClause (opt_lb_lbd_minimzing_clause) , var_decay (opt_var_decay) , clause_decay (opt_clause_decay) , random_var_freq (opt_random_var_freq) , random_seed (opt_random_seed) , ccmin_mode (opt_ccmin_mode) , phase_saving (opt_phase_saving) , rnd_pol (false) , rnd_init_act (opt_rnd_init_act) , garbage_frac (opt_garbage_frac) , certifiedOutput (NULL) , certifiedUNSAT (opt_certified) , vbyte (opt_vbyte) // Statistics: (formerly in 'SolverStats') // , nbRemovedClauses(0),nbReducedClauses(0), nbDL2(0),nbBin(0),nbUn(0) , nbReduceDB(0) , solves(0), starts(0), decisions(0), rnd_decisions(0), propagations(0),conflicts(0),conflictsRestarts(0),nbstopsrestarts(0),nbstopsrestartssame(0),lastblockatrestart(0) , dec_vars(0), clauses_literals(0), learnts_literals(0), max_literals(0), tot_literals(0) , curRestart(1) , ok (true) , cla_inc (1) , var_inc (1) , watches (WatcherDeleted(ca)) , watchesBin (WatcherDeleted(ca)) , qhead (0) , simpDB_assigns (-1) , simpDB_props (0) , order_heap (VarOrderLt(activity)) , progress_estimate (0) , remove_satisfied (true) // Resource constraints: // , conflict_budget (-1) , propagation_budget (-1) , asynch_interrupt (false) , incremental(opt_incremental) , nbVarsInitialFormula(INT32_MAX) { MYFLAG=H=Y=O=e=0; G=1; A=4; Z=15000; // Initialize only first time. Useful for incremental solving, useless otherwise lbdQueue.initSize(sizeLBDQueue); trailQueue.initSize(sizeTrailQueue); sumLBD = 0; nbclausesbeforereduce = firstReduceDB; totalTime4Sat=0;totalTime4Unsat=0; nbSatCalls=0;nbUnsatCalls=0; if(certifiedUNSAT) { if(!strcmp(opt_certified_file,"NULL")) { vbyte = false; // Cannot write binary to stdout certifiedOutput = fopen("/dev/stdout", "wb"); } else { certifiedOutput = fopen(opt_certified_file, "wb"); } // fprintf(certifiedOutput,"o proof DRUP\n"); } } inline Solver::~Solver() { } /**************************************************************** Set the incremental mode ****************************************************************/ // This function set the incremental mode to true. // You can add special code for this mode here. inline void Solver::setIncrementalMode() { incremental = true; } // Number of variables without selectors inline void Solver::initNbInitialVars(int nb) { nbVarsInitialFormula = nb; } //================================================================================================= // Minor methods: // Creates a new SAT variable in the solver. If 'decision' is cleared, variable will not be // used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result). // inline Var Solver::newVar(bool sign, bool dvar) { int v = nVars(); watches .init(mkLit(v, false)); watches .init(mkLit(v, true )); watchesBin .init(mkLit(v, false)); watchesBin .init(mkLit(v, true )); assigns .push(l_Undef); vardata .push(mkVarData(CRef_Undef, 0)); //activity .push(0); activity .push(rnd_init_act ? drand(random_seed) * 0.00001 : 0); seen .push(0); permDiff .push(0); polarity .push(sign); decision .push(); trail .capacity(v+1); setDecisionVar(v, dvar); return v; } inline unsigned char b[2097152]; inline void Solver::write_char (unsigned char ch) { b[e++] = ch; } //if (putc_unlocked ((int) #define write_char b[e++] = //= EOF) exit(1); } inline void Solver::write_lit (int n) { for (; n > 127; n >>= 7) write_char (128 | (n & 127)); write_char (n); if (e > 1048576) fwrite(b, 1, e, certifiedOutput), e = 0; } inline bool Solver::addClause_(vec<Lit>& ps) { assert(decisionLevel() == 0); if (!ok) return false; // Check if clause is satisfied and remove false/duplicate literals: sort(ps); vec<Lit> oc; oc.clear(); Lit p; int i, j, flag = 0; if(certifiedUNSAT) { for (i = j = 0, p = lit_Undef; i < ps.size(); i++) { oc.push(ps[i]); if (value(ps[i]) == l_True || ps[i] == ~p || value(ps[i]) == l_False) flag = 1; } } for (i = j = 0, p = lit_Undef; i < ps.size(); i++) if (value(ps[i]) == l_True || ps[i] == ~p) return true; else if (value(ps[i]) != l_False && ps[i] != p) ps[j++] = p = ps[i]; ps.shrink(i - j); if (i != j && (certifiedUNSAT)) { if (vbyte) { write_char('a'); for (i = j = 0, p = lit_Undef; i < ps.size(); i++) write_lit(2*(var(ps[i])+1) + sign(ps[i])); write_lit(0); write_char('d'); for (i = j = 0, p = lit_Undef; i < oc.size(); i++) write_lit(2*(var(oc[i])+1) + sign(oc[i])); write_lit(0); } else { for (i = j = 0, p = lit_Undef; i < ps.size(); i++) fprintf(certifiedOutput, "%i ", (var(ps[i]) + 1) * (-2 * sign(ps[i]) + 1)); fprintf(certifiedOutput, "0\n"); fprintf(certifiedOutput, "d "); for (i = j = 0, p = lit_Undef; i < oc.size(); i++) fprintf(certifiedOutput, "%i ", (var(oc[i]) + 1) * (-2 * sign(oc[i]) + 1)); fprintf(certifiedOutput, "0\n"); } } if (ps.size() == 0) return ok = false; else if (ps.size() == 1){ uncheckedEnqueue(ps[0]); return ok = (propagate() == CRef_Undef); }else{ CRef cr = ca.alloc(ps, false); clauses.push(cr); attachClause(cr); } return true; } inline void Solver::attachClause(CRef cr) { const Clause& c = ca[cr]; assert(c.size() > 1); if(c.size()==2) { watchesBin[~c[0]].push(Watcher(cr, c[1])); watchesBin[~c[1]].push(Watcher(cr, c[0])); } else { watches[~c[0]].push(Watcher(cr, c[1])); watches[~c[1]].push(Watcher(cr, c[0])); } if (c.learnt()) learnts_literals += c.size(); else clauses_literals += c.size(); } inline void Solver::detachClause(CRef cr, bool strict) { const Clause& c = ca[cr]; assert(c.size() > 1); if(c.size()==2) { if (strict){ remove(watchesBin[~c[0]], Watcher(cr, c[1])); remove(watchesBin[~c[1]], Watcher(cr, c[0])); }else{ // Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause) watchesBin.smudge(~c[0]); watchesBin.smudge(~c[1]); } } else { if (strict){ remove(watches[~c[0]], Watcher(cr, c[1])); remove(watches[~c[1]], Watcher(cr, c[0])); }else{ // Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause) watches.smudge(~c[0]); watches.smudge(~c[1]); } } if (c.learnt()) learnts_literals -= c.size(); else clauses_literals -= c.size(); } inline void Solver::removeClause(CRef cr) { Clause& c = ca[cr]; if (certifiedUNSAT) { if (vbyte) { write_char ('d'); for (int i = 0; i < c.size(); i++) write_lit(2*(var(c[i])+1) + sign(c[i])); write_lit (0); } else { fprintf(certifiedOutput, "d "); for (int i = 0; i < c.size(); i++) fprintf(certifiedOutput, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1)); fprintf(certifiedOutput, "0\n"); } } detachClause(cr); // Don't leave pointers to free'd memory! if (locked(c)) vardata[var(c[0])].reason = CRef_Undef; c.mark(1); ca.free(cr); } inline bool Solver::satisfied(const Clause& c) const { if(incremental) // Check clauses with many selectors is too time consuming return (value(c[0]) == l_True) || (value(c[1]) == l_True); // Default mode. for (int i = 0; i < c.size(); i++) if (value(c[i]) == l_True) return true; return false; } /************************************************************ * Compute LBD functions *************************************************************/ inline unsigned int Solver::computeLBD(const vec<Lit> & lits,int end) { int nblevels = 0; MYFLAG++; if(incremental) { // ----------------- INCREMENTAL MODE if(end==-1) end = lits.size(); unsigned int nbDone = 0; for(int i=0;i<lits.size();i++) { if(nbDone>=end) break; if(isSelector(var(lits[i]))) continue; nbDone++; int l = level(var(lits[i])); if (permDiff[l] != MYFLAG) { permDiff[l] = MYFLAG; nblevels++; } } } else { // -------- DEFAULT MODE. NOT A LOT OF DIFFERENCES... BUT EASIER TO READ for(int i=0;i<lits.size();i++) { int l = level(var(lits[i])); if (l && permDiff[l] != MYFLAG) { permDiff[l] = MYFLAG; nblevels++; } } } return nblevels; } inline unsigned int Solver::computeLBD(const Clause &c) { int nblevels = 0; MYFLAG++; if(incremental) { // ----------------- INCREMENTAL MODE int nbDone = 0; for(int i=0;i<c.size();i++) { if(nbDone>=c.sizeWithoutSelectors()) break; if(isSelector(var(c[i]))) continue; nbDone++; int l = level(var(c[i])); if (permDiff[l] != MYFLAG) { permDiff[l] = MYFLAG; nblevels++; } } } else { // -------- DEFAULT MODE. NOT A LOT OF DIFFERENCES... BUT EASIER TO READ for(int i=0;i<c.size();i++) { int l = level(var(c[i])); if (l && permDiff[l] != MYFLAG) { permDiff[l] = MYFLAG; nblevels++; } } } return nblevels; } /****************************************************************** * Minimisation with binary reolution ******************************************************************/ inline void Solver::minimisationWithBinaryResolution(vec<Lit> &out_learnt) { // Find the LBD measure unsigned int lbd = computeLBD(out_learnt); Lit p = ~out_learnt[0]; if(lbd<=lbLBDMinimizingClause){ MYFLAG++; for(int i = 1;i<out_learnt.size();i++) { permDiff[var(out_learnt[i])] = MYFLAG; } vec<Watcher>& wbin = watchesBin[p]; int nb = 0; for(int k = 0;k<wbin.size();k++) { Lit imp = wbin[k].blocker; if(permDiff[var(imp)]==MYFLAG && value(imp)==l_True) { nb++; permDiff[var(imp)]= MYFLAG-1; } } int l = out_learnt.size()-1; if(nb>0) { nbReducedClauses++; for(int i = 1;i<out_learnt.size()-nb;i++) { if(permDiff[var(out_learnt[i])]!=MYFLAG) { Lit p = out_learnt[l]; out_learnt[l] = out_learnt[i]; out_learnt[i] = p; l--;i--; } } out_learnt.shrink(nb); } } } // Revert to the state at given level (keeping all assignment at 'level' but not beyond). // inline void Solver::cancelUntil(int level) { if (decisionLevel() > level){ for (int c = trail.size()-1; c >= trail_lim[level]; c--){ Var x = var(trail[c]); assigns [x] = l_Undef; if (phase_saving > 1 || ((phase_saving == 1) && c > trail_lim.last())) polarity[x] = sign(trail[c]); insertVarOrder(x); } qhead = trail_lim[level]; trail.shrink(trail.size() - trail_lim[level]); trail_lim.shrink(trail_lim.size() - level); } } //================================================================================================= // Major methods: inline Lit Solver::pickBranchLit() { Var next = var_Undef; // Random decision: if (drand(random_seed) < random_var_freq && !order_heap.empty()){ next = order_heap[irand(random_seed,order_heap.size())]; if (value(next) == l_Undef && decision[next]) rnd_decisions++; } // Activity based decision: while (next == var_Undef || value(next) != l_Undef || !decision[next]) if (order_heap.empty()){ next = var_Undef; break; }else next = order_heap.removeMin(); return next == var_Undef ? lit_Undef : mkLit(next, rnd_pol ? drand(random_seed) < 0.5 : polarity[next]); } /*_________________________________________________________________________________________________ | | analyze : (confl : Clause*) (out_learnt : vec<Lit>&) (out_btlevel : int&) -> [void] | | Description: | Analyze conflict and produce a reason clause. | | Pre-conditions: | * 'out_learnt' is assumed to be cleared. | * Current decision level must be greater than root level. | | Post-conditions: | * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'. | * If out_learnt.size() > 1 then 'out_learnt[1]' has the greatest decision level of the | rest of literals. There may be others from the same level though. | |________________________________________________________________________________________________@*/ inline void Solver::analyze(CRef confl, vec<Lit>& out_learnt,vec<Lit>&selectors, int& out_btlevel,unsigned int &lbd,unsigned int &szWithoutSelectors) { int pathC = 0; Lit p = lit_Undef; // Generate conflict clause: // out_learnt.push(); // (leave room for the asserting literal) int index = trail.size() - 1; do{ assert(confl != CRef_Undef); // (otherwise should be UIP) Clause& c = ca[confl]; // Special case for binary clauses // The first one has to be SAT if( p != lit_Undef && c.size()==2 && value(c[0])==l_False) { assert(value(c[1])==l_True); Lit tmp = c[0]; c[0] = c[1], c[1] = tmp; } if (0 && c.learnt()) claBumpActivity(c); #ifdef DYNAMICNBLEVEL // DYNAMIC NBLEVEL trick (see competition'09 companion paper) if(c.learnt() && c.M() != 3) { unsigned int nblevels = I = computeLBD(c); if(nblevels<c.lbd() ) { // improve the LBD if(c.lbd()<=lbLBDFrozenClause) { c.setCanBeDel(false); } // seems to be interesting : keep it for the next round c.setLBD(nblevels); // Update it if (I < A){ C.P(confl); c.M(3); }else if (I < 7 && !c.M()){ T.P(confl); c.M(2); } } if (c.M() == 2) c.t = Q; if (!c.M()) B(c); } #endif for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){ Lit q = c[j]; if (!seen[var(q)] && level(var(q)) > 0){ if(!isSelector(var(q))) varBumpActivity(var(q)); seen[var(q)] = 1; if (level(var(q)) >= decisionLevel()) { pathC++; #ifdef UPDATEVARACTIVITY // UPDATEVARACTIVITY trick (see competition'09 companion paper) if(!isSelector(var(q)) && (reason(var(q))!= CRef_Undef) && ca[reason(var(q))].learnt()) lastDecisionLevel.push(q); #endif } else { if(isSelector(var(q))) { assert(value(q) == l_False); selectors.push(q); } else out_learnt.push(q); } } } // Select next clause to look at: while (!seen[var(trail[index--])]); p = trail[index+1]; confl = reason(var(p)); seen[var(p)] = 0; pathC--; }while (pathC > 0); out_learnt[0] = ~p; // Simplify conflict clause: // int i, j; for(int i = 0;i<selectors.size();i++) out_learnt.push(selectors[i]); out_learnt.copyTo(analyze_toclear); if (ccmin_mode == 2){ uint32_t abstract_level = 0; for (i = 1; i < out_learnt.size(); i++) abstract_level |= abstractLevel(var(out_learnt[i])); // (maintain an abstraction of levels involved in conflict) for (i = j = 1; i < out_learnt.size(); i++) if (reason(var(out_learnt[i])) == CRef_Undef || !litRedundant(out_learnt[i], abstract_level)) out_learnt[j++] = out_learnt[i]; }else if (ccmin_mode == 1){ for (i = j = 1; i < out_learnt.size(); i++){ Var x = var(out_learnt[i]); if (reason(x) == CRef_Undef) out_learnt[j++] = out_learnt[i]; else{ Clause& c = ca[reason(var(out_learnt[i]))]; // Thanks to Siert Wieringa for this bug fix! for (int k = ((c.size()==2) ? 0:1); k < c.size(); k++) if (!seen[var(c[k])] && level(var(c[k])) > 0){ out_learnt[j++] = out_learnt[i]; break; } } } }else i = j = out_learnt.size(); max_literals += out_learnt.size(); out_learnt.shrink(i - j); tot_literals += out_learnt.size(); /* *************************************** Minimisation with binary clauses of the asserting clause First of all : we look for small clauses Then, we reduce clauses with small LBD. Otherwise, this can be useless */ if(!incremental && out_learnt.size()<=lbSizeMinimizingClause) { minimisationWithBinaryResolution(out_learnt); } // Find correct backtrack level: // if (out_learnt.size() == 1) out_btlevel = 0; else{ int max_i = 1; // Find the first literal assigned at the next-highest level: for (int i = 2; i < out_learnt.size(); i++) if (level(var(out_learnt[i])) > level(var(out_learnt[max_i]))) max_i = i; // Swap-in this literal at index 1: Lit p = out_learnt[max_i]; out_learnt[max_i] = out_learnt[1]; out_learnt[1] = p; out_btlevel = level(var(p)); } // Compute the size of the clause without selectors (incremental mode) if(incremental) { szWithoutSelectors = 0; for(int i=0;i<out_learnt.size();i++) { if(!isSelector(var((out_learnt[i])))) szWithoutSelectors++; else if(i>0) break; } } else szWithoutSelectors = out_learnt.size(); // Compute LBD lbd = computeLBD(out_learnt,out_learnt.size()-selectors.size()); #ifdef UPDATEVARACTIVITY // UPDATEVARACTIVITY trick (see competition'09 companion paper) if(lastDecisionLevel.size()>0) { for(int i = 0;i<lastDecisionLevel.size();i++) { if(ca[reason(var(lastDecisionLevel[i]))].lbd()<lbd) varBumpActivity(var(lastDecisionLevel[i])); } lastDecisionLevel.clear(); } #endif lbd--; for (int j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; // ('seen[]' is now cleared) for(int j = 0 ; j<selectors.size() ; j++) seen[var(selectors[j])] = 0; } // Check if 'p' can be removed. 'abstract_levels' is used to abort early if the algorithm is // visiting literals at levels that cannot be removed later. inline bool Solver::litRedundant(Lit p, uint32_t abstract_levels) { analyze_stack.clear(); analyze_stack.push(p); int top = analyze_toclear.size(); while (analyze_stack.size() > 0){ assert(reason(var(analyze_stack.last())) != CRef_Undef); Clause& c = ca[reason(var(analyze_stack.last()))]; analyze_stack.pop(); if(c.size()==2 && value(c[0])==l_False) { assert(value(c[1])==l_True); Lit tmp = c[0]; c[0] = c[1], c[1] = tmp; } for (int i = 1; i < c.size(); i++){ Lit p = c[i]; if (!seen[var(p)] && level(var(p)) > 0){ if (reason(var(p)) != CRef_Undef && (abstractLevel(var(p)) & abstract_levels) != 0){ seen[var(p)] = 1; analyze_stack.push(p); analyze_toclear.push(p); }else{ for (int j = top; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; analyze_toclear.shrink(analyze_toclear.size() - top); return false; } } } } return true; } /*_________________________________________________________________________________________________ | | analyzeFinal : (p : Lit) -> [void] | | Description: | Specialized analysis procedure to express the final conflict in terms of assumptions. | Calculates the (possibly empty) set of assumptions that led to the assignment of 'p', and | stores the result in 'out_conflict'. |________________________________________________________________________________________________@*/ inline void Solver::analyzeFinal(Lit p, vec<Lit>& out_conflict) { out_conflict.clear(); out_conflict.push(p); if (decisionLevel() == 0) return; seen[var(p)] = 1; for (int i = trail.size()-1; i >= trail_lim[0]; i--){ Var x = var(trail[i]); if (seen[x]){ if (reason(x) == CRef_Undef){ assert(level(x) > 0); out_conflict.push(~trail[i]); }else{ Clause& c = ca[reason(x)]; // for (int j = 1; j < c.size(); j++) Minisat (glucose 2.0) loop // Bug in case of assumptions due to special data structures for Binary. // Many thanks to Sam Bayless ([email protected]) for discover this bug. for (int j = ((c.size()==2) ? 0:1); j < c.size(); j++) if (level(var(c[j])) > 0) seen[var(c[j])] = 1; } seen[x] = 0; } } seen[var(p)] = 0; } inline void Solver::uncheckedEnqueue(Lit p, CRef from) { assert(value(p) == l_Undef); assigns[var(p)] = lbool(!sign(p)); vardata[var(p)] = mkVarData(from, decisionLevel()); trail.push_(p); } /*_________________________________________________________________________________________________ | | propagate : [void] -> [Clause*] | | Description: | Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned, | otherwise CRef_Undef. | | Post-conditions: | * the propagation queue is empty, even if there was a conflict. |________________________________________________________________________________________________@*/ inline CRef Solver::propagate() { CRef confl = CRef_Undef; int num_props = 0; watches.cleanAll(); watchesBin.cleanAll(); while (qhead < trail.size()){ Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate. vec<Watcher>& ws = watches[p]; Watcher *i, *j, *end; num_props++; // First, Propagate binary clauses vec<Watcher>& wbin = watchesBin[p]; for(int k = 0;k<wbin.size();k++) { Lit imp = wbin[k].blocker; if(value(imp) == l_False) { return wbin[k].cref; } if(value(imp) == l_Undef) { uncheckedEnqueue(imp,wbin[k].cref); } } for (i = j = (Watcher*)ws, end = i + ws.size(); i != end;){ // Try to avoid inspecting the clause: Lit blocker = i->blocker; if (value(blocker) == l_True){ *j++ = *i++; continue; } // Make sure the false literal is data[1]: CRef cr = i->cref; Clause& c = ca[cr]; Lit false_lit = ~p; if (c[0] == false_lit) c[0] = c[1], c[1] = false_lit; assert(c[1] == false_lit); i++; // If 0th watch is true, then clause is already satisfied. Lit first = c[0]; Watcher w = Watcher(cr, first); if (first != blocker && value(first) == l_True){ *j++ = w; continue; } // Look for new watch: if(incremental) { // ----------------- INCREMENTAL MODE int choosenPos = -1; for (int k = 2; k < c.size(); k++) { if (value(c[k]) != l_False){ if(decisionLevel()>assumptions.size()) { choosenPos = k; break; } else { choosenPos = k; if(value(c[k])==l_True || !isSelector(var(c[k]))) { break; } } } } if(choosenPos!=-1) { c[1] = c[choosenPos]; c[choosenPos] = false_lit; watches[~c[1]].push(w); goto NextClause; } } else { // ----------------- DEFAULT MODE (NOT INCREMENTAL) for (int k = 2; k < c.size(); k++) { if (value(c[k]) != l_False){ c[1] = c[k]; c[k] = false_lit; watches[~c[1]].push(w); goto NextClause; } } } // Did not find watch -- clause is unit under assignment: *j++ = w; if (value(first) == l_False){ confl = cr; qhead = trail.size(); // Copy the remaining watches: while (i < end) *j++ = *i++; }else { uncheckedEnqueue(first, cr); } NextClause:; } ws.shrink(i - j); } propagations += num_props; simpDB_props -= num_props; return confl; } /*_________________________________________________________________________________________________ | | reduceDB : () -> [void] | | Description: | Remove half of the learnt clauses, minus the clauses locked by the current assignment. Locked | clauses are clauses that are reason to some assignment. Binary clauses are never removed. |________________________________________________________________________________________________@*/ struct reduceDB_lt { ClauseAllocator& ca; reduceDB_lt(ClauseAllocator& ca_) : ca(ca_) {} bool operator () (CRef x, CRef y) { /* // Main criteria... Like in MiniSat we keep all binary clauses if(ca[x].size()> 2 && ca[y].size()==2) return 1; if(ca[y].size()>2 && ca[x].size()==2) return 0; if(ca[x].size()==2 && ca[y].size()==2) return 0; // Second one based on literal block distance if(ca[x].lbd()> ca[y].lbd()) return 1; if(ca[x].lbd()< ca[y].lbd()) return 0; */ // Finally we can use old activity or size, we choose the last one return ca[x].activity() < ca[y].activity(); //return x->size() < y->size(); //return ca[x].size() > 2 && (ca[y].size() == 2 || ca[x].activity() < ca[y].activity()); } } }; inline void Solver::reduceDB() { int i, j; nbReduceDB++; sort(learnts, reduceDB_lt(ca)); // We have a lot of "good" clauses, it is difficult to compare them. Keep more ! //if(ca[learnts[learnts.size() / RATIOREMOVECLAUSES]].lbd()<=3) nbclausesbeforereduce +=specialIncReduceDB; // Useless :-) //if(ca[learnts.last()].lbd()<=5) nbclausesbeforereduce +=specialIncReduceDB; // Don't delete binary or locked clauses. From the rest, delete clauses from the first half // Keep clauses which seem to be usefull (their lbd was reduce during this sequence) int limit = learnts.size() / 2; for (i = j = 0; i < learnts.size(); i++){ Clause& c = ca[learnts[i]]; if (!c.M()) if (c.lbd()>2 && c.size() > 2 && c.canBeDel() && !locked(c) && (i < limit)) { removeClause(learnts[i]); nbRemovedClauses++; } else { if(!c.canBeDel()) limit++; //we keep c, so we can delete an other clause c.setCanBeDel(true); // At the next step, c can be delete learnts[j++] = learnts[i]; } } learnts.shrink(i - j); checkGarbage(); } inline void Solver::removeSatisfied(vec<CRef>& cs) { int i, j; for (i = j = 0; i < cs.size(); i++){ Clause& c = ca[cs[i]]; if (c.M() == O) if (satisfied(c)) removeClause(cs[i]); else cs[j++] = cs[i]; } cs.shrink(i - j); } inline void Solver::rebuildOrderHeap() { vec<Var> vs; for (Var v = 0; v < nVars(); v++) if (decision[v] && value(v) == l_Undef) vs.push(v); order_heap.build(vs); } /*_________________________________________________________________________________________________ | | simplify : [void] -> [bool] | | Description: | Simplify the clause database according to the current top-level assigment. Currently, the only | thing done here is the removal of satisfied clauses, but more things can be put here. |________________________________________________________________________________________________@*/ inline bool Solver::simplify() { assert(decisionLevel() == 0); if (!ok || propagate() != CRef_Undef) return ok = false; if (nAssigns() == simpDB_assigns || (simpDB_props > 0)) return true; // Remove satisfied clauses: #define S removeSatisfied O = 3; S(C); O = 2; S(T); O = 0; removeSatisfied(learnts); if (remove_satisfied) // Can be turned off. removeSatisfied(clauses); checkGarbage(); rebuildOrderHeap(); simpDB_assigns = nAssigns(); simpDB_props = clauses_literals + learnts_literals; // (shouldn't depend on stats really, but it will do for now) return true; } /*_________________________________________________________________________________________________ | | search : (nof_conflicts : int) (params : const SearchParams&) -> [lbool] | | Description: | Search for a model the specified number of conflicts. | NOTE! Use negative value for 'nof_conflicts' indicate infinity. | | Output: | 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If | all variables are decision variables, this means that the clause set is satisfiable. 'l_False' | if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached. |________________________________________________________________________________________________@*/ inline lbool Solver::search(int& n//of_conflicts ) { assert(ok); int backtrack_level; int conflictC = 0; vec<Lit> learnt_clause,selectors; unsigned int nblevels,szWoutSelectors; bool blocked=false; starts++; for (;;){ CRef confl = propagate(); if (confl != CRef_Undef){ // CONFLICT conflicts++; conflictC++;conflictsRestarts++; Y--; Z--; n--; if (Q == 100000 && C.size() < 100) A = 6; if(0 && conflicts%5000==0 && var_decay<0.95) var_decay += 0.01; if (0 && verbosity >= 1 && conflicts%verbEveryConflicts==0){ printf("c | %8d %7d %5d | %7d %8d %8d | %5d %8d %6d %8d | %6.3f %% |\n", (int)starts,(int)nbstopsrestarts, (int)(conflicts/starts), (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]), nClauses(), (int)clauses_literals, (int)nbReduceDB, nLearnts(), (int)nbDL2,(int)nbRemovedClauses, progressEstimate()*100); } if (decisionLevel() == 0) { return l_False; } /* trailQueue.push(trail.size()); // BLOCK RESTART (CP 2012 paper) if( conflictsRestarts>LOWER_BOUND_FOR_BLOCKING_RESTART && lbdQueue.isvalid() && trail.size()>R*trailQueue.getavg()) { lbdQueue.fastclear(); nbstopsrestarts++; if(!blocked) {lastblockatrestart=starts;nbstopsrestartssame++;blocked=true;} } */ learnt_clause.clear(); selectors.clear(); analyze(confl, learnt_clause, selectors,backtrack_level,nblevels,szWoutSelectors); if (G){ H++; lbdQueue.push(nblevels); sumLBD += nblevels > 50 ? 50 : nblevels; } cancelUntil(backtrack_level); if (certifiedUNSAT) { if (vbyte) { write_char('a'); for (int i = 0; i < learnt_clause.size(); i++) write_lit(2*(var(learnt_clause[i])+1) + sign(learnt_clause[i])); write_lit(0); } else { for (int i = 0; i < learnt_clause.size(); i++) fprintf(certifiedOutput, "%i " , (var(learnt_clause[i]) + 1) * (-2 * sign(learnt_clause[i]) + 1) ); fprintf(certifiedOutput, "0\n"); } } if (learnt_clause.size() == 1){ uncheckedEnqueue(learnt_clause[0]);nbUn++; }else{ #define EE ca[cr] CRef cr = ca.alloc(learnt_clause, true); ca[cr].setLBD(I = nblevels); ca[cr].setSizeWithoutSelectors(szWoutSelectors); if(nblevels<=2) nbDL2++; // stats if(ca[cr].size()==2) nbBin++; // stats if (I < A){ C.P(cr); EE.M(3); }else if (I < 7){ T.P(cr); EE.M(2); EE.t = Q; }else{ learnts.push(cr); B(EE); } attachClause(cr); //claBumpActivity(ca[cr]); uncheckedEnqueue(learnt_clause[0], cr); } varDecayActivity(); claDecayActivity(); }else{ // Our dynamic restart, see the SAT09 competition compagnion paper if ((!G && n <= 0) || (G && ( lbdQueue.isvalid() && ((lbdQueue.getavg()*(n > 0 ? K : .9)) > (sumLBD / H//conflictsRestarts ))))) { lbdQueue.fastclear(); progress_estimate = progressEstimate(); int bt = 0; if(incremental) { // DO NOT BACKTRACK UNTIL 0.. USELESS bt = (decisionLevel()<assumptions.size()) ? decisionLevel() : assumptions.size(); } cancelUntil(bt); return l_Undef; } // Simplify the set of problem clauses: if (decisionLevel() == 0 && !simplify()) { return l_False; } if (Y <= 0){ for (I = Y = 0; I < T.size(); I++){ Clause& c = ca[T[I]]; if (c.M() == 2) if (!locked(c) && c.t + 30000 < Q){ learnts.P(T[I]); c.M(0); c.activity() = 0; B(c); }else T[Y++] = T[I]; } T.shrink(I - Y); Y = 10000; } // Perform clause database reduction ! if(Z <= 0)//conflicts>=curRestart* nbclausesbeforereduce) { assert(learnts.size()>0); curRestart = (conflicts/ nbclausesbeforereduce)+1; reduceDB(); nbclausesbeforereduce += incReduceDB; Z = 15000; } Lit next = lit_Undef; while (decisionLevel() < assumptions.size()){ // Perform user provided assumption: Lit p = assumptions[decisionLevel()]; if (value(p) == l_True){ // Dummy decision level: newDecisionLevel(); }else if (value(p) == l_False){ analyzeFinal(~p, conflict); return l_False; }else{ next = p; break; } } if (next == lit_Undef){ // New variable decision: decisions++; next = pickBranchLit(); if (next == lit_Undef){ // printf("c last restart ## conflicts : %d %d \n",conflictC,decisionLevel()); // Model found: return l_True; } } // Increase decision level and enqueue 'next' newDecisionLevel(); uncheckedEnqueue(next); } } } inline double Solver::progressEstimate() const { double progress = 0; double F = 1.0 / nVars(); for (int i = 0; i <= decisionLevel(); i++){ int beg = i == 0 ? 0 : trail_lim[i - 1]; int end = i == decisionLevel() ? trail.size() : trail_lim[i]; progress += pow(F, i) * (end - beg); } return progress / nVars(); } inline void Solver::printIncrementalStats() { printf("c---------- Glucose Stats -------------------------\n"); printf("c restarts : %lld\n", starts); printf("c nb ReduceDB : %lld\n", nbReduceDB); printf("c nb removed Clauses : %lld\n",nbRemovedClauses); printf("c nb learnts DL2 : %lld\n", nbDL2); printf("c nb learnts size 2 : %lld\n", nbBin); printf("c nb learnts size 1 : %lld\n", nbUn); printf("c conflicts : %lld \n",conflicts); printf("c decisions : %lld\n",decisions); printf("c propagations : %lld\n",propagations); printf("c SAT Calls : %d in %g seconds\n",nbSatCalls,totalTime4Sat); printf("c UNSAT Calls : %d in %g seconds\n",nbUnsatCalls,totalTime4Unsat); printf("c--------------------------------------------------\n"); } // NOTE: assumptions passed in member-variable 'assumptions'. inline lbool Solver::solve_() { if(incremental && certifiedUNSAT) { printf("Can not use incremental and certified unsat in the same time\n"); exit(-1); } model.clear(); conflict.clear(); if (!ok) return l_False; double curTime = cpuTime(); solves++; lbool status = l_Undef; if(!incremental && verbosity>=1) { printf("c ========================================[ MAGIC CONSTANTS ]==============================================\n"); printf("c | Constants are supposed to work well together :-) |\n"); printf("c | however, if you find better choices, please let us known... |\n"); printf("c |-------------------------------------------------------------------------------------------------------|\n"); printf("c | | | |\n"); printf("c | - Restarts: | - Reduce Clause DB: | - Minimize Asserting: |\n"); printf("c | * LBD Queue : %6d | * First : %6d | * size < %3d |\n",lbdQueue.maxSize(),nbclausesbeforereduce,lbSizeMinimizingClause); printf("c | * Trail Queue : %6d | * Inc : %6d | * lbd < %3d |\n",trailQueue.maxSize(),incReduceDB,lbLBDMinimizingClause); printf("c | * K : %6.2f | * Special : %6d | |\n",K,specialIncReduceDB); printf("c | * R : %6.2f | * Protected : (lbd)< %2d | |\n",R,lbLBDFrozenClause); printf("c | | | |\n"); printf("c ==================================[ Search Statistics (every %6d conflicts) ]=========================\n",verbEveryConflicts); printf("c | |\n"); printf("c | RESTARTS | ORIGINAL | LEARNT | Progress |\n"); printf("c | NB Blocked Avg Cfc | Vars Clauses Literals | Red Learnts LBD2 Removed | |\n"); printf("c =========================================================================================================\n"); } // Search: int curr_restarts = 0, a = 91, w; while (status == l_Undef){ w = !H ? 10000 : a + G * a; var_decay = G ? .95 : .999; while (status == l_Undef && w > 0) status = search(w); // the parameter is useless in glucose, kept to allow modifications //if (!withinBudget()) break; curr_restarts++; if (!(G = !G)) a += a / 10; } if (!incremental && verbosity >= 1) printf("c =========================================================================================================\n"); if (certifiedUNSAT){ // Want certified output if (status == l_False) { if (vbyte) { write_char('a'); write_lit(0); fwrite(b, 1, e, certifiedOutput), e = 0; } else { fprintf(certifiedOutput, "0\n"); } } fclose(certifiedOutput); } if (status == l_True){ // Extend & copy model: model.growTo(nVars()); for (int i = 0; i < nVars(); i++) model[i] = value(i); }else if (status == l_False && conflict.size() == 0) ok = false; cancelUntil(0); double finalTime = cpuTime(); if(status==l_True) { nbSatCalls++; totalTime4Sat +=(finalTime-curTime); } if(status==l_False) { nbUnsatCalls++; totalTime4Unsat +=(finalTime-curTime); } return status; } //================================================================================================= // Writing CNF to DIMACS: // // FIXME: this needs to be rewritten completely. static Var mapVar(Var x, vec<Var>& map, Var& max) { if (map.size() <= x || map[x] == -1){ map.growTo(x+1, -1); map[x] = max++; } return map[x]; } inline void Solver::toDimacs(FILE* f, Clause& c, vec<Var>& map, Var& max) { if (satisfied(c)) return; for (int i = 0; i < c.size(); i++) if (value(c[i]) != l_False) fprintf(f, "%s%d ", sign(c[i]) ? "-" : "", mapVar(var(c[i]), map, max)+1); fprintf(f, "0\n"); } inline void Solver::toDimacs(const char *file, const vec<Lit>& assumps) { FILE* f = fopen(file, "wr"); if (f == NULL) fprintf(stderr, "could not open file %s\n", file), exit(1); toDimacs(f, assumps); fclose(f); } inline void Solver::toDimacs(FILE* f, const vec<Lit>& assumps) { // Handle case when solver is in contradictory state: if (!ok){ fprintf(f, "p cnf 1 2\n1 0\n-1 0\n"); return; } assumps.copyTo(assumptions); vec<Var> map; Var max = 0; // Cannot use removeClauses here because it is not safe // to deallocate them at this point. Could be improved. int cnt = 0; for (int i = 0; i < clauses.size(); i++) if (!satisfied(ca[clauses[i]])) cnt++; for (int i = 0; i < clauses.size(); i++) if (!satisfied(ca[clauses[i]])){ Clause& c = ca[clauses[i]]; for (int j = 0; j < c.size(); j++) if (value(c[j]) != l_False) mapVar(var(c[j]), map, max); } // Assumptions are added as unit clauses: cnt += assumptions.size(); fprintf(f, "p cnf %d %d\n", max, cnt); for (int i = 0; i < assumptions.size(); i++){ assert(value(assumptions[i]) != l_False); fprintf(f, "%s%d 0\n", sign(assumptions[i]) ? "-" : "", mapVar(var(assumptions[i]), map, max)+1); } for (int i = 0; i < clauses.size(); i++) toDimacs(f, ca[clauses[i]], map, max); if (verbosity > 0) printf("Wrote %d clauses with %d variables.\n", cnt, max); } //================================================================================================= // Garbage Collection methods: inline void Solver::relocAll(ClauseAllocator& to) { // All watchers: // // for (int i = 0; i < watches.size(); i++) watches.cleanAll(); watchesBin.cleanAll(); for (int v = 0; v < nVars(); v++) for (int s = 0; s < 2; s++){ Lit p = mkLit(v, s); // printf(" >>> RELOCING: %s%d\n", sign(p)?"-":"", var(p)+1); vec<Watcher>& ws = watches[p]; for (int j = 0; j < ws.size(); j++) ca.reloc(ws[j].cref, to); vec<Watcher>& ws2 = watchesBin[p]; for (int j = 0; j < ws2.size(); j++) ca.reloc(ws2[j].cref, to); } // All reasons: // for (int i = 0; i < trail.size(); i++){ Var v = var(trail[i]); if (reason(v) != CRef_Undef && (ca[reason(v)].reloced() || locked(ca[reason(v)]))) ca.reloc(vardata[v].reason, to); } // All learnt: // #define X(V) for (I = 0; I < V.size();) ca.reloc(V[I++], to); X(C); X(T); for (int i = 0; i < learnts.size(); i++) ca.reloc(learnts[i], to); // All original: // for (int i = 0; i < clauses.size(); i++) ca.reloc(clauses[i], to); } inline void Solver::garbageCollect() { // Initialize the next region to a size corresponding to the estimated utilization degree. This // is not precise but should avoid some unnecessary reallocations for the new region: ClauseAllocator to(ca.size() - ca.wasted()); relocAll(to); if (verbosity >= 2) printf("| Garbage collection: %12d bytes => %12d bytes |\n", ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size); to.moveTo(ca); } } /************************************************************************************[SimpSolver.h] Copyright (c) 2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #ifndef Ghack_SimpSolver_h #define Ghack_SimpSolver_h namespace GHack { //================================================================================================= class SimpSolver : public Solver { public: // Constructor/Destructor: // SimpSolver(); ~SimpSolver(); // Problem specification: // Var newVar (bool polarity = true, bool dvar = true); bool addClause (const vec<Lit>& ps); bool addEmptyClause(); // Add the empty clause to the solver. bool addClause (Lit p); // Add a unit clause to the solver. bool addClause (Lit p, Lit q); // Add a binary clause to the solver. bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver. bool addClause_( vec<Lit>& ps); bool substitute(Var v, Lit x); // Replace all occurences of v with x (may cause a contradiction). // Variable mode: // void setFrozen (Var v, bool b); // If a variable is frozen it will not be eliminated. bool isEliminated(Var v) const; // Solving: // bool solve (const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false); lbool solveLimited(const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false); bool solve ( bool do_simp = true, bool turn_off_simp = false); bool solve (Lit p , bool do_simp = true, bool turn_off_simp = false); bool solve (Lit p, Lit q, bool do_simp = true, bool turn_off_simp = false); bool solve (Lit p, Lit q, Lit r, bool do_simp = true, bool turn_off_simp = false); bool eliminate (bool turn_off_elim = false); // Perform variable elimination based simplification. // Memory managment: // virtual void garbageCollect(); // Generate a (possibly simplified) DIMACS file: // #if 0 void toDimacs (const char* file, const vec<Lit>& assumps); void toDimacs (const char* file); void toDimacs (const char* file, Lit p); void toDimacs (const char* file, Lit p, Lit q); void toDimacs (const char* file, Lit p, Lit q, Lit r); #endif // Mode of operation: // int parsing; int grow; // Allow a variable elimination step to grow by a number of clauses (default to zero). int clause_lim; // Variables are not eliminated if it produces a resolvent with a length above this limit. // -1 means no limit. int subsumption_lim; // Do not check if subsumption against a clause larger than this. -1 means no limit. double simp_garbage_frac; // A different limit for when to issue a GC during simplification (Also see 'garbage_frac'). bool use_asymm; // Shrink clauses by asymmetric branching. bool use_rcheck; // Check if a clause is already implied. Prett costly, and subsumes subsumptions :) bool use_elim; // Perform variable elimination. // Statistics: // int merges; int asymm_lits; int eliminated_vars; protected: // Helper structures: // struct ElimLt { const vec<int>& n_occ; explicit ElimLt(const vec<int>& no) : n_occ(no) {} // TODO: are 64-bit operations here noticably bad on 32-bit platforms? Could use a saturating // 32-bit implementation instead then, but this will have to do for now. uint64_t cost (Var x) const { return (uint64_t)n_occ[toInt(mkLit(x))] * (uint64_t)n_occ[toInt(~mkLit(x))]; } bool operator()(Var x, Var y) const { return cost(x) < cost(y); } // TODO: investigate this order alternative more. // bool operator()(Var x, Var y) const { // int c_x = cost(x); // int c_y = cost(y); // return c_x < c_y || c_x == c_y && x < y; } }; struct ClauseDeleted { const ClauseAllocator& ca; explicit ClauseDeleted(const ClauseAllocator& _ca) : ca(_ca) {} bool operator()(const CRef& cr) const { return ca[cr].mark() == 1; } }; // Solver state: // int elimorder; bool use_simplification; vec<uint32_t> elimclauses; vec<char> touched; OccLists<Var, vec<CRef>, ClauseDeleted> occurs; vec<int> n_occ; Heap<ElimLt> elim_heap; Queue<CRef> subsumption_queue; vec<char> frozen; vec<char> eliminated; int bwdsub_assigns; int n_touched; // Temporaries: // CRef bwdsub_tmpunit; // Main internal methods: // lbool solve_ (bool do_simp = true, bool turn_off_simp = false); bool asymm (Var v, CRef cr); bool asymmVar (Var v); void updateElimHeap (Var v); void gatherTouchedClauses (); bool merge (const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause); bool merge (const Clause& _ps, const Clause& _qs, Var v, int& size); bool backwardSubsumptionCheck (bool verbose = false); bool eliminateVar (Var v); void extendModel (); void removeClause (CRef cr); bool strengthenClause (CRef cr, Lit l); void cleanUpClauses (); bool implied (const vec<Lit>& c); void relocAll (ClauseAllocator& to); }; //================================================================================================= // Implementation of inline methods: inline bool SimpSolver::isEliminated (Var v) const { return eliminated[v]; } inline void SimpSolver::updateElimHeap(Var v) { assert(use_simplification); // if (!frozen[v] && !isEliminated(v) && value(v) == l_Undef) if (elim_heap.inHeap(v) || (!frozen[v] && !isEliminated(v) && value(v) == l_Undef)) elim_heap.update(v); } inline bool SimpSolver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); } inline bool SimpSolver::addEmptyClause() { add_tmp.clear(); return addClause_(add_tmp); } inline bool SimpSolver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); } inline bool SimpSolver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); } inline bool SimpSolver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); } inline void SimpSolver::setFrozen (Var v, bool b) { frozen[v] = (char)b; if (use_simplification && !b) { updateElimHeap(v); } } inline bool SimpSolver::solve ( bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); return solve_(do_simp, turn_off_simp) == l_True; } inline bool SimpSolver::solve (Lit p , bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_(do_simp, turn_off_simp) == l_True; } inline bool SimpSolver::solve (Lit p, Lit q, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_(do_simp, turn_off_simp) == l_True; } inline bool SimpSolver::solve (Lit p, Lit q, Lit r, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_(do_simp, turn_off_simp) == l_True; } inline bool SimpSolver::solve (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){ budgetOff(); assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp) == l_True; } inline lbool SimpSolver::solveLimited (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){ assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp); } //================================================================================================= } #endif /***********************************************************************************[SimpSolver.cc] Copyright (c) 2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ namespace GHack { //================================================================================================= // Options: static BoolOption opt_use_asymm ("SIMP", "asymm", "Shrink clauses by asymmetric branching.", false); static BoolOption opt_use_rcheck ("SIMP", "rcheck", "Check if a clause is already implied. (costly)", false); static BoolOption opt_use_elim ("SIMP", "elim", "Perform variable elimination.", true); static IntOption opt_grow ("SIMP", "grow", "Allow a variable elimination step to grow by a number of clauses.", 0); static IntOption opt_clause_lim ("SIMP", "cl-lim", "Variables are not eliminated if it produces a resolvent with a length above this limit. -1 means no limit", 20, IntRange(-1, INT32_MAX)); static IntOption opt_subsumption_lim ("SIMP", "sub-lim", "Do not check if subsumption against a clause larger than this. -1 means no limit.", 1000, IntRange(-1, INT32_MAX)); static DoubleOption opt_simp_garbage_frac("SIMP", "simp-gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered during simplification.", 0.5, DoubleRange(0, false, HUGE_VAL, false)); //================================================================================================= // Constructor/Destructor: inline SimpSolver::SimpSolver() : grow (opt_grow) , clause_lim (opt_clause_lim) , subsumption_lim (opt_subsumption_lim) , simp_garbage_frac (opt_simp_garbage_frac) , use_asymm (opt_use_asymm) , use_rcheck (opt_use_rcheck) , use_elim (opt_use_elim) , merges (0) , asymm_lits (0) , eliminated_vars (0) , elimorder (1) , use_simplification (true) , occurs (ClauseDeleted(ca)) , elim_heap (ElimLt(n_occ)) , bwdsub_assigns (0) , n_touched (0) { vec<Lit> dummy(1,lit_Undef); ca.extra_clause_field = true; // NOTE: must happen before allocating the dummy clause below. bwdsub_tmpunit = ca.alloc(dummy); remove_satisfied = false; } inline SimpSolver::~SimpSolver() { } inline Var SimpSolver::newVar(bool sign, bool dvar) { Var v = Solver::newVar(sign, dvar); frozen .push((char)false); eliminated.push((char)false); if (use_simplification){ n_occ .push(0); n_occ .push(0); occurs .init(v); touched .push(0); elim_heap .insert(v); } return v; } inline lbool SimpSolver::solve_(bool do_simp, bool turn_off_simp) { vec<Var> extra_frozen; lbool result = l_True; do_simp &= use_simplification; if (do_simp){ // Assumptions must be temporarily frozen to run variable elimination: for (int i = 0; i < assumptions.size(); i++){ Var v = var(assumptions[i]); // If an assumption has been eliminated, remember it. assert(!isEliminated(v)); if (!frozen[v]){ // Freeze and store. setFrozen(v, true); extra_frozen.push(v); } } result = lbool(eliminate(turn_off_simp)); } if (result == l_True) result = Solver::solve_(); else if (verbosity >= 1) printf("===============================================================================\n"); if (result == l_True) extendModel(); if (do_simp) // Unfreeze the assumptions that were frozen: for (int i = 0; i < extra_frozen.size(); i++) setFrozen(extra_frozen[i], false); return result; } inline bool SimpSolver::addClause_(vec<Lit>& ps) { #ifndef NDEBUG for (int i = 0; i < ps.size(); i++) assert(!isEliminated(var(ps[i]))); #endif int nclauses = clauses.size(); if (use_rcheck && implied(ps)) return true; if (!Solver::addClause_(ps)) return false; if(!parsing && certifiedUNSAT) { if (vbyte) { write_char('a'); for (int i = 0; i < ps.size(); i++) write_lit(2*(var(ps[i])+1) + sign(ps[i])); write_lit(0); } else { for (int i = 0; i < ps.size(); i++) fprintf(certifiedOutput, "%i " , (var(ps[i]) + 1) * (-2 * sign(ps[i]) + 1) ); fprintf(certifiedOutput, "0\n"); } } if (use_simplification && clauses.size() == nclauses + 1){ CRef cr = clauses.last(); const Clause& c = ca[cr]; // NOTE: the clause is added to the queue immediately and then // again during 'gatherTouchedClauses()'. If nothing happens // in between, it will only be checked once. Otherwise, it may // be checked twice unnecessarily. This is an unfortunate // consequence of how backward subsumption is used to mimic // forward subsumption. subsumption_queue.insert(cr); for (int i = 0; i < c.size(); i++){ occurs[var(c[i])].push(cr); n_occ[toInt(c[i])]++; touched[var(c[i])] = 1; n_touched++; if (elim_heap.inHeap(var(c[i]))) elim_heap.increase(var(c[i])); } } return true; } inline void SimpSolver::removeClause(CRef cr) { const Clause& c = ca[cr]; if (use_simplification) for (int i = 0; i < c.size(); i++){ n_occ[toInt(c[i])]--; updateElimHeap(var(c[i])); occurs.smudge(var(c[i])); } Solver::removeClause(cr); } inline bool SimpSolver::strengthenClause(CRef cr, Lit l) { Clause& c = ca[cr]; assert(decisionLevel() == 0); assert(use_simplification); // FIX: this is too inefficient but would be nice to have (properly implemented) // if (!find(subsumption_queue, &c)) subsumption_queue.insert(cr); if (certifiedUNSAT) { if (vbyte) { write_char('a'); for (int i = 0; i < c.size(); i++) if (c[i] != l) write_lit(2*(var(c[i])+1) + sign(c[i])); write_lit(0); } else { for (int i = 0; i < c.size(); i++) if (c[i] != l) fprintf(certifiedOutput, "%i " , (var(c[i]) + 1) * (-2 * sign(c[i]) + 1) ); fprintf(certifiedOutput, "0\n"); } } if (c.size() == 2){ removeClause(cr); c.strengthen(l); }else{ if (certifiedUNSAT) { if (vbyte) { write_char('d'); for (int i = 0; i < c.size(); i++) write_lit(2*(var(c[i])+1) + sign(c[i])); write_lit(0); } else { fprintf(certifiedOutput, "d "); for (int i = 0; i < c.size(); i++) fprintf(certifiedOutput, "%i " , (var(c[i]) + 1) * (-2 * sign(c[i]) + 1) ); fprintf(certifiedOutput, "0\n"); } } detachClause(cr, true); c.strengthen(l); attachClause(cr); remove(occurs[var(l)], cr); n_occ[toInt(l)]--; updateElimHeap(var(l)); } return c.size() == 1 ? enqueue(c[0]) && propagate() == CRef_Undef : true; } // Returns FALSE if clause is always satisfied ('out_clause' should not be used). inline bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause) { merges++; out_clause.clear(); bool ps_smallest = _ps.size() < _qs.size(); const Clause& ps = ps_smallest ? _qs : _ps; const Clause& qs = ps_smallest ? _ps : _qs; for (int i = 0; i < qs.size(); i++){ if (var(qs[i]) != v){ for (int j = 0; j < ps.size(); j++) if (var(ps[j]) == var(qs[i])) if (ps[j] == ~qs[i]) return false; else goto next; out_clause.push(qs[i]); } next:; } for (int i = 0; i < ps.size(); i++) if (var(ps[i]) != v) out_clause.push(ps[i]); return true; } // Returns FALSE if clause is always satisfied. inline bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, int& size) { merges++; bool ps_smallest = _ps.size() < _qs.size(); const Clause& ps = ps_smallest ? _qs : _ps; const Clause& qs = ps_smallest ? _ps : _qs; const Lit* __ps = (const Lit*)ps; const Lit* __qs = (const Lit*)qs; size = ps.size()-1; for (int i = 0; i < qs.size(); i++){ if (var(__qs[i]) != v){ for (int j = 0; j < ps.size(); j++) if (var(__ps[j]) == var(__qs[i])) if (__ps[j] == ~__qs[i]) return false; else goto next; size++; } next:; } return true; } inline void SimpSolver::gatherTouchedClauses() { if (n_touched == 0) return; int i,j; for (i = j = 0; i < subsumption_queue.size(); i++) if (ca[subsumption_queue[i]].mark() == 0) ca[subsumption_queue[i]].mark(2); for (i = 0; i < touched.size(); i++) if (touched[i]){ const vec<CRef>& cs = occurs.lookup(i); for (j = 0; j < cs.size(); j++) if (ca[cs[j]].mark() == 0){ subsumption_queue.insert(cs[j]); ca[cs[j]].mark(2); } touched[i] = 0; } for (i = 0; i < subsumption_queue.size(); i++) if (ca[subsumption_queue[i]].mark() == 2) ca[subsumption_queue[i]].mark(0); n_touched = 0; } inline bool SimpSolver::implied(const vec<Lit>& c) { assert(decisionLevel() == 0); trail_lim.push(trail.size()); for (int i = 0; i < c.size(); i++) if (value(c[i]) == l_True){ cancelUntil(0); return false; }else if (value(c[i]) != l_False){ assert(value(c[i]) == l_Undef); uncheckedEnqueue(~c[i]); } bool result = propagate() != CRef_Undef; cancelUntil(0); return result; } // Backward subsumption + backward subsumption resolution inline bool SimpSolver::backwardSubsumptionCheck(bool verbose) { int cnt = 0; int subsumed = 0; int deleted_literals = 0; assert(decisionLevel() == 0); while (subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()){ // Empty subsumption queue and return immediately on user-interrupt: if (asynch_interrupt){ subsumption_queue.clear(); bwdsub_assigns = trail.size(); break; } // Check top-level assignments by creating a dummy clause and placing it in the queue: if (subsumption_queue.size() == 0 && bwdsub_assigns < trail.size()){ Lit l = trail[bwdsub_assigns++]; ca[bwdsub_tmpunit][0] = l; ca[bwdsub_tmpunit].calcAbstraction(); subsumption_queue.insert(bwdsub_tmpunit); } CRef cr = subsumption_queue.peek(); subsumption_queue.pop(); Clause& c = ca[cr]; if (c.mark()) continue; if (verbose && verbosity >= 2 && cnt++ % 1000 == 0) printf("subsumption left: %10d (%10d subsumed, %10d deleted literals)\r", subsumption_queue.size(), subsumed, deleted_literals); assert(c.size() > 1 || value(c[0]) == l_True); // Unit-clauses should have been propagated before this point. // Find best variable to scan: Var best = var(c[0]); for (int i = 1; i < c.size(); i++) if (occurs[var(c[i])].size() < occurs[best].size()) best = var(c[i]); // Search all candidates: vec<CRef>& _cs = occurs.lookup(best); CRef* cs = (CRef*)_cs; for (int j = 0; j < _cs.size(); j++) if (c.mark()) break; else if (!ca[cs[j]].mark() && cs[j] != cr && (subsumption_lim == -1 || ca[cs[j]].size() < subsumption_lim)){ Lit l = c.subsumes(ca[cs[j]]); if (l == lit_Undef) subsumed++, removeClause(cs[j]); else if (l != lit_Error){ deleted_literals++; if (!strengthenClause(cs[j], ~l)) return false; // Did current candidate get deleted from cs? Then check candidate at index j again: if (var(l) == best) j--; } } } return true; } inline bool SimpSolver::asymm(Var v, CRef cr) { Clause& c = ca[cr]; assert(decisionLevel() == 0); if (c.mark() || satisfied(c)) return true; trail_lim.push(trail.size()); Lit l = lit_Undef; for (int i = 0; i < c.size(); i++) if (var(c[i]) != v && value(c[i]) != l_False) uncheckedEnqueue(~c[i]); else l = c[i]; if (propagate() != CRef_Undef){ cancelUntil(0); asymm_lits++; if (!strengthenClause(cr, l)) return false; }else cancelUntil(0); return true; } inline bool SimpSolver::asymmVar(Var v) { assert(use_simplification); const vec<CRef>& cls = occurs.lookup(v); if (value(v) != l_Undef || cls.size() == 0) return true; for (int i = 0; i < cls.size(); i++) if (!asymm(v, cls[i])) return false; return backwardSubsumptionCheck(); } static void mkElimClause(vec<uint32_t>& elimclauses, Lit x) { elimclauses.push(toInt(x)); elimclauses.push(1); } static void mkElimClause(vec<uint32_t>& elimclauses, Var v, Clause& c) { int first = elimclauses.size(); int v_pos = -1; // Copy clause to elimclauses-vector. Remember position where the // variable 'v' occurs: for (int i = 0; i < c.size(); i++){ elimclauses.push(toInt(c[i])); if (var(c[i]) == v) v_pos = i + first; } assert(v_pos != -1); // Swap the first literal with the 'v' literal, so that the literal // containing 'v' will occur first in the clause: uint32_t tmp = elimclauses[v_pos]; elimclauses[v_pos] = elimclauses[first]; elimclauses[first] = tmp; // Store the length of the clause last: elimclauses.push(c.size()); } inline bool SimpSolver::eliminateVar(Var v) { assert(!frozen[v]); assert(!isEliminated(v)); assert(value(v) == l_Undef); // Split the occurrences into positive and negative: // const vec<CRef>& cls = occurs.lookup(v); vec<CRef> pos, neg; for (int i = 0; i < cls.size(); i++) (find(ca[cls[i]], mkLit(v)) ? pos : neg).push(cls[i]); // Check wether the increase in number of clauses stays within the allowed ('grow'). Moreover, no // clause must exceed the limit on the maximal clause size (if it is set): // int cnt = 0; int clause_size = 0; for (int i = 0; i < pos.size(); i++) for (int j = 0; j < neg.size(); j++) if (merge(ca[pos[i]], ca[neg[j]], v, clause_size) && (++cnt > cls.size() + grow || (clause_lim != -1 && clause_size > clause_lim))) return true; // Delete and store old clauses: eliminated[v] = true; setDecisionVar(v, false); eliminated_vars++; if (pos.size() > neg.size()){ for (int i = 0; i < neg.size(); i++) mkElimClause(elimclauses, v, ca[neg[i]]); mkElimClause(elimclauses, mkLit(v)); }else{ for (int i = 0; i < pos.size(); i++) mkElimClause(elimclauses, v, ca[pos[i]]); mkElimClause(elimclauses, ~mkLit(v)); } // Produce clauses in cross product: vec<Lit>& resolvent = add_tmp; for (int i = 0; i < pos.size(); i++) for (int j = 0; j < neg.size(); j++) if (merge(ca[pos[i]], ca[neg[j]], v, resolvent) && !addClause_(resolvent)) return false; for (int i = 0; i < cls.size(); i++) removeClause(cls[i]); // Free occurs list for this variable: occurs[v].clear(true); // Free watchers lists for this variable, if possible: if (watches[ mkLit(v)].size() == 0) watches[ mkLit(v)].clear(true); if (watches[~mkLit(v)].size() == 0) watches[~mkLit(v)].clear(true); return backwardSubsumptionCheck(); } inline bool SimpSolver::substitute(Var v, Lit x) { assert(!frozen[v]); assert(!isEliminated(v)); assert(value(v) == l_Undef); if (!ok) return false; eliminated[v] = true; setDecisionVar(v, false); const vec<CRef>& cls = occurs.lookup(v); vec<Lit>& subst_clause = add_tmp; for (int i = 0; i < cls.size(); i++){ Clause& c = ca[cls[i]]; subst_clause.clear(); for (int j = 0; j < c.size(); j++){ Lit p = c[j]; subst_clause.push(var(p) == v ? x ^ sign(p) : p); } if (!addClause_(subst_clause)) return ok = false; removeClause(cls[i]); } return true; } inline void SimpSolver::extendModel() { int i, j; Lit x; for (i = elimclauses.size()-1; i > 0; i -= j){ for (j = elimclauses[i--]; j > 1; j--, i--) if (modelValue(toLit(elimclauses[i])) != l_False) goto next; x = toLit(elimclauses[i]); model[var(x)] = lbool(!sign(x)); next:; } } inline bool SimpSolver::eliminate(bool turn_off_elim) { if (!simplify()) return false; else if (!use_simplification) return true; // Main simplification loop: // int toPerform = 1; clauses.size()<=4800000; if(!toPerform) { printf("c Too many clauses... No preprocessing\n"); } while (toPerform && (n_touched > 0 || bwdsub_assigns < trail.size() || elim_heap.size() > 0)){ gatherTouchedClauses(); // printf(" ## (time = %6.2f s) BWD-SUB: queue = %d, trail = %d\n", cpuTime(), subsumption_queue.size(), trail.size() - bwdsub_assigns); if ((subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()) && !backwardSubsumptionCheck(true)){ ok = false; goto cleanup; } // Empty elim_heap and return immediately on user-interrupt: if (asynch_interrupt){ assert(bwdsub_assigns == trail.size()); assert(subsumption_queue.size() == 0); assert(n_touched == 0); elim_heap.clear(); goto cleanup; } // printf(" ## (time = %6.2f s) ELIM: vars = %d\n", cpuTime(), elim_heap.size()); for (int cnt = 0; !elim_heap.empty(); cnt++){ Var elim = elim_heap.removeMin(); if (asynch_interrupt) break; if (isEliminated(elim) || value(elim) != l_Undef) continue; if (verbosity >= 2 && cnt % 100 == 0) printf("elimination left: %10d\r", elim_heap.size()); if (use_asymm){ // Temporarily freeze variable. Otherwise, it would immediately end up on the queue again: bool was_frozen = frozen[elim]; frozen[elim] = true; if (!asymmVar(elim)){ ok = false; goto cleanup; } frozen[elim] = was_frozen; } // At this point, the variable may have been set by assymetric branching, so check it // again. Also, don't eliminate frozen variables: if (use_elim && value(elim) == l_Undef && !frozen[elim] && !eliminateVar(elim)){ ok = false; goto cleanup; } checkGarbage(simp_garbage_frac); } assert(subsumption_queue.size() == 0); } cleanup: // If no more simplification is needed, free all simplification-related data structures: if (turn_off_elim){ touched .clear(true); occurs .clear(true); n_occ .clear(true); elim_heap.clear(true); subsumption_queue.clear(true); use_simplification = false; remove_satisfied = true; ca.extra_clause_field = false; // Force full cleanup (this is safe and desirable since it only happens once): rebuildOrderHeap(); garbageCollect(); }else{ // Cheaper cleanup: cleanUpClauses(); // TODO: can we make 'cleanUpClauses()' not be linear in the problem size somehow? checkGarbage(); } if (verbosity >= 1 && elimclauses.size() > 0) printf("c | Eliminated clauses: %10.2f Mb |\n", double(elimclauses.size() * sizeof(uint32_t)) / (1024*1024)); return ok; } inline void SimpSolver::cleanUpClauses() { occurs.cleanAll(); int i,j; for (i = j = 0; i < clauses.size(); i++) if (ca[clauses[i]].mark() == 0) clauses[j++] = clauses[i]; clauses.shrink(i - j); } //================================================================================================= // Garbage Collection methods: inline void SimpSolver::relocAll(ClauseAllocator& to) { if (!use_simplification) return; // All occurs lists: // for (int i = 0; i < nVars(); i++){ vec<CRef>& cs = occurs[i]; for (int j = 0; j < cs.size(); j++) ca.reloc(cs[j], to); } // Subsumption queue: // for (int i = 0; i < subsumption_queue.size(); i++) ca.reloc(subsumption_queue[i], to); // Temporary clause: // ca.reloc(bwdsub_tmpunit, to); } inline void SimpSolver::garbageCollect() { // Initialize the next region to a size corresponding to the estimated utilization degree. This // is not precise but should avoid some unnecessary reallocations for the new region: ClauseAllocator to(ca.size() - ca.wasted()); cleanUpClauses(); to.extra_clause_field = ca.extra_clause_field; // NOTE: this is important to keep (or lose) the extra fields. relocAll(to); Solver::relocAll(to); if (verbosity >= 2) printf("| Garbage collection: %12d bytes => %12d bytes |\n", ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size); to.moveTo(ca); } } #undef write_char #undef var_Undef #undef DYNAMICNBLEVEL #undef CONSTANTREMOVECLAUSE #undef UPDATEVARACTIVITY #undef RATIOREMOVECLAUSES #undef LOWER_BOUND_FOR_BLOCKING_RESTART #undef M #undef Q #undef P #undef B #undef S #undef EE #undef X
35.979949
243
0.556745
osamamowafy
44cbb1b0cfc3179102cd0bb74edd30370d79a44c
383
cpp
C++
Introductory-Problems/repetitions.cpp
LazyCoder-1506/CSES-Solutions
23430cf2bed7197130a022b7b44a90ee8e13237c
[ "MIT" ]
null
null
null
Introductory-Problems/repetitions.cpp
LazyCoder-1506/CSES-Solutions
23430cf2bed7197130a022b7b44a90ee8e13237c
[ "MIT" ]
null
null
null
Introductory-Problems/repetitions.cpp
LazyCoder-1506/CSES-Solutions
23430cf2bed7197130a022b7b44a90ee8e13237c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define int long long int void solve() { string s; cin >> s; int n = s.length(); int rep = 0; int cnt = 1; for (int i = 1; i < n ; i++) { if (s[i] == s[i - 1]) { cnt++; } else { rep = max(rep, cnt); cnt = 1; } } cout << max(rep, cnt) << "\n"; } signed main() { solve(); return 0; }
14.730769
32
0.456919
LazyCoder-1506
44cc781daca41bf2f50fe61cfe53117d575f1a82
5,069
hpp
C++
falcon/literal/utility.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
2
2018-02-02T14:19:59.000Z
2018-05-13T02:48:24.000Z
falcon/literal/utility.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
falcon/literal/utility.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
#ifndef FALCON_LITERAL_UTILITY_HPP #define FALCON_LITERAL_UTILITY_HPP #include <falcon/literal/detail/literal_support.hpp> #include <type_traits> #include <limits> #include <falcon/type_traits/eval_if.hpp> #include <falcon/type_traits/use.hpp> namespace falcon { namespace literal { template<typename _CharT, _CharT c> struct is_digit : std::integral_constant<bool, (_CharT('0') <= c && c <= _CharT('9'))> {}; template<std::size_t position> struct check_false : std::false_type { static const std::size_t last_position = position; }; template<std::size_t position> struct check_true : std::true_type { static const std::size_t last_position = position; }; template<std::size_t position, typename _CharT, _CharT... chars> struct __is_integral_base_10; template<std::size_t position, typename _CharT, _CharT c, _CharT... chars> struct __is_integral_base_10<position, _CharT, c, chars...> : if_c< is_digit<_CharT, c>, __is_integral_base_10<position + 1, _CharT, chars...>, check_false<position> >::type { static const std::size_t last_position = position; }; template<std::size_t position, typename _CharT> struct __is_integral_base_10<position, _CharT> : check_true<position> {}; template<typename _CharT, _CharT... chars> struct is_integral : __is_integral_base_10<0, _CharT, chars...> {}; template<typename _CharT> struct is_integral<_CharT> : check_false<0> {}; template<std::size_t position, typename _CharT, _CharT... chars> struct __is_floating_point_base_10; template<std::size_t position, typename _CharT, _CharT c, _CharT... chars> struct __is_floating_point_base_10<position, _CharT, c, chars...> : eval_if< c == _CharT('.'), use<__is_integral_base_10<position + 1, _CharT, chars...>>, if_c< is_digit<_CharT, c>, __is_floating_point_base_10<position + 1, _CharT, chars...>, check_false<position> > >::type {}; template<std::size_t position, typename _CharT> struct __is_floating_point_base_10<position, _CharT> : check_true<position> {}; template<typename _CharT, _CharT... chars> struct is_floating_point : __is_floating_point_base_10<0, _CharT, chars...> {}; template<typename _CharT> struct is_floating_point<_CharT> : check_false<0> {}; template<typename _CharT, _CharT c> struct is_floating_point<_CharT, c> : if_<(c == _CharT('.')), check_false<1>, check_true<1>>::type {}; template<typename _To, typename _CharT, _CharT... chars> struct __check_convert_integral { static_assert(is_integral<_CharT, chars...>::value, "value is not integral"); }; template<typename _To, unsigned long long ullvalue> struct __to_value { static_assert((ullvalue <= static_cast<unsigned long long>(std::numeric_limits<_To>::max())), "overflow in implicit constant conversion"); static const _To __value = static_cast<_To>(ullvalue); }; template<typename _To, _To value, typename _CharT, _CharT c> struct __to_value_base_10 : __to_value<_To, value * 10 + (static_cast<_To>(c) - _To('0'))> {}; template<typename _To, _To value, typename _CharT, _CharT... chars> struct __convert_to_integral_base_10; template<typename _To, _To value, typename _CharT, _CharT c, _CharT... chars> struct __convert_to_integral_base_10<_To, value, _CharT, c, chars...> : __convert_to_integral_base_10< _To, __to_value_base_10<_To, value, _CharT, c>::__value, _CharT, chars... > { static_assert(is_digit<_CharT, c>(), "value is not integral"); }; template<typename _To, _To value, typename _CharT> struct __convert_to_integral_base_10<_To, value, _CharT> : std::integral_constant<_To, value> {}; template<typename _To, typename _CharT, _CharT... chars> struct __convert_to_integral : __convert_to_integral_base_10<_To, _To(0), _CharT, chars...> { static_assert(sizeof...(chars), "value is empty"); }; template<bool, bool, typename _To, typename _CharT, _CharT... chars> struct __convert_to; template<typename _To, typename _CharT, _CharT... chars> struct __convert_to<true, false, _To, _CharT, chars...> : __convert_to_integral<_To, _CharT, chars...> {}; // template<typename _To, typename _CharT, _CharT... chars> // struct __convert_to<false, true, _To, _CharT, chars...> // : __convert_to_floating_point<_To, _CharT, chars...> // {}; template<typename _To, typename _CharT, _CharT... chars> struct basic_convert_to : __convert_to< std::is_integral<_To>::value, std::is_floating_point<_To>::value, _To, _CharT, chars...> {}; template<typename _To, char... chars> using convert_to = basic_convert_to<_To, char, chars...>; template<char... chars> using to_short = convert_to<short, chars...>; template<char... chars> using to_int = convert_to<int, chars...>; template<char... chars> using to_long = convert_to<long, chars...>; template<char... chars> using to_long_long = convert_to<long long, chars...>; template<char... chars> using to_ushort = convert_to<unsigned short, chars...>; template<char... chars> using to_uint = convert_to<unsigned int, chars...>; template<char... chars> using to_ulong = convert_to<unsigned long, chars...>; template<char... chars> using to_ulong_long = convert_to<unsigned long long, chars...>; } } #endif
27.4
139
0.744526
jonathanpoelen
44cddaff027d71c261189ccf4f9a372801ca72b3
107,053
cpp
C++
src/aligner.cpp
lnceballosz/vg
82d8ba2f38299525c0b0a6b19dcb785d2c439cfa
[ "MIT" ]
null
null
null
src/aligner.cpp
lnceballosz/vg
82d8ba2f38299525c0b0a6b19dcb785d2c439cfa
[ "MIT" ]
null
null
null
src/aligner.cpp
lnceballosz/vg
82d8ba2f38299525c0b0a6b19dcb785d2c439cfa
[ "MIT" ]
null
null
null
// SPDX-FileCopyrightText: 2014 Erik Garrison // // SPDX-License-Identifier: MIT #include "aligner.hpp" #include "hash_map.hpp" //#define debug_print_score_matrices using namespace vg; using namespace std; using namespace vg::io; static const double quality_scale_factor = 10.0 / log(10.0); static const double exp_overflow_limit = log(std::numeric_limits<double>::max()); GSSWAligner::~GSSWAligner(void) { free(nt_table); free(score_matrix); } GSSWAligner::GSSWAligner(const int8_t* _score_matrix, int8_t _gap_open, int8_t _gap_extension, int8_t _full_length_bonus, double _gc_content) : deletion_aligner(_gap_open, _gap_extension) { log_base = recover_log_base(_score_matrix, _gc_content, 1e-12); // TODO: now that everything is in terms of score matrices, having match/mismatch is a bit // misleading, but a fair amount of code depends on them match = _score_matrix[0]; mismatch = -_score_matrix[1]; gap_open = _gap_open; gap_extension = _gap_extension; full_length_bonus = _full_length_bonus; // table to translate chars to their integer value nt_table = gssw_create_nt_table(); } gssw_graph* GSSWAligner::create_gssw_graph(const HandleGraph& g) const { vector<handle_t> topological_order = handlealgs::lazier_topological_order(&g); gssw_graph* graph = gssw_graph_create(g.get_node_count()); unordered_map<int64_t, gssw_node*> nodes; // compute the topological order for (const handle_t& handle : topological_order) { auto cleaned_seq = nonATGCNtoN(g.get_sequence(handle)); gssw_node* node = gssw_node_create(nullptr, // TODO: the ID should be enough, don't need Node* too g.get_id(handle), cleaned_seq.c_str(), nt_table, score_matrix); // TODO: this arg isn't used, could edit // in gssw nodes[node->id] = node; gssw_graph_add_node(graph, node); } g.for_each_edge([&](const edge_t& edge) { if(!g.get_is_reverse(edge.first) && !g.get_is_reverse(edge.second)) { // This is a normal end to start edge. gssw_nodes_add_edge(nodes[g.get_id(edge.first)], nodes[g.get_id(edge.second)]); } else if (g.get_is_reverse(edge.first) && g.get_is_reverse(edge.second)) { // This is a start to end edge, but isn't reversing and can be converted to a normal end to start edge. // Flip the start and end gssw_nodes_add_edge(nodes[g.get_id(edge.second)], nodes[g.get_id(edge.first)]); } else { // TODO: It's a reversing edge, which gssw doesn't support yet. What // we should really do is do a topological sort to break cycles, and // then flip everything at the lower-rank end of this edge around, // so we don't have to deal with its reversing-ness. But for now we // just die so we don't get nonsense into gssw. #pragma omp critical { // We need the critical section so we don't throw uncaught // exceptions in multiple threads at once, leading to C++ trying // to run termiante in parallel. This doesn't make it safe, just // slightly safer. cerr << "Can't gssw over reversing edge " << g.get_id(edge.first) << (g.get_is_reverse(edge.first) ? "-" : "+") << " -> " << g.get_id(edge.second) << (g.get_is_reverse(edge.second) ? "-" : "+") << endl; // TODO: there's no safe way to kill the program without a way // to signal the master to do it, via a shared variable in the // clause that made us parallel. } exit(1); } return true; }); return graph; } unordered_set<vg::id_t> GSSWAligner::identify_pinning_points(const HandleGraph& graph) const { unordered_set<vg::id_t> return_val; // start at the sink nodes vector<handle_t> sinks = handlealgs::tail_nodes(&graph); // walk backwards to find non-empty nodes if necessary for (const handle_t& handle : sinks) { vector<handle_t> stack(1, handle); while (!stack.empty()) { handle_t here = stack.back(); stack.pop_back(); if (graph.get_length(here) > 0) { return_val.insert(graph.get_id(here)); } else { graph.follow_edges(here, true, [&](const handle_t& prev) { // TODO: technically this won't filter out all redundant walks, but it should // handle all cases we're practically interested in and it doesn't require a // second set object if (!return_val.count(graph.get_id(prev))) { stack.push_back(prev); } }); } } } return return_val; } void GSSWAligner::gssw_mapping_to_alignment(gssw_graph* graph, gssw_graph_mapping* gm, Alignment& alignment, bool pinned, bool pin_left) const { alignment.clear_path(); alignment.set_score(gm->score); alignment.set_query_position(0); Path* path = alignment.mutable_path(); //alignment.set_cigar(graph_cigar(gm)); gssw_graph_cigar* gc = &gm->cigar; gssw_node_cigar* ncs = gc->elements; //cerr << "gm->position " << gm->position << endl; string& to_seq = *alignment.mutable_sequence(); //cerr << "-------------" << endl; #ifdef debug_print_score_matrices gssw_graph_print_score_matrices(graph, to_seq.c_str(), to_seq.size(), stderr); #endif int to_pos = 0; int from_pos = gm->position; for (int i = 0; i < gc->length; ++i) { // check that the current alignment has a non-zero length gssw_cigar* c = ncs[i].cigar; int l = c->length; if (l == 0) continue; gssw_cigar_element* e = c->elements; gssw_node* node = ncs[i].node; Mapping* mapping = path->add_mapping(); if (i > 0) { // reset for each node after the first from_pos = 0; } mapping->mutable_position()->set_node_id(node->id); mapping->mutable_position()->set_offset(from_pos); mapping->set_rank(path->mapping_size()); //cerr << node->id << ":" << endl; for (int j=0; j < l; ++j, ++e) { int32_t length = e->length; //cerr << e->length << e->type << endl; Edit* edit; switch (e->type) { case 'M': case 'X': case 'N': { //cerr << "j = " << j << ", type = " << e->type << endl; // do the sequences match? // emit a stream of "SNPs" and matches int h = from_pos; int last_start = from_pos; int k = to_pos; for ( ; h < from_pos + length; ++h, ++k) { //cerr << h << ":" << k << " " << node->seq[h] << " " << to_seq[k] << endl; if (node->seq[h] != to_seq[k]) { // emit the last "match" region if (h - last_start > 0) { edit = mapping->add_edit(); edit->set_from_length(h-last_start); edit->set_to_length(h-last_start); } // set up the SNP edit = mapping->add_edit(); edit->set_from_length(1); edit->set_to_length(1); edit->set_sequence(to_seq.substr(k,1)); last_start = h+1; } } // handles the match at the end or the case of no SNP if (h - last_start > 0) { edit = mapping->add_edit(); edit->set_from_length(h-last_start); edit->set_to_length(h-last_start); } to_pos += length; from_pos += length; } break; case 'D': edit = mapping->add_edit(); edit->set_from_length(length); edit->set_to_length(0); from_pos += length; break; case 'I': edit = mapping->add_edit(); edit->set_from_length(0); edit->set_to_length(length); edit->set_sequence(to_seq.substr(to_pos, length)); to_pos += length; break; case 'S': // note that soft clips and insertions are semantically equivalent // and can only be differentiated by their position in the read // with soft clips coming at the start or end edit = mapping->add_edit(); edit->set_from_length(0); edit->set_to_length(length); edit->set_sequence(to_seq.substr(to_pos, length)); to_pos += length; break; default: cerr << "error:[Aligner::gssw_mapping_to_alignment] " << "unsupported cigar op type " << e->type << endl; exit(1); break; } } } // compute and set identity alignment.set_identity(identity(alignment.path())); } void GSSWAligner::unreverse_graph(gssw_graph* graph) const { // this is only for getting correct reference-relative edits, so we can get away with only // reversing the sequences and not paying attention to the edges for (size_t i = 0; i < graph->size; i++) { gssw_node* node = graph->nodes[i]; for (int j = 0, stop = node->len / 2; j < stop; j++) { std::swap(node->seq[j], node->seq[node->len - j - 1]); } } } void GSSWAligner::unreverse_graph_mapping(gssw_graph_mapping* gm) const { gssw_graph_cigar* graph_cigar = &(gm->cigar); gssw_node_cigar* node_cigars = graph_cigar->elements; // reverse the order of the node cigars int32_t num_switching_nodes = graph_cigar->length / 2; int32_t last_idx = graph_cigar->length - 1; for (int32_t i = 0; i < num_switching_nodes; i++) { std::swap(node_cigars[i], node_cigars[last_idx - i]); } // reverse the actual cigar string for each node cigar for (int32_t i = 0; i < graph_cigar->length; i++) { gssw_cigar* node_cigar = node_cigars[i].cigar; gssw_cigar_element* elements = node_cigar->elements; int32_t num_switching_elements = node_cigar->length / 2; last_idx = node_cigar->length - 1; for (int32_t j = 0; j < num_switching_elements; j++) { std::swap(elements[j], elements[last_idx - j]); } } // compute the position in the first node if (graph_cigar->length > 0) { gssw_cigar_element* first_node_elements = node_cigars[0].cigar->elements; int32_t num_first_node_elements = node_cigars[0].cigar->length; uint32_t num_ref_aligned = 0; // the number of characters on the node sequence that are aligned for (int32_t i = 0; i < num_first_node_elements; i++) { switch (first_node_elements[i].type) { case 'M': case 'X': case 'N': case 'D': num_ref_aligned += first_node_elements[i].length; break; } } gm->position = node_cigars[0].node->len - num_ref_aligned - (graph_cigar->length == 1 ? gm->position : 0); } else { gm->position = 0; } } string GSSWAligner::graph_cigar(gssw_graph_mapping* gm) const { stringstream s; gssw_graph_cigar* gc = &gm->cigar; gssw_node_cigar* nc = gc->elements; int to_pos = 0; int from_pos = gm->position; //string& to_seq = *alignment.mutable_sequence(); s << from_pos << '@'; for (int i = 0; i < gc->length; ++i, ++nc) { if (i > 0) from_pos = 0; // reset for each node after the first Node* from_node = (Node*) nc->node->data; s << from_node->id() << ':'; gssw_cigar* c = nc->cigar; int l = c->length; gssw_cigar_element* e = c->elements; for (int j=0; j < l; ++j, ++e) { s << e->length << e->type; } if (i + 1 < gc->length) { s << ","; } } return s.str(); } double GSSWAligner::recover_log_base(const int8_t* score_matrix, double gc_content, double tol) const { // convert gc content into base-wise frequencies double* nt_freqs = (double*) malloc(sizeof(double) * 4); nt_freqs[0] = 0.5 * (1 - gc_content); nt_freqs[1] = 0.5 * gc_content; nt_freqs[2] = 0.5 * gc_content; nt_freqs[3] = 0.5 * (1 - gc_content); if (!verify_valid_log_odds_score_matrix(score_matrix, nt_freqs)) { cerr << "error:[Aligner] Score matrix is invalid. Must have a negative expected score against random sequence." << endl; exit(1); } // searching for a positive value (because it's a base of a logarithm) double lower_bound; double upper_bound; // arbitrary starting point greater than zero double lambda = 1.0; // search for a window containing lambda where total probability is 1 double partition = alignment_score_partition_function(lambda, score_matrix, nt_freqs); if (partition < 1.0) { lower_bound = lambda; while (partition <= 1.0) { lower_bound = lambda; lambda *= 2.0; partition = alignment_score_partition_function(lambda, score_matrix, nt_freqs); } upper_bound = lambda; } else { upper_bound = lambda; while (partition >= 1.0) { upper_bound = lambda; lambda /= 2.0; partition = alignment_score_partition_function(lambda, score_matrix, nt_freqs); } lower_bound = lambda; } // bisect to find a log base where total probability is 1 while (upper_bound / lower_bound - 1.0 > tol) { lambda = 0.5 * (lower_bound + upper_bound); if (alignment_score_partition_function(lambda, score_matrix, nt_freqs) < 1.0) { lower_bound = lambda; } else { upper_bound = lambda; } } free(nt_freqs); return 0.5 * (lower_bound + upper_bound); } bool GSSWAligner::verify_valid_log_odds_score_matrix(const int8_t* score_matrix, const double* nt_freqs) const { bool contains_positive_score = false; for (int i = 0; i < 16; i++) { if (score_matrix[i] > 0) { contains_positive_score = 1; break; } } if (!contains_positive_score) { return false; } double expected_score = 0.0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { expected_score += nt_freqs[i] * nt_freqs[j] * score_matrix[i * 4 + j]; } } return expected_score < 0.0; } double GSSWAligner::alignment_score_partition_function(double lambda, const int8_t* score_matrix, const double* nt_freqs) const { double partition = 0.0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { partition += nt_freqs[i] * nt_freqs[j] * exp(lambda * score_matrix[i * 4 + j]); } } if (isnan(partition)) { cerr << "error:[Aligner] overflow error in log-odds base recovery subroutine." << endl; exit(1); } return partition; } int32_t GSSWAligner::score_gap(size_t gap_length) const { return gap_length ? -gap_open - (gap_length - 1) * gap_extension : 0; } double GSSWAligner::maximum_mapping_quality_exact(const vector<double>& scaled_scores, size_t* max_idx_out, const vector<double>* multiplicities) { // work in log transformed values to avoid risk of overflow double log_sum_exp = numeric_limits<double>::lowest(); double max_score = numeric_limits<double>::lowest(); // go in reverse order because this has fewer numerical problems when the scores are sorted (as usual) for (int64_t i = scaled_scores.size() - 1; i >= 0; i--) { // get the value of one copy of the score and check if it's the max double score = scaled_scores.at(i); if (score >= max_score) { // Since we are going in reverse order, make sure to break ties in favor of the earlier item. *max_idx_out = i; max_score = score; } // add all copies of the score if (multiplicities && multiplicities->at(i) > 1.0) { score += log(multiplicities->at(i)); } // accumulate the sum of all score log_sum_exp = add_log(log_sum_exp, score); } // if necessary, assume a null alignment of 0.0 for comparison since this is local if (scaled_scores.size() == 1) { if (multiplicities && multiplicities->at(0) <= 1.0) { log_sum_exp = add_log(log_sum_exp, 0.0); } else if (!multiplicities) { log_sum_exp = add_log(log_sum_exp, 0.0); } } double direct_mapq = -quality_scale_factor * subtract_log(0.0, max_score - log_sum_exp); return std::isinf(direct_mapq) ? (double) numeric_limits<int32_t>::max() : direct_mapq; } // TODO: this algorithm has numerical problems that would be difficult to solve without increasing the // time complexity: adding the probability of the maximum likelihood tends to erase the contribution // of the other terms so that when you subtract them off you get scores of 0 or infinity //vector<double> Aligner::all_mapping_qualities_exact(vector<double>& scaled_scores) { // // double max_score = *max_element(scaled_scores.begin(), scaled_scores.end()); // size_t size = scaled_scores.size(); // // vector<double> mapping_qualities(size); // // if (max_score * size < exp_overflow_limit) { // // no risk of double overflow, sum exp directly (half as many transcendental function evals) // vector<double> exp_scaled_scores(size); // for (size_t i = 0; i < size; i++) { // exp_scaled_scores[i] = exp(scaled_scores[i]); // } // double denom = std::accumulate(exp_scaled_scores.begin(), exp_scaled_scores.end(), 0.0); // for (size_t i = 0; i < size; i++) { // mapping_qualities[i] = -10.0 * log10((denom - exp_scaled_scores[i]) / denom); // } // } // else { // // work in log transformed valued to avoid risk of overflow // double log_sum_exp = scaled_scores[0]; // for (size_t i = 1; i < size; i++) { // log_sum_exp = add_log(log_sum_exp, scaled_scores[i]); // } // for (size_t i = 0; i < size; i++) { // mapping_qualities[i] = -10.0 * log10(1.0 - exp(scaled_scores[i] - log_sum_exp)); // } // } // return mapping_qualities; //} double GSSWAligner::maximum_mapping_quality_approx(const vector<double>& scaled_scores, size_t* max_idx_out, const vector<double>* multiplicities) { assert(!scaled_scores.empty()); // determine the maximum score and the count of the next highest score double max_score = scaled_scores.at(0); size_t max_idx = 0; // we start with the possibility of a null score of 0.0 double next_score = 0.0; double next_count = 1.0; if (multiplicities) { if (multiplicities->at(0) > 1.0) { // there are extra copies of this one, so we'll init with those next_score = max_score; next_count = multiplicities->at(0) - 1.0; } } for (int32_t i = 1; i < scaled_scores.size(); ++i) { double score = scaled_scores.at(i); if (score > max_score) { if (multiplicities && multiplicities->at(i) > 1.0) { // there are extra counts of the new highest score due to multiplicity next_score = score; next_count = multiplicities->at(i) - 1.0; } else if (next_score == max_score) { // the next highest was the same score as the old max, so we can // add its count back in next_count += 1.0; } else { // the old max score is now the second highest next_score = max_score; next_count = multiplicities ? multiplicities->at(max_idx) : 1.0; } max_score = score; max_idx = i; } else if (score > next_score) { // the new score is the second highest next_score = score; next_count = multiplicities ? multiplicities->at(i) : 1.0; } else if (score == next_score) { // the new score ties the second highest, so we combine their counts next_count += multiplicities ? multiplicities->at(i) : 1.0; } } // record the index of the highest score *max_idx_out = max_idx; return max(0.0, quality_scale_factor * (max_score - next_score - (next_count > 1.0 ? log(next_count) : 0.0))); } double GSSWAligner::group_mapping_quality_exact(const vector<double>& scaled_scores, const vector<size_t>& group, const vector<double>* multiplicities) const { // work in log transformed values to avoid risk of overflow double total_log_sum_exp = numeric_limits<double>::lowest(); double non_group_log_sum_exp = numeric_limits<double>::lowest(); // go in reverse order because this has fewer numerical problems when the scores are sorted (as usual) int64_t group_idx = group.size() - 1; for (int64_t i = scaled_scores.size() - 1; i >= 0; i--) { // the score of one alignment double score = scaled_scores.at(i); // the score all the multiples of this score combined double multiple_score = score; if (multiplicities && multiplicities->at(i) > 1.0) { multiple_score += log(multiplicities->at(i)); } total_log_sum_exp = add_log(total_log_sum_exp, multiple_score); if (group_idx >= 0 && i == group[group_idx]) { // this is the next index in the group group_idx--; if (multiplicities && multiplicities->at(i) > 1.0) { // there's some remaining multiples of this score that don't get added into the group non_group_log_sum_exp = add_log(non_group_log_sum_exp, score + log(multiplicities->at(i) - 1.0)); } } else { // this index is not part of the group non_group_log_sum_exp = add_log(non_group_log_sum_exp, multiple_score); } } if (scaled_scores.size() == 1) { if (multiplicities && multiplicities->at(0) <= 1.0) { // assume a null alignment of 0.0 for comparison since this is local non_group_log_sum_exp = add_log(non_group_log_sum_exp, 0.0); total_log_sum_exp = add_log(total_log_sum_exp, 0.0); } else if (!multiplicities) { //TODO: repetitive, do I need to be this careful to not deref a null? // assume a null alignment of 0.0 for comparison since this is local non_group_log_sum_exp = add_log(non_group_log_sum_exp, 0.0); total_log_sum_exp = add_log(total_log_sum_exp, 0.0); } } double direct_mapq = quality_scale_factor * (total_log_sum_exp - non_group_log_sum_exp); return (std::isinf(direct_mapq) || direct_mapq > numeric_limits<int32_t>::max()) ? (double) numeric_limits<int32_t>::max() : direct_mapq; } void GSSWAligner::compute_mapping_quality(vector<Alignment>& alignments, int max_mapping_quality, bool fast_approximation, double cluster_mq, bool use_cluster_mq, int overlap_count, double mq_estimate, double maybe_mq_threshold, double identity_weight) const { assert(log_base > 0.0); if (alignments.empty()) { return; } vector<double> scaled_scores(alignments.size()); for (size_t i = 0; i < alignments.size(); i++) { scaled_scores[i] = log_base * alignments[i].score(); } double mapping_quality; size_t max_idx; if (!fast_approximation) { mapping_quality = maximum_mapping_quality_exact(scaled_scores, &max_idx); } else { mapping_quality = maximum_mapping_quality_approx(scaled_scores, &max_idx); } if (use_cluster_mq) { mapping_quality = prob_to_phred(sqrt(phred_to_prob(cluster_mq + mapping_quality))); } if (overlap_count) { mapping_quality -= quality_scale_factor * log(overlap_count); } auto& max_aln = alignments.at(max_idx); int l = max(alignment_to_length(max_aln), alignment_from_length(max_aln)); double identity = 1. - (double)(l * match - max_aln.score()) / (match + mismatch) / l; mapping_quality /= 2; mapping_quality *= pow(identity, identity_weight); if (mq_estimate < maybe_mq_threshold && mq_estimate < mapping_quality) { mapping_quality = prob_to_phred(sqrt(phred_to_prob(mq_estimate + mapping_quality))); } if (mapping_quality > max_mapping_quality) { mapping_quality = max_mapping_quality; } if (alignments[max_idx].score() == 0) { mapping_quality = 0; } alignments[max_idx].set_mapping_quality(max(0, (int32_t) round(mapping_quality))); for (int i = 1; i < alignments.size(); ++i) { alignments[0].add_secondary_score(alignments[i].score()); } } int32_t GSSWAligner::compute_mapping_quality(const vector<double>& scores, bool fast_approximation, const vector<double>* multiplicities) const { vector<double> scaled_scores(scores.size()); for (size_t i = 0; i < scores.size(); i++) { scaled_scores[i] = log_base * scores[i]; } size_t idx; return (int32_t) (fast_approximation ? maximum_mapping_quality_approx(scaled_scores, &idx, multiplicities) : maximum_mapping_quality_exact(scaled_scores, &idx, multiplicities)); } int32_t GSSWAligner::compute_group_mapping_quality(const vector<double>& scores, const vector<size_t>& group, const vector<double>* multiplicities) const { // make a non-const local version in case we need to sort it vector<size_t> non_const_group; const vector<size_t>* grp_ptr = &group; // ensure that group is in sorted order as following function expects if (!is_sorted(group.begin(), group.end())) { non_const_group = group; sort(non_const_group.begin(), non_const_group.end()); grp_ptr = &non_const_group; } vector<double> scaled_scores(scores.size(), 0.0); for (size_t i = 0; i < scores.size(); i++) { scaled_scores[i] = log_base * scores[i]; } return group_mapping_quality_exact(scaled_scores, *grp_ptr, multiplicities); } void GSSWAligner::compute_paired_mapping_quality(pair<vector<Alignment>, vector<Alignment>>& alignment_pairs, const vector<double>& frag_weights, int max_mapping_quality1, int max_mapping_quality2, bool fast_approximation, double cluster_mq, bool use_cluster_mq, int overlap_count1, int overlap_count2, double mq_estimate1, double mq_estimate2, double maybe_mq_threshold, double identity_weight) const { assert(log_base > 0.0); size_t size = min(alignment_pairs.first.size(), alignment_pairs.second.size()); if (size == 0) { return; } vector<double> scaled_scores(size); for (size_t i = 0; i < size; i++) { auto& aln1 = alignment_pairs.first[i]; auto& aln2 = alignment_pairs.second[i]; scaled_scores[i] = log_base * (aln1.score() + aln2.score()); // + frag_weights[i]); // ^^^ we could also incorporate the fragment weights, but this does not seem to help performance in the current form } size_t max_idx; double mapping_quality; if (!fast_approximation) { mapping_quality = maximum_mapping_quality_exact(scaled_scores, &max_idx); } else { mapping_quality = maximum_mapping_quality_approx(scaled_scores, &max_idx); } if (use_cluster_mq) { mapping_quality = prob_to_phred(sqrt(phred_to_prob(cluster_mq + mapping_quality))); } double mapping_quality1 = mapping_quality; double mapping_quality2 = mapping_quality; if (overlap_count1) { mapping_quality1 -= quality_scale_factor * log(overlap_count1); } if (overlap_count2) { mapping_quality2 -= quality_scale_factor * log(overlap_count2); } auto& max_aln1 = alignment_pairs.first.at(max_idx); int len1 = max(alignment_to_length(max_aln1), alignment_from_length(max_aln1)); double identity1 = 1. - (double)(len1 * match - max_aln1.score()) / (match + mismatch) / len1; auto& max_aln2 = alignment_pairs.second.at(max_idx); int len2 = max(alignment_to_length(max_aln2), alignment_from_length(max_aln2)); double identity2 = 1. - (double)(len2 * match - max_aln2.score()) / (match + mismatch) / len2; mapping_quality1 /= 2; mapping_quality2 /= 2; mapping_quality1 *= pow(identity1, identity_weight); mapping_quality2 *= pow(identity2, identity_weight); double mq_estimate = min(mq_estimate1, mq_estimate2); if (mq_estimate < maybe_mq_threshold && mq_estimate < mapping_quality1) { mapping_quality1 = prob_to_phred(sqrt(phred_to_prob(mq_estimate + mapping_quality1))); } if (mq_estimate < maybe_mq_threshold && mq_estimate < mapping_quality2) { mapping_quality2 = prob_to_phred(sqrt(phred_to_prob(mq_estimate + mapping_quality2))); } if (mapping_quality1 > max_mapping_quality1) { mapping_quality1 = max_mapping_quality1; } if (mapping_quality2 > max_mapping_quality2) { mapping_quality2 = max_mapping_quality2; } if (alignment_pairs.first[max_idx].score() == 0) { mapping_quality1 = 0; } if (alignment_pairs.second[max_idx].score() == 0) { mapping_quality2 = 0; } mapping_quality = max(0, (int32_t)round(min(mapping_quality1, mapping_quality2))); alignment_pairs.first[max_idx].set_mapping_quality(mapping_quality); alignment_pairs.second[max_idx].set_mapping_quality(mapping_quality); for (int i = 1; i < alignment_pairs.first.size(); ++i) { alignment_pairs.first[0].add_secondary_score(alignment_pairs.first[i].score()); } for (int i = 1; i < alignment_pairs.second.size(); ++i) { alignment_pairs.second[0].add_secondary_score(alignment_pairs.second[i].score()); } } double GSSWAligner::mapping_quality_score_diff(double mapping_quality) const { return mapping_quality / (quality_scale_factor * log_base); } double GSSWAligner::estimate_next_best_score(int length, double min_diffs) const { return ((length - min_diffs) * match - min_diffs * mismatch); } double GSSWAligner::max_possible_mapping_quality(int length) const { double max_score = log_base * length * match; vector<double> v = { max_score }; size_t max_idx; return maximum_mapping_quality_approx(v, &max_idx); } double GSSWAligner::estimate_max_possible_mapping_quality(int length, double min_diffs, double next_min_diffs) const { double max_score = log_base * ((length - min_diffs) * match - min_diffs * mismatch); double next_max_score = log_base * ((length - next_min_diffs) * match - next_min_diffs * mismatch); vector<double> v = { max_score, next_max_score }; size_t max_idx; return maximum_mapping_quality_approx(v, &max_idx); } double GSSWAligner::score_to_unnormalized_likelihood_ln(double score) const { // Log base needs to be set, or this can't work. assert(log_base != 0); // Likelihood is proportional to e^(lambda * score), so ln is just the exponent. return log_base * score; } size_t GSSWAligner::longest_detectable_gap(const Alignment& alignment, const string::const_iterator& read_pos) const { return longest_detectable_gap(alignment.sequence().size(), read_pos - alignment.sequence().begin()); } size_t GSSWAligner::longest_detectable_gap(size_t read_length, size_t read_pos) const { // algebraic solution for when score is > 0 assuming perfect match other than gap assert(read_length >= read_pos); int64_t overhang_length = min(read_pos, read_length - read_pos); int64_t numer = match * overhang_length + full_length_bonus; int64_t gap_length = (numer - gap_open) / gap_extension + 1; return gap_length >= 0 && overhang_length > 0 ? gap_length : 0; } size_t GSSWAligner::longest_detectable_gap(const Alignment& alignment) const { // longest detectable gap across entire read is in the middle return longest_detectable_gap(alignment.sequence().size(), alignment.sequence().size() / 2); } size_t GSSWAligner::longest_detectable_gap(size_t read_length) const { return longest_detectable_gap(read_length, read_length / 2); } int32_t GSSWAligner::score_discontiguous_alignment(const Alignment& aln, const function<size_t(pos_t, pos_t, size_t)>& estimate_distance, bool strip_bonuses) const { int score = 0; int read_offset = 0; auto& path = aln.path(); // We keep track of whether the last edit was a deletion for coalescing // adjacent deletions across node boundaries bool last_was_deletion = false; for (int i = 0; i < path.mapping_size(); ++i) { // For each mapping auto& mapping = path.mapping(i); for (int j = 0; j < mapping.edit_size(); ++j) { // For each edit in the mapping auto& edit = mapping.edit(j); // Score the edit according to its type if (edit_is_match(edit)) { score += score_exact_match(aln, read_offset, edit.to_length()); last_was_deletion = false; } else if (edit_is_sub(edit)) { score += score_mismatch(aln.sequence().begin() + read_offset, aln.sequence().begin() + read_offset + edit.to_length(), aln.quality().begin() + read_offset); last_was_deletion = false; } else if (edit_is_deletion(edit)) { if (last_was_deletion) { // No need to charge a gap open score -= edit.from_length() * gap_extension; } else { // We need a gap open score -= edit.from_length() ? gap_open + (edit.from_length() - 1) * gap_extension : 0; } if (edit.from_length()) { // We already charged a gap open last_was_deletion = true; } // If there's a 0-length deletion, leave the last_was_deletion flag unchanged. } else if (edit_is_insertion(edit) && !((i == 0 && j == 0) || (i == path.mapping_size()-1 && j == mapping.edit_size()-1))) { // todo how do we score this qual adjusted? score -= edit.to_length() ? gap_open + (edit.to_length() - 1) * gap_extension : 0; last_was_deletion = false; // No need to track if the last edit was an insertion because // insertions will be all together in a single edit at a point. } else { // Edit has no score effect. Probably a softclip. last_was_deletion = false; } read_offset += edit.to_length(); } // score any intervening gaps in mappings using approximate distances if (i+1 < path.mapping_size()) { // what is the distance between the last position of this mapping // and the first of the next Position last_pos = mapping.position(); last_pos.set_offset(last_pos.offset() + mapping_from_length(mapping)); Position next_pos = path.mapping(i+1).position(); // Estimate the distance int dist = estimate_distance(make_pos_t(last_pos), make_pos_t(next_pos), aln.sequence().size()); if (dist > 0) { // If it's nonzero, score it as a deletion gap score -= gap_open + (dist - 1) * gap_extension; } } } if (!strip_bonuses) { // We should report any bonuses used in the DP in the final score if (!softclip_start(aln)) { score += score_full_length_bonus(true, aln); } if (!softclip_end(aln)) { score += score_full_length_bonus(false, aln); } } return score; } int32_t GSSWAligner::score_contiguous_alignment(const Alignment& aln, bool strip_bonuses) const { return score_discontiguous_alignment(aln, [](pos_t, pos_t, size_t){return (size_t) 0;}, strip_bonuses); } int32_t GSSWAligner::remove_bonuses(const Alignment& aln, bool pinned, bool pin_left) const { int32_t score = aln.score(); if (softclip_start(aln) == 0 && !(pinned && pin_left)) { // No softclip at the start, and a left end bonus was applied. score -= score_full_length_bonus(true, aln); } if (softclip_end(aln) == 0 && !(pinned && !pin_left)) { // No softclip at the end, and a right end bonus was applied. score -= score_full_length_bonus(false, aln); } return score; } Aligner::Aligner(const int8_t* _score_matrix, int8_t _gap_open, int8_t _gap_extension, int8_t _full_length_bonus, double _gc_content) : GSSWAligner(_score_matrix, _gap_open, _gap_extension, _full_length_bonus, _gc_content) { // add in the 5th row and column of 0s for N matches like GSSW wants score_matrix = (int8_t*) malloc(sizeof(int8_t) * 25); for (size_t i = 0, j = 0; i < 25; ++i) { if (i % 5 == 4 || i / 5 == 4) { score_matrix[i] = 0; } else { score_matrix[i] = _score_matrix[j]; ++j; } } // make an XdropAligner for each thread int num_threads = get_thread_count(); xdrops.reserve(num_threads); for (size_t i = 0; i < num_threads; ++i) { xdrops.emplace_back(_score_matrix, _gap_open, _gap_extension); } } void Aligner::align_internal(Alignment& alignment, vector<Alignment>* multi_alignments, const HandleGraph& g, bool pinned, bool pin_left,int32_t max_alt_alns, bool traceback_aln) const { // bench_start(bench); // check input integrity if (pin_left && !pinned) { cerr << "error:[Aligner] cannot choose pinned end in non-pinned alignment" << endl; exit(EXIT_FAILURE); } if (multi_alignments && !pinned) { cerr << "error:[Aligner] multiple traceback is not implemented in local alignment, only pinned and global" << endl; exit(EXIT_FAILURE); } if (!multi_alignments && max_alt_alns != 1) { cerr << "error:[Aligner] cannot specify maximum number of alignments in single alignment" << endl; exit(EXIT_FAILURE); } if (max_alt_alns <= 0) { cerr << "error:[Aligner] cannot do less than 1 alignment" << endl; exit(EXIT_FAILURE); } // alignment pinning algorithm is based on pinning in bottom right corner, if pinning in top // left we need to reverse all the sequences first and translate the alignment back later // make a place to reverse the graph and sequence if necessary ReverseGraph reversed_graph(&g, false); string reversed_sequence; // choose forward or reversed objects const HandleGraph* oriented_graph = &g; const string* align_sequence = &alignment.sequence(); if (pin_left) { // choose the reversed graph oriented_graph = &reversed_graph; // make and assign the reversed sequence reversed_sequence.resize(align_sequence->size()); reverse_copy(align_sequence->begin(), align_sequence->end(), reversed_sequence.begin()); align_sequence = &reversed_sequence; } // to save compute, we won't make these unless we're doing pinning unordered_set<vg::id_t> pinning_ids; NullMaskingGraph* null_masked_graph = nullptr; const HandleGraph* align_graph = oriented_graph; if (pinned) { pinning_ids = identify_pinning_points(*oriented_graph); null_masked_graph = new NullMaskingGraph(oriented_graph); align_graph = null_masked_graph; } // convert into gssw graph gssw_graph* graph = create_gssw_graph(*align_graph); // perform dynamic programming gssw_graph_fill_pinned(graph, align_sequence->c_str(), nt_table, score_matrix, gap_open, gap_extension, full_length_bonus, pinned ? 0 : full_length_bonus, 15, 2, traceback_aln); // traceback either from pinned position or optimal local alignment if (traceback_aln) { if (pinned) { // we can only run gssw's DP on non-empty graphs, but we may have masked the entire graph // if it consists of only empty nodes, so don't both with the DP in that case gssw_graph_mapping** gms = nullptr; if (align_graph->get_node_count() > 0) { gssw_node** pinning_nodes = (gssw_node**) malloc(pinning_ids.size() * sizeof(gssw_node*)); size_t j = 0; for (size_t i = 0; i < graph->size; i++) { gssw_node* node = graph->nodes[i]; if (pinning_ids.count(node->id)) { pinning_nodes[j] = node; j++; } } // trace back pinned alignment gms = gssw_graph_trace_back_pinned_multi (graph, max_alt_alns, true, align_sequence->c_str(), align_sequence->size(), pinning_nodes, pinning_ids.size(), nt_table, score_matrix, gap_open, gap_extension, full_length_bonus, 0); free(pinning_nodes); } // did we both 1) do DP (i.e. the graph is non-empty), and 2) find a traceback with positive score? if (gms ? gms[0]->score > 0 : false) { if (pin_left) { // translate nodes and mappings into original sequence so that the cigars come out right unreverse_graph(graph); for (int32_t i = 0; i < max_alt_alns; i++) { unreverse_graph_mapping(gms[i]); } } // have a mapping, can just convert normally gssw_mapping_to_alignment(graph, gms[0], alignment, pinned, pin_left); if (multi_alignments) { // determine how many non-null alignments were returned int32_t num_non_null = max_alt_alns; for (int32_t i = 1; i < max_alt_alns; i++) { if (gms[i]->score <= 0) { num_non_null = i; break; } } // reserve to avoid illegal access errors that occur when the vector reallocates multi_alignments->reserve(num_non_null); // copy the primary alignment multi_alignments->emplace_back(alignment); // convert the alternate alignments and store them at the back of the vector (this will not // execute if we are doing single alignment) for (int32_t i = 1; i < num_non_null; i++) { // make new alignment object multi_alignments->emplace_back(); Alignment& next_alignment = multi_alignments->back(); // copy over sequence information from the primary alignment next_alignment.set_sequence(alignment.sequence()); next_alignment.set_quality(alignment.quality()); // get path of the alternate alignment gssw_mapping_to_alignment(graph, gms[i], next_alignment, pinned, pin_left); } } } else if (g.get_node_count() > 0) { // we didn't get any alignments either because the graph was empty and we couldn't run // gssw DP or because they had score 0 and gssw didn't want to do traceback. however, // we can infer the location of softclips based on the pinning nodes, so we'll just make // those manually // find the sink nodes of the oriented graph, which may be empty auto pinning_points = handlealgs::tail_nodes(oriented_graph); // impose a consistent ordering for machine independent behavior sort(pinning_points.begin(), pinning_points.end(), [&](const handle_t& h1, const handle_t& h2) { return oriented_graph->get_id(h1) < oriented_graph->get_id(h2); }); for (size_t i = 0; i < max_alt_alns && i < pinning_points.size(); i++) { // make a record in the multi alignments if we're using them if (multi_alignments) { multi_alignments->emplace_back(); } // choose an alignment object to construct the path in Alignment& softclip_alignment = i == 0 ? alignment : multi_alignments->back(); handle_t& pinning_point = pinning_points[i]; Mapping* mapping = alignment.mutable_path()->add_mapping(); mapping->set_rank(1); // locate at the beginning or end of the node Position* position = mapping->mutable_position(); position->set_node_id(oriented_graph->get_id(pinning_point)); position->set_offset(pin_left ? 0 : oriented_graph->get_length(pinning_point)); // soft clip Edit* edit = mapping->add_edit(); edit->set_to_length(alignment.sequence().length()); edit->set_sequence(alignment.sequence()); // we want to also have the first alignment in the multi-alignment vector if (i == 0 && multi_alignments) { multi_alignments->back() = alignment; } } } if (gms) { for (int32_t i = 0; i < max_alt_alns; i++) { gssw_graph_mapping_destroy(gms[i]); } free(gms); } } else { // trace back local alignment gssw_graph_mapping* gm = gssw_graph_trace_back (graph, align_sequence->c_str(), align_sequence->size(), nt_table, score_matrix, gap_open, gap_extension, full_length_bonus, full_length_bonus); gssw_mapping_to_alignment(graph, gm, alignment, pinned, pin_left); gssw_graph_mapping_destroy(gm); } } else { // get the alignment position and score alignment.set_score(graph->max_node->alignment->score1); Mapping* m = alignment.mutable_path()->add_mapping(); Position* p = m->mutable_position(); p->set_node_id(graph->max_node->id); p->set_offset(graph->max_node->alignment->ref_end1); // mark end position; for de-duplication } // this might be null if we're not doing pinned alignment, but delete doesn't care delete null_masked_graph; gssw_graph_destroy(graph); // bench_end(bench); } void Aligner::align(Alignment& alignment, const HandleGraph& g, bool traceback_aln) const { align_internal(alignment, nullptr, g, false, false, 1, traceback_aln); } void Aligner::align(Alignment& alignment, const HandleGraph& g, const std::vector<handle_t>& topological_order) const { // Create a gssw_graph and a mapping from handles to nodes. gssw_graph* graph = gssw_graph_create(topological_order.size()); hash_map<handle_t, gssw_node*> nodes; nodes.reserve(topological_order.size()); // Create the nodes. Use offsets in the topological order as node ids. for (size_t i = 0; i < topological_order.size(); i++) { handle_t handle = topological_order[i]; auto cleaned_seq = nonATGCNtoN(g.get_sequence(handle)); gssw_node* node = gssw_node_create(nullptr, i, cleaned_seq.c_str(), nt_table, score_matrix); nodes[handle] = node; gssw_graph_add_node(graph, node); } // Create the edges. for (const handle_t& from : topological_order) { gssw_node* from_node = nodes[from]; g.follow_edges(from, false, [&](const handle_t& to) { auto iter = nodes.find(to); if (iter != nodes.end()) { gssw_nodes_add_edge(from_node, iter->second); } }); } // Align the read to the subgraph. gssw_graph_fill_pinned(graph, alignment.sequence().c_str(), nt_table, score_matrix, gap_open, gap_extension, full_length_bonus, full_length_bonus, 15, 2, true); gssw_graph_mapping* gm = gssw_graph_trace_back(graph, alignment.sequence().c_str(), alignment.sequence().length(), nt_table, score_matrix, gap_open, gap_extension, full_length_bonus, full_length_bonus); // Convert the mapping to Alignment. this->gssw_mapping_to_alignment(graph, gm, alignment, false, false); Path& path = *(alignment.mutable_path()); for (size_t i = 0; i < path.mapping_size(); i++) { Position& pos = *(path.mutable_mapping(i)->mutable_position()); handle_t handle = topological_order[pos.node_id()]; pos.set_node_id(g.get_id(handle)); pos.set_is_reverse(g.get_is_reverse(handle)); } // Destroy the temporary objects. gssw_graph_mapping_destroy(gm); gssw_graph_destroy(graph); } void Aligner::align_pinned(Alignment& alignment, const HandleGraph& g, bool pin_left, bool xdrop, uint16_t xdrop_max_gap_length) const { if (xdrop) { // XdropAligner manages its own stack, so it can never be threadsafe without be recreated // for every alignment, which meshes poorly with its stack implementation. We achieve // thread-safety by having one per thread, which makes this method const-ish. XdropAligner& xdrop = const_cast<XdropAligner&>(xdrops[omp_get_thread_num()]); // dozeu declines to produce an alignment when the gap is set to 0 xdrop_max_gap_length = max<uint16_t>(xdrop_max_gap_length, 1); // wrap the graph so that empty pinning points are handled correctly DozeuPinningOverlay overlay(&g, !pin_left); if (overlay.get_node_count() == 0 && g.get_node_count() > 0) { // the only nodes in the graph are empty nodes for pinning, which got masked. // we can still infer a pinned alignment based purely on the pinning point but // dozeu won't handle this correctly g.for_each_handle([&](const handle_t& handle) { bool can_pin = g.follow_edges(handle, pin_left, [&](const handle_t& next) {return false;}); if (can_pin) { // manually make the softclip Mapping* mapping = alignment.mutable_path()->add_mapping(); Position* pos = mapping->mutable_position(); pos->set_node_id(g.get_id(handle)); pos->set_is_reverse(false); pos->set_offset(pin_left ? 0 : g.get_length(handle)); mapping->set_rank(1); Edit* edit = mapping->add_edit(); edit->set_from_length(0); edit->set_to_length(alignment.sequence().size()); edit->set_sequence(alignment.sequence()); alignment.set_score(0); return false; } return true; }); } else { // do the alignment xdrop.align_pinned(alignment, overlay, pin_left, full_length_bonus, xdrop_max_gap_length); if (overlay.performed_duplications()) { // the overlay is not a strict subset of the underlying graph, so we may // need to translate some node IDs translate_oriented_node_ids(*alignment.mutable_path(), [&](id_t node_id) { handle_t under = overlay.get_underlying_handle(overlay.get_handle(node_id)); return make_pair(g.get_id(under), g.get_is_reverse(under)); }); } } } else { align_internal(alignment, nullptr, g, true, pin_left, 1, true); } } void Aligner::align_pinned_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g, bool pin_left, int32_t max_alt_alns) const { if (alt_alignments.size() != 0) { cerr << "error:[Aligner::align_pinned_multi] output vector must be empty for pinned multi-aligning" << endl; exit(EXIT_FAILURE); } align_internal(alignment, &alt_alignments, g, true, pin_left, max_alt_alns, true); } void Aligner::align_global_banded(Alignment& alignment, const HandleGraph& g, int32_t band_padding, bool permissive_banding) const { if (alignment.sequence().empty()) { // we can save time by using a specialized deletion aligner for empty strings deletion_aligner.align(alignment, g); return; } // We need to figure out what size ints we need to use. // Get upper and lower bounds on the scores. TODO: if these overflow int64 we're out of luck int64_t best_score = alignment.sequence().size() * match; size_t total_bases = 0; g.for_each_handle([&](const handle_t& handle) { total_bases += g.get_length(handle); }); int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension); // TODO: put this all into another template somehow? if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) { // We'll fit in int8 BandedGlobalAligner<int8_t> band_graph(alignment, g, band_padding, permissive_banding, false); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) { // We'll fit in int16 BandedGlobalAligner<int16_t> band_graph(alignment, g, band_padding, permissive_banding, false); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) { // We'll fit in int32 BandedGlobalAligner<int32_t> band_graph(alignment, g, band_padding, permissive_banding, false); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else { // Fall back to int64 BandedGlobalAligner<int64_t> band_graph(alignment, g, band_padding, permissive_banding, false); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } } void Aligner::align_global_banded_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g, int32_t max_alt_alns, int32_t band_padding, bool permissive_banding) const { if (alignment.sequence().empty()) { // we can save time by using a specialized deletion aligner for empty strings deletion_aligner.align_multi(alignment, alt_alignments, g, max_alt_alns); return; } // We need to figure out what size ints we need to use. // Get upper and lower bounds on the scores. TODO: if these overflow int64 we're out of luck int64_t best_score = alignment.sequence().size() * match; size_t total_bases = 0; g.for_each_handle([&](const handle_t& handle) { total_bases += g.get_length(handle); }); int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension); if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) { // We'll fit in int8 BandedGlobalAligner<int8_t> band_graph(alignment, g, alt_alignments, max_alt_alns, band_padding, permissive_banding, false); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) { // We'll fit in int16 BandedGlobalAligner<int16_t> band_graph(alignment, g, alt_alignments, max_alt_alns, band_padding, permissive_banding, false); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) { // We'll fit in int32 BandedGlobalAligner<int32_t> band_graph(alignment, g, alt_alignments, max_alt_alns, band_padding, permissive_banding, false); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else { // Fall back to int64 BandedGlobalAligner<int64_t> band_graph(alignment, g, alt_alignments, max_alt_alns, band_padding, permissive_banding, false); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } } void Aligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<MaximalExactMatch>& mems, bool reverse_complemented, uint16_t max_gap_length) const { align_xdrop(alignment, g, handlealgs::lazier_topological_order(&g), mems, reverse_complemented, max_gap_length); } void Aligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<handle_t>& order, const vector<MaximalExactMatch>& mems, bool reverse_complemented, uint16_t max_gap_length) const { // XdropAligner manages its own stack, so it can never be threadsafe without be recreated // for every alignment, which meshes poorly with its stack implementation. We achieve // thread-safety by having one per thread, which makes this method const-ish. XdropAligner& xdrop = const_cast<XdropAligner&>(xdrops[omp_get_thread_num()]); xdrop.align(alignment, g, order, mems, reverse_complemented, full_length_bonus, max_gap_length); if (!alignment.has_path() && mems.empty()) { // dozeu couldn't find an alignment, probably because it's seeding heuristic failed // we'll just fall back on GSSW // TODO: This is a bit inconsistent. GSSW gives a full-length bonus at both ends, while // dozeu only gives it once. align(alignment, g, order); } } // Scoring an exact match is very simple in an ordinary Aligner int32_t Aligner::score_exact_match(const Alignment& aln, size_t read_offset, size_t length) const { return match * length; } int32_t Aligner::score_exact_match(const string& sequence) const { return match * sequence.length(); } int32_t Aligner::score_exact_match(string::const_iterator seq_begin, string::const_iterator seq_end) const { return match * (seq_end - seq_begin); } int32_t Aligner::score_exact_match(const string& sequence, const string& base_quality) const { return score_exact_match(sequence); } int32_t Aligner::score_exact_match(string::const_iterator seq_begin, string::const_iterator seq_end, string::const_iterator base_qual_begin) const { return score_exact_match(seq_begin, seq_end); } int32_t Aligner::score_mismatch(string::const_iterator seq_begin, string::const_iterator seq_end, string::const_iterator base_qual_begin) const { return -mismatch * (seq_end - seq_begin); } int32_t Aligner::score_mismatch(size_t length) const { return -match * length; } int32_t Aligner::score_full_length_bonus(bool left_side, string::const_iterator seq_begin, string::const_iterator seq_end, string::const_iterator base_qual_begin) const { return full_length_bonus; } int32_t Aligner::score_full_length_bonus(bool left_side, const Alignment& alignment) const { return full_length_bonus; } int32_t Aligner::score_partial_alignment(const Alignment& alignment, const HandleGraph& graph, const Path& path, string::const_iterator seq_begin, bool no_read_end_scoring) const { int32_t score = 0; string::const_iterator read_pos = seq_begin; bool in_deletion = false; for (size_t i = 0; i < path.mapping_size(); i++) { const Mapping& mapping = path.mapping(i); for (size_t j = 0; j < mapping.edit_size(); j++) { const Edit& edit = mapping.edit(j); if (edit.from_length() > 0) { if (edit.to_length() > 0) { if (edit.sequence().empty()) { // match score += match * edit.from_length(); } else { // mismatch score -= mismatch * edit.from_length(); } // apply full length bonus if (read_pos == alignment.sequence().begin() && !no_read_end_scoring) { score += score_full_length_bonus(true, alignment); } if (read_pos + edit.to_length() == alignment.sequence().end() && !no_read_end_scoring) { score += score_full_length_bonus(false, alignment); } in_deletion = false; } else if (in_deletion) { score -= edit.from_length() * gap_extension; } else { // deletion score -= gap_open + (edit.from_length() - 1) * gap_extension; in_deletion = true; } } else if (edit.to_length() > 0) { // don't score soft clips if scoring read ends if (no_read_end_scoring || (read_pos != alignment.sequence().begin() && read_pos + edit.to_length() != alignment.sequence().end())) { // insert score -= gap_open + (edit.to_length() - 1) * gap_extension; } in_deletion = false; } read_pos += edit.to_length(); } } return score; } QualAdjAligner::QualAdjAligner(const int8_t* _score_matrix, int8_t _gap_open, int8_t _gap_extension, int8_t _full_length_bonus, double _gc_content) : GSSWAligner(_score_matrix, _gap_open, _gap_extension, _full_length_bonus, _gc_content) { // TODO: this interface could really be improved in GSSW, oh well though // find the quality-adjusted scores uint32_t max_base_qual = 255; // add in the 0s to the 5-th row and column for Ns score_matrix = qual_adjusted_matrix(_score_matrix, _gc_content, max_base_qual); // compute the quality adjusted full length bonuses qual_adj_full_length_bonuses = qual_adjusted_bonuses(_full_length_bonus, max_base_qual); // make a QualAdjXdropAligner for each thread int num_threads = get_thread_count(); xdrops.reserve(num_threads); for (size_t i = 0; i < num_threads; ++i) { xdrops.emplace_back(_score_matrix, score_matrix, _gap_open, _gap_extension); } } QualAdjAligner::~QualAdjAligner() { free(qual_adj_full_length_bonuses); } int8_t* QualAdjAligner::qual_adjusted_matrix(const int8_t* _score_matrix, double gc_content, uint32_t max_qual) const { // TODO: duplicative with GSSWAligner() double* nt_freqs = (double*) malloc(sizeof(double) * 4); nt_freqs[0] = 0.5 * (1 - gc_content); nt_freqs[1] = 0.5 * gc_content; nt_freqs[2] = 0.5 * gc_content; nt_freqs[3] = 0.5 * (1 - gc_content); // recover the emission probabilities of the align state of the HMM double* align_prob = (double*) malloc(sizeof(double) * 16); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { align_prob[i * 4 + j] = (exp(log_base * _score_matrix[i * 4 + j]) * nt_freqs[i] * nt_freqs[j]); } } // compute the sum of the emission probabilities under a base error double* align_complement_prob = (double*) malloc(sizeof(double) * 16); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { align_complement_prob[i * 4 + j] = 0.0; for (int k = 0; k < 4; k++) { if (k != j) { align_complement_prob[i * 4 + j] += align_prob[i * 4 + k]; } } } } // quality score of random guessing int lowest_meaningful_qual = ceil(-10.0 * log10(0.75)); // compute the adjusted alignment scores for each quality level int8_t* qual_adj_mat = (int8_t*) malloc(25 * (max_qual + 1) * sizeof(int8_t)); for (int q = 0; q <= max_qual; q++) { double err = pow(10.0, -q / 10.0); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { int8_t score; if (i == 4 || j == 4 || q < lowest_meaningful_qual) { score = 0; } else { score = round(log(((1.0 - err) * align_prob[i * 4 + j] + (err / 3.0) * align_complement_prob[i * 4 + j]) / (nt_freqs[i] * ((1.0 - err) * nt_freqs[j] + (err / 3.0) * (1.0 - nt_freqs[j])))) / log_base); } qual_adj_mat[q * 25 + i * 5 + j] = round(score); } } } free(align_complement_prob); free(align_prob); free(nt_freqs); return qual_adj_mat; } int8_t* QualAdjAligner::qual_adjusted_bonuses(int8_t _full_length_bonus, uint32_t max_qual) const { double p_full_len = exp(log_base * _full_length_bonus) / (1.0 + exp(log_base * _full_length_bonus)); int8_t* qual_adj_bonuses = (int8_t*) calloc(max_qual + 1, sizeof(int8_t)); int lowest_meaningful_qual = ceil(-10.0 * log10(0.75)); // hack because i want the minimum qual value from illumina (2) to have zero score, but phred // values are spaced out in a way to approximate this singularity well ++lowest_meaningful_qual; for (int q = lowest_meaningful_qual; q <= max_qual; ++q) { double err = pow(10.0, -q / 10.0); double score = log(((1.0 - err * 4.0 / 3.0) * p_full_len + (err * 4.0 / 3.0) * (1.0 - p_full_len)) / (1.0 - p_full_len)) / log_base; qual_adj_bonuses[q] = round(score); } return qual_adj_bonuses; } void QualAdjAligner::align_internal(Alignment& alignment, vector<Alignment>* multi_alignments, const HandleGraph& g, bool pinned, bool pin_left, int32_t max_alt_alns, bool traceback_aln) const { // check input integrity if (pin_left && !pinned) { cerr << "error:[Aligner] cannot choose pinned end in non-pinned alignment" << endl; exit(EXIT_FAILURE); } if (multi_alignments && !pinned) { cerr << "error:[Aligner] multiple traceback is not implemented in local alignment, only pinned and global" << endl; exit(EXIT_FAILURE); } if (!multi_alignments && max_alt_alns != 1) { cerr << "error:[Aligner] cannot specify maximum number of alignments in single alignment" << endl; exit(EXIT_FAILURE); } if (max_alt_alns <= 0) { cerr << "error:[Aligner] cannot do less than 1 alignment" << endl; exit(EXIT_FAILURE); } // alignment pinning algorithm is based on pinning in bottom right corner, if pinning in top // left we need to reverse all the sequences first and translate the alignment back later // make a place to reverse the graph and sequence if necessary ReverseGraph reversed_graph(&g, false); string reversed_sequence; string reversed_quality; // choose forward or reversed objects const HandleGraph* oriented_graph = &g; const string* align_sequence = &alignment.sequence(); const string* align_quality = &alignment.quality(); if (pin_left) { // choose the reversed graph oriented_graph = &reversed_graph; // make and assign the reversed sequence reversed_sequence.resize(align_sequence->size()); reverse_copy(align_sequence->begin(), align_sequence->end(), reversed_sequence.begin()); align_sequence = &reversed_sequence; // make and assign the reversed quality reversed_quality.resize(align_quality->size()); reverse_copy(align_quality->begin(), align_quality->end(), reversed_quality.begin()); align_quality = &reversed_quality; } if (align_quality->size() != align_sequence->size()) { cerr << "error:[QualAdjAligner] Read " << alignment.name() << " has sequence and quality strings with different lengths. Cannot perform base quality adjusted alignment. Consider toggling off base quality adjusted alignment at the command line." << endl; exit(EXIT_FAILURE); } // to save compute, we won't make these unless we're doing pinning unordered_set<vg::id_t> pinning_ids; NullMaskingGraph* null_masked_graph = nullptr; const HandleGraph* align_graph = oriented_graph; if (pinned) { pinning_ids = identify_pinning_points(*oriented_graph); null_masked_graph = new NullMaskingGraph(oriented_graph); align_graph = null_masked_graph; } // convert into gssw graph gssw_graph* graph = create_gssw_graph(*align_graph); int8_t front_full_length_bonus = qual_adj_full_length_bonuses[align_quality->front()]; int8_t back_full_length_bonus = qual_adj_full_length_bonuses[align_quality->back()]; // perform dynamic programming // offer a full length bonus on each end, or only on the left if the right end is pinned. gssw_graph_fill_pinned_qual_adj(graph, align_sequence->c_str(), align_quality->c_str(), nt_table, score_matrix, gap_open, gap_extension, front_full_length_bonus, pinned ? 0 : back_full_length_bonus, 15, 2, traceback_aln); // traceback either from pinned position or optimal local alignment if (traceback_aln) { if (pinned) { gssw_graph_mapping** gms = nullptr; if (align_graph->get_node_count() > 0) { gssw_node** pinning_nodes = (gssw_node**) malloc(pinning_ids.size() * sizeof(gssw_node*)); size_t j = 0; for (size_t i = 0; i < graph->size; i++) { gssw_node* node = graph->nodes[i]; if (pinning_ids.count(node->id)) { pinning_nodes[j] = node; j++; } } // trace back pinned alignment gms = gssw_graph_trace_back_pinned_qual_adj_multi (graph, max_alt_alns, true, align_sequence->c_str(), align_quality->c_str(), align_sequence->size(), pinning_nodes, pinning_ids.size(), nt_table, score_matrix, gap_open, gap_extension, front_full_length_bonus, 0); free(pinning_nodes); } // did we both 1) do DP (i.e. the graph is non-empty), and 2) find a traceback with positive score? if (gms && gms[0]->score > 0) { if (pin_left) { // translate graph and mappings into original node space unreverse_graph(graph); for (int32_t i = 0; i < max_alt_alns; i++) { unreverse_graph_mapping(gms[i]); } } // have a mapping, can just convert normally gssw_mapping_to_alignment(graph, gms[0], alignment, pinned, pin_left); if (multi_alignments) { // determine how many non-null alignments were returned int32_t num_non_null = max_alt_alns; for (int32_t i = 1; i < max_alt_alns; i++) { if (gms[i]->score <= 0) { num_non_null = i; break; } } // reserve to avoid illegal access errors that occur when the vector reallocates multi_alignments->reserve(num_non_null); // copy the primary alignment multi_alignments->emplace_back(alignment); // convert the alternate alignments and store them at the back of the vector (this will not // execute if we are doing single alignment) for (int32_t i = 1; i < num_non_null; i++) { // make new alignment object multi_alignments->emplace_back(); Alignment& next_alignment = multi_alignments->back(); // copy over sequence information from the primary alignment next_alignment.set_sequence(alignment.sequence()); next_alignment.set_quality(alignment.quality()); // get path of the alternate alignment gssw_mapping_to_alignment(graph, gms[i], next_alignment, pinned, pin_left); } } } else if (g.get_node_count() > 0) { /// we didn't get any alignments either because the graph was empty and we couldn't run // gssw DP or because they had score 0 and gssw didn't want to do traceback. however, // we can infer the location of softclips based on the pinning nodes, so we'll just make // those manually // find the sink nodes of the oriented graph, which may be empty auto pinning_points = handlealgs::tail_nodes(oriented_graph); // impose a consistent ordering for machine independent behavior sort(pinning_points.begin(), pinning_points.end(), [&](const handle_t& h1, const handle_t& h2) { return oriented_graph->get_id(h1) < oriented_graph->get_id(h2); }); for (size_t i = 0; i < max_alt_alns && i < pinning_points.size(); i++) { // make a record in the multi alignments if we're using them if (multi_alignments) { multi_alignments->emplace_back(); } // choose an alignment object to construct the path in Alignment& softclip_alignment = i == 0 ? alignment : multi_alignments->back(); handle_t& pinning_point = pinning_points[i]; Mapping* mapping = alignment.mutable_path()->add_mapping(); mapping->set_rank(1); // locate at the beginning or end of the node Position* position = mapping->mutable_position(); position->set_node_id(oriented_graph->get_id(pinning_point)); position->set_offset(pin_left ? 0 : oriented_graph->get_length(pinning_point)); // soft clip Edit* edit = mapping->add_edit(); edit->set_to_length(alignment.sequence().length()); edit->set_sequence(alignment.sequence()); // we want to also have the first alignment in the multi-alignment vector if (i == 0 && multi_alignments) { multi_alignments->back() = alignment; } } } if (gms) { for (int32_t i = 0; i < max_alt_alns; i++) { gssw_graph_mapping_destroy(gms[i]); } free(gms); } } else { // trace back local alignment gssw_graph_mapping* gm = gssw_graph_trace_back_qual_adj (graph, align_sequence->c_str(), align_quality->c_str(), align_sequence->size(), nt_table, score_matrix, gap_open, gap_extension, front_full_length_bonus, back_full_length_bonus); gssw_mapping_to_alignment(graph, gm, alignment, pinned, pin_left); gssw_graph_mapping_destroy(gm); } } else { // get the alignment position and score alignment.set_score(graph->max_node->alignment->score1); Mapping* m = alignment.mutable_path()->add_mapping(); Position* p = m->mutable_position(); p->set_node_id(graph->max_node->id); p->set_offset(graph->max_node->alignment->ref_end1); // mark end position; for de-duplication } // this might be null if we're not doing pinned alignment, but delete doesn't care delete null_masked_graph; gssw_graph_destroy(graph); } void QualAdjAligner::align(Alignment& alignment, const HandleGraph& g, bool traceback_aln) const { align_internal(alignment, nullptr, g, false, false, 1, traceback_aln); } void QualAdjAligner::align_pinned(Alignment& alignment, const HandleGraph& g, bool pin_left, bool xdrop, uint16_t xdrop_max_gap_length) const { if (xdrop) { // QualAdjXdropAligner manages its own stack, so it can never be threadsafe without be recreated // for every alignment, which meshes poorly with its stack implementation. We achieve // thread-safety by having one per thread, which makes this method const-ish. QualAdjXdropAligner& xdrop = const_cast<QualAdjXdropAligner&>(xdrops[omp_get_thread_num()]); // wrap the graph so that empty pinning points are handled correctly DozeuPinningOverlay overlay(&g, !pin_left); if (overlay.get_node_count() == 0 && g.get_node_count() > 0) { // the only nodes in the graph are empty nodes for pinning, which got masked. // we can still infer a pinned alignment based purely on the pinning point but // dozeu won't handle this correctly g.for_each_handle([&](const handle_t& handle) { bool can_pin = g.follow_edges(handle, pin_left, [&](const handle_t& next) {return false;}); if (can_pin) { // manually make the softclip Mapping* mapping = alignment.mutable_path()->add_mapping(); Position* pos = mapping->mutable_position(); pos->set_node_id(g.get_id(handle)); pos->set_is_reverse(false); pos->set_offset(pin_left ? 0 : g.get_length(handle)); mapping->set_rank(1); Edit* edit = mapping->add_edit(); edit->set_from_length(0); edit->set_to_length(alignment.sequence().size()); edit->set_sequence(alignment.sequence()); alignment.set_score(0); return false; } return true; }); } else { // dozeu declines to produce an alignment when the gap is set to 0 xdrop_max_gap_length = max<uint16_t>(xdrop_max_gap_length, 1); // get the quality adjusted bonus int8_t bonus = qual_adj_full_length_bonuses[pin_left ? alignment.quality().back() : alignment.quality().front()]; xdrop.align_pinned(alignment, overlay, pin_left, bonus, xdrop_max_gap_length); if (overlay.performed_duplications()) { // the overlay is not a strict subset of the underlying graph, so we may // need to translate some node IDs translate_oriented_node_ids(*alignment.mutable_path(), [&](id_t node_id) { handle_t under = overlay.get_underlying_handle(overlay.get_handle(node_id)); return make_pair(g.get_id(under), g.get_is_reverse(under)); }); } } } else { align_internal(alignment, nullptr, g, true, pin_left, 1, true); } } void QualAdjAligner::align_pinned_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g, bool pin_left, int32_t max_alt_alns) const { align_internal(alignment, &alt_alignments, g, true, pin_left, max_alt_alns, true); } void QualAdjAligner::align_global_banded(Alignment& alignment, const HandleGraph& g, int32_t band_padding, bool permissive_banding) const { if (alignment.sequence().empty()) { // we can save time by using a specialized deletion aligner for empty strings deletion_aligner.align(alignment, g); return; } int64_t best_score = alignment.sequence().size() * match; size_t total_bases = 0; g.for_each_handle([&](const handle_t& handle) { total_bases += g.get_length(handle); }); int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension); // TODO: put this all into another template somehow? if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) { // We'll fit in int8 BandedGlobalAligner<int8_t> band_graph(alignment, g, band_padding, permissive_banding, true); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) { // We'll fit in int16 BandedGlobalAligner<int16_t> band_graph(alignment, g, band_padding, permissive_banding, true); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) { // We'll fit in int32 BandedGlobalAligner<int32_t> band_graph(alignment, g, band_padding, permissive_banding, true); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else { // Fall back to int64 BandedGlobalAligner<int64_t> band_graph(alignment, g, band_padding, permissive_banding, true); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } } void QualAdjAligner::align_global_banded_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g, int32_t max_alt_alns, int32_t band_padding, bool permissive_banding) const { if (alignment.sequence().empty()) { // we can save time by using a specialized deletion aligner for empty strings deletion_aligner.align_multi(alignment, alt_alignments, g, max_alt_alns); return; } // We need to figure out what size ints we need to use. // Get upper and lower bounds on the scores. TODO: if these overflow int64 we're out of luck int64_t best_score = alignment.sequence().size() * match; size_t total_bases = 0; g.for_each_handle([&](const handle_t& handle) { total_bases += g.get_length(handle); }); int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension); if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) { // We'll fit in int8 BandedGlobalAligner<int8_t> band_graph(alignment, g, alt_alignments, max_alt_alns, band_padding, permissive_banding, true); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) { // We'll fit in int16 BandedGlobalAligner<int16_t> band_graph(alignment, g, alt_alignments, max_alt_alns, band_padding, permissive_banding, true); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) { // We'll fit in int32 BandedGlobalAligner<int32_t> band_graph(alignment, g, alt_alignments, max_alt_alns, band_padding, permissive_banding, true); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } else { // Fall back to int64 BandedGlobalAligner<int64_t> band_graph(alignment, g, alt_alignments, max_alt_alns, band_padding, permissive_banding, true); band_graph.align(score_matrix, nt_table, gap_open, gap_extension); } } void QualAdjAligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<MaximalExactMatch>& mems, bool reverse_complemented, uint16_t max_gap_length) const { align_xdrop(alignment, g, handlealgs::lazier_topological_order(&g), mems, reverse_complemented, max_gap_length); } void QualAdjAligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<handle_t>& order, const vector<MaximalExactMatch>& mems, bool reverse_complemented, uint16_t max_gap_length) const { // QualAdjXdropAligner manages its own stack, so it can never be threadsafe without being recreated // for every alignment, which meshes poorly with its stack implementation. We achieve // thread-safety by having one per thread, which makes this method const-ish. QualAdjXdropAligner& xdrop = const_cast<QualAdjXdropAligner&>(xdrops[omp_get_thread_num()]); // get the quality adjusted bonus int8_t bonus = qual_adj_full_length_bonuses[reverse_complemented ? alignment.quality().front() : alignment.quality().back()]; xdrop.align(alignment, g, order, mems, reverse_complemented, bonus, max_gap_length); if (!alignment.has_path() && mems.empty()) { // dozeu couldn't find an alignment, probably because it's seeding heuristic failed // we'll just fall back on GSSW // TODO: This is a bit inconsistent. GSSW gives a full-length bonus at both ends, while // dozeu only gives it once. align(alignment, g, true); } } int32_t QualAdjAligner::score_exact_match(const Alignment& aln, size_t read_offset, size_t length) const { auto& sequence = aln.sequence(); auto& base_quality = aln.quality(); int32_t score = 0; for (int32_t i = 0; i < length; i++) { // index 5 x 5 score matrices (ACGTN) // always have match so that row and column index are same and can combine algebraically score += score_matrix[25 * base_quality[read_offset + i] + 6 * nt_table[sequence[read_offset + i]]]; } return score; } int32_t QualAdjAligner::score_exact_match(const string& sequence, const string& base_quality) const { int32_t score = 0; for (int32_t i = 0; i < sequence.length(); i++) { // index 5 x 5 score matrices (ACGTN) // always have match so that row and column index are same and can combine algebraically score += score_matrix[25 * base_quality[i] + 6 * nt_table[sequence[i]]]; } return score; } int32_t QualAdjAligner::score_exact_match(string::const_iterator seq_begin, string::const_iterator seq_end, string::const_iterator base_qual_begin) const { int32_t score = 0; for (auto seq_iter = seq_begin, qual_iter = base_qual_begin; seq_iter != seq_end; seq_iter++) { // index 5 x 5 score matrices (ACGTN) // always have match so that row and column index are same and can combine algebraically score += score_matrix[25 * (*qual_iter) + 6 * nt_table[*seq_iter]]; qual_iter++; } return score; } int32_t QualAdjAligner::score_mismatch(string::const_iterator seq_begin, string::const_iterator seq_end, string::const_iterator base_qual_begin) const { int32_t score = 0; for (auto seq_iter = seq_begin, qual_iter = base_qual_begin; seq_iter != seq_end; seq_iter++) { // index 5 x 5 score matrices (ACGTN) // always have match so that row and column index are same and can combine algebraically score += score_matrix[25 * (*qual_iter) + 1]; qual_iter++; } return score; } int32_t QualAdjAligner::score_full_length_bonus(bool left_side, string::const_iterator seq_begin, string::const_iterator seq_end, string::const_iterator base_qual_begin) const { if (seq_begin != seq_end) { return qual_adj_full_length_bonuses[left_side ? *base_qual_begin : *(base_qual_begin + (seq_end - seq_begin) - 1)]; } else { return 0; } } int32_t QualAdjAligner::score_full_length_bonus(bool left_side, const Alignment& alignment) const { return score_full_length_bonus(left_side, alignment.sequence().begin(), alignment.sequence().end(), alignment.quality().begin()); } int32_t QualAdjAligner::score_partial_alignment(const Alignment& alignment, const HandleGraph& graph, const Path& path, string::const_iterator seq_begin, bool no_read_end_scoring) const { int32_t score = 0; string::const_iterator read_pos = seq_begin; string::const_iterator qual_pos = alignment.quality().begin() + (seq_begin - alignment.sequence().begin()); bool in_deletion = false; for (size_t i = 0; i < path.mapping_size(); i++) { const Mapping& mapping = path.mapping(i); // get the sequence of this node on the proper strand string node_seq = graph.get_sequence(graph.get_handle(mapping.position().node_id(), mapping.position().is_reverse())); string::const_iterator ref_pos = node_seq.begin() + mapping.position().offset(); for (size_t j = 0; j < mapping.edit_size(); j++) { const Edit& edit = mapping.edit(j); if (edit.from_length() > 0) { if (edit.to_length() > 0) { for (auto siter = read_pos, riter = ref_pos, qiter = qual_pos; siter != read_pos + edit.to_length(); siter++, qiter++, riter++) { score += score_matrix[25 * (*qiter) + 5 * nt_table[*riter] + nt_table[*siter]]; } // apply full length bonus if (read_pos == alignment.sequence().begin() && !no_read_end_scoring) { score += score_full_length_bonus(true, alignment); } if (read_pos + edit.to_length() == alignment.sequence().end() && !no_read_end_scoring) { score += score_full_length_bonus(false, alignment); } in_deletion = false; } else if (in_deletion) { score -= edit.from_length() * gap_extension; } else { // deletion score -= gap_open + (edit.from_length() - 1) * gap_extension; in_deletion = true; } } else if (edit.to_length() > 0) { // don't score soft clips if read end scoring if (no_read_end_scoring || (read_pos != alignment.sequence().begin() && read_pos + edit.to_length() != alignment.sequence().end())) { // insert score -= gap_open + (edit.to_length() - 1) * gap_extension; } in_deletion = false; } read_pos += edit.to_length(); qual_pos += edit.to_length(); ref_pos += edit.from_length(); } } return score; } AlignerClient::AlignerClient(double gc_content_estimate) : gc_content_estimate(gc_content_estimate) { // Adopt the default scoring parameters and make the aligners set_alignment_scores(default_score_matrix, default_gap_open, default_gap_extension, default_full_length_bonus); } const GSSWAligner* AlignerClient::get_aligner(bool have_qualities) const { return (have_qualities && adjust_alignments_for_base_quality) ? (GSSWAligner*) get_qual_adj_aligner() : (GSSWAligner*) get_regular_aligner(); } const QualAdjAligner* AlignerClient::get_qual_adj_aligner() const { assert(qual_adj_aligner.get() != nullptr); return qual_adj_aligner.get(); } const Aligner* AlignerClient::get_regular_aligner() const { assert(regular_aligner.get() != nullptr); return regular_aligner.get(); } int8_t* AlignerClient::parse_matrix(istream& matrix_stream) { int8_t* matrix = (int8_t*) malloc(16 * sizeof(int8_t)); for (size_t i = 0; i < 16; i++) { if (!matrix_stream.good()) { std::cerr << "error: vg Aligner::parse_matrix requires a 4x4 whitespace separated integer matrix\n"; throw ""; } int score; matrix_stream >> score; if (score > 127 || score < -127) { std::cerr << "error: vg Aligner::parse_matrix requires values in the range [-127,127]\n"; throw ""; } matrix[i] = score; } return matrix; } void AlignerClient::set_alignment_scores(int8_t match, int8_t mismatch, int8_t gap_open, int8_t gap_extend, int8_t full_length_bonus) { int8_t* matrix = (int8_t*) malloc(sizeof(int8_t) * 16); for (size_t i = 0; i < 16; ++i) { if (i % 5 == 0) { matrix[i] = match; } else { matrix[i] = -mismatch; } } qual_adj_aligner = unique_ptr<QualAdjAligner>(new QualAdjAligner(matrix, gap_open, gap_extend, full_length_bonus, gc_content_estimate)); regular_aligner = unique_ptr<Aligner>(new Aligner(matrix, gap_open, gap_extend, full_length_bonus, gc_content_estimate)); free(matrix); } void AlignerClient::set_alignment_scores(const int8_t* score_matrix, int8_t gap_open, int8_t gap_extend, int8_t full_length_bonus) { qual_adj_aligner = unique_ptr<QualAdjAligner>(new QualAdjAligner(score_matrix, gap_open, gap_extend, full_length_bonus, gc_content_estimate)); regular_aligner = unique_ptr<Aligner>(new Aligner(score_matrix, gap_open, gap_extend, full_length_bonus, gc_content_estimate)); } void AlignerClient::set_alignment_scores(std::istream& matrix_stream, int8_t gap_open, int8_t gap_extend, int8_t full_length_bonus) { int8_t* score_matrix = parse_matrix(matrix_stream); qual_adj_aligner = unique_ptr<QualAdjAligner>(new QualAdjAligner(score_matrix, gap_open, gap_extend, full_length_bonus, gc_content_estimate)); regular_aligner = unique_ptr<Aligner>(new Aligner(score_matrix, gap_open, gap_extend, full_length_bonus, gc_content_estimate)); free(score_matrix); }
44.62401
261
0.545571
lnceballosz
44d11aca04ecf5e58e8615f2f9c3fd92559abda6
5,703
cpp
C++
tsf/src/v20180326/model/CreateLaneRuleRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tsf/src/v20180326/model/CreateLaneRuleRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tsf/src/v20180326/model/CreateLaneRuleRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tsf/v20180326/model/CreateLaneRuleRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Tsf::V20180326::Model; using namespace std; CreateLaneRuleRequest::CreateLaneRuleRequest() : m_ruleNameHasBeenSet(false), m_remarkHasBeenSet(false), m_ruleTagListHasBeenSet(false), m_ruleTagRelationshipHasBeenSet(false), m_laneIdHasBeenSet(false), m_programIdListHasBeenSet(false) { } string CreateLaneRuleRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_ruleNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuleName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_ruleName.c_str(), allocator).Move(), allocator); } if (m_remarkHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Remark"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator); } if (m_ruleTagListHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuleTagList"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_ruleTagList.begin(); itr != m_ruleTagList.end(); ++itr, ++i) { d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(d[key.c_str()][i], allocator); } } if (m_ruleTagRelationshipHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuleTagRelationship"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_ruleTagRelationship.c_str(), allocator).Move(), allocator); } if (m_laneIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LaneId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_laneId.c_str(), allocator).Move(), allocator); } if (m_programIdListHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ProgramIdList"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_programIdList.begin(); itr != m_programIdList.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string CreateLaneRuleRequest::GetRuleName() const { return m_ruleName; } void CreateLaneRuleRequest::SetRuleName(const string& _ruleName) { m_ruleName = _ruleName; m_ruleNameHasBeenSet = true; } bool CreateLaneRuleRequest::RuleNameHasBeenSet() const { return m_ruleNameHasBeenSet; } string CreateLaneRuleRequest::GetRemark() const { return m_remark; } void CreateLaneRuleRequest::SetRemark(const string& _remark) { m_remark = _remark; m_remarkHasBeenSet = true; } bool CreateLaneRuleRequest::RemarkHasBeenSet() const { return m_remarkHasBeenSet; } vector<LaneRuleTag> CreateLaneRuleRequest::GetRuleTagList() const { return m_ruleTagList; } void CreateLaneRuleRequest::SetRuleTagList(const vector<LaneRuleTag>& _ruleTagList) { m_ruleTagList = _ruleTagList; m_ruleTagListHasBeenSet = true; } bool CreateLaneRuleRequest::RuleTagListHasBeenSet() const { return m_ruleTagListHasBeenSet; } string CreateLaneRuleRequest::GetRuleTagRelationship() const { return m_ruleTagRelationship; } void CreateLaneRuleRequest::SetRuleTagRelationship(const string& _ruleTagRelationship) { m_ruleTagRelationship = _ruleTagRelationship; m_ruleTagRelationshipHasBeenSet = true; } bool CreateLaneRuleRequest::RuleTagRelationshipHasBeenSet() const { return m_ruleTagRelationshipHasBeenSet; } string CreateLaneRuleRequest::GetLaneId() const { return m_laneId; } void CreateLaneRuleRequest::SetLaneId(const string& _laneId) { m_laneId = _laneId; m_laneIdHasBeenSet = true; } bool CreateLaneRuleRequest::LaneIdHasBeenSet() const { return m_laneIdHasBeenSet; } vector<string> CreateLaneRuleRequest::GetProgramIdList() const { return m_programIdList; } void CreateLaneRuleRequest::SetProgramIdList(const vector<string>& _programIdList) { m_programIdList = _programIdList; m_programIdListHasBeenSet = true; } bool CreateLaneRuleRequest::ProgramIdListHasBeenSet() const { return m_programIdListHasBeenSet; }
27.550725
104
0.713835
suluner
44d30c8845789e7c1a30a6f8f4b3b60bc6640599
258
cpp
C++
Kernel/Memory/GenericPagingTable.cpp
UltraOS/Ultra
287035fea303767285e48e5c7867d147790ff55b
[ "Apache-2.0" ]
44
2020-07-09T07:31:43.000Z
2022-03-29T20:55:01.000Z
Kernel/Memory/GenericPagingTable.cpp
8infy/UltraOS
2ed2879c96a7095b5077df5ba5db5b30a6565417
[ "Apache-2.0" ]
3
2021-04-24T13:53:53.000Z
2021-09-27T05:50:28.000Z
Kernel/Memory/GenericPagingTable.cpp
8infy/UltraOS
2ed2879c96a7095b5077df5ba5db5b30a6565417
[ "Apache-2.0" ]
3
2021-03-01T09:29:12.000Z
2021-06-25T17:06:27.000Z
#include "GenericPagingTable.h" #include "MemoryManager.h" namespace kernel { #ifdef ULTRA_64 Address GenericPagingTable::accessible_address_of(size_t index) { return MemoryManager::physical_memory_base + entry_at(index).physical_address(); } #endif }
19.846154
84
0.794574
UltraOS
44d41cf17e0a436311f4dc84aac84ff2a88353bb
4,020
cpp
C++
third_party/libigl/include/igl/vertex_components.cpp
chefmramos85/monster-mash
239a41f6f178ca83c4be638331e32f23606b0381
[ "Apache-2.0" ]
1,125
2021-02-01T09:51:56.000Z
2022-03-31T01:50:40.000Z
third_party/libigl/include/igl/vertex_components.cpp
ryan-cranfill/monster-mash
c1b906d996885f8a4011bdf7558e62e968e1e914
[ "Apache-2.0" ]
19
2021-02-01T12:36:30.000Z
2022-03-19T14:02:50.000Z
third_party/libigl/include/igl/vertex_components.cpp
ryan-cranfill/monster-mash
c1b906d996885f8a4011bdf7558e62e968e1e914
[ "Apache-2.0" ]
148
2021-02-13T10:54:31.000Z
2022-03-28T11:55:20.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Alec Jacobson <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "vertex_components.h" #include "adjacency_matrix.h" #include <queue> #include <vector> template <typename DerivedA, typename DerivedC, typename Derivedcounts> IGL_INLINE void igl::vertex_components( const Eigen::SparseCompressedBase<DerivedA> & A, Eigen::PlainObjectBase<DerivedC> & C, Eigen::PlainObjectBase<Derivedcounts> & counts) { using namespace Eigen; using namespace std; assert(A.rows() == A.cols() && "A should be square."); const size_t n = A.rows(); Array<bool,Dynamic,1> seen = Array<bool,Dynamic,1>::Zero(n,1); C.resize(n,1); typename DerivedC::Scalar id = 0; vector<typename Derivedcounts::Scalar> vcounts; // breadth first search for(int k=0; k<A.outerSize(); ++k) { if(seen(k)) { continue; } queue<int> Q; Q.push(k); vcounts.push_back(0); while(!Q.empty()) { const int f = Q.front(); Q.pop(); if(seen(f)) { continue; } seen(f) = true; C(f,0) = id; vcounts[id]++; // Iterate over inside for(typename DerivedA::InnerIterator it (A,f); it; ++it) { const int g = it.index(); if(!seen(g) && it.value()) { Q.push(g); } } } id++; } assert((size_t) id == vcounts.size()); const size_t ncc = vcounts.size(); assert((size_t)C.maxCoeff()+1 == ncc); counts.resize(ncc,1); for(size_t i = 0;i<ncc;i++) { counts(i) = vcounts[i]; } } template <typename DerivedA, typename DerivedC> IGL_INLINE void igl::vertex_components( const Eigen::SparseCompressedBase<DerivedA> & A, Eigen::PlainObjectBase<DerivedC> & C) { Eigen::VectorXi counts; return vertex_components(A,C,counts); } template <typename DerivedF, typename DerivedC> IGL_INLINE void igl::vertex_components( const Eigen::MatrixBase<DerivedF> & F, Eigen::PlainObjectBase<DerivedC> & C) { Eigen::SparseMatrix<typename DerivedC::Scalar> A; adjacency_matrix(F,A); return vertex_components(A,C); } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh template void igl::vertex_components<Eigen::SparseMatrix<bool, 0, int>, Eigen::Array<int, -1, 1, 0, -1, 1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<bool, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Array<int, -1, 1, 0, -1, 1> >&); template void igl::vertex_components<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); template void igl::vertex_components<Eigen::SparseMatrix<int, 0, int>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<int, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); template void igl::vertex_components<Eigen::SparseMatrix<int, 0, int>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<int, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&); template void igl::vertex_components<Eigen::SparseMatrix<double, 0, int>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<double, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&); template void igl::vertex_components<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&); #endif
40.606061
356
0.650498
chefmramos85
44d7e572a4e13add39ef307b60d9323142d301ad
5,868
cpp
C++
tf2_src/utils/vmpi/vmpi_job_watch/GraphControl.cpp
IamIndeedGamingAsHardAsICan03489/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/utils/vmpi/vmpi_job_watch/GraphControl.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/utils/vmpi/vmpi_job_watch/GraphControl.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// // GraphControl.cpp : implementation file // #include "stdafx.h" #include "vmpi_browser_job_watch.h" #include "GraphControl.h" #include "mathlib/mathlib.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CGraphControl CGraphControl::CGraphControl() { } CGraphControl::~CGraphControl() { } BEGIN_MESSAGE_MAP(CGraphControl, CWnd) //{{AFX_MSG_MAP(CGraphControl) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() void CGraphControl::Clear() { CRect rcClient; GetClientRect( rcClient ); CDC *pDC = GetDC(); CBrush brush( RGB( 0, 0, 0 ) ); CBrush *pOldBrush = pDC->SelectObject( &brush ); pDC->Rectangle( 0, 0, rcClient.Width(), rcClient.Height() ); pDC->SelectObject( pOldBrush ); ReleaseDC( pDC ); } void CGraphControl::Render( CDC *pDC ) { // Clear the background. CRect rcClient; GetClientRect( rcClient ); CBrush brush( RGB( 0, 0, 0 ) ); CBrush *pOldBrush = pDC->SelectObject( &brush ); pDC->Rectangle( 0, 0, rcClient.Width(), rcClient.Height() ); pDC->SelectObject( pOldBrush ); // Work backwards from the right side to the left. int nIntervals = rcClient.Width(); DWORD intervalMS = 500; // one interval per pixel DWORD startTime = 0xFFFFFFFF, endTime = 0; // First, find which order of magnitude to use on the vertical scale by finding the maximum value. for ( int iEntry=0; iEntry < m_Entries.Count(); iEntry++ ) { DWORD msTime = m_Entries[iEntry].m_msTime; startTime = min( startTime, msTime ); endTime = max( endTime, msTime ); } int curTime = (int)endTime - nIntervals*intervalMS; CGraphEntry prevEntry, curEntry; prevEntry.m_msTime = curEntry.m_msTime = -1; CUtlVector<POINT> sentPoints; CUtlVector<POINT> receivedPoints; int iCurEntry = -1; int nMaxBytesSent = -1, nMaxBytesReceived = -1; for ( int x=0; x < nIntervals; x++ ) { if ( curTime >= 0 ) { // Now find the graph_entry for the time we're at. while ( prevEntry.m_msTime == -1 || curTime > curEntry.m_msTime ) { ++iCurEntry; if ( iCurEntry >= m_Entries.Count() ) goto ENDLOOP; prevEntry = curEntry; curEntry = m_Entries[iCurEntry]; } if ( curTime >= prevEntry.m_msTime && curTime <= curEntry.m_msTime ) { // Interpolate the bytes sent. int nBytesSent = (int)RemapVal( curTime, prevEntry.m_msTime, curEntry.m_msTime, prevEntry.m_nBytesSent, curEntry.m_nBytesSent ); POINT sentPoint = { x, nBytesSent }; sentPoints.AddToTail( sentPoint ); nMaxBytesSent = max( nMaxBytesSent, nBytesSent ); int nBytesReceived = (int)RemapVal( curTime, prevEntry.m_msTime, curEntry.m_msTime, prevEntry.m_nBytesReceived, curEntry.m_nBytesReceived ); POINT receivedPoint = { x, nBytesReceived }; receivedPoints.AddToTail( receivedPoint ); nMaxBytesReceived = max( nMaxBytesReceived, nBytesReceived ); } } curTime += intervalMS; } ENDLOOP:; // Now normalize all the values. int largest = max( nMaxBytesSent, nMaxBytesReceived ); int topValue = (largest*11) / 10; /* DWORD nZeros; for( nZeros = 1; nZeros < 20; nZeros++ ) { if ( largest < pow( 10, nZeros ) ) break; } // Now find the value at the top of the graph. We choose the smallest enclosing tenth of the // order of magnitude we're at (so if we were at 1,000,000, and our max value was 350,000, we'd choose 400,000). int iTenth; int topValue; for ( iTenth=1; iTenth <= 10; iTenth++ ) { topValue = (DWORD)( pow( 10, nZeros-1 ) * iTenth ); if ( topValue >= largest ) break; } */ for ( int iSample=0; iSample < sentPoints.Count(); iSample++ ) { double flHeight; flHeight = ((double)sentPoints[iSample].y / topValue) * (rcClient.Height() - 1); sentPoints[iSample].y = (int)( rcClient.Height() - flHeight ); flHeight = ((double)receivedPoints[iSample].y / topValue) * (rcClient.Height() - 1); receivedPoints[iSample].y = (int)( rcClient.Height() - flHeight ); } // Draw some horizontal lines dividing the space. int nLines = 10; for ( int iLine=0; iLine <= nLines; iLine++ ) { CPen penLine; COLORREF color; if ( iLine == 0 || iLine == nLines/2 ) color = RGB( 0, 220, 0 ); else color = RGB( 0, 100, 0 ); penLine.CreatePen( PS_SOLID, 1, color ); CPen *pOldPen = pDC->SelectObject( &penLine ); int y = (iLine * rcClient.Height()) / nLines; pDC->MoveTo( 0, y ); pDC->LineTo( rcClient.Width(), y ); pDC->SelectObject( pOldPen ); } // Now draw the lines for the data. CPen penSent( PS_SOLID, 1, RGB( 0, 255, 0 ) ); CPen *pOldPen = pDC->SelectObject( &penSent ); pDC->Polyline( sentPoints.Base(), sentPoints.Count() ); pDC->SelectObject( pOldPen ); CPen penReceived( PS_SOLID, 1, RGB( 255, 255, 0 ) ); pOldPen = pDC->SelectObject( &penReceived ); pDC->Polyline( receivedPoints.Base(), receivedPoints.Count() ); pDC->SelectObject( pOldPen ); // Draw text labels. pDC->SetTextColor( RGB( 200, 200, 200 ) ); pDC->SetBkColor( 0 ); CString str; str.Format( "%dk", (topValue+511) / 1024 ); pDC->ExtTextOut( 0, 1, 0, NULL, str, NULL ); str.Format( "%dk", (topValue+511) / 1024 / 2 ); pDC->ExtTextOut( 0, rcClient.Height()/2 + 1, 0, NULL, str, NULL ); } void CGraphControl::Fill( CUtlVector<CGraphEntry> &entries ) { CDC *pDC = GetDC(); if ( !pDC ) return; m_Entries = entries; Render( pDC ); ReleaseDC( pDC ); } ///////////////////////////////////////////////////////////////////////////// // CGraphControl message handlers void CGraphControl::OnPaint() { CPaintDC dc(this); // device context for painting Render( &dc ); }
23.757085
113
0.632243
IamIndeedGamingAsHardAsICan03489
44dde9125f17488902a192c50863c28b054d7e7c
8,506
hpp
C++
lib/lorina/lorina/genlib.hpp
fmozafari/mockturtle
ebf32a5643bf818a3720809b867a0401a4bc6eed
[ "MIT" ]
null
null
null
lib/lorina/lorina/genlib.hpp
fmozafari/mockturtle
ebf32a5643bf818a3720809b867a0401a4bc6eed
[ "MIT" ]
null
null
null
lib/lorina/lorina/genlib.hpp
fmozafari/mockturtle
ebf32a5643bf818a3720809b867a0401a4bc6eed
[ "MIT" ]
1
2021-12-20T20:42:30.000Z
2021-12-20T20:42:30.000Z
/* lorina: C++ parsing library * Copyright (C) 2018-2021 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file genlib.hpp \brief Implements GENLIB parser \author Heinz Riener \author Shubham Rai \author Alessandro Tempia Calvino */ #pragma once #include "common.hpp" #include "detail/utils.hpp" #include "diagnostics.hpp" #include <fstream> #include <istream> #include <optional> #include <sstream> #include <string> namespace lorina { enum class phase_type : uint8_t { INV = 0, NONINV = 1, UNKNOWN = 2, }; // PIN <pin-name> <phase> <input-load> <max-load> <rise-block-delay> <rise-fanout-delay> <fall-block-delay> <fall-fanout-delay> struct pin_spec { std::string name; phase_type phase; double input_load; double max_load; double rise_block_delay; double rise_fanout_delay; double fall_block_delay; double fall_fanout_delay; }; /* pin_spec */ /*! \brief A reader visitor for a GENLIB format. * * Callbacks for the GENLIB format. */ class genlib_reader { public: virtual void on_gate( std::string const& name, std::string const& expression, uint32_t num_vars, double area, std::vector<pin_spec> const& pins ) const { (void)name; (void)expression; (void)num_vars; (void)area; (void)pins; } }; /* genlib_reader */ /*! \brief Parse for the GENLIB format. * */ class genlib_parser { public: explicit genlib_parser( std::istream& in, genlib_reader const& reader, diagnostic_engine* diag ) : in( in ) , reader( reader ) , diag( diag ) {} public: bool run() { std::string line; while ( std::getline( in, line ) ) { /* remove whitespaces */ detail::trim( line ); /* skip comments and empty lines */ if ( line[0] == '#' || line.empty() ) { continue; } if ( !parse_gate_definition( line ) ) { return false; } } return true; } private: bool parse_gate_definition( std::string const& line ) { std::stringstream ss( line ); std::string const deliminators{" \t\r\n"}; std::string token; std::vector<std::string> tokens; while ( std::getline( ss, token ) ) { std::size_t prev = 0, pos; while ( ( pos = line.find_first_of( deliminators, prev ) ) != std::string::npos ) { if ( pos > prev ) { tokens.emplace_back( token.substr( prev, pos - prev ) ); } prev = pos + 1; } if ( prev < line.length() ) { tokens.emplace_back( token.substr( prev, std::string::npos ) ); } } if ( tokens.size() < 4u ) { if ( diag ) { diag->report( diag_id::ERR_GENLIB_UNEXPECTED_STRUCTURE ).add_argument( line ); } return false; } if ( tokens[0] != "GATE" ) { if ( diag ) { diag->report( diag_id::ERR_GENLIB_GATE ).add_argument( line ); } return false; } auto const beg = tokens[3].find_first_of( "=" ); auto const end = tokens[3].find_first_of( ";" ); if ( beg == std::string::npos || end == std::string::npos ) { if ( diag ) { diag->report( diag_id::ERR_GENLIB_EXPRESSION ).add_argument( tokens[3] ); } return false; } std::string const& name = tokens[1]; std::string const& expression = tokens[3].substr( beg + 1, end - beg - 1 ); double const area = std::stod( tokens[2] ); uint32_t num_vars{0}; for ( const auto& c : expression ) { if ( c >= 'a' && c <= 'z' ) { uint32_t const var = 1 + ( c - 'a' ); if ( var > num_vars ) { num_vars = var; } } } std::vector<pin_spec> pins; bool generic_pin{false}; uint64_t i{4}; for ( ; i+8 < tokens.size(); i += 9 ) { /* check PIN specification */ if ( tokens[i] != "PIN" ) { if ( diag ) { diag->report( diag_id::ERR_GENLIB_PIN ).add_argument( tokens[i] ); } return false; } std::string const& name = tokens[i+1]; if ( tokens[i+1] == "*" ) { generic_pin = true; } phase_type phase{phase_type::UNKNOWN}; if ( tokens[i+2] == "INV" ) { phase = phase_type::INV; } else if ( tokens[i+2] == "NONINV" ) { phase = phase_type::NONINV; } else { if ( tokens[i+2] != "UNKNOWN" ) { if ( diag ) { diag->report( diag_id::ERR_GENLIB_PIN_PHASE ).add_argument( tokens[i+1] ); } } } double const input_load = std::stod( tokens[i+3] ); double const max_load = std::stod( tokens[i+4] ); double const rise_block_delay = std::stod( tokens[i+5] ); double const rise_fanout_delay = std::stod( tokens[i+6] ); double const fall_block_delay = std::stod( tokens[i+7] ); double const fall_fanout_delay = std::stod( tokens[i+8] ); pins.emplace_back( pin_spec{name,phase,input_load,max_load,rise_block_delay,rise_fanout_delay,fall_block_delay,fall_fanout_delay} ); } if ( pins.size() != num_vars && !( pins.size() == 1 && generic_pin ) ) { if ( diag ) { diag->report( diag_id::ERR_GENLIB_PIN ).add_argument( tokens[i] ); } return false; } if ( i != tokens.size() ) { if ( diag ) { diag->report( diag_id::ERR_GENLIB_FAILED ).add_argument( tokens[i] ); } return false; } reader.on_gate( name, expression, num_vars, area, pins ); return true; } protected: std::istream& in; genlib_reader const& reader; diagnostic_engine* diag; }; /* genlib_parser */ /*! \brief Reader function for the GENLIB format. * * Reads GENLIB format from a stream and invokes a callback * method for each parsed primitive and each detected parse error. * * \param in Input stream * \param reader GENLIB reader with callback methods invoked for parsed primitives * \param diag An optional diagnostic engine with callback methods for parse errors * \return Success if parsing has been successful, or parse error if parsing has failed */ [[nodiscard]] inline return_code read_genlib( std::istream& in, const genlib_reader& reader, diagnostic_engine* diag = nullptr ) { genlib_parser parser( in, reader, diag ); auto result = parser.run(); if ( !result ) { return return_code::parse_error; } else { return return_code::success; } } /*! \brief Reader function for the GENLIB format. * * Reads GENLIB format from a file and invokes a callback * method for each parsed primitive and each detected parse error. * * \param filename Name of the file * \param reader GENLIB reader with callback methods invoked for parsed primitives * \param diag An optional diagnostic engine with callback methods for parse errors * \return Success if parsing has been successful, or parse error if parsing has failed */ [[nodiscard]] inline return_code read_genlib( const std::string& filename, const genlib_reader& reader, diagnostic_engine* diag = nullptr ) { std::ifstream in( detail::word_exp_filename( filename ), std::ifstream::in ); if ( !in.is_open() ) { if ( diag ) { diag->report( diag_id::ERR_FILE_OPEN ).add_argument( filename ); } return return_code::parse_error; } else { auto const ret = read_genlib( in, reader, diag ); in.close(); return ret; } } } /* lorina */
25.932927
153
0.618152
fmozafari
44ded4ccb5a4e2954add318cdc7c412c190c51b9
1,635
cpp
C++
o12e1ska/skar.cpp
czers/oi-tasks
b862cd33bd2230c7cea135333056954388ba9502
[ "Unlicense" ]
null
null
null
o12e1ska/skar.cpp
czers/oi-tasks
b862cd33bd2230c7cea135333056954388ba9502
[ "Unlicense" ]
null
null
null
o12e1ska/skar.cpp
czers/oi-tasks
b862cd33bd2230c7cea135333056954388ba9502
[ "Unlicense" ]
null
null
null
#include <cstdio> class FindUnion { private: int rank; FindUnion *parent; public: static void MakeSet(FindUnion &x) { x.parent = &x; x.rank = 0; } static void Union(FindUnion &x, FindUnion &y) { FindUnion *xRoot = FindUnion::Find(x); FindUnion *yRoot = FindUnion::Find(y); if (xRoot == yRoot) return; if (xRoot->rank < yRoot->rank) xRoot->parent = yRoot; else if (xRoot->rank > yRoot->rank) yRoot->parent = xRoot; else { yRoot->parent = xRoot; xRoot->rank += 1; } } static FindUnion* Find(FindUnion &x) { if (x.parent != &x) x.parent = FindUnion::Find(*x.parent); return x.parent; } static int FindIndex(FindUnion &x, FindUnion fu[]) { return FindUnion::Find(x) - fu; } }; int main() { int n; scanf("%d", &n); FindUnion fu[n]; for (int i = 0; i < n; i++) FindUnion::MakeSet(fu[i]); for (int i = 0; i < n; i++) { int a; scanf("%d", &a); a--; FindUnion::Union(fu[i], fu[a]); } bool setRoot[n]; for (int i = 0; i < n; i++) setRoot[i] = false; for (int i = 0; i < n; i++) setRoot[FindUnion::FindIndex(fu[i], fu)] = true; int count = 0; for (int i = 0; i < n; i++) if (setRoot[i] == true) count++; printf("%d\n", count); return 0; }
24.044118
58
0.428746
czers
44e1baffbba192d7088b5f642560792da83e0db0
447
hpp
C++
SDK/Examples/FilamentViewer/FilamentViewer/Debugging/LogLights.hpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
24
2019-10-28T07:01:48.000Z
2022-03-04T16:10:39.000Z
SDK/Examples/FilamentViewer/FilamentViewer/Debugging/LogLights.hpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
8
2020-04-22T19:42:45.000Z
2021-04-30T16:28:32.000Z
SDK/Examples/FilamentViewer/FilamentViewer/Debugging/LogLights.hpp
h-haris/Quesa
a438ab824291ce6936a88dfae4fd0482dcba1247
[ "BSD-3-Clause" ]
6
2019-09-22T14:44:15.000Z
2021-04-01T20:04:29.000Z
// // LogLights.hpp // FilamentViewer // // Created by James Walker on 5/27/21. // #ifndef LogLights_hpp #define LogLights_hpp namespace filament { class Engine; class Scene; }; /*! @function LogLights @abstract Log various information about lights in a Scene to std::cout. @param inEngine An engine. @param inScene A scene. */ void LogLights( filament::Engine& inEngine, filament::Scene& inScene ); #endif /* LogLights_hpp */
15.964286
72
0.704698
h-haris
44e5a903b3287a21da7c1b1ffa5bd1197bb25453
599
cpp
C++
Difficulty 2/fluortanten.cpp
BrynjarGeir/Kattis
a151972cbae3db04a8e6764d5fa468d0146c862b
[ "MIT" ]
null
null
null
Difficulty 2/fluortanten.cpp
BrynjarGeir/Kattis
a151972cbae3db04a8e6764d5fa468d0146c862b
[ "MIT" ]
null
null
null
Difficulty 2/fluortanten.cpp
BrynjarGeir/Kattis
a151972cbae3db04a8e6764d5fa468d0146c862b
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int calc_sum(vector<int> numbers) { int ans = 0; for(int i = 1; i <= numbers.size(); i++) ans += i * numbers.at(i-1); return ans; } int main() { int n, number, pos; cin >> n; vector<pair<int, int>> numbers; for(int i = 0; i < n; i++) { cin >> number; if(number == 0) pos = i; numbers.push_back(number); } int max_happiness = INT32_MIN, ps = -1; for(int i = 1; i < n; i++) max_happiness = max(max_happiness, calc_sum(swap(numbers, i, pos))); cout << max_happiness; }
21.392857
99
0.557596
BrynjarGeir
44e5dfa02242f7d12230a06294f51d7fe06a5a06
1,451
hxx
C++
Legolas/Vector/VirtualVector.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/Vector/VirtualVector.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/Vector/VirtualVector.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
1
2021-02-11T14:43:25.000Z
2021-02-11T14:43:25.000Z
#pragma once #include <cstdlib> namespace Legolas{ class VirtualVector { public: // virtual int getSize( void ) const = 0 ; typedef std::size_t SizeType; virtual SizeType size( void ) const = 0 ; virtual const VirtualVector & getElement( SizeType i ) const = 0 ; virtual VirtualVector & getElement( SizeType i ) = 0 ; virtual VirtualVector * clone( void ) const = 0 ; virtual VirtualVector * newVirtualVector( const VirtualVectorShape & shape) const = 0 ; virtual ~VirtualVector( void ){}; virtual bool sameShape(const VirtualVector & source ) const = 0; virtual void copy(const VirtualVector & source) = 0 ; virtual void scale( double a ) =0 ; virtual double relativeDiffAndCopy( const VirtualVector & source ) = 0; virtual void plusAssign(double factor, const VirtualVector & source) = 0; virtual double dot(const VirtualVector & source) const = 0; virtual void scaleAndPlusAssign(double scaleFactor, double factor,const VirtualVector & source) = 0; virtual void display( void ) const =0; typedef VirtualVector * VirtualVectorPtr; static inline VirtualVector & getClone(VirtualVectorPtr & vecPtr,const VirtualVector & source){ if (!vecPtr){ vecPtr=source.clone(); } else{ if (!vecPtr->sameShape(source)){ delete vecPtr; vecPtr=source.clone(); } else{ vecPtr->copy(source); } } return (*vecPtr); } }; }
30.87234
104
0.673329
LaurentPlagne
44ea1cd2cb3edc3ee3cfe10d4fbfcfd4ae550453
3,363
cpp
C++
src/cli/main.cpp
brio1009/ElTrazadoDeRayos
8c65eb9c7724812ab9f8103fd00a28324753e4b6
[ "BSL-1.0", "MIT" ]
null
null
null
src/cli/main.cpp
brio1009/ElTrazadoDeRayos
8c65eb9c7724812ab9f8103fd00a28324753e4b6
[ "BSL-1.0", "MIT" ]
null
null
null
src/cli/main.cpp
brio1009/ElTrazadoDeRayos
8c65eb9c7724812ab9f8103fd00a28324753e4b6
[ "BSL-1.0", "MIT" ]
null
null
null
/* The MIT License (MIT) Copyright (c) 2014 CantTouchDis <[email protected]> Copyright (c) 2014 brio1009 <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // GLM-define, because degree-methods are deprected. #define GLM_FORCE_RADIANS // RayTracerLib. #include <Image.h> #include <Ray.h> #include <Scene.h> #include <cameras/PerspectiveCamera.h> #include <materials/Material.h> #include <parser/SceneFileParser.h> #include <shapes/Ellipsoid.h> #include <shapes/Plane.h> // C Header. #include <omp.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include <glm/gtx/vector_angle.hpp> // C++ Header. #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <vector> // void renderScene(const char* fileName, size_t chunks, size_t chunkNr) { // Create the scene. This also adds all the objects. Scene scene; // Load the desired Scene. SceneFileParser sceneParser; sceneParser.parse("testScene.xml", &scene); // Render all the images. scene.render(chunks, chunkNr); // Get the cameras and save the images. for (size_t i = 0; i < scene.cameras().size(); ++i) { // Save the image under different names. char buff[100]; #ifdef WINDOWS _snprintf_s(buff, sizeof(buff), "%s%03lu.bmp", fileName, i); #else snprintf(buff, sizeof(buff), "%s%03zu.bmp", fileName, i); #endif // WINDOWS scene.cameras().at(i)->getImage().saveAsBMP(buff); } } // The main method. int main(int argc, char** argv) { const char* fileName = "Img"; // Print usage info. if (argc > 5) { printf( "Usage: %s <optional: output> <optional: chunks chunknr> " "<optional: random seed>\n", argv[0]); exit(EXIT_FAILURE); } omp_set_num_threads(1); // TODO: Need to replace rand() in PhongBRDF with // thread-safe variant. // Initialize the rand function. unsigned int seed = static_cast<unsigned int>(time(NULL)); if (argc > 1) { fileName = argv[1]; } size_t chunks = 1; size_t chunkNr = 0; if (argc > 3) { chunks = atol(argv[2]); chunkNr = atol(argv[3]); } if (argc == 5) { seed = static_cast<unsigned int>(atoi(argv[4])); } printf("Random seed used: %u\n\n", seed); srand(seed); // Render our test scene. renderScene(fileName, chunks, chunkNr); }
30.853211
78
0.704728
brio1009
44ec4114d7fa6efb661cd63cc83691347994eec8
364
cpp
C++
PrimeNumber.cpp
tusharxsharma/BasicPrograms
8aa30da7c1f63d5c7762bb252e65acb76f1b0edd
[ "Unlicense" ]
1
2020-03-18T18:40:48.000Z
2020-03-18T18:40:48.000Z
PrimeNumber.cpp
tusharxsharma/BasicPrograms
8aa30da7c1f63d5c7762bb252e65acb76f1b0edd
[ "Unlicense" ]
null
null
null
PrimeNumber.cpp
tusharxsharma/BasicPrograms
8aa30da7c1f63d5c7762bb252e65acb76f1b0edd
[ "Unlicense" ]
null
null
null
#include<iostream> using namespace std; int main() { int n , x; cout <<"Enter the number : \n"; cin>>n; if(n<2) cout<<"Number is lesser than 2 and not applicable"; else { for(x=2;x<n;x++) { if(n%x==0) { cout<<"Not Prime Number"; exit(0); } else { cout<<"Prime Number"; exit(1); } } } }
13.481481
54
0.478022
tusharxsharma
44ed03145058d315d8572e1838db40ebe2c60e56
5,207
cpp
C++
ext/native/java/lang/reflect/Array_-native.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/native/java/lang/reflect/Array_-native.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/native/java/lang/reflect/Array_-native.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #include <java/lang/reflect/Array_.hpp> extern void unimplemented_(const char16_t* name); java::lang::Object* java::lang::reflect::Array_::get(::java::lang::Object* array, int32_t index) { /* native */ clinit(); unimplemented_(u"java::lang::Object* java::lang::reflect::Array_::get(::java::lang::Object* array, int32_t index)"); return 0; } bool java::lang::reflect::Array_::getBoolean(::java::lang::Object* array, int32_t index) { /* native */ clinit(); unimplemented_(u"bool java::lang::reflect::Array_::getBoolean(::java::lang::Object* array, int32_t index)"); return 0; } int8_t java::lang::reflect::Array_::getByte(::java::lang::Object* array, int32_t index) { /* native */ clinit(); unimplemented_(u"int8_t java::lang::reflect::Array_::getByte(::java::lang::Object* array, int32_t index)"); return 0; } char16_t java::lang::reflect::Array_::getChar(::java::lang::Object* array, int32_t index) { /* native */ clinit(); unimplemented_(u"char16_t java::lang::reflect::Array_::getChar(::java::lang::Object* array, int32_t index)"); return 0; } double java::lang::reflect::Array_::getDouble(::java::lang::Object* array, int32_t index) { /* native */ clinit(); unimplemented_(u"double java::lang::reflect::Array_::getDouble(::java::lang::Object* array, int32_t index)"); return 0; } float java::lang::reflect::Array_::getFloat(::java::lang::Object* array, int32_t index) { /* native */ clinit(); unimplemented_(u"float java::lang::reflect::Array_::getFloat(::java::lang::Object* array, int32_t index)"); return 0; } int32_t java::lang::reflect::Array_::getInt(::java::lang::Object* array, int32_t index) { /* native */ clinit(); unimplemented_(u"int32_t java::lang::reflect::Array_::getInt(::java::lang::Object* array, int32_t index)"); return 0; } int32_t java::lang::reflect::Array_::getLength(::java::lang::Object* array) { /* native */ clinit(); unimplemented_(u"int32_t java::lang::reflect::Array_::getLength(::java::lang::Object* array)"); return 0; } int64_t java::lang::reflect::Array_::getLong(::java::lang::Object* array, int32_t index) { /* native */ clinit(); unimplemented_(u"int64_t java::lang::reflect::Array_::getLong(::java::lang::Object* array, int32_t index)"); return 0; } int16_t java::lang::reflect::Array_::getShort(::java::lang::Object* array, int32_t index) { /* native */ clinit(); unimplemented_(u"int16_t java::lang::reflect::Array_::getShort(::java::lang::Object* array, int32_t index)"); return 0; } /* private: java::lang::Object* java::lang::reflect::Array_::multiNewArray_(::java::lang::Class* componentType, ::int32_tArray* dimensions) */ /* private: java::lang::Object* java::lang::reflect::Array_::newArray_(::java::lang::Class* componentType, int32_t length) */ void java::lang::reflect::Array_::set(::java::lang::Object* array, int32_t index, ::java::lang::Object* value) { /* native */ clinit(); unimplemented_(u"void java::lang::reflect::Array_::set(::java::lang::Object* array, int32_t index, ::java::lang::Object* value)"); } void java::lang::reflect::Array_::setBoolean(::java::lang::Object* array, int32_t index, bool z) { /* native */ clinit(); unimplemented_(u"void java::lang::reflect::Array_::setBoolean(::java::lang::Object* array, int32_t index, bool z)"); } void java::lang::reflect::Array_::setByte(::java::lang::Object* array, int32_t index, int8_t b) { /* native */ clinit(); unimplemented_(u"void java::lang::reflect::Array_::setByte(::java::lang::Object* array, int32_t index, int8_t b)"); } void java::lang::reflect::Array_::setChar(::java::lang::Object* array, int32_t index, char16_t c) { /* native */ clinit(); unimplemented_(u"void java::lang::reflect::Array_::setChar(::java::lang::Object* array, int32_t index, char16_t c)"); } void java::lang::reflect::Array_::setDouble(::java::lang::Object* array, int32_t index, double d) { /* native */ clinit(); unimplemented_(u"void java::lang::reflect::Array_::setDouble(::java::lang::Object* array, int32_t index, double d)"); } void java::lang::reflect::Array_::setFloat(::java::lang::Object* array, int32_t index, float f) { /* native */ clinit(); unimplemented_(u"void java::lang::reflect::Array_::setFloat(::java::lang::Object* array, int32_t index, float f)"); } void java::lang::reflect::Array_::setInt(::java::lang::Object* array, int32_t index, int32_t i) { /* native */ clinit(); unimplemented_(u"void java::lang::reflect::Array_::setInt(::java::lang::Object* array, int32_t index, int32_t i)"); } void java::lang::reflect::Array_::setLong(::java::lang::Object* array, int32_t index, int64_t l) { /* native */ clinit(); unimplemented_(u"void java::lang::reflect::Array_::setLong(::java::lang::Object* array, int32_t index, int64_t l)"); } void java::lang::reflect::Array_::setShort(::java::lang::Object* array, int32_t index, int16_t s) { /* native */ clinit(); unimplemented_(u"void java::lang::reflect::Array_::setShort(::java::lang::Object* array, int32_t index, int16_t s)"); }
39.44697
142
0.677165
pebble2015
44ed72cc0cc7f5374eb6eef7af91e09a046b67b8
415
cpp
C++
Source/Python/Concat.cpp
andrei-sa/aspen
6644663fc19a83fba0603dc4bbd6dbe71cfd55aa
[ "Apache-2.0" ]
2
2020-10-16T19:41:19.000Z
2021-02-01T04:55:51.000Z
Source/Python/Concat.cpp
andrei-sa/aspen
6644663fc19a83fba0603dc4bbd6dbe71cfd55aa
[ "Apache-2.0" ]
1
2020-04-24T18:17:39.000Z
2020-04-24T18:37:01.000Z
Source/Python/Concat.cpp
andrei-sa/aspen
6644663fc19a83fba0603dc4bbd6dbe71cfd55aa
[ "Apache-2.0" ]
2
2020-04-17T13:24:29.000Z
2020-04-24T18:12:29.000Z
#include "Aspen/Python/Concat.hpp" #include "Aspen/Python/Box.hpp" using namespace Aspen; using namespace pybind11; void Aspen::export_concat(pybind11::module& module) { export_box<SharedBox<object>>(module, "Box"); export_concat<SharedBox<SharedBox<object>>>(module, ""); module.def("concat", [] (SharedBox<SharedBox<object>> producer) { return shared_box(concat(std::move(producer))); }); }
27.666667
58
0.710843
andrei-sa
44ed970a155b89b6b66713b2058e473d5fd16ba2
628
hh
C++
src/Zynga/Framework/Lockable/Cache/V1/Config/Mock/PgData/DevTest.hh
zynga/zynga-hacklang-framework
2730f354adb684085fff6dca3c1cac1b31502c6b
[ "MIT" ]
19
2018-04-23T09:30:48.000Z
2022-03-06T21:35:18.000Z
src/Zynga/Framework/Lockable/Cache/V1/Config/Mock/PgData/DevTest.hh
zynga/zynga-hacklang-framework
2730f354adb684085fff6dca3c1cac1b31502c6b
[ "MIT" ]
22
2017-11-27T23:39:25.000Z
2019-08-09T08:56:57.000Z
src/Zynga/Framework/Lockable/Cache/V1/Config/Mock/PgData/DevTest.hh
zynga/zynga-hacklang-framework
2730f354adb684085fff6dca3c1cac1b31502c6b
[ "MIT" ]
28
2017-11-16T20:53:56.000Z
2021-01-04T11:13:17.000Z
<?hh // strict namespace Zynga\Framework\Lockable\Cache\V1\Config\Mock\PgData; use Zynga\Framework\Testing\TestCase\V2\Base as TestCase; use Zynga\Framework\Lockable\Cache\V1\Config\Mock\PgData\Dev as ConfigUnderTest ; use Zynga\Framework\Cache\V2\Interfaces\DriverInterface as CacheDriverInterface ; class DevTest extends TestCase { public function testCreateKeyFromStorableObject(): void { $obj = new ConfigUnderTest(); $this->assertInstanceOf(CacheDriverInterface::class, $obj->getCache()); $this->assertEquals('Caching', $obj->getDriver()); $this->assertEquals(10, $obj->getLockTTL()); } }
22.428571
77
0.745223
zynga
44ee14f5a59b8bfde4cd42497b82448f1e5a706b
1,055
cpp
C++
Source/FactorySkyline/UI/FSKeyMappingWidget.cpp
RozeDoyanawa/FactorySkyline
381d983d8c8fcac7fa9ce3c386d52bd68d2248b6
[ "MIT" ]
3
2021-07-09T06:20:11.000Z
2022-01-23T09:29:21.000Z
Source/FactorySkyline/UI/FSKeyMappingWidget.cpp
Nuwisam/FactorySkyline
4e4987d2e7f0a67d992d600fc7f280593cee4f94
[ "MIT" ]
null
null
null
Source/FactorySkyline/UI/FSKeyMappingWidget.cpp
Nuwisam/FactorySkyline
4e4987d2e7f0a67d992d600fc7f280593cee4f94
[ "MIT" ]
6
2021-07-11T15:10:12.000Z
2022-02-27T02:16:15.000Z
// ILikeBanas #include "FactorySkyline/UI/FSKeyMappingWidget.h" #include "Components/Image.h" #include "Components/HorizontalBox.h" #include "Components/TextBlock.h" #include "Components/CanvasPanel.h" #include "Components/CanvasPanelSlot.h" #include "Components/HorizontalBoxSlot.h" UFSKeyMappingWidget::UFSKeyMappingWidget(const FObjectInitializer& ObjectInitializer) :Super(ObjectInitializer) { } void UFSKeyMappingWidget::SetTitle(const FText& Title) { this->Title->SetText(Title); } void UFSKeyMappingWidget::SetKey(const FText& Key) { this->Key->SetText(Key); } void UFSKeyMappingWidget::SetPadding(const float& Padding) { UHorizontalBoxSlot* Slot = Cast<UHorizontalBoxSlot>(this->Slot); Slot->SetPadding(FMargin(Padding, 0.0f)); } void UFSKeyMappingWidget::SetDefaultView() { HighLight->SetVisibility(ESlateVisibility::Hidden); IsHighLight = false; } void UFSKeyMappingWidget::SetHighLightView() { HighLight->SetVisibility(ESlateVisibility::SelfHitTestInvisible); IsHighLight = true; }
23.444444
86
0.756398
RozeDoyanawa
6021b37b4b61016702c87a1c89be28a7029a45bc
1,781
cpp
C++
modules/burdukov_mikhail_horse_min_range/test/test_burdukov_mikhail_horse_min_range.cpp
BalovaElena/devtools-course-practice
f8d5774dbb78ec50200c45fd17665ed40fc8c4c5
[ "CC-BY-4.0" ]
null
null
null
modules/burdukov_mikhail_horse_min_range/test/test_burdukov_mikhail_horse_min_range.cpp
BalovaElena/devtools-course-practice
f8d5774dbb78ec50200c45fd17665ed40fc8c4c5
[ "CC-BY-4.0" ]
null
null
null
modules/burdukov_mikhail_horse_min_range/test/test_burdukov_mikhail_horse_min_range.cpp
BalovaElena/devtools-course-practice
f8d5774dbb78ec50200c45fd17665ed40fc8c4c5
[ "CC-BY-4.0" ]
null
null
null
// Copyright 2022 Burdukov Mikhail #include <gtest/gtest.h> #include "include/horse_min_range.h" TEST(minHorseRange, Create) { ASSERT_NO_THROW(minHorseRange hourse); } TEST(minHorseRange, Range_without_barriers) { chess_position_t st('a', 1); chess_position_t fin('b', 3); minHorseRange a(st, fin); EXPECT_EQ(1, a.calc_range()); } TEST(minHorseRange, Range_without_barriers1) { chess_position_t st('a', 1); chess_position_t fin('b', 3); minHorseRange a; a.set_start(st); a.set_finish(fin); EXPECT_EQ(1, a.calc_range()); } TEST(minHorseRange, Range_without_barriers3) { chess_position_t st('a', 1); chess_position_t fin('b', 7); minHorseRange a; a.set_start(st); a.set_finish(fin); EXPECT_EQ(3, a.calc_range()); } TEST(minHorseRange, Range_without_barriers4) { chess_position_t st('a', 1); chess_position_t fin('g', 8); minHorseRange a; a.set_start(st); a.set_finish(fin); EXPECT_EQ(5, a.calc_range()); } TEST(minHorseRange, Range_with_barriers) { chess_position_t st('a', 1); chess_position_t fin('b', 3); chess_position_t bar('g', 8); minHorseRange a; a.set_start(st); a.set_finish(fin); a.set_barrier(bar); EXPECT_EQ(1, a.calc_range()); } TEST(minHorseRange, Range_with_barriers1) { chess_position_t st('a', 1); chess_position_t fin('b', 7); chess_position_t bar('g', 8); minHorseRange a; a.set_start(st); a.set_finish(fin); a.set_barrier(bar); EXPECT_EQ(3, a.calc_range()); } TEST(minHorseRange, Range_with_barriers3) { chess_position_t st('a', 1); chess_position_t fin('b', 3); chess_position_t bar('h', 2); minHorseRange a(st, fin); a.set_barrier(bar); EXPECT_EQ(1, a.calc_range()); }
23.434211
46
0.663672
BalovaElena
6023f4fffb82ea29d1b3546e9969f026ef7d982e
244
cpp
C++
1-Iniciante/12/2879.cpp
pedrospaulo/01-C-
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
[ "MIT" ]
null
null
null
1-Iniciante/12/2879.cpp
pedrospaulo/01-C-
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
[ "MIT" ]
null
null
null
1-Iniciante/12/2879.cpp
pedrospaulo/01-C-
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
[ "MIT" ]
null
null
null
#include <stdio.h> int main(){ int n, t ; int cont = 0; scanf("%d", &n); for(int i = 0; i < n; i++){ scanf("%d", &t); if(t != 1){ cont++; } } printf("%d\n", cont); return 0; }
12.842105
31
0.348361
pedrospaulo
602cac59487adecd87d9608d2df3641c307f5c89
6,426
hpp
C++
include/codegen/include/UnityEngine/RemoteConfigSettingsHelper_Tag.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/RemoteConfigSettingsHelper_Tag.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/RemoteConfigSettingsHelper_Tag.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:39 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: System.Enum #include "System/Enum.hpp" // Including type: UnityEngine.RemoteConfigSettingsHelper #include "UnityEngine/RemoteConfigSettingsHelper.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Autogenerated type: UnityEngine.RemoteConfigSettingsHelper/Tag struct RemoteConfigSettingsHelper::Tag : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUnknown static constexpr const int kUnknown = 0; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUnknown static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kUnknown(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUnknown static void _set_kUnknown(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kIntVal static constexpr const int kIntVal = 1; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kIntVal static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kIntVal(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kIntVal static void _set_kIntVal(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kInt64Val static constexpr const int kInt64Val = 2; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kInt64Val static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kInt64Val(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kInt64Val static void _set_kInt64Val(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUInt64Val static constexpr const int kUInt64Val = 3; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUInt64Val static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kUInt64Val(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUInt64Val static void _set_kUInt64Val(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kDoubleVal static constexpr const int kDoubleVal = 4; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kDoubleVal static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kDoubleVal(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kDoubleVal static void _set_kDoubleVal(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kBoolVal static constexpr const int kBoolVal = 5; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kBoolVal static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kBoolVal(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kBoolVal static void _set_kBoolVal(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kStringVal static constexpr const int kStringVal = 6; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kStringVal static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kStringVal(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kStringVal static void _set_kStringVal(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kArrayVal static constexpr const int kArrayVal = 7; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kArrayVal static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kArrayVal(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kArrayVal static void _set_kArrayVal(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMixedArrayVal static constexpr const int kMixedArrayVal = 8; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMixedArrayVal static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kMixedArrayVal(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMixedArrayVal static void _set_kMixedArrayVal(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMapVal static constexpr const int kMapVal = 9; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMapVal static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kMapVal(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMapVal static void _set_kMapVal(UnityEngine::RemoteConfigSettingsHelper::Tag value); // static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMaxTags static constexpr const int kMaxTags = 10; // Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMaxTags static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kMaxTags(); // Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMaxTags static void _set_kMaxTags(UnityEngine::RemoteConfigSettingsHelper::Tag value); // Creating value type constructor for type: Tag Tag(int value_ = {}) : value{value_} {} }; // UnityEngine.RemoteConfigSettingsHelper/Tag } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::RemoteConfigSettingsHelper::Tag, "UnityEngine", "RemoteConfigSettingsHelper/Tag"); #pragma pack(pop)
67.642105
118
0.791161
Futuremappermydud
602e62a0db31d1a5f427d0dd51730f3182861d4b
1,763
cpp
C++
tests/test-lru.cpp
lcapaldo/c-server-sdk
87edbe872b5f5fa6e797a6e26e89faf941958679
[ "Apache-2.0" ]
5
2019-10-08T05:05:40.000Z
2022-03-23T10:46:27.000Z
tests/test-lru.cpp
lcapaldo/c-server-sdk
87edbe872b5f5fa6e797a6e26e89faf941958679
[ "Apache-2.0" ]
8
2020-01-18T02:16:27.000Z
2022-02-23T21:28:07.000Z
tests/test-lru.cpp
lcapaldo/c-server-sdk
87edbe872b5f5fa6e797a6e26e89faf941958679
[ "Apache-2.0" ]
6
2019-12-13T21:00:11.000Z
2021-06-09T09:55:13.000Z
#include "gtest/gtest.h" #include "commonfixture.h" extern "C" { #include <launchdarkly/api.h> #include "lru.h" #include "utility.h" } // Inherit from the CommonFixture to give a reasonable name for the test output. // Any custom setup and teardown would happen in this derived class. class LRUFixture : public CommonFixture { }; TEST_F(LRUFixture, InsertExisting) { struct LDLRU *lru; ASSERT_TRUE(lru = LDLRUInit(10)); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "abc")); ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "abc")); LDLRUFree(lru); } TEST_F(LRUFixture, MaxCapacity) { struct LDLRU *lru; ASSERT_TRUE(lru = LDLRUInit(2)); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123")); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "456")); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "789")); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123")); ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "789")); LDLRUFree(lru); } TEST_F(LRUFixture, AccessBumpsPosition) { struct LDLRU *lru; ASSERT_TRUE(lru = LDLRUInit(3)); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123")); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "456")); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "789")); ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "123")); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "ABC")); ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "123")); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "456")); LDLRUFree(lru); } TEST_F(LRUFixture, ZeroCapacityAlwaysNew) { struct LDLRU *lru; ASSERT_TRUE(lru = LDLRUInit(0)); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123")); ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123")); LDLRUFree(lru); }
26.313433
80
0.708452
lcapaldo
603035979813b2c6fa11457dbafc6893d44c09fc
13,092
cpp
C++
src/muz/transforms/dl_mk_quantifier_abstraction.cpp
akreuzer/z3
e8917a1a9f97db86bdc38c569ddbde7f79b76ce7
[ "MIT" ]
3
2020-07-15T19:50:12.000Z
2020-12-13T17:28:16.000Z
src/muz/transforms/dl_mk_quantifier_abstraction.cpp
akreuzer/z3
e8917a1a9f97db86bdc38c569ddbde7f79b76ce7
[ "MIT" ]
null
null
null
src/muz/transforms/dl_mk_quantifier_abstraction.cpp
akreuzer/z3
e8917a1a9f97db86bdc38c569ddbde7f79b76ce7
[ "MIT" ]
3
2020-04-12T11:00:44.000Z
2021-10-20T22:08:44.000Z
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: dl_mk_quantifier_abstraction.cpp Abstract: Create quantified Horn clauses from benchmarks with arrays. Author: Ken McMillan Andrey Rybalchenko Nikolaj Bjorner (nbjorner) 2013-04-02 Revision History: --*/ #include "muz/transforms/dl_mk_quantifier_abstraction.h" #include "muz/base/dl_context.h" #include "ast/rewriter/expr_safe_replace.h" #include "ast/expr_abstract.h" namespace datalog { // model converter: // Given model for P^(x, y, i, a[i]) // create model: P(x,y,a) == forall i . P^(x,y,i,a[i]) // requires substitution and list of bound variables. class mk_quantifier_abstraction::qa_model_converter : public model_converter { ast_manager& m; func_decl_ref_vector m_old_funcs; func_decl_ref_vector m_new_funcs; vector<expr_ref_vector> m_subst; vector<sort_ref_vector> m_sorts; vector<bool_vector > m_bound; public: qa_model_converter(ast_manager& m): m(m), m_old_funcs(m), m_new_funcs(m) {} ~qa_model_converter() override {} model_converter * translate(ast_translation & translator) override { return alloc(qa_model_converter, m); } void display(std::ostream& out) override { display_add(out, m); } void get_units(obj_map<expr, bool>& units) override { units.reset(); } void insert(func_decl* old_p, func_decl* new_p, expr_ref_vector& sub, sort_ref_vector& sorts, bool_vector const& bound) { m_old_funcs.push_back(old_p); m_new_funcs.push_back(new_p); m_subst.push_back(sub); m_bound.push_back(bound); m_sorts.push_back(sorts); } void operator()(model_ref & old_model) override { model_ref new_model = alloc(model, m); for (unsigned i = 0; i < m_new_funcs.size(); ++i) { func_decl* p = m_new_funcs.get(i); func_decl* q = m_old_funcs.get(i); expr_ref_vector const& sub = m_subst[i]; sort_ref_vector const& sorts = m_sorts[i]; bool_vector const& is_bound = m_bound[i]; func_interp* f = old_model->get_func_interp(p); expr_ref body(m); SASSERT(0 < p->get_arity()); if (f) { body = f->get_interp(); SASSERT(!f->is_partial()); SASSERT(body); } else { expr_ref_vector args(m); for (unsigned i = 0; i < p->get_arity(); ++i) { args.push_back(m.mk_var(i, p->get_domain(i))); } body = m.mk_app(p, args); } // Create quantifier wrapper around body. TRACE("dl", tout << body << "\n";); // 1. replace variables by the compound terms from // the original predicate. expr_safe_replace rep(m); for (unsigned i = 0; i < sub.size(); ++i) { rep.insert(m.mk_var(i, sub[i]->get_sort()), sub[i]); } rep(body); rep.reset(); TRACE("dl", tout << body << "\n";); // 2. replace bound variables by constants. expr_ref_vector consts(m), bound(m), _free(m); svector<symbol> names; ptr_vector<sort> bound_sorts; for (unsigned i = 0; i < sorts.size(); ++i) { sort* s = sorts[i]; consts.push_back(m.mk_fresh_const("C", s)); rep.insert(m.mk_var(i, s), consts.back()); if (is_bound[i]) { bound.push_back(consts.back()); names.push_back(symbol(i)); bound_sorts.push_back(s); } else { _free.push_back(consts.back()); } } rep(body); rep.reset(); TRACE("dl", tout << body << "\n";); // 3. abstract and quantify those variables that should be bound. body = expr_abstract(bound, body); body = m.mk_forall(names.size(), bound_sorts.c_ptr(), names.c_ptr(), body); TRACE("dl", tout << body << "\n";); // 4. replace remaining constants by variables. unsigned j = 0; for (expr* f : _free) { rep.insert(f, m.mk_var(j++, f->get_sort())); } rep(body); new_model->register_decl(q, body); TRACE("dl", tout << body << "\n";); } old_model = new_model; } }; mk_quantifier_abstraction::mk_quantifier_abstraction( context & ctx, unsigned priority): plugin(priority), m(ctx.get_manager()), m_ctx(ctx), a(m), m_refs(m), m_mc(nullptr) { } mk_quantifier_abstraction::~mk_quantifier_abstraction() { } func_decl* mk_quantifier_abstraction::declare_pred(rule_set const& rules, rule_set& dst, func_decl* old_p) { if (rules.is_output_predicate(old_p)) { dst.inherit_predicate(rules, old_p, old_p); return nullptr; } unsigned sz = old_p->get_arity(); unsigned num_arrays = 0; for (unsigned i = 0; i < sz; ++i) { if (a.is_array(old_p->get_domain(i))) { num_arrays++; } } if (num_arrays == 0) { return nullptr; } func_decl* new_p = nullptr; if (!m_old2new.find(old_p, new_p)) { expr_ref_vector sub(m), vars(m); bool_vector bound; sort_ref_vector domain(m), sorts(m); expr_ref arg(m); for (unsigned i = 0; i < sz; ++i) { sort* s0 = old_p->get_domain(i); unsigned lookahead = 0; sort* s = s0; while (a.is_array(s)) { lookahead += get_array_arity(s); s = get_array_range(s); } arg = m.mk_var(bound.size() + lookahead, s0); s = s0; while (a.is_array(s)) { unsigned arity = get_array_arity(s); expr_ref_vector args(m); for (unsigned j = 0; j < arity; ++j) { sort* s1 = get_array_domain(s, j); domain.push_back(s1); args.push_back(m.mk_var(bound.size(), s1)); bound.push_back(true); sorts.push_back(s1); } arg = mk_select(arg, args.size(), args.c_ptr()); s = get_array_range(s); } domain.push_back(s); bound.push_back(false); sub.push_back(arg); sorts.push_back(s0); } SASSERT(old_p->get_range() == m.mk_bool_sort()); new_p = m.mk_func_decl(old_p->get_name(), domain.size(), domain.c_ptr(), old_p->get_range()); m_refs.push_back(new_p); m_ctx.register_predicate(new_p, false); if (m_mc) { m_mc->insert(old_p, new_p, sub, sorts, bound); } m_old2new.insert(old_p, new_p); } return new_p; } app_ref mk_quantifier_abstraction::mk_head(rule_set const& rules, rule_set& dst, app* p, unsigned idx) { func_decl* new_p = declare_pred(rules, dst, p->get_decl()); if (!new_p) { return app_ref(p, m); } expr_ref_vector args(m); expr_ref arg(m); unsigned sz = p->get_num_args(); for (unsigned i = 0; i < sz; ++i) { arg = p->get_arg(i); sort* s = arg->get_sort(); while (a.is_array(s)) { unsigned arity = get_array_arity(s); for (unsigned j = 0; j < arity; ++j) { args.push_back(m.mk_var(idx++, get_array_domain(s, j))); } arg = mk_select(arg, arity, args.c_ptr()+args.size()-arity); s = get_array_range(s); } args.push_back(arg); } TRACE("dl", tout << mk_pp(new_p, m) << "\n"; for (unsigned i = 0; i < args.size(); ++i) { tout << mk_pp(args[i].get(), m) << "\n"; }); return app_ref(m.mk_app(new_p, args.size(), args.c_ptr()), m); } app_ref mk_quantifier_abstraction::mk_tail(rule_set const& rules, rule_set& dst, app* p) { func_decl* old_p = p->get_decl(); func_decl* new_p = declare_pred(rules, dst, old_p); if (!new_p) { return app_ref(p, m); } SASSERT(new_p->get_arity() > old_p->get_arity()); unsigned num_extra_args = new_p->get_arity() - old_p->get_arity(); var_shifter shift(m); expr_ref p_shifted(m); shift(p, num_extra_args, p_shifted); app* ps = to_app(p_shifted); expr_ref_vector args(m); app_ref_vector pats(m); sort_ref_vector vars(m); svector<symbol> names; expr_ref arg(m); unsigned idx = 0; unsigned sz = p->get_num_args(); for (unsigned i = 0; i < sz; ++i) { arg = ps->get_arg(i); sort* s = arg->get_sort(); bool is_pattern = false; while (a.is_array(s)) { is_pattern = true; unsigned arity = get_array_arity(s); for (unsigned j = 0; j < arity; ++j) { vars.push_back(get_array_domain(s, j)); names.push_back(symbol(idx)); args.push_back(m.mk_var(idx++, vars.back())); } arg = mk_select(arg, arity, args.c_ptr()+args.size()-arity); s = get_array_range(s); } if (is_pattern) { pats.push_back(to_app(arg)); } args.push_back(arg); } expr* pat = nullptr; expr_ref pattern(m); pattern = m.mk_pattern(pats.size(), pats.c_ptr()); pat = pattern.get(); app_ref result(m); symbol qid, skid; result = m.mk_app(new_p, args.size(), args.c_ptr()); result = m.mk_eq(m.mk_forall(vars.size(), vars.c_ptr(), names.c_ptr(), result, 1, qid, skid, 1, &pat), m.mk_true()); return result; } expr * mk_quantifier_abstraction::mk_select(expr* arg, unsigned num_args, expr* const* args) { ptr_vector<expr> args2; args2.push_back(arg); args2.append(num_args, args); return a.mk_select(args2.size(), args2.c_ptr()); } rule_set * mk_quantifier_abstraction::operator()(rule_set const & source) { if (!m_ctx.quantify_arrays()) { return nullptr; } unsigned sz = source.get_num_rules(); for (unsigned i = 0; i < sz; ++i) { rule& r = *source.get_rule(i); if (r.has_negation()) { return nullptr; } } m_refs.reset(); m_old2new.reset(); m_new2old.reset(); rule_manager& rm = source.get_rule_manager(); rule_ref new_rule(rm); expr_ref_vector tail(m); app_ref head(m); expr_ref fml(m); rule_counter& vc = rm.get_counter(); if (m_ctx.get_model_converter()) { m_mc = alloc(qa_model_converter, m); } scoped_ptr<rule_set> result = alloc(rule_set, m_ctx); for (unsigned i = 0; i < sz; ++i) { tail.reset(); rule & r = *source.get_rule(i); TRACE("dl", r.display(m_ctx, tout); ); unsigned cnt = vc.get_max_rule_var(r)+1; unsigned utsz = r.get_uninterpreted_tail_size(); unsigned tsz = r.get_tail_size(); for (unsigned j = 0; j < utsz; ++j) { tail.push_back(mk_tail(source, *result, r.get_tail(j))); } for (unsigned j = utsz; j < tsz; ++j) { tail.push_back(r.get_tail(j)); } head = mk_head(source, *result, r.get_head(), cnt); fml = m.mk_implies(m.mk_and(tail.size(), tail.c_ptr()), head); proof_ref pr(m); rm.mk_rule(fml, pr, *result, r.name()); TRACE("dl", result->last()->display(m_ctx, tout);); } // proof converter: proofs are not necessarily preserved using this transformation. if (m_old2new.empty()) { dealloc(m_mc); result = nullptr; } else { m_ctx.add_model_converter(m_mc); } m_mc = nullptr; return result.detach(); } };
35.383784
129
0.498396
akreuzer
603b990e12f490d760778268ff031a8f3583032e
3,012
cpp
C++
ovPCRE.cpp
theloox/ovSTR
f1fddb6a6e0e3761c770ab604728f7e7f8805466
[ "MIT" ]
null
null
null
ovPCRE.cpp
theloox/ovSTR
f1fddb6a6e0e3761c770ab604728f7e7f8805466
[ "MIT" ]
null
null
null
ovPCRE.cpp
theloox/ovSTR
f1fddb6a6e0e3761c770ab604728f7e7f8805466
[ "MIT" ]
null
null
null
/*************************************************************************** * 2005 by Axel Gonzalez * * [email protected] * * * * This software is in the public domain. Permission to use, copy, * * modify, and distribute this software and its documentation for any * * purpose and without fee is hereby granted, without any conditions or * * restrictions. This software is provided "as is" without express or * * implied warranty. * * * ***************************************************************************/ #include "ovPCRE.h" ovPCRE::ovPCRE() { pattern = "*"; flags = 0; options = 0; error = NULL; erroffset = 0; re = NULL; re = pcre_compile(pattern, flags, &error, &erroffset, NULL); } ovPCRE::ovPCRE(ovStr p) { pattern = p; flags = 0; options = 0; error = NULL; erroffset = 0; re = NULL; re = pcre_compile(pattern, flags, &error, &erroffset, NULL); } ovPCRE::ovPCRE(ovStr p, int f) { pattern = p; flags = PCRE_CASELESS; options = 0; error = NULL; erroffset = 0; re = NULL; re = pcre_compile(pattern, flags, &error, &erroffset, NULL); } ovPCRE::~ovPCRE() { if (re != NULL) pcre_free(re); } void ovPCRE::SetPattern(ovStr p) { pattern = p; flags = 0; if (re != NULL) pcre_free(re); re = pcre_compile(pattern, flags, &error, &erroffset, NULL); } int ovPCRE::GetOptions() { return(this->flags); } void ovPCRE::SetOptions(int f) { this->flags = f; } int ovPCRE::Match(ovStr subject) { int rc; if (re == NULL) return(0); rc = pcre_exec(re, NULL, subject, subject.Len(), 0, this->options, ovector, MAX_VECTORS); if (rc < 0) return(0); return(ovector[0] + 1); } int ovPCRE::MatchAll(ovStr subject, ovStrArray &matches, unsigned int index) { int i; int count, rc; int offset; const char **listptr; ovStr str; i = 0; offset = 0; if (index < 0) index = 0; matches.Clean(); while ((count = pcre_exec(re, NULL, subject, subject.Len(), offset, options, ovector, MAX_VECTORS)) > 0) { rc = pcre_get_substring_list(subject, ovector, count, &listptr); if (rc < 0) return(0); str = listptr[0]; offset = subject.strpos(str, offset) + str.Len(); str = listptr[index < count ? index : (count - 1)]; matches.Add(str); pcre_free_substring_list(listptr); i++; } //printf("COunt: %d\n", count); return(i); } ovStr ovPCRE::Replace() { } ovStr ovPCRE::Error() { if (error == NULL) return(""); else return(error); }
17.928571
110
0.479748
theloox
603fe78538b1cd7b86abaaf5c7c1d79049fa445a
5,710
cpp
C++
Tests/support/matrix_support.cpp
Freddan-67/V3DLib
dcefc24a9a399ee1f5d1aa5529f44d9fd2486929
[ "MIT" ]
44
2021-01-16T14:17:15.000Z
2022-03-11T19:53:59.000Z
Tests/support/matrix_support.cpp
RcCreeperTech/V3DLib
38eb8d55b8276de5cf703d8e13fb9b5f220c49f0
[ "MIT" ]
8
2021-01-16T17:52:02.000Z
2021-12-18T22:38:00.000Z
Tests/support/matrix_support.cpp
RcCreeperTech/V3DLib
38eb8d55b8276de5cf703d8e13fb9b5f220c49f0
[ "MIT" ]
7
2021-01-16T14:25:47.000Z
2022-02-03T16:34:45.000Z
#include "matrix_support.h" #include "../doctest.h" #include "Support/Helpers.h" // random_float() using namespace V3DLib; void compare_arrays(Float::Array2D &a, float const *b, float precision) { // Values empirically determined - the bigger the matrices, the less precise if (precision == -1.0f) { if (Platform::has_vc4()) { precision = 1.0e-3f; } else { precision = 2.5e-4f; // This value works for 640x640 matrices } } float max_diff = -1; for (int r = 0; r < a.rows(); r++) { for (int c = 0; c < a.columns(); c++) { float diff = abs(a[r][c] - b[r*a.columns() + c]); if (max_diff == -1 || max_diff < diff) { max_diff = diff; } } } INFO("Max diff: " << max_diff << ", precision: " << precision); for (int r = 0; r < a.rows(); r++) { for (int c = 0; c < a.columns(); c++) { INFO("r: " << r << ", c: " << c); //INFO("Result: " << a.dump()); INFO("result: " << a[r][c] << ", expected: " << b[r*a.columns() + c]); REQUIRE(abs(a[r][c] - b[r*a.columns() + c]) < precision); } } } /** * This is better than: * * REQUIRE(m1.result() == m2.result()); * * ....which has been known to fail incorrectly. */ void compare_arrays(Float::Array2D &a, Float::Array2D &b, float precision) { REQUIRE(a.rows() == b.rows()); REQUIRE(a.columns() == b.columns()); if ( precision == -1.0f) { //precision = 1.0e-4f; // for high precision sin/cos in kernels precision = 4.1e-1f; // for low precision sin/cos in vc4 kernels (yeah, it sucks) } for (int r = 0; r < a.rows(); ++r) { for (int c = 0; c < a.columns(); ++c) { INFO("(r, c): ( " << r << ", " << c << ")"); INFO(a[r][c] << " == " << b[r][c]); // <= for dealing with precision 0.0f REQUIRE(abs(a[r][c] - b[r][c]) <= precision); REQUIRE(abs(a[r][c] - b[r][c]) <= precision); } } } void compare_arrays(Complex::Array2D &a, Complex::Array2D &b, float precision) { REQUIRE(a.rows() == b.rows()); REQUIRE(a.columns() == b.columns()); if ( precision == -1.0f) { //precision = 1.0e-4f; // for high precision sin/cos in kernels precision = 4.0e-1f; // for low precision sin/cos in kernels } float max_diff_re = -1; float max_diff_im = -1; for (int r = 0; r < a.rows(); r++) { for (int c = 0; c < a.columns(); c++) { float diff_re = abs(a[r][c].re() - b[r][c].re()); if (max_diff_re == -1 || max_diff_re < diff_re) { max_diff_re = diff_re; } float diff_im = abs(a[r][c].im() - b[r][c].im()); if (max_diff_im == -1 || max_diff_im < diff_im) { max_diff_im = diff_im; } } } // Do an overall check if (max_diff_re <= precision && max_diff_im <= precision) { return; // All is well } INFO("Max diff re: " << max_diff_re << ", max diff im: " << max_diff_im << ", precision: " << precision); // Do a specific check to find the (r,c) coordinate where it goes wrong for (int r = 0; r < a.rows(); ++r) { for (int c = 0; c < a.columns(); ++c) { INFO("(r, c): ( " << r << ", " << c << ")"); INFO(a[r][c].dump() << " == " << b[r][c].dump()); // <= for dealing with precision 0.0f // REQUIRE(abs(a[r][c].magnitude() - b[r][c].magnitude()) <= precision); REQUIRE(abs(a[r][c].re() - b[r][c].re()) <= precision); REQUIRE(abs(a[r][c].im() - b[r][c].im()) <= precision); } } } void compare_arrays(std::vector<float> &a, float const *b) { float precision = 1e-4f; for (int r = 0; r < (int) a.size(); ++r) { REQUIRE(abs(a[r] - b[r]) < precision); } } void check_unitary(std::vector<float> &a, int dim) { for (int r = 0; r < dim; r++) { for (int c = 0; c < dim; c++) { INFO("rows: " << dim << ", (r,c): (" << r << ", " << c << ")"); int offset = r*dim + c; if (r == c) { REQUIRE(a[offset] == 1.0f); } else { REQUIRE(a[offset] == 0.0f); } } } } void check_unitary(Float::Array2D &a) { REQUIRE(a.rows() == a.columns()); for (int r = 0; r < a.rows(); r++) { for (int c = 0; c < a.columns(); c++) { INFO("rows: " << a.rows() << ", (r,c): (" << r << ", " << c << ")"); if (r == c) { REQUIRE(a[r][c] == 1.0f); } else { REQUIRE(a[r][c] == 0.0f); } } } } void fill_random(float *arr, int size) { for (int n = 0; n < size; n++) { arr[n] = random_float(); } } void fill_random(std::vector<float> &arr) { assert(!arr.empty()); fill_random(arr.data(), (int) arr.size()); } /** * Pre: dst properly initialized, matches with src */ void copy_array(Float::Array2D &dst, float const *src) { for (int r = 0; r < dst.rows(); r++) { for (int c = 0; c < dst.columns(); c++) { dst[r][c] = src[r*dst.columns() + c]; } } } void copy_array(Float::Array2D &dst, std::vector<float> const &src) { assert(!src.empty()); assert((int) src.size() == dst.rows()*dst.columns()); copy_array(dst, src.data()); } void copy_transposed(float *dst, float const *src, int rows, int columns) { for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { dst[c*rows + r] = src[r*columns + c]; } } } void copy_transposed(std::vector<float> &dst, std::vector<float> const &src, int rows, int columns) { copy_transposed(dst.data(), src.data(), rows, columns); } void compare_array_scalar(Float::Array2D &arr, float scalar) { for (int r = 0; r < arr.rows(); ++r) { for (int c = 0; c < arr.columns(); ++c) { INFO("r: " << r << ", c: " << c); INFO("result: " << arr[r][c] << ", expected: " << scalar); REQUIRE(arr[r][c] == scalar); } } }
26.073059
101
0.509282
Freddan-67
6041e1f3f7b63e83347fb38d839271d52df36c2a
8,928
cpp
C++
inference-engine/src/mkldnn_plugin/cpu_blocked_memory_desc.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
1
2021-03-16T17:40:26.000Z
2021-03-16T17:40:26.000Z
inference-engine/src/mkldnn_plugin/cpu_blocked_memory_desc.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
42
2020-11-23T08:09:57.000Z
2022-02-21T13:03:34.000Z
inference-engine/src/mkldnn_plugin/cpu_blocked_memory_desc.cpp
v-Golubev/openvino
26936d1fbb025c503ee43fe74593ee9d7862ab15
[ "Apache-2.0" ]
4
2021-04-02T08:48:38.000Z
2021-07-01T06:59:02.000Z
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "cpu_blocked_memory_desc.h" #include "mkldnn_memory.h" #include "utils/cpu_utils.hpp" using namespace MKLDNNPlugin; BlockedMemoryDesc::BlockedMemoryDesc(InferenceEngine::Precision prc, const std::vector<size_t>& dims) : MemoryDesc(dims, Blocked) , precision(prc) { order.resize(dims.size()); std::iota(order.begin(), order.end(), 0); blockedDims = dims; offsetPadding = 0; offsetPaddingToData.resize(dims.size(), 0); strides.resize(order.size()); strides[strides.size() - 1] = 1; for (size_t i = 2; i <= order.size(); i++) { strides[strides.size() - i] = strides[strides.size() - (i - 1)] * blockedDims[blockedDims.size() - (i - 1)]; } } BlockedMemoryDesc::BlockedMemoryDesc(InferenceEngine::Precision prc, const std::vector<size_t>& dims, const std::vector<size_t>& blockedDims, const std::vector<size_t>& order, size_t offsetPadding, const std::vector<size_t>& offsetPaddingToData, const std::vector<size_t>& strides) : MemoryDesc(dims, Blocked), precision(prc) { if (std::any_of(order.begin(), order.end(), [](size_t val) { return val == Shape::UNDEFINED_DIM; })) { IE_THROW() << "BlockedMemoryDesc do not support undefined order."; } if (std::any_of(blockedDims.begin() + dims.size(), blockedDims.end(), [](size_t val) { return val == Shape::UNDEFINED_DIM; })) { IE_THROW() << "BlockedMemoryDesc doesn't support undefined blockedDims."; } this->order = order; this->blockedDims = blockedDims; this->offsetPadding = offsetPadding; if (offsetPaddingToData.empty() && !order.empty()) { this->offsetPaddingToData.resize(order.size()); this->offsetPaddingToData[order.size() - 1] = 0; for (size_t i = 2; i <= order.size(); i++) { this->offsetPaddingToData[order.size() - i] = 0; } } else { this->offsetPaddingToData = offsetPaddingToData; } if (strides.empty() && !order.empty()) { if (std::any_of(this->blockedDims.begin(), this->blockedDims.end(), [](size_t val) { return val == Shape::UNDEFINED_DIM; })) { this->strides.resize(order.size(), Shape::UNDEFINED_DIM); } else { this->strides.resize(order.size()); this->strides[order.size() - 1] = 1; for (size_t i = 2; i <= order.size(); i++) { this->strides[order.size() - i] = this->strides[order.size() - (i - 1)] * this->blockedDims[blockedDims.size() - (i - 1)]; } } } else { this->strides = strides; } if (!everyone_is(this->order.size(), this->blockedDims.size(), this->offsetPaddingToData.size(), this->strides.size())) { IE_THROW() << "Order, blocked dims, offset padding to data and strides must have equals size"; } } bool BlockedMemoryDesc::isDefined() const { bool defined = true; defined = defined && std::none_of(blockedDims.cbegin(), blockedDims.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; }); defined = defined && std::none_of(strides.cbegin(), strides.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; }); defined = defined && std::none_of(order.cbegin(), order.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; }); defined = defined && std::none_of(offsetPaddingToData.cbegin(), offsetPaddingToData.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; }); defined = defined && offsetPadding != Shape::UNDEFINED_DIM; return defined; } bool BlockedMemoryDesc::isCompatible(const MemoryDesc& rhs) const { const MemoryDesc* pRhs = &rhs; if (auto blockingDesc = dynamic_cast<const BlockedMemoryDesc*>(pRhs)) { return isCompatible(*blockingDesc); } else if (auto mkldnnDesc = dynamic_cast<const MKLDNNMemoryDesc*>(pRhs)) { return mkldnnDesc->isCompatible(*this); } else { return false; } } bool BlockedMemoryDesc::isCompatible(const BlockedMemoryDesc& rhs) const { if (this->getShape() != rhs.getShape() || this->getPrecision() != rhs.getPrecision()) return false; if (!dimsEqualWeak(this->getBlockDims(), rhs.getBlockDims())) { return false; } if (!dimsEqualWeak(this->getOffsetPaddingToData(), rhs.getOffsetPaddingToData())) { return false; } // this check needed to avoid inserting unnecessary reorders if the memory is used in place and the batch size is equal to 1 size_t skipAxis = this->getShape().getRank() > 0 && this->getShape().getDims().front() == 1 ? 0 : Shape::UNDEFINED_DIM; //ignore batch axis if batch size == 1 if (!dimsEqualWeak(this->getStrides(), rhs.getStrides(), skipAxis)) { return false; } if (!dimsEqualWeak(this->getOrder(), rhs.getOrder())) { return false; } return dimsEqualWeak(this->getOffsetPadding(), rhs.getOffsetPadding()); } bool BlockedMemoryDesc::isCompatible(const MKLDNNMemoryDesc& rhs) const { return rhs.isCompatible(*this); } size_t BlockedMemoryDesc::getMemSizeImp() const { int64_t e_size = getOffsetPadding() + 1; // size in bytes (from begin of data to last element) for (int j = 0; j < getBlockDims().size(); j++) e_size += (getBlockDims()[j] - 1) * getStrides()[j]; e_size *= getPrecision() == InferenceEngine::Precision::BIN ? 1 : getPrecision().size(); return e_size; } size_t BlockedMemoryDesc::getOffset(const InferenceEngine::SizeVector& v) const { InferenceEngine::SizeVector off_v = v; size_t n_blocked_dims = order.size(); if (blockedDims.size() != n_blocked_dims || strides.size() != n_blocked_dims) { IE_THROW() << "Cannot calculate offset. Incorrect primitive descriptor!"; } InferenceEngine::SizeVector blockedShift(n_blocked_dims); for (size_t i = 1; i <= n_blocked_dims; i++) { blockedShift[n_blocked_dims - i] = off_v[order[n_blocked_dims - i]] % blockedDims[n_blocked_dims - i]; off_v[order[n_blocked_dims - i]] /= blockedDims[n_blocked_dims - i]; } size_t offset = getOffsetPadding(); for (size_t d = 0; d < n_blocked_dims; ++d) { const size_t p = blockedShift[d] + getOffsetPaddingToData()[d]; offset += p * strides[d]; } return offset; } size_t BlockedMemoryDesc::getElementOffset(size_t elemNumber) const { // TODO [DS]: rewrite to support dynamic shapes auto& dims = shape.getStaticDims(); size_t n_dims = dims.size(); InferenceEngine::SizeVector pos(n_dims); for (size_t rd = 1; rd <= n_dims; ++rd) { const size_t d = n_dims - rd; const size_t cur_dim = dims[d]; pos[d] = elemNumber % cur_dim; elemNumber /= cur_dim; } return getOffset(pos); } bool BlockedMemoryDesc::hasLayoutType(LayoutType layoutType) const { switch (layoutType) { case LayoutType::ncsp: return isPlainFormat(); case LayoutType::nspc: return isTailCFormat(); case LayoutType::nCsp8c: return isBlockedCFormat(8); case LayoutType::nCsp16c: return isBlockedCFormat(16); default: return false; } } bool BlockedMemoryDesc::isPlainFormat() const { if (shape.getRank() != order.size()) { return false; } for (size_t i = 0; i < order.size(); ++i) { if (order[i] != i) { return false; } } return true; } bool BlockedMemoryDesc::isBlockedCFormat(size_t blk_size) const { if ((order.size() - shape.getRank()) != 1) { return false; } for (size_t i = 0; i < order.size() - 1; ++i) { if (order[i] != i) { return false; } } if (order.back() != 1) { return false; } if (blockedDims.back() != blk_size) { return false; } return true; } bool BlockedMemoryDesc::isTailCFormat() const { if (shape.getRank() < 3) { return false; } if (shape.getRank() != order.size()) { return false; } if (!std::is_sorted(order.begin(), --order.end())) { return false; } if (order.back() != 1) { return false; } return true; } std::string BlockedMemoryDesc::serializeFormat() const { std::stringstream result; char startLetter = 'a'; std::unordered_map<size_t, size_t> mapAxisBlockSize; for (size_t i = shape.getRank(); i < order.size(); ++i) { mapAxisBlockSize.insert({order[i], blockedDims[i]}); } for (size_t i = 0; i < shape.getRank(); ++i) { char nextLetter = startLetter + order[i]; if (mapAxisBlockSize.count(i)) { nextLetter = toupper(nextLetter); } result << nextLetter; } for (auto& item : mapAxisBlockSize) { result << item.second << char(startLetter + item.first); } return result.str(); }
36
152
0.620408
uikilin100
60490e8223ed24a6d95cc69636b5a15321481d1b
1,940
cpp
C++
comm/sender_test.cpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
7
2019-04-09T16:25:49.000Z
2021-12-07T10:29:52.000Z
comm/sender_test.cpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
null
null
null
comm/sender_test.cpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
4
2019-08-07T07:43:27.000Z
2021-05-21T07:54:14.000Z
#include "glog/logging.h" #include "gtest/gtest.h" #include "comm/sender.hpp" #include <iostream> #include <vector> namespace minips { namespace { class TestSender : public testing::Test { public: TestSender() {} ~TestSender() {} protected: void SetUp() {} void TearDown() {} }; class FakeMailbox : public AbstractMailbox { public: virtual int Send(const Message &msg) override { to_send_.Push(msg); return -1; } void WaitAndPop(Message *msg) { to_send_.WaitAndPop(msg); } private: ThreadsafeQueue<Message> to_send_; }; TEST_F(TestSender, StartStop) { FakeMailbox mailbox; Sender sender(&mailbox); sender.Start(); sender.Stop(); } TEST_F(TestSender, Send) { FakeMailbox mailbox; Sender sender(&mailbox); sender.Start(); auto *send_queue = sender.GetMessageQueue(); // Msg Message msg; msg.meta.sender = 123; msg.meta.recver = 0; msg.meta.model_id = 0; msg.meta.flag = Flag::kGet; third_party::SArray<Key> keys{1}; third_party::SArray<float> vals{0.1}; msg.AddData(keys); msg.AddData(vals); // Push the firstbmsg send_queue->Push(msg); Message res; mailbox.WaitAndPop(&res); EXPECT_EQ(res.meta.sender, msg.meta.sender); // Push the second msg msg.meta.sender = 543; send_queue->Push(msg); mailbox.WaitAndPop(&res); EXPECT_EQ(res.meta.sender, msg.meta.sender); sender.Stop(); } } // namespace } // namespace minips
24.25
59
0.495876
RickAi
604d76204206a3460fb5f812df71aad5d4412b2d
4,433
hpp
C++
NWNXLib/API/API/CNWSPlaceable.hpp
nwnstuff/unified
2da1201fdded07235f3d2809a3215315140d19da
[ "MIT" ]
null
null
null
NWNXLib/API/API/CNWSPlaceable.hpp
nwnstuff/unified
2da1201fdded07235f3d2809a3215315140d19da
[ "MIT" ]
null
null
null
NWNXLib/API/API/CNWSPlaceable.hpp
nwnstuff/unified
2da1201fdded07235f3d2809a3215315140d19da
[ "MIT" ]
null
null
null
#pragma once #include "nwn_api.hpp" #include "CExoString.hpp" #include "CExoLocString.hpp" #include "CExoArrayList.hpp" #include "Vector.hpp" #include "CResRef.hpp" #include "CNWSObject.hpp" #ifdef NWN_API_PROLOGUE NWN_API_PROLOGUE(CNWSPlaceable) #endif struct CNWSObjectActionNode; struct CResStruct; struct CNWSArea; struct CNWSItem; struct CItemRepository; struct CResGFF; typedef int BOOL; typedef uint32_t OBJECT_ID; struct CNWSPlaceable : CNWSObject { CExoLocString m_sLocName; CExoString m_sDisplayName; int32_t m_nUpdateDisplayNameSeq; uint16_t m_nAppearance; CExoLocString m_sDescription; CExoString m_sDescriptionOverride; int32_t m_nFactionId; CResRef m_cDialog; uint8_t m_nType; BOOL m_bGroundPile; OBJECT_ID m_oidSittingCreature; uint8_t m_nHardness; float m_fBearing; BOOL m_bLocked; CExoString m_sKeyName; CExoString m_sKeyRequiredFeedbackMessage; BOOL m_bKeyRequired; BOOL m_bAutoRemoveKey; uint8_t m_nOpenLockDC; uint8_t m_nCloseLockDC; OBJECT_ID m_oidTrapCreator; uint8_t m_nTrapDetectionDC; BOOL m_bTrapFlag; uint8_t m_nDisarmDC; BOOL m_bDisarmable; BOOL m_bDetectable; BOOL m_bOneShot; BOOL m_bRecoverable; BOOL m_bFlagged; uint8_t m_nBaseType; BOOL m_bTrapIsActive; int32_t m_nTrapFaction; CExoString m_sScripts[16]; uint8_t m_nFortSave; uint8_t m_nWillSave; uint8_t m_nReflexSave; CExoArrayList<OBJECT_ID> m_poidCreatures; BOOL m_bHasInventory; BOOL m_bUseable; BOOL m_bPickable; BOOL m_bLockable; BOOL m_bDieWhenEmpty; uint32_t m_nOpenCount; int32_t m_nStaticObjectPosition; OBJECT_ID m_oidLootCreature; BOOL m_bIsBodyBag; uint32_t m_nLastHeartbeatScriptCalendarDay; uint32_t m_nLastHeartbeatScriptTimeOfDay; OBJECT_ID m_oidLastOpened; OBJECT_ID m_oidLastClosed; OBJECT_ID m_oidLastUser; OBJECT_ID m_oidLastDefaultClickedBy; OBJECT_ID m_oidLastTriggered; OBJECT_ID m_oidLastDisarmed; OBJECT_ID m_oidLastLocked; OBJECT_ID m_oidLastUnlocked; CItemRepository * m_pcItemRepository; uint16_t m_nRepositoryArrayIndex; uint16_t m_nItemContainerArrayIndex; OBJECT_ID m_oidCurrentItemContainer; Vector m_pvActionPoints[2]; CResRef m_cTemplateResRef; CExoString m_szPortalInfo; uint32_t m_nEffectSpellId; BOOL m_bLightIsOn; BOOL m_bLightStateChange; uint8_t m_nBodyBag; BOOL m_bStaticObject; BOOL m_bNeverMakeIntoStaticObject; virtual CNWSPlaceable * AsNWSPlaceable(); CNWSPlaceable(OBJECT_ID oidId = 0x7f000000); ~CNWSPlaceable(); void AddToArea(CNWSArea * pArea, float fX, float fY, float fZ, BOOL bRunScripts = true); void RemoveFromArea(); void SetOrientation(Vector vOrientation); void AIUpdate(); void DoDamage(int32_t nDamage); void EventHandler(uint32_t nEventId, OBJECT_ID nCallerObjectId, void * pScript, uint32_t nCalendarDay, uint32_t nTimeOfDay); BOOL LoadPlaceable(CResGFF * pRes, CResStruct * cPlaceableStruct, CExoString * pTag = nullptr); BOOL LoadFromTemplate(CResRef cResRef, CExoString * pTag = nullptr); BOOL LoadBodyBag(uint16_t nAppearance); BOOL SavePlaceable(CResGFF * pRes, CResStruct * pStruct, BOOL bSaveOIDs); void PostProcess(); BOOL AcquireItem(CNWSItem * * pItem, OBJECT_ID oidPossessor = 0x7f000000, uint8_t x = 0xff, uint8_t y = 0xff, BOOL bDisplayFeedback = true); BOOL RemoveItem(CNWSItem * pItem, BOOL bSetPossessor = true); uint32_t AcquireItemsFromObject(OBJECT_ID oidObject, BOOL bAcquireDroppablesOnly = true); void OpenInventory(OBJECT_ID oidOpener); void CloseInventory(OBJECT_ID oidCloser, BOOL bUpdatePlayer = true); void DropItemsIntoArea(); Vector GetNearestActionPoint(const Vector & vPosition); BOOL AddCastSpellActions(uint32_t nSpellId, int32_t nMetaType, Vector vTargetLocation, OBJECT_ID oidTarget, BOOL bFake = false, uint8_t nProjectilePathType = 0); uint32_t AIActionCastSpell(CNWSObjectActionNode * pNode); BOOL GetLightIsOn(); void SetLightIsOn(BOOL b); uint16_t GetBodyBagAppearance(); uint32_t GetItemCount(BOOL bDroppableOnly = true); void ClosePlaceableForAllPlayers(); void CalculateActionPoints(); #ifdef NWN_CLASS_EXTENSION_CNWSPlaceable NWN_CLASS_EXTENSION_CNWSPlaceable #endif }; #ifdef NWN_API_EPILOGUE NWN_API_EPILOGUE(CNWSPlaceable) #endif
31.439716
165
0.765847
nwnstuff
604e5692484977e3ff4b257224d809d9f5e9acf6
197
cpp
C++
templates/== libraryName ==/src/library_main.cpp
julian-becker/slush-cmake-library
5511f2276853545b366a34bdda48885f6b2b956b
[ "MIT" ]
null
null
null
templates/== libraryName ==/src/library_main.cpp
julian-becker/slush-cmake-library
5511f2276853545b366a34bdda48885f6b2b956b
[ "MIT" ]
null
null
null
templates/== libraryName ==/src/library_main.cpp
julian-becker/slush-cmake-library
5511f2276853545b366a34bdda48885f6b2b956b
[ "MIT" ]
null
null
null
#include <<%= libraryName %>/export.h> #include <iostream> <%= LIBRARYNAME %>_API int <%= libraryName %>_api() { std::cout << "hello from <%= libraryName %>" << std::endl; return 12345; }
21.888889
62
0.598985
julian-becker
60537596a9774a77332ba1d40d430a02f2ebe5f8
1,573
cc
C++
Mu2eG4/src/Mu2eUniverse.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
null
null
null
Mu2eG4/src/Mu2eUniverse.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
Mu2eG4/src/Mu2eUniverse.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
// // Umbrela for the the Mu2e G4 world classes // // $Id: Mu2eUniverse.cc,v 1.2 2012/11/19 23:03:49 genser Exp $ // $Author: genser $ // $Date: 2012/11/19 23:03:49 $ // // Original author Rob Kutschke // // // C++ includes #include <iostream> #include <vector> #include <iomanip> // Framework includes #include "art/Framework/Services/Registry/ServiceHandle.h" #include "cetlib_except/exception.h" // Mu2e includes #include "G4Helper/inc/G4Helper.hh" #include "Mu2eG4/inc/Mu2eUniverse.hh" // G4 includes #include "G4PhysicalVolumeStore.hh" using namespace std; namespace mu2e { Mu2eUniverse::Mu2eUniverse(): _geom(*(art::ServiceHandle<GeometryService>())), _config(_geom.config()), _helper(&(*(art::ServiceHandle<G4Helper>()))) {} // beware of the order of initialization/declarations Mu2eUniverse::~Mu2eUniverse(){ } // Convert to base units for all of the items in the vector. void Mu2eUniverse::setUnits( vector<double>& V, G4double unit ){ for ( vector<double>::iterator b=V.begin(), e=V.end(); b!=e; ++b){ *b *= unit; } } // A helper function for debugging. Print a subset of the physical volume store. void Mu2eUniverse::printPhys() { G4PhysicalVolumeStore* pstore = G4PhysicalVolumeStore::GetInstance(); int n(0); for ( std::vector<G4VPhysicalVolume*>::const_iterator i=pstore->begin(); i!=pstore->end(); i++){ cout << "Physical Volume: " << setw(5) << n++ << (*i)->GetName() << endl; if ( n > 25 ) break; } } } // end namespace mu2e
24.578125
100
0.643357
bonventre
60568d7eeac972c43eb899da7ac15d571144af92
507
cc
C++
src/samplers/SamplerFattal/bimage/btest.cc
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
44
2018-01-09T19:56:29.000Z
2022-03-03T06:38:54.000Z
src/samplers/SamplerFattal/bimage/btest.cc
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
16
2018-01-29T18:01:42.000Z
2022-03-31T07:01:09.000Z
src/samplers/SamplerFattal/bimage/btest.cc
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
12
2018-03-14T00:24:14.000Z
2022-03-03T06:40:07.000Z
#include "bimage.hh" #include <math.h> #include <fstream> #include <stdlib.h> #include <iostream> using namespace std; int main(int argc, char* argv[]){ BImage image(257,256) ; image.clear(255,255,255) ; image.text(10,10,"abc ABC 123 @$%& ][{}.,:") ; // fghijklmnopquvwxyz") ; for(int i = 0 ; i < 16 ; i++) { for(int j = 2 ; j < 8 ; j++) cout << (char)(j*16+i) << "\t" ; cout << endl ; } image.writeImage("a.bmp") ; image.show() ; //image.close() ; return 0 ; }
16.354839
74
0.540434
FrancoisGaits
605757c835aa09d53b965180a09441a30458a1b2
12,800
cpp
C++
NOLF/ClientShellDLL/FolderWeapons.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
38
2019-09-16T14:46:42.000Z
2022-03-10T20:28:10.000Z
NOLF/ClientShellDLL/FolderWeapons.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
39
2019-08-12T01:35:33.000Z
2022-02-28T16:48:16.000Z
NOLF/ClientShellDLL/FolderWeapons.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
6
2019-09-17T12:49:18.000Z
2022-03-10T20:28:12.000Z
// FolderWeapons.cpp: implementation of the CFolderWeapons class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "FolderWeapons.h" #include "FolderCommands.h" #include "MissionData.h" #include "MissionMgr.h" #include "ClientRes.h" #include "InterfaceMgr.h" #include "GameClientShell.h" extern CGameClientShell* g_pGameClientShell; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CFolderWeapons::CFolderWeapons() { } CFolderWeapons::~CFolderWeapons() { } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::Build // // PURPOSE: Build the folder // // ----------------------------------------------------------------------- // LTBOOL CFolderWeapons::Build() { CreateTitle(IDS_TITLE_WEAPONS); LTBOOL success = CBaseSelectionFolder::Build(); return success; } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::IsAvailable // // PURPOSE: Check to see if there any selections to be made here // // ----------------------------------------------------------------------- // LTBOOL CFolderWeapons::IsAvailable() { int missionNum = g_pInterfaceMgr->GetMissionData()->GetMissionNum(); MISSION* pMission = g_pMissionMgr->GetMission(missionNum); return (pMission->nNumWeapons != 0); } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::OnFocus // // PURPOSE: Handle gaining or losing focus // // ----------------------------------------------------------------------- // void CFolderWeapons::OnFocus(LTBOOL bFocus) { if (bFocus) { UseBack(LTTRUE); SetContinue(); m_szModel[0] = '\0'; m_szSkin[0] = '\0'; BuildWeaponsList(); SetSelection(kNoSelection); } else { SetSelection(kNoSelection); SaveWeaponData(); ClearWeaponsList(); } CBaseSelectionFolder::OnFocus(bFocus); } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::BuildWeaponsList // // PURPOSE: Create the list of weapons // // ----------------------------------------------------------------------- // void CFolderWeapons::BuildWeaponsList() { //get info from MissionMgr CMissionData *pData = g_pInterfaceMgr->GetMissionData(); int missionNum = pData->GetMissionNum(); MISSION* pMission = g_pMissionMgr->GetMission(missionNum); CPlayerStats* pStats = g_pInterfaceMgr->GetPlayerStats(); m_nNumSlots = pMission->nNumWeapons; if (m_nNumSlots == -1 || m_nNumSlots > MAX_SELECTION_SLOTS) m_nNumSlots = MAX_SELECTION_SLOTS; //no choices allowed... don't go here if (m_nNumSlots <= 0) return; int nWID = WMGR_INVALID_ID; WEAPON* pWeapon = LTNULL; for (int i=0; i< pMission->nNumRequiredWeapons; i++) { nWID = pMission->aRequiredWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); AddToSlot(nWID,pWeapon->nNameId,LTTRUE); } for (i=0; i< pMission->nNumOneTimeWeapons; i++) { nWID = pMission->aOneTimeWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); AddToSlot(nWID,pWeapon->nNameId,LTTRUE); } int numCurrWeapons = pData->GetNumWeapons(); if (numCurrWeapons) { CWeaponData* currWeapons[255]; WEAPON* pWeapon = LTNULL; numCurrWeapons = pData->GetWeapons(currWeapons,255); for (i=0; i< numCurrWeapons; i++) { nWID = currWeapons[i]->m_nID; pWeapon = g_pWeaponMgr->GetWeapon(nWID); if (pWeapon && !pWeapon->IsAGadget()) AddToSlot(nWID,pWeapon->nNameId,LTFALSE); } } else { for (i=0; i< pMission->nNumDefaultWeapons; i++) { nWID = pMission->aDefaultWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); AddToSlot(nWID,pWeapon->nNameId,LTFALSE); } } for (i=0; i< pMission->nNumAllowedWeapons; i++) { nWID = pMission->aAllowedWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); AddItem(nWID,pWeapon->nNameId); } int numWeapons = g_pWeaponMgr->GetNumWeapons(); for (i=0; i < numWeapons; i++) { pWeapon = g_pWeaponMgr->GetWeapon(i); AMMO *pAmmo = g_pWeaponMgr->GetAmmo(pWeapon->nDefaultAmmoType); if (pStats->CanUseWeapon(i) && !pWeapon->IsAGadget() && pAmmo->eInstDamageType != DT_MELEE) { AddItem(i,pWeapon->nNameId); } } for (i=0; i< pMission->nNumDeniedWeapons; i++) { nWID = pMission->aDeniedWeapons[i]; RemoveFromSlot(nWID); RemoveItem(nWID); } int nNumSelectable = (int)m_controlArray.GetSize(); int nNumFree = m_nNumSlots - m_nSlotsFilled; if (nNumFree > nNumSelectable) { nNumFree = nNumSelectable; m_nNumSlots = m_nSlotsFilled + nNumFree; while (m_controlArray.GetSize()) { nNumFree--; CLTGUICtrl *pCtrl = GetControl(0); if (pCtrl) { int nWID = pCtrl->GetParam1(); WEAPON* pWeapon = g_pWeaponMgr->GetWeapon(nWID); ItemToSlot(nWID,pWeapon->nNameId); } } } for (i=0;i < nNumFree;i++) { AddEmptySlot(); } return; } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::UpdateSelection // // PURPOSE: Show info based on current selection // // ----------------------------------------------------------------------- // LTBOOL CFolderWeapons::UpdateSelection() { LTBOOL bChanged = CBaseSelectionFolder::UpdateSelection(); if (bChanged) { CLTGUICtrl *pCtrl = GetControl(m_nLastListItem); int weaponId = pCtrl->GetParam1(); WEAPON* pWeapon = g_pWeaponMgr->GetWeapon(weaponId); if (pWeapon) { m_pName->RemoveAll(); m_pName->AddString(pWeapon->nNameId); m_pDescription->SetString(pWeapon->nDescriptionId); SAFE_STRCPY(m_szModel, pWeapon->szInterfaceModel); SAFE_STRCPY(m_szSkin, pWeapon->szInterfaceSkin); VEC_COPY(m_vOffset, pWeapon->vInterfaceOffset); m_fScale = pWeapon->fInterfaceScale; CreateModelSFX(); } } return bChanged; } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::ClearWeaponsList // // PURPOSE: Remove all of the controls // // ----------------------------------------------------------------------- // void CFolderWeapons::ClearWeaponsList() { // Terminate the ctrls RemoveFree(); ClearSlots(); ClearSelection(); } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::SaveWeaponData // // PURPOSE: Save the players selections // // ----------------------------------------------------------------------- // void CFolderWeapons::SaveWeaponData() { CMissionData *pData = g_pInterfaceMgr->GetMissionData(); pData->ClearWeapons(); if (m_bSaveSelection) { for (int slot = 0; slot < m_nSlotsFilled; slot++) { CLTGUICtrl *pCtrl = GetControl(m_nFirstSlot - slot); if (pCtrl && (int)pCtrl->GetParam1() != kEmptySlot) pData->AddWeapon(pCtrl->GetParam1()); } } } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::OnCommand // // PURPOSE: Handle activation of items // // ----------------------------------------------------------------------- // uint32 CFolderWeapons::OnCommand(uint32 dwCommand, uint32 dwParam1, uint32 dwParam2) { switch (dwCommand) { case FOLDER_CMD_SELECT_SLOT: { if (dwParam2) { g_pInterfaceMgr->RequestInterfaceSound(IS_NO_SELECT); return 0; } int nWID = (int)dwParam1; WEAPON *pWeapon = g_pWeaponMgr->GetWeapon(nWID); SlotToItem(nWID,pWeapon->nNameId); return 1; } break; case FOLDER_CMD_SELECT_ITEM: { int nWID = (int)dwParam1; WEAPON *pWeapon = g_pWeaponMgr->GetWeapon(nWID); ItemToSlot(nWID,pWeapon->nNameId); return 1; } break; case FOLDER_CMD_CONTINUE: { if (m_pContinue->GetHelpID() == IDS_HELP_START) { int missionNum = g_pInterfaceMgr->GetMissionData()->GetMissionNum(); g_pGameClientShell->StartMission(missionNum); return 1; } } break; } return CBaseSelectionFolder::OnCommand(dwCommand,dwParam1,dwParam2); } HSTRING CFolderWeapons::GetHelpString(uint32 dwHelpId, int nControlIndex) { WEAPON* pWeapon = LTNULL; char pStr[512] = ""; //slots are fixed controls so count negatively ( 0 > first > last ) int nLastSlot = (m_nFirstSlot - m_nNumSlots) + 1; if (nControlIndex >= 0 || (nControlIndex <= m_nFirstSlot && nControlIndex >= nLastSlot)) { CLTGUICtrl *pCtrl = GetControl(nControlIndex); int weaponId = pCtrl->GetParam1(); if (weaponId == kEmptySlot) return CBaseSelectionFolder::GetHelpString(dwHelpId,nControlIndex); pWeapon = g_pWeaponMgr->GetWeapon(weaponId); if (!pWeapon) return CBaseSelectionFolder::GetHelpString(dwHelpId,nControlIndex); int nameId = pWeapon->nNameId; HSTRING hTemp = g_pLTClient->FormatString(nameId); char *pName = g_pLTClient->GetStringData(hTemp); if (nControlIndex < 0) { //over a slot if (pCtrl->GetParam2()) { sprintf(pStr,"%s %s",pName,m_sRequiredStr); } else if (nControlIndex < 0) { sprintf(pStr,"%s %s",m_sUnselectStr,pName); } } else { sprintf(pStr,"%s %s",m_sSelectStr,pName); } g_pLTClient->FreeString(hTemp); HSTRING hStr = g_pLTClient->CreateString(pStr); return hStr; } else return CBaseSelectionFolder::GetHelpString(dwHelpId,nControlIndex); } void CFolderWeapons::SetContinue() { int nHelp = LTNULL; eFolderID eNext = GetNextSelectionFolder(FOLDER_ID_WEAPONS,&nHelp); if (eNext != FOLDER_ID_NONE) { UseContinue(eNext,nHelp); } else { UseContinue(g_pInterfaceMgr->GetMainFolder(),IDS_HELP_START,IDS_START_MISSION); } } void CFolderWeapons::CreateModelSFX() { // no model = no SFX if (!strlen(m_szModel)) return; HOBJECT hCamera = g_pGameClientShell->GetInterfaceCamera(); if (!hCamera) return; BSCREATESTRUCT bcs; LTVector vPos, vU, vR, vF, vTemp, vScale(1.0f,1.0f,1.0f); LTRotation rRot; g_pLTClient->GetObjectPos(hCamera, &vPos); g_pLTClient->GetObjectRotation(hCamera, &rRot); g_pLTClient->GetRotationVectors(&rRot, &vU, &vR, &vF); g_pLTClient->RotateAroundAxis(&rRot, &vU, MATH_HALFPI); g_pLTClient->RotateAroundAxis(&rRot, &vR, -0.3f); VEC_MULSCALAR(vScale, vScale, m_fScale); LTVector vModPos = g_pLayoutMgr->GetFolderCustomVector((eFolderID)m_nFolderID,"ModelPos"); VEC_ADD(vModPos,vModPos,m_vOffset); VEC_MULSCALAR(vTemp, vF, vModPos.z); VEC_MULSCALAR(vTemp, vTemp, 1);//g_pInterfaceResMgr->GetXRatio()); VEC_ADD(vPos, vPos, vTemp); VEC_MULSCALAR(vTemp, vR, vModPos.x); VEC_ADD(vPos, vPos, vTemp); VEC_MULSCALAR(vTemp, vU, vModPos.y); VEC_ADD(vPos, vPos, vTemp); VEC_COPY(bcs.vPos, vPos); bcs.rRot = rRot; VEC_COPY(bcs.vInitialScale, vScale); VEC_COPY(bcs.vFinalScale, vScale); VEC_SET(bcs.vInitialColor, 1.0f, 1.0f, 1.0f); VEC_SET(bcs.vFinalColor, 1.0f, 1.0f, 1.0f); bcs.bUseUserColors = LTTRUE; bcs.pFilename = m_szModel; bcs.pSkin = m_szSkin; bcs.dwFlags = FLAG_VISIBLE | FLAG_FOGDISABLE | FLAG_NOLIGHT; bcs.nType = OT_MODEL; bcs.fInitialAlpha = 1.0f; bcs.fFinalAlpha = 1.0f; bcs.fLifeTime = 1000000.0f; if (m_ModelSFX.Init(&bcs)) { m_ModelSFX.CreateObject(g_pLTClient); g_pInterfaceMgr->AddInterfaceSFX(&m_ModelSFX, IFX_NORMAL); m_fSFXRot = g_pLayoutMgr->GetFolderCustomFloat((eFolderID)m_nFolderID,"ModelRotSpeed"); } } void CFolderWeapons::RemoveInterfaceSFX() { CBaseSelectionFolder::RemoveInterfaceSFX(); g_pInterfaceMgr->RemoveInterfaceSFX(&m_ModelSFX); m_ModelSFX.Term(); } void CFolderWeapons::UpdateInterfaceSFX() { CBaseSelectionFolder::UpdateInterfaceSFX(); if (m_ModelSFX.GetObject()) { LTFLOAT spin = g_pGameClientShell->GetFrameTime() * m_fSFXRot; LTVector vU, vR, vF; LTRotation rRot; g_pLTClient->GetObjectRotation(m_ModelSFX.GetObject(), &rRot); g_pLTClient->GetRotationVectors(&rRot, &vU, &vR, &vF); g_pLTClient->RotateAroundAxis(&rRot, &vU, spin); g_pLTClient->SetObjectRotation(m_ModelSFX.GetObject(),&rRot); } } void CFolderWeapons::SkipOutfitting() { CMissionData *pData = g_pInterfaceMgr->GetMissionData(); int missionNum = pData->GetMissionNum(); MISSION* pMission = g_pMissionMgr->GetMission(missionNum); pData->ClearWeapons(); int nWID = WMGR_INVALID_ID; WEAPON* pWeapon = LTNULL; for (int i=0; i< pMission->nNumRequiredWeapons; i++) { nWID = pMission->aRequiredWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); pData->AddWeapon(nWID); } for (i=0; i< pMission->nNumOneTimeWeapons; i++) { nWID = pMission->aOneTimeWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); pData->AddWeapon(nWID); } for (i=0; i< pMission->nNumDefaultWeapons; i++) { nWID = pMission->aDefaultWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); pData->AddWeapon(nWID); } }
24.380952
97
0.624766
haekb
605779aec247a93cff658e28eff006079d781e70
30,481
cpp
C++
Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/unitTestOneWayDopplerPartials.cpp
sebranchett/tudat
24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44
[ "BSD-3-Clause" ]
null
null
null
Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/unitTestOneWayDopplerPartials.cpp
sebranchett/tudat
24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44
[ "BSD-3-Clause" ]
null
null
null
Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/unitTestOneWayDopplerPartials.cpp
sebranchett/tudat
24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2019, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. * */ #define BOOST_TEST_MAIN #include <limits> #include <string> #include <vector> #include <boost/test/unit_test.hpp> #include <boost/make_shared.hpp> #include <boost/lambda/lambda.hpp> #include "Tudat/Basics/testMacros.h" #include "Tudat/InputOutput/basicInputOutput.h" #include "Tudat/External/SpiceInterface/spiceInterface.h" #include "Tudat/SimulationSetup/EstimationSetup/createObservationModel.h" #include "Tudat/Astrodynamics/ObservationModels/oneWayDopplerObservationModel.h" #include "Tudat/Astrodynamics/OrbitDetermination/EstimatableParameters/constantRotationRate.h" #include "Tudat/SimulationSetup/EstimationSetup/createObservationPartials.h" #include "Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/numericalObservationPartial.h" #include "Tudat/SimulationSetup/EnvironmentSetup/createGroundStations.h" #include "Tudat/SimulationSetup/EnvironmentSetup/defaultBodies.h" #include "Tudat/Mathematics/BasicMathematics/numericalDerivative.h" #include "Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/observationPartialTestFunctions.h" namespace tudat { namespace unit_tests { BOOST_AUTO_TEST_SUITE( test_one_way_observation_partials) Eigen::Vector3d computeUnitVectorToReceiverFromTransmitterState( const Eigen::Vector3d receiverPosition, const std::function< Eigen::Vector6d( const double ) > transmitterStateFunction, const double evaluationTime ) { return ( receiverPosition - transmitterStateFunction( evaluationTime ).segment( 0, 3 ) ).normalized( ); } Eigen::Vector3d computeUnitVectorToReceiverFromReceiverState( const std::function< Eigen::Vector6d( const double ) > receiverStateFunction, const Eigen::Vector3d transmitterPosition, const double evaluationTime ) { return ( receiverStateFunction( evaluationTime ).segment( 0, 3 ) - transmitterPosition ).normalized( ); } Eigen::VectorXd getProperTimeRateInVectorForm( std::shared_ptr< DopplerProperTimeRateInterface > properTimeRateCalculator, const std::vector< double >& linkEndTimes, const std::vector< Eigen::Matrix< double, 6, 1 > >& linkEndStates, const LinkEndType linkEndAssociatedWithTime ) { return ( Eigen::Vector1d( ) << properTimeRateCalculator->getOberverProperTimeDeviation( linkEndTimes, linkEndStates ) ).finished( ); } //! Test partial derivatives of one-way doppler observable, using general test suite of observation partials. BOOST_AUTO_TEST_CASE( testOneWayDopplerPartials ) { using namespace tudat::gravitation; using namespace tudat::gravitation; using namespace tudat::ephemerides; using namespace tudat::observation_models; using namespace tudat::simulation_setup; using namespace tudat::spice_interface; using namespace tudat::observation_partials; using namespace tudat::estimatable_parameters; // Define and create ground stations. std::vector< std::pair< std::string, std::string > > groundStations; groundStations.resize( 2 ); groundStations[ 0 ] = std::make_pair( "Earth", "Graz" ); groundStations[ 1 ] = std::make_pair( "Mars", "MSL" ); // Test ancilliary functions { double nominalEvaluationTime = 1.1E7; // Create environment NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, false ); // Set link ends for observation model LinkEnds linkEnds; linkEnds[ transmitter ] = groundStations[ 1 ]; linkEnds[ receiver ] = groundStations[ 0 ]; // Create transmitter/receriver state functions std::function< Eigen::Vector6d( const double ) > transmitterStateFunction = getLinkEndCompleteEphemerisFunction< double, double >( linkEnds[ transmitter ], bodyMap ); std::function< Eigen::Vector6d( const double ) > receiverStateFunction = getLinkEndCompleteEphemerisFunction< double, double >( linkEnds[ receiver ], bodyMap ); // Define (independent!) transmission/reception times double transmissionTime = nominalEvaluationTime; double receptionTime = nominalEvaluationTime + 1.0E3; // Compute associated states Eigen::Vector6d nominalTransmitterState = transmitterStateFunction( transmissionTime ); Eigen::Vector6d nominalReceiverState = receiverStateFunction( receptionTime ); Eigen::Vector3d nominalVectorToReceiver = ( nominalReceiverState - nominalTransmitterState ).segment( 0, 3 ); double timePerturbation = 100.0; // Partials for fixed receiver { // Compute numerical derivative of transmitter state for acceleration) Eigen::Vector6d numericalStateDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( transmitterStateFunction, transmissionTime, timePerturbation, numerical_derivatives::order8 ); // Compute unit vector derivative numerically std::function< Eigen::Vector3d( const double ) > unitVectorFunction = std::bind( &computeUnitVectorToReceiverFromTransmitterState, nominalReceiverState.segment( 0, 3 ), transmitterStateFunction, std::placeholders::_1 ); Eigen::Vector3d numericalUnitVectorDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( unitVectorFunction, transmissionTime, timePerturbation, numerical_derivatives::order8 ); // Compute projected velocoty vector derivative numerically std::function< double( const double) > projectedVelocityFunction = std::bind( &calculateLineOfSightVelocityAsCFractionFromTransmitterStateFunction< double, double >, nominalReceiverState.segment( 0, 3 ), transmitterStateFunction, std::placeholders::_1 ); double numericalProjectedVelocityDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( projectedVelocityFunction, transmissionTime, timePerturbation, numerical_derivatives::order8 ); // Compute analytical partial derivatives Eigen::Vector3d analyticalUnitVectorDerivative = -computePartialOfUnitVectorWrtLinkEndTime( nominalVectorToReceiver, nominalVectorToReceiver.normalized( ), nominalVectorToReceiver.norm( ), nominalTransmitterState.segment( 3, 3 ) ); double analyticalProjectedVelocityDerivative = computePartialOfProjectedLinkEndVelocityWrtAssociatedTime( nominalVectorToReceiver, nominalTransmitterState.segment( 3, 3 ), nominalTransmitterState.segment( 3, 3 ), numericalStateDerivative.segment( 3, 3 ), false ); for( unsigned int i = 0; i < 3; i++ ) { BOOST_CHECK_SMALL( std::fabs( analyticalUnitVectorDerivative( i ) - numericalUnitVectorDerivative( i ) ), 1.0E-16 ); } BOOST_CHECK_SMALL( std::fabs( analyticalProjectedVelocityDerivative / physical_constants::SPEED_OF_LIGHT - numericalProjectedVelocityDerivative ), 1.0E-21 ); } // Partials for fixed transmitter { // Compute numerical derivative of receiver state for acceleration) Eigen::Vector6d numericalStateDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( receiverStateFunction, receptionTime, timePerturbation, numerical_derivatives::order8 ); // Compute unit vector derivative numerically std::function< Eigen::Vector3d( const double ) > unitVectorFunction = std::bind( &computeUnitVectorToReceiverFromReceiverState, receiverStateFunction, nominalTransmitterState.segment( 0, 3 ), std::placeholders::_1 ); Eigen::Vector3d numericalUnitVectorDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( unitVectorFunction, receptionTime, timePerturbation, numerical_derivatives::order8 ); // Compute projected velocoty vector derivative numerically std::function< double( const double) > projectedVelocityFunction = std::bind( &calculateLineOfSightVelocityAsCFractionFromReceiverStateFunction< double, double >, receiverStateFunction, nominalTransmitterState.segment( 0, 3 ), std::placeholders::_1 ); double numericalProjectedVelocityDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( projectedVelocityFunction, receptionTime, timePerturbation, numerical_derivatives::order8 ); // Compute analytical partial derivatives Eigen::Vector3d analyticalUnitVectorDerivative = computePartialOfUnitVectorWrtLinkEndTime( nominalVectorToReceiver, nominalVectorToReceiver.normalized( ), nominalVectorToReceiver.norm( ), nominalReceiverState.segment( 3, 3 ) ); double analyticalProjectedVelocityDerivative = computePartialOfProjectedLinkEndVelocityWrtAssociatedTime( nominalVectorToReceiver, nominalReceiverState.segment( 3, 3 ), nominalReceiverState.segment( 3, 3 ),\ numericalStateDerivative.segment( 3, 3 ), true ); for( unsigned int i = 0; i < 3; i++ ) { BOOST_CHECK_SMALL( std::fabs( analyticalUnitVectorDerivative( i ) - numericalUnitVectorDerivative( i ) ), 1.0E-18 ); } BOOST_CHECK_SMALL( std::fabs( analyticalProjectedVelocityDerivative / physical_constants::SPEED_OF_LIGHT - numericalProjectedVelocityDerivative ), 1.0E-22 ); } } // Test partials with constant ephemerides (allows test of position partials) { // Create environment NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, true ); // Set link ends for observation model LinkEnds linkEnds; linkEnds[ transmitter ] = groundStations[ 1 ]; linkEnds[ receiver ] = groundStations[ 0 ]; for( unsigned int estimationCase = 0; estimationCase < 3; estimationCase ++ ) { std::cout << "Case " << estimationCase << std::endl; // Generate one-way doppler model std::shared_ptr< ObservationModel< 1 > > oneWayDopplerModel; std::vector< std::string > perturbingBodies; perturbingBodies.push_back( "Earth" ); if( estimationCase == 0 ) { oneWayDopplerModel = observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< observation_models::ObservationSettings >( observation_models::one_way_doppler, std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >( perturbingBodies ) ), bodyMap ); } else { oneWayDopplerModel = observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< OneWayDopplerObservationSettings > ( std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >( perturbingBodies ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Mars" ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Earth" ) ), bodyMap ); } // Create parameter objects. std::shared_ptr< EstimatableParameterSet< double > > fullEstimatableParameterSet; Eigen::VectorXd parameterPerturbationMultipliers = Eigen::Vector4d::Constant( 1.0 ); if( estimationCase < 2 ) { fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7 ); } else { fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7, true ); parameterPerturbationMultipliers( 2 ) = 1.0E-4; } testObservationPartials< 1 >( oneWayDopplerModel, bodyMap, fullEstimatableParameterSet, linkEnds, one_way_doppler, 1.0E-5, true, true, 10.0, parameterPerturbationMultipliers ); std::cout << "Case " << estimationCase << std::endl; } } // Test partials with real ephemerides (without test of position partials) { // Create environment NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, false ); // Set link ends for observation model LinkEnds linkEnds; linkEnds[ transmitter ] = groundStations[ 1 ]; linkEnds[ receiver ] = groundStations[ 0 ]; for( unsigned int estimationCase = 0; estimationCase < 3; estimationCase ++ ) { std::cout << "Rates: " << estimationCase << std::endl; // Generate one-way doppler model std::shared_ptr< ObservationModel< 1 > > oneWayDopplerModel; std::vector< std::string > perturbingBodies; perturbingBodies.push_back( "Earth" ); if( estimationCase == 0 ) { oneWayDopplerModel = observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< observation_models::ObservationSettings >( observation_models::one_way_doppler, std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >( perturbingBodies ) ), bodyMap ); } else { oneWayDopplerModel = observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< OneWayDopplerObservationSettings > ( std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >( perturbingBodies ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Mars" ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Earth" ) ), bodyMap ); } // Create parameter objects. std::shared_ptr< EstimatableParameterSet< double > > fullEstimatableParameterSet; Eigen::VectorXd parameterPerturbationMultipliers = Eigen::Vector4d::Constant( 1.0 ); if( estimationCase < 2 ) { fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7 ); } else { fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7, true ); parameterPerturbationMultipliers( 2 ) = 1.0E-4; } testObservationPartials< 1 >( oneWayDopplerModel, bodyMap, fullEstimatableParameterSet, linkEnds, one_way_doppler, 1.0E-4, false, true, 1.0, parameterPerturbationMultipliers ); } } // Test partials with constant ephemerides (allows test of position partials) { // Create environment NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, true, 1000000.0 ); // Set link ends for observation model (Mars to Earth) LinkEnds linkEnds; linkEnds[ transmitter ] = groundStations[ 1 ]; linkEnds[ receiver ] = groundStations[ 0 ]; // Create one-way doppler model std::shared_ptr< OneWayDopplerObservationModel< > > oneWayDopplerModel = std::dynamic_pointer_cast< OneWayDopplerObservationModel< > >( observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< OneWayDopplerObservationSettings > ( std::shared_ptr< LightTimeCorrectionSettings >( ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Earth" ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Mars" ) ), bodyMap ) ); // Extract proper time calculators std::shared_ptr< DopplerProperTimeRateInterface > receiverProperTimeRateCalculator = oneWayDopplerModel->getReceiverProperTimeRateCalculator( ); std::shared_ptr< DopplerProperTimeRateInterface > transmitterProperTimeRateCalculator = oneWayDopplerModel->getTransmitterProperTimeRateCalculator( ); // Create parameter objects. std::shared_ptr< EstimatableParameterSet< double > > fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7 ); // Create partials for Doppler with proper time rates std::map< LinkEnds, std::shared_ptr< ObservationModel< 1 > > > observationModelList; observationModelList[ linkEnds ] = oneWayDopplerModel; std::map< LinkEnds, std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > > dopplerPartials = createOneWayDopplerPartials( observationModelList, bodyMap, fullEstimatableParameterSet ); // Retrieve scaling objects and partials with proper time std::shared_ptr< OneWayDopplerScaling > partialScalingObject = std::dynamic_pointer_cast< OneWayDopplerScaling >( dopplerPartials.begin( )->second.second ); std::shared_ptr< OneWayDopplerProperTimeComponentScaling > transmitterProperTimePartials = partialScalingObject->getTransmitterProperTimePartials( ); std::shared_ptr< OneWayDopplerProperTimeComponentScaling > receiverProperTimePartials = partialScalingObject->getReceiverProperTimePartials( ); std::shared_ptr< OneWayDopplerPartial > earthStatePartial = std::dynamic_pointer_cast< OneWayDopplerPartial >( ( dopplerPartials.begin( )->second.first ).begin( )->second ); std::shared_ptr< OneWayDopplerPartial > marsStatePartial = std::dynamic_pointer_cast< OneWayDopplerPartial >( ( ++( ( dopplerPartials.begin( )->second.first ).begin( ) ) )->second ); // Compute nominal observation with proper time double observationTime = 1.1E7; std::vector< double > linkEndTimes; std::vector< Eigen::Vector6d > linkEndStates; LinkEndType referenceLinkEnd = transmitter; Eigen::VectorXd nominalObservable = oneWayDopplerModel->computeIdealObservationsWithLinkEndData( observationTime, referenceLinkEnd, linkEndTimes, linkEndStates ); // Compute partials with proper time. partialScalingObject->update( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > earthStatePartialOutput = earthStatePartial->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > marsStatePartialOutput = marsStatePartial->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); // Compute numerical proper time rate partials and compare to analytical results { std::function< Eigen::VectorXd( const double ) > transmitterProperTimeRateFunction = std::bind( &getProperTimeRateInVectorForm, transmitterProperTimeRateCalculator, linkEndTimes, linkEndStates, referenceLinkEnd ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtMarsPosition = calculatePartialWrtConstantBodyState( "Earth", bodyMap, Eigen::Vector3d::Constant( 1000.0E3 ), transmitterProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtEarthPosition = calculatePartialWrtConstantBodyState( "Mars", bodyMap, Eigen::Vector3d::Constant( 1000.0E3 ), transmitterProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtMarsVelocity = calculatePartialWrtConstantBodyVelocity( "Earth", bodyMap, Eigen::Vector3d::Constant( 1.0E0 ), transmitterProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtEarthVelocity = calculatePartialWrtConstantBodyVelocity( "Mars", bodyMap, Eigen::Vector3d::Constant( 1.0E0 ), transmitterProperTimeRateFunction, 1.1E7, 1 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( transmitterProperTimePartials->getPositionScalingFactor( transmitter ) ), numericalTransmitterProperTimePartialsWrtMarsPosition, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( transmitterProperTimePartials->getPositionScalingFactor( receiver ) ), numericalTransmitterProperTimePartialsWrtEarthPosition, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( transmitterProperTimePartials->getVelocityScalingFactor( transmitter ) ), numericalTransmitterProperTimePartialsWrtMarsVelocity, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( transmitterProperTimePartials->getVelocityScalingFactor( receiver ) ), numericalTransmitterProperTimePartialsWrtEarthVelocity, 1.0E-6 ); std::function< Eigen::VectorXd( const double ) > receiverProperTimeRateFunction = std::bind( &getProperTimeRateInVectorForm, receiverProperTimeRateCalculator, linkEndTimes, linkEndStates, referenceLinkEnd ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtMarsPosition = calculatePartialWrtConstantBodyState( "Earth", bodyMap, Eigen::Vector3d::Constant( 10000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtEarthPosition = calculatePartialWrtConstantBodyState( "Mars", bodyMap, Eigen::Vector3d::Constant( 10000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtMarsVelocity = calculatePartialWrtConstantBodyVelocity( "Earth", bodyMap, Eigen::Vector3d::Constant( 1000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtEarthVelocity = calculatePartialWrtConstantBodyVelocity( "Mars", bodyMap, Eigen::Vector3d::Constant( 1000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( receiverProperTimePartials->getPositionScalingFactor( receiver ) ), numericalReceiverProperTimePartialsWrtEarthPosition, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( receiverProperTimePartials->getPositionScalingFactor( transmitter ) ), numericalReceiverProperTimePartialsWrtMarsPosition, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( receiverProperTimePartials->getVelocityScalingFactor( transmitter ) ), numericalReceiverProperTimePartialsWrtMarsVelocity, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( receiverProperTimePartials->getVelocityScalingFactor( receiver ) ), numericalReceiverProperTimePartialsWrtEarthVelocity, 1.0E-6 ); } // Create one-way doppler model without proper time rates std::shared_ptr< OneWayDopplerObservationModel< > > oneWayDopplerModelWithoutProperTime = std::dynamic_pointer_cast< OneWayDopplerObservationModel< > >( observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< ObservationSettings > ( one_way_doppler, std::shared_ptr< LightTimeCorrectionSettings >( ) ), bodyMap ) ); // Create partials for Doppler without proper time rates observationModelList.clear( ); observationModelList[ linkEnds ] = oneWayDopplerModelWithoutProperTime; std::map< LinkEnds, std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > > dopplerPartialsWithoutProperTime = createOneWayDopplerPartials( observationModelList, bodyMap, fullEstimatableParameterSet ); // Retrieve partial object without proper time std::shared_ptr< OneWayDopplerScaling > partialScalingObjectWithoutProperTime = std::dynamic_pointer_cast< OneWayDopplerScaling >( dopplerPartialsWithoutProperTime.begin( )->second.second ); std::shared_ptr< OneWayDopplerPartial > earthStatePartialWithoutProperTime = std::dynamic_pointer_cast< OneWayDopplerPartial >( ( dopplerPartialsWithoutProperTime.begin( )->second.first ).begin( )->second ); std::shared_ptr< OneWayDopplerPartial > marsStatePartialWithoutProperTime = std::dynamic_pointer_cast< OneWayDopplerPartial >( ( ++( ( dopplerPartialsWithoutProperTime.begin( )->second.first ).begin( ) ) )->second ); // Compute nominal observation without proper time std::vector< double > linkEndTimesWithoutProperTime; std::vector< Eigen::Vector6d > linkEndStatesWithoutProperTime; Eigen::VectorXd nominalObservableWithoutProperTime = oneWayDopplerModelWithoutProperTime->computeIdealObservationsWithLinkEndData( observationTime, referenceLinkEnd, linkEndTimesWithoutProperTime, linkEndStatesWithoutProperTime ); // Compute partials with proper time. partialScalingObjectWithoutProperTime->update( linkEndStatesWithoutProperTime, linkEndTimesWithoutProperTime, referenceLinkEnd, nominalObservableWithoutProperTime ); std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > earthStatePartialOutputWithoutProperTime = earthStatePartialWithoutProperTime->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > marsStatePartialOutputWithoutProperTime = marsStatePartialWithoutProperTime->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); Eigen::MatrixXd partialWrtEarthState = earthStatePartialOutput.at( 0 ).first; Eigen::MatrixXd partialWrtEarthStateWithoutProperTime = earthStatePartialOutputWithoutProperTime.at( 0 ).first; Eigen::MatrixXd partialWrtMarsState = marsStatePartialOutput.at( 0 ).first; Eigen::MatrixXd partialWrtMarsStateWithoutProperTime = marsStatePartialOutputWithoutProperTime.at( 0 ).first; Eigen::MatrixXd properTimePartialWrtMarsPosition = transmitterProperTimePartials->getPositionScalingFactor( transmitter ); Eigen::MatrixXd properTimePartialWrtEarthPosition = receiverProperTimePartials->getPositionScalingFactor( receiver ); Eigen::MatrixXd properTimePartialWrtMarsVelocity = transmitterProperTimePartials->getVelocityScalingFactor( transmitter ); Eigen::MatrixXd properTimePartialWrtEarthVelocity = receiverProperTimePartials->getVelocityScalingFactor( receiver ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( ( partialWrtMarsState - partialWrtMarsStateWithoutProperTime ).block( 0, 0, 1, 3 ) ), properTimePartialWrtMarsPosition, 1.0E-9 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( -( partialWrtEarthState - partialWrtEarthStateWithoutProperTime ).block( 0, 0, 1, 3 ) ), properTimePartialWrtEarthPosition, 1.0E-9 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( ( partialWrtMarsState - partialWrtMarsStateWithoutProperTime ).block( 0, 3, 1, 3 ) ), properTimePartialWrtMarsVelocity, 1.0E-8 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( -( partialWrtEarthState - partialWrtEarthStateWithoutProperTime ).block( 0, 3, 1, 3 ) ), properTimePartialWrtEarthVelocity, 1.0E-8 ); } } BOOST_AUTO_TEST_SUITE_END( ) } // namespace unit_tests } // namespace tudat
56.973832
153
0.661658
sebranchett
605a0f65f0e1e368456e7ba5d78f1c7b313fe66f
2,205
hpp
C++
includes/Fox/Lexer/Token.hpp
Pierre-vh/Fox
ab3d9a5b3c409b5611840c477abef989830ea571
[ "MIT" ]
17
2019-01-17T22:41:11.000Z
2020-08-27T03:39:07.000Z
includes/Fox/Lexer/Token.hpp
Pierre-vh/Moonshot
ab3d9a5b3c409b5611840c477abef989830ea571
[ "MIT" ]
null
null
null
includes/Fox/Lexer/Token.hpp
Pierre-vh/Moonshot
ab3d9a5b3c409b5611840c477abef989830ea571
[ "MIT" ]
2
2019-06-30T19:07:10.000Z
2019-12-26T17:30:17.000Z
//----------------------------------------------------------------------------// // Part of the Fox project, licensed under the MIT license. // See LICENSE.txt in the project root for license information. // File : Token.hpp // Author : Pierre van Houtryve //----------------------------------------------------------------------------// // This file contains the Token class and TokenKind enum. //----------------------------------------------------------------------------// #pragma once #include "Fox/AST/Identifier.hpp" #include "Fox/Common/FoxTypes.hpp" #include "Fox/Common/SourceLoc.hpp" #include "Fox/Common/LLVM.hpp" #include "llvm/ADT/SmallVector.h" #include <cstddef> #include <iosfwd> namespace fox { class ASTContext; class DiagnosticEngine; class SourceManager; /// TokenKind /// The different kind of tokens that exist enum class TokenKind : std::uint8_t { #define TOKEN(ID) ID, #include "TokenKinds.def" }; /// Token /// Provides information about a lexed token: its string, location and kind. struct Token { public: using Kind = TokenKind; /// Creates an invalid token Token() = default; /// Creates a normal token Token(Kind kind, string_view str, SourceRange range); /// \returns true if this token's kind != TokenKind::Invalid bool isValid() const; /// \returns true if this token is the EOF token bool isEOF() const; /// \returns isValid() operator bool() const; /// \returns true if this token's kind matches "kind" bool is(Kind kind) const; /// dumps this token's data to out (without loc info) void dump(std::ostream& out) const; /// dumps this token's data to out (with loc info) void dump(std::ostream& out, SourceManager& srcMgr, bool printFileName) const; /// The SourceRange of this token const SourceRange range; /// A string-view (in the file's buffer) of this token. const string_view str; /// The Kind of token this is const Kind kind = Kind::Invalid; }; /// A Vector of Tokens. using TokenVector = SmallVector<Token, 4>; }
30.625
81
0.570975
Pierre-vh
605c71ebb028d6055653a9c1781de822a64e3e9b
47,941
cpp
C++
src/build_vehicle_gui.cpp
trademarks/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
8
2016-10-21T09:01:43.000Z
2021-05-31T06:32:14.000Z
src/build_vehicle_gui.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
null
null
null
src/build_vehicle_gui.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
4
2017-05-16T00:15:58.000Z
2020-08-06T01:46:31.000Z
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file build_vehicle_gui.cpp GUI for building vehicles. */ #include "stdafx.h" #include "engine_base.h" #include "engine_func.h" #include "station_base.h" #include "articulated_vehicles.h" #include "textbuf_gui.h" #include "command_func.h" #include "company_func.h" #include "vehicle_gui.h" #include "newgrf_engine.h" #include "newgrf_text.h" #include "group.h" #include "string_func.h" #include "strings_func.h" #include "window_func.h" #include "date_func.h" #include "vehicle_func.h" #include "widgets/dropdown_func.h" #include "engine_gui.h" #include "cargotype.h" #include "core/geometry_func.hpp" #include "table/strings.h" /** * Get the height of a single 'entry' in the engine lists. * @param type the vehicle type to get the height of * @return the height for the entry */ uint GetEngineListHeight(VehicleType type) { return max<uint>(FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM, GetVehicleHeight(type)); } enum BuildVehicleWidgets { BUILD_VEHICLE_WIDGET_CAPTION, BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN, BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN, BUILD_VEHICLE_WIDGET_LIST, BUILD_VEHICLE_WIDGET_SCROLLBAR, BUILD_VEHICLE_WIDGET_PANEL, BUILD_VEHICLE_WIDGET_BUILD, BUILD_VEHICLE_WIDGET_BUILD_SEL, BUILD_VEHICLE_WIDGET_RENAME, BUILD_VEHICLE_WIDGET_END }; static const NWidgetPart _nested_build_vehicle_widgets[] = { NWidget(NWID_HORIZONTAL), NWidget(WWT_CLOSEBOX, COLOUR_GREY), NWidget(WWT_CAPTION, COLOUR_GREY, BUILD_VEHICLE_WIDGET_CAPTION), SetDataTip(STR_WHITE_STRING, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS), NWidget(WWT_SHADEBOX, COLOUR_GREY), NWidget(WWT_STICKYBOX, COLOUR_GREY), EndContainer(), NWidget(WWT_PANEL, COLOUR_GREY), NWidget(NWID_HORIZONTAL), NWidget(NWID_VERTICAL), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), NWidget(NWID_SPACER), SetFill(1, 1), EndContainer(), NWidget(NWID_VERTICAL), NWidget(WWT_DROPDOWN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA), NWidget(WWT_DROPDOWN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_FILTER_CRITERIA), EndContainer(), EndContainer(), EndContainer(), /* Vehicle list. */ NWidget(NWID_HORIZONTAL), NWidget(WWT_MATRIX, COLOUR_GREY, BUILD_VEHICLE_WIDGET_LIST), SetResize(1, 1), SetFill(1, 0), SetDataTip(0x101, STR_NULL), SetScrollbar(BUILD_VEHICLE_WIDGET_SCROLLBAR), NWidget(NWID_VSCROLLBAR, COLOUR_GREY, BUILD_VEHICLE_WIDGET_SCROLLBAR), EndContainer(), /* Panel with details. */ NWidget(WWT_PANEL, COLOUR_GREY, BUILD_VEHICLE_WIDGET_PANEL), SetMinimalSize(240, 122), SetResize(1, 0), EndContainer(), /* Build/rename buttons, resize button. */ NWidget(NWID_HORIZONTAL), NWidget(NWID_SELECTION, INVALID_COLOUR, BUILD_VEHICLE_WIDGET_BUILD_SEL), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_BUILD), SetResize(1, 0), SetFill(1, 0), EndContainer(), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_RENAME), SetResize(1, 0), SetFill(1, 0), NWidget(WWT_RESIZEBOX, COLOUR_GREY), EndContainer(), }; /** Special cargo filter criteria */ static const CargoID CF_ANY = CT_NO_REFIT; ///< Show all vehicles independent of carried cargo (i.e. no filtering) static const CargoID CF_NONE = CT_INVALID; ///< Show only vehicles which do not carry cargo (e.g. train engines) static bool _internal_sort_order; ///< false = descending, true = ascending static byte _last_sort_criteria[] = {0, 0, 0, 0}; static bool _last_sort_order[] = {false, false, false, false}; static CargoID _last_filter_criteria[] = {CF_ANY, CF_ANY, CF_ANY, CF_ANY}; /** * Determines order of engines by engineID * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineNumberSorter(const EngineID *a, const EngineID *b) { int r = ListPositionOfEngine(*a) - ListPositionOfEngine(*b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by introduction date * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineIntroDateSorter(const EngineID *a, const EngineID *b) { const int va = Engine::Get(*a)->intro_date; const int vb = Engine::Get(*b)->intro_date; const int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by name * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineNameSorter(const EngineID *a, const EngineID *b) { static EngineID last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE }; static char last_name[2][64] = { "\0", "\0" }; const EngineID va = *a; const EngineID vb = *b; if (va != last_engine[0]) { last_engine[0] = va; SetDParam(0, va); GetString(last_name[0], STR_ENGINE_NAME, lastof(last_name[0])); } if (vb != last_engine[1]) { last_engine[1] = vb; SetDParam(0, vb); GetString(last_name[1], STR_ENGINE_NAME, lastof(last_name[1])); } int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting). /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by reliability * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineReliabilitySorter(const EngineID *a, const EngineID *b) { const int va = Engine::Get(*a)->reliability; const int vb = Engine::Get(*b)->reliability; const int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by purchase cost * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineCostSorter(const EngineID *a, const EngineID *b) { Money va = Engine::Get(*a)->GetCost(); Money vb = Engine::Get(*b)->GetCost(); int r = ClampToI32(va - vb); /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by speed * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineSpeedSorter(const EngineID *a, const EngineID *b) { int va = Engine::Get(*a)->GetDisplayMaxSpeed(); int vb = Engine::Get(*b)->GetDisplayMaxSpeed(); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by power * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EnginePowerSorter(const EngineID *a, const EngineID *b) { int va = Engine::Get(*a)->GetPower(); int vb = Engine::Get(*b)->GetPower(); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by tractive effort * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineTractiveEffortSorter(const EngineID *a, const EngineID *b) { int va = Engine::Get(*a)->GetDisplayMaxTractiveEffort(); int vb = Engine::Get(*b)->GetDisplayMaxTractiveEffort(); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by running costs * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineRunningCostSorter(const EngineID *a, const EngineID *b) { Money va = Engine::Get(*a)->GetRunningCost(); Money vb = Engine::Get(*b)->GetRunningCost(); int r = ClampToI32(va - vb); /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by running costs * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EnginePowerVsRunningCostSorter(const EngineID *a, const EngineID *b) { const Engine *e_a = Engine::Get(*a); const Engine *e_b = Engine::Get(*b); /* Here we are using a few tricks to get the right sort. * We want power/running cost, but since we usually got higher running cost than power and we store the result in an int, * we will actually calculate cunning cost/power (to make it more than 1). * Because of this, the return value have to be reversed as well and we return b - a instead of a - b. * Another thing is that both power and running costs should be doubled for multiheaded engines. * Since it would be multipling with 2 in both numerator and denumerator, it will even themselves out and we skip checking for multiheaded. */ Money va = (e_a->GetRunningCost()) / max(1U, (uint)e_a->GetPower()); Money vb = (e_b->GetRunningCost()) / max(1U, (uint)e_b->GetPower()); int r = ClampToI32(vb - va); /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /* Train sorting functions */ /** * Determines order of train engines by capacity * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL TrainEngineCapacitySorter(const EngineID *a, const EngineID *b) { const RailVehicleInfo *rvi_a = RailVehInfo(*a); const RailVehicleInfo *rvi_b = RailVehInfo(*b); int va = GetTotalCapacityOfArticulatedParts(*a) * (rvi_a->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1); int vb = GetTotalCapacityOfArticulatedParts(*b) * (rvi_b->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of train engines by engine / wagon * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL TrainEnginesThenWagonsSorter(const EngineID *a, const EngineID *b) { int val_a = (RailVehInfo(*a)->railveh_type == RAILVEH_WAGON ? 1 : 0); int val_b = (RailVehInfo(*b)->railveh_type == RAILVEH_WAGON ? 1 : 0); int r = val_a - val_b; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /* Road vehicle sorting functions */ /** * Determines order of road vehicles by capacity * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL RoadVehEngineCapacitySorter(const EngineID *a, const EngineID *b) { int va = GetTotalCapacityOfArticulatedParts(*a); int vb = GetTotalCapacityOfArticulatedParts(*b); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /* Ship vehicle sorting functions */ /** * Determines order of ships by capacity * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL ShipEngineCapacitySorter(const EngineID *a, const EngineID *b) { const Engine *e_a = Engine::Get(*a); const Engine *e_b = Engine::Get(*b); int va = e_a->GetDisplayDefaultCapacity(); int vb = e_b->GetDisplayDefaultCapacity(); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /* Aircraft sorting functions */ /** * Determines order of aircraft by cargo * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL AircraftEngineCargoSorter(const EngineID *a, const EngineID *b) { const Engine *e_a = Engine::Get(*a); const Engine *e_b = Engine::Get(*b); uint16 mail_a, mail_b; int va = e_a->GetDisplayDefaultCapacity(&mail_a); int vb = e_b->GetDisplayDefaultCapacity(&mail_b); int r = va - vb; if (r == 0) { /* The planes have the same passenger capacity. Check mail capacity instead */ r = mail_a - mail_b; if (r == 0) { /* Use EngineID to sort instead since we want consistent sorting */ return EngineNumberSorter(a, b); } } return _internal_sort_order ? -r : r; } static EngList_SortTypeFunction * const _sorter[][11] = {{ /* Trains */ &EngineNumberSorter, &EngineCostSorter, &EngineSpeedSorter, &EnginePowerSorter, &EngineTractiveEffortSorter, &EngineIntroDateSorter, &EngineNameSorter, &EngineRunningCostSorter, &EnginePowerVsRunningCostSorter, &EngineReliabilitySorter, &TrainEngineCapacitySorter, }, { /* Road vehicles */ &EngineNumberSorter, &EngineCostSorter, &EngineSpeedSorter, &EnginePowerSorter, &EngineTractiveEffortSorter, &EngineIntroDateSorter, &EngineNameSorter, &EngineRunningCostSorter, &EnginePowerVsRunningCostSorter, &EngineReliabilitySorter, &RoadVehEngineCapacitySorter, }, { /* Ships */ &EngineNumberSorter, &EngineCostSorter, &EngineSpeedSorter, &EngineIntroDateSorter, &EngineNameSorter, &EngineRunningCostSorter, &EngineReliabilitySorter, &ShipEngineCapacitySorter, }, { /* Aircraft */ &EngineNumberSorter, &EngineCostSorter, &EngineSpeedSorter, &EngineIntroDateSorter, &EngineNameSorter, &EngineRunningCostSorter, &EngineReliabilitySorter, &AircraftEngineCargoSorter, }}; static const StringID _sort_listing[][12] = {{ /* Trains */ STR_SORT_BY_ENGINE_ID, STR_SORT_BY_COST, STR_SORT_BY_MAX_SPEED, STR_SORT_BY_POWER, STR_SORT_BY_TRACTIVE_EFFORT, STR_SORT_BY_INTRO_DATE, STR_SORT_BY_NAME, STR_SORT_BY_RUNNING_COST, STR_SORT_BY_POWER_VS_RUNNING_COST, STR_SORT_BY_RELIABILITY, STR_SORT_BY_CARGO_CAPACITY, INVALID_STRING_ID }, { /* Road vehicles */ STR_SORT_BY_ENGINE_ID, STR_SORT_BY_COST, STR_SORT_BY_MAX_SPEED, STR_SORT_BY_POWER, STR_SORT_BY_TRACTIVE_EFFORT, STR_SORT_BY_INTRO_DATE, STR_SORT_BY_NAME, STR_SORT_BY_RUNNING_COST, STR_SORT_BY_POWER_VS_RUNNING_COST, STR_SORT_BY_RELIABILITY, STR_SORT_BY_CARGO_CAPACITY, INVALID_STRING_ID }, { /* Ships */ STR_SORT_BY_ENGINE_ID, STR_SORT_BY_COST, STR_SORT_BY_MAX_SPEED, STR_SORT_BY_INTRO_DATE, STR_SORT_BY_NAME, STR_SORT_BY_RUNNING_COST, STR_SORT_BY_RELIABILITY, STR_SORT_BY_CARGO_CAPACITY, INVALID_STRING_ID }, { /* Aircraft */ STR_SORT_BY_ENGINE_ID, STR_SORT_BY_COST, STR_SORT_BY_MAX_SPEED, STR_SORT_BY_INTRO_DATE, STR_SORT_BY_NAME, STR_SORT_BY_RUNNING_COST, STR_SORT_BY_RELIABILITY, STR_SORT_BY_CARGO_CAPACITY, INVALID_STRING_ID }}; /** Cargo filter functions */ static bool CDECL CargoFilter(const EngineID *eid, const CargoID cid) { if (cid == CF_ANY) return true; uint32 refit_mask = GetUnionOfArticulatedRefitMasks(*eid, true); return (cid == CF_NONE ? refit_mask == 0 : HasBit(refit_mask, cid)); } static GUIEngineList::FilterFunction * const _filter_funcs[] = { &CargoFilter, }; static int DrawCargoCapacityInfo(int left, int right, int y, EngineID engine, bool refittable) { CargoArray cap = GetCapacityOfArticulatedParts(engine); for (CargoID c = 0; c < NUM_CARGO; c++) { if (cap[c] == 0) continue; SetDParam(0, c); SetDParam(1, cap[c]); SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY); DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY); y += FONT_HEIGHT_NORMAL; /* Only show as refittable once */ refittable = false; } return y; } /* Draw rail wagon specific details */ static int DrawRailWagonPurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi) { const Engine *e = Engine::Get(engine_number); /* Purchase cost */ SetDParam(0, e->GetCost()); DrawString(left, right, y, STR_PURCHASE_INFO_COST); y += FONT_HEIGHT_NORMAL; /* Wagon weight - (including cargo) */ uint weight = e->GetDisplayWeight(); SetDParam(0, weight); uint cargo_weight = (e->CanCarryCargo() ? CargoSpec::Get(e->GetDefaultCargoType())->weight * e->GetDisplayDefaultCapacity() >> 4 : 0); SetDParam(1, cargo_weight + weight); DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT); y += FONT_HEIGHT_NORMAL; /* Wagon speed limit, displayed if above zero */ if (_settings_game.vehicle.wagon_speed_limits) { uint max_speed = e->GetDisplayMaxSpeed(); if (max_speed > 0) { SetDParam(0, max_speed); DrawString(left, right, y, STR_PURCHASE_INFO_SPEED); y += FONT_HEIGHT_NORMAL; } } /* Running cost */ if (rvi->running_cost_class != INVALID_PRICE) { SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; } return y; } /* Draw locomotive specific details */ static int DrawRailEnginePurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi) { const Engine *e = Engine::Get(engine_number); /* Purchase Cost - Engine weight */ SetDParam(0, e->GetCost()); SetDParam(1, e->GetDisplayWeight()); DrawString(left, right, y, STR_PURCHASE_INFO_COST_WEIGHT); y += FONT_HEIGHT_NORMAL; /* Max speed - Engine power */ SetDParam(0, e->GetDisplayMaxSpeed()); SetDParam(1, e->GetPower()); DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER); y += FONT_HEIGHT_NORMAL; /* Max tractive effort - not applicable if old acceleration or maglev */ if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && GetRailTypeInfo(rvi->railtype)->acceleration_type != 2) { SetDParam(0, e->GetDisplayMaxTractiveEffort()); DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE); y += FONT_HEIGHT_NORMAL; } /* Running cost */ if (rvi->running_cost_class != INVALID_PRICE) { SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; } /* Powered wagons power - Powered wagons extra weight */ if (rvi->pow_wag_power != 0) { SetDParam(0, rvi->pow_wag_power); SetDParam(1, rvi->pow_wag_weight); DrawString(left, right, y, STR_PURCHASE_INFO_PWAGPOWER_PWAGWEIGHT); y += FONT_HEIGHT_NORMAL; } return y; } /* Draw road vehicle specific details */ static int DrawRoadVehPurchaseInfo(int left, int right, int y, EngineID engine_number) { const Engine *e = Engine::Get(engine_number); if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) { /* Purchase Cost */ SetDParam(0, e->GetCost()); DrawString(left, right, y, STR_PURCHASE_INFO_COST); y += FONT_HEIGHT_NORMAL; /* Road vehicle weight - (including cargo) */ int16 weight = e->GetDisplayWeight(); SetDParam(0, weight); uint cargo_weight = CargoSpec::Get(e->GetDefaultCargoType())->weight * GetTotalCapacityOfArticulatedParts(engine_number) / 16; SetDParam(1, cargo_weight + weight); DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT); y += FONT_HEIGHT_NORMAL; /* Max speed - Engine power */ SetDParam(0, e->GetDisplayMaxSpeed()); SetDParam(1, e->GetPower()); DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER); y += FONT_HEIGHT_NORMAL; /* Max tractive effort */ SetDParam(0, e->GetDisplayMaxTractiveEffort()); DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE); y += FONT_HEIGHT_NORMAL; } else { /* Purchase cost - Max speed */ SetDParam(0, e->GetCost()); SetDParam(1, e->GetDisplayMaxSpeed()); DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED); y += FONT_HEIGHT_NORMAL; } /* Running cost */ SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; return y; } /* Draw ship specific details */ static int DrawShipPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable) { const Engine *e = Engine::Get(engine_number); /* Purchase cost - Max speed */ SetDParam(0, e->GetCost()); SetDParam(1, e->GetDisplayMaxSpeed()); DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED); y += FONT_HEIGHT_NORMAL; /* Cargo type + capacity */ SetDParam(0, e->GetDefaultCargoType()); SetDParam(1, e->GetDisplayDefaultCapacity()); SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY); DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY); y += FONT_HEIGHT_NORMAL; /* Running cost */ SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; return y; } /* Draw aircraft specific details */ static int DrawAircraftPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable) { const Engine *e = Engine::Get(engine_number); CargoID cargo = e->GetDefaultCargoType(); /* Purchase cost - Max speed */ SetDParam(0, e->GetCost()); SetDParam(1, e->GetDisplayMaxSpeed()); DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED); y += FONT_HEIGHT_NORMAL; /* Cargo capacity */ uint16 mail_capacity; uint capacity = e->GetDisplayDefaultCapacity(&mail_capacity); if (mail_capacity > 0) { SetDParam(0, cargo); SetDParam(1, capacity); SetDParam(2, CT_MAIL); SetDParam(3, mail_capacity); DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_CAPACITY); } else { /* Note, if the default capacity is selected by the refit capacity * callback, then the capacity shown is likely to be incorrect. */ SetDParam(0, cargo); SetDParam(1, capacity); SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY); DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY); } y += FONT_HEIGHT_NORMAL; /* Running cost */ SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; return y; } /** * Display additional text from NewGRF in the purchase information window * @param left Left border of text bounding box * @param right Right border of text bounding box * @param y Top border of text bounding box * @param engine Engine to query the additional purchase information for * @return Bottom border of text bounding box */ static uint ShowAdditionalText(int left, int right, int y, EngineID engine) { uint16 callback = GetVehicleCallback(CBID_VEHICLE_ADDITIONAL_TEXT, 0, 0, engine, NULL); if (callback == CALLBACK_FAILED) return y; /* STR_BLACK_STRING is used to start the string with {BLACK} */ SetDParam(0, GetGRFStringID(GetEngineGRFID(engine), 0xD000 + callback)); PrepareTextRefStackUsage(0); uint result = DrawStringMultiLine(left, right, y, INT32_MAX, STR_BLACK_STRING); StopTextRefStackUsage(); return result; } /** * Draw the purchase info details of a vehicle at a given location. * @param left,right,y location where to draw the info * @param engine_number the engine of which to draw the info of * @return y after drawing all the text */ int DrawVehiclePurchaseInfo(int left, int right, int y, EngineID engine_number) { const Engine *e = Engine::Get(engine_number); YearMonthDay ymd; ConvertDateToYMD(e->intro_date, &ymd); bool refittable = IsArticulatedVehicleRefittable(engine_number); bool articulated_cargo = false; switch (e->type) { default: NOT_REACHED(); case VEH_TRAIN: if (e->u.rail.railveh_type == RAILVEH_WAGON) { y = DrawRailWagonPurchaseInfo(left, right, y, engine_number, &e->u.rail); } else { y = DrawRailEnginePurchaseInfo(left, right, y, engine_number, &e->u.rail); } articulated_cargo = true; break; case VEH_ROAD: y = DrawRoadVehPurchaseInfo(left, right, y, engine_number); articulated_cargo = true; break; case VEH_SHIP: y = DrawShipPurchaseInfo(left, right, y, engine_number, refittable); break; case VEH_AIRCRAFT: y = DrawAircraftPurchaseInfo(left, right, y, engine_number, refittable); break; } if (articulated_cargo) { /* Cargo type + capacity, or N/A */ int new_y = DrawCargoCapacityInfo(left, right, y, engine_number, refittable); if (new_y == y) { SetDParam(0, CT_INVALID); SetDParam(2, STR_EMPTY); DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY); y += FONT_HEIGHT_NORMAL; } else { y = new_y; } } /* Draw details that apply to all types except rail wagons. */ if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) { /* Design date - Life length */ SetDParam(0, ymd.year); SetDParam(1, e->GetLifeLengthInDays() / DAYS_IN_LEAP_YEAR); DrawString(left, right, y, STR_PURCHASE_INFO_DESIGNED_LIFE); y += FONT_HEIGHT_NORMAL; /* Reliability */ SetDParam(0, ToPercent16(e->reliability)); DrawString(left, right, y, STR_PURCHASE_INFO_RELIABILITY); y += FONT_HEIGHT_NORMAL; } /* Additional text from NewGRF */ y = ShowAdditionalText(left, right, y, engine_number); if (refittable) y = ShowRefitOptionsList(left, right, y, engine_number); return y; } /** * Engine drawing loop * @param type Type of vehicle (VEH_*) * @param l The left most location of the list * @param r The right most location of the list * @param y The top most location of the list * @param eng_list What engines to draw * @param min where to start in the list * @param max where in the list to end * @param selected_id what engine to highlight as selected, if any * @param show_count Whether to show the amount of engines or not * @param selected_group the group to list the engines of */ void DrawEngineList(VehicleType type, int l, int r, int y, const GUIEngineList *eng_list, uint16 min, uint16 max, EngineID selected_id, bool show_count, GroupID selected_group) { static const int sprite_widths[] = { 60, 60, 76, 67 }; static const int sprite_y_offsets[] = { -1, -1, -2, -2 }; /* Obligatory sanity checks! */ assert((uint)type < lengthof(sprite_widths)); assert_compile(lengthof(sprite_y_offsets) == lengthof(sprite_widths)); assert(max <= eng_list->Length()); bool rtl = _current_text_dir == TD_RTL; int step_size = GetEngineListHeight(type); int sprite_width = sprite_widths[type]; int sprite_x = (rtl ? r - sprite_width / 2 : l + sprite_width / 2) - 1; int sprite_y_offset = sprite_y_offsets[type] + step_size / 2; int text_left = l + (rtl ? WD_FRAMERECT_LEFT : sprite_width); int text_right = r - (rtl ? sprite_width : WD_FRAMERECT_RIGHT); int normal_text_y_offset = (step_size - FONT_HEIGHT_NORMAL) / 2; int small_text_y_offset = step_size - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1; for (; min < max; min++, y += step_size) { const EngineID engine = (*eng_list)[min]; /* Note: num_engines is only used in the autoreplace GUI, so it is correct to use _local_company here. */ const uint num_engines = GetGroupNumEngines(_local_company, selected_group, engine); SetDParam(0, engine); DrawString(text_left, text_right, y + normal_text_y_offset, STR_ENGINE_NAME, engine == selected_id ? TC_WHITE : TC_BLACK); DrawVehicleEngine(l, r, sprite_x, y + sprite_y_offset, engine, (show_count && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(engine, _local_company)); if (show_count) { SetDParam(0, num_engines); DrawString(text_left, text_right, y + small_text_y_offset, STR_TINY_BLACK_COMA, TC_FROMSTRING, SA_RIGHT); } } } struct BuildVehicleWindow : Window { VehicleType vehicle_type; union { RailTypeByte railtype; RoadTypes roadtypes; } filter; bool descending_sort_order; byte sort_criteria; bool listview_mode; EngineID sel_engine; EngineID rename_engine; GUIEngineList eng_list; CargoID cargo_filter[NUM_CARGO + 2]; ///< Available cargo filters; CargoID or CF_ANY or CF_NONE StringID cargo_filter_texts[NUM_CARGO + 3]; ///< Texts for filter_cargo, terminated by INVALID_STRING_ID byte cargo_filter_criteria; ///< Selected cargo filter int details_height; ///< Minimal needed height of the details panels (found so far). Scrollbar *vscroll; BuildVehicleWindow(const WindowDesc *desc, TileIndex tile, VehicleType type) : Window() { this->vehicle_type = type; this->window_number = tile == INVALID_TILE ? (int)type : tile; this->sel_engine = INVALID_ENGINE; this->sort_criteria = _last_sort_criteria[type]; this->descending_sort_order = _last_sort_order[type]; switch (type) { default: NOT_REACHED(); case VEH_TRAIN: this->filter.railtype = (tile == INVALID_TILE) ? RAILTYPE_END : GetRailType(tile); break; case VEH_ROAD: this->filter.roadtypes = (tile == INVALID_TILE) ? ROADTYPES_ALL : GetRoadTypes(tile); case VEH_SHIP: case VEH_AIRCRAFT: break; } this->listview_mode = (this->window_number <= VEH_END); this->CreateNestedTree(desc); this->vscroll = this->GetScrollbar(BUILD_VEHICLE_WIDGET_SCROLLBAR); /* If we are just viewing the list of vehicles, we do not need the Build button. * So we just hide it, and enlarge the Rename buton by the now vacant place. */ if (this->listview_mode) this->GetWidget<NWidgetStacked>(BUILD_VEHICLE_WIDGET_BUILD_SEL)->SetDisplayedPlane(SZSP_NONE); NWidgetCore *widget = this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_LIST); widget->tool_tip = STR_BUY_VEHICLE_TRAIN_LIST_TOOLTIP + type; widget = this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_BUILD); widget->widget_data = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_BUTTON + type; widget->tool_tip = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_TOOLTIP + type; widget = this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_RENAME); widget->widget_data = STR_BUY_VEHICLE_TRAIN_RENAME_BUTTON + type; widget->tool_tip = STR_BUY_VEHICLE_TRAIN_RENAME_TOOLTIP + type; this->details_height = ((this->vehicle_type == VEH_TRAIN) ? 10 : 9) * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM; this->FinishInitNested(desc, tile == INVALID_TILE ? (int)type : tile); this->owner = (tile != INVALID_TILE) ? GetTileOwner(tile) : _local_company; this->eng_list.ForceRebuild(); this->GenerateBuildList(); // generate the list, since we need it in the next line /* Select the first engine in the list as default when opening the window */ if (this->eng_list.Length() > 0) this->sel_engine = this->eng_list[0]; } /** Populate the filter list and set the cargo filter criteria. */ void SetCargoFilterArray() { uint filter_items = 0; /* Add item for disabling filtering. */ this->cargo_filter[filter_items] = CF_ANY; this->cargo_filter_texts[filter_items] = STR_PURCHASE_INFO_ALL_TYPES; filter_items++; /* Add item for vehicles not carrying anything, e.g. train engines. * This could also be useful for eyecandy vehicles of other types, but is likely too confusing for joe, */ if (this->vehicle_type == VEH_TRAIN) { this->cargo_filter[filter_items] = CF_NONE; this->cargo_filter_texts[filter_items] = STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE; filter_items++; } /* Collect available cargo types for filtering. */ const CargoSpec *cs; FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) { this->cargo_filter[filter_items] = cs->Index(); this->cargo_filter_texts[filter_items] = cs->name; filter_items++; } /* Terminate the filter list. */ this->cargo_filter_texts[filter_items] = INVALID_STRING_ID; /* If not found, the cargo criteria will be set to all cargos. */ this->cargo_filter_criteria = 0; /* Find the last cargo filter criteria. */ for (uint i = 0; i < filter_items; i++) { if (this->cargo_filter[i] == _last_filter_criteria[this->vehicle_type]) { this->cargo_filter_criteria = i; break; } } this->eng_list.SetFilterFuncs(_filter_funcs); this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY); } void OnInit() { this->SetCargoFilterArray(); } /** Filter the engine list against the currently selected cargo filter */ void FilterEngineList() { this->eng_list.Filter(this->cargo_filter[this->cargo_filter_criteria]); if (0 == this->eng_list.Length()) { // no engine passed through the filter, invalidate the previously selected engine this->sel_engine = INVALID_ENGINE; } else if (!this->eng_list.Contains(this->sel_engine)) { // previously selected engine didn't pass the filter, select the first engine of the list this->sel_engine = this->eng_list[0]; } } /** Filter a single engine */ bool FilterSingleEngine(EngineID eid) { CargoID filter_type = this->cargo_filter[this->cargo_filter_criteria]; return (filter_type == CF_ANY || CargoFilter(&eid, filter_type)); } /* Figure out what train EngineIDs to put in the list */ void GenerateBuildTrainList() { EngineID sel_id = INVALID_ENGINE; int num_engines = 0; int num_wagons = 0; this->filter.railtype = (this->listview_mode) ? RAILTYPE_END : GetRailType(this->window_number); this->eng_list.Clear(); /* Make list of all available train engines and wagons. * Also check to see if the previously selected engine is still available, * and if not, reset selection to INVALID_ENGINE. This could be the case * when engines become obsolete and are removed */ const Engine *e; FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) { EngineID eid = e->index; const RailVehicleInfo *rvi = &e->u.rail; if (this->filter.railtype != RAILTYPE_END && !HasPowerOnRail(rvi->railtype, this->filter.railtype)) continue; if (!IsEngineBuildable(eid, VEH_TRAIN, _local_company)) continue; /* Filter now! So num_engines and num_wagons is valid */ if (!FilterSingleEngine(eid)) continue; *this->eng_list.Append() = eid; if (rvi->railveh_type != RAILVEH_WAGON) { num_engines++; } else { num_wagons++; } if (eid == this->sel_engine) sel_id = eid; } this->sel_engine = sel_id; /* make engines first, and then wagons, sorted by ListPositionOfEngine() */ _internal_sort_order = false; EngList_Sort(&this->eng_list, TrainEnginesThenWagonsSorter); /* and then sort engines */ _internal_sort_order = this->descending_sort_order; EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], 0, num_engines); /* and finally sort wagons */ EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], num_engines, num_wagons); } /* Figure out what road vehicle EngineIDs to put in the list */ void GenerateBuildRoadVehList() { EngineID sel_id = INVALID_ENGINE; this->eng_list.Clear(); const Engine *e; FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) { EngineID eid = e->index; if (!IsEngineBuildable(eid, VEH_ROAD, _local_company)) continue; if (!HasBit(this->filter.roadtypes, HasBit(EngInfo(eid)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD)) continue; *this->eng_list.Append() = eid; if (eid == this->sel_engine) sel_id = eid; } this->sel_engine = sel_id; } /* Figure out what ship EngineIDs to put in the list */ void GenerateBuildShipList() { EngineID sel_id = INVALID_ENGINE; this->eng_list.Clear(); const Engine *e; FOR_ALL_ENGINES_OF_TYPE(e, VEH_SHIP) { EngineID eid = e->index; if (!IsEngineBuildable(eid, VEH_SHIP, _local_company)) continue; *this->eng_list.Append() = eid; if (eid == this->sel_engine) sel_id = eid; } this->sel_engine = sel_id; } /* Figure out what aircraft EngineIDs to put in the list */ void GenerateBuildAircraftList() { EngineID sel_id = INVALID_ENGINE; this->eng_list.Clear(); const Station *st = this->listview_mode ? NULL : Station::GetByTile(this->window_number); /* Make list of all available planes. * Also check to see if the previously selected plane is still available, * and if not, reset selection to INVALID_ENGINE. This could be the case * when planes become obsolete and are removed */ const Engine *e; FOR_ALL_ENGINES_OF_TYPE(e, VEH_AIRCRAFT) { EngineID eid = e->index; if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_company)) continue; /* First VEH_END window_numbers are fake to allow a window open for all different types at once */ if (!this->listview_mode && !CanVehicleUseStation(eid, st)) continue; *this->eng_list.Append() = eid; if (eid == this->sel_engine) sel_id = eid; } this->sel_engine = sel_id; } /* Generate the list of vehicles */ void GenerateBuildList() { if (!this->eng_list.NeedRebuild()) return; switch (this->vehicle_type) { default: NOT_REACHED(); case VEH_TRAIN: this->GenerateBuildTrainList(); this->eng_list.Compact(); this->eng_list.RebuildDone(); return; // trains should not reach the last sorting case VEH_ROAD: this->GenerateBuildRoadVehList(); break; case VEH_SHIP: this->GenerateBuildShipList(); break; case VEH_AIRCRAFT: this->GenerateBuildAircraftList(); break; } this->FilterEngineList(); _internal_sort_order = this->descending_sort_order; EngList_Sort(&this->eng_list, _sorter[this->vehicle_type][this->sort_criteria]); this->eng_list.Compact(); this->eng_list.RebuildDone(); } void OnClick(Point pt, int widget, int click_count) { switch (widget) { case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING: this->descending_sort_order ^= true; _last_sort_order[this->vehicle_type] = this->descending_sort_order; this->eng_list.ForceRebuild(); this->SetDirty(); break; case BUILD_VEHICLE_WIDGET_LIST: { uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, BUILD_VEHICLE_WIDGET_LIST); size_t num_items = this->eng_list.Length(); this->sel_engine = (i < num_items) ? this->eng_list[i] : INVALID_ENGINE; this->SetDirty(); if (click_count > 1 && !this->listview_mode) this->OnClick(pt, BUILD_VEHICLE_WIDGET_BUILD, 1); break; } case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN: { // Select sorting criteria dropdown menu uint32 hidden_mask = 0; /* Disable sorting by power or tractive effort when the original acceleration model for road vehicles is being used. */ if (this->vehicle_type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) { SetBit(hidden_mask, 3); // power SetBit(hidden_mask, 4); // tractive effort SetBit(hidden_mask, 8); // power by running costs } /* Disable sorting by tractive effort when the original acceleration model for trains is being used. */ if (this->vehicle_type == VEH_TRAIN && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) { SetBit(hidden_mask, 4); // tractive effort } ShowDropDownMenu(this, _sort_listing[this->vehicle_type], this->sort_criteria, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN, 0, hidden_mask); break; } case BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN: // Select cargo filtering criteria dropdown menu ShowDropDownMenu(this, this->cargo_filter_texts, this->cargo_filter_criteria, BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN, 0, 0); break; case BUILD_VEHICLE_WIDGET_BUILD: { EngineID sel_eng = this->sel_engine; if (sel_eng != INVALID_ENGINE) { CommandCallback *callback = (this->vehicle_type == VEH_TRAIN && RailVehInfo(sel_eng)->railveh_type == RAILVEH_WAGON) ? CcBuildWagon : CcBuildPrimaryVehicle; DoCommandP(this->window_number, sel_eng, 0, GetCmdBuildVeh(this->vehicle_type), callback); } break; } case BUILD_VEHICLE_WIDGET_RENAME: { EngineID sel_eng = this->sel_engine; if (sel_eng != INVALID_ENGINE) { this->rename_engine = sel_eng; SetDParam(0, sel_eng); ShowQueryString(STR_ENGINE_NAME, STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type, MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS); } break; } } } /** * Some data on this window has become invalid. * @param data Information about the changed data. * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details. */ virtual void OnInvalidateData(int data = 0, bool gui_scope = true) { if (!gui_scope) return; /* When switching to original acceleration model for road vehicles, clear the selected sort criteria if it is not available now. */ if (this->vehicle_type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL && this->sort_criteria > 7) { this->sort_criteria = 0; _last_sort_criteria[VEH_ROAD] = 0; } this->eng_list.ForceRebuild(); } virtual void SetStringParameters(int widget) const { switch (widget) { case BUILD_VEHICLE_WIDGET_CAPTION: if (this->vehicle_type == VEH_TRAIN && !this->listview_mode) { const RailtypeInfo *rti = GetRailTypeInfo(this->filter.railtype); SetDParam(0, rti->strings.build_caption); } else { SetDParam(0, (this->listview_mode ? STR_VEHICLE_LIST_AVAILABLE_TRAINS : STR_BUY_VEHICLE_TRAIN_ALL_CAPTION) + this->vehicle_type); } break; case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN: SetDParam(0, _sort_listing[this->vehicle_type][this->sort_criteria]); break; case BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN: SetDParam(0, this->cargo_filter_texts[this->cargo_filter_criteria]); } } virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) { switch (widget) { case BUILD_VEHICLE_WIDGET_LIST: resize->height = GetEngineListHeight(this->vehicle_type); size->height = 3 * resize->height; break; case BUILD_VEHICLE_WIDGET_PANEL: size->height = this->details_height; break; case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING: { Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data); d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better. d.height += padding.height; *size = maxdim(*size, d); break; } } } virtual void DrawWidget(const Rect &r, int widget) const { switch (widget) { case BUILD_VEHICLE_WIDGET_LIST: DrawEngineList(this->vehicle_type, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, &this->eng_list, this->vscroll->GetPosition(), min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->eng_list.Length()), this->sel_engine, false, DEFAULT_GROUP); break; case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING: this->DrawSortButtonState(BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING, this->descending_sort_order ? SBS_DOWN : SBS_UP); break; } } virtual void OnPaint() { this->GenerateBuildList(); this->vscroll->SetCount(this->eng_list.Length()); this->DrawWidgets(); if (!this->IsShaded()) { int needed_height = this->details_height; /* Draw details panels. */ if (this->sel_engine != INVALID_ENGINE) { NWidgetBase *nwi = this->GetWidget<NWidgetBase>(BUILD_VEHICLE_WIDGET_PANEL); int text_end = DrawVehiclePurchaseInfo(nwi->pos_x + WD_FRAMETEXT_LEFT, nwi->pos_x + nwi->current_x - WD_FRAMETEXT_RIGHT, nwi->pos_y + WD_FRAMERECT_TOP, this->sel_engine); needed_height = max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM); } if (needed_height != this->details_height) { // Details window are not high enough, enlarge them. int resize = needed_height - this->details_height; this->details_height = needed_height; this->ReInit(0, resize); return; } } } virtual void OnQueryTextFinished(char *str) { if (str == NULL) return; DoCommandP(0, this->rename_engine, 0, CMD_RENAME_ENGINE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN_TYPE + this->vehicle_type), NULL, str); } virtual void OnDropdownSelect(int widget, int index) { switch (widget) { case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN: if (this->sort_criteria != index) { this->sort_criteria = index; _last_sort_criteria[this->vehicle_type] = this->sort_criteria; this->eng_list.ForceRebuild(); } break; case BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN: // Select a cargo filter criteria if (this->cargo_filter_criteria != index) { this->cargo_filter_criteria = index; _last_filter_criteria[this->vehicle_type] = this->cargo_filter[this->cargo_filter_criteria]; /* deactivate filter if criteria is 'Show All', activate it otherwise */ this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY); this->eng_list.ForceRebuild(); } break; } this->SetDirty(); } virtual void OnResize() { this->vscroll->SetCapacityFromWidget(this, BUILD_VEHICLE_WIDGET_LIST); this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START); } }; static const WindowDesc _build_vehicle_desc( WDP_AUTO, 240, 268, WC_BUILD_VEHICLE, WC_NONE, WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION, _nested_build_vehicle_widgets, lengthof(_nested_build_vehicle_widgets) ); void ShowBuildVehicleWindow(TileIndex tile, VehicleType type) { /* We want to be able to open both Available Train as Available Ships, * so if tile == INVALID_TILE (Available XXX Window), use 'type' as unique number. * As it always is a low value, it won't collide with any real tile * number. */ uint num = (tile == INVALID_TILE) ? (int)type : tile; assert(IsCompanyBuildableVehicleType(type)); DeleteWindowById(WC_BUILD_VEHICLE, num); new BuildVehicleWindow(&_build_vehicle_desc, tile, type); }
34.739855
301
0.728208
trademarks
605e265b864bd9d680900d13c2b8b4d4909505c8
1,320
hpp
C++
src/FrozenWasteland.hpp
miRackModular/FrozenWasteland
2e21f41cb121c2a4036b509a26061bf7981d4d9a
[ "CC0-1.0" ]
null
null
null
src/FrozenWasteland.hpp
miRackModular/FrozenWasteland
2e21f41cb121c2a4036b509a26061bf7981d4d9a
[ "CC0-1.0" ]
null
null
null
src/FrozenWasteland.hpp
miRackModular/FrozenWasteland
2e21f41cb121c2a4036b509a26061bf7981d4d9a
[ "CC0-1.0" ]
null
null
null
#include "rack.hpp" using namespace rack; extern Plugin *pluginInstance; extern Model *modelBPMLFO; extern Model *modelBPMLFO2; extern Model *modelBPMLFOPhaseExpander; extern Model *modelDamianLillard; extern Model *modelEverlastingGlottalStopper; extern Model *modelHairPick; extern Model *modelLissajousLFO; extern Model *modelMrBlueSky; extern Model *modelTheOneRingModulator; extern Model *modelPhasedLockedLoop; extern Model *modelPortlandWeather; extern Model *modelProbablyNote; //extern Model *modelProbablyNoteArabic; extern Model *modelProbablyNoteBP; //extern Model *modelProbablyNoteIndian; extern Model *modelPNChordExpander; extern Model *modelQuadAlgorithmicRhythm; extern Model *modelQARGrooveExpander; extern Model *modelQARProbabilityExpander; extern Model *modelQuantussyCell; extern Model *modelSeedsOfChange; extern Model *modelSeedsOfChangeCVExpander; extern Model *modelSeedsOfChangeGateExpander; extern Model *modelStringTheory; extern Model *modelRouletteLFO; extern Model *modelSeriouslySlowLFO; extern Model *modelVoxInhumana; extern Model *modelVoxInhumanaExpander; extern Model *modelCDCSeriouslySlowLFO; namespace old { extern Model *modelLissajousLFO_old; extern Model *modelRouletteLFO_old; extern Model *modelQuadGolombRulerRhythm_old; extern Model *modelQuadEuclideanRhythm_old; }
30
45
0.852273
miRackModular
605e4b58ca412594170dcd9f6562cfb13e8dde7f
3,025
ipp
C++
implement/oglplus/enums/precision_type_def.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/oglplus/enums/precision_type_def.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/oglplus/enums/precision_type_def.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
// File implement/oglplus/enums/precision_type_def.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/precision_type.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2017 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif #if defined GL_LOW_FLOAT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined LowFloat # pragma push_macro("LowFloat") # undef LowFloat OGLPLUS_ENUM_CLASS_VALUE(LowFloat, GL_LOW_FLOAT) # pragma pop_macro("LowFloat") # else OGLPLUS_ENUM_CLASS_VALUE(LowFloat, GL_LOW_FLOAT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_MEDIUM_FLOAT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined MediumFloat # pragma push_macro("MediumFloat") # undef MediumFloat OGLPLUS_ENUM_CLASS_VALUE(MediumFloat, GL_MEDIUM_FLOAT) # pragma pop_macro("MediumFloat") # else OGLPLUS_ENUM_CLASS_VALUE(MediumFloat, GL_MEDIUM_FLOAT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_HIGH_FLOAT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined HighFloat # pragma push_macro("HighFloat") # undef HighFloat OGLPLUS_ENUM_CLASS_VALUE(HighFloat, GL_HIGH_FLOAT) # pragma pop_macro("HighFloat") # else OGLPLUS_ENUM_CLASS_VALUE(HighFloat, GL_HIGH_FLOAT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_LOW_INT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined LowInt # pragma push_macro("LowInt") # undef LowInt OGLPLUS_ENUM_CLASS_VALUE(LowInt, GL_LOW_INT) # pragma pop_macro("LowInt") # else OGLPLUS_ENUM_CLASS_VALUE(LowInt, GL_LOW_INT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_MEDIUM_INT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined MediumInt # pragma push_macro("MediumInt") # undef MediumInt OGLPLUS_ENUM_CLASS_VALUE(MediumInt, GL_MEDIUM_INT) # pragma pop_macro("MediumInt") # else OGLPLUS_ENUM_CLASS_VALUE(MediumInt, GL_MEDIUM_INT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_HIGH_INT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined HighInt # pragma push_macro("HighInt") # undef HighInt OGLPLUS_ENUM_CLASS_VALUE(HighInt, GL_HIGH_INT) # pragma pop_macro("HighInt") # else OGLPLUS_ENUM_CLASS_VALUE(HighInt, GL_HIGH_INT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif
26.077586
62
0.798347
jnbrq
60671f89364864ec9dea61361a7a3a8f7fe65f6a
1,822
hpp
C++
DDMallocDetector/MallocDetector/Classes/detector/MallocCollectorHelper.hpp
djs66256/DDMallocDetector
f719cdb7abbd8c9590c0fdb68361b943c1674adf
[ "BSD-2-Clause" ]
10
2018-04-08T16:37:17.000Z
2021-07-13T11:04:38.000Z
DDMallocDetector/MallocDetector/Classes/detector/MallocCollectorHelper.hpp
djs66256/DDMallocDetector
f719cdb7abbd8c9590c0fdb68361b943c1674adf
[ "BSD-2-Clause" ]
null
null
null
DDMallocDetector/MallocDetector/Classes/detector/MallocCollectorHelper.hpp
djs66256/DDMallocDetector
f719cdb7abbd8c9590c0fdb68361b943c1674adf
[ "BSD-2-Clause" ]
2
2019-02-13T09:21:41.000Z
2021-07-13T11:04:41.000Z
// // MallocCollectorHelper.hpp // cfunction // // Created by hzduanjiashun on 2018/3/28. // Copyright © 2018年 Daniel. All rights reserved. // #ifndef MallocCollectorHelper_hpp #define MallocCollectorHelper_hpp #include <stdio.h> #include <memory> #include <malloc/malloc.h> #include "MallocMemory.hpp" namespace MD { namespace CollectorDefault { template <class _S> struct CollectorChecker { static int64_t max() { return 1024*1024; } static void overflow(_S* storage) { } }; } template <class _S, class _I, class _C = CollectorDefault::CollectorChecker<_S>> class Collector { public: typedef _S storage_type; typedef _I item_type; typedef _C checker_type; Collector(storage_type* s) : s_(s) { i_.start(); } Collector& setZone(malloc_zone_t *z) { i_.zone = z; return *this; } Collector& setAction(Action act) { i_.action = act; return *this; } Collector& setSize(std::int64_t size) { i_.size = size; return *this; } Collector& set(malloc_zone_t *z, Action act, std::int64_t size) { i_.zone = z; i_.action = act; i_.size = size; return *this; } ~Collector() { i_.stop(); int64_t cnt = s_->collect(std::move(i_)); if (cnt > checker_type::max()) { checker_type::overflow(s_); } } private: storage_type* s_; item_type i_; }; } #endif /* MallocCollectorHelper_hpp */
22.775
84
0.502195
djs66256
6068bfd22ae93d26a163098241f831908c014575
6,504
cxx
C++
PMD/anal/AliPMDOfflineCalibTask.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
PMD/anal/AliPMDOfflineCalibTask.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
PMD/anal/AliPMDOfflineCalibTask.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /************************************ * AliPMD offline calibration task * * Satyajit Jena, IIT Bombay * [email protected] * Fri Feb 12 13:30:19 IST 2010 * ************************************/ #include "TChain.h" #include "TList.h" #include "TFile.h" #include "TTree.h" #include "TH1F.h" #include "TCanvas.h" #include "AliAnalysisTask.h" #include "AliAnalysisManager.h" #include "AliVEvent.h" #include "AliESD.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "TObjArray.h" #include "AliPMDOfflineCalibTask.h" ClassImp(AliPMDOfflineCalibTask) //________________________________________________________________________ AliPMDOfflineCalibTask::AliPMDOfflineCalibTask(const char *name) : AliAnalysisTaskSE(name), fListOfHistos(0), fPmdCalibAdcP(0), fPmdCalibAdcC(0), fPmdCalibEntP(0), fPmdCalibEntC(0), fNEvents(0), fSelectedTrigger(new TObjArray()), fRejected(kTRUE) { // Constructor DefineOutput(1, TList::Class()); } //________________________________________________________________________ void AliPMDOfflineCalibTask::UserCreateOutputObjects() { fListOfHistos = new TList(); fNEvents = new TH1I("hNEvents","Events Statistic", 3, 0, 5); fPmdCalibAdcP = new TH1F("fPmdCalibAdcP", "PMD Calibration ADC fill for PRE", 234795, 0, 234795); fPmdCalibAdcP->GetYaxis()->SetTitle("ADC"); fPmdCalibAdcP->GetXaxis()->SetTitle("Cells in SMN-ROW-COL"); fPmdCalibAdcC = new TH1F("fPmdCalibAdcC", "PMD Calibration ADC fill for CPV", 234795, 0, 234795); fPmdCalibAdcC->GetYaxis()->SetTitle("ADC"); fPmdCalibAdcC->GetXaxis()->SetTitle("Cells in SMN-ROW-COL"); fPmdCalibEntP = new TH1F("fPmdCalibEntP", "PMD Calibration Entries fill for PRE", 234795, 0, 234795); fPmdCalibEntP->GetYaxis()->SetTitle("Frequescy"); fPmdCalibEntP->GetXaxis()->SetTitle("Cells in SMN-ROW-COL"); fPmdCalibEntC = new TH1F("fPmdCalibEntC", "PMD Calibration Entries fill for CPV", 234795, 0, 234795); fPmdCalibEntC->GetYaxis()->SetTitle("Frequescy "); fPmdCalibEntC->GetXaxis()->SetTitle("Cells in SMN-ROW-COL"); fListOfHistos->Add(fPmdCalibAdcP); fListOfHistos->Add(fPmdCalibAdcC); fListOfHistos->Add(fPmdCalibEntP); fListOfHistos->Add(fPmdCalibEntC); fListOfHistos->Add(fNEvents); } //________________________________________________________________________ void AliPMDOfflineCalibTask::UserExec(Option_t *) { AliVEvent *event = InputEvent(); if (!event) { Printf("ERROR: Could not retrieve event"); return; } fNEvents->Fill(1); AliESDEvent* pmdesd = dynamic_cast<AliESDEvent*>(event); if(!pmdesd) return; fNEvents->Fill(2); Bool_t pass = kTRUE; Int_t numberOfTriggerSelected = fSelectedTrigger->GetEntriesFast(); if(fRejected) { pass = kTRUE; for(Int_t k = 0; k < numberOfTriggerSelected; k++) { const TObjString *const obString = (TObjString*)fSelectedTrigger->At(k); const TString tString = obString->GetString(); if(pmdesd->IsTriggerClassFired((const char*)tString)) { pass = kFALSE; } } } else { pass = kFALSE; for(Int_t k = 0; k < numberOfTriggerSelected; k++) { const TObjString *const obString=(TObjString*)fSelectedTrigger->At(k); const TString tString = obString->GetString(); if(pmdesd->IsTriggerClassFired((const char*)tString)) { pass = kTRUE; } } } if(!pass) { PostData(1, fListOfHistos); return; } fNEvents->Fill(3); Int_t npmdcl = pmdesd->GetNumberOfPmdTracks(); if(npmdcl < 1) fNEvents->Fill(4); while (npmdcl--) { AliESDPmdTrack *pmdtr = pmdesd->GetPmdTrack(npmdcl); Int_t det = pmdtr->GetDetector(); Int_t smn = pmdtr->GetSmn(); Float_t adc = pmdtr->GetClusterADC(); Float_t sTag = pmdtr->GetClusterSigmaX(); Float_t sRowCol = pmdtr->GetClusterSigmaY(); Float_t rc = smn*10000 + sRowCol; if(adc > 1200.) continue; if(sTag > 999. && sTag < 1000.) { if(det == 0) { fPmdCalibAdcP->Fill(rc,adc); fPmdCalibEntP->Fill(rc); } else if(det == 1) { fPmdCalibAdcC->Fill(rc,adc); fPmdCalibEntC->Fill(rc); } } } PostData(1, fListOfHistos); } //________________________________________________________________________ void AliPMDOfflineCalibTask::Terminate(Option_t *) { fListOfHistos = dynamic_cast<TList*>(GetOutputData(1)); fPmdCalibAdcP = dynamic_cast<TH1F*>(fListOfHistos->At(0)); if(!fPmdCalibAdcP) { printf("ERROR: No ADC File Generated for PMD-PRE "); return; } fPmdCalibAdcC = dynamic_cast<TH1F*>(fListOfHistos->At(1)); if(!fPmdCalibAdcC) { printf("ERROR: No ADC File Generated for PMD-CPV "); return; } fPmdCalibEntP = dynamic_cast<TH1F*>(fListOfHistos->At(2)); if(!fPmdCalibEntP) { printf("ERROR: No Entry File Generated for PMD-PRE "); printf(" No fhXyPRE "); return; } fPmdCalibEntC = dynamic_cast<TH1F*>(fListOfHistos->At(3)); if(!fPmdCalibEntC) { printf("ERROR: No Entry File Generated for PMD-CPV "); return; } fNEvents = dynamic_cast<TH1I*>(fListOfHistos->At(4)); if(!fNEvents) { printf("ERROR: No Entry File Generated for Event Counter "); return; } Info("AliPMDOfflineCalibTask","PMD offline Calibration Successfully finished"); }
29.165919
103
0.628998
AllaMaevskaya
60695c9676c50e738917c4abd03ecb8d3dd5beea
671
cpp
C++
Excercises_Source/2.Bitfields.cpp
ChenpoHU/C-Excercies_OOP
b009b5a8da82fda6b3918f9f77b1d62ad0a1f876
[ "MIT" ]
null
null
null
Excercises_Source/2.Bitfields.cpp
ChenpoHU/C-Excercies_OOP
b009b5a8da82fda6b3918f9f77b1d62ad0a1f876
[ "MIT" ]
null
null
null
Excercises_Source/2.Bitfields.cpp
ChenpoHU/C-Excercies_OOP
b009b5a8da82fda6b3918f9f77b1d62ad0a1f876
[ "MIT" ]
null
null
null
#include <iostream> struct BitFieldStruct { unsigned int a : 4; unsigned int b : 3; }; int main() { BitFieldStruct x; x.a = 06; x.b = x.a | 3; // | bitwise OR, || logical OR ; & bitwise AND, && logicalwise AND std::cout << x.a << '\n' << std::endl;// converted to unsigned and then displayed std::cout << x.b << '\n' << std::endl;// converted to unsigned and then displayed } // 0 1 1 is 3 // 1 1 0 is 6 bitwise OR of 3 and 6 is: // 1 1 1 is 7 //may save space but cost time in comparison to byte alignment // bitwise logical // OR | || //AND & && //XOR ^ != //NEG ~ !
25.807692
83
0.520119
ChenpoHU
606a40d66e7f65605f06cce15bba65817f404485
1,240
cpp
C++
extras/lib_info/SdFat_Gre/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp
UTSAAH/Dhwani-HA_Library
f182d8b6571d48b1e506637684844eb12e0a791c
[ "MIT" ]
181
2019-09-20T15:49:09.000Z
2022-03-23T01:27:29.000Z
Transmitters/Old Version/X_CTRL_STM32F4xx/X_CTRL_GUN/Libraries/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp
DogDod/X-CTRL
683ffe3b40222e1da6ff156b6595c691cd09fec1
[ "MIT" ]
7
2020-03-06T19:37:07.000Z
2020-05-05T20:33:32.000Z
Transmitters/Old Version/X_CTRL_STM32F4xx/X_CTRL_GUN/Libraries/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp
DogDod/X-CTRL
683ffe3b40222e1da6ff156b6595c691cd09fec1
[ "MIT" ]
75
2019-10-25T02:53:27.000Z
2022-03-23T01:25:00.000Z
// User data functions. Modify these functions for your data items. #include "UserTypes.h" #include "Wire.h" #include "I2Cdev.h" #include "MPU6050.h" //------------------------------------------------------------------------------ MPU6050 mpu; static uint32_t startMicros; // Acquire a data record. void acquireData(data_t* data) { data->time = micros(); mpu.getMotion6(&data->ax, &data->ay, &data->az, &data->gx, &data->gy, &data->gz); } // setup AVR I2C void userSetup() { #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE Wire.begin(); Wire.setClock(400000); #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE Fastwire::setup(400, true); #endif mpu.initialize(); } // Print a data record. void printData(Print* pr, data_t* data) { if (startMicros == 0) { startMicros = data->time; } pr->print(data->time- startMicros); pr->write(','); pr->print(data->ax); pr->write(','); pr->print(data->ay); pr->write(','); pr->print(data->az); pr->write(','); pr->print(data->gx); pr->write(','); pr->print(data->gy); pr->write(','); pr->println(data->gz); } // Print data header. void printHeader(Print* pr) { startMicros = 0; pr->println(F("micros,ax,ay,az,gx,gy,gz")); }
23.846154
80
0.592742
UTSAAH
606ffb194da6ff4a1ca462fd0eaf631574c13785
1,074
cpp
C++
math/normal3.cpp
masrtis/eyebeam
a9ea111c7958838c19c0b26ea1961f119b4f91f1
[ "MIT" ]
null
null
null
math/normal3.cpp
masrtis/eyebeam
a9ea111c7958838c19c0b26ea1961f119b4f91f1
[ "MIT" ]
4
2020-12-13T14:55:24.000Z
2021-03-10T01:47:36.000Z
math/normal3.cpp
masrtis/eyebeam
a9ea111c7958838c19c0b26ea1961f119b4f91f1
[ "MIT" ]
null
null
null
#include "normal3.h" #include <cmath> #include <ostream> namespace eyebeam { Normal3 operator+(const Normal3& lhs, const Normal3& rhs) { auto result(lhs); result += rhs; return result; } Normal3 operator-(const Normal3& lhs, const Normal3& rhs) { auto result(lhs); result -= rhs; return result; } Normal3 operator*(const Normal3& lhs, float rhs) { auto result(lhs); result *= rhs; return result; } Normal3 operator*(float lhs, const Normal3& rhs) { auto result(rhs); result *= lhs; return result; } Normal3 operator/(const Normal3& lhs, float rhs) { auto result(lhs); result /= rhs; return result; } float length(const Normal3& normal) { return std::sqrt(lengthSquared(normal)); } void normalize(Normal3& normal) { normal /= length(normal); } Normal3 norm(Normal3 normal) { normalize(normal); return normal; } std::ostream& operator<<(std::ostream& os, const Normal3& out) { os << "(" << out.x() << ", " << out.y() << ", " << out.z() << ")"; return os; } } // namespace eyebeam
16.029851
70
0.623836
masrtis
6072d2fe54028b06e9ebadf3c78dda234ef29f64
15,068
cpp
C++
http/gzip_mem.cpp
hdsy/public
20ee6559ba4f84a2356785fc53b54c1a4dcdf354
[ "Apache-2.0" ]
null
null
null
http/gzip_mem.cpp
hdsy/public
20ee6559ba4f84a2356785fc53b54c1a4dcdf354
[ "Apache-2.0" ]
null
null
null
http/gzip_mem.cpp
hdsy/public
20ee6559ba4f84a2356785fc53b54c1a4dcdf354
[ "Apache-2.0" ]
1
2020-05-10T23:42:34.000Z
2020-05-10T23:42:34.000Z
#include <stdio.h> #include <zlib.h> #include <string.h> #include <stdlib.h> #include "gzip_mem.h" #define OF(args) args #define OS_CODE 3 // unix #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif /* default memLevel */ #define Z_BUFSIZE 16384 #define ALLOC(size) malloc( size ) #define TRYFREE(p) free( p ) static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ /* gzip flag byte */ #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ #define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ #define ORIG_NAME 0x08 /* bit 3 set: original file name present */ #define COMMENT 0x10 /* bit 4 set: file comment present */ #define RESERVED 0xE0 /* bits 5..7: reserved */ typedef int ( * XGZFILE_PROC_READ )( void* user_cb , void* , int len ); typedef int ( * XGZFILE_PROC_WRITE )( void* user_cb , const void* , int len ); typedef struct xmem_gzstream { z_stream stream; int z_err; /* error code for last stream operation */ int z_eof; /* set if end of input file */ XGZFILE_PROC_READ proc_read ; XGZFILE_PROC_WRITE proc_write; void* user_cb ; Byte *inbuf; /* input buffer */ Byte *outbuf; /* output buffer */ uLong crc; /* crc32 of uncompressed data */ char *msg; /* error message */ int transparent; /* 1 if input file is not a .gz file */ char mode; /* 'w' or 'r' */ long startpos; /* start of compressed data in file (header skipped) */ } xmem_gzstream; static int get_byte OF((xmem_gzstream *s)); static int check_header OF((xmem_gzstream *s)); /*! return bytes of read. */ static int destroy OF((xmem_gzstream *s)); static void putLong OF((xmem_gzstream *s , uLong x)); static uLong getLong OF((xmem_gzstream *s)); xmem_gzstream* XGZFILE_open( XGZFILE_PROC_READ proc_read , XGZFILE_PROC_WRITE proc_write , void* user_cb , int create_flag , int level ) { int err; int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ static Byte simpleheader[] = { 0x1f, 0x8b, Z_DEFLATED , 0 , 0 , 0 , 0 , 0 , 0 , OS_CODE }; xmem_gzstream *s; if( (create_flag&&!proc_write) || (!create_flag&&!proc_read) ) return Z_NULL; s = (xmem_gzstream *)ALLOC( sizeof(xmem_gzstream) ); if( !s ) return Z_NULL; s->stream.zalloc = (alloc_func)0; s->stream.zfree = (free_func)0; s->stream.opaque = (voidpf)0; s->stream.next_in = s->inbuf = Z_NULL; s->stream.next_out = s->outbuf = Z_NULL; s->stream.avail_in = s->stream.avail_out = 0; s->proc_read = proc_read ; s->proc_write = proc_write; s->user_cb = user_cb ; s->z_err = Z_OK; s->z_eof = 0; s->crc = crc32(0L, Z_NULL, 0); s->msg = NULL; s->transparent = 0; s->mode = create_flag ? 'w' : 'r'; if( create_flag ) { err = deflateInit2(&(s->stream), level, Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); if (err != Z_OK || s->outbuf == Z_NULL) { return destroy(s), (xmem_gzstream*)Z_NULL; } } else { s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); err = inflateInit2(&(s->stream), -MAX_WBITS); if (err != Z_OK || s->inbuf == Z_NULL) { return destroy(s), (xmem_gzstream*)Z_NULL; } } s->stream.avail_out = Z_BUFSIZE; if( create_flag ) { s->proc_write( s->user_cb , simpleheader , 10 ); s->startpos = 10L; } else { s->startpos = check_header(s); } return (xmem_gzstream*)s; } int XGZFILE_read ( xmem_gzstream* file , void* buf , int len ) { xmem_gzstream *s = (xmem_gzstream*)file; Bytef *start = (Bytef*)buf; /* starting point for crc computation */ Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ if( !s || s->mode != 'r' ) return Z_STREAM_ERROR; if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; if (s->z_err == Z_STREAM_END) return 0; /* -1 */ next_out = (Byte*)buf; s->stream.next_out = (Bytef*)buf; s->stream.avail_out = len; while (s->stream.avail_out != 0) { if (s->transparent) { /* Copy first the lookahead bytes: */ uInt n = s->stream.avail_in; if (n > s->stream.avail_out) n = s->stream.avail_out; if (n > 0) { memcpy(s->stream.next_out, s->stream.next_in, n); next_out += n; s->stream.next_out = next_out; s->stream.next_in += n; s->stream.avail_out -= n; s->stream.avail_in -= n; } if (s->stream.avail_out > 0) { s->stream.avail_out -= s->proc_read( s->user_cb , next_out , s->stream.avail_out ); } len -= s->stream.avail_out; s->stream.total_in += (uLong)len; s->stream.total_out += (uLong)len; if (len == 0) s->z_eof = 1; return (int)len; } if (s->stream.avail_in == 0 && !s->z_eof) { /* errno = 0; */ s->stream.avail_in = s->proc_read( s->user_cb , s->inbuf , Z_BUFSIZE ); if (s->stream.avail_in == 0) { s->z_eof = 1; } s->stream.next_in = s->inbuf; } s->z_err = inflate(&(s->stream), Z_NO_FLUSH); if (s->z_err == Z_STREAM_END) { /* Check CRC and original size */ s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); start = s->stream.next_out; if (getLong(s) != s->crc) { s->z_err = Z_DATA_ERROR; } else { (void)getLong(s); /* The uncompressed length returned by above getlong() may * be different from s->stream.total_out) in case of * concatenated .gz files. Check for such files: */ check_header(s); if (s->z_err == Z_OK) { uLong total_in = s->stream.total_in; uLong total_out = s->stream.total_out; inflateReset(&(s->stream)); s->stream.total_in = total_in; s->stream.total_out = total_out; s->crc = crc32(0L, Z_NULL, 0); } } } if (s->z_err != Z_OK || s->z_eof) break; } s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); return len - s->stream.avail_out ; } int XGZFILE_write( xmem_gzstream* file , const void* buf , int len ) { xmem_gzstream *s = (xmem_gzstream*)file; if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; s->stream.next_in = (Bytef*)buf; s->stream.avail_in = len; while (s->stream.avail_in != 0) { if (s->stream.avail_out == 0) { s->stream.next_out = s->outbuf; if( s->proc_write( s->user_cb , s->outbuf , Z_BUFSIZE ) != Z_BUFSIZE ) { s->z_err = Z_ERRNO; break; } s->stream.avail_out = Z_BUFSIZE; } s->z_err = deflate(&(s->stream), Z_NO_FLUSH); if (s->z_err != Z_OK) break; } s->crc = crc32(s->crc, (const Bytef *)buf, len); return (int)(len - s->stream.avail_in); } int XGZFILE_flush( xmem_gzstream* file , int flush ) { xmem_gzstream *s = (xmem_gzstream*)file; uInt len; int done = 0; if( !s || s->mode != 'w' ) return Z_STREAM_ERROR; s->stream.avail_in = 0; /* should be zero already anyway */ for (;;) { len = Z_BUFSIZE - s->stream.avail_out; if (len != 0) { if( s->proc_write( s->user_cb , s->outbuf , len ) != (int)len ) { s->z_err = Z_ERRNO; return Z_ERRNO; } s->stream.next_out = s->outbuf; s->stream.avail_out = Z_BUFSIZE; } if (done) break; s->z_err = deflate(&(s->stream), flush); /* Ignore the second of two consecutive flushes: */ if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; /* deflate has finished flushing only when it hasn't used up * all the available space in the output buffer: */ done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; } return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; } int XGZFILE_eof ( xmem_gzstream* file ) { xmem_gzstream *s = (xmem_gzstream*)file; return (s == NULL || s->mode != 'r') ? 0 : s->z_eof; } int XGZFILE_close( xmem_gzstream* file ) { int err; xmem_gzstream *s = (xmem_gzstream*)file; if (s == NULL) return Z_STREAM_ERROR; if (s->mode == 'w') { err = XGZFILE_flush (file, Z_FINISH); if (err != Z_OK) return destroy((xmem_gzstream*)file); putLong (s , s->crc); putLong (s , s->stream.total_in); } return destroy((xmem_gzstream*)file); } static int get_byte (xmem_gzstream *s) { if (s->z_eof) return -1; if (s->stream.avail_in == 0) { /* errno = 0; */ s->stream.avail_in = s->proc_read( s->user_cb , s->inbuf , Z_BUFSIZE ); if (s->stream.avail_in == 0) { s->z_eof = 1; return -1; } s->stream.next_in = s->inbuf; } s->stream.avail_in--; return *(s->stream.next_in)++; } static void putLong (xmem_gzstream *s, uLong x) { int n; char ch; for (n = 0; n < 4; n++) { ch = (char)(x & 0xff); s->proc_write( s->user_cb , &ch , 1 ); x >>= 8; } } static uLong getLong (xmem_gzstream *s) { uLong x = (uLong)get_byte(s); int c; x += ((uLong)get_byte(s))<<8; x += ((uLong)get_byte(s))<<16; c = get_byte(s); if (c == -1) s->z_err = Z_DATA_ERROR; x += ((uLong)c)<<24; return x; } static int destroy (xmem_gzstream *s) { int err = Z_OK; if (!s) return Z_STREAM_ERROR; TRYFREE(s->msg); if (s->stream.state != NULL) { if (s->mode == 'w') { err = deflateEnd(&(s->stream)); } else if (s->mode == 'r') { err = inflateEnd(&(s->stream)); } } if (s->z_err < 0) err = s->z_err; TRYFREE(s->inbuf); TRYFREE(s->outbuf); TRYFREE(s); return err; } static int check_header (xmem_gzstream *s) /*! return bytes of read. */ { int method; /* method byte */ int flags; /* flags byte */ uInt len; int c; int lenret; int ch; /* Check the gzip magic header */ for (len = 0; len < 2; len++) { c = get_byte(s); if (c != gz_magic[len]) { if (len != 0) s->stream.avail_in++, s->stream.next_in--; if (c != -1) { s->stream.avail_in++, s->stream.next_in--; s->transparent = 1; } s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END; return len; } } lenret = 2; method = get_byte(s); if( method != -1 ) ++lenret; flags = get_byte(s); if( flags != -1 ) ++lenret; if (method != Z_DEFLATED || (flags & RESERVED) != 0) { s->z_err = Z_DATA_ERROR; return lenret; } /* Discard time, xflags and OS code: */ for (len = 0; len < 6; len++) { ch = get_byte(s); if( ch != -1 ) ++lenret; else { s->z_err = Z_DATA_ERROR; return lenret; } } if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ ch = get_byte(s); if( ch != -1 ) ++lenret; len = ch; ch = get_byte(s); if( ch != -1 ) ++lenret; len += ((uInt)ch)<<8; /* len is garbage if -1 but the loop below will quit anyway */ while (len-- != 0 && get_byte(s) != -1) ++lenret; } if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ while ((c = get_byte(s)) != 0 && c != -1) ++lenret; } if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ while ((c = get_byte(s)) != 0 && c != -1) ++lenret; } if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ for (len = 0; len < 2; len++) if( get_byte(s) != -1 ) ++lenret; } s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; return lenret; } typedef unsigned char XU8; static XU8 z_input[] = { 0x1F,0x8B,0x08,0x08,0x59,0x96,0x9C,0x46,0x00,0x03,0x74,0x35,0x00,0x2B,0xC9,0xC8 ,0x2C,0x56,0x00,0xA2,0x44,0x85,0x92,0xD4,0xE2,0x12,0x85,0xB4,0xCC,0x9C,0x54,0x5E ,0xAE,0x12,0x4C,0x41,0x00,0x9A,0xA3,0x62,0x77,0x28,0x00,0x00,0x00 }; static XU8 x_text[] = { 0x74,0x68,0x69,0x73,0x20,0x69,0x73,0x20,0x61,0x20,0x74,0x65,0x73,0x74,0x20,0x66 ,0x69,0x6C,0x65,0x0D,0x0A,0x74,0x68,0x69,0x73,0x20,0x69,0x73,0x20,0x61,0x20,0x74 ,0x65,0x73,0x74,0x20,0x66,0x69,0x6C,0x65 }; const static string * pstring = NULL; /* static int X_test_read( void* user_cb , void* buff , int len ) { if( *(int*)user_cb >= sizeof( z_input ) || len <= 0 ) return 0; if( len > (int)(sizeof( z_input ) - *(int*)user_cb) ) len = sizeof( z_input ) - *(int*)user_cb; memcpy( buff , z_input + *(int*)user_cb , len ); *(int*)user_cb += len; return len; } //*/ static int X_test_read( void* user_cb , void* buff , int len ) { if(pstring == NULL) return 0; if( *(int*)user_cb >= pstring->size() || len <= 0 ) return 0; if( len > (int)(pstring->size() - *(int*)user_cb) ) len = pstring->size() - *(int*)user_cb; memcpy( buff , pstring->data() + *(int*)user_cb , len ); *(int*)user_cb += len; return len; } /* int main() { int off = 0 , len; XU8 buff[100]; xmem_gzstream* strm = XGZFILE_open( X_test_read , NULL , &off , 0 , -1 ); len = XGZFILE_read( strm , buff , sizeof( buff ) ); XGZFILE_close( strm ); if( len != sizeof( x_text ) || memcmp( x_text , buff , len ) ) printf( "error\n" ); return 0; } //*/ string GUnzip(const string & zip_mem) { int off = 0 , len; XU8 buff[1024] ; memset(buff,0,sizeof(buff)); string res; pstring = &zip_mem; xmem_gzstream* strm = XGZFILE_open( X_test_read , NULL , &off , 0 , -1 ); while(len = XGZFILE_read( strm , buff , sizeof( buff ) )) { res.append((char *)buff,len); memset(buff,0,sizeof(buff)); } XGZFILE_close( strm ); return res; }
29.837624
88
0.521503
hdsy
607a96483c9d37a6152bba71eb234421ceeb2172
5,936
cpp
C++
src/athena/MemoryWriter.cpp
encounter/athena
6adba82abd8b7f48e6eca9f74361d0c605bc9ec8
[ "MIT" ]
null
null
null
src/athena/MemoryWriter.cpp
encounter/athena
6adba82abd8b7f48e6eca9f74361d0c605bc9ec8
[ "MIT" ]
null
null
null
src/athena/MemoryWriter.cpp
encounter/athena
6adba82abd8b7f48e6eca9f74361d0c605bc9ec8
[ "MIT" ]
null
null
null
#include "athena/MemoryWriter.hpp" #include <cstdio> #include <cstring> #ifdef HW_RVL #include <malloc.h> #endif // HW_RVL namespace athena::io { MemoryWriter::MemoryWriter(atUint8* data, atUint64 length, bool takeOwnership) : m_data(data), m_length(length), m_bufferOwned(takeOwnership) { if (!data) { atError(fmt("data cannot be NULL")); setError(); return; } } MemoryWriter::~MemoryWriter() { if (m_bufferOwned) delete m_data; m_data = nullptr; m_length = 0; } MemoryCopyWriter::MemoryCopyWriter(atUint8* data, atUint64 length) { m_data = data; m_length = length; m_position = 0; m_bufferOwned = false; if (length == 0) { atError(fmt("length cannot be 0")); setError(); return; } m_dataCopy.reset(new atUint8[length]); m_data = m_dataCopy.get(); if (data) memmove(m_data, data, length); } MemoryCopyWriter::MemoryCopyWriter(std::string_view filename) { m_filepath = filename; m_length = 0x10; m_position = 0; m_dataCopy.reset(new atUint8[m_length]); m_data = m_dataCopy.get(); m_bufferOwned = false; if (!m_data) { atError(fmt("Could not allocate memory!")); setError(); return; } } void MemoryWriter::seek(atInt64 position, SeekOrigin origin) { switch (origin) { case SeekOrigin::Begin: if (position < 0) { atError(fmt("Position outside stream bounds")); setError(); return; } if ((atUint64)position > m_length) { atError(fmt("data exceeds available buffer space")); setError(); return; } m_position = position; break; case SeekOrigin::Current: if ((((atInt64)m_position + position) < 0)) { atError(fmt("Position outside stream bounds")); setError(); return; } if (m_position + position > m_length) { atError(fmt("data exceeds available buffer space")); setError(); return; } m_position += position; break; case SeekOrigin::End: if (((atInt64)m_length - position) < 0) { atError(fmt("Position outside stream bounds")); setError(); return; } if ((atUint64)position > m_length) { atError(fmt("data exceeds available buffer space")); setError(); return; } m_position = m_length - position; break; } } void MemoryCopyWriter::seek(atInt64 position, SeekOrigin origin) { switch (origin) { case SeekOrigin::Begin: if (position < 0) { atError(fmt("Position outside stream bounds")); setError(); return; } if ((atUint64)position > m_length) resize(position); m_position = position; break; case SeekOrigin::Current: if ((((atInt64)m_position + position) < 0)) { atError(fmt("Position outside stream bounds")); setError(); return; } if (m_position + position > m_length) resize(m_position + position); m_position += position; break; case SeekOrigin::End: if (((atInt64)m_length - position) < 0) { atError(fmt("Position outside stream bounds")); setError(); return; } if ((atUint64)position > m_length) resize(position); m_position = m_length - position; break; } } void MemoryWriter::setData(atUint8* data, atUint64 length, bool takeOwnership) { if (m_bufferOwned) delete m_data; m_data = data; m_length = length; m_position = 0; m_bufferOwned = takeOwnership; } void MemoryCopyWriter::setData(const atUint8* data, atUint64 length) { m_dataCopy.reset(new atUint8[length]); m_data = m_dataCopy.get(); memmove(m_data, data, length); m_length = length; m_position = 0; m_bufferOwned = false; } atUint8* MemoryWriter::data() const { atUint8* ret = new atUint8[m_length]; memset(ret, 0, m_length); memmove(ret, m_data, m_length); return ret; } void MemoryWriter::save(std::string_view filename) { if (filename.empty() && m_filepath.empty()) { atError(fmt("No file specified, cannot save.")); setError(); return; } if (!filename.empty()) { m_filepath = filename; } std::unique_ptr<FILE, decltype(&std::fclose)> out{std::fopen(m_filepath.c_str(), "wb"), std::fclose}; if (!out) { atError(fmt("Unable to open file '{}'"), m_filepath); setError(); return; } atUint64 done = 0; atUint64 blocksize = BLOCKSZ; do { if (blocksize > m_length - done) { blocksize = m_length - done; } const atInt64 ret = std::fwrite(m_data + done, 1, blocksize, out.get()); if (ret < 0) { atError(fmt("Error writing data to disk")); setError(); return; } if (ret == 0) { break; } done += blocksize; } while (done < m_length); } void MemoryWriter::writeUBytes(const atUint8* data, atUint64 length) { if (!data) { atError(fmt("data cannnot be NULL")); setError(); return; } if (m_position + length > m_length) { atError(fmt("data length exceeds available buffer space")); setError(); return; } memmove(reinterpret_cast<atInt8*>(m_data + m_position), data, length); m_position += length; } void MemoryCopyWriter::writeUBytes(const atUint8* data, atUint64 length) { if (!data) { atError(fmt("data cannnot be NULL")); setError(); return; } if (m_position + length > m_length) resize(m_position + length); memmove(reinterpret_cast<atInt8*>(m_data + m_position), data, length); m_position += length; } void MemoryCopyWriter::resize(atUint64 newSize) { if (newSize < m_length) { atError(fmt("New size cannot be less to the old size.")); return; } // Allocate and copy new buffer auto newArray = std::make_unique<atUint8[]>(newSize); if (m_dataCopy) { std::memmove(newArray.get(), m_dataCopy.get(), m_length); } m_dataCopy = std::move(newArray); // Swap the pointer and size out for the new ones. m_data = m_dataCopy.get(); m_length = newSize; } } // namespace athena::io
21.585455
103
0.635782
encounter
607e300251eb0aac876c03dad8357a69e4656472
17,436
cpp
C++
external_libs/pgenlib/pgenlibr.cpp
tedyun/regenie
6d31b5165e098a08ff575e5a36c0cb6219247cc6
[ "MIT" ]
null
null
null
external_libs/pgenlib/pgenlibr.cpp
tedyun/regenie
6d31b5165e098a08ff575e5a36c0cb6219247cc6
[ "MIT" ]
null
null
null
external_libs/pgenlib/pgenlibr.cpp
tedyun/regenie
6d31b5165e098a08ff575e5a36c0cb6219247cc6
[ "MIT" ]
null
null
null
/* * * File obtained from pgenlibr R library: * https://github.com/chrchang/plink-ng/tree/master/2.0/pgenlibr * * License info obtained from DESCRIPTION file: * https://github.com/chrchang/plink-ng/blob/master/2.0/pgenlibr/DESCRIPTION * ----------------------------------------------------- Package: pgenlibr Type: Package Title: PLINK 2 Binary (.pgen) Reader Version: 0.2 Date: 2019-07-10 Author: Christopher Chang Maintainer: Christopher Chang <[email protected]> Description: A thin wrapper over PLINK 2's core libraries which provides an R interface for reading .pgen files. A minimal .pvar loader is also included. License: LGPL (>= 3) Imports: Rcpp (>= 1.0.1) LinkingTo: Rcpp * ----------------------------------------------------- * Modified by Joelle Mbatchou - June 29 2020 * - removed functions that were for R * - split file to header (added link to several standard C++ libraries) * - modified remaining functions to be fully C/C++ compatible * * This file remains under LGPL v3 license (license is in same directory as this file) */ #include "pgenlibr.h" PgenReader::PgenReader() : _info_ptr(nullptr), //_allele_idx_offsetsp(nullptr), //_nonref_flagsp(nullptr), _state_ptr(nullptr) { } PgenReader::~PgenReader() { Close(); } void PgenReader::Load(std::string filename, uint32_t cur_sample_ct, std::vector<int> sample_subset_1based) { if (_info_ptr) { Close(); } _info_ptr = static_cast<plink2::PgenFileInfo*>(malloc(sizeof(plink2::PgenFileInfo))); if (!_info_ptr) { fprintf(stderr,"Out of memory"); exit(-1); } plink2::PreinitPgfi(_info_ptr); uint32_t cur_variant_ct = UINT32_MAX; const char* fname = filename.c_str(); plink2::PgenHeaderCtrl header_ctrl; uintptr_t pgfi_alloc_cacheline_ct; char errstr_buf[plink2::kPglErrstrBufBlen]; if (PgfiInitPhase1(fname, cur_variant_ct, cur_sample_ct, 0, &header_ctrl, _info_ptr, &pgfi_alloc_cacheline_ct, errstr_buf) != plink2::kPglRetSuccess) { fprintf(stderr, "%s\n", &(errstr_buf[7])); exit(-1); } const uint32_t raw_variant_ct = _info_ptr->raw_variant_ct; if (header_ctrl & 0x30) { fprintf(stderr,"Storing of allele count information is not supported (only bi-allelic variants should be present)."); exit(-1); // no need to zero-initialize this //_allele_idx_offsetsp = plink2::CreateRefcountedWptr(raw_variant_ct + 1); //_info_ptr->allele_idx_offsets = _allele_idx_offsetsp->p; // _info_ptr->max_allele_ct updated by PgfiInitPhase2() in this case } _info_ptr->max_allele_ct = 2; if ((header_ctrl & 0xc0) == 0xc0) { fprintf(stderr,"Tracking og reference alleles in header is not supported."); exit(-1); // todo: load this in pvar, to enable consistency check. we use a // (manually implemented) shared_ptr in preparation for this. //const uintptr_t raw_variant_ctl = plink2::DivUp(raw_variant_ct, plink2::kBitsPerWord); // no need to zero-initialize this //_nonref_flagsp = plink2::CreateRefcountedWptr(raw_variant_ctl + 1); //_info_ptr->nonref_flags = _nonref_flagsp->p; } const uint32_t file_sample_ct = _info_ptr->raw_sample_ct; unsigned char* pgfi_alloc = nullptr; if (plink2::cachealigned_malloc(pgfi_alloc_cacheline_ct * plink2::kCacheline, &pgfi_alloc)) { fprintf(stderr,"Out of memory"); exit(-1); } uint32_t max_vrec_width; uintptr_t pgr_alloc_cacheline_ct; if (PgfiInitPhase2(header_ctrl, 1, 0, 0, 0, raw_variant_ct, &max_vrec_width, _info_ptr, pgfi_alloc, &pgr_alloc_cacheline_ct, errstr_buf)) { if (pgfi_alloc && (!_info_ptr->vrtypes)) { plink2::aligned_free(pgfi_alloc); } fprintf(stderr,"%s\n", &(errstr_buf[7])); exit(-1); } if ((!_allele_idx_offsetsp) && (_info_ptr->gflags & 4)) { // Note that it's safe to be ignorant of multiallelic variants when // phase and dosage info aren't present; GetAlleleCt() then always returns // 2 when that isn't actually true, and all ALTs are treated as if they // were ALT1, but otherwise everything works properly. fprintf(stderr,"Multiallelic variants and phase/dosage info simultaneously present; pvar required in this case"); exit(-1); } _state_ptr = static_cast<plink2::PgenReader*>(malloc(sizeof(plink2::PgenReader))); if (!_state_ptr) { fprintf(stderr,"Out of memory"); exit(-1); } plink2::PreinitPgr(_state_ptr); plink2::PgrSetFreadBuf(nullptr, _state_ptr); const uintptr_t pgr_alloc_main_byte_ct = pgr_alloc_cacheline_ct * plink2::kCacheline; const uintptr_t sample_subset_byte_ct = plink2::DivUp(file_sample_ct, plink2::kBitsPerVec) * plink2::kBytesPerVec; const uintptr_t cumulative_popcounts_byte_ct = plink2::DivUp(file_sample_ct, plink2::kBitsPerWord * plink2::kInt32PerVec) * plink2::kBytesPerVec; const uintptr_t genovec_byte_ct = plink2::DivUp(file_sample_ct, plink2::kNypsPerVec) * plink2::kBytesPerVec; const uintptr_t ac_byte_ct = plink2::RoundUpPow2(file_sample_ct * sizeof(plink2::AlleleCode), plink2::kBytesPerVec); const uintptr_t ac2_byte_ct = plink2::RoundUpPow2(file_sample_ct * 2 * sizeof(plink2::AlleleCode), plink2::kBytesPerVec); uintptr_t multiallelic_hc_byte_ct = 0; if (_info_ptr->max_allele_ct != 2) { multiallelic_hc_byte_ct = 2 * sample_subset_byte_ct + ac_byte_ct + ac2_byte_ct; } const uintptr_t dosage_main_byte_ct = plink2::DivUp(file_sample_ct, (2 * plink2::kInt32PerVec)) * plink2::kBytesPerVec; unsigned char* pgr_alloc; if (plink2::cachealigned_malloc(pgr_alloc_main_byte_ct + (2 * plink2::kPglNypTransposeBatch + 5) * sample_subset_byte_ct + cumulative_popcounts_byte_ct + (1 + plink2::kPglNypTransposeBatch) * genovec_byte_ct + multiallelic_hc_byte_ct + dosage_main_byte_ct + plink2::kPglBitTransposeBufbytes + 4 * (plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8), &pgr_alloc)) { fprintf(stderr,"Out of memory"); exit(-1); } plink2::PglErr reterr = PgrInit(fname, max_vrec_width, _info_ptr, _state_ptr, pgr_alloc); if (reterr != plink2::kPglRetSuccess) { if (!plink2::PgrGetFreadBuf(_state_ptr)) { plink2::aligned_free(pgr_alloc); } sprintf(errstr_buf, "PgrInit() error %d", static_cast<int>(reterr)); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } unsigned char* pgr_alloc_iter = &(pgr_alloc[pgr_alloc_main_byte_ct]); _subset_include_vec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _subset_include_interleaved_vec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); #ifdef USE_AVX2 _subset_include_interleaved_vec[-3] = 0; _subset_include_interleaved_vec[-2] = 0; #endif _subset_include_interleaved_vec[-1] = 0; _subset_cumulative_popcounts = reinterpret_cast<uint32_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[cumulative_popcounts_byte_ct]); _pgv.genovec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[genovec_byte_ct]); if (multiallelic_hc_byte_ct) { _pgv.patch_01_set = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.patch_01_vals = reinterpret_cast<plink2::AlleleCode*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[ac_byte_ct]); _pgv.patch_10_set = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.patch_10_vals = reinterpret_cast<plink2::AlleleCode*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[ac2_byte_ct]); } else { _pgv.patch_01_set = nullptr; _pgv.patch_01_vals = nullptr; _pgv.patch_10_set = nullptr; _pgv.patch_10_vals = nullptr; } _pgv.phasepresent = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.phaseinfo = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.dosage_present = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.dosage_main = reinterpret_cast<uint16_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[dosage_main_byte_ct]); if (sample_subset_1based.size() > 0) { SetSampleSubsetInternal(sample_subset_1based); } else { _subset_size = file_sample_ct; } pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglBitTransposeBufbytes]); _multivar_vmaj_geno_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * genovec_byte_ct]); _multivar_vmaj_phasepresent_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * sample_subset_byte_ct]); _multivar_vmaj_phaseinfo_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * sample_subset_byte_ct]); _multivar_smaj_geno_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 4]); _multivar_smaj_phaseinfo_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8]); _multivar_smaj_phasepresent_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); // pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8]); } uint32_t PgenReader::GetRawSampleCt() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return _info_ptr->raw_sample_ct; } uint32_t PgenReader::GetSubsetSize() const { return _subset_size; } uint32_t PgenReader::GetVariantCt() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return _info_ptr->raw_variant_ct; } uint32_t PgenReader::GetAlleleCt(uint32_t variant_idx) const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } if (variant_idx >= _info_ptr->raw_variant_ct) { char errstr_buf[256]; sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } if (!_allele_idx_offsetsp) { return 2; } fprintf(stderr,"Error: only bi-allelic variants are supported"); exit(-1); //const uintptr_t* allele_idx_offsets = _allele_idx_offsetsp->p; //return allele_idx_offsets[variant_idx + 1] - allele_idx_offsets[variant_idx]; } uint32_t PgenReader::GetMaxAlleleCt() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return _info_ptr->max_allele_ct; } bool PgenReader::HardcallPhasePresent() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return ((_info_ptr->gflags & plink2::kfPgenGlobalHardcallPhasePresent) != 0); } // added by J.Mbatchou (09/22/20) to check if dosages are present in PGEN file bool PgenReader::DosagePresent() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return ((_info_ptr->gflags & plink2::kfPgenGlobalDosagePresent) != 0); } static const int32_t kGenoRInt32Quads[1024] ALIGNV16 = QUAD_TABLE256(0, 1, 2, -3); void PgenReader::ReadIntHardcalls(std::vector<int>& buf, int variant_idx, int allele_idx) { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) { char errstr_buf[256]; sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } if (buf.size() != _subset_size) { char errstr_buf[256]; sprintf(errstr_buf, "buf has wrong length (%" PRIdPTR "; %u expected)", buf.size(), _subset_size); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::PglErr reterr = PgrGet1(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec); if (reterr != plink2::kPglRetSuccess) { char errstr_buf[256]; sprintf(errstr_buf, "PgrGet1() error %d", static_cast<int>(reterr)); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::GenoarrLookup256x4bx4(_pgv.genovec, kGenoRInt32Quads, _subset_size, &buf[0]); } static const double kGenoRDoublePairs[32] ALIGNV16 = PAIR_TABLE16(0.0, 1.0, 2.0, -3.0); void PgenReader::ReadHardcalls(std::vector<double>& buf, int variant_idx, int allele_idx) { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) { char errstr_buf[256]; sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } if (buf.size() != _subset_size) { char errstr_buf[256]; sprintf(errstr_buf, "buf has wrong length (%" PRIdPTR "; %u expected)", buf.size(), _subset_size); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::PglErr reterr = PgrGet1(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec); if (reterr != plink2::kPglRetSuccess) { char errstr_buf[256]; sprintf(errstr_buf, "PgrGet1() error %d", static_cast<int>(reterr)); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::GenoarrLookup16x8bx2(_pgv.genovec, kGenoRDoublePairs, _subset_size, &buf[0]); } void PgenReader::Read(std::vector<double>& buf, int variant_idx, int allele_idx) { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) { char errstr_buf[256]; sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } if (buf.size() != _subset_size) { char errstr_buf[256]; sprintf(errstr_buf, "buf has wrong length (%" PRIdPTR "; %u expected)", buf.size(), _subset_size); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } uint32_t dosage_ct; plink2::PglErr reterr = PgrGet1D(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, &dosage_ct); if (reterr != plink2::kPglRetSuccess) { char errstr_buf[256]; sprintf(errstr_buf, "PgrGet1D() error %d", static_cast<int>(reterr)); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::Dosage16ToDoubles(kGenoRDoublePairs, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, _subset_size, dosage_ct, &buf[0]); } void PgenReader::Close() { // don't bother propagating file close errors for now if (_info_ptr) { //CondReleaseRefcountedWptr(&_allele_idx_offsetsp); //CondReleaseRefcountedWptr(&_nonref_flagsp); if (_info_ptr->vrtypes) { plink2::aligned_free(_info_ptr->vrtypes); } plink2::PglErr reterr = plink2::kPglRetSuccess; plink2::CleanupPgfi(_info_ptr, &reterr); free(_info_ptr); _info_ptr = nullptr; } if (_state_ptr) { plink2::PglErr reterr = plink2::kPglRetSuccess; plink2::CleanupPgr(_state_ptr, &reterr); if (PgrGetFreadBuf(_state_ptr)) { plink2::aligned_free(PgrGetFreadBuf(_state_ptr)); } free(_state_ptr); _state_ptr = nullptr; } _subset_size = 0; } void PgenReader::SetSampleSubsetInternal(std::vector<int>& sample_subset_1based) { const uint32_t raw_sample_ct = _info_ptr->raw_sample_ct; const uint32_t raw_sample_ctv = plink2::DivUp(raw_sample_ct, plink2::kBitsPerVec); const uint32_t raw_sample_ctaw = raw_sample_ctv * plink2::kWordsPerVec; uintptr_t* sample_include = _subset_include_vec; plink2::ZeroWArr(raw_sample_ctaw, sample_include); const uint32_t subset_size = sample_subset_1based.size(); if (subset_size == 0) { fprintf(stderr,"Empty sample_subset is not currently permitted"); exit(-1); } uint32_t sample_uidx = sample_subset_1based[0] - 1; uint32_t idx = 0; uint32_t next_uidx; while (1) { if (sample_uidx >= raw_sample_ct) { char errstr_buf[256]; sprintf(errstr_buf, "sample number out of range (%d; must be 1..%u)", static_cast<int>(sample_uidx + 1), raw_sample_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::SetBit(sample_uidx, sample_include); if (++idx == subset_size) { break; } next_uidx = sample_subset_1based[idx] - 1; // prohibit this since it implies that the caller expects genotypes to be // returned in a different order if (next_uidx <= sample_uidx) { fprintf(stderr,"sample_subset is not in strictly increasing order"); exit(-1); } sample_uidx = next_uidx; } plink2::FillInterleavedMaskVec(sample_include, raw_sample_ctv, _subset_include_interleaved_vec); const uint32_t raw_sample_ctl = plink2::DivUp(raw_sample_ct, plink2::kBitsPerWord); plink2::FillCumulativePopcounts(sample_include, raw_sample_ctl, _subset_cumulative_popcounts); plink2::PgrSetSampleSubsetIndex(_subset_cumulative_popcounts, _state_ptr, &_subset_index); _subset_size = subset_size; }
41.81295
382
0.71708
tedyun
607eb76c427464a3e63567d4b48312bd5c8f70a5
1,335
hh
C++
gecode/string/find.hh
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
1
2021-05-26T13:27:00.000Z
2021-05-26T13:27:00.000Z
gecode/string/find.hh
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
gecode/string/find.hh
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
#ifndef __GECODE_STRING_FIND_HH__ #define __GECODE_STRING_FIND_HH__ namespace Gecode { namespace String { /** * \brief %Propagator for string find. * */ class Find : public MixTernaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND> { protected: using MixTernaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND> ::x0; using MixTernaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND> ::x1; using MixTernaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND> ::x2; /// Constructor for cloning \a p Find(Space& home, Find& p); /// Constructor for posting Find(Home home, StringView, StringView, Gecode::Int::IntView); public: /// Copy propagator during cloning virtual Actor* copy(Space& home); /// Perform propagation virtual ExecStatus propagate(Space& home, const ModEventDelta& med); /// Post propagator for \f n = find(x, y) \f$ static ExecStatus post(Home, StringView, StringView, Gecode::Int::IntView); }; }} #include <gecode/string/int/find.hpp> #endif
32.560976
79
0.697378
ramadini
60800365b8156a58de2c7956ce2151c151a87257
4,152
cc
C++
src/core/ext/transport/chttp2/client/insecure/channel_create.cc
mnuck/grpc
d5b1f9809202bf2338f94a9e1c07bc511b42d67d
[ "Apache-2.0" ]
91
2018-11-24T05:33:58.000Z
2022-03-16T05:58:05.000Z
src/core/ext/transport/chttp2/client/insecure/channel_create.cc
mnuck/grpc
d5b1f9809202bf2338f94a9e1c07bc511b42d67d
[ "Apache-2.0" ]
11
2019-06-02T23:50:17.000Z
2022-02-04T23:58:56.000Z
src/core/ext/transport/chttp2/client/insecure/channel_create.cc
mnuck/grpc
d5b1f9809202bf2338f94a9e1c07bc511b42d67d
[ "Apache-2.0" ]
18
2018-11-24T10:35:29.000Z
2021-04-22T07:22:10.000Z
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include <grpc/grpc.h> #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/string_util.h> #include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/client_channel/resolver_registry.h" #include "src/core/ext/transport/chttp2/client/chttp2_connector.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/channel.h" static void client_channel_factory_ref( grpc_client_channel_factory* cc_factory) {} static void client_channel_factory_unref( grpc_client_channel_factory* cc_factory) {} static grpc_subchannel* client_channel_factory_create_subchannel( grpc_client_channel_factory* cc_factory, const grpc_subchannel_args* args) { grpc_connector* connector = grpc_chttp2_connector_create(); grpc_subchannel* s = grpc_subchannel_create(connector, args); grpc_connector_unref(connector); return s; } static grpc_channel* client_channel_factory_create_channel( grpc_client_channel_factory* cc_factory, const char* target, grpc_client_channel_type type, const grpc_channel_args* args) { if (target == nullptr) { gpr_log(GPR_ERROR, "cannot create channel with NULL target name"); return nullptr; } // Add channel arg containing the server URI. grpc_core::UniquePtr<char> canonical_target = grpc_core::ResolverRegistry::AddDefaultPrefixIfNeeded(target); grpc_arg arg = grpc_channel_arg_string_create((char*)GRPC_ARG_SERVER_URI, canonical_target.get()); const char* to_remove[] = {GRPC_ARG_SERVER_URI}; grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(args, to_remove, 1, &arg, 1); grpc_channel* channel = grpc_channel_create(target, new_args, GRPC_CLIENT_CHANNEL, nullptr); grpc_channel_args_destroy(new_args); return channel; } static const grpc_client_channel_factory_vtable client_channel_factory_vtable = {client_channel_factory_ref, client_channel_factory_unref, client_channel_factory_create_subchannel, client_channel_factory_create_channel}; static grpc_client_channel_factory client_channel_factory = { &client_channel_factory_vtable}; /* Create a client channel: Asynchronously: - resolve target - connect to it (trying alternatives as presented) - perform handshakes */ grpc_channel* grpc_insecure_channel_create(const char* target, const grpc_channel_args* args, void* reserved) { grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE( "grpc_insecure_channel_create(target=%s, args=%p, reserved=%p)", 3, (target, args, reserved)); GPR_ASSERT(reserved == nullptr); // Add channel arg containing the client channel factory. grpc_arg arg = grpc_client_channel_factory_create_channel_arg(&client_channel_factory); grpc_channel_args* new_args = grpc_channel_args_copy_and_add(args, &arg, 1); // Create channel. grpc_channel* channel = client_channel_factory_create_channel( &client_channel_factory, target, GRPC_CLIENT_CHANNEL_TYPE_REGULAR, new_args); // Clean up. grpc_channel_args_destroy(new_args); return channel != nullptr ? channel : grpc_lame_client_channel_create( target, GRPC_STATUS_INTERNAL, "Failed to create client channel"); }
39.169811
80
0.729046
mnuck
60850ff8061079e361d38c3d4c9eb8eefb3caf0d
9,397
cpp
C++
osquery/events/darwin/fsevents.cpp
justintime32/osquery
721dd1ed624b25738c2471dae617d7868df8fb0d
[ "BSD-3-Clause" ]
1
2018-10-30T03:58:24.000Z
2018-10-30T03:58:24.000Z
osquery/events/darwin/fsevents.cpp
justintime32/osquery
721dd1ed624b25738c2471dae617d7868df8fb0d
[ "BSD-3-Clause" ]
null
null
null
osquery/events/darwin/fsevents.cpp
justintime32/osquery
721dd1ed624b25738c2471dae617d7868df8fb0d
[ "BSD-3-Clause" ]
2
2020-09-23T04:49:23.000Z
2022-03-29T17:32:31.000Z
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <fnmatch.h> #include <boost/filesystem.hpp> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/tables.h> #include "osquery/events/darwin/fsevents.h" /** * @brief FSEvents needs a real/absolute path for watches. * * When adding a subscription, FSEvents will resolve a depth of recursive * symlinks. Increasing the max will make tolerance to odd setups more robust * but introduce additional latency during startup. */ #define FSEVENTS_MAX_SYMLINK_DEPTH 5 namespace fs = boost::filesystem; namespace osquery { std::map<FSEventStreamEventFlags, std::string> kMaskActions = { {kFSEventStreamEventFlagItemChangeOwner, "ATTRIBUTES_MODIFIED"}, {kFSEventStreamEventFlagItemXattrMod, "ATTRIBUTES_MODIFIED"}, {kFSEventStreamEventFlagItemInodeMetaMod, "ATTRIBUTES_MODIFIED"}, {kFSEventStreamEventFlagItemCreated, "CREATED"}, {kFSEventStreamEventFlagItemRemoved, "DELETED"}, {kFSEventStreamEventFlagItemModified, "UPDATED"}, {kFSEventStreamEventFlagItemRenamed, "MOVED_TO"}, {kFSEventStreamEventFlagMustScanSubDirs, "COLLISION_WITHIN"}, {kFSEventStreamEventFlagUnmount, "UNMOUNTED"}, {kFSEventStreamEventFlagRootChanged, "ROOT_CHANGED"}, }; REGISTER(FSEventsEventPublisher, "event_publisher", "fsevents"); void FSEventsSubscriptionContext::requireAction(const std::string& action) { for (const auto& bit : kMaskActions) { if (action == bit.second) { mask = mask & bit.first; } } } void FSEventsEventPublisher::restart() { if (run_loop_ == nullptr) { return; } // Remove any existing stream. stop(); // Build paths as CFStrings { WriteLock lock(mutex_); if (paths_.empty()) { // There are no paths to watch. paths_.insert("/dev/null"); } std::vector<CFStringRef> cf_paths; for (const auto& path : paths_) { auto cf_path = CFStringCreateWithCString( nullptr, path.c_str(), kCFStringEncodingUTF8); cf_paths.push_back(cf_path); } // The FSEvents watch takes a CFArrayRef auto watch_list = CFArrayCreate(nullptr, reinterpret_cast<const void**>(&cf_paths[0]), cf_paths.size(), &kCFTypeArrayCallBacks); // Set stream flags. auto flags = kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagWatchRoot; if (no_defer_) { flags |= kFSEventStreamCreateFlagNoDefer; } if (no_self_) { flags |= kFSEventStreamCreateFlagIgnoreSelf; } // Create the FSEvent stream. stream_ = FSEventStreamCreate(nullptr, &FSEventsEventPublisher::Callback, nullptr, watch_list, kFSEventStreamEventIdSinceNow, 1, flags); if (stream_ != nullptr) { // Schedule the stream on the run loop. FSEventStreamScheduleWithRunLoop( stream_, run_loop_, kCFRunLoopDefaultMode); if (FSEventStreamStart(stream_)) { stream_started_ = true; } else { LOG(ERROR) << "Cannot start FSEvent stream: FSEventStreamStart failed"; } } else { LOG(ERROR) << "Cannot create FSEvent stream: FSEventStreamCreate failed"; } // Clean up strings, watch list, and context. CFRelease(watch_list); for (auto& cf_path : cf_paths) { CFRelease(cf_path); } } } void FSEventsEventPublisher::stop() { // Stop the stream. WriteLock lock(mutex_); if (run_loop_ == nullptr) { // No need to stop if there is not run loop. return; } if (stream_ != nullptr) { FSEventStreamStop(stream_); stream_started_ = false; FSEventStreamUnscheduleFromRunLoop( stream_, run_loop_, kCFRunLoopDefaultMode); FSEventStreamInvalidate(stream_); FSEventStreamRelease(stream_); stream_ = nullptr; } // Stop the run loop. CFRunLoopStop(run_loop_); } void FSEventsEventPublisher::tearDown() { stop(); // Do not keep a reference to the run loop. run_loop_ = nullptr; } std::set<std::string> FSEventsEventPublisher::transformSubscription( FSEventsSubscriptionContextRef& sc) const { std::set<std::string> paths; sc->discovered_ = sc->path; if (sc->path.find("**") != std::string::npos) { // Double star will indicate recursive matches, restricted to endings. sc->recursive = true; sc->discovered_ = sc->path.substr(0, sc->path.find("**")); // Remove '**' from the subscription path (used to match later). sc->path = sc->discovered_; } // If the path 'still' OR 'either' contains a single wildcard. if (sc->path.find('*') != std::string::npos) { // First check if the wildcard is applied to the end. auto fullpath = fs::path(sc->path); if (fullpath.filename().string().find('*') != std::string::npos) { sc->discovered_ = fullpath.parent_path().string(); } // FSEvents needs a real path, if the wildcard is within the path then // a configure-time resolve is required. if (sc->discovered_.find('*') != std::string::npos) { std::vector<std::string> exploded_paths; resolveFilePattern(sc->discovered_, exploded_paths); for (const auto& path : exploded_paths) { paths.insert(path); } sc->recursive_match = sc->recursive; return paths; } } paths.insert(sc->discovered_); return paths; } void FSEventsEventPublisher::configure() { // Rebuild the watch paths. stop(); { WriteLock lock(mutex_); paths_.clear(); for (auto& sub : subscriptions_) { auto sc = getSubscriptionContext(sub->context); if (sc->discovered_.size() > 0) { continue; } auto paths = transformSubscription(sc); paths_.insert(paths.begin(), paths.end()); } } restart(); } Status FSEventsEventPublisher::run() { // The run entrypoint executes in a dedicated thread. if (run_loop_ == nullptr) { run_loop_ = CFRunLoopGetCurrent(); // Restart the stream creation. restart(); } // Start the run loop, it may be removed with a tearDown. CFRunLoopRun(); return Status(0, "OK"); } void FSEventsEventPublisher::Callback( ConstFSEventStreamRef stream, void* callback_info, size_t num_events, void* event_paths, const FSEventStreamEventFlags fsevent_flags[], const FSEventStreamEventId fsevent_ids[]) { for (size_t i = 0; i < num_events; ++i) { auto ec = createEventContext(); ec->fsevent_stream = stream; ec->fsevent_flags = fsevent_flags[i]; ec->transaction_id = fsevent_ids[i]; ec->path = std::string(((char**)event_paths)[i]); if (ec->fsevent_flags & kFSEventStreamEventFlagMustScanSubDirs) { // The FSEvents thread coalesced events within and will report a root. TLOG << "FSEvents collision, root: " << ec->path; } if (ec->fsevent_flags & kFSEventStreamEventFlagRootChanged) { // Must rescan for the changed root. } if (ec->fsevent_flags & kFSEventStreamEventFlagUnmount) { // Should remove the watch on this path. } // Record the string-version of the first matched mask bit. bool has_action = false; for (const auto& action : kMaskActions) { if (ec->fsevent_flags & action.first) { // Actions may be multiplexed. Fire and event for each. ec->action = action.second; EventFactory::fire<FSEventsEventPublisher>(ec); has_action = true; } } if (!has_action) { // If no action was matched for this path event, fire and unknown. ec->action = "UNKNOWN"; EventFactory::fire<FSEventsEventPublisher>(ec); } } } bool FSEventsEventPublisher::shouldFire( const FSEventsSubscriptionContextRef& sc, const FSEventsEventContextRef& ec) const { if (sc->recursive && !sc->recursive_match) { ssize_t found = ec->path.find(sc->path); if (found != 0) { return false; } } else if (fnmatch((sc->path + "*").c_str(), ec->path.c_str(), FNM_PATHNAME | FNM_CASEFOLD | ((sc->recursive_match) ? FNM_LEADING_DIR : 0)) != 0) { // Only apply a leading-dir match if this is a recursive watch with a // match requirement (an inline wildcard with ending recursive wildcard). return false; } if (sc->mask != 0 && !(ec->fsevent_flags & sc->mask)) { // Compare the event context mask to the subscription context. return false; } return true; } void FSEventsEventPublisher::flush(bool async) { if (stream_ != nullptr && stream_started_) { if (async) { FSEventStreamFlushAsync(stream_); } else { FSEventStreamFlushSync(stream_); } } } size_t FSEventsEventPublisher::numSubscriptionedPaths() const { return paths_.size(); } bool FSEventsEventPublisher::isStreamRunning() const { if (stream_ == nullptr || !stream_started_ || run_loop_ == nullptr) { return false; } return CFRunLoopIsWaiting(run_loop_); } }
29.737342
79
0.650846
justintime32
60861cacfeab2c90a6d780e5665912549d8ae382
653
cpp
C++
src/Pixel.cpp
kosiken/lion-image-to-ascii
c000d0f90f06a88935f5ffc62e40402238025f4c
[ "MIT" ]
2
2021-05-04T00:30:43.000Z
2021-10-17T15:32:26.000Z
src/Pixel.cpp
kosiken/lion-image-to-ascii
c000d0f90f06a88935f5ffc62e40402238025f4c
[ "MIT" ]
null
null
null
src/Pixel.cpp
kosiken/lion-image-to-ascii
c000d0f90f06a88935f5ffc62e40402238025f4c
[ "MIT" ]
null
null
null
#include <iostream> #include "Pixel.h" #define LION_DIV 256 LionPixel::LionPixel() { r = 0; g= 0; b = 0; } LionPixel::LionPixel(int red, int green, int blue) { r = red; g = green; b = blue; } LionPixel::LionPixel(int red, int green, int blue, double alpha) { r = red; g = green; b = blue; a= alpha; updateCss(); } double LionPixel::intensity() { intensityV = (r + g + b) * a; return intensityV; } std::ostream & operator<<(std::ostream & os, const LionPixel & t){ os << "[ r => " << t.r << ", g => " << t.g << ", b => " << t.b << ", a => " << t.a << " ]"; return os; };
14.195652
66
0.496172
kosiken
608e8341b4f4009be7368848d99c77ca32307ff6
12,039
cpp
C++
source/mango/image/image_hdr.cpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
3
2021-02-27T10:29:37.000Z
2022-02-16T16:31:26.000Z
source/mango/image/image_hdr.cpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
null
null
null
source/mango/image/image_hdr.cpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
5
2021-03-22T11:06:00.000Z
2022-02-22T02:53:19.000Z
/* MANGO Multimedia Development Platform Copyright (C) 2012-2021 Twilight Finland 3D Oy Ltd. All rights reserved. */ #include <cmath> #include <mango/core/pointer.hpp> #include <mango/core/buffer.hpp> #include <mango/core/system.hpp> #include <mango/image/image.hpp> namespace { using namespace mango; using namespace mango::image; // ------------------------------------------------------------ // tokenizer // ------------------------------------------------------------ std::string readline(const u8*& data, const u8* end) { const u8* p = data; int endsize = 1; // scan for endline for ( ; data < end; ) { u8 v = *p++; // Unix ("\n") if (v == '\n') break; // MacOS ("\r") if (v == '\r') { // Windows ("\r\n") if (*p == '\n') { ++endsize; ++p; } break; } } int size = int(p - data) - endsize; std::string msg(reinterpret_cast<const char*>(data), size); data = p; return msg; } inline bool whitespace(char v) { return v == ' ' || v == '\t' || v == '='; } void insert_token(std::vector<std::string>& tokens, const char* text, int size) { if (size > 0) { std::string msg(text, size); tokens.push_back(msg); } } std::vector<std::string> tokenize(const std::string& line) { std::vector<std::string> tokens; const char* p = line.c_str(); const char* endline = p + line.length(); for ( ; p < endline;) { // skip whitespaces for ( ;; ++p) { char v = *p; if (!v) return tokens; if (!whitespace(v)) break; } const char* begin = p; // seek next whitespace for ( ;; ++p) { char v = *p; if (!v) { int size = int(p - begin); insert_token(tokens, begin, size); return tokens; } if (whitespace(v)) break; } int size = int(p - begin); insert_token(tokens, begin, size); } return tokens; } // ------------------------------------------------------------ // encoder // ------------------------------------------------------------ struct rgbe { u8 r, g, b, e; }; /* rgbe create_rgbe(float r, float g, float b) { float maxf = r > g ? r : g; maxf = maxf > b ? maxf : b; rgbe color; if (maxf <= 1e-32f) { color.r = 0; color.g = 0; color.b = 0; color.e = 0; } else { int exponent; std::frexpf(maxf, &exponent); float scale = std::ldexpf(1.0f, 8 - exponent); color.r = u8(r * scale); color.g = u8(g * scale); color.b = u8(b * scale); color.e = u8(exponent + 128); } return color; } */ // ------------------------------------------------------------ // decoder // ------------------------------------------------------------ void write_rgbe(float* buffer, rgbe color) { float scale = color.e ? std::ldexp(1.0f, color.e - 136) : 0; buffer[0] = color.r * scale; buffer[1] = color.g * scale; buffer[2] = color.b * scale; buffer[3] = 1.0f; } struct HeaderRAD { enum rad_format { rad_rle_rgbe, rad_unsupported } format = rad_unsupported; int width = 0; int height = 0; float exposure = 1.0f; bool xflip = false; bool yflip = false; ImageHeader header; const u8* parse(ConstMemory memory) { const u8* data = memory.address; const u8* end = memory.address + memory.size; std::string id = readline(data, end); if (id != "#?RADIANCE") { header.setError("[ImageDecoder.HDR] Incorrect radiance header."); return nullptr; } for ( ;; ) { std::string ln = readline(data, end); if (ln.empty()) break; std::vector<std::string> tokens = tokenize(ln); if (tokens[0] == "FORMAT") { if (tokens.size() != 2) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (format)."); return nullptr; } if (tokens[1] == "32-bit_rle_rgbe") format = rad_rle_rgbe; } else if (tokens[1] == "EXPOSURE") { if (tokens.size() != 2) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (exposure)."); return nullptr; } exposure = float(std::atof(tokens[1].c_str())); } } if (format == rad_unsupported) { header.setError("[ImageDecoder.HDR] Incorrect or unsupported format."); return nullptr; } std::string dims = readline(data, end); std::vector<std::string> tokens = tokenize(dims); if (tokens.size() != 4) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (dimensions)."); return nullptr; } for (int i = 0; i < 2; ++i) { int index = i * 2; if (tokens[index] == "+Y") { yflip = false; height = std::atoi(tokens[index + 1].c_str()); } else if (tokens[index] == "-Y") { yflip = true; height = std::atoi(tokens[index + 1].c_str()); } else if (tokens[index] == "+X") { xflip = false; width = std::atoi(tokens[index + 1].c_str()); } else if (tokens[index] == "-X") { xflip = true; width = std::atoi(tokens[index + 1].c_str()); } else { header.setError("[ImageDecoder.HDR] Incorrect radiance header (dimensions)."); return nullptr; } } if (!width || !height) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (dimensions)."); return nullptr; } header.width = width; header.height = height; header.depth = 0; header.levels = 0; header.faces = 0; header.palette = false; header.format = Format(128, Format::FLOAT32, Format::RGBA, 32, 32, 32, 32); header.compression = TextureCompression::NONE; return data; } }; void hdr_decode(ImageDecodeStatus& status, const Surface& surface, const u8* data) { Buffer buffer(surface.width * 4); for (int y = 0; y < surface.height; ++y) { if (data[0] != 2 || data[1] != 2 || data[2] & 0x80) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (wrong header)."); return; } if (((data[2] << 8) | data[3]) != surface.width) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (wrong scan)."); return; } data += 4; for (int channel = 0; channel < 4; ++channel) { u8* dest = buffer + surface.width * channel; u8* end = dest + surface.width; while (dest < end) { int count = *data++; if (count > 128) { count -= 128; if (!count || dest + count > end) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (rle count)."); return; } u8 value = *data++; std::memset(dest, value, count); dest += count; } else { if (!count || dest + count > end) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (rle count)."); return; } std::memcpy(dest, data, count); dest += count; data += count; } } } float* image = surface.address<float>(0, y); for (int x = 0; x < surface.width; ++x) { rgbe color; color.r = buffer[x + surface.width * 0]; color.g = buffer[x + surface.width * 1]; color.b = buffer[x + surface.width * 2]; color.e = buffer[x + surface.width * 3]; write_rgbe(image, color); image += 4; } } } // ------------------------------------------------------------ // ImageDecoder // ------------------------------------------------------------ struct Interface : ImageDecoderInterface { HeaderRAD m_rad_header; const u8* m_data; Interface(ConstMemory memory) { m_data = m_rad_header.parse(memory); } ~Interface() { } ImageHeader header() override { return m_rad_header.header; } ImageDecodeStatus decode(const Surface& dest, const ImageDecodeOptions& options, int level, int depth, int face) override { MANGO_UNREFERENCED(options); MANGO_UNREFERENCED(level); MANGO_UNREFERENCED(depth); MANGO_UNREFERENCED(face); ImageDecodeStatus status; const ImageHeader& header = m_rad_header.header; if (!header.success) { status.setError(header.info); return status; } status.direct = dest.format == header.format && dest.width == header.width && dest.height == header.height; if (status.direct) { hdr_decode(status, dest, m_data); } else { Bitmap temp(header.width, header.height, header.format); hdr_decode(status, temp, m_data); if (status) { dest.blit(0, 0, temp); } } return status; } }; ImageDecoderInterface* createInterface(ConstMemory memory) { ImageDecoderInterface* x = new Interface(memory); return x; } } // namespace namespace mango::image { void registerImageDecoderHDR() { registerImageDecoder(createInterface, ".hdr"); } } // namespace mango::image
27.361364
129
0.395216
ufoym
6091411015121751c0a2850261a59e0fbec426ec
711
cpp
C++
regression/esbmc-cpp/qt/QMultiMap/multimap_swap/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
regression/esbmc-cpp/qt/QMultiMap/multimap_swap/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
regression/esbmc-cpp/qt/QMultiMap/multimap_swap/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
// swap QMultiMaps #include <iostream> #include <QMultiMap> #include <cassert> using namespace std; int main () { QMultiMap<char,int> foo; QMultiMap<char,int> bar; QMultiMap<char,int>::iterator it; foo['x']=100; foo['y']=200; bar['a']=11; bar['b']=22; bar['c']=33; foo.swap(bar); cout << "foo contains:\n"; for ( it=foo.begin() ; it != foo.end(); it++ ) cout << it.key() << " => " << it.value() << endl; cout << "bar contains:\n"; for ( it=bar.begin() ; it != bar.end(); it++ ) cout << it.key() << " => " << it.value() << endl; assert(bar['x']==100); assert(bar['y']==200); assert(foo['a']==11); assert(foo['b']==22); assert(foo['c']==33); return 0; }
18.230769
53
0.528833
shmarovfedor
60924806e9f5450a31679b7be2d3cb4ba58cdfc8
828
cpp
C++
TrackerValidation/FixationTarget.cpp
tim-murphy/eye-tracker-validation
70515aa9dc61c19fe61eb07bf2606be29e5e80e7
[ "MIT" ]
null
null
null
TrackerValidation/FixationTarget.cpp
tim-murphy/eye-tracker-validation
70515aa9dc61c19fe61eb07bf2606be29e5e80e7
[ "MIT" ]
16
2021-02-12T10:57:29.000Z
2021-11-25T00:35:29.000Z
TrackerValidation/FixationTarget.cpp
tim-murphy/eye-tracker-validation
70515aa9dc61c19fe61eb07bf2606be29e5e80e7
[ "MIT" ]
null
null
null
// Fixation target abstract class // Written by Tim Murphy <[email protected]> 2021 #include "FixationTarget.h" #include "CircleTarget.h" #include "CrosshairBullseyeTarget.h" #include <stdexcept> FixationTarget::FixationTarget(unsigned int diameter) :diameter(diameter) { } unsigned int FixationTarget::getDiameter(void) const { return diameter; } FixationTarget *FixationTarget::create(const std::string &type, unsigned int diameter) { if (type == "circle") { return new CircleTarget(diameter); } else if (type == "crosshairbullseye" || type == "cbe") { return new CrosshairBullseyeTarget(diameter); } else { std::string err("Unknown fixation target type: " + type); throw std::runtime_error(err.c_str()); } }
23
65
0.642512
tim-murphy
6092e6a75c1ff242c56b736c861d3751d55f8fa7
1,007
cpp
C++
725.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
8
2018-10-31T11:00:19.000Z
2020-07-31T05:25:06.000Z
725.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
null
null
null
725.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
2
2018-05-31T11:29:22.000Z
2019-09-11T06:34:40.000Z
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector<ListNode*> splitListToParts(ListNode* root, int k) { int d=depth(root); vector<int> ls; while(k>0){ ls.push_back(d/k); d-=d/k; k--; } vector<ListNode*> ans; ListNode* prev=root; while(ls.size() && root){ while(ls.back()>1){ root=root->next; ls.back()--; } ListNode* tmp=root; root=root->next; tmp->next=NULL; ans.push_back(prev); prev=root; ls.pop_back(); } while(ls.size()){ ans.push_back(NULL); ls.pop_back(); } return ans; } int depth(ListNode* root){ if(!root) return 0; return 1+depth(root->next); } };
22.886364
63
0.443893
zfang399
609476a6eed961cfbe3eb1c4bc49126779a41d14
8,694
cpp
C++
dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp
wonrst/dali-toolkit
f15407e1710844219f3e418e83e689b5ff7341c2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp
wonrst/dali-toolkit
f15407e1710844219f3e418e83e689b5ff7341c2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp
wonrst/dali-toolkit
f15407e1710844219f3e418e83e689b5ff7341c2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * 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. * */ // EXTERNAL INCLUDES #include <dali/public-api/object/type-registry-helper.h> #include <dali/public-api/object/type-registry.h> #include <cstring> // for strcmp // INTERNAL INCLUDES #include <dali-toolkit/internal/controls/control/control-data-impl.h> #include <dali-toolkit/internal/controls/scrollable/scrollable-impl.h> using namespace Dali; namespace Dali { namespace Toolkit { namespace Internal { namespace { BaseHandle Create() { // empty handle as we cannot create Scrollable (but type registered for scroll signal) return BaseHandle(); } // Setup properties, signals and actions using the type-registry. DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Scrollable, Toolkit::Control, Create); DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEffectColor", VECTOR4, OVERSHOOT_EFFECT_COLOR) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootAnimationSpeed", FLOAT, OVERSHOOT_ANIMATION_SPEED) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEnabled", BOOLEAN, OVERSHOOT_ENABLED) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootSize", VECTOR2, OVERSHOOT_SIZE) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollToAlphaFunction", INTEGER, SCROLL_TO_ALPHA_FUNCTION) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollRelativePosition", VECTOR2, SCROLL_RELATIVE_POSITION) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMin", VECTOR2, SCROLL_POSITION_MIN) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinX", SCROLL_POSITION_MIN_X, SCROLL_POSITION_MIN, 0) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinY", SCROLL_POSITION_MIN_Y, SCROLL_POSITION_MIN, 1) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMax", VECTOR2, SCROLL_POSITION_MAX) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxX", SCROLL_POSITION_MAX_X, SCROLL_POSITION_MAX, 0) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxY", SCROLL_POSITION_MAX_Y, SCROLL_POSITION_MAX, 1) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollVertical", BOOLEAN, CAN_SCROLL_VERTICAL) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollHorizontal", BOOLEAN, CAN_SCROLL_HORIZONTAL) DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollStarted", SIGNAL_SCROLL_STARTED) DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollCompleted", SIGNAL_SCROLL_COMPLETED) DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollUpdated", SIGNAL_SCROLL_UPDATED) DALI_TYPE_REGISTRATION_END() const Vector4 DEFAULT_OVERSHOOT_COLOUR(0.0f, 0.64f, 0.85f, 0.25f); const float DEFAULT_OVERSHOOT_ANIMATION_SPEED(120.0f); // 120 pixels per second const Vector2 OVERSHOOT_DEFAULT_SIZE(720.0f, 42.0f); } // namespace /////////////////////////////////////////////////////////////////////////////////////////////////// // Scrollable /////////////////////////////////////////////////////////////////////////////////////////////////// Scrollable::Scrollable(ControlBehaviour behaviourFlags) : Control(ControlBehaviour(behaviourFlags)), mOvershootEffectColor(DEFAULT_OVERSHOOT_COLOUR), mOvershootAnimationSpeed(DEFAULT_OVERSHOOT_ANIMATION_SPEED), mOvershootSize(OVERSHOOT_DEFAULT_SIZE), mScrollToAlphaFunction(AlphaFunction::EASE_OUT), mScrollStartedSignal(), mScrollUpdatedSignal(), mScrollCompletedSignal(), mOvershootEnabled(true) { } Scrollable::~Scrollable() { } bool Scrollable::AccessibleImpl::IsScrollable() { return true; } void Scrollable::OnInitialize() { DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { return std::unique_ptr<Dali::Accessibility::Accessible>( new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE)); }); } bool Scrollable::IsOvershootEnabled() const { return mOvershootEnabled; } void Scrollable::SetOvershootEnabled(bool enable) { EnableScrollOvershoot(enable); mOvershootEnabled = enable; } Vector4 Scrollable::GetOvershootEffectColor() const { return mOvershootEffectColor; }; void Scrollable::SetOvershootAnimationSpeed(float pixelsPerSecond) { mOvershootAnimationSpeed = pixelsPerSecond; } float Scrollable::GetOvershootAnimationSpeed() const { return mOvershootAnimationSpeed; }; const Vector2& Scrollable::GetOvershootSize() const { return mOvershootSize; } Toolkit::Scrollable::ScrollStartedSignalType& Scrollable::ScrollStartedSignal() { return mScrollStartedSignal; } Toolkit::Scrollable::ScrollUpdatedSignalType& Scrollable::ScrollUpdatedSignal() { return mScrollUpdatedSignal; } Toolkit::Scrollable::ScrollCompletedSignalType& Scrollable::ScrollCompletedSignal() { return mScrollCompletedSignal; } bool Scrollable::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { Dali::BaseHandle handle(object); bool connected(true); Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(handle); if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_STARTED)) { scrollable.ScrollStartedSignal().Connect(tracker, functor); } else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_UPDATED)) { scrollable.ScrollUpdatedSignal().Connect(tracker, functor); } else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_COMPLETED)) { scrollable.ScrollCompletedSignal().Connect(tracker, functor); } else { // signalName does not match any signal connected = false; } return connected; } void Scrollable::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object)); if(scrollable) { Scrollable& scrollableImpl(GetImpl(scrollable)); switch(index) { case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR: { scrollableImpl.SetOvershootEffectColor(value.Get<Vector4>()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED: { scrollableImpl.SetOvershootAnimationSpeed(value.Get<float>()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ENABLED: { scrollableImpl.SetOvershootEnabled(value.Get<bool>()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_SIZE: { scrollableImpl.SetOvershootSize(value.Get<Vector2>()); break; } case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION: { int alphaFunction = value.Get<int>(); if(alphaFunction >= AlphaFunction::DEFAULT && alphaFunction < AlphaFunction::COUNT) { scrollableImpl.mScrollToAlphaFunction = static_cast<AlphaFunction::BuiltinFunction>(alphaFunction); } break; } } } } Property::Value Scrollable::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object)); if(scrollable) { Scrollable& scrollableImpl(GetImpl(scrollable)); switch(index) { case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR: { value = scrollableImpl.GetOvershootEffectColor(); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED: { value = scrollableImpl.GetOvershootAnimationSpeed(); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ENABLED: { value = scrollableImpl.IsOvershootEnabled(); break; } case Toolkit::Scrollable::Property::OVERSHOOT_SIZE: { value = scrollableImpl.mOvershootSize; break; } case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION: { value = static_cast<int>(scrollableImpl.mScrollToAlphaFunction); break; } } } return value; } } // namespace Internal } // namespace Toolkit } // namespace Dali
31.846154
146
0.740741
wonrst
609d81f105e1a97e4bf67ec24425ba6d671c8e6b
2,441
cpp
C++
Vorlesungsmaterial/22-05-04/lambda.cpp
TEL21D/Informatik2
d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075
[ "MIT" ]
null
null
null
Vorlesungsmaterial/22-05-04/lambda.cpp
TEL21D/Informatik2
d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075
[ "MIT" ]
null
null
null
Vorlesungsmaterial/22-05-04/lambda.cpp
TEL21D/Informatik2
d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <iostream> #include <iomanip> #include <string> #include <vector> #include "lambda.hpp" using namespace std; bool lessLength(const string &f, const string &s) { return f.length() < s.length(); } void lambda() { vector<string> myStrVec = {"12345", "123456", "1234", "1", "12", "123", "12345"}; cout << "\n\nSortieren mit lessLength():\n"; sort(myStrVec.begin(), myStrVec.end(), lessLength); for (auto v : myStrVec) cout << v << " "; cout << "\n\nSortieren mit einer lambda Funktion:\n"; sort(myStrVec.begin(), myStrVec.end(), [](const string &f, const string &s) { return f.length() < s.length(); }); for (auto v : myStrVec) cout << v << " "; cout << "\n\nSortieren mit einer lambda Funktion:\n"; sort(myStrVec.begin(), myStrVec.end(), [](const string &f, const string &s) { return f.length() > s.length(); }); for (auto v : myStrVec) cout << v << " "; cout << "\n"; // for_each läuft durch alle Elemte des Vektors und wendet die Funktion auf jedes Element an for_each(myStrVec.begin(), myStrVec.end(), [](const string &s) { cout << s << ", "; }); cout << "\n\nAusgeben (foreach) mit einer lambda Funktion:\n"; vector<int> myVec1{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << "i->i*i: "; for_each(myVec1.begin(), myVec1.end(), [](int &i) { i = i * i; }); for (auto v : myVec1) cout << v << " "; cout << endl; vector<double> myVec2{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for_each(myVec2.begin(), myVec2.end(), [](double &i) { i = sqrt(i); }); cout << "i->sqrt(i): "; for (auto v : myVec2) cout << fixed << setprecision(2) << v << " "; // fixed verhindert exponentialschreibweise (z.B. 1.0e-10) // Nachkommastellen auf 2 begrenzt mit setprecision cout << "\n\n"; } void lambda_captures() { cout << endl; string copy = "original"; string ref = "original"; auto lambda = [copy, &ref] { cout << copy << " " << ref << endl; }; lambda(); copy = "changed"; ref = "changed"; lambda(); copy = "changed again"; ref = "changed again"; lambda(); cout << endl; } void lambda_params() { auto addTwoNumbers = [](int a, int b){ return a + b; }; cout << endl; cout << "addTwoNumbers(2000, 17): " << addTwoNumbers(2000, 17) << endl; cout << "addTwoNumbers(2000, 21): " << addTwoNumbers(2000, 21) << endl; }
28.383721
116
0.565752
TEL21D
60a00c7037587a140b01a3b1c39160f93ae0d5ef
3,685
cpp
C++
Daa_code/common/Key_name_from_public_data.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
2
2020-02-28T10:40:12.000Z
2021-02-18T03:32:28.000Z
Daa_code/common/Key_name_from_public_data.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
null
null
null
Daa_code/common/Key_name_from_public_data.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
null
null
null
/******************************************************************************* * File: Key_name_from_public_data.cpp * Description: Calculate the key's name from its public data (TPMT_PUBLIC) * * Author: Chris Newton * * Created: Tueday 29 May 2018 * * (C) Copyright 2018, University of Surrey. * *******************************************************************************/ /******************************************************************************* * * * (C) Copyright 2019 University of Surrey * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright notice, * * this list of conditions and the following disclaimer in the documentation * * and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * *******************************************************************************/ #include <iostream> #include "Marshal_public_data.h" #include "Byte_buffer.h" #include "Sha.h" Byte_buffer get_key_name( TPMT_PUBLIC* public_data ) { Byte_buffer marshalled_public_area=marshal_public_data_T(public_data); // std::cout << "Marshalled area: size: " << marshalled_public_area.size() << '\n'; // std::cout << "Marshalled area: data: " << marshalled_public_area.to_hex_string() << '\n'; Byte_buffer sha256_ma=sha256_bb(marshalled_public_area); // std::cout << "SHA256 of marshalled area: " << sha256_ma.to_hex_string() << '\n'; Byte_buffer name{0x00,0x0b}; // nameAlg (0x0b for sha256) name+=sha256_ma; // std::cout << " Key name: size: " << name.size() << '\n'; // std::cout << " Key name: data: " << name.to_hex_string() << '\n'; return name; } Byte_buffer get_key_name_bb( Byte_buffer key_pd ) { Byte_buffer name; TPM2B_PUBLIC tpm2b_pub; TPM_RC rc=unmarshal_public_data_B(key_pd, &tpm2b_pub); if (rc!=0) { return name; // Leave it to others to sort out } return get_key_name(&tpm2b_pub.publicArea); }
46.0625
95
0.52483
UoS-SCCS
60a40149e2dd260cb8a0a4e503d974086c0df0ff
784
cpp
C++
ASAE/ASAE/Buffer.cpp
BenFields724/AutoSim
063350df2e27c38623a736a463aaf8b0124c9218
[ "MIT" ]
null
null
null
ASAE/ASAE/Buffer.cpp
BenFields724/AutoSim
063350df2e27c38623a736a463aaf8b0124c9218
[ "MIT" ]
null
null
null
ASAE/ASAE/Buffer.cpp
BenFields724/AutoSim
063350df2e27c38623a736a463aaf8b0124c9218
[ "MIT" ]
null
null
null
// // Buffer.cpp // ASAE // // Created by Benjamin G Fields on 4/2/18. // Copyright © 2018 Benjamin G Fields. All rights reserved. // // Description: defines the implementatin of the buffer object #include "Buffer.hpp" //Description:return the state of the buffer by saying if it is full,empty or still has space int Buffer::getState(){ if (queue.size() == capacity) { return FULL; } else if(queue.size()== 0){ return EMPTY; } else{ return SPACE_LEFT; } } int Buffer::getNumInQueue(){ return (int)queue.size(); } //Description:return the next event in the queue Event Buffer::GetNext(){ Event E = queue.front(); queue.pop(); return E; } //Description: put the event in the buffer queue void Buffer::placeInBuffer(Event E){ queue.push(E); }
19.6
93
0.672194
BenFields724
60a6ba044e3289aa9516e4a3c755391e2e6e17b9
650
cpp
C++
src/basic/tests/unit_tests_talker.cpp
sgermanserrano/gitlab_ci_test
df415655757d9674a31ca704bef6bb7c456e7c09
[ "Apache-2.0" ]
null
null
null
src/basic/tests/unit_tests_talker.cpp
sgermanserrano/gitlab_ci_test
df415655757d9674a31ca704bef6bb7c456e7c09
[ "Apache-2.0" ]
null
null
null
src/basic/tests/unit_tests_talker.cpp
sgermanserrano/gitlab_ci_test
df415655757d9674a31ca704bef6bb7c456e7c09
[ "Apache-2.0" ]
1
2019-03-05T16:33:21.000Z
2019-03-05T16:33:21.000Z
#include "basic/talker.h" #include <gtest/gtest.h> class MyTestSuite : public ::testing::Test { public: MyTestSuite(){} ~MyTestSuite(){} }; TEST_F(MyTestSuite, lowValue){ Talker rt; int initial_value = 3; int value = rt.doSomeMath(initial_value); ASSERT_EQ(value, initial_value+5) << "Value should be its initial value plus 5"; } TEST_F(MyTestSuite, highValue){ Talker rt; int initial_value = 49; int value = rt.doSomeMath(initial_value); ASSERT_EQ(value, 0) << "Value should be 0"; } //int main(int argc, char **argv) { // testing::InitGoogleTest(&argc, argv); // ros::init(argc, argv, "TestNode"); // return RUN_ALL_TESTS(); //}
19.117647
81
0.690769
sgermanserrano
60acc4f14e001deaee20496a931c0689e58789e7
36,168
cpp
C++
external/vulkancts/modules/vulkan/pipeline/vktPipelineMultisampleBaseResolveAndPerSampleFetch.cpp
jljusten/VK-GL-CTS
711e764f295a627eebe677a54ebc85d58d6e8920
[ "Apache-2.0" ]
1
2021-02-25T09:06:00.000Z
2021-02-25T09:06:00.000Z
external/vulkancts/modules/vulkan/pipeline/vktPipelineMultisampleBaseResolveAndPerSampleFetch.cpp
jljusten/VK-GL-CTS
711e764f295a627eebe677a54ebc85d58d6e8920
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/pipeline/vktPipelineMultisampleBaseResolveAndPerSampleFetch.cpp
jljusten/VK-GL-CTS
711e764f295a627eebe677a54ebc85d58d6e8920
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2016 The Khronos Group 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. * *//* * \file vktPipelineMultisampleBaseResolveAndPerSampleFetch.cpp * \brief Base class for tests that check results of multisample resolve * and/or values of individual samples *//*--------------------------------------------------------------------*/ #include "vktPipelineMultisampleBaseResolveAndPerSampleFetch.hpp" #include "vktPipelineMakeUtil.hpp" #include "vkBarrierUtil.hpp" #include "vkBuilderUtil.hpp" #include "vkQueryUtil.hpp" #include "vkTypeUtil.hpp" #include "vkCmdUtil.hpp" #include "vkTypeUtil.hpp" #include "vkObjUtil.hpp" #include "tcuTestLog.hpp" #include <vector> namespace vkt { namespace pipeline { namespace multisample { using namespace vk; void MSCaseBaseResolveAndPerSampleFetch::initPrograms (vk::SourceCollections& programCollection) const { // Create vertex shader std::ostringstream vs; vs << "#version 440\n" << "layout(location = 0) in vec4 vs_in_position_ndc;\n" << "\n" << "out gl_PerVertex {\n" << " vec4 gl_Position;\n" << "};\n" << "void main (void)\n" << "{\n" << " gl_Position = vs_in_position_ndc;\n" << "}\n"; programCollection.glslSources.add("per_sample_fetch_vs") << glu::VertexSource(vs.str()); // Create fragment shader std::ostringstream fs; fs << "#version 440\n" << "\n" << "layout(location = 0) out vec4 fs_out_color;\n" << "\n" << "layout(set = 0, binding = 0, input_attachment_index = 0) uniform subpassInputMS imageMS;\n" << "\n" << "layout(set = 0, binding = 1, std140) uniform SampleBlock {\n" << " int sampleNdx;\n" << "};\n" << "void main (void)\n" << "{\n" << " fs_out_color = subpassLoad(imageMS, sampleNdx);\n" << "}\n"; programCollection.glslSources.add("per_sample_fetch_fs") << glu::FragmentSource(fs.str()); } VkPipelineMultisampleStateCreateInfo MSInstanceBaseResolveAndPerSampleFetch::getMSStateCreateInfo (const ImageMSParams& imageMSParams) const { const VkPipelineMultisampleStateCreateInfo multisampleStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkPipelineMultisampleStateCreateFlags)0u, // VkPipelineMultisampleStateCreateFlags flags; imageMSParams.numSamples, // VkSampleCountFlagBits rasterizationSamples; VK_TRUE, // VkBool32 sampleShadingEnable; 1.0f, // float minSampleShading; DE_NULL, // const VkSampleMask* pSampleMask; VK_FALSE, // VkBool32 alphaToCoverageEnable; VK_FALSE, // VkBool32 alphaToOneEnable; }; return multisampleStateInfo; } const VkDescriptorSetLayout* MSInstanceBaseResolveAndPerSampleFetch::createMSPassDescSetLayout(const ImageMSParams& imageMSParams) { DE_UNREF(imageMSParams); return DE_NULL; } const VkDescriptorSet* MSInstanceBaseResolveAndPerSampleFetch::createMSPassDescSet(const ImageMSParams& imageMSParams, const VkDescriptorSetLayout* descSetLayout) { DE_UNREF(imageMSParams); DE_UNREF(descSetLayout); return DE_NULL; } tcu::TestStatus MSInstanceBaseResolveAndPerSampleFetch::iterate (void) { const InstanceInterface& instance = m_context.getInstanceInterface(); const DeviceInterface& deviceInterface = m_context.getDeviceInterface(); const VkDevice device = m_context.getDevice(); const VkPhysicalDevice physicalDevice = m_context.getPhysicalDevice(); Allocator& allocator = m_context.getDefaultAllocator(); const VkQueue queue = m_context.getUniversalQueue(); const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex(); VkImageCreateInfo imageMSInfo; VkImageCreateInfo imageRSInfo; const deUint32 firstSubpassAttachmentsCount = 2u; // Check if image size does not exceed device limits validateImageSize(instance, physicalDevice, m_imageType, m_imageMSParams.imageSize); // Check if device supports image format as color attachment validateImageFeatureFlags(instance, physicalDevice, mapTextureFormat(m_imageFormat), VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT); imageMSInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageMSInfo.pNext = DE_NULL; imageMSInfo.flags = 0u; imageMSInfo.imageType = mapImageType(m_imageType); imageMSInfo.format = mapTextureFormat(m_imageFormat); imageMSInfo.extent = makeExtent3D(getLayerSize(m_imageType, m_imageMSParams.imageSize)); imageMSInfo.arrayLayers = getNumLayers(m_imageType, m_imageMSParams.imageSize); imageMSInfo.mipLevels = 1u; imageMSInfo.samples = m_imageMSParams.numSamples; imageMSInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageMSInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageMSInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; imageMSInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageMSInfo.queueFamilyIndexCount = 0u; imageMSInfo.pQueueFamilyIndices = DE_NULL; if (m_imageType == IMAGE_TYPE_CUBE || m_imageType == IMAGE_TYPE_CUBE_ARRAY) { imageMSInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; } validateImageInfo(instance, physicalDevice, imageMSInfo); const de::UniquePtr<Image> imageMS(new Image(deviceInterface, device, allocator, imageMSInfo, MemoryRequirement::Any)); imageRSInfo = imageMSInfo; imageRSInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageRSInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; validateImageInfo(instance, physicalDevice, imageRSInfo); const de::UniquePtr<Image> imageRS(new Image(deviceInterface, device, allocator, imageRSInfo, MemoryRequirement::Any)); const deUint32 numSamples = static_cast<deUint32>(imageMSInfo.samples); std::vector<de::SharedPtr<Image> > imagesPerSampleVec(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imagesPerSampleVec[sampleNdx] = de::SharedPtr<Image>(new Image(deviceInterface, device, allocator, imageRSInfo, MemoryRequirement::Any)); } // Create render pass std::vector<VkAttachmentDescription> attachments(firstSubpassAttachmentsCount + numSamples); { const VkAttachmentDescription attachmentMSDesc = { (VkAttachmentDescriptionFlags)0u, // VkAttachmentDescriptionFlags flags; imageMSInfo.format, // VkFormat format; imageMSInfo.samples, // VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout initialLayout; VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL // VkImageLayout finalLayout; }; attachments[0] = attachmentMSDesc; const VkAttachmentDescription attachmentRSDesc = { (VkAttachmentDescriptionFlags)0u, // VkAttachmentDescriptionFlags flags; imageRSInfo.format, // VkFormat format; imageRSInfo.samples, // VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout initialLayout; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout finalLayout; }; attachments[1] = attachmentRSDesc; for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { attachments[firstSubpassAttachmentsCount + sampleNdx] = attachmentRSDesc; } } const VkAttachmentReference attachmentMSColorRef = { 0u, // deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }; const VkAttachmentReference attachmentMSInputRef = { 0u, // deUint32 attachment; VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL // VkImageLayout layout; }; const VkAttachmentReference attachmentRSColorRef = { 1u, // deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }; std::vector<VkAttachmentReference> perSampleAttachmentRef(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { const VkAttachmentReference attachmentRef = { firstSubpassAttachmentsCount + sampleNdx, // deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }; perSampleAttachmentRef[sampleNdx] = attachmentRef; } std::vector<deUint32> preserveAttachments(1u + numSamples); for (deUint32 attachNdx = 0u; attachNdx < 1u + numSamples; ++attachNdx) { preserveAttachments[attachNdx] = 1u + attachNdx; } std::vector<VkSubpassDescription> subpasses(1u + numSamples); std::vector<VkSubpassDependency> subpassDependencies(numSamples); const VkSubpassDescription firstSubpassDesc = { (VkSubpassDescriptionFlags)0u, // VkSubpassDescriptionFlags flags; VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint; 0u, // deUint32 inputAttachmentCount; DE_NULL, // const VkAttachmentReference* pInputAttachments; 1u, // deUint32 colorAttachmentCount; &attachmentMSColorRef, // const VkAttachmentReference* pColorAttachments; &attachmentRSColorRef, // const VkAttachmentReference* pResolveAttachments; DE_NULL, // const VkAttachmentReference* pDepthStencilAttachment; 0u, // deUint32 preserveAttachmentCount; DE_NULL // const deUint32* pPreserveAttachments; }; subpasses[0] = firstSubpassDesc; for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { const VkSubpassDescription subpassDesc = { (VkSubpassDescriptionFlags)0u, // VkSubpassDescriptionFlags flags; VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint; 1u, // deUint32 inputAttachmentCount; &attachmentMSInputRef, // const VkAttachmentReference* pInputAttachments; 1u, // deUint32 colorAttachmentCount; &perSampleAttachmentRef[sampleNdx], // const VkAttachmentReference* pColorAttachments; DE_NULL, // const VkAttachmentReference* pResolveAttachments; DE_NULL, // const VkAttachmentReference* pDepthStencilAttachment; 1u + sampleNdx, // deUint32 preserveAttachmentCount; dataPointer(preserveAttachments) // const deUint32* pPreserveAttachments; }; subpasses[1u + sampleNdx] = subpassDesc; const VkSubpassDependency subpassDependency = { 0u, // uint32_t srcSubpass; 1u + sampleNdx, // uint32_t dstSubpass; VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VkPipelineStageFlags srcStageMask; VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, // VkPipelineStageFlags dstStageMask; VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags srcAccessMask; VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, // VkAccessFlags dstAccessMask; 0u, // VkDependencyFlags dependencyFlags; }; subpassDependencies[sampleNdx] = subpassDependency; } const VkRenderPassCreateInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkRenderPassCreateFlags)0u, // VkRenderPassCreateFlags flags; static_cast<deUint32>(attachments.size()), // deUint32 attachmentCount; dataPointer(attachments), // const VkAttachmentDescription* pAttachments; static_cast<deUint32>(subpasses.size()), // deUint32 subpassCount; dataPointer(subpasses), // const VkSubpassDescription* pSubpasses; static_cast<deUint32>(subpassDependencies.size()), // deUint32 dependencyCount; dataPointer(subpassDependencies) // const VkSubpassDependency* pDependencies; }; const Unique<VkRenderPass> renderPass(createRenderPass(deviceInterface, device, &renderPassInfo)); const VkImageSubresourceRange fullImageRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, imageMSInfo.mipLevels, 0u, imageMSInfo.arrayLayers); // Create color attachments image views typedef de::SharedPtr<Unique<VkImageView> > VkImageViewSp; std::vector<VkImageViewSp> imageViewsShPtrs(firstSubpassAttachmentsCount + numSamples); std::vector<VkImageView> imageViews(firstSubpassAttachmentsCount + numSamples); imageViewsShPtrs[0] = makeVkSharedPtr(makeImageView(deviceInterface, device, **imageMS, mapImageViewType(m_imageType), imageMSInfo.format, fullImageRange)); imageViewsShPtrs[1] = makeVkSharedPtr(makeImageView(deviceInterface, device, **imageRS, mapImageViewType(m_imageType), imageRSInfo.format, fullImageRange)); imageViews[0] = **imageViewsShPtrs[0]; imageViews[1] = **imageViewsShPtrs[1]; for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imageViewsShPtrs[firstSubpassAttachmentsCount + sampleNdx] = makeVkSharedPtr(makeImageView(deviceInterface, device, **imagesPerSampleVec[sampleNdx], mapImageViewType(m_imageType), imageRSInfo.format, fullImageRange)); imageViews[firstSubpassAttachmentsCount + sampleNdx] = **imageViewsShPtrs[firstSubpassAttachmentsCount + sampleNdx]; } // Create framebuffer const VkFramebufferCreateInfo framebufferInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkFramebufferCreateFlags)0u, // VkFramebufferCreateFlags flags; *renderPass, // VkRenderPass renderPass; static_cast<deUint32>(imageViews.size()), // uint32_t attachmentCount; dataPointer(imageViews), // const VkImageView* pAttachments; imageMSInfo.extent.width, // uint32_t width; imageMSInfo.extent.height, // uint32_t height; imageMSInfo.arrayLayers, // uint32_t layers; }; const Unique<VkFramebuffer> framebuffer(createFramebuffer(deviceInterface, device, &framebufferInfo)); const VkDescriptorSetLayout* descriptorSetLayoutMSPass = createMSPassDescSetLayout(m_imageMSParams); // Create pipeline layout const VkPipelineLayoutCreateInfo pipelineLayoutMSPassParams = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkPipelineLayoutCreateFlags)0u, // VkPipelineLayoutCreateFlags flags; descriptorSetLayoutMSPass ? 1u : 0u, // deUint32 setLayoutCount; descriptorSetLayoutMSPass, // const VkDescriptorSetLayout* pSetLayouts; 0u, // deUint32 pushConstantRangeCount; DE_NULL, // const VkPushConstantRange* pPushConstantRanges; }; const Unique<VkPipelineLayout> pipelineLayoutMSPass(createPipelineLayout(deviceInterface, device, &pipelineLayoutMSPassParams)); // Create vertex attributes data const VertexDataDesc vertexDataDesc = getVertexDataDescripton(); de::SharedPtr<Buffer> vertexBuffer = de::SharedPtr<Buffer>(new Buffer(deviceInterface, device, allocator, makeBufferCreateInfo(vertexDataDesc.dataSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), MemoryRequirement::HostVisible)); const Allocation& vertexBufferAllocation = vertexBuffer->getAllocation(); uploadVertexData(vertexBufferAllocation, vertexDataDesc); flushAlloc(deviceInterface, device, vertexBufferAllocation); const VkVertexInputBindingDescription vertexBinding = { 0u, // deUint32 binding; vertexDataDesc.dataStride, // deUint32 stride; VK_VERTEX_INPUT_RATE_VERTEX // VkVertexInputRate inputRate; }; const VkPipelineVertexInputStateCreateInfo vertexInputStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkPipelineVertexInputStateCreateFlags)0u, // VkPipelineVertexInputStateCreateFlags flags; 1u, // uint32_t vertexBindingDescriptionCount; &vertexBinding, // const VkVertexInputBindingDescription* pVertexBindingDescriptions; static_cast<deUint32>(vertexDataDesc.vertexAttribDescVec.size()), // uint32_t vertexAttributeDescriptionCount; dataPointer(vertexDataDesc.vertexAttribDescVec), // const VkVertexInputAttributeDescription* pVertexAttributeDescriptions; }; const std::vector<VkViewport> viewports (1, makeViewport(imageMSInfo.extent)); const std::vector<VkRect2D> scissors (1, makeRect2D(imageMSInfo.extent)); const VkPipelineMultisampleStateCreateInfo multisampleStateInfo = getMSStateCreateInfo(m_imageMSParams); // Create graphics pipeline for multisample pass const Unique<VkShaderModule> vsMSPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("vertex_shader"), (VkShaderModuleCreateFlags)0u)); const Unique<VkShaderModule> fsMSPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("fragment_shader"), (VkShaderModuleCreateFlags)0u)); const Unique<VkPipeline> graphicsPipelineMSPass(makeGraphicsPipeline(deviceInterface, // const DeviceInterface& vk device, // const VkDevice device *pipelineLayoutMSPass, // const VkPipelineLayout pipelineLayout *vsMSPassModule, // const VkShaderModule vertexShaderModule DE_NULL, // const VkShaderModule tessellationControlModule DE_NULL, // const VkShaderModule tessellationEvalModule DE_NULL, // const VkShaderModule geometryShaderModule *fsMSPassModule, // const VkShaderModule fragmentShaderModule *renderPass, // const VkRenderPass renderPass viewports, // const std::vector<VkViewport>& viewports scissors, // const std::vector<VkRect2D>& scissors vertexDataDesc.primitiveTopology, // const VkPrimitiveTopology topology 0u, // const deUint32 subpass 0u, // const deUint32 patchControlPoints &vertexInputStateInfo, // const VkPipelineVertexInputStateCreateInfo* vertexInputStateCreateInfo DE_NULL, // const VkPipelineRasterizationStateCreateInfo* rasterizationStateCreateInfo &multisampleStateInfo)); // const VkPipelineMultisampleStateCreateInfo* multisampleStateCreateInfo typedef de::SharedPtr<Unique<VkPipeline> > VkPipelineSp; std::vector<VkPipelineSp> graphicsPipelinesPerSampleFetch(numSamples); // Create descriptor set layout const Unique<VkDescriptorSetLayout> descriptorSetLayout( DescriptorSetLayoutBuilder() .addSingleBinding(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, VK_SHADER_STAGE_FRAGMENT_BIT) .addSingleBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_SHADER_STAGE_FRAGMENT_BIT) .build(deviceInterface, device)); const Unique<VkPipelineLayout> pipelineLayoutPerSampleFetchPass(makePipelineLayout(deviceInterface, device, *descriptorSetLayout)); const deUint32 bufferPerSampleFetchPassSize = 4u * (deUint32)sizeof(tcu::Vec4); de::SharedPtr<Buffer> vertexBufferPerSampleFetchPass = de::SharedPtr<Buffer>(new Buffer(deviceInterface, device, allocator, makeBufferCreateInfo(bufferPerSampleFetchPassSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), MemoryRequirement::HostVisible)); // Create graphics pipelines for per sample texel fetch passes { const Unique<VkShaderModule> vsPerSampleFetchPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("per_sample_fetch_vs"), (VkShaderModuleCreateFlags)0u)); const Unique<VkShaderModule> fsPerSampleFetchPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("per_sample_fetch_fs"), (VkShaderModuleCreateFlags)0u)); std::vector<tcu::Vec4> vertices; vertices.push_back(tcu::Vec4(-1.0f, -1.0f, 0.0f, 1.0f)); vertices.push_back(tcu::Vec4( 1.0f, -1.0f, 0.0f, 1.0f)); vertices.push_back(tcu::Vec4(-1.0f, 1.0f, 0.0f, 1.0f)); vertices.push_back(tcu::Vec4( 1.0f, 1.0f, 0.0f, 1.0f)); const Allocation& vertexAllocPerSampleFetchPass = vertexBufferPerSampleFetchPass->getAllocation(); deMemcpy(vertexAllocPerSampleFetchPass.getHostPtr(), dataPointer(vertices), static_cast<std::size_t>(bufferPerSampleFetchPassSize)); flushAlloc(deviceInterface, device, vertexAllocPerSampleFetchPass); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { graphicsPipelinesPerSampleFetch[sampleNdx] = makeVkSharedPtr((makeGraphicsPipeline(deviceInterface, // const DeviceInterface& vk device, // const VkDevice device *pipelineLayoutPerSampleFetchPass, // const VkPipelineLayout pipelineLayout *vsPerSampleFetchPassModule, // const VkShaderModule vertexShaderModule DE_NULL, // const VkShaderModule tessellationControlModule DE_NULL, // const VkShaderModule tessellationEvalModule DE_NULL, // const VkShaderModule geometryShaderModule *fsPerSampleFetchPassModule, // const VkShaderModule fragmentShaderModule *renderPass, // const VkRenderPass renderPass viewports, // const std::vector<VkViewport>& viewports scissors, // const std::vector<VkRect2D>& scissors VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, // const VkPrimitiveTopology topology 1u + sampleNdx))); // const deUint32 subpass } } // Create descriptor pool const Unique<VkDescriptorPool> descriptorPool( DescriptorPoolBuilder() .addType(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1u) .addType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1u) .build(deviceInterface, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u)); // Create descriptor set const Unique<VkDescriptorSet> descriptorSet(makeDescriptorSet(deviceInterface, device, *descriptorPool, *descriptorSetLayout)); const VkPhysicalDeviceLimits deviceLimits = getPhysicalDeviceProperties(instance, physicalDevice).limits; VkDeviceSize uboOffsetAlignment = sizeof(deInt32) < deviceLimits.minUniformBufferOffsetAlignment ? deviceLimits.minUniformBufferOffsetAlignment : sizeof(deInt32); uboOffsetAlignment += (deviceLimits.minUniformBufferOffsetAlignment - uboOffsetAlignment % deviceLimits.minUniformBufferOffsetAlignment) % deviceLimits.minUniformBufferOffsetAlignment; const VkBufferCreateInfo bufferSampleIDInfo = makeBufferCreateInfo(uboOffsetAlignment * numSamples, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); const de::UniquePtr<Buffer> bufferSampleID(new Buffer(deviceInterface, device, allocator, bufferSampleIDInfo, MemoryRequirement::HostVisible)); std::vector<deUint32> sampleIDsOffsets(numSamples); { deInt8* sampleIDs = new deInt8[static_cast<deUint32>(uboOffsetAlignment) * numSamples]; for (deInt32 sampleNdx = 0u; sampleNdx < static_cast<deInt32>(numSamples); ++sampleNdx) { sampleIDsOffsets[sampleNdx] = static_cast<deUint32>(sampleNdx * uboOffsetAlignment); deInt8* samplePtr = sampleIDs + sampleIDsOffsets[sampleNdx]; deMemcpy(samplePtr, &sampleNdx, sizeof(deInt32)); } deMemcpy(bufferSampleID->getAllocation().getHostPtr(), sampleIDs, static_cast<deUint32>(uboOffsetAlignment * numSamples)); flushAlloc(deviceInterface, device, bufferSampleID->getAllocation()); delete[] sampleIDs; } { const VkDescriptorImageInfo descImageInfo = makeDescriptorImageInfo(DE_NULL, imageViews[0], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); const VkDescriptorBufferInfo descBufferInfo = makeDescriptorBufferInfo(**bufferSampleID, 0u, sizeof(deInt32)); DescriptorSetUpdateBuilder() .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, &descImageInfo) .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, &descBufferInfo) .update(deviceInterface, device); } // Create command buffer for compute and transfer oparations const Unique<VkCommandPool> commandPool(createCommandPool(deviceInterface, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex)); const Unique<VkCommandBuffer> commandBuffer(makeCommandBuffer(deviceInterface, device, *commandPool)); // Start recording commands beginCommandBuffer(deviceInterface, *commandBuffer); { std::vector<VkImageMemoryBarrier> imageOutputAttachmentBarriers(firstSubpassAttachmentsCount + numSamples); imageOutputAttachmentBarriers[0] = makeImageMemoryBarrier ( 0u, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, **imageMS, fullImageRange ); imageOutputAttachmentBarriers[1] = makeImageMemoryBarrier ( 0u, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, **imageRS, fullImageRange ); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imageOutputAttachmentBarriers[firstSubpassAttachmentsCount + sampleNdx] = makeImageMemoryBarrier ( 0u, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, **imagesPerSampleVec[sampleNdx], fullImageRange ); } deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, static_cast<deUint32>(imageOutputAttachmentBarriers.size()), dataPointer(imageOutputAttachmentBarriers)); } { const VkDeviceSize vertexStartOffset = 0u; std::vector<VkClearValue> clearValues(firstSubpassAttachmentsCount + numSamples); for (deUint32 attachmentNdx = 0u; attachmentNdx < firstSubpassAttachmentsCount + numSamples; ++attachmentNdx) { clearValues[attachmentNdx] = makeClearValueColor(tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f)); } beginRenderPass(deviceInterface, *commandBuffer, *renderPass, *framebuffer, makeRect2D(0, 0, imageMSInfo.extent.width, imageMSInfo.extent.height), (deUint32)clearValues.size(), dataPointer(clearValues)); // Bind graphics pipeline deviceInterface.cmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *graphicsPipelineMSPass); const VkDescriptorSet* descriptorSetMSPass = createMSPassDescSet(m_imageMSParams, descriptorSetLayoutMSPass); if (descriptorSetMSPass) { // Bind descriptor set deviceInterface.cmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipelineLayoutMSPass, 0u, 1u, descriptorSetMSPass, 0u, DE_NULL); } // Bind vertex buffer deviceInterface.cmdBindVertexBuffers(*commandBuffer, 0u, 1u, &vertexBuffer->get(), &vertexStartOffset); // Perform a draw deviceInterface.cmdDraw(*commandBuffer, vertexDataDesc.verticesCount, 1u, 0u, 0u); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { deviceInterface.cmdNextSubpass(*commandBuffer, VK_SUBPASS_CONTENTS_INLINE); // Bind graphics pipeline deviceInterface.cmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, **graphicsPipelinesPerSampleFetch[sampleNdx]); // Bind descriptor set deviceInterface.cmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipelineLayoutPerSampleFetchPass, 0u, 1u, &descriptorSet.get(), 1u, &sampleIDsOffsets[sampleNdx]); // Bind vertex buffer deviceInterface.cmdBindVertexBuffers(*commandBuffer, 0u, 1u, &vertexBufferPerSampleFetchPass->get(), &vertexStartOffset); // Perform a draw deviceInterface.cmdDraw(*commandBuffer, 4u, 1u, 0u, 0u); } // End render pass endRenderPass(deviceInterface, *commandBuffer); } { const VkImageMemoryBarrier imageRSTransferBarrier = makeImageMemoryBarrier ( VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **imageRS, fullImageRange ); deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &imageRSTransferBarrier); } // Copy data from imageRS to buffer const deUint32 imageRSSizeInBytes = getImageSizeInBytes(imageRSInfo.extent, imageRSInfo.arrayLayers, m_imageFormat, imageRSInfo.mipLevels, 1u); const VkBufferCreateInfo bufferRSInfo = makeBufferCreateInfo(imageRSSizeInBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT); const de::UniquePtr<Buffer> bufferRS(new Buffer(deviceInterface, device, allocator, bufferRSInfo, MemoryRequirement::HostVisible)); { const VkBufferImageCopy bufferImageCopy = { 0u, // VkDeviceSize bufferOffset; 0u, // deUint32 bufferRowLength; 0u, // deUint32 bufferImageHeight; makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, imageRSInfo.arrayLayers), // VkImageSubresourceLayers imageSubresource; makeOffset3D(0, 0, 0), // VkOffset3D imageOffset; imageRSInfo.extent, // VkExtent3D imageExtent; }; deviceInterface.cmdCopyImageToBuffer(*commandBuffer, **imageRS, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, bufferRS->get(), 1u, &bufferImageCopy); } { const VkBufferMemoryBarrier bufferRSHostReadBarrier = makeBufferMemoryBarrier ( VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, bufferRS->get(), 0u, imageRSSizeInBytes ); deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, 1u, &bufferRSHostReadBarrier, 0u, DE_NULL); } // Copy data from per sample images to buffers std::vector<VkImageMemoryBarrier> imagesPerSampleTransferBarriers(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imagesPerSampleTransferBarriers[sampleNdx] = makeImageMemoryBarrier ( VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **imagesPerSampleVec[sampleNdx], fullImageRange ); } deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, static_cast<deUint32>(imagesPerSampleTransferBarriers.size()), dataPointer(imagesPerSampleTransferBarriers)); std::vector<de::SharedPtr<Buffer> > buffersPerSample(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { buffersPerSample[sampleNdx] = de::SharedPtr<Buffer>(new Buffer(deviceInterface, device, allocator, bufferRSInfo, MemoryRequirement::HostVisible)); const VkBufferImageCopy bufferImageCopy = { 0u, // VkDeviceSize bufferOffset; 0u, // deUint32 bufferRowLength; 0u, // deUint32 bufferImageHeight; makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, imageRSInfo.arrayLayers), // VkImageSubresourceLayers imageSubresource; makeOffset3D(0, 0, 0), // VkOffset3D imageOffset; imageRSInfo.extent, // VkExtent3D imageExtent; }; deviceInterface.cmdCopyImageToBuffer(*commandBuffer, **imagesPerSampleVec[sampleNdx], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **buffersPerSample[sampleNdx], 1u, &bufferImageCopy); } std::vector<VkBufferMemoryBarrier> buffersPerSampleHostReadBarriers(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { buffersPerSampleHostReadBarriers[sampleNdx] = makeBufferMemoryBarrier ( VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, **buffersPerSample[sampleNdx], 0u, imageRSSizeInBytes ); } deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, static_cast<deUint32>(buffersPerSampleHostReadBarriers.size()), dataPointer(buffersPerSampleHostReadBarriers), 0u, DE_NULL); // End recording commands endCommandBuffer(deviceInterface, *commandBuffer); // Submit commands for execution and wait for completion submitCommandsAndWait(deviceInterface, device, queue, *commandBuffer); // Retrieve data from bufferRS to host memory const Allocation& bufferRSAlloc = bufferRS->getAllocation(); invalidateAlloc(deviceInterface, device, bufferRSAlloc); const tcu::ConstPixelBufferAccess bufferRSData (m_imageFormat, imageRSInfo.extent.width, imageRSInfo.extent.height, imageRSInfo.extent.depth * imageRSInfo.arrayLayers, bufferRSAlloc.getHostPtr()); std::stringstream resolveName; resolveName << "Resolve image " << getImageTypeName(m_imageType) << "_" << bufferRSData.getWidth() << "_" << bufferRSData.getHeight() << "_" << bufferRSData.getDepth() << std::endl; m_context.getTestContext().getLog() << tcu::TestLog::Section(resolveName.str(), resolveName.str()) << tcu::LogImage("resolve", "", bufferRSData) << tcu::TestLog::EndSection; std::vector<tcu::ConstPixelBufferAccess> buffersPerSampleData(numSamples); // Retrieve data from per sample buffers to host memory for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { const Allocation& bufferAlloc = buffersPerSample[sampleNdx]->getAllocation(); invalidateAlloc(deviceInterface, device, bufferAlloc); buffersPerSampleData[sampleNdx] = tcu::ConstPixelBufferAccess ( m_imageFormat, imageRSInfo.extent.width, imageRSInfo.extent.height, imageRSInfo.extent.depth * imageRSInfo.arrayLayers, bufferAlloc.getHostPtr() ); std::stringstream sampleName; sampleName << "Sample " << sampleNdx << " image" << std::endl; m_context.getTestContext().getLog() << tcu::TestLog::Section(sampleName.str(), sampleName.str()) << tcu::LogImage("sample", "", buffersPerSampleData[sampleNdx]) << tcu::TestLog::EndSection; } return verifyImageData(imageMSInfo, imageRSInfo, buffersPerSampleData, bufferRSData); } } // multisample } // pipeline } // vkt
45.956798
245
0.729982
jljusten
60afebb2dc180c6fed882952e29a3a46b908a1d5
16,636
cpp
C++
NOLF/ObjectDLL/Intelligence.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
38
2019-09-16T14:46:42.000Z
2022-03-10T20:28:10.000Z
NOLF/ObjectDLL/Intelligence.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
39
2019-08-12T01:35:33.000Z
2022-02-28T16:48:16.000Z
NOLF/ObjectDLL/Intelligence.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
6
2019-09-17T12:49:18.000Z
2022-03-10T20:28:12.000Z
// ----------------------------------------------------------------------- // // // MODULE : Intelligence.cpp // // PURPOSE : Implementation of the Intelligence object // // CREATED : 9/14/99 // // (c) 1999-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "Intelligence.h" #include "ObjectMsgs.h" #include "PlayerObj.h" #include "CommandMgr.h" // Statics static char *s_szActivate = "ACTIVATE"; static char *s_szGadget = "GADGET"; static char *s_szRespawn = "RESPAWN"; extern CVarTrack g_vtNetIntelScore; CVarTrack g_IntelRespawnScale; #define INTEL_RESPAWN_SOUND "Powerups\\Snd\\spawn_intel.wav" #define INTEL_PICKUP_SOUND "Powerups\\Snd\\pu_intel.wav" // ----------------------------------------------------------------------- // // // CLASS: Intelligence // // PURPOSE: An Intelligence object // // ----------------------------------------------------------------------- // BEGIN_CLASS(Intelligence) // Hide parent properties we don't care about... ADD_STRINGPROP_FLAG(Filename, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(Skin, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(Type, "", PF_STATICLIST | PF_DIMS | PF_LOCALDIMS) ADD_LONGINTPROP(InfoId, 0) ADD_BOOLPROP_FLAG(ShowPopup, LTTRUE, 0) ADD_BOOLPROP_FLAG(PhotoOnly, LTFALSE, 0) ADD_STRINGPROP_FLAG(PickedUpCommand, "", 0) ADD_LONGINTPROP(PlayerTeamFilter, 0) ADD_BOOLPROP_FLAG(StartHidden, LTFALSE, 0) ADD_REALPROP(RespawnTime, 30.0f) END_CLASS_DEFAULT_FLAGS_PLUGIN(Intelligence, Prop, NULL, NULL, 0, CIntelPlugin) LTRESULT CIntelPlugin::PreHook_EditStringList( const char* szRezPath, const char* szPropName, char** aszStrings, uint32* pcStrings, const uint32 cMaxStrings, const uint32 cMaxStringLength) { if ( LT_OK == CPropPlugin::PreHook_EditStringList(szRezPath, szPropName, aszStrings, pcStrings, cMaxStrings, cMaxStringLength) ) { return LT_OK; } else if (_strcmpi("Type", szPropName) == 0) { if (m_IntelMgrPlugin.PreHook_EditStringList(szRezPath, szPropName, aszStrings, pcStrings, cMaxStrings, cMaxStringLength) == LT_OK) { return LT_OK; } } return LT_UNSUPPORTED; } LTRESULT CIntelPlugin::PreHook_Dims( const char* szRezPath, const char* szPropValue, char* szModelFilenameBuf, int nModelFilenameBufLen, LTVector & vDims) { if (m_IntelMgrPlugin.PreHook_Dims(szRezPath, szPropValue, szModelFilenameBuf, nModelFilenameBufLen, vDims) == LT_OK) { return LT_OK; } return LT_UNSUPPORTED; } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Intelligence() // // PURPOSE: Initialize object // // ----------------------------------------------------------------------- // Intelligence::Intelligence() : Prop () { m_bShowPopup = LTTRUE; m_bPhotoOnly = LTFALSE; m_hstrPickedUpCmd = LTNULL; m_nPlayerTeamFilter = 0; m_nInfoId = 0; m_nIntelId = INTELMGR_INVALID_ID; m_fRespawnDelay = 30.0f; m_bStartHidden = LTFALSE; m_bFirstUpdate = LTTRUE; m_bSkipUpdate = LTFALSE; } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::~Intelligence() // // PURPOSE: Deallocate object // // ----------------------------------------------------------------------- // Intelligence::~Intelligence() { if (m_hstrPickedUpCmd) { g_pLTServer->FreeString(m_hstrPickedUpCmd); m_hstrPickedUpCmd = LTNULL; } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::EngineMessageFn // // PURPOSE: Handle engine messages // // ----------------------------------------------------------------------- // uint32 Intelligence::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData) { switch(messageID) { case MID_UPDATE: { Update(); } break; case MID_PRECREATE: { uint32 dwRet = Prop::EngineMessageFn(messageID, pData, fData); if (fData == PRECREATE_WORLDFILE || fData == PRECREATE_STRINGPROP) { ReadProp((ObjectCreateStruct*)pData); PostPropRead((ObjectCreateStruct*)pData); } return dwRet; } break; case MID_SAVEOBJECT: { Save((HMESSAGEWRITE)pData); } break; case MID_LOADOBJECT: { Load((HMESSAGEREAD)pData); } break; case MID_INITIALUPDATE: { if (fData != INITIALUPDATE_SAVEGAME) { InitialUpdate(); } CacheFiles(); } break; default : break; } return Prop::EngineMessageFn(messageID, pData, fData); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::ReadProp // // PURPOSE: Set property value // // ----------------------------------------------------------------------- // void Intelligence::ReadProp(ObjectCreateStruct *pInfo) { if (!pInfo) return; GenericProp genProp; if (g_pLTServer->GetPropGeneric("PhotoOnly", &genProp) == LT_OK) { m_bPhotoOnly = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("StartHidden", &genProp) == LT_OK) { m_bStartHidden = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("ShowPopup", &genProp) == LT_OK) { m_bShowPopup = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("PickedUpCommand", &genProp) == LT_OK) { if (genProp.m_String[0]) { m_hstrPickedUpCmd = g_pLTServer->CreateString(genProp.m_String); } } if (g_pLTServer->GetPropGeneric("PlayerTeamFilter", &genProp) == LT_OK) { m_nPlayerTeamFilter = (uint8) genProp.m_Long; } if (g_pLTServer->GetPropGeneric("InfoId", &genProp) == LT_OK) { m_nInfoId = genProp.m_Long; } if (g_pLTServer->GetPropGeneric("RespawnTime", &genProp) == LT_OK) { m_fRespawnDelay = genProp.m_Float; } INTEL* pIntel = LTNULL; if (g_pLTServer->GetPropGeneric("Type", &genProp) == LT_OK) { if (genProp.m_String[0]) { pIntel = g_pIntelMgr->GetIntel(genProp.m_String); } } if (pIntel) { if (!pIntel || !pIntel->szFilename[0]) return; SAFE_STRCPY(pInfo->m_Filename, pIntel->szFilename); uint32 iSkin = 0; ConParse conParse; conParse.Init(pIntel->szSkin); while (g_pLTServer->Common()->Parse(&conParse) == LT_OK) { if (conParse.m_nArgs > 0) { SAFE_STRCPY(pInfo->m_SkinNames[iSkin], conParse.m_Args[0]); iSkin++; } if (iSkin >= MAX_MODEL_TEXTURES) break; } pInfo->m_SkinName[MAX_CS_FILENAME_LEN] = '\0'; m_nIntelId = pIntel->nId; if (pIntel->bChromakey) { m_dwFlags2 |= FLAG2_CHROMAKEY; } m_dwFlags = (pIntel->bChrome ? (m_dwFlags | FLAG_ENVIRONMENTMAP) : (m_dwFlags & ~FLAG_ENVIRONMENTMAP)); } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::PostPropRead() // // PURPOSE: Update Properties // // ----------------------------------------------------------------------- // void Intelligence::PostPropRead(ObjectCreateStruct *pStruct) { if (!pStruct) return; // Make us activateable... pStruct->m_Flags |= FLAG_RAYHIT; // Make sure we don't have gravity set... pStruct->m_Flags &= ~FLAG_GRAVITY; pStruct->m_fDeactivationTime = 0.5f; m_dwUsrFlgs |= (USRFLG_GLOW | USRFLG_IGNORE_PROJECTILES); if (m_bPhotoOnly) { m_dwUsrFlgs |= USRFLG_GADGET_INTELLIGENCE; } else { m_dwUsrFlgs |= USRFLG_CAN_ACTIVATE; } m_damage.SetCanHeal(LTFALSE); m_damage.SetCanRepair(LTFALSE); m_damage.SetApplyDamagePhysics(LTFALSE); m_damage.SetMaxHitPoints(1.0f); m_damage.SetHitPoints(1.0f); m_damage.SetCanDamage(LTFALSE); // Use the default info id if necessary... if (!m_nInfoId) { INTEL* pIntel = g_pIntelMgr->GetIntel(m_nIntelId); if (pIntel && m_bShowPopup) { m_nInfoId = pIntel->nDefaultTextId; } } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::ObjectMessageFn // // PURPOSE: Handle object-to-object messages // // ----------------------------------------------------------------------- // uint32 Intelligence::ObjectMessageFn(HOBJECT hSender, uint32 messageID, HMESSAGEREAD hRead) { if (!g_pLTServer) return 0; switch(messageID) { case MID_TRIGGER: { const char* szMsg = (const char*)g_pLTServer->ReadFromMessageDWord(hRead); // ConParse does not destroy szMsg, so this is safe ConParse parse; parse.Init((char*)szMsg); while (g_pLTServer->Common()->Parse(&parse) == LT_OK) { if (parse.m_nArgs > 0 && parse.m_Args[0]) { if (_stricmp(parse.m_Args[0], s_szActivate) == 0) { if (!m_bPhotoOnly) { DoActivate(hSender); } } else if (_stricmp(parse.m_Args[0], s_szGadget) == 0) { if (m_bPhotoOnly) { HandleGadgetMsg(hSender, parse); } } else if (_stricmp(parse.m_Args[0], s_szRespawn) == 0) { SetNextUpdate( m_fRespawnDelay / g_IntelRespawnScale.GetFloat(1.0f)); } } } } break; default : break; } return Prop::ObjectMessageFn(hSender, messageID, hRead); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::HandleGadgetMsg // // PURPOSE: Handle the camera gadget // // ----------------------------------------------------------------------- // void Intelligence::HandleGadgetMsg(HOBJECT hSender, ConParse & parse) { DoActivate(hSender); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::DoActivate() // // PURPOSE: Handle Activate... // // ----------------------------------------------------------------------- // void Intelligence::DoActivate(HOBJECT hSender) { // BL 10/30/00 - fix multiple photographs of items in multiplayer { if ( g_pGameServerShell->GetGameType() != SINGLE ) { uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); if ( !(dwFlags & FLAG_VISIBLE) ) { return; } } } HOBJECT hPlayer = hSender; if (!hSender || !IsPlayer(hSender)) { // Find the player if the sender isn't one... ObjArray <HOBJECT, 1> objArray; g_pLTServer->FindNamedObjects(DEFAULT_PLAYERNAME, objArray); if (!objArray.NumObjects()) return; hPlayer = objArray.GetObject(0); } // Increment the player's intelligence count... CPlayerObj* pPlayer = (CPlayerObj*)g_pLTServer->HandleToObject(hPlayer); if (pPlayer) { if (g_pGameServerShell->GetGameType() == COOPERATIVE_ASSAULT && m_nPlayerTeamFilter) { if (pPlayer->GetTeamID() != m_nPlayerTeamFilter) return; uint8 nScore = (uint8)g_vtNetIntelScore.GetFloat(); pPlayer->AddToScore(nScore); HCLIENT hClient = pPlayer->GetClient(); uint32 nPlayerID = g_pLTServer->GetClientID(hClient); HMESSAGEWRITE hWrite = g_pLTServer->StartMessage (LTNULL, MID_TEAM_SCORED); g_pLTServer->WriteToMessageDWord (hWrite, nPlayerID); g_pLTServer->WriteToMessageByte (hWrite, (uint8)pPlayer->GetTeamID()); g_pLTServer->WriteToMessageByte (hWrite, nScore); g_pLTServer->EndMessage (hWrite); } CPlayerSummaryMgr* pPSMgr = pPlayer->GetPlayerSummaryMgr(); if (pPSMgr) { pPSMgr->IncIntelligenceCount(); } HCLIENT hClient = pPlayer->GetClient(); if (hClient) { HMESSAGEWRITE hMessage = g_pLTServer->StartMessage(hClient, MID_PLAYER_INFOCHANGE); g_pLTServer->WriteToMessageByte(hMessage, IC_INTEL_PICKUP_ID); g_pLTServer->WriteToMessageByte(hMessage, 0); g_pLTServer->WriteToMessageByte(hMessage, 0); g_pLTServer->WriteToMessageFloat(hMessage, 0.0f); g_pLTServer->EndMessage(hMessage); } // Show the pop-up associated with the intelligence item, if // applicable... INTEL* pIntel = g_pIntelMgr->GetIntel(m_nIntelId); if (pIntel && m_bShowPopup) { char buf[255]; sprintf(buf, "msg %s (popup %d", DEFAULT_PLAYERNAME, m_nInfoId); // Add the scale fx... for (int i=0; i < pIntel->nNumScaleFXNames; i++) { if (pIntel->szScaleFXNames[i]) { strcat(buf, " "); strcat(buf, pIntel->szScaleFXNames[i]); } } strcat(buf, ")"); if (g_pCmdMgr->IsValidCmd(buf)) { g_pCmdMgr->Process(buf); } } // If we have a command, process it... if (m_hstrPickedUpCmd) { char* pCmd = g_pLTServer->GetStringData(m_hstrPickedUpCmd); if (pCmd && g_pCmdMgr->IsValidCmd(pCmd)) { g_pCmdMgr->Process(pCmd); } } if (g_pGameServerShell->GetGameType() == SINGLE) { g_pLTServer->RemoveObject(m_hObject); } else { uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); dwFlags &= (~FLAG_VISIBLE & ~FLAG_RAYHIT); g_pLTServer->SetObjectFlags(m_hObject, dwFlags); // Play pickup sound... LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); g_pServerSoundMgr->PlaySoundFromPos(vPos, INTEL_PICKUP_SOUND, 600.0f, SOUNDPRIORITY_MISC_HIGH); } } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Save // // PURPOSE: Save the object // // ----------------------------------------------------------------------- // void Intelligence::Save(HMESSAGEWRITE hWrite) { if (!hWrite) return; g_pLTServer->WriteToMessageByte(hWrite, m_bPhotoOnly); g_pLTServer->WriteToMessageByte(hWrite, m_bShowPopup); g_pLTServer->WriteToMessageHString(hWrite, m_hstrPickedUpCmd); g_pLTServer->WriteToMessageDWord(hWrite, m_nInfoId); g_pLTServer->WriteToMessageDWord(hWrite, m_nIntelId); g_pLTServer->WriteToMessageByte(hWrite, m_bStartHidden); g_pLTServer->WriteToMessageByte(hWrite, m_bFirstUpdate); g_pLTServer->WriteToMessageByte(hWrite, m_bSkipUpdate); g_pLTServer->WriteToMessageFloat(hWrite, m_fRespawnDelay); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Load // // PURPOSE: Load the object // // ----------------------------------------------------------------------- // void Intelligence::Load(HMESSAGEREAD hRead) { if (!hRead) return; m_bPhotoOnly = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_bShowPopup = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_hstrPickedUpCmd = g_pLTServer->ReadFromMessageHString(hRead); m_nInfoId = g_pLTServer->ReadFromMessageDWord(hRead); m_nIntelId = g_pLTServer->ReadFromMessageDWord(hRead); m_bStartHidden = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_bFirstUpdate = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_bSkipUpdate = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_fRespawnDelay = g_pLTServer->ReadFromMessageFloat(hRead); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Update() // // PURPOSE: Update // // ----------------------------------------------------------------------- // LTBOOL Intelligence::Update() { if (m_bFirstUpdate) { m_bFirstUpdate = LTFALSE; if (m_bStartHidden) { SendTriggerMsgToObject(this, m_hObject, LTFALSE, "Hidden 1"); return LTTRUE; } } // If we aren't visible it must be time to respawn... uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); if (!m_bSkipUpdate && !(dwFlags & FLAG_VISIBLE)) { uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); dwFlags |= (FLAG_VISIBLE | FLAG_RAYHIT); g_pLTServer->SetObjectFlags(m_hObject, dwFlags); // Let the world know what happened... LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); g_pServerSoundMgr->PlaySoundFromPos(vPos, INTEL_RESPAWN_SOUND, 600.0f, SOUNDPRIORITY_MISC_HIGH); } m_bSkipUpdate = LTFALSE; return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::InitialUpdate() // // PURPOSE: First update // // ----------------------------------------------------------------------- // void Intelligence::InitialUpdate() { if (!g_IntelRespawnScale.IsInitted()) { g_IntelRespawnScale.Init(GetServerDE(), "IntelRespawnScale", LTNULL, 1.0f); } if (m_bStartHidden) { SetNextUpdate(0.001f); } m_bSkipUpdate = m_bMoveToFloor; CacheFiles(); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::CacheFiles // // PURPOSE: Cache whatever resources this object uses // // ----------------------------------------------------------------------- // void Intelligence::CacheFiles() { g_pLTServer->CacheFile(FT_SOUND, INTEL_RESPAWN_SOUND); g_pLTServer->CacheFile(FT_SOUND, INTEL_PICKUP_SOUND); }
24.215429
105
0.592871
haekb
60bb1ee20f89d138407a84ba5d07d197b2ca436b
166,332
hpp
C++
external/boost_1_60_0/qsboost/phoenix/core/detail/preprocessed/call_50.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/phoenix/core/detail/preprocessed/call_50.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/phoenix/core/detail/preprocessed/call_50.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
/*============================================================================== Copyright (c) 2005-2010 Joel de Guzman Copyright (c) 2010 Thomas Heller Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ namespace detail { template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 1> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename qsboost::result_of< Fun(A0, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 2> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename qsboost::result_of< Fun(A0 , A1, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 3> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename qsboost::result_of< Fun(A0 , A1 , A2, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 4> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 5> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 6> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 7> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 8> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 9> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 10> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 11> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 12> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 13> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 14> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 15> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 16> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 17> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 18> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 19> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 20> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 21> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 22> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 23> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 24> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 25> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 26> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 27> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 28> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 29> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 30> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 31> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 32> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 33> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 34> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 35> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 36> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 37> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 38> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 39> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 40> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 41> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 42> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 43> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 44> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 45> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 46> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 47> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 48> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename proto::result_of::child_c<Expr, 47>::type A47; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46 , A47, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , proto::child_c< 47>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 49> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename proto::result_of::child_c<Expr, 47>::type A47; typedef typename proto::result_of::child_c<Expr, 48>::type A48; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46 , A47 , A48, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , proto::child_c< 47>(e) , proto::child_c< 48>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 50> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename proto::result_of::child_c<Expr, 47>::type A47; typedef typename proto::result_of::child_c<Expr, 48>::type A48; typedef typename proto::result_of::child_c<Expr, 49>::type A49; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46 , A47 , A48 , A49, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , proto::child_c< 47>(e) , proto::child_c< 48>(e) , proto::child_c< 49>(e) , qsboost::phoenix::context(s, d) ); } }; }
97.156542
3,191
0.621859
wouterboomsma
60bb6951d7ba7390222e945f807c0b5551e529c6
1,039
cpp
C++
Ass7/Q8.cpp
nitishgarg2002/DSA-assignments
34ec3e77e6bb00bc2ab86d2960a18d9e53300c06
[ "MIT" ]
null
null
null
Ass7/Q8.cpp
nitishgarg2002/DSA-assignments
34ec3e77e6bb00bc2ab86d2960a18d9e53300c06
[ "MIT" ]
null
null
null
Ass7/Q8.cpp
nitishgarg2002/DSA-assignments
34ec3e77e6bb00bc2ab86d2960a18d9e53300c06
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *left, *right; }; bool iterativeSearch(struct Node* root, int key) { while (root != NULL) { if (key > root->data) root = root->right; else if (key < root->data) root = root->left; else return true; } return false; } struct Node* newNode(int item) { struct Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } struct Node* insert(struct Node* Node, int data) { if (Node == NULL) return newNode(data); if (data < Node->data) Node->left = insert(Node->left, data); else if (data > Node->data) Node->right = insert(Node->right, data); return Node; } int main() { struct Node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout<<"Searching for 15: in 30 20 40 70 60 80 "<<endl; if (iterativeSearch(root, 15)) cout << "Found"; else cout << "Not Found"; return 0; }
17.610169
58
0.628489
nitishgarg2002
60bd34d4741ea33784463ca8c037f839c8bef2c3
1,574
cpp
C++
Train/El_Sageer/El_Sageer_Pupil/08 - 14 - [SP]/08 - 10 - [SP] Brute Force/10 - [SP] Brute Force/extra/4.CF [467B].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
1
2019-12-19T06:51:20.000Z
2019-12-19T06:51:20.000Z
Train/El_Sageer/El_Sageer_Pupil/08 - 14 - [SP]/08 - 10 - [SP] Brute Force/10 - [SP] Brute Force/extra/4.CF [467B].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
Train/El_Sageer/El_Sageer_Pupil/08 - 14 - [SP]/08 - 10 - [SP] Brute Force/10 - [SP] Brute Force/extra/4.CF [467B].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // input handle #define iln() scanf("\n") #define in(n) scanf("%d",&n) #define ins(n) scanf("%s",n) #define inc(n) scanf("%c",&n) #define inf(n) scanf("%lf",&n) #define inl(n) scanf("%lld",&n) #define ot(x) printf("%d", x) #define sp() printf(" ") #define ots(x) printf("%s", x) #define otc(x) printf("%c", x) #define ln() printf("\n") #define otl(x) printf("%lld", x) #define otf(x) printf("%.2lf", x) // helpers defines #define all(v) v.begin(), v.end() #define sz(v) ((int)((v).size())) #define ssz(s) ((int)strlen(s)) #define pb push_back #define mem(a,b) memset(a,b,sizeof(a)) //helpers void file() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); // freopen("ot.txt", "w", stdout); #else // freopen("jumping.in", "r", stdin); // HERE #endif } // constants #define EPS 1e-9 #define PI acos(-1.0) // important constant; alternative #define PI (2.0 * acos(0.0)) const int MN = 1e9 + 1e2; const int MW = 1e3 + 5; typedef long long int lli; const int OO = 1e9 + 5; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ii> vii; typedef pair<lli, string> lls; #define isOn(S, j) (S & (1 << j)) #define setBit(S, j) (S |= (1 << j)) #define clearBit(S, j) (S &= ~(1 << j)) int main() { file(); //TODO int n, m, k, p[1002] { 0 }, ans = 0; in(n), in(m), in(k); for (int i = 0; i <= m and in(p[i]); ++i) ; for (int i = 0, df = 0; i < m; ans += (df <= k), df = 0, ++i) for (int j = 0; j < 21 and df <= k; ++j) if (isOn(p[m],j) != isOn(p[i], j)) df++; ot(ans); return 0; }
25.387097
85
0.576239
mohamedGamalAbuGalala
60bd97fce1793240c01a2c27f987df91e406831a
776
hpp
C++
Libraries/Gameplay/DefaultGame.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Gameplay/DefaultGame.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Gameplay/DefaultGame.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once namespace Zero { /// Create the starting space and load the starting level into that space class DefaultGameSetup : public Component { public: ZilchDeclareType(DefaultGameSetup, TypeCopyMode::ReferenceType); DefaultGameSetup(); // Component Interface void Initialize(CogInitializer& initializer) override; void Serialize(Serializer& stream) override; void SetDefaults() override; // Space to create for the game. ResourceProperty(Archetype, StartingSpace); // Level to load into the game. ResourceProperty(Level, StartingLevel); void OnSetup(GameEvent* event); // If set to true StartingLevel will be overridden by the currently edited // level bool mLoadEditingLevel; }; } // namespace Zero
22.823529
76
0.753866
RyanTylerRae
60bdb76c845c09b3386e2c3d06b65c916577ae7b
8,110
cpp
C++
Core/GDCore/Serialization/SerializerElement.cpp
sutao80216/GDevelop
79461bf01cc0c626e2f094d3fca940d643f93d76
[ "MIT" ]
1
2019-08-24T03:18:42.000Z
2019-08-24T03:18:42.000Z
Core/GDCore/Serialization/SerializerElement.cpp
sutao80216/GDevelop
79461bf01cc0c626e2f094d3fca940d643f93d76
[ "MIT" ]
9
2020-04-04T19:26:47.000Z
2022-03-25T18:41:20.000Z
Core/GDCore/Serialization/SerializerElement.cpp
sutao80216/GDevelop
79461bf01cc0c626e2f094d3fca940d643f93d76
[ "MIT" ]
2
2020-03-02T05:20:41.000Z
2021-05-10T03:59:05.000Z
#include "GDCore/Serialization/SerializerElement.h" #include <iostream> namespace gd { SerializerElement SerializerElement::nullElement; SerializerElement::SerializerElement() : valueUndefined(true), isArray(false) {} SerializerElement::SerializerElement(const SerializerValue& value) : valueUndefined(false), elementValue(value), isArray(false) {} SerializerElement::~SerializerElement() {} const SerializerValue& SerializerElement::GetValue() const { if (valueUndefined && attributes.find("value") != attributes.end()) return attributes.find("value")->second; return elementValue; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, bool value) { attributes[name].SetBool(value); return *this; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, const gd::String& value) { attributes[name].SetString(value); return *this; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, int value) { attributes[name].SetInt(value); return *this; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, double value) { attributes[name].SetDouble(value); return *this; } bool SerializerElement::GetBoolAttribute(const gd::String& name, bool defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) { return attributes.find(name)->second.GetBool(); } else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) { return attributes.find(deprecatedName)->second.GetBool(); } else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) { return child.GetValue().GetBool(); } } } std::cout << "Bool attribute \"" << name << "\" not found, returning " << defaultValue; return defaultValue; } gd::String SerializerElement::GetStringAttribute( const gd::String& name, gd::String defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) return attributes.find(name)->second.GetString(); else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) return attributes.find(deprecatedName)->second.GetString(); else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) return child.GetValue().GetString(); } } return defaultValue; } int SerializerElement::GetIntAttribute(const gd::String& name, int defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) return attributes.find(name)->second.GetInt(); else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) return attributes.find(deprecatedName)->second.GetInt(); else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) return child.GetValue().GetInt(); } } return defaultValue; } double SerializerElement::GetDoubleAttribute(const gd::String& name, double defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) return attributes.find(name)->second.GetDouble(); else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) return attributes.find(deprecatedName)->second.GetDouble(); else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) return child.GetValue().GetDouble(); } } return defaultValue; } bool SerializerElement::HasAttribute(const gd::String& name) const { return attributes.find(name) != attributes.end(); } SerializerElement& SerializerElement::AddChild(gd::String name) { if (!arrayOf.empty()) { if (name != arrayOf) { std::cout << "WARNING: Adding a child, to a SerializerElement which is " "considered as an array, with a name (" << name << ") which is not the same as the array elements (" << arrayOf << "). Child was renamed." << std::endl; name = arrayOf; } } std::shared_ptr<SerializerElement> newElement(new SerializerElement); children.push_back(std::make_pair(name, newElement)); return *newElement; } SerializerElement& SerializerElement::GetChild(std::size_t index) const { if (arrayOf.empty()) { std::cout << "ERROR: Getting a child from its index whereas the parent is " "not considered as an array." << std::endl; return nullElement; } std::size_t currentIndex = 0; for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == arrayOf || children[i].first.empty() || (!deprecatedArrayOf.empty() && children[i].first == deprecatedArrayOf)) { if (index == currentIndex) return *children[i].second; else currentIndex++; } } std::cout << "ERROR: Request out of bound child at index " << index << std::endl; return nullElement; } SerializerElement& SerializerElement::GetChild( gd::String name, std::size_t index, gd::String deprecatedName) const { if (!arrayOf.empty()) { if (name != arrayOf) { std::cout << "WARNING: Getting a child, from a SerializerElement which " "is considered as an array, with a name (" << name << ") which is not the same as the array elements (" << arrayOf << ")." << std::endl; name = arrayOf; } } std::size_t currentIndex = 0; for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == name || (!arrayOf.empty() && children[i].first.empty()) || (!deprecatedName.empty() && children[i].first == deprecatedName)) { if (index == currentIndex) return *children[i].second; else currentIndex++; } } std::cout << "Child " << name << " not found in SerializerElement::GetChild" << std::endl; return nullElement; } std::size_t SerializerElement::GetChildrenCount( gd::String name, gd::String deprecatedName) const { if (name.empty()) { if (arrayOf.empty()) { std::cout << "ERROR: Getting children count without specifying name, from a " "SerializerElement which is NOT considered as an array." << std::endl; return 0; } name = arrayOf; deprecatedName = deprecatedArrayOf; } std::size_t currentIndex = 0; for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == name || (!arrayOf.empty() && children[i].first.empty()) || (!deprecatedName.empty() && children[i].first == deprecatedName)) currentIndex++; } return currentIndex; } bool SerializerElement::HasChild(const gd::String& name, gd::String deprecatedName) const { for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == name || (!deprecatedName.empty() && children[i].first == deprecatedName)) return true; } return false; } } // namespace gd
33.102041
80
0.6164
sutao80216
60bff93a2d1c86ee195cce173b5eb541bb0eff88
7,087
cpp
C++
test/thread/source/TestThreadRWSemaLock.cpp
tlzyh/EAThread
b5e246fa86d8de5ddbcdb098df0a75f5e8839f5a
[ "BSD-3-Clause" ]
255
2019-06-11T07:05:51.000Z
2022-03-08T20:35:12.000Z
test/thread/source/TestThreadRWSemaLock.cpp
tlzyh/EAThread
b5e246fa86d8de5ddbcdb098df0a75f5e8839f5a
[ "BSD-3-Clause" ]
4
2019-08-10T21:35:17.000Z
2021-11-24T10:42:24.000Z
test/thread/source/TestThreadRWSemaLock.cpp
tlzyh/EAThread
b5e246fa86d8de5ddbcdb098df0a75f5e8839f5a
[ "BSD-3-Clause" ]
75
2019-07-08T00:16:33.000Z
2022-02-25T03:41:13.000Z
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Electronic Arts Inc. All rights reserved. /////////////////////////////////////////////////////////////////////////////// #include "TestThread.h" #include <EATest/EATest.h> #include <eathread/eathread_thread.h> #include <eathread/eathread_rwsemalock.h> #include <stdlib.h> const int kThreadCount = EATHREAD_MAX_CONCURRENT_THREAD_COUNT; /////////////////////////////////////////////////////////////////////////////// // RWSTestType // enum RWSTestType { kRWSTestTypeStandard, kRWSTestTypeAllWriters, kRWSTestTypeAllReaders, kRWSTestTypeMostlyWriters, kRWSTestTypeMostlyReaders, kRWSTestTypeCount }; /////////////////////////////////////////////////////////////////////////////// // RWSemaWorkData // struct RWSemaWorkData { volatile bool mbShouldQuit; EA::Thread::RWSemaLock mRWSemaLock; volatile int mnWriterCount; EA::Thread::AtomicInt32 mnErrorCount; EA::Thread::AtomicInt32 mnCurrentTestType; RWSemaWorkData() : mbShouldQuit(false) , mRWSemaLock() , mnWriterCount(0) , mnErrorCount(0) , mnCurrentTestType(kRWSTestTypeStandard) {} private: RWSemaWorkData(const RWSemaWorkData& rhs); RWSemaWorkData& operator=(const RWSemaWorkData& rhs); }; /////////////////////////////////////////////////////////////////////////////// // RWSThreadFunction // static intptr_t RWSThreadFunction(void* pvWorkData) { using namespace EA::Thread; RWSemaWorkData* const pWorkData = (RWSemaWorkData*)pvWorkData; ThreadId threadId = GetThreadId(); EA::UnitTest::ReportVerbosity(1, "RWSemaLock test function created: %s\n", EAThreadThreadIdToString(threadId)); int nErrorCount = 0; while(!pWorkData->mbShouldQuit) { int nWriteLockChance = 0; const RWSTestType testType = (RWSTestType)pWorkData->mnCurrentTestType.GetValue(); switch (testType) { default: case kRWSTestTypeStandard: nWriteLockChance = 20; break; case kRWSTestTypeAllWriters: nWriteLockChance = 1000; break; case kRWSTestTypeAllReaders: nWriteLockChance = 0; break; case kRWSTestTypeMostlyWriters: nWriteLockChance = 700; break; case kRWSTestTypeMostlyReaders: nWriteLockChance = 5; break; } const bool bShouldWrite = ((rand() % 1000) < nWriteLockChance); if(bShouldWrite) { AutoSemaWriteLock _(pWorkData->mRWSemaLock); pWorkData->mnWriterCount++; EA::UnitTest::ThreadSleepRandom(2, 10); pWorkData->mnWriterCount--; } else { AutoSemaReadLock _(pWorkData->mRWSemaLock); EATEST_VERIFY_MSG(pWorkData->mnWriterCount == 0, "ReadLock is held, there should be no active WriteLocks."); } } pWorkData->mnErrorCount.SetValue(nErrorCount); return nErrorCount; } // NOTE(rparolin): // This exists to introduce test-only functionality for the RWSemaLock. We can add these functions here because we // guarantee they will not be called in a concurrent context and they simplify validation of assumption of the lock. struct TestRWSemaLock : public EA::Thread::RWSemaLock { TestRWSemaLock() = default; TestRWSemaLock(const TestRWSemaLock&) = delete; TestRWSemaLock(TestRWSemaLock&&) = delete; TestRWSemaLock& operator=(const TestRWSemaLock&) = delete; TestRWSemaLock& operator=(TestRWSemaLock&&) = delete; bool IsReadLocked() { Status status; status.data = mStatus.GetValue(); return status.readers > 0; } bool IsWriteLocked() { Status status; status.data = mStatus.GetValue(); return status.writers > 0; } }; int TestThreadRWSemaLock() { using namespace EA::Thread; int nErrorCount = 0; { // RWSemaLock -- Basic single-threaded test. TestRWSemaLock rwSemaLock; // There are no construction parameters. EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); rwSemaLock.ReadTryLock(); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.WriteTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); rwSemaLock.ReadLock(); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); rwSemaLock.ReadUnlock(); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); rwSemaLock.ReadUnlock(); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); rwSemaLock.WriteTryLock(); EATEST_VERIFY_MSG(rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.ReadTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.WriteTryLock(), "RWSemaLock failure"); } { // AutoRWSemaLock -- Basic single-threaded test. TestRWSemaLock rwSemaLock; // There are no construction parameters. { //Special scope just for the AutoRWSemaLock AutoSemaReadLock autoRWSemaLock1(rwSemaLock); AutoSemaReadLock autoRWSemaLock2(rwSemaLock); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.WriteTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); } EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); { //Special scope just for the AutoRWSemaLock AutoSemaWriteLock autoRWSemaLock(rwSemaLock); EATEST_VERIFY_MSG(rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.ReadTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); } EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); } #if EA_THREADS_AVAILABLE { // Multithreaded test RWSemaWorkData workData; Thread thread[kThreadCount]; ThreadId threadId[kThreadCount]; Thread::Status status; for(int i(0); i < kThreadCount; i++) threadId[i] = thread[i].Begin(RWSThreadFunction, &workData); for(int e = 0; e < kRWSTestTypeCount; e++) { workData.mnCurrentTestType.SetValue(e); EA::UnitTest::ThreadSleepRandom(gTestLengthSeconds * 500, gTestLengthSeconds * 500); } workData.mbShouldQuit = true; for(int t(0); t < kThreadCount; t++) { if(threadId[t] != kThreadIdInvalid) { status = thread[t].WaitForEnd(GetThreadTime() + 30000); EATEST_VERIFY_MSG(status != Thread::kStatusRunning, "RWSemalock/Thread failure: status == kStatusRunning.\n"); } } nErrorCount += (int)workData.mnErrorCount; } #endif return nErrorCount; }
27.257692
116
0.693241
tlzyh
60c2a63fc40b22d424c579291dbc7add26e10f4f
8,693
cpp
C++
applications/_libs/cmp_mesh/jrt/jrtppmimage.cpp
galek/Compressonator
cb281b97eb05e35ec739a462c71524c4b1eefae3
[ "MIT" ]
622
2016-05-12T17:39:27.000Z
2020-03-09T08:51:41.000Z
applications/_libs/cmp_mesh/jrt/jrtppmimage.cpp
galek/Compressonator
cb281b97eb05e35ec739a462c71524c4b1eefae3
[ "MIT" ]
110
2020-03-14T15:30:42.000Z
2022-03-31T07:59:29.000Z
applications/_libs/cmp_mesh/jrt/jrtppmimage.cpp
galek/Compressonator
cb281b97eb05e35ec739a462c71524c4b1eefae3
[ "MIT" ]
105
2016-05-12T18:55:39.000Z
2020-03-04T15:02:01.000Z
/************************************************************************************//** // Copyright (c) 2006-2015 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file ****************************************************************************************/ #include "tootlepch.h" #include "jrtcommon.h" #include "jrtppmimage.h" /********************************************************/ /****** Implementation of Class JRTPPMJRTPPMImage *******************/ /********************************************************/ /*************************** * JRTPPMImage Constructor: * Sets the width and height of the image, in pixels * allocates memory for pixels. Each pixel is initialized to * 0,0,0 (black) ***************************/ JRTPPMImage::JRTPPMImage(int width, int height) { p_mlpPixels = NULL; p_miWidth = 0; p_miHeight = 0; AllocPixels(width, height); } JRTPPMImage::JRTPPMImage(const JRTPPMImage& img) { *this = img; } const JRTPPMImage& JRTPPMImage::operator =(const JRTPPMImage& img) { FreePixels(); this->p_miHeight = img.p_miHeight; this->p_miWidth = img.p_miWidth; this->p_mlpPixels = new PIXEL[ GetWidth() * GetHeight() ]; memcpy(this->p_mlpPixels, img.p_mlpPixels, sizeof(PIXEL)*GetWidth()*GetHeight()); return *this; } /*************************** * JRTPPMImage Destructor: * Frees all dynamic memory. ***************************/ JRTPPMImage::~JRTPPMImage() { FreePixels(); } double Round(double x) { double frac = x - floor(x); if (frac > 0.5) { return ceil(x); } else { return floor(x); } } void JRTPPMImage::SetPixel(int x, int y, float r, float g, float b) { if (x >= 0 && x < p_miWidth && y >= 0 && y < p_miHeight) { p_mlpPixels[y * p_miWidth + x].r = (unsigned char)Round(r * 255.0); p_mlpPixels[y * p_miWidth + x].g = (unsigned char)Round(g * 255.0); p_mlpPixels[y * p_miWidth + x].b = (unsigned char)Round(b * 255.0); } } /****************************** * SaveFile * Outputs the image to a PPM (P6) file * with the specified filename. Returns true if the * output was a success, false if not. *********************************/ bool JRTPPMImage::SaveFile(const char* sFile) { // binary write must be specified or this code blows up // on windows FILE* fp = fopen(sFile, "wb"); // sanity check if (fp == NULL) { return false; } // print PPM header stuff fprintf(fp, "P6\n%d %d\n%d\n", this->p_miWidth, this->p_miHeight, 255); // iterate across pixels and dump them to the file for (int row = 0; row < p_miHeight; row++) { for (int col = 0; col < p_miWidth; col++) { const PIXEL& pix = p_mlpPixels[(row * p_miWidth) + col]; fwrite(&pix, 3, 1, fp); } // repeat for next pixel } fclose(fp); return true; } /* Helper function for parsing the headers of PPM files */ void ISkipToToken(FILE* fp) { bool hit_token = false; while (!feof(fp) && !hit_token) { // skip to beginning of next token (width, height, or maxval) int c = fgetc(fp); if (c == '#') { // comment, skip ahead till next newline while (!feof(fp) && c != '\n' && c != '\f' && c != '\r') { c = fgetc(fp); } } else if (c == '\n' || c == '\f' || c == '\r' || c == '\t' || c == ' ') { // whitespace, skip it } else { hit_token = true; // we need that character we just read, so backtrack so we're pointed at it ungetc(c, fp); } } } bool JRTPPMImage::LoadFile(const char* filename) { // try and open the image file FILE* fp = fopen(filename, "rb"); if (fp == NULL) { return false; } /* For reference, here is the PPM image format description, direct from the ppm man page. A "magic number" for identifying the file type. A ppm file's magic number is the two characters "P3". Whitespace (blanks, TABs, CRs, LFs). A width, formatted as ASCII characters in decimal. Whitespace. A height, again in ASCII decimal. Whitespace. The maximum color-component value, again in ASCII decimal. Whitespace. Width * height pixels, each three ASCII decimal values between 0 and the specified maximum value, starting at the top-left corner of the pixmap, proceeding in normal English reading order. The three values for each pixel represent red, green, and blue, respectively; a value of 0 means that color is off, and the maximum value means that color is maxxed out. Characters from a "#" to the next end-of-line are ignored (comments). No line should be longer than 70 characters. The "magic number" is "P6" instead of "P3". The pixel values are stored as plain bytes, instead of ASCII decimal. Whitespace is not allowed in the pixels area, and only a single character of whitespace (typically a newline) is allowed after the maxval. */ // first two bytes had better be "P6" if (fgetc(fp) != 'P') { fclose(fp); return false; } if (fgetc(fp) != '6') { fclose(fp); return false; } UINT width = 0, height = 0, maxval = 0; // parse out the width, height, and maxval, ignoring whitespace and comments. bool at_bits = false, got_width = false, got_height = false, got_maxval = false; while (!at_bits && !feof(fp)) { ISkipToToken(fp); if (!got_width) { // read width if (fscanf(fp, "%d", &width) != 1) { fclose(fp); return false; } got_width = true; } else if (!got_height) { // read height if (fscanf(fp, "%d", &height) != 1) { fclose(fp); return false; } got_height = true; } else if (!got_maxval) { // read maxval if (fscanf(fp, "%d", &maxval) != 1) { fclose(fp); return false; } got_maxval = true; at_bits = true; } } // verify that we got all the header information we needed // if we're EOF, it means we did not if (feof(fp) && (!got_width || !got_height || !got_maxval)) { fclose(fp); return false; } // there are now 3*width*height bytes left in the file. // excluding the extraneous whitespace that may or may not be there // allocate enough space for the rest of the data unsigned char* bytes = (unsigned char*)malloc(3 * width * height); // store current file position long offs = ftell(fp); // read the data size_t bytes_read = fread(bytes, 1, 3 * width * height, fp); if (bytes_read < 3 * width * height) { // not enough bytes fclose(fp); free(bytes); return false; } else if (!feof(fp)) { // still more data in file, means that there was // extraneous whitespace before that needs to be skipped int extra_bytes = 0; while (!feof(fp)) { extra_bytes++; fgetc(fp); } extra_bytes--; // disregard EOF character fseek(fp, offs, SEEK_SET); for (int i = 0; i < extra_bytes; i++) { fgetc(fp); } bytes_read = fread(bytes, 1, 3 * width * height, fp); if (bytes_read != 3 * width * height) { // something is wrong fclose(fp); free(bytes); return false; } } // convert data to double and copy it AllocPixels(width, height); int i = 0; for (int y = 0; y < GetHeight(); y++) { for (int x = 0; x < GetWidth(); x++) { float r = bytes[i] / (float)maxval; float g = bytes[i + 1] / (float)maxval; float b = bytes[i + 2] / (float)maxval; i += 3; SetPixel(x, y, r, g, b); } } free(bytes); return true; } void JRTPPMImage::AllocPixels(int iWidth, int iHeight) { // prevent accidental memory leaks if (p_mlpPixels != NULL) { FreePixels(); } p_miWidth = iWidth; p_miHeight = iHeight; // and make new pixel memory p_mlpPixels = new PIXEL[p_miHeight * p_miWidth]; } void JRTPPMImage::FreePixels() { delete[] p_mlpPixels; p_mlpPixels = NULL; } PIXEL* JRTPPMImage::AccessPixel(int x, int y) { return &p_mlpPixels[ y * p_miWidth + x ]; }
26.26284
130
0.531002
galek
60c347cbfc16aacf9b224bbdadebd88d336cf128
3,371
cpp
C++
3rdparty/unittest-cpp-master/tests/TestDeferredTestReporter.cpp
SiddGururani/MUSI8903_Assignment_2
c4a4dba1206e5772cd1c515ecc59fe7eac803de5
[ "MIT" ]
493
2015-04-16T13:43:20.000Z
2022-03-31T03:54:17.000Z
3rdparty/unittest-cpp-master/tests/TestDeferredTestReporter.cpp
SiddGururani/MUSI8903_Assignment_2
c4a4dba1206e5772cd1c515ecc59fe7eac803de5
[ "MIT" ]
30
2015-01-13T12:17:13.000Z
2021-06-03T14:12:10.000Z
3rdparty/unittest-cpp-master/tests/TestDeferredTestReporter.cpp
SiddGururani/MUSI8903_Assignment_2
c4a4dba1206e5772cd1c515ecc59fe7eac803de5
[ "MIT" ]
112
2015-01-14T12:01:00.000Z
2022-03-29T06:42:00.000Z
#include "UnitTest++/Config.h" #ifndef UNITTEST_NO_DEFERRED_REPORTER #include "UnitTest++/UnitTestPP.h" #include "UnitTest++/DeferredTestReporter.h" #include <cstring> namespace UnitTest { namespace { #ifndef UNITTEST_MEMORYOUTSTREAM_IS_STD_OSTRINGSTREAM MemoryOutStream& operator <<(MemoryOutStream& lhs, const std::string& rhs) { lhs << rhs.c_str(); return lhs; } #endif struct MockDeferredTestReporter : public DeferredTestReporter { virtual void ReportSummary(int, int, int, float) { } }; struct DeferredTestReporterFixture { DeferredTestReporterFixture() : testName("UniqueTestName") , testSuite("UniqueTestSuite") , fileName("filename.h") , lineNumber(12) , details(testName.c_str(), testSuite.c_str(), fileName.c_str(), lineNumber) { } MockDeferredTestReporter reporter; std::string const testName; std::string const testSuite; std::string const fileName; int const lineNumber; TestDetails const details; }; TEST_FIXTURE(DeferredTestReporterFixture, ReportTestStartCreatesANewDeferredTest) { reporter.ReportTestStart(details); CHECK_EQUAL(1, (int)reporter.GetResults().size()); } TEST_FIXTURE(DeferredTestReporterFixture, ReportTestStartCapturesTestNameAndSuite) { reporter.ReportTestStart(details); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK_EQUAL(testName.c_str(), result.testName.c_str()); CHECK_EQUAL(testSuite.c_str(), result.suiteName.c_str()); } TEST_FIXTURE(DeferredTestReporterFixture, ReportTestEndCapturesTestTime) { float const elapsed = 123.45f; reporter.ReportTestStart(details); reporter.ReportTestFinish(details, elapsed); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK_CLOSE(elapsed, result.timeElapsed, 0.0001f); } TEST_FIXTURE(DeferredTestReporterFixture, ReportFailureSavesFailureDetails) { char const* failure = "failure"; reporter.ReportTestStart(details); reporter.ReportFailure(details, failure); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK(result.failed == true); CHECK_EQUAL(fileName.c_str(), result.failureFile.c_str()); } TEST_FIXTURE(DeferredTestReporterFixture, ReportFailureSavesFailureDetailsForMultipleFailures) { char const* failure1 = "failure 1"; char const* failure2 = "failure 2"; reporter.ReportTestStart(details); reporter.ReportFailure(details, failure1); reporter.ReportFailure(details, failure2); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK_EQUAL(2, (int)result.failures.size()); CHECK_EQUAL(failure1, result.failures[0].failureStr); CHECK_EQUAL(failure2, result.failures[1].failureStr); } TEST_FIXTURE(DeferredTestReporterFixture, DeferredTestReporterTakesCopyOfFailureMessage) { reporter.ReportTestStart(details); char failureMessage[128]; char const* goodStr = "Real failure message"; char const* badStr = "Bogus failure message"; using namespace std; strcpy(failureMessage, goodStr); reporter.ReportFailure(details, failureMessage); strcpy(failureMessage, badStr); DeferredTestResult const& result = reporter.GetResults().at(0); DeferredTestFailure const& failure = result.failures.at(0); CHECK_EQUAL(goodStr, failure.failureStr); } }} #endif
27.406504
94
0.741916
SiddGururani
60c3624ae54625c59d506dfb35ab0fe7368b4bd6
16,722
cc
C++
llcc/front-end/src/inter_code_generator.cc
toy-compiler/toy_js_compiler
4267c96cd65b2359b6ba70dad7ee1f17114e88fc
[ "MIT" ]
2
2019-03-12T07:42:33.000Z
2019-03-12T07:42:41.000Z
llcc/front-end/src/inter_code_generator.cc
toy-compiler/awesomeCC
4267c96cd65b2359b6ba70dad7ee1f17114e88fc
[ "MIT" ]
null
null
null
llcc/front-end/src/inter_code_generator.cc
toy-compiler/awesomeCC
4267c96cd65b2359b6ba70dad7ee1f17114e88fc
[ "MIT" ]
1
2019-11-29T11:13:22.000Z
2019-11-29T11:13:22.000Z
/** * @file inter_code_generator.h * @brief 中间代码生成器类具体实现 */ #include "../include/inter_code_generator.h" #define POS(cur) cur->line_number, cur->pos map<string, VARIABLE_INFO_ENUM> Info::VAR_INFO_MAP = { {"double", VARIABLE_INFO_ENUM::DOUBLE}, {"float", VARIABLE_INFO_ENUM::DOUBLE}, {"int", VARIABLE_INFO_ENUM::INT}, {"void", VARIABLE_INFO_ENUM::VOID}, }; /** * @brief VarInfo构造函数 */ VarInfo::VarInfo() = default; /** * @brief VarInfo构造函数 * @param _name 变量名字 * @param _type 种类 */ VarInfo::VarInfo(VARIABLE_INFO_ENUM _type, int _place) { name = "v" + int2string(_place); place = _place; type = _type; } FuncInfo::FuncInfo() = default; FuncInfo::FuncInfo(string _name, VARIABLE_INFO_ENUM _ret_type, int _start_place, int _end_place) { name = move(_name); ret_type = _ret_type; start_place = _start_place; end_place = _end_place; } /** * @brief 中间代码生成器构造函数 */ InterCodeGenerator::InterCodeGenerator() = default; /** * @brief 中间代码生成 * @param _tree SyntaxTree * */ void InterCodeGenerator::analyze(SyntaxTree * _tree, bool verbose) { inter_code.clear(); var_index = 0; temp_var_index = 0; context_index = 0; func_backpatch.clear(); tree = _tree; try { _analyze(tree -> root -> first_son); } catch (Error & e) { cout << "Semantic analyze errors :" << endl; cout << e; exit(0); } if (verbose) { int l = inter_code.size(); cout << "Generated " << l << " inter codes" << endl; for (int i = 0; i < l; i ++) { cout << "#" << setw(3) << setfill(' ') << std::left << i; cout << inter_code[i]; } } } void InterCodeGenerator::_analyze(SyntaxTreeNode * cur) { SyntaxTreeNode * name_tree, * main_block; vector<SyntaxTreeNode *> funcs; string name, type; while (cur) { temp_var_index = 0; if (cur -> value == "FunctionStatement") { name_tree = cur -> first_son -> right; name = name_tree -> first_son -> value; if (name == "main") main_block = name_tree -> right -> right; else { type = cur -> first_son -> value; func_table[name] = FuncInfo(name, Info::VAR_INFO_MAP[type], 0, 0); funcs.emplace_back(cur); } } else if (cur -> value == "Statement") { _statement(cur); } else throw Error("`" + cur -> value + "` is not allowed in a root of a class", POS(cur)); cur = cur -> right; } // main 函数直接执行 _block(main_block, false); int main_end = inter_code.size(); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); // 翻译别的函数 for (auto func: funcs) _functionStatement(func); // main 结束就直接结束 inter_code[main_end].res = int2string(inter_code.size()); for (auto it: func_backpatch) if (! it.second.empty()) { string dest = int2string(func_table[it.first].start_place); for (auto i: it.second) inter_code[i].res = dest; } } void InterCodeGenerator::_functionStatement(SyntaxTreeNode * cur) { SyntaxTreeNode * name_tree, * param_tree, * block_tree, * type_tree; type_tree = cur -> first_son; name_tree = type_tree -> right; param_tree = name_tree -> right; block_tree = param_tree -> right; string func_name = name_tree -> first_son -> value; int func_start = int(inter_code.size()); // start SyntaxTreeNode * ps = param_tree -> first_son; while (ps) { _statement(ps); _emit(INTER_CODE_OP_ENUM::POP, "", "", table[ps -> first_son -> value].name); ps = ps -> right; } _block(block_tree); string temp_place = "t" + int2string(temp_var_index ++); // 自动return _emit(INTER_CODE_OP_ENUM::POP, "", "", temp_place); _emit(INTER_CODE_OP_ENUM::J, "", "", temp_place); // end int func_end = inter_code.size() - 1; func_table[func_name] = FuncInfo(name_tree -> first_son -> value, Info::VAR_INFO_MAP[type_tree -> first_son -> value], func_start, func_end); } /** * @brief 翻译block */ void InterCodeGenerator::_block(SyntaxTreeNode * cur, bool restore) { int _pre_var_index = var_index; map<string, VarInfo> pre_table = table; context_index ++; SyntaxTreeNode * cs = cur -> first_son; cur -> next_list = cs -> next_list; while (cs) { if (cs -> value == "Statement") _statement(cs); else if (cs -> value == "Assignment") _assignment(cs); else if (cs -> value == "Print") _print(cs); else if (cs -> value == "Control-If") _if(cs); else if (cs -> value == "Control-While") _while(cs); else if (cs -> value == "Block") { _block(cs); cur -> next_list = cs -> next_list; } else if (cs -> value == "FunctionCall") _functionCall(cs); else if (cs -> value == "VoidReturn") _voidReturn(cs); // TODO 其他 else cout << "Debug <<<" << cs -> value << endl; // 回填 _backpatch(cs -> next_list, inter_code.size()); cs = cs -> right; // 回填 if (cs) cur -> next_list = cs -> next_list; } if (restore) { var_index = _pre_var_index; table = pre_table; } } /** * @brief 翻译Print */ void InterCodeGenerator::_if(SyntaxTreeNode * cur) { SyntaxTreeNode * cs = cur -> first_son, * pre = nullptr; int m1_inst, m2_inst; while (cs) { if (cs -> value == "Control-Condition") { // 读取条件语句 _expression(cs -> first_son); pre = cs -> first_son; // 回填一下 m1_inst = inter_code.size(); // 读取紧随其后的执行语句 cs = cs -> right; _block(cs); // 只有if if (! cs -> right) { _backpatch(pre -> true_list, m1_inst); cur -> next_list.insert(cur -> next_list.end(), V(cs -> left -> first_son -> false_list)); cur -> next_list.insert(cur -> next_list.end(), V(cs -> next_list)); } else { cur -> next_list.emplace_back(inter_code.size()); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); cur -> next_list.insert(cur -> next_list.end(), V(cs -> next_list)); } } else { // 回填一下 m2_inst = inter_code.size(); _block(cs); _backpatch(pre -> true_list, m1_inst); _backpatch(pre -> false_list, m2_inst); cur -> next_list.insert(cur -> next_list.end(), V(cs -> next_list)); } cs = cs -> right; } } /** * @brief 翻译Print */ void InterCodeGenerator::_print(SyntaxTreeNode * cur) { SyntaxTreeNode * ps = cur -> first_son; string print_place; while (ps) { print_place = _expression(ps); _emit(INTER_CODE_OP_ENUM::PRINT, print_place, "", ""); ps = ps -> right; } _emit(INTER_CODE_OP_ENUM::PRINT, "", "", ""); } /** * @brief 翻译赋值语句 */ void InterCodeGenerator::_assignment(SyntaxTreeNode * cur) { SyntaxTreeNode * cs = cur -> first_son; string r_value_place = _expression(cs -> right); string store_place; if (cs -> value == "Expression-ArrayItem") store_place = _lookUpVar(cs); else store_place = _lookUpVar(cur -> first_son -> value, cur); _emit(INTER_CODE_OP_ENUM::MOV, r_value_place, "", store_place); } /** * @brief 翻译表达式 * @param cur 一个Expression-*节点执政 * @return place, string */ string InterCodeGenerator::_expression(SyntaxTreeNode * cur) { // 双目运算符 if (cur -> value == "Expression-DoubleOp" || cur -> value == "Expression-Bool-DoubleOp") { SyntaxTreeNode * a = cur -> first_son; SyntaxTreeNode * op = a -> right; SyntaxTreeNode * b = op -> right; string a_place, b_place; // 如果是数字运算的话 if (cur -> value == "Expression-DoubleOp") { a_place = _expression(a); b_place = _expression(b); string temp_var_place = "t" + int2string(temp_var_index ++); _emit(Quadruple::INTER_CODE_MAP[op -> first_son -> value], a_place, b_place, temp_var_place); return temp_var_place; } // bool运算要考虑回填 else { string a_place, b_place; if (op -> first_son -> value == "||") { a_place = _expression(a); int m_inst = inter_code.size(); b_place = _expression(b); _backpatch(a -> false_list, m_inst); // update true_list cur -> true_list.insert(cur -> true_list.end(), V(a -> true_list)); cur -> true_list.insert(cur -> true_list.end(), V(b -> true_list)); // update false_list cur -> false_list = b -> false_list; } else if (op -> first_son -> value == "&&") { a_place = _expression(a); int m_inst = inter_code.size(); b_place = _expression(b); _backpatch(a -> true_list, m_inst); // update true_list cur -> true_list = b -> true_list; // update false_list cur -> false_list.insert(cur -> false_list.end(), a -> false_list.begin(), a -> false_list.end()); cur -> false_list.insert(cur -> false_list.end(), b -> false_list.begin(), b -> false_list.end()); } else { a_place = _expression(a); b_place = _expression(b); cur -> true_list.emplace_back(inter_code.size()); _emit(Quadruple::INTER_CODE_MAP[op -> first_son -> value], a_place, b_place, ""); cur -> false_list.emplace_back(inter_code.size()); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); } return ""; } } // 单目运算符 else if (cur -> value == "Expression-UniOp") { // TODO } else if (cur -> value == "Expression-Bool-UniOp") { // TODO } // 常量 else if (cur -> value == "Expression-Constant"){ return cur -> first_son -> value; } // 字符串常量 else if (cur -> value == "Expression-String") { string temp = cur -> first_son -> value; // 转义 temp = regex_replace(temp, regex(","), string("\\,")); temp = regex_replace(temp, regex("\\\\"), string("\\\\")); return temp; } // 变量 else if (cur -> value == "Expression-Variable") { return _lookUpVar(cur -> first_son -> value, cur); } // 数组项 else if (cur -> value == "Expression-ArrayItem") { return _lookUpVar(cur); } cout << "debug >> " << cur -> value << endl; throw Error("How can you step into this place???", POS(cur)); } /** * @brief 翻译while语句 */ void InterCodeGenerator::_while(SyntaxTreeNode * cur) { int m_inst1 = inter_code.size(); SyntaxTreeNode * condition_tree = cur -> first_son -> first_son; _expression(condition_tree); int m_inst2 = inter_code.size(); SyntaxTreeNode * block_tree = cur -> first_son -> right; _block(block_tree); _backpatch(block_tree -> next_list, m_inst1); _backpatch(condition_tree -> true_list, m_inst2); cur -> next_list = condition_tree -> false_list; _emit(INTER_CODE_OP_ENUM::J, "", "", int2string(m_inst1)); } /** * @brief 翻译变量声明语句 */ void InterCodeGenerator::_statement(SyntaxTreeNode * cur) { SyntaxTreeNode * cs = cur -> first_son; while (cs) { string type = cs -> type; if (type == "double" || type == "float") { VarInfo info(VARIABLE_INFO_ENUM::DOUBLE, var_index ++); table[cs -> value] = info; } else if (type == "int") { VarInfo info(VARIABLE_INFO_ENUM::INT, var_index ++); table[cs -> value] = info; } else if (type.size() > 6 && type.substr(0, 6) == "array-") { VarInfo info(VARIABLE_INFO_ENUM::ARRAY, var_index ++); table[cs -> value] = info; string extra_info = cs -> extra_info; int extra_info_len = extra_info.size(); int cur_i = 0; if (cur_i < extra_info_len && extra_info.substr(cur_i, 5) == "size=") { cur_i += 5; int len = 0; while (cur_i + len < extra_info_len && extra_info[cur_i + len] != '&') len ++; var_index += string2int(extra_info.substr(cur_i, len)); cur_i += len; } if (cur_i < extra_info_len && extra_info.substr(cur_i, 3) == "&v=") { cur_i += 3; int len, arr_i = 0; while (cur_i < extra_info_len) { len = 0; while (cur_i + len < extra_info_len && extra_info[cur_i + len] != ',') len ++; _emit(INTER_CODE_OP_ENUM::MOV, extra_info.substr(cur_i, len), "", info.name + "[" + int2string(arr_i) + "]"); cur_i += len + 1; arr_i ++; } } } else { throw Error("type `" + type + "` are not supported yet", POS(cur)); } cs = cs -> right; } } /** * @brief 处理函数调用 */ void InterCodeGenerator::_functionCall(SyntaxTreeNode * cur) { // backup int _pre_var_index = var_index; map<string, VarInfo> pre_table = table; string func_name = cur -> first_son -> first_son -> value; if (func_table.find(func_name) == func_table.end()) throw Error("function `" + func_name + "` is not defined before use", POS(cur)); // TODO 返回地址 int temp_place = inter_code.size(); _emit(INTER_CODE_OP_ENUM::PUSH, "", "", ""); SyntaxTreeNode * param = cur -> first_son -> right; SyntaxTreeNode * ps = param -> first_son; while (ps -> right) ps = ps -> right; string param_place; while (ps) { param_place = _expression(ps -> first_son); _emit(INTER_CODE_OP_ENUM::PUSH, "", "", param_place); ps = ps -> left; } inter_code[temp_place].res = "pc+" + int2string(inter_code.size() - temp_place + 1); if (func_backpatch.find(func_name) == func_backpatch.end()) { vector<int> t; func_backpatch[func_name] = t; } func_backpatch[func_name].emplace_back(inter_code.size()); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); // restore var_index = _pre_var_index; table = pre_table; } /** * @brief 寻找标识符 * @param name 标识符 * @return code var */ string InterCodeGenerator::_lookUpVar(string name, SyntaxTreeNode * cur) { if (table.find(name) == table.end()) throw Error("variable `" + name + "` is not defined before use", POS(cur)); return table[name].name; } /** * @brief 寻找标识符 * @param name 标识符 * @return code var */ string InterCodeGenerator::_lookUpVar(SyntaxTreeNode * arr_pointer) { string base = arr_pointer -> first_son -> value; string index_place = _expression(arr_pointer -> first_son -> right -> first_son); return _lookUpVar(base, arr_pointer) + "[" + index_place + "]"; } /** * @brief 生成一个四元式 * @param op 操作符 * @param arg1 参数1 * @param arg2 参数2 * @param res 结果 */ void InterCodeGenerator::_emit(INTER_CODE_OP_ENUM op, string arg1, string arg2, string res) { inter_code.emplace_back(Quadruple(op, move(arg1), move(arg2), move(res))); } /** * @brief 保存到文件 * @param 路径 */ void InterCodeGenerator::saveToFile(string path) { ofstream out_file; out_file.open(path, ofstream::out | ofstream::trunc); for (auto ic: inter_code) out_file << Quadruple::INTER_CODE_OP[int(ic.op)] << "," << ic.arg1 << "," << ic.arg2 << "," << ic.res << endl; out_file.close(); } void InterCodeGenerator::_backpatch(vector<int> v, int dest_index) { for (auto i: v) inter_code[i].res = int2string(dest_index); } void InterCodeGenerator::_voidReturn(SyntaxTreeNode * cur) { SyntaxTreeNode * cf = cur; while (cf && cf -> value != "FunctionStatement") cf = cf -> father; string temp_place = "t" + int2string(temp_var_index ++); // 自动return _emit(INTER_CODE_OP_ENUM::POP, "", "", temp_place); _emit(INTER_CODE_OP_ENUM::J, "", "", temp_place); }
27.916528
118
0.54204
toy-compiler
60c3729869adc42ebc876a7485af606fca846d14
10,759
hxx
C++
inc/TimerThread.hxx
Clovel/TimerThread
95083010066deeedb3d9e19e332f10827d7b0852
[ "MIT" ]
1
2020-03-04T08:59:59.000Z
2020-03-04T08:59:59.000Z
inc/TimerThread.hxx
Clovel/TimerThread
95083010066deeedb3d9e19e332f10827d7b0852
[ "MIT" ]
2
2020-03-05T08:33:02.000Z
2020-03-05T08:49:17.000Z
inc/TimerThread.hxx
Clovel/TimerThread
95083010066deeedb3d9e19e332f10827d7b0852
[ "MIT" ]
null
null
null
/** * TimerThread class definition * * @file TimerThread.hxx */ #ifndef TIMERTHREAD_HXX #define TIMERTHREAD_HXX /* Includes -------------------------------------------- */ #include <functional> #include <chrono> #include <unordered_map> #include <set> #include <thread> #include <mutex> #include <condition_variable> #include <cstdint> /* TimerThread class definition ------------------------ */ class TimerThread { public: /* Defining the timer ID type */ using timer_id_t = std::uint64_t; /* Each Timer is assigned a unique ID of type timer_id_t */ static timer_id_t constexpr no_timer = timer_id_t(0); /* Valid IDs are guaranteed not to be this value */ /* Defining the handler function type */ using handler_type = std::function<void()>; // Function object we actually use // Function object that we boil down to handler_type with std::bind template<typename ... Args> using bound_handler_type = std::function<void(Args ...)>; /* Defining the microsecond type */ using time_us_t = std::int64_t; /* Values that are a large-range microsecond count */ /** @brief Constructor does not start worker until there is a Timer */ explicit TimerThread(); /** @brief Destructor is thread safe, even if a timer * callback is running. All callbacks are guaranteed * to have returned before this destructor returns */ ~TimerThread(); /** @brief Create timer using microseconds * The delay will be called msDelay microseconds from now * If msPeriod is nonzero, call the callback again every * msPeriod microseconds * All timer creation functions eventually call this one */ timer_id_t addTimer(time_us_t msDelay, time_us_t msPeriod, handler_type handler); /** @brief Create timer using std::chrono delay and period * Optionally binds additional arguments to the callback */ template<typename SRep, typename SPer, typename PRep, typename PPer, typename ... Args> timer_id_t addTimer(typename std::chrono::duration<SRep, SPer> const &delay, typename std::chrono::duration<PRep, PPer> const &period, bound_handler_type<Args ...> handler, Args && ... args); /** @brief Create timer using millisecond units delay and period * Optionally binds additional arguments to the callback */ template<typename ... Args> timer_id_t addTimer(time_us_t msDelay, time_us_t msPeriod, bound_handler_type<Args ...> handler, Args && ... args); /** @brief setInterval API like browser javascript * Call handler every `period` milliseconds, * starting `period` milliseconds from now * Optionally binds additional arguments to the callback */ timer_id_t setInterval(handler_type handler, time_us_t period); /** @brief setTimeout API like browser javascript * Call handler once `timeout` ms from now */ timer_id_t setTimeout(handler_type handler, time_us_t timeout); /** @brief setInterval API like browser javascript * Call handler every `period` microseconds, * starting `period` microseconds from now */ template<typename ... Args> timer_id_t setInterval(bound_handler_type<Args ...> handler, time_us_t period, Args && ... args); /** @brief setTimeout API like browser javascript * Call handler once `timeout` ms from now * binds extra arguments and passes them to the * timer callback */ template<typename ... Args> timer_id_t setTimeout(bound_handler_type<Args ...> handler, time_us_t timeout, Args && ... args); /** @brief Destroy the specified timer * * Synchronizes with the worker thread if the * callback for this timer is running, which * guarantees that the handler for that callback * is not running before clearTimer returns * * You are not required to clear any timers. You can * forget their timer_id_t if you do not need to cancel * them. * * The only time you need this is when you want to * stop a timer that has a repetition period, or * you want to cancel a timeout that has not fired * yet * * See clear() to wipe out all timers in one go */ bool clearTimer(timer_id_t id); /* @brief Destroy all timers, but preserve id uniqueness * This carefully makes sure every timer is not * executing its callback before destructing it */ void clear(); /* @brief Set the TimerThread's priority */ int setScheduling(const int &pPolicy, const int &pPriority); /* @brief Get the TimerThread's priority */ int scheduling(int * const pPolicy, int * const pPriority) noexcept; /* Peek at current state */ std::size_t size() const noexcept; bool empty() const noexcept; /** @brief Returns initialized singleton */ static TimerThread &global(); private: /* Type definitions */ using Lock = std::mutex; using ScopedLock = std::unique_lock<Lock>; using ConditionVar = std::condition_variable; using Clock = std::chrono::high_resolution_clock; using Timestamp = std::chrono::time_point<Clock>; using Duration = std::chrono::microseconds; /* changed milliseconds to microseconds */ /** @brief Timer structure definition */ struct Timer { explicit Timer(timer_id_t id = 0U); Timer(Timer &&r) noexcept; Timer &operator=(Timer &&r) noexcept; Timer(timer_id_t id, Timestamp next, Duration period, handler_type handler) noexcept; // Never called Timer(Timer const &r) = delete; Timer &operator=(Timer const &r) = delete; timer_id_t id; Timestamp next; Duration period; handler_type handler; // You must be holding the 'sync' lock to assign waitCond std::unique_ptr<ConditionVar> waitCond; bool running; }; // Comparison functor to sort the timer "queue" by Timer::next struct NextActiveComparator { bool operator()(Timer const &a, Timer const &b) const noexcept { return a.next < b.next; } }; // Queue is a set of references to Timer objects, sorted by next using QueueValue = std::reference_wrapper<Timer>; using Queue = std::multiset<QueueValue, NextActiveComparator>; using TimerMap = std::unordered_map<timer_id_t, Timer>; void timerThreadWorker(); bool destroy_impl(ScopedLock &lock, TimerMap::iterator i, bool notify); // Inexhaustible source of unique IDs timer_id_t nextId; // The Timer objects are physically stored in this map TimerMap active; // The ordering queue holds references to items in `active` Queue queue; // One worker thread for an unlimited number of timers is acceptable // Lazily started when first timer is started // TODO: Implement auto-stopping the timer thread when it is idle for // a configurable period. mutable Lock sync; ConditionVar wakeUp; std::thread worker; bool done; }; /* Template implementation fo class methods */ template<typename SRep, typename SPer, typename PRep, typename PPer, typename ... Args> TimerThread::timer_id_t TimerThread::addTimer(typename std::chrono::duration<SRep, SPer> const &delay, typename std::chrono::duration<PRep, PPer> const &period, bound_handler_type<Args ...> handler, Args && ... args) { time_us_t msDelay = std::chrono::duration_cast<std::chrono::microseconds>(delay).count(); time_us_t msPeriod = std::chrono::duration_cast<std::chrono::microseconds>(period).count(); return addTimer(msDelay, msPeriod, std::move(handler), std::forward<Args>(args) ...); } template<typename ... Args> TimerThread::timer_id_t TimerThread::addTimer(time_us_t msDelay, time_us_t msPeriod, bound_handler_type<Args ...> handler, Args && ... args) { return addTimer(msDelay, msPeriod, std::bind(std::move(handler), std::forward<Args>(args) ...)); } // Javascript-like setInterval template<typename ... Args> TimerThread::timer_id_t TimerThread::setInterval(bound_handler_type<Args ...> handler, time_us_t period, Args && ... args) { return setInterval(std::bind(std::move(handler), std::forward<Args>(args) ...), period); } // Javascript-like setTimeout template<typename ... Args> TimerThread::timer_id_t TimerThread::setTimeout(bound_handler_type<Args ...> handler, time_us_t timeout, Args && ... args) { return setTimeout(std::bind(std::move(handler), std::forward<Args>(args) ...), timeout); } #endif /* TIMERTHREAD_HXX */
38.701439
121
0.53992
Clovel
60cc3df86cf31033db5c0ff70ed6e6f94509b3c5
2,717
cpp
C++
core/inst_c4c.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
10
2017-07-04T03:05:42.000Z
2022-01-20T17:37:06.000Z
core/inst_c4c.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
2
2020-06-29T13:32:15.000Z
2021-12-22T23:04:43.000Z
core/inst_c4c.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
5
2021-08-28T02:21:56.000Z
2022-01-16T21:39:16.000Z
#include "inst.h" /**************************************************************************** * CLASS 4C ****************************************************************************/ #undef INST #define INST INST_CLASS_4C C33_OP(scan0_rd_rs) { c33word ua, ub; ua = Rs.w; for(ub = 0; ub < 8; ub++) { if(!(ua & (1 << 31))) break; ua <<= 1; } Rd.w = ub; PSR.z = ub == 0; PSR.c = ub == 8; PC.w += 2; CLK += 1; } C33_OP(scan1_rd_rs) { c33word ua, ub; ua = Rs.w; for(ub = 0; ub < 8; ub++) { if(ua & (1 << 31)) break; ua <<= 1; } Rd.w = ub; PSR.z = ub == 0; PSR.c = ub == 8; PC.w += 2; CLK += 1; } C33_OP(swap_rd_rs) { c33word ua; ua = Rs.w; Rd.w = ((ua & 0x000000ff) << 24) | ((ua & 0x0000ff00) << 8) | ((ua & 0x00ff0000) >> 8) | ((ua & 0xff000000) >> 24); PC.w += 2; CLK += 1; } C33_OP(mirror_rd_rs) { c33word ua; ua = Rs.w; Rd.w = ((ua & 0x01010101) << 7) | ((ua & 0x02020202) << 5) | ((ua & 0x04040404) << 3) | ((ua & 0x08080808) << 1) | ((ua & 0x10101010) >> 1) | ((ua & 0x20202020) >> 3) | ((ua & 0x40404040) >> 5) | ((ua & 0x80808080) >> 7); PC.w += 2; CLK += 1; } C33_OP(div0s_rs) { if(!Rs.i) core_trap(TRAP_ZERODIV, 0); AHR.w = (c33int)ALR.w >> 31; PSR.ds = ALR.w >> 31; PSR.n = Rs.w >> 31; PC.w += 2; CLK += 1; } C33_OP(div0u_rs) { if(!Rs.i) core_trap(TRAP_ZERODIV, 0); AHR.w = 0; PSR.ds = 0; PSR.n = 0; PC.w += 2; CLK += 1; } C33_OP(div1_rs) { c33int tmp; /* div0x以外では、ゼロ除算例外は発生しません。 */ AR <<= 1; if(!PSR.ds) { if(!PSR.n) { /* 正÷正 */ tmp = AHR.i - Rs.i; if(tmp <= AHR.i) { /* !C */ AHR.i = tmp; ALR.i |= 1; } } else { /* 正÷負 */ tmp = AHR.i + Rs.i; if(tmp < AHR.i) { /* C */ AHR.i = tmp; ALR.i |= 1; } } } else { if(!PSR.n) { /* 負÷正 */ tmp = AHR.i + Rs.i; if(tmp >= AHR.i) { /* !C */ AHR.i = tmp; ALR.i |= 1; } } else { /* 負÷負 */ tmp = AHR.i - Rs.i; if(tmp > AHR.i) { /* !C */ AHR.i = tmp; ALR.i |= 1; } } } PC.w += 2; CLK += 1; } C33_OP(div2s_rs) { c33word tmp; /* div0x以外では、ゼロ除算例外は発生しません。 */ if(PSR.ds) { if(!PSR.n) { tmp = AHR.i + Rs.i; } else { tmp = AHR.i - Rs.i; } if(!tmp) { AHR.i = tmp; ALR.i += 1; } } PC.w += 2; CLK += 1; } C33_OP(div3s) { /* div0x以外では、ゼロ除算例外は発生しません。 */ if(PSR.ds != PSR.n) { ALR.i = 0 - ALR.i; /* ALR = -ALR では警告になるので… */ } PC.w += 2; CLK += 1; }
14.686486
78
0.375782
autch
60cd2c65df7bc743837a1fbc20efeca4e6d56e69
41
hpp
C++
src/boost_fusion_include_at_c.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_include_at_c.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_include_at_c.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/include/at_c.hpp>
20.5
40
0.780488
miathedev
f59aada8dd2a16a3e0044628da6196866b8a6968
554
cpp
C++
src/noj_am/BOJ_18870.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
1
2020-06-01T12:19:31.000Z
2020-06-01T12:19:31.000Z
src/noj_am/BOJ_18870.cpp
ginami0129g/my-study-history
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
23
2020-11-08T07:14:02.000Z
2021-02-11T11:16:00.000Z
src/noj_am/BOJ_18870.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n, num, cnt; vector<pair<int, int> > arr; vector<int> ans; int main(void) { cin.tie(NULL); ios_base::sync_with_stdio(false); cin >> n; for (int i = 0; i < n; ++i) { cin >> num; arr.push_back({num, i}); } sort(arr.begin(), arr.end()); ans.assign(n, 0); ans[arr[0].second] = 0; for (int i = 1; i < arr.size(); ++i) { if (arr[i - 1].first == arr[i].first) cnt++; ans[arr[i].second] = i - cnt; } for (int i = 0; i < ans.size(); ++i) { cout << ans[i] << ' '; } }
20.518519
48
0.516245
ginami0129g
f5a0b653ea5123444f44a63d1c5db33502ead90a
1,528
hpp
C++
include/engge/Engine/Camera.hpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
127
2018-12-09T18:40:02.000Z
2022-03-06T00:10:07.000Z
include/engge/Engine/Camera.hpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
267
2019-02-26T22:16:48.000Z
2022-02-09T09:49:22.000Z
include/engge/Engine/Camera.hpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
17
2019-02-26T20:45:34.000Z
2021-06-17T15:06:26.000Z
#pragma once #include <memory> #include <optional> #include "Interpolations.hpp" #include <glm/vec2.hpp> #include <ngf/System/TimeSpan.h> #include <ngf/Graphics/Rect.h> namespace ng { class Engine; class Camera { public: Camera(); virtual ~Camera(); /// @brief Pans the camera to the target position in a specified time using a given interpolation. /// \param target Position where the camera needs to go. /// \param time Time needed for the camera to reach the target position. /// \param interpolation Interpolation method to use between the current position and the target position. void panTo(glm::vec2 target, ngf::TimeSpan time, InterpolationMethod interpolation); /// @brief Sets the position of the camera. /// @details The position is the center of the camera. /// \param at Position of the camera to set. void at(const glm::vec2 &at); /// @brief Gets the position of the camera. /// @details The position is the center of the camera. /// \return The current position of the camera. [[nodiscard]] glm::vec2 getAt() const; /// @brief Gets the rectangle of the camera. [[nodiscard]] ngf::frect getRect() const; void move(const glm::vec2 &offset); [[nodiscard]] bool isMoving() const; void setBounds(const ngf::irect &cameraBounds); [[nodiscard]] std::optional<ngf::irect> getBounds() const; void resetBounds(); void setEngine(Engine *pEngine); void update(const ngf::TimeSpan &elapsed); private: struct Impl; std::unique_ptr<Impl> m_pImpl; }; } // namespace ng
31.183673
108
0.712042
scemino
f5a2fe8e78bf109afa2d188699109d4d1c727f36
1,110
cpp
C++
leetcode/word-search.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
null
null
null
leetcode/word-search.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
null
null
null
leetcode/word-search.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
1
2020-10-07T15:02:09.000Z
2020-10-07T15:02:09.000Z
class Solution { public:     bool dfs(vector<vector<char>> &board, int row, int col, string &word, int wc) {    if(wc == (int) word.length()){        return true;   }    if(row < 0 or row >= board.size() or col < 0 or col >= board[row].size() or board[row][col] != word[wc])   {        return false;   }    {        char temp = board[row][col];        board[row][col] = ' ';        bool found = (dfs(board, row+1, col, word, wc+1) || dfs(board, row-1, col, word, wc+1)                      || dfs(board, row, col+1, word, wc+1) || dfs(board, row, col-1, word, wc+1));        board[row][col] = temp;        return found;    } } ​        bool exist(vector<vector<char>>& board, string word) {                int M = board.size(), N = board[0].size();        if(board.empty()){            return false;       }        for(int row = 0; row < M; row++){            for(int col = 0; col < N; col++){                if(board[row][col] == word[0] && dfs(board, row, col, word, 0)){                    return true;               }           }       }        return false;   } };
27.75
108
0.455856
sounishnath003
f5a934acb2b63f19c61facd572b01b01fbe5d2c8
3,532
hpp
C++
src/hash_map.hpp
kophy/TinySTL
366c2f585344a249846f4087904d509fa71e419e
[ "MIT" ]
5
2017-05-04T12:21:09.000Z
2019-03-28T09:29:50.000Z
src/hash_map.hpp
kophy/TinySTL
366c2f585344a249846f4087904d509fa71e419e
[ "MIT" ]
null
null
null
src/hash_map.hpp
kophy/TinySTL
366c2f585344a249846f4087904d509fa71e419e
[ "MIT" ]
null
null
null
#ifndef __TINYSTL_HASH_MAP__ #define __TINYSTL_HASH_MAP__ #include "hash_table.hpp" #include "allocator.hpp" #include "utils.hpp" namespace TinySTL { template <typename Key, typename Value> static bool isEqualKey(const Pair<const Key, Value> &a, const Pair<const Key, Value> &b) { return a.first == b.first; } template <typename Key, typename Value> static unsigned long hashByKey(const Pair<const Key, Value> &a) { return Hash<Key>(a.first); } template <typename Key, typename Value, class Alloc = Allocator<Pair<const Key, Value>>> class HashMap : public HashTable<Pair<const Key, Value>, Alloc> { public: class Iterator : public ForwardIterator { public: bool operator ==(const Iterator &I) { return (this->data == I.data && this->e == I.e); } bool operator !=(const Iterator &I) { return (this->data != I.data || this->e != I.e); } Pair<const Key, Value> &operator *() { return *(e.second); } Pair<const Key, Value> *operator ->() { return &(*(e.second)); } Iterator operator ++() { advance(); return *this; } Iterator operator ++(int dummy) { auto temp = *this; advance(); return temp; } Iterator(HashMap<Key, Value, Alloc> *_data, typename HashMap<Key, Value>::HashEntry _e) : data(_data), e(_e) {} private: HashMap<Key, Value, Alloc> *data; typename HashMap<Key, Value>::HashEntry e; void advance() { e = data->findNext(e); } friend class HashMap<Key, Value>; }; // iterator to the beginning Iterator begin() { return Iterator(this, base::findBegin()); } // iterator to the end Iterator end() { return Iterator(this, base::findEnd()); } // iterator to element with specific key Iterator find(const Key &k) { auto kv = MakePair<const Key, Value>(k, Value()); return Iterator(this, base::find(kv)); } // access element Value &operator [](const Key &k) { auto iter = find(k); if (iter == this->end()) { insert(k, Value()); iter = find(k); } return iter->second; } // insert wrapper void insert(const Key &k, const Value &v) { base::insert(MakePair<const Key, Value>(k, v)); } // erase wrapper void erase(const Key &k) { base::erase(MakePair<const Key, Value>(k, Value())); } // count wrapper unsigned int count(const Key &k) { return base::count(MakePair<const Key, Value>(k, Value())); } HashMap(bool (*_pred)(const Pair<const Key, Value> &a, const Pair<const Key, Value> &b) = isEqualKey<Key, Value>, unsigned long (*_hash)(const Pair<const Key, Value> &val) = hashByKey<Key, Value>, double _alpha = 1.0) : HashTable<Pair<const Key, Value>, Alloc>::HashTable(_pred, _hash, _alpha) {} private: typedef HashTable<Pair<const Key, Value>> base; friend class Iterator; }; }; #endif
36.791667
125
0.507928
kophy
f5aa0118dcc76527f14b2d6720f25e56214cddd7
5,115
cpp
C++
src/StdvNormalizer.cpp
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
71
2015-03-30T17:22:52.000Z
2022-01-01T14:19:23.000Z
src/StdvNormalizer.cpp
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
190
2015-01-27T16:18:58.000Z
2022-03-31T16:49:58.000Z
src/StdvNormalizer.cpp
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
45
2015-04-13T13:42:35.000Z
2021-12-17T08:26:21.000Z
/******************************************************************************* Copyright 2006-2012 Lukas Käll <[email protected]> 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. *******************************************************************************/ #include <iostream> #ifdef WIN32 #include <float.h> #define isfinite _finite #endif #include <math.h> #include <vector> #include <string> using namespace std; #include "Normalizer.h" #include "StdvNormalizer.h" #include "Globals.h" StdvNormalizer::StdvNormalizer() { } StdvNormalizer::~StdvNormalizer() { } void StdvNormalizer::unnormalizeweight(const std::vector<double>& in, std::vector<double>& out) { double sum = 0; unsigned int i = 0; for (; i < numFeatures; i++) { out[i] = in[i] / div[i]; sum += sub[i] * in[i] / div[i]; } out[i] = in[i] - sum; } void StdvNormalizer::normalizeweight(const std::vector<double>& in, std::vector<double>& out) { double sum = 0; size_t i = 0; for (; i < numFeatures; i++) { out[i] = in[i] * div[i]; sum += sub[i] * in[i]; } out[i] = in[i] + sum; } void StdvNormalizer::setSet(std::vector<double*>& featuresV, std::vector<double*>& rtFeaturesV, size_t nf, size_t nrf) { numFeatures = nf; numRetentionFeatures = nrf; sub.resize(nf + nrf, 0.0); div.resize(nf + nrf, 0.0); double n = 0.0; double* features; size_t ix; vector<double*>::iterator it = featuresV.begin(); for (; it != featuresV.end(); ++it) { features = *it; n++; for (ix = 0; ix < numFeatures; ++ix) { sub[ix] += features[ix]; } } for (it = rtFeaturesV.begin(); it != rtFeaturesV.end(); ++it) { features = *it; for (ix = numFeatures; ix < numFeatures + numRetentionFeatures; ++ix) { sub[ix] += features[ix - numFeatures]; } } if (VERB > 2) { cerr.precision(2); cerr << "Normalization factors" << endl << "Avg "; } for (ix = 0; ix < numFeatures + numRetentionFeatures; ++ix) { if (n > 0.0) { sub[ix] /= n; } if (VERB > 2) { cerr << "\t" << sub[ix]; } } for (it = featuresV.begin(); it != featuresV.end(); ++it) { features = *it; for (ix = 0; ix < numFeatures; ++ix) { if (!isfinite(features[ix])) { cerr << "Reached strange feature with val=" << features[ix] << " at col=" << ix << endl; } double d = features[ix] - sub[ix]; div[ix] += d * d; } } for (it = rtFeaturesV.begin(); it != rtFeaturesV.end(); ++it) { features = *it; for (ix = numFeatures; ix < numFeatures + numRetentionFeatures; ++ix) { if (!isfinite(features[ix-numFeatures])) { cerr << "Reached strange feature with val=" << features[ix - numFeatures] << " at col=" << ix << endl; } double d = features[ix - numFeatures] - sub[ix]; div[ix] += d * d; } } if (VERB > 2) { cerr << endl << "Stdv"; } for (ix = 0; ix < numFeatures + numRetentionFeatures; ++ix) { if (div[ix] <= 0 || n == 0) { div[ix] = 1.0; } else { div[ix] = sqrt(div[ix] / n); } if (VERB > 2) { cerr << "\t" << div[ix]; } } if (VERB > 2) { cerr << endl; } } void StdvNormalizer::updateSet(vector<double*> & featuresV, size_t offset, size_t numFeatures) { double n = 0.0; double* features; size_t ix; vector<double*>::iterator it = featuresV.begin(); for (; it != featuresV.end(); ++it) { features = *it; n++; for (ix = 0; ix < numFeatures; ++ix) { sub[offset + ix] += features[ix]; } } if (VERB > 2) { cerr.precision(2); cerr << "Normalization factors" << endl << "Avg "; } for (ix = 0; ix < numFeatures; ++ix) { if (n > 0.0) { sub[offset + ix] /= n; } if (VERB > 2) { cerr << "\t" << sub[offset + ix]; } } for (it = featuresV.begin(); it != featuresV.end(); ++it) { features = *it; for (ix = 0; ix < numFeatures; ++ix) { if (!isfinite(features[ix])) { cerr << "Reached strange feature with val=" << features[ix] << " at col=" << ix << endl; } double d = features[ix] - sub[offset + ix]; div[offset + ix] += d * d; } } if (VERB > 2) { cerr << endl << "Stdv"; } for (ix = 0; ix < numFeatures; ++ix) { if (div[offset + ix] <= 0 || n == 0) { div[offset + ix] = 1.0; } else { div[offset + ix] = sqrt(div[offset + ix] / n); } if (VERB > 2) { cerr << "\t" << div[offset + ix]; } } if (VERB > 2) { cerr << endl; } }
26.640625
81
0.527273
BR903
f5aca9b4c15da8e2a8ea61c8a7b9bdb82aff1c26
542
cpp
C++
ModelViewer/LoadingWrapper.cpp
peted70/glTF-DXViewer
1857e630fc14d19ced41c3ae9b895b017f937ab7
[ "MIT" ]
null
null
null
ModelViewer/LoadingWrapper.cpp
peted70/glTF-DXViewer
1857e630fc14d19ced41c3ae9b895b017f937ab7
[ "MIT" ]
null
null
null
ModelViewer/LoadingWrapper.cpp
peted70/glTF-DXViewer
1857e630fc14d19ced41c3ae9b895b017f937ab7
[ "MIT" ]
null
null
null
#include "pch.h" #include "LoadingWrapper.h" using namespace std; LoadingWrapper::LoadingWrapper(function<void()> ctor, function<void()> dtor) : _dtor(dtor) { Schedule(ctor); } future<void> LoadingWrapper::Schedule(function<void()> fn) { auto disp = Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher; co_await disp->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([fn]() { fn(); })); } LoadingWrapper::~LoadingWrapper() { Schedule(_dtor); }
23.565217
96
0.732472
peted70
f5ae25e03cd71f1b1c8137f547d5c598add9ba63
2,524
cpp
C++
src/collate_result.cpp
lsilvest/crpcut
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
[ "BSD-2-Clause" ]
1
2019-04-09T12:48:41.000Z
2019-04-09T12:48:41.000Z
src/collate_result.cpp
lsilvest/crpcut
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
[ "BSD-2-Clause" ]
2
2020-05-06T16:22:07.000Z
2020-05-07T04:02:41.000Z
src/collate_result.cpp
lsilvest/crpcut
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
[ "BSD-2-Clause" ]
1
2019-04-10T12:47:11.000Z
2019-04-10T12:47:11.000Z
/* * Copyright 2011 Bjorn Fahller <[email protected]> * All rights reserved * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <crpcut.hpp> namespace crpcut { collate_result ::collate_result(const char *refstr, std::string comp, const std::locale& l) : r(refstr), intl(comp), locale(l), side(right) { } collate_result ::collate_result(const collate_result& o) : r(o.r), intl(o.intl), locale(o.locale), side(o.side) { } collate_result ::operator const collate_result::comparator*() const { return operator()(); } const collate_result::comparator* collate_result ::operator()() const { return reinterpret_cast<const comparator*>(r ? 0 : this); } collate_result& collate_result ::set_lh() { side = left; return *this; } std::ostream &operator<<(std::ostream& os, const collate_result &obj) { static const char rs[] = "\"\n" " and right hand value = \""; os << "Failed in locale \"" << obj.locale.name() << "\"\n" " with left hand value = \""; if (obj.side == collate_result::right) { os << obj.intl << rs << obj.r << "\""; } else { os << obj.r << rs << obj.intl << "\""; } return os; } }
29.348837
78
0.669176
lsilvest