text
stringlengths 8
6.88M
|
|---|
#include "stdafx.h"
#include "Command.h"
#include <iostream>
using namespace std;
Command::Command()
{
}
Command::~Command()
{
std::cout << "command baseclass destructor" << endl;
}
void Command::Run(list<string>* parameters, Game * game)
{
}
|
//-----------------------------------------------------------------------------
// VST Plug-Ins SDK
// VSTGUI: Graphical User Interface Framework not only for VST plugins :
//
// Version 4.2
//
//-----------------------------------------------------------------------------
// VSTGUI LICENSE
// (c) 2013, Steinberg Media Technologies, 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 Steinberg Media Technologies nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#include "cshadowviewcontainer.h"
#include "coffscreencontext.h"
#include "cbitmapfilter.h"
#include "cframe.h"
#include "cbitmap.h"
#include <cassert>
namespace VSTGUI {
//-----------------------------------------------------------------------------
CShadowViewContainer::CShadowViewContainer (const CRect& size)
: CViewContainer (size)
, dontDrawBackground (false)
, shadowIntensity (0.3f)
, shadowBlurSize (4)
, scaleFactorUsed (0.)
{
registerViewContainerListener (this);
}
//-----------------------------------------------------------------------------
CShadowViewContainer::CShadowViewContainer (const CShadowViewContainer& copy)
: CViewContainer (copy)
, dontDrawBackground (false)
, shadowIntensity (copy.shadowIntensity)
, shadowBlurSize (copy.shadowBlurSize)
, scaleFactorUsed (0.)
{
registerViewContainerListener (this);
}
//------------------------------------------------------------------------
CShadowViewContainer::~CShadowViewContainer ()
{
unregisterViewContainerListener (this);
}
//-----------------------------------------------------------------------------
bool CShadowViewContainer::removed (CView* parent)
{
getFrame ()->unregisterScaleFactorChangedListeneer (this);
setBackground (0);
return CViewContainer::removed (parent);
}
//-----------------------------------------------------------------------------
bool CShadowViewContainer::attached (CView* parent)
{
if (CViewContainer::attached (parent))
{
invalidateShadow ();
getFrame ()->registerScaleFactorChangedListeneer (this);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::onScaleFactorChanged (CFrame* frame)
{
invalidateShadow ();
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::setShadowOffset (const CPoint& offset)
{
if (shadowOffset != offset)
{
shadowOffset = offset;
invalidateShadow ();
}
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::setShadowIntensity (float intensity)
{
if (shadowIntensity != intensity)
{
shadowIntensity = intensity;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::setShadowBlurSize (double size)
{
if (shadowBlurSize != size)
{
shadowBlurSize = size;
invalidateShadow ();
}
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::invalidateShadow ()
{
scaleFactorUsed = 0.;
invalid ();
}
//-----------------------------------------------------------------------------
CMessageResult CShadowViewContainer::notify (CBaseObject* sender, IdStringPtr message)
{
if (message == kMsgViewSizeChanged)
invalidateShadow ();
return CViewContainer::notify(sender, message);
}
//-----------------------------------------------------------------------------
static std::vector<int32_t> boxesForGauss (double sigma, uint16_t numBoxes)
{
std::vector<int32_t> boxes;
double ideal = std::sqrt ((12 * sigma * sigma / numBoxes) + 1);
uint16_t l = static_cast<uint16_t> (std::floor (ideal));
if (l % 2 == 0)
l--;
int32_t u = l + 2;
ideal = ((12. * sigma * sigma) - (numBoxes * l * l) - (4. * numBoxes * l) - (3. * numBoxes)) / ((-4. * l) - 4.);
int32_t m = static_cast<int32_t> (std::floor (ideal));
for (int32_t i = 0; i < numBoxes; ++i)
boxes.push_back (i < m ? l : u);
return boxes;
}
//-----------------------------------------------------------------------------
static bool isUniformScaled (const CGraphicsTransform& matrix)
{
return matrix.m11 == matrix.m22;
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::drawRect (CDrawContext* pContext, const CRect& updateRect)
{
double scaleFactor = pContext->getScaleFactor ();
CGraphicsTransform matrix = pContext->getCurrentTransform ();
if (isUniformScaled (matrix))
{
double matrixScale = std::floor (matrix.m11 + 0.5);
if (matrixScale != 0.)
scaleFactor *= matrixScale;
}
if (scaleFactor != scaleFactorUsed && getWidth () > 0. && getHeight () > 0.)
{
scaleFactorUsed = scaleFactor;
CCoord width = getWidth ();
CCoord height = getHeight ();
SharedPointer<COffscreenContext> offscreenContext = owned (COffscreenContext::create (getFrame (), width, height, scaleFactor));
if (offscreenContext)
{
offscreenContext->beginDraw ();
CDrawContext::Transform transform (*offscreenContext, CGraphicsTransform ().translate (-getViewSize ().left - shadowOffset.x, -getViewSize ().top - shadowOffset.y));
dontDrawBackground = true;
CViewContainer::draw (offscreenContext);
dontDrawBackground = false;
offscreenContext->endDraw ();
CBitmap* bitmap = offscreenContext->getBitmap ();
if (bitmap)
{
setBackground (bitmap);
SharedPointer<BitmapFilter::IFilter> setColorFilter = owned (BitmapFilter::Factory::getInstance ().createFilter (BitmapFilter::Standard::kSetColor));
if (setColorFilter)
{
setColorFilter->setProperty (BitmapFilter::Standard::Property::kInputBitmap, bitmap);
setColorFilter->setProperty (BitmapFilter::Standard::Property::kInputColor, kBlackCColor);
setColorFilter->setProperty (BitmapFilter::Standard::Property::kIgnoreAlphaColorValue, (int32_t)1);
if (setColorFilter->run (true))
{
SharedPointer<BitmapFilter::IFilter> boxBlurFilter = owned (BitmapFilter::Factory::getInstance ().createFilter (BitmapFilter::Standard::kBoxBlur));
if (boxBlurFilter)
{
std::vector<int32_t> boxSizes = boxesForGauss (shadowBlurSize, 3);
boxBlurFilter->setProperty (BitmapFilter::Standard::Property::kInputBitmap, bitmap);
boxBlurFilter->setProperty (BitmapFilter::Standard::Property::kRadius, boxSizes[0]);
if (boxBlurFilter->run (true))
{
boxBlurFilter->setProperty (BitmapFilter::Standard::Property::kRadius, boxSizes[1]);
boxBlurFilter->run (true);
boxBlurFilter->setProperty (BitmapFilter::Standard::Property::kRadius, boxSizes[2]);
boxBlurFilter->run (true);
}
}
}
}
CViewContainer::drawRect (pContext, updateRect);
}
}
}
else
{
CViewContainer::drawRect (pContext, updateRect);
}
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::drawBackgroundRect (CDrawContext* pContext, const CRect& _updateRect)
{
if (!dontDrawBackground)
{
float tmp = pContext->getGlobalAlpha ();
pContext->setGlobalAlpha (tmp * shadowIntensity);
CViewContainer::drawBackgroundRect (pContext, _updateRect);
pContext->setGlobalAlpha (tmp);
}
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::setViewSize (const CRect& rect, bool invalid)
{
if (getViewSize () != rect)
{
bool diffSize = (getWidth () != rect.getWidth () || getHeight () != rect.getHeight ());
CViewContainer::setViewSize (rect, invalid);
if (diffSize)
invalidateShadow ();
}
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::viewContainerViewAdded (CViewContainer* container, CView* view)
{
assert (container == this);
invalidateShadow ();
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::viewContainerViewRemoved (CViewContainer* container, CView* view)
{
assert (container == this);
invalidateShadow ();
}
//-----------------------------------------------------------------------------
void CShadowViewContainer::viewContainerViewZOrderChanged (CViewContainer* container, CView* view)
{
assert (container == this);
invalidateShadow ();
}
} // namespace
|
#ifndef FUZZYCORE_OUTPUT_VARIABLE_DAO_H
#define FUZZYCORE_OUTPUT_VARIABLE_DAO_H
#include "../DAOUtils/DAOUtils.h"
#include "../DAOUtils/NullConverter.h"
#include "../../utils/stringEditor/StringEditor.h"
#include "../../enums.hpp"
#include "../../models/outputVariable/OutputVariable.h"
class OutputVariableDAO {
private:
std::vector<Field> fields;
std::vector<std::string> constraints;
OutputVariableDAO();
public:
std::string TABLE_NAME;
static OutputVariableDAO &getInstance();
static OutputVariable find_by_name_and_space(const std::string &, unsigned long);
static std::vector<OutputVariable> findAllBySpace(const std::string& spaceName);
static void create(const OutputVariable &);
static void delete_variable(const std::string &, unsigned long);
};
#endif
|
#ifndef _HS_SFM_FEATURE_MATCH_OPENCV_FEATURE_DETECTOR_HPP_
#define _HS_SFM_FEATURE_MATCH_OPENCV_FEATURE_DETECTOR_HPP_
#include <string>
#include <vector>
#include <opencv2/nonfree/features2d.hpp>
#include "hs_sfm/config/hs_config.hpp"
namespace hs
{
namespace sfm
{
namespace feature_match
{
class HS_EXPORT OpenCVFeatureDetector
{
public:
OpenCVFeatureDetector(int number_of_features = 0,
int number_of_octave_layers = 3,
double contrast_threshold = 0.04,
double edge_threshold = 10,
double sigma = 1.6);
int Detect(const std::vector<std::string>& image_paths,
const std::vector<std::string>& key_paths,
const std::vector<std::string>& descriptor_paths,
unsigned int pyramid = 0,
double* complete_ratio = nullptr,
int* keep_work = nullptr);
private:
cv::SIFT sift_;
};
}
}
}
#endif
|
#include <bits/stdc++.h>
using namespace std;
const int MAX_INT = std::numeric_limits<int>::max();
const int MIN_INT = std::numeric_limits<int>::min();
const int INF = 1000000000;
const int NEG_INF = -1000000000;
#define max(a,b)(a>b?a:b)
#define min(a,b)(a<b?a:b)
#define MEM(arr,val)memset(arr,val, sizeof arr)
#define PI acos(0)*2.0
#define eps 1.0e-9
#define are_equal(a,b)fabs(a-b)<eps
#define LS(b)(b& (-b)) // Least significant bit
#define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians
typedef long long ll;
typedef pair<ll, ll> ii;
typedef pair<int,char> ic;
typedef pair<long,char> lc;
typedef vector<int> vi;
typedef vector<ii> vii;
int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);}
int lcm(int a,int b){return a*(b/gcd(a,b));}
ll h, q, i, l, r, a;
int main(){
cin >> h >> q;
vii yes, no;
ll mxx = 1ll<<(h-1), mny = 1ll<<h;
while (q--) {
cin >> i >> l >> r >> a;
l = l << (h-i);
r = (r+1) << (h-i);
if (a) {
mxx = max(mxx, l);
mny = min(mny, r);
}
else no.push_back(ii(l, r));
}
if (mxx > mny) {
printf("Game cheated!\n");
return 0;
}
no.push_back(ii(mny, mny));
sort(no.begin(), no.end());
ll ans = -1;
for (int j = 0; j < no.size(); j++) {
ll x = no[j].first, y = no[j].second;
if (mxx >= mny)
break;
if (x > mxx) {
if (ans != -1 || x > mxx + 1) {
printf("Data not sufficient!\n");
return 0;
}
ans = mxx;
}
mxx = max(mxx, y);
}
if (ans == -1)
printf("Game cheated!\n");
else cout << ans << endl;
return 0;
}
|
#pragma once
#include "Plant.h"
#include<vector>
#include<math.h>
#include<ctime>
#define PI 3.14
/*! \brief
* Derived from Plant class, indicates the pattern for creating each set of top points and the difference between
* each top's and base's radius.
*/
class Tree:public Plant
{
public:
Tree(double width, double height, int numberOfBranches, int level);
~Tree(void);
void SetBranchTop(vector<Point3D> base, vector<Point3D>& top, int currentLevel, GLfloat radius, GLfloat pass, GLfloat index);
void SetInitialPass(GLfloat& pass, GLfloat radius);
void IncrementPass(GLfloat& pass, GLfloat radius);
};
|
/*************************************************************
* > File Name : P1441.cpp
* > Author : Tony
* > Created Time : 2019/06/21 15:27:10
* > Algorithm : [Dfs+DP]
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 22;
const int maxm = 2010;
int n, m, ans, cnt, tmp;
int a[maxn];
bool dp[maxm], vis[maxn];
void DP() {
memset(dp, 0, sizeof(dp)); dp[0] = true;
cnt = 0; tmp = 0;
for (int i = 0; i < n; ++i) {
if (vis[i]) continue;
for (int j = cnt; j >= 0; --j) {
if (dp[j] && !dp[j + a[i]]) {
dp[j + a[i]] = true;
tmp++;
}
}
cnt += a[i];
}
ans = max(ans, tmp);
}
void dfs(int now, int cur) {
if (now > m) return;
if (cur == n) {
if (now == m) {
DP();
}
return;
}
dfs(now, cur + 1);
vis[cur] = true;
dfs(now + 1, cur + 1);
vis[cur] = false;
}
int main() {
n = read(); m = read();
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
dfs(0, 0);
printf("%d\n", ans);
return 0;
}
|
//Asked on HackerEarth/heaps
//All testCases Passed, within the given time complexity.
#include<bits/stdc++.h>
using namespace std;
void buildHeap(vector<long long> &arr, int n, int i) {
int parent = (i-1) / 2;
if(arr[i] > arr[parent]) {
swap(arr[i],arr[parent]);
buildHeap(arr,n,parent);
}
}
void printHeap(vector<long long> &arr) {
vector<long long>::iterator it = arr.begin();
while(it!=arr.end()) {
cout<<*it<<" ";
it++;
}
cout<<"\n";
}
long long int mul(vector<long long> arr, int i) {
long long int y=1;
int l=3,z;
//printHeap(arr);
while(l>0 && i>0) {
z = arr[0];
y = y * z;
pop_heap(arr.begin(), arr.begin()+i);
//printHeap(arr);
i--;
l--;
}
return y;
}
int main() {
long long int n,x,res;
cin>>n;
vector<long long> arr;
for(int i=0; i<n; i++) {
cin>>x;
arr.push_back(x);
}
make_heap(arr.begin(), arr.begin()+3);
res = mul(arr,3);
cout<<"-1"<<"\n"<<"-1"<<"\n"<<res<<"\n";
int i=3;
while(i<n) {
cout<<arr[i]<<" "<<arr[0]<<endl;
if(arr[i] > arr[0] || arr[i] > arr[1] || arr[i] > arr[2]) {
push_heap(arr.begin(), arr.begin()+i+1);
//buildHeap(arr,n,i);
res = mul(arr,i+1);
}
cout<<res<<"\n";
i++;
}
}
|
int Solution::minimize(const vector<int> &a, const vector<int> &b, const vector<int> &c) {
int aa=a.size();
int bb=b.size();
int cc=c.size();
int i=0,j=0,k=0;
int ans=INT_MAX;
while(i<aa and j<bb and k<cc)
{
int temp=max({abs(a[i] - b[j]), abs(b[j] - c[k]), abs(c[k] - a[i])});
ans=min(ans,temp);
if(a[i]<=b[j] and a[i]<=c[k])
i++;
else if(b[j]<=a[i] and b[j]<=c[k])
j++;
else
k++;
}
return ans;
}
|
/**
* Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "multimedia/mmparam.h"
#include "multimedia/mm_debug.h"
MM_LOG_DEFINE_MODULE_NAME("MMParamTest")
using namespace YUNOS_MM;
MMParam g_param;
class MMParamTest : public testing::Test {
protected:
virtual void SetUp() {
}
virtual void TearDown() {
}
};
struct TestS : public MMRefBase {
TestS(int i) : mI(i) {}
~TestS() { MMLOGI("+\n");}
int mI;
virtual void f(){}
};
typedef MMSharedPtr<TestS> TestSSP;
struct TestS2 : public MMRefBase {
TestS2(int i) : mI(i) {}
~TestS2() { MMLOGI("+\n");}
int mI;
virtual void f(){}
};
typedef MMSharedPtr<TestS2> TestS2SP;
static void addPointer(MMParam & param){
TestSSP pointer(new TestS(1));
ASSERT_NE(NULL, pointer.get());
TestS2SP pointer1(new TestS2(2));
ASSERT_NE(NULL, pointer1.get());
EXPECT_EQ(param.writePointer(pointer),MM_ERROR_SUCCESS);
EXPECT_EQ(param.writePointer(pointer1),MM_ERROR_SUCCESS);
}
static void verifyPointer(const MMParam & param){
TestSSP r = std::tr1::dynamic_pointer_cast<TestS>(param.readPointer());
ASSERT_NE(r.get(), NULL);
MMLOGI("gotp1: %d\n", r->mI);
TestS2SP r2 = std::tr1::dynamic_pointer_cast<TestS2>(param.readPointer());
ASSERT_NE(r2.get(), NULL);
MMLOGI("gotp2: %d\n", r2->mI);
}
TEST_F(MMParamTest, paramWriteTest) {
MMLOGD("testing MMParam write\n");
EXPECT_EQ(g_param.writeInt32(12),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeInt32(34),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeInt64(56),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeInt64(78),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeFloat(0.11),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeFloat(0.22),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeDouble(0.33),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeDouble(0.44),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeCString("hello"),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeCString("world"),MM_ERROR_SUCCESS);
EXPECT_EQ(g_param.writeInt32(0xef),MM_ERROR_SUCCESS);
addPointer(g_param);
}
TEST_F(MMParamTest, paramReadTest) {
MMLOGD("testing MMParam read\n");
int32_t i;
g_param.readInt32(&i);
EXPECT_EQ(i, 12);
MMLOGI("retrieve: %d\n", i);
g_param.readInt32(&i);
EXPECT_EQ(i, 34);
MMLOGI("retrieve: %d\n", i);
int64_t j;
g_param.readInt64(&j);
EXPECT_EQ(j, 56);
MMLOGI("retrieve: %" PRId64 "\n", j);
g_param.readInt64(&j);
EXPECT_EQ(j, 78);
MMLOGI("retrieve: %" PRId64 "\n", j);
float f;
g_param.readFloat(&f);
EXPECT_EQ(f, ( float )0.11);
MMLOGI("retrieve: %f\n", f);
g_param.readFloat(&f);
EXPECT_EQ(f, ( float )0.22);
MMLOGI("retrieve: %f\n", f);
double d;
g_param.readDouble(&d);
EXPECT_EQ(d, 0.33);
MMLOGI("retrieve: %f\n", d);
g_param.readDouble(&d);
EXPECT_EQ(d, 0.44);
MMLOGI("retrieve: %f\n", d);
const char * s;
s = g_param.readCString();
EXPECT_STREQ(s, "hello");
MMLOGI("retrieve: %s\n", s);
s = g_param.readCString();
EXPECT_STREQ(s, "world");
MMLOGI("retrieve: %s\n", s);
g_param.readInt32(&i);
EXPECT_EQ(i, 0xef);
MMLOGI("retrieve: %d\n", i);
verifyPointer(g_param);
}
TEST_F(MMParamTest, paramCopyTest) {
MMLOGI("testing MMParam copy \n");
MMParam param_copy1 = MMParam(g_param);
MMParam param_copy2 = MMParam(&g_param);
int32_t i_cp = 0;
param_copy1.readInt32(&i_cp);
EXPECT_EQ(i_cp, 12);
MMLOGI("retrieve copy 1: %d\n", i_cp);
param_copy2.readInt32(&i_cp);
EXPECT_EQ(i_cp, 12);
MMLOGI("retrieve copy 2: %d\n", i_cp);
param_copy1.readInt32(&i_cp);
EXPECT_EQ(i_cp, 34);
MMLOGI("retrieve copy 1: %d\n", i_cp);
param_copy2.readInt32(&i_cp);
EXPECT_EQ(i_cp, 34);
MMLOGI("retrieve copy 2: %d\n", i_cp);
int64_t j_cp =0;
param_copy1.readInt64(&j_cp);
EXPECT_EQ(j_cp ,56);
MMLOGI("retrieve copy 1: %" PRId64 "\n", j_cp);
param_copy2.readInt64(&j_cp);
EXPECT_EQ(j_cp, 56);
MMLOGI("retrieve copy 2: %" PRId64 "\n", j_cp);
param_copy1.readInt64(&j_cp);
EXPECT_EQ(j_cp, 78);
MMLOGI("retrieve copy 1: %" PRId64 "\n", j_cp);
param_copy2.readInt64(&j_cp);
EXPECT_EQ(j_cp, 78);
MMLOGI("retrieve copy 2: %" PRId64 "\n", j_cp);
float f_cp = 0;
param_copy1.readFloat(&f_cp);
EXPECT_EQ(f_cp, ( float )0.11);
MMLOGI("retrieve copy 1: %f\n", f_cp);
param_copy2.readFloat(&f_cp);
EXPECT_EQ(f_cp, ( float )0.11);
MMLOGI("retrieve copy 2: %f\n", f_cp);
param_copy1.readFloat(&f_cp);
EXPECT_EQ(f_cp, ( float )0.22);
MMLOGI("retrieve copy 1: %f\n", f_cp);
param_copy2.readFloat(&f_cp);
EXPECT_EQ(f_cp, ( float )0.22);
MMLOGI("retrieve copy 2: %f\n", f_cp);
double d_cp = 0;
param_copy1.readDouble(&d_cp);
EXPECT_EQ(d_cp, 0.33);
MMLOGI("retrieve copy 1: %f\n", d_cp);
param_copy2.readDouble(&d_cp);
EXPECT_EQ(d_cp, 0.33);
MMLOGI("retrieve copy 2: %f\n", d_cp);
param_copy1.readDouble(&d_cp);
EXPECT_EQ(d_cp, 0.44);
MMLOGI("retrieve copy 1: %f\n", d_cp);
param_copy2.readDouble(&d_cp);
EXPECT_EQ(d_cp, 0.44);
MMLOGI("retrieve copy 2: %f\n", d_cp);
const char * s_cp;
s_cp = param_copy1.readCString();
EXPECT_STREQ(s_cp,"hello");
MMLOGI("retrieve copy 1: %s\n", s_cp);
s_cp = param_copy2.readCString();
EXPECT_STREQ(s_cp, "hello");
MMLOGI("retrieve copy 2: %s\n", s_cp);
s_cp = param_copy1.readCString();
EXPECT_STREQ(s_cp , "world");
MMLOGI("retrieve copy 1: %s\n", s_cp);
s_cp = param_copy2.readCString();
EXPECT_STREQ(s_cp, "world");
MMLOGI("retrieve copy 2: %s\n", s_cp);
param_copy1.readInt32(&i_cp);
EXPECT_EQ(i_cp, 0xef);
MMLOGI("retrieve copy 1: %d\n", i_cp);
param_copy2.readInt32(&i_cp);
EXPECT_EQ(i_cp, 0xef);
MMLOGI("retrieve copy 2: %d\n", i_cp);
verifyPointer(param_copy1);
verifyPointer(param_copy2);
}
TEST_F(MMParamTest, paramOpCopyTest) {
MMLOGI("testing MMParam operator copy\n");
MMParam param_copy3 = g_param;
int32_t i_cp = 0;
i_cp = param_copy3.readInt32();
EXPECT_EQ(i_cp, 12);
MMLOGI("retrieve copy 3: %d\n", i_cp);
i_cp = param_copy3.readInt32();
EXPECT_EQ(i_cp, 34);
MMLOGI("retrieve copy 3: %d\n", i_cp);
int64_t j_cp =0;
j_cp = param_copy3.readInt64();
EXPECT_EQ(j_cp, 56);
MMLOGI("retrieve copy 3: %" PRId64 "\n", j_cp);
j_cp = param_copy3.readInt64();
EXPECT_EQ(j_cp, 78);
MMLOGI("retrieve copy 3: %" PRId64 "\n", j_cp);
float f_cp = 0;
f_cp = param_copy3.readFloat();
EXPECT_EQ(f_cp, ( float )0.11);
MMLOGI("retrieve copy 3: %f\n", f_cp);
f_cp = param_copy3.readFloat();
EXPECT_EQ(f_cp, ( float )0.22);
MMLOGI("retrieve copy 3: %f\n", f_cp);
double d_cp = 0;
d_cp = param_copy3.readDouble();
EXPECT_EQ(d_cp, 0.33);
MMLOGI("retrieve copy 3: %f\n", d_cp);
d_cp = param_copy3.readDouble();
EXPECT_EQ(d_cp, 0.44);
MMLOGI("retrieve copy 3: %f\n", d_cp);
const char * s_cp;
s_cp = param_copy3.readCString();
EXPECT_STREQ(s_cp, "hello");
MMLOGI("retrieve copy 3: %s\n", s_cp);
s_cp = param_copy3.readCString();
EXPECT_STREQ(s_cp, "world");
MMLOGI("retrieve copy 3: %s\n", s_cp);
i_cp = param_copy3.readInt32();
EXPECT_EQ(i_cp, 0xef);
MMLOGI("retrieve copy 3: %d\n", i_cp);
verifyPointer(param_copy3);
}
int main(int argc, char* const argv[]) {
int ret;
try {
::testing::InitGoogleTest(&argc, (char **)argv);
ret = RUN_ALL_TESTS();
} catch (...) {
MMLOGE("InitGoogleTest failed!");
return -1;
}
return ret;
}
|
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<int> temp;
backtrack(n,0,temp,k);
return result;
}
void backtrack(int n, int pos, vector<int> temp, int k)
{
if(temp.size() == k)
{
result.push_back(temp);
return;
}
if(temp.size() + (n-pos) < k) return;
for(int i = pos+1; i <= n; i++)
{
temp.push_back(i);
backtrack(n,i,temp,k);
temp.pop_back();
}
}
private:
vector<vector<int>> result;
};
|
//使用for循环,将50~100相加
#include <iostream>
using namespace std;
int main() {
int sum=0;
for(int val=50;val<=100;val++)
sum+=val;
cout << sum <<endl;
return 0;
}
|
#ifndef NETWORKINTERFACE_H
#define NETWORKINTERFACE_H
#ifdef _WIN32
#include <json/json.h>
#else
#include <jsoncpp/json/json.h>
#endif
#include <string>
class NetworkInterface {
public:
virtual Json::Value sendRequestGet(const std::string& requ, const std::string& body = "") = 0;
virtual Json::Value sendRequestPost(const std::string& requ, const std::string& body = "") = 0;
};
#endif
|
#pragma once
//#include "Module.h"
#include "Application.h"
#include "ImGui\imconfig.h"
//#include "ImGui\imgui_internal.h"
#include "Panel.h"
#include "Console.h"
#include "ConfigPanel.h"
#include "imgui_impl_sdl.h"
#include "SDL/include/SDL_opengl.h"
#include "Geomath.h"
#include "GameObject.h"
#include "ImGui\ImGuizmo\ImGuizmo.h"
class Module;
class Application;
class ConfigPanel;
class PlayPause;
class ModuleImGui : public Module {
public:
ModuleImGui(bool start_enabled = true);
~ModuleImGui();
bool Init(JSON_File* conf);
update_status PreUpdate(float dt);
update_status Update(float dt);
update_status PostUpdate(float dt);
bool CleanUp();
void LoadStyle(char* name);
void ImGuiInput(SDL_Event* ev);
void Draw();
float GetRandomValue(float range_1, float range_2);
void LogFps(float fps, float ms);
void AddPanel(Panel* panel);
void Setproperties(bool set);
GameObject* curr_obj;
bool HoveringWindow();
private:
std::list<Panel*> panels;
bool show_test_window = false;
bool geometry = false;
bool properties = false;
bool about = false;
bool save = false;
bool load = false;
//Console* console = nullptr;
ConfigPanel* configuration = nullptr;
PlayPause* playpause = nullptr;
float x, y, z, r,posx,posy,posz,h,d;
char save_scene_name[50];
char load_scene_name[50];
ImGuizmo::OPERATION curr_operation;
ImGuizmo::MODE curr_mode;
///just for testing mathgeolib///
};
|
#include <Polycode.h>
#include "PolycodeView.h"
#include "Polycode3DPhysics.h"
#include <vector>
#include <list>
using namespace Polycode;
#define MOVE_SPEED 4.0 //speed when area == 100
#define MOVE_SPEED_STEP 0.1
#define MAX_MOVE_SPEED 4.0
#define START_TIME 20
#define MAX_BOOST 10
#define BOOST_RATE 5 //points per second
#define BOOST_BURN 20
#define MAX_AGE 5 //Time a msg should be on screen
#define faster_move Color(0x0000FFFF)
#define slower_move Color(0xCC0066FF)
#define time_up Color(0x00FF00FF)
#define time_down Color(0xCC6600FF)
enum section_type {normal, transition};
struct section {
section_type type;
Number height, width, depth; //Normal dimensions of section
Number height1, width1, height2, width2; //dimentions of ends for transition sections
Vector3 position;
std::vector<ScenePrimitive*> walls;
std::vector<ScenePrimitive*> obstacles;
std::vector<ScenePrimitive*> enemies;
section(Number height, Number width, Number depth, Vector3 pos=Vector3(0,0,0));
section(Number height1, Number width1, Number height2, Number width2, Number depth, Vector3 pos=Vector3(0,0,0));
void setPosition(Vector3 pos);
void setPosition(Number x, Number y, Number z);
bool inSection(Vector3 loc);
Number getArea();
Number getArea(Vector3 loc);
};
struct msg {
ScreenLabel *label;
Number age;
msg(ScreenLabel *label);
};
class HelloPolycodeApp : public EventHandler {
public:
HelloPolycodeApp(PolycodeView *view);
~HelloPolycodeApp();
bool Update();
void handleEvent(Event *e);
void addmsg(const String & text);
private:
Core *core;
Screen *screen;
ScreenLabel *label;
ScreenLabel *boost_l;
ScreenLabel *speed_l;
ScreenLabel *timer_l;
std::list<msg> msgs;
CollisionScene *cscene;
Camera *cam1, *cam2, *cam3, *cam4;
ScenePrimitive *obj;
Number home; //stores current home x-coordinate
Number yspeed;
Number zspeed;
Number boost;
short int x_in, y_in, z_in;
Number game_time;
int end_flag;
Number max_move, max_boost, boost_rate;
//Color more_boost, less_boost, faster_move, slower_move, faster_recharge, slower_recharge;
std::vector<section> sections;
bool addObstacle(Color c, Vector3 p); //adds obstacle to last section in sections
bool addEnemy(Vector3 p); //adds enemy to last section in sections
void addSection(Number length, Number endWidth, Number endHeight);
};
|
#include <ArduinoJson.h>
#include <AzureIoTHub.h>
#include <SPIFFS.h>
#include "logging.h"
#include "iot_device_core.h"
#include "iot_device_method.h"
struct MethodCallback {
const char* methodName;
IOT_DEVICE_METHOD_CALLBACK callback;
};
static MethodCallback methodCallbacks[IOT_DEVICE_MAX_METHOD_COUNT];
static int registeredCount = 0;
static int IoTDevice_DeviceMethodCallback(const char* method_name, const unsigned char* payload, size_t size, unsigned char** response, size_t* response_size, void* userContextCallback)
{
(void)userContextCallback;
(void)payload;
(void)size;
bool methodFound = false;
int result;
Log_Debug("Direct method lookup: %s", method_name);
for(int i = 0; i < registeredCount; i++)
{
Log_Trace("Trying %s", methodCallbacks[i].methodName);
if (strcmp(methodCallbacks[i].methodName, method_name) == 0)
{
Log_Debug("Method callback for %s found. Executing", method_name);
methodFound = true;
result = methodCallbacks[i].callback(payload, size, response, response_size);
}
}
if (!methodFound)
{
Log_Info("Method %s not registered!", method_name);
const char deviceMethodResponse[] = "{ }";
*response_size = sizeof(deviceMethodResponse)-1;
*response = (unsigned char *)malloc(*response_size);
(void)memcpy(*response, deviceMethodResponse, *response_size);
result = -1;
}
return result;
}
int OnSystemInfoInvoked(const unsigned char* payload, size_t size, unsigned char** response, size_t* response_size)
{
String output;
DynamicJsonDocument doc(1024);
doc["chipRevision"] = ESP.getChipRevision();
doc["cpuFreqMHz"] = ESP.getCpuFreqMHz();
doc["cycleCount"] = ESP.getCycleCount();
doc["sdkVersion"] = ESP.getSdkVersion();
doc["flashChip"]["size"] = ESP.getFlashChipSize();
doc["flashChip"]["speed"] = ESP.getFlashChipSpeed();
doc["heap"]["size"] = ESP.getHeapSize(); //total heap size
doc["heap"]["free"] = ESP.getFreeHeap(); //available heap
doc["heap"]["minFree"] = ESP.getMinFreeHeap(); //lowest level of free heap since boot
doc["heap"]["maxAlloc"] = ESP.getMaxAllocHeap(); //largest block of heap that can be allocated at once
doc["spi"]["size"] = ESP.getPsramSize();
doc["spi"]["free"] = ESP.getFreePsram();
doc["spi"]["minFree"] = ESP.getMinFreePsram();
doc["spi"]["maxAlloc"] = ESP.getMaxAllocPsram();
doc["sketch"]["MD5"] = ESP.getSketchMD5();
doc["sketch"]["size"] = ESP.getSketchSize();
doc["sketch"]["space"] = ESP.getFreeSketchSpace();
doc["fs"]["usedBytes"] = SPIFFS.usedBytes();
doc["fs"]["totalBytes"] = SPIFFS.totalBytes();
serializeJsonPretty(doc, output);
const char *deviceMethodResponse = output.c_str();
*response_size = strlen(deviceMethodResponse);
*response = (unsigned char *)malloc(*response_size);
(void)memcpy(*response, deviceMethodResponse, *response_size);
return 200;
}
void IoTDevice_RegisterDeviceMethodCallback(){
(void)IoTHubClient_LL_SetDeviceMethodCallback(__hub_client_handle__, IoTDevice_DeviceMethodCallback, NULL);
IoTDevice_RegisterForMethodInvoke("systemInfo", OnSystemInfoInvoked);
}
void IoTDevice_RegisterForMethodInvoke(const char *methodName, IOT_DEVICE_METHOD_CALLBACK callback) {
Log_Debug("Registering method %s at index: %d", methodName, registeredCount);
if(registeredCount >= IOT_DEVICE_MAX_METHOD_COUNT)
{
Log_Error("Cannot regiter more than %d methods. Increase the IOT_DEVICE_MAX_METHOD_COUNT variable.", IOT_DEVICE_MAX_METHOD_COUNT);
return;
}
MethodCallback item = {
.methodName = methodName,
.callback = callback
};
methodCallbacks[registeredCount] = item;
registeredCount++;
}
|
//**************************************************************************
//
// Copyright (c) 1997.
// Richard D. Irwin, Inc.
//
// This software may not be distributed further without permission from
// Richard D. Irwin, Inc.
//
// This software is distributed WITHOUT ANY WARRANTY. No claims are made
// as to its functionality or purpose.
//
// Author: Devon Lockwood
// Date: 1/30/97
// $Revision: 1.1 $
// $Name: $
//
//**************************************************************************
/* EzWindows Library Header File
FILE: cstring.h
AUTHOR: Devon Lockwood
Time-stamp: <96/11/27 01:10:58 dcl3a>
Description
===========
This file provides easier portability for the code supplied
with the book.
*/
#ifndef EASY_STRING_H
#define EASY_STRING_H
#ifndef USING_CC
#include <string>
#else
#include "dstring.h"
#endif
#endif
|
#include "objeto_juego_i.h"
using namespace App_Interfaces;
Objeto_juego_I::Objeto_juego_I()
:borrar(false)
{
}
|
#include <iostream>
using namespace std;
bool isPrime(int);
int main(){
for(int i = 0; i < 1000; i++)
if (isPrime(i)) cout << i << endl;
return 0;
}
bool isPrime(int a){
if (a < 2) return false;
if (a == 2) return true;
if (a%2 == 0) return false;
for (int i = 3; i*i <= a; i++)
if (a%i == 0) return false;
return true;
}
|
/*
* dolier-remove-subincl.cpp
*
* Created on: Jan 24, 2014
* Author: vbonnici
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <sstream>
#include <set>
#include "data_ts.h"
#include "timer.h"
#include "trim.h"
#include "pars_t.h"
#include "dimers.h"
#include "DNA5Alphabet.h"
#include "FASTAReader.h"
#include "CstyleIndex.h"
#include "NSAIterator.h"
#include "Cs5DLIndex.h"
#include "SASearcher.h"
#include "main_common.h"
using namespace dolierlib;
char* scmd;
void pusage(){
std::cout<<"Remove sub-included kmers.\n";
std::cout<<"Usage: "<<scmd<<" <input_file> <output_file> [-r]\n";
std::cout<<"\t<input_file> is a 1 column file containing kmers of different length.\n";
std::cout<<"\t<output_file> 1 column output file containing only those kmers that are not a sub-string of a longer kmer.\n";
std::cout<<"\toptional [-r] also remove all those kmers that are a sub-string of the reverse complement of a longer kmer.\n";
std::cout<<"Duplicated kmers are considered self sub-included and will not be output.\n";
}
class mpars_t : public pars_t{
public:
std::string ifile;
std::string ofile;
bool opt_r;
mpars_t(int argc, char* argv[]) : pars_t(argc,argv){
opt_r = false;
}
~mpars_t(){}
virtual void print(){
std::cout<<"[ARG][ifile]["<<ifile<<"]\n";
std::cout<<"[ARG][ofile]["<<ofile<<"]\n";
std::cout<<"[ARG][opt_r]["<<opt_r<<"]\n";
}
virtual void check(){
print();
std::cout<<"check...\n";
ifile = trim(ifile);
ofile = trim(ofile);
if( (ifile.length() == 0) ||
(ofile.length() == 0)
){
usage();
exit(1);
}
}
virtual void usage(){
pusage();
}
virtual void parse(){
ifile = next_string();
ofile = next_string();
std::string cmd;
while(has_more()){
cmd = next_string();
if(cmd == "-r"){
opt_r = true;
}
else{
usage();
exit(1);
}
}
check();
}
};
class Ikmer{
public:
std::string kmer;
Ikmer(std::string kmer){
this->kmer = kmer;
}
friend bool operator== (const Ikmer& lhs, const Ikmer& rhs){
return lhs.kmer == rhs.kmer;
}
friend bool operator< (const Ikmer& lhs, const Ikmer& rhs) {
if(lhs.kmer.length() == rhs.kmer.length())
return lhs.kmer < rhs.kmer;
return lhs.kmer.length() < rhs.kmer.length();
}
};
int main(int argc, char* argv[]){
scmd = argv[0];
mpars_t pars(argc,argv);
pars.parse();
std::ifstream ifs;
ifs.open(pars.ifile.c_str(), std::ios::in);
if(!ifs.is_open() || ifs.bad()){
std::cout<<"Error on opening input file : "<<pars.ifile<<" \n";
exit(1);
}
std::ofstream ofs;
ofs.open(pars.ofile.c_str(), std::ios::out);
if(!ofs.is_open()){
std::cout<<"Error on opening output file : "<<pars.ofile<<" \n";
exit(1);
}
if(!pars.opt_r){
std::vector<dna5_t*> f_sequences;
std::vector<usize_t> f_lengths;
std::string ikmer;
while(ifs >> ikmer){
//ikmer = ikmer+DNA5Alphabet::UNDEF_SYMBOL;
f_sequences.push_back(to_dna5(ikmer));
f_lengths.push_back(ikmer.length());
}
ifs.close();
DNA5MS_t f_ms(true);
//concat(f_ms, f_sequences, f_lengths, true);
concat(f_ms, f_sequences, f_lengths, false);
// for(std::vector<dna5_t*>::iterator IT = f_sequences.begin(); IT!=f_sequences.end();IT++)
// delete [] (*IT);
f_ms.areUndefTeminated = true;
CsFullyContainer f_ds(true);
//build_fully_ds(f_ms, f_ds);
build_strict_ds(f_ms, f_ds);
Cs5DLIndex f_dlindex(f_ms.seq, f_ms.seq_length, f_ds.SA, f_ms.lengths, f_ms.nof_seqs);
SASearcher sas(f_ms.seq, f_ds.SA, f_ms.seq_length);
//print_SA_LCP_N(f_ms.seq, f_ms.seq_length, f_ds.SA, f_ds.LCP, f_ds.NS, 6);
std::set<Ikmer> tset;
std::vector<usize_t>::iterator lIT = f_lengths.begin();
for(std::vector<dna5_t*>::iterator IT = f_sequences.begin(); IT!=f_sequences.end(); ){
if (sas.count(*IT, (*lIT)-1) == 1){
tset.insert(Ikmer(to_string(*IT, (*lIT))));
//ofs<< to_string(*IT, (*lIT)-1);
//ofs<< "\n";
//print_dna5(*IT, (*lIT)-1);std::cout<<"\n";
}
IT++;
lIT++;
}
for(std::set<Ikmer>::iterator IT=tset.begin(); IT!=tset.end(); IT++){
ofs<< (*IT).kmer <<"\n";
}
for(std::vector<dna5_t*>::iterator IT = f_sequences.begin(); IT!=f_sequences.end();IT++)
delete [] (*IT);
}
else{
std::vector<dna5_t*> f_sequences;
std::vector<usize_t> f_lengths;
std::string ikmer;
std::string rikmer;
while(ifs >> ikmer){
rikmer = reverseComplement(ikmer);
f_sequences.push_back(to_dna5(ikmer));
f_lengths.push_back(ikmer.length());
f_sequences.push_back(to_dna5(rikmer));
f_lengths.push_back(ikmer.length());
// std::cout<<ikmer<<"\n";
// std::cout<<rikmer<<"\n";
}
ifs.close();
DNA5MS_t f_ms(true);
concat(f_ms, f_sequences, f_lengths, false);
// for(std::vector<dna5_t*>::iterator IT = f_sequences.begin(); IT!=f_sequences.end();IT++)
// delete [] (*IT);
f_ms.areUndefTeminated = true;
CsFullyContainer f_ds(true);
build_fully_ds(f_ms, f_ds);
//build_strict_ds(f_ms, f_ds);
Cs5DLIndex f_dlindex(f_ms.seq, f_ms.seq_length, f_ds.SA, f_ms.lengths, f_ms.nof_seqs);
SASearcher sas(f_ms.seq, f_ds.SA, f_ms.seq_length);
// print_dna5(f_ms.seq,f_ms.seq_length); std::cout<<"\n";
// print_SA_LCP_N(f_ms.seq, f_ms.seq_length, f_ds.SA, f_ds.LCP, f_ds.NS, 6);
std::set<Ikmer> tset;
std::vector<usize_t>::iterator lIT = f_lengths.begin();
for(std::vector<dna5_t*>::iterator IT = f_sequences.begin(); IT!=f_sequences.end(); ){
// print_dna5(*IT, *lIT); std::cout<<"\n";
if(RCeq(*IT, *lIT)){
// std::cout<<"\tRCeq\n";
if (sas.count(*IT, (*lIT)) == 2){
tset.insert(Ikmer(to_string(*IT, (*lIT))));
// ofs<< to_string(*IT, (*lIT));
// ofs<< "\n";
}
}
else if (sas.count(*IT, (*lIT)) == 1){
tset.insert(Ikmer(to_string(*IT, (*lIT))));
// ofs<< to_string(*IT, (*lIT));
// ofs<< "\n";
//print_dna5(*IT, (*lIT)-1);std::cout<<"\n";
}
IT++; IT++;
lIT++; lIT++;
}
for(std::set<Ikmer>::iterator IT=tset.begin(); IT!=tset.end(); IT++){
ofs<< (*IT).kmer <<"\n";
}
for(std::vector<dna5_t*>::iterator IT = f_sequences.begin(); IT!=f_sequences.end();IT++)
delete [] (*IT);
}
ofs.close();
exit(0);
}
|
#include <iostream>
using namespace std;
int main() {
int i = 1;
int number;
cout << "Enter the number:";
cin >> number;
for (; i < number; i *= 2) {
}
if (i == number) {
cout << "Yes";
} else {
cout << "No";
}
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.UI.WebUI.1.h"
#include "Windows.ApplicationModel.1.h"
#include "Windows.ApplicationModel.Activation.1.h"
#include "Windows.ApplicationModel.Background.1.h"
#include "Windows.Foundation.1.h"
#include "Windows.Graphics.Printing.1.h"
#include "Windows.ApplicationModel.2.h"
#include "Windows.ApplicationModel.Activation.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::UI::WebUI {
struct ActivatedEventHandler : Windows::Foundation::IUnknown
{
ActivatedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> ActivatedEventHandler(L lambda);
template <typename F> ActivatedEventHandler (F * function);
template <typename O, typename M> ActivatedEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::ApplicationModel::Activation::IActivatedEventArgs & eventArgs) const;
};
struct EnteredBackgroundEventHandler : Windows::Foundation::IUnknown
{
EnteredBackgroundEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> EnteredBackgroundEventHandler(L lambda);
template <typename F> EnteredBackgroundEventHandler (F * function);
template <typename O, typename M> EnteredBackgroundEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::ApplicationModel::IEnteredBackgroundEventArgs & e) const;
};
struct LeavingBackgroundEventHandler : Windows::Foundation::IUnknown
{
LeavingBackgroundEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> LeavingBackgroundEventHandler(L lambda);
template <typename F> LeavingBackgroundEventHandler (F * function);
template <typename O, typename M> LeavingBackgroundEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::ApplicationModel::ILeavingBackgroundEventArgs & e) const;
};
struct NavigatedEventHandler : Windows::Foundation::IUnknown
{
NavigatedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> NavigatedEventHandler(L lambda);
template <typename F> NavigatedEventHandler (F * function);
template <typename O, typename M> NavigatedEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::WebUI::IWebUINavigatedEventArgs & e) const;
};
struct ResumingEventHandler : Windows::Foundation::IUnknown
{
ResumingEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> ResumingEventHandler(L lambda);
template <typename F> ResumingEventHandler (F * function);
template <typename O, typename M> ResumingEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender) const;
};
struct SuspendingEventHandler : Windows::Foundation::IUnknown
{
SuspendingEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> SuspendingEventHandler(L lambda);
template <typename F> SuspendingEventHandler (F * function);
template <typename O, typename M> SuspendingEventHandler(O * object, M method);
void operator()(const Windows::Foundation::IInspectable & sender, const Windows::ApplicationModel::ISuspendingEventArgs & e) const;
};
struct IActivatedDeferral :
Windows::Foundation::IInspectable,
impl::consume<IActivatedDeferral>
{
IActivatedDeferral(std::nullptr_t = nullptr) noexcept {}
};
struct IActivatedEventArgsDeferral :
Windows::Foundation::IInspectable,
impl::consume<IActivatedEventArgsDeferral>
{
IActivatedEventArgsDeferral(std::nullptr_t = nullptr) noexcept {}
};
struct IActivatedOperation :
Windows::Foundation::IInspectable,
impl::consume<IActivatedOperation>
{
IActivatedOperation(std::nullptr_t = nullptr) noexcept {}
};
struct IHtmlPrintDocumentSource :
Windows::Foundation::IInspectable,
impl::consume<IHtmlPrintDocumentSource>,
impl::require<IHtmlPrintDocumentSource, Windows::Graphics::Printing::IPrintDocumentSource>
{
IHtmlPrintDocumentSource(std::nullptr_t = nullptr) noexcept {}
};
struct IWebUIActivationStatics :
Windows::Foundation::IInspectable,
impl::consume<IWebUIActivationStatics>
{
IWebUIActivationStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IWebUIActivationStatics2 :
Windows::Foundation::IInspectable,
impl::consume<IWebUIActivationStatics2>
{
IWebUIActivationStatics2(std::nullptr_t = nullptr) noexcept {}
};
struct IWebUIBackgroundTaskInstance :
Windows::Foundation::IInspectable,
impl::consume<IWebUIBackgroundTaskInstance>
{
IWebUIBackgroundTaskInstance(std::nullptr_t = nullptr) noexcept {}
};
struct IWebUIBackgroundTaskInstanceStatics :
Windows::Foundation::IInspectable,
impl::consume<IWebUIBackgroundTaskInstanceStatics>
{
IWebUIBackgroundTaskInstanceStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IWebUINavigatedDeferral :
Windows::Foundation::IInspectable,
impl::consume<IWebUINavigatedDeferral>
{
IWebUINavigatedDeferral(std::nullptr_t = nullptr) noexcept {}
};
struct IWebUINavigatedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IWebUINavigatedEventArgs>
{
IWebUINavigatedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IWebUINavigatedOperation :
Windows::Foundation::IInspectable,
impl::consume<IWebUINavigatedOperation>
{
IWebUINavigatedOperation(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
#include "DisplayGrid.h"
DisplayGrid::ColorIdMap DisplayGrid::GridColors;
DisplayGrid::DisplayGrid()
{
loadColors();
}
DisplayGrid::DisplayGrid(GridBool* obsMap) : obsMap(obsMap)
{
loadColors();
}
DisplayGrid::~DisplayGrid()
{}
void DisplayGrid::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
int amtX = obsMap->getWidth();
int amtY = obsMap->getHeight();
int sizeX = getSize().x;
int sizeY = getSize().y;
int tileX, tileY;
sf::Vector2f tileSize(sizeX / amtX, sizeY / amtY);
sf::RectangleShape tile(tileSize);
sf::Vector2f pos = getPosition();
for (int x = 0; x < amtX; x++)
{
for (int y = 0; y < amtY; y++)
{
tileX = pos.x + tileSize.x * x;
tileY = pos.y + tileSize.y * y;
tile.setPosition(tileX, tileY);
tile.setFillColor(getTileColor(obsMap->at(x, y)));
tile.setOutlineColor(getOutlineColor());
tile.setOutlineThickness(getOutlineThickness());
target.draw(tile);
}
}
}
sf::Color DisplayGrid::getTileColor(bool obsType) const
{
if (obsType)
{
return GridColors["Obs"];
}
else
{
return GridColors["Emp"];
}
}
void DisplayGrid::loadColors()
{
if (GridColors.size() != 3)
{
GridColors["Obs"] = sf::Color::Blue;
GridColors["Emp"] = sf::Color::White;
}
}
void DisplayGrid::setGrid(GridBool* grid)
{
obsMap = grid;
}
|
#include "HardwareSerial.hpp"
HardwareSerial::HardwareSerial() {
}
void HardwareSerial::begin(long speed) {
uart_config(speed, EIGHT_BITS, STICK_PARITY_DIS, NONE_BITS, ONE_STOP_BIT, NONE_CTRL);
}
void HardwareSerial::print(const char*s) {
while(*s) {
tx_one_char(*s++);
}
}
void HardwareSerial::print(char c, int base) {
print((long) c, base);
}
void HardwareSerial::print(unsigned char c, int base) {
print((unsigned long) c, base);
}
void HardwareSerial::print(int i, int base) {
print((long) i, base);
}
void HardwareSerial::print(unsigned int i, int base) {
print((unsigned long) i, base);
}
void HardwareSerial::print(long n, int base) {
if (base==BYTE) {
tx_one_char((char)n);
} else if (base==DEC) {
if (n<0) {
tx_one_char('-');
n = -n;
}
printNumber(n, base);
} else {
printNumber(n, base);
}
}
void HardwareSerial::print(unsigned long n, int base) {
if (base==BYTE) {
tx_one_char((char)n);
} else {
printNumber(n, base);
}
}
void HardwareSerial::print(double n, int digits) {
printFloat(n, digits);
}
void HardwareSerial::println(const char*s) {
print(s);
println();
}
void HardwareSerial::println(char c, int base) {
print(c, base);
println();
}
void HardwareSerial::println(unsigned char c, int base) {
print(c, base);
println();
}
void HardwareSerial::println(int n, int base) {
print(n, base);
println();
}
void HardwareSerial::println(unsigned int n, int base) {
print(n, base);
println();
}
void HardwareSerial::println(long n, int base) {
print(n, base);
println();
}
void HardwareSerial::println(unsigned long n, int base) {
print(n, base);
println();
}
void HardwareSerial::println(double n, int digits) {
print(n, digits);
println();
}
void HardwareSerial::println(void) {
tx_one_char('\r');
tx_one_char('\n');
}
// PRIVATE //
void HardwareSerial::tx_one_char(char c) {
while (true) {
uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(UART0)) & (UART_TXFIFO_CNT<<UART_TXFIFO_CNT_S);
if ((fifo_cnt >> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) < 126) {
break;
}
}
WRITE_PERI_REG(UART_FIFO(UART0), c);
}
void HardwareSerial::uart_config(unsigned int baut_rate, UartBitsNum4Char data_bits, UartExistParity exist_parity, UartParityMode parity, UartStopBitsNum stop_bits, UartFlowCtrl flow_ctrl) {
/* rcv_buff size if 0x100 */
//ETS_UART_INTR_ATTACH(uart0_rx_intr_handler, &(UartDev.rcv_buff));
PIN_PULLUP_DIS(PERIPHS_IO_MUX_U0TXD_U);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDO_U, FUNC_U0RTS);
uart_div_modify(UART0, UART_CLK_FREQ / baut_rate);
WRITE_PERI_REG(UART_CONF0(UART0), exist_parity
| parity
| (stop_bits << UART_STOP_BIT_NUM_S)
| (data_bits << UART_BIT_NUM_S));
// clear rx and tx fifo,not ready
SET_PERI_REG_MASK(UART_CONF0(UART0), UART_RXFIFO_RST | UART_TXFIFO_RST);
CLEAR_PERI_REG_MASK(UART_CONF0(UART0), UART_RXFIFO_RST | UART_TXFIFO_RST);
// set rx fifo trigger
// WRITE_PERI_REG(UART_CONF1(uart_no), ((UartDev.rcv_buff.TrigLvl & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | ((96 & UART_TXFIFO_EMPTY_THRHD) << UART_TXFIFO_EMPTY_THRHD_S) | UART_RX_FLOW_EN);
// set rx fifo trigger
WRITE_PERI_REG(UART_CONF1(UART0),
((0x10 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) |
((0x10 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) |
UART_RX_FLOW_EN |
(0x02 & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S |
UART_RX_TOUT_EN);
SET_PERI_REG_MASK(UART_INT_ENA(UART0), UART_RXFIFO_TOUT_INT_ENA | UART_FRM_ERR_INT_ENA);
// clear all interrupt
WRITE_PERI_REG(UART_INT_CLR(UART0), 0xffff);
// enable rx_interrupt
SET_PERI_REG_MASK(UART_INT_ENA(UART0), UART_RXFIFO_FULL_INT_ENA);
}
void HardwareSerial::printNumber(unsigned long n, uint8_t base) {
unsigned char nBuffer[8*sizeof(long)];
unsigned int i = 0;
while (n>0) {
nBuffer[i++] = n % base;
n /= base;
}
if (i==0) {
tx_one_char('0');
}
for (; i>0 ; i--) {
tx_one_char((char)((nBuffer[i-1]<10) ? ('0'+nBuffer[i-1]) : ('A'+nBuffer[i-1]-10)));
}
}
void HardwareSerial::printFloat(double n, uint8_t digits) {
if (n<0) {
tx_one_char('-');
n = -n;
}
double rounding = 0.5;
for (uint8_t i=0 ; i<digits ; ++i) rounding /= 10.0;
n += rounding;
unsigned long int_part = (unsigned long) n;
double rest = n - (double)int_part;
printNumber(int_part, DEC);
if (digits>0)
tx_one_char('.');
while (digits-- > 0) {
rest *= 10.0;
int toPrint = int(rest);
tx_one_char((char)('0'+toPrint));
rest -= toPrint;
}
}
HardwareSerial Serial = HardwareSerial();
|
#pragma once
// includes
namespace Debug
{
/// \brief process memory reader/writer
/// note that for reading from/writing to a process the appropriate system privilige
/// is necessary.
class ProcessMemory
{
public:
/// ctor; takes process id
ProcessMemory(DWORD dwProcessId): m_dwProcessId(dwProcessId){}
/// reads from process memory
bool Read(LPCVOID pAddress, LPVOID pBuffer, SIZE_T nLength);
/// reads from process memory
bool Write(LPVOID pAddress, LPCVOID pBuffer, SIZE_T nLength);
private:
/// process id
DWORD m_dwProcessId;
};
} // namespace Debug
|
#ifndef _PKEYWORD_H
#define _PKEYWORD_H
#include <string>
using std::string;
namespace PorkParserSpace
{
// Enumeration for keywords used in PorkScript
enum PKeyword { NONE, REQUIRES, DEF, SET, EDEF, DYNAMIC, DEFAULT,
STATE, TRUE, FALSE, ESET, RELIESON, FROM, TRIGGER, PRESENT,
N_PRESENT, INF, FOR, DEFINITIVE, NAME, DESC, MAP, ITEM,
ITEMLIST, ITEMDTAG, P, CURITEMAMT, IDENTIFIER, NUMCONST, BOOLCONST,
TEXTCONST, QUOTE, OPEN_PARA, CLOSE_PARA, COMMA, PERIOD, COLON, OPEN_BRACKET,
CLOSE_BRACKET, PLUS };
enum ParserLevels { EMPTY, MAPDEF, ITEMDEF, IMDYNSET, MSTATESET, MITEMLISTSET };
enum SentenceTypes { tNONE, SETDYN, SETPROP, SETDYNPROP, SETSTATE, SETITEMLIST, SETITEMDTAG,
DYNSETPROP, DYNSET, SETNAME, SETDESC, SETMODULE, SETDYNMODULE };
typedef std::pair<PKeyword, string> TokenPair;
// Prototype for ConvertPKeywordToString()
string ConvertPKeywordToString(PKeyword keyword);
}
#endif //_PKEYWORD_H
|
#include <Wire.h>
#include "SHT2x.h"
SHT2x sensor;
void setup() {
Serial.begin(9600);
Wire.begin();
sensor.begin();
Serial.println("Reading...");
Serial.println(sensor.readTemperature());
Serial.println(sensor.readHumidity());
Serial.println(sensor.heaterOn());
Serial.println("Heater On");
Serial.println(sensor.heaterOff());
Serial.println("Heater Off");
}
void loop() {
// put your main code here, to run repeatedly:
}
|
#include "Item.h"
RECT Item::getFrameRectFromType(eAirCraftType type)
{
switch (type)
{
case B:
return SpriteManager::getInstance()->getSourceRect(eID::AIRCRAFT, "b_ammo");
break;
case F:
return SpriteManager::getInstance()->getSourceRect(eID::AIRCRAFT, "f_ammo");
break;
case L:
return SpriteManager::getInstance()->getSourceRect(eID::AIRCRAFT, "l_ammo");
break;
case M:
return SpriteManager::getInstance()->getSourceRect(eID::AIRCRAFT, "m_ammo");
break;
case R:
return SpriteManager::getInstance()->getSourceRect(eID::AIRCRAFT, "r_ammo");
break;
case S:
return SpriteManager::getInstance()->getSourceRect(eID::AIRCRAFT, "s_ammo");
break;
case I:
break;
default:
break;
}
}
Item::Item(GVector2 position, eAirCraftType type) : BaseObject(eID::ITEM)
{
_startposition = position;
_type = type;
}
float Item::checkCollision(BaseObject* object, float dt)
{
auto collisionBody = (CollisionBody*)_listComponent["CollisionBody"];
auto objeciId = object->getId();
eDirection direction;
if (this->getVelocity().y > 0)
return 0.0;
if (collisionBody->checkCollision(object, direction, dt))
{
if (objeciId == eID::LAND || objeciId == eID::BRIDGE) // => ??
{
if (direction == eDirection::TOP)
{
auto gravity = (Gravity*)this->_listComponent["Gravity"];
gravity->setStatus(eGravityStatus::SHALLOWED);
gravity->setGravity(VECTOR2ZERO);
auto move = (Movement*) this->_listComponent["Movement"];
move->setVelocity(VECTOR2ZERO);
}
else if (direction == eDirection::BOTTOM){
return 0.0f;
}
}
if (objeciId == eID::BILL)
{
this->setStatus(eStatus::DESTROY);
((Bill*)object)->changeBulletType(this->_type);
}
}
return 0.0f;
}
void Item::init()
{
_sprite = SpriteManager::getInstance()->getSprite(eID::AIRCRAFT);
_sprite->setFrameRect(Item::getFrameRectFromType(_type));
_sprite->setScale(SCALE_FACTOR);
_sprite->setPosition(_startposition);
if (this->_type == eAirCraftType::I)
{
_animation = new Animation(_sprite, 0.07f);
_animation->addFrameRect(SpriteManager::getInstance()->getSourceRect(this->_id, "invul_1"));
_animation->addFrameRect(SpriteManager::getInstance()->getSourceRect(this->_id, "invul_2"));
_animation->addFrameRect(SpriteManager::getInstance()->getSourceRect(this->_id, "invul_3"));
}
Movement* movement = new Movement(VECTOR2ZERO, ITEM_FORCE, _sprite);
Gravity* gravity = new Gravity(ITEM_GRAVITY, movement);
CollisionBody* collisionBody = new CollisionBody(this);
this->_listComponent["Movement"] = movement;
this->_listComponent["Gravity"] = gravity;
this->_listComponent["CollisionBody"] = collisionBody;
this->setPhysicsBodySide(eDirection::ALL);
}
void Item::update(float deltatime)
{
if (this->_type == eAirCraftType::I)
{
_animation->update(deltatime);
}
for (auto component : _listComponent)
{
component.second->update(deltatime);
}
}
void Item::checkifOutofScreen()
{
if (this->getStatus() != eStatus::NORMAL)
return;
auto viewport = ((PlayScene*)SceneManager::getInstance()->getCurrentScene())->getViewport();
RECT screenBound = viewport->getBounding();
RECT thisBound = BaseObject::getBounding();
GVector2 position = this->getPosition();
if (thisBound.right < screenBound.left || thisBound.top < screenBound.bottom)
{
this->setStatus(eStatus::DESTROY);
}
}
void Item::draw(LPD3DXSPRITE spriteHandle, Viewport* viewport)
{
if (this->_type == eAirCraftType::I)
_animation->draw(spriteHandle, viewport);
else
_sprite->render(spriteHandle, viewport);
}
void Item::release()
{
for (auto component : _listComponent)
{
SAFE_DELETE(component.second);
}
_listComponent.clear();
SAFE_DELETE(_sprite);
SAFE_DELETE(_animation);
}
RECT Item::getBounding()
{
RECT baseBound = BaseObject::getBounding();
baseBound.left += (7 + this->getScale().x);
baseBound.right -= (7 - this->getScale().y);
return baseBound;
}
GVector2 Item::getVelocity()
{
auto move = (Movement*)this->_listComponent["Movement"];
return move->getVelocity();
}
Item::~Item()
{
}
|
#include "shaderc.h"
// Set the default allocator
namespace bgfx
{
static bx::DefaultAllocator s_allocator;
bx::AllocatorI* g_allocator = &s_allocator;
struct TinyStlAllocator
{
static void* static_allocate(size_t _bytes);
static void static_deallocate(void* _ptr, size_t /*_bytes*/);
};
void* TinyStlAllocator::static_allocate(size_t _bytes)
{
return BX_ALLOC(g_allocator, _bytes);
}
void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
{
if (NULL != _ptr)
{
BX_FREE(g_allocator, _ptr);
}
}
} // namespace bgfx
int main(int _argc, const char* _argv[])
{
return shaderc::compileShader(_argc, _argv);
}
|
#include <iostream>
#include "Worker.h"
using namespace std;
int main()
{
init();
int a;
int count = 0;
do {
cout << "\n\t 1.Add new worker \n";
cout << "\t 2.Redakr \n";
cout << "\t 3.Search by age \n";
cout << "\t 4.Search by sekond name \n";
cout << "\t 5.Dellet \n";
cout << "\t 6.Write in file \n";
cout << "\t 7.Exit \n";
cout << "\n\t Select an action: ";
cin >> a;
system("cls");
switch (a)
{
case 1:
addinfo();
break;
case 2:
redakt();
break;
case 3:
shorchbyAge();
break;
case 4:
shourchbySekondname();
break;
case 5:
dleteWorkers();
break;
case 6:
writeinfile();
count++;
break;
case 7:
writeinfile();
break;
}
} while (a != 7);
}
|
/*
1826. 연료 채우기
그리드(탐욕) 알고리즘
힙
연료가 거리보다 작을 때 계속 반복
1) 주유소 정보에서 거리순으로 정렬
2) 현재 연료(=주행가능한 거리) 보다 짧은 거리의 주유소 탐색
3) 그 주요소 탐색 후 우선순위 큐에 주유가능한 연료 넣기
4) 가장 앞에 있는 연료 추가, pop, cnt++
5) 만약 주유 가능한 연료가 없으면(큐 비어있으면) 도착 실패
*/
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#define MAX 101
using namespace std;
int N, a, b, L, P, Cnt = 0;
vector<pair<int, int>> Oil;
priority_queue<int> PQ;
void Sort()
{
sort(Oil.begin(), Oil.end());
}
void Input()
{
cin >> N;
for(int i = 0; i < N; i++)
{
cin >> a >> b;
Oil.push_back({ a, b });
}
cin >> L >> P;
}
void Solution()
{
int Start = -1;
while (P < L)
{
for(int i = Start + 1; i < Oil.size(); i++)
{
if(Oil[i].first > P) break;
PQ.push(Oil[i].second);
Start = i;
}
if(PQ.empty() == false)
{
P += PQ.top();
PQ.pop();
Cnt++;
}
else
{
break;
}
}
}
void Solve()
{
Solution();
if(P >= L) cout << Cnt << endl;
else cout << "-1" << endl;
}
int main()
{
Input();
Sort();
Solve();
return 0;
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <bitset>
#include <utility>
#include <set>
#include <math.h>
#define pi acos(-1.0)
#define INF 10000000
using namespace std;
struct data
{
int x,y;
};
bool ara[1001][1001];
int seen[1000+1][1000+1];
int r,c,cnt,source1, source2;
void bfs(int s1,int s2,int d1,int d2)
{
queue<data>q;
int dis;
bool ck=false;
///map<int,map<int,int> >seen;
memset(seen,0,sizeof(seen));
q.push({s1,s2});
while(!q.empty())
{
data top=q.front();
for(int i=0;i<4;i++)
{
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int fx=top.x+dx[i];
int fy=top.y+dy[i];
if(fx>=0 && fy>=0 && fx<r && fy<c && seen[fx][fy]==0 && (fx!=source1 || fy!=source2) && ara[fx][fy]!=true && seen[fx][fy]==0)
{
///if(ara[fx][fy]!=true && seen[fx][fy]==0)
///{
seen[fx][fy]=seen[top.x][top.y]+1;
dis=seen[fx][fy];
if(fx==d1 && fy==d2)
{
ck=true;
///cout<<dis<<endl;
printf("%d\n",dis);
break;
}
q.push({fx,fy});
///}
}
}
q.pop();
if(ck==true)break;
}
//return dis;
}
int main()
{
int g,rowName,bomb,colName,s1,s2,d1,d2;
while(true)
{
scanf("%d %d",&r,&c);
if(r==0 && c==0)break;
///cin>>g;
scanf("%d",&g);
cnt=0;
memset(ara,false,sizeof(ara));
for(int a=0;a<g;a++)
{
///cin>>rowName>>bomb;
scanf("%d %d",&rowName,&bomb);
for(int i=0;i<bomb;i++)
{
///cin>>colName;
scanf("%d",&colName);
ara[rowName][colName]=1;
}
}
///cin>>s1>>s2;
scanf("%d %d %d %d",&s1,&s2,&d1,&d2);
source1=s1;
source2=s2;
///cin>>d1>>d2;
if(s1==d1 && s2==d2)printf("0\n");
else
bfs(s1,s2,d1,d2);
//cout<<res<<endl;
}
return 0;
}
|
#include "global_utility.h"
int full_initial(GLFWwindow* &window, int _width, int _height) {
/*
窗口初始化
*/
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
glfwWindowHint(GLFW_SAMPLES, 4);
window = glfwCreateWindow(_width, _height, "Homework 3", nullptr, nullptr);
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
return -1;
}
glfwMakeContextCurrent(window);
/*
GLEW 初始化
*/
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
glEnable(GL_MULTISAMPLE);
glEnable(GL_DEPTH_TEST);
/*
回调函数绑定
*/
glfwSetKeyCallback(window, callback::key_callback);
glfwSetMouseButtonCallback(window, callback::mouse_button_callback);
glfwSetCursorPosCallback(window, callback::mouse_callback);
glfwSetScrollCallback(window, callback::scroll_callback);
/*
素材读入
*/
if (callback::callback_init())
return -1;
if (shader::shader_init())
return -1;
if (texture::texture_init())
return -1;
if (coord::coord_init())
return -1;
if (time_system::time_system_init())
return -1;
if (light::init())
return -1;
return 0;
}
std::vector<std::string> split(const std::string &str, const char &ch) {
std::string now; std::vector<std::string> ans;
for (size_t i = 0; i < str.size(); ++ i)
{
if (ch == str.at(i))
{
ans.push_back(now);
now = "";
}
else
now += str.at(i);
}
ans.push_back(now);
return ans;
}
|
/***********************************************************************
created: Tue Mar 3 2009
author: Paul D Turner (parts based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Irrlicht/Renderer.h"
#include "CEGUI/RendererModules/Irrlicht/GeometryBuffer.h"
#include "CEGUI/RendererModules/Irrlicht/WindowTarget.h"
#include "CEGUI/RendererModules/Irrlicht/TextureTarget.h"
#include "CEGUI/RendererModules/Irrlicht/Texture.h"
#include "CEGUI/RendererModules/Irrlicht/ResourceProvider.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/RendererModules/Irrlicht/EventPusher.h"
#include "CEGUI/RendererModules/Irrlicht/ImageCodec.h"
#include <irrlicht.h>
#include <algorithm>
// Start of CEGUI namespace section
namespace CEGUI
{
String IrrlichtRenderer::d_rendererID("CEGUI::IrrlichtRenderer "
"- Official Irrlicht based 2nd generation renderer module.");
//----------------------------------------------------------------------------//
IrrlichtRenderer& IrrlichtRenderer::bootstrapSystem(irr::IrrlichtDevice& device,
const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
if (System::getSingletonPtr())
throw InvalidRequestException(
"CEGUI::System object is already initialised.");
IrrlichtRenderer& renderer = IrrlichtRenderer::create(device);
IrrlichtResourceProvider& rp =
createIrrlichtResourceProvider(*device.getFileSystem());
IrrlichtImageCodec& ic = createIrrlichtImageCodec(*device.getVideoDriver());
System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic);
return renderer;
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroySystem()
{
System* const sys = System::getSingletonPtr();
if (!sys)
throw InvalidRequestException(
"CEGUI::System object is not created or was already destroyed.");
IrrlichtRenderer* const renderer =
static_cast<IrrlichtRenderer*>(sys->getRenderer());
IrrlichtResourceProvider* const rp =
static_cast<IrrlichtResourceProvider*>(sys->getResourceProvider());
IrrlichtImageCodec* const ic =
&static_cast<IrrlichtImageCodec&>(sys->getImageCodec());
System::destroy();
destroyIrrlichtImageCodec(*ic);
destroyIrrlichtResourceProvider(*rp);
destroy(*renderer);
}
//----------------------------------------------------------------------------//
IrrlichtRenderer& IrrlichtRenderer::create(irr::IrrlichtDevice& device,
const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
return *new IrrlichtRenderer(device);
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroy(IrrlichtRenderer& renderer)
{
delete &renderer;
}
//----------------------------------------------------------------------------//
IrrlichtResourceProvider&
IrrlichtRenderer::createIrrlichtResourceProvider(irr::io::IFileSystem& fs)
{
return *new IrrlichtResourceProvider(fs);
}
//----------------------------------------------------------------------------//
void
IrrlichtRenderer::destroyIrrlichtResourceProvider(IrrlichtResourceProvider& rp)
{
delete &rp;
}
//----------------------------------------------------------------------------//
IrrlichtImageCodec& IrrlichtRenderer::createIrrlichtImageCodec(
irr::video::IVideoDriver& driver)
{
return *new IrrlichtImageCodec(driver);
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroyIrrlichtImageCodec(IrrlichtImageCodec& ic)
{
delete ⁣
}
//----------------------------------------------------------------------------//
bool IrrlichtRenderer::injectEvent(const irr::SEvent& event)
{
return d_eventPusher->OnEvent(event);
}
//----------------------------------------------------------------------------//
RenderTarget& IrrlichtRenderer::getDefaultRenderTarget()
{
return *d_defaultTarget;
}
//----------------------------------------------------------------------------//
GeometryBuffer& IrrlichtRenderer::createGeometryBuffer()
{
IrrlichtGeometryBuffer* gb =
new IrrlichtGeometryBuffer(*d_driver);
d_geometryBuffers.push_back(gb);
return *gb;
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer)
{
GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(),
d_geometryBuffers.end(),
&buffer);
if (d_geometryBuffers.end() != i)
{
d_geometryBuffers.erase(i);
delete &buffer;
}
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroyAllGeometryBuffers()
{
while (!d_geometryBuffers.empty())
destroyGeometryBuffer(**d_geometryBuffers.begin());
}
//----------------------------------------------------------------------------//
TextureTarget* IrrlichtRenderer::createTextureTarget(bool addStencilBuffer)
{
if (!d_driver->queryFeature(irr::video::EVDF_RENDER_TO_TARGET))
return 0;
TextureTarget* tt = new IrrlichtTextureTarget(*this, *d_driver, addStencilBuffer);
d_textureTargets.push_back(tt);
return tt;
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroyTextureTarget(TextureTarget* target)
{
TextureTargetList::iterator i = std::find(d_textureTargets.begin(),
d_textureTargets.end(),
target);
if (d_textureTargets.end() != i)
{
d_textureTargets.erase(i);
delete target;
}
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroyAllTextureTargets()
{
while (!d_textureTargets.empty())
destroyTextureTarget(*d_textureTargets.begin());
}
//----------------------------------------------------------------------------//
Texture& IrrlichtRenderer::createTexture(const String& name)
{
throwIfNameExists(name);
IrrlichtTexture* t = new IrrlichtTexture(*this, *d_driver, name);
d_textures[name] = t;
logTextureCreation(name);
return *t;
}
//----------------------------------------------------------------------------//
Texture& IrrlichtRenderer::createTexture(const String& name,
const String& filename,
const String& resourceGroup)
{
throwIfNameExists(name);
IrrlichtTexture* t = new IrrlichtTexture(*this, *d_driver, name,
filename, resourceGroup);
d_textures[name] = t;
logTextureCreation(name);
return *t;
}
//----------------------------------------------------------------------------//
Texture& IrrlichtRenderer::createTexture(const String& name, const Sizef& size)
{
throwIfNameExists(name);
IrrlichtTexture* t = new IrrlichtTexture(*this, *d_driver, name, size);
d_textures[name] = t;
logTextureCreation(name);
return *t;
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::throwIfNameExists(const String& name) const
{
if (d_textures.find(name) != d_textures.end())
throw AlreadyExistsException(
"[IrrlichtRenderer] Texture already exists: " + name);
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::logTextureCreation(const String& name)
{
Logger* logger = Logger::getSingletonPtr();
if (logger)
logger->logEvent("[IrrlichtRenderer] Created texture: " + name);
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroyTexture(Texture& texture)
{
destroyTexture(texture.getName());
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroyTexture(const String& name)
{
TextureMap::iterator i = d_textures.find(name);
if (d_textures.end() != i)
{
logTextureDestruction(name);
delete i->second;
d_textures.erase(i);
}
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::logTextureDestruction(const String& name)
{
Logger* logger = Logger::getSingletonPtr();
if (logger)
logger->logEvent("[IrrlichtRenderer] Destroyed texture: " + name);
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::destroyAllTextures()
{
while (!d_textures.empty())
destroyTexture(d_textures.begin()->first);
}
//----------------------------------------------------------------------------//
Texture& IrrlichtRenderer::getTexture(const String& name) const
{
TextureMap::const_iterator i = d_textures.find(name);
if (i == d_textures.end())
throw UnknownObjectException(
"[IrrlichtRenderer] Texture does not exist: " + name);
return *i->second;
}
//----------------------------------------------------------------------------//
bool IrrlichtRenderer::isTextureDefined(const String& name) const
{
return d_textures.find(name) != d_textures.end();
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::beginRendering()
{
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::endRendering()
{
}
//----------------------------------------------------------------------------//
void IrrlichtRenderer::setDisplaySize(const Sizef& sz)
{
if (sz != d_displaySize)
{
d_displaySize = sz;
// FIXME: This is probably not the right thing to do in all cases.
Rectf area(d_defaultTarget->getArea());
area.setSize(sz);
d_defaultTarget->setArea(area);
}
}
//----------------------------------------------------------------------------//
const Sizef& IrrlichtRenderer::getDisplaySize() const
{
return d_displaySize;
}
//----------------------------------------------------------------------------//
unsigned int IrrlichtRenderer::getMaxTextureSize() const
{
return d_maxTextureSize;
}
//----------------------------------------------------------------------------//
const String& IrrlichtRenderer::getIdentifierString() const
{
return d_rendererID;
}
//----------------------------------------------------------------------------//
IrrlichtRenderer::IrrlichtRenderer(irr::IrrlichtDevice& device) :
d_device(device),
d_driver(d_device.getVideoDriver()),
d_displaySize(static_cast<float>(d_driver->getScreenSize().Width),
static_cast<float>(d_driver->getScreenSize().Height)),
d_defaultTarget(new IrrlichtWindowTarget(*this, *d_driver)),
d_maxTextureSize(2048),
d_eventPusher(new IrrlichtEventPusher(d_device.getCursorControl())),
d_supportsNSquareTextures(d_driver->queryFeature(irr::video::EVDF_TEXTURE_NSQUARE)),
d_supportsNPOTTextures(d_driver->queryFeature(irr::video::EVDF_TEXTURE_NPOT))
{
if (d_driver->queryFeature(video::EVDF_RENDER_TO_TARGET))
d_rendererID += String(" RenderTarget support is enabled.");
else
d_rendererID += String(" RenderTarget support is unavailable :(");
}
//----------------------------------------------------------------------------//
IrrlichtRenderer::~IrrlichtRenderer()
{
destroyAllGeometryBuffers();
destroyAllTextureTargets();
destroyAllTextures();
delete d_eventPusher;
delete d_defaultTarget;
}
//----------------------------------------------------------------------------//
Sizef IrrlichtRenderer::getAdjustedTextureSize(const Sizef& sz) const
{
Sizef out(sz);
// if we can't support non power of two sizes, get appropriate POT values.
if (!d_supportsNPOTTextures)
{
out.d_width = getNextPOTSize(out.d_width);
out.d_height = getNextPOTSize(out.d_height);
}
// if we can't support non square textures, make size square.
if (!d_supportsNSquareTextures)
out.d_width = out.d_height = std::max(out.d_width, out.d_height);
return out;
}
//----------------------------------------------------------------------------//
float IrrlichtRenderer::getNextPOTSize(const float f)
{
unsigned int size = static_cast<unsigned int>(f);
// if not power of 2
if ((size & (size - 1)) || !size)
{
int log = 0;
// get integer log of 'size' to base 2
while (size >>= 1)
++log;
// use log to calculate value to use as size.
size = (2 << log);
}
return static_cast<float>(size);
}
//----------------------------------------------------------------------------//
const IrrlichtEventPusher* IrrlichtRenderer::getEventPusher() const
{
return d_eventPusher;
}
//----------------------------------------------------------------------------//
bool IrrlichtRenderer::isTexCoordSystemFlipped() const
{
return false;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
|
#pragma once
#include "../utility/position.h"
#include "../utility/grid.h"
enum ObstructionType
{
OT_EMPTY,
OT_OBSTRUCTED,
OT_CONSIDERED
};
class ObstructionMap : public Grid<ObstructionType>
{
public:
ObstructionMap(int size_x, int size_y);
bool isObstructed(Position);
bool isConsidered(Position);
bool isOpen(Position);
friend std::ostream& operator<<(std::ostream & os, const ObstructionMap & map)
{
for (int y = 0; y < map.getHeight(); y++)
{
for (int x = 0; x < map.getWidth(); x++)
{
if (map.at(x, y) == OT_EMPTY)
os << ".";
else if (map.at(x, y) == OT_OBSTRUCTED)
os << "X";
else if (map.at(x, y) == OT_CONSIDERED)
os << "o";
}
os << std::endl;
}
return os;
}
};
|
//Isaac Mooney June, 2018 for jet mass analysis in simulation
#include "params.hh"
#include "funcs.hh"
#include "TStarJetPicoDefinitions.h"
using namespace fastjet;
using namespace std;
using namespace Analysis;
typedef fastjet::contrib::SoftDrop SD;
// -------------------------
// Command line arguments: ( Defaults
// Defined for debugging in main )
// [0]: output directory
// [1]: name for the histogram file
// [2]: input data: can be a single .root or a .txt or .list of root files - should always be last argument
int main (int argc, const char ** argv) {
// TStarJetPicoDefinitions::SetDebugLevel(0);
TH1::SetDefaultSumw2( ); // Histograms will calculate gaussian errors
TH2::SetDefaultSumw2( );
TH3::SetDefaultSumw2( );
// Read in command line arguments
// ------------------------------
// Defaults
std::string outputDir = "out/"; // directory where everything will be saved
std::string outFileName = "test.root";
std::string chainList = "simlist.txt"; // input file: can be .root, .txt, .list
bool full = 1; //full = 1 => ch+ne
bool ge_or_py = 1; //ge_or_py = 1 => ge. ge_or_py = 0 => py
// Now check to see if we were given modifying arguments
switch ( argc ) {
case 1: // Default case
__OUT("Using Default Settings");
break;
case 6: { // Custom case
__OUT("Using Custom Settings");
std::vector<std::string> arguments( argv+1, argv+argc );
// Set non-default values
// ----------------------
// output and file names
outputDir = arguments[0];
outFileName = arguments[1];
if (arguments[2] == "ch") {full = 0;} else {full = 1;}
if (arguments[3] == "ge") {ge_or_py = 1;} else if (arguments[3] == "py") {ge_or_py = 0;} else {cerr << "Not a valid flag!" << endl; exit(1);}
chainList = arguments[4];
cout << outputDir << " " << outFileName << " " << full << " " << " " << ge_or_py << " " << chainList << endl;
break;
}
default: { // Error: invalid custom settings
__ERR("Invalid number of command line arguments");
return -1;
break;
}
}
// Initialize readers and provide chains
TStarJetPicoReader Reader; TChain* Chain;
if (ge_or_py == 0) {//pythia
Chain = new TChain( "JetTreeMc" ); // PURE PYTHIA DATA (particle)
}
else {
Chain = new TChain( "JetTree" ); // CORRESPONDING GEANT DATA (detector)
}
// Check to see if the input is a .root file or a .txt
bool inputIsRoot = Analysis::HasEnding( chainList.c_str(), ".root" );
bool inputIsTxt = Analysis::HasEnding( chainList.c_str(), ".txt" );
bool inputIsList = Analysis::HasEnding( chainList.c_str(), ".list" );
// If its a recognized file type, build the chain
// If its not recognized, exit
if ( inputIsRoot ) { Chain->Add( chainList.c_str()); }
else if ( inputIsTxt ) { Chain = TStarJetPicoUtils::BuildChainFromFileList(chainList.c_str());}
else if ( inputIsList) { Chain = TStarJetPicoUtils::BuildChainFromFileList(chainList.c_str());}
else { __ERR("data file is not recognized type: .root or .txt only.") return -1; }
//initialize the readers!
if (ge_or_py == 0) {//pythia
InitReader(Reader, Chain, nEvents, truth_triggerString, truth_absMaxVz, truth_vZDiff, truth_evPtMax, truth_evEtMax, truth_evEtMin, truth_DCA, truth_NFitPts, truth_FitOverMaxPts, sim_maxEtTow, 0.9999, false, sim_badTowers, sim_bad_run_list);
}
if (ge_or_py == 1) {//geant
InitReader(Reader, Chain, nEvents, det_triggerString, det_absMaxVz, det_vZDiff, det_evPtMax, det_evEtMax, det_evEtMin, det_DCA, det_NFitPts, det_FitOverMaxPts, sim_maxEtTow, 0.9999, false, sim_badTowers, sim_bad_run_list);
}
TStarJetPicoEventHeader* header; TStarJetPicoEvent* event;
TStarJetVectorContainer<TStarJetVector> * container; TStarJetVector* sv;
int EventID;
double n_jets, wt;
vector<vector<double> > consDist; vector<vector<double> > consGirth;
vector<vector<double> > conspT;
vector<double> jetMult; vector<double> jetGirth;
vector<double> Pt; vector<double> Eta; vector<double> Phi; vector<double> M; vector<double> E;
vector<double> ch_e_frac;
vector<double> zg; vector<double> rg; vector<double> mg; vector<double> ptg;
vector<double> mcd;
vector<double> tau0; vector<double> tau05; vector<double> tau_05; vector<double> tau_1;
vector<double> tau0_g; vector<double> tau05_g; vector<double> tau_05_g; vector<double> tau_1_g;
TTree *eventTree = new TTree("event","event");
eventTree->Branch("n_jets", &n_jets);
eventTree->Branch("conspT",&conspT);
eventTree->Branch("consDist", &consDist); eventTree->Branch("consGirth",&consGirth);
eventTree->Branch("jetGirth",&jetGirth); eventTree->Branch("jetMult",&jetMult);
eventTree->Branch("Pt", &Pt); eventTree->Branch("Eta",&Eta); eventTree->Branch("Phi",&Phi); eventTree->Branch("M",&M); eventTree->Branch("E",&E);
eventTree->Branch("ch_e_frac", &ch_e_frac);
eventTree->Branch("zg", &zg); eventTree->Branch("rg", &rg); eventTree->Branch("mg", &mg); eventTree->Branch("ptg",&ptg);
eventTree->Branch("mcd",&mcd);
eventTree->Branch("tau0",&tau0); eventTree->Branch("tau05",&tau05); eventTree->Branch("tau_05",&tau_05); eventTree->Branch("tau_1",&tau_1);
eventTree->Branch("tau0_g",&tau0_g); eventTree->Branch("tau05_g",&tau05_g); eventTree->Branch("tau_05_g",&tau_05_g); eventTree->Branch("tau_1_g",&tau_1_g);
eventTree->Branch("weight", &wt); eventTree->Branch("EventID", &EventID);
//TEST
/*
TH1D* pt23 = new TH1D("pt23","",80,0,80);
TH1D* pt34 = new TH1D("pt34","",80,0,80);
TH1D* pt45 = new TH1D("pt45","",80,0,80);
TH1D* pt57 = new TH1D("pt57","",80,0,80);
TH1D* pt79 = new TH1D("pt79","",80,0,80);
TH1D* pt911 = new TH1D("pt911","",80,0,80);
TH1D* pt1115 = new TH1D("pt1115","",80,0,80);
TH1D* pt1520 = new TH1D("pt1520","",80,0,80);
TH1D* pt2025 = new TH1D("pt2025","",80,0,80);
TH1D* pt2535 = new TH1D("pt2535","",80,0,80);
TH1D* pt35plus = new TH1D("pt35plus","",80,0,80);
TH1D* pt23w = new TH1D("pt23w","",80,0,80);
TH1D* pt34w = new TH1D("pt34w","",80,0,80);
TH1D* pt45w = new TH1D("pt45w","",80,0,80);
TH1D* pt57w = new TH1D("pt57w","",80,0,80);
TH1D* pt79w = new TH1D("pt79w","",80,0,80);
TH1D* pt911w = new TH1D("pt911w","",80,0,80);
TH1D* pt1115w = new TH1D("pt1115w","",80,0,80);
TH1D* pt1520w = new TH1D("pt1520w","",80,0,80);
TH1D* pt2025w = new TH1D("pt2025w","",80,0,80);
TH1D* pt2535w = new TH1D("pt2535w","",80,0,80);
TH1D* pt35plusw = new TH1D("pt35plusw","",80,0,80);
TH1D* ptall = new TH1D("ptall","",80,0,80);
TH1D* ptallw = new TH1D("ptallw","",80,0,80);
*/
//Creating SoftDrop grooming object
contrib::SoftDrop sd(Beta,z_cut,R0);
cout << "SoftDrop groomer is: " << sd.description() << endl;
//SELECTORS
// Constituent selectors
// ---------------------
Selector select_track_rap = fastjet::SelectorAbsRapMax(max_track_rap);
Selector select_lopt = fastjet::SelectorPtMin( partMinPt );
Selector select_loptmax = fastjet::SelectorPtMax( partMaxPt );
Selector spart = select_track_rap * select_lopt * select_loptmax;
// Jet candidate selectors
// -----------------------
Selector select_jet_rap = fastjet::SelectorAbsRapMax(max_rap);
Selector select_jet_m_min;
Selector select_jet_pt_min;
if (ge_or_py == 0) {//pythia
select_jet_pt_min = fastjet::SelectorPtMin( jet_ptmin );
select_jet_m_min = fastjet::SelectorMassMin( 0.0 );
}
else {
select_jet_pt_min = fastjet::SelectorPtMin( det_jet_ptmin );
select_jet_m_min = fastjet::SelectorMassMin( mass_min );
}
Selector select_jet_pt_max = fastjet::SelectorPtMax( jet_ptmax );
Selector sjet = select_jet_rap && select_jet_pt_min && select_jet_pt_max && select_jet_m_min;
JetDefinition jet_def(antikt_algorithm, R); // JET DEFINITION
TString Filename;
// Particle containers & counters
vector<PseudoJet> Particles, Jets, GroomedJets;
int nEvents = 0; int NJets = 0; //int EventID;
//1=inclusive, 2=lead
int counter_debug1 = 0, counter_debug2 = 0;
//for later use looking up PDG masses using particle PID
TDatabasePDG *pdg = new TDatabasePDG();
// LOOP!
while ( Reader.NextEvent() ) {
//clearing vectors
conspT.clear(); consDist.clear(); consGirth.clear(); jetMult.clear(); jetGirth.clear();
Pt.clear(); Eta.clear(); Phi.clear(); M.clear(); E.clear();
zg.clear(); rg.clear(); mg.clear(); ptg.clear();
ch_e_frac.clear(); mcd.clear();
tau0.clear(); tau05.clear(); tau_05.clear(); tau_1.clear();
tau0_g.clear(); tau05_g.clear(); tau_05_g.clear(); tau_1_g.clear();
//initializing variables to -9999
n_jets = -9999; wt = -9999; EventID = -9999;
event = Reader.GetEvent(); header = event->GetHeader();
EventID = Reader.GetNOfCurrentEvent();
//TEMP!!!!!!!!!
//if (EventID == 6868 || EventID == 8999 || EventID == 5290) { continue; }
Particles.clear();
Jets.clear();
GroomedJets.clear();
nEvents ++; Reader.PrintStatus(10); // Print out reader status every 10 seconds
event = Reader.GetEvent(); header = event->GetHeader(); // Get event header and event
container = Reader.GetOutputContainer(); // container
Filename = Reader.GetInputChain()->GetCurrentFile()->GetName();
//TEST!!! REMOVE LATER IF THIS DOESN'T DO THE TRICK
// if (((string) Filename).find("2_3_") != std::string::npos) {continue;}
wt = LookupRun12Xsec( Filename );
// GATHER PARTICLES
bool py = 0;
if (ge_or_py == 0) { py = 1;}//pythia
GatherParticles ( container, sv, Particles, 1, py, pdg); // first bool flag: 0 signifies charged-only, 1 = ch+ne; particles: second bool flag: pythia = 0, ge = 1
vector<PseudoJet> cut_Particles = spart(Particles); //applying constituent cuts
ClusterSequence Cluster(cut_Particles, jet_def); // CLUSTER BOTH
vector<PseudoJet> JetsInitial;
if (ge_or_py == 0) {//pythia
JetsInitial = sorted_by_pt(sjet(Cluster.inclusive_jets())); // EXTRACT JETS
}
else {
JetsInitial = sorted_by_pt(sjet(Cluster.inclusive_jets())); //apply jet cuts in Geant
}
vector<PseudoJet> Jets;
//Implementing a neutral energy fraction cut of 90% on inclusive det-level jets
if (ge_or_py == 1) { //geant
ApplyNEFSelection(JetsInitial, Jets);
}
else {Jets = JetsInitial;}
//loop over the jets which passed cuts, groom them, and add to a vector (sorted by pt of the original jet)
for (int i = 0; i < Jets.size(); ++ i) {
GroomedJets.push_back(sd(Jets[i]));
}
if (DiscardEvent(Filename, Jets, Jets)) { counter_debug1 ++; continue; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~TREES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
n_jets = Jets.size();
/*
//TEST!
for (int i = 0; i < Jets.size(); ++ i) {ptall->Fill(Jets[i].pt()); ptallw->Fill(Jets[i].pt(), wt);}
if (((string) Filename).find("2_3_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt23->Fill(Jets[i].pt()); pt23w->Fill(Jets[i].pt(), wt); if (Jets[i].pt() > 15) {cout << "ANSWER: " << EventID << endl;}}}
if (((string) Filename).find("3_4_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt34->Fill(Jets[i].pt());pt34w->Fill(Jets[i].pt(), wt); }}
if (((string) Filename).find("4_5_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt45->Fill(Jets[i].pt());pt45w->Fill(Jets[i].pt(), wt);}}
if (((string) Filename).find("5_7_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt57->Fill(Jets[i].pt());pt57w->Fill(Jets[i].pt(), wt);}}
if (((string) Filename).find("7_9_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt79->Fill(Jets[i].pt());pt79w->Fill(Jets[i].pt(), wt);}}
if (((string) Filename).find("9_11_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt911->Fill(Jets[i].pt());pt911w->Fill(Jets[i].pt(), wt);}}
if (((string) Filename).find("11_15_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt1115->Fill(Jets[i].pt());pt1115w->Fill(Jets[i].pt(), wt);}}
if (((string) Filename).find("15_20_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt1520->Fill(Jets[i].pt());pt1520w->Fill(Jets[i].pt(), wt);}}
if (((string) Filename).find("20_25_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt2025->Fill(Jets[i].pt());pt2025w->Fill(Jets[i].pt(), wt);}}
if (((string) Filename).find("25_35_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt2535->Fill(Jets[i].pt());pt2535w->Fill(Jets[i].pt(), wt);}}
if (((string) Filename).find("35_-1_") != std::string::npos) {for (int i = 0; i < Jets.size(); ++ i) {pt35plus->Fill(Jets[i].pt());pt35plusw->Fill(Jets[i].pt(), wt);}} */
NJets += Jets.size(); // Save jet info and add jets to total
for (int i = 0; i < n_jets; ++ i) {
double jet_girth = 0;
vector<double> cons_girth;
vector<double> cons_dist;
vector<double> cons_pt;
for (int j = 0; j < Jets[i].constituents().size(); ++ j) {
const PseudoJet cons = Jets[i].constituents()[j];
cons_pt.push_back(cons.pt());
double consR = fabs(cons.delta_R(Jets[i]));
cons_dist.push_back(consR);
double part_girth = consR * cons.pt() / (double) Jets[i].pt();
cons_girth.push_back(part_girth);
jet_girth += part_girth;
}
conspT.push_back(cons_pt);
consDist.push_back(cons_dist);
consGirth.push_back(cons_girth);
jetGirth.push_back(jet_girth);
jetMult.push_back(Jets[i].constituents().size());
Pt.push_back(Jets[i].pt()); Eta.push_back(Jets[i].eta()); Phi.push_back(Jets[i].phi());
M.push_back(Jets[i].m()); E.push_back(Jets[i].e());
zg.push_back(GroomedJets[i].structure_of<SD>().symmetry()); rg.push_back(GroomedJets[i].structure_of<SD>().delta_R());
mg.push_back(GroomedJets[i].m()); ptg.push_back(GroomedJets[i].pt());
double m2 = (Jets[i].m())*(Jets[i].m()); double gm2 = (GroomedJets[i].m())*(GroomedJets[i].m());
double m_cd = (double) sqrt(m2 - gm2); if ((m2 - gm2) < 10e-10) {m_cd = 0;}
mcd.push_back(m_cd);
double ch_e = 0; double tot_e = 0;//names are misnomers here since we use pT, not E.
vector<PseudoJet> cons = Jets[i].constituents();
for (int j = 0; j < cons.size(); ++ j) {
if (cons[j].user_index() != 0) {ch_e += cons[j].pt();}
tot_e += cons[j].pt();
}
ch_e_frac.push_back(ch_e/(double)tot_e);
//to be filled with actual values later
tau0.push_back(0); tau05.push_back(0); tau_05.push_back(0); tau_1.push_back(0);
tau0_g.push_back(0); tau05_g.push_back(0); tau_05_g.push_back(0); tau_1_g.push_back(0);
}
if (Jets.size() != 0) {
eventTree->Fill();
}
}
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ END EVENT LOOP! ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
TFile *fout = new TFile( ( outputDir + outFileName ).c_str() ,"RECREATE");
std::cout << std::endl << std::endl << "Of " << nEvents << " events" << std::endl;
std::cout << NJets << " jets have been found" << std::endl;
std::cout <<std::endl << "Writing to: " << fout->GetName() << std::endl << std::endl;
eventTree->Write();
/*
pt23->Write(); pt34->Write(); pt45->Write(); pt57->Write(); pt79->Write(); pt911->Write(); pt1115->Write(); pt1520->Write(); pt2025->Write(); pt2535->Write(); pt35plus->Write();
pt23w->Write(); pt34w->Write(); pt45w->Write(); pt57w->Write(); pt79w->Write(); pt911w->Write(); pt1115w->Write(); pt1520w->Write(); pt2025w->Write(); pt2535w->Write(); pt35plusw->Write();
ptall->Write(); ptallw->Write();*/
fout->Close();
return 0;
}
|
#include "easytf/easytf.h"
#include "easytf/easytf_assert.h"
#include "easytf/easytf_logger.h"
easytf::EasyTFGraph::EasyTFGraph()
{
logCritical("EasyTFGraph construct function begin.");
logCritical("EasyTFGraph construct function end.");
}
void easytf::EasyTFGraph::push_node(const easytf::Node& node)
{
logCritical("EasyTFGraph::push_node begin.");
logCritical("op : %s", node.op.first.c_str());
ops[node.op.first] = node.op.second;
logCritical("src_entitys:");
for (auto iter = node.src_entitys.begin(); iter != node.src_entitys.end(); iter++)
{
const std::string entity_name = iter->first;
const std::shared_ptr<Entity> entity = iter->second;
entitys[entity_name] = entity;
logCritical(" %s", entity_name.c_str());
}
logCritical("dst_entitys:");
for (auto iter = node.dst_entitys.begin(); iter != node.dst_entitys.end(); iter++)
{
const std::string entity_name = iter->first;
const std::shared_ptr<Entity> entity = iter->second;
entitys[entity_name] = entity;
logCritical(" %s", entity_name.c_str());
}
nodes.push_back(node);
logCritical("EasyTFGraph::push_node end.");
}
void easytf::EasyTFGraph::build()
{
logCritical("EasyTFGraph::build begin.");
//todo
logCritical("EasyTFGraph::build end.");
}
void easytf::EasyTFGraph::run()
{
logCritical("EasyTFGraph::run begin.");
for (size_t i = 0; i < nodes.size();i++)
{
Node& node = nodes[i];
const std::string op_name = node.op.first;
std::shared_ptr<Operator> op = node.op.second;
logCritical("op %s forward begin.", op_name.c_str());
op->forward(node.src_entitys, node.dst_entitys);
logCritical("op %s forward end.", op_name.c_str());
}
logCritical("EasyTFGraph::run end.");
}
std::shared_ptr<easytf::Entity> easytf::EasyTFGraph::get_entity(const std::string& id)
{
return entitys[id];
}
|
#include<iostream>
using namespace std;
/*
userNodes is a class with multiple nodes representing users
printRequestingNode is a friend class to userNodes to print the userName and userID
pageCounter is a friend function to userNodes to print the number of pages from that class
*/
class userNodes{
const char* _userName;
int _userID;
int _pages;
public:
userNodes(const char* userName="dummy",int userID = 0,int pages=0): _userName(userName), _userID(userID), _pages(pages) {}
friend class printRequestingNode;
friend void pageCounter(userNodes&);
};
void pageCounter(userNodes& un){
cout <<"user "<<un._userName<<" printing "<< un._pages <<" pages"<<endl;
}
class printRequestingNode{
public:
void print(userNodes& unode){
cout << "userName="<<unode._userName << endl;
cout << "userID="<<unode._userID << endl;
}
};
int main(){
userNodes node1,node2("chopra",100,11),node3("gchop",144,15);
printRequestingNode printer;
printer.print(node1);
printer.print(node2);
printer.print(node3);
pageCounter(node1);
pageCounter(node3);
}
|
#ifndef MockIEncoderTask_h
#define MockIEncoderTask_h
#include <fstream>
#include <string>
#include <gmock/gmock.h>
#include <compressor/data/data.h>
#include <compressor/data/reader.h>
#include <compressor/data/writer.h>
#include <compressor/task/coder.h>
#include <compressor/task/encoder.h>
#include <compressor/engine/engine.h>
class MockIEncoderTask: public compressor::IEncoderTask {
public:
MOCK_METHOD(std::string, input_file, (), (override));
MOCK_METHOD(std::string, output_file, (), (override));
MOCK_METHOD(compressor::IEngine&, engine, (), (override));
MOCK_METHOD(compressor::DecodedData&, data, (), (override));
MOCK_METHOD(compressor::IDataReader<compressor::DecodedData>&, reader, (), (override));
MOCK_METHOD(compressor::IDataWriter<compressor::EncodedData>&, writer, (), (override));
};
#endif /* MockIEncoderTask_h */
|
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> kClosest(vector<vector<int>> &points, int K)
{
if (K == points.size())
return points;
map<float, vector<vector<int>>> m;
for (auto arr : points)
{
float distance = sqrt(arr[0] * arr[0] + arr[1] * arr[1]);
m[distance].push_back(arr);
}
vector<vector<int>> ans;
for (auto itr = m.begin(); itr != m.end(); itr++)
{
if (K <= 0)
break;
else
for (auto c : itr->second)
{
ans.push_back(c);
K--;
}
}
return ans;
}
int main()
{
vector<vector<int>> points{{1, 1}, {-2, 2}, {3, 3}};
kClosest(points, 2);
return 0;
}
|
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcovered-switch-default"
#pragma clang diagnostic ignored "-Wsign-compare"
#pragma clang diagnostic ignored "-Wdeprecated"
#pragma clang diagnostic ignored "-Wshift-sign-overflow"
#include <gtest/gtest.h>
#pragma clang diagnostic pop
#pragma clang diagnostic ignored "-Wcovered-switch-default"
#include <vector>
#include <whiskey/Lexing/LexerContext.hpp>
#include <whiskey/Lexing/Lexer.hpp>
#include <whiskey/Messages/MessageContext.hpp>
#include <whiskey/Source/Source.hpp>
#include <whiskey/Source/Token.hpp>
using namespace whiskey;
TEST(Unit_Lexing_Lexer, Empty) {
std::stringstream ss("");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, Whitespace) {
std::stringstream ss(" \n\r\t");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, UnexpectedChar) {
std::stringstream ss("`");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 1);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentLineEmpty) {
std::stringstream ss("#");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentLine) {
std::stringstream ss("#asdf");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentLineMultiple) {
std::stringstream ss("#asdf\n#asdf\n#asdf");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentLineNested) {
std::stringstream ss("####");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentBlockEmpty) {
std::stringstream ss("#{}#");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentBlock) {
std::stringstream ss("#{asdf}#");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentBlockNested_0) {
std::stringstream ss("#{#{asdf}#}#");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentBlockNested_1) {
std::stringstream ss("#{#{#{}##{}#}##{#{}##{}#}##{#{#{}##{}#}#}#}#");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentBlockNested_2) {
std::stringstream ss("#{#}#");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentBlockMismatched_0) {
std::stringstream ss("#{asdf}");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 1);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentBlockMismatched_1) {
std::stringstream ss("#{asdf");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 1);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, CommentBlockMismatched_2) {
std::stringstream ss("#{#{asdf}#");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 1);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, Symbol_1) {
std::stringstream ss("x");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Symbol);
ASSERT_STREQ(toks[0].getText().c_str(), "x");
}
TEST(Unit_Lexing_Lexer, Symbol_2) {
std::stringstream ss("asdf");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Symbol);
ASSERT_STREQ(toks[0].getText().c_str(), "asdf");
}
TEST(Unit_Lexing_Lexer, Symbol_3) {
std::stringstream ss("x12309871");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Symbol);
ASSERT_STREQ(toks[0].getText().c_str(), "x12309871");
}
TEST(Unit_Lexing_Lexer, Symbol_4) {
std::stringstream ss("_12309871");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Symbol);
ASSERT_STREQ(toks[0].getText().c_str(), "_12309871");
}
TEST(Unit_Lexing_Lexer, Symbol_5) {
std::stringstream ss("x''''''");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Symbol);
ASSERT_STREQ(toks[0].getText().c_str(), "x''''''");
}
TEST(Unit_Lexing_Lexer, Symbol_6) {
std::stringstream ss("asdf''''''");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Symbol);
ASSERT_STREQ(toks[0].getText().c_str(), "asdf''''''");
}
TEST(Unit_Lexing_Lexer, Symbol_7) {
std::stringstream ss("x12309871''''''");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Symbol);
ASSERT_STREQ(toks[0].getText().c_str(), "x12309871''''''");
}
TEST(Unit_Lexing_Lexer, Symbol_8) {
std::stringstream ss("_12309871''''''");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Symbol);
ASSERT_STREQ(toks[0].getText().c_str(), "_12309871''''''");
}
TEST(Unit_Lexing_Lexer, KWNot) {
std::stringstream ss("not");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::KWNot);
ASSERT_STREQ(toks[0].getText().c_str(), "not");
}
TEST(Unit_Lexing_Lexer, Int_0) {
std::stringstream ss("0");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Int);
ASSERT_STREQ(toks[0].getText().c_str(), "0");
}
TEST(Unit_Lexing_Lexer, Int_1) {
std::stringstream ss("5018238971");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Int);
ASSERT_STREQ(toks[0].getText().c_str(), "5018238971");
}
TEST(Unit_Lexing_Lexer, Int_2) {
std::stringstream ss("5asdfkjsdf");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Int);
ASSERT_STREQ(toks[0].getText().c_str(), "5asdfkjsdf");
}
TEST(Unit_Lexing_Lexer, Real_0) {
std::stringstream ss("0.0");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Real);
ASSERT_STREQ(toks[0].getText().c_str(), "0.0");
}
TEST(Unit_Lexing_Lexer, Real_1) {
std::stringstream ss("5018238971.0");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Real);
ASSERT_STREQ(toks[0].getText().c_str(), "5018238971.0");
}
TEST(Unit_Lexing_Lexer, Real_2) {
std::stringstream ss("5asdfkjsdf.0");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Real);
ASSERT_STREQ(toks[0].getText().c_str(), "5asdfkjsdf.0");
}
TEST(Unit_Lexing_Lexer, Real_3) {
std::stringstream ss("5asdfkjsdf.0faljkhasdkfjhsadkfh");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Real);
ASSERT_STREQ(toks[0].getText().c_str(),
"5asdfkjsdf.0faljkhasdkfjhsadkfh");
}
TEST(Unit_Lexing_Lexer, Real_4) {
std::stringstream ss(".0");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Real);
ASSERT_STREQ(toks[0].getText().c_str(), ".0");
}
TEST(Unit_Lexing_Lexer, Real_5) {
std::stringstream ss(".0faljkhasdkfjhsadkfh");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Real);
ASSERT_STREQ(toks[0].getText().c_str(), ".0faljkhasdkfjhsadkfh");
}
TEST(Unit_Lexing_Lexer, Char_0) {
std::stringstream ss("'a'");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Char);
ASSERT_STREQ(toks[0].getText().c_str(), "'a'");
}
TEST(Unit_Lexing_Lexer, Char_1) {
std::stringstream ss("''");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Char);
ASSERT_STREQ(toks[0].getText().c_str(), "''");
}
TEST(Unit_Lexing_Lexer, Char_2) {
std::stringstream ss("'\\\\'");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Char);
ASSERT_STREQ(toks[0].getText().c_str(), "'\\\\'");
}
TEST(Unit_Lexing_Lexer, Char_3) {
std::stringstream ss("'\\''");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Char);
ASSERT_STREQ(toks[0].getText().c_str(), "'\\''");
}
TEST(Unit_Lexing_Lexer, Char_4) {
std::stringstream ss("'a");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 1);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, Char_5) {
std::stringstream ss("'\\'");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 1);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, Char_6) {
std::stringstream ss("'\"'");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Char);
ASSERT_STREQ(toks[0].getText().c_str(), "'\"'");
}
TEST(Unit_Lexing_Lexer, String_0) {
std::stringstream ss("\"a\"");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::String);
ASSERT_STREQ(toks[0].getText().c_str(), "\"a\"");
}
TEST(Unit_Lexing_Lexer, String_1) {
std::stringstream ss("\"\"");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::String);
ASSERT_STREQ(toks[0].getText().c_str(), "\"\"");
}
TEST(Unit_Lexing_Lexer, String_2) {
std::stringstream ss("\"\\\\\"");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::String);
ASSERT_STREQ(toks[0].getText().c_str(), "\"\\\\\"");
}
TEST(Unit_Lexing_Lexer, String_3) {
std::stringstream ss("\"\\\"\"");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::String);
ASSERT_STREQ(toks[0].getText().c_str(), "\"\\\"\"");
}
TEST(Unit_Lexing_Lexer, String_4) {
std::stringstream ss("\"a");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 1);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, String_5) {
std::stringstream ss("\"\\\"");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 1);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, String_6) {
std::stringstream ss("\"'\"");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::String);
ASSERT_STREQ(toks[0].getText().c_str(), "\"'\"");
}
TEST(Unit_Lexing_Lexer, LParen) {
std::stringstream ss("(");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::LParen);
}
TEST(Unit_Lexing_Lexer, RParen) {
std::stringstream ss(")");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::RParen);
}
TEST(Unit_Lexing_Lexer, LBracket) {
std::stringstream ss("[");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::LBracket);
}
TEST(Unit_Lexing_Lexer, RBracket) {
std::stringstream ss("]");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::RBracket);
}
TEST(Unit_Lexing_Lexer, LBrace) {
std::stringstream ss("{");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::LBrace);
}
TEST(Unit_Lexing_Lexer, RBrace) {
std::stringstream ss("}");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::RBrace);
}
TEST(Unit_Lexing_Lexer, Comma) {
std::stringstream ss(",");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Comma);
}
TEST(Unit_Lexing_Lexer, Semicolon) {
std::stringstream ss(";");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Semicolon);
}
TEST(Unit_Lexing_Lexer, Period) {
std::stringstream ss(".");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Period);
}
TEST(Unit_Lexing_Lexer, Add) {
std::stringstream ss("+");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Add);
}
TEST(Unit_Lexing_Lexer, Inc) {
std::stringstream ss("++");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Inc);
}
TEST(Unit_Lexing_Lexer, AddAssign) {
std::stringstream ss("+=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::AddAssign);
}
TEST(Unit_Lexing_Lexer, Sub) {
std::stringstream ss("-");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Sub);
}
TEST(Unit_Lexing_Lexer, Dec) {
std::stringstream ss("--");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Dec);
}
TEST(Unit_Lexing_Lexer, SubAssign) {
std::stringstream ss("-=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::SubAssign);
}
TEST(Unit_Lexing_Lexer, Mul) {
std::stringstream ss("*");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Mul);
}
TEST(Unit_Lexing_Lexer, Exp) {
std::stringstream ss("**");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Exp);
}
TEST(Unit_Lexing_Lexer, ExpAssign) {
std::stringstream ss("**=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::ExpAssign);
}
TEST(Unit_Lexing_Lexer, MulAssign) {
std::stringstream ss("*=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::MulAssign);
}
TEST(Unit_Lexing_Lexer, Div) {
std::stringstream ss("/");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Div);
}
TEST(Unit_Lexing_Lexer, DivInt) {
std::stringstream ss("//");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::DivInt);
}
TEST(Unit_Lexing_Lexer, DivIntAssign) {
std::stringstream ss("//=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::DivIntAssign);
}
TEST(Unit_Lexing_Lexer, DivReal) {
std::stringstream ss("/.");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::DivReal);
}
TEST(Unit_Lexing_Lexer, DivRealAssign) {
std::stringstream ss("/.=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::DivRealAssign);
}
TEST(Unit_Lexing_Lexer, DivAssign) {
std::stringstream ss("/=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::DivAssign);
}
TEST(Unit_Lexing_Lexer, Mod) {
std::stringstream ss("%");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Mod);
}
TEST(Unit_Lexing_Lexer, ModAssign) {
std::stringstream ss("%=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::ModAssign);
}
TEST(Unit_Lexing_Lexer, BitNot) {
std::stringstream ss("~");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitNot);
}
TEST(Unit_Lexing_Lexer, BitAnd) {
std::stringstream ss("&");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitAnd);
}
TEST(Unit_Lexing_Lexer, BitAndAssign) {
std::stringstream ss("&=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitAndAssign);
}
TEST(Unit_Lexing_Lexer, BitOr) {
std::stringstream ss("|");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitOr);
}
TEST(Unit_Lexing_Lexer, BitOrAssign) {
std::stringstream ss("|=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitOrAssign);
}
TEST(Unit_Lexing_Lexer, BitXor) {
std::stringstream ss("^");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitXor);
}
TEST(Unit_Lexing_Lexer, BitXorAssign) {
std::stringstream ss("^=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitXorAssign);
}
TEST(Unit_Lexing_Lexer, LT) {
std::stringstream ss("<");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::LT);
}
TEST(Unit_Lexing_Lexer, BitShL) {
std::stringstream ss("<<");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitShL);
}
TEST(Unit_Lexing_Lexer, LE) {
std::stringstream ss("<=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::LE);
}
TEST(Unit_Lexing_Lexer, LArrow) {
std::stringstream ss("<-");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::LArrow);
}
TEST(Unit_Lexing_Lexer, BitShLAssign) {
std::stringstream ss("<<=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitShLAssign);
}
TEST(Unit_Lexing_Lexer, GT) {
std::stringstream ss(">");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::GT);
}
TEST(Unit_Lexing_Lexer, BitShR) {
std::stringstream ss(">>");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitShR);
}
TEST(Unit_Lexing_Lexer, GE) {
std::stringstream ss(">=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::GE);
}
TEST(Unit_Lexing_Lexer, BitShRAssign) {
std::stringstream ss(">>=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BitShRAssign);
}
TEST(Unit_Lexing_Lexer, ExclamationPointAlone) {
std::stringstream ss("!");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 1);
ASSERT_EQ(toks.size(), 0);
}
TEST(Unit_Lexing_Lexer, NE) {
std::stringstream ss("!=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::NE);
}
TEST(Unit_Lexing_Lexer, Assign) {
std::stringstream ss("=");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::Assign);
}
TEST(Unit_Lexing_Lexer, EQ) {
std::stringstream ss("==");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::EQ);
}
TEST(Unit_Lexing_Lexer, BoolImplies) {
std::stringstream ss("=>");
Source src(ss);
std::vector<Token> toks;
MessageContext msgs;
LexerContext ctx(src, toks);
Lexer lexer;
lexer.lex(ctx, msgs);
ASSERT_EQ(msgs.getMessageCount(), 0);
ASSERT_EQ(toks.size(), 1);
ASSERT_EQ(toks[0].getID(), TokenID::BoolImplies);
}
|
#include<string>
#include <iostream>
#include <vector>
using namespace std;
bool solution(string s)
{
bool answer = true;
vector<char> block;
int i=0;
while(i<s.size()){
if(s[i]=='(') block.push_back('(');
else{
if(block.size()==0) return false;
if(block[block.size()-1]=='(') block.pop_back();
else return false;
}
i++;
}
if(block.size()!=0) return false;
else return true;
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jwon <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/28 11:32:15 by jwon #+# #+# */
/* Updated: 2020/11/28 13:24:06 by jwon ### ########.fr */
/* */
/* ************************************************************************** */
#include "ZombieHorde.hpp"
std::string zombieTypePicker(int idx)
{
std::string type;
std::string types[10] = {
"walker", "runner", "ghoul", "crawler", "screamer",
"bonie", "puker", "stalker", "splitter", "exploder"};
srand(time(NULL));
if (idx == 42)
type = types[rand() % 10];
else
type = types[idx - 1];
std::cout << "\n## Zombie type is <" << type << "> ##" << std::endl;
std::cout << std::endl;
return (type);
}
int zombieTypeInput(void)
{
int input;
bool loop;
std::cout << "┌────────────────────── Type of zombies ─────────────────────────┐" << std::endl;
std::cout << "│ 1. walker 2. runner 3. ghoul 4. crawler 5. screamer │" << std::endl;
std::cout << "│ 6. bonie 7. puker 8. stalker 9. splitter 10. exploder │" << std::endl;
std::cout << "│ * If you enter \'42\', the type is randomly defined. │" << std::endl;
std::cout << "└────────────────────────────────────────────────────────────────┘" << std::endl;
loop = true;
while (loop)
{
std::cout << ">> Please choose the type of zombie : ";
std::cin >> input;
if (std::cin.fail())
{
std::cout << "* Error: Invalid value." << std::endl;
std::cin.clear();
std::cin.ignore(256, '\n');
continue ;
}
if (std::cin.eof())
return (0);
if (input == 42 || (input >= 1 && input <= 10))
loop = false;
else
std::cout << "* Error: Input value is out of range." << std::endl;
}
return (input);
}
void makeZombie(std::string type)
{
int num;
std::cout << ">> How many zombies do you need? : ";
std::cin >> num;
if (std::cin.fail())
{
std::cout << "* Error: Invalid value." << std::endl;
std::cin.clear();
std::cin.ignore(256, '\n');
return (makeZombie(type));
}
if (std::cin.eof())
return ;
ZombieHorde(num, type);
}
int main(void)
{
int idx;
std::string type;
if (!(idx = zombieTypeInput()))
return (-1);
type = zombieTypePicker(idx);
makeZombie(type);
return (0);
}
|
#include <iostream>
int main()
{
using std::cout;
using std::cin;
using std::endl;
cout << "Enter a sentence with a '$' in it: " << endl;
int ct = 0;
char ch;
while ((ch = cin.get()) != '$')
ct++;
// put $ back to stream
cin.putback(ch);
while (cin.get() != '\n')
continue;
cout << "There are " << ct << " characters before $" << endl;
return 0;
}
|
//
// hlog.cpp
//
//
// Created by Artur Gilmutdinov on 4/26/13.
//
//
#ifndef _hlog_cpp
#define _hlog_cpp
#include "../include/hlog.h"
void hlog_clear(string file)
{
FILE *f = fopen(file.c_str(), "w");
}
void hlog_log(string s, string file)
{
FILE *f = fopen(file.c_str(), "a+");
fprintf(f, "%s", s.c_str());
fprintf(f, "\n");
fclose(f);
}
#endif
|
// =============================================================================
// Copyright 2012.
// Scott Alexander Holm.
// All Rights Reserved.
// =============================================================================
#include "game.h"
#include "play.h"
#include "confederateplay.h"
#include <iostream.h>
// Constructors
Game::Game (void) {
// game on
gameover = false;
}
// Methods
// Run the game
void Game::run (void) {
// We need players
Player *p[NUMBER_OF_PLAYERS];
//p[0] = new HumanPlayer();
p[0] = new Player("DMMMY PLAYER");
//p[0] = new ComputerPlayer();
p[1] = new ComputerPlayer();
cout << *p[0] << " vs " << *p[1] << "\n\n";
// What player is the dealer.
dealer = decideDealer(p);
cout << "The dealer is " << *p[dealer] << "\n";
cout << "\n";
// vacuious scorecard display
scorecard (p);
short int starting_dealer = dealer;
int p0_wins = 0;
int p1_wins = 0;
for (int i=0; i < 1; i++) {
// play until someone wins
while (!gameover) {
// make sure no players are holding any cards
p[!dealer]->discardHand();
p[dealer]->discardHand();
crib.discardHand();
deal(p);
discardCrib(p);
//cout << *p[1] << ": " << p[1]->getHand() << "\n";
cut(p);
if (gameover) {
break;
}
play(p);
if (gameover) {
break;
}
count(p);
if (gameover) {
break;
}
// switch the dealer
dealer = !dealer;
cout << "The dealer is now " << *p[dealer] << "\n";
cout << "\n";
}
// announce the winner
cout << "The winner is ";
if (p[0]->getPoints() == GAME_HOLE) {
p0_wins++;
cout << *p[0] << "\n\n";
} else {
p1_wins++;
cout << *p[1] << "\n\n";
}
// print some stats
cout << *p[0] << " wins: " << p0_wins << "\n";
cout << *p[1] << " wins: " << p1_wins << "\n";
// switch the dealer
dealer = !starting_dealer;
starting_dealer = dealer;
// announce the dealer switch
cout << "\n\nThe dealer is now " << *p[dealer] << "\n";
// reset the game to zero
p[0]->setPoints(0);
p[1]->setPoints(0);
gameover = false;
}
}
// Cut for deal. Assume only two players can cut for now.
short int Game::decideDealer(Player *p[]) {
// I have no idea why I did it this way
short unsigned int first = 0;
Card cut[NUMBER_OF_PLAYERS];
// get a cut card for each player
for (int i=0; i < NUMBER_OF_PLAYERS; i++) {
cut[(first + i) % NUMBER_OF_PLAYERS] =
p[(first + i) % NUMBER_OF_PLAYERS]->dealCut(i, d);
cout << "Cut card for player " <<
*p[((first + i) % NUMBER_OF_PLAYERS)]
<< ": " << cut[(first + i) % NUMBER_OF_PLAYERS] << "\n";
}
if (cut[first].getRank() == cut[(first+1) % NUMBER_OF_PLAYERS].getRank()) {
return decideDealer(p);
}
else if
(cut[first].getRank() < cut[(first+1) % NUMBER_OF_PLAYERS].getRank()) {
return first;
}
// the second player cuts
else {
return (first + 1) % NUMBER_OF_PLAYERS;
}
}
void Game::deal (Player *p[]) {
// Semantics but dealer need to deal the deck.
// player 'dealer' deal 'CARDS_PER_PLAYER' to 'NUMBER_OF_PLAYERS' in
// players p[]
p[dealer]->deal (dealer, CARDS_PER_PLAYER, NUMBER_OF_PLAYERS, p, d);
//cout << *p[dealer] << " hand " << p[dealer]->getHand() << "\n";
//cout << *p[!dealer] << " hand " << p[!dealer]->getHand() << "\n";
}
// have players discard cars to the crib
void Game::discardCrib (Player *p[]) {
Hand discard;
for (int i=0; i < NUMBER_OF_PLAYERS; i++) {
discard = p[i]->discardCrib( (dealer == i), p[!i] );
crib.addHand(discard);
//cout << *p[i] << " discard " << discard << "\n";
}
//cout << *p[dealer] << " hand " << p[dealer]->getHand() << "\n";
//cout << *p[!dealer] << " hand " << p[!dealer]->getHand() << "\n";
//cout << "Crib hand " << crib << "\n";
}
bool Game::scorecard (Player *p[]) {
cout << "\n";
cout <<
"BOARD:";
cout << "\n";
cout << " " << *p[0] << " " << p[0]->getPoints() << "\n";
cout << " " << *p[1] << " " << p[1]->getPoints() << "\n";
cout << "\n";
if (p[0]->getPoints() == GAME_HOLE || p[1]->getPoints() == GAME_HOLE) {
gameover = true;
return true;
}
return false;
}
// Get the person to the left of the dealer to cut the starter card
bool Game::cut (Player *p[]) {
// The game of cribbage requires at a cut at least 4 cards deep
// and not at least 4 cards off the bottom
starter = p[(dealer + 1) % NUMBER_OF_PLAYERS]->cut(d, 4, 4);
cout << "Starter card: " << starter << "\n";
// check for 'his heels'
if (starter.getRank() == JACK) {
p[dealer]->peg(NIBS);
cout << *p[dealer] << " announce NIBS\n";
}
return scorecard(p);
}
bool Game::play (Player *p[]) {
// The players turn
//bool turn = !dealer;
// the play object
Play *play = new Play(p, dealer);
gameover = play->playAllSets();
// Make each player pick up their hand
for (int i=0; i < NUMBER_OF_PLAYERS; i++) {
p[i]->restoreDiscards();
//p[i]->addHand(h[i]);
}
if (gameover) {
scorecard(p);
}
return gameover;
}
// count the hands
bool Game::count (Player *p[]) {
// holder for card count
short int count;
// quick recap of points
scorecard(p);
// count the person who didn't deal
//p[!dealer]->addCard(starter);
cout << *p[!dealer] << " counts..." << "\n";
count = p[!dealer]->countHand(starter);
cout << *p[!dealer] << " pegs " << count << "\n";
p[!dealer]->peg(count);
if (scorecard(p)) {
return gameover;
}
// count the dealer
//p[dealer]->addCard(starter);
cout << *p[dealer] << " counts..." << "\n";
count = p[dealer]->countHand(starter);
cout << *p[dealer] << " pegs " << count << "\n";
p[dealer]->peg(count);
if (scorecard(p)) {
return gameover;
}
// count the crib
//crib.addCard(starter);
cout << *p[dealer] << " counts crib..." << "\n";
count = crib.countHand(starter);
cout << *p[dealer] << "'s crib " << count << "\n";
p[dealer]->peg(count);
if (scorecard(p)) {
return gameover;
}
return gameover;
}
|
#include <iostream>
#include <stack>
using namespace std;
void isOK(string s);
string ss;
int main()
{
int n = 0;
cin >> n;
for(int i = 1; i < n; i++)
{
string s;
cin >> s;
isOK(s);
ss.append("\n");
}
string s;
cin >> s;
isOK(s);
cout << ss;
return 0;
}
void isOK(string s)
{
stack<int> left;
static const char leftChar[4] = {'<', '(', '[', '{'};
static const char rightChar[4] = {'>', ')', ']', '}'};
bool flag = false;
int weight = -1;
for(int i = 0; i < s.size(); i++)
{
bool continueFlag = false;
for(int n = 0; n < 4; n++)
{
if(s[i] == leftChar[n]){
left.push(n);
weight = n;
continueFlag = true;
}
}
if(continueFlag) continue;
for(int n = 0; n < 4; n++)
{
if(s[i] == rightChar[n]){
if(left.empty() || n != left.top() || n > weight){
ss.append("NO");
flag = true;
}
else left.pop();
}
}
if(flag) break;
}
if(left.empty() && !flag) ss.append("YES");
}
|
#include "Globals.h"
#include "Application.h"
#include "ModuleInput.h"
#include "SDL/include/SDL.h"
#include "p2Qeue.h"
#include "SDL/include/SDL_gamecontroller.h"
#include "ModulePlayer.h"
#include "ModulePlayer2.h"
ModuleInput::ModuleInput() : Module()
{
for (uint i = 0; i < MAX_KEYS; ++i)
keyboard[i] = KEY_IDLE;
}
// Destructor
ModuleInput::~ModuleInput()
{
}
// Called before render is available
bool ModuleInput::Init()
{
bool ret = true;
SDL_Init(0);
SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_CONTROLLERDEVICEADDED:
LOG("CONNECTED");
if (gGameController == NULL)
{
gGameController = SDL_GameControllerOpen(0);
}
else
{
if (gGameController2 == NULL)
{
gGameController2 = SDL_GameControllerOpen(1);
}
}
break;
case SDL_CONTROLLERDEVICEREMOVED:
LOG("REMOVED");
if (gGameController2 != NULL)
{
LOG("PLAYER 2 CONTROLLER REMOVED");
SDL_GameControllerClose(gGameController2);
gGameController = NULL;
}
else
{
if (gGameController != NULL)
{
LOG("PLAYER 1 CONTROLLER REMOVED");
SDL_GameControllerClose(gGameController);
gGameController = NULL;
}
}
break;
}
}
return ret;
}
bool ModuleInput::external_input()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
//KEYBOARD
if (event.type == SDL_KEYUP && event.key.repeat == 0)
{
switch (event.key.keysym.sym)
{
case SDLK_ESCAPE:
return false;
break;
//PLAYER 1
case SDLK_s:
inputs.Push(IN_CROUCH_UP);
down = false;
break;
case SDLK_w:
up = false;
break;
case SDLK_a:
inputs.Push(IN_LEFT_UP);
left = false;
break;
case SDLK_d:
inputs.Push(IN_RIGHT_UP);
right = false;
break;
case SDLK_v:
inputs.Push(IN_CHARGE_UP);
charge = false;
break;
//PLAYER 2
case SDLK_k:
inputs2.Push(IN_CROUCH_UP2);
down2 = false;
break;
case SDLK_i:
up2 = false;
break;
case SDLK_j:
inputs2.Push(IN_LEFT_UP2);
left2 = false;
break;
case SDLK_l:
inputs2.Push(IN_RIGHT_UP2);
right2 = false;
break;
case SDLK_b:
inputs2.Push(IN_CHARGE_UP2);
charge2 = false;
break;
}
}
if (event.type == SDL_KEYDOWN && event.key.repeat == 0)
{
switch (event.key.keysym.sym)
{
//PLAYER 1
case SDLK_r:
inputs.Push(IN_R);
break;
case SDLK_t:
inputs.Push(IN_T);
break;
case SDLK_f:
inputs.Push(IN_F);
break;
case SDLK_c:
inputs.Push(IN_C);
break;
case SDLK_x:
inputs.Push(IN_X);
break;
case SDLK_q:
inputs.Push(IN_TAUNT);
break;
case SDLK_w:
up = true;
break;
case SDLK_v:
charge = true;
break;
case SDLK_s:
down = true;
break;
case SDLK_a:
left = true;
break;
case SDLK_d:
right = true;
break;
//PLAYER 2
case SDLK_u:
inputs2.Push(IN_U);
break;
case SDLK_y:
inputs2.Push(IN_Y);
break;
case SDLK_h:
inputs2.Push(IN_H);
break;
case SDLK_n:
inputs2.Push(IN_N);
break;
case SDLK_m:
inputs2.Push(IN_M);
break;
case SDLK_o:
inputs2.Push(IN_TAUNT2);
break;
case SDLK_i:
up2 = true;
break;
case SDLK_k:
down2 = true;
break;
case SDLK_j:
left2 = true;
break;
case SDLK_l:
right2 = true;
break;
case SDLK_b:
charge2 = true;
break;
}
}
//GAMEPAD JOYSTICK
if (event.type == SDL_CONTROLLERAXISMOTION)
{
if (event.jaxis.which == 0)
{
//PLAYER 1 JOYSTICK
if (event.jaxis.axis == 0)
{
//Left of dead zone
if (event.jaxis.value < -JOYSTICK_DEAD_ZONE)
{
left = true;
right = false;
}
//Right of dead zone
else if (event.jaxis.value > JOYSTICK_DEAD_ZONE)
{
right = true;
left = false;
}
else
{
left = false;
right = false;
}
}
else if (event.jaxis.axis == 1)
{
//Below of dead zone
if (event.jaxis.value < -JOYSTICK_DEAD_ZONE)
{
down = false;
up = true;
}
//Above of dead zone
else if (event.jaxis.value > JOYSTICK_DEAD_ZONE)
{
up = false;
down = true;
}
else
{
down = false;
up = false;
}
}
}
//Player 2 JOYSTICK
if (event.jaxis.which == 1) //En el gamepad 2
{
if (event.jaxis.axis == 0)
{
//Left of dead zone
if (event.jaxis.value < -JOYSTICK_DEAD_ZONE)
{
left2 = true;
right2 = false;
}
//Right of dead zone
else if (event.jaxis.value > JOYSTICK_DEAD_ZONE)
{
right2 = true;
left2 = false;
}
else
{
left2 = false;
right2 = false;
}
}
else if (event.jaxis.axis == 1)
{
//Below of dead zone
if (event.jaxis.value < -JOYSTICK_DEAD_ZONE)
{
down2 = false;
up2 = true;
}
//Above of dead zone
else if (event.jaxis.value > JOYSTICK_DEAD_ZONE)
{
up2 = false;
down2 = true;
}
else
{
down2 = false;
up2 = false;
}
}
}
}
//GAMEPAD BUTTONS
if (event.type == SDL_CONTROLLERBUTTONDOWN)
{
//PLAYER 1 BUTTONS
if (event.cbutton.which == 0)
{
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_BACK)
{
return false;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_X)
{
inputs.Push(IN_T);
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_Y)
{
inputs.Push(IN_R);
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER)
{
inputs.Push(IN_TAUNT);
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)
{
charge = true;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT)
{
Menuright=true;
}
else {
Menuright =false;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT)
{
Menuleft = true;
}
else {
Menuleft = false;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP)
{
Menuup = true;
}
else {
Menuup = false;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN)
{
Menudown = true;
}
else {
Menudown = false;
}
}
//PLAYER 2 BUTTONS
if (event.cbutton.which == 1)
{
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_BACK)
{
return false;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_X)
{
inputs2.Push(IN_Y);
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_Y)
{
inputs2.Push(IN_U);
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER)
{
inputs2.Push(IN_TAUNT2);
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)
{
charge2 = true;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT)
{
Menuright2 = true;
}
else {
Menuright2 = false;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT)
{
Menuleft2 = true;
}
else {
Menuleft2 = false;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP)
{
Menuup2 = true;
}
else {
Menuup2 = false;
}
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN)
{
Menudown2 = true;
}
else {
Menudown2 = false;
}
}
}
if (event.type == SDL_CONTROLLERBUTTONUP)
{
//PLAYER 1 CHARGE
if (event.cbutton.which == 0)
{
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)
{
inputs.Push(IN_CHARGE_UP);
charge = false;
}
}
//PLAYER 2 CHARGE
if (event.cbutton.which == 1)
{
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)
{
inputs2.Push(IN_CHARGE_UP2);
charge2 = false;
}
}
}
//PLAYER 1
if (left && right)
inputs.Push(IN_LEFT_AND_RIGHT);
{
if (left)
inputs.Push(IN_LEFT_DOWN);
if (right)
inputs.Push(IN_RIGHT_DOWN);
}
if (!left)
inputs.Push(IN_LEFT_UP);
if (!right)
inputs.Push(IN_RIGHT_UP);
if (!down)
inputs.Push(IN_CROUCH_UP);
if (!charge)
inputs.Push(IN_CHARGE_UP);
if (up && down)
inputs.Push(IN_JUMP_AND_CROUCH);
else
{
if (down)
inputs.Push(IN_CROUCH_DOWN);
if (up)
inputs.Push(IN_JUMP);
}
if (charge)
inputs.Push(IN_CHARGE_DOWN);
//PLAYER 2
if (left2 && right2)
inputs2.Push(IN_LEFT_AND_RIGHT2);
{
if (left2)
inputs2.Push(IN_LEFT_DOWN2);
if (right2)
inputs2.Push(IN_RIGHT_DOWN2);
}
if (!left2)
inputs2.Push(IN_LEFT_UP2);
if (!right2)
inputs2.Push(IN_RIGHT_UP2);
if (!down2)
inputs2.Push(IN_CROUCH_UP2);
if (!charge2)
inputs2.Push(IN_CHARGE_UP2);
if (up2 && down2)
inputs2.Push(IN_JUMP_AND_CROUCH2);
else
{
if (down2)
inputs2.Push(IN_CROUCH_DOWN2);
if (up2)
inputs2.Push(IN_JUMP2);
}
if (charge2)
inputs2.Push(IN_CHARGE_DOWN2);
}
return true;
}
void ModuleInput::internal_input(p2Qeue<king_inputs>& inputs, p2Qeue<king_inputs>& inputs2)
{
//PLAYER 1
if (jump_timer > 0)
{
if (SDL_GetTicks() - jump_timer > JUMP_TIME)
{
inputs.Push(IN_JUMP_FINISH);
jump_timer = 0;
}
}
if (punch_timer > 0)
{
if (SDL_GetTicks() - punch_timer > PUNCH_TIME)
{
inputs.Push(IN_PUNCH_FINISH);
punch_timer = 0;
}
}
if (punch_crouch_timer > 0)
{
if (SDL_GetTicks() - punch_crouch_timer > PUNCH_CROUCH_TIME)
{
inputs.Push(IN_PUNCH_CROUCH_FINISH);
punch_crouch_timer = 0;
}
}
if (kick_timer > 0)
{
if (SDL_GetTicks() - kick_timer > KICK_TIME)
{
inputs.Push(IN_KICK_FINISH);
kick_timer = 0;
}
}
if (kick_crouch_timer > 0)
{
if (SDL_GetTicks() - kick_crouch_timer > KICK_CROUCH_TIME)
{
inputs.Push(IN_KICK_CROUCH_FINISH);
kick_crouch_timer = 0;
}
}
if (hadouken_timer > 0)
{
if (SDL_GetTicks() - hadouken_timer > HADOUKEN_TIME)
{
inputs.Push(IN_HADOUKEN_FINISH);
hadouken_timer = 0;
}
}
if (moshuukyaku_timer > 0)
{
if (SDL_GetTicks() - moshuukyaku_timer > MOUSHUUKYAKU_TIME)
{
inputs.Push(IN_MOUSHUUKYAKU_FINISH);
moshuukyaku_timer = 0;
}
}
if (tornadokick_timer > 0)
{
if (SDL_GetTicks() - tornadokick_timer > TORNADOKICK_TIME)
{
inputs.Push(IN_TORNADOKICK_FINISH);
tornadokick_timer = 0;
}
}
if (damage_timer > 0)
{
if (SDL_GetTicks() - damage_timer > DAMAGE_TIME)
{
inputs.Push(IN_DAMAGE_FINISH);
damage_timer = 0;
App->player->damageP2 = false;
}
}
if (damageHadoken_timer > 0)
{
if (SDL_GetTicks() - damageHadoken_timer > DAMAGEHADOKEN_TIME)
{
inputs.Push(IN_DAMAGE_HADOKEN_FINISH);
damageHadoken_timer = 0;
App->player->damageHadokenP2 = false;
}
}
if (taunt_timer > 0)
{
if (SDL_GetTicks() - taunt_timer > TAUNT_TIME)
{
inputs.Push(IN_TAUNT_FINISH);
taunt_timer = 0;
}
}
//PLAYER 2
if (jump_timer2 > 0)
{
if (SDL_GetTicks() - jump_timer2 > JUMP_TIME)
{
inputs2.Push(IN_JUMP_FINISH2);
jump_timer2 = 0;
}
}
if (punch_timer2 > 0)
{
if (SDL_GetTicks() - punch_timer2 > PUNCH_TIME)
{
inputs2.Push(IN_PUNCH_FINISH2);
punch_timer2 = 0;
}
}
if (punch_crouch_timer2 > 0)
{
if (SDL_GetTicks() - punch_crouch_timer2 > PUNCH_CROUCH_TIME)
{
inputs2.Push(IN_PUNCH_CROUCH_FINISH2);
punch_crouch_timer2 = 0;
}
}
if (kick_timer2 > 0)
{
if (SDL_GetTicks() - kick_timer2 > KICK_TIME)
{
inputs2.Push(IN_KICK_FINISH2);
kick_timer2 = 0;
}
}
if (kick_crouch_timer2 > 0)
{
if (SDL_GetTicks() - kick_crouch_timer2 > KICK_CROUCH_TIME)
{
inputs2.Push(IN_KICK_CROUCH_FINISH2);
kick_crouch_timer2 = 0;
}
}
if (hadouken_timer2 > 0)
{
if (SDL_GetTicks() - hadouken_timer2 > HADOUKEN_TIME)
{
inputs2.Push(IN_HADOUKEN_FINISH2);
hadouken_timer2 = 0;
}
}
if (moshuukyaku_timer2 > 0)
{
if (SDL_GetTicks() - moshuukyaku_timer2 > MOUSHUUKYAKU_TIME)
{
inputs2.Push(IN_MOUSHUUKYAKU_FINISH2);
moshuukyaku_timer2 = 0;
}
}
if (tornadokick_timer2 > 0)
{
if (SDL_GetTicks() - tornadokick_timer2 > TORNADOKICK_TIME)
{
inputs2.Push(IN_TORNADOKICK_FINISH2);
tornadokick_timer2 = 0;
}
}
if (damage_timer2 > 0)
{
if (SDL_GetTicks() - damage_timer2 > DAMAGE_TIME)
{
inputs2.Push(IN_DAMAGE_FINISH2);
damage_timer2 = 0;
App->player2->damageP1 = false;
}
}
if (taunt_timer2 > 0)
{
if (SDL_GetTicks() - taunt_timer2 > TAUNT_TIME)
{
inputs2.Push(IN_TAUNT_FINISH2);
taunt_timer2 = 0;
}
}
if (damageHadoken_timer2 > 0)
{
if (SDL_GetTicks() - damageHadoken_timer2 > DAMAGEHADOKEN_TIME)
{
inputs2.Push(IN_DAMAGE_HADOKEN_FINISH2);
damageHadoken_timer2 = 0;
App->player2->damageHadokenP1 = false;
}
}
}
// Called every draw update
update_status ModuleInput::PreUpdate()
{
SDL_PumpEvents();
const Uint8* keys = SDL_GetKeyboardState(NULL);
for (int i = 0; i < MAX_KEYS; ++i)
{
if (keys[i] == 1)
{
if (keyboard[i] == KEY_IDLE)
keyboard[i] = KEY_DOWN;
else
keyboard[i] = KEY_REPEAT;
}
else
{
if (keyboard[i] == KEY_REPEAT || keyboard[i] == KEY_DOWN)
keyboard[i] = KEY_UP;
else
keyboard[i] = KEY_IDLE;
}
}
if (keyboard[SDL_SCANCODE_ESCAPE])
return update_status::UPDATE_STOP;
// Para el input que sean estados
if (external_input() == false) { return update_status::UPDATE_STOP; }
else {
internal_input(inputs, inputs2);
}
return update_status::UPDATE_CONTINUE;
SDL_PumpEvents();
}
update_status ModuleInput::PostUpdate() {
key = -1;
return update_status::UPDATE_CONTINUE;
}
// Called before quitting
bool ModuleInput::CleanUp()
{
SDL_GameControllerClose(gGameController);
SDL_GameControllerClose(gGameController2);
gGameController = NULL;
gGameController2 = NULL;
LOG("Quitting SDL input event subsystem");
SDL_QuitSubSystem(SDL_INIT_EVENTS);
return true;
}
|
#ifndef APPLICATION_H
#define APPLICATION_H
#include <vector>
#include <string>
#include <ostream>
#include "LinkLayer.h"
class Application {
public:
Application();
void run();
private:
LinkLayer link_layer;
int serial_port;
unsigned max_packet_size;
unsigned max_reconnects;
unsigned current_reconnects;
unsigned num_duplicate_data_packets;
unsigned progress;
static const unsigned int table_crc[];
void menuSettings();
void showLog() const;
void sendFile();
void receiveFile();
bool alSendFile(const std::vector<char>& file_vec, const std::string& file_name, unsigned file_crc32, std::ostream& err_stream);
std::vector<char> alCreateInititalEndPacket(unsigned file_size, unsigned file_crc32, const std::string& file_name);
std::vector<char> alCreateDataPacket(const std::vector<char>& file, unsigned& file_ind, unsigned packet_count);
int alReceiveFile(std::vector<char>& file, std::string& file_name, unsigned& file_crc32,std::ostream& err_stream);
void alDecodeInitialEndPacket(const std::vector<char>& buffer, unsigned& file_size, std::string& file_name, unsigned& file_crc32);
bool alDecodeDataPacket(std::vector<char>& file, const std::vector<char>& buffer, unsigned& packet_count);
void updateProgress(unsigned int new_progress, std::string message);
unsigned crc32(const std::vector<char>& buffer);
};
#endif
|
/*
* Copyright (c) 2009-2012 André Tupinambá (andrelrt@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
//-----------------------------------------------------------------------------
#include "composite_memory.h"
#include "composite_event.h"
#include "composite_command_queue.h"
using dcl::info::generic_event;
using dcl::info::generic_memory;
using dcl::info::generic_context;
using dcl::info::generic_command_queue;
//-----------------------------------------------------------------------------
namespace dcl {
namespace composite {
//-----------------------------------------------------------------------------
// composite_memory
//-----------------------------------------------------------------------------
composite_memory::composite_memory( const composite_context& context_ref,
const void* host_ptr, size_t size,
cl_mem_flags flags ) :
composite_object< generic_memory >( context_ref )
{
set_info( host_ptr, size, flags );
}
//-----------------------------------------------------------------------------
void composite_memory::read( generic_command_queue* queue_ptr, void* data_ptr,
size_t size, size_t offset, cl_bool blocking,
events_t& wait_events, generic_event** ret_event_ptr )
{
const generic_context* ctx = queue_ptr->get_context();
generic_memory* memory_ptr = reinterpret_cast<generic_memory*>( find( ctx ) );
events_t context_events;
composite_event::get_context_events( ctx, wait_events, context_events );
if( ret_event_ptr == NULL )
{
memory_ptr->read( queue_ptr, data_ptr, size, offset,
blocking, context_events, ret_event_ptr );
}
else
{
if( *ret_event_ptr == NULL )
{
*ret_event_ptr = new composite_event(
*(reinterpret_cast<const composite_context*>( ctx )), queue_ptr );
}
generic_event* event_ptr = NULL;
memory_ptr->read( queue_ptr, data_ptr, size, offset,
blocking, context_events, &event_ptr );
reinterpret_cast<composite_event*>(*ret_event_ptr)->add_event( ctx, event_ptr );
}
}
//-----------------------------------------------------------------------------
void composite_memory::write( generic_command_queue* queue_ptr, const void* data_ptr,
size_t size, size_t offset, cl_bool blocking,
events_t& wait_events, generic_event** ret_event_ptr )
{
const generic_context* ctx = queue_ptr->get_context();
generic_memory* memory_ptr = reinterpret_cast<generic_memory*>( find( ctx ) );
events_t context_events;
composite_event::get_context_events( ctx, wait_events, context_events );
if( ret_event_ptr == NULL )
{
memory_ptr->write( queue_ptr, data_ptr, size, offset,
blocking, context_events, ret_event_ptr );
}
else
{
if( *ret_event_ptr == NULL )
{
*ret_event_ptr = new composite_event(
*(reinterpret_cast<const composite_context*>( ctx )), queue_ptr );
}
generic_event* event_ptr = NULL;
memory_ptr->write( queue_ptr, data_ptr, size, offset,
blocking, context_events, &event_ptr );
reinterpret_cast<composite_event*>(*ret_event_ptr)->add_event( ctx, event_ptr );
}
}
//-----------------------------------------------------------------------------
void* composite_memory::map( generic_command_queue* queue_ptr, cl_map_flags flags,
size_t size, size_t offset, cl_bool blocking,
events_t& wait_events, generic_event** ret_event_ptr )
{
const generic_context* ctx = queue_ptr->get_context();
generic_memory* memory_ptr = reinterpret_cast<generic_memory*>( find( ctx ) );
void* ret_ptr = NULL;
events_t context_events;
composite_event::get_context_events( ctx, wait_events, context_events );
if( ret_event_ptr == NULL )
{
ret_ptr = memory_ptr->map( queue_ptr, flags, size, offset,
blocking, context_events, ret_event_ptr );
}
else
{
if( *ret_event_ptr == NULL )
{
*ret_event_ptr = new composite_event(
*(reinterpret_cast<const composite_context*>( ctx )), queue_ptr );
}
generic_event* event_ptr = NULL;
ret_ptr = memory_ptr->map( queue_ptr, flags, size, offset,
blocking, context_events, &event_ptr );
reinterpret_cast<composite_event*>(*ret_event_ptr)->add_event( ctx, event_ptr );
}
return ret_ptr;
}
//-----------------------------------------------------------------------------
void composite_memory::unmap( generic_command_queue* queue_ptr, void* data_ptr,
events_t& wait_events, generic_event** ret_event_ptr )
{
const generic_context* ctx = queue_ptr->get_context();
generic_memory* memory_ptr = reinterpret_cast<generic_memory*>( find( ctx ) );
events_t context_events;
composite_event::get_context_events( ctx, wait_events, context_events );
if( ret_event_ptr == NULL )
{
memory_ptr->unmap( queue_ptr, data_ptr, context_events, ret_event_ptr );
}
else
{
if( *ret_event_ptr == NULL )
{
*ret_event_ptr = new composite_event(
*(reinterpret_cast<const composite_context*>( ctx )), queue_ptr );
}
generic_event* event_ptr = NULL;
memory_ptr->unmap( queue_ptr, data_ptr, context_events, &event_ptr );
reinterpret_cast<composite_event*>(*ret_event_ptr)->add_event( ctx, event_ptr );
}
}
//-----------------------------------------------------------------------------
void composite_memory::copy( generic_command_queue* queue_ptr, generic_memory* src_ptr,
size_t size, size_t src_offset, size_t dst_offset,
events_t& wait_events, dcl::info::generic_event** ret_event_ptr )
{
const generic_context* ctx = queue_ptr->get_context();
generic_memory* dst_memory_ptr = reinterpret_cast<generic_memory*>( find( ctx ) );
composite_memory* src = reinterpret_cast<composite_memory*>( src_ptr );
generic_memory* src_memory_ptr = reinterpret_cast<generic_memory*>( src->find( ctx ) );
events_t context_events;
composite_event::get_context_events( ctx, wait_events, context_events );
if( ret_event_ptr == NULL )
{
dst_memory_ptr->copy( queue_ptr, src_memory_ptr, size, src_offset,
dst_offset, context_events, ret_event_ptr );
}
else
{
if( *ret_event_ptr == NULL )
{
*ret_event_ptr = new composite_event(
*(reinterpret_cast<const composite_context*>( ctx )), queue_ptr );
}
generic_event* event_ptr = NULL;
dst_memory_ptr->copy( queue_ptr, src_memory_ptr, size, src_offset,
dst_offset, context_events, &event_ptr );
reinterpret_cast<composite_event*>(*ret_event_ptr)->add_event( ctx, event_ptr );
}
}
//-----------------------------------------------------------------------------
// composite_image
//-----------------------------------------------------------------------------
composite_image::composite_image( const composite_context& context_ref,
const void* host_ptr, cl_mem_flags flags,
const cl_image_format* format, size_t width,
size_t height, size_t row_pitch ) :
composite_object< generic_image >( context_ref )
{
set_info( host_ptr, flags, format, width, height, row_pitch );
}
//-----------------------------------------------------------------------------
void composite_image::write( generic_command_queue* queue_ptr, const void* data_ptr,
const size_t origin[3], const size_t region[3],
size_t row_pitch, size_t slice_pitch, bool blocking,
events_t& wait_events, generic_event** ret_event_ptr )
{
const generic_context* ctx = queue_ptr->get_context();
generic_image* image_ptr = reinterpret_cast<generic_image*>( find( ctx ) );
events_t context_events;
composite_event::get_context_events( ctx, wait_events, context_events );
if( ret_event_ptr == NULL )
{
image_ptr->write( queue_ptr, data_ptr, origin, region, row_pitch,
slice_pitch, blocking, context_events, ret_event_ptr );
}
else
{
if( *ret_event_ptr == NULL )
{
*ret_event_ptr = new composite_event(
*(reinterpret_cast<const composite_context*>( ctx )), queue_ptr );
}
generic_event* event_ptr = NULL;
image_ptr->write( queue_ptr, data_ptr, origin, region, row_pitch,
slice_pitch, blocking, context_events, &event_ptr );
reinterpret_cast<composite_event*>(*ret_event_ptr)->add_event( ctx, event_ptr );
}
}
//-----------------------------------------------------------------------------
void composite_image::unmap( generic_command_queue* queue_ptr, void* data_ptr,
events_t& wait_events, generic_event** ret_event_ptr )
{
const generic_context* ctx = queue_ptr->get_context();
generic_image* image_ptr = reinterpret_cast<generic_image*>( find( ctx ) );
events_t context_events;
composite_event::get_context_events( ctx, wait_events, context_events );
if( ret_event_ptr == NULL )
{
image_ptr->unmap( queue_ptr, data_ptr, context_events, ret_event_ptr );
}
else
{
if( *ret_event_ptr == NULL )
{
*ret_event_ptr = new composite_event(
*(reinterpret_cast<const composite_context*>( ctx )), queue_ptr );
}
generic_event* event_ptr = NULL;
image_ptr->unmap( queue_ptr, data_ptr, context_events, &event_ptr );
reinterpret_cast<composite_event*>(*ret_event_ptr)->add_event( ctx, event_ptr );
}
}
//-----------------------------------------------------------------------------
}} // namespace dcl::composite
//-----------------------------------------------------------------------------
|
#include "Topping.h"
Topping::Topping(){
}
string Topping::get_name() {
return this->name;
}
int Topping::get_price(){
return this->price;
}
void Topping::set_name(string new_name){
this->name = new_name;
}
void Topping::set_price(int new_price){
this->price = new_price;
}
///are currently working on ordering.
|
#ifndef HHREPORT_H
#define HHREPORT_H
#include <QObject>
#include <QVector>
class IoNetClient;
class QFile;
class HhReport : public QObject
{
Q_OBJECT
public:
explicit HhReport(QVector<IoNetClient*> &source,QObject *parent = 0);
signals:
private slots:
void slotGasDataReady(bool);
void slotUpdateaData();
private:
QVector<IoNetClient*> &src;
QFile *file;
QVector<double> mass,gass;
bool gasOk;
qint32 updateCount;
};
#endif // HHREPORT_H
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
#include "Pooma/Pooma.h"
#include "Domain/Interval.h"
#include "Utilities/Inform.h"
#include <iostream>
#include <iomanip>
#include <ios>
#include "Utilities/Tester.h"
int main(int argc, char *argv[])
{
// initialize Pooma
Pooma::initialize(argc,argv);
Pooma::Tester tester(argc, argv);
// create some Inform instances
Inform A("POOMA-II:A");
Inform B("POOMA-II:B");
// add another connection to stderr for B
Inform::ID_t connection = B.open(std::cerr);
// write A's output also to a file
Inform::ID_t connection2 = A.open("inform_test.dat", Inform::out);
// simple test prints, which should have leading and trailing blank lines
A << "------" << std::endl;
A << std::endl
<< "This should have a leading and following blank line."
<< std::endl << std::endl;
A << "------" << std::endl;
B << "------" << std::endl;
B << std::endl
<< "This should have a leading and following blank line."
<< std::endl << std::endl;
B << "------" << std::endl;
// print some domains to this, to test output to ostream:
Interval<1> X(1,5);
A << "Interval X = " << X << ", with no endl, just flush";
A << std::flush;
// use some manipulators
int val = 2;
int val2 = 1234;
A << std::setw(4) << std::setfill('#') << val << ": should be ###2"
<< std::endl;
B << val2 << " = " << std::hex << val2 << " (hex), ";
B << std::oct << val2 << " (oct)" << std::endl;
// close B's second connection
B.close(connection);
B << "This line should only appear once." << std::endl;
// should be some blank lines
A << std::endl << std::endl
<< "There should be two blank lines, then this." << std::endl;
// inform about file to check
A << std::endl
<< "The file 'inform_test.dat' should contain copies of all";
A << " the lines written to the 'A' stream." << std::endl;
int res = tester.results();
// finalize Pooma
Pooma::finalize();
return res;
}
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: inform_test.cpp,v $ $Author: richard $
// $Revision: 1.10 $ $Date: 2004/11/01 18:17:19 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
/// @file LsimLcc.cc
/// @brief LsimLcc の実装ファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2005-2011 Yusuke Matsunaga
/// All rights reserved.
#include "LsimLcc.h"
#include "YmNetworks/BdnNode.h"
BEGIN_NAMESPACE_YM
//////////////////////////////////////////////////////////////////////
// クラス LsimLcc
//////////////////////////////////////////////////////////////////////
// @brief コンストラクタ
LsimLcc::LsimLcc()
{
}
// @brief デストラクタ
LsimLcc::~LsimLcc()
{
}
// @brief ネットワークをセットする.
// @param[in] bdn 対象のネットワーク
// @param[in] order_map 順序マップ
void
LsimLcc::set_network(const BdnMgr& bdn,
const unordered_map<string, ymuint>& order_map)
{
vector<const BdnNode*> node_list;
bdn.sort(node_list);
ymuint n = bdn.max_node_id();
cout << "/// @file lcc_main.cc" << endl
<< "/// @brief コンパイル法シミュレータのメイン関数" << endl
<< "/// @author Yusuke Matsunaga (松永 裕介)" << endl
<< "///" << endl
<< "/// Copyright (C) 2005-2011 Yusuke Matsunaga" << endl
<< "/// All rights reserved." << endl
<< endl
<< "#include <iostream>" << endl
<< endl
<< "void" << endl
<< "eval_logic(unsigned long ivals[]," << endl
<< " unsigned long ovals[])" << endl
<< "{" << endl
<< " unsigned long vals[" << n << "];" << endl;
ymuint input_id = 0;
const BdnNodeList& input_list = bdn.input_list();
ymuint ni = input_list.size();
for (BdnNodeList::const_iterator p = input_list.begin();
p != input_list.end(); ++ p, ++ input_id) {
const BdnNode* node = *p;
cout << " vals[" << node->id() << "] = ivals[" << input_id << "];" << endl;
}
for (vector<const BdnNode*>::iterator p = node_list.begin();
p != node_list.end(); ++ p) {
const BdnNode* node = *p;
cout << " vals[" << node->id() << "] = ";
if ( node->fanin_inv(0) ) {
cout << "~";
}
cout << "vals[" << node->fanin(0)->id() << "]";
if ( node->is_xor() ) {
cout << " ^ ";
}
else {
cout << " & ";
}
if ( node->fanin_inv(1) ) {
cout << "~";
}
cout << "vals[" << node->fanin(1)->id() << "]";
cout << ";" << endl;
}
const BdnNodeList& output_list = bdn.output_list();
ymuint no = output_list.size();
ymuint output_id = 0;
for (BdnNodeList::const_iterator p = output_list.begin();
p != output_list.end(); ++ p, ++ output_id) {
const BdnNode* node = *p;
const BdnNode* inode = node->output_fanin();
cout << " ovals[" << output_id << "] = ";
if ( inode != NULL ) {
if ( node->output_fanin_inv() ) {
cout << "~";
}
cout << "vals[" << inode->id() << "]";
}
else {
cout << "0UL";
}
cout << ";" << endl;
}
cout << "}" << endl
<< endl;
cout << "int" << endl
<< "main(int argc," << endl
<< "const char** argv)"<< endl
<< "{" << endl
<< " using namespace std;" << endl
<< endl
<< " if ( argc != 2 ) {" << endl
<< " cerr << \"Usage: lcc <loop-num>\" << endl;" << endl
<< " return 1;" << endl
<< " }" << endl
<< endl
<< " int n = atoi(argv[1]);" << endl
<< " unsigned long ivals[" << ni << "];" << endl
<< " unsigned long ovals[" << no << "];" << endl
<< " for (int i = 0; i < n; ++ i) {" << endl
<< " for (int j = 0; j < " << ni << "; ++ j) {" << endl
<< " ivals[j] = random();" << endl
<< " }" << endl
<< " eval_logic(ivals, ovals);" << endl
<< " }" << endl
<< endl
<< " return 0;" << endl
<< "}" << endl;
}
// @brief 論理シミュレーションを行う.
// @param[in] iv 入力ベクタ
// @param[out] ov 出力ベクタ
void
LsimLcc::eval(const vector<ymuint64>& iv,
vector<ymuint64>& ov)
{
}
END_NAMESPACE_YM
|
#include "horline.h"
Horline::Horline(uint16_t x_, uint16_t y_, uint16_t * color_, uint16_t length_, uint8_t thick_)
:x(x_), y(y_), colorPtr (color_), length (length_), thick (thick_)
{
}
void Horline::draw () const
{
displayDriver->horLine (x, y, colorPtr, length, thick);
}
void Horline::setPosition (uint16_t x_, uint16_t y_)
{
x = x_;
y = y_;
}
|
#include "usefull.h"
U32 U32_big_endian( void * ptr)
{
BYTE *l_ptr = (BYTE *)ptr;
return ( (UI)l_ptr[0]<< 24) + ((UI)l_ptr[1]<< 16) + ((UI)l_ptr[2]<< 8) + ((UI)l_ptr[3]);
}
void U32_big_endian_to_bytes(U32 val, void * ptr)
{
BYTE *l_ptr = (BYTE *)ptr;
l_ptr[0] = val >> 24;
l_ptr[1] = val >> 16;
l_ptr[2] = val >> 8 ;
l_ptr[3] = val;
}
U32 U32_little_endian( void * ptr)
{
BYTE *l_ptr = (BYTE *)ptr;
return ( (UI)l_ptr[3]<< 24) + ((UI)l_ptr[2]<< 16) + ((UI)l_ptr[1]<< 8) + ((UI)l_ptr[0]);
}
void U32_little_endian_to_bytes(U32 val, void * ptr)
{
BYTE *l_ptr = (BYTE *)ptr;
l_ptr[3] = val >> 24;
l_ptr[2] = val >> 16;
l_ptr[1] = val >> 8 ;
l_ptr[0] = val;
}
U32 U32_change_endian(U32 val)
{
U8 temp[4] = {0,0,0,0};
U32_big_endian_to_bytes(val, temp);
return U32_little_endian( temp);
}
__pure int get_bit_num (UI number)
{
int res = 0;
if (number == 0)
return -1;
while ((number & 1) == 0)
{
number >>= 1;
res++;
}
if (number & ~1)
return -2;
return res;
}
__pure int true_get_bit_num (UI number)
{
int res = 0;
if (number == 0)
return -1;
while ((number & 1) == 0)
{
number >>= 1;
res++;
}
return res;
}
__pure UI get_num_of_bit (UI number)
{
int res = 0;
if (number == 0)
return 0;
while (number)
{
if (number & 1)
res++;
number >>= 1;
}
return res;
}
|
#ifndef __MQTTCLIENTHANDLER_H__
#define __MQTTCLIENTHANDLER_H__
/*
https://github.com/eclipse/paho.mqtt.cpp/blob/master/src/samples/async_subscribe.cpp
https://github.com/eclipse/paho.mqtt.cpp/blob/master/src/samples/async_publish.cpp
*/
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cctype>
#include <thread>
#include <chrono>
#include <utility>
#include "mqtt/async_client.h"
// for logs
#define MQTT_SUBSCRIBER "[MQTT_SUBSCRIBER] "
#define MQTT_PUBLISHER "[MQTT_PUBLISHER] "
// general info`s about MQTT
#define MQTT_BROKER_SERVER_ADDRESS "tcp://localhost:1883"
#define MQTT_LWT_PAYLOAD "Last will and testament"
#define QOS 2
#define NR_RETRY_ATTEMPTS 5
#define PUBLISHING_TIMEOUT 10
// subscribers info`s
#define WATER_SUBSCRIBER 1
#define CLIENT_ID_WATER_SUBSCRIBER "water-subscriber"
#define WATER_SUBSCRIBER_TOPIC "airpurifier/water-subscriber"
#define ADDITIONAL_INFO_SUBSCRIBER_TOPIC "airpurifier/info"
// publishers info`s
#define WATER_PUBLISHER 3
#define DISPLAY_PUBLISHER 4
#define CLIENT_ID_WATER_PUBLISHER "water-publisher"
#define CLIENT_ID_DISPLAY_PUBLISHER "display-publisher"
#define WATER_PUBLISHER_TOPIC "airpurifier/water-publish"
#define DISPLAY_PUBLISHER_TOPIC "airpurifier/display"
class MqttClientHandler
{
public:
static void startPublisher(int publisherId);
static void stopPublisher(int publisherId);
static void publishMessage(int publisherId, const std::string &message);
static void startSubscriber(int subscriberId);
static void stopSubscriber(int subscriberId);
[[nodiscard]] static bool isPublisherRunning(int publisherId);
[[nodiscard]] static bool isSubscriberRunning(int subscriberId);
private:
static std::atomic<bool> waterSubscriberIsRunning;
static std::atomic<bool> additionalInfoSubscriberIsRunning;
static std::atomic<bool> waterPublisherIsRunning;
static std::atomic<bool> displayPublisherIsRunning;
static mqtt::async_client *waterPublisherClient;
static mqtt::async_client *displayPublisherClient;
/**
* Local callback & listener class for use with the client connection.
* This is primarily intended to receive messages, but it will also monitor
* the connection to the broker. If the connection is lost, it will attempt
* to restore the connection and re-subscribe to the topic.
*/
class MqttSubscriberCallback : public virtual mqtt::callback, public virtual mqtt::iaction_listener
{
private:
int nrRetry; // Counter for the number of connection retries
mqtt::async_client &asyncClient; // The MQTT client
mqtt::connect_options &connOpts; // Options to use if we need to reconnect
std::string subscribedTopic;
std::string clientId;
// This demonstrates manually reconnecting to the broker by calling
// connect() again. This is a possibility for an application that keeps
// a copy of it's original connect_options, or if the app wants to
// reconnect with different options.
// Another way this can be done manually, if using the same options, is
// to just call the async_client::reconnect() method.
void reconnect();
// Re-connection failure
void on_failure(const mqtt::token &tok) override;
// (Re)connection success
// Either this or connected() can be used for callbacks.
void on_success(const mqtt::token &tok) override;
// (Re)connection success
void connected(const std::string &cause) override;
// Callback for when the connection is lost.
// This will initiate the attempt to manually reconnect.
void connection_lost(const std::string &cause) override;
// Callback for when a message arrives.
void message_arrived(mqtt::const_message_ptr msg) override;
void delivery_complete(mqtt::delivery_token_ptr token) override;
public:
explicit MqttSubscriberCallback(mqtt::async_client &asyncClient, mqtt::connect_options &connOpts,
std::string topic, std::string _clientId) : nrRetry(0),
asyncClient(asyncClient), connOpts(connOpts),
subscribedTopic(std::move(topic)), clientId(std::move(_clientId)){};
};
/** Callback for publisher */
class MqttPublisherCallback : public virtual mqtt::callback
{
private:
std::string clientId;
public:
void connection_lost(const std::string &cause) override;
void delivery_complete(mqtt::delivery_token_ptr tok) override;
explicit MqttPublisherCallback(std::string _clientId) : clientId(std::move(_clientId)){};
};
};
#endif // __MQTTCLIENTHANDLER_H__
|
#include "main.h"
PCREATE_PROCESS_NOTIFY_ROUTINE trampoline = 0;
BYTE shellcode[] =
{
0x50, // push rax
0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, TARGET
0x48, 0x87, 0x04, 0x24, // xchg QWORD PTR[rsp], rax
0xC3 // ret
};
PRTL_PROCESS_MODULES GetModuleList()
{
ULONG buffer_size = 0;
NTSTATUS status = ZwQuerySystemInformation(SystemModuleInformation, &buffer_size, 0, &buffer_size);
if (!buffer_size)
return NULL;
buffer_size *= 2;
auto module_list = reinterpret_cast<PRTL_PROCESS_MODULES>(ExAllocatePool((POOL_TYPE)(PagedPool | POOL_COLD_ALLOCATION), buffer_size));
if (!module_list)
return NULL;
if (NT_SUCCESS(status = ZwQuerySystemInformation(SystemModuleInformation, module_list, buffer_size, &buffer_size)))
return module_list;
ExFreePool(module_list);
return NULL;
}
VOID ToLower(IN CHAR* in, OUT CHAR* out)
{
INT i = -1;
while (in[++i] != '\x00')
{
out[i] = (CHAR)tolower(in[i]);
}
}
UINT_PTR LookupCodecave(IN VOID* module_base, IN INT required_size)
{
auto* dos_header = reinterpret_cast<IMAGE_DOS_HEADER*>(module_base);
auto* nt_headers = reinterpret_cast<IMAGE_NT_HEADERS*>(((BYTE*)dos_header + dos_header->e_lfanew));
UINT_PTR start = 0, size = 0;
UINT_PTR header_offset = (UINT_PTR)IMAGE_FIRST_SECTION(nt_headers);
for (auto x = 0; x < nt_headers->FileHeader.NumberOfSections; ++x)
{
auto* header = reinterpret_cast<IMAGE_SECTION_HEADER*>(header_offset);
if (strcmp((CHAR*)header->Name, ".text") == 0)
{
start = (UINT_PTR)module_base + header->PointerToRawData;
size = header->SizeOfRawData;
break;
}
header_offset += sizeof(IMAGE_SECTION_HEADER);
}
UINT_PTR match = 0;
INT cur_length = 0;
for (auto cur = start; cur < start + size; ++cur)
{
if (*(BYTE*)cur == 0xCC)
{
if (!match)
match = cur;
if (++cur_length == required_size)
return match;
}
else
match = cur_length = 0;
}
return NULL;
}
BOOLEAN WriteToReadOnlyMemory(IN VOID* destination, IN VOID* source, IN ULONG size)
{
PMDL mdl = IoAllocateMdl(destination, size, FALSE, FALSE, 0);
if (!mdl)
return FALSE;
MmProbeAndLockPages(mdl, KernelMode, IoReadAccess);
PVOID map_address = MmMapLockedPagesSpecifyCache(mdl, KernelMode, MmNonCached, 0, FALSE, NormalPagePriority);
if (!map_address)
{
MmUnlockPages(mdl);
IoFreeMdl(mdl);
return FALSE;
}
NTSTATUS status = MmProtectMdlSystemAddress(mdl, PAGE_EXECUTE_READWRITE);
if (!NT_SUCCESS(status))
{
MmUnmapLockedPages(map_address, mdl);
MmUnlockPages(mdl);
IoFreeMdl(mdl);
return FALSE;
}
RtlCopyMemory(map_address, source, size);
MmUnmapLockedPages(map_address, mdl);
MmUnlockPages(mdl);
IoFreeMdl(mdl);
return TRUE;
}
NTSTATUS SetCreateProcessNotifyRoutine(IN PCREATE_PROCESS_NOTIFY_ROUTINE NotifyRoutine, OUT PCREATE_PROCESS_NOTIFY_ROUTINE* TrampolineBase)
{
NTSTATUS status;
// Get a list of all loaded modules
PRTL_PROCESS_MODULES modules = GetModuleList();
if (!modules)
{
log("GetModuleList() failed");
return STATUS_UNSUCCESSFUL;
}
UINT_PTR found_address = 0;
char driver_name[0x100] = { 0 };
// Iterate them all to find a suitable code cave for our shellcode
for (auto i = 1; i < modules->NumberOfModules; ++i)
{
auto* module = &modules->Modules[i];
ToLower((CHAR*)module->FullPathName, driver_name);
// Filter a bit
if (strlen(driver_name) < 10 || !strstr(driver_name + strlen(driver_name) - 5, ".sys") || strstr(driver_name, "win32kbase") || strstr(driver_name, "clfs"))
continue;
// Try to find a suitable code cave, stop iterating if so
if (found_address = LookupCodecave(module->ImageBase, sizeof(shellcode)))
{
log("Found codecave in %s", driver_name + module->OffsetToFileName);
break;
}
}
// This is not supposed to happen
if (!found_address)
{
log("Unable to find any suitable code cave, aborting...");
return STATUS_UNSUCCESSFUL;
}
// Prepare shellcode with our routine address
*(UINT_PTR*)(shellcode + 3) = (UINT_PTR)NotifyRoutine;
// Write shellcode in the found code cave
if (!WriteToReadOnlyMemory((VOID*)found_address, shellcode, sizeof(shellcode)))
{
log("WriteToReadOnlyMemory failed");
return STATUS_UNSUCCESSFUL;
}
// Out address
*TrampolineBase = (PCREATE_PROCESS_NOTIFY_ROUTINE)found_address;
// Call PsSetCreateProcessNotifyRoutine to register the callback
if (!NT_SUCCESS(status = PsSetCreateProcessNotifyRoutine((PCREATE_PROCESS_NOTIFY_ROUTINE)found_address, FALSE)))
{
log("PsSetCreateProcessNotifyRoutine failed with status 0x%X", status);
return status;
}
// Ok
log("SetCreateProcessNotifyRoutine succeeded");
return STATUS_SUCCESS;
}
NTSTATUS UnSetCreateProcessNotifyRoutine(IN PCREATE_PROCESS_NOTIFY_ROUTINE TrampolineBase)
{
// First we unregister the callback right way
NTSTATUS status = PsSetCreateProcessNotifyRoutine(TrampolineBase, TRUE);
if (!NT_SUCCESS(status))
{
log("PsSetCreateProcessNotifyRoutine failed with status 0x%X", status);
return status;
}
// Now we want to restore the original bytes where we wrote the trampoline
auto pool = ExAllocatePool(NonPagedPool, sizeof(shellcode));
if (!pool)
{
log("ExAllocatePool failed");
return STATUS_UNSUCCESSFUL;
}
// Fill the buffer with 0xCC
memset(pool, 0xCC, sizeof(shellcode));
// Write buffer
if (!WriteToReadOnlyMemory(TrampolineBase, pool, sizeof(shellcode)))
{
log("WriteToReadOnlyMemory failed");
ExFreePool(pool);
return STATUS_UNSUCCESSFUL;
}
// Free previously allocated buffer
ExFreePool(pool);
// Ok
log("UnSetCreateProcessNotifyRoutine succeeded");
return STATUS_SUCCESS;
}
VOID CreateProcessNotifyRoutine(HANDLE ParentId, HANDLE ProcessId, BOOLEAN Create)
{
log("CreateProcessNotifyRoutine(%d, %d, %s)", ParentId, ProcessId, Create != FALSE ? "TRUE" : "FALSE");
}
VOID Sleep(LONGLONG milliseconds)
{
LARGE_INTEGER timeout;
timeout.QuadPart = RELATIVE(MILLISECONDS(milliseconds));
KeDelayExecutionThread(KernelMode, FALSE, &timeout);
}
VOID PoofOfConcept()
{
// First, let's try to call PsSetCreateProcessNotifyRoutine
// STATUS_ACCESS_DENIED expected because of MmVerifyCallbackFunctionCheckFlags!
NTSTATUS status = PsSetCreateProcessNotifyRoutine(CreateProcessNotifyRoutine, FALSE);
log("PsSetCreateProcessNotifyRoutine returned 0x%X (expected 0x%X)", status, STATUS_ACCESS_DENIED);
if (NT_SUCCESS(status))
{
PsSetCreateProcessNotifyRoutine(CreateProcessNotifyRoutine, TRUE);
}
// Register the callback
if (!NT_SUCCESS(status = SetCreateProcessNotifyRoutine(CreateProcessNotifyRoutine, &trampoline)))
{
log("SetCreateProcessNotifyRoutine failed with status 0x%X", status);
return;
}
// Ok
log("Successfully registered notify routine, trampoline at 0x%p", trampoline);
log("Notify routine will be unregistered in 5 seconds...");
// Wait a bit
Sleep(5 * 1000);
log("Unregistering routine...");
// Unregister the callback
status = UnSetCreateProcessNotifyRoutine(trampoline);
if (!NT_SUCCESS(status))
{
log("UnSetCreateProcessNotifyRoutine failed with status 0x%X", status);
return;
}
log("Successfully unregistered notify routine");
}
EXTERN_C NTSTATUS DriverEntry(IN PVOID AllocationBase, IN DWORD32 AllocationSize)
{
log("DriverEntry(0x%p, 0x%X)", AllocationBase, AllocationSize);
HANDLE thread_handle;
NTSTATUS status = PsCreateSystemThread(&thread_handle, THREAD_ALL_ACCESS, NULL, NULL, NULL, (KSTART_ROUTINE*)PoofOfConcept, NULL);
if (!NT_SUCCESS(status))
{
log("PsCreateSystemThread failed with status 0x%X", status);
return status;
}
if (thread_handle)
ZwClose(thread_handle);
return STATUS_SUCCESS;
}
|
//
// SMButton.h
// SMFrameWork
//
// Created by KimSteve on 2016. 11. 4..
//
//
#ifndef SMButton_h
#define SMButton_h
#include "SMView.h"
#include <2d/CCLabel.h>
class ShapeSolidRect; // for under line
class SMButton : public _UIContainerView
{
public:
SMButton();
virtual ~SMButton();
// button style
enum class Style {
DEFAULT, // image and text without solid-color and out-line
RECT, // only out-line Rectangle
ROUNDEDRECT, // only out-line Rounded Rect
CIRCLE, // only out-line Circle
SOLID_RECT, // has solid-color and out-line color
SOLID_ROUNDEDRECT, // has solid-color and out-line color
SOLID_CIRCLE, // has solid-color and out-line color
};
// icon align
enum class Align {
CENTER,
LEFT,
RIGHT,
TOP,
BOTTOM
};
public:
// creator
// basic
static SMButton * create(int tag=0, Style style=Style::SOLID_RECT) {
SMButton * buton = new (std::nothrow)SMButton();
if (buton && buton->initWithStyle(style)) {
buton->setTag(tag);
buton->autorelease();
} else {
CC_SAFE_DELETE(buton);
}
return buton;
};
// specific
static SMButton * create(int tag, Style style, float x, float y, float width, float height, float anchorX=0.0f, float anchorY=0.0f) {
SMButton * button = SMButton::create(tag, style);
if (button != nullptr) {
button->setAnchorPoint(cocos2d::Vec2(anchorX, anchorY));
button->setPosition(cocos2d::Vec2(x, y));
button->setContentSize(cocos2d::Size(width, height));
}
return button;
}
public:
// public method
virtual bool isTouchEnable() const override;
virtual void setContentSize(const cocos2d::Size& size) override;
cocos2d::Label * getTextLabel();
// push state added effect
void setPushDownOffset(const cocos2d::Vec2& offset);
void setPushDownScale(const float scale);
// set color
void setButtonColor(const State state, const cocos2d::Color4F& color);
void setTextColor(const State state, const cocos2d::Color4F& color);
void setIconColor(const State state, const cocos2d::Color4F& color);
void setOutlineWidth(float lineWidth);
void setOutlineColor(const State state, const cocos2d::Color4F& color);
void setButton(const State state, cocos2d::Node * node);
void setButton(const State state, cocos2d::SpriteFrame * frame, bool enableScale9);
void setButton(const State state, const std::string& imageFileName, bool enableScale9);
void setIcon(const State state, cocos2d::Node * node);
void setIcon(const State state, cocos2d::SpriteFrame * frame);
void setIcon(const State state, const std::string& imageFileName);
void setText(const std::string& text);
void setTextTTF(const std::string& text, const std::string& fontFileName, float fontSize);
void setTextTTF(const std::string& text, const cocos2d::TTFConfig& ttfConfig);
void setTextSystemFont(const std::string& text, float fontSize);
void setTextSystemFont(const std::string& text, const std::string& fontName, float fontSize);
void setUnderline();
void setIconPadding(float padding);
void setIconScale(float scale);
void setTextScale(float scale);
void setIconOffset(cocos2d::Vec2& offset);
void setTextOffset(cocos2d::Vec2& offset);
// for circle, rounded-rect
void setShapeCornerRadius(float radius);
void setShapeCornerQuadrant(int quadrant);
void setShapeAntiAliasWidth(float width);
void setShapeLineWidth(float width);
void setIconAlign(Align align=Align::CENTER);
cocos2d::Color4F* getButtonColor(const State state);
cocos2d::Color4F* getIconColor(const State state);
cocos2d::Color4F* getTextColor(const State state);
cocos2d::Color4F* getOutlineColor(const State state);
cocos2d::Node* getButtonNode(const State state);
cocos2d::Node* getIconNode(const State state);
protected:
// initialize
virtual bool initWithStyle(const Style style);
virtual void onStateChangePressToNormal() override;
virtual void onStateChangeNormalToPress() override;
virtual void onUpdateStateTransition(State toState, float t);
virtual void onUpdateOnVisit() override;
private:
class _StateTransitionAction;
class _ReleaseActionStarter;
Style _style;
Align _align;
cocos2d::Label * _textLabel;
cocos2d::Color4F** _textColor;
cocos2d::Color4F** _iconColor;
cocos2d::Color4F** _buttonColor;
cocos2d::Color4F** _outlineColor;
cocos2d::Node** _buttonNode;
cocos2d::Node** _iconNode;
cocos2d::Vec2 _pushDownOffset;
ShapeSolidRect * _textUnderline;
float _pushDownScale;
float _iconScale;
float _textScale;
float _iconPadding;
cocos2d::Vec2 _iconOffset;
cocos2d::Vec2 _textOffset;
float _shapeRadius;
int _shapeQuadrant;
float _shapeLineWidth;
float _shapeAntiAliasWidth;
float _shapeOutlineWidth;
_StateTransitionAction* _buttonPressAction;
_StateTransitionAction* _buttonReleaseAction;
float _buttonPressActionTime;
float _buttonReleaseActionTime;
float _buttonStateValue;
void setStateColor(cocos2d::Color4F*** target, State state, const cocos2d::Color4F& color);
void setStateNode(cocos2d::Node*** target, State state, cocos2d::Node* node, const int localZOrder, cocos2d::Color4F*** targetColor);
void colorChangeSrcNodeToDstNode(cocos2d::Node* srcNode, cocos2d::Node* dstNode, cocos2d::Color4F* srcColor, cocos2d::Color4F* dstColor, float t);
private:
DISALLOW_COPY_AND_ASSIGN(SMButton);
};
#endif /* SMButton_h */
|
#ifndef DE_RENDERBUFFER_H
#define DE_RENDERBUFFER_H
#include "export.h"
#include "core/CountedObject.h"
#include "data/Texture.h"
#include <gl/glew.h>
#include <list>
namespace de
{
class DE_EXPORT RenderBuffer
{
protected:
unsigned int mWidth;
unsigned int mHeight;
GLuint mID;
int mCurrentAttachementMax;
std::list<data::Texture*> mTextures;
public:
RenderBuffer();
~RenderBuffer();
/**
* \brief if pCreateDefault is true, we create a default color attachement and a defaut depth renderbuffer
*/
void init(unsigned int pWidth, unsigned int pHeight, bool pCreateDefault = true);
/**
* \brief pAttachement is the OpenGL enum that definie the attachement.
*/
void addTexture(data::Texture* pTexture, GLint pAttachement = -1);
void bind() const;
void unbind() const;
const std::list<data::Texture*>& getTextures() const;
};
}
#endif
|
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
int sz = nums.size();
int temp;
for(int first = 0; first < sz; first++)
{
if(first > 0 && nums[first] == nums[first-1]) continue;
temp = nums[first];
for(int second = first+1; second < sz; second++)
{
if(second > first+1 && nums[second] == nums[second-1]) continue;
int forth = sz - 1;
for(int third = second + 1; third < sz; third++)
{
if(third > second + 1 && nums[third] == nums[third-1]) continue;
while(third < forth && temp + nums[third] + nums[forth] + nums[second] > target)
{
forth--;
}
if(third == forth) break;
if(temp + nums[third] + nums[forth] + nums[second] == target)
{
result.push_back({nums[first],nums[second],nums[third],nums[forth]});
}
}
}
}
return result;
}
};
|
#include "common.h"
#include "randgen.h"
namespace {
float glc(float crd, float crd0, float acrd) {
return (crd - crd0)/acrd;
}
//line обязательно валидная
float getSingleLambdaCoeff(const line &l, const QVector3D &p) {
if (l.ax != 0) {
return glc(p.x(), l.x0, l.ax);
} else if (l.ay != 0) {
return glc(p.y(), l.y0, l.ay);
} else {//az != 0
return glc(p.z(), l.z0, l.az);
}
}
QVector3D getPointForLambda(const line &l, float lambda) {
QVector3D p;
p.setX(l.x0 + l.ax*lambda);
p.setY(l.y0 + l.ay*lambda);
p.setZ(l.z0 + l.az*lambda);
return p;
}
}//namespace
bool onOneLine(const QVector3D &a, const QVector3D &b, const QVector3D &c)
{
line l = lineEquation(a, b);
if (!l.isValid()) {//a и b - одна и та же точка
return true;
}
float lambda = getSingleLambdaCoeff(l, c);
return getPointForLambda(l, lambda) == c;
}
bool onOnePlane(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &d)
{
plane p = planeEquation(a, b, c);
return p.a*d.x() + p.b*d.y() + p.c*d.z() + p.d == 0;
}
plane planeEquation(const QVector3D &m0, const QVector3D &m1, const QVector3D &m2)
{
float vx10 = m1.x() - m0.x();
float vx20 = m2.x() - m0.x();
float vy10 = m1.y() - m0.y();
float vy20 = m2.y() - m0.y();
float vz10 = m1.z() - m0.z();
float vz20 = m2.z() - m0.z();
float detx = vy10*vz20 - vz10*vy20;
float dety = -(vx10*vz20 - vz10*vx20);
float detz = vx10*vy20 - vy10*vx20;
float d = -m0.x()*detx - m0.y()*dety - m0.z()*detz;
return plane{detx, dety, detz, d};
}
line lineEquation(const QVector3D &a, const QVector3D &b)
{
if (a == b) {//невалидная линия
return line();
}
QVector3D pv(a.x() - b.x(), a.y() - b.y(), a.z() - b.z());
return line(a, pv);
}
line::line(const QVector3D &point, const QVector3D &vector)
: x0(point.x())
, y0(point.y())
, z0(point.z())
, ax(vector.x())
, ay(vector.y())
, az(vector.z())
{}
bool line::isValid() const {
return !(ax == 0 && ay == 0 && az == 0);
}
bool plane::isValid() const {
return !(a == 0 && b == 0 && c == 0 && d == 0);
}
void plane::reverse()
{
a = -a;
b = -b;
c = -c;
d = -d;
}
float plane::setPoint(const QVector3D &p) const
{
return a*p.x() + b*p.y() + c*p.z() + d;
}
QVector3D randomPoint(const QVector3D &mins, const QVector3D &maxs)
{
RandomGenerator xgen(mins.x(), maxs.x());
RandomGenerator ygen(mins.y(), maxs.y());
RandomGenerator zgen(mins.z(), maxs.z());
return QVector3D(xgen(), ygen(), zgen());
}
|
/**
* Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "multimedia/ashmem.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <linux/types.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
int ashmem_create_block(const char *name, int size)
{
int fd = -1;
char buf[ASM_NAME_LEN] = {'\0'};
fd = open(ASM_NAME, O_RDWR);
if (fd < 0) {
printf("open ashmem failed");
return fd;
}
if (name != NULL) {
strncpy(buf, name, ASM_NAME_LEN - 1);
if(ioctl(fd, ASHMEM_SET_NAME, buf) < 0) {
close(fd);
return -1;
}
}
if (ioctl(fd, ASHMEM_SET_SIZE, size) < 0) {
close(fd);
return -1;
}
return fd;
}
int ashmem_set_prot_block(int fd, int prot)
{
return ioctl(fd, ASHMEM_SET_PROT_MASK, prot);
}
int ashmem_pin_block(int fd, struct ashmen_pin *pin)
{
if (pin == NULL) {
return -1;
}
return ioctl(fd, ASHMEM_PIN, pin);
}
int ashmem_unpin_block(int fd, struct ashmen_pin *pin)
{
if (pin == NULL) {
return -1;
}
return ioctl(fd, ASHMEM_UNPIN, pin);
}
int ashmem_get_size_block(int fd)
{
return ioctl(fd, ASHMEM_GET_SIZE, NULL);
}
|
// Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "SACPP/Public/CPPW_Quit.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeCPPW_Quit() {}
// Cross Module References
SACPP_API UClass* Z_Construct_UClass_UCPPW_Quit_NoRegister();
SACPP_API UClass* Z_Construct_UClass_UCPPW_Quit();
UMG_API UClass* Z_Construct_UClass_UUserWidget();
UPackage* Z_Construct_UPackage__Script_SACPP();
UMG_API UClass* Z_Construct_UClass_UButton_NoRegister();
// End Cross Module References
DEFINE_FUNCTION(UCPPW_Quit::execButtonNoOnClicked)
{
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->ButtonNoOnClicked();
P_NATIVE_END;
}
DEFINE_FUNCTION(UCPPW_Quit::execButtonYesOnClicked)
{
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->ButtonYesOnClicked();
P_NATIVE_END;
}
void UCPPW_Quit::StaticRegisterNativesUCPPW_Quit()
{
UClass* Class = UCPPW_Quit::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "ButtonNoOnClicked", &UCPPW_Quit::execButtonNoOnClicked },
{ "ButtonYesOnClicked", &UCPPW_Quit::execButtonYesOnClicked },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_UCPPW_Quit_ButtonNoOnClicked_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UCPPW_Quit_ButtonNoOnClicked_Statics::Function_MetaDataParams[] = {
{ "Category", "Input" },
{ "ModuleRelativePath", "Public/CPPW_Quit.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UCPPW_Quit_ButtonNoOnClicked_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UCPPW_Quit, nullptr, "ButtonNoOnClicked", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04040401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UCPPW_Quit_ButtonNoOnClicked_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UCPPW_Quit_ButtonNoOnClicked_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UCPPW_Quit_ButtonNoOnClicked()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UCPPW_Quit_ButtonNoOnClicked_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UCPPW_Quit_ButtonYesOnClicked_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UCPPW_Quit_ButtonYesOnClicked_Statics::Function_MetaDataParams[] = {
{ "Category", "Input" },
{ "ModuleRelativePath", "Public/CPPW_Quit.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UCPPW_Quit_ButtonYesOnClicked_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UCPPW_Quit, nullptr, "ButtonYesOnClicked", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04040401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UCPPW_Quit_ButtonYesOnClicked_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UCPPW_Quit_ButtonYesOnClicked_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UCPPW_Quit_ButtonYesOnClicked()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UCPPW_Quit_ButtonYesOnClicked_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UCPPW_Quit_NoRegister()
{
return UCPPW_Quit::StaticClass();
}
struct Z_Construct_UClass_UCPPW_Quit_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_NoButton_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_NoButton;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_YesButton_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_YesButton;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UCPPW_Quit_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UUserWidget,
(UObject* (*)())Z_Construct_UPackage__Script_SACPP,
};
const FClassFunctionLinkInfo Z_Construct_UClass_UCPPW_Quit_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_UCPPW_Quit_ButtonNoOnClicked, "ButtonNoOnClicked" }, // 757794277
{ &Z_Construct_UFunction_UCPPW_Quit_ButtonYesOnClicked, "ButtonYesOnClicked" }, // 56156621
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCPPW_Quit_Statics::Class_MetaDataParams[] = {
{ "IncludePath", "CPPW_Quit.h" },
{ "ModuleRelativePath", "Public/CPPW_Quit.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_NoButton_MetaData[] = {
{ "BindWidget", "" },
{ "Category", "Components" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "Public/CPPW_Quit.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_NoButton = { "NoButton", nullptr, (EPropertyFlags)0x001000000008000d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UCPPW_Quit, NoButton), Z_Construct_UClass_UButton_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_NoButton_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_NoButton_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_YesButton_MetaData[] = {
{ "BindWidget", "" },
{ "Category", "Components" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "Public/CPPW_Quit.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_YesButton = { "YesButton", nullptr, (EPropertyFlags)0x001000000008000d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UCPPW_Quit, YesButton), Z_Construct_UClass_UButton_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_YesButton_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_YesButton_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UCPPW_Quit_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_NoButton,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCPPW_Quit_Statics::NewProp_YesButton,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_UCPPW_Quit_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UCPPW_Quit>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UCPPW_Quit_Statics::ClassParams = {
&UCPPW_Quit::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_UCPPW_Quit_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_Quit_Statics::PropPointers),
0,
0x00B010A0u,
METADATA_PARAMS(Z_Construct_UClass_UCPPW_Quit_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_Quit_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UCPPW_Quit()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UCPPW_Quit_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UCPPW_Quit, 1846223281);
template<> SACPP_API UClass* StaticClass<UCPPW_Quit>()
{
return UCPPW_Quit::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UCPPW_Quit(Z_Construct_UClass_UCPPW_Quit, &UCPPW_Quit::StaticClass, TEXT("/Script/SACPP"), TEXT("UCPPW_Quit"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UCPPW_Quit);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
|
#include "SaveLoad.h"
void SAVE(void* addressOfObject, const int sizeOfClass, ofstream& out)
{
out.write(reinterpret_cast<char*>(addressOfObject), sizeOfClass); //write
}
void LOAD(void* addressOfObject, const int sizeOfClass, ifstream& in) {
in.read(reinterpret_cast<char*>(addressOfObject), sizeOfClass);
}
|
/////////////////////////////////////////////////////////////////////////////////////////
// FILE NAME: Control.cpp
//
// DESCRIPTION: CONTROL Class implementation. This class handles the two Status Registers
// and the Timers chips.
//
/////////////////////////////////////////////////////////////////////////////////////////
#include "Control.h"
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::CONTROL(unsigned int* pPiraq_BaseAddress)
//
// DESCRIPTION: Constructor that recieves the base address to the Piraq board.
// This address is used to determine the address to the Status Registers and
// the Timers.
//
// INPUT PARAMETER(s):
// unsigned int* pPiraq_BaseAddress - Address of Piraq board
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
CONTROL::CONTROL(unsigned int* pPiraq_BaseAddress)
{
// Set address to Piraq Board
m_pPiraq_BaseAddress = pPiraq_BaseAddress;
// Set address of status registers
pStatus0 = (unsigned short*)(((unsigned char *)m_pPiraq_BaseAddress )+ 0x1400);
pStatus1 = (unsigned short*)(((unsigned char *)m_pPiraq_BaseAddress )+ 0x1410);
// Set address of timers
pTimer0 = (unsigned int *)(((unsigned char *)m_pPiraq_BaseAddress) + 0x1000);
pTimer1 = (unsigned int *)(((unsigned char *)m_pPiraq_BaseAddress) + 0x1010);
// Reset Dsp to put it into a known state
ResetPiraqBoard();
// Turn the PC LED off
m_LEDState = 0; // used to remember the state of the LED
UnSetBit_StatusRegister0(STAT0_PCLED);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::~CONTROL()
//
// DESCRIPTION: Destructor
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
CONTROL::~CONTROL()
{
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::SetValue_StatusRegister0(unsigned short usValue)
//
// DESCRIPTION: Sets the entire Status Register 0 to this value
//
// INPUT PARAMETER(s):
// unsigned short usValue - Value to set register to
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::SetValue_StatusRegister0(unsigned short usValue)
{
// Store Value for later
StatusRegister0Value = usValue;
// Set register with value;
*pStatus0 = StatusRegister0Value;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::SetBit_StatusRegister0(unsigned short usBit)
//
// DESCRIPTION: Sets only this bit in Status Register 0
//
// INPUT PARAMETER(s):
// unsigned short usBit - Bit to set such as 0x0002 would put a 1 in the second bit
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::SetBit_StatusRegister0(unsigned short usBit)
{
// Add bit(s) to stored value from last time
StatusRegister0Value = StatusRegister0Value | usBit;
// Set register with new value
*pStatus0 = StatusRegister0Value;
// Note that some bits are write only.
// So one can not read the value, OR in the bits, and re-write the value
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::UnSetBit_StatusRegister0(unsigned short usBit)
//
// DESCRIPTION: Removes only this bit in Status Register 0
//
// INPUT PARAMETER(s):
// unsigned short usBit - Bit to remove such as 0x0002 would put a 0 in the second bit
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::UnSetBit_StatusRegister0(unsigned short usBit)
{
// Remove bit(s) to stored value from last time
StatusRegister0Value = StatusRegister0Value & ~usBit;
// Set register with new value
*pStatus0 = StatusRegister0Value;
// Note that some bits are write only.
// So one can not read the value, OR in the bits, and re-write the value
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::SetValue_StatusRegister1(unsigned short usValue)
//
// DESCRIPTION: Sets the entire Status Register 1 to this value
//
// INPUT PARAMETER(s):
// unsigned short usValue - Value to set register to
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::SetValue_StatusRegister1(unsigned short usValue)
{
// Store Value for later
StatusRegister1Value = usValue;
// Set register with value;
//!!!!!!0??????? *pStatus1 = StatusRegister0Value;
*pStatus1 = StatusRegister1Value;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::SetBit_StatusRegister1(unsigned short usBit)
//
// DESCRIPTION: Sets only this bit in Status Register 1
//
// INPUT PARAMETER(s):
// unsigned short usBit - Bit to set such as 0x0002 would put a 1 in the second bit
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::SetBit_StatusRegister1(unsigned short usBit)
{
// Add bit(s) to stored value from last time
StatusRegister1Value = StatusRegister1Value | usBit;
// Set register with new value
*pStatus1 = StatusRegister1Value;
// Note that some bits are write only.
// So one can not read the value, OR in the bits, and re-write the value
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::UnSetBit_StatusRegister1(unsigned short usBit)
//
// DESCRIPTION: Removes only this bit in Status Register 1
//
// INPUT PARAMETER(s):
// unsigned short usBit - Bit to remove such as 0x0002 would put a 0 in the second bit
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::UnSetBit_StatusRegister1(unsigned short usBit)
{
// Remove bit(s) from stored value from last time
StatusRegister1Value = StatusRegister1Value & ~usBit;
// Set register with new value
*pStatus1 = StatusRegister1Value;
// Note that some bits are write only.
// So one can not read the value, OR in the bits, and re-write the value
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::ResetDsp()
//
// DESCRIPTION: Performs a software reset. This should put the DSP in a known state
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::ResetPiraqBoard()
{
// Put timers and PLDs into a known state
InitTimers();
// Put DSP into a reset state
UnSetBit_StatusRegister0(STAT0_SW_RESET);
Sleep(1);
// Take DSP out of the reset state
SetBit_StatusRegister0(STAT0_SW_RESET);
Sleep(1);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::InteruptDSP()
//
// DESCRIPTION: Interupts the DSP
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::InteruptDSP()
{
UnSetBit_StatusRegister1(STAT1_PCI_INT);
SetBit_StatusRegister1(STAT1_PCI_INT);
// Once the STAT1_PCI_INT bit is set, the DSP will continue
// with it's code. If this is the semaphore stating that the
// parameters are set, then it will start to read in the parameters
// from host memory. If the Host application attempts to read or
// write to the registers, LEDs, Fifo's, etc on the Piraq board
// while the DSP is accessing host memory via the PLX PCI chip, then
// a dead lock can occure.
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::ToggleLED()
//
// DESCRIPTION: Toggles the PC LED on and off based on the state.
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::ToggleLED()
{
// Turn the PC LED on the board on and off by alternating
// between one and zero in the setting.
if (m_LEDState)
{
UnSetBit_StatusRegister0(STAT0_PCLED);
m_LEDState = 0;
}
else
{
SetBit_StatusRegister0(STAT0_PCLED);
m_LEDState = 1;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::StopDsp()
//
// DESCRIPTION: Stops the DSP by stopping the Timers and Reseting the DSP
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::StopDsp()
{
// Put DSP into a reset state
UnSetBit_StatusRegister0(STAT0_SW_RESET);
Sleep(1);
// Take DSP out of the reset state
SetBit_StatusRegister0(STAT0_SW_RESET);
Sleep(1);
}
//****************** Timers **********************************
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::InitTimers()
//
// DESCRIPTION: Puts timers into a know state
//
// INPUT PARAMETER(s):
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::InitTimers()
{
// Stop Timers
StopTimers();
// Set TimerChip0 - Counter0 into known state
SetTimerRegister(Counter_0,HStrobe,2,pTimer0);
// Set TimerChip0 - Counter1 into known state
SetTimerRegister(Counter_1,HStrobe,2,pTimer0);
// Set TimerChip0 - Counter2 into known state
SetTimerRegister(Counter_2,HStrobe,2,pTimer0);
// Set TimerChip1 - Counter0 into known state
SetTimerRegister(Counter_0,HStrobe,2,pTimer1);
// Set TimerChip1 - Counter1 into known state
SetTimerRegister(Counter_1,HStrobe,2,pTimer1);
// Set TimerChip1 - Counter2 into known state
SetTimerRegister(Counter_2,HStrobe,2,pTimer1);
// Set Status Register 0 with timing values
// Do not do a SW_Reset
SetValue_StatusRegister0(0x1);
// Set Status Register 1 with timing values
SetValue_StatusRegister1(0x0000);
return;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::StartTimers()
//
// DESCRIPTION: Starts the Timers
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::StartTimers()
{
// Take Timer out of reset by seting bit 1 (TRESET) to 1
SetBit_StatusRegister0(STAT0_TRESET);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::StopTimers()
//
// DESCRIPTION: Stops the Timers
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::StopTimers()
{
// Put Timer into reset by seting bit 1 (TRESET) to 0
UnSetBit_StatusRegister0(STAT0_TRESET);
// Wait for all timers to time-out
Sleep(30);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::SetUpTimers(float fFrequencyHz, long lTransmitPulseWidthNs,long lPreTRNs,
// long lTimeDelayToFirstGateNs, long lGateSpacingNs, long lNumRangeGates)
//
// DESCRIPTION: Sets up the Timers by actually setting the correct values into the timer chips
// and setting the correct values into the status registers
//
// program the timer for different modes with
//
// mode: 0 = continuous mode, 1 = trigger mode, 2 = sync mode
// gate0mode: 0 = regular gate 0, 1 = expanded gate 0
// gatecounts: gate spacing in 10 MHz counts
// numbergates: number of range gates
// timecounts: modes 1 and 2: delay (in 10 MHz counts) after trigger
// before sampling gates
// mode 0: pulse repetition interval in 10 MHz counts
//
// For sync mode (mode 0), delaycounts defines the sync time.
// The prt delay must be reprogrammed after the FIRST signal is detected.
//
//
// INPUT PARAMETER(s):
// float fFrequencyHz - Radar Frequency in Hz
// long lTransmitPulseWidthNs - Width of the Transmit pulse in nanoseconds
// long lPreTRNs - Time from start of Sync pulse to start of Transmit pulse in nanoseconds
// long lTimeDelayToFirstGateNs - Time from end of Transmit pulse to start of first sampling gate in nanoseconds
// long lGateSpacingNs - Time from one sampling gate to the next in nanoseconds
// long lNumRangeGates - Number of sampling gates
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
int CONTROL::SetUpTimers(float fFrequencyHz, long lTransmitPulseWidthNs,long lPreBlankNs,
long lTimeDelayToFirstGateNs, long lGateSpacingNs, long lNumRangeGates,
int iTimerDivide, int iGateSpacingInClockCycles, long lNumCodeBits)
{
// Stop Timers
StopTimers();
if(lNumCodeBits == 0)
{
lNumCodeBits = 1;
}
// *** Set DELAY - Which is the time from the Sync pulse to the first Sample gate.
// Calculate the number of clock cycles to just before the first gate starting at the
// rising edge of the sync pulse. Notice that one GateSpacing has been removed from this
// time. This is becuase the PLD logic takes one full GateSpaceing of time before putting
// out the first gate.
// Divide by iTimerDivide because the Timer chip can not run at 48MHz.
// The timer clock is 48Mhz/iTimerDivide.
// Truncate so that it falls just short of the first gate
m_iCountsPerDelay = ((int)((lPreBlankNs + (lNumCodeBits * lTransmitPulseWidthNs) + lTimeDelayToFirstGateNs - lGateSpacingNs)*fFrequencyHz*1e-9)/iTimerDivide);
// Set TimerChip0 - Counter2 with Delay to Gates
SetTimerRegister(Counter_2,HStrobe,m_iCountsPerDelay,pTimer0);
// *** Set 'Number Of Gates' - Which is the time to the end of Sample gates.
// The time starts when the DELAY timer triggers (1 GateSpacing before the first Sample gate)
// Calculate the number of clock cycles it takes to include all gates.
// Add .5 gates to correctly place the EOF that happens after each set of gates.
// Divide by iTimerDivide because the Timer chip can not run at 48MHz.
// The timer clock is 48Mhz/iTimerDivide.
// Round up so that it includeds all gates
m_iCountsForAllGates = (int)ceil(( iGateSpacingInClockCycles * (lNumRangeGates + .5) )/iTimerDivide);
// Set TimerChip1 - Counter1 with time of all Gates
SetTimerRegister(Counter_1,HStrobe,m_iCountsForAllGates,pTimer1);
// Set the Timer Divide ratio into the PLDs
// The PLDs divide the input clock by the iTimerDivide ratio.
// The IPP length must be an even multiple of this divide ratio.
// Thus the PLDs have to be set to the same ratio or the input Sync pulse
// will not come out of the PLD as the 'Trigger' pulse.
// FINISH - 1/6th does not work because we can not figure out how to set GateClk
if(iTimerDivide == 8)
{
// Set bits 0 & 1 to 0
m_iSpare = 0x0;
}
else if (iTimerDivide == 6)
{
// Set bit 0 to 1 and bit 1 to 1
m_iSpare = STAT1_SPARE0;
}
else
{
// Default to 6
// Set bit 0 to 1 and bit 1 to 1
m_iSpare = STAT1_SPARE0;
}
// Depending on the lTransmit Pulse Width, the FIR is either in /1 , /2 or /4 mode
if ( lTransmitPulseWidthNs < 1000 /*ns*/ )
{
// Set counter to divide input ADC sample clock by 0
m_iSpare = m_iSpare | 0x000;
// *** Set GLEN0 - GLEN3 - Which is the number of clock cycles per Gate
// The count is for only one half of a full Gate Spacing.
// Because of this, it has already been made a multiple of 2 clock cycles.
// Subtract 1 from the count because the PLD uses 1 clock cycle to reload the counters, once for each GLEN.
// Shift left to 9th bit location to put into the correct place in the registers.
m_iGateLengthCount = ((iGateSpacingInClockCycles/2) - 1) << 9;
// Store value for future reference
m_iCountsPerGatePulse = m_iGateLengthCount >> 9;
}
else if (lTransmitPulseWidthNs < 2000 /*ns*/ )
{
// Set counter to divide input ADC sample clock by 2
m_iSpare = m_iSpare | STAT1_SPARE2;
// *** Set GLEN0 - GLEN3 - Which is the number of clock cycles per Gate
// The count is for only one half of a full Gate Spacing.
// Because of this, it has already been made a multiple of 2 clock cycles.
// It has also already been made a multiple of 4 clock cycles because we are also dividing the clock in half.
// Subtract 2 from the count because the PLD uses 1 divided clock cycle to reload the counters, once for each GLEN.
// Shift left to 9th bit location to put into the correct place in the registers.
// By shifting left only 8 bits we are dividing the count by 2 because the clock has been divided in half.
m_iGateLengthCount = ((iGateSpacingInClockCycles/2) - 2) << 8;
// Store value for future reference
m_iCountsPerGatePulse = m_iGateLengthCount >> 9;
}
else
{
// Set counter to divide input ADC sample clock by 4
m_iSpare = m_iSpare | STAT1_SPARE3;
// *** Set GLEN0 - GLEN3 - Which is the number of clock cycles per Gate
// The count is for only one half of a full Gate Spacing.
// Because of this, it has already been made a multiple of 2 clock cycles.
// It has also already been made a multiple of 8 clock cycles because we are also dividing the clock by 4.
// Subtract 4 from the count because the PLD uses 1 divided clock cycle to reload the counters, once for each GLEN.
// Shift left to 9th bit location to put into the correct place in the registers.
// By shifting left only 7 bits we are dividing the count by 4 because the clock has been divided by 4.
m_iGateLengthCount = ((iGateSpacingInClockCycles/2) - 4) << 7;
// Store value for future reference
m_iCountsPerGatePulse = m_iGateLengthCount >> 9;
}
//*** Set Status Register 0 with timing values
// First clear all bits except for the software reset (SW_RESET)
SetValue_StatusRegister0(STAT0_SW_RESET);
// Set bit 2 - TMODE to 0 because ????
UnSetBit_StatusRegister0(STAT0_TMODE);
// Set bit 3 - DELAY_SIGN to 0 to delay the trigger pulse by the count in Timer2 in Chip 1 CNT02 - DELAY
UnSetBit_StatusRegister0(STAT0_DELAY_SIGN);
// Set bit 4 - EVEN_TRIG to 1 to output all even triggers
SetBit_StatusRegister0(STAT0_EVEN_TRIG);
// Set bit 5 - ODD_TRG to 1 to output all odd triggers
SetBit_StatusRegister0(STAT0_ODD_TRIG);
// Set bit 6 - EVEN_TP to 0 because we are not using the Test Pulse
UnSetBit_StatusRegister0(STAT0_EVEN_TP);
// Set bit 7 - ODD_TP to 0 to because we are not using the Test Pulse
UnSetBit_StatusRegister0(STAT0_ODD_TP);
// Set bits 9,10,11,12,13 (GLEN0-4) to the length of one Sample pulse in clock cycles.
SetBit_StatusRegister0(m_iGateLengthCount);
// Set bit 14 - GATE0MODE to 0 to because ????
UnSetBit_StatusRegister0(STAT0_GATE0MODE);
// Set bit 15 - SAMPLE_CTRL to 0 to ????
UnSetBit_StatusRegister0(STAT0_SAMPLE_CTRL);
//*** Set Status Register 1 with timing values
// First clear all entries
SetValue_StatusRegister1(0x0000);
// Set bit 0 - PLL_CLOCK to 0 because we are not using Phase Lock Loop
UnSetBit_StatusRegister1(STAT1_PLL_CLOCK);
// Set bit 1 - PLL_LE to 0 because we are not using Phase Lock Loop
UnSetBit_StatusRegister1(STAT1_PLL_LE);
// Set bit 2 - PLL_DATA to 0 because we are not using Phase Lock Loop
UnSetBit_StatusRegister1(STAT1_PLL_DATA);
// Set bit 3 - WATCHDOG to 0 because we are not using the watchdog timer
UnSetBit_StatusRegister1(STAT1_WATCHDOG);
// Set bit 4 - PCI_INT to 0 because ?
UnSetBit_StatusRegister1(STAT1_PCI_INT);
// Set bit 5 - EXTTRIGEN to 0 because we are not putting an input trigger signal to BTRGIN(U4 pin 22)
UnSetBit_StatusRegister1(STAT1_EXTTRIGEN);
// Set bit 6 - FIRST_TRIG - READ ONLY
// Set bit 7 - PHASELOCK - READ ONLY
// Set bits 8,9,10,11 - Spare0-3 - WRITE ONLY
// Set counter to divide input ADC sample clock by 4 for pulsewidth count
// This sets the decimation rate
SetBit_StatusRegister1(m_iSpare);
/* TEMPORARY ************************
// This allows the Sync pulse to come in through the BTrigIn connector,
// which is the top SMA connector on the front of the board. This
// is being done to get around a hardware issue in the PDL that has to
// do with lining the Sync Pulse up on the correct phase of A0,A1 & A2,
// which are divided clocks internal to the PDL.
SetBit_StatusRegister1(STAT1_EXTTRIGEN);
SetBit_StatusRegister0(STAT0_TMODE);
// Set PRT1 & PRT2 to 1 count.
// The SetTimerRegister function subtracts 1 off of the total count to reload
SetTimerRegister(Counter_0,HStrobe,2,pTimer0);
SetTimerRegister(Counter_1,HStrobe,2,pTimer0);
// Reduce the delay count by 2 because the Sync signal has to run through
// two extra counters called PRT1 & PRT2. .
m_iCountsPerDelay = m_iCountsPerDelay - 2;
// Reduce the delay count by 1 to account for the delay through the External trigger logic
m_iCountsPerDelay = m_iCountsPerDelay - 1;
// Reset TimerChip0 - Counter2 with Delay to Gates
SetTimerRegister(Counter_2,HStrobe,m_iCountsPerDelay,pTimer0);
// END TEMPORARY ************************/
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::SetTimerRegister(int iCounter,int iTimerMode,int iCount,unsigned int *pTimerRegister)
//
// DESCRIPTION: Sets the Timer chips. First it writes the control word. Next it writes
// the upper 16 bits of the count. Then it writes the lower 16 bits of the count. The Timers
// are clocked at 1/4th of the radar frequncy clock. This divide by 4 happens in the PALs.
//
// INPUT PARAMETER(s):
// int iCounter - Determines which of the three timers on one chip is being set
// int iTimerMode - Determines the timer mode
// int iCount - The number of counts that the timer will count in (clock cycles/4).
// unsigned int *pTimerRegister
//
// Write Counter Control Word
// bit 0 always = 0 = 16 bit binary counter
// bit 1,2&3 = (iTimerMode * 2) = (iTimerMode = 5) = Hardware Triggered Strobe
// bit 4&5 = 0x30 = read/write ls bytes first then ms byte
// bit 6&7 = (iCounter * 0x40) = selects counter.
//
// Mode: 5 = HStrobe
// Hardware Triggered Strobe (Retriggerable)
// OUT will initially be high. Counting is triggered by a rising edge of GATE.
// When the initial count has expired, OUT will go low for one CLK pulse and
// then go high again.
// After wirthing the Control Word and initial count, the counter will not be
// loaded until the CLK pulse after a trigger. This CLK pulse does not decrement
// the count, so for an initial count of N, OUT doe not strobe low until N+1 CLK
// pulses after a trigger.
// A trigger rusults in the Coounter being loaded with the initial count on the
// next CLK pulse. The counting sequence is retirggerable. OUT will not strobe
// low for N+1 CLK pulses after any trigger. GATE has no effect on OUT.
// If a new count is written during counting, the current counting sequence will
// not be affected. If a trigger occurs after the new count is written but before
// the current count expires, the Counter will be loaded with the new count on the
// next CLK pulse and counting will continue from there.
//
// OUTPUT PARAMETER(s): None
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::SetTimerRegister(int iCounter,int iTimerMode,int iCount,unsigned int *pTimerRegister)
{
// Subtract one count because the Timer uses one count to load and start the counter
iCount = iCount-1;
volatile short* pTimerOffset;
Sleep(1);
// Write Counter Control Word
// bit 0 always = 0 = 16 bit binary counter
// bit 1,2&3 = (iTimerMode * 2) = (iTimerMode = 5) = Hardware Triggered Strobe
// bit 4&5 = 0x30 = read/write ls bytes first then ms byte
// bit 6&7 = (iCounter * 0x40) = selects counter.
pTimerOffset =((volatile short *)pTimerRegister + 0x3);
*pTimerOffset = ((iCounter * 0x40) + 0x30 + (iTimerMode * 2));
Sleep(1);
// Write Counter Least Significant Byte
pTimerOffset =(((volatile short *)pTimerRegister + iCounter));
*pTimerOffset = iCount;
Sleep(1);
// Write Counter Most Significant Byte
pTimerOffset =((volatile short *)pTimerRegister + iCounter);
*pTimerOffset = (iCount >> 8);
}
/////////////////////////////////////////////////////////////////////////////////////////
// METHOD NAME: CONTROL::ReturnTimerValues(unsigned int* piCountsPerDelay, unsigned int* piCountsForAllGates,
// unsigned int* piCountsPerGatePulse,unsigned short* piSpare)
//
// DESCRIPTION: Returns the values last used to set up the timers for diagnostics
//
// INPUT PARAMETER(s): None
//
// OUTPUT PARAMETER(s):
// unsigned int* piCountsPerDelay - Time in clock cycles from start of Sync to start of first sampling gate
// unsigned int* piCountsForAllGates - Time in clock cycles for all sampling gates to happen
// unsigned int* piCountsPerGatePulse - Time in clock cycles from the start of one sampling gate to the start of the next
// unsigned short* piSpare - Value in the upper 16 bits of Status Register 1 that sets the decimation rate
//
// RETURN: none
//
// WRITTEN BY: Coy Chanders 02-01-02
//
// LAST MODIFIED BY:
//
/////////////////////////////////////////////////////////////////////////////////////////
void CONTROL::ReturnTimerValues(unsigned int* piCountsPerDelay, unsigned int* piCountsForAllGates,
unsigned int* piCountsPerGatePulse,unsigned short* piStatus0, unsigned short* piStatus1)
{
*piCountsPerDelay = m_iCountsPerDelay;
*piCountsForAllGates = m_iCountsForAllGates;
*piCountsPerGatePulse = m_iCountsPerGatePulse;
*piStatus0 = *pStatus0;
*piStatus1 = *pStatus1;
}
|
#include "Bool2.h"
Bool2::Bool2()
{
}
Bool2::Bool2(const bool _x, const bool _y) : x(_x), y(_y)
{
}
|
#include "Score.h"
#include <QFont>
Score::Score(QGraphicsItem *parent)
: QGraphicsTextItem (parent) , playerScore{0}
{
setPlainText(QString::number(playerScore));
setDefaultTextColor(Qt::red);
setFont(QFont("times",20));
//create score player
scorePlayer = new QMediaPlayer();
scorePlayer->setMedia(QUrl("qrc:/music/sun.mp3"));
}
void Score::addToScore(int s)
{
playerScore +=s;
setPlainText(QString::number(playerScore));
}
Score::~Score()
{
delete scorePlayer;
}
int Score::getScore()
{
return playerScore;
}
void Score::setScore(int score)
{
playerScore=score;
setPlainText(QString::number(playerScore));
setDefaultTextColor(Qt::red);
setFont(QFont("times",20));
}
|
#pragma once
#include "floor.h"
#include "roomCT.h"
#include "floorCT.h"
#include "player.h"
#include "playerCT.h"
class Game {
friend int main();
friend class Player;
private:
std::unordered_map<int, Floor> floors;
int floorHighestId{ 0 };
int currentFloor;
int currentRoom;
Player player;
PlayerCT playerCT;
FloorCT floorCT;
RoomCT roomCT;
public:
Game();
int createFloor(); // return the floorid
void setStartingRoom();
void initiatePlayer();
void startGame();
void changeFloor();
void onTick();
void onWait();
};
|
#include<bits//stdc++.h>
using namespace std;
int arr[100010],len = 0;
void find_min_max(int &mini,int &maxi)
{
for(int i = 0 ; i < len ; i++)
{
if(arr[i]<mini)
mini = arr[i];
if(arr[i]>maxi)
maxi = arr[i];
}
}
void devide_and_conquer_min_max(int i, int n, int &mini, int &maxi)
{
if(n-i <= 1)
{
mini = min(arr[i],arr[n]);
maxi = max(arr[i],arr[n]);
return;
}
else
{
int min1,max1;
devide_and_conquer_min_max(i,floor(((i + n)/2)),min1,max1);
int min2,max2;
devide_and_conquer_min_max(floor(((i + n)/2)),n,min2,max2);
mini = min(min1,min2);
maxi = max(max1,max2);
}
}
void readFile(string fname)
{
int x,i=0;
ifstream inFile;
inFile.open(fname);
if (!inFile)
{
cout << "Cannot open file.\n";
exit(1);
}
while (inFile >> x)
{
arr[i++] = x;
}inFile.close();
len = i;
}
int main()
{
int a,b;
string s = "";
cout<<"Enter file name : ";
cin>>s;
while(s != "exit")
{
readFile(s);
a = INT_MAX;
b = INT_MIN;
find_min_max(a,b);
cout<<"Minimum and Maximum of "<<s<<" are : ";
cout<<a<<"\t"<<b<<endl;
devide_and_conquer_min_max(0,len-1,a,b);
cout<<"Minimum and Maximum by divide and conquer of "<<s<<" are : ";
cout<<a<<"\t"<<b<<endl;
cout<<"\n\nEnter file name : ";
cin>>s;
}
return 0;
}
|
#include "wizThumbIndexCache.h"
#include <QDebug>
#include "wizDatabaseManager.h"
#define WIZNOTE_THUMB_CACHE_MAX 1000
#define WIZNOTE_THUMB_CACHE_RESET 300
CWizThumbIndexCache::CWizThumbIndexCache(CWizExplorerApp& app)
: m_dbMgr(app.databaseManager())
{
qRegisterMetaType<WIZABSTRACT>("WIZABSTRACT");
connect(&m_dbMgr, SIGNAL(documentAbstractModified(const WIZDOCUMENTDATA&)),
SLOT(on_abstract_modified(const WIZDOCUMENTDATA&)));
}
bool CWizThumbIndexCache::isFull()
{
return m_data.size() > WIZNOTE_THUMB_CACHE_MAX;
}
void CWizThumbIndexCache::get(const QString& strKbGUID,
const QString& strDocumentGUID,
bool bReload)
{
// discard invalid request
if (!m_dbMgr.isOpened(strKbGUID)) {
qDebug() << "[Thumb Cache Pool]discard request, invalid kb guid: " << strKbGUID;
return;
}
// search deque first
CWizAbstractArray::iterator it;
for (it = m_data.begin(); it != m_data.end(); it++) {
const WIZABSTRACT& abs = *it;
if (abs.strKbGUID == strKbGUID && abs.guid == strDocumentGUID) {
if (bReload) {
m_data.erase(it);
break;
} else {
Q_EMIT loaded(abs);
}
return;
}
}
WIZABSTRACT abs;
CWizDatabase& db = m_dbMgr.db(strKbGUID);
// update if not exist
if (!db.PadAbstractFromGUID(strDocumentGUID, abs)) {
if (!db.UpdateDocumentAbstract(strDocumentGUID)) {
return;
}
}
// load again
if (!db.PadAbstractFromGUID(strDocumentGUID, abs)) {
qDebug() << "[Thumb Cache Pool]failed to load thumb cache, guid: "
<< strDocumentGUID;
return;
}
abs.strKbGUID = strKbGUID;
if (abs.text.isEmpty()) {
abs.text = " ";
}
abs.text.replace('\n', ' ');
abs.text.replace("\r", "");
if (!isFull()) {
m_data.push_back(abs);
} else {
m_data.erase(m_data.begin(), m_data.begin() + WIZNOTE_THUMB_CACHE_RESET);
}
Q_EMIT loaded(abs);
}
void CWizThumbIndexCache::load(const QString& strKbGUID,
const QString& strDocumentGUID)
{
if (!QMetaObject::invokeMethod(this, "get",
Q_ARG(QString, strKbGUID),
Q_ARG(QString, strDocumentGUID),
Q_ARG(bool, false))) {
TOLOG("Invoke load of thumb cache failed");
}
}
void CWizThumbIndexCache::on_abstract_modified(const WIZDOCUMENTDATA& doc)
{
if (!QMetaObject::invokeMethod(this, "get",
Q_ARG(QString, doc.strKbGUID),
Q_ARG(QString, doc.strGUID),
Q_ARG(bool, true))) {
TOLOG("Invoke load of thumb cache failed");
}
}
|
#include <iostream>
using namespace std;
int main(){
int N;
cin >> N;
if (N%2 != 0) {
cout << "Weird" << endl;
} else if ( N%2 == 0) {
if ((N>=2) && (N<=6)) {
cout << "Not Weird" << endl;
} else if ((N>=6) && (N<=20)) {
cout << "Weird" << endl;
} else if (N>20) {
cout << "Not Weird" << endl;
}
}
return 0;
}
|
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <sched.h>
#include <numaif.h>
#define NUM_FUNCS 100000
typedef int (*Fptr) (int, int);
extern void libInit(Fptr*, int);
int driverMain(char* memAddress, int memSize)
{
Fptr funcArr[NUM_FUNCS] = {0};
// initializing function pointers.
libInit(funcArr, NUM_FUNCS);
// calling random functions from the library 1000 times
for (int i = 0; i < 1000000; i++)
{
int funcIdx = rand() % NUM_FUNCS;
Fptr f = funcArr[funcIdx];
assert(f != 0);
int arg1 = rand() % 110;
int arg2 = rand() % 55;
int rVal = (*f)(arg1, arg2);
//for (int j = 0; j < 100; j++)
//*(((memAddress) + ((j * 1009) % memSize)) += rVal;
}
return 0;
}
|
#ifndef UTILS
#define UTILS
#include <bits/stdc++.h>
using namespace std;
double getSol(double a, double b, double c, double &t1, double &t2)
{
double d2 = b*b-4*a*c;
if(d2 < 0) return -1;
double d = sqrt(d2);
t1 = (-b-d)/(2*a);
t2 = (-b+d)/(2*a);
if(t1 > 0) return t1;
if(t2 > 0) return t2;
return -1;
}
#endif
|
// ---------- SYSTEM INCLUDE --------------------------------------------------------------------- //
// ---------- EXTERNAL MODULE INCLUDE ------------------------------------------------------------ //
// N/A
// ---------- PROGRAMMING DEFINITION INCLUDE ----------------------------------------------------- //
// N/A
// ---------- EXTERN OBJECT ---------------------------------------------------------------------- //
// N/A
// ---------- PUBLIC INTERFACE METHOD ------------------------------------------------------------ //
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
//#include "utility/twi.h"
//#include "AD7124.h"
#ifdef __cplusplus
}
#endif
#include <Wire.h>
#include <Spi.h>
#include "AD7124_regs.h"
#include "ADEXTENDER.h"
// ---------- PUBLIC METHOD (FUNCTION PROTOTYPE) ------------------------------------------------- //
// N/A
// ---------- PUBLIC DATA ----------------------------------------------------------------------- //
// N/A
// ---------- PRIVATE METHOD (FUNCTION PROTOTYPE) ----------------------------------------------- //
// N/A
// ---------- PRIVATE DATA ---------------------------------------------------------------------- //
// N/A
// ---------- PRIVATE PROGRAMMING DEFINE -------------------------------------------------------- //
#define DEBUG_LIB
//#define DEBUG_DAC
//#define SHIELD_PRINT
#ifndef DAC_VREF
#endif
#ifndef ADC_VREF
#endif
#define DAC_FACTOR 100
#define ADC_FACTOR 10000000UL
#define CURRENT_TO_VOLTAGE_FACTOR 250
#define SS_PIN 10
#define AD7124_CRC8_POLYNOMIAL_REPRESENTATION 0x07 /* x8 + x2 + x + 1 */
// ---------- PRIVATE MACRO DEFINITION ---------------------------------------------------------- //
// N/A
// ---------- SOURCE FILE IMPLEMENTATION -------------------------------------------------------- //
//=========== Public Method ======================================================================//
ADEXTENDER::ADEXTENDER() {
// TODO Auto-generated constructor stub
//Init();
}
ADEXTENDER::~ADEXTENDER() {
// TODO Auto-generated destructor stub
Wire.end();
SPI.end();
}
uint8_t ADEXTENDER::Begin(void) {
uint32_t u32Temp;
/*u8ADCAddress = ADS101x_DEFAULT_ADDRESS;*/
u8DACAddress = AD533X_DEFAULT_ADDRESS;
Wire.begin();
SPI.begin();
pinMode(SS_PIN, OUTPUT);
// Default Voltage 5V 1 mV per resolution
u16VrefDAC = 5000;
u16VrefADC = 1250;
// Calculate resolution
u16DACResolution = (uint8_t)(((uint32_t)(u16VrefDAC) * (uint32_t)DAC_FACTOR) / 4096) ;//(0xFFFF - 1));
u16ADCResolution = (uint64_t)(((uint64_t)(u16VrefADC) * ADC_FACTOR) / (0xFFFFFF - 1));
// Setting up AD7124
u16ReadTimeout = 500;
// Reset chip
ADCReset();
delay(100);
// Write ERROR_EN register
aDCWriteRegister(AD7124_Error_En, 0x400046, 3, 1);
// Write ADC_CONTROL register
aDCWriteRegister(AD7124_Error_En, 0x0144, 2, 1);
// Write channel config
ADCConfigChannel(AD_EXTENDER_ADC_CH_1, 0, AD_DISABLE);
ADCConfigChannel(AD_EXTENDER_ADC_CH_2, 0, AD_DISABLE);
ADCConfigChannel(AD_EXTENDER_ADC_CH_3, 0, AD_DISABLE);
ADCConfigChannel(AD_EXTENDER_ADC_CH_4, 0, AD_DISABLE);
// Write channel pre-configuration
ADCSetConfig(0, 0, 0); // Config 0 Vref = 1.25V PGA 1 Range 0 - 1.25 V
ADCSetConfig(1, 0, 1); // Config 1 Vref = 1.25V PGA 2 Range 0 - 625 mV
ADCSetConfig(2, 0, 2); // Config 2 Vref = 1.25V PGA 4 Range 0 - 312.5 mV
ADCSetConfig(3, 0, 3); // Config 3 Vref = 1.25V PGA 8 Range 0 - 156.25 mV
ADCSetConfig(4, 0, 4); // Config 4 Vref = 1.25V PGA 16 Range 0 - 78.125 mV
ADCSetConfig(5, 0, 5); // Config 5 Vref = 1.25V PGA 32 Range 0 - 39.0625 mV
ADCSetConfig(6, 0, 6); // Config 6 Vref = 1.25V PGA 64 Range 0 - 19.53125 mV
ADCSetConfig(7, 0, 7); // Config 7 Vref = 1.25V PGA 128 Range 0 - 9.765625 mV
#ifdef SHIELD_PRINT
Serial.print("\nSetting up Shield");
Serial.print("\nADCResolution = ");
Serial.print(u16ADCResolution, DEC);
Serial.print("\tDACResolution = ");
Serial.print(u16DACResolution, DEC);
aDCReadRegisterWithPrintOut(AD7124_Status, 1, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_ADC_Control, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Data, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_IOCon1, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_IOCon2_, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_ID, 1, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Error, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Error_En, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Mclk_Count, 1, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Channel_0, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Channel_1, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Channel_2, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Channel_3, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Channel_4, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Config_0, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Config_1, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Config_2, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Config_3, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Config_4, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Config_5, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Config_6, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Config_7, 2, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Filter_0, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Filter_1, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Filter_2, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Filter_3, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Filter_4, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Filter_5, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Filter_6, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Filter_7, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Offset_0, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Offset_1, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Offset_2, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Offset_3, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Offset_4, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Offset_5, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Offset_6, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Offset_7, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Gain_0, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Gain_1, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Gain_2, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Gain_3, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Gain_4, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Gain_5, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Gain_6, 3, &u32Temp);
aDCReadRegisterWithPrintOut(AD7124_Gain_7, 3, &u32Temp);
#endif
return 0;
}
uint8_t ADEXTENDER::ADCSetZero(uint16_t u16Value) {
u16ADCZero = u16Value;
return 0;
}
uint8_t ADEXTENDER::ADCSetSpan(uint16_t u16Value) {
u16ADCSpan = u16Value;
return 0;
}
uint8_t ADEXTENDER::DACSetZero(uint16_t u16Value) {
u16DACZero = u16Value;
return 0;
}
uint8_t ADEXTENDER::DACSetSpan(uint16_t u16Value) {
u16DACSpan = u16Value;
return 0;
}
uint8_t ADEXTENDER::DACUpdateVaule(
AD533X_OUT_SEL eOutSelect,
AD533X_POWER_DOWN_MODE ePowerMode,
uint8_t bCLR,
uint8_t bLDAC,
uint16_t u16Value) {
uint8_t u8Status;
uint8_t u8Reg;
uint16_t u16WriteValue;
// Insert Pointer byte
u8Reg = eOutSelect;
// Insert Value
u16WriteValue = (uint16_t)(ePowerMode << 14)
| (uint16_t)(bCLR << 13)
| (uint16_t)(bLDAC << 12)
| u16Value;
// Write value to device
u8Status = deviceWrite(u8DACAddress, u8Reg, u16WriteValue);
return u8Status;
}
uint8_t ADEXTENDER::DACUpdateVaule(
AD533X_OUT_SEL eOutSelect,
uint16_t u16Value) {
return DACUpdateVaule(
eOutSelect,
AD533X_POWER_DOWN_NORMAL,
1,
0,
u16Value);
}
uint8_t ADEXTENDER::DACSetOutByVoltage(E_ADEXTENDER_OUT_CHANNEL eCh,
E_ADEXTENDER_MODE eMode, uint16_t u16Volage) {
uint16_t u16DACValue;
u16DACValue = ((uint32_t)u16Volage * (uint32_t)DAC_FACTOR) / u16DACResolution;
if (eMode == AD_EXTENDER_MODE_0_10_V) {
u16DACValue = u16DACValue / 2;
}
if (u16DACValue >= 4095) {
u16DACValue = 4095;
}
#ifdef DEBUG_LIB && DEBUG_DAC
Serial.print("\nWrite Value to DAC : ");
Serial.print(u16DACValue, DEC);
#endif
return DACUpdateVaule(
(AD533X_OUT_SEL)eCh,
AD533X_POWER_DOWN_NORMAL,
1,
0,
u16DACValue);
}
uint8_t ADEXTENDER::DACSetOutByCurrent(E_ADEXTENDER_OUT_CHANNEL eCh,
E_ADEXTENDER_MODE eMode, uint16_t u16Current) {
uint16_t u16DACValue;
uint16_t u16mAConvert;
if (u16Current > 20) {
return 255;
}
u16mAConvert = u16Current * CURRENT_TO_VOLTAGE_FACTOR;
return DACSetOutByVoltage(eCh, AD_EXTENDER_MODE_0_5_V, u16mAConvert);
}
uint8_t ADEXTENDER::ADCReset(void) {
digitalWrite(SS_PIN, LOW);
for(int i = 0; i < 8; i++) {
SPI.transfer(0xFF);
}
digitalWrite(SS_PIN, HIGH);
}
uint8_t ADEXTENDER::ADCReadStatus(void) {
uint32_t u32ReadValue;
#ifndef DEBUG_LIB
aDCReadRegister(AD7124_Status, 1, &u32ReadValue);
#else
aDCReadRegisterWithPrintOut(AD7124_Status, 1, &u32ReadValue);
#endif
return (uint8_t)u32ReadValue;
}
uint8_t ADEXTENDER::ADCRead(E_ADEXTENDER_ADC_CH eChannel, E_ADEXTENDER_MODE eMode , uint32_t pOut[], uint32_t pu32Step[]) {
uint8_t u8Ready;
uint8_t u8Temp[4];
uint32_t timeout;
uint16_t u16Resulotion;
uint64_t u64CalValue;
uint8_t u8ConfigSel;
uint16_t u16TimeOutStep;
u16TimeOutStep = u16ReadTimeout / 10;
// Select pre-setting and resolution
switch (eMode) {
case AD_EXTENDER_MODE_0_5_V:
u8ConfigSel = 1;
u16Resulotion = u16ADCResolution / 2;
break;
case AD_EXTENDERMODE_0_20_mA:
u8ConfigSel = 1;
u16Resulotion = u16ADCResolution / 2;
break;
case AD_EXTENDER_MODE_4_20_mA:
u8ConfigSel = 1;
u16Resulotion = u16ADCResolution / 2;
break;
case AD_EXTENDER_MODE_0_10_V:
u8ConfigSel = 0;
u16Resulotion = u16ADCResolution;
break;
case AD_EXTENDER_MODE_TC:
u8ConfigSel = 5;
u16Resulotion = u16ADCResolution / 32;
break;
}
ADCConfigChannel(eChannel, u8ConfigSel, AD_DISABLE);
aDCStartConversion(eChannel);
pOut[0] = 0xFFFFFFFF;
timeout = 10;
u8Ready = ADCReadStatus();
u8Ready = (u8Ready & AD7124_STATUS_REG_RDY) >> 7;
while(u8Ready && --timeout) {
u8Ready = ADCReadStatus();
u8Ready = (u8Ready & AD7124_STATUS_REG_RDY) >> 7;
delay(u16TimeOutStep);
}
if (timeout == 0) {
return 255;
}
// Read conversion value
aDCGetConversionValue(pu32Step);
// Calculate to voltage/current Domain
u64CalValue = (uint64_t)((uint64_t)(pu32Step[0]) * (uint64_t)(u16Resulotion) / (ADC_FACTOR / 100));
pOut[0] = (uint32_t)u64CalValue * 845;
return 0;
}
uint8_t ADEXTENDER::ADCReadWithPrintOut(E_ADEXTENDER_ADC_CH eChannel, uint32_t pOut[]) {
uint8_t u8Ready;
uint8_t u8Temp[4];
uint32_t timeout;
uint32_t u32ReadValue;
uint16_t u16TimeOutStep;
u16TimeOutStep = u16ReadTimeout / 10;
#ifdef SHIELD_PRINT
Serial.print("\nStart convertion on ch : ");
Serial.print(eChannel, HEX);
#endif
aDCStartConversion(eChannel);
pOut[0] = 0xFFFFFFFF;
timeout = 100;
u8Ready = ADCReadStatus();
u8Ready = (u8Ready & AD7124_STATUS_REG_RDY) >> 7;
#ifdef SHIELD_PRINT
Serial.print("\nRead Status : ");
Serial.print(u8Ready, HEX);
#endif
while(u8Ready && --timeout) {
u8Ready = ADCReadStatus();
u8Ready = (u8Ready & AD7124_STATUS_REG_RDY) >> 7;
#ifdef SHIELD_PRINT
Serial.print("\nRead Status : ");
Serial.print(u8Ready, HEX);
#endif
delay(u16TimeOutStep);
}
if (timeout == 0) {
aDCReadRegisterWithPrintOut(AD7124_Data, 3, pOut);
return 255;
}
aDCReadRegisterWithPrintOut(AD7124_Data, 3, pOut);
return 0;
}
uint8_t ADEXTENDER::ADCConfigControl(uint16_t u16Value) {
uint8_t u8Temp[2];
uint8_t u8Status;
uint16_t u16Temp;
#ifndef DEBUG_LIB
u8Status = aDCWriteRegister(AD7124_ADC_Control, (uint32_t)u16Value, 2, 1);
#else
u8Status = aDCWriteRegisterWithPrintOut(AD7124_ADC_Control, (uint32_t)u16Value, 2, 1);
#endif
return u8Status;
}
uint8_t ADEXTENDER::ADCSetChannelControl(E_ADEXTENDER_ADC_CH eCh, E_ADEXTENDER_STA eSta) {
uint16_t u16CurrentActiveConfigValue;
AD7124_CHANNEL_REGISTER *psChannelConfig;
u16CurrentActiveConfigValue = ADCGetConfigChannel(eCh);
psChannelConfig = (AD7124_CHANNEL_REGISTER*) &u16CurrentActiveConfigValue;
ADCConfigChannel(
eCh,
(uint8_t)psChannelConfig->SETUP,
eSta);
return 0;
}
uint8_t ADEXTENDER::ADCConfigChannel(E_ADEXTENDER_ADC_CH eCh, uint8_t u8config, E_ADEXTENDER_STA en) {
uint8_t u8TempBuffer[8];
uint16_t u16Temp;
uint8_t u8WriteChannel;
uint8_t u8Status;
// Write Channel configuration
u16Temp = en << 15 |
AD7124_CH_MAP_REG_SETUP(u8config) |
AD7124_CH_MAP_REG_AINP(eCh) |
AD7124_CH_MAP_REG_AINM(17);
u8WriteChannel = (uint8_t)(AD7124_Channel_0 + eCh);
#ifndef DEBUG_LIB
u8Status = aDCWriteRegister((ad7124_reg_access)u8WriteChannel, (uint32_t)u16Temp, 2, 1);
#else
u8Status = aDCWriteRegisterWithPrintOut((ad7124_reg_access)u8WriteChannel, (uint32_t)u16Temp, 2, 1);
#endif
return u8Status;
}
uint16_t ADEXTENDER::ADCGetConfigChannel(E_ADEXTENDER_ADC_CH eCh) {
uint32_t u32ReadValue;
uint8_t u8ReadEnrty;
u8ReadEnrty = AD7124_Channel_0 + eCh;
// Read Channel configuration
#ifndef DEBUG_LIB
aDCReadRegister((ad7124_reg_access)u8ReadEnrty, 2, &u32ReadValue);
#else
aDCReadRegisterWithPrintOut((ad7124_reg_access)u8ReadEnrty, 2, &u32ReadValue);
#endif
return (uint16_t)u32ReadValue;
}
uint8_t ADEXTENDER::ADCSetConfig(uint8_t u8Entry, uint8_t vrefSel, uint8_t pga) {
uint8_t u8TempBuffer[8];
uint16_t u16Temp;
uint8_t u8Status;
uint8_t u8WriteConfigEntry;
// Write Channel configuration
u16Temp = AD7124_CFG_REG_REF_SEL(vrefSel) |
AD7124_CFG_REG_REF_BUFP |
AD7124_CFG_REG_REF_BUFM |
AD7124_CFG_REG_AIN_BUFP |
AD7124_CFG_REG_AINN_BUFM |
AD7124_CFG_REG_PGA(pga);
u8WriteConfigEntry = (uint8_t)(AD7124_Config_0 + u8Entry);
#ifndef DEBUG_LIB
u8Status = aDCWriteRegister((ad7124_reg_access)u8WriteConfigEntry, (uint32_t)u16Temp, 2, 1);
#else
u8Status = aDCWriteRegisterWithPrintOut((ad7124_reg_access)u8WriteConfigEntry, (uint32_t)u16Temp, 2, 1);
#endif
return u8Status;
}
uint16_t ADEXTENDER::ADCGetConfig(uint8_t u8Entry) {
uint32_t u32ReadValue;
uint8_t u8ReadEnrty;
if (u8Entry > 7) {
return 255;
}
u8ReadEnrty = AD7124_Config_0 + u8Entry;
#ifndef DEBUG_LIB
aDCReadRegisterWithPrintOut((ad7124_reg_access)u8ReadEnrty, 2, &u32ReadValue);
#else
aDCReadRegisterWithPrintOut((ad7124_reg_access)u8ReadEnrty, 2, &u32ReadValue);
#endif
return (uint16_t)u32ReadValue;
}
uint8_t ADEXTENDER::ADCSetReadTimeOut(uint16_t u16Interval) {
u16ReadTimeout = u16Interval;
}
//=========== Private Method ======================================================================//
uint8_t ADEXTENDER::aDCWriteErrorEn(uint32_t u32Value) {
uint8_t u8TempBuffer[8];
u8TempBuffer[0] = (uint8_t)((u32Value >> 16) & 0xFF);
u8TempBuffer[1] = (uint8_t)((u32Value >> 8) & 0xFF);
u8TempBuffer[2] = (uint8_t)(u32Value & 0xFF);
deviceSPIWrite(AD7124_ERREN_REG, u8TempBuffer, 3);
}
uint8_t ADEXTENDER::aDCStartConversion(E_ADEXTENDER_ADC_CH eChannel) {
uint32_t u32Status;
uint16_t u16ConfigValue;
uint16_t u16CurrentActiveConfigValue;
uint8_t u8TempBuffer[2];
AD7124_STATUS_REGISTER *psStatus;
// Setting configuration
u16ConfigValue = (uint16_t)(AD7124_ADC_CTRL_REG_DOUT_RDY_DEL) |
(uint16_t)(AD7124_ADC_CTRL_REG_REF_EN) |
//(uint16_t)(AD7124_ADC_CTRL_REG_CONT_READ) |
(uint16_t)(AD7124_ADC_CTRL_REG_POWER_MODE(3)) |
(uint16_t)(AD7124_ADC_CTRL_REG_MODE(1)) |
(uint16_t)(AD7124_ADC_CTRL_REG_CLK_SEL(1));
// Read Current active channel
u32Status = (uint32_t)ADCReadStatus();
//aDCReadRegisterWithPrintOut(AD7124_Status, 1, &u32Status);
psStatus = (AD7124_STATUS_REGISTER*) &u32Status;
if (eChannel != psStatus->CH_ACTIVE) {
// Disable current status
ADCSetChannelControl((E_ADEXTENDER_ADC_CH)psStatus->CH_ACTIVE, AD_DISABLE);
}
// Enable channel
ADCSetChannelControl(eChannel, AD_ENABLE);
// Write value to ADC Control
ADCConfigControl(u16ConfigValue);
return 0;
}
uint8_t ADEXTENDER::aDCGetConversionValue(uint32_t data[]) {
return aDCReadRegister(AD7124_Data, 3, data);;
}
uint8_t ADEXTENDER::deviceWrite(uint8_t u8DevAddr,uint8_t u8Reg, uint16_t u16Value) {
Wire.beginTransmission(u8DevAddr);
Wire.write(u8Reg);
Wire.write((uint8_t)(u16Value >> 8));
Wire.write((uint8_t)u16Value);
return Wire.endTransmission();
}
uint8_t ADEXTENDER::deviceRead(uint8_t u8DevAddr, uint8_t u8Reg, uint16_t pu16Value[]) {
uint8_t u8ReadLength;
uint16_t u16ReadValue;
Wire.beginTransmission(u8DevAddr);
Wire.write(u8Reg);
Wire.endTransmission();
u8ReadLength = Wire.requestFrom(u8DevAddr, (uint8_t)2);
if (u8ReadLength > 0) {
u16ReadValue = (uint16_t)(Wire.read()) << 8;
u16ReadValue |= (uint16_t)(Wire.read());
}
pu16Value[0] = u16ReadValue;
return u8ReadLength;
}
uint8_t ADEXTENDER::deviceSPIWrite(uint8_t u8Reg, uint8_t pu8Data[], uint8_t u8Length) {
uint8_t i;
uint8_t u8ComReg;
u8ComReg = AD7124_COMM_REG_WEN | AD7124_COMM_REG_WR | AD7124_COMM_REG_RA(u8Reg);
//SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
digitalWrite(SS_PIN, LOW);
SPI.transfer(u8ComReg);
for(i = 0; i < u8Length; i++) {
SPI.transfer(pu8Data[i]);
}
digitalWrite(SS_PIN, HIGH);
//SPI.endTransaction();
return 0;
}
uint8_t ADEXTENDER::deviceSPIRead(uint8_t u8Reg, uint8_t u8Length, uint8_t pu8DataOut[]) {
uint8_t i;
uint8_t u8ComReg;
u8ComReg = AD7124_COMM_REG_WEN | AD7124_COMM_REG_RD | AD7124_COMM_REG_RA(u8Reg);
//SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3));
digitalWrite(SS_PIN, LOW);
SPI.transfer(u8ComReg);
for(i = 0; i < u8Length; i++) {
pu8DataOut[i] = SPI.transfer(0x00);
}
digitalWrite(SS_PIN, HIGH);
//SPI.endTransaction();
return 0;
}
uint8_t ADEXTENDER::aDCWriteRegister(ad7124_reg_access eRegister,
uint32_t u32Value, uint8_t u8Size, uint8_t u8Verify) {
uint8_t u8Msg[16];
uint8_t i;
uint32_t u32ReadValue;
uint8_t u8Status;
// Read register
u8Msg[0] = AD7124_COMM_REG_WEN | AD7124_COMM_REG_WR | AD7124_COMM_REG_RA(eRegister);
if (u8Size == 3) {
u8Msg[1] = (u32Value >> 16) & 0xFF;
u8Msg[2] = (u32Value >> 8) & 0xFF;
u8Msg[3] = u32Value & 0xFF;
u8Msg[4] = computeCRC8(u8Msg, u8Size + 1);
}
else if (u8Size == 2) {
u8Msg[1] =( u32Value >> 8) & 0xFF;
u8Msg[2] = u32Value & 0xFF;
u8Msg[3] = computeCRC8(u8Msg, u8Size + 1);
}
else {
u8Msg[1] = u32Value;
u8Msg[2] = computeCRC8(u8Msg, u8Size + 1);
}
digitalWrite(SS_PIN, LOW);
for(i = 0; i < u8Size + 2; i++) {
SPI.transfer(u8Msg[i]);
}
digitalWrite(SS_PIN, HIGH);
// Calculate CRC
//Serial.print(computeCRC8(u8Msg, u8Size + 2), HEX);
if (u8Verify == 1) {
u8Status = aDCReadRegister(eRegister, u8Size, &u32ReadValue);
if ((u8Status == 255) || (u32Value != u32ReadValue)) {
// Verify fail
return 255;
}
}
return 0;
}
uint8_t ADEXTENDER::aDCWriteRegisterWithPrintOut(ad7124_reg_access eRegister,
uint32_t u32Value, uint8_t u8Size, uint8_t u8Verify) {
uint8_t u8Msg[16];
uint8_t i;
uint32_t u32ReadValue;
uint8_t u8Status;
// Read register
u8Msg[0] = AD7124_COMM_REG_WEN | AD7124_COMM_REG_WR | AD7124_COMM_REG_RA(eRegister);
if (u8Size == 3) {
u8Msg[1] = (u32Value >> 16) & 0xFF;
u8Msg[2] = (u32Value >> 8) & 0xFF;
u8Msg[3] = u32Value & 0xFF;
u8Msg[4] = computeCRC8(u8Msg, u8Size + 1);
}
else if (u8Size == 2) {
u8Msg[1] =( u32Value >> 8) & 0xFF;
u8Msg[2] = u32Value & 0xFF;
u8Msg[3] = computeCRC8(u8Msg, u8Size + 1);
}
else {
u8Msg[1] = u32Value;
u8Msg[2] = computeCRC8(u8Msg, u8Size + 1);
}
#ifdef SHIELD_PRINT
Serial.print("\nWrite Register ");
Serial.print(eRegister, HEX);
Serial.print("\t\t");
#endif
digitalWrite(SS_PIN, LOW);
for(i = 0; i < u8Size + 2; i++) {
#ifdef SHIELD_PRINT
Serial.print(" 0x");
#endif
SPI.transfer(u8Msg[i]);
#ifdef SHIELD_PRINT
Serial.print(u8Msg[i], HEX);
#endif
}
digitalWrite(SS_PIN, HIGH);
//
#ifdef SHIELD_PRINT
Serial.print("\t CRC = ");
Serial.print(computeCRC8(u8Msg, u8Size + 2), HEX);
#endif
if (u8Verify == 1) {
u8Status = aDCReadRegister(eRegister, u8Size, &u32ReadValue);
if ((u8Status == 255) || (u32Value != u32ReadValue)) {
// Verify fail
#ifdef SHIELD_PRINT
Serial.print("\t Verify fail ");
Serial.print(u32Value ,HEX);
Serial.print(" ");
Serial.print(u32ReadValue, HEX);
#endif
return 255;
}
#ifdef SHIELD_PRINT
Serial.print("\t Verify pass");
#endif
}
return 0;
}
uint8_t ADEXTENDER::aDCReadRegister(ad7124_reg_access eRegister, uint8_t u8Size, uint32_t u32Out[]) {
uint8_t u8Msg[16];
uint8_t i;
uint8_t u8CRC;
// Read register
u8Msg[0] = AD7124_COMM_REG_WEN | AD7124_COMM_REG_RD
| AD7124_COMM_REG_RA(eRegister);
digitalWrite(SS_PIN, LOW);
SPI.transfer(u8Msg[0]);
for (i = 0; i < u8Size + 1; i++) {
u8Msg[1 + i] = SPI.transfer(0xFF);
}
digitalWrite(SS_PIN, HIGH);
// Calculate CRC
u8CRC = computeCRC8(u8Msg, u8Size + 2);
if (u8CRC != 0) {
return 255;
}
if (u8Size == 3) {
u32Out[0] = (uint32_t)(u8Msg[1]) << 16;
u32Out[0] |= (uint32_t)(u8Msg[2]) << 8;
u32Out[0] |= (uint32_t)u8Msg[3];
} else if (u8Size == 2) {
u32Out[0] = (uint32_t)(u8Msg[1]) << 8;
u32Out[0] |= (uint32_t)u8Msg[2];
} else {
u32Out[0] = (uint32_t)u8Msg[1];
}
return 0;
}
uint8_t ADEXTENDER::aDCReadRegisterWithPrintOut(ad7124_reg_access eRegister, uint8_t u8Size, uint32_t u32Out[]) {
uint8_t u8Msg[16];
uint8_t i;
uint8_t u8CRC;
// Read register
u8Msg[0] = AD7124_COMM_REG_WEN | AD7124_COMM_REG_RD
| AD7124_COMM_REG_RA(eRegister);
#ifdef SHIELD_PRINT
Serial.print("\nRead Register ");
Serial.print(eRegister, HEX);
Serial.print("\t\t");
Serial.print("0x");
#endif
digitalWrite(SS_PIN, LOW);
SPI.transfer(u8Msg[0]);
for (i = 0; i < u8Size + 1; i++) {
u8Msg[1 + i] = SPI.transfer(0xFF);
#ifdef SHIELD_PRINT
if (i == u8Size) {
Serial.print("\t");
}
Serial.print(u8Msg[1 + i], HEX);
Serial.print(" ");
#endif
}
digitalWrite(SS_PIN, HIGH);
// Calculate CRC
u8CRC = computeCRC8(u8Msg, u8Size + 2);
#ifdef SHIELD_PRINT
Serial.print("\t CRC = ");
Serial.print(u8CRC, HEX);
#endif
if (u8CRC != 0) {
return 255;
}
if (u8Size == 3) {
u32Out[0] = (uint32_t)(u8Msg[1]) << 16;
u32Out[0] |= (uint32_t)(u8Msg[2]) << 8;
u32Out[0] |= (uint32_t)(u8Msg[3]);
} else if (u8Size == 2) {
u32Out[0] = (uint32_t)(u8Msg[1]) << 8;
u32Out[0] |= (uint32_t)u8Msg[2];
} else {
u32Out[0] = (uint32_t)u8Msg[1];
}
return 0;
}
uint8_t ADEXTENDER::computeCRC8(uint8_t * pBuf, uint8_t bufSize) {
uint8_t i = 0;
uint8_t crc = 0;
while(bufSize)
{
for(i = 0x80; i != 0; i >>= 1)
{
if(((crc & 0x80) != 0) != ((*pBuf & i) != 0)) /* MSB of CRC register XOR input Bit from Data */
{
crc <<= 1;
crc ^= AD7124_CRC8_POLYNOMIAL_REPRESENTATION;
}
else
{
crc <<= 1;
}
}
pBuf++;
bufSize--;
}
return crc;
}
// ---------- END OF SOURCE FILE IMPLEMENTATION ------------------------------------------------- //
|
/*
// Copyright 2007 Alexandros Panagopoulos
//
// This software is distributed under the terms of the GNU Lesser General Public Licence
//
// This file is part of Be3D library.
//
// Be3D is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Be3D is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Be3D. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _COMMON_H24688_INCLUDED_
#define _COMMON_H24688_INCLUDED_
#pragma once
/**
* Common includes, macros, preproc directives and typedefs
* used throughout the program
*
*/
#define _CRT_SECURE_NO_WARNINGS
#undef _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#define SAFE_DELETE(x) { if (x) { delete x; x=0; } }
#define SAFE_DELETE_VEC(x) { if (x) { delete[] x; x=0; } }
#ifndef ASSERT
#define ASSERT(x) { assert(x); }
#endif
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
/**
* OpenGL-relevant includes (opengl, glu32, glaux, glut, glui)
*/
#include <GL/glew.h>
#include <GL/wglew.h>
//#include <gl\gl.h> // opengl
//#include <gl\glu.h> // glu32
//#include "..\gl\glaux.h" // DEPRECATED! REMOVE! (also from project directory) - used in Image.cpp for loading bmps
//#include <gl\glut.h>
//#include <gl\glui.h>
//#include <GL/glext.h>
/**
* Some useful STL types
*/
#include <vector>
#include <list>
#include <string>
/**
* Some basic 3d structs
*/
#include "Vector2.h"
#include "Vector3.h"
#include "Vector4.h"
#include "Color.h"
#include "Matrix4.h"
#include "Matrix3.h"
/**
* A console
*/
#include "Console.h"
/**
* Constants
*/
#define PI 3.14159f
// define integer types with size guarantee
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
// define float types with size guarantee (?)
typedef float float32_t;
typedef double float64_t;
/**
* Some useful enums
*/
enum Axis {
X_AXIS = 0,
Y_AXIS,
Z_AXIS
};
enum TexGenMode {
TG_NORMAL, // object normal
TG_ISNORMAL, // intermediate surface normal
TG_OBJCENTROID, // object centroid
TG_UV, // ready made uv's
TG_SPHERICAL_ENVMAP, // spherical environment map
TG_CUBIC_ENVMAP // cubic environment map
};
enum TexGenPrimitive {
TG_SPHERE,
TG_CYLINDER,
TG_BOX,
TG_PLANE
};
#endif
|
/*
Handle degenerate case of all 0s separately.
Start from top right. Keep doing until we reach last row: go down if current element is 0, go left otherwise.
Column number of final ptr is our answer.
*/
// In a binary matrix (all elements are 0 and 1), every row is sorted in ascending order (0 to the left of 1).
// Find the leftmost column index with a 1 in it.
// ref: Q1004 Max Consecutive Ones III, Sliding Window
int findLeftMostColumnOfOne(vector<vector<int>> & matrix) {
// handle edge cases
if (matrix.empty() || matrix[0].empty()) return -1;
int rows = matrix.size(), cols = matrix[0].size();
int res = -1;
// Search from top right: go down if current element is 0, go left otherwise
// Keep doing until we reach last row
for (int r = 0, c = cols - 1; r < rows && c >= 0; ) {
if (matrix[r][c] == 1) {
res = c;
--c;
}
else {
++r;
}
}
return res;
}
/*
cpp.sh test :
int main()
{
vector<vector<int>> m1 = {{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 1},
{0, 0, 0, 0}};
vector<vector<int>> m2 = {{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}};
vector<vector<int>> m3 = {{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 1}};
cout << "m1: " << findLeftMostColumnOfOne(m1) << endl;
cout << "m2: " << findLeftMostColumnOfOne(m2) << endl;
cout << "m3: " << findLeftMostColumnOfOne(m3) << endl;
return 0;
}
*/
|
#include"Enemy.h"
Enemy::Enemy() :GameObject(244,100,"enemy",1) {
}
Enemy::~Enemy() {
}
void Enemy::init() {
DDS_FILE* dds = readDDS("dds/enemy2.dds");
float x = dds->header.dwWidth*0.5;
float y = dds->header.dwHeight*0.5;
setAnchor(x, y);
setDDS(dds);
fireTime = 0;
fireRate = 1;
speed = 150;
}
void Enemy::update() {
float dist;
float x = getPx(); //에너미의 현재 x-축 좌표를 구한다.
float y = getPy(); //에너미의 현재 y-축 좌표를 구한다.
if (getPx() > 425) {
speed = -speed;
}
else if (getPx() < 45) {
speed = -speed;
}
dist = 0.01*speed;
translate(dist, 0);
///////////레이져 발사 기능///////////////
/*
fireTime = fireTime + getDeltaTime(); //발사 시간을 구하기 위해서 시간을 계속 측정한다.
if (fireTime >= fireRate) {
addGameObj(new ELaser(x, y+ 65));
fireTime = 0;
}
*/
}
|
#pragma once
#include <EventListener.h>
#include <sc2api/sc2_common.h>
#include <set>
#include <glm/vec2.hpp>
class SC2;
class CannonRush : public EventListener
{
public:
~CannonRush();
CannonRush(SC2& api);
void step() override;
void unitCreated(const sc2::Unit* unit) override;
void buildingConstructionComplete(const sc2::Unit* unit) override;
void unitDestroyed(const sc2::Unit*) override;
bool has_forge() const
{
return m_forge_count;
}
const sc2::Unit* get_free_probe() const;
private:
const size_t rushers_count = 2;
class Rusher
{
public:
static const auto vision = 8;
enum class State { Idle, Scouting, Wander, Rushing };
Rusher(const CannonRush* parent, const sc2::Unit* rusher, SC2& sc2);
void step();
const sc2::Unit* unit() const;
private:
void rush();
void scout();
void set_state(State newstate);
const CannonRush* m_parent;
const sc2::Unit* m_unit;
SC2& m_sc2;
State m_state = State::Idle;
sc2::Point3D m_heading;
sc2::Point2D m_target;
std::vector<const sc2::Unit*> m_closest_targets;
};
void assign_rushers();
SC2& m_sc2;
std::vector<std::unique_ptr<Rusher>> m_rushers;
size_t m_forge_count = 0;
};
|
/*
#include <iostream> // подключаем заголовочный файл iostream
int main() // определяем функцию main
{ // начало функции
setlocale(LC_ALL, ""); // функция поддержки кириллических символов
std::cout <<"Привет мир!"; // выводим строку на консоль
std::cout << "Bye World";
return 0; // выходим из функции
} // конец функции
*/
#include <iostream> // подключаем заголовочный файл iostream
#include <stdio.h>
#include <Windows.h> // Изменение цвета отдельных слов
#include <string> // Для хранения строк в C++ применяется тип string.
enum ConsoleColor {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
LightMagenta = 13,
Yellow = 14,
White = 15
};
void hello() // объявление функции
{
std::cout << "hello\n";
}
void exchange(double currate, double sum) // определение программы обменного пункта
{
double result = sum / currate;
std::cout << "Rate: " << currate << "\tSum: " << sum
<< "\tResult: " << result << std::endl;
}
// currate (текущий курс) и sum (сумма, которую надо обменять)
void square(int z) // Функция square принимает число и выводит на консоль его квадрат (при несовпадении типов будет выполнено преобразование в тот тип, который указан в функции)
{
std::cout << "Square of " << z << " is equal to " << z * z << std::endl;
}
void display(std::string name, int age) // функция возвращает строку (имя) и числовой параметр (возраст)
{
std::cout << "Name: " << name << "\tAge: " << age << std::endl;
}
void multiply(int n, int m = 3) // параметр m задан
{
int result = n * m;
std::cout << "n * m = " << result << std::endl;
}
void square_1(int SQ1, int SQ2) // Передача аргументов по значению
{
SQ1 = SQ1 * SQ1;
SQ2 = SQ2 * SQ2;
std::cout << "In square: SQ1 = " << SQ1 << "\tSQ2=" << SQ2 << std::endl;
}
void square_2(int &SQ3, int &SQ4) // Ссылочный параметр связывается непосредственно с объектом, поэтому через ссылку можно менять сам объект.
{
SQ3 = SQ3 * SQ3;
SQ4 = SQ4 * SQ4;
std::cout << "In square: SQ3 = " << SQ3 << "\tSQ4=" << SQ4 << std::endl;
}
int x = 1; // определение переменной ВНЕ функции main (по умолчанию значение такой переменной - 0)
int main() // определяем функцию main. В скобках указывается тип данных (int, float, double и т.д.). Если () или (void) - тип данных не указан
{ // начало функции
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // Получаение дескриптора устройства стандартного вывода
setlocale(LC_ALL, ""); // функция поддержки кириллических символов
// Установка белого фона за отдельным символом. Цвет символа - черный
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 1. Вывод строки на консоль");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
std::cout << "Привет мир!" << "\n"; // выводим строку на консоль
// Целочисленные типы данных
/*
short a = -10;
unsigned short b = 10;
int c = -30;
unsigned int d = 60;
long e = -170;
unsigned long f = 45;
long long g = 89;
*/
// Типы чисел с плавающей точкой иили дробные числа
/*
float h = -10.45;
double i = 0.00105;
long double j = 30.890045;
*/
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 2. Инициализация переменной");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
int age = 27; // инициализация переменной
int year = 1993;
// int age;
// age = 27; // определение переменной ВНУТРИ функции main
std::cout << "Возраст = " << age << " лет" << "\n";
std::cout << "Переменная " << "X = " << x << "\n";
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 3. Определение переменной-символа");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
char A = 'A'; // определение переменной символьного типа
char age_b = 66; // 66 - код символа 'B' в таблице символов ASCII
wchar_t B = 'B';
std::cout << "Возраст A (тип char) " << A << "\n";
std::cout << "Возраст B (тип wchar) " << B << "\n"; // поток std::cout для переменной wchar_t вместо символа будет выводить его числовой код
std::wcout << A << " (char)" << ' ' << B << " (wchar)" << "\n";
std::cout << (char)B << '\n'; // операция приведения к типу char
//std::wcout << "Возрасты A и B (тип char и wchar) " << B << '\n'; // ТЕКСТ ОТОБРАЖАЕТСЯ НЕКОРРЕКТНО
std::cout << "Размер памяти в байтах, которую занимает переменная " << "age = " << sizeof(age) << "\n";
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 4. Преобразования типов");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
int i_1 = 'B'; // символ 'B' будет автоматически преобразовываться в число - код символа в таблице ASCII 66
char word = 66; // код 66 в символьном типе озачает символ 'B'
std::cout << i_1 << " in ASCII is " << word << "\n";
// переменная типа bool получает false, если значение равно 0. Во всех остальных случаях переменная получает true.
bool b_1 = 1; // результат - true
bool b_2 = 3.4; // результат - true
bool b_3 = 'g'; // результат - true
bool b_4 = 0; // результат - false
int i_2 = true; // результат - 1
double d_1 = false; // результат - 0
int i_3 = 3.45; // результат - 3
int i_4 = 7.21; // результат - 7
float a = 35005; // результат - 35005
double b = 3500500000033; // результат - 3.5005e+012
// при присвоении значения -1 переменная типа unsigned char получит 256 - |-1/256| = 255
unsigned char uc_1 = -1; // результат - 255
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 5. Определения константы");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
const int y = 22;
const int x = y;
const float Pi = 3.1415;
std::cout << "Константа Y = " << y << "\n";
std::cout << "Константы X и Y равны 22" << "\n";
std::cout << "Число Пи равно " << Pi << "\n" ;
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 6. Бинарные операции");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// бинарные операции (опреации с двумя операндами)
int i_5 = age + year;
std::cout << i_5 << "\n";
int i_6 = year - age;
std::cout << i_6 << "\n";
int i_7 = age * year;
std::cout << i_7 << "\n";
float f_1 = (float)year / (float)age;
std::cout << "Float " << f_1 << "\n";
double d_2 = (double)year / (double)age;
std::cout << "Double " << d_2 << "\n";
// Операция получения остатка от целочисленного деления:
int i_8 = year % age;
std::cout << "Остаток от целочисленного деления " << i_8 << "\n";
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 7. Унарные арифметические операции");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// унарные арифметические операции, которые производятся над одним числом: ++ (инкремент) и -- (декремент)
int i_9 = ++age; // Префиксный инкремент
std::cout << "Возраст через 1 год = " << i_9 << "\n";
int i_10 = i_9++; // Постфиксный инкремент
std::cout << "Возраст через 2 года (" << i_9 << ") будет больше, чем через 1 год (" << i_10 << ")" << "\n";
std::cout << "age = " << age << "\n";
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 8. Операции отношения");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
bool b_5 = i_9 == age; // false
bool b_6 = i_10 == age; // true
std::cout << b_5 << ' ' << b_6 << "\n";
bool b_7 = i_9 >= i_10; // true
bool b_8 = i_9 != i_10;
std::cout << b_7 << ' ' << b_8 << "\n";
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 9. Логические операции");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// ! (операция отрицания)
bool b_9 = true;
bool b_10 = !b_9;
std::cout << "Отрицание " << b_9 << " есть " << b_10 << "\n";
// && (конъюнкция, логическое умножение)
bool b_11 = true;
bool b_12 = false;
std::cout << (b_11 && b_12) << ' ' << (b_11 && true) << ' ' << (b_12 && false) << "\n"; // 0 1 0
// || (дизъюнкция, логическое сложение)
std::cout << (b_11 || b_12) << ' ' << (b_11 || true) << ' ' << (b_12 || false) << "\n"; // 1 1 0
bool b_13 = 0 > 5; // false
bool b_14 = 0 < 7; // true
bool b_15 = 10 > 13 && 5 < 14; // false
bool b_16 = b_13 && b_14 || true; // true
std::cout << b_13 << ' ' << b_14 << ' ' << b_15 << ' ' << b_16 << "\n"; // 0 1 0 1
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 10. Побитовые операции");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Операции сдивга - работают с целочисленными величинами в двоичной системе
int i_11 = 2 << 2; // 10 на ДВА разрядов влево = 1000 - в результате получим 8
int i_12 = 16 >> 3; // 10000 на ТРИ разряда вправо = 10 - в результате получим 2
// Поразрядные операции
int i_13 = 5 | 2; // 101 | 010 = 111 - 7 поразрядная дизъюнкция
int i_14 = 6 & 2; // 110 & 010 = 10 - 2 поразрядная конъюнкция (нули в начале отбрасываются)
int i_15 = 5 ^ 2; // 101 ^ 010 = 111 - 7 поразрядное исключающее ИЛИ
int i_16 = ~9; // -10 поразрядное отрицание или инверсия
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 11. Операции присваивания");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
int i_17, i_18, i_19, i_20;
i_17 = i_18 = i_19 = 34;
i_20 = i_17 + i_18 + i_19; // 102
std::cout << "i_20 = " << i_20 << "\n";
// += : присваивание после сложения.
i_17 += i_20; // 34 + 102 = 136 = i_17
std::cout << "i_17 = " << i_17 << "\n";
// -=: присваивание после вычитания
i_18 -= i_17; // -102
std::cout << "i_18 = " << i_18 << "\n";
// *=: присваивание после умножения
i_19 *= i_17; // 4624
std::cout << "i_19 = " << i_19 << "\n";
// /= : присваивание после деления
i_20 /= i_17; // 0.75 округляется до 0
std::cout << "i_20 = " << i_20 << "\n";
// %=: присваивание после деления по модулю
i_17 %= age; // остаток от деления 136 на 28 (age) равен 24
std::cout << "i_17 = " << i_17 << "\n";
/*
<<= : присваивание после сдвига разрядов влево
>>= : присваивание после сдвига разрядов вправо
&= : присваивание после поразрядной конъюнкции
|= : присваивание после поразрядной дизъюнкции
^= : присваивание после операции исключающего ИЛИ
*/
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 12. Вывод с консоли");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Для вывода на консоль применяется оператор <<.
// Этот оператор получает два операнда.
// Левый операнд представляет объект типа ostream, в данном случае объект cout.
// А правый операнд - значение, которое надо вывести на консоль.
// "\n" - перевод на новую строку
// "\t" - табуляция
// значение std::endl вызывает перевод на новую строку и сброс буфера
int Tom_age = 33;
double Tom_weight = 81.23;
std::cout << "Name: " << "Tom" << "\n";
std::cout << "Age: " << Tom_age << std::endl;
std::cout << "Weight: " << Tom_weight << std::endl;
// Ввод с консоли
// Для считывания с консоли данных применяется оператор ввода >>
std::cout << "Input age: ";
// std::cin >> Tom_age; // тип integer
std::cout << "Input weight: ";
// std::cin >> Tom_weight; // тип double
// std::cin >> age >> weight; // можно по цепочке считывать данные в различные переменные
// После ввода одного из значений надо будет ввести пробел и затем вводить следующее значение.
std::cout << "Tom age: " << Tom_age << "\t Tom weight: " << Tom_weight << std::endl;
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 13. Пространства имен и using");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
/*
Префикс "std::" указывает, что объекты cout, cin, endl определены в пространствен имен std.
А само двойное двоеточие :: представляет оператор области видимости (scope operator),
который позволяет указать, в каком пространсте имен определен объект.
Оператор "using" позволяет ввести в программу объекты из различных пространств имен
using пространство_имен::объект
*/
using std::cin;
using std::cout;
using std::endl;
using std::string;
// int main()
// {
cout << "Input age: ";
// cin >> Tom_age;
cout << "Tom age: " << Tom_age << endl;
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 14. Условные конструкции");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Конструкция if проверяет истинность условия, и если оно истинно, выполняет блок инструкций
/*
if (условие)
{
инструкции;
}
*/
// В качестве условия использоваться условное выражение, которое возвращает true или false.
if(age > Tom_age)
{
std::cout << "My age is greater than Tom age \n";
}
if(age < Tom_age)
{
std::cout << "My age is less than Tom age \n";
}
// else
if(age == Tom_age)
std::cout << "My age is equal to Tom age \n";
else std::cout << "My age is non equal Tom age \n";
/*
Нередко надо обработать не два возможных альтернативных варианта, а гораздо больше.
Например, в случае выше можно насчитать три условия: переменная x может быть больше 60, меньше 60 и равна 60.
Для проверки альтернативных условий мы можем вводить выражения else if:
*/
// В данном случае мы получаем три ветки развития событий в программе
// Если в блоке if или else или else-if необходимо выполнить только одну инструкцию, то фигурные скобки можно опустить:
if(age > Tom_age)
std::cout << "My age is greater than Tom age \n";
else if (age < Tom_age)
std::cout << "My age is less than Tom age \n";
else
std::cout << "My age is equal Tom age \n";
// Конструкция switch
/*
switch(выражение)
{
case константа_1: инструкции_1;
case константа_2: инструкции_2;
default: инструкции;
}
*/
// После ключевого слова switch в скобках идет сравниваемое выражение.
// Значение этого выражения последовательно сравнивается со значениями после оператора сase.
// И если совпадение будет найдено, то будет выполняться определенный блок сase.
// В конце конструкции switch может стоять блок default.
// Он необязателен и выполняется в том случае, если значение после switch не соответствует ни одному из операторов case.
int i_22 = age;
switch(i_22)
{
case 10:
std::cout << "i_22 = 10" << "\n";
break;
case 23:
std::cout << "i_22 = age" << "\n";
break;
case 35:
std::cout << "i_22 = Tom_age" << "\n";
break;
default:
std::cout << "i_22 is undefined" << "\n";
break;
}
// Чтобы избежать выполнения последующих блоков case/default, в конце каждого блока ставится оператор break.
// Тернарный оператор
// Тернарный оператор "?:" позволяет сократить определение простейших условных конструкций if и имеет следующую форму:
// [первый операнд - условие] ? [второй операнд] : [третий операнд]
/*
Оператор использует сразу три операнда.
В зависимости от условия тернарный оператор возвращает второй или третий операнд: если условие равно true
(то есть истинно), то возвращается второй операнд; если условие равно false (то есть ложно), то третий.
*/
int i_23 = 5;
int i_24 = 3;
char sign = '-';
std::cout << "Введите знак операции: ";
// std::cin >> sign;
int result = sign=='+' ? i_23 + i_24 : i_23 - i_24;
std::cout << "Результат: " << result << "\n";
/*
В данном случае производится ввод знака операции.
Здесь результатом тернарной операции является переменная result.
И если переменная sign содержит знак "+", то result будет равно второму операнду - (x+y) = 8.
Иначе result будет равно третьему операнду = 2.
*/
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 15. Цикл WHILE");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Цикл while - цикл с ПРЕДУСЛОВИЕМ
// Цикл while выполняет некоторый код, пока его условие истинно, то есть возвращает true.
/*
while(условие)
{
// выполняемые действия (набор инструкций)
}
*/
// Выведем квадраты чисел от 1 до 9
int i_25 = 1;
while(i_25 < 10)
{
cout << i_25 << " * " << i_25 << " = " << i_25 * i_25 << endl;
i_25++;
}
// Если цикл содержит одну инструкцию, то фигурные скобки можно опустить:
int i_26 = 0;
while(++i_26 < 10)
cout << i_26 << " * " << i_26 << " = " << i_26 * i_26 << endl;
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 16. Цикл FOR");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Цикл for
/*
for (выражение_1; выражение_2; выражение_3)
{
// тело цикла
}
выражение_1 выполняется один раз при начале выполнения цикла и представляет установку начальных условий,
как правило, это инициализация счетчиков - специальных переменных, которые используются для контроля за циклом.
выражение_2 представляет условие, при соблюдении которого выполняется цикл.
Как правило, в качестве условия используется операция сравнения, и если она возвращает ненулевое значение
(то есть условие истинно), то выполняется тело цикла, а затем вычисляется выражение_3.
выражение_3 задает изменение параметров цикла, нередко здесь происходит увеличение счетчиков цикла на единицу.
*/
// Перепишем программу по выводу квадратов чисел с помощью цикла for
for(int i_27 = 10; i_27 > 0; i_27--)
cout << i_27 << " * " << i_27 << " = " << i_27 * i_27 << endl;
// Необязательно указывать все три выражения в определении цикла, мы можем одно или даже все из них опустить:
// for(; i < 10;)
// вложенные циклы / двойные циклы (вывод таблицы умножения)
for (int i_28 = 1; i_28 < 10; i_28++)
{
for (int i_29 = 1; i_29 < 10; i_29++)
{
std::cout << i_28 * i_29 << "\t";
}
std::cout << std::endl;
}
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 17. Цикл DO");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Цикл do - цикл с ПОСТУСЛОВИЕМ
/*
do
{
инструкции
}
while(условие);
*/
int i_30 = 5;
do
{
std::cout << "i_30" << '=' << i_30 << std::endl;
i_30--;
}
while(i_30 > 0);
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 18. Операторы continue и break");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Операторы "continue" и "break"
// Иногда возникает необходимость выйти из цикла до его завершения
int i_31 = 1;
for ( ; ;)
{
std::cout << i_31 << "*" << i_31 << "=" << i_31*i_31 << "\n";
i_31++;
if (i_31 > 9) break;
}
// оператор continue производит переход к следующей итерации
int summ_1 = 0;
for (int i_32=0; i_32<10; i_32++)
{
if (i_32 % 2 == 0) continue;
summ_1 +=i_32;
std::cout << "i_32 = " << i_32 << "\n";
}
std::cout << "summ_1 = " << summ_1 << std::endl; // 25
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 19. Ссылки (reference)");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Ссылки (reference)
// После установления ссылки мы можем через нее манипулировать самим объектом, на который она ссылается:
int number_1 = 5;
int &refNumber_1 = number_1;
cout << refNumber_1 << endl;;
refNumber_1 = 25;
cout << number_1 << endl;
// ссылки на константы
const int number_2 = 6;
const int &refNumber_2 = number_2;
cout << refNumber_2 << endl;
// refNumber_2 = 20; изменять значение по ссылке нельзя
// константная ссылка может указывать и на обычную переменную
int number_3 = 7;
const int &refNumber_3 = number_3;
cout << refNumber_3 << endl;
// refNumber_3 = 20; изменять значение по ссылке на константу нельзя
// но мы можем изменить саму переменную
number_3 = 27;
cout << refNumber_3 << endl;
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 20. Массивы");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Массивы
// определим массив из 4 чисел
int m_1[4]; // массив из неопределенных чисел
int m_2[4] = {1, 2, 3, 4}; // Значения в фигурных скобках - инициализаторы
// неявное задание массива
int m_3[] = {1, 2, 3, 4, 5, 6};
// символьные массивы
char m_4[] = {'h','e','l','l','o'};
char m_5[] = "world";
// во втором случае массив m_5 будет иметь не 5 элементов, а 6, поскольку при инициализации строкой в символьный массив автоматически добавляется нулевой символ '\0'.
// После определения массива мы можем обратиться к его отдельным элементам по индексу
// нумерация начинается с нуля
int first_number = m_4[0];
cout << first_number << endl; // 'h'
m_4[0] = 'H';
cout << m_4 << endl;
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 21. Перебор массивов");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Перебор массивов
// Используя циклы, можно пробежаться по всему массиву и через индексы обратиться к его элементам:
int size = sizeof(m_3)/sizeof(m_3[0]);
for(int i_32 = 0; i_32 < size; i_32++)
cout << m_3[i_32] << endl;
/*
с помощью выражения sizeof(m_3) находим длину всего массива в байтах,
а с помощью выражения sizeof(m_3[0]) - длину одного элемента в байтах.
Разделив два значения, можно получить количество элементов в массиве
*/
// существует еще одна форма цикла for, которая предназначена специально для работа с коллекциями, в том числе с массивами
/* for(тип переменная : коллекция)
{
инструкции;
}
*/
for(char symbol_1 : m_4)
cout << symbol_1 << endl;
// При переборе массива каждый перебираемый элемент будет помещаться в переменную number,
// значение которой в цикле выводится на консоль.
// Если тип объектов в массиве неизвестен, то можно использовать спецификатор auto для определения типа:
for(auto symbol_2 : m_5)
cout << symbol_2 << endl;
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 22. Многомерные массивы");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Многомерные массивы
// Элементы таких массивов сами в свою очередь являются массивами, в которых также элементы могут быть массивами.
// двухмерный массив чисел
// Такой массив состоит из трех элементов, при этом каждый элемент представляет массив из двух элементов
int m_2d[3][2] = { {1, 2}, {4, 5}, {7, 8} };
cout << m_2d[1][0] << endl;
m_2d[1][0] = 155; // изменение элемента
cout << m_2d[1][0] << endl;
// Переберем двухмерный массив:
const int ROW = 3, COL = 3;
int numbers[ROW][COL] = { {1, 2,3 }, {4 ,5 ,6}, {7 ,8 ,9} };
for(int i_33 = 0; i_33 < ROW; i_33++)
{
for(int i_34 = 0; i_34 < COL; i_34++)
{
cout << numbers[i_33][i_34] << "\t";
}
cout << endl;
}
// Другая форма цикла for:
for(auto &subnumbers : numbers)
{
for(int number : subnumbers)
{
cout << number << "\t";
}
cout << endl;
}
/*
Для перебора массивов, которые входят в массив, применяются ссылки.
То есть во внешнем цикле for(auto &subnumbers : numbers) &subnumbers представляет ссылку
на подмассив в массиве. Во внутреннем цикле for(int number : subnumbers) из каждого подмассива
в subnumbers получаем отдельные его элементы в переменную number и выводим ее значение на консоль.
*/
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 23. Строки");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Строки
std::string morning = "Good morning, C++!";
std::cout << morning << "\n";
/*
Тип string определен в стандартной библиотеке и при его использовании
надо указывать пространство имен std.
Можно использовать выражение using, чтобы не указывать префикс std:
using std::string;
СТРОКА 317
*/
// Для инициализации строк можно использовать различные способы:
string s1; // пустая строка
string s2 = "Good"; // Good
string s3("morning"); // morning
string s4(5, '!'); // !!!!!
string s5 = s2; // Good
cout << s1 << "\n";
cout << s2 << "\n";
cout << s3 << "\n";
cout << s4 << "\n";
cout << s5 << "\n";
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 24. Конкатенация строк");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// можно объединять строки с помощью стандартной операции сложения
string STR = "<<" + s2 + ">>" + " + " + "<<" + s3 + ">> = " + s2 + " " + s3; // Good morning
cout << STR << endl;
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 25. Сравнение строк");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Оператор "==" возвращает true, если все символы обеих строк равны
bool result_1 = s2 == s3; // false
result_1 = s2 == "morning"; // false
result_1 = s2 == "Good"; // true
// При этом символы должны совпадать в том числе по регистру
// Операция "!=" возвращает true, если две строки не совпадают
bool result_2 = s2 != s3; // true
result_2 = s2 != "Good"; // true
result_2 = s2 != "good"; // false
/*
Остальные базовые операции сравнения <, <=, >, >= сравнивают строки в зависимости
от регистра и алфавитного порядка символов.
Например, строка "b" условно больше строки "a", так как символ b по алфавиту идет
после символа a. А строка "a" больше строки "A".
Если первые символы строки равны, то сравниваются последующие символы
*/
s3.replace( 0, 1, 1, 'M' ); // замена (изменение) первого символа в строке
bool result_3 = s2 < s3; // false
cout << s2 << " > " << s3 << " " << result_3 << " (true)" << endl;
// символ "G" меньше символа "M", так в алфавите G стоит раньше M
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 26. Размер строки");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// С помощью метода size() можно узнать размер строки, то есть из скольких символов она состоит
cout << "Длина строки STR составляет" << " " << STR.size() << " " << "символов" << endl; //
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 27. Чтение строки с консоли");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Для считывания введенной строки с консоли можно использовать объект std::cin:
string NAME;
cout << "Введите ваше Имя: ";
cin >> NAME;
cout << "Ваше Имя, кажется, " << NAME << " ?" << endl;
// кириллица не поддерживается!!
/*
Однако если при данном способе ввода строка будет содержать подстроки, разделенные пробелом,
то std::cin будет использовать только первую подстроку:
"NAME SURNAME" --> "NAME"
*/
// НЕ РАБОТАЕТ!!
// Чтобы считать всю строку, применяется метод getline():
string FIO;
cout << "Введите ваши ФИО: ";
std::getline(std::cin, FIO);
cout << "Ваши данные, кажется, " << FIO << " ?" << endl;
// НЕ РАБОТАЕТ!!
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 28. Получение и изменение символов строки");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
char c_1 = s2[1]; // G
s2[0] = 'M';
cout << s2 << endl; // Mood
// Функции
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 29. Определение и объявление функций");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// функция - это именованный блок кода
/*
тип имя_функции(параметры) // заголовок функции (Если функция не возвращает никакого значения, то используется тип void)
{
инструкции
}
имя функции, которое представляет произвольный идентификатор.
К именованию функции применяются те же правила, что и к именованию переменных
Для возвращения результата функция применяет оператор return.
если функция имеет тип void, то ей не надо ничего возвращать
*/
// Определение функции
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 30. Выполнение функции");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// имя_функции(аргументы);
// при вызове функции hello (СТРОКА 39) программа два раза выведет строку "hello".
hello();
hello();
// Параметры функции
// определим программу обменного пункта exchange (СТРОКА 44)
double rate = 58;
double sum = 5000;
exchange(rate, sum); // Параметры перечисляются в скобках после имени функции
exchange(60, 5000); // При вызове функции exchange для этих параметров необходимо передать значения, аргументы.
// первый аргумент передается перому параметру, второй аргумент - второму параметру и так далее.
// Объявление функций с несколькими аргументами различных типов
square(4.56); // число с двойной точностью будет преобразовано в целоечисленное, котороые объявлено в функции square (СТРОКА 52)
display("Tom", 33); // первый аргумент - строка, второй - целое число (СТРОКА 57)
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 31. Аргументы по умолчанию");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Аргументы по умолчанию (СТРОКА 62)
// функция multiply возвращает результат произведения параметров n и m, причем в самой функции параметр n пока не определен
multiply(4, 5); // параметр n = 4, m = 5
multiply(4); // если параметр m явяно не объявить, то будет использовано значение параметра по умолчанию (в самой функции m = 3)
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 32. Передача аргументов по значению");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// Передача аргументов по значению
// изменения аргументов в функции square действуют только в рамках этой функции. Вне ее значения переменных a и b остаются неизменными
int SQ1 = 4;
int SQ2 = 5;
std::cout << "Before square: SQ1 = " << SQ1 << "\tSQ2=" << SQ2 << std::endl;
square_1(SQ1, SQ2);
std::cout << "After square: SQ1 = " << SQ1 << "\tSQ2=" << SQ2 << std::endl;
/*
При компиляции функции для ее параметров выделяются отдельные участки памяти.
При вызове функции вычисляются значения аргументов, которые передаются на место параметров.
И затем значения аргументов заносятся в эти участки памяти.
То есть функция манипулирует копиями значений объектов, а не самими объектами.
*/
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 33. Передача параметров по ссылке");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
// При передаче параметров по ссылке передается ссылка на объект,
// через которую мы можем манипулировать самим объектов, а не просто его значением (СТРОКА 75)
int SQ3 = 4;
int SQ4 = 5;
std::cout << "Before square: SQ3 = " << SQ3 << "\tSQ4=" << SQ4 << std::endl;
square_2(SQ3, SQ4);
std::cout << "After square: SQ3 = " << SQ3 << "\tSQ4=" << SQ4 << std::endl;
/*
Передача параметров по значению больше подходит для передачи в функцию небольших объектов,
значения которых копируются в определенные участки памяти, которые потом использует функция.
Передача параметров по ссылке больше подходит для передачи в функцию больших объектов,
в этом случае не нужно копировать все содержимое объекта в участок памяти,
за счет чего увеличивается производительность программы.
*/
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Green));
printf("Задание № 34. Константные параметры");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
std::cout << "\n";
//Константные параметры
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | Cyan));
printf("Bye World!");
SetConsoleTextAttribute(hConsole, (WORD) ((Black << 4) | White));
return 0; // выходим из функции
} // конец функции
|
#pragma once
#include <vector>
#include <utility>
namespace gms
{
template <typename T>
class matrix
{
public:
matrix(size_t rows, size_t cols);
T* data();
typename std::vector<T>::iterator begin();
typename std::vector<T>::iterator end();
T& operator()(size_t row, size_t col);
const T& operator()(size_t row, size_t col) const;
std::pair<typename std::vector<T>::iterator, typename std::vector<T>::iterator> row(size_t row);
std::pair<typename std::vector<T>::const_iterator, typename std::vector<T>::const_iterator > row(size_t row) const;
size_t rows() const;
size_t cols() const;
private:
size_t m_rows;
size_t m_cols;
std::vector<T> m_data;
};
}
#include "matrix.inl"
|
#include "BackConverter.hpp"
#include "SliceMatcher.hpp"
using namespace type_to_vector;
void FlatBackConverter::setSlice(const std::string& slice) {
if ( mpMatcher ) {
delete mpMatcher;
mpMatcher = 0;
}
if (slice != "") mpMatcher = new SliceMatcher(slice);
}
FlatBackConverter::~FlatBackConverter() {
if (mpMatcher) delete mpMatcher;
}
void FlatBackConverter::apply(const VectorOfDoubles& vec, void* data) {
mpData = data;
mpVec = &vec;
mElementCounter = 0;
VectorTocVisitor::visit(mToc);
mpVec = 0;
mpData = 0;
}
void* FlatBackConverter::getPosition (const VectorValueInfo& info) {
return mpData + info.position;
}
void FlatBackConverter::setElement(const VectorValueInfo& info) {
if (mElementCounter >= mpVec->size()) return;
if (!mpMatcher || mpMatcher->fitsASlice(info.placeDescription)) {
info.backCastFun(getPosition(info), mpVec->at(mElementCounter));
mElementCounter++;
}
}
void FlatBackConverter::visit(const VectorValueInfo& info) {
// Pointer to content equals zero means no container.
if (!info.content.get()) setElement(info);
}
void BackConverter::apply(const VectorOfDoubles& vec, void* data) {
mpData = data;
mpVec = &vec;
mElementCounter = 0;
mBaseStack.clear();
mBaseStack.push_back(data);
mContainersSizeStack.clear();
mPlaceStack.clear();
VectorTocVisitor::visit(mToc);
mpVec = 0;
mpData = 0;
}
void* BackConverter::getPosition(const VectorValueInfo& info) {
void* ptr = mBaseStack.back() + info.position;
if (!mContainersSizeStack.empty())
ptr += mContainersSizeStack.back();
return ptr;
}
void BackConverter::setElement(const VectorValueInfo& info) {
if (mElementCounter >= mpVec->size()) return;
bool push_this = true;
if (mpMatcher) {
if (info.placeDescription != "" ) mPlaceStack.push_back(info.placeDescription);
std::string this_place = utilmm::join(mPlaceStack,".");
push_this = mpMatcher->fitsASlice(this_place);
if (info.placeDescription != "" ) mPlaceStack.pop_back();
}
if (push_this) {
info.backCastFun(getPosition(info), mpVec->at(mElementCounter));
mElementCounter++;
}
}
void BackConverter::visit(const VectorValueInfo& info) {
// If there is a content pointer, it means this is a container.
if (info.content.get()) {
const Typelib::Container& t =
static_cast<const Typelib::Container&>(*mrRegistry.get(info.containerType));
void* ptr = getPosition(info);
unsigned int ecnt = t.getElementCount( ptr );
if ( ecnt == 0 ) return;
unsigned int esize = t.getIndirection().getSize();
std::vector<uint8_t>* vector_ptr =
reinterpret_cast<std::vector<uint8_t>*>( ptr );
mBaseStack.push_back(&(*vector_ptr)[0]);
mContainersSizeStack.push_back(0);
int istar;
if (mpMatcher) {
mPlaceStack.push_back(info.placeDescription);
istar = mPlaceStack.back().size()-1;
}
for ( int i=0; i<ecnt; i++) {
if (mpMatcher) {
mPlaceStack.back().replace(mPlaceStack.back().begin()+istar,
mPlaceStack.back().end(),
boost::lexical_cast<std::string,int>(i) );
}
VectorTocVisitor::visit(*(info.content));
mContainersSizeStack.back() += esize;
}
if (mpMatcher) mPlaceStack.pop_back();
mContainersSizeStack.pop_back();
mBaseStack.pop_back();
}
else setElement(info);
}
|
// Copyright 2020-2021 Russ 'trdwll' Treadwell <trdwll.com>. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "SteamEnums.generated.h"
UENUM(BlueprintType)
enum class ESteamGameOverlayTypes : uint8
{
Friends,
Community,
Players,
Settings,
OfficialGameGroup,
Stats,
Achievements
};
UENUM(BlueprintType)
enum class ESteamGameUserOverlayTypes : uint8
{
SteamID,
Chat,
JoinTrade,
Stats,
Achievements,
FriendAdd,
FriendRemove,
FriendRequestAccept,
FriendRequestIgnore
};
UENUM(BlueprintType)
enum class ESteamBeginAuthSessionResult : uint8
{
OK = 0 UMETA(DisplayName = "OK"),
InvalidTicket = 1 UMETA(DisplayName = "InvalidTicket"),
DuplicateRequest = 2 UMETA(DisplayName = "DuplicateRequest"),
InvalidVersion = 3 UMETA(DisplayName = "InvalidVersion"),
GameMismatch = 4 UMETA(DisplayName = "GameMismatch"),
ExpiredTicket = 5 UMETA(DisplayName = "ExpiredTicket")
};
UENUM(BlueprintType)
enum class ESteamAuthSessionResponse : uint8
{
OK = 0 UMETA(DisplayName = "OK"),
UserNotConnectedToSteam = 1 UMETA(DisplayName = "UserNotConnectedToSteam"),
NoLicenseOrExpired = 2 UMETA(DisplayName = "NoLicenseOrExpired"),
VACBanned = 3 UMETA(DisplayName = "VACBanned"),
LoggedInElseWhere = 4 UMETA(DisplayName = "LoggedInElseWhere"),
VACCheckTimedOut = 5 UMETA(DisplayName = "VACCheckTimedOut"),
AuthTicketCanceled = 6 UMETA(DisplayName = "AuthTicketCanceled"),
AuthTicketInvalidAlreadyUsed = 7 UMETA(DisplayName = "AuthTicketInvalidAlreadyUsed"),
AuthTicketInvalid = 8 UMETA(DisplayName = "AuthTicketInvalid"),
PublisherIssuedBan = 9 UMETA(DisplayName = "PublisherIssuedBan")
};
UENUM(BlueprintType)
enum class ESteamVoiceResult : uint8
{
OK = 0 UMETA(DisplayName = "OK"),
NotInitialized = 1 UMETA(DisplayName = "NotInitialized"),
NotRecording = 2 UMETA(DisplayName = "NotRecording"),
NoData = 3 UMETA(DisplayName = "NoData"),
BufferTooSmall = 4 UMETA(DisplayName = "BufferTooSmall"),
DataCorrupted = 5 UMETA(DisplayName = "DataCorrupted"),
Restricted = 6 UMETA(DisplayName = "Restricted"),
UnsupportedCodec = 7 UMETA(DisplayName = "UnsupportedCodec"),
ReceiverOutOfDate = 8 UMETA(DisplayName = "ReceiverOutOfDate"),
ReceiverDidNotAnswer = 9 UMETA(DisplayName = "ReceiverDidNotAnswer")
};
UENUM(BlueprintType)
enum class ESteamUserHasLicenseForAppResult : uint8
{
HasLicense = 0 UMETA(DisplayName = "HasLicense"),
DoesNotHaveLicense = 1 UMETA(DisplayName = "DoesNotHaveLicense"),
NoAuth = 2 UMETA(DisplayName = "NoAuth")
};
UENUM(BlueprintType)
enum class ESteamFailureType : uint8
{
FlushedCallbackQueue UMETA(DisplayName = "FlushedCallbackQueue"),
PipeFail UMETA(DisplayName = "PipeFail")
};
UENUM(BlueprintType)
enum class ESteamDenyReason : uint8
{
Invalid = 0 UMETA(DisplayName = "Invalid"),
InvalidVersion = 1 UMETA(DisplayName = "InvalidVersion"),
Generic = 2 UMETA(DisplayName = "Generic"),
NotLoggedOn = 3 UMETA(DisplayName = "NotLoggedOn"),
NoLicense = 4 UMETA(DisplayName = "NoLicense"),
Cheater = 5 UMETA(DisplayName = "Cheater"),
LoggedInElseWhere = 6 UMETA(DisplayName = "LoggedInElseWhere"),
UnknownText = 7 UMETA(DisplayName = "UnknownText"),
IncompatibleAnticheat = 8 UMETA(DisplayName = "IncompatibleAnticheat"),
MemoryCorruption = 9 UMETA(DisplayName = "MemoryCorruption"),
IncompatibleSoftware = 10 UMETA(DisplayName = "IncompatibleSoftware"),
SteamConnectionLost = 11 UMETA(DisplayName = "SteamConnectionLost"),
SteamConnectionError = 12 UMETA(DisplayName = "SteamConnectionError"),
SteamResponseTimedOut = 13 UMETA(DisplayName = "SteamResponseTimedOut"),
SteamValidationStalled = 14 UMETA(DisplayName = "SteamValidationStalled"),
SteamOwnerLeftGuestUser = 15 UMETA(DisplayName = "SteamOwnerLeftGuestUser")
};
UENUM(BlueprintType)
enum class ESteamResult : uint8
{
None = 0 UMETA(DisplayName = "None"),
OK = 1 UMETA(DisplayName = "OK"),
Fail = 2 UMETA(DisplayName = "Fail"),
NoConnection = 3 UMETA(DisplayName = "NoConnection"),
InvalidPassword = 5 UMETA(DisplayName = "InvalidPassword"),
LoggedInElsewhere = 6 UMETA(DisplayName = "LoggedInElsewhere"),
InvalidProtocolVer = 7 UMETA(DisplayName = "InvalidProtocolVer"),
InvalidParam = 8 UMETA(DisplayName = "InvalidParam"),
FileNotFound = 9 UMETA(DisplayName = "FileNotFound"),
Busy = 10 UMETA(DisplayName = "Busy"),
InvalidState = 11 UMETA(DisplayName = "InvalidState"),
InvalidName = 12 UMETA(DisplayName = "InvalidName"),
InvalidEmail = 13 UMETA(DisplayName = "InvalidEmail"),
DuplicateName = 14 UMETA(DisplayName = "DuplicateName"),
AccessDenied = 15 UMETA(DisplayName = "AccessDenied"),
Timeout = 16 UMETA(DisplayName = "Timeout"),
Banned = 17 UMETA(DisplayName = "Banned"),
AccountNotFound = 18 UMETA(DisplayName = "AccountNotFound"),
InvalidSteamID = 19 UMETA(DisplayName = "InvalidSteamID"),
ServiceUnavailable = 20 UMETA(DisplayName = "ServiceUnavailable"),
NotLoggedOn = 21 UMETA(DisplayName = "NotLoggedOn"),
Pending = 22 UMETA(DisplayName = "Pending"),
EncryptionFailure = 23 UMETA(DisplayName = "EncryptionFailure"),
InsufficientPrivilege = 24 UMETA(DisplayName = "InsufficientPrivilege"),
LimitExceeded = 25 UMETA(DisplayName = "LimitExceeded"),
Revoked = 26 UMETA(DisplayName = "Revoked"),
Expired = 27 UMETA(DisplayName = "Expired"),
AlreadyRedeemed = 28 UMETA(DisplayName = "AlreadyRedeemed"),
DuplicateRequest = 29 UMETA(DisplayName = "DuplicateRequest"),
AlreadyOwned = 30 UMETA(DisplayName = "AlreadyOwned"),
IPNotFound = 31 UMETA(DisplayName = "IPNotFound"),
PersistFailed = 32 UMETA(DisplayName = "PersistFailed"),
LockingFailed = 33 UMETA(DisplayName = "LockingFailed"),
LogonSessionReplaced = 34 UMETA(DisplayName = "LogonSessionReplaced"),
ConnectFailed = 35 UMETA(DisplayName = "ConnectFailed"),
HandshakeFailed = 36 UMETA(DisplayName = "HandshakeFailed"),
IOFailure = 37 UMETA(DisplayName = "IOFailure"),
RemoteDisconnect = 38 UMETA(DisplayName = "RemoteDisconnect"),
ShoppingCartNotFound = 39 UMETA(DisplayName = "ShoppingCartNotFound"),
Blocked = 40 UMETA(DisplayName = "Blocked"),
Ignored = 41 UMETA(DisplayName = "Ignored"),
NoMatch = 42 UMETA(DisplayName = "NoMatch"),
AccountDisabled = 43 UMETA(DisplayName = "AccountDisabled"),
ServiceReadOnly = 44 UMETA(DisplayName = "ServiceReadOnly"),
AccountNotFeatured = 45 UMETA(DisplayName = "AccountNotFeatured"),
AdministratorOK = 46 UMETA(DisplayName = "AdministratorOK"),
ContentVersion = 47 UMETA(DisplayName = "ContentVersion"),
TryAnotherCM = 48 UMETA(DisplayName = "TryAnotherCM"),
PasswordRequiredToKickSession = 49 UMETA(DisplayName = "PasswordRequiredToKickSession"),
AlreadyLoggedInElsewhere = 50 UMETA(DisplayName = "AlreadyLoggedInElsewhere"),
Suspended = 51 UMETA(DisplayName = "Suspended"),
Cancelled = 52 UMETA(DisplayName = "Cancelled"),
DataCorruption = 53 UMETA(DisplayName = "DataCorruption"),
DiskFull = 54 UMETA(DisplayName = "DiskFull"),
RemoteCallFailed = 55 UMETA(DisplayName = "RemoteCallFailed"),
PasswordUnset = 56 UMETA(DisplayName = "PasswordUnset"),
ExternalAccountUnlinked = 57 UMETA(DisplayName = "ExternalAccountUnlinked"),
PSNTicketInvalid = 58 UMETA(DisplayName = "PSNTicketInvalid"),
ExternalAccountAlreadyLinked = 59 UMETA(DisplayName = "ExternalAccountAlreadyLinked"),
RemoteFileConflict = 60 UMETA(DisplayName = "RemoteFileConflict"),
IllegalPassword = 61 UMETA(DisplayName = "IllegalPassword"),
SameAsPreviousValue = 62 UMETA(DisplayName = "SameAsPreviousValue"),
AccountLogonDenied = 63 UMETA(DisplayName = "AccountLogonDenied"),
CannotUseOldPassword = 64 UMETA(DisplayName = "CannotUseOldPassword"),
InvalidLoginAuthCode = 65 UMETA(DisplayName = "InvalidLoginAuthCode"),
AccountLogonDeniedNoMail = 66 UMETA(DisplayName = "AccountLogonDeniedNoMail"),
HardwareNotCapableOfIPT = 67 UMETA(DisplayName = "HardwareNotCapableOfIPT"),
IPTInitError = 68 UMETA(DisplayName = "IPTInitError"),
ParentalControlRestricted = 69 UMETA(DisplayName = "ParentalControlRestricted"),
FacebookQueryError = 70 UMETA(DisplayName = "FacebookQueryError"),
ExpiredLoginAuthCode = 71 UMETA(DisplayName = "ExpiredLoginAuthCode"),
IPLoginRestrictionFailed = 72 UMETA(DisplayName = "IPLoginRestrictionFailed"),
AccountLockedDown = 73 UMETA(DisplayName = "AccountLockedDown"),
AccountLogonDeniedVerifiedEmailRequired = 74 UMETA(DisplayName = "AccountLogonDeniedVerifiedEmailRequired"),
NoMatchingURL = 75 UMETA(DisplayName = "NoMatchingURL"),
BadResponse = 76 UMETA(DisplayName = "BadResponse"),
RequirePasswordReEntry = 77 UMETA(DisplayName = "RequirePasswordReEntry"),
ValueOutOfRange = 78 UMETA(DisplayName = "ValueOutOfRange"),
UnexpectedError = 79 UMETA(DisplayName = "UnexpectedError"),
Disabled = 80 UMETA(DisplayName = "Disabled"),
InvalidCEGSubmission = 81 UMETA(DisplayName = "InvalidCEGSubmission"),
RestrictedDevice = 82 UMETA(DisplayName = "RestrictedDevice"),
RegionLocked = 83 UMETA(DisplayName = "RegionLocked"),
RateLimitExceeded = 84 UMETA(DisplayName = "RateLimitExceeded"),
AccountLoginDeniedNeedTwoFactor = 85 UMETA(DisplayName = "AccountLoginDeniedNeedTwoFactor"),
ItemDeleted = 86 UMETA(DisplayName = "ItemDeleted"),
AccountLoginDeniedThrottle = 87 UMETA(DisplayName = "AccountLoginDeniedThrottle"),
TwoFactorCodeMismatch = 88 UMETA(DisplayName = "TwoFactorCodeMismatch"),
TwoFactorActivationCodeMismatch = 89 UMETA(DisplayName = "TwoFactorActivationCodeMismatch"),
AccountAssociatedToMultiplePartners = 90 UMETA(DisplayName = "AccountAssociatedToMultiplePartners"),
NotModified = 91 UMETA(DisplayName = "NotModified"),
NoMobileDevice = 92 UMETA(DisplayName = "NoMobileDevice"),
TimeNotSynced = 93 UMETA(DisplayName = "TimeNotSynced"),
SmsCodeFailed = 94 UMETA(DisplayName = "SmsCodeFailed"),
AccountLimitExceeded = 95 UMETA(DisplayName = "AccountLimitExceeded"),
AccountActivityLimitExceeded = 96 UMETA(DisplayName = "AccountActivityLimitExceeded"),
PhoneActivityLimitExceeded = 97 UMETA(DisplayName = "PhoneActivityLimitExceeded"),
RefundToWallet = 98 UMETA(DisplayName = "RefundToWallet"),
EmailSendFailure = 99 UMETA(DisplayName = "EmailSendFailure"),
NotSettled = 100 UMETA(DisplayName = "NotSettled"),
NeedCaptcha = 101 UMETA(DisplayName = "NeedCaptcha"),
GSLTDenied = 102 UMETA(DisplayName = "GSLTDenied"),
GSOwnerDenied = 103 UMETA(DisplayName = "GSOwnerDenied"),
InvalidItemType = 104 UMETA(DisplayName = "InvalidItemType"),
IPBanned = 105 UMETA(DisplayName = "IPBanned"),
GSLTExpired = 106 UMETA(DisplayName = "GSLTExpired"),
InsufficientFunds = 107 UMETA(DisplayName = "InsufficientFunds"),
TooManyPending = 108 UMETA(DisplayName = "TooManyPending")
};
UENUM(BlueprintType)
enum class ESteamPersonaChange : uint8
{
None = 0 UMETA(DisplayName = "None"),
ChangeName = 1 UMETA(DisplayName = "ChangedName"),
ChangeStatus = 2 UMETA(DisplayName = "ChangedStatus"),
ChangeComeOnline = 3 UMETA(DisplayName = "ComeOnline"),
ChangeGoneOffline = 4 UMETA(DisplayName = "GoneOffline"),
ChangeGamePlayed = 5 UMETA(DisplayName = "ChangedGame"),
ChangeGameServer = 6 UMETA(DisplayName = "ChangeServer"),
ChangeAvatar = 7 UMETA(DisplayName = "ChangedAvatar"),
ChangeJoinedSource = 8 UMETA(DisplayName = "ChangedSource"),
ChangeLeftSource = 9 UMETA(DisplayName = "LeftSource"),
ChangeRelationshipChanged = 10 UMETA(DisplayName = "ChangedRelationship"),
ChangeNameFirstSet = 11 UMETA(DisplayName = "ChangedFirstName"),
ChangeFacebookInfo = 12 UMETA(DisplayName = "ChangedFacebookInfo"),
ChangeNickname = 13 UMETA(DisplayName = "ChangedNickname"),
ChangeSteamLevel = 14 UMETA(DisplayName = "ChangeSteamLevel"),
ChangeErr = 15 UMETA(DisplayName = "Error")
};
UENUM(BlueprintType)
enum class ESteamDurationControlNotification : uint8
{
None, // just informing you about progress, no notification to show
OneHour, // "you've been playing for an hour"
ThreeHours, // "you've been playing for 3 hours; take a break"
HalfProgress, // "your XP / progress is half normal"
NoProgress // "your XP / progress is zero"
};
UENUM(BlueprintType)
enum class ESteamDurationControlProgress : uint8
{
Full = 0, // Full progress
Half = 1, // deprecated - XP or persistent rewards should be halved
None = 2, // deprecated - XP or persistent rewards should be stopped
ExitSoon_3h = 3, // allowed 3h time since 5h gap/break has elapsed, game should exit - steam will terminate the game soon
ExitSoon_5h = 4, // allowed 5h time in calendar day has elapsed, game should exit - steam will terminate the game soon
ExitSoon_Night = 5 // game running after day period, game should exit - steam will terminate the game soon
};
UENUM(BlueprintType)
enum class ESteamOverlayToStoreFlag : uint8
{
None = 0,
AddToCart = 1,
AddToCartAndShow = 2
};
UENUM(BlueprintType)
enum class ESteamChatEntryType : uint8
{
Invalid = 0 UMETA(DisplayName = "Invalid"),
ChatMessage = 1 UMETA(DisplayName = "ChatMessage"),
Typing = 2 UMETA(DisplayName = "Typing"),
InviteGame = 3 UMETA(DisplayName = "InviteGame"),
Emote = 4 UMETA(DisplayName = "Emote"),
LeftConversation = 6 UMETA(DisplayName = "LeftConversation"),
Entered = 7 UMETA(DisplayName = "Entered"),
WasKicked = 8 UMETA(DisplayName = "WasKicked"),
WasBanned = 9 UMETA(DisplayName = "WasBanned"),
Disconnected = 10 UMETA(DisplayName = "Disconnected"),
HistoricalChat = 11 UMETA(DisplayName = "HistoricalChat"),
LinkBlocked = 14 UMETA(DisplayName = "LinkBlocked")
};
UENUM(BlueprintType)
enum class ESteamFriendFlags : uint8
{
Blocked = 0 UMETA(DisplayName = "Blocked"),
FriendshipRequested = 1 UMETA(DisplayName = "FriendshipRequested"),
Immediate = 2 UMETA(DisplayName = "Immediate"),
ClanMember = 3 UMETA(DisplayName = "ClanMember"),
OnGameServer = 4 UMETA(DisplayName = "OnGameServer"),
HasPlayedWith = 5 UMETA(DisplayName = "HasPlayedWith"),
FriendOfFriend = 6 UMETA(DisplayName = "FriendOfFriend"),
RequestingFriendship = 7 UMETA(DisplayName = "RequestingFriendship"),
RequestingInfo = 8 UMETA(DisplayName = "RequestingInfo"),
Ignored = 9 UMETA(DisplayName = "Ignored"),
IgnoredFriend = 10 UMETA(DisplayName = "IgnoredFriend"),
Suggested = 11 UMETA(DisplayName = "Suggested"),
ChatMember = 12 UMETA(DisplayName = "ChatMember"),
All = 13 UMETA(DisplayName = "All")
};
UENUM(BlueprintType)
enum class ESteamPersonaState : uint8
{
Offline = 0 UMETA(DisplayName = "Offline"),
Online = 1 UMETA(DisplayName = "Online"),
Busy = 2 UMETA(DisplayName = "Busy"),
Away = 3 UMETA(DisplayName = "Away"),
Snooze = 4 UMETA(DisplayName = "Snooze"),
LookingToTrade = 5 UMETA(DisplayName = "LookingToTrade"),
LookingToPlay = 6 UMETA(DisplayName = "LookingToPlay"),
Max UMETA(DisplayName = "Max")
};
UENUM(BlueprintType)
enum class ESteamFriendRelationship : uint8
{
None = 0 UMETA(DisplayName = "None"),
Blocked = 1 UMETA(DisplayName = "Blocked"),
RequestRecipient = 2 UMETA(DisplayName = "RequestRecipient"),
Friend = 3 UMETA(DisplayName = "Friend"),
RequestInitiator = 4 UMETA(DisplayName = "RequestInitiator"),
Ignored = 5 UMETA(DisplayName = "Ignored"),
IgnoredFriend = 6 UMETA(DisplayName = "IgnoredFriend"),
Max = 8 UMETA(DisplayName = "Max")
};
UENUM(BlueprintType)
enum class ESteamAvatarSize : uint8
{
Small UMETA(DisplayName = "Small (32*32)"),
Medium UMETA(DisplayName = "Medium (64*64)"),
Large UMETA(DisplayName = "Large (128*128)")
};
UENUM(BlueprintType)
enum class ESteamUserRestrictions : uint8
{
Unknown = 0 UMETA(DisplayName = "Unknown"),
AnyChat = 1 UMETA(DisplayName = "AnyChat"),
VoiceChat = 2 UMETA(DisplayName = "VoiceChat"),
GroupChat = 3 UMETA(DisplayName = "GroupChat"),
Rating = 4 UMETA(DisplayName = "Rating"),
GameInvites = 5 UMETA(DisplayName = "GameInvites"),
Trading = 6 UMETA(DisplayName = "Trading")
};
UENUM(BlueprintType)
enum class ESteamChatRoomEnterResponse : uint8
{
Unknown = 0 UMETA(DisplayName = "Unknown"),
Success = 1 UMETA(DisplayName = "Success"),
DoesntExist = 2 UMETA(DisplayName = "DoesntExist"),
NotAllowed = 3 UMETA(DisplayName = "NotAllowed"),
Full = 4 UMETA(DisplayName = "Full"),
Error = 5 UMETA(DisplayName = "Error"),
Banned = 6 UMETA(DisplayName = "Banned"),
Limited = 7 UMETA(DisplayName = "Limited"),
ClanDisabled = 8 UMETA(DisplayName = "ClanDisabled"),
CommunityBan = 9 UMETA(DisplayName = "CommunityBan"),
MemberBlockedYou = 10 UMETA(DisplayName = "MemberBlockedYou"),
YouBlockedMember = 11 UMETA(DisplayName = "YouBlockedMember")
};
UENUM(BlueprintType)
enum class ESteamHTMLKeyModifiers : uint8
{
None = 0,
AltDown = 1 << 0,
CtrlDown = 1 << 1,
ShiftDown = 1 << 2,
};
UENUM(BlueprintType)
enum class ESteamHTMLMouseButton : uint8
{
Left = 0,
Right = 1,
Middle = 2
};
UENUM(BlueprintType)
enum class ESteamMouseCursor : uint8
{
dc_user = 0,
dc_none = 1,
dc_arrow = 2,
dc_ibeam = 3,
dc_hourglass = 4,
dc_waitarrow = 5,
dc_crosshair = 6,
dc_up = 7,
dc_sizenw = 8,
dc_sizese = 9,
dc_sizene = 10,
dc_sizesw = 11,
dc_sizew = 12,
dc_sizee = 13,
dc_sizen = 14,
dc_sizes = 15,
dc_sizewe = 16,
dc_sizens = 17,
dc_sizeall = 18,
dc_no = 19,
dc_hand = 20,
dc_blank = 21,
dc_middle_pan = 22,
dc_north_pan = 23,
dc_north_east_pan = 24,
dc_east_pan = 25,
dc_south_east_pan = 26,
dc_south_pan = 27,
dc_south_west_pan = 28,
dc_west_pan = 29,
dc_north_west_pan = 30,
dc_alias = 31,
dc_cell = 32,
dc_colresize = 33,
dc_copycur = 34,
dc_verticaltext = 35,
dc_rowresize = 36,
dc_zoomin = 37,
dc_zoomout = 38,
dc_help = 39,
dc_custom = 40,
dc_last = 41
};
UENUM(BlueprintType)
enum class ESteamHTTPMethod : uint8
{
Invalid = 0,
GET = 1,
HEAD = 2,
POST = 3,
PUT = 4,
DELETE = 5,
OPTIONS = 6,
PATCH = 7
};
UENUM(BlueprintType)
namespace ESteamHTTPStatus
{
enum Type
{
e_Invalid = 0,
e_100Continue = 100,
e_101SwitchingProtocols = 101,
e_200OK = 200,
e_201Created = 201,
e_202Accepted = 202,
e_203NonAuthoritative = 203,
e_204NoContent = 204,
e_205ResetContent = 205,
e_206PartialContent = 206,
e_300MultipleChoices = 300,
e_301MovedPermanently = 301,
e_302Found = 302,
e_303SeeOther = 303,
e_304NotModified = 304,
e_305UseProxy = 305,
e_307TemporaryRedirect = 307,
e_400BadRequest = 400,
e_401Unauthorized = 401,
e_402PaymentRequired = 402,
e_403Forbidden = 403,
e_404NotFound = 404,
e_405MethodNotAllowed = 405,
e_406NotAcceptable = 406,
e_407ProxyAuthRequired = 407,
e_408RequestTimeout = 408,
e_409Conflict = 409,
e_410Gone = 410,
e_411LengthRequired = 411,
e_412PreconditionFailed = 412,
e_413RequestEntityTooLarge = 413,
e_414RequestURITooLong = 414,
e_415UnsupportedMediaType = 415,
e_416RequestedRangeNotSatisfiable = 416,
e_417ExpectationFailed = 417,
e_4xxUnknown = 418,
e_429TooManyRequests = 429,
e_500InternalServerError = 500,
e_501NotImplemented = 501,
e_502BadGateway = 502,
e_503ServiceUnavailable = 503,
e_504GatewayTimeout = 504,
e_505HTTPVersionNotSupported = 505,
e_5xxUnknown = 599
};
}
UENUM(BlueprintType)
enum class ESteamControllerSourceMode : uint8
{
None = 0,
Dpad = 1,
Buttons = 2,
FourButtons = 3,
AbsoluteMouse = 4,
RelativeMouse = 5,
JoystickMove = 6,
JoystickMouse = 7,
JoystickCamera = 8,
ScrollWheel = 9,
Trigger = 10,
TouchMenu = 11,
MouseJoystick = 12,
MouseRegion = 13,
RadialMenu = 14,
SingleButton = 15,
Switches = 16
};
UENUM(BlueprintType)
enum class ESteamInputActionOrigin : uint8
{
None,
A,
B,
X,
Y,
LeftBumper,
RightBumper,
LeftGrip,
RightGrip,
Start,
Back,
LeftPad_Touch,
LeftPad_Swipe,
LeftPad_Click,
LeftPad_DPadNorth,
LeftPad_DPadSouth,
LeftPad_DPadWest,
LeftPad_DPadEast,
RightPad_Touch,
RightPad_Swipe,
RightPad_Click,
RightPad_DPadNorth,
RightPad_DPadSouth,
RightPad_DPadWest,
RightPad_DPadEast,
LeftTrigger_Pull,
LeftTrigger_Click,
RightTrigger_Pull,
RightTrigger_Click,
LeftStick_Move,
LeftStick_Click,
LeftStick_DPadNorth,
LeftStick_DPadSouth,
LeftStick_DPadWest,
LeftStick_DPadEast,
Gyro_Move,
Gyro_Pitch,
Gyro_Yaw,
Gyro_Roll,
SteamController_Reserved0,
SteamController_Reserved1,
SteamController_Reserved2,
SteamController_Reserved3,
SteamController_Reserved4,
SteamController_Reserved5,
SteamController_Reserved6,
SteamController_Reserved7,
SteamController_Reserved8,
SteamController_Reserved9,
SteamController_Reserved10,
PS4_X,
PS4_Circle,
PS4_Triangle,
PS4_Square,
PS4_LeftBumper,
PS4_RightBumper,
PS4_Options,
PS4_Share,
PS4_LeftPad_Touch,
PS4_LeftPad_Swipe,
PS4_LeftPad_Click,
PS4_LeftPad_DPadNorth,
PS4_LeftPad_DPadSouth,
PS4_LeftPad_DPadWest,
PS4_LeftPad_DPadEast,
PS4_RightPad_Touch,
PS4_RightPad_Swipe,
PS4_RightPad_Click,
PS4_RightPad_DPadNorth,
PS4_RightPad_DPadSouth,
PS4_RightPad_DPadWest,
PS4_RightPad_DPadEast,
PS4_CenterPad_Touch,
PS4_CenterPad_Swipe,
PS4_CenterPad_Click,
PS4_CenterPad_DPadNorth,
PS4_CenterPad_DPadSouth,
PS4_CenterPad_DPadWest,
PS4_CenterPad_DPadEast,
PS4_LeftTrigger_Pull,
PS4_LeftTrigger_Click,
PS4_RightTrigger_Pull,
PS4_RightTrigger_Click,
PS4_LeftStick_Move,
PS4_LeftStick_Click,
PS4_LeftStick_DPadNorth,
PS4_LeftStick_DPadSouth,
PS4_LeftStick_DPadWest,
PS4_LeftStick_DPadEast,
PS4_RightStick_Move,
PS4_RightStick_Click,
PS4_RightStick_DPadNorth,
PS4_RightStick_DPadSouth,
PS4_RightStick_DPadWest,
PS4_RightStick_DPadEast,
PS4_DPad_North,
PS4_DPad_South,
PS4_DPad_West,
PS4_DPad_East,
PS4_Gyro_Move,
PS4_Gyro_Pitch,
PS4_Gyro_Yaw,
PS4_Gyro_Roll,
PS4_Reserved0,
PS4_Reserved1,
PS4_Reserved2,
PS4_Reserved3,
PS4_Reserved4,
PS4_Reserved5,
PS4_Reserved6,
PS4_Reserved7,
PS4_Reserved8,
PS4_Reserved9,
PS4_Reserved10,
XBoxOne_A,
XBoxOne_B,
XBoxOne_X,
XBoxOne_Y,
XBoxOne_LeftBumper,
XBoxOne_RightBumper,
XBoxOne_Menu,
XBoxOne_View,
XBoxOne_LeftTrigger_Pull,
XBoxOne_LeftTrigger_Click,
XBoxOne_RightTrigger_Pull,
XBoxOne_RightTrigger_Click,
XBoxOne_LeftStick_Move,
XBoxOne_LeftStick_Click,
XBoxOne_LeftStick_DPadNorth,
XBoxOne_LeftStick_DPadSouth,
XBoxOne_LeftStick_DPadWest,
XBoxOne_LeftStick_DPadEast,
XBoxOne_RightStick_Move,
XBoxOne_RightStick_Click,
XBoxOne_RightStick_DPadNorth,
XBoxOne_RightStick_DPadSouth,
XBoxOne_RightStick_DPadWest,
XBoxOne_RightStick_DPadEast,
XBoxOne_DPad_North,
XBoxOne_DPad_South,
XBoxOne_DPad_West,
XBoxOne_DPad_East,
XBoxOne_Reserved0,
XBoxOne_Reserved1,
XBoxOne_Reserved2,
XBoxOne_Reserved3,
XBoxOne_Reserved4,
XBoxOne_Reserved5,
XBoxOne_Reserved6,
XBoxOne_Reserved7,
XBoxOne_Reserved8,
XBoxOne_Reserved9,
XBoxOne_Reserved10,
XBox360_A,
XBox360_B,
XBox360_X,
XBox360_Y,
XBox360_LeftBumper,
XBox360_RightBumper,
XBox360_Start,
XBox360_Back,
XBox360_LeftTrigger_Pull,
XBox360_LeftTrigger_Click,
XBox360_RightTrigger_Pull,
XBox360_RightTrigger_Click,
XBox360_LeftStick_Move,
XBox360_LeftStick_Click,
XBox360_LeftStick_DPadNorth,
XBox360_LeftStick_DPadSouth,
XBox360_LeftStick_DPadWest,
XBox360_LeftStick_DPadEast,
XBox360_RightStick_Move,
XBox360_RightStick_Click,
XBox360_RightStick_DPadNorth,
XBox360_RightStick_DPadSouth,
XBox360_RightStick_DPadWest,
XBox360_RightStick_DPadEast,
XBox360_DPad_North,
XBox360_DPad_South,
XBox360_DPad_West,
XBox360_DPad_East,
XBox360_Reserved0,
XBox360_Reserved1,
XBox360_Reserved2,
XBox360_Reserved3,
XBox360_Reserved4,
XBox360_Reserved5,
XBox360_Reserved6,
XBox360_Reserved7,
XBox360_Reserved8,
XBox360_Reserved9,
XBox360_Reserved10,
Switch_A,
Switch_B,
Switch_X,
Switch_Y,
Switch_LeftBumper,
Switch_RightBumper,
Switch_Plus,
Switch_Minus,
Switch_Capture,
Switch_LeftTrigger_Pull,
Switch_LeftTrigger_Click,
Switch_RightTrigger_Pull,
Switch_RightTrigger_Click,
Switch_LeftStick_Move,
Switch_LeftStick_Click,
Switch_LeftStick_DPadNorth,
Switch_LeftStick_DPadSouth,
Switch_LeftStick_DPadWest,
Switch_LeftStick_DPadEast,
Switch_RightStick_Move,
Switch_RightStick_Click,
Switch_RightStick_DPadNorth,
Switch_RightStick_DPadSouth,
Switch_RightStick_DPadWest,
Switch_RightStick_DPadEast,
Switch_DPad_North,
Switch_DPad_South,
Switch_DPad_West,
Switch_DPad_East,
SwitchProGyro_Move,
SwitchProGyro_Pitch,
SwitchProGyro_Yaw,
SwitchProGyro_Roll,
Switch_Reserved0,
Switch_Reserved1,
Switch_Reserved2,
Switch_Reserved3,
Switch_Reserved4,
Switch_Reserved5,
Switch_Reserved6,
Switch_Reserved7,
Switch_Reserved8,
Switch_Reserved9,
Switch_Reserved10,
Count
};
// Added the _ since Steam actually has this enum already and we need it accessible in BP
UENUM(BlueprintType)
enum class ESteamInputType_ : uint8
{
Unknown = 0,
SteamController = 1,
XBox360Controller = 2,
XBoxOneController = 3,
GenericXInput = 4,
PS4Controller = 5,
AppleMFiController = 6,
AndroidController = 7,
SwitchJoyConPair = 8,
SwitchJoyConSingle = 9,
SwitchProController = 10,
MobileTouch = 11,
PS3Controller = 12,
Count = 13,
};
// Added the _ since Steam actually has this enum already and we need it accessible in BP
UENUM(BlueprintType)
enum class ESteamControllerLEDFlag_ : uint8
{
SetColor = 0,
RestoreUserDefault = 1
};
// Added the _ since Steam actually has this enum already and we need it accessible in BP
UENUM(BlueprintType)
enum class ESteamControllerPad_ : uint8
{
Left = 0,
Right = 1
};
UENUM(BlueprintType)
enum class ESteamXboxOrigin : uint8
{
A,
B,
X,
Y,
LeftBumper,
RightBumper,
Menu, //Start
View, //Back
LeftTrigger_Pull,
LeftTrigger_Click,
RightTrigger_Pull,
RightTrigger_Click,
LeftStick_Move,
LeftStick_Click,
LeftStick_DPadNorth,
LeftStick_DPadSouth,
LeftStick_DPadWest,
LeftStick_DPadEast,
RightStick_Move,
RightStick_Click,
RightStick_DPadNorth,
RightStick_DPadSouth,
RightStick_DPadWest,
RightStick_DPadEast,
DPad_North,
DPad_South,
DPad_West,
DPad_East,
Count,
};
// Added the _ since Steam actually has this enum already and we need it accessible in BP
UENUM(BlueprintType)
enum class ESteamItemFlags_ : uint8
{
NoTrade = 0,
ItemRemoved = 8,
ItemConsumed = 9,
};
UENUM(BlueprintType)
enum class ESteamFavoriteFlags : uint8
{
None = 0 UMETA(DisplayName = "None"),
Favorite = 1 UMETA(DisplayName = "Favorite"),
History = 2 UMETA(DisplayName = "History"),
};
UENUM(BlueprintType)
enum class ESteamLobbyDistanceFilter : uint8
{
Close = 0,
Default = 1,
Far = 2,
Worldwide = 3
};
UENUM(BlueprintType)
enum class ESteamLobbyComparison : uint8
{
EqualToOrLessThan = 0,
LessThan = 1,
Equal = 2,
GreaterThan = 3,
EqualToOrGreaterThan = 4,
NotEqual = 5
};
UENUM(BlueprintType)
enum class ESteamLobbyType : uint8
{
Private = 0 UMETA(DisplayName = "Private"),
FriendsOnly = 1 UMETA(DisplayName = "FriendsOnly"),
Public = 2 UMETA(DisplayName = "Public"),
Invisible = 3 UMETA(DisplayName = "Invisible"),
};
UENUM(BlueprintType)
enum class ESteamChatMemberStateChange : uint8
{
Entered = 0 UMETA(DisplayName = "Entered"),
Left = 1 UMETA(DisplayName = "Left"),
Disconnected = 2 UMETA(DisplayName = "Disconnected"),
Kicked = 3 UMETA(DisplayName = "Kicked"),
Banned = 4 UMETA(DisplayName = "Banned")
};
UENUM(BlueprintType)
enum class ESteamAudioPlaybackStatus : uint8
{
Undefined = 0,
Playing = 1,
Paused = 2,
Idle = 3
};
UENUM(BlueprintType)
enum class ESteamPartyBeaconLocation : uint8
{
Invalid = 0,
ChatGroup = 1,
Max
};
// Added the _ since Steam actually has this enum already and we need it accessible in BP
UENUM(BlueprintType)
enum class ESteamPartyBeaconLocationData_ : uint8
{
Invalid = 0,
Name = 1,
IconURLSmall = 2,
IconURLMedium = 3,
IconURLLarge = 4,
};
// Added the _ since Steam actually has this enum already and we need it accessible in BP
UENUM(BlueprintType)
enum class ESteamDeviceFormFactor_ : uint8
{
Unknown = 0,
Phone = 1,
Tablet = 2,
Computer = 3,
TV = 4,
};
UENUM(BlueprintType)
enum class ESteamAPICallFailure_ : uint8
{
None = 0, // no failure
SteamGone = 1, // the local Steam process has gone away
NetworkFailure = 2, // the network connection to Steam has been broken, or was already broken
InvalidHandle = 3, // the SteamAPICall_t handle passed in no longer exists
MismatchedCallback = 4, // GetAPICallResult() was called with the wrong callback type for this API call
};
UENUM(BlueprintType)
enum class ESteamUniverse : uint8
{
Invalid = 0,
Public = 1,
Beta = 2,
Internal = 3,
Dev = 4,
Max
};
UENUM(BlueprintType)
enum class ESteamTextFilteringContext : uint8
{
Unknown = 0,
GameContent = 1,
Chat = 2,
Name = 3
};
UENUM(BlueprintType)
enum class ESteamNotificationPosition : uint8
{
TopLeft = 0,
TopRight = 1,
BottomLeft = 2,
BottomRight = 3,
};
UENUM(BlueprintType)
enum class ESteamGamepadTextInputMode : uint8
{
Normal = 0,
Password = 1
};
UENUM(BlueprintType)
enum class ESteamGamepadTextInputLineMode : uint8
{
SingleLine = 0,
MultipleLines = 1
};
UENUM(BlueprintType)
enum class ESteamLeaderboardDataRequest : uint8
{
Global = 0,
GlobalAroundUser = 1,
Friends = 2,
Users = 3
};
// the sort order of a leaderboard
UENUM(BlueprintType)
enum class ESteamLeaderboardSortMethod : uint8
{
None = 0,
Ascending = 1, // top-score is lowest number
Descending = 2, // top-score is highest number
};
// the display type (used by the Steam Community web site) for a leaderboard
UENUM(BlueprintType)
enum class ESteamLeaderboardDisplayType : uint8
{
None = 0,
Numeric = 1, // simple numerical score
TimeSeconds = 2, // the score represents a time, in seconds
TimeMilliSeconds = 3, // the score represents a time, in milliseconds
};
UENUM(BlueprintType)
enum class ESteamLeaderboardUploadScoreMethod : uint8
{
None = 0,
KeepBest = 1, // Leaderboard will keep user's best score
ForceUpdate = 2, // Leaderboard will always replace score with specified
};
UENUM(BlueprintType)
enum class ESteamRemoteStoragePlatform : uint8
{
Windows = 0 UMETA(DisplayName = "Windows"),
OSX = 1 UMETA(DisplayName = "OSX"),
PS3 = 2 UMETA(DisplayName = "PS3"),
Linux = 3 UMETA(DisplayName = "Linux"),
Reserved = 4 UMETA(DisplayName = "Reserved"),
All = 5 UMETA(DisplayName = "All")
};
UENUM(BlueprintType)
enum class ESteamVRScreenshotType : uint8
{
None = 0,
Mono = 1,
Stereo = 2,
MonoCubemap = 3,
MonoPanorama = 4,
StereoPanorama = 5
};
UENUM(BlueprintType)
enum class ESteamItemPreviewType : uint8
{
Image = 0, // standard image file expected (e.g. jpg, png, gif, etc.)
YouTubeVideo = 1, // video id is stored
Sketchfab = 2, // model id is stored
EnvironmentMap_HorizontalCross = 3, // standard image file expected - cube map in the layout
EnvironmentMap_LatLong = 4, // standard image file expected
ReservedMax = 255, // you can specify your own types above this value
};
UENUM(BlueprintType)
enum class ESteamWorkshopFileType : uint8
{
First = 0,
Community = 0, // normal Workshop item that can be subscribed to
Microtransaction = 1, // Workshop item that is meant to be voted on for the purpose of selling in-game
Collection = 2, // a collection of Workshop or Greenlight items
Art = 3, // artwork
Video = 4, // external video
Screenshot = 5, // screenshot
Game = 6, // Greenlight game entry
Software = 7, // Greenlight software entry
Concept = 8, // Greenlight concept
WebGuide = 9, // Steam web guide
IntegratedGuide = 10, // application integrated guide
Merch = 11, // Workshop merchandise meant to be voted on for the purpose of being sold
ControllerBinding = 12, // Steam Controller bindings
SteamworksAccessInvite = 13, // internal
SteamVideo = 14, // Steam video
GameManagedItem = 15, // managed completely by the game, not the user, and not shown on the web
// Update k_EWorkshopFileTypeMax if you add values.
Max = 16
};
UENUM(BlueprintType)
enum class ESteamUGCQuery : uint8
{
RankedByVote = 0,
RankedByPublicationDate = 1,
AcceptedForGameRankedByAcceptanceDate = 2,
RankedByTrend = 3,
FavoritedByFriendsRankedByPublicationDate = 4,
CreatedByFriendsRankedByPublicationDate = 5,
RankedByNumTimesReported = 6,
CreatedByFollowedUsersRankedByPublicationDate = 7,
NotYetRated = 8,
RankedByTotalVotesAsc = 9,
RankedByVotesUp = 10,
RankedByTextSearch = 11,
RankedByTotalUniqueSubscriptions = 12,
RankedByPlaytimeTrend = 13,
RankedByTotalPlaytime = 14,
RankedByAveragePlaytimeTrend = 15,
RankedByLifetimeAveragePlaytime = 16,
RankedByPlaytimeSessionsTrend = 17,
RankedByLifetimePlaytimeSessions = 18,
};
UENUM(BlueprintType)
enum class ESteamUGCMatchingUGCType : uint8
{
Items = 0, // both mtx items and ready-to-use items
Items_Mtx = 1,
Items_ReadyToUse = 2,
Collections = 3,
Artwork = 4,
Videos = 5,
Screenshots = 6,
AllGuides = 7, // both web guides and integrated guides
WebGuides = 8,
IntegratedGuides = 9,
UsableInGame = 10, // ready-to-use items and integrated guides
ControllerBindings = 11,
GameManagedItems = 12, // game managed items (not managed by users)
All = 254, // @note: will only be valid for CreateQueryUserUGCRequest requests
};
UENUM(BlueprintType)
enum class ESteamUserUGCList : uint8
{
Published,
VotedOn,
VotedUp,
VotedDown,
WillVoteLater,
Favorited,
Subscribed,
UsedOrPlayed,
Followed,
};
UENUM(BlueprintType)
enum class ESteamUserUGCListSortOrder : uint8
{
CreationOrderDesc,
CreationOrderAsc,
TitleAsc,
LastUpdatedDesc,
SubscriptionDateDesc,
VoteScoreDesc,
ForModeration,
};
UENUM(BlueprintType)
enum class ESteamItemUpdateStatus : uint8
{
Invalid = 0, // The item update handle was invalid, job might be finished, listen too SubmitItemUpdateResult_t
PreparingConfig = 1, // The item update is processing configuration data
PreparingContent = 2, // The item update is reading and processing content files
UploadingContent = 3, // The item update is uploading content changes to Steam
UploadingPreviewFile = 4, // The item update is uploading new preview file image
CommittingChanges = 5 // The item update is committing all changes
};
UENUM(BlueprintType)
enum class ESteamRemoteStoragePublishedFileVisibility : uint8
{
Public = 0,
FriendsOnly = 1,
Private = 2,
};
UENUM(BlueprintType)
enum class ESteamItemStatistic : uint8
{
NumSubscriptions = 0,
NumFavorites = 1,
NumFollowers = 2,
NumUniqueSubscriptions = 3,
NumUniqueFavorites = 4,
NumUniqueFollowers = 5,
NumUniqueWebsiteViews = 6,
ReportScore = 7,
NumSecondsPlayed = 8,
NumPlaytimeSessions = 9,
NumComments = 10,
NumSecondsPlayedDuringTimePeriod = 11,
NumPlaytimeSessionsDuringTimePeriod = 12,
};
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool comp(int i, int j){
return i > j;
}
int main(){
int n, k, num, sum = 0;
cin >> n >> k;
vector<int> v1;
vector<int> v2;
for(int a = 0; a < n; a++){
cin >> num;
v1.push_back(num);
}
for(int a = 0; a < n; a++){
cin >> num;
v2.push_back(num);
}
/*v1은 오름차순, v2는 내림차순으로 정렬해
v2는 가장 앞 k개를 , v1은 가장 뒤 k개를
선택해 sum에 더해준다.*/
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end(), comp);
for(int a = k; a < v1.size(); a++){
sum += v1[a];
}
for(int a = 0; a < k; a++){
sum += v2[a];
}
cout << sum << endl;
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
for(int k = 1; k <= t; k ++){
int n;
cin >> n;
string in, out;
cin >> in >> out;
vector<vector<int>>adj(n, vector<int>(n, 0));
vector<int>graph[n];
for(int i = 0; i < n; i ++){
for(int j = i - 1; j <= (i + 1); j ++){
if(j < 0 && j >= n) continue;
if(i == j){
adj[i][j] = 1;
continue;
}
if(abs(i-j) == 1){
if(out[i] == 'Y' && in[j] == 'Y'){
adj[i][j] = 1;
graph[i].push_back(j);
}
}
}
}
queue<int>q;
vector<bool>isvisited(n, false);
for(int i = 0; i < n; i ++){
q.push(i);
isvisited[i] = true;
while(!q.empty()){
int u = q.front(); q.pop();
for(int v : graph[u]){
if(!isvisited[v]){
q.push(v);
isvisited[v] = true;
}
}
}
for(int j = 0; j < n; j ++){
if(isvisited[j]) adj[i][j] = 1;
}
isvisited.assign(n, false);
}
cout << "Case #" << k << ":\n";
for(int i = 0; i < n; i ++){
for(int j = 0; j < n; j ++){
if(adj[i][j]) cout << "Y";
else cout << "N";
}
cout << "\n";
}
}
return 0;
}
|
#pragma once
#include <string>
#include <map>
#include <clang/Basic/SourceLocation.h>
// FIXME
using namespace clang;
struct ClassInfo {
SourceLocation loc;
std::string locStr;
std::string diagName;
ClassInfo(SourceLocation loc, std::string&& locStr, std::string&& diagName) :
loc(loc), locStr(std::move(locStr)), diagName(std::move(diagName))
{}
};
// Holds the number of private or protected variables, methods, types
// in a class.
struct ClassCounts {
int privateVarsCount = 0;
int privateMethodsCount = 0;
int privateTypesCount = 0;
std::shared_ptr<ClassInfo> info;
};
struct Result {
// Number of friend decls which refer to a class or class template
int friendClassDeclCount = 0;
// Number of friend decls which refer to a function or function template
int friendFuncDeclCount = 0;
struct FuncResult {
std::string diagName;
SourceLocation friendDeclLoc; // The location of the friend declaration
std::string friendDeclLocStr;
SourceLocation defLoc; // The location of the definition of the friend
std::string defLocStr;
// Below the static variables and static methods are counted in as well.
// The number of used variables in this (friend) function
int usedPrivateVarsCount = 0;
// The number of priv/protected variables
// in this (friend) function's referred class.
int parentPrivateVarsCount = 0;
// The number of used methods in this (friend) function
int usedPrivateMethodsCount = 0;
// The number of priv/protected methods
// in this (friend) function's referred class.
int parentPrivateMethodsCount = 0;
struct Types {
// The number of used types in this (friend) function
int usedPrivateCount = 0;
// The number of priv/protected types
// in this (friend) function's referred class.
int parentPrivateCount = 0;
} types;
std::shared_ptr<ClassInfo> parentClassInfo;
};
// Each friend funciton declaration might have it's connected function
// definition.
// We collect statistics only on friend functions and friend function
// templates with body (i.e if they have the definition provided).
// Each friend function template could have different specializations with
// their own definition.
using FriendDeclId = std::string;
using BefriendingClassInstantiationId = std::string;
using FunctionTemplateInstantiationId = std::string;
using FuncResultKey = std::pair<BefriendingClassInstantiationId,
FunctionTemplateInstantiationId>;
using FuncResultsForFriendDecl =
std::map<FuncResultKey, FuncResult>;
std::map<FriendDeclId, FuncResultsForFriendDecl> FuncResults;
struct ClassResult {
std::string diagName;
std::string defLocStr;
std::string friendDeclLocStr;
FuncResultsForFriendDecl memberFuncResults;
};
// Each friend class template could have different specializations or
// instantiations. We handle one non-template class exactly the same as it was
// an instantiation/specialization of a class template. We collect statistics
// from every member functions of such records(class template inst/spec or
// non-template class). Also we collect stats from member function templates.
// We do this exactly the same as we do it with direct friend functions and
// function templates.
using ClassTemplateInstantiationId = std::string;
using ClassResultKey = std::pair<BefriendingClassInstantiationId,
ClassTemplateInstantiationId>;
using ClassResultsForFriendDecl =
std::map<ClassResultKey, ClassResult>;
std::map<FriendDeclId, ClassResultsForFriendDecl> ClassResults;
};
|
/*
* Point.h
*
* Created on: May 17, 2017
* Author: muhammadhassnain
*/
#ifndef POINT_H_
#define POINT_H_
class Point {
int x;
int y;
public:
Point(int=-1,int=-1);
int getX();
int getY();
float distance(Point);
void setPoint(int,int);
bool operator==(Point);
};
#endif /* POINT_H_ */
|
/*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE 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 ANY
- 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.
*====================================================================*/
/*
* webpio.c
*
* Reading WebP
* PIX *pixReadStreamWebP()
* PIX *pixReadMemWebP()
*
* Reading WebP header
* l_int32 readHeaderWebP()
* l_int32 readHeaderMemWebP()
*
* Writing WebP
* l_int32 pixWriteWebP() [ special top level ]
* l_int32 pixWriteStreamWebP()
* l_int32 pixWriteMemWebP()
*/
#include "allheaders.h"
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif /* HAVE_CONFIG_H */
/* --------------------------------------------*/
#if HAVE_LIBWEBP /* defined in environ.h */
/* --------------------------------------------*/
#include "webp/decode.h"
#include "webp/encode.h"
/*---------------------------------------------------------------------*
* Reading WebP *
*---------------------------------------------------------------------*/
/*!
* pixReadStreamWebP()
*
* Input: stream corresponding to WebP image
* Return: pix (32 bpp), or null on error
*/
PIX *
pixReadStreamWebP(FILE *fp)
{
l_uint8 *filedata;
size_t filesize;
PIX *pix;
PROCNAME("pixReadStreamWebP");
if (!fp)
{
return (PIX *)ERROR_PTR("fp not defined", procName, NULL);
}
/* Read data from file and decode into Y,U,V arrays */
rewind(fp);
if ((filedata = l_binaryReadStream(fp, &filesize)) == NULL)
{
return (PIX *)ERROR_PTR("filedata not read", procName, NULL);
}
pix = pixReadMemWebP(filedata, filesize);
FREE(filedata);
return pix;
}
/*!
* pixReadMemWebP()
*
* Input: filedata (webp compressed data in memory)
* filesize (number of bytes in data)
* Return: pix (32 bpp), or null on error
*
* Notes:
* (1) When the encoded data only has 3 channels (no alpha),
* WebPDecodeRGBAInto() generates a raster of 32-bit pixels, with
* the alpha channel set to opaque (255).
* (2) We don't need to use the gnu runtime functions like fmemopen()
* for redirecting data from a stream to memory, because
* the webp library has been written with memory-to-memory
* functions at the lowest level (which is good!). And, in
* any event, fmemopen() doesn't work with l_binaryReadStream().
*/
PIX *
pixReadMemWebP(const l_uint8 *filedata,
size_t filesize)
{
l_uint8 *out = NULL;
l_int32 w, h, has_alpha, wpl, stride;
l_uint32 *data;
size_t size;
PIX *pix;
WebPBitstreamFeatures features;
PROCNAME("pixReadMemWebP");
if (!filedata)
{
return (PIX *)ERROR_PTR("filedata not defined", procName, NULL);
}
if (WebPGetFeatures(filedata, filesize, &features))
{
return (PIX *)ERROR_PTR("Invalid WebP file", procName, NULL);
}
w = features.width;
h = features.height;
has_alpha = features.has_alpha;
/* Write from compressed Y,U,V arrays to pix raster data */
pix = pixCreate(w, h, 32);
if (has_alpha)
{
pixSetSpp(pix, 4);
}
data = pixGetData(pix);
wpl = pixGetWpl(pix);
stride = wpl * 4;
size = stride * h;
out = WebPDecodeRGBAInto(filedata, filesize, (uint8_t *)data, size,
stride);
if (out == NULL) /* error: out should also point to data */
{
pixDestroy(&pix);
return (PIX *)ERROR_PTR("WebP decode failed", procName, NULL);
}
/* WebP decoder emits opposite byte order for RGBA components */
pixEndianByteSwap(pix);
return pix;
}
/*!
* readHeaderWebP()
*
* Input: filename
* &w (<return> width)
* &h (<return> height)
* &spp (<return> spp (3 or 4))
* Return: 0 if OK, 1 on error
*/
l_int32
readHeaderWebP(const char *filename,
l_int32 *pw,
l_int32 *ph,
l_int32 *pspp)
{
l_uint8 data[100]; /* expect size info within the first 50 bytes or so */
l_int32 nbytes, bytesread;
size_t filesize;
FILE *fp;
PROCNAME("readHeaderWebP");
if (!pw || !ph || !pspp)
{
return ERROR_INT("input ptr(s) not defined", procName, 1);
}
*pw = *ph = *pspp = 0;
if (!filename)
{
return ERROR_INT("filename not defined", procName, 1);
}
/* Read no more than 100 bytes from the file */
if ((filesize = nbytesInFile(filename)) == 0)
{
return ERROR_INT("no file size found", procName, 1);
}
if (filesize < 100)
{
L_WARNING("very small webp file\n", procName);
}
nbytes = L_MIN(filesize, 100);
if ((fp = fopenReadStream(filename)) == NULL)
{
return ERROR_INT("image file not found", procName, 1);
}
bytesread = fread((char *)data, 1, nbytes, fp);
fclose(fp);
if (bytesread != nbytes)
{
return ERROR_INT("failed to read requested data", procName, 1);
}
return readHeaderMemWebP(data, nbytes, pw, ph, pspp);
}
/*!
* readHeaderMemWebP()
*
* Input: data
* size (100 bytes is sufficient)
* &w (<return> width)
* &h (<return> height)
* &spp (<return> spp (3 or 4))
* Return: 0 if OK, 1 on error
*/
l_int32
readHeaderMemWebP(const l_uint8 *data,
size_t size,
l_int32 *pw,
l_int32 *ph,
l_int32 *pspp)
{
WebPBitstreamFeatures features;
PROCNAME("readHeaderWebP");
if (pw)
{
*pw = 0;
}
if (ph)
{
*ph = 0;
}
if (pspp)
{
*pspp = 0;
}
if (!data)
{
return ERROR_INT("data not defined", procName, 1);
}
if (!pw || !ph || !pspp)
{
return ERROR_INT("input ptr(s) not defined", procName, 1);
}
if (WebPGetFeatures(data, (l_int32)size, &features))
{
return ERROR_INT("invalid WebP file", procName, 1);
}
*pw = features.width;
*ph = features.height;
*pspp = (features.has_alpha) ? 4 : 3;
return 0;
}
/*---------------------------------------------------------------------*
* Writing WebP *
*---------------------------------------------------------------------*/
/*!
* pixWriteWebP()
*
* Input: filename
* pixs
* quality (0 - 100; default ~80)
* lossless (use 1 for lossless; 0 for lossy)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) Special top-level function allowing specification of quality.
*/
l_int32
pixWriteWebP(const char *filename,
PIX *pixs,
l_int32 quality,
l_int32 lossless)
{
FILE *fp;
PROCNAME("pixWriteWebP");
if (!pixs)
{
return ERROR_INT("pixs not defined", procName, 1);
}
if (!filename)
{
return ERROR_INT("filename not defined", procName, 1);
}
if ((fp = fopenWriteStream(filename, "wb+")) == NULL)
{
return ERROR_INT("stream not opened", procName, 1);
}
if (pixWriteStreamWebP(fp, pixs, quality, lossless) != 0)
{
fclose(fp);
return ERROR_INT("pixs not compressed to stream", procName, 1);
}
fclose(fp);
return 0;
}
/*!
* pixWriteStreampWebP()
*
* Input: stream
* pixs (all depths)
* quality (0 - 100; default ~80)
* lossless (use 1 for lossless; 0 for lossy)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) See pixWriteMemWebP() for details.
* (2) Use 'free', and not leptonica's 'FREE', for all heap data
* that is returned from the WebP library.
*/
l_int32
pixWriteStreamWebP(FILE *fp,
PIX *pixs,
l_int32 quality,
l_int32 lossless)
{
l_uint8 *filedata;
size_t filebytes, nbytes;
PROCNAME("pixWriteStreamWebP");
if (!fp)
{
return ERROR_INT("stream not open", procName, 1);
}
if (!pixs)
{
return ERROR_INT("pixs not defined", procName, 1);
}
pixWriteMemWebP(&filedata, &filebytes, pixs, quality, lossless);
rewind(fp);
nbytes = fwrite(filedata, 1, filebytes, fp);
free(filedata);
if (nbytes != filebytes)
{
return ERROR_INT("Write error", procName, 1);
}
return 0;
}
/*!
* pixWriteMemWebP()
*
* Input: &encdata (<return> webp encoded data of pixs)
* &encsize (<return> size of webp encoded data)
* pixs (any depth, cmapped OK)
* quality (0 - 100; default ~80)
* lossless (use 1 for lossless; 0 for lossy)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) Lossless and lossy encoding are entirely different in webp.
* @quality applies to lossy, and is ignored for lossless.
* (2) The input image is converted to RGB if necessary. If spp == 3,
* we set the alpha channel to fully opaque (255), and
* WebPEncodeRGBA() then removes the alpha chunk when encoding,
* setting the internal header field has_alpha to 0.
*/
l_int32
pixWriteMemWebP(l_uint8 **pencdata,
size_t *pencsize,
PIX *pixs,
l_int32 quality,
l_int32 lossless)
{
l_int32 w, h, d, wpl, stride;
l_uint32 *data;
PIX *pix1, *pix2;
PROCNAME("pixWriteMemWebP");
if (!pencdata)
{
return ERROR_INT("&encdata not defined", procName, 1);
}
*pencdata = NULL;
if (!pencsize)
{
return ERROR_INT("&encsize not defined", procName, 1);
}
*pencsize = 0;
if (!pixs)
{
return ERROR_INT("&pixs not defined", procName, 1);
}
if (lossless == 0 && (quality < 0 || quality > 100))
{
return ERROR_INT("quality not in [0 ... 100]", procName, 1);
}
if ((pix1 = pixRemoveColormap(pixs, REMOVE_CMAP_TO_FULL_COLOR)) == NULL)
{
return ERROR_INT("failure to remove color map", procName, 1);
}
/* Convert to rgb if not 32 bpp; pix2 must not be a clone of pixs. */
if (pixGetDepth(pix1) != 32)
{
pix2 = pixConvertTo32(pix1);
}
else
{
pix2 = pixCopy(NULL, pix1);
}
pixDestroy(&pix1);
pixGetDimensions(pix2, &w, &h, &d);
if (w <= 0 || h <= 0 || d != 32)
{
pixDestroy(&pix2);
return ERROR_INT("pix2 not 32 bpp or of 0 size", procName, 1);
}
/* If spp == 3, need to set alpha layer to opaque (all 1s). */
if (pixGetSpp(pix2) == 3)
{
pixSetComponentArbitrary(pix2, L_ALPHA_CHANNEL, 255);
}
/* Webp encoder assumes big-endian byte order for RGBA components */
pixEndianByteSwap(pix2);
wpl = pixGetWpl(pix2);
data = pixGetData(pix2);
stride = wpl * 4;
if (lossless)
{
*pencsize = WebPEncodeLosslessRGBA((uint8_t *)data, w, h,
stride, pencdata);
}
else
{
*pencsize = WebPEncodeRGBA((uint8_t *)data, w, h, stride,
quality, pencdata);
}
pixDestroy(&pix2);
if (*pencsize == 0)
{
free(pencdata);
*pencdata = NULL;
return ERROR_INT("webp encoding failed", procName, 1);
}
return 0;
}
/* --------------------------------------------*/
#endif /* HAVE_LIBWEBP */
/* --------------------------------------------*/
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Gaming.UI.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_c50898f6_c536_5f47_8583_8b2c2438a13b
#define WINRT_GENERIC_c50898f6_c536_5f47_8583_8b2c2438a13b
template <> struct __declspec(uuid("c50898f6-c536-5f47-8583-8b2c2438a13b")) __declspec(novtable) EventHandler<Windows::Foundation::IInspectable> : impl_EventHandler<Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_fe4f13bf_689c_5fe3_b7ad_55bc57f92466
#define WINRT_GENERIC_fe4f13bf_689c_5fe3_b7ad_55bc57f92466
template <> struct __declspec(uuid("fe4f13bf-689c-5fe3-b7ad-55bc57f92466")) __declspec(novtable) TypedEventHandler<Windows::Gaming::UI::GameChatOverlayMessageSource, Windows::Gaming::UI::GameChatMessageReceivedEventArgs> : impl_TypedEventHandler<Windows::Gaming::UI::GameChatOverlayMessageSource, Windows::Gaming::UI::GameChatMessageReceivedEventArgs> {};
#endif
}
namespace Windows::Gaming::UI {
struct IGameBarStatics :
Windows::Foundation::IInspectable,
impl::consume<IGameBarStatics>
{
IGameBarStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IGameChatMessageReceivedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IGameChatMessageReceivedEventArgs>
{
IGameChatMessageReceivedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IGameChatOverlay :
Windows::Foundation::IInspectable,
impl::consume<IGameChatOverlay>
{
IGameChatOverlay(std::nullptr_t = nullptr) noexcept {}
};
struct IGameChatOverlayMessageSource :
Windows::Foundation::IInspectable,
impl::consume<IGameChatOverlayMessageSource>
{
IGameChatOverlayMessageSource(std::nullptr_t = nullptr) noexcept {}
};
struct IGameChatOverlayStatics :
Windows::Foundation::IInspectable,
impl::consume<IGameChatOverlayStatics>
{
IGameChatOverlayStatics(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
#ifndef PARSERCONFIG_H
#define PARSERCONFIG_H
#include <QObject>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
class ParserConfig
{
public:
ParserConfig();
public slots:
QString GetParam(QByteArray, QString);
QVariant GetParamStandby(QByteArray, QString);
int GetRequestInteraval(QByteArray);
private:
QString buf;
};
#endif // PARSERCONFIG_H
|
#ifndef _AUTOCALL_YIELDNOTE_LEAST_PERFORM_PAYOFF_H_
#define _AUTOCALL_YIELDNOTE_LEAST_PERFORM_PAYOFF_H_
#include "multiasset_autocall_payoff.h"
#include "cpn_freq.h"
#include <vector>
class ACYNLeastPerformPayoff: public MAACPayoff {
public:
/* Constructors and destructor */
ACYNLeastPerformPayoff();
ACYNLeastPerformPayoff(double principal, double cpnRate, CouponFreq freq,
double trigger, double maturity, std::vector<double> ACSchedule);
~ACYNLeastPerformPayoff();
virtual double operator()(std::vector<double> spot, double t);
private:
double mPrincipal;
double mCoupon;
double mCpnRate;
CouponFreq mFreq;
};
struct Compare {
double trigger;
Compare(double const &value): trigger(value) { }
bool operator()(double const i) {
return (i < trigger);
}
};
#endif
|
/*
* This program is to demonstrate basic to class type conversion.
*/
#include<iostream> // Header
using namespace std;
class Vector { // Vector class
public:
Vector():x{0},y{0}{} // Default constructor.
Vector(int a){ // Constructor with one parameter, which work as basic to class type converter.
x=y=a;
}
Vector(int a,int b){ // Constructor with one parameter, which work as basic to class type converter.
x=a; y=b;
}
void print(){ // Print values of vector object.
cout<<endl<<"Values of vector : ("<<x<<","<<y<<")\n";
}
void operator=(int a){ // Basic to class type converesion using operator overloading.
x=y=a;
}
private:
int x,y;
};
int main(){
Vector v1(5); // Declaring object using basic to class type conversion.
Vector v2(2,6); // Declaring object using basic to class type convesion.
Vector v3; // Declaring object.
v3=7; // assigning values in vector object using basic to class type conversion.
cout<<"Printing vectors.\n";
v1.print();
v2.print();
v3.print();
return 0;
}
|
#pragma once
#include <exception>
#include <string>
#include <vector>
typedef unsigned int uint;
typedef unsigned char uchar;
class WorldException : public std::exception {
std::string mReason;
public:
WorldException(std::string reason) : mReason(reason) {}
const char *what() const noexcept override {return mReason.c_str();}
};
std::string StringPrintf(const std::string fmt, ...);
template <class Ptr>
struct LessPtr {
int operator()(const Ptr &a, const Ptr &b) const { return *a < *b;}
};
std::vector<std::string> Split(const std::string& s, char delimiter);
|
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10); // CE, CSN
const byte address[6] = "00001";
char datos[4];
void setup() {
radio.begin();
Serial.begin(115200);
//Abrimos un canal de escritura
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();
}
void loop() {
if (Serial.available()){
datos[0] = Serial.read();
Serial.flush();
//cargamos los datos en la variable datos[]
//enviamos los datos
bool ok = radio.write(datos, sizeof(datos));
}
}
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m;
cin>>n>>m;
int a[n], mn = n, ans = 0;
memset(a, -1, sizeof(a));
for(int i=0; i<m; i++)
{
int v;
cin>>v;
a[v] = 0;
mn = min(mn, v);
}
for(int i=mn+1; i<n; i++)
{
if(a[i]==-1) a[i] = a[i-1]+1;
}
for(int i=n-2; i>=0; i--)
{
if(a[i]==-1) a[i] = a[i+1]+1;
else a[i] = min(a[i], a[i+1]+1);
}
for(int i=0; i<n; i++) ans = max(ans, a[i]);
cout<<ans<<endl;
}
|
#include "ARCH.h"
#include <intrin.h>
namespace ARCH {
unsigned long long GetCR3(void)
{
return __readcr3();
}
unsigned long long ReadMsr(unsigned long msrId)
{
return __readmsr(msrId);
}
void WriteMsr(unsigned long msrId, unsigned long long value)
{
__writemsr(msrId, value);
}
unsigned long GetCpuCount()
{
return KeGetCurrentProcessorNumber();
}
unsigned long long GetProcessCr3(unsigned int pid)
{
UINT64 CurrentCr3 = 0;
PEPROCESS proceses = nullptr;
if (PsLookupProcessByProcessId((PVOID)pid, &proceses) == STATUS_SUCCESS)
{
//todo add specific windows version checks and hardcode offsets/ or use scans
if (GetCR3() & 0xfff)
{
DbgPrint("Split kernel/usermode pages\n");
//uses supervisor/usermode pagemaps
CurrentCr3 = *(UINT64*)((UINT_PTR)proceses + 0x278);
if ((CurrentCr3 & 0xfffffffffffff000ULL) == 0)
{
DbgPrint("No usermode CR3\n");
CurrentCr3 = *(UINT64*)((UINT_PTR)proceses + 0x28);
}
DbgPrint("CurrentCR3=%llx\n", CurrentCr3);
}
else
{
KAPC_STATE apc_state;
RtlZeroMemory(&apc_state, sizeof(apc_state));
__try
{
KeStackAttachProcess((PRKPROCESS)proceses, &apc_state);
CurrentCr3 = GetCR3();
KeUnstackDetachProcess(&apc_state);
}
__except (1)
{
DbgPrint("Failure getting CR3 for this process");
ObDereferenceObject(proceses);
return 0;
}
}
ObDereferenceObject(proceses);
}
else
{
DbgPrint("Failure getting the EProcess for pid %d", pid);
return 0;
}
return CurrentCr3;
}
VOID DpcDelegate(
_In_ struct _KDPC* Dpc,
_In_opt_ PVOID DeferredContext,
_In_opt_ PVOID SystemArgument1,
_In_opt_ PVOID SystemArgument2
)
{
Dpc = Dpc;
SystemArgument2 = SystemArgument2;
auto func = (CpuCallBack)DeferredContext;
func(SystemArgument1);
}
void ForEachCpu(CpuCallBack func, void* param)
{
CCHAR cpunr;
KAFFINITY cpus;
ULONG cpucount;
PKDPC dpc;
int dpcnr;
//KeIpiGenericCall is not present in xp
//count cpus first KeQueryActiveProcessorCount is not present in xp)
cpucount = 0;
cpus = KeQueryActiveProcessors();
while (cpus)
{
if (cpus % 2)
cpucount++;
cpus = cpus / 2;
}
dpc = (PKDPC)ExAllocatePool(NonPagedPool, sizeof(KDPC) * cpucount);
cpus = KeQueryActiveProcessors();
cpunr = 0;
dpcnr = 0;
while (cpus)
{
if (cpus % 2)
{
//bit is set
//DbgPrint("Calling dpc routine for cpunr %d (dpc=%p)\n", cpunr, &dpc[dpcnr]);
KeInitializeDpc(&dpc[dpcnr], DpcDelegate, func);
KeSetTargetProcessorDpc(&dpc[dpcnr], cpunr);
KeInsertQueueDpc(&dpc[dpcnr], param, nullptr);
KeFlushQueuedDpcs();
dpcnr++;
}
cpus = cpus / 2;
cpunr++;
}
ExFreePool(dpc);
}
int GetCurrentCpuIdx()
{
return KeGetCurrentProcessorNumber();
}
void* AllocContinueMemory(unsigned int size, unsigned int aligneSize)
{
PHYSICAL_ADDRESS lowAddr, highAddr, boundary;
lowAddr.QuadPart = 0;
highAddr.QuadPart = 0xFFFFFFFFFFFFFFFFULL;
boundary.QuadPart = aligneSize;
return MmAllocateContiguousMemorySpecifyCache(size, lowAddr, highAddr, boundary, MmCached);
}
void* AllocNonPagedMemory(unsigned int size)
{
return ExAllocatePool(NonPagedPool, size);
}
void ReleaseContinueMemory(void* addr)
{
MmFreeContiguousMemory(addr);
}
void ReleaseNonPagedMemory(void* addr)
{
ExFreePool(addr);
}
PHYSICAL_ADDRESS GetPhyAddress(void* addr)
{
return MmGetPhysicalAddress(addr);
}
};
|
/*
* Fichero de implementación listaPersonas.cc del módulo listaPersonas
*/
#include "../Persona/persona.h"
#include "listaPersonas.h"
/*
* Pre: ---
* Post: Devuelve una lista que no almacena ninguna persona, es decir,
* devuelve la lista <>
*/
ListaPersonas nuevaLista () {
ListaPersonas nueva;
nueva.numDatos = 0;
return nueva;
}
/*
* Pre: La lista L almacena K personas, es decir, L = < p_1, p_2, ..., p_K >
* Post: Devuelve el número K de personas almacenadas en la lista L
*/
int numPersonas (const ListaPersonas L) {
return L.numDatos;
}
/*
* Pre: La lista L almacena K personas, es decir, L = < p_1, p_2, ..., p_K >
* y i >= 1 y i <= K
* Post: Devuelve p_i, es decir, la persona ubicada en la posición i
* de la lista L
*/
Persona consultar (const ListaPersonas L, const int i) {
return L.datos[i-1];
}
/*
* Pre: La lista L almacena K personas, es decir, L = < p_1, p_2, ..., p_K >
* y K < DIM
* Post: La lista L almacena K+1 personas ya que a las K personas que
* almacenaba inicialmente se ha incorporado p como último elemento de la
* lista, es decir, ahora L = < p_1, p_2, ..., p_K, p >
*/
void anyadir (ListaPersonas& L, const Persona p) {
L.datos[L.numDatos] = p;
++L.numDatos;
}
/*
* Pre: La lista L almacena K personas, es decir, L = {p_1, p_2, ..., p_K}
* y K > 0
* Post: Devuelve la persona que ocupaba el primer lugar de la lista L, es
* decir, p_1, y modifica la lista L eliminando de ella la persona p_1,
* es decir, ahora L = {p_2, ..., p_K}
*/
Persona retirar (ListaPersonas& L) {
--L.numDatos;
return consultar(L, 1);
}
/*
* Pre: La lista L, siendo L = < p_1, p2, ..., p_i-1, p_i,..., p_K >, almacena K
* personas, K < DIM, i >= 1 e i <= K
* Post: La lista L almacena K+1 personas ya que a las K personas que almacenaba
* inicialmente se ha incorporado [p] como i-ésimo elemento de la lista, es decir,
* ahora L = < p_1, p2, ..., p_i-1, p, p_i, ..., p_K >
*/
void insertar (ListaPersonas& L, const Persona p, const int i) {
++L.numDatos;
for (int j = L.numDatos; j>i-1; --j) {
L.datos[j] = L.datos[j-1];
}
L.datos[i-1] = p;
}
/*
* Pre: La lista L, siendo, L = < p_1, p2, ..., p_i-1, p_i, p_i+1, ..., p_K >,
* almacena K personas, K > 0, i >= 1 e i < = K
* Post: Modifica la lista L eliminando de ella la persona p_i, es decir ahora solo
* almacena K-1 personas, siendo L = < p_1, p2, ..., p_i-1, p_i+1, ..., p_K >
*/
void eliminar (ListaPersonas& L, const int i) {
for (int j = i-1; j<L.numDatos; ++j) {
L.datos[j] = L.datos[j+1];
}
--L.numDatos;
}
|
// C++ program to implement recursive Binary Search
#include <bits/stdc++.h>
using namespace std;
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
//printf("%d ",mid);
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not
// present in array
return -1;
}
int main(void)
{
int* arr = new int[1000000];
ifstream inFile;
inFile.open("hash.in.txt");
int n;
inFile >> n ;
for (int i=0;i<n;i++)
{
inFile >> arr[i];
}
inFile.close();
sort(arr,arr+n);
int in=1;
if (in==1)
{
clock_t time;
time = clock();
double total=0;
for (int x=1;x<=1000000;x++)
{
int result = binarySearch(arr, 0, n - 1, x);
//printf("%d ",result);
if (x%100000==0)
{
time = clock()-time;
double tle = ((double) time)/ CLOCKS_PER_SEC ;
total+=tle;
printf("%d searches done in %lf seconds\n",x,total);
}
}
}
return 0;
}
|
#pragma once
#include <stdint.h>
#include <math.h>
#include <vector>
#include "common.h"
#include "Sample.h"
template<typename T>
class SampleBuffer
{
public:
T Get(int index) const
{
if (index < 0)
{
if (m_samples.empty()) return T();
return m_samples.front();
}
if (index >= m_samples.size())
{
if (m_samples.empty()) return T();
return m_samples.back();
}
return m_samples[index];
}
T operator[](int index) const
{
return Get(index);
}
T GetSample(float fpos) const
{
float fpos0 = truncf(fpos);
float frac = fpos - fpos0;
int p0 = (int)fpos0;
int p1 = p0 + 1;
float f0 = 1.0f - frac;
float f1 = frac;
T sample = Get(p0) * f0 + Get(p1) * f1;
return sample;
}
void push_back(T value)
{
m_samples.push_back(value);
}
const std::vector<T> &GetVector() const
{
return m_samples;
}
void Assign(const std::vector<T> &v)
{
m_samples = v;
}
using Titerator = typename std::vector<T>::iterator;
void Assign(Titerator start,Titerator end)
{
size_t total = end - start;
m_samples.clear();
m_samples.reserve(total);
m_samples.assign(start, end);
}
void clear()
{
m_samples.clear();
}
void reserve(size_t capacity)
{
m_samples.reserve(capacity);
}
size_t size() const
{
return m_samples.size();
}
void resize(size_t size)
{
m_samples.resize(size);
}
const T * data() const
{
return m_samples.data();
}
T * data()
{
return m_samples.data();
}
template<typename TFactor>
void Modulate(TFactor factor)
{
for (auto &it : m_samples)
{
it *= factor;
}
}
void ApplyKernel(SampleBuffer<T> &outBuffer, float k0, float k1, float k2, float k3) const
{
if (m_samples.empty())
return;
outBuffer.reserve(m_samples.size());
T s0 = m_samples.front();
T s1 = s0;
T s2 = s1;
T s3 = s2;
for (const auto &it : m_samples)
{
s3 = s2;
s2 = s1;
s1 = s0;
s0 = it;
T o = (s0 * k0) + (s1 * k1) + (s2 * k2) + (s3 * k3);
outBuffer.push_back(o);
}
}
void ApplyKernel(float k0, float k1, float k2, float k3)
{
if (m_samples.empty())
return;
T s0 = m_samples.front();
T s1 = s0;
T s2 = s1;
T s3 = s2;
for (auto &it : m_samples)
{
s3 = s2;
s2 = s1;
s1 = s0;
s0 = it;
T out = (s0 * k0) + (s1 * k1) + (s2 * k2) + (s3 * k3);
it = out;
}
}
void Smooth(float factor)
{
float f0 = 1.0f - factor;
float f1 = f0 * factor;
float f2 = f1 * factor;
float f3 = f2 * factor;
ApplyKernel(f0, f1, f2, f3);
}
void Smooth(SampleBuffer<T> &out_data, float factor)
{
float f0 = 1.0f - factor;
float f1 = f0 * factor;
float f2 = f1 * factor;
float f3 = f2 * factor;
ApplyKernel(out_data, f0, f1, f2, f3);
}
float GetSampleRate() const {return m_sampleRate;}
void SetSampleRate(float rate) {m_sampleRate = rate;}
private:
float m_sampleRate = 0;
std::vector<T> m_samples;
};
|
#include <iostream>
#include <vector>
using namespace std;
// o(n), with 2 ptr
void sortColors2(vector<int> &nums) {
int first = -1;
int second = nums.size();
if (second == 0)
return;
int cur = 0;
while (cur < second) {
if (nums[cur] < 1) {
first++;
swap(nums[first], nums[cur]);
cur++;
}
else if(nums[cur] > 1) {
second--;
swap(nums[second], nums[cur]);
}
else {
cur++;
}
}
}
// Quick sort
void partition(vector<int> &nums, int pivot) {
int left = 0;
int right = nums.size()-1;
while( left < right ){
while( nums[left] <= pivot && left < right )
++left;
while( nums[right] > pivot && left < right )
--right;
swap( nums[left], nums[right] );
}
}
void swap(int &x, int &y){
int temp = x;
x = y;
y = temp;
}
void sortColors(vector<int> &nums) {
if( nums.size() <= 1 )
return;
partition(nums, 0);
partition(nums, 1);
}
void main(){
int a[] = {1, 0, 1,2,0,1,1};
vector<int> num(a, a+ 7);
sortColors2(num);
int t;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.