blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
afda1109dc86860cff962dd77d1dc76130ead727 | dd3a1ea4a43e067f14c0ba1c08d066ab2332d002 | /Codeforces/Codeforces 1348C.cpp | a92e731144800c7d75c9c6dd1d8de08cf23884be | [] | no_license | codermehraj/Problem-solving-and-discussion-ACM- | eda9546d30c4c9b4ac77841d986d2c57d279c1ae | 657875866f08b7b2598ca9b63246a17f914e223b | refs/heads/master | 2023-03-08T17:05:04.525101 | 2021-02-25T14:51:43 | 2021-02-25T14:51:43 | 256,446,820 | 2 | 1 | null | 2020-07-13T16:00:21 | 2020-04-17T08:32:21 | C++ | UTF-8 | C++ | false | false | 584 | cpp | /* ~ CoderMehraJ ~ */
#include <bits/stdc++.h>
using namespace std;
#define show(x) cout << #x << " = " << x << '\n';
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int t,n,k,num;
string s;
cin>>t;
while(t--){
cin>>n>>k;
cin>>s;
sort(s.begin(), s.end());
if(s[0]!=s[k-1]) cout<<s[k-1]<<endl;
if(s[0]!=s[k-1]) continue;
cout<<s[k-1];
num=(n-1)/k;
if(s[k]!=s[n-1]) for(int i=k;i<n;i++) cout<<s[i];
else for(int i=0;i<num;i++) cout<<s[k];
cout<<'\n';
}
return 0;
}
| [
"noreply@github.com"
] | codermehraj.noreply@github.com |
4539776f3922f27303dd206d7653ac2a866c6a7b | 202c37b75acc5d19a188b390a7ac7fbd102ac1a1 | /队列/LinkQueue.cpp | 0558f57534e63b67e7b2e6cef0702ceae04587f8 | [] | no_license | mayali123/data-structure | 72eb7e4ee8868ded60d40e3cf79db6a800a28ebf | 9fea520870e9769c183273ac859424fd98da713a | refs/heads/master | 2023-03-02T07:36:45.965688 | 2021-02-16T08:17:43 | 2021-02-16T08:17:43 | 296,842,832 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,059 | cpp | // 用链表实现的队列
#include<stdio.h>
#include<malloc.h>
#define ElemType int
typedef struct List{
ElemType data;
struct List* next;
}L;
typedef struct LinkQueue{
L* front;
L* rear;
}LQ;
LQ* CreateLinkQueue()
{
LQ* lq = (LQ*)malloc(sizeof(LQ));
lq->front = lq->rear = NULL;
return lq;
}
void AddElem(LQ *lq,ElemType e)
{
L* n = (L*)malloc(sizeof(L));
n->data = e;
if (lq->rear == NULL)
{
lq->front = n;
lq->rear = n;
}
else
{
lq->rear->next = n;
lq->rear=n;
lq->rear->next = NULL;
}
}
void show(LQ* lq)
{
L* list = lq->front;
while (list!=NULL)
{
printf("%d ",list->data);
list = list->next;
}
printf("\n");
}
void DeletElem(LQ* lq)
{
if (lq->front == NULL)
{
printf("队列为空!");
return;
}
L* n= lq->front;
lq->front = lq->front->next;
free(n);
}
int main()
{
LQ* lq = CreateLinkQueue();
for (int i = 0; i < 5; i++)
{
AddElem(lq, i);
}
show(lq);
for (int i = 0; i < 2; i++)
DeletElem(lq);
show(lq);
return 0;
} | [
"noreply@github.com"
] | mayali123.noreply@github.com |
038cad7ad9924622156a21541fefd3a9c3eaa8d7 | 6431762a17ab2f0f9e4bc41cd1f9837145687520 | /metadataGatherer/lowLevelTimer.cc | 80943858bde4322db699245a45028019d105ed64 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | minghao2016/KFF | 324d3751a0b290b0fe74c1c2db05fff55d21d788 | 609e5afac8a9477dd1af31eacadbcd5b61530113 | refs/heads/master | 2021-01-17T22:44:06.535735 | 2015-08-26T07:10:20 | 2015-08-26T07:10:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,039 | cc | #ifndef LOW_LEVEL_TIMER_CPP_INCLUDED
#define LOW_LEVEL_TIMER_CPP_INCLUDED
#ifdef _WIN32
#include <windows.h>
#elif __APPLE__
#include <mach/mach_time.h>
#endif
#include <lowLevelTimer.h>
namespace meta
{
LowLevelTimer::LowLevelTimer()
{
start();
}
void LowLevelTimer::start()
{
beginning = rdtsc();
beginningS = ( beginning + 0.0 ) * 1.0e-9;
running = true;
}
void LowLevelTimer::stop()
{
ending = rdtsc();
endingS = ( ending + 0.0 ) * 1.0e-9;
running = false;
}
LowLevelTimer::Cycle LowLevelTimer::cycles() const
{
if( running )
{
return ( rdtsc() - beginning );
}
else
{
return ( ending - beginning );
}
}
LowLevelTimer::Second LowLevelTimer::seconds() const
{
if( running )
{
return ( ( ( rdtsc() + 0.0 ) * 1.0e-9 ) - beginningS );
}
else
{
return endingS - beginningS;
}
}
LowLevelTimer::Second LowLevelTimer::absolute() const
{
if( running )
{
return ( ( ( rdtsc() + 0.0 ) * 1.0e-9 ) );
}
else
{
return endingS;
}
}
extern "C"
{
LowLevelTimer::Cycle LowLevelTimer::rdtsc()
{
#ifdef _WIN32
Cycle cycles = 0;
Cycle frequency = 0;
QueryPerformanceFrequency((LARGE_INTEGER*) &frequency);
QueryPerformanceCounter((LARGE_INTEGER*) &cycles);
return cycles / frequency;
#elif __APPLE__
uint64_t absolute_time = mach_absolute_time();
mach_timebase_info_data_t info = {0,0};
if (info.denom == 0) mach_timebase_info(&info);
uint64_t elapsednano = absolute_time * (info.numer / info.denom);
timespec spec;
spec.tv_sec = elapsednano * 1e-9;
spec.tv_nsec = elapsednano - (spec.tv_sec * 1e9);
return spec.tv_nsec + (Cycle)spec.tv_sec * 1e9;
#else
timespec spec;
clock_gettime( CLOCK_REALTIME, &spec );
return spec.tv_nsec + (Cycle)spec.tv_sec * 1e9;
#endif
}
}
}
#endif
| [
"mwhahibium@yahoo.com"
] | mwhahibium@yahoo.com |
f3bd4d74ba8b4bb330081843ccc2c1f1bf6ea46b | 86cf43b623ba45164d46d265f419cb4538b3a1d1 | /cat/tests/snsrgtwy/radio/messages/TestAttrMessage.cpp | 57f9c669088afc25a3fd3248b5b83b713777aa0c | [] | no_license | CentreForAlternativeTechnology/SensorGateway | d00bb897e53c291f44c2755a756c11163e2d377d | 3152381ed7b949a7f50d9b8c3c02dc0764c787a8 | refs/heads/master | 2021-01-01T19:38:21.240330 | 2015-05-20T09:23:37 | 2015-05-20T09:23:37 | 35,937,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,774 | cpp | #include <boost/test/unit_test.hpp>
#include <iostream>
#include <cat/snsrgtwy/radio/messages/EncryptedMessage.hpp>
#include <cat/snsrgtwy/radio/messages/AttrMessage.hpp>
#include <cat/snsrgtwy/radio/messages/CorruptMessageException.hpp>
namespace cat { namespace snsrgtwy { namespace radio { namespace messages {
class TestAttrMessage : public AttrMessage {
public:
TestAttrMessage(char message[]) : AttrMessage(message) {}
Data get_last() {
return this->get_last_data_item();
}
void decrypt_and_interpret() {
this->before_respond_to(HEADER);
}
};
BOOST_AUTO_TEST_SUITE(AttrMessageTestSuite)
BOOST_AUTO_TEST_CASE(should_match_raw_message) {
char attr_msg[] = {
0x0E, 0x00, /* Size (16 bytes) */
0x00, /* Status (OK) */
0x05, /* 5 Items */
/* Node ID */
0x05, /* unsigned short */
0xFF, 0xFF, /* 65535 */
/* Group ID */
0x05, /* unsigned short */
0x01, 0x00, /* 1 */
/* Attribute ID */
0x05, /* unsigned short */
0x0F, 0x0F, /* 3855 */
/* Attribute Number */
0x05, /* unsigned short */
0xF0, 0xF0, /* 61680 */
/* Attribute Value */
0x02, /* char */
0x55 /* 01010101 or 'U' in utf8 */
};
size_t size = sizeof(attr_msg);
char* attr_msg_encrypted = new char[size]();
memcpy(attr_msg_encrypted, attr_msg, size);
EncryptedMessage::convert_to_encrypted_message(
attr_msg_encrypted,
size,
SHARED_KEY
);
TestAttrMessage* m = new TestAttrMessage(attr_msg_encrypted);
m->decrypt_and_interpret();
BOOST_CHECK(m->get_node_id() == 0xFFFF);
BOOST_CHECK(m->get_group_id() == 0x0001);
BOOST_CHECK(m->get_attr_id() == 0x0F0F);
BOOST_CHECK(m->get_attr_number() == 0xF0F0);
BOOST_CHECK(m->get_last().signed_char == 0x55);
delete m;
}
BOOST_AUTO_TEST_CASE(should_catch_invalid_data_items) {
char invalid_data_items[] = {
0x00, 0x0A, /* Size (10 bytes) */
0x00, /* Status (OK) */
0x04, /* 4 items (5 expected) */
/* Node ID */
0x02, /* signed char (incorrect) */
'F',
/* Group ID */
0x02, /* signed char (incorrect) */
'A',
/* Attribute ID */
0x02, /* signed char (incorrect) */
'I',
/* Attribute Number */
0x02, /* signed char (incorrect) */
'L'
/* Missing Attribute Value */
};
TestAttrMessage* m = new TestAttrMessage(invalid_data_items);
BOOST_CHECK_THROW(m->interpret(), CorruptMessageException);
BOOST_CHECK_THROW(m->get_node_id(), CorruptMessageException);
BOOST_CHECK_THROW(m->get_group_id(), CorruptMessageException);
BOOST_CHECK_THROW(m->get_attr_id(), CorruptMessageException);
BOOST_CHECK_THROW(m->get_attr_number(), CorruptMessageException);
BOOST_CHECK_THROW(m->get_last(), CorruptMessageException);
delete m;
}
BOOST_AUTO_TEST_SUITE_END()
}}}}
| [
"jonty.newman@gmail.com"
] | jonty.newman@gmail.com |
953dabb11d06fbf5a92821db89c26424f1d30fe7 | 7e48d392300fbc123396c6a517dfe8ed1ea7179f | /RodentVR/Intermediate/Build/Win64/RodentVR/Shipping/Engine/Module.Engine.gen.4_of_65.cpp | e03768f4bc62644ab1fd86ad47df4c010c3214da | [] | no_license | WestRyanK/Rodent-VR | f4920071b716df6a006b15c132bc72d3b0cba002 | 2033946f197a07b8c851b9a5075f0cb276033af6 | refs/heads/master | 2021-06-14T18:33:22.141793 | 2020-10-27T03:25:33 | 2020-10-27T03:25:33 | 154,956,842 | 1 | 1 | null | 2018-11-29T09:56:21 | 2018-10-27T11:23:11 | C++ | UTF-8 | C++ | false | false | 3,202 | cpp | // This file is automatically generated at compile-time to include some subset of the user-created cpp files.
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimInstanceProxy.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimLayerInterface.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimLinkableElement.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimMetaData.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimMontage.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_ApplyMeshSpaceAdditive.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_AssetPlayerBase.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_CustomProperty.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_Inertialization.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_LinkedAnimGraph.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_LinkedAnimLayer.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_LinkedInputPose.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_Root.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_SaveCachedPose.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_SequencePlayer.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_StateMachine.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_TransitionPoseEvaluator.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_TransitionResult.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNode_UseCachedPose.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNodeBase.gen.cpp"
#include "C:/Users/Ryan/Drive/BYU/2018_Fall/cs_497r/Rodent-VR/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/AnimNodeSpaceConversions.gen.cpp"
| [
"west.ryan.k@gmail.com"
] | west.ryan.k@gmail.com |
7ba44607dbf9d626ad27b8ecb893a457420e0412 | 5145d166dbb699a8f75c4b9d9614002607ae0597 | /algos_semina/5th_seminar/seminar_1/2nd_grade/김윤서_minnie03/3649.cpp | fc04ae09dc72a0e55b5414185a7f795971988e73 | [] | no_license | Sookmyung-Algos/2021algos | 8cedfb92d8efaf4f6241dece5bc9b820fc5dc277 | be152912517558f0fc8685574064090e6c175065 | refs/heads/master | 2022-07-21T03:47:38.926142 | 2021-12-02T01:35:13 | 2021-12-02T01:35:13 | 341,102,594 | 11 | 46 | null | 2021-12-02T01:35:14 | 2021-02-22T06:32:53 | C++ | UTF-8 | C++ | false | false | 1,613 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int x;
while (cin >> x) {
int n;
cin >> n;
vector<int> blocks(n); // 레고조각의 수 n을 크기로하는 정수 벡터 blocks 생성
for (int i = 0; i < n; i++) { // 레고조각의 수만큼
cin >> blocks[i]; // 레고조각의 길이 입력
}
sort(blocks.begin(), blocks.end()); // 레고조각 작은 것부터 정렬
int flag = 0; // 막을 수 있는지 없는지 체크하는 변수
x *= 10000000; // 센티미터 단위를 나노미터 단위로 변환
for (int i = 0; i < n && blocks[i] <= x / 2; i++) {
int low = i + 1, high = n - 1;
// 이분탐색
while (low <= high) {
int mid = (low + high) / 2;
if (blocks[mid] + blocks[i] == x) { // 구멍에 넣을 두 조각의 길이의 합이 구멍의 너비와 일치한다면
flag = 1; // flag=1로 저장
cout << "yes " << blocks[i] << " " << blocks[mid] << "\n"; break;
}
else if (blocks[mid] + blocks[i] < x) { // 구멍의 너비보다 작다면
low = mid + 1; // 범위의 가장 작은 수를 중간+1 값으로 저장
}
else { // 구멍의 너비보다 크다면
high = mid - 1; // 범위의 가장 큰 수를 중간-1 값으로 저장
}
}
if (flag) { // 구멍을 완벽하게 막을 수 있다면
break; // 반복문 종료
}
}
if (flag == false) { // 구멍을 완벽하게 막을 수 없다면
cout << "danger\n"; // 'danger' 출력
}
}
return 0;
}
| [
"noreply@github.com"
] | Sookmyung-Algos.noreply@github.com |
f05fd005d2a391712d5d87ea0ed8a9a9501e0937 | c76adc973e5251452e1beb3de7776d0a2b709fce | /submissions/c2.s42.ncu100502507.ProblemA.cpp.0.Scanner.cpp | 739e17939caf6a357588ae35b783e03ff2b3099c | [] | no_license | ncuoolab/domjudge | 779a167f695f45a6a33437996ec5ad0f9d01c563 | bda18c69d418c829ff653f9183b3244520139f8a | refs/heads/master | 2020-05-19T08:10:39.974107 | 2015-03-10T19:35:03 | 2015-03-10T19:43:26 | 31,972,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 994 | cpp | #include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
enum type {ERR, ID, ASSIGN, INUM};
void proc(string);
void stmt(string);
void val();
int scannDigit(string);
int scannID(string);
int peek(string);
bool eof(string&);
void advance(string&);
struct token {
int type;
string val;
};
int main() {
string stream = "";
cout << "$ ";
getline(cin, stream);
cout << stream;
system("pause");
return 0;
}
void proc(string stream) {
}
void stmt(string stream) {
}
void val() {
}
int peek(string stream) {
char ch = stream.begin;
if (ch == '=') {
return ASSIGN;
}
else if (isdigit(ch)) {
return INUM;
}
else {
return ID;
}
}
void advance(string &stream) {
stream = stream.substr(1, stream.length-1);
}
bool eof(string &stream) {
if (stream == "") {
return true;
}
else {
return false;
}
}
int scannDigit(string stream) {
}
int scannID(string stream) {
} | [
"fntsrlike@gmail.com"
] | fntsrlike@gmail.com |
fa5ef74498b863d83a34ce82b3e522887fac50de | 410e45283cf691f932b07c5fdf18d8d8ac9b57c3 | /content/renderer/fetchers/resource_fetcher_impl.cc | f5bda17799c4d6f03466c1ceb005e5e08c18ee24 | [
"BSD-3-Clause"
] | permissive | yanhuashengdian/chrome_browser | f52a7f533a6b8417e19b85f765f43ea63307a1fb | 972d284a9ffa4b794f659f5acc4116087704394c | refs/heads/master | 2022-12-21T03:43:07.108853 | 2019-04-29T14:20:05 | 2019-04-29T14:20:05 | 184,068,841 | 0 | 2 | BSD-3-Clause | 2022-12-17T17:35:55 | 2019-04-29T12:40:27 | null | UTF-8 | C++ | false | false | 11,664 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/fetchers/resource_fetcher_impl.h"
#include <stdint.h>
#include <memory>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/single_thread_task_runner.h"
#include "content/public/common/referrer.h"
#include "content/public/renderer/render_frame.h"
#include "content/renderer/loader/resource_dispatcher.h"
#include "content/renderer/loader/web_url_request_util.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "net/base/net_errors.h"
#include "net/http/http_request_headers.h"
#include "net/url_request/url_request_context.h"
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/web_url_response.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame.h"
namespace {
constexpr int32_t kRoutingId = 0;
const char kAccessControlAllowOriginHeader[] = "Access-Control-Allow-Origin";
} // namespace
namespace content {
// static
std::unique_ptr<ResourceFetcher> ResourceFetcher::Create(const GURL& url) {
// Can not use std::make_unique<> because the constructor is private.
return std::unique_ptr<ResourceFetcher>(new ResourceFetcherImpl(url));
}
// TODO(toyoshim): Internal implementation might be replaced with
// SimpleURLLoader, and content::ResourceFetcher could be a thin-wrapper
// class to use SimpleURLLoader with blink-friendly types.
class ResourceFetcherImpl::ClientImpl : public network::mojom::URLLoaderClient {
public:
ClientImpl(ResourceFetcherImpl* parent,
Callback callback,
size_t maximum_download_size,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: parent_(parent),
client_binding_(this),
data_pipe_watcher_(FROM_HERE,
mojo::SimpleWatcher::ArmingPolicy::MANUAL,
std::move(task_runner)),
status_(Status::kNotStarted),
completed_(false),
maximum_download_size_(maximum_download_size),
callback_(std::move(callback)) {}
~ClientImpl() override {
callback_ = Callback();
Cancel();
}
void Start(const network::ResourceRequest& request,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const net::NetworkTrafficAnnotationTag& annotation_tag,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
status_ = Status::kStarted;
response_.SetCurrentRequestUrl(request.url);
network::mojom::URLLoaderClientPtr client;
client_binding_.Bind(mojo::MakeRequest(&client), std::move(task_runner));
url_loader_factory->CreateLoaderAndStart(
mojo::MakeRequest(&loader_), kRoutingId,
ResourceDispatcher::MakeRequestID(), network::mojom::kURLLoadOptionNone,
request, std::move(client),
net::MutableNetworkTrafficAnnotationTag(annotation_tag));
}
void Cancel() {
ClearReceivedDataToFail();
completed_ = true;
Close();
}
bool IsActive() const {
return status_ == Status::kStarted || status_ == Status::kFetching ||
status_ == Status::kClosed;
}
private:
enum class Status {
kNotStarted, // Initial state.
kStarted, // Start() is called, but data pipe is not ready yet.
kFetching, // Fetching via data pipe.
kClosed, // Data pipe is already closed, but may not be completed yet.
kCompleted, // Final state.
};
void MayComplete() {
DCHECK(IsActive()) << "status: " << static_cast<int>(status_);
DCHECK_NE(Status::kCompleted, status_);
if (status_ == Status::kFetching || !completed_)
return;
status_ = Status::kCompleted;
loader_.reset();
parent_->OnLoadComplete();
if (callback_.is_null())
return;
std::move(callback_).Run(response_, data_);
}
void ClearReceivedDataToFail() {
response_ = blink::WebURLResponse();
data_.clear();
}
void ReadDataPipe() {
DCHECK_EQ(Status::kFetching, status_);
for (;;) {
const void* data;
uint32_t size;
MojoResult result =
data_pipe_->BeginReadData(&data, &size, MOJO_READ_DATA_FLAG_NONE);
if (result == MOJO_RESULT_SHOULD_WAIT) {
data_pipe_watcher_.ArmOrNotify();
return;
}
if (result == MOJO_RESULT_FAILED_PRECONDITION) {
// Complete to read the data pipe successfully.
Close();
return;
}
DCHECK_EQ(MOJO_RESULT_OK, result); // Only program errors can fire.
if (data_.size() + size > maximum_download_size_) {
data_pipe_->EndReadData(size);
Cancel();
return;
}
data_.append(static_cast<const char*>(data), size);
result = data_pipe_->EndReadData(size);
DCHECK_EQ(MOJO_RESULT_OK, result); // Only program errors can fire.
}
}
void Close() {
if (status_ == Status::kFetching) {
data_pipe_watcher_.Cancel();
data_pipe_.reset();
}
status_ = Status::kClosed;
MayComplete();
}
void OnDataPipeSignaled(MojoResult result,
const mojo::HandleSignalsState& state) {
ReadDataPipe();
}
// network::mojom::URLLoaderClient overrides:
void OnReceiveResponse(
const network::ResourceResponseHead& response_head) override {
DCHECK_EQ(Status::kStarted, status_);
// Existing callers need URL and HTTP status code. URL is already set in
// Start().
if (response_head.headers)
response_.SetHttpStatusCode(response_head.headers->response_code());
}
void OnReceiveRedirect(
const net::RedirectInfo& redirect_info,
const network::ResourceResponseHead& response_head) override {
DCHECK_EQ(Status::kStarted, status_);
loader_->FollowRedirect({}, {}, base::nullopt);
response_.SetCurrentRequestUrl(redirect_info.new_url);
}
void OnUploadProgress(int64_t current_position,
int64_t total_size,
OnUploadProgressCallback ack_callback) override {}
void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override {}
void OnTransferSizeUpdated(int32_t transfer_size_diff) override {}
void OnStartLoadingResponseBody(
mojo::ScopedDataPipeConsumerHandle body) override {
DCHECK_EQ(Status::kStarted, status_);
status_ = Status::kFetching;
data_pipe_ = std::move(body);
data_pipe_watcher_.Watch(
data_pipe_.get(),
MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
MOJO_WATCH_CONDITION_SATISFIED,
base::BindRepeating(
&ResourceFetcherImpl::ClientImpl::OnDataPipeSignaled,
base::Unretained(this)));
ReadDataPipe();
}
void OnComplete(const network::URLLoaderCompletionStatus& status) override {
// When Cancel() sets |complete_|, OnComplete() may be called.
if (completed_)
return;
DCHECK(IsActive()) << "status: " << static_cast<int>(status_);
if (status.error_code != net::OK) {
ClearReceivedDataToFail();
Close();
}
completed_ = true;
MayComplete();
}
private:
ResourceFetcherImpl* parent_;
network::mojom::URLLoaderPtr loader_;
mojo::Binding<network::mojom::URLLoaderClient> client_binding_;
mojo::ScopedDataPipeConsumerHandle data_pipe_;
mojo::SimpleWatcher data_pipe_watcher_;
Status status_;
// A flag to represent if OnComplete() is already called. |data_pipe_| can be
// ready even after OnComplete() is called.
bool completed_;
// Maximum download size to be stored in |data_|.
const size_t maximum_download_size_;
// Received data to be passed to the |callback_|.
std::string data_;
// Response to be passed to the |callback_|.
blink::WebURLResponse response_;
// Callback when we're done.
Callback callback_;
DISALLOW_COPY_AND_ASSIGN(ClientImpl);
};
ResourceFetcherImpl::ResourceFetcherImpl(const GURL& url) {
DCHECK(url.is_valid());
request_.url = url;
}
ResourceFetcherImpl::~ResourceFetcherImpl() {
client_.reset();
}
void ResourceFetcherImpl::SetMethod(const std::string& method) {
DCHECK(!client_);
request_.method = method;
}
void ResourceFetcherImpl::SetBody(const std::string& body) {
DCHECK(!client_);
request_.request_body =
network::ResourceRequestBody::CreateFromBytes(body.data(), body.size());
}
void ResourceFetcherImpl::SetHeader(const std::string& header,
const std::string& value) {
DCHECK(!client_);
if (base::LowerCaseEqualsASCII(header, net::HttpRequestHeaders::kReferer)) {
request_.referrer = GURL(value);
DCHECK(request_.referrer.is_valid());
request_.referrer_policy = Referrer::GetDefaultReferrerPolicy();
} else {
request_.headers.SetHeader(header, value);
}
}
void ResourceFetcherImpl::SetFetchRequestMode(
network::mojom::FetchRequestMode fetch_request_mode) {
request_.fetch_request_mode = fetch_request_mode;
}
void ResourceFetcherImpl::Start(
blink::WebLocalFrame* frame,
blink::mojom::RequestContextType request_context,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const net::NetworkTrafficAnnotationTag& annotation_tag,
Callback callback,
size_t maximum_download_size) {
DCHECK(!client_);
DCHECK(frame);
DCHECK(url_loader_factory);
DCHECK(!frame->GetDocument().IsNull());
if (request_.method.empty())
request_.method = net::HttpRequestHeaders::kGetMethod;
if (request_.request_body) {
DCHECK(!base::LowerCaseEqualsASCII(request_.method,
net::HttpRequestHeaders::kGetMethod))
<< "GETs can't have bodies.";
}
request_.fetch_request_context_type = static_cast<int>(request_context);
request_.site_for_cookies = frame->GetDocument().SiteForCookies();
if (!frame->GetDocument().GetSecurityOrigin().IsNull()) {
request_.request_initiator =
static_cast<url::Origin>(frame->GetDocument().GetSecurityOrigin());
SetHeader(kAccessControlAllowOriginHeader,
blink::WebSecurityOrigin::CreateUnique().ToString().Ascii());
}
request_.resource_type = RequestContextToResourceType(request_context);
client_ = std::make_unique<ClientImpl>(
this, std::move(callback), maximum_download_size,
frame->GetTaskRunner(blink::TaskType::kNetworking));
// TODO(kinuko, toyoshim): This task runner should be given by the consumer
// of this class.
client_->Start(request_, std::move(url_loader_factory), annotation_tag,
frame->GetTaskRunner(blink::TaskType::kNetworking));
// No need to hold on to the request; reset it now.
request_ = network::ResourceRequest();
}
void ResourceFetcherImpl::SetTimeout(const base::TimeDelta& timeout) {
DCHECK(client_);
DCHECK(client_->IsActive());
DCHECK(!timeout_timer_.IsRunning());
timeout_timer_.Start(FROM_HERE, timeout, this,
&ResourceFetcherImpl::OnTimeout);
}
void ResourceFetcherImpl::OnLoadComplete() {
timeout_timer_.Stop();
}
void ResourceFetcherImpl::OnTimeout() {
DCHECK(client_);
DCHECK(client_->IsActive());
client_->Cancel();
}
} // namespace content
| [
"279687673@qq.com"
] | 279687673@qq.com |
8d6178e0353ded6cdd8df0f5c99c9cba5f476589 | 4da55187c399730f13c5705686f4b9af5d957a3f | /projects/robots/gctronic/e-puck/plugins/robot_windows/botstudio/core/TransitionRepresentation.cpp | caedd38fa4976c88c90f7cf3fba34e776d54c7eb | [
"Apache-2.0"
] | permissive | Ewenwan/webots | 7111c5587100cf35a9993ab923b39b9e364e680a | 6b7b773d20359a4bcf29ad07384c5cf4698d86d3 | refs/heads/master | 2020-04-17T00:23:54.404153 | 2019-01-16T13:58:12 | 2019-01-16T13:58:12 | 166,048,591 | 2 | 0 | Apache-2.0 | 2019-01-16T13:53:50 | 2019-01-16T13:53:50 | null | UTF-8 | C++ | false | false | 4,814 | cpp | // Copyright 1996-2018 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* Description: Implementation of the TransitionRepresentation.hpp functions
*/
#include "TransitionRepresentation.hpp"
#include "AutomatonScene.hpp"
#include "CommonProperties.hpp"
#include "State.hpp"
#include "StateRepresentation.hpp"
#include "Transition.hpp"
#include <QtCore/qmath.h>
#include <QtGui/QPainter>
#include <QtGui/QTextDocument>
#include <QtWidgets/QStyle>
#include <QtWidgets/QWidget>
static const int ROUNDED_RECT_RADIUS = 10;
static const double ARROW_LENGTH = 15.0;
static const double ARROW_ANGLE = 0.5;
static const double ARROW_PERCENTAGE = 1.0 / 4.0;
static const double PIVOT_PERCENTAGE = 1.5;
TransitionRepresentation::TransitionRepresentation(Transition *t) :
AutomatonObjectRepresentation(t),
mPathItem(NULL),
mAutomatonScene(NULL),
mStartState(NULL),
mEndState(NULL),
mIsInitialized(false) {
setZValue(2.0);
QFont f = font();
f.setPointSize(8);
setFont(f);
}
TransitionRepresentation::~TransitionRepresentation() {
if (mPathItem)
delete mPathItem;
}
// init should be called after the attachment of the object over the scene
void TransitionRepresentation::initialize() {
if (mIsInitialized)
return;
AutomatonObjectRepresentation::initialize();
mAutomatonScene = static_cast<AutomatonScene *>(scene());
mStartState = mAutomatonScene->findStateRepresentationFromState(transition()->startState());
mEndState = mAutomatonScene->findStateRepresentationFromState(transition()->endState());
if (!mStartState || !mEndState)
qFatal("Error on transition \"%s\": its start and/or end states are invalid",
transition()->name().toLocal8Bit().constData());
mPathItem = new QGraphicsPathItem;
mAutomatonScene->addItem(mPathItem);
connect(this, SIGNAL(positionChanged()), this, SLOT(updatePathItem()));
connect(document(), SIGNAL(contentsChanged()), this, SLOT(updatePathItem()));
connect(mStartState, SIGNAL(positionChanged()), this, SLOT(updatePathItem()));
connect(mEndState, SIGNAL(positionChanged()), this, SLOT(updatePathItem()));
connect(mStartState->document(), SIGNAL(contentsChanged()), this, SLOT(updatePathItem()));
connect(mEndState->document(), SIGNAL(contentsChanged()), this, SLOT(updatePathItem()));
mIsInitialized = true;
}
void TransitionRepresentation::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
painter->setPen(Qt::black);
QPainterPath path;
QColor color = CommonProperties::transitionColor();
if (isSelected())
color = CommonProperties::selectionColor();
if (!isEnabled())
color = widget->style()->standardPalette().color(QPalette::Window);
path.addRoundedRect(boundingRect(), ROUNDED_RECT_RADIUS, ROUNDED_RECT_RADIUS);
painter->fillPath(path, QBrush(color));
painter->drawPath(path);
AutomatonObjectRepresentation::paint(painter, option, widget);
}
Transition *TransitionRepresentation::transition() const {
return static_cast<Transition *>(automatonObject());
}
void TransitionRepresentation::updatePathItem() {
if (!mIsInitialized)
initialize();
// set the arrow bezier curve
QPainterPath path;
QPointF start(mStartState->computeCenter());
QPointF end(mEndState->computeCenter());
QPointF pivot(computeCenter());
QPointF statesCenter((start + end) / 2.0);
QLineF statesCenterToPivot(statesCenter, pivot);
QPointF extendedPivot(statesCenterToPivot.pointAt(PIVOT_PERCENTAGE));
path.moveTo(start);
path.cubicTo(extendedPivot, extendedPivot, end);
// compute the point where the arrow is (at a specific percentage of the bezier curve)
QPointF arrowCenter(path.pointAtPercent(ARROW_PERCENTAGE));
double angleAtArrowCenter = path.angleAtPercent(ARROW_PERCENTAGE) / 180.0 * M_PI - M_PI_2;
QPointF arrowExtremity1(qSin(angleAtArrowCenter + ARROW_ANGLE), qCos(angleAtArrowCenter + ARROW_ANGLE));
QPointF arrowExtremity2(qSin(angleAtArrowCenter - ARROW_ANGLE), qCos(angleAtArrowCenter - ARROW_ANGLE));
// set the arrow lines
path.moveTo(arrowCenter);
path.lineTo(arrowCenter + arrowExtremity1 * ARROW_LENGTH);
path.moveTo(arrowCenter);
path.lineTo(arrowCenter + arrowExtremity2 * ARROW_LENGTH);
// set the path to the QGraphicsPathItem
mPathItem->setPath(path);
}
| [
"David.Mansolino@cyberbotics.com"
] | David.Mansolino@cyberbotics.com |
2b5cb9b3becba423adc281b9257a9fd55d57e129 | 5a258d6ee19e0566c2911f8ad1d62a089f100407 | /Cirk_Per_Uni_v0.1/Cirk_Per_Uni_v0.1/Header17.h | d37727d3cefe5a0cea2a1247db2bad0cd8f96263 | [] | no_license | dulejuve/Cirk_Per_Uni | 9dae9721ceda9ec1283fc7ad17365a0b7e8e53bc | 2921c563d75f1085e155b433599ac74f4c3bb93a | refs/heads/master | 2021-01-10T12:20:32.349954 | 2016-04-14T12:20:50 | 2016-04-14T12:20:50 | 55,682,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,189 | h | #include <iostream>
//#define sizeSbox 256
//#define binary 9
#define NumMatrx17 17
int CirMat17[binary256][NumMatrx17], CirMatPer17[binary256][NumMatrx17];
int InvPerm17[sizeSbox256];
#include "SetCirMatPer17.h"
//int STT17[binary256][sizeSbox256];
//int STT117[binary256][sizeSbox256];
using namespace std;
//==================Function Set Matrix Circulant========================
void SetMatCir17()
{
int br = 0;
for (int i = 0; i<NumMatrx; i++)
{
for (int j = 1; j<binary; j++)
{
CirMat17[j][i] = CirMatAll[br];
//cout << CirMat[j][i] << " ";
br++;
}
}
cout << "\nPrint cyclic matrix:\n";
for (int i = 0; i<binary; i++)
{
for (int j = 0; j<NumMatrx; j++)
{
cout << CirMat17[i][j] << " ";
}
cout << "\n";
}
}
//=======================================================================
//Inverse STT, use inverse permutation array===========================
void InverzPer_Inv17()
{
for (int i = 1; i<binary; i++)
{
for (int j = 1; j<sizeSbox; j++)
{
STT1_256[i][InvPerm17[j]] = STT256[i][j];
// cout << InvPerm[j]<<" ";
}
// cout<<"\n";
}
// cout<<"Print Inverz Matrix\n";
for (int i = 0; i<binary; i++)
{
for (int j = 0; j<sizeSbox; j++)
{
STT256[i][j] = STT1_256[i][j];
}
}
}
//=======================================================================
//=======================================================================
void PrintSST17()
{
for (int j = 0; j<binary; j++)
{
for (int i = 0; i<sizeSbox; i++)
{
//cout << i <<":"<< STT[j][i] << " ";
cout << STT256[j][i] << " ";
}
cout << "\n";
}
}
//=======================================================================
//=======================================================================
void SetPerInvVect17()
{
//=======in order save binar representation of the matrix============
for (int y = 1; y<binary; y++)
{
int counterBin = (NumDigits*NumMatrx), binar;
for (int q = NumMatrx - 1; q >= 0; q--)
{
//CirMatPer[y][q]=CirMat[y][tvFix[q]-1];//CirMatPer[y][q]=CirMat[y][Per[q]-1];
CirMatPer17[y][q] = CirMat17[y][q];//CirMatPer[y][q]=CirMat[y][Per[q]-1];
for (int bin = 0; bin<NumDigits; bin++)
{
binar = 1 & (CirMatPer17[y][q] >> bin);
STT256[y][counterBin] = binar;
counterBin--;
}
}
}
//====================================================================
//************************Print the STT*******************************
cout << "\nPrint STT table:\n";
PrintSST17();
//********************************************************************
//========Convert binar to decimal and print==========================
cout << "\nPrint Invers Permutation element:\n";
for (int i = 0; i<sizeSbox; i++)
{
int decimal = 0, counterBin = 0, bin, sum = 0;
for (int j = binary - 1; j>0; j--)
{
//decimal=decimal+STT[j][i]<<j;
bin = STT256[j][i];
decimal = bin << counterBin;
//cout <<" "<< decimal << " ";
counterBin++;
sum = sum + decimal;
//cout << i <<":"<< STT[j][i] << " ";
}
cout << i << ":" << sum << ", ";
InvPerm17[i] = sum;
//cout << "\n";
}
//====================================================================
InverzPer_Inv17(); //Function set invers table
//************************Print the Invers STT************************
cout << "\n\nPrint STT Invers table:\n";
PrintSST17();
//********************************************************************
//********************Convert binar to decimal and print**************
//cout << "\nPrint Invers S-box:\n";
//
//for(int i = 0; i<sizeSbox; i++)
//{
// int decimal=0, counterBin=0, bin, sum=0;
// for(int j=binary-1; j>0; j--)
// {
// //decimal=decimal+STT[j][i]<<j;
// bin=STT[j][i];
// decimal=bin<<counterBin;
// //cout <<" "<< decimal << " ";
// counterBin++;
// sum=sum+decimal;
// //cout << i <<":"<< STT[j][i] << " ";
//
// }
// cout <<i<<":"<< sum << ", ";
// //SboxInv[i]=sum;
// //cout << "\n";
//}
//********************************************************************
}
void main17()
{
SetMatCir17(); // Function Set matrix circulante
SetPerInvVect17(); //Set Inversan Permutation
SetInputPar();
SetCirMatPer17();
EndOfProgram();
} | [
"dule.juve@gmai.com"
] | dule.juve@gmai.com |
d07aaa082d3053a937cb0b0108e40470e50043cd | 8c2b209d83d457eb0b55822d440007387f2d2a75 | /foundation/src/Thread_POSIX.cpp | b18876b1e249b79208ccb9a4bdf1eb110e3e1508 | [] | no_license | MayaPosch/Lucid | 491277fdd2edacb8469171292330853d51b35bc6 | 48e7563f59ba125e3d694976fc4d7a8fd47e66bc | refs/heads/master | 2022-09-07T08:03:40.387631 | 2020-06-01T15:33:42 | 2020-06-01T15:33:42 | 266,867,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,108 | cpp | //
// Thread_POSIX.cpp
//
// Library: Foundation
// Package: Threading
// Module: Thread
//
// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "lucid/Thread_POSIX.h"
#include "lucid/Thread.h"
#include "lucid/Exception.h"
#include "lucid/ErrorHandler.h"
#include "lucid/Timespan.h"
#include "lucid/Timestamp.h"
#include <signal.h>
#if defined(__sun) && defined(__SVR4)
# if !defined(__EXTENSIONS__)
# define __EXTENSIONS__
# endif
#endif
#if POCO_OS == POCO_OS_LINUX || POCO_OS == POCO_OS_ANDROID || POCO_OS == POCO_OS_MAC_OS_X || POCO_OS == POCO_OS_QNX
# include <time.h>
#endif
//
// Block SIGPIPE in main thread.
//
#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS)
namespace
{
class SignalBlocker
{
public:
SignalBlocker()
{
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &sset, 0);
}
~SignalBlocker()
{
}
};
static SignalBlocker signalBlocker;
}
#endif
#if defined(POCO_POSIX_DEBUGGER_THREAD_NAMES)
namespace {
void setThreadName(pthread_t thread, const std::string& threadName)
{
#if (POCO_OS == POCO_OS_MAC_OS_X)
pthread_setname_np(threadName.c_str()); // __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2)
#else
if (pthread_setname_np(thread, threadName.c_str()) == ERANGE && threadName.size() > 15)
{
std::string truncName(threadName, 0, 7);
truncName.append("~");
truncName.append(threadName, threadName.size() - 7, 7);
pthread_setname_np(thread, truncName.c_str());
}
#endif
}
}
#endif
namespace Lucid {
ThreadImpl::CurrentThreadHolder ThreadImpl::_currentThreadHolder;
ThreadImpl::ThreadImpl():
_pData(new ThreadData)
{
}
ThreadImpl::~ThreadImpl()
{
if (_pData->started && !_pData->joined)
{
pthread_detach(_pData->thread);
}
}
void ThreadImpl::setPriorityImpl(int prio)
{
if (prio != _pData->prio)
{
_pData->prio = prio;
_pData->policy = SCHED_OTHER;
if (isRunningImpl())
{
struct sched_param par; struct MyStruct
{
};
par.sched_priority = mapPrio(_pData->prio, SCHED_OTHER);
if (pthread_setschedparam(_pData->thread, SCHED_OTHER, &par))
throw SystemException("cannot set thread priority");
}
}
}
void ThreadImpl::setOSPriorityImpl(int prio, int policy)
{
if (prio != _pData->osPrio || policy != _pData->policy)
{
if (_pData->pRunnableTarget)
{
struct sched_param par;
par.sched_priority = prio;
if (pthread_setschedparam(_pData->thread, policy, &par))
throw SystemException("cannot set thread priority");
}
_pData->prio = reverseMapPrio(prio, policy);
_pData->osPrio = prio;
_pData->policy = policy;
}
}
int ThreadImpl::getMinOSPriorityImpl(int policy)
{
#if defined(POCO_THREAD_PRIORITY_MIN)
return POCO_THREAD_PRIORITY_MIN;
#elif defined(__digital__)
return PRI_OTHER_MIN;
#else
return sched_get_priority_min(policy);
#endif
}
int ThreadImpl::getMaxOSPriorityImpl(int policy)
{
#if defined(POCO_THREAD_PRIORITY_MAX)
return POCO_THREAD_PRIORITY_MAX;
#elif defined(__digital__)
return PRI_OTHER_MAX;
#else
return sched_get_priority_max(policy);
#endif
}
void ThreadImpl::setStackSizeImpl(int size)
{
#ifndef PTHREAD_STACK_MIN
_pData->stackSize = 0;
#else
if (size != 0)
{
#if defined(POCO_OS_FAMILY_BSD)
// we must round up to a multiple of the memory page size
const int STACK_PAGE_SIZE = 4096;
size = ((size + STACK_PAGE_SIZE - 1)/STACK_PAGE_SIZE)*STACK_PAGE_SIZE;
#endif
if (size < PTHREAD_STACK_MIN)
size = PTHREAD_STACK_MIN;
}
_pData->stackSize = size;
#endif
}
void ThreadImpl::startImpl(SharedPtr<Runnable> pTarget)
{
if (_pData->pRunnableTarget)
throw SystemException("thread already running");
pthread_attr_t attributes;
pthread_attr_init(&attributes);
if (_pData->stackSize != 0)
{
if (0 != pthread_attr_setstacksize(&attributes, _pData->stackSize))
{
pthread_attr_destroy(&attributes);
throw SystemException("cannot set thread stack size");
}
}
_pData->pRunnableTarget = pTarget;
if (pthread_create(&_pData->thread, &attributes, runnableEntry, this))
{
_pData->pRunnableTarget = 0;
pthread_attr_destroy(&attributes);
throw SystemException("cannot start thread");
}
_pData->started = true;
pthread_attr_destroy(&attributes);
if (_pData->policy == SCHED_OTHER)
{
if (_pData->prio != PRIO_NORMAL_IMPL)
{
struct sched_param par;
par.sched_priority = mapPrio(_pData->prio, SCHED_OTHER);
if (pthread_setschedparam(_pData->thread, SCHED_OTHER, &par))
throw SystemException("cannot set thread priority");
}
}
else
{
struct sched_param par;
par.sched_priority = _pData->osPrio;
if (pthread_setschedparam(_pData->thread, _pData->policy, &par))
throw SystemException("cannot set thread priority");
}
}
void ThreadImpl::joinImpl()
{
if (!_pData->started) return;
_pData->done.wait();
void* result;
if (pthread_join(_pData->thread, &result))
throw SystemException("cannot join thread");
_pData->joined = true;
}
bool ThreadImpl::joinImpl(long milliseconds)
{
if (_pData->started && _pData->done.tryWait(milliseconds))
{
void* result;
if (pthread_join(_pData->thread, &result))
throw SystemException("cannot join thread");
_pData->joined = true;
return true;
}
else if (_pData->started) return false;
else return true;
}
ThreadImpl* ThreadImpl::currentImpl()
{
return _currentThreadHolder.get();
}
ThreadImpl::TIDImpl ThreadImpl::currentTidImpl()
{
return pthread_self();
}
void ThreadImpl::sleepImpl(long milliseconds)
{
#if defined(__digital__)
// This is specific to DECThreads
struct timespec interval;
interval.tv_sec = milliseconds / 1000;
interval.tv_nsec = (milliseconds % 1000)*1000000;
pthread_delay_np(&interval);
#elif POCO_OS == POCO_OS_LINUX || POCO_OS == POCO_OS_ANDROID || POCO_OS == POCO_OS_MAC_OS_X || POCO_OS == POCO_OS_QNX || POCO_OS == POCO_OS_VXWORKS
Lucid::Timespan remainingTime(1000*Lucid::Timespan::TimeDiff(milliseconds));
int rc;
do
{
struct timespec ts;
ts.tv_sec = (long) remainingTime.totalSeconds();
ts.tv_nsec = (long) remainingTime.useconds()*1000;
Lucid::Timestamp start;
rc = ::nanosleep(&ts, 0);
if (rc < 0 && errno == EINTR)
{
Lucid::Timestamp end;
Lucid::Timespan waited = start.elapsed();
if (waited < remainingTime)
remainingTime -= waited;
else
remainingTime = 0;
}
}
while (remainingTime > 0 && rc < 0 && errno == EINTR);
if (rc < 0 && remainingTime > 0) throw Lucid::SystemException("Thread::sleep(): nanosleep() failed");
#else
Lucid::Timespan remainingTime(1000*Lucid::Timespan::TimeDiff(milliseconds));
int rc;
do
{
struct timeval tv;
tv.tv_sec = (long) remainingTime.totalSeconds();
tv.tv_usec = (long) remainingTime.useconds();
Lucid::Timestamp start;
rc = ::select(0, NULL, NULL, NULL, &tv);
if (rc < 0 && errno == EINTR)
{
Lucid::Timestamp end;
Lucid::Timespan waited = start.elapsed();
if (waited < remainingTime)
remainingTime -= waited;
else
remainingTime = 0;
}
}
while (remainingTime > 0 && rc < 0 && errno == EINTR);
if (rc < 0 && remainingTime > 0) throw Lucid::SystemException("Thread::sleep(): select() failed");
#endif
}
void* ThreadImpl::runnableEntry(void* pThread)
{
_currentThreadHolder.set(reinterpret_cast<ThreadImpl*>(pThread));
#if defined(POCO_OS_FAMILY_UNIX)
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset, SIGQUIT);
sigaddset(&sset, SIGTERM);
sigaddset(&sset, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &sset, 0);
#endif
ThreadImpl* pThreadImpl = reinterpret_cast<ThreadImpl*>(pThread);
#if defined(POCO_POSIX_DEBUGGER_THREAD_NAMES)
setThreadName(pThreadImpl->_pData->thread, reinterpret_cast<Thread*>(pThread)->getName());
#endif
AutoPtr<ThreadData> pData = pThreadImpl->_pData;
try
{
pData->pRunnableTarget->run();
}
catch (Exception& exc)
{
ErrorHandler::handle(exc);
}
catch (std::exception& exc)
{
ErrorHandler::handle(exc);
}
catch (...)
{
ErrorHandler::handle();
}
pData->pRunnableTarget = 0;
pData->done.set();
return 0;
}
int ThreadImpl::mapPrio(int prio, int policy)
{
int pmin = getMinOSPriorityImpl(policy);
int pmax = getMaxOSPriorityImpl(policy);
switch (prio)
{
case PRIO_LOWEST_IMPL:
return pmin;
case PRIO_LOW_IMPL:
return pmin + (pmax - pmin)/4;
case PRIO_NORMAL_IMPL:
return pmin + (pmax - pmin)/2;
case PRIO_HIGH_IMPL:
return pmin + 3*(pmax - pmin)/4;
case PRIO_HIGHEST_IMPL:
return pmax;
default:
poco_bugcheck_msg("invalid thread priority");
}
return -1; // just to satisfy compiler - we'll never get here anyway
}
int ThreadImpl::reverseMapPrio(int prio, int policy)
{
if (policy == SCHED_OTHER)
{
int pmin = getMinOSPriorityImpl(policy);
int pmax = getMaxOSPriorityImpl(policy);
int normal = pmin + (pmax - pmin)/2;
if (prio == pmax)
return PRIO_HIGHEST_IMPL;
if (prio > normal)
return PRIO_HIGH_IMPL;
else if (prio == normal)
return PRIO_NORMAL_IMPL;
else if (prio > pmin)
return PRIO_LOW_IMPL;
else
return PRIO_LOWEST_IMPL;
}
else return PRIO_HIGHEST_IMPL;
}
} // namespace Lucid
| [
"maya@nyanko.ws"
] | maya@nyanko.ws |
512ecd6b7d08a9f287af2693f77cf7f616d2bfb3 | 15c086a39bcc075bfbcbdb814b1fe5480fd126df | /project/arduino/HomeNodeController/EncodeNSendMessage.h | 8640c206fb97aee23d0993d502ef1d32056b826a | [] | no_license | youkkwon/smarthome | 78960b9fcd114a988793e787c0500058e5dc3134 | a2342761e75d6b48afb327ae515a43799b58c1e8 | refs/heads/master | 2021-01-10T01:08:40.726332 | 2015-09-04T04:46:29 | 2015-09-04T04:46:29 | 36,963,274 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 709 | h |
#ifndef EncodNSendMessage_h
#define EncodNSendMessage_h
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <SPI.h>
#include <WiFi.h>
#include "HomeNodeDDI.h" // Note that the DHT file must be in your Arduino installation folder, in the library foler.
class EncodeNSendMessage
{
public :
void SendJSONobject(char *, char *, bool);
void SendJSONdiscoverRegister(WiFiClient , bool, String);
void SendJSONstatusEvent(WiFiClient, String, HomeNodeDDI);
void SendJSONnotAuthorizedEvent(WiFiClient, String);
void SendJSONMsgErrEvent(WiFiClient, String);
private :
//void SendJSONThing(WiFiClient, char *, int);
};
#endif
| [
"carrot205@naver.com"
] | carrot205@naver.com |
29e5f9cbe5c1584264e5eee942097ed73cf92ab8 | 174413d04cd4c75e843f1a325732a64d7cf1a69a | /plugins/dispvaluesplugin/src/dispval.cpp | 997a51177dfbdc601e3618f2ba7458559cb196d1 | [] | no_license | mysmartgrid/chumby-controlpanel | f0a0f8683a1b1227b86c76d274ea2c32d7657cbc | b02135ee36d3943b89d117d8ba4151153a23973d | refs/heads/master | 2021-01-22T23:37:06.116170 | 2012-09-21T12:07:01 | 2012-09-21T12:07:01 | 3,144,299 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,922 | cpp | #include "dispval.h"
#include <QObject>
Msg::DisplayPage::DisplayPage ( QWidget* parent ) : QWidget ( parent )
{
digitalClk = new QLCDNumber ();
digitalClk->setSegmentStyle ( QLCDNumber::Filled );
digitalClk->setFrameStyle ( QFrame::StyledPanel | QFrame::Plain );
digitalClk->setMaximumSize ( 220, 32 );
digitalClk->setMinimumSize ( 190, 30 );
digitalClk->setDigitCount ( 8 );
digitalClk->display ( "00:00:00" );
QLabel* clkLabel = new QLabel ( "<span style='font-size:16pt;'>Time</span>" );
clkLabel->setTextFormat ( Qt::RichText );
clkLabel->setFrameStyle ( QFrame::StyledPanel | QFrame::Plain );
QHBoxLayout* clkLayout = new QHBoxLayout();
clkLayout->addWidget ( clkLabel );
clkLayout->addWidget ( digitalClk );
sensorval = new QLCDNumber ();
sensorval->setSegmentStyle ( QLCDNumber::Filled );
sensorval->setFrameStyle ( QFrame::StyledPanel | QFrame::Plain );
sensorval->setMinimumSize ( 190, 75 );
sensorval->setMaximumSize ( 200, 80 );
QLabel* sensorLabel = new QLabel ( "<span style='font-size:16pt;'>Consumption</span><br><span style='font-size:12pt;'>Watt</span>" );
sensorLabel->setTextFormat ( Qt::RichText );
sensorLabel->setFrameStyle ( QFrame::StyledPanel | QFrame::Plain );
QHBoxLayout* sensorLayout = new QHBoxLayout();
sensorLayout->addWidget ( sensorLabel );
sensorLayout->addWidget ( sensorval );
QGridLayout* avgLayout = new QGridLayout();
QLabel* avgLabel1 = new QLabel ( tr ( "avg.(1m)" ) );
QLabel* avgLabel2 = new QLabel ( tr ( "avg.(15m)" ) );
avgLabel1->setFrameStyle ( QFrame::StyledPanel | QFrame::Plain );
avgLabel2->setFrameStyle ( QFrame::StyledPanel | QFrame::Plain );
avgLabel1->setAlignment ( Qt::AlignRight );
avgLabel2->setAlignment ( Qt::AlignRight );
avgLabel1->setMaximumSize ( 150, 20 );
avgLabel2->setMaximumSize ( 150, 20 );
avgval1 = new QLCDNumber ();
avgval2 = new QLCDNumber ();
avgval1->display ( "---" );
avgval2->display ( "---" );
avgval1->setSegmentStyle ( QLCDNumber::Filled );
avgval1->setFrameStyle ( QFrame::StyledPanel | QFrame::Plain );
avgval2->setSegmentStyle ( QLCDNumber::Filled );
avgval2->setFrameStyle ( QFrame::StyledPanel | QFrame::Plain );
avgLayout->addWidget ( avgLabel1, 0, 0, 1, 1 );
avgLayout->addWidget ( avgLabel2, 0, 1, 1, 1 );
avgLayout->addWidget ( avgval1, 1, 0, 1, 1 );
avgLayout->addWidget ( avgval2, 1, 1, 1, 1 );
avgLayout->setSpacing ( 1 );
QVBoxLayout* layout = new QVBoxLayout ( this );
layout->addLayout ( clkLayout );
layout->addLayout ( sensorLayout );
layout->addLayout ( avgLayout );
layout->setContentsMargins ( 0, 0, 0, 0 );
layout->setSpacing ( 4 );
valueiter = 0;
lastval = 0;
}
Msg::URLPage::URLPage ( QWidget* parent ) : QWidget ( parent )
{
//QSettings settings ( "flukso.conf", QSettings::IniFormat );
//QSettings settings ( "/mnt/usb/displayvalues/flukso.conf", QSettings::IniFormat );
QSettings settings ( "/mnt/usb/flukso.conf", QSettings::IniFormat );
QLabel* urlLabel = new QLabel ( tr ( "Flukso IP:Port" ) );
//urlLineEdit = new QLineEdit ( "131.246.191.27:8080" );
//urlLineEdit = new QLineEdit ( "192.168.130.21:8080" );
urlLineEdit = new QLineEdit ( settings.value ( "ip" ).toString() + ":" + settings.value ( "port" ).toString() );
QLabel* sensorLabel = new QLabel ( tr ( "Sensors:" ) );
sensorLabel1 = new QLabel ( settings.value ( "sensor1" ).toString() );
sensorLabel2 = new QLabel ( settings.value ( "sensor2" ).toString() );
sensorLabel3 = new QLabel ( settings.value ( "sensor3" ).toString() );
sen1 = new QPushButton ( "Enable" );
sen2 = new QPushButton ( "Enable" );
sen3 = new QPushButton ( "Enable" );
sen1->setCheckable ( true );
sen2->setCheckable ( true );
sen3->setCheckable ( true );
sen1->setMaximumWidth ( 54 );
sen2->setMaximumWidth ( 54 );
sen3->setMaximumWidth ( 54 );
if ( settings.value ( "sen1ena" ).toInt() == 1 ) {
sen1->setChecked ( true );
sen1->setText ( "Disable" );
}
if ( settings.value ( "sen2ena" ).toInt() == 1 ) {
sen2->setChecked ( true );
sen2->setText ( "Disable" );
}
if ( settings.value ( "sen3ena" ).toInt() == 1 ) {
sen3->setChecked ( true );
sen3->setText ( "Disable" );
}
QHBoxLayout* topLayout = new QHBoxLayout;
topLayout->addWidget ( urlLabel );
topLayout->addWidget ( urlLineEdit );
QHBoxLayout* topLayout_s1 = new QHBoxLayout;
//topLayout_s1->addWidget ( sensorLineEdit1 );
topLayout_s1->addWidget ( sensorLabel1 );
topLayout_s1->addWidget ( sen1 );
QHBoxLayout* topLayout_s2 = new QHBoxLayout;
//topLayout_s2->addWidget ( sensorLineEdit2 );
topLayout_s2->addWidget ( sensorLabel2 );
topLayout_s2->addWidget ( sen2 );
QHBoxLayout* topLayout_s3 = new QHBoxLayout;
//topLayout_s3->addWidget ( sensorLineEdit3 );
topLayout_s3->addWidget ( sensorLabel3 );
topLayout_s3->addWidget ( sen3 );
QVBoxLayout* topLayout2 = new QVBoxLayout;
topLayout2->addWidget ( sensorLabel );
topLayout2->addLayout ( topLayout_s1 );
topLayout2->addLayout ( topLayout_s2 );
topLayout2->addLayout ( topLayout_s3 );
statusLabel = new QLabel ( tr ( "Status: ----" ) );
debugLabel = new QLabel ( tr ( "Mapsize: ----" ) );
QLabel* info = new QLabel ( tr ( "Settings / Debug " ) );
QVBoxLayout* layout = new QVBoxLayout ( this );
layout->addWidget ( info );
layout->addStretch();
layout->addLayout ( topLayout );
layout->addLayout ( topLayout2 );
//layout->addStretch();
layout->addWidget ( statusLabel );
layout->addWidget ( debugLabel );
layout->addStretch();
layout->setContentsMargins ( 0, 0, 0, 0 );
layout->setSpacing ( 5 );
connect ( sen1, SIGNAL ( toggled ( bool ) ), this, SLOT ( buttonToggled ( bool ) ) );
connect ( sen2, SIGNAL ( toggled ( bool ) ), this, SLOT ( buttonToggled ( bool ) ) );
connect ( sen3, SIGNAL ( toggled ( bool ) ), this, SLOT ( buttonToggled ( bool ) ) );
}
void Msg::URLPage::buttonToggled ( bool checked )
{
QPushButton* button = ( QPushButton* ) sender();
button->setText ( ( checked ) ? QString ( "Disable" ) : QString ( "Enable" ) );
}
Msg::PlotPage::PlotPage ( QWidget* parent ) : QWidget ( parent )
{
QVBoxLayout* layout = new QVBoxLayout ( this );
plotter = new Plotter ( this );
TimeConverter_s* tc = new Msg::TimeConverter_s(); //create a new converter object...
plotter->setConverter ( tc ); //override the default "do-nothing"-converter
layout->addWidget ( plotter );
layout->setContentsMargins ( 0, 0, 0, 0 );
layout->setSpacing ( 5 );
}
Msg::VisPage::VisPage ( QWidget* parent ) : QWidget ( parent )
{
QVBoxLayout* layout = new QVBoxLayout ( this );
tacho = new Tacho ( this );
layout->addWidget ( tacho );
layout->setContentsMargins ( 0, 0, 0, 0 );
layout->setSpacing ( 5 );
}
Msg::Display::Display() : QDialog()
{
startButton = new QPushButton ( tr ( "Start" ) );
startButton->setDefault ( true );
quitButton = new QPushButton ( tr ( "Quit" ) );
quitButton->setAutoDefault ( false );
previous = new QPushButton ( tr ( "< Numbers" ) );
next = new QPushButton ( tr ( "Plot >" ) );
previous->setEnabled ( false );
QHBoxLayout* mainbuttonBox = new QHBoxLayout();
mainbuttonBox->addWidget ( startButton );
mainbuttonBox->addWidget ( previous );
mainbuttonBox->addWidget ( next );
mainbuttonBox->addWidget ( quitButton );
mainbuttonBox->setContentsMargins ( 0, 0, 0, 0 );
mainbuttonBox->setSpacing ( 5 );
pages = new QStackedWidget ( this );
pages->addWidget ( displayPg = new DisplayPage ( pages ) ); // index 0
pages->addWidget ( plotPg = new PlotPage ( pages ) ); // index 1
pages->addWidget ( visPg = new VisPage ( pages ) ); // index 2
pages->addWidget ( urlPg = new URLPage ( pages ) ); // index 3
QVBoxLayout* mainlayout = new QVBoxLayout ( this );
mainlayout->addWidget ( pages );
mainlayout->addLayout ( mainbuttonBox );
mainlayout->setContentsMargins ( 5, 10, 5, 8 );
mainlayout->setSpacing ( 6 );
connect ( next, SIGNAL ( clicked() ), this, SLOT ( doNext() ) );
connect ( previous, SIGNAL ( clicked() ), this, SLOT ( doPrev() ) );
connect ( startButton, SIGNAL ( clicked() ), this, SLOT ( startDisp() ) );
connect ( quitButton, SIGNAL ( clicked() ), this, SLOT ( close() ) );
connect ( urlPg->urlLineEdit, SIGNAL ( textChanged ( QString ) ), this, SLOT ( enablestartButton() ) );
curtimestamp = 0; //variable for the latest timestamp (for further use)
valinterval = 2; //timeinterval (sec) for updating the numerical consumption display
fetchinterval = 4; //timeinterval (sec) for fetching sensordate from a flukso device
dlcounter = 0; //counter for debug purposes
currentsensors = 1; //on app start only one sensor is enabled by default....
int plotdelay = 1; // delay on plotter updating (see httpReadyRead() method for details)
tfetch = new QTimer();
tshow = new QTimer();
tplot = new QTimer();
tfetch->setInterval ( 1000 * fetchinterval );
tshow->setInterval ( 1000 * valinterval );
tplot->setInterval ( 1000 * plotdelay );
map1 = new QMap<uint, uint>();
map2 = new QMap<uint, uint>();
map3 = new QMap<uint, uint>();
connect ( tshow, SIGNAL ( timeout() ), this, SLOT ( showCurrentVal_alt() ) );
connect ( tfetch, SIGNAL ( timeout() ), this, SLOT ( getAllSensors_new() ) );
connect ( tplot, SIGNAL ( timeout() ), this, SLOT ( updatePlotter() ) );
finishedMapper = new QSignalMapper ( this );
readyreadMapper = new QSignalMapper ( this );
errMapper = new QSignalMapper ( this );
connect ( finishedMapper, SIGNAL ( mapped ( QObject* ) ), this, SLOT ( httpFinished ( QObject* ) ) );
connect ( readyreadMapper, SIGNAL ( mapped ( QObject* ) ), this, SLOT ( httpReadyRead ( QObject* ) ) );
connect ( errMapper, SIGNAL ( mapped ( QObject* ) ), this, SLOT ( sensorErr ( QObject* ) ) );
connect ( urlPg->sen1, SIGNAL ( toggled ( bool ) ), this, SLOT ( buttonToggled_gatekeeper ( bool ) ) );
connect ( urlPg->sen2, SIGNAL ( toggled ( bool ) ), this, SLOT ( buttonToggled_gatekeeper ( bool ) ) );
connect ( urlPg->sen3, SIGNAL ( toggled ( bool ) ), this, SLOT ( buttonToggled_gatekeeper ( bool ) ) );
qDebug() << "created..";
checkSettings();
}
//performs a quick check at app-start; if the flukso device specified in "flukso.conf" with
//it's first sensor is reachable or not
void Msg::Display::checkSettings()
{
if ( QFile::exists ( "/mnt/usb/flukso.conf" ) ) {
QSettings settings ( "/mnt/usb/flukso.conf", QSettings::IniFormat );
QString ipport ( settings.value ( "ip" ).toString() + ":" + settings.value ( "port" ).toString() );
QString sen ( settings.value ( "sensor1" ).toString() );
QNetworkRequest req ( QUrl ( "http://" + ipport + QString ( "/sensor/%1?unit=watt&interval=minute&version=1.0" ).arg ( sen ) ) );
qDebug() << "---checker-->" << req.url().toString();
QNetworkAccessManager* manager = new QNetworkAccessManager ( this );
manager->get ( req );
connect ( manager, SIGNAL ( finished ( QNetworkReply* ) ), this, SLOT ( checkSettingsStatus ( QNetworkReply* ) ) );
} else {
qDebug() << "could not find the flukso configuration file...";
QMessageBox* msgBox = new QMessageBox ( QMessageBox::Critical, "Configuration Error", "Couldn't find the configuration file!", QMessageBox::Ok , this, Qt::Dialog | Qt::CustomizeWindowHint );
msgBox->move ( 0, 1 );
msgBox->exec();
}
}
//evaluates the result of the networking check at the start..
void Msg::Display::checkSettingsStatus ( QNetworkReply* rep )
{
if ( rep->error() == QNetworkReply::NoError ) {
qDebug() << "-out-->" << rep->readAll();
rep->deleteLater();
startDisp();
} else {
qDebug() << QString ( "there was a problem downloading %1 data!" ).arg ( rep->url().toString() );
qDebug() << "error was: " << rep->errorString();
QMessageBox* msgBox = new QMessageBox ( QMessageBox::Critical, "Connection Error", "Couldn't reach the Flukso device. Check your Settings!", QMessageBox::Abort | QMessageBox::Retry, this, Qt::Dialog | Qt::CustomizeWindowHint );
msgBox->layout()->setContentsMargins ( 5, 6, 5, 6 );
msgBox->layout()->setSpacing ( 8 );
msgBox->move ( 0, 1 );
msgBox->setDetailedText ( ( QString ( "Sensor URL: %1\nError: %2" ).arg ( rep->url().toString() ).arg ( rep->errorString() ) ).remove ( "?unit=watt&interval=minute&version=1.0" , Qt::CaseInsensitive ) );
int ret = msgBox->exec();
if ( ret == QMessageBox::Abort ) {
rep->deleteLater();
close();
} else if ( ret == QMessageBox::Retry ) {
rep->deleteLater();
checkSettings();
}
//QMessageBox* msgBox = new QMessageBox ( QMessageBox::Critical, "Connection Error" , "Couldn't reach the Flukso device. Check your Settings!", QMessageBox::Ok | QMessageBox::Retry , this, Qt::Dialog | Qt::CustomizeWindowHint );
//msgBox->exec();
}
//rep->deleteLater();
}
void Msg::Display::buttonToggled_gatekeeper ( bool checked )
{
( checked ) ? currentsensors++ : currentsensors--;
qDebug() << "sensors enabled: " << currentsensors;
if ( !urlPg->sen1->isChecked() ) {
map1->clear();
qDebug() << "sensor1 data (map1) cleared!";
}
if ( !urlPg->sen2->isChecked() ) {
map2->clear();
qDebug() << "sensor2 data (map1) cleared!";
}
if ( !urlPg->sen3->isChecked() ) {
map3->clear();
qDebug() << "sensor3 data (map1) cleared!";
}
}
void Msg::Display::updatePlotter()
{
//qDebug() << "plotupdate triggered..";
tplot->stop();
plotData_new ( plotPg->plotter );
showAvg();
}
void Msg::Display::doNext() // TODO: refactor button functions!
{
switch ( pages->currentIndex() ) {
case 0: //displayPg
pages->setCurrentWidget ( plotPg );
previous->setText ( tr ( "< Numbers" ) );
previous->setEnabled ( true );
next->setText ( tr ( "Visual >" ) );
break;
case 1: //plotPg
pages->setCurrentWidget ( visPg );
previous->setText ( tr ( "< Plot" ) );
next->setText ( tr ( "Settings >" ) );
break;
case 2: //visPg
pages->setCurrentWidget ( urlPg );
previous->setText ( tr ( "< Visual" ) );
next->setText ( tr ( "Settings >" ) );
next->setEnabled ( false );
break;
}
}
void Msg::Display::doPrev()
{
switch ( pages->currentIndex() ) {
case 1: //plotPg
pages->setCurrentWidget ( displayPg );
previous->setEnabled ( false );
previous->setText ( tr ( "< Numbers" ) );
next->setText ( tr ( "Plot >" ) );
break;
case 2: //visPg
pages->setCurrentWidget ( plotPg );
previous->setText ( tr ( "< Numbers" ) );
next->setText ( tr ( "Visual >" ) );
break;
case 3: //urlPg
pages->setCurrentWidget ( visPg );
previous->setText ( tr ( "< Plot" ) );
next->setEnabled ( true );
next->setText ( tr ( "Settings >" ) );
break;
}
}
void Msg::Display::enablestartButton()
{
startButton->setEnabled ( !urlPg->urlLineEdit->text().isEmpty() );
}
void Msg::Display::startDisp()
{
if ( tshow->isActive() || tfetch->isActive() ) {
qDebug() << "stoping...";
tfetch->stop();
tshow->stop();
qDebug() << "timer stoped.";
dlcounter = 0;
map1->clear();
map2->clear();
map3->clear();
startButton->setText ( tr ( "Start" ) );
urlPg->statusLabel->setText ( tr ( "Stopped" ) );
} else {
qDebug() << "starting...";
getAllSensors_new();
tfetch->start();
tshow->start();
qDebug() << "timer started...";
startButton->setText ( tr ( "Stop" ) );
}
}
void Msg::Display::getSensor ( QNetworkReply*& replyn, QString sensortoken, QString sensormarker )
{
QString sensortxt = "/sensor/%1?unit=watt&interval=minute&version=1.0";
QNetworkRequest req ( QUrl ( "http://" + urlPg->urlLineEdit->text() + sensortxt.arg ( sensortoken ) ) );
req.setAttribute ( QNetworkRequest::User, QString ( sensormarker ) );
replyn = qnam.get ( req ); //store reply in a QNetworkReply object
finishedMapper->setMapping ( replyn, qobject_cast<QObject*> ( replyn ) );
readyreadMapper->setMapping ( replyn, qobject_cast<QObject*> ( replyn ) );
errMapper->setMapping ( replyn, qobject_cast<QObject*> ( replyn ) );
connect ( replyn, SIGNAL ( finished() ), finishedMapper, SLOT ( map() ) );
connect ( replyn, SIGNAL ( readyRead() ), readyreadMapper, SLOT ( map() ) );
connect ( replyn, SIGNAL ( error ( QNetworkReply::NetworkError ) ), errMapper, SLOT ( map() ) );
}
void Msg::Display::getAllSensors_new()
{
if ( !urlPg->sensorLabel1->text().isEmpty() && urlPg->sen1->isChecked() ) {
getSensor ( reply1 , urlPg->sensorLabel1->text(), "sensor1" );
}
if ( !urlPg->sensorLabel2->text().isEmpty() && urlPg->sen2->isChecked() ) {
getSensor ( reply2 , urlPg->sensorLabel2->text(), "sensor2" );
}
if ( !urlPg->sensorLabel3->text().isEmpty() && urlPg->sen3->isChecked() ) {
getSensor ( reply3 , urlPg->sensorLabel3->text(), "sensor3" );
}
}
void Msg::Display::httpFinished ( QObject* repn )
{
QNetworkReply* replyn = qobject_cast<QNetworkReply*> ( repn );
if ( replyn->error() ) {
qDebug() << QString ( tr ( "Sensordata (%1) Download failed: %2" ).arg ( replyn->request().attribute ( QNetworkRequest::User ).toString() ).arg ( replyn->errorString() ) );
} else {
dlcounter += 1;
urlPg->statusLabel->setText ( tr ( "Sensordata downloaded! (count: %1)" ).arg ( dlcounter ) );
}
replyn->deleteLater();
replyn = 0;
}
// this slot is only triggered when QNetworkReply has new data available,
// not when the finished() signal is emmited - this way we use less RAM
void Msg::Display::httpReadyRead ( QObject* repn )
{
QNetworkReply* replyn = qobject_cast<QNetworkReply*> ( repn );
//trigger a plot delay timer; if there is another sensor readout while the
//timer is running, the plot update will be delayed again (timer restart).
//when a timeout occurs, meaning there was no sensor readout during the delay,
//the plot will be updated and averages recalculated. this way the peak cpu
//usage on the chumby is reduced..
tplot->start();
QByteArray result;
result = replyn->readAll();
QString sensormark ( replyn->request().attribute ( QNetworkRequest::User ).toString() );
//qDebug() << "req user data: " << sensormark;
QMap<uint, uint>* map = 0;
//depending on which sensordata was requested, the "output" map is switched...
if ( sensormark == QString ( "sensor1" ) ) {
map = map1;
} else if ( sensormark == QString ( "sensor2" ) ) {
map = map2;
} else if ( sensormark == QString ( "sensor3" ) ) {
map = map3;
}
bool ok;
QVariantList json = QtJson::Json::parse ( QString ( result ), ok ).toList();
if ( !ok ) {
qFatal ( "An error occurred during parsing" );
} else {
if ( json.isEmpty() ) {
qDebug() << "json data is empty!";
}
foreach ( QVariant data, json ) {
if ( data.toList().value ( 1 ).toString() != "nan" ) {
map->insert ( data.toList().value ( 0 ).toUInt(), data.toList().value ( 1 ).toUInt() );
} else {
map->insert ( data.toList().value ( 0 ).toUInt(), ( map->end() - 1 ).value() );
//map->insert ( data.toList().value ( 0 ).toUInt(), map->value( data.toList().value ( 0 ).toUInt() - 1 ) ); //alternative
//map->insert ( data.toList().value ( 0 ).toUInt(), 0 ); //alternative2
//qDebug() << "zero/nan value found!-> dupe inserted - map size was: " << map->size() << "for " << sensormark;
}
//qDebug() << data.toList().value(1).toString();
}
if ( map->size() > 2100 ) {
QMap<uint, uint>::iterator i = map->begin();
while ( i != map->end() - 1801 ) {
i = map->erase ( i );
}
qDebug() << sensormark << "data map size was cut down! new size: " << map->size();
}
urlPg->debugLabel->setText ( tr ( "Map sizes: %1 | %2 | %3" ).arg ( map1->size() ).arg ( map2->size() ).arg ( map3->size() ) );
}
}
void Msg::Display::plotData_new ( Plotter* plotter )
{
int plotlen = 900; //TODO: make plot length method parameter, thus variable
bool s1 = urlPg->sen1->isChecked();
bool s2 = urlPg->sen1->isChecked();
bool s3 = urlPg->sen1->isChecked();
if ( plotlen > 240 ) {
TimeConverter_m* tc = new Msg::TimeConverter_m();
plotPg->plotter->setConverter ( tc );
}
uint minx = 0;
uint maxx = 0;
uint miny = 0;
uint maxy = 0;
uint maxx1 = ( s1 && !map1->isEmpty() ) ? ( map1->end() - 1 ).key() : 0;
uint maxx2 = ( s2 && !map2->isEmpty() ) ? ( map2->end() - 1 ).key() : 0;
uint maxx3 = ( s3 && !map3->isEmpty() ) ? ( map3->end() - 1 ).key() : 0;
if ( maxx1 >= maxx2 && maxx1 >= maxx3 ) {
maxx = maxx1;
minx = ( ( map1->begin() ).key() ) - ( plotlen - map1->size() );
miny = ( map1->end() - 1 ).value();
} else if ( maxx2 >= maxx1 && maxx2 >= maxx3 ) {
maxx = maxx2;
minx = ( ( map2->begin() ).key() ) - ( plotlen - map2->size() );
miny = ( map2->end() - 1 ).value();
} else if ( maxx3 >= maxx1 && maxx3 >= maxx2 ) {
maxx = maxx3;
minx = ( ( map3->begin() ).key() ) - ( plotlen - map3->size() );
miny = ( map3->end() - 1 ).value();
}
curtimestamp = maxx;
//qDebug() << "minx pre: " << minx << " | maxx pre: " << maxx << " | miny pre : " << miny << " | maxy pre: " << maxy ;
if ( s1 && !map1->isEmpty() ) {
QVector<QPointD> plval = plotData_helper ( map1, plotlen, miny, maxy );
plotter->setCurveData ( 0, plval );
//qDebug() << "minx m1: " << miny << " | maxy m1: " << maxy;
}
if ( s2 && !map2->isEmpty() ) {
QVector<QPointD> plval = plotData_helper ( map2, plotlen, miny, maxy );
plotter->setCurveData ( 1, plval );
//qDebug() << "minx m2: " << miny << " | maxy m2: " << maxy;
}
if ( s3 && !map3->isEmpty() ) {
QVector<QPointD> plval = plotData_helper ( map3, plotlen, miny, maxy );
plotter->setCurveData ( 2, plval );
//qDebug() << "minx m3: " << miny << " | maxy m3: " << maxy;
}
miny = miny - std::floor ( miny * 0.1 );
maxy = maxy + std::ceil ( maxy * 0.1 );
//qDebug() << "minx: " << minx << " | maxx: " << maxx << " | miny: " << miny << " | maxy: " << maxy << "\n";
//PlotSettings* pset = new PlotSettings ( minx, miny, maxx, maxy, 4, 5 );
//plotter->setPlotSettings ( *pset );
plotter->setPlotSettings ( * ( new PlotSettings ( minx, miny, maxx, maxy, 4, 5 ) ) );
}
// plot-helper method; just to keep the code a bit cleaner..
QVector<QPointD> Msg::Display::plotData_helper ( QMap<uint, uint>* mp, int plen, uint& miny, uint& maxy )
{
int msize = mp->size();
int goback = ( msize < plen ) ? msize : plen ;
QVector<QPointD> plval;
QMap<uint, uint>::const_iterator i;
for ( i = mp->constEnd() - goback ; i != mp->constEnd(); ++i ) {
uint val = i.value();
plval.append ( QPointD ( i.key(), val ) );
if ( val > maxy ) {
maxy = val;
} else if ( val < miny ) {
miny = val;
}
}
return plval;
}
void Msg::Display::showCurrentVal_alt()
{
//qDebug() << "lastval: " << displayPg->lastval;
//qDebug() << "mapend:" << ( map->constEnd() - 1 ).key();
if ( ! ( displayPg->lastval == ( map1->constEnd() - 1 ).key() ) ) {
displayPg->lastval = ( map1->constEnd() - 1 ).key();
displayPg->valueiter = 0;
} else {
displayPg->valueiter = displayPg->valueiter + valinterval;
//qDebug() << "valiter: " << displayPg->valueiter;
}
uint showts = ( map1->constEnd() - 1 - ( int ) fetchinterval + ( int ) displayPg->valueiter ).key();
//output data for calculated timestamp...
QDateTime dtime = QDateTime::fromMSecsSinceEpoch ( quint64 ( showts ) * 1000 );
displayPg->digitalClk->display ( dtime.toString ( "hh:mm:ss" ) );
displayPg->sensorval->display ( QString::number ( map1->value ( showts ) ) );
visPg->tacho->setValue ( map1->value ( showts ) );
//qDebug() << "show:" << show;
//qDebug() << "mapvals: " << map1->value ( show ) << "\n";
}
void Msg::Display::showAvg() //TODO: make dependant on which sensor data is displayed in the first place..
{
uint avg1 = 0;
uint avg2 = 0;
int size = map1->size();
int a1end = 0;
int a2end = 0;
if ( map1->isEmpty() ) {
return;
}
QMap<uint, uint>::const_iterator i;
( size < 60 ) ? a1end = size : a1end = 60; //1min
( size < 900 ) ? a2end = size : a2end = 900; // 10min = 600
for ( i = ( map1->constEnd() - 1 ); i != ( map1->constEnd() - 1 - a1end ); --i ) {
avg1 += i.value(); //TODO: hier absichern falls values nicht geliefert wurden...
}
avg1 = avg1 / a1end;
displayPg->avgval1->display ( ( int ) avg1 );
//qDebug() << "avg1: " << avg1;
for ( i = ( map1->constEnd() - 1 ); i != ( map1->constEnd() - 1 - a2end ); --i ) {
avg2 += i.value();
}
avg2 = avg2 / a2end;
displayPg->avgval2->display ( ( int ) avg2 );
//qDebug() << "avg2: " << avg2;
}
void Msg::Display::sensorErr ( QObject* repn )
{
QNetworkReply* replyn = qobject_cast<QNetworkReply*> ( repn );
qDebug() << QString ( "seems there was a problem downloading %1 data!" ).arg ( replyn->request().attribute ( QNetworkRequest::User ).toString() );
qDebug() << "error was: " << replyn->errorString();
urlPg->statusLabel->setText ( tr ( "http-reply error! - resuming in 2s.." ) );
QTimer::singleShot ( 2000, this, SLOT ( getAllSensors_new() ) );
}
QString Msg::TimeConverter_s::convert ( double value )
{
QDateTime dtime = QDateTime::fromMSecsSinceEpoch ( qint64 ( value ) * 1000 );
return dtime.toString ( "hh:mm:ss" );
}
QString Msg::TimeConverter_m::convert ( double value )
{
QDateTime dtime = QDateTime::fromMSecsSinceEpoch ( qint64 ( value ) * 1000 );
return dtime.toString ( "hh:mm" );
}
| [
"github@paalsteek.de"
] | github@paalsteek.de |
2a2eca428e5d097f4f5b03fa693207cbfc15f0d1 | b667f7c5ab0bfc6727890468f2e9eba9564efcff | /AppServiceSandwich/ResourcePath.hpp | 406ebca0bb012087c22d936eaed4c8c49b162346 | [] | no_license | peterekepeter/app-service-sandwich | c6fe39f1ef5be9ae7537c2c893a7a33152f002aa | 6299e23b62f2484ce82e34ba214d2ca8dd892853 | refs/heads/master | 2021-07-10T12:30:19.020482 | 2021-04-09T17:38:34 | 2021-04-09T17:38:34 | 88,741,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,879 | hpp | #pragma once
#include <stdexcept>
#include <string>
// a class for handling paths towards resources
class ResourcePath
{
friend std::ostream& operator<<(std::ostream& os, const ResourcePath& obj);
public:
// construct default path which is current folder, in relative path form
ResourcePath();
// can create a new path from string
ResourcePath(const std::string& path);
// can create a new path from const char*
ResourcePath(const char* path);
// concatenate 2 paths to create a third, it will be normalized
friend ResourcePath operator +(const ResourcePath& lhs, const ResourcePath& rhs);
// concatenate another path to the first path
friend ResourcePath& operator +=(ResourcePath& lhs, const ResourcePath& rhs);
friend bool operator==(const ResourcePath& lhs, const ResourcePath& rhs); //see if equal
friend bool operator!=(const ResourcePath& lhs, const ResourcePath& rhs); //see if not equal
ResourcePath(const ResourcePath& other); //copy
ResourcePath(ResourcePath&& other); // move
ResourcePath& operator=(const ResourcePath& other); //copy op
ResourcePath& operator=(ResourcePath&& other); // move
// check if the path points to a file
bool IsFilePath() const;
// check if the path points to a directory
bool IsDirectoryPath() const;
// check if we have a relative path
bool IsRelativePath() const;
// check if we have an absolute path
bool IsAbsolutePath() const;
// return const char*, which can be passed to other APIs
const char* ToCharPtr() const;
// return a copy in std::string which can be passed (preferably moved) to other APIs
std::string ToString() const;
// implicit conversion operator so that you can pass ResourcePaths directly to functions that accept const char*
operator const char*() const { return this->ToCharPtr(); }
// convert path to a directory path
ResourcePath ToDirectory() const;
// relational operators are for ordering, they don't have any other meaning
friend bool operator<(const ResourcePath& lhs, const ResourcePath& rhs);
friend bool operator<=(const ResourcePath& lhs, const ResourcePath& rhs);
friend bool operator>(const ResourcePath& lhs, const ResourcePath& rhs);
friend bool operator>=(const ResourcePath& lhs, const ResourcePath& rhs);
// hasher functor value for unordered map
class Hasher
{
public:
size_t operator()(const ResourcePath& obj) const;
};
// an exception type for this class only
class Exception : public std::runtime_error
{
public:
explicit Exception(const std::string& _Message) : runtime_error(_Message) { }
explicit Exception(const char* _Message) : runtime_error(_Message) { }
};
private:
std::string data;
// bring the path to a normal form, automatically called every time path changes
// optimized, calling on already normalized paths is super fast, as there is no need for reallocation or resizing
void Normalize();
};
| [
"peterekepeter@gmail.com"
] | peterekepeter@gmail.com |
36b1c30b1802fd5b09c60b60462baef3041d2adc | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/agc003/A/2742431.cpp | 3e5a073d3796f671d5a5690b3857f7fe91a60bc4 | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 572 | cpp | #include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
int main(){
string s;
cin>>s;
bool north=false;
bool south=false;
bool east=false;
bool west=false;
for(int i=0;i<s.size();i++){
if(s[i]=='S')south=true;
if(s[i]=='N')north=true;
if(s[i]=='E')east=true;
if(s[i]=='W')west=true;
}
bool sn=true;
bool ew=true;
if(south!=north)sn=false;
if(east!=west)ew=false;
if(sn==true&&ew==true){
cout<<"Yes"<<endl;
}
else{
cout<<"No"<<endl;
}
} | [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
45f1ffdbaa16d87b690cc03308c553176fd6544f | 23787ce9f0c55c04ba00a109c45d5d7a26daff0b | /extlibs/vili/include/vili/NodeValidator.hpp | 0af17cc14f9e5502c6db5b4c3f10dc5d74e69f27 | [
"MIT",
"Zlib",
"BSD-2-Clause"
] | permissive | Tzupy/ObEngine | 859e350de2987929ed99f532c60b5eaca227c528 | fa5c36aa41be1586088b76319c648d39c7f57cdf | refs/heads/master | 2020-08-22T15:13:43.899147 | 2019-10-20T21:10:42 | 2019-10-20T21:10:42 | 216,424,002 | 0 | 0 | MIT | 2019-10-20T20:35:26 | 2019-10-20T20:35:26 | null | UTF-8 | C++ | false | false | 1,032 | hpp | #pragma once
#include <NodeIterator.hpp>
namespace vili
{
/**
* \brief Almost like the NodeIterator except it should return a result
* \tparam T Type the NodeValidator should return (validate)
* @Bind
*/
template <class T>
class NodeValidator : public NodeIterator
{
private:
T m_result;
public:
/**
* \brief Creates a new NodeValidator in realtime mode
*/
NodeValidator();
/**
* \brief Creates a new NodeValidator in cached mode
* \param node ComplexNode used to generate the cache (The ComplexNode that will be used to walk)
*/
NodeValidator(ComplexNode* node);
/**
* \brief Stops the iteration and returns the given result
* \param result Value to return
*/
void validate(T result);
/**
* \brief Gets the result returned using the NodeValidator::validate method
* \return The returned value
*/
T result();
};
}
| [
"Mizugola@gmail.com"
] | Mizugola@gmail.com |
8a34da68548535b6363db87556724245852b185e | d071e6156cf23ddee37a612f71d71a650c27fcfe | /template/string_algorithm/SuffixAutomaton[后缀自动机].cpp | 6efea92e3f4cd505b115f0b589e0fa44129e81fe | [] | no_license | tsstss123/code | 57f1f7d1a1bf68c47712897e2d8945a28e3e9862 | e10795c35aac442345f84a58845ada9544a9c748 | refs/heads/master | 2021-01-24T23:00:08.749712 | 2013-04-30T12:33:24 | 2013-04-30T12:33:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | cpp | const int MAXN = 250005;
struct SuffixAutomaton {
struct Node {
int len;
Node *f, *ch[26];
};
Node *root, *last;
Node pool[MAXN*2];
int cnt;
void init() {
root = last = pool;
memset(root, 0, sizeof(Node));
cnt = 1;
}
void append(char ch) { /* 添加一个字符到末尾,last为一个后缀终止态,沿着last->f走,经过的都是终止态 */
int c = ch - 'a';
Node *p = last, *np = pool + cnt++;
memset(np, 0, sizeof(Node));
np->len = last->len + 1;
last = np;
for (; NULL != p && NULL == p->ch[c]; p = p->f) p->ch[c] = np;
if (p == NULL) {
np->f = root;
} else {
if (p->ch[c]->len == p->len+1) {
np->f = p->ch[c];
} else { /* 新建一个节点,避免接受不存在的后缀 */
Node *q = p->ch[c], *nq = pool + cnt++;
*nq = *q;
nq->len = p->len + 1;
q->f = np->f = nq;
for (; NULL != p && p->ch[c] == q; p = p->f) p->ch[c] = nq;
}
}
}
};
| [
"leon.acwa@gmail.com"
] | leon.acwa@gmail.com |
065b4d365f97140a0227bb75669d45f1f6c6d86a | 1424e17abdd5710526695687626a083f5abaf476 | /Chapter07/Teacher.cpp | c944d72359c71b6115e1f41b0bf09a62bfcc8170 | [] | no_license | nosuggest/sladeRode3 | f0c827909175e9510c56ea8d8fb587a61d7583b6 | 4145dcf20321a49033ea88a3c0990f802aeee758 | refs/heads/master | 2022-11-17T19:29:41.919594 | 2019-11-20T15:57:10 | 2019-11-20T15:57:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,027 | cpp | //
// Created by 沙韬伟 on 2019-09-24.
//
#include "Teacher.h"
const string &Teacher::getName() const {
return name;
}
void Teacher::setName(const string &name) {
Teacher::name = name;
}
int Teacher::getAge() const {
return age;
}
void Teacher::setAge(int age) {
Teacher::age = age;
}
float *Teacher::getScores() const {
return scores;
}
void Teacher::setScores(float *scores) {
Teacher::scores = scores;
}
void Teacher::initScores() {
this->scores = new float[1];
this->scoreCount = 1;
}
void Teacher::addScore(float score) {
this->scores[this->scoreCount - 1] = score;
// 创建一个新数组,分配scoreCount+1个空间
float *newScores = new float[scoreCount + 1];
float *oldScores = scores;
// 复制原数组到新数组中
memcpy(newScores, scores, sizeof(float) * scoreCount);
// 更新分配scoreCount
scoreCount++;
// scores指向新数组
scores = newScores;
delete oldScores;
}
void Teacher::showInfo() {
cout << getName() << "\t" << getAge() << endl;
for (int i = 0; i < scoreCount - 1; ++i) {
cout << this->scores[i] << "\t";
}
cout << endl;
}
Teacher::Teacher() {
initScores();
}
Teacher::Teacher(const string &name, int age, float *scores, int scoreCount) : name(name), age(age), scores(scores),
scoreCount(scoreCount) {
initScores();
}
Teacher::~Teacher() {
cout << "release" << endl;
delete this->scores;
}
Teacher::Teacher(const string &name, int age) : name(name), age(age) {
initScores();
}
float Teacher::getTotal() {
float tmp = 0;
for (int i = 0; i < scoreCount - 1; ++i) {
tmp += scores[i];
}
return tmp;
}
// 返回一个score更高的teacher对象
Teacher &Teacher::superSchooler(Teacher &teacher) {
if (teacher.getTotal() > this->getTotal()) {
return teacher;//返回对象引用
} else {
return *this;//返回对象引用
}
} | [
"taowei.sha@ymm56.com"
] | taowei.sha@ymm56.com |
cbe44538ca0c0c7ad19ab786198fb50f1e9ffff3 | 014c74aac6e6e6e7e86a39eecc299c6a3f89d702 | /includes/ara/diag/impl_type_monitoractiontype.h | b025e6f12f563cf46fab9b82b8cb2787f0331add | [] | no_license | xuanwolanxue/ucm_client | 927e0ee25816b2f6b64a5755a5baca0a91bf5b5d | 130f87bff609ad78bbd4224a5781f9999ce36c01 | refs/heads/master | 2023-03-15T21:10:05.574505 | 2020-02-17T12:17:38 | 2020-02-17T12:17:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | h | #ifndef ARA_DIAG_IMPL_TYPE_MONITORACTIONTYPE_H
#define ARA_DIAG_IMPL_TYPE_MONITORACTIONTYPE_H
#include "impl_type_uint8.h"
namespace ara
{
namespace diag
{
enum class MonitorActionType : ::UInt8
{
kPassed=0,
kFailed=1,
kPrepassed=2,
kPrefailed=3,
kFdcThresholdReached=4,
kResetTestFailed=5,
kFreezeDebouncing=6,
kResetDebouncing=7,
kPrestore=8,
kClearPrestore=9,
};
}
}
#endif // ARA_DIAG_IMPL_TYPE_MONITORACTIONTYPE_H
| [
"yang.dongwei@foxmail.com"
] | yang.dongwei@foxmail.com |
b11aaeffaeb120f912aa82600bf4b1cea2a76a2c | d681b93f80b75d2b79b77ec621773e66efcf6cba | /include/mqf/portfolio/efficient_frontier_unconstrained.h | 448afdfeca9b0bfb2a04999924413cb193197c8b | [] | no_license | gansuranga/mqf | 0ebcf6bd2607afc5cc9bbfd28b35c3f301742508 | 25de0f3df1cc2edadb2bac87cfd7ed4238646b4d | refs/heads/master | 2020-03-28T12:48:31.289331 | 2015-07-21T00:01:08 | 2015-07-21T00:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,507 | h | #ifndef INCLUDED_MQF_PORTFOLIO_EFFICIENT_FRONTIER_UNCONSTRAINED
#define INCLUDED_MQF_PORTFOLIO_EFFICIENT_FRONTIER_UNCONSTRAINED
#include "../eigen_pinv.h"
namespace mqf {
/*
* Efficient Frontier Unconstrained
*
* The set of portfolios that have the least variance for their expected return.
*
* This places no constraints on the portfolio weights.
*
*/
struct EfficientFrontierUnconstrained {
using Vec = Eigen::VectorXd;
using Mat = Eigen::MatrixXd;
Vec returns;
Mat covarianceInv;
double retCovInvRet;
void set( const Vec& ret, const Mat& cov ) {
returns = ret;
covarianceInv = pseudoInverse(cov);
retCovInvRet = returns.dot( covarianceInv * returns );
}
Vec computeWeightsForReturn( double mu ) const {
return returns * ( mu / retCovInvRet );
}
Vec computeWeightsForVariance( double var ) const {
return ( covarianceInv * returns ) * std::sqrt( var / retCovInvRet );
}
double computeVarianceForReturn( double mu ) const {
return (mu * mu) / retCovInvRet;
}
double computeReturnForVariance( double var ) const {
return std::sqrt( var * retCovInvRet );
}
double computeRiskAversionForReturn( double mu ) const {
return retCovInvRet / mu;
}
double computeRiskAversionForVariance( double var ) const {
return std::sqrt( retCovInvRet / var );
}
Vec computeReturnsFromWeights( const Vec& weights, double riskAversion ) const {
return riskAversion * pseudoInverse( covarianceInv ) * weights;
}
};
}
#endif
| [
"chriswelshman@gmail.com"
] | chriswelshman@gmail.com |
fa9bfa0c629632682d6c4916fa0b22b6a82f4c13 | 92b7ba1025bd462cef8ce1595baba3bb7f602439 | /AlgoSolution/PKU/poj3128(AC).cpp | b13e85d380bc5c797c8a022677c07453af2f6717 | [] | no_license | robotcator/Algo | 4f60b8140cde6891b7425412ab98124094f3ae7f | 9c49c4f6ea50339539756964c5f3f3ad7b92141f | refs/heads/master | 2020-12-30T09:59:15.529226 | 2014-11-27T06:03:31 | 2014-11-27T06:03:31 | 20,529,193 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 949 | cpp | // Accepted 164K 16MS
// 置换T^2,如果置换长度为n && gcd(n, 2) == 1
// 则T^2长度仍然为n
// 若置换长度n 满足2 | n,则T^2分裂为 2个长度为
// n/2的循环的并
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
int t;
int vis[30];
int cnt[30];
// 统计循环个数为i的循环个数
char B[30];
scanf("%d", &t);
while(t--){
scanf("%s", B);
memset(vis, 0, sizeof(vis));
memset(cnt, 0, sizeof(cnt));
for(int i = 0; i < 26; i ++){
if(vis[i] == 0){
vis[i] = 1;
int temp = B[i] - 'A';
int num = 1;
while(temp >= 0 && temp != i){
vis[temp] = 1;
temp = B[temp] - 'A';
num ++;
}
cnt[num] ++;
}
}
int ok = 1;
for(int i = 2; i <= 26; i += 2)
if(cnt[i] % 2 == 1) ok = 0;
if(ok == 1) printf("Yes\n");
else printf("No\n");
}
return 0;
}
| [
"problemset@163.com"
] | problemset@163.com |
9ac2862204cd214bca9e5ecc78d55c74a5889d37 | 09849dc5ec4f7456f4f791491dc7002e23e250a1 | /c/cppp/class/test.hpp | 397dde0d7e2f977bd9adf8fa6671df92318110d6 | [] | no_license | Cuculidae/Learn | e6f97dad5524681a5e1e113fb2f7fa4d2c088916 | f811b0ee36298824bc179f08d9bdc81447ccfeac | refs/heads/master | 2021-01-10T17:38:36.370590 | 2015-11-29T05:07:35 | 2015-11-29T05:07:35 | 47,028,983 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 224 | hpp | #include <iostream>
class test
{
friend std::istream &read(std::istream &is, test &item);
public:
// fuck! it compiled
test() { read(std::cin, *this); }
};
std::istream &read(std::istream &is, test &item);
| [
"2863043993@qq.com"
] | 2863043993@qq.com |
beea8b8564879bfc1a4468e2d4d0fb838ac7b12e | 2a855997a890ed3f21618adf132f4214c2ddd8c3 | /October_LeetCoding_Challenge/Week_1 October 1st–October 7th/Day_1 Number of Recent Calls.c++ | fa38b7f95ae2bcd02dff064032daf791572a9efa | [] | no_license | DaliaAymanAmeen/leetcoding-challenges | 81354f2d48239424898ca95ba4e732a239255015 | 0a9f4b81c31d48031d23238c67bac46d599d3261 | refs/heads/master | 2022-12-24T07:27:38.323666 | 2020-10-05T10:53:05 | 2020-10-05T10:53:05 | 260,786,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,009 | class RecentCounter {
public:
int requests_done = 0;
vector <int> request;
RecentCounter() {
requests_done = 0;
}
int ping(int t) {
RecentCounter();
request.push_back(t);
int upper = t;
int lower = t - 3000;
auto upper_it = lower_bound (request.begin(), request.end(), upper);
auto lower_it = lower_bound (request.begin(), request.end(), lower);
requests_done = distance (request.begin(), upper_it) - distance(request.begin(), lower_it) + 1;
/*for (int i = 0 ; i < request.size() ; i++)
{
if (request[i] > upper) return requests_done;
if (request[i]>= lower && request[i] <= upper)
requests_done++;
}*/
return requests_done;
}
};
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter* obj = new RecentCounter();
* int param_1 = obj->ping(t);
*/ | [
"dalia.ayman.ameen@gmail.com"
] | dalia.ayman.ameen@gmail.com | |
eea10395d5ba265b7cf2cdfe623d4f350c82771a | af555a7397356ca5b1a30bf4d1a62960b8649774 | /example/windows/runner/main.cpp | da8ee2be9d588dc590a1fff868b9547e8062bc34 | [] | no_license | xTudoS/flutter-native-desktop | fc3d36e34591584c2edda6208d42a85495676e76 | 39dba305dab974631025bb8572498d1547c9e2fa | refs/heads/master | 2023-03-30T11:12:15.705075 | 2021-04-06T04:55:43 | 2021-04-06T04:55:43 | 350,507,323 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,240 | cpp | #include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "run_loop.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
RunLoop run_loop;
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(&run_loop, project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"flutter_native_desktop_example", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
run_loop.Run();
::CoUninitialize();
return EXIT_SUCCESS;
}
| [
"x2do@pm.me"
] | x2do@pm.me |
6da25e856830ffdecaa822802aeea296bf2c83fb | b77b296844bc196a881a5cd9f2495671578ec6c9 | /include/vo_core/mappoint3d.h | 1bd19e34268913d9341dd85ef0d142b47404e341 | [] | no_license | GabrielDracula/Mixed-form-map-with-panoramic-images-based-on-SLAM | 41555193508dc5c28818c0dc3004d97a74d5553c | 6374e6544fceb58765131cac997c28f231263407 | refs/heads/master | 2020-04-07T01:58:50.781380 | 2018-11-17T07:13:05 | 2018-11-17T07:13:05 | 157,959,490 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,221 | h | #ifndef MAPPOINT3D_H
#define MAPPOINT3D_H
#include "common_include.h"
namespace mixmap
{
class Frame;
}
namespace vocore
{
class MapPoint3d
{
public:
typedef std::shared_ptr<MapPoint3d> Ptr;
unsigned long id_; // ID
static unsigned long factory_id_; // factory id
bool good_; // wheter a good point
Vector3d pos_; // Position in world
Vector3d norm_; // Normal of viewing direction
Mat descriptor_; // Descriptor for matching
list<mixmap::Frame*> observed_frames_; // frames that can observe this point
int matched_times_; // being an inliner in pose estimation
int visible_times_; // being visible in current frame
public:
MapPoint3d();
MapPoint3d(
unsigned long id,
const Vector3d& position,
const Vector3d& norm,
mixmap::Frame* frame=nullptr,
const Mat& descriptor=Mat()
);
inline cv::Point3f getPositionCV() const {
return cv::Point3f( pos_(0,0), pos_(1,0), pos_(2,0) );
}
static MapPoint3d::Ptr createLocalMapPoint();
static MapPoint3d::Ptr createLocalMapPoint(
const Vector3d& pos_world,
const Vector3d& norm_,
const Mat& descriptor,
mixmap::Frame* frame );
};
}
#endif | [
"243652457@qq.com"
] | 243652457@qq.com |
2b4a9e550f95eb53464ef6ecb3fd02beef871e54 | 4033100805905577cc1e75b1cdec88f43e9205c7 | /core/utility/include/reference.h | 0338529fb6f2017a6363f5366226e73095f1e96d | [
"MIT"
] | permissive | uwdb/lightdb | de69ed28bf8ceb13e2ef1cffa2b32a80d5244fa3 | b24edb60b601a948e6b441e2ccc59b1911c47ac9 | refs/heads/master | 2023-05-31T21:21:07.674916 | 2023-05-16T20:08:26 | 2023-05-16T20:08:26 | 90,768,966 | 36 | 5 | null | 2021-02-18T18:02:27 | 2017-05-09T16:40:37 | C++ | UTF-8 | C++ | false | false | 5,967 | h | #ifndef LIGHTDB_REFERENCE_H
#define LIGHTDB_REFERENCE_H
#include "errors.h"
#include <memory>
#include <unordered_map>
#include <optional>
namespace lightdb {
class DefaultMixin {
public:
inline void PostConstruct(const DefaultMixin&) const { }
};
template<typename T, typename Mixin=DefaultMixin>
class shared_reference: public Mixin {
public:
//TODO Change PostConstruct to use SFINAE
explicit shared_reference(std::shared_ptr<T> pointer)
: Mixin(*this),
pointer_(std::move(pointer))
#ifndef NDEBUG
, direct_(&*pointer_)
#endif
{ Mixin::PostConstruct(*this); }
shared_reference(const shared_reference &reference)
: Mixin(*this), pointer_(reference.pointer_)
#ifndef NDEBUG
, direct_(&*pointer_)
#endif
{ Mixin::PostConstruct(*this); }
template<typename TDerived>
shared_reference(const std::shared_ptr<TDerived> &value)
: Mixin(*this), pointer_{std::dynamic_pointer_cast<T>(value)}
#ifndef NDEBUG
, direct_(&*pointer_)
#endif
{ Mixin::PostConstruct(*this); }
template<typename TDerived>
shared_reference(const shared_reference<TDerived> &value)
: Mixin(*this),
pointer_{std::dynamic_pointer_cast<T>(static_cast<std::shared_ptr<TDerived>>(value))}
#ifndef NDEBUG
, direct_(&*pointer_)
#endif
{ Mixin::PostConstruct(*this); }
shared_reference(const T &value)
: Mixin(*this), pointer_{std::make_shared<T>(value)}
#ifndef NDEBUG
, direct_(&*pointer_)
#endif
{
Mixin::PostConstruct(*this);
}
template<typename TDerived>
shared_reference(const TDerived &value, typename std::enable_if<std::is_base_of<T,TDerived>::value>::type* = 0)
: Mixin(*this), pointer_{std::make_shared<TDerived>(value)}
#ifndef NDEBUG
, direct_(&*pointer_)
#endif
{
Mixin::PostConstruct(*this);
}
template<typename TDerived>
shared_reference(TDerived &value, typename std::enable_if<std::is_base_of<T,TDerived>::value>::type* = 0)
: Mixin(*this), pointer_{std::make_shared<TDerived>(value)}
#ifndef NDEBUG
, direct_(&*pointer_)
#endif
{
Mixin::PostConstruct(*this);
}
virtual ~shared_reference() = default;
explicit inline operator T&() const {
return *pointer_;
}
inline T* operator->() const {
return pointer_.get();
}
inline T& operator*() const {
return *pointer_;
}
inline explicit operator const std::shared_ptr<T>&() const {
return pointer_;
}
bool operator==(const shared_reference& other) const { return pointer_ == other.pointer_; }
bool operator!=(const shared_reference& other) const { return !(*this == other); }
bool operator<(const shared_reference& other) const { return pointer_ < other.pointer_; }
bool operator<=(const shared_reference& other) const { return pointer_ <= other.pointer_; }
bool operator>(const shared_reference& other) const { return pointer_ > other.pointer_; }
bool operator>=(const shared_reference& other) const { return pointer_ >= other.pointer_; }
shared_reference& operator=(const shared_reference&) = default;
shared_reference& operator=(shared_reference&&) noexcept = default;
template<typename TDerived>
inline const TDerived& downcast() const {
return *dynamic_cast<TDerived*>(pointer_.get());
}
template<typename TDerived>
inline TDerived& downcast() {
return *dynamic_cast<TDerived*>(pointer_.get());
}
template<typename TDerived>
inline const TDerived& expect_downcast() const {
if(is<TDerived>())
return downcast<TDerived>();
else
throw BadCastError("Could not downcast instance of type " + type() + " to " + typeid(TDerived).name());
}
template<typename TDerived>
inline TDerived& expect_downcast() {
if(is<TDerived>())
return downcast<TDerived>();
else
throw BadCastError("Could not downcast instance of type " + type() + " to " + typeid(TDerived).name());
}
template<typename TDerived>
inline bool is() const {
return dynamic_cast<const TDerived*>(pointer_.get()) != nullptr;
}
template<typename TDerived>
inline const std::optional<std::reference_wrapper<const TDerived>> try_downcast() const {
auto cast = dynamic_cast<const TDerived*>(pointer_.get());
return cast != nullptr
? std::optional<std::reference_wrapper<const TDerived>>{*cast}
: std::nullopt;
}
template<typename TDerived>
inline std::optional<std::reference_wrapper<TDerived>> try_downcast() {
auto cast = dynamic_cast<TDerived*>(pointer_.get());
return cast != nullptr
? std::optional<std::reference_wrapper<TDerived>>{*cast}
: std::nullopt;
}
inline long use_count() const noexcept { return pointer_.use_count(); }
inline std::string type() const {
return typeid(*pointer_.get()).name();
}
template<typename TDerived, typename... _Args>
inline static shared_reference
make(_Args&&... args) {
return shared_reference{static_cast<std::shared_ptr<T>>(std::make_shared<TDerived>(std::forward<_Args>(args)...))};
}
private:
std::shared_ptr<T> pointer_;
#ifndef NDEBUG
T* direct_;
#endif
};
template<typename T>
class AddressableMixin : public std::enable_shared_from_this<T> {
public:
void PostConstruct(const shared_reference<T, AddressableMixin>& instance) { }
shared_reference<T, AddressableMixin> get() {
return shared_reference<T, AddressableMixin>(this->shared_from_this());
};
};
} // namespace lightdb
#endif //LIGHTDB_REFERENCE_H
| [
"bhaynes@cs.washington.edu"
] | bhaynes@cs.washington.edu |
8bd2a03d5c01a738ea10ef238551687480dd3fa7 | fec81bfe0453c5646e00c5d69874a71c579a103d | /blazetest/src/mathtest/operations/smatsmatkron/DCaSCa.cpp | 7e7494983bb7f4a250d174a4e0fbd4495686f85a | [
"BSD-3-Clause"
] | permissive | parsa/blaze | 801b0f619a53f8c07454b80d0a665ac0a3cf561d | 6ce2d5d8951e9b367aad87cc55ac835b054b5964 | refs/heads/master | 2022-09-19T15:46:44.108364 | 2022-07-30T04:47:03 | 2022-07-30T04:47:03 | 105,918,096 | 52 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 4,335 | cpp | //=================================================================================================
/*!
// \file src/mathtest/operations/smatsmatkron/DCaSCa.cpp
// \brief Source file for the DCaSCa sparse matrix/sparse matrix Kronecker product math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/operations/smatsmatkron/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'DCaSCa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
using DCa = blaze::DiagonalMatrix< blaze::CompressedMatrix<TypeA> >;
using SCa = blaze::SymmetricMatrix< blaze::CompressedMatrix<TypeA> >;
// Creator type definitions
using CDCa = blazetest::Creator<DCa>;
using CSCa = blazetest::Creator<SCa>;
// Running tests with small matrices
for( size_t i=0UL; i<=4UL; ++i ) {
for( size_t j=0UL; j<=i; ++j ) {
for( size_t k=0UL; k<=4UL; ++k ) {
for( size_t l=0UL; l<=k*k; ++l ) {
RUN_SMATSMATKRON_OPERATION_TEST( CDCa( i, j ), CSCa( k, l ) );
}
}
}
}
// Running tests with large matrices
RUN_SMATSMATKRON_OPERATION_TEST( CDCa( 9UL, 7UL ), CSCa( 8UL, 7UL ) );
RUN_SMATSMATKRON_OPERATION_TEST( CDCa( 16UL, 7UL ), CSCa( 15UL, 7UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix Kronecker product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
0b3d3410a5c62a3fa913a4fb17107e83776e32cc | e30bb72d0836bd9bda3279dc469a3b3a5e78724c | /test/unittest/test_factory_template.cpp | d83e3b899402f877a9bb7be5f3bae44088e0e0f9 | [] | no_license | hutusi/xns | 2f2bc30c7421d3a80826e1e20b077816f7d4e098 | 3bd838e1b51566d1d837bb0abfa3e869a3d5866a | refs/heads/master | 2016-09-06T00:40:54.589869 | 2012-09-27T15:32:41 | 2012-09-27T15:32:41 | 3,582,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | cpp |
#include "xns/pattern/factory_template.h"
#include "xns/pattern/singleton.h"
#include "gtest/gtest.h"
using namespace testing;
using namespace std;
class Product{
public:
virtual void Show(){cout<<"I'm base!";}
DEFINE_SINGLETON(Product)
};
class AP : public Product{
public:
DEFINE_PRODUCT_MAKER(Product, AP)
virtual void Show(){cout<<"I'm AP!";}
};
REGISTER_PRODUCT_CATEGORY(Product, AP, 1)
TEST(test_factory, test){
Factory<Product> fa;
Product* p = fa.make(1);
p->Show();
}
| [
"huziyong@gmail.com"
] | huziyong@gmail.com |
f467462e62c0f4b2181370d9198990dc5d083613 | 1e944c61257df92db3e8fff37302cfa38e9f1717 | /src/gamecontroller_subsystem.cc | 3d172dcd137728cf75f22fc531892d970e388f76 | [] | no_license | wilhelmtell/glasses | 273ece7c15d1940c468eed4553e18ff1a87fce8a | 650eabcc7170b064e8589ef1b35827861f05184c | refs/heads/master | 2021-01-17T12:54:31.700871 | 2016-07-24T14:18:00 | 2016-07-24T14:18:00 | 58,410,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 291 | cc | #include "gamecontroller_subsystem.hh"
#include "subsystem_init_error.hh"
#include <SDL2/SDL.h>
namespace gls {
gamecontroller_subsystem::gamecontroller_subsystem() {
if(SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) < 0)
throw subsystem_init_error(SDL_GetError());
}
} // namespace gls
| [
"matan.nassau@gmail.com"
] | matan.nassau@gmail.com |
1d556e3f7d7fe15213f11d8970dd83fb075227cc | 2a60865fe06327e545e8bdea149315baa6e56e23 | /src/cholmpi.cpp | 2a27ca34b87efe55eb26ee5496c52247b12a0a60 | [] | no_license | pguz/CholeskyFactorization | 7dc4463b9fc1791e1c8334fd38921c58b571f538 | a415a32876ee347f64f6524f1e36757f53e53de9 | refs/heads/master | 2016-09-06T04:45:44.638615 | 2015-02-21T13:02:39 | 2015-02-21T13:02:39 | 31,124,319 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,646 | cpp | #include <fstream>
#include <cmath>
#include <stdlib.h>
#include <iostream>
#include <cassert>
#include <stddef.h>
#include <sys/time.h>
#include <math.h>
#include <mpi.h>
double gettime_ (void) {
struct timeval timer;
if (gettimeofday(&timer,NULL))
return -1.0;
return timer.tv_sec+1.0e-6*timer.tv_usec;
}
bool readConfig(
const int argc,
char** argv,
std::string& input_file,
std::string& output_file) {
if(argc != 3) {
std::cout << "Usage: ./" << argv[0] << " input_filename output_filename" << std::endl;
return false;
}
input_file = argv[1];
output_file = argv[2];
return true;
}
double t_1, t_1s, t_1e;
bool cholesky_decompose(double* C, double* R, int n, int npes, int rank) {
MPI_Barrier(MPI_COMM_WORLD);
if(rank == 0) {
t_1s = MPI_Wtime();
}
for (int j = 0; j < n; ++j) {
double s = 0;
int jn = j * n;
if (j % npes == rank) {
for (int k = 0; k < j; ++k) {
s += R[jn + k] * R[jn + k];
}
R[jn + j] = sqrt(C[jn + j] - s);
}
MPI_Bcast(&R[jn], n, MPI_DOUBLE, j % npes, MPI_COMM_WORLD);
for (int i = j + 1; i < n; ++i) {
double s = 0;
int in = i * n;
if (i % npes == rank )
{
for (int k = 0; k < j; k++) {
s += R[in + k] * R[jn + k];
}
R[in + j] = (1.0 / R[jn + j] * (C[in + j] - s));
}
}
}
MPI_Barrier(MPI_COMM_WORLD);
if(rank == 0) {
t_1e = MPI_Wtime();
}
t_1 += (t_1e - t_1s);
return true;
}
int main(int argc, char* argv[]) {
std::string input_file, output_file;
if(!readConfig(argc, argv, input_file, output_file))
return 1;
std::ifstream finput;
std::ofstream foutput;
finput.open(input_file.c_str());
foutput.open(output_file.c_str());
int npes, rank;
MPI_Init(&argc , &argv);
MPI_Comm_size(MPI_COMM_WORLD, &npes);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
while (!finput.eof()) {
int n, m;
finput >> n >> m;
assert(n == m);
double *C = (double*)malloc(n * n * sizeof(double));
if (C == NULL)
return 1;
double *R = (double*)calloc(n * n, sizeof(double));
if (R == NULL)
return 1;
for(int i = 0; i < n * n; ++i)
finput >> C[i];
double t_start = gettime_();
if(cholesky_decompose(C, R, n, npes, rank)) {
double t_end = gettime_();
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
foutput << R[i * n + j] << ' ';
}
}
foutput << '\n';
} else {
foutput << "Not proper form of matrix C" << std::endl;
}
free(C);
free(R);
}
MPI_Finalize();
std::cout << t_1 << std::endl;
finput.close();
foutput.close();
return 0;
}
| [
"pawelguz@gmail.com"
] | pawelguz@gmail.com |
f902a4198a895929b2069f20983b45a3ad49fc21 | 9c09ff82d3eeb1977ff8cf06c9f4565abb75183e | /databaseDriver.cpp | 1e979d28203df08078c5554d6ca6c31faa728f37 | [] | no_license | zachnudels/3022H-Assignment1 | ec7262ebce553d102986949b0f3aa40bc7b0be5f | a4ef808a614558b41c36a4f0017917054666769f | refs/heads/master | 2021-04-26T23:09:16.207957 | 2018-03-05T15:33:48 | 2018-03-05T15:33:48 | 123,937,490 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,897 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include "students.h"
int main(void)
{
using namespace std;
string command;
NDLZAC001::printMenu();
while(command!="q")
{
cout << "\n";
cin >> command;
system("clear");
cout << command << "\n\n";
if(command=="q"){
break;
}
// Add student command
if(command=="1"){
string fullName;
string studentNumber;
string classRecord;
cout << "\nPlease Enter Full Name: \n";
cin.ignore();
getline(cin,fullName);
cout << "Please Enter Student Number: \n";
cin >> studentNumber ;
cout << "Please Enter Grades Separated by a Space: \n";
cin.ignore();
getline(cin,classRecord);
NDLZAC001::addStudent(fullName, studentNumber, classRecord);
}
// Read db from file command
if(command=="2"){
string ifileName;
cout << "\nPlease enter name of file to be read\n";
cin >> ifileName;
NDLZAC001::readDatabase(ifileName);
}
// Save current db to file command
if(command=="3"){
string ofileName;
cout << "\nPlease enter name of file to save database in\n";
cin >> ofileName;
NDLZAC001::saveDatabase(ofileName);
}
// Display student command
if(command=="4"){
string studentNumber;
cout << "\nPlease Enter the Student Number of the Required Student: \n\n";
cin >> studentNumber;
NDLZAC001::displayStudentData(studentNumber);
}
// Display average grade of student command
if(command=="5"){
string studentNumber;
cout << "\nPlease Enter the Student Number of the Required Student: \n\n";
cin >> studentNumber;
NDLZAC001::gradeStudent(studentNumber);
}
NDLZAC001::printMenu();
}
}
| [
"zachnudels@gmail.com"
] | zachnudels@gmail.com |
0e185996787b115ad842b395833a160193c704a8 | ced0044646a4271afadc9d5aecb0cebe34051d4a | /Plugins/FFMPEGMedia1/Source/FFMPEGMedia/Private/FFMPEG/FFMPEGDecoder.h | e4aa819f5124f804c321c65ad58839e26e0a9ad6 | [] | no_license | asdlei99/example_ue4 | dd4cf53b360cb29222c52a640a6249d99eaf0730 | cbbc63e917900a63cb3802dbd3d90f916650f41b | refs/heads/master | 2022-04-12T11:19:19.581619 | 2020-03-13T11:49:56 | 2020-03-13T11:49:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,141 | h | #pragma once
#include "CondWait.h"
#include "FFMPEGPacketQueue.h"
#include "FFMPEGFrameQueue.h"
#include <thread>
extern "C" {
#include <libavcodec/avcodec.h>
}
class FFMPEGDecoder
{
public:
FFMPEGDecoder();
~FFMPEGDecoder();
void Init(AVCodecContext *avctx, FFMPEGPacketQueue *queue, CondWait *empty_queue_cond);
int DecodeFrame( AVFrame *frame, AVSubtitle *sub);
void SetDecoderReorderPts ( int pts );
void Abort(FFMPEGFrameQueue* fq);
void Destroy();
int Start(std::function<int (void *)> thread_func, void *arg );
AVCodecContext* GetAvctx();
int GetPktSerial();
int GetFinished();
void SetTime ( int64_t start_pts, AVRational start_pts_tb);
void SetFinished ( int finished );
private:
int decoder_reorder_pts;
AVPacket pkt;
FFMPEGPacketQueue *queue;
AVCodecContext *avctx;
int pkt_serial;
int finished;
bool packet_pending;
CondWait *empty_queue_cond;
int64_t start_pts;
AVRational start_pts_tb;
int64_t next_pts;
AVRational next_pts_tb;
std::thread *decoder_tid;
};
| [
"gxj21720@126.com"
] | gxj21720@126.com |
678818fc6e3a1d1b431ef8198f35119a5e804a3f | 6a6e28867e78bf3f4e88b3639cf27074b0153226 | /C++_Standard.cpp | c01c864c91c17065124bb4866a2e2ca416c75423 | [] | no_license | denden-kata/Study | 02ecee28b7e4e8818b8dbc74f99e1a02d9e23d9b | 2f7e9ec06aae99418e82f0dbd69ac09bce542f3c | refs/heads/master | 2021-01-02T09:18:36.209727 | 2018-09-23T15:41:21 | 2018-09-23T15:41:21 | 99,189,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | cpp | /*
コメント例
*/
// C++の標準入出力ライブラリ
#include<iostream>
// 出力(cout)を使用するために記述
using namespace std;
int main(){
// C++ では特定の文字や数値の表記を「リテラル」と呼ぶ
// 文字列リテラル
cout << "これがC++の標準出力だ!\n";
// 文字リテラル
cout << 'A' << '\n';
// 数値リテラル
cout << 123 << '\n';
// エスケープシーケンス(特殊文字の出力) ⇒ "\" をつける
cout << "アポストロフィ ⇒ " << '\'';
// どこでも宣言できる
int num = 1;
cout << "変数num=" << num << "です\n";
return 0;
} | [
"denden3104@gmail.com"
] | denden3104@gmail.com |
03dc59b533f4a4bed51ba16c6ae155196b8cd67c | e8bd00c6904a163024783cb31403a5ff668750e3 | /libs/bcg_library/math/Mathematics/LogToStdout.h | ec86bd6123fc53b06737aa989cabe18804ed118f | [] | no_license | intrinsicD/basics_lab | 165f53d9420de7ab7abd8bde5f3f32b9824f5762 | 109afca04014275015efc93e0472412d8f3feb13 | refs/heads/basics_lab | 2023-04-14T04:54:25.658721 | 2021-04-13T05:52:09 | 2021-04-13T05:52:09 | 343,719,615 | 0 | 3 | null | 2021-04-13T05:52:09 | 2021-03-02T09:37:53 | C++ | UTF-8 | C++ | false | false | 622 | h | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2020
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 4.0.2019.08.13
#pragma once
#include <Mathematics/Logger.h>
#include <iostream>
namespace bcg {
class LogToStdout : public Logger::Listener {
public:
LogToStdout(int flags)
:
Logger::Listener(flags) {
}
private:
virtual void Report(std::string const &message) {
std::cout << message.c_str() << std::flush;
}
};
}
| [
"dieckman@cs.uni-bonn.de"
] | dieckman@cs.uni-bonn.de |
187e56e212fcf47bff0b692150224f5c3eb39334 | 72d740ddb5fa5aa88874b197d3352cc899f3fca6 | /SPOJ/BRCKTS.cpp | 158e94ad2ee3eff45d746b15653edef9b42f2bc4 | [] | no_license | abdullaAshraf/Problem-Solving | b632dabfc40ce7333b6c86deb1384e7834835934 | f89f334b36f8294f1a5aef228723a666c6fc788e | refs/heads/master | 2018-09-18T06:14:44.792582 | 2018-08-19T05:37:24 | 2018-08-19T05:37:24 | 112,501,076 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,184 | cpp | /*
Author: Abdulla Ashraf
Idea:
-keep 2 paramters for every node in the segment tree , how many unmatched left and right facing bracktes
-when conecting 2 segments match as much unmatched bracktes as possible
-answer is the answer for the whole segmet tree which exist at 1.
*/
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define sz(x) ((int)(x).size())
#define sqr(x) ((x) * (x))
#define INF ((int)1e9)
typedef long long ll;
const double PI = acos(-1.0);
const double EPS = 1e-9;
const int N = (1 << 15);
const int OO = 200000;
char w[N+2];
int n,m,t;
int tree[2 * N][2];
void build(int cur, int l, int r)
{
if (l == r)
{
if(l > n)
tree[cur][0] = tree[cur][1] = 0;
else
{
tree[cur][0] = (w[l-1] == ')' ? 1 : 0);
tree[cur][1] = 1 - tree[cur][0];
}
return;
}
int left = 2 * cur;
int right = 2 * cur + 1;
int mid = (l + r) / 2;
build(left, l, mid);
build(right, mid + 1, r);
tree[cur][0] = tree[left][0]+ max(0,tree[right][0]-tree[left][1]);
tree[cur][1] = tree[right][1]+ max(0,tree[left][1]-tree[right][0]);
}
void update(int cur, int l, int r, int ind)
{
if (ind < l || ind > r)
return;
if (l == r && ind == l)
{
tree[cur][0] = 1 - tree[cur][0];
tree[cur][1] = 1 - tree[cur][1];
return;
}
int left = 2 * cur;
int right = 2 * cur + 1;
int mid = (l + r) / 2;
update(left, l, mid, ind);
update(right, mid + 1, r, ind);
tree[cur][0] = tree[left][0]+ max(0,tree[right][0]-tree[left][1]);
tree[cur][1] = tree[right][1]+ max(0,tree[left][1]-tree[right][0]);
}
int main()
{
for(int tt =1 ; tt<=10; tt++)
{
printf("Test %d:\n",tt);
scanf("%d",&n);
scanf("%s", &w);
scanf("%d",&m);
build(1,1,N);
while(m--)
{
scanf("%d",&t);
if(t)
update(1,1,N,t);
else if(tree[1][0] == 0 && tree[1][1] == 0)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
| [
"noreply@github.com"
] | abdullaAshraf.noreply@github.com |
45ecc2633cc89a85275a52e03bf2d9f486f2b1b5 | 146d64aa4de1ddd14995ed3c9aaaa08ac8c6a92b | /all-cpp-files-v2/doctors.cpp | 67dde7f434c1e2ba20d98fbf846cfd9d8311ecab | [] | no_license | orestotel/hacktoberfest-ProjectCPlusPlus | 09edc23a3a9f1d148fe623f105b67398744c0dc3 | baabde9f6957cb108f5208ebba0c194b96687a32 | refs/heads/master | 2021-07-10T15:49:15.890975 | 2019-12-28T10:02:46 | 2019-12-28T10:02:46 | 206,317,639 | 1 | 7 | null | 2020-10-02T13:23:54 | 2019-09-04T12:47:44 | C++ | UTF-8 | C++ | false | false | 1,054 | cpp | ...
//beginning to be added
void print(People**a, int u,string ill){
for(int i=0;i<1;i++){
Patient*p=dynamiccast-Patient*>(a[i]);
if(p!=null){
o=(Patient*)(a[i]);
if(p->getIllness()==ill){
p->output(cout);
}
}
}
}
//створити базовий тип транспортний засіб
//рік випуску, назва
//два похідні типи
//пасажирський транспорт
//(місткість, вартість переїзду)
//
//Вантажний транспорт
//(об'єм перевезення, допустима вага)
//
//створити масив вказівників на батьківський тип
//1)посортувати їх за роком випуску
//2)Знайти пасажирський транспорт з максимальною пасажировмісткістю
//3)Вивести всі вантажні транспортні засоби з об'ємом перевезення, більшим за вказаний
| [
"orekpk@gmail.com"
] | orekpk@gmail.com |
2b2f23f6311a218ece59319a2521ba4f1c7a9529 | 620ad318d120802b5f85616f6d114a790fe1a80a | /XYZ_DBT.cpp | 59e074edc874867d92b9254e74d27e0cd49409f6 | [] | no_license | realbigws/DeepOpen_source | 2b2de98c1c09ca24bcfb8136c4eaf7e6ec0ee6de | 2802ea4f7cdce35f968ec1dae8f04336a5b49a37 | refs/heads/master | 2021-01-21T05:02:37.762274 | 2018-12-04T12:46:42 | 2018-12-04T12:46:42 | 39,541,440 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,209 | cpp | #include "XYZ_DBT.h"
//--------------constructor--------------------//
XYZ_DBT::XYZ_DBT(void)
{
//init_process (determine_first_three)
cle_X_Axis[0]=1.0;
cle_X_Axis[1]=0.0;
cle_X_Axis[2]=0.0;
cle_Z_Axis[0]=0.0;
cle_Z_Axis[1]=0.0;
cle_Z_Axis[2]=1.0;
}
XYZ_DBT::~XYZ_DBT(void)
{
}
//--------------- function ----------------//
void XYZ_DBT::xyz_to_dbt(double *dist,double *bend,double *tort,int n,XYZ *r)
{
int i,j;
double x0,x1,y0,y1;
double b,t;
//------------------//
//----real_start---//[0-2]
//----------------//
//calculate_bend
(r[1]-r[0]).xyz2double(cle_x_point[0]);
x0=sqrt(dot(cle_x_point[0],cle_x_point[0]));
(r[2]-r[1]).xyz2double(cle_x_point[1]);
x1=sqrt(dot(cle_x_point[1],cle_x_point[1]));
cross(cle_y_point[0],cle_x_point[0],cle_x_point[1]);
y0=sqrt(dot(cle_y_point[0],cle_y_point[0]));
b=dot(cle_x_point[0],cle_x_point[1])/x0/x1;
b=limit(b,-1.0,1.0);
cle_w_point[0]=acos(1.0*b);
//evaluate
if(dist!=NULL)dist[0]=-1.0;
if(dist!=NULL)dist[1]=x0;
if(dist!=NULL)dist[2]=x1;
if(bend!=NULL)bend[0]=-9.9;
if(bend!=NULL)bend[1]=-9.9;
if(bend!=NULL)bend[2]=cle_w_point[0];
if(tort!=NULL)tort[0]=-9.9;
if(tort!=NULL)tort[1]=-9.9;
if(tort!=NULL)tort[2]=-9.9;
//update
x0=x1;
for(j=0;j<3;j++)cle_x_point[0][j]=cle_x_point[1][j];
//--------------------//
//----real_process---//[3-n]
//------------------//
for(i=3;i<n;i++)
{
//calculate_tort
(r[i]-r[i-1]).xyz2double(cle_x_point[1]);
x1=sqrt(dot(cle_x_point[1],cle_x_point[1]));
cross(cle_y_point[1],cle_x_point[0],cle_x_point[1]);
y1=sqrt(dot(cle_y_point[1],cle_y_point[1]));
t=dot(cle_y_point[0],cle_y_point[1])/y0/y1;
t=limit(t,-1.0,1.0);
t=acos(1.0*t);
if(dot(cle_y_point[0],cle_x_point[1])<0.0) t*=-1.0;
cle_w_point[1]=t;
//calculate_bend
b=dot(cle_x_point[0],cle_x_point[1])/x0/x1;
b=limit(b,-1.0,1.0);
cle_w_point[2]=acos(1.0*b);
//evaluate
if(dist!=NULL)dist[i]=x1;
if(bend!=NULL)bend[i]=cle_w_point[2];
if(tort!=NULL)tort[i]=cle_w_point[1];
//update
x0=x1;
y0=y1;
for(j=0;j<3;j++)cle_x_point[0][j]=cle_x_point[1][j];
for(j=0;j<3;j++)cle_y_point[0][j]=cle_y_point[1][j];
cle_w_point[0]=cle_w_point[2];
}
}
void XYZ_DBT::dbt_to_xyz(double *dist,double *bend,double *tort,int n,XYZ *r)
{
int i;
double radi;
XYZ xyz;
xyz=0.0;
//real_process//
Matrix_Unit(cle_T_Back,1.0);
for(i=0;i<n;i++)
{
radi=dist[i];
if(i==0)
{
r[i]=0.0;
}
else if(i==1)
{
r[i]=0.0;
r[i].X=radi;
}
else if(i==2)
{
Universal_Rotation(cle_Z_Axis,bend[i],cle_R_Theta);
Vector_Dot(cle_D_Back,radi,cle_X_Axis,3);
Matrix_Multiply(cle_T_Pre,cle_T_Back,cle_R_Theta);
Vector_Multiply(cle_D_Pre,cle_T_Pre,cle_D_Back);
Matrix_Equal(cle_T_Back,cle_T_Pre);
xyz.double2xyz(cle_D_Pre);
r[i]=r[i-1]+xyz;
}
else
{
Universal_Rotation(cle_Z_Axis,bend[i],cle_R_Theta);
Universal_Rotation(cle_X_Axis,tort[i],cle_R_Thor);
Vector_Dot(cle_D_Back,radi,cle_X_Axis,3);
Matrix_Multiply(cle_temp,cle_R_Thor,cle_R_Theta);
Matrix_Multiply(cle_T_Pre,cle_T_Back,cle_temp);
Vector_Multiply(cle_D_Pre,cle_T_Pre,cle_D_Back);
Matrix_Equal(cle_T_Back,cle_T_Pre);
xyz.double2xyz(cle_D_Pre);
r[i]=r[i-1]+xyz;
}
}
}
| [
"realbigws@gmail.com"
] | realbigws@gmail.com |
820277d0ee813ab422dc5ed4fc3ec805f7e9bc8e | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/shell/ext/ratings/msrating/mslubase.cpp | 53c94d8755a7f672e46e2347d6c21c8aafc43757 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 32,951 | cpp | /****************************************************************************\
*
* MSLUBASE.C --Structures for holding pics information
*
* Created: Jason Thomas
* Updated: Ann McCurdy
*
\****************************************************************************/
/*Includes------------------------------------------------------------------*/
#include "msrating.h"
#include "mslubase.h"
#include "reghive.h" // CRegistryHive
#include "debug.h"
#include <buffer.h>
#include <regentry.h>
#include <mluisupp.h>
/*Helpers-------------------------------------------------------------------*/
char PicsDelimChar='/';
int MyMessageBox(HWND hwnd, LPCSTR pszText, UINT uTitle, UINT uType)
{
CHAR szTitle[MAXPATHLEN];
MLLoadStringA(uTitle, szTitle, sizeof(szTitle));
return MessageBox(hwnd, pszText, szTitle, uType);
}
int MyMessageBox(HWND hwnd, UINT uText, UINT uTitle, UINT uType)
{
CHAR szText[MAXPATHLEN];
MLLoadStringA(uText, szText, sizeof(szText));
return MyMessageBox(hwnd, szText, uTitle, uType);
}
/* Variant for long messages: uText2 message will be concatenated onto the end
* of uText before display. Message text should contain \r\n or other desired
* separators, this function won't add them.
*/
int MyMessageBox(HWND hwnd, UINT uText, UINT uText2, UINT uTitle, UINT uType)
{
CHAR szText[MAXPATHLEN*2] = { 0 };
MLLoadStringA(uText, szText, sizeof(szText));
/* Using lstrlen in case MLLoadString really returns a count of CHARACTERS,
* on a DBCS system...
*/
UINT cbFirst = lstrlen(szText);
MLLoadStringA(uText2, szText + cbFirst, sizeof(szText) - cbFirst);
return MyMessageBox(hwnd, szText, uTitle, uType);
}
/*******************************************************************
NAME: MyRegDeleteKey
********************************************************************/
LONG MyRegDeleteKey(HKEY hkey,LPCSTR pszSubkey)
{
DWORD dwError;
TraceMsg( TF_ALWAYS, "MyRegDeleteKey() - Deleting Subkey='%s'...", pszSubkey );
dwError = SHDeleteKey( hkey, pszSubkey );
if ( dwError != ERROR_SUCCESS )
{
TraceMsg( TF_WARNING, "MyRegDeleteKey() - Failed to Delete Subkey='%s' dwError=%d!", pszSubkey, dwError );
}
return dwError;
}
BOOL MyAtoi(char *pIn, int *pi)
{
char *pc;
ASSERT(pIn);
*pi = 0;
pc = NonWhite(pIn);
if (!pc)
return FALSE;
if (*pc < '0' || *pc > '9')
return FALSE;
int accum = 0;
while (*pc >= '0' && *pc <= '9')
{
accum = accum * 10 + (*pc - '0');
pc++;
}
*pi = accum;
return TRUE;
}
/*Simple types--------------------------------------------------------------*/
/* ETN */
#ifdef DEBUG
void ETN::Set(int rIn){
Init();
r = rIn;
}
int ETN::Get(){
return r;
}
#endif
ETN* ETN::Duplicate(){
ETN *pETN=new ETN;
if (fIsInit()) pETN->Set(Get());
return pETN;
}
/* ETB */
#ifdef DEBUG
BOOL ETB::Get()
{
ASSERT(fIsInit());
return m_nFlags & ETB_VALUE;
}
void ETB::Set(BOOL b)
{
m_nFlags = ETB_ISINIT | (b ? ETB_VALUE : 0);
}
#endif
ETB* ETB::Duplicate()
{
ASSERT(fIsInit());
ETB *pETB = new ETB;
if (pETB != NULL)
pETB->m_nFlags = m_nFlags;
return pETB;
}
/* ETS */
ETS::~ETS()
{
if (pc != NULL) {
delete pc;
pc = NULL;
}
}
#ifdef DEBUG
char* ETS::Get()
{
// ASSERT(fIsInit());
return pc;
}
#endif
void ETS::Set(const char *pIn)
{
if (pc != NULL)
delete pc;
if (pIn != NULL) {
pc = new char[strlenf(pIn) + 1];
if (pc != NULL) {
strcpyf(pc, pIn);
}
}
else {
pc = NULL;
}
}
void ETS::SetTo(char *pIn)
{
if (pc != NULL)
delete pc;
pc = pIn;
}
ETS* ETS::Duplicate()
{
ETS *pETS=new ETS;
if (pETS != NULL)
pETS->Set(Get());
return pETS;
}
UINT EtBoolRegRead(ETB &etb, HKEY hKey, char *pKeyWord)
{
ASSERT(pKeyWord);
if ( ! pKeyWord )
{
TraceMsg( TF_ERROR, "EtBoolRegRead() - pKeyWord is NULL!" );
return ERROR_INVALID_PARAMETER;
}
DWORD dwSize, dwValue, dwType;
UINT uErr;
etb.Set(FALSE);
dwSize = sizeof(dwValue);
uErr = RegQueryValueEx(hKey, pKeyWord, NULL, &dwType,
(LPBYTE)&dwValue, &dwSize);
if (uErr == ERROR_SUCCESS)
{
if ((dwType == REG_DWORD) && (dwValue != 0))
etb.Set(TRUE);
}
else
{
TraceMsg( TF_WARNING, "EtBoolRegRead() - Failed to read pKeyWord='%s'!", pKeyWord );
}
return uErr;
}
UINT EtBoolRegWrite(ETB &etb, HKEY hKey, char *pKeyWord)
{
ASSERT(pKeyWord);
if ( ! pKeyWord )
{
TraceMsg( TF_ERROR, "EtBoolRegWrite() - pKeyWord is NULL!" );
return ERROR_INVALID_PARAMETER;
}
UINT uErr;
DWORD dwNum = (etb.fIsInit() && etb.Get());
uErr = RegSetValueEx(hKey, pKeyWord, 0, REG_DWORD, (LPBYTE)&dwNum, sizeof(dwNum));
if ( uErr != ERROR_SUCCESS )
{
TraceMsg( TF_WARNING, "EtBoolRegWrite() - Failed to set pKeyWord='%s'!", pKeyWord );
}
return uErr;
}
UINT EtStringRegRead(ETS &ets, HKEY hKey, char *pKeyWord)
{
ASSERT(pKeyWord);
if ( ! pKeyWord )
{
TraceMsg( TF_ERROR, "EtStringRegRead() - pKeyWord is NULL!" );
return ERROR_INVALID_PARAMETER;
}
DWORD dwSize;
UINT uErr;
char szTemp[80]; /* default size */
dwSize = sizeof(szTemp);
uErr = RegQueryValueEx(hKey, pKeyWord, NULL, NULL,
(LPBYTE)szTemp, &dwSize);
if (uErr == ERROR_SUCCESS)
{
ets.Set(szTemp);
}
else if (uErr == ERROR_MORE_DATA)
{
char *pszTemp = new char[dwSize];
if (pszTemp == NULL)
{
TraceMsg( TF_WARNING, "EtStringRegRead() - Failed to allocate dwSize=%d memory!", dwSize );
uErr = ERROR_NOT_ENOUGH_MEMORY;
}
else
{
uErr = RegQueryValueEx(hKey, pKeyWord, NULL, NULL, (LPBYTE)pszTemp,
&dwSize);
if (uErr == ERROR_SUCCESS)
{
ets.SetTo(pszTemp);
/* ets now owns pszTemp memory, don't delete it here */
}
else
{
TraceMsg( TF_WARNING, "EtStringRegRead() - Failed to read (dwSize %d) pKeyWord='%s'!", dwSize, pKeyWord );
delete pszTemp;
pszTemp = NULL;
}
}
}
else
{
TraceMsg( TF_WARNING, "EtStringRegRead() - Failed to read pKeyWord='%s'!", pKeyWord );
}
return uErr;
}
UINT EtStringRegWrite(ETS &ets, HKEY hKey, char *pKeyWord)
{
ASSERT(pKeyWord);
if ( ! pKeyWord )
{
TraceMsg( TF_ERROR, "EtStringRegWrite() - pKeyWord is NULL!" );
return ERROR_INVALID_PARAMETER;
}
UINT uErr = ERROR_SUCCESS;
if (ets.fIsInit())
{
uErr = RegSetValueEx(hKey, pKeyWord, 0, REG_SZ, (LPBYTE)ets.Get(), strlenf(ets.Get())+1);
if ( uErr != ERROR_SUCCESS )
{
TraceMsg( TF_WARNING, "EtStringRegWrite() - Failed to set pKeyWord='%s' with ets='%s'!", pKeyWord, ets.Get() );
}
}
else
{
TraceMsg( TF_ERROR, "EtStringRegWrite() - ETS is not initialized!" );
}
return uErr;
}
UINT EtNumRegRead(ETN &etn, HKEY hKey, char *pKeyWord)
{
ASSERT(pKeyWord);
if ( ! pKeyWord )
{
TraceMsg( TF_ERROR, "EtNumRegRead() - pKeyWord is NULL!" );
return ERROR_INVALID_PARAMETER;
}
DWORD dwSize, dwType;
int nValue;
UINT uErr;
dwSize = sizeof(nValue);
uErr = RegQueryValueEx(hKey, pKeyWord, NULL, &dwType,
(LPBYTE)&nValue, &dwSize);
if (uErr == ERROR_SUCCESS)
{
etn.Set(nValue);
}
else
{
TraceMsg( TF_WARNING, "EtNumRegRead() - Failed to read pKeyWord='%s'!", pKeyWord );
}
return uErr;
}
UINT EtNumRegWrite(ETN &etn, HKEY hKey, char *pKeyWord)
{
UINT uErr = ERROR_SUCCESS;
if (etn.fIsInit())
{
int nTemp;
nTemp = etn.Get();
uErr = RegSetValueEx(hKey, pKeyWord, 0, REG_DWORD, (LPBYTE)&nTemp, sizeof(nTemp));
if ( uErr != ERROR_SUCCESS )
{
TraceMsg( TF_WARNING, "EtNumRegWrite() - Failed to set pKeyWord='%s' with nTemp=%d!", pKeyWord, nTemp );
}
}
else
{
TraceMsg( TF_ERROR, "EtNumRegWrite() - ETS is not initialized!" );
}
return uErr;
}
/*PicsDefault---------------------------------------------------------------*/
PicsDefault::PicsDefault()
{
/* nothing to do but construct members */
}
PicsDefault::~PicsDefault()
{
/* nothing to do but destruct members */
}
/*PicsEnum------------------------------------------------------------------*/
PicsEnum::PicsEnum()
{
/* nothing to do but construct members */
}
PicsEnum::~PicsEnum()
{
/* nothing to do but destruct members */
}
/*PicsCategory--------------------------------------------------------------*/
PicsCategory::PicsCategory()
{
/* nothing to do but construct members */
}
PicsCategory::~PicsCategory()
{
arrpPC.DeleteAll();
arrpPE.DeleteAll();
}
/*PicsRatingSystem----------------------------------------------------------*/
PicsRatingSystem::PicsRatingSystem()
: m_pDefaultOptions(NULL),
dwFlags(0),
nErrLine(0)
{
/* nothing to do but construct members */
}
PicsRatingSystem::~PicsRatingSystem()
{
arrpPC.DeleteAll();
if (m_pDefaultOptions != NULL)
{
delete m_pDefaultOptions;
m_pDefaultOptions = NULL;
}
}
void PicsRatingSystem::ReportError(HRESULT hres)
{
NLS_STR nls1(etstrFile.Get());
if (!nls1.QueryError())
{
ISTR istrMarker(nls1);
if (nls1.strchr(&istrMarker, '*'))
{
nls1.DelSubStr(istrMarker);
}
}
else
{
nls1 = szNULL;
}
UINT idMsg, idTemplate;
NLS_STR nlsBaseMessage(MAX_RES_STR_LEN);
char szNumber[16]; /* big enough for a 32-bit (hex) number */
if (hres == E_OUTOFMEMORY || (hres > RAT_E_BASE && hres <= RAT_E_BASE + 0xffff)) {
idTemplate = IDS_LOADRAT_SYNTAX_TEMPLATE; /* default is ratfile content error */
switch (hres)
{
case E_OUTOFMEMORY:
idMsg = IDS_LOADRAT_MEMORY;
idTemplate = IDS_LOADRAT_GENERIC_TEMPLATE;
break;
case RAT_E_EXPECTEDLEFT:
idMsg = IDS_LOADRAT_EXPECTEDLEFT;
break;
case RAT_E_EXPECTEDRIGHT:
idMsg = IDS_LOADRAT_EXPECTEDRIGHT;
break;
case RAT_E_EXPECTEDTOKEN:
idMsg = IDS_LOADRAT_EXPECTEDTOKEN;
break;
case RAT_E_EXPECTEDSTRING:
idMsg = IDS_LOADRAT_EXPECTEDSTRING;
break;
case RAT_E_EXPECTEDNUMBER:
idMsg = IDS_LOADRAT_EXPECTEDNUMBER;
break;
case RAT_E_EXPECTEDBOOL:
idMsg = IDS_LOADRAT_EXPECTEDBOOL;
break;
case RAT_E_DUPLICATEITEM:
idMsg = IDS_LOADRAT_DUPLICATEITEM;
break;
case RAT_E_MISSINGITEM:
idMsg = IDS_LOADRAT_MISSINGITEM;
break;
case RAT_E_UNKNOWNITEM:
idMsg = IDS_LOADRAT_UNKNOWNITEM;
break;
case RAT_E_UNKNOWNMANDATORY:
idMsg = IDS_LOADRAT_UNKNOWNMANDATORY;
break;
case RAT_E_EXPECTEDEND:
idMsg = IDS_LOADRAT_EXPECTEDEND;
break;
default:
ASSERT(FALSE); /* there aren't any other RAT_E_ errors */
idMsg = IDS_LOADRAT_UNKNOWNERROR;
break;
}
wsprintf(szNumber, "%d", nErrLine);
NLS_STR nlsNumber(STR_OWNERALLOC, szNumber);
const NLS_STR *apnls[] = { &nlsNumber, NULL };
nlsBaseMessage.LoadString((USHORT)idMsg, apnls);
}
else
{
idTemplate = IDS_LOADRAT_GENERIC_TEMPLATE;
if (HRESULT_FACILITY(hres) == FACILITY_WIN32)
{
wsprintf(szNumber, "%d", HRESULT_CODE(hres));
idMsg = IDS_LOADRAT_WINERROR;
}
else
{
wsprintf(szNumber, "0x%x", hres);
idMsg = IDS_LOADRAT_MISCERROR;
}
NLS_STR nls1(STR_OWNERALLOC, szNumber);
const NLS_STR *apnls[] = { &nls1, NULL };
nlsBaseMessage.LoadString((USHORT)idMsg, apnls);
}
NLS_STR nlsMessage(MAX_RES_STR_LEN);
const NLS_STR *apnls[] = { &nls1, &nlsBaseMessage, NULL };
nlsMessage.LoadString((USHORT)idTemplate, apnls);
if (!nlsMessage.QueryError())
{
MyMessageBox(NULL, nlsMessage.QueryPch(), IDS_GENERIC, MB_OK | MB_ICONWARNING);
}
}
/*Rating Information--------------------------------------------------------*/
BOOL PicsRatingSystemInfo::LoadProviderFiles(HKEY hKey)
{
char szFileName[8 + 7 + 1]; /* "Filename" + big number plus null byte */
ETS etstrFileName;
int index = 0;
EtStringRegRead(etstrRatingBureau, hKey, (char *)szRATINGBUREAU);
wsprintf(szFileName, szFilenameTemplate, index);
while (EtStringRegRead(etstrFileName, hKey, szFileName) == ERROR_SUCCESS)
{
PicsRatingSystem *pPRS;
HRESULT hres = LoadRatingSystem(etstrFileName.Get(), &pPRS);
if (pPRS != NULL)
{
arrpPRS.Append(pPRS);
/* If the thing has a pathname, write it back out to the policy
* file, in case loading the rating system marked it as invalid
* (or it had been marked as invalid, but the user fixed things
* and it's OK now).
*/
if (pPRS->etstrFile.fIsInit())
{
/* If the rating system is not valid and was not previously
* marked invalid, then report the error to the user.
* LoadRatingSystem will have already marked the filename
* as invalid for us.
*/
if ((pPRS->dwFlags & (PRS_ISVALID | PRS_WASINVALID)) == 0)
{
pPRS->ReportError(hres); /* report error to user */
}
EtStringRegWrite(pPRS->etstrFile, hKey, szFileName);
}
}
index++;
wsprintf(szFileName, szFilenameTemplate, index);
}
return arrpPRS.Length() != 0;
}
BOOL RunningOnNT()
{
return !(::GetVersion() & 0x80000000);
}
// Verify the Registry Key for the Ratings can be opened with full access.
// This is only useful if the Ratings registry key has been previously created.
bool IsRegistryModifiable( HWND p_hwndParent )
{
bool fReturn = false;
CRegKey regKey;
if ( regKey.Open( HKEY_LOCAL_MACHINE, ::szRATINGS, KEY_ALL_ACCESS ) == ERROR_SUCCESS )
{
fReturn = true;
}
else
{
TraceMsg( TF_WARNING, "IsRegistryModifiable() - Failed to Create Registry Key Ratings for Full Access!" );
MyMessageBox( p_hwndParent, IDS_REGISTRY_NOT_MODIFIABLE, IDS_GENERIC, MB_OK|MB_ICONERROR);
}
return fReturn;
}
SID_IDENTIFIER_AUTHORITY siaNTAuthority = SECURITY_NT_AUTHORITY;
SID_IDENTIFIER_AUTHORITY siaWorldAuthority = SECURITY_WORLD_SID_AUTHORITY;
class CSecurityAttributes
{
private:
SECURITY_ATTRIBUTES m_sa;
LPSECURITY_ATTRIBUTES m_lpsa;
PSECURITY_DESCRIPTOR m_psd;
PACL m_pACL;
PSID m_psidAdmins;
PSID m_psidWorld;
UINT m_cbACL; /* default ACL size */
public:
CSecurityAttributes()
{
m_lpsa = NULL;
m_psd = NULL;
m_pACL = NULL;
m_psidAdmins = NULL;
m_psidWorld = NULL;
m_cbACL = 1024;
}
~CSecurityAttributes()
{
if ( m_psidAdmins != NULL )
{
FreeSid(m_psidAdmins);
m_psidAdmins = NULL;
}
if ( m_psidWorld )
{
FreeSid(m_psidWorld);
m_psidWorld = NULL;
}
if ( m_psd )
{
MemFree(m_psd);
m_psd = NULL;
}
if ( m_pACL )
{
MemFree(m_pACL);
m_pACL = NULL;
}
}
LPSECURITY_ATTRIBUTES GetSecurityAttributes( void )
{
return m_lpsa;
}
bool AllocateSecurityAttributes( void )
{
m_psd = (PSECURITY_DESCRIPTOR)MemAlloc(SECURITY_DESCRIPTOR_MIN_LENGTH);
if (m_psd == NULL ||
!InitializeSecurityDescriptor(m_psd, SECURITY_DESCRIPTOR_REVISION))
{
TraceMsg( TF_ERROR, "CSecurityAttributes::AllocateSecurityAttributes() - Failed Security Descriptor Allocation!" );
return false;
}
m_pACL = (PACL)MemAlloc(m_cbACL);
if (m_pACL == NULL || !InitializeAcl(m_pACL, m_cbACL, ACL_REVISION2))
{
TraceMsg( TF_ERROR, "CSecurityAttributes::AllocateSecurityAttributes() - Failed ACL Initialization!" );
return false;
}
if (!AllocateAndInitializeSid(&siaNTAuthority,
2, /* number of subauthorities */
SECURITY_BUILTIN_DOMAIN_RID, /* first subauthority: this domain */
DOMAIN_ALIAS_RID_ADMINS, /* second: admins local group */
0, 0, 0, 0, 0, 0, /* unused subauthorities */
&m_psidAdmins))
{
TraceMsg( TF_ERROR, "CSecurityAttributes::AllocateSecurityAttributes() - Failed NT Authority Initialization!" );
return false;
}
if (!AllocateAndInitializeSid(&siaWorldAuthority,
1, /* number of subauthorities */
SECURITY_WORLD_RID, /* first subauthority: all users */
0, 0, 0, 0, 0, 0, 0, /* unused subauthorities */
&m_psidWorld))
{
TraceMsg( TF_ERROR, "CSecurityAttributes::AllocateSecurityAttributes() - Failed World Authority Initialization!" );
return false;
}
if (!AddAccessAllowedAce(m_pACL, ACL_REVISION2, KEY_ALL_ACCESS, m_psidAdmins) ||
!AddAccessAllowedAce(m_pACL, ACL_REVISION2, KEY_READ, m_psidWorld))
{
TraceMsg( TF_ERROR, "CSecurityAttributes::AllocateSecurityAttributes() - Failed Admins or World Access!" );
return false;
}
ACE_HEADER *pAce;
/* Make both ACEs inherited by subkeys created later */
if (GetAce(m_pACL, 0, (LPVOID *)&pAce))
{
pAce->AceFlags |= CONTAINER_INHERIT_ACE;
}
if (GetAce(m_pACL, 1, (LPVOID *)&pAce))
{
pAce->AceFlags |= CONTAINER_INHERIT_ACE;
}
if (!SetSecurityDescriptorDacl(m_psd,
TRUE, /* fDaclPresent */
m_pACL,
FALSE)) /* not a default discretionary ACL */
{
TraceMsg( TF_ERROR, "CSecurityAttributes::AllocateSecurityAttributes() - Failed Set of Security Descriptor!" );
return false;
}
m_sa.nLength = sizeof(m_sa);
m_sa.lpSecurityDescriptor = m_psd;
m_sa.bInheritHandle = FALSE;
m_lpsa = &m_sa;
return true;
}
};
// The following first attempts to open an existing registry key.
// If the key cannot be opened, the key is created.
// Under NT, the key is created with Admin read-write access and World read-only access.
// Under 9x, the key is created with no special security attributes.
HKEY CreateRegKeyNT(LPCSTR pszKey)
{
HKEY hKey = NULL;
LONG err = RegOpenKey(HKEY_LOCAL_MACHINE, pszKey, &hKey);
if (err == ERROR_SUCCESS)
{
TraceMsg( TF_ALWAYS, "CreateRegKeyNT() - Successfully Opened Ratings Registry Key." );
return hKey;
}
CSecurityAttributes sa;
if (RunningOnNT())
{
if ( ! sa.AllocateSecurityAttributes() )
{
TraceMsg( TF_ERROR, "CreateRegKeyNT() - Failed to allocate security attributes()!" );
return NULL;
}
}
DWORD dwDisp;
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, pszKey, NULL, "",
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, sa.GetSecurityAttributes(),
&hKey, &dwDisp) != ERROR_SUCCESS)
{
TraceMsg( TF_ERROR, "CreateRegKeyNT() - Failed Registry Key Creation with %s Security Attributes!", sa.GetSecurityAttributes() ? "<sa>" : "<NULL>" );
hKey = NULL;
}
return hKey;
}
HKEY PicsRatingSystemInfo::GetUserProfileKey( void )
{
HKEY hkeyUser = NULL;
// HKLM\System\CurrentControlSet\Control\Update
RegEntry re(szPOLICYKEY, HKEY_LOCAL_MACHINE);
// UpdateMode
if (re.GetNumber(szPOLICYVALUE) != 0)
{
// HKLM\Network\Logon
RegEntry reLogon(szLogonKey, HKEY_LOCAL_MACHINE);
// UserProfiles
if (reLogon.GetNumber(szUserProfiles) != 0)
{
/* The ratings key has the supervisor password and maybe other
* settings. To see if there are other settings here, try to
* find the user subkey (".Default"). If it's not there, we'll
* try a policy file.
*/
// HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Ratings
if (RegOpenKey(HKEY_LOCAL_MACHINE, szRATINGS, &hkeyUser) == ERROR_SUCCESS)
{
HKEY hkeyTemp;
// .Default
if (RegOpenKey(hkeyUser, szDefaultUserName, &hkeyTemp) == ERROR_SUCCESS)
{
RegCloseKey(hkeyTemp);
hkeyTemp = NULL;
}
else
{
TraceMsg( TF_WARNING, "PicsRatingSystemInfo::GetUserProfileKey() - Failed to Open key szDefaultUserName='%s'!", szDefaultUserName );
RegCloseKey(hkeyUser);
hkeyUser = NULL;
}
}
else
{
TraceMsg( TF_WARNING, "PicsRatingSystemInfo::GetUserProfileKey() - Failed to Open key szRATINGS='%s'!", szRATINGS );
}
}
else
{
TraceMsg( TF_WARNING, "PicsRatingSystemInfo::GetUserProfileKey() - No key szLogonKey='%s' szUserProfiles='%s'!", szLogonKey, szUserProfiles );
}
}
else
{
TraceMsg( TF_WARNING, "PicsRatingSystemInfo::GetUserProfileKey() - No key szPOLICYKEY='%s' szPOLICYVALUE='%s'!", szPOLICYKEY, szPOLICYVALUE );
}
return hkeyUser;
}
BOOL PicsRatingSystemInfo::Init( void )
{
PicsUser *pPU = NULL;
BOOL fRet = TRUE;
BOOL fIsNT;
HKEY hkeyUser = NULL;
CRegistryHive rh;
fRatingInstalled = FALSE;
pUserObject = NULL;
fIsNT = RunningOnNT();
if (fIsNT)
{
hkeyUser = CreateRegKeyNT(::szRATINGS);
fStoreInRegistry = TRUE;
}
else
{
hkeyUser = GetUserProfileKey();
if (hkeyUser != NULL)
{
fStoreInRegistry = TRUE;
}
else
{
fStoreInRegistry = FALSE;
if ( rh.OpenHiveFile( false ) )
{
hkeyUser = rh.GetHiveKey();
}
}
}
// read information from whatever key we opened
if (hkeyUser != NULL)
{
//First load the rating files, then load the user names.
fRatingInstalled = LoadProviderFiles(hkeyUser);
if ( fRatingInstalled )
{
TraceMsg( TF_ALWAYS, "PicsRatingSystemInfo::Init() - Ratings Installed!" );
}
else
{
TraceMsg( TF_ALWAYS, "PicsRatingSystemInfo::Init() - Ratings Not Installed!" );
}
pPU = new PicsUser;
if (pPU != NULL)
{
pPU->ReadFromRegistry(hkeyUser, (char *)szDefaultUserName);
pUserObject = pPU;
}
else
{
fRet = FALSE;
}
RegCloseKey(hkeyUser);
hkeyUser = NULL;
/* Make sure the user settings have defaults for all installed
* rating systems.
*/
for (int i=0; i<arrpPRS.Length(); i++)
{
CheckUserSettings(arrpPRS[i]);
}
}
else
{
TraceMsg( TF_WARNING, "PicsRatingSystemInfo::Init() - hkeyUser is NULL!" );
}
rh.UnloadHive();
/* Check to see if there is a supervisor password set. If there is,
* but we have no settings, then someone's been tampering.
*/
if ( SUCCEEDED( VerifySupervisorPassword() ) && ! fRatingInstalled )
{
MyMessageBox(NULL, IDS_NO_SETTINGS, IDS_GENERIC, MB_OK | MB_ICONSTOP);
// Clear out the password to allow the user to modify the ratings.
RemoveSupervisorPassword();
fSettingsValid = FALSE;
}
else
{
fSettingsValid = TRUE;
}
return fRet;
}
BOOL PicsRatingSystemInfo::FreshInstall()
{
PicsUser *pPU = NULL;
pPU = new PicsUser;
if (pPU != NULL)
{
pPU->NewInstall();
pUserObject = pPU;
fRatingInstalled = TRUE; // we have settings now
return TRUE;
}
else
{
return FALSE;
}
}
extern HANDLE g_hsemStateCounter; // created at process attatch time
long GetStateCounter()
{
long count;
if (ReleaseSemaphore(g_hsemStateCounter, 1, &count)) // poll and bump the count
{
WaitForSingleObject(g_hsemStateCounter, 0); // reduce the count
}
else
{
count = -1;
}
return count;
}
void BumpStateCounter()
{
ReleaseSemaphore(g_hsemStateCounter, 1, NULL); // bump the count
}
// check the global semaphore count to see if we need to reconstruct our
// state.
void CheckGlobalInfoRev(void)
{
ENTERCRITICAL;
if (gPRSI != NULL && !g_fIsRunningUnderCustom)
{ // do not reinit if under Custom
if (gPRSI->nInfoRev != GetStateCounter())
{
delete gPRSI;
gPRSI = new PicsRatingSystemInfo;
if (gPRSI != NULL)
{
gPRSI->Init();
}
CleanupRatingHelpers();
InitRatingHelpers();
}
}
LEAVECRITICAL;
}
void PicsRatingSystemInfo::SaveRatingSystemInfo()
{
int z;
HKEY hkeyUser = NULL;
CRegistryHive rh;
char szFileName[MAXPATHLEN];
if (!fSettingsValid || !fRatingInstalled)
{
TraceMsg( TF_WARNING, "PicsRatingSystemInfo::SaveRatingSystemInfo() - Ratings are not installed!" );
return; /* ratings aren't installed, nothing to save */
}
// load the hive file
if (fStoreInRegistry)
{
hkeyUser = CreateRegKeyNT(::szRATINGS);
}
else
{
if ( rh.OpenHiveFile( true ) )
{
hkeyUser = rh.GetHiveKey();
}
}
// read information from local registry
if (hkeyUser != NULL)
{
if (etstrRatingBureau.fIsInit())
{
EtStringRegWrite(etstrRatingBureau, hkeyUser, (char *)szRATINGBUREAU);
}
else
{
RegDeleteValue(hkeyUser, szRATINGBUREAU);
}
for (z = 0; z < arrpPRS.Length(); ++z)
{
wsprintf(szFileName, szFilenameTemplate, z);
EtStringRegWrite(arrpPRS[z]->etstrFile, hkeyUser, szFileName);
}
// Delete the next one, as a safety precaution
wsprintf(szFileName, szFilenameTemplate, z);
RegDeleteValue(hkeyUser, szFileName);
pUserObject->WriteToRegistry(hkeyUser);
RegCloseKey(hkeyUser);
hkeyUser = NULL;
}
else
{
TraceMsg( TF_ERROR, "PicsRatingSystemInfo::SaveRatingSystemInfo() - hkeyUser is NULL!" );
}
BumpStateCounter();
nInfoRev = GetStateCounter();
}
HRESULT LoadRatingSystem(LPCSTR pszFilename, PicsRatingSystem **pprsOut)
{
TraceMsg( TF_ALWAYS, "LoadRatingSystem() - Loading Rating System '%s'...", pszFilename );
PicsRatingSystem *pPRS = new PicsRatingSystem;
*pprsOut = pPRS;
if (pPRS == NULL)
{
TraceMsg( TF_ERROR, "LoadRatingSystem() - pPRS is NULL!" );
return E_OUTOFMEMORY;
}
UINT cbFilename = strlenf(pszFilename) + 1 + 1; /* room for marker character */
LPSTR pszNameCopy = new char[cbFilename];
if (pszNameCopy == NULL)
{
TraceMsg( TF_ERROR, "LoadRatingSystem() - pszNameCopy is NULL!" );
return E_OUTOFMEMORY;
}
strcpyf(pszNameCopy, pszFilename);
pPRS->etstrFile.SetTo(pszNameCopy);
LPSTR pszMarker = strchrf(pszNameCopy, '*');
if (pszMarker != NULL) { /* ended in marker character... */
ASSERT(*(pszMarker+1) == '\0');
pPRS->dwFlags |= PRS_WASINVALID; /* means it failed last time */
*pszMarker = '\0'; /* strip marker for loading */
}
HRESULT hres;
HANDLE hFile = CreateFile(pszNameCopy, GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
DWORD cbFile = ::GetFileSize(hFile, NULL);
BUFFER bufData(cbFile + 1);
if (bufData.QueryPtr() != NULL)
{
LPSTR pszData = (LPSTR)bufData.QueryPtr();
DWORD cbRead;
if (ReadFile(hFile, pszData, cbFile, &cbRead, NULL))
{
pszData[cbRead] = '\0'; /* null terminate whole file */
hres = pPRS->Parse(pszFilename, pszData);
if (SUCCEEDED(hres))
{
pPRS->dwFlags |= PRS_ISVALID;
}
else
{
TraceMsg( TF_WARNING, "LoadRatingSystem() - Failed Parse with hres=0x%x!", hres );
}
}
else
{
hres = HRESULT_FROM_WIN32(::GetLastError());
TraceMsg( TF_WARNING, "LoadRatingSystem() - Failed ReadFile() with hres=0x%x!", hres );
}
CloseHandle(hFile);
}
else
{
hres = E_OUTOFMEMORY;
TraceMsg( TF_WARNING, "LoadRatingSystem() - Failed Buffer Allocation with cbFile=%d!", cbFile );
}
}
else
{
hres = HRESULT_FROM_WIN32(::GetLastError());
TraceMsg( TF_WARNING, "LoadRatingSystem() - Failed CreateFile() with hres=0x%x!", hres );
}
if (!(pPRS->dwFlags & PRS_ISVALID))
{
TraceMsg( TF_ALWAYS, "LoadRatingSystem() - Failed Loaded Rating System '%s' (hres=0x%x)!", pszFilename, hres );
strcatf(pszNameCopy, "*"); /* mark filename as invalid */
}
else
{
TraceMsg( TF_ALWAYS, "LoadRatingSystem() - Successfully Loaded Rating System '%s'.", pszFilename );
}
return hres;
}
// constructor for CustomRatingHelper
CustomRatingHelper::CustomRatingHelper()
{
hLibrary = NULL;
pNextHelper = NULL;
dwSort = 0;
}
CustomRatingHelper::~CustomRatingHelper()
{
if (hLibrary)
{
FreeLibrary(hLibrary);
hLibrary = NULL;
}
pNextHelper = NULL;
}
// a little function to convert from ANSI to Unicode
HRESULT Ansi2Unicode(LPWSTR *pdest, LPCSTR src)
{
UINT cbSize;
cbSize = MultiByteToWideChar(CP_ACP, 0, src, -1, NULL, 0);
if (cbSize > 0)
{
*pdest = new WCHAR[cbSize+1];
cbSize = MultiByteToWideChar(CP_ACP, 0, src, -1, *pdest, cbSize+1);
}
return cbSize > 0 ? S_OK : E_FAIL;
}
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
4718e661738a1500156973c4125af6eb86636f09 | 28deeddb892e01cc44ae45739e83e5774b197b2e | /source/Irrlicht/CFileSystem.cpp | 002b386691eaccf4925e25937a6b7d912c49488c | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive",
"Zlib"
] | permissive | gametechnology/psi-old | c3e4430f3f57751371324ea5be0a579bae45a63a | aade1b7a4db670a24f8eb9a2a39f3eb84d40addc | refs/heads/master | 2021-01-15T21:48:44.375001 | 2013-03-04T11:43:00 | 2013-03-04T11:43:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,447 | cpp | // Copyright (C) 2002-2011 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#include "CFileSystem.h"
#include "IReadFile.h"
#include "IWriteFile.h"
#include "CZipReader.h"
#include "CMountPointReader.h"
#include "CPakReader.h"
#include "CNPKReader.h"
#include "CTarReader.h"
#include "CWADReader.h"
#include "CFileList.h"
#include "CXMLReader.h"
#include "CXMLWriter.h"
#include "stdio.h"
#include "os.h"
#include "CAttributes.h"
#include "CMemoryFile.h"
#include "CLimitReadFile.h"
#include "irrList.h"
#if defined (_IRR_WINDOWS_API_)
#if !defined ( _WIN32_WCE )
#include <direct.h> // for _chdir
#include <io.h> // for _access
#include <tchar.h>
#endif
#else
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#endif
namespace irr
{
namespace io
{
//! constructor
CFileSystem::CFileSystem()
{
#ifdef _DEBUG
setDebugName("CFileSystem");
#endif
setFileListSystem(FILESYSTEM_NATIVE);
//! reset current working directory
getWorkingDirectory();
#ifdef __IRR_COMPILE_WITH_PAK_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderPAK(this));
#endif
#ifdef __IRR_COMPILE_WITH_NPK_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderNPK(this));
#endif
#ifdef __IRR_COMPILE_WITH_TAR_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderTAR(this));
#endif
#ifdef __IRR_COMPILE_WITH_WAD_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderWAD(this));
#endif
#ifdef __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderMount(this));
#endif
#ifdef __IRR_COMPILE_WITH_ZIP_ARCHIVE_LOADER_
ArchiveLoader.push_back(new CArchiveLoaderZIP(this));
#endif
}
//! destructor
CFileSystem::~CFileSystem()
{
u32 i;
for ( i=0; i < FileArchives.size(); ++i)
{
FileArchives[i]->drop();
}
for ( i=0; i < ArchiveLoader.size(); ++i)
{
ArchiveLoader[i]->drop();
}
}
//! opens a file for read access
IReadFile* CFileSystem::createAndOpenFile(const io::path& filename)
{
IReadFile* file = 0;
u32 i;
for (i=0; i< FileArchives.size(); ++i)
{
file = FileArchives[i]->createAndOpenFile(filename);
if (file)
return file;
}
// Create the file using an absolute path so that it matches
// the scheme used by CNullDriver::getTexture().
return createReadFile(getAbsolutePath(filename));
}
//! Creates an IReadFile interface for treating memory like a file.
IReadFile* CFileSystem::createMemoryReadFile(void* memory, s32 len,
const io::path& fileName, bool deleteMemoryWhenDropped)
{
if (!memory)
return 0;
else
return new CMemoryFile(memory, len, fileName, deleteMemoryWhenDropped);
}
//! Creates an IReadFile interface for reading files inside files
IReadFile* CFileSystem::createLimitReadFile(const io::path& fileName,
IReadFile* alreadyOpenedFile, long pos, long areaSize)
{
if (!alreadyOpenedFile)
return 0;
else
return new CLimitReadFile(alreadyOpenedFile, pos, areaSize, fileName);
}
//! Creates an IReadFile interface for treating memory like a file.
IWriteFile* CFileSystem::createMemoryWriteFile(void* memory, s32 len,
const io::path& fileName, bool deleteMemoryWhenDropped)
{
if (!memory)
return 0;
else
return new CMemoryFile(memory, len, fileName, deleteMemoryWhenDropped);
}
//! Opens a file for write access.
IWriteFile* CFileSystem::createAndWriteFile(const io::path& filename, bool append)
{
return createWriteFile(filename, append);
}
//! Adds an external archive loader to the engine.
void CFileSystem::addArchiveLoader(IArchiveLoader* loader)
{
if (!loader)
return;
loader->grab();
ArchiveLoader.push_back(loader);
}
//! Returns the total number of archive loaders added.
u32 CFileSystem::getArchiveLoaderCount() const
{
return ArchiveLoader.size();
}
//! Gets the archive loader by index.
IArchiveLoader* CFileSystem::getArchiveLoader(u32 index) const
{
if (index < ArchiveLoader.size())
return ArchiveLoader[index];
else
return 0;
}
//! move the hirarchy of the filesystem. moves sourceIndex relative up or down
bool CFileSystem::moveFileArchive(u32 sourceIndex, s32 relative)
{
bool r = false;
const s32 dest = (s32) sourceIndex + relative;
const s32 dir = relative < 0 ? -1 : 1;
const s32 sourceEnd = ((s32) FileArchives.size() ) - 1;
IFileArchive *t;
for (s32 s = (s32) sourceIndex;s != dest; s += dir)
{
if (s < 0 || s > sourceEnd || s + dir < 0 || s + dir > sourceEnd)
continue;
t = FileArchives[s + dir];
FileArchives[s + dir] = FileArchives[s];
FileArchives[s] = t;
r = true;
}
return r;
}
//! Adds an archive to the file system.
bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase,
bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
const core::stringc& password,
IFileArchive** retArchive)
{
IFileArchive* archive = 0;
bool ret = false;
// see if archive is already added
if (changeArchivePassword(filename, password, retArchive))
return true;
s32 i;
// do we know what type it should be?
if (archiveType == EFAT_UNKNOWN || archiveType == EFAT_FOLDER)
{
// try to load archive based on file name
for (i = ArchiveLoader.size()-1; i >=0 ; --i)
{
if (ArchiveLoader[i]->isALoadableFileFormat(filename))
{
archive = ArchiveLoader[i]->createArchive(filename, ignoreCase, ignorePaths);
if (archive)
break;
}
}
// try to load archive based on content
if (!archive)
{
io::IReadFile* file = createAndOpenFile(filename);
if (file)
{
for (i = ArchiveLoader.size()-1; i >= 0; --i)
{
file->seek(0);
if (ArchiveLoader[i]->isALoadableFileFormat(file))
{
file->seek(0);
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
file->drop();
}
}
}
else
{
// try to open archive based on archive loader type
io::IReadFile* file = 0;
for (i = ArchiveLoader.size()-1; i >= 0; --i)
{
if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
{
// attempt to open file
if (!file)
file = createAndOpenFile(filename);
// is the file open?
if (file)
{
// attempt to open archive
file->seek(0);
if (ArchiveLoader[i]->isALoadableFileFormat(file))
{
file->seek(0);
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
else
{
// couldn't open file
break;
}
}
}
// if open, close the file
if (file)
file->drop();
}
if (archive)
{
FileArchives.push_back(archive);
if (password.size())
archive->Password=password;
if (retArchive)
*retArchive = archive;
ret = true;
}
else
{
os::Printer::log("Could not create archive for", filename, ELL_ERROR);
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
// don't expose!
bool CFileSystem::changeArchivePassword(const path& filename,
const core::stringc& password,
IFileArchive** archive)
{
for (s32 idx = 0; idx < (s32)FileArchives.size(); ++idx)
{
// TODO: This should go into a path normalization method
// We need to check for directory names with trailing slash and without
const path absPath = getAbsolutePath(filename);
const path arcPath = FileArchives[idx]->getFileList()->getPath();
if ((absPath == arcPath) || ((absPath+_IRR_TEXT("/")) == arcPath))
{
if (password.size())
FileArchives[idx]->Password=password;
if (archive)
*archive = FileArchives[idx];
return true;
}
}
return false;
}
bool CFileSystem::addFileArchive(IReadFile* file, bool ignoreCase,
bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
const core::stringc& password, IFileArchive** retArchive)
{
if (!file || archiveType == EFAT_FOLDER)
return false;
if (file)
{
if (changeArchivePassword(file->getFileName(), password, retArchive))
return true;
IFileArchive* archive = 0;
s32 i;
if (archiveType == EFAT_UNKNOWN)
{
// try to load archive based on file name
for (i = ArchiveLoader.size()-1; i >=0 ; --i)
{
if (ArchiveLoader[i]->isALoadableFileFormat(file->getFileName()))
{
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
// try to load archive based on content
if (!archive)
{
for (i = ArchiveLoader.size()-1; i >= 0; --i)
{
file->seek(0);
if (ArchiveLoader[i]->isALoadableFileFormat(file))
{
file->seek(0);
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
}
}
else
{
// try to open archive based on archive loader type
for (i = ArchiveLoader.size()-1; i >= 0; --i)
{
if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
{
// attempt to open archive
file->seek(0);
if (ArchiveLoader[i]->isALoadableFileFormat(file))
{
file->seek(0);
archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
if (archive)
break;
}
}
}
}
if (archive)
{
FileArchives.push_back(archive);
if (password.size())
archive->Password=password;
if (retArchive)
*retArchive = archive;
return true;
}
else
{
os::Printer::log("Could not create archive for", file->getFileName(), ELL_ERROR);
}
}
return false;
}
//! Adds an archive to the file system.
bool CFileSystem::addFileArchive(IFileArchive* archive)
{
for (u32 i=0; i < FileArchives.size(); ++i)
{
if (archive == FileArchives[i])
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
}
FileArchives.push_back(archive);
return true;
}
//! removes an archive from the file system.
bool CFileSystem::removeFileArchive(u32 index)
{
bool ret = false;
if (index < FileArchives.size())
{
FileArchives[index]->drop();
FileArchives.erase(index);
ret = true;
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return ret;
}
//! removes an archive from the file system.
bool CFileSystem::removeFileArchive(const io::path& filename)
{
for (u32 i=0; i < FileArchives.size(); ++i)
{
if (filename == FileArchives[i]->getFileList()->getPath())
return removeFileArchive(i);
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
//! Removes an archive from the file system.
bool CFileSystem::removeFileArchive(const IFileArchive* archive)
{
for (u32 i=0; i < FileArchives.size(); ++i)
{
if (archive == FileArchives[i])
{
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return removeFileArchive(i);
}
}
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
return false;
}
//! gets an archive
u32 CFileSystem::getFileArchiveCount() const
{
return FileArchives.size();
}
IFileArchive* CFileSystem::getFileArchive(u32 index)
{
return index < getFileArchiveCount() ? FileArchives[index] : 0;
}
//! Returns the string of the current working directory
const io::path& CFileSystem::getWorkingDirectory()
{
EFileSystemType type = FileSystemType;
if (type != FILESYSTEM_NATIVE)
{
type = FILESYSTEM_VIRTUAL;
}
else
{
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
// does not need this
#elif defined(_IRR_WINDOWS_API_)
fschar_t tmp[_MAX_PATH];
#if defined(_IRR_WCHAR_FILESYSTEM )
_wgetcwd(tmp, _MAX_PATH);
WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
WorkingDirectory[FILESYSTEM_NATIVE].replace(L'\\', L'/');
#else
_getcwd(tmp, _MAX_PATH);
WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
WorkingDirectory[FILESYSTEM_NATIVE].replace('\\', '/');
#endif
#endif
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
// getting the CWD is rather complex as we do not know the size
// so try it until the call was successful
// Note that neither the first nor the second parameter may be 0 according to POSIX
#if defined(_IRR_WCHAR_FILESYSTEM )
u32 pathSize=256;
wchar_t *tmpPath = new wchar_t[pathSize];
while ((pathSize < (1<<16)) && !(wgetcwd(tmpPath,pathSize)))
{
delete [] tmpPath;
pathSize *= 2;
tmpPath = new char[pathSize];
}
if (tmpPath)
{
WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
delete [] tmpPath;
}
#else
u32 pathSize=256;
char *tmpPath = new char[pathSize];
while ((pathSize < (1<<16)) && !(getcwd(tmpPath,pathSize)))
{
delete [] tmpPath;
pathSize *= 2;
tmpPath = new char[pathSize];
}
if (tmpPath)
{
WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
delete [] tmpPath;
}
#endif
#endif
WorkingDirectory[type].validate();
}
return WorkingDirectory[type];
}
//! Changes the current Working Directory to the given string.
bool CFileSystem::changeWorkingDirectoryTo(const io::path& newDirectory)
{
bool success=false;
if (FileSystemType != FILESYSTEM_NATIVE)
{
WorkingDirectory[FILESYSTEM_VIRTUAL] = newDirectory;
// is this empty string constant really intended?
flattenFilename(WorkingDirectory[FILESYSTEM_VIRTUAL], _IRR_TEXT(""));
success = true;
}
else
{
WorkingDirectory[FILESYSTEM_NATIVE] = newDirectory;
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
success = true;
#elif defined(_MSC_VER)
#if defined(_IRR_WCHAR_FILESYSTEM)
success = (_wchdir(newDirectory.c_str()) == 0);
#else
success = (_chdir(newDirectory.c_str()) == 0);
#endif
#else
success = (chdir(newDirectory.c_str()) == 0);
#endif
}
return success;
}
io::path CFileSystem::getAbsolutePath(const io::path& filename) const
{
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
return filename;
#elif defined(_IRR_WINDOWS_API_)
fschar_t *p=0;
fschar_t fpath[_MAX_PATH];
#if defined(_IRR_WCHAR_FILESYSTEM )
p = _wfullpath(fpath, filename.c_str(), _MAX_PATH);
core::stringw tmp(p);
tmp.replace(L'\\', L'/');
#else
p = _fullpath(fpath, filename.c_str(), _MAX_PATH);
core::stringc tmp(p);
tmp.replace('\\', '/');
#endif
return tmp;
#elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
c8* p=0;
c8 fpath[4096];
fpath[0]=0;
p = realpath(filename.c_str(), fpath);
if (!p)
{
// content in fpath is unclear at this point
if (!fpath[0]) // seems like fpath wasn't altered, use our best guess
{
io::path tmp(filename);
return flattenFilename(tmp);
}
else
return io::path(fpath);
}
if (filename[filename.size()-1]=='/')
return io::path(p)+_IRR_TEXT("/");
else
return io::path(p);
#else
return io::path(filename);
#endif
}
//! returns the directory part of a filename, i.e. all until the first
//! slash or backslash, excluding it. If no directory path is prefixed, a '.'
//! is returned.
io::path CFileSystem::getFileDir(const io::path& filename) const
{
// find last forward or backslash
s32 lastSlash = filename.findLast('/');
const s32 lastBackSlash = filename.findLast('\\');
lastSlash = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
if ((u32)lastSlash < filename.size())
return filename.subString(0, lastSlash);
else
return _IRR_TEXT(".");
}
//! returns the base part of a filename, i.e. all except for the directory
//! part. If no directory path is prefixed, the full name is returned.
io::path CFileSystem::getFileBasename(const io::path& filename, bool keepExtension) const
{
// find last forward or backslash
s32 lastSlash = filename.findLast('/');
const s32 lastBackSlash = filename.findLast('\\');
lastSlash = core::max_(lastSlash, lastBackSlash);
// get number of chars after last dot
s32 end = 0;
if (!keepExtension)
{
// take care to search only after last slash to check only for
// dots in the filename
end = filename.findLast('.');
if (end == -1 || end < lastSlash)
end=0;
else
end = filename.size()-end;
}
if ((u32)lastSlash < filename.size())
return filename.subString(lastSlash+1, filename.size()-lastSlash-1-end);
else if (end != 0)
return filename.subString(0, filename.size()-end);
else
return filename;
}
//! flatten a path and file name for example: "/you/me/../." becomes "/you"
io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root) const
{
directory.replace('\\', '/');
if (directory.lastChar() != '/')
directory.append('/');
io::path dir;
io::path subdir;
s32 lastpos = 0;
s32 pos = 0;
bool lastWasRealDir=false;
while ((pos = directory.findNext('/', lastpos)) >= 0)
{
subdir = directory.subString(lastpos, pos - lastpos + 1);
if (subdir == _IRR_TEXT("../"))
{
if (lastWasRealDir)
{
deletePathFromPath(dir, 2);
lastWasRealDir=(dir.size()!=0);
}
else
{
dir.append(subdir);
lastWasRealDir=false;
}
}
else if (subdir == _IRR_TEXT("/"))
{
dir = root;
}
else if (subdir != _IRR_TEXT("./"))
{
dir.append(subdir);
lastWasRealDir=true;
}
lastpos = pos + 1;
}
directory = dir;
return directory;
}
//! Get the relative filename, relative to the given directory
path CFileSystem::getRelativeFilename(const path& filename, const path& directory) const
{
if ( filename.empty() || directory.empty() )
return filename;
io::path path1, file, ext;
core::splitFilename(getAbsolutePath(filename), &path1, &file, &ext);
io::path path2(getAbsolutePath(directory));
core::list<io::path> list1, list2;
path1.split(list1, _IRR_TEXT("/\\"), 2);
path2.split(list2, _IRR_TEXT("/\\"), 2);
u32 i=0;
core::list<io::path>::ConstIterator it1,it2;
it1=list1.begin();
it2=list2.begin();
#if defined (_IRR_WINDOWS_API_)
fschar_t partition1 = 0, partition2 = 0;
io::path prefix1, prefix2;
if ( it1 != list1.end() )
prefix1 = *it1;
if ( it2 != list2.end() )
prefix2 = *it2;
if ( prefix1.size() > 1 && prefix1[1] == _IRR_TEXT(':') )
partition1 = core::locale_lower(prefix1[0]);
if ( prefix2.size() > 1 && prefix2[1] == _IRR_TEXT(':') )
partition2 = core::locale_lower(prefix2[0]);
// must have the same prefix or we can't resolve it to a relative filename
if ( partition1 != partition2 )
{
return filename;
}
#endif
for (; i<list1.size() && i<list2.size()
#if defined (_IRR_WINDOWS_API_)
&& (io::path(*it1).make_lower()==io::path(*it2).make_lower())
#else
&& (*it1==*it2)
#endif
; ++i)
{
++it1;
++it2;
}
path1=_IRR_TEXT("");
for (; i<list2.size(); ++i)
path1 += _IRR_TEXT("../");
while (it1 != list1.end())
{
path1 += *it1++;
path1 += _IRR_TEXT('/');
}
path1 += file;
if (ext.size())
{
path1 += _IRR_TEXT('.');
path1 += ext;
}
return path1;
}
//! Sets the current file systen type
EFileSystemType CFileSystem::setFileListSystem(EFileSystemType listType)
{
EFileSystemType current = FileSystemType;
FileSystemType = listType;
return current;
}
//! Creates a list of files and directories in the current working directory
IFileList* CFileSystem::createFileList()
{
CFileList* r = 0;
io::path Path = getWorkingDirectory();
Path.replace('\\', '/');
if (Path.lastChar() != '/')
Path.append('/');
//! Construct from native filesystem
if (FileSystemType == FILESYSTEM_NATIVE)
{
// --------------------------------------------
//! Windows version
#ifdef _IRR_WINDOWS_API_
#if !defined ( _WIN32_WCE )
r = new CFileList(Path, true, false);
struct _tfinddata_t c_file;
long hFile;
if( (hFile = _tfindfirst( _T("*"), &c_file )) != -1L )
{
do
{
r->addItem(Path + c_file.name, 0, c_file.size, (_A_SUBDIR & c_file.attrib) != 0, 0);
}
while( _tfindnext( hFile, &c_file ) == 0 );
_findclose( hFile );
}
#endif
//TODO add drives
//entry.Name = "E:\\";
//entry.isDirectory = true;
//Files.push_back(entry);
#endif
// --------------------------------------------
//! Linux version
#if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
r = new CFileList(Path, false, false);
r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0);
//! We use the POSIX compliant methods instead of scandir
DIR* dirHandle=opendir(Path.c_str());
if (dirHandle)
{
struct dirent *dirEntry;
while ((dirEntry=readdir(dirHandle)))
{
u32 size = 0;
bool isDirectory = false;
if((strcmp(dirEntry->d_name, ".")==0) ||
(strcmp(dirEntry->d_name, "..")==0))
{
continue;
}
struct stat buf;
if (stat(dirEntry->d_name, &buf)==0)
{
size = buf.st_size;
isDirectory = S_ISDIR(buf.st_mode);
}
#if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__)
// only available on some systems
else
{
isDirectory = dirEntry->d_type == DT_DIR;
}
#endif
r->addItem(Path + dirEntry->d_name, 0, size, isDirectory, 0);
}
closedir(dirHandle);
}
#endif
}
else
{
//! create file list for the virtual filesystem
r = new CFileList(Path, false, false);
//! add relative navigation
SFileListEntry e2;
SFileListEntry e3;
//! PWD
r->addItem(Path + _IRR_TEXT("."), 0, 0, true, 0);
//! parent
r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0);
//! merge archives
for (u32 i=0; i < FileArchives.size(); ++i)
{
const IFileList *merge = FileArchives[i]->getFileList();
for (u32 j=0; j < merge->getFileCount(); ++j)
{
if (core::isInSameDirectory(Path, merge->getFullFileName(j)) == 0)
{
r->addItem(merge->getFullFileName(j), merge->getFileOffset(j), merge->getFileSize(j), merge->isDirectory(j), 0);
}
}
}
}
if (r)
r->sort();
return r;
}
//! Creates an empty filelist
IFileList* CFileSystem::createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths)
{
return new CFileList(path, ignoreCase, ignorePaths);
}
//! determines if a file exists and would be able to be opened.
bool CFileSystem::existFile(const io::path& filename) const
{
for (u32 i=0; i < FileArchives.size(); ++i)
if (FileArchives[i]->getFileList()->findFile(filename)!=-1)
return true;
#if defined(_IRR_WINDOWS_CE_PLATFORM_)
#if defined(_IRR_WCHAR_FILESYSTEM)
HANDLE hFile = CreateFileW(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
#else
HANDLE hFile = CreateFileW(core::stringw(filename).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
#endif
if (hFile == INVALID_HANDLE_VALUE)
return false;
else
{
CloseHandle(hFile);
return true;
}
#else
_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
#if defined(_MSC_VER)
#if defined(_IRR_WCHAR_FILESYSTEM)
return (_waccess(filename.c_str(), 0) != -1);
#else
return (_access(filename.c_str(), 0) != -1);
#endif
#elif defined(F_OK)
return (access(filename.c_str(), F_OK) != -1);
#else
return (access(filename.c_str(), 0) != -1);
#endif
#endif
}
//! Creates a XML Reader from a file.
IXMLReader* CFileSystem::createXMLReader(const io::path& filename)
{
IReadFile* file = createAndOpenFile(filename);
if (!file)
return 0;
IXMLReader* reader = createXMLReader(file);
file->drop();
return reader;
}
//! Creates a XML Reader from a file.
IXMLReader* CFileSystem::createXMLReader(IReadFile* file)
{
if (!file)
return 0;
return createIXMLReader(file);
}
//! Creates a XML Reader from a file.
IXMLReaderUTF8* CFileSystem::createXMLReaderUTF8(const io::path& filename)
{
IReadFile* file = createAndOpenFile(filename);
if (!file)
return 0;
IXMLReaderUTF8* reader = createIXMLReaderUTF8(file);
file->drop();
return reader;
}
//! Creates a XML Reader from a file.
IXMLReaderUTF8* CFileSystem::createXMLReaderUTF8(IReadFile* file)
{
if (!file)
return 0;
return createIXMLReaderUTF8(file);
}
//! Creates a XML Writer from a file.
IXMLWriter* CFileSystem::createXMLWriter(const io::path& filename)
{
IWriteFile* file = createAndWriteFile(filename);
IXMLWriter* writer = 0;
if (file)
{
writer = createXMLWriter(file);
file->drop();
}
return writer;
}
//! Creates a XML Writer from a file.
IXMLWriter* CFileSystem::createXMLWriter(IWriteFile* file)
{
return new CXMLWriter(file);
}
//! creates a filesystem which is able to open files from the ordinary file system,
//! and out of zipfiles, which are able to be added to the filesystem.
IFileSystem* createFileSystem()
{
return new CFileSystem();
}
//! Creates a new empty collection of attributes, usable for serialization and more.
IAttributes* CFileSystem::createEmptyAttributes(video::IVideoDriver* driver)
{
return new CAttributes(driver);
}
} // end namespace irr
} // end namespace io
| [
"stephan@vanderfeest.nl"
] | stephan@vanderfeest.nl |
a529a2b6ecc16b336f71e53ccdb3c22029ab334b | b0eda7d367ae3bba928fd5c1df318a6034317ed1 | /Source/ResourceManager/cubemap.h | 6a8b4d0b8313cc05aa0139a03bf4375fad64c085 | [] | no_license | Bargestt/GameFrame-DROPPED | dc098465ea93db9c2ffeeee68b94990ffbf439ec | 8a9345a2582b55bc5994d4b1335739138addc4d8 | refs/heads/master | 2021-07-02T10:16:11.524246 | 2017-09-23T12:51:29 | 2017-09-23T12:51:29 | 104,484,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 222 | h | #ifndef CUBEMAP_H
#define CUBEMAP_H
#include "gtexture.h"
class CubeMap : public GTexture
{
public:
CubeMap();
bool load(std::vector<std::string> faces);
void bind() const override;
};
#endif // CUBEMAP_H
| [
"bulgakovbarg@ya.ru"
] | bulgakovbarg@ya.ru |
40ded8f34349661f81d88c0d7e4aca48ade1fa6c | dd7da9964eeae4d0839709fff92f6f4da2c0c26b | /NodeMCU_ConexaoWiFi/NodeMCU_ConexaoWiFi.ino | be592af996bf6a4e8ccbf50ac57cfc3801aaad93 | [] | no_license | EduardoFRRZ/NodeMCU_ESP8266 | 93f9eed4d5a1cf8a93e012eae48b823559f952ac | 90dbb6fc880905d5d8f05cfc27db0161685a1e71 | refs/heads/master | 2020-07-19T07:23:05.151671 | 2019-09-04T20:28:45 | 2019-09-04T20:28:45 | 206,154,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | ino | #include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Dados do WiFi
const char* ssid = "Net Virtua 577";
const char* password = "1000160930";
void setup() {
Serial.begin(115200);
// Inicia conexão com o WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
if(WiFi.status() == WL_CONNECTED) {
Serial.println(" ");
Serial.print("WiFi conectado - IP da NoceMCU: ");
Serial.println(WiFi.localIP());
}
}
void loop() {
}
| [
"eduardogd20@gmail.com"
] | eduardogd20@gmail.com |
79617b59c86a8687b288c1dcac25b7961310c15f | dad699d7c5359cbafcb39006345b138f098a8124 | /rrbs/test.cpp | a48412ab8cabfc772e592618278ee944329067f9 | [] | no_license | ZhouQiangwei/utils | 48328f6cb871c0b552cb7f6db7b84cc1077d5ea6 | 1450cb9c322db5560540d33ba026a7548011446d | refs/heads/master | 2020-03-26T05:46:20.600045 | 2018-08-13T12:28:46 | 2018-08-13T12:28:46 | 144,573,923 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
string str="01234567890000";
int a;
a=str.find("0");
cout<<a<<endl;//返回0
a=str.find("123");
cout<<a<<endl;//返回1
a=str.find("456");
cout<<a<<endl;//返回4
return 0;
}
| [
"1010170266@qq.com"
] | 1010170266@qq.com |
e2da676abb06717cbc00be8cffb81bbd01cf66f0 | c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e | /Source/Source/KG3DEngine/KG3DEngine/KG3DAnimationSplitter.cpp | 06eddede53591ae27655fe923ba30a7045c584d9 | [
"MIT"
] | permissive | uvbs/FullSource | f8673b02e10c8c749b9b88bf18018a69158e8cb9 | 07601c5f18d243fb478735b7bdcb8955598b9a90 | refs/heads/master | 2020-03-24T03:11:13.148940 | 2018-07-25T18:30:25 | 2018-07-25T18:30:25 | 142,408,505 | 2 | 2 | null | 2018-07-26T07:58:12 | 2018-07-26T07:58:12 | null | GB18030 | C++ | false | false | 22,224 | cpp | #include "StdAfx.h"
#include "KG3DAnimationSplitter.h"
#include "KG3DEngineManager.h"
#include "KG3DGraphicsTool.h"
#include "KG3DAnimationTagContainer.h"
#include "KG3DClipTable.h"
#include "KG3DClip.h"
#include "KG3DClipTools.h"
#include "KG3DModelST.h"
const TCHAR* KG3DAnimationSplitter::s_strConfigFile = "Data\\public\\animationJointInfo\\config.ini";
BOOL KG3DAnimationSplitter::m_bConfigLoaded = FALSE;
std::vector<string> KG3DAnimationSplitter::m_PresetPathName;
#ifdef _DEBUG
#define new DEBUG_NEW_3DENGINE
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
KG3DAnimationSplitter::KG3DAnimationSplitter(void)
{
m_pModel = NULL;
m_uCurrentPreset = 0xffffffff;
}
KG3DAnimationSplitter::~KG3DAnimationSplitter(void)
{
m_pModel = NULL;
}
void KG3DAnimationSplitter::UnInit()
{
m_Warper.UnInit();
}
void KG3DAnimationSplitter::SetModel(KG3DModel* pModel)
{
KG_PROCESS_SUCCESS(m_pModel == pModel);
m_pModel = pModel;
if (m_pModel)
{
m_Warper.SetModel(m_pModel);
}
Exit1:
return;
}
BOOL IsAniLoaded(enuModelPlayAnimationType AniType,
KG3DAnimationTagContainer* pTagInput,
KG3DClip*& pClipInput)
{
switch (AniType)
{
case MPAT_NORMAL:
{
if(pClipInput && pClipInput->IsLoad())
return TRUE;
}
break;
case MPAT_TAGGED:
{
if(pTagInput && pTagInput->IsLoaded())
{
if(!pClipInput)
{
LPCSTR strTagAnimationFilePath = NULL;
strTagAnimationFilePath = pTagInput->GetAnimationFilePath();
HRESULT hr = g_cClipTable.LoadResourceFromFile(strTagAnimationFilePath, 0, 0, &pClipInput);
KGLOG_COM_PROCESS_ERROR(hr);
}
if (pClipInput && pClipInput->IsLoad())
{
return TRUE;
}
}
}
break;
}
Exit0:
return FALSE;
}
HRESULT GetAniResource(LPCSTR strAnimationName,
enuModelPlayAnimationType& AniType,
KG3DAnimationTagContainer*& pTagInput,
KG3DClip*& pClipInput,
BOOL IsFirstAni)
{
HRESULT hr = E_FAIL;
unsigned uClipLoadOption = 0;
KGLOG_PROCESS_ERROR(strAnimationName);
KG_PROCESS_ERROR(strAnimationName[0] != '\0');
if (IsFirstAni)
{
uClipLoadOption = MLO_ANI_MULTI;
}
AniType = g_cGraphicsTool.GetAnimationTypeByFileName(strAnimationName);
switch (AniType)
{
case MPAT_NORMAL:
{
hr = g_cClipTable.LoadResourceFromFile(strAnimationName, 0, uClipLoadOption, &pClipInput);
KG_COM_PROCESS_ERROR(hr);
}
break;
case MPAT_TAGGED:
{
LPCSTR strTagAnimationFilePath = NULL;
pTagInput = g_tagConTable.LoadTag(strAnimationName); //g_cClipTable.GetTagTable()->LoadTag(strAnimationName);
KGLOG_PROCESS_ERROR(pTagInput);
if(pTagInput && pTagInput->IsLoaded())
{
strTagAnimationFilePath = pTagInput->GetAnimationFilePath();
hr = g_cClipTable.LoadResourceFromFile(strTagAnimationFilePath, 0, uClipLoadOption, &pClipInput);
KGLOG_COM_PROCESS_ERROR(hr);
}
}
break;
}
hr = S_OK;
Exit0:
return hr;
}
HRESULT KG3DAnimationSplitter::PlayAnimation(LPCSTR strAnimationName,
unsigned int uPresetIndex,
DWORD dwSplitType,
DWORD dwPlayType,
FLOAT fSpeed,
int nOffsetTime,
PVOID pReserved,
PVOID pUserdata,
enuAnimationControllerPriority Priority,
enuModelPlayAnimationType Type,
KG3DAnimationTagContainer* pTagContainerNew,
KG3DClip* pClip)
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
DWORD dwStartTime = timeGetTime();
if (pReserved)
{
m_Warper.m_TweenSpan[dwSplitType] = *(TweenTimeSpan*)(pReserved);
}
else
{
m_Warper.m_TweenSpan[dwSplitType].dwTweenIn = 0;
m_Warper.m_TweenSpan[dwSplitType].dwTweenOut = 0;
m_Warper.m_TweenSpan[dwSplitType].fTweenWeigth = 1.0f;
}
switch (m_Warper.m_ControllerPriority[dwSplitType])
{
case ANICTL_PRIMARY:
{
switch (Priority)
{
case ANICTL_PRIMARY:
//如果当前的优先级是高, 新的也是高, 那么替代掉高的
hrRetCode = PlayAnimationChange(strAnimationName,
uPresetIndex,
dwSplitType,
dwPlayType,
fSpeed,
nOffsetTime,
pReserved,
pUserdata,
Type,pTagContainerNew,pClip);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
m_Warper.m_ControllerPriority[dwSplitType] = ANICTL_PRIMARY;
break;
case ANICTL_SECONDARY:
//如果当前的优先级是低, 新的是高, 那么把当前的移到低轨, 并且在高轨播放新的
hrRetCode = MoveCurrentToSecondaryAndPlay(strAnimationName,
uPresetIndex,
dwSplitType,
dwPlayType,
fSpeed,
nOffsetTime,
pReserved,
pUserdata,
Type,pTagContainerNew,pClip);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
m_Warper.m_ControllerPriority[dwSplitType] = ANICTL_SECONDARY;
break;
}
}
break;
case ANICTL_SECONDARY:
{
switch (Priority)
{
case ANICTL_PRIMARY:
//如果当前的优先级是高, 新的是低, 那么在低轨播放
hrRetCode= PlayAnimationSecondary(strAnimationName,
dwSplitType,
dwPlayType,
fSpeed,
nOffsetTime,
pReserved,
pUserdata,
Type,pTagContainerNew,pClip);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
m_Warper.m_ControllerPriority[dwSplitType] = ANICTL_SECONDARY;
break;
case ANICTL_SECONDARY:
//如果当前的优先级是低, 新的也是低, 那么在替换掉当前的低轨的
hrRetCode = PlayAnimationChange(strAnimationName,
uPresetIndex,
dwSplitType,
dwPlayType,
fSpeed,
nOffsetTime,
pReserved,
pUserdata,
Type,pTagContainerNew,pClip);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
m_Warper.m_ControllerPriority[dwSplitType] = ANICTL_SECONDARY;
break;
}
}
break;
}
hrResult = S_OK;
Exit0:
DWORD dwCost = timeGetTime() - dwStartTime;
if(g_cEngineOption.bEnableTimeOptimizeLog && dwCost > 10)
{
KGLogPrintf(KGLOG_INFO,"TimeOptimize KG3DAnimationSplitter::PlayAnimation cost %d",dwCost);
}
return hrResult;
}
void KG3DAnimationSplitter::OnSecondaryAnimationFinish(KG3DAnimationController *pActiveController)
{
//处理Secondary播放完成之后的切回
KG3DAnimationComposer *pComposer = NULL;
KG3DAnimationController *pController = NULL;
KG3DAnimationTagContainer *pTagContainerRemove = NULL;
DWORD64 dwSplitType = pActiveController->GetMotionExtraInfo();
static DWORD const s_dwContainerMap[] = { 1, //TYPE_NONE
0, //TYPE_PART0
1}; //TYPE_PART1
pTagContainerRemove = m_Warper.m_vecTagContainers[s_dwContainerMap[dwSplitType]];
if (pTagContainerRemove)
{
pActiveController->RemoveAnimationControllerUpdateNotifier(pTagContainerRemove);
}
switch (dwSplitType)
{
case IKG3DAnimationController::TYPE_PART0:
{
KG3DAnimationController ControllerSave;
m_Warper.GetComposer(JOINT_TOPINFO_COMPOSERINDEX, (IEKG3DAnimationComposer **)&pComposer);
ASSERT(pComposer);
pController = pComposer->GetAnimationController(JOINT_TOPINFO_ANI_TOP_INDEX);
ASSERT(pController);
//保存当前的作为之后的pStart
pController->Clone(ControllerSave);
//复制二号到主控制器
m_Warper.m_SecondaryControllers[ANI_JOINT_TOP].Clone(*pController);
pController->m_Priority = ANICTL_PRIMARY;
m_Warper.ChangeAnimation(JOINT_TOPINFO_COMPOSERINDEX,
JOINT_TOPINFO_ANI_TOP_INDEX,
pController->GetCurAnimation(),
&ControllerSave,
m_Warper.m_TweenSpan[ANI_JOINT_TOP].dwTweenOut);
SAFE_RELEASE(pTagContainerRemove);
if (m_Warper.m_SecondaryTagContainers[ANI_JOINT_TOP])
{
pController->AddAnimationControllerUpdateNotifier(m_Warper.m_SecondaryTagContainers[0]);
}
m_Warper.m_SecondaryControllers[ANI_JOINT_TOP].RemoveAnimationControllerUpdateNotifier(m_Warper.m_SecondaryTagContainers[0]);
m_Warper.m_vecTagContainers[s_dwContainerMap[dwSplitType]] = m_Warper.m_SecondaryTagContainers[0];
m_Warper.m_SecondaryTagContainers[ANI_JOINT_TOP] = NULL;
m_Warper.m_SecondaryControllers[ANI_JOINT_TOP].Detach();
m_Warper.m_ControllerPriority[ANI_JOINT_TOP] = ANICTL_PRIMARY;
}
break;
case IKG3DAnimationController::TYPE_PART1:
{
KG3DAnimationController ControllerSaveBottom;
KG3DAnimationController *pBottomController = NULL;
//Set bottom animation controller information
m_Warper.GetComposer(JOINT_BOTTOMINFO_COMPOSERINDEX, (IEKG3DAnimationComposer **)&pComposer);
ASSERT(pComposer);
pBottomController = pComposer->GetAnimationController(JOINT_BOTTOMINFO_ANI_BOTTOM_INDEX);
ASSERT(pBottomController);
pBottomController->Clone(ControllerSaveBottom);
m_Warper.m_SecondaryControllers[ANI_JOINT_BOTTOM].Clone(*pBottomController);
pBottomController->m_Priority = ANICTL_PRIMARY;
m_Warper.ChangeAnimation(JOINT_BOTTOMINFO_COMPOSERINDEX,
JOINT_BOTTOMINFO_ANI_BOTTOM_INDEX,
pBottomController->GetCurAnimation(),
&ControllerSaveBottom,
m_Warper.m_TweenSpan[ANI_JOINT_BOTTOM].dwTweenOut);
SAFE_RELEASE(pTagContainerRemove);
m_Warper.m_vecTagContainers[ANI_JOINT_BOTTOM] = NULL;
m_Warper.m_SecondaryControllers[ANI_JOINT_BOTTOM].Detach();
m_Warper.m_ControllerPriority[ANI_JOINT_BOTTOM] = ANICTL_PRIMARY;
}
break;
case IKG3DAnimationController::TYPE_NONE:
break;
default:
ASSERT(0);
}
}
HRESULT KG3DAnimationSplitter::PlayAnimationSecondary(LPCSTR strAnimationName,
DWORD dwSplitType,
DWORD dwPlayType,
FLOAT fSpeed,
int nOffsetTime,
PVOID pReserved,
PVOID pUserdata,
enuModelPlayAnimationType AniType,
KG3DAnimationTagContainer* pTagContainerNew,
KG3DClip* pClip)
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
KG3DAnimationController &Controller = m_Warper.m_SecondaryControllers[dwSplitType];
KG3DModelST *pModelST = NULL;
KG3DBip *pBip = NULL;
DWORD dwStartTime = timeGetTime();
BOOL bTagAddRefFlag = FALSE;
KG_ASSERT_EXIT(strAnimationName);
KG_ASSERT_EXIT(pClip);
if (m_Warper.m_SecondaryTagContainers[dwSplitType])
{
Controller.RemoveAnimationControllerUpdateNotifier(m_Warper.m_SecondaryTagContainers[dwSplitType]);
SAFE_RELEASE(m_Warper.m_SecondaryTagContainers[dwSplitType]);
}
if (AniType == MPAT_TAGGED)
{
KG_ASSERT_EXIT(pTagContainerNew);
if (dwSplitType == ANI_JOINT_BOTTOM)
{
//在这里暂时对禁止掉下半身的标签的功能
AniType = MPAT_NORMAL;
}
else
{
pTagContainerNew->AttachToModel(m_pModel);
m_Warper.m_SecondaryTagContainers[dwSplitType] = pTagContainerNew;
m_Warper.m_SecondaryTagContainers[dwSplitType]->AddRef();
bTagAddRefFlag = TRUE;
}
}
ASSERT(m_pModel->GetType() == MESHTYPE_MODELST);
pModelST = dynamic_cast<KG3DModelST*>(m_pModel);
KG_PROCESS_ERROR(pModelST);
pBip = pModelST->GetBip();
KG_PROCESS_ERROR(pBip);
hrRetCode = GetClipTool().CheckClipByBip(pClip, pBip);
KG_COM_PROCESS_ERROR(hrRetCode);
Controller.SetUserdata(pUserdata);
Controller.StartAnimation(dwPlayType, nOffsetTime, fSpeed);
Controller.Attach(pClip);
if (AniType == MPAT_TAGGED)
{
KG3DAnimationTagContainer *pTag = m_Warper.m_SecondaryTagContainers[dwSplitType];
Controller.AddAnimationControllerUpdateNotifier(pTag);
}
hrResult = S_OK;
Exit0:
if (FAILED(hrResult))
{
if (bTagAddRefFlag)
{
KG_COM_RELEASE(m_Warper.m_SecondaryTagContainers[dwSplitType]);
bTagAddRefFlag = FALSE;
}
}
DWORD dwCost = timeGetTime() - dwStartTime;
if(g_cEngineOption.bEnableTimeOptimizeLog && dwCost > 10)
{
KGLogPrintf(KGLOG_INFO,"TimeOptimize KG3DAnimationSplitter::PlayAnimationSecondary cost %d",dwCost);
}
return hrResult;
}
HRESULT KG3DAnimationSplitter::MoveCurrentToSecondaryAndPlay(LPCSTR strAnimationName,
unsigned int uPresetIndex,
DWORD dwSplitType,
DWORD dwPlayType,
FLOAT fSpeed,
int nOffsetTime,
PVOID pReserved,
PVOID pUserdata,
enuModelPlayAnimationType AniType,
KG3DAnimationTagContainer* pTagContainerNew,
KG3DClip* pClip)
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
KG3DAnimationTagContainer *pTagContainerSrc = NULL;
KG3DAnimationController *pController = NULL;
KG3DAnimationComposer *pComposer = NULL;
KG_ASSERT_EXIT(strAnimationName);
KG_ASSERT_EXIT(pClip);
static DWORD const s_dwControllerMap[] = { 1, 0 };
hrRetCode = m_Warper.GetComposer(dwSplitType, (IEKG3DAnimationComposer**)&pComposer);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
pController = pComposer->GetAnimationController(s_dwControllerMap[dwSplitType]);
KG_PROCESS_ERROR(pController);
pController->m_Priority = ANICTL_SECONDARY;
pTagContainerSrc = m_Warper.m_vecTagContainers[dwSplitType];
if (pTagContainerSrc)
{
pController->RemoveAnimationControllerUpdateNotifier(pTagContainerSrc);
KG3DAnimationTagContainer *pSecondaryTagContainer = m_Warper.m_SecondaryTagContainers[dwSplitType];
if (pSecondaryTagContainer)
{
m_Warper.m_SecondaryControllers[dwSplitType].RemoveAnimationControllerUpdateNotifier(pSecondaryTagContainer);
}
SAFE_RELEASE(m_Warper.m_SecondaryTagContainers[dwSplitType]);
m_Warper.m_SecondaryTagContainers[dwSplitType] = pTagContainerSrc;
m_Warper.m_vecTagContainers[dwSplitType] = NULL;
m_Warper.m_SecondaryControllers[dwSplitType].AddAnimationControllerUpdateNotifier(pTagContainerSrc);
}
pController->Clone(m_Warper.m_SecondaryControllers[dwSplitType]);
hrRetCode = PlayAnimationChange(strAnimationName,
uPresetIndex,
dwSplitType,
dwPlayType,
fSpeed,
nOffsetTime,
pReserved,
pUserdata,
AniType,pTagContainerNew,pClip);
KG_COM_PROCESS_ERROR(hrRetCode);
hrResult = S_OK;
Exit0:
return hrResult;
}
HRESULT KG3DAnimationSplitter::PlayAnimationChange(LPCSTR strAnimationName,
unsigned int uPresetIndex,
DWORD dwSplitType,
DWORD dwPlayType,
FLOAT fSpeed,
int nOffsetTime,
PVOID pReserved,
PVOID pUserdata,
enuModelPlayAnimationType AniType,
KG3DAnimationTagContainer* pTagContainerNew,
KG3DClip* pClip)
{
HRESULT hrResult = E_FAIL;
HRESULT hrRetCode = E_FAIL;
KG3DAnimationComposer *pComposer = NULL;
KG3DAnimationController *pController = NULL;
KG3DAnimationTagContainer *pTagContainerRemove = NULL;
KG3DModelST *pModelST = NULL;
KG3DBip *pBip = NULL;
DWORD dwStartTime = timeGetTime();
BOOL bTagAddRefFlag = FALSE;
KG_ASSERT_EXIT(strAnimationName);
KG_ASSERT_EXIT(uPresetIndex < m_PresetPathName.size());
KG_ASSERT_EXIT(pClip);
if (uPresetIndex != m_uCurrentPreset)
{
hrRetCode = LoadPreset(uPresetIndex);
KG_COM_PROCESS_ERROR(hrRetCode);
m_uCurrentPreset = uPresetIndex;
}
m_Warper.Enable(TRUE);
pTagContainerRemove = m_Warper.m_vecTagContainers[dwSplitType];
if (pTagContainerRemove)
{
static DWORD const s_dwControllerMap[] = { 1, 0 };
hrRetCode = m_Warper.GetComposer(dwSplitType, (IEKG3DAnimationComposer**)&pComposer);
KG_COM_PROCESS_ERROR(hrRetCode);
pController = pComposer->GetAnimationController(s_dwControllerMap[dwSplitType]);
KG_PROCESS_ERROR(pController);
pController->RemoveAnimationControllerUpdateNotifier(pTagContainerRemove);
SAFE_RELEASE(pTagContainerRemove);
m_Warper.m_vecTagContainers[dwSplitType] = NULL;
}
if (AniType == MPAT_TAGGED)
{
KG_ASSERT_EXIT(pTagContainerNew);
if (dwSplitType == ANI_JOINT_BOTTOM)
{
//在这里暂时禁止掉下半身的标签的功能
AniType = MPAT_NORMAL;
}
else
{
pTagContainerNew->AttachToModel(m_pModel);
m_Warper.m_vecTagContainers[dwSplitType] = pTagContainerNew;
m_Warper.m_vecTagContainers[dwSplitType]->AddRef();
bTagAddRefFlag = TRUE;
}
}
ASSERT(m_pModel->GetType() == MESHTYPE_MODELST);
pModelST = dynamic_cast<KG3DModelST*>(m_pModel);
KG_PROCESS_ERROR(pModelST);
pBip = pModelST->GetBip();
KG_PROCESS_ERROR(pBip);
hrRetCode = GetClipTool().CheckClipByBip(pClip, pBip);
KGLOG_COM_PROCESS_ERROR(hrRetCode);
switch (dwSplitType)
{
case ANI_JOINT_TOP:
{
KG3DAnimationController ControllerSaveTop;
m_Warper.GetComposer(JOINT_TOPINFO_COMPOSERINDEX, (IEKG3DAnimationComposer **)&pComposer);
ASSERT(pComposer);
pController = pComposer->GetAnimationController(JOINT_TOPINFO_ANI_TOP_INDEX);
ASSERT(pController);
pController->Clone(ControllerSaveTop);
pController->SetUserdata(pUserdata);
pController->StartAnimation(dwPlayType, nOffsetTime, fSpeed);
if (AniType == MPAT_TAGGED)
pController->AddAnimationControllerUpdateNotifier(pTagContainerNew);
m_Warper.ChangeAnimation(JOINT_TOPINFO_COMPOSERINDEX,
JOINT_TOPINFO_ANI_TOP_INDEX,
pClip,
&ControllerSaveTop,
m_Warper.m_TweenSpan[dwSplitType].dwTweenIn);
}
break;
case ANI_JOINT_BOTTOM:
{
KG3DAnimationController ControllerSaveBottom;
m_Warper.GetComposer(JOINT_BOTTOMINFO_COMPOSERINDEX, (IEKG3DAnimationComposer **)&pComposer);
ASSERT(pComposer);
pController = pComposer->GetAnimationController(JOINT_BOTTOMINFO_ANI_BOTTOM_INDEX);
ASSERT(pController);
pController->Clone(ControllerSaveBottom);
pController->SetUserdata(pUserdata);
pController->StartAnimation(dwPlayType, nOffsetTime, fSpeed);
if (AniType == MPAT_TAGGED)
pController->AddAnimationControllerUpdateNotifier(pTagContainerNew);
m_Warper.ChangeAnimation(JOINT_BOTTOMINFO_COMPOSERINDEX,
JOINT_BOTTOMINFO_ANI_BOTTOM_INDEX,
pClip,
&ControllerSaveBottom,
m_Warper.m_TweenSpan[dwSplitType].dwTweenIn);
}
break;
default:
ASSERT(0);
}
m_Warper.GetComposer(JOINT_TOPINFO_COMPOSERINDEX, (IEKG3DAnimationComposer **)&pComposer);
ASSERT(pComposer);
pController = pComposer->GetAnimationController(JOINT_TOPINFO_ANI_TOP_INDEX);
ASSERT(pController);
pController->SetMotionExtraInfo(IKG3DAnimationController::TYPE_PART0);
m_Warper.GetComposer(JOINT_BOTTOMINFO_COMPOSERINDEX, (IEKG3DAnimationComposer **)&pComposer);
ASSERT(pComposer);
pController = pComposer->GetAnimationController(JOINT_BOTTOMINFO_ANI_BOTTOM_INDEX);
ASSERT(pController);
pController->SetMotionExtraInfo(IKG3DAnimationController::TYPE_PART1);
hrResult = S_OK;
Exit0:
if (FAILED(hrResult))
{
if (bTagAddRefFlag)
{
KG_COM_RELEASE(m_Warper.m_vecTagContainers[dwSplitType]);
bTagAddRefFlag = FALSE;
}
}
DWORD dwCost = timeGetTime() - dwStartTime;
if(g_cEngineOption.bEnableTimeOptimizeLog && dwCost > 10)
{
KGLogPrintf(KGLOG_INFO,"TimeOptimize KG3DAnimationSplitter::PlayAnimationChange cost %d",dwCost);
}
return hrResult;
}
extern KG3DAnimationWarperTable g_cAnimationWarperTable;
HRESULT KG3DAnimationSplitter::LoadPreset(unsigned int uIndex)
{
HRESULT hr = E_FAIL;
TCHAR strFullPath[MAX_PATH];
KG_PROCESS_ERROR(uIndex < m_PresetPathName.size());
sprintf_s(strFullPath,
MAX_PATH,
"%s",
m_PresetPathName[uIndex].c_str());
hr = g_cAnimationWarperTable.LoadWarper(&m_Warper,strFullPath);
//hr = m_Warper.Load(strFullPath);
Exit0:
return hr;
}
HRESULT KG3DAnimationSplitter::LoadConfig()
{
HRESULT hResult = E_FAIL;
TCHAR strConfigFilePath[MAX_PATH];
TCHAR strSectionName[MAX_PATH];
IIniFile *pConfig = NULL;
int nNumSection = 0;
KG_PROCESS_SUCCESS(m_bConfigLoaded);
m_PresetPathName.clear();
pConfig = g_OpenIniFile(s_strConfigFile);
KG_PROCESS_ERROR(pConfig);
pConfig->GetInteger("Header", "NumSection", 0, &nNumSection);
m_PresetPathName.resize(nNumSection);
for (int i = 0; i < nNumSection; i++)
{
sprintf_s(strSectionName,
MAX_PATH,
"Section%d",
i);
pConfig->GetString(strSectionName,
"File",
"",
strConfigFilePath,
MAX_PATH);
m_PresetPathName[i] = strConfigFilePath;
}
m_bConfigLoaded = TRUE;
Exit1:
hResult = S_OK;
Exit0:
KG_COM_RELEASE(pConfig);
if (FAILED(hResult))
{
KGLogPrintf(KGLOG_ERR, "KG3DAnimationSplitter load configuration file %s failed.", s_strConfigFile);
}
return hResult;
}
BOOL KG3DAnimationSplitter::GetEnable()
{
return m_Warper.GetEnable();
}
HRESULT KG3DAnimationSplitter::FrameMove(D3DXMATRIX *pResult)
{
HRESULT hRetCode = E_FAIL;
if (m_Warper.GetEnable())
{
hRetCode = m_Warper.FrameMove(pResult);
}
return hRetCode;
}
KG3DAnimationWarper* KG3DAnimationSplitter::GetAnimationWarper()
{
return &m_Warper;
}
void KG3DAnimationSplitter::EnableWarper(BOOL bEnable)
{
m_Warper.Enable(bEnable);
}
void KG3DAnimationSplitter::SeekAnimation(DWORD dwSplitType,
enuAnimationControllerPriority nPrority,
DWORD dwSeekType,
int nOffset)
{
switch(nPrority)
{
case ANICTL_PRIMARY:
{
KG3DAnimationComposer *pComposer = NULL;
KG3DAnimationController *pController = NULL;
switch (dwSplitType)
{
case ANI_JOINT_TOP:
{
m_Warper.GetComposer(JOINT_TOPINFO_COMPOSERINDEX, (IEKG3DAnimationComposer **)&pComposer);
ASSERT(pComposer);
KGLOG_PROCESS_ERROR(pComposer);
pController = pComposer->GetAnimationController(JOINT_TOPINFO_ANI_TOP_INDEX);
KGLOG_PROCESS_ERROR(pController);
ASSERT(pController);
pController->SeekAnimation(dwSeekType, nOffset);
}
break;
case ANI_JOINT_BOTTOM:
{
m_Warper.GetComposer(JOINT_BOTTOMINFO_COMPOSERINDEX, (IEKG3DAnimationComposer **)&pComposer);
ASSERT(pComposer);
KGLOG_PROCESS_ERROR(pComposer);
pController = pComposer->GetAnimationController(JOINT_BOTTOMINFO_ANI_BOTTOM_INDEX);
KGLOG_PROCESS_ERROR(pController);
ASSERT(pController);
pController->SeekAnimation(dwSeekType, nOffset);
}
break;
}
}
break;
case ANICTL_SECONDARY:
{
m_Warper.m_SecondaryControllers[dwSplitType].SeekAnimation(dwSeekType, nOffset);
}
break;
}
Exit0:
;
}
| [
"dark.hades.1102@GAMIL.COM"
] | dark.hades.1102@GAMIL.COM |
ce6400697adec5339f52aa83d9ebd1b144cb55ef | 93e55f080779f16f47a7382a3fb0b29a4189e074 | /convertor/huawei/1.72.T5.0.B050/atc/ccec_compiler/include/llvm/Analysis/BasicAliasAnalysis.h | 049c22022ab400fe42ccaee8f3fe8290632bc0f8 | [] | no_license | jizhuoran/caffe-huawei-atlas-convertor | b00cfdec3888da3bb18794f52a41deea316ada67 | 148511a31bfd195df889291946c43bb585acb546 | refs/heads/master | 2022-11-25T13:59:45.181910 | 2020-07-31T07:37:02 | 2020-07-31T07:37:02 | 283,966,371 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,609 | h | //===- BasicAliasAnalysis.h - Stateless, local Alias Analysis ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This is the interface for LLVM's primary stateless and local alias analysis.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_ANALYSIS_BASICALIASANALYSIS_H
#define LLVM_ANALYSIS_BASICALIASANALYSIS_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Pass.h"
#include <algorithm>
#include <cstdint>
#include <memory>
#include <utility>
namespace llvm {
struct AAMDNodes;
class APInt;
class AssumptionCache;
class BasicBlock;
class DataLayout;
class DominatorTree;
class Function;
class GEPOperator;
class LoopInfo;
class PHINode;
class SelectInst;
class TargetLibraryInfo;
class PhiValues;
class Value;
/// This is the AA result object for the basic, local, and stateless alias
/// analysis. It implements the AA query interface in an entirely stateless
/// manner. As one consequence, it is never invalidated due to IR changes.
/// While it does retain some storage, that is used as an optimization and not
/// to preserve information from query to query. However it does retain handles
/// to various other analyses and must be recomputed when those analyses are.
class BasicAAResult : public AAResultBase<BasicAAResult> {
friend AAResultBase<BasicAAResult>;
const DataLayout &DL;
const Function &F;
const TargetLibraryInfo &TLI;
AssumptionCache &AC;
DominatorTree *DT;
LoopInfo *LI;
PhiValues *PV;
bool DisNullPointerOpt;
public:
BasicAAResult(const DataLayout &DL, const Function &F,
const TargetLibraryInfo &TLI, AssumptionCache &AC,
DominatorTree *DT = nullptr, LoopInfo *LI = nullptr,
PhiValues *PV = nullptr,
bool disableNullPointerOptimizations = false)
: AAResultBase(), DL(DL), F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), PV(PV),
DisNullPointerOpt(disableNullPointerOptimizations) {}
BasicAAResult(const BasicAAResult &Arg,
bool disableNullPointerOptimizations = false)
: AAResultBase(Arg), DL(Arg.DL), F(Arg.F), TLI(Arg.TLI), AC(Arg.AC),
DT(Arg.DT), LI(Arg.LI), PV(Arg.PV),
DisNullPointerOpt(disableNullPointerOptimizations) {}
BasicAAResult(BasicAAResult &&Arg,
bool disableNullPointerOptimizations = false)
: AAResultBase(std::move(Arg)), DL(Arg.DL), F(Arg.F), TLI(Arg.TLI),
AC(Arg.AC), DT(Arg.DT), LI(Arg.LI), PV(Arg.PV),
DisNullPointerOpt(disableNullPointerOptimizations) {}
/// Handle invalidation events in the new pass manager.
bool invalidate(Function &Fn, const PreservedAnalyses &PA,
FunctionAnalysisManager::Invalidator &Inv);
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc);
ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2);
/// Chases pointers until we find a (constant global) or not.
bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal);
/// Get the location associated with a pointer argument of a callsite.
ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx);
/// Returns the behavior when calling the given call site.
FunctionModRefBehavior getModRefBehavior(const CallBase *Call);
/// Returns the behavior when calling the given function. For use when the
/// call site is not known.
FunctionModRefBehavior getModRefBehavior(const Function *Fn);
private:
// A linear transformation of a Value; this class represents ZExt(SExt(V,
// SExtBits), ZExtBits) * Scale + Offset.
struct VariableGEPIndex {
// An opaque Value - we can't decompose this further.
const Value *V;
// We need to track what extensions we've done as we consider the same Value
// with different extensions as different variables in a GEP's linear
// expression;
// e.g.: if V == -1, then sext(x) != zext(x).
unsigned ZExtBits;
unsigned SExtBits;
APInt Scale;
bool operator==(const VariableGEPIndex &Other) const {
return V == Other.V && ZExtBits == Other.ZExtBits &&
SExtBits == Other.SExtBits && Scale == Other.Scale;
}
bool operator!=(const VariableGEPIndex &Other) const {
return !operator==(Other);
}
};
// Represents the internal structure of a GEP, decomposed into a base pointer,
// constant offsets, and variable scaled indices.
struct DecomposedGEP {
// Base pointer of the GEP
const Value *Base;
// Total constant offset w.r.t the base from indexing into structs
APInt StructOffset;
// Total constant offset w.r.t the base from indexing through
// pointers/arrays/vectors
APInt OtherOffset;
// Scaled variable (non-constant) indices.
SmallVector<VariableGEPIndex, 4> VarIndices;
};
/// Track alias queries to guard against recursion.
using LocPair = std::pair<MemoryLocation, MemoryLocation>;
using AliasCacheTy = SmallDenseMap<LocPair, AliasResult, 8>;
AliasCacheTy AliasCache;
/// Tracks phi nodes we have visited.
///
/// When interpret "Value" pointer equality as value equality we need to make
/// sure that the "Value" is not part of a cycle. Otherwise, two uses could
/// come from different "iterations" of a cycle and see different values for
/// the same "Value" pointer.
///
/// The following example shows the problem:
/// %p = phi(%alloca1, %addr2)
/// %l = load %ptr
/// %addr1 = gep, %alloca2, 0, %l
/// %addr2 = gep %alloca2, 0, (%l + 1)
/// alias(%p, %addr1) -> MayAlias !
/// store %l, ...
SmallPtrSet<const BasicBlock *, 8> VisitedPhiBBs;
/// Tracks instructions visited by pointsToConstantMemory.
SmallPtrSet<const Value *, 16> Visited;
static const Value *
GetLinearExpression(const Value *V, APInt &Scale, APInt &Offset,
unsigned &ZExtBits, unsigned &SExtBits,
const DataLayout &DL, unsigned Depth, AssumptionCache *AC,
DominatorTree *DT, bool &NSW, bool &NUW);
static bool DecomposeGEPExpression(const Value *V, DecomposedGEP &Decomposed,
const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT);
static bool isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
LocationSize ObjectAccessSize);
/// A Heuristic for aliasGEP that searches for a constant offset
/// between the variables.
///
/// GetLinearExpression has some limitations, as generally zext(%x + 1)
/// != zext(%x) + zext(1) if the arithmetic overflows. GetLinearExpression
/// will therefore conservatively refuse to decompose these expressions.
/// However, we know that, for all %x, zext(%x) != zext(%x + 1), even if
/// the addition overflows.
bool
constantOffsetHeuristic(const SmallVectorImpl<VariableGEPIndex> &VarIndices,
LocationSize V1Size, LocationSize V2Size,
APInt BaseOffset, AssumptionCache *AC,
DominatorTree *DT);
bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
const SmallVectorImpl<VariableGEPIndex> &Src);
AliasResult aliasGEP(const GEPOperator *V1, LocationSize V1Size,
const AAMDNodes &V1AAInfo, const Value *V2,
LocationSize V2Size, const AAMDNodes &V2AAInfo,
const Value *UnderlyingV1, const Value *UnderlyingV2);
AliasResult aliasPHI(const PHINode *PN, LocationSize PNSize,
const AAMDNodes &PNAAInfo, const Value *V2,
LocationSize V2Size, const AAMDNodes &V2AAInfo,
const Value *UnderV2);
AliasResult aliasSelect(const SelectInst *SI, LocationSize SISize,
const AAMDNodes &SIAAInfo, const Value *V2,
LocationSize V2Size, const AAMDNodes &V2AAInfo,
const Value *UnderV2);
AliasResult aliasCheck(const Value *V1, LocationSize V1Size,
AAMDNodes V1AATag, const Value *V2,
LocationSize V2Size, AAMDNodes V2AATag,
const Value *O1 = nullptr, const Value *O2 = nullptr);
};
/// Analysis pass providing a never-invalidated alias analysis result.
class BasicAA : public AnalysisInfoMixin<BasicAA> {
friend AnalysisInfoMixin<BasicAA>;
static AnalysisKey Key;
public:
using Result = BasicAAResult;
BasicAAResult run(Function &F, FunctionAnalysisManager &AM);
};
/// Legacy wrapper pass to provide the BasicAAResult object.
class BasicAAWrapperPass : public FunctionPass {
std::unique_ptr<BasicAAResult> Result;
virtual void anchor();
public:
static char ID;
BasicAAWrapperPass();
BasicAAResult &getResult() { return *Result; }
const BasicAAResult &getResult() const { return *Result; }
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
};
FunctionPass *createBasicAAWrapperPass();
/// A helper for the legacy pass manager to create a \c BasicAAResult object
/// populated to the best of our ability for a particular function when inside
/// of a \c ModulePass or a \c CallGraphSCCPass.
BasicAAResult createLegacyPMBasicAAResult(Pass &P, Function &F);
/// This class is a functor to be used in legacy module or SCC passes for
/// computing AA results for a function. We store the results in fields so that
/// they live long enough to be queried, but we re-use them each time.
class LegacyAARGetter {
Pass &P;
Optional<BasicAAResult> BAR;
Optional<AAResults> AAR;
public:
LegacyAARGetter(Pass &P) : P(P) {}
AAResults &operator()(Function &F) {
BAR.emplace(createLegacyPMBasicAAResult(P, F));
AAR.emplace(createLegacyPMAAResults(P, F, *BAR));
return *AAR;
}
};
} // end namespace llvm
#endif // LLVM_ANALYSIS_BASICALIASANALYSIS_H
| [
"jizr@connect.hku.hk"
] | jizr@connect.hku.hk |
1a5d76fbb4fced3f97ab7d836c963ea5b813d628 | ea9fdab491ca277959f7dc59004d1a30c4ee6be4 | /virtualbox/patches/patch-src_VBox_VMM_testcase_tstX86-1.cpp | e8047bf207409a265a14c969bd85d16869b1d483 | [] | no_license | NetBSD/pkgsrc-wip | 99f40fb6f56e2a5a11840a810e9cf8b6097e7f21 | c94e923855e9515400435b2437a1659fdb26d2fb | refs/heads/master | 2023-08-30T14:27:26.946664 | 2023-08-30T12:09:15 | 2023-08-30T12:09:15 | 42,824,785 | 81 | 59 | null | 2021-01-28T20:10:38 | 2015-09-20T18:44:07 | Makefile | UTF-8 | C++ | false | false | 826 | cpp | $NetBSD$
--- src/VBox/VMM/testcase/tstX86-1.cpp.orig 2016-03-04 19:30:15.000000000 +0000
+++ src/VBox/VMM/testcase/tstX86-1.cpp
@@ -112,6 +112,13 @@ static void sigHandler(int iSig, siginfo
uintptr_t uErr = ~(uintptr_t)0;
uintptr_t uCr2 = ~(uintptr_t)0;
+# elif defined(RT_ARCH_AMD64) && defined(RT_OS_NETBSD)
+ uintptr_t *puPC = (uintptr_t *)&pCtx->pc;
+ uintptr_t *puSP = (uintptr_t *)&pCtx->sp;
+ uintptr_t uTrapNo = ~(uintptr_t)0;
+ uintptr_t uErr = ~(uintptr_t)0;
+ uintptr_t uCr2 = ~(uintptr_t)0;
+
# elif defined(RT_ARCH_AMD64)
uintptr_t *puPC = (uintptr_t *)&pCtx->uc_mcontext.gregs[REG_RIP];
uintptr_t *puSP = (uintptr_t *)&pCtx->uc_mcontext.gregs[REG_RSP];
@@ -267,4 +274,3 @@ int main()
return RTTestSummaryAndDestroy(hTest);
}
-
| [
"rillig@NetBSD.org"
] | rillig@NetBSD.org |
9066616fa6fd3864773961a102b196c37bb98287 | b35451bfa0035682faa945d7a0951334fb223c71 | /BehaviorTree/Includes/BehaviorTree/Details/DecoratorNode.hpp | 05318d1df3c013e62c7ba578bf986949cdec08b8 | [
"MIT"
] | permissive | herpec-j/BehaviorTree | e185d7bd6b0b4b663aaacf24591aea034425ebe6 | 5f9d2f4e60563dd2d6363dc280fd98f545abfc9a | refs/heads/master | 2021-01-19T08:23:50.167994 | 2015-04-08T07:57:50 | 2015-04-08T07:57:50 | 32,944,336 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,763 | hpp | #pragma once
#include "BehaviorTree/Details/CompositeNode.hpp"
namespace AO
{
namespace BehaviorTree
{
inline namespace Version_1
{
namespace Details
{
template <class Entity, typename... Args>
class DecoratorNode : public CompositeNode < Entity, Args... >
{
protected:
using EntityType = typename CompositeNode<Entity, Args...>::EntityType;
using EntityPtr = typename CompositeNode<Entity, Args...>::EntityPtr;
using Parent = typename CompositeNode<Entity, Args...>::Parent;
using ParentPtr = typename CompositeNode<Entity, Args...>::ParentPtr;
using Child = typename CompositeNode<Entity, Args...>::Child;
using ChildPtr = typename CompositeNode<Entity, Args...>::ChildPtr;
using ChildrenList = typename CompositeNode<Entity, Args...>::ChildrenList;
public:
// Destructor
virtual ~DecoratorNode(void) = default;
// Inherited Methods
ParentPtr addChild(ChildPtr child) override final
{
assert(this->children.empty() && "Tree should be empty");
return CompositeNode<Entity, Args...>::addChild(child);
}
protected:
// Constructors
DecoratorNode(void) = default;
DecoratorNode(DecoratorNode const &) = default;
DecoratorNode(DecoratorNode &&) = default;
// Assignment Operators
DecoratorNode &operator=(DecoratorNode const &) = default;
DecoratorNode &operator=(DecoratorNode &&) = default;
// Virtual Methods
virtual void initialize(EntityPtr) override = 0;
virtual Status filter(EntityPtr entity, Args... args) = 0;
// Inherited Methods
Status execute(EntityPtr entity, Args... args) override final
{
return filter(entity, args...);
}
};
}
}
}
}
| [
"jonathan.herpeche+github@gmail.com"
] | jonathan.herpeche+github@gmail.com |
decfdcd1c8d7e8f837e9c7cefee28d76aa7ff0fe | d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3 | /Modules/ThirdParty/VNL/src/vxl/core/vnl/tests/test_quaternion.cxx | fd0614faad1c823a7bc7e09b2369a475c6d7bb82 | [
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"NTP",
"IJG",
"GPL-1.0-or-later",
"libtiff",
"BSD-4.3TAHOE",
"Zlib",
"MIT",
"LicenseRef-scancode-proprietary-license",
"Spencer-86",
"Apache-2.0",
"FSFUL",
"LicenseRef-scancode-public-domain",
"Libpng",
"BSD-2-Clause"
] | permissive | nalinimsingh/ITK_4D | 18e8929672df64df58a6446f047e6ec04d3c2616 | 95a2eacaeaffe572889832ef0894239f89e3f303 | refs/heads/master | 2020-03-17T18:58:50.953317 | 2018-10-01T20:46:43 | 2018-10-01T21:21:01 | 133,841,430 | 0 | 0 | Apache-2.0 | 2018-05-17T16:34:54 | 2018-05-17T16:34:53 | null | UTF-8 | C++ | false | false | 8,438 | cxx | #include <iostream>
#include <limits>
#include <testlib/testlib_test.h>
#include <vnl/vnl_math.h>
#include <vnl/vnl_random.h>
#include <vnl/vnl_quaternion.h>
#include <vnl/vnl_vector_fixed.h>
#include <vnl/vnl_matrix_fixed.h>
#include <vnl/vnl_rotation_matrix.h>
#include <vcl_compiler.h>
// Tolerance between doubles. This was inferred by trial and error.
// Could be derived mathematically?
const double dtol = 16*std::numeric_limits<double>::epsilon();
static void test_operators()
{
vnl_quaternion<double> a(0,0,0,1), b(2,2,2,2), c, d(2,2,2,3), e(1,2,3,4);
TEST("!=", a!=b, true);
TEST("==", a==a, true);
c = a + b; TEST("+", c, d);
TEST(".x()", e.x(), 1.0);
TEST(".y()", e.y(), 2.0);
TEST(".z()", e.z(), 3.0);
TEST(".r()", e.r(), 4.0);
std::cout << std::endl;
}
static void test_random_round_trip()
{
vnl_random rng(13241ul);
unsigned errcount=0;
double avg_sqr_error = 0.0;
for (unsigned i=0;i<1000;++i)
{
// Need to be careful abount wrap around - don't test with angles that are too big
vnl_vector_fixed<double,3> euler(rng.normal()*vnl_math::pi/18.0,
rng.normal()*vnl_math::pi/18.0,
rng.normal()*vnl_math::pi/18.0);
vnl_quaternion<double> quat(euler(0), euler(1), euler(2));
vnl_vector_fixed<double,3> out = quat.rotation_euler_angles();
double err = vnl_vector_ssd(euler, out);
avg_sqr_error+=err;
if (err > 1e-16)
{
errcount++;
std::cout << "ERROR: " << euler << std::endl;
}
}
TEST("1000*Random euler -> quaternion -> euler consistent", errcount, 0);
std::cout << "Average squared error: " << avg_sqr_error << std::endl;
}
static void test_random_euler_near_zero()
{
vnl_random rng(13241ul);
unsigned errcount=0;
double avg_sqr_error = 0.0;
for (unsigned i=0;i<1000;++i)
{
// Need to be careful abount wrap around - don't test with angles that are too big
vnl_vector_fixed<double,3> euler(rng.normal()*vnl_math::pi_over_180,
rng.normal()*vnl_math::pi_over_180,
rng.normal()*vnl_math::pi_over_180);
vnl_quaternion<double> quat(euler(0), euler(1), euler(2));
if (quat.angle() > vnl_math::pi/36.0)
{
errcount++;
std::cout << "ERROR: should be small: " << euler << ": " << quat << std::endl;
}
quat *= -1.0;
vnl_vector_fixed<double,3> out = quat.rotation_euler_angles();
double err = vnl_vector_ssd(euler, out);
avg_sqr_error+=err;
if (err > 1e-16)
{
errcount++;
std::cout << "ERROR: -quat -> euler == quat -> euler" << euler << ": " << out << std::endl;
}
}
TEST("1000*Random small euler -> small quaternion angle", errcount, 0);
std::cout << "Average squared error: " << avg_sqr_error << std::endl;
}
static void test_random_quat_near_zero()
{
vnl_random rng(13241ul);
unsigned errcount=0;
for (unsigned i=0;i<1000;++i)
{
vnl_quaternion<double> quat(rng.normal()/1000.0, rng.normal()/1000.0, rng.normal()/1000.0,
vnl_math::sgn0(rng.normal()) * (1.0+rng.normal()/1000.0) );
quat.normalize();
vnl_vector_fixed<double,3> euler = quat.rotation_euler_angles();
if (euler.magnitude() > 0.01)
{
errcount++;
std::cout << "ERROR: should be small: " << quat << ": " << euler << std::endl;
}
}
TEST("1000*Random small quat -> small euler values", errcount, 0);
}
// Test whether the rotation matrix and Euler angles are correct.
// Do this by checking consistency with vnl_rotation_matrix().
static void test_rotation_matrix_and_euler_angles()
{
bool success = true;
vnl_random rng(13241ul);
const unsigned ntrials=100;
for (unsigned i=0; i<ntrials; ++i)
{
bool this_trial_ok = true;
double x = rng.drand32(-1.0, 1.0);
double y = rng.drand32(-1.0, 1.0);
double z = rng.drand32(-1.0, 1.0);
vnl_vector_fixed<double,3> axis(x,y,z);
axis.normalize();
double ang = rng.drand32(-4*vnl_math::pi, 4*vnl_math::pi);
// Construct the quaternion from this axis and angle,
// and extract both euler_angles and rotation matrix.
vnl_quaternion<double> q(axis, ang);
vnl_vector_fixed<double,3> eu = q.rotation_euler_angles();
vnl_matrix_fixed<double,3,3> R = (q.rotation_matrix_transpose()).transpose();
// Use vnl_rotation_matrix() with axis+angle form
{
vnl_vector_fixed<double,3> axis_ang = axis * ang;
vnl_matrix_fixed<double,3,3> M = vnl_rotation_matrix(axis_ang);
vnl_matrix_fixed<double,3,3> D = R - M;
double max_err = D.absolute_value_max();
this_trial_ok = this_trial_ok && (max_err<=dtol);
#ifndef NDEBUG
if (max_err>dtol)
{
std::cout << "Warning (a+a): max_err=" << max_err
<< " dtol=" << dtol << std::endl;
}
#endif
}
// Use vnl_rotation_matrix() with euler angles.
{
vnl_vector<double> ex(3), ey(3), ez(3);
ex[0]=1.0; ex[1]=0.0; ex[2]=0.0;
ey[0]=0.0; ey[1]=1.0; ey[2]=0.0;
ez[0]=0.0; ez[1]=0.0; ez[2]=1.0;
ex *= eu[0];
ey *= eu[1];
ez *= eu[2];
vnl_matrix<double> Rx = vnl_rotation_matrix(ex);
vnl_matrix<double> Ry = vnl_rotation_matrix(ey);
vnl_matrix<double> Rz = vnl_rotation_matrix(ez);
vnl_matrix<double> M = Rz * Ry * Rx;
vnl_matrix<double> D = R - M;
double max_err = D.absolute_value_max();
this_trial_ok = this_trial_ok && (max_err<=dtol);
#ifndef NDEBUG
if (max_err>dtol)
{
std::cout << "Warning (ea): max_err=" << max_err
<< " dtol=" << dtol << std::endl;
}
#endif
}
success = success && this_trial_ok;
}
TEST("test_rotation_matrix_and_euler_angles() for many trials", success, true);
}
static void test_rotations()
{
vnl_vector_fixed<double,3> p1(2,2,2), p2(1,0,0), p3(0,1,0);
vnl_vector_fixed<double,3> e0(0,0,0);
vnl_quaternion<double> q0(0,0,0,0);
TEST_NEAR("rotate p1 using q0", vnl_vector_ssd(q0.rotate(p1),p1), 0.0, 1e-8);
TEST_NEAR("rotate p2 using q0", vnl_vector_ssd(q0.rotate(p2),p2), 0.0, 1e-8);
vnl_quaternion<double> q0_b(0,0,0,1);
TEST_NEAR("rotate p1 using q0_b", vnl_vector_ssd(q0_b.rotate(p1),p1), 0.0, 1e-8);
TEST_NEAR("rotate p2 using q0_b", vnl_vector_ssd(q0_b.rotate(p2),p2), 0.0, 1e-8);
TEST_NEAR("q0_b -> Euler angles", vnl_vector_ssd(q0_b.rotation_euler_angles(),e0), 0.0, 1e-8);
std::cout << "q0_b -> Euler angles: " << q0_b.rotation_euler_angles() << std::endl;
vnl_quaternion<double> q0_c(0,0,0,-4);
TEST_NEAR("rotate p1 using q0_c", vnl_vector_ssd(q0_c.rotate(p1),p1), 0.0, 1e-8);
TEST_NEAR("rotate p2 using q0_c", vnl_vector_ssd(q0_c.rotate(p2),p2), 0.0, 1e-8);
vnl_quaternion<double> q0_d(0,0,0);
TEST_NEAR("rotate p1 using q0_d", vnl_vector_ssd(q0_d.rotate(p1),p1), 0.0, 1e-8);
TEST_NEAR("rotate p2 using q0_d", vnl_vector_ssd(q0_d.rotate(p2),p2), 0.0, 1e-8);
// The axis replacing rotation - i.e. 120 degrees about (1,1,1)
vnl_vector_fixed<double,3> e1(vnl_math::pi/2, 0, vnl_math::pi/2);
vnl_quaternion<double> q1(p1/p1.magnitude(), vnl_math::twopi / 3.0);
TEST_NEAR("rotate p1 using q1", vnl_vector_ssd(q1.rotate(p1),p1), 0.0, 1e-8);
TEST_NEAR("rotate p2 using q1", vnl_vector_ssd(q1.rotate(p2),p3), 0.0, 1e-8);
vnl_vector_fixed<double,3> e1_b = q1.rotation_euler_angles();
TEST_NEAR("q1 -> Euler angles", vnl_vector_ssd(e1_b,e1), 0.0, 1e-8);
vnl_quaternion<double> q1_c = -q1;
vnl_vector_fixed<double,3> e1_c = q1_c.rotation_euler_angles();
TEST_NEAR("-q1 -> Euler angles", vnl_vector_ssd(e1_c,e1), 0.0, 1e-8);
std::cout << "q1 -> Euler angles: " << e1 << std::endl;
vnl_quaternion<double> q1_b(e1(0), e1(1), e1(2));
std::cout << "q1 -> Euler angles: " << q1_b << std::endl;
TEST_NEAR("Euler angles -> q1",
vnl_vector_ssd(q1_b, q1), 0.0, 1e-8);
std::cout << "Euler angles -> q1: " << q1_b << std::endl;
test_random_round_trip();
test_random_quat_near_zero();
test_random_euler_near_zero();
test_rotation_matrix_and_euler_angles();
}
// Main testing function
void test_quaternion()
{
test_operators();
test_rotations();
}
TESTMAIN(test_quaternion);
| [
"ruizhi@csail.mit.edu"
] | ruizhi@csail.mit.edu |
cd60ab80281def89c87a624b6e45a10cf404bdfe | 813eb8705581a31726c432007406c88af4ac9822 | /Kth_root.cpp | e87a573346c30faf917a02e0a6d1d13c987f5b35 | [] | no_license | vansh-kapila/Coding_Blocks_CPP | ac59a8b1e444ab4ef1e2204e9b514ce856ce974d | f660d544e578ab361bc12d52fca539b478057c0e | refs/heads/main | 2023-07-13T20:39:07.878081 | 2021-08-18T07:06:38 | 2021-08-18T07:06:38 | 397,504,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,150 | cpp | /* Author : VANSH KAPILA */
/* "The greatest glory in living lies not in never falling, but in rising every time we fall." -*/
#include <bits/stdc++.h>
#define pb(x) push_back(x)
#define all(x) x.begin(), x.end()
#define debug(x) cout << '>' << #x << ':' << x << endl;
#define int long long
#define ld long double
#define endl "\n";
const int mod = 1000000007;
using namespace std;
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int test;
cin >> test;
while (test--) {
double n, k;
cin >> n >> k;
int r = n;
int l = 1;
int ans = 0;
while (l <= r)
{
int mid = (l + r) / 2;
if (pow(mid, k) == n)
{
ans = mid + 1;
break;
}
else if (pow(mid, k) < n)
{
l = mid;
ans = mid;
}
else
{
r = mid - 1;
ans = mid;
}
}
int x = 1;
ans--;
cout << max(x, ans) << endl;
}
return 0;
} | [
"vanshkapila2002@gmail.com"
] | vanshkapila2002@gmail.com |
879d921b1214b68999b1eb3a96870eac62d57519 | 2758b84e44ea542f42c087d689e847353426e2db | /Libs/Include/OutputFile.h | 46c5ca95e605f3d2dcf883c89f8f68a44b8388d5 | [] | no_license | stravaganza/sgzsourcepack | db8949506f5d68c6ed23bdf2681b67ba4b485ce6 | 20ac3be3c4a9f994c7119030baff3bad216c5a09 | refs/heads/master | 2016-09-05T14:22:55.940388 | 2013-10-16T07:44:33 | 2013-10-16T07:44:33 | 13,604,601 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,345 | h | // ==[ File ]===================================================================================
//
// -Name : OutputFile.h
// -Proyect : BaseLib
// -Author : Enrique Tromp Maseda A.K.A. Ithaqua^Stravaganza
//
// -Contents : COutputFile definition.
//
// =============================================================================================
/*
27/09/2001 - File created.
*/
#ifndef __OUTPUTFILE_H
#define __OUTPUTFILE_H
// ==[ Class definitions ]======================================================================
// --[ Class ]-----------------------------------------------------------
//
// - Name : COutputFile
//
// - Purpose : File data output.
//
// - Note : Data output is limited to secuential order.
//
// ---------------------------------------------------------------------------
class COutputFile : public COutput
{
public:
COutputFile();
~COutputFile() { Close(); }
bool Open(const std::string& strFile, bool bAsText, bool bAppend);
bool Ready() const { return m_pFile != NULL; }
bool Close();
bool WriteChar (char chValue);
bool WriteInt (int nValue);
bool WriteFloat(float fValue);
int WriteRawData (int nNumBytes, int nNumTimes, const void *pSource);
int WriteStringZero(const std::string& strStringZero);
private:
FILE* m_pFile;
};
#endif
| [
"fernandojsg@gmail.com"
] | fernandojsg@gmail.com |
80bd10e77d61bb41896fad1ab6b944edcaf47689 | 871cca811f1517447f04fd3c57597df1342bc487 | /c/dp/0-1.cpp | 964c0258621c769830e48b14b9733ffac622218e | [] | no_license | sonaspy/LeetCode | a4794f3ab46ba8116ea78a2fd48253735469e212 | da34f85a393ba0d2c566949c2c10ae7d1bca0580 | refs/heads/master | 2021-06-22T04:06:02.147723 | 2021-01-04T12:22:40 | 2021-01-04T12:22:40 | 175,682,471 | 0 | 0 | null | 2020-09-20T11:12:06 | 2019-03-14T19:00:16 | C++ | UTF-8 | C++ | false | false | 829 | cpp | // author -sonaspy@outlook.com
// coding - utf_8
#include <bits/stdc++.h>
#define test() freopen("in", "r", stdin)
using namespace std;
vector<int> w, d;
int n, m;
int main(int argc, char const *argv[])
{
/* code */
//test();
cin >> n >> m;
w = vector<int>(n + 1);
d = vector<int>(n + 1);
vector<vector<int>> f(n + 1, vector<int>(m + 1, 0));
f[0] = vector<int>(n + 1, 1);
/*
f[i][j] = 前i个物品 总体积不超过j max价值总和
体积 M
c [0][0][0][0][0][0][0][0][0][0][0]
h [0][0][y][0][0][0][0][0][0][0][0]
N o [0][0][0][0][0][0][0][0][0][0][0]
o [0][0][0][0][0][0][0][0][0][0][0]
s [0][0][x][t][0][0][0][0][0][0][0]
e [0][0][0][0][0][0][0][0][0][0][0]
*/
int ans = f.back().back();
return 0;
} | [
"sonaspy@zju.edu.cn"
] | sonaspy@zju.edu.cn |
2439bff0acead2f5024ab2c0655c0df3412c69a8 | 13e3207ae5a63c70cabcf2bab00547df487ea657 | /MetodyPomocnicze.cpp | fc46e552672beb19f60331782782ee5c695f3f47 | [] | no_license | mateuszklosek/Budzet_Osobisty | 8a6f926f1b5a3e4eee3d40e1199bdd7cb250d3e8 | 74f087d5c807ff8c8a2f8cb07b17eec740e360d3 | refs/heads/master | 2023-03-03T07:26:36.329774 | 2021-02-07T20:33:50 | 2021-02-07T20:33:50 | 332,528,067 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,202 | cpp | #include "MetodyPomocnicze.h"
char MetodyPomocnicze::getChoice() {
string wejscie = "";
char znak = {0};
while (true) {
getline(cin, wejscie);
if (wejscie.length() == 1) {
znak = wejscie[0];
break;
}
cout << "To nie jest pojedynczy znak. Wpisz ponownie." << endl;
return 0;
}
return znak;
}
string MetodyPomocnicze::getLine() {
string wejscie = "";
getline(cin, wejscie);
return wejscie;
}
int MetodyPomocnicze::dateToInt(string date) {
string newDate, year, day, month;
int newDateInt;
year = date.substr(0,4);
day = date.substr(8,2);
date.erase(0,5);
month = date.erase(2,3);
newDate = year + month + day;
newDateInt = atoi(newDate.c_str());
return newDateInt;
}
string MetodyPomocnicze::dateToString(int date) {
string year, month, day,newDate;
ostringstream ss;
ss<<date;
string str = ss.str();
year = str.substr(0,4);
day = str.substr(6,2);
month = str.substr(4,2);
newDate = year + "-" +month + "-" +day;
return newDate;
}
string MetodyPomocnicze::localDate() {
time_t czas;
struct tm * data;
char bufor[ 11 ];
stringstream ss;
string dzisiejszaData;
time( & czas );
data = localtime( & czas );
strftime( bufor, sizeof( bufor ), "%Y-%m-%d", data );
ss << bufor;
ss >> dzisiejszaData;
return dzisiejszaData;
}
int MetodyPomocnicze::howManyDays(int month, int year) {
int days=0;
if (month == 4 || month == 6 || month == 9 || month == 11)
days = 30;
else if (month == 02) {
bool leapyear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (leapyear == 0)
days = 28;
else
days = 29;
} else
days = 31;
return days;
}
bool MetodyPomocnicze::isDateCorrect(string date) {
int intDate =0, correctDays =0;
if (date.size() == 10 && date[4] == '-' && date[7] == '-') {
intDate = dateToInt(date);
int year = 0, month = 0, days = 0;
year = intDate/10000;
month = (intDate - year*10000)/100;
days = intDate - (intDate/100)*100;
/*cout << year << "-rok " << month << "- miesiac " << days << endl;
cout << howManyDays(month, year) << endl;
system("pause"); */
if (howManyDays(month, year) >= days && month <= 12 && year >= 1000){
return true; }
else
return false;
} else {
return false;
}
}
double MetodyPomocnicze::stringToDouble(string amountInString){
double amount = ::atof(amountInString.c_str());
//cout << setprecision(2) << fixed <<amount << endl;
return amount;
}
string MetodyPomocnicze::commaToDot(string amount){
int sizeOfAmount = amount.size();
for (int i = 0; i <= sizeOfAmount; i++)
{
if (amount[i] == ','){
amount[i] = '.';
if (sizeOfAmount > i+3){
amount.erase(i+3,sizeOfAmount-i-3);
}
}
if (amount[i] == '.'){
if (sizeOfAmount > i+3){
amount.erase(i+3,sizeOfAmount-i-3);
}
}
}
//cout << amount << endl;
return amount;
}
| [
"klosekmateusz@gmail.com"
] | klosekmateusz@gmail.com |
a6f531f41a1a17c953a91b947c9d38d98d64e7c0 | 19d05e32de0f8e3f949e4dc3e29100497cc32204 | /ocs2_ipm/src/IpmSolver.cpp | 46ea304b7c1fbcc91754c9cd85663b745ebb8732 | [
"BSD-3-Clause"
] | permissive | scmwang/ocs2 | 4ff6cad19520a839fb14986d589c636078f5ec1a | ebde452b10d0eceaac45364f7bb8f0ac1038b637 | refs/heads/main | 2023-07-10T22:59:25.645731 | 2022-12-20T17:07:07 | 2022-12-20T17:07:07 | 395,916,310 | 0 | 0 | BSD-3-Clause | 2021-08-14T06:37:03 | 2021-08-14T06:37:03 | null | UTF-8 | C++ | false | false | 48,945 | cpp | /******************************************************************************
Copyright (c) 2020, Farbod Farshidian. 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 holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "ocs2_ipm/IpmSolver.h"
#include <iomanip>
#include <iostream>
#include <numeric>
#include <ocs2_oc/approximate_model/LinearQuadraticApproximator.h>
#include <ocs2_oc/multiple_shooting/Helpers.h>
#include <ocs2_oc/multiple_shooting/Initialization.h>
#include <ocs2_oc/multiple_shooting/LagrangianEvaluation.h>
#include <ocs2_oc/multiple_shooting/MetricsComputation.h>
#include <ocs2_oc/multiple_shooting/PerformanceIndexComputation.h>
#include <ocs2_oc/oc_problem/OcpSize.h>
#include <ocs2_oc/trajectory_adjustment/TrajectorySpreadingHelperFunctions.h>
#include "ocs2_ipm/IpmHelpers.h"
#include "ocs2_ipm/IpmInitialization.h"
#include "ocs2_ipm/IpmPerformanceIndexComputation.h"
namespace ocs2 {
namespace {
ipm::Settings rectifySettings(const OptimalControlProblem& ocp, ipm::Settings&& settings) {
// We have to create the value function if we want to compute the Lagrange multipliers.
if (settings.computeLagrangeMultipliers) {
settings.createValueFunction = true;
}
// Turn off the barrier update strategy if there are no inequality constraints.
if (ocp.inequalityConstraintPtr->empty() && ocp.stateInequalityConstraintPtr->empty() && ocp.preJumpInequalityConstraintPtr->empty() &&
ocp.finalInequalityConstraintPtr->empty()) {
settings.targetBarrierParameter = settings.initialBarrierParameter;
}
return settings;
}
} // anonymous namespace
IpmSolver::IpmSolver(ipm::Settings settings, const OptimalControlProblem& optimalControlProblem, const Initializer& initializer)
: settings_(rectifySettings(optimalControlProblem, std::move(settings))),
hpipmInterface_(OcpSize(), settings_.hpipmSettings),
threadPool_(std::max(settings_.nThreads, size_t(1)) - 1, settings_.threadPriority) {
Eigen::setNbThreads(1); // No multithreading within Eigen.
Eigen::initParallel();
// Dynamics discretization
discretizer_ = selectDynamicsDiscretization(settings_.integratorType);
sensitivityDiscretizer_ = selectDynamicsSensitivityDiscretization(settings_.integratorType);
// Clone objects to have one for each worker
for (int w = 0; w < settings_.nThreads; w++) {
ocpDefinitions_.push_back(optimalControlProblem);
}
// Operating points
initializerPtr_.reset(initializer.clone());
// Linesearch
filterLinesearch_.g_max = settings_.g_max;
filterLinesearch_.g_min = settings_.g_min;
filterLinesearch_.gamma_c = settings_.gamma_c;
filterLinesearch_.armijoFactor = settings_.armijoFactor;
}
IpmSolver::~IpmSolver() {
if (settings_.printSolverStatistics) {
std::cerr << getBenchmarkingInformation() << std::endl;
}
}
void IpmSolver::reset() {
// Clear solution
primalSolution_ = PrimalSolution();
costateTrajectory_.clear();
projectionMultiplierTrajectory_.clear();
slackIneqTrajectory_.clear();
dualIneqTrajectory_.clear();
valueFunction_.clear();
performanceIndeces_.clear();
// reset timers
totalNumIterations_ = 0;
initializationTimer_.reset();
linearQuadraticApproximationTimer_.reset();
solveQpTimer_.reset();
linesearchTimer_.reset();
computeControllerTimer_.reset();
}
std::string IpmSolver::getBenchmarkingInformation() const {
const auto initializationTotal = initializationTimer_.getTotalInMilliseconds();
const auto linearQuadraticApproximationTotal = linearQuadraticApproximationTimer_.getTotalInMilliseconds();
const auto solveQpTotal = solveQpTimer_.getTotalInMilliseconds();
const auto linesearchTotal = linesearchTimer_.getTotalInMilliseconds();
const auto computeControllerTotal = computeControllerTimer_.getTotalInMilliseconds();
const auto benchmarkTotal =
initializationTotal + linearQuadraticApproximationTotal + solveQpTotal + linesearchTotal + computeControllerTotal;
std::stringstream infoStream;
if (benchmarkTotal > 0.0) {
const scalar_t inPercent = 100.0;
infoStream << "\n########################################################################\n";
infoStream << "The benchmarking is computed over " << totalNumIterations_ << " iterations. \n";
infoStream << "IPM Benchmarking\t :\tAverage time [ms] (% of total runtime)\n";
infoStream << "\tInitialization :\t" << initializationTimer_.getAverageInMilliseconds() << " [ms] \t\t("
<< initializationTotal / benchmarkTotal * inPercent << "%)\n";
infoStream << "\tLQ Approximation :\t" << linearQuadraticApproximationTimer_.getAverageInMilliseconds() << " [ms] \t\t("
<< linearQuadraticApproximationTotal / benchmarkTotal * inPercent << "%)\n";
infoStream << "\tSolve QP :\t" << solveQpTimer_.getAverageInMilliseconds() << " [ms] \t\t("
<< solveQpTotal / benchmarkTotal * inPercent << "%)\n";
infoStream << "\tLinesearch :\t" << linesearchTimer_.getAverageInMilliseconds() << " [ms] \t\t("
<< linesearchTotal / benchmarkTotal * inPercent << "%)\n";
infoStream << "\tCompute Controller :\t" << computeControllerTimer_.getAverageInMilliseconds() << " [ms] \t\t("
<< computeControllerTotal / benchmarkTotal * inPercent << "%)\n";
}
return infoStream.str();
}
const std::vector<PerformanceIndex>& IpmSolver::getIterationsLog() const {
if (performanceIndeces_.empty()) {
throw std::runtime_error("[IpmSolver]: No performance log yet, no problem solved yet?");
} else {
return performanceIndeces_;
}
}
ScalarFunctionQuadraticApproximation IpmSolver::getValueFunction(scalar_t time, const vector_t& state) const {
if (valueFunction_.empty()) {
throw std::runtime_error("[IpmSolver] Value function is empty! Is createValueFunction true and did the solver run?");
} else {
// Interpolation
const auto indexAlpha = LinearInterpolation::timeSegment(time, primalSolution_.timeTrajectory_);
ScalarFunctionQuadraticApproximation valueFunction;
using T = std::vector<ocs2::ScalarFunctionQuadraticApproximation>;
using LinearInterpolation::interpolate;
valueFunction.f = 0.0;
valueFunction.dfdx = interpolate(indexAlpha, valueFunction_, [](const T& v, size_t ind) -> const vector_t& { return v[ind].dfdx; });
valueFunction.dfdxx = interpolate(indexAlpha, valueFunction_, [](const T& v, size_t ind) -> const matrix_t& { return v[ind].dfdxx; });
// Re-center around query state
valueFunction.dfdx.noalias() += valueFunction.dfdxx * state;
return valueFunction;
}
}
vector_t IpmSolver::getStateInputEqualityConstraintLagrangian(scalar_t time, const vector_t& state) const {
if (settings_.computeLagrangeMultipliers && !projectionMultiplierTrajectory_.empty()) {
using T = std::vector<multiple_shooting::ProjectionMultiplierCoefficients>;
const auto indexAlpha = LinearInterpolation::timeSegment(time, primalSolution_.timeTrajectory_);
const auto nominalState = LinearInterpolation::interpolate(indexAlpha, primalSolution_.stateTrajectory_);
const auto sensitivityWrtState = LinearInterpolation::interpolate(
indexAlpha, projectionMultiplierCoefficients_, [](const T& v, size_t ind) -> const matrix_t& { return v[ind].dfdx; });
auto multiplier = LinearInterpolation::interpolate(indexAlpha, projectionMultiplierTrajectory_);
multiplier.noalias() += sensitivityWrtState * (state - nominalState);
return multiplier;
} else {
throw std::runtime_error("[IpmSolver] getStateInputEqualityConstraintLagrangian() not available yet.");
}
}
MultiplierCollection IpmSolver::getIntermediateDualSolution(scalar_t time) const {
if (!dualIneqTrajectory_.timeTrajectory.empty()) {
return getIntermediateDualSolutionAtTime(dualIneqTrajectory_, time);
} else {
throw std::runtime_error("[IpmSolver] getIntermediateDualSolution() not available yet.");
}
}
void IpmSolver::runImpl(scalar_t initTime, const vector_t& initState, scalar_t finalTime) {
if (settings_.printSolverStatus || settings_.printLinesearch) {
std::cerr << "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++";
std::cerr << "\n+++++++++++++ IPM solver is initialized ++++++++++++++";
std::cerr << "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
}
// Determine time discretization, taking into account event times.
const auto& eventTimes = this->getReferenceManager().getModeSchedule().eventTimes;
const auto timeDiscretization = timeDiscretizationWithEvents(initTime, finalTime, settings_.dt, eventTimes);
// Initialize references
for (auto& ocpDefinition : ocpDefinitions_) {
const auto& targetTrajectories = this->getReferenceManager().getTargetTrajectories();
ocpDefinition.targetTrajectoriesPtr = &targetTrajectories;
}
// old and new mode schedules for the trajectory spreading
const auto oldModeSchedule = primalSolution_.modeSchedule_;
const auto& newModeSchedule = this->getReferenceManager().getModeSchedule();
initializationTimer_.startTimer();
// Initialize the state and input
if (!primalSolution_.timeTrajectory_.empty()) {
std::ignore = trajectorySpread(oldModeSchedule, newModeSchedule, primalSolution_);
}
vector_array_t x, u;
multiple_shooting::initializeStateInputTrajectories(initState, timeDiscretization, primalSolution_, *initializerPtr_, x, u);
// Initialize the slack and dual variables of the interior point method
if (!slackIneqTrajectory_.timeTrajectory.empty()) {
std::ignore = trajectorySpread(oldModeSchedule, newModeSchedule, slackIneqTrajectory_);
std::ignore = trajectorySpread(oldModeSchedule, newModeSchedule, dualIneqTrajectory_);
}
scalar_t barrierParam = settings_.initialBarrierParameter;
vector_array_t slackStateIneq, dualStateIneq, slackStateInputIneq, dualStateInputIneq;
initializeSlackDualTrajectory(timeDiscretization, x, u, barrierParam, slackStateIneq, dualStateIneq, slackStateInputIneq,
dualStateInputIneq);
// Initialize the costate and projection multiplier
vector_array_t lmd, nu;
if (settings_.computeLagrangeMultipliers) {
initializeCostateTrajectory(timeDiscretization, x, lmd);
initializeProjectionMultiplierTrajectory(timeDiscretization, nu);
}
initializationTimer_.endTimer();
// Bookkeeping
performanceIndeces_.clear();
std::vector<Metrics> metrics;
int iter = 0;
ipm::Convergence convergence = ipm::Convergence::FALSE;
while (convergence == ipm::Convergence::FALSE) {
if (settings_.printSolverStatus || settings_.printLinesearch) {
std::cerr << "\nIPM iteration: " << iter << " (barrier parameter: " << barrierParam << ")\n";
}
// Make QP approximation
linearQuadraticApproximationTimer_.startTimer();
const auto baselinePerformance = setupQuadraticSubproblem(timeDiscretization, initState, x, u, lmd, nu, barrierParam, slackStateIneq,
slackStateInputIneq, dualStateIneq, dualStateInputIneq, metrics);
linearQuadraticApproximationTimer_.endTimer();
// Solve QP
solveQpTimer_.startTimer();
const vector_t delta_x0 = initState - x[0];
const auto deltaSolution =
getOCPSolution(delta_x0, barrierParam, slackStateIneq, dualStateIneq, slackStateInputIneq, dualStateInputIneq);
extractValueFunction(timeDiscretization, x, lmd, deltaSolution.deltaXSol);
solveQpTimer_.endTimer();
// Apply step
linesearchTimer_.startTimer();
const scalar_t maxPrimalStepSize = settings_.usePrimalStepSizeForDual
? std::min(deltaSolution.maxDualStepSize, deltaSolution.maxPrimalStepSize)
: deltaSolution.maxPrimalStepSize;
const auto stepInfo = takePrimalStep(baselinePerformance, timeDiscretization, initState, deltaSolution, x, u, barrierParam,
slackStateIneq, slackStateInputIneq, metrics);
takeDualStep(deltaSolution, stepInfo, lmd, nu, dualStateIneq, dualStateInputIneq);
performanceIndeces_.push_back(stepInfo.performanceAfterStep);
linesearchTimer_.endTimer();
// Check convergence
convergence = checkConvergence(iter, barrierParam, baselinePerformance, stepInfo);
// Update the barrier parameter
barrierParam = updateBarrierParameter(barrierParam, baselinePerformance, stepInfo);
// Next iteration
++iter;
++totalNumIterations_;
}
computeControllerTimer_.startTimer();
primalSolution_ = toPrimalSolution(timeDiscretization, std::move(x), std::move(u));
costateTrajectory_ = std::move(lmd);
projectionMultiplierTrajectory_ = std::move(nu);
slackIneqTrajectory_ = ipm::toDualSolution(timeDiscretization, constraintsSize_, slackStateIneq, slackStateInputIneq);
dualIneqTrajectory_ = ipm::toDualSolution(timeDiscretization, constraintsSize_, dualStateIneq, dualStateInputIneq);
problemMetrics_ = multiple_shooting::toProblemMetrics(timeDiscretization, std::move(metrics));
computeControllerTimer_.endTimer();
if (settings_.printSolverStatus || settings_.printLinesearch) {
std::cerr << "\nConvergence : " << toString(convergence) << "\n";
std::cerr << "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++";
std::cerr << "\n+++++++++++++ IPM solver has terminated ++++++++++++++";
std::cerr << "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
}
}
void IpmSolver::runParallel(std::function<void(int)> taskFunction) {
threadPool_.runParallel(std::move(taskFunction), settings_.nThreads);
}
void IpmSolver::initializeCostateTrajectory(const std::vector<AnnotatedTime>& timeDiscretization, const vector_array_t& stateTrajectory,
vector_array_t& costateTrajectory) const {
costateTrajectory.clear();
costateTrajectory.reserve(stateTrajectory.size());
// Determine till when to use the previous solution
const auto interpolateTill =
primalSolution_.timeTrajectory_.size() < 2 ? timeDiscretization.front().time : primalSolution_.timeTrajectory_.back();
const scalar_t initTime = getIntervalStart(timeDiscretization[0]);
if (initTime < interpolateTill) {
costateTrajectory.push_back(LinearInterpolation::interpolate(initTime, primalSolution_.timeTrajectory_, costateTrajectory_));
} else {
costateTrajectory.push_back(vector_t::Zero(stateTrajectory[0].size()));
}
for (int i = 1; i < stateTrajectory.size(); i++) {
const auto time = getIntervalEnd(timeDiscretization[i]);
if (time < interpolateTill) { // interpolate previous solution
costateTrajectory.push_back(LinearInterpolation::interpolate(time, primalSolution_.timeTrajectory_, costateTrajectory_));
} else { // Initialize with zero
costateTrajectory.push_back(vector_t::Zero(stateTrajectory[i].size()));
}
}
}
void IpmSolver::initializeProjectionMultiplierTrajectory(const std::vector<AnnotatedTime>& timeDiscretization,
vector_array_t& projectionMultiplierTrajectory) const {
const size_t N = static_cast<int>(timeDiscretization.size()) - 1; // size of the input trajectory
projectionMultiplierTrajectory.clear();
projectionMultiplierTrajectory.reserve(N);
const auto& ocpDefinition = ocpDefinitions_[0];
// Determine till when to use the previous solution
const auto interpolateTill =
primalSolution_.timeTrajectory_.size() < 2 ? timeDiscretization.front().time : *std::prev(primalSolution_.timeTrajectory_.end(), 2);
// @todo Fix this using trajectory spreading
auto interpolateProjectionMultiplierTrajectory = [&](scalar_t time) -> vector_t {
const size_t numConstraints = ocpDefinition.equalityConstraintPtr->getNumConstraints(time);
const size_t index = LinearInterpolation::timeSegment(time, primalSolution_.timeTrajectory_).first;
if (projectionMultiplierTrajectory_.size() > index + 1) {
if (projectionMultiplierTrajectory_[index].size() == numConstraints &&
projectionMultiplierTrajectory_[index].size() == projectionMultiplierTrajectory_[index + 1].size()) {
return LinearInterpolation::interpolate(time, primalSolution_.timeTrajectory_, projectionMultiplierTrajectory_);
}
}
if (projectionMultiplierTrajectory_.size() > index) {
if (projectionMultiplierTrajectory_[index].size() == numConstraints) {
return projectionMultiplierTrajectory_[index];
}
}
return vector_t::Zero(numConstraints);
};
for (int i = 0; i < N; i++) {
if (timeDiscretization[i].event == AnnotatedTime::Event::PreEvent) {
// Event Node
projectionMultiplierTrajectory.push_back(vector_t()); // no input at event node
} else {
// Intermediate node
const scalar_t time = getIntervalStart(timeDiscretization[i]);
const size_t numConstraints = ocpDefinition.equalityConstraintPtr->getNumConstraints(time);
if (time < interpolateTill) { // interpolate previous solution
projectionMultiplierTrajectory.push_back(interpolateProjectionMultiplierTrajectory(time));
} else { // Initialize with zero
projectionMultiplierTrajectory.push_back(vector_t::Zero(numConstraints));
}
}
}
}
void IpmSolver::initializeSlackDualTrajectory(const std::vector<AnnotatedTime>& timeDiscretization, const vector_array_t& x,
const vector_array_t& u, scalar_t barrierParam, vector_array_t& slackStateIneq,
vector_array_t& dualStateIneq, vector_array_t& slackStateInputIneq,
vector_array_t& dualStateInputIneq) {
const auto& oldTimeTrajectory = slackIneqTrajectory_.timeTrajectory;
const auto& oldPostEventIndices = slackIneqTrajectory_.postEventIndices;
const auto newTimeTrajectory = toInterpolationTime(timeDiscretization);
const auto newPostEventIndices = toPostEventIndices(timeDiscretization);
// find the time period that we can interpolate the cached solution
const auto timePeriod = std::make_pair(newTimeTrajectory.front(), newTimeTrajectory.back());
const auto interpolatableTimePeriod =
findIntersectionToExtendableInterval(oldTimeTrajectory, this->getReferenceManager().getModeSchedule().eventTimes, timePeriod);
const bool interpolateTillFinalTime = numerics::almost_eq(interpolatableTimePeriod.second, timePeriod.second);
const auto cacheEventIndexBias = [&]() -> size_t {
if (!newPostEventIndices.empty()) {
const auto firstEventTime = newTimeTrajectory[newPostEventIndices[0] - 1];
return getNumberOfPrecedingEvents(oldTimeTrajectory, oldPostEventIndices, firstEventTime);
} else {
return 0;
}
}();
auto& ocpDefinition = ocpDefinitions_.front();
const size_t N = static_cast<int>(timeDiscretization.size()) - 1; // size of the input trajectory
slackStateIneq.resize(N + 1);
dualStateIneq.resize(N + 1);
slackStateInputIneq.resize(N);
dualStateInputIneq.resize(N);
int eventIdx = 0;
for (size_t i = 0; i < N; i++) {
if (timeDiscretization[i].event == AnnotatedTime::Event::PreEvent) {
const auto cachedEventIndex = cacheEventIndexBias + eventIdx;
if (cachedEventIndex < slackIneqTrajectory_.preJumps.size()) {
std::tie(slackStateIneq[i], std::ignore) = ipm::fromMultiplierCollection(slackIneqTrajectory_.preJumps[cachedEventIndex]);
std::tie(dualStateIneq[i], std::ignore) = ipm::fromMultiplierCollection(dualIneqTrajectory_.preJumps[cachedEventIndex]);
} else {
scalar_t time = timeDiscretization[i].time;
slackStateIneq[i] = ipm::initializeEventSlackVariable(ocpDefinition, timeDiscretization[i].time, x[i],
settings_.initialSlackLowerBound, settings_.initialSlackMarginRate);
dualStateIneq[i] =
ipm::initializeDualVariable(slackStateIneq[i], barrierParam, settings_.initialDualLowerBound, settings_.initialDualMarginRate);
}
slackStateInputIneq[i].resize(0);
dualStateInputIneq[i].resize(0);
++eventIdx;
} else {
const scalar_t time = getIntervalStart(timeDiscretization[i]);
if (interpolatableTimePeriod.first <= time && time <= interpolatableTimePeriod.second) {
std::tie(slackStateIneq[i], slackStateInputIneq[i]) =
ipm::fromMultiplierCollection(getIntermediateDualSolutionAtTime(slackIneqTrajectory_, time));
std::tie(dualStateIneq[i], dualStateInputIneq[i]) =
ipm::fromMultiplierCollection(getIntermediateDualSolutionAtTime(slackIneqTrajectory_, time));
} else {
std::tie(slackStateIneq[i], slackStateInputIneq[i]) = ipm::initializeIntermediateSlackVariable(
ocpDefinition, time, x[i], u[i], settings_.initialSlackLowerBound, settings_.initialSlackMarginRate);
dualStateIneq[i] =
ipm::initializeDualVariable(slackStateIneq[i], barrierParam, settings_.initialDualLowerBound, settings_.initialDualMarginRate);
dualStateInputIneq[i] = ipm::initializeDualVariable(slackStateInputIneq[i], barrierParam, settings_.initialDualLowerBound,
settings_.initialDualMarginRate);
}
}
}
// Disable the state-only inequality constraints at the initial node
slackStateIneq[0].resize(0);
dualStateIneq[0].resize(0);
if (interpolateTillFinalTime) {
std::tie(slackStateIneq[N], std::ignore) = ipm::fromMultiplierCollection(slackIneqTrajectory_.final);
std::tie(dualStateIneq[N], std::ignore) = ipm::fromMultiplierCollection(dualIneqTrajectory_.final);
} else {
slackStateIneq[N] = ipm::initializeTerminalSlackVariable(ocpDefinition, getIntervalStart(timeDiscretization[N]), x[N],
settings_.initialSlackLowerBound, settings_.initialSlackMarginRate);
dualStateIneq[N] =
ipm::initializeDualVariable(slackStateIneq[N], barrierParam, settings_.initialDualLowerBound, settings_.initialDualMarginRate);
}
}
IpmSolver::OcpSubproblemSolution IpmSolver::getOCPSolution(const vector_t& delta_x0, scalar_t barrierParam,
const vector_array_t& slackStateIneq, const vector_array_t& dualStateIneq,
const vector_array_t& slackStateInputIneq,
const vector_array_t& dualStateInputIneq) {
// Solve the QP
OcpSubproblemSolution solution;
auto& deltaXSol = solution.deltaXSol;
auto& deltaUSol = solution.deltaUSol;
hpipm_status status;
hpipmInterface_.resize(extractSizesFromProblem(dynamics_, lagrangian_, nullptr));
status = hpipmInterface_.solve(delta_x0, dynamics_, lagrangian_, nullptr, deltaXSol, deltaUSol, settings_.printSolverStatus);
if (status != hpipm_status::SUCCESS) {
throw std::runtime_error("[IpmSolver] Failed to solve QP");
}
// to determine if the solution is a descent direction for the cost: compute gradient(cost)' * [dx; du]
solution.armijoDescentMetric = armijoDescentMetric(lagrangian_, deltaXSol, deltaUSol);
// Extract value function
if (settings_.createValueFunction) {
valueFunction_ = hpipmInterface_.getRiccatiCostToGo(dynamics_[0], lagrangian_[0]);
}
// Problem horizon
const int N = static_cast<int>(deltaXSol.size()) - 1;
auto& deltaLmdSol = solution.deltaLmdSol;
auto& deltaNuSol = solution.deltaNuSol;
auto& deltaSlackStateIneq = solution.deltaSlackStateIneq;
auto& deltaDualStateIneq = solution.deltaDualStateIneq;
auto& deltaSlackStateInputIneq = solution.deltaSlackStateInputIneq;
auto& deltaDualStateInputIneq = solution.deltaDualStateInputIneq;
deltaLmdSol.resize(N + 1);
deltaNuSol.resize(N);
deltaSlackStateIneq.resize(N + 1);
deltaDualStateIneq.resize(N + 1);
deltaSlackStateInputIneq.resize(N);
deltaDualStateInputIneq.resize(N);
scalar_array_t primalStepSizes(settings_.nThreads, 1.0);
scalar_array_t dualStepSizes(settings_.nThreads, 1.0);
std::atomic_int timeIndex{0};
auto parallelTask = [&](int workerId) {
// Get worker specific resources
vector_t tmp; // 1 temporary for re-use for projection.
int i = timeIndex++;
while (i < N) {
deltaSlackStateIneq[i] = ipm::retrieveSlackDirection(stateIneqConstraints_[i], deltaXSol[i], barrierParam, slackStateIneq[i]);
deltaDualStateIneq[i] = ipm::retrieveDualDirection(barrierParam, slackStateIneq[i], dualStateIneq[i], deltaSlackStateIneq[i]);
deltaSlackStateInputIneq[i] =
ipm::retrieveSlackDirection(stateInputIneqConstraints_[i], deltaXSol[i], deltaUSol[i], barrierParam, slackStateInputIneq[i]);
deltaDualStateInputIneq[i] =
ipm::retrieveDualDirection(barrierParam, slackStateInputIneq[i], dualStateInputIneq[i], deltaSlackStateInputIneq[i]);
primalStepSizes[workerId] = std::min(
{primalStepSizes[workerId],
ipm::fractionToBoundaryStepSize(slackStateIneq[i], deltaSlackStateIneq[i], settings_.fractionToBoundaryMargin),
ipm::fractionToBoundaryStepSize(slackStateInputIneq[i], deltaSlackStateInputIneq[i], settings_.fractionToBoundaryMargin)});
dualStepSizes[workerId] = std::min(
{dualStepSizes[workerId],
ipm::fractionToBoundaryStepSize(dualStateIneq[i], deltaDualStateIneq[i], settings_.fractionToBoundaryMargin),
ipm::fractionToBoundaryStepSize(dualStateInputIneq[i], deltaDualStateInputIneq[i], settings_.fractionToBoundaryMargin)});
// Extract Newton directions of the costate
if (settings_.computeLagrangeMultipliers) {
deltaLmdSol[i + 1] = valueFunction_[i + 1].dfdx;
deltaLmdSol[i + 1].noalias() += valueFunction_[i + 1].dfdxx * deltaXSol[i + 1];
}
if (constraintsProjection_[i].f.size() > 0) {
// Extract Newton directions of the Lagrange multiplier associated with the state-input equality constraints
if (settings_.computeLagrangeMultipliers) {
deltaNuSol[i] = projectionMultiplierCoefficients_[i].f;
deltaNuSol[i].noalias() += projectionMultiplierCoefficients_[i].dfdx * deltaXSol[i];
deltaNuSol[i].noalias() += projectionMultiplierCoefficients_[i].dfdu * deltaUSol[i];
deltaNuSol[i].noalias() += projectionMultiplierCoefficients_[i].dfdcostate * deltaLmdSol[i + 1];
}
// Re-map the projected input back to the original space.
tmp.noalias() = constraintsProjection_[i].dfdu * deltaUSol[i];
deltaUSol[i] = tmp + constraintsProjection_[i].f;
deltaUSol[i].noalias() += constraintsProjection_[i].dfdx * deltaXSol[i];
}
i = timeIndex++;
}
if (i == N) { // Only one worker will execute this
deltaSlackStateIneq[i] = ipm::retrieveSlackDirection(stateIneqConstraints_[i], deltaXSol[i], barrierParam, slackStateIneq[i]);
deltaDualStateIneq[i] = ipm::retrieveDualDirection(barrierParam, slackStateIneq[i], dualStateIneq[i], deltaSlackStateIneq[i]);
primalStepSizes[workerId] =
std::min(primalStepSizes[workerId],
ipm::fractionToBoundaryStepSize(slackStateIneq[i], deltaSlackStateIneq[i], settings_.fractionToBoundaryMargin));
dualStepSizes[workerId] = std::min(dualStepSizes[workerId], ipm::fractionToBoundaryStepSize(dualStateIneq[i], deltaDualStateIneq[i],
settings_.fractionToBoundaryMargin));
// Extract Newton directions of the costate
if (settings_.computeLagrangeMultipliers) {
deltaLmdSol[0] = valueFunction_[0].dfdx;
deltaLmdSol[0].noalias() += valueFunction_[i].dfdxx * deltaXSol[0];
}
}
};
runParallel(std::move(parallelTask));
solution.maxPrimalStepSize = *std::min_element(primalStepSizes.begin(), primalStepSizes.end());
solution.maxDualStepSize = *std::min_element(dualStepSizes.begin(), dualStepSizes.end());
return solution;
}
void IpmSolver::extractValueFunction(const std::vector<AnnotatedTime>& time, const vector_array_t& x, const vector_array_t& lmd,
const vector_array_t& deltaXSol) {
if (settings_.createValueFunction) {
// Correct for linearization state. Naive value function of hpipm is already extracted and stored in valueFunction_ in getOCPSolution().
for (int i = 0; i < time.size(); ++i) {
valueFunction_[i].dfdx.noalias() -= valueFunction_[i].dfdxx * x[i];
if (settings_.computeLagrangeMultipliers) {
valueFunction_[i].dfdx.noalias() += lmd[i];
}
}
}
}
PrimalSolution IpmSolver::toPrimalSolution(const std::vector<AnnotatedTime>& time, vector_array_t&& x, vector_array_t&& u) {
if (settings_.useFeedbackPolicy) {
ModeSchedule modeSchedule = this->getReferenceManager().getModeSchedule();
matrix_array_t KMatrices = hpipmInterface_.getRiccatiFeedback(dynamics_[0], lagrangian_[0]);
multiple_shooting::remapProjectedGain(constraintsProjection_, KMatrices);
return multiple_shooting::toPrimalSolution(time, std::move(modeSchedule), std::move(x), std::move(u), std::move(KMatrices));
} else {
ModeSchedule modeSchedule = this->getReferenceManager().getModeSchedule();
return multiple_shooting::toPrimalSolution(time, std::move(modeSchedule), std::move(x), std::move(u));
}
}
PerformanceIndex IpmSolver::setupQuadraticSubproblem(const std::vector<AnnotatedTime>& time, const vector_t& initState,
const vector_array_t& x, const vector_array_t& u, const vector_array_t& lmd,
const vector_array_t& nu, scalar_t barrierParam, const vector_array_t& slackStateIneq,
const vector_array_t& slackStateInputIneq, const vector_array_t& dualStateIneq,
const vector_array_t& dualStateInputIneq, std::vector<Metrics>& metrics) {
// Problem horizon
const int N = static_cast<int>(time.size()) - 1;
std::vector<PerformanceIndex> performance(settings_.nThreads, PerformanceIndex());
lagrangian_.resize(N + 1);
dynamics_.resize(N);
stateInputEqConstraints_.resize(N + 1);
stateIneqConstraints_.resize(N + 1);
stateInputIneqConstraints_.resize(N + 1);
constraintsProjection_.resize(N);
projectionMultiplierCoefficients_.resize(N);
constraintsSize_.resize(N + 1);
metrics.resize(N + 1);
std::atomic_int timeIndex{0};
auto parallelTask = [&](int workerId) {
// Get worker specific resources
OptimalControlProblem& ocpDefinition = ocpDefinitions_[workerId];
int i = timeIndex++;
while (i < N) {
if (time[i].event == AnnotatedTime::Event::PreEvent) {
// Event node
auto result = multiple_shooting::setupEventNode(ocpDefinition, time[i].time, x[i], x[i + 1]);
metrics[i] = multiple_shooting::computeMetrics(result);
performance[workerId] += ipm::computePerformanceIndex(result, barrierParam, slackStateIneq[i]);
dynamics_[i] = std::move(result.dynamics);
stateInputEqConstraints_[i].resize(0, x[i].size());
stateIneqConstraints_[i] = std::move(result.ineqConstraints);
stateInputIneqConstraints_[i].resize(0, x[i].size());
constraintsProjection_[i].resize(0, x[i].size());
projectionMultiplierCoefficients_[i] = multiple_shooting::ProjectionMultiplierCoefficients();
constraintsSize_[i] = std::move(result.constraintsSize);
if (settings_.computeLagrangeMultipliers) {
lagrangian_[i] = multiple_shooting::evaluateLagrangianEventNode(lmd[i], lmd[i + 1], std::move(result.cost), dynamics_[i]);
} else {
lagrangian_[i] = std::move(result.cost);
}
ipm::condenseIneqConstraints(barrierParam, slackStateIneq[i], dualStateIneq[i], stateIneqConstraints_[i], lagrangian_[i]);
performance[workerId].dualFeasibilitiesSSE += multiple_shooting::evaluateDualFeasibilities(lagrangian_[i]);
performance[workerId].dualFeasibilitiesSSE +=
ipm::evaluateComplementarySlackness(barrierParam, slackStateIneq[i], dualStateIneq[i]);
} else {
// Normal, intermediate node
const scalar_t ti = getIntervalStart(time[i]);
const scalar_t dt = getIntervalDuration(time[i], time[i + 1]);
auto result = multiple_shooting::setupIntermediateNode(ocpDefinition, sensitivityDiscretizer_, ti, dt, x[i], x[i + 1], u[i]);
// Disable the state-only inequality constraints at the initial node
if (i == 0) {
result.stateIneqConstraints.setZero(0, x[i].size());
std::fill(result.constraintsSize.stateIneq.begin(), result.constraintsSize.stateIneq.end(), 0);
}
metrics[i] = multiple_shooting::computeMetrics(result);
performance[workerId] += ipm::computePerformanceIndex(result, dt, barrierParam, slackStateIneq[i], slackStateInputIneq[i]);
multiple_shooting::projectTranscription(result, settings_.computeLagrangeMultipliers);
dynamics_[i] = std::move(result.dynamics);
stateInputEqConstraints_[i] = std::move(result.stateInputEqConstraints);
stateIneqConstraints_[i] = std::move(result.stateIneqConstraints);
stateInputIneqConstraints_[i] = std::move(result.stateInputIneqConstraints);
constraintsProjection_[i] = std::move(result.constraintsProjection);
projectionMultiplierCoefficients_[i] = std::move(result.projectionMultiplierCoefficients);
constraintsSize_[i] = std::move(result.constraintsSize);
if (settings_.computeLagrangeMultipliers) {
lagrangian_[i] = multiple_shooting::evaluateLagrangianIntermediateNode(lmd[i], lmd[i + 1], nu[i], std::move(result.cost),
dynamics_[i], stateInputEqConstraints_[i]);
} else {
lagrangian_[i] = std::move(result.cost);
}
ipm::condenseIneqConstraints(barrierParam, slackStateIneq[i], dualStateIneq[i], stateIneqConstraints_[i], lagrangian_[i]);
ipm::condenseIneqConstraints(barrierParam, slackStateInputIneq[i], dualStateInputIneq[i], stateInputIneqConstraints_[i],
lagrangian_[i]);
performance[workerId].dualFeasibilitiesSSE += multiple_shooting::evaluateDualFeasibilities(lagrangian_[i]);
performance[workerId].dualFeasibilitiesSSE +=
ipm::evaluateComplementarySlackness(barrierParam, slackStateIneq[i], dualStateIneq[i]);
performance[workerId].dualFeasibilitiesSSE +=
ipm::evaluateComplementarySlackness(barrierParam, slackStateInputIneq[i], dualStateInputIneq[i]);
}
i = timeIndex++;
}
if (i == N) { // Only one worker will execute this
const scalar_t tN = getIntervalStart(time[N]);
auto result = multiple_shooting::setupTerminalNode(ocpDefinition, tN, x[N]);
metrics[i] = multiple_shooting::computeMetrics(result);
performance[workerId] += ipm::computePerformanceIndex(result, barrierParam, slackStateIneq[N]);
stateInputEqConstraints_[i].resize(0, x[i].size());
stateIneqConstraints_[i] = std::move(result.ineqConstraints);
constraintsSize_[i] = std::move(result.constraintsSize);
if (settings_.computeLagrangeMultipliers) {
lagrangian_[i] = multiple_shooting::evaluateLagrangianTerminalNode(lmd[i], std::move(result.cost));
} else {
lagrangian_[i] = std::move(result.cost);
}
ipm::condenseIneqConstraints(barrierParam, slackStateIneq[N], dualStateIneq[N], stateIneqConstraints_[N], lagrangian_[N]);
performance[workerId].dualFeasibilitiesSSE += multiple_shooting::evaluateDualFeasibilities(lagrangian_[N]);
performance[workerId].dualFeasibilitiesSSE += ipm::evaluateComplementarySlackness(barrierParam, slackStateIneq[N], dualStateIneq[N]);
}
};
runParallel(std::move(parallelTask));
// Account for initial state in performance
const vector_t initDynamicsViolation = initState - x.front();
metrics.front().dynamicsViolation += initDynamicsViolation;
performance.front().dynamicsViolationSSE += initDynamicsViolation.squaredNorm();
// Sum performance of the threads
PerformanceIndex totalPerformance = std::accumulate(std::next(performance.begin()), performance.end(), performance.front());
totalPerformance.merit = totalPerformance.cost + totalPerformance.equalityLagrangian + totalPerformance.inequalityLagrangian;
return totalPerformance;
}
PerformanceIndex IpmSolver::computePerformance(const std::vector<AnnotatedTime>& time, const vector_t& initState, const vector_array_t& x,
const vector_array_t& u, scalar_t barrierParam, const vector_array_t& slackStateIneq,
const vector_array_t& slackStateInputIneq, std::vector<Metrics>& metrics) {
// Problem horizon
const int N = static_cast<int>(time.size()) - 1;
metrics.resize(N + 1);
std::vector<PerformanceIndex> performance(settings_.nThreads, PerformanceIndex());
std::atomic_int timeIndex{0};
auto parallelTask = [&](int workerId) {
// Get worker specific resources
OptimalControlProblem& ocpDefinition = ocpDefinitions_[workerId];
int i = timeIndex++;
while (i < N) {
if (time[i].event == AnnotatedTime::Event::PreEvent) {
// Event node
metrics[i] = multiple_shooting::computeEventMetrics(ocpDefinition, time[i].time, x[i], x[i + 1]);
performance[workerId] += ipm::toPerformanceIndex(metrics[i], barrierParam, slackStateIneq[i]);
} else {
// Normal, intermediate node
const scalar_t ti = getIntervalStart(time[i]);
const scalar_t dt = getIntervalDuration(time[i], time[i + 1]);
const bool enableStateInequalityConstraints = (i > 0);
metrics[i] = multiple_shooting::computeIntermediateMetrics(ocpDefinition, discretizer_, ti, dt, x[i], x[i + 1], u[i]);
// Disable the state-only inequality constraints at the initial node
if (i == 0) {
metrics[i].stateIneqConstraint.clear();
}
performance[workerId] += ipm::toPerformanceIndex(metrics[i], dt, barrierParam, slackStateIneq[i], slackStateInputIneq[i]);
}
i = timeIndex++;
}
if (i == N) { // Only one worker will execute this
const scalar_t tN = getIntervalStart(time[N]);
metrics[N] = multiple_shooting::computeTerminalMetrics(ocpDefinition, tN, x[N]);
performance[workerId] += ipm::toPerformanceIndex(metrics[N], barrierParam, slackStateIneq[N]);
}
};
runParallel(std::move(parallelTask));
// Account for initial state in performance
const vector_t initDynamicsViolation = initState - x.front();
metrics.front().dynamicsViolation += initDynamicsViolation;
performance.front().dynamicsViolationSSE += initDynamicsViolation.squaredNorm();
// Sum performance of the threads
PerformanceIndex totalPerformance = std::accumulate(std::next(performance.begin()), performance.end(), performance.front());
totalPerformance.merit = totalPerformance.cost + totalPerformance.equalityLagrangian + totalPerformance.inequalityLagrangian;
return totalPerformance;
}
ipm::StepInfo IpmSolver::takePrimalStep(const PerformanceIndex& baseline, const std::vector<AnnotatedTime>& timeDiscretization,
const vector_t& initState, const OcpSubproblemSolution& subproblemSolution, vector_array_t& x,
vector_array_t& u, scalar_t barrierParam, vector_array_t& slackStateIneq,
vector_array_t& slackStateInputIneq, std::vector<Metrics>& metrics) {
using StepType = FilterLinesearch::StepType;
/*
* Filter linesearch based on:
* "On the implementation of an interior-point filter line-search algorithm for large-scale nonlinear programming"
* https://link.springer.com/article/10.1007/s10107-004-0559-y
*/
if (settings_.printLinesearch) {
std::cerr << std::setprecision(9) << std::fixed;
std::cerr << "\n=== Linesearch ===\n";
std::cerr << "Baseline:\n" << baseline << "\n";
}
// Baseline costs
const scalar_t baselineConstraintViolation = FilterLinesearch::totalConstraintViolation(baseline);
// Update norm
const auto& dx = subproblemSolution.deltaXSol;
const auto& du = subproblemSolution.deltaUSol;
const auto& deltaSlackStateIneq = subproblemSolution.deltaSlackStateIneq;
const auto& deltaSlackStateInputIneq = subproblemSolution.deltaSlackStateInputIneq;
const auto deltaUnorm = multiple_shooting::trajectoryNorm(du);
const auto deltaXnorm = multiple_shooting::trajectoryNorm(dx);
scalar_t alpha = subproblemSolution.maxPrimalStepSize;
vector_array_t xNew(x.size());
vector_array_t uNew(u.size());
vector_array_t slackStateIneqNew(slackStateIneq.size());
vector_array_t slackStateInputIneqNew(slackStateInputIneq.size());
std::vector<Metrics> metricsNew(metrics.size());
do {
// Compute step
multiple_shooting::incrementTrajectory(u, du, alpha, uNew);
multiple_shooting::incrementTrajectory(x, dx, alpha, xNew);
multiple_shooting::incrementTrajectory(slackStateIneq, deltaSlackStateIneq, alpha, slackStateIneqNew);
multiple_shooting::incrementTrajectory(slackStateInputIneq, deltaSlackStateInputIneq, alpha, slackStateInputIneqNew);
// Compute cost and constraints
const PerformanceIndex performanceNew =
computePerformance(timeDiscretization, initState, xNew, uNew, barrierParam, slackStateIneqNew, slackStateInputIneqNew, metricsNew);
// Step acceptance and record step type
bool stepAccepted;
StepType stepType;
std::tie(stepAccepted, stepType) =
filterLinesearch_.acceptStep(baseline, performanceNew, alpha * subproblemSolution.armijoDescentMetric);
if (settings_.printLinesearch) {
std::cerr << "Step size: " << alpha << ", Step Type: " << toString(stepType)
<< (stepAccepted ? std::string{" (Accepted)"} : std::string{" (Rejected)"}) << "\n";
std::cerr << "|dx| = " << alpha * deltaXnorm << "\t|du| = " << alpha * deltaUnorm << "\n";
std::cerr << performanceNew << "\n";
}
if (stepAccepted) { // Return if step accepted
x = std::move(xNew);
u = std::move(uNew);
slackStateIneq = std::move(slackStateIneqNew);
slackStateInputIneq = std::move(slackStateInputIneqNew);
metrics = std::move(metricsNew);
// Prepare step info
ipm::StepInfo stepInfo;
stepInfo.primalStepSize = alpha;
stepInfo.stepType = stepType;
stepInfo.dx_norm = alpha * deltaXnorm;
stepInfo.du_norm = alpha * deltaUnorm;
stepInfo.performanceAfterStep = performanceNew;
stepInfo.totalConstraintViolationAfterStep = FilterLinesearch::totalConstraintViolation(performanceNew);
return stepInfo;
} else { // Try smaller step
alpha *= settings_.alpha_decay;
// Detect too small step size during back-tracking to escape early. Prevents going all the way to alpha_min
if (alpha * deltaXnorm < settings_.deltaTol && alpha * deltaUnorm < settings_.deltaTol) {
if (settings_.printLinesearch) {
std::cerr << "Exiting linesearch early due to too small primal steps |dx|: " << alpha * deltaXnorm
<< ", and or |du|: " << alpha * deltaUnorm << " are below deltaTol: " << settings_.deltaTol << "\n";
}
break;
}
}
} while (alpha >= settings_.alpha_min);
// Alpha_min reached -> Don't take a step
ipm::StepInfo stepInfo;
stepInfo.primalStepSize = 0.0;
stepInfo.stepType = StepType::ZERO;
stepInfo.dx_norm = 0.0;
stepInfo.du_norm = 0.0;
stepInfo.performanceAfterStep = baseline;
stepInfo.totalConstraintViolationAfterStep = FilterLinesearch::totalConstraintViolation(baseline);
if (settings_.printLinesearch) {
std::cerr << "[Linesearch terminated] Primal Step size: " << stepInfo.primalStepSize << ", Step Type: " << toString(stepInfo.stepType)
<< "\n";
}
return stepInfo;
}
void IpmSolver::takeDualStep(const OcpSubproblemSolution& subproblemSolution, const ipm::StepInfo& stepInfo, vector_array_t& lmd,
vector_array_t& nu, vector_array_t& dualStateIneq, vector_array_t& dualStateInputIneq) const {
if (settings_.computeLagrangeMultipliers) {
multiple_shooting::incrementTrajectory(lmd, subproblemSolution.deltaLmdSol, stepInfo.primalStepSize, lmd);
multiple_shooting::incrementTrajectory(nu, subproblemSolution.deltaNuSol, stepInfo.primalStepSize, nu);
}
const scalar_t dualStepSize = settings_.usePrimalStepSizeForDual ? std::min(stepInfo.primalStepSize, subproblemSolution.maxDualStepSize)
: subproblemSolution.maxDualStepSize;
multiple_shooting::incrementTrajectory(dualStateIneq, subproblemSolution.deltaDualStateIneq, dualStepSize, dualStateIneq);
multiple_shooting::incrementTrajectory(dualStateInputIneq, subproblemSolution.deltaDualStateInputIneq, dualStepSize, dualStateInputIneq);
}
scalar_t IpmSolver::updateBarrierParameter(scalar_t currentBarrierParameter, const PerformanceIndex& baseline,
const ipm::StepInfo& stepInfo) const {
if (currentBarrierParameter <= settings_.targetBarrierParameter) {
return currentBarrierParameter;
} else if (std::abs(stepInfo.performanceAfterStep.merit - baseline.merit) < settings_.barrierReductionCostTol &&
FilterLinesearch::totalConstraintViolation(stepInfo.performanceAfterStep) < settings_.barrierReductionConstraintTol) {
return std::min((currentBarrierParameter * settings_.barrierLinearDecreaseFactor),
std::pow(currentBarrierParameter, settings_.barrierSuperlinearDecreasePower));
} else {
return currentBarrierParameter;
}
}
ipm::Convergence IpmSolver::checkConvergence(int iteration, scalar_t barrierParam, const PerformanceIndex& baseline,
const ipm::StepInfo& stepInfo) const {
using Convergence = ipm::Convergence;
if ((iteration + 1) >= settings_.ipmIteration) {
// Converged because the next iteration would exceed the specified number of iterations
return Convergence::ITERATIONS;
} else if (stepInfo.primalStepSize < settings_.alpha_min) {
// Converged because step size is below the specified minimum
return Convergence::STEPSIZE;
} else if (std::abs(stepInfo.performanceAfterStep.merit - baseline.merit) < settings_.costTol &&
FilterLinesearch::totalConstraintViolation(stepInfo.performanceAfterStep) < settings_.g_min) {
// Converged because the change in merit is below the specified tolerance while the constraint violation is below the minimum
return Convergence::METRICS;
} else if (stepInfo.dx_norm < settings_.deltaTol && stepInfo.du_norm < settings_.deltaTol &&
barrierParam <= settings_.targetBarrierParameter) {
// Converged because the change in primal variables is below the specified tolerance
return Convergence::PRIMAL;
} else {
// None of the above convergence criteria were met -> not converged.
return Convergence::FALSE;
}
}
} // namespace ocs2
| [
"ihtf4ta7f@gmail.com"
] | ihtf4ta7f@gmail.com |
80196820e371658cd9c51c1ffe58ef832e57c070 | f3478562ae598ed6d0e8d4c124010c5be38afe08 | /src/qt/notificator.h | da49a7c624440e329606016c89dffc3fca4f2f14 | [
"MIT",
"FSFAP"
] | permissive | cryptocoinico/cloudnode-v2 | 782f5f6379bcd6e79359b6ef73dd272f7712b9f3 | 75c21d6602bc96b95ba715825b7648751736f77b | refs/heads/master | 2020-06-15T16:40:01.531396 | 2019-06-13T13:59:56 | 2019-06-13T13:59:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,820 | h | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_NOTIFICATOR_H
#define BITCOIN_QT_NOTIFICATOR_H
#if defined(HAVE_CONFIG_H)
#include "config/cloudenode-config.h"
#endif
#include <QIcon>
#include <QObject>
QT_BEGIN_NAMESPACE
class QSystemTrayIcon;
#ifdef USE_DBUS
class QDBusInterface;
#endif
QT_END_NAMESPACE
/** Cross-platform desktop notification client. */
class Notificator : public QObject
{
Q_OBJECT
public:
/** Create a new notificator.
@note Ownership of trayIcon is not transferred to this object.
*/
Notificator(const QString& programName, QSystemTrayIcon* trayIcon, QWidget* parent);
~Notificator();
// Message class
enum Class {
Information, /**< Informational message */
Warning, /**< Notify user of potential problem */
Critical /**< An error occurred */
};
public slots:
/** Show notification message.
@param[in] cls general message class
@param[in] title title shown with message
@param[in] text message content
@param[in] icon optional icon to show with message
@param[in] millisTimeout notification timeout in milliseconds (defaults to 10 seconds)
@note Platform implementations are free to ignore any of the provided fields except for \a text.
*/
void notify(Class cls, const QString& title, const QString& text, const QIcon& icon = QIcon(), int millisTimeout = 10000);
private:
QWidget* parent;
enum Mode {
None, /**< Ignore informational notifications, and show a modal pop-up dialog for Critical notifications. */
Freedesktop, /**< Use DBus org.freedesktop.Notifications */
QSystemTray, /**< Use QSystemTray::showMessage */
Growl12, /**< Use the Growl 1.2 notification system (Mac only) */
Growl13, /**< Use the Growl 1.3 notification system (Mac only) */
UserNotificationCenter /**< Use the 10.8+ User Notification Center (Mac only) */
};
QString programName;
Mode mode;
QSystemTrayIcon* trayIcon;
#ifdef USE_DBUS
QDBusInterface* interface;
void notifyDBus(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout);
#endif
void notifySystray(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout);
#ifdef Q_OS_MAC
void notifyGrowl(Class cls, const QString& title, const QString& text, const QIcon& icon);
void notifyMacUserNotificationCenter(Class cls, const QString& title, const QString& text, const QIcon& icon);
#endif
};
#endif // BITCOIN_QT_NOTIFICATOR_H
| [
"udaydeep.yadav@gmail.com"
] | udaydeep.yadav@gmail.com |
c1dff27d5a2d78d82574d83c07d2f8daaaad3b3c | d4d06745a1ed357cad9ef1dc03462bfbe65b1d63 | /day00/ex01/src/main.cpp | 9704bcb907fc6a7deff5be927a7999fb118e4a7f | [] | no_license | potatokuka/Cpp_Piscene | 5d7c7b5af0691f347e5b2dde9027ea9fdacbcd00 | f203d026ad0ab12d5711ddd18686e4335703a762 | refs/heads/master | 2022-12-16T13:44:51.960228 | 2020-09-18T10:09:10 | 2020-09-18T10:09:10 | 282,245,546 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,326 | cpp | /* ************************************************************************** */
/* */
/* :::::::: */
/* main.cpp :+: :+: */
/* +:+ */
/* By: greed <greed@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2020/07/25 09:25:15 by greed #+# #+# */
/* Updated: 2020/07/27 16:38:58 by greed ######## odam.nl */
/* */
/* ************************************************************************** */
#include <iostream>
#include <string>
#include <sstream>
#include "Database.class.hpp"
int main(void){
Database db;
std::cout << "Welcome to the Hell >>" << std::endl;
std::string command = "";
while (command.compare("EXIT") != 0)
{
std::cout << "\033[1;31mRed Pages> \033[0m";
std::getline(std::cin, command);
if (command.compare("ADD") == 0)
{
// check if phonebook is full
if (db.Count() >= 8)
{
std::cout << "Error: Sorry this level of Hell can not hold more than 8 souls"
<< std::endl;
continue;
}
// if not full start filling new Contact
Contact c;
c.Prompt();
db.AddContact(c);
}
else if (command.compare("SEARCH") == 0)
{
std::cout << "Souls: " << db.Count() << std::endl;
db.List();
if (db.Count() == 0)
continue;
std::string input;
int index = -1;
while (true)
{
std::cout << "Enter an index to view: ";
std::getline(std::cin, input);
if (!std::cin.good())
exit(0);
if (input.compare("EXIT") == 0)
exit(0);
std::stringstream convert(input);
if (convert >> index && index >= 0 && index < db.Count())
break;
std::cout << "Error: invalid index. Must be between 0 -> "
<< (db.Count() - 1) << "." << std::endl;
}
std::cout << std::endl;
db.GetContact(index).Display();
}
else
std::cout << "Valid command options: [ADD] [SEARCH] [EXIT]"
<< std::endl;
}
return (0);
}
| [
"griffin.reed3@gmail.com"
] | griffin.reed3@gmail.com |
5f79e62a0bed784d4d578938f5cb3d12bce31e4b | be59c390795966476e777e8b75e27b5999640ee0 | /src/device/device.hpp | 02dd2db63b73f8b2ca0a36ebf347d4555d8988ec | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | BRTChain/BRT-Chain | cdefbb1ab54c186b1f66e01c4bc5cf97b830f45a | e4bfc027bc82eb79940331f9d334ab31708d4202 | refs/heads/master | 2022-12-21T15:57:45.359810 | 2020-09-26T08:02:12 | 2020-09-26T08:02:12 | 298,766,400 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,514 | hpp | // Copyright (c) 2017-2020, The BRT Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#include "crypto/crypto.h"
#include "crypto/chacha.h"
#include "ringct/rctTypes.h"
#include "cryptonote_config.h"
#ifndef USE_DEVICE_LEDGER
#define USE_DEVICE_LEDGER 1
#endif
#if !defined(HAVE_HIDAPI)
#undef USE_DEVICE_LEDGER
#define USE_DEVICE_LEDGER 0
#endif
#if USE_DEVICE_LEDGER
#define WITH_DEVICE_LEDGER
#endif
// forward declaration needed because this header is included by headers in libcryptonote_basic which depends on libdevice
namespace cryptonote
{
struct account_public_address;
struct account_keys;
struct subaddress_index;
struct tx_destination_entry;
struct keypair;
class transaction_prefix;
}
namespace hw {
namespace {
//device funcion not supported
#define dfns() \
throw std::runtime_error(std::string("device function not supported: ")+ std::string(__FUNCTION__) + \
std::string(" (device.hpp line ")+std::to_string(__LINE__)+std::string(").")); \
return false;
}
class device_progress {
public:
virtual double progress() const { return 0; }
virtual bool indeterminate() const { return false; }
};
class i_device_callback {
public:
virtual void on_button_request(uint64_t code=0) {}
virtual void on_button_pressed() {}
virtual boost::optional<epee::wipeable_string> on_pin_request() { return boost::none; }
virtual boost::optional<epee::wipeable_string> on_passphrase_request(bool & on_device) { on_device = true; return boost::none; }
virtual void on_progress(const device_progress& event) {}
virtual ~i_device_callback() = default;
};
class device {
protected:
std::string name;
public:
device(): mode(NONE) {}
device(const device &hwdev) {}
virtual ~device() {}
explicit virtual operator bool() const = 0;
enum device_mode {
NONE,
TRANSACTION_CREATE_REAL,
TRANSACTION_CREATE_FAKE,
TRANSACTION_PARSE
};
enum device_type
{
SOFTWARE = 0,
LEDGER = 1,
TREZOR = 2
};
enum device_protocol_t {
PROTOCOL_DEFAULT,
PROTOCOL_PROXY, // Originally defined by Ledger
PROTOCOL_COLD, // Originally defined by Trezor
};
/* ======================================================================= */
/* SETUP/TEARDOWN */
/* ======================================================================= */
virtual bool set_name(const std::string &name) = 0;
virtual const std::string get_name() const = 0;
virtual bool init(void) = 0;
virtual bool release() = 0;
virtual bool connect(void) = 0;
virtual bool disconnect(void) = 0;
virtual bool set_mode(device_mode mode) { this->mode = mode; return true; }
virtual device_mode get_mode() const { return mode; }
virtual device_type get_type() const = 0;
virtual device_protocol_t device_protocol() const { return PROTOCOL_DEFAULT; };
virtual void set_callback(i_device_callback * callback) {};
virtual void set_derivation_path(const std::string &derivation_path) {};
virtual void set_pin(const epee::wipeable_string & pin) {}
virtual void set_passphrase(const epee::wipeable_string & passphrase) {}
/* ======================================================================= */
/* LOCKER */
/* ======================================================================= */
virtual void lock(void) = 0;
virtual void unlock(void) = 0;
virtual bool try_lock(void) = 0;
/* ======================================================================= */
/* WALLET & ADDRESS */
/* ======================================================================= */
virtual bool get_public_address(cryptonote::account_public_address &pubkey) = 0;
virtual bool get_secret_keys(crypto::secret_key &viewkey , crypto::secret_key &spendkey) = 0;
virtual bool generate_chacha_key(const cryptonote::account_keys &keys, crypto::chacha_key &key, uint64_t kdf_rounds) = 0;
/* ======================================================================= */
/* SUB ADDRESS */
/* ======================================================================= */
virtual bool derive_subaddress_public_key(const crypto::public_key &pub, const crypto::key_derivation &derivation, const std::size_t output_index, crypto::public_key &derived_pub) = 0;
virtual crypto::public_key get_subaddress_spend_public_key(const cryptonote::account_keys& keys, const cryptonote::subaddress_index& index) = 0;
virtual std::vector<crypto::public_key> get_subaddress_spend_public_keys(const cryptonote::account_keys &keys, uint32_t account, uint32_t begin, uint32_t end) = 0;
virtual cryptonote::account_public_address get_subaddress(const cryptonote::account_keys& keys, const cryptonote::subaddress_index &index) = 0;
virtual crypto::secret_key get_subaddress_secret_key(const crypto::secret_key &sec, const cryptonote::subaddress_index &index) = 0;
/* ======================================================================= */
/* DERIVATION & KEY */
/* ======================================================================= */
virtual bool verify_keys(const crypto::secret_key &secret_key, const crypto::public_key &public_key) = 0;
virtual bool scalarmultKey(rct::key & aP, const rct::key &P, const rct::key &a) = 0;
virtual bool scalarmultBase(rct::key &aG, const rct::key &a) = 0;
virtual bool sc_secret_add( crypto::secret_key &r, const crypto::secret_key &a, const crypto::secret_key &b) = 0;
virtual crypto::secret_key generate_keys(crypto::public_key &pub, crypto::secret_key &sec, const crypto::secret_key& recovery_key = crypto::secret_key(), bool recover = false) = 0;
virtual bool generate_key_derivation(const crypto::public_key &pub, const crypto::secret_key &sec, crypto::key_derivation &derivation) = 0;
virtual bool conceal_derivation(crypto::key_derivation &derivation, const crypto::public_key &tx_pub_key, const std::vector<crypto::public_key> &additional_tx_pub_keys, const crypto::key_derivation &main_derivation, const std::vector<crypto::key_derivation> &additional_derivations) = 0;
virtual bool derivation_to_scalar(const crypto::key_derivation &derivation, const size_t output_index, crypto::ec_scalar &res) = 0;
virtual bool derive_secret_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::secret_key &sec, crypto::secret_key &derived_sec) = 0;
virtual bool derive_public_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::public_key &pub, crypto::public_key &derived_pub) = 0;
virtual bool secret_key_to_public_key(const crypto::secret_key &sec, crypto::public_key &pub) = 0;
virtual bool generate_key_image(const crypto::public_key &pub, const crypto::secret_key &sec, crypto::key_image &image) = 0;
// alternative prototypes available in libringct
rct::key scalarmultKey(const rct::key &P, const rct::key &a)
{
rct::key aP;
scalarmultKey(aP, P, a);
return aP;
}
rct::key scalarmultBase(const rct::key &a)
{
rct::key aG;
scalarmultBase(aG, a);
return aG;
}
/* ======================================================================= */
/* TRANSACTION */
/* ======================================================================= */
virtual void generate_tx_proof(const crypto::hash &prefix_hash,
const crypto::public_key &R, const crypto::public_key &A, const boost::optional<crypto::public_key> &B, const crypto::public_key &D, const crypto::secret_key &r,
crypto::signature &sig) = 0;
virtual bool open_tx(crypto::secret_key &tx_key) = 0;
virtual void get_transaction_prefix_hash(const cryptonote::transaction_prefix& tx, crypto::hash& h) = 0;
virtual bool encrypt_payment_id(crypto::hash8 &payment_id, const crypto::public_key &public_key, const crypto::secret_key &secret_key) = 0;
bool decrypt_payment_id(crypto::hash8 &payment_id, const crypto::public_key &public_key, const crypto::secret_key &secret_key)
{
// Encryption and decryption are the same operation (xor with a key)
return encrypt_payment_id(payment_id, public_key, secret_key);
}
virtual rct::key genCommitmentMask(const rct::key &amount_key) = 0;
virtual bool ecdhEncode(rct::ecdhTuple & unmasked, const rct::key & sharedSec, bool short_amount) = 0;
virtual bool ecdhDecode(rct::ecdhTuple & masked, const rct::key & sharedSec, bool short_amount) = 0;
virtual bool generate_output_ephemeral_keys(const size_t tx_version, const cryptonote::account_keys &sender_account_keys, const crypto::public_key &txkey_pub, const crypto::secret_key &tx_key,
const cryptonote::tx_destination_entry &dst_entr, const boost::optional<cryptonote::account_public_address> &change_addr, const size_t output_index,
const bool &need_additional_txkeys, const std::vector<crypto::secret_key> &additional_tx_keys,
std::vector<crypto::public_key> &additional_tx_public_keys,
std::vector<rct::key> &amount_keys,
crypto::public_key &out_eph_public_key) = 0;
virtual bool mlsag_prehash(const std::string &blob, size_t inputs_size, size_t outputs_size, const rct::keyV &hashes, const rct::ctkeyV &outPk, rct::key &prehash) = 0;
virtual bool mlsag_prepare(const rct::key &H, const rct::key &xx, rct::key &a, rct::key &aG, rct::key &aHP, rct::key &rvII) = 0;
virtual bool mlsag_prepare(rct::key &a, rct::key &aG) = 0;
virtual bool mlsag_hash(const rct::keyV &long_message, rct::key &c) = 0;
virtual bool mlsag_sign(const rct::key &c, const rct::keyV &xx, const rct::keyV &alpha, const size_t rows, const size_t dsRows, rct::keyV &ss) = 0;
virtual bool clsag_prepare(const rct::key &p, const rct::key &z, rct::key &I, rct::key &D, const rct::key &H, rct::key &a, rct::key &aG, rct::key &aH) = 0;
virtual bool clsag_hash(const rct::keyV &data, rct::key &hash) = 0;
virtual bool clsag_sign(const rct::key &c, const rct::key &a, const rct::key &p, const rct::key &z, const rct::key &mu_P, const rct::key &mu_C, rct::key &s) = 0;
virtual bool close_tx(void) = 0;
virtual bool has_ki_cold_sync(void) const { return false; }
virtual bool has_tx_cold_sign(void) const { return false; }
virtual bool has_ki_live_refresh(void) const { return true; }
virtual bool compute_key_image(const cryptonote::account_keys& ack, const crypto::public_key& out_key, const crypto::key_derivation& recv_derivation, size_t real_output_index, const cryptonote::subaddress_index& received_index, cryptonote::keypair& in_ephemeral, crypto::key_image& ki) { return false; }
virtual void computing_key_images(bool started) {};
virtual void set_network_type(cryptonote::network_type network_type) { }
virtual void display_address(const cryptonote::subaddress_index& index, const boost::optional<crypto::hash8> &payment_id) {}
protected:
device_mode mode;
} ;
struct reset_mode {
device& hwref;
reset_mode(hw::device& dev) : hwref(dev) { }
~reset_mode() { hwref.set_mode(hw::device::NONE);}
};
class device_registry {
private:
std::map<std::string, std::unique_ptr<device>> registry;
public:
device_registry();
bool register_device(const std::string & device_name, device * hw_device);
device& get_device(const std::string & device_descriptor);
};
device& get_device(const std::string & device_descriptor);
bool register_device(const std::string & device_name, device * hw_device);
}
| [
"blockchainServ01@gmail.com"
] | blockchainServ01@gmail.com |
2e77a47d55bc808bd2666548ee62910294bc5111 | ab82efbe38387847fdb59be73a6193ddf636ff11 | /cpp/004/004.cpp | 04d53fc7a2b8bfde12f07ac28a581048e65cdb2d | [] | no_license | j-browne/euler | 88d00688579b81d49599147a91af706fcf598bc9 | 224f0893365f8f7ec83c040b889098d2517b2684 | refs/heads/master | 2022-12-11T23:48:34.247440 | 2020-09-20T05:46:26 | 2020-09-20T05:46:26 | 291,895,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | #include <iostream>
#include <sstream>
#include <string>
using namespace std;
bool palindrome (int num)
{
stringstream stream;
string str;
string::iterator f;
string::reverse_iterator b;
stream << num;
str = stream.str ();
for (f = str.begin (), b = str.rbegin ();
f != str.end () && b != str.rend ();
f++, b++)
{
if (*f != *b)
{
return false;
}
}
return true;
}
int main ()
{
int biggest = 0;
for (int i = 100; i < 1000; i++)
{
for (int j = i; j < 1000; j++)
{
if (palindrome (i*j) && i*j > biggest)
{
biggest = i*j;
}
}
}
cout << biggest << endl;
return 0;
}
| [
"jebdude89@gmail.com"
] | jebdude89@gmail.com |
232080facce11a1f3bd419fad2d355812bd2630b | 36579e820f5c07cd1fe796abc777f23f32efeb10 | /src/cc/paint/paint_op_reader.cc | b89c8e677dd54676787a283c47ed83f04833ca62 | [
"BSD-3-Clause"
] | permissive | sokolovp/BraveMining | 089ea9940ee6e6cb8108b106198e66c62049d27b | 7040cdee80f6f7176bea0e92f8f3435abce3e0ae | refs/heads/master | 2020-03-20T00:52:22.001918 | 2018-06-12T11:33:31 | 2018-06-12T11:33:31 | 137,058,944 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 34,844 | cc | // Copyright 2017 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.
#include "cc/paint/paint_op_reader.h"
#include <stddef.h>
#include <algorithm>
#include "cc/paint/image_transfer_cache_entry.h"
#include "cc/paint/paint_flags.h"
#include "cc/paint/paint_image_builder.h"
#include "cc/paint/paint_op_buffer.h"
#include "cc/paint/paint_shader.h"
#include "cc/paint/paint_typeface_transfer_cache_entry.h"
#include "cc/paint/transfer_cache_deserialize_helper.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "third_party/skia/include/core/SkTextBlob.h"
namespace cc {
namespace {
// If we have more than this many colors, abort deserialization.
const size_t kMaxShaderColorsSupported = 10000;
const size_t kMaxMergeFilterCount = 10000;
const size_t kMaxKernelSize = 1000;
const size_t kMaxRegionByteSize = 10 * 1024;
struct TypefacesCatalog {
TransferCacheDeserializeHelper* transfer_cache;
bool had_null = false;
};
sk_sp<SkTypeface> ResolveTypeface(uint32_t id, void* ctx) {
TypefacesCatalog* catalog = static_cast<TypefacesCatalog*>(ctx);
auto* entry = catalog->transfer_cache
->GetEntryAs<ServicePaintTypefaceTransferCacheEntry>(id);
// TODO(vmpstr): The !entry->typeface() check is here because not all
// typefaces are supported right now. Instead of making the reader invalid
// during the typeface deserialization, which results in an invalid op,
// instead just make the textblob be null by setting |had_null| to true.
if (!entry || !entry->typeface()) {
catalog->had_null = true;
return nullptr;
}
return entry->typeface().ToSkTypeface();
}
bool IsValidPaintShaderType(PaintShader::Type type) {
return static_cast<uint8_t>(type) <
static_cast<uint8_t>(PaintShader::Type::kShaderCount);
}
bool IsValidSkShaderTileMode(SkShader::TileMode mode) {
// When Skia adds Decal, update this (skbug.com/7638)
return mode <= SkShader::kMirror_TileMode;
}
bool IsValidPaintShaderScalingBehavior(PaintShader::ScalingBehavior behavior) {
return behavior == PaintShader::ScalingBehavior::kRasterAtScale ||
behavior == PaintShader::ScalingBehavior::kFixedScale;
}
} // namespace
// static
void PaintOpReader::FixupMatrixPostSerialization(SkMatrix* matrix) {
// Can't trust malicious clients to provide the correct derived matrix type.
// However, if a matrix thinks that it's identity, then make it so.
if (matrix->isIdentity())
matrix->setIdentity();
else
matrix->dirtyMatrixTypeCache();
}
// static
bool PaintOpReader::ReadAndValidateOpHeader(const volatile void* input,
size_t input_size,
uint8_t* type,
uint32_t* skip) {
uint32_t first_word = reinterpret_cast<const volatile uint32_t*>(input)[0];
*type = static_cast<uint8_t>(first_word & 0xFF);
*skip = first_word >> 8;
if (input_size < *skip)
return false;
if (*skip % PaintOpBuffer::PaintOpAlign != 0)
return false;
if (*type > static_cast<uint8_t>(PaintOpType::LastPaintOpType))
return false;
return true;
}
template <typename T>
void PaintOpReader::ReadSimple(T* val) {
static_assert(base::is_trivially_copyable<T>::value,
"Not trivially copyable");
if (remaining_bytes_ < sizeof(T))
SetInvalid();
if (!valid_)
return;
// Most of the time this is used for primitives, but this function is also
// used for SkRect/SkIRect/SkMatrix whose implicit operator= can't use a
// volatile. TOCTOU violations don't matter for these simple types so
// use assignment.
*val = *reinterpret_cast<const T*>(const_cast<const char*>(memory_));
memory_ += sizeof(T);
remaining_bytes_ -= sizeof(T);
}
template <typename T>
void PaintOpReader::ReadFlattenable(sk_sp<T>* val) {
size_t bytes = 0;
ReadSimple(&bytes);
if (remaining_bytes_ < bytes)
SetInvalid();
if (!valid_)
return;
if (bytes == 0)
return;
// This is assumed safe from TOCTOU violations as the flattenable
// deserializing function uses an SkReadBuffer which reads each piece of
// memory once much like PaintOpReader does.
DCHECK(SkIsAlign4(reinterpret_cast<uintptr_t>(memory_)));
val->reset(static_cast<T*>(
SkFlattenable::Deserialize(T::GetFlattenableType(),
const_cast<const char*>(memory_), bytes)
.release()));
if (!val)
SetInvalid();
memory_ += bytes;
remaining_bytes_ -= bytes;
}
void PaintOpReader::ReadData(size_t bytes, void* data) {
if (remaining_bytes_ < bytes)
SetInvalid();
if (!valid_)
return;
if (bytes == 0)
return;
memcpy(data, const_cast<const char*>(memory_), bytes);
memory_ += bytes;
remaining_bytes_ -= bytes;
}
void PaintOpReader::ReadArray(size_t count, SkPoint* array) {
size_t bytes = count * sizeof(SkPoint);
if (remaining_bytes_ < bytes)
SetInvalid();
// Overflow?
if (count > static_cast<size_t>(~0) / sizeof(SkPoint))
SetInvalid();
if (!valid_)
return;
if (count == 0)
return;
memcpy(array, const_cast<const char*>(memory_), bytes);
memory_ += bytes;
remaining_bytes_ -= bytes;
}
void PaintOpReader::ReadSize(size_t* size) {
ReadSimple(size);
}
void PaintOpReader::Read(SkScalar* data) {
ReadSimple(data);
}
void PaintOpReader::Read(uint8_t* data) {
ReadSimple(data);
}
void PaintOpReader::Read(uint32_t* data) {
ReadSimple(data);
}
void PaintOpReader::Read(uint64_t* data) {
ReadSimple(data);
}
void PaintOpReader::Read(int32_t* data) {
ReadSimple(data);
}
void PaintOpReader::Read(SkRect* rect) {
ReadSimple(rect);
}
void PaintOpReader::Read(SkIRect* rect) {
ReadSimple(rect);
}
void PaintOpReader::Read(SkRRect* rect) {
ReadSimple(rect);
}
void PaintOpReader::Read(SkPath* path) {
AlignMemory(4);
if (!valid_)
return;
// This is assumed safe from TOCTOU violations as the SkPath deserializing
// function uses an SkRBuffer which reads each piece of memory once much
// like PaintOpReader does. Additionally, paths are later validated in
// PaintOpBuffer.
size_t read_bytes =
path->readFromMemory(const_cast<const char*>(memory_), remaining_bytes_);
if (!read_bytes)
SetInvalid();
memory_ += read_bytes;
remaining_bytes_ -= read_bytes;
}
void PaintOpReader::Read(PaintFlags* flags) {
Read(&flags->text_size_);
ReadSimple(&flags->color_);
Read(&flags->width_);
Read(&flags->miter_limit_);
ReadSimple(&flags->blend_mode_);
ReadSimple(&flags->bitfields_uint_);
// TODO(enne): ReadTypeface, http://crbug.com/737629
// Flattenables must be read at 4-byte boundary, which should be the case
// here.
ReadFlattenable(&flags->path_effect_);
AlignMemory(4);
ReadFlattenable(&flags->mask_filter_);
AlignMemory(4);
ReadFlattenable(&flags->color_filter_);
AlignMemory(4);
if (enable_security_constraints_) {
size_t bytes = 0;
ReadSimple(&bytes);
if (bytes != 0u) {
SetInvalid();
return;
}
} else {
ReadFlattenable(&flags->draw_looper_);
}
Read(&flags->image_filter_);
Read(&flags->shader_);
}
void PaintOpReader::Read(PaintImage* image) {
uint8_t serialized_type_int = 0u;
Read(&serialized_type_int);
if (serialized_type_int >
static_cast<uint8_t>(PaintOp::SerializedImageType::kLastType)) {
SetInvalid();
return;
}
auto serialized_type =
static_cast<PaintOp::SerializedImageType>(serialized_type_int);
if (serialized_type == PaintOp::SerializedImageType::kNoImage)
return;
if (enable_security_constraints_) {
switch (serialized_type) {
case PaintOp::SerializedImageType::kNoImage:
NOTREACHED();
return;
case PaintOp::SerializedImageType::kImageData: {
SkColorType color_type;
Read(&color_type);
uint32_t width;
Read(&width);
uint32_t height;
Read(&height);
size_t pixel_size;
ReadSize(&pixel_size);
if (!valid_)
return;
SkImageInfo image_info =
SkImageInfo::Make(width, height, color_type, kPremul_SkAlphaType);
const volatile void* pixel_data = ExtractReadableMemory(pixel_size);
if (!valid_)
return;
SkPixmap pixmap(image_info, const_cast<const void*>(pixel_data),
image_info.minRowBytes());
*image = PaintImageBuilder::WithDefault()
.set_id(PaintImage::GetNextId())
.set_image(SkImage::MakeRasterCopy(pixmap),
PaintImage::kNonLazyStableId)
.TakePaintImage();
}
return;
case PaintOp::SerializedImageType::kTransferCacheEntry:
SetInvalid();
return;
}
NOTREACHED();
return;
}
if (serialized_type != PaintOp::SerializedImageType::kTransferCacheEntry) {
SetInvalid();
return;
}
uint32_t transfer_cache_entry_id;
ReadSimple(&transfer_cache_entry_id);
if (!valid_)
return;
// If we encountered a decode failure, we may write an invalid id for the
// image. In these cases, just return, leaving the image as nullptr.
if (transfer_cache_entry_id == kInvalidImageTransferCacheEntryId)
return;
if (auto* entry = transfer_cache_->GetEntryAs<ServiceImageTransferCacheEntry>(
transfer_cache_entry_id)) {
*image = PaintImageBuilder::WithDefault()
.set_id(PaintImage::GetNextId())
.set_image(entry->image(), PaintImage::kNonLazyStableId)
.TakePaintImage();
}
}
void PaintOpReader::Read(sk_sp<SkData>* data) {
size_t bytes = 0;
ReadSimple(&bytes);
if (remaining_bytes_ < bytes)
SetInvalid();
if (!valid_)
return;
// Separate out empty vs not valid cases.
if (bytes == 0) {
bool has_data = false;
Read(&has_data);
if (has_data)
*data = SkData::MakeEmpty();
return;
}
// This is safe to cast away the volatile as it is just a memcpy internally.
*data = SkData::MakeWithCopy(const_cast<const char*>(memory_), bytes);
memory_ += bytes;
remaining_bytes_ -= bytes;
}
void PaintOpReader::Read(scoped_refptr<PaintTextBlob>* paint_blob) {
sk_sp<SkData> data;
Read(&data);
if (!data || !valid_) {
SetInvalid();
return;
}
// Skia expects the following to be true, make sure we don't pass it incorrect
// data.
if (!data->data() || !SkIsAlign4(data->size())) {
SetInvalid();
return;
}
TypefacesCatalog catalog;
catalog.transfer_cache = transfer_cache_;
sk_sp<SkTextBlob> blob = SkTextBlob::Deserialize(data->data(), data->size(),
&ResolveTypeface, &catalog);
// TODO(vmpstr): If we couldn't serialize |blob|, we should make |paint_blob|
// nullptr. However, this causes GL errors right now, because not all
// typefaces are serialized. Fix this once we serialize everything. For now
// the behavior is that the |paint_blob| op exists and is valid, but
// internally it has a nullptr SkTextBlob which skia ignores.
// See also: TODO in paint_op_buffer_eq_fuzzer.
if (catalog.had_null)
blob = nullptr;
*paint_blob = base::MakeRefCounted<PaintTextBlob>(
std::move(blob), std::vector<PaintTypeface>());
}
void PaintOpReader::Read(sk_sp<PaintShader>* shader) {
bool has_shader = false;
ReadSimple(&has_shader);
if (!has_shader) {
*shader = nullptr;
return;
}
PaintShader::Type shader_type;
ReadSimple(&shader_type);
// Avoid creating a shader if something is invalid.
if (!valid_ || !IsValidPaintShaderType(shader_type)) {
SetInvalid();
return;
}
*shader = sk_sp<PaintShader>(new PaintShader(shader_type));
PaintShader& ref = **shader;
ReadSimple(&ref.flags_);
ReadSimple(&ref.end_radius_);
ReadSimple(&ref.start_radius_);
ReadSimple(&ref.tx_);
ReadSimple(&ref.ty_);
if (!IsValidSkShaderTileMode(ref.tx_) || !IsValidSkShaderTileMode(ref.ty_))
SetInvalid();
ReadSimple(&ref.fallback_color_);
ReadSimple(&ref.scaling_behavior_);
if (!IsValidPaintShaderScalingBehavior(ref.scaling_behavior_))
SetInvalid();
bool has_local_matrix = false;
ReadSimple(&has_local_matrix);
if (has_local_matrix) {
ref.local_matrix_.emplace();
Read(&*ref.local_matrix_);
}
ReadSimple(&ref.center_);
ReadSimple(&ref.tile_);
ReadSimple(&ref.start_point_);
ReadSimple(&ref.end_point_);
ReadSimple(&ref.start_degrees_);
ReadSimple(&ref.end_degrees_);
Read(&ref.image_);
bool has_record = false;
ReadSimple(&has_record);
if (has_record)
Read(&ref.record_);
decltype(ref.colors_)::size_type colors_size = 0;
ReadSimple(&colors_size);
// If there are too many colors, abort.
if (colors_size > kMaxShaderColorsSupported) {
SetInvalid();
return;
}
size_t colors_bytes = colors_size * sizeof(SkColor);
if (colors_bytes > remaining_bytes_) {
SetInvalid();
return;
}
ref.colors_.resize(colors_size);
ReadData(colors_bytes, ref.colors_.data());
decltype(ref.positions_)::size_type positions_size = 0;
ReadSimple(&positions_size);
// Positions are optional. If they exist, they have the same count as colors.
if (positions_size > 0 && positions_size != colors_size) {
SetInvalid();
return;
}
size_t positions_bytes = positions_size * sizeof(SkScalar);
if (positions_bytes > remaining_bytes_) {
SetInvalid();
return;
}
ref.positions_.resize(positions_size);
ReadData(positions_size * sizeof(SkScalar), ref.positions_.data());
// We don't write the cached shader, so don't attempt to read it either.
if (!(*shader)->IsValid()) {
SetInvalid();
return;
}
// TODO(vmpstr): We should have a PaintShader id and cache these shaders
// instead of creating every time we deserialize.
(*shader)->CreateSkShader();
}
void PaintOpReader::Read(SkMatrix* matrix) {
ReadSimple(matrix);
FixupMatrixPostSerialization(matrix);
}
void PaintOpReader::Read(SkColorType* color_type) {
uint32_t raw_color_type;
ReadSimple(&raw_color_type);
if (raw_color_type > kLastEnum_SkColorType) {
SetInvalid();
return;
}
*color_type = static_cast<SkColorType>(raw_color_type);
}
void PaintOpReader::AlignMemory(size_t alignment) {
// Due to the math below, alignment must be a power of two.
DCHECK_GT(alignment, 0u);
DCHECK_EQ(alignment & (alignment - 1), 0u);
uintptr_t memory = reinterpret_cast<uintptr_t>(memory_);
// The following is equivalent to:
// padding = (alignment - memory % alignment) % alignment;
// because alignment is a power of two. This doesn't use modulo operator
// however, since it can be slow.
size_t padding = ((memory + alignment - 1) & ~(alignment - 1)) - memory;
if (padding > remaining_bytes_)
SetInvalid();
memory_ += padding;
remaining_bytes_ -= padding;
}
inline void PaintOpReader::SetInvalid() {
valid_ = false;
}
const volatile void* PaintOpReader::ExtractReadableMemory(size_t bytes) {
if (remaining_bytes_ < bytes)
SetInvalid();
if (!valid_)
return nullptr;
if (bytes == 0)
return nullptr;
const volatile void* extracted_memory = memory_;
memory_ += bytes;
remaining_bytes_ -= bytes;
return extracted_memory;
}
void PaintOpReader::Read(sk_sp<PaintFilter>* filter) {
uint32_t type_int = 0;
ReadSimple(&type_int);
if (type_int > static_cast<uint32_t>(PaintFilter::Type::kMaxFilterType))
SetInvalid();
if (!valid_)
return;
auto type = static_cast<PaintFilter::Type>(type_int);
if (type == PaintFilter::Type::kNullFilter) {
*filter = nullptr;
return;
}
uint32_t has_crop_rect = 0;
base::Optional<PaintFilter::CropRect> crop_rect;
ReadSimple(&has_crop_rect);
if (has_crop_rect) {
uint32_t flags = 0;
SkRect rect = SkRect::MakeEmpty();
ReadSimple(&flags);
ReadSimple(&rect);
crop_rect.emplace(rect, flags);
}
AlignMemory(4);
switch (type) {
case PaintFilter::Type::kNullFilter:
NOTREACHED();
break;
case PaintFilter::Type::kColorFilter:
ReadColorFilterPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kBlur:
ReadBlurPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kDropShadow:
ReadDropShadowPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kMagnifier:
ReadMagnifierPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kCompose:
ReadComposePaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kAlphaThreshold:
ReadAlphaThresholdPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kXfermode:
ReadXfermodePaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kArithmetic:
ReadArithmeticPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kMatrixConvolution:
ReadMatrixConvolutionPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kDisplacementMapEffect:
ReadDisplacementMapEffectPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kImage:
ReadImagePaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kPaintRecord:
ReadRecordPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kMerge:
ReadMergePaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kMorphology:
ReadMorphologyPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kOffset:
ReadOffsetPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kTile:
ReadTilePaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kTurbulence:
ReadTurbulencePaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kPaintFlags:
ReadPaintFlagsPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kMatrix:
ReadMatrixPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kLightingDistant:
ReadLightingDistantPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kLightingPoint:
ReadLightingPointPaintFilter(filter, crop_rect);
break;
case PaintFilter::Type::kLightingSpot:
ReadLightingSpotPaintFilter(filter, crop_rect);
break;
}
}
void PaintOpReader::ReadColorFilterPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
sk_sp<SkColorFilter> color_filter;
sk_sp<PaintFilter> input;
ReadFlattenable(&color_filter);
Read(&input);
if (!color_filter)
SetInvalid();
if (!valid_)
return;
filter->reset(new ColorFilterPaintFilter(std::move(color_filter),
std::move(input),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadBlurPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
SkScalar sigma_x = 0.f;
SkScalar sigma_y = 0.f;
BlurPaintFilter::TileMode tile_mode = SkBlurImageFilter::kClamp_TileMode;
sk_sp<PaintFilter> input;
Read(&sigma_x);
Read(&sigma_y);
ReadSimple(&tile_mode);
Read(&input);
if (!valid_)
return;
filter->reset(new BlurPaintFilter(sigma_x, sigma_y, tile_mode,
std::move(input),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadDropShadowPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
SkScalar dx = 0.f;
SkScalar dy = 0.f;
SkScalar sigma_x = 0.f;
SkScalar sigma_y = 0.f;
SkColor color = SK_ColorBLACK;
DropShadowPaintFilter::ShadowMode shadow_mode =
SkDropShadowImageFilter::kDrawShadowAndForeground_ShadowMode;
sk_sp<PaintFilter> input;
Read(&dx);
Read(&dy);
Read(&sigma_x);
Read(&sigma_y);
Read(&color);
ReadSimple(&shadow_mode);
Read(&input);
if (shadow_mode > SkDropShadowImageFilter::kLast_ShadowMode)
SetInvalid();
if (!valid_)
return;
filter->reset(new DropShadowPaintFilter(dx, dy, sigma_x, sigma_y, color,
shadow_mode, std::move(input),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadMagnifierPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
SkRect src_rect = SkRect::MakeEmpty();
SkScalar inset = 0.f;
sk_sp<PaintFilter> input;
Read(&src_rect);
Read(&inset);
Read(&input);
if (!valid_)
return;
filter->reset(new MagnifierPaintFilter(src_rect, inset, std::move(input),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadComposePaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
sk_sp<PaintFilter> outer;
sk_sp<PaintFilter> inner;
Read(&outer);
Read(&inner);
if (!valid_)
return;
filter->reset(new ComposePaintFilter(std::move(outer), std::move(inner)));
}
void PaintOpReader::ReadAlphaThresholdPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
SkRegion region;
SkScalar inner_min = 0.f;
SkScalar outer_max = 0.f;
sk_sp<PaintFilter> input;
Read(®ion);
ReadSimple(&inner_min);
ReadSimple(&outer_max);
Read(&input);
if (!valid_)
return;
filter->reset(new AlphaThresholdPaintFilter(
region, inner_min, outer_max, std::move(input),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadXfermodePaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
uint32_t blend_mode_int = 0;
sk_sp<PaintFilter> background;
sk_sp<PaintFilter> foreground;
Read(&blend_mode_int);
Read(&background);
Read(&foreground);
SkBlendMode blend_mode = SkBlendMode::kClear;
if (blend_mode_int > static_cast<uint32_t>(SkBlendMode::kLastMode))
SetInvalid();
if (!valid_)
return;
blend_mode = static_cast<SkBlendMode>(blend_mode_int);
filter->reset(new XfermodePaintFilter(blend_mode, std::move(background),
std::move(foreground),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadArithmeticPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
float k1 = 0.f;
float k2 = 0.f;
float k3 = 0.f;
float k4 = 0.f;
bool enforce_pm_color = false;
sk_sp<PaintFilter> background;
sk_sp<PaintFilter> foreground;
Read(&k1);
Read(&k2);
Read(&k3);
Read(&k4);
Read(&enforce_pm_color);
Read(&background);
Read(&foreground);
if (!valid_)
return;
filter->reset(new ArithmeticPaintFilter(
k1, k2, k3, k4, enforce_pm_color, std::move(background),
std::move(foreground), crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadMatrixConvolutionPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
SkISize kernel_size = SkISize::MakeEmpty();
SkScalar gain = 0.f;
SkScalar bias = 0.f;
SkIPoint kernel_offset = SkIPoint::Make(0, 0);
uint32_t tile_mode_int = 0;
bool convolve_alpha = false;
sk_sp<PaintFilter> input;
ReadSimple(&kernel_size);
if (!valid_)
return;
auto size =
static_cast<size_t>(sk_64_mul(kernel_size.width(), kernel_size.height()));
if (size > kMaxKernelSize) {
SetInvalid();
return;
}
std::vector<SkScalar> kernel(size);
for (size_t i = 0; i < size; ++i)
Read(&kernel[i]);
Read(&gain);
Read(&bias);
ReadSimple(&kernel_offset);
Read(&tile_mode_int);
Read(&convolve_alpha);
Read(&input);
if (tile_mode_int > SkMatrixConvolutionImageFilter::kMax_TileMode)
SetInvalid();
if (!valid_)
return;
MatrixConvolutionPaintFilter::TileMode tile_mode =
static_cast<MatrixConvolutionPaintFilter::TileMode>(tile_mode_int);
filter->reset(new MatrixConvolutionPaintFilter(
kernel_size, kernel.data(), gain, bias, kernel_offset, tile_mode,
convolve_alpha, std::move(input), crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadDisplacementMapEffectPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
// Unknown, R, G, B, A: max type is 4.
static const int kMaxChannelSelectorType = 4;
uint32_t channel_x_int = 0;
uint32_t channel_y_int = 0;
SkScalar scale = 0.f;
sk_sp<PaintFilter> displacement;
sk_sp<PaintFilter> color;
Read(&channel_x_int);
Read(&channel_y_int);
Read(&scale);
Read(&displacement);
Read(&color);
if (channel_x_int > kMaxChannelSelectorType ||
channel_y_int > kMaxChannelSelectorType) {
SetInvalid();
}
if (!valid_)
return;
DisplacementMapEffectPaintFilter::ChannelSelectorType channel_x =
static_cast<DisplacementMapEffectPaintFilter::ChannelSelectorType>(
channel_x_int);
DisplacementMapEffectPaintFilter::ChannelSelectorType channel_y =
static_cast<DisplacementMapEffectPaintFilter::ChannelSelectorType>(
channel_y_int);
filter->reset(new DisplacementMapEffectPaintFilter(
channel_x, channel_y, scale, std::move(displacement), std::move(color),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadImagePaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
PaintImage image;
Read(&image);
if (!image) {
SetInvalid();
return;
}
SkRect src_rect;
Read(&src_rect);
SkRect dst_rect;
Read(&dst_rect);
SkFilterQuality quality;
Read(&quality);
if (!valid_)
return;
filter->reset(
new ImagePaintFilter(std::move(image), src_rect, dst_rect, quality));
}
void PaintOpReader::ReadRecordPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
SkRect record_bounds;
sk_sp<PaintRecord> record;
Read(&record_bounds);
Read(&record);
if (!valid_)
return;
filter->reset(new RecordPaintFilter(std::move(record), record_bounds));
}
void PaintOpReader::ReadMergePaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
size_t input_count = 0;
ReadSimple(&input_count);
if (input_count > kMaxMergeFilterCount)
SetInvalid();
if (!valid_)
return;
std::vector<sk_sp<PaintFilter>> inputs(input_count);
for (auto& input : inputs)
Read(&input);
if (!valid_)
return;
filter->reset(new MergePaintFilter(inputs.data(),
static_cast<int>(input_count),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadMorphologyPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
uint32_t morph_type_int = 0;
int radius_x = 0;
int radius_y = 0;
sk_sp<PaintFilter> input;
Read(&morph_type_int);
Read(&radius_x);
Read(&radius_y);
Read(&input);
if (morph_type_int >
static_cast<uint32_t>(MorphologyPaintFilter::MorphType::kMaxMorphType)) {
SetInvalid();
}
if (!valid_)
return;
MorphologyPaintFilter::MorphType morph_type =
static_cast<MorphologyPaintFilter::MorphType>(morph_type_int);
filter->reset(new MorphologyPaintFilter(morph_type, radius_x, radius_y,
std::move(input),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadOffsetPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
SkScalar dx = 0.f;
SkScalar dy = 0.f;
sk_sp<PaintFilter> input;
Read(&dx);
Read(&dy);
Read(&input);
if (!valid_)
return;
filter->reset(new OffsetPaintFilter(dx, dy, std::move(input),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadTilePaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
SkRect src = SkRect::MakeEmpty();
SkRect dst = SkRect::MakeEmpty();
sk_sp<PaintFilter> input;
Read(&src);
Read(&dst);
Read(&input);
if (!valid_)
return;
filter->reset(new TilePaintFilter(src, dst, std::move(input)));
}
void PaintOpReader::ReadTurbulencePaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
uint32_t turbulence_type_int = 0;
SkScalar base_frequency_x = 0.f;
SkScalar base_frequency_y = 0.f;
int num_octaves = 0;
SkScalar seed = 0.f;
SkISize tile_size = SkISize::MakeEmpty();
Read(&turbulence_type_int);
Read(&base_frequency_x);
Read(&base_frequency_y);
Read(&num_octaves);
Read(&seed);
ReadSimple(&tile_size);
if (turbulence_type_int >
static_cast<uint32_t>(
TurbulencePaintFilter::TurbulenceType::kMaxTurbulenceType)) {
SetInvalid();
}
if (!valid_)
return;
TurbulencePaintFilter::TurbulenceType turbulence_type =
static_cast<TurbulencePaintFilter::TurbulenceType>(turbulence_type_int);
filter->reset(new TurbulencePaintFilter(
turbulence_type, base_frequency_x, base_frequency_y, num_octaves, seed,
&tile_size, crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadPaintFlagsPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
AlignMemory(4);
PaintFlags flags;
Read(&flags);
if (!valid_)
return;
filter->reset(
new PaintFlagsPaintFilter(flags, crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadMatrixPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
SkMatrix matrix = SkMatrix::I();
SkFilterQuality filter_quality = kNone_SkFilterQuality;
sk_sp<PaintFilter> input;
Read(&matrix);
ReadSimple(&filter_quality);
Read(&input);
if (filter_quality > kLast_SkFilterQuality)
SetInvalid();
if (!valid_)
return;
filter->reset(
new MatrixPaintFilter(matrix, filter_quality, std::move(input)));
}
void PaintOpReader::ReadLightingDistantPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
uint32_t lighting_type_int = 0;
SkPoint3 direction = SkPoint3::Make(0.f, 0.f, 0.f);
SkColor light_color = SK_ColorBLACK;
SkScalar surface_scale = 0.f;
SkScalar kconstant = 0.f;
SkScalar shininess = 0.f;
sk_sp<PaintFilter> input;
Read(&lighting_type_int);
ReadSimple(&direction);
Read(&light_color);
Read(&surface_scale);
Read(&kconstant);
Read(&shininess);
Read(&input);
if (lighting_type_int >
static_cast<uint32_t>(PaintFilter::LightingType::kMaxLightingType)) {
SetInvalid();
}
if (!valid_)
return;
PaintFilter::LightingType lighting_type =
static_cast<PaintFilter::LightingType>(lighting_type_int);
filter->reset(new LightingDistantPaintFilter(
lighting_type, direction, light_color, surface_scale, kconstant,
shininess, std::move(input), crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadLightingPointPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
uint32_t lighting_type_int = 0;
SkPoint3 location = SkPoint3::Make(0.f, 0.f, 0.f);
SkColor light_color = SK_ColorBLACK;
SkScalar surface_scale = 0.f;
SkScalar kconstant = 0.f;
SkScalar shininess = 0.f;
sk_sp<PaintFilter> input;
Read(&lighting_type_int);
ReadSimple(&location);
Read(&light_color);
Read(&surface_scale);
Read(&kconstant);
Read(&shininess);
Read(&input);
if (lighting_type_int >
static_cast<uint32_t>(PaintFilter::LightingType::kMaxLightingType)) {
SetInvalid();
}
if (!valid_)
return;
PaintFilter::LightingType lighting_type =
static_cast<PaintFilter::LightingType>(lighting_type_int);
filter->reset(new LightingPointPaintFilter(
lighting_type, location, light_color, surface_scale, kconstant, shininess,
std::move(input), crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::ReadLightingSpotPaintFilter(
sk_sp<PaintFilter>* filter,
const base::Optional<PaintFilter::CropRect>& crop_rect) {
uint32_t lighting_type_int = 0;
SkPoint3 location = SkPoint3::Make(0.f, 0.f, 0.f);
SkPoint3 target = SkPoint3::Make(0.f, 0.f, 0.f);
SkScalar specular_exponent = 0.f;
SkScalar cutoff_angle = 0.f;
SkColor light_color = SK_ColorBLACK;
SkScalar surface_scale = 0.f;
SkScalar kconstant = 0.f;
SkScalar shininess = 0.f;
sk_sp<PaintFilter> input;
Read(&lighting_type_int);
ReadSimple(&location);
ReadSimple(&target);
Read(&specular_exponent);
Read(&cutoff_angle);
Read(&light_color);
Read(&surface_scale);
Read(&kconstant);
Read(&shininess);
Read(&input);
if (lighting_type_int >
static_cast<uint32_t>(PaintFilter::LightingType::kMaxLightingType)) {
SetInvalid();
}
if (!valid_)
return;
PaintFilter::LightingType lighting_type =
static_cast<PaintFilter::LightingType>(lighting_type_int);
filter->reset(new LightingSpotPaintFilter(
lighting_type, location, target, specular_exponent, cutoff_angle,
light_color, surface_scale, kconstant, shininess, std::move(input),
crop_rect ? &*crop_rect : nullptr));
}
void PaintOpReader::Read(sk_sp<PaintRecord>* record) {
size_t size_bytes = 0;
ReadSimple(&size_bytes);
AlignMemory(PaintOpBuffer::PaintOpAlign);
if (enable_security_constraints_) {
// Validate that the record was not serialized if security constraints are
// enabled.
if (size_bytes != 0) {
SetInvalid();
return;
}
*record = sk_make_sp<PaintOpBuffer>();
return;
}
if (size_bytes > remaining_bytes_)
SetInvalid();
if (!valid_)
return;
PaintOp::DeserializeOptions options;
options.transfer_cache = transfer_cache_;
*record = PaintOpBuffer::MakeFromMemory(memory_, size_bytes, options);
if (!*record) {
SetInvalid();
return;
}
memory_ += size_bytes;
remaining_bytes_ -= size_bytes;
}
void PaintOpReader::Read(SkRegion* region) {
size_t region_bytes = 0;
ReadSimple(®ion_bytes);
if (region_bytes == 0 || region_bytes > kMaxRegionByteSize)
SetInvalid();
if (!valid_)
return;
std::unique_ptr<char[]> data(new char[region_bytes]);
ReadData(region_bytes, data.get());
if (!valid_)
return;
size_t result = region->readFromMemory(data.get(), region_bytes);
if (!result)
SetInvalid();
}
} // namespace cc
| [
"sokolov.p@gmail.com"
] | sokolov.p@gmail.com |
39157dc64028bb3c7be94c009aac25ebcd5dba05 | be6601674657294784b9ef455c1773d73ad657d9 | /PandoraSDK/include/Objects/OrderedCaloHitList.h | b1434358dcb8a4c41d55ac199a0d220a0acf648d | [] | no_license | cms-externals/pandora | 0a7a7eaec6596f57bec89f28e72ac4eb04a68eb7 | 41abc90c25109c5bc91896079546e53a8586c057 | refs/heads/master | 2016-09-05T13:13:39.703922 | 2015-03-12T09:48:17 | 2015-03-12T09:48:17 | 31,168,496 | 0 | 1 | null | 2015-03-12T09:48:20 | 2015-02-22T16:01:51 | C++ | UTF-8 | C++ | false | false | 7,778 | h | /**
* @file PandoraSDK/include/Objects/OrderedCaloHitList.h
*
* @brief Header file for the ordered calo hit list class.
*
* $Log: $
*/
#ifndef PANDORA_ORDERED_CALO_HIT_LIST_H
#define PANDORA_ORDERED_CALO_HIT_LIST_H 1
#include "Objects/CaloHit.h"
#include "Pandora/PandoraInternal.h"
#include "Pandora/StatusCodes.h"
#include <map>
namespace pandora
{
/**
* @brief Calo hit lists arranged by pseudo layer
*/
class OrderedCaloHitList
{
public:
typedef std::map<unsigned int, CaloHitList *> TheList;
typedef TheList::const_iterator const_iterator;
typedef TheList::const_reverse_iterator const_reverse_iterator;
/**
* @brief Default constructor
*/
OrderedCaloHitList();
/**
* @brief Copy constructor
*
* @param rhs the ordered calo hit list to copy
*/
OrderedCaloHitList(const OrderedCaloHitList &rhs);
/**
* @brief Destructor
*/
~OrderedCaloHitList();
/**
* @brief Add the hits from a second ordered calo hit list to this list
*
* @param rhs the source ordered calo hit list
*/
StatusCode Add(const OrderedCaloHitList &rhs);
/**
* @brief Remove the hits in a second ordered calo hit list from this list
*
* @param rhs the source ordered calo hit list
*/
StatusCode Remove(const OrderedCaloHitList &rhs);
/**
* @brief Add a list of calo hits to the ordered calo hit list
*
* @param caloHitList the calo hit list
*/
StatusCode Add(const CaloHitList &caloHitList);
/**
* @brief Remove a list of calo hits from the ordered calo hit list
*
* @param caloHitList the calo hit list
*/
StatusCode Remove(const CaloHitList &caloHitList);
/**
* @brief Add a calo hit to the ordered calo hit list
*
* @param pCaloHit the address of the calo hit
*/
StatusCode Add(const CaloHit *const pCaloHit);
/**
* @brief Remove a calo hit from the ordered calo hit list
*
* @param pCaloHit the address of the calo hit
*/
StatusCode Remove(const CaloHit *const pCaloHit);
/**
* @brief Get calo hits in specified pseudo layer
*
* @param pseudoLayer the pseudo layer
* @param pCaloHitList to receive the address of the relevant calo hit list
*/
StatusCode GetCaloHitsInPseudoLayer(const unsigned int pseudoLayer, CaloHitList *&pCaloHitList) const;
/**
* @brief Get the number of calo hits in a specified pseudo layer
*
* @param pseudoLayer the pseudo layer
*
* @return The number of calo hits in the specified pseudo layer
*/
unsigned int GetNCaloHitsInPseudoLayer(const unsigned int pseudoLayer) const;
/**
* @brief Reset the ordered calo hit list, emptying its contents
*/
void Reset();
/**
* @brief Get a simple list of all the calo hits in the ordered calo hit list (no ordering by pseudolayer)
*
* @param caloHitList to receive the simple list of calo hits
*/
void GetCaloHitList(CaloHitList &caloHitList) const;
/**
* @brief Returns a const iterator referring to the first element in the ordered calo hit list
*/
const_iterator begin() const;
/**
* @brief Returns a const iterator referring to the past-the-end element in the ordered calo hit list
*/
const_iterator end() const;
/**
* @brief Returns a const reverse iterator referring to the first element in the ordered calo hit list
*/
const_reverse_iterator rbegin() const;
/**
* @brief Returns a const reverse iterator referring to the past-the-end element in the ordered calo hit list
*/
const_reverse_iterator rend() const;
/**
* @brief Searches the container for an element with specified layer and returns an iterator to it if found,
* otherwise it returns an iterator to the past-the-end element.
*/
const_iterator find(const unsigned int index) const;
/**
* @brief Returns the number of elements in the container.
*/
unsigned int size() const;
/**
* @brief Returns whether the map container is empty (i.e. whether its size is 0)
*/
bool empty() const;
/**
* @brief Assignment operator
*
* @param rhs the ordered calo hit list to assign
*/
bool operator= (const OrderedCaloHitList &rhs);
private:
/**
* @brief Clear the ordered calo hit list
*/
void clear();
/**
* @brief Add a calo hit to a specified pseudo layer
*
* @param pCaloHit the address of the calo hit
* @param pseudoLayer the pesudo layer
*/
StatusCode Add(const CaloHit *const pCaloHit, const unsigned int pseudoLayer);
/**
* @brief Remove a calo hit from a specified pseudo layer
*
* @param pCaloHit the address of the calo hit
* @param pseudoLayer the pesudo layer
*/
StatusCode Remove(const CaloHit *const pCaloHit, const unsigned int pseudoLayer);
TheList m_theList; ///< The ordered calo hit list
};
//------------------------------------------------------------------------------------------------------------------------------------------
inline OrderedCaloHitList::const_iterator OrderedCaloHitList::begin() const
{
return m_theList.begin();
}
//------------------------------------------------------------------------------------------------------------------------------------------
inline OrderedCaloHitList::const_iterator OrderedCaloHitList::end() const
{
return m_theList.end();
}
//------------------------------------------------------------------------------------------------------------------------------------------
inline OrderedCaloHitList::const_iterator OrderedCaloHitList::find(const unsigned int index) const
{
return m_theList.find(index);
}
//------------------------------------------------------------------------------------------------------------------------------------------
inline OrderedCaloHitList::const_reverse_iterator OrderedCaloHitList::rbegin() const
{
return m_theList.rbegin();
}
//------------------------------------------------------------------------------------------------------------------------------------------
inline OrderedCaloHitList::const_reverse_iterator OrderedCaloHitList::rend() const
{
return m_theList.rend();
}
//------------------------------------------------------------------------------------------------------------------------------------------
inline unsigned int OrderedCaloHitList::size() const
{
return m_theList.size();
}
//------------------------------------------------------------------------------------------------------------------------------------------
inline bool OrderedCaloHitList::empty() const
{
return m_theList.empty();
}
//------------------------------------------------------------------------------------------------------------------------------------------
inline StatusCode OrderedCaloHitList::Add(const CaloHit *const pCaloHit)
{
return this->Add(pCaloHit, pCaloHit->GetPseudoLayer());
}
//------------------------------------------------------------------------------------------------------------------------------------------
inline StatusCode OrderedCaloHitList::Remove(const CaloHit *const pCaloHit)
{
return this->Remove(pCaloHit, pCaloHit->GetPseudoLayer());
}
//------------------------------------------------------------------------------------------------------------------------------------------
inline void OrderedCaloHitList::clear()
{
m_theList.clear();
}
} // namespace pandora
#endif // #ifndef PANDORA_ORDERED_CALO_HIT_LIST_H
| [
"a.degano@gmail.com"
] | a.degano@gmail.com |
5c3e05d22e8b42ad708761034b2c3f2148153589 | 15ffb46a378b034ac16df9a42c4a799fa3ba79eb | /code/util/cust_memory_pool.cc | d705ee6e20fdd0b2cda88ad4430766ce6d8d3fe1 | [] | no_license | cloudfuse-io/lab-cpp | bad69e95946b4d14b8f82935e97a1d86d9c3560c | 5d357ed46673044e710884feec79f667432aefe3 | refs/heads/master | 2022-12-23T10:36:51.629721 | 2020-10-01T14:08:21 | 2020-10-01T14:08:21 | 300,302,731 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,685 | cc | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "cust_memory_pool.h"
#include <sys/mman.h>
#define BOOST_STACKTRACE_USE_ADDR2LINE
#include <algorithm> // IWYU pragma: keep
#include <boost/stacktrace.hpp>
#include <cstdlib> // IWYU pragma: keep
#include <cstring> // IWYU pragma: keep
#include <iostream> // IWYU pragma: keep
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <queue>
static constexpr int64_t PREALLOC_SIZE_BYTES = 1024 * 1024;
static constexpr int64_t PREALLOC_COUNT = 1500;
namespace Buzz {
// compute the "whole page size" equivalent of this size
size_t whole_page_size(size_t raw_size) {
size_t page_size = 4 * 1024;
int remainder = raw_size % page_size;
if (remainder == 0) return raw_size;
return raw_size + page_size - remainder;
}
class guarded_map {
private:
std::map<uint8_t*, int64_t> map_;
mutable std::mutex mutex_;
public:
void set(uint8_t* key, int64_t value) {
std::lock_guard<std::mutex> lk(mutex_);
map_[key] = value;
}
bool erase(uint8_t* key) {
std::lock_guard<std::mutex> lk(mutex_);
return map_.erase(key);
}
bool contains(uint8_t* key) const {
std::lock_guard<std::mutex> lk(mutex_);
return map_.find(key) != map_.end();
}
int64_t sum() const {
std::lock_guard<std::mutex> lk(mutex_);
int64_t sum = 0;
for (auto alloc : map_) {
sum += alloc.second;
}
return sum;
}
};
class linked_set {
using Node = std::pair<uint8_t*, int64_t>;
private:
std::vector<std::vector<Node>> vect_vect_;
mutable std::mutex mutex_;
public:
void add(uint8_t* old_key, uint8_t* new_key, int64_t value) {
#ifdef ACTIVATE_ALLOCATION_LINKING
std::lock_guard<std::mutex> lk(mutex_);
for (auto& node_vect : vect_vect_) {
if (node_vect[node_vect.size() - 1].first == old_key) {
node_vect.push_back({new_key, value});
return;
}
}
std::vector<Node> new_node_vect;
new_node_vect.push_back({new_key, value});
vect_vect_.push_back(new_node_vect);
#endif
}
void print() const {
#ifdef ACTIVATE_ALLOCATION_LINKING
std::lock_guard<std::mutex> lk(mutex_);
for (auto node_vect : vect_vect_) {
uint8_t* prev_addr = nullptr;
int64_t prev_size = 0;
for (auto node : node_vect) {
std::string sep;
if (node.second >= prev_size) {
sep = "+";
} else {
sep = "-";
}
if (node.first == prev_addr) {
std::cout << sep;
} else {
std::cout << sep << sep;
}
std::cout << node.second;
prev_addr = node.first;
prev_size = node.second;
}
std::cout << std::endl;
}
#endif
}
};
class guarded_queue {
private:
std::queue<uint8_t*> queue_;
mutable std::mutex mutex_;
public:
uint8_t* pop() {
std::lock_guard<std::mutex> lk(mutex_);
if (queue_.size() == 0) {
return nullptr;
}
auto res = queue_.front();
queue_.pop();
return res;
}
void push(uint8_t* key) {
std::lock_guard<std::mutex> lk(mutex_);
queue_.push(key);
}
};
class CustomMemoryPool::CustomMemoryPoolImpl {
public:
explicit CustomMemoryPoolImpl(MemoryPool* pool) : pool_(pool) {
#ifdef ACTIVATE_ALLOCATION_LINKING
std::cout << "ACTIVATE_ALLOCATION_LINKING = ON" << std::endl;
#else
std::cout << "ACTIVATE_ALLOCATION_LINKING = OFF" << std::endl;
#endif
#ifdef ACTIVATE_RUNWAY_ALLOCATOR
std::cout << "ACTIVATE_RUNWAY_ALLOCATOR = ON" << std::endl;
#else
std::cout << "ACTIVATE_RUNWAY_ALLOCATOR = OFF" << std::endl;
#endif
#ifdef ACTIVATE_POOL_ALLOCATOR
for (int i = 0; i < PREALLOC_COUNT; i++) {
void* raw_ptr =
mmap(nullptr, // attribute address automatically
PREALLOC_SIZE_BYTES, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, 0, 0);
pool_allocs_.push(reinterpret_cast<uint8_t*>(raw_ptr));
memset(raw_ptr, 1, static_cast<size_t>(PREALLOC_SIZE_BYTES));
}
std::cout << "ACTIVATE_POOL_ALLOCATOR = ON" << std::endl;
#else
std::cout << "ACTIVATE_POOL_ALLOCATOR = OFF" << std::endl;
#endif
}
Status Allocate(int64_t size, uint8_t** out) {
#ifdef ACTIVATE_ALLOCATION_PRINTING
if (size > 0) {
std::cout << "Allocate," << size << "," << size << "," << 0 << std::endl;
}
#endif
#ifdef ACTIVATE_RUNWAY_ALLOCATOR
if (size >= HUGE_ALLOC_THRESHOLD_BYTES) {
auto status = runway_allocate(size, out);
linked_allocs_.add(nullptr, *out, size);
return status;
}
#endif
#ifdef ACTIVATE_POOL_ALLOCATOR
if (size > 0) {
auto status = pool_allocate(size, out);
linked_allocs_.add(nullptr, *out, size);
return status;
}
#endif
auto status = pool_->Allocate(size, out);
linked_allocs_.add(nullptr, *out, size);
return status;
}
Status Reallocate(int64_t old_size, int64_t new_size, uint8_t** ptr) {
uint8_t* previous_ptr = *ptr;
#ifdef ACTIVATE_RUNWAY_ALLOCATOR
if (old_size >= SMALL_ALLOC_THRESHOLD_BYTES ||
new_size >= HUGE_ALLOC_THRESHOLD_BYTES) {
// this seems to be meat for the custom allocator
auto result = runway_reallocate(old_size, new_size, ptr);
RETURN_NOT_OK(result.status());
if (result.ValueOrDie()) {
linked_allocs_.add(previous_ptr, *ptr, new_size);
print_realloc(old_size, new_size, previous_ptr, *ptr);
return Status::OK();
}
}
#endif
#ifdef ACTIVATE_POOL_ALLOCATOR
if (new_size > 0) {
// this seems to be meat for the custom allocator
auto result = pool_reallocate(old_size, new_size, ptr);
RETURN_NOT_OK(result.status());
if (result.ValueOrDie()) {
linked_allocs_.add(previous_ptr, *ptr, new_size);
print_realloc(old_size, new_size, previous_ptr, *ptr);
return Status::OK();
}
}
#endif
RETURN_NOT_OK(pool_->Reallocate(old_size, new_size, ptr));
linked_allocs_.add(previous_ptr, *ptr, new_size);
print_realloc(old_size, new_size, previous_ptr, *ptr);
return Status::OK();
}
void Free(uint8_t* buffer, int64_t size) {
#ifdef ACTIVATE_ALLOCATION_PRINTING
if (size > 0) {
std::cout << "Free," << -size << "," << 0 << "," << size << std::endl;
}
#endif
#ifdef ACTIVATE_RUNWAY_ALLOCATOR
if (size >= SMALL_ALLOC_THRESHOLD_BYTES) {
runway_free(buffer, size);
return;
}
#endif
#ifdef ACTIVATE_POOL_ALLOCATOR
if (size > 0) {
pool_free(buffer, size);
return;
}
#endif
pool_->Free(buffer, size);
}
int64_t bytes_allocated() const {
linked_allocs_.print();
return pool_->bytes_allocated() + large_allocs_.sum();
}
int64_t max_memory() const { throw "Not implemented yet."; }
std::string backend_name() const { return pool_->backend_name() + "_custom"; }
int64_t copied_bytes_;
private:
MemoryPool* pool_;
guarded_map large_allocs_;
linked_set linked_allocs_;
guarded_queue pool_allocs_;
Status runway_allocate(int64_t size, uint8_t** out) {
void* raw_ptr = mmap(nullptr, // attribute address automatically
HUGE_ALLOC_RUNWAY_SIZE_BYTES, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE, 0, 0);
*out = reinterpret_cast<uint8_t*>(raw_ptr);
large_allocs_.set(*out, size);
return Status::OK();
}
Status pool_allocate(int64_t size, uint8_t** out) {
if (size > PREALLOC_SIZE_BYTES) {
return Status::ExecutionError("Allocation larger than PREALLOC_SIZE_BYTES");
}
auto alloc = pool_allocs_.pop();
if (alloc != nullptr) {
*out = alloc;
return Status::OK();
} else {
return Status::ExecutionError("no more alloc in pool");
}
}
Result<bool> runway_reallocate(int64_t old_size, int64_t new_size, uint8_t** ptr) {
uint8_t* previous_ptr = *ptr;
bool allocation_done = false;
if (large_allocs_.contains(*ptr)) {
// already managed by the custom allocator
if (new_size < SMALL_ALLOC_THRESHOLD_BYTES) {
// got so small than we return it to inner allocator
pool_->Allocate(new_size, ptr);
memcpy(*ptr, previous_ptr, new_size);
runway_free(previous_ptr, old_size);
} else {
large_allocs_.set(*ptr, new_size);
if (new_size < old_size) {
// size shrinked so give unused pages back to the OS
auto new_wps = whole_page_size(new_size);
// std::cout << "new_wps:" << new_wps << std::endl;
if (old_size - new_wps > 0) {
int madv_result = madvise(*ptr + new_wps, old_size - new_wps, MADV_DONTNEED);
if (madv_result != 0) {
return Status::ExecutionError("MADV_DONTNEED failed");
}
}
}
}
allocation_done = true;
} else if (new_size >= HUGE_ALLOC_THRESHOLD_BYTES) {
// from now on manage with custom allocator
RETURN_NOT_OK(runway_allocate(new_size, ptr));
memcpy(*ptr, previous_ptr, old_size);
pool_->Free(previous_ptr, old_size);
allocation_done = true;
}
return allocation_done;
}
Result<bool> pool_reallocate(int64_t old_size, int64_t new_size, uint8_t** ptr) {
if (old_size == 0) {
RETURN_NOT_OK(pool_allocate(new_size, ptr));
} else if (new_size > PREALLOC_SIZE_BYTES) {
return Status::ExecutionError("Reallocation larger than PREALLOC_SIZE_BYTES");
}
return true;
}
void runway_free(uint8_t* buffer, int64_t size) {
auto is_erased = large_allocs_.erase(buffer);
if (is_erased) {
munmap(buffer, HUGE_ALLOC_RUNWAY_SIZE_BYTES);
}
}
void pool_free(uint8_t* buffer, int64_t size) { pool_allocs_.push(buffer); }
void print_realloc(int64_t old_size, int64_t new_size, uint8_t* old_ptr,
uint8_t* new_ptr) {
#ifdef ACTIVATE_ALLOCATION_PRINTING
if (old_ptr != new_ptr) {
copied_bytes_ += old_size;
std::cout << "ReallocateCopy,";
} else {
std::cout << "Reallocate,";
}
std::cout << new_size - old_size << "," << new_size << "," << old_size << std::endl;
#endif
}
};
CustomMemoryPool::CustomMemoryPool(MemoryPool* pool) {
impl_.reset(new CustomMemoryPoolImpl(pool));
}
CustomMemoryPool::~CustomMemoryPool() {}
Status CustomMemoryPool::Allocate(int64_t size, uint8_t** out) {
return impl_->Allocate(size, out);
}
Status CustomMemoryPool::Reallocate(int64_t old_size, int64_t new_size, uint8_t** ptr) {
return impl_->Reallocate(old_size, new_size, ptr);
}
void CustomMemoryPool::Free(uint8_t* buffer, int64_t size) {
return impl_->Free(buffer, size);
}
int64_t CustomMemoryPool::bytes_allocated() const { return impl_->bytes_allocated(); }
int64_t CustomMemoryPool::max_memory() const { return impl_->max_memory(); }
int64_t CustomMemoryPool::copied_bytes() const { return impl_->copied_bytes_; }
std::string CustomMemoryPool::backend_name() const { return impl_->backend_name(); }
} // namespace arrow
| [
"rdettai@gmail.com"
] | rdettai@gmail.com |
5a5d3206516a3729f6bc90a772fb5ae6a6721af6 | d64dabe0b2136523fa9e75847189738946c3899d | /new/dayz_code/config/CfgMagazines/Attachments/SupBizon.hpp | ace64cdf45473aedcca8bfbd8f1802723b4b3ef0 | [] | no_license | AlexAFlorov/DayZ | d506eced27c5234fa3953979fca6c210ccd4f019 | e66dbe751409e70e141f29d76f7b0ec6141a7578 | refs/heads/Development | 2021-01-14T14:16:21.149249 | 2016-07-25T00:01:28 | 2016-07-25T00:01:28 | 39,254,564 | 0 | 0 | null | 2015-07-17T13:06:56 | 2015-07-17T13:06:56 | null | UTF-8 | C++ | false | false | 609 | hpp | class Attachment_SupBizon : CA_Magazine
{
scope = public;
count = 1;
type = WeaponSlotItem;
model = "z\addons\dayz_communityassets\models\surpressor.p3d";
picture = "\z\addons\dayz_communityassets\pictures\attachment_silencer.paa";
displayName = $STR_ATTACHMENT_NAME_SILENCER_BIZON;
descriptionShort = $STR_ATTACHMENT_DESC_SILENCER_BIZON;
class ItemActions
{
class AttachToPrimary
{
text = $STR_DZ_ATT_ACT_TO_PRIMARY;
action = "[_this select 0, 1] call dz_fn_attachment_attach";
condition = "[_this select 0, 1] call dz_fn_attachment_canAttach";
closeDisplay = true;
};
};
}; | [
"asfoxyy@gmail.com"
] | asfoxyy@gmail.com |
ff828e61d0c9914c1154cf05988dc8fc112de0e0 | 3ae2a16953f0262a42a0bcfbd0ac63cb1895f1d5 | /MPI_Online_Course/Lecture_4/reduce_parts.cpp | 5a8a1059084282b48419538a3df9427ea2bd00b2 | [] | no_license | TaigoFr/ARCHER_MPI | da01ddf529024c10229c6a9e219e779fa7717118 | cb02ce1173496f989a42d0d9248f7b76efb53c46 | refs/heads/master | 2020-04-25T04:39:03.192748 | 2019-04-04T15:22:27 | 2019-04-04T15:22:27 | 172,517,454 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,724 | cpp |
#include "mpi.h"
#include <cstdio>
#include <cstring>
#include <fstream>
#include <cmath>
#include <iomanip> //setprecision
/*
N=10
SIZE | Time for 1M*2*N iterations
1 1.4s
2 ~4.7s
3 ~5.1s
4 ~6.0s
5 ~8.0s
6 ~9.8s
7 ~10.2s
Average: ~[0.24us-0.09us]
Latency (from pingpong exercise): ~0.3us
Big delay for 1 CPU.
Definitely a lot worse than reduce_vec.cpp.
It almost seems as if the collective reduction operation is seen as a single operation (without the factor of 10 being needed)
*/
int main(){
MPI_Init(NULL,NULL);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
const int N = 10;
int vec[N];
for(int i=0; i<N; ++i)
vec[i] = rank;
int next = (rank+1)%size;
int prev = (rank+size-1)%size;
MPI_Request request;
MPI_Status status;
int sum[N], sum2[N];
int send1[N], send2[N];
const unsigned repeat = 1000000;
MPI_Barrier(MPI_COMM_WORLD);
double time = MPI_Wtime();
for(unsigned k=0; k<repeat; ++k){
for(int i=0; i<N; ++i){
sum[i] = rank;
sum2[i] = (rank+1)*(rank+1);
send1[i] = sum[i];
send2[i] = sum2[i];
}
int recv[N];
for(int i=0; i<N; ++i){
MPI_Allreduce(&(send1[i]), &(recv[i]), 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
sum[i] = recv[i];
}
for(int i=0; i<N; ++i){
MPI_Allreduce(&(send2[i]), &(recv[i]), 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
sum2[i] = recv[i];
}
}
printf("[%d/%d] sum[5] = %d;\tsum2[5] = %d\n",rank,size,sum[5],sum2[5]);
MPI_Barrier(MPI_COMM_WORLD);
time = MPI_Wtime() - time;
if(rank==0)
printf("Time elapsed: %lf\n",time);
if(rank==0)
printf("Final results should be: sum = %d;\tsum2 = %d\n",size*(size-1)/2,size*(size+1)*(2*size+1)/6);
MPI_Finalize();
} | [
"taigo.fr@outlook.com"
] | taigo.fr@outlook.com |
fd15e8dbb3ec0d147b4afd18805f824a7ce11f57 | 920b66d220bdcd6c65a0e80a1c3cb9a7e042685a | /cruise/navigation_tutorials/simple_navigation_goals_tutorial/src/simple_navigation_goals.cpp | af397fe7225466150d11d79adce26eaad14de9ec | [] | no_license | NKU-ZiXuan/Graduation_Project | 34795b1f9202380a2feac347ac290425bf05e763 | d2bf757084f274677e953ea20c8f9fd5b824698d | refs/heads/master | 2022-07-27T08:00:27.497738 | 2020-05-23T04:02:13 | 2020-05-23T04:02:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,636 | cpp | /*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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.
*
* Author: Eitan Marder-Eppstein
*
* For a discussion of this tutorial, please see:
* http://pr.willowgarage.com/wiki/navigation/Tutorials/SendingSimpleGoals
*********************************************************************/
#include <ros/ros.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <tf/transform_datatypes.h>
#include <boost/thread.hpp>
#include <geometry_msgs/Point.h>
geometry_msgs::Point target_point;
ros::Subscriber get_target_point_sub;
typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;
void spinThread(){
ros::spin();
}
void get_target_point_cb( const geometry_msgs::Point::ConstPtr& target_msg)
{
target_point = *target_msg;
}
int main(int argc, char** argv){
ros::init(argc, argv, "simple_navigation_goals");
ros::NodeHandle n;
boost::thread spin_thread = boost::thread(boost::bind(&spinThread));
MoveBaseClient ac("pose_base_controller");
//give some time for connections to register
sleep(2.0);
get_target_point_sub = n.subscribe<geometry_msgs::Point>("nearest_turtlebot1", 1000, &get_target_point_cb);
move_base_msgs::MoveBaseGoal goal;
//we'll send a goal to the robot to move 2 meters forward
goal.target_pose.header.frame_id = "base_link";
goal.target_pose.header.stamp = ros::Time::now();
goal.target_pose.pose.position.x = target_point.x;
goal.target_pose.pose.position.y = target_point.y;
goal.target_pose.pose.orientation = tf::createQuaternionMsgFromYaw(M_PI);
ROS_INFO("Sending goal");
ac.sendGoal(goal);
ac.waitForResult();
if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED)
ROS_INFO("Hooray, the base moved 2 meters forward");
else
ROS_INFO("The base failed to move forward 2 meters for some reason");
sleep(10);
goal.target_pose.pose.position.x = 4;
goal.target_pose.pose.position.y = -4;
return 0;
}
| [
"gjxslwz@gmail.com"
] | gjxslwz@gmail.com |
bb200d39b22a33f96c9b87729f4111855f2c7fed | e778be8ebc60a2ec915698280f17fafffe55c5fb | /platforms/imx8mm/include/nav_os/conf/nav_os_conf.h | 1d60473fd18963b7a8758c3cf57f7d69e8babeec | [] | no_license | 3JLinux/xag_xhome | 30b933e11b40ff3c72c810e49a857caaf49a7247 | c2b00f449354cf12b72c8c87246a3b4493b751d8 | refs/heads/master | 2023-06-14T08:05:29.771649 | 2021-07-02T02:00:42 | 2021-07-02T02:00:42 | 382,225,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 207 | h |
#include <string>
namespace xag_nav{
namespace os{
namespace conf{
const std::string XAG_NAV_UPDATE_FLAG_FILE = "/usr/local/xag_navigation_update_pkg/xag_nav_update_flagfile";
}
}
} // namespace xag_nav
| [
"421721486@qq.com"
] | 421721486@qq.com |
4390675429fa71add3aa7efc58bf4f79a28e2bf6 | 21d95c8e302242eb03e334d97ff51b9fee8fff90 | /server/src/jMetalCpp/Ranking.cpp | 32971e859fe481cafe855636f5d2e719cb34a455 | [] | no_license | nszknao/master | 8e909336476efba112e27bd5c4478373a191db12 | ef7fd255209e7ef3d63a483ae03a55b54727a194 | refs/heads/master | 2023-04-30T16:23:17.485757 | 2023-04-26T07:26:17 | 2023-04-26T07:26:17 | 45,908,367 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,929 | cpp | // Ranking.cpp
//
// Author:
// Antonio J. Nebro <antonio@lcc.uma.es>
// Juan J. Durillo <durillo@lcc.uma.es>
// Esteban López-Camacho <esteban@lcc.uma.es>
//
// Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <Ranking.h>
/**
* This class implements some facilities for ranking solutions.
* Given a <code>SolutionSet</code> object, their solutions are ranked
* according to scheme proposed in NSGA-II; as a result, a set of subsets
* are obtained. The subsets are numbered starting from 0 (in NSGA-II, the
* numbering starts from 1); thus, subset 0 contains the non-dominated
* solutions, subset 1 contains the non-dominated solutions after removing those
* belonging to subset 0, and so on.
*/
/**
* Constructor.
* @param solutionSet The <code>SolutionSet</code> to be ranked.
*/
Ranking::Ranking (SolutionSet * solutionSet) {
solutionSet_ = solutionSet;
dominance_ = new DominanceComparator();
constraint_ = new OverallConstraintViolationComparator();
// dominateMe[i] contains the number of solutions dominating i
int * dominateMe = new int[solutionSet_->size()];
if (dominateMe == NULL) {
cout << "Fatal Problem: Cannot reserve memory in class Ranking" << endl;
exit(-1);
}
// iDominate[k] contains the list of solutions dominated by k
vector<int> * iDominate = new vector<int>[solutionSet_->size()];
// front[i] contains the list of individuals belonging to the front i
vector<int> * front = new vector<int>[solutionSet_->size()+1];
// flagDominate is an auxiliar variable
int flagDominate;
//-> Fast non dominated sorting algorithm
for (int p = 0; p < solutionSet_->size(); p++) {
dominateMe[p] = 0;
}
// For all q individuals , calculate if p dominates q or vice versa
for (int p = 0; p < (solutionSet_->size() - 1); p++) {
for (int q = p + 1; q < solutionSet_->size(); q++) {
flagDominate =constraint_->compare(solutionSet->get(p),solutionSet->get(q));
if (flagDominate == 0) {
flagDominate =dominance_->compare(solutionSet->get(p),solutionSet->get(q));
} // if
if (flagDominate == -1) {
iDominate[p].push_back(q);
dominateMe[q]++;
} else if (flagDominate == 1) {
iDominate[q].push_back(p);
dominateMe[p]++;
} // if
} // for
} // for
for (int p = 0; p < solutionSet_->size(); p++) {
// If nobody dominates p, p belongs to the first front
if (dominateMe[p] == 0) {
front[0].push_back(p);
solutionSet_->get(p)->setRank(0);
} // if
} // for
// Obtain the rest of fronts
int i = 0;
vector<int>::iterator it1, it2;
while (front[i].size()!=0) {
i++;
for (it1=front[i-1].begin(); it1<front[i-1].end(); it1++) {
for (it2=iDominate[*it1].begin(); it2 < iDominate[*it1].end();it2++) {
dominateMe[*it2]--;
if (dominateMe[*it2]==0) {
front[i].push_back(*it2);
solutionSet->get(*it2)->setRank(i);
} // if
} // for
} // for
} // while
ranking_ = new SolutionSet*[i];
if (ranking_ == NULL) {
cout << "Fatal Error: Impossible to reserve memory in Ranking" << endl;
exit(-1);
}
//0,1,2,....,i-1 are front, then i fronts
numberOfSubfronts_ = i;
for (int j = 0; j < i; j++) {
ranking_[j] = new SolutionSet(front[j].size());
for (it1=front[j].begin(); it1<front[j].end(); it1++) {
ranking_[j]->add(new Solution(solutionSet_->get(*it1)));
} // for
} // for
delete [] dominateMe;
delete [] iDominate;
delete [] front;
} // Ranking
/**
* Destructor
*/
Ranking::~Ranking() {
for (int i = 0; i < numberOfSubfronts_; i++) {
delete ranking_[i];
}
delete [] ranking_;
delete dominance_;
delete constraint_;
} // ~Ranking
/**
* Returns a <code>SolutionSet</code> containing the solutions of a given rank.
* @param rank The rank
* @return Object representing the <code>SolutionSet</code>.
*/
SolutionSet * Ranking::getSubfront(int rank) {
return ranking_[rank];
} // getSubFront
/**
* Returns the total number of subFronts founds.
*/
int Ranking::getNumberOfSubfronts() {
return numberOfSubfronts_;
} // getNumberOfSubfronts
| [
"iloilo_has@yahoo.co.jp"
] | iloilo_has@yahoo.co.jp |
c854e0d8e46b0ff24b693ded0f0516930e8facb4 | 451ea083d1dce106ffb3ab7c78e8fa3abe61a725 | /Day 149/luckyNumber.cpp | f09ca046b75eaacd3ad5d9c2eb24f74fd77ff15e | [] | no_license | S4ND1X/365-Days-Of-Code | 52dd6a8b9d0f5c3c27b23da8914725e141d06596 | 257186d2a4d7c28a3063add55d6b72d20fccb111 | refs/heads/master | 2022-04-19T22:55:08.426317 | 2020-03-02T23:35:28 | 2020-03-02T23:35:28 | 164,487,731 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 933 | cpp | // A. Nearly Lucky Number
// time limit per test2 seconds
// memory limit per test256 megabytes
// inputstandard input
// outputstandard output
// Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
// Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.
#include <iostream>
using namespace std;int main()
{
long long n;
cin >> n;
int count = 0;
while (n != 0)
{
if (n % 10 == 4 || n % 10 == 7)
{
count += 1;
}
n /= 10;
}
if (count == 4 || count == 7)
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
return 0;
} | [
"42609763+S4ND1X@users.noreply.github.com"
] | 42609763+S4ND1X@users.noreply.github.com |
d0ed60208643893d32e6fc741e7783ea7bd873c8 | 11ade524c747aa7497724cb8996fe465790e35f4 | /src/tcpsocket.cpp | 944c2abb79840ed0599477a7aa7313968cfa6722 | [] | no_license | zstoychev/retrace-distributed | 08a3831a11395738ed2a8c975020c90eee0a7196 | 14c52bc42e80d5fc1f1cc3f033ff8ba4f7bd1b7a | refs/heads/master | 2021-01-23T03:28:31.375682 | 2012-09-09T19:16:27 | 2012-09-09T19:16:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,843 | cpp | #include "tcpsocket.h"
#include <algorithm>
Socket::Socket() {
}
Socket::Socket(const char* host, int port) {
IPaddress ip;
if(SDLNet_ResolveHost(&ip, host, port) == -1) {
throw NetworkException();
}
if ((socket = SDLNet_TCP_Open(&ip)) == 0) {
throw NetworkException();
}
set.addSocket(*this);
}
Socket::Socket(const TCPsocket& socket)
: socket(socket) {
set.addSocket(*this);
}
bool Socket::read(void* buffer, int length, Uint32 timeout, bool fineTimeoutControl) {
Uint32 start = SDL_GetTicks();
Uint32 current;
if (timeout == 0 || !fineTimeoutControl) {
int totalReadedBytes = 0;
while (totalReadedBytes < length) {
current = SDL_GetTicks();
if (timeout != 0 && ((current - start) >= timeout || !checkForActivity(timeout - (current - start)))) {
return false;
}
int readedCount;
if ((readedCount = SDLNet_TCP_Recv(socket,reinterpret_cast<char*>(buffer) + totalReadedBytes, length - totalReadedBytes)) <= 0) {
throw NetworkException();
}
totalReadedBytes += readedCount;
}
return true;
} else {
for (int i = 0; i < length; i++) {
current = SDL_GetTicks();
if ((current - start) >= timeout || !checkForActivity(timeout - (current - start))) {
return false;
}
if (SDLNet_TCP_Recv(socket, reinterpret_cast<char*>(buffer) + i, 1) <= 0) {
throw NetworkException();
}
}
return true;
}
}
void Socket::write(const void* buffer, int length) {
if (SDLNet_TCP_Send(socket, buffer, length) < length) {
throw NetworkException();
}
}
bool Socket::readLine(char* buffer, int maxSize, Uint32 timeout) {
if ((int) readLineBuffer.size() >= maxSize) {
return false;
}
Uint32 start = SDL_GetTicks();
Uint32 current;
while ((int) readLineBuffer.size() < maxSize) {
current = SDL_GetTicks();
if (timeout != 0 && ((current - start) >= timeout || !checkForActivity(timeout - (current - start)))) {
return false;
}
char ch;
if (SDLNet_TCP_Recv(socket, &ch, 1) <= 0) {
throw NetworkException();
}
if (ch == '\n') {
strcpy(buffer, readLineBuffer.c_str());
readLineBuffer.clear();
break;
} else {
readLineBuffer += ch;
}
}
return true;
}
void Socket::writeLine(const char* buffer) {
int length = strlen(buffer);
if (SDLNet_TCP_Send(socket, buffer, length) < length) {
throw NetworkException();
}
if (SDLNet_TCP_Send(socket, "\n", 1) < 1) {
throw NetworkException();
}
}
void Socket::close() {
SDLNet_TCP_Close(socket);
}
bool Socket::checkForActivity(Uint32 timeout) {
return set.hasActiveSockets(timeout);
}
TCPsocket Socket::getSDLSocket() const {
return socket;
}
std::string Socket::getSocketAddressAsText() {
IPaddress* address = SDLNet_TCP_GetPeerAddress(socket);
Uint8* octets = reinterpret_cast<Uint8*>(&address->host);
char resultString[24];
sprintf(resultString, "%d.%d.%d.%d:%d", octets[0], octets[1], octets[2], octets[3], address->port);
return resultString;
}
bool Socket::operator==(const Socket& s) {
return socket == s.socket;
}
ServerSocket::ServerSocket(int port) {
IPaddress ip;
if(SDLNet_ResolveHost(&ip, 0, port) == -1) {
throw NetworkException();
}
if ((socket = SDLNet_TCP_Open(&ip)) == 0) {
throw NetworkException();
}
}
bool ServerSocket::accept(Socket& client) {
TCPsocket clientSocket = SDLNet_TCP_Accept(socket);
client = Socket(clientSocket);
return clientSocket != 0;
}
void ServerSocket::close() {
SDLNet_TCP_Close(socket);
}
SocketSet::SocketSet()
: set(0) {
}
SocketSet::~SocketSet() {
if (set != 0) {
SDLNet_FreeSocketSet(set);
}
}
void SocketSet::addSocket(const Socket& socket) {
sockets.push_back(socket);
}
void SocketSet::removeSocket(const Socket& socket) {
std::vector<Socket>::iterator it = std::find(sockets.begin(), sockets.end(), socket);
if (it != sockets.end()) {
sockets.erase(it);
}
}
void SocketSet::prepareSet() {
if (set != 0) {
SDLNet_FreeSocketSet(set);
}
set = SDLNet_AllocSocketSet(sockets.size());
if (!set) {
throw NetworkException();
}
for (size_t i = 0; i < sockets.size(); i++) {
if (SDLNet_TCP_AddSocket(set, sockets[i].getSDLSocket()) == -1) {
throw NetworkException();
}
}
}
bool SocketSet::hasActiveSockets(Uint32 timeout) {
prepareSet();
int numberOfReadySockets = SDLNet_CheckSockets(set, timeout);
if (numberOfReadySockets == -1) {
throw NetworkException();
}
return numberOfReadySockets > 0;
}
std::vector<Socket> SocketSet::getActiveSockets(Uint32 timeout) {
prepareSet();
int numberOfReadySockets = SDLNet_CheckSockets(set, timeout);
if (numberOfReadySockets == -1) {
throw NetworkException();
}
std::vector<Socket> result;
for (size_t i = 0; i < sockets.size() && numberOfReadySockets > 0; i++) {
if (SDLNet_SocketReady(sockets[i].getSDLSocket())) {
result.push_back(sockets[i]);
numberOfReadySockets--;
}
}
return result;
}
| [
"zstoychev@gmail.com"
] | zstoychev@gmail.com |
7927e88cc7fe5b60faade7384e859253a6b0a5f0 | ef8e28a7b0648d3e09e39d037c0d313a98ef3cea | /D2/1986. 지그재그 숫자.cpp | a71032f5ba6d2ebd488ee91b40a2f1c195e467c1 | [] | no_license | RBJH/SWExpertAcademy | 07eecf6039e8178797e0a9ac3b0e9c8aa43f0c3e | 3b3cb2f71ce33e8f748831e4cb8c5b032551f846 | refs/heads/master | 2020-07-03T09:12:44.652707 | 2019-10-25T12:33:55 | 2019-10-25T12:33:55 | 201,862,798 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | cpp | #include <iostream>
using namespace std;
int T, N;
int main() {
cin >> T;
for (int t = 1; t <= T; t++) {
cin >> N;
int result = 0;
for (int n = 1; n <= N; n++) {
if (n % 2)
result += n;
else
result -= n;
}
cout << '#' << t << ' ' << result << '\n';
}
return 0;
} | [
"46277703+RBJH@users.noreply.github.com"
] | 46277703+RBJH@users.noreply.github.com |
a71829e99cdacce8c20c5f5e91d5685160aee850 | 45e0fbd9a9dbcdd4fbe6aaa2fdb2aed296f81e33 | /FindSecret/Classes/Native/mscorlib_System_Collections_Generic_Dictionary_2_Va767236274.h | dc48fe21d8f3e776749b4e8df3563bab2d977b12 | [
"MIT"
] | permissive | GodIsWord/NewFindSecret | d4a5d2d810ee1f9d6b3bc91168895cc808bac817 | 4f98f316d29936380f9665d6a6d89962d9ee5478 | refs/heads/master | 2020-03-24T09:54:50.239014 | 2018-10-27T05:22:11 | 2018-10-27T05:22:11 | 142,641,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,425 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Object3080106164.h"
// System.Collections.Generic.Dictionary`2<System.UInt32,System.Collections.Generic.List`1<ZGGame.AssetLoadData>>
struct Dictionary_2_t3346159252;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2/ValueCollection<System.UInt32,System.Collections.Generic.List`1<ZGGame.AssetLoadData>>
struct ValueCollection_t767236274 : public Il2CppObject
{
public:
// System.Collections.Generic.Dictionary`2<TKey,TValue> System.Collections.Generic.Dictionary`2/ValueCollection::dictionary
Dictionary_2_t3346159252 * ___dictionary_0;
public:
inline static int32_t get_offset_of_dictionary_0() { return static_cast<int32_t>(offsetof(ValueCollection_t767236274, ___dictionary_0)); }
inline Dictionary_2_t3346159252 * get_dictionary_0() const { return ___dictionary_0; }
inline Dictionary_2_t3346159252 ** get_address_of_dictionary_0() { return &___dictionary_0; }
inline void set_dictionary_0(Dictionary_2_t3346159252 * value)
{
___dictionary_0 = value;
Il2CppCodeGenWriteBarrier(&___dictionary_0, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"zhangyide@9fbank.cc"
] | zhangyide@9fbank.cc |
96a325a82ab4e473bea1274513ba378b29d926f3 | cff8e3ed690c9fb7ef3cf5b982d79712e5c4bd86 | /ipc/ipc_channel_posix.cc | ac9de554657771704fe9d7a58bbad53c5587522d | [] | no_license | sinoory/chromebase | 33d1de7224b54ec3ba854a3a1532239bbea02eb0 | 59b86d44c9a3b83fe0330f120245ae853de9ea6e | refs/heads/master | 2021-01-10T03:20:20.101937 | 2015-12-18T08:44:28 | 2015-12-18T08:44:28 | 48,563,156 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 34,852 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ipc/ipc_channel_posix.h"
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#if defined(OS_OPENBSD)
#include <sys/uio.h>
#endif
#include <map>
#include <string>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/posix/eintr_wrapper.h"
#include "base/posix/global_descriptors.h"
#include "base/process/process_handle.h"
#include "base/rand_util.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/synchronization/lock.h"
#include "ipc/file_descriptor_set_posix.h"
#include "ipc/ipc_descriptors.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_logging.h"
#include "ipc/ipc_message_utils.h"
#include "ipc/ipc_switches.h"
#include "ipc/unix_domain_socket_util.h"
namespace IPC {
// IPC channels on Windows use named pipes (CreateNamedPipe()) with
// channel ids as the pipe names. Channels on POSIX use sockets as
// pipes These don't quite line up.
//
// When creating a child subprocess we use a socket pair and the parent side of
// the fork arranges it such that the initial control channel ends up on the
// magic file descriptor kPrimaryIPCChannel in the child. Future
// connections (file descriptors) can then be passed via that
// connection via sendmsg().
//
// A POSIX IPC channel can also be set up as a server for a bound UNIX domain
// socket, and will handle multiple connect and disconnect sequences. Currently
// it is limited to one connection at a time.
//------------------------------------------------------------------------------
namespace {
// The PipeMap class works around this quirk related to unit tests:
//
// When running as a server, we install the client socket in a
// specific file descriptor number (@kPrimaryIPCChannel). However, we
// also have to support the case where we are running unittests in the
// same process. (We do not support forking without execing.)
//
// Case 1: normal running
// The IPC server object will install a mapping in PipeMap from the
// name which it was given to the client pipe. When forking the client, the
// GetClientFileDescriptorMapping will ensure that the socket is installed in
// the magic slot (@kPrimaryIPCChannel). The client will search for the
// mapping, but it won't find any since we are in a new process. Thus the
// magic fd number is returned. Once the client connects, the server will
// close its copy of the client socket and remove the mapping.
//
// Case 2: unittests - client and server in the same process
// The IPC server will install a mapping as before. The client will search
// for a mapping and find out. It duplicates the file descriptor and
// connects. Once the client connects, the server will close the original
// copy of the client socket and remove the mapping. Thus, when the client
// object closes, it will close the only remaining copy of the client socket
// in the fd table and the server will see EOF on its side.
//
// TODO(port): a client process cannot connect to multiple IPC channels with
// this scheme.
class PipeMap {
public:
static PipeMap* GetInstance() {
return Singleton<PipeMap>::get();
}
~PipeMap() {
// Shouldn't have left over pipes.
DCHECK(map_.empty());
}
// Lookup a given channel id. Return -1 if not found.
int Lookup(const std::string& channel_id) {
base::AutoLock locked(lock_);
ChannelToFDMap::const_iterator i = map_.find(channel_id);
if (i == map_.end())
return -1;
return i->second;
}
// Remove the mapping for the given channel id. No error is signaled if the
// channel_id doesn't exist
void Remove(const std::string& channel_id) {
base::AutoLock locked(lock_);
map_.erase(channel_id);
}
// Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
// mapping if one already exists for the given channel_id
void Insert(const std::string& channel_id, int fd) {
base::AutoLock locked(lock_);
DCHECK_NE(-1, fd);
ChannelToFDMap::const_iterator i = map_.find(channel_id);
CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
<< "for '" << channel_id << "' while first "
<< "(fd " << i->second << ") still exists";
map_[channel_id] = fd;
}
private:
base::Lock lock_;
typedef std::map<std::string, int> ChannelToFDMap;
ChannelToFDMap map_;
friend struct DefaultSingletonTraits<PipeMap>;
#if defined(OS_ANDROID)
friend void ::IPC::Channel::NotifyProcessForkedForTesting();
#endif
};
//------------------------------------------------------------------------------
bool SocketWriteErrorIsRecoverable() {
#if defined(OS_MACOSX)
// On OS X if sendmsg() is trying to send fds between processes and there
// isn't enough room in the output buffer to send the fd structure over
// atomically then EMSGSIZE is returned.
//
// EMSGSIZE presents a problem since the system APIs can only call us when
// there's room in the socket buffer and not when there is "enough" room.
//
// The current behavior is to return to the event loop when EMSGSIZE is
// received and hopefull service another FD. This is however still
// technically a busy wait since the event loop will call us right back until
// the receiver has read enough data to allow passing the FD over atomically.
return errno == EAGAIN || errno == EMSGSIZE;
#else
return errno == EAGAIN;
#endif // OS_MACOSX
}
} // namespace
#if defined(OS_ANDROID)
// When we fork for simple tests on Android, we can't 'exec', so we need to
// reset these entries manually to get the expected testing behavior.
void Channel::NotifyProcessForkedForTesting() {
PipeMap::GetInstance()->map_.clear();
}
#endif
//------------------------------------------------------------------------------
#if defined(OS_LINUX)
int ChannelPosix::global_pid_ = 0;
#endif // OS_LINUX
ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
Mode mode, Listener* listener)
: ChannelReader(listener),
mode_(mode),
peer_pid_(base::kNullProcessId),
is_blocked_on_write_(false),
waiting_connect_(true),
message_send_bytes_written_(0),
server_listen_pipe_(-1),
pipe_(-1),
client_pipe_(-1),
#if defined(IPC_USES_READWRITE)
fd_pipe_(-1),
remote_fd_pipe_(-1),
#endif // IPC_USES_READWRITE
pipe_name_(channel_handle.name),
must_unlink_(false) {
memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
if (!CreatePipe(channel_handle)) {
// The pipe may have been closed already.
const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
<< "\" in " << modestr << " mode";
}
}
ChannelPosix::~ChannelPosix() {
Close();
}
bool SocketPair(int* fd1, int* fd2) {
int pipe_fds[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
PLOG(ERROR) << "socketpair()";
return false;
}
// Set both ends to be non-blocking.
if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
PLOG(ERROR) << "fcntl(O_NONBLOCK)";
if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
PLOG(ERROR) << "close";
if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
PLOG(ERROR) << "close";
return false;
}
*fd1 = pipe_fds[0];
*fd2 = pipe_fds[1];
return true;
}
bool ChannelPosix::CreatePipe(
const IPC::ChannelHandle& channel_handle) {
DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
// Four possible cases:
// 1) It's a channel wrapping a pipe that is given to us.
// 2) It's for a named channel, so we create it.
// 3) It's for a client that we implement ourself. This is used
// in single-process unittesting.
// 4) It's the initial IPC channel:
// 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
// 4b) Server side: create the pipe.
int local_pipe = -1;
if (channel_handle.socket.fd != -1) {
// Case 1 from comment above.
local_pipe = channel_handle.socket.fd;
#if defined(IPC_USES_READWRITE)
// Test the socket passed into us to make sure it is nonblocking.
// We don't want to call read/write on a blocking socket.
int value = fcntl(local_pipe, F_GETFL);
if (value == -1) {
PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
return false;
}
if (!(value & O_NONBLOCK)) {
LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
return false;
}
#endif // IPC_USES_READWRITE
} else if (mode_ & MODE_NAMED_FLAG) {
// Case 2 from comment above.
if (mode_ & MODE_SERVER_FLAG) {
if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
&local_pipe)) {
return false;
}
must_unlink_ = true;
} else if (mode_ & MODE_CLIENT_FLAG) {
if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
&local_pipe)) {
return false;
}
} else {
LOG(ERROR) << "Bad mode: " << mode_;
return false;
}
} else {
local_pipe = PipeMap::GetInstance()->Lookup(pipe_name_);
if (mode_ & MODE_CLIENT_FLAG) {
if (local_pipe != -1) {
// Case 3 from comment above.
// We only allow one connection.
local_pipe = HANDLE_EINTR(dup(local_pipe));
PipeMap::GetInstance()->Remove(pipe_name_);
} else {
// Case 4a from comment above.
// Guard against inappropriate reuse of the initial IPC channel. If
// an IPC channel closes and someone attempts to reuse it by name, the
// initial channel must not be recycled here. http://crbug.com/26754.
static bool used_initial_channel = false;
if (used_initial_channel) {
LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
<< pipe_name_;
return false;
}
used_initial_channel = true;
local_pipe =
base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
}
} else if (mode_ & MODE_SERVER_FLAG) {
// Case 4b from comment above.
if (local_pipe != -1) {
LOG(ERROR) << "Server already exists for " << pipe_name_;
return false;
}
base::AutoLock lock(client_pipe_lock_);
if (!SocketPair(&local_pipe, &client_pipe_))
return false;
PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
} else {
LOG(ERROR) << "Bad mode: " << mode_;
return false;
}
}
#if defined(IPC_USES_READWRITE)
// Create a dedicated socketpair() for exchanging file descriptors.
// See comments for IPC_USES_READWRITE for details.
if (mode_ & MODE_CLIENT_FLAG) {
if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
return false;
}
}
#endif // IPC_USES_READWRITE
if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
server_listen_pipe_ = local_pipe;
local_pipe = -1;
}
pipe_ = local_pipe;
return true;
}
bool ChannelPosix::Connect() {
if (server_listen_pipe_ == -1 && pipe_ == -1) {
DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
return false;
}
bool did_connect = true;
if (server_listen_pipe_ != -1) {
// Watch the pipe for connections, and turn any connections into
// active sockets.
base::MessageLoopForIO::current()->WatchFileDescriptor(
server_listen_pipe_,
true,
base::MessageLoopForIO::WATCH_READ,
&server_listen_connection_watcher_,
this);
} else {
did_connect = AcceptConnection();
}
return did_connect;
}
void ChannelPosix::CloseFileDescriptors(Message* msg) {
#if defined(OS_MACOSX)
// There is a bug on OSX which makes it dangerous to close
// a file descriptor while it is in transit. So instead we
// store the file descriptor in a set and send a message to
// the recipient, which is queued AFTER the message that
// sent the FD. The recipient will reply to the message,
// letting us know that it is now safe to close the file
// descriptor. For more information, see:
// http://crbug.com/298276
std::vector<int> to_close;
msg->file_descriptor_set()->ReleaseFDsToClose(&to_close);
for (size_t i = 0; i < to_close.size(); i++) {
fds_to_close_.insert(to_close[i]);
QueueCloseFDMessage(to_close[i], 2);
}
#else
msg->file_descriptor_set()->CommitAll();
#endif
}
bool ChannelPosix::ProcessOutgoingMessages() {
DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
// no connection?
if (output_queue_.empty())
return true;
if (pipe_ == -1)
return false;
// Write out all the messages we can till the write blocks or there are no
// more outgoing messages.
while (!output_queue_.empty()) {
Message* msg = output_queue_.front();
size_t amt_to_write = msg->size() - message_send_bytes_written_;
DCHECK_NE(0U, amt_to_write);
const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
message_send_bytes_written_;
struct msghdr msgh = {0};
struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
msgh.msg_iov = &iov;
msgh.msg_iovlen = 1;
char buf[CMSG_SPACE(
sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
ssize_t bytes_written = 1;
int fd_written = -1;
if (message_send_bytes_written_ == 0 &&
!msg->file_descriptor_set()->empty()) {
// This is the first chunk of a message which has descriptors to send
struct cmsghdr *cmsg;
const unsigned num_fds = msg->file_descriptor_set()->size();
DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
" IPC. Aborting to maintain sandbox isolation.";
// If you have hit this then something tried to send a file descriptor
// to a directory over an IPC channel. Since IPC channels span
// sandboxes this is very bad: the receiving process can use openat
// with ".." elements in the path in order to reach the real
// filesystem.
}
msgh.msg_control = buf;
msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
cmsg = CMSG_FIRSTHDR(&msgh);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
msg->file_descriptor_set()->GetDescriptors(
reinterpret_cast<int*>(CMSG_DATA(cmsg)));
msgh.msg_controllen = cmsg->cmsg_len;
// DCHECK_LE above already checks that
// num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
msg->header()->num_fds = static_cast<uint16>(num_fds);
#if defined(IPC_USES_READWRITE)
if (!IsHelloMessage(*msg)) {
// Only the Hello message sends the file descriptor with the message.
// Subsequently, we can send file descriptors on the dedicated
// fd_pipe_ which makes Seccomp sandbox operation more efficient.
struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
msgh.msg_iov = &fd_pipe_iov;
fd_written = fd_pipe_;
bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
msgh.msg_iov = &iov;
msgh.msg_controllen = 0;
if (bytes_written > 0) {
CloseFileDescriptors(msg);
}
}
#endif // IPC_USES_READWRITE
}
if (bytes_written == 1) {
fd_written = pipe_;
#if defined(IPC_USES_READWRITE)
if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
}
if (!msgh.msg_controllen) {
bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
} else
#endif // IPC_USES_READWRITE
{
bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
}
}
if (bytes_written > 0)
CloseFileDescriptors(msg);
if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
// We can't close the pipe here, because calling OnChannelError
// may destroy this object, and that would be bad if we are
// called from Send(). Instead, we return false and hope the
// caller will close the pipe. If they do not, the pipe will
// still be closed next time OnFileCanReadWithoutBlocking is
// called.
#if defined(OS_MACOSX)
// On OSX writing to a pipe with no listener returns EPERM.
if (errno == EPERM) {
return false;
}
#endif // OS_MACOSX
if (errno == EPIPE) {
return false;
}
PLOG(ERROR) << "pipe error on "
<< fd_written
<< " Currently writing message of size: "
<< msg->size();
return false;
}
if (static_cast<size_t>(bytes_written) != amt_to_write) {
if (bytes_written > 0) {
// If write() fails with EAGAIN then bytes_written will be -1.
message_send_bytes_written_ += bytes_written;
}
// Tell libevent to call us back once things are unblocked.
is_blocked_on_write_ = true;
base::MessageLoopForIO::current()->WatchFileDescriptor(
pipe_,
false, // One shot
base::MessageLoopForIO::WATCH_WRITE,
&write_watcher_,
this);
return true;
} else {
message_send_bytes_written_ = 0;
// Message sent OK!
DVLOG(2) << "sent message @" << msg << " on channel @" << this
<< " with type " << msg->type() << " on fd " << pipe_;
delete output_queue_.front();
output_queue_.pop();
}
}
return true;
}
bool ChannelPosix::Send(Message* message) {
DVLOG(2) << "sending message @" << message << " on channel @" << this
<< " with type " << message->type()
<< " (" << output_queue_.size() << " in queue)";
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging::GetInstance()->OnSendMessage(message, "");
#endif // IPC_MESSAGE_LOG_ENABLED
message->TraceMessageBegin();
output_queue_.push(message);
if (!is_blocked_on_write_ && !waiting_connect_) {
return ProcessOutgoingMessages();
}
return true;
}
int ChannelPosix::GetClientFileDescriptor() const {
base::AutoLock lock(client_pipe_lock_);
return client_pipe_;
}
int ChannelPosix::TakeClientFileDescriptor() {
base::AutoLock lock(client_pipe_lock_);
int fd = client_pipe_;
if (client_pipe_ != -1) {
PipeMap::GetInstance()->Remove(pipe_name_);
client_pipe_ = -1;
}
return fd;
}
void ChannelPosix::CloseClientFileDescriptor() {
base::AutoLock lock(client_pipe_lock_);
if (client_pipe_ != -1) {
PipeMap::GetInstance()->Remove(pipe_name_);
if (IGNORE_EINTR(close(client_pipe_)) < 0)
PLOG(ERROR) << "close " << pipe_name_;
client_pipe_ = -1;
}
}
bool ChannelPosix::AcceptsConnections() const {
return server_listen_pipe_ != -1;
}
bool ChannelPosix::HasAcceptedConnection() const {
return AcceptsConnections() && pipe_ != -1;
}
bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
return IPC::GetPeerEuid(pipe_, peer_euid);
}
void ChannelPosix::ResetToAcceptingConnectionState() {
// Unregister libevent for the unix domain socket and close it.
read_watcher_.StopWatchingFileDescriptor();
write_watcher_.StopWatchingFileDescriptor();
if (pipe_ != -1) {
if (IGNORE_EINTR(close(pipe_)) < 0)
PLOG(ERROR) << "close pipe_ " << pipe_name_;
pipe_ = -1;
}
#if defined(IPC_USES_READWRITE)
if (fd_pipe_ != -1) {
if (IGNORE_EINTR(close(fd_pipe_)) < 0)
PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
fd_pipe_ = -1;
}
if (remote_fd_pipe_ != -1) {
if (IGNORE_EINTR(close(remote_fd_pipe_)) < 0)
PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
remote_fd_pipe_ = -1;
}
#endif // IPC_USES_READWRITE
while (!output_queue_.empty()) {
Message* m = output_queue_.front();
output_queue_.pop();
delete m;
}
// Close any outstanding, received file descriptors.
ClearInputFDs();
#if defined(OS_MACOSX)
// Clear any outstanding, sent file descriptors.
for (std::set<int>::iterator i = fds_to_close_.begin();
i != fds_to_close_.end();
++i) {
if (IGNORE_EINTR(close(*i)) < 0)
PLOG(ERROR) << "close";
}
fds_to_close_.clear();
#endif
}
// static
bool ChannelPosix::IsNamedServerInitialized(
const std::string& channel_id) {
return base::PathExists(base::FilePath(channel_id));
}
#if defined(OS_LINUX)
// static
void ChannelPosix::SetGlobalPid(int pid) {
global_pid_ = pid;
}
#endif // OS_LINUX
// Called by libevent when we can read from the pipe without blocking.
void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
if (fd == server_listen_pipe_) {
int new_pipe = 0;
if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe) ||
new_pipe < 0) {
Close();
listener()->OnChannelListenError();
}
if (pipe_ != -1) {
// We already have a connection. We only handle one at a time.
// close our new descriptor.
if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
DPLOG(ERROR) << "shutdown " << pipe_name_;
if (IGNORE_EINTR(close(new_pipe)) < 0)
DPLOG(ERROR) << "close " << pipe_name_;
listener()->OnChannelDenied();
return;
}
pipe_ = new_pipe;
if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
// Verify that the IPC channel peer is running as the same user.
uid_t client_euid;
if (!GetPeerEuid(&client_euid)) {
DLOG(ERROR) << "Unable to query client euid";
ResetToAcceptingConnectionState();
return;
}
if (client_euid != geteuid()) {
DLOG(WARNING) << "Client euid is not authorised";
ResetToAcceptingConnectionState();
return;
}
}
if (!AcceptConnection()) {
NOTREACHED() << "AcceptConnection should not fail on server";
}
waiting_connect_ = false;
} else if (fd == pipe_) {
if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
waiting_connect_ = false;
}
if (!ProcessIncomingMessages()) {
// ClosePipeOnError may delete this object, so we mustn't call
// ProcessOutgoingMessages.
ClosePipeOnError();
return;
}
} else {
NOTREACHED() << "Unknown pipe " << fd;
}
// If we're a server and handshaking, then we want to make sure that we
// only send our handshake message after we've processed the client's.
// This gives us a chance to kill the client if the incoming handshake
// is invalid. This also flushes any closefd messages.
if (!is_blocked_on_write_) {
if (!ProcessOutgoingMessages()) {
ClosePipeOnError();
}
}
}
// Called by libevent when we can write to the pipe without blocking.
void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
DCHECK_EQ(pipe_, fd);
is_blocked_on_write_ = false;
if (!ProcessOutgoingMessages()) {
ClosePipeOnError();
}
}
bool ChannelPosix::AcceptConnection() {
base::MessageLoopForIO::current()->WatchFileDescriptor(
pipe_, true, base::MessageLoopForIO::WATCH_READ, &read_watcher_, this);
QueueHelloMessage();
if (mode_ & MODE_CLIENT_FLAG) {
// If we are a client we want to send a hello message out immediately.
// In server mode we will send a hello message when we receive one from a
// client.
waiting_connect_ = false;
return ProcessOutgoingMessages();
} else if (mode_ & MODE_SERVER_FLAG) {
waiting_connect_ = true;
return true;
} else {
NOTREACHED();
return false;
}
}
void ChannelPosix::ClosePipeOnError() {
if (HasAcceptedConnection()) {
ResetToAcceptingConnectionState();
listener()->OnChannelError();
} else {
Close();
if (AcceptsConnections()) {
listener()->OnChannelListenError();
} else {
listener()->OnChannelError();
}
}
}
int ChannelPosix::GetHelloMessageProcId() const {
int pid = base::GetCurrentProcId();
#if defined(OS_LINUX)
// Our process may be in a sandbox with a separate PID namespace.
if (global_pid_) {
pid = global_pid_;
}
#endif
return pid;
}
void ChannelPosix::QueueHelloMessage() {
// Create the Hello message
scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
HELLO_MESSAGE_TYPE,
IPC::Message::PRIORITY_NORMAL));
if (!msg->WriteInt(GetHelloMessageProcId())) {
NOTREACHED() << "Unable to pickle hello message proc id";
}
#if defined(IPC_USES_READWRITE)
scoped_ptr<Message> hello;
if (remote_fd_pipe_ != -1) {
if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
false))) {
NOTREACHED() << "Unable to pickle hello message file descriptors";
}
DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
}
#endif // IPC_USES_READWRITE
output_queue_.push(msg.release());
}
ChannelPosix::ReadState ChannelPosix::ReadData(
char* buffer,
int buffer_len,
int* bytes_read) {
if (pipe_ == -1)
return READ_FAILED;
struct msghdr msg = {0};
struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = input_cmsg_buf_;
// recvmsg() returns 0 if the connection has closed or EAGAIN if no data
// is waiting on the pipe.
#if defined(IPC_USES_READWRITE)
if (fd_pipe_ >= 0) {
*bytes_read = HANDLE_EINTR(read(pipe_, buffer, buffer_len));
msg.msg_controllen = 0;
} else
#endif // IPC_USES_READWRITE
{
msg.msg_controllen = sizeof(input_cmsg_buf_);
*bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
}
if (*bytes_read < 0) {
if (errno == EAGAIN) {
return READ_PENDING;
#if defined(OS_MACOSX)
} else if (errno == EPERM) {
// On OSX, reading from a pipe with no listener returns EPERM
// treat this as a special case to prevent spurious error messages
// to the console.
return READ_FAILED;
#endif // OS_MACOSX
} else if (errno == ECONNRESET || errno == EPIPE) {
return READ_FAILED;
} else {
PLOG(ERROR) << "pipe error (" << pipe_ << ")";
return READ_FAILED;
}
} else if (*bytes_read == 0) {
// The pipe has closed...
return READ_FAILED;
}
DCHECK(*bytes_read);
CloseClientFileDescriptor();
// Read any file descriptors from the message.
if (!ExtractFileDescriptorsFromMsghdr(&msg))
return READ_FAILED;
return READ_SUCCEEDED;
}
#if defined(IPC_USES_READWRITE)
bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
char dummy;
struct iovec fd_pipe_iov = { &dummy, 1 };
struct msghdr msg = { 0 };
msg.msg_iov = &fd_pipe_iov;
msg.msg_iovlen = 1;
msg.msg_control = input_cmsg_buf_;
msg.msg_controllen = sizeof(input_cmsg_buf_);
ssize_t bytes_received = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
if (bytes_received != 1)
return true; // No message waiting.
if (!ExtractFileDescriptorsFromMsghdr(&msg))
return false;
return true;
}
#endif
// On Posix, we need to fix up the file descriptors before the input message
// is dispatched.
//
// This will read from the input_fds_ (READWRITE mode only) and read more
// handles from the FD pipe if necessary.
bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
uint16 header_fds = msg->header()->num_fds;
if (!header_fds)
return true; // Nothing to do.
// The message has file descriptors.
const char* error = NULL;
if (header_fds > input_fds_.size()) {
// The message has been completely received, but we didn't get
// enough file descriptors.
#if defined(IPC_USES_READWRITE)
if (!ReadFileDescriptorsFromFDPipe())
return false;
if (header_fds > input_fds_.size())
#endif // IPC_USES_READWRITE
error = "Message needs unreceived descriptors";
}
if (header_fds > FileDescriptorSet::kMaxDescriptorsPerMessage)
error = "Message requires an excessive number of descriptors";
if (error) {
LOG(WARNING) << error
<< " channel:" << this
<< " message-type:" << msg->type()
<< " header()->num_fds:" << header_fds;
// Abort the connection.
ClearInputFDs();
return false;
}
// The shenaniganery below with &foo.front() requires input_fds_ to have
// contiguous underlying storage (such as a simple array or a std::vector).
// This is why the header warns not to make input_fds_ a deque<>.
msg->file_descriptor_set()->SetDescriptors(&input_fds_.front(),
header_fds);
input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
return true;
}
bool ChannelPosix::DidEmptyInputBuffers() {
// When the input data buffer is empty, the fds should be too. If this is
// not the case, we probably have a rogue renderer which is trying to fill
// our descriptor table.
return input_fds_.empty();
}
bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
// Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
// return an invalid non-NULL pointer in the case that controllen == 0.
if (msg->msg_controllen == 0)
return true;
for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
cmsg;
cmsg = CMSG_NXTHDR(msg, cmsg)) {
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
DCHECK_EQ(0U, payload_len % sizeof(int));
const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
unsigned num_file_descriptors = payload_len / 4;
input_fds_.insert(input_fds_.end(),
file_descriptors,
file_descriptors + num_file_descriptors);
// Check this after adding the FDs so we don't leak them.
if (msg->msg_flags & MSG_CTRUNC) {
ClearInputFDs();
return false;
}
return true;
}
}
// No file descriptors found, but that's OK.
return true;
}
void ChannelPosix::ClearInputFDs() {
for (size_t i = 0; i < input_fds_.size(); ++i) {
if (IGNORE_EINTR(close(input_fds_[i])) < 0)
PLOG(ERROR) << "close ";
}
input_fds_.clear();
}
void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
switch (hops) {
case 1:
case 2: {
// Create the message
scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
CLOSE_FD_MESSAGE_TYPE,
IPC::Message::PRIORITY_NORMAL));
if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
NOTREACHED() << "Unable to pickle close fd.";
}
// Send(msg.release());
output_queue_.push(msg.release());
break;
}
default:
NOTREACHED();
break;
}
}
void ChannelPosix::HandleInternalMessage(const Message& msg) {
// The Hello message contains only the process id.
PickleIterator iter(msg);
switch (msg.type()) {
default:
NOTREACHED();
break;
case Channel::HELLO_MESSAGE_TYPE:
int pid;
if (!msg.ReadInt(&iter, &pid))
NOTREACHED();
#if defined(IPC_USES_READWRITE)
if (mode_ & MODE_SERVER_FLAG) {
// With IPC_USES_READWRITE, the Hello message from the client to the
// server also contains the fd_pipe_, which will be used for all
// subsequent file descriptor passing.
DCHECK_EQ(msg.file_descriptor_set()->size(), 1U);
base::FileDescriptor descriptor;
if (!msg.ReadFileDescriptor(&iter, &descriptor)) {
NOTREACHED();
}
fd_pipe_ = descriptor.fd;
CHECK(descriptor.auto_close);
}
#endif // IPC_USES_READWRITE
peer_pid_ = pid;
listener()->OnChannelConnected(pid);
break;
#if defined(OS_MACOSX)
case Channel::CLOSE_FD_MESSAGE_TYPE:
int fd, hops;
if (!msg.ReadInt(&iter, &hops))
NOTREACHED();
if (!msg.ReadInt(&iter, &fd))
NOTREACHED();
if (hops == 0) {
if (fds_to_close_.erase(fd) > 0) {
if (IGNORE_EINTR(close(fd)) < 0)
PLOG(ERROR) << "close";
} else {
NOTREACHED();
}
} else {
QueueCloseFDMessage(fd, hops);
}
break;
#endif
}
}
void ChannelPosix::Close() {
// Close can be called multiple time, so we need to make sure we're
// idempotent.
ResetToAcceptingConnectionState();
if (must_unlink_) {
unlink(pipe_name_.c_str());
must_unlink_ = false;
}
if (server_listen_pipe_ != -1) {
if (IGNORE_EINTR(close(server_listen_pipe_)) < 0)
DPLOG(ERROR) << "close " << server_listen_pipe_;
server_listen_pipe_ = -1;
// Unregister libevent for the listening socket and close it.
server_listen_connection_watcher_.StopWatchingFileDescriptor();
}
CloseClientFileDescriptor();
}
base::ProcessId ChannelPosix::GetPeerPID() const {
return peer_pid_;
}
base::ProcessId ChannelPosix::GetSelfPID() const {
return GetHelloMessageProcId();
}
ChannelHandle ChannelPosix::TakePipeHandle() {
ChannelHandle handle = ChannelHandle(pipe_name_,
base::FileDescriptor(pipe_, false));
pipe_ = -1;
return handle;
}
//------------------------------------------------------------------------------
// Channel's methods
// static
scoped_ptr<Channel> Channel::Create(
const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
return make_scoped_ptr(new ChannelPosix(
channel_handle, mode, listener)).PassAs<Channel>();
}
// static
std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
// A random name is sufficient validation on posix systems, so we don't need
// an additional shared secret.
std::string id = prefix;
if (!id.empty())
id.append(".");
return id.append(GenerateUniqueRandomChannelID());
}
bool Channel::IsNamedServerInitialized(
const std::string& channel_id) {
return ChannelPosix::IsNamedServerInitialized(channel_id);
}
#if defined(OS_LINUX)
// static
void Channel::SetGlobalPid(int pid) {
ChannelPosix::SetGlobalPid(pid);
}
#endif // OS_LINUX
} // namespace IPC
| [
"wangc_os@sari.ac.cn"
] | wangc_os@sari.ac.cn |
272e8a415faa1f7e304e8651891c7873ab0d8eb2 | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /Codes/AC/3844.cpp | 19560efdf9da0ae5a1de8b4b4ac926253713fe4c | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 924 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i = (a); i < (b); i++)
#define iter(it,c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end();++it)
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef long long ll;
const int INF = ~(1<<31);
const double pi = acos(-1);
int main() {
cin.sync_with_stdio(false);
ll C[3];
memset(C,0,sizeof(C));
string s;
cin >> s;
rep(i,0,s.size()) {
if(s[i] == 'B') C[0]++;
else if(s[i] == 'S') C[1]++;
else C[2]++;
}
ll G[3],R[3];
cin >> G[0] >> G[1] >> G[2];
cin >> R[0] >> R[1] >> R[2];
ll r;
cin >> r;
ll lo = 0, hi = 10000000000000LL;
while(lo <= hi) {
ll mid = (lo+hi)/2;
ll N[3];
ll money = r;
rep(i,0,3) N[i] = C[i]*mid;
rep(i,0,3) N[i] = max(N[i]-G[i],0LL);
rep(i,0,3) money -= N[i]*R[i];
if(money < 0) {
hi = mid-1;
} else lo = mid+1;
}
cout << (lo+hi)/2 << endl;
return 0;
}
| [
"harshitagar1907@gmail.com"
] | harshitagar1907@gmail.com |
77b4cbf73a8b066b37f07c7b41aaf5e83001f702 | 71b88bd1e34823ca9dcc29ae97db8eb852d2130d | /LAFORE_CH_11_EX3_CLASS_DiSTANCE_RELOAD_OPERATIONS/main.cpp | 414a81325d5b67c98991603689239cdb92759738 | [] | no_license | KirillBy/Lafore_cpp_solutions | bd57399088c67a35d3b7835e1f205bc5d03101d3 | 9fc9ac9971eacee4a7a63f9ed20d7f857059f3c2 | refs/heads/master | 2020-09-21T14:09:13.348077 | 2019-11-29T13:13:51 | 2019-11-29T13:13:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,785 | cpp | #include <iostream>
///////////////////////////////////////////////////////////
class Distance //Класс английских расстояний
{
private:
int feet;
double inches;
public:
Distance() //конструктор без аргументов
{
feet = 0; inches = 0.0;
}
Distance(double fltfeet) //конструктор (1 арг.)
{ //Переводит double в Distance
feet = int(fltfeet); //feet – целая часть
inches = 12 * (fltfeet - feet); //слева - дюймы
}
Distance(int ft, double in) //конструктор (2 арг.)
{
feet = ft; inches = in;
}
void showdist() //Вывести длину
{
std::cout << feet << "\'-" << inches << '\"';
}
friend Distance operator + (Distance, Distance); //дружественный
friend Distance operator * (Distance, Distance); //дружественый
};
//---------------------------------------------------------
Distance operator * (Distance d1, Distance d2) // d1 * d2
{
int f = d1.feet * d2.feet; //* футы
double i = static_cast<int>(d1.inches * d2.inches)*10; //* дюймы
if (i >= 12.0) //если больше 12 дюймов,
{
i -= 12.0; f++;//уменьшить на 12 дюймов, //прибавить 1 фут
}
return Distance(f, i);
}
Distance operator + (Distance d1, Distance d2) // d1 + d2
{
int f = d1.feet + d2.feet; //+ футы
double i =d1.inches + d2.inches; //+ дюймы
if (i >= 12.0) //если больше 12 дюймов,
{
i -= 12.0; f++;//уменьшить на 12 дюймов,
//прибавить 1 фут
}
return Distance(f, i); //Новая длина с суммой
}
//---------------------------------------------------------
int main()
{
Distance d1 = 2.5; //конструктор переводит
Distance d2 = 1.25; //double-feet в Distance
Distance d3;
std::cout << "\nd1 = "; d1.showdist();
std::cout << "\nd2 = "; d2.showdist();
d3 = d1 + 10.0; //distance + double: OK
std::cout << "\nd3 = "; d3.showdist();
d3 = 10.0 + d1; //double + Distance: OK
std::cout << "\nd3 = "; d3.showdist();
std::cout << std::endl;
Distance d4 = 1.5;
Distance d5 = 2.5;
std::cout << "\nd4 = "; d4.showdist();
std::cout << "\nd5 = "; d5.showdist();
Distance d6 = 10.1 * d1; // double * Distance
std::cout << "\nd6 = "; d6.showdist();
d6 = d2 * 10.2; //Distance * double
std::cout << "\nd6 = "; d6.showdist();
return 0;
}
| [
"balanovichks@gmail.com"
] | balanovichks@gmail.com |
7a6e35840f3dabfa668d8b87fafea1c248d8647f | 0e733c19c693715c5757a1dd5f39091071d0ab58 | /libvt/test/unittest-pcg.cpp | ce6ede3dc51466de7fa957065030fa630c068546 | [] | no_license | ZhouYzzz/vt | 309f07bd31fa517e359d29ba20df139a0454e117 | 23b15b20df33b9377a60d356d8b71873c1b9e79a | refs/heads/master | 2021-07-11T10:31:23.054872 | 2017-10-10T02:37:26 | 2017-10-10T02:37:26 | 104,697,422 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 936 | cpp | //
// unittest-pcg.cpp
// vt
//
// Created by Yizhuang Zhou on 09/10/2017.
// Copyright © 2017 Yizhuang Zhou. All rights reserved.
//
#include <stdio.h>
#include "gtest/gtest.h"
#include "pcg.hpp"
TEST(PCG, 0) {
Mat A = Mat(2, 2, CV_32F);
A.at<float>(0,0) = 4;
A.at<float>(0,1) = 1;
A.at<float>(1,0) = 1;
A.at<float>(1,1) = 3;
Mat x = Mat(2,1, CV_32F);
x.at<float>(0,0) = 2;
x.at<float>(1,0) = 1;
Mat b = Mat(2,1, CV_32F);
b.at<float>(0,0) = 1;
b.at<float>(1,0) = 2;
Mat M = Mat(2,1, CV_32F);
M.at<float>(0,0) = 1;
M.at<float>(1,0) = 1;
pcg(A, x, b, M, 20);
LOG(INFO) << x;
LOG(INFO) << A * x;
// struct lhs {
// Mat A_;
// Mat operator()(Mat &x) { return A_ * x; }
// } Af;
// Af.A_ = A;
// FA fa;
// fa.A = A;
x.at<float>(0,0) = 0;
x.at<float>(1,0) = 0;
auto funA = [&A](Mat &x)->Mat {
return A * x;
};
fpcg(funA, x, b, M, 20);
// fpcg(A, x, b, M, 20);
LOG(INFO) << x;
LOG(INFO) << funA(x);
}
| [
"zhouyz9608@gmail.com"
] | zhouyz9608@gmail.com |
1055c2212397bbf364c0a4a5a5bf97f6b77479b6 | 3a0471bfc6ff059e5baa67b48befecc2d8447f86 | /hud.h | 368f4204b59023de44919da448e10d320f2de918 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | fcccode/ABCEnchance | f042a793562ae6bf7d5cb8ee1f577a0e48a287ad | 717e4554538e052b2b446f3352da4152f9c8f80e | refs/heads/main | 2023-07-04T16:36:59.820541 | 2021-08-30T03:58:22 | 2021-08-30T03:58:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,320 | h | #define CVAR_GET_FLOAT(x) gEngfuncs.pfnGetCvarFloat(x)
#define CVAR_GET_STRING(x) gEngfuncs.pfnGetCvarString(x)
#define SPR_Load (*gEngfuncs.pfnSPR_Load)
#define SPR_Set (*gEngfuncs.pfnSPR_Set)
#define SPR_Frames (*gEngfuncs.pfnSPR_Frames)
#define SPR_GetList (*gEngfuncs.pfnSPR_GetList)
// SPR_Draw draws a the current sprite as solid
#define SPR_Draw (*gEngfuncs.pfnSPR_Draw)
// SPR_DrawHoles draws the current sprites, with color index255 not drawn (transparent)
#define SPR_DrawHoles (*gEngfuncs.pfnSPR_DrawHoles)
// SPR_DrawAdditive adds the sprites RGB values to the background (additive transulency)
#define SPR_DrawAdditive (*gEngfuncs.pfnSPR_DrawAdditive)
// SPR_EnableScissor sets a clipping rect for HUD sprites. (0,0) is the top-left hand corner of the screen.
#define SPR_EnableScissor (*gEngfuncs.pfnSPR_EnableScissor)
// SPR_DisableScissor disables the clipping rect
#define SPR_DisableScissor (*gEngfuncs.pfnSPR_DisableScissor)
#define FillRGBA (*gEngfuncs.pfnFillRGBA)
// ScreenHeight returns the height of the screen, in pixels
#define ScreenHeight (gScreenInfo.iHeight)
// ScreenWidth returns the width of the screen, in pixels
#define ScreenWidth (gScreenInfo.iWidth)
#define GetScreenInfo (*gEngfuncs.pfnGetScreenInfo)
#define ServerCmd (*gEngfuncs.pfnServerCmd)
#define EngineClientCmd (*gEngfuncs.pfnClientCmd)
#define SetCrosshair (*gEngfuncs.pfnSetCrosshair)
#define WEAPON_SUIT 31
#ifndef _WIN32
#define _cdecl
#endif
typedef int HSPRITE; // handle to a graphic
#define DHN_DRAWZERO 1
#define DHN_2DIGITS 2
#define DHN_3DIGITS 4
#define MIN_ALPHA 100
#define HUDELEM_ACTIVE 1
typedef struct {
int x, y;
} POSITION;
typedef struct {
unsigned char r, g, b, a;
} RGBA;
typedef struct cvar_s cvar_t;
#define HUD_ACTIVE 1
#define HUD_INTERMISSION 2
#define MAX_PLAYER_NAME_LENGTH 32
#define MAX_MOTD_LENGTH 1536
class CHudBase
{
public:
POSITION m_pos;
int m_type;
int m_iFlags; // active, moving,
virtual ~CHudBase() {}
virtual int Init(void) { return 0; }
virtual int VidInit(void) { return 0; }
virtual int Draw(float flTime) { return 0; }
virtual void Think(void) { return; }
virtual void Reset(void) { return; }
virtual void InitHUDData(void) {} // called every time a server is connected to
};
struct HUDLIST {
CHudBase* p;
HUDLIST* pNext;
}; | [
"dr.abc@cykaskin.com"
] | dr.abc@cykaskin.com |
28e4367a93ba7188f5b6736f4cf3beffda36637e | 4beac7b3eaea0b62a04f5365be0457e060973d9e | /src/ProcessingDialog.hpp | 12a85e311a0fa3e21b86f5f9543983eb79c8803a | [] | no_license | yokeap/sl-calibrator-gige | 72eb69e50b151e5f1f3f6a024602ae8e3a536219 | d4c13a7edecaa77653421d5d60e24b619b0ff045 | refs/heads/master | 2020-03-25T18:13:11.477695 | 2018-08-13T18:03:57 | 2018-08-13T18:03:57 | 144,018,978 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,504 | hpp | /*
Copyright (c) 2012, Daniel Moreno and Gabriel Taubin
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 Brown University 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 DANIEL MORENO AND GABRIEL TAUBIN 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.
*/
#ifndef __PROCESSDIALOG_HPP__
#define __PROCESSDIALOG_HPP__
#include <QDialog>
#include "ui_ProcessingDialog.h"
class ProcessingDialog : public QDialog, public Ui::ProcessingDialog
{
Q_OBJECT
public:
ProcessingDialog(QWidget * parent = 0, Qt::WindowFlags flags = 0);
~ProcessingDialog();
inline void set_current_message(const QString & text) {current_message_label->setText(text);}
void reset(void);
inline void set_progress_total(unsigned value) {_total = value; progress_bar->setMaximum(_total);}
inline void set_progress_value(unsigned value) {progress_bar->setValue(value);}
void finish(void);
void message(const QString & text);
inline bool canceled(void) const {return _cancel;}
public slots:
void on_close_cancel_button_clicked(bool checked = false);
private:
unsigned _total;
bool _cancel;
};
#endif /* __PROCESSDIALOG_HPP__ */ | [
"siwakorn.ictrl@gmail.com"
] | siwakorn.ictrl@gmail.com |
b1939465c680c70b452e2425a0e0108588bbb48b | 45e0fbd9a9dbcdd4fbe6aaa2fdb2aed296f81e33 | /FindSecret/Classes/Native/mscorlib_System_Collections_Generic_Dictionary_2_Ke971183276.h | 05d703224f42bfa72848996a79dfc435f01f830a | [
"MIT"
] | permissive | GodIsWord/NewFindSecret | d4a5d2d810ee1f9d6b3bc91168895cc808bac817 | 4f98f316d29936380f9665d6a6d89962d9ee5478 | refs/heads/master | 2020-03-24T09:54:50.239014 | 2018-10-27T05:22:11 | 2018-10-27T05:22:11 | 142,641,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,292 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_ValueType3640485471.h"
#include "mscorlib_System_Collections_Generic_Dictionary_2_E2743189067.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2/KeyCollection/Enumerator<System.Object,System.Int64>
struct Enumerator_t971183276
{
public:
// System.Collections.Generic.Dictionary`2/Enumerator<TKey,TValue> System.Collections.Generic.Dictionary`2/KeyCollection/Enumerator::host_enumerator
Enumerator_t2743189067 ___host_enumerator_0;
public:
inline static int32_t get_offset_of_host_enumerator_0() { return static_cast<int32_t>(offsetof(Enumerator_t971183276, ___host_enumerator_0)); }
inline Enumerator_t2743189067 get_host_enumerator_0() const { return ___host_enumerator_0; }
inline Enumerator_t2743189067 * get_address_of_host_enumerator_0() { return &___host_enumerator_0; }
inline void set_host_enumerator_0(Enumerator_t2743189067 value)
{
___host_enumerator_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"zhangyide@9fbank.cc"
] | zhangyide@9fbank.cc |
ee5ea73860afb94c4c71d8c3cc5dc5b007c658c9 | 14917b274d686fe52726662fe244a61b3a4451d7 | /Source/UiPlotter.cpp | 62f6a9faf79f7a2a744764594508daa1a66d380b | [
"MIT"
] | permissive | StefanoLusardi/BilinearOscillator | 984a6fc8825fd7e4b10802fca439d4bca7822219 | cb53ba05a865cc360243adf0e04ef9421028abcf | refs/heads/master | 2020-03-22T20:36:21.801474 | 2020-03-15T17:55:43 | 2020-03-15T17:55:43 | 140,614,150 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,452 | cpp | /*
==============================================================================
This is an automatically generated GUI class created by the Projucer!
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Created with Projucer version: 5.4.3
------------------------------------------------------------------------------
The Projucer is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
==============================================================================
*/
//[Headers] You can add your own extra header files here...
#include "Core.h"
//[/Headers]
#include "UiPlotter.h"
//[MiscUserDefs] You can add your own user definitions and misc code here...
//[/MiscUserDefs]
//==============================================================================
UiPlotter::UiPlotter (Component* parent, Core& core, const String& objId)
: mParent{parent}
{
//[Constructor_pre] You can add your own custom stuff here..
setName(Widgets[Widget::Plotter] + objId);
//[/Constructor_pre]
//[UserPreSize]
//[/UserPreSize]
setSize (600, 400);
//[Constructor] You can add your own custom stuff here..
const auto sliderUiModel = core.getModel().getChildWithProperty(Props[Prop::Id], Widgets[Widget::Osc]+objId).getChildWithProperty(Props[Prop::Id], Widgets[Widget::SliderStrip]);
const auto ampModel = sliderUiModel.getChildWithProperty(Props[Prop::Id], Params[Param::Amp] ).getPropertyAsValue(Props[Prop::Value], nullptr, false);
const auto freqModel = sliderUiModel.getChildWithProperty(Props[Prop::Id], Params[Param::Freq] ).getPropertyAsValue(Props[Prop::Value], nullptr, false);
const auto phaseModel = sliderUiModel.getChildWithProperty(Props[Prop::Id], Params[Param::PhInv]).getPropertyAsValue(Props[Prop::Value], nullptr, false);
mAmp.referTo(ampModel);
mFreq.referTo(freqModel);
mPhaseInvert.referTo(phaseModel);
const auto buttonUiModel = core.getModel().getChildWithProperty(Props[Prop::Id], Widgets[Widget::Osc]+objId).getChildWithProperty(Props[Prop::Id], Widgets[Widget::ButtonStrip]);
const auto sawModel = buttonUiModel.getChildWithProperty(Props[Prop::Id], Waves[Wave::Saw]).getPropertyAsValue(Props[Prop::Value], nullptr, false);
const auto sqrModel = buttonUiModel.getChildWithProperty(Props[Prop::Id], Waves[Wave::Sqr]).getPropertyAsValue(Props[Prop::Value], nullptr, false);
const auto triModel = buttonUiModel.getChildWithProperty(Props[Prop::Id], Waves[Wave::Tri]).getPropertyAsValue(Props[Prop::Value], nullptr, false);
mWaveforms[Wave::Saw].referTo(sawModel);
mWaveforms[Wave::Sqr].referTo(sqrModel);
mWaveforms[Wave::Tri].referTo(triModel);
//[/Constructor]
}
UiPlotter::~UiPlotter()
{
//[Destructor_pre]. You can add your own custom destruction code here..
//[/Destructor_pre]
//[Destructor]. You can add your own custom destruction code here..
//[/Destructor]
}
//==============================================================================
void UiPlotter::paint (Graphics& g)
{
//[UserPrePaint] Add your own custom painting code here..
//[/UserPrePaint]
{
float x = 0.0f, y = 0.0f, width = static_cast<float> (proportionOfWidth (1.0000f)), height = static_cast<float> (proportionOfHeight (1.0000f));
Colour fillColour = Colours::yellow;
Colour strokeColour = Colours::black;
//[UserPaintCustomArguments] Customize the painting arguments here..
//[/UserPaintCustomArguments]
g.setColour (fillColour);
g.fillRoundedRectangle (x, y, width, height, 20.000f);
g.setColour (strokeColour);
g.drawRoundedRectangle (x, y, width, height, 20.000f, 5.000f);
}
{
float x = static_cast<float> (proportionOfWidth (0.0500f)), y = static_cast<float> (proportionOfHeight (0.0500f)), width = static_cast<float> (proportionOfWidth (0.9000f)), height = static_cast<float> (proportionOfHeight (0.9000f));
Colour strokeColour = Colours::black;
//[UserPaintCustomArguments] Customize the painting arguments here..
//[/UserPaintCustomArguments]
g.setColour (strokeColour);
g.drawRoundedRectangle (x, y, width, height, 20.000f, 2.000f);
}
//[UserPaint] Add your own custom painting code here..
{
// Plotter Grid
const auto marginX = static_cast<float>(proportionOfWidth(0.05f));
const auto marginY = static_cast<float>(proportionOfHeight(0.05f));
g.setColour(Colours::black);
g.drawVerticalLine(int((getLocalBounds().getCentreX()-marginX)*1/2 + marginX), marginY, getLocalBounds().getHeight()-marginY);
g.drawVerticalLine(int((getLocalBounds().getCentreX()-marginX)*3/2 + marginX), marginY, getLocalBounds().getHeight()-marginY);
g.drawVerticalLine(getLocalBounds().getCentreX(), marginY, getLocalBounds().getHeight()-marginY);
g.drawHorizontalLine(getLocalBounds().getCentreY(), marginX, getLocalBounds().getWidth()-marginX);
}
Path path;
switch(getWaveform())
{
case Wave::Saw: plotSaw(path); break;
case Wave::Sqr: plotSqr(path); break;
case Wave::Tri: plotTri(path); break;
default: break;
}
g.setColour(Colours::blueviolet);
g.strokePath(path, PathStrokeType(5.0f, PathStrokeType::mitered, PathStrokeType::EndCapStyle::rounded));
//[/UserPaint]
}
void UiPlotter::resized()
{
//[UserPreResize] Add your own custom resize code here..
//[/UserPreResize]
//[UserResized] Add your own custom resize handling here..
//[/UserResized]
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
float UiPlotter::getAmp() const
{
return float(mAmp.getValue());
}
float UiPlotter::getFreq() const
{
return float(mFreq.getValue());
}
float UiPlotter::getPhaseInvert() const
{
return int(mPhaseInvert.getValue()) == 0 ? 1.0f : -1.0f;
}
Wave UiPlotter::getWaveform() const
{
const auto wave = std::find_if(mWaveforms.begin(), mWaveforms.end(), [](const auto& w) { return w.second == 1; });
return wave!=mWaveforms.end() ? wave->first : Wave::None;
}
void UiPlotter::plotSaw(Path& path) const
{
const auto marginX = static_cast<float>(proportionOfWidth(0.05f));
const auto marginY = static_cast<float>(proportionOfHeight(0.05f));
const auto width = getLocalBounds().getWidth() - marginX;
const auto yc = (getLocalBounds().getCentreY() - marginY) * getAmp();
auto y = getPhaseInvert() == 1 ? 0.0f : 2.0f * yc;
auto step = 2.0f * yc / float(getLocalBounds().getWidth() - 2.0f * marginX);
path.startNewSubPath(Point<float>(marginX, yc)); // first point
for (auto x = marginX; x < width; ++x)
{
y += step*getPhaseInvert();
path.lineTo(Point<float>(x, y));
}
path.lineTo(Point<float>(width-1, yc)); // last point
path.applyTransform(AffineTransform::translation(0.0f, getLocalBounds().getCentreY() - yc));
}
void UiPlotter::plotSqr(Path& path) const
{
const auto marginX = static_cast<float>(proportionOfWidth(0.05f));
const auto marginY = static_cast<float>(proportionOfHeight(0.05f));
const auto width = getLocalBounds().getWidth() - marginX;
const auto yc = (getLocalBounds().getCentreY() - marginY) * getAmp();
const auto xc = getLocalBounds().getWidth() / 2.0f;
auto step = 0.0f;
auto y = step;
path.startNewSubPath(Point<float>(marginX, yc)); // first point
for (auto x = marginX; x < width; ++x)
{
if (x < xc) { step = getPhaseInvert() == 1 ? 0.0f : 2.0f * yc; }
if (x >= xc) { step = getPhaseInvert() == 1 ? 2.0f * yc : 0.0f; }
y = step;
path.lineTo(Point<float>(x, y));
}
path.lineTo(Point<float>(width-1, yc)); // last point
path.applyTransform(AffineTransform::translation(0.0f, getLocalBounds().getCentreY() - yc));
}
void UiPlotter::plotTri(Path& path) const
{
const auto marginX = static_cast<float>(proportionOfWidth(0.05f));
const auto marginY = static_cast<float>(proportionOfHeight(0.05f));
const auto width = getLocalBounds().getWidth() - marginX;
const auto yc = (getLocalBounds().getCentreY() - marginY) * getAmp();
const auto xc = getLocalBounds().getWidth() / 2.0f;
const auto x_1_4 = 1.0f * (getLocalBounds().getCentreX()-marginX) / 2.0f + marginX;
const auto x_2_4 = xc;
const auto x_3_4 = 3.0f * (getLocalBounds().getCentreX()-marginX) / 2.0f + marginX;
auto y = yc;
auto step = 0.0f;
const auto stepUp = -1.0f * yc / float((xc - marginX) / 2.0f);
const auto stepDw = 2.0f * yc / float(xc - marginX);
path.startNewSubPath(Point<float>(marginX, yc)); // first point
for (auto x = marginX; x < width; ++x)
{
if (x >= 0 && x < x_1_4) { step = stepUp; }
if (x >= x_1_4 && x < x_2_4) { step = stepDw; }
if (x >= x_2_4 && x < x_3_4) { step = stepDw; }
if (x >= x_3_4) { step = stepUp; }
y += step*getPhaseInvert();
path.lineTo(Point<float>(x, y));
}
// last point already computed
path.applyTransform(AffineTransform::translation(0.0f, getLocalBounds().getCentreY() - yc));
}
//[/MiscUserCode]
//==============================================================================
#if 0
/* -- Projucer information section --
This is where the Projucer stores the metadata that describe this GUI layout, so
make changes in here at your peril!
BEGIN_JUCER_METADATA
<JUCER_COMPONENT documentType="Component" className="UiPlotter" componentName=""
parentClasses="public Component" constructorParams="Component* parent, Core& core, const String& objId"
variableInitialisers="mParent{parent}" snapPixels="8" snapActive="1"
snapShown="1" overlayOpacity="0.330" fixedSize="0" initialWidth="600"
initialHeight="400">
<BACKGROUND backgroundColour="0">
<ROUNDRECT pos="0 0 100% 100%" cornerSize="20.0" fill="solid: ffffff00"
hasStroke="1" stroke="5, mitered, butt" strokeColour="solid: ff000000"/>
<ROUNDRECT pos="5% 5% 90% 90%" cornerSize="20.0" fill="solid: ffffff" hasStroke="1"
stroke="2, mitered, butt" strokeColour="solid: ff000000"/>
</BACKGROUND>
</JUCER_COMPONENT>
END_JUCER_METADATA
*/
#endif
//[EndFile] You can add extra defines here...
//[/EndFile]
| [
"lusardi.stefano@gmail.com"
] | lusardi.stefano@gmail.com |
4e612ca4d2b2a04f7347988288452503cffdd729 | 83dc4149bb57cd0d4c3d4f682951e80f53378ef2 | /841b.cpp | 579468c07969b3a960886672d7056331c19b2f1b | [] | no_license | asperaa/Codeforces_Problems | 20d2bec826a5f427e19e65003839f5df8f2411b5 | bb28935f47598bd74fe41552e258cbd447b8ddde | refs/heads/master | 2021-01-23T21:46:59.301036 | 2018-08-22T13:29:17 | 2018-08-22T13:29:17 | 102,904,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int n,o=0,e=0,om=0,em=0;
cin>>n;
vector<int>v;
int c;
for(int i=0;i<n;i++)
{
cin>>c;
v.push_back(c);
}
for(int i=0;i<v.size();i++)
cout<<v[i]<<" "<<endl;
while(v.size()>0)
{
for(int i=0;i<v.size();i++)
{
o+=v[i];
if(o%2==1)
{
v.erase(v.begin()+i);
i--;
}
else
{
o-=v[i];
if(o==0)
continue;
else{
om++;
break;
}
}
}
for(int i=0;i<v.size();i++)
{
e+=v[i];
if(e%2==0)
{
v.erase(v.begin()+i);
i--;
}
else
{
e-=v[i];
if(e==0)
continue;
else
{
em++;
break;
}
}
}
}
cout<<om<<endl;
cout<<em<<endl;
if(om>em)
cout<<"First";
else
cout<<"Second";
}
| [
"adityaankr44@gmail.com"
] | adityaankr44@gmail.com |
276b8c4d60dc0dfea4235073a9cfabda224d5cb6 | 1074cd97c08562bd3d90c48c6e31c3fb4e6faead | /server/test.h | f90bd64cc60e2f72d392576e016c25a55df4a2dc | [] | no_license | ryder1986/pedestrian-v12 | e2fbaf8068c92b205c51486fac7cfc60e2833604 | 1bc6faf260ab5a77dc1f3702eef0beb779f42e5e | refs/heads/master | 2021-08-23T15:00:05.830717 | 2017-12-05T09:41:02 | 2017-12-05T09:41:02 | 111,528,231 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,955 | h | #ifndef TEST_H
#define TEST_H
#include <iostream>
#include <cstdio>
#include <chrono>
#include <thread>
#include <ctime>
#include <cstring>
#include <mutex>
#include <thread>
#include <bitset>
#include <QtCore>
#include <QUdpSocket>
#include <QNetworkInterface>
#include <list>
using namespace std;
class Tools
{
public:
enum FIXED_VALUE{
PATH_LENGTH=200,
BUF_LENGTH=200
};
static mutex lock;
private:
int cc=0;
static char filename[FIXED_VALUE::PATH_LENGTH];
const int static buf_size=200;
public:
Tools()
{
}
inline static void prt(const char *buf,const int line_no,const char *func_name,const char *file_name,const char *label,const char *time)
{
char buffer[buf_size];
memset(buffer,0,buf_size);
memcpy(buffer,time,strlen(time));
int i;
for( i=0;buffer[i]!='\n';i++)
;
buffer[i]='\0';
cout<<"("<<buf<<")"<<'['<<line_no<<']'<<'['<<func_name<<']'<<'['<<file_name<<']'<<'['<<buffer<<']'<<'['<<label<<']'<<endl;
}
inline static char* get_time()
{
chrono::system_clock::time_point today= chrono::system_clock::now();
time_t tt= chrono::system_clock::to_time_t(today);
return ctime(&tt);
}
static void init(const char *)
{
}
static int aaaa;
static const int ss=123;
enum test{
ABC=1,
BCD=2
};
typedef test sss;
void aaa()
{
}
};
class Protocol{
public :
const int static camera_max_num=8;
enum VER{
VERSION=1
};
enum LEN{
HEAD_LENGTH=8
};
enum AABB{
SS=0,
PP=1
};
enum CMD{
GET_CONFIG,
ADD_CAMERA,
DEL_CAMERA,
MOD_CAMERA
};
enum RET{
RET_SUCCESS,
RET_FAIL,
RET_REFRESH
};
enum PORTS{
SERVER_PORT=12345,
SERVER_DATA_OUTPUT_PORT=12346,
CLIENT_REPORTER_PORT=12347,
SERVER_REPORTER_PORT=12348
};
static void pkg_set_len(char *c,int len)//encode length of pkg
{
char *dst=c;
quint16 *p_len=( quint16 *)dst;
*p_len=len;
}
static int pkg_get_len(char *c)//decode length of pkg
{
char *dst=c;
quint16 *p_len=( quint16 *)dst;
return *p_len;
}
static void pkg_set_ret(char *c,int ret)//encode ret of pkg
{
char *dst=c+2+2+2;
quint16 *p_ret=( quint16 *)dst;
*p_ret=ret;
}
static int pkg_get_ret(char *c)//decode ret of pkg
{
char *dst=c+2+2+2;
quint16 *p_ret=( quint16 *)dst;
return *p_ret;
}
static void pkg_set_version(char *c,int version)
{
char *dst=c+2;
quint16 *p_version=( quint16 *)dst;
*p_version=version;
}
static int pkg_get_version(char *c)
{
char *dst=c+2;
quint16 *p_version=( quint16 *)dst;
return *p_version;
}
static void pkg_set_op(char *c,int op)
{
char *dst=c+2+2;
quint16 *p_op=( quint16 *)dst;
*p_op=op;
}
static int pkg_get_op(char *c)
{
char *dst=c+2+2;
quint16 *p_op=( quint16 *)dst;
return *p_op;
}
// static int pkg_get_len(QByteArray &ba)
// {
// return 0;
// }
// static void pkg_set_version(QByteArray &ba)
// {
// }
// static int pkg_get_version(QByteArray &ba)
// {
// return ba;
// }
// static void pkg_set_op(QByteArray &ba)
// {
// }
// static int pkg_get_get(QByteArray &ba)
// {
// return ba;
// }
static int encode_configuration_request(char *buf){
// pkg_set_len(ba);
memset(buf,0,Tools::BUF_LENGTH);
pkg_set_len(buf,0);
pkg_set_version(buf,VERSION);
pkg_set_op(buf,GET_CONFIG);
pkg_set_ret(buf,RET_SUCCESS);
return HEAD_LENGTH;
}
static int encode_configuration_reply(char *buf,int len,int ret){
// pkg_set_len(ba);
// memset(buf,0,BUF_MAX_LEN);
pkg_set_len(buf,len);
pkg_set_version(buf,VERSION);
pkg_set_op(buf,GET_CONFIG);
pkg_set_ret(buf,ret);
return HEAD_LENGTH;
}
static int encode_addcam_request(char *buf,int len){
// pkg_set_len(ba);
memset(buf,0,Tools::BUF_LENGTH);
pkg_set_len(buf,len);
pkg_set_version(buf,VERSION);
pkg_set_op(buf,ADD_CAMERA);
pkg_set_ret(buf,RET_SUCCESS);
return HEAD_LENGTH+len;
}
static int encode_delcam_request(char *buf,int index){
// pkg_set_len(ba);
memset(buf,0,Tools::BUF_LENGTH);
pkg_set_len(buf,0);
pkg_set_version(buf,VERSION);
pkg_set_op(buf,DEL_CAMERA);
pkg_set_ret(buf,index);
return HEAD_LENGTH;
}
static int get_operation(char *buf){
return pkg_get_op(buf);
}
static int get_length(char *buf){
return pkg_get_len(buf);
}
static int get_cam_index(char *buf){
return pkg_get_ret(buf);
}
};
#define prt(label,...) {Tools::lock.lock(); Tools::init("log.txt"); char buf[1000];sprintf(buf,__VA_ARGS__);\
Tools::prt(buf,__LINE__,__FUNCTION__,__FILE__,#label,Tools::get_time());Tools::lock.unlock();}
#define THREAD_DEF(cls,fun) new thread(std::mem_fn(&cls::fun),*(cls*)this);
//void fun()
//{
// try {
// throw std::invalid_argument("test error!");
// }
// catch (const invalid_argument& ia) {
// std::cerr << "Invalid argument: " << ia.what() << '\n';
// }
//}
//#include <mutex>
//using namespace std;
//#include <windows.h>
class TestThread{
static void thread_fun1()
{
// this_thread::sleep_for(chrono::seconds(10));
while(1) {
// Sleep(1000);
this_thread::sleep_for(chrono::microseconds(1));
// lk.lock();
prt(info,"thread fun11 ");
// lk.unlock();
// cout<<"1"<<endl;
}
}
static void thread_fun2()
{
// this_thread::sleep_for(chrono::seconds(10));
while(1) {
// Sleep(1000);
this_thread::sleep_for(chrono::microseconds(1));
// this_thread::sleep_for(chrono::seconds(1));
// lk.lock();
prt(info,"thread fun22 ");
// lk.unlock();
// cout<<"1"<<endl;
}
}
public:
TestThread(){
// while(1)
// {
// // this_thread::sleep_for(chrono::milliseconds(1000));
// Sleep(1000);
// cout<<"aa"<<endl;
// }
thread tmp1(thread_fun1);
thread tmp2(thread_fun2);
// tmp.detach();
// this_thread::sleep_for(chrono::seconds(1));
tmp1.join();
tmp2.join();
}
~TestThread(){}
};
class TestThread1{
public:
void fun()
{
while(1)
{
this_thread::sleep_for(chrono::milliseconds(1000));
// Sleep(1000);
cout<<t<<endl;
}
}
public:
TestThread1():t(12){
}
int t;
};
class PrintNum1{
public:
PrintNum1():start(17){}
void fun()
{
while(1)
{
this_thread::sleep_for(chrono::milliseconds(1000));
cout<<start++<<endl;
}
}
void start_thread()
{
t=new thread(std::mem_fn(&PrintNum1::fun),*this);
}
void stop_thread()
{
t->join();
}
private:
int start;
// thread t(std::mem_fn(&PrintNum1::fun),*(PrintNum1 *)obj);
thread *t;
};
class AThread{
public:
AThread()
{
}
};
class AbstructThread{
public:
AbstructThread(thread *th):t(th){
thread_started=1;
cout<<thread_started<<endl;
//sss=11;
}
//virtual void fun()=0;
~AbstructThread()
{
// t->join();
}
int is_started()
{
cout<<thread_started<<endl;
return thread_started;
}
void start_thread()
{
cout<<"thread_started"<<endl;
thread_started=1;
}
void stop_thread()
{
cout<<"stoping thread"<<endl;
thread_started=0;
}
void ter()
{
t->join();
}
private:
// thread t(std::mem_fn(&PrintNum1::fun),*(PrintNum1 *)obj);
thread *t;
int thread_started;
//void *obj;
// / int num;
};
class Thread1{
public:
Thread1(){
// th=new AbstructThread( thread(std::mem_fn(&Thread1::fun),*(Thread1*)obj));
ttt=10;
// p_thread=new thread(std::mem_fn(&Thread1::fun),*(Thread1*)obj);
p_thread_fun1=THREAD_DEF(Thread1,fun1);
p_thread_fun1->detach();
p_thread_fun2=THREAD_DEF(Thread1,fun2);
p_thread_fun2->detach();
}
void fun1()
{
while(1){
if(1)
{
this_thread::sleep_for(std::chrono::milliseconds(10)); //休眠三秒
cout<<__FUNCTION__<<endl;
}
else{
this_thread::sleep_for(std::chrono::seconds(1)); //休眠三秒
}
}
}
void fun2()
{
while(1){
if(1)
{
this_thread::sleep_for(std::chrono::milliseconds(10)); //休眠三秒
cout<<__FUNCTION__<<endl;
}
else{
this_thread::sleep_for(std::chrono::seconds(1)); //休眠三秒
}
}
}
thread *p_thread_fun1;
thread *p_thread_fun2;
// AbstructThread *th;
int ttt;
};
//#include <sys/socket.h>
//#include <arpa/inet.h>
//#include <netinet/in.h>
//#include <string.h>
//#include <sys/ioctl.h>
//#include <net/if.h>
//#include <fcntl.h>
//#include <stdlib.h>
//#include <stdio.h>
//#include <unistd.h>
//#include <linux/netlink.h>
//#include <linux/rtnetlink.h>
//#include <errno.h>
////#include <tcp.h>
//#include <sys/ioctl.h>
#define BROADCAST_STR "pedestrian"
/*
ServerInfoReporter:check port 12348 per sec. if string "pedestrian" recived , send string "ssssss" to the port 12347 of incoming ip
*/
//#include "common.h"
//#include "protocol.h"
class ServerInfoReporter : public QObject{
Q_OBJECT
public:
ServerInfoReporter(){
timer=new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(check_client()));//TODO:maybe replace with readReady signal
udp_skt = new QUdpSocket(this);
udp_skt->bind(Protocol::SERVER_REPORTER_PORT,QUdpSocket::ShareAddress);
timer->start(1000);
}
~ServerInfoReporter()
{
disconnect(timer);
delete timer;
delete udp_skt;
}
public slots:
void check_client()
{
QByteArray client_msg;
char *msg;
if(udp_skt->hasPendingDatagrams())
{
client_msg.resize((udp_skt->pendingDatagramSize()));
udp_skt->readDatagram(client_msg.data(),client_msg.size());
prt(info,"msg :%s",msg=client_msg.data());
if(!strcmp(msg,"pedestrian"))
send_buffer_to_client();
// udp_skt->flush();
}else{
//prt(debug,"searching client on port %d",Protocol::SERVER_REPORTER_PORT)
}
}
void send_buffer_to_client()
{
QByteArray datagram;
datagram.clear();
QList <QNetworkInterface>list_interface=QNetworkInterface::allInterfaces();
foreach (QNetworkInterface i, list_interface) {
if(i.name()!="lo"){
QList<QNetworkAddressEntry> list_entry=i.addressEntries();
foreach (QNetworkAddressEntry e, list_entry) {
if(e.ip().protocol()==QAbstractSocket::IPv4Protocol)
{
datagram.append(QString(e.ip().toString())).append(QString(",")).\
append(QString(e.netmask().toString())).append(QString(",")).append(QString(e.broadcast().toString()));
}
}
}
}
udp_skt->writeDatagram(datagram.data(), datagram.size(),
QHostAddress::Broadcast, Protocol::CLIENT_REPORTER_PORT);
}
private:
QTimer *timer;
QUdpSocket *udp_skt;
};
#include <QFile>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QTextStream>
class FileDataBase{
QByteArray data;
QString config_filename;
public:
FileDataBase(QString name):config_filename(name)
{
load_config_from_file(config_filename);
}
~FileDataBase()
{
}
QByteArray get()
{
return data;
}
void set(const QByteArray &d)
{
data=d;
save_config_to_file();
}
private:
int load_config_from_file()
{
QFile *f=new QFile(config_filename);
bool ret = f->open(QIODevice::ReadOnly);
if(!ret){
delete f;
return 0;
}
data=f->readAll();
f->close();
return 1;
}
int load_config_from_file(QString file_name)
{
QFile *f=new QFile(file_name);
bool ret = f->open(QIODevice::ReadOnly);
if(!ret){
delete f;
return 0;
}
data=f->readAll();
f->close();
return 1;
}
void save_config_to_file()
{
QFile *f=new QFile(config_filename);
bool ret = f->open(QIODevice::ReadWrite|QIODevice::Truncate);
if(!ret){
prt(info,"fail to open %s",config_filename.toStdString().data());
delete f;
}
f->write(data);
f->close();
}
void save_config_to_file(QString file_name)
{
QFile *f=new QFile(file_name);
bool ret = f->open(QIODevice::ReadWrite|QIODevice::Truncate);
if(!ret){
prt(info,"fail to open %s",file_name.toStdString().data());
delete f;
}
f->write(data);
f->close();
}
};
class CameraConfiguration{
public:
/*
config save in cfg(config_t),which is load from p_database(FileDatabase).
*/
FileDataBase *p_database;
typedef struct camera_config{
QString ip;
int port;
}camera_config_t;
typedef struct config{
int camera_amount;
QList<camera_config_t> camera;
}config_t;
config_t cfg;
CameraConfiguration(QString name)
{
p_database=new FileDataBase(name);
reload_cfg();
// QByteArray b=p_database->get();
// cfg=decode_from_json(b);
}
~CameraConfiguration()
{
delete p_database;
}
// int add_camera(int index,QString url,int port)
// {
// if(index<0||index > Protocol::camera_max_num)
// return -1;
// camera_config_t cam;
// cam.ip=url;
// cam.port=port;
// cfg.camera.insert(index,cam);
// cfg.camera_amount++;
// save();
// return 0;
// }
// int del_camera(int index)
// {
// if(index<0||index > Protocol::camera_max_num)
// return -1;
// cfg.camera.removeAt(index-1);
// cfg.camera_amount--;
// save();
// return 0;
// }
// void mod_camera()
// {
// }
void set_config(QByteArray &ba)
{
p_database->set(ba);
reload_cfg();
}
void set_config(const char *buf)
{
QByteArray ba;
ba.clear();
ba.append(buf);
p_database->set(ba);
reload_cfg();
}
// camera_config_t get_camera_config(int index)
// {
// if(index>0&&index<=cfg.camera_amount)
// return cfg.camera[index-1];
// }
// camera_config_t get_camera_config()
// {
// if(0<cfg.camera_amount)
// return cfg.camera[cfg.camera_amount-1];
// else
// return NULL;
// }
private:
void reload_cfg()
{
QByteArray b=p_database->get();
cfg=decode_from_json(b);
}
void save()
{
p_database->set(encode_to_json(cfg));
}
/*
parse structure from data
*/
config_t decode_from_json(QByteArray &json_src)
{
QJsonDocument json_doc=QJsonDocument::fromJson(json_src);
QJsonObject root_obj=json_doc.object();
config_t data;
data.camera.clear();
data.camera_amount=get_int(root_obj,"camera_total_number");
QJsonArray cams=get_child_array(root_obj,"camera");
foreach (QJsonValue v, cams) {
QJsonObject obj=v.toObject();
camera_config_t t;
t.ip=get_string(obj,"ip");
t.port=get_int(obj,"port");
data.camera.append(t);
}
return data;
}
/*
pack data from structure
*/
QByteArray encode_to_json(config_t data)
{
QJsonDocument json_doc_new;
QJsonObject root_obj;
root_obj["camera_total_number"]=data.camera_amount;
QJsonArray cams;
for(int i=0;i<data.camera_amount;i++)
{
QJsonObject o;
o["ip"]=data.camera[i].ip;
o["port"]=data.camera[i].port;
cams.append(o);
}
root_obj["camera"]=cams;
json_doc_new.setObject(root_obj);
return json_doc_new.toJson();
}
inline int get_int(QJsonObject obj,const char *member_name)
{
return obj[member_name].toInt();
}
inline QString get_string(QJsonObject obj,const char *member_name)
{
return obj[member_name].toString();
}
inline bool get_bool(QJsonObject obj,const char *member_name)
{
return obj[member_name].toBool();
}
inline QJsonObject get_child_obj(QJsonObject obj,const char *member_name)
{
return obj[member_name].toObject();
}
inline QJsonArray get_child_array(QJsonObject obj,const char *member_name)
{
return obj[member_name].toArray();
}
};
class Config
{
typedef struct camera_data{
QString ip;
int port;
}camera_data_t;
typedef struct data{
int camera_amount;
QList<camera_data_t> camera;
}data_t;
public:
Config(char *name)
{
config_filename.clear();
config_filename.append(name);
load_config_from_file();
}
~Config()
{
}
// void set_ba(QByteArray ba){
// decode_from_json(ba);
// save_config_to_file();
// }
// QByteArray get_ba(){
// return encode_to_json();
// }
// void save(){
// save_config_to_file();
// }
// void append_camera(QString url,int port)
// {
// camera_data_t cam;
// cam.ip=url;
// cam.port=port;
// data.camera.append(cam);
// data.camera_amount++;
// save();
// }
// void del_camera(int index)
// {
// data.camera.removeAt(index-1);
// data.camera_amount--;
// save();
// }
int load_config_from_file()
{
QFile *f=new QFile(config_filename);
bool ret = f->open(QIODevice::ReadOnly);
if(!ret){
delete f;
return 0;
}
QByteArray json_data;
json_data=f->readAll();
decode_from_json(json_data);
f->close();
return 1;
}
int load_config_from_file(QString file_name)
{
QFile *f=new QFile(file_name);
bool ret = f->open(QIODevice::ReadOnly);
if(!ret){
delete f;
return 0;
}
QByteArray json_data;
json_data=f->readAll();
decode_from_json(json_data);
f->close();
return 1;
}
void save_config_to_file()
{
QFile *f=new QFile(config_filename);
bool ret = f->open(QIODevice::ReadWrite|QIODevice::Truncate);
if(!ret){
prt(info,"fail to open %s",config_filename.toStdString().data());
delete f;
}
f->write(encode_to_json());
f->close();
}
void save_config_to_file(QString file_name)
{
QFile *f=new QFile(file_name);
bool ret = f->open(QIODevice::ReadWrite|QIODevice::Truncate);
if(!ret){
prt(info,"fail to open %s",file_name.toStdString().data());
delete f;
}
f->write(encode_to_json());
f->close();
}
private:
/*
parse structure from data
*/
void decode_from_json(QByteArray &json_src)
{
QJsonDocument json_doc=QJsonDocument::fromJson(json_src);
QJsonObject root_obj=json_doc.object();
data.camera.clear();
data.camera_amount=get_int(root_obj,"camera_total_number");
QJsonArray cams=get_child_array(root_obj,"camera");
foreach (QJsonValue v, cams) {
QJsonObject obj=v.toObject();
camera_data_t t;
t.ip=get_string(obj,"ip");
t.port=get_int(obj,"port");
data.camera.append(t);
}
}
QByteArray encode_to_json()
{
QJsonDocument json_doc_new;
QJsonObject root_obj;
root_obj["camera_total_number"]=data.camera_amount;
QJsonArray cams;
for(int i=0;i<data.camera_amount;i++)
{
QJsonObject o;
o["ip"]=data.camera[i].ip;
o["port"]=data.camera[i].port;
cams.append(o);
}
root_obj["camera"]=cams;
json_doc_new.setObject(root_obj);
return json_doc_new.toJson();
}
inline int get_int(QJsonObject obj,const char *member_name)
{
return obj[member_name].toInt();
}
inline QString get_string(QJsonObject obj,const char *member_name)
{
return obj[member_name].toString();
}
inline bool get_bool(QJsonObject obj,const char *member_name)
{
return obj[member_name].toBool();
}
inline QJsonObject get_child_obj(QJsonObject obj,const char *member_name)
{
return obj[member_name].toObject();
}
inline QJsonArray get_child_array(QJsonObject obj,const char *member_name)
{
return obj[member_name].toArray();
}
QString config_filename;
data_t data;
};
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/video.hpp>
#include <opencv2/ml/ml.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <QObject>
using namespace cv;
using namespace std;
class VideoSrc:public QObject{
Q_OBJECT
public:
bool video_connected_flag;
VideoSrc(QString path):p_cap(NULL)
{
video_connected_flag=true;
memset(url,0,Tools::PATH_LENGTH);
strcpy(url,path.toStdString().data());
p_cap= cvCreateFileCapture(url); //create video source
width=cvGetCaptureProperty(p_cap,CV_CAP_PROP_FRAME_WIDTH);
height=cvGetCaptureProperty(p_cap,CV_CAP_PROP_FRAME_HEIGHT);
// prt(info,"video widtbh %d ",ret);
if(p_cap==NULL){
prt(info,"video src start %s err ",url);
video_connected_flag=false;
}
else {
prt(info,"video src start %s ok ",url);
}
// if(p_cap==NULL)
// emit video_disconnected();
// else
// emit video_connected();
// timer=new QTimer();
// tmr->singleShot(1000,this,SLOT(time_up()));
// prt(info," shot afer 100 ms")
// QTimer::singleShot(1000,this,SLOT(time_up()));
// connect(timer,SIGNAL(timeout()),this,SLOT(time_up()));
// timer->start(wait_duration);
}
~VideoSrc()
{
// cap_lock.lock();
// timer->stop();
// disconnect(timer,SIGNAL(timeout()),this,SLOT(time_up()));
// delete timer;
// QThread::sleep(1);
// prt(info," delete src");
// disconnect(tmr,SIGNAL(timeout()),this,SLOT(time_up()));
cvReleaseCapture(&p_cap);
p_cap=NULL;
// cap_lock.unlock();
// delete tmr;
// delete p_cap;
}
Mat *get_frame()
{
// tmr->singleShot(10,this,SLOT(time_up()));
int err=0;
if(p_cap==NULL){
video_connected_flag=false;
err=1;
// emit video_disconnected();
}
IplImage *ret_img;
// prt(info,"try to grb");
// int tmp= cvGrabFrame(p_cap);
// prt(info,"grub source url:%s ret %d (%p)",url,tmp,p_cap);
// ret_img= cvRetrieveFrame(p_cap);
// prt(info,"try to query");
// CV_CAP_PROP_XI_TIMEOUT
//CV_CAP_PROP_FRAME_WIDTH
// int ret=cvSetCaptureProperty(p_cap,CV_CAP_PROP_XI_TIMEOUT,999);
// double pro=cvGetCaptureProperty(p_cap,CV_CAP_PROP_XI_TIMEOUT);
// prt(info," set %d ,opecv time out %d",ret ,pro);
// CV_CAP_PROP_XI_TIMEOUT
//prt(info," start query 1 frame ");
ret_img=cvQueryFrame(p_cap);
Mat(ret_img).copyTo(mat_rst);
if(ret_img==NULL){
err=1;
// std::this_thread::sleep_for(chrono::milliseconds(1000));
// QThread::sleep(1);
if(video_connected_flag==true)
{
// prt(info,"%s disconnected",url);
video_connected_flag=false;
}
}else{
if(video_connected_flag==false)
{
// prt(info,"%s connected",url);
video_connected_flag=true;
}
}
if(err)
return NULL;
else
return &mat_rst;
}
char *get_url(){
return url;
}
public slots:
signals:
private:
CvCapture *p_cap;
char url[Tools::PATH_LENGTH];
int width;
int height;
Mat mat_rst;
};
using namespace cv;
using namespace std;
class VideoHandler{
public:
IplImage * frame_ori;
VideoHandler()
{
}
~VideoHandler()
{
}
void set_frame( Mat * frame)
{
frame_mat=frame;
}
void set_null_frame( )
{
Mat frame;
frame.resize(0);
frame_mat=&frame;
}
// bool work(QByteArray &rst_ba)
bool work()
{
QByteArray rst_ba;
int min_win_width = 64; // 48, 64, 96, 128, 160, 192, 224
int max_win_width = 256;
bool ret=false;
CascadeClassifier cascade;
vector<Rect> objs;
//string cascade_name = "../Hog_Adaboost_Pedestrian_Detect\\hogcascade_pedestrians.xml";
// string cascade_name = "/root/hogcascade_pedestrians.xml";
const string cascade_name = "/root/repo-github/pedestrian-v12/server/hogcascade_pedestrians.xml";
if (!cascade.load(cascade_name))
{
prt(info,"can't load cascade");
// cout << "can't load cascade!" << endl;
//return -1;
}
#if 1
// while (1)
{
// frame_ori = cvQueryFrame(p_cap);
// frame.create(frame_ori->height,frame_ori->width,CV_8U);
// memcpy(frame.data,frame_ori->imageData,frame_ori->imageSize);
// Mat frame(frame_ori);
// int test= waitKey(1);
// printf("%d\n",test);
Mat frame(*frame_mat);
// cv::namedWindow("1111")
if(!frame.empty())
imshow("url",frame);
// waitKey(2000);
// return true;
// waitKey(25);
// QThread::msleep(1);
// return 0;
if (!frame.empty())
{
frame_num++;
if (frame_num % 100 == 0)
{
cout << "Processed " << frame_num << " frames!" << endl;
}
// if (frame_num % 3 == 0)
if (1)
{
resize(frame,frame,Size(frame.cols / 2, frame.rows / 2),CV_INTER_LINEAR);
//resize(frame,frame,Size(704, 576),CV_INTER_LINEAR);
cvtColor(frame, gray_frame, CV_BGR2GRAY);
// gray_frame=frame;
//Rect rect;
//rect.x = 275;
//rect.y = 325;
//rect.width = 600;
//rect.height = 215;
//Mat detect_area = gray_frame(rect);
//cascade.detectMultiScale(detect_area,objs,1.1,3);
cascade.detectMultiScale(gray_frame, objs, 1.1, 3);
vector<Rect>::iterator it = objs.begin();
while (it != objs.end() && objs.size() != 0)
{
pedestrian_num++;
pedestrians = frame(*it);
Rect rct = *it;
if (rct.width >= min_win_width && rct.width < max_win_width)
{
// sprintf(file_name, "%d.jpg", pedestrian_num);
// imwrite(file_name, pedestrians);
//rct.x += rect.x;
//rct.y += rect.y;
int test=12345;
rectangle(frame, rct, Scalar(0, 255, 0), 2);
QString x_str=QString::number(rct.x);
QString y_str=QString::number(rct.y);
QString test_str=QString::number(test);
rst_ba.append(x_str.toStdString().data());
rst_ba.append(",");
rst_ba.append(y_str.toStdString().data());
//prt(info,"%d %d",rct.x,rct.y);
ret=true;
break;//TODO, now we get first one
}
// rst_ba.append(";");
// rst_ba.append(rct.x);
it++;
}
#if 0
imshow("result", frame);
QThread::msleep(1);
#endif
// waitKey(1);
// rectangle(frame,rect,Scalar(0,255,0),2);
// imshow("result", frame);
//outputVideo << frame;
// waitKey(1);
objs.clear();
}
}
else
{
prt(info,"opencv handle frame error !");
}
}
#endif
if(ret==true){
// emit send_rst(rst_ba);
}
return ret;
}
private:
Mat gray_frame;
Mat pedestrians;
Mat *frame_mat;
QList <Mat> frame_list;
int pedestrian_num = 0;
int frame_num = 0;
};
class Camera{
typedef CameraConfiguration::camera_config_t camera_config;
public:
int test_flg;
typedef struct data{
bool quit_flag;
bool quit_flag_src;
bool quit_flag_sink;
thread *video_src_thread;
thread *video_sink_thread;
thread *record_thread;
camera_config cfg;
VideoSrc *p_src;
VideoHandler * p_handler;
Mat* p_mt;
deque <Mat> frame_list;
deque <int> int_list;
mutex *p_lock;
int testflg;
}data_t;
data_t d;
Camera( camera_config config)
{
// p_lock=new mutex;
// p_src=new VideoSrc(QString("/root/video/test.264"));
// p_handler=new VideoHandler();
// video_src_thread=THREAD_DEF(Camera,get_frame);
// video_src_thread->detach();
// video_sink_thread=THREAD_DEF(Camera,process_frame);
// video_sink_thread->detach();
d.testflg=12;
d.p_lock=new mutex();
d.p_src=new VideoSrc(QString("/root/video/test.264"));
d.p_handler=new VideoHandler();
d.video_sink_thread=new thread(get_frame,&d);
d.video_sink_thread=new thread(get_frame,&d);
d.record_thread=new thread(record_fun,&d);
d.video_src_thread=new thread(process_frame,&d);
d.quit_flag=false;
// d.video_sink_thread->detach();
// d.video_src_thread->detach();
// Mat *m1;
// while(1)
// {
// p_lock->lock();
// m1=p_src->get_frame();
// p_handler->set_frame(m1);
// this_thread::sleep_for(chrono::seconds(1));
// prt(info,"1");
// p_lock->unlock();
//
// }
}
// Camera(const Camera &c)
// {
// p_src= c.p_src;
// }
~Camera()
{
// while(1)
// ;
d.quit_flag=true;
d.video_sink_thread->join();
d.video_src_thread->join();
d.record_thread->join();
delete d.video_sink_thread;
delete d.video_src_thread;
delete d.record_thread;
// d.video_sink_thread->join();
// d.video_src_thread->join();
delete d.record_thread;
delete d.p_handler;
delete d.p_src;
// delete p_lock;
//delete p_handler;
// delete p_src;
// delete video_src_thread;
// delete video_sink_thread;
}
void restart(camera_config new_cfg)
{
// quit_flag=true;
// video_src_thread->join();
// video_sink_thread->join();
// cfg=new_cfg;
// video_src_thread=THREAD_DEF(Camera,get_frame);
// video_sink_thread=THREAD_DEF(Camera,process_frame);
}
int try_restart(camera_config new_cfg)//experinmental
{
// quit_flag=true;
// if(video_src_thread->joinable())
// video_src_thread->detach();
// if(video_sink_thread->joinable())
// video_sink_thread->detach();
// cfg=new_cfg;
// this_thread::sleep_for(chrono::seconds(1));
// if(quit_flag==true&&quit_flag_src==true&&quit_flag_sink==true){
// quit_flag=false;
// quit_flag_sink=false;
// quit_flag_src=false;
// // video_src_thread=THREAD_DEF(Camera,get_frame);
// // video_sink_thread=THREAD_DEF(Camera,process_frame);
// return 0;
// }else{
// return 1;
// }
}
private:
static void record_fun(data_t *data)
{
while(!data->quit_flag)
{
this_thread::sleep_for(chrono::milliseconds(1000));
}
}
static void get_frame(data_t *data)
{
// while(!quit_flag){
// prt(info,"getting frame");
// p_mt=p_src->get_frame();
// p_lock->lock();
// // frame_list.push_front(*p_mt);
// test_flg++;
// prt(info,"++ %d",test_flg);
// p_lock->unlock();
// prt(info,"%d",frame_list.size());
// this_thread::sleep_for(chrono::seconds(1));
// }
// quit_flag_src=true;
while(!data->quit_flag){
data->p_lock->lock();
// data->p_mt=data->p_src->get_frame();
//prt(info,"get : %d",data->testflg++);
data->frame_list.push_back(*data->p_src->get_frame());
// data->int_list.push_back(data->testflg);
prt(info,"get frame ");
data->p_lock->unlock();
this_thread::sleep_for(chrono::milliseconds(1000));
// this_thread::sleep_for(chrono::seconds(1));
}
}
static void process_frame(data_t *data)
{
// QByteArray ba;
// while(!quit_flag){
// prt(info,"processing frame");
// p_lock->lock();
// test_flg--;
//// if(frame_list.size()>1){
//// p_handler->set_frame(&(*frame_list.end()));
//// p_handler->work(ba);
//// }
// p_lock->unlock();
// this_thread::sleep_for(chrono::seconds(1));
// }
// quit_flag_sink=true;
while(!data->quit_flag){
data->p_lock->lock();
if(data->frame_list.size()>0){
prt(info,"size : %d",data->frame_list.size());
data->p_handler->set_frame(&(*data->frame_list.begin()));
// if(data->int_list.size()>0){
// prt(info,"process : %d,size %d",(*data->int_list.begin()),data->int_list.size());
// data->int_list.pop_front();
// }
data->p_handler->work();
data->frame_list.pop_front();
}
data->p_lock->unlock();
this_thread::sleep_for(chrono::milliseconds(100));
//this_thread::sleep_for(chrono::seconds(1));
}
}
};
#include <X11/Xlib.h>
class CameraManager{
public:
CameraManager()
{
XInitThreads();
p_cfg=new CameraConfiguration("/root/repo-github/pedestrian-v12/server/config.json");
start_all();
}
~CameraManager()
{
stop_all();
delete p_cfg;
}
void start_all()
{
foreach (CameraConfiguration::camera_config_t tmp, p_cfg->cfg.camera) {
Camera *c=new Camera(tmp);
cameras.push_back(c);
}
}
void stop_all()
{
foreach (Camera *tmp, cameras) {
delete tmp;
cameras.removeOne(tmp);
}
}
void add_camera(const char *cfg_buf)
{
p_cfg->set_config(cfg_buf);
Camera *c=new Camera(p_cfg->cfg.camera[p_cfg->cfg.camera_amount-1]);
cameras.push_back(c);
}
void del_camera(const char *cfg_buf,const int index)
{
p_cfg->set_config(cfg_buf);
delete cameras[index-1];
cameras.removeAt(index-1);
}
void mod_camera(const char *cfg_buf,const int index)
{
p_cfg->set_config(cfg_buf);
while(true){
if(0==cameras[index-1]->try_restart(p_cfg->cfg.camera[p_cfg->cfg.camera_amount-1]))
break;
else
{
prt(info,"restarting camera %d",index);
}
}
}
private:
CameraConfiguration *p_cfg;
QList<Camera *> cameras;
};
class NetServer{
public:
NetServer(const NetServer&)
{
}
NetServer()
{
cmd_list_lock=new mutex;
}
~NetServer()
{
}
void get_cmd()
{
// cmd_list_lock.lock();
// cmd_list_lock.unlock();
}
private:
void set_cmd()
{
// cmd_list_lock.lock();
// cmd_list_lock.unlock();
}
// QList <string> cmd_list;
mutex *cmd_list_lock;
mutex ccmd_list_lock;
};
int test();
class abc123{
public:
abc123(const abc123 &){
}
mutex ccmd_list_lock;
abc123()
{
}
};
class Test
{
NetServer server;
CameraManager *p_cam_manager;
// std::thread *fetch_cmd_thread;
// abc123 aaa;
//
public:
//
// Test(const Test&){//this is need by std:move sometimes(ex:keep every member in class can be move )
// }
// explicit
Test() {
ServerInfoReporter *r=new ServerInfoReporter ;
// Config cfg("/root/repo-github/pedestrian-v12/server/config.json");
// cfg.save_config_to_file(QString("/root/repo-github/pedestrian-v12/server/config.json-test"));
p_cam_manager=new CameraManager();
// c.start();
// Camera c;
// fetch_cmd_thread=THREAD_DEF(Test,fetch_cmd);
// fetch_cmd_thread->detach();
// fetch_cmd_thread=new std::thread(std::mem_fn(&Test::fetch_cmd),*this);
// fetch_cmd_thread=new std::thread(test);
}
~Test()
{
// delete fetch_cmd_thread;
delete p_cam_manager;
}
void process_net_cmd()
{
int cmd;
char *config_buf;
switch(cmd){
case Protocol::ADD_CAMERA:
p_cam_manager->add_camera(config_buf);
break;
case Protocol::DEL_CAMERA:
p_cam_manager->del_camera(config_buf,1);
break;
default:break;
}
}
void fun111()
{
// abcd::test_fun();
//Tools::aaaa=4;
// cout<<Tools::BCD<<endl;
// cout<<Tools::sss::ABC<<endl;
// Tools::prt_time();
// http://blog.csdn.net/qq_31175231/article/details/77923212
// chrono::milliseconds ms{3};
// using namespace std::chrono;
// typedef duration<int,std::ratio<60*60*24*356>> days_type;
// time_point<system_clock,days_type> today = time_point_cast<days_type>(system_clock::now());
// std::cout << today.time_since_epoch().count() << " days since epoch" << std::endl;
//cout<< Tools::FIXED_VALUE::BUF_LENGTH;
// TestThread t;
// TestThread1 t1;
// thread t(std::mem_fn(&TestThread1::fun),t1);
// t.join();
// PrintNum p;
// p.start_thread(&p);
// cout<<"ok1"<<endl;
// p.stop_thread();
// PrintNum1 p;
// p.start_thread();
// cout<<"ok1"<<endl;
// p.stop_thread();
// Thread1 t1;
// t1.start_thread();
// t1.stop_thread();
// this_thread::sleep_for(std::chrono::seconds(3)); //休眠三秒
// cout<<"done"<<endl;
// t1.stop_thread();
// while(1)
// ;
// ThreadTool1 t1;
// t1.start_thread();
// cout<<"ok2"<<endl;
// t1.stop_thread();
// Tools::init("aa");
// this_thread::sleep_for(std::chrono::seconds(3)); //休眠三秒
// prt(info,"the name is %d %s",11,"FDASFASDF" );
}
private:
void fetch_cmd()
{
while(1)
{
prt(info,"fecthing cmd");
this_thread::sleep_for(chrono::seconds(1));
}
}
};
#endif
| [
"you@example.com"
] | you@example.com |
70ba127d91602a2e24f6f175dc7a781464ced683 | 41457a07f7cb8e59a363ed2047dd08c6394e26e1 | /AtelierEditor/Private/CameraConfigurateTool.cpp | 67c812411b94a09a14ba0c5cfd619ff67f679bfb | [] | no_license | DingSongYun/FinalWork | 8702a47d179a8cc180b32915ff22eaced570ef9c | d5e7ad1179cdde95d6016c8a070f78b9c93c55c9 | refs/heads/master | 2020-09-10T22:21:51.703748 | 2019-11-15T05:34:39 | 2019-11-15T05:34:39 | 221,851,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,173 | cpp | #include "CameraConfigurateTool.h"
#include "Engine/Engine.h"
#include "Kismet/KismetMathLibrary.h"
ACameraConfigurateTool::ACameraConfigurateTool(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
ACameraConfigurateTool::~ACameraConfigurateTool()
{
}
void ACameraConfigurateTool::BeginPlay()
{
GEngine->OnActorMoved().AddUObject(this, &ACameraConfigurateTool::OnActorMove);
}
void ACameraConfigurateTool::Destroyed()
{
GEngine->OnActorMoved().RemoveAll(this);
if (ActorLocked)
{
ActorLocked->GetRootComponent()->TransformUpdated.RemoveAll(this);
}
}
bool ACameraConfigurateTool::IsEditMode() const
{
return Mode == EEditMode::Edit_FocusMode || Mode == EEditMode::Edit_FreeMode;
}
FRotator LookRotationToTarget(const FVector& FromLocation, const AActor* Target)
{
return UKismetMathLibrary::FindLookAtRotation(FromLocation, Target->GetActorLocation());
}
bool ACameraConfigurateTool::CanEditChange(const UProperty* InProperty) const
{
if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, CameraToParam)
|| InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, bCameraStartUseCurrent)
|| InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, bNeedMoveMeToTarget)
|| InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, bInterpolateByDistance)
|| InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, Duration)
)
{
return IsEditMode();
}
if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, CameraFromParam))
{
return IsEditMode() && !bCameraStartUseCurrent;
}
if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, CameraToParamAdd))
{
return IsEditMode() && bInterpolateByDistance;
}
if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, BaseDistance))
{
return IsEditMode() && bInterpolateByDistance;
}
if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, DistanceMeToTarget))
{
return IsEditMode() && bNeedMoveMeToTarget;
}
return Super::CanEditChange(InProperty);
}
void ACameraConfigurateTool::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
if(UProperty* InProperty = PropertyChangedEvent.MemberProperty)
{
if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, CameraFromParam))
{
CameraFromParam.FilledToCachedParam(CamFromTarget, Mode);
FlushLockedActor();
return ;
}
else if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, CameraToParam))
{
CameraToParam.FilledToCachedParam(CamFocusTarget, Mode);
FlushLockedActor();
return ;
}
else if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, CameraToParamAdd))
{
CameraToParamAdd.FilledToCachedParam(CamFocusTarget, Mode);
FlushLockedActor();
return ;
}
}
if(UProperty* InProperty = PropertyChangedEvent.Property)
{
if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, CameraID))
{
return PostLoadCameraConfiguration(CameraID);
}
if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, CamFocusTarget))
{
return RefreshMultiCoordParam();
}
else if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(ACameraConfigurateTool, Mode))
{
return OnEditModeChanged(Mode);
}
}
return Super::PostEditChangeProperty(PropertyChangedEvent);
}
//void ACameraConfigurateTool::PreEditChange( FEditPropertyChain& PropertyAboutToChange )
//{
// //Super::PreEditChange(PropertyAboutToChange);
//}
void ACameraConfigurateTool::PostLoadCameraConfiguration(FName inCameraID)
{
BP_PostLoadCameraConfiguration(inCameraID);
RefreshMultiCoordParam();
}
bool ACameraConfigurateTool::IsPlaying()
{
UWorld* World = GetWorld();
return World->WorldType != EWorldType::Editor;
}
void ACameraConfigurateTool::OnEditModeChanged(EEditMode inMode)
{
RefreshMultiCoordParam();
}
void ACameraConfigurateTool::RefreshMultiCoordParam()
{
CameraFromParam.RecalculateFromCachedParam(CamFromTarget, Mode);
CameraToParam.RecalculateFromCachedParam(CamFocusTarget, Mode);
CameraToParamAdd.RecalculateFromCachedParam(CamFocusTarget, Mode);
}
void ACameraConfigurateTool::SetActorLocked(class AActor* Actor)
{
AActor* PreActor = ActorLocked;
if (PreActor)
{
PreActor->GetRootComponent()->TransformUpdated.RemoveAll(this);
}
ActorLocked = Actor;
if (ActorLocked)
{
ActorLocked->GetRootComponent()->TransformUpdated.AddUObject(this, &ACameraConfigurateTool::OnActorLockedMove);
}
}
void ACameraConfigurateTool::FlushLockedActor()
{
//return ;
if (ActorLocked == nullptr)
{
return ;
}
const FTransform& Transfrom = CamFocusTarget->GetActorTransform();
FVector WLocation = Transfrom.TransformPosition(CameraToParam.CachedParam.Location);
FRotator WRotation = LookRotationToTarget(WLocation, CamFocusTarget) + CameraToParam.CachedParam.Rotation;
ActorLocked->SetActorLocation(WLocation);
ActorLocked->SetActorRotation(WRotation);
//UE_LOG(LogAtelier, Warning, TEXT("Flush Locked Actor: from(%s, %s) => to(%s, %s)"),
// *CameraToParam.CachedParam.Location.ToString(), *CameraToParam.CachedParam.Rotation.ToString(),
// *WLocation.ToString(), *WRotation.ToString()
// );
}
void ACameraConfigurateTool::SyncLockedActor()
{
//return ;
if (Mode == EEditMode::Preview)
{
return ;
}
if (ActorLocked == nullptr || CamFocusTarget == nullptr)
{
return ;
}
FVector WLocation = ActorLocked->GetActorLocation();
FRotator WRotation = ActorLocked->GetActorRotation();
const FTransform& Transfrom = CamFocusTarget->GetActorTransform();
CameraToParam.CachedParam.Location = Transfrom.InverseTransformPosition(WLocation);
CameraToParam.CachedParam.Rotation = WRotation - LookRotationToTarget(WLocation, CamFocusTarget);
//UE_LOG(LogAtelier, Warning, TEXT("Sync Locked Actor: from(%s, %s) => to(%s, %s)"),
// *WLocation.ToString(), *WRotation.ToString(),
// *CameraToParam.CachedParam.Location.ToString(), *CameraToParam.CachedParam.Rotation.ToString()
// );
CameraToParam.RecalculateFromCachedParam(CamFocusTarget, Mode);
}
void FMultiCoordPOVParam::RecalculateFromCachedParam(class AActor* Target, EEditMode Mode)
{
if (Target == nullptr)
{
Location = CachedParam.Location;
Rotation = CachedParam.Rotation;
FOV = CachedParam.FOV;
return ;
}
switch (Mode)
{
case EEditMode::Preview:
case EEditMode::Edit_FocusMode:
{
Location = CachedParam.Location;
Rotation = CachedParam.Rotation;
FOV = CachedParam.FOV;
}
break;
case EEditMode::Edit_FreeMode:
{
const FTransform& Transfrom = Target->GetActorTransform();
Location = Transfrom.TransformPosition(CachedParam.Location);
Rotation = LookRotationToTarget(Location, Target) + CachedParam.Rotation;
FOV = CachedParam.FOV;
}
break;
}
}
void FMultiCoordPOVParam::FilledToCachedParam(class AActor* Target, EEditMode Mode)
{
if (Target == nullptr)
{
CachedParam.Location = Location;
CachedParam.Rotation = Rotation;
CachedParam.FOV = FOV;
return ;
}
switch (Mode)
{
case EEditMode::Preview:
case EEditMode::Edit_FocusMode:
{
CachedParam.Location = Location;
CachedParam.Rotation = Rotation;
CachedParam.FOV = FOV;
}
break;
case EEditMode::Edit_FreeMode:
{
const FTransform& Transfrom = Target->GetActorTransform();
CachedParam.Location = Transfrom.InverseTransformPosition(Location);
//CachedParam.Rotation = Transfrom.InverseTransformRotation(Rotation.Quaternion()).Rotator();
CachedParam.Rotation = Rotation - LookRotationToTarget(Location, Target);
CachedParam.FOV = FOV;
}
break;
}
}
void ACameraConfigurateTool::OnActorMove(AActor* InActor)
{
if (InActor)
{
UE_LOG(LogAtelier, Warning, TEXT("OnActorMove: %s"), *InActor->GetActorLabel());
if (InActor == ActorLocked)
{
if (Mode != EEditMode::Preview)
{
SyncLockedActor();
}
}
}
}
void ACameraConfigurateTool::OnActorLockedMove(USceneComponent* InRootComponent, EUpdateTransformFlags UpdateTransformFlags, ETeleportType Teleport)
{
if (Mode != EEditMode::Preview)
{
SyncLockedActor();
}
} | [
"dingsongyun@xindong.com"
] | dingsongyun@xindong.com |
dd298571b4668becd4c51851a7fc57ad45963e37 | 70b642e909096134db8bb0e788c59e35d5117a22 | /RunAsDesktopUser-mod/RunAsDesktopUser_Implementation.h | 409dea7c21d47b6bdcab0c2513efbcbf48c79fa7 | [
"MIT"
] | permissive | jay/RunAsDesktopUser | ac67994baabdc22507ae14a2fd358f02537d4a0d | f027a1ae057793dd068b28b6ae8530d860cd9a44 | refs/heads/master | 2021-08-28T11:30:13.290093 | 2021-08-23T04:12:06 | 2021-08-23T04:12:06 | 99,401,226 | 12 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 675 | h | #pragma once
#include <sstream>
// Declaration of the function this sample is all about.
// The szApp, szCmdLine, szCurrDir, si, and pi parameters are passed directly to CreateProcessWithTokenW.
// sErrorInfo returns text describing any error that occurs.
// Returns "true" on success, "false" on any error.
// It is up to the caller to close the HANDLEs returned in the PROCESS_INFORMATION structure.
bool RunAsDesktopUser(
__in const wchar_t * szApp,
__in wchar_t * szCmdLine,
__in const wchar_t * szCurrDir,
__in STARTUPINFOW & si,
__inout PROCESS_INFORMATION & pi,
__inout std::wstringstream & sErrorInfo);
| [
"raysatiro@yahoo.com"
] | raysatiro@yahoo.com |
7f418934197316cbb8f74d1d3846a43aa889c75f | 3ba06ac484bfc05d3cd9eebe08f444759b8d196b | /Socket/Socket1/Client.h | 3887b8caea3f2d7b53958e94a782660b2a6ff7f2 | [] | no_license | XungangYin/C-Program | 0aa5a6316f091f0f42ca16474cb1dff47a16065f | a4241b8d1052b8a8399266beedc9249b789f9d27 | refs/heads/master | 2020-05-27T08:33:29.988863 | 2020-01-16T03:13:20 | 2020-01-16T03:13:20 | 188,547,180 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 861 | h | #ifndef CHATROOM_CLIENT_H
#define CHATROOM_CLIENT_H
#include <iostream>
#include <string>
#include "Common.h"
using namespace std;
//客户端类用来链接服务器发送和接受信息
class Client{
public:
Client();
//链接服务器
void Connect();
//断开链接
void Close();
//启动客户端
void Start();
private:
//当前链接服务器端创建的socket
int sock;
//当前进程
int pid;
//epoll_creat创建后的返回值
int epfd;
//创建管道,其中fd【0】用于父进程,fd【1】用于子进程
int pipe_fd[2];
//表示客户端是否正常工作
bool isClientwork;
//聊天信息
Msg msg;
//结构体转换为字符串
char send_buf[BUF_SIZE];
char recv_buf[BUF_SIZE];
//用户链接的服务器IP和port
struct sockaddr_in serverAddr;
};
#endif | [
""
] | |
fc806724b05f10c622e7c0be183d031f26ff8929 | 4217ba1b23cfec70a56857995f5d6976c622fb8a | /richMan_display.cpp | d40380ab5413400ad83e4ce4b4d68c3f8b9c14fa | [] | no_license | WongWingLam/Group2_richman | 0cd1573d4e4203b9a551bc297a4287925313c5dc | d20dff4b2454104efef69ada0186d1a7231550f0 | refs/heads/master | 2022-06-16T04:39:47.583510 | 2020-05-09T15:54:15 | 2020-05-09T15:54:15 | 451,532,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,307 | cpp | //richMan_display.cpp
#include <iostream>
#include <string>
#include <iomanip>
#include "richMan_display.h"
#include "richMan_struct.h"
//display map when necessary
using namespace std;
void displayMap(Block *mapBlocks, Status *players, int playerNo){
for (int j = 0; j < 2; j++)
{
for (int i = 0; i < 10; i++)
{
cout << setfill('-') << setw(15) << '-';
}
cout << endl;
for (int i = 0; i < 10; i++)
{
if (i+j*(j*27-i*2) == 27)
cout << '|' << setfill(' ') << setw(13) << left << mapBlocks[i+j*(j*27-i*2)].name.substr(0,9) << '|';
else
cout << '|' << setfill(' ') << setw(13) << left << mapBlocks[i+j*(j*27-i*2)].name << '|';
}
cout << endl;
for (int i = 0; i < 10; i++)
{
if (mapBlocks[i+j*(j*27-i*2)].price != 0)
cout << "|price: " << setfill(' ') << setw(6) << left << mapBlocks[i+j*(j*27-i*2)].price << '|';
else if (i+j*(j*27-i*2) == 27)
cout << '|' << setfill(' ') << setw(13) << left << mapBlocks[i+j*(j*27-i*2)].name.substr(9,8) << '|';
else
cout << '|' << setfill(' ') << setw(13) << ' ' << '|';
}
cout << endl;
for (int i = 0; i < 10; i++)
{
if (mapBlocks[i+j*(j*27-i*2)].Lv != 0)
cout << "|Lv: " << setfill(' ') << setw(9) << left << mapBlocks[i+j*(j*27-i*2)].Lv << '|';
else
cout << '|' << setfill(' ') << setw(13) << ' ' << '|';
}
cout << endl;
for (int i = 0; i < 10; i++)
{
if (players[0].position == i+j*(j*27-i*2))
cout << '|' << setfill(' ') << setw(6) << left << players[0].name << ' ';
else
cout << "| ";
if (players[1].position == i+j*(j*27-i*2))
cout << setfill(' ') << setw(6) << left << players[1].name << '|';
else
cout << " |";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
if (playerNo > 2 && players[2].position == i+j*(j*27-i*2))
cout << '|' << setfill(' ') << setw(6) << left << players[2].name << ' ';
else
cout << "| ";
if (playerNo > 3 && players[3].position == i+j*(j*27-i*2))
cout << setfill(' ') << setw(6) << left << players[3].name << '|';
else
cout << " |";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << setfill('-') << setw(15) << '-';
}
cout << endl;
if (j == 1)
break;
int temp = playerNo;
//display players info in this loop
for (int i = 0; i < 8; i++)
{
cout << setfill('-') << setw(15) << '-' << setfill(' ') << setw(120) << ' ' << setfill('-') << setw(15) << '-' <<endl;
cout << '|' << setfill(' ') << setw(13) << left << mapBlocks[35-i].name << '|' << setfill(' ') << setw(120) << ' '
<< '|' << setfill(' ') << setw(13) << left << mapBlocks[10+i].name << '|' <<endl;
if (mapBlocks[35-i].price != 0)
cout << "|price: " << setfill(' ') << setw(6) << left << mapBlocks[35-i].price << '|';
else
cout << '|' << setfill(' ') << setw(13) << ' ' << '|';
if ( i>0 && playerNo-i > -1)
cout << setfill(' ') << setw(40) << ' ' << setw(30) << players[i-1].name << setfill(' ') << setw(50) << ' ' ;
else
cout << setfill(' ') << setw(120) << ' ';
if (mapBlocks[10+i].price != 0)
cout << "|price: " << setfill(' ') << setw(6) << left << mapBlocks[10+i].price << '|' << endl;
else
cout << '|' << setfill(' ') << setw(13) << ' ' << '|' << endl;
if (mapBlocks[35-i].Lv != 0)
cout << "|Lv: " << setfill(' ') << setw(9) << left << mapBlocks[35-i].Lv << '|';
else
cout << '|' << setfill(' ') << setw(13) << ' ' << '|';
if ( i>0 && playerNo-i > -1)
cout << setfill(' ') << setw(40) << ' ' << setw(20) << "Cash on hand: "<< setw(10) << players[i-1].cash << setfill(' ') << setw(50) << ' ' ;
else
cout << setfill(' ') << setw(120) << ' ';
if (mapBlocks[10+i].Lv != 0)
cout << "|Lv: " << setfill(' ') << setw(9) << left << mapBlocks[10+i].Lv << '|' <<endl;
else
cout << '|' << setfill(' ') << setw(13) << ' ' << '|' << endl;
if (players[0].position == 35-i)
cout << '|' << setfill(' ') << setw(6) << left << players[0].name << ' ';
else
cout << "| ";
if (players[1].position == 35-i)
cout << setfill(' ') << setw(6) << left << players[1].name << '|';
else
cout << " |";
if ( i>0 && playerNo-i > -1)
cout << setfill(' ') << setw(40) << ' ' << setw(20) << "Property Owned: " << setw(10) << players[i-1].property << setfill(' ') << setw(50) << ' ' ;
else
cout << setfill(' ') << setw(120) << ' ';
if (players[0].position == 10+i)
cout << '|' << setfill(' ') << setw(6) << left << players[0].name << ' ';
else
cout << "| ";
if (players[1].position == 10+i)
cout << setfill(' ') << setw(6) << left << players[1].name << '|' << endl;
else
cout << " |" << endl;
if (playerNo > 2 && players[2].position == 35-i)
cout << '|' << setfill(' ') << setw(6) << left << players[2].name << ' ';
else
cout << "| ";
if (playerNo > 3 && players[3].position == 35-i)
cout << setfill(' ') << setw(6) << left << players[3].name << '|';
else
cout << " |";
if ( i>0 && playerNo-i > -1)
cout << setfill(' ') << setw(40) << ' ' << setw(20) << "Position: " << setw(20) << mapBlocks[players[i-1].position].name << setfill(' ') << setw(40) << ' ' ;
else
cout << setfill(' ') << setw(120) << ' ';
if (playerNo > 2 && players[2].position == 10+i)
cout << '|' << setfill(' ') << setw(6) << left << players[2].name << ' ';
else
cout << "| ";
if (playerNo > 3 && players[3].position == 10+i)
cout << setfill(' ') << setw(6) << left << players[3].name << '|' << endl;
else
cout << " |" << endl;
cout << setfill('-') << setw(15) << '-' << setfill(' ') << setw(120) << ' ' << setfill('-') << setw(15) << '-' << endl;
}
}
return;
}
| [
"noreply@github.com"
] | WongWingLam.noreply@github.com |
4046a73448de5b0feb448aa8680574d645613981 | 5900a82ac0566b0255a2bcd2a6b100a031656c69 | /sources/modules/levelset/ExplicitIntegration/Terms/TermLaxFriedrichs_cuda_dummy.cpp | 171670f239441757a0451be96204821620f4cab5 | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | HJReachability/beacls | b21381b3725d13ce3d9c0596f3b1ca35cc3a0191 | e3103175d6d325fa096754bd11db4361e6554915 | refs/heads/master | 2023-07-08T16:37:37.383133 | 2023-06-27T14:46:27 | 2023-06-27T14:46:27 | 84,489,492 | 40 | 9 | NOASSERTION | 2023-06-27T14:46:29 | 2017-03-09T21:18:07 | C++ | UTF-8 | C++ | false | false | 740 | cpp | #include <typedef.hpp>
#include <cuda_macro.hpp>
#include <algorithm>
#include "TermLaxFriedrichs_cuda.hpp"
#if !defined(WITH_GPU)
void TermLaxFriedrichs_execute_cuda(
beacls::UVec& ydot_uvec,
const beacls::UVec& diss_uvec,
const beacls::UVec& ham_uvec
) {
FLOAT_TYPE* dst_ydot_ptr = beacls::UVec_<FLOAT_TYPE>(ydot_uvec).ptr();
const FLOAT_TYPE* diss_ptr = beacls::UVec_<FLOAT_TYPE>(diss_uvec).ptr();
const FLOAT_TYPE* ham_ptr = beacls::UVec_<FLOAT_TYPE>(ham_uvec).ptr();
beacls::synchronizeUVec(ham_uvec);
beacls::synchronizeUVec(diss_uvec);
const size_t length = ham_uvec.size();
for (size_t index = 0; index < length; ++index) {
dst_ydot_ptr[index] = diss_ptr[index] - ham_ptr[index];
}
}
#endif /* !defined(WITH_GPU) */
| [
"k-tanabe@berkeley.edu"
] | k-tanabe@berkeley.edu |
0b375c9f6f56eddd278286becc314df304402966 | e016b0b04a6db80b0218a4f095e6aa4ea6fcd01c | /Classes/Native/System_Xml_Mono_Xml_Schema_XmlSchemaUri1295878664.h | 3bf4dc546fc0f0f2b50cbcb912ae92db8bbd931c | [
"MIT"
] | permissive | rockarts/MountainTopo3D | 5a39905c66da87db42f1d94afa0ec20576ea68de | 2994b28dabb4e4f61189274a030b0710075306ea | refs/heads/master | 2021-01-13T06:03:01.054404 | 2017-06-22T01:12:52 | 2017-06-22T01:12:52 | 95,056,244 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,007 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "System_System_Uri19570940.h"
// System.String
struct String_t;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Mono.Xml.Schema.XmlSchemaUri
struct XmlSchemaUri_t1295878664 : public Uri_t19570940
{
public:
// System.String Mono.Xml.Schema.XmlSchemaUri::value
String_t* ___value_36;
public:
inline static int32_t get_offset_of_value_36() { return static_cast<int32_t>(offsetof(XmlSchemaUri_t1295878664, ___value_36)); }
inline String_t* get_value_36() const { return ___value_36; }
inline String_t** get_address_of_value_36() { return &___value_36; }
inline void set_value_36(String_t* value)
{
___value_36 = value;
Il2CppCodeGenWriteBarrier(&___value_36, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"stevenrockarts@gmail.com"
] | stevenrockarts@gmail.com |
851bfedb90c77b2bbc2f8a5043c84523fec2d5e8 | 3ae8fb577d6f34bc94c725b3b7140abacc51047d | /gambit/gambit_driver/src/actuator_RX28.cpp | 4ed1fbbfbdcf0d7911dba9ac3072d3c7eebc825e | [] | no_license | mjyc/gambit-lego-pkg | b25b7831e864bba0f126f64a3d40f412a19664c1 | d2ae2fa4eb09d5e149c0816eabf9213f75b7283f | refs/heads/master | 2022-12-30T17:11:30.768639 | 2013-09-03T22:02:21 | 2013-09-03T22:02:21 | 306,082,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,317 | cpp | /**
* @file
* @author Brian D. Mayton <bmayton@bdm.cc>
* @version 1.0
*
* @section LICENSE
*
* Copyright (c) 2010, Intel Labs Seattle
* 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 Intel Labs Seattle nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @section DESCRIPTION
*
* An implementation of Actuator for Dynamixel RX-28 (and similar) servomotors.
*/
#include <ros/ros.h>
#include <gambit_driver/actuator_RX28.h>
namespace gambit_driver {
ActuatorRX28::ActuatorRX28(bus::Interface *iface, unsigned int node_id) {
rx28 = new dynamixel::RX28(iface, node_id);
if(!rx28) {
ROS_FATAL("Unable to create actuator (out of memory?)");
throw "out of memory";
}
}
ActuatorRX28::~ActuatorRX28() {
delete rx28;
}
double ActuatorRX28::get_position() {
return rx28->get_position();
}
double ActuatorRX28::get_velocity() {
return rx28->get_speed() * RX28_SPEED_CONVERSION;
}
double ActuatorRX28::get_torque() {
return rx28->get_load() * RX28_MAX_TORQUE / rx28->get_torque_limit();
}
bool ActuatorRX28::ping() {
return rx28->ping();
}
void ActuatorRX28::set_torque_enabled(bool enabled) {
rx28->set_torque_enabled(enabled);
}
void ActuatorRX28::read_status() {
rx28->read_status();
uint8_t status = rx28->get_status();
if(status != 0) {
double since_last_warning = (ros::Time::now() - last_error_warning).toSec();
if(since_last_warning > 5.0 || last_error_state != status) {
if(status & dynamixel::StatusPacket::ERR_INSTRUCTION)
ROS_ERROR("Bad instruction for actuator on joint %d", DOFs[0]->get_index());
if(status & dynamixel::StatusPacket::ERR_OVERLOAD)
ROS_ERROR("Actuator on joint %d is overloaded", DOFs[0]->get_index());
if(status & dynamixel::StatusPacket::ERR_CHECKSUM)
ROS_ERROR("Bad checksum for actuator on joint %d", DOFs[0]->get_index());
if(status & dynamixel::StatusPacket::ERR_RANGE)
ROS_ERROR("Range error for actuator on joint %d", DOFs[0]->get_index());
if(status & dynamixel::StatusPacket::ERR_OVERHEAT)
ROS_ERROR("Actuator on joint %d is overheating", DOFs[0]->get_index());
if(status & dynamixel::StatusPacket::ERR_ANGLE_LIMIT)
ROS_ERROR("Angle limit error for actuator on joint %d", DOFs[0]->get_index());
if(status & dynamixel::StatusPacket::ERR_VOLTAGE)
ROS_ERROR("Invalid supply voltage to actuator on joint %d",
DOFs[0]->get_index());
last_error_warning = ros::Time::now();
last_error_state = status;
}
} else {
last_error_state = 0;
}
}
void ActuatorRX28::send_control() {
rx28->set_position(get_cmd_position());
}
bool ActuatorRX28::set_property(DOFProperty &p) {
if(p.property_name == "TORQUE_LIMIT") {
if(p.float_value > RX28_MAX_TORQUE) p.float_value = RX28_MAX_TORQUE;
else if(p.float_value < 0.0) p.float_value = 0.0;
int tlim = (int)round(p.float_value * 1023.0 / RX28_MAX_TORQUE);
rx28->set_torque_limit(tlim);
return true;
} else if(p.property_name == "COMPLIANCE_MARGIN") {
if(p.int_value > 254) p.int_value = 254;
if(p.int_value < 0) p.int_value = 0;
rx28->set_compliance_margin(p.int_value);
return true;
} else if(p.property_name == "COMPLIANCE_SLOPE") {
if(p.int_value > 254) p.int_value = 254;
if(p.int_value < 0) p.int_value = 0;
rx28->set_compliance_slope(p.int_value);
return true;
} else if(p.property_name == "COMPLIANCE_PUNCH") {
if(p.int_value > 1023) p.int_value = 1023;
if(p.int_value < 0) p.int_value = 0;
rx28->set_punch(p.int_value);
return true;
}
return false;
}
void ActuatorRX28::get_properties(std::vector<DOFProperty> &properties) {
unsigned int idx = DOFs[0]->get_index();
DOFProperty p_compl_margin;
p_compl_margin.DOF_index = idx;
p_compl_margin.property_name="COMPLIANCE_MARGIN";
p_compl_margin.display_name="Margin";
p_compl_margin.type="int";
p_compl_margin.rw="rw";
p_compl_margin.int_value = rx28->get_compliance_margin();
properties.push_back(p_compl_margin);
DOFProperty p_compl_slope;
p_compl_slope.DOF_index = idx;
p_compl_slope.property_name="COMPLIANCE_SLOPE";
p_compl_slope.display_name="Slope";
p_compl_slope.type="int";
p_compl_slope.rw="rw";
p_compl_slope.int_value = rx28->get_compliance_slope();
properties.push_back(p_compl_slope);
DOFProperty p_compl_punch;
p_compl_punch.DOF_index = idx;
p_compl_punch.property_name="COMPLIANCE_PUNCH";
p_compl_punch.display_name="Punch";
p_compl_punch.type="int";
p_compl_punch.rw="rw";
p_compl_punch.int_value = rx28->get_punch();
properties.push_back(p_compl_punch);
DOFProperty p_torque_limit;
p_torque_limit.DOF_index = idx;
p_torque_limit.property_name="TORQUE_LIMIT";
p_torque_limit.display_name="Torque";
p_torque_limit.type="float";
p_torque_limit.rw="rw";
p_torque_limit.float_value = rx28->get_torque_limit() * RX28_MAX_TORQUE / 1024.0;
properties.push_back(p_torque_limit);
DOFProperty p_voltage;
p_voltage.DOF_index = idx;
p_voltage.property_name="VOLTAGE";
p_voltage.display_name="Voltage";
p_voltage.type="float";
p_voltage.rw="r";
p_voltage.float_value = rx28->get_voltage();
properties.push_back(p_voltage);
DOFProperty p_temperature;
p_temperature.DOF_index = idx;
p_temperature.property_name="TEMPERATURE";
p_temperature.display_name="Temp.";
p_temperature.type="int";
p_temperature.rw="r";
p_temperature.int_value = (int)round(rx28->get_temperature());
properties.push_back(p_temperature);
}
}
| [
"mjyc@cs.washington.edu"
] | mjyc@cs.washington.edu |
9e7ee6f83d6c9a6b11bd8f0c874fc1b2c8fc64bd | 479aacc339f9b1d38fa0cc2a3888036d8a1c6c6b | /Clases - AdministracionDelTiempo/main.ino | 02df2dc9cd4743bcd5bc967ab25fd149e633efc7 | [] | no_license | ComputadorasElectronicas/sprenna | 222912cbab8e53550952f8ffe768d2a56c6b6d46 | 60528c65c96ce90d95d9d50447e3b5a46e21b2f2 | refs/heads/main | 2023-07-15T18:05:14.231590 | 2021-08-27T20:03:11 | 2021-08-27T20:03:11 | 383,602,508 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,823 | ino |
#include "ContadorSimple.h"
// TODO: ver esto
#define PULSADOR_CUENTA 3
#define PULSADOR_INGRESO_SERIAL 4
#define LED_BLINK 5
#define LED_INDICADOR 6
int referencia;
boolean flagPulsadorCuenta;
boolean flagIngresandoEntero;
String cadenaDeCaracteres;
int contadorDeLoopParaImpresion;
//--------------------
#define PERIODO_DE_LA_TAREA_IMPRESION 2000
unsigned long ultimaEjecucionDeLaTareaImpresion = 0;
//--------------------
#define PERIODO_DE_LA_TAREA_BLINK 200
unsigned long ultimaEjecucionDeLaTareaBlink = 0;
//--------------------
ContadorSimple contador = ContadorSimple();
void setup()
{
Serial.begin(9600);
pinMode(0, INPUT);
pinMode(1, OUTPUT);
Serial.setTimeout(100000);
pinMode(3, INPUT);
pinMode(4, INPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
contador.Reset();
referencia = 0;
flagPulsadorCuenta = false;
flagIngresandoEntero = false;
cadenaDeCaracteres = "";
contadorDeLoopParaImpresion = 0;
}
void loop()
{
// Cuenta de pulsaciones sin bloqueo del programa
// Cuenta una sola vez por pulsacion...
if (digitalRead(PULSADOR_CUENTA) == LOW)
{
if (flagPulsadorCuenta == false)
{
contador.Inc();
flagPulsadorCuenta = true;
}
}
else
{
flagPulsadorCuenta = false;
}
//------------------------------------------------------------------------------
// Ingresar numero cuando se pulsa el otro pulsador...
//------------------------------------------------------------------------------
// Primero, si no esta en el modo de ingresar, y se pulsa, inicializa todo
// lo necesario para adquirir el numero
// y hace true la bandera que indica que esta en el proceso de adquisicion.
if ((digitalRead(PULSADOR_INGRESO_SERIAL) == LOW) && (flagIngresandoEntero == false))
{
Serial.println("Ingrese el valor de referencia: ");
cadenaDeCaracteres = "";
flagIngresandoEntero = true;
while (Serial.available() > 0)
{
char c = Serial.read();
c++;
}
}
// Si esta en el proceso de adquisicion, mientras haya caracteres NUMERICOS
// en Serial, los lee y va armando una cadena de caracteres.
// Cuando se recibe algo NO numerico, hace la conversion de String a Int
// y "apaga" el modo de adquisicion.
if (flagIngresandoEntero == true)
{
while (Serial.available() > 0)
{
char c = Serial.read();
if ((c <= '9') && (c >= '0'))
{
cadenaDeCaracteres = cadenaDeCaracteres + c;
}
else
{
referencia = cadenaDeCaracteres.toInt();
flagIngresandoEntero = false;
}
}
}
//------------------------------------------------------------------------------
unsigned long ahora = millis();
if (ahora - ultimaEjecucionDeLaTareaImpresion >= PERIODO_DE_LA_TAREA_IMPRESION)
{
ultimaEjecucionDeLaTareaImpresion = ahora;
Serial.println("Tiempo seg: " + String(ahora / 1000.0));
Serial.println("Referencia: " + String(referencia));
Serial.println("Cuenta: " + String(contador.CuentaActual()));
Serial.println("-----------------");
}
ahora = millis();
if (ahora - ultimaEjecucionDeLaTareaBlink >= PERIODO_DE_LA_TAREA_BLINK)
{
ultimaEjecucionDeLaTareaBlink = ahora;
if (digitalRead(LED_BLINK) == HIGH)
{
digitalWrite(LED_BLINK, LOW);
}
else
{
digitalWrite(LED_BLINK, HIGH);
}
}
if(contador.CuentaActual() > referencia){
digitalWrite(LED_INDICADOR, HIGH);
}else{
digitalWrite(LED_INDICADOR, LOW);
}
}
| [
"secpre@hotmail.com"
] | secpre@hotmail.com |
776b06bbe52e40a57ba893288497426032196b4f | ab08c7d474c3b8b91bedef9ec198ecd822ddf86d | /cubeEncryptor/encryptor.h | fdf7d5a7e90fa61c6890843edd3cc50cab9c5f0d | [] | no_license | narekmartiros/Daily-projects | 794ae01c487c35a47c6affc3c9f55b0b8c15ec8e | 0a8333b2306243d50bdcb135fab51705a182bcc0 | refs/heads/main | 2023-05-24T13:10:16.236670 | 2021-06-15T14:39:33 | 2021-06-15T14:39:33 | 375,952,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | h |
#ifndef ENCRYPTOR
#define ENCRYPTOR
#include "cube.h"
#include <vector>
#include <fstream>
#include <iostream>
#include <time.h>
#include <algorithm>
class encryptor{
public:
void splitter(const std::string& filename);
int encryptor_size();
cube& get_cube(int index);
std::string rot_dir();
void encrypt();
void save_encryption(const std::string& filename);
void save_key(const std::string& filename);
private:
std::ifstream file1;
std::vector<cube> m_enc;
std::vector<std::string> m_splitted;
};
#endif // encryptor | [
"noreply@github.com"
] | narekmartiros.noreply@github.com |
5788e37956978e059a3939fae2b7de3c049ec5d7 | cdea87e9889ce65e81d66c3f6df3199747c86609 | /src/CascadedMetadata.cpp | 9017ab108ae8312c79a50521519aaa5e361674f0 | [] | permissive | nsakharnykh/nvcomp | ebdfc4fbf9fcf2cb2c2b931e163cca65be1794f5 | 8640ba9d4f4916ff5e12fbbe3b03617518f551d4 | refs/heads/main | 2023-04-23T03:09:15.309774 | 2020-12-19T18:36:01 | 2020-12-19T18:36:01 | 323,417,590 | 0 | 0 | BSD-3-Clause | 2020-12-21T18:31:31 | 2020-12-21T18:31:31 | null | UTF-8 | C++ | false | false | 8,311 | cpp | /*
* Copyright (c) 2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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.
*/
#include "CascadedMetadata.h"
#include "common.h"
#include "CascadedCommon.h"
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <iostream>
namespace nvcomp
{
/******************************************************************************
* CONSTANTS ******************************************************************
*****************************************************************************/
using Header = CascadedMetadata::Header;
namespace
{
constexpr const size_t NULL_OFFSET = static_cast<size_t>(-1);
}
/******************************************************************************
* CONSTRUCTORS / DESTRUCTOR **************************************************
*****************************************************************************/
CascadedMetadata::CascadedMetadata(
const nvcompCascadedFormatOpts opts,
const nvcompType_t type,
const size_t uncompressedBytes,
const size_t compressedBytes) :
Metadata(type, uncompressedBytes, compressedBytes, COMPRESSION_ID),
m_formatOpts(opts),
m_headers(),
m_dataOffsets(),
m_dataType(),
m_isSaved()
{
if (static_cast<size_t>(m_formatOpts.num_RLEs) > MAX_NUM_RLES) {
throw std::runtime_error(
"Invalid number of RLEs: " + std::to_string(m_formatOpts.num_RLEs)
+ ", maximum is " + std::to_string(MAX_NUM_RLES));
}
initialize();
}
/******************************************************************************
* PUBLIC METHODS *************************************************************
*****************************************************************************/
int CascadedMetadata::getNumRLEs() const
{
return m_formatOpts.num_RLEs;
}
int CascadedMetadata::getNumDeltas() const
{
return m_formatOpts.num_deltas;
}
unsigned int CascadedMetadata::getNumInputs() const
{
// Determine the number of unique data id's that will be present in the
// compressed data. Currently, the input data gets assigned a value of 0,
// each RLE produces a runs and values which each take an id, and delta also
// produces a values which takes an id. Bitpacking is not treated as a layer
// unless it is the only present operation, which is what the 'max' below is
// for.
return static_cast<unsigned int>(
std::max(1, m_formatOpts.num_RLEs * 2 + m_formatOpts.num_deltas) + 1);
}
bool CascadedMetadata::useBitPacking() const
{
return m_formatOpts.use_bp;
}
void CascadedMetadata::setHeader(const size_t index, const Header header)
{
if (index >= getNumInputs()) {
throw std::runtime_error(
"Invalid header index to set: " + std::to_string(index) + " / "
+ std::to_string(getNumInputs()));
}
assert(index < m_headers.size());
m_headers[index] = header;
}
void CascadedMetadata::setDataOffset(const size_t index, const size_t offset)
{
if (index >= getNumInputs()) {
throw std::runtime_error(
"Invalid data index to set: " + std::to_string(index) + " / "
+ std::to_string(getNumInputs()));
}
m_dataOffsets[index] = offset;
}
Header CascadedMetadata::getHeader(const size_t index) const
{
if (index >= getNumInputs()) {
throw std::runtime_error(
"Invalid header index to set: " + std::to_string(index) + " / "
+ std::to_string(getNumInputs()));
}
assert(index < m_headers.size());
return m_headers[index];
}
size_t CascadedMetadata::getNumElementsOf(const size_t index) const
{
return m_headers[index].length;
}
size_t CascadedMetadata::getDataOffset(const size_t index) const
{
if (index >= getNumInputs()) {
throw std::runtime_error(
"Invalid data index to set: " + std::to_string(index) + " / "
+ std::to_string(getNumInputs()));
}
const size_t offset = m_dataOffsets[index];
if (offset == NULL_OFFSET) {
throw std::runtime_error(
"Cannot get data offset which has not been set: "
+ std::to_string(index));
}
return offset;
}
bool CascadedMetadata::haveAnyOffsetsBeenSet() const
{
for (const size_t offset : m_dataOffsets) {
if (offset != NULL_OFFSET) {
return true;
}
}
return false;
}
bool CascadedMetadata::haveAllOffsetsBeenSet() const
{
for (const size_t offset : m_dataOffsets) {
if (offset == NULL_OFFSET) {
return false;
}
}
return true;
}
bool CascadedMetadata::isSaved(const size_t index) const
{
if (index >= getNumInputs()) {
throw std::runtime_error(
"Invalid data index to check if saved: " + std::to_string(index) + " / "
+ std::to_string(getNumInputs()));
}
return m_isSaved[index];
}
nvcompType_t CascadedMetadata::getDataType(size_t index) const
{
if (index >= getNumInputs()) {
throw std::runtime_error(
"Invalid data index to get type of: " + std::to_string(index) + " / "
+ std::to_string(getNumInputs()));
}
return m_dataType[index];
}
/******************************************************************************
* PRIVATE METHODS ************************************************************
*****************************************************************************/
void CascadedMetadata::initialize()
{
m_headers.resize(getNumInputs());
m_dataOffsets.resize(getNumInputs(), NULL_OFFSET);
m_dataType.resize(getNumInputs(), getValueType());
m_isSaved.resize(getNumInputs(), false);
// fill out data based on tree
const int numRLEs = getNumRLEs();
const int numDeltas = getNumDeltas();
const bool bitPacking = useBitPacking();
int vals_id = 0;
const int numSteps = std::max(numRLEs, numDeltas);
for (int r = numSteps - 1; r >= 0; r--) {
int nextValId;
if (numSteps - r - 1 < numRLEs) {
const int runId = ++vals_id;
const int valId = ++vals_id;
// rle
if (numRLEs - 1 - r < numDeltas) {
// delta
nextValId = ++vals_id;
} else {
nextValId = valId;
}
// save runs output `runId`
m_isSaved[runId] = true;
if (bitPacking) {
m_dataType[runId] = NVCOMP_TYPE_BITS;
} else {
m_dataType[runId] = selectRunsType(getNumUncompressedElements());
}
} else {
// delta only
nextValId = ++vals_id;
}
if (r == 0) {
// save last layer `nextValId`
m_isSaved[nextValId] = true;
if (bitPacking) {
m_dataType[nextValId] = NVCOMP_TYPE_BITS;
} else {
m_dataType[nextValId] = getValueType();
}
}
}
// If there are no RLEs or Deltas, we will do a single BP step.
if (numRLEs == 0 && numDeltas == 0) {
const int nextValId = ++vals_id;
// bit pack `nextValId`
m_isSaved[nextValId] = true;
m_dataType[nextValId] = NVCOMP_TYPE_BITS;
}
}
} // namespace nvcomp
| [
"dlasalle@nvidia.com"
] | dlasalle@nvidia.com |
3573b2b459f7ac73acb486a0118eecd46929407e | 9598f48703820d9c2e263cb8864226eeb13332bf | /uri/Right_Area.cpp | c5e97a5fa7c3c4df14c8620e3e7f412aa9819fe8 | [] | no_license | leiverandres/programming-contest | 4da6343119290b480757435788ff90d950492ff9 | 66cfb41326b0d35abbe70634976176446cb0fa63 | refs/heads/master | 2021-01-15T08:59:18.035112 | 2016-10-22T16:54:01 | 2016-10-22T16:54:20 | 45,351,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 398 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie();
char op;
cin >> op;
double aux, sum = 0;
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
cin >> aux;
if (i < j and (i+j) >= 12)
sum += aux;
}
}
cout << fixed << setprecision(1) << ((op == 'S')? sum: sum/30.0) << endl;
return 0;
}
| [
"leiverandres04p@hotmail.com"
] | leiverandres04p@hotmail.com |
b143b61fa0dcbc472d7e7a507730ad102e1d9704 | 240406279c9f3c271678d485f57e7944c98acaad | /etc/zmac/zi80dis.h | bceb9a977acb995292e01c95810f570654716beb | [
"Apache-2.0"
] | permissive | hallorant/bigmit | 7eb5bc0c1c2a56e86fcd0631bb91454bf13290f9 | 80f077ee4075e8bd01205896e003553017d5f5ab | refs/heads/master | 2023-07-06T03:26:38.935561 | 2023-07-03T19:32:13 | 2023-07-03T19:32:13 | 208,386,483 | 13 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,291 | h | //
// zi80dis.h - extract disassembly and timing information for Z-80 and 8080 instructions.
//
// The Zi80dis class is little more than a bag of values filled in when Disassemble()
// is called. For most programs "mem" points to the start of the Z-80's memory and the
// instruction to disassemble is at mem + pc. Passing "true" for the 3rd argument means
// "mem" points to the start of the instruction. In this case the caller needs to
// guarantee or at least check that sufficient data is available.
//
// Call Format() to output the disassembled instruction in a reasonably generic way.
// Advanced disassemblers will want to replace the %s arguments in m_format with
// symbolic names as directed by the associated m_arg[] and m_argType[] values.
//
#if defined(__cplusplus)
class Zi80dis
{
public:
Zi80dis();
// Don't re-order these or you'l break zmac.
enum Processor {
proc8080,
procZ80,
procZ180
};
void SetProcessor(Processor proc); // default is procZ80
void SetAssemblerable(bool assemblerable); // default true, slightly alters Format() output
void SetDollarHex(bool dollarhex); // default false, prints hex constants with $ notation
void SetUndocumented(bool undoc); // default false, does not disassemble undocumented instructions
void Disassemble(const unsigned char *mem, int pc, bool memPointsToInstruction = false);
void Format(char *outputBuffer);
bool IsUndefined();
enum ArgType {
argByte, // byte constant
argWord, // word constant
argAddress, // memory address
argRelative, // relative jump (but value is a memory address not an offset)
argCall, // call address
argRst, // restart address
argIndex, // IX or IY index offset
argPort // I/O port
};
// Data resulting from call to Disassemble()
int m_length; // length of instruction in bytes
int m_maxT; // maximum number of T states to execute on z80
int m_minT; // minimum number of T states to execute on z80
int m_max8080T; // maximum number of T states to execute on 8080
int m_min8080T; // minimum number of T states to execute on 8080
int m_max180T; // maximum number of T states to execute on z180
int m_min180T; // minimum number of T states to execute on z180
int m_ocf; // number of opcode fetches (M1 states)
char m_format[16]; // format string for disassembly
int m_numArg; // number of arguments
int m_arg[2]; // decoded arguments
ArgType m_argType[2]; // type of argument
bool m_neverNext; // processor never proceeds to the following instruction
int m_stableMask; // bit set for each byte of instruction invariant to relocation
int m_attrMask; // bit set indicating read/write/byte/word/in/out/jp/jr/jp(rr) (see AttrBit)
enum AttrBit {
attrRead = 1,
attrWrite = 2,
attrByte = 4,
attrWord = 8,
attrIn = 16,
attrOut = 32,
attrJump = 64,
attrBranch = 128,
attrCall = 256,
attrRst = 512,
attrJumpReg = 1024
};
// Options.
Processor m_processor;
bool m_assemblerable;
bool m_dollarhex;
bool m_undoc;
};
#else
// For the one holdout still using C (zmac).
int zi_tstates(const unsigned char *inst, int proc, int *low, int *high, int *ocf);
#endif /* defined(__cplusplus) */
| [
"hallorant@gmail.com"
] | hallorant@gmail.com |
c469d2a20ca036a1c854fc1a3dd67a86b43463ae | d443ca6a0f68ebc845dc652e221d02844b9889aa | /TP7_refait/max.cpp | 2f5a8583343afbb598d1a263023ed675477a96e3 | [] | no_license | JulietteNdn/CPlusPlus_TP | 66ec1332cad3690dafa881084f724cd17588733b | fa3aeecb9db3da79680929593452fffc9e88b5a5 | refs/heads/master | 2020-04-05T00:53:11.950831 | 2018-12-01T16:02:48 | 2018-12-01T16:02:48 | 156,414,365 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 258 | cpp | #include <iostream>
#include <stdexcept>
using namespace std;
template <typename T>
const T& maxi(const T& a, const T & b){
return ((a>b)? a : b);
}
int main(int, char**){
cout << maxi(4,7) << endl;
cout << maxi(3.0,1.0) << endl;
return 0;
}
| [
"juliette-naudin@live.fr"
] | juliette-naudin@live.fr |
5ef8888d4486ca439936cdaa9006f3f1ba759660 | ddf9c40b06eb465bc89fb728d014c260ca0c4bf4 | /src/main_window.cpp | 4981910779ad768114fdc25c311bd56c7b96333b | [
"MIT"
] | permissive | kriolog/laser_painter | ae33bbc70ee682bff2bbbe167cf0671a383dcd46 | 392deae6b8f939ddbaec8cd15c753b3e5098b5f9 | refs/heads/master | 2021-01-19T08:31:44.861370 | 2017-04-08T15:29:57 | 2017-04-08T15:29:57 | 87,641,144 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,240 | cpp | #include "main_window.h"
#include <QSettings>
#include <QAction>
#include <QActionGroup>
#include <QMenuBar>
#include <QShortcut>
#include <QHBoxLayout>
#include <QKeySequence>
#include <QDockWidget>
#include <QVBoxLayout>
#include <QStatusBar>
#include "video_frame_grabber.h"
#include "camera_settings.h"
#include "image_modifier.h"
#include "laser_detector.h"
#include "point_modifier.h"
#include "laser_detector_settings.h"
#include "laser_detector_calibration_dialog.h"
#include "roi_image_widget.h"
#include "track_widget.h"
#include "tracker_settings.h"
namespace laser_painter {
MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags)
: QMainWindow(parent, flags)
{
QSettings settings;
setWindowTitle(tr("Laser Tracker"));
setMinimumSize(1024, 768);
setFixedSize(settings.value("MainWindow/window_size", minimumSize()).toSize());
createActions();
createMenus();
createWidgets();
}
void MainWindow::createActions()
{
_exit_act = new QAction(QIcon::fromTheme("application-exit"), tr("E&xit"), this);
_exit_act->setShortcuts(QKeySequence::Quit);
_exit_act->setStatusTip(tr("Exit application"));
connect(_exit_act, &QAction::triggered, this, &MainWindow::close);
// Streams are the camera capture and the lasetr tracker
QActionGroup* streams_gp = new QActionGroup(this);
connect(streams_gp, &QActionGroup::triggered, this, &MainWindow::updateStreamsVisibility);
streams_gp->setExclusive(true);
_camera_capture_act = new QAction(tr("Camera Capture"), streams_gp);
_camera_capture_act->setShortcut(QKeySequence(tr("Ctrl+1", "ShowCamera")));
_camera_capture_act->setCheckable(true);
_camera_capture_act->setChecked(false);
_laser_tracker_act = new QAction(tr("Laser Tracker"), streams_gp);
_laser_tracker_act->setShortcut(QKeySequence(tr("Ctrl+2", "ShowTracker")));
_laser_tracker_act->setCheckable(true);
_laser_tracker_act->setChecked(false);
_camera_tracker_act = new QAction(tr("Both Camera and Tracker"), streams_gp);
_camera_tracker_act->setShortcut(QKeySequence(tr("Ctrl+3", "ShowCameraAndTracker")));
_camera_tracker_act->setCheckable(true);
_camera_tracker_act->setChecked(true);
_full_screen_act = new QAction(tr("Full-screen Mode"), this);
_full_screen_act->setCheckable(true);
_full_screen_act->setShortcut(QKeySequence(tr("Ctrl+F", "ToggleFullScreenExitFullScreen")));
_exit_act->setStatusTip(tr("Press Esc to exit fulls screen mode"));
connect(_full_screen_act, &QAction::triggered, this, &MainWindow::toggleFullScreen);
connect(
new QShortcut(QKeySequence(tr("Escape", "ExitFullScreen")), this), SIGNAL(activated()),
this, SLOT(toggleFullScreen())
);
}
void MainWindow::createMenus()
{
_file_mu = menuBar()->addMenu(tr("&File"));
_file_mu->addAction(_exit_act);
_view_mu = menuBar()->addMenu(tr("&View"));
_view_mu->addAction(_camera_capture_act);
_view_mu->addAction(_laser_tracker_act);
_view_mu->addAction(_camera_tracker_act);
_view_mu->addSeparator();
_view_mu->addAction(_full_screen_act);
// Force actions to work when menu is hidden
addAction(_camera_capture_act);
addAction(_laser_tracker_act);
addAction(_camera_tracker_act);
addAction(_full_screen_act);
}
void MainWindow::createWidgets()
{
VideoFrameGrabber* video_frame_grabber = new VideoFrameGrabber(this);
_camera_settings = new CameraSettings(video_frame_grabber);
_roi_image_wgt = new ROIImageWidget();
connect(video_frame_grabber, &VideoFrameGrabber::frameAvailable, _roi_image_wgt, &ROIImageWidget::setImage);
ImageModifier* image_modifier = new ImageModifier(this);
connect(_roi_image_wgt, SIGNAL(roiChanged(const QRect&, const QSize&)), image_modifier, SLOT(setROI(const QRect&)));
connect(video_frame_grabber, &VideoFrameGrabber::frameAvailable, image_modifier, &ImageModifier::run);
LaserDetector* laser_detector = new LaserDetector(this);
connect(image_modifier, &ImageModifier::imageAvailable, laser_detector, &LaserDetector::run);
PointModifier* point_modifier = new PointModifier(this);
connect(_roi_image_wgt, SIGNAL(roiChanged(const QRect&, const QSize&)), point_modifier, SLOT(setROI(const QRect&)));
connect(laser_detector, &LaserDetector::laserPosition, point_modifier, &PointModifier::run);
_track_widget = new TrackWidget();
connect(point_modifier, SIGNAL(pointAvailable(const QPointF&, bool)), _track_widget, SLOT(addTip(const QPointF&, bool)));
connect(_camera_settings, &CameraSettings::resolutionChanged, _track_widget, &TrackWidget::setCanvasSize);
_track_widget->setCanvasSize(_camera_settings->currentResolution());
_laser_detector_calibration_dialog = new LaserDetectorCalibrationDialog(laser_detector, this);
_laser_detector_settings = new LaserDetectorSettings(_laser_detector_calibration_dialog);
connect(_laser_detector_settings, &LaserDetectorSettings::scaleChanged, image_modifier, &ImageModifier::setScale);
connect(_laser_detector_settings, &LaserDetectorSettings::scaleChanged, point_modifier, &PointModifier::setUnscale);
_laser_detector_settings->emitScaleChanged();
_tracker_settings = new TrackerSettings(_track_widget);
QHBoxLayout* central_widget_lo = new QHBoxLayout();
central_widget_lo->setMargin(0);
central_widget_lo->setSpacing(0);
central_widget_lo->addWidget(_roi_image_wgt);
central_widget_lo->addWidget(_track_widget);
QWidget* central_wgt = new QWidget();
central_wgt->setLayout(central_widget_lo);
setCentralWidget(central_wgt);
// Put settings to a dockable widget
QWidget* settings_wgt = new QWidget();
QVBoxLayout* settings_lo = new QVBoxLayout();
settings_wgt->setLayout(settings_lo);
settings_lo->addWidget(_camera_settings);
settings_lo->addWidget(_laser_detector_settings);
settings_lo->addWidget(_tracker_settings);
settings_lo->addStretch();
_settings_dk = new QDockWidget(tr("Settings"), this);
_settings_dk->setFeatures(QDockWidget::DockWidgetMovable);
_settings_dk->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
_settings_dk->setWidget(settings_wgt);
addDockWidget(Qt::LeftDockWidgetArea, _settings_dk);
setStatusBar(new QStatusBar());
connect(video_frame_grabber, &VideoFrameGrabber::warning, this, &MainWindow::showWarning);
connect(laser_detector, &LaserDetector::warning, this, &MainWindow::showWarning);
}
void MainWindow::updateStreamsVisibility(QAction* stream_act)
{
if(stream_act == _camera_capture_act) {
_roi_image_wgt->setVisible(true);
_track_widget->setVisible(false);
} else if (stream_act == _laser_tracker_act) {
_roi_image_wgt->setVisible(false);
_track_widget->setVisible(true);
} else if (stream_act == _camera_tracker_act) {
_roi_image_wgt->setVisible(true);
_track_widget->setVisible(true);
} else {
Q_ASSERT(false);
}
}
void MainWindow::toggleFullScreen(bool enable)
{
if(enable) {
menuBar()->hide();
_settings_dk->hide();
setWindowState(Qt::WindowFullScreen);
if(_full_screen_act->isChecked())
_full_screen_act->setChecked(true);
} else {
menuBar()->show();
_settings_dk->show();
setWindowState(Qt::WindowNoState);
if(_full_screen_act->isChecked())
_full_screen_act->setChecked(false);
}
}
void MainWindow::showWarning(const QString& text)
{
Q_ASSERT(statusBar());
statusBar()->setStyleSheet("QStatusBar{padding-left:8px;;color:red;}");
statusBar()->showMessage(text, 5000);
}
void MainWindow::writeSettings()
{
QSettings settings;
_camera_settings->writeSettings();
_laser_detector_settings->writeSettings();
_laser_detector_calibration_dialog->writeSettings();
_tracker_settings->writeSettings();
settings.beginGroup("MainWindow");
settings.setValue("window_size", size());
settings.endGroup();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
writeSettings();
QMainWindow::closeEvent(event);
_laser_detector_calibration_dialog->deleteLater();
}
} // namespace laser_painter | [
"kriolog@gmail.com"
] | kriolog@gmail.com |
31e8323fdfc7082ac25590a7e446fd7d61ff674e | bd6e36612cd2e00f4e523af0adeccf0c5796185e | /src/core/initializeClassesWithWx.cc | 4f479edbb99f4b1aac3cdc98b9455d6247b773a2 | [] | no_license | robert-strandh/clasp | 9efc8787501c0c5aa2480e82bb72b2a270bc889a | 1e00c7212d6f9297f7c0b9b20b312e76e206cac2 | refs/heads/master | 2021-01-21T20:07:39.855235 | 2015-03-27T20:23:46 | 2015-03-27T20:23:46 | 33,315,546 | 1 | 0 | null | 2015-04-02T15:13:04 | 2015-04-02T15:13:04 | null | UTF-8 | C++ | false | false | 1,457 | cc | /*
File: initializeClassesWithWx.cc
*/
/*
Copyright (c) 2014, Christian E. Schafmeister
CLASP is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
See directory 'clasp/licenses' for full details.
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 <clasp/core/foundation.h>
#include <clasp/core/package.h>
#include <clasp/core/lisp.h>
#include <wxWidgetsExpose.h>
namespace core
{
//
// Initialize classes with WxWidgets
//
void initializePackagesAndClasses(Lisp_sp lisp)
{
lisp->makePackage(WxPackage);
#define Use_CorePkg
#define Use_MbbPackage
#define Use_WxPackage
#include <core_initClasses_inc.h>
lisp->installGlobalInitializationCallback(initializeWxWidgetsConstants);
};
};
| [
"chris.schaf@verizon.net"
] | chris.schaf@verizon.net |
6d3f2678c4953ddc4cbd89ed646da164c313f94a | 355fd721b8e51f1099713810f07e94f2e02f7d7c | /shadow learn material/advanced-shadows/GraphicsEngine/include/Qhull/cpp/Coordinates.h | 774fd4819d8ef4a9db54672602331319b8023d06 | [] | no_license | liangshiweigithub/update | bbfd1f40d6f714198468585b928bb01fa85cf8ba | 3a9a7e2dd4afaffcc3cdf7ff9292ed6fcd01e138 | refs/heads/master | 2023-07-20T05:19:40.586753 | 2023-07-17T15:50:28 | 2023-07-17T15:50:28 | 186,344,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,506 | h | /****************************************************************************
**
** Copyright (C) 2009-2010 C.B. Barber. All rights reserved.
** $Id: //product/qhull/main/rel/cpp/Coordinates.h#36 $$Change: 1193 $
** $DateTime: 2010/01/23 11:31:35 $$Author: bbarber $
**
****************************************************************************/
#ifndef QHCOORDINATES_H
#define QHCOORDINATES_H
#include "QhullError.h"
#include "QhullIterator.h"
extern "C" {
#include "../src/qhull_a.h"
};
#include <cstddef> // ptrdiff_t, size_t
#include <ostream>
#include <vector>
namespace orgQhull {
#//Types
//! an allocated vector of point coordinates
//! Used by PointCoordinates for RboxPoints
//! A QhullPoint refers to previously allocated coordinates
class Coordinates;
class MutableCoordinatesIterator;
class Coordinates {
private:
#//Fields
std::vector<coordT> coordinate_array;
public:
#//Subtypes
class const_iterator;
class iterator;
typedef iterator Iterator;
typedef const_iterator ConstIterator;
typedef coordT value_type;
typedef const value_type *const_pointer;
typedef const value_type &const_reference;
typedef value_type *pointer;
typedef value_type &reference;
typedef ptrdiff_t difference_type;
typedef int size_type;
#//Construct
Coordinates() {};
explicit Coordinates(const std::vector<coordT> &other) : coordinate_array(other) {}
Coordinates(const Coordinates &other) : coordinate_array(other.coordinate_array) {}
Coordinates &operator=(const Coordinates &other) { coordinate_array= other.coordinate_array; return *this; }
Coordinates &operator=(const std::vector<coordT> &other) { coordinate_array= other; return *this; }
~Coordinates() {}
#//Conversion
coordT *data() { return isEmpty() ? 0 : &at(0); }
const coordT *data() const { return const_cast<const pointT*>(isEmpty() ? 0 : &at(0)); }
#ifndef QHULL_NO_STL
std::vector<coordT> toStdVector() const { return coordinate_array; }
#endif //QHULL_NO_STL
#ifdef QHULL_USES_QT
QList<coordT> toQList() const;
#endif //QHULL_USES_QT
#//GetSet
int count() const { return static_cast<int>(size()); }
bool empty() const { return coordinate_array.empty(); }
bool isEmpty() const { return empty(); }
bool operator==(const Coordinates &other) const { return coordinate_array==other.coordinate_array; }
bool operator!=(const Coordinates &other) const { return coordinate_array!=other.coordinate_array; }
size_t size() const { return coordinate_array.size(); }
#//Element access
coordT &at(int idx) { return coordinate_array.at(idx); }
const coordT &at(int idx) const { return coordinate_array.at(idx); }
coordT &back() { return coordinate_array.back(); }
const coordT &back() const { return coordinate_array.back(); }
coordT &first() { return front(); }
const coordT &first() const { return front(); }
coordT &front() { return coordinate_array.front(); }
const coordT &front() const { return coordinate_array.front(); }
coordT &last() { return back(); }
const coordT &last() const { return back(); }
Coordinates mid(int idx, int length= -1) const;
coordT &operator[](int idx) { return coordinate_array.operator[](idx); }
const coordT &operator[](int idx) const { return coordinate_array.operator[](idx); }
coordT value(int idx, const coordT &defaultValue) const;
#//Iterator
iterator begin() { return iterator(coordinate_array.begin()); }
const_iterator begin() const { return const_iterator(coordinate_array.begin()); }
const_iterator constBegin() const { return begin(); }
const_iterator constEnd() const { return end(); }
iterator end() { return iterator(coordinate_array.end()); }
const_iterator end() const { return const_iterator(coordinate_array.end()); }
#//Read-only
Coordinates operator+(const Coordinates &other) const;
#//Modify
void append(const coordT &c) { push_back(c); }
void clear() { coordinate_array.clear(); }
iterator erase(iterator idx) { return iterator(coordinate_array.erase(idx.base())); }
iterator erase(iterator begin, iterator end) { return iterator(coordinate_array.erase(begin.base(), end.base())); }
void insert(int before, const coordT &c) { insert(begin()+before, c); }
iterator insert(iterator before, const coordT &c) { return iterator(coordinate_array.insert(before.base(), c)); }
void move(int from, int to) { insert(to, takeAt(from)); }
Coordinates &operator+=(const Coordinates &other);
Coordinates &operator+=(const coordT &c) { append(c); return *this; }
Coordinates &operator<<(const Coordinates &other) { return *this += other; }
Coordinates &operator<<(const coordT &c) { return *this += c; }
void pop_back() { coordinate_array.pop_back(); }
void pop_front() { removeFirst(); }
void prepend(const coordT &c) { insert(begin(), c); }
void push_back(const coordT &c) { coordinate_array.push_back(c); }
void push_front(const coordT &c) { insert(begin(), c); }
//removeAll below
void removeAt(int idx) { erase(begin()+idx); }
void removeFirst() { erase(begin()); }
void removeLast() { erase(--end()); }
void replace(int idx, const coordT &c) { (*this)[idx]= c; }
void reserve(int i) { coordinate_array.reserve(i); }
void swap(int idx, int other);
coordT takeAt(int idx);
coordT takeFirst() { return takeAt(0); }
coordT takeLast();
#//Search
bool contains(const coordT &t) const;
int count(const coordT &t) const;
int indexOf(const coordT &t, int from = 0) const;
int lastIndexOf(const coordT &t, int from = -1) const;
void removeAll(const coordT &t);
#//Coordinates::iterator -- from QhullPoints, forwarding to coordinate_array
// before const_iterator for conversion with comparison operators
class iterator {
private:
std::vector<coordT>::iterator i;
friend class const_iterator;
public:
typedef std::random_access_iterator_tag iterator_category;
typedef coordT value_type;
typedef value_type *pointer;
typedef value_type &reference;
typedef ptrdiff_t difference_type;
iterator() {}
iterator(const iterator &other) { i= other.i; }
explicit iterator(const std::vector<coordT>::iterator &vi) { i= vi; }
iterator &operator=(const iterator &other) { i= other.i; return *this; }
std::vector<coordT>::iterator &base() { return i; }
// No operator-> for base types
coordT &operator*() const { return *i; }
coordT &operator[](int idx) const { return i[idx]; }
bool operator==(const iterator &other) const { return i==other.i; }
bool operator!=(const iterator &other) const { return i!=other.i; }
bool operator<(const iterator &other) const { return i<other.i; }
bool operator<=(const iterator &other) const { return i<=other.i; }
bool operator>(const iterator &other) const { return i>other.i; }
bool operator>=(const iterator &other) const { return i>=other.i; }
// reinterpret_cast to break circular dependency
bool operator==(const Coordinates::const_iterator &other) const { return *this==reinterpret_cast<const iterator &>(other); }
bool operator!=(const Coordinates::const_iterator &other) const { return *this!=reinterpret_cast<const iterator &>(other); }
bool operator<(const Coordinates::const_iterator &other) const { return *this<reinterpret_cast<const iterator &>(other); }
bool operator<=(const Coordinates::const_iterator &other) const { return *this<=reinterpret_cast<const iterator &>(other); }
bool operator>(const Coordinates::const_iterator &other) const { return *this>reinterpret_cast<const iterator &>(other); }
bool operator>=(const Coordinates::const_iterator &other) const { return *this>=reinterpret_cast<const iterator &>(other); }
iterator operator++() { return iterator(++i); } //FIXUP QH11012 Should return reference, but get reference to temporary
iterator operator++(int) { return iterator(i++); }
iterator operator--() { return iterator(--i); }
iterator operator--(int) { return iterator(i--); }
iterator operator+=(int idx) { return iterator(i += idx); }
iterator operator-=(int idx) { return iterator(i -= idx); }
iterator operator+(int idx) const { return iterator(i+idx); }
iterator operator-(int idx) const { return iterator(i-idx); }
difference_type operator-(iterator other) const { return i-other.i; }
};//Coordinates::iterator
#//Coordinates::const_iterator
class const_iterator {
private:
std::vector<coordT>::const_iterator i;
public:
typedef std::random_access_iterator_tag iterator_category;
typedef coordT value_type;
typedef const value_type *pointer;
typedef const value_type &reference;
typedef ptrdiff_t difference_type;
const_iterator() {}
const_iterator(const const_iterator &other) { i= other.i; }
const_iterator(iterator o) : i(o.i) {}
explicit const_iterator(const std::vector<coordT>::const_iterator &vi) { i= vi; }
const_iterator &operator=(const const_iterator &other) { i= other.i; return *this; }
// No operator-> for base types
// No reference to a base type for () and []
const coordT &operator*() const { return *i; }
const coordT &operator[](int idx) const { return i[idx]; }
bool operator==(const const_iterator &other) const { return i==other.i; }
bool operator!=(const const_iterator &other) const { return i!=other.i; }
bool operator<(const const_iterator &other) const { return i<other.i; }
bool operator<=(const const_iterator &other) const { return i<=other.i; }
bool operator>(const const_iterator &other) const { return i>other.i; }
bool operator>=(const const_iterator &other) const { return i>=other.i; }
const_iterator operator++() { return const_iterator(++i); } //FIXUP QH11014 -- too much copying
const_iterator operator++(int) { return const_iterator(i++); }
const_iterator operator--() { return const_iterator(--i); }
const_iterator operator--(int) { return const_iterator(i--); }
const_iterator operator+=(int idx) { return const_iterator(i += idx); }
const_iterator operator-=(int idx) { return const_iterator(i -= idx); }
const_iterator operator+(int idx) const { return const_iterator(i+idx); }
const_iterator operator-(int idx) const { return const_iterator(i-idx); }
difference_type operator-(const_iterator other) const { return i-other.i; }
};//Coordinates::const_iterator
};//Coordinates
//class CoordinatesIterator
//QHULL_DECLARE_SEQUENTIAL_ITERATOR(Coordinates, coordT)
class CoordinatesIterator
{
typedef Coordinates::const_iterator const_iterator;
const Coordinates *c;
const_iterator i;
public:
inline CoordinatesIterator(const Coordinates &container)
: c(&container), i(c->constBegin()) {}
inline CoordinatesIterator &operator=(const Coordinates &container)
{ c = &container; i = c->constBegin(); return *this; }
inline void toFront() { i = c->constBegin(); }
inline void toBack() { i = c->constEnd(); }
inline bool hasNext() const { return i != c->constEnd(); }
inline const coordT &next() { return *i++; }
inline const coordT &peekNext() const { return *i; }
inline bool hasPrevious() const { return i != c->constBegin(); }
inline const coordT &previous() { return *--i; }
inline const coordT &peekPrevious() const { const_iterator p = i; return *--p; }
inline bool findNext(const coordT &t)
{ while (i != c->constEnd()) if (*i++ == t) return true; return false; }
inline bool findPrevious(const coordT &t)
{ while (i != c->constBegin()) if (*(--i) == t) return true;
return false; }
};//CoordinatesIterator
//class MutableCoordinatesIterator
//QHULL_DECLARE_MUTABLE_SEQUENTIAL_ITERATOR(Coordinates, coordT)
class MutableCoordinatesIterator
{
typedef Coordinates::iterator iterator;
typedef Coordinates::const_iterator const_iterator;
Coordinates *c;
iterator i, n;
inline bool item_exists() const { return const_iterator(n) != c->constEnd(); }
public:
inline MutableCoordinatesIterator(Coordinates &container)
: c(&container)
{ i = c->begin(); n = c->end(); }
inline ~MutableCoordinatesIterator()
{}
inline MutableCoordinatesIterator &operator=(Coordinates &container)
{ c = &container;
i = c->begin(); n = c->end(); return *this; }
inline void toFront() { i = c->begin(); n = c->end(); }
inline void toBack() { i = c->end(); n = i; }
inline bool hasNext() const { return c->constEnd() != const_iterator(i); }
inline coordT &next() { n = i++; return *n; }
inline coordT &peekNext() const { return *i; }
inline bool hasPrevious() const { return c->constBegin() != const_iterator(i); }
inline coordT &previous() { n = --i; return *n; }
inline coordT &peekPrevious() const { iterator p = i; return *--p; }
inline void remove()
{ if (c->constEnd() != const_iterator(n)) { i = c->erase(n); n = c->end(); } }
inline void setValue(const coordT &t) const { if (c->constEnd() != const_iterator(n)) *n = t; }
inline coordT &value() { QHULL_ASSERT(item_exists()); return *n; }
inline const coordT &value() const { QHULL_ASSERT(item_exists()); return *n; }
inline void insert(const coordT &t) { n = i = c->insert(i, t); ++i; }
inline bool findNext(const coordT &t)
{ while (c->constEnd() != const_iterator(n = i)) if (*i++ == t) return true; return false; }
inline bool findPrevious(const coordT &t)
{ while (c->constBegin() != const_iterator(i)) if (*(n = --i) == t) return true;
n = c->end(); return false; }
};//MutableCoordinatesIterator
}//namespace orgQhull
#//Global functions
std::ostream &operator<<(std::ostream &os, const orgQhull::Coordinates &c);
#endif // QHCOORDINATES_H
| [
"183071083@qq.com"
] | 183071083@qq.com |
a912adca0061d549478f2ffd65fabdcadd451480 | c7fd308ee062c23e1b036b84bbf890c3f7e74fc4 | /RobotInicial/main.cpp | e00824f14932cd21cd05bdc19a46cb4344ae5a81 | [] | no_license | truenite/truenite-opengl | 805881d06a5f6ef31c32235fb407b9a381a59ed9 | 157b0e147899f95445aed8f0d635848118fce8b6 | refs/heads/master | 2021-01-10T01:59:35.796094 | 2011-05-06T02:03:16 | 2011-05-06T02:03:16 | 53,160,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,351 | cpp | #include <windows.h>
#include <GL/glut.h>
float rotationX=0.0;
float rotationY=0.0;
float prevX=0.0;
float prevY=0.0;
bool mouseDown=false;
float viewer[]= {0.0, 0.0, 7.0};
int displayMode=1;
typedef struct treenode{
GLfloat m[16];
void (*f)();
struct treenode *sibling;
struct treenode *child;
}treenode;
treenode torso;
// Declarar todas!
void paintTorso(){
glPushMatrix();
glScalef(1.0,1.5,1.0);
// Display mode
if(displayMode==1)
glutWireCube(1);
else
glutSolidCube(1);
glPopMatrix();
}
void init(){
glColor3f(1.0, 0.0, 0.0);
glEnable(GL_DEPTH_TEST);
// Torso
glLoadIdentity();
glGetFloatv(GL_MODELVIEW_MATRIX, torso.m);
torso.f = paintTorso;
torso.sibling = NULL;
torso.child = NULL;
}
void traverse(treenode *node){
glPushMatrix();
glMultMatrixf(node->m);
node->f();
if(node->child != NULL)
traverse(node->child);
glPopMatrix();
if(node->sibling != NULL)
traverse(node->sibling);
}
void display(void){
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(viewer[0],viewer[1],viewer[2],0,0,0,0,1,0);
glRotatef(rotationX,1,0,0);
glRotatef(rotationY,0,1,0);
glPushMatrix();
traverse(&torso);
glPopMatrix();
glutSwapBuffers();
}
void reshape(int w, int h){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (GLdouble)w/(GLdouble)h, 1.0, 100.0);
glViewport(0,0,w,h);
}
void mouse(int button, int state, int x, int y){
if(button == GLUT_LEFT_BUTTON && state==GLUT_DOWN){
mouseDown = true;
prevX = x - rotationY;
prevY = y - rotationX;
}else{
mouseDown = false;
}
}
void mouseMotion(int x, int y){
if(mouseDown){
rotationX = y - prevY;
rotationY = x - prevX;
glutPostRedisplay();
}
}
void specialKey(int c, int x, int y){
if(c == GLUT_KEY_RIGHT) {
}
if(c == GLUT_KEY_UP) {
}
if(c == GLUT_KEY_DOWN) {
}
glutPostRedisplay();
}
void key(unsigned char key, int x, int y)
{
if(key == 'x') viewer[0]-= 0.1;
if(key == 'X') viewer[0]+= 0.1;
if(key == 'y') viewer[1]-= 0.1;
if(key == 'Y') viewer[1]+= 0.1;
if(key == 'z') viewer[2]-= 0.1;
if(key == 'Z') viewer[2]+= 0.1;
glutPostRedisplay();
}
void menu(int val){
displayMode=val;
glutPostRedisplay();
}
int addMenu(){
int mainMenu, subMenu1;
mainMenu = glutCreateMenu(menu);
subMenu1 = glutCreateMenu(menu);
glutSetMenu(mainMenu);
glutAddSubMenu("Display mode", subMenu1);
glutSetMenu(subMenu1);
glutAddMenuEntry("Wireframe", 1);
glutAddMenuEntry("Solid", 2);
glutSetMenu(mainMenu);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int main(int argc, char **argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Robot");
glutInitWindowSize(500,500);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMotionFunc(mouseMotion);
glutKeyboardFunc(key);
glutSpecialFunc(specialKey);
addMenu();
init();
glutMainLoop();
}
| [
"diego.mendiburu@gmail.com"
] | diego.mendiburu@gmail.com |
5e76130eb5d91244236a4e32f51d1920b701dc35 | b22522fe8fc3777b51dba385f0cdb7a7d2911e96 | /opencv3/ch7/ch7/tx_equalizeHist.cpp | 30c38390d46b956906751021db51a71bea915495 | [] | no_license | txaxx/opencv | 5320cbe28b04dc9b6b4b0ed17daf2464ae46816d | 23e2394ab204f7439c62cffbae1f997cca50bf3e | refs/heads/master | 2020-05-16T01:54:16.331452 | 2019-05-09T02:36:42 | 2019-05-09T02:36:42 | 182,612,736 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 966 | cpp | #include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
//--------------------------------------【main( )函数】-----------------------------------------
// 描述:控制台应用程序的入口函数,我们的程序从这里开始执行
//-----------------------------------------------------------------------------------------------
int main()
{
// 【1】加载源图像
Mat srcImage, dstImage;
srcImage = imread("4.jpg", 1);
if (!srcImage.data) { printf("读取图片错误,请确定目录下是否有imread函数指定图片存在~! \n"); return false; }
// 【2】转为灰度图并显示出来
cvtColor(srcImage, srcImage, COLOR_BGR2GRAY);
imshow("原始图", srcImage);
// 【3】进行直方图均衡化
equalizeHist(srcImage, dstImage);
// 【4】显示结果
imshow("经过直方图均衡化后的图", dstImage);
// 等待用户按键退出程序
waitKey(0);
return 0;
} | [
"1192622499@example.com"
] | 1192622499@example.com |
f93bc675689f78a266778f2c85f376e29a99e24e | 830ed304a7d320e731bacb0dc78475339df46954 | /QuickChips/qcprocessmanager.h | 61c88e5511da31f1bdc58fd1c4c4780fc0524f6a | [] | no_license | anacecisb/Agri-Reader | 95899df0d058feaa7574b1319968dc8571bdff53 | d58cd1c43f724492dfbbeb1f6d6d928a3a4e17ac | refs/heads/main | 2023-04-25T20:37:47.331848 | 2021-05-17T00:00:43 | 2021-05-17T00:00:43 | 368,003,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 833 | h | #ifndef QCPROCESSMANAGER_H
#define QCPROCESSMANAGER_H
#include <QObject>
class QCProcessManagerThread;
class QCProcessManager : public QObject
{
Q_OBJECT
public:
explicit QCProcessManager(QObject *parent = 0);
void loadProcessFile( QString filename );
void setExposure( int exposureTarget );
void setTargetTemperatureCentiCel( int targetCentiCel );
void setHeatingDuration( int heatingDurationSec );
void setROIFile( QString filename );
void startProcess();
void pauseProcess();
void stopProcess();
QCProcessManagerThread* processThread;
QString processName;
int targetExposure;
int targetTempCentiCel;
int heatingDurationSec;
QString roiFilename;
signals:
void issueCommand( QString command, int value );
public slots:
};
#endif // QCPROCESSMANAGER_H
| [
"noreply@github.com"
] | anacecisb.noreply@github.com |
e82ed296269ff838f01f03738e0bb11d97dc9f06 | 387549ab27d89668e656771a19c09637612d57ed | /DRGLib UE project/Source/FSD/Private/Flare.cpp | 83d37117522c87515e919172142f605b5a9f4889 | [
"MIT"
] | permissive | SamsDRGMods/DRGLib | 3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a | 76f17bc76dd376f0d0aa09400ac8cb4daad34ade | refs/heads/main | 2023-07-03T10:37:47.196444 | 2023-04-07T23:18:54 | 2023-04-07T23:18:54 | 383,509,787 | 16 | 5 | MIT | 2023-04-07T23:18:55 | 2021-07-06T15:08:14 | C++ | UTF-8 | C++ | false | false | 1,349 | cpp | #include "Flare.h"
#include "Net/UnrealNetwork.h"
#include "Templates/SubclassOf.h"
void AFlare::StartLightFunction(ULightComponent* mainLight, TArray<ULightComponent*> spotLights, UCurveFloat* flutterCurve, UCurveFloat* fadeInCurve) {
}
void AFlare::OnRep_IsFlareOn() {
}
void AFlare::OnFlareSpawnCompleted() {
}
void AFlare::Inhibit() {
}
float AFlare::ImmidiateFadeLight() {
return 0.0f;
}
TSubclassOf<AActor> AFlare::GetWeaponViewClass() const {
return NULL;
}
AFlare* AFlare::GetFlareDefaultObject(TSubclassOf<AFlare> flareClass) {
return NULL;
}
void AFlare::ActorWasHit(AActor* SelfActor, AActor* OtherActor, FVector NormalImpulse, const FHitResult& Hit) {
}
void AFlare::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const {
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(AFlare, Duration);
DOREPLIFETIME(AFlare, IsFlareOn);
}
AFlare::AFlare() {
this->InitialSpeed = 750.00f;
this->InitialAngularImpulse = 20.00f;
this->InitialAngularImpulseRandomScale = 3.00f;
this->MaxFlares = 3;
this->ProductionTime = 15.00f;
this->Duration = 0.00f;
this->IsFlareOn = true;
this->DamageCauser = NULL;
this->WeaponPreviewClass = NULL;
this->LoadoutItem = NULL;
this->ItemID = NULL;
this->ImpactGroundSound = NULL;
}
| [
"samamstar@gmail.com"
] | samamstar@gmail.com |
484d096674002471f19f9623192077765a25de16 | 4db1629242d9ef04efcffc04193ac7c7234accb5 | /main.cpp | 79912b221450b705a11e21ea38980591efd129ec | [
"MIT"
] | permissive | casey-c/egg-parser | 0972d17da41b9cb6ada39a3db6ae4ede60d7beaa | ab5fed78950d1c4d73f033d3e7b80ad63f9d2436 | refs/heads/master | 2021-01-19T08:36:32.063592 | 2017-04-10T00:53:34 | 2017-04-10T00:53:34 | 87,653,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | #include <iostream>
#include <string>
#include "node.h"
int main()
{
std::list <std::string> list;
list.push_back( "221PQ21QP" );
list.push_back( "221QP21PQ" );
list.push_back( "3A1C3EBD" );
list.push_back( "23CABA" );
list.push_back( "31A1C1B" );
list.push_back( "3ABC" );
std::list<std::string>::iterator it = list.begin();
for ( ; it != list.end(); ++it )
{
std::string curr = (*it);
std::cout << "Current string: " << curr << std::endl;
Node* node = Node::parseFromString( curr );
if ( node == NULL )
{
std::cerr << "ERROR: invalid" << std::endl;
continue;
}
node->print();
std::cout << "Test to make sure toString retains input order:\n";
std::cout << "OLD: " << curr << std::endl;
std::cout << "NEW: " << node->toString() << std::endl << std::endl;
std::cout << "Standardized:" << std::endl;
Node::standardize( node );
node->print();
std::cout << "Final output: " << node->toString() << std::endl;
std::cout << "----------" << std::endl;
}
}
| [
"casey-c@users.noreply.github.com"
] | casey-c@users.noreply.github.com |
877651c6d42e709ab7bff1a7c20fdf1a759785bd | 3fa8244506a4bf9d8d439981a75d84a797d31abe | /readObj.h | 2a0f6ecfa5a3d973ce69a6d772281adda2f4afa2 | [] | no_license | ariellav/Coursework-OpenGLProject | caf4378da6d6d5f1a68a035d9b94c1d49e244b7f | 2fe5095acf1f1ddb83bb57ebeef98e3420afc82d | refs/heads/master | 2021-01-16T18:42:33.949465 | 2014-11-05T22:08:54 | 2014-11-05T22:08:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 501 | h | #include <glm/glm.hpp>
#include "glheader.h"
// Mesh class
// vertices are a vector of 4D points (x,y,z,1)
// normals are a vector of 3D point
// but the elements (triangles) is a vector of 3m integer indices,
// three per triangle.
class Mesh {
public:
std::vector<glm::vec4> vertices;
std::vector<glm::vec3> normals;
std::vector<GLuint> elements;
// Creation and destruction
Mesh() {}
~Mesh() {}
};
// Function to read in object in .obj format
void load_obj(const char*, Mesh*);
| [
"ariellavu@gmail.com"
] | ariellavu@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.