blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
sequencelengths
1
1
author
stringlengths
0
119
5ff7de41d7b6e47d94803f087d3b0eee85a4dfc2
2a74108e7b36b32bca8a1fd84ed4c177a5b50913
/src/light_block.h
eb33a3cff2f89c19add46c22e24098d9ddb2aa7d
[]
no_license
DanTheMan1/light
2daa866b342a38599f39d7759431d7bfe120e694
aa25a08a7ea2a44f407283ed95cd223a0d8ae1d6
refs/heads/master
2021-01-18T08:57:52.881496
2015-12-10T05:16:11
2015-12-10T05:34:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,094
h
#pragma once #include <stdint.h> #include <stdlib.h> #include <utility> namespace light { struct block { block() {} explicit block(size_t size) { resize(size); } block(const block &other) { *this = other; } block(block &&other) { *this = std::move(other); } ~block(); block &operator =(const block &other); block &operator =(block &&other); size_t size() const { return _size; } size_t capacity() const { return _capacity; } bool empty() const { return !_size; } const void *data() const { return _data; } void *data() { return _data; } void clear() { _size = 0; } void grow(size_t delta); void shrink(size_t delta); void resize(size_t size); void reserve(size_t capacity); void insert(size_t index, size_t delta); void remove(size_t index, size_t delta); void move(size_t before, size_t after, size_t count); void swap(block &other); void shrink_to_fit(); private: void change_capacity(size_t capacity); uint8_t *_data = nullptr; size_t _capacity = 0; size_t _size = 0; }; }
46e4252001f55acffac6c4fc63e6da4b14306469
b4efa2b16ee0db5c945b8a0334ca0be3cc4e7c8e
/src/Ontology/OntTxBuilder.cpp
a5116153a34cdfaa5855738b97b0ff7f5a9d2721
[ "MIT" ]
permissive
dakarcoin/wallet
94b1f7a48ff396a184fd00da252e82a57c963bbf
5d961e9e322ee769322124cb711cdebc5206aa0d
refs/heads/master
2023-05-28T23:37:07.650035
2021-06-08T12:13:05
2021-06-08T12:13:05
374,943,848
1
1
null
null
null
null
UTF-8
C++
false
false
1,733
cpp
// Copyright © 2020-2021 Dakar Wallet. // // This file is part of Dakar. The full Dakar copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "OntTxBuilder.h" using namespace TW; using namespace TW::Ontology; Data OntTxBuilder::decimals(const Ontology::Proto::SigningInput &input) { auto transaction = Ont().decimals(input.nonce()); auto encoded = transaction.serialize(); return encoded; } Data OntTxBuilder::balanceOf(const Ontology::Proto::SigningInput &input) { auto queryAddress = Address(input.query_address()); auto transaction = Ont().balanceOf(queryAddress, input.nonce()); auto encoded = transaction.serialize(); return encoded; } Data OntTxBuilder::transfer(const Ontology::Proto::SigningInput &input) { auto payerSigner = Signer(PrivateKey(input.payer_private_key())); auto fromSigner = Signer(PrivateKey(input.owner_private_key())); auto toAddress = Address(input.to_address()); auto tranferTx = Ont().transfer(fromSigner, toAddress, input.amount(), payerSigner, input.gas_price(), input.gas_limit(), input.nonce()); auto encoded = tranferTx.serialize(); return encoded; } Data OntTxBuilder::build(const Ontology::Proto::SigningInput &input) { auto method = std::string(input.method().begin(), input.method().end()); if (method == "transfer") { return OntTxBuilder::transfer(input); } else if (method == "balanceOf") { return OntTxBuilder::balanceOf(input); } else if (method == "decimals") { return OntTxBuilder::decimals(input); } return Data(); }
76e42796586cca265860b73ff77c13fe836738c7
45014139581f1211a43b6415a6ee32d442c29fc0
/src/net/third_party/quiche/src/quic/core/quic_crypto_client_handshaker_test.cc
660663a9acd98168f0a88470cab9b03e87a75683
[ "BSD-3-Clause" ]
permissive
webosose/chromium91
a31b847e64391c3de98ca5b6dac3ac247d393e78
b28e2ae83ee2e4907a36a49a4c0f054aa386dbfa
refs/heads/master
2022-12-12T09:32:30.580155
2022-09-01T09:02:15
2022-09-18T23:58:11
460,692,960
1
5
null
2022-10-05T07:19:39
2022-02-18T03:16:04
null
UTF-8
C++
false
false
8,381
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 "quic/core/quic_crypto_client_handshaker.h" #include <utility> #include "absl/strings/string_view.h" #include "quic/core/proto/crypto_server_config_proto.h" #include "quic/platform/api/quic_test.h" #include "quic/test_tools/quic_test_utils.h" namespace quic { namespace { class TestProofHandler : public QuicCryptoClientStream::ProofHandler { public: ~TestProofHandler() override {} void OnProofValid( const QuicCryptoClientConfig::CachedState& /*cached*/) override {} void OnProofVerifyDetailsAvailable( const ProofVerifyDetails& /*verify_details*/) override {} }; class InsecureProofVerifier : public ProofVerifier { public: InsecureProofVerifier() {} ~InsecureProofVerifier() override {} // ProofVerifier override. QuicAsyncStatus VerifyProof( const std::string& /*hostname*/, const uint16_t /*port*/, const std::string& /*server_config*/, QuicTransportVersion /*transport_version*/, absl::string_view /*chlo_hash*/, const std::vector<std::string>& /*certs*/, const std::string& /*cert_sct*/, const std::string& /*signature*/, const ProofVerifyContext* /*context*/, std::string* /*error_details*/, std::unique_ptr<ProofVerifyDetails>* /*verify_details*/, std::unique_ptr<ProofVerifierCallback> /*callback*/) override { return QUIC_SUCCESS; } QuicAsyncStatus VerifyCertChain( const std::string& /*hostname*/, const uint16_t /*port*/, const std::vector<std::string>& /*certs*/, const std::string& /*ocsp_response*/, const std::string& /*cert_sct*/, const ProofVerifyContext* /*context*/, std::string* /*error_details*/, std::unique_ptr<ProofVerifyDetails>* /*details*/, uint8_t* /*out_alert*/, std::unique_ptr<ProofVerifierCallback> /*callback*/) override { return QUIC_SUCCESS; } std::unique_ptr<ProofVerifyContext> CreateDefaultContext() override { return nullptr; } }; class DummyProofSource : public ProofSource { public: DummyProofSource() {} ~DummyProofSource() override {} // ProofSource override. void GetProof(const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const std::string& hostname, const std::string& /*server_config*/, QuicTransportVersion /*transport_version*/, absl::string_view /*chlo_hash*/, std::unique_ptr<Callback> callback) override { QuicReferenceCountedPointer<ProofSource::Chain> chain = GetCertChain(server_address, client_address, hostname); QuicCryptoProof proof; proof.signature = "Dummy signature"; proof.leaf_cert_scts = "Dummy timestamp"; callback->Run(true, chain, proof, /*details=*/nullptr); } QuicReferenceCountedPointer<Chain> GetCertChain( const QuicSocketAddress& /*server_address*/, const QuicSocketAddress& /*client_address*/, const std::string& /*hostname*/) override { std::vector<std::string> certs; certs.push_back("Dummy cert"); return QuicReferenceCountedPointer<ProofSource::Chain>( new ProofSource::Chain(certs)); } void ComputeTlsSignature( const QuicSocketAddress& /*server_address*/, const QuicSocketAddress& /*client_address*/, const std::string& /*hostname*/, uint16_t /*signature_algorit*/, absl::string_view /*in*/, std::unique_ptr<SignatureCallback> callback) override { callback->Run(true, "Dummy signature", /*details=*/nullptr); } TicketCrypter* GetTicketCrypter() override { return nullptr; } }; class Handshaker : public QuicCryptoClientHandshaker { public: Handshaker(const QuicServerId& server_id, QuicCryptoClientStream* stream, QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context, QuicCryptoClientConfig* crypto_config, QuicCryptoClientStream::ProofHandler* proof_handler) : QuicCryptoClientHandshaker(server_id, stream, session, std::move(verify_context), crypto_config, proof_handler) {} void DoSendCHLOTest(QuicCryptoClientConfig::CachedState* cached) { QuicCryptoClientHandshaker::DoSendCHLO(cached); } }; class QuicCryptoClientHandshakerTest : public QuicTestWithParam<ParsedQuicVersion> { protected: QuicCryptoClientHandshakerTest() : version_(GetParam()), proof_handler_(), helper_(), alarm_factory_(), server_id_("host", 123), connection_(new test::MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_CLIENT, {version_})), session_(connection_, false), crypto_client_config_(std::make_unique<InsecureProofVerifier>()), client_stream_( new QuicCryptoClientStream(server_id_, &session_, nullptr, &crypto_client_config_, &proof_handler_, /*has_application_state = */ false)), handshaker_(server_id_, client_stream_, &session_, nullptr, &crypto_client_config_, &proof_handler_), state_() { // Session takes the ownership of the client stream! (but handshaker also // takes a reference to it, but doesn't take the ownership). session_.SetCryptoStream(client_stream_); session_.Initialize(); } void InitializeServerParametersToEnableFullHello() { QuicCryptoServerConfig::ConfigOptions options; QuicServerConfigProtobuf config = QuicCryptoServerConfig::GenerateConfig( helper_.GetRandomGenerator(), helper_.GetClock(), options); state_.Initialize( config.config(), "sourcetoken", std::vector<std::string>{"Dummy cert"}, "", "chlo_hash", "signature", helper_.GetClock()->WallNow(), helper_.GetClock()->WallNow().Add(QuicTime::Delta::FromSeconds(30))); state_.SetProofValid(); } ParsedQuicVersion version_; TestProofHandler proof_handler_; test::MockQuicConnectionHelper helper_; test::MockAlarmFactory alarm_factory_; QuicServerId server_id_; // Session takes the ownership of the connection. test::MockQuicConnection* connection_; test::MockQuicSession session_; QuicCryptoClientConfig crypto_client_config_; QuicCryptoClientStream* client_stream_; Handshaker handshaker_; QuicCryptoClientConfig::CachedState state_; }; INSTANTIATE_TEST_SUITE_P( QuicCryptoClientHandshakerTests, QuicCryptoClientHandshakerTest, ::testing::ValuesIn(AllSupportedVersionsWithQuicCrypto()), ::testing::PrintToStringParamName()); TEST_P(QuicCryptoClientHandshakerTest, TestSendFullPaddingInInchoateHello) { handshaker_.DoSendCHLOTest(&state_); EXPECT_TRUE(connection_->fully_pad_during_crypto_handshake()); } TEST_P(QuicCryptoClientHandshakerTest, TestDisabledPaddingInInchoateHello) { crypto_client_config_.set_pad_inchoate_hello(false); handshaker_.DoSendCHLOTest(&state_); EXPECT_FALSE(connection_->fully_pad_during_crypto_handshake()); } TEST_P(QuicCryptoClientHandshakerTest, TestPaddingInFullHelloEvenIfInchoateDisabled) { // Disable inchoate, but full hello should still be padded. crypto_client_config_.set_pad_inchoate_hello(false); InitializeServerParametersToEnableFullHello(); handshaker_.DoSendCHLOTest(&state_); EXPECT_TRUE(connection_->fully_pad_during_crypto_handshake()); } TEST_P(QuicCryptoClientHandshakerTest, TestNoPaddingInFullHelloWhenDisabled) { crypto_client_config_.set_pad_full_hello(false); InitializeServerParametersToEnableFullHello(); handshaker_.DoSendCHLOTest(&state_); EXPECT_FALSE(connection_->fully_pad_during_crypto_handshake()); } } // namespace } // namespace quic
5653f7619b5a0dec3d55e74ca1d4cf28d0628861
5272052bfc0c83f8bed0189e5506c876efa0feba
/NK_Instance/generate.cpp
17c486523f087ea3de5f7813f596e152a8923849
[]
no_license
tianliyu/DSMGA-II-TwoEdge
f7d845a336a96ed8faeef50467fdf876bd7e3af1
f56820dada0a11ab7bdac42bc134cccc6273a7e5
refs/heads/master
2021-01-19T16:43:50.292003
2017-08-22T06:08:06
2017-08-22T06:08:06
101,024,278
0
1
null
null
null
null
UTF-8
C++
false
false
1,382
cpp
#include<stdio.h> #include<stdlib.h> #include<time.h> #include <iostream> #include <iomanip> using namespace std; int main(int argc, char* argv[]){ int ell = atoi(argv[1]); double max_f,tmp,optima; int max_index[160]; int base; srand(time(NULL)); char filename[50]; for(int n=0;n<100;n++){ sprintf(filename,"pnk%d_4_5_%d",ell,n); FILE* f = fopen(filename,"w"); fprintf(f,"%d 4 5\n",ell); optima = 0.0; for(int i=0;i<ell/5;i++){ max_f = ((double)rand()/(double)RAND_MAX); max_index[i] = 0; fprintf(f,"%.9lf ",max_f); for(int j=1;j<32;j++){ tmp = ((double)rand()/(double)RAND_MAX); fprintf(f,"%.9lf ",tmp); if(tmp>max_f){ max_f = tmp; max_index[i] = j; } } optima = optima + max_f; } fprintf(f,"\n%.9lf\n",optima); for(int i=0;i<ell;i++) fprintf(f,"%d ",i); fprintf(f,"\n"); for(int i=0;i<ell/5;i++){ base = 16; //printf("index=%d\n",max_index[i]); for(int j=0;j<5;j++){ fprintf(f,"%d",max_index[i]/base); //printf("%d",max_index[i]/base); max_index[i] = max_index[i]%base; base = base/2; } fprintf(f," "); //printf(" "); } fprintf(f,"\n"); fclose(f); } return 0; }
816fde42b4372a51b72a951bee2949afff248bfe
a6e0dac05610177331c0413112ea92d0b1d5866b
/ProjectFR/FREditor/CamWaiting.h
d4f09db2b582cc6508715efd4289020ef657150b
[]
no_license
wwr1977/SJ-Studio
11c64f4bed95d53eefc2fe2198c17a419dcb0cf4
9da71a796fa6636f260b77694b51be828ce1a891
refs/heads/master
2020-05-18T03:46:24.014589
2019-04-29T22:35:19
2019-04-29T22:35:19
184,147,071
0
0
null
null
null
null
UTF-8
C++
false
false
175
h
#pragma once #include "EditCamState.h" class CCamWaiting : public CEditCamState { public: void StateReset(); void Update(); public: CCamWaiting(); ~CCamWaiting(); };
6813edfc7c2b81841dcb2e806bb149782730e971
f9726d2483d3c5ac38c8867a9cf962dc1bcaf5b4
/CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab5/sortedtype(5).cpp
19d551c3d18780f936bc063c677c5bafcaa21ee7
[ "MIT" ]
permissive
diptu/Teaching
e03c82feefe6cda52ebd05cd644063abb3cf8cd5
20655bb2c688ae29566b0a914df4a3e5936a2f61
refs/heads/main
2023-06-27T15:27:32.113183
2021-07-31T05:53:47
2021-07-31T05:53:47
341,259,841
0
0
null
null
null
null
UTF-8
C++
false
false
1,653
cpp
#include "sortedtype.h" template <class ItemType> SortedType<ItemType>::SortedType() { length=0; currentPos=-1; } template <class ItemType> void SortedType<ItemType>::MakeEmpty() { length=0; } template <class ItemType> bool SortedType<ItemType>::IsFull() { if(length==MAX_ITEMS) return true; else return false; } template <class ItemType> int SortedType<ItemType>::LengthIs() { return length; } template <class ItemType> void SortedType<ItemType>::ResetList() { currentPos=-1; } template <class ItemType> void SortedType<ItemType>::GetNextItem(ItemType& item) { currentPos++; item=info[currentPos]; } template <class ItemType> void SortedType<ItemType>::InsertItem(ItemType item) { int location=0; if(length==MAX_ITEMS) length=0; while(info[location]<item) location++; for(int i=location;i<MAX_ITEMS;i++) info[i+1]=info[i]; info[location]=item; length++; } template <class ItemType> void SortedType<ItemType>::DeleteItem(ItemType item) { int location=0; while(item!=info[location]) location++; for(int i=location+1;i<length-1;i++) info[i-1]=info[i]; length--; } template <class ItemType> void SortedType<ItemType>::RetrieveItem(ItemType& item, bool& found) { int first,last,mid; first=0; last=length-1; found=false; while(first<=last) { mid=(first+last)/2; if(item==info[mid]) { item=info[mid]; found=true; return; } else if(item<info[mid]) last=mid-1; else first=mid+1; } }
9e8d42193f20462ec9c08a23d1ee1cca6152aa6b
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-codeguruprofiler/include/aws/codeguruprofiler/model/AgentConfiguration.h
e9eb656c70f858f873e3f1b50ae99de2a039ac83
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
2,477
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/codeguruprofiler/CodeGuruProfiler_EXPORTS.h> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace CodeGuruProfiler { namespace Model { /** * <p/><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/AgentConfiguration">AWS * API Reference</a></p> */ class AWS_CODEGURUPROFILER_API AgentConfiguration { public: AgentConfiguration(); AgentConfiguration(Aws::Utils::Json::JsonView jsonValue); AgentConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p/> */ inline int GetPeriodInSeconds() const{ return m_periodInSeconds; } /** * <p/> */ inline bool PeriodInSecondsHasBeenSet() const { return m_periodInSecondsHasBeenSet; } /** * <p/> */ inline void SetPeriodInSeconds(int value) { m_periodInSecondsHasBeenSet = true; m_periodInSeconds = value; } /** * <p/> */ inline AgentConfiguration& WithPeriodInSeconds(int value) { SetPeriodInSeconds(value); return *this;} /** * <p/> */ inline bool GetShouldProfile() const{ return m_shouldProfile; } /** * <p/> */ inline bool ShouldProfileHasBeenSet() const { return m_shouldProfileHasBeenSet; } /** * <p/> */ inline void SetShouldProfile(bool value) { m_shouldProfileHasBeenSet = true; m_shouldProfile = value; } /** * <p/> */ inline AgentConfiguration& WithShouldProfile(bool value) { SetShouldProfile(value); return *this;} private: int m_periodInSeconds; bool m_periodInSecondsHasBeenSet; bool m_shouldProfile; bool m_shouldProfileHasBeenSet; }; } // namespace Model } // namespace CodeGuruProfiler } // namespace Aws
8aa2ab33374c1b185fa941c1bcfa0cda7445cc23
21a8cae66b5f0b9365b63037ed5d5eecfb4741c8
/teensy/test_notes/test_notes.ino
a2af72d5aa408ea0765e15780be2b14e2d86c611
[]
no_license
LukeMoll/teensy-midi
b0231650a9af105da70857e9547e6f26eba6d456
3b6162a45452ad207a900a4f37b007899d1a005c
refs/heads/master
2020-04-22T10:12:41.504463
2019-02-15T16:02:49
2019-02-15T16:02:49
170,297,415
0
0
null
null
null
null
UTF-8
C++
false
false
1,012
ino
#include <Bounce.h> #define MIDI_CHAN 1 // desu #define DEBOUNCE_MS 5 int led = 13; int buttonPin0 = 30; int buttonPin1 = 31; uint8_t notes = 0; Bounce button0 = Bounce(buttonPin0, DEBOUNCE_MS); Bounce button1 = Bounce(buttonPin1, DEBOUNCE_MS); void setup() { pinMode(led, OUTPUT); pinMode(buttonPin0, INPUT_PULLUP); pinMode(buttonPin1, INPUT_PULLUP); } void loop() { if(button0.update()) { if(button0.fallingEdge()) { usbMIDI.sendNoteOn(60, 99, MIDI_CHAN); notes++; } else if(button0.risingEdge()) { usbMIDI.sendNoteOff(60, 99, MIDI_CHAN); notes = notes ? notes-1 : 0; } } if(button1.update()) { if(button1.fallingEdge()) { usbMIDI.sendNoteOn(61, 99, MIDI_CHAN); notes++; } else if(button1.risingEdge()) { usbMIDI.sendNoteOff(61, 99, MIDI_CHAN); notes = notes > 0 ? notes - 1 : 0; } } digitalWrite(led, notes > 0 ? HIGH : LOW); delay(10); while (usbMIDI.read()) { // ignore incoming messages } }
39c9f09e0930ab6aab854bd9707866f14cc2b3a9
f6b33088e82fd2043f709b25515260ae3e31f00b
/1_9_FindComMaxStr.cpp
1b0e7d52f71ac121350e71835e309a4cc47a70f3
[ "MIT" ]
permissive
Yazooliu/Algorthm_Interviews
94906f2fe025bd6a5c80507932fdadcffd5389ee
0c49f4fbdab9776761f2d0a3acc0f63d92eeacd6
refs/heads/master
2020-06-02T23:08:03.708608
2019-08-28T09:10:47
2019-08-28T09:10:47
191,338,061
0
0
null
null
null
null
UTF-8
C++
false
false
1,609
cpp
// 面试题目One. 刷刷看 - 推荐算法工程师 // 9.编程题: 怎样找到两个字符串中最长公共子子串 // 具体编程思想:https://blog.csdn.net/qq_25800311/article/details/81607168 #include<iostream> #include<string> #include<vector> using namespace std; void FindComMaxStr(string str1,string str2) { if(str1.size()>str2.size()) swap(str1,str2); // 希望这里str1的长度最小作为横坐标的个数 int maxLen = 0,start = 0; int len1 = str1.length(),len2 = str2.length(); vector<vector<int>> res(len1+1,vector<int>(len2+1,0)); // res初始化成len1+1行,和len2+1列,并且全部是0 // 下面 i = 1,j=1 初始赋值是因为 表格是从第二个表格开始 // 而str1 and str2的索引是从 0 k开始的,所以str1[i-1],str2[j-1] for (int i = 1;i<=len1;i++) for (int j = 1;j<=len2;j++){ if(str1[i-1] == str2[j-1]) { res[i][j] = res[i-1][j-1] +1; // 对角线上,如果前面的元素已经是1了,则后面的逐渐递加,最后的res[i][j]就是最大长度 if (maxLen<res[i][j]) { maxLen = res[i][j]; start = i -maxLen; // 这里i 索引从1开始,所以i -maxLen 并不需要加1,start 表示最大公共字符串的开始位置 } } } cout<<str1.substr(start,maxLen)<<endl; // position = start , maxlen = 长度 } int main() { string str1,str2; while(cin>>str1>>str2) { FindComMaxStr(str1,str2); } return 0; }
420b013f297de44bd04cf0076920b34fa6b02c6e
35d7bd647e9be78c053a66081ba4f4fa7825a96b
/lib/Stepper/Stepper.cpp
215ccc5d0f3503ebf35f894468d26437365db933
[]
no_license
orange-beans/lpc1786-mbed
d58e331c4bf56415c3b8b1e1148af983583dd5b5
ca7661a0e20a58e9b127bf8627bf1de92b965c3c
refs/heads/master
2021-01-13T09:22:45.195005
2017-06-28T08:31:52
2017-06-28T08:31:52
69,566,608
0
0
null
null
null
null
UTF-8
C++
false
false
2,113
cpp
/* mbed Stepper Library * Copyright (c) 2010 fachatz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "stepper.h" #include "mbed.h" // define the Stepper Motor save start/stop speed #define START_STOP_SPEED 300 // define Library version number #define VERSION 0.3 stepper::stepper(PinName clk, PinName dir) : _clk(clk), _dir(dir) { _clk = 0, _dir = 0; } void stepper::step(int n_steps = 0, bool direction = 0, int speed = 300, bool accel = false) { int accelspeed; if(accel) accelspeed = START_STOP_SPEED; else accelspeed = speed; for(int i=0; i<n_steps; i++) { if(accel)//linear acceleration { if(i < START_STOP_SPEED) if (--accelspeed == speed) accelspeed ++; if(i > (n_steps-START_STOP_SPEED)) if(++accelspeed == START_STOP_SPEED) accelspeed--; } _dir = direction; _clk = 1; wait_us(1); _clk = 0; wait_us(1); wait_us(accelspeed); } } // version() returns the version number of the library float stepper::version(void) { return VERSION; }
23fc85a03065f7d3a868ec3d5fea77ae45394f48
5705705b182ae3ee383f394a6f5c5c5039c47449
/lib/common/ArduinoJson/src/ArduinoJson/Strings/SizedFlashStringAdapter.hpp
54da915dd62ae8ed7aa10de3fe412c7f4353dd05
[ "MIT" ]
permissive
shihaocao/lodestar
2849c1ed6d05027755b08fd69eeaa682a47eba38
1f07c8ed14dec76d10bdff615b77183bbdb5848e
refs/heads/master
2023-02-20T00:43:25.173943
2021-09-18T02:05:22
2021-09-18T02:05:22
229,489,562
2
1
MIT
2023-02-15T23:13:56
2019-12-21T22:17:53
C++
UTF-8
C++
false
false
1,315
hpp
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2020 // MIT License #pragma once #include <ArduinoJson/Namespace.hpp> namespace ARDUINOJSON_NAMESPACE { class SizedFlashStringAdapter { public: SizedFlashStringAdapter(const __FlashStringHelper* str, size_t sz) : _str(str), _size(sz) {} int8_t compare(const char* other) const { if (!other && !_str) return 0; if (!_str) return -1; if (!other) return 1; return int8_t( -strncmp_P(other, reinterpret_cast<const char*>(_str), _size)); } bool equals(const char* expected) const { return compare(expected) == 0; } bool isNull() const { return !_str; } char* save(MemoryPool* pool) const { if (!_str) return NULL; char* dup = pool->allocFrozenString(_size); if (dup) memcpy_P(dup, reinterpret_cast<const char*>(_str), _size); return dup; } size_t size() const { return _size; } bool isStatic() const { return false; } private: const __FlashStringHelper* _str; size_t _size; }; inline SizedFlashStringAdapter adaptString(const __FlashStringHelper* str, size_t sz) { return SizedFlashStringAdapter(str, sz); } } // namespace ARDUINOJSON_NAMESPACE
f63015cacc3f59d815e0c5c1882e427ef1d56566
9147ea14bbf89d66dab3d461d3743d63f561d15e
/85.cc
ea426df77fa34e6ebe718c2273f53fe8b834ca32
[]
no_license
wujingyue/leetcode
6824d7fabe5d7076aa99a5a0892bb3007003f640
53a4d31cc2e81395ad88ee5933c5ff7cfcf19ea4
refs/heads/master
2022-06-01T02:10:46.279612
2022-05-22T18:30:05
2022-05-22T18:30:05
121,978,997
1
0
null
null
null
null
UTF-8
C++
false
false
1,464
cc
#include <iostream> #include <vector> using namespace std; struct Rectangle { int left; int height; }; class Solution { public: int maximalRectangle(const vector<vector<char>>& matrix) { int m = matrix.size(); if (m == 0) { return 0; } int n = matrix[0].size(); int max_area = 0; vector<int> h(n); for (int x = 0; x < m; ++x) { for (int y = 0; y < n; ++y) { if (matrix[x][y] == '1') { h[y]++; } else { h[y] = 0; } } max_area = max(max_area, MaxRectangleInHistogram(h)); } return max_area; } private: int MaxRectangleInHistogram(const vector<int>& h) { int n = h.size(); int max_area = 0; vector<Rectangle> stack; for (int y = 0; y < n; ++y) { int left = y; while (!stack.empty() && stack.back().height >= h[y]) { max_area = max(max_area, (y - stack.back().left) * stack.back().height); left = stack.back().left; stack.pop_back(); } stack.push_back(Rectangle{left, h[y]}); } while (!stack.empty()) { max_area = max(max_area, (n - stack.back().left) * stack.back().height); stack.pop_back(); } return max_area; } }; int main() { string line; vector<vector<char>> matrix; while (getline(cin, line)) { matrix.push_back(vector<char>(line.begin(), line.end())); } Solution solution; cout << solution.maximalRectangle(matrix) << endl; }
6f072ef3383e184c713229262eda41b9becb8ab1
eb2b04a0eb683ef576b4e26c4cd5d01ca74e0d12
/project/video/video/main.cpp
4d92fd9cbdf1d8dbdc37eb823d2accebe79c7e84
[]
no_license
snail5201/Qt_example
6ba3d181c7015ed1955c445ec41000bf697012b1
9cf123148c28cdeb6a9ea20b61149e90b141d162
refs/heads/master
2020-08-04T09:06:48.316615
2019-10-01T12:01:08
2019-10-01T12:01:08
212,083,990
0
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.setWindowTitle("video"); w.show(); return a.exec(); }
bd77a631ff1ab5a8f8c301a14ea9fe528a457a4d
67a5c1f346c8467afbdf64b16e81153c12714741
/lhe/var_ttbar.h
8c6e360119ba87386b1f5ae9f9b7e4c3acdcb7f8
[]
no_license
milosdjordjevic/tHFCNC
d676806e2cdd1753300270ab0f7336dfb9c655ca
31bb7a30433c9ce6cb4d1ef4d89a294bd9c7e139
refs/heads/master
2021-01-18T02:00:19.755925
2015-10-29T13:01:43
2015-10-29T13:01:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,663
h
const int nh = 82; std::string hname[nh] = { "h_pt_t", "h_pt_tb", "h_pt_tWl", "h_pt_tWnu", "h_pt_W", "h_pt_H", "h_pt_Hb", "h_pt_j", "h_eta_t", "h_eta_tb", "h_eta_tWl", "h_eta_tWnu", "h_eta_W", "h_eta_H", "h_eta_Hb", "h_eta_j", "h_phi_t", "h_phi_tb", "h_phi_tWl", "h_phi_tWnu", "h_phi_W", "h_phi_H", "h_phi_Hb", "h_phi_j", "h_dr_t_H", "h_dr_t_j", "h_dr_t_Hb", "h_dr_t_tb", "h_dr_t_W", "h_dr_t_tWl", "h_dr_t_tWnu", "h_dr_H_j", "h_dr_H_Hb", "h_dr_H_tb", "h_dr_H_W", "h_dr_H_tWl", "h_dr_H_tWnu", "h_dr_W_tWl", "h_dr_W_tWnu", "h_dr_j_Hb", "h_dr_j_tb", "h_dr_j_W", "h_dr_j_tWl", "h_dr_j_tWnu", "h_dr_Hb_tb", "h_dr_Hb_W", "h_dr_Hb_tWl", "h_dr_Hb_tWnu", "h_dr_tb_W", "h_dr_tb_tWl", "h_dr_tb_tWnu", "h_dr_tWl_tWnu", "h_dr_Hb1_Hb2", "h_costheta_t_H", "h_costheta_t_j", "h_costheta_t_Hb", "h_costheta_t_tb", "h_costheta_t_W", "h_costheta_t_tWl", "h_costheta_t_tWnu", "h_costheta_H_j", "h_costheta_H_Hb", "h_costheta_H_tb", "h_costheta_H_W", "h_costheta_H_tWl", "h_costheta_H_tWnu", "h_costheta_W_tWl", "h_costheta_W_tWnu", "h_costheta_j_Hb", "h_costheta_j_tb", "h_costheta_j_W", "h_costheta_j_tWl", "h_costheta_j_tWnu", "h_costheta_Hb_tb", "h_costheta_Hb_W", "h_costheta_Hb_tWl", "h_costheta_Hb_tWnu", "h_costheta_tb_W", "h_costheta_tb_tWl", "h_costheta_tb_tWnu", "h_costheta_tWl_tWnu", "h_costheta_Hb1_Hb2" }; std::string xtit[nh] = { "P_{T} (t) [GeV]", "P_{T} (b_{t}) [GeV]", "P_{T} (l) [GeV]", "P_{T} (#nu) [GeV]", "P_{T} (W) [GeV]", "P_{T} (H) [GeV]", "P_{T} (b_{H}) [GeV]", "P_{T} (q) [GeV]", "#eta (t)", "#eta (b_{t})", "#eta (l)", "#eta (#nu)", "#eta (W)", "#eta (H)", "#eta (b_{H})", "#eta (q)", "#varphi (t)", "#varphi (b_{t})", "#varphi (l)", "#varphi (#nu)", "#varphi (W)", "#varphi (H)", "#varphi (b_{H})", "#varphi (q)", "#Delta R (t,H)", "#Delta R (t,q)", "#Delta R (t,b_{H})", "#Delta R (t,b_{t})", "#Delta R (t,W)", "#Delta R (t,l)", "#Delta R (t,#nu)", "#Delta R (H,q)", "#Delta R (H,b_{H})", "#Delta R (H,b_{t})", "#Delta R (H,W)", "#Delta R (H,l)", "#Delta R (H,#nu)", "#Delta R (W,l)", "#Delta R (W,#nu)", "#Delta R (q,b_{H})", "#Delta R (q,b_{t})", "#Delta R (q,W)", "#Delta R (q,l)", "#Delta R (q,#nu)", "#Delta R (b_{H},b_{t})", "#Delta R (b_{H},W)", "#Delta R (b_{H},l)", "#Delta R (b_{H},#nu)", "#Delta R (b_{t},W)", "#Delta R (b_{t},l)", "#Delta R (b_{t},#nu)", "#Delta R (l,#nu)", "#Delta R (b1_{H},b2_{H})", "cos#theta (t,H)", "cos#theta (t,q)", "cos#theta (t,b_{H})", "cos#theta (t,b_{t})", "cos#theta (t,W)", "cos#theta (t,l)", "cos#theta (t,#nu)", "cos#theta (H,q)", "cos#theta (H,b_{H})", "cos#theta (H,b_{t})", "cos#theta (H,W)", "cos#theta (H,l)", "cos#theta (H,#nu)", "cos#theta (W,l)", "cos#theta (W,#nu)", "cos#theta (q,b_{H})", "cos#theta (q,b_{t})", "cos#theta (q,W)", "cos#theta (q,l)", "cos#theta (q,#nu)", "cos#theta (b_{H},b_{t})", "cos#theta (b_{H},W)", "cos#theta (b_{H},l)", "cos#theta (b_{H},#nu)", "cos#theta (b_{t},W)", "cos#theta (b_{t},l)", "cos#theta (b_{t},#nu)", "cos#theta (l,#nu)", "cos#theta (b1_{H},b2_{H})", }; // samples const int nf = 2; std::string fname[nf] = { "TTtoHToBB-1L-Kappa-hut_CMS", "TTtoHToBB-1L-Kappa-hct_CMS" }; std::string glab[nf] = { "Hut (ttbar)", "Hct (ttbar)" };
c2f614d833564b1ec97639327f904c423ff5d236
e7e1b7ef69ccfefba7f3a13d7c23413ec335be56
/data_struct_algorithm/array_list/array_list.h
881567ade114d30822b940777fdfeb2bb79d4030
[ "MIT" ]
permissive
zhangqiang880/optimized_cplusplus
008ba55b65c07d19e81d5e36988d4340b0ed006e
a91c2ed842e270a9de0c3188f376bc6391dba47c
refs/heads/main
2023-08-14T08:39:07.748500
2021-09-26T00:14:50
2021-09-26T00:14:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,588
h
// // Created by andrew on 2021/9/25. // #ifndef OPTIMIZED_CPLUSPLUS_ARRAY_LIST_H #define OPTIMIZED_CPLUSPLUS_ARRAY_LIST_H #include "linear_list.h" #include <iostream> /* * // 需要实现的内容,先粘贴到这里 * // return element whose index is theIndex virtual int indexOf(const T &theElement) const = 0; // return index of first occurence of theElement virtual void erase(int theIndex) = 0; // remove the element whose index is theIndex virtual void insert(int theIndex, const T &theElement) = 0; // insert theElement so that its index is theIndex virtual void output(ostream &out) const = 0; * * * */ template<typename T> class ArrayList : public LinearList<T> { public: // 构造函数 析枸函数 赋值构造函数 explicit ArrayList(int32_t initialCapacity = 10); ArrayList(const ArrayList<T>& arrayList); ~ArrayList() { // nullptr 也可进行delete 不会出问题 delete [] m_element; } // ADT methods bool Empty() const override { // 只有list为空的返回true return 0 == m_listSize; } int Size() const override { return m_listSize; } T& Get(int index) const override; int IndexOf(const T &theElement) const override; void Erase(int theIndex) override; protected: void CheckIndex(int32_t index); T* m_element; // 指向一个数组,数组里面存储列表的内容 int32_t m_arrayLength{}; // 数组的长度 int32_t m_listSize{}; // 列表的大小 }; #endif //OPTIMIZED_CPLUSPLUS_ARRAY_LIST_H
fc55ffc1e87111fee865f12a1a79d8d039cff094
f1e27c1dd9ab142acc643689f7768db8b59c148d
/efm32/1.0.1/libraries/EmusDevices/CPUInfoDevice.h
997ed64bdab98f78dfa8d944529fc38727a926a9
[]
no_license
poojajune/engimusing-firmware
f15dbceb853b68b0b6714975e5ab287310261dd4
b6fbd990f016e26cb950a589bb54006efc8d615c
refs/heads/master
2021-01-23T16:13:26.348003
2017-06-04T04:01:05
2017-06-04T04:08:52
93,287,461
0
0
null
2017-06-04T03:21:52
2017-06-04T03:21:52
null
UTF-8
C++
false
false
1,175
h
/* Copyright (c) 2016 Engimusing LLC. All right reserved. This library 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 2.1 of the License, or (at your option) any later version. This library 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 library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "Arduino.h" #include "Device.h" class CPUInfoDevice : public Device { public: virtual void begin(); virtual float getTemperatureC(); virtual float getTemperatureF(); virtual float voltage(); virtual Device::ValueStruct readValue(int index); virtual uint32_t numValues(); protected: };
55f453f82c29341e7915be2ec42fc344478edb32
c466c487e1d1e743d4e3bfbe7168358c0787d5f3
/src/game/server/Bullet.cpp
ef7704dc24cb9d89e8c636cc59eb248d1a816546
[]
no_license
jucham/rouage
686a0905cf198cf735dcec7dc28577756e3e321f
33160fb4c44fb1320a33d893d36397075beeb223
refs/heads/master
2022-11-18T09:16:25.104931
2020-07-10T10:18:53
2020-07-10T10:18:53
278,144,034
0
0
null
null
null
null
UTF-8
C++
false
false
1,134
cpp
#include "Bullet.h" #include <game/server/GameServer.h> #include "EntityEnumerations.h" float Bullet::m_fWIDTH; float Bullet::m_fHEIGHT; Bullet::Bullet(Character* pShooter, const Vector2D& facing, float magnitude, int damage) : Projectile(pShooter, facing) { assert(pShooter != 0); m_HitBox.setWidth(m_fWIDTH); m_HitBox.setHeight(m_fHEIGHT); m_pCurrentTileSpot = CurrentTileSpot(); m_iDamage = damage; setMagnitude(magnitude); //0.7; m_fG *= 0.3f; setImpulseForce(); } Bullet::~Bullet() { } void Bullet::onCollide(EntityType entType, OrientHV ori) { switch (entType) { case ENTITY_TILE: { if (ori == HORIZ) { if (m_vVelocity.x > 0.0f) { } else { } Vector2D v(m_vVelocity); v.Normalize(); } else { if (m_vVelocity.y > 0.0f) { } else { } Vector2D v(m_vVelocity); v.Normalize(); } break; } case ENTITY_CHARACTER: case ENTITY_PROJECTILE: case ENTITY_TRIGGER: case ENTITY_NONE: default: assert(false); } }
17c02f44f2677af3435da3e5ceea465cb8ad01c9
8df198126a11543066c64a98a9d5ee24c7fa7618
/(((... All online judge practice and contest ...)))/Light Oj/Ad-Hoc/AC/1354 - IP Checking.cpp
7764661dbe27b1a2a2f8ec08071bbb0230ca720d
[]
no_license
mehadi-trackrep/ACM_Programming_related
eef0933febf44e3b024bc45afb3195b854eba719
7303931aa9f2ab68d76bbe04b06157b00ac9f6a6
refs/heads/master
2021-10-09T03:15:09.188172
2018-12-20T09:35:22
2018-12-20T09:35:22
117,265,703
0
0
null
null
null
null
UTF-8
C++
false
false
1,840
cpp
#include <bits/stdc++.h> using namespace std; char str[15]; void dec_to_bi(int n) { int i=0; while(n > 0) { str[i++] = (n%2)+'0'; ///AC n /= 2; } if(i < 8) { for(int j=i; j<8; j++) { str[j] = '0'; } } for(int j=0; j<4; j++) { char temp; temp = str[j]; str[j] = str[8-j-1]; str[8-j-1] = temp; } str[8] = '\0'; } int main() { int tcas; int c=1; cin >> tcas; getchar(); while(tcas--) { char ch; int ara[5]; int i=0,sum=0; char str1[4][10]; while(1) { scanf("%c",&ch); if(ch != '.' && ch != '\n') { sum = sum*10 + (ch-'0'); } else { ara[i++] = sum; sum = 0; } if(ch == '\n') break; } i = 0; int j = 0; while(1) { scanf("%c",&ch); if(ch != '.' && ch != '\n') { str1[i][j++] = ch; } else { str1[i][j] = '\0'; i++; j = 0; } if(ch == '\n') break; } int ck=1; for(int j=0; j<4; j++) { dec_to_bi(ara[j]); //cerr << "###: " << str << endl; //cerr << "***: " << str1[j] << endl; if(strcmp(str,str1[j]) == 0) continue; else { ck = 0; break; } } if(ck == 1) printf("Case %d: Yes\n",c++); else printf("Case %d: No\n",c++); } return 0; }
9339f0341a1759be16241aaec92866edcf84e7c4
f5cc952686cf4b07c6f91f902474bd7cf3089042
/Programmers(C++)/Programmers(C++)/Programmers(C++)/_0418_LV1_이상한문자 만들기.h
e9a831251a5a3d838bd2273e7af27b66433ebe19
[]
no_license
ParkHD/programmers
0d21803b8dda3cc32fac6bacd117a7bd42d4fd09
cfedec08855e826e873a68db37b347f16949a652
refs/heads/main
2023-06-11T21:47:19.362522
2021-07-10T11:16:25
2021-07-10T11:16:25
355,236,184
1
0
null
null
null
null
UTF-8
C++
false
false
1,029
h
#pragma once #include <string> #include <vector> #include <cctype> using namespace std; string solution(string s) { int count = 0; for (int i = 0; i < s.size(); i++) { if ('a' <= s[i] && s[i] <= 'z') { if (count % 2 == 0) { s[i] = toupper(s[i]); } count++; continue; } if ('A' <= s[i] && s[i] <= 'Z') { if (count % 2 == 1) { s[i] = tolower(s[i]); } count++; continue; } else count = 0; } return s; } string solution1(string s) { string answer = ""; int nIndex = 1; for (int i = 0; i < s.size(); i++, nIndex++) { if (s[i] == ' ') { nIndex = 0; answer += " "; } else nIndex & 1 ? answer += toupper(s[i]) : answer += tolower(s[i]); } return answer; }
03531ec96920f514b55e5563728b98ecffd3e121
a4344b32439a01e4ef67c521f97dc13e3600c642
/before/10951.cpp
1634d7c5d1055f39ce8706c40e2e59c0ab620a08
[]
no_license
jjunCoder/ProblemSolving
419ed6ded9ac46fcc52ec14fcfe626055462cfcc
ed150d186d2b02e514239f5d585bc068d426f4dd
refs/heads/master
2022-09-03T14:10:32.086545
2020-05-30T04:15:59
2020-05-30T04:15:59
66,230,023
0
0
null
null
null
null
UTF-8
C++
false
false
179
cpp
#include <iostream> using namespace std; int main(){ int a,b; cin.sync_with_stdio(false); cin>>a>>b; while(!cin.eof()){ printf("%d\n",a+b); cin>>a>>b; } return 0; }
3091ec8ed33175efa0d255ce79645e132b5eb091
507ca05e8357bf6ce6c821d28dce1faca6d39b73
/rttr/include/detail/metadata/metadata.h
6e5dcb316f601ab138c9cd1bd5ae5b621832b554
[]
no_license
ahdaemon/rttr-test
eb200859970c37edc936d2a1d49c33fe2cb802e0
8224f935150e05175516b15e3b5643f2d158fa87
refs/heads/master
2023-06-05T12:55:45.824226
2021-06-19T12:53:05
2021-06-19T12:53:05
378,407,510
0
0
null
null
null
null
UTF-8
C++
false
false
3,727
h
/************************************************************************************ * * * Copyright (c) 2014 - 2018 Axel Menzel <[email protected]> * * * * This file is part of RTTR (Run Time Type Reflection) * * License: MIT License * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * * SOFTWARE. * * * *************************************************************************************/ #ifndef RTTR_METADATA_H_ #define RTTR_METADATA_H_ #include "../base/core_prerequisites.h" #include "../../variant.h" namespace rttr { namespace detail { /*! * This class holds meta data. * */ class RTTR_API metadata { public: metadata() { } metadata(variant key, variant value) : m_key(std::move(key)), m_value(std::move(value)) { } metadata(const metadata& other) : m_key(other.m_key), m_value(other.m_value) {} metadata(metadata&& other) : m_key(std::move(other.m_key)), m_value(std::move(other.m_value)) {} metadata& operator=(const metadata& other) { m_key = other.m_key; m_value = other.m_value; return *this; } variant get_key() const { return m_key; } variant get_value() const { return m_value; } struct order_by_key { RTTR_INLINE bool operator () ( const metadata& _left, const metadata& _right ) const { return _left.m_key < _right.m_key; } RTTR_INLINE bool operator () ( const variant& _left, const metadata& _right ) const { return _left < _right.m_key; } RTTR_INLINE bool operator () ( const metadata& _left, const variant& _right ) const { return _left.m_key < _right; } }; private: variant m_key; variant m_value; }; } // end namespace detail } // end namespace rttr #endif // RTTR_METADATA_H_
6b2295a53050a118e437e89a891363bd2d4fcb97
52680e9f94cd9c5ba9a22a57b32d12e7f2d4e80b
/src/screen/GameOver.cpp
02cb05116f76c22866a529bbb8d45cb75b75e423
[]
no_license
VitorVRS/mind-blocs
6cc66c5642f2cdffbb61fbc4d66552b463d0cc43
2e592f83a2fe83ff5367733497b528e9f74fef69
refs/heads/master
2020-06-27T20:03:26.338376
2016-12-06T01:34:15
2016-12-06T01:34:15
74,520,846
5
0
null
null
null
null
UTF-8
C++
false
false
535
cpp
#include "GameOver.h" Screen::GameOver::GameOver() { this->message = new Render::Text("GAME OVER", 350, 310); } Screen::GameOver::~GameOver() { delete this->message; } void Screen::GameOver::show(double time) { this->message->render(); } void Screen::GameOver::keypress(int key, int scancode, int mods) { switch (key) { case GLFW_KEY_ENTER: Screen::Manager::getInstance()->change(Screen::Manager::Start); break; } }; void Screen::GameOver::click(double x, double y, int mods) {};
3b7c1d8d1b107e21813a7cf20ba9318e7eb02781
5b7b4d3883233e21e7545478664a04d0eaebd423
/tests/world/test_instance_pool.cpp
65204df2bd310d9e29eb0f1d3670655c97afce30
[ "MIT" ]
permissive
stefannesic/world
c8dca13c6d46c91c4d2a6e027f5cf413f51ccab0
44c01623ab1777c3224f83f53b74d50b58372fb1
refs/heads/master
2021-03-02T01:02:15.200828
2020-03-07T09:10:26
2020-03-07T09:10:26
245,825,486
0
0
MIT
2020-03-08T14:04:50
2020-03-08T14:04:49
null
UTF-8
C++
false
false
1,834
cpp
#include <catch/catch.hpp> #include <world/core.h> #include <world/terrain.h> using namespace world; TEST_CASE("Templates", "[instance pool]") { Template tmplate; CHECK(tmplate.getAt(0) == nullptr); CHECK(tmplate.getAt(12) == nullptr); SECTION("Add node without resolution") { tmplate.insert(SceneNode("dudu")); REQUIRE(tmplate.getAt(12) != nullptr); REQUIRE(tmplate.getAt(0) != nullptr); auto *item = tmplate.getAt(0); REQUIRE(item->_nodes.size() == 1); CHECK(item->_nodes[0].getMeshID() == "dudu"); CHECK(item->_minRes == Approx(0)); } SECTION("Create template with a scene node") { Template tmplate2(SceneNode("dudu")); REQUIRE(tmplate2.getAt(0) != nullptr); auto *item = tmplate2.getAt(0); CHECK(item->_nodes.size() == 1); CHECK(item->_minRes == Approx(0)); } SECTION("Add item at a given resolution") { tmplate.insert(10, SceneNode("dada")); tmplate.insert(15, SceneNode("dodo")); CHECK(tmplate.getAt(0) == nullptr); CHECK(tmplate.getAt(1) == nullptr); REQUIRE(tmplate.getAt(10) != nullptr); REQUIRE(tmplate.getAt(11) != nullptr); REQUIRE(tmplate.getAt(15) != nullptr); REQUIRE(tmplate.getAt(20) != nullptr); CHECK(tmplate.getAt(10)->_minRes == Approx(10)); CHECK(tmplate.getAt(11)->_minRes == Approx(10)); CHECK(tmplate.getAt(15)->_minRes == Approx(15)); CHECK(tmplate.getAt(20)->_minRes == Approx(15)); CHECK(tmplate.getAt(11)->_nodes.at(0).getMeshID() == "dada"); CHECK(tmplate.getAt(15)->_nodes.at(0).getMeshID() == "dodo"); } } TEST_CASE("MapFilteredDistribution", "[instance pool]") { CHECK_THROWS(MapFilteredDistribution<SeedDistribution>(nullptr, nullptr)); }
33614ec3c2a68c0eac4f790c4effb7ffe56cd9c5
314983bf9b412ef0bf0ad86327f081946a9b82c4
/tracer2/src/triangle.cpp
aaae4e91e01ed5e743882b2341538d440e9e27de
[]
no_license
DarwinSenior/cs419
ca8b3722c43dcb960089908bd8e0f7820f9fa21c
81d6932a1dfa642de504891cec7486e8770e3606
refs/heads/master
2016-08-13T01:07:52.853231
2016-03-22T19:27:42
2016-03-22T19:27:42
50,739,417
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
cpp
#include "triangle.h" #include <limits> using namespace cv; Triangle::Triangle(Vec3f p1, Vec3f p2, Vec3f p3){ m_p1 = p1; m_p2 = p2; m_p3 = p3; m_norm = normalize((m_p1-m_p2).cross(m_p1-m_p3)); } bool Triangle::intersect(const Ray& ray, Intersect& intersect) const{ auto d = m_norm.dot(m_p1); float dist = (d-ray.o.dot(m_norm))/(ray.d.dot(m_norm)); auto pos = ray.pos(dist); if (dist > 0 && dist < intersect.dist && inside_triange(pos)){ intersect.norm = m_norm; intersect.pos = pos; intersect.dist = dist; return true; }else{ return false; } } bool Triangle::inside_triange(const Vec3f& p) const{ auto v1 = m_p2-m_p1; auto v2 = m_p3-m_p1; auto v3 = p-m_p1; auto dot11 = v1.dot(v1); auto dot12 = v1.dot(v2); auto dot13 = v1.dot(v3); auto dot22 = v2.dot(v2); auto dot23 = v2.dot(v3); float in_denom = 1.0/(dot11*dot22-dot12*dot12); float u = (dot22*dot13-dot12*dot23) * in_denom; float v = (dot11*dot23-dot12*dot13) * in_denom; return (u>=0) && (v>=0) && (u+v<1); } Vec3f Triangle::center() const{ return (m_p1+m_p2+m_p3)/3; }
5146075b5f56913171a93a4a1877ed9edccc6f88
798e8d56678b4adaf640856c67c707044a51ba97
/ACM ICPC Team.cpp
917e691d148dc3eaa1fe2ee2cacb27b01b61b814
[]
no_license
Wajeeha-Fatima/HackerRank
5f01fb83b77da7197cf14ceba7023e5e0ddd1947
784b21bc4b11fe10b72ca514afc1b0b6765e9b06
refs/heads/main
2023-07-29T11:42:50.052354
2021-09-10T16:29:23
2021-09-10T16:29:23
338,267,549
0
0
null
null
null
null
UTF-8
C++
false
false
2,189
cpp
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); // Complete the acmTeam function below. vector<int> acmTeam(vector<string> topic) { vector <int> team; int count = 0, max = 0, teams= 0; for(int i = 0; i < topic.size()-1; i++) { for(int j = i+1; j < topic.size(); j++) { count = 0; for(int k = 0; k < topic[i].size(); k++) { if(topic[i][k] == '1' || topic[j][k] == '1') count++; } if(count > max) { max = count; teams = 1; } else if(count == max) teams++; } } team.push_back(max); team.push_back(teams); return team; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string nm_temp; getline(cin, nm_temp); vector<string> nm = split_string(nm_temp); int n = stoi(nm[0]); int m = stoi(nm[1]); vector<string> topic(n); for (int i = 0; i < n; i++) { string topic_item; getline(cin, topic_item); topic[i] = topic_item; } vector<int> result = acmTeam(topic); for (int i = 0; i < result.size(); i++) { fout << result[i]; if (i != result.size() - 1) { fout << "\n"; } } fout << "\n"; fout.close(); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
047b15a3ab4b539398ae1de59b657fea442e8718
2e231d20c2079a19ad2e8616669f33a64fd3b038
/src/seq.h
37f24eb6901677922c1e449c260eac77d2a411d6
[]
no_license
pcppcp/disciple
396e0e636d83c86bd78464bcb12669ff46b7ff18
98e19794885d35dd7f7d35fd723db195d5843885
refs/heads/master
2021-01-23T07:38:04.422431
2017-06-02T13:24:21
2017-06-02T13:24:21
93,036,790
2
0
null
null
null
null
UTF-8
C++
false
false
643
h
#ifndef _SEQ_H_ #define _SEQ_H_ /* system includes */ /* local includes */ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #define SEQ_STEPS 16 #define INSTRUMENTS_MAX 4 namespace Seq { typedef struct { uint8_t trigger:1; uint8_t param1; uint8_t param2; } seq_step_t; typedef struct _pat { _pat() : pat(), len(SEQ_STEPS), idx(0) {} seq_step_t pat[INSTRUMENTS_MAX][SEQ_STEPS]; uint8_t len; uint8_t idx; } pattern_t; pattern_t *getPattern(); void pattern_inc(pattern_t &pat); const seq_step_t *pattern_get_step(const pattern_t &pat, const uint8_t instr); } #endif #endif /* _SEQ_H_ */
9a63e25dc87dc236635465aa169aeff391ad7192
baf3c6dbd6f6ce65c6f597e2f6920f228bccb341
/CPP/nSteps/nSteps.cpp
4f69035a8514b88fb919bec0b8eab4d7e63d72f1
[]
no_license
abhikmr778/cpp
ced86bb8fa7136e9b86dcf0b47a18819f3145390
0ceb41f6f5ba7bc3a79542443311cbbf86fb1014
refs/heads/master
2020-03-18T16:01:07.276659
2018-05-26T08:15:51
2018-05-26T08:15:51
134,942,400
0
0
null
null
null
null
UTF-8
C++
false
false
337
cpp
#include "iostream" using namespace std; int sum=0; int steps(int n){ if(n==0){ return 1; } else if(n<0){ return 0; } // for(int x=1;x<=3;x++){ // return steps(n-x); // } return steps(n-1)+steps(n-2)+steps(n-3); } int main(){ int n; cin>>n; cout<<steps(n); return 0; }
1a3b07ecaeb0061cf3ad86adcad8bafba9630834
dee9e7a5b9b0ecf3b9a8ddf7f30f972045217a45
/gdem_terrainengine/CTriangleSelector.cpp
60199807828631609fefc056583c6c7f026a7d39
[]
no_license
shengzhe8688/QGlobe
3e2d5c86ad6a2bff89f3773385fa8fd84d4ddf57
8e13b894fc1d89a18869c979740fefe47a161eeb
refs/heads/master
2022-11-12T12:19:06.046336
2020-07-05T14:04:59
2020-07-05T14:04:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,047
cpp
// Copyright (C) 2002-2008 Nikolaus Gebhardt // This file is part of the "Geo Engine". // For conditions of distribution and use, see copyright notice in geoEngine.h #include "CTriangleSelector.h" #include "ISceneNode.h" #include "IMeshBuffer.h" namespace geo { namespace scene { //! constructor CTriangleSelector::CTriangleSelector(const ISceneNode* node) : SceneNode(node) { #ifdef _DEBUG setDebugName("CTriangleSelector"); #endif } //! constructor CTriangleSelector::CTriangleSelector(const IMesh* mesh, const ISceneNode* node) : SceneNode(node) { #ifdef _DEBUG setDebugName("CTriangleSelector"); #endif const u32 cnt = mesh->getMeshBufferCount(); u32 totalFaceCount = 0; for (u32 j=0; j<cnt; ++j) totalFaceCount += mesh->getMeshBuffer(j)->getIndexCount(); totalFaceCount /= 3; Triangles.reallocate(totalFaceCount); for (u32 i=0; i<cnt; ++i) { const IMeshBuffer* buf = mesh->getMeshBuffer(i); const u32 idxCnt = buf->getIndexCount(); const u16* const indices = buf->getIndices(); for (u32 j=0; j<idxCnt; j+=3) { Triangles.push_back(core::triangle3df( buf->getPosition(indices[j+0]), buf->getPosition(indices[j+1]), buf->getPosition(indices[j+2]))); } } } //! constructor CTriangleSelector::CTriangleSelector(const core::aabbox3d<f32>& box, const ISceneNode* node) : SceneNode(node) { #ifdef _DEBUG setDebugName("CTriangleSelector"); #endif // TODO } //! Gets all triangles. void CTriangleSelector::getTriangles(core::triangle3df* triangles, s32 arraySize, s32& outTriangleCount, const core::matrix4* transform) const { s32 cnt = Triangles.size(); if (cnt > arraySize) cnt = arraySize; core::matrix4 mat; if (transform) mat = *transform; if (SceneNode) mat *= SceneNode->getAbsoluteTransformation(); for (s32 i=0; i<cnt; ++i) { triangles[i] = Triangles[i]; mat.transformVect(triangles[i].pointA); mat.transformVect(triangles[i].pointB); mat.transformVect(triangles[i].pointC); } outTriangleCount = cnt; } //! Gets all triangles which lie within a specific bounding box. void CTriangleSelector::getTriangles(core::triangle3df* triangles, s32 arraySize, s32& outTriangleCount, const core::aabbox3d<f32>& box, const core::matrix4* transform) const { // return all triangles getTriangles(triangles, arraySize, outTriangleCount, transform); } //! Gets all triangles which have or may have contact with a 3d line. void CTriangleSelector::getTriangles(core::triangle3df* triangles, s32 arraySize, s32& outTriangleCount, const core::line3d<f32>& line, const core::matrix4* transform) const { // return all triangles getTriangles(triangles, arraySize, outTriangleCount, transform); } //! Returns amount of all available triangles in this selector s32 CTriangleSelector::getTriangleCount() const { return Triangles.size(); } } // end namespace scene } // end namespace geo
a1a33a16ee78570a2847d926bd11907f8cb19e97
e9ade5ea33cf3382f8ab3ad980e7f6d8cb76faf8
/solved/abc188/e.cpp
b7d352887296019e1303ba9bdf08cae1a4219b66
[]
no_license
Creamy1137689/kyopro
75bc3f92edb7bff2cbf27dc79d384b422a0a4702
dcacbf27defe840ea7998e06a5f3fb78718e7d53
refs/heads/master
2023-05-10T19:28:56.447493
2021-06-03T12:54:11
2021-06-03T12:54:11
266,143,691
0
0
null
null
null
null
UTF-8
C++
false
false
1,094
cpp
#include <iostream> #include <iomanip> #include <utility> #include <cmath> #include <random> #include <vector> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <string> #include <algorithm> using namespace std; #define rep(i,n) for(int i = 0; i<n; ++i) #define REP(i,n) for(int i = 1; i<=n; ++i) #define all(x) begin(x),end(x) #define show(obj) for(auto x:obj)cout<<x<<' ';cout<<endl; typedef long long ll; typedef pair<int,int> P; typedef pair<ll,ll> lp; typedef pair<double, double> FP; const int inf = 1001001000; const ll INF = 1LL<<60; const int MOD = (int)1e9 + 7; int main(){ int n, m; int x, y; cin >> n >> m; vector<ll> a(n); rep(i,n)cin >> a[i]; vector<vector<int>> G(n, vector<int>()); rep(i,m){ cin >> x >> y; --x; --y; G[x].push_back(y); } vector<ll> mins(n, INF); rep(i,n){ for(auto x:G[i]){ mins[x] = min({mins[x], mins[i], a[i]}); } } ll ans = -INF; rep(i,n)ans = max(ans, a[i] - mins[i]); cout << ans << endl; return 0; }
cc97072eaf792e8cce9bdf30789d96d77b5da61d
ac48af1d42007f57ab21754ae135ec4a22fb533f
/kernel/archs/x86_32/Paging.cpp
80765a90124dcaa5107752f2cfbbc157103f5f81
[ "MIT", "BSD-2-Clause" ]
permissive
raxracks/chadOS
47e4e09dd61f61e1e2415dccc560783bb5e76827
0469528f5d4f390ff45d680b91783da445e66dcc
refs/heads/main
2023-06-19T04:52:01.601917
2021-07-13T04:29:41
2021-07-13T04:29:41
379,407,996
3
0
NOASSERTION
2021-06-25T21:27:39
2021-06-22T21:43:36
C++
UTF-8
C++
false
false
7,974
cpp
#include <string.h> #include "system/Streams.h" #include <libutils/ResultOr.h> #include "archs/Arch.h" #include "archs/x86_32/Paging.h" #include "system/interrupts/Interupts.h" #include "system/memory/Memory.h" #include "system/memory/Physical.h" #include "system/system/System.h" namespace Arch::x86_32 { PageDirectory _kernel_page_directory ALIGNED(ARCH_PAGE_SIZE) = {}; PageTable _kernel_page_tables[256] ALIGNED(ARCH_PAGE_SIZE) = {}; void virtual_initialize() { // Setup the kernel pagedirectory. for (size_t i = 0; i < 256; i++) { PageDirectoryEntry *entry = &_kernel_page_directory.entries[i]; entry->User = 0; entry->Write = 1; entry->Present = 1; entry->PageFrameNumber = (size_t)&_kernel_page_tables[i] / ARCH_PAGE_SIZE; } } void virtual_memory_enable() { paging_enable(); } PageDirectory *kernel_page_directory() { return &_kernel_page_directory; } bool virtual_present(PageDirectory *page_directory, uintptr_t virtual_address) { ASSERT_INTERRUPTS_RETAINED(); int page_directory_index = PAGE_DIRECTORY_INDEX(virtual_address); PageDirectoryEntry &page_directory_entry = page_directory->entries[page_directory_index]; if (!page_directory_entry.Present) { return false; } PageTable &page_table = *reinterpret_cast<PageTable *>(page_directory_entry.PageFrameNumber * ARCH_PAGE_SIZE); int page_table_index = PAGE_TABLE_INDEX(virtual_address); PageTableEntry &page_table_entry = page_table.entries[page_table_index]; return page_table_entry.Present; } uintptr_t virtual_to_physical(PageDirectory *page_directory, uintptr_t virtual_address) { ASSERT_INTERRUPTS_RETAINED(); int page_directory_index = PAGE_DIRECTORY_INDEX(virtual_address); PageDirectoryEntry &page_directory_entry = page_directory->entries[page_directory_index]; if (!page_directory_entry.Present) { return 0; } PageTable &page_table = *reinterpret_cast<PageTable *>(page_directory_entry.PageFrameNumber * ARCH_PAGE_SIZE); int page_table_index = PAGE_TABLE_INDEX(virtual_address); PageTableEntry &page_table_entry = page_table.entries[page_table_index]; if (!page_table_entry.Present) { return 0; } return (page_table_entry.PageFrameNumber * ARCH_PAGE_SIZE) + (virtual_address & 0xfff); } HjResult virtual_map(PageDirectory *page_directory, MemoryRange physical_range, uintptr_t virtual_address, MemoryFlags flags) { ASSERT_INTERRUPTS_RETAINED(); for (size_t i = 0; i < physical_range.size() / ARCH_PAGE_SIZE; i++) { size_t offset = i * ARCH_PAGE_SIZE; int page_directory_index = PAGE_DIRECTORY_INDEX(virtual_address + offset); PageDirectoryEntry &page_directory_entry = page_directory->entries[page_directory_index]; PageTable *page_table = reinterpret_cast<PageTable *>(page_directory_entry.PageFrameNumber * ARCH_PAGE_SIZE); if (!page_directory_entry.Present) { TRY(memory_alloc_identity(page_directory, MEMORY_CLEAR, (uintptr_t *)&page_table)); page_directory_entry.Present = 1; page_directory_entry.Write = 1; page_directory_entry.User = 1; page_directory_entry.PageFrameNumber = (uint32_t)(page_table) >> 12; } int page_table_index = PAGE_TABLE_INDEX(virtual_address + offset); PageTableEntry &page_table_entry = page_table->entries[page_table_index]; page_table_entry.Present = 1; page_table_entry.Write = 1; page_table_entry.User = flags & MEMORY_USER; page_table_entry.PageFrameNumber = (physical_range.base() + offset) >> 12; } paging_invalidate_tlb(); return SUCCESS; } MemoryRange virtual_alloc(PageDirectory *page_directory, MemoryRange physical_range, MemoryFlags flags) { ASSERT_INTERRUPTS_RETAINED(); bool is_user_memory = flags & MEMORY_USER; uintptr_t virtual_address = 0; size_t current_size = 0; // we skip the first page to make null deref trigger a page fault for (size_t i = (is_user_memory ? 256 : 1) * 1024; i < (is_user_memory ? 1024 : 256) * 1024; i++) { uintptr_t current_address = i * ARCH_PAGE_SIZE; if (!virtual_present(page_directory, current_address)) { if (current_size == 0) { virtual_address = current_address; } current_size += ARCH_PAGE_SIZE; if (current_size == physical_range.size()) { assert(SUCCESS == virtual_map(page_directory, physical_range, virtual_address, flags)); return {virtual_address, current_size}; } } else { current_size = 0; } } system_panic("Out of virtual memory!"); } void virtual_free(PageDirectory *page_directory, MemoryRange virtual_range) { ASSERT_INTERRUPTS_RETAINED(); for (size_t i = 0; i < virtual_range.size() / ARCH_PAGE_SIZE; i++) { size_t offset = i * ARCH_PAGE_SIZE; size_t page_directory_index = PAGE_DIRECTORY_INDEX(virtual_range.base() + offset); PageDirectoryEntry *page_directory_entry = &page_directory->entries[page_directory_index]; if (!page_directory_entry->Present) { continue; } PageTable *page_table = (PageTable *)(page_directory_entry->PageFrameNumber * ARCH_PAGE_SIZE); size_t page_table_index = PAGE_TABLE_INDEX(virtual_range.base() + offset); PageTableEntry *page_table_entry = &page_table->entries[page_table_index]; if (page_table_entry->Present) { page_table_entry->as_uint = 0; } } paging_invalidate_tlb(); } PageDirectory *page_directory_create() { InterruptsRetainer retainer; PageDirectory *page_directory = nullptr; if (memory_alloc(kernel_page_directory(), sizeof(PageDirectory), MEMORY_CLEAR, (uintptr_t *)&page_directory) != SUCCESS) { Kernel::logln("Page directory allocation failed!"); return nullptr; } memset(page_directory, 0, sizeof(PageDirectory)); // Copy first gigs of virtual memory (kernel space); for (size_t i = 0; i < 256; i++) { PageDirectoryEntry *page_directory_entry = &page_directory->entries[i]; page_directory_entry->User = 0; page_directory_entry->Write = 1; page_directory_entry->Present = 1; page_directory_entry->PageFrameNumber = (uint32_t)&_kernel_page_tables[i] / ARCH_PAGE_SIZE; } return page_directory; } void page_directory_destroy(PageDirectory *page_directory) { InterruptsRetainer retainer; assert(page_directory != kernel_page_directory()); for (size_t i = 256; i < 1024; i++) { PageDirectoryEntry *page_directory_entry = &page_directory->entries[i]; if (page_directory_entry->Present) { PageTable *page_table = (PageTable *)(page_directory_entry->PageFrameNumber * ARCH_PAGE_SIZE); for (size_t i = 0; i < 1024; i++) { PageTableEntry *page_table_entry = &page_table->entries[i]; if (page_table_entry->Present) { uintptr_t physical_address = page_table_entry->PageFrameNumber * ARCH_PAGE_SIZE; MemoryRange physical_range{physical_address, ARCH_PAGE_SIZE}; physical_free(physical_range); } } memory_free(kernel_address_space(), (MemoryRange){(uintptr_t)page_table, sizeof(PageTable)}); } } memory_free(kernel_address_space(), (MemoryRange){(uintptr_t)page_directory, sizeof(PageDirectory)}); } void page_directory_switch(PageDirectory *page_directory) { InterruptsRetainer retainer; paging_load_directory(virtual_to_physical(kernel_page_directory(), (uintptr_t)page_directory)); } } // namespace Arch::x86_32
90f44af99dea88998a1aa5f63e64fca9b1a1bdc9
68a8b2e583bb941e74fac797771cc9d99b816505
/singleton/main.cpp
36a0566efb9f324a379d6a13a033ea2a7a4afb1a
[]
no_license
mowiru/My-thingy
79dd802228699e5578d856561ffab8d5e8215779
fd818096ff0f9004ab266540b524f18e41291f08
refs/heads/master
2020-04-04T20:08:26.916072
2018-12-03T15:02:17
2018-12-03T15:02:17
150,397,590
0
0
null
null
null
null
UTF-8
C++
false
false
629
cpp
#include <iostream> #include <string.h> #include <iomanip> #include "log.hpp" #define APP "singleton_test" using namespace std; /** * Project: singleton_test * Creator: ruedel * Creation Date: Fr 30. Nov 14:19:43 CET 2018 */ int main(int argc, char* argv[]) { /* ifstream inputFileBla("./MeineDatenDatei.json"); string ErsteZeile; inputFileBla >> ErsteZeile;*/ FileLog Log; //Log.START(" "); Log.i("New Projekt: ", APP); Log.i("I'm a test."); Log.a("Potato."); Log.w("This is a Test."); Log.e("Test has no error!"); //Log.END(" "); //cout << setw(40) << setfill('_') << endl; return 0; }
237d4aa988f74ea7365f96c8b94ea34da0a1d2eb
64fb05a37eea449e271a7255ee5dd0d382d18a11
/formula.cpp
0ce34567b3a2b5e903d6c69b94d23ee408cd8b3f
[]
no_license
JonathanNielson/CS-1410
c52d93db0a5b2f4fa88593d480ed90dc9f4373b3
f3cd10ad46a674c67ebe75c6f3e827864db9a281
refs/heads/master
2021-01-11T19:53:09.144949
2017-02-26T05:54:05
2017-02-26T05:54:05
79,416,784
0
0
null
null
null
null
UTF-8
C++
false
false
671
cpp
/* * * Solution to Programming Test #1 * Written by Jonathan Nielson on 1/25/2017 * */ #include <iostream> #include <cmath> using namespace std; int main() { double P; double i; double g; double n; double F; cout << "First off, please enter a value for P:" << endl; cin >> P; cout << "Second, please enter a value for i:" << endl; cin >> i; cout << "Now enter a value for g:" << endl; cin >> g; cout << "Finally, please enter a value for n:" << endl; cin >> n; F = P * ((1 - pow((1 + g), n) * pow((1 + i), n)) / (i - g)); cout << "Based on the provided numbers, the value of F is: " << F << endl; return 0; }
56f3943126b6c3f47fea49cc7a708348839f51dd
d822ffd937fae821fdc1f96369c26b8b31c0cda6
/luogu/p6198.cpp
c439ec2d3cac849808d08ae87376fbed3236e7c5
[ "MIT" ]
permissive
freedomDR/coding
f8bb5b43951f49cc1018132cc5c53e756a782740
408f0fd8d7e5dd986842746d27d4d26a8dc9896c
refs/heads/master
2023-03-30T03:01:01.837043
2023-03-28T12:36:53
2023-03-28T12:36:53
183,414,292
1
0
null
null
null
null
UTF-8
C++
false
false
1,389
cpp
#include<bits/stdc++.h> using namespace std; int n; int val = 1; vector<int> arr(1e6+5), ans(1e6+5); vector<vector<int>> pos(1e6+5, vector<int>()); void slove(int l, int r, int splitNum) { /* cout << l << " " << r << endl; */ if(l>r) return; vector<int> splitPos; //记录分割点 // 二分查端点 int st = lower_bound(pos[splitNum].begin(), pos[splitNum].end(), r) - pos[splitNum].begin(); // splitNum 从r到l 按照val递增赋值 for(int i = min(st, int(pos[splitNum].size()-1)); i >= 0 && pos[splitNum][i] >= l; i--) { if(pos[splitNum][i] <= r && arr[pos[splitNum][i]] == splitNum) { ans[pos[splitNum][i]] = val++; splitPos.push_back(pos[splitNum][i]); } } // l r 也可以作为分割点 if(!splitPos.empty() && splitPos.back()!=l) splitPos.push_back(l-1); if(splitPos.front()!=r) splitPos.insert(splitPos.begin(),r+1); for(int i = splitPos.size()-2; i >= 0; i--) { slove(splitPos[i+1]+1, splitPos[i]-1, splitNum+1); } } int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n; for(int i = 1; i <= n; i++) { cin >> arr[i]; if(arr[i] == -1) arr[i] = arr[i-1]+1; pos[arr[i]].push_back(i); } slove(1, n, 1); for(int i = 1; i <= n; i++) cout << ans[i] << " "; cout << endl; return 0; }
e76be0d70a2103c70fb2093481e8205eac92b883
4c93ca76318969f1624a0e77749bcdea3e7809d3
/~9999/1978_소수찾기.cpp
9fc081c57dc3d7acc386f2937c7886b3f5b17c77
[]
no_license
root-jeong/BOJ
080925f6cfbb5dcbdf13c4c3a3c7e0a444908e6e
ec1ef5ad322597883b74d276078da8a508f164a8
refs/heads/master
2022-04-03T22:33:44.866564
2020-01-08T12:21:19
2020-01-08T12:21:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
388
cpp
#include <iostream> #include <vector> using namespace std; int main() { int arr[1001]; int N; int data, count = 0; vector<int> vec; cin >> N; bool can; for (int i = 0; i < N; i++) { cin >> data; can = true; if (data != 1) { for (int i = 2; i < data; i++) { if (data % i == 0) { can = false; break; } } if (can) count++; } } cout << count; }
e426c365df95c8d9df647fd9e8612ce9a2dad9a7
db1467d280a821f2ef944f36003f2c049fc2c478
/12周C++作业/6.20 Multiple/main.cpp
73e89d424f82547a7a35b8f6ff7830b75ed7bfb1
[]
no_license
Xinxrong/xin_xiangrong
77a182f481a22b3a702fcbfd1356468d07fdff47
eb215da6ae26bdd39c680f9a9d3a8bbb271a0754
refs/heads/master
2020-04-02T09:09:42.715874
2019-04-21T13:01:17
2019-04-21T13:01:17
154,277,030
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include <iostream> using namespace std; bool multiple(int a,int b); int main() { int a,b; int c=1; while(c>0) { cout<<"Please input two number :"; cin>>a>>b; cout<<multiple(a,b)<<endl; } return 0; } bool multiple(int a,int b) { if(b%a==0) { return true; } else { return false; } }
590c77fc282723c367c4b44e51d19ee38dccf3e9
95f7c923592bafc734f8970fa743faafd5226253
/spoj/PARADOX.cpp
a47f5480e45aa651766e7eccb61545f3df4c9b9b
[]
no_license
vishnujayvel/practicecodes
33132a1afc97e619df9950cd8782951ab183833d
3849ac44596f56dda95b83d00a38b79a3921c496
refs/heads/master
2021-01-06T20:37:49.840924
2014-09-09T13:25:36
2014-09-09T13:25:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,226
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <climits> #include <stdlib.h> using namespace std; #define REP(i,n) for(int i=0; i<n; i++) #define FOR(i,st,end) for(int i=st;i<end;i++) #define db(x) cout << (#x) << " = " << x << endl; #define mp make_pair #define pb push_back int main(){ int n; while(1){ scanf("%d",&n); if(n==0) break; int dist[n+1][n+1]; REP(i,n+1) REP(j,n+1) dist[i][j]=999999; int s; char str[10]; FOR(i,1,n+1){ scanf("%d %s",&s,str); if(str[0]=='f') dist[i][s]=1; else dist[i][s]=2; } FOR(k,1,n+1) FOR(i,1,n+1) FOR(j,1,n+1){ if(dist[i][j]>dist[i][k]+dist[k][j]) dist[i][j]=dist[i][k]+dist[k][j]; } int f=1; FOR(i,1,n+1) if(dist[i][i]<999999&&dist[i][i]%2==1){ printf("PARADOX\n"); f=0; break; } if(f) printf("NOT PARADOX\n"); } }
d684f07ea503433c7be1caf90e3ec8509f7423e9
89ed66520d8646b0d7182a667c3846c1da6cada1
/join.cpp
e6fe983baeb8f60bf90b9ae4eb564f042e10e4be
[]
no_license
mukul13/DBMS-Join-using-external-hashing
509a6a62bdc9371f51c2ab79b5bfe4681e846e51
fcd422a55fe7e69fa68109e4fc9e58aacef32d62
refs/heads/master
2016-09-14T00:58:31.868987
2016-04-13T16:34:09
2016-04-13T16:34:09
56,168,563
1
0
null
null
null
null
UTF-8
C++
false
false
18,374
cpp
#include <iostream> #include <stdio.h> #include <string> #include <math.h> #include <vector> #include <sstream> #include <stdlib.h> #include <fstream> using namespace std; namespace patch { template < typename T > std::string to_string( const T& n ) { std::ostringstream stm ; stm << n ; return stm.str() ; } } //relation1 file, relation 2 file, record size, page size, number of available pages, maximum number //of hashing rounds //int results; bool chart=true; FILE* result; ofstream log_file; ofstream quiz_output; //FILE* log_file; //int hash(int value,int rounds,int size) //{ /* long long ans=1; for(int i=1;i<=rounds;i++) { ans=ans*value+value*(value + rounds); ans=ans%size; } */ // return (value*rounds+value)%size; //long long value^rounds + value*(value + rounds) // return int(value*rounds*3.14157)%size; //} int hash(int value,int rounds,int max_buckets) { vector<int> bin; int sig_bits=rounds+max_buckets; for(int i=0;i<16;i++) { bin.push_back(0); } int temp= value; for(int i=0;i<16;i++) { bin[15-i]=temp%2; temp=temp/2; // cout<<bin[i]; if(temp==0) break; } int ans=0; for(int i=0;i<sig_bits;i++) { ans=ans+bin[15-i]*pow(2,i); //cout<<bin[i]; } //cout<<"k+ i value"<<ans<<endl; ans=ans%max_buckets; //cout<<ans<<endl; //cout<<endl<<endl; return ans; } void hash_relation(string input_file,int record_size,int page_size,int max_avail_pages,int max_hash_rounds,int rounds,int relation) { FILE* f1; //max_avail_pages=5; //page_size=4; //record_size=2; int records_per_page=floor(page_size/record_size); //int rounds=1; int max_buckets=max_avail_pages-1; FILE* bucket[max_buckets]; FILE* t_pages; //char buffer[50]; //int relation=2; //char file_name[50]; vector<int> t_records,t_flush; cout<<endl; log_file<<endl; cout<<"Performing hashing round : "<<rounds<<endl; log_file<<"Performing hashing round : "<<rounds<<endl; //quiz_output<<"Round : "<<rounds<<endl; string temp,file_name; temp=input_file+".txt"; cout<<"Reading: "<<temp<<endl<<endl; log_file<<"Reading: "<<temp<<endl<<endl; //quiz_output<<"Reading: "<<temp<<endl<<endl; f1=fopen(temp.c_str(),"r"); cout<<"Creating following files:"<<endl; log_file<<"Creating following files:"<<endl; for(int i=0;i<max_buckets;i++) { //file_name="rel"+string(relation)+"_round"+string(itoa(rounds))+"_bucket"+string(itoa(i))+".txt"; //sprintf(file_name,"rel%d_round%d_bucket%d.txt",relation,rounds,i); file_name=input_file+"_bucket"+patch::to_string(i); temp=file_name+".txt"; cout<<temp<<endl; log_file<<temp<<endl; bucket[i]=fopen(temp.c_str(),"w"); t_records.push_back(0); t_flush.push_back(0); } cout<<endl; log_file<<endl; //sprintf(file_name,"rel%d_round%d.txt",relation,rounds); file_name=input_file+"_round"+patch::to_string(rounds); temp=file_name+".txt"; //fwrite(result,"%s\n",temp); //fputs(temp.c_str(),result); //fprintf(result,"\n"); t_pages=fopen(temp.c_str(),"w"); //cout<<"hello"; if(f1 == NULL) { cout<<"Error opening file"<<endl; log_file<<"Error opening file"<<endl; return ; } else { int count =1; vector<int> data[max_buckets]; while ( ! feof (f1) ) { int d; fscanf(f1,"%d",&d); if(feof(f1)) break; // cout<<d<<endl; int t1=hash(d,rounds,max_buckets); //int t1=floor((d+ rounds*3.14157)); //t1=t1%max_buckets; cout<<"Tuple "<<count<<" : value "<<d<<" Mapped to bucket : "<< t1<<endl ; log_file<<"Tuple "<<count<<" : value "<<d<<" Mapped to bucket : "<< t1<<endl ; //fprintf(bucket[t1], "%d\n", d); data[t1].push_back(d); t_records[t1]++; t_flush[t1]++; if(int((t_flush[t1])/records_per_page)==1) { cout<<"Page for bucket "<<t1<<" is full. Flushing to secondary memory"<<endl; log_file<<"Page for bucket "<<t1<<" is full. Flushing to secondary memory"<<endl; for(int i=0;i<data[t1].size();i++) { fprintf(bucket[t1], "%d\n", data[t1][i]); } data[t1].clear(); t_flush[t1]=0; } count++; } cout<<"Flushing all buckets to secondary memory"<<endl; log_file<<"Flushing all buckets to secondary memory"<<endl; for(int i=0;i<max_buckets;i++) { for(int j=0;j<data[i].size();j++) { fprintf(bucket[i], "%d\n", data[i][j]); } data[i].clear(); } rounds++; // cout<<d<<endl; } cout<<endl; log_file<<endl; for(int i=0;i<t_records.size();i++) { cout<<"Bucket "<<i<<" : "<<"Pages required : "<< int(ceil(float(t_records[i])/records_per_page))<<endl; log_file<<"Bucket "<<i<<" : "<<"Pages required : "<< int(ceil(float(t_records[i])/records_per_page))<<endl; fprintf(t_pages,"%d\n",int(ceil(float(t_records[i])/records_per_page))); } for(int i=0;i<max_buckets;i++) { fclose(bucket[i]); } fclose(t_pages); fclose (f1); cout<<endl; } void perform_hashing(string input_file1,string input_file2,int record_size1,int record_size2,int page_size,int max_avail_pages,int max_hash_rounds,int rounds) { //int max_avail_pages=5; //int rounds=1; string temp; if(rounds > max_hash_rounds) { quiz_output<<"Unable to perform join in "<<max_hash_rounds<<" hashing rounds"<<endl<<endl; cout<<"Unable to perform join in "<<max_hash_rounds<<" hashing rounds"<<endl<<endl; log_file<<"Unable to perform join in "<<max_hash_rounds<<" hashing rounds"<<endl<<endl; chart=false; return; } int max_buckets=max_avail_pages-1; //temp = input_file1+".txt"; hash_relation(input_file1,record_size1,page_size,max_avail_pages,max_hash_rounds,rounds,1); hash_relation(input_file2,record_size2,page_size,max_avail_pages,max_hash_rounds,rounds,2); FILE *f1,*f2; string file_name,file_name1; //char file_name[50],file_name1[50]; // sprintf(file_name,"rel1_round%d.txt",rounds); file_name1=input_file1+"_round"+patch::to_string(rounds); temp=file_name1+".txt"; //fputs(temp.c_str(),log_file); //fprintf(log_file,"\n"); //cout<<"opening file "<<temp; f1=fopen(temp.c_str(),"r"); // sprintf(file_name,"rel2_round%d.txt",rounds); file_name1=input_file2+"_round"+patch::to_string(rounds); temp=file_name1+".txt"; //cout<<"opening file "<<temp; f2=fopen(temp.c_str(),"r"); if(f1 == NULL) { cout<<"Error opening file"<<endl; log_file<<"Error opening file"<<endl; return ; } if(f2 == NULL) { cout<<"Error opening file"<<endl; log_file<<"Error opening file"<<endl; return ; } FILE *out1,*out2; int b=0; cout<<"For "+input_file1+" and "+input_file2<<endl<<endl; log_file<<"For "+input_file1+" and "+input_file2<<endl<<endl; quiz_output<<"round : "<<rounds<<endl<<endl; quiz_output<<"Processed "<<input_file1<<endl; quiz_output<<"Processed "<<input_file2<<endl; while ( ! feof (f1) ) { int d1,d2; fscanf(f1,"%d",&d1); fscanf(f2,"%d",&d2); // cout<<d1<<" "<<d2<<endl; if(feof(f1)) break; cout<<"For bucket "<<b<<" :" <<endl; log_file<<"For bucket "<<b<<" :" <<endl; // cout<<d1+d2<<endl; if(d1+d2>max_buckets) { cout<<"Size of relation "<<input_file1<<" : "<<d1<<endl; cout<<"Size of relation "<<input_file2<<" : "<<d2<<endl; cout<<"Total pages required : "<<d1+d2<<endl; cout<<"Cannot perform in memory join for bucket "<<b<<endl; cout<<"Total pages available: " <<max_avail_pages<<endl; log_file<<"Size of relation "<<input_file1<<" : "<<d1<<endl; log_file<<"Size of relation "<<input_file2<<" : "<<d2<<endl; log_file<<"Total pages required : "<<d1+d2<<endl; log_file<<"Cannot perform in memory join for bucket "<<b<<endl; log_file<<"Total pages available: " <<max_avail_pages<<endl; file_name=input_file1+"_bucket"+patch::to_string(b); temp=file_name+".txt"; out1=fopen(temp.c_str(),"r"); //sprintf(file_name,"rel2_round%d_bucket%d.txt",rounds,b); file_name=input_file2+"_bucket"+patch::to_string(b); temp=file_name+".txt"; out2=fopen(temp.c_str(),"r"); if(out1 == NULL) { cout<<"Error opening file"<<endl; return ; } if(out2 == NULL) { cout<<"Error opening file"<<endl; return ; } vector<int> vec1; vector<int> vec2; while ( ! feof (out1) ) { int d1,d2; fscanf(out1,"%d",&d1); if(feof(out1)) break; vec1.push_back(d1); } while ( ! feof (out2) ) { int d1,d2; fscanf(out2,"%d",&d2); if(feof(out2)) break; vec2.push_back(d2); } //sprintf(file_name,"result%d",results); //FILE* r1=fopen(file_name,"w"); //results++; //Zcout<<endl; bool flag=false; quiz_output<<"bucket "<<b<<" :"<<endl; quiz_output<<input_file1<<" Keys :"; for(int i=0;i<vec1.size();i++) { quiz_output<<vec1[i]<<" "; } quiz_output<<" Pages : "<<d1; quiz_output<<endl; quiz_output<<input_file2<<" Keys :"; for(int i=0;i<vec2.size();i++) { quiz_output<<vec2[i]<<" "; } quiz_output<<"Pages : "<<d2<<endl; quiz_output<<"In memory Join :No"<<endl<<endl; // quiz_output<<"In memory join: No"<<endl; //sprintf(file_name,"rel1_round%d_bucket%d.txt",rounds,b); file_name=input_file1+"_bucket"+patch::to_string(b); //temp=file_name+".txt"; // hash_relation(temp.c_str(),record_size1,page_size,max_avail_pages,max_hash_rounds,rounds+1,1); //sprintf(file_name1,"rel2_round%d_bucket%d.txt",rounds,b); file_name1=input_file2+"_bucket"+patch::to_string(b); //temp=file_name+".txt"; //hash_relation(temp.c_str(),record_size2,page_size,max_avail_pages,max_hash_rounds,rounds+1,2); perform_hashing(file_name,file_name1,record_size1,record_size2,page_size,max_avail_pages,max_hash_rounds,rounds+1); // cout<<endl; } else { cout<<"Size of relation "<<input_file1<<" : "<<d1<<endl; cout<<"Size of relation "<<input_file2<<" : "<<d2<<endl; cout<<"Total pages required "<<d1+d2<<endl; cout<<"Total pages available: " <<max_avail_pages<<endl; cout<<"Performing in memory join"<<endl; log_file<<"Size of relation "<<input_file1<<" : "<<d1<<endl; log_file<<"Size of relation "<<input_file2<<" : "<<d2<<endl; log_file<<"Total pages required "<<d1+d2<<endl; log_file<<"Total pages available: " <<max_avail_pages<<endl; log_file<<"Performing in memory join"<<endl; //sprintf(file_name,"rel1_round%d_bucket%d.txt",rounds,b); //file_name="rel1_round"+to_string(rounds)+ file_name=input_file1+"_bucket"+patch::to_string(b); temp=file_name+".txt"; out1=fopen(temp.c_str(),"r"); //sprintf(file_name,"rel2_round%d_bucket%d.txt",rounds,b); file_name=input_file2+"_bucket"+patch::to_string(b); temp=file_name+".txt"; out2=fopen(temp.c_str(),"r"); if(out1 == NULL) { cout<<"Error opening file"<<endl; return ; } if(out2 == NULL) { cout<<"Error opening file"<<endl; return ; } vector<int> vec1; vector<int> vec2; while ( ! feof (out1) ) { int d1,d2; fscanf(out1,"%d",&d1); if(feof(out1)) break; vec1.push_back(d1); } while ( ! feof (out2) ) { int d1,d2; fscanf(out2,"%d",&d2); if(feof(out2)) break; vec2.push_back(d2); } //sprintf(file_name,"result%d",results); //FILE* r1=fopen(file_name,"w"); //results++; //Zcout<<endl; bool flag=false; quiz_output<<"bucket "<<b<<" :"<<endl; quiz_output<<input_file1<<" Keys :"; for(int i=0;i<vec1.size();i++) { quiz_output<<vec1[i]<<" "; } quiz_output<<" Pages : "<<d1; quiz_output<<endl; quiz_output<<input_file2<<" Keys :"; for(int i=0;i<vec2.size();i++) { quiz_output<<vec2[i]<<" "; } quiz_output<<"Pages : "<<d2<<endl; quiz_output<<"In memory Join Yes"<<endl<<endl; for(int i=0;i<vec1.size();i++) { for(int j=0;j<vec2.size();j++) { if(vec1[i]==vec2[j]) { fprintf(result,"%d\n",vec1[i]); if(!flag) { cout<<"Matching tuples are : "; log_file<<"Matching tuples are : "; flag=true; } cout<<vec1[i]<<" "; log_file<<vec1[i]<<" "; } } } if(!flag) { cout<<"No matching tuple. No further processing required"; log_file<<"No matching tuple. No further processing required"; } cout<<endl; log_file<<endl; //fclose(r1); fclose(out1); fclose(out2); } cout<<endl; log_file<<endl; b++; } fclose(f1); fclose(f2); } void join(string input_file1,string input_file2,int record_size1,int record_size2,int page_size,int max_avail_pages,int max_hash_rounds) { FILE *f1,*f2; string temp=input_file1+".txt"; f1=fopen(temp.c_str(),"r"); temp=input_file2+".txt"; f2=fopen(temp.c_str(),"r"); int records_per_page2=floor(page_size/record_size1); int records_per_page1=floor(page_size/record_size2); vector<int> vec1,vec2; if(f1 == NULL) { cout<<"Error opening file"<<endl; log_file<<"Error opening file"<<endl; return ; } if(f2 == NULL) { cout<<"Error opening file"<<endl; log_file<<"Error opening file"<<endl; return ; } int pages1=0,pages2=0; while ( ! feof (f1) ) { int d; fscanf(f1,"%d",&d); if(feof(f1)) break; vec1.push_back(d); pages1++; } while ( ! feof (f2) ) { int d; fscanf(f2,"%d",&d); if(feof(f2)) break; vec2.push_back(d); pages2++; } pages1=ceil(float(pages1)/records_per_page1); pages2=ceil(float(pages2)/records_per_page2); bool flag=false; if(pages1+pages2<max_avail_pages) { cout<<"Size of relation "<<input_file1<<" : "<<pages1<<endl; cout<<"Size of relation "<<input_file2<<" : "<<pages2<<endl; cout<<"Total pages required "<<pages1+pages2<<endl; cout<<"Total pages available: " <<max_avail_pages<<endl; cout<<"Performing in memory join"<<endl; log_file<<"Size of relation "<<input_file1<<" : "<<pages1<<endl; log_file<<"Size of relation "<<input_file2<<" : "<<pages2<<endl; log_file<<"Total pages required "<<pages1+pages2<<endl; log_file<<"Total pages available: " <<max_avail_pages<<endl; log_file<<"Performing in memory join"<<endl; quiz_output<<"round "<<0<<endl<<endl; quiz_output<<"Processed "<<input_file1<<endl; quiz_output<<"Processed "<<input_file2<<endl; quiz_output<<input_file1<<" keys "; for(int i=0;i<vec1.size();i++) { quiz_output<<vec1[i]<<" "; } quiz_output<<"Pages "<<pages1<<endl; quiz_output<<input_file1<<" keys "; for(int i=0;i<vec2.size();i++) { quiz_output<<vec2[i]<<" "; } quiz_output<<"Pages "<<pages2<<endl; quiz_output<<"In memory join : yes"<<endl<<endl; for(int i=0;i<vec1.size();i++) { for(int j=0;j<vec2.size();j++) { if(vec1[i]==vec2[j]) { fprintf(result,"%d\n",vec1[i]); if(!flag) { cout<<"Matching tuples are : "; log_file<<"Matching tuples are : "; flag=true; } cout<<vec1[i]<<" "; log_file<<vec1[i]<<" "; } } } } else { perform_hashing(input_file1,input_file2,record_size1,record_size2,page_size,max_avail_pages,max_hash_rounds,1); } } int main() { //results=0; result=fopen("result.txt","w"); log_file.open("log_file.txt"); quiz_output.open("quiz_output.txt"); int record_size1; int record_size2; int page_size; int max_avail_pages; int max_hash_rounds; string file1; string file2; cout<<"Enter relation 1 name"<<endl; cin>>file1; cout<<"Enter relation 2 name"<<endl; cin>>file2; cout<<"Enter record_size1"<<endl; cin>>record_size1; cout<<"Enter record_size2"<<endl; cin>>record_size2; cout<<"Enter page size"<<endl; cin>>page_size; cout<<"Enter maximum available pages"<<endl; cin>>max_avail_pages; cout<<"Enter maximum hashing rounds"<<endl; cin>>max_hash_rounds; //perform_hashing(file1,file2,record_size1,record_size2,page_size,max_avail_pages,max_hash_rounds,1); join(file1,file2,record_size1,record_size2,page_size,max_avail_pages,max_hash_rounds); //hash_relation("relation1",180,400,5,3,1,1); if(!chart) { cout<<endl; cout<<"Unable to perform join in "<<max_hash_rounds<<" hashing rounds"<<endl<<endl; log_file<<"Unable to perform join in "<<max_hash_rounds<<" hashing rounds"<<endl<<endl; } fclose(result); log_file.close(); quiz_output.close(); }
b56eef226bc6d178bfb5a664a0215622c903e8fa
4153e7912b6cd79ab31fdc18df529b50f1582b67
/seminars/task_3/task_3_3.cpp
56c9f0d1260bce8a4c3ef7e37d33bbc5e47c513a
[ "BSD-3-Clause" ]
permissive
shevkunov/sgtl-and-others
be7c9e4509575fd3bac4dc3ae518425ea58c7eb8
573e8d57c8d0272c025d8509485bec0a26de3153
refs/heads/master
2021-01-19T08:36:04.822435
2017-04-08T18:04:13
2017-04-08T18:04:13
87,650,320
0
0
null
null
null
null
UTF-8
C++
false
false
412
cpp
#include <iostream> #include "barrier.h" int main() { barrier br(3); auto lambda = [&br](size_t id) { while(true) { br.enter(); std::cout << "Broken : " << id << std::endl; } }; std::thread t[3]; for (int i = 0; i < 3; ++i) { t[i] = std::thread(lambda, i); } for (int i = 0; i < 3; ++i) { t[i].join(); } return 0; }
96fc853607179a8b6e5bd1c212a101e1fdf66c93
90e2d052ee6185678b01106ba2e9a180360ac18c
/gameupdate.cpp
522e6ca2a574f9506920ff99e6209bea9fd1efd9
[ "BSD-3-Clause", "IJG" ]
permissive
imoimo2009/tetris
7fe8cf16252195b4db6bf124b96e75bbdf6ba582
69f7f03cdc1b5535bbe94c052de1b5d6136a32c5
refs/heads/master
2020-03-19T08:01:01.140364
2019-02-18T04:10:19
2019-02-18T04:10:19
136,168,497
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
22,515
cpp
// gameupdate.cpp #include "tetris.h" void GameMainUpdate(GameStatus *gs){ if(gs->AnimeTimer == 0){ UserControl(gs); MoveTetriDrop(gs); }else{ gs->AnimeTimer--; if(gs->EraseLineNum > 0){ if(gs->AnimeTimer == L_ERASE_TIME){ EraseBlockLine(gs->Stage,gs->EraseLines); }else if(gs->AnimeTimer == L_DROP_TIME){ DropBlockLine(gs->Stage,gs->Bl_Y - 1); PlaySoundMem(gs->SoundHandle[SOUND_DROP],DX_PLAYTYPE_BACK); }else if(gs->AnimeTimer == L_FLASH_TIME){ PlaySoundMem(gs->SoundHandle[SOUND_FLSH],DX_PLAYTYPE_BACK); }else if(gs->AnimeTimer == 0){ UpdateGameParam(gs); } } if(gs->AnimeTimer <= 0){ ResetTetriBlocks(gs); gs->AnimeTimer = 0; } } if(gs->ReplayMode == REPLAYMODE_PLAY){ if(gs->FadeStart == 1){ if(gs->FadeTimer > FADEOUT_END - FADEOUT_START){ gs->GameMode = GAMEMODE_TITLE; StopSoundMem(gs->SoundHandle[SOUND_BGM]); InitTitle(gs); } gs->FadeTimer += FADE_SPEED; }else{ if(GetJoypadInputState(DX_INPUT_KEY_PAD1) == PAD_INPUT_A){ gs->FadeStart = 1; PlaySoundMem(gs->SoundHandle[SOUND_KEYH],DX_PLAYTYPE_BACK); } } } gs->GameTime++; } void GameInitFirst(GameStatus *gs){ int ret; gs->BgHandle = LoadGraph(BG_FNAME); gs->TitleBgHandle = LoadGraph(TITLEBG_FNAME); gs->OptionCharHandle = LoadGraph(OPTIONCH_FNAME); ret = LoadCharacters(gs->CharHandle,CHAR_FNAME,CHARSET_SIZE_X,CHARSET_SIZE_Y,CHAR_SIZE); ret = LoadCharacters(gs->CharHandle1,CHAR1_FNAME,CHARSET_SIZE_X,CHARSET1_SIZE_Y,CHAR_SIZE); ret = LoadCharacters(gs->FontHandle,FONT_FNAME,FONTSET_SIZE_X,FONTSET_SIZE_Y,FONT_SIZE); LoadSoundFiles(gs->SoundHandle); SetLoopPosSoundMem(BGM_LOOP_POINT,gs->SoundHandle[SOUND_BGM]); gs->CurrentReplay = gs->ReplayStart = NULL; for(int i=0;i<SPEED_MAX;i++){ gs->SpeedTable[i] = GetStrParam(SPEED_TABLE,i*3,2); } DestroyBGHandle(gs->BgChipHandle); if(LoadRankingFile(gs->PlayerRanking,RANKING_FILE) == DXLIB_FALSE){ RankingInit(gs); SaveRankingFile(gs->PlayerRanking,RANKING_FILE); } LoadReplayFile(gs,REPLAY_FILE); OptionInit(&gs->Op); InitTitle(gs); } void InitStatus(GameStatus *gs){ int s_index = STAGE_SIZE_Y * STAGE_SIZE_X; // ステージ初期化 for(int i=0;i<s_index;i++) gs->Stage[i] = BLOCK_OFF; for(int i=0;i<STAGE_SIZE_Y;i++){ int index = i * STAGE_SIZE_X; gs->Stage[index] = gs->Stage[index + 1] = BLOCK_WALL; gs->Stage[index + 12] = gs->Stage[index + 13] = BLOCK_WALL; } for(int i=0;i<(STAGE_SIZE_X*2);i++){ int bot_index = s_index - (STAGE_SIZE_X * 2) + i; gs->Stage[bot_index] = BLOCK_WALL; } // 各パラメータ初期化 gs->Speed = 0; gs->GameTime = 0; gs->Level = 1; gs->Score = 0; gs->GetLines = 0; gs->StackHeight = 0; gs->Hold = 0; gs->FadeStart = 0; gs->FadeTimer = 0; gs->GovCounter = 0; gs->HiScore = gs->PlayerRanking[0].Score; gs->Rank = 0; gs->KeyFlag_A = 1; gs->KeyFlag_B = 1; gs->KeyFlag_C = 0; gs->KeyFlag_L = 1; gs->KeyFlag_R = 1; gs->KeyFlag_UP = 1; gs->KeyRepeat_L = KEY_REPEAT_TIME; gs->KeyRepeat_R = KEY_REPEAT_TIME; // リプレイ用初期化処理 if(gs->ReplayMode == REPLAYMODE_REC){ DATEDATA dd; GetDateTime(&dd); gs->RandSeed = dd.Sec; ResetReplay(gs); }else{ gs->CurrentReplay = gs->ReplayStart; gs->RecordIndex = 0; } SRand(gs->RandSeed); for(int i=0;i<NEXT_NUM;i++) gs->Next[i] = GetRand(TETRI_NUM - 1) + 1; ResetTetriBlocks(gs); SetVolume(gs,VOL_BGM,gs->Op.BgmVolume * VOL_PITCH); SetVolume(gs,VOL_SE,gs->Op.SeVolume * VOL_PITCH); PlaySoundMem(gs->SoundHandle[SOUND_BGM],DX_PLAYTYPE_LOOP); } void ResetTetriBlocks(GameStatus *gs){ gs->Bl_Y = START_POS_Y; gs->Bl_X = START_POS_X; gs->PieceCenter = SetPattern(gs->Piece,RotateNext(gs)); gs->RotateStatus = 0; gs->KeyFlag_UP = 1; gs->KeyFlag_DOWN = 1; gs->KeyFlag_C = 0; gs->EraseLineNum = 0; gs->AnimeTimer = 0; gs->WaitTime = gs->SpeedTable[gs->Speed]; gs->HardDrop = 0; gs->GroundFlag = 0; if(GetCollision(gs->Piece,gs->Stage,gs->Bl_X,gs->Bl_Y) == DXLIB_TRUE){ GameOverInit(gs); } PlaySoundMem(gs->SoundHandle[SOUND_BLIN],DX_PLAYTYPE_BACK); } int SetPattern(int *piece,int type){ int returnValue = DXLIB_FALSE; for(int i=0;i<TETRI_SIZE;i++){ for(int j=0;j<TETRI_SIZE;j++){ piece[i*TETRI_SIZE+j] = BLOCK_OFF; } } switch(type){ case PIECE_TYPE_1: piece[PIECE_1_1] = piece[PIECE_1_2] = piece[PIECE_1_3] = piece[PIECE_1_4] = PIECE_TYPE_1; returnValue = PIECE_CENTER_1; break; case PIECE_TYPE_2: piece[PIECE_2_1] = piece[PIECE_2_2] = piece[PIECE_2_3] = piece[PIECE_2_4] = PIECE_TYPE_2; returnValue = PIECE_CENTER_2; break; case PIECE_TYPE_3: piece[PIECE_3_1] = piece[PIECE_3_2] = piece[PIECE_3_3] = piece[PIECE_3_4] = PIECE_TYPE_3; returnValue = PIECE_CENTER_3; break; case PIECE_TYPE_4: piece[PIECE_4_1] = piece[PIECE_4_2] = piece[PIECE_4_3] = piece[PIECE_4_4] = PIECE_TYPE_4; returnValue = PIECE_CENTER_4; break; case PIECE_TYPE_5: piece[PIECE_5_1] = piece[PIECE_5_2] = piece[PIECE_5_3] = piece[PIECE_5_4] = PIECE_TYPE_5; returnValue = PIECE_CENTER_5; break; case PIECE_TYPE_6: piece[PIECE_6_1] = piece[PIECE_6_2] = piece[PIECE_6_3] = piece[PIECE_6_4] = PIECE_TYPE_6; returnValue = PIECE_CENTER_6; break; case PIECE_TYPE_7: piece[PIECE_7_1] = piece[PIECE_7_2] = piece[PIECE_7_3] = piece[PIECE_7_4] = PIECE_TYPE_7; returnValue = PIECE_CENTER_7; break; } return returnValue; } int LoadCharacters(int *gHandle,const char *str,int width,int height,int size){ const int allNum = width * height; int retVal; retVal = LoadDivGraph(str,allNum,width,height,size,size,gHandle); return retVal; } int GetDigitNum(int num,int digit){ char buf[STRING_BUFFER]; int digit_max; int returnValue; sprintf_s(buf,STRING_BUFFER,"%d",num); digit_max = (int)strlen(buf); if(digit >= digit_max) return DXLIB_FALSE; returnValue = (int)(buf[(digit_max - digit) - 1] - '0'); return returnValue; } void MoveTetriDrop(GameStatus *gs){ const int waitDrop = gs->SpeedTable[gs->Speed]; if(gs->GroundFlag == 0){ if(GetCollision(gs->Piece,gs->Stage,gs->Bl_X,gs->Bl_Y + 1) == DXLIB_TRUE){ gs->WaitTime = gs->SpeedTable[0]; gs->GroundFlag = 1; PlaySoundMem(gs->SoundHandle[SOUND_BHIT],DX_PLAYTYPE_BACK); } }else{ if(GetCollision(gs->Piece,gs->Stage,gs->Bl_X,gs->Bl_Y + 1) == DXLIB_FALSE){ gs->WaitTime = waitDrop; gs->GroundFlag = 0; } } if(gs->HardDrop == 1){ gs->Bl_Y = GetGhostPos(gs->Stage,gs->Piece,gs->Bl_X,gs->Bl_Y); gs->WaitTime = 0; PlaySoundMem(gs->SoundHandle[SOUND_HDRP],DX_PLAYTYPE_BACK); } gs->WaitTime--; if(gs->WaitTime < 0){ gs->Bl_Y++; gs->WaitTime = waitDrop; if(GetCollision(gs->Piece,gs->Stage,gs->Bl_X,gs->Bl_Y) == DXLIB_TRUE){ StackBlock(gs,gs->Bl_X,gs->Bl_Y-1); gs->EraseLineNum = ScanBlockLine(gs->Stage,gs->EraseLines,gs->Bl_Y-1); if(gs->EraseLineNum == 0) gs->AnimeTimer = BLOCK_RECAST; else gs->AnimeTimer = ANIME_TIME; if(gs->StackHeight >= PINCH_HEIGHT){ SetFrequencySoundMem(PINCH_FREQ,gs->SoundHandle[SOUND_BGM]); } } } } int TetriRotate(GameStatus *gs,int rotate){ int tmpPiece[TETRI_SIZE * TETRI_SIZE]; int stat = gs->RotateStatus; const int pieceNum = TETRI_SIZE * TETRI_SIZE; const int ptype = gs->Next[0]; const int rOffsetX[] = { 1, 0,-1, 0, 0}; const int rOffsetY[] = { 0, 1, 0,-1, 0}; int ox,oy,ov,oIndex; int offset_X = 0; int offset_Y = 0; if((ptype == PIECE_TYPE_1)||(ptype == PIECE_TYPE_3)||(ptype == PIECE_TYPE_4)){ if(stat == 1) rotate = ROTATE_LEFT; else if(stat == 0) rotate = ROTATE_RIGHT; } for(int i=0;i<TETRI_SIZE;i++){ for(int j=0;j<TETRI_SIZE;j++){ int index; switch(rotate){ case ROTATE_RIGHT: index = (12 + i) - (j * TETRI_SIZE); break; case ROTATE_LEFT: index = (3 - i) + (j * TETRI_SIZE); break; } tmpPiece[i*TETRI_SIZE + j] = gs->Piece[index]; } } if(rotate == ROTATE_RIGHT){ stat++; ov = 1; if(stat > 3) stat = 0; }else{ stat--; ov = -1; if(stat < 0) stat = 3; } if(gs->PieceCenter == 0){ oIndex = 4; }else if(gs->PieceCenter == 1){ oIndex = stat; }else { oIndex = stat - 1; if(oIndex < 0) oIndex = 3; } if(ov == -1){ oIndex = 3 - oIndex; if(oIndex < 0) oIndex = 4; } ox = gs->Bl_X + (rOffsetX[oIndex] * ov); oy = gs->Bl_Y + (rOffsetY[oIndex]); offset_Y = PieceOffsetY(tmpPiece,gs->Stage,ox,oy); offset_X = PieceOffsetX(tmpPiece,gs->Stage,ox,oy + offset_Y); if(offset_X == ROTATE_NOT) return DXLIB_FALSE; //if(GetCollision(tmpPiece,gs->Stage,ox,oy) == DXLIB_TRUE) return DXLIB_FALSE; for(int i=0;i<pieceNum;i++) gs->Piece[i] = tmpPiece[i]; gs->RotateStatus = stat; gs->Bl_X = ox + offset_X; gs->Bl_Y = oy + offset_Y; PlaySoundMem(gs->SoundHandle[SOUND_ROTE],DX_PLAYTYPE_BACK); return DXLIB_TRUE; } int GetCollision(int *piece,int *stage,int x,int y){ int colFlag = DXLIB_FALSE; for(int i=0;i<TETRI_SIZE;i++){ for(int j=0;j<TETRI_SIZE;j++){ int p_index = i * TETRI_SIZE + j; int s_index = (i + y) * STAGE_SIZE_X + (j + x); if(piece[p_index] > 0){ if(stage[s_index] > 0) colFlag = DXLIB_TRUE; } } } return colFlag; } void StackBlock(GameStatus *gs,int x,int y){ const int stageTop = STAGE_SIZE_X * STAGE_CLIP; const int stageBot = STAGE_SIZE_Y - STAGE_CLIP; int pieceHeight = 0; int stage_mask[] = {1,1,1,1,1,0,0,0,0,1,1,1,1,1}; for(int i=0;i<TETRI_SIZE;i++){ for(int j=0;j<TETRI_SIZE;j++){ int p_index = i * TETRI_SIZE + j; int mask_index = j + x; int s_index = (i + y) * STAGE_SIZE_X + mask_index; if(gs->Piece[p_index] > BLOCK_OFF){ if((s_index > stageTop)||(stage_mask[mask_index] == 0)){ gs->Stage[s_index] = gs->Piece[p_index]; if(pieceHeight == 0) pieceHeight = stageBot - (y + i); } } } } if(gs->StackHeight < pieceHeight) gs->StackHeight = pieceHeight; } int UserControl(GameStatus *gs){ int vx = 0; int stick; if(gs->ReplayMode == REPLAYMODE_REC){ stick = GetJoypadInputState(DX_INPUT_KEY_PAD1); RecordReplay(gs,stick); }else{ stick = PlaybackReplay(gs); if(stick == DXLIB_FALSE){ gs->GameMode = GAMEMODE_TITLE; return 0; } } // 左移動 if(stick & PAD_INPUT_LEFT){ if(gs->KeyFlag_L == 0){ vx = -1; gs->KeyFlag_L = 1; }else{ gs->KeyRepeat_L--; if(gs->KeyRepeat_L <= 0){ gs->KeyFlag_L = 0; gs->KeyRepeat_L = 0; } } }else{ gs->KeyFlag_L = 0; gs->KeyRepeat_L = KEY_REPEAT_TIME; } // 右移動 if(stick & PAD_INPUT_RIGHT){ if(gs->KeyFlag_R == 0){ vx = 1; gs->KeyFlag_R = 1; }else{ gs->KeyRepeat_R--; if(gs->KeyRepeat_R <= 0){ gs->KeyFlag_R = 0; gs->KeyRepeat_R = 0; } } }else{ gs->KeyFlag_R = 0; gs->KeyRepeat_R = KEY_REPEAT_TIME; } // 下入力(高速落下) if(stick & PAD_INPUT_DOWN){ if(gs->KeyFlag_DOWN == 0){ gs->WaitTime = 0; vx = 0; } }else{ gs->KeyFlag_DOWN = 0; } // 上入力(ハードドロップ) if(gs->Op.HardDrop == 1){ if(stick & PAD_INPUT_UP){ if(gs->KeyFlag_UP == 0){ gs->HardDrop = 1; gs->KeyFlag_UP = 1; vx = 0; } }else{ gs->KeyFlag_UP = 0; } } // 座標計算 if(GetCollision(gs->Piece,gs->Stage,gs->Bl_X+vx,gs->Bl_Y) == DXLIB_TRUE) vx = 0; gs->Bl_X += vx; // ボタン1(右回転) if(stick & gs->Op.KeyRight){ if(gs->KeyFlag_A == 0){ TetriRotate(gs,ROTATE_RIGHT); gs->KeyFlag_A = 1; } }else{ gs->KeyFlag_A = 0; } // ボタン2(左回転) if(stick & gs->Op.KeyLeft){ if(gs->KeyFlag_B == 0){ TetriRotate(gs,ROTATE_LEFT); gs->KeyFlag_B = 1; } }else{ gs->KeyFlag_B = 0; } // ボタン3(HOLD機能) if(gs->Op.Hold == 1){ if(stick & gs->Op.KeyHold){ if(gs->KeyFlag_C == 0){ if(GetHoldBlock(gs) != DXLIB_FALSE) gs->KeyFlag_C = 1; } } } return stick; } int RotateNext(GameStatus *gs){ for(int i=1;i<NEXT_NUM;i++) gs->Next[i-1] = gs->Next[i]; gs->Next[NEXT_NUM-1] = GetRandomPiece(gs->Next); return gs->Next[0]; } int ScanBlockLine(int *stage,int *eraseLines,int row){ int lines = 0; for(int i=0;i<STAGE_SIZE_Y;i++) eraseLines[i] = BLOCK_OFF; for(int i=0;i<TETRI_SIZE;i++){ int count = 0; if(CheckBlockLine(stage,row + i) == C_LINE_FULL){ eraseLines[i + row] = BLOCK_ENABLE; lines++; } } return lines; } void EraseBlockLine(int *stage,int *eraseLines){ const int stageBot = STAGE_SIZE_Y - STAGE_CLIP; const int stageTop = STAGE_CLIP; for(int i=stageTop;i<stageBot;i++){ if(eraseLines[i] == BLOCK_ENABLE){ for(int j=STAGE_CLIP;j<(STAGE_SIZE_X-STAGE_CLIP);j++){ int index = i * STAGE_SIZE_X + j; stage[index] = BLOCK_OFF; } } } } void DropBlockLine(int *stage,int row){ int scanY = row + TETRI_SIZE - 1; int scanLimit = TETRI_SIZE; const int stageLeft = STAGE_CLIP; const int stageRight = STAGE_SIZE_X - STAGE_CLIP; const int stageTop = STAGE_CLIP; const int stageBot = STAGE_SIZE_Y - STAGE_CLIP; const int scanEnd = row; if(scanY >= stageBot) scanY = stageBot - 1; while((scanY >= scanEnd)&&(scanLimit >= 0)){ if(CheckBlockLine(stage,scanY) == C_LINE_EMPTY){ for(int i=scanY;i>stageTop;i--){ CopyBlockLine(stage,i - 1,i); } for(int i=stageLeft;i<stageRight;i++){ const int index = STAGE_CLIP * STAGE_SIZE_X + i; stage[index] = BLOCK_OFF; } } if(CheckBlockLine(stage,scanY) != C_LINE_EMPTY){ scanY--; } scanLimit--; } } int UpdateGameParam(GameStatus *gs){ gs->Score += gs->EraseLineNum * gs->EraseLineNum * 10; if(gs->Score > gs->HiScore) gs->HiScore = gs->Score; gs->GetLines += gs->EraseLineNum; gs->StackHeight -= gs->EraseLineNum; if(gs->GetLines >= (gs->Level * LEVEL_UP_LINES)){ gs->Level++; gs->Speed++; if(gs->Speed >= SPEED_MAX) gs->Speed = 5; PlaySoundMem(gs->SoundHandle[SOUND_LVUP],DX_PLAYTYPE_BACK); } if(gs->StackHeight < PINCH_HEIGHT){ SetFrequencySoundMem(NORMAL_FREQ,gs->SoundHandle[SOUND_BGM]); } return gs->EraseLineNum; } void CopyBlockLine(int *stage,int orgLine,int copyLine){ const int stageLeft = STAGE_CLIP; const int stageRight = STAGE_SIZE_X - STAGE_CLIP; const int orgDes = orgLine * STAGE_SIZE_X; const int copyDes = copyLine * STAGE_SIZE_X; for(int i=stageLeft;i<stageRight;i++){ int s_index = orgDes + i; int c_index = copyDes + i; stage[c_index] = stage[s_index]; } } int CheckBlockLine(int *stage,int checkLine){ const int stageLeft = STAGE_CLIP; const int stageRight = STAGE_SIZE_X - STAGE_CLIP; const int checkDes = checkLine * STAGE_SIZE_X; int count = 0; for(int i=stageLeft;i<stageRight;i++){ int index = checkDes + i; if((stage[index] > 0)&&(stage[index] < 9)) count++; } return count; } int GetGhostPos(int *stage,int *piece,int x,int y){ while(GetCollision(piece,stage,x,y) == DXLIB_FALSE) y++; return --y; } int GetHoldBlock(GameStatus *gs){ int tmpHold; int offset_X = 0; int tmpPiece[TETRI_SIZE * TETRI_SIZE]; if(gs->Hold == 0){ gs->Hold = gs->Next[0]; gs->AnimeTimer = BLOCK_RECAST; }else{ tmpHold = gs->Hold; SetPattern(tmpPiece,tmpHold); offset_X = PieceOffsetX(tmpPiece,gs->Stage,gs->Bl_X,gs->Bl_Y); if(offset_X == ROTATE_NOT) return DXLIB_FALSE; gs->Bl_X += offset_X; gs->Hold = gs->Next[0]; gs->Next[0] = tmpHold; SetPattern(gs->Piece,gs->Next[0]); } PlaySoundMem(gs->SoundHandle[SOUND_HOLD],DX_PLAYTYPE_BACK); return gs->Hold; } int PieceOffsetX(int *piece,int *stage,int x,int y){ int offset = 0; if(GetCollision(piece,stage,x,y) == DXLIB_FALSE) return 0; for(int i=-2;i<=2;i++){ int of_x = x + i; int returnValue; if(of_x < 0) of_x = 0; else if(of_x > STAGE_SIZE_X - TETRI_SIZE) of_x = STAGE_SIZE_X - TETRI_SIZE; returnValue = GetCollision(piece,stage,of_x,y); if(returnValue == DXLIB_FALSE){ if(i == 0) return 0; else if(offset == 0) offset = i; } } if(offset == 0) return ROTATE_NOT; return offset; } int PieceOffsetY(int *piece,int *stage,int x,int y){ int offset = 0; if(GetCollision(piece,stage,x,y) == DXLIB_FALSE) return 0; for(int i=1;i<=2;i++){ int of_y = y - i; int returnValue; if(of_y > STAGE_SIZE_Y - TETRI_SIZE) of_y = STAGE_SIZE_Y - TETRI_SIZE; returnValue = GetCollision(piece,stage,x,of_y); if(returnValue == DXLIB_FALSE){ if(offset == 0) offset = -i; } } return offset; } int LoadSoundFiles(int *sHandle){ sHandle[SOUND_BGM] = LoadSoundMem(S_FN_BGM); sHandle[SOUND_BLIN] = LoadSoundMem(S_FN_BLIN); sHandle[SOUND_BHIT] = LoadSoundMem(S_FN_BHIT); sHandle[SOUND_DROP] = LoadSoundMem(S_FN_DROP); sHandle[SOUND_HOLD] = LoadSoundMem(S_FN_HOLD); sHandle[SOUND_ROTE] = LoadSoundMem(S_FN_ROTE); sHandle[SOUND_FLSH] = LoadSoundMem(S_FN_FLSH); sHandle[SOUND_KEYH] = LoadSoundMem(S_FN_KEYH); sHandle[SOUND_HDRP] = LoadSoundMem(S_FN_HDRP); sHandle[SOUND_LVUP] = LoadSoundMem(S_FN_LVUP); sHandle[SOUND_GOVR] = LoadSoundMem(S_FN_GOVR); for(int i=0;i<SOUND_NUM;i++){ if(sHandle[i] == DXLIB_FALSE) return DXLIB_FALSE; } return DXLIB_TRUE; } int GetRandomPiece(int *next){ int rnd,repeat= 1; while(repeat){ rnd = GetRand(TETRI_NUM - 1) + 1; repeat = 0; for(int i=1;i<NEXT_NUM;i++){ if(rnd == next[i]) repeat = 1; } } return rnd; } void GameOverUpdate(GameStatus *gs){ int stick = GetJoypadInputState(DX_INPUT_KEY_PAD1); if(gs->GovCounter > GOVERDEMO_END){ if((stick > 0)&&(stick != PAD_INPUT_M)){ if(gs->KeyFlag_A == 0){ gs->Rank = CheckRanking(gs->PlayerRanking,gs->Score,gs->GetLines); if((gs->Rank != DXLIB_FALSE)&&(gs->ReplayMode == REPLAYMODE_REC)){ StartRankingInput(gs); }else InitTitle(gs); gs->KeyFlag_A = 1; PlaySoundMem(gs->SoundHandle[SOUND_KEYH],DX_PLAYTYPE_BACK); } }else gs->KeyFlag_A = 0; gs->FadeTimer++; if(gs->FadeTimer > GOVFADE_END) gs->FadeTimer = GOVFADE_END; }else if(gs->GovCounter == GOVERDEMO_END){ int tetriMax = TETRI_SIZE * TETRI_SIZE; for(int i=0;i<tetriMax;i++){ if(gs->Piece[i] > 0) gs->Piece[i] = BLOCK_WALL; } }else{ int gy = STAGE_SIZE_Y - STAGE_CLIP - gs->GovCounter - 1; int stg_left = STAGE_SIZE_X - STAGE_CLIP; for(int i=STAGE_CLIP;i<stg_left;i++){ int index = gy * STAGE_SIZE_X + i; if(gs->Stage[index] > 0) gs->Stage[index] = BLOCK_WALL; } } if((gs->GameTime % GOVERDEMO_TIME) == 0) gs->GovCounter++; gs->GameTime++; } void SetBlockMask(int *mask,int x,int y){ int stage_mask[] = {1,1,1,1,1,0,0,0,0,1,1,1,1,1}; if(y == 0){ for(int i=0;i<TETRI_SIZE;i++){ int index = i + x; mask[i] = MASK_ON; mask[i + TETRI_SIZE] = stage_mask[index]; } }else if(y == 1){ for(int i=0;i<TETRI_SIZE;i++){ int index = i + x; mask[i] = stage_mask[index]; mask[i + TETRI_SIZE] = MASK_OFF; } } } void RecordReplay(GameStatus *gs,int stick){ Replay *rp; if(stick != 0){ if(gs->ReplayStart == NULL){ rp = new Replay; rp->Next = NULL; rp->Stick = stick; rp->GameTime = gs->GameTime; gs->ReplayStart = gs->CurrentReplay = rp; }else{ rp = gs->CurrentReplay; rp->Next = new Replay; rp->Next->Next = NULL; rp->Next->GameTime = gs->GameTime; rp->Next->Stick = stick; gs->CurrentReplay = rp->Next; } gs->RecordIndex++; } } int PlaybackReplay(GameStatus *gs){ Replay *rp = gs->CurrentReplay; if(rp == NULL) goto END_OF_RECORD; if(rp->GameTime == gs->GameTime){ gs->CurrentReplay = rp->Next; gs->RecordIndex++; return rp->Stick; } END_OF_RECORD: return 0; } void ResetReplay(GameStatus *gs){ Replay *rp = gs->ReplayStart; gs->RecordIndex = 0; if(rp == NULL) return; while(rp->Next != NULL){ Replay *rt = rp->Next; delete rp; rp = rt; } delete rp; gs->ReplayStart = gs->CurrentReplay = NULL; } void GameOverInit(GameStatus *gs){ StopSoundMem(gs->SoundHandle[SOUND_BGM]); SetFrequencySoundMem(NORMAL_FREQ,gs->SoundHandle[SOUND_BGM]); PlaySoundMem(gs->SoundHandle[SOUND_GOVR],DX_PLAYTYPE_BACK); gs->GameMode = GAMEMODE_GOV; gs->FadeStart = 0; gs->FadeTimer = 0; } int LoadRankingFile(Ranking *rp,char *str){ FILE *fp; char buf[STRING_BUFFER]; if(fopen_s(&fp,str,"r") != 0) return DXLIB_FALSE; for(int i=0;i<RANK_MAX;i++){ fgets(buf,STRING_BUFFER,fp); rp[i].Date.Year = GetStrParam(buf,3,4); rp[i].Date.Mon = GetStrParam(buf,8,2); rp[i].Date.Day = GetStrParam(buf,11,2); rp[i].Date.Hour = GetStrParam(buf,14,2); rp[i].Date.Min = GetStrParam(buf,17,2); rp[i].Score = GetStrParam(buf,20,7); rp[i].Lines = GetStrParam(buf,28,4); for(int j=0;j<RANKING_NAME;j++){ int index = 33 + j * 3; rp[i].Name[j] = GetStrParam(buf,index,2); } } fclose(fp); return DXLIB_TRUE; } int SaveRankingFile(Ranking *rp,char *str){ FILE *fp; char buf[STRING_BUFFER]; if(fopen_s(&fp,str,"w") != 0) return DXLIB_FALSE; for(int i=0;i<RANK_MAX;i++){ const int rank = i + 1; const int year = rp[i].Date.Year; const int month = rp[i].Date.Mon; const int day = rp[i].Date.Day; const int hour = rp[i].Date.Hour; const int minit = rp[i].Date.Min; const int score = rp[i].Score; const int line = rp[i].Lines; int *name = rp[i].Name; sprintf_s(buf,STRING_BUFFER ,"%02d,%04d,%02d,%02d,%02d,%02d,%07d,%04d,%02d,%02d,%02d,%02d,%02d\n" ,rank,year,month,day,hour,minit,score,line ,name[0],name[1],name[2],name[3],name[4] ); fputs(buf,fp); } fclose(fp); return DXLIB_TRUE; } int GetStrParam(char *str,int start,int digit){ char buf[STRING_BUFFER]; const int len = strlen(str); int endpos = start + digit; if(start > len) return DXLIB_FALSE; if(endpos > len){ digit = len - start; endpos = len; } for(int i=start;i<endpos;i++){ const int index = i - start; buf[index] = str[i]; buf[index + 1] = NULL; } return atoi(buf); } int LoadReplayFile(GameStatus *gs,char *str){ FILE *fp; int count = 0; int seed; if(fopen_s(&fp,str,"rb") != 0) return DXLIB_FALSE; ResetReplay(gs); fread(&seed,sizeof(int),1,fp); gs->RandSeed = seed; while(feof(fp) == 0){ int time; int stick; fread(&time,sizeof(int),1,fp); fread(&stick,sizeof(int),1,fp); gs->GameTime = time; RecordReplay(gs,stick); count++; } fclose(fp); return DXLIB_TRUE; } int SaveReplayFile(GameStatus *gs,char *str){ FILE *fp; Replay *rp = gs->ReplayStart; int time,stick; const int seed = gs->RandSeed; if(fopen_s(&fp,str,"wb") != 0) return DXLIB_FALSE; fwrite(&seed,sizeof(int),1,fp); while(rp->Next !=NULL){ time = rp->GameTime; stick = rp->Stick; fwrite(&time,sizeof(int),1,fp); fwrite(&stick,sizeof(int),1,fp); rp = rp->Next; } time = rp->GameTime; stick = rp->Stick; fwrite(&time,sizeof(int),1,fp); fwrite(&stick,sizeof(int),1,fp); fclose(fp); return DXLIB_TRUE; } void SetVolume(GameStatus *gs,int mode,int volume){ if(mode == 0){ ChangeVolumeSoundMem(volume,gs->SoundHandle[SOUND_BGM]); }else{ for(int i=SOUND_BLIN;i<SOUND_NUM;i++){ ChangeVolumeSoundMem(volume,gs->SoundHandle[i]); } } }
[ "今西弘治" ]
今西弘治
5db9e9a0255f8b5f096e11e57d638d921f699e25
402d447604a9443f9085786753e36edc89f25890
/Longest_Substring_Without_Repeating_Characters.cpp
f9743cac7e6dc659b272d0b0d6dc7a624a8937b2
[]
no_license
whodewho/leetcode
4f8c1b8064985482d495ec0b3ecf7f1f524cd039
10b9b106c7ae0c0bff383bf79dbe079b8d240b50
refs/heads/master
2021-01-21T21:39:37.151922
2016-04-06T11:21:43
2016-04-06T11:21:43
28,042,560
0
0
null
null
null
null
UTF-8
C++
false
false
539
cpp
//O(N*N) class Solution { public: int lengthOfLongestSubstring(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if(s.empty())return 0; int result=1,last=1; for(int i=1;i!=s.size();i++) { int j=i-1; while(j>=0&&s[j]!=s[i]&&i-last<=j)j--; last=i-j; result=max(last,result); } return result; } };
1ec1051b171758fb87a0bab29cc9c446ad1a97df
07a4c96f62a92fab367e4909d3c92ac877a4fd46
/LF/LF/lfinterpolate.h
c73824aa41854da63928ea0e2843d61aee18394e
[]
no_license
sushantojal/Multi-Perspective-Stereoscopy-from-Light-Fields
78bb150595ae9e7fc7abf19e7077009bb6609f97
21ba394e574d14bf7d9d5ed3ba7f171f0b8f1971
refs/heads/master
2021-04-29T08:11:42.999570
2016-12-30T02:26:19
2016-12-30T02:26:19
77,652,718
3
0
null
null
null
null
UTF-8
C++
false
false
492
h
#pragma once #include <cstdio> #include <fstream> #include <string> #include <cstring> #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "opencv2/imgproc/imgproc.hpp" #include <math.h> using namespace std; using namespace cv; //for interpolating and synthesising more images from a light field with a lesser number of miages. class lfinterpolate { private: Mat interplf; public: Mat interp(Mat rvolume, Mat dvolume, int grain); };
f2bc62757fd8eeb9c068d467a1726ab8651310bf
521685507e5b26ec9be38b39a249bdc1ee638138
/Servers/Filters/vtkMultiViewManager.cxx
4dd1c3d694e23b2b3f40c08e07ff94e373731e1d
[ "LicenseRef-scancode-paraview-1.2" ]
permissive
matthb2/ParaView-beforekitwareswtichedtogit
6ad4662a1ad8c3d35d2c41df209fc4d78b7ba298
392519e17af37f66f6465722930b3705c1c5ca6c
refs/heads/master
2020-04-05T05:11:15.181579
2009-05-26T20:50:10
2009-05-26T20:50:10
211,087
1
2
null
null
null
null
UTF-8
C++
false
false
6,329
cxx
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMultiViewManager.h" #include "vtkObjectFactory.h" #include "vtkMemberFunctionCommand.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRendererCollection.h" #include "vtkSmartPointer.h" #include <vtkstd/map> class vtkMultiViewManager::vtkRendererMap : public vtkstd::map<int, vtkSmartPointer<vtkRendererCollection> > { }; vtkStandardNewMacro(vtkMultiViewManager); vtkCxxRevisionMacro(vtkMultiViewManager, "$Revision$"); //---------------------------------------------------------------------------- vtkMultiViewManager::vtkMultiViewManager() { this->RenderWindow = 0; this->ActiveViewID = 0; this->FixViewport = false; this->RendererMap = new vtkRendererMap(); vtkMemberFunctionCommand<vtkMultiViewManager>* obs = vtkMemberFunctionCommand<vtkMultiViewManager>::New(); obs->SetCallback(*this, &vtkMultiViewManager::StartRenderCallback); this->Observer = obs; } //---------------------------------------------------------------------------- vtkMultiViewManager::~vtkMultiViewManager() { this->SetRenderWindow(0); this->Observer->Delete(); delete this->RendererMap; this->RendererMap = 0; } //---------------------------------------------------------------------------- void vtkMultiViewManager::SetRenderWindow(vtkRenderWindow* win) { if (this->RenderWindow) { this->RenderWindow->RemoveObserver(this->Observer); } vtkSetObjectBodyMacro(RenderWindow, vtkRenderWindow, win); if (this->RenderWindow) { // We want our event handler to be called before the event handler in the // parallel render manager. this->RenderWindow->AddObserver(vtkCommand::StartEvent, this->Observer, 100); } } //---------------------------------------------------------------------------- vtkRendererCollection* vtkMultiViewManager::GetActiveRenderers() { return this->GetRenderers(this->ActiveViewID); } //---------------------------------------------------------------------------- vtkRendererCollection* vtkMultiViewManager::GetRenderers(int id) { vtkRendererMap::iterator iter = this->RendererMap->find(id); if (iter != this->RendererMap->end()) { return iter->second.GetPointer(); } return 0; } //---------------------------------------------------------------------------- void vtkMultiViewManager::StartMagnificationFix() { this->FixViewport = false; vtkRendererCollection* renderers = this->GetActiveRenderers(); if (!renderers) { vtkErrorMacro("No active renderers selected!"); return; } int *size = this->RenderWindow->GetActualSize(); this->OriginalRenderWindowSize[0] = size[0]; this->OriginalRenderWindowSize[1] = size[1]; renderers->InitTraversal(); vtkRenderer* ren = renderers->GetNextItem(); ren->GetViewport(this->OriginalViewport); int newSize[2]; newSize[0] = int((this->OriginalViewport[2]-this->OriginalViewport[0])*size[0] + 0.5); newSize[1] = int((this->OriginalViewport[3]-this->OriginalViewport[1])*size[1]+0.5); this->RenderWindow->SetSize(newSize); renderers->InitTraversal(); while ( (ren = renderers->GetNextItem()) != 0) { ren->SetViewport(0, 0, 1, 1); } this->FixViewport = true; } //---------------------------------------------------------------------------- void vtkMultiViewManager::EndMagnificationFix() { if (!this->FixViewport) { return; } vtkRendererCollection* renderers = this->GetActiveRenderers(); renderers->InitTraversal(); while (vtkRenderer* ren = renderers->GetNextItem()) { ren->SetViewport(this->OriginalViewport); } this->FixViewport = false; this->RenderWindow->SetSize(this->OriginalRenderWindowSize); } //---------------------------------------------------------------------------- void vtkMultiViewManager::StartRenderCallback() { vtkRendererMap::iterator iter = this->RendererMap->begin(); for (; iter != this->RendererMap->end(); ++iter) { vtkRendererCollection* renderers = iter->second.GetPointer(); renderers->InitTraversal(); while (vtkRenderer* ren = renderers->GetNextItem()) { ren->DrawOff(); } } vtkRendererCollection* renderers = this->GetActiveRenderers(); if (!renderers) { vtkErrorMacro("No active renderers selected!"); return; } renderers->InitTraversal(); while (vtkRenderer* ren = renderers->GetNextItem()) { ren->DrawOn(); } } //---------------------------------------------------------------------------- void vtkMultiViewManager::AddRenderer(int id, vtkRenderer* ren) { vtkRendererMap::iterator iter = this->RendererMap->find(id); if (iter== this->RendererMap->end()) { (*this->RendererMap)[id] = vtkSmartPointer<vtkRendererCollection>::New(); iter = this->RendererMap->find(id); } iter->second.GetPointer()->AddItem(ren); } //---------------------------------------------------------------------------- void vtkMultiViewManager::RemoveRenderer(int id, vtkRenderer* ren) { vtkRendererMap::iterator iter = this->RendererMap->find(id); if (iter!= this->RendererMap->end()) { iter->second.GetPointer()->RemoveItem(ren); } } //---------------------------------------------------------------------------- void vtkMultiViewManager::RemoveAllRenderers(int id) { vtkRendererMap::iterator iter = this->RendererMap->find(id); if (iter!= this->RendererMap->end()) { this->RendererMap->erase(iter); } } //---------------------------------------------------------------------------- void vtkMultiViewManager::RemoveAllRenderers() { this->RendererMap->clear(); } //---------------------------------------------------------------------------- void vtkMultiViewManager::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
1f25405460f4106e739b604e971d7a547059ed4a
bba62e6e48e60e4e41469061594cf1d6a96eb2fb
/tools/qcheck/main.cpp
28ab74e36e9bb771f13f7d437760fc9bc489e3d4
[ "MIT" ]
permissive
antonovvk/geonames
0f2ad5127be118899073d7657d5a69d9c149a491
aedf20574636eb6618337f7fa63d81f4c8c81e56
refs/heads/master
2020-12-24T07:35:21.414486
2016-10-21T09:44:27
2016-10-21T09:44:27
58,719,197
0
0
null
null
null
null
UTF-8
C++
false
false
8,748
cpp
#include <vector> #include <fstream> #include <codecvt> #include <tclap/CmdLine.h> #include "src/json.hpp" #include "geonames/geonames.h" using namespace std; void JsonResult(nlohmann::json& res, const string& name, const geonames::ParsedObject& obj, bool printTokens) { if (!obj) { return; } wstring_convert<codecvt_utf8<char32_t>, char32_t> utf8codec; res[name] = { { "name", utf8codec.to_bytes(obj.Object_->Name()) }, { "latitude", obj.Object_->Latitude() }, { "longitude", obj.Object_->Longitude() } }; if (printTokens) { res[name + "_tokens"] = obj.Tokens_; } } int Main(int argc, char* argv[]) { TCLAP::CmdLine cmd("Geonames quality checker"); TCLAP::ValueArg<string> input("i", "input", "Input file", false, "", "file_name", cmd); TCLAP::MultiArg<string> queries("q", "query", "Query string (discards -i)", false, "string", cmd); TCLAP::ValueArg<string> jsonField("j", "json-field", "Input is json object per line, read given field", true, "", "field", cmd); TCLAP::ValueArg<string> output("o", "output", "Output file", false, "", "file_name", cmd); TCLAP::ValueArg<string> jsonUpdate("", "json-update", "Input file is json object per line, add result as field obj", false, "", "field", cmd); TCLAP::ValueArg<double> mergeNear("m", "merge-near", "Merge nearby ambiguous results", false, 0, "haversine distance", cmd); TCLAP::SwitchArg uniqueOnly("u", "unique-only", "Output only results with unique match", cmd); TCLAP::SwitchArg tokens("t", "tokens", "Output tokens used to deduce objects", cmd); TCLAP::SwitchArg oneLine("1", "one-line", "Output result JSON in one line per request", cmd); TCLAP::SwitchArg compareResults("", "compare-results", "Used with --json-update. Extract position from existing object and compare", cmd); TCLAP::ValueArg<double> epsilon("e", "epsilon", "Report errors if distance more than epsilon", false, 0.1, "number", cmd); TCLAP::UnlabeledValueArg<string> geodata("geodata", "Input map file", true, "", "file name", cmd); cmd.parse(argc, argv); geonames::GeoNames geoNames; ostringstream err; if (!geoNames.Init(geodata.getValue(), err)) { cerr << "Failed to initialize geodata: " << err.str() << endl; return 1; } auto* in = &cin; auto* out = &cout; unique_ptr<ifstream> inFile; unique_ptr<istringstream> inString; if (input.isSet()) { inFile.reset(new ifstream(input.getValue())); in = inFile.get(); } else if (queries.isSet()) { string queriesString; for (auto& q: queries) { queriesString += q + '\n'; } inString.reset(new istringstream(queriesString)); in = inString.get(); } unique_ptr<ofstream> outFile; if (output.isSet()) { outFile.reset(new ofstream(output.getValue())); out = outFile.get(); } wstring_convert<codecvt_utf8<char32_t>, char32_t> utf8codec; bool cmpResults = compareResults.getValue() && jsonUpdate.isSet(); size_t total = 0; size_t cmp_matched = 0; size_t cmp_errors = 0; size_t cmp_missing = 0; size_t cmp_ambiguous = 0; size_t unique = 0; size_t missing = 0; size_t ambiguous = 0; size_t n = 0; string line; geonames::ParserSettings settings; settings.MergeNear_ = mergeNear.getValue(); settings.UniqueOnly_ = uniqueOnly.getValue(); vector<geonames::ParseResult> results; while (getline(*in, line)) { ++n; if (!jsonField.getValue().empty()) { nlohmann::json data; try { data = nlohmann::json::parse(line); } catch (const exception& e) { cerr << "Failed to parse JSON from line: " << n << " error: " << e.what() << endl; return 1; } const nlohmann::json* old = nullptr; if (cmpResults) { auto it = data.find(jsonUpdate.getValue()); if (it != data.end()) { old = &it.value(); if (!old->count("lat") || !old->count("lng")) { old = nullptr; } } } nlohmann::json res; auto it = data.find(jsonField.getValue()); if (it != data.end()) { results.clear(); if (geoNames.Parse(results, it.value().get<string>(), settings)) { assert(!results.empty()); string city; string state; string country; double lat; double lng; if (results[0].City_) { city = utf8codec.to_bytes(results[0].City_.Object_->Name()); lat = results[0].City_.Object_->Latitude(); lng = results[0].City_.Object_->Longitude(); } else if (results[0].Province_) { state = utf8codec.to_bytes(results[0].Province_.Object_->Name()); lat = results[0].Province_.Object_->Latitude(); lng = results[0].Province_.Object_->Longitude(); } else { assert(results[0].Country_); country = utf8codec.to_bytes(results[0].Country_.Object_->Name()); lat = results[0].Country_.Object_->Latitude(); lng = results[0].Country_.Object_->Longitude(); } res = { { "city", city }, { "state", state }, { "country", country }, { "lat", lat }, { "lng", lng } }; if (old) { if (results.size() == 1) { const double e = sqrt( pow(lat - old->find("lat").value().get<double>(), 2) + pow(lng - old->find("lng").value().get<double>(), 2) ); if (e > epsilon.getValue()) { ++cmp_errors; cerr << "Data: " << it.value().get<string>() << endl; cerr << old->dump(4) << endl; nlohmann::json obj(nlohmann::json::object()); JsonResult(obj, "country", results[0].Country_, tokens.getValue()); JsonResult(obj, "state", results[0].Province_, tokens.getValue()); JsonResult(obj, "city", results[0].City_, tokens.getValue()); cerr << obj.dump(4) << endl; } else { ++cmp_matched; } } else { ++cmp_ambiguous; } } else if (results.size() == 1) { ++unique; } else { ++ambiguous; } } else if (old) { ++cmp_missing; } else { ++missing; } ++total; } if (jsonUpdate.getValue().empty()) { data = res; } else if (!old && !res.is_null()) { data[jsonUpdate.getValue()] = res; } *out << data.dump(oneLine.getValue() ? -1 : 4) << endl; } } if (cmpResults) { nlohmann::json stats = { { "total", total }, { "cmp_matched", cmp_matched }, { "cmp_errors", cmp_errors }, { "cmp_missing", cmp_missing }, { "cmp_ambiguous", cmp_ambiguous }, { "unique", unique }, { "missing", missing }, { "ambiguous", ambiguous }, { "valid_stats", total == ( cmp_matched + cmp_errors + cmp_missing + cmp_ambiguous + unique + missing + ambiguous ) } }; cerr << stats.dump(4) << endl; } return 0; } int main(int argc, char* argv[]) { try { return Main(argc, argv); } catch (const TCLAP::ArgException& e) { cerr << "error: " << e.error() << " for arg " << e.argId() << endl; } catch (const exception& e) { cerr << "Caught exception: " << e.what() << endl; } return 1; }
c89bccfa51b6809847632fedd2fbcaf6efeab690
8e324e84f525262719c4a9642be37b05136e1641
/src/server/game/Battlegrounds/Zones/BattlegroundTP.cpp
44076d4d959614c26cb57e70d5c3baf5d5ce869e
[]
no_license
ProjectStarGate/StarGateEmu-Projekt
837d1551fda58c1c91b6a31f0994a0993a043d53
4eabe8f08cf2802a31969a9a1503922116743833
refs/heads/master
2016-09-06T12:02:34.697192
2012-01-14T18:49:56
2012-01-14T18:49:56
3,037,279
3
2
null
null
null
null
UTF-8
C++
false
false
34,113
cpp
/* * Copyright (C) 2010-2012 Project StarGate */ #include "gamePCH.h" #include "Battleground.h" #include "BattlegroundTP.h" #include "Creature.h" #include "GameObject.h" #include "Language.h" #include "Object.h" #include "ObjectMgr.h" #include "BattlegroundMgr.h" #include "Player.h" #include "World.h" #include "WorldPacket.h" // these variables aren't used outside of this file, so declare them only here enum BG_TP_Rewards { BG_TP_WIN = 0, BG_TP_FLAG_CAP, BG_TP_MAP_COMPLETE, BG_TP_REWARD_NUM }; uint32 BG_TP_Honor[BG_HONOR_MODE_NUM][BG_TP_REWARD_NUM] = { {20, 40, 40}, // normal honor {60, 40, 80} // holiday }; uint32 BG_TP_Reputation[BG_HONOR_MODE_NUM][BG_TP_REWARD_NUM] = { {0, 35, 0}, // normal honor {0, 45, 0} // holiday }; BattlegroundTP::BattlegroundTP() { m_BgObjects.resize(BG_TP_OBJECT_MAX); m_BgCreatures.resize(BG_CREATURES_MAX_TP); m_StartMessageIds[BG_STARTING_EVENT_FIRST] = LANG_BG_TP_START_TWO_MINUTES; m_StartMessageIds[BG_STARTING_EVENT_SECOND] = LANG_BG_TP_START_ONE_MINUTE; m_StartMessageIds[BG_STARTING_EVENT_THIRD] = LANG_BG_TP_START_HALF_MINUTE; m_StartMessageIds[BG_STARTING_EVENT_FOURTH] = LANG_BG_TP_HAS_BEGUN; } BattlegroundTP::~BattlegroundTP() { } void BattlegroundTP::Update(uint32 diff) { Battleground::Update(diff); if (GetStatus() == STATUS_IN_PROGRESS) { if (GetStartTime() >= 25*MINUTE*IN_MILLISECONDS) { if (GetTeamScore(ALLIANCE) == 0) { if (GetTeamScore(HORDE) == 0) // No one scored - result is tie EndBattleground(NULL); else // Horde has more points and thus wins EndBattleground(HORDE); } else if (GetTeamScore(HORDE) == 0) EndBattleground(ALLIANCE); // Alliance has > 0, Horde has 0, alliance wins else if (GetTeamScore(HORDE) == GetTeamScore(ALLIANCE)) // Team score equal, winner is team that scored the last flag EndBattleground(m_LastFlagCaptureTeam); else if (GetTeamScore(HORDE) > GetTeamScore(ALLIANCE)) // Last but not least, check who has the higher score EndBattleground(HORDE); else EndBattleground(ALLIANCE); } else if (GetStartTime() > uint32(m_minutesElapsed * MINUTE * IN_MILLISECONDS)) { ++m_minutesElapsed; UpdateWorldState(BG_TP_STATE_TIMER, 25 - m_minutesElapsed); } if (m_FlagState[BG_TEAM_ALLIANCE] == BG_TP_FLAG_STATE_WAIT_RESPAWN) { m_FlagsTimer[BG_TEAM_ALLIANCE] -= diff; if (m_FlagsTimer[BG_TEAM_ALLIANCE] < 0) { m_FlagsTimer[BG_TEAM_ALLIANCE] = 0; RespawnFlag(ALLIANCE, true); } } if (m_FlagState[BG_TEAM_ALLIANCE] == BG_TP_FLAG_STATE_ON_GROUND) { m_FlagsDropTimer[BG_TEAM_ALLIANCE] -= diff; if (m_FlagsDropTimer[BG_TEAM_ALLIANCE] < 0) { m_FlagsDropTimer[BG_TEAM_ALLIANCE] = 0; RespawnFlagAfterDrop(ALLIANCE); m_BothFlagsKept = false; } } if (m_FlagState[BG_TEAM_HORDE] == BG_TP_FLAG_STATE_WAIT_RESPAWN) { m_FlagsTimer[BG_TEAM_HORDE] -= diff; if (m_FlagsTimer[BG_TEAM_HORDE] < 0) { m_FlagsTimer[BG_TEAM_HORDE] = 0; RespawnFlag(HORDE, true); } } if (m_FlagState[BG_TEAM_HORDE] == BG_TP_FLAG_STATE_ON_GROUND) { m_FlagsDropTimer[BG_TEAM_HORDE] -= diff; if (m_FlagsDropTimer[BG_TEAM_HORDE] < 0) { m_FlagsDropTimer[BG_TEAM_HORDE] = 0; RespawnFlagAfterDrop(HORDE); m_BothFlagsKept = false; } } if (m_BothFlagsKept) { m_FlagSpellForceTimer += diff; if (m_FlagDebuffState == 0 && m_FlagSpellForceTimer >= 600000) //10 minutes { if (Player * plr = sObjectMgr->GetPlayer(m_FlagKeepers[0])) plr->CastSpell(plr, TP_SPELL_FOCUSED_ASSAULT, true); if (Player * plr = sObjectMgr->GetPlayer(m_FlagKeepers[1])) plr->CastSpell(plr, TP_SPELL_FOCUSED_ASSAULT, true); m_FlagDebuffState = 1; } else if (m_FlagDebuffState == 1 && m_FlagSpellForceTimer >= 900000) //15 minutes { if (Player * plr = sObjectMgr->GetPlayer(m_FlagKeepers[0])) { plr->RemoveAurasDueToSpell(TP_SPELL_FOCUSED_ASSAULT); plr->CastSpell(plr, TP_SPELL_BRUTAL_ASSAULT, true); } if (Player * plr = sObjectMgr->GetPlayer(m_FlagKeepers[1])) { plr->RemoveAurasDueToSpell(TP_SPELL_FOCUSED_ASSAULT); plr->CastSpell(plr, TP_SPELL_BRUTAL_ASSAULT, true); } m_FlagDebuffState = 2; } } else { m_FlagSpellForceTimer = 0; //reset timer. m_FlagDebuffState = 0; } } } void BattlegroundTP::StartingEventCloseDoors() { for (uint32 i = BG_TP_OBJECT_DOOR_A_1; i <= BG_TP_OBJECT_DOOR_H_3; ++i) { DoorClose(i); SpawnBGObject(i, RESPAWN_IMMEDIATELY); } for (uint32 i = BG_TP_OBJECT_A_FLAG; i <= BG_TP_OBJECT_BERSERKBUFF_2; ++i) SpawnBGObject(i, RESPAWN_ONE_DAY); UpdateWorldState(BG_TP_STATE_TIMER_ACTIVE, 1); UpdateWorldState(BG_TP_STATE_TIMER, 25); } void BattlegroundTP::StartingEventOpenDoors() { for (uint32 i = BG_TP_OBJECT_DOOR_A_1; i <= BG_TP_OBJECT_DOOR_H_3; ++i) { DoorOpen(i); SpawnBGObject(i, RESPAWN_ONE_DAY); } for (uint32 i = BG_TP_OBJECT_A_FLAG; i <= BG_TP_OBJECT_BERSERKBUFF_2; ++i) SpawnBGObject(i, RESPAWN_IMMEDIATELY); // players joining later are not egible //StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, TP_EVENT_START_BATTLE); } void BattlegroundTP::AddPlayer(Player *plr) { Battleground::AddPlayer(plr); //create score and add it to map, default values are set in constructor BattlegroundTPScore* sc = new BattlegroundTPScore; m_PlayerScores[plr->GetGUID()] = sc; } void BattlegroundTP::RespawnFlag(uint32 Team, bool captured) { if (Team == ALLIANCE) { sLog->outDebug(LOG_FILTER_BATTLEGROUND, "Respawn Alliance flag"); m_FlagState[BG_TEAM_ALLIANCE] = BG_TP_FLAG_STATE_ON_BASE; } else { sLog->outDebug(LOG_FILTER_BATTLEGROUND, "Respawn Horde flag"); m_FlagState[BG_TEAM_HORDE] = BG_TP_FLAG_STATE_ON_BASE; } if (captured) { //when map_update will be allowed for battlegrounds this code will be useless SpawnBGObject(BG_TP_OBJECT_H_FLAG, RESPAWN_IMMEDIATELY); SpawnBGObject(BG_TP_OBJECT_A_FLAG, RESPAWN_IMMEDIATELY); SendMessageToAll(LANG_BG_TP_F_PLACED, CHAT_MSG_BG_SYSTEM_NEUTRAL); PlaySoundToAll(BG_TP_SOUND_FLAGS_RESPAWNED); // flag respawned sound... } m_BothFlagsKept = false; } void BattlegroundTP::RespawnFlagAfterDrop(uint32 team) { if (GetStatus() != STATUS_IN_PROGRESS) return; RespawnFlag(team, false); if (team == ALLIANCE) { SpawnBGObject(BG_TP_OBJECT_A_FLAG, RESPAWN_IMMEDIATELY); SendMessageToAll(LANG_BG_TP_ALLIANCE_FLAG_RESPAWNED, CHAT_MSG_BG_SYSTEM_NEUTRAL); } else { SpawnBGObject(BG_TP_OBJECT_H_FLAG, RESPAWN_IMMEDIATELY); SendMessageToAll(LANG_BG_TP_HORDE_FLAG_RESPAWNED, CHAT_MSG_BG_SYSTEM_NEUTRAL); } PlaySoundToAll(BG_TP_SOUND_FLAGS_RESPAWNED); GameObject *obj = GetBgMap()->GetGameObject(GetDroppedFlagGUID(team)); if (obj) obj->Delete(); else sLog->outError("unknown droped flag bg, guid: %u", GUID_LOPART(GetDroppedFlagGUID(team))); SetDroppedFlagGUID(0, team); m_BothFlagsKept = false; } void BattlegroundTP::EventPlayerCapturedFlag(Player *Source) { if (GetStatus() != STATUS_IN_PROGRESS) return; uint32 winner = 0; Source->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); if (Source->GetTeam() == ALLIANCE) { if (!this->IsHordeFlagPickedup()) return; SetHordeFlagPicker(0); // must be before aura remove to prevent 2 events (drop+capture) at the same time // horde flag in base (but not respawned yet) m_FlagState[BG_TEAM_HORDE] = BG_TP_FLAG_STATE_WAIT_RESPAWN; // Drop Horde Flag from Player Source->RemoveAurasDueToSpell(BG_TP_SPELL_HORDE_FLAG); if (m_FlagDebuffState == 1) Source->RemoveAurasDueToSpell(TP_SPELL_FOCUSED_ASSAULT); if (m_FlagDebuffState == 2) Source->RemoveAurasDueToSpell(TP_SPELL_BRUTAL_ASSAULT); if (GetTeamScore(ALLIANCE) < BG_TP_MAX_TEAM_SCORE) AddPoint(ALLIANCE, 1); PlaySoundToAll(BG_TP_SOUND_FLAG_CAPTURED_ALLIANCE); RewardReputationToTeam(890, m_ReputationCapture, ALLIANCE); } else { if (!this->IsAllianceFlagPickedup()) return; SetAllianceFlagPicker(0); // must be before aura remove to prevent 2 events (drop+capture) at the same time // alliance flag in base (but not respawned yet) m_FlagState[BG_TEAM_ALLIANCE] = BG_TP_FLAG_STATE_WAIT_RESPAWN; // Drop Alliance Flag from Player Source->RemoveAurasDueToSpell(BG_TP_SPELL_ALLIANCE_FLAG); if (m_FlagDebuffState == 1) Source->RemoveAurasDueToSpell(TP_SPELL_FOCUSED_ASSAULT); if (m_FlagDebuffState == 2) Source->RemoveAurasDueToSpell(TP_SPELL_BRUTAL_ASSAULT); if (GetTeamScore(HORDE) < BG_TP_MAX_TEAM_SCORE) AddPoint(HORDE, 1); PlaySoundToAll(BG_TP_SOUND_FLAG_CAPTURED_HORDE); RewardReputationToTeam(889, m_ReputationCapture, HORDE); } //for flag capture is reward 2 honorable kills RewardHonorToTeam(GetBonusHonorFromKill(2), Source->GetTeam()); SpawnBGObject(BG_TP_OBJECT_H_FLAG, BG_TP_FLAG_RESPAWN_TIME); SpawnBGObject(BG_TP_OBJECT_A_FLAG, BG_TP_FLAG_RESPAWN_TIME); if (Source->GetTeam() == ALLIANCE) SendMessageToAll(LANG_BG_TP_CAPTURED_HF, CHAT_MSG_BG_SYSTEM_ALLIANCE, Source); else SendMessageToAll(LANG_BG_TP_CAPTURED_AF, CHAT_MSG_BG_SYSTEM_HORDE, Source); UpdateFlagState(Source->GetTeam(), 1); // flag state none UpdateTeamScore(Source->GetTeam()); // only flag capture should be updated UpdatePlayerScore(Source, SCORE_FLAG_CAPTURES, 1); // +1 flag captures // update last flag capture to be used if teamscore is equal SetLastFlagCapture(Source->GetTeam()); if (GetTeamScore(ALLIANCE) == BG_TP_MAX_TEAM_SCORE) winner = ALLIANCE; if (GetTeamScore(HORDE) == BG_TP_MAX_TEAM_SCORE) winner = HORDE; if (winner) { UpdateWorldState(BG_TP_FLAG_UNK_ALLIANCE, 0); UpdateWorldState(BG_TP_FLAG_UNK_HORDE, 0); UpdateWorldState(BG_TP_FLAG_STATE_ALLIANCE, 1); UpdateWorldState(BG_TP_FLAG_STATE_HORDE, 1); UpdateWorldState(BG_TP_STATE_TIMER_ACTIVE, 0); RewardHonorToTeam(BG_TP_Honor[m_HonorMode][BG_TP_WIN], winner); EndBattleground(winner); } else { m_FlagsTimer[GetTeamIndexByTeamId(Source->GetTeam()) ? 0 : 1] = BG_TP_FLAG_RESPAWN_TIME; } } void BattlegroundTP::EventPlayerDroppedFlag(Player *Source) { if (GetStatus() != STATUS_IN_PROGRESS) { // if not running, do not cast things at the dropper player (prevent spawning the "dropped" flag), neither send unnecessary messages // just take off the aura if (Source->GetTeam() == ALLIANCE) { if (!this->IsHordeFlagPickedup()) return; if (GetHordeFlagPickerGUID() == Source->GetGUID()) { SetHordeFlagPicker(0); Source->RemoveAurasDueToSpell(BG_TP_SPELL_HORDE_FLAG); } } else { if (!this->IsAllianceFlagPickedup()) return; if (GetAllianceFlagPickerGUID() == Source->GetGUID()) { SetAllianceFlagPicker(0); Source->RemoveAurasDueToSpell(BG_TP_SPELL_ALLIANCE_FLAG); } } return; } bool set = false; if (Source->GetTeam() == ALLIANCE) { if (!IsHordeFlagPickedup()) return; if (GetHordeFlagPickerGUID() == Source->GetGUID()) { SetHordeFlagPicker(0); Source->RemoveAurasDueToSpell(BG_TP_SPELL_HORDE_FLAG); if (m_FlagDebuffState == 1) Source->RemoveAurasDueToSpell(TP_SPELL_FOCUSED_ASSAULT); if (m_FlagDebuffState == 2) Source->RemoveAurasDueToSpell(TP_SPELL_BRUTAL_ASSAULT); m_FlagState[BG_TEAM_HORDE] = BG_TP_FLAG_STATE_ON_GROUND; Source->CastSpell(Source, BG_TP_SPELL_HORDE_FLAG_DROPPED, true); set = true; } } else { if (!IsAllianceFlagPickedup()) return; if (GetAllianceFlagPickerGUID() == Source->GetGUID()) { SetAllianceFlagPicker(0); Source->RemoveAurasDueToSpell(BG_TP_SPELL_ALLIANCE_FLAG); if (m_FlagDebuffState == 1) Source->RemoveAurasDueToSpell(TP_SPELL_FOCUSED_ASSAULT); if (m_FlagDebuffState == 2) Source->RemoveAurasDueToSpell(TP_SPELL_BRUTAL_ASSAULT); m_FlagState[BG_TEAM_ALLIANCE] = BG_TP_FLAG_STATE_ON_GROUND; Source->CastSpell(Source, BG_TP_SPELL_ALLIANCE_FLAG_DROPPED, true); set = true; } } if (set) { Source->CastSpell(Source, SPELL_RECENTLY_DROPPED_FLAG, true); UpdateFlagState(Source->GetTeam(), 1); if (Source->GetTeam() == ALLIANCE) { SendMessageToAll(LANG_BG_TP_DROPPED_HF, CHAT_MSG_BG_SYSTEM_HORDE, Source); UpdateWorldState(BG_TP_FLAG_UNK_HORDE, uint32(-1)); } else { SendMessageToAll(LANG_BG_TP_DROPPED_AF, CHAT_MSG_BG_SYSTEM_ALLIANCE, Source); UpdateWorldState(BG_TP_FLAG_UNK_ALLIANCE, uint32(-1)); } m_FlagsDropTimer[GetTeamIndexByTeamId(Source->GetTeam()) ? 0 : 1] = BG_TP_FLAG_DROP_TIME; } } void BattlegroundTP::EventPlayerClickedOnFlag(Player *Source, GameObject* target_obj) { if (GetStatus() != STATUS_IN_PROGRESS) return; int32 message_id = 0; ChatMsg type = CHAT_MSG_BG_SYSTEM_NEUTRAL; //alliance flag picked up from base if (Source->GetTeam() == HORDE && this->GetFlagState(ALLIANCE) == BG_TP_FLAG_STATE_ON_BASE && this->m_BgObjects[BG_TP_OBJECT_A_FLAG] == target_obj->GetGUID()) { message_id = LANG_BG_TP_PICKEDUP_AF; type = CHAT_MSG_BG_SYSTEM_HORDE; PlaySoundToAll(BG_TP_SOUND_ALLIANCE_FLAG_PICKED_UP); SpawnBGObject(BG_TP_OBJECT_A_FLAG, RESPAWN_ONE_DAY); SetAllianceFlagPicker(Source->GetGUID()); m_FlagState[BG_TEAM_ALLIANCE] = BG_TP_FLAG_STATE_ON_PLAYER; //update world state to show correct flag carrier UpdateFlagState(HORDE, BG_TP_FLAG_STATE_ON_PLAYER); UpdateWorldState(BG_TP_FLAG_UNK_ALLIANCE, 1); Source->CastSpell(Source, BG_TP_SPELL_ALLIANCE_FLAG, true); //Source->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_TARGET, BG_TP_SPELL_ALLIANCE_FLAG_PICKED); if (m_FlagState[1] == BG_TP_FLAG_STATE_ON_PLAYER) m_BothFlagsKept = true; } //horde flag picked up from base if (Source->GetTeam() == ALLIANCE && this->GetFlagState(HORDE) == BG_TP_FLAG_STATE_ON_BASE && this->m_BgObjects[BG_TP_OBJECT_H_FLAG] == target_obj->GetGUID()) { message_id = LANG_BG_TP_PICKEDUP_HF; type = CHAT_MSG_BG_SYSTEM_ALLIANCE; PlaySoundToAll(BG_TP_SOUND_HORDE_FLAG_PICKED_UP); SpawnBGObject(BG_TP_OBJECT_H_FLAG, RESPAWN_ONE_DAY); SetHordeFlagPicker(Source->GetGUID()); m_FlagState[BG_TEAM_HORDE] = BG_TP_FLAG_STATE_ON_PLAYER; //update world state to show correct flag carrier UpdateFlagState(ALLIANCE, BG_TP_FLAG_STATE_ON_PLAYER); UpdateWorldState(BG_TP_FLAG_UNK_HORDE, 1); Source->CastSpell(Source, BG_TP_SPELL_HORDE_FLAG, true); //Source->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_TARGET, BG_TP_SPELL_HORDE_FLAG_PICKED); if (m_FlagState[0] == BG_TP_FLAG_STATE_ON_PLAYER) m_BothFlagsKept = true; } //Alliance flag on ground(not in base) (returned or picked up again from ground!) if (GetFlagState(ALLIANCE) == BG_TP_FLAG_STATE_ON_GROUND && Source->IsWithinDistInMap(target_obj, 10)) { if (Source->GetTeam() == ALLIANCE) { message_id = LANG_BG_TP_RETURNED_AF; type = CHAT_MSG_BG_SYSTEM_ALLIANCE; UpdateFlagState(HORDE, BG_TP_FLAG_STATE_WAIT_RESPAWN); RespawnFlag(ALLIANCE, false); SpawnBGObject(BG_TP_OBJECT_A_FLAG, RESPAWN_IMMEDIATELY); PlaySoundToAll(BG_TP_SOUND_FLAG_RETURNED); UpdatePlayerScore(Source, SCORE_FLAG_RETURNS, 1); m_BothFlagsKept = false; } else { message_id = LANG_BG_TP_PICKEDUP_AF; type = CHAT_MSG_BG_SYSTEM_HORDE; PlaySoundToAll(BG_TP_SOUND_ALLIANCE_FLAG_PICKED_UP); SpawnBGObject(BG_TP_OBJECT_A_FLAG, RESPAWN_ONE_DAY); SetAllianceFlagPicker(Source->GetGUID()); Source->CastSpell(Source, BG_TP_SPELL_ALLIANCE_FLAG, true); m_FlagState[BG_TEAM_ALLIANCE] = BG_TP_FLAG_STATE_ON_PLAYER; UpdateFlagState(HORDE, BG_TP_FLAG_STATE_ON_PLAYER); if (m_FlagDebuffState == 1) Source->CastSpell(Source, TP_SPELL_FOCUSED_ASSAULT, true); if (m_FlagDebuffState == 2) Source->CastSpell(Source, TP_SPELL_BRUTAL_ASSAULT, true); UpdateWorldState(BG_TP_FLAG_UNK_ALLIANCE, 1); } //called in HandleGameObjectUseOpcode: //target_obj->Delete(); } //Horde flag on ground(not in base) (returned or picked up again) if (GetFlagState(HORDE) == BG_TP_FLAG_STATE_ON_GROUND && Source->IsWithinDistInMap(target_obj, 10)) { if (Source->GetTeam() == HORDE) { message_id = LANG_BG_TP_RETURNED_HF; type = CHAT_MSG_BG_SYSTEM_HORDE; UpdateFlagState(ALLIANCE, BG_TP_FLAG_STATE_WAIT_RESPAWN); RespawnFlag(HORDE, false); SpawnBGObject(BG_TP_OBJECT_H_FLAG, RESPAWN_IMMEDIATELY); PlaySoundToAll(BG_TP_SOUND_FLAG_RETURNED); UpdatePlayerScore(Source, SCORE_FLAG_RETURNS, 1); m_BothFlagsKept = false; } else { message_id = LANG_BG_TP_PICKEDUP_HF; type = CHAT_MSG_BG_SYSTEM_ALLIANCE; PlaySoundToAll(BG_TP_SOUND_HORDE_FLAG_PICKED_UP); SpawnBGObject(BG_TP_OBJECT_H_FLAG, RESPAWN_ONE_DAY); SetHordeFlagPicker(Source->GetGUID()); Source->CastSpell(Source, BG_TP_SPELL_HORDE_FLAG, true); m_FlagState[BG_TEAM_HORDE] = BG_TP_FLAG_STATE_ON_PLAYER; UpdateFlagState(ALLIANCE, BG_TP_FLAG_STATE_ON_PLAYER); if (m_FlagDebuffState == 1) Source->CastSpell(Source, TP_SPELL_FOCUSED_ASSAULT, true); if (m_FlagDebuffState == 2) Source->CastSpell(Source, TP_SPELL_BRUTAL_ASSAULT, true); UpdateWorldState(BG_TP_FLAG_UNK_HORDE, 1); } //called in HandleGameObjectUseOpcode: //target_obj->Delete(); } if (!message_id) return; SendMessageToAll(message_id, type, Source); Source->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); } void BattlegroundTP::RemovePlayer(Player *plr, uint64 guid) { // sometimes flag aura not removed :( if (IsAllianceFlagPickedup() && m_FlagKeepers[BG_TEAM_ALLIANCE] == guid) { if (!plr) { sLog->outError("BattlegroundTP: Removing offline player who has the FLAG!!"); this->SetAllianceFlagPicker(0); this->RespawnFlag(ALLIANCE, false); } else this->EventPlayerDroppedFlag(plr); } if (IsHordeFlagPickedup() && m_FlagKeepers[BG_TEAM_HORDE] == guid) { if (!plr) { sLog->outError("BattlegroundTP: Removing offline player who has the FLAG!!"); this->SetHordeFlagPicker(0); this->RespawnFlag(HORDE, false); } else this->EventPlayerDroppedFlag(plr); } } void BattlegroundTP::UpdateFlagState(uint32 team, uint32 value) { if (team == ALLIANCE) UpdateWorldState(BG_TP_FLAG_STATE_ALLIANCE, value); else UpdateWorldState(BG_TP_FLAG_STATE_HORDE, value); } void BattlegroundTP::UpdateTeamScore(uint32 team) { if (team == ALLIANCE) UpdateWorldState(BG_TP_FLAG_CAPTURES_ALLIANCE, GetTeamScore(team)); else UpdateWorldState(BG_TP_FLAG_CAPTURES_HORDE, GetTeamScore(team)); } void BattlegroundTP::HandleAreaTrigger(Player *Source, uint32 Trigger) { // this is wrong way to implement these things. On official it done by gameobject spell cast. if (GetStatus() != STATUS_IN_PROGRESS) return; //uint32 SpellId = 0; //uint64 buff_guid = 0; switch(Trigger) { case 5904: // Alliance Flag spawn if (m_FlagState[BG_TEAM_HORDE] && !m_FlagState[BG_TEAM_ALLIANCE]) if (GetHordeFlagPickerGUID() == Source->GetGUID()) EventPlayerCapturedFlag(Source); break; case 5905: // Horde Flag spawn if (m_FlagState[BG_TEAM_ALLIANCE] && !m_FlagState[BG_TEAM_HORDE]) if (GetAllianceFlagPickerGUID() == Source->GetGUID()) EventPlayerCapturedFlag(Source); break; case 5908: // Horde Tower case 5909: // Twin Peak House big case 5910: // Horde House case 5911: // Twin Peak House small case 5914: // Allianz Start right case 5916: // Allianz Start case 5917: // Allianz Start left case 5918: // Horde Start case 5920: // Horde Start Front entrance case 5921: // Horde Start left Water channel break; default: sLog->outError("WARNING: Unhandled AreaTrigger in Battleground: %u", Trigger); Source->GetSession()->SendAreaTriggerMessage("Warning: Unhandled AreaTrigger in Battleground: %u", Trigger); break; } //if (buff_guid) // HandleTriggerBuff(buff_guid, Source); } bool BattlegroundTP::SetupBattleground() { // flags X Y Z Orientation Rotation2 Rotation3 if (!AddObject(BG_TP_OBJECT_A_FLAG, BG_OBJECT_A_FLAG_TP_ENTRY, 2118.210f, 191.621f, 44.052f, 5.741259f, 0, 0, 0.9996573f, 0.02617699f, BG_TP_FLAG_RESPAWN_TIME/1000) // Cata || !AddObject(BG_TP_OBJECT_H_FLAG, BG_OBJECT_H_FLAG_TP_ENTRY, 1578.380f, 344.037f, 2.419f, 3.055978f, 0, 0, 0.008726535f, 0.9999619f, BG_TP_FLAG_RESPAWN_TIME/1000) // Cata // buffs || !AddObject(BG_TP_OBJECT_SPEEDBUFF_1, BG_OBJECTID_SPEEDBUFF_ENTRY, 1545.402f, 304.028f, 0.5923f, -1.64061f, 0, 0, 0.7313537f, -0.6819983f, BUFF_RESPAWN_TIME) // Cata || !AddObject(BG_TP_OBJECT_SPEEDBUFF_2, BG_OBJECTID_SPEEDBUFF_ENTRY, 2171.279f, 222.334f, 43.8001f, 2.663309f, 0, 0, 0.7313537f, 0.6819984f, BUFF_RESPAWN_TIME) // Cata || !AddObject(BG_TP_OBJECT_REGENBUFF_1, BG_OBJECTID_REGENBUFF_ENTRY, 1753.957f, 242.092f, -14.1170f, 1.105848f, 0, 0, 0.1305263f, -0.9914448f, BUFF_RESPAWN_TIME) // Cata || !AddObject(BG_TP_OBJECT_REGENBUFF_2, BG_OBJECTID_REGENBUFF_ENTRY, 1952.121f, 383.857f, -10.2870f, 4.192612f, 0, 0, 0.333807f, -0.9426414f, BUFF_RESPAWN_TIME) // Cata || !AddObject(BG_TP_OBJECT_BERSERKBUFF_1, BG_OBJECTID_BERSERKERBUFF_ENTRY, 1934.369f, 226.064f, -17.0441f, 2.499154f, 0, 0, 0.5591929f, 0.8290376f, BUFF_RESPAWN_TIME) // Cata || !AddObject(BG_TP_OBJECT_BERSERKBUFF_2, BG_OBJECTID_BERSERKERBUFF_ENTRY, 1725.240f, 446.431f, -7.8327f, 5.709677f, 0, 0, 0.9396926f, -0.3420201f, BUFF_RESPAWN_TIME) // Cata // alliance gates || !AddObject(BG_TP_OBJECT_DOOR_A_1, BG_OBJECT_DOOR_A_1_TP_ENTRY, 2115.399f, 150.175f, 43.526f, 2.62f, 0, 0, 0, 0, RESPAWN_IMMEDIATELY) // Cata || !AddObject(BG_TP_OBJECT_DOOR_A_2, BG_OBJECT_DOOR_A_2_TP_ENTRY, 2156.803f, 220.331f, 43.482f, 5.76f, 0, 0, 0, 0, RESPAWN_IMMEDIATELY) // Cata || !AddObject(BG_TP_OBJECT_DOOR_A_3, BG_OBJECT_DOOR_A_3_TP_ENTRY, 2126.760f, 224.051f, 43.647f, 2.63f, 0, 0, 0, 0, RESPAWN_IMMEDIATELY) // Cata // horde gates || !AddObject(BG_TP_OBJECT_DOOR_H_1, BG_OBJECT_DOOR_H_1_TP_ENTRY, 1556.595f, 314.502f, 1.223f, 3.04f, 0, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_TP_OBJECT_DOOR_H_2, BG_OBJECT_DOOR_H_2_TP_ENTRY, 1587.415f, 319.935f, 1.522f, 6.20f, 0, 0, 0, 0, RESPAWN_IMMEDIATELY) || !AddObject(BG_TP_OBJECT_DOOR_H_3, BG_OBJECT_DOOR_H_3_TP_ENTRY, 1558.315f, 372.709f, 1.484f, 6.12f, 0, 0, 0, 0, RESPAWN_IMMEDIATELY) ) { sLog->outErrorDb("BatteGroundTP: Failed to spawn some object Battleground not created!"); return false; } WorldSafeLocsEntry const *sg = sWorldSafeLocsStore.LookupEntry(TP_GRAVEYARD_MIDDLE_ALLIANCE); if (!sg || !AddSpiritGuide(TP_SPIRIT_ALLIANCE, sg->x, sg->y, sg->z, 3.641396f, ALLIANCE)) { sLog->outErrorDb("BatteGroundTP: Failed to spawn Alliance spirit guide! Battleground not created!"); return false; } sg = sWorldSafeLocsStore.LookupEntry(TP_GRAVEYARD_START_ALLIANCE); if (!sg || !AddSpiritGuide(TP_SPIRIT_ALLIANCE, sg->x, sg->y, sg->z, 3.641396f, ALLIANCE)) { sLog->outErrorDb("BatteGroundTP: Failed to spawn Alliance start spirit guide! Battleground not created!"); return false; } sg = sWorldSafeLocsStore.LookupEntry(TP_GRAVEYARD_MIDDLE_HORDE); if (!sg || !AddSpiritGuide(TP_SPIRIT_HORDE, sg->x, sg->y, sg->z, 3.641396f, HORDE)) { sLog->outErrorDb("BatteGroundTP: Failed to spawn Horde spirit guide! Battleground not created!"); return false; } sg = sWorldSafeLocsStore.LookupEntry(TP_GRAVEYARD_START_HORDE); if (!sg || !AddSpiritGuide(TP_SPIRIT_ALLIANCE, sg->x, sg->y, sg->z, 3.641396f, HORDE)) { sLog->outErrorDb("BatteGroundTP: Failed to spawn Horde start spirit guide! Battleground not created!"); return false; } sLog->outDebug(LOG_FILTER_BATTLEGROUND, "BatteGroundTP: BG objects and spirit guides spawned"); return true; } void BattlegroundTP::Reset() { //call parent's class reset Battleground::Reset(); m_FlagKeepers[BG_TEAM_ALLIANCE] = 0; m_FlagKeepers[BG_TEAM_HORDE] = 0; m_DroppedFlagGUID[BG_TEAM_ALLIANCE] = 0; m_DroppedFlagGUID[BG_TEAM_HORDE] = 0; m_FlagState[BG_TEAM_ALLIANCE] = BG_TP_FLAG_STATE_ON_BASE; m_FlagState[BG_TEAM_HORDE] = BG_TP_FLAG_STATE_ON_BASE; m_TeamScores[BG_TEAM_ALLIANCE] = 0; m_TeamScores[BG_TEAM_HORDE] = 0; bool isBGWeekend = sBattlegroundMgr->IsBGWeekend(GetTypeID()); m_ReputationCapture = (isBGWeekend) ? 45 : 35; m_HonorWinKills = (isBGWeekend) ? 3 : 1; m_HonorEndKills = (isBGWeekend) ? 4 : 2; // For WorldState m_minutesElapsed = 0; m_LastFlagCaptureTeam = 0; /* Spirit nodes is static at this BG and then not required deleting at BG reset. if (m_BgCreatures[TP_SPIRIT_ALLIANCE]) DelCreature(TP_SPIRIT_ALLIANCE); if (m_BgCreatures[TP_SPIRIT_HORDE]) DelCreature(TP_SPIRIT_HORDE); */ } void BattlegroundTP::EndBattleground(uint32 winner) { //win reward if (winner == ALLIANCE) RewardHonorToTeam(GetBonusHonorFromKill(m_HonorWinKills), ALLIANCE); RewardReputationToTeam(1168, m_ReputationCapture, ALLIANCE); if (winner == HORDE) RewardHonorToTeam(GetBonusHonorFromKill(m_HonorWinKills), HORDE); RewardReputationToTeam(1168, m_ReputationCapture, HORDE); //complete map_end rewards (even if no team wins) RewardHonorToTeam(GetBonusHonorFromKill(m_HonorEndKills), ALLIANCE); RewardHonorToTeam(GetBonusHonorFromKill(m_HonorEndKills), HORDE); Battleground::EndBattleground(winner); } void BattlegroundTP::HandleKillPlayer(Player *player, Player *killer) { if (GetStatus() != STATUS_IN_PROGRESS) return; EventPlayerDroppedFlag(player); Battleground::HandleKillPlayer(player, killer); } void BattlegroundTP::UpdatePlayerScore(Player *Source, uint32 type, uint32 value, bool doAddHonor) { BattlegroundScoreMap::iterator itr = m_PlayerScores.find(Source->GetGUID()); if (itr == m_PlayerScores.end()) // player not found return; switch(type) { case SCORE_FLAG_CAPTURES: // flags captured ((BattlegroundTPScore*)itr->second)->FlagCaptures += value; //Source->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, TP_OBJECTIVE_CAPTURE_FLAG); break; case SCORE_FLAG_RETURNS: // flags returned ((BattlegroundTPScore*)itr->second)->FlagReturns += value; //Source->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, TP_OBJECTIVE_RETURN_FLAG); break; default: Battleground::UpdatePlayerScore(Source, type, value, doAddHonor); break; } } WorldSafeLocsEntry const* BattlegroundTP::GetClosestGraveYard(Player* player) { //if status in progress, it returns main or start graveyards with spiritguides //else it will return the graveyard in the flagroom - this is especially good //if a player dies in preparation phase - then the player can't cheat //and teleport to the graveyard outside the flagroom //and start running around, while the doors are still closed if (player->GetTeam() == ALLIANCE) { if (GetStatus() == STATUS_IN_PROGRESS) { WorldSafeLocsEntry const* ret; WorldSafeLocsEntry const* closest; float dist, nearest; float x, y, z; player->GetPosition(x, y, z); closest = sWorldSafeLocsStore.LookupEntry(TP_GRAVEYARD_MIDDLE_ALLIANCE); nearest = sqrt((closest->x - x)*(closest->x - x) + (closest->y - y)*(closest->y - y)+(closest->z - z)*(closest->z - z)); ret = sWorldSafeLocsStore.LookupEntry(TP_GRAVEYARD_START_ALLIANCE); dist = sqrt((ret->x - x)*(ret->x - x) + (ret->y - y)*(ret->y - y)+(ret->z - z)*(ret->z - z)); if (dist < nearest) { closest = ret; nearest = dist; } return closest; } else return sWorldSafeLocsStore.LookupEntry(TP_GRAVEYARD_FLAGROOM_ALLIANCE); } else { if (GetStatus() == STATUS_IN_PROGRESS) return sWorldSafeLocsStore.LookupEntry(TP_GRAVEYARD_MIDDLE_HORDE); else return sWorldSafeLocsStore.LookupEntry(TP_GRAVEYARD_FLAGROOM_HORDE); } } void BattlegroundTP::FillInitialWorldStates(WorldPacket& data) { data << uint32(BG_TP_FLAG_CAPTURES_ALLIANCE) << uint32(GetTeamScore(ALLIANCE)); data << uint32(BG_TP_FLAG_CAPTURES_HORDE) << uint32(GetTeamScore(HORDE)); if (m_FlagState[BG_TEAM_ALLIANCE] == BG_TP_FLAG_STATE_ON_GROUND) data << uint32(BG_TP_FLAG_UNK_ALLIANCE) << uint32(-1); else if (m_FlagState[BG_TEAM_ALLIANCE] == BG_TP_FLAG_STATE_ON_PLAYER) data << uint32(BG_TP_FLAG_UNK_ALLIANCE) << uint32(1); else data << uint32(BG_TP_FLAG_UNK_ALLIANCE) << uint32(0); if (m_FlagState[BG_TEAM_HORDE] == BG_TP_FLAG_STATE_ON_GROUND) data << uint32(BG_TP_FLAG_UNK_HORDE) << uint32(-1); else if (m_FlagState[BG_TEAM_HORDE] == BG_TP_FLAG_STATE_ON_PLAYER) data << uint32(BG_TP_FLAG_UNK_HORDE) << uint32(1); else data << uint32(BG_TP_FLAG_UNK_HORDE) << uint32(0); data << uint32(BG_TP_FLAG_CAPTURES_MAX) << uint32(BG_TP_MAX_TEAM_SCORE); if (GetStatus() == STATUS_IN_PROGRESS) { data << uint32(BG_TP_STATE_TIMER_ACTIVE) << uint32(1); data << uint32(BG_TP_STATE_TIMER) << uint32(25-m_minutesElapsed); } else data << uint32(BG_TP_STATE_TIMER_ACTIVE) << uint32(0); if (m_FlagState[BG_TEAM_HORDE] == BG_TP_FLAG_STATE_ON_PLAYER) data << uint32(BG_TP_FLAG_STATE_ALLIANCE) << uint32(2); else data << uint32(BG_TP_FLAG_STATE_ALLIANCE) << uint32(1); if (m_FlagState[BG_TEAM_ALLIANCE] == BG_TP_FLAG_STATE_ON_PLAYER) data << uint32(BG_TP_FLAG_STATE_HORDE) << uint32(2); else data << uint32(BG_TP_FLAG_STATE_HORDE) << uint32(1); }
186d4384f9893d35e93aef0f86fc5151a474a0e2
7619f1f54f8a1f7b11dc1dbb840fd15677a10855
/ExampleCode/Bullet.cpp
8a62f2ec6faf19849da788f3813a5411a3c54875
[]
no_license
kbyun03/4122FinalProject
b52ffd6f3f09161c2523f48dd6e061e130ea2554
83a414c3ebe49d03b0e90a8b515c81fa1666891c
refs/heads/master
2020-03-10T15:13:30.964122
2018-05-03T18:22:36
2018-05-03T18:22:36
129,444,228
0
0
null
null
null
null
UTF-8
C++
false
false
1,161
cpp
#include "Bullet.h" #include <QTimer> #include <QDebug> #include <QGraphicsScene> #include <typeinfo> #include "Enemy.h" #include <QList> #include "Game.h" extern Game *game; //there is an external global object called game of type Game Bullet::Bullet() { //draw rect setRect(0,0,10,50); //connect QTimer *timer = new QTimer(); connect(timer,SIGNAL(timeout()),this,SLOT(move())); timer->start(50); } void Bullet::move() { //if bullet colldes iwth enemy, destroy both QList<QGraphicsItem *> colliding_items = collidingItems(); for (int i = 0, n = colliding_items.size(); i < n; ++i){ if(typeid (*(colliding_items[i])) == typeid(Enemy)){ //increase the score game->score->increase(); //remove them both scene()->removeItem(colliding_items[i]); scene()->removeItem(this); //delete them both delete colliding_items[i]; delete this; return; } } //move bullet up setPos(x(),y()-10); if (pos().y() + rect().height()< 0){ scene()->removeItem(this); delete this; } }
5fc975097c1d8909e2ebc1777a4613b3d4b63dd9
1c52a71a1d6851842a13ff193771aed24e46318c
/codeforces/670-B/670-B-23023757.cpp
f462a9ac29708b4fe3e181b83b0fd8b262a39fb7
[]
no_license
nimxor/competitive_progeamming
d19654b94478aa59ff2103b4433e613f1fdf5ff6
7caf1353a2e8fc3d423cc9711228fbb4fd1e9a97
refs/heads/master
2021-01-19T03:28:52.056161
2017-04-05T14:02:33
2017-04-05T14:02:33
87,314,559
0
0
null
null
null
null
UTF-8
C++
false
false
705
cpp
// https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/explorers-birthday/description/ #include<bits/stdc++.h> #include<time.h> using namespace std; #define ll long long #define mset(m,v) memset(m,v,sizeof(m)) #define pb push_back #define mp make_pair #define fi first #define se second #define pi 3.1415926535897932384 #define mod 1000000007 const int MAXM = 1e5+5; const int MAXN = 5e1+5; ll a[MAXM]; int main() { int n,k,i,j; cin>>n>>k; for(i=1;i<=n;i++){ cin>>a[i]; } ll p = (-1+sqrt(1+8LL*k))/2; ll x = ((1LL*p)*(p+1))/2; k -= x; if(k==0) cout<<a[p]<<endl; else cout<<a[k]<<endl; return 0; }
5cbd6e0f03e31fd8ae77f65d1e10be7bf08f7675
6457f1ee6c51b895c598e77b2e69454aabb8a411
/include/UBLOX/serial_interface.h
f57bf98be5f3febbec6bf89cf9be7ebce20bdcfd
[]
no_license
superjax/UBLOX_read
c9c0f9c25ccd661e7c542a8131b534f0ffe22477
7f91e796c571389c71ac0b846c30f8e8093e43bc
refs/heads/master
2021-06-02T01:41:28.760795
2020-10-16T16:13:05
2020-10-16T16:13:05
134,342,772
12
8
null
2019-11-15T20:55:51
2018-05-22T01:15:39
C++
UTF-8
C++
false
false
548
h
#pragma once #include <cstdint> #include <cstdlib> #include <functional> class SerialListener { public: virtual void read_cb(const uint8_t* buf, const size_t size) = 0; }; class SerialInterface { public: typedef std::function<void(const uint8_t* buf, const size_t size)> serial_cb; virtual void write(const uint8_t* buf, const size_t size) = 0; void add_listener(SerialListener* l) { listeners_.push_back(l); } void add_callback(serial_cb cb) { cb_ = cb; } std::vector<SerialListener*> listeners_; serial_cb cb_; };
13e6ca86c77dea0b796d6b8974e9a63b1b884dbb
4f37d83eff2baed92fffb0a567ea6bbed1dda0ff
/arduino/configuracion_BT/configuracion_BT.ino
575d2332863b2fb4eb715a75850740df3eb2dd55
[]
no_license
georgesaavedra1612/desarrollo-ekg-ads1298R-arduino
82166fe7a606e97087368470b62e46cb92b405eb
25ef3344d7ca067059a9d6db6ddfb897cc2bf7ee
refs/heads/master
2020-04-18T10:54:28.548323
2019-04-11T18:22:43
2019-04-11T18:22:43
167,482,155
0
1
null
null
null
null
UTF-8
C++
false
false
1,414
ino
/* Software serial multple serial test Receives from the hardware serial, sends to software serial. Receives from software serial, sends to hardware serial. The circuit: * RX is digital pin 10 (connect to TX of other device) * TX is digital pin 11 (connect to RX of other device) Note: Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69 Not all pins on the Leonardo and Micro support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI). created back in the mists of time modified 25 May 2012 by Tom Igoe based on Mikal Hart's example This example code is in the public domain. */ #include <SoftwareSerial.h> SoftwareSerial mySerial(10, 11); // RX, TX mySerial es el dispositivo o modulo que estoy conectando al arduino. void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); // set the data rate for the SoftwareSerial port mySerial.begin(38400); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.println("Ingresar comandos AT:"); } void loop() { // run over and over if (mySerial.available()) { Serial.write(mySerial.read()); } if (Serial.available()) { mySerial.write(Serial.read()); } }
1d59944e15f0598d191f3baf96f2c7de934d5847
f6fca6c43ad746c45c8321541178eb02e2cb555e
/openconf_src/ITextDoc.h
54325fb17144ad3b9a82a1a92ff5e060727c7742
[]
no_license
Asakra/alterplast
da271c590b32767953f09266fed1569831aa78cb
682e1c2d2f4246183e9b8284d8cf2dbc14f6e228
refs/heads/master
2023-06-22T04:16:34.924155
2021-07-16T06:20:20
2021-07-16T06:20:20
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,634
h
// ITextDoc.h: interface for the CITextDoc class. #if !defined(AFX_ITEXTDOC_H__99E6A405_0802_4BF4_BCC2_8CD5AFBC9392__INCLUDED_) #define AFX_ITEXTDOC_H__99E6A405_0802_4BF4_BCC2_8CD5AFBC9392__INCLUDED_ #include "icfgdoc.h" class CITextDoc : public CCfgDocDerived<ITextDoc, TextDoc> { public: // Пустышки макросов, чтобы VC++ унутре себя связал интерфейс с классом реализации BEGIN_COM_MAP(Empty) COM_INTERFACE_ENTRY(ITextDoc) END_COM_MAP() CITextDoc(CDocument* pDoc); virtual ~CITextDoc(); STDMETHOD(SaveToFile)(BSTR FileName,VARIANT_BOOL *bSucces); STDMETHOD(LoadFromFile)(BSTR FileName,VARIANT_BOOL *bSuccess); STDMETHOD(get_Text)(BSTR *pVal); STDMETHOD(put_Text)(BSTR newVal); STDMETHOD(get_LineCount)(long *pVal); STDMETHOD(get_LineLen)(long LineNum,long *pVal); STDMETHOD(get_IsModule)(VARIANT_BOOL *pVal); STDMETHOD(put_IsModule)(VARIANT_BOOL newVal); STDMETHOD(get_ReadOnly)(VARIANT_BOOL *pVal); STDMETHOD(put_ReadOnly)(VARIANT_BOOL newVal); STDMETHOD(get_Range)(long StartLine,VARIANT StartCol,VARIANT EndLine,VARIANT EndCol,BSTR *pVal); STDMETHOD(put_Range)(long StartLine,VARIANT StartCol,VARIANT EndLine,VARIANT EndCol,BSTR newVal); STDMETHOD(get_SelStartLine)(long *pVal); STDMETHOD(get_SelStartCol)(long *pVal); STDMETHOD(get_SelEndLine)(long *pVal); STDMETHOD(get_SelEndCol)(long *pVal); STDMETHOD(get_CurrentWord)(BSTR *pVal); STDMETHOD(MoveCaret)(long LineStart,long ColStart,VARIANT LineEnd,VARIANT ColEnd); STDMETHOD(get_BookMark)(long LineNum,VARIANT_BOOL *pVal); STDMETHOD(put_BookMark)(long LineNum,VARIANT_BOOL newVal); STDMETHOD(NextBookmark)(long StartLine,long *pNextBookmark); STDMETHOD(PrevBookmark)(long StartLine,long *pRet); STDMETHOD(ClearAllBookMark)(); STDMETHOD(get_CanUndo)(VARIANT_BOOL *pVal); STDMETHOD(get_CanRedo)(VARIANT_BOOL *pVal); STDMETHOD(Undo)(); STDMETHOD(Redo)(); STDMETHOD(Cut)(); STDMETHOD(Copy)(); STDMETHOD(Paste)(); STDMETHOD(CommentSel)(); STDMETHOD(UncommentSel)(); STDMETHOD(FormatSel)(); CTextEditor* GetView(CTextDocument* pDoc) { if(pDoc) { POSITION pos=pDoc->GetFirstViewPosition(); if(pos) return (CTextEditor*)pDoc->GetNextView(pos); } SetError(E_FAIL,"Данная операция допустима только при открытом документе"); return NULL; } CTextDocument* GetTD(){return (CTextDocument*) m_doc.GetDocument();} bool GetSelection(long num,long* res); }; #endif // !defined(AFX_ITEXTDOC_H__99E6A405_0802_4BF4_BCC2_8CD5AFBC9392__INCLUDED_)
b47f493c53488a07aa1e8176c5e187758abf49a3
82112ca0a021b66c6c645b101ce5976a52f15a6a
/src/libgeo2tag/src/session.cpp
8641fa6d3c788a9449d4e051f4225b1e679f2017
[]
no_license
OSLL/geo2tag
3d68eab2ed0eac4fd1d512eb2416eae9523ec44a
d8fa52aa72e64b98daf640c737c667926fd49a8c
refs/heads/master
2021-01-23T07:21:28.296042
2012-12-10T04:16:02
2012-12-10T04:16:02
1,591,152
7
4
null
null
null
null
UTF-8
C++
false
false
1,966
cpp
/* * Copyright 2010 - 2012 Kirill Krinkin [email protected] * * Geo2tag LBS Platform (geo2tag.org) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR 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. * * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * The advertising clause requiring mention in adverts must never be included. */ /*! --------------------------------------------------------------- * * \file Session.cpp * \brief Session implementation * * File description * * PROJ: OSLL/geo2tag * ---------------------------------------------------------------- */ #include "../inc/session.h" namespace Geo2tag { } // namespace Geo2tag
a8c603abcbb36e6918aa96a06d3ba1f8ce7e8a86
3fcb04025ed75c0f41076c437259f1d090bb0950
/Algo solução - modificado Ruan/KociembaRubikSolver/SOLVER.CPP
6bdc11f17b52e1ce15b8d0351c30d9302adff2ca
[]
no_license
petcomputacaoufrgs/robo-rubik
3ba209e5359a4abf7eb1bc10c1a85fef630241d9
4865d99bf2c0cb059e92f5ac92ad4bc716e6b9c4
refs/heads/master
2023-01-24T22:56:07.489225
2014-05-14T20:11:01
2014-05-14T20:11:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,282
cpp
// solver.cpp - Cube Solver class implementation #include "stdafx.h" #include "solver.h" // Solver #include <iostream> #include <iomanip> Solver::Solver(void) // Phase 1 move mapping tables : twistMoveTable(cube), flipMoveTable(cube), choiceMoveTable(cube), // Phase 2 move mapping tables cornerPermutationMoveTable(cube), nonMiddleSliceEdgePermutationMoveTable(cube), middleSliceEdgePermutationMoveTable(cube), // Phase 1 pruning tables TwistAndFlipPruningTable( twistMoveTable, flipMoveTable, cube.Twist(), cube.Flip()), TwistAndChoicePruningTable( twistMoveTable, choiceMoveTable, cube.Twist(), cube.Choice()), FlipAndChoicePruningTable( flipMoveTable, choiceMoveTable, cube.Flip(), cube.Choice()), // Phase 2 pruning tables CornerAndSlicePruningTable( cornerPermutationMoveTable, middleSliceEdgePermutationMoveTable, cube.CornerPermutation(), cube.MiddleSliceEdgePermutation()), EdgeAndSlicePruningTable( nonMiddleSliceEdgePermutationMoveTable, middleSliceEdgePermutationMoveTable, cube.NonMiddleSliceEdgePermutation(), cube.MiddleSliceEdgePermutation()) { minSolutionLength = Huge; // Any solution disovered will look better than this one! } Solver::~Solver() { } void Solver::InitializeTables(void) { // Phase 1 move mapping tables cout << "Initializing TwistMoveTable" << endl; twistMoveTable.Initialize("Twist.mtb"); cout << "Size = " << twistMoveTable.SizeOf() << endl; cout << "Initializing FlipMoveTable" << endl; flipMoveTable.Initialize("Flip.mtb"); cout << "Size = " << flipMoveTable.SizeOf() << endl; cout << "Initializing ChoiceMoveTable" << endl; choiceMoveTable.Initialize("Choice.mtb"); cout << "Size = " << choiceMoveTable.SizeOf() << endl; // Phase 2 move mapping tables cout << "Initializing CornerPermutationMoveTable" << endl; cornerPermutationMoveTable.Initialize("CrnrPerm.mtb"); cout << "Size = " << cornerPermutationMoveTable.SizeOf() << endl; cout << "Initializing NonMiddleSliceEdgePermutationMoveTable" << endl; nonMiddleSliceEdgePermutationMoveTable.Initialize("EdgePerm.mtb"); cout << "Size = " << nonMiddleSliceEdgePermutationMoveTable.SizeOf() << endl; cout << "Initializing MiddleSliceEdgePermutationMoveTable" << endl; middleSliceEdgePermutationMoveTable.Initialize("SlicPerm.mtb"); cout << "Size = " << middleSliceEdgePermutationMoveTable.SizeOf() << endl; // Phase 1 pruning tables cout << "Initializing TwistAndFlipPruningTable" << endl; TwistAndFlipPruningTable.Initialize("TwstFlip.ptb"); cout << "Size = " << TwistAndFlipPruningTable.SizeOf() << endl; cout << "Initializing TwistAndChoicePruningTable" << endl; TwistAndChoicePruningTable.Initialize("TwstChce.ptb"); cout << "Size = " << TwistAndChoicePruningTable.SizeOf() << endl; cout << "Initializing FlipAndChoicePruningTable" << endl; FlipAndChoicePruningTable.Initialize("FlipChce.ptb"); cout << "Size = " << FlipAndChoicePruningTable.SizeOf() << endl; // Phase 2 pruning tables // Obviously a CornerAndEdgePruningTable doesn't make sense as it's size // would be extremely large (i.e. 8!*8!) cout << "Initializing CornerAndSlicePruningTable" << endl; CornerAndSlicePruningTable.Initialize("CrnrSlic.ptb"); cout << "Size = " << CornerAndSlicePruningTable.SizeOf() << endl; cout << "Initializing EdgeAndSlicePruningTable" << endl; EdgeAndSlicePruningTable.Initialize("EdgeSlic.ptb"); cout << "Size = " << EdgeAndSlicePruningTable.SizeOf() << endl; } int Solver::Solve(KociembaCube& scrambledCube) { int iteration = 1; int result = NOT_FOUND; // Make a copy of the scrambled cube for use later on cube = scrambledCube; // Establish initial cost estimate to goal state threshold1 = Phase1Cost(cube.Twist(), cube.Flip(), cube.Choice()); nodes1 = 1; // Count root node here solutionLength1 = 0; do { cout << "threshold(" << iteration << ") = " << threshold1 << endl; newThreshold1 = Huge; // Any cost will be less than this // Perform the phase 1 recursive IDA* search result = Search1(cube.Twist(), cube.Flip(), cube.Choice(), 0); // Establish a new threshold for a deeper search threshold1 = newThreshold1; // Count interative deepenings iteration++; } while (result == NOT_FOUND); cout << "Phase 1 nodes = " << nodes1 << endl; return result; } int Solver::Search1(int twist, int flip, int choice, int depth) { int cost, totalCost; int move; int power; int twist2, flip2, choice2; int result; // Compute cost estimate to phase 1 goal state cost = Phase1Cost(twist, flip, choice); // h if (cost == 0) // Phase 1 solution found... { solutionLength1 = depth; // Save phase 1 solution length // We need an appropriately initialized cube in order // to begin phase 2. First, create a new cube that // is a copy of the initial scrambled cube. Then we // apply the phase 1 move sequence to that cube. The // phase 2 search can then determine the initial // phase 2 coordinates (corner, edge, and slice // permutation) from this cube. // // Note: No attempt is made to merge moves of the same // face adjacent to the phase 1 & phase 2 boundary since // the shorter sequence will quickly be found. KociembaCube phase2Cube = cube; for (int i = 0; i < solutionLength1; i++) { for (power = 0; power < solutionPowers1[i]; power++) phase2Cube.ApplyMove(solutionMoves1[i]); } // Invoke Phase 2 (void)Solve2(phase2Cube); } // See if node should be expanded totalCost = depth + cost; // g + h if (totalCost <= threshold1) // Expand node { // If this happens, we should have found the // optimal solution at this point, so we // can exit indicating such. Note: the first // complete solution found in phase1 is optimal // due to it being an addmissible IDA* search. if (depth >= minSolutionLength-1 || minSolutionLength < 24) return OPTIMUM_FOUND; for (move = Cube::Move::R; move <= Cube::Move::B; move++) { if (Disallowed(move, solutionMoves1, depth)) continue; twist2 = twist; flip2 = flip; choice2 = choice; solutionMoves1[depth] = move; for (power = 1; power < 4; power++) { solutionPowers1[depth] = power; twist2 = twistMoveTable[twist2][move]; flip2 = flipMoveTable[flip2][move]; choice2 = choiceMoveTable[choice2][move]; nodes1++; // Apply the move if (result = Search1(twist2, flip2, choice2, depth+1)) return result; } } } else // Maintain minimum cost exceeding threshold { if (totalCost < newThreshold1) newThreshold1 = totalCost; } return NOT_FOUND; } int Solver::Solve2(KociembaCube& cube) { int iteration = 1; int result = NOT_FOUND; // Establish initial cost estimate to goal state threshold2 = Phase2Cost( cube.CornerPermutation(), cube.NonMiddleSliceEdgePermutation(), cube.MiddleSliceEdgePermutation()); nodes2 = 1; // Count root node here solutionLength2 = 0; do { newThreshold2 = Huge; // Any cost will be less than this // Perform the phase 2 recursive IDA* search result = Search2( cube.CornerPermutation(), cube.NonMiddleSliceEdgePermutation(), cube.MiddleSliceEdgePermutation(), 0); // Establish a new threshold for a deeper search threshold2 = newThreshold2; // Count interative deepenings iteration++; } while (result == NOT_FOUND); // cout << "Phase 2 nodes = " << nodes2 << endl; return result; } int Solver::Search2( int cornerPermutation, int nonMiddleSliceEdgePermutation, int middleSliceEdgePermutation, int depth) { int cost, totalCost; int move; int power, powerLimit; int cornerPermutation2; int nonMiddleSliceEdgePermutation2; int middleSliceEdgePermutation2; int result; // Compute cost estimate to goal state cost = Phase2Cost( cornerPermutation, nonMiddleSliceEdgePermutation, middleSliceEdgePermutation); // h if (cost == 0) // Solution found... { solutionLength2 = depth; // Save phase 2 solution length if (solutionLength1 + solutionLength2 < minSolutionLength) minSolutionLength = solutionLength1 + solutionLength2; PrintSolution(); return FOUND; } // See if node should be expanded totalCost = depth + cost; // g + h if (totalCost <= threshold2) // Expand node { // No point in continuing to search for solutions of equal or greater // length than the current best solution if (solutionLength1 + depth >= minSolutionLength-1) return ABORT; for (move = Cube::Move::R; move <= Cube::Move::B; move++) { if (Disallowed(move, solutionMoves2, depth)) continue; cornerPermutation2 = cornerPermutation; nonMiddleSliceEdgePermutation2 = nonMiddleSliceEdgePermutation; middleSliceEdgePermutation2 = middleSliceEdgePermutation; solutionMoves2[depth] = move; powerLimit = 4; if (move != Cube::Move::U && move != Cube::Move::D) powerLimit=2; for (power = 1; power < powerLimit; power++) { cornerPermutation2 = cornerPermutationMoveTable[cornerPermutation2][move]; nonMiddleSliceEdgePermutation2 = nonMiddleSliceEdgePermutationMoveTable[nonMiddleSliceEdgePermutation2][move]; middleSliceEdgePermutation2 = middleSliceEdgePermutationMoveTable[middleSliceEdgePermutation2][move]; solutionPowers2[depth] = power; nodes2++; // Apply the move if (result = Search2( cornerPermutation2, nonMiddleSliceEdgePermutation2, middleSliceEdgePermutation2, depth+1)) return result; } } } else // Maintain minimum cost exceeding threshold { if (totalCost < newThreshold2) newThreshold2 = totalCost; } return NOT_FOUND; } int Solver::Phase1Cost(int twist, int flip, int choice) { // Combining admissible heuristics by taking their maximum // produces an improved admissible heuristic. int cost = TwistAndFlipPruningTable.GetValue(twist*flipMoveTable.SizeOf()+flip); int cost2 = TwistAndChoicePruningTable.GetValue(twist*choiceMoveTable.SizeOf()+choice); if (cost2 > cost) cost = cost2; cost2 = FlipAndChoicePruningTable.GetValue(flip*choiceMoveTable.SizeOf()+choice); if (cost2 > cost) cost = cost2; return cost; } int Solver::Phase2Cost( int cornerPermutation, int nonMiddleSliceEdgePermutation, int middleSliceEdgePermutation) { // Combining admissible heuristics by taking their maximum // produces an improved admissible heuristic. int cost = CornerAndSlicePruningTable.GetValue( cornerPermutation*middleSliceEdgePermutationMoveTable.SizeOf()+middleSliceEdgePermutation); int cost2 = EdgeAndSlicePruningTable.GetValue( nonMiddleSliceEdgePermutation*middleSliceEdgePermutationMoveTable.SizeOf()+middleSliceEdgePermutation); if (cost2 > cost) cost = cost2; return cost; } int Solver::Disallowed(int move, int* solutionMoves, int depth) { if (depth > 0) { // Disallow successive moves of a single face (RR2 is same as R') if (solutionMoves[depth-1] == move) return 1; // Disallow a move of an opposite face if the current face // moved is B,L, or D. (BF, LR, DU are same as FB,RL,UD) if ((move == Cube::Move::F) && solutionMoves[depth-1] == Cube::Move::B) return 1; if ((move == Cube::Move::R) && solutionMoves[depth-1] == Cube::Move::L) return 1; if ((move == Cube::Move::U) && solutionMoves[depth-1] == Cube::Move::D) return 1; // Disallow 3 or more consecutive moves of opposite faces // (UDU is same as DU2 and U2D) if ((depth > 1) && solutionMoves[depth-2] == move && solutionMoves[depth-1] == Cube::OpposingFace(move)) return 1; } return 0; // This move is allowed } void Solver::PrintSolution(void) { int i; Moves = new char[170]; for(int i=0; i<170; i++) Moves[i] = 0; for (i = 0; i < solutionLength1; i++) { cout << Cube::NameOfMove(TranslateMove(solutionMoves1[i], solutionPowers1[i], 0)) << " "; if(i>0) std::sprintf(Moves,"%s %s",Moves,Cube::NameOfMove(TranslateMove(solutionMoves1[i], solutionPowers1[i], 0))); else std::sprintf(Moves,"%s",Cube::NameOfMove(TranslateMove(solutionMoves1[i], solutionPowers1[i], 0))); } cout << ". "; for (i = 0; i < solutionLength2; i++) { cout << Cube::NameOfMove(TranslateMove(solutionMoves2[i], solutionPowers2[i], 1)) << " "; if(i==0 && solutionLength1 <= 0) std::sprintf(Moves,"%s",Cube::NameOfMove(TranslateMove(solutionMoves2[i], solutionPowers2[i], 1))); else std::sprintf(Moves,"%s %s",Moves,Cube::NameOfMove(TranslateMove(solutionMoves2[i], solutionPowers2[i], 1))); } cout << "(" << solutionLength1 + solutionLength2 << ")" << endl; } int Solver::TranslateMove(int move, int power, int phase2) { int translatedMove = move; if (phase2 && move != Cube::Move::U && move != Cube::Move::D) power = 2; if (power == 2) translatedMove = Cube::QuarterTurnToHalfTurnMove(move); else if (power == 3) translatedMove = Cube::InverseOfMove(move); else ; return translatedMove; }
[ "lir-pet2@LRI-PET2.(none)" ]
lir-pet2@LRI-PET2.(none)
6829c56c9217959ebeab88a1c3dc08b2da8f9c43
238165028f560e39a5fa795a0d3b1d9e6d34ba11
/MyTimeIntegration/ExplicitNystroemNoVelocity.h
b53b11ab356b617607f621ad578428331a5377e5
[]
no_license
pmueller2/NuToApps
3b1d41b34cc3267f270fd20311543ec0751e96e2
b09cb916ed510d79df99c85666a0b0b9a1bf6608
refs/heads/master
2018-12-18T08:58:14.402501
2018-09-14T12:28:47
2018-09-14T12:28:47
125,864,845
0
0
null
null
null
null
UTF-8
C++
false
false
2,007
h
#pragma once #include <vector> namespace NuTo { namespace TimeIntegration { template <typename Tstate> class ExplicitNystroemNoVelocity { public: //! @brief Initialization with method specific parameters (butcher tableau) ExplicitNystroemNoVelocity(std::vector<std::vector<double>> aa2, std::vector<double> bb1, std::vector<double> bb2, std::vector<double> cc) : a2(aa2) , b1(bb1) , b2(bb2) , c(cc) { } //! @brief Performs one Nystroem step //! @param f A functor that returns the right hand side of //! the differential equation y'' = f(y,t) //! //! The signature of its call operator must be: //! operator()(const Tstate& w, Tstate& d2wdt2, double t) //! The return value is stored in dwdt //! //! @param w0 initial value //! @param v0 initial velocity //! @param t0 start time //! @param h step size (t-t0) //! @return value after one Nystroem step template <typename F> std::pair<Tstate, Tstate> DoStep(F f, Tstate w0, Tstate v0, double t0, double h) { if (k.empty()) { k.resize(c.size()); } for (int i=0; i<k.size(); i++) { k[i] = w0; } Tstate resultW = w0 + h * v0; Tstate resultV = v0; for (std::size_t i = 0; i < c.size(); i++) { double t = t0 + c[i] * h; Tstate wni = w0 + h * v0 * c[i]; for (std::size_t j = 0; j < i; j++) { if (a2[i][j] != 0) wni += h * h * a2[i][j] * k[j]; } f(wni, k[i], t); resultW += h * h * b2[i] * k[i]; resultV += h * b1[i] * k[i]; } return std::make_pair(resultW, resultV); } protected: std::vector<std::vector<double>> a2; std::vector<double> b1; std::vector<double> b2; std::vector<double> c; std::vector<Tstate> k; }; } }
1ccdd3b554bbe4ecee8d1274ab765f3195034915
daf2dfb1dee546bbac8462bafb4026aaf622bc47
/tf2_bot_detector/UI/ImGui_TF2BotDetector.cpp
d69fa766dd25aa607d32f85a41caa9fa69ddaabe
[ "MIT" ]
permissive
kittenchilly/tf2_bot_detector
67770462e0b3d118f87ea23c924093c4c2395f98
f904eb5ac4622fe9c0ae1e7919adfc0ed92ad0a5
refs/heads/master
2023-06-23T04:48:22.024866
2021-07-20T03:57:03
2021-07-20T03:57:03
272,867,208
0
0
MIT
2020-06-17T03:16:51
2020-06-17T03:16:51
null
UTF-8
C++
false
false
16,466
cpp
#include "ImGui_TF2BotDetector.h" #include "Util/PathUtils.h" #include "Clock.h" #include "Networking/NetworkHelpers.h" #include "Config/Settings.h" #include "Util/RegexUtils.h" #include "SteamID.h" #include "Platform/Platform.h" #include "Version.h" #include "ReleaseChannel.h" #include <imgui_internal.h> #include <imgui_desktop/ScopeGuards.h> #include <mh/memory/cached_variable.hpp> #include <mh/text/string_insertion.hpp> #include <cstdarg> #include <memory> #include <regex> #include <stdexcept> namespace ScopeGuards = ImGuiDesktop::ScopeGuards; using namespace std::chrono_literals; using namespace std::string_literals; using namespace std::string_view_literals; using namespace tf2_bot_detector; namespace { enum class OverrideEnabled : int { Unset, Disabled, Enabled, }; } void ImGui::TextRightAligned(const std::string_view& text, float offsetX) { const auto textSize = ImGui::CalcTextSize(text.data(), text.data() + text.size()); float cursorPosX = ImGui::GetCursorPosX(); cursorPosX += ImGui::GetColumnWidth();// ImGui::GetContentRegionAvail().x; cursorPosX -= textSize.x; cursorPosX -= 2 * ImGui::GetStyle().ItemSpacing.x; cursorPosX -= offsetX; ImGui::SetCursorPosX(cursorPosX); ImGui::TextFmt(text); } void ImGui::TextRightAlignedF(const char* fmt, ...) { std::va_list ap, ap2; va_start(ap, fmt); va_copy(ap2, ap); const int count = vsnprintf(nullptr, 0, fmt, ap); va_end(ap); auto buf = std::make_unique<char[]>(count + 1); vsnprintf(buf.get(), count + 1, fmt, ap2); va_end(ap2); ImGui::TextRightAligned(std::string_view(buf.get(), count)); } void ImGui::AutoScrollBox(const char* ID, ImVec2 size, void(*contentsFn)(void* userData), void* userData) { if (!contentsFn) throw std::invalid_argument("contentsFn cannot be nullptr"); if (ImGui::BeginChild(ID, size, true, ImGuiWindowFlags_AlwaysVerticalScrollbar)) { const auto initialScrollY = ImGui::GetScrollY(); const auto maxScrollY = ImGui::GetScrollMaxY(); contentsFn(userData); if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) ImGui::SetScrollHereY(1); } ImGui::EndChild(); } void ImGui::HorizontalScrollBox(const char* ID, void(*contentsFn)(void* userData), void* userData) { ScopeGuards::ID id(ID); auto storage = ImGui::GetStateStorage(); static struct {} s_ScrollerHeight; // Unique pointer const auto scrollerHeightID = ImGui::GetID(&s_ScrollerHeight); auto& height = *storage->GetFloatRef(scrollerHeightID, 1); if (ImGui::BeginChild("HorizontalScrollerBox", { 0, height }, false, ImGuiWindowFlags_HorizontalScrollbar)) { ImGui::BeginGroup(); contentsFn(userData); ImGui::EndGroup(); const auto contentRect = ImGui::GetItemRectSize(); const auto windowSize = ImGui::GetWindowSize(); height = contentRect.y; if (contentRect.x > windowSize.x) { auto& style = ImGui::GetStyle(); height += style.FramePadding.y + style.ScrollbarSize; } } ImGui::EndChild(); } static std::filesystem::path GetLastPathElement(const std::filesystem::path& path) { auto begin = path.begin(); auto end = path.end(); for (auto it = end; (it--) != begin; ) { if (!it->empty()) return *it; } return {}; } using ValidatorFn = tf2_bot_detector::DirectoryValidatorResult(*)(std::filesystem::path path); static std::string_view GetVisibleLabel(const std::string_view& label_id) { if (!label_id.empty()) { auto hashIdx = label_id.find("##"sv); if (hashIdx != 0) { if (hashIdx == label_id.npos) return label_id; else return label_id.substr(0, hashIdx); } } return {}; } static bool InputPathValidated(const std::string_view& label_id, const std::filesystem::path& exampleDir, std::filesystem::path& outPath, bool requireValid, ValidatorFn validator) { ScopeGuards::ID idScope(label_id); bool modified = false; std::string pathStr; if (outPath.empty()) { pathStr = exampleDir.string(); modified = true; } else { pathStr = outPath.string(); } constexpr char BROWSE_BTN_LABEL[] = "Browse..."; const auto browseBtnSize = ImGui::CalcButtonSize(BROWSE_BTN_LABEL).x; ImGui::SetNextItemWidth(ImGui::CalcItemWidth() - browseBtnSize - 8); modified = ImGui::InputTextWithHint("##input", exampleDir.string().c_str(), &pathStr) || modified; ImGui::SameLine(); if (ImGui::Button("Browse...")) { if (auto result = Shell::BrowseForFolderDialog(); !result.empty()) { pathStr = result.string(); modified = true; } } if (auto label = GetVisibleLabel(label_id); !label.empty()) { ImGui::SameLine(0, 4); ImGui::TextFmt(label); } bool modifySuccess = false; const std::filesystem::path newPath(pathStr); if (newPath.empty()) { ImGui::TextFmt({ 1, 1, 0, 1 }, "Cannot be empty"sv); } else if (const auto validationResult = validator(newPath); !validationResult) { ImGui::TextFmt({ 1, 0, 0, 1 }, "Doesn't look like a real {} directory: {}", GetLastPathElement(exampleDir), validationResult.m_Message); } else { ImGui::TextFmt({ 0, 1, 0, 1 }, "Looks good!"sv); if (modified) modifySuccess = true; } ImGui::NewLine(); if (!requireValid) modifySuccess = modified; if (modifySuccess) outPath = newPath; return modifySuccess; } template<typename T, typename TIsValidFunc, typename TInputFunc> static bool OverrideControl(const std::string_view& overrideLabel, T& overrideValue, const T& autodetectedValue, TIsValidFunc&& isValidFunc, TInputFunc&& inputFunc) { ScopeGuards::ID id(overrideLabel); auto storage = ImGui::GetStateStorage(); static struct {} s_OverrideEnabled; // Unique pointer const auto overrideEnabledID = ImGui::GetID(&s_OverrideEnabled); auto& overrideEnabled = *reinterpret_cast<OverrideEnabled*>(storage->GetIntRef(overrideEnabledID, int(OverrideEnabled::Unset))); if (overrideEnabled == OverrideEnabled::Unset) overrideEnabled = isValidFunc(overrideValue) ? OverrideEnabled::Enabled : OverrideEnabled::Disabled; const auto visibleLabel = GetVisibleLabel(overrideLabel); const bool isAutodetectedValueValid = isValidFunc(autodetectedValue); ImGui::EnabledSwitch(isAutodetectedValueValid, [&](bool enabled) { if (bool checked = (overrideEnabled == OverrideEnabled::Enabled || !enabled); ImGui::Checkbox(mh::fmtstr<512>("Override {}", visibleLabel).c_str(), &checked)) { overrideEnabled = checked ? OverrideEnabled::Enabled : OverrideEnabled::Disabled; } }, mh::fmtstr<512>("Failed to autodetect value for {}", visibleLabel).c_str()); ScopeGuards::Indent indent; bool retVal = false; if (overrideEnabled == OverrideEnabled::Enabled || !isAutodetectedValueValid) { retVal = inputFunc();// , InputPathValidated(label_id, exampleDir, outPath, requireValid, validator); } else { ImGui::TextFmt("Autodetected value: {}", autodetectedValue); ImGui::TextFmt({ 0, 1, 0, 1 }, "Looks good!"); ImGui::NewLine(); if (overrideValue != T{}) { overrideValue = T{}; retVal = true; } } return retVal; } static bool InputTextSteamID(const char* label, SteamID& steamID, bool requireValid) { std::string steamIDStr; if (steamID.IsValid()) steamIDStr = steamID.str(); SteamID newSID; const bool modified = ImGui::InputTextWithHint(label, "[U:1:1234567890]", &steamIDStr); bool modifySuccess = false; { if (steamIDStr.empty()) { ScopeGuards::TextColor textColor({ 1, 1, 0, 1 }); ImGui::TextFmt("Cannot be empty"); } else { try { const auto CheckValid = [&](const SteamID& id) { return !requireValid || id.IsValid(); }; bool valid = false; if (modified) { newSID = SteamID(steamIDStr); if (CheckValid(newSID)) { modifySuccess = true; valid = true; } } else { valid = CheckValid(steamID); } if (valid) { ScopeGuards::TextColor textColor({ 0, 1, 0, 1 }); ImGui::TextFmt("Looks good!"sv); } else { ScopeGuards::TextColor textColor({ 1, 0, 0, 1 }); ImGui::TextFmt("Invalid SteamID"sv); } } catch (const std::invalid_argument& error) { ScopeGuards::TextColor textColor({ 1, 0, 0, 1 }); ImGui::TextUnformatted(error.what()); } } } ImGui::NewLine(); if (modifySuccess) steamID = newSID; return modifySuccess; } bool tf2_bot_detector::InputTextSteamIDOverride(const char* label, SteamID& steamID, bool requireValid) { return OverrideControl("SteamID"sv, steamID, GetCurrentActiveSteamID(), [&](const SteamID& id) { return !requireValid || id.IsValid(); }, [&] { return InputTextSteamID(label, steamID, requireValid); }); #if 0 if (overrideEnabled) { if (!overrideEnabled->has_value()) overrideEnabled->emplace(steamID.IsValid()); ImGui::Checkbox(("Override "s << label).c_str(), &overrideEnabled->value()); } if (!overrideEnabled || overrideEnabled->value()) { } else if (steamID.IsValid()) { steamID = {}; return true; } return false; #endif } static bool InputPathValidatedOverride(const std::string_view& label_id, const std::string_view& overrideLabel, const std::filesystem::path& exampleDir, std::filesystem::path& outPath, const std::filesystem::path& autodetectedPath, bool requireValid, ValidatorFn validator) { return OverrideControl(overrideLabel, outPath, autodetectedPath, [](const std::filesystem::path& path) { return !path.empty(); }, [&] { return InputPathValidated(label_id, exampleDir, outPath, requireValid, validator); } ); } bool tf2_bot_detector::InputTextTFDirOverride(const std::string_view& label_id, std::filesystem::path& outPath, const std::filesystem::path& autodetectedPath, bool requireValid) { static const std::filesystem::path s_ExamplePath("C:\\Program Files (x86)\\Steam\\steamapps\\common\\Team Fortress 2\\tf"); return InputPathValidatedOverride(label_id, "tf directory"sv, s_ExamplePath, outPath, autodetectedPath, requireValid, &ValidateTFDir); } bool tf2_bot_detector::InputTextSteamDirOverride(const std::string_view& label_id, std::filesystem::path& outPath, bool requireValid) { static const std::filesystem::path s_ExamplePath("C:\\Program Files (x86)\\Steam"); return InputPathValidatedOverride(label_id, "Steam directory"sv, s_ExamplePath, outPath, GetCurrentSteamDir(), requireValid, &ValidateSteamDir); } namespace { struct [[nodiscard]] IPValidatorResult { IPValidatorResult(std::string addr) : m_Address(std::move(addr)) {} enum class Result { Valid, InvalidFormat, // Doesn't match XXX.XXX.XXX.XXX InvalidOctetValue, // One of the octets is < 0 or > 255 } m_Result = Result::Valid; operator bool() const { return m_Result == Result::Valid; } std::string m_Address; std::string m_Message; }; //static IPValidatorResult ValidateIP(std::string addr, ) } static IPValidatorResult ValidateAndParseIPv4(std::string addr, uint8_t* values) { IPValidatorResult retVal(std::move(addr)); using Result = IPValidatorResult::Result; static const std::regex s_IPRegex(R"regex((\d+)\.(\d+)\.(\d+)\.(\d+))regex", std::regex::optimize); std::smatch match; if (!std::regex_match(retVal.m_Address, match, s_IPRegex)) { retVal.m_Result = Result::InvalidFormat; retVal.m_Message = "Unknown IPv4 format, it should look something like \"192.168.1.10\""; return retVal; } for (size_t i = 0; i < 4; i++) { auto& octetStr = match[i + 1]; if (auto parseResult = from_chars(octetStr, values[i]); !parseResult) { retVal.m_Result = Result::InvalidOctetValue; retVal.m_Message = "Octet #"s << (i + 1) << " should be between 0 and 255 inclusive"; return retVal; } } return retVal; } static bool InputTextIPv4(std::string& addr, bool requireValid) { if (ImGui::InputTextWithHint("", "XXX.XXX.XXX.XXX", &addr)) { uint8_t octets[4]; auto validation = ValidateAndParseIPv4(addr, octets); if (auto validation = ValidateAndParseIPv4(addr, octets); !validation) { ImGui::TextColored({ 1, 0, 0, 1 }, "Invalid IPv4 address: %s", validation.m_Message); return !requireValid; } else { ImGui::TextFmt({ 0, 1, 0, 1 }, "Looks good!"); return true; } } return false; } bool tf2_bot_detector::InputTextLocalIPOverride(const std::string_view& label_id, std::string& ip, bool requireValid) { static mh::cached_variable s_AutodetectedValue(1s, &Networking::GetLocalIP); static const auto IsValid = [](std::string value) -> bool { uint8_t dummy[4]; return !!ValidateAndParseIPv4(std::move(value), dummy); }; const auto InputFunc = [&]() -> bool { return InputTextIPv4(ip, true); }; return OverrideControl(label_id, ip, s_AutodetectedValue.get(), IsValid, InputFunc); } bool tf2_bot_detector::InputTextSteamAPIKey(const char* label_id, std::string& key, bool requireValid) { constexpr char BASE_INVALID_KEY_MSG[] = "Your Steam API key should be a 32 character hexadecimal string (NOT your Steam account password)."; std::string newKey = key; if (ImGui::InputText(label_id, &newKey)) { bool isValid = true; if (isValid && newKey.size() > 0 && newKey.size() != 32) { isValid = false; ImGui::TextColored({ 1, 0, 0, 1 }, "%s (current length: %zu)", BASE_INVALID_KEY_MSG, newKey.size()); ImGui::NewLine(); } if (isValid) { const auto invalidCharIndex = newKey.find_first_not_of("0123456789abcdefABCDEF"); if (invalidCharIndex != newKey.npos) { isValid = false; ImGui::TextColored({ 1, 0, 0, 1 }, "%s (invalid character '%c')", BASE_INVALID_KEY_MSG, newKey.at(invalidCharIndex)); ImGui::NewLine(); } } if (requireValid && !isValid) newKey = key; } if (ImGui::Button("More Info...")) Platform::Shell::OpenURL("https://github.com/PazerOP/tf2_bot_detector/wiki/Integrations:-Steam-API"); if (key.empty()) { ImGui::SameLine(); if (ImGui::Button("Generate Steam API Key")) Platform::Shell::OpenURL("https://steamcommunity.com/dev/apikey"); } if (newKey != key) { key = newKey; return true; } return false; } bool tf2_bot_detector::Combo(const char* label_id, std::optional<ReleaseChannel>& mode) { const char* friendlyText = "<UNKNOWN>"; static constexpr char FRIENDLY_TEXT_DISABLED[] = "Disable automatic update checks"; static constexpr char FRIENDLY_TEXT_NIGHTLY[] = "Notify about every new build (unstable)"; static constexpr char FRIENDLY_TEXT_PREVIEW[] = "Notify about new preview releases"; static constexpr char FRIENDLY_TEXT_STABLE[] = "Notify about new stable releases"; const auto oldMode = mode; #if 0 constexpr bool allowReleases = VERSION.m_Preview == 0; if (!allowReleases && mode == ProgramUpdateCheckMode::Releases) mode = ProgramUpdateCheckMode::Previews; #endif if (mode.has_value()) { switch (*mode) { case ReleaseChannel::None: friendlyText = FRIENDLY_TEXT_DISABLED; break; case ReleaseChannel::Nightly: friendlyText = FRIENDLY_TEXT_NIGHTLY; break; case ReleaseChannel::Preview: friendlyText = FRIENDLY_TEXT_PREVIEW; break; case ReleaseChannel::Public: friendlyText = FRIENDLY_TEXT_STABLE; break; } } else { friendlyText = "Select an option"; } if (ImGui::BeginCombo(label_id, friendlyText)) { if (ImGui::Selectable(FRIENDLY_TEXT_DISABLED)) mode = ReleaseChannel::None; #if 0 ImGui::EnabledSwitch(allowReleases, [&] { ImGui::BeginGroup(); if (ImGui::Selectable(FRIENDLY_TEXT_STABLE)) mode = ProgramUpdateCheckMode::Releases; ImGui::EndGroup(); }, "Since you are using a preview build, you will always be notified of new previews."); #else if (ImGui::Selectable(FRIENDLY_TEXT_STABLE)) mode = ReleaseChannel::Public; #endif if (ImGui::Selectable(FRIENDLY_TEXT_PREVIEW)) mode = ReleaseChannel::Preview; if (ImGui::Selectable(FRIENDLY_TEXT_NIGHTLY)) mode = ReleaseChannel::Nightly; ImGui::EndCombo(); } return mode != oldMode; } bool tf2_bot_detector::AutoLaunchTF2Checkbox(bool& value) { return ImGui::Checkbox("Automatically launch TF2 when TF2 Bot Detector is opened", &value); } ImVec2 ImGui::CalcButtonSize(const char* label) { const auto& style = ImGui::GetStyle(); return (ImVec2(style.FramePadding) * 2) + CalcTextSize(label); } void ImGui::Value(const char* prefix, double v, const char* float_format) { return Value(prefix, float(v), float_format); } void ImGui::PushDisabled() { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); } void ImGui::PopDisabled() { ImGui::PopItemFlag(); } float ImGui::GetCurrentFontScale() { ImGuiContext& g = *GImGui; return (g.FontSize * g.IO.FontGlobalScale) / g.FontBaseSize; } void ImGui::PacifierText() { ImGui::TextFmt("Loading..."sv); }
274a91e6f0f4b65d66eff54caec2624ab5bcb343
d64306c77907757fff2d90198c3f63af0c2f88e5
/project/Engine/Game.h
4cfb3654b28c2f6a82a75e424428ab3d0b545149
[]
no_license
kenbo736/TDP005
0f69a60f59673dd9d7daff30038b5cb9a6a0a6fd
71cb30741ae2064fa2b217e98b078dd000dd0a07
refs/heads/master
2021-01-10T08:52:04.510906
2016-04-09T13:15:31
2016-04-09T13:15:31
51,699,467
0
0
null
null
null
null
UTF-8
C++
false
false
367
h
/* Game.h */ #pragma once #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include "./Graphics/Graphics.h" #include "./System/Logic.h" #include "./System/Input.h" #include "../World/World.h" class Game { public: Game(); ~Game(); void run(); private: SDL_Window* window; Graphics* graphics; Logic* logic; Input* input; World* world; int fps; };
8c8bdb0cfb9a9af3834d12fe14b351475ae55a93
7e753f9cadc4bb542ce751b29ceabd2cb83848c6
/controls-home-devices-in-relay-control-mode-via-wifi.ino
7fd18f46cf5ead6e37fb96d3f8e73470664ef5ae
[ "MIT" ]
permissive
ithieund/ArduinoRemoteLITE
9e875f7a49bdac0778753cdb751de008d3efd6ed
f3562829456dcbf3e690d8f1432df33ba78ec14c
refs/heads/master
2020-03-24T13:26:32.626722
2018-09-16T02:23:26
2018-09-16T02:23:26
142,744,396
1
0
null
null
null
null
UTF-8
C++
false
false
5,315
ino
/* * Controls home devices with Arduino Remote LITE in Relay Control Mode via Wifi * Author: Top Hot Apps * Website: https://hotapps.top * Email: [email protected] * This sketch runs with Arduino Remote LITE. Download: https://play.google.com/store/apps/details?id=it.hieund.arduino_remote_lite */ #include <WiFi.h> // Ports const char PORT_RELAY1 = 13; const char PORT_RELAY2 = 12; const char PORT_RELAY3 = 14; const char PORT_RELAY4 = 27; const char PORT_RELAY5 = 26; const char PORT_RELAY6 = 25; const char PORT_RELAY7 = 33; const char PORT_RELAY8 = 32; // Constants const char RELAY_ON = 0; // Relay on const char RELAY_OFF = 1; // Relay off // Variables WiFiServer server(80); char ssid[] = "YOUR-WIFI-SSID"; // Change this value before uploading char password[] = "YOUR-WIFI-PASSWORD"; // Change this value before uploading String request = ""; // Util function to setup wifi connection void setupWiFi() { Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); // Wait until the connection is establed while(WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } // Show connection info Serial.println(""); Serial.println("Connected to Wifi."); Serial.print("WebServer URL: http://"); Serial.println(WiFi.localIP()); // Start the web server server.begin(); } // Setup when Arduino boots void setup() { Serial.begin(9600); // Sets all ports as OUTPUT pinMode(PORT_RELAY1, OUTPUT); pinMode(PORT_RELAY2, OUTPUT); pinMode(PORT_RELAY3, OUTPUT); pinMode(PORT_RELAY4, OUTPUT); pinMode(PORT_RELAY5, OUTPUT); pinMode(PORT_RELAY6, OUTPUT); pinMode(PORT_RELAY7, OUTPUT); pinMode(PORT_RELAY8, OUTPUT); // Sets default state as OFF digitalWrite(PORT_RELAY1, RELAY_OFF); digitalWrite(PORT_RELAY2, RELAY_OFF); digitalWrite(PORT_RELAY3, RELAY_OFF); digitalWrite(PORT_RELAY4, RELAY_OFF); digitalWrite(PORT_RELAY5, RELAY_OFF); digitalWrite(PORT_RELAY6, RELAY_OFF); digitalWrite(PORT_RELAY7, RELAY_OFF); digitalWrite(PORT_RELAY8, RELAY_OFF); setupWiFi(); } // Repeats continuously after boot void loop() { WiFiClient client = server.available(); if(!client) return; // Listen to client request String currentLine = ""; while(client.connected()) { if(client.available()) { char c = client.read(); request += c; if(c != '\r' && c != '\n') currentLine += c; if (c == '\n') { if(currentLine.length() == 0) break; currentLine = ""; } } } // Handle client request if(request.length() > 0) { // Control Relay 1 if(request.indexOf("1:0") >= 0) { digitalWrite(PORT_RELAY1, RELAY_OFF); Serial.println("Relay 1: Off"); } if(request.indexOf("1:1") >= 0) { digitalWrite(PORT_RELAY1, RELAY_ON); Serial.println("Relay 1: On"); } // Control Relay 2 if(request.indexOf("2:0") >= 0) { digitalWrite(PORT_RELAY2, RELAY_OFF); Serial.println("Relay 2: Off"); } if(request.indexOf("2:1") >= 0) { digitalWrite(PORT_RELAY2, RELAY_ON); Serial.println("Relay 1: On"); } // Control Relay 3 if(request.indexOf("3:0") >= 0) { digitalWrite(PORT_RELAY3, RELAY_OFF); Serial.println("Relay 3: Off"); } if(request.indexOf("3:1") >= 0) { digitalWrite(PORT_RELAY3, RELAY_ON); Serial.println("Relay 3: On"); } // Control Relay 4 if(request.indexOf("4:0") >= 0) { digitalWrite(PORT_RELAY4, RELAY_OFF); Serial.println("Relay 4: Off"); } if(request.indexOf("4:1") >= 0) { digitalWrite(PORT_RELAY4, RELAY_ON); Serial.println("Relay 4: On"); } // Control Relay 5 if(request.indexOf("5:0") >= 0) { digitalWrite(PORT_RELAY5, RELAY_OFF); Serial.println("Relay 5: Off"); } if(request.indexOf("5:1") >= 0) { digitalWrite(PORT_RELAY5, RELAY_ON); Serial.println("Relay 5: On"); } // Control Relay 6 if(request.indexOf("6:0") >= 0) { digitalWrite(PORT_RELAY6, RELAY_OFF); Serial.println("Relay 6: Off"); } if(request.indexOf("6:1") >= 0) { digitalWrite(PORT_RELAY6, RELAY_ON); Serial.println("Relay 6: On"); } // Control Relay 7 if(request.indexOf("7:0") >= 0) { digitalWrite(PORT_RELAY7, RELAY_OFF); Serial.println("Relay 7: Off"); } if(request.indexOf("7:1") >= 0) { digitalWrite(PORT_RELAY7, RELAY_ON); Serial.println("Relay 7: On"); } // Control Relay 8 if(request.indexOf("8:0") >= 0) { digitalWrite(PORT_RELAY8, RELAY_OFF); Serial.println("Relay 8: Off"); } if(request.indexOf("8:1") >= 0) { digitalWrite(PORT_RELAY8, RELAY_ON); Serial.println("Relay 8: On"); } // Reset string to be ready for next request request = ""; // Send response to client client.println("HTTP/1.1 200 OK"); client.println("Content-type: text/html"); client.println("Connection: close"); client.println(); client.println("<!DOCTYPE html><html>"); client.println("<head><link rel=\"icon\" href=\"data:,\"><title>Arduino Remote LITE - ESP32</title></head>"); client.println("<body></body></html>"); } // Close connection to client client.stop(); }
041cf641dffa8ba1f9bd72a9613ce71d3f2253c4
28bbc168051237c97e810697c589b51c3d4b6836
/ValentinaHernandez/Semestre1-2017/comentados/UVA-11385.cpp
f7477e6e113537fffab795d871af307b7a4a863f
[]
no_license
fernandezeric/acmudec
1ac14d916445a8c31d5914f2a99c33c7bb8af9b0
1042c759b1636b47fcf3c20fd8daeaa39338bbd1
refs/heads/master
2020-07-31T05:09:51.501552
2018-09-13T01:55:49
2018-09-13T01:55:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,501
cpp
/*COMENTADO https://github.com/ackoroa/UVa-Solutions/blob/master/UVa%2011385%20-%20Da%20Vinci%20Code/src/UVa%2011385%20-%20Da%20Vinci%20Code.cpp */ #include <cstdio> #include <cmath> #include <map> #include <cctype> #include <cstring> using namespace std; map<int, int> fibIdx, revFibIdx; /*Obtiene el termino n de la sucesión de fibonacci y se guardan en mapas, uno con la posicion y tu termino otro al reves*/ int fib(int n) { if (n == 1) return 1; if (n == 2) return 2; if (fibIdx.count(n) != 0) return fibIdx[n]; int ans = fib(n - 1) + fib(n - 2); fibIdx[n] = ans; revFibIdx[ans] = n; return ans; } /*inicializa fibonacci*/ void init() { fibIdx[1] = 1; fibIdx[2] = 2; revFibIdx[1] = 1; revFibIdx[2] = 2; fib(46); } int main() { int tc, n, i; char s[10001], ans[10001], c; int key[100]; init(); scanf("%d", &tc); while (tc--) { scanf("%d", &n); int max = 0; for (i = 0; i < n; i++) { scanf("%d", &key[i]); if (key[i] > max) max = key[i]; } /*En max se guarda el máximo termino de fibonacci*/ i = 0; scanf("%c", &c); while (true) { scanf("%c", &c); if (c == '\n') break; if (isupper(c)) s[i++] = c; } //se llena con espacios en donde no se encuentra el termino de fibonacci for (i = 0; i < revFibIdx[max]; i++) { ans[i] = ' '; } //se guarda en ans el termino que existe for (i = 0; i < n; i++) { ans[revFibIdx[key[i]] - 1] = s[i]; } ans[revFibIdx[max]] = '\0'; printf("%s\n", ans); } return 0; }
102fe4f68c101780b33579b58985c555c4fccc55
180159ae833c2ecfdafb3bbbba7c412b7b98bfb2
/Demo4_1/main.cpp
a658c5ba7a61e6f391cccaf11356b0fd65ad8140
[]
no_license
z2058550226/QtCode
f4a09808435b031c7a984fe6daa3d4ec2c58adb8
5d93ce50dcca968b11127851983f159859bfbda7
refs/heads/master
2020-03-25T20:32:45.795662
2018-08-09T10:06:08
2018-08-09T10:06:08
144,135,401
1
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.setTitle("OpenGL Hello World!"); w.resize(640,480); w.show(); return a.exec(); }
2467210150230b5d03711c2278e3ab4d40e5e824
d13c1ce1555622663ebd6b21a70fb718b2a034e3
/src/Van_Hove_all.cpp
7a1a38b06576f92e28a63f3544f3f990d43d9bd3
[]
no_license
mformlos/ReversibleSim
207b56e94c8b85d0426975ac52b437eecb82d392
e342d770e916c55b49e3108ab96102f20ac7921d
refs/heads/master
2020-03-16T22:00:20.962087
2018-11-23T09:47:36
2018-11-23T09:47:36
133,023,126
0
0
null
null
null
null
UTF-8
C++
false
false
4,773
cpp
#include <vector> #include <stdlib.h> #include <iostream> #include <fstream> #include <string> #include <map> #include <math.h> #include <sys/stat.h> #include <sys/time.h> #include "Molecule.h" #include "HelperFunctions.h" #include "BoundaryConditions.h" int main(int argc, char* argv[]) { std::string Directory{}, ReplicaDir {}, ConfigFile{}, ConfigFileStart{}, StepSampleFile{}, OutputDir{}, OutputFileStart{}, OutputFileName {}; double StartR{0.0}, DR{0.1}; unsigned StartStep{}, SamplingStep{}, Replicas{}, Monomers{}, BoxSize{}, T0Step {}, T1Step{}; double DeltaT{}, bin{}; std::vector<unsigned long long> SampleSteps {}; if (argc != 10) { std::cout << "usage: ./Van_Hove DIRECTORY STEPFILE REPLICAS STARTSTEP SAMPLINGSTEP DELTAT Monomers BOXSIZE INTERVAL" << std::endl; return EXIT_FAILURE; } Directory=argv[1]; StepSampleFile=argv[2]; Replicas = std::stoi(argv[3]); StartStep = std::stoi(argv[4]); SamplingStep = std::stoi(argv[5]); DeltaT = std::stod(argv[6]); Monomers = std::stoi(argv[7]); BoxSize = std::stoi(argv[8]); DR = std::stod(argv[9]); std::cout << "Directory: " << Directory << std::endl; std::cout << "StartStep: " << StartStep << " SamplingStep: " << SamplingStep << std::endl; std::cout << "Replicas: " << Replicas << " DR: " << DR << std::endl; initializeStepVector(SampleSteps, StepSampleFile); std::vector<Particle> Monomers_zero{}; std::vector<Particle> Monomers_t{}; for (unsigned i = 0; i < Monomers; i++) { Monomers_zero.push_back(Particle(i)); Monomers_t.push_back(Particle(i)); } Vector3d relPos {}; double distance {}; std::array<unsigned,3> Box {}; Box[0] = Box[1] = Box[2] = BoxSize; timeval start {}, end {}; gettimeofday(&start, NULL); for (unsigned repl = 0; repl < Replicas; repl++){ std::cout << "Replica " << repl << std::endl; ReplicaDir = Directory+"/REPL-"+std::to_string(repl); OutputDir = ReplicaDir+"/VanHove"; ConfigFileStart = Directory+"/REPL-"+std::to_string(repl)+"/configs/config"; std::cout << OutputDir << std::endl; const int dir_err {mkdir(OutputDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)}; if (-1 == dir_err) { printf("Error creating directory!"); return EXIT_FAILURE; } OutputFileStart = OutputDir + "/VanHove"; std::map<unsigned,std::map<double,double>> VanHove {}; // for each t, there is a map (r, p(r)) std::map<unsigned,unsigned> VanHove_count {}; // for each t, there is a map (r, p(r)) //initialize the VanHoveFunctions for (unsigned i = 0; i < SampleSteps.size(); i++) { VanHove[SampleSteps[i]] = std::map<double, double>(); VanHove_count[SampleSteps[i]] = 0; } T0Step = StartStep; while(true) { ConfigFile = ConfigFileStart+std::to_string(T0Step)+".pdb"; std::cout << "ConfigFile T0: " << ConfigFile << std::endl; if (!initializePositions(Monomers_zero, ConfigFile)) { std::cout << "problem with initializing monomers" << std::endl; break; } for (auto& Step : SampleSteps) { ConfigFile = ConfigFileStart+std::to_string(T0Step+Step)+".pdb"; std::cout << "ConfigFile T1: " << ConfigFile << std::endl; if (!initializePositions(Monomers_t, ConfigFile)) { std::cout << "problem with initializing monomers" << std::endl; break; } for (unsigned i = 0; i < Monomers; i++) { for (unsigned j = 0; j < Monomers; j++) { relPos = relative(Monomers_zero[i], Monomers_t[j], Box, 0.0); distance = relPos.norm(); bin = unsigned(distance/DR)*DR; VanHove[Step][bin]++; VanHove_count[Step]++; } } } T0Step += SamplingStep; } for (auto& Step : SampleSteps) { OutputFileName = OutputFileStart + std::to_string(Step*DeltaT); std::ofstream OutputFile (OutputFileName, std::ios::out | std::ios::trunc); for (auto& corr : VanHove[Step]) { OutputFile << corr.first << " " << corr.second/(Monomers*VanHove_count[Step]) << std::endl; } OutputFile.close(); } } gettimeofday(&end, NULL); double realTime { ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6 }; std::cout << "total time: " << realTime << std::endl; return 0; }
47f4a044808ee75977486eeb31c758bcaf584302
721ecafc8ab45066f3661cbde2257f6016f5b3a8
/uva/random/188.cpp
d8c392d76085be4547f9bf279faa330d85b0fa82
[]
no_license
dr0pdb/competitive
8651ba9722ec260aeb40ef4faf5698e6ebd75d4b
fd0d17d96f934d1724069c4e737fee37a5874887
refs/heads/master
2022-04-08T02:14:39.203196
2020-02-15T19:05:38
2020-02-15T19:05:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,397
cpp
#include<bits/stdc++.h> #define ABS(a) ((a < 0) ? ((-1)*(a)) : (a)) #define F(i,a,b) for(long long i = (long long)(a); i < (long long)(b); i++) #define RF(i,a,b) for(long long i = (long long)(a); i >= (long long)(b); i--) #define MIN3(a,b,c) (a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c)) #define MAX(a,b) (a)>(b)?(a):(b) #define MIN2(a,b) (a)<(b)?(a):(b) #define SIEVELIM 10000000+10 #define coud(a,b) cout<<fixed << setprecision((b)) << (a) using namespace std; typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<ii> vii; typedef vector<int> vi; typedef long long ll; #define ull unsigned long long typedef long double ld; typedef vector<ll> vll; typedef pair<ll,ll> pll; inline int nextint(){ int temporary; scanf("%d",&temporary); return temporary; } inline ll nextll(){ ll temporary; scanf("%lld",&temporary); return temporary; } inline double nextdouble(){double temporary; scanf("%lf",&temporary); return temporary;} ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); } ll lcm(ll a, ll b) { return a * (b / gcd(a, b)); } ll leftChild(ll p ){return p<<1;} ll rightChild(ll p ){return (p<<1)+1;} inline ll mid(ll l, ll r){ return (l+r)/2;} const ll MOD = 1000000007; const ll INF = 1e9+5; const double eps = 1e-7; const double PI = acos(-1.0); #define deb(x ) cerr << #x << " here "<< x; #define endl "\n" #define pb push_back #define mp make_pair #define all(cc) (cc).begin(),(cc).end() inline bool is_palindrome(const string& s){ return std::equal(s.begin(), s.end(), s.rbegin()); } template<typename T > void modulize(T & a, const T & b) { if (a >= b) { a %= b; } } ll mulmod(ll a, ll b, ll m) { ll q = (ll)(((ld)a*(ld)b) / (ld)m); ll r = a*b - q*m; if (r>m)r %= m; if (r<0)r += m; return r; } template <typename T, typename S>T expo(T e, S n) { T x = 1, p = e; while (n) { if (n & 1)x = x*p; p = p*p; n >>= 1; }return x; } template <typename T>T power(T e, T n, T & m) { T x = 1, p = e; while (n) { if (n & 1)x = mod(x*p, m); p = mod(p*p, m); n >>= 1; }return x; } template <typename T>T powerL(T e, T n, T & m) { T x = 1, p = e; while (n) { if (n & 1)x = mulmod(x, p, m); p = mulmod(p, p, m); n >>= 1; }return x; } template <typename T> T InverseEuler(T a, T & m) { return (a == 1 ? 1 : power(a, m - 2, m)); } inline int two(int n) { return 1 << n; } inline void set_bit(int & n, int b) { n |= two(b); } inline void unset_bit(int & n, int b) { n &= ~two(b); } /*----------------------------------------------------------------------*/ int main(){ std::ios::sync_with_stdio(false);cin.tie(NULL); cout.tie(NULL); string s, line; while(getline(cin, s) && s != "") { line = s; stringstream ss(s); std::vector<string> vs; vi vals; int c = INT_MAX, n; while(ss>>s) { int val = 0,mult = 1; RF(i, s.size()-1, 0) { val += mult * (s[i]-'a' + 1); mult *= 32; } vs.push_back(s); vals.pb(val); c = min(c, val); } n = vals.size(); while(true) { int next = c; F(i, 0, vals.size()) { F(j, i+1, vals.size()) { if((c/vals[i]) % n == (c/vals[j]) % n) { next = max(next, min((c/vals[i]+1)*vals[i], (c/vals[j]+1)*vals[j])); } } } if(next == c) { break; } c = next; } cout<<line<<"\n"<<c<<endl<<endl; } return 0; }/* */
e29519558fd19ff7077082847a220dd17be857bd
9c04607c6a658060a16c269cb673e5818a7074cf
/src/include/fst/script/convert.h
1649bd90ad30c0904aab63aeea5a19202f83e7b0
[ "Apache-2.0" ]
permissive
demitasse/openfst
5e0029065f85126c7853bc3c5ba762cdbc66d01b
6e4a66f7747e921dd2c220ee49927d0a2b69febf
refs/heads/master
2020-06-11T08:39:08.108955
2017-11-18T13:54:53
2017-11-18T13:54:53
75,707,831
0
1
null
null
null
null
UTF-8
C++
false
false
876
h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_CONVERT_H_ #define FST_SCRIPT_CONVERT_H_ #include <memory> #include <string> #include <fst/script/arg-packs.h> #include <fst/script/fst-class.h> namespace fst { namespace script { typedef args::Package<const FstClass &, const string &> ConvertInnerArgs; typedef args::WithReturnValue<FstClass *, ConvertInnerArgs> ConvertArgs; template <class Arc> void Convert(ConvertArgs *args) { const Fst<Arc> &fst = *(args->args.arg1.GetFst<Arc>()); const string &new_type = args->args.arg2; std::unique_ptr<Fst<Arc>> result(Convert(fst, new_type)); args->retval = result ? new FstClass(*result) : nullptr; } FstClass *Convert(const FstClass &f, const string &new_type); } // namespace script } // namespace fst #endif // FST_SCRIPT_CONVERT_H_
6632e9e3890fa6f7fa3a6b4ecf119bf076f4b50b
359c8f346dc634010905080cfa3c8754403d8432
/covidm_for_fitting/model_v2/parameters.cpp
b00a403c03073adc19494a8435a036d6c8a7f6ad
[ "MIT" ]
permissive
rosannaclairebarnard/covidm-mtd-Omi
b954e10895c7286ee9c8233305714a77760bc837
5458524d213b6590156ef0b5cc5e89cd7e22ea7b
refs/heads/main
2023-04-15T04:18:54.867356
2022-08-31T11:57:09
2022-08-31T11:57:09
511,480,146
10
1
null
null
null
null
UTF-8
C++
false
false
28,771
cpp
// parameters.cpp #include "parameters.h" // Helpers to set parameters #define _CheckSet(variable) else if (name == #variable) { ParamSet(variable, value); } #define _CheckSetParent(P, variable) else if (P != 0 && name == #variable) { ParamSet(P->variable, value); return false; } void ParamSet(double& variable, Rcpp::RObject& value) { variable = Rcpp::as<double>(value); } void ParamSet(Discrete& variable, Rcpp::RObject& value) { variable = Rcpp::as<vector<double>>(value); } void ParamSet(vector<double>& variable, Rcpp::RObject& value) { variable = Rcpp::as<vector<double>>(value); } void ParamSet(Matrix& variable, Rcpp::RObject& value) { Rcpp::NumericMatrix rhs = Rcpp::as<Rcpp::NumericMatrix>(value); variable = Matrix(0.0, rhs.nrow(), rhs.ncol()); for (int r = 0; r < rhs.nrow(); ++r) for (int c = 0; c < rhs.ncol(); ++c) variable(r, c) = rhs(r, c); } void ParamSet(vector<Matrix>& variable, Rcpp::RObject& value) { Rcpp::List ml = Rcpp::as<Rcpp::List>(value); for (unsigned int i = 0; i < ml.size(); ++i) { Rcpp::RObject mat = Rcpp::as<Rcpp::RObject>(ml[i]); ParamSet(variable[i], mat); } } void ParamSet(vector<ProcessSpec>& variable, Rcpp::RObject& value) { Rcpp::List pl = Rcpp::as<Rcpp::List>(value); unsigned int pc_id = 0; vector<string> pc_names; for (unsigned int i = 0; i < pl.size(); ++i) { Rcpp::List pli = Rcpp::as<Rcpp::List>(pl[i]); ProcessSpec process; process.source_name = Rcpp::as<string>(pli["source"]); process.type = Rcpp::as<string>(pli["type"]); process.names = Rcpp::as<vector<string>>(pli["names"]); process.ids = vector<unsigned int>(process.names.size(), 0); for (unsigned int j = 0; j < process.ids.size(); ++j) { if (process.names[j] == "null") { process.ids[j] = Null; } else { process.ids[j] = pc_id++; pc_names.push_back(process.names[j]); } } process.report = Rcpp::as<vector<string>>(pli["report"]); Matrix m_prob, m_delays; Rcpp::RObject r_prob = Rcpp::as<Rcpp::RObject>(pli["prob"]); Rcpp::RObject r_delays = Rcpp::as<Rcpp::RObject>(pli["delays"]); ParamSet(m_prob, r_prob); ParamSet(m_delays, r_delays); for (unsigned int c = 0; c < m_prob.NCol(); ++c) { process.prob.push_back(vector<double>(m_prob.NRow(), 0.)); for (unsigned int r = 0; r < m_prob.NRow(); ++r) process.prob[c][r] = m_prob(r, c); } for (unsigned int r = 0; r < m_delays.NRow(); ++r) { process.delays.push_back(Discrete()); std::vector<double> uw(m_delays.NCol(), 0.); for (unsigned int c = 0; c < m_delays.NCol(); ++c) uw[c] = m_delays(r, c); process.delays.back() = uw; } variable.push_back(process); } // Set source_ids for (auto& pr : variable) { auto sn = std::find(pc_names.begin(), pc_names.end(), pr.source_name); if (sn == pc_names.end()) { if (pr.source_name == "newE") pr.source_id = src_newE; else if (pr.source_name == "newI") pr.source_id = src_newI; else if (pr.source_name == "newIp") pr.source_id = src_newIp; else if (pr.source_name == "newIs") pr.source_id = src_newIs; else if (pr.source_name == "newIa") pr.source_id = src_newIa; else if (pr.source_name == "newE2") pr.source_id = src_newE2; else if (pr.source_name == "newI2") pr.source_id = src_newI2; else if (pr.source_name == "newIp2") pr.source_id = src_newIp2; else if (pr.source_name == "newIs2") pr.source_id = src_newIs2; else if (pr.source_name == "newIa2") pr.source_id = src_newIa2; else if (pr.source_name == "newE3") pr.source_id = src_newE3; else if (pr.source_name == "newI3") pr.source_id = src_newI3; else if (pr.source_name == "newIp3") pr.source_id = src_newIp3; else if (pr.source_name == "newIs3") pr.source_id = src_newIs3; else if (pr.source_name == "newIa3") pr.source_id = src_newIa3; else if (pr.source_name == "newEE2E3") pr.source_id = src_newEE2E3; else if (pr.source_name == "newII2I3") pr.source_id = src_newII2I3; else if (pr.source_name == "newIpIp2Ip3") pr.source_id = src_newIpIp2Ip3; else if (pr.source_name == "newIsIs2Is3") pr.source_id = src_newIsIs2Is3; else if (pr.source_name == "newIaIa2Ia3") pr.source_id = src_newIaIa2Ia3; else if (pr.source_name == "newVa1") pr.source_id = src_newVa1; else if (pr.source_name == "newVb1") pr.source_id = src_newVb1; else if (pr.source_name == "HospAdm") pr.source_id = src_HospAdm; else throw logic_error("Unrecognized process source name " + pr.source_name); } else { pr.source_id = (unsigned int)(sn - pc_names.begin()); } } } bool PopulationParameters::Set(Parameters* parent, string& name, Rcpp::RObject& value) { if (name == "contact" || name == "contact_mult" || name == "contact_lowerto" || name == "matrices") needs_recalc = true; if (false) {} _CheckSet(dE) _CheckSet(dIp) _CheckSet(dIa) _CheckSet(dIs) _CheckSet(dE2) _CheckSet(dIp2) _CheckSet(dIa2) _CheckSet(dIs2) _CheckSet(dE3) _CheckSet(dIp3) _CheckSet(dIa3) _CheckSet(dIs3) _CheckSet(dVa1) _CheckSet(dVb1) _CheckSet(dVa2) _CheckSet(dVb2) _CheckSet(size) _CheckSet(imm0) _CheckSet(matrices) _CheckSet(contact) _CheckSet(contact_mult) _CheckSet(contact_lowerto) _CheckSet(u) _CheckSet(u2) _CheckSet(u3) _CheckSet(fIp) _CheckSet(fIa) _CheckSet(fIs) _CheckSet(y) _CheckSet(y2) _CheckSet(y3) _CheckSet(omega) _CheckSet(tau) _CheckSet(pi_r) _CheckSet(pi_r2) _CheckSet(pi_r3) _CheckSet(pi2_r) _CheckSet(pi2_r2) _CheckSet(pi2_r3) _CheckSet(pi3_r) _CheckSet(pi3_r2) _CheckSet(pi3_r3) _CheckSet(wn) _CheckSet(wn2) _CheckSet(wn3) _CheckSet(va1) _CheckSet(wva1) _CheckSet(ei_va1) _CheckSet(ei2_va1) _CheckSet(ei3_va1) _CheckSet(ed_va1i) _CheckSet(ed_va1i2) _CheckSet(ed_va1i3) _CheckSet(wva2) _CheckSet(ei_va2) _CheckSet(ei2_va2) _CheckSet(ei3_va2) _CheckSet(ed_va2i) _CheckSet(ed_va2i2) _CheckSet(ed_va2i3) _CheckSet(wva3) _CheckSet(ei_va3) _CheckSet(ei2_va3) _CheckSet(ei3_va3) _CheckSet(ed_va3i) _CheckSet(ed_va3i2) _CheckSet(ed_va3i3) _CheckSet(vb1) _CheckSet(wvb1) _CheckSet(ei_vb1) _CheckSet(ei2_vb1) _CheckSet(ei3_vb1) _CheckSet(ed_vb1i) _CheckSet(ed_vb1i2) _CheckSet(ed_vb1i3) _CheckSet(wvb2) _CheckSet(ei_vb2) _CheckSet(ei2_vb2) _CheckSet(ei3_vb2) _CheckSet(ed_vb2i) _CheckSet(ed_vb2i2) _CheckSet(ed_vb2i3) _CheckSet(wvb3) _CheckSet(ei_vb3) _CheckSet(ei2_vb3) _CheckSet(ei3_vb3) _CheckSet(ed_vb3i) _CheckSet(ed_vb3i2) _CheckSet(ed_vb3i3) _CheckSet(A) _CheckSet(B) _CheckSet(D) _CheckSet(season_A) _CheckSet(season_T) _CheckSet(season_phi) _CheckSet(ifr1) _CheckSet(ihr1) _CheckSet(iir1) _CheckSet(ifr2) _CheckSet(ihr2) _CheckSet(iir2) _CheckSet(ifr3) _CheckSet(ihr3) _CheckSet(iir3) _CheckSet(eh_va1d) _CheckSet(eh_va1d2) _CheckSet(eh_va1d3) _CheckSet(eh_va2d) _CheckSet(eh_va2d2) _CheckSet(eh_va2d3) _CheckSet(eh_va3d) _CheckSet(eh_va3d2) _CheckSet(eh_va3d3) _CheckSet(eh_vb1d) _CheckSet(eh_vb1d2) _CheckSet(eh_vb1d3) _CheckSet(eh_vb2d) _CheckSet(eh_vb2d2) _CheckSet(eh_vb2d3) _CheckSet(eh_vb3d) _CheckSet(eh_vb3d2) _CheckSet(eh_vb3d3) _CheckSet(em_va1d) _CheckSet(em_va1d2) _CheckSet(em_va1d3) _CheckSet(em_va2d) _CheckSet(em_va2d2) _CheckSet(em_va2d3) _CheckSet(em_va3d) _CheckSet(em_va3d2) _CheckSet(em_va3d3) _CheckSet(em_vb1d) _CheckSet(em_vb1d2) _CheckSet(em_vb1d3) _CheckSet(em_vb2d) _CheckSet(em_vb2d2) _CheckSet(em_vb2d3) _CheckSet(em_vb3d) _CheckSet(em_vb3d2) _CheckSet(em_vb3d3) _CheckSet(et_va1i) _CheckSet(et_va1i2) _CheckSet(et_va1i3) _CheckSet(et_va2i) _CheckSet(et_va2i2) _CheckSet(et_va2i3) _CheckSet(et_va3i) _CheckSet(et_va3i2) _CheckSet(et_va3i3) _CheckSet(et_vb1i) _CheckSet(et_vb1i2) _CheckSet(et_vb1i3) _CheckSet(et_vb2i) _CheckSet(et_vb2i2) _CheckSet(et_vb2i3) _CheckSet(et_vb3i) _CheckSet(et_vb3i2) _CheckSet(et_vb3i3) _CheckSet(dDeath) _CheckSet(dHosp) _CheckSet(lHosp) _CheckSet(dICU) _CheckSet(lICU) _CheckSetParent(parent, travel) else { throw logic_error("Unrecognised parameter " + name + "."); } return true; } void ParamSet(double& variable, vector<double>& value) { variable = value[0]; } void ParamSet(Discrete& variable, vector<double>& value) { variable = value; } void ParamSet(vector<double>& variable, vector<double>& value) { variable = value; } bool PopulationParameters::Set(Parameters* parent, string& name, vector<double>& value) { if (name == "contact" || name == "contact_mult" || name == "contact_lowerto" || name == "matrices") needs_recalc = true; if (false) {} _CheckSet(dE) _CheckSet(dIp) _CheckSet(dIa) _CheckSet(dIs) _CheckSet(dE2) _CheckSet(dIp2) _CheckSet(dIa2) _CheckSet(dIs2) _CheckSet(dE3) _CheckSet(dIp3) _CheckSet(dIa3) _CheckSet(dIs3) _CheckSet(dVa1) _CheckSet(dVb1) _CheckSet(dVa2) _CheckSet(dVb2) _CheckSet(size) _CheckSet(imm0) //_CheckSet(matrices) _CheckSet(contact) _CheckSet(contact_mult) _CheckSet(contact_lowerto) _CheckSet(u) _CheckSet(u2) _CheckSet(u3) _CheckSet(fIp) _CheckSet(fIa) _CheckSet(fIs) _CheckSet(y) _CheckSet(y2) _CheckSet(y3) _CheckSet(omega) _CheckSet(tau) _CheckSet(pi_r) _CheckSet(pi_r2) _CheckSet(pi_r3) _CheckSet(pi2_r) _CheckSet(pi2_r2) _CheckSet(pi2_r3) _CheckSet(pi3_r) _CheckSet(pi3_r2) _CheckSet(pi3_r3) _CheckSet(wn) _CheckSet(wn2) _CheckSet(wn3) _CheckSet(va1) _CheckSet(wva1) _CheckSet(ei_va1) _CheckSet(ei2_va1) _CheckSet(ei3_va1) _CheckSet(ed_va1i) _CheckSet(ed_va1i2) _CheckSet(ed_va1i3) _CheckSet(wva2) _CheckSet(ei_va2) _CheckSet(ei2_va2) _CheckSet(ei3_va2) _CheckSet(ed_va2i) _CheckSet(ed_va2i2) _CheckSet(ed_va2i3) _CheckSet(wva3) _CheckSet(ei_va3) _CheckSet(ei2_va3) _CheckSet(ei3_va3) _CheckSet(ed_va3i) _CheckSet(ed_va3i2) _CheckSet(ed_va3i3) _CheckSet(vb1) _CheckSet(wvb1) _CheckSet(ei_vb1) _CheckSet(ei2_vb1) _CheckSet(ei3_vb1) _CheckSet(ed_vb1i) _CheckSet(ed_vb1i2) _CheckSet(ed_vb1i3) _CheckSet(wvb2) _CheckSet(ei_vb2) _CheckSet(ei2_vb2) _CheckSet(ei3_vb2) _CheckSet(ed_vb2i) _CheckSet(ed_vb2i2) _CheckSet(ed_vb2i3) _CheckSet(wvb3) _CheckSet(ei_vb3) _CheckSet(ei2_vb3) _CheckSet(ei3_vb3) _CheckSet(ed_vb3i) _CheckSet(ed_vb3i2) _CheckSet(ed_vb3i3) _CheckSet(A) _CheckSet(B) _CheckSet(D) _CheckSet(season_A) _CheckSet(season_T) _CheckSet(season_phi) _CheckSet(ifr1) _CheckSet(ihr1) _CheckSet(iir1) _CheckSet(ifr2) _CheckSet(ihr2) _CheckSet(iir2) _CheckSet(ifr3) _CheckSet(ihr3) _CheckSet(iir3) _CheckSet(eh_va1d) _CheckSet(eh_va1d2) _CheckSet(eh_va1d3) _CheckSet(eh_va2d) _CheckSet(eh_va2d2) _CheckSet(eh_va2d3) _CheckSet(eh_va3d) _CheckSet(eh_va3d2) _CheckSet(eh_va3d3) _CheckSet(eh_vb1d) _CheckSet(eh_vb1d2) _CheckSet(eh_vb1d3) _CheckSet(eh_vb2d) _CheckSet(eh_vb2d2) _CheckSet(eh_vb2d3) _CheckSet(eh_vb3d) _CheckSet(eh_vb3d2) _CheckSet(eh_vb3d3) _CheckSet(em_va1d) _CheckSet(em_va1d2) _CheckSet(em_va1d3) _CheckSet(em_va2d) _CheckSet(em_va2d2) _CheckSet(em_va2d3) _CheckSet(em_va3d) _CheckSet(em_va3d2) _CheckSet(em_va3d3) _CheckSet(em_vb1d) _CheckSet(em_vb1d2) _CheckSet(em_vb1d3) _CheckSet(em_vb2d) _CheckSet(em_vb2d2) _CheckSet(em_vb2d3) _CheckSet(em_vb3d) _CheckSet(em_vb3d2) _CheckSet(em_vb3d3) _CheckSet(et_va1i) _CheckSet(et_va1i2) _CheckSet(et_va1i3) _CheckSet(et_va2i) _CheckSet(et_va2i2) _CheckSet(et_va2i3) _CheckSet(et_va3i) _CheckSet(et_va3i2) _CheckSet(et_va3i3) _CheckSet(et_vb1i) _CheckSet(et_vb1i2) _CheckSet(et_vb1i3) _CheckSet(et_vb2i) _CheckSet(et_vb2i2) _CheckSet(et_vb2i3) _CheckSet(et_vb3i) _CheckSet(et_vb3i2) _CheckSet(et_vb3i3) _CheckSet(dDeath) _CheckSet(dHosp) _CheckSet(lHosp) _CheckSet(dICU) _CheckSet(lICU) //_CheckSetParent(parent, travel) else { throw logic_error("Unrecognised parameter " + name + "."); } return true; } void Parameters::FilterForRun(unsigned int r) { for (auto i = changes.ch.begin(); i != changes.ch.end(); ) { if (i->runs.empty() || find(i->runs.begin(), i->runs.end(), r) != i->runs.end()) ++i; else i = changes.ch.erase(i); } } // Helpers to set parameters #define ParamAssign(t, v) if (list.containsElementNamed(#v)) P.v = Rcpp::as<t>(list[#v]); #define ParamMatrixAssign(v) if (list.containsElementNamed(#v)) SetMatrix(P.v, Rcpp::as<Rcpp::NumericMatrix>(list[#v])); #define ParamPopAssign(t, v, i) if (popi.containsElementNamed(#v)) P.pop[i].v = Rcpp::as<t>(popi[#v]); #define ParamPopMatrixAssign(v, i) if (popi.containsElementNamed(#v)) SetMatrix(P.pop[i].v, Rcpp::as<Rcpp::NumericMatrix>(popi[#v])); void SetMatrix(Matrix& mat, const Rcpp::NumericMatrix& rhs) { mat = Matrix(0.0, rhs.nrow(), rhs.ncol()); for (int r = 0; r < rhs.nrow(); ++r) for (int c = 0; c < rhs.ncol(); ++c) mat(r, c) = rhs(r, c); } void SetParameters(Parameters& P, Rcpp::List list, Randomizer& Rand) { P.vax_limit = 1.0; // TODO clean up and use namespace Rcpp // TODO use the ParamSet functions above for all of these parameter assignments ParamAssign(string, model); ParamAssign(double, time_step); ParamAssign(double, time0); ParamAssign(double, time1); ParamAssign(unsigned int, report_every); ParamAssign(bool, fast_multinomial); ParamAssign(bool, deterministic); if (P.report_every != 1/P.time_step) throw("report_every must be the reciprocal of time_step."); if (list.containsElementNamed("pop")) { Rcpp::List populations = Rcpp::as<Rcpp::List>(list["pop"]); unsigned int np = populations.size(); P.pop.assign(np, PopulationParameters()); for (unsigned int i = 0; i < np; ++i) { Rcpp::List popi = Rcpp::as<Rcpp::List>(populations[i]); ParamPopAssign(vector<double>, dE, i); ParamPopAssign(vector<double>, dIp, i); ParamPopAssign(vector<double>, dIa, i); ParamPopAssign(vector<double>, dIs, i); ParamPopAssign(vector<double>, dE2, i); ParamPopAssign(vector<double>, dIp2, i); ParamPopAssign(vector<double>, dIa2, i); ParamPopAssign(vector<double>, dIs2, i); ParamPopAssign(vector<double>, dE3, i); ParamPopAssign(vector<double>, dIp3, i); ParamPopAssign(vector<double>, dIa3, i); ParamPopAssign(vector<double>, dIs3, i); ParamPopAssign(vector<double>, dVa1, i); ParamPopAssign(vector<double>, dVb1, i); ParamPopAssign(vector<double>, dVa2, i); ParamPopAssign(vector<double>, dVb2, i); if (P.fast_multinomial) { P.pop[i].dE.mn_approx.Set(P, Rand, P.pop[i].dE.weights); P.pop[i].dIp.mn_approx.Set(P, Rand, P.pop[i].dIp.weights); P.pop[i].dIa.mn_approx.Set(P, Rand, P.pop[i].dIa.weights); P.pop[i].dIs.mn_approx.Set(P, Rand, P.pop[i].dIs.weights); P.pop[i].dE2.mn_approx.Set(P, Rand, P.pop[i].dE2.weights); P.pop[i].dIp2.mn_approx.Set(P, Rand, P.pop[i].dIp2.weights); P.pop[i].dIa2.mn_approx.Set(P, Rand, P.pop[i].dIa2.weights); P.pop[i].dIs2.mn_approx.Set(P, Rand, P.pop[i].dIs2.weights); P.pop[i].dE3.mn_approx.Set(P, Rand, P.pop[i].dE3.weights); P.pop[i].dIp3.mn_approx.Set(P, Rand, P.pop[i].dIp3.weights); P.pop[i].dIa3.mn_approx.Set(P, Rand, P.pop[i].dIa3.weights); P.pop[i].dIs3.mn_approx.Set(P, Rand, P.pop[i].dIs3.weights); P.pop[i].dVa1.mn_approx.Set(P, Rand, P.pop[i].dVa1.weights); P.pop[i].dVb1.mn_approx.Set(P, Rand, P.pop[i].dVb1.weights); P.pop[i].dVa2.mn_approx.Set(P, Rand, P.pop[i].dVa2.weights); P.pop[i].dVb2.mn_approx.Set(P, Rand, P.pop[i].dVb2.weights); } ParamPopAssign(vector<double>, size, i); ParamPopAssign(vector<double>, imm0, i); if (popi.containsElementNamed("matrices")) { Rcpp::List ml = Rcpp::as<Rcpp::List>(popi["matrices"]); for (unsigned int m = 0; m < ml.size(); ++m) { Matrix mat; SetMatrix(mat, Rcpp::as<Rcpp::NumericMatrix>(ml[m])); P.pop[i].matrices.push_back(mat); } } ParamPopAssign(vector<double>, contact, i); ParamPopAssign(vector<double>, contact_mult, i); ParamPopAssign(vector<double>, contact_lowerto, i); ParamPopAssign(vector<double>, u, i); ParamPopAssign(vector<double>, u2, i); ParamPopAssign(vector<double>, u3, i); ParamPopAssign(vector<double>, fIp, i); ParamPopAssign(vector<double>, fIa, i); ParamPopAssign(vector<double>, fIs, i); ParamPopAssign(vector<double>, y, i); ParamPopAssign(vector<double>, y2, i); ParamPopAssign(vector<double>, y3, i); ParamPopAssign(vector<double>, omega, i); ParamPopAssign(vector<double>, tau, i); ParamPopAssign(vector<double>, pi_r, i); ParamPopAssign(vector<double>, pi_r2, i); ParamPopAssign(vector<double>, pi_r3, i); ParamPopAssign(vector<double>, pi2_r, i); ParamPopAssign(vector<double>, pi2_r2, i); ParamPopAssign(vector<double>, pi2_r3, i); ParamPopAssign(vector<double>, pi3_r, i); ParamPopAssign(vector<double>, pi3_r2, i); ParamPopAssign(vector<double>, pi3_r3, i); ParamPopAssign(vector<double>, wn, i); ParamPopAssign(vector<double>, wn2, i); ParamPopAssign(vector<double>, wn3, i); ParamPopAssign(vector<double>, va1, i); ParamPopAssign(vector<double>, wva1, i); ParamPopAssign(vector<double>, ei_va1, i); ParamPopAssign(vector<double>, ei2_va1, i); ParamPopAssign(vector<double>, ei3_va1, i); ParamPopAssign(vector<double>, ed_va1i, i); ParamPopAssign(vector<double>, ed_va1i2, i); ParamPopAssign(vector<double>, ed_va1i3, i); ParamPopAssign(vector<double>, wva2, i); ParamPopAssign(vector<double>, ei_va2, i); ParamPopAssign(vector<double>, ei2_va2, i); ParamPopAssign(vector<double>, ei3_va2, i); ParamPopAssign(vector<double>, ed_va2i, i); ParamPopAssign(vector<double>, ed_va2i2, i); ParamPopAssign(vector<double>, ed_va2i3, i); ParamPopAssign(vector<double>, wva3, i); ParamPopAssign(vector<double>, ei_va3, i); ParamPopAssign(vector<double>, ei2_va3, i); ParamPopAssign(vector<double>, ei3_va3, i); ParamPopAssign(vector<double>, ed_va3i, i); ParamPopAssign(vector<double>, ed_va3i2, i); ParamPopAssign(vector<double>, ed_va3i3, i); ParamPopAssign(vector<double>, vb1, i); ParamPopAssign(vector<double>, wvb1, i); ParamPopAssign(vector<double>, ei_vb1, i); ParamPopAssign(vector<double>, ei2_vb1, i); ParamPopAssign(vector<double>, ei3_vb1, i); ParamPopAssign(vector<double>, ed_vb1i, i); ParamPopAssign(vector<double>, ed_vb1i2, i); ParamPopAssign(vector<double>, ed_vb1i3, i); ParamPopAssign(vector<double>, wvb2, i); ParamPopAssign(vector<double>, ei_vb2, i); ParamPopAssign(vector<double>, ei2_vb2, i); ParamPopAssign(vector<double>, ei3_vb2, i); ParamPopAssign(vector<double>, ed_vb2i, i); ParamPopAssign(vector<double>, ed_vb2i2, i); ParamPopAssign(vector<double>, ed_vb2i3, i); ParamPopAssign(vector<double>, wvb3, i); ParamPopAssign(vector<double>, ei_vb3, i); ParamPopAssign(vector<double>, ei2_vb3, i); ParamPopAssign(vector<double>, ei3_vb3, i); ParamPopAssign(vector<double>, ed_vb3i, i); ParamPopAssign(vector<double>, ed_vb3i2, i); ParamPopAssign(vector<double>, ed_vb3i3, i); ParamPopAssign(vector<double>, A, i); ParamPopAssign(vector<double>, B, i); ParamPopAssign(vector<double>, D, i); ParamPopAssign(vector<double>, season_A, i); ParamPopAssign(vector<double>, season_T, i); ParamPopAssign(vector<double>, season_phi, i); ParamPopAssign(vector<double>, ifr1, i); ParamPopAssign(vector<double>, ihr1, i); ParamPopAssign(vector<double>, iir1, i); ParamPopAssign(vector<double>, ifr2, i); ParamPopAssign(vector<double>, ihr2, i); ParamPopAssign(vector<double>, iir2, i); ParamPopAssign(vector<double>, ifr3, i); ParamPopAssign(vector<double>, ihr3, i); ParamPopAssign(vector<double>, iir3, i); ParamPopAssign(vector<double>, eh_va1d, i); ParamPopAssign(vector<double>, eh_va1d2, i); ParamPopAssign(vector<double>, eh_va1d3, i); ParamPopAssign(vector<double>, eh_va2d, i); ParamPopAssign(vector<double>, eh_va2d2, i); ParamPopAssign(vector<double>, eh_va2d3, i); ParamPopAssign(vector<double>, eh_va3d, i); ParamPopAssign(vector<double>, eh_va3d2, i); ParamPopAssign(vector<double>, eh_va3d3, i); ParamPopAssign(vector<double>, eh_vb1d, i); ParamPopAssign(vector<double>, eh_vb1d2, i); ParamPopAssign(vector<double>, eh_vb1d3, i); ParamPopAssign(vector<double>, eh_vb2d, i); ParamPopAssign(vector<double>, eh_vb2d2, i); ParamPopAssign(vector<double>, eh_vb2d3, i); ParamPopAssign(vector<double>, eh_vb3d, i); ParamPopAssign(vector<double>, eh_vb3d2, i); ParamPopAssign(vector<double>, eh_vb3d3, i); ParamPopAssign(vector<double>, em_va1d, i); ParamPopAssign(vector<double>, em_va1d2, i); ParamPopAssign(vector<double>, em_va1d3, i); ParamPopAssign(vector<double>, em_va2d, i); ParamPopAssign(vector<double>, em_va2d2, i); ParamPopAssign(vector<double>, em_va2d3, i); ParamPopAssign(vector<double>, em_va3d, i); ParamPopAssign(vector<double>, em_va3d2, i); ParamPopAssign(vector<double>, em_va3d3, i); ParamPopAssign(vector<double>, em_vb1d, i); ParamPopAssign(vector<double>, em_vb1d2, i); ParamPopAssign(vector<double>, em_vb1d3, i); ParamPopAssign(vector<double>, em_vb2d, i); ParamPopAssign(vector<double>, em_vb2d2, i); ParamPopAssign(vector<double>, em_vb2d3, i); ParamPopAssign(vector<double>, em_vb3d, i); ParamPopAssign(vector<double>, em_vb3d2, i); ParamPopAssign(vector<double>, em_vb3d3, i); ParamPopAssign(vector<double>, et_va1i, i); ParamPopAssign(vector<double>, et_va1i2, i); ParamPopAssign(vector<double>, et_va1i3, i); ParamPopAssign(vector<double>, et_va2i, i); ParamPopAssign(vector<double>, et_va2i2, i); ParamPopAssign(vector<double>, et_va2i3, i); ParamPopAssign(vector<double>, et_va3i, i); ParamPopAssign(vector<double>, et_va3i2, i); ParamPopAssign(vector<double>, et_va3i3, i); ParamPopAssign(vector<double>, et_vb1i, i); ParamPopAssign(vector<double>, et_vb1i2, i); ParamPopAssign(vector<double>, et_vb1i3, i); ParamPopAssign(vector<double>, et_vb2i, i); ParamPopAssign(vector<double>, et_vb2i2, i); ParamPopAssign(vector<double>, et_vb2i3, i); ParamPopAssign(vector<double>, et_vb3i, i); ParamPopAssign(vector<double>, et_vb3i2, i); ParamPopAssign(vector<double>, et_vb3i3, i); ParamPopAssign(vector<double>, dDeath, i); ParamPopAssign(vector<double>, dHosp, i); ParamPopAssign(vector<double>, lHosp, i); ParamPopAssign(vector<double>, dICU, i); ParamPopAssign(vector<double>, lICU, i); ParamPopAssign(vector<double>, seed_times, i); ParamPopAssign(vector<double>, seed_times2, i); ParamPopAssign(vector<double>, seed_times3, i); ParamPopAssign(vector<double>, dist_seed_ages, i); // Names ParamPopAssign(string, name, i); ParamPopAssign(vector<string>, group_names, i); // Calculate P.pop[i].Recalculate(); } } // Read in processes if (list.containsElementNamed("processes")) { Rcpp::RObject r_processes = Rcpp::as<Rcpp::RObject>(list["processes"]); ParamSet(P.processes, r_processes); } ParamMatrixAssign(travel); // Read in schedule (change set) if (list.containsElementNamed("schedule")) { Rcpp::List schedule = Rcpp::as<Rcpp::List>(list["schedule"]); for (unsigned int j = 0; j < schedule.size(); ++j) { Rcpp::List sched = Rcpp::as<Rcpp::List>(schedule[j]); string param_name = Rcpp::as<string>(sched["parameter"]); vector<unsigned int> pops = Rcpp::as<vector<unsigned int>>(sched["pops"]); vector<unsigned int> runs; if (sched.containsElementNamed("runs")) runs = Rcpp::as<vector<unsigned int>>(sched["runs"]); string mode_name = Rcpp::as<string>(sched["mode"]); Change::Mode mode = Change::Assign; if (mode_name == "assign") mode = Change::Assign; else if (mode_name == "add") mode = Change::Add; else if (mode_name == "multiply") mode = Change::Multiply; else if (mode_name == "lowerto") mode = Change::LowerTo; else if (mode_name == "raiseto") mode = Change::RaiseTo; else if (mode_name == "bypass") mode = Change::Bypass; else throw std::logic_error("Unrecognized change mode " + mode_name + "."); vector<double> times = Rcpp::as<vector<double>>(sched["times"]); Rcpp::List values_list = Rcpp::as<Rcpp::List>(sched["values"]); vector<vector<double>> values; for (unsigned int k = 0; k < values_list.size(); ++k) values.push_back(Rcpp::as<vector<double>>(values_list[k])); P.changes.ch.push_back(Change(P, pops, runs, param_name, mode, times, values)); } } }
88aa5f12964f4ff490c9a87692217f0e96b96fd5
bf8b47c7726a07beef697de4c7ccd97d9df1cd8a
/testes/vectors.cpp
39a767787a45cf4306869980a2e80e70851b3010
[]
no_license
Vitor-labs/Trabalhos_ufc
2b5ee23aeb9366646ce1ea5cbb32d2d125de4de1
59c579aa45eecb20304448dfd0de121f17ae3263
refs/heads/main
2023-08-25T20:24:41.648233
2021-09-24T20:42:50
2021-09-24T20:42:50
404,305,634
6
0
null
null
null
null
UTF-8
C++
false
false
2,223
cpp
#include <iostream> #include <vector> // vector são recomendados para dados que // irão mudar pouco ao longo do tempo, já // que retirar um certo dado é custoso. // vectors pré-alocam espaço para elementos // futuros, mas sem espaço adicional além do // tipo do vector. // armazena elementos em locais de memória // contíguos, como uma matriz. Portanto, no // vetor o acesso aleatório é possível. using namespace std; class ponto { public: int x, y; ponto(int x, int y) { this->x = x; this->y = y; } }; int main(int argc, char const *argv[]) { /*vector<int> vet(5); for (int i = 0; i < vet.size(); i++){ vet[i] = i + 10;} if (vet.empty()){ cout << "vetor vazio" << endl;} else{ cout << "vetor com elementos: " << endl;} vector<int>::iterator it; for (it = vet.begin(); it != vet.end(); it++){ cout << vet.at(*it) << endl;} cout << endl << "Ultimo inserido: "<< vet.back() << endl; cout << "Primeiro inserido: " << vet.front() << endl; cout << endl; cout << "Primeiro Elemento: " << *vet.begin() << endl; cout << "Ultimo Elemento: " << *(--vet.end()) << endl; vet.pop_back(); vet.insert(vet.begin(), 40); cout << "Primeiro Elemento: " << *vet.begin() << endl; cout << "Ultimo Elemento: " << *(--vet.end()) << endl; cout << endl; vector<int>::reverse_iterator revit; cout << "Revertido" << endl; for (revit = vet.rbegin(); revit != vet.rend(); revit++){ cout << *revit << endl;} vet.pop_back(); cout << "Ultimo Elemento: " << *(--vet.end()) << endl;*/ vector<ponto *> vet; vector<ponto *>::iterator iter; ponto *p1 = new ponto(1, 2); ponto *p2 = new ponto(3, 4); ponto *p3 = new ponto(5, 6); ponto *p4 = new ponto(7, 8); ponto *p5 = new ponto(9, 0); vet.push_back(p1); vet.push_back(p2); vet.push_back(p3); vet.push_back(p4); vet.push_back(p5); for (iter = vet.begin(); iter != vet.end(); iter++) { cout << (*iter)->x << " " << (*iter)->y << endl; } return 0; }
797846ba820f9ee9b44242f9daacb5da5b551cff
47923a324bf9b694d341072ee0d649f2af5d7fe3
/src/Multiplicator.h
d4e57da1e9de45b93b98cfd1864d972b666673f2
[]
no_license
SKYMAN44/research-ads2020
da002ba6054c61dec1c5a1f3799751100d1c20d4
7fef93704a5a262e13497009ad42ac4cff84ee8e
refs/heads/master
2023-03-20T00:10:46.553204
2021-03-11T19:47:37
2021-03-11T19:47:37
258,759,694
1
0
null
null
null
null
UTF-8
C++
false
false
824
h
// // Created by Дмитрий Соколов on 26.04.2020. // #ifndef UNTITLED2_MULTIPLICATOR_H #define UNTITLED2_MULTIPLICATOR_H #endif //UNTITLED2_MULTIPLICATOR_H #include <random> #include <ctime> #include "Number.h" class Multiplicator { public: virtual Number multiply(Number& a, Number& b) = 0; static Number generate_random(size_t k, int seed); virtual ~Multiplicator() {} }; class GradeSchool : public Multiplicator { public: Number multiply(Number &num_1, Number &num_2) override; ~GradeSchool () {} }; class Karatsuba_M : public Multiplicator { public: Number multiply(Number &fst, Number &scnd) override; ~Karatsuba_M() {} }; class Divide_Conquere : public Multiplicator { public: Number multiply(Number& fst,Number& scnd) override; ~Divide_Conquere () {} };
98e88682b307da1f7b1661979f2f474d9f3389c0
3208e9d63e390f2d84fb442c22c7dafc255e9795
/Arrays/Easy/positionsoflargegroups.cpp
43f5631140b3fe3916c5f6caa4a63edc8850530f
[]
no_license
preethichandra20/LeetCode
892214522d164d8a616c5bb3906bfa10626e8b13
5ff4f7064089c3775eaef973ac33d52d3380d269
refs/heads/master
2023-05-28T21:48:44.559310
2021-06-14T17:23:34
2021-06-14T17:23:34
376,902,980
0
0
null
null
null
null
UTF-8
C++
false
false
861
cpp
#include<bits/stdc++.h> using namespace std; int main() { string s="abbxxxxzzy"; s=s+'0'; int n=s.length(); int count=1; char key=s[0]; int j=0; vector<vector<int>> result; for(int i=1;i<n;i++) { if(s[i]==key) { count++; } else{ key=s[i]; if(count>=3) { vector<int> temp; temp.push_back(i-count); temp.push_back(i-1); result[j].push_back(temp); j++; } count=1; } } for(int i=0;i<result.size();i++) { for(int j=0;j<2;j++) { cout<<result[i][j]<<" "; } cout<<endl; } }
c35ad47da074087c5f53e7450f5f831115b9f09b
77315d0f84ec16354b490e705722df39be47b7b6
/Source/NoesisGuiEditor/Private/NoesisBlueprintFactory.cpp
b66e0b9a5ba4922660562bdcbf469c4d0db55477
[]
no_license
miaohongbiao/UE4Plugin
d259f57fadf77a5b152249fe303f5947ae4f28b7
8ae40958c823e6a5a29f8ff3fef1ba4c4c449623
refs/heads/master
2021-06-21T14:26:42.443016
2017-02-27T19:48:27
2017-02-27T19:48:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,664
cpp
//////////////////////////////////////////////////////////////////////////////////////////////////// // Noesis Engine - http://www.noesisengine.com // Copyright (c) 2009-2010 Noesis Technologies S.L. All Rights Reserved. //////////////////////////////////////////////////////////////////////////////////////////////////// #include "NoesisGuiEditorPrivatePCH.h" #include "NoesisXamlFactory.h" // NoesisGuiEditor includes #include "NoesisGuiEditorModule.h" #define LOCTEXT_NAMESPACE "UNoesisBlueprintFactory" UNoesisBlueprintFactory::UNoesisBlueprintFactory(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { bCreateNew = true; SupportedClass = UNoesisBlueprint::StaticClass(); ParentClass = UNoesisInstance::StaticClass(); } UObject* UNoesisBlueprintFactory::FactoryCreateNew(UClass* Class, UObject* Parent, FName Name, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn) { if ((ParentClass == NULL) || !FKismetEditorUtilities::CanCreateBlueprintOfClass(ParentClass) || !ParentClass->IsChildOf(UNoesisInstance::StaticClass())) { FFormatNamedArguments Args; Args.Add(TEXT("ClassName"), (ParentClass != NULL) ? FText::FromString(ParentClass->GetName()) : LOCTEXT("Null", "(null)")); FMessageDialog::Open(EAppMsgType::Ok, FText::Format(LOCTEXT("CannotCreateNoesisBlueprint", "Cannot create a NoesisGui Blueprint based on the class '{ClassName}'."), Args)); return NULL; } else { return CastChecked<UNoesisBlueprint>(FKismetEditorUtilities::CreateBlueprint(ParentClass, Parent, Name, BPTYPE_Normal, UNoesisBlueprint::StaticClass(), UNoesisBlueprintGeneratedClass::StaticClass(), "UNoesisBlueprintFactory")); } }
85346a95d70c18b0994bf7cf0acd893c6eb51d79
b4e91238f886f5c79fd0563e53f5eefeca1e3875
/graph_theory/Edmonds_Karp.cpp
c4265754a5c25865889f9797a8dd361d82587e8c
[]
no_license
dushujun/ACM_SDNU
89e8191f1572b113840695550af6d217abddda4a
e3b38762f91c623a4ed7eca4c33f9e722d0fe7f2
refs/heads/master
2021-01-17T12:37:21.553730
2014-09-13T16:44:08
2014-09-13T16:44:08
23,982,232
1
0
null
null
null
null
UTF-8
C++
false
false
1,984
cpp
/*********************************************************** 最大流 Edmonds_Karp算法 Edmonds-Karp是一种求网络最大流的算法,与Ford-Fulkerson算法不同的是Edmonds-Karp 要求每次找长度最短的增广路径。可以使用BFS。 Ford-Fulkerson和Edmonds-Karp的执行效率不可相提并论——Edmonds-Karp可以过100, 而Ford-Fulkerson过50时时间就不可忍受了。 ***********************************************************/ #include <iostream> #include <queue> using namespace std; const int N = 210; const int INF = 0x7FFFFFFF; int n,m,map[N][N],path[N],flow[N],start,end; queue<int> q; int bfs(){ int i,t; while(!q.empty()) q.pop(); memset(path,-1,sizeof(path)); path[start]=0,flow[start]=INF; q.push(start); while(!q.empty()){ t=q.front(); q.pop(); if(t==end) break; for(i=1;i<=m;i++){ if(i!=start && path[i]==-1 && map[t][i]){ flow[i]=flow[t]<map[t][i]?flow[t]:map[t][i]; q.push(i); path[i]=t; } } } if(path[end]==-1) return -1; return flow[m]; //一次遍历之后的流量增量 } int Edmonds_Karp(){ int max_flow=0,step,now,pre; while((step=bfs())!=-1){ //找不到增路径时退出 max_flow+=step; now=end; while(now!=start){ pre=path[now]; map[pre][now]-=step; //更新正向边的实际容量 map[now][pre]+=step; //添加反向边 now=pre; } } return max_flow; } int main(){ int i,u,v,cost; while(scanf("%d %d",&n,&m)!=EOF){ memset(map,0,sizeof(map)); for(i=0;i<n;i++){ scanf("%d %d %d",&u,&v,&cost); map[u][v]+=cost; //not just only one input } start=1,end=m; printf("%d\n",Edmonds_Karp()); } return 0; }
c56b9c758a82e59b5cdcf3b4669a39bdff43cb6e
0ccba45cf6212c42daca792b764eec3051e103e7
/LeetCode/Sort/maximum-gap.cpp
715fecbc1a2a21e2c1cbb6dc69452486bb429f2d
[]
no_license
novostary/codes
a92d260484fb9b02d4e52de05bc30861b2b16376
2483f2b60b92b6e7b9c8d8e8cc38aeda6c2281c7
refs/heads/master
2021-01-22T03:39:34.870844
2016-03-28T15:35:38
2016-03-28T15:35:38
25,671,647
0
0
null
null
null
null
UTF-8
C++
false
false
1,788
cpp
#include <vector> #include <algorithm> using std::vector; using std::max; using std::min; // Runtime: 8 ms // bucket sort // https://leetcode.com/discuss/18499/bucket-sort-java-solution-with-explanation-o-time-and-space // https://leetcode.com/discuss/27754/my-c-code-12-ms-bucket-sort-o-n-time-and-space class Solution { public: // Runtime: 8 ms int maximumGap(vector<int>& nums) { if (nums.size() < 2) { return 0; } int minV = nums[0], maxV = nums[0]; for (int i = 1; i < nums.size(); i++) { //minV = min(minV, nums[i]); // Runtime: 12 ms //maxV = max(maxV, nums[i]); if (minV > nums[i]) { // Runtime: 8 ms minV = min(minV, nums[i]); } else { maxV = max(maxV, nums[i]); } } int bucketSize = max(1, (maxV - minV) / ((int)nums.size() - 1)); int bucketNum = (maxV - minV) / bucketSize + 1; if (bucketNum == 1) { return maxV - minV; } vector<int> bucketMax(bucketNum, INT_MIN); vector<int> bucketMin(bucketNum, INT_MAX); vector<int> bucketCount(bucketNum, 0); for (auto n : nums) { int index = (n - minV) / bucketSize; bucketCount[index]++; bucketMax[index] = max(bucketMax[index], n); bucketMin[index] = min(bucketMin[index], n); } int preMax = minV; int maxGap = INT_MIN; for (int i = 0; i < bucketNum; i++) { if (bucketCount[i] > 0) { // if (bucketMin[i] != INT_MAX || bucketMax[i] != INT_MIN) // don't use bucketCount maxGap = max(maxGap, bucketMin[i] - preMax); preMax = bucketMax[i]; } } return maxGap; } // Runtime: 16 ms int maximumGap3(vector<int>& nums) { if (nums.size() < 2) { return 0; } sort(nums.begin(), nums.end()); int maxGap = 0; for (int i = 0; i < nums.size() - 1; i++) { maxGap = max(nums[i + 1] - nums[i], maxGap); } return maxGap; } };
914f9011c5ebd44dc062105c19d34430782c56f9
7a589d807fdce6d11a7e6d3bcc1289cf7e138137
/2016-IAP-Arduino/group_large_projects/Jimmy-two shoes/src/AnimationController.h
653e304c3e6d373acd897151f4e7cb5798ab6316
[]
no_license
mens-et-manus/archive
d24b35019a28029da62ac40c17c2da4331ecaadb
80959af9322cda6bc7bf843c3faf4d9aba31c0b4
refs/heads/master
2020-06-03T14:02:26.737837
2017-09-18T23:31:41
2017-09-18T23:31:41
94,132,895
0
0
null
null
null
null
UTF-8
C++
false
false
635
h
/* AnimationController.h - Library to control the different weather conditions. */ #ifndef AnimationController_h #define AnimationController_h #include "Arduino.h" enum WeatherCondition{ NONE, RAINY, CLOUDY, SUNNY, RAINY_LIGHTNING, CLOUD_LIGHTNING, STORM } class AnimationController { public: AnimationController(CloudController cloud, LightController light, RainController rain, SoundController sound); animateWithCondition(WeatherCondition weather); private: CloudController _cloud; LightController _light; RainController _rain; SoundController _sound; WeatherCondition _weather; }; #endif
15d373c34ba710b6ea7cbc959e6515a8efe602a5
5f46f7b94395f6586889d6a1062d74745694fa27
/Project/Bin/CHighScores.h
9d83ec7e96e0117ab9bef1d1f3d4540a00a79e9f
[]
no_license
phautamaki/Space-Invaders
360d7ce58a708e02b02325be127fcef2a70e5408
d6f06e604246d1b7d8e58f8326889e615372928f
refs/heads/master
2020-12-30T14:56:33.907381
2012-11-30T15:15:04
2012-11-30T15:15:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
758
h
#ifndef _CHIGHSCORES_H_ #define _CHIGHSCORES_H_ #include "CSurface.h" #include <vector> #include <string> //============================================================================= class CHighScores { public: CHighScores(); bool OnInit(); void OnRender(SDL_Surface* Surf_Display) const; bool CheckPoints(int Points) const; void Add(std::string Name, int Points); private: bool SavePoints(); //----------------------------------------------------------------------------- private: // TODO: Use better container (or vector with struct) std::vector<int> ScoreList; std::vector<std::string> NameList; std::string FilePath; unsigned int MaxScores; }; //============================================================================= #endif
42d26aab00f9b0083c998cb1269dc72c10eb9ee1
b34ee8a23cbdf8210566d1557b02d65bd5d5f23b
/tmp.cpp
bdbb8a2c812760bc89e7c0737f0d0c7641343a58
[]
no_license
abramkinyura/Billiards
dfc7f53ecc252895d652f29555b4959b75d6bc29
62e9b118d21fbd816e46b2b035d2e6c63ae29963
refs/heads/master
2021-08-08T18:19:47.214257
2017-11-10T21:46:48
2017-11-10T21:46:48
110,293,496
0
0
null
null
null
null
UTF-8
C++
false
false
8,809
cpp
// // A simple example of OpenGL usage over X11: // draw a tetraedron with a spere on top of it. // // The 3D model can be rotated by the mouse movement // with the left mouse button pressed. // // The program is based on the class GLWindow, that presents a // convenient C++ interface to OpenGL and X11 functions. // // Written by V.Borisenko #include <stdio.h> #include <stdlib.h> #include <math.h> #include "GLWindow.h" //-------------------------------------------------- // Definition of class "MyWindow" // class MyWindow: public GLWindow { // Our main class derived from GLWindow GLUquadricObj* m_Quadric; // Quadric object used to draw a sphere GLfloat m_Alpha; // Angle of rotation around vert.axis in degrees GLfloat m_Beta; // Angle of rotation around hor.axis in degrees I2Point m_MousePos; // Previous position of mouse pointer public: MyWindow(): // Constructor GLWindow(), m_Quadric(0), m_Alpha(-10.), m_Beta(-7.), m_MousePos(-1, -1) {} void render(); // Draw a scene graph double f(double x, double y); virtual void onExpose(XEvent& event); virtual void onKeyPress(XEvent& event); virtual void onButtonPress(XEvent& event); virtual void onButtonRelease(XEvent& event); virtual void onMotionNotify(XEvent& event); }; // // Process the Expose event: draw in the window // void MyWindow::onExpose(XEvent& event) { makeCurrent(); // Rotate the scene glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_LIGHT0); // Turn on the first light source // Rotate a model glRotatef(m_Beta, 1., 0., 0.); glRotatef(m_Alpha, 0., 1., 0.); render(); // Draw a scene graph swapBuffers(); } // // Process the KeyPress event: // if "q" is pressed, then close the window // void MyWindow::onKeyPress(XEvent& event) { KeySym key; char keyName[256]; int nameLen = XLookupString(&(event.xkey), keyName, 255, &key, 0); printf("KeyPress: keycode=0x%x, state=0x%x, KeySym=0x%x\n", event.xkey.keycode, event.xkey.state, (int) key); if (nameLen > 0) { keyName[nameLen] = 0; printf("\"%s\" button pressed.\n", keyName); if (keyName[0] == 'q') { // quit => close window destroyWindow(); } } } // Process mouse click void MyWindow::onButtonPress(XEvent& event) { int x = event.xbutton.x; int y = event.xbutton.y; int mouseButton = event.xbutton.button; // printf("Mouse click: x=%d, y=%d, button=%d\n", x, y, mouseButton); m_MousePos.x = (-1); m_MousePos.y = (-1); // Mouse position undefined } void MyWindow::onButtonRelease(XEvent& event) { m_MousePos.x = (-1); m_MousePos.y = (-1); // Mouse position undefined } // // Process the mouse movement // void MyWindow::onMotionNotify(XEvent& event) { int x = event.xbutton.x; int y = event.xbutton.y; if ((event.xbutton.state & Button1Mask) != 0) { if (m_MousePos.x >= 0) { int dx = x - m_MousePos.x; int dy = y - m_MousePos.y; if (m_Beta > 100. || m_Beta < (-100.)) dx = -dx; m_Alpha += (GLfloat) dx * 0.1; if (fabs(m_Alpha) > 360.) m_Alpha -= ((int) m_Alpha / 360) * 360.; m_Beta += (GLfloat) dy * 0.1; if (fabs(m_Beta) > 360.) m_Beta -= ((int) m_Beta / 360) * 360.; redraw(); } m_MousePos.x = x; m_MousePos.y = y; } else { m_MousePos.x = (-1); m_MousePos.y = (-1); // Undefined } } // // Draw a 3D model // void MyWindow::render() { GLfloat color[4], normal[3]; glClearColor(0.2, 0.3, 0.5, 1.); // Background color: dark blue glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); color[0] = 1.0; color[1] = 0.2; color[2] = 0.2; // Red glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color); // Coordinate system glBegin(GL_LINES); // X-axis normal[0] = 0.; normal[1] = 0.; normal[2] = 1.; glNormal3fv(normal); glVertex3f(-10., 0., 0.); glVertex3f(10., 0., 0.); // Y-axis //... normal[0] = 0.; //... normal[1] = 0.; //... normal[2] = 1.; //... glNormal3fv(normal); glVertex3f(0., -10., 0.); glVertex3f(0., 10., 0.); // Z-axis normal[0] = 1.; normal[1] = 0.; normal[2] = 0.; glNormal3fv(normal); glVertex3f(0., 0., -10.); glVertex3f(0., 0., 10.); glEnd(); // Construct a tetraedron GLfloat side = sqrt(3.); GLfloat height = sqrt(2.); // Coordinates of tetraedron vertices: GLfloat x0 = 0., y0 = (-height/4.), z0 = 1.; GLfloat x1 = side/2., y1 = y0, z1 = (-0.5); GLfloat x2 = (-x1), y2 = y0, z2 = z1; GLfloat x3 = 0., y3 = height*3./4., z3 = 0.; // Draw a tetraedron glBegin(GL_TRIANGLES); // Bottom face -------------------------------------- color[0] = 0.2; color[1] = 1.; color[2] = 0.2; // Green glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color); // Set a normal to the bottom face normal[0] = 0.; normal[1] = -1.; normal[2] = 0.; glNormal3fv(normal); // Define vertices of the face glVertex3f(x0, y0, z0); glVertex3f(x2, y2, z2); glVertex3f(x1, y1, z1); // Right side face -------------------------------------- color[0] = 1.; color[1] = 0.2; color[2] = 0.2; // Red glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color); // Set a normal to the right side face normal[0] = (x0 + x1 + x3) / 3.; normal[1] = (y0 + y1 + y3) / 3.; normal[2] = (z0 + z1 + z3) / 3.; glNormal3fv(normal); // Define vertices of the face glVertex3f(x0, y0, z0); glVertex3f(x1, y1, z1); glVertex3f(x3, y3, z3); // Back face -------------------------------------- color[0] = 0.9; color[1] = 0.8; color[2] = 0.1; // Yellow glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color); // Define the normal to the face normal[0] = (x1 + x2 + x3) / 3.; normal[1] = (y1 + y2 + y3) / 3.; normal[2] = (z1 + z2 + z3) / 3.; glNormal3fv(normal); // Define vertices of the face glVertex3f(x1, y1, z1); glVertex3f(x2, y2, z2); glVertex3f(x3, y3, z3); // Left side face -------------------------------------- color[0] = 0.2; color[1] = 0.2; color[2] = 1.; // Blue glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color); // Define the normal to the face normal[0] = (x0 + x2 + x3) / 3.; normal[1] = (y0 + y2 + y3) / 3.; normal[2] = (z0 + z2 + z3) / 3.; glNormal3fv(normal); // Define vertices of the face glVertex3f(x2, y2, z2); glVertex3f(x0, y0, z0); glVertex3f(x3, y3, z3); glEnd(); // Draw a sphere on top of tetraedron if (m_Quadric == 0) { m_Quadric = gluNewQuadric(); // Create a Quadric object gluQuadricNormals(m_Quadric, GLU_SMOOTH); } glTranslatef(x3, y3, z3); color[0] = 0.2; color[1] = 0.6; color[2] = 0.9; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color); gluSphere( m_Quadric, 0.3, 32, // Num. slices (similar to lines of longitude) 16 // Num. stacks (similar to lines of latitude) ); } ///////////////////////////////////////////////////////////// // Main: initialize X, create an instance of MyWindow class, // and start the message loop int main() { // Initialize X stuff if (!GWindow::initX()) { printf("Could not connect to X-server.\n"); exit(1); } int width = GWindow::screenMaxX()/2; int height = GWindow::screenMaxY()/2; double aspect = (double) width / (double) height; MyWindow w; w.createWindow( I2Rectangle( // Window frame rectangle: I2Point(10, 10), // left-top corner, width, height // width, height ), R2Rectangle( // Window coordinate rectangle R2Point(-2. * aspect, -2.), // left-top corner, 4. * aspect, 4. // width, height ), "OpenGL Test" // Window title ); w.setBackground("lightGray"); w.makeCurrent(); GLWindow::initializeOpenGL(); GWindow::messageLoop(); GWindow::closeX(); return 0; }
c35cff7b00e29806267ec1aa29443fc2c5b28843
7129fecf95c3c27f19ccb63d2a6529647e766c6c
/TestClient/TCPsend.cpp
a11252d1b39a48b60e471a39bec2c0f78433ae2a
[ "MIT" ]
permissive
labbloe/Oracle
d103b5d60386c4d70306463256754d5c9d143ebe
9acb42d68c04291da87bac7b92cabbae0c32a50d
refs/heads/master
2023-04-14T11:00:34.558345
2021-04-24T21:01:30
2021-04-24T21:01:30
271,418,115
0
0
MIT
2021-04-24T21:01:30
2020-06-11T00:57:41
C++
UTF-8
C++
false
false
7,090
cpp
// Client program example #define WIN32_LEAN_AND_MEAN #include <iostream> #include <winsock2.h> #include <stdlib.h> #include <stdio.h> #include <string.h> using std::getline; using std::cin; using std::cout; using std::endl; using std::string; #define DEFAULT_PORT 2007 // TCP socket type #define DEFAULT_PROTO SOCK_STREAM void Usage(char *progname) { fprintf(stderr,"Usage: %s -p [protocol] -n [server name/IP] -e [port_num] -l [iterations]\n", progname); fprintf(stderr,"Where:\n\tprotocol is one of TCP or UDP\n"); fprintf(stderr,"\t- server is the IP address or name of server\n"); fprintf(stderr,"\t- port_num is the port to listen on\n"); fprintf(stderr,"\t- iterations is the number of loops to execute.\n"); fprintf(stderr,"\t- (-l by itself makes client run in an infinite loop,\n"); fprintf(stderr,"\t- Hit Ctrl-C to terminate it)\n"); fprintf(stderr,"\t- The defaults are TCP , localhost and 2007\n"); WSACleanup(); exit(1); } int main(int argc, char **argv) { char Buffer[128]; // default to localhost char *server_name= "localhost"; unsigned short port = DEFAULT_PORT; int retval, loopflag = 0; int i, loopcount, maxloop=-1; unsigned int addr; int socket_type = DEFAULT_PROTO; struct sockaddr_in server; struct hostent *hp; WSADATA wsaData; SOCKET conn_socket; if (argc >1) { for(i=1; i<argc; i++) { if ((argv[i][0] == '-') || (argv[i][0] == '/')) { switch(tolower(argv[i][1])) { case 'p': if (!stricmp(argv[i+1], "TCP")) socket_type = SOCK_STREAM; else if (!stricmp(argv[i+1], "UDP")) socket_type = SOCK_DGRAM; else Usage(argv[0]); i++; break; case 'n': server_name = argv[++i]; break; case 'e': port = atoi(argv[++i]); break; case 'l': loopflag =1; if (argv[i+1]) { if (argv[i+1][0] != '-') maxloop = atoi(argv[i+1]); } else maxloop = -1; i++; break; default: Usage(argv[0]); break; } } else Usage(argv[0]); } } if ((retval = WSAStartup(0x202, &wsaData)) != 0) { fprintf(stderr,"Client: WSAStartup() failed with error %d\n", retval); WSACleanup(); return -1; } else printf("Client: WSAStartup() is OK.\n"); if (port == 0) { Usage(argv[0]); } // Attempt to detect if we should call gethostbyname() or gethostbyaddr() if (isalpha(server_name[0])) { // server address is a name hp = gethostbyname(server_name); } else { // Convert nnn.nnn address to a usable one addr = inet_addr(server_name); hp = gethostbyaddr((char *)&addr, 4, AF_INET); } if (hp == NULL ) { fprintf(stderr,"Client: Cannot resolve address \"%s\": Error %d\n", server_name, WSAGetLastError()); WSACleanup(); exit(1); } else printf("Client: gethostbyaddr() is OK.\n"); // Copy the resolved information into the sockaddr_in structure memset(&server, 0, sizeof(server)); memcpy(&(server.sin_addr), hp->h_addr, hp->h_length); server.sin_family = hp->h_addrtype; server.sin_port = htons(port); conn_socket = socket(AF_INET, socket_type, 0); /* Open a socket */ if (conn_socket <0 ) { fprintf(stderr,"Client: Error Opening socket: Error %d\n", WSAGetLastError()); WSACleanup(); return -1; } else printf("Client: socket() is OK.\n"); // Notice that nothing in this code is specific to whether we // are using UDP or TCP. // We achieve this by using a simple trick. // When connect() is called on a datagram socket, it does not // actually establish the connection as a stream (TCP) socket // would. Instead, TCP/IP establishes the remote half of the // (LocalIPAddress, LocalPort, RemoteIP, RemotePort) mapping. // This enables us to use send() and recv() on datagram sockets, // instead of recvfrom() and sendto() printf("Client: Client connecting to: %s.\n", hp->h_name); if (connect(conn_socket, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) { fprintf(stderr,"Client: connect() failed: %d\n", WSAGetLastError()); WSACleanup(); return -1; } else printf("Client: connect() is OK.\n"); // Test sending some string loopcount = 0; while(1) { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// cout<<"Enter Command: "; string userInput; getline(cin,userInput,'\n'); LPSTR tempInput = const_cast<char*>(userInput.c_str()); wsprintf(Buffer,tempInput, loopcount++); retval = send(conn_socket, Buffer, sizeof(Buffer), 0); if (retval == SOCKET_ERROR) { fprintf(stderr,"Client: send() failed: error %d.\n", WSAGetLastError()); WSACleanup(); return -1; } else printf("Client: send() is OK.\n"); printf("Client: Sent data \"%s\"\n", Buffer); retval = recv(conn_socket, Buffer, sizeof(Buffer), 0); if (retval == SOCKET_ERROR) { fprintf(stderr,"Client: recv() failed: error %d.\n", WSAGetLastError()); closesocket(conn_socket); WSACleanup(); return -1; } else printf("Client: recv() is OK.\n"); // We are not likely to see this with UDP, since there is no // 'connection' established. if (retval == 0) { printf("Client: Server closed connection.\n"); closesocket(conn_socket); WSACleanup(); return -1; } printf("Client: Received %d bytes, data \"%s\" from server.\n", retval, Buffer); if (!loopflag) { printf("Client: Terminating connection...\n"); break; } else { if ((loopcount >= maxloop) && (maxloop >0)) break; } } closesocket(conn_socket); WSACleanup(); return 0; }
828014ee7851ccd8ad697edd357e6e27d39e6470
629ae5d7d939996dccbf4505cb74d1509ecf294d
/livox_ros_driver/livox_ros_driver/lds_lidar.cpp
e76117b0a0731ec980f6e7f946983497c65d7ab4
[ "BSD-3-Clause", "Zlib", "BSD-4-Clause-UC", "LicenseRef-scancode-rsa-md4", "BSD-4-Clause", "LicenseRef-scancode-other-permissive", "MIT", "Beerware", "RSA-MD", "ISC", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-rsa-1990" ]
permissive
kmiya/livox_ros_driver
643b9dfb80e181a51dd99cdf7b09bd23cb3bbb09
5b37ab7795eba597df2d10e17be4f5b29d79983d
refs/heads/master
2022-12-29T18:26:41.301610
2020-08-13T01:26:59
2020-08-13T01:26:59
287,151,001
0
0
NOASSERTION
2020-08-13T01:22:09
2020-08-13T01:22:08
null
UTF-8
C++
false
false
30,520
cpp
// // The MIT License (MIT) // // Copyright (c) 2019 Livox. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #include "lds_lidar.h" #include <stdio.h> #include <string.h> #include <memory> #include <thread> #include <mutex> #include "rapidjson/document.h" #include "rapidjson/filereadstream.h" #include "rapidjson/stringbuffer.h" using namespace std; namespace livox_ros { /** Const varible * ------------------------------------------------------------------------------- */ /** For callback use only */ LdsLidar *g_lds_ldiar = nullptr; /** Global function for common use * ---------------------------------------------------------------*/ /** Lds lidar function * ---------------------------------------------------------------------------*/ LdsLidar::LdsLidar(uint32_t interval_ms) : Lds(interval_ms, kSourceRawLidar) { auto_connect_mode_ = true; is_initialized_ = false; whitelist_count_ = 0; memset(broadcast_code_whitelist_, 0, sizeof(broadcast_code_whitelist_)); ResetLdsLidar(); } LdsLidar::~LdsLidar() {} void LdsLidar::ResetLdsLidar(void) { ResetLds(kSourceRawLidar); } int LdsLidar::InitLdsLidar(std::vector<std::string> &broadcast_code_strs, const char *user_config_path) { if (is_initialized_) { printf("LiDAR data source is already inited!\n"); return -1; } if (!Init()) { Uninit(); printf("Livox-SDK init fail!\n"); return -1; } LivoxSdkVersion _sdkversion; GetLivoxSdkVersion(&_sdkversion); printf("Livox SDK version %d.%d.%d\n", _sdkversion.major, _sdkversion.minor, _sdkversion.patch); SetBroadcastCallback(OnDeviceBroadcast); SetDeviceStateUpdateCallback(OnDeviceChange); /** Add commandline input broadcast code */ for (auto input_str : broadcast_code_strs) { AddBroadcastCodeToWhitelist(input_str.c_str()); } ParseConfigFile(user_config_path); if (whitelist_count_) { DisableAutoConnectMode(); printf("Disable auto connect mode!\n"); printf("List all broadcast code in whiltelist:\n"); for (uint32_t i = 0; i < whitelist_count_; i++) { printf("%s\n", broadcast_code_whitelist_[i]); } } else { EnableAutoConnectMode(); printf("No broadcast code was added to whitelist, swith to automatic " "connection mode!\n"); } if (enable_timesync_) { timesync_ = TimeSync::GetInstance(); if (timesync_->InitTimeSync(timesync_config_)) { printf("Timesync init fail\n"); return -1; } if (timesync_->SetReceiveSyncTimeCb(ReceiveSyncTimeCallback, this)) { printf("Set Timesync callback fail\n"); return -1; } timesync_->StartTimesync(); } /** Start livox sdk to receive lidar data */ if (!Start()) { Uninit(); printf("Livox-SDK init fail!\n"); return -1; } /** Add here, only for callback use */ if (g_lds_ldiar == nullptr) { g_lds_ldiar = this; } is_initialized_ = true; printf("Livox-SDK init success!\n"); return 0; } int LdsLidar::DeInitLdsLidar(void) { if (!is_initialized_) { printf("LiDAR data source is not exit"); return -1; } Uninit(); printf("Livox SDK Deinit completely!\n"); if (timesync_) { timesync_->DeInitTimeSync(); } return 0; } void LdsLidar::PrepareExit(void) { DeInitLdsLidar(); } /** Static function in LdsLidar for callback or event process * ------------------------------------*/ /** Receiving point cloud data from Livox LiDAR. */ void LdsLidar::OnLidarDataCb(uint8_t handle, LivoxEthPacket *data, uint32_t data_num, void *client_data) { using namespace std; LdsLidar *lds_lidar = static_cast<LdsLidar *>(client_data); LivoxEthPacket *eth_packet = data; if (!data || !data_num || (handle >= kMaxLidarCount)) { return; } LidarDevice *p_lidar = &lds_lidar->lidars_[handle]; LidarPacketStatistic *packet_statistic = &p_lidar->statistic_info; LdsStamp cur_timestamp; memcpy(cur_timestamp.stamp_bytes, eth_packet->timestamp, sizeof(cur_timestamp)); if (kImu != eth_packet->data_type) { if (p_lidar->raw_data_type != eth_packet->data_type) { p_lidar->raw_data_type = eth_packet->data_type; p_lidar->packet_interval = GetPacketInterval(eth_packet->data_type); p_lidar->packet_interval_max = p_lidar->packet_interval * 1.8f; } if (eth_packet->timestamp_type == kTimestampTypePps) { if ((cur_timestamp.stamp < packet_statistic->last_timestamp) && (cur_timestamp.stamp < kPacketTimeGap)) { // whether a new sync frame auto cur_time = std::chrono::high_resolution_clock::now(); int64_t sync_time = cur_time.time_since_epoch().count(); packet_statistic->timebase = sync_time; // used receive time as timebase } } packet_statistic->last_timestamp = cur_timestamp.stamp; LidarDataQueue *p_queue = &p_lidar->data; if (nullptr == p_queue->storage_packet) { uint32_t queue_size = CalculatePacketQueueSize(lds_lidar->buffer_time_ms_, eth_packet->data_type); queue_size = queue_size * 16; /* 16 multiple the min size */ InitQueue(p_queue, queue_size); printf("Lidar%02d[%s] queue size : %d %d\n", p_lidar->handle, p_lidar->info.broadcast_code, queue_size, p_queue->size); } if (!QueueIsFull(p_queue)) { QueuePushAny(p_queue, (uint8_t *)eth_packet, GetEthPacketLen(eth_packet->data_type), packet_statistic->timebase, GetPointsPerPacket(eth_packet->data_type)); } } else { if (eth_packet->timestamp_type == kTimestampTypePps) { if ((cur_timestamp.stamp < packet_statistic->last_imu_timestamp) && (cur_timestamp.stamp < kPacketTimeGap)) { // whether a new sync frame auto cur_time = std::chrono::high_resolution_clock::now(); int64_t sync_time = cur_time.time_since_epoch().count(); packet_statistic->imu_timebase = sync_time; // used receive time as timebase } } packet_statistic->last_imu_timestamp = cur_timestamp.stamp; LidarDataQueue *p_queue = &p_lidar->imu_data; if (nullptr == p_queue->storage_packet) { uint32_t queue_size = 256; InitQueue(p_queue, queue_size); printf("Lidar%02d[%s] imu queue size : %d %d\n", p_lidar->handle, p_lidar->info.broadcast_code, queue_size, p_queue->size); } if (!QueueIsFull(p_queue)) { QueuePushAny(p_queue, (uint8_t *)eth_packet, GetEthPacketLen(eth_packet->data_type), packet_statistic->timebase, GetPointsPerPacket(eth_packet->data_type)); } } } void LdsLidar::OnDeviceBroadcast(const BroadcastDeviceInfo *info) { if (info == nullptr) { return; } if (info->dev_type == kDeviceTypeHub) { printf("In lidar mode, couldn't connect a hub : %s\n", info->broadcast_code); return; } if (g_lds_ldiar->IsAutoConnectMode()) { printf("In automatic connection mode, will connect %s\n", info->broadcast_code); } else { if (!g_lds_ldiar->IsBroadcastCodeExistInWhitelist(info->broadcast_code)) { printf("Not in the whitelist, please add %s to if want to connect!\n", info->broadcast_code); return; } } bool result = false; uint8_t handle = 0; result = AddLidarToConnect(info->broadcast_code, &handle); if (result == kStatusSuccess && handle < kMaxLidarCount) { SetDataCallback(handle, OnLidarDataCb, (void *)g_lds_ldiar); LidarDevice *p_lidar = &(g_lds_ldiar->lidars_[handle]); p_lidar->handle = handle; p_lidar->connect_state = kConnectStateOff; UserRawConfig config; if (g_lds_ldiar->GetRawConfig(info->broadcast_code, config)) { printf("Could not find raw config, set config to default!\n"); config.enable_fan = 1; config.return_mode = kFirstReturn; config.coordinate = kCoordinateCartesian; config.imu_rate = kImuFreq200Hz; config.extrinsic_parameter_source = kNoneExtrinsicParameter; config.enable_high_sensitivity = false; } p_lidar->config.enable_fan = config.enable_fan; p_lidar->config.return_mode = config.return_mode; p_lidar->config.coordinate = config.coordinate; p_lidar->config.imu_rate = config.imu_rate; p_lidar->config.extrinsic_parameter_source = config.extrinsic_parameter_source; p_lidar->config.enable_high_sensitivity = config.enable_high_sensitivity; } else { printf("Add lidar to connect is failed : %d %d \n", result, handle); } } /** Callback function of changing of device state. */ void LdsLidar::OnDeviceChange(const DeviceInfo *info, DeviceEvent type) { if (info == nullptr) { return; } uint8_t handle = info->handle; if (handle >= kMaxLidarCount) { return; } LidarDevice *p_lidar = &(g_lds_ldiar->lidars_[handle]); if (type == kEventConnect) { QueryDeviceInformation(handle, DeviceInformationCb, g_lds_ldiar); if (p_lidar->connect_state == kConnectStateOff) { p_lidar->connect_state = kConnectStateOn; p_lidar->info = *info; } } else if (type == kEventDisconnect) { printf("Lidar[%s] disconnect!\n", info->broadcast_code); ResetLidar(p_lidar, kSourceRawLidar); } else if (type == kEventStateChange) { p_lidar->info = *info; } if (p_lidar->connect_state == kConnectStateOn) { printf("Lidar[%s] status_code[%d] working state[%d] feature[%d]\n", p_lidar->info.broadcast_code, p_lidar->info.status.status_code.error_code, p_lidar->info.state, p_lidar->info.feature); SetErrorMessageCallback(handle, LidarErrorStatusCb); /** Config lidar parameter */ if (p_lidar->info.state == kLidarStateNormal) { /** Ensure the thread safety for set_bits and connect_state */ lock_guard<mutex> lock(g_lds_ldiar->config_mutex_); if (p_lidar->config.coordinate != 0) { SetSphericalCoordinate(handle, SetCoordinateCb, g_lds_ldiar); } else { SetCartesianCoordinate(handle, SetCoordinateCb, g_lds_ldiar); } p_lidar->config.set_bits |= kConfigCoordinate; if (kDeviceTypeLidarMid40 != info->type) { LidarSetPointCloudReturnMode( handle, (PointCloudReturnMode)(p_lidar->config.return_mode), SetPointCloudReturnModeCb, g_lds_ldiar); p_lidar->config.set_bits |= kConfigReturnMode; } if (kDeviceTypeLidarMid40 != info->type) { LidarSetImuPushFrequency(handle, (ImuFreq)(p_lidar->config.imu_rate), SetImuRatePushFrequencyCb, g_lds_ldiar); p_lidar->config.set_bits |= kConfigImuRate; } if (p_lidar->config.extrinsic_parameter_source == kExtrinsicParameterFromLidar) { LidarGetExtrinsicParameter(handle, GetLidarExtrinsicParameterCb, g_lds_ldiar); p_lidar->config.set_bits |= kConfigGetExtrinsicParameter; } if (kDeviceTypeLidarTele == info->type) { if (p_lidar->config.enable_high_sensitivity) { LidarEnableHighSensitivity(handle, SetHighSensitivityCb, g_lds_ldiar); printf("Enable high sensitivity\n"); } else { LidarDisableHighSensitivity(handle, SetHighSensitivityCb, g_lds_ldiar); printf("Disable high sensitivity\n"); } p_lidar->config.set_bits |= kConfigSetHighSensitivity; } p_lidar->connect_state = kConnectStateConfig; } } } /** Query the firmware version of Livox LiDAR. */ void LdsLidar::DeviceInformationCb(livox_status status, uint8_t handle, DeviceInformationResponse *ack, void *clent_data) { if (status != kStatusSuccess) { printf("Device Query Informations Failed : %d\n", status); } if (ack) { printf("firmware version: %d.%d.%d.%d\n", ack->firmware_version[0], ack->firmware_version[1], ack->firmware_version[2], ack->firmware_version[3]); } } /** Callback function of Lidar error message. */ void LdsLidar::LidarErrorStatusCb(livox_status status, uint8_t handle, ErrorMessage *message) { static uint32_t error_message_count = 0; if (message != NULL) { ++error_message_count; if (0 == (error_message_count % 100)) { printf("handle: %u\n", handle); printf("temp_status : %u\n", message->lidar_error_code.temp_status); printf("volt_status : %u\n", message->lidar_error_code.volt_status); printf("motor_status : %u\n", message->lidar_error_code.motor_status); printf("dirty_warn : %u\n", message->lidar_error_code.dirty_warn); printf("firmware_err : %u\n", message->lidar_error_code.firmware_err); printf("pps_status : %u\n", message->lidar_error_code.device_status); printf("fan_status : %u\n", message->lidar_error_code.fan_status); printf("self_heating : %u\n", message->lidar_error_code.self_heating); printf("ptp_status : %u\n", message->lidar_error_code.ptp_status); printf("time_sync_status : %u\n", message->lidar_error_code.time_sync_status); printf("system_status : %u\n", message->lidar_error_code.system_status); } } } void LdsLidar::ControlFanCb(livox_status status, uint8_t handle, uint8_t response, void *clent_data) {} void LdsLidar::SetPointCloudReturnModeCb(livox_status status, uint8_t handle, uint8_t response, void *clent_data) { LdsLidar *lds_lidar = static_cast<LdsLidar *>(clent_data); if (handle >= kMaxLidarCount) { return; } LidarDevice *p_lidar = &(lds_lidar->lidars_[handle]); if (status == kStatusSuccess) { printf("Set return mode success!\n"); lock_guard<mutex> lock(lds_lidar->config_mutex_); p_lidar->config.set_bits &= ~((uint32_t)(kConfigReturnMode)); if (!p_lidar->config.set_bits) { LidarStartSampling(handle, StartSampleCb, lds_lidar); p_lidar->connect_state = kConnectStateSampling; } } else { LidarSetPointCloudReturnMode( handle, (PointCloudReturnMode)(p_lidar->config.return_mode), SetPointCloudReturnModeCb, lds_lidar); printf("Set return mode fail, try again!\n"); } } void LdsLidar::SetCoordinateCb(livox_status status, uint8_t handle, uint8_t response, void *clent_data) { LdsLidar *lds_lidar = static_cast<LdsLidar *>(clent_data); if (handle >= kMaxLidarCount) { return; } LidarDevice *p_lidar = &(lds_lidar->lidars_[handle]); if (status == kStatusSuccess) { printf("Set coordinate success!\n"); lock_guard<mutex> lock(lds_lidar->config_mutex_); p_lidar->config.set_bits &= ~((uint32_t)(kConfigCoordinate)); if (!p_lidar->config.set_bits) { LidarStartSampling(handle, StartSampleCb, lds_lidar); p_lidar->connect_state = kConnectStateSampling; } } else { if (p_lidar->config.coordinate != 0) { SetSphericalCoordinate(handle, SetCoordinateCb, lds_lidar); } else { SetCartesianCoordinate(handle, SetCoordinateCb, lds_lidar); } printf("Set coordinate fail, try again!\n"); } } void LdsLidar::SetImuRatePushFrequencyCb(livox_status status, uint8_t handle, uint8_t response, void *clent_data) { LdsLidar *lds_lidar = static_cast<LdsLidar *>(clent_data); if (handle >= kMaxLidarCount) { return; } LidarDevice *p_lidar = &(lds_lidar->lidars_[handle]); if (status == kStatusSuccess) { printf("Set imu rate success!\n"); lock_guard<mutex> lock(lds_lidar->config_mutex_); p_lidar->config.set_bits &= ~((uint32_t)(kConfigImuRate)); if (!p_lidar->config.set_bits) { LidarStartSampling(handle, StartSampleCb, lds_lidar); p_lidar->connect_state = kConnectStateSampling; } } else { LidarSetImuPushFrequency(handle, (ImuFreq)(p_lidar->config.imu_rate), SetImuRatePushFrequencyCb, g_lds_ldiar); printf("Set imu rate fail, try again!\n"); } } /** Callback function of get LiDARs' extrinsic parameter. */ void LdsLidar::GetLidarExtrinsicParameterCb( livox_status status, uint8_t handle, LidarGetExtrinsicParameterResponse *response, void *clent_data) { LdsLidar *lds_lidar = static_cast<LdsLidar *>(clent_data); if (handle >= kMaxLidarCount) { return; } if (status == kStatusSuccess) { if (response != nullptr) { printf("Lidar[%d] get ExtrinsicParameter status[%d] response[%d]\n", handle, status, response->ret_code); LidarDevice *p_lidar = &(lds_lidar->lidars_[handle]); ExtrinsicParameter *p_extrinsic = &p_lidar->extrinsic_parameter; p_extrinsic->euler[0] = static_cast<float>(response->roll * PI / 180.0); p_extrinsic->euler[1] = static_cast<float>(response->pitch * PI / 180.0); p_extrinsic->euler[2] = static_cast<float>(response->yaw * PI / 180.0); p_extrinsic->trans[0] = static_cast<float>(response->x / 1000.0); p_extrinsic->trans[1] = static_cast<float>(response->y / 1000.0); p_extrinsic->trans[2] = static_cast<float>(response->z / 1000.0); EulerAnglesToRotationMatrix(p_extrinsic->euler, p_extrinsic->rotation); if (p_lidar->config.extrinsic_parameter_source) { p_extrinsic->enable = true; } printf("Lidar[%d] get ExtrinsicParameter success!\n", handle); lock_guard<mutex> lock(lds_lidar->config_mutex_); p_lidar->config.set_bits &= ~((uint32_t)(kConfigGetExtrinsicParameter)); if (!p_lidar->config.set_bits) { LidarStartSampling(handle, StartSampleCb, lds_lidar); p_lidar->connect_state = kConnectStateSampling; } } else { printf("Lidar[%d] get ExtrinsicParameter fail!\n", handle); } } else if (status == kStatusTimeout) { printf("Lidar[%d] get ExtrinsicParameter timeout!\n", handle); } } void LdsLidar::SetHighSensitivityCb(livox_status status, uint8_t handle, DeviceParameterResponse *response, void *clent_data) { LdsLidar *lds_lidar = static_cast<LdsLidar *>(clent_data); if (handle >= kMaxLidarCount) { return; } LidarDevice *p_lidar = &(lds_lidar->lidars_[handle]); if (status == kStatusSuccess) { p_lidar->config.set_bits &= ~((uint32_t)(kConfigSetHighSensitivity)); printf("Set high sensitivity success!\n"); lock_guard<mutex> lock(lds_lidar->config_mutex_); if (!p_lidar->config.set_bits) { LidarStartSampling(handle, StartSampleCb, lds_lidar); p_lidar->connect_state = kConnectStateSampling; }; } else { if (p_lidar->config.enable_high_sensitivity) { LidarEnableHighSensitivity(handle, SetHighSensitivityCb, g_lds_ldiar); } else { LidarDisableHighSensitivity(handle, SetHighSensitivityCb, g_lds_ldiar); } printf("Set high sensitivity fail, try again!\n"); } } /** Callback function of starting sampling. */ void LdsLidar::StartSampleCb(livox_status status, uint8_t handle, uint8_t response, void *clent_data) { LdsLidar *lds_lidar = static_cast<LdsLidar *>(clent_data); if (handle >= kMaxLidarCount) { return; } LidarDevice *p_lidar = &(lds_lidar->lidars_[handle]); if (status == kStatusSuccess) { if (response != 0) { p_lidar->connect_state = kConnectStateOn; printf("Lidar start sample fail : state[%d] handle[%d] res[%d]\n", status, handle, response); } else { printf("Lidar start sample success\n"); } } else if (status == kStatusTimeout) { p_lidar->connect_state = kConnectStateOn; printf("Lidar start sample timeout : state[%d] handle[%d] res[%d]\n", status, handle, response); } } /** Callback function of stopping sampling. */ void LdsLidar::StopSampleCb(livox_status status, uint8_t handle, uint8_t response, void *clent_data) {} void LdsLidar::SetRmcSyncTimeCb(livox_status status, uint8_t handle, uint8_t response, void *client_data) { if (handle >= kMaxLidarCount) { return; } printf("Set lidar[%d] sync time status[%d] response[%d]\n", handle, status, response); } void LdsLidar::ReceiveSyncTimeCallback(const char *rmc, uint32_t rmc_length, void *client_data) { LdsLidar *lds_lidar = static_cast<LdsLidar *>(client_data); // std::unique_lock<std::mutex> lock(mtx); LidarDevice *p_lidar = nullptr; for (uint8_t handle = 0; handle < kMaxLidarCount; handle++) { p_lidar = &(lds_lidar->lidars_[handle]); if (p_lidar->connect_state == kConnectStateSampling && p_lidar->info.state == kLidarStateNormal) { livox_status status = LidarSetRmcSyncTime(handle, rmc, rmc_length, SetRmcSyncTimeCb, lds_lidar); if (status != kStatusSuccess) { printf("Set GPRMC synchronization time error code: %d.\n", status); } } } } /** Add broadcast code to whitelist */ int LdsLidar::AddBroadcastCodeToWhitelist(const char *broadcast_code) { if (!broadcast_code || (strlen(broadcast_code) > kBroadcastCodeSize) || (whitelist_count_ >= kMaxLidarCount)) { return -1; } if (LdsLidar::IsBroadcastCodeExistInWhitelist(broadcast_code)) { printf("%s is alrealy exist!\n", broadcast_code); return -1; } strcpy(broadcast_code_whitelist_[whitelist_count_], broadcast_code); ++whitelist_count_; return 0; } bool LdsLidar::IsBroadcastCodeExistInWhitelist(const char *broadcast_code) { if (!broadcast_code) { return false; } for (uint32_t i = 0; i < whitelist_count_; i++) { if (strncmp(broadcast_code, broadcast_code_whitelist_[i], kBroadcastCodeSize) == 0) { return true; } } return false; } int LdsLidar::ParseTimesyncConfig(rapidjson::Document &doc) { do { if (!doc.HasMember("timesync_config") || !doc["timesync_config"].IsObject()) break; const rapidjson::Value &object = doc["timesync_config"]; if (!object.IsObject()) break; if (!object.HasMember("enable_timesync") || !object["enable_timesync"].IsBool()) break; enable_timesync_ = object["enable_timesync"].GetBool(); if (!object.HasMember("device_name") || !object["device_name"].IsString()) break; std::string device_name = object["device_name"].GetString(); std::strncpy(timesync_config_.dev_config.name, device_name.c_str(), sizeof(timesync_config_.dev_config.name)); if (!object.HasMember("comm_device_type") || !object["comm_device_type"].IsInt()) break; timesync_config_.dev_config.type = object["comm_device_type"].GetInt(); if (timesync_config_.dev_config.type == kCommDevUart) { if (!object.HasMember("baudrate_index") || !object["baudrate_index"].IsInt()) break; timesync_config_.dev_config.config.uart.baudrate = object["baudrate_index"].GetInt(); if (!object.HasMember("parity_index") || !object["parity_index"].IsInt()) break; timesync_config_.dev_config.config.uart.parity = object["parity_index"].GetInt(); } if (enable_timesync_) { printf("Enable timesync : \n"); if (timesync_config_.dev_config.type == kCommDevUart) { printf("Uart[%s],baudrate index[%d],parity index[%d]\n", timesync_config_.dev_config.name, timesync_config_.dev_config.config.uart.baudrate, timesync_config_.dev_config.config.uart.parity); } } else { printf("Disable timesync\n"); } return 0; } while (0); return -1; } /** Config file process */ int LdsLidar::ParseConfigFile(const char *pathname) { FILE *raw_file = std::fopen(pathname, "rb"); if (!raw_file) { printf("Open json config file fail!\n"); return -1; } char read_buffer[32768]; rapidjson::FileReadStream config_file(raw_file, read_buffer, sizeof(read_buffer)); rapidjson::Document doc; if (!doc.ParseStream(config_file).HasParseError()) { if (doc.HasMember("lidar_config") && doc["lidar_config"].IsArray()) { const rapidjson::Value &array = doc["lidar_config"]; size_t len = array.Size(); for (size_t i = 0; i < len; i++) { const rapidjson::Value &object = array[i]; if (object.IsObject()) { UserRawConfig config = {0}; memset(&config, 0, sizeof(config)); if (object.HasMember("broadcast_code") && object["broadcast_code"].IsString()) { std::string broadcast_code = object["broadcast_code"].GetString(); std::strncpy(config.broadcast_code, broadcast_code.c_str(), sizeof(config.broadcast_code)); } else { printf("User config file parse error\n"); continue; } if (object.HasMember("enable_connect") && object["enable_connect"].IsBool()) { config.enable_connect = object["enable_connect"].GetBool(); } if (object.HasMember("enable_fan") && object["enable_fan"].IsBool()) { config.enable_fan = object["enable_fan"].GetBool(); } if (object.HasMember("return_mode") && object["return_mode"].IsInt()) { config.return_mode = object["return_mode"].GetInt(); } if (object.HasMember("coordinate") && object["coordinate"].IsInt()) { config.coordinate = object["coordinate"].GetInt(); } if (object.HasMember("imu_rate") && object["imu_rate"].IsInt()) { config.imu_rate = object["imu_rate"].GetInt(); } if (object.HasMember("extrinsic_parameter_source") && object["extrinsic_parameter_source"].IsInt()) { config.extrinsic_parameter_source = object["extrinsic_parameter_source"].GetInt(); } if (object.HasMember("enable_high_sensitivity") && object["enable_high_sensitivity"].GetBool()) { config.enable_high_sensitivity = object["enable_high_sensitivity"].GetBool(); } printf("broadcast code[%s] : %d %d %d %d %d %d\n", config.broadcast_code, config.enable_connect, config.enable_fan, config.return_mode, config.coordinate, config.imu_rate, config.extrinsic_parameter_source); if (config.enable_connect) { if (!AddBroadcastCodeToWhitelist(config.broadcast_code)) { if (AddRawUserConfig(config)) { printf("Raw config is already exist : %s \n", config.broadcast_code); } } } } } } if (ParseTimesyncConfig(doc)) { printf("Parse timesync config fail\n"); enable_timesync_ = false; } } else { printf("User config file parse error[%d]\n", doc.ParseStream(config_file).HasParseError()); } std::fclose(raw_file); return 0; } int LdsLidar::AddRawUserConfig(UserRawConfig &config) { if (IsExistInRawConfig(config.broadcast_code)) { return -1; } raw_config_.push_back(config); printf("Add Raw user config : %s \n", config.broadcast_code); return 0; } bool LdsLidar::IsExistInRawConfig(const char *broadcast_code) { if (broadcast_code == nullptr) { return false; } for (auto ite_config : raw_config_) { if (strncmp(ite_config.broadcast_code, broadcast_code, kBroadcastCodeSize) == 0) { return true; } } return false; } int LdsLidar::GetRawConfig(const char *broadcast_code, UserRawConfig &config) { if (broadcast_code == nullptr) { return -1; } for (auto ite_config : raw_config_) { if (strncmp(ite_config.broadcast_code, broadcast_code, kBroadcastCodeSize) == 0) { config.enable_fan = ite_config.enable_fan; config.return_mode = ite_config.return_mode; config.coordinate = ite_config.coordinate; config.imu_rate = ite_config.imu_rate; config.extrinsic_parameter_source = ite_config.extrinsic_parameter_source; config.enable_high_sensitivity = ite_config.enable_high_sensitivity; return 0; } } return -1; } } // namespace livox_ros
6a6b4e99bcdd7169d8db5997359d5024aab4f8b9
eecf0603c8336a49d35ca87f12ad7b2769115422
/QOSS-V1.0/Calculation/Gaussian_Beam_Circular.cpp
38769f8741435cb276b1fd4b3f5aed16411506c1
[]
no_license
Devil-ly/QOSS-V1.0
e90fab43f9a69fdd16f5cbfc5f95db83fa09e656
73e15f398be7567e187cb2814415a2dd23caaf63
refs/heads/master
2021-05-06T19:12:02.890104
2018-05-26T07:49:56
2018-05-26T07:49:56
112,161,447
2
4
null
2018-04-12T06:13:32
2017-11-27T07:15:17
C++
GB18030
C++
false
false
1,768
cpp
#include "Gaussian_Beam_Circular.h" //返回传播z长度后的高斯波束W值 double Gauss_Omega_Circular(double frequency0, double w0, double z0) { double lamda = C_Speed / frequency0; double w = w0*pow(1.0 + pow((lamda*z0 / Pi / w0 / w0), 2), 0.5); return w; } //返回圆高斯波束在P(x,y,z)的复数主极化值 complex<double> Gauss_E_Circular(double frequency0, double w0, Vector3 P) { double x0 = P.x; double y0 = P.y; double z0 = P.z; double lamda = C_Speed / frequency0; double k = 2 * Pi / lamda; //由于公式中的R,即曲率半径公式中存在z为分母的情况,为了保险起见改为定义R1=1/R double R1 = z0 / (z0*z0 + pow(Pi*w0*w0 / lamda, 2)); double phi0 = atan(lamda*z0 / Pi / w0 / w0); complex <double> j(0, 1);//定义虚数单位j complex<double> E = pow(2.0 / Pi / pow(Gauss_Omega_Circular(frequency0, w0, z0), 2), 0.5) *exp(-(x0*x0 + y0*y0) / pow(Gauss_Omega_Circular(frequency0, w0, z0), 2)) *exp(-j*k*z0) *exp(-j*k*(x0*x0 + y0*y0) / 2.0 *R1) *exp(j*phi0); //公式来源:《Gaussian Beam Quasi-optical Propagation and Applications》P25 return E; } //返回圆高斯波束在P(x,y,z)的弧度形式的未折叠相位值 double Gauss_Phase_Circular(double frequency0, double w0, Vector3 P) { double x0 = P.x; double y0 = P.y; double z0 = P.z; double lamda = C_Speed / frequency0; double k = 2 * Pi / lamda; //由于公式中的R,即曲率半径公式中存在z为分母的情况,为了保险起见改为定义R1=1/R double R1 = z0 / (z0*z0 + pow(Pi*w0*w0 / lamda, 2)); double phi0 = atan(lamda*z0 / Pi / w0 / w0); double Phase = -k*z0 - k*(x0*x0 + y0*y0) / 2.0 *R1 + phi0; //公式来源:《Gaussian Beam Quasi-optical Propagation and Applications》P25 return Phase; }
cdb0ddcd1e67cc22b4f2fb2024fdc04e54c3603e
0ad0cb2fcadd104f8bd7ad2e10324904335f107c
/Sample_GL3_2D (copy).cpp
a14408ba9bf5ce8fb8cce6f182d6d80c9a65a17b
[]
no_license
onkarverma975/Blox-Puzzle
c34418d4454b042f034f051adf37bc64d35a0600
592869c5a0b1cf278d8943cc3c50275a9efc460d
refs/heads/master
2021-01-21T10:25:58.174906
2018-03-23T20:03:38
2018-03-23T20:03:38
83,428,278
0
0
null
null
null
null
UTF-8
C++
false
false
54,229
cpp
#include <iostream> #include <cmath> #include <fstream> #include <vector> #include <map> #include <cstdlib> #include <GL/glew.h> #include <GL/gl.h> #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/matrix_transform.hpp> // #include <glad/glad.h> #include <FTGL/ftgl.h> #include <GLFW/glfw3.h> #include <SOIL/SOIL.h> using namespace std; struct VAO { GLuint VertexArrayID; GLuint VertexBuffer; GLuint ColorBuffer; GLenum PrimitiveMode; GLenum FillMode; int NumVertices; }; typedef struct VAO VAO; struct COLOR{ float r,g,b; }; typedef struct COLOR COLOR; struct Sprite{ glm::vec3 pos; glm::vec3 back; glm::vec3 scale; int speed; int dr; glm::vec3 ori; glm::vec3 theta; glm::vec3 limit; COLOR color; bool active; int status; bool choose; bool hover; VAO* object; VAO* line; string name; }; typedef struct Sprite Sprite; struct GLMatrices { glm::mat4 projection; glm::mat4 model; glm::mat4 view; GLuint MatrixID; } Matrices; typedef struct switch_struct{ bool used; glm::vec3 place; vector<glm::vec3>locations; }switch_struct; typedef struct cross_struct{ bool used; glm::vec3 place; glm::vec3 other; }cross_struct; typedef struct Level_struct{ int levelMatrix[10][10]; glm::vec3 cube0_pos; glm::vec3 cube1_pos; vector<switch_struct>switches; vector<cross_struct>crosses; }Level_struct; int do_rot; GLuint programID; double last_update_time, current_time; float rectangle_rotation = 0; /* Function to load Shaders - Use it as it is */ GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path) { // Create the shaders GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); // Read the Vertex Shader code from the file std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); if(VertexShaderStream.is_open()) { std::string Line = ""; while(getline(VertexShaderStream, Line)) VertexShaderCode += "\n" + Line; VertexShaderStream.close(); } // Read the Fragment Shader code from the file std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); if(FragmentShaderStream.is_open()){ std::string Line = ""; while(getline(FragmentShaderStream, Line)) FragmentShaderCode += "\n" + Line; FragmentShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; // Compile Vertex Shader // printf("Compiling shader : %s\n", vertex_file_path); char const * VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL); glCompileShader(VertexShaderID); // Check Vertex Shader glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> VertexShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); // fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]); // Compile Fragment Shader // printf("Compiling shader : %s\n", fragment_file_path); char const * FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL); glCompileShader(FragmentShaderID); // Check Fragment Shader glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> FragmentShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); // fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]); // Link the program // fprintf(stdout, "Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> ProgramErrorMessage( max(InfoLogLength, int(1)) ); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); // fprintf(stdout, "%s\n", &ProgramErrorMessage[0]); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } static void error_callback(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } void quit(GLFWwindow *window) { glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } void initGLEW(void){ glewExperimental = GL_TRUE; if(glewInit()!=GLEW_OK){ fprintf(stderr,"Glew failed to initialize : %s\n", glewGetErrorString(glewInit())); } if(!GLEW_VERSION_3_3) fprintf(stderr, "3.3 version not available\n"); } /* Generate VAO, VBOs and return VAO handle */ struct VAO* create3DObject (GLenum primitive_mode, int numVertices, const GLfloat* vertex_buffer_data, const GLfloat* color_buffer_data, GLenum fill_mode=GL_FILL) { struct VAO* vao = new struct VAO; vao->PrimitiveMode = primitive_mode; vao->NumVertices = numVertices; vao->FillMode = fill_mode; // Create Vertex Array Object // Should be done after CreateWindow and before any other GL calls glGenVertexArrays(1, &(vao->VertexArrayID)); // VAO glGenBuffers (1, &(vao->VertexBuffer)); // VBO - vertices glGenBuffers (1, &(vao->ColorBuffer)); // VBO - colors glBindVertexArray (vao->VertexArrayID); // Bind the VAO glBindBuffer (GL_ARRAY_BUFFER, vao->VertexBuffer); // Bind the VBO vertices glBufferData (GL_ARRAY_BUFFER, 3*numVertices*sizeof(GLfloat), vertex_buffer_data, GL_STATIC_DRAW); // Copy the vertices into VBO glVertexAttribPointer( 0, // attribute 0. Vertices 3, // size (x,y,z) GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glBindBuffer (GL_ARRAY_BUFFER, vao->ColorBuffer); // Bind the VBO colors glBufferData (GL_ARRAY_BUFFER, 3*numVertices*sizeof(GLfloat), color_buffer_data, GL_STATIC_DRAW); // Copy the vertex colors glVertexAttribPointer( 1, // attribute 1. Color 3, // size (r,g,b) GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); return vao; } /* Generate VAO, VBOs and return VAO handle - Common Color for all vertices */ struct VAO* create3DObject (GLenum primitive_mode, int numVertices, const GLfloat* vertex_buffer_data, const GLfloat red, const GLfloat green, const GLfloat blue, GLenum fill_mode=GL_FILL) { GLfloat* color_buffer_data = new GLfloat [3*numVertices]; for (int i=0; i<numVertices; i++) { color_buffer_data [3*i] = red; color_buffer_data [3*i + 1] = green; color_buffer_data [3*i + 2] = blue; } return create3DObject(primitive_mode, numVertices, vertex_buffer_data, color_buffer_data, fill_mode); } /* Render the VBOs handled by VAO */ void draw3DObject (struct VAO* vao) { // Change the Fill Mode for this object glPolygonMode (GL_FRONT_AND_BACK, vao->FillMode); // Bind the VAO to use glBindVertexArray (vao->VertexArrayID); // Enable Vertex Attribute 0 - 3d Vertices glEnableVertexAttribArray(0); // Bind the VBO to use glBindBuffer(GL_ARRAY_BUFFER, vao->VertexBuffer); // Enable Vertex Attribute 1 - Color glEnableVertexAttribArray(1); // Bind the VBO to use glBindBuffer(GL_ARRAY_BUFFER, vao->ColorBuffer); // Draw the geometry ! glDrawArrays(vao->PrimitiveMode, 0, vao->NumVertices); // Starting from vertex 0; 3 vertices total -> 1 triangle } /************************** * Customizable functions * **************************/ Sprite floor_grey; Sprite floor_orange; Sprite floor_black; Sprite floor_green; Sprite floor_red; Sprite rectangle_line; Sprite cube[2]; Sprite camera; vector<Level_struct>levels; int score=0; int timer[10]; int current_level; int dom; int rec; int mode; int toppling; int merged; int chosen; float rectangle_rot_dir = 1; bool rectangle_rot_status = true; int dim=10; bool paused; int boardMatrix[10][10]; int falling =0; float camera_rotation_angle_x = 90; float camera_rotation_angle_y = 90; int moves[10]={0}; bool right_move; map <string, bool> buttons; void updateScore(){ score+=(int)(1000000/(moves[current_level]*timer[current_level])); } void Initialize(){ if(right_move){ updateScore(); cout << "Score : "<<score<<endl; current_level++; right_move=false; } dom=0; cube[dom].pos = levels[current_level].cube0_pos; cube[1-dom].pos = levels[current_level].cube1_pos; for(int i=0;i<dim;i++){ for(int j=0;j<dim;j++){ boardMatrix[i][j] = levels[current_level].levelMatrix[i][j]; } } for(vector<switch_struct>::iterator it=levels[current_level].switches.begin();it<levels[current_level].switches.end();it++) { it->used=false; boardMatrix[(int)it->place.x][(int)it->place.y]=8; } for(vector<cross_struct>::iterator it=levels[current_level].crosses.begin();it<levels[current_level].crosses.end();it++) { boardMatrix[(int)it->place.x][(int)it->place.y]=7; } merged=1; toppling=0; falling=0; timer[current_level]=1; cube[0].theta.x=cube[0].ori.x=-45; cube[0].theta.y=cube[0].ori.y=-45; cube[1].theta.x=cube[1].ori.x=-45; cube[1].theta.y=cube[1].ori.y=-45; paused=false; camera.pos = glm::vec3(0,0,0); } /* Executed when a regular key is pressed/released/held-down */ /* Prefered for Keyboard events */ int NorthDOM(){ if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y != cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 1 if(cube[0].pos.y > cube[1].pos.y) return 0; // fore most is dom else return 1; } if(cube[0].pos.x != cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 2 if(cube[0].pos.x > cube[1].pos.x) return 0; // both are dom else return 1; } if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z != cube[1].pos.z){ //case 3 if(cube[0].pos.z < cube[1].pos.z) return 0; // lower is dom else return 1; } } int NorthMode(){ if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y != cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 1 return 1; } if(cube[0].pos.x != cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 2 return 2; } if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z != cube[1].pos.z){ //case 3 return 3; } } int SouthDOM(){ if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y != cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 1 if(cube[0].pos.y < cube[1].pos.y) return 0; // back most is dom else return 1; } if(cube[0].pos.x != cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 2 if(cube[0].pos.x > cube[1].pos.x) return 0; // both are dom else return 1; } if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z != cube[1].pos.z){ //case 3 if(cube[0].pos.z < cube[1].pos.z) return 0; // lower is dom else return 1; } } int SouthMode(){ if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y != cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 1 return 3; } if(cube[0].pos.x != cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 2 return 2; } if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z != cube[1].pos.z){ //case 3 return 1; } } int EastDOM(){ if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y != cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 1 if(cube[0].pos.y > cube[1].pos.y) return 0; else return 1;//both are dom } if(cube[0].pos.x != cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 2 if(cube[0].pos.x > cube[1].pos.x) return 0; // fore x is dom else return 1; } if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z != cube[1].pos.z){ //case 3 if(cube[0].pos.z < cube[1].pos.z) return 0; // lower is dom else return 1; } } int EastMode(){ if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y != cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 1 return 2; } if(cube[0].pos.x != cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 2 return 1; } if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z != cube[1].pos.z){ //case 3 return 3; } } int WestDOM(){ if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y != cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 1 if(cube[0].pos.y > cube[1].pos.y) return 0; else return 1;//both are dom } if(cube[0].pos.x != cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 2 if(cube[0].pos.x < cube[1].pos.x) return 0; // less x is dom else return 1; } if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z != cube[1].pos.z){ //case 3 if(cube[0].pos.z < cube[1].pos.z) return 0; // lower is dom else return 1; } } int WestMode(){ if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y != cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 1 return 2; } if(cube[0].pos.x != cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z == cube[1].pos.z){ //case 2 return 3; } if(cube[0].pos.x == cube[1].pos.x && cube[0].pos.y == cube[1].pos.y && cube[0].pos.z != cube[1].pos.z){ //case 3 return 1; } } void CuboidToppleNorth(){ cube[dom].pos = glm::vec3( cube[dom].back.x, cube[dom].back.y + cube[dom].scale.y + cube[dom].scale.z*sin(cube[dom].theta.y*M_PI/180.0f)*sqrt(2), floor_grey.scale.z + cube[dom].scale.z*cos(cube[dom].theta.y*M_PI/180.0f)*sqrt(2) ); float dist; if(mode == 1) { cube[rec].pos = glm::vec3( cube[dom].back.x, cube[dom].pos.y - cos(45+cube[dom].theta.y*M_PI/180.0f), cube[dom].pos.z + sin(45+cube[dom].theta.y*M_PI/180.0f) ); } else if (mode ==2){ cube[rec].pos = glm::vec3( cube[rec].back.x, cube[dom].pos.y , cube[dom].pos.z ); } else if (mode ==3){ cube[rec].pos = glm::vec3( cube[dom].back.x, cube[dom].pos.y + sin(45+cube[dom].theta.y*M_PI/180.0f), cube[dom].pos.z + cos(45+cube[dom].theta.y*M_PI/180.0f) ); } cube[dom].theta.y += cube[dom].dr; cube[rec].theta.y += cube[rec].dr; if(cube[dom].theta.y >= cube[dom].limit.y){ if(mode==1){ cube[rec].pos = glm::vec3(cube[rec].back.x,cube[rec].back.y+2,cube[rec].back.z+1); } else if(mode==2){ cube[rec].pos = glm::vec3(cube[rec].back.x,cube[rec].back.y+1,cube[rec].back.z); } else if(mode==3){ cube[rec].pos = glm::vec3(cube[rec].back.x,cube[rec].back.y+2,cube[rec].back.z-1); } cube[dom].pos = glm::vec3(cube[dom].back.x,cube[dom].back.y+1,cube[dom].back.z); cube[dom].theta.y=cube[rec].limit.y; cube[rec].theta.y=cube[rec].limit.y; toppling=0; } } void CuboidToppleSouth(){ cube[dom].pos = glm::vec3( cube[dom].back.x, cube[dom].back.y - cube[dom].scale.y + cube[dom].scale.z*sin(cube[dom].theta.y*M_PI/180.0f)*sqrt(2), floor_grey.scale.z + cube[dom].scale.z*cos(cube[dom].theta.y*M_PI/180.0f)*sqrt(2) ); if(mode == 1) { cube[rec].pos = glm::vec3( cube[dom].back.x, cube[dom].pos.y - cos(45+cube[dom].theta.y*M_PI/180.0f), cube[dom].pos.z + sin(45+cube[dom].theta.y*M_PI/180.0f) ); } else if (mode ==2){ cube[rec].pos = glm::vec3( cube[rec].back.x, cube[dom].pos.y, cube[dom].pos.z ); } else if (mode ==3){ cube[rec].pos = glm::vec3( cube[dom].back.x, cube[dom].pos.y + sin(45+cube[dom].theta.y*M_PI/180.0f), cube[dom].pos.z + cos(45+cube[dom].theta.y*M_PI/180.0f) ); } cube[dom].theta.y += cube[dom].dr; cube[rec].theta.y += cube[rec].dr; if(cube[dom].theta.y <= cube[dom].limit.y){ if(mode==1){ cube[rec].pos = glm::vec3(cube[rec].back.x,cube[rec].back.y-2,cube[rec].back.z-1); } else if(mode==2){ cube[rec].pos = glm::vec3(cube[rec].back.x,cube[rec].back.y-1,cube[rec].back.z); } else if(mode==3){ cube[rec].pos = glm::vec3(cube[rec].back.x,cube[rec].back.y-2,cube[rec].back.z+1); } cube[dom].pos = glm::vec3(cube[dom].back.x,cube[dom].back.y-1,cube[dom].back.z); toppling=0; cube[dom].theta.y=-45; cube[rec].theta.y=-45; } } void CuboidToppleWest(){ cube[dom].pos = glm::vec3( cube[dom].back.x - cube[dom].scale.y + cube[dom].scale.z*sin(cube[dom].theta.x*M_PI/180.0f)*sqrt(2), cube[dom].back.y, floor_grey.scale.z + cube[dom].scale.z*cos(cube[dom].theta.x*M_PI/180.0f)*sqrt(2) ); if(mode == 1) { cube[rec].pos = glm::vec3( cube[dom].pos.x - cos(45+cube[dom].theta.x*M_PI/180.0f), cube[dom].pos.y, cube[dom].pos.z + sin(45+cube[dom].theta.x*M_PI/180.0f) ); } else if (mode ==2){ cube[rec].pos = glm::vec3( cube[dom].pos.x, cube[rec].pos.y, cube[dom].pos.z ); } else if (mode ==3){ cube[rec].pos = glm::vec3( cube[dom].pos.x + sin(45+cube[dom].theta.x*M_PI/180.0f), cube[dom].pos.y, cube[dom].pos.z + cos(45+cube[dom].theta.x*M_PI/180.0f) ); } cube[dom].theta.x += cube[dom].dr; cube[rec].theta.x += cube[rec].dr; if(cube[dom].theta.x <= cube[dom].limit.x){ if(mode==1){ cube[rec].pos = glm::vec3(cube[rec].back.x-2,cube[rec].back.y,cube[rec].back.z-1); } else if(mode==2){ cube[rec].pos = glm::vec3(cube[rec].back.x-1,cube[rec].back.y,cube[rec].back.z); } else if(mode==3){ cube[rec].pos = glm::vec3(cube[rec].back.x-2,cube[rec].back.y,cube[rec].back.z+1); } cube[dom].pos = glm::vec3(cube[dom].back.x-1,cube[dom].back.y,cube[dom].back.z); cube[dom].theta.x=-45; cube[rec].theta.x=-45; toppling=0; } } void CuboidToppleEast(){ cube[dom].pos = glm::vec3( cube[dom].back.x + cube[dom].scale.y + cube[dom].scale.z*sin(cube[dom].theta.x*M_PI/180.0f)*sqrt(2), cube[dom].back.y, floor_grey.scale.z + cube[dom].scale.z*cos(cube[dom].theta.x*M_PI/180.0f)*sqrt(2) ); if(mode == 1) { cube[rec].pos = glm::vec3( cube[dom].pos.x - cos(45+cube[dom].theta.x*M_PI/180.0f), cube[dom].back.y, cube[dom].pos.z + sin(45+cube[dom].theta.x*M_PI/180.0f) ); } else if (mode ==2){ cube[rec].pos = glm::vec3( cube[dom].pos.x , cube[rec].pos.y, cube[dom].pos.z ); } else if (mode ==3){ cube[rec].pos = glm::vec3( cube[dom].pos.x + sin(45+cube[dom].theta.x*M_PI/180.0f), cube[dom].back.y, cube[dom].pos.z + cos(45+cube[dom].theta.x*M_PI/180.0f) ); } cube[dom].theta.x += cube[dom].dr; cube[rec].theta.x += cube[rec].dr; if(cube[dom].theta.x >= cube[dom].limit.x){ if(mode==1){ cube[rec].pos = glm::vec3(cube[rec].back.x+2,cube[rec].back.y,cube[rec].back.z+1); } else if(mode==2){ cube[rec].pos = glm::vec3(cube[rec].back.x+1,cube[rec].back.y,cube[rec].back.z); } else if(mode==3){ cube[rec].pos = glm::vec3(cube[rec].back.x+2,cube[rec].back.y,cube[rec].back.z-1); } cube[dom].pos = glm::vec3(cube[dom].back.x+1,cube[dom].back.y,cube[dom].back.z); cube[dom].theta.x=-cube[dom].limit.x; cube[rec].theta.x=-cube[rec].limit.x; toppling=0; } } void CubeToppleNorth(){ cube[dom].pos = glm::vec3( cube[dom].back.x, cube[dom].back.y + cube[dom].scale.y + cube[dom].scale.z*sin(cube[dom].theta.y*M_PI/180.0f)*sqrt(2), floor_grey.scale.z + cube[dom].scale.z*cos(cube[dom].theta.y*M_PI/180.0f)*sqrt(2) ); cube[dom].theta.y += cube[dom].dr; if(cube[dom].theta.y >= cube[dom].limit.y){ cube[dom].pos = glm::vec3(cube[dom].back.x,cube[dom].back.y+1,cube[dom].back.z); cube[dom].theta.y=cube[dom].limit.y; toppling=0; } } void CubeToppleSouth(){ cube[dom].pos = glm::vec3( cube[dom].back.x, cube[dom].back.y - cube[dom].scale.y + cube[dom].scale.z*sin(cube[dom].theta.y*M_PI/180.0f)*sqrt(2), floor_grey.scale.z + cube[dom].scale.z*cos(cube[dom].theta.y*M_PI/180.0f)*sqrt(2) ); cube[dom].theta.y += cube[dom].dr; if(cube[dom].theta.y <= cube[dom].limit.y){ cube[dom].pos = glm::vec3(cube[dom].back.x,cube[dom].back.y-1,cube[dom].back.z); toppling=0; cube[dom].theta.y=-45; } } void CubeToppleWest(){ cube[dom].pos = glm::vec3( cube[dom].back.x - cube[dom].scale.y + cube[dom].scale.z*sin(cube[dom].theta.x*M_PI/180.0f)*sqrt(2), cube[dom].back.y, floor_grey.scale.z + cube[dom].scale.z*cos(cube[dom].theta.x*M_PI/180.0f)*sqrt(2) ); cube[dom].theta.x += cube[dom].dr; if(cube[dom].theta.x <= cube[dom].limit.x){ cube[dom].pos = glm::vec3(cube[dom].back.x-1,cube[dom].back.y,cube[dom].back.z); cube[dom].theta.x=-45; toppling=0; } } void CubeToppleEast(){ cube[dom].pos = glm::vec3( cube[dom].back.x + cube[dom].scale.y + cube[dom].scale.z*sin(cube[dom].theta.x*M_PI/180.0f)*sqrt(2), cube[dom].back.y, floor_grey.scale.z + cube[dom].scale.z*cos(cube[dom].theta.x*M_PI/180.0f)*sqrt(2) ); cube[dom].theta.x += cube[dom].dr; if(cube[dom].theta.x >= cube[dom].limit.x){ cube[dom].pos = glm::vec3(cube[dom].back.x+1,cube[dom].back.y,cube[dom].back.z); cube[dom].theta.x=-cube[dom].limit.x; toppling=0; } } void CubeActivateTopple(int dir){ if(toppling !=0) return; moves[current_level]++; system("aplay -q ./sounds/button.wav &"); if(dir==1){ if(merged==1){ dom = NorthDOM(); rec = 1 - dom; mode = NorthMode(); toppling = dir; cube[dom].back = cube[dom].pos; cube[rec].back = cube[rec].pos; cube[dom].dr = cube[dom].speed; cube[rec].dr = cube[rec].speed; cube[dom].theta.y = cube[dom].ori.y = -45; cube[dom].limit.y = 90 + cube[dom].theta.y ; cube[rec].limit.y = 90 + cube[rec].theta.y ; } else{ dom = chosen; rec = 1 - dom; toppling = dir; cube[dom].back = cube[dom].pos; cube[dom].dr = cube[dom].speed; cube[dom].theta.y = cube[dom].ori.y = -45; cube[dom].limit.y = 90 + cube[dom].theta.y ; } } else if(dir==2){ if(merged==1){ dom = SouthDOM(); rec = 1 - dom; mode = SouthMode(); toppling = dir; cube[dom].back = cube[dom].pos; cube[rec].back = cube[rec].pos; cube[dom].dr = -cube[dom].speed; cube[rec].dr = -cube[rec].speed; cube[dom].theta.y = cube[dom].ori.y = 45; cube[dom].limit.y = -90 + cube[dom].theta.y ; cube[rec].limit.y = -90 + cube[rec].theta.y ; } else{ toppling = dir; dom = chosen; rec = 1 - dom; cube[dom].back = cube[dom].pos; cube[dom].dr = -cube[dom].speed; cube[dom].theta.y = cube[dom].ori.y = 45; cube[dom].limit.y = -90 + cube[dom].theta.y ; } } else if(dir==3){ if(merged==1){ dom = WestDOM(); rec = 1 - dom; mode = WestMode(); toppling = dir; cube[dom].back = cube[dom].pos; cube[rec].back = cube[rec].pos; cube[dom].dr = -cube[dom].speed; cube[rec].dr = -cube[rec].speed; cube[dom].theta.x = cube[dom].ori.x = 45; cube[dom].limit.x = -90 + cube[dom].theta.x ; cube[rec].limit.x = -90 + cube[rec].theta.x ; } else{ dom = chosen; rec = 1 - dom; toppling = dir; cube[dom].back = cube[dom].pos; cube[dom].dr = -cube[dom].speed; cube[dom].theta.x = cube[dom].ori.x = 45; cube[dom].limit.x = -90 + cube[dom].theta.x ; } } else if(dir==4){ if(merged==1){ dom = EastDOM(); rec = 1 - dom; mode = EastMode(); toppling=dir; cube[dom].back = cube[dom].pos; cube[rec].back = cube[rec].pos; cube[dom].dr = cube[dom].speed; cube[rec].dr = cube[rec].speed; cube[dom].theta.x = cube[dom].ori.x = -45; cube[dom].limit.x = 90 + cube[dom].theta.x ; cube[rec].limit.x = 90 + cube[rec].theta.x ; } else{ dom = chosen; rec = 1 - dom; toppling=dir; cube[dom].back = cube[dom].pos; cube[dom].dr = cube[dom].speed; cube[dom].theta.x = cube[dom].ori.x = -45; cube[dom].limit.x = 90 + cube[dom].theta.x ; } } } /* Executed for character input (like in text boxes) */ /* Executed when a mouse button is pressed/released */ void keyboard (GLFWwindow* window, int key, int scancode, int action, int mods) { // Function is called first on GLFW_PRESS. if (action == GLFW_RELEASE) { switch (key) { case GLFW_KEY_LEFT: buttons["LEFT"]=false; break; case GLFW_KEY_RIGHT: buttons["RIGHT"]=false; break; case GLFW_KEY_UP: buttons["UP"]=false; break; case GLFW_KEY_DOWN: buttons["DOWN"]=false; break; case GLFW_KEY_W: buttons["W"]=false; break; case GLFW_KEY_S: buttons["S"]=false; break; case GLFW_KEY_A: buttons["A"]=false; break; case GLFW_KEY_D: buttons["D"]=false; break; case GLFW_KEY_SPACE: chosen = 1-chosen; // do something .. break; default: break; } } else if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_ESCAPE: quit(window); break; if(buttons["LEFT"]) // CubeActivateTopple(3); // if(buttons["RIGHT"]) // CubeActivateTopple(4); // if(buttons["UP"]) // CubeActivateTopple(1); // if(buttons["DOWN"]) // CubeActivateTopple(2); case GLFW_KEY_LEFT: CubeActivateTopple(3); // buttons["LEFT"]=true; break; case GLFW_KEY_RIGHT: CubeActivateTopple(4); // buttons["RIGHT"]=true; break; case GLFW_KEY_UP: CubeActivateTopple(1); // buttons["UP"]=true; break; case GLFW_KEY_DOWN: CubeActivateTopple(2); // buttons["DOWN"]=true; break; case GLFW_KEY_W: buttons["W"]=true; break; case GLFW_KEY_S: buttons["S"]=true; break; case GLFW_KEY_A: buttons["A"]=true; break; case GLFW_KEY_D: buttons["D"]=true; break; default: break; } } } void keyboardChar (GLFWwindow* window, unsigned int key) { switch (key) { case 'Q': case 'q': quit(window); break; case 'w': camera_rotation_angle_y+=10; break; case 's': camera_rotation_angle_y-=10; break; case 'a': camera_rotation_angle_x-=10; break; case 'd': camera_rotation_angle_x+=10; break; case 'j': camera.pos.x-=0.1; break; case 'l': camera.pos.x+=0.1; break; case 'i': camera.pos.z+=0.1; break; case 'k': camera.pos.z-=0.1; break; case 'p': paused=!paused; break; case 'r': Initialize(); break; case 'g': break; case ' ': break; default: break; } } void mouseButton (GLFWwindow* window, int button, int action, int mods) { switch (button) { case GLFW_MOUSE_BUTTON_RIGHT: if (action == GLFW_RELEASE) { rectangle_rot_dir *= -1; } break; default: break; } } /* Executed when window is resized to 'width' and 'height' */ /* Modify the bounds of the screen here in glm::ortho or Field of View in glm::Perspective */ void reshapeWindow (GLFWwindow* window, int width, int height) { int fbwidth=width, fbheight=height; glfwGetFramebufferSize(window, &fbwidth, &fbheight); GLfloat fov = M_PI/2; // sets the viewport of openGL renderer glViewport (0, 0, (GLsizei) fbwidth, (GLsizei) fbheight); // Store the projection matrix in a variable for future use // Perspective projection for 3D views Matrices.projection = glm::perspective(fov, (GLfloat) fbwidth / (GLfloat) fbheight, 0.1f, 500.0f); // Ortho projection for 2D views //Matrices.projection = glm::ortho(-4.0f, 4.0f, -4.0f, 4.0f, 0.1f, 500.0f); } VAO *rectangle, *cam, *floor_vao, *rectangle_grey, *rectangle_orange, *rectangle_grey_line; // Creates the rectangle object used in this sample code void createRectangle () { floor_grey.pos = floor_orange.pos = glm::vec3(0,0,0); floor_grey.scale = floor_orange.scale = glm::vec3(0.5,0.5,0.1); cube[0].scale = cube[0].scale = glm::vec3(0.5,0.5,0.5); cube[0].pos = cube[0].pos = glm::vec3(0,0,floor_grey.scale.z+cube[0].scale.z); cube[0].speed = 10; cube[1].scale = cube[1].scale = glm::vec3(0.5,0.5,0.5); cube[1].pos = cube[1].pos = glm::vec3(1,0,floor_grey.scale.z+cube[1].scale.z); cube[1].speed = 10; // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data[] = { -1.0f,-1.0f,-1.0f, // triangle 1 : begin -1.0f,-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, // triangle 1 : end 1.0f, 1.0f,-1.0f, // triangle 2 : begin -1.0f,-1.0f,-1.0f, -1.0f, 1.0f,-1.0f, // triangle 2 : end 1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, 1.0f,-1.0f, 1.0f, -1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f }; float grey=(float)112/255; float line=(float)50/255; float b=(float)112/255; COLOR orange,green, red; orange.r=1; orange.g=162.0f/255.0f; orange.b=0; green.r = (float)144/255; green.g = (float)238 /255; green.b = (float)144/255; red.r = (float)1; red.g = (float)0 /255; red.b = (float)0/255; static const GLfloat color_buffer_data_grey[] = { grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey, grey }; static const GLfloat color_buffer_data_green[] = { green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b, green.r, green.g, green.b }; static const GLfloat color_buffer_data_red[] = { red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b, red.r, red.g, red.b }; float black=(float)0/255; static const GLfloat color_buffer_data_black[] = { black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black, black }; static const GLfloat color_buffer_data_orange[] = { orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b, orange.r, orange.g, orange.b }; cube[1].color.r = cube[0].color.r=1; cube[1].color.g = cube[0].color.g=162.0f/255.0f; cube[1].color.b = cube[0].color.b=200.0f/255.0f; static const GLfloat color_buffer_data_cube1[] = { cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b, cube[0].color.r, cube[0].color.g, cube[0].color.b }; static const GLfloat color_buffer_data_line[] = { line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line, line }; // create3DObject creates and returns a handle to a VAO that can be used later floor_grey.object = create3DObject(GL_TRIANGLES, 13*3, vertex_buffer_data, color_buffer_data_grey, GL_FILL); floor_black.object = create3DObject(GL_TRIANGLES, 13*3, vertex_buffer_data, color_buffer_data_black, GL_FILL); floor_red.object = create3DObject(GL_TRIANGLES, 13*3, vertex_buffer_data, color_buffer_data_red, GL_FILL); floor_green.object = create3DObject(GL_TRIANGLES, 13*3, vertex_buffer_data, color_buffer_data_green, GL_FILL); floor_black.line = floor_grey.line = floor_orange.line = cube[1].line =cube[0].line = create3DObject(GL_TRIANGLES, 13*3, vertex_buffer_data, color_buffer_data_line, GL_LINE); floor_orange.object = create3DObject(GL_TRIANGLES, 13*3, vertex_buffer_data, color_buffer_data_orange, GL_FILL); cube[0].object = create3DObject(GL_TRIANGLES, 13*3, vertex_buffer_data, color_buffer_data_cube1, GL_FILL); cube[1].object = create3DObject(GL_TRIANGLES, 13*3, vertex_buffer_data, color_buffer_data_cube1, GL_FILL); } void createCam () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -0.1, 0, 0, 0.1, 0, 0, 0, 0.1, 0, }; static const GLfloat color_buffer_data [] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, }; // create3DObject creates and returns a handle to a VAO that can be used later cam = create3DObject(GL_TRIANGLES, 1*3, vertex_buffer_data, color_buffer_data, GL_LINE); } void createFloor () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -2, -1, 2, 2, -1, 2, -2, -1, -2, -2, -1, -2, 2, -1, 2, 2, -1, -2, }; static const GLfloat color_buffer_data [] = { 0.65, 0.165, 0.165, 0.65, 0.165, 0.165, 0.65, 0.165, 0.165, 0.65, 0.165, 0.165, 0.65, 0.165, 0.165, 0.65, 0.165, 0.165, }; // create3DObject creates and returns a handle to a VAO that can be used later floor_vao = create3DObject(GL_TRIANGLES, 2*3, vertex_buffer_data, color_buffer_data, GL_FILL); } /* Render the scene with openGL */ /* Edit this function according to your assignment */ void draw (GLFWwindow* window, float x, float y, float w, float h, int doM, int doV, int doP) { int fbwidth, fbheight; glfwGetFramebufferSize(window, &fbwidth, &fbheight); glViewport((int)(x*fbwidth), (int)(y*fbheight), (int)(w*fbwidth), (int)(h*fbheight)); // use the loaded shader program // Don't change unless you know what you are doing glUseProgram(programID); // Eye - Location of camera. Don't change unless you are sure!! glm::vec3 eye ( 5*cos(camera_rotation_angle_x*M_PI/180.0f), 5*cos(camera_rotation_angle_y*M_PI/180.0f), 5*sin(camera_rotation_angle_y*M_PI/180.0f) + 5*sin(camera_rotation_angle_x*M_PI/180.0f) ); // Target - Where is the camera looking at. Don't change unless you are sure!! glm::vec3 target (0, 0, 0); // Up - Up vector defines tilt of camera. Don't change unless you are sure!! glm::vec3 up (0, 1, 0); // Compute Camera matrix (view) if(doV) Matrices.view = glm::lookAt(eye, target, up); // Fixed camera for 2D (ortho) in XY plane else Matrices.view = glm::mat4(1.0f); // Compute ViewProject matrix as view/camera might not be changed for this frame (basic scenario) glm::mat4 VP; if (doP) VP = Matrices.projection * Matrices.view; else VP = Matrices.view; glm::mat4 MVP; // MVP = Projection * View * Model // Send our transformation to the currently bound shader, in the "MVP" uniform // For each model you render, since the MVP will be different (at least the M part) for(int i=0;i<dim;i++){ for(int j=0;j<dim;j++){ // Load identity to model matrix Matrices.model = glm::mat4(1.0f); glm::mat4 translateRectangle = glm::translate (glm::vec3(floor_grey.pos.x+i, floor_grey.pos.y+j, floor_grey.pos.z)); // glTranslatef glm::mat4 rotateRectangle = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 myScalingMatrix = glm::scale(glm::mat4(1.0f),floor_grey.scale); Matrices.model *= (translateRectangle * rotateRectangle * myScalingMatrix); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix if(boardMatrix[i][j]==1) draw3DObject(floor_grey.object); else if(boardMatrix[i][j]==2) draw3DObject(floor_orange.object); else if(boardMatrix[i][j]==8) draw3DObject(floor_green.object); else if(boardMatrix[i][j]==7) draw3DObject(floor_red.object); else if(boardMatrix[i][j]==9) draw3DObject(floor_black.object); draw3DObject(floor_grey.line); } } // Load identity to model matrix Matrices.model = glm::mat4(1.0f); glm::mat4 translateCam = glm::translate(eye); glm::mat4 rotateCamX = glm::rotate((float)((90 - camera_rotation_angle_x)*M_PI/180.0f), glm::vec3(0,1,0)); glm::mat4 rotateCamY = glm::rotate((float)((90 - camera_rotation_angle_y)*M_PI/180.0f), glm::vec3(0,1,0)); Matrices.model *= (translateCam * rotateCamX*rotateCamY); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(cam); Matrices.model = glm::mat4(1.0f); glm::mat4 translateCube1 = glm::translate (cube[0].pos); // glTranslatef glm::mat4 rotateCube1X = glm::rotate((float)(-(cube[0].theta.x+45)*M_PI/180.0f), glm::vec3(0,-1,0)); glm::mat4 rotateCube1Y = glm::rotate((float)(-(cube[0].theta.y+45)*M_PI/180.0f), glm::vec3(1,0,0)); glm::mat4 myScalingMatrix2 = glm::scale(glm::mat4(1.0f),cube[0].scale); Matrices.model *= (translateCube1 * rotateCube1X * rotateCube1Y * myScalingMatrix2); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(cube[0].object); draw3DObject(cube[0].line); Matrices.model = glm::mat4(1.0f); glm::mat4 translateCube2 = glm::translate (cube[1].pos); // glTranslatef glm::mat4 rotateCube2X = glm::rotate((float)(-(cube[1].theta.x+45)*M_PI/180.0f), glm::vec3(0,-1,0)); glm::mat4 rotateCube2Y = glm::rotate((float)(-(cube[1].theta.y+45)*M_PI/180.0f), glm::vec3(1,0,0)); glm::mat4 myScalingMatrix = glm::scale(glm::mat4(1.0f),cube[1].scale); Matrices.model *= (translateCube2 * rotateCube2X * rotateCube2Y * myScalingMatrix); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(cube[1].object); draw3DObject(cube[1].line); Matrices.model = glm::mat4(1.0f); glm::mat4 translateText = glm::translate(glm::vec3(-3,2,0)); glm::mat4 scaleText = glm::scale(glm::vec3(fontScaleValue,fontScaleValue,fontScaleValue)); Matrices.model *= (translateText * scaleText); MVP = Matrices.projection * Matrices.view * Matrices.model; // send font's MVP and font color to fond shaders glUniformMatrix4fv(GL3Font.fontMatrixID, 1, GL_FALSE, &MVP[0][0]); glUniform3fv(GL3Font.fontColorID, 1, &fontColor[0]); // Render font GL3Font.font->Render("Round n Round we go !!"); } /* Initialise glfw window, I/O callbacks and the renderer to use */ /* Nothing to Edit here */ GLFWwindow* initGLFW (int width, int height){ GLFWwindow* window; // window desciptor/handle glfwSetErrorCallback(error_callback); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(width, height, "Sample OpenGL 3.3 Application", NULL, NULL); if (!window) { exit(EXIT_FAILURE); glfwTerminate(); } glfwMakeContextCurrent(window); // gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval( 1 ); glfwSetFramebufferSizeCallback(window, reshapeWindow); glfwSetWindowSizeCallback(window, reshapeWindow); glfwSetWindowCloseCallback(window, quit); glfwSetKeyCallback(window, keyboard); // general keyboard input glfwSetCharCallback(window, keyboardChar); // simpler specific character handling glfwSetMouseButtonCallback(window, mouseButton); // mouse button clicks return window; } /* Initialize the OpenGL rendering properties */ /* Add all the models to be created here */ void initGL (GLFWwindow* window, int width, int height) { /* Objects should be created before any other gl function and shaders */ // Create the models createRectangle (); createCam(); createFloor(); // Create and compile our GLSL program from the shaders programID = LoadShaders( "Sample_GL.vert", "Sample_GL.frag" ); // Get a handle for our "MVP" uniform Matrices.MatrixID = glGetUniformLocation(programID, "MVP"); reshapeWindow (window, width, height); // Background color of the scene glClearColor (0.3f, 0.3f, 0.3f, 0.0f); // R, G, B, A glClearDepth (1.0f); glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LEQUAL); cout << "VENDOR: " << glGetString(GL_VENDOR) << endl; cout << "RENDERER: " << glGetString(GL_RENDERER) << endl; cout << "VERSION: " << glGetString(GL_VERSION) << endl; cout << "GLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; } int fall_checker(){ if(boardMatrix[(int)cube[0].pos.x][(int)cube[0].pos.y]==0 || (int)cube[0].pos.y>=dim ||(int)cube[0].pos.y<0 || (int)cube[0].pos.x>=dim || (int)cube[0].pos.x<0 ) { system("aplay -q ./sounds/pin.wav &"); return 0; } if(boardMatrix[(int)cube[1].pos.x][(int)cube[1].pos.y]==0 || (int)cube[1].pos.y>=dim ||(int)cube[1].pos.y<0 || (int)cube[1].pos.x>=dim || (int)cube[1].pos.x<0 ) { system("aplay -q ./sounds/pin.wav &"); return 1; } return -1; } int hola,other; void merge_checker(){ if((abs((int)cube[0].pos.y - (int)cube[1].pos.y)==1&&abs((int)cube[0].pos.x - (int)cube[1].pos.x)==0) || (abs((int)cube[0].pos.y - (int)cube[1].pos.y)==0 &&abs((int)cube[0].pos.x - (int)cube[1].pos.x)==1) ){ if(merged==0 && toppling==0 && falling==0){ merged=1; } } } void black_checker(){ if(cube[0].pos.y==cube[1].pos.y && cube[0].pos.x ==cube[1].pos.x && abs(cube[0].pos.z-cube[1].pos.z)==1 && merged==1 && falling ==0 && boardMatrix[(int)cube[0].pos.x][(int)cube[0].pos.y]==9){ falling = 1; hola=0; other=1; right_move=true; system("aplay -q ./sounds/pin.wav &"); } } void orange_checker(){ if(cube[0].pos.y==cube[1].pos.y && cube[0].pos.x ==cube[1].pos.x && abs(cube[0].pos.z-cube[1].pos.z)==1&& toppling ==0 && merged==1 && falling ==0 && boardMatrix[(int)cube[0].pos.x][(int)cube[0].pos.y]==2){ falling = 1; hola=0; other=1; } } void cross_checker(){ for(vector<cross_struct>::iterator it=levels[current_level].crosses.begin();it<levels[current_level].crosses.end();it++) { if(merged==1 && falling ==0 && toppling ==0 && cube[0].pos.y==cube[1].pos.y && cube[0].pos.x==cube[1].pos.x && ((cube[0].pos.x==it->place.x&&cube[0].pos.y==it->place.y))){ cube[0].pos = it->place; cube[1].pos = it->other; merged=0; chosen=0; break; } } } void switch_checker(){ for(vector<switch_struct>::iterator it=levels[current_level].switches.begin();it<levels[current_level].switches.end();it++) { if(falling ==0 && toppling ==0 && ((cube[0].pos.x==it->place.x&&cube[0].pos.y==it->place.y)||(cube[1].pos.x==it->place.x&&cube[1].pos.y==it->place.y))){ if(it->used==false){ it->used=true; for(vector<glm::vec3>::iterator it2 = it->locations.begin();it2< it->locations.end();it2++){ boardMatrix[(int)it2->x][(int)it2->y]=1; } } } } } void gameEngine(){ merge_checker(); orange_checker(); black_checker(); cross_checker(); switch_checker(); //faller if(fall_checker()!=-1 && toppling==0 && falling == 0){ hola = fall_checker(); other = 1-hola; if(merged==1){ if(cube[other].pos.x == cube[hola].pos.x && cube[other].pos.y != cube[hola].pos.y){ int temp=1; } else if(cube[other].pos.y == cube[hola].pos.y && cube[other].pos.x != cube[hola].pos.x){ int temp=1; } else{ cube[other].pos.x = cube[hola].pos.x; cube[other].pos.y = cube[hola].pos.y; cube[other].pos.z = floor_grey.scale.z + cube[other].scale.z; cube[ hola].pos.z = floor_grey.scale.z + 3*cube[other].scale.z; } } toppling = 0; falling = 1; } if(falling ==1){ if(merged==1){ cube[other].pos.z -=0.1; cube[hola].pos.z -=0.1; if(cube[hola].pos.z <=-10){ falling = 0; Initialize(); } } else{ cube[dom].pos.z -=0.1; if(cube[dom].pos.z <=-10){ falling = 0; Initialize(); } } } if(toppling!=0 && falling == 0 ){ if(toppling == 1){ if(merged==1) CuboidToppleNorth(); else CubeToppleNorth(); } if(toppling == 2){ if(merged==1) CuboidToppleSouth(); else CubeToppleSouth(); } if(toppling == 3){ if(merged==1) CuboidToppleWest(); else CubeToppleWest(); } if(toppling == 4){ if(merged==1) CuboidToppleEast(); else CubeToppleEast(); } } // if(buttons["LEFT"]) // CubeActivateTopple(3); // if(buttons["RIGHT"]) // CubeActivateTopple(4); // if(buttons["UP"]) // CubeActivateTopple(1); // if(buttons["DOWN"]) // CubeActivateTopple(2); } void Level_creator(){ //Level1 Level_struct curr; int m1[10][10] = { {1,1,2,0,0,0,0,0,0,0}, {1,1,1,1,2,1,0,0,0,0}, {1,1,1,1,1,1,1,1,1,0}, {0,1,1,1,1,1,1,1,1,1}, {0,0,0,0,0,1,1,9,1,1}, {0,0,0,0,0,0,1,1,1,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0} }; for(int i=0;i<dim;i++){ for(int j=0;j<dim;j++){ curr.levelMatrix[i][j] = m1[i][j]; } } curr.cube0_pos = glm::vec3(0,0,floor_grey.scale.z+ cube[0].scale.z); curr.cube1_pos = glm::vec3(0,1,floor_grey.scale.z+ cube[0].scale.z); levels.push_back(curr); //Level2 int m2[10][10] = { {1,1,1,1,0,0,0,1,1,1}, {1,1,1,1,0,0,0,1,9,1}, {1,1,1,1,0,0,0,1,1,1}, {1,1,1,1,0,0,1,1,1,1}, {0,0,0,0,1,1,1,0,0,0}, {0,0,0,0,1,1,1,0,0,0}, {0,0,0,0,1,1,1,0,0,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0} }; for(int i=0;i<dim;i++){ for(int j=0;j<dim;j++){ curr.levelMatrix[i][j] = m2[i][j]; } } switch_struct sw; sw.used=false; sw.place = glm::vec3(2,2,0); sw.locations.push_back(glm::vec3(3,4,0)); curr.switches.push_back(sw); cross_struct cw; cw.place = glm::vec3(6,4,floor_grey.scale.z+ cube[0].scale.z); cw.other = glm::vec3(4,6,floor_grey.scale.z+ cube[0].scale.z); curr.crosses.push_back(cw); levels.push_back(curr); Level_struct curr2; int m3[10][10] = { {1,1,1,1,2,2,2,2,0,0}, {1,1,1,1,2,2,2,2,0,0}, {1,1,1,1,0,0,0,1,1,1}, {1,1,1,1,0,0,0,0,1,1}, {0,0,0,0,0,0,0,0,1,1}, {0,0,0,0,0,0,2,2,2,2}, {0,1,1,1,1,1,2,2,2,2}, {0,1,1,1,1,1,2,1,2,2}, {0,1,9,1,0,0,2,2,2,2}, {0,1,1,1,0,0,0,0,0,0} }; for(int i=0;i<dim;i++){ for(int j=0;j<dim;j++){ curr2.levelMatrix[i][j] = m3[i][j]; } } switch_struct sw1; sw1.used=false; sw1.place = glm::vec3(2,7,0); sw1.locations.push_back(glm::vec3(4,1,0)); sw1.locations.push_back(glm::vec3(5,1,0)); curr2.switches.push_back(sw1); curr2.cube0_pos = glm::vec3(0,0,floor_grey.scale.z+ cube[0].scale.z); curr2.cube1_pos = glm::vec3(0,1,floor_grey.scale.z+ cube[0].scale.z); levels.push_back(curr2); } int main (int argc, char** argv) { int width = 600; int height = 600; do_rot = 0; GLFWwindow* window = initGLFW(width, height); initGLEW(); initGL (window, width, height); last_update_time = glfwGetTime(); Level_creator(); int current_level=0; Initialize(); score=0; /* Draw in loop */ while (!glfwWindowShouldClose(window)) { // clear the color and depth in the frame buffer if(!paused){ gameEngine(); } if(current_level>2) break; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // OpenGL Draw commands current_time = glfwGetTime(); if ((current_time - last_update_time) >= 1) { // atleast 0.5s elapsed since last frame if(!paused) timer[current_level]+=1; // do something every 0.5 seconds .. } last_update_time = current_time; draw(window, 0, 0, 1, 1, 0, 1, 1); // draw(window, 0.5, 0, 0.5, 0.5, 0, 1, 1); // draw(window, 0, 0.5, 0.5, 0.5, 1, 0, 1); // draw(window, 0.5, 0.5, 0.5, 0.5, 0, 0, 1); // Swap Frame Buffer in double buffering glfwSwapBuffers(window); // Poll for Keyboard and mouse events glfwPollEvents(); } glfwTerminate(); // exit(EXIT_SUCCESS); }
90acf5818442bbc1cf5c32b2f8f95b6db86debf7
a081002197d091f1c387576894a160ececb69497
/activemq-cpp/src/main/activemq/wireformat/openwire/marshal/generated/WireFormatInfoMarshaller.cpp
48245e56460ab2fae7003508cda06b462ee1e1e9
[ "Apache-2.0" ]
permissive
greatyang/activemq-cpp
357fe087c839ed0d535ad7e3d987db2dc0badf1e
4f5d0847552d6a5e206cc54c4354ebd8b0bb8fe3
refs/heads/master
2021-03-03T09:53:20.887464
2020-03-09T05:34:59
2020-03-09T05:34:59
245,951,764
0
0
Apache-2.0
2020-03-09T05:31:25
2020-03-09T05:31:25
null
UTF-8
C++
false
false
6,890
cpp
/* * 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 <activemq/wireformat/openwire/marshal/generated/WireFormatInfoMarshaller.h> #include <activemq/commands/WireFormatInfo.h> #include <activemq/exceptions/ActiveMQException.h> #include <decaf/lang/Pointer.h> // // NOTE!: This file is autogenerated - do not modify! // if you need to make a change, please see the Java Classes in the // activemq-core module // using namespace std; using namespace activemq; using namespace activemq::exceptions; using namespace activemq::commands; using namespace activemq::wireformat; using namespace activemq::wireformat::openwire; using namespace activemq::wireformat::openwire::marshal; using namespace activemq::wireformat::openwire::utils; using namespace activemq::wireformat::openwire::marshal::generated; using namespace decaf; using namespace decaf::io; using namespace decaf::lang; /////////////////////////////////////////////////////////////////////////////// DataStructure* WireFormatInfoMarshaller::createObject() const { return new WireFormatInfo(); } /////////////////////////////////////////////////////////////////////////////// unsigned char WireFormatInfoMarshaller::getDataStructureType() const { return WireFormatInfo::ID_WIREFORMATINFO; } /////////////////////////////////////////////////////////////////////////////// void WireFormatInfoMarshaller::tightUnmarshal(OpenWireFormat* wireFormat, DataStructure* dataStructure, DataInputStream* dataIn, BooleanStream* bs) { try { BaseDataStreamMarshaller::tightUnmarshal(wireFormat, dataStructure, dataIn, bs); WireFormatInfo* info = dynamic_cast<WireFormatInfo*>(dataStructure); info->beforeUnmarshal(wireFormat); info->setMagic(tightUnmarshalConstByteArray(dataIn, bs, 8)); info->setVersion(dataIn->readInt()); info->setMarshalledProperties(tightUnmarshalByteArray(dataIn, bs)); info->afterUnmarshal( wireFormat ); } AMQ_CATCH_RETHROW(decaf::io::IOException) AMQ_CATCH_EXCEPTION_CONVERT(exceptions::ActiveMQException, decaf::io::IOException) AMQ_CATCHALL_THROW(decaf::io::IOException) } /////////////////////////////////////////////////////////////////////////////// int WireFormatInfoMarshaller::tightMarshal1(OpenWireFormat* wireFormat, DataStructure* dataStructure, BooleanStream* bs) { try { WireFormatInfo* info = dynamic_cast<WireFormatInfo*>(dataStructure); info->beforeMarshal(wireFormat); int rc = BaseDataStreamMarshaller::tightMarshal1(wireFormat, dataStructure, bs); bs->writeBoolean(info->getMarshalledProperties().size() != 0); rc += info->getMarshalledProperties().size() == 0 ? 0 : (int)info->getMarshalledProperties().size() + 4; return rc + 12; } AMQ_CATCH_RETHROW(decaf::io::IOException) AMQ_CATCH_EXCEPTION_CONVERT(exceptions::ActiveMQException, decaf::io::IOException) AMQ_CATCHALL_THROW(decaf::io::IOException) } /////////////////////////////////////////////////////////////////////////////// void WireFormatInfoMarshaller::tightMarshal2(OpenWireFormat* wireFormat, DataStructure* dataStructure, DataOutputStream* dataOut, BooleanStream* bs) { try { BaseDataStreamMarshaller::tightMarshal2(wireFormat, dataStructure, dataOut, bs ); WireFormatInfo* info = dynamic_cast<WireFormatInfo*>(dataStructure); dataOut->write((const unsigned char*)(&info->getMagic()[0]), 8, 0, 8); dataOut->writeInt(info->getVersion()); if (bs->readBoolean()) { dataOut->writeInt((int)info->getMarshalledProperties().size() ); dataOut->write((const unsigned char*)(&info->getMarshalledProperties()[0]), (int)info->getMarshalledProperties().size(), 0, (int)info->getMarshalledProperties().size()); } info->afterMarshal(wireFormat); } AMQ_CATCH_RETHROW(decaf::io::IOException) AMQ_CATCH_EXCEPTION_CONVERT( exceptions::ActiveMQException, decaf::io::IOException) AMQ_CATCHALL_THROW(decaf::io::IOException) } /////////////////////////////////////////////////////////////////////////////// void WireFormatInfoMarshaller::looseUnmarshal(OpenWireFormat* wireFormat, DataStructure* dataStructure, DataInputStream* dataIn) { try { BaseDataStreamMarshaller::looseUnmarshal(wireFormat, dataStructure, dataIn); WireFormatInfo* info = dynamic_cast<WireFormatInfo*>(dataStructure); info->beforeUnmarshal(wireFormat); info->setMagic(looseUnmarshalConstByteArray(dataIn, 8)); info->setVersion(dataIn->readInt()); info->setMarshalledProperties(looseUnmarshalByteArray(dataIn)); info->afterUnmarshal(wireFormat); } AMQ_CATCH_RETHROW(decaf::io::IOException) AMQ_CATCH_EXCEPTION_CONVERT(exceptions::ActiveMQException, decaf::io::IOException) AMQ_CATCHALL_THROW(decaf::io::IOException) } /////////////////////////////////////////////////////////////////////////////// void WireFormatInfoMarshaller::looseMarshal(OpenWireFormat* wireFormat, DataStructure* dataStructure, DataOutputStream* dataOut) { try { WireFormatInfo* info = dynamic_cast<WireFormatInfo*>(dataStructure); info->beforeMarshal(wireFormat); BaseDataStreamMarshaller::looseMarshal(wireFormat, dataStructure, dataOut); dataOut->write((const unsigned char*)(&info->getMagic()[0]), 8, 0, 8); dataOut->writeInt(info->getVersion()); dataOut->write( info->getMarshalledProperties().size() != 0 ); if( info->getMarshalledProperties().size() != 0 ) { dataOut->writeInt( (int)info->getMarshalledProperties().size() ); dataOut->write((const unsigned char*)(&info->getMarshalledProperties()[0]), (int)info->getMarshalledProperties().size(), 0, (int)info->getMarshalledProperties().size()); } info->afterMarshal(wireFormat); } AMQ_CATCH_RETHROW(decaf::io::IOException) AMQ_CATCH_EXCEPTION_CONVERT(exceptions::ActiveMQException, decaf::io::IOException) AMQ_CATCHALL_THROW(decaf::io::IOException) }
7d121a6b6e0576db8c6f877bdea565fc4fe0077c
cf3ef2cb7cbce88fb28b184d05f1286a17c6a09a
/ns-3.19/src/buildings/model/buildings-propagation-loss-model.cc
bc1639fe939cb4c94a322b453b4e640460d5e83d
[]
no_license
G8XSU/ns3-pmipv6
4d318e39a799e2cfa8f8b8948972494d0d4ad559
cde2da6d2476eaa5ed49580494e2788f62ddb71e
refs/heads/master
2016-09-05T18:13:23.367968
2014-05-06T12:56:14
2014-05-06T12:56:14
19,178,140
6
6
null
null
null
null
UTF-8
C++
false
false
7,230
cc
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Marco Miozzo <[email protected]>, * Nicola Baldo <[email protected]> * */ #include "ns3/propagation-loss-model.h" #include "ns3/log.h" #include "ns3/mobility-model.h" #include "ns3/double.h" #include "ns3/pointer.h" #include <cmath> #include "buildings-propagation-loss-model.h" #include <ns3/mobility-building-info.h> #include "ns3/enum.h" NS_LOG_COMPONENT_DEFINE ("BuildingsPropagationLossModel"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (BuildingsPropagationLossModel) ; BuildingsPropagationLossModel::ShadowingLoss::ShadowingLoss () { } BuildingsPropagationLossModel::ShadowingLoss::ShadowingLoss (double shadowingValue, Ptr<MobilityModel> receiver) : m_shadowingValue (shadowingValue), m_receiver (receiver) { NS_LOG_INFO (this << " New Shadowing value " << m_shadowingValue); } double BuildingsPropagationLossModel::ShadowingLoss::GetLoss () const { return (m_shadowingValue); } Ptr<MobilityModel> BuildingsPropagationLossModel::ShadowingLoss::GetReceiver () const { return m_receiver; } TypeId BuildingsPropagationLossModel::GetTypeId (void) { static TypeId tid = TypeId ("ns3::BuildingsPropagationLossModel") .SetParent<PropagationLossModel> () .AddAttribute ("ShadowSigmaOutdoor", "Standard deviation of the normal distribution used for calculate the shadowing for outdoor nodes", DoubleValue (7.0), MakeDoubleAccessor (&BuildingsPropagationLossModel::m_shadowingSigmaOutdoor), MakeDoubleChecker<double> ()) .AddAttribute ("ShadowSigmaIndoor", "Standard deviation of the normal distribution used for calculate the shadowing for indoor nodes ", DoubleValue (8.0), MakeDoubleAccessor (&BuildingsPropagationLossModel::m_shadowingSigmaIndoor), MakeDoubleChecker<double> ()) .AddAttribute ("ShadowSigmaExtWalls", "Standard deviation of the normal distribution used for calculate the shadowing due to ext walls ", DoubleValue (5.0), MakeDoubleAccessor (&BuildingsPropagationLossModel::m_shadowingSigmaExtWalls), MakeDoubleChecker<double> ()) .AddAttribute ("InternalWallLoss", "Additional loss for each internal wall [dB]", DoubleValue (5.0), MakeDoubleAccessor (&BuildingsPropagationLossModel::m_lossInternalWall), MakeDoubleChecker<double> ()); return tid; } BuildingsPropagationLossModel::BuildingsPropagationLossModel () { m_randVariable = CreateObject<NormalRandomVariable> (); } double BuildingsPropagationLossModel::ExternalWallLoss (Ptr<MobilityBuildingInfo> a) const { double loss = 0.0; Ptr<Building> aBuilding = a->GetBuilding (); if (aBuilding->GetExtWallsType () == Building::Wood) { loss = 4; } else if (aBuilding->GetExtWallsType () == Building::ConcreteWithWindows) { loss = 7; } else if (aBuilding->GetExtWallsType () == Building::ConcreteWithoutWindows) { loss = 15; // 10 ~ 20 dB } else if (aBuilding->GetExtWallsType () == Building::StoneBlocks) { loss = 12; } return (loss); } double BuildingsPropagationLossModel::HeightLoss (Ptr<MobilityBuildingInfo> node) const { double loss = 0.0; int nfloors = node->GetFloorNumber () - 1; loss = -2 * (nfloors); return (loss); } double BuildingsPropagationLossModel::InternalWallsLoss (Ptr<MobilityBuildingInfo> a, Ptr<MobilityBuildingInfo>b) const { // approximate the number of internal walls with the Manhattan distance in "rooms" units double dx = std::abs (a->GetRoomNumberX () - b->GetRoomNumberX ()); double dy = std::abs (a->GetRoomNumberY () - b->GetRoomNumberY ()); return m_lossInternalWall * (dx+dy); } double BuildingsPropagationLossModel::GetShadowing (Ptr<MobilityModel> a, Ptr<MobilityModel> b) const { Ptr<MobilityBuildingInfo> a1 = a->GetObject <MobilityBuildingInfo> (); Ptr<MobilityBuildingInfo> b1 = b->GetObject <MobilityBuildingInfo> (); NS_ASSERT_MSG ((a1 != 0) && (b1 != 0), "BuildingsPropagationLossModel only works with MobilityBuildingInfo"); std::map<Ptr<MobilityModel>, std::map<Ptr<MobilityModel>, ShadowingLoss> >::iterator ait = m_shadowingLossMap.find (a); if (ait != m_shadowingLossMap.end ()) { std::map<Ptr<MobilityModel>, ShadowingLoss>::iterator bit = ait->second.find (b); if (bit != ait->second.end ()) { return (bit->second.GetLoss ()); } else { double sigma = EvaluateSigma (a1, b1); // side effect: will create new entry // sigma is standard deviation, not variance double shadowingValue = m_randVariable->GetValue (0.0, (sigma*sigma)); ait->second[b] = ShadowingLoss (shadowingValue, b); return (ait->second[b].GetLoss ()); } } else { double sigma = EvaluateSigma (a1, b1); // side effect: will create new entries in both maps // sigma is standard deviation, not variance double shadowingValue = m_randVariable->GetValue (0.0, (sigma*sigma)); m_shadowingLossMap[a][b] = ShadowingLoss (shadowingValue, b); return (m_shadowingLossMap[a][b].GetLoss ()); } } double BuildingsPropagationLossModel::EvaluateSigma (Ptr<MobilityBuildingInfo> a, Ptr<MobilityBuildingInfo> b) const { if (a->IsOutdoor ()) { if (b->IsOutdoor ()) { return (m_shadowingSigmaOutdoor); } else { double sigma = std::sqrt ((m_shadowingSigmaOutdoor * m_shadowingSigmaOutdoor) + (m_shadowingSigmaExtWalls * m_shadowingSigmaExtWalls)); return (sigma); } } else if (b->IsIndoor ()) { return (m_shadowingSigmaIndoor); } else { double sigma = std::sqrt ((m_shadowingSigmaOutdoor * m_shadowingSigmaOutdoor) + (m_shadowingSigmaExtWalls * m_shadowingSigmaExtWalls)); return (sigma); } } double BuildingsPropagationLossModel::DoCalcRxPower (double txPowerDbm, Ptr<MobilityModel> a, Ptr<MobilityModel> b) const { return txPowerDbm - GetLoss (a, b) - GetShadowing (a, b); } int64_t BuildingsPropagationLossModel::DoAssignStreams (int64_t stream) { m_randVariable->SetStream (stream); return 1; } } // namespace ns3
b683a1acd9224f7bda74870720308cd999ebda1e
db4bf625fd9098ec1d54be8a65abefda9d21b74b
/INET_EC/applications/packetdrill/PacketDrillInfo_m.h
24d31d2cf556aeca6675f2193512c071962f1893
[ "Apache-2.0" ]
permissive
LarryNguyen/ECSimpp
1e648e3006b6908e342bea442c90b56d5a7026d0
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
refs/heads/master
2021-07-02T19:38:40.266460
2017-09-21T02:59:35
2017-09-21T02:59:35
104,284,993
0
1
null
null
null
null
UTF-8
C++
false
false
2,744
h
// // Generated file, do not edit! Created by nedtool 5.1 from inet/applications/packetdrill/PacketDrillInfo.msg. // #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #ifndef __PACKETDRILLINFO_M_H #define __PACKETDRILLINFO_M_H #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0501 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif // dll export symbol #ifndef INET_API # if defined(INET_EXPORT) # define INET_API OPP_DLLEXPORT # elif defined(INET_IMPORT) # define INET_API OPP_DLLIMPORT # else # define INET_API # endif #endif /** * Class generated from <tt>inet/applications/packetdrill/PacketDrillInfo.msg:20</tt> by nedtool. * <pre> * message PacketDrillInfo * { * simtime_t scriptTime; * simtime_t scriptTimeEnd; * simtime_t offset; * uint16 timeType; * simtime_t liveTime; * } * </pre> */ class INET_API PacketDrillInfo : public ::omnetpp::cMessage { protected: ::omnetpp::simtime_t scriptTime; ::omnetpp::simtime_t scriptTimeEnd; ::omnetpp::simtime_t offset; uint16_t timeType; ::omnetpp::simtime_t liveTime; private: void copy(const PacketDrillInfo& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const PacketDrillInfo&); public: PacketDrillInfo(const char *name=nullptr, short kind=0); PacketDrillInfo(const PacketDrillInfo& other); virtual ~PacketDrillInfo(); PacketDrillInfo& operator=(const PacketDrillInfo& other); virtual PacketDrillInfo *dup() const override {return new PacketDrillInfo(*this);} virtual void parsimPack(omnetpp::cCommBuffer *b) const override; virtual void parsimUnpack(omnetpp::cCommBuffer *b) override; // field getter/setter methods virtual ::omnetpp::simtime_t getScriptTime() const; virtual void setScriptTime(::omnetpp::simtime_t scriptTime); virtual ::omnetpp::simtime_t getScriptTimeEnd() const; virtual void setScriptTimeEnd(::omnetpp::simtime_t scriptTimeEnd); virtual ::omnetpp::simtime_t getOffset() const; virtual void setOffset(::omnetpp::simtime_t offset); virtual uint16_t getTimeType() const; virtual void setTimeType(uint16_t timeType); virtual ::omnetpp::simtime_t getLiveTime() const; virtual void setLiveTime(::omnetpp::simtime_t liveTime); }; inline void doParsimPacking(omnetpp::cCommBuffer *b, const PacketDrillInfo& obj) {obj.parsimPack(b);} inline void doParsimUnpacking(omnetpp::cCommBuffer *b, PacketDrillInfo& obj) {obj.parsimUnpack(b);} #endif // ifndef __PACKETDRILLINFO_M_H
4a7d330140c071ef1e27646ee1a0ae91917123fa
71c2107d2e98fee6399d0ecbb88c63fa529e7cfa
/parentpixmapgraph.cpp
e1c6fe2936d0cd73a3877a318c5528aea85ffdaa
[]
no_license
AiK312/DPLM
f3fc26701fab1462d3dc65076e15d697d12f0039
5a75d09f51c618c040ea1e7be147aac5392a7ab4
refs/heads/master
2021-01-17T07:15:14.884080
2016-05-24T10:00:21
2016-05-24T10:00:21
51,583,850
0
0
null
null
null
null
UTF-8
C++
false
false
1,583
cpp
#include "parentpixmapgraph.h" parentPixmapGraph::parentPixmapGraph() : startX(0), startY(0) { } QRectF parentPixmapGraph::boundingRect() const { return QRectF(pos(), QSizeF(10000.0, 10000.0)); } void parentPixmapGraph::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setRenderHint(QPainter::HighQualityAntialiasing); painter->drawLine(QPointF(0,0), pos()); Q_UNUSED(option); Q_UNUSED(widget); } void parentPixmapGraph::mousePressEvent(QGraphicsSceneMouseEvent *event) { this->setCursor(QCursor(Qt::ClosedHandCursor)); pressX = event->pos().x(); pressY = event->pos().y(); Q_UNUSED(event); } void parentPixmapGraph::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { this->setCursor(QCursor(Qt::ArrowCursor)); releaseX = event->pos().x(); releaseY = event->pos().y(); int deltaX = pressX - releaseX; int deltaY = pressY - releaseY; if (deltaX == 0 && deltaY == 0) return; this->setPos(startX-deltaX, startY-deltaY); startX -= deltaX; startY -= deltaY; Q_UNUSED(event); emit movingTiles(); } void parentPixmapGraph::wheelEvent(QGraphicsSceneWheelEvent *event) { QPoint *p = new QPoint(event->pos().toPoint()); if(event->delta() > 0) emit zoomIn(p); else emit zoomOut(p); } QPoint *parentPixmapGraph::getStartCoordinates(QPoint *coordinates) { coordinates->setX(startX); coordinates->setY(startY); return coordinates; }
b1146cc5106f478fa1793affa964833fa29796b6
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.h
9cb8670c0c976d9ffc6579a3997bf62be6420ce6
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "LGPL-2.0-only", "LGPL-2.1-only", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
4,431
h
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * Copyright (C) 2010 Google 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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. */ #ifndef CSSPreloadScanner_h #define CSSPreloadScanner_h #include "core/fetch/CSSStyleSheetResource.h" #include "core/fetch/ResourceOwner.h" #include "core/fetch/StyleSheetResourceClient.h" #include "core/html/parser/HTMLToken.h" #include "core/html/parser/PreloadRequest.h" #include "platform/heap/Handle.h" #include "wtf/text/StringBuilder.h" namespace blink { class SegmentedString; class HTMLResourcePreloader; class CSSPreloadScanner { DISALLOW_NEW(); WTF_MAKE_NONCOPYABLE(CSSPreloadScanner); public: CSSPreloadScanner(); ~CSSPreloadScanner(); void reset(); void scan(const HTMLToken::DataVector&, const SegmentedString&, PreloadRequestStream&, const KURL&); void scan(const String&, const SegmentedString&, PreloadRequestStream&, const KURL&); void setReferrerPolicy(const ReferrerPolicy); private: enum State { Initial, MaybeComment, Comment, MaybeCommentEnd, RuleStart, Rule, AfterRule, RuleValue, AfterRuleValue, DoneParsingImportRules, }; template <typename Char> void scanCommon(const Char* begin, const Char* end, const SegmentedString&, PreloadRequestStream&, const KURL&); inline void tokenize(UChar, const SegmentedString&); void emitRule(const SegmentedString&); State m_state = Initial; StringBuilder m_rule; StringBuilder m_ruleValue; ReferrerPolicy m_referrerPolicy = ReferrerPolicyDefault; // Below members only non-null during scan() PreloadRequestStream* m_requests = nullptr; const KURL* m_predictedBaseElementURL = nullptr; }; // Each CSSPreloaderResourceClient keeps track of a single CSS resource, and // drives a CSSPreloadScanner as raw data arrives for it. This lets us preload // @import tags before parsing. class CORE_EXPORT CSSPreloaderResourceClient : public GarbageCollectedFinalized<CSSPreloaderResourceClient>, public StyleSheetResourceClient { USING_GARBAGE_COLLECTED_MIXIN(CSSPreloaderResourceClient); public: CSSPreloaderResourceClient(Resource*, HTMLResourcePreloader*); ~CSSPreloaderResourceClient(); void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*) override; void didAppendFirstData(const CSSStyleSheetResource*) override; String debugName() const override { return "CSSPreloaderResourceClient"; } DECLARE_TRACE(); protected: // Protected for tests, which don't want to initialize a fully featured // DocumentLoader. virtual void fetchPreloads(PreloadRequestStream& preloads); private: void scanCSS(const CSSStyleSheetResource*); void clearResource(); enum PreloadPolicy { ScanOnly, ScanAndPreload, }; const PreloadPolicy m_policy; WeakMember<HTMLResourcePreloader> m_preloader; WeakMember<CSSStyleSheetResource> m_resource; }; } // namespace blink #endif
705204ce62358bb9473a06c179290f9d566f0ba9
5387aefed0e5cd0a55f10fae7784f03190f2fdf0
/catkin_ws/devel/include/ki_robotics/AIServiceRequest.h
8d2b7e2f7f5cb7def7e299b010167777cecdcf4a
[]
no_license
Horenhof/ROSproject
45f2979be9422f2f345746ed4f1d6c3e11198c60
d6b479bb963b30c960f870dcf067db982256fb25
refs/heads/main
2023-02-23T06:03:37.376547
2021-01-21T20:01:19
2021-01-21T20:01:19
330,743,476
0
0
null
null
null
null
UTF-8
C++
false
false
7,320
h
// Generated by gencpp from file ki_robotics/AIServiceRequest.msg // DO NOT EDIT! #ifndef KI_ROBOTICS_MESSAGE_AISERVICEREQUEST_H #define KI_ROBOTICS_MESSAGE_AISERVICEREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <sensor_msgs/Image.h> namespace ki_robotics { template <class ContainerAllocator> struct AIServiceRequest_ { typedef AIServiceRequest_<ContainerAllocator> Type; AIServiceRequest_() : image() { } AIServiceRequest_(const ContainerAllocator& _alloc) : image(_alloc) { (void)_alloc; } typedef ::sensor_msgs::Image_<ContainerAllocator> _image_type; _image_type image; typedef boost::shared_ptr< ::ki_robotics::AIServiceRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::ki_robotics::AIServiceRequest_<ContainerAllocator> const> ConstPtr; }; // struct AIServiceRequest_ typedef ::ki_robotics::AIServiceRequest_<std::allocator<void> > AIServiceRequest; typedef boost::shared_ptr< ::ki_robotics::AIServiceRequest > AIServiceRequestPtr; typedef boost::shared_ptr< ::ki_robotics::AIServiceRequest const> AIServiceRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::ki_robotics::AIServiceRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::ki_robotics::AIServiceRequest_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::ki_robotics::AIServiceRequest_<ContainerAllocator1> & lhs, const ::ki_robotics::AIServiceRequest_<ContainerAllocator2> & rhs) { return lhs.image == rhs.image; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::ki_robotics::AIServiceRequest_<ContainerAllocator1> & lhs, const ::ki_robotics::AIServiceRequest_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace ki_robotics namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsMessage< ::ki_robotics::AIServiceRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ki_robotics::AIServiceRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::ki_robotics::AIServiceRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::ki_robotics::AIServiceRequest_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::ki_robotics::AIServiceRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::ki_robotics::AIServiceRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::ki_robotics::AIServiceRequest_<ContainerAllocator> > { static const char* value() { return "b13d2865c5af2a64e6e30ab1b56e1dd5"; } static const char* value(const ::ki_robotics::AIServiceRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xb13d2865c5af2a64ULL; static const uint64_t static_value2 = 0xe6e30ab1b56e1dd5ULL; }; template<class ContainerAllocator> struct DataType< ::ki_robotics::AIServiceRequest_<ContainerAllocator> > { static const char* value() { return "ki_robotics/AIServiceRequest"; } static const char* value(const ::ki_robotics::AIServiceRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::ki_robotics::AIServiceRequest_<ContainerAllocator> > { static const char* value() { return "sensor_msgs/Image image\n" "\n" "================================================================================\n" "MSG: sensor_msgs/Image\n" "# This message contains an uncompressed image\n" "# (0, 0) is at top-left corner of image\n" "#\n" "\n" "Header header # Header timestamp should be acquisition time of image\n" " # Header frame_id should be optical frame of camera\n" " # origin of frame should be optical center of camera\n" " # +x should point to the right in the image\n" " # +y should point down in the image\n" " # +z should point into to plane of the image\n" " # If the frame_id here and the frame_id of the CameraInfo\n" " # message associated with the image conflict\n" " # the behavior is undefined\n" "\n" "uint32 height # image height, that is, number of rows\n" "uint32 width # image width, that is, number of columns\n" "\n" "# The legal values for encoding are in file src/image_encodings.cpp\n" "# If you want to standardize a new string format, join\n" "# [email protected] and send an email proposing a new encoding.\n" "\n" "string encoding # Encoding of pixels -- channel meaning, ordering, size\n" " # taken from the list of strings in include/sensor_msgs/image_encodings.h\n" "\n" "uint8 is_bigendian # is this data bigendian?\n" "uint32 step # Full row length in bytes\n" "uint8[] data # actual matrix data, size is (step * rows)\n" "\n" "================================================================================\n" "MSG: std_msgs/Header\n" "# Standard metadata for higher-level stamped data types.\n" "# This is generally used to communicate timestamped data \n" "# in a particular coordinate frame.\n" "# \n" "# sequence ID: consecutively increasing ID \n" "uint32 seq\n" "#Two-integer timestamp that is expressed as:\n" "# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n" "# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n" "# time-handling sugar is provided by the client library\n" "time stamp\n" "#Frame this data is associated with\n" "string frame_id\n" ; } static const char* value(const ::ki_robotics::AIServiceRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::ki_robotics::AIServiceRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.image); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct AIServiceRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::ki_robotics::AIServiceRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ki_robotics::AIServiceRequest_<ContainerAllocator>& v) { s << indent << "image: "; s << std::endl; Printer< ::sensor_msgs::Image_<ContainerAllocator> >::stream(s, indent + " ", v.image); } }; } // namespace message_operations } // namespace ros #endif // KI_ROBOTICS_MESSAGE_AISERVICEREQUEST_H
fc4f44521018133a31eb980344c86e92276243c2
ec66f1b78f80a00b4405f7a227cfb8bbbe6b1efb
/HackerRank/Cipher.cpp
73dc7caa58952d0072187342cfd567151bdf4b86
[]
no_license
bagaria1207/CODE-Practice
bc0531934d50bd4c965765fc29cc94741ac2cdcd
69f7cd12922e8ad52f91c3ad66199eb0974513d5
refs/heads/master
2022-11-26T02:55:06.492045
2020-08-04T11:51:51
2020-08-04T11:51:51
268,247,666
0
0
null
null
null
null
UTF-8
C++
false
false
688
cpp
#include<bits/stdc++.h> using namespace std; /* Done with the help of editorial Ascii of 0->48 1->48 %48 -> to get the value in int as directly we get as ascii value from string */ int main(){ int n,k; cin>>n>>k; string s; cin>>s; string b=""; b+=s[0]; if(n<=k){ for(int i=1;i<n;i++){ int a = s[i-1]%48^s[i]%48; b+=(a+48); } } else{ int i; for(i=1;i<k;i++){ int a = s[i-1]%48^s[i]%48; b+=(a+48); } for(int j=0;b.size()<n;j++,i++){ int a = s[i-1]%48^s[i]%48^b[j]%48; b+=(a+48); } } cout<<b<<"\n"; }
aee832a9e4d8a13ea0a1208e97b2a5d99b8f7e21
6de5de01e4fc9ac387e2f41e0776be562ba0860a
/sapphire/dllmain.cpp
f0cf1362912a7432d014d1fc37a2a621247ae083
[]
no_license
MatrixKung/sapphire
f1e07dce1d0616fdadccc2609cad2b6164711d86
34908a2ffb61543e5b5ba9befcabb845f52953c9
refs/heads/main
2023-08-28T03:33:23.887109
2021-10-26T02:11:10
2021-10-26T02:11:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,436
cpp
#include "sapphire_crt.hpp" #include "sapphire_hook.hpp" #include "sapphire_importer.hpp" #include "hooks.hpp" auto DllMain( void*, std::uint32_t call_reason, void* ) -> bool { if ( call_reason != 1 ) return false; il2cpp_lib::init( ); { impl::hooks::ddraw_ongui.setup( "UnityEngine::DDraw.OnGUI()", &impl::hooks::hk_ddraw_ongui, 0 ); // should work anywhere as long as we have hook to call it in. impl::hooks::bp_client_input.setup( "BasePlayer.ClientInput()", &impl::hooks::hk_bp_client_input ); impl::hooks::launch_projectile.setup( "BaseProjectile.LaunchProjectile()", &impl::hooks::hk_launch_projectile ); impl::hooks::on_attacked.setup( "BasePlayer.OnAttacked()", &impl::hooks::hk_on_attacked ); // I think we can only hook this function in-game. Maybe find another function thats called in game often, or hook inside client input hook. static auto projectile_shoot_sig = utl::pattern::find( L"GameAssembly.dll", "4C 8B 0D ? ? ? ? 48 8B 75 28" ); const auto relative_projectile_shoot = *reinterpret_cast< std::uintptr_t* >( projectile_shoot_sig + *reinterpret_cast< std::int32_t* >( projectile_shoot_sig + 3 ) + 7 ); if ( relative_projectile_shoot ) { const auto projectile_shoot_rpc = **reinterpret_cast< std::uintptr_t*** >( relative_projectile_shoot + 0x30 ); HOOK_CUSTOM( projectile_shoot_rpc, impl::hooks::o_projectile_shoot_rpc, &impl::hooks::hk_projectile_shoot_rpc ); } } return true; }
3df51b453c96bbb084c9600e17283ba4c1b40e4e
f3fa6c321305992c5b962a60f52c706a157e2c2e
/Audio/wave_vc_con/src/main_.cpp
72e55b578ddd664cc82969383631326fb07e50f8
[]
no_license
0xFF1E071F/asm
a09a825b0b9fd50086410d4638174cf069ebe16e
459a1b3b1a361717e5caf1e53f0ce87479d872c6
refs/heads/master
2022-11-23T02:15:32.968568
2020-07-24T08:40:41
2020-07-24T08:40:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,421
cpp
#include <windows.h> #include <mmsystem.h> #define IDD_MAIN 101 #define IDC_LST1 103 BOOL CALLBACK DlgProc(HWND,UINT,WPARAM,LPARAM); void ShowWaveDevices (HWND hList); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { //HWND hWnd = GetDesktopWindow(); //MessageBox(hWnd, "123", "Hello", 0); DialogBox( hInstance, MAKEINTRESOURCE(IDD_MAIN), 0, DlgProc); return 0; } BOOL CALLBACK DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: { switch(wParam) { case IDOK: { HWND hList = GetDlgItem(hWnd,IDC_LST1); ShowWaveDevices (hList); return FALSE; } case IDCANCEL: { EndDialog(hWnd, NULL); return TRUE; } default: return FALSE; } } default: return FALSE; } } void ShowWaveDevices (HWND hList) { WAVEINCAPS inCaps; WAVEOUTCAPS outCaps; int i, nDevs = waveInGetNumDevs(); for (i=0; i<nDevs; i++){ waveInGetDevCaps(i,&inCaps,sizeof(inCaps)); SendMessage(hList,LB_ADDSTRING,0,(LPARAM)inCaps.szPname); } SendMessage(hList,LB_ADDSTRING,0,(LPARAM)" "); nDevs = waveOutGetNumDevs(); for (i=0; i<nDevs; i++){ waveOutGetDevCaps(i,&outCaps,sizeof(outCaps)); SendMessage(hList,LB_ADDSTRING,0,(LPARAM)outCaps.szPname); } }
e9517eff4e50e1df1e98b9d2a0603e4e83db4b81
65b02eae4e6ea39beadb67c5efd62e0b429bb43b
/Algorithm/graph/spfa/k-short.cpp
2653787696215eacce089a4ee7f51f6c244b2875
[]
no_license
ctuu/acm-icpc
c0a96a347feba414fce28455e9b71546ac1cb08d
7fde619dce94dd2e722465cdcad32c76d30afa16
refs/heads/master
2021-07-08T06:14:57.837572
2018-12-29T04:09:40
2018-12-29T04:09:40
81,524,853
2
0
null
null
null
null
UTF-8
C++
false
false
2,476
cpp
#include <algorithm> #include <array> #include <iostream> #include <queue> #include <vector> using namespace std; const int N = 1e4 + 7; const int M = 1e5 + 7; const int INF = 0x3f3f3f3f; using G = vector<vector<int>>; //save index array<int, N> vis, d; array<int, M> pth; struct Node { int d, u; Node(int d, int u) : d(d), u(u) {} bool operator<(const Node &a) const { return d > a.d; } }; struct Edge { int fr, to, di; Edge() = default; Edge(int u, int v, int w) : fr(u), to(v), di(w) {} }; using E = vector<Edge>; void dijkstra(G &gr, E &edg, int s) { d.fill(INF); d[s] = 0; vis.fill(0); priority_queue<Node> pq; pq.push(Node(0, s)); while (!pq.empty()) { Node x = pq.top(); pq.pop(); int u = x.u; if (d[u] < x.d) continue; for (auto i : gr[u]) { Edge &e = edg[i]; int to = (e.fr == u) ? e.to : e.fr; if (d[to] > d[u] + e.di) { d[to] = d[u] + e.di; pth[to] = i; pq.push(Node(d[to], to)); } } } } struct Ande { int u, g, f; Ande(int u, int g, int f) : u(u), g(g), f(f) {} bool operator<(const Ande a) const { if (a.f == f) return a.g < g; return a.f < f; } }; int astar(G &gr, E &edg, int s, int t, int k) { if(d[s] == INF) return INF; priority_queue<Ande> que; que.push(Ande(s, 0, d[s])); while (!que.empty()) { Ande c = que.top(); que.pop(); int u = c.u; if (u == t) if (k-- <= 1) return c.f; for (auto i : gr[u]) { Edge &e = edg[i]; int to = (e.fr == u) ? e.to : e.fr; que.push(Ande(to, c.g+e.di, c.g + e.di + d[to])); } } return INF; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m, s, t, k; cin >> n >> m; cin >> s >> t >> k; G gr, grr; E edg; gr.resize(n + 1); grr.resize(n + 1); edg.resize(m + 1); for (int i = 0; i < m; ++i) { int fr, to, di; cin >> fr >> to >> di; edg[i] = Edge(fr, to, di); grr[to].push_back(i); // 反向建图 gr[fr].push_back(i); // gr[to].push_back(i);// if Two-Way } dijkstra(grr, edg, t); cout << astar(gr, edg, s, t, k) << endl; // cout << d[t] << endl; return 0; }
2ea70f694de61292fa4de7b67fe30dec68bb1e3c
3378a6f06cf3d6fed65ba6f9b4908f92646822dd
/bacalaureat/teste_antrenament/testul4/p3/main.cpp
8e983170a3a2cc4a3aa93084c403c33cf91d4a73
[]
no_license
zaBogdan/problemeInfo
6bac9cd7f9ccb5cb81c5388752e3c3a37ff8af97
4046619186e6d57c2620ce4c6725fe4ebf931fdb
refs/heads/master
2021-07-11T18:23:09.095312
2020-09-05T17:02:58
2020-09-05T17:02:58
192,736,624
1
1
null
null
null
null
UTF-8
C++
false
false
369
cpp
#include <iostream> #include <fstream> using namespace std; ifstream f("bac.txt"); int main(){ int x,y,ap=0; f >> x; while(f >> y){ if(x==y) ap++; else{ if(!ap) cout << x << ' '; ap=0; } x=y; } if(!ap) cout << x << ' '; cout << endl; return 0; }
2210ac585809e99460c7248332a2357473f106ba
b258e2449fd26ab92c4be56a368e45c514efe60a
/moc_bypasspage.cpp
ea229767020a06a5bdd8a0147b8eec8f48980c76
[]
no_license
MinnieJewel/DJY
f6c3e6b99104f334fa41f98d6c5256352ff6fad8
74a3b6b34871a7fbd38b9fc0d8158b679d54014a
refs/heads/master
2022-09-16T19:30:46.147808
2020-06-02T06:29:42
2020-06-02T06:29:42
268,722,025
0
0
null
null
null
null
UTF-8
C++
false
false
2,049
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'bypasspage.h' ** ** Created: Tue Jun 2 11:36:01 2020 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "bypasspage.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'bypasspage.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_ByPassPage[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_ByPassPage[] = { "ByPassPage\0" }; const QMetaObject ByPassPage::staticMetaObject = { { &MyBase::staticMetaObject, qt_meta_stringdata_ByPassPage, qt_meta_data_ByPassPage, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &ByPassPage::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *ByPassPage::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *ByPassPage::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_ByPassPage)) return static_cast<void*>(const_cast< ByPassPage*>(this)); return MyBase::qt_metacast(_clname); } int ByPassPage::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = MyBase::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
3bd7ea4dd2463bd5354a027ce54c90d1d5cb9cbd
d34b4df56264f411470bb0e99385f575a34eae8d
/p4c-bm/p4c_bm/templates/src/pd.cpp
44415d94ddc6f4521bb3362e8bb712207a623d20
[ "Apache-2.0" ]
permissive
evelinad/ops-p4c
17dfb0d2ad3bf583dc40deee68cdbc61fb3e881b
efd7f7b01ae9af2b92d821abc271aed183015b5c
refs/heads/master
2020-06-12T17:16:47.613630
2016-02-12T01:23:23
2016-02-12T01:23:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,273
cpp
/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas ([email protected]) * */ #include <cstring> #include "pd/pd.h" #include "pd_conn_mgr.h" #include "pd_notifications.h" extern pd_conn_mgr_t *conn_mgr_state; #define NUM_DEVICES 256 int *my_devices; extern "C" { void ${pd_prefix}learning_notification_cb(const char *hdr, const char *data); p4_pd_status_t ${pd_prefix}learning_new_device(int dev_id); p4_pd_status_t ${pd_prefix}learning_remove_device(int dev_id); void ${pd_prefix}ageing_notification_cb(const char *hdr, const char *data); p4_pd_status_t ${pd_prefix}ageing_new_device(int dev_id); p4_pd_status_t ${pd_prefix}ageing_remove_device(int dev_id); p4_pd_status_t ${pd_prefix}init(void) { my_devices = (int *) calloc(NUM_DEVICES, sizeof(int)); return 0; } p4_pd_status_t ${pd_prefix}assign_device(int dev_id, const char *notifications_addr, int rpc_port_num) { assert(!my_devices[dev_id]); ${pd_prefix}learning_new_device(dev_id); ${pd_prefix}ageing_new_device(dev_id); pd_notifications_add_device(dev_id, notifications_addr, ${pd_prefix}ageing_notification_cb, ${pd_prefix}learning_notification_cb); my_devices[dev_id] = 1; return pd_conn_mgr_client_init(conn_mgr_state, dev_id, rpc_port_num); } p4_pd_status_t ${pd_prefix}remove_device(int dev_id) { assert(my_devices[dev_id]); pd_notifications_remove_device(dev_id); ${pd_prefix}learning_remove_device(dev_id); ${pd_prefix}ageing_remove_device(dev_id); my_devices[dev_id] = 0; return pd_conn_mgr_client_close(conn_mgr_state, dev_id); } }
b419f4ccbc6a8eb5dc8877eb5369dbe82667dd74
9a12150c1672fa7b304a728d86e5434aafeb5120
/888A.cpp
d07c57f6cea7fb65e6ce4c885a655fc1e9565cb7
[]
no_license
apurvparekh30/codeforces
93b53f99d5d9e16f3d833f89418c8f7edfb63549
c18384a62ddfc514e4d087007a9717276d02a350
refs/heads/master
2021-07-24T20:04:29.526385
2020-08-01T05:10:25
2020-08-01T05:10:25
204,581,591
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
#include <bits/stdc++.h> using namespace std; int n; int arr[1001]; int main() { cin >> n; for(int i=0;i<n;i++) { cin >> arr[i]; } int ex_count = 0; for(int i=1;i<n-1;i++) { if(arr[i] < arr[i-1] && arr[i] < arr[i+1]) ex_count++; if(arr[i] > arr[i-1] && arr[i] > arr[i+1]) ex_count++; } cout << ex_count << "\n"; return 0; }
80285bf206df0734e362cd34e8ade7b658dc085b
1b6e1561cbe910195ee9c26b122663b94719a971
/комбинаторика/task4.cpp
346c9fe1a698976705bdd1197ebf39ac37144baa
[]
no_license
FADelto/ASD
e3b5df5b835ea3b616f2dd506b95e0cce91b3acf
cd85e79efcb119117d434a8d17d5f88cd49ce2d4
refs/heads/master
2022-03-05T19:46:02.595275
2019-10-09T08:25:08
2019-10-09T08:25:08
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,425
cpp
/* Задание 4. Переборный алгоритм Сколько существует четных чисел, принадлежащих диапазону [10^10;10^11), для которых выполняется правило: в записи числа не встречается подряд две цифры, являющихся простыми числами (2, 3, 5, 7)? */ #include <iostream> #include <ctime> using namespace std; // Проверка правила: в записи числа не встречается подряд две цифры, являющихся простыми числами (2, 3, 5, 7) bool two_digits_is_prime_nembers(unsigned __int64 n) { int count = 0; do { if (n % 10 == 2 || n % 10 == 3 || n % 10 == 5 || n % 10 == 7) { count += 1; if (count == 2) return true; } else count = 0; n /= 10; } while (n > 0); return false; } unsigned __int64 count_with_two_prime_numbers() { unsigned __int64 count = 0; for (unsigned __int64 i = pow(10,10); i < pow(10, 11); i++) if (!two_digits_is_prime_nembers(i) && i % 2 == 0) ++count; return count; } int main() { time_t start = clock(); cout << "Count even and two in a row prime numbers in range [10^10;10^11) = " << count_with_two_prime_numbers() << endl; cout.precision(20); cout << "; Time: " << double(clock() - start) / CLOCKS_PER_SEC << " seconds\n"; system("pause"); }
1e1e6739eced6723f1459d1dc7cf29dd5ae30b2f
dfec8731e6297a27121fd66859548ec25c406860
/OpenGL_Project/OpenGL_dependency/gem/src/projects/lit_particles/lit_particles_system.hh
04c51fb77c545dae3daa454ea1debe99f20ad800
[ "MIT" ]
permissive
felixyf0124/COMP477_F19_A2
6a8d6de71912c6116ab7e7cc0be166358bdbbe8a
80f96e130ef2715c3f10de25d1b973a60cc440e5
refs/heads/master
2020-08-26T20:17:28.525490
2020-02-07T21:44:30
2020-02-07T21:44:30
217,133,945
2
0
null
null
null
null
UTF-8
C++
false
false
1,845
hh
/************************************************************************* * Copyright (c) 2016 François Trudel * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * *************************************************************************/ #ifndef LIT_PARTICLES_SYSTEM_HH #define LIT_PARTICLES_SYSTEM_HH #include "core/particle_system.hh" #include "utils/light_module.hh" #include "projects/lit_particles/lit_particles_pool.hh" namespace gem { namespace particle { class LitParticleSystem : public ParticleSystem<LifeDeathCycle::Enabled,lit_particles_project::LitParticlesData> { DECLARE_UNCOPYABLE(LitParticleSystem) DECLARE_UNMOVABLE(LitParticleSystem) public: LitParticleSystem(std::size_t a_unMaxParticleCount, std::size_t lightsCount, const std::string& a_sSystemName = std::move(std::string("DEFAULT_SYS_NAME"))) : ParticleSystem<LifeDeathCycle::Enabled, lit_particles_project::LitParticlesData>(a_unMaxParticleCount, a_sSystemName) { m_pParticlePool->CreateLightIndexes(lightsCount); light::module::Resize(light::module::GetLightsCount() + lightsCount); } ~LitParticleSystem() = default; }; /* class ParticlePool*/ /*}*/ /* namespace lit_particles_project */ } /* namespace particle */ } /* namespace gem */ #endif /* end of include guard: LIT_PARTICLES_SYSTEM_HH */
548513704b708ae0640f51a6283855e0d72b9655
91eb400364e3d4157b719526e0c12ab089a43e31
/src/Client/ClientBaseHelpers.h
64fb0616647a6eeea8d6f62c5876b9e6b3a5266f
[ "Apache-2.0" ]
permissive
GaryXiangK/ClickHouse
aa96651b1b74226fcca7f1ddd8850830c69572bc
ec966b7df587bcaea5357cebfba6177c3ef75c3d
refs/heads/master
2023-07-31T10:38:52.673178
2021-10-01T13:18:52
2021-10-01T13:18:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
h
#pragma once #include <Core/Types.h> #if USE_REPLXX # include <common/ReplxxLineReader.h> #endif namespace DB { /// Should we celebrate a bit? bool isNewYearMode(); bool isChineseNewYearMode(const String & local_tz); #if USE_REPLXX void highlight(const String & query, std::vector<replxx::Replxx::Color> & colors); #endif }
3b5e15243f8fe5cdf92c000088ba8de94592494f
98cc7d0c00a6580885eb9f4278bfcad2b8b7186f
/src/BalanceServer/error.h
7b83d89f5efaf1c264d7952e4f70d2c07302467c
[]
no_license
liuhangyang/TSHH
800216ceffde27280b666932fdd239f5c58e3167
890dc070db118812824b3becc5121d9da7e2e2fb
refs/heads/master
2021-05-02T16:24:02.866599
2017-02-27T01:16:32
2017-02-27T01:16:32
65,291,519
3
1
null
2017-02-27T00:57:09
2016-08-09T12:01:10
C++
UTF-8
C++
false
false
611
h
// // Created by kiosk on 8/9/16. // #ifndef TSHH_BALANCE_ERROR_H #define TSHH_BALANCE_ERROR_H #include <errno.h> #include <string> #include <iostream> class error { public: error() = default; error(const std::string errmsg,int errline) { msg = errmsg; line = errline; } void show() { std::cerr << line << " : "; perror(msg.c_str()); } error set(const std::string errmsg, const int errline) { msg = errmsg; line = errline; return *this; } private: std::string msg; int line; }; #endif //TSHH_BALANCE_ERROR_H
a545f065fc397a158353eae200665c86a109c85a
58f46a28fc1b58f9cd4904c591b415c29ab2842f
/chromium-courgette-redacted-29.0.1547.57/chrome/browser/ui/webui/favicon_source.cc
45522732b755fe411cb35e45929c56361a6d8aee
[ "BSD-3-Clause" ]
permissive
bbmjja8123/chromium-1
e739ef69d176c636d461e44d54ec66d11ed48f96
2a46d8855c48acd51dafc475be7a56420a716477
refs/heads/master
2021-01-16T17:50:45.184775
2015-03-20T18:38:11
2015-03-20T18:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,148
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 "chrome/browser/ui/webui/favicon_source.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/top_sites.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/instant_io_context.h" #include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_factory.h" #include "chrome/common/url_constants.h" #include "grit/locale_settings.h" #include "grit/ui_resources.h" #include "net/url_request/url_request.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" #include "ui/webui/web_ui_util.h" namespace { // Parameters which can be used in chrome://favicon path. See .h file for a // description of what each does. const char kIconURLParameter[] = "iconurl/"; const char kLargestParameter[] = "largest/"; const char kOriginParameter[] = "origin/"; const char kSizeParameter[] = "size/"; // Returns true if |search| is a substring of |path| which starts at // |start_index|. bool HasSubstringAt(const std::string& path, size_t start_index, const std::string& search) { if (search.empty()) return false; if (start_index + search.size() >= path.size()) return false; return (path.compare(start_index, search.size(), search) == 0); } } // namespace FaviconSource::IconRequest::IconRequest() : size_in_dip(gfx::kFaviconSize), scale_factor(ui::SCALE_FACTOR_NONE) { } FaviconSource::IconRequest::IconRequest( const content::URLDataSource::GotDataCallback& cb, const GURL& path, int size, ui::ScaleFactor scale) : callback(cb), request_path(path), size_in_dip(size), scale_factor(scale) { } FaviconSource::IconRequest::~IconRequest() { } FaviconSource::FaviconSource(Profile* profile, IconType type) : profile_(profile->GetOriginalProfile()), icon_types_(type == FAVICON ? chrome::FAVICON : chrome::TOUCH_PRECOMPOSED_ICON | chrome::TOUCH_ICON | chrome::FAVICON) { } FaviconSource::~FaviconSource() { } std::string FaviconSource::GetSource() const { return icon_types_ == chrome::FAVICON ? chrome::kChromeUIFaviconHost : chrome::kChromeUITouchIconHost; } void FaviconSource::StartDataRequest( const std::string& path, int render_process_id, int render_view_id, const content::URLDataSource::GotDataCallback& callback) { FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS); if (!favicon_service) { SendDefaultResponse(callback); return; } bool is_icon_url = false; GURL url; int size_in_dip = 16; ui::ScaleFactor scale_factor = ui::SCALE_FACTOR_100P; bool success = ParsePath(path, &is_icon_url, &url, &size_in_dip, &scale_factor); if (!success) { SendDefaultResponse(callback); return; } if (is_icon_url) { // TODO(michaelbai): Change GetRawFavicon to support combination of // IconType. favicon_service->GetRawFavicon( url, chrome::FAVICON, size_in_dip, scale_factor, base::Bind(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), IconRequest(callback, url, size_in_dip, scale_factor)), &cancelable_task_tracker_); } else { // Intercept requests for prepopulated pages. for (size_t i = 0; i < arraysize(history::kPrepopulatedPages); i++) { if (url.spec() == l10n_util::GetStringUTF8(history::kPrepopulatedPages[i].url_id)) { callback.Run( ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( history::kPrepopulatedPages[i].favicon_id, scale_factor)); return; } } favicon_service->GetRawFaviconForURL( FaviconService::FaviconForURLParams( profile_, url, icon_types_, size_in_dip), scale_factor, base::Bind(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), IconRequest(callback, url, size_in_dip, scale_factor)), &cancelable_task_tracker_); } } std::string FaviconSource::GetMimeType(const std::string&) const { // We need to explicitly return a mime type, otherwise if the user tries to // drag the image they get no extension. return "image/png"; } bool FaviconSource::ShouldReplaceExistingSource() const { // Leave the existing DataSource in place, otherwise we'll drop any pending // requests on the floor. return false; } bool FaviconSource::ShouldServiceRequest(const net::URLRequest* request) const { if (request->url().SchemeIs(chrome::kChromeSearchScheme)) return InstantIOContext::ShouldServiceRequest(request); return URLDataSource::ShouldServiceRequest(request); } bool FaviconSource::HandleMissingResource(const IconRequest& request) { // No additional checks to locate the favicon resource in the base // implementation. return false; } bool FaviconSource::ParsePath(const std::string& path, bool* is_icon_url, GURL* url, int* size_in_dip, ui::ScaleFactor* scale_factor) const { DCHECK_EQ(16, gfx::kFaviconSize); *is_icon_url = false; *url = GURL(); *size_in_dip = 16; *scale_factor = ui::SCALE_FACTOR_100P; if (path.empty()) return false; size_t parsed_index = 0; if (HasSubstringAt(path, parsed_index, kLargestParameter)) { parsed_index += strlen(kLargestParameter); *size_in_dip = 0; } else if (HasSubstringAt(path, parsed_index, kSizeParameter)) { parsed_index += strlen(kSizeParameter); size_t slash = path.find("/", parsed_index); if (slash == std::string::npos) return false; size_t scale_delimiter = path.find("@", parsed_index); std::string size_str; std::string scale_str; if (scale_delimiter == std::string::npos) { // Support the legacy size format of 'size/aa/' where 'aa' is the desired // size in DIP for the sake of not regressing the extensions which use it. size_str = path.substr(parsed_index, slash - parsed_index); } else { size_str = path.substr(parsed_index, scale_delimiter - parsed_index); scale_str = path.substr(scale_delimiter + 1, slash - scale_delimiter - 1); } if (!base::StringToInt(size_str, size_in_dip)) return false; if (*size_in_dip != 64 && *size_in_dip != 32) { // Only 64x64, 32x32 and 16x16 icons are supported. *size_in_dip = 16; } if (!scale_str.empty()) webui::ParseScaleFactor(scale_str, scale_factor); // Return the default favicon (as opposed to a resized favicon) for // favicon sizes which are not cached by the favicon service. // Currently the favicon service caches: // - favicons of sizes "16 * scale factor" px of type FAVICON // where scale factor is one of FaviconUtil::GetFaviconScaleFactors(). // - the largest TOUCH_ICON / TOUCH_PRECOMPOSED_ICON if (*size_in_dip != 16 && icon_types_ == chrome::FAVICON) return false; parsed_index = slash + 1; } if (HasSubstringAt(path, parsed_index, kIconURLParameter)) { parsed_index += strlen(kIconURLParameter); *is_icon_url = true; *url = GURL(path.substr(parsed_index)); } else { // URL requests prefixed with "origin/" are converted to a form with an // empty path and a valid scheme. (e.g., example.com --> // http://example.com/ or http://example.com/a --> http://example.com/) if (HasSubstringAt(path, parsed_index, kOriginParameter)) { parsed_index += strlen(kOriginParameter); std::string possibly_invalid_url = path.substr(parsed_index); // If the URL does not specify a scheme (e.g., example.com instead of // http://example.com), add "http://" as a default. if (!GURL(possibly_invalid_url).has_scheme()) possibly_invalid_url = "http://" + possibly_invalid_url; // Strip the path beyond the top-level domain. *url = GURL(possibly_invalid_url).GetOrigin(); } else { *url = GURL(path.substr(parsed_index)); } } return true; } void FaviconSource::OnFaviconDataAvailable( const IconRequest& request, const chrome::FaviconBitmapResult& bitmap_result) { if (bitmap_result.is_valid()) { // Forward the data along to the networking system. request.callback.Run(bitmap_result.bitmap_data.get()); } else if (!HandleMissingResource(request)) { SendDefaultResponse(request); } } void FaviconSource::SendDefaultResponse( const content::URLDataSource::GotDataCallback& callback) { SendDefaultResponse( IconRequest(callback, GURL(), 16, ui::SCALE_FACTOR_100P)); } void FaviconSource::SendDefaultResponse(const IconRequest& icon_request) { int favicon_index; int resource_id; switch (icon_request.size_in_dip) { case 64: favicon_index = SIZE_64; resource_id = IDR_DEFAULT_FAVICON_64; break; case 32: favicon_index = SIZE_32; resource_id = IDR_DEFAULT_FAVICON_32; break; default: favicon_index = SIZE_16; resource_id = IDR_DEFAULT_FAVICON; break; } base::RefCountedMemory* default_favicon = default_favicons_[favicon_index].get(); if (!default_favicon) { ui::ScaleFactor scale_factor = icon_request.scale_factor; default_favicon = ResourceBundle::GetSharedInstance() .LoadDataResourceBytesForScale(resource_id, scale_factor); default_favicons_[favicon_index] = default_favicon; } icon_request.callback.Run(default_favicon); }
9cee6dfab1d1433ed692ae1cdfcb361f7d5cefac
c0d291eed180ef5c03cf818dd501faa2c435c8b2
/DynamicLibrary/UnixDynaLib.cpp
e03343507f89b5614b1275bc4ece29cf843e6f67
[]
no_license
alex-min/rtype-2014-minetta
61e27ce2813fd499f1eb95a2b1fa53673c563cc5
442c6a472b9c50e3d586a6dcea40317356417a9e
refs/heads/master
2016-08-12T06:34:30.565350
2012-01-31T10:36:11
2012-01-31T10:36:11
46,982,048
0
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
#include "UnixDynaLib.hpp" UnixDynaLib::UnixDynaLib() { } void UnixDynaLib::dynaLoad(std::string libName) { libName += ".so"; _handle = dlopen(libName.c_str(), RTLD_LAZY); if (_handle == NULL) throw Exception(dlerror()); dlerror(); } void *UnixDynaLib::funcLoad(std::string funcName) { char *error; void *tmp = dlsym(_handle, funcName.c_str()); if ((error = dlerror()) != NULL) { throw Exception(error); } return (tmp); } void UnixDynaLib::dynaFree() { if (_handle) { dlclose(_handle); } }
75387416f9fe9828cd3407b39aac6b681fd6f711
a3b8cf0df20ccfbed4ed73ebe67dc2e7cfcf0d7b
/Task4_Tim/Source.cpp
7d5137e855719b2fb390504a130bc5784a8a883b
[]
no_license
anon20016/Modelirovanie
b6c86a173f0d77024e34622719c21ae4f92cc07f
d248711bf1cb40c991007c542f40043b436f557c
refs/heads/master
2022-12-26T13:10:48.533346
2020-10-14T10:05:10
2020-10-14T10:05:10
262,797,207
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,892
cpp
#include <iostream> #include <set> #include <map> #include <algorithm> #include <time.h> #include <vector> #include <random> using namespace std; // // 0 0 5 // 0 7 6 // bool ispointincircle(double x, double y, double xc, double yc, double r) { // Функция проверяет принадлежит ли точка окружности return (x - xc) * (x - xc) + (y - yc) * (y - yc) <= r * r; } int main() { std::random_device rd; std::mt19937 gen(rd()); // В этой задаче на вход подаётся информация о двух окружностях // x1 y1 r1 // x2 y2 r2 // Берется прямоугольник в который помещаются обе окружности так, что они касаются сторон прямоугольника. // Методом Монте-Карло считается площадь пересечения. double x1, x2, y1, y2, r1, r2; cin >> x1 >> y1 >> r1; cin >> x2 >> y2 >> r2; double xmin = min(x1 - r1, x2 - r2); double xmax = max(x1 + r1, x2 + r1); // Считаются координаты углов прямоугольника. double ymin = min(y1 - r2, y2 - r2); double ymax = max(y1 + r2, y2 + r2); // Генераторы для выбора случайной точки внутри прямоугольника std::uniform_real_distribution<> d1(xmin, xmax); std::uniform_real_distribution<> d2(ymin, ymax); // Проведение эксперимента double s = 0; vector<double> r; for (int i = 0; i < 10000; i++) { double x = d1(gen); double y = d2(gen); if (ispointincircle(x, y, x1, y1, r1) and ispointincircle(x, y, x2, y2, r2)) { s++; } } cout << "Square: " << ((xmax - xmin) * (ymax - ymin)) * s / 10000; }
b4d88027ba0f0769e92a9a77a3005d8bf783832f
07427bde05816a58facb0c3573bbb753f9b312c9
/Weekly Assessments and Exercises/Week 7/Exercise 2/pinChangeInterrupt.ino
cf222f30c6813182898b42b5df262830dcad8e8f
[]
no_license
AimanCheong/MCTE_4342_Embedded_System_Design
cc634043f72fd4d69644555073869358b683bfe7
0c6d0168bb902f49231dd966bbd7d30b5d8bff06
refs/heads/main
2023-02-21T11:44:23.902456
2021-01-21T09:31:00
2021-01-21T09:31:00
309,981,539
0
0
null
null
null
null
UTF-8
C++
false
false
734
ino
volatile bool changed; unsigned char* sreg = (unsigned char*) 0x5F; unsigned char* pcicr = (unsigned char*) 0x68; unsigned char* pcmsk0 = (unsigned char*) 0x6B; void setup() { *sreg |= (1 << 7); //Enable interrupts in general *pcicr = 1; //Enable pin change interrupt 0 *pcmsk0 = 255; //Enable pin change interrupt on all the Port B pin Serial.begin(9600); while (1) { if (changed) { Serial.println("Sensor values changed"); //Perform necessary investigation and subsequent operations changed = 0; } //Do other things or go back to sleep //Sleep(); //There is no such function called ‘Sleep’. Just for demo. } } ISR(PCINT0_vect) { changed = 1; }
114267fc57fd8b2b19eb2d0fae262850aff1049e
21e8ed6d923068e56c988a77b29bd7fc19da958a
/src/test/script_P2PKH_tests.cpp
13512ad16d832be72e1b82e0fd2165a0625fd147
[ "MIT" ]
permissive
BTC-Tech/Blockcoin
2f98130672ab3c30c8553cda65b84fa3724f2ced
9a1ff83c267107112246b7ce3443b67889ab76b6
refs/heads/master
2020-05-19T03:01:25.657939
2019-05-06T09:43:55
2019-05-06T09:43:55
184,791,344
2
0
null
null
null
null
UTF-8
C++
false
false
2,246
cpp
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/script.h" #include "test/test_blockcoin.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(script_P2PKH_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(IsPayToPublicKeyHash) { // Test CScript::IsPayToPublicKeyHash() uint160 dummy; CScript p2pkh; p2pkh << OP_DUP << OP_HASH160 << ToByteVector(dummy) << OP_EQUALVERIFY << OP_CHECKSIG; BOOST_CHECK(p2pkh.IsPayToPublicKeyHash()); static const unsigned char direct[] = { OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG }; BOOST_CHECK(CScript(direct, direct+sizeof(direct)).IsPayToPublicKeyHash()); static const unsigned char notp2pkh1[] = { OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG, OP_CHECKSIG }; BOOST_CHECK(!CScript(notp2pkh1, notp2pkh1+sizeof(notp2pkh1)).IsPayToPublicKeyHash()); static const unsigned char p2sh[] = { OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL }; BOOST_CHECK(!CScript(p2sh, p2sh+sizeof(p2sh)).IsPayToPublicKeyHash()); static const unsigned char extra[] = { OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG, OP_CHECKSIG }; BOOST_CHECK(!CScript(extra, extra+sizeof(extra)).IsPayToPublicKeyHash()); static const unsigned char missing[] = { OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG, OP_RETURN }; BOOST_CHECK(!CScript(missing, missing+sizeof(missing)).IsPayToPublicKeyHash()); static const unsigned char missing2[] = { OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; BOOST_CHECK(!CScript(missing2, missing2+sizeof(missing2)).IsPayToPublicKeyHash()); static const unsigned char tooshort[] = { OP_DUP, OP_HASH160, 2, 0,0, OP_EQUALVERIFY, OP_CHECKSIG }; BOOST_CHECK(!CScript(tooshort, tooshort+sizeof(tooshort)).IsPayToPublicKeyHash()); } BOOST_AUTO_TEST_SUITE_END()
754b4539e44fc215dd18ebac6928b24a76d9a40a
7689de51f8641eb43493685e8cbf962d1b79c9fb
/newbasic/date_filter_msg_buffer.h
1cf40980660561a10b97fe6c337b1839685b48d8
[]
no_license
sPHENIX-Collaboration/online_distribution
f229323fc848092d873524ab16458eb5bfc0ea5e
f87aeaacc79f8b7babad8804e648b0f87a6e01db
refs/heads/master
2023-09-01T09:35:33.711931
2023-08-24T15:56:35
2023-08-24T15:56:35
84,598,252
4
18
null
2023-06-28T23:13:03
2017-03-10T20:29:17
C++
UTF-8
C++
false
false
1,015
h
#ifndef __DATE_FILTER_MSG_BUFFER_CC__ #define __DATE_FILTER_MSG_BUFFER_CC__ #include "filter_msg_buffer.h" #define ON 1 #define OFF 0 /** This is the "date\_filter" msg\_buffer class which allows you to filter messages based on their profile. Itacts much like the filter\_msg\_buffer, but it also prepends a date tag to messages which have a profile. */ class date_filter_msg_buffer : public filter_msg_buffer { public: /** The msglen parameter specifies the initial length of the message string which is kept internally. If you exceed the length, it is automautically extended. */ date_filter_msg_buffer (const int msglen=256); /** This constructor defines a custom-sized matrix of type/source/severities. */ date_filter_msg_buffer (const int type_max, const int source_max, const int sev_max, const int msglen=256); /// the virtual destructor virtual ~date_filter_msg_buffer(); virtual int sync (); }; #endif /* __DATE_FILTER_MSG_BUFFER_CC__ */
5656860e2b4ad976e288c2ecb744c9b58e799990
95e95426db170526b269e60b162ff9f0c36ab3b0
/thermostat_client/include/TemperatureSensor.hpp
b1b3708e18b8eccce824045021721b133db2e90a
[]
no_license
AcumenDev/climate_datalogger_client
2cd69e35c34664cdfc7779eaf92e4e2223524c45
6ca862b3742729ea776ccc18acc8c0f1acbddb20
refs/heads/master
2018-12-20T16:49:33.654959
2018-12-09T22:58:35
2018-12-09T22:58:35
115,912,110
0
0
null
null
null
null
UTF-8
C++
false
false
413
hpp
// // Created by vst on 5/22/18. // #ifndef ESP_TEMPERATURESENSOR_HPP #define ESP_TEMPERATURESENSOR_HPP #include <OneWire.h> #include <DallasTemperature.h> class TemperatureSensor { OneWire *oneWire; DallasTemperature *ds; uint8_t sensorAdr[8]; const uint8_t *searchSensors(); public: TemperatureSensor(uint8_t pin); float getTemperature(); }; #endif //ESP_TEMPERATURESENSOR_HPP
7ca6cee12f7c113cabf75ee27ea7419feecd244f
349f0ae175c2ae449fdcc17b10f49ef2ec3d2dde
/World.cpp
51e5a23af8d23c4a8dd2d7665ad38bd962151d5b
[]
no_license
scottrick/mcparse
088425a9ee6d6d827e91fa41ffb29ae33b99448f
01cb3a0e7c172be22325ffa86839dd92f9fc2533
refs/heads/master
2021-01-18T15:22:19.183663
2013-10-05T15:14:09
2013-10-05T15:14:09
2,075,508
0
0
null
null
null
null
UTF-8
C++
false
false
1,317
cpp
#include "World.h" #include "Chunk.h" #include <iostream> using namespace std; World::World(void) { } World::~World(void) { deleteChunks(); } void World::addRegion(Region *pRegion) { const list<Chunk *> chunks = pRegion->getChunks(); list<Chunk *>::const_iterator iter; unsigned int MAX = 50000; for (iter = chunks.begin(); iter != chunks.end(); iter++) { Chunk *pChunk = *iter; pChunk->addRef(); pChunk->setWorld(this); m_Chunks[pChunk->getLoc()] = pChunk; if (m_Chunks.size() >= MAX) { break; } } } void World::deleteChunks() { map<const ChunkLoc, Chunk *>::const_iterator iter; for (iter = m_Chunks.begin(); iter != m_Chunks.end(); iter++) { pair<const ChunkLoc, Chunk*> item = *iter; Chunk *pChunk = item.second; pChunk->release(); } m_Chunks.clear(); } void World::dump() const { map<const ChunkLoc, Chunk *>::const_iterator iter; for (iter = m_Chunks.begin(); iter != m_Chunks.end(); iter++) { pair<const ChunkLoc, Chunk*> item = *iter; ChunkLoc loc = item.first; Chunk *pChunk = item.second; cout << "(" << loc.x << ", " << loc.z << ")" << endl; } } Chunk *World::getChunk(ChunkLoc &loc) { return m_Chunks[loc]; } map<ChunkLoc, Chunk *> World::getChunks() const { return m_Chunks; } const char *World::getClassName() const { return "World"; }