blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
b73fd8464ed165f2fd482f4f4cf51d34d5fa6a70
3615e7a2da642b5c039378d055f89365c6dbba5b
/src/client/StandartGameLogic.h
7c710031cdbc30f7c48035918a4983a4227dbbcd
[]
no_license
shimoncohen/Reversi
09ea75c2fb00adce65c3bcfa2e41e7a54994dc97
349fa5cf2fd0279238a9ae6cc1708863db31512b
refs/heads/master
2021-09-04T22:32:06.867138
2018-01-22T18:38:13
2018-01-22T18:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
845
h
StandartGameLogic.h
// 315383133 shimon cohen // 302228275 Nadav Spitzer #ifndef EX1_STANDARTGAMELOGIC_H #define EX1_STANDARTGAMELOGIC_H #include "GameLogic.h" /* * The class decides the game logic of a regular game of reversi. * The standart rules apply. */ class StandartGameLogic : public GameLogic { public: vector<Point> availableMoves(Board &board, type type1); bool validOption(Board &board, int x, int y, vector<Point> options); void changeTiles(type type, int x, int y, Board &board); char gameWon(Board &board); bool isGameWon(Board &board); bool gameFinalMove(Board &board, type pType, int x, int y); private: bool validMove(Board &board, int x, int y, int right, int down, char piece, int iteration); void flipTiles(char type, int x, int y, int right, int down, Board &board); }; #endif //EX1_STANDARTGAMELOGIC_H
c2483ce5aa7ff8c39e6eb591959708d17d4df743
16d5cd8328ff8b31334afac4030754e59151c376
/source/http/response_test.cpp
5759c5919285d3770477de65e554f2ff9d9aa825
[ "MIT" ]
permissive
TorstenRobitzki/Sioux
c443083677b10a8796dedc3adc3f950e273758e5
709eef5ebab5fed896b0b36f0c89f0499954657d
refs/heads/master
2023-03-31T18:44:55.391134
2023-03-16T06:51:56
2023-03-16T06:51:56
5,154,565
19
9
MIT
2023-03-16T06:51:57
2012-07-23T16:51:12
C++
UTF-8
C++
false
false
4,578
cpp
response_test.cpp
// Please note that the content of this file is confidential or protected by law. // Any unauthorised copying or unauthorised distribution of the information contained herein is prohibited. #include <boost/test/unit_test.hpp> #include "http/response.h" #include "http/test_request_texts.h" using namespace http; using namespace http::test; BOOST_AUTO_TEST_CASE(broken_response_line) { const response_header with_tabs("HTTP/1.1\t100\tI don't know\r\n\r\n"); BOOST_CHECK_EQUAL(http::message::syntax_error, with_tabs.state()); const response_header response_code_out_of_lower_range("HTTP/1.1 99 I don't know\r\n\r\n"); BOOST_CHECK_EQUAL(http::message::syntax_error, response_code_out_of_lower_range.state()); const response_header response_code_out_of_upper_range("HTTP/1.1 600 I don't know\r\n\r\n"); BOOST_CHECK_EQUAL(http::message::syntax_error, response_code_out_of_upper_range.state()); const response_header broken_version("HTTP\\1.1 100 I don't know\r\n\r\n"); BOOST_CHECK_EQUAL(http::message::syntax_error, broken_version.state()); const response_header missing_code("HTTP/4.4 I don't know\r\n\r\n"); BOOST_CHECK_EQUAL(http::message::syntax_error, missing_code.state()); const response_header missing_end_line("HTTP/1.1 100 ok\r\n"); BOOST_CHECK_EQUAL(http::message::parsing, missing_end_line.state()); } BOOST_AUTO_TEST_CASE(valid_response_line) { const response_header empty_phrase("HTTP/1.1 222\r\n\r\n"); BOOST_CHECK_EQUAL(message::ok, empty_phrase.state()); BOOST_CHECK_EQUAL(1001u, empty_phrase.milli_version()); BOOST_CHECK_EQUAL(static_cast<http_error_code>(222), empty_phrase.code()); const response_header smallest_code("HTTp/2.2 100 Ok\r\n\r\n"); BOOST_CHECK_EQUAL(message::ok, smallest_code.state()); BOOST_CHECK_EQUAL(2u, smallest_code.major_version()); BOOST_CHECK_EQUAL(2u, smallest_code.minor_version()); BOOST_CHECK_EQUAL(http_continue, smallest_code.code()); const response_header highest_code("http/12.21 599 WTF!\r\n\r\n"); BOOST_CHECK_EQUAL(message::ok, highest_code.state()); BOOST_CHECK_EQUAL(12u, highest_code.major_version()); BOOST_CHECK_EQUAL(21u, highest_code.minor_version()); BOOST_CHECK_EQUAL(static_cast<http_error_code>(599), highest_code.code()); BOOST_CHECK_EQUAL("WTF!", highest_code.phrase()); } /** * @test the propper working of the body_expected() function */ BOOST_AUTO_TEST_CASE(response_body_expected) { // response is 200 ok, combined with the request method, a body is expected or not { const http::response_header header(ok_response_header_apache); BOOST_CHECK_EQUAL(message::ok, header.state()); BOOST_CHECK( header.body_expected(http_options)); BOOST_CHECK( header.body_expected(http_get)); BOOST_CHECK(!header.body_expected(http_head)); BOOST_CHECK( header.body_expected(http_post)); BOOST_CHECK( header.body_expected(http_put)); BOOST_CHECK( header.body_expected(http_delete)); BOOST_CHECK( header.body_expected(http_trace)); BOOST_CHECK( header.body_expected(http_connect)); } // All 1xx (informational), 204 (no content), and 304 (not modified) responses MUST NOT include a message-body. { const http::response_header info( "HTTP/1.1 101 Switching Protocols\r\n\r\n"); BOOST_CHECK_EQUAL(message::ok, info.state()); BOOST_CHECK(!info.body_expected(http_get)); const http::response_header no_content( "HTTP/1.1 204 Nix da\r\n\r\n"); BOOST_CHECK_EQUAL(message::ok, no_content.state()); BOOST_CHECK(!no_content.body_expected(http_get)); const http::response_header not_modified(cached_response_apache); BOOST_CHECK_EQUAL(message::ok, not_modified.state()); BOOST_CHECK(!not_modified.body_expected(http_get)); } // All other responses do include a message-body, although it MAY be of zero length. { const http::response_header conflict( "HTTP/1.0 409 Conflict\r\n\r\n"); BOOST_CHECK_EQUAL(message::ok, conflict.state()); BOOST_CHECK(conflict.body_expected(http_delete)); const http::response_header gateway_timeout( "HTTP/1.0 502 GW TO\r\n\r\n"); BOOST_CHECK_EQUAL(message::ok, gateway_timeout.state()); BOOST_CHECK(gateway_timeout.body_expected(http_delete)); } }
8e07317a903056b62415e79e52699cac9cfecd67
3fc31a8dbd2aa09db040431db145f56d9ed61396
/solution/0002.h
0a3fac95db58b056f59371c539b7cd19098ad1b6
[]
no_license
BearRiding/leetcode
a606f154d2537a3a10b8fe1dc8a87ddcb0fb6ddc
4c5efac7a6e1447a721cbbe7fbdddbee19ed97f0
refs/heads/master
2021-07-09T16:06:51.314645
2020-10-28T06:37:03
2020-10-28T06:37:03
211,312,089
0
0
null
null
null
null
UTF-8
C++
false
false
2,690
h
0002.h
/* * 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 * */ #include <bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* addTwoNumbers(ListNode* &l1, ListNode* &l2) { ListNode *result, *p1 = l1, *p2 = l2, *p3; p3 = result = new ListNode(0); int adder_flag = 0; while(p1 && p2){ int num = p1->val + p2->val + adder_flag; adder_flag = 0; p1 = p1->next; p2= p2->next; if(num > 9) { adder_flag = 1; num = num % 10; } p3->next = new ListNode(num); p3 = p3->next; } ListNode *q = p1 ? p1 : p2; while(q){ int num = q->val + adder_flag; adder_flag = 0; q = q->next; if(num > 9) { adder_flag = 1; num = num % 10; } p3->next = new ListNode(num); p3 = p3->next; } if(adder_flag){ p3->next = new ListNode(1); } return result->next; } void listInit(ListNode* &l1){ l1 = new ListNode(rand()%10); ListNode *p; p = l1; int max = rand()%10 + 3; for(int i = 0; i < max; i++){ p->next = new ListNode(rand()%10); p = p->next; } } void printList(ListNode* &l1){ stack<int> nums; ListNode *p = l1; while(p){ nums.push(p->val); p = p->next; } while(!nums.empty()){ cout << nums.top(); nums.pop(); } cout << endl; } void printList_Node(ListNode* l1){ ListNode* p = l1; cout << p->val; p = p->next; while(p){ cout << " -> " << p->val; p = p->next; } cout << endl; } void run() { ListNode *l1, *l2; listInit(l1); printList_Node(l1); listInit(l2); printList_Node(l2); Solution solution; ListNode *result = solution.addTwoNumbers(l1, l2); printList_Node(result); return 0; } };
a35a3461d52d851cf4a1e300a0f2a2a4dac1a432
579ad2b15e00fb9fc690eb97b1444d531f2d5d3f
/webc/WebC/gui/peg/source/fonts/Verdana9bi.cpp
d337af504567d83c8517f3354e82bcc0996cb952
[]
no_license
peteratebs/webcwebbrowser
239af360deabed60eaa392206d2ca56f3b5215f9
08c446afc94d45d97efc948eb370cf8b7e0d3676
refs/heads/master
2021-01-10T05:33:26.367330
2015-10-12T22:30:38
2015-10-12T22:30:38
44,170,009
14
1
null
null
null
null
UTF-8
C++
false
false
14,384
cpp
Verdana9bi.cpp
/* This Font was created by PEG Font Capture, a utility program written by Swell Software Inc. for use with the PEG graphical interface library. The font captured was 9 Point Verdana */ #include <peg.hpp> #define WORD PEGUSHORT #define UCHAR PEGUBYTE ROMDATA WORD Verdana9bi_offset_table[130] = { 0x0000,0x0004,0x0009,0x0010,0x001a,0x0023,0x0032,0x003c,0x0040,0x0047,0x004e,0x0057,0x0061,0x0065,0x006c,0x0070, 0x0078,0x0081,0x008a,0x0093,0x009c,0x00a5,0x00ae,0x00b7,0x00c0,0x00c9,0x00d2,0x00d7,0x00dc,0x00e6,0x00f0,0x00fa, 0x0101,0x010d,0x0116,0x011f,0x0128,0x0132,0x013a,0x0142,0x014c,0x0156,0x015c,0x0162,0x016b,0x0173,0x017e,0x0188, 0x0192,0x019b,0x01a5,0x01ae,0x01b6,0x01be,0x01c8,0x01d1,0x01df,0x01e8,0x01f1,0x01f9,0x0200,0x0208,0x020f,0x0219, 0x0222,0x022b,0x0233,0x023b,0x0242,0x024a,0x0252,0x0257,0x025f,0x0268,0x026c,0x0271,0x0279,0x027d,0x028b,0x0294, 0x029c,0x02a4,0x02ac,0x02b2,0x02b9,0x02be,0x02c7,0x02d0,0x02dc,0x02e4,0x02ed,0x02f4,0x02fd,0x0304,0x030d,0x0317, 0x0323,0x032f,0x033b,0x0347,0x0353,0x035f,0x036b,0x0377,0x0383,0x038f,0x039b,0x03a7,0x03b3,0x03bf,0x03cb,0x03d7, 0x03e3,0x03ef,0x03fb,0x0407,0x0413,0x041f,0x042b,0x0437,0x0443,0x044f,0x045b,0x0467,0x0473,0x047f,0x048b,0x0497, 0x04a3,0x04a7, }; ROMDATA UCHAR Verdana9bi_data_table[2086] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x06, 0x30, 0x20, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x30, 0x1e, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x00, 0xc0, 0x06, 0x00, 0x60, 0x31, 0x98, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0xc3, 0x80, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x1b, 0x09, 0x0f, 0x87, 0x04, 0x0f, 0x03, 0x0c, 0x18, 0xa8, 0x00, 0x00, 0x00, 0x03, 0x3e, 0x06, 0x0f, 0x83, 0xc0, 0x71, 0xf8, 0x3c, 0xfe, 0x3e, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x03, 0xc0, 0x38, 0xf8, 0x1e, 0x3e, 0x0f, 0xcf, 0xc3, 0xc3, 0x0c, 0xf3, 0xcc, 0x66, 0x06, 0x0c, 0xc1, 0x0f, 0x0f, 0xc1, 0xe1, 0xf8, 0xf9, 0xfc, 0xc3, 0x61, 0xb0, 0xc6, 0xc3, 0x60, 0xbf, 0x8c, 0x30, 0x06, 0x18, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0xc0, 0x0c, 0x00, 0x60, 0x31, 0x98, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xc0, 0xc0, 0x00, 0x1b, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x00, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x03, 0xc0, 0x3c, 0x00, 0x03, 0x1b, 0x09, 0x1a, 0x4d, 0x88, 0x19, 0x83, 0x18, 0x18, 0x70, 0x10, 0x00, 0x00, 0x06, 0x63, 0x1e, 0x18, 0xc6, 0x60, 0xb1, 0x80, 0x60, 0x0c, 0x63, 0x31, 0x80, 0x00, 0x18, 0x00, 0x60, 0x19, 0x8c, 0x20, 0x78, 0xcc, 0x33, 0x33, 0x0c, 0x0c, 0x06, 0x63, 0x0c, 0x60, 0xcc, 0xc6, 0x06, 0x1c, 0xc1, 0x31, 0x8c, 0x66, 0x31, 0x8d, 0x8c, 0x30, 0xc3, 0x61, 0xb0, 0xc6, 0x66, 0x31, 0x81, 0x8c, 0x30, 0x06, 0x24, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0xc0, 0x0c, 0x00, 0x60, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xc0, 0xc0, 0x00, 0x36, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x00, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x00, 0x03, 0x00, 0x3f, 0x9a, 0x0d, 0x90, 0x19, 0x80, 0x30, 0x18, 0x70, 0x10, 0x00, 0x00, 0x0c, 0x63, 0x06, 0x00, 0xc0, 0x61, 0x33, 0x00, 0xc0, 0x0c, 0x63, 0x61, 0x8c, 0x60, 0x60, 0x00, 0x18, 0x01, 0x93, 0xd0, 0xd8, 0xcc, 0x63, 0x31, 0x8c, 0x0c, 0x0c, 0x63, 0x0c, 0x60, 0xcd, 0x86, 0x07, 0x2c, 0xe1, 0x31, 0x8c, 0x66, 0x31, 0x8d, 0x8c, 0x30, 0xc3, 0x63, 0x31, 0xcc, 0x6c, 0x33, 0x03, 0x18, 0x30, 0x0c, 0x24, 0x00, 0x00, 0x07, 0x8f, 0x87, 0x8f, 0x8f, 0x3e, 0x7c, 0xdc, 0x67, 0x33, 0x33, 0x73, 0x8d, 0xc3, 0xc7, 0xc3, 0xe6, 0xcf, 0x7d, 0x8c, 0xc6, 0x66, 0x66, 0x36, 0x33, 0xe0, 0xc0, 0xc1, 0x80, 0x00, 0x36, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x00, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x00, 0x06, 0x00, 0x3f, 0x9a, 0x0d, 0x97, 0x0f, 0x00, 0x30, 0x18, 0xa8, 0x10, 0x00, 0x00, 0x0c, 0xc3, 0x0c, 0x01, 0x80, 0xc2, 0x63, 0xe1, 0xf8, 0x18, 0x66, 0x61, 0x8c, 0x61, 0x81, 0xfc, 0x06, 0x03, 0x16, 0xd0, 0xd9, 0x8c, 0xc0, 0x61, 0x98, 0x18, 0x18, 0x06, 0x18, 0xc1, 0x9b, 0x0c, 0x0b, 0x59, 0x62, 0x61, 0x98, 0x6c, 0x33, 0x0d, 0xc0, 0x61, 0x86, 0x66, 0x32, 0xc8, 0x38, 0x1e, 0x06, 0x18, 0x18, 0x0c, 0x42, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0x59, 0x99, 0x98, 0xcc, 0xe6, 0x63, 0x36, 0x33, 0x9c, 0xce, 0x66, 0x66, 0x66, 0x67, 0xd8, 0x31, 0x8c, 0xc6, 0x66, 0xc6, 0x66, 0x30, 0x60, 0xc0, 0xc1, 0x81, 0x84, 0x36, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x00, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x07, 0x80, 0x78, 0x00, 0x06, 0x00, 0x12, 0x0f, 0x0d, 0xad, 0x9e, 0x60, 0x60, 0x18, 0x20, 0xfe, 0x03, 0xe0, 0x18, 0xc3, 0x0c, 0x03, 0x03, 0x84, 0x60, 0x31, 0x8c, 0x18, 0x3c, 0x63, 0x00, 0x06, 0x00, 0x00, 0x01, 0x86, 0x2c, 0xd1, 0x99, 0xf8, 0xc0, 0x61, 0x9f, 0x9f, 0x98, 0x07, 0xf8, 0xc1, 0x9e, 0x0c, 0x09, 0x99, 0x32, 0x61, 0x98, 0xcc, 0x33, 0x18, 0xf0, 0x61, 0x86, 0x66, 0x32, 0xd8, 0x38, 0x1c, 0x0c, 0x18, 0x18, 0x0c, 0x81, 0x00, 0x00, 0x03, 0xcc, 0xd8, 0x31, 0xb1, 0x99, 0x8c, 0xc6, 0x63, 0x3c, 0x33, 0x18, 0xcc, 0x6c, 0x66, 0x6c, 0x66, 0x18, 0x31, 0x8c, 0xcc, 0x6e, 0xc3, 0xc6, 0x60, 0xc7, 0x00, 0xc0, 0x82, 0x44, 0x6c, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x00, 0x06, 0x00, 0x7f, 0x05, 0x87, 0x4d, 0xb3, 0xc0, 0x60, 0x18, 0x00, 0x10, 0x00, 0x00, 0x18, 0xc3, 0x0c, 0x06, 0x00, 0xc8, 0x60, 0x33, 0x0c, 0x30, 0x66, 0x3f, 0x00, 0x06, 0x00, 0x00, 0x01, 0x8c, 0x2d, 0x91, 0x99, 0x8c, 0xc0, 0x61, 0x98, 0x18, 0x18, 0xe6, 0x18, 0xc1, 0x9b, 0x0c, 0x09, 0x99, 0x1a, 0x61, 0x9f, 0x8c, 0x33, 0xe0, 0x38, 0x61, 0x86, 0x6c, 0x34, 0xd0, 0x38, 0x0c, 0x18, 0x30, 0x18, 0x18, 0x00, 0x00, 0x00, 0x0c, 0xcc, 0xd8, 0x31, 0xbf, 0x99, 0x8c, 0xc6, 0x63, 0x38, 0x33, 0x18, 0xcc, 0x6c, 0x66, 0x6c, 0x66, 0x0c, 0x33, 0x18, 0xcc, 0x6e, 0x83, 0x86, 0x61, 0x80, 0x80, 0xc0, 0x72, 0x24, 0x6c, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x7f, 0x05, 0x80, 0x4d, 0xb1, 0x80, 0x60, 0x30, 0x00, 0x10, 0x00, 0x00, 0x30, 0xc6, 0x18, 0x0c, 0x00, 0xcf, 0xf0, 0x33, 0x0c, 0x30, 0xc6, 0x06, 0x00, 0x01, 0x81, 0xfc, 0x06, 0x00, 0x2d, 0xa3, 0xfb, 0x0c, 0xc6, 0xc3, 0x30, 0x30, 0x18, 0x6c, 0x31, 0x83, 0x31, 0x98, 0x11, 0x32, 0x1c, 0x63, 0x30, 0x0c, 0x66, 0x33, 0x18, 0xc3, 0x0c, 0x68, 0x34, 0xe0, 0x6c, 0x18, 0x30, 0x30, 0x18, 0x18, 0x00, 0x00, 0x00, 0x19, 0x98, 0xd8, 0x33, 0x30, 0x31, 0x99, 0x8c, 0xc6, 0x6c, 0x66, 0x31, 0x98, 0xcc, 0x6c, 0x6c, 0xcc, 0x06, 0x63, 0x18, 0xd8, 0x77, 0x07, 0x86, 0xc3, 0x00, 0xc0, 0xc1, 0x82, 0x18, 0x6c, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x0f, 0x00, 0xf0, 0x00, 0x0c, 0x00, 0x24, 0x25, 0x80, 0x8d, 0xb1, 0xc0, 0x60, 0x30, 0x00, 0x10, 0x60, 0x0c, 0x30, 0xc6, 0x18, 0x18, 0x18, 0xc0, 0xc6, 0x63, 0x18, 0x60, 0xc6, 0x0c, 0x18, 0xc0, 0x60, 0x00, 0x18, 0x18, 0x27, 0xe6, 0x1b, 0x18, 0xc6, 0xc6, 0x30, 0x30, 0x18, 0xcc, 0x31, 0x83, 0x31, 0x98, 0x10, 0x32, 0x0c, 0x63, 0x30, 0x0c, 0x66, 0x1b, 0x18, 0xc3, 0x0c, 0x78, 0x38, 0xe0, 0xcc, 0x18, 0x60, 0x30, 0x0c, 0x18, 0x00, 0x00, 0x00, 0x19, 0x99, 0x98, 0xb3, 0x31, 0x31, 0x99, 0x8c, 0xc6, 0x66, 0x66, 0x31, 0x98, 0xcc, 0xcc, 0xcc, 0xcc, 0x06, 0x63, 0x38, 0x70, 0x77, 0x0c, 0xc3, 0x86, 0x00, 0xc0, 0xc1, 0x80, 0x00, 0xf8, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x00, 0x00, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x1e, 0x01, 0xe0, 0x00, 0x0c, 0x00, 0x24, 0x1f, 0x01, 0x07, 0x1e, 0x60, 0x60, 0x60, 0x00, 0x00, 0x60, 0x0c, 0x60, 0x7c, 0x7f, 0x3f, 0x8f, 0x80, 0xc3, 0xc1, 0xf0, 0x60, 0x7c, 0x78, 0x18, 0xc0, 0x18, 0x00, 0x60, 0x18, 0x10, 0x06, 0x1b, 0xf0, 0x7c, 0xfc, 0x3f, 0x30, 0x0f, 0x8c, 0x33, 0xce, 0x30, 0xdf, 0xd0, 0x32, 0x0c, 0x3c, 0x30, 0x07, 0x86, 0x0d, 0xf0, 0xc1, 0xf8, 0x70, 0x30, 0xc1, 0x86, 0x18, 0x7f, 0x60, 0x0c, 0x30, 0x00, 0x00, 0x00, 0x0f, 0x9f, 0x0f, 0x1f, 0x1e, 0x30, 0xf9, 0x8c, 0xc6, 0x63, 0x66, 0x31, 0x98, 0xc7, 0x8f, 0x87, 0xcc, 0x3c, 0x39, 0xd8, 0x70, 0x66, 0x08, 0xc3, 0x87, 0xc1, 0x80, 0xc3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x60, 0xc0, 0x00, 0x00, 0x60, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x0c, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x80, 0xc3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x31, 0x80, 0x00, 0x00, 0x40, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0c, 0xf0, 0x00, 0x7f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xe0, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0xe0, 0xce, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; PegFont Verdana9bi = {1, 14, 0, 14, 149, 32, 160, (WORD *) Verdana9bi_offset_table, NULL, (UCHAR *) Verdana9bi_data_table};
b7ec9d50226cf685187c766638edaac1e89231f0
d0fd87e6225953624cbf13af62f36bd604705349
/RadioList/main.cpp
5ecc313e8a1126b2053d6a7feb947d4201095cb1
[]
no_license
oranmoshe/methods
7037d97b02e68dab985cec42fb8dd6edbcd418cc
3716ad5b4f337e8376e2b21067d312050cff9d3c
refs/heads/master
2021-01-10T06:03:40.880182
2016-03-30T21:43:03
2016-03-30T21:43:03
55,097,411
0
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
main.cpp
#include <iostream> #include <fstream> #include "RadioList.h" using namespace std; int main(int argc, char *argv[]) { RadioList r; r.display(); return 0; }
8a9adf31c3897ec88a472d9e534abd23a1e806ab
1a20961af3b03b46c109b09812143a7ef95c6caa
/Book/Boost C++ Application Development Cookbook/Chapter10/extern_template/source.cpp
293946659bebac2e2d749e02bdf58f57050839e8
[ "BSL-1.0" ]
permissive
JetAr/ZNginx
eff4ae2457b7b28115787d6af7a3098c121e8368
698b40085585d4190cf983f61b803ad23468cdef
refs/heads/master
2021-07-16T13:29:57.438175
2017-10-23T02:05:43
2017-10-23T02:05:43
26,522,265
3
1
null
null
null
null
UTF-8
C++
false
false
200
cpp
source.cpp
// Header with 'extern template' #include "header.hpp" #ifndef BOOST_NO_CXX11_EXTERN_TEMPLATE template class boost::variant< boost::blank, int, std::string, double >; #endif
bad8604984ee9b40742180e385438b82171ef52f
f83f4b7fd0ddc90e8b32b6471df56b5c8cc5757a
/MeshTools/FECreateShells.cpp
46d3456d3e093a83d469d0c1c662f4eb08f48cf0
[ "MIT" ]
permissive
febiosoftware/FEBioStudio
e2e9c018247fd09dd779ea6cab811f45b5a031bd
d11e97ab3af4981196c7187d18915e3656c47e2d
refs/heads/develop
2023-09-01T03:39:19.777596
2023-09-01T01:15:28
2023-09-01T01:15:28
271,643,351
49
23
MIT
2023-06-15T18:47:52
2020-06-11T20:44:57
C++
UTF-8
C++
false
false
4,223
cpp
FECreateShells.cpp
/*This file is part of the FEBio Studio source code and is licensed under the MIT license listed below. See Copyright-FEBio-Studio.txt for details. Copyright (c) 2021 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "stdafx.h" #include "FECreateShells.h" #include <GeomLib/GMeshObject.h> using namespace std; FECreateShells::FECreateShells() : FEModifier("Create Shells") { AddDoubleParam(0, "h", "h"); } FSMesh* FECreateShells::Apply(FSGroup* pg) { if (pg->Type() != FE_SURFACE) { FEModifier::SetError("Invalid selection"); return 0; } if (pg->size() == 0) { FEModifier::SetError("Empty selection"); return 0; } vector<int> faceList; for (FEItemListBuilder::Iterator it = pg->begin(); it != pg->end(); ++it) { faceList.push_back(*it); } FSMesh* pm = pg->GetMesh(); FSMesh* pnm = new FSMesh(*pm); CreateShells(pnm, faceList); return pnm; } FSMesh* FECreateShells::Apply(FSMesh* pm) { vector<int> faceList; for (int i=0; i<pm->Faces(); ++i) { if (pm->Face(i).IsSelected()) faceList.push_back(i); } FSMesh* pnm = new FSMesh(*pm); CreateShells(pnm, faceList); return pnm; } void FECreateShells::CreateShells(FSMesh* pm, vector<int>& faceList){ //get the user value double thick = GetFloatValue(0); //we count the nbr of selected faces and that they are tri or quad int faces = 0; for (int i=0; i < (int)faceList.size(); ++i) { FSFace& face = pm->Face(faceList[i]); int n = face.Nodes(); // verification if ((n != 4) && (n != 3) && (n != 9) && (n != 8) && (n != 6)) return; for (int j = 0; j<n; ++j) pm->Node(face.n[j]).m_ntag = 1; ++faces; } //error message when no face is selected if (faces==0){ FEModifier::SetError("Empty Selection"); return ; } // get the largest element group number int nid = 0; for (int i = 0; i<pm->Elements(); ++i) { FSElement& el = pm->Element(i); if (el.m_gid > nid) nid = el.m_gid; } nid++; // create the new shell elements int nbrelem = pm->Elements(); pm->Create(0, nbrelem + faces); int n=nbrelem; for (int i=0; i <(int)faceList.size(); ++i){ FSElement& pe=pm->Element(n); FSFace& face = pm->Face(faceList[i]); int nf = face.Nodes(); switch (nf) { case 3: pe.SetType(FE_TRI3 ); break; case 4: pe.SetType(FE_QUAD4); break; case 6: pe.SetType(FE_TRI6 ); break; case 7: pe.SetType(FE_TRI7 ); break; case 8: pe.SetType(FE_QUAD8); break; case 9: pe.SetType(FE_QUAD9); break; default: assert(false); FEModifier::SetError("Failure"); return ; } for (int j=0; j<nf; ++j) pe.m_node[j] = face.n[j]; pe.m_gid = nid; double* h = pe.m_h; for (int j=0; j<pe.Nodes(); ++j) h[j] = thick; n++; } pm->RebuildMesh(); }
0e0dc7e3eaf9fe7b8bd8a37537548e7bda3f7379
95a43c10c75b16595c30bdf6db4a1c2af2e4765d
/codecrawler/_code/hdu2141/16209916.cpp
28d1108cbb90606216a10923a892c3cb6d567e47
[]
no_license
kunhuicho/crawl-tools
945e8c40261dfa51fb13088163f0a7bece85fc9d
8eb8c4192d39919c64b84e0a817c65da0effad2d
refs/heads/master
2021-01-21T01:05:54.638395
2016-08-28T17:01:37
2016-08-28T17:01:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,570
cpp
16209916.cpp
#include <iostream> #include <algorithm> using namespace std; const int N = 505; __int64 ab[N * N]; int num; int search(__int64 x) { int f = 0, l = num - 1; int mid; while(f <= l) { mid = (f + l) / 2; if(ab[mid] == x) return 1; else if(ab[mid] < x) f = mid + 1; else l = mid - 1; } return 0; } int main() { int n, m, l, flag = 0, s; __int64 a[N], b[N], c[N], x; while(cin >> n >> m >> l) { flag++; num = 0; for(int i = 0; i < n; i++) scanf("%I64d", &a[i]); for(int i = 0; i < m; i++) scanf("%I64d", &b[i]); for(int i = 0; i < l; i++) scanf("%I64d", &c[i]); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) ab[num++] = a[i] + b[j]; sort(ab, ab+num); sort(c, c+l); scanf("%d", &s); printf("Case %d:\n", flag); while(s--) { scanf("%I64d", &x); if(x < ab[0] + c[0] || x > ab[num-1] + c[l-1]) printf("NO\n"); else { __int64 p; int j; for(j = 0; j < l; j++) { p = x - c[j]; if(search(p)) { printf("YES\n"); break; } } if(j == l) printf("NO\n"); } } } return 0; }
cf9dbab0b9a4f47be8253d55825f9bbc69f904f3
58a02a83cf4e5a9db396eb243576eaab4735e4c5
/src/sksignal.hpp
f39463a595a2390b7e36dcc3216fa7dd699e2aa1
[]
no_license
dolmenes/skel
c050717c69d2181f58ce9fa82e63f51336f392ab
b723469bb5644016c6a69990c2712abd4c75a23b
refs/heads/master
2021-05-14T02:23:56.551491
2018-01-08T05:07:20
2018-01-08T05:07:20
116,593,832
0
0
null
null
null
null
UTF-8
C++
false
false
115
hpp
sksignal.hpp
#ifndef SK_SIGNAL_HPP #define SK_SIGNAL_HPP namespace sk { template< typename... ARGS > signal { } } #endif
f6d0ec2bc6808fdfe2040eba02be8f8334bc4a44
a4016e3a099af344cbb07eff1a9268b621305a10
/hackerrank/cipher.cpp
ff66c1ab236f2459fefe86a3fe7cccb61ebf8bb1
[ "MIT" ]
permissive
btjanaka/algorithm-problems
4d92ae091676a90f5a8cb5a0b6b8c65e34946aee
e3df47c18451802b8521ebe61ca71ee348e5ced7
refs/heads/master
2021-06-17T22:10:01.324863
2021-02-09T11:29:35
2021-02-09T11:29:35
169,714,578
4
1
null
null
null
null
UTF-8
C++
false
false
1,025
cpp
cipher.cpp
// Author: btjanaka (Bryon Tjanaka) // Problem: (HackerRank) cipher // Title: Cipher // Link: https://www.hackerrank.com/challenges/cipher/problem // Idea: Keep a count of how many bits we expect to see at each position. If the // count is odd, we expect to see "1", and if the count is even, we expect to // see "0". Sometimes, this won't match up though - when it doesn't, we know a 1 // was added into the number. // Difficulty: // Tags: #include <bits/stdc++.h> using namespace std; int main() { int n, k; scanf("%d %d", &n, &k); vector<int> encoded(n + k - 1); for (int i = 0; i < n + k - 1; ++i) scanf("%1d", &encoded[i]); // Keep a running count of number of "on" bits in the last k positions int count = 0; vector<int> res(n, 0); for (int i = 0; i < n; ++i) { if (i >= k && res[i - k] == 1) --count; int expected = count % 2; if (expected != encoded[i]) { ++count; res[i] = 1; } } for (int i = 0; i < n; ++i) printf("%1d", res[i]); printf("\n"); return 0; }
6e0100f11df870e8dca08ee9c26e09ef1a74bfac
e6b0006949ed9d21efce8c4fd18fd6e371cd4bf9
/util/unittest/testConfig.cpp
c37184cbf8f9a1cf598995f07a91fbf4909912e9
[]
no_license
liweiliv/DBStream
ced5a25e934ab64e0986a8a4230767e12f04bdab
584f20f938530bb52bf38faa832992bfb59e7dbb
refs/heads/master
2021-07-21T02:58:20.442685
2021-06-07T12:57:34
2021-06-07T13:04:33
182,390,627
1
2
null
null
null
null
UTF-8
C++
false
false
657
cpp
testConfig.cpp
#include "../config.h" int main() { config conf(nullptr); conf.set("a","test1","123456"); conf.set("A","test1","1234567"); conf.set("a","test12","12345678"); conf.set("a","Test1","23456"); conf.set("a","word","drow"); assert(strcmp(conf.get("a","test1").c_str(),"123456")==0); assert(strcmp(conf.get("A","test1").c_str(),"1234567")==0); assert(strcmp(conf.get("a","test12").c_str(),"12345678")==0); assert(strcmp(conf.get("a","Test1").c_str(),"23456")==0); assert(strcmp(conf.get("a","word").c_str(),"drow")==0); assert(conf.getLong("A","test1",0,0,65535)==65535); assert(conf.getLong("A","test1",0,0,6553500)==1234567); conf.save("1.cnf"); }
ff4472df6bac238f63a5104a4fa994747be83062
14c83e6156c3565755abf29fa5e2e3a7826dd49c
/B3/phonebook_interface.hpp
5213dec8ee913bc12de06a4766e8367abfaa1302
[]
no_license
aosandy/labworks-cpp
ac164b21a5148ae478403ce7d3faa5b08ee0f759
374d038fdb6240e9e39c9e2b04af6cc56e66c365
refs/heads/main
2023-08-04T22:57:40.499687
2021-09-28T08:24:22
2021-09-28T08:24:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,244
hpp
phonebook_interface.hpp
#ifndef B3_PHONEBOOK_INTERFACE_HPP #define B3_PHONEBOOK_INTERFACE_HPP #include <unordered_map> #include <string> #include "phonebook.hpp" class PhonebookInterface { public: enum Place { BEFORE, AFTER }; enum StepsKeywords { FIRST, LAST }; enum StepsValues { NUMERIC, KEYWORD, INVALID }; enum ErrorMessage { EMPTY, INVALID_STEP, INVALID_COMMAND, INVALID_BOOKMARK }; struct steps_t { union { StepsKeywords keyword; int steps; }; StepsValues storedType; }; PhonebookInterface(); void add(const Phonebook::record_t&, std::ostream&); void store(const std::string&, const std::string&, std::ostream&); void insert(Place, const std::string&, const Phonebook::record_t&, std::ostream&); void deleteRecord(const std::string&, std::ostream&); void show(const std::string&, std::ostream&) const; void move(const std::string&, steps_t, std::ostream&); static void displayErrorMessage(PhonebookInterface::ErrorMessage, std::ostream&); private: Phonebook phonebook_; std::unordered_map<std::string, Phonebook::iterator> bookmarks_; void moveMarks(); }; #endif
9245b73d484621a5b1c4b77d5173e3e1094f3c17
20c1580b3eed4f4bad3a9be8b177308e5a64fc47
/op2/src/mpi/op_mpi_cuda_decl.cpp
b386f529bbecda41753bbf2494fee13bb4d7f17e
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
OP-DSL/OP2-Common
5c341952a680a9c4c8ecf940c6bab91af9c57103
a728da9af179ca745ab022bcd9b8915e38a7f512
refs/heads/master
2023-08-16T17:10:44.844025
2023-06-23T15:48:34
2023-06-23T15:48:34
1,843,043
65
33
NOASSERTION
2023-06-23T15:48:35
2011-06-03T15:36:25
C++
UTF-8
C++
false
false
28,006
cpp
op_mpi_cuda_decl.cpp
/* * Open source copyright declaration based on BSD open source template: * http://www.opensource.org/licenses/bsd-license.php * * This file is part of the OP2 distribution. * * Copyright (c) 2011, Mike Giles and others. Please see the AUTHORS file in * the main source directory for a full list of copyright holders. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * The name of Mike Giles may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Mike Giles ''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 Mike Giles 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 file implements the OP2 user-level functions for the CUDA backend // #include <cuda.h> #include <cuda_runtime.h> #include <cuda_runtime_api.h> #include <mpi.h> #include <op_cuda_rt_support.h> #include <op_lib_core.h> #include <op_rt_support.h> #include <op_lib_c.h> #include <op_lib_mpi.h> #include <op_util.h> // // MPI Communicator for halo creation and exchange // MPI_Comm OP_MPI_WORLD; MPI_Comm OP_MPI_GLOBAL; // // CUDA-specific OP2 functions // void op_init(int argc, char **argv, int diags) { op_init_soa(argc, argv, diags, 0); } void op_init_soa(int argc, char **argv, int diags, int soa) { int flag = 0; OP_auto_soa = soa; MPI_Initialized(&flag); if (!flag) { MPI_Init(&argc, &argv); } OP_MPI_WORLD = MPI_COMM_WORLD; OP_MPI_GLOBAL = MPI_COMM_WORLD; op_init_core(argc, argv, diags); #if CUDART_VERSION < 3020 #error : "must be compiled using CUDA 3.2 or later" #endif #ifdef CUDA_NO_SM_13_DOUBLE_INTRINSICS #warning : " *** no support for double precision arithmetic *** " #endif cutilDeviceInit(argc, argv); // // The following call is only made in the C version of OP2, // as it causes memory trashing when called from Fortran. // \warning add -DSET_CUDA_CACHE_CONFIG to compiling line // for this file when implementing C OP2. // if (OP_hybrid_gpu) { #ifdef SET_CUDA_CACHE_CONFIG cutilSafeCall(cudaDeviceSetCacheConfig(cudaFuncCachePreferShared)); #endif cutilSafeCall(cudaDeviceSetSharedMemConfig(cudaSharedMemBankSizeEightByte)); printf("\n 16/48 L1/shared \n"); } } void op_mpi_init(int argc, char **argv, int diags, MPI_Fint global, MPI_Fint local) { op_mpi_init_soa(argc, argv, diags, global, local, 0); } void op_mpi_init_soa(int argc, char **argv, int diags, MPI_Fint global, MPI_Fint local, int soa) { OP_auto_soa = soa; int flag = 0; MPI_Initialized(&flag); if (!flag) { printf("Error: MPI has to be initialized when calling op_mpi_init with " "communicators\n"); exit(-1); } OP_MPI_WORLD = MPI_Comm_f2c(local); OP_MPI_GLOBAL = MPI_Comm_f2c(global); op_init_core(argc, argv, diags); #if CUDART_VERSION < 3020 #error : "must be compiled using CUDA 3.2 or later" #endif #ifdef CUDA_NO_SM_13_DOUBLE_INTRINSICS #warning : " *** no support for double precision arithmetic *** " #endif cutilDeviceInit(argc, argv); // // The following call is only made in the C version of OP2, // as it causes memory trashing when called from Fortran. // \warning add -DSET_CUDA_CACHE_CONFIG to compiling line // for this file when implementing C OP2. // #ifdef SET_CUDA_CACHE_CONFIG cutilSafeCall(cudaDeviceSetCacheConfig(cudaFuncCachePreferShared)); #endif //cutilSafeCall(cudaDeviceSetCacheConfig(cudaFuncCachePreferShared)); cutilSafeCall(cudaDeviceSetSharedMemConfig(cudaSharedMemBankSizeEightByte)); printf("\n 16/48 L1/shared \n"); } op_dat op_decl_dat_char(op_set set, int dim, char const *type, int size, char *data, char const *name) { if (set == NULL) return NULL; /*char *d = (char *)malloc((size_t)set->size * (size_t)dim * (size_t)size); if (d == NULL && set->size>0) { printf(" op_decl_dat_char error -- error allocating memory to dat\n"); exit(-1); } memcpy(d, data, set->size * dim * size * sizeof(char)); op_dat out_dat = op_decl_dat_core(set, dim, type, size, d, name);*/ op_dat out_dat = op_decl_dat_core(set, dim, type, size, data, name); op_dat_entry *item; op_dat_entry *tmp_item; for (item = TAILQ_FIRST(&OP_dat_list); item != NULL; item = tmp_item) { tmp_item = TAILQ_NEXT(item, entries); if (item->dat == out_dat) { item->orig_ptr = data; break; } } out_dat->user_managed = 0; return out_dat; } op_dat op_decl_dat_temp_char(op_set set, int dim, char const *type, int size, char const *name) { char *data = NULL; op_dat dat = op_decl_dat_temp_core(set, dim, type, size, data, name); // create empty data block to assign to this temporary dat (including the // halos) int set_size = set->size + OP_import_exec_list[set->index]->size + OP_import_nonexec_list[set->index]->size; // initialize data bits to 0 for (size_t i = 0; i < set_size * dim * size; i++) dat->data[i] = 0; dat->user_managed = 0; // transpose if (strstr(dat->type, ":soa") != NULL || (OP_auto_soa && dat->dim > 1)) { cutilSafeCall( cudaMalloc((void **)&(dat->buffer_d_r), (size_t)dat->size * (OP_import_exec_list[set->index]->size + OP_import_nonexec_list[set->index]->size))); } op_cpHostToDevice((void **)&(dat->data_d), (void **)&(dat->data), (size_t)dat->size * set_size); // need to allocate mpi_buffers for this new temp_dat op_mpi_buffer mpi_buf = (op_mpi_buffer)xmalloc(sizeof(op_mpi_buffer_core)); halo_list exec_e_list = OP_export_exec_list[set->index]; halo_list nonexec_e_list = OP_export_nonexec_list[set->index]; mpi_buf->buf_exec = (char *)xmalloc((exec_e_list->size) * (size_t)dat->size); mpi_buf->buf_nonexec = (char *)xmalloc((nonexec_e_list->size) * (size_t)dat->size); halo_list exec_i_list = OP_import_exec_list[set->index]; halo_list nonexec_i_list = OP_import_nonexec_list[set->index]; mpi_buf->s_req = (MPI_Request *)xmalloc( sizeof(MPI_Request) * (exec_e_list->ranks_size + nonexec_e_list->ranks_size)); mpi_buf->r_req = (MPI_Request *)xmalloc( sizeof(MPI_Request) * (exec_i_list->ranks_size + nonexec_i_list->ranks_size)); mpi_buf->s_num_req = 0; mpi_buf->r_num_req = 0; dat->mpi_buffer = mpi_buf; // need to allocate device buffers for mpi comms for this new temp_dat cutilSafeCall( cudaMalloc((void **)&(dat->buffer_d), (size_t)dat->size * (OP_export_exec_list[set->index]->size + OP_export_nonexec_list[set->index]->size))); return dat; } int op_free_dat_temp_char(op_dat dat) { // need to free mpi_buffers use in this op_dat free(((op_mpi_buffer)(dat->mpi_buffer))->buf_exec); free(((op_mpi_buffer)(dat->mpi_buffer))->buf_nonexec); free(((op_mpi_buffer)(dat->mpi_buffer))->s_req); free(((op_mpi_buffer)(dat->mpi_buffer))->r_req); free(dat->mpi_buffer); // need to free device buffers used in mpi comms cutilSafeCall(cudaFree(dat->buffer_d)); if (strstr(dat->type, ":soa") != NULL || (OP_auto_soa && dat->dim > 1)) { cutilSafeCall(cudaFree(dat->buffer_d_r)); } // free data on device cutilSafeCall(cudaFree(dat->data_d)); return op_free_dat_temp_core(dat); } void op_mv_halo_device(op_set set, op_dat dat) { int set_size = set->size + OP_import_exec_list[set->index]->size + OP_import_nonexec_list[set->index]->size; if (strstr(dat->type, ":soa") != NULL || (OP_auto_soa && dat->dim > 1)) { char *temp_data = (char *)malloc((size_t)dat->size * set_size * sizeof(char)); size_t element_size = (size_t)dat->size / dat->dim; for (size_t i = 0; i < dat->dim; i++) { for (size_t j = 0; j < set_size; j++) { for (size_t c = 0; c < element_size; c++) { temp_data[element_size * i * set_size + element_size * j + c] = dat->data[(size_t)dat->size * j + element_size * i + c]; } } } op_cpHostToDevice((void **)&(dat->data_d), (void **)&(temp_data), (size_t)dat->size * set_size); free(temp_data); if (dat->buffer_d_r != NULL) cutilSafeCall(cudaFree(dat->buffer_d_r)); cutilSafeCall( cudaMalloc((void **)&(dat->buffer_d_r), (size_t)dat->size * (OP_import_exec_list[set->index]->size + OP_import_nonexec_list[set->index]->size))); } else { op_cpHostToDevice((void **)&(dat->data_d), (void **)&(dat->data), (size_t)dat->size * set_size); } dat->dirty_hd = 0; if (dat->buffer_d != NULL) cutilSafeCall(cudaFree(dat->buffer_d)); cutilSafeCall( cudaMalloc((void **)&(dat->buffer_d), (size_t)dat->size * (OP_export_exec_list[set->index]->size + OP_export_nonexec_list[set->index]->size + set_import_buffer_size[set->index]))); } void op_mv_halo_list_device() { if (export_exec_list_d != NULL) { for (int s = 0; s < OP_set_index; s++) if (export_exec_list_d[OP_set_list[s]->index] != NULL) cutilSafeCall(cudaFree(export_exec_list_d[OP_set_list[s]->index])); free(export_exec_list_d); } export_exec_list_d = (int **)xmalloc(sizeof(int *) * OP_set_index); for (int s = 0; s < OP_set_index; s++) { // for each set op_set set = OP_set_list[s]; export_exec_list_d[set->index] = NULL; op_cpHostToDevice((void **)&(export_exec_list_d[set->index]), (void **)&(OP_export_exec_list[set->index]->list), OP_export_exec_list[set->index]->size * sizeof(int)); } if (export_nonexec_list_d != NULL) { for (int s = 0; s < OP_set_index; s++) if (export_nonexec_list_d[OP_set_list[s]->index] != NULL) cutilSafeCall(cudaFree(export_nonexec_list_d[OP_set_list[s]->index])); free(export_nonexec_list_d); } export_nonexec_list_d = (int **)xmalloc(sizeof(int *) * OP_set_index); for (int s = 0; s < OP_set_index; s++) { // for each set op_set set = OP_set_list[s]; export_nonexec_list_d[set->index] = NULL; op_cpHostToDevice((void **)&(export_nonexec_list_d[set->index]), (void **)&(OP_export_nonexec_list[set->index]->list), OP_export_nonexec_list[set->index]->size * sizeof(int)); } //for grouped, we need the disps array on device too if (export_exec_list_disps_d != NULL) { for (int s = 0; s < OP_set_index; s++) if (export_exec_list_disps_d[OP_set_list[s]->index] != NULL) cutilSafeCall(cudaFree(export_exec_list_disps_d[OP_set_list[s]->index])); free(export_exec_list_disps_d); } export_exec_list_disps_d = (int **)xmalloc(sizeof(int *) * OP_set_index); for (int s = 0; s < OP_set_index; s++) { // for each set op_set set = OP_set_list[s]; export_exec_list_disps_d[set->index] = NULL; //make sure end size is there too OP_export_exec_list[set->index] ->disps[OP_export_exec_list[set->index]->ranks_size] = OP_export_exec_list[set->index]->ranks_size == 0 ? 0 : OP_export_exec_list[set->index] ->disps[OP_export_exec_list[set->index]->ranks_size - 1] + OP_export_exec_list[set->index] ->sizes[OP_export_exec_list[set->index]->ranks_size - 1]; op_cpHostToDevice((void **)&(export_exec_list_disps_d[set->index]), (void **)&(OP_export_exec_list[set->index]->disps), (OP_export_exec_list[set->index]->ranks_size+1) * sizeof(int)); } if (export_nonexec_list_disps_d != NULL) { for (int s = 0; s < OP_set_index; s++) if (export_nonexec_list_disps_d[OP_set_list[s]->index] != NULL) cutilSafeCall(cudaFree(export_nonexec_list_disps_d[OP_set_list[s]->index])); free(export_nonexec_list_disps_d); } export_nonexec_list_disps_d = (int **)xmalloc(sizeof(int *) * OP_set_index); for (int s = 0; s < OP_set_index; s++) { // for each set op_set set = OP_set_list[s]; export_nonexec_list_disps_d[set->index] = NULL; //make sure end size is there too OP_export_nonexec_list[set->index] ->disps[OP_export_nonexec_list[set->index]->ranks_size] = OP_export_nonexec_list[set->index]->ranks_size == 0 ? 0 : OP_export_nonexec_list[set->index] ->disps[OP_export_nonexec_list[set->index]->ranks_size - 1] + OP_export_nonexec_list[set->index] ->sizes[OP_export_nonexec_list[set->index]->ranks_size - 1]; op_cpHostToDevice((void **)&(export_nonexec_list_disps_d[set->index]), (void **)&(OP_export_nonexec_list[set->index]->disps), (OP_export_nonexec_list[set->index]->ranks_size+1) * sizeof(int)); } if (import_exec_list_disps_d != NULL) { for (int s = 0; s < OP_set_index; s++) if (import_exec_list_disps_d[OP_set_list[s]->index] != NULL) cutilSafeCall(cudaFree(import_exec_list_disps_d[OP_set_list[s]->index])); free(import_exec_list_disps_d); } import_exec_list_disps_d = (int **)xmalloc(sizeof(int *) * OP_set_index); for (int s = 0; s < OP_set_index; s++) { // for each set op_set set = OP_set_list[s]; import_exec_list_disps_d[set->index] = NULL; //make sure end size is there too OP_import_exec_list[set->index] ->disps[OP_import_exec_list[set->index]->ranks_size] = OP_import_exec_list[set->index]->ranks_size == 0 ? 0 : OP_import_exec_list[set->index] ->disps[OP_import_exec_list[set->index]->ranks_size - 1] + OP_import_exec_list[set->index] ->sizes[OP_import_exec_list[set->index]->ranks_size - 1]; op_cpHostToDevice((void **)&(import_exec_list_disps_d[set->index]), (void **)&(OP_import_exec_list[set->index]->disps), (OP_import_exec_list[set->index]->ranks_size+1) * sizeof(int)); } if (import_nonexec_list_disps_d != NULL) { for (int s = 0; s < OP_set_index; s++) if (import_nonexec_list_disps_d[OP_set_list[s]->index] != NULL) cutilSafeCall(cudaFree(import_nonexec_list_disps_d[OP_set_list[s]->index])); free(import_nonexec_list_disps_d); } import_nonexec_list_disps_d = (int **)xmalloc(sizeof(int *) * OP_set_index); for (int s = 0; s < OP_set_index; s++) { // for each set op_set set = OP_set_list[s]; import_nonexec_list_disps_d[set->index] = NULL; //make sure end size is there too OP_import_nonexec_list[set->index] ->disps[OP_import_nonexec_list[set->index]->ranks_size] = OP_import_nonexec_list[set->index]->ranks_size == 0 ? 0 : OP_import_nonexec_list[set->index] ->disps[OP_import_nonexec_list[set->index]->ranks_size - 1] + OP_import_nonexec_list[set->index] ->sizes[OP_import_nonexec_list[set->index]->ranks_size - 1]; op_cpHostToDevice((void **)&(import_nonexec_list_disps_d[set->index]), (void **)&(OP_import_nonexec_list[set->index]->disps), (OP_import_nonexec_list[set->index]->ranks_size+1) * sizeof(int)); } if ( export_nonexec_list_partial_d!= NULL) { for (int s = 0; s < OP_map_index; s++) if (OP_map_partial_exchange[s] && export_nonexec_list_partial_d[OP_map_list[s]->index] != NULL) cutilSafeCall(cudaFree(export_nonexec_list_partial_d[OP_map_list[s]->index])); free(export_nonexec_list_partial_d); } export_nonexec_list_partial_d = (int **)calloc(sizeof(int *) * OP_map_index,1); for (int s = 0; s < OP_map_index; s++) { // for each set if (!OP_map_partial_exchange[s]) continue; op_map map = OP_map_list[s]; export_nonexec_list_partial_d[map->index] = NULL; op_cpHostToDevice((void **)&(export_nonexec_list_partial_d[map->index]), (void **)&(OP_export_nonexec_permap[map->index]->list), OP_export_nonexec_permap[map->index]->size * sizeof(int)); } if ( import_nonexec_list_partial_d!= NULL) { for (int s = 0; s < OP_map_index; s++) if (OP_map_partial_exchange[s] && import_nonexec_list_partial_d[OP_map_list[s]->index] != NULL) cutilSafeCall(cudaFree(import_nonexec_list_partial_d[OP_map_list[s]->index])); free(import_nonexec_list_partial_d); } import_nonexec_list_partial_d = (int **)calloc(sizeof(int *) * OP_map_index,1); for (int s = 0; s < OP_map_index; s++) { // for each set if (!OP_map_partial_exchange[s]) continue; op_map map = OP_map_list[s]; import_nonexec_list_partial_d[map->index] = NULL; op_cpHostToDevice((void **)&(import_nonexec_list_partial_d[map->index]), (void **)&(OP_import_nonexec_permap[map->index]->list), OP_import_nonexec_permap[map->index]->size * sizeof(int)); } } op_set op_decl_set(int size, char const *name) { return op_decl_set_core(size, name); } op_map op_decl_map(op_set from, op_set to, int dim, int *imap, char const *name) { // int *m = (int *)xmalloc(from->size * dim * sizeof(int)); // memcpy(m, imap, from->size * dim * sizeof(int)); op_map out_map = op_decl_map_core(from, to, dim, imap, name); out_map->user_managed = 0; return out_map; // return op_decl_map_core ( from, to, dim, imap, name ); } op_arg op_arg_dat(op_dat dat, int idx, op_map map, int dim, char const *type, op_access acc) { return op_arg_dat_core(dat, idx, map, dim, type, acc); } op_arg op_opt_arg_dat(int opt, op_dat dat, int idx, op_map map, int dim, char const *type, op_access acc) { return op_opt_arg_dat_core(opt, dat, idx, map, dim, type, acc); } op_arg op_arg_gbl_char(char *data, int dim, const char *type, int size, op_access acc) { return op_arg_gbl_core(1, data, dim, type, size, acc); } op_arg op_opt_arg_gbl_char(int opt, char *data, int dim, const char *type, int size, op_access acc) { return op_arg_gbl_core(opt, data, dim, type, size, acc); } void op_printf(const char *format, ...) { int my_rank; MPI_Comm_rank(OP_MPI_WORLD, &my_rank); if (my_rank == MPI_ROOT) { va_list argptr; va_start(argptr, format); vprintf(format, argptr); va_end(argptr); } } void op_print(const char *line) { int my_rank; MPI_Comm_rank(OP_MPI_WORLD, &my_rank); if (my_rank == MPI_ROOT) { printf("%s\n", line); } } void op_timers(double *cpu, double *et) { MPI_Barrier(OP_MPI_WORLD); op_timers_core(cpu, et); } // // This function is defined in the generated master kernel file // so that it is possible to check on the runtime size of the // data in cases where it is not known at compile time // /* void op_decl_const_char ( int dim, char const * type, int size, char * dat, char const * name ) { cutilSafeCall ( cudaMemcpyToSymbol ( name, dat, dim * size, 0, cudaMemcpyHostToDevice ) ); } */ void op_exit() { // need to free buffer_d used for mpi comms in each op_dat if (OP_hybrid_gpu) { op_dat_entry *item; TAILQ_FOREACH(item, &OP_dat_list, entries) { if (strstr(item->dat->type, ":soa") != NULL || (OP_auto_soa && item->dat->dim > 1)) { cutilSafeCall(cudaFree((item->dat)->buffer_d_r)); } cutilSafeCall(cudaFree((item->dat)->buffer_d)); } for (int i = 0; i < OP_set_index; i++) { if (export_exec_list_d[i] != NULL) cutilSafeCall(cudaFree(export_exec_list_d[i])); if (export_nonexec_list_d[i] != NULL) cutilSafeCall(cudaFree(export_nonexec_list_d[i])); } for (int i = 0; i < OP_map_index; i++) { if (!OP_map_partial_exchange[i]) continue; cutilSafeCall(cudaFree(export_nonexec_list_partial_d[i])); cutilSafeCall(cudaFree(import_nonexec_list_partial_d[i])); } } op_mpi_exit(); op_cuda_exit(); // frees dat_d memory op_rt_exit(); // frees plan memory op_exit_core(); // frees lib core variables int flag = 0; MPI_Finalized(&flag); if (!flag) MPI_Finalize(); } void op_timing_output() { op_timing_output_core(); printf("Total plan time: %8.4f\n", OP_plan_time); } void op_timings_to_csv(const char *outputFileName) { int comm_size, comm_rank; MPI_Comm_size(OP_MPI_WORLD, &comm_size); MPI_Comm_rank(OP_MPI_WORLD, &comm_rank); FILE * outputFile = NULL; if (op_is_root()) { outputFile = fopen(outputFileName, "w"); if (outputFile == NULL) { printf("ERROR: Failed to open file for writing: '%s'\n", outputFileName); } else { fprintf(outputFile, "rank,thread,nranks,nthreads,count,total time,plan time,mpi time,GB used,GB total,kernel name\n"); } } bool can_write = (outputFile != NULL); MPI_Bcast(&can_write, 1, MPI_INT, MPI_ROOT, OP_MPI_WORLD); if (can_write) { for (int n = 0; n < OP_kern_max; n++) { if (OP_kernels[n].count > 0) { if (OP_kernels[n].ntimes == 1 && OP_kernels[n].times[0] == 0.0f && OP_kernels[n].time != 0.0f) { // This library is being used by an OP2 translation made with the // older // translator with older timing logic. Adjust to new logic: OP_kernels[n].times[0] = OP_kernels[n].time; } if (op_is_root()) { double times[OP_kernels[n].ntimes*comm_size]; for (int i=0; i<(OP_kernels[n].ntimes*comm_size); i++) times[i] = 0.0f; MPI_Gather(OP_kernels[n].times, OP_kernels[n].ntimes, MPI_DOUBLE, times, OP_kernels[n].ntimes, MPI_DOUBLE, MPI_ROOT, OP_MPI_WORLD); float plan_times[comm_size]; for (int i=0; i<comm_size; i++) plan_times[i] = 0.0f; MPI_Gather(&(OP_kernels[n].plan_time), 1, MPI_FLOAT, plan_times, 1, MPI_FLOAT, MPI_ROOT, OP_MPI_WORLD); double mpi_times[comm_size]; for (int i=0; i<comm_size; i++) mpi_times[i] = 0.0f; MPI_Gather(&(OP_kernels[n].mpi_time), 1, MPI_DOUBLE, mpi_times, 1, MPI_DOUBLE, MPI_ROOT, OP_MPI_WORLD); float transfers[comm_size]; for (int i=0; i<comm_size; i++) transfers[i] = 0.0f; MPI_Gather(&(OP_kernels[n].transfer), 1, MPI_FLOAT, transfers, 1, MPI_FLOAT, MPI_ROOT, OP_MPI_WORLD); float transfers2[comm_size]; for (int i=0; i<comm_size; i++) transfers2[i] = 0.0f; MPI_Gather(&(OP_kernels[n].transfer2), 1, MPI_FLOAT, transfers2, 1, MPI_FLOAT, MPI_ROOT, OP_MPI_WORLD); // Have data, now write: for (int p=0 ; p<comm_size ; p++) { for (int thr=0; thr<OP_kernels[n].ntimes; thr++) { double kern_time = times[p*OP_kernels[n].ntimes + thr]; fprintf(outputFile, "%d,%d,%d,%d,%d,%f,%f,%f,%f,%f,%s\n", p, thr, comm_size, OP_kernels[n].ntimes, OP_kernels[n].count, kern_time, plan_times[p], mpi_times[p], transfers[p] / 1e9f, transfers2[p] / 1e9f, OP_kernels[n].name); } } } else { MPI_Gather(OP_kernels[n].times, OP_kernels[n].ntimes, MPI_DOUBLE, NULL, 0, MPI_DOUBLE, MPI_ROOT, OP_MPI_WORLD); MPI_Gather(&(OP_kernels[n].plan_time), 1, MPI_FLOAT, NULL, 0, MPI_FLOAT, MPI_ROOT, OP_MPI_WORLD); MPI_Gather(&(OP_kernels[n].mpi_time), 1, MPI_DOUBLE, NULL, 0, MPI_DOUBLE, MPI_ROOT, OP_MPI_WORLD); MPI_Gather(&(OP_kernels[n].transfer), 1, MPI_FLOAT, NULL, 0, MPI_FLOAT, MPI_ROOT, OP_MPI_WORLD); MPI_Gather(&(OP_kernels[n].transfer2), 1, MPI_FLOAT, NULL, 0, MPI_FLOAT, MPI_ROOT, OP_MPI_WORLD); } op_mpi_barrier(); } } } if (op_is_root() && outputFile != NULL) { fclose(outputFile); } } void op_print_dat_to_binfile(op_dat dat, const char *file_name) { // need to get data from GPU op_cuda_get_data(dat); // rearrange data backe to original order in mpi op_dat temp = op_mpi_get_data(dat); print_dat_to_binfile_mpi(temp, file_name); free(temp->data); free(temp->set); free(temp); } void op_print_dat_to_txtfile(op_dat dat, const char *file_name) { // need to get data from GPU op_cuda_get_data(dat); // rearrange data backe to original order in mpi op_dat temp = op_mpi_get_data(dat); print_dat_to_txtfile_mpi(temp, file_name); free(temp->data); free(temp->set); free(temp); } void op_upload_all() { op_dat_entry *item; TAILQ_FOREACH(item, &OP_dat_list, entries) { op_dat dat = item->dat; int set_size = dat->set->size + OP_import_exec_list[dat->set->index]->size + OP_import_nonexec_list[dat->set->index]->size; if (dat->data_d) { if (strstr(dat->type, ":soa") != NULL || (OP_auto_soa && dat->dim > 1)) { char *temp_data = (char *)malloc((size_t)dat->size * set_size * sizeof(char)); size_t element_size = (size_t)dat->size / dat->dim; for (size_t i = 0; i < dat->dim; i++) { for (size_t j = 0; j < set_size; j++) { for (size_t c = 0; c < element_size; c++) { temp_data[element_size * i * set_size + element_size * j + c] = dat->data[(size_t)dat->size * j + element_size * i + c]; } } } cutilSafeCall(cudaMemcpy(dat->data_d, temp_data, (size_t)dat->size * set_size, cudaMemcpyHostToDevice)); dat->dirty_hd = 0; free(temp_data); } else { cutilSafeCall(cudaMemcpy(dat->data_d, dat->data, (size_t)dat->size * set_size, cudaMemcpyHostToDevice)); dat->dirty_hd = 0; } } } } void op_fetch_data_char(op_dat dat, char *usr_ptr) { // need to get data from GPU op_cuda_get_data(dat); // rearrange data backe to original order in mpi op_dat temp = op_mpi_get_data(dat); // copy data into usr_ptr memcpy((void *)usr_ptr, (void *)temp->data, temp->set->size * temp->size); free(temp->data); free(temp->set); free(temp); } op_dat op_fetch_data_file_char(op_dat dat) { // need to get data from GPU op_cuda_get_data(dat); // rearrange data backe to original order in mpi return op_mpi_get_data(dat); } void op_fetch_data_idx_char(op_dat dat, char *usr_ptr, int low, int high) { // need to get data from GPU op_cuda_get_data(dat); // rearrange data backe to original order in mpi op_dat temp = op_mpi_get_data(dat); // do allgather on temp->data and copy it to memory block pointed to by // use_ptr fetch_data_hdf5(temp, usr_ptr, low, high); free(temp->data); free(temp->set); free(temp); }
025cd4747c66b1067d2041bb0439595bd6ac45ba
19865cda31b2a42fbb17ac4105e4a422a83342f6
/BOJ/03000/3029_경고.cpp
2cb3a0f142f928477c44c02aa7d8d511861536ca
[]
no_license
warmwhiten/PS
0f19c3742b09ee966196fc4e25f4fd58070a0eb2
a2a1d8952e6cb4f65cc0fede35d730a80af617ff
refs/heads/master
2023-02-08T15:55:06.389594
2020-12-28T06:57:40
2020-12-28T06:57:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,108
cpp
3029_경고.cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int #define FUP(i, a, b) for(int i = a; i <= b; i++) #define FDOWN(i, a, b) for(int i = a; i >= b; i--) #define MS(a, b) memset(a, b, sizeof(a)) #define ALL(v) v.begin(), v.end() #define ENDL '\n' int dy[4] = { -1, 1, 0, 0 }; int dx[4] = { 0, 0, 1, -1 }; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); string start, end; int s[3], e[3], ans[3]; cin >> start >> end; s[0] = stoi(start.substr(0, 2)); s[1] = stoi(start.substr(3, 2)); s[2] = stoi(start.substr(6, 2)); e[0] = stoi(end.substr(0, 2)); e[1] = stoi(end.substr(3, 2)); e[2] = stoi(end.substr(6, 2)); if (e[2] >= s[2]) ans[2] = e[2] - s[2]; else ans[2] = 60 + e[2] - s[2], e[1]--; if (e[1] >= s[1]) ans[1] = e[1] - s[1]; else ans[1] = 60 + e[1] - s[1], e[0]--; if (e[0] >= s[0]) ans[0] = e[0] - s[0]; else ans[0] = 24 + e[0] - s[0]; if (ans[2] == 0 && ans[1] == 0 && ans[0] == 0) ans[0] = 24; for (int i = 0; i < 3; i++) { if (ans[i] < 10) cout << '0' << ans[i]; else cout << ans[i]; if (i != 2) cout << ':'; } return 0; }
940beb0d410bc433e083d6843bbb464328fcc715
8ab4144a0a68a5b2e39694c306c9cc481093f74a
/OnlineJudges/lydsy/2659.cpp
c5d0f99f185bba762b99c56bbf4529fe35141384
[ "WTFPL" ]
permissive
TooYoungTooSimp/my_solutions
4a7ff93e8bd05f111c4a8ec73afbc988c69dc567
74387e4b9902c1cac13d0347889953890dc27df9
refs/heads/master
2022-10-28T00:11:25.215037
2020-06-14T17:06:14
2020-06-14T17:06:14
66,897,046
8
3
null
2017-01-12T12:05:49
2016-08-30T02:00:46
C++
UTF-8
C++
false
false
210
cpp
2659.cpp
//http://www.cnblogs.com/iwtwiioi/p/4985747.html #include <cstdio> int main() { int p, q; scanf("%d%d", &p, &q); printf("%lld", 1ll * (q - 1) * (p - 1) / 4 + (p == q) * (q - 1) / 2); return 0; }
205c7365698a81f7e74f3680232068554870fbb0
af4363f65ff81393d8893a710d4a5f9498eb8f4b
/refer.cpp
d57b7dc182b7d9b18341d6a7cad4b43048e6be1b
[]
no_license
granty1/cpplearning
7b86d63626bbb72fa9ccd68698fcf8afd4249f05
39e749710c11b3e880cd5fc37c8a4f3e6ab1037e
refs/heads/master
2022-11-06T08:45:39.281518
2020-06-14T12:50:53
2020-06-14T12:50:53
272,132,518
1
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
refer.cpp
// // refer.cpp // cpplearning // // Created by Grant on 2020/6/14. // Copyright © 2020 Grant. All rights reserved. // #include "refer.hpp" #include "iostream" using namespace std; double values[] = {10.1, 5.2 ,6,3}; double getValue(int index); void swap(int *a, int *b); void referDesc() { int a = 1, b = 2; swap(a, b); cout << a << b << endl; cout << getValue(10) << endl; } void swap(int& a, int& b) { int temp = a; a = b; b = temp; } double getValue(int index){ if (values[index] == 0) { cout << "index out of range!" << endl; return 0; } return values[index]; }
df659aa8a422a69ced1bc32d8aa76815e535377f
350fe17d45d545242682e667c16c1aafb2f2c904
/SHO_GS/CUserLIST.h
acbd15510761b34c557e298c49b855cb895f41fd
[]
no_license
hdelanno/titanmods
cd371984f26432b238087bac61bda395166e06fb
1712e5bc5f9d192eca2666721475419c7da0adf2
refs/heads/master
2021-01-20T16:45:18.250756
2014-03-18T16:55:13
2014-03-18T16:55:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,141
h
CUserLIST.h
//////////////////////////////////////////////////////////////////////// /////// CUserLIST class by MaTT (c) 2009-2010 //////////// //////////////////////////////////////////////////////////////////////// #ifndef CUserLIST_H #define CUserLIST_H #include "SHO_GS.h" #include "IOCPSocketSERVER.h" #include "CDataPOOL.h" #include "CCriticalSection.h" class TGAMESERVER_API CUserLIST : public IOCPSocketSERVER , public CDataPOOL<classUSER> { public: CCriticalSection m_csHashACCOUNT; CCriticalSection m_csHashCHAR; CCriticalSection m_csNullZONE; classHASH<classUSER *>* m_pHashACCOUNT; classHASH<classUSER *>* m_pHashCHAR; classDLLIST<CGameOBJ *> m_NullZoneLIST; int m_iUserCNT; void InitData(classUSER* pData); void FreeData(classUSER* pData); unsigned long m_HashLevelUpTRIGGER[0xC8]; CUserLIST(); CUserLIST(unsigned int uiInitDataCNT, unsigned int uiIncDataCNT); virtual ~CUserLIST(); void DeleteUSER(classUSER* pUSER, unsigned char btLogOutMODE); bool SendPacketToSocketIDX(int iClientSocketIDX, classPACKET* pCPacket); void Send_wsv_CREATE_CHAR(int iSocketIDX, unsigned char btResult); void Send_wsv_MEMO(int iSocketIDX, unsigned char btTYPE, short nMemoCNT); void Send_wsv_GUILD_COMMAND(int iSocketIDX, unsigned char btResult, char* szStr); classUSER* Find_CHAR(char* szCharName); bool Add_CHAR(classUSER* pUSER); classUSER* Find_ACCOUNT(char* szAccount); bool Add_ACCOUNT(int iSocketIDX, t_PACKET* pRecvPket, char* szAccount); classUSER* Find_IP(char* szIP); void Send_zws_ACCOUNT_LIST(CClientSOCKET* pSrvSocket, bool bSendToGUMS); void Send_cli_STRESS_TEST(classPACKET* pCPacket); void Save_AllUSER(); int Get_AccountCNT(); bool Kick_ACCOUNT(char* szAccount); unsigned long Get_LevelUpTRIGGER(short nLevel); void Add_NullZONE(classDLLNODE<CGameOBJ *>* pUserNODE); void Sub_NullZONE(classDLLNODE<CGameOBJ *>* pUserNODE); void Check_SocketALIVE(); virtual iocpSOCKET* AllocClientSOCKET(); virtual void FreeClientSOCKET(iocpSOCKET* pCLIENT); virtual void ClosedClientSOCKET(iocpSOCKET* pCLIENT); }; #endif
35f9b02afdeed7fcd4c054c6d8ed4163abb3c9b9
24f26275ffcd9324998d7570ea9fda82578eeb9e
/chrome/browser/sharing/shared_clipboard/shared_clipboard_message_handler_desktop.h
9e8c2fb8c663b0e29e143b57461d819f531bdb9e
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
1,242
h
shared_clipboard_message_handler_desktop.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SHARING_SHARED_CLIPBOARD_SHARED_CLIPBOARD_MESSAGE_HANDLER_DESKTOP_H_ #define CHROME_BROWSER_SHARING_SHARED_CLIPBOARD_SHARED_CLIPBOARD_MESSAGE_HANDLER_DESKTOP_H_ #include "base/macros.h" #include "chrome/browser/sharing/shared_clipboard/shared_clipboard_message_handler.h" class NotificationDisplayService; class SharingService; // Handles incoming messages for the shared clipboard feature. class SharedClipboardMessageHandlerDesktop : public SharedClipboardMessageHandler { public: SharedClipboardMessageHandlerDesktop( SharingService* sharing_service, NotificationDisplayService* notification_display_service); ~SharedClipboardMessageHandlerDesktop() override; private: // SharedClipboardMessageHandler implementation. void ShowNotification(const std::string& device_name) override; NotificationDisplayService* notification_display_service_ = nullptr; DISALLOW_COPY_AND_ASSIGN(SharedClipboardMessageHandlerDesktop); }; #endif // CHROME_BROWSER_SHARING_SHARED_CLIPBOARD_SHARED_CLIPBOARD_MESSAGE_HANDLER_DESKTOP_H_
d8e5fac1d93a493b71e49a89d51bc04cdef37923
369dc5cdc4a15a328d1d6bb386baae3f057835e0
/src/NodeInfo.cpp
78d8b8368098f0b78ef8ef5ab9a6537c3c425935
[]
no_license
poskart/TIN_p2p
659e97b73bcf9a605a983b44973b1b347bfc9660
e40f899c3ddc353d7f35c7ee35466fc11e742254
refs/heads/dev
2021-09-05T10:36:01.609239
2018-01-26T08:29:56
2018-01-26T08:29:56
115,791,180
0
1
null
2018-01-26T09:16:19
2017-12-30T11:00:47
C++
UTF-8
C++
false
false
5,992
cpp
NodeInfo.cpp
#include "NodeInfo.h" #include "NetUtils.h" #include "Command.h" #include "SendFileTcp.h" #include <unistd.h> NodeInfo::~NodeInfo() { // Delete all conditionla variables for(auto & pair: nodeFiles) delete std::get<2>(pair.second); } void NodeInfo::addNewFileEntry(std::string hash, size_t nodeId) { std::unique_lock<std::mutex> uLock(nodeFilesMtx); FileInfo info = std::make_tuple(nodeId, 0, new std::condition_variable()); nodeFiles.insert(std::pair<std::string, FileInfo>(hash, info)); } void NodeInfo::removeFile(std::string hash) { std::unique_lock<std::mutex> uLock(nodeFilesMtx); auto it = nodeFiles.find(hash); FileInfo & fInfo = it->second; // Wait until there is 0 transfers std::get<2>(fInfo)->wait(uLock, [&fInfo]{return std::get<1>(fInfo) == 0;}); delete std::get<2>(fInfo); // free heap memory unlink(it->first.c_str()); nodeFiles.erase(it); } void NodeInfo::addNewNode(struct in_addr nodeIP) { std::unique_lock<std::mutex> uLock(nodeMapMtx); nodeMap.insert(std::pair<size_t,struct in_addr>(nodeCnt, nodeIP)); ++nodeCnt; } void NodeInfo::removeNode(size_t nodeId) { std::unique_lock<std::mutex> uLock(nodeMapMtx); nodeMap.erase(nodeId); --nodeCnt; } struct in_addr NodeInfo::getNodeIP(size_t nodeId) { std::unique_lock<std::mutex> uLock(nodeMapMtx); std::map<size_t,struct in_addr>::iterator it = nodeMap.find(nodeId); if (it == nodeMap.end()) { struct in_addr tmp; tmp.s_addr = 0; return tmp; } return it->second; } void NodeInfo::setNode(size_t nodeId, struct in_addr nodeIP) { //change node IP or create new entry std::unique_lock<std::mutex> uLock(nodeMapMtx); std::map<size_t,struct in_addr>::iterator it = nodeMap.find(nodeId); if (it == nodeMap.end()) { nodeMap.insert(std::pair<size_t,struct in_addr>(nodeId, nodeIP)); ++nodeCnt; return; } it->second = nodeIP; } void NodeInfo::removeFiles(size_t ownerId, std::unique_lock<std::mutex>& uLock) { for (auto it = nodeFiles.begin(); it != nodeFiles.end(); ++it) { if (std::get<0>(it->second) == ownerId) { // Wait until there is 0 transfers on this file std::get<2>(it->second)->wait(uLock, [&it]{return std::get<1>(it->second) == 0;}); unlink(it->first.c_str()); delete std::get<2>(it->second); // free heap memory (condition variable) nodeFiles.erase(it); } } } // Used only in reconfiguration void NodeInfo::changeFilesOwner(size_t newOwnerId, size_t oldOwnerId) { for (auto it = nodeFiles.begin(); it != nodeFiles.end(); ++it) { if (std::get<0>(it->second) == oldOwnerId) std::get<0>(it->second) = newOwnerId; } } void NodeInfo::reconfiguration(size_t newNodeCnt, size_t leavingNodeId, bool isMe) { std::unique_lock<std::mutex> uLock(nodeFilesMtx); if (newNodeCnt != nodeCnt - 1) { std::cout << "Network's corrupted!" << std::endl; return; } if (nodeCnt == 0 && isMe) { //last node in network removeFiles(0, uLock); return; } removeFiles(leavingNodeId, uLock); //remove files from leaving node if (newNodeCnt != leavingNodeId) { //not last node setNode(leavingNodeId, getNodeIP(newNodeCnt)); //swap nodes removeNode(newNodeCnt); changeFilesOwner(leavingNodeId, newNodeCnt); if (nodeId == newNodeCnt) //this was last added node nodeId = leavingNodeId; } else //last node removeNode(newNodeCnt); for (auto it = nodeFiles.begin(); it != nodeFiles.end(); ++it) { size_t newNodeId = NetUtils::calcNodeId(it->first, this); if (newNodeId != nodeId || isMe) { //need to send this file || its leaving InfoMessage msg(304, newNodeId, it->first); pthread_t thread; Command* command = new SendFileTcp(msg, true); pthread_create(&thread, NULL, Command::commandExeWrapper, static_cast<void *>(command)); pthread_join(thread, 0); unlink(it->first.c_str()); delete std::get<2>(it->second); // free heap memory (condition variable) nodeFiles.erase(it); } } } void NodeInfo::reconfiguration(size_t newNodeCnt, struct in_addr newNodeAddr) { addNewNode(newNodeAddr); std::unique_lock<std::mutex> uLock(nodeFilesMtx); if (newNodeCnt != nodeCnt) { //added node before std::cout << "Network's corrupted!" << std::endl; return; } for (auto it = nodeFiles.begin(); it != nodeFiles.end(); ++it) { size_t newNodeId = NetUtils::calcNodeId(it->first, this); if (newNodeId != nodeId) { //need to send this file InfoMessage msg(304, newNodeId, it->first); pthread_t thread; Command* command = new SendFileTcp(msg, true); pthread_create(&thread, NULL, Command::commandExeWrapper, static_cast<void *>(command)); pthread_join(thread, 0); unlink(it->first.c_str()); delete std::get<2>(it->second); // free heap memory (condition variable) nodeFiles.erase(it); } } } void NodeInfo::callForEachNode(std::function<void (struct in_addr *)> callback) { std::unique_lock<std::mutex> uLock(nodeMapMtx); for(auto & addr : nodeMap) callback(&(addr.second)); } void NodeInfo::callForEachNode(std::function<void (size_t, struct in_addr *)> callback) { std::unique_lock<std::mutex> uLock(nodeMapMtx); for(auto & addr : nodeMap) callback(addr.first, &(addr.second)); } void NodeInfo::callForEachFile(std::function<void (std::string)> callback) { std::unique_lock<std::mutex> uLock(nodeFilesMtx); for(auto & file : nodeFiles) callback(file.first); } void NodeInfo::registerFileTransfer(std::string hash, bool noMutex) { if (!noMutex) std::unique_lock<std::mutex> uLock(nodeFilesMtx); auto it = nodeFiles.find(hash); ++std::get<1>(it->second); } void NodeInfo::unregisterFileTransfer(std::string hash, bool noMutex) { if (!noMutex) std::unique_lock<std::mutex> uLock(nodeFilesMtx); auto it = nodeFiles.find(hash); --std::get<1>(it->second); // Notify if all transfers completed if(std::get<1>(it->second) == 0) (std::get<2>(it->second))->notify_one(); } size_t NodeInfo::getOwnerId(std::string hash, bool noMutex) { if (!noMutex) std::unique_lock<std::mutex> uLock(nodeFilesMtx); auto it = nodeFiles.find(hash); return std::get<0>(it->second); }
69145b2998ccd03318995e65bcaaef38a39733bc
93b7d6b36f2388ae5594c651b45e1618da4bf2af
/src/utility/VectorSerializer.cpp
da8377002717fb472484986a40f60ba375f97368
[]
no_license
seccijr/es.upm.euitt.pfg.master
a38e20a5b8b0f1f0e2f7335ac64e71fd93f1565d
316228aadac3f947acb14cd3c278fbbff24c1669
refs/heads/master
2021-01-10T04:10:14.417198
2016-01-04T10:40:19
2016-01-04T10:40:19
45,617,525
0
0
null
null
null
null
UTF-8
C++
false
false
1,941
cpp
VectorSerializer.cpp
#include "VectorSerializer.h" #include "DirectionSerializer.h" #include "PacketSerializer.h" #include "master_types.h" void VectorSerializer::deserialize(Vector *v, const byte *buffer) { const byte *direction_prt = buffer; const byte *packet_prt = buffer + (2 * MMT_ENDPOINT_LEN) + 2; Direction drct; DirectionSerializer::deserialize(&drct, direction_prt); Packet pckt; PacketSerializer::deserialize(&pckt, packet_prt); v->packet = pckt; v->direction = drct; } void VectorSerializer::deserialize(Vector *v, Stream *s) { int i = 0; byte buffer[MMT_VECTOR_LEN] = {0}; while (s->available() > 0) { buffer[i++] = s->read(); } VectorSerializer::deserialize(v, (const byte *)buffer); } void VectorSerializer::serialize(const Vector &v, Print *p) { DirectionSerializer::serialize(v.direction, p); PacketSerializer::serialize(v.packet, p); } void VectorSerializer::humanReadable(const Vector &v, Print *p) { char ip_str[17] = {0}; sprintf(ip_str, "%u.%u.%u.%u", v.direction.source.endpoint[0], v.direction.source.endpoint[1], v.direction.source.endpoint[2], v.direction.source.endpoint[3]); p->print("Source endpoint: "); p->println(ip_str); sprintf(ip_str, "%u.%u.%u.%u", v.direction.destination.endpoint[0], v.direction.destination.endpoint[1], v.direction.destination.endpoint[2], v.direction.destination.endpoint[3]); p->print("Destination endpoint: "); p->println(ip_str); p->print("Origin resource: "); p->println(v.direction.source.resource); p->print("Target resource: "); p->println(v.direction.destination.resource); p->print("Method: "); p->println(v.packet.method); char value_str[13] = {0}; sprintf(value_str, "%02x %02x %02x %02x", v.packet.message.value.b[0], v.packet.message.value.b[1], v.packet.message.value.b[2], v.packet.message.value.b[3]); p->print("Value: "); p->println(value_str); }
acc02f2725999d8575f7ce93b135e0ae64b9efb5
7507deeb5944435d3f6bf242ef79e0b6b1022a37
/cpp/Client.cpp
d9cfa95221c2752c073bfe976e39bcd9bf5ed1a0
[]
no_license
adam-zhang/proxy
def51981627516459cb8cb3126e0278b91520477
cf5a238112de4bad267fbe951a0385fda7279743
refs/heads/master
2020-04-10T20:33:40.013276
2019-01-16T07:50:54
2019-01-16T07:50:54
68,060,678
0
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
Client.cpp
#include <iostream> #include "SocketClient.h" #include "Common.h" using namespace std; int main(int, char**) { SocketClient client("127.0.0.1", PORT); auto ret = client.Connect(); client.Send("Hello Server"); return 0; }
368e7883a3af75f01173b58c5a2fcb816da873b1
b480c710a2a17d5738380ceb4fb07d4c91369bac
/HZZUtils/HZZUtils/.svn/text-base/SampleShowerInfo.h.svn-base
e182413e7af8915b0f43c367e7be7bad6e963c88
[]
no_license
MittalMonika/VBSZZ4l
36783dfd489966295a29a63f98f598d762720cb4
1b2dd019b7a8a5520901f1bcea7a4863d3dfe9a7
refs/heads/master
2021-01-13T13:41:04.987774
2017-06-22T10:56:15
2017-06-22T10:56:15
95,105,662
0
1
null
null
null
null
UTF-8
C++
false
false
452
SampleShowerInfo.h.svn-base
#ifndef SAMPLESHOWERINFO_H #define SAMPLESHOWERINFO_H #include <string> namespace SampleShowerInfo { // This gets the efficiency map for btagging SF tool void fillEffMapForBTag(std::string& effMap); // Return backs the MC used for showering void fillSampleShowerInfo(const std::string& containerName, std::string& showerMCName); void fillIndexForBTag(const std::string& containerName, int& index); } #endif//SAMPLESHOWERINFO_H
8b86a19deeb62b4f516e991bfa12f0ab8b2480cc
444080c760d38fb6a21107166e6db0829522b1fa
/TestLegendre/TestLegendreArray.cpp
9733f732d524ed50c7fa650c4231860726a3cc0e
[]
no_license
pmann84/Legendre
36f1a62700b40e20de693fa994341603199cac31
f2e8ffcbb971d0fcada921b9e8af8d81c923580c
refs/heads/master
2020-06-05T03:38:26.602616
2017-06-29T15:41:24
2017-06-29T15:41:24
192,300,873
1
0
null
null
null
null
UTF-8
C++
false
false
2,735
cpp
TestLegendreArray.cpp
#include "gtest/gtest.h" #include "gmock/gmock.h" #include "TestLegendreUtils.h" #include "../Legendre/AssociatedLegendre.h" TEST(TestLegendreArray, LegendreInvalidInput) { unsigned int l = 1; unsigned int m = 1; std::vector<double> inputs({-0.75, -0.5, 0.0, 0.25, 1.5}); AssociatedLegendre legendre(l, m); EXPECT_THROW(legendre(inputs), LegendreException::InputOutOfRange); } TEST(TestLegendreArray, LegendreEvaluateAtM0L0) { unsigned int l = 0; unsigned int m = 0; std::vector<double> inputs({ -0.75, -0.5, 0.0, 0.25, 0.5 }); AssociatedLegendre legendre(l, m); EXPECT_THAT(legendre(inputs), testing::ElementsAre(TestLegendreUtils::Legendre00(inputs[0]), TestLegendreUtils::Legendre00(inputs[1]), TestLegendreUtils::Legendre00(inputs[2]), TestLegendreUtils::Legendre00(inputs[3]), TestLegendreUtils::Legendre00(inputs[4]))); } TEST(TestLegendreArray, LegendreEvaluateAtM1L1) { unsigned int l = 1; unsigned int m = 1; std::vector<double> inputs({ -0.75, -0.5, 0.0, 0.25, 0.5 }); AssociatedLegendre legendre(l, m); EXPECT_THAT(legendre(inputs), testing::ElementsAre(TestLegendreUtils::Legendre11(inputs[0]), TestLegendreUtils::Legendre11(inputs[1]), TestLegendreUtils::Legendre11(inputs[2]), TestLegendreUtils::Legendre11(inputs[3]), TestLegendreUtils::Legendre11(inputs[4]))); } TEST(TestLegendreArray, LegendreEvaluateAtM1L2) { unsigned int l = 2; unsigned int m = 1; std::vector<double> inputs({ -0.75, -0.5, 0.0, 0.25, 0.5 }); AssociatedLegendre legendre(l, m); std::vector<double> results = legendre(inputs); EXPECT_THAT(legendre(inputs), testing::ElementsAre(TestLegendreUtils::Legendre21(inputs[0]), TestLegendreUtils::Legendre21(inputs[1]), TestLegendreUtils::Legendre21(inputs[2]), TestLegendreUtils::Legendre21(inputs[3]), TestLegendreUtils::Legendre21(inputs[4]))); } TEST(TestLegendreArray, LegendreEvaluateAtM1L3) { unsigned int l = 3; unsigned int m = 1; std::vector<double> inputs({ -0.75, -0.5, 0.0, 0.25, 0.5 }); AssociatedLegendre legendre(l, m); std::vector<double> results = legendre(inputs); for (int i = 0; i < results.size(); ++i) { EXPECT_DOUBLE_EQ(results[i], TestLegendreUtils::Legendre31(inputs[i])); } } TEST(TestLegendreArray, LegendreEvaluateAtM3L4) { unsigned int l = 4; unsigned int m = 3; std::vector<double> inputs({ -0.75, -0.5, 0.0, 0.25, 0.5 }); AssociatedLegendre legendre(l, m); std::vector<double> results = legendre(inputs); for (int i = 0; i < results.size(); ++i) { EXPECT_DOUBLE_EQ(results[i], TestLegendreUtils::Legendre43(inputs[i])); } }
0393e8b38e9a9f19368de062f24f38e0a4d7deba
3df995fa02a43932ab2ea5fea26c06403f139f1f
/abc/abc087b.cc
36ddefd8d04d2c599a219d413c70632b71bc86b7
[]
no_license
jojonki/atcoder
75fb7016dd90b3b7495f1ff558eedcdc755eac11
ec487b4e11835f25c6770f0115b98b7e93b16466
refs/heads/master
2021-06-23T09:56:05.636055
2021-03-13T03:38:50
2021-03-13T03:38:50
201,834,404
0
0
null
null
null
null
UTF-8
C++
false
false
763
cc
abc087b.cc
#include<iostream> using namespace std; // なんて言うか50の倍数であることは気にせず,普通に3重for回せばよかった.50^3ほどの処理なので回せる int main() { int A, B, C, X, count = 0; cin >> A >> B >> C >> X; int Xt = X / 50; int At[A+1], Bt[B+1], Ct[C+1]; for (int i=0; i<A+1; i++) { At[i] = i * (500/50); } for (int i=0; i<B+1; i++) { Bt[i] = i * (100/50); } for (int i=0; i<C+1; i++) { Ct[i] = i * (50/50); } for (int i=0; i<A+1; i++) { for (int j=0; j<B+1; j++) { for (int k=0; k<C+1; k++) { if ((At[i]+ Bt[j] + Ct[k]) == Xt) count++; } } } cout << count << endl; return 0; }
028ffa97f5568ebb24be056637c73824768cca5c
51a43135ba39a2c168b74aca54dadaee79edb950
/Exercise 5/Point.cpp
78e53e2bdc34fd9b63d20e2a0571ad20a8edba32
[]
no_license
sirhamsteralot/School-Exercises
2e1788417083f147aaaef8f23d790e6a6b943dd9
0d305fe1bb75bb05199957007d9a4025124f6939
refs/heads/master
2021-04-15T12:30:31.419722
2018-03-27T15:09:09
2018-03-27T15:09:09
126,706,405
0
0
null
null
null
null
UTF-8
C++
false
false
891
cpp
Point.cpp
#include "stdafx.h" #include "Point.h" #include <iostream> #include <math.h> Point::Point() { this->X = 0.0; this->Y = 0.0; } Point::Point(const double _x, const double _y, std::string _name) { this->X = _x; this->Y = _y; this->Name = _name; } void Point::Print() { std::cout << "[" << this->X << ", " << this->Y << ", " << this->Name << std::endl; } double Point::GetX() { return this->X; } double Point::GetY() { return this->Y; } std::string Point::GetName() { return this->Name; } void Point::SetX(const double _x) { this->X = _x; } void Point::SetY(const double _y) { this->Y = _y; } void Point::SetName(std::string _name) { this->Name = _name; } double Point::Distance(const Point secondPoint) { double distX = abs(secondPoint.X - this->X); double distY = abs(secondPoint.Y - this->Y); return sqrt((distX * distX) + (distY * distY)); } Point::~Point() { }
e1f4183976553bfcbcf0289453e049c711d71837
0a68bc0c89f4e52791bb1e1998c712205d48f27a
/Main.cpp
f6e28ee3db99cee00dfb76b830dde151541c0ceb
[]
no_license
simonque/blockbreaker
80d0fbe074eef4a03d8719c11ad2e8b41616cc60
498f7ef45a596f8ee5fc6c53703e0eb4fc2a71c5
refs/heads/master
2021-05-28T21:50:30.662310
2013-11-11T00:54:16
2013-11-11T00:54:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,595
cpp
Main.cpp
////////////////////////////////////////////////////////////////////////////////// // Project: Block Breaker (Breakout) // File: Main.cpp ////////////////////////////////////////////////////////////////////////////////// // These three lines link in the required SDL components for our project. // // Alternatively, we could have linked them in our project settings. // #pragma comment(lib, "SDL.lib") #pragma comment(lib, "SDLmain.lib") #pragma comment(lib, "SDL_TTF.lib") #include "SDL/SDL.h" // Main SDL header #include "SDL/SDL_TTF.h" // True Type Font header #include "Defines.h" // Our defines header using namespace std; // The STL stack can't take a function pointer as a type // // so we encapsulate a function pointer within a struct. // struct StateStruct { void (*StatePointer)(); }; // The block just stores it's location and the amount of times it can be hit (health) // struct Block { SDL_Rect screen_location; // location on screen SDL_Rect bitmap_location; // location of image in bitmap int num_hits; // health }; // The paddle only moves horizontally so there's no need for a y_speed variable // struct Paddle { SDL_Rect screen_location; // location on screen SDL_Rect bitmap_location; // location of image in bitmap int x_speed; }; // The ball moves in any direction so we need to have two speed variables // struct Ball { SDL_Rect screen_location; // location on screen SDL_Rect bitmap_location; // location of image in bitmap int x_speed; int y_speed; }; #define MAX_STACK_SIZE 16 class StateStack { public: StateStack() : stack_size(0) {} bool empty() const { return (stack_size == 0); } const StateStruct& top() const { if (!empty()) return pointers[stack_size - 1]; return StateStruct(); } void pop() { if (!empty()) --stack_size; } void push(const StateStruct& ptr) { if (stack_size < MAX_STACK_SIZE) pointers[stack_size++] = ptr; } private: StateStruct pointers[MAX_STACK_SIZE]; int stack_size; }; // Global data // StateStack g_StateStack; // Our state stack SDL_Surface* g_Bitmap = NULL; // Our background image SDL_Surface* g_Window = NULL; // Our backbuffer SDL_Event g_Event; // An SDL event structure for input int g_Timer; // Our timer is just an integer Paddle g_Player; // The player's paddle Ball g_Ball; // The game ball int g_Lives; // Player's lives int g_Level = 1; // Current level int g_NumBlocks = 0; // Keep track of number of blocks Block g_Blocks[MAX_BLOCKS]; // The blocks we're breaking // Functions to handle the states of the game // void Menu(); void Game(); void Exit(); void GameWon(); void GameLost(); // Helper functions for the main game state functions // void ClearScreen(); void DisplayText(const char* text, int x, int y, int size, int fR, int fG, int fB, int bR, int bG, int bB); void HandleMenuInput(); void HandleGameInput(); void HandleExitInput(); void HandleWinLoseInput(); // Since there's only one paddle, we no longer need to pass the player's paddle // // to CheckBallCollisions. The function will just assume that's what we mean. // bool CheckBallCollisions(); void CheckBlockCollisions(); void HandleBlockCollision(int index); bool CheckPointInRect(int x, int y, SDL_Rect rect); void HandleBall(); void MoveBall(); void HandleLoss(); void HandleWin(); void ChangeLevel(); // Init and Shutdown functions // void Init(); void InitBlocks(); void Shutdown(); int main(int argc, char **argv) { Init(); // Our game loop is just a while loop that breaks when our state stack is empty. // while (!g_StateStack.empty()) { g_StateStack.top().StatePointer(); } Shutdown(); return 0; } // This function initializes our game. // void Init() { // Initiliaze SDL video and our timer. // SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER); // Setup our window's dimensions, bits-per-pixel (0 tells SDL to choose for us), // // and video format (SDL_ANYFORMAT leaves the decision to SDL). This function // // returns a pointer to our window which we assign to g_Window. // g_Window = SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 0, SDL_ANYFORMAT); // Set the title of our window. // SDL_WM_SetCaption(WINDOW_CAPTION, 0); // Get the number of ticks since SDL was initialized. // g_Timer = SDL_GetTicks(); // Initialize the player's data // // screen locations g_Player.screen_location.x = (WINDOW_WIDTH / 2) - (PADDLE_WIDTH / 2); // center screen g_Player.screen_location.y = PLAYER_Y; g_Player.screen_location.w = PADDLE_WIDTH; g_Player.screen_location.h = PADDLE_HEIGHT; // image location g_Player.bitmap_location.x = PADDLE_BITMAP_X; g_Player.bitmap_location.y = PADDLE_BITMAP_Y; g_Player.bitmap_location.w = PADDLE_WIDTH; g_Player.bitmap_location.h = PADDLE_HEIGHT; // player speed g_Player.x_speed = PLAYER_SPEED; // lives g_Lives = NUM_LIVES; // Initialize the ball's data // // screen location g_Ball.screen_location.x = (WINDOW_WIDTH / 2) - (BALL_DIAMETER / 2); // center screen g_Ball.screen_location.y = (WINDOW_HEIGHT / 2) - (BALL_DIAMETER / 2); // center screen g_Ball.screen_location.w = BALL_DIAMETER; g_Ball.screen_location.h = BALL_DIAMETER; // image location g_Ball.bitmap_location.x = BALL_BITMAP_X; g_Ball.bitmap_location.y = BALL_BITMAP_Y; g_Ball.bitmap_location.w = BALL_DIAMETER; g_Ball.bitmap_location.h = BALL_DIAMETER; // speeds g_Ball.x_speed = 0; g_Ball.y_speed = 0; // We'll need to initialize our blocks for each level, so we have a separate function handle it // InitBlocks(); // Fill our bitmap structure with information. // g_Bitmap = SDL_LoadBMP("data/BlockBreaker.bmp"); // Set our transparent color (magenta) // SDL_SetColorKey( g_Bitmap, SDL_SRCCOLORKEY, SDL_MapRGB(g_Bitmap->format, 255, 0, 255) ); // We start by adding a pointer to our exit state, this way // // it will be the last thing the player sees of the game. // StateStruct state; state.StatePointer = Exit; g_StateStack.push(state); // Then we add a pointer to our menu state, this will // // be the first thing the player sees of our game. // state.StatePointer = Menu; g_StateStack.push(state); // Initialize the true type font library. // TTF_Init(); } // This function determines which level to load and then iterates through the block structure // // reading in values from the level file and setting up the blocks accordingly. // void InitBlocks() { // The following code creates a buffer storing the proper file name. If // // g_Level = 1, we get: "data\\level" + "1" + ".txt" = "data\\level1.txt" // char file_name[256]; // for sprintf // the file will always start with "level" sprintf(file_name, "data\\level%d.txt", g_Level); // Open the file for input. FILE* inFile = fopen(file_name, "r"); int index = 0; // used to index blocks in g_Blocks array // We'll first read in the number of hits a block has and then determine whether we // // should create the block (num_hits = 1-4) or if we should skip that block (0) // int temp_hits; // Iterate through each row and column of blocks // for (int row=0; row<NUM_ROWS; row++) { for (int col=0; col<NUM_COLS; col++) { // Read the next value into temp_hits // fscanf(inFile, "%d", &temp_hits); g_Blocks[index].num_hits = temp_hits; // We set the location of the block according to what row and column // // we're on in our loop. Notice that we use BLOCK_SCREEN_BUFFER to set // // the blocks away from the sides of the screen. // g_Blocks[index].screen_location.x = col*BLOCK_WIDTH + BLOCK_WIDTH - BLOCK_SCREEN_BUFFER; g_Blocks[index].screen_location.y = row*BLOCK_HEIGHT + BLOCK_HEIGHT + BLOCK_SCREEN_BUFFER; g_Blocks[index].screen_location.w = BLOCK_WIDTH; g_Blocks[index].screen_location.h = BLOCK_HEIGHT; g_Blocks[index].bitmap_location.w = BLOCK_WIDTH; g_Blocks[index].bitmap_location.h = BLOCK_HEIGHT; // Now we set the bitmap location rect according to num_hits // switch (g_Blocks[index].num_hits) { case 1: { g_Blocks[index].bitmap_location.x = RED_X; g_Blocks[index].bitmap_location.y = RED_Y; } break; case 2: { g_Blocks[index].bitmap_location.x = YELLOW_X; g_Blocks[index].bitmap_location.y = YELLOW_Y; } break; case 3: { g_Blocks[index].bitmap_location.x = GREEN_X; g_Blocks[index].bitmap_location.y = GREEN_Y; } break; case 4: { g_Blocks[index].bitmap_location.x = BLUE_X; g_Blocks[index].bitmap_location.y = BLUE_Y; } break; } // For future use, keep track of how many blocks we have. // g_NumBlocks++; index++; // move to next block } } fclose(inFile); } // This function shuts down our game. // void Shutdown() { // Shutdown the true type font library. // TTF_Quit(); // Free our surfaces. // SDL_FreeSurface(g_Bitmap); SDL_FreeSurface(g_Window); // Tell SDL to shutdown and free any resources it was using. // SDL_Quit(); } // This function handles the game's main menu. From here // // the player can select to enter the game, or quit. // void Menu() { // Here we compare the difference between the current time and the last time we // // handled a frame. If FRAME_RATE amount of time has, it's time for a new frame. // if ( (SDL_GetTicks() - g_Timer) >= FRAME_RATE ) { HandleMenuInput(); // Make sure nothing from the last frame is still drawn. // ClearScreen(); DisplayText("Start (G)ame", 350, 250, 12, 255, 255, 255, 0, 0, 0); DisplayText("(Q)uit Game", 350, 270, 12, 255, 255, 255, 0, 0, 0); // Tell SDL to display our backbuffer. The four 0's will make // // SDL display the whole screen. // SDL_UpdateRect(g_Window, 0, 0, 0, 0); // We've processed a frame so we now need to record the time at which we did it. // // This way we can compare this time the next time our function gets called and // // see if enough time has passed between iterations. // g_Timer = SDL_GetTicks(); } } // This function handles the main game. We'll control the // // drawing of the game as well as any necessary game logic. // void Game() { // Here we compare the difference between the current time and the last time we // // handled a frame. If FRAME_RATE amount of time has, it's time for a new frame. // if ( (SDL_GetTicks() - g_Timer) >= FRAME_RATE ) { HandleGameInput(); HandleBall(); // Make sure nothing from the last frame is still drawn. // ClearScreen(); // Draw the paddle and the ball // SDL_BlitSurface(g_Bitmap, &g_Player.bitmap_location, g_Window, &g_Player.screen_location); SDL_BlitSurface(g_Bitmap, &g_Ball.bitmap_location, g_Window, &g_Ball.screen_location); // Iterate through the blocks array, drawing each block // for (int i=0; i < NUM_ROWS * NUM_COLS; i++) { if (g_Blocks[i].num_hits > 0) SDL_BlitSurface(g_Bitmap, &g_Blocks[i].bitmap_location, g_Window, &g_Blocks[i].screen_location); } // Output the number of lives the player has left and the current level // char buffer[256]; sprintf(buffer, "Lives: %d", g_Lives); DisplayText(buffer, LIVES_X, LIVES_Y, 12, 66, 239, 16, 0, 0, 0); sprintf(buffer, "Level: %d", g_Level); DisplayText(buffer, LEVEL_X, LEVEL_Y, 12, 66, 239, 16, 0, 0, 0); // Tell SDL to display our backbuffer. The four 0's will make // // SDL display the whole screen. // SDL_UpdateRect(g_Window, 0, 0, 0, 0); // We've processed a frame so we now need to record the time at which we did it. // // This way we can compare this time the next time our function gets called and // // see if enough time has passed between iterations. // g_Timer = SDL_GetTicks(); } } // This function handles the game's exit screen. It will display // // a message asking if the player really wants to quit. // void Exit() { // Here we compare the difference between the current time and the last time we // // handled a frame. If FRAME_RATE amount of time has, it's time for a new frame. // if ( (SDL_GetTicks() - g_Timer) >= FRAME_RATE ) { HandleExitInput(); // Make sure nothing from the last frame is still drawn. // ClearScreen(); DisplayText("Quit Game (Y or N)?", 350, 260, 12, 255, 255, 255, 0, 0, 0); // Tell SDL to display our backbuffer. The four 0's will make // // SDL display the whole screen. // SDL_UpdateRect(g_Window, 0, 0, 0, 0); // We've processed a frame so we now need to record the time at which we did it. // // This way we can compare this time the next time our function gets called and // // see if enough time has passed between iterations. // g_Timer = SDL_GetTicks(); } } // Display a victory message. // void GameWon() { if ( (SDL_GetTicks() - g_Timer) >= FRAME_RATE ) { HandleWinLoseInput(); ClearScreen(); DisplayText("You Win!!!", 350, 250, 12, 255, 255, 255, 0, 0, 0); DisplayText("Quit Game (Y or N)?", 350, 270, 12, 255, 255, 255, 0, 0, 0); SDL_UpdateRect(g_Window, 0, 0, 0, 0); g_Timer = SDL_GetTicks(); } } // Display a game over message. // void GameLost() { if ( (SDL_GetTicks() - g_Timer) >= FRAME_RATE ) { HandleWinLoseInput(); ClearScreen(); DisplayText("You Lose.", 350, 250, 12, 255, 255, 255, 0, 0, 0); DisplayText("Quit Game (Y or N)?", 350, 270, 12, 255, 255, 255, 0, 0, 0); SDL_UpdateRect(g_Window, 0, 0, 0, 0); g_Timer = SDL_GetTicks(); } } // This function simply clears the back buffer to black. // void ClearScreen() { // This function just fills a surface with a given color. The // // first 0 tells SDL to fill the whole surface. The second 0 // // is for black. // SDL_FillRect(g_Window, 0, 0); } // This function displays text to the screen. It takes the text // // to be displayed, the location to display it, the size of the // // text, and the color of the text and background. // void DisplayText(const char* text, int x, int y, int size, int fR, int fG, int fB, int bR, int bG, int bB) { // Open our font and set its size to the given parameter. // TTF_Font* font = TTF_OpenFont("arial.ttf", size); SDL_Color foreground = { fR, fG, fB}; // Text color. // SDL_Color background = { bR, bG, bB }; // Color of what's behind the text. // // This renders our text to a temporary surface. There // // are other text functions, but this one looks nice. // SDL_Surface* temp = TTF_RenderText_Shaded(font, text, foreground, background); // A structure storing the destination of our text. // SDL_Rect destination = { x, y, 0, 0 }; // Blit the text surface to our window surface. // SDL_BlitSurface(temp, NULL, g_Window, &destination); // Always free memory! // SDL_FreeSurface(temp); // Close the font. // TTF_CloseFont(font); } // This function receives player input and // // handles it for the game's menu screen. // void HandleMenuInput() { // Fill our event structure with event information. // if ( SDL_PollEvent(&g_Event) ) { // Handle user manually closing game window // if (g_Event.type == SDL_QUIT) { // While state stack isn't empty, pop // while (!g_StateStack.empty()) { g_StateStack.pop(); } return; // game is over, exit the function } // Handle keyboard input here // if (g_Event.type == SDL_KEYDOWN) { if (g_Event.key.keysym.sym == SDLK_ESCAPE) { g_StateStack.pop(); return; // this state is done, exit the function } // Quit // if (g_Event.key.keysym.sym == SDLK_q) { g_StateStack.pop(); return; // game is over, exit the function } // Start Game // if (g_Event.key.keysym.sym == SDLK_g) { StateStruct temp; temp.StatePointer = Game; g_StateStack.push(temp); return; // this state is done, exit the function } } } } // This function receives player input and // // handles it for the main game state. // void HandleGameInput() { static bool left_pressed = false; static bool right_pressed = false; // Fill our event structure with event information. // if ( SDL_PollEvent(&g_Event) ) { // Handle user manually closing game window // if (g_Event.type == SDL_QUIT) { // While state stack isn't empty, pop // while (!g_StateStack.empty()) { g_StateStack.pop(); } return; // game is over, exit the function } // Handle keyboard input here // if (g_Event.type == SDL_KEYDOWN) { if (g_Event.key.keysym.sym == SDLK_ESCAPE) { g_StateStack.pop(); return; // this state is done, exit the function } if (g_Event.key.keysym.sym == SDLK_SPACE) { // Player can hit 'space' to make the ball move at start // if (g_Ball.y_speed == 0) g_Ball.y_speed = BALL_SPEED_Y; } if (g_Event.key.keysym.sym == SDLK_LEFT) { left_pressed = true; } if (g_Event.key.keysym.sym == SDLK_RIGHT) { right_pressed = true; } } if (g_Event.type == SDL_KEYUP) { if (g_Event.key.keysym.sym == SDLK_LEFT) { left_pressed = false; } if (g_Event.key.keysym.sym == SDLK_RIGHT) { right_pressed = false; } } } // This is where we actually move the paddle // if (left_pressed) { // Notice that we do this here now instead of in a separate function // if ( (g_Player.screen_location.x - PLAYER_SPEED) >= 0 ) { g_Player.screen_location.x -= PLAYER_SPEED; } } if (right_pressed) { if ( (g_Player.screen_location.x + PLAYER_SPEED) <= WINDOW_WIDTH ) { g_Player.screen_location.x += PLAYER_SPEED; } } } // This function receives player input and // // handles it for the game's exit screen. // void HandleExitInput() { // Fill our event structure with event information. // if ( SDL_PollEvent(&g_Event) ) { // Handle user manually closing game window // if (g_Event.type == SDL_QUIT) { // While state stack isn't empty, pop // while (!g_StateStack.empty()) { g_StateStack.pop(); } return; // game is over, exit the function } // Handle keyboard input here // if (g_Event.type == SDL_KEYDOWN) { if (g_Event.key.keysym.sym == SDLK_ESCAPE) { g_StateStack.pop(); return; // this state is done, exit the function } // Yes // if (g_Event.key.keysym.sym == SDLK_y) { g_StateStack.pop(); return; // game is over, exit the function } // No // if (g_Event.key.keysym.sym == SDLK_n) { StateStruct temp; temp.StatePointer = Menu; g_StateStack.push(temp); return; // this state is done, exit the function } } } } // Input handling for win/lose screens. // void HandleWinLoseInput() { if ( SDL_PollEvent(&g_Event) ) { // Handle user manually closing game window // if (g_Event.type == SDL_QUIT) { // While state stack isn't empty, pop // while (!g_StateStack.empty()) { g_StateStack.pop(); } return; } // Handle keyboard input here // if (g_Event.type == SDL_KEYDOWN) { if (g_Event.key.keysym.sym == SDLK_ESCAPE) { g_StateStack.pop(); return; } if (g_Event.key.keysym.sym == SDLK_y) { g_StateStack.pop(); return; } // If player chooses to continue playing, we pop off // // current state and push exit and menu states back on. // if (g_Event.key.keysym.sym == SDLK_n) { g_StateStack.pop(); StateStruct temp; temp.StatePointer = Exit; g_StateStack.push(temp); temp.StatePointer = Menu; g_StateStack.push(temp); return; } } } } // Check to see if the ball is going to hit the paddle // bool CheckBallCollisions() { // Temporary values to keep things tidy // int ball_x = g_Ball.screen_location.x; int ball_y = g_Ball.screen_location.y; int ball_width = g_Ball.screen_location.w; int ball_height = g_Ball.screen_location.h; int ball_speed = g_Ball.y_speed; int paddle_x = g_Player.screen_location.x; int paddle_y = g_Player.screen_location.y; int paddle_width = g_Player.screen_location.w; int paddle_height = g_Player.screen_location.h; // Check to see if ball is in Y range of the player's paddle. // // We check its speed to see if it's even moving towards the player's paddle. // if ( (ball_speed > 0) && (ball_y + ball_height >= paddle_y) && (ball_y + ball_height <= paddle_y + paddle_height) ) // side hit { // If ball is in the X range of the paddle, return true. // if ( (ball_x <= paddle_x + paddle_width) && (ball_x + ball_width >= paddle_x) ) { return true; } } return false; } // This function checks to see if the ball has hit one of the blocks. It also checks // // what part of the ball hit the block so we can adjust the ball's speed acoordingly. // void CheckBlockCollisions() { // collision points int left_x = g_Ball.screen_location.x; int left_y = g_Ball.screen_location.y + g_Ball.screen_location.h/2; int right_x = g_Ball.screen_location.x + g_Ball.screen_location.w; int right_y = g_Ball.screen_location.y + g_Ball.screen_location.h/2; int top_x = g_Ball.screen_location.x + g_Ball.screen_location.w/2; int top_y = g_Ball.screen_location.y; int bottom_x = g_Ball.screen_location.x + g_Ball.screen_location.w/2; int bottom_y = g_Ball.screen_location.y + g_Ball.screen_location.h; bool top = false; bool bottom = false; bool left = false; bool right = false; int left_col = (left_x - BLOCK_WIDTH + BLOCK_SCREEN_BUFFER) / BLOCK_WIDTH; int right_col = (right_x - BLOCK_WIDTH + BLOCK_SCREEN_BUFFER) / BLOCK_WIDTH; if (left_col < 0) left_col = 0; if (right_col >= NUM_COLS) right_col = NUM_COLS - 1; int top_row = (top_y - BLOCK_WIDTH - BLOCK_SCREEN_BUFFER) / BLOCK_HEIGHT; int bottom_row = (bottom_x - BLOCK_WIDTH - BLOCK_SCREEN_BUFFER) / BLOCK_HEIGHT; if (top_row < 0) top_row = 0; if (bottom_row >= NUM_ROWS) bottom_row = NUM_ROWS - 1; for (int row = top_row; row <= bottom_row; ++row) { for (int col = left_col; col <= right_col; ++col) { int block = col + row * NUM_COLS; if (g_Blocks[block].num_hits == 0) continue; // top // if ( CheckPointInRect(top_x, top_y, g_Blocks[block].screen_location) ) { top = true; HandleBlockCollision(block); } // bottom // if ( CheckPointInRect(bottom_x, bottom_y, g_Blocks[block].screen_location) ) { bottom = true; HandleBlockCollision(block); } // left // if ( CheckPointInRect(left_x, left_y, g_Blocks[block].screen_location) ) { left = true; HandleBlockCollision(block); } // right // if ( CheckPointInRect(right_x, right_y, g_Blocks[block].screen_location) ) { right = true; HandleBlockCollision(block); } } } if (top) { g_Ball.y_speed = -g_Ball.y_speed; g_Ball.screen_location.y += BALL_DIAMETER; } if (bottom) { g_Ball.y_speed = -g_Ball.y_speed; g_Ball.screen_location.y -= BALL_DIAMETER; } if (left) { g_Ball.x_speed = -g_Ball.x_speed; g_Ball.screen_location.x += BALL_DIAMETER; } if (right) { g_Ball.x_speed = -g_Ball.x_speed; g_Ball.screen_location.x -= BALL_DIAMETER; } } // This function changes the block's hit count. We also need it to change // // the color of the block and check to see if the hit count reached zero. // void HandleBlockCollision(int index) { if (g_Blocks[index].num_hits == 0) return; g_Blocks[index].num_hits--; // If num_hits is 0, the block needs to be erased // if (g_Blocks[index].num_hits == 0) { g_NumBlocks--; // Check to see if it's time to change the level // if (g_NumBlocks == 0) { ChangeLevel(); } } // If the hit count hasn't reached zero, we need to change the block's color // else { switch (g_Blocks[index].num_hits) { case 1: { g_Blocks[index].bitmap_location.x = RED_X; g_Blocks[index].bitmap_location.y = RED_Y; } break; case 2: { g_Blocks[index].bitmap_location.x = YELLOW_X; g_Blocks[index].bitmap_location.y = YELLOW_Y; } break; case 3: { g_Blocks[index].bitmap_location.x = GREEN_X; g_Blocks[index].bitmap_location.y = GREEN_Y; } break; } } } // Check to see if a point is within a rectangle // bool CheckPointInRect(int x, int y, SDL_Rect rect) { if ( (x >= rect.x) && (x <= rect.x + rect.w) && (y >= rect.y) && (y <= rect.y + rect.h) ) { return true; } return false; } void ChangeLevel() { g_Level++; // Check to see if the player has won // if (g_Level > NUM_LEVELS) { HandleWin(); return; } // Reset the ball // g_Ball.x_speed = 0; g_Ball.y_speed = 0; g_Ball.screen_location.x = WINDOW_WIDTH/2 - g_Ball.screen_location.w/2; g_Ball.screen_location.y = WINDOW_HEIGHT/2 - g_Ball.screen_location.h/2; g_NumBlocks = 0; // Set this to zero before calling InitBlocks() InitBlocks(); // InitBlocks() will load the proper level } void HandleBall() { // Start by moving the ball // MoveBall(); if ( CheckBallCollisions() ) { // Get center location of paddle // int paddle_center = g_Player.screen_location.x + g_Player.screen_location.w / 2; int ball_center = g_Ball.screen_location.x + g_Ball.screen_location.w / 2; // Find the location on the paddle that the ball hit // int paddle_location = ball_center - paddle_center; // Increase X speed according to distance from center of paddle. // // Use bit shifting, multiplication, and pre-compile division to avoid // runtime division, which can be expensive on embedded systems. g_Ball.x_speed = (paddle_location * ((1 << BALL_SPEED_MODIFIER_SHIFT) / BALL_SPEED_MODIFIER)) >> BALL_SPEED_MODIFIER_SHIFT; g_Ball.y_speed = -g_Ball.y_speed; } // Check for collisions with blocks // CheckBlockCollisions(); } void MoveBall() { g_Ball.screen_location.x += g_Ball.x_speed; g_Ball.screen_location.y += g_Ball.y_speed; // If the ball is moving left, we see if it hits the wall. If does, // // we change its direction. We do the same thing if it's moving right. // if ( ( (g_Ball.x_speed < 0) && (g_Ball.screen_location.x <= 0) ) || ( (g_Ball.x_speed > 0) && (g_Ball.screen_location.x + g_Ball.screen_location.w >= WINDOW_WIDTH) ) ) { g_Ball.x_speed = -g_Ball.x_speed; } // If the ball is moving up, we should check to see if it hits the 'roof' // if ( (g_Ball.y_speed < 0) && (g_Ball.screen_location.y <= 0) ) { g_Ball.y_speed = -g_Ball.y_speed; } // Check to see if ball has passed the player // if ( g_Ball.screen_location.y >= WINDOW_HEIGHT ) { g_Lives--; g_Ball.x_speed = 0; g_Ball.y_speed = 0; g_Ball.screen_location.x = WINDOW_WIDTH/2 - g_Ball.screen_location.w/2; g_Ball.screen_location.y = WINDOW_HEIGHT/2 - g_Ball.screen_location.h/2; if (g_Lives == 0) { HandleLoss(); } } } void HandleLoss() { while ( !g_StateStack.empty() ) { g_StateStack.pop(); } g_Ball.x_speed = 0; g_Ball.y_speed = 0; g_Ball.screen_location.x = WINDOW_WIDTH/2 - g_Ball.screen_location.w/2; g_Ball.screen_location.y = WINDOW_HEIGHT/2 - g_Ball.screen_location.h/2; g_Lives = NUM_LIVES; g_NumBlocks = 0; g_Level = 1; InitBlocks(); StateStruct temp; temp.StatePointer = GameLost; g_StateStack.push(temp); } void HandleWin() { while ( !g_StateStack.empty() ) { g_StateStack.pop(); } g_Ball.x_speed = 0; g_Ball.y_speed = 0; g_Ball.screen_location.x = WINDOW_WIDTH/2 - g_Ball.screen_location.w/2; g_Ball.screen_location.y = WINDOW_HEIGHT/2 - g_Ball.screen_location.h/2; g_Lives = NUM_LIVES; g_NumBlocks = 0; g_Level = 1; InitBlocks(); StateStruct temp; temp.StatePointer = GameWon; g_StateStack.push(temp); } // Aaron Cox, 2004 //
be930021687964a9113532baa00bb32c2677ce26
c40b21b737c8906d104d6e1a63904884b8ec345d
/Operator/UTOP_Otp/Otp/SonyOtp.h
df2624611fb66d46c2b718239c03aab75379252b
[]
no_license
liupengsyk/UTS_NEW
f4eac1f327126eda4dd0bfaae0a1372a77263175
0fa04109a0f0808dd973a6f86cc0133f068ea02d
refs/heads/master
2020-06-03T02:30:18.394317
2019-01-30T02:32:32
2019-01-30T02:32:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
276
h
SonyOtp.h
#pragma once #include "baseotp.h" class SonyOtp : public BaseOtp { public: SonyOtp(BaseDevice *dev); ~SonyOtp(void); protected: int get_wb_gain(WB_RATIO *ratio, WB_RATIO *ratio_target, WB_GAIN *gain); int get_wb_cali_data(WB_GAIN *gain, void *out); };
cead75c667c600acc968a947e5502d19f4c638ba
00213d6c03bc5310ad582043ca4632aee16c5726
/HandForests/src/OLD_SOURCE/open_ni_funcs.cpp
4efe22a39a2fb7a340912db3ec9db63426dd0392
[]
no_license
jonathantompson/KinectHands
ce0634c5c9d505877ad8cf83528bb5ec0809b354
03b5f9e4b00581d264fd7f67a2cb1582c8fa2b63
refs/heads/master
2021-03-16T10:05:12.403678
2015-01-15T22:41:56
2015-01-15T22:41:56
8,038,081
8
2
null
null
null
null
UTF-8
C++
false
false
3,319
cpp
open_ni_funcs.cpp
// // open_ni_dg.h // // Source origionally from OpenNI libraries, then modified by Otavio B. for // Computer Vision class code, then adapted by Ken Perlin's lab for KinectHands #include <cmath> #include <string> #include <iostream> #include "open_ni_funcs.h" using std::cout; using std::endl; #ifndef XN_STATUS_OK #define XN_STATUS_OK ((uint32_t)0) #endif namespace kinect { const double OpenNIFuncs::fHFOV = 1.0144686707507438; const double OpenNIFuncs::fVFOV = 0.78980943449644714; // FROM: XnOpenNI.cpp (and slightly edited) const double OpenNIFuncs::m_fRealWorldXtoZ = tan(OpenNIFuncs::fHFOV/2)*2; const double OpenNIFuncs::m_fRealWorldYtoZ = tan(OpenNIFuncs::fVFOV/2)*2; const uint32_t OpenNIFuncs::nXRes = 640; const uint32_t OpenNIFuncs::nYRes = 480; const uint32_t OpenNIFuncs::nFPS = 30; // FROM: XnOpenNI.cpp (and slightly edited) uint32_t OpenNIFuncs::xnConvertProjectiveToRealWorld(uint32_t nCount, const Vector3D* aProjective, Vector3D* aRealWorld) { uint32_t nRetVal = XN_STATUS_OK; /** * X_RW = (X_proj / X_res - 1/2) * Z * x_to_z */ double fXToZ = GetRealWorldXtoZ(); double fYToZ = GetRealWorldYtoZ(); for (uint32_t i = 0; i < nCount; ++i) { double fNormalizedX = (aProjective[i].X / nXRes - 0.5); aRealWorld[i].X = (float)(fNormalizedX * aProjective[i].Z * fXToZ); double fNormalizedY = (0.5 - aProjective[i].Y / nYRes); aRealWorld[i].Y = (float)(fNormalizedY * aProjective[i].Z * fYToZ); aRealWorld[i].Z = aProjective[i].Z; } return nRetVal; } // FROM: XnOpenNI.cpp (and slightly edited) uint32_t OpenNIFuncs::xnConvertRealWorldToProjective(uint32_t nCount, const Vector3D* aRealWorld, Vector3D* aProjective) { uint32_t nRetVal = XN_STATUS_OK; /** * X_proj = X_res * (X_RW / (z*x_to_z) + 1/2) * * = X_res / x_to_z * X_RW / z + X_res/2 (more efficient) */ double fXToZ = GetRealWorldXtoZ(); double fYToZ = GetRealWorldYtoZ(); double fCoeffX = nXRes / fXToZ; double fCoeffY = nYRes / fYToZ; // we can assume resolution is even (so integer div is sufficient) uint32_t nHalfXres = nXRes / 2; uint32_t nHalfYres = nYRes / 2; for (uint32_t i = 0; i < nCount; ++i) { aProjective[i].X = (float)fCoeffX * aRealWorld[i].X / aRealWorld[i].Z + nHalfXres; aProjective[i].Y = nHalfYres - (float)fCoeffY * aRealWorld[i].Y / aRealWorld[i].Z; aProjective[i].Z = aRealWorld[i].Z; } return nRetVal; } uint32_t OpenNIFuncs::ConvertDepthImageToProjective(const uint16_t* aDepth, Vector3D* aProjective) { int nIndex = 0; for (int nY = 0; nY < nYRes; nY += 1) { for (int nX = 0; nX < nXRes; nX += 1, nIndex += 1) { aProjective[nIndex].X = static_cast<float>(nX); aProjective[nIndex].Y = static_cast<float>(nY); aProjective[nIndex].Z = aDepth[nIndex]; } } return XN_STATUS_OK; } } // namespace kinect
b6b23fdb659fffbd1d8c750db3ee55367dae9f16
88ae8695987ada722184307301e221e1ba3cc2fa
/chrome/browser/ash/crosapi/copy_migrator.h
11266d61901eed80a4b9de27037ad3c01c33a5a0
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
4,533
h
copy_migrator.h
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ASH_CROSAPI_COPY_MIGRATOR_H_ #define CHROME_BROWSER_ASH_CROSAPI_COPY_MIGRATOR_H_ #include <memory> #include <string> #include "base/files/file_path.h" #include "base/gtest_prod_util.h" #include "base/memory/raw_ref.h" #include "base/memory/scoped_refptr.h" #include "chrome/browser/ash/crosapi/browser_data_migrator.h" #include "chrome/browser/ash/crosapi/browser_data_migrator_util.h" #include "chrome/browser/ash/crosapi/migration_progress_tracker.h" namespace ash { // The following are UMA names. constexpr char kFinalStatus[] = "Ash.BrowserDataMigrator.FinalStatus"; constexpr char kCopiedDataSize[] = "Ash.BrowserDataMigrator.CopiedDataSizeMB"; constexpr char kLacrosDataSize[] = "Ash.BrowserDataMigrator.LacrosDataSizeMB"; constexpr char kCommonDataSize[] = "Ash.BrowserDataMigrator.CommonDataSizeMB"; constexpr char kTotalTime[] = "Ash.BrowserDataMigrator.TotalTimeTakenMS"; constexpr char kLacrosDataTime[] = "Ash.BrowserDataMigrator.LacrosDataTimeTakenMS"; constexpr char kCommonDataTime[] = "Ash.BrowserDataMigrator.CommonDataTimeTakenMS"; constexpr char kCreateDirectoryFail[] = "Ash.BrowserDataMigrator.CreateDirectoryFailure"; constexpr char kTotalCopySizeWhenNotEnoughSpace[] = "Ash.BrowserDataMigrator.TotalCopySizeWhenNotEnoughSpace"; using MigrationFinishedCallback = base::OnceCallback<void(BrowserDataMigratorImpl::MigrationResult)>; class CopyMigrator : public BrowserDataMigratorImpl::MigratorDelegate { public: // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. // // This enum corresponds to BrowserDataMigratorFinalStatus in hisograms.xml // and enums.xml. enum class FinalStatus { kSkipped = 0, // No longer in use. kSuccess = 1, kGetPathFailed = 2, kDeleteTmpDirFailed = 3, kNotEnoughSpace = 4, kCopyFailed = 5, kMoveFailed = 6, kDataWipeFailed = 7, kSizeLimitExceeded = 8, // No longer in use. kCancelled = 9, kMaxValue = kCancelled }; CopyMigrator( const base::FilePath& original_profile_dir, const std::string& user_id_hash, std::unique_ptr<MigrationProgressTracker> progress_tracker, scoped_refptr<browser_data_migrator_util::CancelFlag> cancel_flag, MigrationFinishedCallback finished_callback); CopyMigrator(const CopyMigrator&) = delete; CopyMigrator& operator=(const CopyMigrator&) = delete; ~CopyMigrator() override; // BrowserDataMigratorImpl::MigratorDelegate override. void Migrate() override; private: FRIEND_TEST_ALL_PREFIXES(CopyMigratorTest, SetupTmpDir); FRIEND_TEST_ALL_PREFIXES(CopyMigratorTest, CancelSetupTmpDir); FRIEND_TEST_ALL_PREFIXES(CopyMigratorTest, MigrateInternal); FRIEND_TEST_ALL_PREFIXES(CopyMigratorTest, MigrateInternalOutOfDisk); // Handles the migration on a worker thread. Returns the end status of data // wipe and migration. `progress_callback` gets posted on UI thread whenever // an update to the UI is required static BrowserDataMigratorImpl::MigrationResult MigrateInternal( const base::FilePath& original_profile_dir, std::unique_ptr<MigrationProgressTracker> progress_tracker, scoped_refptr<browser_data_migrator_util::CancelFlag> cancel_flag); // Set up the temporary directory `tmp_dir` by copying items into it. static bool SetupTmpDir( const browser_data_migrator_util::TargetItems& lacros_items, const browser_data_migrator_util::TargetItems& need_copy_items, const base::FilePath& tmp_dir, browser_data_migrator_util::CancelFlag* cancel_flag, MigrationProgressTracker* progress_tracker); // Path to the original profile data directory, which is directly under the // user data directory. const raw_ref<const base::FilePath, ExperimentalAsh> original_profile_dir_; // A hash string of the profile user ID. const std::string user_id_hash_; std::unique_ptr<MigrationProgressTracker> progress_tracker_; // `cancel_flag_` gets set by `Cancel()` and tasks posted to worker threads // can check if migration is cancelled or not. scoped_refptr<browser_data_migrator_util::CancelFlag> cancel_flag_; // `finished_callback_` should be called once migration is completed/failed. MigrationFinishedCallback finished_callback_; }; } // namespace ash #endif // CHROME_BROWSER_ASH_CROSAPI_COPY_MIGRATOR_H_
895c5b9ab62aa3d50a0d163a2f69c9378add17a3
fedd7aa847b6e6cf5421156dec9a3089405dd7d6
/src/structures/graph.cpp
05303c61e6ce2265d32610b59475edd23e77068e
[ "MIT" ]
permissive
Ezibenroc/satsolver
e47622bdd0f03420190ce5d0bc2af62738a219d8
5f58b8f9502090f05cbc2351304a289530b74f63
refs/heads/master
2016-09-05T13:45:16.929200
2015-03-09T18:52:58
2015-03-09T18:52:58
24,460,807
1
0
null
null
null
null
UTF-8
C++
false
false
2,337
cpp
graph.cpp
#include <cassert> #include <cstdlib> #include <cstring> #include "structures/graph.h" using namespace graphsolver; Graph::Graph(int nodes_count, int default_value) : nodes_count(nodes_count), values(static_cast<int*>(malloc(sizeof(int)*nodes_count))), adjacency(static_cast<std::set<int>**>(malloc(sizeof(std::set<int>*)*nodes_count))) { int i; memset(values, default_value, nodes_count); for (i=0; i<nodes_count; i++) { this->adjacency[i] = new std::set<int>(); } } graphsolver::Graph::Graph(const graphsolver::Graph &that) : nodes_count(that.nodes_count), values(static_cast<int*>(malloc(sizeof(int)*nodes_count))), adjacency(static_cast<std::set<int>**>(malloc(sizeof(std::set<int>*)*nodes_count))) { int i; memcpy(values, that.values, nodes_count); for (i=0; i<nodes_count; i++) { this->adjacency[i] = new std::set<int>(*that.adjacency[i]); } } graphsolver::Graph& graphsolver::Graph::operator=(const graphsolver::Graph &that) { int i; free(this->values); for (i=0; i<this->nodes_count; i++) { delete this->adjacency[i]; } free(this->adjacency); this->nodes_count = that.nodes_count; values = static_cast<int*>(malloc(sizeof(int)*that.nodes_count)); adjacency = static_cast<std::set<int>**>(malloc(sizeof(std::set<int>*)*nodes_count)); memcpy(values, that.values, nodes_count); for (i=0; i<nodes_count; i++) { this->adjacency[i] = new std::set<int>(*that.adjacency[i]); } return *this; } Graph::~Graph() { int i; free(this->values); for (i=0; i<this->nodes_count; i++) { delete this->adjacency[i]; } free(this->adjacency); } void Graph::set_value(int node_id, int value) { assert(node_id > 0); assert(node_id <= this->nodes_count); this->values[node_id-1] = value; } void Graph::add_edge(int first, int second) { assert(first < this->nodes_count); assert(second < this->nodes_count); assert(first != second); if (first > second) this->adjacency[first]->insert(second); else this->adjacency[second]->insert(first); } int Graph::get_nodes_count() const { return this->nodes_count; } std::set<int>* Graph::get_lower_adjacent_nodes(int node_id) const { assert(node_id < this->nodes_count); return this->adjacency[node_id]; }
f6ffd93f83f14e51315d84c7377cf934e7f71574
1f515c64253d340a22436628623d68fd13ec3513
/blingfirecompile.library/inc/FAPrmInterpreter_t.h
ada01fe6de3163b11c5158fd9542d53594c7b649
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
microsoft/BlingFire
92467240018cdbed9a3288b7f8d33f04bc9b28c5
5dad17aa31dd87c9992d9570ab0dd20e84246fa6
refs/heads/master
2023-08-20T23:43:13.448077
2023-06-27T13:00:11
2023-06-27T13:00:11
175,482,543
574
81
MIT
2023-06-27T13:00:13
2019-03-13T19:04:41
C++
UTF-8
C++
false
false
24,062
h
FAPrmInterpreter_t.h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_PRMINTERPRETER_T_H_ #define _FA_PRMINTERPRETER_T_H_ #include "FAConfig.h" #include "FAFsmConst.h" #include "FALimits.h" #include "FAMorphLDB_t_packaged.h" #include "FAWordGuesser_t.h" #include "FASuffixInterpretTools_t.h" #include "FASegmentationTools_bf_t.h" #include "FANfstLookupTools_t.h" #include "FAUtf32Utils.h" #include "FAUtils_cl.h" #include "FASecurity.h" namespace BlingFire { /// /// PRM run-time interpreter. /// template < class Ty > class FAPrmInterpreter_t { public: /// creates uninitialized object FAPrmInterpreter_t (FAAllocatorA * pAlloc); ~FAPrmInterpreter_t (); public: void SetLDB (const FAMorphLDB_t < Ty > * pLDB); public: /// word -> { word-tag } const int ProcessW2T ( const Ty * pIn, const int InSize, const int ** ppTags ); /// base -> { word-tag } const int ProcessB2T ( const Ty * pIn, const int InSize, const int ** ppTags ); /// word -> { E1, ..., En } /// the output is a set of ending positions of segments const int ProcessW2S ( const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) int * pOut, const int MaxOutSize ); /// word -> { base_form }, word can be on of the base_form too /// returns -1 if no transformation exist const int ProcessW2B ( const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ); /// base_form -> { word }, { word } includes base_form too /// returns -1 if no transformation exist const int ProcessB2W ( const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ); /// word -> { word }, word can be on of the base_form too /// returns -1 if no transformation exist const int ProcessW2W ( const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ); /// word, from_tag -> { base } /// returns -1 if no transformation exist const int ProcessWT2B ( const Ty * pIn, const int InSize, const int FromTag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ); /// base, to_tag -> { word } /// returns -1 if no transformation exist const int ProcessB2WT ( const Ty * pIn, const int InSize, const int ToTag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ); /// word, from_tag, to_tag -> { word } /// returns -1 if no transformation exist const int ProcessWTT2W ( const Ty * pIn, const int InSize, const int FromTag, const int ToTag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ); private: // returns object into initial state inline void Clear (); // makes initialization and takes care of m_Ready_w2t flag inline void InitW2T (); // makes initialization and takes care of m_Ready_b2t flag inline void InitB2T (); // makes initialization and takes care of m_Ready_w2s flag inline void InitW2S (); // makes initialization and takes care of m_Ready_w2b flag inline void InitW2B (); // makes initialization and takes care of m_Ready_b2w flag inline void InitB2W (); // makes initialization and takes care of m_Ready_w2w flag inline void InitW2W (); // makes initialization and takes care of m_Ready_wt2b flag inline void InitWT2B (); // makes initialization and takes care of m_Ready_b2wt flag inline void InitB2WT (); // makes initialization and takes care of m_Ready_wtt2w flag inline void InitWTT2W (); private: // keeps morphology resources const FAMorphLDB_t < Ty > * m_pLDB; FAAllocatorA * m_pAlloc; // true if object was initialized bool m_Ready_w2t; bool m_Ready_b2t; bool m_Ready_w2s; bool m_Ready_w2b; bool m_Ready_b2w; bool m_Ready_w2w; bool m_Ready_wt2b; bool m_Ready_b2wt; bool m_Ready_wtt2w; // word-guesser interpreter FAWordGuesser_t < Ty > * m_pW2T; FAWordGuesser_t < Ty > * m_pB2T; // detection of word segments FASegmentationTools_bf_t < Ty > * m_pW2S; // word -> base suffix rules interpreter FASuffixInterpretTools_t < Ty > * m_pSuffW2B; // base -> word suffix rules interpreter FASuffixInterpretTools_t < Ty > * m_pSuffB2W; // word, tag -> base suffix rules interpreter FASuffixInterpretTools_t < Ty > * m_pSuffWT2B; // base, tag -> word suffix rules interpreter FASuffixInterpretTools_t < Ty > * m_pSuffB2WT; // word -> base NFST FANfstLookupTools_t < Ty > * m_pNfstW2B; // base -> word NFST FANfstLookupTools_t < Ty > * m_pNfstB2W; // buffer of temporary intermediate base forms, needed by w2w function enum { DefBaseListSize = FALimits::MaxWordLen * 5 }; FAArray_cont_t < Ty > m_base_list; Ty * m_pBaseList; int m_MaxBaseListSize; }; template < class Ty > FAPrmInterpreter_t< Ty >::FAPrmInterpreter_t (FAAllocatorA * pAlloc) : m_pLDB (NULL), m_pAlloc (pAlloc), m_Ready_w2t (false), m_Ready_b2t (false), m_Ready_w2s (false), m_Ready_w2b (false), m_Ready_b2w (false), m_Ready_w2w (false), m_Ready_wt2b (false), m_Ready_b2wt (false), m_Ready_wtt2w (false), m_pW2T (NULL), m_pB2T (NULL), m_pW2S (NULL), m_pSuffW2B (NULL), m_pSuffB2W (NULL), m_pSuffWT2B (NULL), m_pSuffB2WT (NULL), m_pNfstW2B (NULL), m_pNfstB2W (NULL), m_pBaseList (NULL), m_MaxBaseListSize (0) { m_base_list.SetAllocator (pAlloc); m_base_list.Create (DefBaseListSize); m_base_list.resize (DefBaseListSize); m_pBaseList = m_base_list.begin (); m_MaxBaseListSize = DefBaseListSize; } template < class Ty > FAPrmInterpreter_t< Ty >::~FAPrmInterpreter_t () { FAPrmInterpreter_t< Ty >::Clear (); } template < class Ty > void FAPrmInterpreter_t< Ty >::SetLDB (const FAMorphLDB_t < Ty > * pLDB) { m_pLDB = pLDB; m_Ready_w2t = false; m_Ready_b2t = false; m_Ready_w2s = false; m_Ready_w2b = false; m_Ready_b2w = false; m_Ready_w2w = false; m_Ready_wt2b = false; m_Ready_b2wt = false; m_Ready_wtt2w = false; } template < class Ty > void FAPrmInterpreter_t< Ty >::Clear () { m_Ready_w2t = false; m_Ready_b2t = false; m_Ready_w2s = false; m_Ready_w2b = false; m_Ready_b2w = false; m_Ready_w2w = false; m_Ready_wt2b = false; m_Ready_b2wt = false; m_Ready_wtt2w = false; if (m_pW2T) { delete m_pW2T; m_pW2T = NULL; } if (m_pB2T) { delete m_pB2T; m_pB2T = NULL; } if (m_pW2S) { delete m_pW2S; m_pW2S = NULL; } if (m_pSuffW2B) { delete m_pSuffW2B; m_pSuffW2B = NULL; } if (m_pSuffB2W) { delete m_pSuffB2W; m_pSuffB2W = NULL; } if (m_pSuffWT2B) { delete m_pSuffWT2B; m_pSuffWT2B = NULL; } if (m_pSuffB2WT) { delete m_pSuffB2WT; m_pSuffB2WT = NULL; } if (m_pNfstW2B) { delete m_pNfstW2B; m_pNfstW2B = NULL; } if (m_pNfstB2W) { delete m_pNfstB2W; m_pNfstB2W = NULL; } } template < class Ty > void FAPrmInterpreter_t< Ty >::InitW2T () { DebugLogAssert (!m_Ready_w2t); if (!m_pLDB) { return; } if (!m_pW2T) { m_pW2T = NEW FAWordGuesser_t < Ty > (); LogAssert (m_pW2T); } const FAWgConfKeeper * pConf = m_pLDB->GetW2TConf (); // may be NULL const FATransformCA_t < Ty > * pInTr = m_pLDB->GetInTr (); // may be NULL m_pW2T->Initialize (pConf, pInTr); m_Ready_w2t = pConf && pConf->GetRsDfa () && pConf->GetState2Ows (); } template < class Ty > const int FAPrmInterpreter_t< Ty >:: ProcessW2T ( const Ty * pIn, const int InSize, const int ** ppTags ) { if (!m_Ready_w2t) { InitW2T (); if (!m_Ready_w2t) return -1; } // check for limits if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn) { return -1; } DebugLogAssert (m_pW2T); const int TagCount = m_pW2T->Process (pIn, InSize, ppTags); return TagCount; } template < class Ty > void FAPrmInterpreter_t< Ty >::InitB2T () { DebugLogAssert (!m_Ready_b2t); if (!m_pLDB) { return; } if (!m_pB2T) { m_pB2T = NEW FAWordGuesser_t < Ty > (); LogAssert (m_pB2T); } const FAWgConfKeeper * pConf = m_pLDB->GetB2TConf (); // may be NULL const FATransformCA_t < Ty > * pInTr = m_pLDB->GetInTr (); // may be NULL m_pB2T->Initialize (pConf, pInTr); m_Ready_b2t = pConf && pConf->GetRsDfa () && pConf->GetState2Ows (); } template < class Ty > const int FAPrmInterpreter_t< Ty >:: ProcessB2T ( const Ty * pIn, const int InSize, const int ** ppTags ) { if (!m_Ready_b2t) { InitB2T (); if (!m_Ready_b2t) return -1; } // check for limits if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn) return -1; DebugLogAssert (m_pB2T); const int TagCount = m_pB2T->Process (pIn, InSize, ppTags); return TagCount; } template < class Ty > void FAPrmInterpreter_t< Ty >::InitW2S () { DebugLogAssert (!m_Ready_w2s); if (!m_pLDB) { return; } const FAW2SConfKeeper * pConf = m_pLDB->GetW2SConf (); if (!pConf) { return; } const FARSDfaCA * pDfa = pConf->GetRsDfa (); const FAState2OwCA * pState2Ow = pConf->GetState2Ow (); // check whether there were enough parameters specified for operation if (pDfa && pState2Ow) { if (!m_pW2S) { m_pW2S = NEW FASegmentationTools_bf_t < Ty > (); LogAssert (m_pW2S); } m_pW2S->SetConf (pConf); m_Ready_w2s = true; } } template < class Ty > const int FAPrmInterpreter_t< Ty >:: ProcessW2S ( const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) int * pOut, const int MaxOutSize ) { if (!m_Ready_w2s) { InitW2S (); if (!m_Ready_w2s) return -1; } // check for limits if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn || \ (NULL == pOut && 0 != MaxOutSize)) return -1; DebugLogAssert (m_pW2S); const int SegCount = m_pW2S->Process (pIn, InSize, pOut, MaxOutSize); return SegCount; } template < class Ty > void FAPrmInterpreter_t< Ty >::InitW2B () { DebugLogAssert (!m_Ready_w2b); if (!m_pLDB) { return; } const FAWftConfKeeper * pConf = m_pLDB->GetW2BConf (); if (!pConf) { return; } const bool NoTrUse = pConf->GetNoTrUse (); const bool UseNfst = pConf->GetUseNfst (); if (UseNfst) { if (!m_pNfstW2B) { m_pNfstW2B = NEW FANfstLookupTools_t < Ty > (m_pAlloc); LogAssert (m_pNfstW2B); } if (false == NoTrUse) { m_pNfstW2B->SetInTr (m_pLDB->GetInTr ()); m_pNfstW2B->SetOutTr (m_pLDB->GetOutTr ()); } m_pNfstW2B->SetConf (pConf); m_Ready_w2b = pConf->GetRsDfa () && pConf->GetIws () && \ pConf->GetActs (); } else { if (!m_pSuffW2B) { m_pSuffW2B = NEW FASuffixInterpretTools_t < Ty > (); LogAssert (m_pSuffW2B); } if (false == NoTrUse) { m_pSuffW2B->SetInTr (m_pLDB->GetInTr ()); m_pSuffW2B->SetOutTr (m_pLDB->GetOutTr ()); } m_pSuffW2B->SetConf (pConf); m_Ready_w2b = pConf->GetRsDfa () && pConf->GetState2Ows () && \ pConf->GetActs (); } } template < class Ty > const int FAPrmInterpreter_t< Ty >:: ProcessW2B ( const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) { if (!m_Ready_w2b) { InitW2B (); if (!m_Ready_w2b) return -1; } // of if (!m_Ready_w2b) ... // check for limits if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn || \ (NULL == pOut && 0 != MaxOutSize)) return -1; int OutSize = -1; if (m_pSuffW2B) { OutSize = m_pSuffW2B->Process (pIn, InSize, pOut, MaxOutSize); } else { DebugLogAssert (m_pNfstW2B); OutSize = m_pNfstW2B->Process (pIn, InSize, pOut, MaxOutSize); } return OutSize; } template < class Ty > void FAPrmInterpreter_t< Ty >::InitB2W () { DebugLogAssert (!m_Ready_b2w); if (!m_pLDB) { return; } const FAWftConfKeeper * pConf = m_pLDB->GetB2WConf (); if (!pConf) { return; } const bool NoTrUse = pConf->GetNoTrUse (); const bool UseNfst = pConf->GetUseNfst (); if (UseNfst) { if (!m_pNfstB2W) { m_pNfstB2W = NEW FANfstLookupTools_t < Ty > (m_pAlloc); LogAssert (m_pNfstB2W); } if (false == NoTrUse) { m_pNfstB2W->SetInTr (m_pLDB->GetInTr ()); m_pNfstB2W->SetOutTr (m_pLDB->GetOutTr ()); } m_pNfstB2W->SetConf (pConf); m_Ready_b2w = pConf->GetRsDfa () && pConf->GetIws () && \ pConf->GetActs (); } else { if (!m_pSuffB2W) { m_pSuffB2W = NEW FASuffixInterpretTools_t < Ty > (); LogAssert (m_pSuffB2W); } if (false == NoTrUse) { m_pSuffB2W->SetInTr (m_pLDB->GetInTr ()); m_pSuffB2W->SetOutTr (m_pLDB->GetOutTr ()); } m_pSuffB2W->SetConf (pConf); m_Ready_b2w = pConf->GetRsDfa () && pConf->GetState2Ows () && \ pConf->GetActs (); } } template < class Ty > const int FAPrmInterpreter_t< Ty >:: ProcessB2W ( const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) { if (!m_Ready_b2w) { InitB2W (); if (!m_Ready_b2w) return -1; } // check for limits if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn || \ (NULL == pOut && 0 != MaxOutSize)) return -1; int OutSize = -1; if (m_pSuffB2W) { OutSize = m_pSuffB2W->Process (pIn, InSize, pOut, MaxOutSize); } else { DebugLogAssert (m_pNfstB2W); OutSize = m_pNfstB2W->Process (pIn, InSize, pOut, MaxOutSize); } return OutSize; } template < class Ty > void FAPrmInterpreter_t< Ty >::InitW2W () { DebugLogAssert (!m_Ready_w2w); if (!m_Ready_w2b) { InitW2B (); } if (!m_Ready_b2w) { InitB2W (); } m_Ready_w2w = m_Ready_b2w && m_Ready_w2b; } template < class Ty > const int FAPrmInterpreter_t< Ty >:: ProcessW2W ( const Ty * pIn, const int InSize, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) { DebugLogAssert (m_pBaseList && DefBaseListSize <= m_MaxBaseListSize); if (!m_Ready_w2w) { InitW2W (); if (!m_Ready_w2w) return -1; } // check for limits if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn || \ (NULL == pOut && 0 != MaxOutSize)) return -1; /// generate list of base forms const int BaseListSize = \ FAPrmInterpreter_t<Ty>::ProcessW2B (pIn, InSize, m_pBaseList, m_MaxBaseListSize); /// see whether generated list of base forms does not fit the buffer if (BaseListSize > m_MaxBaseListSize) { /// just extra check for reasonableness DebugLogAssert (BaseListSize < 10 * DefBaseListSize); m_base_list.resize (BaseListSize + 100); m_pBaseList = m_base_list.begin (); m_MaxBaseListSize = BaseListSize + 100; #ifndef NDEBUG const int BaseListSize2 = #endif FAPrmInterpreter_t<Ty>::ProcessW2B (pIn, InSize, m_pBaseList, m_MaxBaseListSize); DebugLogAssert (BaseListSize2 == BaseListSize); } /// make interation thru the generated base forms int Pos = 0; int CurrBasePos = 0; int OutSize = 0; while (Pos < BaseListSize) { if (0 == m_pBaseList [Pos]) { const int CurrBaseSize = Pos - CurrBasePos; DebugLogAssert (0 < CurrBaseSize); /// generate list of word-forms const int TmpSize = \ m_pSuffB2W->Process ( m_pBaseList + CurrBasePos, CurrBaseSize, pOut + OutSize, MaxOutSize - OutSize ); if (0 < TmpSize) { OutSize += TmpSize; } CurrBasePos = Pos + 1; } // of if (0 == m_pBaseList [Pos]) ... Pos++; } return OutSize; } template < class Ty > void FAPrmInterpreter_t< Ty >::InitWT2B () { DebugLogAssert (!m_Ready_wt2b); if (!m_pLDB) { return; } const FAWftConfKeeper * pConf = m_pLDB->GetWT2BConf (); if (!pConf) { return; } const bool NoTrUse = pConf->GetNoTrUse (); const bool UseNfst = pConf->GetUseNfst (); LogAssert (!UseNfst); if (!m_pSuffWT2B) { m_pSuffWT2B = NEW FASuffixInterpretTools_t < Ty > (); LogAssert (m_pSuffWT2B); } if (false == NoTrUse) { m_pSuffWT2B->SetInTr (m_pLDB->GetInTr ()); m_pSuffWT2B->SetOutTr (m_pLDB->GetOutTr ()); } m_pSuffWT2B->SetConf (pConf); m_Ready_wt2b = pConf->GetRsDfa () && pConf->GetState2Ows () && \ pConf->GetActs (); } template < class Ty > void FAPrmInterpreter_t< Ty >::InitB2WT () { DebugLogAssert (!m_Ready_b2wt); if (!m_pLDB) { return; } const FAWftConfKeeper * pConf = m_pLDB->GetB2WTConf (); if (!pConf) { return; } const bool NoTrUse = pConf->GetNoTrUse (); const bool UseNfst = pConf->GetUseNfst (); LogAssert (!UseNfst); if (!m_pSuffB2WT) { m_pSuffB2WT = NEW FASuffixInterpretTools_t < Ty > (); LogAssert (m_pSuffB2WT); } if (false == NoTrUse) { m_pSuffB2WT->SetInTr (m_pLDB->GetInTr ()); m_pSuffB2WT->SetOutTr (m_pLDB->GetOutTr ()); } m_pSuffB2WT->SetConf (pConf); m_Ready_b2wt = pConf->GetRsDfa () && pConf->GetState2Ows () && \ pConf->GetActs (); } template < class Ty > const int FAPrmInterpreter_t< Ty >:: ProcessWT2B ( const Ty * pIn, const int InSize, const int FromTag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) { if (!m_Ready_wt2b) { InitWT2B (); if (!m_Ready_wt2b) return -1; } // of if (!m_Ready_wt2b) ... // check for limits if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn || \ (NULL == pOut && 0 != MaxOutSize)) return -1; DebugLogAssert (m_pSuffWT2B); const int OutSize = \ m_pSuffWT2B->Process (pIn, InSize, FromTag, pOut, MaxOutSize); //// do not copy the original word to the output if (0 >= OutSize) { return -1; } else { return OutSize; } } template < class Ty > const int FAPrmInterpreter_t< Ty >:: ProcessB2WT ( const Ty * pIn, const int InSize, const int ToTag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) { if (!m_Ready_b2wt) { InitB2WT (); if (!m_Ready_b2wt) return -1; } // check for limits if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn || \ (NULL == pOut && 0 != MaxOutSize)) return -1; DebugLogAssert (m_pSuffB2WT); const int OutSize = \ m_pSuffB2WT->Process (pIn, InSize, ToTag, pOut, MaxOutSize); //// do not copy the original word to the output if (0 >= OutSize) { return -1; } else { return OutSize; } } template < class Ty > void FAPrmInterpreter_t< Ty >::InitWTT2W () { DebugLogAssert (!m_Ready_wtt2w); if (!m_Ready_wt2b) { InitWT2B (); } if (!m_Ready_b2wt) { InitB2WT (); } m_Ready_wtt2w = m_Ready_wt2b && m_Ready_b2wt; } template < class Ty > const int FAPrmInterpreter_t< Ty >:: ProcessWTT2W ( const Ty * pIn, const int InSize, const int FromTag, const int ToTag, __out_ecount_opt(MaxOutSize) Ty * pOut, const int MaxOutSize ) { DebugLogAssert (m_pBaseList && DefBaseListSize <= m_MaxBaseListSize); if (!m_Ready_wtt2w) { InitWTT2W (); if (!m_Ready_wtt2w) return -1; } // check for limits if (0 >= InSize || FALimits::MaxWordSize < InSize || !pIn || \ (NULL == pOut && 0 != MaxOutSize)) return -1; /// generate list of base forms const int BaseListSize = \ FAPrmInterpreter_t::ProcessWT2B (pIn, InSize, FromTag, m_pBaseList, m_MaxBaseListSize); /// see whether generated list of base forms does not fit the buffer if (BaseListSize > m_MaxBaseListSize) { /// just extra check for reasonableness DebugLogAssert (BaseListSize < 10 * DefBaseListSize); m_base_list.resize (BaseListSize + 100); m_pBaseList = m_base_list.begin (); m_MaxBaseListSize = BaseListSize + 100; #ifndef NDEBUG const int BaseListSize2 = #endif FAPrmInterpreter_t::ProcessWT2B (pIn, InSize, FromTag, m_pBaseList, m_MaxBaseListSize); DebugLogAssert (BaseListSize2 == BaseListSize); } /// make interation thru the generated base forms int Pos = 0; int CurrBasePos = 0; int OutSize = 0; while (Pos < BaseListSize) { if (0 == m_pBaseList [Pos]) { const int CurrBaseSize = Pos - CurrBasePos; DebugLogAssert (0 < CurrBaseSize); /// generate list of word-forms const int TmpSize = \ m_pSuffB2WT->Process ( m_pBaseList + CurrBasePos, CurrBaseSize, ToTag, pOut + OutSize, MaxOutSize - OutSize ); if (0 < TmpSize) { OutSize += TmpSize; } CurrBasePos = Pos + 1; } // of if (0 == m_pBaseList [Pos]) ... Pos++; } //// do not copy the original word to the output if (0 >= OutSize) { return -1; } else { return OutSize; } } } #endif
78635fda2908725b998974d7a95115fcb6c4caf7
565d6096f8e9cb2379b243c752890011f6f11544
/alignment/include/NCBI_xml.h
ba104631032f25c4514b58a921a49a88cd6056ac
[]
no_license
sungpia/HunivLab
4293954cc25bf6c2a99d22bc7ec345d53819a485
fddb70d5a5091e19f6b2c58f1acab4195a8f52e4
refs/heads/master
2021-01-13T01:13:22.742915
2014-12-18T23:59:26
2014-12-18T23:59:26
28,207,084
1
0
null
null
null
null
UTF-8
C++
false
false
20,256
h
NCBI_xml.h
#pragma once #include <stdio.h> #include <iostream> #include <string> #include <vector> #include <sstream> #include <malloc.h> #include <string.h> #include "support.h" #include "exception.h" #include "tinyxml2.h" #include "genetics.h" /* The namespace tinyXmlUtil conatins many little help function for XML handling */ namespace tinyXmlUtil { /* Dummy filter predicate. */ template<typename TP> inline bool bAlwaysTrue( TP argument ) { return true; } // function template <typename TP_FUNC_APPLY, typename TP_FUNC_FILTER> void forSelfAndAllNextSiblingElementDo( tinyxml2::XMLElement* pElementRef, TP_FUNC_APPLY &&fApply, TP_FUNC_FILTER fFilter ) { while ( pElementRef != NULL ) { if ( fFilter( pElementRef ) == true ) { fApply( pElementRef ); } // if pElementRef = pElementRef->NextSiblingElement(); } // while } // function /* Applies the function fApply to all child elements of some given element reference. */ template <typename TP_FUNC_APPLY> void forAllChildElementsDo( tinyxml2::XMLElement* pElementRef, TP_FUNC_APPLY &&fApply ) { if ( pElementRef != NULL ) { forSelfAndAllNextSiblingElementDo( pElementRef->FirstChildElement(), fApply, bAlwaysTrue<tinyxml2::XMLElement*> ); } // if } // function /* Little Debug function for the display of all element names */ void vDumpAllElementNamesOfChildren( tinyxml2::XMLElement* pElementRef ) { forAllChildElementsDo ( pElementRef, /* Predicate function */ [&](tinyxml2::XMLElement *pSequenceElement ) { std::cout << pSequenceElement->Name() << std::endl; } // lambda ); } // function /* Applies the function fApply to all children of some element, where the predicate function delivers true. * pElementRef can be NULL. */ template <typename TP_FUNC_APPLY, typename TP_FUNC_FILTER> void forFilteredChildElementsDo( tinyxml2::XMLElement* pElementRef, TP_FUNC_APPLY &&fApply, TP_FUNC_FILTER fPredicate ) { if ( pElementRef != NULL ) { forSelfAndAllNextSiblingElementDo( pElementRef->FirstChildElement(), fApply, fPredicate ); } // if } // function /* Be careful, pElementRef is not allowed to be NULL. * Assumes that the child of the given reference is a text node. * Compares pcString to the text of the child-node. */ bool bCompareTextInsideElement( tinyxml2::XMLElement* pElementRef, const char *pcString ) { const char* pcElementText = pElementRef->GetText(); return ( pcElementText != NULL ) ? strcmp( pcString, pcElementText ) == 0 : false; } // function /* Tries to find some element starting from pElementRef, using the path syntax in path. * WARNING!: Delivers NULL if the search fails. * The function is a variant of the split-string function introduced elsewhere. * TO DO: Improve performance by getting rid of the std::string stuff. */ tinyxml2::XMLElement* findElementByPath( tinyxml2::XMLElement* pElementRef, std::string path ) { std::string bufferString; std::string::iterator iterator; for ( iterator = path.begin(); iterator < path.end(); iterator++ ) { if ( (const char)*iterator != '.' ) { bufferString += *iterator; } // if else { if ( pElementRef != NULL ) { pElementRef = pElementRef->FirstChildElement( bufferString.c_str() ); } // if else { return NULL; } // else bufferString.clear(); } // else } // for if (! bufferString.empty() ) { if ( pElementRef != NULL ) { pElementRef = pElementRef->FirstChildElement( bufferString.c_str() ); } // if } // if return pElementRef; } // function template <typename TP_FUNC_APPLY> void vDoIfPathLeadsToELement( tinyxml2::XMLElement* pElementRef, std::string path, TP_FUNC_APPLY &&fApply ) { pElementRef = findElementByPath( pElementRef, path ); if ( pElementRef != NULL ) { fApply( pElementRef ); } // if } // function /* Generic function for the parsing of text contents of XML-elements. * Improvement: Here we could throw an exception if something goes wrong. */ template <typename TP_RETURN_VALUE, typename TP_FUNC_PARSE> TP_RETURN_VALUE genericGetByPath( tinyxml2::XMLElement* pElementRef, const char* pcPathAsString, TP_FUNC_PARSE parsefun, TP_RETURN_VALUE uxReturnedValue ) { /* First we try to get the element... */ if ( ( pElementRef = tinyXmlUtil::findElementByPath( pElementRef, pcPathAsString ) ) != NULL) { /* ... and if we could find some, we try to get the text and parse it. */ const char *pcText = pElementRef->GetText(); if ( pcText != NULL ) { parsefun( pcText, &uxReturnedValue ); } // inner if } // outer if return uxReturnedValue; } // function template <typename TP_FUNC> void doIfAttributeByPathDoesExists( tinyxml2::XMLElement* pElementRef, const char* pcPathAsString, const char* pcAttributeName, TP_FUNC doFunction ) { if ( ( pElementRef = tinyXmlUtil::findElementByPath( pElementRef, pcPathAsString ) ) != NULL) { const char* pcAttributeTextRef = pElementRef->Attribute( pcAttributeName ); if ( pcAttributeTextRef != NULL ) { doFunction( pcAttributeTextRef ); } // inner if } // outer if } // generic function /* parse function for genericGetByPath. */ void cStringToStdString(const char* pcText, std::string* pStringRef ) { pStringRef->append( pcText ); } // function /* parse function for genericGetByPath. */ void CStringToCSTring(const char* pcText, const char **ppcText ) { *ppcText = pcText; } // function /* Gets an parsed unsigned integer from some element. */ uint32_t getUnsignedByPath( tinyxml2::XMLElement* pElementRef, const char* pcPathAsString ) { return genericGetByPath<uint32_t>( pElementRef, pcPathAsString, tinyxml2::XMLUtil::ToUnsigned, 0 ); } // function /* Gets a text child as std:string. */ std::string getStringByPath( tinyxml2::XMLElement* pElementRef, const char* pcPathAsString ) { return genericGetByPath<std::string>( pElementRef, pcPathAsString, cStringToStdString, "" ); } // function /* Gets a text child as constant C-string. */ const char* getCStringByPath( tinyxml2::XMLElement* pElementRef, const char* pcPathAsString ) { return genericGetByPath<const char *>( pElementRef, pcPathAsString, CStringToCSTring, "" ); } // function } // namespace tinyXmlUtil /* Function for debug purposes: * tinyXmlUtil::vDumpAllElementNamesOfChildren( pEntrezgeneElementRef ); */ namespace INSD_XMLUtil { /* Special tailored function for the loading of sequential XML records in INSD_XML files. */ template <typename TP_FUNC_APPLY> void doForXMLSequenceInINSD_XML( tinyxml2::XMLElement* pRelativeRootElement, TP_FUNC_APPLY &&fApply, const char* pcPathToSequenceContainer, const char* pcNameOfElementSelectedForStringComparsion, const char* pcRequestedTextOfTextNode ) { tinyXmlUtil::forFilteredChildElementsDo ( /* Starting from the given root, we search the start of the sequence of XML elements (given by pcPathToSequenceContainer). */ tinyXmlUtil::findElementByPath( pRelativeRootElement, pcPathToSequenceContainer ), /* fApply is applied to all elements where the predicate delivers true. */ fApply, /* Predicate function */ [&](tinyxml2::XMLElement *pSequenceElement ) -> bool { /* We look for a candidate... */ auto pElementRef = tinyXmlUtil::findElementByPath( pSequenceElement, pcNameOfElementSelectedForStringComparsion ); /* We found a matching element, now we have to compare the text child. */ if ( pElementRef != NULL ) { return tinyXmlUtil::bCompareTextInsideElement( pElementRef, pcRequestedTextOfTextNode ); } // if return false; } // lambda ); } // function /* pElementRef must be a reference to a <INSDFeature>. * The <INSDFeature> should have children called <INSDInterval_from> and <INSDInterval_to>. * In the NCBI interval world the counting start with 1, where the end-index seems to be "inclusive". * So start = 1 and end = 2 means internally start = 0 and end = 2, because our end-element is exclusive and we start counting with 0 * Edit: * Now we have already cases, where NCBI seems to count from zero as well. */ IntervalDescriptor xCreateIntervalDescriptorFromINSDFeatureElement( tinyxml2::XMLElement* pINSDFeatureElementRef ) { tinyxml2::XMLElement* pInterval = tinyXmlUtil::findElementByPath( pINSDFeatureElementRef, "INSDFeature_intervals.INSDInterval" ); IntervalDescriptor intervalDescriptor( tinyXmlUtil::getUnsignedByPath( pInterval, "INSDInterval_from" ) - 1, // start ( !!! - 1 !!! ) tinyXmlUtil::getUnsignedByPath( pInterval, "INSDInterval_to" ) // end ); intervalDescriptor.sAccession = tinyXmlUtil::getStringByPath( pInterval, "INSDInterval_accession" ); return intervalDescriptor; } // method /* Special tailored function for loading single sequences in a <INSDSeq_feature-table> section. */ template <typename TP> void vLoadFromINSDSeq_feature_table( tinyxml2::XMLElement* INSDSeqElementRef, std::vector<TP> &vector, const char* pcINSDFeature_keyText ) { INSD_XMLUtil::doForXMLSequenceInINSD_XML ( /* A INSDSeq_feature-table is the child of a INSDSeq element. */ INSDSeqElementRef, /* element will be a reference to a INSDFeature element. * exons is bound on object level */ [&](tinyxml2::XMLElement *pINSDFeatureElement) { vector.push_back( xCreateIntervalDescriptorFromINSDFeatureElement( pINSDFeatureElement ) ); }, // lambda /* The children of INSDSeq_feature-table are a sequence of INSDFeature elements. */ "INSDSeq_feature-table", /* We select all INSDFeature elements where the child INSDFeature_key contains a text element with content pcINSDFeature_keyText. */ "INSDFeature_key", pcINSDFeature_keyText ); } // generic function /* Extracts the content of a <INSDSeq> element as mRNA. */ void vGet_mRNAFromINSDSeq( tinyxml2::XMLElement* pISNDSeqElementRef, GeneticCompound_mRNA &rCompoundmRNA ) { /* We get the definition (description of our sequence data) */ rCompoundmRNA.sDefinition = tinyXmlUtil::getStringByPath( pISNDSeqElementRef, "INSDSeq_definition" ); /* We get the RNA sequence data */ rCompoundmRNA.xRNASequence.vAppend( tinyXmlUtil::getCStringByPath( pISNDSeqElementRef, "INSDSeq_sequence" ) ); /* We get the size of the RNA sequence data. This data can be used for data inconsistency checks. * TO DO: Impelemnt such a consistency check. */ rCompoundmRNA.uxSequenceSize = tinyXmlUtil::getUnsignedByPath( pISNDSeqElementRef, "INSDSeq_length" ); /* We get the exon data */ vLoadFromINSDSeq_feature_table( pISNDSeqElementRef, rCompoundmRNA.exonVector, "exon" ); /* We get the CDS data */ vLoadFromINSDSeq_feature_table( pISNDSeqElementRef, rCompoundmRNA.cdsVector, "CDS" ); /* We get the STS data */ vLoadFromINSDSeq_feature_table( pISNDSeqElementRef, rCompoundmRNA.stsVector, "STS" ); } // function /* Loads the XML file with the name pcFileName and extracts a mRNA description out of the file. */ void vLoadINSD_XML( const char* pcFileName, GeneticCompound_mRNA &rCompoundmRNA ) { tinyxml2::XMLDocument xmlDocument; /* We try to load the XML document from the given location */ xmlDocument.LoadFile( pcFileName ); if ( xmlDocument.ErrorID() != tinyxml2::XML_SUCCESS ) { /* Something went wrong ... * We throw some exception */ throw fasta_reader_exception( "XML file loading failed" ); } // if /* We load from the first sequence */ INSD_XMLUtil::vGet_mRNAFromINSDSeq( tinyXmlUtil::findElementByPath( xmlDocument.RootElement(), "INSDSeq" ), rCompoundmRNA ); } // function } // namespace INSD_XMLUtil /* Code for loading gene information in a NCBI XML-file that start with a <Entrezgene-Set> element */ namespace NCBI_Entrezgene { /* pElementRef must be a reference to a <Seq-interval>. * TO DO: Read the strand. (Reverse or forward) */ DoubleStrandIntervalDescriptor xCreateIntervalDescriptorFromSeq_interval( tinyxml2::XMLElement* pSeq_intervalElementRef ) { /* WARNING: Counting starts here suddenly with 0. (Normally the NCBI world starts with 1) * So from 0 to 2 means from the first until the third (inclusive) * In our internal representation 0, 3 because we take the first element after. */ DoubleStrandIntervalDescriptor intervalDescriptor( tinyXmlUtil::getUnsignedByPath( pSeq_intervalElementRef, "Seq-interval_from" ), // start tinyXmlUtil::getUnsignedByPath( pSeq_intervalElementRef, "Seq-interval_to" ) + 1 // end ); /* TO DO: change this part here to id */ intervalDescriptor.sAccession = tinyXmlUtil::getStringByPath( pSeq_intervalElementRef, "Seq-interval_id.Seq-id.Seq-id_gi" ); tinyXmlUtil::doIfAttributeByPathDoesExists ( pSeq_intervalElementRef, // start element ref "Seq-interval_strand.Na-strand", // path "value", // attribute value [&] (const char* pcAttributeTextRef) { intervalDescriptor.eStrand = strcmp( pcAttributeTextRef, "plus" ) == 0 ? ChromosomeSequence::IS_FORWARD_STRAND : strcmp( pcAttributeTextRef, "minus" ) == 0 ? ChromosomeSequence::IS_REVERSE_STRAND : ChromosomeSequence::UNKNOWN_STRAND; } ); return intervalDescriptor; } // method /* Special tailored function for loading many <Sec-loc> sections in a <Seq-loc-mix> section. */ template <typename TP> void vExtractIntervalsFromSeq_loc_mix( tinyxml2::XMLElement* Seq_loc_mixElementRef, std::vector<TP> &vector ) { tinyXmlUtil::forAllChildElementsDo ( /* We iterate over the children of Seq_loc_mixElementRef */ Seq_loc_mixElementRef, /* pSeq_locElementRef refers a <Sec-loc> element * We get the single <Seq-loc_int> child of <Sec-loc> and read all intervals */ [&]( tinyxml2::XMLElement *pSeq_locElementRef ) { vector.push_back( xCreateIntervalDescriptorFromSeq_interval( tinyXmlUtil::findElementByPath( pSeq_locElementRef, "Seq-loc_int.Seq-interval" ) ) ); } // lambda ); } // generic function /* Gets all intervals below * starting by <Gene-commentary_genomic-coords> : "Gene-commentary_genomic-coords.Seq-loc.Seq-loc_mix.Seq-loc-mix" * starting by <Gene-commentary_seqs> : "Gene-commentary_seqs.Seq-loc" */ template <typename TP> void vExtractIntervalsOfGene_commentary( tinyxml2::XMLElement* pGene_commentaryElementRef, std::vector<TP> &vector, const char* pcPath ) { vExtractIntervalsFromSeq_loc_mix ( tinyXmlUtil::findElementByPath( pGene_commentaryElementRef, pcPath ), vector ); } // generic function /* Reads a commentary below the given <Gene-commentary> element. * In the moment we read here the locus information. */ void vExtractGene_commentary( tinyxml2::XMLElement* pGen_commentaryElementRef, std::shared_ptr<GeneLocusDescriptor> const &pLocusDescriptorRef ) { /* Get the classification e.g. genomic or mRNA */ pLocusDescriptorRef->eNCBIClassification = (GeneLocusDescriptor::eNCBIClassificationType)tinyXmlUtil::getUnsignedByPath( pGen_commentaryElementRef, "Gene-commentary_type" ); /* TExtual description of the info in the Gene-commentary. */ pLocusDescriptorRef->sLabel = tinyXmlUtil::getStringByPath( pGen_commentaryElementRef, "Gene-commentary_label" ); /* NCBI reference code */ pLocusDescriptorRef->sNCBIAccession = tinyXmlUtil::getStringByPath( pGen_commentaryElementRef, "Gene-commentary_accession" ); /* We read all the intervals that belong to the comment. * Here we have to be careful, because the intervals are on different location for different types! */ vExtractIntervalsOfGene_commentary ( pGen_commentaryElementRef, pLocusDescriptorRef->locationsVector, pLocusDescriptorRef->eNCBIClassification == GeneLocusDescriptor::GENOMIC ? "Gene-commentary_seqs" // for genomic comments the sequences are here : "Gene-commentary_genomic-coords.Seq-loc.Seq-loc_mix.Seq-loc-mix" // otherwise we get them here ); if ( pGen_commentaryElementRef->FirstChildElement( "Gene-commentary_products" ) != NULL ) { /* There is a <Gene-commentary_products>. So, we recursively parse this comment. * In the moment we parse only the first child. (TO DO: Check the DTD, if we can have more than one product) */ vExtractGene_commentary ( tinyXmlUtil::findElementByPath( pGen_commentaryElementRef, "Gene-commentary_products.Gene-commentary" ), /* get product creates a sub-object, if required. */ pLocusDescriptorRef->pGetProduct() ); } // if } // function void vFindNCBI_Entrezgene_geneElementAndGetData( tinyxml2::XMLElement* pEntrezgeneElementRef, geneDescriptor &rGene ) { tinyXmlUtil::vDoIfPathLeadsToELement ( pEntrezgeneElementRef, // start element ref "Entrezgene_gene.Gene-ref", // path [&]( tinyxml2::XMLElement *pGene_refElementRef ) { /* Store the result in the interpretations section of the gene record. */ rGene.sReferenceDescriptions = tinyXmlUtil::getStringByPath( pGene_refElementRef, "Gene-ref_desc" ); } // lambda ); // function call } // function /* gets genom information of a NCBI XML-tree with root element <Entrezgene-Set> * (pEntrezgeneElementRef should refer some <Entrezgene> element) */ void vFindNCBI_Entrezgene_locusElementAndGetData( tinyxml2::XMLElement* pEntrezgeneElementRef, geneDescriptor &rGene ) { tinyXmlUtil::vDoIfPathLeadsToELement ( pEntrezgeneElementRef, // start element ref "Entrezgene_locus", // path [&]( tinyxml2::XMLElement *pEntrezgene_locusElementRef ) { /* We have a <Entrezgene_locus> section, so we create a new locus descriptor. * We work here with shared pointers in order to get automatic garbage collection. */ std::shared_ptr<GeneLocusDescriptor> pLocusDescriptorRef = std::make_shared<GeneLocusDescriptor>(); /* Take the Gene-commentary child and parse locus information. */ vExtractGene_commentary( pEntrezgene_locusElementRef->FirstChildElement( "Gene-commentary" ), pLocusDescriptorRef ); /* Store the result in the interpretations section of the gene record. */ rGene.geneLocusDescriptions = pLocusDescriptorRef; } // lambda ); } // function /* Loads the XML file with the name pcFileName and extracts a gene description from the XML content. */ void vLoadNCBI_Entrezgene( const char* pcFileName, geneDescriptor &rGene ) { tinyxml2::XMLDocument xmlDocument; /* We try to load the XML document from the given location */ xmlDocument.LoadFile( pcFileName ); if ( xmlDocument.ErrorID() != tinyxml2::XML_SUCCESS ) { /* Something went wrong ... * We throw some exception */ throw fasta_reader_exception( "XML file loading failed" ); } // if /* We get the <Entrezgene> in the XML tree and keep a reference to this element */ tinyxml2::XMLElement* pEntrezgeneElementRef = tinyXmlUtil::findElementByPath( xmlDocument.RootElement(), "Entrezgene" ); /* We get the data contained in the <Entrezgene_locus> section */ vFindNCBI_Entrezgene_locusElementAndGetData( pEntrezgeneElementRef, rGene ); /* We get the data contained in the <Entrezgene_gene> section */ vFindNCBI_Entrezgene_geneElementAndGetData( pEntrezgeneElementRef, rGene ); } // function } // namespace NCBI_Entrezgene
3c453f83a0e47f3b9bab7d188719d39606870294
a8f00b9b7da68409dc66fe0d4ebb90cda80ecffc
/src/shaders.cc
797bab5683cc340c9d47abd092b83029a34a640d
[ "MIT" ]
permissive
skeggse/boids
b500c1b0573b1a162c9a8b7d78ca7ddced8c4096
5057d8478194cac8ebe6621f1c5d9e0c38533f8a
refs/heads/master
2023-06-27T05:42:33.833569
2017-01-08T21:13:44
2017-01-08T21:13:44
78,178,232
0
0
null
null
null
null
UTF-8
C++
false
false
4,850
cc
shaders.cc
////////////////////////////////////////////////////////////////////////////// // // A support source file from Angel 6th Edition // // This file is provided under the MIT License // (http://opensource.org/licenses/MIT). // // Original work Copyright (c) <2014-2015> <Ed Angel and Dave Shreiner> // Modified work Copyright (c) 2017 Eli Skeggs // // 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 <iostream> #include "Angel.h" using namespace std; // modified from http://www.lighthouse3d.com/opengl/glsl/index.php?oglinfo // prints out shader info void printShaderInfoLog(const GLuint shader) { GLint infologLength; GLsizei charsWritten; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infologLength); if (infologLength > 1) { char *infoLog = new char[infologLength]; glGetShaderInfoLog(shader, infologLength, &charsWritten, infoLog); cout << "Shader Log (" << charsWritten << ": " << infoLog << endl; delete[] infoLog; } else { #ifdef DEBUG cout << "Shader: OK" << endl; #endif } } // modified from http://www.lighthouse3d.com/opengl/glsl/index.php?oglinfo // prints out shader info void printProgramInfoLog(const GLuint program) { GLint infologLength; GLsizei charsWritten; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infologLength); if (infologLength > 1) { char *infoLog = new char[infologLength]; glGetProgramInfoLog(program, infologLength, &charsWritten, infoLog); cout << "Program Log (" << charsWritten << ": " << infoLog << endl; delete[] infoLog; } else { #ifdef DEBUG cout << "Program: OK" << endl; #endif } } namespace Angel { // create a NULL-terminated string by reading the provided file static char *readShaderSource(const char *shaderFile) { FILE *fp = fopen(shaderFile, "rb"); if (fp == NULL) return NULL; fseek(fp, 0L, SEEK_END); long size = ftell(fp); fseek(fp, 0L, SEEK_SET); char *buf = new char[size + 1]; size_t readSize = fread(buf, 1, size, fp); buf[readSize] = '\0'; fclose(fp); return buf; } void attachShader(const GLuint program, const GLenum type, const char *source) { GLuint shader = glCreateShader(type); const GLchar *sources[] = {"#version 430 core\n", (const GLchar*) source}; glShaderSource(shader, 2, sources, NULL); glCompileShader(shader); printShaderInfoLog(shader); GLint compiled; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { cerr << "shader failed to compile:" << std::endl; GLint logSize; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logSize); char *logMsg = new char[logSize]; glGetShaderInfoLog(shader, logSize, NULL, logMsg); cerr << logMsg << std::endl; delete[] logMsg; exit(EXIT_FAILURE); } glAttachShader(program, shader); } void attachShaderFile(const GLuint program, const GLenum type, const char *file) { char *shader = readShaderSource(file); attachShader(program, type, shader); delete[] shader; } void linkProgram(const GLuint program) { glLinkProgram(program); GLint linked; glGetProgramiv(program, GL_LINK_STATUS, &linked); if (!linked) { std::cerr << "shader program failed to link:" << std::endl; GLint logSize; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logSize); char *logMsg = new char[logSize]; glGetProgramInfoLog(program, logSize, NULL, logMsg); std::cerr << logMsg << std::endl; delete[] logMsg; exit(EXIT_FAILURE); } printProgramInfoLog(program); } } // Close namespace Angel block
033bb97b385ba27807d30706c427429dd9a85caf
785df77400157c058a934069298568e47950e40b
/TnbGeo/TnbLib/Geo/Graph/3d/Geo3d_Graph.hxx
8c03a004a861bfebc9027efef0f7e856d63d85be
[]
no_license
amir5200fx/Tonb
cb108de09bf59c5c7e139435e0be008a888d99d5
ed679923dc4b2e69b12ffe621fc5a6c8e3652465
refs/heads/master
2023-08-31T08:59:00.366903
2023-08-31T07:42:24
2023-08-31T07:42:24
230,028,961
9
3
null
2023-07-20T16:53:31
2019-12-25T02:29:32
C++
UTF-8
C++
false
false
188
hxx
Geo3d_Graph.hxx
#pragma once #ifndef _Geo3d_Graph_Header #define _Geo3d_Graph_Header #include <Geo_Graph.hxx> #include <Geo3d_GraphEdge.hxx> #include <Geo3d_GraphFwd.hxx> #endif // !_Geo3d_Graph_Header
917c222b356727616ff3533bd4363743bdd94737
31f5b05ce19b58ef983e08bdd1ceb6233d88954f
/cry-c++/solutions/win64/Code_uber.cpp
04fe9d1cccfdfe5d98677af748fa049d6756e185
[ "MIT" ]
permissive
spPT-2018/language-benchmark
478ec31ce3ff7450b1e3dc7e8a8c9bf0b3054760
9f3973cbac683362d1f7c1cf3a3288ab87c7843d
refs/heads/master
2020-04-01T20:00:41.089152
2019-03-22T12:20:47
2019-03-22T12:20:47
153,583,527
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
Code_uber.cpp
// Unity Build Uber File generated by CMake // This file is auto generated, do not manually edit it. #include <StdAfx.h> #include <C:/Users/tobia/Documents/GitHub/language-benchmark/cry-c++/Code/GamePlugin.cpp>
84aa3aea8d1038d1fa40be7d6080e5b439ee1bd7
e946a20c33bdc4eaa84da0ab2feff9e866c1f6a8
/Calculdora.cpp
27eca5597ca58780b7c8a0e8b01d933663940ca7
[]
no_license
vichente96/Unidad-2-Sistemas-Operativos-1
abbddbca2e120e66124d5a8db16b8c798156bf46
0c33f8d6b4350dd9f29378f745120bee804c3c87
refs/heads/master
2021-01-25T14:32:30.301098
2018-03-20T13:33:37
2018-03-20T13:33:37
123,702,332
0
0
null
null
null
null
UTF-8
C++
false
false
2,317
cpp
Calculdora.cpp
#include <stdio.h> #include <math.h> int main(){ int x,y,z; float d1,d2,r; do{ printf("***************CALCULADORA**************\n"); printf("***Elaborado por Vicente Mata Velasco***\n"); printf ("Elige una opcion\n"); //Imprimimos un menu de operaciones printf("-------------------------------------\n"); printf ("1.Suma\n2.Resta\n3.Division\n4.Multiplicacion\n5.Raiz Cuadrada\n6.Potencia\n"); printf("-------------------------------------\n"); printf("Opcion: "); scanf ("%d",&x); if(x>=1&&x<=6){ //Delimitamos los numeros del 1 al 6 para las cinco opcioness if (x==5){ //Como para raiz cuadrada solo se calcula con un solo numero hacemos la condicion solo para la opcion 5 printf("Introcuce el numero: \n"); scanf ("%f",&d1); r=sqrt(d1); printf("Su raiz cuadrada es: %.2f",r); //Solo imprimira 2 decimales } else if (x==6){ printf("Introcuce el numero: \n"); scanf ("%f",&d1); printf ("Itroduce el numero a elevar:\n"); scanf("%f",&d2); r=pow (d1,d2); printf("El resudltado de %.f elevado a %.f es: %.2f ",d1,d2,r); } else{ //Sino se eligio la opcion 5 se realiza un switch case para las otras 4 opciones printf("Introduce el primer numero:\n"); //Para las siguintes operaciones forzosamente se necesitan 2 numeros scanf ("%f",&d1); printf("Introduce el segundo numero:\n"); scanf ("%f",&d2); switch (x) //Asignamos el dato de respuesta la variable x { case 1: { r=d1+d2; //Suma printf("\nLa suma de valores es: %.2f",r); break; } case 2: { //Resta r=d1-d2; printf("\nLa Resta de valores es: %.2f",r); break; } case 3: { //Division r=d1/d2; printf("\nLa division de valores es: %.2f",r); break; } case 4: { //Multiplicacion r=d1*d2; printf("\nLa multiplicacion de valores es: %.2f",r); break; } } } } else{ printf("\n***ERROR*** Opcion no valida"); //Mandamos una respuesta de error en dado caso que se digite un numero que no este en el menu } printf("\nDigite 1 para otra opcion \nPresione un numero distinto para terminar \n"); scanf ("%d",&y); }while (y==1); //Usamos un do while para hacer distintas operaciones y se termine la ejecucion cuando se digite un numero distinto a 1 return 0; }
7d4472eff5f8e971343e5806c61f1160f41536ce
f83654206f28e58b5c7473b49a43336b477ee9e3
/PETCS/Intermediate/gfssoc3s1.cpp
6ce3893ec4642db84f95f3b8a77b685ced2cb2a8
[ "MIT" ]
permissive
TimothyW553/Competitive-Programming
180c80105dab59942819217aef50b3832875f8f1
2d17e10fad597e148dc28ffb1dcfe5a5950ffe6d
refs/heads/master
2022-12-20T05:00:32.120465
2020-10-15T17:13:21
2020-10-15T17:13:21
115,227,938
2
2
MIT
2020-10-15T17:13:22
2017-12-23T23:29:10
C++
UTF-8
C++
false
false
238
cpp
gfssoc3s1.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll N; int main() { cin.sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> N; for(ll i = 1; i <= N; i <<= 1) { cout << "1"; } return 0; }
a72845a97f0b8f085e87737feddfbcedb687d6d5
32dae960d93d85c4a4b1baf63f18c709ea22a70f
/tw99.cpp
27c9baae166ef4a7382e806f82f307bead424a85
[]
no_license
shubhamkhule/tw99
1c87fa47ed11a636fab90a8d07ebf7c7ab62d342
8819bcc01b2a39f15df53d8073be56895aff9e4e
refs/heads/master
2021-01-17T01:13:44.503242
2016-07-09T08:33:55
2016-07-09T08:33:55
62,939,728
0
0
null
null
null
null
UTF-8
C++
false
false
542
cpp
tw99.cpp
//============================================================================ // Name : tw99.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int main() { int a,b,c; cout<<"Enter any 2 numbers"; cin>>a>>b; cout<<endl<<"Select the operation to be performed::"; cout<<endl<<"1.Addition"; cout<<endl<<"2.Subtraction"; return 0; }
7795eb7ee5a8b10c493943f536098a672601b0ea
630ba426e56fcada45cbc3dcd8c4477347d73b07
/007_ReverseInteger/007_ReverseInteger.cpp
9a745c5013117534c16fb01570a9f1f172461cb2
[]
no_license
henryoier/leetcode
3975817d2651fce455aa1f32d5ffd341f920205e
329af8279d4233b694f319a2c3874c899adc12e3
refs/heads/master
2020-04-15T12:45:00.140811
2016-11-15T07:08:03
2016-11-15T07:08:03
63,466,657
1
0
null
null
null
null
UTF-8
C++
false
false
885
cpp
007_ReverseInteger.cpp
/************************************************************************* > File Name: 007_ReverseInteger.cpp > Author: Sheng Qin > Mail: sheng.qin@yale.edu > Created Time: Tue Aug 2 21:25:47 2016 ************************************************************************/ #include<iostream> using namespace std; class Solution { public: int reverse(int x) { long result = 0; bool negative = false; if(x < 0){ x = 0 - x; negative = true; } while(x>0){ result = result * 10 + x % 10; x = x/10; } if(result > INT_MAX) return 0; if(negative) return 0 - result; else return result; } }; int main(){ int x; cin >> x; Solution newSolution; cout << newSolution.reverse(x) <<endl; return 0; }
ee7f5e958d46b95b5d878d94f47917001baf3e96
802005880fafb7b333576e4c658126c180f2a5ff
/da/da_radiance/da_rttov_tl.inc
c6905d752f4f1b033acd6f66eba84f77a70e8154
[ "LicenseRef-scancode-public-domain" ]
permissive
whudddddd/WRFDA
3043cce9dc29bb6929e4a82b1e808854a89ced0a
dab0145011a314dca296e1526799ef9661eb0951
refs/heads/master
2020-06-29T20:17:19.943571
2009-12-21T22:11:59
2009-12-21T22:11:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,578
inc
da_rttov_tl.inc
#ifdef RTTOV subroutine da_rttov_tl(inst, nchanl, nprofiles, con_vars, aux_vars, & con_vars_tl, aux_vars_tl, tb) !--------------------------------------------------------------------------- ! PURPOSE: interface to the tangent linear subroutine of RTTOV !--------------------------------------------------------------------------- implicit none #include "rttov_tl.interface" integer , intent (in) :: inst, nchanl, nprofiles type (con_vars_type), intent (in) :: con_vars (nprofiles) type (con_vars_type), intent (in) :: con_vars_tl (nprofiles) type (aux_vars_type), intent (in) :: aux_vars (nprofiles) type (aux_vars_type), intent (in) :: aux_vars_tl (nprofiles) real , intent (out) :: tb(nchanl,nprofiles) ! local variables integer :: n, nc Integer :: alloc_status(140) ! RTTOV input parameters integer :: nfrequencies, nchannels, nbtout integer :: nchan(nprofiles) integer , pointer :: lprofiles(:) type(rttov_coef) :: coef type(profile_type) :: profiles(nprofiles), profiles_tl(nprofiles) logical :: addcloud real , allocatable :: surfem(:) integer , pointer :: channels (:), polarisations(:,:) logical, allocatable :: calcemis (:) ! RTTOV out parameters integer :: errorstatus(nprofiles) ! RTTOV inout parameters real , pointer :: emissivity (:), emissivity_tl (:) type (radiance_type) :: radiance, radiance_tl type (transmission_type) :: transmission, transmission_tl call da_trace_entry("da_rttov_tl") nchan (:) = nchanl coef = coefs(inst) addcloud = .false. alloc_status(:) = 0 do n = 1, nprofiles profiles(n) % nlevels = con_vars(n) % nlevels allocate (profiles(n)%p(profiles(n) % nlevels), stat=alloc_status(1)) allocate (profiles(n)%t(profiles(n) % nlevels), stat=alloc_status(2)) allocate (profiles(n)%q(profiles(n) % nlevels), stat=alloc_status(3)) allocate (profiles(n)%o3(profiles(n) % nlevels), stat=alloc_status(4)) allocate (profiles(n)%co2(profiles(n) % nlevels), stat=alloc_status(5)) allocate (profiles(n)%clw(profiles(n) % nlevels), stat=alloc_status(6)) if (any(alloc_status /= 0)) then WRITE(UNIT=message(1),FMT='(A,I5)') & "mem allocation error to for profiles",n call da_error(__FILE__,__LINE__,message(1:1)) end if profiles(n) % ozone_data = .false. profiles(n) % co2_data = .false. profiles(n) % clw_data = .false. profiles(n) % p(:) = coef%ref_prfl_p(:) profiles(n) % t(:) = con_vars(n)%t(:) profiles(n) % q(:) = con_vars(n)%q(:) profiles(n) % o3(:) = 0.0 !con_vars(n)%o3(:) profiles(n) % co2(:) = 0.0 !con_vars(n)%co2(:) profiles(n) % clw(:) = 0.0 !con_vars(n)%clw(:) profiles(n) % skin % surftype = aux_vars (n) % surftype profiles(n) % skin % t = aux_vars (n) % surft profiles(n) % skin % fastem (:) = 0.0 ! aux_vars (n) % fastem (:) profiles(n) % s2m % t = aux_vars (n) % t2m profiles(n) % s2m % q = aux_vars (n) % q2m profiles(n) % s2m % o = 0.0 !aux_vars (n) % o3 profiles(n) % s2m % p = con_vars (n) % ps profiles(n) % s2m % u = aux_vars (n) % u10 profiles(n) % s2m % v = aux_vars (n) % v10 profiles(n) % zenangle = aux_vars (n) % satzen profiles(n) % azangle = aux_vars (n) % satazi profiles(n) % ctp = 500.0 profiles(n) % cfraction = 0.0 profiles_tl(n) % nlevels = con_vars_tl(n) % nlevels allocate (profiles_tl(n)%p(profiles_tl(n) % nlevels), stat=alloc_status(1)) allocate (profiles_tl(n)%t(profiles_tl(n) % nlevels), stat=alloc_status(2)) allocate (profiles_tl(n)%q(profiles_tl(n) % nlevels), stat=alloc_status(3)) allocate (profiles_tl(n)%o3(profiles_tl(n) % nlevels), stat=alloc_status(4)) allocate (profiles_tl(n)%co2(profiles_tl(n) % nlevels), stat=alloc_status(5)) allocate (profiles_tl(n)%clw(profiles_tl(n) % nlevels), stat=alloc_status(6)) if (any(alloc_status /= 0)) then WRITE(UNIT=message(1),FMT='(A,I5)') & "mem allocation error to for profiles_tl",n call da_error(__FILE__,__LINE__,message(1:1)) end if profiles_tl(n) % ozone_data = .false. profiles_tl(n) % co2_data = .false. profiles_tl(n) % clw_data = .false. profiles_tl(n) % p(:) = 0.0 profiles_tl(n) % t(:) = con_vars_tl(n)%t(:) profiles_tl(n) % q(:) = con_vars_tl(n)%q(:) profiles_tl(n) % o3(:) = 0.0 !con_vars(n)%o3(:) profiles_tl(n) % co2(:) = 0.0 !con_vars(n)%co2(:) profiles_tl(n) % clw(:) = 0.0 !con_vars(n)%clw(:) profiles_tl(n) % skin % surftype = -1 profiles_tl(n) % skin % t = 0.0 !aux_vars_tl (n) % surft profiles_tl(n) % skin % fastem (:) = 0.0 ! aux_vars (n) % fastem (:) profiles_tl(n) % s2m % t = 0.0 !aux_vars_tl (n) % t2m profiles_tl(n) % s2m % q = 0.0 !aux_vars_tl (n) % q2m profiles_tl(n) % s2m % o = 0.0 !aux_vars_tl (n) % o3 profiles_tl(n) % s2m % p = con_vars_tl (n) % ps profiles_tl(n) % s2m % u = 0.0 !aux_vars_tl (n) % u10 profiles_tl(n) % s2m % v = 0.0 !aux_vars_tl (n) % v10 profiles_tl(n) % zenangle = -1 profiles_tl(n) % azangle = -1 profiles_tl(n) % ctp = 0.0 !500. profiles_tl(n) % cfraction = 0.0 end do #ifdef RTTOV call rttov_setupchan(nprofiles, nchan, coef, & ! in nfrequencies, nchannels, nbtout) ! out #endif allocate (lprofiles(nfrequencies), stat = alloc_status(31)) allocate (channels (nfrequencies), stat = alloc_status(32)) allocate (polarisations(nchannels, 3), stat = alloc_status(33)) allocate (emissivity(nchannels), stat = alloc_status(34)) allocate (emissivity_tl(nchannels), stat = alloc_status(134)) allocate (calcemis(nchannels), stat = alloc_status(35)) allocate (surfem (nchannels), stat = alloc_status(36)) ! allocate transmittance structure allocate (transmission % tau_surf (nchannels) ,stat= alloc_status(8)) allocate (transmission % tau_layer (coef % nlevels, nchannels) ,stat= alloc_status(9)) allocate (transmission % od_singlelayer(coef % nlevels, nchannels ),stat= alloc_status(10)) allocate (transmission_tl % tau_surf (nchannels) ,stat= alloc_status(108)) allocate (transmission_tl % tau_layer (coef % nlevels, nchannels) ,stat= alloc_status(109)) allocate (transmission_tl % od_singlelayer(coef % nlevels, nchannels ),stat= alloc_status(110)) ! allocate radiance results arrays with number of channels allocate (radiance % clear (nchannels) ,stat= alloc_status(11)) allocate (radiance % cloudy (nchannels) ,stat= alloc_status(12)) allocate (radiance % total (nchannels) ,stat= alloc_status(13)) allocate (radiance % bt (nchannels) ,stat= alloc_status(14)) allocate (radiance % bt_clear (nchannels) ,stat= alloc_status(15)) allocate (radiance % upclear (nchannels) ,stat= alloc_status(16)) allocate (radiance % dnclear (nchannels) ,stat= alloc_status(17)) allocate (radiance % reflclear(nchannels) ,stat= alloc_status(18)) allocate (radiance % overcast (coef % nlevels, nchannels) ,stat= alloc_status(19)) ! allocate the cloudy radiances with full size even ! if not used allocate (radiance % downcld (coef % nlevels, nchannels) ,stat= alloc_status(20)) allocate (radiance % out (nbtout) ,stat= alloc_status(121)) allocate (radiance % out_clear(nbtout) ,stat= alloc_status(122)) allocate (radiance % total_out(nbtout) ,stat= alloc_status(123)) allocate (radiance % clear_out(nbtout) ,stat= alloc_status(124)) ! allocate radiance results arrays with number of channels allocate (radiance_tl % clear (nchannels) ,stat= alloc_status(111)) allocate (radiance_tl % cloudy (nchannels) ,stat= alloc_status(112)) allocate (radiance_tl % total (nchannels) ,stat= alloc_status(113)) allocate (radiance_tl % bt (nchannels) ,stat= alloc_status(114)) allocate (radiance_tl % bt_clear (nchannels) ,stat= alloc_status(115)) allocate (radiance_tl % upclear (nchannels) ,stat= alloc_status(116)) allocate (radiance_tl % dnclear (nchannels) ,stat= alloc_status(117)) allocate (radiance_tl % reflclear(nchannels) ,stat= alloc_status(118)) allocate (radiance_tl % overcast (coef % nlevels, nchannels) ,stat= alloc_status(119)) ! allocate the cloudy radiances with full size even ! if not used allocate (radiance_tl % downcld (coef % nlevels, nchannels) ,stat= alloc_status(120)) allocate (radiance_tl % out (nbtout) ,stat= alloc_status(121)) allocate (radiance_tl % out_clear(nbtout) ,stat= alloc_status(122)) allocate (radiance_tl % total_out(nbtout) ,stat= alloc_status(123)) allocate (radiance_tl % clear_out(nbtout) ,stat= alloc_status(124)) if (any(alloc_status /= 0)) then call da_error(__FILE__,__LINE__, & (/"mem allocation error prior to rttov_tl"/)) end if surfem (:) = 0.0 #ifdef RTTOV call rttov_setupindex(nchan, nprofiles, nfrequencies, & ! in nchannels, nbtout, coef, surfem, & ! in lprofiles, channels, polarisations, & ! out emissivity ) ! out #endif nc = nchannels/nprofiles if (coef%id_sensor == 1) then ! infrared sensor calcemis (1:nchannels) = .true. emissivity (1:nchannels) = 0.0 emissivity_tl (1:nchannels) = 0.0 else if (coef%id_sensor == 2) then ! microwave sensor do n = 1, nprofiles if (profiles(n) % skin % surftype == 1) then ! sea calcemis ((n-1)*nc+1:n*nc) = .true. emissivity ((n-1)*nc+1:n*nc) = 0.0 emissivity_tl ((n-1)*nc+1:n*nc) = 0.0 else ! 0:land ; 2:sea-ice calcemis ((n-1)*nc+1:n*nc) = .false. emissivity ((n-1)*nc+1:n*nc) = 0.9 emissivity_tl ((n-1)*nc+1:n*nc) = 0.0 end if end do end if #ifdef RTTOV call rttov_tl(& & errorstatus, &! out & nfrequencies, &! in & nchannels, &! in & nbtout, &! in & nprofiles, &! in & channels, &! in & polarisations, &! in & lprofiles, &! in & profiles, &! in & coef, &! in & addcloud, &! in & calcemis, &! in & emissivity, &! inout & profiles_tl, &! in & emissivity_tl, &! inout & transmission, &! inout & transmission_tl, &! inout & radiance, &! inout & radiance_tl) ! inout #endif ! rttov87 generates warnings we want to ignore if (print_detail_rad .and. (any(errorstatus(:) == errorstatus_fatal))) then write (message(1),*) 'rttov_direct error code = ', errorstatus(:) write (message(2),*) 'nfrequencies = ', nfrequencies write (message(3),*) 'nchannels = ', nchannels write (message(4),*) 'nbtout = ', nbtout write (message(5),*) 'nprofiles = ', nprofiles write (message(6),*) 'channels = ', channels write (message(7),*) 'polarisations = ', polarisations write (message(8),*) 'lprofiles = ', lprofiles write (message(9),*) 'addcloud = ', addcloud write (message(10),*) 'calcemis = ', calcemis write (message(11),*) 'profiles%s2m = ', profiles(1)%s2m write (message(12),*) 'profiles%skin = ', profiles(1)%skin write (message(13),*) 'profiles%zenangle = ', profiles(1)%zenangle write (message(14),*) 'profiles%azangle = ', profiles(1)%azangle write (message(15),*) 'profiles%p = ', profiles(1)%p write (message(16),*) 'profiles%t = ', profiles(1)%t write (message(17),*) 'profiles%q = ', profiles(1)%q write (message(18),*) 'emissivity = ', emissivity write (message(19),*) 'radiance = ', radiance%out_clear write (message(20),*) 'profiles_tl%s2m = ', profiles_tl(1)%s2m write (message(21),*) 'profiles_tl%skin = ', profiles_tl(1)%skin write (message(22),*) 'profiles_tl%zenangle = ', profiles_tl(1)%zenangle write (message(23),*) 'profiles_tl%azangle = ', profiles_tl(1)%azangle write (message(24),*) 'profiles_tl%p = ', profiles_tl(1)%p write (message(25),*) 'profiles_tl%t = ', profiles_tl(1)%t write (message(26),*) 'profiles_tl%q = ', profiles_tl(1)%q write (message(27),*) 'emissivity_tl = ', emissivity_tl write (message(28),*) 'radiance_tl = ', radiance_tl%out_clear call da_warning(__FILE__,__LINE__,message(1:28)) end if nc = nbtout / nprofiles do n = 1, nprofiles tb(1:nc,n) = radiance_tl % out_clear((n-1)*nc+1:n*nc) end do deallocate (lprofiles) deallocate (channels) deallocate (polarisations) deallocate (emissivity) deallocate (emissivity_tl) deallocate (calcemis) deallocate (surfem) do n = 1, nprofiles deallocate (profiles(n)%p) deallocate (profiles(n)%t) deallocate (profiles(n)%q) deallocate (profiles(n)%o3) deallocate (profiles(n)%co2) deallocate (profiles(n)%clw) deallocate (profiles_tl(n)%p) deallocate (profiles_tl(n)%t) deallocate (profiles_tl(n)%q) deallocate (profiles_tl(n)%o3) deallocate (profiles_tl(n)%co2) deallocate (profiles_tl(n)%clw) end do ! deallocate transmittance structure deallocate (transmission % tau_surf ,stat= alloc_status(6)) deallocate (transmission % tau_layer ,stat= alloc_status(7)) deallocate (transmission % od_singlelayer,stat= alloc_status(8)) ! deallocate transmittance structure deallocate (transmission_tl % tau_surf ,stat= alloc_status(106)) deallocate (transmission_tl % tau_layer ,stat= alloc_status(107)) deallocate (transmission_tl % od_singlelayer,stat= alloc_status(108)) ! deallocate radiance results arrays with number of channels deallocate (radiance % clear ,stat=alloc_status(9)) deallocate (radiance % cloudy ,stat=alloc_status(10)) deallocate (radiance % total ,stat=alloc_status(11)) deallocate (radiance % bt ,stat=alloc_status(12)) deallocate (radiance % bt_clear ,stat=alloc_status(13)) deallocate (radiance % upclear ,stat=alloc_status(14)) deallocate (radiance % dnclear ,stat=alloc_status(15)) deallocate (radiance % reflclear,stat=alloc_status(16)) deallocate (radiance % overcast ,stat=alloc_status(17)) deallocate (radiance % downcld ,stat=alloc_status(18)) deallocate (radiance % out ,stat= alloc_status(19)) deallocate (radiance % out_clear ,stat= alloc_status(20)) deallocate (radiance % total_out ,stat= alloc_status(21)) deallocate (radiance % clear_out ,stat= alloc_status(22)) deallocate (radiance_tl % clear ,stat=alloc_status(109)) deallocate (radiance_tl % cloudy ,stat=alloc_status(110)) deallocate (radiance_tl % total ,stat=alloc_status(111)) deallocate (radiance_tl % bt ,stat=alloc_status(112)) deallocate (radiance_tl % bt_clear ,stat=alloc_status(113)) deallocate (radiance_tl % upclear ,stat=alloc_status(114)) deallocate (radiance_tl % dnclear ,stat=alloc_status(115)) deallocate (radiance_tl % reflclear,stat=alloc_status(116)) deallocate (radiance_tl % overcast ,stat=alloc_status(117)) deallocate (radiance_tl % downcld ,stat=alloc_status(118)) deallocate (radiance_tl % out ,stat= alloc_status(119)) deallocate (radiance_tl % out_clear ,stat= alloc_status(120)) deallocate (radiance_tl % total_out ,stat= alloc_status(121)) deallocate (radiance_tl % clear_out ,stat= alloc_status(122)) if (any(alloc_status /= 0)) then call da_error(__FILE__,__LINE__, & (/"mem deallocation error"/)) end if call da_trace_exit("da_rttov_tl") end subroutine da_rttov_tl #endif
a2c5a5e0255175a3e580193b4a8f08af5731c5cb
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/hunk_3023.cpp
694ca92bb7e1406783bd0008e93c83c70e935366
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,272
cpp
hunk_3023.cpp
test_expect_success 'fails silently when using -q with deleted reflogs' ' ref=$(git rev-parse HEAD) && - : >.git/logs/refs/test && - git update-ref -m "message for refs/test" refs/test "$ref" && + git update-ref --create-reflog -m "message for refs/test" refs/test "$ref" && git reflog delete --updateref --rewrite refs/test@{0} && test_must_fail git rev-parse -q --verify refs/test@{0} >error 2>&1 && test_must_be_empty error ' test_expect_success 'fails silently when using -q with not enough reflogs' ' ref=$(git rev-parse HEAD) && - : >.git/logs/refs/test2 && - git update-ref -m "message for refs/test2" refs/test2 "$ref" && + git update-ref --create-reflog -m "message for refs/test2" refs/test2 "$ref" && test_must_fail git rev-parse -q --verify refs/test2@{999} >error 2>&1 && test_must_be_empty error ' test_expect_success 'succeeds silently with -q and reflogs that do not go far back enough in time' ' ref=$(git rev-parse HEAD) && - : >.git/logs/refs/test3 && - git update-ref -m "message for refs/test3" refs/test3 "$ref" && + git update-ref --create-reflog -m "message for refs/test3" refs/test3 "$ref" && git rev-parse -q --verify refs/test3@{1.year.ago} >actual 2>error && test_must_be_empty error && echo "$ref" >expect &&
97afc818aaf7a443e72a057797de60162e7b85e7
8d1ee4bfb88b5f884d23a14cc83799b79904a7b0
/badcode.cpp
2c37c4d70fd2c876bdcacd17c3e7ea896a461b90
[]
no_license
mojoe12/UVa
aefb2020fe3b48c115557be131acb62ede08f5dc
dba57e95b3f387b187a872620ae9e72290fa1a61
refs/heads/master
2021-01-23T01:45:54.335619
2017-09-29T02:22:29
2017-09-29T02:22:29
92,890,593
1
0
null
null
null
null
UTF-8
C++
false
false
1,674
cpp
badcode.cpp
#include <iostream> #include <vector> #include <cmath> #include <algorithm> using namespace std; // function declarations void getcodes (vector< pair<char, string> >& code, string final, vector<string>& codes, string current, string currentchars); bool comp(pair<char, string> i, pair<char, string> j) { return i.first < j.first; } int main() { // setup input int n; for (int c = 1; cin >> n; c++) { if (!n) break; vector< pair<char, string> > code (n); for (int i = 0; i < n; i++) { cin >> code[i].first >> code[i].second; } sort(code.begin(), code.end(), comp); string final; cin >> final; vector<string> codes; getcodes(code, final, codes, "", ""); cout << "Case #" << c << endl; for (int i = 0; i < codes.size(); i++) { cout << codes[i] << endl; } cout << endl; } } void getcodes (vector< pair<char, string> >& code, string final, vector<string>& codes, string current, string currentchars) { if (codes.size() == 100) return; if (current == final) { codes.push_back(currentchars); return; } int fl = final.length(), cl = current.length(); if (final[cl] == '0' && fl > cl+1) { current += '0'; getcodes(code, final, codes, current, currentchars); return; } for (int i = 0; i < code.size(); i++) { bool ifok = true; for (int j = 0; j < code[i].second.length(); j++) { if (code[i].second[j] != final[cl + j]) ifok = false; } if (ifok) { current = current + code[i].second; currentchars += code[i].first; getcodes(code, final, codes, current, currentchars); current.pop_back(); if (code[i].second.length() == 2) current.pop_back(); currentchars.pop_back(); } } }
50b1fcd6898c5eded57ed3d766e18a2aed74d49d
483ff22f4f72fbd95eadf601875745ef04a0dbd3
/CampusLife/VOJ/POJ_2513.cpp
2151570edf04b7c9af864ddb717820fcaf9ac66b
[]
no_license
Domacles/MyCXXode
a7c98f52824ee62d79e22e9e5f7487c81a2e6108
f72fc8b230d3b4bff8972472a39a66c1103bc341
refs/heads/master
2021-08-24T02:19:54.177050
2017-12-07T16:30:41
2017-12-07T16:30:41
113,472,855
0
0
null
null
null
null
UTF-8
C++
false
false
2,349
cpp
POJ_2513.cpp
#include <map> #include <set> #include <list> #include <cmath> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <string> #include <cctype> #include <complex> #include <cassert> #include <utility> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; ///#pragma comment(linker, "/STACK:102400000,102400000") typedef pair<int, int> PII; typedef long long ll; int size01(int x) { return __builtin_popcount(x); } #define lson l,m,rt<<1 #define rson m+1,r,rt<<11 #define All 1,N,1 const ll INFll = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x7ffffff; const int maxn = 1e5 + 3e4 + 100; const int mod = 1000000007; const double pi = acos(-1); const double eps = 1e-10; typedef complex<double> Point; typedef complex<double> Vector; typedef vector<int> intV; typedef vector<double> intD; #define X real() #define Y imag() Vector rotate(Vector v, double a) { return v * polar(1.0, a); } int dx[] = {0 , -1, 0, 1}; int dy[] = { -1, 0, 1, 0}; struct Node { int next[26]; int num; Node() { memset(next, -1, sizeof(next)); num = 0; } } node[5005]; char s[11], p[11]; int has, cnt, sum[5555], f[5555]; void init() { cnt = has = 0; memset(sum, 0, sizeof(sum)); for (int i = 1; i <= 5010; i++) f[i] = i; } int Trie(char *str) { int i = 0, rt = 0; while (str[i]) { int id = str[i] - 'a'; if (node[rt].next[id] == -1) node[rt].next[id] = ++cnt; rt = node[rt].next[id]; i++; } if(!node[rt].num) node[rt].num=++has; return node[rt].num; } inline int findw(int x) { if (f[x] == x) return x; return f[x] = findw(f[x]); } void solve() { int flag = 0; while (~scanf("%s%s", s, p)) { int a = Trie(s) , b = Trie(p); int x = findw(a), y = findw(b); f[y] = x, sum[a]++, sum[b]++; } int rt = findw(1); for (int i = 2; i <= has; i++) if (findw(i) != rt) { flag = 1000; break; } for (int i = 1; i <= has; i++) if (sum[i] % 2) flag++; if (flag == 0 || flag == 2) printf("Possible\n"); else printf("Impossible\n"); } int main() { //freopen("1.in","r",stdin); //freopen("1.out","w",stdout); init(); solve(); return 0; }
567314ada0ece0b1cefb3f51ead3cdf3ca39114a
54a8af66c0a26047d886a9be4902a091ee3f1e8d
/trabajoEnClase/main.cpp
a0055210b5c34e74b6f221298d1bcca72b854248
[]
no_license
octavioguti/octavioguti
9c8ede2170dd607f2fae7497b89fd8f445e7ea8d
6ba5f79d581664bff2a154daf3bfbff5388947c6
refs/heads/master
2016-09-06T08:46:22.982642
2014-06-13T03:47:08
2014-06-13T03:47:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,324
cpp
main.cpp
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; struct alumno { char nombre[30]; double parcial[2]; double promedio; char obs[15]; }; const int n=4; alumno alum[n]; void ingreso (alumno alum[]) { for (int i=0;i<=n;i++) { _flushall(); cout<<"Nombre del alumno...:"; cin.getline(alum[i].nombre,30); for (int k=0; k<=2; k++) { cout<<"Ingresar la nota parcial.."<<k<<"..."; cin>> alum[i].parcial[k]; } } } double promedio(double parcial[]) { double suma=0; for (int i=0; i<3;i++) suma += parcial[i]; return suma/3; } void calcular(alumno alum[]) { for (int i=0; i<=n; i++) { alum[i].promedio=alum[i].parcial / 3; if (alum[i].promedio>=60) { strcopy(alum[i].obs,"Aprobado"); } else { strcopy(alum[i].obs,"Reprobado"); } } } void presentar(alumno alum) { cout<<" Alumno "<<alum.nombre<<" Nota final es "<<alum.promedio<<"\n"; cout<<" Esta " <<alum.obs<<"\n"; } void presentartodos(alumno alum[]) { for (int i=0; i<=0; i++) { presentar(alum[i]); } } int main() { ingreso (alum); calcular (alum); presentar (alum); }
57ca5e26a38136151e8bc328cd3063f5c7667dc7
ea55b2ca51e7b3ff5478dcc58fa5462712e6e2f5
/Custom_PriceTag_AccesPoint/ESP32_Async_PlatformIO/RFV3/mode_wun_activation.h
e5ac91d7244fab79d62a975f853973fbb6121c1f
[]
no_license
jeason-j/E-Paper_Pricetags
26c7f98477bf506690fc41aa0d8d8682e54e2a80
d5e51a48143e877ad7ce14b492b6017b0ac882d0
refs/heads/main
2023-03-24T07:47:40.336647
2021-03-28T08:47:14
2021-03-28T08:47:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,660
h
mode_wun_activation.h
#pragma once #include "RFV3.h" class ModeWunAct : public mode_class { public: virtual void interrupt() { wakeup(); } virtual void new_interval() { } virtual void pre() { log_main(mode_name); set_last_activation_status(1); wakeup_start_time = millis(); memset(tx_wu_buffer, 0xff, 10); tx_wu_buffer[0] = 0x00; tx_wu_buffer[1] = 0xff; // New Version Activation tx_wu_buffer[2] = 0x05; // Num Periods per slot tx_wu_buffer[3] = 0x4c; // Slot time in MS LOW tx_wu_buffer[4] = 0x04; // Slot time in MS HIGH tx_wu_buffer[5] = 0x10; // Num Slots Activation tx_wu_buffer[6] = 0x02; tx_wu_buffer[7] = 0x01; // Frequenzy tx_wu_buffer[8] = 0x03; tx_wu_buffer[9] = 0xfe; // Used NetID for Activation Serial.print("Wun Activation: 0x"); Serial.print(tx_wu_buffer[0], HEX); Serial.print(" 0x"); Serial.print(tx_wu_buffer[1], HEX); Serial.print(" 0x"); Serial.print(tx_wu_buffer[2], HEX); Serial.print(" 0x"); Serial.print(tx_wu_buffer[3], HEX); Serial.print(" 0x"); Serial.print(tx_wu_buffer[4], HEX); Serial.print(" 0x"); Serial.print(tx_wu_buffer[5], HEX); Serial.print(" 0x"); Serial.print(tx_wu_buffer[6], HEX); Serial.print(" 0x"); Serial.print(tx_wu_buffer[7], HEX); Serial.print(" 0x"); Serial.print(tx_wu_buffer[8], HEX); Serial.print(" 0x"); Serial.println(tx_wu_buffer[9], HEX); cc1101_prepaire_tx(get_wu_channel(), 0); wakeup(); cc1101_tx(); } virtual void main() { } virtual void post() { } virtual String get_name() { return mode_name; } private: String mode_name = "Wakeup new Activation"; long wakeup_start_time; uint8_t tx_wu_buffer[10]; void wakeup() { if (millis() - wakeup_start_time > 16000) { uint8_t temp_freq = get_freq(); uint8_t temp_network_id = get_network_id(); uint16_t temp_display_id = get_display_id(); uint8_t temp_num_slots = get_num_slots(); uint8_t temp_display_slot = temp_num_slots & temp_display_id; save_current_settings(); set_num_slot(0x10); set_freq(0); set_network_id(0xfe); uint8_t serial[7]; get_serial(serial); set_display_id(serial[4] << 8 | serial[5]); /* This is the config send to the new Activation version*/ uint8_t temp_buffer[] = { /*SetRfConfig*/ 0x92, /*len*/ 0x1D, /*Used Frequenzy*/ (uint8_t)(temp_freq + 1), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*NetID temp_network_id*/ temp_network_id, /*Display_ID*/ (uint8_t)(temp_display_id & 0xFF), (uint8_t)(temp_display_id >> 8), /*Num slots temp_num_slots*/ (uint8_t)(temp_num_slots + 1), /*Slot time in MS: 1100*/ 0x4C, 0x04, 0x00, 0x00, 0xFF, 0x00, /*Periods per slot sync???*/ 0x05, /*Freq Location Region???*/ 0x40, 0x18, 0xFC, 0xE7, 0x03, /*Max missed sync periods but unknown so better leave at 0x06*/ (uint8_t)(60 / (get_num_slots() + 1)), /*General config*/ 0x00, 0x01, 0x00, /*WuSlot*/ temp_display_slot, /*GetFirmwareType*/ 0x1F, /*GetDisplaySize*/ 0x1A, }; set_trans_buffer(temp_buffer, sizeof(temp_buffer)); set_is_data_waiting(true); set_trans_mode(1); set_mode_idle(); } else { cc1101_tx_fill(tx_wu_buffer, 10); } } }; ModeWunAct modeWunAct;
d4046bdd8e5db09429ad6a2fd8a5339f869a332c
7ec0bf6f76a17452b7d7a907a57505b965b86b00
/server/model/src/basket.cpp
cfa8ec7bf2f4fb7b776a6e1d11c47fbf6245995c
[]
no_license
JoseManuelAR/cabify
ce7fb6f1208c71211f2ed604a7bcedee6d16ca03
7fa9526f454fca4e44c124acb1ff19a892cd14b7
refs/heads/master
2020-04-06T19:23:06.607474
2018-11-27T19:36:34
2018-11-27T19:36:34
157,735,038
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
basket.cpp
#include <model/basket.hpp> namespace model { BasketId Basket::_currentId = 0; nlohmann::json Basket::toJson() { nlohmann::json val = nlohmann::json::object(); val["id"] = _id; return val; } void Basket::createProduct(const std::string &code) { _products[code]++; } } // namespace model
894128ff6c839e452f21c5f1cfaa3eb00b22a779
f5164b8e2ec20ae88684b52a9df42244234b1ca1
/src/dinitcheck.cc
bdabd6df489c08817fe5a2d992d79fd008fdd042
[ "Apache-2.0" ]
permissive
davmac314/dinit
b51811c6644abaab68477aa318f24428afcbb0cd
021cdbfe75066af847120e869b8684d0be5c6c50
refs/heads/master
2023-09-01T17:50:00.433095
2023-09-01T12:46:38
2023-09-01T12:46:38
46,341,079
470
62
Apache-2.0
2023-09-13T08:27:26
2015-11-17T10:54:54
C++
UTF-8
C++
false
false
16,827
cc
dinitcheck.cc
#include <algorithm> #include <iostream> #include <fstream> #include <cstring> #include <string> #include <vector> #include <list> #include <map> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/resource.h> #include <pwd.h> #include <dirent.h> #include "dinit-util.h" #include "service-constants.h" #include "load-service.h" #include "options-processing.h" // dinitcheck: utility to check Dinit configuration for correctness/lint using string = std::string; using string_iterator = std::string::iterator; static void report_service_description_err(const std::string &service_name, const std::string &what); // prelim_dep: A preliminary (unresolved) service dependency class prelim_dep { public: std::string name; dependency_type dep_type; prelim_dep(const std::string &name_p, dependency_type dep_type_p) : name(name_p), dep_type(dep_type_p) { } prelim_dep(std::string &&name_p, dependency_type dep_type_p) : name(std::move(name_p)), dep_type(dep_type_p) { } }; class service_record { public: service_record(const std::string &name_p, const std::string &chain_to_p, std::list<prelim_dep> dependencies_p, std::list<string> before_svcs) : name(name_p), dependencies(dependencies_p), before_svcs(before_svcs) {} std::string name; std::string chain_to; std::list<prelim_dep> dependencies; std::list<string> before_svcs; bool visited = false; // flag used to detect cyclic dependencies bool cycle_free = false; }; using service_set_t = std::map<std::string, service_record *>; service_record *load_service(service_set_t &services, const std::string &name, const service_dir_pathlist &service_dirs); // Add some missing standard library functionality... template <typename T> bool contains(std::vector<T> vec, const T& elem) { return std::find(vec.begin(), vec.end(), elem) != vec.end(); } static bool errors_found = false; int main(int argc, char **argv) { using namespace std; service_dir_opt service_dir_opts; bool am_system_init = (getuid() == 0); std::vector<std::string> services_to_check; // Process command line if (argc > 1) { for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { // An option... if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) { if (++i < argc) { service_dir_opts.set_specified_service_dir(argv[i]); } else { cerr << "dinitcheck: '--services-dir' (-d) requires an argument" << endl; return 1; } } else if (strcmp(argv[i], "--help") == 0) { cout << "dinitcheck: check dinit service descriptions\n" " --help display help\n" " --services-dir <dir>, -d <dir>\n" " set base directory for service description\n" " files, can be specified multiple times\n" " <service-name> check service with name <service-name>\n"; return EXIT_SUCCESS; } else { std::cerr << "dinitcheck: Unrecognized option: '" << argv[i] << "' (use '--help' for help)\n"; return EXIT_FAILURE; } } else { services_to_check.push_back(argv[i]); } } } service_dir_opts.build_paths(am_system_init); if (services_to_check.empty()) { services_to_check.push_back("boot"); } size_t num_services_to_check = services_to_check.size(); // Load named service(s) // - load the service, store dependencies as strings // - recurse std::map<std::string, service_record *> service_set; for (size_t i = 0; i < services_to_check.size(); ++i) { const std::string &name = services_to_check[i]; std::cout << "Checking service: " << name << "...\n"; try { service_record *sr = load_service(service_set, name, service_dir_opts.get_paths()); service_set[name] = sr; // add dependencies to services_to_check for (auto &dep : sr->dependencies) { if (service_set.count(dep.name) == 0 && !contains(services_to_check, dep.name)) { services_to_check.push_back(dep.name); } } // add chain_to to services_to_check if (!sr->chain_to.empty() && !contains(services_to_check, sr->chain_to)) { if (!contains(services_to_check, sr->chain_to)) { services_to_check.push_back(sr->chain_to); } } // add before_svcs to services_to_check for (const std::string &before_name : sr->before_svcs) { if (!contains(services_to_check, before_name)) { services_to_check.push_back(before_name); } } } catch (service_load_exc &exc) { std::cerr << "Unable to load service '" << name << "': " << exc.exc_description << "\n"; errors_found = true; } } // For "before" reverse-dependencies, set up dependencies in the forwards direction (from the dependent) for (const auto &svc_name_record : service_set) { for (const std::string &before_name : svc_name_record.second->before_svcs) { auto before_svc_it = service_set.find(before_name); if (before_svc_it != service_set.end()) { before_svc_it->second->dependencies.emplace_back(svc_name_record.first, dependency_type::BEFORE); } } } // Check for circular dependencies std::vector<std::tuple<service_record *, size_t>> service_chain; for (size_t i = 0; i < num_services_to_check; ++i) { service_record *root = service_set[services_to_check[i]]; if (! root) continue; if (root->visited) continue; // invariant: service_chain is empty service_chain.emplace_back(root, 0); // Depth first traversal. If we find a link (dependency) on a service already visited (but not // marked as cycle-free), we know then that we've found a cycle. while (true) { auto n = service_chain.size() - 1; auto &last = service_chain[n]; service_record *last_record = std::get<0>(last); size_t &index = std::get<1>(last); if (index >= last_record->dependencies.size()) { // Processed all dependencies, go back up: last_record->cycle_free = true; service_chain.pop_back(); if (n == 0) break; size_t &prev_index = std::get<1>(service_chain[n - 1]); ++prev_index; continue; } // Down the tree: auto dep_it = std::next(last_record->dependencies.begin(), index); service_record *next_link = service_set[dep_it->name]; if (next_link == nullptr) { ++index; continue; } if (next_link->visited) { if (! next_link->cycle_free) { // We've found a cycle. Clear entries before the beginning of the cycle, then // exit the loop. auto first = std::find_if(service_chain.begin(), service_chain.end(), [next_link](std::tuple<service_record *, size_t> &a) -> bool { return std::get<0>(a) == next_link; }); service_chain.erase(service_chain.begin(), first); break; } } next_link->visited = true; service_chain.emplace_back(next_link, 0); } // Report only one cycle; otherwise difficult to avoid reporting duplicates or overlapping // cycles. if (!service_chain.empty()) break; } if (!service_chain.empty()) { errors_found = true; std::cerr << "Found dependency cycle:\n"; for (auto chain_link : service_chain) { service_record *svc = std::get<0>(chain_link); size_t dep_index = std::get<1>(chain_link); std::cerr << " " << svc->name << " ->"; auto dep_it = std::next(svc->dependencies.begin(), dep_index); if (dep_it->dep_type == dependency_type::BEFORE) { std::cerr << " (via 'before')"; } std::cerr << "\n"; } std::cerr << " " << std::get<0>(service_chain[0])->name << ".\n"; } if (! errors_found) { std::cout << "No problems found.\n"; } else { std::cout << "One or more errors/warnings issued.\n"; } return errors_found ? EXIT_FAILURE : EXIT_SUCCESS; } static void report_service_description_err(const std::string &service_name, unsigned line_num, const std::string &what) { std::cerr << "Service '" << service_name << "' (line " << line_num << "): " << what << "\n"; errors_found = true; } static void report_service_description_err(const std::string &service_name, const char *setting_name, const std::string &what) { std::cerr << "Service '" << service_name << "' setting '" << setting_name << "': " << what << "\n"; errors_found = true; } static void report_service_description_err(const std::string &service_name, const std::string &what) { std::cerr << "Service '" << service_name << "': " << what << "\n"; errors_found = true; } static void report_service_description_exc(service_description_exc &exc) { if (exc.line_num != (unsigned)-1) { report_service_description_err(exc.service_name, exc.line_num, exc.exc_description); } else { report_service_description_err(exc.service_name, exc.setting_name, exc.exc_description); } } static void report_error(std::system_error &exc, const std::string &service_name) { std::cerr << "Service '" << service_name << "', error reading service description: " << exc.what() << "\n"; errors_found = true; } static void report_dir_error(const char *service_name, const std::string &dirpath) { std::cerr << "Service '" << service_name << "', error reading dependencies from directory " << dirpath << ": " << strerror(errno) << "\n"; errors_found = true; } // Process a dependency directory - filenames contained within correspond to service names which // are loaded and added as a dependency of the given type. Expected use is with a directory // containing symbolic links to other service descriptions, but this isn't required. // Failure to read the directory contents, or to find a service listed within, is not considered // a fatal error. static void process_dep_dir(const char *servicename, const string &service_filename, std::list<prelim_dep> &deplist, const std::string &depdirpath, dependency_type dep_type) { std::string depdir_fname = combine_paths(parent_path(service_filename), depdirpath.c_str()); DIR *depdir = opendir(depdir_fname.c_str()); if (depdir == nullptr) { report_dir_error(servicename, depdirpath); return; } errno = 0; dirent * dent = readdir(depdir); while (dent != nullptr) { char * name = dent->d_name; if (name[0] != '.') { deplist.emplace_back(name, dep_type); } dent = readdir(depdir); } if (errno != 0) { report_dir_error(servicename, depdirpath); } closedir(depdir); } service_record *load_service(service_set_t &services, const std::string &name, const service_dir_pathlist &service_dirs) { using namespace std; using namespace dinit_load; auto found = services.find(name); if (found != services.end()) { return found->second; } string service_filename; ifstream service_file; int fail_load_errno = 0; std::string fail_load_path; // Couldn't find one. Have to load it. for (auto &service_dir : service_dirs) { service_filename = service_dir.get_dir(); if (*(service_filename.rbegin()) != '/') { service_filename += '/'; } service_filename += name; service_file.open(service_filename.c_str(), ios::in); if (service_file) break; if (errno != ENOENT && fail_load_errno == 0) { fail_load_errno = errno; fail_load_path = std::move(service_filename); } } if (!service_file) { if (fail_load_errno == 0) { throw service_not_found(string(name)); } else { throw service_load_error(name, std::move(fail_load_path), fail_load_errno); } } service_settings_wrapper<prelim_dep> settings; environment menv{}; environment renv{}; string line; service_file.exceptions(ios::badbit); try { process_service_file(name, service_file, [&](string &line, unsigned line_num, string &setting, string_iterator &i, string_iterator &end) -> void { auto process_dep_dir_n = [&](std::list<prelim_dep> &deplist, const std::string &waitsford, dependency_type dep_type) -> void { process_dep_dir(name.c_str(), service_filename, deplist, waitsford, dep_type); }; auto load_service_n = [&](const string &dep_name) -> const string & { return dep_name; }; try { process_service_line(settings, name.c_str(), line, line_num, setting, i, end, load_service_n, process_dep_dir_n); } catch (service_description_exc &exc) { if (exc.service_name.empty()) { exc.service_name = name; } report_service_description_exc(exc); } }); } catch (std::system_error &sys_err) { report_error(sys_err, name); throw service_load_exc(name, "error while reading service description."); } auto report_err = [&](const char *msg) { report_service_description_err(name, msg); }; bool issued_var_subst_warning = false; environment::env_map renvmap = renv.build(menv); auto resolve_var = [&](const string &name, environment::env_map const &envmap) { if (!issued_var_subst_warning) { report_service_description_err(name, "warning: variable substitution performed by dinitcheck " "for file paths may not match dinitd (environment may differ)"); issued_var_subst_warning = true; } return resolve_env_var(name, envmap); }; settings.finalise(report_err, renvmap, report_err, resolve_var); auto check_command = [&](const char *setting_name, const char *command) { struct stat command_stat; if (stat(command, &command_stat) == -1) { report_service_description_err(name, std::string("could not stat ") + setting_name + " executable '" + command + "': " + strerror(errno)); } else { if ((command_stat.st_mode & S_IFMT) != S_IFREG) { report_service_description_err(name, std::string(setting_name) + " executable '" + command + "' is not a regular file."); } else if ((command_stat.st_mode & S_IXUSR) == 0) { report_service_description_err(name, std::string(setting_name) + " executable '" + command + "' is not executable by owner."); } } }; if (!settings.command.empty()) { int offset_start = settings.command_offsets.front().first; int offset_end = settings.command_offsets.front().second; check_command("command", settings.command.substr(offset_start, offset_end - offset_start).c_str()); } if (!settings.stop_command.empty()) { int offset_start = settings.stop_command_offsets.front().first; int offset_end = settings.stop_command_offsets.front().second; check_command("stop command", settings.stop_command.substr(offset_start, offset_end - offset_start).c_str()); } return new service_record(name, settings.chain_to_name, settings.depends, settings.before_svcs); }
c1850e472a4bef6b44fe35b78e1f3edc80222386
ff0b45f419af85caf126ac35706dd4bcaeb585e3
/Tardis_Alarm_Clock/OledMenu.h
8f5ba5154b29480f412daf6acdd0ca0563e149cd
[]
no_license
Scott216/Tardis_Alarm_Clock
9d14b00fa0ac93c12cea15148783c7bef58abec8
5f8e97dc9bf84df16faa0212d02ecd81c41cc5d7
refs/heads/master
2021-01-18T23:09:06.784771
2016-05-26T00:03:46
2016-05-26T00:03:46
13,789,051
0
0
null
null
null
null
UTF-8
C++
false
false
2,092
h
OledMenu.h
/* Using namespace for the menu http://www.cprogramming.com/tutorial/namespaces.html */ #ifndef OLED_MENU_H #define OLED_MENU_H #include "Arduino.h" #include "Speaker.h" #include <SSD1306_I2C_DSS.h> // http://github.com/Scott216/SSD1306_I2C_DSS static uint8_t oledClockHour; static uint8_t oledClockMinute; static uint8_t oledAlarmHour; static uint8_t oledAlarmMinute; static uint8_t soundIndex; // ID number of active alarm sound static int8_t menuChange; // -1 for down button, +1 for up, zero for select static int8_t menuSelection; // Determines which item in menu user has selected extern AlarmSpeaker Speaker; #define KEYUP 10 #define KEYDOWN 20 #define KEYSEL 30 #define NOKEY 40 // No button pressed #define KEY_TIMEOUT 50 // Menu times out because of no activity #define MENU_BTN 0 // Menu pushbutton input #define SETCLOCKTIME false #define SETALARMTIME true // Return codes forMenu_ChangeSettings #define NOCHANGE 0 #define NEWTIME 1 #define NEWALARM 2 #define NEWSOUND 3 // Sound file indexes #define SOUND_TARDIS 0 #define SOUND_THEME 1 #define SOUND_EXTERMINATE 2 // For kicks set this up as a namespace namespace Menu { // Function Prototypes void init(Adafruit_SSD1306& oled); int8_t changeSettings(Adafruit_SSD1306& oled, uint8_t clockHr, uint8_t clockMin, uint8_t alarmHr, uint8_t alarmMin); bool setNewTime(Adafruit_SSD1306& oled, bool alarmTime); void displayTopLevel(Adafruit_SSD1306& oled, uint8_t selection); void displayTime(Adafruit_SSD1306& oled, int8_t newHour, int8_t newMinute, bool changingHours); void writeToDisplay(Adafruit_SSD1306& oled, char line1[], char line2[], uint8_t Line1_x, uint8_t Line1_y, uint8_t Line2_x, uint8_t Line2_y); void finished(Adafruit_SSD1306& oled); void displayAlarmTime(Adafruit_SSD1306& oled); bool setNewSound(Adafruit_SSD1306& oled); uint8_t getSoundId(); // Returns the current sound ID number uint8_t getClockHour(); uint8_t getClockMinute(); uint8_t getAlarmHour(); uint8_t getAlarmMinute(); int8_t PollKey(); uint8_t KeyScan(); } #endif
b73878b2587b4eb22d9679632978d8e0b5ee7de1
00e9e71b86551545016455114da0fdf818f32937
/test.cpp
7a7608d81a480cd79fa6f00eb61efc0b0f73922c
[]
no_license
dylanrosser/sandbox
f866eaba1fb002620cd45ef0d4c46b27004fc0f7
67903f94dde45f4279140551b8f6e502a33d8568
refs/heads/master
2022-11-04T06:38:00.979795
2020-06-17T00:08:30
2020-06-17T00:08:30
272,834,626
0
0
null
null
null
null
UTF-8
C++
false
false
69
cpp
test.cpp
int a, b, sum cin >> a; cim >> b; sum = a+ b; cout << sum << endl;
ac821230bc82a7b3f6ff52cb1f41c8e0193d262c
75c21bafbc6167c5d9d1b5e208432b6a8dbc62a6
/TugasAnalgo6/adjacency_matrix.cpp
e2e40097562b326836c01e6fbeece66695f60fe3
[]
no_license
benhard123/TugasAnalgo
f0208a7a15790fc4973be20b1537454f3f68c2de
0a5f08865b45b2bd2ed12c3c1f9247cdc1fe3d1e
refs/heads/master
2020-04-30T06:31:38.010040
2019-05-26T16:58:08
2019-05-26T16:58:08
176,654,741
0
0
null
null
null
null
UTF-8
C++
false
false
1,088
cpp
adjacency_matrix.cpp
#include <stdio.h> #include <iostream> using namespace std; int input(int x[100][100]){ int node; printf("masukan banyaknya node: "); scanf("%i",&node); for(int i=0; i<node; i++){ printf("masukan adjacency dari node %i (Hentikan dengan memasukan 0): ", i+1); for(int j=0; j<node; j++){ scanf("%i", &x[i][j]); if(x[i][j]<=0 || x[i][j]>node){ break; } } } return node; } void output(int input[100][100],int node,int matrix[100][100]){ for(int i=0; i<node; i++){ for(int j=0; j<node; j++){ bool ok=true; for(int k=0; k<node; k++){ if(input[i][k]==(j+1)){ printf("%i ",1); ok=false; break; } } if(ok){ printf("%i ",0); } } printf("\n"); } } int main(){ int matrix[100][100]; int in[100][100]; int node = input(in); printf("\n"); output(in,node,matrix); return 0; }
0061b51a37a71911d952019036ce5ac460d25458
f04eca8d3952e419e3f5ab45a360393c9c331346
/cpp/0651FourKeysKeyboard.cpp
ad31f8739361ff1a1417e53ab65c366376e7bc62
[]
no_license
diordnar/leetCode
9c41290dc4072d81581a0506299472531cce5105
d3b373ec49e717c6d8b259b5494b43414b9050f7
refs/heads/master
2021-08-10T21:46:01.704325
2021-01-17T11:01:44
2021-01-17T11:01:44
242,065,565
0
0
null
null
null
null
UTF-8
C++
false
false
2,935
cpp
0651FourKeysKeyboard.cpp
#include <iostream> #include <vector> #include <algorithm> #include <bitset> #include <cstring> using namespace std; // 这种思路稍微有点复杂,但是效率高。继续走流程,「选择」还是那 4 个,但是这次我们只定义一个「状态」, // 也就是剩余的敲击次数 n。 // 这个算法基于这样一个事实,最优按键序列一定只有两种情况: // 要么一直按 A:A,A,...A(当 N 比较小时)。 // 要么是这么一个形式:A,A,...C-A,C-C,C-V,C-V,...C-V(当 N 比较大时)。 // 因为字符数量少(N 比较小)时,C-A C-C C-V 这一套操作的代价相对比较高,可能不如一个个按 A; // 而当 N 比较大时,后期 C-V 的收获肯定很大。这种情况下整个操作序列大致是:开头连按几个 A,然后 C-A C-C 组合再接若干 C-V,然后再 C-A C-C 接着若干 C-V,循环下去。 // 换句话说,最后一次按键要么是 A 要么是 C-V。明确了这一点,可以通过这两种情况来设计算法: // int[] dp = new int[N + 1]; // // 定义:dp[i] 表示 i 次操作后最多能显示多少个 A // for (int i = 0; i <= N; i++) // dp[i] = max( // 这次按 A 键, // 这次按 C-V // ) // 对于「按 A 键」这种情况,就是状态 i - 1 的屏幕上新增了一个 A 而已,很容易得到结果: // // 按 A 键,就比上次多一个 A 而已 // dp[i] = dp[i - 1] + 1; // 但是,如果要按 C-V,还要考虑之前是在哪里 C-A C-C 的。 // 刚才说了,最优的操作序列一定是 C-A C-C 接着若干 C-V,所以我们用一个变量 j 作为若干 C-V 的起点。 // 那么 j 之前的 2 个操作就应该是 C-A C-C 了: // public int maxA(int N) { // int[] dp = new int[N + 1]; // dp[0] = 0; // for (int i = 1; i <= N; i++) { // // 按 A 键 // dp[i] = dp[i - 1] + 1; // for (int j = 2; j < i; j++) { // // 全选 & 复制 dp[j-2],连续粘贴 i - j 次 // // 屏幕上共 dp[j - 2] * (i - j + 1) 个 A // dp[i] = Math.max(dp[i], dp[j - 2] * (i - j + 1)); // } // } // // N 次按键之后最多有几个 A? // return dp[N]; // } // 其中 j 变量减 2 是给 C-A C-C 留下操作数,看个图就明白了: class Solution { public: int maxA(int N) { vector<int> dp(N + 1, 0); dp[0] = 0; for (int i = 1; i <= N; ++i) { dp[i] = dp[i - 1] + 1; for (int j = 2; j < i; ++j) { dp[i] = max(dp[i], dp[j - 2] * (i - j + 1)); } } return dp[N]; } }; int main() { // N=3 output: 3 // N=7 output: 9 Solution slv; cout << slv.maxA(3) << endl; cout << slv.maxA(7) << endl; cout << slv.maxA(20) << endl; return 0; }
82a0eb9aebe2cef85396c668c3fafd842c91f2a0
2cfeba676f6d72345db60ab9ee36d155a94d3706
/host/TabOpenGL.cpp
c42f0e24e3aa8ff55c6f9b15ba412457eb287724
[]
no_license
voidregreso/DxWnd
92d53fa552ba0d3aed9650be782ceebc57c0cc4e
af8cce2deb351f80c32fb2f45b77af4eaeacbd5b
refs/heads/master
2022-12-02T14:08:28.437876
2020-08-21T15:06:18
2020-08-21T15:06:18
289,295,441
0
1
null
null
null
null
UTF-8
C++
false
false
2,147
cpp
TabOpenGL.cpp
// TabOpenGL.cpp : implementation file // #include "stdafx.h" #include "TargetDlg.h" #include "TabOpenGL.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTabOpenGL dialog CTabOpenGL::CTabOpenGL(CWnd *pParent /*=NULL*/) : CDialog(CTabOpenGL::IDD, pParent) { //{{AFX_DATA_INIT(CTabOpenGL) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } BOOL CTabOpenGL::PreTranslateMessage(MSG *pMsg) { //if(((pMsg->message == WM_KEYDOWN) || (pMsg->message == WM_KEYUP)) if((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_RETURN)) return TRUE; return CWnd::PreTranslateMessage(pMsg); } void CTabOpenGL::DoDataExchange(CDataExchange *pDX) { CDialog::DoDataExchange(pDX); CTargetDlg *cTarget = ((CTargetDlg *)(this->GetParent()->GetParent())); // OpenGL DDX_Check(pDX, IDC_HOOKOPENGL, cTarget->m_HookOpenGL); DDX_Check(pDX, IDC_FORCEHOOKOPENGL, cTarget->m_ForceHookOpenGL); DDX_Check(pDX, IDC_FIXPIXELZOOM, cTarget->m_FixPixelZoom); DDX_Check(pDX, IDC_FIXBINDTEXTURE, cTarget->m_FixBindTexture); DDX_Check(pDX, IDC_SCALEGLBITMAPS, cTarget->m_ScaleglBitmaps); DDX_Check(pDX, IDC_HOOKGLUT32, cTarget->m_HookGlut32); DDX_Check(pDX, IDC_HOOKWGLCONTEXT, cTarget->m_HookWGLContext); DDX_Check(pDX, IDC_SCALEMAINVIEWPORT, cTarget->m_ScaleMainViewport); DDX_Check(pDX, IDC_LOCKGLVIEWPORT, cTarget->m_LockGLViewport); DDX_Check(pDX, IDC_GLEXTENSIONSLIE, cTarget->m_GLExtensionsLie); DDX_Check(pDX, IDC_GLFIXCLAMP, cTarget->m_GLFixClamp); DDX_Text (pDX, IDC_OPENGLLIB, cTarget->m_OpenGLLib); } BOOL CTabOpenGL::OnInitDialog() { AfxEnableControlContainer(); CDialog::OnInitDialog(); return TRUE; } BEGIN_MESSAGE_MAP(CTabOpenGL, CDialog) //{{AFX_MSG_MAP(CTabOpenGL) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTabOpenGL message handlers
421db8711bab67fd2725a09be3bb9684e264f0d3
f45e2b74be8ed7d0fa6b3813a3149b65489ba64b
/Janus/VariableDef.cpp
799bead3b1367d821ccbdbd4338a70b12d4fe5f8
[ "MIT" ]
permissive
fltdyn/Janus
8e7230aa2556e15ad232a2cf0e11b8100663768a
51b6503c291fc0789edaf130962c4c22c8293628
refs/heads/master
2023-04-01T15:20:17.009699
2023-03-20T01:35:41
2023-03-20T01:35:41
217,967,268
12
2
null
null
null
null
UTF-8
C++
false
false
81,994
cpp
VariableDef.cpp
// // DST Janus Library (Janus DAVE-ML Interpreter Library) // // Defence Science and Technology (DST) Group // Department of Defence, Australia. // 506 Lorimer St // Fishermans Bend, VIC // AUSTRALIA, 3207 // // Copyright 2005-2021 Commonwealth of Australia // // 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. // //------------------------------------------------------------------------// // Title: Janus/VariableDef // Class: VariableDef // Module: VariableDef.cpp // First Date: 2009-06-05 // Reference: Janus Reference Manual //------------------------------------------------------------------------// /** * \file VariableDef.cpp * * A VariableDef instance holds in its allocated memory alphanumeric data * derived from a \em variableDef element of a DOM corresponding to * a DAVE-ML compliant XML dataset source file. It includes descriptive, * alphanumeric identification and cross-reference data, and may include * a calculation process tree for variables computed through MathML. * The variable definition can include statistical information regarding * the uncertainty of the values that it might take on, when measured * after any calculation is performed. This class sets up a structure * which manages the \em variableDef content. * * The VariableDef class is only used within the janus namespace, and should * only be referenced through the Janus class. */ /* * Author: D. M. Newman * * Modified : G. Brian, S. Hill * */ #include <algorithm> #ifdef _MSC_VER #include <functional> #else #include <tr1/functional> #endif // Ute Includes #include <Ute/aMessageStream.h> #include <Ute/aString.h> #include <Ute/aMath.h> #include <Ute/aOptional.h> #include "Janus.h" #include "DomFunctions.h" #include "VariableDef.h" #include "ParseMathML.h" #include "SolveMathML.h" #include "ExportMathML.h" using namespace std; using namespace dstoute; using namespace dstomath; using namespace dstomathml; using namespace parsemathml; using namespace solvematrixmathml; using namespace exportmathml; namespace janus { aString mathML_to_ExprTkScript( const DomFunctions::XmlNode& xmlElement, const aString &varID); aStringList variableTypeStringList = ( aStringList() << "INTERNAL" << "INPUT" << "OUTPUT" ); aStringList variableMethodStringList = ( aStringList() << "PLAIN VARIABLE" << "FUNCTION" << "MATHML" << "SCRIPT" << "ARRAY" << "MODEL" ); //------------------------------------------------------------------------// VariableDef::VariableDef() : XmlElementDefinition(), janus_( 0), elementType_( ELEMENT_VARIABLE), varIndex_( aOptionalSizeT::invalidValue()), initialValue_( nan()), minValue_( -std::numeric_limits<double>::max()), maxValue_( std::numeric_limits<double>::max()), isProvenanceRef_( false), hasProvenance_( false), isInput_( false), isControl_( false), isDisturbance_( false), isOutput_( false), isState_( false), isStateDeriv_( false), isStdAIAA_( false), hasUncertainty_( false), exportUncertainty_(false), variableType_( TYPE_INTERNAL), variableMethod_( METHOD_PLAIN_VARIABLE), functionRef_( aOptionalSizeT::invalidValue()), outputScaleFactor_( 1.0), hasOutputScaleFactor_( false), isCurrent_( false), value_( nan()), isCurrentVariance_( false), variance_( 0.0), isCurrentBound_( false), lowerBound_( 0.0), upperBound_( 0.0), isForced_( false), isReferencedExternally_( false), isDimensionRef_( false), hasDimensionDef_( false), hasVarIdEntries_( false), isMatrix_( false), hasMatrixOps_( false), matrix_( 1, 1, 0.0), matrixScaleFactor_( 1, 1, 1.0), matrixVarId_( 1, 1, aOptionalSizeT::invalidValue()), scriptType_( NO_SCRIPT), script_(), scriptContainsThisVarDef_( false), thisVarDef_( 0), eFunc_( 0), kFunc_( 0), isCurrentable_( true), inEvaluation_( false), hasPerturbation_( false), associatedPerturbationVarIndex_( aOptionalSizeT::invalidValue()), perturbationTargetVarIndex_( aOptionalSizeT::invalidValue()), perturbationEffect_( UNKNOWN_UNCERTAINTY), inputWarningDone_( false), outputWarningDone_( false) { mathCalculation_.janus_ = janus_; } //------------------------------------------------------------------------// VariableDef::VariableDef( Janus* janus, const DomFunctions::XmlNode& elementDefinition) : XmlElementDefinition(), janus_( janus), elementType_( ELEMENT_VARIABLE), varIndex_( aOptionalSizeT::invalidValue()), initialValue_( nan()), minValue_( -std::numeric_limits<double>::max()), maxValue_( std::numeric_limits<double>::max()), isProvenanceRef_( false), hasProvenance_( false), isInput_( false), isControl_( false), isDisturbance_( false), isOutput_( false), isState_( false), isStateDeriv_( false), isStdAIAA_( false), hasUncertainty_( false), exportUncertainty_(false), variableType_( TYPE_INTERNAL), variableMethod_( METHOD_PLAIN_VARIABLE), functionRef_( aOptionalSizeT::invalidValue()), outputScaleFactor_( 1.0), hasOutputScaleFactor_( false), isCurrent_( false), value_( nan()), isCurrentVariance_( false), variance_( 0.0), isCurrentBound_( false), lowerBound_( 0.0), upperBound_( 0.0), isForced_( false), isReferencedExternally_( false), isDimensionRef_( false), hasDimensionDef_( false), hasVarIdEntries_( false), isMatrix_( false), hasMatrixOps_( false), matrix_( 1, 1, 0.0), matrixScaleFactor_( 1, 1, 1.0), matrixVarId_( 1, 1, aOptionalSizeT::invalidValue()), scriptType_( NO_SCRIPT), script_(), scriptContainsThisVarDef_( false), thisVarDef_( 0), eFunc_( 0), kFunc_( 0), isCurrentable_( true), inEvaluation_( false), hasPerturbation_( false), associatedPerturbationVarIndex_( aOptionalSizeT::invalidValue()), perturbationTargetVarIndex_( aOptionalSizeT::invalidValue()), perturbationEffect_( UNKNOWN_UNCERTAINTY), inputWarningDone_( false), outputWarningDone_( false) { mathCalculation_.janus_ = janus; initialiseDefinition( janus, elementDefinition); } VariableDef::~VariableDef() { deleteExprTkFunction(); deleteLuaFunction(); } //------------------------------------------------------------------------// const dstoute::aString& VariableDef::getTypeString( ) const { return variableTypeStringList[ variableType_]; } //------------------------------------------------------------------------// const dstoute::aString& VariableDef::getMethodString( ) const { return variableMethodStringList[ variableMethod_]; } //------------------------------------------------------------------------// bool VariableDef::isCalculation() const { switch ( variableMethod_) { case VariableDef::METHOD_MATHML: case VariableDef::METHOD_SCRIPT: return true; default: break; } return false; } bool VariableDef::isInitialValueAllowed() const { switch ( variableMethod_) { case METHOD_PLAIN_VARIABLE: case METHOD_MATHML: case METHOD_SCRIPT: case METHOD_ARRAY: return true; default: break; } return false; } //------------------------------------------------------------------------// void VariableDef::initialiseDefinition( Janus* janus, const DomFunctions::XmlNode& elementDefinition) { static const aString functionName( "VariableDef::initialiseDefinition()"); janus_ = janus; domElement_ = elementDefinition; mathCalculation_.janus_ = janus_; /* * Dimension definition */ elementType_ = ELEMENT_DIMENSION; try { DomFunctions::initialiseChildOrRef( this, elementDefinition, EMPTY_STRING, "dimensionDef", "dimensionRef", "dimID", false); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } /* * Drop through to the original VariableDef class function to populate * other entries of the variable. */ try { initialiseBaseVariableDef( elementDefinition); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } /* * If the variableDef represents a vector or a matrix then check * that it has been defined either using an array element, a * calculation element, a script definition, or a dynamic system model. * * If none of the elements have been defined for the variableDef then * return an error message. * * N.B. a vector or matrix variableDef is identified by having a * dimensionDef or dimensionRef element. */ /* * Check if an array or model element is defined for the variable. * If no calculation, array or model element send an error message. */ bool isCalculationAvailable = DomFunctions::isChildInNode( elementDefinition, "calculation"); bool isArrayAvailable = DomFunctions::isChildInNode( elementDefinition, "array"); bool isModelAvailable = DomFunctions::isChildInNode( elementDefinition, "model"); if (( isArrayAvailable || isCalculationAvailable || isModelAvailable) && !( isArrayAvailable ^ isCalculationAvailable ^ isModelAvailable)) { throw_message( range_error, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" has more than 1 array/calculation/model entries." ); } bool isWrongScriptAvailable = DomFunctions::isChildInNode( elementDefinition, "script"); if ( isWrongScriptAvailable) { throw_message( range_error, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" - Need to place script inside <calculation> element." ); } if ( dimensionDef_.getDimCount() > 0) { size_t dimTotal = dimensionDef_.getDimTotal(); size_t index = dimensionDef_.getDimCount() - 1; size_t baseDimRef = dimensionDef_.getDim( index); if ( dimensionDef_.getDimCount() == 1) { matrix_.resize( baseDimRef, 1); } else { matrix_.resize(( dimTotal / baseDimRef), baseDimRef); } isMatrix_ = true; /* * Retrieve Array definition. * This requires the dimensions of the vector or matrix to be defined first */ if ( isArrayAvailable) { elementType_ = ELEMENT_ARRAY; try { DomFunctions::initialiseChild( this, elementDefinition, varID_, "array", false); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } } } // Scalar/Vector/Matrix Initial Values. initialValueString_ = DomFunctions::getAttribute( elementDefinition, "initialValue"); if ( !initialValueString_.empty() && isInitialValueAllowed()) { // Vector/Matrix value. if ( isMatrix_) { /* * Check if an initial value(s) has been set. * Populate based on number of initialValues. */ aStringList initData = initialValueString_.toStringList( " \t\n\r,;"); if ( initData.size() == 1) { matrix_ = initData.front().toDouble(); isCurrent_ = !isCalculation(); value_ = nan(); } else if ( initData.size() == matrix_.size()) { for ( size_t i = 0; i < matrix_.size(); ++i) { matrix_.matrixData()[ i] = initData[ i].toDouble(); } isCurrent_ = !isCalculation(); value_ = nan(); } else { throw_message( range_error, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" - Invalid number of initial values for vector/matrix. Must be 1 or " << matrix_.size() ); } } // Scalar value. else { if ( initialValueString_.isNumeric()) { initialValue_ = initialValueString_.toDouble(); value_ = initialValue_; isCurrent_ = !isCalculation(); } } } if ( !isMatrix_) { minValueString_ = DomFunctions::getAttribute( elementDefinition, "minValue"); if ( minValueString_.isNumeric()) { minValue_ = minValueString_.toDouble(); value_ = dstomath::max( minValue_, value_); isCurrent_ = true; } maxValueString_ = DomFunctions::getAttribute( elementDefinition, "maxValue"); if ( maxValueString_.isNumeric()) { maxValue_ = maxValueString_.toDouble(); value_ = dstomath::min( value_, maxValue_); isCurrent_ = true; } } /* * Check for an model element if the variableDef represents a dynamic * system model: transfer function or state-space. * * Retrieve Dynamic System Model definition if present */ if ( isModelAvailable) { elementType_ = ELEMENT_MODEL; try { DomFunctions::initialiseChild( this, elementDefinition, varID_, "model", false); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } } /* * Set up ancestor cross references. */ //setAncestorCrossReferences( independentVarRef_); /* * Get the current units and set up conversion factors using aUnitConverter. * * Note: The AIAA/ANSI S-119-2011 standard defines the following * dgC, dgF, dgR, dgK for temperature as opposed to the unit definitions * used here of C, F, R, K */ xmlUnits_.clear(); try { xmlUnits_ = findUnits( units_); } catch (...) { } return; } //------------------------------------------------------------------------// VariableDef::VariableFlag VariableDef::getVariableFlag() const { if ( true == isState_ && true == isStdAIAA_) { return ISSTATE_STDAIAA; } else if ( true == isStateDeriv_ && true == isStdAIAA_) { return ISSTATEDERIV_STDAIAA; } else if ( true == isState_) { return ISSTATE; } else if ( true == isStateDeriv_) { return ISSTATEDERIV; } else if ( true == isStdAIAA_) { return ISSTDAIAA; } return ISERRORFLAG; } //------------------------------------------------------------------------// bool VariableDef::isValue() { if ( !isCurrent_) { solveValue(); } return !isMatrix_; } //------------------------------------------------------------------------// bool VariableDef::isVector() { if ( !isCurrent_) { solveValue(); } return ( isMatrix_ && matrix_.isVector()); } //------------------------------------------------------------------------// bool VariableDef::isMatrix() { if ( !isCurrent_) { solveValue(); } return isMatrix_; } //------------------------------------------------------------------------// double VariableDef::getValue() const { if ( !isCurrent_) { solveValue(); } math_range_check( if ( isMatrix_ && !matrix_.isSingleValue()) { throw_message( runtime_error, setFunctionName( "VariableDef::getValue()") << "\n - variable \"" << name_ << " is not of type value." ); } ); return value_; } //------------------------------------------------------------------------// const DVector& VariableDef::getVector() { if ( !isCurrent_) { solveValue(); } math_range_check( if ( !isMatrix_ || !matrix_.isVector()) { throw_message( runtime_error, setFunctionName( "VariableDef::getVector()") << "\n - variable \"" << name_ << " is not of type vector." ); } ); return matrix_.matrixData(); } //------------------------------------------------------------------------// const DMatrix& VariableDef::getMatrix() { if ( !isCurrent_) { solveValue(); } math_range_check( if ( !isMatrix_ || matrix_.isSingleValue()) { throw_message( runtime_error, setFunctionName( "VariableDef::getMatrix()") << "\n - variable \"" << name_ << " is not of type matrix." ); } ); return matrix_; } //------------------------------------------------------------------------// void VariableDef::solveValue() const { static const aString functionName( "VariableDef::solveValue()"); /* * First check input variables computed as necessary to ensure that * the final result will reflect the current state of all * contributing input variables. This can lead to recursion. * * may not need to go entirely up the tree if a previous evaluation * has satisfied requirements. */ // Exit if currently in evaluation due to setVarDef if ( inEvaluation_) return; for ( vector<size_t>::const_iterator indRefIdx = independentVarRef_.begin(); indRefIdx != independentVarRef_.end(); ++indRefIdx) { VariableDef& indepVariableDef = janus_->variableDef_.at( *indRefIdx); if ( !indepVariableDef.isCurrent_) { indepVariableDef.solveValue(); } } switch ( variableMethod_) { case METHOD_PLAIN_VARIABLE: if ( hasPerturbation_) { value_ = initialValue_; } break; case METHOD_FUNCTION: { /* * 1. Tabular function, either linear or polynomial interpolation. */ Function& thisFunction = janus_->function_[ functionRef_ ]; if ( thisFunction.getData().size() > 0) { if ( ELEMENT_GRIDDEDTABLE == thisFunction.getTableType()) { // gridded numeric if ( thisFunction.isAllInterpolationLinear()) { value_ = janus_->getLinearInterpolation( thisFunction); } else { value_ = janus_->getPolyInterpolation( thisFunction); } } else { // ungridded numeric value_ = janus_->getUngriddedInterpolation( thisFunction); } } //else string data - leave numeric value alone } break; case METHOD_MATHML: /* * 3. MathML function evaluation required. */ solveMath(); if ( hasOutputScaleFactor_) { if ( isMatrix_) { matrix_ *= outputScaleFactor_; } else { value_ *= outputScaleFactor_; } } break; case METHOD_SCRIPT: /* * 4. Lua script function evaluation required. */ switch ( scriptType_) { case LUA_SCRIPT: solveLuaScript(); break; case EXPRTK_SCRIPT: default: solveExprTkScript(); break; } if ( hasOutputScaleFactor_) { if ( isMatrix_) { matrix_ *= outputScaleFactor_; } else { value_ *= outputScaleFactor_; } } break; case METHOD_ARRAY: if ( isMatrix_ && hasVarIdEntries_) { evaluateDataTable(); } break; case METHOD_MODEL: break; default: throw_message( runtime_error, setFunctionName( functionName) << "\n - Impossible situation - see VariableDef.cpp." ); break; } if ( isMatrix_) { if ( matrix_.size() == 1) { value_ = matrix_.matrixData()[0]; } } else { if ( !minValueString_.empty() && value_ < minValue_) value_ = minValue_; if ( !maxValueString_.empty() && value_ > maxValue_) value_ = maxValue_; if ( matrix_.size() != 1) { matrix_ = DMatrix( 1, 1, value_); } } if ( hasPerturbation_) { applyPerturbation(); } isCurrent_ = isCurrentable_; } //------------------------------------------------------------------------// double VariableDef::getValueSI() const { xmlUnits_.setValue( getValue()); return xmlUnits_.valueSI(); } //------------------------------------------------------------------------// double VariableDef::getValueMetric() const { xmlUnits_.setValue( getValue()); return xmlUnits_.valueMetric(); } //------------------------------------------------------------------------// const double& VariableDef::getVariance() { /* * Check whether the variance for the variableDef is current, or * the uncertainty type is a normal pdf. */ if ( !isCurrentVariance_) { const Uncertainty::UncertaintyPdf& pdf = uncertainty_.getPdf(); switch ( pdf) { case Uncertainty::UNIFORM_PDF: case Uncertainty::ERROR_PDF: // wrong PDF type variance_ = nan(); break; case Uncertainty::UNKNOWN_PDF: variance_ = 0.0; // no uncertainty specified isCurrentVariance_ = true; break; case Uncertainty::NORMAL_PDF: /* * Compute the variance of the Normal PDF for the variableDef. */ variance_ = computeVarianceForNormalPdf(); isCurrentVariance_ = true; break; default: break; } } return variance_; } //------------------------------------------------------------------------// double VariableDef::computeVarianceForNormalPdf() { static const aString functionName( "VariableDef::computeVarianceForNormalPdf()"); /* * Compute the variance of Normal PDF for the variableDef. */ bool appliedAtOutput = false; double variance = 0.0; double sigmaFactor = 0.0; double sdBound = 0.0; double stdDev; UncertaintyEffect effect = UNKNOWN_UNCERTAINTY; /* * check if applied directly to variable at output */ if ( !uncertainty_.isSet()) { switch ( variableMethod_) { case METHOD_FUNCTION: { const Function& thisFunction = janus_->getFunction( functionRef_); aOptionalSizeT tableRef = thisFunction.getTableRef(); if ( tableRef.isValid()) { Uncertainty& functionUncertainty = janus_->griddedTableDef_[ tableRef ].getUncertainty(); if ( ELEMENT_UNGRIDDEDTABLE == thisFunction.getTableType()) { functionUncertainty = janus_->ungriddedTableDef_[ tableRef ].getUncertainty(); } if ( functionUncertainty.isSet()) { effect = functionUncertainty.getEffect(); sdBound = functionUncertainty.getBounds()[0].getBound( functionRef_); sigmaFactor = 1.0 / (double)functionUncertainty.getNumSigmas(); appliedAtOutput = true; } } } /* FALLTHRU */ case METHOD_MATHML: if ( !appliedAtOutput) { size_t n = independentVarRef_.size(); vector<double> jacVec( n, 0.0); vector<double> tempVec( n, 0.0); vector<double> covar( n * n, 0.0); /* * no direct contribution from function or from MathML - call * recursively up independent variable tree */ for ( size_t i = 0; i < n; ++i) { size_t indxi = independentVarRef_[ i ]; jacVec[ i ] = getJacobianComponent( indxi); covar[ i + n * i ] = janus_->variableDef_[ indxi ].getVariance(); } for ( size_t i = 0; i < n; ++i) { for ( size_t j = i + 1; j < n; ++j) { if ( j != i) { // variances already set up size_t i1 = independentVarRef_[ i ]; size_t j1 = independentVarRef_[ j ]; size_t ij = j + n * i; size_t ji = i + n * j; // covariances double corrCoef = janus_->variableDef_[ i1 ].getCorrelationCoefficient( j1); covar[ ij ] = corrCoef * sqrt( covar[ i + n * i ] * covar[ j + n * j ]); covar[ ji ] = covar[ ij ]; } } } for ( size_t i = 0; i < n; ++i) { tempVec[ i ] = 0.0; for ( size_t j = 0; j < n; ++j) { size_t ij = j + n * i; tempVec[ i ] = tempVec[ i ] + covar[ ij ] * jacVec[ j ]; } } variance = 0.0; for ( size_t i = 0; i < n; ++i) { variance = variance + jacVec[ i ] * tempVec[ i ]; } } break; case METHOD_ARRAY: // @TODO What to do here break; default: throw_message( runtime_error, setFunctionName( functionName) << "\n - Impossible variance - see VariableDef.cpp." ); break; } } else { effect = uncertainty_.getEffect(); sdBound = uncertainty_.getBounds()[0].getBound(); sigmaFactor = 1.0 / (double)uncertainty_.getNumSigmas(); appliedAtOutput = true; } /* * */ if ( appliedAtOutput) { switch( effect) { case ADDITIVE_UNCERTAINTY: stdDev = sdBound * sigmaFactor; break; case MULTIPLICATIVE_UNCERTAINTY: stdDev = sdBound * getValue() * sigmaFactor; break; case PERCENTAGE_UNCERTAINTY: stdDev = sdBound / 100.0 * getValue() * sigmaFactor; break; case ABSOLUTE_UNCERTAINTY: stdDev = fabs( getValue() - sdBound) * sigmaFactor; break; default: stdDev = nan(); break; } variance = stdDev * stdDev; } return variance; } //------------------------------------------------------------------------// const double& VariableDef::getAdditiveBounds( const bool& isUpper) { /* * Check whether the bounds for the variableDef are current, or * the uncertainty type is a uniform pdf. */ if ( !isCurrentBound_) { const Uncertainty::UncertaintyPdf& pdf = uncertainty_.getPdf(); switch ( pdf) { case Uncertainty::NORMAL_PDF: case Uncertainty::ERROR_PDF: // wrong PDF type lowerBound_ = nan(); upperBound_ = nan(); break; case Uncertainty::UNKNOWN_PDF: // no uncertainty specified lowerBound_ = 0.0; upperBound_ = 0.0; isCurrentBound_ = true; break; case Uncertainty::UNIFORM_PDF: /* * Compute the additive bound of the Uniform PDF for the variableDef. */ computeAdditiveBoundsForUniformPdf(); isCurrentBound_ = true; break; default: break; } } if ( true == isUpper) { return upperBound_; } return lowerBound_; } //------------------------------------------------------------------------// void VariableDef::computeAdditiveBoundsForUniformPdf() { static const aString functionName( "VariableDef::computeAdditiveBoundsForUniformPdf()"); /* * Compute the additive bounds of the Uniform Pdf for the variableDef. */ bool appliedAtOutput = false; size_t nBound; double luBound[ 2 ] = { 0.0, 0.0}; UncertaintyEffect effect = UNKNOWN_UNCERTAINTY; /* * check if applied directly to variable at output */ if ( !uncertainty_.isSet()) { switch ( variableMethod_) { case METHOD_FUNCTION: { /* * first check for contribution from the function table itself */ const Function& thisFunction = janus_->getFunction( functionRef_); aOptionalSizeT tableRef = thisFunction.getTableRef(); if ( tableRef.isValid()) { Uncertainty& functionUncertainty = janus_->griddedTableDef_[ tableRef ].getUncertainty(); if ( ELEMENT_UNGRIDDEDTABLE == thisFunction.getTableType()) { functionUncertainty = janus_->ungriddedTableDef_[ tableRef ].getUncertainty(); } if ( functionUncertainty.isSet()) { const vector<Bounds>& bounds = functionUncertainty.getBounds(); nBound = bounds.size(); effect = functionUncertainty.getEffect(); for ( size_t i = 0; i < nBound; ++i) { // 1 or 2 bounds luBound[ i ] = bounds[ i ].getBound(); } appliedAtOutput = true; } } } /* FALLTHRU */ case METHOD_MATHML: if ( !appliedAtOutput) { size_t n = independentVarRef_.size(); double savedOutput = getValue(); double lowerBound = 0.0; double upperBound = 0.0; double output; /* * no direct contribution from function or from MathML - call * recursively up independent variable tree - for n input variables, * needs 2^n function evaluations */ unsigned long int nEvals = 2 << ( n - 1); vector<double> savedInput(n, 0.0); vector<double> inputBound(2*n, 0.0); vector<int> ulbit(n, 0); vector<size_t> ivar(n, 0); size_t ibits; for ( size_t i = 0; i < n; ++i) { size_t k = independentVarRef_[i]; ivar[i] = k; janus_->variableDef_[k].getAdditiveBounds( true); // set both bounds savedInput[i] = janus_->variableDef_[k].getValue(); inputBound[ 2 * i ] = janus_->variableDef_[k].getValue() + janus_->variableDef_[k].upperBound_; inputBound[ 2 * i + 1 ] = janus_->variableDef_[k].getValue() + janus_->variableDef_[k].lowerBound_; } for ( size_t i = 0; i < nEvals; ++i) { ibits = i; for ( int j = static_cast<int>( n) - 1; j >= 0; j--) { ulbit[j] = ( ibits & 1); ibits = ibits >> 1; } for ( size_t j = 0; j < n; ++j) { if ( !janus_->variableDef_[ ivar[j]].isMatrix()) { // @TODO: Temporary till vector/matrix support worked out janus_->variableDef_[ ivar[j]].setValueForUncertainty( inputBound[ 2 * j + ulbit[j]]); } } output = getValue() - savedOutput; lowerBound = std::min( lowerBound, output); upperBound = std::max( upperBound, output); } for ( size_t i = 0; i < n; ++i) { if ( !janus_->variableDef_[ ivar[i]].isMatrix()) { // @TODO: Temporary till vector/matrix support worked out janus_->variableDef_[ ivar[i]].setValueForUncertainty( savedInput[i]); } } getValue(); lowerBound_ = lowerBound; upperBound_ = upperBound; } break; case METHOD_ARRAY: // @TODO What to do here break; default: throw_message( runtime_error, setFunctionName( functionName) << "\n - Impossible bounds - see VariableDef.cpp." ); break; } } else { const vector<Bounds>& bounds = uncertainty_.getBounds(); nBound = bounds.size(); effect = uncertainty_.getEffect(); for ( size_t i = 0; i < nBound; ++i) { // 1 or 2 bounds luBound[ i ] = bounds[i].getBound(); } appliedAtOutput = true; } if ( appliedAtOutput) { double value = getValue(); /* * compute ADDITIVE uncertainties, -ve for lower bound and +ve for * upper bound */ lowerBound_ = - luBound[ 0 ]; if ( 1 == nBound) { upperBound_ = luBound[ 0 ]; } else { upperBound_ = luBound[ 1 ]; } switch( effect) { case ADDITIVE_UNCERTAINTY: break; case MULTIPLICATIVE_UNCERTAINTY: lowerBound_ *= value; upperBound_ *= value; break; case PERCENTAGE_UNCERTAINTY: lowerBound_ *= ( value * 0.01); upperBound_ *= ( value * 0.01); break; case ABSOLUTE_UNCERTAINTY: // must have 2 values lowerBound_ = -lowerBound_ - value; upperBound_ -= value; break; default: lowerBound_ = nan(); upperBound_ = nan(); break; } } } //------------------------------------------------------------------------// double VariableDef::getJacobianComponent( const aOptionalSizeT& indxi) { static const aString functionName( "VariableDef::getJacobianComponent()"); if ( !janus_->variableDef_[ indxi ].isMatrix()) { // Temporary check to avoid computing if variable is a vector or matrix double savedInput = janus_->variableDef_[ indxi ].value_; janus_->variableDef_[ indxi].setValueForUncertainty( savedInput - 1000.0 * EPS); double low = getValue(); janus_->variableDef_[ indxi].setValueForUncertainty( savedInput + 1000.0 * EPS); double high = getValue(); double result = ( high - low) / ( 2000.0 * EPS); janus_->variableDef_[ indxi].setValueForUncertainty( savedInput); getValue(); // reset any internal variables return result; } return 0.0; } //------------------------------------------------------------------------// double VariableDef::getCorrelationCoefficient( const size_t& indx2) { /* * correlation coefficient may be associated with either or both of the * variables - need to check both */ double result = 0.0; const Uncertainty& uncertainty1 = uncertainty_; const Uncertainty& uncertainty2 = janus_->variableDef_[ indx2 ].getUncertainty(); const vector<correlationPair>& correlationPair1 = uncertainty1.getCorrelation(); const vector<correlationPair>& correlationPair2 = uncertainty2.getCorrelation(); size_t correlationPair1size = correlationPair1.size(); for ( size_t i = 0; i < correlationPair1size; ++i) { if ( indx2 == correlationPair1[i].first) { result = correlationPair1[i].second; if ( 0.0 == result) { size_t correlationPair2size = correlationPair2.size(); for ( size_t j = 0; j < correlationPair2size; ++j) { if ((size_t)varIndex_ == correlationPair1[j].first) { result = correlationPair2[j].second; return result; } } } return result; } } return result; // should only reach here if there is no correlation } //------------------------------------------------------------------------// // @TODO :: Temporary internal function used by uncertainty calculations only void VariableDef::setValueForUncertainty( const double &x) { static const aString functionName( "VariableDef::setValueForUncertainty()"); value_ = x; if (isMatrix_) { matrix_ = x; } else { isMatrix_ = false; } isCurrent_ = isCurrentable_; for ( size_t j = 0; j < descendantsRef_.size(); ++j){ janus_->getVariableDef( descendantsRef_[ j ]).setNotCurrent(); } } //------------------------------------------------------------------------// void VariableDef::setValue( const double &x, bool isForced) { static const aString functionName( "VariableDef::setValue( double)"); if ( !inputWarningDone_ && variableType_ != TYPE_INPUT && !isForced) { inputWarningDone_ = true; warning_message( setFunctionName( functionName) << verbose << "\n - In DML file \"" << janus_->getXmlFileName() << "\"" << "\n - Attempting to set internal or output variable \"" << varID_ << "\"." << "\n - Consider using the <isInput/> element for this variable." ); } math_range_check( isForced_ = isForced; if ( !isForced_ && isMatrix_) { throw_message( range_error, setFunctionName( functionName) << "\n - Attempt to set a vector/matrix to a single value with variable \"" << varID_ << "\"." ); } ); value_ = x; if ( !minValueString_.empty() && value_ < minValue_) value_ = minValue_; if ( !maxValueString_.empty() && value_ > maxValue_) value_ = maxValue_; isMatrix_ = false; isCurrent_ = isCurrentable_; if ( hasPerturbation_) { applyPerturbation(); } for ( size_t j = 0; j < descendantsRef_.size(); ++j){ janus_->getVariableDef( descendantsRef_[ j ]).setNotCurrent(); math_range_check( janus_->getVariableDef( descendantsRef_[ j ]).setForced( isForced_)); } } //------------------------------------------------------------------------// void VariableDef::setValue( const dstomath::DVector &x, bool isForced) { static const aString functionName( "VariableDef::setValue( vector)"); if ( !inputWarningDone_ && variableType_ != TYPE_INPUT && !isForced) { inputWarningDone_ = true; warning_message( setFunctionName( functionName) << verbose << "\n - In DML file \"" << janus_->getXmlFileName() << "\"" << "\n - Attempting to set internal or output vector variable \"" << varID_ << "\"." << "\n - Consider using the <isInput/> element for this variable." ); } math_range_check( isForced_ = isForced; if ( x.size() != matrix_.size() || !matrix_.isVector()) { // Size must match and one of rows or cols must be 1, but not both. if ( isForced_) { matrix_.resize( x.size(), 1); } else { throw_message( range_error, setFunctionName( functionName) << "\n - Input vector dimensions are not compatible with variable \"" << varID_ << "\"." ); } } ); else_no_math_range_check( matrix_.resize( x.size(), 1); ); matrix_ = x; isMatrix_ = true; isCurrent_ = isCurrentable_; for ( size_t j = 0; j < descendantsRef_.size(); ++j){ janus_->getVariableDef( descendantsRef_[ j ]).setNotCurrent(); math_range_check( janus_->getVariableDef( descendantsRef_[ j ]).setForced( isForced_)); } return; } //------------------------------------------------------------------------// void VariableDef::setValue( const dstomath::DMatrix &x, bool isForced) { static const aString functionName( "VariableDef::setValue( matrix)"); if ( !inputWarningDone_ && variableType_ != TYPE_INPUT && !isForced) { inputWarningDone_ = true; warning_message( setFunctionName( functionName) << verbose << "\n - In DML file \"" << janus_->getXmlFileName() << "\"" << "\n - Attempting to set internal or output matrix variable \"" << varID_ << "\"." << "\n - Consider using the <isInput/> element for this variable." ); } math_range_check( isForced_ = isForced; if ( !isForced_ && !x.isSameDimension( matrix_)) { throw_message( range_error, setFunctionName( functionName) << "\n - Input matrix dimensions are not compatible with variable \"" << varID_ << "\"" << "\n - given " << x.rows() << "x" << x.cols() << " expected " << matrix_.rows() << "x" << matrix_.cols() << "." ); } ); matrix_ = x; isMatrix_ = true; isCurrent_ = isCurrentable_; for ( size_t j = 0; j < descendantsRef_.size(); ++j){ janus_->getVariableDef( descendantsRef_[ j ]).setNotCurrent(); math_range_check( janus_->getVariableDef( descendantsRef_[ j ]).setForced( isForced_)); } } //------------------------------------------------------------------------// void VariableDef::setValueSI( const double &xSI) { xmlUnits_.setValueSI( xSI); setValue( xmlUnits_.value()); } //------------------------------------------------------------------------// void VariableDef::setValueMetric( const double &xMetric) { xmlUnits_.setValueMetric( xMetric); setValue( xmlUnits_.value()); } //------------------------------------------------------------------------// void VariableDef::setFunctionRef( const aOptionalSizeT& functionRef) { functionRef_ = functionRef; /* * Append function table independent variables ancestors to the * ancestor list. */ size_t functionIndependentVarDefSize = janus_->getFunction()[functionRef].getInDependentVarDef().size(); // vector<size_t> independentVariables( functionIndependentVarDefSize, 0); for ( size_t i = 0; i < functionIndependentVarDefSize; ++i) { aOptionalSizeT indVarIndex = janus_->getFunction()[functionRef].getInDependentVarDef()[i].getVariableReference(); if ( indVarIndex > janus_->getVariableDef().size()) { throw_message( std::out_of_range, "Independent variable " << janus_->getFunction()[functionRef].getInDependentVarDef()[i].getVarID() << " referenced from function " << janus_->getFunction()[functionRef].getName() << " does not exist."); } independentVarRef_.push_back( indVarIndex); // independentVariables[i) = // janus_->getFunction()[ functionRef).getInDependentVarDef()[i).getVariableReference(); } //setAncestorCrossReferences( independentVarRef_); } //------------------------------------------------------------------------// void VariableDef::setMathMLDependencies() { MathMLData::crossReference_ci( mathCalculation_, janus_); if ( variableMethod_ == METHOD_MATHML) { hasMatrixOps_ = hasMatrixOps( mathCalculation_); } } //------------------------------------------------------------------------// const aString& VariableDef::getStringValue() { static const aString functionName( "VariableDef::getStringValue()"); /* * Check validity of table */ if ( !functionRef_.isValid()) { throw_message( range_error, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" is not a string table function." ); } Function& thisFunction = janus_->getFunction( functionRef_); aOptionalSizeT tableRef = thisFunction.getTableRef(); if (( !tableRef.isValid()) || ( ELEMENT_UNGRIDDEDTABLE == thisFunction.getTableType())) { throw_message( range_error, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" is not a string table function." ); } if ( janus_->griddedTableDef_[ tableRef].isStringDataTableEmpty()) { throw_message( range_error, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" is an empty string table function." ); } /* * this assumes string table is n-dimensional, and that the input index * matches one of the integer breakpoints in each dimension */ double x; size_t j, indxi = 0, indxj, indxiv, ibp; size_t nIndVar = independentVarRef_.size(); vector<size_t> nbp( nIndVar); for ( size_t i = 0; i < nIndVar; ++i) { ibp = janus_->griddedTableDef_[ tableRef].getBreakpointRef()[ i]; nbp[ i ] = janus_->breakpointDef_[ ibp].getBpVals().size(); } for ( int i = static_cast<int>( nIndVar) - 1; i >= 0; i--) { indxiv = thisFunction.getIndependentVarRef( aOptionalSizeT( i)); x = dstomath::nearbyint( janus_->getVariableDef()[ indxiv].getValue()); /* * find the breakpoint to which this corresponds */ indxj = 0; ibp = janus_->griddedTableDef_[ tableRef].getBreakpointRef()[ size_t( i)]; for ( j = 0; j < nbp[ i ]; j++) { if ( x == janus_->getBreakpointDef()[ ibp].getBpVals()[ j]) { indxj = j; break; } } if (( nIndVar - 1) == size_t( i)) { indxi = indxj; } else { indxi = indxi + indxj * nbp[ i + 1 ]; } } /* * Bound the index: 0 -- size()-1 */ indxi = dstomath::bound( indxi, size_t( 0), (janus_->griddedTableDef_[ tableRef].getStringData().size() - 1)); return janus_->griddedTableDef_[ tableRef].getStringData()[ indxi]; } //------------------------------------------------------------------------// void VariableDef::exportDefinition( DomFunctions::XmlNode& documentElement) { /* * Create a child node in the DOM for the VariableDef element */ DomFunctions::XmlNode childElement = DomFunctions::setChild( documentElement, "variableDef"); /* * Add attributes to the VariableDef child */ DomFunctions::setAttribute( childElement, "name", name_); DomFunctions::setAttribute( childElement, "varID", varID_); DomFunctions::setAttribute( childElement, "units", units_); if ( !axisSystem_.empty()) { DomFunctions::setAttribute( childElement, "axisSystem", axisSystem_); } if ( !sign_.empty()) { DomFunctions::setAttribute( childElement, "sign", sign_); } if ( !alias_.empty()) { DomFunctions::setAttribute( childElement, "alias", alias_); } if ( !symbol_.empty()) { DomFunctions::setAttribute( childElement, "symbol", symbol_); } if ( !initialValueString_.empty()) { DomFunctions::setAttribute( childElement, "initialValue", initialValueString_); } if ( !minValueString_.empty()) { DomFunctions::setAttribute( childElement, "minValue", aString("%").arg( minValue_)); } if ( !maxValueString_.empty()) { DomFunctions::setAttribute( childElement, "maxValue", aString("%").arg( maxValue_)); } /* * Add description element */ if ( !description_.empty()) { DomFunctions::setChild( childElement, "description", description_); } /* * Add the optional provenance entry to the VariableDef child */ if ( hasProvenance_) { provenance_.exportDefinition( childElement, isProvenanceRef_); } /* * Add the vector/matrix dimensions to the VariableDef child */ if ( dimensionDef_.getDimCount() > 0) { dimensionDef_.exportDefinition( childElement, isDimensionRef_); } /* * Add the calculation element if either MathML or a script is used * for this VariableDef child. This includes MathML scripts that have * been converted to ExprTk scripts. */ if ( mathCalculation_.mathChildren_.size() > 0 || !script_.empty()) { DomFunctions::XmlNode calculationElement = DomFunctions::setChild( childElement, "calculation"); if ( !script_.empty()) { exportScript( calculationElement); } else { exportMath( calculationElement); } } /* * Add the array element if the VariableDef child represents a non-computed * vector or matrix */ if ( array_.getArraySize() > 0) { array_.exportDefinition( childElement); } /* * Add the model element if the VariableDef child represents a dynamic system * model */ if ( !model_.getModelID().empty()) { model_.exportDefinition( childElement); } /* * Add the type tag elements to the VariableDef child */ if ( isInput_) { DomFunctions::setChild( childElement, "isInput"); } if ( isControl_) { DomFunctions::setChild( childElement, "isControl"); } if ( isDisturbance_) { DomFunctions::setChild( childElement, "isDisturbance"); } if ( isState_) { DomFunctions::setChild( childElement, "isState"); } if ( isStateDeriv_) { DomFunctions::setChild( childElement, "isStateDeriv"); } if ( isOutput_) { DomFunctions::setChild( childElement, "isOutput"); } if ( isStdAIAA_) { DomFunctions::setChild( childElement, "isStdAIAA"); } /* * Add the optional uncertainty entry to the VariableDef child * only if it was defined when initially parsing a file or it was * explicitly set */ if ( hasUncertainty_ && exportUncertainty_) { uncertainty_.exportDefinition( childElement); } // if ( script_.empty() && mathCalculation_.mathChildren_.size() == 0 // && hasUncertainty_) { // uncertainty_.exportDefinition( childElement); // } } //------------------------------------------------------------------------// void VariableDef::readDefinitionFromDom( const DomFunctions::XmlNode& xmlElement) { static const aString functionName( "VariableDef::readDefinitionFromDom()"); try { switch ( elementType_) { case ELEMENT_ARRAY: initialiseArray( xmlElement); break; case ELEMENT_CALCULATION: initialiseCalculation( xmlElement); break; case ELEMENT_SCRIPT: initialiseScript( xmlElement); break; case ELEMENT_DIMENSION: dimensionDef_.initialiseDefinition( xmlElement); hasDimensionDef_ = true; break; case ELEMENT_MATH: initialiseMath( xmlElement); /* * Try converting MathMl to an equivalent script representation. * This is done for simple MathML expressions to increase the * speed of runtime execution. */ if ( janus_->getMathML_to_ExprTk()) { try { script_ = mathML_to_ExprTkScript( xmlElement, varID_); #ifdef _DEBUG_ cout << "---------------------------------------" << endl; cout << "VARID = " << varID_ << " =\n" << endl; cout << script_ << endl << endl; #endif } #ifndef _DEBUG_ catch( exception& ) { script_.clear(); #else catch( exception &excep) { script_.clear(); cout << "VARID: MathML script conversion to ExprTk failed...\n" << excep.what() << endl; #endif } catch(...) { script_.clear(); #ifdef _DEBUG_ cout << "VARID: MathML script conversion to ExprTk failed." << endl; #endif } } break; case ELEMENT_MODEL: initialiseModel( xmlElement); break; case ELEMENT_PROVENANCE: provenance_.initialiseDefinition( xmlElement); hasProvenance_ = true; break; case ELEMENT_PERTURBATION: initialisePerturbation( xmlElement); break; default: break; } } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } } //------------------------------------------------------------------------// bool VariableDef::compareElementID( const DomFunctions::XmlNode& xmlElement, const aString& elementID, const size_t& /*documentElementReferenceIndex*/) { switch ( elementType_) { case ELEMENT_PROVENANCE: if ( DomFunctions::getAttribute( xmlElement, "provID") != elementID) { return false; } isProvenanceRef_ = true; break; case ELEMENT_DIMENSION: if ( DomFunctions::getAttribute( xmlElement, "dimID") != elementID) { return false; } isDimensionRef_ = true; break; default: return false; break; } readDefinitionFromDom( xmlElement); return true; } //------------------------------------------------------------------------// void VariableDef::resetJanus( Janus *janus) { janus_ = janus; /* * Reset the Janus pointer in the Uncertainty class */ uncertainty_.resetJanus( janus); /* * Reset the Janus pointer in the MathMLDataClass class */ MathMLData::crossReference_ci( mathCalculation_, janus); /* * Reset the Kaguya/Lua, ExprTk script function pointer. */ deleteLuaFunction(); deleteExprTkFunction(); } //------------------------------------------------------------------------// void VariableDef::initialiseBaseVariableDef( const DomFunctions::XmlNode& variableDefElement) { static const aString functionName( "VariableDef::initialiseBaseVariableDef()"); /* * Retrieve attributes for the Variable Definition */ name_ = DomFunctions::getAttribute( variableDefElement, "name"); varID_ = DomFunctions::getAttribute( variableDefElement, "varID"); units_ = DomFunctions::getAttribute( variableDefElement, "units"); sign_ = DomFunctions::getAttribute( variableDefElement, "sign"); alias_ = DomFunctions::getAttribute( variableDefElement, "alias"); symbol_ = DomFunctions::getAttribute( variableDefElement, "symbol"); axisSystem_ = DomFunctions::getAttribute( variableDefElement, "axisSystem"); /* * Retrieve the description associated with the variable */ description_ = DomFunctions::getChildValue( variableDefElement, "description"); /* * Provenance definition */ elementType_ = ELEMENT_PROVENANCE; try { DomFunctions::initialiseChildOrRef( this, variableDefElement, varID_, "provenance", "provenanceRef", "provID", false); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } /* * Variable Type Definitions */ isInput_ = DomFunctions::isChildInNode( variableDefElement, "isInput"); if ( isInput_) { variableType_ = TYPE_INPUT; } if ( !isInput_) { isControl_ = DomFunctions::isChildInNode( variableDefElement, "isControl"); if ( isControl_) { variableType_ = TYPE_INPUT; } } if ( !isInput_ && !isControl_) { isDisturbance_ = DomFunctions::isChildInNode( variableDefElement, "isDisturbance"); if ( isDisturbance_) { variableType_ = TYPE_INPUT; } } isOutput_ = DomFunctions::isChildInNode( variableDefElement, "isOutput"); if ( isOutput_) { variableType_ = TYPE_OUTPUT; /* * this element has not yet been appended to the variableDef_ vector, * so it will go in position "size()" */ janus_->outputIndex_.push_back( janus_->variableDef_.size()); } /* * Variable Flag Definitions */ isState_ = DomFunctions::isChildInNode( variableDefElement, "isState"); isStateDeriv_ = DomFunctions::isChildInNode( variableDefElement, "isStateDeriv"); isStdAIAA_ = DomFunctions::isChildInNode( variableDefElement, "isStdAIAA"); /* * Is this a perturbation */ elementType_ = ELEMENT_PERTURBATION; try { DomFunctions::initialiseChild( this, variableDefElement, varID_, "isPerturbation", false); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } /* * Uncertainty is processed in Janus, since it requires cross-referencing. * Just set the uncertainty flag if it is present for this variableDef. */ hasUncertainty_ = DomFunctions::isChildInNode( variableDefElement, "uncertainty"); exportUncertainty_ = hasUncertainty_; /* * Retrieve Calculation definition */ elementType_ = ELEMENT_CALCULATION; try { DomFunctions::initialiseChild( this, variableDefElement, varID_, "calculation", false); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } return; } //------------------------------------------------------------------------// void VariableDef::initialiseCalculation( const DomFunctions::XmlNode& xmlElement) { static const aString functionName( "VariableDef::initialiseCalculation()"); isCurrent_ = false; /* * Check the entries for the calculation element to check that it has * valid content. If neither of a "math" or "script" sub-element have * been specified then provide a error message and exit the function */ bool isMathAvailable = DomFunctions::isChildInNode( xmlElement, "math"); bool isScriptAvailable = DomFunctions::isChildInNode( xmlElement, "script"); if ( !( isMathAvailable ^ isScriptAvailable)) { throw_message( range_error, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" has neither or both the \"math\" and \"script\" elements specified." ); } /* * Parse either the "math" or "script" element */ if ( isMathAvailable) { /* * Get the highest level <apply> child node within the <math> * child node. NB this assumes the child element is tagged as * <mathml2:math>. Note there can be multiple <apply> nodes * below <math>, but only the highest is the pointer to the * complete function. If there is no calculation involved, but just * straight equality to another variable value or to a constant, this * may also be <ci> or <cn>. There are also numerous other top-level * components allowed by the MathML spec. These may be added as * required. Math tags may include alternative namespace form */ variableMethod_ = METHOD_MATHML; elementType_ = ELEMENT_MATH; if ( DomFunctions::isChildInNode( xmlElement, "math")) { try { DomFunctions::initialiseChild( this, xmlElement, varID_, "math", false); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } } else { try { DomFunctions::initialiseChild( this, xmlElement, varID_, "mathml2:math", false); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } } } else if ( isScriptAvailable) { /* * Retrieve Script definition */ variableMethod_ = METHOD_SCRIPT; elementType_ = ELEMENT_SCRIPT; try { DomFunctions::initialiseChild( this, xmlElement, varID_, "script", false); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } } } //------------------------------------------------------------------------// void VariableDef::initialiseScript( const DomFunctions::XmlNode& xmlElement) { static const aString functionName( "VariableDef::initialiseScript()"); script_ = DomFunctions::getCData( xmlElement); aString scriptType = DomFunctions::getAttribute( xmlElement, "type", true); if ( scriptType.toLowerCase() == "exprtk") { scriptType_ = EXPRTK_SCRIPT; initialiseExprTkScript(); } else if ( scriptType.toLowerCase() == "lua") { scriptType_ = LUA_SCRIPT; initialiseLuaScript(); } else { aString scriptTypes = "ExprTk"; aString elseNote; #ifdef HAVE_KAGUYA scriptTypes += " and Lua"; #else elseNote = "\nNote: Lua scripts have not been compiled into this version of Janus."; #endif throw_message( invalid_argument, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" - Only " << scriptTypes << " scripts currently supported." << elseNote ); } isCurrent_ = false; variableMethod_ = METHOD_SCRIPT; } //------------------------------------------------------------------------// void VariableDef::initialiseArray( const DomFunctions::XmlNode& xmlElement) { static const aString functionName( "VariableDef::initialiseArray()"); isCurrent_ = false; variableMethod_ = METHOD_ARRAY; try { array_.initialiseDefinition( xmlElement); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } /* * Once the array data has been read need to check the * dimension size against number of points. * If not consistent then trigger an error command. * If consistent need to convert the data table to * numeric representations, set up ancestry and * descendant linkages. */ instantiateDataTable(); } //------------------------------------------------------------------------// void VariableDef::initialiseModel( const DomFunctions::XmlNode& xmlElement) { static const aString functionName( "VariableDef::initialiseModel()"); isCurrent_ = false; variableMethod_ = METHOD_MODEL; try { model_.initialiseDefinition( xmlElement); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - " << excep.what() ); } } //------------------------------------------------------------------------// void VariableDef::initialiseMath( const DomFunctions::XmlNode& xmlElement) { static const aString functionName( "VariableDef::initialiseMath()"); /* * NOTE: attributes of the <math> element are ignored as they are primarily * for presentation of the MathML content, and therefore, do not contribute * to defining how a mathematical expression should be evaluated. */ DomFunctions::XmlNodeList childList; /* * Retrieve a list of the children for the 'math' element */ try { childList = DomFunctions::getChildren( xmlElement, EMPTY_STRING, varID_); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - for ID \"" << varID_ << "\"\n - " << excep.what() ); } /* * find one and only one of the allowable children of this element */ size_t childListLength = childList.size(); size_t numberOfValidChildren = 0; size_t offset = 0; aString childName; bool isApply = true; for ( size_t i = 0; i < childListLength; ++i) { childName = DomFunctions::getChildName( childList[ i]).trim(); if ( childName == "apply") { isApply = true; offset = i; numberOfValidChildren++; } else if (( childName == "ci") || ( childName == "cn") || ( childName == "piecewise") || ( childName == "pi") || ( childName == "exponentiale") || ( childName == "notanumber") || ( childName == "eulergamma") || ( childName == "infinity")) { isApply = false; offset = i; numberOfValidChildren++; } else if ( childName.size()) { throw_message( range_error, setFunctionName( functionName) << "\n - for ID \"" << varID_ << "\", support for tag \"" << childName << "\" is not provided." ); } if ( numberOfValidChildren > 1) { throw_message( range_error, setFunctionName( functionName) << "\n - ID \"" << varID_ << "\" has more than 1 valid top level tag in <math> definition." ); } } if ( 0 == numberOfValidChildren) { throw_message( range_error, setFunctionName( functionName) << "\n - ID \"" << varID_ << "\" has no valid top level tags in <math> definition." ); } /* * set up the MathML equation and cross-references for this variable, * only looking for cross-references to previously-defined variables */ try { dstomathml::parsemathml::parse( childList[ offset], mathCalculation_); } catch ( exception &excep) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - ID \"" << varID_ << "\"\n - " << excep.what() ); } /* * set up the cross-references for this variable. Only looking for * cross-references to previously-defined variables */ DomFunctions::XmlNodeList ciList; if ( isApply) { DomFunctions::getNodesByName( childList[ offset], "ci", ciList); } else { DomFunctions::getNodesByName( xmlElement, "ci", ciList); } size_t ciListSize = ciList.size(); for ( size_t j = 0; j < ciListSize; ++j) { aString ciVarId = DomFunctions::getCData( ciList[j]).trim(); aOptionalSizeT ciVarIndex = janus_->crossReferenceId( ELEMENT_VARIABLE, ciVarId); if ( ciVarIndex.isValid()) { independentVarRef_.push_back( ciVarIndex); } else { throw_message( range_error, setFunctionName( functionName) << "\n - ID \"" << ciVarId << "\" is not in VariableDef list." ); } } } //------------------------------------------------------------------------// void VariableDef::solveMath() const { if ( !hasMatrixOps_) { value_ = mathCalculation_.mathMLFunctionPtr_( mathCalculation_); } else { mathCalculation_.mathMLMatrixFunctionPtr_( mathCalculation_); math_range_check( if ( !isForced_) { if ( mathCalculation_.isMatrix_ != isMatrix_) { if ( isMatrix_) { throw_message( range_error, setFunctionName( "VariableDef::solveMath()") << "\n - ID \"" << varID_ << "\" expected a matrix not a single value." ); } else { throw_message( range_error, setFunctionName( "VariableDef::solveMath()") << "\n - ID \"" << varID_ << "\" expected a single value not a matrix." ); } } if ( isMatrix_ && !mathCalculation_.matrix_.isSameDimension( matrix_)) { throw_message( range_error, setFunctionName( "VariableDef::solveMath()") << "\n - ID \"" << varID_ << "\" expected a " << matrix_.rows() << "x" << matrix_.cols() << " matrix not a " << mathCalculation_.matrix_.rows() << "x" << mathCalculation_.matrix_.cols() << " matrix." ); } } ); if ( mathCalculation_.isMatrix_) { isMatrix_ = true; matrix_ = mathCalculation_.matrix_; } else { isMatrix_ = false; value_ = mathCalculation_.value_; } } } //------------------------------------------------------------------------// bool VariableDef::hasMatrixOps() const { if ( isMatrix_) { return true; } if ( variableMethod_ == METHOD_MATHML) { hasMatrixOps_ = hasMatrixOps( mathCalculation_); return hasMatrixOps_; } return false; } //------------------------------------------------------------------------// bool VariableDef::hasMatrixOps( const dstomathml::MathMLData &t) const { if ( t.variableDef_) { if ( t.variableDef_->isMatrix_) { // Variable is a matrix. return true; } if ( t.variableDef_->hasMatrixOps()) { // See if this variable has dependent matrix ops. return true; } } else if ( !t.mathMLFunctionPtr_ && t.mathMLMatrixFunctionPtr_) { return true; // Function not found in single double value table. Use matrix table instead. } for ( MathMLDataVector::const_iterator child = t.mathChildren_.begin(); child != t.mathChildren_.end(); ++child) { if ( hasMatrixOps( *child)) { return true; } } return false; } //------------------------------------------------------------------------// void VariableDef::exportScript( DomFunctions::XmlNode& documentElement) { /* * Create a child node in the DOM for the math element * * NOTE: attributes of the <math> element are ignored as they are primarily * for presentation of the MathML content, and therefore, do not contribute * to defining how a mathematical expression should be evaluated. */ if ( mathCalculation_.mathChildren_.size() > 0) { DomFunctions::setComment( documentElement, " MathML script converted to ExprTk script "); } DomFunctions::XmlNode childElement = DomFunctions::setChildCData( documentElement, "script", script_); DomFunctions::setAttribute( childElement, "type", ( scriptType_ == LUA_SCRIPT) ? "lua" : "exprtk"); } //------------------------------------------------------------------------// void VariableDef::exportMath( DomFunctions::XmlNode& documentElement) { /* * Create a child node in the DOM for the math element * * NOTE: attributes of the <math> element are ignored as they are primarily * for presentation of the MathML content, and therefore, do not contribute * to defining how a mathematical expression should be evaluated. */ DomFunctions::XmlNode childElement = DomFunctions::setChild( documentElement, "math"); /* * Traverse the mathCalculation_ construct to create the mathML tree */ dstomathml::exportmathml::exportMathMl( childElement, mathCalculation_); } //------------------------------------------------------------------------// void VariableDef::instantiateDataTable() { static const aString functionName( "VariableDef::instantiateDataTable()"); /* * Once the array data has been read need to check the * dimension size against number of points. * If not consistent then trigger an error command. * If consistent need to convert the data table to * numeric representations, set up ancestry and * descendant linkages. */ size_t nrows = 0; size_t ncols = 0; if ( dimensionDef_.getDimTotal() == array_.getArraySize()) { nrows = matrix_.rows(); ncols = matrix_.cols(); matrixVarId_.resize( nrows, ncols, aOptionalSizeT()); matrixScaleFactor_.resize( nrows, ncols); if ( dimensionDef_.getDimCount() > 1) { nrows = dimensionDef_.getDim( dimensionDef_.getDimCount() - 2); } /* * Evaluate the data table from the array class and * determine the ancestry relationships. */ size_t j = 0; size_t k = 0; size_t offset = 1; size_t nStart = 0; aString dataEntry; int minusFactor = 1; hasVarIdEntries_ = false; const aStringList& dataTable = array_.getStringDataTable(); size_t arrayLength = array_.getArraySize(); for ( size_t i = 0; i < arrayLength; ++i) { minusFactor = 1; dataEntry = dataTable[ i]; if ( dataEntry.isNumeric()) { matrix_(( j * offset), k) = dataEntry.toDouble(); matrixVarId_(( j * offset), k) = aOptionalSizeT(); matrixScaleFactor_(( j * offset), k) = 1.0; } else { // Need to convert this to a numeric value and populate ancestry data. // If first character is a '-' need to set the minusFactor to -1. nStart = dataEntry.find_first_not_of( "-"); if ( nStart != 0) { minusFactor = -1; dataEntry = dataEntry.substr( nStart); } // Note: Can't populate the matrix_ element at this point, especially if it relies on MathML aOptionalSizeT matrixVarIDIndex = janus_->crossReferenceId( ELEMENT_VARIABLE, dataEntry); if ( matrixVarIDIndex.isValid()) { matrixVarId_(( j * offset), k) = matrixVarIDIndex; matrixScaleFactor_(( j * offset), k) = minusFactor; independentVarRef_.push_back( matrixVarId_(( j * offset), k)); hasVarIdEntries_ = true; } else { throw_message( range_error, setFunctionName( functionName) << "\n - ID \"" << matrixVarIDIndex << " : " << dataEntry << "\" is not in VariableDef list." ); } } ++k; k %= ncols; if ( k == 0) { ++j; j %= nrows; } if ( j == nrows) { j = 0; ++offset; } } if ( !hasVarIdEntries_) { isCurrent_ = true; } } else { throw_message( range_error, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" array size incompatible with defined dimensions." ); } } //------------------------------------------------------------------------// void VariableDef::evaluateDataTable() const { for ( size_t i = 0; i < matrix_.rows(); ++i) { for ( size_t j = 0; j < matrix_.cols(); ++j) { if ( matrixVarId_( i, j).isValid()) { matrix_( i, j) = janus_->getVariableDef( matrixVarId_( i, j)).getValue() * matrixScaleFactor_( i, j); } } } } //------------------------------------------------------------------------// double VariableDef::evaluateDataEntry( const aString &dataEntry) { static const aString functionName( "VariableDef::evaluateDataEntry()"); VariableDef* variableDef = janus_->findVariableDef( dataEntry); if ( variableDef == 0) { throw_message( range_error, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" alpha-numeric varID array element not defined before use." ); } return variableDef->getValue(); } //------------------------------------------------------------------------// void VariableDef::initialisePerturbation( const DomFunctions::XmlNode& xmlElement) { static const aString functionName( "VariableDef::initialisePerturbation()"); // Get target variableRef const aString perturbationTargetVarId = DomFunctions::getAttribute( xmlElement, "variableRef", true); perturbationTargetVarIndex_ = janus_->getVariableIndex( perturbationTargetVarId); if ( !perturbationTargetVarIndex_.isValid()) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" - Invalid perturbation variableRef \"" << perturbationTargetVarId << "\"." ); } // Check effect is valid const aString effectString = DomFunctions::getAttribute( xmlElement, "effect", true); aOptionalInt effect = Uncertainty::uncertaintyAttributesMap.get( effectString); if ( effect.isValid() && ( effect.value() == ADDITIVE_UNCERTAINTY || effect.value() == MULTIPLICATIVE_UNCERTAINTY)) { perturbationEffect_ = UncertaintyEffect( effect.value()); } else { throw_message( invalid_argument, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" - Invalid perturbation effect \"" << effectString << "\"." ); } } //------------------------------------------------------------------------// void VariableDef::setPerturbation( UncertaintyEffect uncertaintyEffect, const double& value) { static const aString functionName( "VariableDef::setPerturbation()"); if ( uncertaintyEffect != MULTIPLICATIVE_UNCERTAINTY && uncertaintyEffect != ADDITIVE_UNCERTAINTY) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - varID \"" << varID_ << "\" - Invalid perturbation effect set \"" << Uncertainty::uncertaintyAttributesMap.get( uncertaintyEffect, "Unknown Uncertainty") << "\"." ); } auto setupPerturbation = [&]( VariableDef& ptb) -> void { ptb.variableMethod_ = METHOD_PLAIN_VARIABLE; ptb.value_ = value; ptb.perturbationEffect_ = uncertaintyEffect; ptb.xmlUnits_ = aUnits( ptb.perturbationEffect_ == MULTIPLICATIVE_UNCERTAINTY ? "nd" : xmlUnits_.unitsMetric(), value); }; if ( hasPerturbation_) { setupPerturbation( janus_->getVariableDef( associatedPerturbationVarIndex_)); isCurrent_ = false; return; } const size_t thisIdx = janus_->getVariableIndex( varID_); const size_t newIdx = janus_->variableDef_.size(); VariableDef newVariableDef; setupPerturbation( newVariableDef); newVariableDef.resetJanus( janus_); newVariableDef.perturbationTargetVarIndex_ = thisIdx; vector<size_t> descendants = getDescendantsRef(); descendants.push_back( thisIdx); newVariableDef.setDescendantsRef( descendants); ancestorsRef_.push_back( newIdx); janus_->variableDef_.push_back( newVariableDef); setPerturbationVarIndex( newIdx); } //------------------------------------------------------------------------// void VariableDef::setPerturbationVarIndex( const size_t index) { static const aString functionName( "VariableDef::setPerturbationVarIndex()"); if ( hasPerturbation_) { throw_message( runtime_error, setFunctionName( "Janus::setPerturbationVarIndex( size_t index)") << "\n - perturbation is already associated with this variable." << "\n - varID: \"" << varID_ << "\"" ); } const VariableDef& perturbation = janus_->getVariableDef( index); // Check unit compatibility. switch ( perturbation.perturbationEffect_) { case ADDITIVE_UNCERTAINTY: if ( !xmlUnits_.isCompatible( perturbation.xmlUnits_, false)) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - varID \"" << perturbation.getVarID() << "\" - additive perturbation must have units compatible with the perturbation target." ); } break; case MULTIPLICATIVE_UNCERTAINTY: { const aString units = perturbation.xmlUnits_.units(); if ( !( units == "ND" || units == "nd" || units == "")) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - varID \"" << perturbation.getVarID() << "\" - multiplicative perturbation must be non-dimensional." ); } } break; default: break; } // Check axis system compatibility. if ( perturbation.getAxisSystem().trim().toLowerCase() != getAxisSystem().trim().toLowerCase()) { throw_message( invalid_argument, setFunctionName( functionName) << "\n - varID \"" << perturbation.getVarID() << "\" - the axisSystem does not match that of the perturbation target." ); } // TODO: Matrix compatibility check if ( isMatrix_) { throw_message( runtime_error, "\n - matrix perturbations are not yet supported." ); } associatedPerturbationVarIndex_ = index; hasPerturbation_ = true; independentVarRef_.push_back( index); isCurrent_ = false; } //------------------------------------------------------------------------// void VariableDef::applyPerturbation() const { const VariableDef& perturbation = janus_->getVariableDef( associatedPerturbationVarIndex_); if ( isMatrix_) { // TODO: Matrix handling throw_message( runtime_error, "\n - matrix perturbations are not yet supported" ); } else { switch ( perturbation.perturbationEffect_) { case ADDITIVE_UNCERTAINTY: { xmlUnits_.setValue( value_); const double valueSI = xmlUnits_.valueSI(); xmlUnits_.setValueSI( valueSI + perturbation.getValueSI()); value_ = xmlUnits_.value(); } break; case MULTIPLICATIVE_UNCERTAINTY: value_ *= perturbation.getValue(); break; default: break; } } } //------------------------------------------------------------------------// ostream& operator<< ( ostream& os, const VariableDef& variableDef) { /* * General properties of the Class */ os << endl << endl << "Display VariableDef contents:" << endl << "-----------------------------------" << endl; os << " name : " << variableDef.getName() << endl << " varID : " << variableDef.getVarID() << endl << " units : " << variableDef.getUnits() << endl << " axisSystem : " << variableDef.getAxisSystem() << endl << " sign : " << variableDef.getSign() << endl << " alias : " << variableDef.getAlias() << endl << " symbol : " << variableDef.getSymbol() << endl << " initialValue : " << variableDef.getInitialValue() << endl << " maxValue : " << variableDef.getMinValue() << endl << " minValue : " << variableDef.getMaxValue() << endl << endl; os << " isInput : " << variableDef.isInput() << endl << " isControl : " << variableDef.isControl() << endl << " isDisturbance : " << variableDef.isDisturbance() << endl << " isOutput : " << variableDef.isOutput() << endl << " isState : " << variableDef.isState() << endl << " isStateDeriv : " << variableDef.isStateDeriv() << endl << " isStdAIAA : " << variableDef.isStdAIAA() << endl << endl; os << " description : " << variableDef.getDescription() << endl << " hasProvenance : " << variableDef.hasProvenance() << endl << " hasUncertainty : " << variableDef.hasUncertainty() << endl << " hasDimension : " << variableDef.hasDimension() << endl << endl; /* * Provenance data for the Class */ if ( variableDef.hasProvenance()) { os << variableDef.getProvenance() << endl; } /* * Uncertainty data for the Class */ if ( variableDef.hasUncertainty()) { os << variableDef.uncertainty_ << endl; } /* * Dimension data for the Class */ if ( variableDef.hasDimension()) { os << variableDef.getDimension() << endl; } /* * function table reference */ aOptionalSizeT functionRef = variableDef.getFunctionRef(); os << " Function table Ref : " << functionRef << endl; if ( functionRef.isValid()) { os << variableDef.janus_->getFunction()[ functionRef] << endl; } /* * Independent variable data */ size_t independentVarCount = variableDef.getIndependentVarCount(); os << " # independent vars : " << independentVarCount << endl; if ( 0 < independentVarCount) { vector<size_t> independentVarRefs = variableDef.getIndependentVarRef(); for ( size_t i = 0; i < independentVarCount; ++i) { os << " independent var # : "<< i << " : Reference :" << independentVarRefs[ i] << endl; } } /* * Ancestor variable data */ size_t ancestorCount = variableDef.getAncestorCount(); os << " # ancestor vars : " << ancestorCount << endl; if ( 0 < ancestorCount) { vector<size_t> ancestorRefs = variableDef.getAncestorsRef(); for ( size_t i = 0; i < ancestorCount; ++i) { os << " ancestor variable #: "<< i << " : Reference :" << ancestorRefs[ i] << endl; } } /* * Descendent variable data */ size_t descendantCount = variableDef.getDescendantsRef().size(); os << " # descendant vars : " << descendantCount << endl; if ( 0 < descendantCount) { vector<size_t> descendantRefs = variableDef.getDescendantsRef(); for ( size_t i = 0; i < descendantCount; ++i) { os << " descendant variable #: " << i << " : Reference :" << descendantRefs[ i] << endl; } } // @TODO More to add // os << " cnValue : " << variableDef.mathCalculation_.cnValue_ << endl; // // if ( variableDef.mathCalculation_.mathRetType_ == dstomathml::BOOL) { // os << " mathRetType : BOOL" << endl; // } // else { // os << " mathRetType : REAL" << endl; // } // os << " # children : " << variableDef.mathCalculation_ << endl; os << "-----------------" << endl; return os; } //------------------------------------------------------------------------// } // namespace janus
01e687870a5791594585187af7887c0c96a6d91b
84811d492da05a6a680f402ca340d46f5cec8f08
/lul.cpp
2a2e11cd673d4b45675e69bae9df65c5a7cbd8d6
[]
no_license
xKarfi/maturka-zad-2.1
cd38b9e53e4c66365fba653994ca398452b4593f
85d89fd53ab6242ca1fe9684b77cd25a2107a25e
refs/heads/main
2022-12-24T04:51:11.848103
2020-10-07T13:00:48
2020-10-07T13:00:48
302,037,175
0
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
lul.cpp
#include <iostream> using namespace std; int y; int k; void algo(double x, int k) { double y; cout<<"0,"; y=x; for(int i=0; i<k; i++) { if(y>=0.67) { cout<<"2"; } if(y>=0.33 && y<0.66) { cout<<"1"; } if(y<0.33) { cout<<"0"; } y*=3; if(y>=2) { y -= 2; } else if(y>=1) { y-= 1; } } } int main(int argc, char** argv) { algo(0.33, 4); return 0; }
534c939322746344ca3e35c9f5426a8516507499
f3ed29d56c31168989ab88f160e4dd9f058df587
/source/frontend/views/custom_widgets/rmv_resource_details.h
051bb74ce04ef90116f292362487a5f988364129
[ "MIT" ]
permissive
bofh80/radeon_memory_visualizer
6301598244f6238e298d2236947553ed302fe085
a331b4472dafe15badfe1e0ebf4fe850779f7e41
refs/heads/master
2023-02-03T14:10:05.888254
2020-12-03T14:23:35
2020-12-08T20:40:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,872
h
rmv_resource_details.h
//============================================================================= /// Copyright (c) 2018-2020 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file /// \brief Header for the resource details widget. This is the details /// widget at the bottom of the resource overview that's shown when a resource /// is clicked on. //============================================================================= #ifndef RMV_VIEWS_CUSTOM_WIDGETS_RMV_RESOURCE_DETAILS_H_ #define RMV_VIEWS_CUSTOM_WIDGETS_RMV_RESOURCE_DETAILS_H_ #include <QGraphicsObject> #include "rmt_resource_list.h" #include "rmt_virtual_allocation_list.h" #include "views/colorizer.h" static const int kResourceDetailsHeight = 50; /// Describes an allocation details widget. struct RMVResourceDetailsConfig { uint32_t width; ///< Widget width. uint32_t height; ///< Widget height. RmtResource resource; ///< A copy of the resource. bool resource_valid; ///< Is the resource above valid. bool allocation_thumbnail; ///< Should the allocation rendering on the left be included? const Colorizer* colorizer; ///< The colorizer used to color this widget. }; /// Container class for resource details which is rendered in resource overview and allocation delta pane. class RMVResourceDetails : public QGraphicsObject { Q_OBJECT public: /// Constructor. /// \param config A configuration struct for this object. explicit RMVResourceDetails(const RMVResourceDetailsConfig& config); /// Destructor. virtual ~RMVResourceDetails(); /// Implementation of Qt's bounding volume for this item. /// \return The item's bounding rectangle. virtual QRectF boundingRect() const Q_DECL_OVERRIDE; /// Implementation of Qt's paint for this item. /// \param painter The painter object to use. /// \param item Provides style options for the item, such as its state, exposed area and its level-of-detail hints. /// \param widget Points to the widget that is being painted on if specified. virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* item, QWidget* widget) Q_DECL_OVERRIDE; /// Update the current resource. /// \param resource The resource to update. void UpdateResource(const RmtResource* resource); /// Set width and height of the QGraphicsView being drawn into. /// \param width The width. /// \param height The height. void UpdateDimensions(int width, int height); /// Get the resource being displayed. /// \return The resource. const RmtResource* GetResource() const; private: RMVResourceDetailsConfig config_; ///< Description of this widget. }; #endif // RMV_VIEWS_CUSTOM_WIDGETS_RMV_RESOURCE_DETAILS_H_
5a1e526a8ca9b215d7fa373bcac74af2ff40329b
d8a34d78b312518a3c057b82e25f98d42f573463
/src/main.cpp
203d898b55e6bee48ccf9de922cd6192dc2e0fa0
[]
no_license
abred/Shadow-Volume
885c4be5035d7ca3e0effd7055771d00d917da8a
caacdda0193b632c12e8613a826372cee4073c90
refs/heads/master
2021-01-18T14:19:15.899953
2018-04-24T15:46:54
2018-04-24T15:46:54
4,617,847
0
0
null
null
null
null
UTF-8
C++
false
false
21,757
cpp
main.cpp
#include <iostream> #include <glf.hpp> #include <gli/gli.hpp> #include <gli/gtx/gl_texture2d.hpp> //GLuint textureID(0); GLuint texFloorID(0); std::vector<glm::vec4> objVertices; std::vector<glm::vec4> objNormals; std::vector<glm::vec2> objTexCoord; //std::vector<GLushort> objIndices; //std::string objName = glf::MESH_DIRECTORY + "Imrod_LowPoly/ImrodLowPoly2.obj"; //std::string objName = glf::MESH_DIRECTORY + "Imrod_LowPoly/untitled2.obj"; std::string const NAME = "OpenGL Varying structs"; std::string const AMBIENT_VERTEX_SHADER(glf::SHADER_DIRECTORY + "ambient.vert"); std::string const AMBIENT_FRAGMENT_SHADER(glf::SHADER_DIRECTORY + "ambient.frag"); std::string const STENCIL_VERTEX_SHADER(glf::SHADER_DIRECTORY + "stencil.vert"); std::string const STENCIL_GEOMETRY_SHADER(glf::SHADER_DIRECTORY + "stencil.geom"); std::string const STENCIL_FRAGMENT_SHADER(glf::SHADER_DIRECTORY + "stencil.frag"); std::string const FINAL_VERTEX_SHADER(glf::SHADER_DIRECTORY + "final.vert"); std::string const FINAL_GEOMETRY_SHADER(glf::SHADER_DIRECTORY + "final.geom"); std::string const FINAL_FRAGMENT_SHADER(glf::SHADER_DIRECTORY + "final.frag"); int const SIZE_WIDTH(640); int const SIZE_HEIGHT(480); int const MAJOR_VERSION(4); int const MINOR_VERSION(1); glf::Window window(glm::ivec2(SIZE_WIDTH, SIZE_HEIGHT)); GLuint shaderAmbient(0); GLuint shaderStencil(0); GLuint shaderFinal(0); GLuint objArrayBufferID[3] = {0}; GLuint objVertexArrayID(0); //GLuint objIndexBufferID(0); GLint uniformMVPa(0); GLint uniformMVPf(0); GLint uniformM(0); GLint uniformP(0); GLint uniformPf(0); GLint uniformMV(0); GLint uniformMIT(0); GLint uniformTexa(0); GLint uniformTexf(0); GLint uniformLightPoss(0); GLint uniformLightPosf(0); GLint uniformZPass(0); GLint uniformMVf(0); int zPass = 0; GLuint ArrayBufferName(0); GLuint VertexArrayName(0); GLuint ArrayBufferName2(0); GLuint VertexArrayName2(0); GLuint VertexArrayName3(0); GLuint IndexBufferName2(0); GLuint IndexBufferName3(0); GLuint IndexBufferName(0); GLsizei const VertexCount(4); GLsizeiptr const VertexSize = VertexCount * sizeof(glf::vertex_v4fv4fv2f); glf::vertex_v4fv4fv2f const VertexData[VertexCount] = { glf::vertex_v4fv4fv2f (glm::vec4(-50.0f,-0.5f, -50.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)), glf::vertex_v4fv4fv2f (glm::vec4( 50.0f,-0.5f, -50.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f)), glf::vertex_v4fv4fv2f (glm::vec4(-50.0f, -0.5f, 50.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 1.0f)), glf::vertex_v4fv4fv2f (glm::vec4( 50.0f, -0.5f, 50.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 1.0f)) }; glf::vertex_v4fv4fv2f const VertexData2[2*VertexCount] = { glf::vertex_v4fv4fv2f (glm::vec4(-5.0f,10.5f, 5.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)), glf::vertex_v4fv4fv2f (glm::vec4( 5.0f,10.5f, 5.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f)), glf::vertex_v4fv4fv2f (glm::vec4(-5.0f,5.5f, 5.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)), glf::vertex_v4fv4fv2f (glm::vec4( 5.0f,5.5f, 5.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f)), glf::vertex_v4fv4fv2f (glm::vec4(-5.0f,10.5f, 10.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 1.0f)), glf::vertex_v4fv4fv2f (glm::vec4( 5.0f,10.5f, 10.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 1.0f)), glf::vertex_v4fv4fv2f (glm::vec4(-5.0f,5.5f, 10.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 1.0f)), glf::vertex_v4fv4fv2f (glm::vec4( 5.0f,5.5f, 10.0f, 1.0f), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 1.0f)) }; // glf::vertex_v4fv4fv2f const VertexData2[2*VertexCount] = // { // glf::vertex_v4fv4fv2f (glm::vec4(-5.0f,10.5f, 5.0f, 1.0f), // glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), // glm::vec2(0.0f, 0.0f)), // glf::vertex_v4fv4fv2f (glm::vec4( 5.0f,10.5f, 5.0f, 1.0f), // glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), // glm::vec2(1.0f, 0.0f)), // glf::vertex_v4fv4fv2f (glm::vec4(-5.0f,10.5f, 10.0f, 1.0f), // glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), // glm::vec2(0.0f, 1.0f)), // glf::vertex_v4fv4fv2f (glm::vec4( 5.0f,10.5f, 10.0f, 1.0f), // glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), // glm::vec2(1.0f, 1.0f)), // glf::vertex_v4fv4fv2f (glm::vec4(-5.0f,5.5f, 5.0f, 1.0f), // glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), // glm::vec2(0.0f, 0.0f)), // glf::vertex_v4fv4fv2f (glm::vec4( 5.0f,5.5f, 5.0f, 1.0f), // glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), // glm::vec2(1.0f, 0.0f)), // glf::vertex_v4fv4fv2f (glm::vec4(-5.0f,5.5f, 10.0f, 1.0f), // glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), // glm::vec2(0.0f, 1.0f)), // glf::vertex_v4fv4fv2f (glm::vec4( 5.0f,5.5f, 10.0f, 1.0f), // glm::vec4(0.0f, 1.0f, 0.0f, 0.0f), // glm::vec2(1.0f, 1.0f)) // }; // unsigned int indices[6] = {0, 1, 2, 1, 3, 2}; unsigned int indices2[72] = {0, 4, 1, 3, 2, 6, 1, 7, 3, 6, 2, 0, 1, 4, 5, 7, 3, 2, 5, 6, 7, 2, 3, 1, 5, 1, 4, 0, 6, 7, 5, 4, 6, 3, 7, 1, 4, 1, 0, 2, 6, 5, 0, 3, 2, 7, 6, 4, 4, 5, 1, 3, 0, 2, 4, 7, 5, 3, 1, 0, 2, 0, 3, 7, 6, 4, 3, 5, 7, 4, 6, 2}; // unsigned int indices2[72] = {0, 4, 1, 3, 2, 6, // 1, 7, 3, 6, 2, 0, // 1, 4, 5, 7, 3, 2, // 5, 6, 7, 2, 3, 1, // 5, 1, 4, 0, 6, 7, // 5, 4, 6, 3, 7, 1, // 4, 1, 0, 2, 6, 5, // 0, 3, 2, 7, 6, 4, // 4, 5, 1, 3, 0, 2, // 4, 7, 5, 3, 1, 0, // 2, 0, 3, 7, 6, 4, // 3, 5, 7, 4, 6, 2}; unsigned int indices3[36] = {0, 1, 2, 1, 3, 2, 1, 5, 3, 5, 7, 3, 0, 4, 1, 4, 5, 1, 6, 2, 3, 6, 3, 7, 5, 6, 7, 5, 4, 6, 4, 0, 6, 0, 2, 6}; bool initDebugOutput() { bool Validated(true); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glDebugMessageCallbackARB(&glf::debugOutput, NULL); return Validated; } bool initProgram() { bool validated = true; // if (textureID < 0) // { // printf("error while loading texture:%d", textureID); // exit(0); // } // Create program if(validated) { // AMBIENT SHADER printf("creating ambient shader...\n"); GLuint vertexShader = glf::createShader(GL_VERTEX_SHADER, AMBIENT_VERTEX_SHADER); GLuint fragmentShader = glf::createShader(GL_FRAGMENT_SHADER, AMBIENT_FRAGMENT_SHADER); shaderAmbient = glCreateProgram(); glAttachShader(shaderAmbient, vertexShader); glAttachShader(shaderAmbient, fragmentShader); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); glLinkProgram(shaderAmbient); // STENCIL SHADER printf("creating stencil shader...\n"); vertexShader = glf::createShader(GL_VERTEX_SHADER, STENCIL_VERTEX_SHADER); GLuint geometryShader = glf::createShader(GL_GEOMETRY_SHADER, STENCIL_GEOMETRY_SHADER); fragmentShader = glf::createShader(GL_FRAGMENT_SHADER, STENCIL_FRAGMENT_SHADER); shaderStencil = glCreateProgram(); glAttachShader(shaderStencil, vertexShader); glAttachShader(shaderStencil, geometryShader); glAttachShader(shaderStencil, fragmentShader); glDeleteShader(vertexShader); glDeleteShader(geometryShader); glDeleteShader(fragmentShader); glLinkProgram(shaderStencil); // FINAL SHADER printf("creating final shader...\n"); vertexShader = glf::createShader(GL_VERTEX_SHADER, FINAL_VERTEX_SHADER); fragmentShader = glf::createShader(GL_FRAGMENT_SHADER, FINAL_FRAGMENT_SHADER); // geometryShader = glf::createShader(GL_GEOMETRY_SHADER, FINAL_GEOMETRY_SHADER); shaderFinal = glCreateProgram(); glAttachShader(shaderFinal, vertexShader); // glAttachShader(shaderFinal, geometryShader); glAttachShader(shaderFinal, fragmentShader); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // glDeleteShader(geometryShader); glLinkProgram(shaderFinal); } // textureID = gli::createTexture2D(glf::MESH_DIRECTORY + "Imrod_LowPoly/Imrod_Diffuse.tga"); texFloorID = gli::createTexture2D(glf::TEXTURE_DIRECTORY + "Skybox1/dn.tga"); // Get variables locations if(validated) { // using layout, or maybe not uniformMVPa = glGetUniformLocation(shaderAmbient, "mvpMatrix"); uniformMVPf = glGetUniformLocation(shaderFinal, "mvpMatrix"); uniformM = glGetUniformLocation(shaderFinal, "modelMatrix"); uniformP = glGetUniformLocation(shaderStencil, "projectionMatrix"); uniformPf = glGetUniformLocation(shaderFinal, "projectionMatrix"); uniformMV = glGetUniformLocation(shaderStencil, "modelViewMatrix"); uniformMIT = glGetUniformLocation(shaderFinal, "modelMatrixIT"); // uniformMVf = glGetUniformLocation(shaderFinal, "modelViewMatrix"); // uniformTex(; // uniformLightPos(0); uniformTexa = glGetUniformLocation(shaderAmbient, "diffuseMap"); uniformTexf = glGetUniformLocation(shaderFinal, "diffuseMap"); uniformLightPoss = glGetUniformLocation(shaderStencil, "lightPos"); uniformLightPosf = glGetUniformLocation(shaderFinal, "lightPos"); uniformZPass = glGetUniformLocation(shaderStencil, "zPass"); } return validated && glf::checkError("initProgram"); } bool initvertexArray() { // Build a vertex array object glGenVertexArrays(1, &objVertexArrayID); glBindVertexArray(objVertexArrayID); { glBindBuffer(GL_ARRAY_BUFFER, objArrayBufferID[0]); glVertexAttribPointer(glf::semantic::attr::POSITION, 4, GL_FLOAT, GL_FALSE, 0, GLF_BUFFER_OFFSET(0)); glBindBuffer(GL_ARRAY_BUFFER, objArrayBufferID[1]); glVertexAttribPointer(glf::semantic::attr::NORMAL, 4, GL_FLOAT, GL_FALSE, 0, GLF_BUFFER_OFFSET(0)); glBindBuffer(GL_ARRAY_BUFFER, objArrayBufferID[2]); glVertexAttribPointer(glf::semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, 0, GLF_BUFFER_OFFSET(0)); glEnableVertexAttribArray(glf::semantic::attr::POSITION); glEnableVertexAttribArray(glf::semantic::attr::NORMAL); glEnableVertexAttribArray(glf::semantic::attr::TEXCOORD); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, objIndexBufferID); } glBindVertexArray(0); glGenVertexArrays(1, &VertexArrayName); glBindVertexArray(VertexArrayName); glBindBuffer(GL_ARRAY_BUFFER, ArrayBufferName); glVertexAttribPointer(glf::semantic::attr::POSITION, 4, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v4fv4fv2f), GLF_BUFFER_OFFSET(0)); glVertexAttribPointer(glf::semantic::attr::NORMAL, 4, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v4fv4fv2f), GLF_BUFFER_OFFSET(sizeof(glm::vec4))); glVertexAttribPointer(glf::semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v4fv4fv2f), GLF_BUFFER_OFFSET(2*sizeof(glm::vec4))); glBindBuffer(GL_ARRAY_BUFFER, 0); glEnableVertexAttribArray(glf::semantic::attr::POSITION); glEnableVertexAttribArray(glf::semantic::attr::NORMAL); glEnableVertexAttribArray(glf::semantic::attr::TEXCOORD); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferName); glBindVertexArray(0); glGenVertexArrays(1, &VertexArrayName2); glBindVertexArray(VertexArrayName2); glBindBuffer(GL_ARRAY_BUFFER, ArrayBufferName2); glVertexAttribPointer(glf::semantic::attr::POSITION, 4, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v4fv4fv2f), GLF_BUFFER_OFFSET(0)); glVertexAttribPointer(glf::semantic::attr::NORMAL, 4, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v4fv4fv2f), GLF_BUFFER_OFFSET(sizeof(glm::vec4))); glVertexAttribPointer(glf::semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v4fv4fv2f), GLF_BUFFER_OFFSET(2*sizeof(glm::vec4))); glBindBuffer(GL_ARRAY_BUFFER, 0); glEnableVertexAttribArray(glf::semantic::attr::POSITION); glEnableVertexAttribArray(glf::semantic::attr::NORMAL); glEnableVertexAttribArray(glf::semantic::attr::TEXCOORD); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferName2); glBindVertexArray(0); glGenVertexArrays(1, &VertexArrayName3); glBindVertexArray(VertexArrayName3); glBindBuffer(GL_ARRAY_BUFFER, ArrayBufferName2); glVertexAttribPointer(glf::semantic::attr::POSITION, 4, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v4fv4fv2f), GLF_BUFFER_OFFSET(0)); glVertexAttribPointer(glf::semantic::attr::NORMAL, 4, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v4fv4fv2f), GLF_BUFFER_OFFSET(sizeof(glm::vec4))); glVertexAttribPointer(glf::semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v4fv4fv2f), GLF_BUFFER_OFFSET(2*sizeof(glm::vec4))); glBindBuffer(GL_ARRAY_BUFFER, 0); glEnableVertexAttribArray(glf::semantic::attr::POSITION); glEnableVertexAttribArray(glf::semantic::attr::NORMAL); glEnableVertexAttribArray(glf::semantic::attr::TEXCOORD); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferName3); glBindVertexArray(0); return glf::checkError("initvertexArray"); } bool initarrayBuffer() { // Generate a buffer object glGenBuffers(3, &objArrayBufferID[0]); glBindBuffer(GL_ARRAY_BUFFER, objArrayBufferID[0]); glBufferData(GL_ARRAY_BUFFER, 4*objVertices.size() * sizeof(GLfloat), &objVertices[0], GL_STATIC_DRAW); // glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, objArrayBufferID[1]); glBufferData(GL_ARRAY_BUFFER, 4*objNormals.size() * sizeof(GLfloat), &objNormals[0], GL_STATIC_DRAW); // glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, objArrayBufferID[2]); glBufferData(GL_ARRAY_BUFFER, 4*objTexCoord.size() * sizeof(GLfloat), &objTexCoord[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // glGenBuffers(1, &objIndexBufferID); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, objIndexBufferID); // glBufferData(GL_ELEMENT_ARRAY_BUFFER, objIndices.size() * sizeof(GLuint), &objIndices[0], GL_STATIC_DRAW); glGenBuffers(1, &ArrayBufferName); glBindBuffer(GL_ARRAY_BUFFER, ArrayBufferName); glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &ArrayBufferName2); glBindBuffer(GL_ARRAY_BUFFER, ArrayBufferName2); glBufferData(GL_ARRAY_BUFFER, 2*VertexSize, VertexData2, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // glGenBuffers(1, &IndexBufferName); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferName); // glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int)*6, &indices[0], GL_STATIC_DRAW); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glGenBuffers(1, &IndexBufferName2); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferName2); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int)*72, &indices2[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glGenBuffers(1, &IndexBufferName3); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferName3); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int)*36, &indices3[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); return glf::checkError("initarrayBuffer"); } bool begin() { bool validated = glf::checkGLVersion(MAJOR_VERSION, MINOR_VERSION); if(validated) { objVertices.reserve(25200); objNormals.reserve(25200); objTexCoord.reserve(25200); // objIndices.reserve(76000); // glf::loadObj (objName.c_str(), objVertices, objNormals, objTexCoord); } if(validated && glf::checkExtension("GL_ARB_debug_output")) validated = initDebugOutput(); if(validated) validated = initProgram(); if(validated) validated = initarrayBuffer(); if(validated) validated = initvertexArray(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); // glEnable( GL_BLEND ); // set OpenGL state // enable depth and stencil test glEnable (GL_DEPTH_TEST); glEnable (GL_STENCIL_TEST); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_CLAMP); glDepthFunc(GL_LEQUAL); // glCullFace(GL_BACK); // glFrontFace(GL_CW); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f)[0]); glClearDepth(1.0f); glClearColor( 1.0f, 1.0f, 1.0f, 1.0f ); glClearStencil(0); return validated && glf::checkError("begin"); } bool end() { glDeleteVertexArrays(1, &objVertexArrayID); glDeleteBuffers(1, objArrayBufferID); glDeleteProgram(shaderAmbient); glDeleteProgram(shaderStencil); glDeleteProgram(shaderFinal); return glf::checkError("end"); } void display() { glm::mat4 projectionMatrix = glm::perspective(45.0f, float(window.size.x / window.size.y), 0.1f, 10000.0f); glm::mat4 modelTranslate = glm::translate(glm::mat4(1.0f), glm::vec3( window.translationCurrent.x, -window.translationCurrent.y, window.translationCurrent.z)); glm::mat4 viewTranslate = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, -20.0f, -80.0f)); glm::mat4 viewRotateX = glm::rotate(viewTranslate, window.rotationCurrent.y, glm::vec3(1.f, 0.f, 0.f)); glm::mat4 viewMatrix = glm::rotate(viewRotateX, window.rotationCurrent.x, glm::vec3(0.f, 1.f, 0.f)); glm::mat4 modelMatrix = glm::scale (glm::mat4(1.0f), glm::vec3(1.0f)); glm::mat4 MVP = projectionMatrix * viewMatrix * modelMatrix; glm::mat4 MVP2 = projectionMatrix * viewMatrix * modelTranslate * modelMatrix; glm::mat4 modelMatrixIT = glm::inverse (glm::transpose(modelMatrix)); glm::mat4 modelViewMatrix = viewMatrix * modelTranslate * modelMatrix; glm::vec4 lightPosa = modelViewMatrix * glm::vec4 (-25.0f, 100.0f, 40.0f, 1.0f); glm::vec4 lightPosb = modelMatrix * glm::vec4 (-5.0f, 100.0f, 100.0f, 1.0f); glViewport(0, 0, window.size.x, window.size.y); glm::vec3 lightPoss = glm::vec3( lightPosa.x, lightPosa.y, lightPosa.z); glm::vec3 lightPosf = glm::vec3( lightPosb.x, lightPosb.y, lightPosb.z); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // ambient draw (to fill depth buffer) glUseProgram(shaderAmbient); glUniformMatrix4fv (uniformMVPa, 1, GL_FALSE, &MVP[0][0]); // glBindVertexArray(objVertexArrayID); glActiveTexture(GL_TEXTURE0); // glBindTexture(GL_TEXTURE_2D, textureID); // glDrawArrays (GL_TRIANGLES, 0, objVertices.size()); glBindTexture(GL_TEXTURE_2D, texFloorID); glBindVertexArray(VertexArrayName); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glUniformMatrix4fv (uniformMVPa, 1, GL_FALSE, &MVP2[0][0]); glBindVertexArray(VertexArrayName3); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); // stencil draw (to fill stencil buffer) if (zPass) { // incr for front facing triangles, decr for back facing triangles if depth test passes glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_INCR_WRAP); glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_DECR_WRAP); // stencil test always passes glStencilFunc (GL_ALWAYS, 0, ~0); } else { // decr for front facing triangles, incr for back facing triangles if depth test fails glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_DECR_WRAP, GL_KEEP); glStencilOpSeparate(GL_BACK, GL_KEEP, GL_INCR_WRAP, GL_KEEP); // stencil test always passes glStencilFunc (GL_ALWAYS, 0, ~0); } // clear stencil buffer and lock color and depth buffer glClear(GL_STENCIL_BUFFER_BIT); //glClear(GL_COLOR_BUFFER_BIT); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); glUseProgram(shaderStencil); glUniformMatrix4fv (uniformMV, 1, GL_FALSE, &modelViewMatrix[0][0]); glUniformMatrix4fv (uniformP, 1, GL_FALSE, &projectionMatrix[0][0]); glUniform3fv (uniformLightPoss, 1, &lightPoss[0]); // zPass or zFail? glUniform1i(uniformZPass, zPass); // glBindVertexArray(objVertexArrayID); // glDrawArrays (GL_TRIANGLES_ADJACENCY, 0, objVertices.size()); glBindTexture(GL_TEXTURE_2D, texFloorID); glBindVertexArray(VertexArrayName); glDrawArrays(GL_TRIANGLES_ADJACENCY, 0, 4); glBindVertexArray(VertexArrayName2); glDrawElements(GL_TRIANGLES_ADJACENCY, 72, GL_UNSIGNED_INT, 0); // unlock depth and color buffer glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDepthMask(GL_TRUE); // final draw (skip parts in shadow -> keep ambient color) glClear(GL_DEPTH_BUFFER_BIT); // dont change stencil buffer values glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP); glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP); // stencil test only passes if value in stencil buffer == 0 glStencilFunc (GL_EQUAL, 0, ~0); glUseProgram(shaderFinal); glUniformMatrix4fv (uniformM, 1, GL_FALSE, &modelMatrix[0][0]); glUniformMatrix4fv (uniformMIT, 1, GL_FALSE, &modelMatrixIT[0][0]); glUniformMatrix4fv (uniformMVPf, 1, GL_FALSE, &MVP[0][0]); // glUniformMatrix4fv (uniformPf, 1, GL_FALSE, &projectionMatrix[0][0]); glUniform3fv (uniformLightPosf, 1, &lightPosf[0]); glActiveTexture(GL_TEXTURE0); glBindVertexArray(objVertexArrayID); // glBindTexture(GL_TEXTURE_2D, textureID); // glDrawArrays (GL_TRIANGLES, 0, objVertices.size()); glBindTexture(GL_TEXTURE_2D, texFloorID); glBindVertexArray(VertexArrayName); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // glBindVertexArray(VertexArrayName2); // glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glUniformMatrix4fv (uniformMVPf, 1, GL_FALSE, &MVP2[0][0]); glBindVertexArray(VertexArrayName3); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); glf::checkError("display"); glf::swapBuffers(); } int main(int argc, char* argv[]) { return glf::run (argc, argv, glm::ivec2(::SIZE_WIDTH, ::SIZE_HEIGHT), GL_CONTEXT_CORE_PROFILE_BIT, ::MAJOR_VERSION, ::MINOR_VERSION); }
6a6fac9b2440d9e28acdd0fa187fb5fda18d5e56
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_hunk_2415.cpp
20c80685ccf38262f4e4aafb8129c1f7b5f945f8
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,906
cpp
httpd_new_hunk_2415.cpp
apr_dbd_row_t *row = NULL; authn_dbd_conf *conf = ap_get_module_config(r->per_dir_config, &authn_dbd_module); ap_dbd_t *dbd = authn_dbd_acquire_fn(r); if (dbd == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01653) "Failed to acquire database connection to look up " "user '%s'", user); return AUTH_GENERAL_ERROR; } if (conf->user == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01654) "No AuthDBDUserPWQuery has been specified"); return AUTH_GENERAL_ERROR; } statement = apr_hash_get(dbd->prepared, conf->user, APR_HASH_KEY_STRING); if (statement == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01655) "A prepared statement could not be found for " "AuthDBDUserPWQuery with the key '%s'", conf->user); return AUTH_GENERAL_ERROR; } if (apr_dbd_pvselect(dbd->driver, r->pool, dbd->handle, &res, statement, 0, user, NULL) != 0) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01656) "Query execution error looking up '%s' " "in database", user); return AUTH_GENERAL_ERROR; } for (rv = apr_dbd_get_row(dbd->driver, r->pool, res, &row, -1); rv != -1; rv = apr_dbd_get_row(dbd->driver, r->pool, res, &row, -1)) { if (rv != 0) { ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01657) "Error retrieving results while looking up '%s' " "in database", user); return AUTH_GENERAL_ERROR; } if (dbd_password == NULL) { #if APU_MAJOR_VERSION > 1 || (APU_MAJOR_VERSION == 1 && APU_MINOR_VERSION >= 3)
7bca08876c65a4f6ef932dea24270c5aedddb5ed
c5de5d072f5099e7f13b94bf2c81975582788459
/C++ Core Library/hdr/gsdt/GsDtFunc.h
61bfa48c97c1739c579aee2d896609dbb30fd30a
[]
no_license
uhasan1/QLExtension-backup
e125ad6e3f20451dfa593284507c493a6fd66bb8
2bea9262841b07c2fb3c3495395e66e66a092035
refs/heads/master
2020-05-31T06:08:40.523979
2015-03-16T03:09:28
2015-03-16T03:09:28
190,136,053
2
0
null
null
null
null
UTF-8
C++
false
false
2,504
h
GsDtFunc.h
/**************************************************************** ** ** GSDTFUNC.H - ** ** Copyright 2000 - Goldman, Sachs & Co. - New York ** ** $Header: /home/cvs/src/gsdt/src/gsdt/GsDtFunc.h,v 1.5 2001/11/27 22:43:58 procmon Exp $ ** ****************************************************************/ #if !defined( IN_GSDT_GSDTFUNC_H ) #define IN_GSDT_GSDTFUNC_H #include <gsdt/base.h> #include <gsdt/GsDt.h> CC_BEGIN_NAMESPACE( Gs ) /**************************************************************** ** Class : GsDtFunc ** Description : A class representing an aribrary type-checked ** function for double to double. This is actually ** an abstract base class for more than one kind ** of function. The first kind of derived class ** is one containing a GsFuncHandle< D, R >, which ** type-checks its arg to make sure it is a D. ** The second is the composition of two other ** GsDtFuncs. ****************************************************************/ class EXPORT_CLASS_GSDT GsDtFunc : public GsDt { GSDT_DECLARE_ABSTRACT_TYPE( GsDtFunc ) public: GsDtFunc( const GsType *DomainType, const GsType *RangeType ); GsDtFunc( const GsDtFunc & ); virtual ~GsDtFunc(); GsDtFunc &operator=( const GsDtFunc &rhs ); // Virtual functions from GsDt virtual GsDt *Evaluate( const GsDtArray &Args ) const; virtual GsString toString() const; // Stuff relevant to this actual class. virtual GsDt* operator()( const GsDt * ) const = 0; protected: // Types we expect the arg and return to be. const GsType *m_DomainType, *m_RangeType; }; /**************************************************************** ** Class : GsDtFunc2 ** Description : A two arg version of GsDtFunc ****************************************************************/ class EXPORT_CLASS_GSDT GsDtFunc2 : public GsDt { GSDT_DECLARE_ABSTRACT_TYPE( GsDtFunc2 ) public: GsDtFunc2( const GsType *Domain1Type, const GsType *Domain2Type, const GsType *RangeType ); GsDtFunc2( const GsDtFunc2 & ); virtual ~GsDtFunc2(); GsDtFunc2 &operator=( const GsDtFunc2 &rhs ); // Virtual functions from GsDt virtual GsDt *Evaluate( const GsDtArray &Args ) const; virtual GsString toString() const; // Stuff relevant to this actual class. virtual GsDt* operator()( const GsDt *, const GsDt * ) const = 0; protected: // Types we expect the arg and return to be. const GsType *m_Domain1Type, *m_Domain2Type, *m_RangeType; }; CC_END_NAMESPACE #endif
59af975242283580825896e1639e33f2959cf83f
6192a585b88e7754ab8aaa2ab2eb9263499244e2
/include/wavefield/tags.hpp
8650622588debe643f407dd6ec99113030227e9c
[]
no_license
dieu-detruit/wavefield
674024ce79acc48f78d8bbeda40427666dbd3f94
82743837103f27810b39d254a9487db1cb580822
refs/heads/master
2022-12-23T11:14:23.768293
2020-10-02T07:45:47
2020-10-02T07:45:47
274,889,434
0
0
null
null
null
null
UTF-8
C++
false
false
764
hpp
tags.hpp
#pragma once namespace wavefield { struct diffraction_tag { }; // Fraunhofer struct fraunhofer_diffraction_tag : diffraction_tag { }; inline constexpr fraunhofer_diffraction_tag fraunhofer; // Fresnel struct fresnel_fft_diffraction_tag : diffraction_tag { }; inline constexpr fresnel_fft_diffraction_tag fresnel_fft; struct fresnel_convolution_diffraction_tag : diffraction_tag { }; inline constexpr fresnel_convolution_diffraction_tag fresnel_convolution; struct fresnel_shifted_fft_diffraction_tag : diffraction_tag { }; inline constexpr fresnel_shifted_fft_diffraction_tag fresnel_shifted_fft; // Angular struct angular_spectrum_diffraction_tag : diffraction_tag { }; inline constexpr angular_spectrum_diffraction_tag angular; } // namespace wavefield
9069ed7da0618771687688cc65b8b3ee41a00d73
aa4c442fd7578b3655f296ea493643ddf59a1c4e
/numbers.h
81c803850450ef1de5f2ed9714cdf0691039f704
[ "MIT" ]
permissive
ReinaldoDiasAbreu/Calculos-com-Numeros-Extensos
916655480d58ee9dc2863cf848b0f459f4fe8635
10f3bd7f23450ab62c70aa35e7de7989ea450ea8
refs/heads/master
2020-05-24T05:40:22.448584
2019-05-17T00:52:24
2019-05-17T00:52:24
187,121,658
1
0
null
null
null
null
UTF-8
C++
false
false
11,402
h
numbers.h
#ifndef NUMBERS_H #define NUMBERS_H #include <iostream> #include <cstdlib> #include <cmath> class LongNum { private: int *dados; int topo; int capacidade; public: LongNum(int cap=1) /// Construtor da pilha e inicia os elementos { dados = new int[cap]; topo = -1; capacidade = cap; } bool vazia() /// Verifica se a pilha está vazia { return topo == -1; } void realocar() /// Realoca mais uma posição na pilha { int *aux = new int[capacidade+1]; for(int i=0; i< capacidade; i++) aux[i] = dados[i]; delete []dados; dados = aux; capacidade += 1; } void EmpilhaElemento(int elem) /// Empilha um elemento inteiro { if(topo+1 == capacidade) { this->realocar(); // Realoca 1 dezena no numero dados[++topo] = elem; } else { dados[++topo] = elem; } } int tamanho() /// Retorna capacidade da pilha. { return capacidade; } void EmpilhaNumero(std::string num) /// Empilha toda uma string de inteiros. { for(int i = 0; i < capacidade; i++) { int elem = (num[i] - 48); // Conversão explicita pela tabela ASCII EmpilhaElemento(elem); // Empilha o elemento na pilha correspondente } } int desempilha() /// Retorna numero no topo da pilha { if(!vazia()) return dados[topo--]; else return -1; // Retorna -1 que é tratado nas funções } int retornanumpos(int p) /// Retorna numero da posicao de dados { if(!vazia()) return dados[p]; else return -1; } void inverter() /// Inverte os dados da pilha { int t = tamanho(); int *aux = new int[t]; for(int i = 0, j = t-1 ; i < t || j >= 0 ; i++ , j--) aux[j] = dados[i]; delete(dados); dados = aux; } void imprimir() /// Imprime a pilha { if(!vazia()) { for(int i=0; i <= topo; i++) { std::cout << dados[i]; } } std::cout << std::endl; } void imprimeresultado() /// Imprime a pilha do resultado { if(!vazia()) { for(int i=topo; i >= 0; i--) { std::cout << dados[i]; } std::cout << std::endl; } } void somar(LongNum num2) /// Soma a pilha, com a passada por parâmetro e preenche a pilha com a soma { LongNum num; // Copia o primeiro numero for(int i=0; i < capacidade; i++) num.EmpilhaElemento(this->retornanumpos(i)); delete []dados; // Desaloca o primeiro numero topo = -1; int var1, var2, soma, elev=0; // Variáveis Auxiliares for(int i=0; i < num.tamanho(); i++) { var1 = num.desempilha(); // Captura o valor do topo da pilha 1 var2 = num2.desempilha(); // Captura o valor do topo da pilha 2 if(var1 == -1) // Caso o topo retorne -1, para se uma pilha for maior que a outra var1 = 0; // O valor -1 passa a ser zero, neutro na soma if(var2 == -1) var2 = 0; soma = var1 + var2 + elev; // A soma será os dois elementos mais o número elevado elev = soma / 10; // O numero elevado será o que passar da base 10 soma = soma % 10; // O resto dessa soma por 10 será o valor da soma this->EmpilhaElemento(soma); } if(elev > 0) { this->EmpilhaElemento(elev); // Ultimo elemento da soma para caso as duas pilhas serem do mesmo tamanho } } void dobrar(LongNum *numDobro) /// Dobra o valor { if(!vazia()) { int dobro, elev=0; // Variáveis Auxiliares for(int i=0; i < capacidade; i++) { dobro = 2 * desempilha() + elev; elev = dobro / 10; dobro = dobro % 10; numDobro->EmpilhaElemento(dobro); } if(elev > 0) numDobro->EmpilhaElemento(elev); } } void metade(int tam, LongNum *numResultado) { LongNum numDiv(tam); // Pilha para as divisões LongNum numResto(tam); // Pilha para o resto int resultado=0, div=0, resto=0; // Variáveis auxiliares for(int i = capacidade-1; i >= 0; i--) { int aux = this->desempilha(); // Desempilha o numero a partir das unidades div = aux / 2; // Captura a divisão por 2 resto = aux % 2; // Captura o resto da divisão por 2 numDiv.EmpilhaElemento(div); // Empilha o resultado da divisão numResto.EmpilhaElemento(resto); // Empilha o resultado do resto } for(int i = 0; i < capacidade; i++) { div = resto = resultado = 0; // Inicializa as variáveis div = numDiv.desempilha(); // Desempilha as divisões até as unidades if(i == 0) resultado = div; // Se for o primeiro algarismo, o primeiro digito else // do resultado será ele { resto = numResto.desempilha(); // Desempilha o resto do algarismo anterior resultado = ((div*2) + (resto*10))/2; // Calcula o resultado para a posição desse algarismo } numResultado->EmpilhaElemento(resultado); // Salva a posição do resultado na pilha } } void diferenca(LongNum *num) /// Calcula diferença { LongNum dif; // Pilha de resultado int emp = 0; // Variável auxiliar para empréstimo for(int i=0; i < this->capacidade; i++) { int aux1 = this->desempilha(); // Captura valor a partir das unidades int aux2 = num->desempilha(); // Captura valor a partir das unidades if(aux1 == -1) aux1 = 0; // Troca para 0 caso já esteja vazia if(aux2 == -1) aux2 = 0; // Troca para 0 caso já esteja vazia if(aux1 < aux2) { if(emp == 0) { dif.EmpilhaElemento((10+aux1) - aux2); emp++; } else { dif.EmpilhaElemento(((10-emp)+aux1) - aux2); } } else if(aux1 == aux2) { if(emp == 0) { dif.EmpilhaElemento(aux1 - aux2); } else { dif.EmpilhaElemento(((10-emp)+aux1) - aux2); } } else { if(emp == 0) { dif.EmpilhaElemento(aux1 - aux2); } else { dif.EmpilhaElemento((aux1-emp) - aux2); emp--; } } } dif.imprimeresultado(); } void multiplica(LongNum *num, LongNum *Resultado) /// Não Funcional não deu tempo de revisar e { /// enxugar o código, funciona para alguns números int aux1, aux2, M; LongNum *tabela = new LongNum[this->capacidade]; // Aloca o resultado das multiplicações for(int i=this->capacidade-1; i >=0; i--) // Realiza a multiplicação de cada parcela { aux1 = this->retornanumpos(i); int elev = 0; // Auxiliar para valores excedidos for(int j= num->capacidade-1; j >= 0; j--) { aux2 = num->retornanumpos(j); M = (aux1 * aux2) + elev; if(M<10) { tabela[i].EmpilhaElemento(M); elev=0; } else { int aux = M%10; elev = M/10; tabela[i].EmpilhaElemento(aux); } //std::cout << "Num1: " << aux1 << " - Num2: " << aux2 << " = Result: " << M << " Elev: " << elev << std::endl; } tabela[i].EmpilhaElemento(elev); } for(int i=0; i < this->capacidade; i++) tabela[i].inverter(); // Inverte os valores da tabela // Realizando a soma da Multiplicação das parcelas int rep = this->capacidade-1; int elevado = 0; for(int i=0; i < this->capacidade+1; i++) { int num1=0, num2=0, soma =0; if(i < this->capacidade) num1 = tabela[rep].desempilha(); if(i > 0) num2 = tabela[rep+1].desempilha(); if(num1 == -1) // Caso o topo retorne -1, para se uma pilha for maior que a outra num1 = 0; // O valor -1 passa a ser zero, neutro na soma if(num2 == -1) num2 = 0; soma = num1 + num2 + elevado; // A soma será os dois elementos mais o número elevado elevado = soma / 10; // O numero elevado será o que passar da base 10 soma = soma % 10; // O resto dessa soma por 10 será o valor da soma std::cout << " Elev: " << elevado << " Soma: " << soma << std::endl; Resultado->EmpilhaElemento(soma); rep--; } if(elevado > 0) { Resultado->EmpilhaElemento(elevado); // Ultimo elemento da soma para caso as duas pilhas serem do mesmo tamanho } Resultado->imprimeresultado(); } ~LongNum() { if(dados) delete []dados; } }; #endif // NUMBERS_H
0635707669661c8007440c1ce2e27b16f7831a6b
16d39329747a9592cd9b6c673f4602694038d84c
/hw4.cpp
16dad424f8de14eb9f6d6c34b651d11acf393cd8
[]
no_license
3A713212/advance-homework04
549b1f4890b5d014baaf7e3cb1aefea3f14022c8
85c3ef3d75fe90f851e15f5563132dbbbc61d0bb
refs/heads/master
2020-05-18T21:57:56.328668
2019-05-03T00:36:15
2019-05-03T00:36:15
184,678,184
0
0
null
null
null
null
BIG5
C++
false
false
492
cpp
hw4.cpp
#include<stdio.h> #include<stdlib.h> int main() { int y,m,d,total=0,n,x; int a[12]={31,28,31,30,31,30,31,31,30,31,30,31}; printf("請輸入年 月 日判斷為第幾天:"); scanf("%d%d%d",&y,&m,&d); if(y%400==0||y%4==0&&y%100!=0==0) a[1]=29; else a[1]=28; for(x=0;x<=m-2;x++){ total=total+a[x];} if(m==1) { printf("為第%d日",d); } else { printf("為第%d日",total+d); } system("pause"); return 0 ; }
d80be1db97b13e96831514ec153b41242af8850b
70b45659b8c416eb41b90af0605cf56fbb7481bd
/tuw_voronoi_graph/src/segment.cpp
d1fc3fe7db34449f59eb4742c9cec14a82d0d0c5
[ "BSD-3-Clause" ]
permissive
tuw-robotics/tuw_multi_robot
240732055dab2dccae4dc74c25454129faf0dc85
6863bf4f04c02e99f4bbe74fec48612f85125918
refs/heads/master
2023-04-30T14:17:24.301279
2022-03-04T09:56:43
2022-03-04T09:56:43
114,774,827
206
106
BSD-3-Clause
2021-07-20T06:30:56
2017-12-19T14:28:58
C++
UTF-8
C++
false
false
6,082
cpp
segment.cpp
/* * Copyright (c) 2017, <copyright holder> <email> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 <copyright holder> <email> ''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 <copyright holder> <email> 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 <tuw_voronoi_graph/segment.h> #include <limits> namespace tuw_graph { uint32_t Segment::static_id_ = 0; void Segment::cleanNeighbors(uint32_t _id) { for(uint32_t i = 0; i < predecessor_.size(); i++) { if(predecessor_[i] == _id) { predecessor_.erase(predecessor_.begin() + i); } } for(uint32_t i = 0; i < successor_.size(); i++) { if(successor_[i] == _id) { successor_.erase(successor_.begin() + i); } } } void Segment::decreaseNeighborIdAbove(uint32_t _id) { if(id_ >= _id) id_--; for(uint32_t i = 0; i < predecessor_.size(); i++) { if(predecessor_[i] >= _id) { predecessor_[i]--; } } for(uint32_t i = 0; i < successor_.size(); i++) { if(successor_[i] >= _id) { successor_[i]--; } } } void Segment::addPredecessor(const uint32_t _predecessor) { predecessor_.push_back(_predecessor); } void Segment::addSuccessor(const uint32_t _successor) { successor_.push_back(_successor); } Segment::Segment(const std::vector<Eigen::Vector2d> &_points, const float _min_space) : predecessor_(), successor_(), optimizedStart_(false), optimizedEnd_(false) { if(_points.size() > 0) { start_ = _points.front(); end_ = _points.back(); length_ = _points.size(); min_space_ = _min_space; wayPoints_ = _points; } id_ = static_id_++; } Segment::Segment(const uint32_t _id, const std::vector<Eigen::Vector2d> &_points, const float _min_space) : predecessor_(), successor_(), optimizedStart_(false), optimizedEnd_(false) { if(_points.size() > 0) { start_ = _points.front(); end_ = _points.back(); length_ = _points.size(); min_space_ = _min_space; wayPoints_ = _points; } id_ = _id; } void Segment::setStart(const Eigen::Vector2d &_pt) { if(wayPoints_.size() == 0) wayPoints_.emplace_back(_pt); wayPoints_[0] = _pt; start_ = _pt; } void Segment::setEnd(const Eigen::Vector2d &_pt) { while(wayPoints_.size() <= 1) { wayPoints_.emplace_back(_pt); } wayPoints_[wayPoints_.size() - 1] = _pt; end_ = _pt; } uint32_t Segment::getId() const { return id_; } void Segment::setId(uint32_t _id) { id_ = _id; } const Eigen::Vector2d &Segment::getEnd() const { return end_; } const Eigen::Vector2d &Segment::getStart() const { return start_; } const std::vector<uint32_t > &Segment::getPredecessors() const { return predecessor_; } const std::vector<uint32_t > &Segment::getSuccessors() const { return successor_; } bool Segment::containsPredecessor(const uint32_t _predecessor) { for(const auto & pred : predecessor_) { if(pred == _predecessor) return true; } return false; } bool Segment::containsSuccessor(const uint32_t _successor) { for(uint32_t i = 0; i < successor_.size(); i++) { if(successor_[i] == _successor) return true; } return false; } void Segment::resetId() { static_id_ = 0; } std::vector< Eigen::Vector2d > Segment::getPath() const { return wayPoints_; } void Segment::setPath(const std::vector< Eigen::Vector2d > &_points) { if(_points.size() > 0) { start_ = _points.front(); end_ = _points.back(); length_ = _points.size(); wayPoints_ = _points; } } float Segment::getMinPathSpace() const { return min_space_; } void Segment::setMinPathSpace(const float _space) { min_space_ = _space; } int Segment::getLength() const { return length_; } bool &Segment::getOptStart() { return optimizedStart_; } bool &Segment::getOptEnd() { return optimizedEnd_; } }
167c34743373b99fe7561982a35c40851e815ee4
e5b98edd817712e1dbcabd927cc1fee62c664fd7
/Classes/module/homeUI/homeMap/HomeHeroManager.cpp
d681f69f91592b96f4cfc5bbbe8f752f52bd66df
[]
no_license
yuangu/project
1a49092221e502bd5f070d7de634e4415c6a2314
cc0b354aaa994c0ee2d20d1e3d74da492063945f
refs/heads/master
2020-05-02T20:09:06.234554
2018-12-18T01:56:36
2018-12-18T01:56:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,750
cpp
HomeHeroManager.cpp
// // HomeHeroManager.cpp // FightPass // // Created by zhangxiaobin on 15/10/20. // // #include "HomeHeroManager.h" #include "../../../module/battle/data/MapDataManager.h" HomeHeroManager* HomeHeroManager::_instance = NULL; HomeHeroManager::HomeHeroManager() :_heroList(NULL) ,_mapWidth(0) ,_mapHeight(0) { _heroList = new __Set(); } HomeHeroManager::~HomeHeroManager() { CC_SAFE_DELETE(_heroList); _heroList = NULL; } void HomeHeroManager::clear() { _heroList->removeAllObjects(); } HomeHeroManager* HomeHeroManager::getInstance() { if(!_instance) { _instance = new HomeHeroManager(); } return _instance; } void HomeHeroManager::destroyInstance() { CC_SAFE_DELETE(_instance); _instance = NULL; } void HomeHeroManager::addHero(Hero* hero) { _heroList->addObject(hero); } void HomeHeroManager::updateHeroList(float dt) { int rand = 0; Point direction; long long nowTime = TimeUtil::getNativeTime(); for(__SetIterator it = this->_heroList->begin(); it != _heroList->end(); it++ ) { Hero* hero = (Hero*)*it; hero->updatePositon(dt); float posX = MIN(_mapWidth - hero->_centerToSide,MAX(hero->_centerToSide,hero->_destinatsionPostion.x)); float posY = MIN(_mapHeight - hero->_centerToBottom,MAX(hero->_centerToBottom,hero->_destinatsionPostion.y)); hero->setPosition(posX,posY); hero->setZOrder(10000 - posY); if(nowTime < hero->_nextDecisionTime ) { // if(hero->getActionState() == kActionStateWalk) // { // direction = MapDataManager::getInstance()->getAvatarWalkDirection(hero, hero->isLeft); // if(direction != Point::ZERO) // { // hero->walkWithDirection(direction, true); // } // } continue; } rand = PublicShowUI::genRandom(0, 5); if(rand == 0) { direction = Point(0,1); } else if(rand == 1) { direction = Point(1,0); } else if(rand == 2) { direction = Point(0,1); } else if(rand == 3) { direction = Point(0,-1); } else if(rand == 4) { direction = Point(-1,0); } else { direction.x = 0; direction.y = 0; } if(direction != Point::ZERO) { hero->walkWithDirection(direction, true); } else { hero->idle(); hero->_velocity = Point::ZERO; } hero->_nextDecisionTime = nowTime + PublicShowUI::genRandom(100, 3000); } }
93dc3358630e2177f7879172161f0cc8d6ce996d
26bec0f8021b1e3df7ce56cddd14ec2986eaceea
/src/BinarySearchTree.cpp
ca7c72719a759f0f35243ece7864e87718ddb539
[ "MIT" ]
permissive
RozanskiP/SDIZO1
c3f90583a9fa7da9866d2e8f634f1910d73a6346
c4efb26692e6d3573d4e15a96eb6a6c64ef1718b
refs/heads/master
2023-04-17T11:47:49.234677
2021-04-27T22:54:27
2021-04-27T22:54:27
349,562,940
0
0
null
null
null
null
UTF-8
C++
false
false
9,105
cpp
BinarySearchTree.cpp
/* * BinarySearchTree.cpp * * Created on: 6 mar 2021 * Author: Pawel */ #include "BinarySearchTree.h" #include <cstdlib> #include <ctime> #include <iostream> #include <fstream> #include <cstring> #include <cmath> using namespace std; BSTNode::BSTNode(){ left = NULL; right = NULL; parent = NULL; key = 0; } BSTNode::~BSTNode(){ if(this->left != NULL){ delete this->left; this->left = NULL; } if(this->right != NULL){ delete this->right; this->right = NULL; } } BinarySearchTree::BinarySearchTree() { root = NULL; } BinarySearchTree::~BinarySearchTree() { deleteStructure(); } void BinarySearchTree::deleteStructure(){ if(this->root != NULL){ delete this->root; this->root = NULL; //wazne jesli nie bedzie to wartosc bedzie sie usuwac w nieskonczosnosc } } void BinarySearchTree::inOrder(BSTNode *node){ //rekurencyjnie if(node){ inOrder(node->left); cout << node->key << endl; inOrder(node->right); } } void BinarySearchTree::addNode(int value){ BSTNode *node = new BSTNode(); node->key = value; //nadanie wartosci poczatkowych BSTNode *temproot = this->root; BSTNode *temp2 = NULL; while(temproot != NULL){ //sprawdzaj az nie dojdziesz do ostatniego syna w tej galezi temp2 = temproot; if(node->key < temproot->key){ //jesli mniejszy to na lewo temproot = temproot->left; }else{ temproot = temproot->right; //w przeciwnym razie na prawo } } node->parent = temp2; // przypisanie do nowego wezla jego rodzica if(temp2 == NULL){ // jesli nie ma elementow zadnych to korzen this->root = node; } else if(temp2->key > node->key){ //jesli jest mniejsza niz wartosc z wezle rodzica to na lewo temp2->left = node; }else{ // w przeciwnym nazie na prawo temp2->right = node; } // DSW(); } BSTNode * BinarySearchTree::minimum(BSTNode *node){ if(node == NULL){ return node; } while(node->left != NULL){ node = node->left; } return node; } BSTNode * BinarySearchTree::maximum(BSTNode *node){ if(node == NULL){ return node; } while(node->right != NULL){ node = node->right; } return node; } BSTNode * BinarySearchTree::nastepnik(BSTNode *node){ if(node == NULL){ //sprawdza czy drzewo jest puste return node; } if(node->right != NULL){ //pierwszy przypadek jesli ma prawego syna to wtedy wez minimum z prawej gałezi return minimum(node->right); }else{ // 2 i 3 przypadek nie ma prawego syna BSTNode *temp = node->parent; while(temp->right == node && temp){ //idziemy w gore drzewa az do wtedy kiedy znajdziemy taki wezel node = temp; // ze node lezy w jego lewej galezi temp = temp->parent; } return temp; } } BSTNode * BinarySearchTree::poprzednik(BSTNode *node){ if(node == NULL){ return node; } if(node->left != NULL){ return maximum(node->left); }else{ BSTNode *temp = node->parent; while(temp->left == node && temp){ node = temp; temp = temp->parent; } return temp; } } void BinarySearchTree::deleteNode(int value){ BSTNode * temp = searching(value); //je�li nie ma takiego elementu if(temp == NULL){ return; } if(this->root->right != NULL){ if(this->root->key == this->root->right->key && temp->key == this->root->key){ //warunek gdy sa 2 takie same wartosci w korzeniu i w prawym synu temp = this->root->right; } } // -1 opcja: nie ma zadnego syna if(temp->right == NULL && temp->left == NULL){ BSTNode * parent = temp->parent; if(temp != this->root){ //jesli nie jest rowny korzeniowy if(parent->left == temp){ parent->left = NULL; }else{ parent->right = NULL; } }else{ this->root = NULL; } temp->left = NULL; temp->right = NULL; delete temp; return; } // -2 opcja: posiada jednego syna - lewego if(temp->right == NULL && temp->left != NULL){ BSTNode * parent = temp->parent; BSTNode * son = temp->left; if(temp != this->root){ son->parent = parent; if(parent->left == temp){ parent->left = son; }else{ parent->right = son; } }else{ this->root = son; } //ustawienie wartosci prawej i lewej na null zeby destruktor nie usunal innych elementow temp->left = NULL; temp->right = NULL; delete temp; return; } // -2 opcja: posiada jednego syna - prawego if(temp->right != NULL && temp->left == NULL){ BSTNode * parent = temp->parent; BSTNode * son = temp->right; if(temp != this->root){ son->parent = parent; if(parent->left == temp){ parent->left = son; }else{ parent->right = son; } }else{ this->root = son; } temp->left = NULL; temp->right = NULL; delete temp; return; } // -3 opcja: 2 syn�w // naprawienie miejsca skad wzielismy wezle next BSTNode * next = nastepnik(temp); // cout << "RODZIC: " << next->parent->key << endl; // cout << "Prawy syn: " << next->right->key << endl; int val = next->key; //zapisz wartosc deleteNode(next->key); //zrob rekurencyjnie tak znowu az nie bedizie mial jednego syna temp->key = val; //przypisz wartosc // DSW(); return; } BSTNode * BinarySearchTree::searching(int value){ BSTNode *node = this->root; while(node != NULL){ if(node->key == value){ cout << "Znalazlem taki element" << endl; return node; }else if(node->key > value){ node = node->left; }else{ node = node->right; } } cout << "Nie ma takiej liczby" << endl; return NULL; } void BinarySearchTree::rightRotation(BSTNode *tempRoot, BSTNode *& root){ //rotacja w prawo potrzebna dla alrogrytmu DSW if(tempRoot->left != NULL){ BSTNode *leftson = tempRoot->left; BSTNode *tempRootparent = tempRoot->parent; tempRoot->left = leftson->right; if(tempRoot->left != NULL){ //jesli istnieje lewa strona to przypisz jej rodzica tempRoot->left->parent = tempRoot; } leftson->right = tempRoot; leftson->parent = tempRootparent; tempRoot->parent = leftson; if(tempRootparent != NULL){ if(tempRootparent->left == tempRoot){ tempRootparent->left = leftson; }else{ tempRootparent->right = leftson; } }else{ root = leftson; } } } void BinarySearchTree::leftRotation(BSTNode *tempRoot, BSTNode *& root){ //rotacja w lewo potrzebna dla alrogrytmu DSW if(tempRoot->right != NULL){ BSTNode *rightson = tempRoot->right; BSTNode *tempRootparent = tempRoot->parent; tempRoot->right = rightson->left; if(tempRoot->right != NULL){ tempRoot->right->parent = tempRoot; } rightson->left = tempRoot; rightson->parent = tempRootparent; tempRoot->parent = rightson; if(tempRootparent != NULL){ //jezli rodzic nie byl korzeniem if(tempRootparent->left == tempRoot){ //jesli nasz weze zamieniany byl po lewo tempRootparent->left = rightson; }else{ //jesli byl po prawo tempRootparent->right = rightson; } }else{ //jesli byl korzeniem root = rightson; } } } void BinarySearchTree::DSW(){ BSTNode *temp = root; //Pierwsza czesc utowrzenie kregoslupa int count = 0; while(temp != NULL){ if(temp->left != NULL){ rightRotation(temp, this->root); temp = temp->parent; }else{ temp = temp->right; ++count; } } // druga czesc pierwsze przejscie przez wszystkie int m = count + 1 - pow(2, floor(log2(count+1))); temp = root; for(int i=0;i < m; i++){ leftRotation(temp, this->root); temp = temp->parent->right; } // przejscie przez elementy skladanie do konca w zaleznowsci od elementow count = count - m; while(count > 1){ count = count/2; temp = root; for(int i = 0;i < count; i++){ leftRotation(temp, this->root); temp = temp->parent->right; } } } void BinarySearchTree::loadDataFromFile(const char * filename){ string line; ifstream file; file.open(filename); if(!file){ cout << "Blad otwarcia pliku" << endl; }else{ deleteStructure(); int sizeFromFile = 0; getline(file, line); sizeFromFile = atoi(line.c_str()); int i; for(i = 0;i < sizeFromFile;i++){ getline(file, line); addNode(atoi(line.c_str())); } } } //https://eduinf.waw.pl/inf/alg/001_search/0113.php void print(string sp, string sn, BSTNode *& v){ //TODO sa jakies dziwne ascii string s; string cr, cl, cp; cr = cl = cp = " "; cr [0] = 43; cr [1] = 45; cl [0] = 45; cl [1] = 43; cp [0] = 124 ; if(v) { s = sp; if( sn == cr ) s [ s.length( ) - 2 ] = ' '; print( s + cp, cr, v->right ); s = s.substr ( 0, sp.length( ) - 2 ); cout << s << sn << v->key << endl; s = sp; if( sn == cl ) s [ s.length( ) - 2 ] = ' '; print( s + cp, cl, v->left ); } } void BinarySearchTree::show(){ print("" ,"" , this->root); } void BinarySearchTree::AddRandomToTesting(int size, int start, int end){ deleteStructure(); srand(time(NULL)); int randvalue = 0; int i; for(i = 0;i < size; i++){ randvalue = rand()%end + start; addNode(randvalue); } }
1b39ea4a2573d7cccca9a4a91569f2ddc88d49f3
0a52639a4075dad6f8b1b8bd7582e6c003904049
/test.hh
d5488f8a09174798ec385f7ea5e95e4a6a700089
[ "MIT" ]
permissive
mascanio/Canny-Acc-Cuda-compare
b553f091c4421076d6a05126e7e86ecdd90fac15
0f4221f693a760a11213f25e823170f5b6850f03
refs/heads/master
2021-01-17T12:06:34.669374
2017-03-06T10:09:17
2017-03-06T10:09:17
84,056,899
0
0
null
null
null
null
UTF-8
C++
false
false
136
hh
test.hh
// Miguel Ascanio Gómez // GPU - Práctica 1 #pragma once bool equals(const float* C_cpu, const float* C_gpu, int height, int width);
2685c072f4f12ef40e8328d4c9084a79d2133c60
2d6a94921443030861a5ac6f13dc94884ea728c4
/src/pointer_range.hpp
b8bc7415d02e147a377cc1828238ffdada02b699
[]
no_license
logicmachine/HHMM02
1dddbef7b65181de5458d96639cd2fb4dd216c3a
18bb0f9b4707bad24ae86b6438cfcb7d590d5d3b
refs/heads/master
2021-08-28T07:59:28.985341
2017-12-11T15:57:34
2017-12-11T15:57:34
112,818,246
0
0
null
null
null
null
UTF-8
C++
false
false
622
hpp
pointer_range.hpp
#pragma once template <typename T> class PointerRange { public: using value_type = T; using const_iterator = const T *; private: const T *m_begin; const T *m_end; public: PointerRange(const T *begin, const T *end) : m_begin(begin) , m_end(end) { } bool empty() const { return m_begin == m_end; } size_t size() const { return m_end - m_begin; } value_type operator[](const size_t i) const { return m_begin[i]; } const_iterator cbegin() const { return m_begin; } const_iterator cend() const { return m_end; } const_iterator begin() const { return m_begin; } const_iterator end() const { return m_end; } };
722603d9f60269cb25341d4b594eeb0fc584f856
1904675844784c4f010e146ff255b1c2e70d7259
/gemdroid.src/gemdroid/gemdroid_mem.hh
a76da7ca7067c66582c9ced5b0b09b5bbed1deef
[]
no_license
GemDroidResearch/GemDroid_gem5
c1b56fa17090432de9e92500aa05b25a7809dfc5
9897775f4c4faad4bcab8ea4a14a90719d095d15
refs/heads/master
2022-11-24T23:50:48.693128
2020-08-01T14:42:11
2020-08-01T14:42:11
192,766,248
0
0
null
null
null
null
UTF-8
C++
false
false
4,148
hh
gemdroid_mem.hh
/** * Copyright (c) 2016 The Pennsylvania State University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Contact: Shulin Zhao (suz53@cse.psu.edu) */ #ifndef __GEMDROID_MEM_HH__ #define __GEMDROID_MEM_HH__ #include "base/statistics.hh" #include "mem/dramsim2_wrapper.hh" using namespace std; class GemDroidMemory { private: /** * The actual DRAMSim2 wrapper */ DRAMSim2Wrapper dramWrapper; int mem_id; string desc; GemDroid *gemDroid; long ticks; bool perfectMemory; int perfectMemLatency; int m_cyclesToStall; double m_freq; double m_optMemFreq; double totalPowerConsumed; double powerConsumed; //in the last 1 milli-seconds double m_power; uint64_t m_addr; bool m_isRead; int m_type; int m_id; /** * Read completion callback. * * @param id Channel id of the responder * @param addr Address of the request * @param cycle Internal cycle count of DRAMSim2 */ void readComplete(unsigned id, uint64_t addr, uint64_t cycle, int sender_type, int sender_id); /** * Write completion callback. * * @param id Channel id of the responder * @param addr Address of the request * @param cycle Internal cycle count of DRAMSim2 */ void writeComplete(unsigned id, uint64_t addr, uint64_t cycle, int sender_type, int sender_id); public: GemDroidMemory(int id, string deviceConfigFile, string systemConfigFile, string filePath, string traceFile, long size, bool perfectMemory, bool enableDebug, GemDroid *gemDroid); void regStats(); void resetStats(); void printPeriodicStats(); double powerIn1ms(); double getMaxBandwidth(double freq); //in Ghz; GBPS. double getMaxBandwidth(); //in Ghz; GBPS. void setMemFreq(double freq); //freq in Ghz double getMemFreq(); //returns freq in Ghz inline double getMaxMemFreq() { return MAX_MEM_FREQ; } inline double getMinMemFreq() { return MIN_MEM_FREQ; } inline double getOptMemFreq() { return m_optMemFreq; } void setMaxMemFreq(); //m_freq in Ghz void setOptMemFreq(); //m_freq in Ghz void setMinMemFreq(); //m_freq in Ghz void incMemFreq(int steps=1); //freq in Ghz void decMemFreq(int steps=1); //freq in Ghz double getFreqForBandwidth(double bw); //m_freq in Ghz; function return val in GBPS; double getBandwidth(); //in GBPS double getLastLatency(); int getNumChannels(); double getEnergyEst(double currFreq, double currEnergy, double newFreq); void tick(); bool enqueueMemReq(int type, int id, int core_id, uint64_t addr, bool isRead); Stats::Scalar m_memCPUReqs; Stats::Scalar m_memIPReqs; Stats::Scalar m_memRejected; long stats_m_memCPUReqs; long stats_m_memIPReqs; long stats_m_memRejected; }; #endif //__GEMDROID_MEM_HH__
631288872b8b3e30927133562e036e8c2712e77f
9a24dae8388ea76009bec893b63e59a0bd490bd2
/src/rdf/property.h
a54db3916aedb923cfce5ba0261931a6992c1467
[]
no_license
KDE/syndication
61c79e5ed362a2f968dac38eac3445a6a7234cd3
8004c796ebf962343d5bfb7dfbf36ea7e65ecfd0
refs/heads/master
2023-08-17T03:15:15.324190
2023-06-29T20:57:15
2023-06-30T21:10:48
42,730,053
8
2
null
null
null
null
UTF-8
C++
false
false
1,562
h
property.h
/* This file is part of the syndication library SPDX-FileCopyrightText: 2006 Frank Osterfeld <osterfeld@kde.org> SPDX-License-Identifier: LGPL-2.0-or-later */ #ifndef SYNDICATION_RDF_PROPERTY_H #define SYNDICATION_RDF_PROPERTY_H #include <syndication/rdf/resource.h> class QString; namespace Syndication { namespace RDF { //@cond PRIVATE class Property; typedef QSharedPointer<Property> PropertyPtr; //@endcond /** * a property is node type that represents properties of things, * like "name" is a property of a person, or "color" is a property of e.g. * a car. Properties can be used as predicates in statements. * * @author Frank Osterfeld */ class SYNDICATION_EXPORT Property : public Resource { public: /** * creates a null property */ Property(); /** * creates a property with a given URI * * @param uri the URI of the property */ explicit Property(const QString &uri); /** * destructor */ ~Property() override; /** * Used by visitors for double dispatch. See NodeVisitor * for more information. * @param visitor the visitor calling the method * @param ptr a shared pointer object for this node */ void accept(NodeVisitor *visitor, NodePtr ptr) override; /** * returns true for properties */ bool isProperty() const override; /** * creates a copy of the property object */ Property *clone() const override; }; } // namespace RDF } // namespace Syndication #endif // SYNDICATION_RDF_PROPERTY_H
e319b754aed368b717f4b5e11c60389ea266156b
fb6d28aa1255a2588e05aa7889ac0921fbb47aeb
/ClrsExercise/Chapter26 (Max Flow)/26.1-6.cpp
f20c729fc40f52a052e2f27261727cb6d22d10ea
[]
no_license
OasisGallagher/CLRS
c1471a05ec51ff47b193cc74047fd2efbe80e15b
c11843faff5ee50b59ba774800c6f8e973b9c6b6
refs/heads/master
2020-12-17T01:45:59.622658
2016-05-31T02:48:15
2016-05-31T02:48:15
59,834,685
1
0
null
null
null
null
UTF-8
C++
false
false
401
cpp
26.1-6.cpp
// 性质1, 不一定满足: // (f1+f2)(u, v) = f1(u, v) + f2(u, v) <= c(u, v) + c(u, v) = 2c(u, v). // // 满足性质2: //(f1 + f2)(u, v) = f1(u, v) + f2(u, v) = -f1(v, u) - f2(v, u) // = -(f1(v, u) + f2(v, u)) = -(f1+f2)(v, u). // 满足性质3: // 设u∈V-s-t. // sum(f1+f2)(u, v)(v∈V) = f1(u, v1) + f2(u, v1) + f1(u, v2) + f2(u, v2) ... // = sum(f1(u, v)) + sum(f2(u, v)) = 0.
297893b2fbdb1e4781d4c1713c9265723dda1f3d
b6288ed9edbaef00a556cfeaf6522626baff0b8b
/designPattern2/ProxyPattern/testPP.hpp
e28b686f815fb362b1ffa05bb3cae377d84bac44
[]
no_license
AlexWuDDD/designPattern2
dfa6166bda17a4974bc892177f19f63485fca575
9cb7bb03b73bfcdab51320d9b2afb1a85f54f0ae
refs/heads/master
2020-05-28T07:48:59.065861
2019-06-03T22:03:05
2019-06-03T22:03:05
188,927,758
0
0
null
null
null
null
UTF-8
C++
false
false
231
hpp
testPP.hpp
// // testPP.hpp // designPattern2 // // Created by Wu.Alex on 2019/5/30. // Copyright © 2019 Wu.Alex. All rights reserved. // #ifndef testPP_hpp #define testPP_hpp #include <stdio.h> void testPP(); #endif /* testPP_hpp */
f0bc54058b990c979aca50edde06572018564a40
a871415fe39f81e55851346d5ef7ad4823ac7d28
/example/eigensolver.cc
4e3d1c939330308ab3ccc67da5c9536f23d48a29
[ "MIT" ]
permissive
PeterGerds/HAMLS
18892e5bc30a75a28ff37d3ad439a65d691f236c
6531765a364b44c02e3763b5d3283fdde980b2f2
refs/heads/master
2020-08-03T06:46:10.460169
2019-11-14T07:40:59
2019-11-14T07:40:59
211,658,319
0
0
null
null
null
null
UTF-8
C++
false
false
24,528
cc
eigensolver.cc
//---------------------------------------------------------------------------------------------- // This file is part of the HAMLS software. // // MIT License // // Copyright (c) 2019 Peter Gerds // // 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. //---------------------------------------------------------------------------------------------- // Project : HAMLS // File : eigensolver.cc // Description : example for H-AMLS methopd applied to an elliptic PDE eigenvalue problem // Author : Peter Gerds // Copyright : Peter Gerds, 2019. All Rights Reserved. #include <iostream> #include <hlib.hh> #include <boost/format.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include "hamls/TEigenArnoldi.hh" #include "hamls/TEigenArpack.hh" #include "hamls/THAMLS.hh" using namespace std; using namespace HLIB; using namespace boost::filesystem; using namespace boost::program_options; using HLIB::uint; using boost::format; using std::cout; using std::endl; using std::unique_ptr; using std::string; using real_t = HLIB::real; using complex_t = HLIB::complex; using namespace HAMLS; namespace { template < typename T > string mem_per_dof ( T && A ) { const size_t mem = A->byte_size(); const size_t pdof = size_t( double(mem) / double(A->rows()) ); return Mem::to_string( mem ) + " (" + Mem::to_string( pdof ) + "/dof)"; } // // Print some general informations of the given sparse matrix // TSparseMatrix * import_matrix ( const std::string fmatrix ) { cout<<endl; cout<<" importing sparse matrix from file \'"<<fmatrix<<"\'"<<endl; THLibMatrixIO matrix_io; unique_ptr< TMatrix > K( matrix_io.read( fmatrix ) ); if ( K.get() == nullptr ) { cout<<endl<<" warning: no matrix found" << endl; exit( 1 ); }// if if ( ! IS_TYPE( K.get(), TSparseMatrix ) ) { // try to convert to sparse cout<<endl<<" warning: matrix is of type "<<K->typestr()<<" --> converting to sparse format"; auto T = to_sparse( K.get() ); if ( T.get() != nullptr ) K = std::move( T ); else exit( 1 ); }// if TSparseMatrix * S = ptrcast( K.release(), TSparseMatrix ); if ( S->rows() != S->cols() ) { cout<<endl<<" warning: matrix not quadratic" << endl; exit( 1 ); }// if if ( S->test_symmetry() ) S->set_form( symmetric ); cout << " matrix has dimension " << S->rows() << " x " << S->cols() << endl; cout << " no of non-zeroes = " << S->n_non_zero() << " (" << format( "%.2f" ) % ( 1000.0 * double(S->n_non_zero()) / Math::square(double(S->rows())) ) << "‰" << ", avg=" << S->avg_entries_per_row() << ", max=" << S->max_entries_per_row() << ")" << endl; cout << " matrix is " << ( S->is_complex() ? "complex" : "real" ) << " valued" << endl; cout << " format = "; if ( S->is_unsymmetric() ) cout << "unsymmetric" << endl; else if ( S->is_symmetric() ) cout << "symmetric" << endl; else if ( S->is_hermitian() ) cout << "hermitian" << endl; cout << " size of sparse matrix = " << mem_per_dof( S ) << endl; cout << " |S|_F = " << format( "%.6e" ) % norm_F( S ) << endl; return S; } }// namespace anonymous // // // main function // // int main ( int argc, char ** argv ) { //===================================================================== // program options //===================================================================== //--------------------------------------------------------- // general options //--------------------------------------------------------- int input_hlib_verbosity = 1; real_t input_eta = real_t(50); uint input_nmin = 0; size_t input_n_ev = 5; int input_nthreads = 0; string input_data_path = "/home/user/"; bool input_print_solver_info = false; //--------------------------------------------------------- // basic HAMLS options //--------------------------------------------------------- real_t input_rel_accuracy_transform = real_t(1e-8); uint input_max_dof_subdomain = 1000; //--------------------------------------------------------- // options for mode selection options applied in HAMLS //--------------------------------------------------------- real_t input_c_subdomain = real_t(1.5); real_t input_c_interface = real_t(1.0); real_t input_c_condense = real_t(6.0); real_t input_e_subdomain = real_t(1)/real_t(3.0); real_t input_e_interface = real_t(1)/real_t(2.0); //--------------------------------------------------------- // options for classical iterativ eigensolver //--------------------------------------------------------- real_t input_shift = real_t(0); //===================================================================== // define command line options //===================================================================== // define command line options options_description all_opts; options_description vis_opts( "usage: eigensolver [options] data_path\n where options include" ); options_description general_opts( "General options", 0 ); options_description HAMLS_opts( "Basic options of H-AMLS", 0 ); options_description modalTrunc_opts( "Options for the modal trunction applied in H-AMLS", 0 ); options_description arnoldi_opts( "Options for the classical iterativ eigensolver", 0 ); options_description hid_opts( "Hidden options", 0 ); positional_options_description pos_opts; variables_map vm; // general options general_opts.add_options() ( "help,h", ": print this help text" ) ( "hlib_verbosity", value<int>(), ": HLIBpro verbosity level" ) ( "eta", value<real_t>(), ": set eta for admissible condition" ) ( "nmin", value<uint>(), ": set minimal cluster size" ) ( "n_ev", value<size_t>(), ": set the number of sought eigenpairs" ) ( "threads", value<int>(), ": number of threads used for parallel computation (if set to 0 all available threads are used)" ) ( "print_solver_info", ": print basic information regarding eigensolver execution to logfile" ); // basic options of HAMLS HAMLS_opts.add_options() ( "rel_accuracy_transform", value<real_t>(), ": relative accurcy of H-matrix arithmetic used for the problem transformation in H-AMLS" ) ( "max_dof_subdomain", value<uint>(), ": maximal degrees of freedom used for the subdomain problems applied in the matrix partitioning" ); // options for mode selection applied in HAMLS modalTrunc_opts.add_options() ( "c_subdomain", value<real_t>(), ": select k_i smallest eigenpairs of subdomain problem with size N_i where k_i := c_subdomain (N_i)^(e_subdomain)" ) ( "e_subdomain",value<real_t>(), ": select k_i smallest eigenpairs of subdomain problem with size N_i where k_i := c_subdomain (N_i)^(e_subdomain)" ) ( "c_interface", value<real_t>(), ": select k_i smallest eigenpairs of interface problem with size N_i where k_i := c_interface (N_i)^(e_interface)" ) ( "e_interface",value<real_t>(), ": select k_i smallest eigenpairs of interface problem with size N_i where k_i := c_interface (N_i)^(e_interface)" ) ( "c_condense", value<real_t>(), ": select k_i smallest eigenpairs of condensed subdomain problem with size N_i where k_i := c_condense (N_i)^(e_subdomain)" ); // parameter for classical iterativ eigensolver arnoldi_opts.add_options() ( "shift", value<real_t>(), ": set shift displacement in get_shift" ); hid_opts.add_options() ( "data_path", value<string>(), ": path to the folder that must contain the following input files of this program\n" " file 'K' contains the data for the sparse matrix K\n" " file 'M' contains the data for the sparse matrix M\n" " file 'coord' contains the data for the associated coordinate information of the problem\n"); // options for command line parsing vis_opts.add(general_opts).add(HAMLS_opts).add(modalTrunc_opts).add(arnoldi_opts); all_opts.add( vis_opts ).add( hid_opts ); // all "non-option" arguments should be "--data_path" arguments pos_opts.add( "data_path", -1 ); //===================================================================== // parse command line options //===================================================================== try { store( command_line_parser( argc, argv ).options( all_opts ).positional( pos_opts ).run(), vm ); notify( vm ); }// try catch ( unknown_option & e ) { cout << e.what() << ", try \"-h\"" << endl; exit( 1 ); }// catch //===================================================================== // eval command line options //===================================================================== if ( vm.count( "help") ) { cout << vis_opts << endl; cout << "usage: eigensolver [options] data_path "<< endl; cout << " where \'data_path\' is the path to the folder that must contain the following input files for this program (use corresponding HLIBpro format for each file):\n" " file 'K' contains the data for the sparse matrix K\n" " file 'M' contains the data for the sparse matrix M\n" " file 'coord' contains the data for the associated coordinate information of the problem\n"; exit( 1 ); }// if if ( vm.count( "data_path" ) ) input_data_path = vm["data_path"].as<string>(); else { cout << "usage: eigensolver [options] data_path "<< endl; exit( 1 ); }// if //--------------------------------------------------------- // general parameters //--------------------------------------------------------- if ( vm.count( "hlib_verbosity" ) ) input_hlib_verbosity = vm["hlib_verbosity"].as<int>(); if ( vm.count( "eta" ) ) input_eta = vm["eta"].as<real_t>(); if ( vm.count( "nmin" ) ) input_nmin = vm["nmin"].as<uint>(); if ( vm.count( "n_ev" ) ) input_n_ev = vm["n_ev"].as<size_t>(); if ( vm.count( "threads" ) ) input_nthreads = vm["threads"].as<int>(); if ( vm.count( "print_solver_info" ) ) input_print_solver_info = true; //--------------------------------------------------------- // basic HAMLS parameters //--------------------------------------------------------- if ( vm.count( "rel_accuracy_transform" ) ) input_rel_accuracy_transform = vm["rel_accuracy_transform"].as<real_t>(); if ( vm.count( "max_dof_subdomain" ) ) input_max_dof_subdomain = vm["max_dof_subdomain"].as<uint>(); //--------------------------------------------------------- // mode selection parameters of HAMLS //--------------------------------------------------------- if ( vm.count( "c_subdomain" ) ) input_c_subdomain = vm["c_subdomain"].as<real_t>(); if ( vm.count( "c_interface" ) ) input_c_interface = vm["c_interface"].as<real_t>(); if ( vm.count( "c_condense" ) ) input_c_condense = vm["c_condense"].as<real_t>(); if ( vm.count( "e_subdomain") ) input_e_subdomain = vm["e_subdomain"].as<real_t>(); if ( vm.count( "e_interface") ) input_e_interface = vm["e_interface"].as<real_t>(); //--------------------------------------------------------- // parameter for classical iterativ eigensolver //--------------------------------------------------------- if ( vm.count( "shift" ) ) input_shift = vm["shift"].as<real_t>(); try { //---------------------------------------------------------------------------- // init HLIBpro and set general HLIBpro options //---------------------------------------------------------------------------- INIT(); if ( input_nthreads != 0 ) CFG::set_nthreads( input_nthreads ); cout<<endl<<"# "<<CFG::nthreads()<<" threads are used for parallel computation"<<endl; if ( CFG::nthreads() > 1 ) CFG::Arith::use_dag = true; else CFG::Arith::use_dag = false; CFG::set_verbosity( input_hlib_verbosity ); ////////////////////////////////////////////////////////////////////////////// // // Load sparse matrices K and M, and the associated coordinate information // ////////////////////////////////////////////////////////////////////////////// cout<<endl<<"# Load Sparse Matrix K"; unique_ptr< TSparseMatrix > K( import_matrix( input_data_path + "input_K" ) ); cout<<endl<<"# Load Sparse Matrix M"; unique_ptr< TSparseMatrix > M( import_matrix( input_data_path + "input_M" ) ); cout<<endl<<"# Load Coordinate Data From File \'"<<input_data_path + "input_coord"<<"\'"<<endl; TAutoCoordIO coord_io; unique_ptr< TCoordinate > coord( coord_io.read ( input_data_path + "input_coord") ); ////////////////////////////////////////////////////////////////////////////// // // Construct H-matrix representations K_h and M_h of the sparse matrices K and M // ////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------- // 1) Apply nested dissection for the creation of the cluster tree //---------------------------------------------------------------------------- uint nmin; if ( input_nmin == 0 ) nmin = max( size_t(40), min( M->avg_entries_per_row(), size_t(100) ) ); else nmin = uint(input_nmin); // partitioning of clusters is based on an adaptive bisection TGeomBSPPartStrat part_strat( adaptive_split_axis ); //NOTE: Choose this special sparse matrix for the construction of cluster tree //that has everywhere there non-zero entries where K or M has a non-zero entry, //i.e., choose for example |K|+|M| TBSPNDCTBuilder ct_builder( M.get(), & part_strat, nmin ); unique_ptr< TClusterTree > ct( ct_builder.build( coord.get() ) ); //---------------------------------------------------------------------------- // 2) Create corresponding block cluster tree //---------------------------------------------------------------------------- TStdGeomAdmCond adm_cond( input_eta ); TBCBuilder bct_builder; unique_ptr< TBlockClusterTree > bct( bct_builder.build( ct.get(), ct.get(), & adm_cond ) ); //---------------------------------------------------------------------------- // 3) Construct corresponding H-matrix representations //---------------------------------------------------------------------------- TSparseMBuilder h_builder_K( K.get(), ct->perm_i2e(), ct->perm_e2i() ); TSparseMBuilder h_builder_M( M.get(), ct->perm_i2e(), ct->perm_e2i() ); TTruncAcc acc_exact( real_t(0) ); unique_ptr< TMatrix > K_h( h_builder_K.build( bct.get(), K->form(), acc_exact ) ); unique_ptr< TMatrix > M_h( h_builder_M.build( bct.get(), M->form(), acc_exact ) ); //////////////////////////////////////////////////////////////////////////////////////// // // Compute the eigendecomposition (D,Z) of the eigenvalue problem (K,M), i.e., // solve the problem K*Z = M*Z*D where D is a diagonal matrix containing the // eigenvalues and Z is the matrix containing the associated eigenvectors. // //////////////////////////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------------------------- // Solve eigenvalue problem using the ARPACK eigensolver // // - this solver is fast and very robust // - this solver computes numerically exact eigenpairs // - this solver is based on the well-proven and well-tested ARPACK library // - this solver is recommended only when a small portion of the eigenpairs is sought // - this solver supports shifts // - this solver can be performed with and without a symmentric problem transformation // - this solver has been parallelized as well, however, only one problem can be solved // by this solver concurrently, since the ARPACK library is not threadsafe //-------------------------------------------------------------------------------------- cout<<endl<<"# Solve Eigenvalue Problem (K,M) via ARPACK and H-Matrix Arithmetic"<<endl; // initialise the output data unique_ptr< TDenseMatrix > D_arpack ( new TDenseMatrix() ); unique_ptr< TDenseMatrix > Z_arpack ( new TDenseMatrix() ); // adjust the ARPACK eigensolver TEigenArpack arpack_solver; arpack_solver.set_shift ( input_shift ); arpack_solver.set_print_info ( input_print_solver_info); arpack_solver.set_n_ev_searched ( input_n_ev ); // solve the problem arpack_solver.comp_decomp( K_h.get(), M_h.get(), D_arpack.get(), Z_arpack.get() ); // analyse the computed eigensolution TEigenAnalysis eigen_analysis; eigen_analysis.set_verbosity( 4 ); eigen_analysis.analyse_vector_residual ( K.get(), M.get(), D_arpack.get(), Z_arpack.get(), ct.get() ); //-------------------------------------------------------------------------------------- // Solve eigenvalue problem using the Arnoldi eigensolver // // - this solver is fast // - this solver computes numerically exact eigenpairs // - this solver is a basic implementation of the Arnoldi solver and uses a symmetric // problem transformation, i.e., the generalized eigenvalue problem (K,M) is transformed // to a standard eigenvaluue // - this solver is recommended only when a small portion of the eigenpairs is sought // - this solver supports shifts // - this solver has been parallelized several problem can be solved by this solver concurrently //-------------------------------------------------------------------------------------- cout<<endl<<"# Solve Eigenvalue Problem (K,M) via Arnoli Method and H-Matrix Arithmetic"<<endl; // initialise the output data unique_ptr< TDenseMatrix > D_arnoldi ( new TDenseMatrix() ); unique_ptr< TDenseMatrix > Z_arnoldi ( new TDenseMatrix() ); // adjust the Arnoldi eigensolver TEigenArnoldi arnoldi_solver; arnoldi_solver.set_shift ( input_shift ); arnoldi_solver.set_print_info ( input_print_solver_info); arnoldi_solver.set_n_ev_searched ( input_n_ev ); // solve the problem arnoldi_solver.comp_decomp( K_h.get(), M_h.get(), D_arnoldi.get(), Z_arnoldi.get() ); // analyse the computed eigensolution eigen_analysis.analyse_vector_residual ( K.get(), M.get(), D_arnoldi.get(), Z_arnoldi.get(), ct.get() ); //-------------------------------------------------------------------------------------- // Solve eigenvalue problem using the H-AMLS method // // - this solver is very fast especially when many eigenpairs are sought // - this solver computes only approximative eigenpairs, however, the approximation // error can be controlled such that the error is of the order of the discretisation error // - this solver is highly recommended when a large portion of the eigenpairs is sought // and when numerical exact eigenpairs are not needed, e.g., when one is actually // interested in the eigensolutions of an underlying continuous problem //-------------------------------------------------------------------------------------- cout<<endl<<"# Solve Eigenvalue Problem (K,M) via H-AMLS Method"<<endl; // initialise the output data unique_ptr< TDenseMatrix > D_hamls ( new TDenseMatrix() ); unique_ptr< TDenseMatrix > Z_hamls ( new TDenseMatrix() ); // adjust basic options of the H-AMLS eigensolver THAMLS hamls_solver; hamls_solver.set_n_ev_searched ( input_n_ev ); hamls_solver.set_max_dof_subdomain( input_max_dof_subdomain ); hamls_solver.set_do_improving ( true ); hamls_solver.set_do_condensing ( true ); hamls_solver.set_print_info ( input_print_solver_info ); // set the accurcy of the H-matrix arithmetic used in H-AMLS TTruncAcc acc_transform( input_rel_accuracy_transform, real_t(0) ); hamls_solver.set_acc_transform_K( acc_transform ); hamls_solver.set_acc_transform_M( acc_transform ); // set options for mode selection applied in HAMLS hamls_solver.set_factor_subdomain ( input_c_subdomain ); hamls_solver.set_factor_interface ( input_c_interface ); hamls_solver.set_factor_condense ( input_c_condense ); hamls_solver.set_exponent_interface( input_e_interface ); hamls_solver.set_exponent_subdomain( input_e_subdomain ); // solve the problem hamls_solver.comp_decomp ( ct.get(), K_h.get(), M_h.get(), D_hamls.get(), Z_hamls.get(), K.get(), M.get() ); // analyse the computed eigensolution eigen_analysis.analyse_vector_residual ( K.get(), M.get(), D_hamls.get(), Z_hamls.get(), ct.get() ); DONE(); }// try catch ( Error & e ) { cout << e.to_string() << endl; }// catch catch ( std::exception & e ) { std::cout << e.what() << std::endl; }// catch return 0; }
ca9961af447932b6dfc35c327cc5dcf006e4c998
620824781c6639c8b87c8a13f19caae5c4615222
/Malnati_Lab01/Malnati_Lab1/Malnati_Lab1/StringBuffer.cpp
dae508867b0cdc3fbc1f53aabcaa7413eb3c3f5d
[ "MIT" ]
permissive
MartinoMensio/PDS-Labs
ea6f3524c1453c897e49d8564a8dae59d8d128da
21e1d6c7492d13e050bad1e9681cb215837ae820
refs/heads/master
2021-06-04T23:31:41.200886
2017-06-28T09:40:34
2017-06-28T09:40:34
58,085,919
5
0
MIT
2020-02-25T23:58:30
2016-05-04T21:43:11
C
UTF-8
C++
false
false
2,039
cpp
StringBuffer.cpp
#include "StringBuffer.h" StringBuffer::StringBuffer() { bufLength = DEF_SIZE; buf = new char[DEF_SIZE]; length = 0; } StringBuffer::StringBuffer(const char * str) { int l = strlen(str); bufLength = (l / DEF_SIZE + 1) * DEF_SIZE; buf = new char[bufLength]; strcpy_s(buf, bufLength, str); length = l; } StringBuffer::StringBuffer(const StringBuffer & sb) { bufLength = sb.bufLength; length = sb.length; buf = new char[sb.bufLength]; strcpy_s(buf, bufLength, sb.buf); } StringBuffer::~StringBuffer() { delete[] buf; } size_t StringBuffer::size() { return length; } size_t StringBuffer::bufsize() { return bufLength; } void StringBuffer::clear() { length = 0; strcpy_s(buf, bufLength, ""); } void StringBuffer::insert(const char * str, size_t pos) { int str_l = strlen(str); if (length + str_l >= bufLength) { // need to reallocate the buffer int newSize = length + str_l; int newBufLength = (newSize / DEF_SIZE + 1) * DEF_SIZE; char *newBuf = new char[newBufLength]; strcpy_s(newBuf, bufLength, buf); delete[] buf; buf = newBuf; bufLength = newBufLength; length = strlen(buf); } if (pos > length) { // insert spaces for (size_t i = length; i < pos; i++) { buf[i] = ' '; } // terminate string buf[pos] = 0; } else { // move forward the chars starting from pos for (int i = length; i >= (signed) pos; i--) { buf[str_l + i] = buf[i]; } } // insert string for (int i = 0; i < str_l; i++) { buf[i + pos] = str[i]; } //buf[pos + str_l] = 0; // update length length = strlen(buf); } void StringBuffer::insert(const StringBuffer & sb, size_t pos) { char *str = sb.buf; insert(str, pos); } void StringBuffer::append(const char * str) { int pos = strlen(buf); insert(str, pos); } void StringBuffer::append(const StringBuffer & sb) { char *str = sb.buf; append(str); } const char * StringBuffer::c_str() { return buf; } void StringBuffer::set(const char * str) { clear(); append(str); } void StringBuffer::set(const StringBuffer & s) { set(s.buf); }
1ff2636c926c54c41319eb035bee362f51ecaf95
e9172462c822ad88c7d32d46c0d7d9ec90fe15c1
/day04/ex03/AMateria.hpp
76a02b639543df0f8df81560e19fb647f96eeb63
[]
no_license
AnaChepurna/CPP_Piscine
c0628e8ba04adc22427f59e9095af3ce360ff20d
092e98fab6501cb7c3991c3777bda2130ba0f720
refs/heads/master
2020-03-20T22:12:15.908691
2018-06-29T14:46:09
2018-06-29T14:46:09
137,785,229
0
0
null
null
null
null
UTF-8
C++
false
false
594
hpp
AMateria.hpp
// // Created by Anastasia CHEPURNA on 6/23/18. // #ifndef AMATERIA_HPP # define AMATERIA_HPP #include "ICharacter.hpp" #include <iostream> class AMateria { private: std::string type; unsigned int xp; public: AMateria(void); AMateria(std::string const & type); AMateria(AMateria const & cpy); virtual ~AMateria(); virtual AMateria & operator=(AMateria const & rhs); std::string const & getType() const; unsigned int getXP() const; void setXP(); virtual AMateria* clone() const = 0; virtual void use(ICharacter& target); }; #endif
8105d084fbd6e5d9083503c929f28778b1ab6085
80e684fc50d835520ffacd00d5428037157c73ed
/Lab4Testing/Lab4Testing/ATM.h
649b26b72b37d22d5bc6cd0338bbf487447e986d
[]
no_license
ClaushWong/c-plus-plus
679ea2df0374a790e7e4500aebe894902f892b21
cb7ddbba5c328d72fc98bd37554a964b9685a049
refs/heads/master
2020-04-08T00:24:14.596879
2019-05-23T11:05:00
2019-05-23T11:05:00
158,850,757
0
0
null
2019-01-23T05:53:56
2018-11-23T15:40:00
C++
UTF-8
C++
false
false
312
h
ATM.h
#ifndef ATM_H #define ATM_H #include <string> class BankAccount; class ATM { public: ATM(int AN, std::string NM,int bal=0); ATM(); double Deposit(double d, int c); double Withdrawal(double w, int c); void displayBalance(); int getAN(); private: BankAccount *ptr; }; #endif
9f8a697dc2cf62745cd1e99578694ffbc2dcd32f
a366f060b1d0249529339a9bbb4e96b223e4e86e
/DH_Key_&_aes_community/DH_Client/Client_run.cpp
4836f0c2cbab89c87c29af503732832135894668
[]
no_license
kkoogqw/cryptography
7d3212b57b5c39a9796b01a2410fdfec8678c73d
bd358001d82df0ef4a2d1f0e1457bfadba4a5aa2
refs/heads/master
2020-09-06T11:48:52.444990
2019-11-08T08:20:48
2019-11-08T08:20:48
220,414,490
1
0
null
null
null
null
GB18030
C++
false
false
5,964
cpp
Client_run.cpp
#include "DH_AES_init.h" #include <stdlib.h> #include <stdio.h> #include <winsock2.h> #include <string.h> #include <time.h> #include <windows.h> #include <process.h> #include <math.h> #define BUFLEN 2000 // 缓冲区大小 #define WSVERS MAKEWORD(2, 0) // 指明版本2.0 #pragma comment(lib,"ws2_32.lib") // 指明winsock 2.0 Llibrary SOCKET sock, sockets[100] = { NULL }; // int cc; char *packet = NULL; char *pts, *input; HANDLE hThread; unsigned threadID; BigInt temp_init = build_128_number(); BigInt g("2"); BigInt private_order = build_128_number(); BigInt mod_p; BigInt rec_key; string order = private_order.to_string(private_order); string send_key; string AES_key; // 标识状态: // 0 等待接收mod p // 1 收到 p 计算完成 g ^ x mod p,等待发送完成 // 2 已经发送完成 g ^ x mod p, 准备接受对方密钥,计算 AES key // 3 连接建立完成,可以发送消息 // int state = 0; unsigned int __stdcall Chat(PVOID PM) { time_t now; (void)time(&now); pts = ctime(&now); char buf[BUFLEN]; while (1) { int cc = recv(sock, buf, BUFLEN, 0); // cc为接收的字符数 if (cc == SOCKET_ERROR || cc == 0) { cout << "ERROR: " << GetLastError(); cout << " Lost the connection with the Server!" << endl; CloseHandle(hThread); (void)closesocket(sock); break; } else if (cc > 0) { if (state == 0) { string temp_p = buf; mod_p = unpack_rec_p(temp_p); send_key = pack_send_key_info(private_order, mod_p, g); //test print // cout << send_key << endl; char my_info_buf[BUFLEN]; sprintf(my_info_buf, send_key.c_str()); (void)send(sock, my_info_buf, sizeof(my_info_buf), 0); cout << "Waiting for another client..." << endl; state = 2; } else if (state == 2) { string temp_k_info = buf; cout << "building AES key..." << endl; rec_key = unpack_rec_key_info(temp_k_info); AES_key = build_encrypt_key(private_order, rec_key, mod_p); // test print // cout << "AES key: "; print_ciphertext(AES_key); cout << "AES key builds successfully!" << endl; cout << "Diffie-Hellman Key Exchange Agreement has finished!" << endl; state = 3; } else if (state == 3){ // 检查接收的消息包 // “[server]” 不进行解密直接输出 // “[Client]” 提取对应字段解密后输出 // 应当分别输出密文与对应翻译出的明文 string temp_msg = buf; string msg_from = temp_msg.substr(0, 8); if (msg_from == "[Server]") { cout << "From: "<< buf << endl; continue; } // 对buf中的字符提取: 对方IP/端口/线程号 else if (msg_from == "[Client]") { int msg_begin, msg_end; int client_info_begin, client_info_end; // 获取消息内容 for (int i = 0; i < temp_msg.length(); i++) { if (temp_msg[i] == '\n' && temp_msg[i + 1] == 'T' && temp_msg[i + 2] == 'h' && temp_msg[i + 3] == 'r') { client_info_begin = i; continue; } if (temp_msg[i] == '\t' && temp_msg[i + 1] == 'S' && temp_msg[i + 2] == 'a' && temp_msg[i + 3] == 'y') { client_info_end = i; continue; } if (temp_msg[i] == '=' && temp_msg[i + 1] == '>') { msg_begin = i + 2; continue; } if (temp_msg[i] == '<' && temp_msg[i + 1] == '=') { msg_end = i; break; } } string client_info = temp_msg.substr(client_info_begin, client_info_end - client_info_begin); string cip_msg = temp_msg.substr(msg_begin, msg_end - msg_begin); // test print cout << "From: " << msg_from << client_info << endl; cout << "Recived ciphertext: " << endl; print_ciphertext(cip_msg); // todo 解密部分 string decrypted_text = AES_128_CBC_decrypt(AES_key, cip_msg, "sysu"); cout << "Decrypt result: " << endl; print_decrypt_result(decrypted_text); cout << endl; cout << "Raw decrypt result:" << endl << decrypted_text << endl; } else { cout << "Cannot recognize the message source!" << endl; } } } } return 0; } int main() { cout << "===[ AES / Diffie-Hellman Chat test Program ]===" << endl; cout << "Name:\tGao Qian-wen" << endl; cout << "ID:\t16338002" << endl; cout << "Major:\tSDCS Information Security" << endl; cout << "====================[ Client ]====================" << endl; time_t now; (void)time(&now); pts = ctime(&now); char host_ip[] = "127.0.0.1"; /* server IP to connect */ char service_port[] = "5050"; /* server port to connect */ struct sockaddr_in sin; WSADATA wsadata; WSAStartup(WSVERS, &wsadata); memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons((u_short)atoi(service_port)); sin.sin_addr.s_addr = inet_addr(host_ip); sock = socket(PF_INET, SOCK_STREAM, 0); connect(sock, (struct sockaddr *)&sin, sizeof(sin)); hThread = (HANDLE)_beginthreadex(NULL, 0, Chat, NULL, 0, &threadID); cout << "You can send massage to others online!" << endl; cout << "And the massage you send will be encrypted by AES - 128 in CBC type." << endl; while (1) { char buf1[BUFLEN]; // todo // 输入消息进行加密打包发送 string plaintext; getline(cin, plaintext); if (plaintext == "exit") { break; } // AES 加密部分 string AES_encrypted_text = AES_128_CBC_encrypt(AES_key, plaintext, "sysu"); sprintf(buf1, AES_encrypted_text.c_str()); // gets_s(buf1); (void)send(sock, buf1, sizeof(buf1), 0); (void)time(&now); pts = ctime(&now); cout << "Send successfully!\tTime: " << pts << endl; } CloseHandle(hThread); closesocket(sock); WSACleanup(); /* 卸载某版本的DLL */ cout << "Plaese press ENTER to exit the prcess..." << endl; getchar(); return 0; /* exit */ }
93d844e5b967b8acacaacaa2cd632c5f6d083af8
9fed1d3f1bb3c4beaf292eecb6299a4d635d0be2
/ai.cpp
a87d4997cd6f1f7c63f0916a190910996c33b0b9
[]
no_license
mnikn/GoBang
b6e140b42c0b472e0e78ac23b2cc273c606117c6
96576e2d8781622d4260579825240a3bb8638b67
refs/heads/master
2020-06-05T08:34:04.413986
2015-10-06T15:40:16
2015-10-06T15:40:16
37,410,287
2
0
null
null
null
null
UTF-8
C++
false
false
27,543
cpp
ai.cpp
#include "ai.h" #include <QDebug> Ai::Ai() :tool(new Tool), alpha(-INFINITY), beta(INFINITY), score(0) { } Ai::~Ai() { delete tool; } /** * @brief Ai::greedAlgorithm * @param chessboard * @param playerChessboard * @param computerChessboard * @param colorFlag 当前玩家棋色 * @return 下棋点 */ const QPoint Ai::greedAlgorithm(int chessboard[15][15], int playerChessboard[15][15][8], int computerChessboard[15][15][8],int colorFlag) { getScore(chessboard,playerChessboard,computerChessboard,colorFlag); int max_score = 0; QPoint targetPoint; targetPoint.setX(0); targetPoint.setY(0); //遍历棋型表找最佳点 for (int i=0;i<15;i++){ for (int j=0;j<15;j++){ for (int a=0;a<8;a++){ if (max_score < computerChessboard[i][j][a] && chessboard[i][j] ==0){ max_score = computerChessboard[i][j][a]; targetPoint.setX(i); targetPoint.setY(j); } else if(max_score < playerChessboard[i][j][a]&& chessboard[i][j] ==0){ max_score = playerChessboard[i][j][a]; targetPoint.setX(i); targetPoint.setY(j); } } } } return targetPoint; } /** * @brief Ai::minMax * @param depth * @param chessboard * @param playerChessboard * @param computerChessboard * @param isComputerTerm * @param colorFlag * @return */ int Ai::minMax(const int &depth,int chessboard[15][15], int playerChessboard[15][15][8], int computerChessboard[15][15][8],int isComputerTerm,int colorFlag) { int best=0,val=0; if(depth==0||tool->checkWin(chessboard)==true){ return this->getScore(chessboard,playerChessboard,computerChessboard,colorFlag); } else{ //极大节点 if (isComputerTerm ==true){ best = -INFINITY; for (int i=0;i<15;i++){ for (int j=0;j<15;j++){ if (chessboard[i][j]==EMPTY){ if (colorFlag ==BLACK) chessboard[i][j] = WHITE; else chessboard[i][j] = BLACK; isComputerTerm = false; val = minMax(depth-1,chessboard,playerChessboard,computerChessboard,isComputerTerm,colorFlag); chessboard [i][j] = EMPTY; if(best<val){ best = val; position.setX(i); position.setY(j); } } } } } //极小节点 else if(isComputerTerm == false){ best = INFINITY; for (int i=0;i<15;i++){ for (int j=0;j<15;j++){ if (chessboard[i][j]==EMPTY){ chessboard [i][j] = colorFlag; isComputerTerm = true; val = minMax(depth-1,chessboard,playerChessboard,computerChessboard,isComputerTerm,colorFlag); chessboard [i][j] = EMPTY; if(best>val){ best = val; } } } } } } return best; } /** * @brief Ai::minMaxAlgorithm * @param depth * @param chessboard * @param playerChessboard * @param computerChessboard * @param isComputerTerm * @param colorFlag * @return 下棋点 */ const QPoint Ai::minMaxAlgorithm(const int &depth,int chessboard[15][15], int playerChessboard[15][15][8], int computerChessboard[15][15][8],int isComputerTerm,int colorFlag) { this->minMax(depth,chessboard,playerChessboard,computerChessboard,isComputerTerm,colorFlag); return position; } /** * @brief Ai::getScore * @param chessboard * @param playerChessboard * @param computerChessboard * @param colorFlag * @return 分数 */ int Ai::getScore(int chessboard[15][15], int playerChessboard[15][15][8], int computerChessboard[15][15][8],int colorFlag) { int playerColoer = colorFlag; int computerColor; if (colorFlag == BLACK) computerColor = WHITE; else computerColor = BLACK; //置零 int count =0; score = 0; bool dead_flag= false; for (int i =0;i<15;i++){ for(int j=0;j<15;j++){ for(int a=0;a<8;a++){ playerChessboard[i][j][a] = EMPTY; computerChessboard[i][j][a] = EMPTY; } } } for (int i=0;i<15;i++){ for (int j=0;j<15;j++){ if (chessboard[i][j] ==EMPTY){ /***玩家棋盘估分***/ //横向 count = 0; dead_flag = false; for (int check =1;check<=5;check++){ if (chessboard[i-check][j] == playerColoer&&i>=2) count ++; else if(chessboard[i-check][j] == computerColor){ dead_flag = true; break; } else break; } for (int check =1;check<=5;check++){ if (chessboard[i+check][j] == playerColoer&&i<=13) count ++; else if(chessboard[i+check][j] == computerColor){ dead_flag = true; break; } else break; } if (count ==1){ if (dead_flag == false) playerChessboard[i][j][0] = 5; else playerChessboard[i][j][0] = 3; } else if(count ==2){ if (dead_flag == false) playerChessboard[i][j][0] = 50; else playerChessboard[i][j][0] = 30; } else if(count == 3){ if (dead_flag == false) playerChessboard[i][j][0] = 500; else playerChessboard[i][j][0] = 300; } else if (count == 4){ if (dead_flag == false) playerChessboard[i][j][0] = 5000; else playerChessboard[i][j][0] = 3000; } else if (count >=5){ playerChessboard[i][j][0] = 50000; } //纵向 count = 0; dead_flag = false; for (int check =1;check<=5;check++){ if (chessboard[i][j-check] == playerColoer&&j>=2) count ++; else if(chessboard[i][j-check]==computerColor){ dead_flag= true; break; } else break; } for (int check =1;check<=5;check++){ if (chessboard[i][j+check] == playerColoer&&j<=13) count ++; else if(chessboard[i][j+check]==computerColor){ dead_flag= true; break; } else break; } if (count ==1){ if (dead_flag ==false) playerChessboard[i][j][1] = 5; else playerChessboard[i][j][1] = 3; } else if(count ==2){ if (dead_flag ==false) playerChessboard[i][j][1] = 50; else playerChessboard[i][j][1] = 30; } else if(count == 3){ if (dead_flag ==false) playerChessboard[i][j][1] = 500; else playerChessboard[i][j][1] = 300; } else if (count == 4){ if (dead_flag ==false) playerChessboard[i][j][1] = 5000; else playerChessboard[i][j][1] = 3000; } else if (count >=5){ playerChessboard[i][j][1] = 50000; } //左斜线 count = 0; dead_flag = false; for (int check =1;check<=5;check++){ if (chessboard[i-check][j-check] == playerColoer&&i>=2&&j>=2) count ++; else if(chessboard[i-check][j-check]==computerColor){ dead_flag = true; break; } else break; } for (int check =1;check<=5;check++){ if (chessboard[i+check][j+check] == playerColoer&&i<=13&&j<=13) count ++; else if(chessboard[i+check][j+check]==computerColor){ dead_flag = true; break; } else break; } if (count ==1){ if (dead_flag == false) playerChessboard[i][j][2] = 5; else playerChessboard[i][j][2] = 3; } else if(count ==2){ if (dead_flag == false) playerChessboard[i][j][2] = 50; else playerChessboard[i][j][2] = 30; } else if(count == 3){ if (dead_flag == false) playerChessboard[i][j][2] = 500; else playerChessboard[i][j][2] = 300; } else if (count == 4){ if (dead_flag == false) playerChessboard[i][j][2] = 5000; else playerChessboard[i][j][2] = 3000; } else if (count >=5){ playerChessboard[i][j][2] = 50000; } //右斜线 count = 0; dead_flag = false; for (int check =1;check<=5;check++){ if (chessboard[i+check][j-check] == playerColoer&&i<=13&&j>=2) count ++; else if(chessboard[i+check][j-check]==computerColor){ dead_flag = true; break; } else break; } for (int check =1;check<=5;check++){ if (chessboard[i-check][j+check] == playerColoer&&i>=2&&j<=13) count ++; else if(chessboard[i-check][j+check]==computerColor){ dead_flag = true; break; } else break; } if (count ==1){ if (dead_flag == false) playerChessboard[i][j][3] = 5; else playerChessboard[i][j][3] = 3; } else if(count ==2){ if (dead_flag == false) playerChessboard[i][j][3] = 50; else playerChessboard[i][j][3] = 30; } else if(count == 3){ if (dead_flag == false) playerChessboard[i][j][3] = 500; else playerChessboard[i][j][3] = 300; } else if (count == 4){ if (dead_flag == false) playerChessboard[i][j][3] = 5000; else playerChessboard[i][j][3] = 3000; } else if (count >=5){ playerChessboard[i][j][3] = 50000; } /***电脑棋盘估分***/ //横向 count = 0; dead_flag = false; for (int check =1;check<=5;check++){ if (chessboard[i-check][j] == computerColor&&i>=2) count ++; else if(chessboard[i-check][j] == playerColoer){ dead_flag = true; break; } else break; } for (int check =1;check<=5;check++){ if (chessboard[i+check][j] == computerColor&&i<=13) count ++; else if(chessboard[i+check][j] == playerColoer){ dead_flag = true; break; } else break; } if (count ==1){ if (dead_flag ==false) computerChessboard[i][j][0] = 5; else computerChessboard[i][j][0] = 3; } else if(count ==2){ if (dead_flag ==false) computerChessboard[i][j][0] = 50; else computerChessboard[i][j][0] = 30; } else if(count == 3){ if (dead_flag ==false) computerChessboard[i][j][0] = 500; else computerChessboard[i][j][0] = 300; } else if (count == 4){ if (dead_flag ==false) computerChessboard[i][j][0] = 5000; else computerChessboard[i][j][0] = 3000; } else if (count >=5){ computerChessboard[i][j][0] = 50000; } //纵向 count = 0; dead_flag = false; for (int check =1;check<=5;check++){ if (chessboard[i][j-check] == computerColor&&j>=2) count ++; else if(chessboard[i][j-check]==playerColoer){ dead_flag= true; break; } else break; } for (int check =1;check<=5;check++){ if (chessboard[i][j+check] == computerColor&&j<=13) count ++; else if(chessboard[i][j+check]==playerColoer){ dead_flag= true; break; } else break; } if (count ==1){ if (dead_flag == false) computerChessboard[i][j][1] = 5; else computerChessboard[i][j][1] = 3; } else if(count ==2){ if (dead_flag == false) computerChessboard[i][j][1] = 50; else computerChessboard[i][j][1] = 30; } else if(count == 3){ if (dead_flag == false) computerChessboard[i][j][1] = 500; else computerChessboard[i][j][1] = 300; } else if (count == 4){ if (dead_flag == false) computerChessboard[i][j][1] = 5000; else computerChessboard[i][j][1] = 3000; } else if (count >=5){ computerChessboard[i][j][1] = 50000; } //左斜线 count = 0; dead_flag = false; for (int check =1;check<=5;check++){ if (chessboard[i-check][j-check] == computerColor&&i>=2&&j>=2) count ++; else if(chessboard[i-check][j-check]==playerColoer){ dead_flag = true; break; } else break; } for (int check =1;check<=5;check++){ if (chessboard[i+check][j+check] == computerColor&&i<=13&&j<=13) count ++; else if(chessboard[i+check][j+check]==playerColoer){ dead_flag = true; break; } else break; } if (count ==1){ if (dead_flag == false) computerChessboard[i][j][2] = 5; else computerChessboard[i][j][2] = 3; } else if(count ==2){ if (dead_flag == false) computerChessboard[i][j][2] = 50; else computerChessboard[i][j][2] = 30; } else if(count == 3){ if (dead_flag == false) computerChessboard[i][j][2] = 500; else computerChessboard[i][j][2] = 300; } else if (count == 4){ if (dead_flag == false) computerChessboard[i][j][2] = 5000; else computerChessboard[i][j][2] = 3000; } else if (count >=5){ computerChessboard[i][j][2] = 50000; } //右斜线 count = 0; dead_flag = false; for (int check =1;check<=5;check++){ if (chessboard[i+check][j-check] == computerColor&&i<=13&&j>=2) count ++; else if(chessboard[i+check][j-check]==playerColoer){ dead_flag = true; break; } else break; } for (int check =1;check<=5;check++){ if (chessboard[i-check][j+check] == computerColor&&i>=2&&j<=13) count ++; else if(chessboard[i-check][j+check]==playerColoer){ dead_flag = true; break; } else break; } if (count ==1){ if (dead_flag ==false) computerChessboard[i][j][3] = 5; else computerChessboard[i][j][3] = 3; } else if(count ==2){ if (dead_flag ==false) computerChessboard[i][j][3] = 50; else computerChessboard[i][j][3] = 30; } else if(count == 3){ if (dead_flag ==false) computerChessboard[i][j][3] = 500; else computerChessboard[i][j][3] = 300; } else if (count == 4){ if (dead_flag ==false) computerChessboard[i][j][3] = 5000; else computerChessboard[i][j][3] = 3000; } else if (count >=5){ computerChessboard[i][j][3] = 50000; } /***棋型判断***/ //死四活四 if(playerChessboard[i][j][0]==300&&(playerChessboard[i][j][1]==500||playerChessboard[i][j][2]==500||playerChessboard[i][j][3]==500)) playerChessboard[i][j][4] = 8000; if(playerChessboard[i][j][1]==300&&(playerChessboard[i][j][0]==500||playerChessboard[i][j][2]==500||playerChessboard[i][j][3]==500)) playerChessboard[i][j][4] = 8000; if(playerChessboard[i][j][2]==300&&(playerChessboard[i][j][0]==500||playerChessboard[i][j][1]==500||playerChessboard[i][j][3]==500)) playerChessboard[i][j][4] = 8000; if(playerChessboard[i][j][3]==300&&(playerChessboard[i][j][0]==500||playerChessboard[i][j][1]==500||playerChessboard[i][j][2]==500)) playerChessboard[i][j][4] = 8000; if(computerChessboard[i][j][0]==300&&(computerChessboard[i][j][1]==500||computerChessboard[i][j][2]==500||computerChessboard[i][j][3]==500)) computerChessboard[i][j][4] = 8000; if(computerChessboard[i][j][1]==300&&(computerChessboard[i][j][0]==500||computerChessboard[i][j][2]==500||computerChessboard[i][j][3]==500)) computerChessboard[i][j][4] = 8000; if(computerChessboard[i][j][2]==300&&(computerChessboard[i][j][0]==500||computerChessboard[i][j][1]==500||computerChessboard[i][j][3]==500)) computerChessboard[i][j][4] = 8000; if(computerChessboard[i][j][3]==300&&(computerChessboard[i][j][0]==500||computerChessboard[i][j][1]==500||computerChessboard[i][j][2]==500)) computerChessboard[i][j][4] = 8000; //死四活三 if(playerChessboard[i][j][0]==300&&(playerChessboard[i][j][1]==50||playerChessboard[i][j][2]==50||playerChessboard[i][j][3]==50)) playerChessboard[i][j][5] = 3500; if(playerChessboard[i][j][1]==300&&(playerChessboard[i][j][0]==50||playerChessboard[i][j][2]==50||playerChessboard[i][j][3]==50)) playerChessboard[i][j][5] = 3500; if(playerChessboard[i][j][2]==300&&(playerChessboard[i][j][0]==50||playerChessboard[i][j][1]==50||playerChessboard[i][j][3]==50)) playerChessboard[i][j][5] = 3500; if(playerChessboard[i][j][3]==300&&(playerChessboard[i][j][0]==50||playerChessboard[i][j][1]==50||playerChessboard[i][j][2]==50)) playerChessboard[i][j][5] = 3500; if(computerChessboard[i][j][0]==300&&(computerChessboard[i][j][1]==50||computerChessboard[i][j][2]==50||computerChessboard[i][j][3]==50)) computerChessboard[i][j][5] = 3500; if(computerChessboard[i][j][1]==300&&(computerChessboard[i][j][0]==50||computerChessboard[i][j][2]==50||computerChessboard[i][j][3]==50)) computerChessboard[i][j][5] = 3500; if(computerChessboard[i][j][2]==300&&(computerChessboard[i][j][0]==50||computerChessboard[i][j][1]==50||computerChessboard[i][j][3]==50)) computerChessboard[i][j][5] = 3500; if(computerChessboard[i][j][3]==300&&(computerChessboard[i][j][0]==50||computerChessboard[i][j][1]==50||computerChessboard[i][j][2]==50)) computerChessboard[i][j][5] = 3500; //双活三 if(playerChessboard[i][j][0]==50&&(playerChessboard[i][j][1]==50||playerChessboard[i][j][2]==50||playerChessboard[i][j][3]==50)) playerChessboard[i][j][6] = 1000; if(playerChessboard[i][j][1]==50&&(playerChessboard[i][j][0]==50||playerChessboard[i][j][2]==50||playerChessboard[i][j][3]==50)) playerChessboard[i][j][6] = 1000; if(playerChessboard[i][j][2]==50&&(playerChessboard[i][j][0]==50||playerChessboard[i][j][1]==50||playerChessboard[i][j][3]==50)) playerChessboard[i][j][6] = 1000; if(playerChessboard[i][j][3]==50&&(playerChessboard[i][j][0]==50||playerChessboard[i][j][1]==50||playerChessboard[i][j][2]==50)) playerChessboard[i][j][6] = 1000; if(computerChessboard[i][j][0]==50&&(computerChessboard[i][j][1]==50||computerChessboard[i][j][2]==50||computerChessboard[i][j][3]==50)) computerChessboard[i][j][6] = 1000; if(computerChessboard[i][j][1]==50&&(computerChessboard[i][j][0]==50||computerChessboard[i][j][2]==50||computerChessboard[i][j][3]==50)) computerChessboard[i][j][6] = 1000; if(computerChessboard[i][j][2]==50&&(computerChessboard[i][j][0]==50||computerChessboard[i][j][1]==50||computerChessboard[i][j][3]==50)) computerChessboard[i][j][6] = 1000; if(computerChessboard[i][j][3]==50&&(computerChessboard[i][j][0]==50||computerChessboard[i][j][1]==50||computerChessboard[i][j][2]==50)) computerChessboard[i][j][6] = 1000; //活四活三 if(playerChessboard[i][j][0]==500&&(playerChessboard[i][j][1]==500||playerChessboard[i][j][2]==500||playerChessboard[i][j][3]==500)) playerChessboard[i][j][7] = 5500; if(playerChessboard[i][j][1]==500&&(playerChessboard[i][j][0]==500||playerChessboard[i][j][2]==500||playerChessboard[i][j][3]==500)) playerChessboard[i][j][7] = 5500; if(playerChessboard[i][j][2]==500&&(playerChessboard[i][j][0]==500||playerChessboard[i][j][1]==500||playerChessboard[i][j][3]==500)) playerChessboard[i][j][7] = 5500; if(playerChessboard[i][j][3]==500&&(playerChessboard[i][j][0]==500||playerChessboard[i][j][1]==500||playerChessboard[i][j][2]==500)) playerChessboard[i][j][7] = 5500; if(computerChessboard[i][j][0]==500&&(computerChessboard[i][j][1]==500||computerChessboard[i][j][2]==500||computerChessboard[i][j][3]==500)) computerChessboard[i][j][7] = 5500; if(computerChessboard[i][j][1]==500&&(computerChessboard[i][j][0]==500||computerChessboard[i][j][2]==500||computerChessboard[i][j][3]==500)) computerChessboard[i][j][7] = 5500; if(computerChessboard[i][j][2]==500&&(computerChessboard[i][j][0]==500||computerChessboard[i][j][1]==500||computerChessboard[i][j][3]==500)) computerChessboard[i][j][7] = 5500; if(computerChessboard[i][j][3]==500&&(computerChessboard[i][j][0]==500||computerChessboard[i][j][1]==500||computerChessboard[i][j][2]==500)) computerChessboard[i][j][7] = 5500; } } } for (int i=0;i<15;i++){ for (int j=0;j<15;j++){ for (int a=0;a<4;a++){ score += computerChessboard[i][j][a]; score -= playerChessboard[i][j][a]; } } } return score; }
28451cd9904c807327d2786db69c93871a9f2ac9
cbbda1ec71197cba4ccedfc4ffbbf6fec766d9a1
/Algorithm/isolatationg.cpp
e45025e6f2cc547a5d764f5906cbb5e9a5cf782d
[]
no_license
hyeonzin/Algorithm
25184871f7c36c111a64542865d46f94f1d950c0
def408dce9e49de3bd5821419f55e0ad3fc4eb46
refs/heads/master
2020-03-27T10:07:11.608521
2018-09-21T12:37:59
2018-09-21T12:37:59
146,396,550
0
0
null
null
null
null
UHC
C++
false
false
1,830
cpp
isolatationg.cpp
#include<stdio.h> using namespace std; typedef struct bug{ int col; int row; int num; int dir; }Bug; int main() { int testcase; scanf("%d", &testcase); for (int i = 0; i < testcase; i++) { int cell, time, num; Bug bug[1000]; scanf("%d %d %d", &cell, &time, &num); for (int j = 0; j < num; j++) { scanf("%d %d %d %d", &bug[j].col, &bug[j].row, &bug[j].num, &bug[j].dir); } //입력 끝 for (int j = 0; j < time; j++) { //시간마다 for (int k = 0; k < num; k++) { //미생물 군집의 수 만큼 switch (bug[k].dir) { case 1: bug[k].col--; if (bug[k].col == 0) { bug[k].num = bug[k].num / 2; bug[k].dir = 2; } break; case 2: bug[k].col++; if ( bug[k].col == cell-1) { bug[k].num = bug[k].num / 2; bug[k].dir = 1; } break; case 3: bug[k].row--; if (bug[k].row == 0) { bug[k].num = bug[k].num / 2; bug[k].dir = 4; } break; case 4: bug[k].row++; if (bug[k].row == cell-1) { bug[k].num = bug[k].num / 2; bug[k].dir = 3; } break; default: break; } } for (int m = 0; m < num; m++) { //같은 위치에 있는 것끼리 더하기 (최대 네개까지 가능 ->단순비교ㄴㄴ) int max = bug[m].num; for (int k = m+1; k < num; k++) { if ((bug[m].col == bug[k].col) && (bug[m].row == bug[k].row)) { if (max < bug[k].num) { max = bug[k].num; bug[m].num += bug[k].num; bug[m].dir = bug[k].dir; bug[k].num = 0; bug[k].dir = 0; } else { bug[m].num += bug[k].num; bug[k].num = 0; bug[k].dir = 0; } } } } } int answer = 0; for (int j = 0; j < num; j++) { answer += bug[j].num; } printf("#%d %d\n", i + 1, answer); } }
ae6487b0b0798306b725242cce6fe2886f4c239d
c3c5f939717ffbbfaec59425230d76abacfdb711
/MATHEMATICAL ALGOS/find the nth catalan number.cpp
412b9c3be96199aaa30903e57149866437d23392
[]
no_license
himanshu14263/ALGORITHMS
a0dad744bb780cc2103c0b5ea6a72daa9269a2c4
2fd8a5f3ba9c99a83d650cb8678268ecee35520c
refs/heads/master
2021-01-25T06:45:50.310679
2017-07-11T18:23:09
2017-07-11T18:23:09
93,610,351
0
0
null
null
null
null
UTF-8
C++
false
false
389
cpp
find the nth catalan number.cpp
// PROBLEM :: FIND THE Nth CATALAN NUMBER #include <bits/stdc++.h> using namespace std; int nCk(int n,int k) { if(n-k<k) k=n-k; int res=1; for(int i=0;i<k;i++) { res*=(n-i); res/=(i+1); } return res; } int findCatalan(int n) { // catalan = 2nCn/(n+1) return (nCk(2*n,n))/(n+1); } int main() { int n; cout<<"enter the value of n\n"; cin>>n; cout<<findCatalan(n); }
01ef792cc7498ac0279009c9a7148bc3046e3805
caadfff86085e210e97e1a37f2625990dc1af14e
/Emotion Classifier/src/Feature.h
b6e5227eca39fcc4c9ed6700274d0d2ecee426bc
[ "MIT" ]
permissive
EStormLynn/Emotion-Classifier
89fae06b6d2d6865609389c171644a427bce63af
7986bd4968c319fb5fec82d1f7b6210031810c37
refs/heads/master
2021-01-23T03:03:56.009827
2018-03-29T12:49:30
2018-03-29T12:49:30
86,041,820
4
1
null
null
null
null
GB18030
C++
false
false
3,578
h
Feature.h
#pragma once #include "PXCFaceData.h" #include "iostream" class Feature { public: Feature(); virtual void CatureFeature(PXCFaceData facedata) {} //virtual void DynamicFeature(); double GetDistance(PXCPointF32 pointA, PXCPointF32 pointB); double GetDistance(PXCPoint3DF32 pointA, PXCPoint3DF32 pointB); double GetAngle(PXCPointF32 poinA, PXCPointF32 pointB, PXCPointF32 pointC); double GetAngle(PXCPoint3DF32 poinA, PXCPoint3DF32 pointB, PXCPoint3DF32 pointC); ~Feature(); }; class EuclideanFeature :public Feature { public: EuclideanFeature(PXCFaceData *facedata); void CatureFeature(PXCFaceData facedata); std::vector< std::vector<double> > getUList(); private: enum FeatureName { //1右眼眉毛外边界点 - 右眼眉毛内边界点(4, 0) EYEBROW_RIGHT_RIGHT_to_RIGHT_LEFT, //2 左眼眉毛外边界点-左眼眉毛内边界点 (9,5) EYEBROW_LEFT_RIGHT_to_LEFT_LEFT, //3 右眼眉毛内边界点-左眼眉毛内边界点 (0,5) EYEBROW_RIGHT_RIGHT_to_LEFT_RIGHT, //4 右嘴角点-左嘴角点 (33,39) EYELID_RIGHT_LEFT_to_LEFT_RIGHT, //5 右眼眉毛内边界点-右眼内眼角点 (0,10) EYEBROW_RIGHT_LEFT_to_EYELID_RIGHT_LEFT, //6 左眼眉毛内边界点-左眼内眼角点 (5,18) EYEBROW_LEFT_RIGHT_to_EYELID_LEFT_RIGHT, //7 右眼眉毛外边界点-右眼外眼角点 (4,14) EYEBROW_RIGHT_RIGHT_to_EYELID_RIGHT_RIGHT, //8 左眼眉毛外边界点-左眼外眼角点 (9,22) EYEBROW_LEFT_LEFT_to_EYELID_LEFT_LEFT, //9 右眼内眼角点-右眼外眼角点 (10,14) EYELID_RIGHT_LEFT_to_RIGHT_RIGHT, //10 左眼内眼角点-左眼外眼角点 (18,22) EYELID_LEFT_RIGHT_to_LEFT_LEFT, //11 右上眼皮中点-右下眼皮中点 (12,16) EYELID_RIGHT_TOP_to_RIGHT_BOTTOM, //12 左上眼皮中点-左下眼皮中点 (20,24) EYELID_LEFT_TOP_to_LEFT_BOTTOM, //13 右眼内眼角点-右鼻翼点 (10,30) EYELID_RIGHT_LEFT_to_NOSE_RIGHT, //14 左眼内眼角点-左鼻翼点 (18,32) EYELID_LEFT_RIGHT_to_NOSE_LEFT, //15 右眼外眼角点-右嘴角点 (14,33) EYELID_RIGHT_RIGHT_to_LIP_RIGHT, //16 左眼外眼角点-左嘴角点 (22,39) EYELID_LEFT_LEFT_to_LIP_LEFT, //17 右鼻翼点-右嘴角点 (30,33) NOSE_RIGHT_to_LIP_RIGHT, //18 左鼻翼点-左嘴角点 (32,39) NOSE_LEFT_to_LIP_LEFT, //19 鼻尖点-上嘴唇中点 (29,47) NOSE_TIP_to_UPPER_LIP_CENTER, //20 上嘴唇中点-下嘴唇中点 (47,51) UPPER_LIP_CENTER_to_LOWER_LIP_CENTER, //21 下嘴唇中点-下巴点 (51,61) LOWER_LIP_CENTER_to_CHIN, //22 右嘴角点-下巴点 (33,61) LIP_RIGHT_to_CHIN, //23 左嘴角点-下巴点 (39,61) LIP_LEFT_to_CHIN, //24 鼻尖点-右眼内眼角点 (29,10) NOSE_TIP_to_EYELID_RIGHT_LEFT, //25 鼻尖点-左眼内眼角点 (29,18) NOSE_TIP_to_EYELID_LEFT_RIGHT, }; }; class AngleFeature :public Feature { public: AngleFeature(PXCFaceData *facedata); void CatureFeature(PXCFaceData facedata); std::vector< std::vector<double> > getAList(); private: enum Mouth { //嘴角下拉 (61,33,58)(61,39,64) up //嘴角张大(47,51) up //嘴角上扬(30,33,56)(32,39,66)down }; enum Brow { //眼睛变小(12,14,16)(20,22,24)down //眼睛变大(12,14,16)(20,22,24)up }; };
b0d0f61a66d0f6e420bb6943dbd6f37c7325711d
c3298a651699d3cc0cb7ad53b7fad4069801a35f
/TwitterOAuth.hpp
21c9f151d2f40f00d632c924fbd2085a80b47364
[ "MIT" ]
permissive
leico/libTwitterOAuth
0f6af7f117004cabf44f602161dc07319c52e7ad
99db5d364e2ec890fb4a77894fba84d7fa2b7f13
refs/heads/master
2021-01-12T05:38:25.713882
2016-12-24T18:08:45
2016-12-24T18:08:45
77,153,918
3
0
null
null
null
null
UTF-8
C++
false
false
19,062
hpp
TwitterOAuth.hpp
// // TwitterOAuth.hpp // twitter-oauth-commandline // // Created by leico on 2016/12/22. // Copyright © 2016年 leico. All rights reserved. // #ifndef __TwitterOAuth_hpp___ #define __TwitterOAuth_hpp___ #include <iostream> #include <string> #include <sstream> #include <map> #include <ctime> #include <cstdlib> #include <algorithm> #include <locale> #include <oauth.h> #include <curl/curl.h> #include <picojson.h> #endif /* TwitterOAuth_hpp */ class TwitterOAuth{ using StrMap = std :: map<std :: string, std :: string>; using ustring = std :: basic_string<unsigned char>; private: //Twitter const value static const int NONCE_LETTER_COUNT; //32 static const std :: string SIGNATURE_METHOD; //"HMAC-SHA1" static const std :: string OAUTH_VERSION; //"1.0" //OAuth data StrMap _oauthdata; StrMap _restdata; StrMap _signaturedata; //Curl data struct curl_slist *_httpheader; CURL *_httphandle; CURLM *_multihandle; bool _curl_verbose; std :: string _curl_agent; //NULL_RESPONSEFUNC = 0; static size_t (*const NULL_RESPONSEFUNC)(char*, size_t, size_t, void*); //NULL_PROGRESSFUNC = 0; static int (*const NULL_PROGRESSFUNC)(void*, curl_off_t, curl_off_t, curl_off_t, curl_off_t); size_t (*_responsefunc)(char*, size_t, size_t, void*); int (*_progressfunc)(void*, curl_off_t, curl_off_t, curl_off_t, curl_off_t); void *_data_responsecallback; void *_data_progresscallback; public: TwitterOAuth(void); virtual ~TwitterOAuth(void); //strange, huge constructor TwitterOAuth( const std :: string& rest_method , const std :: string& url , const std :: string& consumer_key , const std :: string& consumer_secret , const std :: string& access_token , const std :: string& token_secret , const bool curl_verbose = false , const std :: string& curl_useragetn = "" , size_t(*const response_callback)(char*, size_t, size_t, void*) = NULL_RESPONSEFUNC , int (*const progress_callback)(void*, curl_off_t, curl_off_t, curl_off_t, curl_off_t) = NULL_PROGRESSFUNC , void *const data_passedresponsecallback = NULL , void *const data_passedprogresscallback = NULL ); //REST data passing functions const std :: string& RESTMethod(void) const; const std :: string& RESTMethod(const std :: string& method); const std :: string& URL(void) const; const std :: string& URL(const std :: string& url); //OAuth data passing functions const std :: string& ConsumerKey(void) const; const std :: string& ConsumerKey(const std :: string& consumer_key); const std :: string& ConsumerSecret(void) const; const std :: string& ConsumerSecret(const std :: string& consumer_secret); const std :: string& AccessToken(void) const; const std :: string& AccessToken(const std :: string& access_token); const std :: string& AccessTokenSecret(void) const; const std :: string& AccessTokenSecret(const std :: string& token_secret); //related callback pointers function const bool isResponseCallback(void) const; const bool ResponseCallback(size_t (*const response_callback)(char*, size_t, size_t, void*) ); const bool isProgressCallback(void) const; const bool ProgressCallback(int (*const progress_callback)(void*, curl_off_t, curl_off_t, curl_off_t, curl_off_t) ); const void * const PassedResponseCallbackData(void) const; const void * const PassedResponseCallbackData(void * const data); const void * const PassedProgressCallbackData(void) const; const void * const PassedProgressCallbackData(void * const data); //Curl data passing functions const bool CurlVerbose(const bool verbose); const bool CurlVerbose(void); const std :: string CurlUserAgent(const std :: string& agent); const std :: string CurlUserAgent(void); //Curl utility void CurlDisconnect (void); const int CurlConnectCount (void); const int CurlReadMsgs (std :: vector<std :: string>& msgs); //execute function void StartSendRequest(void); //and related to generate/create/construct OAuth parameters const std :: string GenerateQuery(void); const std :: string ConstructBaseString(const std :: string& query); const std :: string ConstructKeyString (void); const std :: string ConstructSignature(const std :: string& query, const std :: string& key); const std :: string ConstructAuthorizationHeader(void); //related oauth_nonce random byte chain that encoded base64 const std :: string GenerateNonce (const unsigned int lettercount); const ustring GenerateRandomLetters(const unsigned int lettercount); const std :: string EncodeBase64 (const ustring& letters); private: //initialize method called in constructor void InitParam(void); //convert from curl string to std :: string const std :: string CurlToString(char* cstr); }; /* ================================= * constructor/destructor * ================================= */ inline TwitterOAuth :: TwitterOAuth(void){ InitParam(); } inline TwitterOAuth :: ~TwitterOAuth(void){ CurlDisconnect(); curl_easy_cleanup(_httphandle); curl_global_cleanup(); } inline TwitterOAuth :: TwitterOAuth( const std :: string& rest_method , const std :: string& url , const std :: string& consumer_key , const std :: string& consumer_secret , const std :: string& access_token , const std :: string& token_secret , const bool curl_verbose , const std :: string& curl_useragent , size_t(*const response_callback)(char*, size_t, size_t, void*) , int (*const progress_callback)(void*, curl_off_t, curl_off_t, curl_off_t, curl_off_t) , void *const data_passedresponsecallback , void *const data_passedprogresscallback ) { InitParam(); RESTMethod(rest_method); URL (url); ConsumerKey(consumer_key); AccessToken(access_token); ConsumerSecret (consumer_secret); AccessTokenSecret(token_secret); ResponseCallback(response_callback); ProgressCallback(progress_callback); PassedResponseCallbackData(data_passedresponsecallback); PassedProgressCallbackData(data_passedprogresscallback); }; /* ============================== * related oauth_nonce * ============================== */ inline const std :: string TwitterOAuth :: GenerateNonce(const unsigned int lettercount){ return EncodeBase64( GenerateRandomLetters(lettercount) ); } inline const std :: string TwitterOAuth :: EncodeBase64(const std :: basic_string<unsigned char>& letters){ return CurlToString( oauth_encode_base64(static_cast<int>(letters.size()), letters.data()) ); } inline const std :: basic_string<unsigned char> TwitterOAuth :: GenerateRandomLetters(const unsigned int lettercount){ std :: basic_string<unsigned char> str; if(lettercount <= 0) return str; str.resize(lettercount); srand(static_cast<unsigned>(time(NULL))); for(int i = 0 ; i < lettercount ; ++ i) str.at(i) = rand() % UCHAR_MAX; return str; } /* ============================= * REST data passing functions * ============================= */ inline const std :: string& TwitterOAuth :: RESTMethod(void) const { return _restdata.at("RESTmethod"); } inline const std :: string& TwitterOAuth :: URL (void) const { return _restdata.at("url"); } inline const std :: string& TwitterOAuth :: RESTMethod(const std :: string& method){ return _restdata.at("RESTmethod") = method; }; inline const std :: string& TwitterOAuth :: URL (const std :: string& url) { return _restdata.at("url") = url; }; /* ============================= * OAuth data passing functions * ============================= */ //for construct query inline const std :: string& TwitterOAuth :: ConsumerKey(void) const { return _oauthdata.at("oauth_consumer_key"); } inline const std :: string& TwitterOAuth :: ConsumerKey(const std :: string& consumer_key) { return _oauthdata.at("oauth_consumer_key") = consumer_key; } inline const std :: string& TwitterOAuth :: AccessToken(void) const { return _oauthdata.at("oauth_token"); } inline const std :: string& TwitterOAuth :: AccessToken(const std :: string& access_token) { return _oauthdata.at("oauth_token") = access_token; } //for construct key inline const std :: string& TwitterOAuth :: ConsumerSecret (void) const { return _signaturedata.at("consumer_secret"); } inline const std :: string& TwitterOAuth :: ConsumerSecret (const std :: string& consumer_secret) { return _signaturedata.at("consumer_secret") = consumer_secret; } inline const std :: string& TwitterOAuth :: AccessTokenSecret(void) const { return _signaturedata.at("token_secret"); } inline const std :: string& TwitterOAuth :: AccessTokenSecret(const std :: string& token_secret) { return _signaturedata.at("token_secret") = token_secret; } /* ============================= * Related Callback functions * ============================= */ inline const bool TwitterOAuth :: isResponseCallback(void) const { return _responsefunc != NULL_RESPONSEFUNC; } inline const bool TwitterOAuth :: isProgressCallback(void) const { return _progressfunc != NULL_PROGRESSFUNC; } inline const bool TwitterOAuth :: ResponseCallback(size_t (*const response_callback)(char*, size_t, size_t, void*) ){ _responsefunc = response_callback; return true; } inline const bool TwitterOAuth :: ProgressCallback(int (*const progress_callback)(void*, curl_off_t, curl_off_t, curl_off_t, curl_off_t) ){ _progressfunc = progress_callback; return true; } inline const void * const TwitterOAuth :: PassedResponseCallbackData(void) const { return _data_responsecallback; } inline const void * const TwitterOAuth :: PassedProgressCallbackData(void) const { return _data_progresscallback; } inline const void * const TwitterOAuth :: PassedResponseCallbackData(void * const data) { return _data_responsecallback = data; } inline const void * const TwitterOAuth :: PassedProgressCallbackData(void * const data) { return _data_progresscallback = data; } /* ============================= * Curl data passing functions * ============================= */ inline const bool TwitterOAuth :: CurlVerbose(const bool verbose){ return _curl_verbose = verbose; } inline const bool TwitterOAuth :: CurlVerbose(void) { return _curl_verbose; } inline const std :: string TwitterOAuth :: CurlUserAgent(const std :: string& agent){ return _curl_agent = agent; } inline const std :: string TwitterOAuth :: CurlUserAgent(void) { return _curl_agent; } /* ============================= * Curl utility functions * ============================= */ inline void TwitterOAuth :: CurlDisconnect(void){ curl_multi_remove_handle(_multihandle, _httphandle); curl_multi_cleanup (_multihandle); //reset curl options curl_easy_reset(_httphandle); _multihandle = NULL; //cleanup header curl_slist_free_all(_httpheader); _httpheader = NULL; } inline const int TwitterOAuth :: CurlConnectCount (void){ if(_multihandle == NULL) return 0; int num; curl_multi_perform(_multihandle, &num); return num; } inline const int TwitterOAuth :: CurlReadMsgs(std :: vector<std :: string>& msgs){ msgs.clear(); if(_multihandle == NULL) return 0; struct CURLMsg *m = NULL; int count = 0; while( (m = curl_multi_info_read(_multihandle, &count)) ){ if(m -> msg == CURLMSG_DONE){ CURL *handle = m -> easy_handle; //get status and messages long http_code = 0; curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_code); //combine httpcode and result data std :: stringstream ss; ss << http_code << ":" << curl_easy_strerror( m -> data.result ); msgs.push_back( ss.str() ); } } return static_cast<const int>(msgs.size()); } /* ============================= * execute functions * ============================= */ inline void TwitterOAuth :: StartSendRequest(void){ using Pair = StrMap :: value_type; if(_multihandle != NULL) CurlDisconnect(); //generate signature base string , and signature key std :: string query = ConstructBaseString( GenerateQuery() ); std :: string key = ConstructKeyString (); //signature caricuration std :: string signature = ConstructSignature(query, key); //add signature in oauth data _oauthdata.insert( Pair("oauth_signature", signature) ); //construct authorization header std :: string authorizationheader = ConstructAuthorizationHeader(); //delete signature _oauthdata.erase("oauth_signature"); //curl URL set curl_easy_setopt(_httphandle, CURLOPT_URL, _restdata.at("url").c_str() ); //REST method POST mode if(RESTMethod() == "POST") curl_easy_setopt(_httphandle, CURLOPT_POST, 1L); //if you want show header etc, use CurlVerbose(true) if(CurlVerbose()) curl_easy_setopt(_httphandle, CURLOPT_VERBOSE, 1L); //announce your app name if( ! CurlUserAgent().empty() ) curl_easy_setopt(_httphandle, CURLOPT_USERAGENT, CurlUserAgent().c_str() ); //construct httpheader and set header _httpheader = curl_slist_append(_httpheader, authorizationheader.c_str() ); curl_easy_setopt(_httphandle, CURLOPT_HTTPHEADER, _httpheader); //if got any error, stop curl_easy_setopt(_httphandle, CURLOPT_FAILONERROR, 1); //transfer data compressed curl_easy_setopt(_httphandle, CURLOPT_ENCODING, "gzip"); //responsefunc called when any response got if( isResponseCallback() ) curl_easy_setopt(_httphandle, CURLOPT_WRITEFUNCTION, _responsefunc); //and data to responsefunc passed pointer if( PassedResponseCallbackData() != NULL) curl_easy_setopt(_httphandle, CURLOPT_WRITEDATA, _data_responsecallback); //progressfunc called regularly when connecting if( isProgressCallback() ){ curl_easy_setopt(_httphandle, CURLOPT_NOPROGRESS, 0L); curl_easy_setopt(_httphandle, CURLOPT_XFERINFOFUNCTION, _progressfunc); } //data to progressfunc passed pointer if( PassedProgressCallbackData() != NULL) curl_easy_setopt(_httphandle, CURLOPT_XFERINFODATA, _data_progresscallback ); //setting multi handles _multihandle = curl_multi_init(); if(_multihandle == NULL){ std :: cout << "multihandle is NULL" << std :: endl; exit(1); } //add twitterhandle to multi hundle curl_multi_add_handle(_multihandle, _httphandle); int count = 0; //connect twitter curl_multi_perform(_multihandle, &count); } /* ============================= * related authorization functions * see : https://dev.twitter.com/oauth/overview/authorizing-requests * ============================= */ inline const std :: string TwitterOAuth :: GenerateQuery(void){ _oauthdata.at("oauth_timestamp") = [&](){ std :: stringstream ss; ss << std :: time(NULL); return ss.str(); }(); _oauthdata.at("oauth_nonce") = [&](){ std :: string nonce = GenerateNonce(NONCE_LETTER_COUNT); nonce.erase( std :: remove_if( nonce.begin() , nonce.end () , [](char c) -> bool { return (std :: isalnum(c) == 0); } ) , nonce.end() ); return nonce; }(); std :: string query = [&](){ std :: stringstream ss; for(StrMap :: iterator it = _oauthdata.begin() ; it != _oauthdata.end() ; ++ it){ if(it != _oauthdata.begin()) ss << '&'; ss << CurlToString( curl_easy_escape(_httphandle, (it -> first) .c_str(), 0) ); ss << '=' << CurlToString( curl_easy_escape(_httphandle, (it -> second).c_str(), 0) ); } return ss.str(); }(); return query; } inline const std :: string TwitterOAuth :: ConstructBaseString(const std :: string& query){ std :: stringstream ss; ss << CurlToString( curl_easy_escape(_httphandle, _restdata.at("RESTmethod").c_str(), 0) ); ss << '&' << CurlToString( curl_easy_escape(_httphandle, _restdata.at("url") .c_str(), 0) ); ss << '&' << CurlToString( curl_easy_escape(_httphandle, query .c_str(), 0) ); return ss.str(); } inline const std :: string TwitterOAuth :: ConstructKeyString (void){ std :: stringstream ss; ss << CurlToString( curl_easy_escape(_httphandle, _signaturedata.at("consumer_secret").c_str(), 0) ); ss << '&' << CurlToString( curl_easy_escape(_httphandle, _signaturedata.at("token_secret") .c_str(), 0) ); return ss.str(); } inline const std :: string TwitterOAuth :: ConstructSignature(const std :: string& query, const std :: string& key){ std :: string signature = CurlToString( oauth_sign_hmac_sha1(query.c_str(), key.c_str()) ); signature = CurlToString( curl_easy_escape (_httphandle, signature.c_str(), 0) ); return signature; } inline const std :: string TwitterOAuth :: ConstructAuthorizationHeader(void){ std :: stringstream ss; for(StrMap :: iterator it = _oauthdata.begin() ; it != _oauthdata.end() ; ++ it){ ss << ( (it == _oauthdata.begin()) ? "Authorization: OAuth " : ", " ); ss << (it -> first) << '=' << '\"' << (it -> second) << '\"'; } return ss.str(); } inline void TwitterOAuth :: InitParam(void){ using Pair = StrMap :: value_type; _oauthdata.insert( Pair("oauth_signature_method", SIGNATURE_METHOD) ); _oauthdata.insert( Pair("oauth_version" , OAUTH_VERSION) ); _oauthdata.insert( Pair("oauth_consumer_key" , "") ); _oauthdata.insert( Pair("oauth_timestamp" , "") ); _oauthdata.insert( Pair("oauth_nonce" , "") ); _oauthdata.insert( Pair("oauth_token" , "") ); _restdata.insert( Pair("RESTmethod", "") ); _restdata.insert( Pair("url" , "") ); _signaturedata.insert( Pair("consumer_secret", "") ); _signaturedata.insert( Pair("token_secret", "") ); curl_global_init(CURL_GLOBAL_ALL); _httphandle = curl_easy_init(); _multihandle = NULL; _httpheader = NULL; if(_httphandle == NULL){ std :: cout << "httphandle is NULL" << std :: endl; exit(1); } CurlVerbose (false); CurlUserAgent(""); return; } inline const std :: string TwitterOAuth :: CurlToString(char* cstr){ std :: string str = cstr; curl_free(cstr); return str; }
5ec3f567d2a5d2a9e2553477ff0863857819c10f
e3d917181ee947fe596df4b66e1bdc066e9f9e02
/windowsbuild/MSVC2022/Qt/6.4.2/include/QtPrintSupport/6.4.2/QtPrintSupport/private/qcocoaprintersupport_p.h
73ebe7c90a7cc070288290603e0ac4498118e477
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
visit-dav/visit-deps
d1be0023fa4c91c02589e5d87ab4e48c99145bb5
d779eb48a12e667c3b759cedd3732053d7676abf
refs/heads/master
2023-08-08T15:30:28.412508
2023-07-31T22:34:52
2023-07-31T22:34:52
174,021,407
2
3
NOASSERTION
2023-07-06T16:07:22
2019-03-05T21:12:14
C++
UTF-8
C++
false
false
1,246
h
qcocoaprintersupport_p.h
// Copyright (C) 2020 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QCOCOAPRINTERSUPPORT_H #define QCOCOAPRINTERSUPPORT_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of internal files. This header file may change from version to version // without notice, or even be removed. // // We mean it. // #include <qpa/qplatformprintersupport.h> #include <private/qglobal_p.h> #ifndef QT_NO_PRINTER #include <QtPrintSupport/qtprintsupportglobal.h> QT_BEGIN_NAMESPACE class Q_PRINTSUPPORT_EXPORT QCocoaPrinterSupport : public QPlatformPrinterSupport { public: QCocoaPrinterSupport(); ~QCocoaPrinterSupport(); QPrintEngine *createNativePrintEngine(QPrinter::PrinterMode printerMode, const QString &deviceId = QString()) override; QPaintEngine *createPaintEngine(QPrintEngine *, QPrinter::PrinterMode printerMode) override; QPrintDevice createPrintDevice(const QString &id) override; QStringList availablePrintDeviceIds() const override; QString defaultPrintDeviceId() const override; }; QT_END_NAMESPACE #endif // QT_NO_PRINTER #endif // QCOCOAPRINTERSUPPORT_H
753fb70e6d3135c14fa1c2c5f86bd48700535605
1e613841e216e1b38360e683a00bee6964690e94
/main.cpp
35ebe1c1fee48a1cd0a6a620a71749ee8266c615
[]
no_license
Hordinska/Hordinska
65eeb1b16b0a36813cb96fc927d29a4ac1dc5ea7
c346a8df6754e634af8ba5ca8b062798d8d2472e
refs/heads/main
2023-03-11T12:07:22.563771
2021-02-24T20:15:59
2021-02-24T20:15:59
337,996,100
0
0
null
null
null
null
UTF-8
C++
false
false
2,923
cpp
main.cpp
#include <iostream> using namespace std; /*int main() { float a, b, c; cin >> a >> b >> c; float d = b*b-4*a*c; if (d>0) { float x1 = ((-b+sqrt(d))/2*a); float x2 = ((-b-sqrt(d))/2*a); cout << "x1=" << x1 << ""<<"x2="<< x2; } else if (d<0) { cout << "немає коренів."; } else if (d==0) { float x = -b/2*a; cout << "x=" << x; } return 0; }*/ /*int main() { int n, i; bool Proste = true; cout << "Enter a number"; cin >> n; for(i=2; i<= (sqrt(abs(n))); i++) { if(n%i == 0) { Proste = false; break; } } if(Proste) { cout << "кукусікі" << endl; } else { cout << "прівєт" << endl; } system("pause"); return 0; } */ // using another variable int main(){ int a = 3, b = 2, c; c= a; a = b; b = c; // adding and subtracting int main(){ int a = 3, b = 2, c; a += b; b=a-b; a=a-b; // multiplication and division int main(){ int a = 3, b = 2, c; a*=b; b=a/b; a=a/b; //&& - conunctia, || - disunctia } */ /*int main(){ int a, b, c; cout<<"enter a b and c"<<endl; cin >> a>>b>>c; if (a<b && a<c){ cout<<a; if(b<c){ cout<<b; cout<<c; } else{ cout<<c; cout<<b; } } else if(b<a && b<c){ cout<<b; if(a<c){ cout<<a; cout<<c; } else{ cout<<c; cout<<a; } } else if(c<a && c<b){ cout<<c; if(a<b){ cout<<a; cout<<b; } else{ cout<<b; cout<<a; } } } */ //2.a /*int minimum(int x, int y){ if(x<y){ return x; } else{ return y; } } int maximum(int x, int y){ if(x>y){ return x; } else{ return y; } } int main(){ int a, b, c; cout<<"enter a b and c"<<endl; cin >> a>>b>>c; int max, middle, min; min = minimum(a, minimum(b,c)); max = maximum(a, maximum(b, c)); middle = a+b+c - min - max; cout<<min<<" "<<middle<<" "<< max<<endl; } */ //2.b /* void main(){ int* arr; int n = 0; int s cout << "n="; cin >> n // arr = new int[n]; for (int i = 0; i<n; i++){ cout<<"a[" << i << "]="; cin>> arr[i]; } // s=0; for (int i = 0; i<n; i++) { s = s + *(arr + i); } // cout << "s=" << s << endl; system("pause") } void main(){ int* arr; int n = 0; int p cout << "n="; cin >> n // proud p=1; for (int i = 0; i<n; i++){ p=p*(i+1); } cout << " p ="<< p<< endl; }*/
31eb25d41deed10001eb01bd4eb5d43c22f2c405
852578007612a0fe81ff051d0356e9828358f087
/VividFlow/cmodules/petesting/grabFrameFromVideo.cpp
bd6ea04d81edc51151b952e7091948732c6828b6
[]
no_license
jjc224/VividFlow
6f7968d67961ed709cb83ab0211cfac5c125a2bf
3bf840a138fd0be91f01dfd837e1e35b96820b83
refs/heads/master
2020-03-11T12:45:45.247059
2020-01-05T10:47:22
2020-01-05T10:47:22
130,005,051
0
0
null
null
null
null
UTF-8
C++
false
false
1,907
cpp
grabFrameFromVideo.cpp
//Inputs: //1: Integer - Frame Index, the index number of the frame to grab //2: Video - Source Video //Outputs: //1: Image - The output image. //Video test module adapted by Philip Edwards from: /* * starter_video.cpp * * Created on: Nov 23, 2010 * Author: Ethan Rublee * * Modified on: April 17, 2013 * Author: Kevin Hughes * * A starter sample for using OpenCV VideoCapture with capture devices, video files or image sequences * easy as CV_PI right? */ #include <opencv2/imgcodecs.hpp> #include <opencv2/videoio/videoio.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <stdio.h> #include <vividflow.h> using namespace cv; using namespace std; //hide the local functions in an anon namespace namespace { int get_frame(std::string in_filename, std::string out_filename, int frameToCap) { VideoCapture capture(in_filename); int n = 0; Mat frame; for (int i = 0; i < frameToCap; i++) { capture >> frame; if (frame.empty()) { return -1; } } imwrite( out_filename, frame ); return 0; } } int main(int argc, char* argv[]) { int frameIdx = 0; string in_filename = ""; string out_filename = ""; initInterface(argc, argv); //input socket 1 - edge threshold frameIdx = readInteger(1); //input socket 2 - image file if(getInputSocketFilename(2) != NULL) { in_filename = getInputSocketFilename(2); } if(getInputSocketFilename(1) != NULL) { out_filename = getOutputSocketFilename(1); } cout << "frame to capture = " << frameIdx << endl; cout << "in filename = " << in_filename << endl; cout << "out filename = " << out_filename << endl; //process(capture); get_frame(in_filename, out_filename, frameIdx); freeInterface(); return 0; }
227f66600a98e55fab3b7de807377403af3552b2
1a543e7112e6a3b49098c2c8f8b1a7f1973a77fe
/Books/C++프로그래밍/Chapter 11/01_=Overloading.cpp
70a1496393939c90d2c2185d4193e09e7e99d33f
[]
no_license
booknu/PS_Relative
d0bc27cbc695511610b83a6f541410f4c13fafd8
944964bfed4ae04f38c20b1dfddea1c63f236f82
refs/heads/master
2022-06-09T02:22:12.306623
2020-05-05T08:35:20
2020-05-05T08:35:20
198,022,480
1
1
null
null
null
null
UHC
C++
false
false
2,879
cpp
01_=Overloading.cpp
///************ //<주소> : p443 //********** //<해결방안> : // //대입 연산자와 복사 생성자는 상당히 유사한데, 그 호출 시기가 다르다 // //[ 대입 연산자 ] //Obj src(...); //Obj cpy; //cpy = src; //==> 이미 초기화된 객체에 대입을 하면 대입 연산자 호출 // //[ 복사 생성자 ] //Obj src(...); //Obj cpy = src; //==> 초기화 하며 대입을 하면 복사 생성자 호출 // //따라서 객체 내부에 포인터형 변수가 있다면 대입 연산자, 복사 생성자를 모두 사용자 지정 해줘야 //깊은 복사, 초기화가 가능함 // //********** //<오답노트> : // //*/ // //#include <iostream> //using namespace std; // ///** // @class First // @date // @author LimSY // @brief 대입 연산자(=)을 오버로딩 하지 않은 클래스 //*/ //class First { //private: // int n1, n2; // //public: // First(int n1 = 0, int n2 = 0) : n1(n1), n2(n2) { } // friend ostream& operator<<(ostream &os, First &target); //}; // ///* // @brief cout << Second 객체 연산을 가능하게 만들어줌 // @param os ostream 객체 (ex: cout) // @param target 출력할 Second 객체 // */ //ostream& operator<<(ostream &os, First &target) { // os << target.n1 << ", " << target.n2; // return os; //} // ///** // @class Second // @date // @author LimSY // @brief 대입 연산자(=)을 오버로딩한 클래스 //*/ //class Second { //private: // int n3, n4; // //public: // Second(int n3 = 0, int n4 = 0) : n3(n3), n4(n4) { } // Second& operator=(const Second &copy) { // n3 = copy.n3; // n4 = copy.n4; // return *this; // a = b = c 와 같이 연속된 = 을 사용 가능하게 만들어줌 // } // friend ostream& operator<<(ostream &os, Second &target); //}; // ///* // @brief cout << Second 객체 연산을 가능하게 만들어줌 // @param os ostream 객체 (ex: cout) // @param target 출력할 Second 객체 //*/ //ostream& operator<<(ostream &os, Second &target) { // os << target.n3 << ", " << target.n4; // return os; //} // //int main() { // ////////////////////////////////////////////////////////////// // First fsrc(111, 222); // First fcpy; // Second ssrc(333, 444); // Second scpy; // // fcpy = fsrc; // default operator= 함수가 호출됨 (얕은 복사) // scpy = ssrc; // 위에서 지정한 operator= 함수가 호출됨 (깊은 복사) // // cout << "fcpy: " << fcpy << endl; // cout << "scpy: " << scpy << endl << endl; // // /////////////////////////////////////////////////////////////// // First fob1, fob2; // Second sob1, sob2; // // // 여러개의 = 연산자가 연속되어 있으면 오른쪽에서부터 진행 // fob1 = fob2 = fsrc; // default // sob1 = sob2 = ssrc; // 오버로딩 // // cout << "fob1: " << fob1 << endl; // cout << "fob2: " << fob2 << endl; // cout << "sob1: " << sob1 << endl; // cout << "sob2: " << sob2 << endl; // // return 0; //}
018d7e8f9f23bd1b946dda007e86f372fe99961a
6a529fefe58e3b587cbf9a065b98024bbf48d4d9
/console.cc
90a94c22793d52037072430a3b7f788e774b9109
[]
no_license
broderic/dynamic-shadows
68ac34eafe4269ab2e7d96fb4476375cc0466f3f
57111957ce5e19b9f229bbd313b8955487e7ebe2
refs/heads/master
2021-01-25T10:07:14.028449
2014-06-25T22:55:07
2014-06-25T22:55:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,166
cc
console.cc
#include <stdarg.h> #include "shad.h" int console_state = CONSOLE_FULL; float console_bottom = -1.0f; // console text #define CONSOLE_MAX_LINES 1024 #define CONSOLE_MAX_LINE_LEN 128 int c_input_len=0; int c_hoffset=0; int c_toffset=0; char c_input[128]; // font stuff texture_t *font; float font_xstep = 0.045; float font_ystep = 0.035; // background shader surf_t console_surf; face_t console_face; shader_t *background; // properties cvar_t *con_speed; /****************************************************************************/ /* Text handling */ /****************************************************************************/ // wrap long lines into several void wordWrapLine(int skipwhite, char *str, char *out, int max, int *outoff) { int i,j,k; char word[1024]; // skip leading whitespace i = 0; if (skipwhite) for (; str[i]; i++) // FIXME: cygwin won't compile this //if (!isspace(str[i])) break; if (str[i]!=' ') break; for (j=0; j<max && str[i]; ) { // read the next word for (k=0; j+k<max && str[i+k] && // FIXME: cygwin won't compile this // !isspace(str[i+k]); str[i+k]!=' '; ) word[k++] = str[i+k]; if (j + k >= max) break; // didn't overflow line, so copy it over word[k] = 0; out[j] = 0; strcat(out, word); j += k; i += k; // read some whitespace while (j < max && str[i] && //FIXME: cygwin won't compile this //isspace(str[i]) str[i] == ' ' ) out[j++] = str[i++]; } out[j] = 0; *outoff = i; } /****************************************************************************/ /* Draw the console */ /****************************************************************************/ void DrawConsoleBackground() { if (background == NULL) { glColor4f(.3, .3, .3, 1.0); glDisable(GL_TEXTURE_2D); glBegin(GL_QUADS); glVertex3f(-1.0, console_bottom+2, 0.0); glVertex3f( 1.0, console_bottom+2, 0.0); glVertex3f( 1.0, console_bottom+0, 0.0); glVertex3f(-1.0, console_bottom+0, 0.0); glEnd(); glEnable(GL_TEXTURE_2D); } else { DrawFace(&console_face, &player); } // yellow line at bottom glDisable(GL_TEXTURE_2D); glColor4fv(yellow); glBegin(GL_LINES); glVertex3f(-1.0, console_bottom, 0.0); glVertex3f( 1.0, console_bottom, 0.0); glEnd(); glEnable(GL_TEXTURE_2D); } void DrawConsoleText() { int j; float y; char *str; glColor4fv(white); SetBlend(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D, font->name); DrawString(-1, console_bottom+font_ystep+0.01, "$%s_", c_input); y = console_bottom + 2*font_ystep + 0.01; for (j=c_toffset; y<1.0; y+=font_ystep, j++) { str = Shell_GetText(j); if (!str) continue; // FIXME: do word wrap somehow DrawString(-1, y, " %s", str); } } void DrawConsole() { if (!console_state) return; //FIXME: remove this when console shader is implemented! SetAlphaFunc(ALPHA_FUNC_NONE); DrawConsoleBackground(); DrawConsoleText(); } void ConRegisterChar(char c) { char found[33]; switch(c) { case 8: // Backspace if (c_input_len) c_input[--c_input_len] = 0; break; case 9: // Tab if (Shell_AutoComplete(c_input, found)) { strcpy(c_input, found); strcat(c_input, " "); c_input_len = strlen(c_input); } break; case 127: // Delete // FIXME: do anything? break; case 13: // Enter conprintf(c_input); ProcessInput(c_input); Shell_AddHistory(c_input); c_input_len = 0; c_input[0] = 0; break; default: // normal input if (c_input_len < CONSOLE_MAX_LINE_LEN) { c_input[c_input_len++] = c; c_input[c_input_len] = 0; //strcpy(c_hist[c_nhist], c_input); } } } // FIXME: un-break shell history void ConRegisterSpecialChar(char c) { char *str; switch(c) { case GLUT_KEY_UP: str = Shell_GetHistory(++c_hoffset); if (str) { strcpy(c_input, str); c_input_len = strlen(c_input); } else { --c_hoffset; } break; case GLUT_KEY_DOWN: str = Shell_GetHistory(--c_hoffset); if (str) { strcpy(c_input, str); c_input_len = strlen(c_input); } else { ++c_hoffset; } break; case GLUT_KEY_PAGE_UP: c_toffset++; break; case GLUT_KEY_PAGE_DOWN: c_toffset--; break; } } void DrawCharacter(float x1, float y1, float x2, float y2, int c) { float ss = 1.0 / 16.0; float tx = (c & 15) / 16.0; float ty = (c / 16) / 16.0; if (c == '\n' || c == '\r') return; glBegin(GL_QUADS); glTexCoord2f(tx, ty); glVertex2f(x1, y1); glTexCoord2f(tx+ss, ty); glVertex2f(x2, y1); glTexCoord2f(tx+ss, ty+ss); glVertex2f(x2, y2); glTexCoord2f(tx, ty+ss); glVertex2f(x1, y2); glEnd(); } void DrawString(float x, float y, char *args, ...) { int i, len; float cx, sx, sy; char out[1024]; va_list list; va_start(list, args); vsnprintf(out, 1023, args, list); va_end(list); // fit 75 characters onto the screen sx = 2 * 1/75.0; sy = sx * player.viewwidth / player.viewheight; len = strlen(out); for(i=0, cx = x; i<len; i++) { DrawCharacter(cx, y, cx+sx, y-sy, out[i]); cx += sx; } } void LoadFont() { char font_file[] = "gfx/2d/bigchars.tga"; conprintf("Loading font: '%s'", font_file); font = LoadTexture(font_file); if (!font) error("Couldn't load font file!\n"); font->flags |= TEX_PERMANENT; TextureSetup(font, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP, GL_CLAMP); } // load the console shader and setup the face for drawing void LoadBackground() { mesh_t *mesh; char name[] = "console"; conprintf("Loading background shader: '%s'...", name); background = FindShader(name); if (!background) { conprintf("Console shader not found!"); } else { LoadShader(background, 1); } console_surf.flags = 0; console_surf.contents = 0; console_surf.shader = background; console_face.type = FACE_POLYGON; console_face.surface = &console_surf; console_face.mesh = mesh = MeshAllocate(); mesh->numverts = 4; mesh->numtris = 2; mesh->trinorm = NULL; mesh->numedges = 0; mesh->orvert = NULL; mesh->vertex = (vertex_t*)malloc(4*sizeof(vertex_t)); mesh->meshvert = (unsigned int*)malloc(6*sizeof(unsigned int)); // setup the vertices // FIXME: specify vertex colors? VectorSet3(-1, 0, 0, mesh->vertex[0].p); VectorSet3( 0, 0, 1, mesh->vertex[0].norm); VectorSet2( 0, 0, mesh->vertex[0].tc); VectorSet3( 1, 0, 0, mesh->vertex[1].p); VectorSet3( 0, 0, 1, mesh->vertex[1].norm); VectorSet2( 1, 0, mesh->vertex[1].tc); VectorSet3( 1, 0, 0, mesh->vertex[2].p); VectorSet3( 0, 0, 1, mesh->vertex[2].norm); VectorSet2( 1, 1, mesh->vertex[2].tc); VectorSet3(-1, 0, 0, mesh->vertex[3].p); VectorSet3( 0, 0, 1, mesh->vertex[3].norm); VectorSet2( 0, 1, mesh->vertex[3].tc); // set the meshverts mesh->meshvert[0] = 0; mesh->meshvert[1] = 1; mesh->meshvert[2] = 2; mesh->meshvert[3] = 0; mesh->meshvert[4] = 2; mesh->meshvert[5] = 3; } void ConsoleInit() { conprintf("================= ConsoleInit ================="); c_input_len = 0; c_input[0] = 0; register_cvar(&con_speed, "con_speed", "0.07"); LoadFont(); LoadBackground(); conprintf("================= ConsoleInit ================="); conprintf(" "); } // update position of console void UpdateConsole() { if (!console_state) return; if (!bsp_loaded) console_state = CONSOLE_FULL; double s = time_delta / (double)cvar_double(p_interval); if (console_state == CONSOLE_LOWERING) { console_bottom -= cvar_float(con_speed)*s; if (console_bottom < -0.5) { console_bottom = -0.5; console_state = CONSOLE_DOWN; } } else if (console_state == CONSOLE_RISING) { console_bottom += cvar_float(con_speed)*s; if (console_bottom >= 1.0) { console_bottom = 1.0; console_state = CONSOLE_HIDDEN; } } else if (console_state == CONSOLE_FULL) { console_bottom = -1.0; } // move the console vertices console_face.mesh->vertex[0].p[1] = console_bottom+2; console_face.mesh->vertex[1].p[1] = console_bottom+2; console_face.mesh->vertex[2].p[1] = console_bottom; console_face.mesh->vertex[3].p[1] = console_bottom; }
18dd91919f1a29062af96ca30cff2956363aecec
c17f6ab0f47739bc084c14f5e072523df2d5278f
/Rouguegame2/Window.h
506bb1899ac8babffcf72ac3233b90997d65ee75
[]
no_license
guidolippi94/ProjectRogueGame
c7e0d74a553eb21c94273986880c8afbae797964
61f65e2d4f8cff1bf2a9f11b51890bf827100189
refs/heads/master
2021-01-18T01:51:18.385913
2016-03-21T13:39:06
2016-03-21T13:39:06
54,392,641
0
0
null
2016-03-21T13:49:15
2016-03-21T13:49:14
null
UTF-8
C++
false
false
239
h
Window.h
// // Window.h // Rouguegame2 // // Created by Francesco Pegoraro on 20/03/16. // Copyright © 2016 Francesco Pegoraro. All rights reserved. // #ifndef Window_h #define Window_h class Window{ Window }; #endif /* Window_h */
462adccf2c87e1cec8f8b805b3cc80718b86c62f
c64c30cf44b6b3da80c17b1cd02eb93e93a14020
/TeamProject/buggedClient/buggedClient.cpp
8a9c9b931ff18d4fddaa9ca9ecf0db4486ea540b
[]
no_license
Krieglied/Assignments
d5e50585a63e0bcc108192909f75b9c5c66931d1
d02eee2fcc2edbd2fc59fc06377242d38a723edf
refs/heads/master
2021-06-21T13:39:50.673194
2020-12-01T16:54:37
2020-12-01T16:54:37
140,303,107
0
1
null
2018-08-28T18:53:11
2018-07-09T15:11:12
C++
UTF-8
C++
false
false
3,892
cpp
buggedClient.cpp
//Team Project Smith, Kreiser, Graham //August 22, 2018 #include "client.h" int __cdecl main(void) { WSADATA wsaData; int iResult; //Sets the socket needed for the connection SOCKET ListenSocket = INVALID_SOCKET; SOCKET ServerSocket = INVALID_SOCKET; struct addrinfo *result = NULL; struct addrinfo hints; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { std::cout << "WSAStartup failed with error: " << iResult << std::endl; return 1; } ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Resolve the server address and port iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); if (iResult != 0) { std::cout << "getaddrinfo failed with error: " << iResult << std::endl; WSACleanup(); return 1; } // Create a SOCKET for connecting to server ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { std::cout << "socket failed with error: " << WSAGetLastError() << std::endl; freeaddrinfo(result); WSACleanup(); return 1; } // Setup the TCP listening socket iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { std::cout << "bind failed with error: " << WSAGetLastError() << std::endl; freeaddrinfo(result); closesocket(ListenSocket); WSACleanup(); return 1; } freeaddrinfo(result); // Accepts a listener socket iResult = listen(ListenSocket, SOMAXCONN); if (iResult == SOCKET_ERROR) { std::cout << "listen failed with error: " << WSAGetLastError() << std::endl; closesocket(ListenSocket); WSACleanup(); return 1; } // Accept a client socket ServerSocket = accept(ListenSocket, NULL, NULL); if (ServerSocket == INVALID_SOCKET) { std::cout << "accept failed with error: " << WSAGetLastError() << std::endl; closesocket(ListenSocket); WSACleanup(); return 1; } std::stringstream output; // No longer need listening socket closesocket(ListenSocket); // Receive until the peer shuts down the connection do { std::vector<char> inputBuffer(5000); std::vector<char> outputBuffer; //Receives any incoming buffers from the server iResult = recv(ServerSocket, inputBuffer.data(), inputBuffer.size(), 0); std::cout << "Data has been received." << std::endl; //If the result is not -1, then resize inputBuffer to make sure that it can hold the bytes incoming if (iResult != -1) { inputBuffer.resize(iResult); } //If the result is not 0, information was pulled and can be processed if (iResult != 0) { //Central function that handles switch/cases for all the commands processCommand(inputBuffer, outputBuffer); std::cout << std::endl; char newbuffer[4096 * 2]; //If the command asks for a result (at this stage, all will), the result needs to be sent back //to the server for (int i = 0; i < outputBuffer.size(); i++) { newbuffer[i % sizeof(newbuffer)] = outputBuffer[i]; if ((i % sizeof(newbuffer)) == 0 && i != 0) { std::cout << newbuffer << std::endl; iResult = send(ServerSocket, newbuffer, sizeof(newbuffer), 0); } } iResult = send(ServerSocket, newbuffer, sizeof(newbuffer), 0); char end = 0; iResult = send(ServerSocket, &end, sizeof(end), 0); } //If 0 bytes has been sent, then the server has shutdown and so should the client else { break; } outputBuffer.clear(); } while (true); // shutdown the connection since we're done iResult = shutdown(ServerSocket, SD_SEND); if (iResult == SOCKET_ERROR) { std::cout << "shutdown failed with error: " << WSAGetLastError() << std::endl; closesocket(ServerSocket); WSACleanup(); return 1; } // cleanup closesocket(ServerSocket); WSACleanup(); return 0; }
605b68e206fcf3c42cce3ddcb4f6312de53129d1
5d774394ee218bdda3d581307fc4e771d7a2fff9
/test1/test1/test.cpp
b28f2f06ee0ef8daa9e143256f1b4d682522f238
[]
no_license
3zheng/chaos
26c96c16152c2430ca4740479dff471c867e496d
111fa8218644c4a0545a5ee115e1190ecd647e72
refs/heads/master
2021-07-26T14:54:22.904978
2017-11-07T07:48:57
2017-11-07T07:48:57
56,032,135
0
0
null
null
null
null
GB18030
C++
false
false
12,848
cpp
test.cpp
#include <stdio.h> #include <stdlib.h> #include <vector> #include <map> #include <stdio.h> #include <sys/timeb.h> #include <time.h> #include <set> #include <winsock.h> #include <inttypes.h> #pragma comment(lib, "Ws2_32.lib") using namespace std; void TestMaxRand() { printf("%x\n", RAND_MAX); } void TestStdPlusPlus() //测试Map的元素是否能直接进行++操作 { static vector<int> vec_test = {0, 6, 0}; static map<int, int> map_test = { { 1, 4 }, { 5, 22 } }; vec_test[1]++; auto it = map_test.find(5); if (it != map_test.end()) { it->second++; } printf("%d, %d\n", vec_test[1], it->second); return; } void TestVectorPoint() //测试指针元素的vector的语法 { struct MyStruct { int one = 2; }; MyStruct *p1 = new MyStruct; MyStruct *p2 = new MyStruct; p2->one = 6; vector<MyStruct*> vec_test = { p1, p2 }; for (auto it = vec_test.begin(); it != vec_test.end(); it++) { (*it)->one; //不好玩it->one不行,it->->one也不行 } } void TestFreadByDifferentSize() { char *buff = new char[1000000]; //申请1M内存 memset(buff, 0, 1000000); FILE *fp = fopen("adt-bundle-windows-x86-20130917.rar", "rb"); // FILE *fp = fopen("20150207-2013.log", "r"); if (nullptr == fp) { return; } fseek(fp, 0, SEEK_END); int size = ftell(fp); struct _timeb now, end_now; //以1M为步长 _ftime(&now); printf("现在%lld:%hd\n", now.time, now.millitm); FILE *fpwrite = fopen("test1M", "wb"); fseek(fp, 0, SEEK_SET); int ref = 0; while (!feof(fp)) { int ret = fread(buff, 1000000, 1, fp); fwrite(buff, 1000000, 1, fpwrite); } fclose(fpwrite); _ftime(&end_now); printf("1M结果,现在%lld:%hd,耗时%lld:%d\n", end_now.time, end_now.millitm, end_now.time - now.time, end_now.millitm - now.millitm); //以1K为步长 _ftime(&now); printf("现在%lld:%d\n", now.time, now.millitm); fpwrite = fopen("test1K", "wb"); fseek(fp, 0, SEEK_SET); while (!feof(fp)) { int ret = fread(buff, 1000, 1000, fp); fwrite(buff, 1000000, 1, fpwrite); } fclose(fpwrite); _ftime(&end_now); printf("1K结果,现在%lld:%hd,耗时%lld:%d\n", end_now.time, end_now.millitm, end_now.time - now.time, end_now.millitm - now.millitm); //以1B为步长 _ftime(&now); printf("现在%lld:%d\n", now.time, now.millitm); fpwrite = fopen("test1B", "wb"); fseek(fp, 0, SEEK_SET); while (!feof(fp)) { int ret = fread(buff, 1, 1000000, fp); fwrite(buff, 1000000, 1, fpwrite); } fclose(fpwrite); _ftime(&end_now); printf("1B结果,现在%lld:%d,耗时%lld:%d\n", end_now.time, end_now.millitm, end_now.time - now.time, end_now.millitm - now.millitm); fpwrite = nullptr; fclose(fp); fp = nullptr; delete buff; } //测试容器的迭代器被erase以后的指向问题 void TestContainIterator() { map<int, string> map_test = { { 5, "海贼王我当定了" }, { 2, "名船医我当定了" }, { 19, "海上钢琴师我当定了" }, { 12, "ALL BLUE我找定了" } }; auto it = map_test.find(5); if (it == map_test.end()) { return; } it = map_test.begin(); // it += 2; return; //这么做会出错,删除了5以后,不管是++it还是判断it是否等于map_test.end()都会出错 map_test.erase(5); if (++it == map_test.end()) { return; } else { printf("%d说:%s\n", it->first, it->second.c_str()); } } //如果已知vector的一个元素位置,并想对他进行删除,可以实用it = vector.begin() + 位置下标的方式来实现快速删除 void InterestingIterator() { vector<int> vec_test = { 2, 4, 6, 8, 1, 342, 32, 65, 76, 25 }; //假设我已知要删除的vector元素下标为4,即上面值为1的元素,那么我可以这么操作 auto it = vec_test.begin() + 4; vec_test.erase(it); //1已被删除 for (it = vec_test.begin(); it != vec_test.end(); it++) { printf("%d ", *it); } printf("\n"); } class ST_C2 { public: int c2[10]; }; class C1 { public: int num = 0; char *pbuff = nullptr; static ST_C2 *st2; public: C1(){ // printf("C1 is constructed\n"); } ~C1() { // printf("C1 is destroyed\n"); if (pbuff != nullptr) { // delete pbuff; 这里会造成二次释放哦 pbuff = nullptr; } } ST_C2 *GetC2() { return st2; } }; ST_C2 *C1::st2 = nullptr; void Construct() { C1 c1; c1.num = 1; c1.pbuff = new char[10]; strcpy(c1.pbuff, "hello"); map<int, C1> map_test; map_test.insert(map<int, C1>::value_type(3, c1)); int i = 0; i++; } void TestSizeOfEveryType() { int size = 0; size = sizeof(long); printf("long is %d\n", size); } void TestEnum() { enum MyEnum { ENUM1 = 3, ENUM2 = 3 }; MyEnum test1 = ENUM1; MyEnum test2 = ENUM2; printf("%d,%d\n", test1, test2); } void TestMutilmap() { multimap<int, string> multimap_test1 = { { 1, "hello " }, { 1, "world " }, { 1, "monkey " }, { 6, "luffy " }, { 1, "hello" } }; int size = multimap_test1.size(); auto pos = multimap_test1.equal_range(9); for (auto it = pos.first; it != pos.second; it++) { printf("%s", it->second.c_str()); } //查找1这key的多个值 pos = multimap_test1.equal_range(1); for (auto it = pos.first; it != pos.second; it++) { printf("%s", it->second.c_str()); } pos = multimap_test1.equal_range(6); for (auto it = pos.first; it != pos.second; it++) { printf("%s", it->second.c_str()); } pos = multimap_test1.equal_range(4); for (auto it = pos.first; it != pos.second; it++) { printf("%s", it->second.c_str()); } printf("\n"); typedef struct GroupT { int id = 0; string name = ""; inline bool operator<(const GroupT &Right) const { return this->id < Right.id; } }Group; Group group_test1; group_test1.id = 4; group_test1.name = "hello"; set<Group> set_test1 = { group_test1 }; Group group_test2; group_test2.id = 4; group_test2.name = "world"; auto it = set_test1.find(group_test2); printf("%s\n", it->name.c_str()); set_test1.insert(group_test2); } void TestUnsigned() { unsigned int a = 99; int b = -34; unsigned int c = static_cast<int>(a) + b; } void TestPrintf() { int a = 0x4fa5ef; printf("d is %08d, x is %08x\n", a, a); string b = 0; printf("%d\n", b); } void TestIPChange() { unsigned long Ip = 0x0a0101c0; int i_test = Ip % 0; in_addr address; address.S_un.S_addr = Ip; string strIp = inet_ntoa(address); string strTest, strTest2, strTest3; char buff[100] = ""; for (int i = 0; i < 100; i++) { buff[i] = static_cast<char>(i); } strTest.assign(buff, 50); strTest = buff; for (const char *pstr = strTest.c_str(); *pstr != 99; *pstr++) { printf("%c", *pstr); } strTest2.assign(strTest); strTest3 = strTest; } #define SERVERADDR_NUM 3 #define SERVER_LEN 30 //游戏房间列表结构 struct tagGameServer { WORD wGameType; //GAME_TYPE_INNER=0,GAME_TYPE_OUTER=1 (xuweiqun 2015-4-29) WORD wServerType; //房间标识 WORD wMatchType; //比赛类型 WORD wSortID; //排序号码 WORD wKindID; //名称号码 WORD wServerID; //房间号码 WORD wStationID; //站点号码 WORD wMaxConnect; //最大连接 WORD wServerPort; //房间端口 DWORD dwServerAddr[SERVERADDR_NUM]; //房间地址(电信、移动、联通) DWORD dwOnLineCount; //在线人数 DWORD dwMatchJoinCount; //报名人数 DWORD dwMatchStartCount; //开赛人数(普通场作特殊配置用0x0001用户列表乱序 0x0002禁止用户设置密码) DWORD dwSpreaderID; //房间推广ID LONG lCellScore; //单位积分 __int64 lLessScore; //最低积分 __int64 lMaxScore; //最高积分 LONG lMatchGold; //金币(报名费) LONG lMatchProve; //参赛卷(报名费) __time64_t tMatchStartTime; //开始时间 __time64_t tMatchEndTime; //结束时间 LONG lDefaulSortCol; //默认用户列表排序列(比赛房间作大厅右侧排序ID) TCHAR szServerName[SERVER_LEN]; //房间名称 TCHAR szRoomType[SERVER_LEN]; //房间类型 TCHAR szRewardInfo[SERVER_LEN]; //奖励信息 TCHAR szPrizeImageFileName[SERVER_LEN]; //奖品图片名称 }; struct CMD_CS_RegGameServer { tagGameServer GameServer; //房间信息 }; struct MyStruct { char seg1[7]; int seg2; uint64_t seg3; }; void TestDeleteMemory() { int size = sizeof(CMD_CS_RegGameServer); size = sizeof(MyStruct); char **rec = new char*[6000000]; //测试指针类型被改变后是否还能释放 for (int i = 0; i < 6000000; i++) { MyStruct *p_new = new MyStruct; rec[i] = static_cast<char*>((void*)p_new); //delete rec[i].pbuff; } for (int i = 0; i < 6000000; i++) { delete rec[i]; } delete rec; } void TestDosCommand() { system("rd funny\\SogouWP /q /s"); } void TestTime() { time_t now = 1434441600; struct tm *tm_now = nullptr; tm_now = localtime(&now); } void TestStaticMember() //测试静态成员变量 { C1 ob[10]; ST_C2 *p_c2 = ob[0].GetC2(); p_c2->c2[1] = 9; p_c2->c2[4] = 664; int tmp = ob[1].st2->c2[1]; } void WriteFile(string content) { FILE *fp = nullptr; fp = fopen("gate_user_detail.log", "a"); if (nullptr == fp) { return; } fseek(fp, 0L, SEEK_END); fwrite(content.c_str(), 1, content.size(), fp); fclose(fp); } /** * 将一个串拆分出来 * * @param arr 输出的字符串组 * @param strSource 源串 * @param strDelimit 分隔字符 * * @example * char string[] = "A string\tof ,,tokens\nand some more tokens"; * char seps[] = " ,\t\n"; * * std::vector<std::string> arr; * split(arr,string,seps); * * for(size_t i=0;i<arr.size();i++) * printf("arr[%d]=\"%s\"\n",i,arr[i]); */ inline void split(std::vector<std::string> & arr, char * strSource, const char* strDelimit) { arr.clear(); char * token = strtok(strSource, strDelimit); while (token != NULL) { arr.push_back(token); token = strtok(NULL, strDelimit); } } struct MyFileInfo { uint32_t app_id = 0; uint32_t app_type = 0; string exe_name = ""; vector<string> update_files; //替换文件 string path; //文件路径 bool is_ready = false; //是否已经准备好更新,就是是否已经收到AppStopRsp的回复报文 bool operator==(const MyFileInfo &Right) const { return this->app_id == Right.app_id && this->app_type == Right.app_type; } }; bool RepalceFile() { char file_name[100] = "fund.cfg"; FILE *fp = fopen(file_name, "r"); if (!fp) { return false; } char buff[100] = ""; uint32_t app_type = 0; string exe_name; vector<string> app_ids; //app_id vector<string> paths; //路径 vector<string> update_files; //替换文件 //app_type fscanf(fp, "%s", buff); char *p_sub = strstr(buff, "app_type="); if (!p_sub) { return false; } p_sub = p_sub + 9; app_type = atoi(p_sub); //可执行程序名 fscanf(fp, "%s", buff); p_sub = strstr(buff, "可执行程序名="); if (!p_sub) { return false; } p_sub = p_sub + 13; exe_name = p_sub; //app_id fscanf(fp, "%s", buff); p_sub = strstr(buff, "app_id="); if (!p_sub) { return false; } p_sub = p_sub + 7; split(app_ids, p_sub, "|"); //app路径 fscanf(fp, "%s", buff); p_sub = strstr(buff, "app路径="); if (!p_sub) { return false; } p_sub = p_sub + 8; split(paths, p_sub, "|"); //更新文件 fscanf(fp, "%s", buff); p_sub = strstr(buff, "更新的文件="); if (!p_sub) { return false; } p_sub = p_sub + 11; split(update_files, p_sub, "|"); //替换文件 if (app_ids.size() != paths.size()) { return false; } vector<MyFileInfo> m_file_info; for (int i = 0; i < app_ids.size(); i++) { MyFileInfo info; info.app_type = app_type; info.exe_name = exe_name; info.app_id = atoi(app_ids[i].c_str()); info.path = paths[i]; info.update_files = update_files; m_file_info.push_back(info); } Sleep(1000); //先延时1秒 //复制更新 for (auto it_file = m_file_info.begin(); it_file != m_file_info.end(); it_file++) { for (auto it_update = it_file->update_files.begin(); it_update != it_file->update_files.end(); it_update++) { sprintf(buff, "copy /y %s %s", it_update->c_str(), it_file->path.c_str()); system(buff); } sprintf(buff, "%s\\%s", it_file->path.c_str(), it_file->exe_name.c_str()); system(buff); } } int main() { TestMaxRand(); TestStdPlusPlus(); // TestFreadByDifferentSize(); TestContainIterator(); InterestingIterator(); //如果已知vector的一个元素位置,并想对他进行删除,可以实用it = vector.begin() + 位置下标的方式来实现快速删除 Construct(); TestSizeOfEveryType(); TestEnum(); TestMutilmap(); TestUnsigned(); RepalceFile(); // TestPrintf(); //string赋值0会赋值nullptr // TestIPChange(); // TestDeleteMemory(); // TestDosCommand(); // TestTime(); // TestStaticMember(); return 0; }
c0ff3bc740980074e09be35b2c97cfa137c31481
cab7f74d1ee550874e3092a0ea0259e6c35ee203
/src/P0199_BinaryTreeRightSideView.cpp
e6f5b73935d889cc9fd88018556878c72d8eab7d
[]
no_license
guyongpu/LeetCode
865e4d0a7325a7754c5d348cf1f99013da9f67b4
c5305141f8c3e0911fdc1a7a8af259face0ea774
refs/heads/master
2020-08-03T01:31:37.281926
2019-12-30T14:19:32
2019-12-30T14:19:32
211,578,145
1
0
null
null
null
null
UTF-8
C++
false
false
1,841
cpp
P0199_BinaryTreeRightSideView.cpp
// // Created by yongpu on 2019/10/24 10:47. // #include "P0199_BinaryTreeRightSideView.h" /** * 题目:二叉树的右视图 * 描述:给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值. * 思路:采用层序遍历思想,把每层的最右节点保存到result中即可. * 备注:掌握层序遍历. */ vector<int> P0199_BinaryTreeRightSideView::rightSideView(TreeNode *root) { vector<int> result; if (root == nullptr) { return result; } vector<TreeNode *> nodeVec = {root}; while (nodeVec.size() > 0) { int node_size = nodeVec.size(); /* //输出当前层的所有节点 for (int i = 0; i < node_size; i++) { cout << nodeVec[i]->val << " "; } cout << endl; */ result.push_back(nodeVec[node_size-1]->val); vector<TreeNode *> nodeVec_child; for (int i = 0; i < nodeVec.size(); i++) { if (nodeVec[i]->left) nodeVec_child.push_back(nodeVec[i]->left); if (nodeVec[i]->right) nodeVec_child.push_back(nodeVec[i]->right); } nodeVec = nodeVec_child; } return result; } int P0199_BinaryTreeRightSideView::test() { TreeNode *t1 = new TreeNode(1); TreeNode *t2 = new TreeNode(2); TreeNode *t3 = new TreeNode(3); TreeNode *t4 = new TreeNode(4); TreeNode *t5 = new TreeNode(5); TreeNode *t6 = new TreeNode(6); t1->left = t2; t1->right = t3; t2->right = t5; t3->right = t4; t5->left = t6; TreeNode *root = t1; vector<int> result = rightSideView(root); int num = result.size(); for (int i = 0; i < num; i++) { cout << result[i] << " "; } cout << endl; return 0; }
6ad5013d82ce3595bfc2345e644b8191dcbe4b5e
e6fe317af9b1e2cd6d03218a645b7bd1682dead9
/Universales/Universales/Button.cpp.orig
d618fc2dfd071dcae2a345cbe2ba898c0e9ab4d9
[]
no_license
guilhermeanselmo2/Universales
01cee9283b404cee67232a8684d19c57b74e736f
6e63b1a3ad694a439004a781c0d252e0664a99fa
refs/heads/master
2021-01-01T05:59:20.989415
2014-07-09T22:39:44
2014-07-09T22:39:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
710
orig
Button.cpp.orig
#include "Button.h" Button::Button(string text, int size, int x, int y) { content = text; texto = new Text("font/TRIBAL__.ttf", 20, Text::TEXT_BLENDED, text.c_str(), WHITE, 100); texto->SetPos(x, y, true, true); area = texto->box; pressed = false; } Button::~Button() { delete texto; } void Button::Update(float dt){ Point p(0, 0); p.x = InputManager::GetInstance().GetMouseX(); p.y = InputManager::GetInstance().GetMouseY(); bool click = InputManager::GetInstance().MouseRelease(1); if (area.IsInside(p.x,p.y)){ texto->SetColor(BLUE); if (click){ pressed = true; } else{ pressed = false; } } else{ texto->SetColor(WHITE); } } void Button::Render(){ texto->Render(); }
fb05d817eb99d2c808c04d73c4749d968700639d
a6f4e2510abccc7c4b6fd638eea7daffa7be50f8
/tmp/init.cpp
7a35656bf656f27cb761e596aca34cb2c25cf182
[]
no_license
keroro520/Compiler_NirLauncher
1eb4a6c9b17194b4bae42cb1507cb0173efe54ab
7e822ccaf08db7cc5b53d54d2d993c8f3171d868
refs/heads/master
2021-03-12T23:20:21.527280
2014-05-11T12:15:23
2014-05-11T12:15:23
17,426,869
1
0
null
null
null
null
UTF-8
C++
false
false
4,643
cpp
init.cpp
#include <string.h> #include <ctype.h> #include <stdio.h> #include <algorithm> #include <set> #include "structure.hpp" #include "init.hpp" using namespace std; char null; char eof ; char beginSymbol; set<char> nullSet, eofSet; vector<Product> pro; set <char> terminal, nonTerminal, symbol; set <char> first[256]; set <char> follow[256]; vector<ItemSet> LR0Stats; // 规范LR(0)项集族 int GOTO[1984][1984]; int action[1984][1984]; //Action表 int ACCEPT; int ERROR; //0xffffffff ? void analizeProduct(FILE * f) { char c = ' '; while (true) { while ( isspace(c = getc(f)) ) ; if (c == EOF) break; Product p ; if (beginSymbol == ' ') { beginSymbol = 'S'; pro.push_back(Product('S', c)); } p.left = c; while ( (c = getc(f)) != ':' ) ; while (true) { while ((c = getc(f)) == ' ' || c == '\t') ; if (c == '\n' || c == EOF) break; p.right += c; } pro.push_back(p); nonTerminal.insert(p.left); for_each(it, p.right) { if (!isupper(*it)) terminal.insert(*it); } } nonTerminal.insert( beginSymbol = 'S'); terminal.insert(null); terminal.insert(eof); symbol = terminal; symbol.insert(nonTerminal.begin(), nonTerminal.end()); } void getFirstSet() { for_each(it, terminal) { first[*it].insert(*it); } first[null].insert(null); first[eof].insert(eof); bool flag = true; while (flag) { flag = false; for_each (p, pro) { set<char> rhs ; set_difference(first[p->right[0]].begin(), first[p->right[0]].end(), nullSet.begin(), nullSet.end(), insert_iterator<set<char> >(rhs,rhs.begin())); auto it = p->right.begin() ; for ( ++it; it != p->right.end() && first[*it].find(null) != first[*it].end(); it++) { rhs.insert(first[*it].begin(), first[*it].end()); rhs.erase(null); } if (it == p->right.end() && first[*it].find(null) != first[*it].end()) { rhs.insert(null); } int tmp = first[p->left].size(); first[p->left].insert(rhs.begin(), rhs.end()); if (tmp != first[p->left].size()) flag = true; } } ; } void getFollowSet() { follow[beginSymbol].insert(eof); bool flag = true; while (flag) { flag = false; for_each (p, pro) { set<char> trailer = follow[p->left]; for (int i = p->right.length() - 1; i >= 0; i--) { char ch = p->right[i]; if (isupper(ch)) { int tmp = follow[ch].size(); follow[ch].insert(trailer.begin(), trailer.end()); if (tmp != follow[ch].size()) flag = true; if (first[ch].find(null) != first[ch].end()) { trailer.insert(first[ch].begin(), first[ch].end()); trailer.erase(null); } else { trailer = first[ch]; } } else { trailer = first[ch]; } } } } } ItemSet closure(ItemSet I) { for (int i = 0; i < I.items.size(); i++) { string & s = pro[I.items[i].pid].right; if ( IN(nonTerminal, s[I.items[i].pos]) ) { for_each(p, pro) { if (p->left == s[I.items[i].pos] && !IN(I.items, Item(p-pro.begin(),0))) { I.items.push_back(Item(p-pro.begin(),0)); } } } } return I; } ItemSet _goto(ItemSet I, char X) { ItemSet J; for_each (i, I.items) { if (i->pos < pro[i->pid].right.length() && pro[i->pid].right[i->pos] == X) { J.items.push_back(Item(i->pid, i->pos+1)); } } return J; } void buildItemSetClue () { memset(GOTO, 128, sizeof GOTO); vector<ItemSet> &C = LR0Stats; C.push_back( closure(ItemSet(Item(0, 0))) ); int cdr = 0; while (cdr < C.size()) { ItemSet I = C[cdr++]; for_each (ch, symbol) { char X = *ch; ItemSet newI = closure(_goto(I,X)); if (newI.items.size() > 0 && !IN(C,newI)) { C.push_back(newI); } if (newI.items.size() > 0) GOTO[cdr-1][X] = find(C.begin(), C.end(), newI) - C.begin(); } } } void getActionTable() { memset(&ERROR, 128, sizeof (int)); ACCEPT = ERROR + 1; for (int i = 0; i < LR0Stats.size(); i++) { for_each(ch, symbol) { action[i][*ch] = ERROR; } } for_each (I, LR0Stats) { int stat = I - LR0Stats.begin(); for_each (i, I->items) { Product &p = pro[i->pid]; string &s = p.right; if (i->pos < s.length() && !isupper(s[i->pos])) { char ch = s[i->pos]; action[stat][ch] = GOTO[stat][ch]; } else if (i->pos == s.length()) { for_each (a, follow[p.left]) { action[stat][*a] = -i->pid; } } } if (IN(I->items, Item(0,1))) { action[stat][eof] = ACCEPT; } } } void init() { null = '@'; eof = '$'; beginSymbol = ' '; nullSet.insert(null); eofSet.insert(eof); FILE * f = fopen("grammar.txt", "r"); analizeProduct(f); fclose(f); getFirstSet(); getFollowSet(); buildItemSetClue () ; getActionTable(); }
8f43dd9aa7fb59bca81ee6568e7b6269c40067b3
102beccb4a386876dfeaea493209537c9a0db742
/InventoryModule/WebdavInventoryDataModel.cpp
b49f88b29d9ea5207a9a7ef9d8c504b7d20ca372
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Chiru/naali
cc4150241d37849dde1b9a1df983e41a53bfdab1
b0fb756f6802ac09a7cd9733e24e4db37d5c1b7e
refs/heads/master
2020-12-25T05:03:47.606650
2010-09-16T14:08:42
2010-09-17T08:34:19
1,290,932
1
1
null
null
null
null
UTF-8
C++
false
false
21,819
cpp
WebdavInventoryDataModel.cpp
// For conditions of distribution and use, see copyright notice in license.txt /** * @file WebDavInventoryDataModel.cpp * @brief Data model providing the WebDAV inventory model backend functionality. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "WebdavInventoryDataModel.h" #include "InventoryAsset.h" #include "InventoryModule.h" #include "RexUUID.h" #include "MemoryLeakCheck.h" #include <QDir> #include <QDebug> namespace Inventory { WebDavInventoryDataModel::WebDavInventoryDataModel(const QString &identity, const QString &host, const QString &password) : webdav_identity_(identity), webdav_host_(host), webdav_password_(password), rootFolder_(0) { if (!webdav_host_.endsWith("/")) webdav_host_.append("/"); if (InitPythonQt()) FetchRootFolder(); else ErrorOccurredCreateEmptyRootFolder(); } WebDavInventoryDataModel::~WebDavInventoryDataModel() { SAFE_DELETE(rootFolder_); } AbstractInventoryItem *WebDavInventoryDataModel::GetFirstChildFolderByName(const QString &searchName) const { if (!rootFolder_) return 0; return rootFolder_->GetFirstChildFolderByName(searchName); } AbstractInventoryItem *WebDavInventoryDataModel::GetChildFolderById(const QString &searchId) const { if (RexUUID::IsValid(searchId.toStdString())) return 0; else return rootFolder_->GetChildFolderById(searchId); } AbstractInventoryItem *WebDavInventoryDataModel::GetChildAssetById(const QString &searchId) const { InventoryModule::LogDebug("Webdav | You are in GetChildAssetById() that is not implemented yet"); return 0; } AbstractInventoryItem *WebDavInventoryDataModel::GetChildById(const QString &searchId) const { return rootFolder_->GetChildById(searchId); } AbstractInventoryItem *WebDavInventoryDataModel::GetOrCreateNewFolder(const QString &id, AbstractInventoryItem &parentFolder, const QString &name, const bool &notify_server) { if (name.isEmpty()) return 0; InventoryFolder *parent = dynamic_cast<InventoryFolder *>(&parentFolder); if (!parent) return 0; if (RexUUID::IsValid(id.toStdString())) { // This is a new folder if the id is RexUUID // RexUUID generated in data model, cant do nothing about this... QString parentPath = parent->GetID(); QString newFolderName = name; if (parentPath == "root") return 0; QStringList result = webdavclient_.call("createDirectory", QVariantList() << parentPath << newFolderName).toStringList(); if (result.count() >= 1) { if (result[0] == "True") { parent->SetDirty(true); InventoryModule::LogDebug(QString("Webdav | Created folder named %1 to path %2\n").arg(newFolderName, parentPath).toStdString()); FetchInventoryDescendents(parent); return parent->GetFirstChildFolderByName(newFolderName); } else InventoryModule::LogDebug(QString("Webdav | Could not create folder named %1 to path %2\n").arg(newFolderName, parentPath).toStdString()); } } else { // If its not RexUUID or and existing item in this folder, // then its a move command. Lets do that to the webdav server then... InventoryFolder *existingItem = parent->GetChildFolderById(id); if (!existingItem) { InventoryFolder *currentFolder = rootFolder_->GetChildFolderById(name); if (!currentFolder) return 0; QString currentPath = ValidateFolderPath(currentFolder->GetParent()->GetID()); QString newPath = ValidateFolderPath(parent->GetID()); QString folderName = name; QString deepCopy = "False"; if (currentFolder->HasChildren()) deepCopy = "True"; QStringList result = webdavclient_.call("moveResource", QVariantList() << currentPath << newPath << folderName).toStringList(); if (result.count() >= 1) { if (result[0] == "True") { parent->SetDirty(true); //FetchInventoryDescendents(parent); InventoryModule::LogDebug(QString("Webdav | Moved folder %1 from %2 to %3\nNote: This fucntionality is experimental,").append( "dont assume it went succesfull\n").arg(folderName, currentPath, newPath).toStdString()); } else { InventoryModule::LogDebug(QString("Webdav | Failed to move folder %1 from %2 to %3\n").arg( folderName, currentPath, newPath).toStdString()); } } } else return existingItem; } // Return 0 to data model, we just updated // folder content from webdav, no need to return the real item return 0; } AbstractInventoryItem *WebDavInventoryDataModel::GetOrCreateNewAsset(const QString &inventory_id, const QString &asset_id, AbstractInventoryItem &parentFolder, const QString &name) { InventoryModule::LogDebug("Webdav | You are in GetOrCreateNewAsset() that is not implemented yet"); return 0; } bool WebDavInventoryDataModel::FetchInventoryDescendents(AbstractInventoryItem *item) { InventoryFolder *selected = dynamic_cast<InventoryFolder *>(item); if (!selected) return false; // Delete children selected->GetChildren().clear(); QString itemPath = selected->GetID(); QStringList children = webdavclient_.call("listResources", QVariantList() << itemPath).toStringList(); if (children.count() == 0) { InventoryModule::LogDebug(QString("Webdav | No child items in path /%1").arg(itemPath).toStdString()); return true; } // Process child list to map QMap<QString, QString> childMap; for (int index=0; index<=children.count(); index++) { childMap[children.value(index)] = children.value(index+1); index++; } // Get properties, we are interested in the custom property assetreferenceurl QStringList child_properties = webdavclient_.call("findProperties", QVariantList() << itemPath).toStringList(); // Process propertylist QMap<QString, QString> propertyMap; for (int index=0; index<=child_properties.count(); index++) { propertyMap[child_properties.value(index)] = child_properties.value(index+1); index++; } AbstractInventoryItem *newItem = 0; QString path, name, type, asset_reference_url; for (QMap<QString, QString>::iterator iter = childMap.begin(); iter!=childMap.end(); ++iter) { path = RemovePrePath(iter.key()); name = path.split("/").last(); type = iter.value(); if (name != "") { asset_reference_url = "Asset url for " + name + " not available"; if (propertyMap.contains(name)) asset_reference_url = propertyMap[name]; if (type == "resource") newItem = new InventoryAsset(path, asset_reference_url, name, selected); else { newItem = new InventoryFolder(path, name, selected, true); dynamic_cast<InventoryFolder*>(newItem)->SetDirty(true); } selected->AddChild(newItem); } } //InventoryModule::LogDebug(QString("Webdav | Fetched %1 children to path /%2").arg(QString::number(childMap.count()), itemPath).toStdString()); selected->SetDirty(false); return true; } void WebDavInventoryDataModel::NotifyServerAboutItemMove(AbstractInventoryItem *item) { InventoryModule::LogDebug("Webdav | You are in NotifyServerAboutItemMove() that is not implemented yet"); } void WebDavInventoryDataModel::NotifyServerAboutItemCopy(AbstractInventoryItem *item) { InventoryModule::LogDebug("Webdav | You are in NotifyServerAboutItemCopy() that is not implemented yet"); } void WebDavInventoryDataModel::NotifyServerAboutItemRemove(AbstractInventoryItem *item) { QString parentPath = ValidateFolderPath(item->GetParent()->GetID()); QString itemName = item->GetName(); QString methodName; QStringList result; if (item->GetItemType() == AbstractInventoryItem::Type_Folder) methodName = "deleteDirectory"; else if (item->GetItemType() == AbstractInventoryItem::Type_Asset) methodName = "deleteResource"; else return; result = webdavclient_.call(methodName, QVariantList() << parentPath << itemName).toStringList(); if (result.count() >= 1) { if (result[0] == "True") { InventoryFolder *parent_folder = dynamic_cast<InventoryFolder*>(item->GetParent()); if (parent_folder) parent_folder->SetDirty(true); //FetchInventoryDescendents(item->GetParent()); InventoryModule::LogDebug(QString("Webdav | Removed item from %1\n").arg(item->GetID()).toStdString()); } else InventoryModule::LogDebug(QString("Webdav | Could not remove item from %1\n").arg(item->GetID()).toStdString()); } } void WebDavInventoryDataModel::NotifyServerAboutItemUpdate(AbstractInventoryItem *item, const QString &old_name) { QString parentPath = ValidateFolderPath(item->GetParent()->GetID()); QString newName = item->GetName(); QString oldName = old_name; if (newName == oldName || newName.isEmpty()) return; QStringList result = webdavclient_.call("renameResource", QVariantList() << parentPath << newName << oldName).toStringList(); if (result.count() >= 1) { if (result[0] == "True") { InventoryFolder *parent_folder = dynamic_cast<InventoryFolder*>(item->GetParent()); if (parent_folder) parent_folder->SetDirty(true); //FetchInventoryDescendents(item->GetParent()); InventoryModule::LogDebug(QString("Webdav | Renamed folder from %0 to %1 in path %3\n").arg(oldName, newName, parentPath).toStdString()); } else InventoryModule::LogDebug(QString("Webdav | Could not rename folder from %0 to %1 in path %3\n").arg(oldName, newName, parentPath).toStdString()); } } bool WebDavInventoryDataModel::OpenItem(AbstractInventoryItem *item) { InventoryModule::LogDebug("Webdav | You are in OpenItem() that is not implemented yet"); return false; } void WebDavInventoryDataModel::UploadFile(const QString &file_path, AbstractInventoryItem *parent_folder) { if (!parent_folder) parent_folder = GetFirstChildFolderByName("My Inventory"); InventoryFolder *parentFolder = dynamic_cast<InventoryFolder *>(parent_folder); if (!parentFolder) return; QString filePath = file_path; QString filename = filePath.split(QDir::separator()).last(); QString parentPath = ValidateFolderPath(parentFolder->GetID()); QStringList result = webdavclient_.call("uploadFile", QVariantList() << filePath << parentPath << filename).toStringList(); if (result.count() >= 1) { if (result[0] == "True") { parentFolder->SetDirty(true); FetchInventoryDescendents(parent_folder); InventoryAsset *asset = parentFolder->GetChildAssetById(parentFolder->GetName() + "/" + filename); if (asset) emit UploadCompleted(filename, asset->GetAssetReference()); else emit UploadCompleted(filename, ""); InventoryModule::LogDebug(QString("Webdav | Upload of file %1 to path %2%3 succeeded\n").arg(filePath, parentPath, filename).toStdString()); } else InventoryModule::LogDebug(QString("Webdav | Upload of file %1 to path %2%3 failed\n").arg(filePath, parentPath, filename).toStdString()); } } void WebDavInventoryDataModel::UploadBuffer(const QString &filename, QByteArray& buffer, AbstractInventoryItem *parent_folder) { if (!parent_folder) parent_folder = GetFirstChildFolderByName("My Inventory"); InventoryFolder *parentFolder = dynamic_cast<InventoryFolder *>(parent_folder); if (!parentFolder) return; QString parentPath = ValidateFolderPath(parentFolder->GetID()); QStringList result = webdavclient_.call("uploadFileBuffer", QVariantList() << buffer << parentPath << filename).toStringList(); if (result.count() >= 1) { if (result[0] == "True") { parentFolder->SetDirty(true); FetchInventoryDescendents(parent_folder); InventoryAsset *asset = parentFolder->GetChildAssetById(parentFolder->GetName() + "/" + filename); if (asset) emit UploadCompleted(filename, asset->GetAssetReference()); else emit UploadCompleted(filename, ""); InventoryModule::LogDebug(QString("Webdav | Upload of file %1 to path %2%3 succeeded\n").arg(filename, parentPath, filename).toStdString()); } else InventoryModule::LogDebug(QString("Webdav | Upload of file %1 to path %2%3 failed\n").arg(filename, parentPath, filename).toStdString()); } } void WebDavInventoryDataModel::UploadFiles(QStringList &filenames, QStringList &item_names, AbstractInventoryItem *parent_folder) { ///\todo Use also the item names. for (uint i = 0; i < filenames.size(); ++i) UploadFile(filenames[i], parent_folder); } void WebDavInventoryDataModel::UploadFilesFromBuffer(QStringList &filenames, QVector<QVector<uchar> > &buffers, AbstractInventoryItem *parent_folder) { for(uint i = 0; i < filenames.size(); ++i) { QByteArray data; QDataStream data_stream(&data, QIODevice::ReadWrite); data_stream.writeRawData((const char*)&buffers[i][0], buffers[i].size()); UploadBuffer(filenames[i], data, parent_folder); } } void WebDavInventoryDataModel::DownloadFile(const QString &store_folder, AbstractInventoryItem *selected_item) { InventoryAsset *item = dynamic_cast<InventoryAsset *>(selected_item); if (!item) return; QString storePath = store_folder; QString parentPath = ValidateFolderPath(item->GetParent()->GetID()); QString filename = item->GetName(); //emit DownloadStarted(id); QStringList result = webdavclient_.call("downloadFile", QVariantList() << storePath << parentPath << filename).toStringList(); if (result.count() >= 1) { if (result[0] == "True") { InventoryModule::LogDebug(QString("Webdav | Downloaded file %1%2 to path %3\n").arg(parentPath, filename, storePath).toStdString()); //emit DownloadCompleted(id); } else InventoryModule::LogDebug(QString("Webdav | Downloaded of file %1%2 to path %3 failed\n").arg(parentPath, filename, storePath).toStdString()); } } bool WebDavInventoryDataModel::InitPythonQt() { QString myPath = QString("%1/pymodules/webdavinventory").arg(QDir::currentPath()); pythonQtMainModule_ = PythonQt::self()->getMainModule(); pythonQtMainModule_.evalScript(QString("import sys\n")); pythonQtMainModule_.evalScript(QString("sys.path.append('%1')\n").arg(myPath)); Q_ASSERT(!pythonQtMainModule_.isNull()); return true; } bool WebDavInventoryDataModel::FetchWebdavUrlWithIdentity() { pythonQtMainModule_.evalScript("import connection\n"); PythonQtObjectPtr httpclient = pythonQtMainModule_.evalScript("connection.HTTPClient()\n", Py_eval_input); // Some url verification, remove http:// and everything after the port int index = webdav_host_.indexOf("http://"); if (index != -1) webdav_host_ = webdav_host_.midRef(index+7).toString(); index = webdav_host_.indexOf("/"); if (index != -1) webdav_host_ = webdav_host_.midRef(0, index).toString(); // Set up HTTP connection to Taiga WorldServer httpclient.call("setupConnection", QVariantList() << webdav_host_ << "openid" << webdav_identity_); // Get needed webdav access urls from Taiga WorldServer QStringList resultList = httpclient.call("requestIdentityAndWebDavURL").toStringList(); // Store results if (resultList.count() < 1) return false; fetched_webdav_identity_ = resultList.value(0); fetched_webdav_host_ = resultList.value(1); return true; } void WebDavInventoryDataModel::FetchRootFolder() { pythonQtMainModule_.evalScript("import connection\n"); webdavclient_ = pythonQtMainModule_.evalScript("connection.WebDavClient()\n", Py_eval_input); if (!webdavclient_) { ErrorOccurredCreateEmptyRootFolder(); return; } // Set urls webdavclient_.call("setHostAndUser", QVariantList() << webdav_identity_ << webdav_host_ << webdav_password_); // Connect to webdav bool success = webdavclient_.call("setupConnection").toBool(); if (!success) { InventoryModule::LogWarning("Could not setup webdav connection to " + webdav_host_.toStdString() + " with user " + webdav_identity_.toStdString()); return; } // Fetch root resources QStringList rootResources = webdavclient_.call("listResources").toStringList(); if (rootResources.count() < 1) { ErrorOccurredCreateEmptyRootFolder(); return; } QMap<QString, QString> folders; InventoryFolder *parentFolder; for (int index=0; index<=rootResources.count(); index++) { if (!rootResources.value(index).isEmpty() && !rootResources.value(index+1).isEmpty()) folders[rootResources.value(index)] = rootResources.value(index+1); index++; } if (!rootFolder_) { rootFolder_ = new InventoryFolder("root", "Webdav Inventory", false, 0); parentFolder = new InventoryFolder("", QString("My Inventory"), false, rootFolder_); rootFolder_->AddChild(parentFolder); rootFolder_->SetDirty(true); parentFolder->SetDirty(true); } AbstractInventoryItem *newItem = 0; QString path; QString name; QString type; for (QMap<QString, QString>::iterator iter = folders.begin(); iter!=folders.end(); ++iter) { path = RemovePrePath(iter.key()); name = path.split("/").last(); type = iter.value(); if (name != "") { if (type.toLower() == "resource") newItem = new InventoryAsset(path, "No url ref for folders.", name, parentFolder); else { newItem = new InventoryFolder(path, name, parentFolder, true); dynamic_cast<InventoryFolder*>(newItem)->SetDirty(true); } parentFolder->AddChild(newItem); } } } void WebDavInventoryDataModel::ErrorOccurredCreateEmptyRootFolder() { if (!rootFolder_) rootFolder_ = new InventoryFolder("root", "Error while fetching Webdav Inventory", false, 0); InventoryFolder *parentFolder = new InventoryFolder("/", QString("My Inventory"), false, rootFolder_); rootFolder_->AddChild(parentFolder); rootFolder_->SetDirty(true); parentFolder->SetDirty(true); } QString WebDavInventoryDataModel::ValidateFolderPath(QString path) { if (!path.endsWith("/") && !path.isEmpty()) path.append("/"); return path; } QString WebDavInventoryDataModel::RemovePrePath(QString full_path) { QString real_path; QStringList path_split = full_path.split("/"); if (path_split.count() < 2) return full_path; QUuid agent_uuid(path_split[1]); if (path_split[0] == "inventory" && !agent_uuid.isNull()) { path_split.removeFirst(); path_split.removeFirst(); real_path = path_split.join("/"); if (real_path.endsWith("/")) real_path = real_path.left(real_path.count()-1); return real_path; } else return full_path; } }
a50429ef9248ca156ca279b433e153658bf11860
6e78b9684493c1debcfbef329e02fffafb97a13a
/GP_Project/TNode.cpp
eef9d541f26b70e0771be2f52c5ac265dc095c6a
[]
no_license
Goomenny/GP_Project
2d7832f1848537426c5326e463cd17ac7d0aeddd
b6f2fdf4fa15881668f315608618406b19f1bd88
refs/heads/master
2021-08-23T20:05:40.749139
2017-12-06T10:04:21
2017-12-06T10:04:21
112,374,141
0
0
null
null
null
null
UTF-8
C++
false
false
9,628
cpp
TNode.cpp
#include "TNode.h" //--------------------------------------------------------------------------- void TNode::Set_symbol(int gfunc) { switch (gfunc) { case 0: symbol = "+"; break; case 1: symbol = "-"; break; case 2: symbol = "*"; break; case 3: symbol = "/"; break; } } //--------------------------------------------------------------------------- TNode_symbolic::TNode_symbolic() { state = NULL; constant = NULL; type = NULL; num_var = NULL; value = NULL; func = NULL; arn = NULL; num_parent = NULL; n_child = NULL; child = 0; argument = 0; num_self = NULL; symbol = ""; index = ""; } //--------------------------------------------------------------------------- TNode_symbolic::TNode_symbolic(const TNode_symbolic &other) { this->state = other.state; this->constant = other.constant; this->type = other.type; this->num_var = other.num_var; this->value = other.value; this->func = other.func; this->arn = other.arn; this->num_parent = other.num_parent; this->n_child = other.n_child; this->num_self = other.num_self; this->num_layer = other.num_layer; this->argument = 0; // if (type) { this->symbol = other.symbol; this->index = other.index; } this->child = new int[this->n_child]; for (int i = 0; i < this->n_child; i++) { this->child[i] = other.child[i]; } } //--------------------------------------------------------------------------- TNode_symbolic& TNode_symbolic::operator=(const TNode_symbolic &other) {//перегрузка оператора присваивания if (this == &other) return *this; // присвоение самому себе, ничего делать не надо delete[] child; this->state = other.state; this->constant = other.constant; this->type = other.type; this->num_var = other.num_var; this->value = other.value; this->func = other.func; this->arn = other.arn; this->num_parent = other.num_parent; this->n_child = other.n_child; this->num_self = other.num_self; this->num_layer = other.num_layer; this->argument = 0; // if (type) { this->symbol = other.symbol; this->index = other.index; } this->child = new int[this->n_child]; for (int i = 0; i < this->n_child; i++) { this->child[i] = other.child[i]; } return *this; } //--------------------------------------------------------------------------- void TNode_symbolic::Init(bool gtype, int gfunc, int gn_var, int inheriters) { state = false; type = gtype; func = gfunc; if (type) { n_child = 2; //Бинарное дерево arn = 2; child = new int[n_child]; Set_symbol(func); } else { n_child = 0; arn = 0; if (true) //Регрессия { constant = rand() % 2; n_child = 0; arn = 0; if (constant) { value = rand() % 20001 / 10000. - 1; } else { value = NULL; num_var = rand() % gn_var; } } else if (problem == 1) { //Нечеткая логика value = rand() % inheriters; num_var = value; } } } //--------------------------------------------------------------------------- __fastcall TNode_symbolic::~TNode_symbolic() { delete[] child; } //--------------------------------------------------------------------------- //Нечеткая логика void TNode_symbolic::Get_result(vector<int *>& rules, int n_vars, int *n_terms) { if (type) { for (int i = 0; i < n_child; i++) { argument[child[i]].Get_result(rules, n_vars, n_terms); } } else { int *a = new int[n_vars]; a[0] = num_layer; a[1] = num_self; a[2] = num_layer + num_self; rules.push_back(a); } } //--------------------------------------------------------------------------- //Регрессия double TNode_symbolic::Get_result(double *gvar) { if (type) { switch (func) { case 0: value = Sum<TNode_symbolic>(argument, child, n_child, gvar); break; case 1: value = Minu<TNode_symbolic>(argument, child, n_child, gvar); break; case 2: value = Multip<TNode_symbolic>(argument, child, n_child, gvar); break; case 3: value = Divis<TNode_symbolic>(argument, child, n_child, gvar); break; } } else if (!constant) { value = gvar[num_var]; } return value; } //--------------------------------------------------------------------------- string TNode_symbolic::Get_formula(string gsymbol) { string formula; //Формула данного узла if (type) { if (num_layer != 0) formula = "("; for (int i = 0; i < n_child; i++) { formula += argument[child[i]].Get_formula(argument[child[i]].symbol); if (i<n_child - 1) formula += gsymbol; } if (num_layer != 0) formula += ")"; } else if (constant) { if (value<0) { formula += "("; formula += to_string(value); formula += ")"; } else formula = to_string(value); } else { formula = "x"; formula += to_string(num_var); } return formula; } void TNode_symbolic::Set_argument(TNode_symbolic *arg) { argument = arg; } int TNode_symbolic::Get_n_heirs() { if (type) { int max = 0, tmp = 0; for (int i = 0; i < n_child; i++) { tmp = argument[child[i]].Get_n_heirs(); if (tmp>max) max = tmp; } return max + 1; } else return 0; } //--------------------------------------------------------------------------- //------------------------DE------------DE--------DE------------------------- //--------------------------------------------------------------------------- TNode_DE::TNode_DE() { state = NULL; constant = NULL; type = NULL; num_var = NULL; value = NULL; func = NULL; arn = NULL; num_parent = NULL; n_child = NULL; child = 0; argument = 0; num_self = NULL; symbol = ""; index = ""; } //--------------------------------------------------------------------------- TNode_DE::TNode_DE(const TNode_DE &other) { this->state = other.state; this->constant = other.constant; this->type = other.type; this->num_var = other.num_var; this->value = other.value; this->func = other.func; this->arn = other.arn; this->num_parent = other.num_parent; this->n_child = other.n_child; this->num_self = other.num_self; this->num_layer = other.num_layer; this->argument = 0; // if (type) { this->symbol = other.symbol; this->index = other.index; } this->child = new int[this->n_child]; for (int i = 0; i < this->n_child; i++) { this->child[i] = other.child[i]; } } //--------------------------------------------------------------------------- TNode_DE& TNode_DE::operator=(const TNode_DE &other) {//перегрузка оператора присваивания if (this == &other) return *this; // присвоение самому себе, ничего делать не надо delete[] child; this->state = other.state; this->constant = other.constant; this->type = other.type; this->num_var = other.num_var; this->value = other.value; this->func = other.func; this->arn = other.arn; this->num_parent = other.num_parent; this->n_child = other.n_child; this->num_self = other.num_self; this->num_layer = other.num_layer; this->argument = 0; // if (type) { this->symbol = other.symbol; this->index = other.index; } this->child = new int[this->n_child]; for (int i = 0; i < this->n_child; i++) { this->child[i] = other.child[i]; } return *this; } //--------------------------------------------------------------------------- void TNode_DE::Init(bool gtype, int gfunc, int gn_var, int inheriters) { state = false; type = gtype; func = rand() % 3; if (type) { n_child = 2; //Бинарное дерево arn = 2; child = new int[n_child]; Set_symbol(func); } else { n_child = 0; arn = 0; constant = rand() % 2; n_child = 0; arn = 0; if (constant) { value = rand() % 20001 / 10000. - 1; } else { value = NULL; num_var = rand() % gn_var; } } } //--------------------------------------------------------------------------- TNode_DE::~TNode_DE() { delete[] child; } //--------------------------------------------------------------------------- //Регрессия double TNode_DE::Get_result(double *gvar) { if (type) { switch (func) { case 0: value = Sum<TNode_DE>(argument, child, n_child, gvar); break; case 1: value = Minu<TNode_DE>(argument, child, n_child, gvar); break; case 2: value = Multip<TNode_DE>(argument, child, n_child, gvar); break; case 3: // value = Divis(argument, child, n_child, gvar); break; } } else if (!constant) { value = gvar[num_var]; } return value; } //--------------------------------------------------------------------------- string TNode_DE::Get_formula(string gsymbol) { string formula; //Формула данного узла if (type) { if (num_layer != 0) formula = "("; for (int i = 0; i < n_child; i++) { formula += argument[child[i]].Get_formula(argument[child[i]].symbol); if (i<n_child - 1) formula += gsymbol; } if (num_layer != 0) formula += ")"; } else if (constant) { if (value<0) { formula += "("; formula += to_string(value); formula += ")"; } else formula = to_string(value); } else if (num_var == 0) { formula = "self"; } else if (num_var == 1) { formula = "best"; } else { formula = "ind"; formula += to_string(num_var-2); } return formula; } void TNode_DE::Set_argument(TNode_DE *arg) { argument = arg; } int TNode_DE::Get_n_heirs() { if (type) { int max = 0, tmp = 0; for (int i = 0; i < n_child; i++) { tmp = argument[child[i]].Get_n_heirs(); if (tmp>max) max = tmp; } return max + 1; } else return 0; }
5aabce4fdf832fee1a612a18e4135a72d86dd12f
c8980f8c73493ef6cdbc6f2c7173ebee5e22059d
/Gem5/params/X86TLB.hh
9a71ccddfef5ba7e3394d7fa2aee24069eea9bb2
[]
no_license
kongziyun/RPCache
ec6c577e8c9cec06f21727a34d1b97783e4019fb
cefbe5235b46464df489d2eaf672b8b8bea832ef
refs/heads/master
2016-09-05T09:15:31.842718
2013-12-09T05:07:35
2013-12-09T05:07:35
14,177,011
2
0
null
null
null
null
UTF-8
C++
false
false
395
hh
X86TLB.hh
#ifndef __PARAMS__X86TLB__ #define __PARAMS__X86TLB__ namespace X86ISA { class TLB; } // namespace X86ISA #include <cstddef> #include "params/X86PagetableWalker.hh" #include <cstddef> #include "base/types.hh" #include "params/BaseTLB.hh" struct X86TLBParams : public BaseTLBParams { X86ISA::TLB * create(); X86ISA::Walker * walker; int size; }; #endif // __PARAMS__X86TLB__
bb3668391981b81e642a71ae295407c812008c49
3aa684df8c6c4ef8e777a42426fda0c72dd4df6e
/src/log/basic_formatter.cpp
84dbd44eff42fa0cc8dfbd7b1eda11ff0aa38f0b
[ "MIT", "BSD-3-Clause", "Zlib", "BSL-1.0", "Unlicense" ]
permissive
ojas0419/iris
02f9f053e30bd179e02a2d7badd4da933e20966f
cbc2f571bd8d485cdd04f903dcb867e699314682
refs/heads/main
2023-08-21T16:11:10.480107
2021-10-16T06:20:25
2021-10-16T06:20:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,956
cpp
basic_formatter.cpp
//////////////////////////////////////////////////////////////////////////////// // Distributed under the Boost Software License, Version 1.0. // // (See accompanying file LICENSE or copy at // // https://www.boost.org/LICENSE_1_0.txt) // //////////////////////////////////////////////////////////////////////////////// #include "log/basic_formatter.h" #include <chrono> #include <filesystem> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include "log/log_level.h" namespace { /** * Helper function to extract just the filename from a full path. * * @param filename * Filename to extract from. * * @returns * Filename from supplied string. */ std::string format_filename(const std::string &filename) { // find last occurrence of file separator const auto index = filename.rfind(std::filesystem::path::preferred_separator); return std::string{filename.substr(index + 1)}; } /** * Convert log level to string and get first character. * * @param level * Log level to get first character of. * * @returns * First character of log level. */ char first_char_of_level(const iris::LogLevel level) { std::stringstream strm{}; strm << level; const auto str = strm.str(); return !str.empty() ? str.front() : 'U'; } } namespace iris { std::string BasicFormatter::format( const LogLevel level, const std::string &tag, const std::string &message, const std::string &filename, const int line) { const auto now = std::chrono::system_clock::now(); const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()); std::stringstream strm{}; strm << first_char_of_level(level) << " " << seconds.count() << " [" << tag << "] " << format_filename(filename) << ":" << line << " | " << message; return strm.str(); } }
3f9c6bd4f7c638819938ffaf13c005b11fa67bd2
c0a24b3c498a586f39f347f20caea830fc2c8694
/openFrameworks/apps/Ray Tracing Renderer/src/ofApp.h
e70089864ed6c35be310ad692949a4bfc37d6a6f
[ "MIT" ]
permissive
AlexWolski/Ray-Tracing-Renderer
adc4e505ecb4ab665b91722b6567dbad8192fc77
c52a82fabaef937686da89df0c46501cbbce0a17
refs/heads/master
2023-05-01T16:18:20.269657
2021-05-19T12:32:15
2021-05-19T12:32:15
316,375,461
0
0
MIT
2021-05-19T11:52:58
2020-11-27T01:52:37
C++
UTF-8
C++
false
false
350
h
ofApp.h
#pragma once #include "ofBaseApp.h" #include "ofGraphics.h" #include "rtGraphics/rtMain.h" using namespace rtGraphics; class ofApp : public ofBaseApp { private: shared_ptr<rtScene> demoScene; shared_ptr<rtCam> mainCamera; bool showFps = true; void drawFps(); public: void setup(); void update(); void draw(); void keyPressed(int key); };
04e688171988bf99566a62accc24fb2b17fa82e3
4c23be1a0ca76f68e7146f7d098e26c2bbfb2650
/elbow/42/U
b5957c08b465c41bb84dadb97b79c292343e5961
[]
no_license
labsandy/OpenFOAM_workspace
a74b473903ddbd34b31dc93917e3719bc051e379
6e0193ad9dabd613acf40d6b3ec4c0536c90aed4
refs/heads/master
2022-02-25T02:36:04.164324
2019-08-23T02:27:16
2019-08-23T02:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,047
U
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "42"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 918 ( (0.985047 -0.000710173 0) (0.0053349 2.96625 0) (-0.00304161 0.833704 0) (0.979574 0.00195719 0) (-0.0155704 2.02903 2.90914e-20) (-0.00708521 2.94855 -2.68367e-18) (0.809968 1.13049 4.18245e-19) (0.281536 0.105338 -1.55657e-20) (0.999921 -0.000242214 0) (0.0815287 0.737286 0) (0.0111355 0.521254 0) (0.735022 -0.0165495 0) (0.0102024 2.93157 0) (0.00345797 2.79425 0) (-0.000728712 3.19006 8.13035e-19) (-0.0137844 1.88691 3.22776e-21) (0.339214 0.0243193 1.02344e-18) (0.236516 1.14241 3.3544e-19) (0.964479 0.00670142 0) (-0.0228538 0.536725 0) (0.0764989 0.169163 -7.39691e-19) (1.00184 -0.00455745 0) (0.999853 -0.0089334 0) (0.975157 -0.00605614 0) (0.595876 -0.0369044 0) (0.0228682 2.64371 0) (-0.0123689 2.91199 9.89869e-19) (-0.0030718 0.906204 0) (0.00142573 1.13498 0) (-0.00524233 0.880803 0) (-0.0241517 2.60902 0) (-0.00611433 2.0869 -2.32187e-20) (-0.0103249 1.85409 0) (-0.0221705 2.9876 -9.70531e-23) (-0.0165028 3.00551 2.08549e-18) (0.00230729 3.00061 0) (0.871261 -0.00950237 0) (0.376318 0.919515 1.73565e-19) (0.810045 1.14157 -5.03186e-19) (0.943524 0.994941 5.23531e-19) (0.67648 1.2259 -9.60864e-20) (0.687416 1.20017 5.54843e-19) (0.309374 0.197874 1.51857e-20) (0.290703 0.0898508 0) (1.13215 0.50781 0) (0.275451 0.19399 6.93893e-20) (0.253493 0.117097 -7.20053e-20) (0.920409 -0.00700941 0) (1.00026 7.51812e-05 0) (0.999909 0.00031603 0) (1.00369 -0.00729453 0) (1.0009 -0.00095424 0) (1.00011 -1.49184e-05 0) (0.095404 1.83334 -7.87059e-19) (0.0295978 0.911691 0) (0.13293 0.804851 0) (0.0182249 0.862795 0) (0.0431034 0.680939 0) (0.0102651 2.01065 0) (0.0136741 0.757154 0) (0.007347 0.55409 0) (0.0045734 0.744992 0) (0.00433569 0.504596 0) (0.840677 -0.0154075 0) (0.841965 0.0329356 0) (0.767119 -0.00653721 0) (0.814126 0.0434104 0) (0.700216 -0.0176056 0) (0.0139655 3.00019 9.97522e-19) (0.0111978 3.00592 0) (0.00630598 3.00391 0) (0.0118795 2.99708 1.13521e-23) (0.00829241 2.95872 -1.48256e-18) (0.0121886 2.98291 0) (0.00901509 2.90487 0) (0.0211004 2.93132 2.33307e-24) (0.00414006 2.82426 0) (0.0262786 2.91884 0) (-0.00050148 2.74495 0) (0.310127 3.59031 0) (-0.122665 3.67361 0) (0.152538 3.28121 -7.56699e-19) (0.00579916 3.01416 0) (-0.0261842 2.02263 0) (-0.00441257 2.16525 -3.18353e-21) (-0.00376533 1.90336 -6.44599e-21) (0.423121 0.135963 -3.53897e-19) (0.342748 -0.00211485 -3.4179e-19) (0.398401 0.156051 -1.06589e-18) (0.325927 0.0432222 -7.01804e-19) (0.259917 0.998839 0) (0.335441 1.27223 -3.50647e-19) (0.412041 1.17557 5.78054e-19) (0.987909 0.00808557 0) (0.94341 0.00580212 0) (1.00029 0.000674699 0) (1.00254 0.00907306 0) (1.00314 0.0089505 -2.69654e-18) (0.992127 0.00948333 2.03769e-18) (-0.0359469 0.772777 0) (-0.0173788 0.51053 0) (-0.0200192 0.954905 0) (-0.00692701 0.798403 0) (-0.0169755 0.552392 0) (0.0978352 0.178338 2.2893e-19) (0.148606 0.15048 0) (0.993612 -0.00769896 0) (0.954002 -0.00646255 0) (0.75955 0.049828 0) (0.692822 0.0556524 0) (0.661249 -0.0229569 0) (0.970934 -0.00482572 0) (0.623921 0.0604961 0) (0.451763 -0.0300891 1.50708e-18) (-0.0406746 2.86143 7.9643e-19) (0.0335308 2.91437 0) (0.0425424 2.89192 0) (0.00364667 2.70156 0) (-0.00866954 2.98629 9.4992e-19) (-0.0142795 2.89473 0) (-0.011078 2.99167 -2.91928e-18) (-0.0116087 2.92958 9.93246e-19) (0.0151569 1.33977 0) (0.0337601 1.38243 0) (-0.00757273 2.12211 3.06565e-22) (-0.00872341 2.06984 0) (-0.0197228 1.87204 0) (0.93833 -0.00546678 0) (0.85624 -0.0108348 0) (0.863587 0.00579553 0) (0.949275 -0.00636174 0) (0.883229 -0.00794001 0) (0.500954 1.12061 -2.19899e-19) (0.548594 1.19161 0) (0.337183 0.852482 3.32666e-20) (0.28094 0.717279 0) (0.904298 1.03241 -1.45997e-19) (1.01579 0.83302 2.8543e-19) (0.393858 1.33244 0) (0.539689 1.28628 0) (0.590877 1.22027 0) (0.0955878 0.17241 -2.98468e-19) (0.328705 0.19556 0) (0.292669 0.0834438 1.9914e-19) (0.97902 0.889051 0) (1.04695 0.730468 0) (1.07457 0.66442 -2.17191e-19) (1.11392 0.574374 0) (1.16861 0.379765 4.47983e-20) (0.957251 -0.0072464 0) (0.962595 -0.0081912 0) (0.900641 -0.00731642 0) (0.983893 -0.00814865 0) (0.974355 -0.0080836 0) (0.936457 -0.00654228 0) (1.0002 0.00250362 0) (1.00077 0.00124729 0) (0.999999 0.000773057 0) (0.0423244 2.07992 4.37259e-19) (0.146413 1.77604 0) (0.0158512 2.19841 6.69353e-19) (0.0551522 1.88384 -5.64942e-19) (0.173932 1.12234 -2.7473e-19) (0.0530858 0.986765 0) (0.123945 0.981068 0) (0.00478655 0.821364 0) (0.0291266 0.618744 0) (-0.00648611 2.24922 -9.07156e-22) (0.022743 2.01994 0) (-0.00584016 2.25083 -3.79293e-20) (0.0080262 2.02197 6.32016e-20) (0.00613601 0.791664 0) (0.0071123 0.775368 0) (0.00854308 0.584814 0) (-0.015439 0.745067 0) (-1.20639e-06 0.495081 0) (0.937119 0.0134716 0) (0.852449 -0.0118416 0) (0.926867 0.00450633 0) (0.844226 -0.0126417 0) (0.812315 -0.000440151 0) (0.899927 0.0217728 0) (0.874447 0.0275404 0) (0.788667 -0.00359098 0) (0.0102424 3.06724 -9.34543e-21) (0.015222 3.05913 0) (0.0123524 2.97035 0) (0.00756908 2.87657 0) (0.901161 3.9889 0) (1.19662 3.38287 9.43252e-19) (0.0828175 3.09566 0) (-0.0160814 2.92106 0) (0.0145216 1.41386 0) (-0.028946 1.73389 0) (0.00357587 1.58167 0) (-0.0343458 2.56503 -6.24586e-21) (-0.0219217 2.2641 0) (-0.0268848 2.40515 0) (0.0118422 1.95068 3.18498e-22) (-0.0113344 2.22925 8.99465e-22) (-0.00542564 2.19332 6.33395e-21) (0.00936719 1.92893 0) (0.444283 0.113475 5.36857e-19) (0.35877 -0.0126805 -5.26976e-19) (0.235558 1.57967 0) (0.283853 0.737322 -3.26086e-19) (0.177747 1.68005 -1.08747e-18) (0.241867 1.20496 1.0882e-18) (0.901887 0.00615387 0) (0.967224 0.0104826 0) (0.975072 0.00973986 0) (0.923157 0.0059582 0) (-0.00896789 0.734405 0) (-0.0269613 0.74358 0) (-0.0141801 0.499111 0) (0.235264 0.193697 6.38072e-19) (0.196069 0.17786 -7.58674e-19) (0.20158 0.131219 0) (1.09454 0.0864967 2.60456e-20) (1.07872 0.0398309 0) (1.01099 0.0422021 0) (0.906988 -0.00316373 0) (0.473923 0.0911507 0) (0.53312 0.0668719 -2.41585e-18) (0.391242 -0.0168851 9.09817e-19) (0.0109731 2.97701 8.36766e-19) (-0.0333173 2.86169 4.58025e-20) (0.00824984 3.05332 -1.96825e-20) (0.0156508 3.04328 7.37171e-19) (-0.0118846 3.00002 3.26183e-20) (-0.0122897 2.95232 -1.31546e-22) (-0.0150266 3.01333 -6.07641e-19) (0.0143094 3.02664 4.27839e-19) (0.00755916 3.03481 -6.96254e-19) (0.933578 0.00165078 0) (0.938746 -0.00148824 0) (0.846686 -0.0109538 0) (0.956599 0.0114904 0) (0.942879 0.0128205 0) (0.881886 0.00592596 0) (0.916925 0.0173703 0) (0.925963 0.0145845 0) (0.838192 0.00279156 0) (0.675079 1.42179 8.93394e-21) (0.693647 1.53316 0) (0.121396 0.30693 6.982e-20) (0.199198 0.635632 5.54755e-19) (0.234646 0.688286 -3.24668e-19) (0.219519 0.516008 6.43545e-19) (0.328625 0.803728 1.57952e-18) (0.124865 0.224437 3.79663e-19) (0.373836 0.179865 7.45964e-19) (0.357553 0.19303 1.93404e-19) (0.306694 0.0634988 3.70491e-19) (1.16345 0.430569 6.03852e-20) (1.19291 0.241478 5.87377e-20) (0.00449971 2.24237 2.64004e-19) (0.0432246 1.94896 0) (0.967744 0.0320677 0) (0.942998 0.0188512 0) (0.865794 -0.015925 0) (0.0124124 3.07497 0) (0.0168954 2.94403 1.30959e-18) (0.0139986 2.95695 0) (0.00581292 2.84982 -1.29978e-18) (0.00892615 3.09052 3.20542e-19) (0.0117691 3.08283 0) (0.714754 1.83141 -1.71052e-19) (1.24118 2.63921 5.78524e-19) (0.699762 2.01022 -1.40339e-18) (0.0226685 2.97676 -7.33568e-19) (0.0412794 3 0) (-0.0381697 2.88039 0) (-0.00739293 2.22681 -1.2379e-20) (-0.00998603 2.24543 -5.87778e-21) (0.00896323 1.97948 -8.09297e-21) (0.263472 1.38506 1.0492e-18) (0.270339 0.532058 -7.20623e-19) (0.070491 1.99668 7.73701e-19) (0.121933 1.86552 -9.27539e-19) (0.207634 1.52519 1.01776e-19) (0.00596958 3.12042 -1.79325e-18) (0.0130546 3.12083 1.97272e-18) (-0.00508831 2.98056 8.93183e-19) (-0.00147018 2.97519 -8.5994e-19) (-0.0177636 2.87737 -9.09744e-19) (0.0123155 3.10045 -2.38586e-18) (0.00546439 3.10526 2.41914e-18) (0.249185 0.674324 0) (0.203643 0.641049 -1.16978e-18) (0.0683516 0.210065 5.14087e-19) (0.339614 0.920156 1.12713e-18) (0.190033 0.266523 -1.73549e-18) (1.18039 0.170793 5.81122e-20) (1.1919 0.294937 0) (1.17671 0.11874 -3.79853e-21) (-0.00609775 2.25957 -1.63329e-21) (-0.00133802 2.24653 0) (0.0343877 1.98136 0) (0.313704 1.30628 -3.74469e-19) (0.350818 1.14873 -8.09086e-19) (0.220248 0.375515 1.44349e-18) (1.00642 -0.00972454 0) (1.00773 -0.00780771 4.9591e-19) (0.0137494 1.3148 0) (-0.00972088 1.28904 0) (1.00245 0.0033086 1.38158e-21) (1.00323 0.00788113 1.01773e-18) (-0.0283985 2.54983 7.90655e-21) (-0.0334324 2.59076 0) (0.0419437 3.1736 5.31558e-19) (0.379318 3.55266 0) (1.13534 0.680469 -6.46518e-20) (1.01196 0.0107939 -2.78711e-21) (1.02078 -0.00908909 0) (1.00159 0.000234364 1.46833e-22) (0.107608 1.36335 0) (0.141523 2.59114 0) (0.0185787 1.30319 0) (-0.00168693 2.6398 3.19619e-20) (-0.0218929 2.59105 1.71545e-20) (0.999148 0.0262969 2.57609e-21) (1.06151 0.00476735 0) (1.0979 0.0265374 0) (-0.0260135 1.76166 0) (-0.0227269 2.59526 0) (-0.0129189 1.29293 0) (0.289859 1.48281 -1.56342e-19) (1.01146 -0.00910471 0) (1.00969 -0.0130065 0) (1.00229 0.000918526 6.35564e-19) (1.00549 -0.00494516 -7.48484e-19) (1.00115 -0.000877844 0) (-0.00584578 1.47097 0) (0.0112563 1.36848 0) (0.0130476 1.43456 0) (-0.0133116 1.27894 0) (-0.00555898 1.25209 0) (-0.0119448 1.23109 0) (1.03528 -0.00467727 0) (1.01949 0.0150718 -9.19179e-22) (0.786256 1.3029 2.55996e-19) (1.00236 0.000342452 -6.34383e-19) (1.00339 0.00451632 7.57199e-19) (1.00129 0.00211223 0) (1.01132 0.00965146 6.3196e-19) (1.00697 0.00757119 -7.69206e-19) (1.00735 0.0112941 0) (-0.0289668 2.62167 0) (-0.0332798 2.59979 -1.30266e-20) (-0.0301051 2.61347 9.22723e-21) (1.23313 0.265983 5.69808e-19) (1.1597 0.0871775 0) (0.0456123 3.09028 -1.03799e-18) (0.0511415 2.87085 -7.3341e-20) (0.104784 3.20121 1.3899e-18) (0.123233 3.21391 -3.06186e-19) (0.145665 3.26124 0) (0.0233261 3.13793 2.86257e-19) (0.0623075 3.16166 1.03397e-18) (0.0625547 3.17908 -5.34989e-19) (0.0276928 3.12892 0) (0.629494 0.299468 0) (0.588132 0.33924 0) (1.11286 0.712999 1.59109e-19) (1.07843 0.846321 -1.59299e-19) (1.17392 0.596685 0) (1.20481 0.530337 0) (1.01584 0.0120534 -1.17426e-18) (1.01478 0.0128266 1.47642e-18) (1.02554 -0.00884461 0) (1.02387 -0.0103696 0) (1.00657 0.00286229 0) (1.01098 0.0042043 0) (1.00442 0.00214095 0) (1.00944 0.00643316 0) (1.00706 0.00509375 0) (1.00455 0.00533782 0) (0.0947014 1.35924 0) (0.0766353 1.34235 0) (0.135218 1.4106 0) (0.131649 1.41204 0) (0.150334 2.61527 0) (0.192638 2.68245 -4.35252e-19) (0.108659 2.67531 0) (0.0846815 2.67739 1.84668e-19) (0.0308369 2.68291 -1.88896e-19) (0.0202505 1.31878 0) (0.0233915 1.25729 0) (0.0236571 1.33282 0) (0.0273365 1.27771 0) (0.00107597 1.99243 5.10602e-22) (-0.0218897 2.61903 -3.53661e-21) (-0.00855099 2.68286 1.53733e-20) (-0.0195583 2.69606 0) (-0.0253022 2.62671 -3.46173e-20) (-0.0237977 2.62219 -2.0443e-21) (0.00965234 1.99153 1.37122e-21) (-0.00973353 2.41343 4.74536e-21) (-0.0135864 2.43397 -1.74286e-20) (1.01 0.0377281 1.19014e-18) (1.00621 0.0171558 -1.48325e-18) (1.00336 0.0433443 -1.21693e-18) (0.977402 0.0299734 1.53199e-18) (1.06333 0.008128 0) (1.04893 -0.00676418 0) (1.09064 0.0356155 0) (1.0742 0.0137351 0) (1.073 -0.000636826 0) (1.13818 0.075911 0) (1.11274 0.0432357 0) (1.11523 0.0356304 0) (-0.0261675 2.44802 4.06808e-23) (-0.0251603 2.02308 0) (-0.0204869 2.2322 0) (-0.0247341 2.6159 -7.19981e-21) (-0.0228873 2.62556 3.53999e-23) (0.00373566 1.57324 -1.92552e-20) (0.00298784 1.50067 1.94885e-20) (-0.0135053 1.38383 0) (-0.0101236 1.39148 0) (-0.0086344 1.38779 0) (-0.0114375 1.29737 0) (-0.000400915 1.24341 0) (0.37534 1.50432 2.55595e-19) (0.421127 1.51129 1.42779e-19) (0.598039 2.46675 -2.5465e-19) (0.391455 2.56314 7.09015e-19) (0.350341 2.07006 7.68291e-20) (1.02056 -0.0081102 0) (1.01572 -0.00942667 0) (1.0148 -0.0132411 0) (1.00759 -0.000701524 0) (1.00492 -0.000684343 0) (1.00798 -0.0045584 0) (1.0095 -0.00360594 0) (1.01455 -0.00444342 0) (1.02026 0.015914 1.15203e-18) (1.01766 0.0147984 -1.459e-18) (1.02073 0.0180986 -1.16108e-18) (1.01845 0.016496 1.45271e-18) (0.74616 1.34687 0) (0.681653 1.38495 2.20196e-19) (0.851451 1.22538 7.82504e-20) (0.886133 1.19184 -1.03824e-19) (1.16622 2.62275 3.00934e-19) (0.78671 0.122843 5.92368e-19) (1.1669 0.102728 0) (1.20546 0.193257 -4.61305e-19) (1.18628 0.152576 -1.91416e-20) (1.01226 0.155376 0) (0.0853987 3.02411 3.74379e-19) (0.0875274 2.90517 -1.23543e-18) (0.0353094 2.36507 7.84881e-19) (0.133609 -0.0912044 -3.78012e-19) (0.346836 3.45501 -2.38931e-19) (0.196318 3.34565 0) (0.227412 3.40533 3.11234e-19) (0.228946 3.08242 -1.28757e-18) (0.263076 3.20297 0) (0.00734877 3.12233 5.34897e-20) (0.0174912 3.13113 -6.13895e-19) (0.0167347 3.12704 9.03559e-19) (0.0340299 3.13992 0) (0.0319575 3.14982 0) (1.26282 2.58953 0) (0.52148 0.826691 -5.33859e-19) (0.99788 1.02353 1.05785e-20) (0.964731 1.07161 0) (0.83401 0.961382 -1.19292e-19) (1.05392 0.892713 2.77458e-20) (0.404678 0.372374 -9.31707e-19) (0.691657 0.314492 -2.46995e-20) (0.643443 0.23272 4.19355e-19) (0.607125 0.364974 3.09381e-20) (0.520548 0.341456 -1.24761e-18) (0.656141 0.327269 0) (0.697405 0.415062 7.22649e-19) (0.702681 0.421408 0) (0.638643 0.348617 0) (0.585845 0.293104 0) (0.769855 0.645362 4.15473e-19) (1.2402 0.294391 -4.68063e-19) (1.22842 0.428831 0) (1.23519 0.381397 0) (0.73249 0.179827 6.2691e-19) (0.832785 0.539914 -3.94307e-19) (0.750413 0.491748 6.99258e-19) (0.954966 0.427876 -7.30835e-19) (1.01887 0.0145088 7.82088e-19) (1.01733 0.0135899 -7.90017e-19) (1.01614 0.0142379 0) (1.0366 -0.00488057 0) (1.03016 -0.00788329 -7.41597e-19) (1.02831 -0.0107579 7.33982e-19) (1.02478 0.010454 0) (1.02294 0.0144373 0) (1.01253 0.00449495 0) (1.01454 0.00907003 0) (1.0161 0.00400096 0) (1.01535 0.00279991 0) (0.0628033 1.3554 0) (0.0618074 1.31948 0) (0.140816 1.41061 5.07987e-20) (0.265094 1.47768 7.28865e-20) (0.160741 1.4521 1.62722e-19) (0.190584 1.45735 -2.63575e-19) (0.145795 1.41506 0) (0.126661 1.57888 -1.17405e-19) (0.125759 1.57379 0) (0.344918 2.02839 -1.11828e-19) (0.337799 2.34324 6.70415e-19) (0.179162 1.45311 1.02353e-19) (0.264243 1.37796 1.67881e-20) (0.189682 1.3807 -1.36758e-20) (0.279056 1.31346 -1.11037e-19) (0.252303 1.5757 0) (0.253344 1.6243 1.15333e-19) (0.028518 2.275 -2.12782e-20) (0.0380587 2.677 0) (0.0678405 2.41454 1.1541e-19) (0.0618539 2.43399 0) (0.0708429 2.69394 -2.04886e-19) (0.0448432 2.71044 0) (0.0278007 1.41952 2.21873e-20) (0.0369267 1.4787 0) (0.033281 1.38209 0) (0.0246214 1.38184 -2.60035e-20) (0.000549345 2.66712 -3.14904e-21) (0.0255464 2.70102 2.17521e-19) (0.00903085 2.73608 1.30194e-21) (0.00204616 1.83734 4.09967e-21) (-0.00448638 1.68309 -1.33375e-21) (0.0179018 1.30735 0) (0.0232787 1.24138 0) (0.0409105 1.57496 1.3203e-20) (0.0378853 1.45089 -4.47966e-21) (0.0352207 1.52179 1.74515e-21) (0.0450881 1.60375 0) (-0.0329904 2.28101 6.39965e-20) (-0.0332781 2.56456 -2.59497e-20) (-0.0220076 2.46297 1.81717e-21) (-0.00843924 1.85448 -4.96969e-21) (-0.0302499 2.51479 -2.75538e-22) (-0.0247016 2.45434 1.99923e-20) (1.01861 0.0210598 -7.88208e-19) (1.01464 0.027088 7.90977e-19) (1.01375 0.0168215 0) (1.01234 0.0679135 1.08407e-18) (0.991953 0.0548438 -1.24821e-18) (0.953519 0.051466 1.39687e-18) (1.01344 0.111468 -1.47795e-19) (1.0433 -0.00510163 0) (1.05126 -0.00108354 7.10618e-19) (1.03975 -0.00837721 -7.10429e-19) (1.0706 0.0415448 -4.22391e-20) (1.06361 0.0277485 3.64453e-19) (1.06381 0.0626056 0) (1.0534 0.0517888 -1.31139e-19) (1.03242 0.0428749 0) (1.0259 0.0380002 0) (1.0277 0.0130962 0) (1.02415 0.0157184 0) (1.04013 0.032377 2.6946e-19) (1.03931 0.0273478 -5.96048e-19) (1.05251 0.036414 -2.85424e-19) (1.04854 0.0362595 -3.14712e-19) (1.07609 0.0670089 6.0467e-19) (1.09937 0.052843 0) (1.10557 0.0921211 0) (-0.0270326 2.29006 4.42161e-20) (-0.0196734 2.03985 -1.28803e-22) (-0.0212718 2.04383 0) (-0.0320954 2.45757 -4.40636e-20) (-0.0322282 2.41618 9.28841e-23) (-0.0349553 2.48814 3.80961e-21) (-0.0243353 2.63491 2.68625e-21) (-0.0287083 2.57847 -3.77469e-22) (-0.0260093 2.53072 -3.24888e-22) (-0.0206163 2.62962 3.45226e-21) (-0.0247008 2.63042 -3.20938e-21) (-0.0122733 1.48383 -7.08699e-22) (0.00233128 1.62283 -1.5612e-20) (0.365793 1.43344 -1.05261e-19) (0.363279 1.36094 3.60612e-20) (0.631189 1.4313 -2.13082e-19) (0.510144 1.5022 -1.38212e-19) (0.558417 1.46458 0) (0.608259 2.42962 2.1845e-19) (0.667406 2.43169 3.42286e-19) (0.424719 2.52173 7.99624e-20) (0.401682 2.54734 -6.86831e-19) (0.498458 2.49211 5.95077e-19) (0.549159 2.48254 0) (0.490095 2.53068 -5.62506e-19) (0.262307 2.59497 1.18145e-18) (0.362591 2.57012 -6.13119e-20) (0.284153 2.65559 -1.63015e-18) (0.964672 2.39654 7.20684e-19) (0.847394 2.39512 0) (1.0114 0.0012044 2.57876e-20) (1.01525 -0.00533665 -2.10426e-20) (1.01762 -0.00412452 -3.8476e-19) (1.01545 -0.00119784 3.83434e-19) (1.01297 0.00167065 0) (0.621158 1.29468 0) (0.657799 1.18224 0) (0.769729 1.10668 0) (0.644862 1.14189 0) (1.197 2.63918 5.01265e-20) (1.08875 2.38735 0) (0.825771 2.20025 3.60738e-21) (0.825628 2.45486 0) (0.918759 2.54315 -4.43107e-19) (0.950737 2.49314 2.96081e-19) (0.80674 0.150405 0) (0.767322 0.133829 1.61959e-19) (0.919839 0.150099 9.39969e-19) (0.835299 0.128055 -3.52369e-19) (0.792974 0.0873377 -1.08047e-18) (1.08287 0.230788 -8.7793e-19) (0.984892 0.294715 -7.76858e-21) (0.926778 0.330663 8.51659e-19) (1.01399 0.242799 7.13944e-19) (0.934407 0.190738 -1.24682e-18) (0.897353 0.201928 1.55865e-19) (0.943065 0.294589 -3.27284e-19) (0.910199 0.204987 0) (0.999204 0.194761 6.10495e-19) (1.05379 0.205053 0) (1.05024 0.213188 0) (1.12198 0.11919 2.77961e-19) (1.06187 0.183096 -1.06033e-20) (1.07619 0.234455 -1.58433e-19) (1.11536 0.202937 0) (1.02343 0.0468441 6.10367e-19) (1.03926 0.0607514 7.58928e-19) (1.03292 0.0448292 -6.05288e-19) (1.04139 0.0660557 -5.08792e-19) (1.01508 0.0719874 -7.67588e-19) (0.991093 0.160294 0) (0.992659 0.104144 0) (0.962567 0.0647341 -4.95744e-19) (0.910739 0.0954465 1.96057e-19) (1.03772 0.11129 7.04325e-19) (1.07365 0.130441 -8.13805e-19) (1.06627 0.170995 7.30747e-19) (1.034 0.148347 0) (1.083 0.115123 0) (1.05674 0.107203 -3.32125e-19) (1.04419 0.103556 -5.73111e-19) (0.588136 1.11047 1.1792e-19) (0.625047 1.43769 -2.41373e-20) (1.1476 2.73418 -2.49839e-19) (1.20002 3.11536 3.19347e-21) (1.25591 2.74072 -1.44825e-19) (1.29744 2.71248 2.6e-20) (1.27326 2.33441 -3.70411e-20) (1.18788 3.0212 -7.66199e-20) (1.20661 2.97801 2.28217e-19) (1.18218 3.26942 -1.22092e-19) (1.40188 2.98536 1.51001e-19) (1.41396 2.92418 0) (0.553796 0.848974 -4.83511e-20) (0.23498 1.22478 4.95038e-19) (0.498414 0.447591 5.9383e-19) (0.374089 0.209773 6.81495e-19) (0.544418 0.370239 7.04649e-19) (0.558571 0.467875 -1.13405e-18) (0.55968 0.465826 9.29163e-19) (0.511142 0.393867 -3.59406e-19) (0.439679 0.325345 8.11916e-19) (0.752947 0.235268 -3.59147e-19) (0.717622 0.272179 0) (0.686276 0.196324 9.41072e-21) (0.737327 0.506468 3.82173e-19) (0.693003 0.476816 -1.38902e-18) (0.648788 0.462206 2.22797e-20) (0.644281 0.433024 0) (0.691834 0.735064 3.83622e-19) (0.811908 0.792836 4.33242e-19) (0.740008 0.843951 -5.03114e-19) (0.879515 0.813389 -1.61248e-19) (0.913 0.853572 -4.03369e-20) (0.920686 0.860617 4.13565e-20) (0.870787 0.673737 -6.93986e-19) (0.937105 0.722695 1.4995e-19) (0.986622 0.724493 0) (0.985562 0.699629 -1.96413e-19) (1.03034 0.315563 2.24616e-19) (1.15017 0.317453 2.77853e-19) (1.06649 0.270546 3.59581e-19) (0.990766 0.360146 -4.41565e-19) (1.03556 0.465785 0) (1.12294 0.412051 0) (0.892323 0.40545 6.83082e-21) (0.842786 0.292286 0) (0.875361 0.279664 4.05078e-19) (0.907633 0.327253 9.5573e-21) (0.96383 0.463673 2.05694e-18) (0.889687 0.532389 5.26321e-19) (0.912991 0.475731 -5.69653e-19) (0.827185 0.453054 6.04217e-19) (0.810216 0.433009 3.70026e-19) (0.793097 0.402679 -3.6296e-19) (1.02796 -0.000530862 6.36106e-19) (1.02029 0.000348085 0) (1.01893 0.00119059 4.15034e-19) (1.02255 -0.000953171 -9.39625e-19) (1.02245 0.00433067 4.57609e-19) (1.0201 0.0112459 -9.57588e-19) (1.02097 0.0110031 0) (1.01994 0.0117739 -1.99416e-19) (1.01645 0.00759364 4.99807e-19) (1.01673 0.0106981 -2.50953e-19) (1.01739 0.0103139 1.83714e-19) (0.028837 1.32325 0) (0.0341656 1.34968 0) (0.0444011 1.33363 0) (0.0433451 1.29203 0) (0.0764717 1.36242 3.44845e-20) (0.0910025 1.33561 -3.52649e-20) (0.0503477 1.54585 -1.48899e-20) (0.105949 1.3779 -5.02853e-20) (0.0431204 1.46024 1.32549e-21) (0.0461055 1.45788 -1.49712e-21) (0.0673752 1.36559 -4.06346e-20) (0.0571052 1.37009 3.48774e-20) (0.0473727 1.34822 5.67612e-21) (0.0396137 1.36648 1.17387e-21) (0.106787 2.38547 -1.26708e-19) (0.0972102 2.42832 0) (0.154901 2.03221 1.05341e-19) (0.114239 1.70547 4.66235e-20) (0.217918 2.02589 -8.57405e-20) (0.215754 2.43333 0) (0.232881 2.3967 -6.84103e-19) (0.301645 2.38571 4.94039e-19) (0.251393 2.00167 -2.29486e-19) (0.142981 2.16032 1.59045e-19) (0.112738 2.26568 0) (0.0225307 1.86241 -4.11548e-20) (-0.0069665 2.39863 -6.95928e-20) (0.00436071 2.14601 0) (0.0060725 2.4594 -1.50404e-20) (0.0260573 2.30395 2.97574e-20) (0.0197994 1.40334 -5.36178e-21) (0.0133424 1.38843 8.51923e-20) (0.0126059 1.39147 -3.03718e-20) (0.0201668 1.3909 -2.04492e-20) (0.0255215 1.42328 0) (0.0107682 1.37308 0) (-0.0015296 1.29857 -3.42252e-20) (0.00390663 1.36473 9.09015e-21) (0.00850391 1.36714 0) (0.0139372 1.29703 -2.78837e-20) (0.0139873 1.22909 5.50934e-20) (1.04198 0.0139694 0) (1.04829 0.00952508 -6.65178e-20) (1.039 0.0230029 -4.80196e-19) (1.04933 0.0218458 0) (1.05393 0.0209249 0) (1.03625 0.0119183 -6.72129e-21) (1.03026 0.0122777 7.70579e-19) (1.03188 0.0164916 9.36995e-19) (1.02575 0.0203493 0) (1.02246 0.0207688 0) (1.03549 0.0246808 4.79209e-19) (1.026 0.0268624 0) (1.02369 0.0271378 0) (-0.0242153 2.03106 0) (-0.000285937 1.6549 -4.45587e-21) (-0.0107143 1.76308 -2.19088e-20) (-0.00495655 1.37048 0) (-0.0170319 1.55231 -8.45506e-21) (-0.00401387 1.45495 5.55002e-21) (-0.00801324 1.3759 0) (0.403864 1.66088 0) (0.355472 1.30016 -5.23943e-20) (0.277443 1.34385 0) (0.420821 1.30668 -9.81869e-21) (0.462686 1.46258 0) (0.445295 1.40436 2.75319e-20) (1.03976 2.68727 -1.54551e-20) (0.980139 2.4178 -9.05627e-19) (0.938687 2.20768 1.03254e-18) (0.862774 2.38815 2.41815e-19) (0.854012 2.50404 0) (0.921571 2.50139 0) (0.948474 2.38969 0) (0.925521 2.37714 -9.38172e-19) (0.694413 2.4749 -3.88657e-19) (0.8033 2.4586 -9.98709e-20) (0.81139 2.43683 7.54366e-20) (0.70421 2.40562 0) (0.808464 2.39994 0) (0.770392 2.41493 -3.69206e-19) (0.768707 2.48285 0) (0.605389 1.07113 0) (0.518748 0.894118 -5.52262e-19) (0.522137 0.95899 -3.21508e-20) (0.504016 1.09656 0) (0.491035 1.00937 8.46677e-19) (0.771072 0.877445 -1.42208e-19) (0.780701 1.01476 0) (0.758433 0.993368 2.01e-19) (0.645891 1.02296 0) (0.641181 0.936758 0) (1.16483 2.7683 -2.26609e-19) (1.14014 2.82711 -9.35965e-20) (0.927424 2.35675 8.00062e-20) (0.903356 2.33538 -7.76274e-20) (1.13378 2.74609 0) (1.08556 2.71479 9.33248e-20) (1.10118 2.5063 -3.04915e-19) (1.00068 2.25927 -2.85503e-20) (0.500746 1.35648 0) (0.518678 1.09436 -1.03946e-19) (0.579375 1.1781 0) (0.85825 0.215132 0) (0.78462 0.166418 0) (0.724977 0.135712 0) (0.860237 0.214377 -6.22013e-19) (0.773464 0.208818 3.73911e-19) (0.925724 0.0790735 -4.06356e-19) (0.944208 0.129207 0) (0.917705 0.139831 1.74686e-19) (0.858262 0.0991009 7.01135e-19) (0.821754 0.0684065 -4.38472e-19) (1.1031 3.36295 -6.79984e-19) (1.16811 3.28559 0) (1.12285 3.44814 -1.57908e-18) (0.662178 3.59341 1.31571e-18) (1.03374 3.08938 1.20995e-19) (0.524222 0.828322 5.71616e-19) (0.511211 0.798007 0) (0.380175 0.477663 -1.50393e-19) (0.47063 0.671173 8.68811e-19) (0.525333 0.454327 -2.06868e-19) (0.514102 0.503432 2.36709e-19) (0.691386 0.543028 4.93194e-19) (0.720974 0.570566 0) (0.64892 0.607614 0) (0.621042 0.560007 0) (0.994176 0.605811 1.0306e-19) (0.945821 0.5769 -5.09218e-19) (0.963228 0.599935 3.81646e-19) (1.02544 0.527019 -3.81414e-19) (1.0649 0.497687 0) (1.06816 0.589127 -9.93293e-20) (0.856352 0.394096 -8.30578e-19) (0.852259 0.386216 -1.05716e-18) (0.802735 0.38397 6.5294e-19) (0.80377 0.340888 -6.73415e-19) (0.845637 0.301777 -5.24336e-19) (0.804357 0.300889 6.44578e-19) (1.0265 0.00629956 -4.79041e-19) (1.02616 0.00641213 9.65822e-19) (1.02985 0.000534221 6.16713e-19) (1.03387 0.00121033 -7.40653e-19) (1.03363 0.0108372 0) (1.02979 0.011052 -1.20505e-18) (0.090873 1.66632 1.42636e-20) (0.051042 1.59444 0) (0.102479 1.71231 1.0406e-19) (0.108028 1.68084 -9.70009e-20) (0.0319426 1.53715 2.79903e-20) (0.0242665 1.52092 0) (0.00695215 1.68606 0) (-0.00422592 1.49062 4.38724e-21) (-0.00182722 1.43121 -3.95097e-21) (-0.0098181 1.5469 3.05438e-21) (-0.00431739 1.8894 4.40506e-21) (-0.0189217 1.94333 2.23035e-22) (0.490206 1.37805 -2.75966e-19) (0.493819 1.37422 3.01126e-19) (0.436287 1.29893 -2.35671e-20) (0.421514 1.29982 8.84298e-21) (0.611343 1.30329 0) (0.543408 1.39412 1.00899e-19) (0.543872 1.39736 -9.81993e-20) (0.467834 1.27807 2.25524e-20) (0.509566 1.2403 0) (0.576296 1.20982 0) (0.668577 2.43694 5.728e-19) (0.662825 2.45984 1.31382e-18) (0.719612 2.47677 -9.02854e-19) (0.622571 2.44938 -2.04761e-19) (0.553193 2.54625 2.83319e-19) (0.493513 2.50716 -7.37111e-19) (0.989105 2.39463 -5.81783e-19) (1.02362 2.4135 0) (0.945314 2.19237 -6.43007e-19) (1.05571 2.69542 0) (1.05497 2.67797 0) (0.617113 2.3137 2.80114e-20) (1.12419 3.08259 9.15805e-20) (1.00679 2.98408 -1.4767e-19) (0.336357 0.86426 0) (0.354252 0.771007 -3.04474e-19) (0.544287 0.697982 -3.09266e-19) (0.383839 2.16063 0) (0.411634 2.75126 -8.51183e-20) (0.423017 2.49065 0) (0.700863 0.700308 -8.18204e-19) (0.763637 0.695526 1.14869e-18) (0.771855 0.657611 -1.13989e-18) (0.686884 0.658131 -1.04613e-19) (0.744047 0.613364 -4.3526e-19) (0.979623 2.76926 -6.93712e-20) (1.01688 2.77191 -2.09079e-19) (0.57056 2.24089 4.04289e-19) (0.618078 1.75812 -3.25933e-19) (0.7153 1.87647 -4.93991e-19) (0.983536 2.41019 -1.37522e-19) (0.981709 2.36626 3.6439e-19) (0.662422 1.79733 3.30838e-20) (0.469511 1.3244 1.75238e-19) ) ; boundaryField { wall-4 { type noSlip; } velocity-inlet-5 { type fixedValue; value uniform (1 0 0); } velocity-inlet-6 { type fixedValue; value uniform (0 3 0); } pressure-outlet-7 { type zeroGradient; } wall-8 { type noSlip; } frontAndBackPlanes { type empty; } } // ************************************************************************* //
ac235215bc4736ede4a934afeca995da5be7fec3
9528e613be5b65667ac114d9e213aa6099e5a969
/drivers/Confusion/EricksonManufacturedSolution.cpp
3dd72009dc656b34f34db7ae2a97305f0c2bffa5
[]
no_license
CamelliaDPG/Camellia
e8c2e95236b756acace0cade23b55a8ce459555a
e6e6c24e4d2b521941d14f13f3cc4fcbde873f96
refs/heads/master
2020-04-05T14:03:51.868718
2016-08-31T20:09:22
2016-08-31T20:09:22
4,127,915
13
8
null
null
null
null
UTF-8
C++
false
false
12,244
cpp
EricksonManufacturedSolution.cpp
#include "ConfusionBilinearForm.h" #include "EricksonManufacturedSolution.h" typedef Sacado::Fad::SFad<double,2> F2; // FAD with # of independent vars fixed at 2 (x and y) typedef Sacado::Fad::SFad< Sacado::Fad::SFad<double,2>, 2> F2_2; // same thing, but nested so we can take 2 derivatives EricksonManufacturedSolution::EricksonManufacturedSolution(double epsilon, double beta_x, double beta_y) { _epsilon = epsilon; _beta_x = beta_x; _beta_y = beta_y; _useWallBC = true; // use wall u=0 bc on outflow // set the class variables from ExactSolution: _bc = Teuchos::rcp(this,false); // false: don't let the RCP own the memory _rhs = Teuchos::rcp(this,false); _bilinearForm = Teuchos::rcp(new ConfusionBilinearForm(epsilon,beta_x,beta_y)); } int EricksonManufacturedSolution::H1Order() { // -1 for non-polynomial solution... return -1; } template <typename T> const T EricksonManufacturedSolution::u(T &x, T &y) { // in Bui, Demkowicz, Ghattas' paper double pi = acos(0.0)*2.0; T t = exp((1.0-x)/_epsilon)*sin(pi*y/(_epsilon*_epsilon)); // Norbert's example return t; } double EricksonManufacturedSolution::solutionValue(int trialID, FieldContainer<double> &physicalPoint) { double x = physicalPoint(0); double y = physicalPoint(1); F2 sx(2,0,x), sy(2,1,y), su; // s for Sacado su = u(sx,sy); double value; double pi = acos(0.0)*2.0; double C0 = 0.0;// average of u0 double u = C0; double u_x = 0.0; double u_y = 0.0; for (int n = 1; n<20; n++) { double lambda = n*n*pi*pi*_epsilon; double d = sqrt(1.0+4.0*_epsilon*lambda); double r1 = (1.0+d)/(2.0*_epsilon); double r2 = (1.0-d)/(2.0*_epsilon); double Cn = 0.0; if (n==1) { Cn = 1.0; // first term only } /* // discontinuous hat Cn = -1 + cos(n*pi/2)+.5*n*pi*sin(n*pi/2) + sin(n*pi/4)*(n*pi*cos(n*pi/4)-2*sin(3*n*pi/4)); Cn /= (n*pi); Cn /= (n*pi); */ // normal stress outflow double Xbottom; double Xtop; double dXtop; if (!_useWallBC) { Xbottom = r1*exp(-r2) - r2*exp(-r1); Xtop = r1*exp(r2*(x-1.0)) - r2*exp(r1*(x-1.0)); dXtop = r1*r2*(exp(r2*(x-1.0)) - exp(r1*(x-1.0))); } else { // wall, zero outflow Xtop = (exp(r2*(x-1))-exp(r1*(x-1))); Xbottom = (exp(-r2)-exp(-r1)); dXtop = (exp(r2*(x-1))*r2-exp(r1*(x-1))*r1); } double X = Xtop/Xbottom; double dX = dXtop/Xbottom; double Y = Cn*cos(n*pi*y); double dY = -Cn*n*pi*sin(n*pi*y); u += X*Y; u_x += _epsilon * dX*Y; u_y += _epsilon * X*dY; } // cout << "u = " << u << endl; switch(trialID) { case ConfusionBilinearForm::U: value = u; break; case ConfusionBilinearForm::U_HAT: value = u; break; case ConfusionBilinearForm::SIGMA_1: value = u_x; // SIGMA_1 == eps * d/dx (u) break; case ConfusionBilinearForm::SIGMA_2: value = u_y; // SIGMA_2 == eps * d/dy (u) break; case ConfusionBilinearForm::BETA_N_U_MINUS_SIGMA_HAT: TEUCHOS_TEST_FOR_EXCEPTION( trialID == ConfusionBilinearForm::BETA_N_U_MINUS_SIGMA_HAT, std::invalid_argument, "for fluxes, you must call solutionValue with unitNormal argument."); break; default: TEUCHOS_TEST_FOR_EXCEPTION( true, std::invalid_argument, "solutionValues called with unknown trialID."); } return value; } double EricksonManufacturedSolution::solutionValue(int trialID, FieldContainer<double> &physicalPoint, FieldContainer<double> &unitNormal) { if ( trialID != ConfusionBilinearForm::BETA_N_U_MINUS_SIGMA_HAT ) { return solutionValue(trialID,physicalPoint); } // otherwise, get SIGMA_1 and SIGMA_2, and the unit normal double sigma1 = solutionValue(ConfusionBilinearForm::SIGMA_1,physicalPoint); double sigma2 = solutionValue(ConfusionBilinearForm::SIGMA_2,physicalPoint); double u = solutionValue(ConfusionBilinearForm::U,physicalPoint); double n1 = unitNormal(0); double n2 = unitNormal(1); double sigma_n = sigma1*n1 + sigma2*n2; double beta_n = _beta_x*n1 + _beta_y*n2; return u*beta_n - sigma_n; } /********** RHS implementation **********/ bool EricksonManufacturedSolution::nonZeroRHS(int testVarID) { return false; } void EricksonManufacturedSolution::rhs(int testVarID, const FieldContainer<double> &physicalPoints, FieldContainer<double> &values) { int numCells = physicalPoints.dimension(0); int numPoints = physicalPoints.dimension(1); int spaceDim = physicalPoints.dimension(2); if (testVarID == ConfusionBilinearForm::V) { // f = - eps * (d^2/dx^2 + d^2/dy^2) ( u ) + beta_x du/dx + beta_y du/dy values.resize(numCells,numPoints); for (int cellIndex=0; cellIndex<numCells; cellIndex++) { for (int ptIndex=0; ptIndex<numPoints; ptIndex++) { double x = physicalPoints(cellIndex,ptIndex,0); double y = physicalPoints(cellIndex,ptIndex,1); F2_2 sx(2,0,x), sy(2,1,y), su; // s for Sacado sx.val() = F2(2,0,x); sy.val() = F2(2,1,y); su = u(sx,sy); /* these are values of convection-diffusion values(cellIndex,ptIndex) = - _epsilon * ( su.dx(0).dx(0) + su.dx(1).dx(1) ) + _beta_x * su.dx(0).val() + _beta_y * su.dx(1).val(); */ // this RHS corresponds to only convection //values(cellIndex,ptIndex) = _beta_x * su.dx(0).val() + _beta_y * su.dx(1).val(); // exact RHS double pi = acos(0.0)*2.0; double epsSquared = _epsilon*_epsilon; // values(cellIndex,ptIndex) = exp((1.0-x)/_epsilon)*(pi*pi - 2*epsSquared)*sin(pi*y/epsSquared)/(epsSquared*_epsilon); values(cellIndex,ptIndex) = 0.0; } } } } /***************** BC Implementation *****************/ bool EricksonManufacturedSolution::bcsImposed(int varID) { // returns true if there are any BCs anywhere imposed on varID return (varID == ConfusionBilinearForm::U_HAT); // return (varID == ConfusionBilinearForm::BETA_N_U_MINUS_SIGMA_HAT || (varID == ConfusionBilinearForm::U_HAT)); } void EricksonManufacturedSolution::imposeBC(int varID, FieldContainer<double> &physicalPoints, FieldContainer<double> &unitNormals, FieldContainer<double> &dirichletValues, FieldContainer<bool> &imposeHere) { int numCells = physicalPoints.dimension(0); int numPoints = physicalPoints.dimension(1); int spaceDim = physicalPoints.dimension(2); TEUCHOS_TEST_FOR_EXCEPTION( ( spaceDim != 2 ), std::invalid_argument, "ConfusionBC expects spaceDim==2."); TEUCHOS_TEST_FOR_EXCEPTION( ( dirichletValues.dimension(0) != numCells ) || ( dirichletValues.dimension(1) != numPoints ) || ( dirichletValues.rank() != 2 ), std::invalid_argument, "dirichletValues dimensions should be (numCells,numPoints)."); TEUCHOS_TEST_FOR_EXCEPTION( ( imposeHere.dimension(0) != numCells ) || ( imposeHere.dimension(1) != numPoints ) || ( imposeHere.rank() != 2 ), std::invalid_argument, "imposeHere dimensions should be (numCells,numPoints)."); Teuchos::Array<int> pointDimensions; pointDimensions.push_back(2); for (int cellIndex=0; cellIndex<numCells; cellIndex++) { for (int ptIndex=0; ptIndex<numPoints; ptIndex++) { FieldContainer<double> physicalPoint(pointDimensions, &physicalPoints(cellIndex,ptIndex,0)); FieldContainer<double> unitNormal(pointDimensions, &unitNormals(cellIndex,ptIndex,0)); double beta_n = unitNormals(cellIndex,ptIndex,0)*_beta_x + unitNormals(cellIndex,ptIndex,1)*_beta_y; double x = physicalPoint(cellIndex,ptIndex,0); double y = physicalPoint(cellIndex,ptIndex,1); imposeHere(cellIndex,ptIndex) = false; // if (varID==ConfusionBilinearForm::BETA_N_U_MINUS_SIGMA_HAT) { // dirichletValues(cellIndex,ptIndex) = solutionValue(varID, physicalPoint, unitNormal); if (varID==ConfusionBilinearForm::U_HAT) { dirichletValues(cellIndex,ptIndex) = solutionValue(varID, physicalPoint); if ( abs(x-1.0) > 1e-12) // if not the outflow (pts on boundary already) { imposeHere(cellIndex,ptIndex) = true; } // wall boundary if (abs(x-1.0)<1e-12 && _useWallBC) { dirichletValues(cellIndex,ptIndex) = solutionValue(varID, physicalPoint); imposeHere(cellIndex,ptIndex) = true; } } } } } void EricksonManufacturedSolution::getConstraints(FieldContainer<double> &physicalPoints, FieldContainer<double> &unitNormals, vector<map<int,FieldContainer<double > > > &constraintCoeffs, vector<FieldContainer<double > > &constraintValues) { int numCells = physicalPoints.dimension(0); int numPoints = physicalPoints.dimension(1); int spaceDim = physicalPoints.dimension(2); map<int,FieldContainer<double> > outflowConstraint; FieldContainer<double> uCoeffs(numCells,numPoints); FieldContainer<double> beta_sigmaCoeffs(numCells,numPoints); FieldContainer<double> outflowValues(numCells,numPoints); double tol = 1e-12; // default to no constraints, apply on outflow only uCoeffs.initialize(0.0); beta_sigmaCoeffs.initialize(0.0); outflowValues.initialize(0.0); Teuchos::Array<int> pointDimensions; pointDimensions.push_back(2); for (int cellIndex=0; cellIndex<numCells; cellIndex++) { for (int pointIndex=0; pointIndex<numPoints; pointIndex++) { FieldContainer<double> physicalPoint(pointDimensions, &physicalPoints(cellIndex,pointIndex,0)); FieldContainer<double> unitNormal(pointDimensions, &unitNormals(cellIndex,pointIndex,0)); double x = physicalPoints(cellIndex,pointIndex,0); double y = physicalPoints(cellIndex,pointIndex,1); double beta_n = _beta_x*unitNormals(cellIndex,pointIndex,0)+_beta_y*unitNormals(cellIndex,pointIndex,1); if ( abs(x-1.0) < tol ) // if on outflow boundary { TEUCHOS_TEST_FOR_EXCEPTION(beta_n < 0,std::invalid_argument,"Inflow condition on boundary"); // this combo isolates sigma_n //uCoeffs(cellIndex,pointIndex) = 1.0; uCoeffs(cellIndex,pointIndex) = beta_n; beta_sigmaCoeffs(cellIndex,pointIndex) = -1.0; double beta_n_u_minus_sigma_n = solutionValue(ConfusionBilinearForm::BETA_N_U_MINUS_SIGMA_HAT, physicalPoint, unitNormal); double u_hat = solutionValue(ConfusionBilinearForm::U_HAT, physicalPoint, unitNormal); outflowValues(cellIndex,pointIndex) = beta_n*u_hat - beta_n_u_minus_sigma_n; // sigma_n } } } outflowConstraint[ConfusionBilinearForm::U_HAT] = uCoeffs; outflowConstraint[ConfusionBilinearForm::BETA_N_U_MINUS_SIGMA_HAT] = beta_sigmaCoeffs; if (!_useWallBC) { constraintCoeffs.push_back(outflowConstraint); // only one constraint on outflow constraintValues.push_back(outflowValues); // only one constraint on outflow } } // =============== ABSTRACT FUNCTION INTERFACE for trialID U =================== void EricksonManufacturedSolution::getValues(FieldContainer<double> &functionValues, const FieldContainer<double> &physicalPoints) { int numCells = physicalPoints.dimension(0); int numPoints = physicalPoints.dimension(1); int spaceDim = physicalPoints.dimension(2); functionValues.resize(numCells,numPoints); Teuchos::Array<int> pointDimensions; pointDimensions.push_back(spaceDim); for (int i=0; i<numCells; i++) { for (int j=0; j<numPoints; j++) { double x = physicalPoints(i,j,0); double y = physicalPoints(i,j,1); FieldContainer<double> physicalPoint(pointDimensions); physicalPoint(0) = x; physicalPoint(1) = y; functionValues(i,j) = solutionValue(ConfusionBilinearForm::U,physicalPoint); } } }
395cd3b02a252d3e41657c3626a8ffc61e5c206c
086c5bb3df096194d3bd51c9b3a06b7c4e893207
/Quantorium/SourceCode/QuantumServer/src/utils/strutils.h
a3b1b4e2b6f2cf82e83455ba1d275534fcd6634a
[]
no_license
519984307/Randomize
3bb7c8082f993ad7aa8092790d032c91eb4bf875
c9b8cd59c097630b9878c7975f9fc77cbd8519f2
refs/heads/master
2023-03-18T18:51:43.774835
2020-09-13T12:35:13
2020-09-13T12:35:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
697
h
strutils.h
#ifndef STRUTILS_H #define STRUTILS_H #include <QString> #include <QMap> #include <QHash> #include "math.h" class StrUtils { public: static QString fillValues(QString templ, QMap<QString, QString> valuesMap); static QString intToBitmask(int intVal); static QList<qlonglong> longToList(qlonglong longVal); static QString replaceTag(QString inStr, QString tagName, QString templ); static QHash<QString, QString> attrsToHash(QString attrs); static QStringList dashValues(QString inStr); static QString uuid(); private: StrUtils(); }; bool lessThanByLength(QString &str1, QString &str2); bool greaterThanByLength(QString &str1, QString &str2); #endif // STRUTILS_H
f363f93f059b1bb4266945f904af20322566fdec
a888a75916821cda3487aa023efd277378936d75
/libs/tex/view_selection.cpp
538b634d0baa0bda7568749ba3f97c66793128ab
[ "BSD-3-Clause" ]
permissive
nmoehrle/mvs-texturing
9639762b031df52ff3c015b9b552171da78f3f23
1a8603e7804e679f329885bceeb3bea1d156be02
refs/heads/master
2023-08-30T10:40:17.191146
2022-03-30T10:19:26
2022-03-30T10:19:26
27,456,043
888
342
NOASSERTION
2023-01-10T20:53:36
2014-12-02T22:08:53
C++
UTF-8
C++
false
false
4,716
cpp
view_selection.cpp
/* * Copyright (C) 2015, Nils Moehrle * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #include <util/timer.h> #include "util.h" #include "texturing.h" #include "mapmap/full.h" TEX_NAMESPACE_BEGIN void view_selection(DataCosts const & data_costs, UniGraph * graph, Settings const &) { using uint_t = unsigned int; using cost_t = float; constexpr uint_t simd_w = mapmap::sys_max_simd_width<cost_t>(); using unary_t = mapmap::UnaryTable<cost_t, simd_w>; using pairwise_t = mapmap::PairwisePotts<cost_t, simd_w>; /* Construct graph */ mapmap::Graph<cost_t> mgraph(graph->num_nodes()); for (std::size_t i = 0; i < graph->num_nodes(); ++i) { if (data_costs.col(i).empty()) continue; std::vector<std::size_t> adj_faces = graph->get_adj_nodes(i); for (std::size_t j = 0; j < adj_faces.size(); ++j) { std::size_t adj_face = adj_faces[j]; if (data_costs.col(adj_face).empty()) continue; /* Uni directional */ if (i < adj_face) { mgraph.add_edge(i, adj_face, 1.0f); } } } mgraph.update_components(); mapmap::LabelSet<cost_t, simd_w> label_set(graph->num_nodes(), false); for (std::size_t i = 0; i < data_costs.cols(); ++i) { DataCosts::Column const & data_costs_for_node = data_costs.col(i); std::vector<mapmap::_iv_st<cost_t, simd_w> > labels; if (data_costs_for_node.empty()) { labels.push_back(0); } else { labels.resize(data_costs_for_node.size()); for(std::size_t j = 0; j < data_costs_for_node.size(); ++j) { labels[j] = data_costs_for_node[j].first + 1; } } label_set.set_label_set_for_node(i, labels); } std::vector<unary_t> unaries; unaries.reserve(data_costs.cols()); pairwise_t pairwise(1.0f); for (std::size_t i = 0; i < data_costs.cols(); ++i) { DataCosts::Column const & data_costs_for_node = data_costs.col(i); std::vector<mapmap::_s_t<cost_t, simd_w> > costs; if (data_costs_for_node.empty()) { costs.push_back(1.0f); } else { costs.resize(data_costs_for_node.size()); for(std::size_t j = 0; j < data_costs_for_node.size(); ++j) { float cost = data_costs_for_node[j].second; costs[j] = cost; } } unaries.emplace_back(i, &label_set); unaries.back().set_costs(costs); } mapmap::StopWhenReturnsDiminish<cost_t, simd_w> terminate(5, 0.01); std::vector<mapmap::_iv_st<cost_t, simd_w> > solution; auto display = [](const mapmap::luint_t time_ms, const mapmap::_iv_st<cost_t, simd_w> objective) { std::cout << "\t\t" << time_ms / 1000 << "\t" << objective << std::endl; }; /* Create mapMAP solver object. */ mapmap::mapMAP<cost_t, simd_w> solver; solver.set_graph(&mgraph); solver.set_label_set(&label_set); for(std::size_t i = 0; i < graph->num_nodes(); ++i) solver.set_unary(i, &unaries[i]); solver.set_pairwise(&pairwise); solver.set_logging_callback(display); solver.set_termination_criterion(&terminate); /* Pass configuration arguments (optional) for solve. */ mapmap::mapMAP_control ctr; ctr.use_multilevel = true; ctr.use_spanning_tree = true; ctr.use_acyclic = true; ctr.spanning_tree_multilevel_after_n_iterations = 5; ctr.force_acyclic = true; ctr.min_acyclic_iterations = 5; ctr.relax_acyclic_maximal = true; ctr.tree_algorithm = mapmap::LOCK_FREE_TREE_SAMPLER; /* Set false for non-deterministic (but faster) mapMAP execution. */ ctr.sample_deterministic = true; ctr.initial_seed = 548923723; std::cout << "\tOptimizing:\n\t\tTime[s]\tEnergy" << std::endl; solver.optimize(solution, ctr); /* Label 0 is undefined. */ std::size_t num_labels = data_costs.rows() + 1; std::size_t undefined = 0; /* Extract resulting labeling from solver. */ for (std::size_t i = 0; i < graph->num_nodes(); ++i) { int label = label_set.label_from_offset(i, solution[i]); if (label < 0 || num_labels <= static_cast<std::size_t>(label)) { throw std::runtime_error("Incorrect labeling"); } if (label == 0) undefined += 1; graph->set_label(i, static_cast<std::size_t>(label)); } std::cout << '\t' << undefined << " faces have not been seen" << std::endl; } TEX_NAMESPACE_END