blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e1f04095e61c5cb215d2dc48baab41f1c2368fc4
|
6247051fc105ee0f7847c9ad7d64e6dd22e2e5e2
|
/codeforces/701-B/701-B-19438425.cpp
|
2f138208111291ba0ae6f5c8153c72052556f7df
|
[] |
no_license
|
satishrdd/comp-coding
|
5aa01c79bd1269287f588a064d5d09f824daa8fd
|
96d22817488d55623d77a2e7f3d4ef0955028086
|
refs/heads/master
| 2020-04-07T06:50:53.743622
| 2017-04-16T09:05:25
| 2017-04-16T09:05:25
| 46,654,615
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 490
|
cpp
|
701-B-19438425.cpp
|
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<set>
using namespace std;
int main(int argc, char const *argv[])
{
/* code */
long long m,n;
cin>>n>>m;
long long res =n*n;
bool l1[n+1];
bool l2[n+1];
memset(l1,0,sizeof(l1));
memset(l2,0,sizeof(l2));
long long a =n,b=n;
while(m--){
long long x,y,c=0,d=0;
cin>>x>>y;
if(!l1[x]){
l1[x]=1;
res= res-a;
c=1;
}
b = b-c;
if(!l2[y]){
l2[y]=1;
res = res-b;
d=1;
}
a = a -d;
cout<<res<<endl;
}
return 0;
}
|
11654f22f0d22983f4f10728f6b2690b7770c9d0
|
a88f0ca4bc31b40ab414476f0a0df733418ff038
|
/Include/GXCommon/Posix/GXMutex.h
|
8a7f45edba0d5d9feaa133684ca84d3fc72885f8
|
[] |
no_license
|
Goshido/GXEngine-Windows-OS-x64
|
8c9011442a5ef47a3c2864bdc7e6471e622763d5
|
10a1428d0284552856528d519283295388eea35b
|
refs/heads/master
| 2020-06-28T16:59:26.904805
| 2019-11-24T06:07:03
| 2019-11-24T06:09:40
| 74,490,143
| 11
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 310
|
h
|
GXMutex.h
|
//version 1.0
#ifndef GX_MUTEX_POSIX
#define GX_MUTEX_POSIX
#include "../GXTypes.h"
#include <pthread.h>
class GXMutex
{
private:
pthread_mutex_t _mutex;
public:
GXMutex ();
~GXMutex ();
GXVoid Lock ();
GXVoid Release ();
};
#endif //GX_MUTEX_POSIX
|
cffba9512f512c851694e13eb9c40d413090bcce
|
e6d4a87dcf98e93bab92faa03f1b16253b728ac9
|
/algorithms/cpp/kthSmallestInstructions/kthSmallestInstructions.cpp
|
bbcab8a9b3002a383cacd7faa767d4f79a018d32
|
[] |
no_license
|
MichelleZ/leetcode
|
b5a58e1822e3f6ef8021b29d9bc9aca3fd3d416f
|
a390adeeb71e997b3c1a56c479825d4adda07ef9
|
refs/heads/main
| 2023-03-06T08:16:54.891699
| 2023-02-26T07:17:47
| 2023-02-26T07:17:47
| 326,904,500
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,061
|
cpp
|
kthSmallestInstructions.cpp
|
// Source: https://leetcode.com/problems/kth-smallest-instructions/
// Author: Miao Zhang
// Date: 2021-05-25
class Solution {
public:
string kthSmallestPath(vector<int>& destination, int k) {
int v = destination[0];
int h = destination[1];
vector<vector<int>> comb(h + v, vector<int>(h));
comb[0][0] = 1;
for (int i = 1; i < h + v; i++) {
comb[i][0] = 1;
for (int j = 1; j <= i && j < h; j++) {
comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j];
}
}
string res;
for (int i = 0; i < destination[0] + destination[1]; i++) {
if (h > 0) {
int tmp = comb[h + v - 1][h - 1];
if (k > tmp) {
res += 'V';
v--;
k -= tmp;
} else {
res += 'H';
h--;
}
} else {
res += 'V';
v--;
}
}
return res;
}
};
|
769f0c8165d21c32ce1de4ef180da0ad53c79f74
|
a21d7710b1d193ae7ee12205c2af2c47db09905e
|
/LeetCode/Explore/June-LeetCoding-Challenge-2021/#Day#29_MaxConsecutiveOnesIII_sol3_prefix_sum_and_lower_bound_O(NlogN)_time_O(N)_extra_space_96ms_57.8MB.cpp
|
75f7e907fd6d39f4becc69a7b706636024ada7a9
|
[
"MIT"
] |
permissive
|
Tudor67/Competitive-Programming
|
0db89e0f8376cac7c058185b84fdf11dcb99dae8
|
827cabc45951ac33f63d1d6e69e57897207ea666
|
refs/heads/master
| 2023-08-19T05:22:10.451067
| 2023-08-14T21:21:51
| 2023-08-14T21:21:51
| 243,604,510
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 685
|
cpp
|
#Day#29_MaxConsecutiveOnesIII_sol3_prefix_sum_and_lower_bound_O(NlogN)_time_O(N)_extra_space_96ms_57.8MB.cpp
|
class Solution {
public:
int longestOnes(vector<int>& nums, int k) {
const int N = nums.size();
vector<int> zerosPrefixSum(N);
zerosPrefixSum[0] = (nums[0] == 0);
for(int i = 1; i < N; ++i){
zerosPrefixSum[i] = zerosPrefixSum[i - 1] + (nums[i] == 0);
}
int maxLen = 0;
for(int i = 0; i < N; ++i){
int j = lower_bound(zerosPrefixSum.begin() + i, zerosPrefixSum.end(), zerosPrefixSum[i] - (nums[i] == 0) + k + 1) - zerosPrefixSum.begin() - 1;
int len = j - i + 1;
maxLen = max(len, maxLen);
}
return maxLen;
}
};
|
22eaba72a4f721832bf837dd79f3d6031a689e7b
|
ae6dbcfd6a333bf598b871e15a7741fef81f964f
|
/Projects/Protect/src/ApiProtectObjectModelTests/TestDocument.h
|
7aedbb98056593560285a652ac31a1facf49672e
|
[] |
no_license
|
xeon2007/WSProf
|
7d431ec6a23071dde25226437583141f68ff6f85
|
d02c386118bbd45237f6defa14106be8fd989cd0
|
refs/heads/master
| 2016-11-03T17:25:02.997045
| 2015-12-08T22:04:14
| 2015-12-08T22:04:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 665
|
h
|
TestDocument.h
|
#pragma once
#include "..\ApiProtectObjectModel\workshare\protect\document.h"
#include "..\ApiProtectObjectModel\Workshare\Protect\application.h"
class TestDocument :
public TestCase
{
public:
TestDocument(std::tstring name) : TestCase(name), m_pDocument(0) {}
virtual ~TestDocument();
static Test* suite();
void setUp();
void tearDown();
public:
virtual std::wstring GetExpectedFullPath() const;
virtual std::wstring GetExpectedPath() const;
virtual std::wstring GetExpectedName() const;
protected:
void TestGetPath();
void TestGetName();
protected:
Workshare::Protect::Document* m_pDocument;
Workshare::Protect::Application* m_pApplication;
};
|
9470393595685a144fe7183fb52e5382d2fed64c
|
f242f69df361d871d6c8f512f9dacb2210fef9f6
|
/SCS_openMesh/CSM/cityModule/cityScene.h
|
1a70eaa55bc84eae37e965733bd75f8a402ec970
|
[] |
no_license
|
joilee/MCV_Platform
|
c4796957b08038dc9689f29825f36291728c7573
|
51760e54c6ab2bd32928b1d12d273e22f63339c0
|
refs/heads/master
| 2018-07-08T20:03:14.667927
| 2018-06-09T03:29:11
| 2018-06-09T03:29:11
| 110,204,214
| 1
| 1
| null | 2018-05-26T02:10:38
| 2017-11-10T04:54:36
|
C++
|
GB18030
|
C++
| false
| false
| 1,607
|
h
|
cityScene.h
|
#pragma once
#include "../util/vector.h"
#include "../util/emxUtilityInc.h"
#include <vector>
#include <string>
#include "cityGroundVector.h"
#include "cityBuilding.h"
using namespace std;
/*
建筑物类
包含:建筑物数组、地面模型
*/
class cityScene
{
public:
/*
@brief 从本地读文件
*/
cityScene(vector<string> _v, vector<string> _h, string _p);
/*
@brief 从整体生成局部场景
*/
cityScene(Vector3d center, double range, cityScene* cityAll);
~cityScene();
cityGroundVector *getGround();
double getAltitude(double x, double y);
vector<Building>& getTotal_Building(){ return total_Buildings; }
inline size_t getBuildingSize(){ return total_Buildings.size(); }
inline int getConcaveNum(){ return concave_num; }
const Building& getBuildingByReference(int id){ return total_Buildings[id]; }
Building getBuildingByValue(int id){ return total_Buildings[id]; }
inline Vector3d getMaxPoint(){ return MaxPoint; }
inline Vector3d getMinPoint(){ return MinPoint; }
inline vector<Vedge>& getAPEdge(){ return AP_Edge_list; }
inline vector<int>& getAPEdgeID(){ return Vertical_Edge_ID; }
private:
void readBuilding(const char*filename_2D, const char*filename_Height);
void readGround(string p);
private:
vector<Building> total_Buildings;
int concave_num;
Vector3d MaxPoint, MinPoint;
//地面模型数组
cityGroundVector * ground;
vector<Vedge> AP_Edge_list;
vector<int> Vertical_Edge_ID;
//找出局部场景中所有的棱边,以便于考虑绕射时所需,实际上仅考虑建筑物棱边
void GenerateEdge();
};
|
9306848eb293974c268c216ed08c02a7df0c6207
|
dfa0014b3b2e1140694788dd8f385301588ebcbe
|
/P2/cadena.hpp
|
52fd4ba1e7cd50c79eb47bc9af1feaaf92f40da2
|
[] |
no_license
|
aleeeesf/POO
|
8af267109092887feb69b370dbae57c8ab1753a4
|
2f01eb19d0d89612f9794c09135c3372bd433e1e
|
refs/heads/master
| 2022-09-18T18:06:16.105189
| 2020-06-04T19:12:35
| 2020-06-04T19:12:35
| 265,229,444
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,845
|
hpp
|
cadena.hpp
|
#ifndef CADENA_HPP_
#define CADENA_HPP_
#include <iostream>
#include <cstring>
#include <iterator>
#include <string>
using namespace std;
class Cadena{
public:
/*Constructores*/
explicit Cadena(unsigned t = 0,char c = ' ');
Cadena(const char*);
Cadena(const Cadena&);
Cadena(Cadena&&);
~Cadena();
//void mostrarcadena() noexcept; //Funcion de prueba
/*Funciones consultoras*/
const unsigned length()const noexcept;
char& at(unsigned) const;
const char* c_str() const{return s_;};
Cadena substr(unsigned, const int&) const;
/*Sobrecarga de operadores*/
char& operator[](unsigned);
char operator[](unsigned) const;
Cadena& operator =(const char*);
Cadena& operator =(Cadena&& cad);
Cadena& operator =(const Cadena&);
Cadena& operator +=(const Cadena&);
//Cadena& operator +=(const char*);
/*Sobrecarga de iteradores*/
typedef char* iterator;
typedef const char* const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
const_iterator cbegin() const;
const_iterator cend() const;
const_reverse_iterator rbegin() const;
const_reverse_iterator rend() const;
const_reverse_iterator crbegin() const;
const_reverse_iterator crend() const;
reverse_iterator rbegin();
reverse_iterator rend();
private:
char *s_;
unsigned tam_;
};
/* SOBRECARGA OPERADORES BINARIOS */
Cadena operator +(const Cadena&,const Cadena&);
bool operator <(const Cadena&,const Cadena&);
bool operator >(const Cadena&,const Cadena&);
bool operator ==(const Cadena&,const Cadena&);
bool operator <=(const Cadena&,const Cadena&);
bool operator >=(const Cadena&,const Cadena&);
bool operator !=(const Cadena&,const Cadena&);
/* SOBRECARGA OPERADORES E/S */
std::ostream& operator<<(std::ostream& os, const Cadena&);
std::istream& operator>>(std::istream& is, Cadena&);
// Para P2 y ss.// Especialización de la plantilla hash<T> para definir la
// función hash a utilizar con contenedores desordenados de// Cadena, unordered_[set|map|multiset|multimap]
namespace std{ // Estaremos dentro del espacio de nombres std
template<> // Es una especialización de una plantilla para Cadena
struct hash<Cadena> { // Es una clase con solo un operador publico
size_t operator() (const Cadena& cad) const // El operador función
{
hash<string> hs; // Creamos un objeto hash de string
const char *p = cad.c_str(); // Obtenemos la cadena de la Cadena
string s(p); // Creamos un string desde una cadena
size_t res = hs(s); // El hash del string. Como hs.operator()(s);
return res; // Devolvemos el hash del string
}
};
}
#endif
|
658b49f69306fb88d51c99f8bd8a6bbec25b08fb
|
03b5b626962b6c62fc3215154b44bbc663a44cf6
|
/src/keywords/__m128.cpp
|
aac7b35f8b271c43a8450b386cb91bfa42202bc7
|
[] |
no_license
|
haochenprophet/iwant
|
8b1f9df8ee428148549253ce1c5d821ece0a4b4c
|
1c9bd95280216ee8cd7892a10a7355f03d77d340
|
refs/heads/master
| 2023-06-09T11:10:27.232304
| 2023-05-31T02:41:18
| 2023-05-31T02:41:18
| 67,756,957
| 17
| 5
| null | 2018-08-11T16:37:37
| 2016-09-09T02:08:46
|
C++
|
UTF-8
|
C++
| false
| false
| 157
|
cpp
|
__m128.cpp
|
#include "__m128.h"
int C__m128::my_init(void *p)
{
this->name = "C__m128";
this->alias = "__m128";
return 0;
}
C__m128::C__m128()
{
this->my_init();
}
|
19b3d95e3911f165d7e89b4e60f5b76814e93ec2
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/webrtc/video/video_send_stream_impl_unittest.cc
|
c88ad06cfb4160a9def4eebf2261fbe0b5ab2051
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C++
| false
| false
| 40,069
|
cc
|
video_send_stream_impl_unittest.cc
|
/*
* Copyright 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "video/video_send_stream_impl.h"
#include <algorithm>
#include <memory>
#include <string>
#include "absl/types/optional.h"
#include "api/rtc_event_log/rtc_event_log.h"
#include "api/sequence_checker.h"
#include "api/task_queue/task_queue_base.h"
#include "api/units/time_delta.h"
#include "api/units/timestamp.h"
#include "call/rtp_video_sender.h"
#include "call/test/mock_bitrate_allocator.h"
#include "call/test/mock_rtp_transport_controller_send.h"
#include "modules/rtp_rtcp/source/rtp_sequence_number_map.h"
#include "modules/video_coding/fec_controller_default.h"
#include "rtc_base/event.h"
#include "rtc_base/experiments/alr_experiment.h"
#include "rtc_base/fake_clock.h"
#include "rtc_base/logging.h"
#include "test/gmock.h"
#include "test/gtest.h"
#include "test/mock_transport.h"
#include "test/scoped_key_value_config.h"
#include "test/time_controller/simulated_time_controller.h"
#include "video/test/mock_video_stream_encoder.h"
#include "video/video_send_stream.h"
namespace webrtc {
bool operator==(const BitrateAllocationUpdate& a,
const BitrateAllocationUpdate& b) {
return a.target_bitrate == b.target_bitrate &&
a.round_trip_time == b.round_trip_time &&
a.packet_loss_ratio == b.packet_loss_ratio;
}
namespace internal {
namespace {
using ::testing::_;
using ::testing::AllOf;
using ::testing::Field;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::Return;
constexpr int64_t kDefaultInitialBitrateBps = 333000;
const double kDefaultBitratePriority = 0.5;
const float kAlrProbingExperimentPaceMultiplier = 1.0f;
std::string GetAlrProbingExperimentString() {
return std::string(
AlrExperimentSettings::kScreenshareProbingBweExperimentName) +
"/1.0,2875,80,40,-60,3/";
}
class MockRtpVideoSender : public RtpVideoSenderInterface {
public:
MOCK_METHOD(void, SetActiveModules, (const std::vector<bool>&), (override));
MOCK_METHOD(void, Stop, (), (override));
MOCK_METHOD(bool, IsActive, (), (override));
MOCK_METHOD(void, OnNetworkAvailability, (bool), (override));
MOCK_METHOD((std::map<uint32_t, RtpState>),
GetRtpStates,
(),
(const, override));
MOCK_METHOD((std::map<uint32_t, RtpPayloadState>),
GetRtpPayloadStates,
(),
(const, override));
MOCK_METHOD(void, DeliverRtcp, (const uint8_t*, size_t), (override));
MOCK_METHOD(void,
OnBitrateAllocationUpdated,
(const VideoBitrateAllocation&),
(override));
MOCK_METHOD(void,
OnVideoLayersAllocationUpdated,
(const VideoLayersAllocation&),
(override));
MOCK_METHOD(EncodedImageCallback::Result,
OnEncodedImage,
(const EncodedImage&, const CodecSpecificInfo*),
(override));
MOCK_METHOD(void, OnTransportOverheadChanged, (size_t), (override));
MOCK_METHOD(void,
OnBitrateUpdated,
(BitrateAllocationUpdate, int),
(override));
MOCK_METHOD(uint32_t, GetPayloadBitrateBps, (), (const, override));
MOCK_METHOD(uint32_t, GetProtectionBitrateBps, (), (const, override));
MOCK_METHOD(void, SetEncodingData, (size_t, size_t, size_t), (override));
MOCK_METHOD(std::vector<RtpSequenceNumberMap::Info>,
GetSentRtpPacketInfos,
(uint32_t ssrc, rtc::ArrayView<const uint16_t> sequence_numbers),
(const, override));
MOCK_METHOD(void, SetFecAllowed, (bool fec_allowed), (override));
};
BitrateAllocationUpdate CreateAllocation(int bitrate_bps) {
BitrateAllocationUpdate update;
update.target_bitrate = DataRate::BitsPerSec(bitrate_bps);
update.packet_loss_ratio = 0;
update.round_trip_time = TimeDelta::Zero();
return update;
}
} // namespace
class VideoSendStreamImplTest : public ::testing::Test {
protected:
VideoSendStreamImplTest()
: time_controller_(Timestamp::Seconds(1000)),
config_(&transport_),
send_delay_stats_(time_controller_.GetClock()),
encoder_queue_(time_controller_.GetTaskQueueFactory()->CreateTaskQueue(
"encoder_queue",
TaskQueueFactory::Priority::NORMAL)),
stats_proxy_(time_controller_.GetClock(),
config_,
VideoEncoderConfig::ContentType::kRealtimeVideo,
field_trials_) {
config_.rtp.ssrcs.push_back(8080);
config_.rtp.payload_type = 1;
EXPECT_CALL(transport_controller_, packet_router())
.WillRepeatedly(Return(&packet_router_));
EXPECT_CALL(transport_controller_, CreateRtpVideoSender)
.WillRepeatedly(Return(&rtp_video_sender_));
ON_CALL(rtp_video_sender_, Stop()).WillByDefault(::testing::Invoke([&] {
active_modules_.clear();
}));
ON_CALL(rtp_video_sender_, IsActive())
.WillByDefault(::testing::Invoke([&]() {
for (bool enabled : active_modules_) {
if (enabled)
return true;
}
return false;
}));
ON_CALL(rtp_video_sender_, SetActiveModules)
.WillByDefault(::testing::SaveArg<0>(&active_modules_));
}
~VideoSendStreamImplTest() {}
std::unique_ptr<VideoSendStreamImpl> CreateVideoSendStreamImpl(
int initial_encoder_max_bitrate,
double initial_encoder_bitrate_priority,
VideoEncoderConfig::ContentType content_type) {
EXPECT_CALL(bitrate_allocator_, GetStartBitrate(_))
.WillOnce(Return(123000));
std::map<uint32_t, RtpState> suspended_ssrcs;
std::map<uint32_t, RtpPayloadState> suspended_payload_states;
auto ret = std::make_unique<VideoSendStreamImpl>(
time_controller_.GetClock(), &stats_proxy_, &transport_controller_,
&bitrate_allocator_, &video_stream_encoder_, &config_,
initial_encoder_max_bitrate, initial_encoder_bitrate_priority,
content_type, &rtp_video_sender_, field_trials_);
// The call to GetStartBitrate() executes asynchronously on the tq.
// Ensure all tasks get to run.
time_controller_.AdvanceTime(TimeDelta::Zero());
testing::Mock::VerifyAndClearExpectations(&bitrate_allocator_);
return ret;
}
protected:
GlobalSimulatedTimeController time_controller_;
webrtc::test::ScopedKeyValueConfig field_trials_;
NiceMock<MockTransport> transport_;
NiceMock<MockRtpTransportControllerSend> transport_controller_;
NiceMock<MockBitrateAllocator> bitrate_allocator_;
NiceMock<MockVideoStreamEncoder> video_stream_encoder_;
NiceMock<MockRtpVideoSender> rtp_video_sender_;
std::vector<bool> active_modules_;
RtcEventLogNull event_log_;
VideoSendStream::Config config_;
SendDelayStats send_delay_stats_;
std::unique_ptr<TaskQueueBase, TaskQueueDeleter> encoder_queue_;
SendStatisticsProxy stats_proxy_;
PacketRouter packet_router_;
};
TEST_F(VideoSendStreamImplTest, RegistersAsBitrateObserverOnStart) {
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillOnce(Invoke(
[&](BitrateAllocatorObserver*, MediaStreamAllocationConfig config) {
EXPECT_EQ(config.min_bitrate_bps, 0u);
EXPECT_EQ(config.max_bitrate_bps, kDefaultInitialBitrateBps);
EXPECT_EQ(config.pad_up_bitrate_bps, 0u);
EXPECT_EQ(config.enforce_min_bitrate, !kSuspend);
EXPECT_EQ(config.bitrate_priority, kDefaultBitratePriority);
}));
vss_impl->StartPerRtpStream({true});
EXPECT_CALL(bitrate_allocator_, RemoveObserver(vss_impl.get())).Times(1);
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, UpdatesObserverOnConfigurationChange) {
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(RtpExtension::kTransportSequenceNumberUri,
1);
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
vss_impl->StartPerRtpStream({true});
// QVGA + VGA configuration matching defaults in
// media/engine/simulcast.cc.
VideoStream qvga_stream;
qvga_stream.width = 320;
qvga_stream.height = 180;
qvga_stream.max_framerate = 30;
qvga_stream.min_bitrate_bps = 30000;
qvga_stream.target_bitrate_bps = 150000;
qvga_stream.max_bitrate_bps = 200000;
qvga_stream.max_qp = 56;
qvga_stream.bitrate_priority = 1;
VideoStream vga_stream;
vga_stream.width = 640;
vga_stream.height = 360;
vga_stream.max_framerate = 30;
vga_stream.min_bitrate_bps = 150000;
vga_stream.target_bitrate_bps = 500000;
vga_stream.max_bitrate_bps = 700000;
vga_stream.max_qp = 56;
vga_stream.bitrate_priority = 1;
int min_transmit_bitrate_bps = 30000;
config_.rtp.ssrcs.emplace_back(1);
config_.rtp.ssrcs.emplace_back(2);
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillRepeatedly(Invoke(
[&](BitrateAllocatorObserver*, MediaStreamAllocationConfig config) {
EXPECT_EQ(config.min_bitrate_bps,
static_cast<uint32_t>(min_transmit_bitrate_bps));
EXPECT_EQ(config.max_bitrate_bps,
static_cast<uint32_t>(qvga_stream.max_bitrate_bps +
vga_stream.max_bitrate_bps));
if (config.pad_up_bitrate_bps != 0) {
EXPECT_EQ(config.pad_up_bitrate_bps,
static_cast<uint32_t>(qvga_stream.target_bitrate_bps +
vga_stream.min_bitrate_bps));
}
EXPECT_EQ(config.enforce_min_bitrate, !kSuspend);
}));
encoder_queue_->PostTask([&] {
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{qvga_stream, vga_stream}, false,
VideoEncoderConfig::ContentType::kRealtimeVideo,
min_transmit_bitrate_bps);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, UpdatesObserverOnConfigurationChangeWithAlr) {
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(RtpExtension::kTransportSequenceNumberUri,
1);
config_.periodic_alr_bandwidth_probing = true;
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->StartPerRtpStream({true});
// Simulcast screenshare.
VideoStream low_stream;
low_stream.width = 1920;
low_stream.height = 1080;
low_stream.max_framerate = 5;
low_stream.min_bitrate_bps = 30000;
low_stream.target_bitrate_bps = 200000;
low_stream.max_bitrate_bps = 1000000;
low_stream.num_temporal_layers = 2;
low_stream.max_qp = 56;
low_stream.bitrate_priority = 1;
VideoStream high_stream;
high_stream.width = 1920;
high_stream.height = 1080;
high_stream.max_framerate = 30;
high_stream.min_bitrate_bps = 60000;
high_stream.target_bitrate_bps = 1250000;
high_stream.max_bitrate_bps = 1250000;
high_stream.num_temporal_layers = 2;
high_stream.max_qp = 56;
high_stream.bitrate_priority = 1;
// With ALR probing, this will be the padding target instead of
// low_stream.target_bitrate_bps + high_stream.min_bitrate_bps.
int min_transmit_bitrate_bps = 400000;
config_.rtp.ssrcs.emplace_back(1);
config_.rtp.ssrcs.emplace_back(2);
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillRepeatedly(Invoke(
[&](BitrateAllocatorObserver*, MediaStreamAllocationConfig config) {
EXPECT_EQ(config.min_bitrate_bps,
static_cast<uint32_t>(low_stream.min_bitrate_bps));
EXPECT_EQ(config.max_bitrate_bps,
static_cast<uint32_t>(low_stream.max_bitrate_bps +
high_stream.max_bitrate_bps));
if (config.pad_up_bitrate_bps != 0) {
EXPECT_EQ(config.pad_up_bitrate_bps,
static_cast<uint32_t>(min_transmit_bitrate_bps));
}
EXPECT_EQ(config.enforce_min_bitrate, !kSuspend);
}));
encoder_queue_->PostTask([&] {
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{low_stream, high_stream}, false,
VideoEncoderConfig::ContentType::kScreen, min_transmit_bitrate_bps);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest,
UpdatesObserverOnConfigurationChangeWithSimulcastVideoHysteresis) {
test::ScopedKeyValueConfig hysteresis_experiment(
field_trials_, "WebRTC-VideoRateControl/video_hysteresis:1.25/");
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
vss_impl->StartPerRtpStream({true});
// 2-layer video simulcast.
VideoStream low_stream;
low_stream.width = 320;
low_stream.height = 240;
low_stream.max_framerate = 30;
low_stream.min_bitrate_bps = 30000;
low_stream.target_bitrate_bps = 100000;
low_stream.max_bitrate_bps = 200000;
low_stream.max_qp = 56;
low_stream.bitrate_priority = 1;
VideoStream high_stream;
high_stream.width = 640;
high_stream.height = 480;
high_stream.max_framerate = 30;
high_stream.min_bitrate_bps = 150000;
high_stream.target_bitrate_bps = 500000;
high_stream.max_bitrate_bps = 750000;
high_stream.max_qp = 56;
high_stream.bitrate_priority = 1;
config_.rtp.ssrcs.emplace_back(1);
config_.rtp.ssrcs.emplace_back(2);
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillRepeatedly(Invoke([&](BitrateAllocatorObserver*,
MediaStreamAllocationConfig config) {
EXPECT_EQ(config.min_bitrate_bps,
static_cast<uint32_t>(low_stream.min_bitrate_bps));
EXPECT_EQ(config.max_bitrate_bps,
static_cast<uint32_t>(low_stream.max_bitrate_bps +
high_stream.max_bitrate_bps));
if (config.pad_up_bitrate_bps != 0) {
EXPECT_EQ(config.pad_up_bitrate_bps,
static_cast<uint32_t>(low_stream.target_bitrate_bps +
1.25 * high_stream.min_bitrate_bps));
}
}));
encoder_queue_->PostTask([&] {
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{low_stream, high_stream}, false,
VideoEncoderConfig::ContentType::kRealtimeVideo,
/*min_transmit_bitrate_bps=*/0);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, SetsScreensharePacingFactorWithFeedback) {
test::ScopedFieldTrials alr_experiment(GetAlrProbingExperimentString());
constexpr int kId = 1;
config_.rtp.extensions.emplace_back(RtpExtension::kTransportSequenceNumberUri,
kId);
EXPECT_CALL(transport_controller_,
SetPacingFactor(kAlrProbingExperimentPaceMultiplier))
.Times(1);
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->StartPerRtpStream({true});
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, DoesNotSetPacingFactorWithoutFeedback) {
test::ScopedFieldTrials alr_experiment(GetAlrProbingExperimentString());
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
EXPECT_CALL(transport_controller_, SetPacingFactor(_)).Times(0);
vss_impl->StartPerRtpStream({true});
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, ForwardsVideoBitrateAllocationWhenEnabled) {
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
EXPECT_CALL(transport_controller_, SetPacingFactor(_)).Times(0);
VideoStreamEncoderInterface::EncoderSink* const sink =
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get());
vss_impl->StartPerRtpStream({true});
// Populate a test instance of video bitrate allocation.
VideoBitrateAllocation alloc;
alloc.SetBitrate(0, 0, 10000);
alloc.SetBitrate(0, 1, 20000);
alloc.SetBitrate(1, 0, 30000);
alloc.SetBitrate(1, 1, 40000);
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(0);
encoder_queue_->PostTask([&] {
// Encoder starts out paused, don't forward allocation.
sink->OnBitrateAllocationUpdated(alloc);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
// Unpause encoder, allocation should be passed through.
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(1);
encoder_queue_->PostTask([&] { sink->OnBitrateAllocationUpdated(alloc); });
time_controller_.AdvanceTime(TimeDelta::Zero());
// Pause encoder again, and block allocations.
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(0));
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(0);
encoder_queue_->PostTask([&] { sink->OnBitrateAllocationUpdated(alloc); });
time_controller_.AdvanceTime(TimeDelta::Zero());
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, ThrottlesVideoBitrateAllocationWhenTooSimilar) {
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->StartPerRtpStream({true});
// Unpause encoder, to allows allocations to be passed through.
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
VideoStreamEncoderInterface::EncoderSink* const sink =
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get());
// Populate a test instance of video bitrate allocation.
VideoBitrateAllocation alloc;
alloc.SetBitrate(0, 0, 10000);
alloc.SetBitrate(0, 1, 20000);
alloc.SetBitrate(1, 0, 30000);
alloc.SetBitrate(1, 1, 40000);
// Initial value.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(1);
encoder_queue_->PostTask([&] { sink->OnBitrateAllocationUpdated(alloc); });
time_controller_.AdvanceTime(TimeDelta::Zero());
VideoBitrateAllocation updated_alloc = alloc;
// Needs 10% increase in bitrate to trigger immediate forward.
const uint32_t base_layer_min_update_bitrate_bps =
alloc.GetBitrate(0, 0) + alloc.get_sum_bps() / 10;
// Too small increase, don't forward.
updated_alloc.SetBitrate(0, 0, base_layer_min_update_bitrate_bps - 1);
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(_)).Times(0);
encoder_queue_->PostTask(
[&] { sink->OnBitrateAllocationUpdated(updated_alloc); });
time_controller_.AdvanceTime(TimeDelta::Zero());
// Large enough increase, do forward.
updated_alloc.SetBitrate(0, 0, base_layer_min_update_bitrate_bps);
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(updated_alloc))
.Times(1);
encoder_queue_->PostTask(
[&] { sink->OnBitrateAllocationUpdated(updated_alloc); });
time_controller_.AdvanceTime(TimeDelta::Zero());
// This is now a decrease compared to last forward allocation,
// forward immediately.
updated_alloc.SetBitrate(0, 0, base_layer_min_update_bitrate_bps - 1);
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(updated_alloc))
.Times(1);
encoder_queue_->PostTask(
[&] { sink->OnBitrateAllocationUpdated(updated_alloc); });
time_controller_.AdvanceTime(TimeDelta::Zero());
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, ForwardsVideoBitrateAllocationOnLayerChange) {
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->StartPerRtpStream({true});
// Unpause encoder, to allows allocations to be passed through.
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
VideoStreamEncoderInterface::EncoderSink* const sink =
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get());
// Populate a test instance of video bitrate allocation.
VideoBitrateAllocation alloc;
alloc.SetBitrate(0, 0, 10000);
alloc.SetBitrate(0, 1, 20000);
alloc.SetBitrate(1, 0, 30000);
alloc.SetBitrate(1, 1, 40000);
// Initial value.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(1);
sink->OnBitrateAllocationUpdated(alloc);
// Move some bitrate from one layer to a new one, but keep sum the
// same. Since layout has changed, immediately trigger forward.
VideoBitrateAllocation updated_alloc = alloc;
updated_alloc.SetBitrate(2, 0, 10000);
updated_alloc.SetBitrate(1, 1, alloc.GetBitrate(1, 1) - 10000);
EXPECT_EQ(alloc.get_sum_bps(), updated_alloc.get_sum_bps());
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(updated_alloc))
.Times(1);
encoder_queue_->PostTask(
[&] { sink->OnBitrateAllocationUpdated(updated_alloc); });
time_controller_.AdvanceTime(TimeDelta::Zero());
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, ForwardsVideoBitrateAllocationAfterTimeout) {
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->StartPerRtpStream({true});
const uint32_t kBitrateBps = 100000;
// Unpause encoder, to allows allocations to be passed through.
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillRepeatedly(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
VideoStreamEncoderInterface::EncoderSink* const sink =
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get());
// Populate a test instance of video bitrate allocation.
VideoBitrateAllocation alloc;
alloc.SetBitrate(0, 0, 10000);
alloc.SetBitrate(0, 1, 20000);
alloc.SetBitrate(1, 0, 30000);
alloc.SetBitrate(1, 1, 40000);
EncodedImage encoded_image;
CodecSpecificInfo codec_specific;
EXPECT_CALL(rtp_video_sender_, OnEncodedImage)
.WillRepeatedly(Return(
EncodedImageCallback::Result(EncodedImageCallback::Result::OK)));
// Max time we will throttle similar video bitrate allocations.
static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
{
// Initial value.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(1);
encoder_queue_->PostTask([&] { sink->OnBitrateAllocationUpdated(alloc); });
time_controller_.AdvanceTime(TimeDelta::Zero());
}
{
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(0);
encoder_queue_->PostTask([&] {
// Sending same allocation again, this one should be throttled.
sink->OnBitrateAllocationUpdated(alloc);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
}
time_controller_.AdvanceTime(TimeDelta::Millis(kMaxVbaThrottleTimeMs));
{
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(1);
encoder_queue_->PostTask([&] {
// Sending similar allocation again after timeout, should
// forward.
sink->OnBitrateAllocationUpdated(alloc);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
}
{
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(0);
encoder_queue_->PostTask([&] {
// Sending similar allocation again without timeout, throttle.
sink->OnBitrateAllocationUpdated(alloc);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
}
{
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(0);
encoder_queue_->PostTask([&] {
// Send encoded image, should be a noop.
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
}
{
// Advance time and send encoded image, this should wake up and
// send cached bitrate allocation.
time_controller_.AdvanceTime(TimeDelta::Millis(kMaxVbaThrottleTimeMs));
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(1);
encoder_queue_->PostTask([&] {
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
}
{
// Advance time and send encoded image, there should be no
// cached allocation to send.
time_controller_.AdvanceTime(TimeDelta::Millis(kMaxVbaThrottleTimeMs));
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc)).Times(0);
encoder_queue_->PostTask([&] {
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
}
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, CallsVideoStreamEncoderOnBitrateUpdate) {
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(RtpExtension::kTransportSequenceNumberUri,
1);
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
vss_impl->StartPerRtpStream({true});
VideoStream qvga_stream;
qvga_stream.width = 320;
qvga_stream.height = 180;
qvga_stream.max_framerate = 30;
qvga_stream.min_bitrate_bps = 30000;
qvga_stream.target_bitrate_bps = 150000;
qvga_stream.max_bitrate_bps = 200000;
qvga_stream.max_qp = 56;
qvga_stream.bitrate_priority = 1;
int min_transmit_bitrate_bps = 30000;
config_.rtp.ssrcs.emplace_back(1);
encoder_queue_->PostTask([&] {
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{qvga_stream}, false,
VideoEncoderConfig::ContentType::kRealtimeVideo,
min_transmit_bitrate_bps);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
const DataRate network_constrained_rate =
DataRate::BitsPerSec(qvga_stream.target_bitrate_bps);
BitrateAllocationUpdate update;
update.target_bitrate = network_constrained_rate;
update.stable_target_bitrate = network_constrained_rate;
update.round_trip_time = TimeDelta::Millis(1);
EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _));
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.WillOnce(Return(network_constrained_rate.bps()));
EXPECT_CALL(
video_stream_encoder_,
OnBitrateUpdated(network_constrained_rate, network_constrained_rate,
network_constrained_rate, 0, _, 0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(update);
// Test allocation where the link allocation is larger than the
// target, meaning we have some headroom on the link.
const DataRate qvga_max_bitrate =
DataRate::BitsPerSec(qvga_stream.max_bitrate_bps);
const DataRate headroom = DataRate::BitsPerSec(50000);
const DataRate rate_with_headroom = qvga_max_bitrate + headroom;
update.target_bitrate = rate_with_headroom;
update.stable_target_bitrate = rate_with_headroom;
EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _));
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.WillOnce(Return(rate_with_headroom.bps()));
EXPECT_CALL(video_stream_encoder_,
OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate,
rate_with_headroom, 0, _, 0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(update);
// Add protection bitrate to the mix, this should be subtracted
// from the headroom.
const uint32_t protection_bitrate_bps = 10000;
EXPECT_CALL(rtp_video_sender_, GetProtectionBitrateBps())
.WillOnce(Return(protection_bitrate_bps));
EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _));
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.WillOnce(Return(rate_with_headroom.bps()));
const DataRate headroom_minus_protection =
rate_with_headroom - DataRate::BitsPerSec(protection_bitrate_bps);
EXPECT_CALL(video_stream_encoder_,
OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate,
headroom_minus_protection, 0, _, 0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(update);
// Protection bitrate exceeds head room, link allocation should be
// capped to target bitrate.
EXPECT_CALL(rtp_video_sender_, GetProtectionBitrateBps())
.WillOnce(Return(headroom.bps() + 1000));
EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _));
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.WillOnce(Return(rate_with_headroom.bps()));
EXPECT_CALL(video_stream_encoder_,
OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate,
qvga_max_bitrate, 0, _, 0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(update);
// Set rates to zero on stop.
EXPECT_CALL(video_stream_encoder_,
OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
DataRate::Zero(), 0, 0, 0));
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, DisablesPaddingOnPausedEncoder) {
int padding_bitrate = 0;
std::unique_ptr<VideoSendStreamImpl> vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
// Capture padding bitrate for testing.
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillRepeatedly(Invoke(
[&](BitrateAllocatorObserver*, MediaStreamAllocationConfig config) {
padding_bitrate = config.pad_up_bitrate_bps;
}));
// If observer is removed, no padding will be sent.
EXPECT_CALL(bitrate_allocator_, RemoveObserver(vss_impl.get()))
.WillRepeatedly(
Invoke([&](BitrateAllocatorObserver*) { padding_bitrate = 0; }));
EXPECT_CALL(rtp_video_sender_, OnEncodedImage)
.WillRepeatedly(Return(
EncodedImageCallback::Result(EncodedImageCallback::Result::OK)));
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(RtpExtension::kTransportSequenceNumberUri,
1);
VideoStream qvga_stream;
qvga_stream.width = 320;
qvga_stream.height = 180;
qvga_stream.max_framerate = 30;
qvga_stream.min_bitrate_bps = 30000;
qvga_stream.target_bitrate_bps = 150000;
qvga_stream.max_bitrate_bps = 200000;
qvga_stream.max_qp = 56;
qvga_stream.bitrate_priority = 1;
int min_transmit_bitrate_bps = 30000;
config_.rtp.ssrcs.emplace_back(1);
vss_impl->StartPerRtpStream({true});
// Starts without padding.
EXPECT_EQ(0, padding_bitrate);
encoder_queue_->PostTask([&] {
// Reconfigure e.g. due to a fake frame.
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{qvga_stream}, false,
VideoEncoderConfig::ContentType::kRealtimeVideo,
min_transmit_bitrate_bps);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
// Still no padding because no actual frames were passed, only
// reconfiguration happened.
EXPECT_EQ(0, padding_bitrate);
// Unpause encoder.
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
encoder_queue_->PostTask([&] {
// A frame is encoded.
EncodedImage encoded_image;
CodecSpecificInfo codec_specific;
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
// Only after actual frame is encoded are we enabling the padding.
EXPECT_GT(padding_bitrate, 0);
time_controller_.AdvanceTime(TimeDelta::Seconds(5));
// Since no more frames are sent the last 5s, no padding is supposed to be
// sent.
EXPECT_EQ(0, padding_bitrate);
testing::Mock::VerifyAndClearExpectations(&bitrate_allocator_);
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, KeepAliveOnDroppedFrame) {
std::unique_ptr<VideoSendStreamImpl> vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
EXPECT_CALL(bitrate_allocator_, RemoveObserver(vss_impl.get())).Times(0);
vss_impl->StartPerRtpStream({true});
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
encoder_queue_->PostTask([&] {
// Keep the stream from deallocating by dropping a frame.
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnDroppedFrame(EncodedImageCallback::DropReason::kDroppedByEncoder);
});
time_controller_.AdvanceTime(TimeDelta::Seconds(2));
testing::Mock::VerifyAndClearExpectations(&bitrate_allocator_);
vss_impl->Stop();
}
TEST_F(VideoSendStreamImplTest, ConfiguresBitratesForSvc) {
struct TestConfig {
bool screenshare = false;
bool alr = false;
int min_padding_bitrate_bps = 0;
};
std::vector<TestConfig> test_variants;
for (bool screenshare : {false, true}) {
for (bool alr : {false, true}) {
for (int min_padding : {0, 400000}) {
test_variants.push_back({screenshare, alr, min_padding});
}
}
}
for (const TestConfig& test_config : test_variants) {
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(
RtpExtension::kTransportSequenceNumberUri, 1);
config_.periodic_alr_bandwidth_probing = test_config.alr;
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
test_config.screenshare
? VideoEncoderConfig::ContentType::kScreen
: VideoEncoderConfig::ContentType::kRealtimeVideo);
vss_impl->StartPerRtpStream({true});
// Svc
VideoStream stream;
stream.width = 1920;
stream.height = 1080;
stream.max_framerate = 30;
stream.min_bitrate_bps = 60000;
stream.target_bitrate_bps = 6000000;
stream.max_bitrate_bps = 1250000;
stream.num_temporal_layers = 2;
stream.max_qp = 56;
stream.bitrate_priority = 1;
config_.rtp.ssrcs.emplace_back(1);
config_.rtp.ssrcs.emplace_back(2);
EXPECT_CALL(
bitrate_allocator_,
AddObserver(
vss_impl.get(),
AllOf(Field(&MediaStreamAllocationConfig::min_bitrate_bps,
static_cast<uint32_t>(stream.min_bitrate_bps)),
Field(&MediaStreamAllocationConfig::max_bitrate_bps,
static_cast<uint32_t>(stream.max_bitrate_bps)),
// Stream not yet active - no padding.
Field(&MediaStreamAllocationConfig::pad_up_bitrate_bps, 0u),
Field(&MediaStreamAllocationConfig::enforce_min_bitrate,
!kSuspend))));
encoder_queue_->PostTask([&] {
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{stream}, true,
test_config.screenshare
? VideoEncoderConfig::ContentType::kScreen
: VideoEncoderConfig::ContentType::kRealtimeVideo,
test_config.min_padding_bitrate_bps);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
::testing::Mock::VerifyAndClearExpectations(&bitrate_allocator_);
// Simulate an encoded image, this will turn the stream active and
// enable padding.
EXPECT_CALL(rtp_video_sender_, OnEncodedImage)
.WillRepeatedly(Return(
EncodedImageCallback::Result(EncodedImageCallback::Result::OK)));
// Screensharing implicitly forces ALR.
const bool using_alr = test_config.alr || test_config.screenshare;
// If ALR is used, pads only to min bitrate as rampup is handled by
// probing. Otherwise target_bitrate contains the padding target.
int expected_padding =
using_alr ? stream.min_bitrate_bps
: static_cast<int>(stream.target_bitrate_bps *
(test_config.screenshare ? 1.35 : 1.2));
// Min padding bitrate may override padding target.
expected_padding =
std::max(expected_padding, test_config.min_padding_bitrate_bps);
EXPECT_CALL(
bitrate_allocator_,
AddObserver(
vss_impl.get(),
AllOf(Field(&MediaStreamAllocationConfig::min_bitrate_bps,
static_cast<uint32_t>(stream.min_bitrate_bps)),
Field(&MediaStreamAllocationConfig::max_bitrate_bps,
static_cast<uint32_t>(stream.max_bitrate_bps)),
// Stream now active - min bitrate use as padding target
// when ALR is active.
Field(&MediaStreamAllocationConfig::pad_up_bitrate_bps,
expected_padding),
Field(&MediaStreamAllocationConfig::enforce_min_bitrate,
!kSuspend))));
encoder_queue_->PostTask([&] {
EncodedImage encoded_image;
CodecSpecificInfo codec_specific;
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific);
});
time_controller_.AdvanceTime(TimeDelta::Zero());
::testing::Mock::VerifyAndClearExpectations(&bitrate_allocator_);
vss_impl->Stop();
}
}
} // namespace internal
} // namespace webrtc
|
ee18e218ec7c47a8bc0382daffd03bb0ebac2593
|
bc95d233db18ce8a4a50b047fdcfceadb43c5818
|
/day2/stars.cpp
|
628df0a5ea4f08f030a356767211c08b095ca0f1
|
[] |
no_license
|
kizzlebot/Intro-To-Cpp
|
cd253c0489a3868defd3de78e54429295dc3eb7d
|
2136bae943940aae1e65a9ab6012c464c5f91a9a
|
refs/heads/master
| 2021-01-02T22:45:05.117479
| 2014-05-07T07:20:41
| 2014-05-07T07:20:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 364
|
cpp
|
stars.cpp
|
//This Program outputs a bunch of stars lol
#include <iostream>
using namespace std;
int main(){
// Declare
int noTime = 0;
// while user has not specified how many lines of stars they want, ask for it
while ( noTime = 0 ){
cout << "\n\n\tHow Many Lines of Stars?: " ;
cin >> noTime;
}
return 0;
}
|
85e874166837f94ed78d309df9636b9bb129bf17
|
8c1add484810df818286a6bbf7331c213e945018
|
/Chapter8/Level.cpp
|
f01e7ae6cb252d46235c9dbc27528e308c26c0cc
|
[
"BSD-3-Clause"
] |
permissive
|
sgeos/book_sdl_game_development
|
558075ed34177298fa9026c285ffe6af68d89485
|
a37466bfe916313216f332cbcff07dc6b3800908
|
refs/heads/master
| 2020-05-04T21:02:00.730299
| 2019-06-13T06:16:20
| 2019-06-13T06:16:20
| 179,461,655
| 8
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 519
|
cpp
|
Level.cpp
|
#include <string>
#include <vector>
#include "Level.h"
Level::Level(void) { }
Level::~Level(void) { }
void Level::render(void) {
int size = mLayerList.size();
for (int i = 0; i < size; i++) {
mLayerList[i]->render();
}
}
void Level::update(void) {
int size = mLayerList.size();
for (int i = 0; i < size; i++) {
mLayerList[i]->update();
}
}
std::vector<Tileset> *Level::getTilesetList(void) {
return &mTilesetList;
}
std::vector<Layer *> *Level::getLayerList(void) {
return &mLayerList;
}
|
02f7334c20ff0ff33a3edfc551c2b54b2c828f45
|
afb7006e47e70c1deb2ddb205f06eaf67de3df72
|
/third_party/libwebrtc/audio/voip/test/audio_ingress_unittest.cc
|
d46154820818b7b8a8e53399590b5822e98fae3e
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
marco-c/gecko-dev-wordified
|
a66383f85db33911b6312dd094c36f88c55d2e2c
|
3509ec45ecc9e536d04a3f6a43a82ec09c08dff6
|
refs/heads/master
| 2023-08-10T16:37:56.660204
| 2023-08-01T00:39:54
| 2023-08-01T00:39:54
| 211,297,590
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,016
|
cc
|
audio_ingress_unittest.cc
|
/
*
*
Copyright
(
c
)
2020
The
WebRTC
project
authors
.
All
Rights
Reserved
.
*
*
Use
of
this
source
code
is
governed
by
a
BSD
-
style
license
*
that
can
be
found
in
the
LICENSE
file
in
the
root
of
the
source
*
tree
.
An
additional
intellectual
property
rights
grant
can
be
found
*
in
the
file
PATENTS
.
All
contributing
project
authors
may
*
be
found
in
the
AUTHORS
file
in
the
root
of
the
source
tree
.
*
/
#
include
"
audio
/
voip
/
audio_ingress
.
h
"
#
include
"
api
/
audio_codecs
/
builtin_audio_decoder_factory
.
h
"
#
include
"
api
/
audio_codecs
/
builtin_audio_encoder_factory
.
h
"
#
include
"
api
/
call
/
transport
.
h
"
#
include
"
api
/
task_queue
/
default_task_queue_factory
.
h
"
#
include
"
audio
/
voip
/
audio_egress
.
h
"
#
include
"
modules
/
audio_mixer
/
sine_wave_generator
.
h
"
#
include
"
modules
/
rtp_rtcp
/
source
/
rtp_rtcp_impl2
.
h
"
#
include
"
rtc_base
/
event
.
h
"
#
include
"
rtc_base
/
logging
.
h
"
#
include
"
test
/
gmock
.
h
"
#
include
"
test
/
gtest
.
h
"
#
include
"
test
/
mock_transport
.
h
"
#
include
"
test
/
run_loop
.
h
"
namespace
webrtc
{
namespace
{
using
:
:
testing
:
:
Invoke
;
using
:
:
testing
:
:
NiceMock
;
using
:
:
testing
:
:
Unused
;
constexpr
int16_t
kAudioLevel
=
3004
;
/
/
Used
for
sine
wave
level
.
class
AudioIngressTest
:
public
:
:
testing
:
:
Test
{
public
:
const
SdpAudioFormat
kPcmuFormat
=
{
"
pcmu
"
8000
1
}
;
AudioIngressTest
(
)
:
fake_clock_
(
123456789
)
wave_generator_
(
1000
.
0
kAudioLevel
)
{
receive_statistics_
=
ReceiveStatistics
:
:
Create
(
&
fake_clock_
)
;
RtpRtcpInterface
:
:
Configuration
rtp_config
;
rtp_config
.
clock
=
&
fake_clock_
;
rtp_config
.
audio
=
true
;
rtp_config
.
receive_statistics
=
receive_statistics_
.
get
(
)
;
rtp_config
.
rtcp_report_interval_ms
=
5000
;
rtp_config
.
outgoing_transport
=
&
transport_
;
rtp_config
.
local_media_ssrc
=
0xdeadc0de
;
rtp_rtcp_
=
ModuleRtpRtcpImpl2
:
:
Create
(
rtp_config
)
;
rtp_rtcp_
-
>
SetSendingMediaStatus
(
false
)
;
rtp_rtcp_
-
>
SetRTCPStatus
(
RtcpMode
:
:
kCompound
)
;
task_queue_factory_
=
CreateDefaultTaskQueueFactory
(
)
;
encoder_factory_
=
CreateBuiltinAudioEncoderFactory
(
)
;
decoder_factory_
=
CreateBuiltinAudioDecoderFactory
(
)
;
}
void
SetUp
(
)
override
{
constexpr
int
kPcmuPayload
=
0
;
ingress_
=
std
:
:
make_unique
<
AudioIngress
>
(
rtp_rtcp_
.
get
(
)
&
fake_clock_
receive_statistics_
.
get
(
)
decoder_factory_
)
;
ingress_
-
>
SetReceiveCodecs
(
{
{
kPcmuPayload
kPcmuFormat
}
}
)
;
egress_
=
std
:
:
make_unique
<
AudioEgress
>
(
rtp_rtcp_
.
get
(
)
&
fake_clock_
task_queue_factory_
.
get
(
)
)
;
egress_
-
>
SetEncoder
(
kPcmuPayload
kPcmuFormat
encoder_factory_
-
>
MakeAudioEncoder
(
kPcmuPayload
kPcmuFormat
absl
:
:
nullopt
)
)
;
egress_
-
>
StartSend
(
)
;
ingress_
-
>
StartPlay
(
)
;
rtp_rtcp_
-
>
SetSendingStatus
(
true
)
;
}
void
TearDown
(
)
override
{
rtp_rtcp_
-
>
SetSendingStatus
(
false
)
;
ingress_
-
>
StopPlay
(
)
;
egress_
-
>
StopSend
(
)
;
egress_
.
reset
(
)
;
ingress_
.
reset
(
)
;
}
std
:
:
unique_ptr
<
AudioFrame
>
GetAudioFrame
(
int
order
)
{
auto
frame
=
std
:
:
make_unique
<
AudioFrame
>
(
)
;
frame
-
>
sample_rate_hz_
=
kPcmuFormat
.
clockrate_hz
;
frame
-
>
samples_per_channel_
=
kPcmuFormat
.
clockrate_hz
/
100
;
/
/
10
ms
.
frame
-
>
num_channels_
=
kPcmuFormat
.
num_channels
;
frame
-
>
timestamp_
=
frame
-
>
samples_per_channel_
*
order
;
wave_generator_
.
GenerateNextFrame
(
frame
.
get
(
)
)
;
return
frame
;
}
test
:
:
RunLoop
run_loop_
;
SimulatedClock
fake_clock_
;
SineWaveGenerator
wave_generator_
;
NiceMock
<
MockTransport
>
transport_
;
std
:
:
unique_ptr
<
ReceiveStatistics
>
receive_statistics_
;
std
:
:
unique_ptr
<
ModuleRtpRtcpImpl2
>
rtp_rtcp_
;
rtc
:
:
scoped_refptr
<
AudioEncoderFactory
>
encoder_factory_
;
rtc
:
:
scoped_refptr
<
AudioDecoderFactory
>
decoder_factory_
;
std
:
:
unique_ptr
<
TaskQueueFactory
>
task_queue_factory_
;
std
:
:
unique_ptr
<
AudioIngress
>
ingress_
;
std
:
:
unique_ptr
<
AudioEgress
>
egress_
;
}
;
TEST_F
(
AudioIngressTest
PlayingAfterStartAndStop
)
{
EXPECT_EQ
(
ingress_
-
>
IsPlaying
(
)
true
)
;
ingress_
-
>
StopPlay
(
)
;
EXPECT_EQ
(
ingress_
-
>
IsPlaying
(
)
false
)
;
}
TEST_F
(
AudioIngressTest
GetAudioFrameAfterRtpReceived
)
{
rtc
:
:
Event
event
;
auto
handle_rtp
=
[
&
]
(
const
uint8_t
*
packet
size_t
length
Unused
)
{
ingress_
-
>
ReceivedRTPPacket
(
rtc
:
:
ArrayView
<
const
uint8_t
>
(
packet
length
)
)
;
event
.
Set
(
)
;
return
true
;
}
;
EXPECT_CALL
(
transport_
SendRtp
)
.
WillRepeatedly
(
Invoke
(
handle_rtp
)
)
;
egress_
-
>
SendAudioData
(
GetAudioFrame
(
0
)
)
;
egress_
-
>
SendAudioData
(
GetAudioFrame
(
1
)
)
;
event
.
Wait
(
TimeDelta
:
:
Seconds
(
1
)
)
;
AudioFrame
audio_frame
;
EXPECT_EQ
(
ingress_
-
>
GetAudioFrameWithInfo
(
kPcmuFormat
.
clockrate_hz
&
audio_frame
)
AudioMixer
:
:
Source
:
:
AudioFrameInfo
:
:
kNormal
)
;
EXPECT_FALSE
(
audio_frame
.
muted
(
)
)
;
EXPECT_EQ
(
audio_frame
.
num_channels_
1u
)
;
EXPECT_EQ
(
audio_frame
.
samples_per_channel_
static_cast
<
size_t
>
(
kPcmuFormat
.
clockrate_hz
/
100
)
)
;
EXPECT_EQ
(
audio_frame
.
sample_rate_hz_
kPcmuFormat
.
clockrate_hz
)
;
EXPECT_NE
(
audio_frame
.
timestamp_
0u
)
;
EXPECT_EQ
(
audio_frame
.
elapsed_time_ms_
0
)
;
}
TEST_F
(
AudioIngressTest
TestSpeechOutputLevelAndEnergyDuration
)
{
/
/
Per
audio_level
'
s
kUpdateFrequency
we
need
more
than
10
audio
samples
to
/
/
get
audio
level
from
output
source
.
constexpr
int
kNumRtp
=
6
;
int
rtp_count
=
0
;
rtc
:
:
Event
event
;
auto
handle_rtp
=
[
&
]
(
const
uint8_t
*
packet
size_t
length
Unused
)
{
ingress_
-
>
ReceivedRTPPacket
(
rtc
:
:
ArrayView
<
const
uint8_t
>
(
packet
length
)
)
;
if
(
+
+
rtp_count
=
=
kNumRtp
)
{
event
.
Set
(
)
;
}
return
true
;
}
;
EXPECT_CALL
(
transport_
SendRtp
)
.
WillRepeatedly
(
Invoke
(
handle_rtp
)
)
;
for
(
int
i
=
0
;
i
<
kNumRtp
*
2
;
i
+
+
)
{
egress_
-
>
SendAudioData
(
GetAudioFrame
(
i
)
)
;
fake_clock_
.
AdvanceTimeMilliseconds
(
10
)
;
}
event
.
Wait
(
/
*
give_up_after
=
*
/
TimeDelta
:
:
Seconds
(
1
)
)
;
for
(
int
i
=
0
;
i
<
kNumRtp
*
2
;
+
+
i
)
{
AudioFrame
audio_frame
;
EXPECT_EQ
(
ingress_
-
>
GetAudioFrameWithInfo
(
kPcmuFormat
.
clockrate_hz
&
audio_frame
)
AudioMixer
:
:
Source
:
:
AudioFrameInfo
:
:
kNormal
)
;
}
EXPECT_EQ
(
ingress_
-
>
GetOutputAudioLevel
(
)
kAudioLevel
)
;
constexpr
double
kExpectedEnergy
=
0
.
00016809565587789564
;
constexpr
double
kExpectedDuration
=
0
.
11999999999999998
;
EXPECT_DOUBLE_EQ
(
ingress_
-
>
GetOutputTotalEnergy
(
)
kExpectedEnergy
)
;
EXPECT_DOUBLE_EQ
(
ingress_
-
>
GetOutputTotalDuration
(
)
kExpectedDuration
)
;
}
TEST_F
(
AudioIngressTest
PreferredSampleRate
)
{
rtc
:
:
Event
event
;
auto
handle_rtp
=
[
&
]
(
const
uint8_t
*
packet
size_t
length
Unused
)
{
ingress_
-
>
ReceivedRTPPacket
(
rtc
:
:
ArrayView
<
const
uint8_t
>
(
packet
length
)
)
;
event
.
Set
(
)
;
return
true
;
}
;
EXPECT_CALL
(
transport_
SendRtp
)
.
WillRepeatedly
(
Invoke
(
handle_rtp
)
)
;
egress_
-
>
SendAudioData
(
GetAudioFrame
(
0
)
)
;
egress_
-
>
SendAudioData
(
GetAudioFrame
(
1
)
)
;
event
.
Wait
(
TimeDelta
:
:
Seconds
(
1
)
)
;
AudioFrame
audio_frame
;
EXPECT_EQ
(
ingress_
-
>
GetAudioFrameWithInfo
(
kPcmuFormat
.
clockrate_hz
&
audio_frame
)
AudioMixer
:
:
Source
:
:
AudioFrameInfo
:
:
kNormal
)
;
EXPECT_EQ
(
ingress_
-
>
PreferredSampleRate
(
)
kPcmuFormat
.
clockrate_hz
)
;
}
/
/
This
test
highlights
the
case
where
caller
invokes
StopPlay
(
)
which
then
/
/
AudioIngress
should
play
silence
frame
afterwards
.
TEST_F
(
AudioIngressTest
GetMutedAudioFrameAfterRtpReceivedAndStopPlay
)
{
/
/
StopPlay
before
we
start
sending
RTP
packet
with
sine
wave
.
ingress_
-
>
StopPlay
(
)
;
/
/
Send
6
RTP
packets
to
generate
more
than
100
ms
audio
sample
to
get
/
/
valid
speech
level
.
constexpr
int
kNumRtp
=
6
;
int
rtp_count
=
0
;
rtc
:
:
Event
event
;
auto
handle_rtp
=
[
&
]
(
const
uint8_t
*
packet
size_t
length
Unused
)
{
ingress_
-
>
ReceivedRTPPacket
(
rtc
:
:
ArrayView
<
const
uint8_t
>
(
packet
length
)
)
;
if
(
+
+
rtp_count
=
=
kNumRtp
)
{
event
.
Set
(
)
;
}
return
true
;
}
;
EXPECT_CALL
(
transport_
SendRtp
)
.
WillRepeatedly
(
Invoke
(
handle_rtp
)
)
;
for
(
int
i
=
0
;
i
<
kNumRtp
*
2
;
i
+
+
)
{
egress_
-
>
SendAudioData
(
GetAudioFrame
(
i
)
)
;
fake_clock_
.
AdvanceTimeMilliseconds
(
10
)
;
}
event
.
Wait
(
/
*
give_up_after
=
*
/
TimeDelta
:
:
Seconds
(
1
)
)
;
for
(
int
i
=
0
;
i
<
kNumRtp
*
2
;
+
+
i
)
{
AudioFrame
audio_frame
;
EXPECT_EQ
(
ingress_
-
>
GetAudioFrameWithInfo
(
kPcmuFormat
.
clockrate_hz
&
audio_frame
)
AudioMixer
:
:
Source
:
:
AudioFrameInfo
:
:
kMuted
)
;
const
int16_t
*
audio_data
=
audio_frame
.
data
(
)
;
size_t
length
=
audio_frame
.
samples_per_channel_
*
audio_frame
.
num_channels_
;
for
(
size_t
j
=
0
;
j
<
length
;
+
+
j
)
{
EXPECT_EQ
(
audio_data
[
j
]
0
)
;
}
}
/
/
Now
we
should
still
see
valid
speech
output
level
as
StopPlay
won
'
t
affect
/
/
the
measurement
.
EXPECT_EQ
(
ingress_
-
>
GetOutputAudioLevel
(
)
kAudioLevel
)
;
}
}
/
/
namespace
}
/
/
namespace
webrtc
|
9b19c29bdd32ad7b8e8d2af5b81564888da79d26
|
27c8f4c3ce82ddd6ae2bcd1c0319936d90b36ce4
|
/codeforces/1155b.cpp
|
1c72d8cd8bd58770851a94440e1ba720d75baf40
|
[] |
no_license
|
liv1n9/competitive-programing
|
8ed486390c4f1960fe8749c6a09ece0f030f3fc2
|
ddc5a1dcc1ade30f64c9a374923ad5e6e419ecb1
|
refs/heads/master
| 2020-08-22T00:59:32.965539
| 2019-10-20T00:13:20
| 2019-10-20T00:13:20
| 216,286,007
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 730
|
cpp
|
1155b.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
string s;
cin >> s;
int eight = 0;
for (int i = 0; i < n; i++) {
eight += (int)(s[i] == '8');
}
int move = n - 11;
if (eight == 0) {
cout << "NO";
return 0;
}
if (move / 2 < eight) {
int temp = 0;
int pass = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '8') {
if (pass == move / 2) {
break;
}
pass++;
} else {
temp++;
}
}
cout << (temp <= move / 2 ? "YES" : "NO");
} else {
cout << "NO";
return 0;
}
}
|
af05f7c25b93e43f7c7b8cf8e88076b49021fd16
|
e549fdb6af47cc19aa84da710e1311ddf1d363e1
|
/src/Base/log/Log.h
|
faf33ba1da8b00febc58670bfd08bab872aa15fb
|
[] |
no_license
|
shizhan-shelly/MotionControl
|
b331e0a53400fd2b5d325bf8a17bc04f099b43e5
|
99c815acf5047e7a9a2a43e49f08f990e878cb5c
|
refs/heads/master
| 2021-07-07T01:39:50.728336
| 2020-07-22T10:53:40
| 2020-07-22T10:53:40
| 130,342,938
| 1
| 2
| null | 2020-03-25T15:27:08
| 2018-04-20T09:46:54
|
C
|
UTF-8
|
C++
| false
| false
| 584
|
h
|
Log.h
|
// Copyright 2018 Fangling Software Co., Ltd. All Rights Reserved.
// Author: shizhan-shelly@hotmail.com (Zhan Shi)
#ifndef BASE_LOG_LOG_H__
#define BASE_LOG_LOG_H__
namespace base {
typedef unsigned int LogId;
typedef std::string LogArgument;
// LOG_UNIQUE_ID_BITS is always LOG_DATABASE_ID_BITS + LOG_ID_BITS
#define LOG_UNIQUE_ID_BITS 32
#define LOG_DATABASE_ID_BITS 12
#define LOG_ID_BITS 20
typedef enum _LogLevel {
LogLevelDebug,
LogLevelInformation,
LogLevelWarning,
LogLevelError,
} LogLevel;
} // namespace base
#endif BASE_LOG_LOG_H__
|
c6e6a864e968398d26a24f869a229583b1dc6622
|
166cfb7d5c3a09d7d252f611b34d723c1ac2cdb2
|
/Week 11/Add two numbers without using arithmetic operators.cpp
|
01e0eca5bb557e6a7de6259f97a0f286ed7c42d3
|
[] |
no_license
|
yash56244/DSA
|
8db4fa9687e46207966cc17e0be827f0fd9fd78d
|
3aea589aa7807544d188e40d88c5f0c9d60a9e52
|
refs/heads/main
| 2023-06-24T04:51:17.471693
| 2021-07-09T05:15:52
| 2021-07-09T05:15:52
| 353,593,125
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 288
|
cpp
|
Add two numbers without using arithmetic operators.cpp
|
int Add(int x, int y)
{
if (y == 0)
return x;
else
return Add( x ^ y, (x & y) << 1);
}
// Another Method using half adder logic.
int add(int x, int y){
int sum, carry;
while(y ! = 0){
sum = x ^ y;
carry (x & y) << 1;
x = sum;
y = carry;
}
return x;
}
|
79718d59b36d0a22a2d17edb48763907433420c0
|
3d4b050616b00947a4afc55af1238cdc5bfd33a3
|
/controller/genreartistsongsitem.h
|
577986e961169ee8f251bae4bf2643e0bcf31d1f
|
[
"MIT"
] |
permissive
|
duganchen/quetzalcoatl
|
6910e2fc5d664382d22c4eaae9337c0b691c9442
|
de09175810994b7a085e6aa0ac9eaacc89388f07
|
refs/heads/master
| 2023-04-30T13:48:53.238533
| 2023-04-19T16:54:30
| 2023-04-19T16:54:30
| 1,010,675
| 8
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 322
|
h
|
genreartistsongsitem.h
|
#ifndef GENREARTISTSONGSITEM_H
#define GENREARTISTSONGSITEM_H
#include "item.h"
class GenreArtistSongsItem : public Item
{
public:
GenreArtistSongsItem(QString, QString);
QVector<Item *> fetchMore(Controller *) override;
private:
QString m_genre;
QString m_artist;
};
#endif // GENREARTISTSONGSITEM_H
|
06a37231d42546653569bf4841c85fe752fc85c2
|
3d9c6163656436abed072a7b56534ecae1ca2f66
|
/Sources/x10/xla_tensor/ops/all_to_all.h
|
4a0cd0cf2566fee7604ef89cda7984e50dbaafd0
|
[
"Apache-2.0"
] |
permissive
|
kongzii/swift-apis
|
5c807e12e443bf032cbf78f8cbbe0d75fed14082
|
cd2236fb51c20d3c9bbf1b37524cf9bc2ed04ce6
|
refs/heads/master
| 2020-11-28T20:17:45.644349
| 2020-10-05T18:00:51
| 2020-10-05T18:00:51
| 220,660,173
| 0
| 0
|
Apache-2.0
| 2019-11-09T15:14:09
| 2019-11-09T15:14:08
| null |
UTF-8
|
C++
| false
| false
| 1,084
|
h
|
all_to_all.h
|
#pragma once
#include "tensorflow/compiler/tf2xla/xla_tensor/cross_replica_reduces.h"
#include "tensorflow/compiler/tf2xla/xla_tensor/ir.h"
namespace swift_xla {
namespace ir {
namespace ops {
class AllToAll : public Node {
public:
AllToAll(const Value& input, const Value& token, xla::int64 split_dimension,
xla::int64 concat_dimension, xla::int64 split_count,
std::vector<std::vector<xla::int64>> groups);
std::string ToString() const override;
NodePtr Clone(OpList operands) const override;
XlaOpVector Lower(LoweringContext* loctx) const override;
xla::int64 split_dimension() const { return split_dimension_; }
xla::int64 concat_dimension() const { return concat_dimension_; }
xla::int64 split_count() const { return split_count_; }
const std::vector<std::vector<xla::int64>>& groups() const { return groups_; }
private:
xla::int64 split_dimension_;
xla::int64 concat_dimension_;
xla::int64 split_count_;
std::vector<std::vector<xla::int64>> groups_;
};
} // namespace ops
} // namespace ir
} // namespace swift_xla
|
389f3ba655252042f72ead53a83e936a18196554
|
0c360ce74a4b3f08457dd354a6d1ed70a80a7265
|
/src/components/application_manager/src/commands/mobile/register_app_interface_request.cc
|
9ae2bac73ccf899e89d9ca198d8d1ad9da75d1be
|
[] |
permissive
|
APCVSRepo/sdl_implementation_reference
|
917ef886c7d053b344740ac4fc3d65f91b474b42
|
19be0eea481a8c05530048c960cce7266a39ccd0
|
refs/heads/master
| 2021-01-24T07:43:52.766347
| 2017-10-22T14:31:21
| 2017-10-22T14:31:21
| 93,353,314
| 4
| 3
|
BSD-3-Clause
| 2022-10-09T06:51:42
| 2017-06-05T01:34:12
|
C++
|
UTF-8
|
C++
| false
| false
| 42,409
|
cc
|
register_app_interface_request.cc
|
/*
Copyright (c) 2015, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/mobile/register_app_interface_request.h"
#include <unistd.h>
#include <algorithm>
#include <map>
#include <string.h>
#include <utils/make_shared.h>
#include "application_manager/application_manager.h"
#include "application_manager/policies/policy_handler_interface.h"
#include "application_manager/application_impl.h"
#include "application_manager/app_launch/app_launch_ctrl.h"
#include "application_manager/message_helper.h"
#include "application_manager/resumption/resume_ctrl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/generated_msg_version.h"
namespace {
namespace custom_str = utils::custom_string;
mobile_apis::AppHMIType::eType StringToAppHMIType(const std::string& str) {
if ("DEFAULT" == str) {
return mobile_apis::AppHMIType::DEFAULT;
} else if ("COMMUNICATION" == str) {
return mobile_apis::AppHMIType::COMMUNICATION;
} else if ("MEDIA" == str) {
return mobile_apis::AppHMIType::MEDIA;
} else if ("MESSAGING" == str) {
return mobile_apis::AppHMIType::MESSAGING;
} else if ("NAVIGATION" == str) {
return mobile_apis::AppHMIType::NAVIGATION;
} else if ("INFORMATION" == str) {
return mobile_apis::AppHMIType::INFORMATION;
} else if ("SOCIAL" == str) {
return mobile_apis::AppHMIType::SOCIAL;
} else if ("BACKGROUND_PROCESS" == str) {
return mobile_apis::AppHMIType::BACKGROUND_PROCESS;
} else if ("TESTING" == str) {
return mobile_apis::AppHMIType::TESTING;
} else if ("SYSTEM" == str) {
return mobile_apis::AppHMIType::SYSTEM;
} else {
return mobile_apis::AppHMIType::INVALID_ENUM;
}
}
std::string AppHMITypeToString(mobile_apis::AppHMIType::eType type) {
const std::map<mobile_apis::AppHMIType::eType, std::string> app_hmi_type_map =
{{mobile_apis::AppHMIType::DEFAULT, "DEFAULT"},
{mobile_apis::AppHMIType::COMMUNICATION, "COMMUNICATION"},
{mobile_apis::AppHMIType::MEDIA, "MEDIA"},
{mobile_apis::AppHMIType::MESSAGING, "MESSAGING"},
{mobile_apis::AppHMIType::NAVIGATION, "NAVIGATION"},
{mobile_apis::AppHMIType::INFORMATION, "INFORMATION"},
{mobile_apis::AppHMIType::SOCIAL, "SOCIAL"},
{mobile_apis::AppHMIType::BACKGROUND_PROCESS, "BACKGROUND_PROCESS"},
{mobile_apis::AppHMIType::TESTING, "TESTING"},
{mobile_apis::AppHMIType::SYSTEM, "SYSTEM"}};
std::map<mobile_apis::AppHMIType::eType, std::string>::const_iterator iter =
app_hmi_type_map.find(type);
return app_hmi_type_map.end() != iter ? iter->second : std::string("");
}
struct AppHMITypeInserter {
AppHMITypeInserter(smart_objects::SmartObject& so_array)
: index_(0), so_array_(so_array) {}
bool operator()(const std::string& app_hmi_type) {
so_array_[index_] = StringToAppHMIType(app_hmi_type);
++index_;
return true;
}
private:
uint32_t index_;
smart_objects::SmartObject& so_array_;
};
struct CheckMissedTypes {
CheckMissedTypes(const policy::StringArray& policy_app_types,
std::string& log)
: policy_app_types_(policy_app_types), log_(log) {}
bool operator()(const smart_objects::SmartArray::value_type& value) {
std::string app_type_str = AppHMITypeToString(
static_cast<mobile_apis::AppHMIType::eType>(value.asInt()));
if (!app_type_str.empty()) {
policy::StringArray::const_iterator it = policy_app_types_.begin();
policy::StringArray::const_iterator it_end = policy_app_types_.end();
for (; it != it_end; ++it) {
if (app_type_str == *it) {
return true;
}
}
}
log_ += app_type_str;
log_ += ",";
return true;
}
private:
const policy::StringArray& policy_app_types_;
std::string& log_;
};
struct IsSameNickname {
IsSameNickname(const custom_str::CustomString& app_id) : app_id_(app_id) {}
bool operator()(const policy::StringArray::value_type& nickname) const {
return app_id_.CompareIgnoreCase(nickname.c_str());
}
private:
const custom_str::CustomString& app_id_;
};
}
namespace application_manager {
namespace commands {
RegisterAppInterfaceRequest::RegisterAppInterfaceRequest(
const MessageSharedPtr& message, ApplicationManager& application_manager)
: CommandRequestImpl(message, application_manager)
, result_checking_app_hmi_type_(mobile_apis::Result::INVALID_ENUM) {}
RegisterAppInterfaceRequest::~RegisterAppInterfaceRequest() {}
bool RegisterAppInterfaceRequest::Init() {
LOG4CXX_AUTO_TRACE(logger_);
return true;
}
void RegisterAppInterfaceRequest::Run() {
using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "Connection key is " << connection_key());
// Fix problem with SDL and HMI HTML. This problem is not actual for HMI PASA.
// Flag conditional compilation specific to customer is used in order to
// exclude hit code
// to RTC
// FIXME(EZamakhov): on shutdown - get freez
// wait till HMI started
while (!application_manager_.IsStopping() &&
!application_manager_.IsHMICooperating()) {
LOG4CXX_DEBUG(logger_,
"Waiting for the HMI... conn_key="
<< connection_key()
<< ", correlation_id=" << correlation_id()
<< ", default_timeout=" << default_timeout()
<< ", thread=" << pthread_self());
application_manager_.updateRequestTimeout(
connection_key(), correlation_id(), default_timeout());
sleep(1);
// TODO(DK): timer_->StartWait(1);
}
if (application_manager_.IsStopping()) {
LOG4CXX_WARN(logger_, "The ApplicationManager is stopping!");
return;
}
const std::string mobile_app_id =
(*message_)[strings::msg_params][strings::app_id].asString();
ApplicationSharedPtr application =
application_manager_.application(connection_key());
if (application) {
SendResponse(false, mobile_apis::Result::APPLICATION_REGISTERED_ALREADY);
return;
}
const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
const std::string& policy_app_id = msg_params[strings::app_id].asString();
if (application_manager_.IsApplicationForbidden(connection_key(),
policy_app_id)) {
SendResponse(false, mobile_apis::Result::TOO_MANY_PENDING_REQUESTS);
return;
}
if (IsApplicationWithSameAppIdRegistered()) {
SendResponse(false, mobile_apis::Result::DISALLOWED);
return;
}
mobile_apis::Result::eType policy_result = CheckWithPolicyData();
if (Compare<mobile_apis::Result::eType, NEQ, ALL>(
policy_result,
mobile_apis::Result::SUCCESS,
mobile_apis::Result::WARNINGS)) {
SendResponse(false, policy_result);
return;
}
mobile_apis::Result::eType coincidence_result = CheckCoincidence();
if (mobile_apis::Result::SUCCESS != coincidence_result) {
LOG4CXX_ERROR(logger_, "Coincidence check failed.");
if (mobile_apis::Result::DUPLICATE_NAME == coincidence_result) {
usage_statistics::AppCounter count_of_rejections_duplicate_name(
GetPolicyHandler().GetStatisticManager(),
policy_app_id,
usage_statistics::REJECTIONS_DUPLICATE_NAME);
++count_of_rejections_duplicate_name;
}
SendResponse(false, coincidence_result);
return;
}
if (IsWhiteSpaceExist()) {
LOG4CXX_INFO(logger_,
"Incoming register app interface has contains \t\n \\t \\n");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
application = application_manager_.RegisterApplication(message_);
if (!application) {
LOG4CXX_ERROR(logger_, "Application hasn't been registered!");
return;
}
// For resuming application need to restore hmi_app_id from resumeCtrl
resumption::ResumeCtrl& resumer = application_manager_.resume_controller();
const std::string& device_mac = application->mac_address();
// there is side affect with 2 mobile app with the same mobile app_id
if (resumer.IsApplicationSaved(policy_app_id, device_mac)) {
application->set_hmi_application_id(
resumer.GetHMIApplicationID(policy_app_id, device_mac));
} else {
application->set_hmi_application_id(
application_manager_.GenerateNewHMIAppID());
}
application->set_is_media_application(
msg_params[strings::is_media_application].asBool());
if (msg_params.keyExists(strings::vr_synonyms)) {
application->set_vr_synonyms(msg_params[strings::vr_synonyms]);
}
if (msg_params.keyExists(strings::ngn_media_screen_app_name)) {
application->set_ngn_media_screen_name(
msg_params[strings::ngn_media_screen_app_name]);
}
if (msg_params.keyExists(strings::tts_name)) {
application->set_tts_name(msg_params[strings::tts_name]);
}
if (msg_params.keyExists(strings::app_hmi_type)) {
application->set_app_types(msg_params[strings::app_hmi_type]);
// check app type
const smart_objects::SmartObject& app_type =
msg_params.getElement(strings::app_hmi_type);
for (size_t i = 0; i < app_type.length(); ++i) {
if (mobile_apis::AppHMIType::NAVIGATION ==
static_cast<mobile_apis::AppHMIType::eType>(
app_type.getElement(i).asUInt())) {
application->set_is_navi(true);
}
if (mobile_apis::AppHMIType::COMMUNICATION ==
static_cast<mobile_apis::AppHMIType::eType>(
app_type.getElement(i).asUInt())) {
application->set_voice_communication_supported(true);
}
}
}
// Add device to policy table and set device info, if any
policy::DeviceParams dev_params;
if (-1 ==
application_manager_.connection_handler()
.get_session_observer()
.GetDataOnDeviceID(application->device(),
&dev_params.device_name,
NULL,
&dev_params.device_mac_address,
&dev_params.device_connection_type)) {
LOG4CXX_ERROR(logger_,
"Failed to extract information for device "
<< application->device());
}
policy::DeviceInfo device_info;
device_info.AdoptDeviceType(dev_params.device_connection_type);
if (msg_params.keyExists(strings::device_info)) {
FillDeviceInfo(&device_info);
}
GetPolicyHandler().SetDeviceInfo(device_mac, device_info);
SendRegisterAppInterfaceResponseToMobile();
smart_objects::SmartObjectSPtr so =
GetLockScreenIconUrlNotification(connection_key(), application);
application_manager_.ManageMobileCommand(so, commands::Command::ORIGIN_SDL);
}
smart_objects::SmartObjectSPtr
RegisterAppInterfaceRequest::GetLockScreenIconUrlNotification(
const uint32_t connection_key, ApplicationSharedPtr app) {
DCHECK_OR_RETURN(app.get(), smart_objects::SmartObjectSPtr());
smart_objects::SmartObjectSPtr message =
utils::MakeShared<smart_objects::SmartObject>(
smart_objects::SmartType_Map);
(*message)[strings::params][strings::function_id] =
mobile_apis::FunctionID::OnSystemRequestID;
(*message)[strings::params][strings::connection_key] = connection_key;
(*message)[strings::params][strings::message_type] =
mobile_apis::messageType::notification;
(*message)[strings::params][strings::protocol_type] =
commands::CommandImpl::mobile_protocol_type_;
(*message)[strings::params][strings::protocol_version] =
commands::CommandImpl::protocol_version_;
(*message)[strings::msg_params][strings::request_type] =
mobile_apis::RequestType::LOCK_SCREEN_ICON_URL;
(*message)[strings::msg_params][strings::url] =
GetPolicyHandler().GetLockScreenIconUrl();
return message;
}
void FillVRRelatedFields(smart_objects::SmartObject& response_params,
const HMICapabilities& hmi_capabilities) {
response_params[strings::language] = hmi_capabilities.active_vr_language();
if (hmi_capabilities.vr_capabilities()) {
response_params[strings::vr_capabilities] =
*hmi_capabilities.vr_capabilities();
}
}
void FillVIRelatedFields(smart_objects::SmartObject& response_params,
const HMICapabilities& hmi_capabilities) {
if (hmi_capabilities.vehicle_type()) {
response_params[hmi_response::vehicle_type] =
*hmi_capabilities.vehicle_type();
}
}
void FillTTSRelatedFields(smart_objects::SmartObject& response_params,
const HMICapabilities& hmi_capabilities) {
response_params[strings::language] = hmi_capabilities.active_tts_language();
if (hmi_capabilities.speech_capabilities()) {
response_params[strings::speech_capabilities] =
*hmi_capabilities.speech_capabilities();
}
if (hmi_capabilities.prerecorded_speech()) {
response_params[strings::prerecorded_speech] =
*(hmi_capabilities.prerecorded_speech());
}
}
void FillUIRelatedFields(smart_objects::SmartObject& response_params,
const HMICapabilities& hmi_capabilities) {
response_params[strings::hmi_display_language] =
hmi_capabilities.active_ui_language();
if (hmi_capabilities.display_capabilities()) {
response_params[hmi_response::display_capabilities] =
smart_objects::SmartObject(smart_objects::SmartType_Map);
smart_objects::SmartObject& display_caps =
response_params[hmi_response::display_capabilities];
display_caps[hmi_response::display_type] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::display_type);
display_caps[hmi_response::text_fields] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::text_fields);
display_caps[hmi_response::image_fields] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::image_fields);
display_caps[hmi_response::media_clock_formats] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::media_clock_formats);
display_caps[hmi_response::templates_available] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::templates_available);
display_caps[hmi_response::screen_params] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::screen_params);
display_caps[hmi_response::num_custom_presets_available] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::num_custom_presets_available);
display_caps[hmi_response::graphic_supported] =
(hmi_capabilities.display_capabilities()
->getElement(hmi_response::image_capabilities)
.length() > 0);
display_caps[hmi_response::templates_available] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::templates_available);
display_caps[hmi_response::screen_params] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::screen_params);
display_caps[hmi_response::num_custom_presets_available] =
hmi_capabilities.display_capabilities()->getElement(
hmi_response::num_custom_presets_available);
}
if (hmi_capabilities.audio_pass_thru_capabilities()) {
if (smart_objects::SmartType_Array ==
hmi_capabilities.audio_pass_thru_capabilities()->getType()) {
// hmi_capabilities json contains array and HMI response object
response_params[strings::audio_pass_thru_capabilities] =
*hmi_capabilities.audio_pass_thru_capabilities();
} else {
response_params[strings::audio_pass_thru_capabilities][0] =
*hmi_capabilities.audio_pass_thru_capabilities();
}
}
response_params[strings::hmi_capabilities] =
smart_objects::SmartObject(smart_objects::SmartType_Map);
response_params[strings::hmi_capabilities][strings::navigation] =
hmi_capabilities.navigation_supported();
response_params[strings::hmi_capabilities][strings::phone_call] =
hmi_capabilities.phone_call_supported();
}
void RegisterAppInterfaceRequest::SendRegisterAppInterfaceResponseToMobile() {
LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObject response_params(smart_objects::SmartType_Map);
mobile_apis::Result::eType result_code = mobile_apis::Result::SUCCESS;
const HMICapabilities& hmi_capabilities =
application_manager_.hmi_capabilities();
const uint32_t key = connection_key();
ApplicationSharedPtr application = application_manager_.application(key);
resumption::ResumeCtrl& resumer = application_manager_.resume_controller();
if (!application) {
LOG4CXX_ERROR(logger_,
"There is no application for such connection key" << key);
LOG4CXX_DEBUG(logger_, "Need to start resume data persistent timer");
resumer.OnAppRegistrationEnd();
return;
}
response_params[strings::sync_msg_version][strings::major_version] =
major_version; // From generated file interfaces/generated_msg_version.h
response_params[strings::sync_msg_version][strings::minor_version] =
minor_version; // From generated file interfaces/generated_msg_version.h
const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
if (msg_params[strings::language_desired].asInt() !=
hmi_capabilities.active_vr_language() ||
msg_params[strings::hmi_display_language_desired].asInt() !=
hmi_capabilities.active_ui_language()) {
LOG4CXX_WARN(logger_,
"Wrong language on registering application "
<< application->name().c_str());
LOG4CXX_ERROR(
logger_,
"VR language desired code is "
<< msg_params[strings::language_desired].asInt()
<< " , active VR language code is "
<< hmi_capabilities.active_vr_language() << ", UI language code is "
<< msg_params[strings::hmi_display_language_desired].asInt()
<< " , active UI language code is "
<< hmi_capabilities.active_ui_language());
result_code = mobile_apis::Result::WRONG_LANGUAGE;
}
if (HmiInterfaces::STATE_NOT_AVAILABLE !=
application_manager_.hmi_interfaces().GetInterfaceState(
HmiInterfaces::HMI_INTERFACE_TTS)) {
FillTTSRelatedFields(response_params, hmi_capabilities);
}
if (HmiInterfaces::STATE_NOT_AVAILABLE !=
application_manager_.hmi_interfaces().GetInterfaceState(
HmiInterfaces::HMI_INTERFACE_VR)) {
FillVRRelatedFields(response_params, hmi_capabilities);
}
if (HmiInterfaces::STATE_NOT_AVAILABLE !=
application_manager_.hmi_interfaces().GetInterfaceState(
HmiInterfaces::HMI_INTERFACE_UI)) {
FillUIRelatedFields(response_params, hmi_capabilities);
}
if (hmi_capabilities.button_capabilities()) {
response_params[hmi_response::button_capabilities] =
*hmi_capabilities.button_capabilities();
}
if (hmi_capabilities.soft_button_capabilities()) {
response_params[hmi_response::soft_button_capabilities] =
*hmi_capabilities.soft_button_capabilities();
}
if (hmi_capabilities.preset_bank_capabilities()) {
response_params[hmi_response::preset_bank_capabilities] =
*hmi_capabilities.preset_bank_capabilities();
}
if (hmi_capabilities.hmi_zone_capabilities()) {
if (smart_objects::SmartType_Array ==
hmi_capabilities.hmi_zone_capabilities()->getType()) {
// hmi_capabilities json contains array and HMI response object
response_params[hmi_response::hmi_zone_capabilities] =
*hmi_capabilities.hmi_zone_capabilities();
} else {
response_params[hmi_response::hmi_zone_capabilities][0] =
*hmi_capabilities.hmi_zone_capabilities();
}
}
if (HmiInterfaces::STATE_NOT_AVAILABLE !=
application_manager_.hmi_interfaces().GetInterfaceState(
HmiInterfaces::HMI_INTERFACE_TTS)) {
FillTTSRelatedFields(response_params, hmi_capabilities);
}
if (hmi_capabilities.pcm_stream_capabilities()) {
response_params[strings::pcm_stream_capabilities] =
*hmi_capabilities.pcm_stream_capabilities();
}
if (HmiInterfaces::STATE_NOT_AVAILABLE !=
application_manager_.hmi_interfaces().GetInterfaceState(
HmiInterfaces::HMI_INTERFACE_VehicleInfo)) {
FillVIRelatedFields(response_params, hmi_capabilities);
}
const std::vector<uint32_t>& diag_modes =
application_manager_.get_settings().supported_diag_modes();
if (!diag_modes.empty()) {
std::vector<uint32_t>::const_iterator it = diag_modes.begin();
uint32_t index = 0;
for (; it != diag_modes.end(); ++it) {
response_params[strings::supported_diag_modes][index] = *it;
++index;
}
}
response_params[strings::sdl_version] =
application_manager_.get_settings().sdl_version();
const std::string ccpu_version =
application_manager_.hmi_capabilities().ccpu_version();
if (!ccpu_version.empty()) {
response_params[strings::system_software_version] = ccpu_version;
}
bool resumption =
(*message_)[strings::msg_params].keyExists(strings::hash_id);
bool need_restore_vr = resumption;
std::string hash_id;
std::string add_info;
if (resumption) {
hash_id = (*message_)[strings::msg_params][strings::hash_id].asString();
if (!resumer.CheckApplicationHash(application, hash_id)) {
LOG4CXX_WARN(logger_,
"Hash from RAI does not match to saved resume data.");
result_code = mobile_apis::Result::RESUME_FAILED;
add_info = "Hash from RAI does not match to saved resume data.";
need_restore_vr = false;
} else if (!resumer.CheckPersistenceFilesForResumption(application)) {
LOG4CXX_WARN(logger_, "Persistent data is missing.");
result_code = mobile_apis::Result::RESUME_FAILED;
add_info = "Persistent data is missing.";
need_restore_vr = false;
} else {
add_info = "Resume succeeded.";
}
}
if ((mobile_apis::Result::SUCCESS == result_code) &&
(mobile_apis::Result::INVALID_ENUM != result_checking_app_hmi_type_)) {
add_info += response_info_;
result_code = result_checking_app_hmi_type_;
}
// in case application exist in resumption we need to send resumeVrgrammars
if (false == resumption) {
resumption = resumer.IsApplicationSaved(application->policy_app_id(),
application->mac_address());
}
SendResponse(true, result_code, add_info.c_str(), &response_params);
SendOnAppRegisteredNotificationToHMI(
*(application.get()), resumption, need_restore_vr);
if (result_code != mobile_apis::Result::RESUME_FAILED) {
resumer.StartResumption(application, hash_id);
} else {
resumer.StartResumptionOnlyHMILevel(application);
}
// By default app subscribed to CUSTOM_BUTTON
SendSubscribeCustomButtonNotification();
SendChangeRegistrationOnHMI(application);
}
void RegisterAppInterfaceRequest::SendChangeRegistration(
const hmi_apis::FunctionID::eType function_id,
const int32_t language,
const uint32_t app_id) {
using helpers::Compare;
using helpers::EQ;
using helpers::ONE;
const HmiInterfaces& hmi_interfaces = application_manager_.hmi_interfaces();
const HmiInterfaces::InterfaceID interface =
hmi_interfaces.GetInterfaceFromFunction(function_id);
if (hmi_interfaces.GetInterfaceState(interface) !=
HmiInterfaces::STATE_NOT_AVAILABLE) {
smart_objects::SmartObject msg_params(smart_objects::SmartType_Map);
msg_params[strings::language] = language;
msg_params[strings::app_id] = app_id;
SendHMIRequest(function_id, &msg_params);
} else {
LOG4CXX_DEBUG(logger_, "Interface " << interface << "is not avaliable");
}
}
void RegisterAppInterfaceRequest::SendChangeRegistrationOnHMI(
ApplicationConstSharedPtr app) {
using namespace hmi_apis::FunctionID;
DCHECK_OR_RETURN_VOID(app);
DCHECK_OR_RETURN_VOID(mobile_apis::Language::INVALID_ENUM != app->language());
SendChangeRegistration(VR_ChangeRegistration, app->language(), app->app_id());
SendChangeRegistration(
TTS_ChangeRegistration, app->language(), app->app_id());
SendChangeRegistration(UI_ChangeRegistration, app->language(), app->app_id());
}
void RegisterAppInterfaceRequest::SendOnAppRegisteredNotificationToHMI(
const Application& application_impl,
bool resumption,
bool need_restore_vr) {
using namespace smart_objects;
SmartObjectSPtr notification = utils::MakeShared<SmartObject>(SmartType_Map);
if (!notification) {
LOG4CXX_ERROR(logger_, "Failed to create smart object");
return;
}
(*notification)[strings::params] = SmartObject(SmartType_Map);
smart_objects::SmartObject& params = (*notification)[strings::params];
params[strings::function_id] = static_cast<int32_t>(
hmi_apis::FunctionID::BasicCommunication_OnAppRegistered);
params[strings::message_type] = static_cast<int32_t>(kNotification);
params[strings::protocol_version] = commands::CommandImpl::protocol_version_;
params[strings::protocol_type] = commands::CommandImpl::hmi_protocol_type_;
(*notification)[strings::msg_params] = SmartObject(SmartType_Map);
smart_objects::SmartObject& msg_params = (*notification)[strings::msg_params];
// Due to current requirements in case when we're in resumption mode
// we have to always send resumeVRGrammar field.
if (resumption) {
msg_params[strings::resume_vr_grammars] = need_restore_vr;
}
if (application_impl.vr_synonyms()) {
msg_params[strings::vr_synonyms] = *(application_impl.vr_synonyms());
}
if (application_impl.tts_name()) {
msg_params[strings::tts_name] = *(application_impl.tts_name());
}
std::string priority;
GetPolicyHandler().GetPriority(application_impl.policy_app_id(), &priority);
if (!priority.empty()) {
msg_params[strings::priority] = MessageHelper::GetPriorityCode(priority);
}
msg_params[strings::msg_params] = SmartObject(SmartType_Map);
smart_objects::SmartObject& application = msg_params[strings::application];
application[strings::app_name] = application_impl.name();
application[strings::app_id] = application_impl.app_id();
application[hmi_response::policy_app_id] = application_impl.policy_app_id();
application[strings::icon] = application_impl.app_icon_path();
const smart_objects::SmartObject* ngn_media_screen_name =
application_impl.ngn_media_screen_name();
if (ngn_media_screen_name) {
application[strings::ngn_media_screen_app_name] = *ngn_media_screen_name;
}
application[strings::hmi_display_language_desired] =
static_cast<int32_t>(application_impl.ui_language());
application[strings::is_media_application] =
application_impl.is_media_application();
const smart_objects::SmartObject* app_type = application_impl.app_types();
if (app_type) {
application[strings::app_type] = *app_type;
}
std::vector<std::string> request_types =
GetPolicyHandler().GetAppRequestTypes(application_impl.policy_app_id());
application[strings::request_type] = SmartObject(SmartType_Array);
smart_objects::SmartObject& request_array =
application[strings::request_type];
uint32_t index = 0;
std::vector<std::string>::const_iterator it = request_types.begin();
for (; request_types.end() != it; ++it) {
request_array[index] = *it;
++index;
}
application[strings::device_info] = SmartObject(SmartType_Map);
smart_objects::SmartObject& device_info = application[strings::device_info];
const protocol_handler::SessionObserver& session_observer =
application_manager_.connection_handler().get_session_observer();
std::string device_name;
std::string mac_address;
std::string transport_type;
const connection_handler::DeviceHandle handle = application_impl.device();
if (-1 ==
session_observer.GetDataOnDeviceID(
handle, &device_name, NULL, &mac_address, &transport_type)) {
LOG4CXX_ERROR(logger_,
"Failed to extract information for device " << handle);
}
device_info[strings::name] = device_name;
device_info[strings::id] = mac_address;
const policy::DeviceConsent device_consent =
GetPolicyHandler().GetUserConsentForDevice(mac_address);
device_info[strings::isSDLAllowed] =
policy::DeviceConsent::kDeviceAllowed == device_consent;
device_info[strings::transport_type] =
application_manager_.GetDeviceTransportType(transport_type);
DCHECK(application_manager_.ManageHMICommand(notification));
}
mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckCoincidence() {
LOG4CXX_AUTO_TRACE(logger_);
const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
ApplicationSet accessor = application_manager_.applications().GetData();
ApplicationSetConstIt it = accessor.begin();
const custom_str::CustomString& app_name =
msg_params[strings::app_name].asCustomString();
for (; accessor.end() != it; ++it) {
// name check
const custom_str::CustomString& cur_name = (*it)->name();
if (app_name.CompareIgnoreCase(cur_name)) {
LOG4CXX_ERROR(logger_, "Application name is known already.");
return mobile_apis::Result::DUPLICATE_NAME;
}
const smart_objects::SmartObject* vr = (*it)->vr_synonyms();
const std::vector<smart_objects::SmartObject>* curr_vr = NULL;
if (NULL != vr) {
curr_vr = vr->asArray();
CoincidencePredicateVR v(app_name);
if (0 != std::count_if(curr_vr->begin(), curr_vr->end(), v)) {
LOG4CXX_ERROR(logger_, "Application name is known already.");
return mobile_apis::Result::DUPLICATE_NAME;
}
}
// vr check
if (msg_params.keyExists(strings::vr_synonyms)) {
const std::vector<smart_objects::SmartObject>* new_vr =
msg_params[strings::vr_synonyms].asArray();
CoincidencePredicateVR v(cur_name);
if (0 != std::count_if(new_vr->begin(), new_vr->end(), v)) {
LOG4CXX_ERROR(logger_, "vr_synonyms duplicated with app_name .");
return mobile_apis::Result::DUPLICATE_NAME;
}
} // end vr check
} // application for end
return mobile_apis::Result::SUCCESS;
} // method end
mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckWithPolicyData() {
LOG4CXX_AUTO_TRACE(logger_);
// TODO(AOleynik): Check is necessary to allow register application in case
// of disabled policy
// Remove this check, when HMI will support policy
if (!GetPolicyHandler().PolicyEnabled()) {
return mobile_apis::Result::WARNINGS;
}
smart_objects::SmartObject& message = *message_;
policy::StringArray app_nicknames;
policy::StringArray app_hmi_types;
const std::string mobile_app_id =
message[strings::msg_params][strings::app_id].asString();
const bool init_result = GetPolicyHandler().GetInitialAppData(
mobile_app_id, &app_nicknames, &app_hmi_types);
if (!init_result) {
LOG4CXX_ERROR(logger_, "Error during initial application data check.");
return mobile_apis::Result::INVALID_DATA;
}
if (!app_nicknames.empty()) {
IsSameNickname compare(
message[strings::msg_params][strings::app_name].asCustomString());
policy::StringArray::const_iterator it =
std::find_if(app_nicknames.begin(), app_nicknames.end(), compare);
if (app_nicknames.end() == it) {
LOG4CXX_WARN(logger_,
"Application name was not found in nicknames list.");
// App should be unregistered, if its name is not present in nicknames
// list
usage_statistics::AppCounter count_of_rejections_nickname_mismatch(
GetPolicyHandler().GetStatisticManager(),
mobile_app_id,
usage_statistics::REJECTIONS_NICKNAME_MISMATCH);
++count_of_rejections_nickname_mismatch;
return mobile_apis::Result::DISALLOWED;
}
}
mobile_apis::Result::eType result = mobile_apis::Result::SUCCESS;
// If AppHMIType is not included in policy - allow any type
if (!app_hmi_types.empty()) {
if (message[strings::msg_params].keyExists(strings::app_hmi_type)) {
// If AppHMITypes are partially same, the system should allow those listed
// in the policy table and send warning info on missed values
smart_objects::SmartArray app_types =
*(message[strings::msg_params][strings::app_hmi_type].asArray());
std::string log;
CheckMissedTypes checker(app_hmi_types, log);
std::for_each(app_types.begin(), app_types.end(), checker);
if (!log.empty()) {
response_info_ =
"Following AppHMITypes are not present in policy "
"table:" +
log;
result_checking_app_hmi_type_ = mobile_apis::Result::WARNINGS;
}
}
// Replace AppHMITypes in request with values allowed by policy table
message[strings::msg_params][strings::app_hmi_type] =
smart_objects::SmartObject(smart_objects::SmartType_Array);
smart_objects::SmartObject& app_hmi_type =
message[strings::msg_params][strings::app_hmi_type];
AppHMITypeInserter inserter(app_hmi_type);
std::for_each(app_hmi_types.begin(), app_hmi_types.end(), inserter);
}
return result;
}
void RegisterAppInterfaceRequest::FillDeviceInfo(
policy::DeviceInfo* device_info) {
const std::string hardware = "hardware";
const std::string firmware_rev = "firmwareRev";
const std::string os = "os";
const std::string os_ver = "osVersion";
const std::string carrier = "carrier";
const std::string max_number_rfcom_ports = "maxNumberRFCOMMPorts";
const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
const smart_objects::SmartObject& device_info_so =
msg_params[strings::device_info];
if (device_info_so.keyExists(hardware)) {
device_info->hardware =
msg_params[strings::device_info][hardware].asString();
}
if (device_info_so.keyExists(firmware_rev)) {
device_info->firmware_rev =
msg_params[strings::device_info][firmware_rev].asString();
}
if (device_info_so.keyExists(os)) {
device_info->os = device_info_so[os].asString();
}
if (device_info_so.keyExists(os_ver)) {
device_info->os_ver = device_info_so[os_ver].asString();
}
if (device_info_so.keyExists(carrier)) {
device_info->carrier = device_info_so[carrier].asString();
}
if (device_info_so.keyExists(max_number_rfcom_ports)) {
device_info->max_number_rfcom_ports =
device_info_so[max_number_rfcom_ports].asInt();
}
}
bool RegisterAppInterfaceRequest::IsApplicationWithSameAppIdRegistered() {
LOG4CXX_AUTO_TRACE(logger_);
const custom_string::CustomString mobile_app_id =
(*message_)[strings::msg_params][strings::app_id].asCustomString();
const ApplicationSet& applications =
application_manager_.applications().GetData();
ApplicationSetConstIt it = applications.begin();
ApplicationSetConstIt it_end = applications.end();
for (; it != it_end; ++it) {
if (mobile_app_id.CompareIgnoreCase((*it)->policy_app_id().c_str())) {
return true;
}
}
return false;
}
bool RegisterAppInterfaceRequest::IsWhiteSpaceExist() {
LOG4CXX_AUTO_TRACE(logger_);
const char* str = NULL;
str = (*message_)[strings::msg_params][strings::app_name].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid app_name syntax check failed");
return true;
}
if ((*message_)[strings::msg_params].keyExists(strings::tts_name)) {
const smart_objects::SmartArray* tn_array =
(*message_)[strings::msg_params][strings::tts_name].asArray();
smart_objects::SmartArray::const_iterator it_tn = tn_array->begin();
smart_objects::SmartArray::const_iterator it_tn_end = tn_array->end();
for (; it_tn != it_tn_end; ++it_tn) {
str = (*it_tn)[strings::text].asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid tts_name syntax check failed");
return true;
}
}
}
if ((*message_)[strings::msg_params].keyExists(
strings::ngn_media_screen_app_name)) {
str = (*message_)[strings::msg_params][strings::ngn_media_screen_app_name]
.asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid ngn_media_screen_app_name syntax check failed");
return true;
}
}
if ((*message_)[strings::msg_params].keyExists(strings::vr_synonyms)) {
const smart_objects::SmartArray* vs_array =
(*message_)[strings::msg_params][strings::vr_synonyms].asArray();
smart_objects::SmartArray::const_iterator it_vs = vs_array->begin();
smart_objects::SmartArray::const_iterator it_vs_end = vs_array->end();
for (; it_vs != it_vs_end; ++it_vs) {
str = (*it_vs).asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid vr_synonyms syntax check failed");
return true;
}
}
}
if ((*message_)[strings::msg_params].keyExists(strings::hash_id)) {
str = (*message_)[strings::msg_params][strings::hash_id].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid hash_id syntax check failed");
return true;
}
}
if ((*message_)[strings::msg_params].keyExists(strings::device_info)) {
if ((*message_)[strings::msg_params][strings::device_info].keyExists(
strings::hardware)) {
str = (*message_)[strings::msg_params][strings::device_info]
[strings::hardware].asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid device_info hardware syntax check failed");
return true;
}
}
if ((*message_)[strings::msg_params][strings::device_info].keyExists(
strings::firmware_rev)) {
str = (*message_)[strings::msg_params][strings::device_info]
[strings::firmware_rev].asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid device_info firmware_rev syntax check failed");
return true;
}
}
if ((*message_)[strings::msg_params][strings::device_info].keyExists(
strings::os)) {
str = (*message_)[strings::msg_params][strings::device_info][strings::os]
.asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid device_info os syntax check failed");
return true;
}
}
if ((*message_)[strings::msg_params][strings::device_info].keyExists(
strings::os_version)) {
str = (*message_)[strings::msg_params][strings::device_info]
[strings::os_version].asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid device_info os_version syntax check failed");
return true;
}
}
if ((*message_)[strings::msg_params][strings::device_info].keyExists(
strings::carrier)) {
str = (*message_)[strings::msg_params][strings::device_info]
[strings::carrier].asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid device_info carrier syntax check failed");
return true;
}
}
}
if ((*message_)[strings::msg_params].keyExists(strings::app_id)) {
str = (*message_)[strings::msg_params][strings::app_id].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid app_id syntax check failed");
return true;
}
}
return false;
}
void RegisterAppInterfaceRequest::CheckResponseVehicleTypeParam(
smart_objects::SmartObject& vehicle_type,
const std::string& param,
const std::string& backup_value) {
using namespace hmi_response;
if (!vehicle_type.keyExists(param) || vehicle_type[param].empty()) {
if (!backup_value.empty()) {
LOG4CXX_DEBUG(logger_,
param << " is missing."
"Will be replaced with policy table value.");
vehicle_type[param] = backup_value;
} else {
vehicle_type.erase(param);
}
}
}
void RegisterAppInterfaceRequest::SendSubscribeCustomButtonNotification() {
using namespace smart_objects;
using namespace hmi_apis;
SmartObject msg_params = SmartObject(SmartType_Map);
msg_params[strings::app_id] = connection_key();
msg_params[strings::name] = Common_ButtonName::CUSTOM_BUTTON;
msg_params[strings::is_suscribed] = true;
CreateHMINotification(FunctionID::Buttons_OnButtonSubscription, msg_params);
}
policy::PolicyHandlerInterface&
RegisterAppInterfaceRequest::GetPolicyHandler() {
return application_manager_.GetPolicyHandler();
}
} // namespace commands
} // namespace application_manager
|
389f496b73bf4d14d4b86b1e51eefa651732189d
|
f81c34bc603914dc7d076924618cdd29d8e2acf7
|
/Functions/Roo2SumExp.cxx
|
f0c4049b1ac0058c1b36b0db5547606170c954ed
|
[] |
no_license
|
Xaunther/root-tools
|
342704e362ddaf3d825298eafda9c3ca6afc28de
|
1472980f9f72eac0685daf470b5892f9d008edd4
|
refs/heads/master
| 2023-08-23T07:06:35.728180
| 2021-09-28T09:25:53
| 2021-09-28T09:25:53
| 411,723,170
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,724
|
cxx
|
Roo2SumExp.cxx
|
/********************************************************************
* *
* \[T]/ P R A I S E T H E R O O C L A S S F A C T O R Y \[T]/ *
* *
*******************************************************************/
#include "Riostream.h"
#include "Functions/Roo2SumExp.h"
#include "RooAbsReal.h"
#include "RooAbsCategory.h"
#include <math.h>
#include "TMath.h"
#include "RooMath.h"
//ClassImp(Roo2SumExp)
Roo2SumExp::Roo2SumExp(const char *name, const char *title,
RooAbsReal& _m,
RooAbsReal& _A,
RooAbsReal& _tau1,
RooAbsReal& _tau2) :
RooAbsPdf(name,title),
m("m","m",this,_m),
A("A","A",this,_A),
tau1("tau1","tau1",this,_tau1),
tau2("tau2","tau2",this,_tau2)
{
}
Roo2SumExp::Roo2SumExp(const Roo2SumExp& other, const char* name) :
RooAbsPdf(other,name),
m("m",this,other.m),
A("A",this,other.A),
tau1("tau1",this,other.tau1),
tau2("tau2",this,other.tau2)
{
}
Double_t Roo2SumExp::evaluate() const
{
double result;
result = std::exp(m*tau1)+A*std::exp(m*tau2);
return result ;
}
Int_t Roo2SumExp::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const
{
if( matchArgs(allVars,analVars,m) ) return 1 ;
return 0 ;
}
Double_t Roo2SumExp::analyticalIntegral(Int_t code, const char* rangeName) const
{
R__ASSERT(code==1);
double mmin = m.min(rangeName) ;
double mmax = m.max(rangeName) ;
assert( code==1 ) ;
double result;
// Integrate
result = (std::exp(mmax*tau1)-std::exp(mmin*tau1))/tau1+A*(std::exp(mmax*tau2)-std::exp(mmin*tau2))/tau2;
return result;
}
|
069d8b6d5656ccec634c2fbff44e4884deb64e59
|
38269173c9e65bc090eef96c7dee1365b92e40c2
|
/HashTable/CountingSort/CountingSort/main.cpp
|
def45b7f8ee1e60ec3207855b14318a6fb134bf4
|
[] |
no_license
|
SecurityQQ/CPlusPlus_MIPT_Algorithms
|
0a25e7026a2f8c59305077f1e8c6901c5bee5daa
|
abb51f63a879abd3517a458499b17b101852b900
|
refs/heads/master
| 2020-04-16T01:46:08.294347
| 2015-10-09T09:01:17
| 2015-10-09T09:01:17
| 43,944,397
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,573
|
cpp
|
main.cpp
|
//
// main.cpp
// CountingSort
//
// Created by Александр Малышев on 10.11.14.
// Copyright (c) 2014 SecurityQQ. All rights reserved.
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
const int MaxSize = 1000;
void countSort(int* arr, int n);
int main(int argc, const char * argv[]) {
int n = 0;
int* data = (int*) malloc(MaxSize * sizeof(int));
while( scanf("%d", &data[n]) == 1) {
++n;
}
countSort(data, n);
for( int i = 0; i < n; ++i ) {
std::cout<<data[i] << " ";
}
free(data);
return 0;
}
void countSort(int* data, int n) {
assert(n > 0);
int minValue = data[0];
int maxValue = data[0];
//Finding min and max values in array
for( int i = 0; i < n; ++i) {
minValue = std::min(data[i], minValue);
maxValue = std::max(data[i], maxValue);
}
int valuesCount = maxValue - minValue + 1;
int* valuesData = (int*)calloc(valuesCount, sizeof(int));
for( int i = 0; i < n; ++i) {
++valuesData[data[i] - minValue];
}
for( int i = 1; i < valuesCount; ++i) {
valuesData[i] += valuesData[i - 1];
}
int* tempData = (int*) malloc(n * sizeof(int));
for( int i = n - 1; i >= 0; --i) {
int value = data[i] - minValue;
--valuesData[value];
tempData[valuesData[value]] = data[i];
}
memcpy(data, tempData, n * sizeof(int));
free(tempData);
free(valuesData);
}
|
39e6ce2dfedf57ea66f19f4763290c522a93f05b
|
5e6b47d32d27bdb3e8fbe962dd3fb521a8a248a5
|
/lab08/bigthree.cpp
|
58a2c7900d10a178486e0d78927cecaf185494d1
|
[] |
no_license
|
tgroechel/F17-280
|
45db4bca7f29420e3faa4e405c1ef7508378a3a0
|
fd79973a17dfaae94be034490687264c2d85af76
|
refs/heads/master
| 2021-08-28T18:44:18.683841
| 2017-12-13T00:42:59
| 2017-12-13T00:42:59
| 103,156,666
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,791
|
cpp
|
bigthree.cpp
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class A {
private:
int size;
int * arr;
void copy_rhs(const A & right_hand_side) {
size = right_hand_side.size;
arr = new int[size];
for (int i = 0; i < size; ++i) {
arr[i] = right_hand_side.arr[i];
}
}
public:
static int potato;
A() : size(3), arr(new int[size]) {
for (int i = 0; i < size; ++i) {
arr[i] = i;
}
}
A(const A & right_hand_side) {
copy_rhs(right_hand_side);
}
A & operator=(const A & right_hand_side) {
if (&right_hand_side == this) {
return *this;
}
delete[] arr;
copy_rhs(right_hand_side);
return *this;
}
~A() {
delete[] arr;
}
};
int A::potato = 0;
int main(int argc, char ** argv) {
A a1; // a1 = {size = 3, int * arr = 0x10}
A a2(a1); // a2 = {size =3, int * arr = 0x40} ->
a1 = a2; // a1 = {size = 3, int * arr = 0x30} -> 0x30:[0,1,2]
a2 = a2; // a2 = {size = 3, int * arr = 0x60} -> 0x60:[ , , ]
cout << a1.potato << endl; // 0
a1.potato++;
a2.potato++;
cout << a1.potato << endl; // 2
cout << a2.potato << endl; // 2
auto i = 9;
cout << i << endl;
std::vector<int> v1;
v1.push_back(2);
v1.push_back(3);
for (vector<int>::iterator it = v1.begin(); it != v1.end(); ++it) {
cout << *it << endl;
}
for (auto it = v1.begin(); it != v1.end(); ++it) {
cout << *it << endl;
}
for (auto & it : v1) {
cout << it << endl;
it = 9;
}
for (const auto & it : v1) {
cout << it << endl;
}
// a1.i++;
// a2.i++;
// cout << a1.i << endl;
return 0;
}
|
0b44c9e4b8e310774075ff98ea0579016c53e0c0
|
fecf09fb6dd1b102764890eb6d112af5d934fa21
|
/基础练习代码/数组中的字符串匹配.cpp
|
0afbfbe45f1c44f6ba1687cc92355a3458aa0a48
|
[] |
no_license
|
zhaomengchao/C-
|
5821df6d004b791e1212140fa734d20b01b00e8c
|
377b99061bc4d7122438fbe6c5c76a7201b0f993
|
refs/heads/master
| 2021-07-12T15:02:02.509446
| 2020-10-12T09:08:55
| 2020-10-12T09:08:55
| 209,292,144
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,110
|
cpp
|
数组中的字符串匹配.cpp
|
/*
输入:words = ["mass","as","hero","superhero"]
输出:["as","hero"]
解释:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。
["hero","as"] 也是有效的答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-matching-in-an-array
*/
class Solution {
public:
static bool lengthcompare(string& a, string& b){
if(a.length()<b.length()){
return true;
}
return false;
}
vector<string> stringMatching(vector<string>& words) {
vector<string> result;
bool flag;
sort(words.begin(),words.end(),lengthcompare);
for(int i = 0;i < words.size()-1;i++)
{
for(int j = i+1;j < words.size();j++)
{
flag = false;
if(-1 != words[j].find(words[i]))
{
flag = true;
break;
}
}
if(flag)
{
result.push_back(words[i]);
}
}
return result;
}
};
|
85fa60ac309afb22d477cc7fab5fb461be8ed427
|
3cd6d8c07fff1c7851418aaf0a0a10b0ae3d888c
|
/i2c-argon.ino
|
4d65778d00866aced8b55ba9092e82dbf4170c68
|
[] |
no_license
|
elpeacey/SIT210_Task8.1D_RPi_I2C-
|
6105fb65168f7192589cc015acacc7ac68394494
|
a04ee2c0cadb97d6957f7cf54a7f55460a7987e5
|
refs/heads/master
| 2022-09-22T10:02:42.027858
| 2020-06-03T00:13:21
| 2020-06-03T00:13:21
| 268,932,756
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 803
|
ino
|
i2c-argon.ino
|
#include "Particle.h"
void setup() {
Wire.begin(0x40); //Initialise argon on slave address 40
Wire.onReceive(observeEvent); //When master device sends signal, call observeEvent
Serial.print("Light value");
}
void observeEvent(int bytes) {
int c = Wire.read(); //Read value from RPi
while( Wire.available() ) {
if( c == 1 ) {
Serial.println("Too dark");
}
else if( c == 2 ) {
Serial.println("Dark");
}
else if( c == 3 ) {
Serial.println("Medium");
}
else if( c == 4 ) {
Serial.println("Bright");
}
else {
Serial.println("Too bright");
}
}
}
void loop() {
delay(50);
}
|
b3e6caedc194f749dbc4e5318e3340ab393af057
|
1eddfc58034e70dbf32c93c5ecdfc47e377eca84
|
/examenes.cpp
|
16ab79c21a8d8809a5e785a027de82443fe10b6c
|
[] |
no_license
|
Rodagui/CodeForces-Solutions
|
ec90ad3806ca6025c9f588eb298b33a47f097bd4
|
fbcce297deb645ea8f6d7a30297071a12e447489
|
refs/heads/master
| 2022-07-27T21:36:20.656936
| 2022-07-15T00:54:17
| 2022-07-15T00:54:17
| 178,289,421
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 427
|
cpp
|
examenes.cpp
|
/*Problema E – Exámenes*/
#include <bits/stdc++.h>
#define EPS 1e-12
using namespace std;
int main(){
double T1, T2, r1, r2, ans1, ans2;
cin >> T1 >> T2 >> r1 >> r2;
ans1 = (100.0f * r1 / T1) + (100.0f * r2 / T2);
ans1 /= 2.0f;
ans2 = 100.0f * (r1 + r2) / (T1 + T2);
if(fabs(ans1 - ans2) < EPS)
cout << "C";
else if(ans1 > ans2)
cout << "A";
else
cout << "B";
return 0;
}
|
a91b8d8e052c643e15cd1261ad1585e59716ea97
|
aec35d48351acac8513a1c793e74d56a7d72cdf4
|
/CAsteroidGame.cpp
|
800bec38ae6f102f3ce5f96cb389167119dbd1b2
|
[] |
no_license
|
JoshPenner/Asteroids
|
d1458fec5d937084bf902ce6abe885a58cf7221b
|
faa88854badfe35d491f4c66e21b7b2599fe0ee4
|
refs/heads/master
| 2023-05-07T22:57:48.294513
| 2021-05-31T17:59:46
| 2021-05-31T17:59:46
| 372,589,888
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,737
|
cpp
|
CAsteroidGame.cpp
|
#include "stdafx.h"
#include "CAsteroidGame.h"
CAsteroidGame::CAsteroidGame()
{
}
CAsteroidGame::CAsteroidGame(int com_port)
{
uCtlr.init_com(com_port);
// add check for com function
// initialize canvas image to desired width and height
_Canvas = cv::Mat::zeros(cv::Size(1000, 800), CV_8UC3); // image type is CV_8UC3 : means 8 bit unsigned pixels with 3 channels(color)
}
CAsteroidGame::~CAsteroidGame()
{
}
void CAsteroidGame::update() // update internal variables of CSketch
{
// use get_analog to get x position value as %
uCtlr.get_analog(JOYSTICK_X, JOYSTICK_X_MAX, jstick_pct);
// calculate x position based on joystick input
// x = width of canvas * [ (sensitivity * input) - (1/2 scaled width offset) + (1/2 width offset) ]
joystick_pos.x = _Canvas.cols * ( (jstick_sens * jstick_pct / 100) - (jstick_sens / 2) + 0.5 );
//std::cout << "X position: " << joystick_pos.x << "\t";
// limit x-coordinate to edges
if (joystick_pos.x > _Canvas.cols) {
joystick_pos.x = _Canvas.cols;
}
if (joystick_pos.x <= 0) {
joystick_pos.x = 0;
}
// use get_analog to get y position value as %
uCtlr.get_analog(JOYSTICK_Y, JOYSTICK_Y_MAX, jstick_pct);
// calculate y position based on joystick input
joystick_pos.y = _Canvas.rows *(1 - ((jstick_sens * jstick_pct / 100) - (jstick_sens / 2) + 0.5 ));
//std::cout << "Y position: " << joystick_pos.y << "\n";
// limit y-coordinate to edges
if (joystick_pos.y > _Canvas.rows) {
joystick_pos.y = _Canvas.rows;
}
if (joystick_pos.y <= 0) {
joystick_pos.y = 0;
}
// Update ship position
myShip.set_pos(joystick_pos);
// Update asteroid positions:
if (_asteroid_list.size() != 0)
{
for (int i = 0; i < _asteroid_list.size(); i++)
{
_asteroid_list[i].move();
// check for asteroid - ship collisions
if (_asteroid_list[i].collide(myShip))
{
_asteroid_list[i].set_lives(0);
myShip.set_lives(myShip.get_lives() - 1);
}
// check for asteroid - missile collisions
for (int j = 0; j < _missile_list.size(); j++)
{
if (_asteroid_list[i].collide(_missile_list[j]))
{
_asteroid_list[i].set_lives(0);
_missile_list[j].set_lives(0);
// add 10 to score
score = score + 10;
}
}
// check for asteroid - wall collisions
if (_asteroid_list[i].collide_wall(_Canvas.size()))
_asteroid_list[i].set_lives(0);
}
}
// Update missile positions:
if (_missile_list.size() != 0)
{
for (int i = 0; i < _missile_list.size(); i++)
{
_missile_list[i].move();
// check for missile - wall collisions
if (_missile_list[i].collide_wall(_Canvas.size()))
_missile_list[i].set_lives(0);
}
}
// Check remaining lives on asteroids:
if (_asteroid_list.size() != 0)
{
for (int i = 0; i < _asteroid_list.size(); i++)
{
if (_asteroid_list[i].get_lives() <= 0)
{
_asteroid_list.erase(_asteroid_list.begin() + i);
}
}
}
// Check remaining lives on missiles:
if (_missile_list.size() != 0)
{
for (int i = 0; i < _missile_list.size(); i++)
{
if (_missile_list[i].get_lives() <= 0)
_missile_list.erase(_missile_list.begin() + i);
}
}
// read a debounced pushbutton and create a missile if pressed
if (uCtlr.pushbutton_db(PB1))
{
// create missile
CMissile missile(_Canvas.size());
missile.set_pos(myShip.get_pos());
_missile_list.push_back(missile);
// print the event to the screen with cout
std::cout << "PB1 PRESSED: FIRE MISSILE\n";
}
// read a debounced pushbutton and set a _reset flag to true if pressed
if (uCtlr.pushbutton_db(PB2))
{
//set _reset flag
_reset = true;
// print the event to the screen with cout
std::cout << "PB2 PRESSED: SET RESET FLAG\n";
}
}
void CAsteroidGame::draw() // performs all the drawing on the Mat image and displays image on the screen
{
// start timer
auto calc_start = std::chrono::steady_clock::now();
// check if _reset flag is set and if so, clear image and _reset flag
if ((_reset) || (myShip.get_lives() <= 0))
{
_reset = false; // clear flag
// reset score
score = 0;
// reset lives
myShip.set_lives(10);
// reset asteroids
_asteroid_list.clear();
// reset missiles
_missile_list.clear();
}
// clear previous image
_Canvas = cv::Mat::zeros(_Canvas.size(), CV_8UC3);
// draw ship
/*
cv::circle(_Canvas,
myShip.get_pos(), // location
10, // radius
cv::Scalar(255, 255, 255), // color
CV_FILLED); // filled
*/
myShip.draw(_Canvas);
// draw asteroids
if (_asteroid_list.size() != 0)
{
for (int i = 0; i < _asteroid_list.size(); i++)
{
_asteroid_list[i].draw(_Canvas);
}
}
// draw missiles
if (_missile_list.size() != 0)
{
for (int i = 0; i < _missile_list.size(); i++)
{
_missile_list[i].draw(_Canvas);
}
}
// draw player score
cv::putText(_Canvas,
"Score: ",
cv::Point(50, 50),
CV_FONT_HERSHEY_PLAIN,
2,
cv::Scalar(255, 255, 255));
cv::putText(_Canvas,
std::to_string(score),
cv::Point(200, 50),
CV_FONT_HERSHEY_PLAIN,
2,
cv::Scalar(255, 255, 255));
// draw number of lives
cv::putText(_Canvas,
"Lives: ",
cv::Point(400, 50),
CV_FONT_HERSHEY_PLAIN,
2,
cv::Scalar(255, 255, 255));
cv::putText(_Canvas,
std::to_string(myShip.get_lives()),
cv::Point(550, 50),
CV_FONT_HERSHEY_PLAIN,
2,
cv::Scalar(255, 255, 255));
// draw fps
cv::putText(_Canvas,
std::to_string(fps),
cv::Point(800, 50),
CV_FONT_HERSHEY_PLAIN,
2,
cv::Scalar(255, 255, 255));
// display canvas image
cv::imshow("Canvas", _Canvas);
// set update rate: 45ms per loop for 22fps
// Sleep if time remaining
std::this_thread::sleep_until(calc_start + std::chrono::milliseconds(45));
// calculate fps
auto calc_end = std::chrono::steady_clock::now();
auto calc_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(calc_end - calc_start);
//elapsed = calc_elapsed.count();
fps = 1000 / calc_elapsed.count();
}
void CAsteroidGame::run()
{
/*
// initialize ship object
CShip myShip(10);
*/
auto start_time = std::chrono::steady_clock::now();
// call update and draw in a loop while waiting for user to press 'q' to quit
do
{
update();
draw();
//create asteroid every few seconds
auto end_time = std::chrono::steady_clock::now();
auto calc_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
if (calc_elapsed.count() > asteroid_delay) {
CAsteroid astro(_Canvas.size());
_asteroid_list.push_back(astro);
//std::cout << "\nCreate asteroid " << _asteroid_list.size();
//reset timer
start_time = std::chrono::steady_clock::now();
//std::cout << "\n Asteroid 1 pos: " << _asteroid_list[0].get_pos();
}
} while (cv::waitKey(1) != 'q');
}
|
c7747df8bd991404bad3788cdb628ccd39e28ae5
|
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
|
/app/src/main/cpp/dir7941/dir22441/dir22442/dir22443/dir22444/dir22808/file22861.cpp
|
71d3f0ba78b3580ab7d4b9e88bf6ae704277f09d
|
[] |
no_license
|
tgeng/HugeProject
|
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
|
4488d3b765e8827636ce5e878baacdf388710ef2
|
refs/heads/master
| 2022-08-21T16:58:54.161627
| 2020-05-28T01:54:03
| 2020-05-28T01:54:03
| 267,468,475
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 115
|
cpp
|
file22861.cpp
|
#ifndef file22861
#error "macro file22861 must be defined"
#endif
static const char* file22861String = "file22861";
|
a8a8ce7154c709a92ef8b83a12bd1a60af531fb5
|
6db847c4c3fb3ef0b5712f102e8686955a57beb7
|
/cpp_tests/Test.hpp
|
ac37575cecfe00bbd13f370815bb6bf8ac5de2a1
|
[] |
no_license
|
manuelTorrealba/ndeAero
|
b3e73e4812e141b83cb3059f262f29f85d5bf405
|
254fc1b9f6028a14d24e2507c8458f3842b192fd
|
refs/heads/master
| 2021-01-20T15:41:47.715590
| 2015-06-16T14:33:37
| 2015-06-16T14:33:37
| 22,061,833
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 349
|
hpp
|
Test.hpp
|
/**
* File: Test.hpp
* Author: kenobi
*
* Created on Jun 8, 2015, 11:00 PM
*/
#ifndef INCLUDE_TEST_HPP
#define INCLUDE_TEST_HPP
#include "Vector.hpp"
namespace nde {
bool testThinAirfoilTheory();
bool testODESolver();
bool testNACAAirfoil(const Vector<unsigned int> &naca_codenum,
const std::string& out_file_name);
}
#endif
|
b2e6656e9bd9e0335529cd4df2322cb5f06bcffe
|
b8dd0d9a23083d166c5173cc315041b1b00ba710
|
/linkedlist2.cpp
|
b1b70348a905d0eece7b6b237f1603f3e3f1ac09
|
[] |
no_license
|
WonJoonPark/BOJ-Algorithm
|
244fb955ce422ae2ca47f3c33e53f32a6c9c691f
|
48353b3ed90829066e46bfae27ddc06c6918f0fd
|
refs/heads/main
| 2023-04-08T23:23:16.138284
| 2021-04-12T00:45:32
| 2021-04-12T00:45:32
| 307,600,337
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 309
|
cpp
|
linkedlist2.cpp
|
#include<iostream>
using namespace std;
class Double_LinkedList_Node {
public:
int number;
Double_LinkedList_Node * next;
Double_LinkedList_Node * prev;
Double_LinkedList_Node(int num) {
number = num;
next = NULL;
prev = NULL;
}
};
class Double_LinkedList {
public:
};
int main() {
return 0;
}
|
eaf5756d26dbbdb02fcb2a750bedd6d606b51433
|
16d1b9eb73c970d96a5bf316ea01bdbe8e6fccd1
|
/Classes/FirstBossScene.h
|
16350f50413b0ea747189f92d26c979c475e7d06
|
[] |
no_license
|
xurui25/cocos2d-x-
|
5cb2835f89018b92b281cc5f82a79283af0210d4
|
9a5ffb5597a0b5b9ec2b270122d07a96a899c9ae
|
refs/heads/master
| 2021-05-15T01:47:03.240010
| 2016-11-28T10:52:36
| 2016-11-28T10:52:36
| 39,554,445
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,529
|
h
|
FirstBossScene.h
|
#ifndef __FIRST_BOSS_SCENE_H__
#define __FIRST_BOSS_SCENE_H__
#include "cocos2d.h"
#include "SimpleAudioEngine.h"
#include "SkillButton.h"
#include "Man.h"
#include <iostream>
#include <string>
#include <vector>
USING_NS_CC;
using namespace std;
//
class FirstBossScene : public cocos2d::Layer, public CMTouchSpriteProtocol
{
public:
//私有变量
//分数
int score;
//当前坐标
int curx;
int cury;
//武器类型
int TypeWeapon;
//魔法
int Magic;
//人物
Sprite *man;
//炸弹
Sprite *bomb;
//炸弹的威力
int weapon_eff;
//boss
Sprite *boss;
//人物移动的速度
int speed_for_man;
//人物的大小
float manscale;
//炸弹增加的威力
int increase_for_weapon;
//炸弹增加的距离
int increase_for_dis;
//技能的类别
//人物类别
int mantype;
//人物特征
Man manfu;
//人物技能的种类
static int type_for_skill;
//武器精灵
MenuItemImage *btn1;
MenuItemImage *btn2;
Menu *menu;
//存储所有炸弹还剩的距离
vector<int> bombs_dis;
//人物的血量
int blood_for_man;
//boss的血量
int blood_for_boss;
int useKey;
//设置boss的移动方向
bool boss_move_up;
//设置boss技能的鱼的速率
float rate;
//存储所有的鱼(可碰和不可碰)
cocos2d::Vector<cocos2d::Sprite *> enemyList;
cocos2d::Vector<cocos2d::Sprite*> bombs;
static cocos2d::Scene* createScene();
virtual bool init();
virtual void onEnter();
CREATE_FUNC(FirstBossScene);
//响应鼠标及其键盘
virtual bool onTouchBegan(Touch *touch, Event *unused_event);
virtual void keyPress(EventKeyboard::KeyCode keyCode, Event* event);
virtual void keyRelease(EventKeyboard::KeyCode keyCode, Event* event);
//重写代理方法
SkillButton* mSkillButton;
void CMTouchSpriteSelectSprite(SkillButton *sprite);
//人物移动
void playerGo(float t);
//label集合
void createLabel();
//武器的生成
void setBomb();
void setnull(Ref* ref);
//让鱼游动
void objectMove(float f);
//让武器移动
void bombsMove(float f);
//创建鱼和能量球
void enemyCreate(float f);
//创建BOSS
void bossCreate();
//boss移动
void bossMove(float f);
//boss的技能
//void BossKill_1();
//设置速率
void setRate(float f);
//获取速率
float getRate();
//停止所有的定时器
void stopAllSchedule();
//设置人物的技能
static void setTypeSkill(int i);
static int getTypeSkill();
float time_1;
bool OK_;
//游戏结束
void gameOver();
void win();
};
#endif // __FIRST_BOSS_SCENE_H__
|
9706241d1e884625478649d065ae8bad27ae17fb
|
8e3bed8a6cdd5f979840b205f9cedbe297769f13
|
/Source/GameServer/include/Crywolf.h
|
c954a8b58bdb5bef86fc66560efa6add33a57a3f
|
[
"MIT"
] |
permissive
|
vuonglequoc/ServerSimulator
|
93cd48edf1cd5bec77e9c823b930bf35f26c7111
|
12bd6f24fcf957c657864a81da3dfb0467b48c2b
|
refs/heads/master
| 2023-02-03T05:55:40.232793
| 2020-12-19T22:27:34
| 2020-12-19T22:27:34
| 35,360,781
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,033
|
h
|
Crywolf.h
|
// Crywolf.h: interface for the CCrywolf class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CRYWOLF_H__ADDDADAD_136F_4C82_9920_91B557B8C9B5__INCLUDED_)
#define AFX_CRYWOLF_H__ADDDADAD_136F_4C82_9920_91B557B8C9B5__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "MapClass.h"
#include "CrywolfObjInfo.h"
#include "CrywolfStateTimeInfo.h"
#define CRYWOLF_STATUE_CHECK(iClass) ( ( ((iClass)) == 204 )?TRUE:FALSE)
#define MAX_CRYWOLF_STATE_TIME 20
#define MAX_CRYWOLF_MONSTER_GROUP 20
#define MAX_CRYWOLF_STATE 7
#define CRYWOLF_STATE_NONE 0
#define CRYWOLF_STATE_NOTIFY_1 1
#define CRYWOLF_STATE_NOTIFY_2 2
#define CRYWOLF_STATE_READY 3
#define CRYWOLF_STATE_START 4
#define CRYWOLF_STATE_END 5
#define CRYWOLF_STATE_ENDCYCLE 6
struct PMSG_ANS_CRYWOLF_INFO
{
PBMSG_HEAD2 h; // C1:BD:00
BYTE btOccupationState; // 4
BYTE btCrywolfState; // 5
};
struct PMSG_ANS_CRYWOLF_LEFTTIME
{
PBMSG_HEAD2 h; // C1:BD:04
BYTE btHour; // 4
BYTE btMinute; // 5
};
struct PMSG_ANS_CRYWOLF_STATUE_ALTAR_INFO
{
PBMSG_HEAD2 h; // C1:BD:02
int iCrywolfStatueHP; // 4
BYTE btAltarState1; // 8
BYTE btAltarState2; // 9
BYTE btAltarState3; // A
BYTE btAltarState4; // B
BYTE btAltarState5; // C
};
class CCrywolf
{
public:
CCrywolf();
virtual ~CCrywolf();
BOOL LoadData(const char* lpszFileName);
void Init();
void Run();
void DelAllData();
void LoadCrywolfMapAttr(const char* lpszFileName, int iOccupationState);
void SetState(int iCrywolfState);
void SetNextState(int iCurrentState);
int CheckStateTimeSync();
void SetState_NONE();
void SetState_NOTIFY_1();
void SetState_NOTIFY_2();
void SetState_READY();
void SetState_START();
void SetState_END();
void SetState_ENDCYCLE();
void ProcState_NONE();
void ProcState_NOTIFY_1();
void ProcState_NOTIFY_2();
void ProcState_READY();
void ProcState_START();
void ProcState_END();
void ProcState_ENDCYCLE();
void CrywolfNpcAct(int iIndex);
void CrywolfMonsterAct(int iIndex);
void CrywolfSecondAct();
int GetCrywolfState(){return this->m_iCrywolfState;}
int GetOccupationState(){return this->m_iOccupationState;}
//int __thiscall GetCrywolfBossIndex();
void SetDBDataLoad(BOOL bIsLoaded){this->m_bDBDataLoadOK = bIsLoaded;}
void SetCrywolfState(int iCrywolfState){this->m_iCrywolfState = iCrywolfState;}
void SetCrywolfStateAppliedTime(int iCrywolfState){this->m_StateTimeInfo[iCrywolfState].SetAppliedTime();}
void SetOccupationState(int iOccupationState){this->m_iOccupationState = iOccupationState;}
void SetCrywolfBossIndex(int iBossIndex){this->m_iBossIndex = iBossIndex;}
void NotifyCrywolfCurrentState();
void NotifyCrywolfStatueAndAltarInfo();
void NotifyCrywolfBossMonsterInfo();
void NotifyCrywolfStateLeftTime();
void NotifyCrywolfStageEffectOnOff(BYTE btOnOff);
void NotifyCrywolfPersonalRank();
void NotifyCrywolfHeroList();
void ChangeAI(int iAIOrder);
void TurnUpBoss();
void SetCrywolfCommonNPC(int iOccupationState);
void SetCrywolfMapAttr(int iOccupationState);
void SetCrywolfAllCommonMonsterState(int iMonsterState, int iMode);
void RemoveCrywolfCommonMonster();
void CreateCrywolfCommonMonster();
void CrywolfMonsterDieProc(int iMonIndex, int iKillerIndex);
void MakeRewardForAltarElf(int iAltarUserIndex);
void MakeRewardForHeroListTop5(int iUserIndex);
void OperateGmCommand(int iUserIndex, int iCommand);
void CrywolfServerGroupSync();
void CrywolfInfoDBSave();
void CrywolfInfoDBLoad();
void ApplyCrywolfDBInfo(int iCrywolfState, int iOccupationState);
int CalcGettingScore(int iUserIndex, int iMonIndex, int iScoreType);
int CalcGettingRank(int iUserIndex);
int CalcGettingRewardExp(int iUserIndex, int iMVPRank);
void GiveRewardExp(int iUserIndex, int iRewardExp);
void ResetAllUserMVPScore();
private:
BOOL m_bFileDataLoad; // 4
BOOL m_bDBDataLoadOK; // 8
BOOL m_bDBDataLoading; // C
int m_iScheduleMode; // 10
MapClass m_CrywolfMapAttr[3]; // 14
int m_iCrywolfState; // F314C
int m_iOccupationState; // F3150
public:
CCrywolfObjInfo m_ObjCommonNPC; // F3154
CCrywolfObjInfo m_ObjSpecialNPC; // F3608
CCrywolfObjInfo m_ObjCommonMonster; // F3ABC
CCrywolfObjInfo m_ObjSpecialMonster; // F3F70
private:
CCrywolfStateTimeInfo m_StartTimeInfo[MAX_CRYWOLF_STATE_TIME]; // F4424
int m_StartTimeInfoCount; // F4794
CCrywolfStateTimeInfo m_StateTimeInfo[MAX_CRYWOLF_STATE]; //F4798
DWORD m_dwCrywolfNotifyMsgStartTick; // F48CC
DWORD m_dwCrywolfStartProcTick; // F48D0
BOOL m_bTurnUpBoss; // F48D4
BOOL m_bChangeAI; // F48D8
int m_iMonsterGroupNumberArray[MAX_CRYWOLF_MONSTER_GROUP]; // F48DC
int m_iMonsterGroupNumberCount; // F492C
int m_iMonsterGroupChangeAITime; // F4930
int m_iBossIndex; // F4934
int m_iBossGroupNumber; // F4938
int m_iBossTurnUpTime; // F493C
int m_iMVPScoreTable[7]; // F4940
int m_iMVPRankScoreTable[5]; // F495C
int m_iMVPRankExpTable[5]; // F4970
};
extern CCrywolf g_Crywolf;
#endif // !defined(AFX_CRYWOLF_H__ADDDADAD_136F_4C82_9920_91B557B8C9B5__INCLUDED_)
|
80d3eeccdd6501b1cc0c8bc7a227827f5f1c7cc5
|
1165a7e419ef77b9c21ff419b5ef11b03ea03467
|
/src/Renderer/Material.h
|
e93a4ea208362efabb382f955db0c58263a5972b
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
Stral9315/xsngine
|
19c171cb729c0126c8c7f845c17b2db8f261a34b
|
4a4afe21f12483dbe266113b17a4b51ea850ee56
|
refs/heads/master
| 2020-03-07T18:11:46.674231
| 2018-04-01T13:20:42
| 2018-04-01T13:20:42
| 127,630,592
| 0
| 0
|
MIT
| 2018-04-01T13:12:40
| 2018-04-01T13:12:39
| null |
UTF-8
|
C++
| false
| false
| 794
|
h
|
Material.h
|
#pragma once
#include <string>
#include <vector>
#include "Renderer/Buffer.h"
#include "Renderer/Texture.h"
namespace Renderer {
class ShaderProgram;
const uint32_t MF_NONE = 0x00000000u;
const uint32_t MF_WIREFRAME = 0x00000001u;
struct Material {
struct SamplerBinding {
int unit;
std::string uniform;
const Texture *texture;
};
struct BufferBinding {
int index;
Backend::Buffer *buffer;
~BufferBinding() {
delete buffer;
buffer = nullptr;
}
};
ShaderProgram *shaderProgram = nullptr;
std::vector<SamplerBinding> samplerBindings;
std::vector<BufferBinding> bufferBindings;
uint32_t flags = 0u;
// use this material for subsequent rendering
void Bind(
void
) const;
};
} // namespace Renderer
|
c2d1fd5a092a83644f8ccf59924669142b512dbb
|
c371f8325cb85a77c1772d9ff48ca31d4602de68
|
/labhelper/Model.h
|
cdb579c911ca9873313d5797653f1c51a3272ef5
|
[] |
no_license
|
ivanzamoraarias/lab_computer_graphics_1
|
0231ecc67ff54c7a63255b47865fab40bd1f5e2e
|
6b08244f83156564a90ffd5a0408c87e2ed1308d
|
refs/heads/master
| 2020-09-05T05:31:47.370238
| 2020-03-30T16:58:57
| 2020-03-30T16:58:57
| 219,997,909
| 1
| 0
| null | 2020-03-30T16:58:58
| 2019-11-06T13:01:30
|
C
|
UTF-8
|
C++
| false
| false
| 2,187
|
h
|
Model.h
|
#pragma once
#include <string>
#include <vector>
#include <glm/glm.hpp>
namespace labhelper
{
struct Texture
{
bool valid = false;
uint32_t gl_id = 0;
std::string filename;
std::string directory;
int width, height;
uint8_t* data = nullptr;
bool load(const std::string& directory, const std::string& filename, int nof_components);
};
//////////////////////////////////////////////////////////////////////////////
// This material class implements a subset of the suggested PBR extension
// to the OBJ/MTL format, explained at:
// http://exocortex.com/blog/extending_wavefront_mtl_to_support_pbr
// NOTE: A material can have _either_ a (textured) roughness, or a good old
// shininess value. We still use shininess for the Blinn mfd in the
// GL labs, but roughness for pathtracing.
//////////////////////////////////////////////////////////////////////////////
struct Material
{
std::string m_name;
glm::vec3 m_color;
float m_reflectivity;
float m_shininess;
float m_metalness;
float m_fresnel;
float m_emission;
float m_transparency;
Texture m_color_texture;
Texture m_reflectivity_texture;
Texture m_shininess_texture;
Texture m_metalness_texture;
Texture m_fresnel_texture;
Texture m_emission_texture;
};
struct Mesh
{
std::string m_name;
uint32_t m_material_idx;
// Where this Mesh's vertices start
uint32_t m_start_index;
uint32_t m_number_of_vertices;
};
class Model
{
public:
~Model();
// The name of the whole model
std::string m_name;
// The filename of this model
std::string m_filename;
// The materials
std::vector<Material> m_materials;
// A model will contain one or more "Meshes"
std::vector<Mesh> m_meshes;
// Buffers on CPU
std::vector<glm::vec3> m_positions;
std::vector<glm::vec3> m_normals;
std::vector<glm::vec2> m_texture_coordinates;
// Buffers on GPU
uint32_t m_positions_bo;
uint32_t m_normals_bo;
uint32_t m_texture_coordinates_bo;
// Vertex Array Object
uint32_t m_vaob;
};
Model* loadModelFromOBJ(std::string filename);
void saveModelToOBJ(Model* model, std::string filename);
void freeModel(Model* model);
void render(const Model* model, const bool submitMaterials = true);
} // namespace labhelper
|
5bf899215234fc43542e05d2f6cd21ff7a057176
|
91cd380b9d0d51c31ee8debde9a5073f73c67268
|
/PAT/PAT/04.cpp
|
af43aa50e2d864259678739c494511c54764fd90
|
[] |
no_license
|
lrx0014/PATStudy
|
28d57f17fee4e2f1177bcb6ec861560b04052959
|
74e81e49645079f5b3436979ccb28ba944d80d8e
|
refs/heads/master
| 2021-05-16T16:08:49.938895
| 2018-04-02T12:58:09
| 2018-04-02T12:58:09
| 119,804,924
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,282
|
cpp
|
04.cpp
|
#include <iostream>
#include <vector>
#include <map>
using namespace std;
typedef struct node{
int id;
int childs_num;
vector<int> childs;
}Node;
void dfs(const Node *tree,Node node,map<int,int>& m,int depth)
{
if(m[depth==0]) m[depth] = 0;
if(node.childs_num == 0)
{
++m[depth];
return;
}
vector<int> childs = node.childs;
for(int i=0;i<childs.size();i++)
{
dfs(tree,tree[childs[i]],m,depth+1);
}
}
int main()
{
int N,M;
cin>>N>>M;
Node *tree = (Node*)malloc((N+1)*sizeof(Node));
for(int i=0;i<100;i++)
{
tree[i].id = 0;
tree[i].childs_num = 0;
}
int ID,K;
while(M--)
{
cin>>ID>>K;
tree[ID].id = ID;
tree[ID].childs_num = K;
int child;
while(K--)
{
cin>>child;
(*(tree+ID)).childs.push_back(child);
//tree[ID].childs.push_back(child);
}
}
map<int,int> result;
dfs(tree,tree[1],result,1);
bool first = 1;
for(map<int,int>::iterator itor=result.begin();itor!=result.end();itor++)
{
if(first)
{
cout<<itor->second;
first = 0;
}
else{
cout<<" "<<itor->second;
}
}
}
|
03823a7a9c0b87c1959d0e5ef9eaedb4fff8bbf7
|
3235a542c9593c45ec3d526b066ceedcc0205f67
|
/38.cpp
|
be3a2f8dd462d42fbde2e318fb7abb3620635a8d
|
[] |
no_license
|
TomFrank/LeetCode
|
2937c3ba8b54177b3f2979c9f40c2264d1d9b91d
|
024b5ff09be841cb830219f23b6e74f85159ff1f
|
refs/heads/master
| 2022-04-30T06:59:25.925446
| 2022-03-24T03:43:59
| 2022-03-24T03:43:59
| 106,986,742
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,170
|
cpp
|
38.cpp
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
pair<char,int> max_cont_ch(string& s, int i) {
int cnt = 1;
char c = s[i];
for(;i+1<s.size();) {
if(s[i+1] == s[i]) {
cnt++;
i++;
} else break;
}
return {c,cnt};
}
string countAndSay(int n) {
string s{"1"};
for(int i=1;i<n;++i) {
string ns;
for(int j=0;j<s.size();) {
auto [ch, m] = max_cont_ch(s, j);
//cout << "from=" << j << " ch=" << ch << " m=" << m << " ";
ns.append(to_string(m)+ch);
//cout << s << endl;
j += m;
}
s = ns;
//cout << "------------" << endl;
}
return s;
}
};
int stringToInteger(string input) {
return stoi(input);
}
int main() {
string line;
while (getline(cin, line)) {
int n = stringToInteger(line);
string ret = Solution().countAndSay(n);
string out = (ret);
cout << out << endl;
}
return 0;
}
|
4f88c927be938d3c36f8edbd86aeafe015d744f5
|
822150d9dd48c6d7140364a01b778a66c90ecd2c
|
/protocol/offset_response.cc
|
57d60c8c685a3c8e4c05f2b387e95f19ff725628
|
[] |
no_license
|
leo-987/kafkaconsumer
|
f66da43aa32a6b7fbfea5c6438ab29cf54270a73
|
3b88fd536e11dff9033159e4e9b40e5d1b7fe82a
|
refs/heads/master
| 2023-03-05T13:54:56.505116
| 2016-06-19T03:55:39
| 2016-06-19T03:55:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,072
|
cc
|
offset_response.cc
|
#include "offset_response.h"
#include "util.h"
#include "easylogging++.h"
PartitionOffsets::PartitionOffsets(char **buf)
{
partition_ = Util::NetBytesToInt(*buf);
(*buf) += 4;
error_code_ = Util::NetBytesToShort(*buf);
(*buf) += 2;
LOG_IF(error_code_ != 0, ERROR) << "OffsetResponse error code = " << error_code_;
int array_size = Util::NetBytesToInt(*buf);
(*buf) += 4;
for (int i = 0; i < array_size; i++)
{
long offset;
memcpy(&offset, *buf, 8);
// for Linux
offset = be64toh(offset);
// for Mac
//offset = ntohll(offset);
(*buf) += 8;
offset_array_.push_back(offset);
}
}
int PartitionOffsets::CountSize()
{
return 4 + 2 + 4 + offset_array_.size() * 8;
}
void PartitionOffsets::PrintAll()
{
LOG(DEBUG) << "partition = " << partition_;
LOG(DEBUG) << "error code = " << error_code_;
for (auto o_it = offset_array_.begin(); o_it != offset_array_.end(); ++o_it)
LOG(DEBUG) << "offset = " << *o_it;
}
TopicPartitionOR::TopicPartitionOR(char **buf)
{
short topic_len = Util::NetBytesToShort(*buf);
(*buf) += 2;
topic_ = std::string(*buf, topic_len);
(*buf) += topic_len;
int array_size = Util::NetBytesToInt(*buf);
(*buf) += 4;
for (int i = 0; i < array_size; i++)
{
std::shared_ptr<PartitionOffsets> partition_offset = std::make_shared<PartitionOffsets>(buf);
partition_offset_array_.push_back(partition_offset);
}
}
int TopicPartitionOR::CountSize()
{
int size = 2 + topic_.length();
size += 4;
for (auto po_it = partition_offset_array_.begin(); po_it != partition_offset_array_.end(); ++po_it)
{
size += (*po_it)->CountSize();
}
return size;
}
void TopicPartitionOR::PrintAll()
{
LOG(DEBUG) << "topic = " << topic_;
for (auto po_it = partition_offset_array_.begin(); po_it != partition_offset_array_.end(); ++po_it)
(*po_it)->PrintAll();
}
OffsetResponse::OffsetResponse(char **buf)
: Response(ApiKey::OffsetType, buf)
{
int array_size = Util::NetBytesToInt(*buf);
(*buf) += 4;
for (int i = 0; i < array_size; i++)
{
std::shared_ptr<TopicPartitionOR> tp = std::make_shared<TopicPartitionOR>(buf);
topic_partition_array_.push_back(tp);
}
if (Response::GetTotalSize() != CountSize())
{
LOG(ERROR) << "CountSize are not equal";
throw;
}
}
int OffsetResponse::CountSize()
{
int size = Response::CountSize();
size += 4;
for (auto tp_it = topic_partition_array_.begin(); tp_it != topic_partition_array_.end(); ++tp_it)
{
size += (*tp_it)->CountSize();
}
return size;
}
void OffsetResponse::PrintAll()
{
LOG(DEBUG) << "-----OffsetResponse-----";
Response::PrintAll();
for (auto tp_it = topic_partition_array_.begin(); tp_it != topic_partition_array_.end(); ++tp_it)
(*tp_it)->PrintAll();
LOG(DEBUG) << "------------------------";
}
// return value
// >0
// <0
long OffsetResponse::GetNewOffset()
{
// XXX: need improve
// When the broker just up, error code = NOT_LEADER_FOR_PARTITION (6)
if (topic_partition_array_[0]->partition_offset_array_[0]->error_code_ != 0)
return -1;
else
return topic_partition_array_[0]->partition_offset_array_[0]->offset_array_[0];
}
|
41d11b63658e56d85d7d59e6a5898dbbd86b2bd8
|
04a2a2378ee2d7d020edb79369dd4b9899baf9c2
|
/tictactoe/botmove.h
|
ac720d4301af90dfd1caa50bcf5322ae0d6e5972
|
[] |
no_license
|
Unplugged2/tic-tac-toe-cpp
|
dbc8a6ea9374fc899b694dd90ef86e1821c8f034
|
fcd0db1262f2792759cbd659575e4864bf29b8fe
|
refs/heads/main
| 2023-04-16T10:34:25.836882
| 2021-05-04T13:24:39
| 2021-05-04T13:24:39
| 364,258,619
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,801
|
h
|
botmove.h
|
#include<iostream>
using namespace std;
int bot_AI(){
int a;
bool chose = false;
if(board[1] == 'X' && board[2] == 'X' && board[3] != 'X' && board[3] != 'O'){ //1st row
a = 3;
chose = true;
}
else if(board[1] == 'O' && board[3] == 'O' && board[2] != 'X' && board[2] != 'O'){
a = 2;
chose = true;
}
else if(board[2] == 'O' && board[3] == 'O' && board[1] != 'X' && board[1] != 'O'){
a = 1;
chose = true;
}
else if(board[4] == 'O' && board[5] == 'O' && board[6] != 'X' && board[6] != 'O'){ //2nd row
a = 6;
chose = true;
}
else if(board[4] == 'O' && board[6] == 'O' && board[5] != 'X' && board[5] != 'O'){
a = 5;
chose = true;
}
else if(board[6] == 'O' && board[5] == 'O' && board[4] != 'X' && board[4] != 'O'){
a = 4;
chose = true;
}
else if(board[7] == 'O' && board[8] == 'O' && board[9] != 'X' && board[9] != 'O'){ //3rd row
a = 9;
chose = true;
}
else if(board[7] == 'O' && board[9] == 'O' && board[8] != 'X' && board[8] != 'O'){
a = 8;
chose = true;
}
else if(board[8] == 'O' && board[9] == 'O' && board[7] != 'X' && board[7] != 'O'){
a = 7;
chose = true;
}
else if(board[1] == 'O' && board[4] == 'O' && board[7] != 'X' && board[7] != 'O'){ //1st col
a = 7;
chose = true;
}
else if(board[1] == 'O' && board[7] == 'O' && board[4] != 'X' && board[4] != 'O'){
a = 4;
chose = true;
}
else if(board[7] == 'O' && board[4] == 'O' && board[1] != 'X' && board[1] != 'O'){
a = 1;
chose = true;
}
else if(board[2] == 'O' && board[5] == 'O' && board[8] != 'X' && board[8] != 'O'){ //2nd col
a = 8;
chose = true;
}
else if(board[2] == 'O' && board[8] == 'O' && board[5] != 'X' && board[5] != 'O'){
a = 5;
chose = true;
}
else if(board[8] == 'O' && board[5] == 'O' && board[2] != 'X' && board[2] != 'O'){
a = 2;
chose = true;
}
else if(board[3] == 'O' && board[6] == 'O' && board[9] != 'X' && board[9] != 'O'){ //3rd col
a = 9;
chose = true;
}
else if(board[3] == 'O' && board[9] == 'O' && board[6] != 'X' && board[6] != 'O'){
a = 6;
chose = true;
}
else if(board[9] == 'O' && board[6] == 'O' && board[3] != 'X' && board[3] != 'O'){
a = 3;
chose = true;
}
else if(board[1] == 'O' && board[5] == 'O' && board[9] != 'X' && board[9] != 'O'){ //1st diagonal
a = 9;
chose = true;
}
else if(board[1] == 'O' && board[9] == 'O' && board[5] != 'X' && board[5] != 'O'){
a = 5;
chose = true;
}
else if(board[9] == 'O' && board[5] == 'O' && board[1] != 'X' && board[1] != 'O'){
a = 1;
chose = true;
}
else if(board[3] == 'O' && board[5] == 'O' && board[7] != 'X' && board[7] != 'O'){ //2nd diagonal
a = 7;
chose = true;
}
else if(board[3] == 'O' && board[7] == 'O' && board[5] != 'X' && board[5] != 'O'){
a = 5;
chose = true;
}
else if(board[7] == 'O' && board[5] == 'O' && board[3] != 'X' && board[3] != 'O'){
a = 3;
chose = true;
}
else if(board[1] == 'X' && board[2] == 'X' && board[3] != 'X' && board[3] != 'O'){ //1st row
a = 3;
chose = true;
}
else if(board[1] == 'X' && board[3] == 'X' && board[2] != 'X' && board[2] != 'O'){
a = 2;
chose = true;
}
else if(board[2] == 'X' && board[3] == 'X' && board[1] != 'X' && board[1] != 'O'){
a = 1;
chose = true;
}
else if(board[4] == 'X' && board[5] == 'X' && board[6] != 'X' && board[6] != 'O'){ //2nd row
a = 6;
chose = true;
}
else if(board[4] == 'X' && board[6] == 'X' && board[5] != 'X' && board[5] != 'O'){
a = 5;
chose = true;
}
else if(board[6] == 'X' && board[5] == 'X' && board[4] != 'X' && board[4] != 'O'){
a = 4;
chose = true;
}
else if(board[7] == 'X' && board[8] == 'X' && board[9] != 'X' && board[9] != 'O'){ //3rd row
a = 9;
chose = true;
}
else if(board[7] == 'X' && board[9] == 'X' && board[8] != 'X' && board[8] != 'O'){
a = 8;
chose = true;
}
else if(board[8] == 'X' && board[9] == 'X' && board[7] != 'X' && board[7] != 'O'){
a = 7;
chose = true;
}
else if(board[1] == 'X' && board[4] == 'X' && board[7] != 'X' && board[7] != 'O'){ //1st col
a = 7;
chose = true;
}
else if(board[1] == 'X' && board[7] == 'X' && board[4] != 'X' && board[4] != 'O'){
a = 4;
chose = true;
}
else if(board[7] == 'X' && board[4] == 'X' && board[1] != 'X' && board[1] != 'O'){
a = 1;
chose = true;
}
else if(board[2] == 'X' && board[5] == 'X' && board[8] != 'X' && board[8] != 'O'){ //2nd col
a = 8;
chose = true;
}
else if(board[2] == 'X' && board[8] == 'X' && board[5] != 'X' && board[5] != 'O'){
a = 5;
chose = true;
}
else if(board[8] == 'X' && board[5] == 'X' && board[2] != 'X' && board[2] != 'O'){
a = 2;
chose = true;
}
else if(board[3] == 'X' && board[6] == 'X' && board[9] != 'X' && board[9] != 'O'){ //3rd col
a = 9;
chose = true;
}
else if(board[3] == 'X' && board[9] == 'X' && board[6] != 'X' && board[6] != 'O'){
a = 6;
chose = true;
}
else if(board[9] == 'X' && board[6] == 'X' && board[3] != 'X' && board[3] != 'O'){
a = 3;
chose = true;
}
else if(board[1] == 'X' && board[5] == 'X' && board[9] != 'X' && board[9] != 'O'){ //1st diagonal
a = 9;
chose = true;
}
else if(board[1] == 'X' && board[9] == 'X' && board[5] != 'X' && board[5] != 'O'){
a = 5;
chose = true;
}
else if(board[9] == 'X' && board[5] == 'X' && board[1] != 'X' && board[1] != 'O'){
a = 1;
chose = true;
}
else if(board[3] == 'X' && board[5] == 'X' && board[7] != 'X' && board[7] != 'O'){ //2nd diagonal
a = 7;
chose = true;
}
else if(board[3] == 'X' && board[7] == 'X' && board[5] != 'X' && board[5] != 'O'){
a = 5;
chose = true;
}
else if(board[7] == 'X' && board[5] == 'X' && board[3] != 'X' && board[3] != 'O'){
a = 3;
chose = true;
}
if (chose == true){
return a;
}
else if (chose == false){
return rand() % 9 + 1;
}
}
|
03d79765667f473758e92297513288205fa069b5
|
5d8cec1e270f3d21971c253818e35ea3ec144434
|
/Element.cpp
|
f8443afc54a95945857d8b784d9e1220a01f3760
|
[] |
no_license
|
agouasmi/DG2D
|
1692ed9f053dcba01d24fbc13f6f8eeba865b8c2
|
24c08cf0f4ed80316c08e128421a27ef30bcc254
|
refs/heads/master
| 2021-01-20T04:04:56.962800
| 2017-04-27T19:54:10
| 2017-04-27T19:54:10
| 89,634,678
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,497
|
cpp
|
Element.cpp
|
#include "Element.h"
/* Base class */
Element::Element(){}
Element::~Element(){
//delete [] smax;
// ---------------- //
delete [] dofs_rhs;
delete [] dofs;
delete [] dofs_backup;
// ---------------- //
delete [] quad_F1;
delete [] quad_F2;
// ---------------- //
delete [] flux_faces;
// --------------- //
FE_BASIS = NULL;
FE_DATA = NULL;
MODEL = NULL;
}
void Element::setup(int m, int p, double* points, FE_2D_Basis* fe_basis,
FE_Store *fe_data, Equation* model){
// Parameters
M = m;
ORDER = p;
DOFS_NUMBER = fe_data->FE_DIM;
FE_BASIS = fe_basis;
MODEL = model;
FE_DATA = fe_data;
N = MatrixXd(NF,2);
X = VectorXd(NF,1);
Y = VectorXd(NF,1);
L = VectorXd(NF,1);
// Geometry info
for (int i = 0; i < NF; i++){
X(i) = points[2*i];
Y(i) = points[2*i+1];
}
for (int i = 0; i < NF-1; i++){
N(i,0) = Y(i+1) - Y(i);
N(i,1) = - (X(i+1) - X(i));
}
N(NF-1,0) = Y(0) - Y(NF-1);
N(NF-1,1) = - (X(0) - X(NF-1));
//smax = new double[NF];
double P = 0.;
for (int i = 0; i < NF; i++){
L(i) = N.row(i).norm();
N.row(i) /= L(i);
P += L(i);
}
size = 1.0;
compute_imass();
// Allocating memory
dofs_rhs = new double[M*DOFS_NUMBER];
dofs = new double[M*DOFS_NUMBER];
dofs_backup = new double[M*DOFS_NUMBER];
quad_F1 = new double[M*FE_DATA->Q2_N_PTS];
quad_F2 = new double[M*FE_DATA->Q2_N_PTS];
flux_faces = new double[NF*M*(ORDER+1)];
}
void Element::xy_at_node(double *x, double *y, unsigned int node){
double xi, eta;
xi = FE_DATA->XIETA[2*node];
eta = FE_DATA->XIETA[2*node + 1];
XI_to_X(x, y, xi, eta);
}
void Element::eval_at_quad(double * U, unsigned int n){
/* Evaluates the state in the reference element */
double phi;
for (int m = 0; m < M; m++){
U[m] = 0.;
}
for (int dof = 0; dof < DOFS_NUMBER; dof++){
phi = FE_DATA->PHI[dof*(FE_DATA->Q2_N_PTS) + n];
for (int m = 0; m < M; m++){
U[m] += dofs[dof*M + m]*phi;
}
}
}
void Element::compute_quad_fluxes(){
/* Computes the weighted flux values at 2D quadrature points */
double quad_dof[M], xi, eta, w;
int n, m;
for (n = 0; n < FE_DATA->Q2_N_PTS; n++){
w = FE_DATA->Q2_WEIGHTS[n];
// Eval the state at the quad point
eval_at_quad(quad_dof, n);
MODEL->flux_N(&quad_F1[n*M], quad_dof, 1., 0.);
MODEL->flux_N(&quad_F2[n*M], quad_dof, 0., 1.);
// Multiply by the weight
for (m = 0; m < M; m++){
quad_F1[n*M + m] *= w;
quad_F2[n*M + m] *= w;
}
}
}
void Element::volume_integral(double* RHS){
int node, n;
double xi, eta, dphi_dxi, dphi_deta, detJ;
RowVector2d NABLA_PHI;
MatrixXd F(2,M);
Matrix2d J_, J1;
Map < RowVectorXd > F1(NULL,M);
Map < RowVectorXd > F2(NULL,M);
Map < RowVectorXd > R_node(NULL,M);
for (node = 0; node < DOFS_NUMBER; node++){
new (&R_node) Map < RowVectorXd >(&RHS[node*M],M);
R_node *= 0.;
for (n = 0; n < FE_DATA->Q2_N_PTS; n++){
new (&F1) Map < RowVectorXd > (&quad_F1[n*M],M);
new (&F2) Map < RowVectorXd > (&quad_F2[n*M],M);
F.row(0) = F1;
F.row(1) = F2;
xi = FE_DATA->Q2_POINTS[2*n];
eta = FE_DATA->Q2_POINTS[2*n+1];
Jacobian(J_, xi, eta);
detJ = J_.determinant();
J1 = J_.inverse();
dphi_dxi = FE_DATA->DPHI_DXI [node*FE_DATA->Q2_N_PTS + n];
dphi_deta = FE_DATA->DPHI_DETA[node*FE_DATA->Q2_N_PTS + n];
NABLA_PHI << dphi_dxi , dphi_deta;
R_node += detJ*NABLA_PHI*J1*F;
}
}
}
void Element::surface_integral(double* RHS){
Map < RowVectorXd > F_edge(NULL,M);
Map < RowVectorXd > R_node(NULL,M);
int face, k, node, n;
double w;
for (face = 0; face < NF; face++){
for (k = 0; k < ORDER + 1; k++){
node = FE_DATA->face_index[(ORDER+1)*face + k];
new (&R_node) Map < RowVectorXd > (&RHS[node*M],M);
new (&F_edge) Map < RowVectorXd > (&flux_faces[((ORDER+1)*face + k)*M],M);
for (n = 0; n < FE_DATA->Q1_N_PTS; n++){
w = FE_DATA->Q1_WEIGHTS[n];
R_node -= 0.5 * L[face] * w * F_edge *
FE_DATA->EDGE_PHI[k*(FE_DATA->Q1_N_PTS) + n];
}
}
}
}
void Element::assemble_rhs(double * RHS){
// Volume term
volume_integral(RHS);
// Interface term
surface_integral(RHS);
}
void Element::compute_CFL(double dt){
/*double S_MAX, P = J/size;
for (int face = 0; face < NF; face++){
S_MAX += smax[face]*L[face]/P;
}
CFL = dt * S_MAX / size;*/
}
void Element::step(double dt){
/* Euler explicit */
compute_quad_fluxes();
assemble_rhs(dofs_rhs);
Map< Matrix<double, Dynamic, Dynamic, RowMajor> > RHS(dofs_rhs, DOFS_NUMBER, M);
Map< Matrix<double, Dynamic, Dynamic, RowMajor> > U(dofs, DOFS_NUMBER, M);
Map< Matrix<double, Dynamic, Dynamic, RowMajor> > U_OLD(dofs_backup, DOFS_NUMBER, M);
compute_CFL(dt);
U = U_OLD + dt*IMASS*RHS;
}
void Element::step(double dt, double alpha1, double alpha2, double beta){
/* SSP Euler explicit */
compute_quad_fluxes();
assemble_rhs(dofs_rhs);
Map< Matrix<double, Dynamic, Dynamic, RowMajor> > RHS(dofs_rhs, DOFS_NUMBER, M);
Map< Matrix<double, Dynamic, Dynamic, RowMajor> > U(dofs, DOFS_NUMBER, M);
Map< Matrix<double, Dynamic, Dynamic, RowMajor> > U_OLD(dofs_backup, DOFS_NUMBER, M);
U = alpha1*U_OLD + alpha2*U + dt*IMASS*RHS*beta;
}
void copy_vec(double *out, double* in, int N){
memcpy(out, in, N * sizeof (double));
}
void Element::save_dofs(){
copy_vec(dofs_backup, dofs, M*DOFS_NUMBER);
}
void Element::print(){
/* Prints Lagrangian-like information on the element */
double x, y;
cout << " Vertices positions: " << X << endl << endl;
cout << " Positions of the nodes:" << endl;
for (int node = 0; node < DOFS_NUMBER; node++){
xy_at_node(&x, &y, node);
cout << " Node " << node << ": ";
cout << x << " " << y << endl;
}
cout << endl << " ----------------- " << endl;
}
/* Triangle */
void Tri_Element::compute_imass(){
Matrix2d J;
Jacobian(J, 0., 0.);
IMASS = FE_DATA->MASS_INV / J.determinant();
}
void Tri_Element::Jacobian(Matrix2d &J, double xi, double eta){
J << X(1) - X(0), X(2) - X(0),
Y(1) - Y(0), Y(2) - Y(0);
}
void Tri_Element::XI_to_X(double *x, double *y, double xi, double eta){
*x = X(0) + (X(1) - X(0))*xi + (X(2) - X(0))*eta;
*y = Y(0) + (Y(1) - Y(0))*xi + (Y(2) - Y(0))*eta;
}
/* Quadrilateral */
void Quad_Element::compute_imass(){
Matrix2d J_;
MatrixXd MASS(DOFS_NUMBER, DOFS_NUMBER);
int i, j, n;
double xi, eta, detJ;
Gauss quad1(ORDER+1);
Tensor Quad(&quad1);
for (i = 0; i < DOFS_NUMBER; i++){
for (j = 0; j < DOFS_NUMBER; j++){
MASS(i,j) = 0.;
for (n = 0; n < Quad.N_PTS; n++){
xi = Quad.POINTS[2*n];
eta = Quad.POINTS[2*n+1];
Jacobian(J_, xi, eta);
detJ = J_.determinant();
MASS(i,j) += detJ*Quad.WEIGHTS[n]*
FE_BASIS->PHI(i,xi,eta)*
FE_BASIS->PHI(j,xi,eta);
}
}
}
IMASS = MASS.inverse();
}
void Quad_Element::Jacobian(Matrix2d &J, double xi, double eta){
J(0,0) = 0.25*((X(1) - X(0))*(1 - eta) + (X(2) - X(3))*(1 + eta));
J(1,0) = 0.25*((Y(1) - Y(0))*(1 - eta) + (Y(2) - Y(3))*(1 + eta));
J(0,1) = 0.25*((X(3) - X(0))*(1 - xi) + (X(2) - X(1))*(1 + xi));
J(1,1) = 0.25*((Y(3) - Y(0))*(1 - xi) + (Y(2) - Y(1))*(1 + xi));
}
void Quad_Element::XI_to_X(double *x, double *y, double xi, double eta){
*x = 0.25*(X(0)*(1-xi)*(1-eta) + X(1)*(1+xi)*(1-eta)
+ X(2)*(1+xi)*(1+eta) + X(3)*(1-xi)*(1+eta));
*y = 0.25*(Y(0)*(1-xi)*(1-eta) + Y(1)*(1+xi)*(1-eta)
+ Y(2)*(1+xi)*(1+eta) + Y(3)*(1-xi)*(1+eta));
}
|
580f0e41ea986850ef5403be1053c0828358ffb6
|
f8c0b8a0ae169b6a86c08b3e4dcfc9a69f4a77d1
|
/src/World/World.hpp
|
fbf4ef53045bc6e8db67875f4d2efe280ae1c5da
|
[
"MIT"
] |
permissive
|
lvseouren/Swift2
|
a25ca01b24dd77b162ece98a1374041fe70bb9f7
|
3dd898c0ca6f508fbf37f5e507c2998378de89e0
|
refs/heads/master
| 2021-01-21T05:36:14.638937
| 2015-01-19T02:46:05
| 2015-01-19T02:46:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,335
|
hpp
|
World.hpp
|
#ifndef WORLD_HPP
#define WORLD_HPP
#include <string>
#include <vector>
#include <map>
/* SFML */
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/View.hpp>
#include <SFML/Graphics/Drawable.hpp>
/* Resources */
#include "../ResourceManager/AssetManager.hpp"
/* Entity */
#include "../EntitySystem/Entity.hpp"
#include "../EntitySystem/Systems/AnimatedSystem.hpp"
#include "../EntitySystem/Systems/ControllableSystem.hpp"
#include "../EntitySystem/Systems/DrawableSystem.hpp"
#include "../EntitySystem/Systems/MovableSystem.hpp"
#include "../EntitySystem/Systems/PathfinderSystem.hpp"
#include "../EntitySystem/Systems/PhysicalSystem.hpp"
#include "../EntitySystem/Systems/NoisySystem.hpp"
#include "../Mapping/TileMap.hpp"
#include "../SoundSystem/MusicPlayer.hpp"
#include "../SoundSystem/SoundPlayer.hpp"
namespace swift
{
class World
{
public:
World(const std::string& n, AssetManager& am, SoundPlayer& sp, MusicPlayer& mp, const std::vector<std::string>& scriptFiles);
virtual ~World();
virtual void update(float dt);
bool addScript(const std::string& scriptFile);
bool removeScript(const std::string& scriptFile);
void drawWorld(sf::RenderTarget& target, sf::RenderStates states = sf::RenderStates::Default);
void drawEntities(sf::RenderTarget& target, float e, sf::RenderStates states = sf::RenderStates::Default);
const std::string& getName() const;
Entity* addEntity();
bool removeEntity(int e);
Entity* getEntity(int e) const;
const std::vector<Entity*>& getEntities() const;
const std::vector<Entity*> getEntitiesAround(const sf::Vector2f& pos, float radius);
const std::vector<unsigned> getEntitiesAroundIDs(const sf::Vector2f& pos, float radius);
const std::vector<Collision*> getCollisions() const;
virtual bool load();
virtual bool save();
TileMap tilemap;
protected:
AssetManager& assets;
SoundPlayer& soundPlayer;
MusicPlayer& musicPlayer;
AnimatedSystem animSystem;
ControllableSystem controlSystem;
DrawableSystem drawSystem;
MovableSystem moveSystem;
PathfinderSystem pathSystem;
PhysicalSystem physicalSystem;
NoisySystem noisySystem;
std::vector<Entity*> entities;
private:
std::string name;
std::map<std::string, Script*> scripts;
};
}
#endif // WORLD_HPP
|
00e7a797004ce408f0b37092712b581f5ee17731
|
771b8d391585df59d8c7438e21e54976c4180011
|
/lib/OTExtensionBristol/OT/OTExtension.cpp
|
9a752a9bc176bcea68a084cb0d9b96325f5defaf
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
cryptobiu/libscapi
|
1f11f92065c1cea418e73b932c9810d374bac060
|
1f70a88548501eaca5fb635194443e7a2b871088
|
refs/heads/master
| 2023-08-10T08:34:21.304797
| 2022-08-16T16:48:20
| 2022-08-16T16:48:20
| 53,246,303
| 186
| 74
|
MIT
| 2023-07-20T11:01:17
| 2016-03-06T08:59:43
|
C++
|
UTF-8
|
C++
| false
| false
| 24,651
|
cpp
|
OTExtension.cpp
|
// (C) 2016 University of Bristol. See LICENSE.txt
#include "OTExtension.h"
#include "OT/Tools.h"
#include "Tools/aes.h"
#include "Tools/MMO.h"
#include <wmmintrin.h>
#include <emmintrin.h>
word TRANSPOSE_MASKS128[7][2] = {
{ 0x0000000000000000, 0xFFFFFFFFFFFFFFFF },
{ 0x00000000FFFFFFFF, 0x00000000FFFFFFFF },
{ 0x0000FFFF0000FFFF, 0x0000FFFF0000FFFF },
{ 0x00FF00FF00FF00FF, 0x00FF00FF00FF00FF },
{ 0x0F0F0F0F0F0F0F0F, 0x0F0F0F0F0F0F0F0F },
{ 0x3333333333333333, 0x3333333333333333 },
{ 0x5555555555555555, 0x5555555555555555 }
};
string word_to_str(word a)
{
stringstream ss;
ss << hex;
for(int i = 0;i < 8; i++)
ss << ((a >> (i*8)) & 255) << " ";
return ss.str();
}
// Transpose 16x16 matrix starting at bv[x][y] in-place using SSE2
void sse_transpose16(vector<BitVector>& bv, int x, int y)
{
__m128i input[2];
// 16x16 in two halves, 128 bits each
for (int i = 0; i < 2; i++)
for (int j = 0; j < 16; j++)
((octet*)&input[i])[j] = bv[x+j].get_byte(y / 8 + i);
for (int i = 0; i < 2; i++)
for (int j = 0; j < 8; j++)
{
int output = _mm_movemask_epi8(input[i]);
input[i] = _mm_slli_epi64(input[i], 1);
for (int k = 0; k < 2; k++)
// _mm_movemask_epi8 uses most significant bit, hence +7-j
bv[x+8*i+7-j].set_byte(y / 8 + k, ((octet*)&output)[k]);
}
}
/*
* Transpose 128x128 bit-matrix using Eklundh's algorithm
*
* Input is in input[i] [ bits <offset> to <offset+127> ], i = 0, ..., 127
* Output is in output[i + offset] (entire 128-bit vector), i = 0, ..., 127.
*
* Transposes 128-bit vectors in little-endian format.
*/
void eklundh_transpose128(vector<BitVector>& output, const vector<BitVector>& input,
int offset)
{
int width = 64;
int logn = 7, nswaps = 1;
#ifdef TRANSPOSE_DEBUG
stringstream input_ss[128];
stringstream output_ss[128];
#endif
// first copy input to output
for (int i = 0; i < 128; i++)
{
//output[i + offset*64] = input[i].get(offset);
output[i + offset].set_word(0, input[i].get_word(offset/64));
output[i + offset].set_word(1, input[i].get_word(offset/64 + 1));
#ifdef TRANSPOSE_DEBUG
for (int j = 0; j < 128; j++)
{
input_ss[j] << input[i].get_bit(offset + j);
}
#endif
}
// now transpose output in-place
for (int i = 0; i < logn; i++)
{
word mask1 = TRANSPOSE_MASKS128[i][1], mask2 = TRANSPOSE_MASKS128[i][0];
word inv_mask1 = ~mask1, inv_mask2 = ~mask2;
if (width == 8)
{
for (int j = 0; j < 8; j++)
for (int k = 0; k < 8; k++)
sse_transpose16(output, offset + 16 * j, 16 * k);
break;
}
else
// for width >= 64, shift is undefined so treat as a special case
// (and avoid branching in inner loop)
if (width < 64)
{
for (int j = 0; j < nswaps; j++)
{
for (int k = 0; k < width; k++)
{
int i1 = k + 2*width*j;
int i2 = k + width + 2*width*j;
// t1 is lower 64 bits, t2 is upper 64 bits
// (remember we're transposing in little-endian format)
word t1 = output[i1 + offset].get_word(0);
word t2 = output[i1 + offset].get_word(1);
word tt1 = output[i2 + offset].get_word(0);
word tt2 = output[i2 + offset].get_word(1);
// swap operations due to little endian-ness
output[i1 + offset].set_word(0, (t1 & mask1) ^
((tt1 & mask1) << width));
output[i1 + offset].set_word(1, (t2 & mask2) ^
((tt2 & mask2) << width) ^
((tt1 & mask1) >> (64 - width)));
output[i2 + offset].set_word(0, (tt1 & inv_mask1) ^
((t1 & inv_mask1) >> width) ^
((t2 & inv_mask2)) << (64 - width));
output[i2 + offset].set_word(1, (tt2 & inv_mask2) ^
((t2 & inv_mask2) >> width));
}
}
}
else
{
for (int j = 0; j < nswaps; j++)
{
for (int k = 0; k < width; k++)
{
int i1 = k + 2*width*j;
int i2 = k + width + 2*width*j;
// t1 is lower 64 bits, t2 is upper 64 bits
// (remember we're transposing in little-endian format)
word t1 = output[i1 + offset].get_word(0);
word t2 = output[i1 + offset].get_word(1);
word tt1 = output[i2 + offset].get_word(0);
word tt2 = output[i2 + offset].get_word(1);
output[i1 + offset].set_word(0, (t1 & mask1));
output[i1 + offset].set_word(1, (t2 & mask2) ^
((tt1 & mask1) >> (64 - width)));
output[i2 + offset].set_word(0, (tt1 & inv_mask1) ^
((t2 & inv_mask2)) << (64 - width));
output[i2 + offset].set_word(1, (tt2 & inv_mask2));
}
}
}
nswaps *= 2;
width /= 2;
}
#ifdef TRANSPOSE_DEBUG
for (int i = 0; i < 128; i++)
{
for (int j = 0; j < 128; j++)
{
output_ss[j] << output[offset + j].get_bit(i);
}
}
for (int i = 0; i < 128; i++)
{
if (output_ss[i].str().compare(input_ss[i].str()) != 0)
{
cerr << "String " << i << " failed. offset = " << offset << endl;
cerr << input_ss[i].str() << endl;
cerr << output_ss[i].str() << endl;
exit(1);
}
}
//cout << "\ttranspose with offset " << offset << " ok\n";
#endif
}
// get bit, starting from MSB as bit 0
int get_bit(word x, int b)
{
return (x >> (63 - b)) & 1;
}
int get_bit128(word x1, word x2, int b)
{
if (b < 64)
{
return (x1 >> (b - 64)) & 1;
}
else
{
return (x2 >> b) & 1;
}
}
void naive_transpose128(vector<BitVector>& output, const vector<BitVector>& input,
int offset)
{
for (int i = 0; i < 128; i++)
{
// NB: words are read from input in big-endian format
word w1 = input[i].get_word(offset/64);
word w2 = input[i].get_word(offset/64 + 1);
for (int j = 0; j < 128; j++)
{
//output[j + offset].set_bit(i, input[i].get_bit(j + offset));
if (j < 64)
output[j + offset].set_bit(i, (w1 >> j) & 1);
else
output[j + offset].set_bit(i, w2 >> (j-64) & 1);
}
}
}
void transpose64(
vector<BitVector>::iterator& output_it,
vector<BitVector>::iterator& input_it)
{
for (int i = 0; i < 64; i++)
{
for (int j = 0; j < 64; j++)
{
(output_it + j)->set_bit(i, (input_it + i)->get_bit(j));
}
}
}
// Naive 64x64 bit matrix transpose
void naive_transpose64(vector<BitVector>& output, const vector<BitVector>& input,
int xoffset, int yoffset)
{
int word_size = 64;
for (int i = 0; i < word_size; i++)
{
word w = input[i + yoffset].get_word(xoffset);
for (int j = 0; j < word_size; j++)
{
//cout << j + xoffset*word_size << ", " << yoffset/word_size << endl;
//int wbit = (((w >> j) & 1) << i); cout << "wbit " << wbit << endl;
// set i-th bit of output to j-th bit of w
// scale yoffset by 64 since we're selecting words from the BitVector
word tmp = output[j + xoffset*word_size].get_word(yoffset/word_size);
output[j + xoffset*word_size].set_word(yoffset/word_size, tmp ^ ((w >> j) & 1) << i);
// set i-th bit of output to j-th bit of w
//output[j + offset*word_size] ^= ((w >> j) & 1) << i;
}
}
}
void OTExtension::transfer(int nOTs,
const BitVector& receiverInput)
{
#ifdef OTEXT_TIMER
timeval totalstartv, totalendv;
gettimeofday(&totalstartv, NULL);
#endif
//cout << "\tDoing " << nOTs << " extended OTs as " << role_to_str(ot_role) << endl;
if (nOTs % nbaseOTs != 0)
throw invalid_length(); //"nOTs must be a multiple of nbaseOTs\n");
if (nOTs == 0)
return;
// add k + s to account for discarding k OTs
nOTs += 2 * 128;
vector<BitVector> t0(nbaseOTs, BitVector(nOTs)), tmp(nbaseOTs, BitVector(nOTs)), t1(nbaseOTs, BitVector(nOTs));
BitVector u(nOTs);
senderOutput.resize(2, vector<BitVector>(nOTs, BitVector(nbaseOTs)));
// resize to account for extra k OTs that are discarded
PRNG G;
G.ReSeed();
BitVector newReceiverInput(nOTs);
for (unsigned int i = 0; i < receiverInput.size_bytes(); i++)
{
newReceiverInput.set_byte(i, receiverInput.get_byte(i));
}
//BitVector newReceiverInput(receiverInput);
newReceiverInput.resize(nOTs);
receiverOutput.resize(nOTs, BitVector(nbaseOTs));
for (int loop = 0; loop < nloops; loop++)
{
vector<octetStream> os(2), tmp_os(2);
// randomize last 128 + 128 bits that will be discarded
for (int i = 0; i < 4; i++)
newReceiverInput.set_word(nOTs/64 - i, G.get_word());
// expand with PRG and create correlation
if (ot_role & RECEIVER)
{
for (int i = 0; i < nbaseOTs; i++)
{
t0[i].randomize(G_sender[i][0]);
t1[i].randomize(G_sender[i][1]);
tmp[i].assign(t1[i]);
tmp[i].add(t0[i]);
tmp[i].add(newReceiverInput);
tmp[i].pack(os[0]);
/*cout << "t0: " << t0[i].str() << endl;
cout << "t1: " << t1[i].str() << endl;
cout << "Sending tmp: " << tmp[i].str() << endl;*/
}
}
#ifdef OTEXT_TIMER
timeval commst1, commst2;
gettimeofday(&commst1, NULL);
#endif
// send t0 + t1 + x
send_if_ot_receiver(player, os, ot_role);
// sender adjusts using base receiver bits
if (ot_role & SENDER)
{
for (int i = 0; i < nbaseOTs; i++)
{
// randomize base receiver output
tmp[i].randomize(G_receiver[i]);
// u = t0 + t1 + x
u.unpack(os[1]);
if (baseReceiverInput.get_bit(i) == 1)
{
// now tmp is q[i] = t0[i] + Delta[i] * x
tmp[i].add(u);
}
}
}
#ifdef OTEXT_TIMER
gettimeofday(&commst2, NULL);
double commstime = timeval_diff(&commst1, &commst2);
//cout << "\t\tCommunication took time " << commstime/1000000 << endl << flush;
times["Communication"] += timeval_diff(&commst1, &commst2);
#endif
// transpose t0[i] onto receiverOutput and tmp (q[i]) onto senderOutput[i][0]
//cout << "Starting matrix transpose\n" << flush << endl;
#ifdef OTEXT_TIMER
timeval transt1, transt2;
gettimeofday(&transt1, NULL);
#endif
// transpose in 128-bit chunks with Eklundh's algorithm
for (int i = 0; i < nOTs / 128; i++)
{
// assume nbaseOTs = 128
if (ot_role & RECEIVER)
{
eklundh_transpose128(receiverOutput, t0, i*128);
//naive_transpose128(receiverOutput, t0, i*128);
}
if (ot_role & SENDER)
{
eklundh_transpose128(senderOutput[0], tmp, i*128);
//naive_transpose128(senderOutput[0], tmp, i*128);
}
}
#ifdef OTEXT_TIMER
gettimeofday(&transt2, NULL);
double transtime = timeval_diff(&transt1, &transt2);
//cout << "\t\tMatrix transpose took time " << transtime/1000000 << endl << flush;
times["Matrix transpose"] += timeval_diff(&transt1, &transt2);
#endif
#ifdef OTEXT_DEBUG
// verify correctness of the OTs
// i.e. senderOutput[0][i] + x_i * Delta = receiverOutput[i]
// (where Delta = baseReceiverOutput)
BitVector tmp_vector1(nbaseOTs), tmp_vector2(nOTs);//nbaseOTs);
//cout << "\tVerifying OT extensions (debugging)\n";
for (int i = 0; i < nOTs; i++)
{
os[0].reset_write_head();
os[1].reset_write_head();
if (ot_role & RECEIVER)
{
// send t0 and x over
receiverOutput[i].pack(os[0]);
//t0[i].pack(os[0]);
newReceiverInput.pack(os[0]);
}
send_if_ot_receiver(player, os, ot_role);
if (ot_role & SENDER)
{
tmp_vector1.unpack(os[1]);
tmp_vector2.unpack(os[1]);
// if x_i = 1, add Delta
if (tmp_vector2.get_bit(i) == 1)
{
tmp_vector1.add(baseReceiverInput);
}
if (!tmp_vector1.equals(senderOutput[0][i]))
{
cerr << "Incorrect OT at " << i << "\n";
exit(1);
}
}
}
//cout << "Correlated OTs all OK\n";
#endif
double elapsed;
// correlation check
if (!passive_only)
{
#ifdef OTEXT_TIMER
timeval startv, endv;
gettimeofday(&startv, NULL);
#endif
check_correlation(nOTs, newReceiverInput);
#ifdef OTEXT_TIMER
gettimeofday(&endv, NULL);
elapsed = timeval_diff(&startv, &endv);
//cout << "\t\tTotal correlation check time: " << elapsed/1000000 << endl << flush;
times["Total correlation check"] += timeval_diff(&startv, &endv);
#endif
}
hash_outputs(nOTs, receiverOutput);
#ifdef OTEXT_TIMER
gettimeofday(&totalendv, NULL);
elapsed = timeval_diff(&totalstartv, &totalendv);
//cout << "\t\tTotal thread time: " << elapsed/1000000 << endl << flush;
#endif
#ifdef OTEXT_DEBUG
// verify correctness of the random OTs
// i.e. senderOutput[0][i] + x_i * Delta = receiverOutput[i]
// (where Delta = baseReceiverOutput)
//cout << "Verifying random OTs (debugging)\n";
for (int i = 0; i < nOTs; i++)
{
os[0].reset_write_head();
os[1].reset_write_head();
if (ot_role & RECEIVER)
{
// send receiver's input/output over
receiverOutput[i].pack(os[0]);
newReceiverInput.pack(os[0]);
}
send_if_ot_receiver(player, os, ot_role);
//player->send_receive_player(os);
if (ot_role & SENDER)
{
tmp_vector1.unpack(os[1]);
tmp_vector2.unpack(os[1]);
// if x_i = 1, comp with sender output[1]
if ((tmp_vector2.get_bit(i) == 1))
{
if (!tmp_vector1.equals(senderOutput[1][i]))
{
cerr << "Incorrect OT\n";
exit(1);
}
}
// else should be sender output[0]
else if (!tmp_vector1.equals(senderOutput[0][i]))
{
cerr << "Incorrect OT\n";
exit(1);
}
}
}
//cout << "Random OTs all OK\n";
#endif
}
#ifdef OTEXT_TIMER
gettimeofday(&totalendv, NULL);
times["Total thread"] += timeval_diff(&totalstartv, &totalendv);
#endif
receiverOutput.resize(nOTs - 2 * 128);
senderOutput[0].resize(nOTs - 2 * 128);
senderOutput[1].resize(nOTs - 2 * 128);
}
/*
* Hash outputs to make into random OT
*/
void OTExtension::hash_outputs(int nOTs, vector<BitVector>& receiverOutput)
{
//cout << "Hashing... " << flush;
octetStream os, h_os(HASH_SIZE);
BitVector tmp(nbaseOTs);
RO ro;
MMO mmo;
#ifdef OTEXT_TIMER
timeval startv, endv;
gettimeofday(&startv, NULL);
#endif
for (int i = 0; i < nOTs; i++)
{
if (ot_role & SENDER)
{
tmp.add(senderOutput[0][i], baseReceiverInput);
if (senderOutput[0][i].size() == 128)
{
mmo.hashOneBlock(senderOutput[0][i].get_ptr(), senderOutput[0][i].get_ptr());
mmo.hashOneBlock(senderOutput[1][i].get_ptr(), tmp.get_ptr());
}
else
{
os.reset_write_head();
h_os.reset_write_head();
senderOutput[0][i].pack(os);
ro.Call(os, h_os, nbaseOTs/8);
senderOutput[0][i].unpack(h_os);
os.reset_write_head();
h_os.reset_write_head();
tmp.pack(os);
ro.Call(os, h_os, nbaseOTs/8);
senderOutput[1][i].unpack(h_os);
}
}
if (ot_role & RECEIVER)
{
if (receiverOutput[i].size() == 128)
mmo.hashOneBlock(receiverOutput[i].get_ptr(), receiverOutput[i].get_ptr());
else
{
os.reset_write_head();
h_os.reset_write_head();
receiverOutput[i].pack(os);
ro.Call(os, h_os, nbaseOTs/8);
receiverOutput[i].unpack(h_os);
}
}
}
//cout << "done.\n";
#ifdef OTEXT_TIMER
gettimeofday(&endv, NULL);
double elapsed = timeval_diff(&startv, &endv);
//cout << "\t\tOT ext hashing took time " << elapsed/1000000 << endl << flush;
times["Hashing"] += timeval_diff(&startv, &endv);
#endif
}
// test if a == b
int eq_m128i(__m128i a, __m128i b)
{
__m128i vcmp = _mm_cmpeq_epi8(a, b);
uint16_t vmask = _mm_movemask_epi8(vcmp);
return (vmask == 0xffff);
}
void random_m128i(PRNG& G, __m128i *r)
{
BitVector rv(128);
rv.randomize(G);
*r = _mm_load_si128((__m128i*)&(rv.get_ptr()[0]));
}
void test_mul()
{
//cout << "Testing GF(2^128) multiplication\n";
__m128i t1, t2, t3, t4, t5, t6, t7, t8;
PRNG G;
G.ReSeed();
BitVector r(128);
for (int i = 0; i < 1000; i++)
{
random_m128i(G, &t1);
random_m128i(G, &t2);
// test commutativity
gfmul128(t1, t2, &t3);
gfmul128(t2, t1, &t4);
if (!eq_m128i(t3, t4))
{
cerr << "Incorrect multiplication:\n";
cerr << "t1 * t2 = " << __m128i_toString<octet>(t3) << endl;
cerr << "t2 * t1 = " << __m128i_toString<octet>(t4) << endl;
}
// test distributivity: t1*t3 + t2*t3 = (t1 + t2) * t3
random_m128i(G, &t1);
random_m128i(G, &t2);
random_m128i(G, &t3);
gfmul128(t1, t3, &t4);
gfmul128(t2, t3, &t5);
t6 = _mm_xor_si128(t4, t5);
t7 = _mm_xor_si128(t1, t2);
gfmul128(t7, t3, &t8);
if (!eq_m128i(t6, t8))
{
cerr << "Incorrect multiplication:\n";
cerr << "t1 * t3 + t2 * t3 = " << __m128i_toString<octet>(t6) << endl;
cerr << "(t1 + t2) * t3 = " << __m128i_toString<octet>(t8) << endl;
}
}
t1 = _mm_set_epi32(0, 0, 0, 03);
t2 = _mm_set_epi32(0, 0, 0, 11);
//gfmul128(t1, t2, &t3);
mul128(t1, t2, &t3, &t4);
//cout << "t1 = " << __m128i_toString<octet>(t1) << endl;
//cout << "t2 = " << __m128i_toString<octet>(t2) << endl;
//cout << "t3 = " << __m128i_toString<octet>(t3) << endl;
//cout << "t4 = " << __m128i_toString<octet>(t4) << endl;
uint64_t cc[] __attribute__((aligned (16))) = { 0,0 };
_mm_store_si128((__m128i*)cc, t1);
word t1w = cc[0];
_mm_store_si128((__m128i*)cc, t2);
word t2w = cc[0];
//cout << "t1w = " << t1w << endl;
//cout << "t1 = " << word_to_bytes(t1w) << endl;
//cout << "t2 = " << word_to_bytes(t2w) << endl;
//cout << "t1 * t2 = " << word_to_bytes(t1w*t2w) << endl;
}
void OTExtension::check_correlation(int nOTs,
const BitVector& receiverInput)
{
//cout << "\tStarting correlation check\n" << flush;
#ifdef OTEXT_TIMER
timeval startv, endv;
gettimeofday(&startv, NULL);
#endif
if (nbaseOTs != 128)
{
cerr << "Correlation check not implemented for length != 128\n";
throw not_implemented();
}
PRNG G;
octet* seed = new octet[SEED_SIZE];
random_seed_commit(seed, *player, SEED_SIZE);
#ifdef OTEXT_TIMER
gettimeofday(&endv, NULL);
double elapsed = timeval_diff(&startv, &endv);
//cout << "\t\tCommitment for seed took time " << elapsed/1000000 << endl << flush;
times["Commitment for seed"] += timeval_diff(&startv, &endv);
gettimeofday(&startv, NULL);
#endif
G.SetSeed(seed);
vector<octetStream> os(2);
if (!Check_CPU_support_AES())
{
cerr << "Not implemented GF(2^128) multiplication in C\n";
throw not_implemented();
}
__m128i Delta, x128i;
Delta = _mm_load_si128((__m128i*)&(baseReceiverInput.get_ptr()[0]));
BitVector chi(nbaseOTs);
BitVector x(nbaseOTs);
__m128i t = _mm_setzero_si128();
__m128i q = _mm_setzero_si128();
__m128i t2 = _mm_setzero_si128();
__m128i q2 = _mm_setzero_si128();
__m128i chii, ti, qi, ti2, qi2;
x128i = _mm_setzero_si128();
for (int i = 0; i < nOTs; i++)
{
// chi.randomize(G);
// chii = _mm_load_si128((__m128i*)&(chi.get_ptr()[0]));
chii = G.get_doubleword();
if (ot_role & RECEIVER)
{
if (receiverInput.get_bit(i) == 1)
{
x128i = _mm_xor_si128(x128i, chii);
}
ti = _mm_loadu_si128((__m128i*)get_receiver_output(i));
// multiply over polynomial ring to avoid reduction
mul128(ti, chii, &ti, &ti2);
t = _mm_xor_si128(t, ti);
t2 = _mm_xor_si128(t2, ti2);
}
if (ot_role & SENDER)
{
qi = _mm_loadu_si128((__m128i*)(get_sender_output(0, i)));
mul128(qi, chii, &qi, &qi2);
q = _mm_xor_si128(q, qi);
q2 = _mm_xor_si128(q2, qi2);
}
}
#ifdef OTEXT_DEBUG
if (ot_role & RECEIVER)
{
//cout << "\tSending x,t\n";
//cout << "\tsend x = " << __m128i_toString<octet>(x128i) << endl;
//cout << "\tsend t = " << __m128i_toString<octet>(t) << endl;
//cout << "\tsend t2 = " << __m128i_toString<octet>(t2) << endl;
}
#endif
check_iteration(Delta, q, q2, t, t2, x128i);
#ifdef OTEXT_TIMER
gettimeofday(&endv, NULL);
elapsed = timeval_diff(&startv, &endv);
//cout << "\t\tChecking correlation took time " << elapsed/1000000 << endl << flush;
times["Checking correlation"] += timeval_diff(&startv, &endv);
#endif
}
void OTExtension::check_iteration(__m128i delta, __m128i q, __m128i q2,
__m128i t, __m128i t2, __m128i x)
{
vector<octetStream> os(2);
// send x, t;
__m128i received_t, received_t2, received_x, tmp1, tmp2;
if (ot_role & RECEIVER)
{
os[0].append((octet*)&x, sizeof(x));
os[0].append((octet*)&t, sizeof(t));
os[0].append((octet*)&t2, sizeof(t2));
}
send_if_ot_receiver(player, os, ot_role);
if (ot_role & SENDER)
{
os[1].consume((octet*)&received_x, sizeof(received_x));
os[1].consume((octet*)&received_t, sizeof(received_t));
os[1].consume((octet*)&received_t2, sizeof(received_t2));
// check t = x * Delta + q
//gfmul128(received_x, delta, &tmp1);
mul128(received_x, delta, &tmp1, &tmp2);
tmp1 = _mm_xor_si128(tmp1, q);
tmp2 = _mm_xor_si128(tmp2, q2);
if (eq_m128i(tmp1, received_t) && eq_m128i(tmp2, received_t2))
{
//cout << "\tCheck passed\n";
}
else
{
cerr << "Correlation check failed\n";
//cout << "rec t = " << __m128i_toString<octet>(received_t) << endl;
//cout << "tmp1 = " << __m128i_toString<octet>(tmp1) << endl;
//cout << "q = " << __m128i_toString<octet>(q) << endl;
exit(1);
}
}
}
octet* OTExtension::get_receiver_output(int i)
{
return receiverOutput[i].get_ptr();
}
octet* OTExtension::get_sender_output(int choice, int i)
{
return senderOutput[choice][i].get_ptr();
}
|
1e34f5964829a1883d7ff528221a41fd9776448c
|
dbc0e3582d65bcf9d8fba29d872d6407454f9e28
|
/PRACTICE/activity_selection.cpp
|
63715174454f501864f9f60d7b9ed525707ae79c
|
[] |
no_license
|
sirAdarsh/CP-files
|
0b7430e2146620535451e0ab8959f70047bd7ea2
|
8d411224293fec547a3caa2708eed351c977ebed
|
refs/heads/master
| 2023-04-05T09:07:21.554361
| 2021-04-08T19:57:33
| 2021-04-08T19:57:33
| 297,582,418
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 886
|
cpp
|
activity_selection.cpp
|
#include<bits/stdc++.h>
#define ll long long
using namespace std;
typedef pair<int,int> Pair; //(start time, end time)
bool comp(Pair j1, Pair j2){
if(j1.first < j2.first){
return true;
}
else if(j1.first == j2.first && j1.second < j2.second){
return true;
}
return false;
}
int solve(vector<Pair> jobs){
int n = jobs.size();
sort(jobs.begin(), jobs.end(), comp);
int dp[n] = {}; //stores the max jobs done till i
dp[0]=1;
for(int i=1; i<n; i++){
for(int j=0; j<i; j++){
if( jobs[j].second < jobs[i].first ){
if(dp[j] > dp[i]){
dp[i] = dp[j];
}
}
}
dp[i]++;
}
return *max_element(dp,dp+n);
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
vector<Pair> jobs =
{
{1, 4}, {3, 5}, {0, 6}, {5, 7}, {3, 8}, {5, 9},
{6, 10}, {8, 11}, {8, 12}, {2, 13}, {12, 14}
};
cout<< solve(jobs);
}
|
b95614e778b30fb054a7588250cf1244c3c0f46e
|
15db79adc4476f06f35cd4a219313aacda5890eb
|
/util.cpp
|
7bf8118c178402ed3f5f2e9655f0b952e745e581
|
[] |
no_license
|
12tqian/cryptanalysis
|
2e61ca80015e7d2033460c540a8c96b0f7c4e320
|
b38806fba41bc39b093c689011a51d0674818e7d
|
refs/heads/master
| 2020-06-23T14:23:30.955360
| 2020-03-17T18:04:27
| 2020-03-17T18:04:27
| 198,648,463
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,251
|
cpp
|
util.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll WS = 16;
ll one = 1;
ll rotl(ll n, ll d, ll MX = WS) {
return ((n << d)|(n >> (MX - d)))&((one<<MX) - one);
}
ll rotr(ll n, ll d, ll MX = WS) {
return (n >> d)|(n << (MX - d))&((one<<MX) - one);
}
ll flip(ll n, ll MX = WS){
return (((one<<MX)-one)^n);
}
ll wt(ll n, ll MX = WS){
int cnt = 0;
while(n){
cnt += (n&1);
n>>=1;
}
return cnt;
}
ll f(ll x, ll MX = WS){
return (rotl(x, 1, MX)&rotl(x, 8, MX))^rotl(x, 2, MX);
}
pair<ll, ll> split(ll x, ll MX = WS){
return make_pair((x>>MX), ((x)%(1<<MX)));
}
ll get(ll a, ll n){
return (a>>n)&1;
}
ll compose(ll l, ll r, ll MX = WS){
return r + (l<<MX);
}
ll convert(vector<int> a, ll MX = WS){
ll ret = 0;
ll exp = 1;
for(int i = 0; i< MX; i++){
ret += exp*a[i];
exp *= 2;
}
return ret;
}
ll convert2(vector<int> a, ll MX = WS){
vector<int> use;
for(int i = a.size() -1; i>= 0; i--){
use.emplace_back(a[i]);
}
return convert(use, MX);
}
vector<int> arr(ll a, ll MX = WS){
vector<int> ret;
for(int i = 0; i<MX; i++){
ret.emplace_back(get(a, i));
}
return ret;
}
int main(){
return 0;
}
|
80082520ee81b51758f98573e725515eb021a896
|
9d6e7657ef109d4131a239ccd21b665a92f3b17b
|
/Observer/WeatherData.cpp
|
0a9d11dad2c844bcbf05ea116fa25d0098857f2f
|
[] |
no_license
|
CtfChan/DesignPatternsCpp
|
380f445887156c5d356a4de14f503710bd080480
|
1ca4288b907e0b711b4d5418ff0dc0ade72b25f0
|
refs/heads/master
| 2022-07-06T02:16:10.142991
| 2020-05-19T19:05:45
| 2020-05-19T19:05:45
| 264,729,319
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 977
|
cpp
|
WeatherData.cpp
|
#include "WeatherData.hpp"
#include "Observer.hpp"
#include <algorithm>
void WeatherData::registerObsever(Observer* o) {
observers_.push_back(o);
}
void WeatherData::removeObserver(Observer* o) {
auto it = std::find_if(observers_.begin(), observers_.end(), [&o](const auto& other_obs){
return other_obs == o;
});
observers_.erase(it);
}
void WeatherData::notifyObservers() {
for (auto obs : observers_) {
obs->update(temperature_, humidity_, pressure_);
}
}
void WeatherData::measurementsChanged() {
notifyObservers();
}
void WeatherData::setMeasurements(float temperature, float humidity, float pressure) {
temperature_ = temperature;
humidity_ = humidity;
pressure_ = pressure;
measurementsChanged();
}
float WeatherData::getTemperature() const {
return temperature_;
}
float WeatherData::getHumidity() const {
return humidity_;
}
float WeatherData::getPressure() const {
return pressure_;
}
|
ae13ad3e7fed675a41e6ed8dd60087e2ad90c7b6
|
656cbd1962d676fadbecd430f2847c3d378daca9
|
/1011C.cpp
|
4baea9118306d9f72afebcbc79e44b1eef90edc3
|
[] |
no_license
|
AkazawaNozomu/codeforces
|
b642fdc85bfdff3010b81ef971faefe5d1c11e33
|
c0da0e8095e482f0adfd02865b77412f4e6f25d5
|
refs/heads/master
| 2020-04-02T10:40:41.729352
| 2018-10-23T15:09:27
| 2018-10-23T15:09:27
| 154,349,586
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 728
|
cpp
|
1011C.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e3+5;
ll a[maxn],b[maxn];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
ll m,n;
cin>>n>>m;
for(int i=0;i<n;i++)cin>>a[i];
for(int i=0;i<n;i++)cin>>b[i];
b[n]=b[0];
long double l=0,r=1e9,mid,curw;
for(int j=0;j<10;j++)
{
mid=(l+r)/2;
curw=mid+(long double)m;
for(int i=0;i<n;i++)
{
curw-=curw/(long double)a[i];
//curw=mid+(long double)m;
curw-=curw/(long double)b[i+1];
//curw=mid+(long double)m;
if(curw<m)break;
cout<<fixed<<setprecision(9)<<curw<<endl;
}
if(curw<m)r=mid;
else l=mid;
cout<<fixed<<setprecision(9)<<l<<r<<endl;
}
cout<<fixed<<setprecision(9)<<l;
return 0;
}
|
fc4562e8ee29e44c65e2cc776e284010beb3243a
|
e8dd6366a191a797c8b9ec08efc7bfbf35073636
|
/include/doomtype.h
|
e26a09c196891141e9c736ea828e49cd0dcfa4ae
|
[] |
no_license
|
meiavy/doom-legacy
|
f89888790c47ec8188c7d97cdbb559ea2d45af7e
|
60b4651c64a1630868623a49fd6de7e78db5feac
|
refs/heads/master
| 2020-12-29T08:43:48.813795
| 2014-05-23T21:27:21
| 2014-05-23T21:27:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,880
|
h
|
doomtype.h
|
// Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id$
//
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 1998-2007 by DooM Legacy Team.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//-----------------------------------------------------------------------------
/// \file
/// \brief Basic typedefs and platform-dependent #defines
#ifndef doomtype_h
#define doomtype_h 1
// Standard library differences
#ifdef __WIN32__
# include <windows.h>
# define ASMCALL __cdecl
#else
# define ASMCALL
#endif
#ifdef __APPLE_CC__
# define __MACOS__
# define DEBUG_LOG
# ifndef O_BINARY
# define O_BINARY 0
# endif
#endif
#if defined(__MSC__) || defined(__OS2__) // Microsoft VisualC++
# define strncasecmp strnicmp
# define strcasecmp stricmp
# define inline __inline
#elseif defined(__WATCOMC__)
# define strncasecmp strnicmp
# define strcasecmp strcmpi
#endif
#if defined(__linux__)
# define O_BINARY 0
#endif
// Basic typedefs.
// NOTE! Somewhere in the code we may still implicitly assume that int = 32 bits, short = 16 bits!
// These should be replaced with the unambiguous types defined below.
#ifdef SDL
# include "SDL_types.h"
#else
# include <stdint.h>
typedef int8_t Sint8;
typedef int16_t Sint16;
typedef int32_t Sint32;
# ifdef __WIN32__
typedef __int64 Sint64;
# else
typedef int64_t Sint64;
# endif
typedef uint8_t Uint8;
typedef uint16_t Uint16;
typedef uint32_t Uint32;
#endif
typedef Uint8 byte;
typedef Uint32 tic_t;
typedef Uint32 angle_t;
struct RGB_t
{
byte r, g, b;
};
union RGBA_t
{
Uint32 rgba;
struct
{
byte red;
byte green;
byte blue;
byte alpha;
};
};
// Predefined with some OS.
#ifndef __WIN32__
# ifndef __MACOS__
# ifndef FREEBSD
# include <values.h>
# else
# include <limits.h>
# endif
# endif
#endif
#ifndef MAXCHAR
# define MAXCHAR ((char)0x7f)
#endif
#ifndef MAXSHORT
# define MAXSHORT ((short)0x7fff)
#endif
#ifndef MAXINT
# define MAXINT ((int)0x7fffffff)
#endif
#ifndef MAXLONG
# define MAXLONG ((long)0x7fffffff)
#endif
#ifndef MINCHAR
# define MINCHAR ((char)0x80)
#endif
#ifndef MINSHORT
# define MINSHORT ((short)0x8000)
#endif
#ifndef MININT
# define MININT ((int)0x80000000)
#endif
#ifndef MINLONG
# define MINLONG ((long)0x80000000)
#endif
#endif
|
eff17753bf40d4a37f657e1b0fa585f005b4bca7
|
691ab076d1498018bee99eff9118e2f8df3ab764
|
/mpi/src/Grid.h
|
43c5692c986c837ff3275c04a0a4a6b515cffbb8
|
[] |
no_license
|
pedrorio/parallel_and_distributed_computing
|
7b0375b22839b768d6d67af203c1b0483f09cf1c
|
e78f417411cbe78a1d8ae3bd4a3b18d480d89b2a
|
refs/heads/master
| 2022-12-09T10:28:09.553931
| 2020-09-16T10:46:37
| 2020-09-16T10:46:37
| 244,902,238
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 125
|
h
|
Grid.h
|
//
// Created by Pedro Rio on 28/05/2020.
//
#ifndef MPI_GRID_H
#define MPI_GRID_H
class Grid {
};
#endif //MPI_GRID_H
|
ce0168b0d78e3a3db107735b6f37933a0fc5ea8f
|
07fe910f4a2c7d14e67db40ab88a8c91d9406857
|
/game/xme/Reference.h
|
14656824703c15aa9ce63f7e086bba9394a24c5e
|
[] |
no_license
|
SEDS/GAME
|
e6d7f7a8bb034e421842007614d306b3a6321fde
|
3e4621298624b9189b5b6b43ff002306fde23f08
|
refs/heads/master
| 2021-03-12T23:27:39.115003
| 2015-09-22T15:05:33
| 2015-09-22T15:05:33
| 20,278,561
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,339
|
h
|
Reference.h
|
// -*- C++ -*-
//=============================================================================
/**
* @file Reference.h
*
* $Id$
*
* @author James H. Hill
*/
//=============================================================================
#ifndef _GAME_XME_REFERENCE_H_
#define _GAME_XME_REFERENCE_H_
#include "FCO.h"
namespace GAME
{
namespace XME
{
// Forward decl.
class Folder;
// Forward decl.
class Model;
/**
* @class Reference
*
* Base class for all the objects
*/
class GAME_XME_Export Reference : public FCO
{
public:
/**
* Create a new folder
*
* @param[in] parent Parent of the new folder
* @param[in] kind Type folder's type
*/
static Reference _create (Folder parent, const GAME::Xml::String & kind);
/**
* Create a new folder
*
* @param[in] parent Parent of the new folder
* @param[in] kind Type folder's type
*/
static Reference _create (Model parent, const GAME::Xml::String & kind);
/**
* Narrow an object to an atom.
*
* @param[in] obj Source object
* @return The atom version of the object
*/
static Reference _narrow (const Object & obj);
/// Default constructor.
Reference (void);
/**
* Initializing constructor
*
* @param[in] obj The source object.
*/
Reference (xercesc::DOMElement * ref, bool validate);
/**
* Copy constructor
*
* @param[in] obj The source object
*/
Reference (const Reference & atom);
/// Destructor.
~Reference (void);
/**
* Assignment operator
*
* @param[in] obj The right side of the operator
*/
const Reference & operator = (const Reference & atom);
/**
* Get the FCO that this object references.
*
* @return Referenced FCO
*/
FCO refers_to (void) const;
/**
* Set the FCO this object references
*
* @param[in] fco Target FCO
*/
void refers_to (const FCO & fco);
/// Reset the reference. This will remove the current FCO
/// that this object references.
void reset (void);
/// The XML tagname for this element.
static const GAME::Xml::String TAGNAME;
/// Test if the reference is null.
bool is_null (void) const;
/// Refresh the state of the reference. This will relocate the
/// referred object and store it, or set the point to null of it
/// no longer exists.
void refresh (void);
protected:
/**
* Initializing constructor. This constructor creates the actual
* DOMElement that represents the folder object.
*/
Reference (xercesc::DOMElement * parent,
const GAME::Xml::String & kind,
size_t relid);
Reference (xercesc::DOMElement * ref);
private:
/// Helper method that locates referenced object in document.
void get_reference (void) const;
/// Implementation of the creation method.
template <typename T>
static Reference create_impl (T parent, const GAME::Xml::String & kind);
/// FCO that this object references.
mutable FCO refers_to_;
/// XML attributes for this element.
static const GAME::Xml::String ATTR_REFERRED;
static const GAME::Xml::String NULL_REFERENCE;
};
}
}
#if defined (__GAME_INLINE__)
#include "Reference.inl"
#endif
#endif // !defined _GAME_XME_ATOM_H_
|
c0849a0aa34ade31d7c7f44a9f25983b28fdd89c
|
be4e0185d682641023e98c35723bf3c9ca30192f
|
/src/sim_acceptance.cc
|
da1ae1db8a04e11a2cacf1b36a71afb0fcf9e1b4
|
[] |
no_license
|
mam-mih-val/hades_v1_even
|
43a5d18cdd11969f4b377b18e29db5050eb959a4
|
088a62d16515b4b528964b91dc42d075f9f2450b
|
refs/heads/master
| 2023-03-18T11:09:26.358677
| 2021-03-03T12:12:39
| 2021-03-03T12:12:39
| 343,820,016
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,581
|
cc
|
sim_acceptance.cc
|
//
// Created by mikhail on 6/29/20.
//
#include "sim_acceptance.h"
#include <AnalysisTree/DataHeader.hpp>
namespace AnalysisTree {
void SimAcceptance::Init(std::map<std::string, void *> &branch_map) {
std::cout << "SimAcceptance::Init(): START" << std::endl;
sim_header_ = static_cast<EventHeader *>(branch_map.at("sim_header"));
reco_header_ = static_cast<EventHeader *>(branch_map.at("event_header"));
sim_tracks_ = static_cast<Particles *>(branch_map.at("sim_tracks"));
double y_axis[16];
for(int j=0; j<16; ++j){ y_axis[j]=-0.75+0.1* (double) j; }
double pt_axis[]={0, 0.29375, 0.35625, 0.41875, 0.48125, 0.54375, 0.61875, 0.70625, 0.81875, 1.01875, 2.0};
v1_even_ = new TProfile2D( "v1_even_10_40pc", ";y_{cm};p_{T}",
15, y_axis,
10, pt_axis );
v1_straight_ = new TProfile2D( "v1_(y)_10_40pc", ";y_{cm};p_{T}",
15, y_axis,
10, pt_axis );
v1_reflected_ = new TProfile2D( "v1_(-y)_10_40pc", ";y_{cm};p_{T}",
15, y_axis,
10, pt_axis );
std::cout << "SimAcceptance::Init(): RETURN" << std::endl;
}
void SimAcceptance::Exec() {
// std::cout << "SimAcceptance::Exec(): START" << std::endl;
auto centrality = reco_header_->GetField<float>(
config_->GetBranchConfig("event_header").GetFieldId("selected_tof_rpc_hits_centrality") );
if( centrality > 40 )
return;
if( centrality < 10 )
return;
auto psi_rp = sim_header_->GetField<float>(
config_->GetBranchConfig("sim_header").GetFieldId("reaction_plane"));
auto beam_y = data_header_->GetBeamRapidity();
int n_sim_tracks = sim_tracks_->GetNumberOfChannels();
for (int i = 0; i < n_sim_tracks; ++i) {
auto s_track = (sim_tracks_->GetChannel(i));
if( s_track.GetPid() != 2212 )
continue;
auto y = s_track.GetRapidity() - beam_y;
auto phi = s_track.GetPhi();
auto pt = s_track.GetPt();
auto delta_phi = phi - psi_rp;
v1_straight_->Fill( y, pt, cos(delta_phi) );
v1_reflected_->Fill( -y, pt, cos(delta_phi) );
v1_even_->Fill( y, pt, 0.5*cos(delta_phi) );
v1_even_->Fill( -y, pt, 0.5*cos(delta_phi) );
}
// std::cout << "SimAcceptance::Exec(): RETURN" << std::endl;
}
void SimAcceptance::Finish() {
std::cout << "SimAcceptance::Finish(): START" << std::endl;
v1_straight_->Write();
v1_reflected_->Write();
v1_even_->Write();
std::cout << "SimAcceptance::Finish(): Files are written" << std::endl;
}
} // namespace AnalysisTree
|
67c777752ffd2f87bc8d817e9849c3541289a42f
|
87502da17952d4f4bc63f91ac1d8bf4d62eb068b
|
/Sequence_aligner.h
|
23cfddda5d16c26a7cac87512dd188871b4b9e27
|
[] |
no_license
|
artiee/star
|
9b4fd08145fa6ef7db64b7be1e7b0ea23068d3a3
|
0c6ee7b101301864d0754af7ae236dab18d9aa3a
|
refs/heads/master
| 2016-09-06T08:07:41.502828
| 2014-03-07T15:57:48
| 2014-03-07T15:57:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,020
|
h
|
Sequence_aligner.h
|
#ifndef SEQUENCE_ALIGNER_H
#define SEQUENCE_ALIGNER_H
#include <iostream>
#include <string>
#include <vector>
#include "Sequence.h"
using namespace std;
/**
* The abstract sequence aligner class.
* Based on the tutorial at http://www.sbc.su.se/~per/molbioinfo2001/dynprog/dynamic.html
*/
class Sequence_aligner
{
public:
Sequence_aligner(); // Default constructor. If used the sequences must be set using set_sequence..-functions.
Sequence_aligner(Sequence a, Sequence b);
Sequence_aligner(string s1, string s2) ;
virtual ~Sequence_aligner();
void initialize_matrix(string seq1, string seq2); //Initialises the matrix. The first column and first row are filled with nulls by default. Different initialisation can be done by overwriting this method.
void fill_matrix(); // Fills the matrix by using the scoring set to class.
void print_matrix(); // Prints the values from matrice mp.
virtual vector<Sequence>* traceback(); // Walks through the matrix and aligns the sequences in the way programmer wants.
int get_cap_penalty() const; // Tells how much cap costs in sequence.
int get_match_score() const;
int get_mismatch_score() const;
void set_cap_penalty(const int cp);
void set_match_score(const int ms);
void set_mismatch_score(const int mms);
void set_sequence1(const string a); // The sequences that are aligned must be set if the default constructor is used.
void set_sequence2(string b);
void set_verbalize(bool v); // If true program tells what it is doing.
string reverse( const string& strReversible ); // Returns a copy that is reversed of string.
protected:
int *mp; // Pointer to valuematrix.
/* Table sized of matrice mp. Each element is a pointer to a int-table.
Table is used in traback phase. Int-table holds values which tell
where to brach in traback.
___________
tbmp-> |p0|p1|p2|p3| p0--->[p0.1|p0.2|p0.3|...]
|p4|p5|p6|p7|
|p8|p9|pA|pB|
*/
int **tbmp; // Traceback matrices pointer.
int y_size; // Matrices y-size
int x_size; // Matrices x-size
string seq1; // Sequence 1
string seq2;
int cap_penalty; // How much costs to add a cap (empty space) to a sequence.
int match_score;
int mismatch_score;
static const int MIN = -9999;
bool verbalize; // Tells what is done while execution.
/**
* Functions that involve walking in matrice:
*/
int left(int pos); // Walks one left in matrice.
int ldiag(int pos); // ldiag = left diagonal. Walks one top left.
int top(int pos); // Walks one up.
/**
* Functions which check if element next to matrices position is the same.
*/
int left_match(int pos); // Element in pos matches to a element one left from position.
int ldiag_match(int pos); // Element in pos matches to a element one left and up (top left) from position.
int top_match(int pos); // Element in pos matches to a element one up from position.
char get_seq1_letter(int pos) const; // Returns the letter from sequence1 (which can be thought to be on top column.)
char get_seq2_letter(int pos) const; // Returns the letter from sequence2 (which can be thought to be on left row.)
int max(int a, int b, int c) const; // Returns max of these 3 integers.
/**
* The following functions assume that i > 0 and j > 0.
*
* The purpose is to calculate from elements next to position
* (left, top left and top) which value they hold when the
* cap_penalty and match_score are taken into account.
* The left and top incorporate cap_penalty and top left gets
* match_score or mismatch score.
*/
int f1(int i, int j); // ldiag. Counts calue for left top. (match/mismatch_score)
int f2(int i, int j); // top. (cap_penalty)
int f3(int i, int j); // left. (cap_penalty)
int match(int i, int j) const; // Returns match_score if match, otherwise mismatch_score.
int letter_match(int pos) const; // Returns 1 if letters match in sequence1 and sequence2 in given position in matrice mp. (The sequence1 is thought to be on top and sequence2 left to the matrice.)
};
#endif
|
8e11de6ed323ec98498a2f4c59be369c501dae16
|
1a91bdd47ab7829a278da1fb6ddcfc5c386293b3
|
/third_party/dapcstp/include/bbnode.h
|
c118ec79e13f2a2d5df0f566e1b7fc1b734cf880
|
[] |
no_license
|
danzeng8/TopoSimplifier
|
43738b843577fc34cc469bed24bdf23c4fcf088b
|
10753151afac5bd35f574f834a029788ecd1e25e
|
refs/heads/master
| 2023-07-09T22:06:18.850305
| 2021-08-04T21:09:00
| 2021-08-04T21:09:00
| 266,427,563
| 22
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 859
|
h
|
bbnode.h
|
/**
* \file bbnode.h
* \brief branch-and-bound node
*
* \author Martin Luipersbeck
* \date 2015-05-03
*/
#ifndef BBNODE_H_
#define BBNODE_H_
#include "inst.h"
#include "ds.h"
class BBNode {
public:
weight_t lb = 0.0;
int v = -1, bdir = -1; // branching node and direction (0 or 1)
int depth = 0;
int n = 0, m = 0, nfree = 0;
bool feas = false;
bool processed = false;
int state = -1;
int v2 = -1;
Inst* inst;
// queue positions in B&B
PQMin<weight_t,BBNode*>::handle_type pqposMin;
PQMax<weight_t,BBNode*>::handle_type pqposMax;
BBNode(Inst* inst);
// creating node rooted at given root
BBNode(Inst* inst, int root, vector<int>& fe0);
// create a node by branching on variable var (bdir is 0 or 1)
BBNode(const BBNode* b, int var, int bdir);
// updates instance graph size
void updateNodeSize();
};
#endif // BBNODE_H_
|
ddaf1fc0a6a4a81cb383b42c3988a265a5099a1f
|
09f01e31045092400652ca237a11ae9016a801e9
|
/openGL/2D/MosPro/src/physics/bspNode2D.cpp
|
587bcbea22f26ee35930cb74360a1177693ec07e
|
[] |
no_license
|
forsythrosin/MosPro
|
186078e72e909022f8cc9f0c0a8bf3d80c6ba403
|
bd6566bc3052f5e17b15f4f3abd014bcc834f87c
|
refs/heads/master
| 2016-09-10T20:05:15.125834
| 2013-11-26T12:52:10
| 2013-11-26T12:52:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,127
|
cpp
|
bspNode2D.cpp
|
#include "BSPNode2D.h"
#include "rigidBody2D.h"
#include "potentialCollision2D.h"
#include "physicsEngine2D.h"
#include "../lib/debugInterface.h"
BSPNode2D::BSPNode2D(BSPNode2D *parent, BSPLocation2D location, double granularity) {
assert(parent);
this->location = location;
this->parent = parent;
this->bodies = std::set<RigidBody2D*>();
this->size = parent->size * 0.5f;
glm::vec2 parentCenter = parent->globalCenter;
switch (location) {
case rightUpper:
this->globalCenter = glm::vec2(parentCenter.x + size.x/2, parentCenter.y + size.y/2);
break;
case leftUpper:
this->globalCenter = glm::vec2(parentCenter.x - size.x/2, parentCenter.y + size.y/2);
break;
case leftLower:
this->globalCenter = glm::vec2(parentCenter.x - size.x/2, parentCenter.y - size.y/2);
break;
case rightLower:
this->globalCenter = glm::vec2(parentCenter.x + size.x/2, parentCenter.y - size.y/2);
break;
}
if (size.x > granularity || size.y > granularity) {
q1 = new BSPNode2D(this, rightUpper, granularity);
q2 = new BSPNode2D(this, leftUpper, granularity);
q3 = new BSPNode2D(this, leftLower, granularity);
q4 = new BSPNode2D(this, rightLower, granularity);
} else {
q1 = NULL;
q2 = NULL;
q3 = NULL;
q4 = NULL;
}
}
BSPNode2D::BSPNode2D(glm::vec2 size, double granularity) {
this->location = root;
this->size = size;
this->parent = NULL;
this->bodies = std::set<RigidBody2D*>();
if (size.x > granularity || size.y > granularity) {
q1 = new BSPNode2D(this, rightUpper, granularity);
q2 = new BSPNode2D(this, leftUpper, granularity);
q3 = new BSPNode2D(this, leftLower, granularity);
q4 = new BSPNode2D(this, rightLower, granularity);
} else {
q1 = NULL;
q2 = NULL;
q3 = NULL;
q4 = NULL;
}
}
void BSPNode2D::updatePosition(RigidBody2D *rb) {
if (shouldContain(rb)) {
if (!contains(rb)) {
insert(rb);
}
updateChildren(rb);
} else {
if (contains(rb)) {
remove(rb);
updateChildren(rb);
}
}
}
void BSPNode2D::updateChildren(RigidBody2D *rb) {
if (hasChildren()) {
q1->updatePosition(rb);
q2->updatePosition(rb);
q3->updatePosition(rb);
q4->updatePosition(rb);
}
}
std::set<PotentialCollision2D> BSPNode2D::getPotentialCollisions() {
std::set<PotentialCollision2D> pc;
if (bodies.size() > 1) {
if (hasChildren()) {
std::set<PotentialCollision2D> pc1, pc2, pc3, pc4;
pc1 = q1->getPotentialCollisions();
pc2 = q2->getPotentialCollisions();
pc3 = q3->getPotentialCollisions();
pc4 = q4->getPotentialCollisions();
pc.insert(pc1.begin(), pc1.end());
pc.insert(pc2.begin(), pc2.end());
pc.insert(pc3.begin(), pc3.end());
pc.insert(pc4.begin(), pc4.end());
} else {
std::set<RigidBody2D*>::iterator i, j;
for (i = bodies.begin(); i != bodies.end(); i++) {
j = i;
for (j++; j != bodies.end(); j++) {
RigidBody2D *a = *i;
RigidBody2D *b = *j;
PotentialCollision2D p(a, b);
pc.insert(p);
}
}
}
}
return pc;
}
Box2D BSPNode2D::getBox() {
glm::vec2 halfSize = size * 0.5f;
Box2D b = Box2D(-halfSize.x, -halfSize.y, halfSize.x, halfSize.y) + globalCenter;
return b;
}
bool BSPNode2D::shouldContain(RigidBody2D *rb) {
return getBox().intersects(rb->getBoundingBox());
}
bool BSPNode2D::contains(RigidBody2D *rb) {
return bodies.find(rb) != bodies.end();
}
bool BSPNode2D::hasChildren() {
return !!q1;
}
void BSPNode2D::insert(RigidBody2D *rb) {
bodies.insert(rb);
}
void BSPNode2D::remove(RigidBody2D *rb) {
std::set<RigidBody2D*>::iterator i = bodies.find(rb);
if (i != bodies.end()) {
bodies.erase(i);
}
}
std::string BSPNode2D::getIdentifier() const {
std::stringstream s;
if (parent) {
s << parent->getIdentifier();
}
switch (location) {
case root:
s << "0";
break;
case rightUpper:
s << "1";
break;
case leftUpper:
s << "2";
break;
case leftLower:
s << "3";
break;
case rightLower:
s << "4";
break;
}
return s.str();
}
std::ostream &operator<< (std::ostream &out, const BSPNode2D& b) {
return out << "BSPNode2D: " << b.getIdentifier();
}
// Todo: create destructor
|
3d17194557f17b2a4b930bc2bfad2f3176e1543b
|
84c5f501eb2001f166470ce8d26de3eec8de9c99
|
/5/server.cpp
|
c5c0e704637467d5f40d615d63997d404fdfe159
|
[] |
no_license
|
Aidenryan/Network-programming.
|
f2e1d69cdb5a0404356e5b0232d525b85398dbe9
|
a45b6378b4de8a13a099c57dd2ae4bfe43d7b20f
|
refs/heads/main
| 2023-04-24T04:07:17.012400
| 2021-05-05T08:28:43
| 2021-05-05T08:28:43
| 358,571,929
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,629
|
cpp
|
server.cpp
|
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define buf_size 1024//设置缓冲区大小
int main(int argc, char* argv[])
{
if(argc <=2)
{
cout<<"usage: ./exe ip_address port_number"<<endl;
return -1;
}
const char* ip = argv[1];
int port = atoi(argv[2]);
sockaddr_in server_address;
bzero(&server_address, sizeof(server_address));
server_address.sin_family = AF_INET;
inet_pton(AF_INET, ip, &server_address.sin_addr);
server_address.sin_port = htons(port);
//创建socket
int sockfd = socket(PF_INET, SOCK_STREAM, 0);
assert(sockfd >= 0);
//绑定
int ret = bind(sockfd, (sockaddr*)&server_address, sizeof(server_address));
assert(ret != -1);
//监听
ret = listen(sockfd, 5);
assert(ret != -1);
int cfd = accept(sockfd, NULL, NULL);
if(cfd < 0)
{
perror("Accept error");
}
else
{
char buff[buf_size];
memset(buff, 0, buf_size);
ret = recv(cfd, buff, buf_size-1, 0);
cout<<"Got "<<ret<<" bytes of normal data "<<buff<<endl;
memset(buff, 0, buf_size);
ret = recv(cfd, buff, buf_size-1, MSG_OOB);
cout<<"Got "<<ret<<" bytes of normal data "<<buff<<endl;
memset(buff, 0, buf_size);
ret = recv(cfd, buff, buf_size-1, 0);
cout<<"Got "<<ret<<" bytes of normal data "<<buff<<endl;
}
close(cfd);
close(sockfd);
return 0;
}
|
1e1a392f0fbdc595f9b7a3cd6a64f72bf758a0cf
|
29bbd8d1c15d3401d01fba25b2f7d99b755dee7f
|
/problem29/problem29/main.cpp
|
da73b7e67ed80c0528d4ee7375dfdacc6214bddb
|
[] |
no_license
|
zackluckyf/Project-Euler
|
b1ad4c4e89d81bcd9ad27914d5f739494101cc53
|
478dd00a095c46a48a69486321e64b450bd97f79
|
refs/heads/master
| 2021-01-21T12:53:59.813574
| 2016-04-23T05:13:49
| 2016-04-23T05:13:49
| 47,661,130
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,343
|
cpp
|
main.cpp
|
//
// main.cpp
// problem29
//
// Created by Zack Fanning on 12/13/15.
// Copyright © 2015 Zackluckyf. All rights reserved.
//
/*
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed,
we get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
*/
#include <iostream>
#include <chrono>
#include <vector>
#include <math.h>
#include <vector>
#include <string>
#include <set>
int main(int argc, const char * argv[])
{
auto start = std::chrono::system_clock::now();
std::set<double> list;
for (double a = 2; a <= 100; a++)
{
for (double b = 2; b <= 100; b++)
{
list.insert (pow (a, b));
}
}
std::cout << list.size() << std::endl;
auto end = std::chrono::system_clock::now();
auto elapsed = end - start;
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << elapsed.count() << "ms" << '\n';
return 0;
}
|
a37ab4392fd3d3ac901e32aba93519939cc545d8
|
281c2763051432271b132499702860bd2b3f5ffa
|
/Volume_11/1172_Chebyshev’s_Theorem.cpp
|
7ff7b60d25512048d6d1d3f9c390330ba0c98798
|
[
"Apache-2.0"
] |
permissive
|
dtbinh/AOJ
|
27c95c32a829adbee37431e6e5f510723992fe45
|
f4fc75717e67b85977f5ba0ccf9e823762e44a45
|
refs/heads/master
| 2021-01-24T23:42:46.858379
| 2015-05-25T17:05:03
| 2015-05-25T17:05:03
| 36,429,163
| 1
| 0
| null | 2015-05-28T09:46:45
| 2015-05-28T09:46:44
| null |
UTF-8
|
C++
| false
| false
| 551
|
cpp
|
1172_Chebyshev’s_Theorem.cpp
|
#include <iostream>
#include <deque>
#include <cstdio>
#include <vector>
#include <string>
#include <limits>
#include <algorithm>
#include <sstream>
using namespace std;
int dp[1000001];
int main(){
fill((int*)dp,(int*)dp + 1000000,1);
dp[0] = 0;
dp[1] = 0;
for(int i=2;i*i<=1000000;i++){
if(!dp[i]) continue;
for(int j=i+i;j<=1000000;j+=i){
dp[j] = 0;
}
}
int n;
while(~scanf("%d",&n)){
if(n==0) break;
int sum = 0;
for(int i=n+1;i<=n*2;i++){
sum += dp[i];
}
printf("%dn",sum);
}
}
|
79e20394d5718abf419a5c49d16b2a2cb252ac2f
|
e6cae0446ff336189f37f983614c853a8d4f4e7f
|
/PointFighting/form_advertisement.cpp
|
8517e7b7128fad17d5c6822c1aa044c411136ba0
|
[] |
no_license
|
BarsukAlexey/xelarogi
|
de5b7e7424ade51f214e2289a29163ae0ce467b6
|
47dcee42bd4568d38b211e59bd38a540849fb8bd
|
refs/heads/master
| 2020-04-05T22:55:46.988577
| 2020-02-06T13:17:00
| 2020-02-06T13:17:00
| 46,854,119
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 418
|
cpp
|
form_advertisement.cpp
|
#include "forma_dvertisement.h"
#include "ui_form_advertisement.h"
FormAdvertisement::FormAdvertisement(QWidget *parent) :
QDialog(parent),
ui(new Ui::FormAdvertisement)
{
ui->setupUi(this);
}
FormAdvertisement::~FormAdvertisement()
{
delete ui;
}
void FormAdvertisement::setImage(QImage img)
{
img = img.scaled(size(), Qt::KeepAspectRatio);
ui->label->setPixmap(QPixmap::fromImage(img));
}
|
7fe6a891e7bf5d71444dce0f6a7288f25085cc86
|
843e995a92a6ceb1c207cc3b58c528da073562bd
|
/Orbis Toolbox/Build_Overlay.cpp
|
9c9a233395fa516efd11d3bb585ff47b2026ba7d
|
[] |
no_license
|
PSTools/Orbis-Toolbox
|
d3dd710366c91d4478c76805050dc1a0513319af
|
59caaf1d19b1787d2c67cb423dd4ea73d10c8784
|
refs/heads/main
| 2023-06-26T04:48:31.691451
| 2021-07-28T14:56:07
| 2021-07-28T14:56:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,390
|
cpp
|
Build_Overlay.cpp
|
#include "Common.h"
#include "Build_Overlay.h"
bool Build_Overlay::Draw = false;
Widget* Build_Overlay::Root_Widget = nullptr;
void Build_Overlay::Update()
{
if (Draw)
{
if (Root_Widget->Has_Child("BUILDPANEL"))
return;
//Create new Label for the build string.
Label* BuildLabel = new Label("BUILDLABEL", 20.0f, 36.0f, ORBIS_TOOLBOX_BUILDSTRING, 20, Label::fsItalic,
Label::fwBold, Label::VerticalAlignment::vCenter, Label::HorizontalAlignment::hCenter, 1.0f, 1.0f, 1.0f, 1.0f);
//Create new panel for the build Panel.
Panel* BuildPanel = new Panel("BUILDPANEL", UI::Utilities::ScreenWidth() - (BuildLabel->Get_Text_Width() + 30.0f), 20.0f, 440.0f, 100.0f,
0.92f, 0.2f, 0.16f, 0.8f, Panel::RenderingOrder::Last, UI::Utilities::Adjust_Content(Panel::Vertical, 4, 4, 4, 4));
//Append the Text to the Build Panel.
BuildPanel->Append_Child("BUILDLABEL", BuildLabel);
//Append the Label to the root widget.
Root_Widget->Append_Child("BUILDPANEL", BuildPanel);
}
else
Root_Widget->Remove_Child("BUILDPANEL");
}
void Build_Overlay::Init()
{
//Init the local widget class with our new root widget.
Root_Widget = new Widget();
Root_Widget->Instance = UI::Utilities::Get_root_Widget();
}
void Build_Overlay::Term()
{
//Remove the build panel for destruction.
Root_Widget->Remove_Child("BUILDPANEL");
//Clean up alocated classses.
delete Root_Widget;
}
|
72bc9062fed26d334fda71a67ab7a1deaec351bc
|
1b1c4c38707f500cdfdb8d37a7d9c436815a1d10
|
/main.cpp
|
b3562ab5407b7437055927695f6619547ce1f092
|
[] |
no_license
|
syt92/Equivalence-relations
|
ab8a1cca707c0811e8b79c39aaaf8cd0a9306a6f
|
46cd3c4bf7a986e84368da2e028cb54da5ce4fb0
|
refs/heads/master
| 2023-03-13T06:19:36.524525
| 2021-02-25T08:18:39
| 2021-02-25T08:18:39
| null | 0
| 0
| null | null | null | null |
BIG5
|
C++
| false
| false
| 876
|
cpp
|
main.cpp
|
#include <iostream>
#include <fstream>
#include "linked_list.h"
#include "linked_list.cpp"
using namespace std;
int main(){
int list_number = 12;
List<int> *seq = new List<int>[list_number];
int i, j, x, y;
for(int i=0; i<9; i++){
cout<<"第"<<i+1<<"次輸入"<<endl;
cout<<"請輸入相關數字1:";
cin>>x;
cout<<"請輸入相關數字2:";
cin>>y;
seq[x].PushFront(y);
seq[y].PushFront(x);
}
// for(int i = 0;i <list_number; i++){
// seq[i].PushFront(i);
// }
// for(int i=0; i<12; i++){
// equivalence(seq[i]);
// }
equivalence(seq);
cout<<endl;
// for(int i=0; i<list_number; i++){
// cout<<"----------------------"<<"List "<<i+1<<"----------------------"<<endl;
// seq[i].PrintList();
// }
system("pause");
return 0;
}
|
38a9e42d404460240dfaf72e3a8b8e4b828ee915
|
8da79a17fb9dcf7400afed2bed07d313e1823d7a
|
/libhwcservice/IControls.h
|
ff78a74e8621c8c7abb61d3bbb9e4e43321be4fb
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
intel/hwc
|
6109b7c498cffaab6309cda4b5e696dc8b4fc14d
|
65f8fac3557ee4e88fe7a5dae83ea88bafdae7dc
|
refs/heads/master
| 2023-08-29T22:49:30.063925
| 2022-08-04T22:55:55
| 2022-08-04T22:55:55
| 87,242,180
| 11
| 9
| null | 2018-07-29T20:09:18
| 2017-04-04T22:46:08
|
C++
|
UTF-8
|
C++
| false
| false
| 3,074
|
h
|
IControls.h
|
/*
// Copyright (c) 2017 Intel Corporation
//
// 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.
*/
#ifndef INTEL_UFO_HWC_ICONTROLS_H
#define INTEL_UFO_HWC_ICONTROLS_H
#include "HwcServiceApi.h"
#include <binder/IInterface.h>
#include <binder/Parcel.h>
namespace intel {
namespace ufo {
namespace hwc {
namespace services {
class IControls : public android::IInterface
{
public:
DECLARE_META_INTERFACE(Controls);
virtual status_t displaySetOverscan(uint32_t display, int32_t xoverscan, int32_t yoverscan) = 0;
virtual status_t displayGetOverscan(uint32_t display, int32_t *xoverscan, int32_t *yoverscan) = 0;
virtual status_t displaySetScaling(uint32_t display, EHwcsScalingMode eScalingMode) = 0;
virtual status_t displayGetScaling(uint32_t display, EHwcsScalingMode *eScalingMode) = 0;
virtual status_t displayEnableBlank(uint32_t display, bool blank) = 0;
virtual status_t displayRestoreDefaultColorParam(uint32_t display, EHwcsColorControl color) = 0;
virtual status_t displayGetColorParam(uint32_t display, EHwcsColorControl color, float *value, float *startvalue, float *endvalue) = 0;
virtual status_t displaySetColorParam(uint32_t display, EHwcsColorControl color, float value) = 0;
virtual android::Vector<HwcsDisplayModeInfo> displayModeGetAvailableModes(uint32_t display) = 0;
virtual status_t displayModeGetMode(uint32_t display, HwcsDisplayModeInfo *pMode) = 0;
virtual status_t displayModeSetMode(uint32_t display, const HwcsDisplayModeInfo *pMode) = 0;
virtual status_t videoEnableEncryptedSession(uint32_t sessionID, uint32_t instanceID) = 0;
virtual status_t videoDisableEncryptedSession(uint32_t sessionID) = 0;
virtual status_t videoDisableAllEncryptedSessions() = 0;
virtual bool videoIsEncryptedSessionEnabled(uint32_t sessionID, uint32_t instanceID) = 0;
virtual status_t videoSetOptimizationMode(EHwcsOptimizationMode mode) = 0;
virtual status_t mdsUpdateVideoState(int64_t videoSessionID, bool isPrepared) = 0;
virtual status_t mdsUpdateVideoFPS(int64_t videoSessionID, int32_t fps) = 0;
virtual status_t mdsUpdateInputState(bool state) = 0;
virtual status_t widiGetSingleDisplay(bool *pEnabled) = 0;
virtual status_t widiSetSingleDisplay(bool enable) = 0;
};
class BnControls : public android::BnInterface<IControls>
{
public:
virtual status_t onTransact(uint32_t, const android::Parcel&, android::Parcel*, uint32_t);
};
} // namespace services
} // namespace hwc
} // namespace ufo
} // namespace intel
#endif // INTEL_UFO_HWC_ICONTROLS_H
|
3d854aeffb5ca45e8c55e453e75df82b2ebf57ab
|
f38e1eeee8678d5b228d9340dbeab87edb6a9368
|
/TeeNew/Builder2007/Function_High.h
|
6ba59e591bb3dba0e05b59cd3b2d3e9ceaad1450
|
[] |
no_license
|
Steema/TeeChart-VCL-samples
|
383f28bfb7e6c812ed7d0db9768c5c1c64366831
|
cb26790fa9e5b4c1e50e57922697813e43a0b0bc
|
refs/heads/master
| 2021-11-17T07:02:23.895809
| 2021-09-14T07:43:04
| 2021-09-14T07:43:04
| 8,649,033
| 23
| 14
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,156
|
h
|
Function_High.h
|
//---------------------------------------------------------------------------
#ifndef Function_HighH
#define Function_HighH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "Base.h"
#include <Chart.hpp>
#include <ExtCtrls.hpp>
#include <TeEngine.hpp>
#include <TeeProcs.hpp>
#include <Series.hpp>
#include <TeeFunci.hpp>
//---------------------------------------------------------------------------
class THighForm : public TBaseForm
{
__published: // IDE-managed Components
TBarSeries *Series1;
TLineSeries *Series2;
TCheckBox *CheckBox1;
THighTeeFunction *TeeFunction1;
void __fastcall CheckBox1Click(TObject *Sender);
void __fastcall FormCreate(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall THighForm(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE THighForm *HighForm;
//---------------------------------------------------------------------------
#endif
|
7e57e85b5c577746a1682c8a0a7e31b5922ccc6f
|
ad0140e5a3fa1a8c963cb8d75f0aff29eb73446b
|
/04week/2day/07ex/src/07ex.cpp
|
1f4cc3f2055a560999ef676fba5e477c5992d5f4
|
[] |
no_license
|
greenfox-zerda-sparta/wekkew
|
a8550337287b1cbc6a358b2a37d9f7d7bf8fb5ab
|
1409e47b77dc7a1dfb8052352428f4cc3375f87c
|
refs/heads/master
| 2021-01-12T18:15:09.853176
| 2017-04-23T20:29:30
| 2017-04-23T20:29:30
| 71,350,692
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 563
|
cpp
|
07ex.cpp
|
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
int main() {
// Create a class called "Car"
// It should have a "type" property that stores the car's type in a string eg: "Mazda"
// It should have a "km" property that stores how many kilometers it have run
// The km and the type property should be a parmeter in the constructor
// It should have a method called "run" that takes a number and increments the "km" property by it
Car myCar("Volvo", 1234);
myCar.runCar(1000);
myCar.printKm();
return 0;
}
|
4a27f5e5439986a1f8241f2f6053e8bb9564a6aa
|
293d5084e57a015cca69038c9f0ee86005047bca
|
/sort-algo.cpp
|
a50c329a70efdae2e302e21c59876e4c2f9afbcc
|
[] |
no_license
|
Max-Arbuzov/research-of-sorting
|
53a15f09a09a9285ba8d44246ce0f2b1a78d7d2a
|
1415407a9e8b44b499e7bea7eff1a8f5f5416919
|
refs/heads/master
| 2023-06-28T00:54:23.859549
| 2021-07-06T07:31:50
| 2021-07-06T07:31:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,440
|
cpp
|
sort-algo.cpp
|
#if !defined(CSTRINGS) && !defined(CSTRINGS_SHORT) && !defined(CSTRINGS_LONG)
#include "opt/SortAlgo/SortAlgo-m.cpp" //sources are taken from https://github.com/chromi/sound-of-sorting/tree/master/src
//they were modified a bit - all hooks for visualisation are removed
//shellsorts are still not added
template<class T>
void insertionsort_sa(vector<T> &a) { //no in nsort
SortArray1<T> a1(a);
InsertionSort(a1);
}
template<class T>
void insertionsort2_sa(vector<T> &a) { //no in nsort
SortArray1<T> a1(a);
InsertionSort2(a1);
}
template<class T>
void bininsertionsort_sa(vector<T> &a) {
SortArray1<T> a1(a);
BinaryInsertionSort(a1);
}
template<class T>
void mergesort_sa(vector<T> &a) {
SortArray1<T> a1(a);
MergeSort(a1);
}
template<class T>
void mergesort_iter_sa(vector<T> &a) {
SortArray1<T> a1(a);
MergeSortIterative(a1);
}
template<class T>
void mergesortInPlace_sa(vector<T> &a) {
SortArray1<T> a1(a);
MergeSortInPlace(a1);
}
template<class T>
void mergesortSemiInPlace_sa(vector<T> &a) {
SortArray1<T> a1(a);
MergeSortSemiInPlace(a1);
}
template<class T>
void cataMergesort_sa(vector<T> &a) {
SortArray1<T> a1(a);
CataMergeSort(a1);
}
template<class T>
void cataMergesortStable_sa(vector<T> &a) {
SortArray1<T> a1(a);
CataMergeSortStable(a1);
}
template<class T>
void quicksort_lr_sa(vector<T> &a) {
SortArray1<T> a1(a);
QuickSortLR(a1);
}
template<class T>
void quicksort_ll_sa(vector<T> &a) {
SortArray1<T> a1(a);
QuickSortLL(a1);
}
template<class T>
void quicksort_3lr_sa(vector<T> &a) {
SortArray1<T> a1(a);
QuickSortTernaryLR(a1);
}
template<class T>
void quicksort_3ll_sa(vector<T> &a) {
SortArray1<T> a1(a);
QuickSortTernaryLL(a1);
}
template<class T>
void quicksort_2p_sa(vector<T> &a) {
SortArray1<T> a1(a);
QuickSortDualPivot(a1);
}
template<class T>
void introsort_sa(vector<T> &a) {
SortArray1<T> a1(a);
IntroSort(a1);
}
template<class T>
void introsort2_sa(vector<T> &a) {
SortArray1<T> a1(a);
IntroSortDual(a1);
}
template<class T>
void introsort2_stb_sa(vector<T> &a) {
SortArray1<T> a1(a);
IntroSortDualStable(a1);
}
template<class T>
void septenaryquick_sa(vector<T> &a) {
SortArray1<T> a1(a);
SeptenaryQuickSort(a1);
}
template<class T>
void septenaryquick_stb_sa(vector<T> &a) {
SortArray1<T> a1(a);
SeptenaryStableQuickSort(a1);
}
template<class T>
void cocktailshaker_sa(vector<T> &a) {
SortArray1<T> a1(a);
CocktailShakerSort(a1);
}
template<class T>
void gnome_sa(vector<T> &a) {
SortArray1<T> a1(a);
GnomeSort(a1);
}
template<class T>
void comb_sa(vector<T> &a) {
SortArray1<T> a1(a);
CombSort(a1);
}
template<class T>
void oddeven_sa(vector<T> &a) {
SortArray1<T> a1(a);
OddEvenSort(a1);
}
template<class T>
void heap_sa(vector<T> &a) {
SortArray1<T> a1(a);
HeapSort(a1);
}
#if defined(INT32) || defined(INT64) || defined(INT128)
template<class T>
void radix_msd_sa(vector<T> &a) {
SortArray1<T> a1(a);
RadixSortMSD(a1);
}
template<class T>
void radix_lsd_sa(vector<T> &a) {
SortArray1<T> a1(a);
RadixSortLSD(a1);
}
#endif
template<class T>
void bogo_sa(vector<T> &a) {
SortArray1<T> a1(a);
BogoSort(a1);
}
template<class T>
void bozo_sa(vector<T> &a) {
SortArray1<T> a1(a);
BozoSort(a1);
}
template<class T>
void stooge_sa(vector<T> &a) {
SortArray1<T> a1(a);
StoogeSort(a1);
}
template<class T>
void slowsort_sa(vector<T> &a) {
SortArray1<T> a1(a);
SlowSort(a1);
}
template<class T>
void cyclesort_sa(vector<T> &a) {
SortArray1<T> a1(a);
CycleSort(a1);
}
template<class T>
void bitonic_sa(vector<T> &a) {
SortArray1<T> a1(a);
BitonicSort(a1);
}
template<class T>
void bitonic_nw_sa(vector<T> &a) {
SortArray1<T> a1(a);
BitonicSortNetwork(a1);
}
template<class T>
void batcher_nw_sa(vector<T> &a) {
SortArray1<T> a1(a);
BatcherSortNetwork(a1);
}
template<class T>
void smooth_sa(vector<T> &a) {
SortArray1<T> a1(a);
SmoothSort(a1);
}
template<class T>
void splay_sa(vector<T> &a) {
SortArray1<T> a1(a);
SplaySort(a1);
}
template<class T>
void splayshake_sa(vector<T> &a) {
SortArray1<T> a1(a);
SplayShakeSort(a1);
}
template<class T>
void splaymerge_sa(vector<T> &a) {
SortArray1<T> a1(a);
SplayMergeSort(a1);
}
#endif
|
7c6ab38d79c09459952ded354483757fad3f3db0
|
f81124e4a52878ceeb3e4b85afca44431ce68af2
|
/re20_2/processor3/constant/polyMesh/pointProcAddressing
|
9ac9b033fdbfd2f97927dacbb69436a4a88f5703
|
[] |
no_license
|
chaseguy15/coe-of2
|
7f47a72987638e60fd7491ee1310ee6a153a5c10
|
dc09e8d5f172489eaa32610e08e1ee7fc665068c
|
refs/heads/master
| 2023-03-29T16:59:14.421456
| 2021-04-06T23:26:52
| 2021-04-06T23:26:52
| 355,040,336
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,414
|
pointProcAddressing
|
/*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class labelList;
location "constant/polyMesh";
object pointProcAddressing;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
1064
(
3049
3649
3674
3698
3699
3722
3723
3724
3746
3747
3748
3749
3771
3772
3773
3774
3795
3796
3797
3798
3799
3819
3820
3821
3822
3823
3824
3844
3845
3846
3847
3848
3849
3868
3869
3870
3871
3872
3873
3874
3893
3894
3895
3896
3897
3898
3899
3917
3918
3919
3920
3921
3922
3923
3924
3942
3943
3944
3945
3946
3947
3948
3949
3966
3967
3968
3969
3970
3971
3972
3973
3974
3991
3992
3993
3994
3995
3996
3997
3998
3999
4016
4017
4018
4019
4020
4021
4022
4023
4024
4041
4042
4043
4044
4045
4046
4047
4048
4049
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4274
4298
4299
4322
4323
4324
4346
4347
4348
4349
4371
4372
4373
4374
4395
4396
4397
4398
4399
4419
4420
4421
4422
4423
4424
4444
4445
4446
4447
4448
4449
4468
4469
4470
4471
4472
4473
4474
4493
4494
4495
4496
4497
4498
4499
4517
4518
4519
4520
4521
4522
4523
4524
4542
4543
4544
4545
4546
4547
4548
4549
4566
4567
4568
4569
4570
4571
4572
4573
4574
4591
4592
4593
4594
4595
4596
4597
4598
4599
4616
4617
4618
4619
4620
4621
4622
4623
4624
4641
4642
4643
4644
4645
4646
4647
4648
4649
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5041
5042
5043
5044
5045
5046
5047
5048
5049
5066
5067
5068
5069
5070
5071
5072
5073
5074
5091
5092
5093
5094
5095
5096
5097
5098
5099
5116
5117
5118
5119
5120
5121
5122
5123
5124
5142
5143
5144
5145
5146
5147
5148
5149
5167
5168
5169
5170
5171
5172
5173
5174
5193
5194
5195
5196
5197
5198
5199
5218
5219
5220
5221
5222
5223
5224
5244
5245
5246
5247
5248
5249
5269
5270
5271
5272
5273
5274
5295
5296
5297
5298
5299
5321
5322
5323
5324
5346
5347
5348
5349
5372
5373
5374
5398
5399
5424
5449
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5641
5642
5643
5644
5645
5646
5647
5648
5649
5666
5667
5668
5669
5670
5671
5672
5673
5674
5691
5692
5693
5694
5695
5696
5697
5698
5699
5716
5717
5718
5719
5720
5721
5722
5723
5724
5742
5743
5744
5745
5746
5747
5748
5749
5767
5768
5769
5770
5771
5772
5773
5774
5793
5794
5795
5796
5797
5798
5799
5818
5819
5820
5821
5822
5823
5824
5844
5845
5846
5847
5848
5849
5869
5870
5871
5872
5873
5874
5895
5896
5897
5898
5899
5921
5922
5923
5924
5946
5947
5948
5949
5972
5973
5974
5998
5999
6024
6049
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29940
29950
29960
29970
29980
29990
30000
30010
30020
30030
30040
30050
30180
30190
30200
30210
30220
30230
30240
30250
30260
30270
30280
30290
30530
30540
30550
30560
30570
30580
30590
30600
30610
30620
30630
30640
30650
30770
30780
30790
30800
30810
30820
30830
30840
30850
30860
30870
30880
30890
30900
30901
30911
30912
30922
30923
30933
30934
30944
30945
30955
30956
30966
30967
30977
30978
30988
30989
30999
31000
31010
31011
31021
31022
31032
31033
31043
31044
31054
31055
31065
31066
31076
31077
31087
31088
31098
31099
31109
31110
31120
31121
31131
31132
31142
31143
31153
31154
31164
31165
31175
31176
31186
31187
31197
31198
31208
31209
31219
31220
31230
31231
31241
31242
31252
31253
31263
31264
31274
31275
31285
31286
31296
31297
31307
31308
31318
31319
31329
31330
31340
31341
31351
31352
31362
31363
31373
31374
31384
31385
31395
31396
31406
31407
31417
31418
31428
31429
31439
31440
31450
31451
31461
31462
31472
31473
31483
31484
31494
31495
31505
31506
31516
31517
31527
31528
31538
31539
31549
31550
31560
31561
31571
31572
31582
31583
31593
31594
31604
31605
31615
31616
31626
31627
31637
31638
31648
31649
31659
31660
31670
31671
31681
31682
31692
31693
31703
31704
31714
31715
31725
31726
31736
31737
31747
31748
31758
31759
31769
31770
)
// ************************************************************************* //
|
|
1bf91885bdcd55ad09a8054661cb37af2aec331d
|
19257b8f4be8c0f6deaf02041a6ade7c44571d56
|
/IMU_Table_Arduino/Brewer/LocalMailbox.h
|
3a9fd79d7ffec9bebe0973e1606e7d7ed9766ebc
|
[] |
no_license
|
JLReitz/Banderole_Bois
|
02a811aa127f7acdd68a215a177996f56403dc47
|
d60e99a61d8f8dc64773269e14d510e88ca01287
|
refs/heads/master
| 2020-04-18T14:24:20.366789
| 2019-04-11T00:38:00
| 2019-04-11T00:38:00
| 167,587,705
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 585
|
h
|
LocalMailbox.h
|
#ifndef LOCALMAILBOX_H
#define LOCALMAILBOX_H
#include <string.h>
#include "Mailbox.h"
#include "serial.h"
//#include "src/Cereal/serial.h"
class LocalMailbox : MailBox {
public:
LocalMailbox();
void SendCereal(); //Testing
void ReadCereal();
float getPositionX();
float getPositionY();
float getPositionZ();
private:
//These Are The Ones To Be Overloaded
void RX_Specific(Letter_T & lLetter); //Overload of pure virtual RX function within Mailbox
void TX_Specific(Letter_T & lLetter); //Overload of pure virtual TX function within Mailbox
};
#endif
|
5dd483a5901eae3cce65015cf5ea40ac814d6a7a
|
9bda87aaafcd95bffbc75421833102e863dde4df
|
/src/ZLogging.cpp
|
7bdbf93f3fb0a9926d211e446c161e7688f3f5a6
|
[
"MIT"
] |
permissive
|
pbertie/esp8266-SK6812
|
ceb951e72c698623fde189b32875a5f93d206ad9
|
27d00d9c16d5f2791f64ab1d93383dc3d85d1358
|
refs/heads/main
| 2023-05-27T04:45:09.420140
| 2021-06-03T22:13:56
| 2021-06-03T22:13:56
| 320,792,421
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 735
|
cpp
|
ZLogging.cpp
|
//
// Created by paul on 30/11/2020.
//
#include "ZLogging.h"
namespace ZLogging {
#if Z_DEBUG_OUTPUT == true
void beginLogger(unsigned long baud) {
Serial.begin(baud);
}
void log(const char *str) {
div_t d = div(millis(), 1000);
Serial.print(d.quot), Serial.write('.'), Serial.print(d.rem);
Serial.print(" >>> ");
Serial.println(str);
}
void log(const String& str) {
div_t d = div(millis(), 1000);
Serial.print(d.quot), Serial.write('.'), Serial.print(d.rem);
Serial.print(" >>> ");
Serial.println(str);
}
#else
void beginLogger(unsigned long baud) {}
void log(const char *str) {}
void log(const String& str) {}
#endif
}
|
3c900428674281e4c4812a121296f5585bf35358
|
792cc0154791006a2e4fc8a3088cd090a72fac2c
|
/clvm_operator.h
|
4a20ac8049b6a949f20ba189bffb2c896181d09b
|
[] |
no_license
|
kitech/ruby-jit-qt
|
2298ee6d02780c68bd745f923e67e87649174d2c
|
a138abfcda16e0d26cd9c30f8255926adc10d2cc
|
refs/heads/master
| 2020-12-24T13:36:14.567039
| 2017-05-02T14:48:36
| 2017-05-02T14:48:36
| 26,012,744
| 16
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,270
|
h
|
clvm_operator.h
|
#ifndef CLVM_OPERATOR_H
#define CLVM_OPERATOR_H
#include <QtCore>
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/TypeBuilder.h"
class FrontEngine;
bool irop_new(llvm::LLVMContext &ctx, llvm::IRBuilder<> &builder,
llvm::Module *module, QString klass);
bool irop_call(llvm::LLVMContext &ctx, llvm::IRBuilder<> &builder,
llvm::Module *module, void *kthis, QString klass, QString method);
class IROperator
{
public:
IROperator();
~IROperator();
bool init();
public:
bool knew(QString klass); // klass new
bool kdelete(void *kthis, QString klass);
bool call(void *kthis, QString klass, QString method, QVector<QVariant> args,
QString &symbol_name);
public:
QString resolve_mangle_name(QString klass, QString method, QVector<QVariant> args);
QString resolve_return_type(QString klass, QString method,
QVector<QVariant> args, QString &mangle_name);
public:
llvm::Module *tmod = NULL; // for jit types
llvm::Module *dmod = NULL; // default irgen module
llvm::LLVMContext &ctx;
llvm::IRBuilder<> builder;
public:
FrontEngine *mfe = NULL; //
};
#endif /* CLVM_OPERATOR_H */
|
ad965472c2800a752277e1e5ae6b69fa7b1cc1e7
|
cc6f684543e01ee8044934743ce3225da50076e2
|
/canal/canal.ino
|
fd6e023bb6b274c5be3f6de86a38f4f8c072be77
|
[] |
no_license
|
RyanH1234/IOT
|
837840041ed4428ec99032bb0d6b93e09d2d070c
|
b67a5ea8c64be5b8593cbe53a66531605120f238
|
refs/heads/master
| 2023-04-27T16:41:07.782826
| 2021-05-01T04:10:57
| 2021-05-01T04:10:57
| 344,107,597
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,386
|
ino
|
canal.ino
|
#include "Wire.h"
#include <TimeLib.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include <LiquidCrystal.h>
static const int MPU_ADDR = 0x68;
const char* fileName = "DATA.CSV";
TinyGPSPlus gps;
SoftwareSerial ss(6, 5); // e.g. ensure pin 6 on arduino is linked to TX on GPS
LiquidCrystal lcd(7, 8, 9, 4, 3, 2); // rs, en, d4, d5, d6, d7
void setup()
{
Serial.begin(9600);
// set analog pins to digital
pinMode(A0, INPUT); // A0
pinMode(A1, INPUT); // A1
pinMode(A2, INPUT); // A2
// setup LCD screen
lcd.begin(16, 2);
// setup SD card
lcd.clear();
if (!SD.begin(10)) {
lcd.print(F("SD Card failed!"));
Serial.println(F("SD Card failed!"));
while (1);
} else {
lcd.print(F("SD Card done."));
Serial.println(F("SD Card done."));
}
// setup GPS
ss.begin(9600);
// setup accelerometer
Wire.begin();
Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
delay(1000);
// calibration for accelerometer
lcd.clear();
lcd.print(F("Calibrate start"));
delay(1000);
lcd.clear();
}
void loop()
{
lcd.setCursor(0, 0);
lcd.print(F("Select mode."));
if(digitalRead(14) == HIGH) {
lcd.clear();
lcd.print(F("Selected record."));
while(true) {
while (ss.available() > 0)
if (gps.encode(ss.read()))
getInfo();
if (millis() > 5000 && gps.charsProcessed() < 10)
doNotAvailable();
}
} else if(digitalRead(15) == HIGH) {
lcd.clear();
lcd.print(F("Selected reset."));
removeFile();
while(1);
} else if(digitalRead(16) == HIGH) {
lcd.clear();
lcd.print(F("Selected read."));
readFromDisk();
while(1);
}
}
void doNotAvailable() {
Serial.println(F("No GPS detected: check wiring."));
lcd.print(F("No GPS detected."));
while(true);
}
void getInfo()
{
lcd.setCursor(0,0);
lcd.print(F("Retrieving info."));
// tell MPU-6050 we want to read
Wire.beginTransmission(MPU_ADDR);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU_ADDR, 6, true);
if (gps.location.isValid() && gps.date.isValid() && gps.time.isValid()) {
setTime(gps.time.hour(), gps.time.minute(), gps.time.second(), gps.date.day(), gps.date.month(), gps.date.year());
char lat[12]; dtostrf(gps.location.lat(), 4, 6, lat);
char lng[12]; dtostrf(gps.location.lng(), 4, 6, lng);
char dataString[80];
// default +- 2g range
// please refer to - https://howtomechatronics.com/tutorials/arduino/arduino-and-mpu6050-accelerometer-and-gyroscope-tutorial/
float x_float = (Wire.read()<<8 | Wire.read()) / 16384.0;
float y_float = (Wire.read()<<8 | Wire.read()) / 16384.0;
float z_float = (Wire.read()<<8 | Wire.read()) / 16384.0;
char accelerometer_x[12]; dtostrf(x_float, 5, 2, accelerometer_x);
char accelerometer_y[12]; dtostrf(y_float, 5, 2, accelerometer_y);
char accelerometer_z[12]; dtostrf(z_float, 5, 2, accelerometer_z);
sprintf(
dataString,
"%s,%s,%lu,%s,%s,%s",
lat,
lng,
(unsigned long) now(),
accelerometer_x,
accelerometer_y,
accelerometer_z
);
File file = SD.open(fileName, FILE_WRITE);
Serial.println(dataString);
file.println(dataString);
file.close();
}
delay(1000);
return;
}
void removeFile() {
lcd.setCursor(0,0);
// filename must include extension
if(SD.exists(fileName)) {
Serial.println(F("Removing file."));
if(SD.remove(fileName)) {
lcd.print(F("Removed file."));
Serial.println(F("Successfully removed file."));
} else {
lcd.print(F("Unsuccessful"));
Serial.println(F("Unsuccessfully removed file."));
}
} else {
Serial.println(F("File doesn't exist"));
lcd.print(F("File DNE"));
}
}
void readFromDisk() {
lcd.clear();
Serial.println(SD.exists(fileName));
if(SD.exists(fileName)) {
Serial.println(F("Reading from file."));
File file = SD.open(fileName);
while (file.available()) {
Serial.write(file.read());
}
file.close();
} else {
Serial.println(F("File doesn't exist"));
lcd.print(F("File DNE"));
}
}
|
77f2373e6fb2726a35389f3f603b1ed6e333977f
|
ca7e94eb918c080fe256f0120613f1251709229f
|
/HK3/OOP/code/practice/Tuan_04/1712358_lab4_copyconstructor/1712358_lab4_copyconstructor/Tuan_04/main.cpp
|
2733a423062ede6f7b32d26b4929063fc33e13ba
|
[] |
no_license
|
minhduc2803/School
|
8965d49a0994cf1cf4a44d7268a513a92fceeb62
|
e636cdc9869312472b2ad508d0abc9f4c12892c4
|
refs/heads/master
| 2022-12-26T04:41:28.511045
| 2021-01-23T05:36:11
| 2021-01-23T05:36:11
| 245,672,910
| 0
| 0
| null | 2022-12-11T20:53:27
| 2020-03-07T17:07:39
|
C++
|
UTF-8
|
C++
| false
| false
| 1,741
|
cpp
|
main.cpp
|
#include "Point.h"
#include "LineV3.h"
#include "RectangleV3.h"
#include "DynamicArray.h"
int Point::InstanceCount = 0;
int Line::InstanceCount = 0;
int Rectangle::InstanceCount = 0;
int main()
{
Point *A = new Point(0, 0);
Point *B = new Point(1, 5);
cout << "Now we have here 2 points A(0,0) and B(1,5)";
cout << endl << endl << "Test copy Line function" << endl;
Line *d = new Line(A, B);
cout << "The line d is from A(0,0) to B(1,5)" << endl;
cout << "The length of d: " << d->Length() << endl;
cout << "the line copy of d is d1" << endl;
Line *d1 = new Line(*d);
cout << "d1: ";
d1->declare();
cout << "Total lines have been created: " << Line::InstanceCount;
cout << endl << endl << "Test copy Rectangle function" << endl;
Rectangle *H = new Rectangle(A, B);
cout << "The Rectangle H has the top left point A(0,0), the bottom right point B(1,5)" << endl;
cout << "The area of H: " << H->Area() << endl;
cout << "The rectangle copy of H is H1" << endl;
Rectangle *H1 = new Rectangle(*H);
cout << "H1 has: ";
H1->declare();
cout << "Total rectangles have been created: " << Rectangle::InstanceCount << endl;
cout << endl << "Test dynamic array copy funtion" << endl;
DynamicArray* D = new DynamicArray;
cout << "The DArray (dynamic array) D after adding 5,12,7,4,5,10" << endl;
D->PushBack(5);
D->PushBack(12);
D->PushBack(7);
D->PushBack(4);
D->PushBack(5);
D->PushBack(10);
cout << "D: ";
for (int i = 0; i < D->lenght(); i++)
{
cout << D->GetAt(i) << " ";
}
cout << endl << "The DArray E is a copy of D" << endl;
cout << "E: ";
DynamicArray* E = new DynamicArray(*D);
for (int i = 0; i < E->lenght(); i++)
{
cout << E->GetAt(i) << " ";
}
cout << endl;
system("pause");
return 0;
}
|
ab4194056c26a8a7dbb46d6a8d0b8071df36df96
|
600df3590cce1fe49b9a96e9ca5b5242884a2a70
|
/third_party/WebKit/Source/web/WebSelection.cpp
|
75f263deed98380222d0e0675e300732f20bd2f6
|
[
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] |
permissive
|
metux/chromium-suckless
|
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
|
72a05af97787001756bae2511b7985e61498c965
|
refs/heads/orig
| 2022-12-04T23:53:58.681218
| 2017-04-30T10:59:06
| 2017-04-30T23:35:58
| 89,884,931
| 5
| 3
|
BSD-3-Clause
| 2022-11-23T20:52:53
| 2017-05-01T00:09:08
| null |
UTF-8
|
C++
| false
| false
| 2,050
|
cpp
|
WebSelection.cpp
|
// Copyright 2015 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 "public/web/WebSelection.h"
#include "core/editing/SelectionType.h"
#include "core/layout/compositing/CompositedSelection.h"
namespace blink {
static WebSelectionBound getWebSelectionBound(
const CompositedSelection& selection,
bool isStart) {
DCHECK_NE(selection.type, NoSelection);
const CompositedSelectionBound& bound =
isStart ? selection.start : selection.end;
DCHECK(bound.layer);
WebSelectionBound::Type type = WebSelectionBound::Caret;
if (selection.type == RangeSelection) {
if (isStart)
type = bound.isTextDirectionRTL ? WebSelectionBound::SelectionRight
: WebSelectionBound::SelectionLeft;
else
type = bound.isTextDirectionRTL ? WebSelectionBound::SelectionLeft
: WebSelectionBound::SelectionRight;
}
WebSelectionBound result(type);
result.layerId = bound.layer->platformLayer()->id();
result.edgeTopInLayer = roundedIntPoint(bound.edgeTopInLayer);
result.edgeBottomInLayer = roundedIntPoint(bound.edgeBottomInLayer);
result.isTextDirectionRTL = bound.isTextDirectionRTL;
return result;
}
// SelectionType enums have the same values; enforced in
// AssertMatchingEnums.cpp.
WebSelection::WebSelection(const CompositedSelection& selection)
: m_selectionType(static_cast<WebSelection::SelectionType>(selection.type)),
m_start(getWebSelectionBound(selection, true)),
m_end(getWebSelectionBound(selection, false)),
m_isEditable(selection.isEditable),
m_isEmptyTextFormControl(selection.isEmptyTextFormControl) {}
WebSelection::WebSelection(const WebSelection& other)
: m_selectionType(other.m_selectionType),
m_start(other.m_start),
m_end(other.m_end),
m_isEditable(other.m_isEditable),
m_isEmptyTextFormControl(other.m_isEmptyTextFormControl) {}
} // namespace blink
|
b7d5103acea3675423423b5e14f110716246c5b0
|
dd22c07fd0a4d033f085e7bb9b3c07d70acba707
|
/tracer3/src/shader_factory.h
|
3b2d2748a3ddb9fcda649b71198b193e63be02f9
|
[] |
no_license
|
marma/tracerpp
|
5f67b607e12cb5539aaa4beebbcab8e352e44757
|
cba54961cb6de38b9c484720f1799e4ed4c9e36f
|
refs/heads/master
| 2021-05-27T14:59:51.943121
| 2013-02-03T14:19:01
| 2013-02-03T14:19:01
| 7,989,572
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 798
|
h
|
shader_factory.h
|
#ifndef __SHADER_FACTORY_H__
#define __SHADER_FACTORY_H__
#include <map>
#include <string>
#include "shader.h"
namespace tracer {
class shader_factory {
public:
// contructors & destructors
// methods
static int registerShader(shader *s) {
//std::cerr << "Registering shader '" << s->__name << "'" << std::endl;
prototypes[s->__name] = s;
return 1;
}
static shader* createShader(std::istream& in) {
std::string name;
in >> name;
shader *s = prototypes[name]->clone();
in >> *s;
//std::cerr << "Created shader '" << *s << "'" << std::endl;
return s;
}
// data members
static std::map<std::string, shader*> prototypes;
// friends
};
}
#endif
|
03ce9856d3ec0d7773eb75e398f2c8db697cd58e
|
a68a7971d0a9357fc3fab0183d356a7cb52a783f
|
/mbolge-gen.cpp
|
9259783035c9b6e76e42148eea5c93448ec08609
|
[] |
no_license
|
jmbjorndalen/Malbolge-gen
|
e95ac5babc12fc73ed518bd737e662b3ec11d042
|
0028d9dc5f9ded619ee6935580ec1a519c5c5174
|
refs/heads/master
| 2020-06-08T06:19:11.129299
| 2015-05-19T21:33:31
| 2015-05-19T21:33:31
| 35,908,823
| 5
| 2
| null | null | null | null |
ISO-8859-15
|
C++
| false
| false
| 16,285
|
cpp
|
mbolge-gen.cpp
|
/*
* Searches for a short Malboge program that prints the target string
* by using a branch-on-memory-read based interpreter: every time a
* new memory location is read, the interpreter branches off in all
* possible directions (for all possible values of that location),
* recursively searching for the shortest Malbolge program.
*
* In effect, the program recursively searches through all possible
* execution paths of a Malbolge program to find a program that prints the
* desired output.
*
* (C) John Markus Bjørndalen, 2006
*
* The interpreter code is based on the Malbolge interpreter by Ben
* Olmstead (1998).
*
* NB: If you're mad enough to want to write Malbolge programs in the
* first place, you should be cabable of finding out where the output
* files are stored and how to modify this program to search for
* anything else than "Hello" ;-)
*/
#include <string>
#include <iostream>
#include <exception>
#include <fstream>
#include <sstream>
#include "utils.h"
#include <map>
#include <stack>
#define MAX_TRIT 59049 // Max 10-trit value is 59049 = 3^10
/* ------------------- parameters to tune - begin ------------------- */
#define MAX_OSEARCH 10 // max number of new emits between output chars
#define MAX_SEARCH_ITERS 10000000 // Max number of emits in total. May not be needed any more
std::string TARGET = "Hello world";
int maxAllowedProgLen = 250; // or MAX_TRIT
/* ------------------- parameters to tune - end ------------------- */
enum MB_Exception {
BRANCH_DEPTH_EXCEPTION = 42,
ILLEGAL_ADDR_EXCEPTION,
MAX_APLEN_EXCEPTION
};
// Stages of the interpreters main loop, used in the interpreter interpreter
enum InterpreterStage {
STAGE_IFETCH = 0, // instruction fetch and check for infinity
STAGE_EXEC, // execute given instruction
STAGE_MODMEM, // modify location of memory that the Rc register currently points at
STAGE_MODINC, // modulo increment instruction and data pointer
//
STAGE_NUMSTAGES, // Number of stages
};
/* ------------------------------------------------------------ */
/*
* the xlat1 table translates one of the 8 legal positions to opcodes for malbolge.
* instead of going through that translation table, I use the positions as opcodes directly.
*
*/
enum {
OP_READ_DATA = 7, // 'j'
OP_READ_IP = 65, // 'i'
OP_ROT_RIGHT = 6, // '*'
OP_TERNARY = 29, // 'p'
OP_WRITE = 66, // '<'
OP_READ = 84, // '/'
OP_TERMINATE = 48, // 'v'
OP_NOP = 35, // 'o' - or any other translation
NUM_OPCODES = 8, // Number of operations in malbolge
};
// True if it's a legal Malbolge operation
static inline int legal_op(unsigned int op)
{
switch(op) {
case OP_READ_DATA:
case OP_READ_IP:
case OP_ROT_RIGHT:
case OP_TERNARY:
case OP_WRITE:
case OP_READ:
case OP_TERMINATE:
case OP_NOP:
return 1;
}
return 0;
}
// Decrypt/decode the contenct in the memory as a malbolge operation.
// The pos/addr in memory is a necessary part of the operation.
static inline unsigned short decode_op(unsigned short val, unsigned short pos)
{
return (val - 33 + pos) % 94;
}
// Given a legal opcode, encode it such that decode_op brings back the original opcode.
static inline unsigned short encode_op(unsigned short opcode, unsigned short pos)
{
// Need to convert to ints to get correct treatment of the expression using modulo arithmetic.
int o = opcode;
int p = pos;
return 33 + imod(o - p, 94);
}
// Used by malbolge to modify the instruction the IP(c) is currently pointing at.
static const char xlat2[] =
"5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72FhOA1C"
"B6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";
// Perform a tritwise op on the values x and y
static inline unsigned short op(unsigned short x, unsigned short y)
{
unsigned short i = 0, j;
static const unsigned short p9[5] =
{ 1, 9, 81, 729, 6561 }; // Tritvals : 1=3**0, 9=3**2, 81=3**4, 729=3**6, 6561=3**8
static const unsigned short o[9][9] =
{
{ 4, 3, 3, 1, 0, 0, 1, 0, 0 },
{ 4, 3, 5, 1, 0, 2, 1, 0, 2 },
{ 5, 5, 4, 2, 2, 1, 2, 2, 1 },
{ 4, 3, 3, 1, 0, 0, 7, 6, 6 },
{ 4, 3, 5, 1, 0, 2, 7, 6, 8 },
{ 5, 5, 4, 2, 2, 1, 8, 8, 7 },
{ 7, 6, 6, 7, 6, 6, 4, 3, 3 },
{ 7, 6, 8, 7, 6, 8, 4, 3, 5 },
{ 8, 8, 7, 8, 8, 7, 5, 5, 4 },
};
for (j = 0; j < 5; j++)
i += o [y / p9[j] % 9] [x / p9[j] % 9] * p9[j];
return (i);
}
/* ------------------------------------------------------------ */
/* I'm using an STL map to implement a sparse array. This gives me a
* 10-fold increase in total execution speed speed from saving memory
* bandwidth when I push and pop copies of the MBSearch object on the
* stack.
*/
typedef std::map<unsigned int,unsigned int> MBMemory;
class MBSearch {
public:
unsigned short Ra, Rc, Rd; // Registers
int nFetches; // Number of new fetches (that caused a branch in the search algorithm)
int curNewMem; // current position we had to create a new memory op at
int curNewOP; // which of the opcodes did we currently write
int odepth; // current depth / number of new instructions since last output
MBMemory mem; // Current content
MBMemory orig; // The program value we wrote when a read fault was triggered
int highestAddrRead; // Highest address read
InterpreterStage iStage; // Current stage of the interpreter
unsigned short instr; // used internally in the loop, currently read instruction
std::string output;
// Return values from doExec
enum {
RES_OK,
RES_INFINITE_LOOP,
RES_TRIED_INPUT,
RES_MAX_ITERS,
RES_WRITE_MISMATCH,
RES_ERROR,
RES_BRANCH_DEPTH,
};
void initExec();
int doExec();
// read and write functions for the interpreters memory
unsigned short getMem(unsigned short addr);
unsigned short storeMem(unsigned short addr, unsigned short val);
// Insert a decoded program (simplifies auto-generating malbolge programs)
int insertDecodedProg(unsigned short *prog, int len);
// Highest memory address that was accessed by the program. No need to store anything after this
int maxMemLoc() { return highestAddrRead; }
// Dump the current program to a given file, inserting NOPs in memory locations that
// were not visited.
void dumpProgram(std::string fname);
};
// MBSearch objects are pushed and popped from this stack to implement recursive execution path searches
std::stack<MBSearch*> globalStack;
/* This is a list of the sequence of Malbolge opcodes that we try in the searching interpreter.
* NB: the WRITE (=print) operation is put first, to favorise program output. In my limited testing, this
* has resulted in finding the targets faster.
*/
unsigned short MalbolgeOps[] = {
OP_WRITE, // nb
OP_READ_DATA,
OP_READ_IP,
OP_ROT_RIGHT,
OP_TERNARY,
OP_READ,
OP_TERMINATE,
OP_NOP
};
/* ------------------------------------------------------------ */
/*
* Retrieves from the memory, generating a branch exception every time a new
* location is visited.
*/
unsigned short MBSearch::getMem(unsigned short addr)
{
if (addr >= MAX_TRIT)
{
//std::cerr << "MBSearch::getMem called with addr " << addr << " with is outside legal bounds\n";
throw ILLEGAL_ADDR_EXCEPTION; // program made an illegal reference, which will not fare well with the original interpreter, so abort this branch
}
if (addr >= maxAllowedProgLen)
throw MAX_APLEN_EXCEPTION;
if (addr > highestAddrRead)
highestAddrRead = addr;
MBMemory::iterator pos = mem.find(addr);
if (pos != mem.end())
return pos->second; // already have it
// Reading a new memory location that has never been visited before.
// First, check whether we have branched out too deeply before omitting chars
++odepth;
if (odepth > MAX_OSEARCH)
throw BRANCH_DEPTH_EXCEPTION;
// Simply fill in the first possible OP, then store this object on the stack, allowing the main loop to
// pick it up again and modify it later (restarting the object with the next possible instruction).
curNewMem = addr; // keep track of addr, so main loop can modify this instruction
curNewOP = 0; // we're currently using the first one
orig[addr] = mem[addr] = encode_op(MalbolgeOps[curNewOP], addr);
++nFetches;
// Store a copy of this one on the stack
globalStack.push(new MBSearch(*this)); // default copy constructor is ok
return mem[addr];
}
unsigned short MBSearch::storeMem(unsigned short addr, unsigned short val)
{
// NB: writes to an addr always occurs after a read to the same addr, so we never have to consider path branching
// or any other recording here.
if (addr >= MAX_TRIT)
{
std::cerr << "MBSearch::storeMem called with addr " << addr << " with is outside legal bounds\n";
throw ILLEGAL_ADDR_EXCEPTION; // program made an illegal reference, which will not fare well with the original interpreter, so abort this branch
}
if (addr >= maxAllowedProgLen)
throw MAX_APLEN_EXCEPTION;
mem[addr] = val;
return 0;
}
int MBSearch::doExec()
{
const long long MAX_ITERS = 100000000LL;
long long iters;
try
{
for (iters = 0; iters < MAX_ITERS; iters++) // Guard againt infinite loops
{
switch(iStage) {
case STAGE_IFETCH: // instruction fetch
instr = getMem(Rc);
// Check for infinity: trying to execute values outside the 94-range causes an infinite loop!
if (instr < 33 || instr > 126)
return RES_INFINITE_LOOP;
break;
case STAGE_EXEC: // execute given instruction
// Decode op to NOP or one of the 8 ops.
switch (decode_op(instr, Rc))
{
case OP_READ_DATA: // read data register from current
Rd = getMem(Rd);
break;
case OP_READ_IP: // jump to addr
Rc = getMem(Rd);
break;
case OP_ROT_RIGHT: // rotate right 1, lstrit=> mstrit (3**9 = 19683)
{
unsigned short t = getMem(Rd);
Ra = t / 3 + t % 3 * 19683;
storeMem(Rd, Ra);
break;
}
case OP_TERNARY: // run ternary operator on two values
Ra = op(Ra, getMem(Rd));
storeMem(Rd, Ra);
break;
case OP_WRITE: // output accumulator as a character
{
// Checks whether this is a 'good' character, otherwise abort!
odepth = 0;
char c = (char) Ra;
if ((output.length() >= TARGET.length()) || // too long string
(c != TARGET[output.length()])) // wrong character
return RES_WRITE_MISMATCH;
output += c;
break;
}
case OP_READ: // We don't allow input from stdin in the program
return RES_TRIED_INPUT;
case OP_TERMINATE: // terminate program
return RES_OK;
case OP_NOP:
default: // Unspecified operatins correspond to NOPs in the original interpreter
break;
}
break;
case STAGE_MODMEM: { // modify location of memory that the Rc register currently points at
// Modify op at position. Note that all chars in xlat2 are in the legal range for ops: 33..126
// So, an OP will always be translated into an OP (either a NOP or the other 8 ops)
int addr = getMem(Rc);
if (addr < 33 || (addr > (95+33)))
{
// Pruning search paths that result in accesses out of bounds for xlat2
// NB: This happens very often when we search for programs, so we need to explicitly prune these
// paths as they will not execute correctly if we try them with the interpreter.
return RES_ERROR;
}
storeMem(Rc, xlat2[addr - 33]);
break;
}
case STAGE_MODINC: // modulo increment instruction and data pointer
Rc = modInc(Rc, MAX_TRIT);
Rd = modInc(Rd, MAX_TRIT);
break;
default:
std::cerr << "ERROR, interpreter interpreter with illegal stage " << iStage << std::endl;
exit(-1);
}
iStage = (InterpreterStage) modInc(iStage, STAGE_NUMSTAGES);
}
}
catch (MB_Exception e)
{
switch (e) {
case BRANCH_DEPTH_EXCEPTION:
case MAX_APLEN_EXCEPTION:
return RES_BRANCH_DEPTH;
default:
return RES_ERROR;
}
}
return RES_MAX_ITERS;
}
void MBSearch::initExec()
{
Ra = 0;
Rc = 0;
Rd = 0;
output = "";
odepth = 0;
iStage = STAGE_IFETCH;
}
void MBSearch::dumpProgram(std::string fname)
{
std::ofstream f(fname.c_str(), std::ios::trunc);
for (int i = 0; i <= highestAddrRead; i++)
{
MBMemory::iterator pos = mem.find(i);
if (pos == mem.end())
f << (char) (encode_op(OP_NOP, i)); // Since these aren't fetched, I could dump anything here
else
f << (char) orig[i];
}
}
/* ------------------------------------------------------------ */
void printCurOutput(MBSearch *cur, int newline = true)
{
std::cout << "\r output from program '" << cur->output << "' "
<< "maxMemLoc " << cur->maxMemLoc()
<< " nFetches " << cur->nFetches << " ";
if (newline)
std::cout << std::endl;
}
/* Dumps a program to a filename made from the prefix, the length of the program and the suffix .mb */
void storeProgram(std::string prefix, MBSearch * prog)
{
std::ostringstream str;
str << prefix << prog->maxMemLoc() << ".mb";
prog->dumpProgram(str.str());
}
int main(int argc, char *argv[])
{
MBSearch *mb = new MBSearch();
mb->initExec();
mb->doExec(); // get the initial execution started.. TODO: this is wrong. I'm ignoring the result of the first path, even if it could be correct (however unlikely)
MBSearch *bestProg = NULL;
std::cout << "Parameters for the generator\n";
std::cout << " TARGET '" << TARGET << "'\n";
std::cout << " MAX_OSEARCH " << MAX_OSEARCH << std::endl;
std::cout << " MAX_SEARCH_ITERS " << MAX_SEARCH_ITERS << std::endl;
std::cout << " maxAllowedProgLen " << maxAllowedProgLen << std::endl;
std::cout << " sizeof(MBSearch) " << sizeof(MBSearch) << std::endl;
std::cout << " sizeof(xlat2) " << sizeof(xlat2) << std::endl;
long long start = get_tod_usecs(); // start of search
long long prevOut = start; // previous output time
for (int i = 0; i < MAX_SEARCH_ITERS && !globalStack.empty(); i++)
{
MBSearch *cur = globalStack.top();
globalStack.pop();
if (bestProg != NULL && cur->maxMemLoc() >= bestProg->maxMemLoc())
{
// No point in continuing along a longer code path.
delete cur;
continue;
}
++cur->curNewOP;
if (cur->curNewOP >= NUM_OPCODES)
{
// exchausted our options with this branch
delete cur;
continue;
}
// First, modify the current instruction
int addr = cur->curNewMem;
cur->orig[addr] = cur->mem[addr] = encode_op(MalbolgeOps[cur->curNewOP], addr);
// prepare for next round, push a copy back on the stack before we execute with the current search path
globalStack.push(new MBSearch(*cur));
int ret = cur->doExec();
if (i % 50000 == 0)
{
// every once in a while, provide some output for the user
std::cout << "\n done with search # " << i << " DT " << timeSince(prevOut) << std::endl;
printCurOutput(cur);
prevOut = get_tod_usecs();
}
if (ret == MBSearch::RES_OK && cur->output.compare(TARGET) == 0)
{
// Found a correct program that terminates after printing the target string.
// Check if it's better than the currently best program, and store the result
if ((bestProg == NULL) || (cur->maxMemLoc() < bestProg->maxMemLoc()))
{
if (bestProg)
delete bestProg;
bestProg = new MBSearch(*cur);
std::cout << "\nSTORING new best program with score " << bestProg->maxMemLoc()
<< " after " << timeSince(start) << " seconds" << std::endl;
printCurOutput(cur);
storeProgram("/tmp/t-", bestProg);
maxAllowedProgLen = bestProg->maxMemLoc();
}
}
delete cur;
};
return 0;
}
|
8747e16d477fa6c634aea5f6e1ead029cece5bda
|
e0925ef9e7f09a2511b73c9f35b4397187207319
|
/random/greatest_power_of_2.cpp
|
8c49df323903efa509da6dcf8846d905bde686cb
|
[] |
no_license
|
ksadhu/random
|
f9c7a34d5ea7cd25a73803173bf88042c9698d33
|
804cedde2cecd654fb892049326b15cbe22ab963
|
refs/heads/master
| 2021-01-22T18:18:41.349826
| 2014-01-17T22:39:19
| 2014-01-17T22:39:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 159
|
cpp
|
greatest_power_of_2.cpp
|
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int ans=n&(-n);
cout<<"greatest power of 2 that divides n is "<<ans<<endl;
return 0;
}
|
fe01c11612b8e78830b85fc509b8c3f6de87ff63
|
4f37a2544e5c665dc5a505f009b62aed78afc455
|
/2017/sem1/seminar2/intro_unit_testing/tests/polylen_calc_unittest.cpp
|
9a80b1c5246a034c92f4c3e9e63c21e2a67a4738
|
[
"MIT"
] |
permissive
|
broniyasinnik/cpp_shad_students
|
b6ccab3c61943f4167e0621f78fde9b35af39156
|
eaff4d24d18afa08ecf8c0c52dfd3acc74e370d0
|
refs/heads/master
| 2022-10-31T13:49:31.901463
| 2022-10-13T11:08:42
| 2022-10-13T11:08:42
| 250,561,827
| 1
| 0
|
MIT
| 2020-03-27T14:53:02
| 2020-03-27T14:53:01
| null |
UTF-8
|
C++
| false
| false
| 750
|
cpp
|
polylen_calc_unittest.cpp
|
#include "gtest/gtest.h"
#include "polylen_calc.h"
TEST(GetPolylineLen, GenericPolyline)
{
// arrange
std::vector<Point> polyline{
{0., 0.},
{3., 4.},
{3., 0.}
};
// act
double res = get_polyline_len(polyline);
// assert
EXPECT_DOUBLE_EQ(9., res);
}
TEST(GetPolylineLen, EmptyPolyline)
{
std::vector<Point> polyline;
double res = get_polyline_len(polyline);
EXPECT_DOUBLE_EQ(0., res);
}
TEST(GetPolylineLen, SinglePoint)
{
std::vector<Point> polyline{
{1., 1.}
};
double res = get_polyline_len(polyline);
EXPECT_DOUBLE_EQ(0., res);
}
TEST(GetPolylineLen, RepeatingPoint)
{
std::vector<Point> polyline{
{0., 0.},
{3., 4.},
{3., 4.}
};
double res = get_polyline_len(polyline);
EXPECT_DOUBLE_EQ(5., res);
}
|
85d092f49778331ccc4d1e15542a948d53c3301e
|
8ded7c00ee602b557b31d09f8b1516597a9171aa
|
/cpp/simple.cpp
|
fa63b15a460d6ba5ccaa14cf8226ee477b5152ff
|
[] |
no_license
|
mugur9/cpptruths
|
1a8d6999392ed0d941147a5d5874dc387aecb34d
|
87204023817e263017f64060353dd793f182c558
|
refs/heads/master
| 2020-12-04T17:00:20.550500
| 2019-09-06T15:40:30
| 2019-09-06T15:40:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 287
|
cpp
|
simple.cpp
|
#include <iostream>
#include <conio.h>
using namespace std;
int i=10;
int main(void)
{
string myname;
cout << "Hello World" << endl;
cin >> myname;
cout << (void *)cout.rdbuf();
cout << "My name is: " << myname << endl;
getch();
return 0;
}
|
c774c27fb366c1b48f48c201ebb04eb85832e54e
|
93b5ad97f2a4de14d80d129a6d8cb93ba4f81ff9
|
/include/GameController.h
|
766e2a2b1940092ec0094c9ec6877ab853219bcf
|
[] |
no_license
|
alexkitching/Tiny-Tanks
|
4f5b10bd19029cde33460e6ddb480e9045189412
|
373c808625abe5785d1f79dea803665d5d6b9482
|
refs/heads/master
| 2021-09-01T12:07:51.919497
| 2017-12-26T22:23:52
| 2017-12-26T22:23:52
| 108,608,482
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,164
|
h
|
GameController.h
|
//////////////////////////////////////////////////////////////////////////
// File: <GameController.h>
// Author: <Alex Kitching>
// Date Created: <6/4/17>
// Brief: <Header file for the Game Controller class, functions and variables.>
/////////////////////////////////////////////////////////////////////////
#ifndef _GAMECONTROLLER_H_
#define _GAMECONTROLLER_H_
#include "Enumerations.h"
#include "GameStates.h"
#include "Menu.h"
#include "LevelController.h"
class GameController
{
public:
static GameController& GetGameController();
static void DestroyGameController();
void RunGameLoop();
void ChangeState(const GameState a_gsState);
void PauseGame(const int a_iReason); // a_iReason - 0, Pause, 1, Player 1 Won, 2, Player 2 Won
void PauseMenu();
private:
// Constructors
GameController(bool a_bRunning, GameState a_gsStartState);
~GameController();
// General Variables
bool bRunning;
GameState gsCurrentState;
float fDeltaTime;
// Pause Menu Variables
int iPauseReason;
float fNavDelayTime;
// Objects
Menu Menu;
LevelController* levelController;
};
#endif // ! _GAMECONTROLLER_H_
|
ef4b6b156119c16a8eb8db828fd80a5823647687
|
625fb07c453c671a44111a910ea48848667a4c21
|
/core/include/Timer.hpp
|
370c74c37b36c227928c2d264ad01d88b83d6136
|
[] |
no_license
|
Murami/nibbler
|
030dcd41b28b08d52444194a561b84c26d6cf0cf
|
f28074ddcf5e76e2315361b8e9cc999603cabc39
|
refs/heads/master
| 2022-05-16T21:28:30.189690
| 2014-04-06T20:54:45
| 2014-04-06T20:54:45
| 244,874,224
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 398
|
hpp
|
Timer.hpp
|
//
// Timer.hpp for in /home/guerot_a/rendu/cpp_nibbler/core
//
// Made by guerot_a
// Login <guerot_a@epitech.net>
//
// Started on Tue Apr 1 15:34:01 2014 guerot_a
// Last update Sat Apr 5 17:44:56 2014
//
#ifndef TIMER_HPP
#define TIMER_HPP
class Timer
{
public:
Timer();
~Timer();
int getElapsedTime();
void reset();
private:
unsigned int _time;
};
#endif /* TIMER_HPP */
|
8e3383a3c3b396d2180da70a0e3a2f0dcd48d249
|
18e3a95712203d6f81734ac5638c1bf89e85fa21
|
/Solver.cpp
|
b1559006799b9f7e8fecb5cdc3e366fcc7de6528
|
[
"MIT"
] |
permissive
|
darkedge/GT1
|
1ba926497d8b542fa98da47b810ab50a3ffb09d2
|
b9b569909c4d505f16400e8b744fba714077c952
|
refs/heads/master
| 2021-01-02T09:37:27.580345
| 2014-03-16T18:05:08
| 2014-03-16T18:05:08
| 14,470,623
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,472
|
cpp
|
Solver.cpp
|
#include "Solver.h"
#include "RigidBody.h"
#include "Transform.h"
using namespace GT1;
using glm::vec3;
using glm::mat3;
const int Solver::ITERATION_COUNT = 100;
// For the Successive Overrelaxation Method;
// @see http://mathworld.wolfram.com/SuccessiveOverrelaxationMethod.html
const float Solver::RELAXATION = 1.0f;
const float Solver::GRAVITY = 3.0f;
/************************************************************************/
/* Class vecN */
/************************************************************************/
vecN::vecN(int size) {
this->size = size;
cell = new float[size];
LoadZero();
}
vecN::vecN(const vecN& copy) {
this->size = copy.size;
cell = new float[size];
for(int i = 0; i < size; i++)
cell[i] = copy[i];
}
vecN::~vecN() {
delete[] cell;
cell = nullptr;
}
void vecN::LoadZero() {
for(int i = 0; i < size; i++)
cell[i] = 0.0f;
}
// Unchecked
void vecN::InsertVec3(int i, glm::vec3 vec) {
assert(i + 2 < size);
assert(i >= 0);
memcpy(cell + i, &vec[0], sizeof(float) * 3);
}
void vecN::Set(int i, float f) {
assert(i >= 0);
assert(i < size);
cell[i] = f;
}
vec3 vecN::GetVec3(int i) const {
assert(i + 2 < size);
assert(i >= 0);
return vec3(cell[i], cell[i + 1], cell[i + 2]);
}
/************************************************************************/
/* Class matSxN */
/************************************************************************/
matMxN::matMxN(int width, int height) {
this->width = width;
this->height = height;
cell = new float*[height];
for(int i = 0; i < height; i++)
cell[i] = new float[width];
LoadZero();
}
matMxN::matMxN(const matMxN& copy) {
this->width = copy.width;
this->height = copy.height;
cell = new float*[height];
for(int i = 0; i < height; i++)
cell[i] = new float[width];
for(int y = 0; y < height; y++)
for(int x = 0; x < width; x++)
cell[y][x] = copy[y][x];
}
matMxN::~matMxN() {
for(int i = 0; i < height; i++)
delete[] cell[i];
delete[] cell;
}
void matMxN::LoadZero() {
for(int y = 0; y < height; y++)
for(int x = 0; x < width; x++)
cell[y][x] = 0.0f;
}
void matMxN::Set(int x, int y, float val) {
assert(x < width);
assert(x >= 0);
assert(y < height);
assert(y >= 0);
cell[y][x] = val;
}
void matMxN::InsertVec3(int x, int y, vec3 vec) {
assert(x >= 0);
assert(x + 2 < width);
assert(y >= 0);
assert(y < height);
memcpy(cell[y] + x, &vec[0], sizeof(float) * 3);
}
/************************************************************************/
/* Transpose */
/************************************************************************/
matMxN Transpose(const matMxN& mat) {
matMxN result(mat.height, mat.width);
for(int x = 0; x < mat.width; x++)
for(int y = 0; y < mat.height; y++)
result[x][y] = mat[y][x];
return result;
}
/************************************************************************/
/* Class MatCSR */
/************************************************************************/
// Converts a dense matrix to a Compressed Sparse Row matrix.
matCSR::matCSR(const matMxN& mat) {
this->width = mat.width;
this->height = mat.height;
int row = 0;
int k = 0;
row_ptr.reserve(mat.height);
for(int i = 0; i < mat.height; i++) {
int sum = 0;
for(int j = 0; j < mat.width; j++) {
if(mat.cell[i][j] != 0.0f) {
val.push_back(mat.cell[i][j]);
col_ind.push_back(j);
sum++;
}
}
row_ptr.push_back(sum);
}
}
/************************************************************************/
/* Class Constraint */
/************************************************************************/
ContactConstraint::ContactConstraint(glm::vec3 normal, float distance, glm::vec3 r_A, glm::vec3 r_B, RigidBody* a, RigidBody* b) {
this->normal = normal;
this->distance = distance;
this->r_A = r_A;
this->r_B = r_B;
this->rb_A = a;
this->rb_B = b;
this->indexA = Solver::RegisterRigidBody(a);
this->indexB = Solver::RegisterRigidBody(b);
}
void ContactConstraint::FillJacobian(matMxN& mat, int row, vecN& epsilon, vecN& min, vecN& max, float dt) {
mat.InsertVec3(indexA * 6 + 0, row, -normal);
mat.InsertVec3(indexA * 6 + 3, row, -glm::cross(r_A, normal));
mat.InsertVec3(indexB * 6 + 0, row, normal);
mat.InsertVec3(indexB * 6 + 3, row, glm::cross(r_B, normal));
//epsilon->Set(row, distance * 0.00015f / dt);
epsilon[row] = 0.0f;
min[row] = 0.0f;
max[row] = FLT_MAX;
}
FrictionConstraint::FrictionConstraint(glm::vec3 tangent, float mass, glm::vec3 r_A, glm::vec3 r_B, RigidBody* rb_A, RigidBody* rb_B) {
this->tangent = tangent;
this->mass = mass;
this->r_A = r_A;
this->r_B = r_B;
this->rb_A = rb_A;
this->rb_B = rb_B;
this->indexA = Solver::RegisterRigidBody(rb_A);
this->indexB = Solver::RegisterRigidBody(rb_B);
}
void FrictionConstraint::FillJacobian(matMxN& mat, int row, vecN& epsilon, vecN& min, vecN& max, float dt) {
mat.InsertVec3(indexA * 6 + 0, row, -tangent);
mat.InsertVec3(indexA * 6 + 3, row, -glm::cross(r_A, tangent));
mat.InsertVec3(indexB * 6 + 0, row, tangent);
mat.InsertVec3(indexB * 6 + 3, row, glm::cross(r_B, tangent));
epsilon[row] = 0.0f;
min[row] = -0.5f * mass * Solver::GRAVITY;
max[row] = 0.5f * mass * Solver::GRAVITY;
}
/************************************************************************/
/* Class Solver */
/************************************************************************/
std::vector<Constraint*> Solver::constraints;
std::vector<RigidBody*> Solver::rigidBodies;
void Solver::Solve(float dt) {
// Amount of constraints
int s = (int) constraints.size();
if(s == 0) return;
// Number of rigid bodies * 6
int matrixWidth = rigidBodies.size() * 6;
// Velocity vector of all bodies
vecN V(matrixWidth);
// Inverted mass matrix
matMxN M⁻¹(matrixWidth, matrixWidth);
// External vector
vecN Fext(matrixWidth);
// Fill V, M⁻¹ and F
for (int i = 0; i < (int) rigidBodies.size(); i++) {
RigidBody* rb = rigidBodies[i];
// Velocity vector layout
// [Vx Vy Vz ωx ωy ωz [...]]
V.InsertVec3(i * 6, rb->GetVelocity());
V.InsertVec3(i * 6 + 3, rb->GetAngularVelocity());
mat3 I⁻¹ = rb->GetInvertedInertiaTensor();
// Fill matrix like this:
//
// m⁻¹ 0 0 0 0 0 ...
// 0 m⁻¹ 0 0 0 0 ...
// 0 0 m⁻¹ 0 0 0 ...
// 0 0 0 I⁻¹ I⁻¹ I⁻¹ ...
// 0 0 0 I⁻¹ I⁻¹ I⁻¹ ...
// 0 0 0 I⁻¹ I⁻¹ I⁻¹ ...
// ... ... ... ... ... ... [...]
for(int j = 0; j < 3; j++)
M⁻¹.Set(i * 6 + j, i * 6 + j, rb->GetInvertedMass());
for(int y = 0; y < 3; y++)
for(int x = 0; x < 3; x++)
M⁻¹[i * 6 + 3 + y][i * 6 + 3 + x] = I⁻¹[y][x];
// Force vector layout:
// [Fx Fy Fz τx τy τz [...]]
Fext.InsertVec3(i * 6 + 0, rb->NetForce());
Fext.InsertVec3(i * 6 + 3, rb->NetTorque());
}
// Create Jacobian
matMxN J(matrixWidth, s);
// "ϵ is the vector of force offsets
// which allows contact forces to perform work"
vecN epsilon(s);
vecN projMin(s);
vecN projMax(s);
// Let each constraint fill its row
for(int i = 0; i < s; i++)
constraints[i]->FillJacobian(J, i, epsilon, projMin, projMax, dt);
matMxN Jt = Transpose(J);
// From the slides:
// Ax = b where
// A = J * M⁻¹ * Jt
// b = ϵ / Δt - J * V1 - Δt * J * M⁻¹ * Fext
matMxN A = (J * M⁻¹) * Jt;
vecN b = (epsilon / dt) - (J * V) - dt * ((J * M⁻¹) * Fext);
// Solve Ax = b iteratively using PGS
// From this we get a Lagrange multiplier
vecN λ = SolvePGS(A, b, RELAXATION, projMin, projMax, ITERATION_COUNT);
// Multiplying the transposed Jacobian with the Lagrange multiplier
// gives us a change in momentum
vecN P = Jt * λ;
// Apply momentum
for(int i = 0; i < (int) rigidBodies.size(); i++)
rigidBodies[i]->AddMomentum(P.GetVec3(i * 6 + 0), P.GetVec3(i * 6 + 3));
}
// @see: http://stackoverflow.com/questions/11719704/projected-gauss-seidel-for-lcp
// Projected Gauss-Seidel with successive over-relaxation (SOR)
vecN Solver::SolvePGS(matMxN& A, vecN& b, float relaxation, vecN& min, vecN& max, int iterations) {
assert(A.width == b.GetSize());
matCSR csr(A);
int n = b.GetSize();
float delta;
vecN x = b;
while(iterations--) {
int i = 0;
int begin = 0, end = 0;
// for height
for(int it = 0; it < (int) csr.row_ptr.size(); it++, i++) {
// Reset delta
delta = 0.0f;
begin = end;
end += csr.row_ptr[it];
for(int j = begin; j < end; j++) {
if(csr.col_ind[j] != i) {
delta += csr.val[j] * x[csr.col_ind[j]];
}
}
delta = (b[i] - delta) / A[i][i];
// Apply relaxation
x[i] += relaxation * (delta - x[i]);
// Clamping
if(x[i] < min[i])
x[i] = min[i];
else if(x[i] > max[i])
x[i] = max[i];
}
}
return x;
}
// Puts a rigid body into the solver and returns its index
// for future reference. If the body is already listed, then
// that body's index is returned instead.
int Solver::RegisterRigidBody(RigidBody* rb) {
for(int i = 0; i < (int) rigidBodies.size(); i++)
if(rigidBodies[i] == rb) return i;
rigidBodies.push_back(rb);
return (int) (rigidBodies.size() - 1);
}
void Solver::Clear() {
rigidBodies.clear();
for(Constraint* c : constraints)
delete c;
constraints.clear();
}
|
6a4ded7e941feee23411696423f2470005511d4b
|
5d40a3ff81a0efd61bfb6066e4a2fdf99849d5ae
|
/A-32896/khachhang.h
|
4036cf1b142ea7bbb11cd7b19737eaf26754c735
|
[] |
no_license
|
nguyenquan17/quannnnnnn
|
276cb410252dc442f998d55f81264307c5e1169d
|
14fd3384ba30231ca78e216860b34a70129a3ab9
|
refs/heads/master
| 2020-05-18T19:43:45.239090
| 2019-06-23T04:55:55
| 2019-06-23T04:55:55
| 184,615,467
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 740
|
h
|
khachhang.h
|
#pragma once
#include "accout.h"
#include "BMW.h"
class khachhang: public account{
protected:
double sodu;
public:
khachhang();
khachhang(string ,int, string, double);
void setsodu(double);
double getsodu()const;
//
double themtien(double money);
double trutien(BMW *a);
};
khachhang::khachhang()
{}
khachhang::khachhang(string name, int ID, string password, double sodu):account(name, ID, password)
{
this ->sodu = sodu;
}
void khachhang::setsodu(double sodu)
{
this ->sodu = sodu;
}
double khachhang::getsodu()const
{
return this ->sodu;
}
double khachhang::themtien(double money)
{
return this ->sodu + money;
}
double khachhang::trutien(BMW *a)
{
return this ->sodu -a -> giatien();
}
|
d44d791f45eca7fe0de54725c2095720740674dc
|
464367c7180487bba74097d6b229174b53246676
|
/base/src/MemoryTraits.cc
|
33275ce7e4cb930973716b97b40b8b8e259bbee0
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
openhwgroup/force-riscv
|
5ff99fd73456b9918a954ef1d29997da2c3f2df7
|
144fb52a99cde89e73552f88c872c05d2e90b603
|
refs/heads/master
| 2023-08-08T14:03:54.749423
| 2023-06-21T02:17:30
| 2023-06-21T02:17:30
| 271,641,901
| 190
| 53
|
NOASSERTION
| 2023-09-14T01:16:08
| 2020-06-11T20:36:00
|
C++
|
UTF-8
|
C++
| false
| false
| 18,047
|
cc
|
MemoryTraits.cc
|
//
// Copyright (C) [2020] Futurewei Technologies, Inc.
//
// FORCE-RISCV is 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
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
// FIT FOR A PARTICULAR PURPOSE.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "MemoryTraits.h"
#include <algorithm>
#include <memory>
#include "Constraint.h"
#include "Log.h"
using namespace std;
/*!
\file MemoryTraits.cc
\brief Code supporting tracking memory characteristics associated with physical addresses.
*/
namespace Force {
MemoryTraitsRange::MemoryTraitsRange(const map<uint32, ConstraintSet*>& rTraitRanges, cuint64 startAddr, cuint64 endAddr)
: mTraitRanges(), mpEmptyRanges(new ConstraintSet(startAddr, endAddr)), mStartAddr(startAddr), mEndAddr(endAddr)
{
for (const auto& trait_range : rTraitRanges) {
auto trait_addresses = new ConstraintSet();
trait_range.second->CopyInRange(mStartAddr, mEndAddr, *trait_addresses);
if (not trait_addresses->IsEmpty()) {
mTraitRanges.emplace(trait_range.first, trait_addresses);
mpEmptyRanges->SubConstraintSet(*trait_addresses);
}
else {
delete trait_addresses;
}
}
}
MemoryTraitsRange::MemoryTraitsRange(const vector<uint32>& rTraitIds, cuint64 startAddr, cuint64 endAddr)
: mTraitRanges(), mpEmptyRanges(new ConstraintSet()), mStartAddr(startAddr), mEndAddr(endAddr)
{
if (not rTraitIds.empty()) {
for (uint32 trait_id : rTraitIds) {
mTraitRanges.emplace(trait_id, new ConstraintSet(startAddr, endAddr));
}
}
else {
mpEmptyRanges->AddRange(startAddr, endAddr);
}
}
MemoryTraitsRange::MemoryTraitsRange(const MemoryTraitsRange& rOther)
: mTraitRanges(), mpEmptyRanges(rOther.mpEmptyRanges->Clone()), mStartAddr(rOther.mStartAddr), mEndAddr(rOther.mEndAddr)
{
for (const auto& trait_range : rOther.mTraitRanges) {
mTraitRanges.emplace(trait_range.first, trait_range.second->Clone());
}
}
MemoryTraitsRange::~MemoryTraitsRange()
{
for (auto trait_range : mTraitRanges) {
delete trait_range.second;
}
delete mpEmptyRanges;
}
MemoryTraitsRange* MemoryTraitsRange::CreateMergedMemoryTraitsRange(const MemoryTraitsRange& rOther) const
{
if ((mStartAddr != rOther.mStartAddr) or (mEndAddr != rOther.mEndAddr)) {
LOG(fail) << "{MemoryTraitsRange::CreateMergedMemoryTraitsRange} the starting and ending addresses for both MemoryTraitsRanges must be equal" << endl;
FAIL("address-ranges-not-equal");
}
MemoryTraitsRange* merged_mem_traits_range = new MemoryTraitsRange(rOther);
for (const auto& trait_range : mTraitRanges) {
auto itr = merged_mem_traits_range->mTraitRanges.find(trait_range.first);
if (itr != merged_mem_traits_range->mTraitRanges.end()) {
itr->second->MergeConstraintSet(*(trait_range.second));
}
else {
merged_mem_traits_range->mTraitRanges.emplace(trait_range.first, trait_range.second->Clone());
}
merged_mem_traits_range->mpEmptyRanges->SubConstraintSet(*(trait_range.second));
}
return merged_mem_traits_range;
}
bool MemoryTraitsRange::IsCompatible(const MemoryTraitsRange& rOther) const
{
bool compatible = HasCompatibleTraits(rOther);
if (compatible) {
compatible = rOther.HasCompatibleTraits(*this);
}
return compatible;
}
bool MemoryTraitsRange::IsEmpty() const
{
return mTraitRanges.empty();
}
bool MemoryTraitsRange::HasCompatibleTraits(const MemoryTraitsRange& rOther) const
{
bool compatible = true;
for (const auto& trait_range : mTraitRanges) {
// Get the addresses associated with the trait in this MemoryTraitsRange, but remove addresses
// that are beyond the boundaries of the other MemoryTraitsRange
ConstraintSet trait_addresses;
trait_range.second->CopyInRange(rOther.mStartAddr, rOther.mEndAddr, trait_addresses);
// Get the addresses associated with the trait in the other MemoryTraitsRange, and combine
// them with the addresses with no associated traits
unique_ptr<ConstraintSet> other_compatible_addresses(rOther.mpEmptyRanges->Clone());
auto itr = rOther.mTraitRanges.find(trait_range.first);
if (itr != rOther.mTraitRanges.end()) {
other_compatible_addresses->MergeConstraintSet(*(itr->second));
}
// If the first set of addresses are not entirely contained in the second set of addresses,
// then there is a mismatch, and the traits are not compatible
if (not other_compatible_addresses->ContainsConstraintSet(trait_addresses)) {
compatible = false;
break;
}
}
return compatible;
}
MemoryTraits::MemoryTraits()
: mTraitRanges()
{
}
MemoryTraits::~MemoryTraits()
{
for (auto trait_range : mTraitRanges) {
delete trait_range.second;
}
}
void MemoryTraits::AddTrait(cuint32 traitId, cuint64 startAddr, cuint64 endAddr)
{
auto itr = mTraitRanges.find(traitId);
if (itr != mTraitRanges.end()) {
itr->second->AddRange(startAddr, endAddr);
}
else {
auto constr = new ConstraintSet(startAddr, endAddr);
mTraitRanges.emplace(traitId, constr);
}
}
bool MemoryTraits::HasTrait(cuint32 traitId, cuint64 startAddr, cuint64 endAddr) const
{
bool has_trait = false;
auto itr = mTraitRanges.find(traitId);
if (itr != mTraitRanges.end()) {
has_trait = itr->second->ContainsRange(startAddr, endAddr);
}
return has_trait;
}
bool MemoryTraits::HasTraitPartial(cuint32 traitId, cuint64 startAddr, cuint64 endAddr) const
{
bool has_trait_partial = false;
auto itr = mTraitRanges.find(traitId);
if (itr != mTraitRanges.end()) {
has_trait_partial = itr->second->Intersects(ConstraintSet(startAddr, endAddr));
}
return has_trait_partial;
}
const ConstraintSet* MemoryTraits::GetTraitAddressRanges(cuint32 traitId) const
{
const ConstraintSet* trait_addresses = nullptr;
auto itr = mTraitRanges.find(traitId);
if (itr != mTraitRanges.end()) {
trait_addresses = itr->second;
}
return trait_addresses;
}
MemoryTraitsRange* MemoryTraits::CreateMemoryTraitsRange(cuint64 startAddr, cuint64 endAddr) const
{
return new MemoryTraitsRange(mTraitRanges, startAddr, endAddr);
}
MemoryTraitsRegistry::MemoryTraitsRegistry()
: mTraitIds(), mExclusiveTraitIds(), mThreadTraitIds(), mNextTraitId(1)
{
}
uint32 MemoryTraitsRegistry::AddTrait(const EMemoryAttributeType trait)
{
return AddTrait(EMemoryAttributeType_to_string(trait));
}
uint32 MemoryTraitsRegistry::AddTrait(const string& rTrait)
{
uint32 trait_id = 0;
auto itr = mTraitIds.find(rTrait);
if (itr == mTraitIds.end()) {
trait_id = mNextTraitId++;
mTraitIds.emplace(rTrait, trait_id);
}
else {
LOG(fail) << "{MemoryTraitsRegistry::AddTrait} trait " << rTrait << " has already been added" << endl;
FAIL("trait-already-exists");
}
return trait_id;
}
uint32 MemoryTraitsRegistry::GetTraitId(const EMemoryAttributeType trait) const
{
return GetTraitId(EMemoryAttributeType_to_string(trait));
}
uint32 MemoryTraitsRegistry::GetTraitId(const string& rTrait) const
{
uint32 trait_id = 0;
auto itr = mTraitIds.find(rTrait);
if (itr != mTraitIds.end()) {
trait_id = itr->second;
}
return trait_id;
}
std::string MemoryTraitsRegistry::GetTraitName(cuint32 traitId) const
{
string trait_name;
auto itr = find_if(mTraitIds.cbegin(), mTraitIds.cend(),
[traitId](const pair<string, uint32>& traitIdEntry) { return (traitIdEntry.second == traitId); });
if (itr != mTraitIds.end()) {
trait_name = itr->first;
}
return trait_name;
}
uint32 MemoryTraitsRegistry::RequestTraitId(const EMemoryAttributeType trait)
{
return RequestTraitId(EMemoryAttributeType_to_string(trait));
}
uint32 MemoryTraitsRegistry::RequestTraitId(const string& rTrait)
{
uint32 trait_id = GetTraitId(rTrait);
if (trait_id == 0) {
trait_id = AddTrait(rTrait);
}
return trait_id;
}
void MemoryTraitsRegistry::AddMutuallyExclusiveTraits(const vector<EMemoryAttributeType>& rTraits)
{
set<uint32> exclusive_ids;
for (EMemoryAttributeType trait : rTraits) {
exclusive_ids.insert(RequestTraitId(trait));
}
AddMutuallyExclusiveTraitIds(exclusive_ids);
}
void MemoryTraitsRegistry::AddThreadTraits(const vector<EMemoryAttributeType>& rTraits)
{
for (EMemoryAttributeType trait : rTraits) {
mThreadTraitIds.insert(RequestTraitId(trait));
}
}
void MemoryTraitsRegistry::GetMutuallyExclusiveTraitIds(cuint32 traitId, vector<uint32>& rExclusiveIds) const
{
auto itr = mExclusiveTraitIds.find(traitId);
if (itr != mExclusiveTraitIds.end()) {
// Don't include the specified trait ID in the output
copy_if(itr->second.cbegin(), itr->second.cend(), back_inserter(rExclusiveIds),
[traitId](cuint32 exclusiveId) { return (exclusiveId != traitId); });
}
}
bool MemoryTraitsRegistry::IsThreadTrait(cuint32 threadId)
{
bool is_thread_trait = false;
auto itr = mThreadTraitIds.find(threadId);
if (itr != mThreadTraitIds.end()) {
is_thread_trait = true;
}
return is_thread_trait;
}
void MemoryTraitsRegistry::AddMutuallyExclusiveTraitIds(const set<uint32>& rExclusiveIds)
{
for (uint32 trait_id : rExclusiveIds) {
auto itr = mExclusiveTraitIds.find(trait_id);
if (itr != mExclusiveTraitIds.end()) {
copy(rExclusiveIds.cbegin(), rExclusiveIds.cend(), inserter(itr->second, itr->second.begin()));
}
else {
mExclusiveTraitIds.emplace(trait_id, rExclusiveIds);
}
}
}
MemoryTraitsManager::MemoryTraitsManager(MemoryTraitsRegistry* pMemTraitsRegistry)
: mGlobalMemTraits(), mThreadMemTraits(), mpMemTraitsRegistry(pMemTraitsRegistry)
{
}
MemoryTraitsManager::~MemoryTraitsManager()
{
for (auto mem_traits : mThreadMemTraits) {
delete mem_traits.second;
}
delete mpMemTraitsRegistry;
}
void MemoryTraitsManager::AddTrait(cuint32 threadId, const EMemoryAttributeType trait, cuint64 startAddr, cuint64 endAddr)
{
AddTrait(threadId, mpMemTraitsRegistry->RequestTraitId(trait), startAddr, endAddr);
}
void MemoryTraitsManager::AddTrait(cuint32 threadId, const string& rTrait, cuint64 startAddr, cuint64 endAddr)
{
AddTrait(threadId, mpMemTraitsRegistry->RequestTraitId(rTrait), startAddr, endAddr);
}
void MemoryTraitsManager::AddTrait(cuint32 threadId, cuint32 traitId, cuint64 startAddr, cuint64 endAddr)
{
if (mpMemTraitsRegistry->IsThreadTrait(traitId)) {
AddThreadTrait(threadId, traitId, startAddr, endAddr);
}
else {
AddGlobalTrait(traitId, startAddr, endAddr);
}
}
bool MemoryTraitsManager::HasTrait(cuint32 threadId, const EMemoryAttributeType trait, cuint64 startAddr, cuint64 endAddr) const
{
return HasTrait(threadId, EMemoryAttributeType_to_string(trait), startAddr, endAddr);
}
bool MemoryTraitsManager::HasTrait(cuint32 threadId, const string& rTrait, cuint64 startAddr, cuint64 endAddr) const
{
uint32 trait_id = mpMemTraitsRegistry->GetTraitId(rTrait);
if (trait_id == 0) {
return false;
}
bool has_trait = mGlobalMemTraits.HasTrait(trait_id, startAddr, endAddr);
if (not has_trait) {
auto itr = mThreadMemTraits.find(threadId);
if (itr != mThreadMemTraits.end()) {
has_trait = itr->second->HasTrait(trait_id, startAddr, endAddr);
}
}
return has_trait;
}
const ConstraintSet* MemoryTraitsManager::GetTraitAddressRanges(cuint32 threadId, cuint32 traitId) const
{
const ConstraintSet* trait_addresses = mGlobalMemTraits.GetTraitAddressRanges(traitId);
if (trait_addresses == nullptr) {
auto itr = mThreadMemTraits.find(threadId);
if (itr != mThreadMemTraits.end()) {
trait_addresses = itr->second->GetTraitAddressRanges(traitId);
}
}
return trait_addresses;
}
MemoryTraitsRange* MemoryTraitsManager::CreateMemoryTraitsRange(cuint32 threadId, cuint64 startAddr, cuint64 endAddr) const
{
MemoryTraitsRange* mem_traits_range = nullptr;
unique_ptr<MemoryTraitsRange> global_mem_traits_range(mGlobalMemTraits.CreateMemoryTraitsRange(startAddr, endAddr));
auto itr = mThreadMemTraits.find(threadId);
if (itr != mThreadMemTraits.end()) {
unique_ptr<MemoryTraitsRange> thread_mem_traits_range(itr->second->CreateMemoryTraitsRange(startAddr, endAddr));
mem_traits_range = global_mem_traits_range->CreateMergedMemoryTraitsRange(*thread_mem_traits_range);
}
else {
mem_traits_range = global_mem_traits_range.release();
}
return mem_traits_range;
}
void MemoryTraitsManager::AddGlobalTrait(cuint32 traitId, cuint64 startAddr, cuint64 endAddr)
{
AddToMemoryTraits(traitId, startAddr, endAddr, mGlobalMemTraits);
}
void MemoryTraitsManager::AddThreadTrait(cuint32 threadId, cuint32 traitId, cuint64 startAddr, cuint64 endAddr)
{
MemoryTraits* thread_mem_traits = nullptr;
auto itr = mThreadMemTraits.find(threadId);
if (itr != mThreadMemTraits.end()) {
thread_mem_traits = itr->second;
}
else {
thread_mem_traits = new MemoryTraits();
mThreadMemTraits.emplace(threadId, thread_mem_traits);
}
AddToMemoryTraits(traitId, startAddr, endAddr, *thread_mem_traits);
}
void MemoryTraitsManager::AddToMemoryTraits(cuint32 traitId, cuint64 startAddr, cuint64 endAddr, MemoryTraits& rMemTraits)
{
vector<uint32> exclusive_ids;
mpMemTraitsRegistry->GetMutuallyExclusiveTraitIds(traitId, exclusive_ids);
for (uint32 exclusive_id : exclusive_ids) {
if (rMemTraits.HasTraitPartial(exclusive_id, startAddr, endAddr)) {
LOG(fail) << "{MemoryTraitsManager::AddToMemoryTraits} a trait mutually exclusive with the specified trait is already associated with an address in the range 0x" << hex << startAddr << "-0x" << endAddr << endl;
FAIL("trait-conflict");
}
}
rMemTraits.AddTrait(traitId, startAddr, endAddr);
}
MemoryTraitsJson::MemoryTraitsJson(const MemoryTraitsRegistry* pMemTraitsRegistry)
: mpMemTraitsRegistry(pMemTraitsRegistry)
{
}
void MemoryTraitsJson::DumpTraits(ofstream& rOutFile, cuint32 threadId, const MemoryTraitsManager& rMemTraitsManager) const
{
map<string, const ConstraintSet*> arch_mem_attr_ranges;
map<string, const ConstraintSet*> impl_mem_attr_ranges;
CategorizeTraitRanges(rMemTraitsManager.mGlobalMemTraits.mTraitRanges, arch_mem_attr_ranges, impl_mem_attr_ranges);
auto itr = rMemTraitsManager.mThreadMemTraits.find(threadId);
if (itr != rMemTraitsManager.mThreadMemTraits.end()) {
CategorizeTraitRanges(itr->second->mTraitRanges, arch_mem_attr_ranges, impl_mem_attr_ranges);
}
DumpCategorizedTraitRanges(rOutFile, arch_mem_attr_ranges, impl_mem_attr_ranges);
}
void MemoryTraitsJson::DumpTraitsRange(ofstream& rOutFile, const MemoryTraitsRange& rMemTraitsRange) const
{
map<string, const ConstraintSet*> arch_mem_attr_ranges;
map<string, const ConstraintSet*> impl_mem_attr_ranges;
CategorizeTraitRanges(rMemTraitsRange.mTraitRanges, arch_mem_attr_ranges, impl_mem_attr_ranges);
DumpCategorizedTraitRanges(rOutFile, arch_mem_attr_ranges, impl_mem_attr_ranges);
}
void MemoryTraitsJson::CategorizeTraitRanges(const map<uint32, ConstraintSet*>& rTraitRanges, map<string, const ConstraintSet*>& rArchMemAttributeRanges, map<string, const ConstraintSet*>& rImplMemAttributeRanges) const
{
for (const auto& trait_range : rTraitRanges) {
string trait_name = mpMemTraitsRegistry->GetTraitName(trait_range.first);
bool is_arch_mem_attr = false;
try_string_to_EMemoryAttributeType(trait_name, is_arch_mem_attr);
if (is_arch_mem_attr) {
rArchMemAttributeRanges.emplace(trait_name, trait_range.second);
}
else {
rImplMemAttributeRanges.emplace(trait_name, trait_range.second);
}
}
}
void MemoryTraitsJson::DumpCategorizedTraitRanges(ofstream& rOutFile, const map<string, const ConstraintSet*>& rArchMemAttributeRanges, const map<string, const ConstraintSet*>& rImplMemAttributeRanges) const
{
rOutFile << "\"ArchMemAttributes\": ";
DumpTraitRangeCategory(rOutFile, rArchMemAttributeRanges);
rOutFile << "," << endl;
rOutFile << "\"ImplMemAttributes\": ";
DumpTraitRangeCategory(rOutFile, rImplMemAttributeRanges);
}
void MemoryTraitsJson::DumpTraitRangeCategory(ofstream& rOutFile, const map<string, const ConstraintSet*>& rTraitRanges) const
{
bool first_trait = true;
rOutFile << dec;
rOutFile << "[";
for (const auto& trait_range : rTraitRanges) {
if (not first_trait) {
rOutFile << ", ";
}
rOutFile << "{";
rOutFile << "\"Name\": \"" << trait_range.first << "\", ";
bool first_range = true;
rOutFile << "\"Ranges\": ";
rOutFile << "[";
for (Constraint* constr : trait_range.second->GetConstraints()) {
if (not first_range) {
rOutFile << ", ";
}
rOutFile << "{";
rOutFile << "\"StartPhysAddr\": " << constr->LowerBound() << ", ";
rOutFile << "\"EndPhysAddr\": " << constr->UpperBound();
rOutFile << "}";
first_range = false;
}
rOutFile << "]";
rOutFile << "}";
first_trait = false;
}
rOutFile << "]";
}
}
|
685c45c456e44feff215ba3336ace4f57ac96094
|
0212e535be3d51ca5ec8f75f6d00bd022b4b4d7b
|
/Lumos/src/Utilities/CommonUtils.cpp
|
74e362a41c1a27519ca6bfe07e659003cd0c4a63
|
[
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
heitaoflower/Lumos
|
e4be9d63677fae8b85edf63006ff3693ff994c6c
|
9b7f75c656ab89e45489de357fb029591df3dfd9
|
refs/heads/master
| 2022-04-24T14:17:14.530531
| 2020-04-26T14:31:32
| 2020-04-26T14:31:32
| 256,513,707
| 0
| 0
|
MIT
| 2020-04-27T07:51:17
| 2020-04-17T13:40:48
| null |
UTF-8
|
C++
| false
| false
| 9,330
|
cpp
|
CommonUtils.cpp
|
#include "lmpch.h"
#include "CommonUtils.h"
#include "Physics/LumosPhysicsEngine/SphereCollisionShape.h"
#include "Physics/LumosPhysicsEngine/PyramidCollisionShape.h"
#include "Physics/LumosPhysicsEngine/CuboidCollisionShape.h"
#include "Utilities/AssetsManager.h"
#include "Physics/LumosPhysicsEngine/LumosPhysicsEngine.h"
#include "Graphics/ModelLoader/ModelLoader.h"
#include "Utilities/RandomNumberGenerator.h"
#include "App/Scene.h"
#include "App/Application.h"
#include "Graphics/Camera/Camera.h"
#include "Graphics/Material.h"
#include "Graphics/Mesh.h"
#include "Graphics/Light.h"
#include "ECS/Component/Components.h"
#include "Maths/Transform.h"
namespace Lumos
{
using namespace Maths;
Maths::Vector4 CommonUtils::GenColour(float alpha)
{
Maths::Vector4 c;
c.w = alpha;
c.x = RandomNumberGenerator32::Rand(0.0f, 1.0f);
c.y = RandomNumberGenerator32::Rand(0.0f, 1.0f);
c.z = RandomNumberGenerator32::Rand(0.0f, 1.0f);
return c;
}
entt::entity CommonUtils::BuildSphereObject(
entt::registry& registry,
const std::string& name,
const Maths::Vector3& pos,
float radius,
bool physics_enabled,
float inverse_mass,
bool collidable,
const Maths::Vector4& color)
{
auto pSphere = registry.create();
registry.emplace<NameComponent>(pSphere, name);
Ref<Graphics::Mesh> sphereModel = AssetsManager::DefaultModels()->Get("Sphere");
registry.emplace<MeshComponent>(pSphere, sphereModel);
Ref<Material> matInstance = CreateRef<Material>();
MaterialProperties properties;
properties.albedoColour = color;
properties.roughnessColour = Vector4(RandomNumberGenerator32::Rand(0.0f, 1.0f));
properties.specularColour = Vector4(RandomNumberGenerator32::Rand(0.0f, 1.0f));
properties.usingAlbedoMap = 0.0f;
properties.usingRoughnessMap = 0.0f;
properties.usingNormalMap = 0.0f;
properties.usingSpecularMap = 0.0f;
matInstance->SetMaterialProperites(properties);
registry.emplace<MaterialComponent>(pSphere, matInstance);
registry.emplace<Maths::Transform>(pSphere, Maths::Matrix4::Scale(Maths::Vector3(radius, radius, radius)));
if (physics_enabled)
{
//Otherwise create a physics object, and set it's position etc
Ref<PhysicsObject3D> testPhysics = CreateRef<PhysicsObject3D>();
testPhysics->SetPosition(pos);
testPhysics->SetInverseMass(inverse_mass);
if (!collidable)
{
//Even without a collision shape, the inertia matrix for rotation has to be derived from the objects shape
testPhysics->SetInverseInertia(SphereCollisionShape(radius).BuildInverseInertia(inverse_mass));
}
else
{
testPhysics->SetCollisionShape(CreateRef<SphereCollisionShape>(radius));
testPhysics->SetInverseInertia(testPhysics->GetCollisionShape()->BuildInverseInertia(inverse_mass));
}
registry.emplace<Physics3DComponent>(pSphere, testPhysics);
}
else
{
registry.get<Maths::Transform>(pSphere).SetLocalPosition(pos);
}
return pSphere;
}
entt::entity CommonUtils::BuildCuboidObject(
entt::registry& registry,
const std::string& name,
const Maths::Vector3& pos,
const Maths::Vector3& halfdims,
bool physics_enabled,
float inverse_mass,
bool collidable,
const Maths::Vector4& color)
{
auto cube = registry.create();
registry.emplace<NameComponent>(cube, name);
Ref<Graphics::Mesh> cubeModel = AssetsManager::DefaultModels()->Get("Cube");
registry.emplace<MeshComponent>(cube, cubeModel);
auto matInstance = CreateRef<Material>();
MaterialProperties properties;
properties.albedoColour = color;
properties.roughnessColour = Vector4(RandomNumberGenerator32::Rand(0.0f, 1.0f));
properties.specularColour = Vector4(RandomNumberGenerator32::Rand(0.0f, 1.0f));
properties.emissiveColour = color;
properties.usingAlbedoMap = 0.0f;
properties.usingRoughnessMap= 0.0f;
properties.usingNormalMap = 0.0f;
properties.usingSpecularMap = 0.0f;
matInstance->SetMaterialProperites(properties);
matInstance->SetRenderFlags(0);
registry.emplace<MaterialComponent>(cube, matInstance);
registry.emplace<Maths::Transform>(cube, Maths::Matrix4::Scale(halfdims));
if (physics_enabled)
{
//Otherwise create a physics object, and set it's position etc
Ref<PhysicsObject3D> testPhysics = CreateRef<PhysicsObject3D>();
testPhysics->SetPosition(pos);
testPhysics->SetInverseMass(inverse_mass);
if (!collidable)
{
//Even without a collision shape, the inertia matrix for rotation has to be derived from the objects shape
testPhysics->SetInverseInertia(CuboidCollisionShape(halfdims).BuildInverseInertia(inverse_mass));
}
else
{
testPhysics->SetCollisionShape(CreateRef<CuboidCollisionShape>(halfdims));
testPhysics->SetInverseInertia(testPhysics->GetCollisionShape()->BuildInverseInertia(inverse_mass));
}
registry.emplace<Physics3DComponent>(cube, testPhysics);
}
else
{
registry.get<Maths::Transform>(cube).SetLocalPosition(pos);
}
return cube;
}
entt::entity CommonUtils::BuildPyramidObject(
entt::registry& registry,
const std::string& name,
const Maths::Vector3& pos,
const Maths::Vector3& halfdims,
bool physics_enabled,
float inverse_mass,
bool collidable,
const Maths::Vector4& color)
{
auto pyramid = registry.create();
registry.emplace<NameComponent>(pyramid, name);
registry.emplace<Maths::Transform>(pyramid);
auto pyramidMeshEntity = registry.create();
Ref<Graphics::Mesh> pyramidModel = AssetsManager::DefaultModels()->Get("Pyramid");
Ref<Material> matInstance = CreateRef<Material>();
MaterialProperties properties;
properties.albedoColour = color;
properties.roughnessColour = Vector4(RandomNumberGenerator32::Rand(0.0f, 1.0f));
properties.specularColour = Vector4(RandomNumberGenerator32::Rand(0.0f, 1.0f));
properties.usingAlbedoMap = 0.0f;
properties.usingRoughnessMap = 0.0f;
properties.usingNormalMap = 0.0f;
properties.usingSpecularMap = 0.0f;
matInstance->SetMaterialProperites(properties);
registry.emplace<MaterialComponent>(pyramidMeshEntity, matInstance);
registry.emplace<Maths::Transform>(pyramidMeshEntity, Maths::Quaternion(-90.0f, 0.0f,0.0f).RotationMatrix4() * Maths::Matrix4::Scale(halfdims));
registry.emplace<Hierarchy>(pyramidMeshEntity, pyramid);
registry.emplace<MeshComponent>(pyramidMeshEntity, pyramidModel);
if (physics_enabled)
{
//Otherwise create a physics object, and set it's position etc
Ref<PhysicsObject3D> testPhysics = CreateRef<PhysicsObject3D>();
testPhysics->SetPosition(pos);
testPhysics->SetInverseMass(inverse_mass);
if (!collidable)
{
//Even without a collision shape, the inertia matrix for rotation has to be derived from the objects shape
testPhysics->SetInverseInertia(PyramidCollisionShape(halfdims).BuildInverseInertia(inverse_mass));
}
else
{
testPhysics->SetCollisionShape(CreateRef<PyramidCollisionShape>(halfdims));
testPhysics->SetInverseInertia(testPhysics->GetCollisionShape()->BuildInverseInertia(inverse_mass));
}
registry.emplace<Physics3DComponent>(pyramid, testPhysics);
}
else
{
registry.get<Maths::Transform>(pyramid).SetLocalPosition(pos);
}
return pyramid;
}
void CommonUtils::AddLightCube(Scene* scene)
{
Maths::Vector4 colour = Maths::Vector4(RandomNumberGenerator32::Rand(0.0f, 1.0f),
RandomNumberGenerator32::Rand(0.0f, 1.0f),
RandomNumberGenerator32::Rand(0.0f, 1.0f),1.0f);
entt::registry& registry = scene->GetRegistry();
auto cube = CommonUtils::BuildCuboidObject(
registry,
"light Cube",
scene->GetCamera()->GetPosition(),
Maths::Vector3(0.5f, 0.5f, 0.5f),
true,
1.0f,
true,
colour);
registry.get<Physics3DComponent>(cube).GetPhysicsObject()->SetIsAtRest(true);
const float radius = RandomNumberGenerator32::Rand(1.0f, 30.0f);
const float intensity = RandomNumberGenerator32::Rand(0.0f, 2.0f);
registry.emplace<Graphics::Light>(cube, scene->GetCamera()->GetPosition(), colour, intensity, Graphics::LightType::PointLight, scene->GetCamera()->GetPosition(), radius);
}
void CommonUtils::AddSphere(Scene* scene)
{
entt::registry& registry = scene->GetRegistry();
auto sphere = CommonUtils::BuildSphereObject(
registry,
"Sphere",
scene->GetCamera()->GetPosition(),
0.5f,
true,
1.0f,
true,
Maths::Vector4(RandomNumberGenerator32::Rand(0.0f, 1.0f),
RandomNumberGenerator32::Rand(0.0f, 1.0f),
RandomNumberGenerator32::Rand(0.0f, 1.0f),
1.0f));
const Maths::Vector3 forward = -scene->GetCamera()->GetForwardDirection();
registry.get<Physics3DComponent>(sphere).GetPhysicsObject()->SetLinearVelocity(forward * 30.0f);
}
void CommonUtils::AddPyramid(Scene* scene)
{
entt::registry& registry = scene->GetRegistry();
auto sphere = CommonUtils::BuildPyramidObject(
registry,
"Pyramid",
scene->GetCamera()->GetPosition(),
Maths::Vector3(0.5f),
true,
1.0f,
true,
Maths::Vector4(RandomNumberGenerator32::Rand(0.0f, 1.0f),
RandomNumberGenerator32::Rand(0.0f, 1.0f),
RandomNumberGenerator32::Rand(0.0f, 1.0f),
1.0f));
const Maths::Vector3 forward = -scene->GetCamera()->GetForwardDirection();
registry.get<Physics3DComponent>(sphere).GetPhysicsObject()->SetLinearVelocity(forward * 30.0f);
}
}
|
caf89162887b71d04157fe7dc052ded55c7867cb
|
8b5863165a41f5b86e1918352d49daed9a75c0a7
|
/bigballer/Bot.h
|
d1bc9b51b0b7c068f2b1281a5a7a17af9767df49
|
[] |
no_license
|
jsajnani79/Mechatronics-Basketball-Robot
|
25f492130cb99c9693d41529580ea9a6308d7cf5
|
a4d280ce6226217023ef6449c2e67c81602bf6ee
|
refs/heads/master
| 2021-01-17T11:40:52.125503
| 2015-03-12T02:50:47
| 2015-03-12T02:50:47
| 30,993,171
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 626
|
h
|
Bot.h
|
/*---------------- Module Defines ---------------------------*/
#ifndef Bot_h
#define Bot_h
#include "Motor.h"
class Bot
{
public:
Bot(unsigned char enableLeft, unsigned char dirLeft, unsigned char enableRight, unsigned char dirRight);
void moveForward(int dutyCycleR, int dutyCycleL);
void moveBackward(int dutyCycleR, int dutyCycleL);
void coastStop();
void hardStop();
bool hasFinishedLeftTurn();
void turnLeft();
bool hasFinishedRightTurn();
void turnRight();
void makeSquare();
private:
Motor* leftMotor;
Motor* rightMotor;
unsigned char turnTimer;
};
#endif
|
2af2b704e0e8abb87bf557cf4217ad4f7ac7f4ef
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/admin/pchealth/helpctr/service/searchenginelib/wrapper_keyword/pchsewrap.cpp
|
bc52084d29fa15f84ba860137953e7c9fb136c58
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 7,415
|
cpp
|
pchsewrap.cpp
|
/******************************************************************************
Copyright (c) 2001 Microsoft Corporation
Module Name:
PCHSEWrap.cpp
Abstract:
Implementation of SearchEngine::WrapperKeyword
Revision History:
Davide Massarenti (dmassare) 06/01/2001
created
******************************************************************************/
#include "stdafx.h"
SearchEngine::WrapperKeyword::WrapperKeyword()
{
m_Results = NULL; // CPCHQueryResultCollection* m_Results;
// CComVariant m_vKeywords;
MPC::LocalizeString( IDS_HELPSVC_SEMGR_OWNER , m_bstrOwner , /*fMUI*/true );
MPC::LocalizeString( IDS_HELPSVC_SEMGR_KW_NAME, m_bstrName , /*fMUI*/true );
MPC::LocalizeString( IDS_HELPSVC_SEMGR_KW_DESC, m_bstrDescription, /*fMUI*/true );
m_bstrHelpURL = L"hcp://system/blurbs/keywordhelp.htm";
m_bstrID = L"9488F2E9-47AF-46da-AE4A-86372DEBD56C";
}
SearchEngine::WrapperKeyword::~WrapperKeyword()
{
Thread_Wait();
MPC::Release( m_Results );
}
HRESULT SearchEngine::WrapperKeyword::GetParamDefinition( /*[out]*/ const ParamItem_Definition*& lst, /*[out]*/ int& len )
{
static const ParamItem_Definition c_lst[] =
{
{ PARAM_BSTR, VARIANT_FALSE, VARIANT_FALSE, L"SUBSITE" , 0, L"Name of subsite to search", NULL },
{ PARAM_BOOL, VARIANT_FALSE, VARIANT_FALSE, L"UI_BULLET", 0, L"UI_BULLET" , L"true" },
};
lst = c_lst;
len = ARRAYSIZE(c_lst);
return S_OK;
}
////////////////////////////////////////////////////////////////////////////////
STDMETHODIMP SearchEngine::WrapperKeyword::Result( /*[in]*/ long lStart, /*[in]*/ long lEnd, /*[out,retval]*/ IPCHCollection* *ppC )
{
__HCP_FUNC_ENTRY( "SearchEngine::WrapperKeyword::Result" );
HRESULT hr;
MPC::SmartLock<_ThreadModel> lock( this );
CComPtr<CPCHCollection> pColl;
__MPC_PARAMCHECK_BEGIN(hr)
__MPC_PARAMCHECK_POINTER_AND_SET(ppC,NULL);
__MPC_PARAMCHECK_END();
//
// Create the Enumerator and fill it with jobs.
//
__MPC_EXIT_IF_METHOD_FAILS(hr, MPC::CreateInstance( &pColl ));
//
// If there are results
//
if(m_Results && m_bEnabled)
{
long lSize = m_Results->Size();
long lPos;
//
// Loop thru all results to generate Enumerator
//
for(lPos=0; lPos<lSize; lPos++)
{
//
// Check if they are between start and end
//
if(lPos >= lStart && lPos < lEnd)
{
CComPtr<CPCHQueryResult> obj;
if(SUCCEEDED(m_Results->GetItem( lPos, &obj )) && obj)
{
CComPtr<SearchEngine::ResultItem> pRIObj;
//
// Create the item to be inserted into the list
//
__MPC_EXIT_IF_METHOD_FAILS(hr, MPC::CreateInstance( &pRIObj ));
{
ResultItem_Data& dataDst = pRIObj->Data();
const CPCHQueryResult::Payload& dataSrc = obj->GetData();
dataDst.m_bstrTitle = dataSrc.m_bstrTitle;
dataDst.m_bstrURI = dataSrc.m_bstrTopicURL;
dataDst.m_bstrDescription = dataSrc.m_bstrDescription;
dataDst.m_lContentType = dataSrc.m_lType;
dataDst.m_dRank = -1.0;
}
//
// Add to enumerator
//
__MPC_EXIT_IF_METHOD_FAILS(hr, pColl->AddItem( pRIObj ));
}
}
}
}
__MPC_EXIT_IF_METHOD_FAILS(hr, pColl.QueryInterface( ppC ));
hr = S_OK;
__MPC_FUNC_CLEANUP;
__MPC_FUNC_EXIT(hr);
}
STDMETHODIMP SearchEngine::WrapperKeyword::get_SearchTerms( /*[out, retval]*/ VARIANT *pVal )
{
MPC::SmartLock<_ThreadModel> lock( this );
return ::VariantCopy( pVal, &m_vKeywords );
}
/////////////////////////////////////////////////////////////////////////////
// SearchEngine::WrapperKeyword : IPCHSEWrapperInternal
STDMETHODIMP SearchEngine::WrapperKeyword::AbortQuery()
{
//
// Abort any threads still running
//
Thread_Abort();
return S_OK;
}
STDMETHODIMP SearchEngine::WrapperKeyword::ExecAsyncQuery()
{
__HCP_FUNC_ENTRY( "SearchEngine::WrapperKeyword::ExecAsyncQuery" );
HRESULT hr;
//
// Create a thread to execute the query
//
__MPC_EXIT_IF_METHOD_FAILS(hr, Thread_Start( this, ExecQuery, NULL ));
hr = S_OK;
__MPC_FUNC_CLEANUP;
__MPC_FUNC_EXIT(hr);
}
////////////////////////////////////////////////////////////////////////////////
HRESULT SearchEngine::WrapperKeyword::ExecQuery()
{
__HCP_FUNC_ENTRY( "SearchEngine::WrapperKeyword::ExecQuery" );
HRESULT hr;
MPC::SmartLock<_ThreadModel> lock( this );
if(m_bEnabled)
{
CComBSTR bstrSubSite;
MPC::WStringList lst;
if(m_bstrQueryString.Length() == 0)
{
__MPC_SET_WIN32_ERROR_AND_EXIT(hr, ERROR_INVALID_DATA);
}
//
// If previous results exist, release it
//
MPC::Release( m_Results );
//
// Create a new collection
//
__MPC_EXIT_IF_METHOD_FAILS(hr, MPC::CreateInstance( &m_Results ));
//
// Check if search in subsite
//
{
VARIANT* v = GetParamInternal( L"SUBSITE" );
if(v && v->vt == VT_BSTR) bstrSubSite = v->bstrVal;
}
//
// Execute the query
//
{
Taxonomy::Settings ts( m_ths );
__MPC_EXIT_IF_METHOD_FAILS(hr, ts.KeywordSearch( m_bstrQueryString, bstrSubSite, m_Results, &lst ));
}
//
// Sort, first by Priority, then by Content Type.
//
__MPC_EXIT_IF_METHOD_FAILS(hr, m_Results->Sort( CPCHQueryResultCollection::SORT_BYPRIORITY , m_lNumResult ));
__MPC_EXIT_IF_METHOD_FAILS(hr, m_Results->Sort( CPCHQueryResultCollection::SORT_BYCONTENTTYPE ));
//
// Get the list of keywords.
//
__MPC_EXIT_IF_METHOD_FAILS(hr, MPC::ConvertListToSafeArray( lst, m_vKeywords, VT_VARIANT ));
}
hr = S_OK;
__MPC_FUNC_CLEANUP;
Thread_Abort();
//
// Call the SearchManager's OnComplete
//
(void)m_pSEMgr->WrapperComplete( hr, this );
__MPC_FUNC_EXIT(hr);
}
////////////////////////////////////////////////////////////////////////////////
HRESULT SearchEngine::WrapperItem__Create_Keyword( /*[out]*/ CComPtr<IPCHSEWrapperInternal>& pVal )
{
__HCP_FUNC_ENTRY( "SearchEngine::WrapperKeywordperItem__Create_Keyword" );
HRESULT hr;
CComPtr<SearchEngine::WrapperKeyword> pKW;
__MPC_EXIT_IF_METHOD_FAILS(hr, MPC::CreateInstance( &pKW ));
pVal = pKW;
hr = S_OK;
__HCP_FUNC_CLEANUP;
__HCP_FUNC_EXIT(hr);
}
|
8b4282f19345608ed195e39e09a7f65a0392460a
|
baf32fa1a4d3ac49b59c35f0a9226ff2a786fbc6
|
/NumberTheoryCodes/gcd.cpp
|
3455b4f0083b154769860c0dbba9672653b65a15
|
[] |
no_license
|
rajnishgeek/DSandAlgorithmPracticeSolution
|
1ef24f140a2a5d9d435b7fa36edf77074473f7b6
|
2cdd988c286f61552bd92ae995415e613d8af2fa
|
refs/heads/master
| 2023-07-14T21:15:24.016176
| 2021-09-01T18:00:04
| 2021-09-01T18:00:04
| 271,195,284
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 415
|
cpp
|
gcd.cpp
|
#include<bits/stdc++.h>
using namespace std;
int gcd(int &x, int &y)
{
int r;
if(x>y);
else
{
r=x;
x=y;
y=r;
}
int gcdvalue=0;
r=x%y;
if(r==0)
return x/y;
while(r)
{
gcdvalue=r;
x=y;
y=r;
r=x%y;
}
return gcdvalue;
}
int main()
{
int x,y;
cin>>x>>y;
cout<<gcd(x,y)<<endl;
return 0;
}
|
12ce04c2031656e4772c6da03527db8b9e747f1d
|
da715bb23c2f5fbbb541ce1499346d82f10cc8a2
|
/Library/DCmotor.h
|
b40d39c762494494051814765924ff6c28ac8758
|
[] |
no_license
|
redzenova/uRobot_Motor_Drive
|
443a4feb806c819e84b8f7187f63c4d3730ba0a3
|
44a81c467f57c09badda95a384779f73473a8c65
|
refs/heads/main
| 2023-04-01T09:50:46.149462
| 2021-04-03T20:02:11
| 2021-04-03T20:02:11
| 354,383,363
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,209
|
h
|
DCmotor.h
|
/*======================================================
| Multi-Function Motor Driver and Control Board |
| 4 CH x (DC Motor Control) |
| |
| Design by Raweeroj Thongdee |
======================================================*/
#include "Arduino.h"
#ifndef DCmotor_h
#define DCmotor_h
// Arduino pins for the PWM signals to control motor speed
#define MOTOR1_SPEED_PIN 4
#define MOTOR2_SPEED_PIN 7
#define MOTOR3_SPEED_PIN 8
#define MOTOR4_SPEED_PIN 9
// These are used to set the direction of motor
#define MOTOR1_INA_PIN 22
#define MOTOR1_INB_PIN 23
#define MOTOR2_INA_PIN 24
#define MOTOR2_INB_PIN 25
#define MOTOR3_INA_PIN 26
#define MOTOR3_INB_PIN 27
#define MOTOR4_INA_PIN 28
#define MOTOR4_INB_PIN 29
// Motor function codes
#define FORWARD 1
#define BACKWARD 2
#define BRAKE 3
#define RELEASE 4
class DCmotor
{
public:
DCmotor();
void motor(int numMotor, int command, int speed);
private:
void motor_output(int output, int high_low, int speed);
};
#endif
|
fc1826fd35b130d941f85d7651f3000ed7c677da
|
c218d50fda93a26a35dd8452b2fecde4cafdfdf1
|
/ParallelLoadBalancing/LoadBalancing/include/LoadBalancing/IMPI.h
|
d632ae15b01491e0039c3c9f644b390678cbf588
|
[] |
no_license
|
Yliana/load-balancing
|
f62928be8f4931628b7b4aaaa8d48b17a1367267
|
70aabe977cd10ae1006ddb2e2f5ea83588e32db3
|
refs/heads/master
| 2021-01-18T00:04:50.441858
| 2012-12-17T23:15:48
| 2012-12-17T23:15:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,845
|
h
|
IMPI.h
|
// ****************************************************************************
// LOAD BALANCING
// Copyright (C) 2012 Gerasimov, Smoryakova, Katerov, Afanasov, Kulakovich, Sobolev
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// ****************************************************************************
#ifndef _IMPI_H
#define _IMPI_H
#include "IMPICommunicator.h"
/**
* \class IMPI
*
* \brief MPI interface. Should be used for initialization and deinitianilization of MPI. Contains world communicator.
*/
class IMPI
{
public:
/**
* \fn virtual int IMPI::Init(int *argc, char ***argv) = 0;
*
* \brief Initialises MPI.
*
* \param [in,out] argc Program command line argument count.
* \param [in,out] argv Program command line arguments.
*
* \return .
*/
virtual int Init(int *argc, char ***argv) = 0;
/**
* \fn virtual IMPICommunicator& IMPI::World() = 0;
*
* \brief Gets the world communicator.
*
* \return The world communicator.
*/
virtual IMPICommunicator& World() = 0;
/**
* \fn virtual void IMPI::Finalize() = 0;
*
* \brief Finalizes MPI.
*/
virtual void Finalize() = 0;
};
#endif
|
8f89161d688493fb7b6a40856dec14605db248d9
|
1a9ccaa3e9edeadcae31ff81ee20ee22327b5c10
|
/gihkim/etc 1/2751.cpp
|
b9ad508c8cd0fbb96ab3eb423dccfb6be9591bfa
|
[] |
no_license
|
42somoim/42somoim3
|
e939a11f39ac5bc00f73df0bda4f5aa43bb99360
|
7b4b123e50363861475a9888ec330e4acc275fea
|
refs/heads/main
| 2023-02-22T05:29:53.472744
| 2021-01-26T10:59:02
| 2021-01-26T10:59:02
| 300,508,013
| 0
| 1
| null | 2020-11-17T11:20:54
| 2020-10-02T05:15:00
|
C++
|
UTF-8
|
C++
| false
| false
| 1,087
|
cpp
|
2751.cpp
|
#include <iostream>
using namespace std;
void change(int arry1, int arry2, int last, int *arry, int *table)
{
int tmp;
int idx_t;
idx_t = 0;
for (int idx = arry1; idx <= arry2-1; idx++)
{
for (int idx1 = arry2; idx1 <= last; idx1++)
{
if (arry[idx] > arry[idx1])
{
table[idx_t] = arry[idx1];
arry2 = idx1;
idx_t++;
}
else
{
table[idx_t] = arry[idx];
idx_t++;
}
}
}
if (arry2 < last)
{
for(int idx = arry2; idx <= last; idx++)
{
table[idx_t] = arry[idx];
idx_t++;
}
}
}
void recursive(int start, int last, int *arry, int *table)
{
if ((last == start))
return ;
recursive(start, (start+last)/2, arry, table);
recursive((start+last)/2 + 1, last, arry, table);
change(start, (start+last)/2 + 1, last, arry, table);
}
int main()
{
int n;
int *arry = nullptr;
int *table = nullptr;
cin >> n;
arry = new int[n];
table = new int[n];
for (int idx = 0; idx < n; idx++)
{
cin >> arry[idx];
}
recursive(0, n-1, arry, table);
for (int idx = 0; idx < n; idx++)
{
cout << table[idx] << endl;
}
}
|
7ac61f9b4bef1e0876117a0ce504eefa6b02db2b
|
e589fb440835151e7b9913ccad0bc1b1fc844ebe
|
/Commands/Deliver.cpp
|
8c2ba23c598db4bde48de55db9920dc43a7bb878
|
[] |
no_license
|
lsthiros/NOROBOT2013
|
15a5ccce52ed831d8ecb3f4baa91d2d151535235
|
5bdd53cd44f49e52ffc780db0543edcd5b234c45
|
refs/heads/master
| 2016-09-15T23:43:50.638703
| 2013-03-01T00:52:52
| 2013-03-01T00:52:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 232
|
cpp
|
Deliver.cpp
|
#include "Deliver.h"
#include "WPILib.h"
#include "DeliveryKick.h"
Deliver::Deliver(bool upper) {
AddSequential(new DeliveryKick(upper, true));
AddSequential(new WaitCommand(.5));
AddSequential(new DeliveryKick(upper, false));
}
|
d86fc7bda33bd8c8e5a840101944d89e5a94d486
|
cc2a953fc0a4f42f796a89d90dfb2d7703ecdb09
|
/Contest & Online Judge/SPOJ/TAP2016E.cpp
|
1516bf2b1f319c934cb2419a5b6ae0658eb5f472
|
[] |
no_license
|
210183/CP
|
107af662a3ab759760b14c6ed31fb21dc7c274e4
|
bd0b74aa2a90e12c5e5f45ac251de9d6cf69a7c6
|
refs/heads/master
| 2020-08-05T05:41:36.075888
| 2019-07-07T02:23:05
| 2019-07-07T02:23:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,044
|
cpp
|
TAP2016E.cpp
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
bool vis[N][N];
vector<int> radj[N][N];
int n, m;
bool init() {
if(scanf("%d %d",&n,&m) != 2) return 0;
for(int i = 1 ; i <= n ; i++)
for(int j = 1 ; j <= m ; j++) {
int x; scanf("%d",&x);
radj[j][x].push_back(i);
}
return 1;
}
bool solve() {
vis[1][1] = 1;
queue<pair<int,int>> q;
q.push({1,1});
while(!q.empty()) {
pair<int,int> now = q.front();
q.pop();
for(int color = 1 ; color <= m ; color++)
for(int x : radj[color][now.first])
for(int y : radj[color][now.second])
if(!vis[x][y]) {
vis[x][y] = 1;
q.push({x,y});
}
}
for(int i = 1 ; i <= n ; i++)
for(int j = 1 ; j <= n ; j++)
if(!vis[i][j])
return 0;
return 1;
}
void reset() {
for(int i = 1 ; i <= n ; i++)
for(int j = 1 ; j <= n ; j++)
vis[i][j] = 0;
for(int i = 1 ; i <= m ; i++)
for(int j = 1 ; j <= n ; j++)
radj[i][j].clear();
}
int main() {
while(init()) {
printf("%c\n", solve() ? 'S' : 'N');
reset();
}
return 0;
}
|
097943870531981d4da2534661a2893dc8963755
|
dffefb5bf3239436511af116ef3d60e377909437
|
/chapter02/EX2.03(P13).cpp
|
8817cec5adc429fde87eedb2b1596832ced9fe5c
|
[] |
no_license
|
nideng/Data_Structures
|
d9e8ae067b9fb3b0d26655de769834ec885afd17
|
7165538624f186ccfe321f7e1f855df11d0842c7
|
refs/heads/master
| 2021-05-24T09:38:50.184718
| 2020-04-25T16:10:56
| 2020-04-25T16:10:56
| 253,500,791
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 93
|
cpp
|
EX2.03(P13).cpp
|
/*
当不需频繁在存储的元素间进行插入和删除操作时,用顺序表较好
*/
|
00a58b3022f9517fa7755e49716085ca49819d8a
|
8d991e979b3eb1051998ea7dd6195011c506c0fc
|
/HackerRank/HR_Chessboard_Game_Again.cpp
|
042f56da6f13f2917cfca1de9208f3a074c1fd47
|
[] |
no_license
|
caogtaa/OJCategory
|
b33ccdfb6534f6856ab7b5668c9433c144d9f905
|
cfedef5c64c48dd2b7245b1ff795af9312e7707e
|
refs/heads/master
| 2020-09-21T13:06:25.028801
| 2020-02-05T09:05:18
| 2020-02-05T09:05:18
| 224,797,482
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,367
|
cpp
|
HR_Chessboard_Game_Again.cpp
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int G[15][15];
pair<int, int> delta[4] = {
{-2, 1},
{-2, -1},
{1, -2},
{-1, -2}
};
int Grundy(int x, int y) {
int &ret = G[x][y];
if (ret == -1) {
vector<int> S;
int nx, ny;
for (int i = 0; i < 4; ++i) {
nx = x + delta[i].first;
ny = y + delta[i].second;
if (nx < 0 || nx >= 15 || ny < 0 || ny >= 15)
continue;
S.push_back(Grundy(nx, ny));
}
S.push_back(-1);
sort(S.begin(), S.end());
ret = S.back() + 1;
for (int i = 1; i < (int)S.size(); ++i) {
if (S[i-1] + 1 < S[i]) {
ret = S[i-1] + 1;
break;
}
}
}
return ret;
}
int main() {
memset(G, -1, sizeof(G));
int T;
cin >> T;
while (T--) {
int K;
cin >> K;
int x, y;
int nimValue = 0;
for (int i = 0; i < K; ++i) {
cin >> x >> y;
nimValue ^= Grundy(x-1, y-1);
}
if (nimValue > 0) {
cout << "First" << endl;
} else {
cout << "Second" << endl;
}
}
return 0;
}
|
bbfe6c1b1b1643c43c9f6f21a5e252a87a437a2d
|
d17ea175e8047800e9e8adf78187b7e381428074
|
/src/coronaOSL/oslUtils.cpp
|
6ab4211078327dd6643130de8a10fba3b63714ac
|
[] |
no_license
|
wildparky/mayaToCorona
|
9aaa6de5d3a60735656cf9884f43be64dcefc414
|
38bd9618dac01e674899164425a289027a71aa10
|
refs/heads/master
| 2021-01-23T22:11:02.007879
| 2016-01-24T18:35:07
| 2016-01-24T18:35:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,516
|
cpp
|
oslUtils.cpp
|
#include "oslUtils.h"
#include <maya/MPlugArray.h>
#include <maya/MFnDependencyNode.h>
#include "utilities/logging.h"
#include "utilities/tools.h"
static Logging logger;
namespace OSL{
void listProjectionHistory(MObject& mobject, ProjectionUtil& util)
{
MFnDependencyNode depFn(mobject);
MStatus stat;
MPlugArray pa;
MObjectArray inputNodes;
MString dn = depFn.name();
depFn.getConnections(pa);
for (uint i = 0; i < pa.length(); i++)
{
if (pa[i].isSource())
continue;
getConnectedInNodes(pa[i], inputNodes);
}
if (mobject.hasFn(MFn::kProjection))
{
util.projectionNodes.append(mobject);
// found a projection node, clear all input plugs
// and follow only the plugs connected to the "image" plug
MPlug imagePlug = depFn.findPlug("image");
MPlugArray imgPlugs;
imagePlug.connectedTo(imgPlugs, true, false);
if (imgPlugs.length() == 0)
return;
inputNodes.clear();
for (uint i = 0; i < imgPlugs.length(); i++)
inputNodes.append(imgPlugs[i].node());
}
// no more nodes, this is my leaf node
if (inputNodes.length() == 0)
{
logger.debug(MString("node ") + depFn.name() + " has no incoming connections this is my leaf node.");
util.leafNodes.append(depFn.object());
return;
}
uniqueMObjectArray(inputNodes);
for (uint i = 0; i < inputNodes.length(); i++)
{
MString nodeName = getObjectName(inputNodes[i]);
logger.debug(MString("Checking node ") + nodeName);
listProjectionHistory(inputNodes[i], util);
}
}
}
|
401522ed2e7adcf96aaa0cd164a2d2ac02bb2e74
|
786e39df00e252ab241bd024862a43a3ad4968ac
|
/VJTI Coding Club/VCC-1/Goku And Ancient Country.cpp
|
6b27ea2ad5f4655aa39f51971ba2f63beb8d26ab
|
[] |
no_license
|
mishka1980/competitive-programming
|
51e9366c012eaa25cb48c588fdbcd089e6e5f1e0
|
c13b805a7dd9ab1228a91a3d088331ce3f0f99bf
|
refs/heads/master
| 2020-03-21T02:05:16.260788
| 2015-01-13T17:21:21
| 2015-01-13T17:21:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,001
|
cpp
|
Goku And Ancient Country.cpp
|
#include <vector>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <deque>
#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 <cstring>
#include <ctime>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
#define sz(c) (c).size()
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define tr(c, i) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define present(c, x) ((c).find(x) != (c).end())
#define cpresent(c, x) (find(all(c), x) != (c).end())
#define REP(i, n) for(int i = 0; i < (n); i++)
#define REPD(i, n) for(int i = (n)-1; i >= 0; i--)
#define FOR(i, a, b) for(int i = (a); i <= (b); i++)
#define FORD(i, a, b) for(int i = (a); i >= (b); i--)
#define mp make_pair
#define LL long long
#define CHECK(S, j) (S & (1 << j))
#define SET(S, j) (S |= (1 << j))
#define SETALL(S, j) (S = (1 << j)-1)
#define UNSET(S, j) (S &= ~(1 << j))
#define TOGGLE(S, j) (S ^= (1 << j))
#define modulo 1000000007
template<class T>string tostring(T t){stringstream s;s<<t;return s.str();}
int main(){
int T;
cin >> T;
while(T--){
int m, n;
cin >> m >> n;
char kingdom[100][100];
int level[100][100];
queue<int> q;
REP(i, m){
REP(j, n){
cin >> kingdom[i][j];
if(kingdom[i][j] >= 'A' && kingdom[i][j] <= 'Z'){
level[i][j] = 0;
q.push(i*n + j);
}else{
level[i][j] = 999999999;
}
}
}
while(!q.empty()){
int node = q.front();
q.pop();
int c = node % n;
int r = (node-c)/n;
if(r - 1 > -1){
if(level[r][c]+1 < level[r-1][c]){
kingdom[r-1][c] = kingdom[r][c];
q.push((r-1)*n+c);
level[r-1][c] = level[r][c]+1;
}else if(level[r][c]+1 == level[r-1][c]){
if(kingdom[r][c] <= kingdom[r-1][c]){
q.push((r-1)*n+c);
kingdom[r-1][c] = kingdom[r][c];
}
}
}
if(r + 1 < m){
if(level[r][c]+1 < level[r+1][c]){
kingdom[r+1][c] = kingdom[r][c];
q.push((r+1)*n+c);
level[r+1][c] = level[r][c]+1;
}else if(level[r][c]+1 == level[r+1][c]){
if(kingdom[r][c] <= kingdom[r+1][c]){
q.push((r+1)*n+c);
kingdom[r+1][c] = kingdom[r][c];
}
}
}
if(c - 1 > -1){
if(level[r][c]+1 < level[r][c-1]){
kingdom[r][c-1] = kingdom[r][c];
q.push(r*n+c-1);
level[r][c-1] = level[r][c]+1;
}else if(level[r][c]+1 == level[r][c-1]){
if(kingdom[r][c] <= kingdom[r][c-1]){
q.push(r*n+c-1);
kingdom[r][c-1] = kingdom[r][c];
}
}
}
if(c + 1 < n){
if(level[r][c]+1 < level[r][c+1]){
kingdom[r][c+1] = kingdom[r][c];
q.push(r*n+c+1);
level[r][c+1] = level[r][c]+1;
}else if(level[r][c]+1 == level[r][c+1]){
if(kingdom[r][c] <= kingdom[r][c+1]){
q.push(r*n+c+1);
kingdom[r][c+1] = kingdom[r][c];
}
}
}
}
REP(i, m){
REP(j, n){
cout << kingdom[i][j];
}
cout << endl;
}
}
return 0;
}
|
22c5912afbf4fca4c71d5032da7c86474ec8e76b
|
45b32ffcdc7ac3864c0b810b61deeee136616554
|
/GameEditor/QtGameEditor/Src/TreeWidget/MyDirModel.h
|
f6ba9d944c0562e55164a308605322e32339d865
|
[] |
no_license
|
atom-chen/Tools-2
|
812071cf6ab3e5a22fb13e4ffdc896ac03de1c68
|
0c41e12bd7526d2e7bd3328b82f11ea1b4a93938
|
refs/heads/master
| 2020-11-29T10:05:24.253448
| 2017-07-12T06:05:17
| 2017-07-12T06:05:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 166
|
h
|
MyDirModel.h
|
#ifndef __MyDirModel_H
#define __MyDirModel_H
#include "QtIncAll.h"
class MyDirModel : public QDirModel
{
public:
MyDirModel();
};
#endif // __FileSystemModel_H
|
cd74df3862d8fd3e44a8ff8794eecc679d25da5a
|
1cf5270086bd43fddf9989b282254d2464d031ea
|
/System Monitor/src/system.cpp
|
b5c6f8c7e37fdf5688f378f4587368b87fe62daa
|
[
"MIT"
] |
permissive
|
Mostafa-Alakdawi/Personal-Projects
|
2383ad6cd75d9192e775126e6601d6b8a33c441c
|
bffacda5a3aeac1ef33bb9cb19a3f5fc4368ccc7
|
refs/heads/master
| 2023-02-17T08:12:25.385856
| 2021-01-18T14:04:13
| 2021-01-18T14:04:13
| 292,952,761
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,334
|
cpp
|
system.cpp
|
#include <dirent.h>
#include <unistd.h>
#include <cstddef>
#include <set>
#include <string>
#include <vector>
#include <iostream>
#include "system.h"
#include "process.h"
#include "processor.h"
#include "linux_parser.h"
using namespace LinuxParser;
using std::set;
using std::size_t;
using std::string;
using std::vector;
// TODO: Return the system's CPU
Processor& System::Cpu() {
long user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice;
string cpuN, line;
std::ifstream stream(kProcDirectory + kStatusFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> cpuN >> user >> nice >> system >> idle;
linestream >> iowait >> irq >> softirq >> steal >> guest >> guest_nice;
}
this->cpu_.User(user);
this->cpu_.Nice(nice);
this->cpu_.System(system);
this->cpu_.Idle(idle);
this->cpu_.Iowait(iowait);
this->cpu_.Irq(irq);
this->cpu_.Softirq(softirq);
this->cpu_.Steal(steal);
this->cpu_.Guest(guest);
this->cpu_.Guest_nice(guest_nice);
this->cpu_.Utilization();
return this->cpu_;
}
// TODO: Return a container composed of the system's processes
vector<Process>& System::Processes() {
for(int pid :LinuxParser::Pids()){
Process process(pid);
this->processes_.push_back(process);
}
return this->processes_;
}
// TODO: Return the system's kernel identifier (string)
std::string System::Kernel() {
string kernel, os, version, line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
}
return kernel;
}
// TODO: Return the system's memory utilization
float System::MemoryUtilization() {
string text, line;
float MemTotal, MemFree;
std::ifstream stream(kProcDirectory + kMeminfoFilename);
while (std::getline(stream, line)) {
std::istringstream linestream(line);
linestream >> text;
if(text == "MemTotal:"){
linestream >> MemTotal;
}
else if(text == ("MemFree:")){
linestream >> MemFree;
}
else{
break;
}
}
return ((MemTotal - MemFree)/MemTotal);
}
// TODO: Return the operating system name
std::string System::OperatingSystem() {
string os,osVersion , line;
std::ifstream stream(kOSPath);
while (std::getline(stream, line)) {
if(line.find("PRETTY_NAME") != string::npos){
break;
}
}
os = line.substr(13,18);
return os;
}
// TODO: Return the number of processes actively running on the system
int System::RunningProcesses() {
string line, text;
int runningProcesses;
std::ifstream stream(kProcDirectory + kStatFilename);
while (std::getline(stream, line)) {
if(line.find("procs_running") != string::npos){
std::istringstream linestream(line);
linestream >> text >> runningProcesses;
break;
}
}
return runningProcesses;
}
// TODO: Return the total number of processes on the system
int System::TotalProcesses() {
string line, text;
int processes;
std::ifstream stream(kProcDirectory + kStatFilename);
while (std::getline(stream, line)) {
if(line.find("processes") != string::npos){
std::istringstream linestream(line);
linestream >> text >> processes;
}
}
return processes;
}
// TODO: Return the number of seconds since the system started running
long int System::UpTime() {
string line;
int upTime;
std::ifstream stream(kProcDirectory + kUptimeFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> upTime;
}
return upTime;
}
long int System::IdleTime() {
string line, text;
int idleTime;
std::ifstream stream(kProcDirectory + kUptimeFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> text >> idleTime;
}
return idleTime;
}
|
4b38e9f964ca273921a42e63244f6e30b3526a94
|
494c26f6678ecfb6d2ea67bda94da860fb29e422
|
/proj11/proj11.cpp
|
ae12abb9ec1eb1537e3b0500c3889bbd98064e10
|
[] |
no_license
|
mattmenna/CSE231
|
8d0b6cd62ecf8f280c5fe448ceeb0c5fb8299e1e
|
390d7344dcbb04148b29c9651d6f725f23074094
|
refs/heads/master
| 2020-12-02T19:22:11.292805
| 2017-07-05T15:04:25
| 2017-07-05T15:04:25
| 96,331,121
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,290
|
cpp
|
proj11.cpp
|
#include <iostream>
#include "mennamat.h"
#include "dummy.h"
#ifndef MOVE_
#define MOVE_
enum Move {Cooperate, Defect};
#endif
using namespace std;
main()
{
ostream & operator<<(ostream&, Move &m);
int rounds;
int player1Year =0;
int player2Year =0;
mennamatPlayer Player1;
dummyPlayer Player2;
Move move1=Cooperate;
Move move2=Cooperate;
cout << "How many rounds?" << endl;
cin >> rounds;
cout<<endl;
cout<<endl;
while(rounds >0)
{
move1 = Player1.move(move2);
move2 = Player2.move(move1);
cout << "First (1) Prisoner Chooses to: " << move1;
cout << "Second (2) Prisoner Chooses to: " << move2;
if(move1==move2)
{
if(move1 == Cooperate)
{
player1Year+=1;
player2Year+=1;
}
else if(move2 == Defect)
{
player1Year+=2;
player2Year+=2;
}
}//end outer if
else if(move1!=move2)
{
if(move1 == Cooperate)
player1Year+=3;
if(move2 == Cooperate)
player2Year+=3;
}//end outer if
rounds--;
cout<<endl;
} // end of while loop
cout<<"Player One got "<<player1Year<<" years in jail!"<<endl;
cout<<"Player Two got "<<player2Year<<" years in jail!"<<endl;
}
ostream & operator<<(ostream &out, Move &m)
{
if(m==0)
cout<<"Cooperate"<<endl;
if(m==1)
cout<<"Defect"<<endl;
return out;
}
|
90a15506b229ade058e46b494c04d6af1374af6a
|
d9a66840bf09cb926de8ee1749a47acc11bcdd05
|
/old/AtCoder/agc003/B.cpp
|
e2e81e9509eb18e11d9977b5bc85914b6d67a999
|
[
"Unlicense"
] |
permissive
|
not522/CompetitiveProgramming
|
b632603a49d3fec5e0815458bd2c5f355e96a84f
|
a900a09bf1057d37d08ddc7090a9c8b8f099dc74
|
refs/heads/master
| 2023-05-12T12:14:57.888297
| 2023-05-07T07:36:29
| 2023-05-07T07:36:29
| 129,512,758
| 7
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 210
|
cpp
|
B.cpp
|
#include "template.hpp"
int main() {
int64_t n, a, c = 0, res = 0;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a;
res += (a + c) / 2;
c = a ? (a + c) % 2 : 0;
}
cout << res << endl;
}
|
64388717fff3f79f9fde174517207efb6d1d3cb4
|
9b86a8dfaa30306a12fac2687236d7931950b5a3
|
/src/4_object_factory/main.cc
|
b8d957a344219f8fb70af3fb61e7cd5e43027dd7
|
[] |
no_license
|
SageWu/addon-example
|
378ecfd95c7c5b7838f3b4ec7509158ac99dea82
|
30be79f0829a185fb0694a00c326a34ed422c638
|
refs/heads/master
| 2023-03-30T08:19:22.039943
| 2021-04-10T04:03:28
| 2021-04-10T04:03:28
| 351,468,204
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 532
|
cc
|
main.cc
|
#include <node.h>
using namespace v8;
void CreateObject(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = Isolate::GetCurrent();
// 创建scope
HandleScope scope();
// 创建对象
Local<Object> obj = Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate, "msg"), info[0]);
// 返回对象
info.GetReturnValue().Set(obj);
}
// 初始化模块
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "createObject", CreateObject);
}
// 声明模块
NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
|
311a8e667bb9b27fea954250a9b81501fb4a64e5
|
fe7b1e7729a06e7294f14d3a504409dbc03ca9bb
|
/Echelle.h
|
746e59b8d4142fddd86d87a1685b3cb393330c9c
|
[] |
no_license
|
demandre/donkey-kong-cpp
|
382a440009a7092be02859c65131d80dbe441f9f
|
64b915fa38d08d16d32bd5f625c8fe6e1c364c2e
|
refs/heads/master
| 2022-11-13T00:02:36.128550
| 2020-07-10T23:00:43
| 2020-07-10T23:01:13
| 279,153,422
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 70
|
h
|
Echelle.h
|
#pragma once
#include "Entity.h"
class Echelle :
public Entity
{
};
|
e2b53802ddcee8ddf7266949b97e0559054c536a
|
f2eff57b83f7388b1df4bb660ac121d58eef2ce5
|
/cpp04/ex01/Enemy.hpp
|
6fd56ffaff6b166c6e4e751b7772cf24882ae964
|
[] |
no_license
|
janusz1995/CPP-MODULES
|
ea0acb7106c5930ba2cc9879b7507da49dd73fc7
|
43ed4e3a4a58c6bde1e11935976cc9bcb22b6c4f
|
refs/heads/master
| 2023-03-11T20:25:16.602332
| 2021-03-01T11:09:20
| 2021-03-01T11:09:20
| 343,384,262
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 349
|
hpp
|
Enemy.hpp
|
#ifndef ENEMY_HPP
# define ENEMY_HPP
# include <iostream>
class Enemy{
protected:
int hp;
std::string type;
Enemy();
public:
Enemy(int hp, std::string const &type);
Enemy(Enemy const &enemy);
int getHp() const;
std::string getType() const;
virtual void takeDamage(int);
Enemy& operator=(Enemy const &enemy);
virtual ~Enemy();
};
#endif
|
a55c147c1b6a7c07a7a8226a0f25830c27b3e25d
|
479a9c76b19b84d6cde69305828031cd2531aa56
|
/rest/rest_request_router.cc
|
3a2371cd949e5dfdc9d93973d1aadf4783ef72b5
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
mldbai/mldb
|
d36801bd99dd3f82d7557cd0f438b0121f63f22c
|
19bc4bc92a41ee8ad4eab0979dffd9c985d95758
|
refs/heads/master
| 2023-09-03T22:59:11.621839
| 2022-12-30T18:42:24
| 2022-12-30T18:42:24
| 47,634,692
| 701
| 107
|
Apache-2.0
| 2023-02-10T23:08:05
| 2015-12-08T16:34:16
|
C++
|
UTF-8
|
C++
| false
| false
| 30,778
|
cc
|
rest_request_router.cc
|
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
/* rest_request_router.cc
Jeremy Barnes, 15 November 2012
Copyright (c) 2012 mldb.ai inc. All rights reserved.
*/
#include "mldb/types/url.h"
#include "mldb/rest/rest_request_router.h"
#include "mldb/utils/vector_utils.h"
#include "mldb/arch/exception_handler.h"
#include "mldb/utils/set_utils.h"
#include "mldb/utils/environment.h"
#include "mldb/types/db/file_read_buffer.h"
#include "mldb/utils/string_functions.h"
#include "mldb/base/less.h"
#include "mldb/types/value_description.h"
using namespace std;
namespace MLDB {
/*****************************************************************************/
/* PATH SPEC */
/*****************************************************************************/
PathSpec::
PathSpec()
: type(NONE)
{
}
PathSpec::
PathSpec(const std::string & fullPath)
: type(STRING), path(fullPath)
{
}
PathSpec::
PathSpec(const Utf8String & fullPath)
: type(STRING), path(fullPath)
{
}
PathSpec::
PathSpec(const char * fullPath)
: type(STRING), path(fullPath)
{
}
PathSpec::
PathSpec(Regex rex)
: type(REGEX),
path(rex.surface()),
rex(std::move(rex))
{
}
void
PathSpec::
getHelp(Json::Value & result) const
{
switch (type) {
case STRING:
result["path"] = path;
break;
case REGEX: {
Json::Value & v = result["path"];
v["regex"] = path;
v["desc"] = desc;
break;
}
default:
throw AnnotatedException(400, "unknown path parameter");
}
}
Utf8String
PathSpec::
getPathDesc() const
{
if (!desc.empty())
return desc;
return path;
}
int
PathSpec::
numCapturedElements() const
{
switch (type) {
case NONE: return 0;
case STRING: return 1;
case REGEX: return rex.mark_count() + 1;
default:
throw AnnotatedException(400, "unknown mark count");
}
}
bool
PathSpec::
operator == (const PathSpec & other) const
{
return path == other.path;
}
bool
PathSpec::
operator != (const PathSpec & other) const
{
return ! operator == (other);
}
bool
PathSpec::
operator < (const PathSpec & other) const
{
return path < other.path;
}
PathSpec
Rx(const Utf8String & regexString, const Utf8String & desc)
{
Regex rex(regexString);
PathSpec result(rex);
result.desc = desc;
return result;
}
std::ostream & operator << (std::ostream & stream, const PathSpec & path)
{
switch (path.type) {
case PathSpec::STRING: return stream << path.path;
case PathSpec::REGEX: return stream << path.rex.surface();
case PathSpec::NONE:
default:
return stream << "none";
}
}
bool
RequestParamFilter::
operator < (const RequestParamFilter & other) const
{
return MLDB::less_all(location, other.location,
param, other.param,
value, other.value);
}
/*****************************************************************************/
/* REQUEST FILTER */
/*****************************************************************************/
/** Filter for a REST request by method, etc. */
RequestFilter::
RequestFilter()
{
}
RequestFilter::
RequestFilter(const std::string & verb)
{
verbs.insert(verb);
parseVerbs();
}
RequestFilter::
RequestFilter(const char * verb)
{
verbs.insert(verb);
parseVerbs();
}
RequestFilter::
RequestFilter(std::set<std::string> verbs)
: verbs(std::move(verbs))
{
parseVerbs();
}
RequestFilter::
RequestFilter(const std::initializer_list<std::string> & verbs)
: verbs(verbs)
{
parseVerbs();
}
void
RequestFilter::
parseVerbs()
{
std::set<std::string> newVerbs;
for (auto & v: verbs) {
auto i = v.find('=');
if (i == std::string::npos) {
newVerbs.insert(v);
continue;
}
std::string key(v, 0, i);
std::string value(v, i + 1);
RequestParamFilter::Location location
= RequestParamFilter::QUERY;
if (key.find("header:") == 0) {
location = RequestParamFilter::HEADER;
key = string(key, 7); // strip off header:
}
filters.emplace_back(location, key, value);
}
verbs = newVerbs;
}
void
RequestFilter::
getHelp(Json::Value & result) const
{
if (!verbs.empty()) {
int i = 0;
for (auto it = verbs.begin(), end = verbs.end(); it != end; ++it, ++i) {
result["verbs"][i] = *it;
}
}
if (!filters.empty()) {
for (auto & f: filters) {
string loc = (f.location == RequestParamFilter::HEADER ? "header:" : "");
result["filters"].append(loc + f.param + "=" + f.value);
}
}
}
std::set<Utf8String>
RequestFilter::
getIgnoredQueryParameters() const
{
std::set<Utf8String> result;
for (auto & f: filters) {
if (f.location == RequestParamFilter::QUERY)
result.insert(f.param);
}
return result;
}
std::ostream & operator << (std::ostream & stream, const RequestParamFilter & filter)
{
return stream << (filter.location == RequestParamFilter::QUERY ? "query:" : "header:")
<< filter.param << "=" << filter.value;
}
std::ostream & operator << (std::ostream & stream, const RequestFilter & filter)
{
return stream << "verbs " << filter.verbs << " filters " << filter.filters;
}
/*****************************************************************************/
/* REST REQUEST PARSING CONTEXT */
/*****************************************************************************/
std::ostream & operator << (std::ostream & stream,
const RestRequestParsingContext & context)
{
return stream << context.resources << " " << context.remaining;
}
/*****************************************************************************/
/* REST REQUEST ROUTER */
/*****************************************************************************/
RestRequestRouter::
RestRequestRouter()
: terminal(false)
{
notFoundHandler = defaultNotFoundHandler;
}
RestRequestRouter::
RestRequestRouter(const OnProcessRequest & processRequest,
const OnNotFoundRequest & notFoundHandler,
const Utf8String & description,
bool terminal,
const Json::Value & argHelp)
: rootHandler(processRequest),
notFoundHandler(notFoundHandler),
description(description),
terminal(terminal),
argHelp(argHelp)
{
}
RestRequestRouter::
~RestRequestRouter()
{
}
RestRequestRouter::OnHandleRequest
RestRequestRouter::
requestHandler() const
{
return std::bind(&RestRequestRouter::handleRequest,
this,
std::placeholders::_1,
std::placeholders::_2);
}
void
RestRequestRouter::
handleRequest(RestConnection & connection,
const RestRequest & request) const
{
//MLDB_TRACE_EXCEPTIONS(false);
RestRequestParsingContext context(request);
RestRequestMatchResult res = processRequest(connection, request, context);
if (res == MR_NO) {
notFoundHandler(connection, request);
}
}
static std::string getVerbsStr(const std::set<std::string> & verbs)
{
string verbsStr;
for (auto v: verbs) {
if (!verbsStr.empty())
verbsStr += ",";
verbsStr += v;
}
return verbsStr;
}
namespace {
EnvOption<bool, true> TRACE_REST_REQUESTS("TRACE_REST_REQUESTS", false);
} // file scope
RestRequestMatchResult
RestRequestRouter::
processRequest(RestConnection & connection,
const RestRequest & request,
RestRequestParsingContext & context) const
{
bool debug = TRACE_REST_REQUESTS;
if (debug) {
cerr << "processing request " << request
<< " with context " << context
<< " against route " << description
<< " with " << subRoutes.size() << " subroutes" << endl;
}
if (request.verb == "OPTIONS") {
Json::Value help;
std::set<std::string> verbs;
this->options(verbs, help, request, context);
RestParams headers = { { "Allow", getVerbsStr(verbs) } };
if (verbs.empty())
connection.sendHttpResponse(400, "", "", headers);
else
connection.sendHttpResponse(200, help.toStyledString(),
"application/json",
headers);
return MR_YES;
}
if (rootHandler && (!terminal || context.remaining.empty())) {
if (debug) {
cerr << "invoked root handler for request " << request << endl;
}
return rootHandler(connection, request, context);
}
for (auto & sr: subRoutes) {
if (debug)
cerr << " trying subroute " << sr.router->description << endl;
try {
RestRequestMatchResult mr = sr.process(request, context, connection);
//cerr << "returned " << mr << endl;
if (mr == MR_YES || mr == MR_ASYNC || mr == MR_ERROR) {
if (debug) {
cerr << "invoked subroute "
<< " for request " << request << endl;
}
return mr;
}
} catch (const std::exception & exc) {
return sendExceptionResponse(connection, exc);
} catch (...) {
connection.sendJsonErrorResponse(500, "unknown exception");
return MR_YES;
}
}
return MR_NO;
//connection.sendErrorResponse(404, "invalid route for "
// + request.resource);
}
void
RestRequestRouter::
options(std::set<std::string> & verbsAccepted,
Json::Value & help,
const RestRequest & request,
RestRequestParsingContext & context) const
{
for (auto & sr: subRoutes) {
sr.options(verbsAccepted, help, request, context);
}
}
bool
RestRequestRouter::Route::
matchPath(RestRequestParsingContext & context) const
{
switch (path.type) {
case PathSpec::STRING: {
if (context.remaining.removePrefix(path.path)) {
context.resources.push_back(path.path);
break;
}
else return false;
}
case PathSpec::REGEX: {
MatchResults results;
bool found
= regex_search(context.remaining, results, path.rex,
std::regex_constants::match_continuous)
&& !results.prefix().matched; // matches from the start
if (!found)
return false;
for (unsigned i = 0; i < results.size(); ++i) {
// decode URI prior to pushing it to context.resources
Utf8String in(results[i].first, results[i].second);
context.resources.push_back(Url::decodeUri(in));
}
context.remaining.replace(0, results[0].length(), "");
break;
}
case PathSpec::NONE:
default:
throw AnnotatedException(400, "unknown rest request type");
}
return true;
}
RestRequestMatchResult
RestRequestRouter::Route::
process(const RestRequest & request,
RestRequestParsingContext & context,
RestConnection & connection) const
{
using namespace std;
bool debug = TRACE_REST_REQUESTS;
if (debug) {
cerr << "verb = " << request.verb << " filter.verbs = " << filter.verbs
<< endl;
}
if (!filter.verbs.empty()
&& !filter.verbs.count(request.verb))
return MR_NO;
// Check that the parameter filters match
for (auto & f: filter.filters) {
bool matched = false;
if (f.location == RequestParamFilter::QUERY) {
for (auto & p: request.params) {
if (p.first == f.param && (f.value == "*" || p.second == f.value)) {
matched = true;
break;
}
}
}
else if (f.location == RequestParamFilter::HEADER) {
if (debug) {
cerr << "matching header " << f.param << " with value "
<< request.header.tryGetHeader(f.param)
<< " against " << f.value << endl;
}
if (request.header.tryGetHeader(f.param) == f.value) {
matched = true;
}
}
if (!matched)
return MR_NO;
}
// At the end, make sure we put the context back to how it was
RestRequestParsingContext::StateGuard guard(&context);
if (!matchPath(context))
return MR_NO;
if (extractObject)
extractObject(connection, request, context);
if (connection.responseSent())
return MR_YES;
return router->processRequest(connection, request, context);
}
void
RestRequestRouter::Route::
options(std::set<std::string> & verbsAccepted,
Json::Value & help,
const RestRequest & request,
RestRequestParsingContext & context) const
{
RestRequestParsingContext::StateGuard guard(&context);
if (!matchPath(context))
return;
if (context.remaining.empty()) {
verbsAccepted.insert(filter.verbs.begin(), filter.verbs.end());
string path = "";//this->path.getPathDesc();
Json::Value & sri = help[path + getVerbsStr(filter.verbs)];
this->path.getHelp(sri);
filter.getHelp(sri);
router->getHelp(help, path, filter.verbs);
}
router->options(verbsAccepted, help, request, context);
}
void
RestRequestRouter::
addRoute(PathSpec path, RequestFilter filter,
const std::shared_ptr<RestRequestRouter> & handler,
ExtractObject extractObject)
{
if (rootHandler)
throw AnnotatedException(500, "can't add a sub-route to a terminal route");
Route route;
route.path = path;
route.filter = filter;
route.router = handler;
route.extractObject = extractObject;
// see explanation in header as why this is necessary
std::vector<RequestParamFilter> sortedNewFilters(route.filter.filters);
std::sort(sortedNewFilters.begin(), sortedNewFilters.end());
auto hideRoute = [&](const Route& existingRoute) {
std::vector<RequestParamFilter> sortedExistingFilters(existingRoute.filter.filters);
std::sort(sortedExistingFilters.begin(), sortedExistingFilters.end());
// check if verbs and filters are already part of an existing route
if ( !std::includes(existingRoute.filter.verbs.begin(),
existingRoute.filter.verbs.end(),
route.filter.verbs.begin(),
route.filter.verbs.end()) ||
!std::includes(sortedNewFilters.begin(),
sortedNewFilters.end(),
sortedExistingFilters.begin(),
sortedExistingFilters.end()) )
return false;
// check if the path match one of an existing route
switch (route.path.type) {
case PathSpec::STRING:
switch (existingRoute.path.type) {
case PathSpec::STRING:
return route.path.path == existingRoute.path.path;
case PathSpec::REGEX: {
MatchResults results;
//cerr << "path " << route.path.path.rawString() << " regex " << existingRoute.path.rex.surface().rawString() << endl;
if (route.path.path.empty())
return existingRoute.path.rex.surface().empty();
return regex_match(route.path.path, results, existingRoute.path.rex);
}
case PathSpec::NONE:
default:
throw AnnotatedException(400, "unknown rest request type");
}
case PathSpec::REGEX:
switch (existingRoute.path.type) {
case PathSpec::STRING: {
//cerr << "regex " << route.path.rex.surface() << " path " << existingRoute.path.path << endl;
return false; // we assume here that a regex path cannot be hidden by a string path
}
case PathSpec::REGEX:
return route.path.rex.surface() == existingRoute.path.rex.surface();
case PathSpec::NONE:
default:
throw AnnotatedException(400, "unknown rest request type");
}
case PathSpec::NONE:
default:
throw AnnotatedException(400, "unknown rest request type");
}
};
/* do not allow route to be hidden by a previously registered one */
auto hidingRoute = std::find_if(subRoutes.begin(), subRoutes.end(), hideRoute);
if (hidingRoute != subRoutes.end()) {
std::ostringstream message;
message << "route [" << hidingRoute->path << " " << hidingRoute->filter << "]"
<< " is hiding newly added route [" << route.path << " " << route.filter << "]";
throw AnnotatedException(500, message.str());
}
subRoutes.emplace_back(std::move(route));
}
void
RestRequestRouter::
addRoute(PathSpec path, RequestFilter filter,
const Utf8String & description,
const OnProcessRequest & cb,
const Json::Value & argHelp,
ExtractObject extractObject)
{
addRoute(path, filter,
std::make_shared<RestRequestRouter>(cb, notFoundHandler, description, true, argHelp),
extractObject);
}
void
RestRequestRouter::
addHelpRoute(PathSpec path, RequestFilter filter)
{
OnProcessRequest helpRoute
= [=] (RestConnection & connection,
const RestRequest & request,
const RestRequestParsingContext & context)
{
Json::Value help;
if (request.params.hasValue("autodoc")) {
getAutodocHelp(help, "", set<string>());
} else {
getHelp(help, "", set<string>());
}
connection.sendJsonResponse(200, help);
return MR_YES;
};
addRoute(path, filter, "Get help on the available API commands",
helpRoute, Json::Value());
}
void
RestRequestRouter::
addAutodocRoute(PathSpec autodocPath, PathSpec helpPath,
const string & autodocFilesPath)
{
Utf8String autodocPathStr = autodocPath.getPathDesc();
OnProcessRequest rootRoute
= [=] (RestConnection & connection,
const RestRequest & request,
const RestRequestParsingContext & context) {
connection.sendRedirect(302, (autodocPathStr + "/index.html").rawString());
return RestRequestRouter::MR_YES;
};
addRoute(autodocPathStr, "GET", "Main autodoc page",
rootRoute, Json::Value());
addRoute(autodocPathStr + "/", "GET", "Main autodoc page",
rootRoute, Json::Value());
OnProcessRequest autodocRoute
= [=] (RestConnection & connection,
const RestRequest & request,
const RestRequestParsingContext & context) {
Utf8String path = context.resources.back();
if (path.find("..") != path.end()) {
throw AnnotatedException(400, "not dealing with path with .. in it");
}
if (!path.removePrefix(autodocPathStr)) {
throw AnnotatedException(400, "not serving file not under " + autodocPathStr);
}
Utf8String filename = path;
// Remove any leading / characters
while (filename.removePrefix("/"));
if (filename == "autodoc") {
connection.sendRedirect(302, (helpPath.getPathDesc() + "?autodoc").rawString());
return RestRequestRouter::MR_YES;
}
Utf8String filenameToLoad = autodocFilesPath + "/" + filename;
filenameToLoad.removePrefix("file://");
MLDB::File_Read_Buffer buf(filenameToLoad.rawString());
string mimeType = "text/plain";
if (filename.endsWith(".html")) {
mimeType = "text/html";
}
else if (filename.endsWith(".js")) {
mimeType = "application/javascript";
}
else if (filename.endsWith(".css")) {
mimeType = "text/css";
}
string result(buf.start(), buf.end());
connection.sendResponse(200, result, mimeType);
return RestRequestRouter::MR_YES;
};
addRoute(Rx(autodocPathStr + "/.*", "<resource>"), "GET",
"Static content", autodocRoute, Json::Value());
}
void
RestRequestRouter::
getHelp(Json::Value & result, const Utf8String & currentPath,
const std::set<std::string> & verbs) const
{
Json::Value & v = result[(currentPath.empty() ? "" : currentPath + " ")
+ getVerbsStr(verbs)];
v["description"] = description;
if (!argHelp.isNull())
v["arguments"] = argHelp;
for (unsigned i = 0; i < subRoutes.size(); ++i) {
Utf8String path = currentPath + subRoutes[i].path.getPathDesc();
Json::Value & sri = result[(path.empty() ? "" : path + " ")
+ getVerbsStr(subRoutes[i].filter.verbs)];
subRoutes[i].path.getHelp(sri);
subRoutes[i].filter.getHelp(sri);
subRoutes[i].router->getHelp(result, path, subRoutes[i].filter.verbs);
}
}
void
RestRequestRouter::
updateFromValueDescription(Json::Value & v, const ValueDescription * vd) const {
const ValueKind kind = vd->kind;
if (kind == ValueKind::INTEGER) {
v["type"] = "integer";
}
else if (kind == ValueKind::BOOLEAN) {
v["type"] = "boolean";
}
else if (kind == ValueKind::STRING) {
v["type"] = "string";
}
else if (kind == ValueKind::ENUM) {
v["description"].asString() + " (cppType: " + vd->typeName + ")";
v["type"] = "string";
vector<string> keys = vd->getEnumKeys();
stringstream pattern;
bool first = true;
for (const string & k: keys) {
if (!first) {
pattern << "|";
}
pattern << k;
};
v["pattern"] = pattern.str();
}
else if (kind == ValueKind::LINK) {
cerr << "Got link field as final value: " << vd->typeName << endl;
v["description"].asString() + " (cppType: " + vd->typeName + ")";
const ValueDescription * subVdPtr = &(vd->contained());
cerr << subVdPtr->typeName << endl;
v["type"] = "string";
}
else if (kind == ValueKind::FLOAT) {
v["type"] = "float";
}
else if (kind == ValueKind::ARRAY) {
v["type"] = "array";
const ValueDescription * subVdPtr = &(vd->contained());
updateFromValueDescription(v["items"], subVdPtr);
}
else if (kind == ValueKind::STRUCTURE) {
v["description"].asString() + " (cppType: " + vd->typeName + ")";
v["type"] = "object";
}
else if (kind == ValueKind::ATOM) {
v["description"] =
v["description"].asString() + " (cppType: " + vd->typeName + ")";
if (vd->typeName == "MLDB::TimePeriod") {
v["type"] = "string";
v["pattern"] = "^[\\d]+(s|m|h|d)$";
}
else if (vd->typeName == "MLDB::Any") {
v["type"] = "object";
}
else {
v["type"] = "string";
}
}
else if (kind == ValueKind::ANY) {
//cppType == Json::Value
v["type"] = "object";
}
else {
cerr << "uncovered conversion case for kind: " << kind
<< " typeName: " << vd->typeName << endl;
v["type"] = "object (cppType: " + vd->typeName + ")";
}
}
void
RestRequestRouter::
addValueDescriptionToProperties(const ValueDescription * vd,
Json::Value & properties, int recur) const
{
using namespace Json;
if (recur > 2) {
//Too many recursions
return;
}
auto onField = [&] (const ValueDescription::FieldDescription & fd) {
Value tmpObj;
tmpObj["description"] = fd.comment;
const ValueDescription * curr = fd.description.get();
if (curr->kind == ValueKind::LINK) {
curr = &(curr->contained());
if (curr->kind == ValueKind::LINK) {
cerr << "link of link not supported" << endl;
}
}
updateFromValueDescription(tmpObj, curr);
if (curr->kind == ValueKind::ARRAY) {
const ValueDescription * subVdPtr = &(curr->contained());
if (subVdPtr->kind == ValueKind::STRUCTURE) {
if (vd == subVdPtr) {
tmpObj["items"]["type"] =
"object (recursive, cppType: " + curr->typeName + ")";
tmpObj["items"]["properties"] = objectValue;
}
else {
Value itemProperties;
addValueDescriptionToProperties(subVdPtr, itemProperties,
recur + 1);
tmpObj["items"]["items"]["properties"] = itemProperties;
}
}
else {
if (subVdPtr->kind == ValueKind::ARRAY) {
// unsupported "pair" type
tmpObj["items"]["type"] =
"object (cppType: " + curr->typeName + ")";
}
else {
updateFromValueDescription(tmpObj["items"], subVdPtr);
}
}
}
else if (curr->kind == ValueKind::STRUCTURE) {
Value itemProperties;
addValueDescriptionToProperties(curr,
itemProperties, recur + 1);
tmpObj["items"]["properties"] = itemProperties;
}
properties[fd.fieldName] = tmpObj;
};
vd->forEachField(nullptr, onField);
}
void
RestRequestRouter::
addJsonParamsToProperties(const Json::Value & params,
Json::Value & properties) const
{
using namespace Json;
for (Value param: params) {
string cppType = param["cppType"].asString();
const ValueDescription * vd = ValueDescription::get(cppType).get();
if (vd->kind == ValueKind::STRUCTURE) {
addValueDescriptionToProperties(vd, properties);
}
else {
Value tmpObj;
updateFromValueDescription(tmpObj, vd);
tmpObj["description"] = param["description"].asString();
properties[param["name"].asString()] = tmpObj;
}
}
}
void
RestRequestRouter::
getAutodocHelp(Json::Value & result, const Utf8String & currentPath,
const std::set<std::string> & verbs) const
{
using namespace Json;
Value tmpResult;
getHelp(tmpResult, "", set<string>());
result["routes"] = arrayValue;
result["literate"] = arrayValue;
result["config"] = objectValue;
for (ValueIterator it = tmpResult.begin() ; it != tmpResult.end() ; it++) {
string key = it.key().asString();
vector<string> parts = MLDB::split(it.key().asString());
int size = parts.size();
if (size == 0) {
// the empty key contains the description
continue;
}
if (size == 1) {
// useless route
continue;
}
ExcAssert(size == 2);
if (parts[1] != "GET" && parts[1] != "POST" && parts[1] != "PUT"
&& parts[1] != "DELETE") {
//unsupported verb + param
continue;
}
Value curr = arrayValue;
curr.append(parts[1] + " " + parts[0]);
Value subObj;
subObj["out"] = objectValue;
subObj["out"]["required"] = arrayValue;
subObj["out"]["type"] = "object";
subObj["out"]["properties"] = objectValue;
subObj["required_role"] = nullValue;
subObj["docstring"] = (*it)["description"].asString();
subObj["in"] = nullValue;
subObj["in"]["required"] = arrayValue;
subObj["in"]["type"] = "object";
subObj["in"]["properties"] = objectValue;
if ((*it).isMember("arguments") && (*it)["arguments"].isMember("jsonParams")) {
addJsonParamsToProperties((*it)["arguments"]["jsonParams"],
subObj["in"]["properties"]);
}
curr.append(subObj);
result["routes"].append(curr);
}
}
RestRequestRouter &
RestRequestRouter::
addSubRouter(PathSpec path,
const Utf8String & description,
ExtractObject extractObject,
std::shared_ptr<RestRequestRouter> subRouter)
{
// TODO: check it doesn't exist
Route route;
route.path = path;
if (subRouter)
route.router = subRouter;
else route.router.reset(new RestRequestRouter());
route.router->description = description;
route.router->notFoundHandler = notFoundHandler;
route.extractObject = extractObject;
subRoutes.push_back(route);
return *route.router;
}
void
RestRequestRouter::
defaultNotFoundHandler(RestConnection & connection,
const RestRequest & request) {
connection.sendJsonErrorResponse(404, "unknown resource " + request.verb + " " + request.resource);
};
RestRequestMatchResult
sendExceptionResponse(RestConnection & connection,
const std::exception & exc)
{
int defaultCode = 400;
Json::Value val = extractException(exc, defaultCode);
int code = defaultCode;
if (val.isMember("httpCode")) {
code = val["httpCode"].asInt();
}
connection.sendJsonResponse(code, val);
return RestRequestRouter::MR_ERROR;
}
Json::Value extractException(const std::exception & exc, int defaultCode)
{
const AnnotatedException * http
= dynamic_cast<const AnnotatedException *>(&exc);
const std::bad_alloc * balloc
= dynamic_cast<const std::bad_alloc *>(&exc);
Json::Value val;
val["error"] = exc.what();
if (http) {
val["httpCode"] = http->httpCode;
if (!http->details.empty())
val["details"] = jsonEncode(http->details);
} else if (balloc) {
val["error"] = "Out of memory. A memory allocation failed when performing "
"the operation. Consider retrying with a smaller amount of data "
"or running on a machine with more memory. "
"(std::bad_alloc)";
}
else {
val["httpCode"] = defaultCode;
}
return val;
}
} // namespace MLDB
|
30ffbb664089959dbe2b835ba09add4508813a86
|
2132b3aad607c4cec2a05ea0c523d59724dd2a68
|
/modules/src/csdm_mm.cpp
|
d5905bfb5e5f64251db9dfd7539b42b9cf373e2d
|
[
"Apache-2.0"
] |
permissive
|
zirplex/countering
|
a8745396631bb47e7b92dd65b922c4c20be4152e
|
a28cb8bed06bbb3269c41c2fdd0c35b432022785
|
refs/heads/master
| 2021-01-07T13:11:27.951913
| 2020-02-25T19:27:32
| 2020-02-25T19:27:32
| 241,704,592
| 0
| 0
|
Apache-2.0
| 2020-02-20T09:25:10
| 2020-02-19T19:19:03
|
Dockerfile
|
UTF-8
|
C++
| false
| false
| 10,722
|
cpp
|
csdm_mm.cpp
|
#include "amxxmodule.h"
#include "csdm_amxx.h"
#include "csdm_message.h"
#include "csdm_timer.h"
#include "csdm_config.h"
#include "csdm_player.h"
#include "csdm_util.h"
#include "csdm_tasks.h"
#include "csdm_spawning.h"
#define FRAMEWAIT 2.0f
#define GETINFOKEYBUFFER (*g_engfuncs.pfnGetInfoKeyBuffer)
#define SETCLIENTKEYVALUE (*g_engfuncs.pfnSetClientKeyValue)
#define GETCLIENTKEYVALUE (*g_engfuncs.pfnInfoKeyValue)
Message g_Msg;
FakeCommand g_FakeCmd;
int g_DeathMsg = 0;
int g_ShowMenuMsg = 0;
int g_CurMsg = 0;
int g_VGUIMenuMsg = 0;
int g_CurPostMsg = 0;
float g_LastTime;
bool g_First = true;
edict_t *pTarget = NULL;
float g_LastScore = 0.0f;
float g_LastHudReset = 0.0f;
int g_HudResets = 0;
int g_HudsNeeded = 0;
cvar_t init_csdm_active = {"csdm_active", "1", FCVAR_SERVER|FCVAR_SPONLY};
cvar_t init_csdm_version = {"csdm_version", MODULE_VERSION, FCVAR_SERVER|FCVAR_SPONLY};
cvar_t init_mp_freeforall = {"mp_freeforall", "0", FCVAR_SERVER|FCVAR_SPONLY};
cvar_t *csdm_active = NULL;
cvar_t *csdm_version = NULL;
cvar_t *mp_freeforall = NULL;
edict_t *pLastCliKill = NULL;
void csdm_version_cmd()
{
print_srvconsole("[CSDM] Version %s (C)2003-2013 David \"BAILOPAN\" Anderson\n", MODULE_VERSION);
print_srvconsole("[CSDM] Written by the CSDM Team (BAILOPAN and Freecode), edited by KWo\n");
print_srvconsole("[CSDM] http://www.bailopan.net/\n");
}
void OnMetaAttach()
{
CVAR_REGISTER(&init_csdm_active);
CVAR_REGISTER(&init_csdm_version);
CVAR_REGISTER(&init_mp_freeforall);
csdm_active = CVAR_GET_POINTER(init_csdm_active.name);
csdm_version = CVAR_GET_POINTER(init_csdm_version.name);
mp_freeforall = CVAR_GET_POINTER(init_mp_freeforall.name);
g_LastTime = gpGlobals->time;
REG_SVR_COMMAND("csdm", csdm_version_cmd);
}
void OnMetaDetach()
{
ClearAllTaskCaches();
}
bool g_already_ran = false;
void ServerDeactivate_Post()
{
g_Timer.Clear();
g_Config.Clear();
g_SpawnMngr.Clear();
g_already_ran = false;
RETURN_META(MRES_IGNORED);
}
void SetActive(bool active)
{
if (active)
{
csdm_active->value = 1;
} else {
csdm_active->value = 0;
}
MF_ExecuteForward(g_StateChange, (active) ? CSDM_ENABLE : CSDM_DISABLE);
}
void ClientKill(edict_t *pEdict)
{
pLastCliKill = pEdict;
RETURN_META(MRES_IGNORED);
}
int DispatchSpawn_Post(edict_t *pEdict)
{
if (g_already_ran)
RETURN_META_VALUE(MRES_IGNORED, 0);
g_already_ran = true;
g_LastTime = gpGlobals->time;
ClearAllPlayers();
if (!g_load_okay)
{
MF_Log("CSDM failed to load, contact author...");
MF_ExecuteForward(g_InitFwd, "");
RETURN_META_VALUE(MRES_IGNORED, 0);
}
MF_ExecuteForward(g_InitFwd, MODULE_VERSION);
MF_ExecuteForward(g_CfgInitFwd);
char file[255];
MF_BuildPathnameR(file, sizeof(file)-1, "%s/csdm.cfg", LOCALINFO("amxx_configsdir"));
if (g_Config.ReadConfig(file) != Config_Ok)
MF_Log("Could not read config file: %s", file);
RETURN_META_VALUE(MRES_IGNORED, 0);
}
void StartFrame_Post()
{
if (IsActive() && g_LastTime + 0.1 < gpGlobals->time)
{
g_LastTime = gpGlobals->time;
g_Timer.Tick(gpGlobals->time);
if (g_First)
{
if (!g_DeathMsg)
g_DeathMsg = GET_USER_MSG_ID(PLID, "DeathMsg", NULL);
if (!g_ShowMenuMsg)
g_ShowMenuMsg = GET_USER_MSG_ID(PLID, "ShowMenu", NULL);
if (!g_VGUIMenuMsg)
g_VGUIMenuMsg = GET_USER_MSG_ID(PLID, "VGUIMenu", NULL);
g_First = false;
}
}
RETURN_META(MRES_IGNORED);
}
void MessageBegin(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed)
{
if (!IsActive())
RETURN_META(MRES_IGNORED);
if (g_DeathMsg && (msg_type == g_DeathMsg))
{
g_CurMsg = msg_type;
} else if (g_ShowMenuMsg && (msg_type == g_ShowMenuMsg)) {
g_CurMsg = g_ShowMenuMsg;
pTarget = ed;
} else if (g_VGUIMenuMsg && (msg_type == g_VGUIMenuMsg)) {
g_CurMsg = g_VGUIMenuMsg;
pTarget = ed;
}
RETURN_META(MRES_IGNORED);
}
void MessageEnd()
{
if (g_CurMsg)
{
if (g_CurMsg == g_DeathMsg)
{
int pk = g_Msg.GetParamInt(0);
int pv = g_Msg.GetParamInt(1);
int hs = g_Msg.GetParamInt(2);
const char *sz = g_Msg.GetParamString(3);
DeathHandler(pk, pv, hs, sz, false);
g_CurPostMsg = g_DeathMsg;
} else if (g_CurMsg == g_ShowMenuMsg) {
const char *str = g_Msg.GetParamString(3);
if (!strcmp(str, "#Terrorist_Select") || !strcmp(str, "#CT_Select"))
{
int client = ENTINDEX(pTarget);
player_states *pPlayer = GET_PLAYER(client);
if (pPlayer->spawned)
{
//doesn't matter if they're dead, stop respawn
pPlayer->spawned = 0;
pPlayer->spawning = false;
pPlayer->blockspawn = true;
pPlayer->wait = -1.0f;
SetPlayerModel(pTarget, 0xFF);
}
}
g_Msg.Reset();
} else if (g_CurMsg == g_VGUIMenuMsg) {
int id = g_Msg.GetParamInt(0);
int client = ENTINDEX(pTarget);
player_states *pPlayer = GET_PLAYER(client);
if ((id == 26 || id == 27) && pPlayer->spawned)
{
pPlayer->spawned = 0;
pPlayer->spawning = false;
pPlayer->blockspawn = true;
pPlayer->wait = -1.0f;
SetPlayerModel(pTarget, 0xFF);
}
g_Msg.Reset();
}
g_CurMsg = 0;
}
RETURN_META(MRES_IGNORED);
}
void MessageEnd_Post()
{
if (g_CurPostMsg)
{
if (g_CurPostMsg == g_DeathMsg)
{
int pk = g_Msg.GetParamInt(0);
int pv = g_Msg.GetParamInt(1);
if (!pv && !FNullEnt(pLastCliKill))
pv = ENTINDEX(pLastCliKill);
if (pv)
{
int hs = g_Msg.GetParamInt(2);
const char *sz = g_Msg.GetParamString(3);
DeathHandler(pk, pv, hs, sz, true);
}
}
g_CurPostMsg = 0;
g_Msg.Reset();
}
RETURN_META(MRES_IGNORED);
}
void WriteByte(int iValue)
{
if (g_CurMsg)
{
g_Msg.AddParam(iValue);
}
RETURN_META(MRES_IGNORED);
}
void WriteChar(int iValue)
{
if (g_CurMsg)
{
g_Msg.AddParam(iValue);
}
RETURN_META(MRES_IGNORED);
}
void WriteShort(int iValue)
{
if (g_CurMsg)
{
g_Msg.AddParam(iValue);
}
RETURN_META(MRES_IGNORED);
}
void WriteLong(int iValue)
{
if (g_CurMsg)
{
g_Msg.AddParam(iValue);
}
RETURN_META(MRES_IGNORED);
}
void WriteAngle(float fValue)
{
if (g_CurMsg)
{
g_Msg.AddParam(fValue);
}
RETURN_META(MRES_IGNORED);
}
void WriteCoord(float fValue)
{
if (g_CurMsg)
{
g_Msg.AddParam(fValue);
}
RETURN_META(MRES_IGNORED);
}
void WriteString(const char *sz)
{
if (g_CurMsg)
{
g_Msg.AddParam(sz);
}
RETURN_META(MRES_IGNORED);
}
void WriteEntity(int iValue)
{
if (g_CurMsg)
{
g_Msg.AddParam(iValue);
}
RETURN_META(MRES_IGNORED);
}
void ClientPutInServer(edict_t *pEdict)
{
int index = ENTINDEX(pEdict);
player_states *pPlayer = GET_PLAYER(index);
pPlayer->ingame = true;
if (g_IntroMsg)
{
Welcome *pWelcome = new Welcome(pEdict);
g_Timer.AddTask(pWelcome, 10.0);
}
RETURN_META(MRES_IGNORED);
}
void ClientDisconnect(edict_t *pEdict)
{
int index = ENTINDEX(pEdict);
if (pEdict == pLastCliKill)
pLastCliKill = NULL;
ClearPlayer(index);
RETURN_META(MRES_IGNORED);
}
void ClientUserInfoChanged(edict_t *pEntity, char *infobuffer)
{
int index = ENTINDEX(pEntity);
player_states *pPlayer = GET_PLAYER(index);
if (!pPlayer->ingame && (pEntity->v.flags & FL_FAKECLIENT))
pPlayer->ingame = true;
RETURN_META(MRES_IGNORED);
}
BOOL ClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[128])
{
int index = ENTINDEX(pEntity);
player_states *pPlayer = GET_PLAYER(index);
if (pEntity->v.flags & FL_FAKECLIENT)
pPlayer->ingame = true;
else
pPlayer->ingame = false;
pPlayer->blockspawn = false;
pPlayer->wait = 0.0f;
RETURN_META_VALUE(MRES_IGNORED, true);
}
#if 0 //temporarily disabled, under research
void PlayerPreThink(edict_t *pEdict)
{
int index = ENTINDEX(pEdict);
if (!IsActive())
{
RETURN_META(MRES_IGNORED);
}
player_states *pPlayer = GET_PLAYER(index);
if ( (!(pEdict->v.flags & FL_CLIENT) &&
!(pEdict->v.flags & FL_FAKECLIENT))
||
(pEdict->v.flags & FL_SPECTATOR) )
{
RETURN_META(MRES_IGNORED);
}
int team = GetPlayerTeam(pEdict);
if ( (team != TEAM_T && team != TEAM_CT) )
{
RETURN_META(MRES_IGNORED);
}
if ( (pEdict->v.deadflag == DEAD_NO) && ((int)pEdict->v.health > 0) )
{
if (pEdict->v.weaponmodel != 0)
{
const char *str = STRING(pEdict->v.weaponmodel);
if (!str || str[0] == '\0')
{
RespawnPlayer(pEdict);
}
} else {
//we need some sort of timer or validation here
RespawnPlayer(pEdict);
}
}
RETURN_META(MRES_IGNORED);
}
#endif
void PlayerPostThink(edict_t *pEdict)
{
int index = ENTINDEX(pEdict);
if (!IsActive())
{
RETURN_META(MRES_IGNORED);
}
player_states *pPlayer = GET_PLAYER(index);
//if they're not in game or have already spawned once, we don't care...
if (pPlayer->spawned)
{
RETURN_META(MRES_IGNORED);
} else if (!pPlayer->ingame || pPlayer->spawning) {
RETURN_META(MRES_IGNORED);
}
//if they're on an invalid team, we don't care...
int team = GetPlayerTeam(pEdict);
if (team != TEAM_T && team != TEAM_CT)
{
RETURN_META(MRES_IGNORED);
}
if (strcmp(STRING(pEdict->v.model), "models/player.mdl")==0 ||
strcmp(STRING(pEdict->v.model), "models\\player.mdl")==0)
{
RETURN_META(MRES_IGNORED);
}
if (GetPlayerModel(pEdict) == 0xFF)
RETURN_META(MRES_IGNORED);
//are they alive?
if ((pEdict->v.deadflag == DEAD_NO) && !(pEdict->v.flags & FL_SPECTATOR))
{
pPlayer->spawned = 1;
FakespawnPlayer(pEdict);
} else {
if (pPlayer->wait == -1.0f)
{
pPlayer->spawned = 1;
RespawnPlayer(pEdict);
pPlayer->wait = 0.0f;
} else if (pPlayer->wait < 0.1f) {
pPlayer->wait = gpGlobals->time;
} else if (gpGlobals->time - pPlayer->wait > FRAMEWAIT) {
//they've selected a team, and we can safely respawn him.
pPlayer->spawned = 1;
RespawnPlayer(pEdict);
pPlayer->wait = 0.0f;
}
}
RETURN_META(MRES_IGNORED);
}
const char *Cmd_Args()
{
if (g_FakeCmd.GetArgc())
RETURN_META_VALUE(MRES_SUPERCEDE, g_FakeCmd.GetFullString());
RETURN_META_VALUE(MRES_IGNORED, NULL);
}
const char *Cmd_Argv(int argc)
{
if (g_FakeCmd.GetArgc())
RETURN_META_VALUE(MRES_SUPERCEDE, g_FakeCmd.GetArg(argc));
RETURN_META_VALUE(MRES_IGNORED, NULL);
}
int Cmd_Argc(void)
{
if (g_FakeCmd.GetArgc())
RETURN_META_VALUE(MRES_SUPERCEDE, g_FakeCmd.GetArgc());
RETURN_META_VALUE(MRES_IGNORED, 0);
}
void ClientCommand(edict_t *pEntity)
{
const char* cmd = CMD_ARGV(0);
if (!cmd)
RETURN_META(MRES_IGNORED);
if (strcmp(cmd, "csdm")==0 || strcmp(cmd, "csdm_version")==0)
{
print_client(pEntity, 2, "[CSDM] Version %s (C)2003-2013 David \"BAILOPAN\" Anderson\n", MODULE_VERSION);
print_client(pEntity, 2, "[CSDM] Written by the CSDM Team (BAILOPAN and Freecode), edited by KWo\n");
print_client(pEntity, 2, "[CSDM] http://www.bailopan.net/csdm/\n");
RETURN_META(MRES_SUPERCEDE);
}
RETURN_META(MRES_IGNORED);
}
|
7d0f17fdb0e870f81230a07975e8e589ce8e7675
|
a34f083ca56929f9d0d40f7e36a9b94bc2b0830b
|
/src/diffuse.hpp
|
4475a0b626f5deb43d42671f003f1e33f3f7fdab
|
[] |
no_license
|
sakanaman/RayStatistics
|
c07c26e9989540173547bbb335de21af10215df6
|
7b69b0e140503bdbd84a6c40765c52b39d9f3664
|
refs/heads/master
| 2022-11-03T02:22:41.769532
| 2020-06-17T23:38:58
| 2020-06-17T23:38:58
| 256,610,697
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 194
|
hpp
|
diffuse.hpp
|
#ifndef DIFFUSE_HPP
#define DIFFUSE_HPP
#include "vec.hpp"
Vec sample_cosine_hemisphere(float u, float v);
Vec brdf_diffuse(const Vec& albedo);
float pdf_diffuse(const Vec& wi);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.