text
stringlengths 8
6.88M
|
|---|
#include <bits/stdc++.h>
using namespace std;
int toInt(string s){
int x;
stringstream convert(s);
convert >> x;
return x;
}
int main(){
string s, result = "";
getline(cin, s);
while(!s.empty()){
string number = "";
while(s[0] < '0' || s[0] > '9')
s.erase(0,1);
while(s[0] >= '0' && s[0] <= '9'){
number.push_back(s.front());
s.erase(0,1);
}
int n = toInt(number);
for (int i = 0; i < n; ++i)
result.push_back(s[0]);
s.erase(0,1);
}
cout << result;
return 0;
}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp 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 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace RendererRuntime
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
inline float CameraSceneItem::getFovY() const
{
return mFovY;
}
inline void CameraSceneItem::setFovY(float fovY)
{
mFovY = fovY;
}
inline float CameraSceneItem::getNearZ() const
{
return mNearZ;
}
inline void CameraSceneItem::setNearZ(float nearZ)
{
mNearZ = nearZ;
}
inline float CameraSceneItem::getFarZ() const
{
return mFarZ;
}
inline void CameraSceneItem::setFarZ(float farZ)
{
mFarZ = farZ;
}
inline bool CameraSceneItem::hasCustomWorldSpaceToViewSpaceMatrix() const
{
return mHasCustomWorldSpaceToViewSpaceMatrix;
}
inline void CameraSceneItem::unsetCustomWorldSpaceToViewSpaceMatrix()
{
mHasCustomWorldSpaceToViewSpaceMatrix = false;
}
inline void CameraSceneItem::setCustomWorldSpaceToViewSpaceMatrix(const glm::mat4& customWorldSpaceToViewSpaceMatrix)
{
mWorldSpaceToViewSpaceMatrix = customWorldSpaceToViewSpaceMatrix;
mHasCustomWorldSpaceToViewSpaceMatrix = true;
}
inline bool CameraSceneItem::hasCustomViewSpaceToClipSpaceMatrix() const
{
return mHasCustomViewSpaceToClipSpaceMatrix;
}
inline void CameraSceneItem::unsetCustomViewSpaceToClipSpaceMatrix()
{
mHasCustomViewSpaceToClipSpaceMatrix = false;
}
inline void CameraSceneItem::setCustomViewSpaceToClipSpaceMatrix(const glm::mat4& customViewSpaceToClipSpaceMatrix, const glm::mat4& customViewSpaceToClipSpaceMatrixReversedZ)
{
mViewSpaceToClipSpaceMatrix = customViewSpaceToClipSpaceMatrix;
mViewSpaceToClipSpaceMatrixReversedZ = customViewSpaceToClipSpaceMatrixReversedZ;
mHasCustomViewSpaceToClipSpaceMatrix = true;
}
//[-------------------------------------------------------]
//[ Public RendererRuntime::ISceneItem methods ]
//[-------------------------------------------------------]
inline SceneItemTypeId CameraSceneItem::getSceneItemTypeId() const
{
return TYPE_ID;
}
//[-------------------------------------------------------]
//[ Protected methods ]
//[-------------------------------------------------------]
inline CameraSceneItem::~CameraSceneItem()
{
// Nothing here
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // RendererRuntime
|
/***********************************************************************
h£şModel Loader (mainly from file)
************************************************************************/
#pragma once
#include "_FbxLoader.h"
namespace Noise3D
{
class IMesh;
class IAtmosphere;
//name lists of loaded objects (e.g. from .fbx)
struct N_SceneLoadingResult
{
N_SceneLoadingResult(){}
std::vector<N_UID> meshNameList;
std::vector<N_UID> materialNameList;
};
class /*_declspec(dllexport)*/ IModelLoader
{
public:
bool LoadPlane(IMesh* pTargetMesh, float fWidth, float fDepth, UINT iRowCount = 5, UINT iColumnCount = 5);
bool LoadBox(IMesh* pTargetMesh, float fWidth, float fHeight, float fDepth, UINT iDepthStep = 3, UINT iWidthStep = 3, UINT iHeightStep = 3);
bool LoadSphere(IMesh* pTargetMesh, float fRadius, UINT iColumnCount = 20, UINT iRingCount = 20);
bool LoadCylinder(IMesh* pTargetMesh,float fRadius, float fHeight, UINT iColumnCount = 40, UINT iRingCount = 8);
bool LoadCustomizedModel(IMesh* pTargetMesh, const std::vector<N_DefaultVertex>& vertexList, const std::vector<UINT>& indicesList);
bool LoadFile_STL(IMesh* pTargetMesh, NFilePath filePath);
bool LoadFile_OBJ(IMesh* pTargetMesh, NFilePath filePath);
//bool LoadFile_3DS(NFilePath pFilePath, std::vector<IMesh*>& outMeshPtrList, std::vector<N_UID>& outMeshNameList);
//meshes are created automatically. call MeshManager.GetMesh() to retrieve pointers to mesh objects
void LoadFile_FBX(NFilePath pFilePath, N_SceneLoadingResult& outLoadingResult);
bool LoadSkyDome(IAtmosphere* pAtmo,N_UID texture, float fRadiusXZ, float fHeight);
bool LoadSkyBox(IAtmosphere* pAtmo, N_UID texture, float fWidth, float fHeight, float fDepth);
private:
friend class IFactory<IModelLoader>;
IModelLoader();
~IModelLoader();
//internal mesh loading helper
IFileIO mFileIO;
IGeometryMeshGenerator mMeshGenerator;
IFbxLoader mFbxLoader;
};
};
|
/******************************************************************************
* *
* Copyright 2018 Jan Henrik Weinstock *
* *
* 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 <gmock/gmock.h>
using namespace ::testing;
#include "vcml.h"
class mock_processor: public vcml::processor
{
public:
vcml::u64 cycles;
mock_processor(const sc_core::sc_module_name& nm):
vcml::processor(nm), cycles(0) {}
virtual ~mock_processor() {}
virtual vcml::u64 cycle_count() const override {
return cycles;
}
virtual void simulate(unsigned int n) override {
sc_core::sc_time now = sc_core::sc_time_stamp();
ASSERT_EQ(local_time_stamp(), now);
simulatem(n);
cycles += n;
ASSERT_EQ(local_time(), clock_cycles(n));
}
MOCK_METHOD2(interrupt, void(unsigned int,bool));
MOCK_METHOD1(simulatem, void(unsigned int));
MOCK_METHOD0(reset, void(void));
MOCK_METHOD2(handle_clock_update, void(clock_t,clock_t));
};
TEST(processor, processor) {
sc_core::sc_signal<clock_t> clk("CLK");
sc_core::sc_signal<bool> rst("RST");
sc_core::sc_signal<bool> irq0("IRQ0");
sc_core::sc_signal<bool> irq1("IRQ1");
vcml::generic::memory imem("IMEM", 0x1000);
vcml::generic::memory dmem("DMEM", 0x1000);
mock_processor cpu("CPU");
cpu.CLOCK.bind(clk);
cpu.RESET.bind(rst);
imem.CLOCK.bind(clk);
imem.RESET.bind(rst);
dmem.CLOCK.bind(clk);
dmem.RESET.bind(rst);
cpu.INSN.bind(imem.IN);
cpu.DATA.bind(dmem.IN);
cpu.IRQ[0].bind(irq0);
cpu.IRQ[1].bind(irq1);
vcml::clock_t defclk = 1 * vcml::kHz;
clk.write(defclk);
rst.write(false);
// finish elaboration
EXPECT_CALL(cpu, handle_clock_update(0, defclk)).Times(1);
sc_core::sc_start(sc_core::SC_ZERO_TIME);
sc_core::sc_time quantum(1.0, sc_core::SC_SEC);
sc_core::sc_time cycle = cpu.clock_cycle();
tlm::tlm_global_quantum::instance().set(quantum);
// test processor::simulate
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(1);
sc_core::sc_start(quantum);
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(10);
sc_core::sc_start(10 * quantum);
// test processor::interrupt
irq0.write(true);
EXPECT_CALL(cpu, interrupt(0, true)).Times(1);
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(1);
sc_core::sc_start(quantum);
irq0.write(false);
EXPECT_CALL(cpu, interrupt(0, false)).Times(1);
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(1);
sc_core::sc_start(quantum);
irq1.write(true);
EXPECT_CALL(cpu, interrupt(1, true)).Times(1);
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(1);
sc_core::sc_start(quantum);
irq1.write(false);
EXPECT_CALL(cpu, interrupt(1, false)).Times(1);
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(1);
sc_core::sc_start(quantum);
// test processor::reset
rst.write(true);
EXPECT_CALL(cpu, reset()).Times(AtMost(1));
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(1);
sc_core::sc_start(10 * quantum);
rst.write(false);
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(AtLeast(9));
sc_core::sc_start(10 * quantum);
// test processor::handle_clock_update
clk.write(0);
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(AtMost(1));
EXPECT_CALL(cpu, handle_clock_update(Eq(defclk), Eq(0))).Times(1);
sc_core::sc_start(10 * quantum);
clk.write(defclk);
EXPECT_CALL(cpu, simulatem(quantum / cycle)).Times(AtLeast(9));
EXPECT_CALL(cpu, handle_clock_update(Eq(0), Eq(defclk))).Times(1);
sc_core::sc_start(10 * quantum);
}
|
#include "ClosedState.h"
#include "OpenedState.h"
#include "StateContext.h"
#include <iostream>
void ClosedState::unlock(StateContext* stateContext) {
std::cout << "Can not unlock, current state is close\n";
}
void ClosedState::open(StateContext* stateContext) {
stateContext->setState(new OpenedState);
std::cout << "Changed from closed state to opened state\n";
delete this;
}
void ClosedState::close(StateContext* stateContext) {
std::cout << "Can not close, the current state is close\n";
}
void ClosedState::lock(StateContext* stateContext) {
stateContext->setState(new OpenedState);
std::cout << "Changed from closed state to locked state\n";
delete this;
}
|
#line 82 "ChessMatchup.cpp"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
VI u,t;
int n;
int memo[55][55][55];
int go(int ul, int uh, int th) {
if (ul >= uh) return 0;
if (th >= n) return 0;
if (memo[ul][uh][th] >= 0) return memo[ul][uh][th];
int best = 0;
int p1 = 0;
if (u[ul] > t[th]) p1 = 2;
if (u[ul] == t[th]) p1 = 1;
int p2 = 0;
if (u[uh - 1] > t[th]) p2 = 2;
if (u[uh - 1] == t[th]) p2 = 1;
best >?= go(ul + 1, uh , th + 1) + p1;
best >?= go(ul, uh - 1, th + 1) + p2;
return memo[ul][uh][th] = best;
}
class ChessMatchup
{
public:
int maximumScore(vector <int> us, vector <int> them)
{
n = us.size();
sort(us.rbegin(), us.rend());
sort(them.rbegin(), them.rend());
memset(memo, 0xff, sizeof(memo));
u = us;
t = them;
return go(0, n, 0);
}
};
// Powered by FileEdit
// Powered by TZTester 1.01 [25-Feb-2003]
// Powered by CodeProcessor
|
#ifndef KWIK_PARSER_STATE_H
#define KWIK_PARSER_STATE_H
#include "ast.h"
#include "io.h"
#include "exception.h"
namespace kwik {
struct ParseState {
ParseState(const Source& src)
: src(src), nested_paren(0), program(nullptr) { }
// void error_with_context(const std::string& msg, int line, int col) {
// assert(line - 1 >= 0);
// assert(size_t(line - 1) < src.lines.size());
// auto errmsg = op::format("{}:{}:{}: {}\n",
// src.name, line, col, msg);
// std::string indent(col - 1 + 4, ' ');
// errmsg += op::format(" {}\n{}^\n", src.lines[line - 1], indent);
// op::fprint(std::cout, errmsg);
// }
const Source& src;
int nested_paren;
std::unique_ptr<ast::CompoundStmt> program;
std::vector<std::unique_ptr<CompilationError>> errors;
};
void parse(const Source& src);
}
#endif
|
#include "apriltag_opencv.h"
#include "apriltag_family.h"
extern "C"{
#include "common/homography.h"
}
#include "getopt.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <iostream>
void getRelativeTransform(
double tag_size,
cv::Matx33f& K,
cv::Mat& rvec,
cv::Mat& tvec,
double* p,
double* tx, double* ty, double* tz
) {
std::vector<cv::Point3f> objPts;
std::vector<cv::Point2f> imgPts;
double s = tag_size/2.;
objPts.push_back(cv::Point3f(-s,-s, 0));
objPts.push_back(cv::Point3f( s,-s, 0));
objPts.push_back(cv::Point3f( s, s, 0));
objPts.push_back(cv::Point3f(-s, s, 0));
imgPts.push_back(cv::Point2f(p[0], p[1]));
imgPts.push_back(cv::Point2f(p[2], p[3]));
imgPts.push_back(cv::Point2f(p[4], p[5]));
imgPts.push_back(cv::Point2f(p[6], p[7]));
cv::Vec4f distParam(0,0,0,0); // all 0?
cv::solvePnP(objPts, imgPts, K, distParam, rvec, tvec);
*tx = tvec.at<double>(0);
*ty = tvec.at<double>(1);
*tz = tvec.at<double>(2);
return;
}
int main(int argc, char** argv) {
getopt_t *getopt = getopt_create();
getopt_add_bool(getopt, 'h', "help", 0, "Show this help");
getopt_add_bool(getopt, 'q', "quiet", 0, "Reduce output");
getopt_add_string(getopt, 'f', "family", "tag36h11", "Tag family to use");
getopt_add_int(getopt, '\0', "border", "1", "Set tag family border size");
getopt_add_int(getopt, 't', "threads", "4", "Use this many CPU threads");
getopt_add_double(getopt, 'x', "decimate", "1.0", "Decimate input image by this factor");
getopt_add_double(getopt, 'b', "blur", "0.0", "Apply low-pass blur to input");
getopt_add_bool(getopt, '0', "refine-edges", 1, "Spend more time trying to align edges of tags");
getopt_add_bool(getopt, '1', "refine-decode", 0, "Spend more time trying to decode tags");
getopt_add_bool(getopt, '2', "refine-pose", 0, "Spend more time trying to precisely localize tags");
getopt_add_bool(getopt, 'c', "contours", 0, "Use new contour-based quad detection");
if (!getopt_parse(getopt, argc, argv, 1) || getopt_get_bool(getopt, "help")) {
printf("Usage: %s [options] Camera index or movie file\n", argv[0]);
getopt_do_usage(getopt);
exit(0);
}
const char *famname = getopt_get_string(getopt, "family");
apriltag_family_t *tf = apriltag_family_create(famname);
if (!tf) {
printf("Unrecognized tag family name. Use e.g. \"tag36h11\".\n");
exit(-1);
}
tf->black_border = getopt_get_int(getopt, "border");
apriltag_detector_t *td = apriltag_detector_create();
apriltag_detector_add_family(td, tf);
if (getopt_get_bool(getopt, "contours")) {
apriltag_detector_enable_quad_contours(td, 1);
}
td->quad_decimate = getopt_get_double(getopt, "decimate");
td->quad_sigma = getopt_get_double(getopt, "blur");
td->nthreads = getopt_get_int(getopt, "threads");
td->debug = 0;
td->refine_edges = getopt_get_bool(getopt, "refine-edges");
td->refine_decode = getopt_get_bool(getopt, "refine-decode");
td->refine_pose = getopt_get_bool(getopt, "refine-pose");
const zarray_t *inputs = getopt_get_extra_args(getopt);
int camera_index = 0;
const char* movie_file = NULL;
if (zarray_size(inputs) > 1) {
printf("Usage: %s [options] Camera index or movie file\n", argv[0]);
exit(-1);
} else if (zarray_size(inputs)) {
char* input;
zarray_get(inputs, 0, &input);
char* endptr;
camera_index = strtol(input, &endptr, 10);
if (!endptr || *endptr) {
movie_file = input;
}
}
cv::VideoCapture* cap;
if (movie_file) {
cap = new cv::VideoCapture(movie_file);
int length = int(cap->get(CV_CAP_PROP_FRAME_COUNT));
printf("Video Length : %d\n" , length);
} else {
cap = new cv::VideoCapture(camera_index);
}
const char* window = "Camera";
cv::Mat frame;
bool ok = cap->read(frame);
if(!ok){
std::cerr << "Failed To Read First Frame" << std::endl;
return 1;
}
bool suc = cap->set(CV_CAP_PROP_POS_FRAMES, 0); //reset
if(!suc){
std::cerr << "Failed To Reset To First Frame" << std::endl;
return 1;
}
float fx = 85.0;
float fy = 85.0;
float tag_sz = 19.8;
float px = frame.cols / 2.0;
float py = frame.rows / 2.0;
cv::Mat rvec, tvec;
double tx, ty, tz;
cv::Matx33f K(
fx, 0, px,
0, fy, py,
0, 0, 1);
//cv::namedWindow(window);
Mat8uc1 gray;
while (1) {
bool ok = cap->read(frame);
if (!ok) { break; }
//cv::imshow(window, frame);
if (frame.channels() == 3) {
cv::cvtColor(frame, gray, cv::COLOR_RGB2GRAY);
} else {
frame.copyTo(gray);
}
image_u8_t* im8 = cv2im8_copy(gray);
zarray_t *detections = apriltag_detector_detect(td, im8);
image_u8_destroy(im8);
//printf("detected %d tags\n", zarray_size(detections));
//cv::Mat display = detectionsImage(detections, frame.size(), frame.type());
//printf("size : %d\n", zarray_size(detections));
for (int i = 0; i < zarray_size(detections); i++) {
apriltag_detection_t *det;
zarray_get(detections, i, &det);
getRelativeTransform(tag_sz, K, rvec, tvec, (double*)det->p, &tx, &ty, &tz);
//printf("detection %3d: id (%2dx%2d)-%-4d, hamming %d, "
// "goodness %8.3f, margin %8.3f\n",
// i, det->family->d*det->family->d, det->family->h,
// det->id, det->hamming, det->goodness, det->decision_margin);
//matd_t* p = homography_to_pose(det->H, 26.0, 26.0, gray.cols/2.0, gray.rows/2.0);
//double x = MATD_EL(p, 0,3);
//double y = MATD_EL(p, 1,3);
//double z = MATD_EL(p, 2,3);
//
//matd_destroy(p);
printf("%d,%.9f,%.9f,%.9f|", det->id, tx,ty,tz);
}
printf("\n");
apriltag_detections_destroy(detections);
//display = 0.5*display + 0.5*frame;
//cv::imshow(window, display);
//int k = cv::waitKey(1);
//if (k == 27) { break; }
}
return 0;
}
|
//UVA 1583 Digit Generator
//题意:每个数M可以产生一个新的数N,N等于M加上他的各位数字之和,例如216可以产生216+2+1+6=225。
// 那么给定一个数N,他的Generator(按照前述规则产生N的数称为这个数的Generator)可能会有多个也可能没有,
// 例如216的Generator可以是198和207。现在给定一个数N,让你求它的最小Generator,如果没有就输出0
//解题思路:先算出给定的N(1<=N<=100 000)的位数digitNum,则它的Generator肯定在[N-digitNum*9,N]之间产生
// (因为它的各位数肯定小于等于9),枚举这个区间的数字,找到了输出最小值,没找到输出0
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
int n;
cin >> n;
while (n--)
{
string stringN;
cin >> stringN;
int len = stringN.length();//N的位数
stringstream ss;//用于转换stringN和longN的类型
ss << stringN;
long long longN;
ss >> longN;//类型转换
long long i, j;
int flag = 0;
for (i = longN - len * 9; i <= longN; i++)
{
stringstream i_number;
long long sum = i;
i_number << i;
string number;
i_number >> number;
int len_num = number.length();
for (j = 0; j < len_num; j++)
{
sum += ((int)number[j]) - 48;
}
if (sum == longN)
{
flag = 1;
cout << i << endl;
break;
}
}
if (flag == 0)
{
cout << 0 << endl;
}
}
system("pause");
return 0;
}
|
#include <iostream>
#include "Form.hpp"
const int Form::minGrade = 1;
const int Form::maxGrade = 150;
Form::Form(std::string const &name, int sGrade, int eGrade, std::string const &target)
throw(GradeTooHighException, GradeTooLowException) :
_name(name),
_sGrade(sGrade),
_eGrade(eGrade),
_isSigned(false),
_target(target)
{
std::cout << "[Form](std::string const&,int,int) Ctor called" << std::endl;
if (sGrade < Form::minGrade || eGrade < Form::minGrade)
throw GradeTooHighException();
if (sGrade > Form::maxGrade || eGrade > Form::maxGrade)
throw GradeTooLowException();
return ;
}
Form::GradeTooHighException::GradeTooHighException() :
std::exception()
{
std::cout << "[GradeTooHighException]() Ctor called" << std::endl;
return ;
}
Form::GradeTooLowException::GradeTooLowException() :
std::exception()
{
std::cout << "[GradeTooLowException]() Ctor called" << std::endl;
return ;
}
Form::GradeTooHighException::GradeTooHighException(
GradeTooHighException const &rhs) : std::exception()
{
std::cout << "[GradeTooHighException](cpy) Ctor called" << std::endl;
(void)rhs;
return ;
}
Form::GradeTooLowException::GradeTooLowException(
GradeTooLowException const &rhs) : std::exception()
{
std::cout << "[GradeTooLowException](cpy) Ctor called" << std::endl;
(void)rhs;
return ;
}
Form::FormNotSignedException::FormNotSignedException(
FormNotSignedException const &rhs) : std::exception()
{
std::cout << "[FormNotSignedException](cpy) Ctor called" << std::endl;
(void)rhs;
return ;
}
Form::~Form()
{
std::cout << "[Form]() Dtor called" << std::endl;
return ;
}
Form::GradeTooHighException::~GradeTooHighException() throw()
{
std::cout << "[GradeTooHighException]() Dtor called" << std::endl;
return ;
}
Form::GradeTooLowException::~GradeTooLowException() throw()
{
std::cout << "[GradeTooLowException]() Dtor called" << std::endl;
return ;
}
Form::FormNotSignedException::~FormNotSignedException() throw()
{
std::cout << "[FormNotSignedException]() Dtor called" << std::endl;
return ;
}
std::ostream &operator<<(std::ostream &o, Form const &rhs)
{
o << "Form(" << rhs.getSGrade() << "," << rhs.getEGrade() <<
"):"<< rhs.getName() << " signed:" << std::boolalpha <<
rhs.getIsSigned();
return (o);
}
std::string const &Form::getName(void) const{return this->_name;}
int Form::getSGrade(void) const{return this->_sGrade;}
int Form::getEGrade(void) const{return this->_eGrade;}
bool Form::getIsSigned(void) const {return this->_isSigned;}
std::string const &Form::getTarget(void) const{return this->_target;}
void Form::beSigned(Bureaucrat const &b)
throw(GradeTooLowException)
{
if (!this->_isSigned)
{
if (b.getGrade() > this->_sGrade)
throw Form::GradeTooLowException();
this->_isSigned = true;
}
else
std::cout << this->_name << " is already signed..." << std::endl;
return ;
}
void Form::tryExecute(Bureaucrat const &executor) const
throw(GradeTooLowException, FormNotSignedException)
{
if (!this->_isSigned)
throw Form::FormNotSignedException();
else if (executor.getGrade() > this->_sGrade)
throw Form::GradeTooLowException();
else
this->execute(executor);
return ;
}
const char *Form::GradeTooHighException::what() const throw()
{
return ("Grade too high");
}
const char *Form::GradeTooLowException::what() const throw()
{
return ("Grade too low");
}
const char *Form::FormNotSignedException::what() const throw()
{
return ("Form not signed");
}
|
#pragma once
#include "calculateproteinprobability.h"
class CCalProteinProbLogisticRegression :
public CCalculateProteinProbability
{
public:
void calculateProteinProbability();
CCalProteinProbLogisticRegression(CListMassPeptideXcorr* pLMX,CListProtein* pLP):CCalculateProteinProbability(pLMX,pLP){};
~CCalProteinProbLogisticRegression(void);
};
|
#ifndef REACTOR_BASE_PATH_H
#define REACTOR_BASE_PATH_H
#include <utility>
#include <string>
namespace reactor {
namespace base {
/*
* see python os.path for API doc
* XXX noly suppory english path name
*/
namespace path {
std::string abspath(const std::string &path);
std::string basename(const std::string &path);
// commonprefix
std::string dirname(const std::string &path);
bool exists(const std::string &path);
std::string expanduser(const std::string &path);
std::string expandvars(const std::string &path);
time_t getatime(const std::string &path);
time_t getctime(const std::string &path);
time_t getmtime(const std::string &path);
size_t getsize(const std::string &path);
bool isabs(const std::string &path);
bool isdir(const std::string &path);
bool isfile(const std::string &path);
bool islink(const std::string &path);
bool ismount(const std::string &path);
std::string join(const std::string &a, const std::string &b);
bool lexists(const std::string &path);
std::string normpath(const std::string &path);
std::string realpath(const std::string &path);
std::string relpath(const std::string &path, const std::string &start=".");
bool samefile(const std::string &a, const std::string &b);
std::pair<std::string, std::string> split(const std::string &path);
std::pair<std::string, std::string> splitext(const std::string &path);
// walk
} // namespace path
} // namespace base
} // namespace reactor
#endif
|
// 특수문자 제외 문자열 뒤집기
// "abs/sae&stge["
#include <iostream>
using namespace std;
bool isAlphabet(char c) {
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
return true;
else
return false;
}
void main() {
char str[100];
cout << "문자를 입력하세요. (100자 이내)" << endl;
cout << "입력 : ";
cin >> str;
cout << "입력한 문자열 : " << str << endl;
int len = strlen(str);
int start = 0;
int end = len - 1;
while(start < end) {
// check
cout << "\tstart: " << str[start] << ", end: " << str[end] << endl;
// alphabet 인 경우 swap
if (isAlphabet(str[start]) && isAlphabet(str[end])) {
cout << "\t\t둘 다 알파벳 swap" << endl;
char temp;
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
// start가 알파벳이 아닌 경우
else if (isAlphabet(str[start]) == false) {
cout << "\t\tstart 다음 문자로" << endl;
start++;
}
// end가 알파벳이 아닌 경우
else {
cout << "\t\tend 이전 문자로" << endl;
end--;
}
}
cout << "뒤집힌 문자열 : " << str << endl;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
class DataFile_Record;
#include "modules/hardcore/mem/mem_man.h"
#include "modules/url/url_brel.h"
#include "modules/url/url_rel.h"
BOOL URL_RelRep::TraverseActionL(uint32 action, void *params)
{
#ifndef RAMCACHE_ONLY
if(!last_visited)
return TRUE;
if(action == 0)
WriteCacheDataL((DataFile_Record *) params);
#ifdef CACHE_FAST_INDEX
else if(action == 100)
WriteCacheDataL((DiskCacheEntry *) params);
#endif
#endif
return TRUE;
}
int URL_RelRep::SearchCompare(void *search_param)
{
const char *rel = (const char *) search_param;
if(name.HasContent())
{
return rel ? name.Compare(rel) : +1;
}
else
{
return (rel && *rel) ? -1 : 0;
}
}
/* return positive if first is greater than second */
int RelRep_Compare(const B23Tree_Item *first, const B23Tree_Item *second)
{
URL_RelRep *item1 = (URL_RelRep *)first;
URL_RelRep *item2 = (URL_RelRep *)second;
if(item1 && item2)
{
return item1->Name().Compare(item2->Name());
}
else
{
return (item1 ? +1 : (item2 ? -1 : 0));
}
}
RelRep_Store::RelRep_Store()
: B23Tree_Store(RelRep_Compare)
{
}
#ifndef RAMCACHE_ONLY
void RelRep_Store::WriteCacheDataL(DataFile_Record *rec)
{
TraverseL(0, rec);
}
#ifdef CACHE_FAST_INDEX
void RelRep_Store::WriteCacheDataL(DiskCacheEntry *entry)
{
TraverseL(100, entry);
}
#endif
#endif
void RelRep_Store::DeleteRep(const char *rel)
{
URL_RelRep *rep;
if(rel == NULL)
return;
rep = (URL_RelRep *) Search((void *) rel);
if(rep != NULL)
Delete(rep);
}
URL_RelRep *RelRep_Store::FindOrAddRep(const char *rel)
{
URL_RelRep *rep;
if(rel == NULL)
return NULL;
rep = (URL_RelRep *) Search((void *)rel);
if(rep == NULL)
{
OP_STATUS op_err = URL_RelRep::Create(&rep, rel);
if(OpStatus::IsError(op_err))
{
g_memory_manager->RaiseCondition(op_err);
OP_DELETE(rep);
return NULL;
}
TRAP_AND_RETURN_VALUE_IF_ERROR(op_err, InsertL(rep), NULL);
}
return rep;
}
void RelRep_Store::FindOrAddRep(URL_RelRep *rel)
{
if(rel == NULL)
return;
OP_STATUS op_err;
TRAP_AND_RETURN_VOID_IF_ERROR(op_err, InsertL(rel));
}
|
#ifndef ENEMY_H
#define ENEMY_H
#include "MobileObject.h"
#include <stack>
#include "Node.h"
#include "Projectile.h"
#include "PowerUp.h"
class Enemy : public MobileObject {
public:
Enemy(float, stack<Node*>, int, int, float, glm::vec3, glm::vec3);
// Update function for moving the object around by its path
virtual void update(double, vector<PowerUp*>*,vector<Projectile*>*, int*, int*);
void damage(int d);
bool spawnPowerup();
inline void addStagger(float s) { stagger += s; };
inline int getHealth() { return health; }
protected:
int health;
int loot;
float chance;
float stagger;
float timer;
stack<Node*> path;
};
#endif
|
//============================================================================
// Name : Assignment_3.cpp
// Author : Aditya
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <queue>
using namespace std;
class node
{
int data;
node *left,*right;
int lbit,rbit;
public:
node(int x)
{
data = x;
left = right = NULL;
lbit = rbit = 0;
}
friend class TBT;
};
class TBT
{
node* root;
public:
TBT()
{
root = new node(-1);
root->left = root->right = root;
root->lbit = 0;
root->rbit = 1;
}
void create();
void linsert(node*,node*);
void rinsert(node*,node*);
node* insuc(node*);
void inorder();
void preorder();
};
void TBT::create()
{
queue <node*> q;
q.push(root);
node *p, *temp;
int x;
while(!q.empty())
{
temp = q.front();
q.pop();
cout << "Left of " << temp->data << " :";
cin >> x;
if(x != -1)
{
p = new node(x);
linsert(temp,p);
q.push(p);
}
if(temp != root)
{
cout << "Right of " << temp->data << " :";
cin >> x;
if(x != -1)
{
p = new node(x);
rinsert(temp,p);
q.push(p);
}
}
}
}
void TBT::linsert(node* s,node* t)
{
t->left = s->left;
t->lbit = s->lbit;
t->right = s;
t->rbit = 0;
s->left = t;
s->lbit = 1;
}
void TBT::rinsert(node* s,node* t)
{
t->right = s->right;
t->rbit = s->rbit;
t->left = s;
t->lbit = 0;
s->right = t;
s->rbit = 1;
}
node* TBT::insuc(node* x)
{
node* s = x->right;
if(x->rbit == 1)
{
while(s->lbit == 1)
{
s = s->left;
}
}
return s;
}
void TBT::inorder()
{
node* T = root;
while(1)
{
T = insuc(T);
if(T == root)
{
return;
}
cout << T->data << " ";
}
}
void TBT::preorder()
{
int flag = 1;
node* p = root->left;
while(p != root)
{
while(flag != 0)
{
cout << p->data << " ";
if(p->lbit == 1)
{
p = p->left;
}
else
{
break;
}
}
flag = p->rbit;
p = p->right;
}
}
int main()
{
TBT t;
t.create();
t.inorder();
t.preorder();
}
|
#ifndef TRASHBINPIONEERS_H
#define TRASHBINPIONEERS_H
#include "services/pioneerservice.h"
#include "ui/mainwindow.h"
#include <QDialog>
namespace Ui {
class TrashBinPioneers;
}
class TrashBinPioneers : public QDialog
{
Q_OBJECT
public:
explicit TrashBinPioneers(QWidget *parent = 0);
~TrashBinPioneers();
private slots:
void on_table_pioneers_clicked(const QModelIndex &);
void on_button_restore_selected_clicked();
void on_button_take_out_the_trash_clicked();
void on_button_close_clicked();
private:
Ui::TrashBinPioneers *ui;
void displayPioneers();
// Displays the Pioneers in the trash bin
PioneerService data;
vector<Pioneer> currentlyDisplayedPioneers;
};
#endif // TRASHBINPIONEERS_H
|
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <iomanip>
#include <set>
#include <climits>
#include <ctime>
#include <complex>
#include <cmath>
#include <string>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std;
#define endl '\n'
typedef pair<int,int> pii;
typedef long double ld;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
const int maxn=1005;
const int INF=100000000;
const double pi=acos(-1.0);
const double eps=1e-9;
inline int sgn(double a) {
return a<-eps? -1:a>eps;
}
int dx[]= {0,0,-1,1};
int dy[]= {1,-1,0,0};
int n,m;
char mp[maxn][maxn];
int path[4][maxn][maxn];
void bfs(int C) {
queue<pii> q;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(mp[i][j]=='0'+C) {
path[C][i][j]=0;
q.push(make_pair(i,j));
} else {
path[C][i][j]=INF;
}
}
}
while(!q.empty()) {
pii x=q.front();
q.pop();
for(int i=0; i<4; i++) {
int tx=x.first+dx[i];
int ty=x.second+dy[i];
if(tx>=0&&tx<n&&ty>=0&&ty<m&&mp[tx][ty]!='#'&&path[C][tx][ty]==INF) {
path[C][tx][ty]=path[C][x.first][x.second]+1;
q.push(make_pair(tx,ty));
}
}
}
return;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
cin>>n>>m;
for(int i=0; i<n; i++)
cin>>mp[i];
for(int i=1; i<=3; i++)
bfs(i);
int ans=INF;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int t=1;
for(int k=1;k<=3;k++)
t+=max(0,path[k][i][j]-1);
// cout<<t<<endl;
ans=min(ans,t);
}
}
// cout<<ans<<endl;
for(int k=1; k<=3; k++) {
int t1=INF,t2=INF;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(mp[i][j]=='0'+k) {
if(k==1) {
t1=min(t1,path[2][i][j]);
t2=min(t2,path[3][i][j]);
} else if(k==2) {
t1=min(t1,path[1][i][j]);
t2=min(t2,path[3][i][j]);
} else if(k==3) {
t1=min(t1,path[1][i][j]);
t2=min(t2,path[2][i][j]);
}
}
}
}
ans=min(ans,t1+t2-2);
}
if(ans>=INF/10) {
ans=-1;
}
cout<<ans<<endl;
return 0;
}
|
/**
* created: 2013-3-22 19:39
* filename: FKError
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#pragma once
//------------------------------------------------------------------------
#include <exception>
#include "FKVsVer8Define.h"
//------------------------------------------------------------------------
#define ERROR_MAXBUF 1024
using namespace std;
//------------------------------------------------------------------------
class CLDError : public std::exception
{
protected:
char m_szMsg[ERROR_MAXBUF];
int m_nErrorCode;
public:
CLDError( char *pMsg ,int nErrorCode=0,bool syserror=false );
virtual ~CLDError();
virtual const char * GetMsg();
virtual const int GetErrorCode()
{
return m_nErrorCode;
}
virtual const char *what() const _THROW0()
{
return m_szMsg;
}
virtual void formatsyserror(int nerror,char* sWinErrMsgBuf,int nlen)
{
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ARGUMENT_ARRAY,NULL,nerror,0,sWinErrMsgBuf,nlen-1,NULL);
char* p=strrchr( sWinErrMsgBuf, '\r' );
if (p){*(p) = ' ';}
}
};
//------------------------------------------------------------------------
void _outputerr( char *pMsg, ... );
//------------------------------------------------------------------------
|
#include<bits/stdc++.h>
using namespace std;
struct node{
int a,b;
};
node q[100];
int ans[100],n;
void readit(){
scanf("%d",&n);
for (int i=1;i<=n;i++)
scanf("%d%d",&q[i].a,&q[i].b);
}
int pow(int m,int n,int p){
int ans=1;
while (n>0){
if (n&1) ans=ans*m%p;
n=n>>1;
m=m*m%p;
}
return ans;
}
void writeit(){
for (int i=1;i<=n;i++)
printf("%d\n",ans[i]);
}
void work(){
for (int i=1;i<=n;i++)
ans[i]=pow(q[i].a,q[i].b,1012);
}
int main(){
readit();
work();
writeit();
return 0;
}
|
/*
* HeapUsage.h
*
* Created on: 2014-12-04
* Author: Roger
*/
#ifndef HEAPUSAGE_H_
#define HEAPUSAGE_H_
#include <QObject>
#include <sys/procfs.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdint.h>
class HeapUsage : public QObject
{
Q_OBJECT
public:
HeapUsage() {}
virtual ~HeapUsage() {}
Q_INVOKABLE int measureMem(); // Can be invoked from QML as well
};
#endif /* HEAPUSAGE_H_ */
|
#include "mainWindow.h"
mainWindow::mainWindow(entryStats* userStats, std::list<dataEntry*> &entries, int width, int height, const char* title) : Fl_Window(width, height, title) {
entryList = entries;
stats = userStats;
begin();
//efficiency stat box
effAvgStat = new Fl_Box(160, 60, 160, 90); //stats->returnEffAvgS());
effAvgStat->box(FL_NO_BOX);
effAvgStat->labelfont(FL_BOLD);
effAvgStat->labelsize(64);
effAvgStat->labeltype(FL_ENGRAVED_LABEL);
//effciency label box
effAvgLabel = new Fl_Box(195, 110, 90, 90, "L/100km (Avg)");
effAvgLabel->box(FL_NO_BOX);
effAvgLabel->labelsize(24);
//total distance stat box
distStat = new Fl_Box(45, 160, 120, 90);
distStat->labelfont(FL_BOLD);
distStat->labelsize(36);
distStat->labeltype(FL_ENGRAVED_LABEL);
//total distance label box
distLabel = new Fl_Box(60, 190, 90, 90, "Distance (km)");
distLabel->box(FL_NO_BOX);
distLabel->labelsize(14);
//total fills stat box
fillsStat = new Fl_Box(195, 160, 90, 90);
fillsStat->box(FL_NO_BOX);
fillsStat->labelfont(FL_BOLD);
fillsStat->labelsize(36);
fillsStat->labeltype(FL_ENGRAVED_LABEL);
//total fills label box
fillsLabel = new Fl_Box(195, 190, 90, 90, "Fills");
fillsLabel->box(FL_NO_BOX);
fillsLabel->labelsize(14);
//avg price per litre stat box
avgLitreStat = new Fl_Box(335, 160, 90, 90);
avgLitreStat->box(FL_NO_BOX);
avgLitreStat->labelfont(FL_BOLD);
avgLitreStat->labelsize(36);
avgLitreStat->labeltype(FL_ENGRAVED_LABEL);
//avg price per litre label box
avgLitreLabel = new Fl_Box(335, 190, 90, 90, "Avg $/Litre");
avgLitreLabel->box(FL_NO_BOX);
avgLitreLabel->labelsize(14);
//add new entry button
addNewEntry = new Fl_Button(20, 270, 210, 60, "New Entry");
addNewEntry->type(FL_NORMAL_BUTTON);
addNewEntry->box(FL_UP_BOX);
addNewEntry->labelsize(24);
addNewEntry->callback(CBopenEntryWindow, this);
//view past entries button
viewEntries = new Fl_Button(250, 270, 210, 60, "View Entries");
viewEntries->type(FL_NORMAL_BUTTON);
viewEntries->box(FL_UP_BOX);
viewEntries->labelsize(24);
viewEntries->callback(CBviewEntriesWindow, this);
//reset statistics and delete entries button
reset = new Fl_Button(20, 20, 65, 25, "Reset");
reset->type(FL_NORMAL_BUTTON);
reset->box(FL_UP_BOX);
reset->labelsize(18);
reset->callback(CBresetData, this);
setStatWidgetLabels();
end();
show();
}
mainWindow::~mainWindow()
{
}
void
mainWindow::CBopenEntryWindow(Fl_Widget*, void* v) {
((mainWindow*)v)->CBopenEntryWindowI(); //overcomes function being static so we can pass std::list<dataEntry*> and entryStats* into called functions
}
void
mainWindow::CBopenEntryWindowI() {
newEntryWindow* window = new newEntryWindow(entryList, stats, effAvgStat, distStat, fillsStat, avgLitreStat, 240, 360, "New Entry");
}
void
mainWindow::CBresetData(Fl_Widget*, void* v) {
((mainWindow*)v)->CBresetDataI();
}
//asks user if they want to continue with reset
//resets statistics, deletes entries in list, and clears saveData file
void
mainWindow::CBresetDataI() {
switch (fl_choice("Are you sure you want to reset?", "Yes", "No", 0)) {
case 0: //yes
stats->resetStats(); //set all stats to 0
resetEntryList(); //reset to null list
saveEntries(entryList); //clears save file
//set widgets on main window to reset stat values
setStatWidgetLabels();
break;
case 1: //no
break;
}
}
void
mainWindow::CBviewEntriesWindow(Fl_Widget*, void* v) {
((mainWindow*)v)->CBviewEntriesWindowI();
}
void
mainWindow::CBviewEntriesWindowI() {
Fl_Double_Window* win = new Fl_Double_Window(842, 400, "View Entries");
viewEntriesWindow* table = new viewEntriesWindow(entryList, 10, 10, 822, 380);
win->resizable(table);
win->show();
}
void
mainWindow::resetEntryList() {
//delete each dataEntry object pointed to in list
for (std::list<dataEntry*>::iterator entry = entryList.begin(); entry != entryList.end(); ++entry) {
delete *entry;
}
entryList.clear(); //deletes pointers within list and resets size to 0
}
//sets the label of the stat widgets to the current stat values
void
mainWindow::setStatWidgetLabels() {
effAvgStat->label(stats->returnStatS(0));
distStat->label(stats->returnStatS(1));
fillsStat->label(stats->returnStatS(2));
avgLitreStat->label(stats->returnStatS(3));
}
|
#ifndef APPLICATION_LOGIN_H
#define APPLICATION_LOGIN_H
#include <QObject>
#include <QMessageBox>
#include <CallbacksHolder/Callback/BaseCallback.h>
#include <Controller/Controller.h>
#include "ui/LoginWidget/loginwidget.h"
#include "ui/MainWidget/mainwidget.h"
#include "ui/UserData/UserData.h"
// Callback for Login
class LoginCallback : public BaseCallback {
public:
LoginCallback(std::shared_ptr<LoginWidget> widget) : widget(widget) {};
public:
void operator()(std::shared_ptr<BaseObject> data,
const std::optional<std::string>& error) override {
if (error)
widget->ui->SignInLabel->setText(QString::fromStdString("Sing in error: " + (*error)));
else {
auto authInfo = std::static_pointer_cast<UserInfo>(data);
auto userData = UserData::getInstance();
userData->company = authInfo->company;
userData->userId = authInfo->userId;
userData->firstName = authInfo->firstName;
userData->lastName = authInfo->lastName;
userData->role = authInfo->role;
auto window = widget;
Controller::getInstance()->reconnectClient(authInfo->ip, authInfo->port);
window->showMainWidget();
}
}
private:
std::shared_ptr<LoginWidget> widget;
};
#endif //APPLICATION_LOGIN_H
|
class ItemAntibacterialWipe
{
weight = 0.003;
};
class ItemSepsisBandage
{
weight = 0.005;
};
class ItemBandage
{
weight = 0.005;
};
class ItemPainkiller
{
weight = 0.1;
};
class ItemMorphine
{
weight = 0.1;
};
class ItemEpinephrine
{
weight = 0.1;
};
class ItemHeatPack
{
weight = 0.1;
};
class ItemBloodbag
{
weight = 0.4;
};
class ItemAntibiotic
{
weight = 0.1;
};
class ItemAntibiotic6
{
weight = 0.08;
};
class ItemAntibiotic5
{
weight = 0.06;
};
class ItemAntibiotic4
{
weight = 0.04;
};
class ItemAntibiotic3
{
weight = 0.02;
};
class ItemAntibiotic2
{
weight = 0.009;
};
class ItemAntibiotic1
{
weight = 0.005;
};
class ItemAntibioticEmpty
{
weight = 0.002;
};
class bloodBagANEG
{
weight = 0.4;
};
class bloodBagAPOS
{
weight = 0.4;
};
class bloodBagBNEG
{
weight = 0.4;
};
class bloodBagBPOS
{
weight = 0.4;
};
class bloodBagABNEG
{
weight = 0.4;
};
class bloodBagABPOS
{
weight = 0.4;
};
class bloodBagONEG
{
weight = 0.4;
};
class bloodBagOPOS
{
weight = 0.4;
};
class wholeBloodBagANEG
{
weight = 0.4;
};
class wholeBloodBagAPOS
{
weight = 0.4;
};
class wholeBloodBagBNEG
{
weight = 0.4;
};
class wholeBloodBagBPOS
{
weight = 0.4;
};
class wholeBloodBagABNEG
{
weight = 0.4;
};
class wholeBloodBagABPOS
{
weight = 0.4;
};
class wholeBloodBagONEG
{
weight = 0.4;
};
class wholeBloodBagOPOS
{
weight = 0.4;
};
class bloodTester
{
weight = 0.1;
};
class transfusionKit
{
weight = 0.1;
};
class emptyBloodBag
{
weight = 0.003;
};
class ItemPainkiller6
{
weight = 0.6;
};
class ItemPainkiller5
{
weight = 0.5;
};
class ItemPainkiller4
{
weight = 0.4;
};
class ItemPainkiller3
{
weight = 0.3;
};
class ItemPainkiller2
{
weight = 0.2;
};
class ItemPainkiller1
{
weight = 0.1;
};
class ItemPainkillerEmpty
{
weight = 0.0;
};
class equip_woodensplint
{
weight = 1.0;
};
class equip_gauze
{
weight = 0.2;
};
class equip_gauzepackaged
{
weight = 0.4;
};
class equip_herb_box
{
weight = 0.8;
};
class ItemBloodbagInfected
{
weight = 0.4;
};
class ItemBloodbagZombie
{
weight = 0.4;
};
class ItemBloodbagRabbit
{
weight = 0.4;
};
class ItemBloodbagChicken
{
weight = 0.4;
};
class ItemBloodbagDog
{
weight = 0.4;
};
class ItemBloodbagCow
{
weight = 0.4;
};
class ItemBloodbagBoar
{
weight = 0.4;
};
class ItemBloodbagGoat
{
weight = 0.4;
};
class ItemBloodbagSheep
{
weight = 0.4;
};
|
#include "ConsoleTextStyle.h"
#include <iostream>
#include <windows.h>
const int consoleWidth = 120;
OutputTable * CreateOutputTable()
{
OutputTable * outTable = new OutputTable();
outTable->content = 0;
outTable->columnsCount = 0;
outTable->rowsCount = 0;
outTable->highLights = 0;
outTable->highLightsCount = 0;
outTable->primaryColor = 7;
outTable->headerColor = 14;
outTable->highLightsColor = 12;
return outTable;
}
bool KillOutputTable(OutputTable * outTable)
{
for (int r = 0; r < outTable->rowsCount; r++) {
delete[] outTable->content[r];
}
delete[] outTable->content;
delete[] outTable->highLights;
delete outTable;
return true;
}
//Цвета: 7 - белый(стандартный), 10 - зеленый, 12 - красный, 14 - желтый, 224 - черный на желтом фоне
bool AddConsoleTextColor(const string _text, const int color)
{
if (color == 7) {
cout << _text << endl;
}
else {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
cout << _text << endl;
SetConsoleTextAttribute(hConsole, 7);
}
return true;
}
bool AddConsoleTable(OutputTable * outTable)
{
if (outTable->columnsCount <= 0 || outTable->columnsCount >= 29 || outTable->rowsCount <= 0 || outTable->rowsCount >= 9000) {
AddConsoleTextColor("Ошибка отображения таблицы! Невозможно отобразить таблицу!", 12);
return false;
}
//Объявление основных переменных
//max width 120
int *columsWidth = new int[outTable->columnsCount];
int columnWidth = 0, sumColumsWidth = 0, spaceForColumnContent = consoleWidth - 1 - outTable->columnsCount;
//Валидация таблицы
for (int c = 0; c < outTable->columnsCount; c++) {
columsWidth[c] = 0;
for (int r = 0; r < outTable->rowsCount; r++) {
columnWidth = outTable->content[r][c].length();
columsWidth[c] = columnWidth > columsWidth[c] ? columnWidth : columsWidth[c];
}
if (columsWidth[c] <= 0) {
delete[] columsWidth;
AddConsoleTextColor("Ошибка отображения таблицы! В колонке номер " + to_string(c + 1) + " все значения пустые!", 12);
return false;
}
sumColumsWidth += columsWidth[c];
}
//Масштабирование размеров колонок под размер консоли
if (sumColumsWidth > spaceForColumnContent) {
int newColumnWidth = 0;
for (int c = 0; c < outTable->columnsCount; c++) {
newColumnWidth = columsWidth[c] * 100 / sumColumsWidth * spaceForColumnContent / 100;
if (newColumnWidth >= 3 && (spaceForColumnContent - newColumnWidth) > ((outTable->columnsCount - c - 1) * 3)) {
columsWidth[c] = newColumnWidth;
}
else if (columsWidth[c] <= newColumnWidth) {
columsWidth[c] = newColumnWidth;
}
else if ((spaceForColumnContent - newColumnWidth) < ((outTable->columnsCount - c - 1) * 3)) {
spaceForColumnContent -= 3 - newColumnWidth;
columsWidth[c] = 3;
}
else {
AddConsoleTextColor("Ошибка отображения таблицы! Колонка номер " + to_string(c + 1) + " слишком большая!", 12);
return false;
}
}
sumColumsWidth = spaceForColumnContent;
}
//подготовка к отображению
sumColumsWidth += 1 + outTable->columnsCount;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, outTable->headerColor);
cout.fill('_');
cout.width(sumColumsWidth);
cout << "" << endl;
//Отображение заголовка таблицы
cout.width();
cout << "|";
for (int r = 0, c = 0; c < outTable->columnsCount; c++) {
cout.width(columsWidth[c]);
cout << left << outTable->content[r][c].substr(0, columsWidth[c]);
cout.width();
cout << "|";
}
cout << endl;
//отображение тела таблицы
SetConsoleTextAttribute(hConsole, outTable->primaryColor);
for (int r = 1; r < outTable->rowsCount; r++) {
cout.width();
cout << "|";
for (int c = 0; c < outTable->columnsCount; c++) {
cout.width(columsWidth[c]);
if (outTable->highLightsCount > 0) {
bool isFound = false;
int h = 0;
do {
isFound = outTable->content[r][c] == outTable->highLights[h];
h++;
} while (isFound == false && h < outTable->highLightsCount);
if (isFound) {
SetConsoleTextAttribute(hConsole, outTable->highLightsColor);
cout << left << outTable->content[r][c].substr(0, columsWidth[c]);
SetConsoleTextAttribute(hConsole, outTable->primaryColor);
}
else {
cout << left << outTable->content[r][c].substr(0, columsWidth[c]);
}
}
else {
cout << left << outTable->content[r][c].substr(0, columsWidth[c]);
}
cout.width();
cout << "|";
}
cout << endl;
}
//Возвращение исходных настроек
cout.fill('-');
cout.width(sumColumsWidth);
cout << "" << endl;
SetConsoleTextAttribute(hConsole, 7);
cout.fill();
return true;
}
int DoubleSMatrixToConsole(double ** DoubleMatrix, int Rows, int Cols, int MainColor, double ZeroVal, int ZeroColor)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
for (int IndRow = 0; IndRow < Rows; IndRow++)
{
for (int IndCol = 0; IndCol < Cols; IndCol++)
{
if (DoubleMatrix[IndRow][IndCol] != ZeroVal) SetConsoleTextAttribute(hConsole, MainColor);
else SetConsoleTextAttribute(hConsole, ZeroColor);
cout << DoubleMatrix[IndRow][IndCol] << "\t";
}
cout << endl;
}
SetConsoleTextAttribute(hConsole, 7);
return 0;
}
|
#include <iostream>
using namespace std;
int main()
{
cout<<"hell"<<endl;
}
|
#include <memory.h>
#include <clang-c/Index.h>
CXChildVisitResult printFuncHeader(CXCursor cursor, CXCursor parent, CXClientData client_data)
{
CXString str;
CXCursor temp;
CXChildVisitResult ret = CXChildVisit_Recurse;
if (clang_getCursorKind (cursor) != CXCursor_FunctionDecl
&& clang_getCursorKind (cursor) != CXCursor_ParmDecl) {
ret = CXChildVisit_Continue;
goto proc_exit;
}
switch (clang_getCursorKind(cursor)) {
case CXCursor_FunctionDecl :
str = clang_getCursorSpelling(cursor);
printf("/* =============================================================== *\n");
printf(" * Name : %s\n", clang_getCString(str));
printf(" * Desc :\n");
temp = clang_getTypeDeclaration(clang_getResultType(clang_getCursorType(cursor)));
if (clang_isInvalid(clang_getCursorKind(temp)))
str = clang_getTypeKindSpelling(clang_getResultType(clang_getCursorType(cursor)).kind);
else {
str = clang_getCursorDisplayName(temp);
}
printf(" * Return : %s\n", clang_getCString(str));
printf(" * ----------------------[ Params ]------------------------------- \n");
clang_visitChildren(cursor, printFuncHeader, NULL);
printf(" */\n");
ret = CXChildVisit_Continue;
break;
case CXCursor_ParmDecl:
str = clang_getCursorDisplayName(cursor);
printf(" * %s :\n", clang_getCString(str));
ret = CXChildVisit_Continue;
break;
}
proc_exit:
return ret;
}
int main(int argc, char **argv)
{
CXIndex Index = clang_createIndex(0, 0);
CXTranslationUnit TU = clang_parseTranslationUnit(Index, NULL, argv, argc, 0, 0, CXTranslationUnit_None);
CXCursor rootCursor = clang_getTranslationUnitCursor(TU);
clang_visitChildren(rootCursor, printFuncHeader, NULL);
clang_disposeTranslationUnit(TU);
clang_disposeIndex(Index);
return 0;
}
|
#pragma once
class CUserSession : public CPacketSession
{
public:
CUserSession();
virtual ~CUserSession();
private:
BOOL mIsConnected;
TCHAR ID[32];
public:
BOOL Begin(VOID);
BOOL End(VOID);
BOOL Reload(SOCKET listenSocket);
inline BOOL SetIsConnected(BOOL isConnected) { CThreadSync Sync; mIsConnected = isConnected; return TRUE; }
inline BOOL GetIsConnected(VOID) { CThreadSync Sync; return mIsConnected; }
inline VOID SetID(WCHAR _ID[32]) { CThreadSync Sync; wcscpy(ID, _ID); }
inline LPTSTR GetID() { CThreadSync Sync; return ID; }
};
|
#pragma once
#include "Header.h"
#include "Graphics.h"
class Graphics;
class GameObject {
public:
int x;
int y;
public:
GameObject();
virtual ~GameObject();
public:
virtual void update(int keyCode);
virtual void render(Graphics& graphics);
};
|
#include "PlayerTimer.h"
#include "IProcess.h"
#include "Player.h"
#include "Logger.h"
#include "RobotRedis.h"
#include "Configure.h"
#include "AIDo.h"
//====================CTimer_Handler==================================//
int CTimer_Handler::ProcessOnTimerOut()
{
if(handler)
return handler->ProcessOnTimerOut(this->timeid, this->uid);
else
return 0;
}
void CTimer_Handler::SetTimeEventObj(PlayerTimer * obj, int timeid, int uid)
{
this->handler = obj;
this->timeid = timeid;
this->uid = uid;
}
//==========================PlayerTimer==================================//
void PlayerTimer::init(Player* player)
{
this->player = player;
}
void PlayerTimer::stopAllTimer()
{
stopBetCoinTimer();
stopLeaveTimer();
stopActiveLeaveTimer();
stopHeartTimer();
}
void PlayerTimer::startBetCoinTimer(int uid,int timeout)
{
m_BetTimer.SetTimeEventObj(this, BET_COIN_TIMER, uid);
m_BetTimer.StartTimer(timeout);
}
void PlayerTimer::stopBetCoinTimer()
{
m_BetTimer.StopTimer();
}
void PlayerTimer::startLeaveTimer(int timeout)
{
m_LeaveTimer.SetTimeEventObj(this, LEAVE_TIMER);
m_LeaveTimer.StartTimer(timeout);
}
void PlayerTimer::stopLeaveTimer()
{
m_LeaveTimer.StopTimer();
}
void PlayerTimer::startActiveLeaveTimer(int timeout)
{
m_ActiveLeaveTimer.SetTimeEventObj(this, ACTIVE_LEAVE_TIMER);
m_ActiveLeaveTimer.StartTimer(timeout);
}
void PlayerTimer::stopActiveLeaveTimer()
{
m_ActiveLeaveTimer.StopTimer();
}
void PlayerTimer::startStartGameTimer(int timeout)
{
m_StartTimer.SetTimeEventObj(this, START_TIMER);
m_StartTimer.StartTimer(timeout);
}
void PlayerTimer::stopStartGameTimer()
{
m_StartTimer.StopTimer();
}
void PlayerTimer::startHeartTimer(int uid,int timeout)
{
m_HeartTimer.SetTimeEventObj(this, HEART_TIMER, uid);
m_HeartTimer.StartTimer(timeout);
}
void PlayerTimer::stopHeartTimer()
{
m_HeartTimer.StopTimer();
}
int PlayerTimer::ProcessOnTimerOut(int Timerid, int uid)
{
switch (Timerid)
{
case BET_COIN_TIMER:
return BetTimerTimeOut(uid);
case LEAVE_TIMER:
return LeaveTimerTimeOut();
case ACTIVE_LEAVE_TIMER:
return ActiveLeaveTimeOut();
case HEART_TIMER:
return HeatTimeOut(uid);
case START_TIMER:
return StartTimeOut();
default:
return 0;
}
return 0;
}
int PlayerTimer::BetTimerTimeOut(int uid)
{
this->stopBetCoinTimer();
if(player->id != uid)
{
LOGGER(E_LOG_DEBUG)<< "player uid["<<player->id<<"] is not this uid["<<uid<<"]";
//_LOG_ERROR_("player uid[%d] is not this uid[%d]\n", player->id, uid);
return -1;
}
short level = player->clevel;
short loadtype = 2;
if(level <= LEVEL1)
loadtype = 1;
else if (level > LEVEL1 && level <= LEVEL2)
loadtype = 2;
else if (level > LEVEL2 && level <= LEVEL3)
loadtype = 3;
else if (level >= LEVEL6)
loadtype = 6;
int switchknowcoin = 0;
switchmoney = RobotRedis::getInstance()->getRobotWinCount(loadtype);
if ( loadtype == 1 )
{
switchmoneyup = Configure::instance()->swtichWin1;
switchknowcoin = Configure::instance()->swtichOnKnow1;
}
else if (loadtype == 2 )
{
switchmoneyup = Configure::instance()->swtichWin2;
switchknowcoin = Configure::instance()->swtichOnKnow2;
}
else if(loadtype == 6 )
{
switchmoneyup = Configure::instance()->swtichWin6;
switchknowcoin = Configure::instance()->swtichOnKnow6;
}
printf("-----switchmoney:%d switchknowcoin:%d \n", switchmoney, switchknowcoin);
if(switchmoney <= switchknowcoin)
{
if(switchmoney > switchmoneyup)
return handleProcess(uid);
else
return knowProcess(uid);
}
AIDo* aiPlayer = AIDo::getInstance();
BYTE mycard[2]={0,0};
mycard[0] = player->card_array[0];
mycard[1] = player->card_array[1];
BYTE publicCard[5] = {0,0,0,0,0};
for (int i = 0; i<5; i++)
{
if (player->CenterCard[i]!=0)
{
publicCard[i] = player->CenterCard[i];
}
}
int action = aiPlayer->getAIDo(mycard, publicCard, player->PoolCoin, player->currMaxCoin - player->betCoinList[player->currRound],
player->ante,player->getPlayNum());
switch (action)
{
case AI_FOLD:
{
return player->throwcard();
break;
}
case AI_CALL:
{
if(player->optype & OP_CALL)
return player->call();
if(player->optype & OP_CHECK)
return player->check();
if(player->optype & OP_ALLIN)
return player->allin();
break;
}
case AI_RAISE:
{
int64_t maxValue=player->limitcoin;
int64_t callNeedMoney = player->currMaxCoin - player->betCoinList[player->currRound];
int64_t miniValue =0;
int64_t chipToRaiseMin = callNeedMoney*2;
if (player->betCoinList[player->currRound]==player->ante*0.5)
{
if (callNeedMoney <= player->ante*0.5)
{
chipToRaiseMin = (int64_t)(player->ante*0.5+player->ante);
}
else
{
chipToRaiseMin = (int64_t)((callNeedMoney-player->ante*0.5)*2+player->ante*0.5);
}
}
if (chipToRaiseMin==0)
{
int randindex = rand()%6;
int64_t raisebackup=0;
if (randindex>=0&&randindex<=2)
{
raisebackup = player->PoolCoin/3;
}
else if (randindex>=3&&randindex<=4)
{
raisebackup = player->PoolCoin/2;
}
else
{
raisebackup = player->PoolCoin*2/3;
}
int64_t num = raisebackup/player->ante;
if (raisebackup%player->ante>0)
{
num++;
}
chipToRaiseMin = player->ante*num;
}
if (chipToRaiseMin>=player->limitcoin)
{
miniValue = player->limitcoin;
}
else
{
miniValue = chipToRaiseMin;
}
int64_t raiseChip = miniValue;
int64_t gap = maxValue-miniValue;
int64_t raiseGap = player->ante*2;
int64_t raisebackup[5] = {0,0,0,0,0};
for (int i = 0; i<5; i++)
{
int64_t raisenum =raiseGap*(i+1);
if (raisenum>10000)
{
int left = raisenum%100;
if (left>0)
{
raisenum = raisenum-left;
}
}
if (raisenum<gap)
{
raisebackup[i]=raisenum;
}
else
{
raisebackup[i] = gap;
}
}
int randnum = rand()%100;
if (randnum>70&&randnum<82)
{
raiseChip+=raisebackup[0];
}
else if (randnum>=82&&randnum<90)
{
raiseChip+=raisebackup[1];
}
else if (randnum>=90&&randnum<95)
{
raiseChip+=raisebackup[2];
}
else if (randnum>=95&&randnum<98)
{
raiseChip+=raisebackup[3];
}
else if (randnum>=98&&randnum<100)
{
raiseChip+=raisebackup[4];
}
player->rasecoin = raiseChip;
return player->rase();
break;
}
default:
break;
}
/*if(player->isKnow)
{
_LOG_DEBUG_("---------knowProcess-------uid:%d isKnow:%s\n",player->id, player->isKnow ? "true" : "false");
return knowProcess(uid);
}
else
{
_LOG_DEBUG_("---------notKonwProcess-------uid:%d isKnow:%s\n",player->id, player->isKnow ? "true" : "false");
return notKonwProcess(uid);
}*/
return 0;
}
int PlayerTimer::knowProcess(int uid)
{
if(player->robotKonwIsLargest())
{
//已经知道一定赢!!!!
int num = rand()%100;
short cardvalue1 = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short cardvalue2 = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
short cardcolor1 = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short cardcolor2 = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
BYTE bCardType = player->finalcardvalue;
if(player->clevel != 8)
{
if(player->currRound == 1)
return Round1Op();
}
if(player->currRound > 1)
{
bool isInHand = false;
tagAnalyseResult AnalyseResult;
player->m_GameLogic.AnalysebCardData(player->Knowcard_array,5,AnalyseResult);
if( AnalyseResult.cbThreeCount > 0 &&
(AnalyseResult.cbThreeLogicVolue[0] == cardvalue1 || AnalyseResult.cbThreeLogicVolue[0] == cardvalue2))
{
isInHand = true;
}
int randnum = rand()%100;
//三条以上
if( bCardType > CT_THREE_TIAO || ( bCardType == CT_THREE_TIAO && isInHand ) )
{
//梭哈
if( bCardType > CT_TONG_HUA )
{
if( randnum < 20)
{
if( player->optype & OP_ALLIN )
return player->allin();
}
}
//加注
if( player->optype & OP_RASE )
{
if( player->setRandRaseCoin(3, 6 ) == 0 )
{
if( player->optype & OP_ALLIN )
return player->allin();
}
else
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
return player->rase();
}
}
//跟注
if( player->optype & OP_CALL )
return player->call();
}
}
if( player->currMaxCoin == 0 && bCardType > CT_ONE_LONG )
{
int randnum = rand()%100;
if( randnum < 60 )
{
if(player->optype & OP_RASE)
{
if( player->setRandRaseCoin( 1, 3 ) == 1 )
return player->rase();
}
}
}
if( bCardType >= CT_THREE_TIAO )
{
if( player->currRound == 4 || num < 20 )
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
if( bCardType < CT_THREE_TIAO )
{
if((cardvalue1 >= 10 && cardvalue2 >= 10) ||
(cardvalue1 > 5 && (cardvalue1 == cardvalue2)) ||
((cardcolor1 == cardcolor2) && (cardvalue1 >= 13 || cardvalue2 >= 13)))
{
if( num < 40 )
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
else
{
if( (cardvalue1 > 10 && cardvalue2 > 10) || (cardcolor1 == cardcolor2 ) || cardvalue1 == 0x0E || cardvalue2 == 0x0E
|| ((cardvalue1>10 || cardvalue2>10) && ((cardvalue1 - cardvalue2) == 1)))
{
if( player->optype & OP_CALL )
return player->call();
}
if( num < 60 )
{
if(player->optype & OP_CALL)
return player->call();
}
}
}
if(player->optype & OP_RASE)
{
if((cardvalue1 >= 10 && cardvalue2 >= 10) ||
(cardvalue1 > 5 && (cardvalue1 == cardvalue2)) ||
((cardcolor1 == cardcolor2) && (cardvalue1 >= 13 || cardvalue2 >= 13)))
{
if( num < 30 )
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
int willrase = rand()%1000;
if(player->currMaxCoin < player->limitcoin)
{
if( player->currRound < 3 )
{
if( willrase < 800 )
player->setRandRaseCoin( 2, 5 );
else
player->setKnowRaseCoin();
}
else
{
if( willrase < 500 )
player->setRandRaseCoin( 2, 8 );
else
player->setKnowRaseCoin();
}
}
else if(player->optype & OP_ALLIN)
{
return player->allin();
}
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
if (willrase < 500)
{
return player->rase();
}
}
if( (cardvalue1 > 10 && cardvalue2 > 10) || (cardcolor1 == cardcolor2 ) || cardvalue1 == 0x0E || cardvalue2 == 0x0E
|| ((cardvalue1>10 || cardvalue2>10) && ((cardvalue1 - cardvalue2) == 1)))
{
if( player->currMaxCoin == 0)
{
int randnum = rand()%100;
if( randnum < 60 )
{
if(player->optype & OP_RASE)
{
if( player->setRandRaseCoin( 1, 3 ) == 1 )
return player->rase();
}
}
}
if(player->optype & OP_CALL)
{
return player->call();
}
}
if( num < 50 )
{
if( player->currMaxCoin == 0)
{
int randnum = rand()%100;
if( randnum < 60 )
{
if(player->optype & OP_RASE)
{
if( player->setRandRaseCoin( 1, 3 ) == 1 )
return player->rase();
}
}
}
if(player->optype & OP_CALL)
return player->call();
}
if(player->optype & OP_CHECK)
return player->check();
if(player->optype & OP_CALL)
return player->call();
if( player->optype & OP_ALLIN )
return player->allin();
if(player->optype & OP_THROW)
return player->throwcard();
}
else
return notWinProcess(uid);
return 0;
}
int PlayerTimer::notWinProcess(int uid)
{
//机器人一直在输,在无法赢时,只能看牌或弃牌
if(player->optype & OP_CHECK)
return player->check();
if(player->optype & OP_THROW)
return player->throwcard();
return 0;
}
int PlayerTimer::handleProcess(int uid)
{
if(player->currRound == 1)
return Round1Op();
if(player->currRound == 2)
return Round2Op();
if(player->currRound == 3)
return Round3Op();
if(player->currRound == 4)
return Round4Op();
return 0;
}
int PlayerTimer::Round1Op()
{
short card1value = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short card2value = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
short cardcolor1 = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short cardcolor2 = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
if(card1value < card2value)
{
short temp = card1value;
card1value = card2value;
card2value = temp;
}
bool bLargest = player->robotKonwIsLargest();
int randnum = rand()%100;
printf("+++++++++++++++++++++=uid:%d=======card1:0x%02x card2:0x%02x\n", player->id, player->card_array[0], player->card_array[1]);
if(card1value == card2value || (card1value == 0x0E && (card2value == 0x0D || card2value == 0x0C)))
{
if( randnum < 40 )
{
if( player->optype & OP_ALLIN )
return player->allin();
}
else
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 0, 8) > 0)
return player->rase();
}
}
}
if( (card1value > 10 && card2value > 10) ||
((card1value - card2value) == 1) || (cardcolor1 == cardcolor2 ) )
{
if(player->currMaxCoin == 0)
{
if(player->optype & OP_RASE)
{
if( player->setRandRaseCoin(0, 4) == 1 )
return player->rase();
}
}
else
{
if(player->currMaxCoin < player->ante*6)
{
if(player->optype & OP_CALL)
return player->call();
}
}
if(randnum < 30)
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 1, 5) > 0)
return player->rase();
}
}
}
if(switchmoney > switchmoneyup)
{
if(player->currMaxCoin <= player->ante*10)
{
if(player->optype & OP_CALL)
return player->call();
}
else
{
if(bLargest)
{
if( (card1value > 10 && card2value > 10) || (cardcolor1 == cardcolor2 ) || card1value == 0x0E || card1value == 0x0E
|| ((card1value>10 || card2value>10) && ((card1value - card2value) == 1)))
{
if(player->currMaxCoin > player->ante*15)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
if(randnum < 80)
{
if(player->optype & OP_CALL)
return player->call();
}
int randallin = rand()%100;
if(randallin < 10)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
}
if(!bLargest)
{
int randrase = rand()%100;
if(randrase < 50)
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 1, 5) > 0)
return player->rase();
}
}
}
}
else
{
if(bLargest)
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
int randrase = rand()%100;
if(randrase < 60)
{
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 0, 5) > 0)
return player->rase();
}
}
if( (card1value > 10 && card2value > 10) || (cardcolor1 == cardcolor2 ) || card1value == 0x0E || card1value == 0x0E
|| ((card1value>10 || card2value>10) && ((card1value - card2value) == 1)))
{
if(player->currMaxCoin > player->ante*15)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
if(randnum < 80)
{
if(player->optype & OP_CALL)
return player->call();
}
int randallin = rand()%100;
if(randallin < 10)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
}
//当前小牌,跟注小于底注3倍
if( player->optype & OP_CALL )
{
if( player->currMaxCoin < player->ante*4 )
{
return player->call();
}
}
if(player->optype & OP_CHECK)
return player->check();
if(player->optype & OP_THROW)
return player->throwcard();
return 0;
}
int PlayerTimer::Round2Op()
{
BYTE cbTempCard[5] = {0};
cbTempCard[0] = player->card_array[0];
cbTempCard[1] = player->card_array[1];
cbTempCard[2] = player->CenterCard[0];
cbTempCard[3] = player->CenterCard[1];
cbTempCard[4] = player->CenterCard[2];
short card1value = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short card2value = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
short cardcolor1 = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short cardcolor2 = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
if(card1value < card2value)
{
short temp = card1value;
card1value = card2value;
card2value = temp;
}
player->m_GameLogic.SortCardList( cbTempCard, 5 );
BYTE bCardType = player->m_GameLogic.GetCardType(cbTempCard, 5);
//_LOG_DEBUG_("cbTempCard:%02x, %02x, %02x, %02x, %02x\n",cbTempCard[0],cbTempCard[1],
//cbTempCard[2], cbTempCard[3], cbTempCard[4]);
bool bLargest = player->robotKonwIsLargest();
int randnum = rand()%100;
bool isInHand = false;
tagAnalyseResult AnalyseResult;
player->m_GameLogic.AnalysebCardData(cbTempCard,5,AnalyseResult);
if( AnalyseResult.cbThreeCount > 0 &&
(AnalyseResult.cbThreeLogicVolue[0] == card1value || AnalyseResult.cbThreeLogicVolue[0] == card2value))
{
isInHand = true;
}
//三条以上
if( bCardType > CT_THREE_TIAO || ( bCardType == CT_THREE_TIAO && isInHand ) )
{
//梭哈
if( bCardType > CT_TONG_HUA )
{
if( randnum < 50)
{
if( player->optype & OP_ALLIN )
return player->allin();
}
}
//加注
if( player->optype & OP_RASE )
{
if( player->setRandRaseCoin( 2, 8 ) == 0 )
{
if( player->optype & OP_ALLIN )
return player->allin();
}
else
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
if( randnum < 80 )
return player->rase();
}
}
//跟注
if( player->optype & OP_CALL )
return player->call();
}
//对子、两对
if( bCardType > CT_SINGLE )
{
bool isPaireInHand = false;
for( int i = 0; i < AnalyseResult.cbLONGCount; i++ )
{
if( AnalyseResult.cbLONGLogicVolue[i] == card1value ||
AnalyseResult.cbLONGLogicVolue[i] == card2value )
{
isPaireInHand = true;
break;
}
}
//底牌中有相关的对子
if( isPaireInHand )
{
//加注
if( player->optype & OP_RASE )
{
if( player->setRandRaseCoin( 2, 3 ) == 0 )
{
if( player->limitcoin < player->ante*6 )
{
if( player->optype & OP_ALLIN )
return player->allin();
}
}
else if( player->currMaxCoin <= player->ante*6 )
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
if( randnum < 50 )
return player->rase();
}
}
if( player->currMaxCoin < player->ante*5 )
{
if( player->optype & OP_CALL )
return player->call();
}
}
}
//这一轮,由此用户开始
if( player->currMaxCoin == 0 && bCardType > CT_ONE_LONG )
{
if( randnum < 60 )
{
if(player->optype & OP_RASE)
{
if( player->setRandRaseCoin( 1, 3 ) == 1 )
return player->rase();
}
}
}
if(switchmoney > switchmoneyup)
{
if(randnum < 40)
{
if(player->optype & OP_CALL)
return player->call();
}
if(!bLargest)
{
int randrase = rand()%100;
if(randrase < 60)
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 2, 8) > 0)
return player->rase();
}
}
}
else
{
if( (card1value > 10 && card2value > 10) || (cardcolor1 == cardcolor2 ) || card1value == 0x0E || card1value == 0x0E
|| ((card1value>10 || card2value>10) && ((card1value - card2value) == 1)))
{
if(player->currMaxCoin > player->ante*15)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
if(player->optype & OP_CALL)
return player->call();
}
int temprand = rand()%100;
if(player->currMaxCoin <= player->ante*10)
{
if(player->optype & OP_CALL)
return player->call();
}
else
{
if(temprand < 30)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
}
}
else
{
if(bLargest)
{
if( (card1value > 10 && card2value > 10) || (cardcolor1 == cardcolor2 ) || card1value == 0x0E || card1value == 0x0E
|| ((card1value>10 || card2value>10) && ((card1value - card2value) == 1)))
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
int randrase = rand()%100;
if(randrase < 60)
{
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 3, 5) > 0)
return player->rase();
}
}
}
else
{
int randrase = rand()%100;
if(randrase < 60 && player->currMaxCoin < player->ante*4)
{
if(player->optype & OP_CALL)
return player->call();
}
}
}
}
if(player->optype & OP_CHECK)
return player->check();
if(player->optype & OP_THROW)
return player->throwcard();
return 0;
}
int PlayerTimer::Round3Op()
{
short card1value = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short card2value = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
short cardcolor1 = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short cardcolor2 = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
if(card1value < card2value)
{
short temp = card1value;
card1value = card2value;
card2value = temp;
}
bool bLargest = player->robotKonwIsLargest();
int randnum = rand()%100;
BYTE bCardType = player->finalcardvalue;
randnum = rand()%100;
bool isInHand = false;
tagAnalyseResult AnalyseResult;
player->m_GameLogic.AnalysebCardData(player->Knowcard_array,5,AnalyseResult);
if( AnalyseResult.cbThreeCount > 0 &&
(AnalyseResult.cbThreeLogicVolue[0] == card1value || AnalyseResult.cbThreeLogicVolue[0] == card2value))
{
isInHand = true;
}
//三条以上
if( bCardType > CT_THREE_TIAO || ( bCardType == CT_THREE_TIAO && isInHand ) )
{
//梭哈
if( bCardType > CT_TONG_HUA )
{
if( randnum < 20)
{
if( player->optype & OP_ALLIN )
return player->allin();
}
}
//加注
if( player->optype & OP_RASE )
{
if( player->setRandRaseCoin(3, 6 ) == 0 )
{
if( player->optype & OP_ALLIN )
return player->allin();
}
else
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
return player->rase();
}
}
//跟注
if( player->optype & OP_CALL )
return player->call();
}
if(switchmoney > switchmoneyup)
{
if(randnum < 40)
{
if(player->optype & OP_CALL)
return player->call();
}
if(!bLargest)
{
int randrase = rand()%100;
if(randrase < 60)
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 3, 3) > 0)
return player->rase();
}
}
}
else
{
if( (card1value > 10 && card2value > 10) || (cardcolor1 == cardcolor2 ) || card1value == 0x0E || card1value == 0x0E
|| ((card1value>10 || card2value>10) && ((card1value - card2value) == 1)))
{
if(player->currMaxCoin > player->ante*15)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
if(player->optype & OP_CALL)
return player->call();
}
int temprand = rand()%100;
if(player->currMaxCoin <= player->ante*10)
{
if(player->optype & OP_CALL)
return player->call();
}
else
{
if(temprand < 30)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
}
}
else
{
if(bLargest)
{
if( (card1value > 10 && card2value > 10) || (cardcolor1 == cardcolor2 ) || card1value == 0x0E || card1value == 0x0E
|| ((card1value>10 || card2value>10) && ((card1value - card2value) == 1)))
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
int randrase = rand()%100;
if(randrase < 60)
{
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 4, 5) > 0)
return player->rase();
}
}
}
else
{
int randrase = rand()%100;
if(randrase < 60 && player->currMaxCoin < player->ante*4)
{
if(player->optype & OP_CALL)
return player->call();
}
}
}
}
if(player->optype & OP_CHECK)
return player->check();
if(player->optype & OP_THROW)
return player->throwcard();
return 0;
}
int PlayerTimer::Round4Op()
{
short card1value = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short card2value = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
short cardcolor1 = player->m_GameLogic.GetCardLogicValue(player->card_array[0]);
short cardcolor2 = player->m_GameLogic.GetCardLogicValue(player->card_array[1]);
if(card1value < card2value)
{
short temp = card1value;
card1value = card2value;
card2value = temp;
}
BYTE bCardType = player->finalcardvalue;
bool bLargest = player->robotKonwIsLargest();
int randnum = rand()%100;
if( bCardType > CT_HU_LU && player->robotKonwIsLargest() )
{
if( player->optype & OP_ALLIN )
return player->allin();
}
bool isInHand = false;
tagAnalyseResult AnalyseResult;
player->m_GameLogic.AnalysebCardData(player->Knowcard_array,5,AnalyseResult);
if( AnalyseResult.cbThreeCount > 0 &&
(AnalyseResult.cbThreeLogicVolue[0] == card1value || AnalyseResult.cbThreeLogicVolue[0] == card2value))
{
isInHand = true;
}
//三条以上
if( bCardType > CT_THREE_TIAO || ( bCardType == CT_THREE_TIAO && isInHand ) )
{
//梭哈
if( randnum < 10)
{
if( player->optype & OP_ALLIN )
return player->allin();
}
//加注
if( player->optype & OP_RASE )
{
if( player->setRandRaseCoin( 4, 5 ) == 0 )
{
if( player->optype & OP_ALLIN )
return player->allin();
}
else
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
return player->rase();
}
}
//跟注
if( player->optype & OP_CALL )
return player->call();
}
if(switchmoney > switchmoneyup)
{
if(randnum < 20)
{
if(player->optype & OP_CALL)
return player->call();
}
if(!bLargest)
{
int randrase = rand()%100;
if(randrase < 60)
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 4, 2) > 0)
return player->rase();
}
}
}
else
{
if( (card1value > 10 && card2value > 10) || (cardcolor1 == cardcolor2 ) || card1value == 0x0E || card1value == 0x0E
|| ((card1value>10 || card2value>10) && ((card1value - card2value) == 1)))
{
if(player->currMaxCoin > player->ante*15)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
if(player->optype & OP_CALL)
return player->call();
}
int temprand = rand()%100;
if(player->currMaxCoin <= player->ante*10)
{
if(player->optype & OP_CALL)
return player->call();
}
else
{
if(temprand < 30)
{
if(player->optype & OP_ALLIN)
return player->allin();
}
}
}
}
else
{
if(bLargest)
{
if( (card1value > 10 && card2value > 10) || (cardcolor1 == cardcolor2 ) || card1value == 0x0E || card1value == 0x0E
|| ((card1value>10 || card2value>10) && ((card1value - card2value) == 1)))
{
if(player->betCoinList[player->currRound] != 0)
{
if(player->optype & OP_CALL)
return player->call();
}
int randrase = rand()%100;
if(randrase < 60)
{
if((player->optype & OP_RASE))
{
if(player->setRandRaseCoin( 4, 5) > 0)
return player->rase();
}
}
}
else
{
int randrase = rand()%100;
if(randrase < 60 && player->currMaxCoin < player->ante*4)
{
if(player->optype & OP_CALL)
return player->call();
}
}
}
}
if(player->optype & OP_CHECK)
return player->check();
if(player->optype & OP_THROW)
return player->throwcard();
return 0;
}
int PlayerTimer::LeaveTimerTimeOut()
{
this->stopLeaveTimer();
player->logout();
return 0;
}
int PlayerTimer::ActiveLeaveTimeOut()
{
this->stopActiveLeaveTimer();
if(player->status != STATUS_PLAYER_ACTIVE)
{
if(player->status == STATUS_TABLE_OVER)
{
if(rand()%10 < 2)
{
player->logout();
return 0;
}
}
else
{
if(rand()%10 < 3)
{
player->logout();
return 0;
}
}
this->startActiveLeaveTimer(5+rand()%4);
}
return 0;
}
int PlayerTimer::HeatTimeOut(int uid)
{
this->stopHeartTimer();
if(player->id != uid)
{
LOGGER(E_LOG_WARNING)<< "HeatTimeOut player uid["<<player->id<<"] is not this uid["<<uid<<"]";
//_LOG_ERROR_("HeatTimeOut player uid[%d] is not this uid[%d]\n", player->id, uid);
return -1;
}
player->heartbeat();
this->startHeartTimer(uid, 30);
return 0;
}
int PlayerTimer::StartTimeOut()
{
this->stopStartGameTimer();
player->stargame();
return 0;
}
|
/*
* cppmain.cpp
*
* Created on: Dec 25, 2020
* Author: hajime
*/
#include <stdio.h>
#include "cppmain.hpp"
#include "main.h"
#include "tim.h"
#include "gpio.h"
#include "can.h"
// 設定項目
// 左クローラー:MCU_ID = 0X0A,緑LEDを点滅
// 右クローラー:MCU_ID = 0X0B,青LEDを点滅
static const int MCU_ID = 0X0A;
static const uint16_t BLINK_LED_GPIO_PIN = LED_G_Pin;
// モジュールのインクルード
#include "stm32_easy_can/stm32_easy_can.h"
void setup(void)
{
// stm32_easy_canモジュールの初期化
stm32_easy_can_init(&hcan, MCU_ID, 0X7FF);
// エンコーダスタート
HAL_TIM_Encoder_Start(&htim4, TIM_CHANNEL_ALL);
// タイマスタート
HAL_TIM_Base_Start_IT(&htim1);
}
void loop(void)
{
}
//**************************
// タイマ割り込み関数
//**************************
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
// 5msecタイマ
if (htim->Instance == TIM1) {
// エンコーダの値の計算
static int last_encoder_count = TIM4->CNT;
int encoder_count = TIM4->CNT;
int divided_encoder_count = encoder_count - last_encoder_count;
if (divided_encoder_count > MAX_ENCODER_COUNT / 2) {
divided_encoder_count -= (MAX_ENCODER_COUNT + 1);
}
else if (divided_encoder_count < -(MAX_ENCODER_COUNT / 2)) {
divided_encoder_count += (MAX_ENCODER_COUNT + 1);
}
last_encoder_count = encoder_count;
// 送信データ生成->送信
int id = (1 << 10) | MCU_ID;
unsigned char message[2];
message[0] = divided_encoder_count >> 8 & 0XFF;
message[1] = divided_encoder_count & 0XFF;
stm32_easy_can_transmit_message(id, sizeof(message), message);
// デバッグ用にLEDを点滅
static int i = 0;
if (i >= 20) {
HAL_GPIO_TogglePin(GPIOC, BLINK_LED_GPIO_PIN);
i = 0;
}
else {
i++;
}
}
}
//**************************
// CAN通信受信割り込み
//**************************
void stm32_easy_can_interrupt_handler(void)
{
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int a=10, b=10;
printf("a = %d\n",a++);
printf("a = %d\n",a);
printf("b = %d\n",++b);
printf("b = %d\n",b);
}
|
#ifndef _SHAPE_H_
#define _SHAPE_H_
#include <memory>
#include <d3d11.h>
#include <wrl\client.h>
#include <SimpleMath.h>
#pragma once
class Shape
{
public:
Shape();
~Shape();
struct VertexType
{
DirectX::SimpleMath::Vector3 position;
DirectX::SimpleMath::Vector4 color;
};
struct VertexTextureType
{
DirectX::SimpleMath::Vector3 position;
DirectX::SimpleMath::Vector2 texture;
};
struct ModelType
{
float x, y, z;
float tu, tv;
float nx, ny, nz;
};
bool Initialize(ID3D11Device* device, char* fileName);
bool Render(ID3D11DeviceContext* deviceContext);
private:
bool LoadModel(char* fileName);
bool InitializeBuffer(ID3D11Device* device);
bool RenderBuffer(ID3D11DeviceContext* deviceContext);
private:
int m_vertexCount;
int m_indexCount;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_indexBuffer;
std::unique_ptr<ModelType[]> m_model;
};
#endif // !_SHAPE_H_
|
#ifndef __Maze3D_h__
#define __Maze3D_h__
#include <ctime> //FIXME: is this portable?
#include "Cell.h"
#include "CellCoord.h"
#include "Wall.h"
#include "Prize.h"
#include "Image.h"
#include "Picture.h"
class Maze3D {
public:
const static int wMax = 30, hMax = 30, dMax = 30; // This is necessary because C++ doesn't do fully dynamic
// multidimensional arrays. I've been spoiled by Java.
const static int prizeMax = 30, pictureMax = 30; // max # of prizes, pictures
int nPrizes, nPrizesLeft, nPictures;
// The following probably belong in a Maze class.
int w, h, d; // width (x) of maze in cells
// sparsity: two passageway cells cannot be closer to each other than sparsity, unless
// they are connected as directly as possible.
int sparsity; // how sparse the maze must be
// branchClustering affects tendency for the maze to branch out as much as possible from any given cell.
// The maze will branch out as much as possible up to branchClustering branches; after that, the
// likelihood decreases. Suggested range 1-6.
int branchClustering;
// Number of cells, after maze generation, that are passage.
int numPassageCells;
// size of one cell in world coordinates. Some code might depend on cellSize = 1.0
const static float cellSize;
// margin around walls that we can't collide with; should be << cellSize.
const static float wallMargin;
static bool checkCollisions;
static clock_t whenEntered, whenSolved, lastSolvedTime;
static bool hasFoundExit, newBest;
static float exitRot; // used for rotating exit decorations
static float exitHoleRadius;
static float exitThickness;
static float edgeRadius;
static float routeRadius;
static int seeThroughRarity; // 1 out of seeThroughRarity walls will be see-through.
/* The maze consists of both cells and walls. Each wall may be shared by two cells. */
Cell (*cells)[hMax][dMax]; // The maze's cells
CellCoord ccExit, ccEntrance;
CellCoord *solutionRoute; // record of computed solution route
/* C++ doesn't support dynamic multidimensional arrays very well, hence the following cruft. */
// The maze's walls
Wall (*xWalls)[Maze3D::hMax][Maze3D::dMax]; // Walls facing along X axis [w+1][h][d]
Wall (*yWalls)[Maze3D::hMax+1][Maze3D::dMax]; // Walls facing along Y axis [w][h+1][d]
Wall (*zWalls)[Maze3D::hMax][Maze3D::dMax+1]; // Walls facing along Z axis [w][h][d+1]
// Pointers to the open "walls" at entrance and exit.
Wall *exitWall, *entranceWall;
Prize prizes[prizeMax];
Picture pictures[pictureMax];
bool hitLockedExit;
bool isGenerating; // true while maze is being generated
// Maze3D::Maze3D();
Maze3D(int _w = 8, int _h = 8, int _d = 8, int _s = 3, int _b = 2);
void setDims(int _w = 8, int _h = 8, int _d = 8, int _s = 3, int _b = 2);
void randomizeDims(void);
void incrementDims(int level);
bool IsInside(glPoint position);
// Return true if this wall is CLOSED or is entrance or exit.
inline bool IsWall(Wall *wall) {
return (wall == entranceWall || wall == exitWall || wall->state == Wall::CLOSED);
}
inline bool isExitLocked() { return (prizes && nPrizesLeft > 0); }
inline int volume() { return w * h * d; }
// estimate the number of passages that will be generated for a maze of this size and sparsity.
int estPassages() { return int((sparsity * 3 - 1) * (volume() + 0.0) / (sparsity * sparsity * sparsity)); }
void drawXEdge(int i, int j, int k, bool forbidden = false);
void drawYEdge(int i, int j, int k, bool forbidden = false);
void drawZEdge(int i, int j, int k, bool forbidden = false);
void drawOutline(void);
void drawForbidden(void);
void drawQueue(void);
void drawSolutionRoute(void);
void drawPrizes(void);
void drawPictures(void);
void drawCylinder(int x1, int y1, int z1, int x2, int y2, int z2);
int solutionRouteLen;
void computeSolution(void);
void addPrizeAt(CellCoord &cc);
void addPrizes(void);
void addPictureAt(CellCoord &cc, Wall *w, char dir, Image *image);
void addPictures(void);
void static inline glvc(int x, int y, int z) { glVertex3f(x * cellSize, y * cellSize, z * cellSize); }
// queue of cells to be expanded from next
CellCoord *queue; // only populated during maze generation
int queueSize;
private:
int fillInDeadEnd(int x, int y, int z, CellCoord *route);
};
extern Maze3D maze;
#endif // __Maze3D_h__
|
#include<iostream>
#include<string>
#include<stdexcept>
#include<postgresql/libpq-fe.h>
#include<stdlib.h>
#include<vector>
#include<climits>
#include<iomanip>
using std::cout;
using std::cin;
using std::logic_error;
using std::cerr;
using std::string;
using std::endl;
using std::vector;
using std::to_string;
using std::stoi;
using std::stof;
using std::setw;
using std::right;
using std::left;
using std::fixed;
using std::setprecision;
//function prototypesa
PGconn* connect(vector<string>&);
string clean_input(string council_name);
void query_db(string council_name, int troop_num);
//database handler (global var)
PGconn *mydb = NULL;
//global debug flag
int debug = 0;
//global var for schema that needs
//to be inputted by user
string schema;
int main(void)
{
string council_name;
int troop_num;
string db;
string temp;
cout << "Do you want to turn on debug? Y/N " ;
cin >> db;
//check for the debug flag
if(db == "Y" || db =="y")
debug = 1;
else
debug = 0;
//get necessary information for login
//connection information vector
vector<string> conn;
cout << "Enter host name of the database: ";
cin>>temp;
//get host into the connection vector
conn.push_back(temp);
//dbname
cout << "Enter database user name: ";
cin >> temp;
//put in conn vector
conn.push_back(temp);
//get password
cout << "Enter password: ";
cin >> temp;
conn.push_back(temp);
//get dbname
cout << "Enter database name: ";
cin>> temp;
//save the dbname
conn.push_back(temp);
//get the schema name
cout << "Enter schema name: ";
cin>>schema;
//connect to the db
try
{
//connect to the database
mydb = connect(conn);
}
catch(...)
{
//report another error message
cerr << "Bad connection to database!" << endl;
//exit with fail
exit(EXIT_FAILURE);
}
//get the information from the user
cout << "Enter council name: " ;
//flush the cin buffer
cin.ignore(INT_MAX, '\n');
//get a line from cin
getline(cin, council_name);
debug && cout << "Council Name Selected: " << council_name << endl;
cout << "Enter troop number: ";
cin >> troop_num;
debug && cout << "Troop Number Selected: " << troop_num << endl;
try
{
//get clean input
council_name = clean_input(council_name);
debug && cout << "The cleaned council name is: " << council_name << endl;
query_db(council_name, troop_num);
}
catch(...)
{
PQfinish(mydb);
exit(EXIT_FAILURE);
}
//close the connection
PQfinish(mydb);
return 0;
}
//connect function connects to the database using hardcoded information
//it throws an error if the connection is not established properly
PGconn* connect(vector<string>& conn)
{
//construct the connection string using user input
string connection = "host=" + conn[0] + " user=" + conn[1] + " password=" + conn[2] + " dbname=" + conn[3];
debug && cout << "Connection string: " + connection << endl;
//establish connection with the db
PGconn *mydb = PQconnectdb(connection.c_str());
//check for successful connection, if connection is not established report error
if(PQstatus(mydb) == CONNECTION_BAD)
{
cerr << "Connection to database failed with: "
<< PQerrorMessage(mydb) << endl;
throw( logic_error("Connection to database unsuccessful"));
}
else
{
//if there was successful connection report it to the console
cout << "Connection to database is successful!" << endl << endl;
}
//return the connection handler to be used above
return mydb;
}
//cleans the council name and espcapes it using the proper
//postgresql function. The function does make a call to the
//database getting the maximum council name length and comparing
//it to the length of the inputted string. If the inputted sting
//length is larger the function reports error.
string clean_input(string council_name)
{
string query = "select max(length(name)) from " + schema + ".council";
debug && cout << "Query for max length of name: " << query << endl;
//execute query to get table names out of the metadata of db
PGresult * res = PQexec(mydb, query.c_str());
if(PQresultStatus(res) != PGRES_TUPLES_OK)
{
cerr<<"Error getting the maximum council name from the database!" << endl;
cerr << "Exiting!" << endl;
PQfinish(mydb);
exit(EXIT_FAILURE);
}
//get the max number of characters the council name can be
int max_char = atoi(PQgetvalue(res,0,0));
debug && cout << "Maximum number of characters allowed for council: " << max_char << endl;
//if the string is past the maximum number of characters end the function with error Not found
if((int) council_name.length() > max_char)
{
debug && cout << "No council name found! Length of sting is too great" << endl;
throw(logic_error("No council name found!"));
}
//size of buf is 2 times size of input str + 1
int size = (council_name.length() *2) + 1;
//set up destination for escaped string
char buf[size];
//errors generated in escaping
int er;
//escape the string
PQescapeStringConn(mydb ,buf, council_name.c_str(), council_name.length(), &er);
//if error occured terminate the function
if(er != 0)
throw(logic_error("Error in escaping Council Name entered!"));
//get the new string
council_name = buf;
//shrink it to size
council_name.shrink_to_fit();
//return the new escaped string
return council_name;
}
//Assembles the query with the provided escaped infomration
//and prints the output in a table format
//the function will report empty result from the database
//on error the function exists the entire program
void query_db(string council_name, int troop_num)
{
//assemble the query
string query = "select sum(quantity),shop_sales.cookie_name,price from " +
schema + ".shop_sales, "+ schema + ".sells_for where sells_for.cookie_name "
"= shop_sales.cookie_name and shop_sales.troop_council_name = "
"sells_for.council_name and troop_number = " + to_string(troop_num) +
" and council_name = '"+ council_name +
"' group by shop_sales.cookie_name,price";
debug && cout << "Query being executed: " << endl << endl
<< query << endl;
//execute query to get table names out of the metadata of db
PGresult * res = PQexec(mydb, query.c_str());
if(PQresultStatus(res) != PGRES_TUPLES_OK)
{
cerr<<"Error contacting the database!" << endl;
cerr << "Exiting!" << endl;
PQfinish(mydb);
exit(EXIT_FAILURE);
}
//get the number of rows
int rows = PQntuples(res);
int col = PQnfields(res);
debug && cout << "Number of tuples: " << rows << endl;
debug && cout << "Number of columns: " << col << endl;
//check if we have an empty result from the db
if(rows == 0)
{
cout << "Invalid council or troop entered!" << endl;
return;
}
cout << endl << endl << endl;
cout << "-----------------------------------------------------------" << endl;
cout << setw(15) << "Number of Boxes" << setw(18) << "Cookie Type"
<< setw(26) << "Total Amount" <<endl;
cout << "-----------------------------------------------------------" << endl;
//declarations used in loop
int qty;
string temp;
float total;
//turn everything into a float by deving by this value
float constant = 1.0;
//string size type used for stof
std::string::size_type sz;
cout << fixed <<setprecision(2);
//go through the result and grab the information
//go through rows
for(int i = 0; i < rows; i++)
{
//get the number of boxes
qty = stoi(PQgetvalue(res,i,0));
debug && cout << "Quantity: " << qty << endl;
//get the get the price per box
temp = PQgetvalue(res,i,2);
debug && cout << "Value of temp: " << temp << endl;
//get rid of the dollar sign
temp = temp.substr(1, temp.length()-1);
//get the total for the type of cookies
total = qty * (stof(temp, &sz) / constant) ;
debug && cout << "Total: " << total << endl;
//print out the final result table
cout <<" "<< left << setw(15) <<PQgetvalue(res,i,0);
cout << setw(25) <<PQgetvalue(res,i,1);
cout << right << setw(6) << "$" <<total;
cout << endl;
cout << "-----------------------------------------------------------" << endl;
}
}
|
#include "ccartaoitem.h"
CCartaoItem::CCartaoItem(QObject *parent) :
QObject(parent)
{
_estudos = new CEstudos(this, this);
QObject::connect(this, SIGNAL(atualizarEstudo()), _estudos, SLOT(calcularSlot()));
}
CCartaoItem::~CCartaoItem()
{
_compras.clear();
Q_CHECK_PTR(_estudos);
delete _estudos;
}
QHash<int, QByteArray> CCartaoItem::roleNames()
{
QHash<int, QByteArray> roles;
roles[numeroRole] = "numero";
roles[descricaoRole] = "descricao";
roles[saldoRole] = "saldo";
roles[dataBeneficioRole] = "dataBeneficio";
roles[valorBeneficioRole] = "valorBeneficio";
roles[dataProximoBeneficioRole] = "dataProximoBeneficio";
roles[valorProximoBeneficioRole] = "valorProximoBeneficio";
roles[comprasRole] = "compras";
roles[estudosRole] = "estudos";
return roles;
}
QVariant CCartaoItem::data(int role)
{
switch(role) {
case numeroRole:
return this->getNumero();
break;
case descricaoRole:
return getDescricao();
break;
case saldoRole:
return getSaldo();
break;
case dataBeneficioRole:
return getDataBeneficio();
break;
case valorBeneficioRole:
return getValorBeneficio();
break;
case dataProximoBeneficioRole:
return getDataProximoBeneficio();
break;
case valorProximoBeneficioRole:
return getValorProximoBeneficio();
break;
case comprasRole:
return QVariant::fromValue(getCompras());
break;
case estudosRole:
return QVariant::fromValue(getEstudos());
break;
}
return QVariant();
}
void CCartaoItem::setDataBeneficio(QDate data)
{
_dataBeneficio = data;
emit dataChanged();
}
void CCartaoItem::setDataProximoBeneficio(QDate data)
{
_dataProximoBeneficio = data;
emit dataChanged();
}
void CCartaoItem::setValorProximoBeneficio(double valor)
{
_valorProximoBeneficio = valor;
emit dataChanged();
}
void CCartaoItem::setNumero(QString numero)
{
_numero = numero;
emit dataChanged();
}
void CCartaoItem::setDescricao(QString descricao)
{
_descricao = descricao;
emit dataChanged();
}
void CCartaoItem::setSaldo(double saldo)
{
_saldo = saldo;
emit dataChanged();
}
void CCartaoItem::setValorBeneficio(double valor)
{
_valorBeneficio = valor;
emit dataChanged();
}
QString CCartaoItem::getNumero()
{
return _numero;
}
QString CCartaoItem::getDescricao()
{
return _descricao;
}
double CCartaoItem::getSaldo()
{
return _saldo;
}
QDate CCartaoItem::getDataBeneficio()
{
return _dataBeneficio;
}
QDate CCartaoItem::getDataProximoBeneficio()
{
return _dataProximoBeneficio;
}
double CCartaoItem::getValorProximoBeneficio()
{
return _valorProximoBeneficio;
}
QList<QObject*> CCartaoItem::getCompras()
{
return _compras;
}
double CCartaoItem::getValorBeneficio()
{
return _valorBeneficio;
}
CEstudos *CCartaoItem::getEstudos()
{
return _estudos;
}
void CCartaoItem::atualizarEstudoSlot(const QString &numeroDaVez)
{
if (this->getNumero() == numeroDaVez)
emit atualizarEstudo();
}
void CCartaoItem::atualizarEstudoSlot()
{
emit atualizarEstudo();
}
|
// Created on: 1997-02-14
// Created by: Jean Yves LEBEY
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepDS_ProcessInterferencesTool_HeaderFile
#define _TopOpeBRepDS_ProcessInterferencesTool_HeaderFile
#include <TopOpeBRepDS_EXPORT.hxx>
Standard_EXPORT Handle(TopOpeBRepDS_Interference) MakeCPVInterference
(const TopOpeBRepDS_Transition& T, // transition
const Standard_Integer S, // curve/edge index
const Standard_Integer G, // point/vertex index
const Standard_Real P, // parameter of G on S
const TopOpeBRepDS_Kind GK); // POINT/VERTEX
Standard_EXPORT Handle(TopOpeBRepDS_Interference) MakeEPVInterference
(const TopOpeBRepDS_Transition& T, // transition
const Standard_Integer S, // curve/edge index
const Standard_Integer G, // point/vertex index
const Standard_Real P, // parameter of G on S
const TopOpeBRepDS_Kind GK,
const Standard_Boolean B); // G is a vertex (or not) of the interference master
Standard_EXPORT Handle(TopOpeBRepDS_Interference) MakeEPVInterference
(const TopOpeBRepDS_Transition& T, // transition
const Standard_Integer S, // curve/edge index
const Standard_Integer G, // point/vertex index
const Standard_Real P, // parameter of G on S
const TopOpeBRepDS_Kind GK, // POINT/VERTEX
const TopOpeBRepDS_Kind SK,
const Standard_Boolean B); // G is a vertex (or not) of the interference master
Standard_EXPORT Standard_Boolean FUN_hasStateShape(const TopOpeBRepDS_Transition& T,const TopAbs_State state,const TopAbs_ShapeEnum shape);
Standard_EXPORT Standard_Integer FUN_selectTRASHAinterference(TopOpeBRepDS_ListOfInterference& L1,const TopAbs_ShapeEnum sha,TopOpeBRepDS_ListOfInterference& L2);
Standard_EXPORT Standard_Integer FUN_selectITRASHAinterference(TopOpeBRepDS_ListOfInterference& L1,const Standard_Integer Index, TopOpeBRepDS_ListOfInterference& L2);
Standard_EXPORT Standard_Integer FUN_selectTRAUNKinterference(TopOpeBRepDS_ListOfInterference& L1,TopOpeBRepDS_ListOfInterference& L2);
Standard_EXPORT Standard_Integer FUN_selectTRAORIinterference(TopOpeBRepDS_ListOfInterference& L1, const TopAbs_Orientation O, TopOpeBRepDS_ListOfInterference& L2);
Standard_EXPORT Standard_Integer FUN_selectGKinterference(TopOpeBRepDS_ListOfInterference& L1,const TopOpeBRepDS_Kind GK,TopOpeBRepDS_ListOfInterference& L2);
Standard_EXPORT Standard_Integer FUN_selectSKinterference(TopOpeBRepDS_ListOfInterference& L1,const TopOpeBRepDS_Kind SK,TopOpeBRepDS_ListOfInterference& L2);
Standard_EXPORT Standard_Integer FUN_selectGIinterference(TopOpeBRepDS_ListOfInterference& L1,const Standard_Integer GI,TopOpeBRepDS_ListOfInterference& L2);
Standard_EXPORT Standard_Integer FUN_selectSIinterference(TopOpeBRepDS_ListOfInterference& L1,const Standard_Integer SI,TopOpeBRepDS_ListOfInterference& L2);
Standard_EXPORT Standard_Boolean FUN_interfhassupport(const TopOpeBRepDS_DataStructure& DS,const Handle(TopOpeBRepDS_Interference)& I,const TopoDS_Shape& S);
Standard_EXPORT Standard_Boolean FUN_transitionEQUAL(const TopOpeBRepDS_Transition&,const TopOpeBRepDS_Transition&);
Standard_EXPORT Standard_Boolean FUN_transitionSTATEEQUAL(const TopOpeBRepDS_Transition&,const TopOpeBRepDS_Transition&);
Standard_EXPORT Standard_Boolean FUN_transitionSHAPEEQUAL(const TopOpeBRepDS_Transition&,const TopOpeBRepDS_Transition&);
Standard_EXPORT Standard_Boolean FUN_transitionINDEXEQUAL(const TopOpeBRepDS_Transition&,const TopOpeBRepDS_Transition&);
Standard_EXPORT void FUN_reducedoublons(TopOpeBRepDS_ListOfInterference& LI,const TopOpeBRepDS_DataStructure& BDS,const Standard_Integer SIX);
Standard_EXPORT void FUN_unkeepUNKNOWN(TopOpeBRepDS_ListOfInterference& LI,TopOpeBRepDS_DataStructure& BDS,const Standard_Integer SIX);
Standard_EXPORT Standard_Integer FUN_select2dI(const Standard_Integer SIX, TopOpeBRepDS_DataStructure& BDS,const TopAbs_ShapeEnum TRASHAk,TopOpeBRepDS_ListOfInterference& lI, TopOpeBRepDS_ListOfInterference& l2dI);
Standard_EXPORT Standard_Integer FUN_selectpure2dI(const TopOpeBRepDS_ListOfInterference& lF, TopOpeBRepDS_ListOfInterference& lFE, TopOpeBRepDS_ListOfInterference& l2dFE);
Standard_EXPORT Standard_Integer FUN_select1dI(const Standard_Integer SIX, TopOpeBRepDS_DataStructure& BDS,TopOpeBRepDS_ListOfInterference& LI,TopOpeBRepDS_ListOfInterference& l1dI);
Standard_EXPORT void FUN_select3dinterference
(const Standard_Integer SIX, TopOpeBRepDS_DataStructure& BDS,TopOpeBRepDS_ListOfInterference& lF, TopOpeBRepDS_ListOfInterference& l3dF,
TopOpeBRepDS_ListOfInterference& lFE,TopOpeBRepDS_ListOfInterference& lFEresi,TopOpeBRepDS_ListOfInterference& l3dFE, TopOpeBRepDS_ListOfInterference& l3dFEresi,
TopOpeBRepDS_ListOfInterference& l2dFE);
#endif
|
//
// Created by Kolby on 6/19/2019.
//
#include <guiutil.h>
#include <startoptions.h>
#include <ui_startoptions.h>
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
StartOptions::StartOptions(QWidget *parent)
: QWidget(parent), ui(new Ui::StartOptions) {
ui->setupUi(this);
// Size of the icon
QSize iconSize(400 * GUIUtil::scale(), 95 * GUIUtil::scale());
// Load the icon
QPixmap icon = QPixmap(":icons/navcoin_full").scaled(iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
// Add alt text
ui->welcomeIcon->setToolTip(tr("Welcome to Navcoin!"));
// Add the icon
ui->welcomeIcon->setPixmap(icon);
}
int StartOptions::getRows() {
rows = 4;
return rows;
};
StartOptions::~StartOptions() {
delete ui;
}
|
/****************************************************************************
** Copyright (C) 2017 Olaf Japp
**
** This file is part of FlatSiteBuilder.
**
** FlatSiteBuilder is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** FlatSiteBuilder is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#ifndef INSTALLDIALOG_H
#define INSTALLDIALOG_H
#include <QDialog>
class QLineEdit;
class InstallDialog : public QDialog
{
Q_OBJECT
public:
InstallDialog();
QString installDirectory() {return m_installDirectory;}
private slots:
void installClicked();
void cancelClicked();
void chooseClicked();
private:
QString m_installDirectory;
QLineEdit *m_path;
};
#endif // INSTALLDIALOG_H
|
//////////////////////////////////////////////////////////////////////////
//
// This software is distributed under the terms of the GNU GENERAL
// PUBLIC LICENSE Version 2, June 1991. See the package LICENSE
// file for more information.
//
//////////////////////////////////////////////////////////////////////////
#ifndef CHNGPTBOOT_CC
#define CHNGPTBOOT_CC
// the following leads to many problem
//#ifndef SCYTHE_LAPACK
//#define SCYTHE_LAPACK
#include "fastgrid_helper.h"
#include "matrix.h"
#include "distributions.h"
#include "stat.h"
#include "la.h"
#include "ide.h"
#include "smath.h"
#include <R.h> // needed to use Rprintf()
#include <R_ext/Utils.h> // needed to allow user interrupts
#include <Rdefines.h>
#include <Rinternals.h>
#include <float.h> //DBL_EPSILON
#include <R_ext/Lapack.h>
#include <Rmath.h>
#define RUNIF runif
#define PRINTF Rprintf
#define MAX(A,B) ((A) > (B) ? (A) : (B))
#define MIN(A,B) ((A) < (B) ? (A) : (B))
using namespace std;
using namespace scythe;
extern "C" {
//variables such as Bcusum are defined outside this function since when bootstrapping, we do not want to allocate the memory over and over again
int _twoD_search(
Matrix<double,Row>& B, Matrix<double,Row>& r, vector<double>& x,
vector<double>& w,
vector<int>& stratified_by,
int n, int p,
int n0, int n1,
int nThresholds1, int nThresholds2,
vector<int>& thresholdIdx1, vector<int>& thresholdIdx2,
vector<double>& thresholds1, vector<double>& thresholds2,
Matrix<double,Row>& Bcusum, vector<double>& rcusum, vector<double>& Wcusum, vector<double>& xcusum,
double* logliks)
{
const int TH=2; // assume there are two thresholds
// loop index
int i,j,t1,t2,k;
// PRINTF("thresholds1\n"); for (int i=0; i<nThresholds1; i++) PRINTF("%f ", thresholds1[i]); PRINTF("\n");
// PRINTF("thresholds2\n"); for (int i=0; i<nThresholds2; i++) PRINTF("%f ", thresholds2[i]); PRINTF("\n");
// PRINTF("thresholdIdx1\n"); for (int i=0; i<nThresholds1; i++) PRINTF("%i ", thresholdIdx1[i]); PRINTF("\n");
// PRINTF("thresholdIdx2\n"); for (int i=0; i<nThresholds2; i++) PRINTF("%i ", thresholdIdx2[i]); PRINTF("\n");
// save a copy of x for potential later use, e.g. if we do threshold thinning b/c x gets updated in Step 4
vector<double> x_cpy(n);
for(i=0; i<n; i++) x_cpy[i] = x[i];
// if (!isUpperHinge) {
// // first group from 1 to n0: u==0
// Bcusum(n0-1,_) = B(n0-1,_)*w[n0-1];
// rcusum[n0-1] = r[n0-1]*w[n0-1];
// xcusum[n0-1] = x[n0-1]*w[n0-1];
// Wcusum[n0-1] = w[n0-1];
// //
// for (i=n0-2; i>=0; i--) {
// Bcusum(i,_) = Bcusum(i+1,_) + B(i,_)* w[i];
// rcusum[i] = rcusum[i+1] + r[i]* w[i];
// xcusum[i] = xcusum[i+1] + x[i]* w[i];
// Wcusum[i] = Wcusum[i+1] + w[i];
// }
// // second group from n0+1 to n: u==1
// Bcusum(n-1,_) = B(n-1,_)*w[n -1];
// rcusum[n-1] = r[n-1]*w[n -1];
// xcusum[n-1] = x[n-1]*w[n -1];
// Wcusum[n-1] = w[n-1];
// //
// for (i=n-2; i>=n0; i--) {
// Bcusum(i,_) = Bcusum(i+1,_) + B(i,_)* w[i];
// rcusum[i] = rcusum[i+1] + r[i]* w[i];
// xcusum[i] = xcusum[i+1] + x[i]* w[i];
// Wcusum[i] = Wcusum[i+1] + w[i];
// }
// } else {
// upperhinge model
// first group from 1 to n0: u==0
xcusum[0] = x[0]* w[0]* w[0];
rcusum[0] = r(0)* w[0];
Wcusum[0] = w[0]* w[0];
if(p>1) Bcusum(0,_) = B(0,_)* w[0]; // if we take out the if condition, there will be memory issue when p is 1
for (i=1; i<n0; i++) {
xcusum[i] = xcusum[i-1] + x[i]* w[i]* w[i]; // x is not prescaled, which is why w is multiplied twice
rcusum[i] = rcusum[i-1] + r(i)* w[i]; // r is prescaled
Wcusum[i] = Wcusum[i-1] + w[i]* w[i]; // w is sqrt of true weights
if(p>1) Bcusum(i,_) = Bcusum(i-1,_) + B(i,_)* w[i]; // B is prescaled
}
// second group from n0+1 to n: u==1
xcusum[n0] = x[n0]* w[n0]* w[n0];
rcusum[n0] = r(n0)* w[n0];
Wcusum[n0] = w[n0]* w[n0];
if(p>1) Bcusum(n0,_) = B(n0,_)* w[n0]; // if we take out the if condition, there will be memory issue when p is 1
for (i=n0; i<n; i++) {
xcusum[i] = xcusum[i-1] + x[i]* w[i]* w[i]; // x is not prescaled, which is why w is multiplied twice
rcusum[i] = rcusum[i-1] + r(i)* w[i]; // r is prescaled
Wcusum[i] = Wcusum[i-1] + w[i]* w[i]; // w is sqrt of true weights
if(p>1) Bcusum(i,_) = Bcusum(i-1,_) + B(i,_)* w[i]; // B is prescaled
}
//for (i=0; i<n; i++) {for (j=0; j<p; j++) PRINTF("%f ", Bcusum(i,j)); PRINTF("\n");}
Matrix <double,Row,Concrete> vB (TH, p, true, 0), vv (TH, TH, true, 0), vr (TH, 1, true, 0);
Matrix <double,Row,Concrete> vB2(TH, p, true, 0), vv2(TH, TH, true, 0), vr2(TH, 1, true, 0); // a second copy for updating across the second threshold
double delta;
// Step 3: Initialize vv, vr and vB
// if (!isUpperHinge) {
// // (x-e)+
// for(i=0; i<thresholdIdx1[0]; i++) x[i]=0;
// for(i=thresholdIdx1[0]; i<n0; i++) x[i]=x[i]-thresholds1[0];
// for(i=n0; i<thresholdIdx2[0]; i++) x[i]=0;
// for(i=thresholdIdx2[0]; i<n ; i++) x[i]=x[i]-thresholds2[0];
// } else {
// (x-e)-
for(i=0; i<thresholdIdx1[0]; i++) x[i]=x[i]-thresholds1[0];
for(i=thresholdIdx1[0]; i<n0; i++) x[i]=0;
for(i=n0; i<thresholdIdx2[0]; i++) x[i]=x[i]-thresholds2[0];
for(i=thresholdIdx2[0]; i<n ; i++) x[i]=0;
// PRINTF("x_cpy, xcusum, x, r\n"); for (i=0; i<n; i++) {PRINTF("%f ", x_cpy[i]); PRINTF("%f ", xcusum[i]); PRINTF("%f ", x[i]); PRINTF("%f ", r[i]); PRINTF("\n");}
// we may be able to make this more efficient by changing summation index since we know some of the x's are 0
// vv is v'v
for (i=0 ; i<n0; i++) vv(0,0) += pow(x[i],2);
for (i=n0; i<n ; i++) vv(1,1) += pow(x[i],2);
for (i=0 ; i<n0; i++) vr(0,0) += x[i]*r[i];
for (i=n0; i<n ; i++) vr(1,0) += x[i]*r[i];
for (j=0; j<p; j++) {
for (i=0; i<n0; i++) vB(0,j) += x[i] * B(i,j);
for (i=n0; i<n; i++) vB(1,j) += x[i] * B(i,j);
}
// save a copy for updating across the first row
vv2=vv; vr2=vr; vB2=vB;
// PRINTF("vv2:\n"); for (i=0; i<TH; i++) {for (j=0; j<TH; j++) PRINTF("%f ", vv2(i,j)); PRINTF("\n");}
// for (i=0; i<TH; i++) PRINTF("%f ", vr[i]); PRINTF("\n");
// for (i=0; i<TH; i++) {for (j=0; j<p; j++) PRINTF("%f ", vB(i,j)); PRINTF("\n");}
//Matrix <double,Row,Concrete> dtmp=vv - vB * t(vB);
//for (i=0; i<TH; i++) {for (j=0; j<TH; j++) PRINTF("%f ", dtmp(i,j)); PRINTF("\n");}
int which=0, chosen;
double crit, crit_max;
// Step 4: Compute criterion function
crit = (t(vr) * invpd(vv - vB * t(vB)) * vr)[0];
logliks[which++] = crit;
chosen=which-1; crit_max=crit;
// Step 5:
for(t2=0; t2<nThresholds2; t2++) {
// update vv2/vr2/vB2 for the first row
if(t2>0) {
// Step 5a for updating across the first row: update vv2, vr2 and vB2
delta= thresholds2[t2]-thresholds2[t2-1];
// if (!isUpperHinge) {
// iB = thresholdIdx2[t2]-1;
// k = n-thresholdIdx2[t2]+1; // the current threshold is the kth largest
// vv2(1,1) -= 2 * delta * (xcusum[iB] - k*thresholds2[t2-1]) - k * pow(delta,2);
// vr2(1,0) -= delta * rcusum[iB];
// for (j=0; j<p; j++) vB2(1,j) -= delta * Bcusum(iB,j);
// } else {
k = thresholdIdx2[t2-1]; // k is 1-based index of x, e_t = x_k
// if (t2==1){
// PRINTF("vv2:\n"); for (i=0; i<TH; i++) {for (j=0; j<TH; j++) PRINTF("%f ", vv2(i,j)); PRINTF("\n");}
// }
vv2(1,1) -= 2*delta*(xcusum[k-1]-xcusum[n0-1] - (Wcusum[k-1]-Wcusum[n0-1])*thresholds2[t2-1]) - (Wcusum[k-1]-Wcusum[n0-1]) * pow(delta,2);
vr2(1,0) -= delta * (rcusum[k-1]-rcusum[n0-1]);
for (j=0; j<p; j++) vB2(1,j) -= delta * (Bcusum(k-1,j)-Bcusum(n0-1,j)); //j<p not j<p-1 b/c Bcusum here has a different dimension from fastgrid2.cc
vv=vv2; vr=vr2; vB=vB2; // copy to vv/vr/vB for updating columns
// if (t2==1){
// PRINTF("delta %f\n", delta);
// PRINTF("vv\n"); for (i=0; i<TH; i++) {for (j=0; j<TH; j++) PRINTF("%f ", vv(i,j)); PRINTF("\n");}
// PRINTF("vr\n"); for (i=0; i<TH; i++) PRINTF("%f ", vr[i]); PRINTF("\n");
// PRINTF("vB\n"); for (i=0; i<TH; i++) {for (j=0; j<p; j++) PRINTF("%f ", vB(i,j)); PRINTF("\n");}
// Matrix <double,Row,Concrete> dtmp=vB * t(vB);
// PRINTF("vB * t(vB)\n"); for (i=0; i<TH; i++) {for (j=0; j<TH; j++) PRINTF("%f ", dtmp(i,j)); PRINTF("\n");}
// }
// Step 5b: Compute criterion function
crit = (t(vr2) * invpd(vv2 - vB2 * t(vB2)) * vr2)[0];
logliks[which++] = crit;
if(crit>=crit_max) {chosen = which-1; crit_max=crit;}
}
// update vv/vr/vB for columns
for(t1=1; t1<nThresholds1; t1++) {
// Step 5a for updating columns: update vv, vr and vB
delta= thresholds1[t1]-thresholds1[t1-1];
// if (!isUpperHinge) {
// iB = thresholdIdx1[t1]-1;
// k = n0-thresholdIdx1[t1]+1; // the current threshold is the kth largest
// vv(0,0) -= 2 * delta * (xcusum[iB] - k*thresholds1[t1-1]) - k * pow(delta,2);
// vr(0,0) -= delta * rcusum[iB];
// for (j=0; j<p; j++) vB(0,j) -= delta * Bcusum(iB,j);
// } else {
// upperhinge model
k = thresholdIdx1[t1-1]; // k is 1-based index of x, e_t = x_k
vv(0,0) -= 2*delta*(xcusum[k-1] - Wcusum[k-1]*thresholds1[t1-1]) - Wcusum[k-1]*pow(delta,2);
vr(0,0) -= delta * rcusum[k-1];
for (j=0; j<p; j++) vB(0,j) -= delta * Bcusum(k-1,j);
// if (t1==1 && t2==0){
// PRINTF("vv\n"); for (i=0; i<TH; i++) {for (j=0; j<TH; j++) PRINTF("%f ", vv(i,j)); PRINTF("\n");}
// PRINTF("vr\n"); for (i=0; i<TH; i++) PRINTF("%f ", vr[i]); PRINTF("\n");
// PRINTF("vB\n"); for (i=0; i<TH; i++) {for (j=0; j<p; j++) PRINTF("%f ", vB(i,j)); PRINTF("\n");}
// Matrix <double,Row,Concrete> dtmp=vB * t(vB);
// PRINTF("vB * t(vB)\n"); for (i=0; i<TH; i++) {for (j=0; j<TH; j++) PRINTF("%f ", dtmp(i,j)); PRINTF("\n");}
// }
// Step 5b: Compute criterion function
crit = (t(vr) * invpd(vv - vB * t(vB)) * vr)[0];
logliks[which++] = crit;
if(crit>=crit_max) {chosen = which-1; crit_max=crit;}
} // end for t1
} // end for t2
return chosen;
}
//// X gets written over when the function is done
//void _preprocess2(Matrix<double,Row>& X, Matrix<double,Row>& Y, vector<double>& r) {
// int i,j;
// int p=X.cols();
// int n=X.rows();
//
////// R code: for reference only
//// A <- solve(t(Z.sorted) %*% Z.sorted)
//// H <- Z.sorted %*% A %*% t(Z.sorted)
//// r <- as.numeric((diag(n)-H) %*% y.sorted)
//// a.eig <- eigen(A)
//// A.sqrt <- a.eig$vectors %*% diag(sqrt(a.eig$values)) %*% solve(a.eig$vectors)
//// B = Z.sorted %*% A.sqrt
//
// Matrix<> A = invpd(crossprod(X));
//
// Matrix <> resid = Y - X * A * (t(X) * Y);
// // copy to r
// for (i=0; i<n; i++) r[i]=resid[i];
//
// // eigen decomposition to get B
// Eigen Aeig = eigen(A);
// Matrix <double,Row,Concrete> A_eig (p, p, true, 0);
// for (j=0; j<p; j++) A_eig(j,j)=sqrt(Aeig.values(j));
// Matrix<> B = X * (Aeig.vectors * A_eig * t(Aeig.vectors));
// // Do this last: replace the first p column of X with B
// for (j=0; j<p; j++) X(_,j)=B(_,j);
//
// //PRINTF("A\n"); for (i=0; i<p; i++) {for (j=0; j<p; j++) PRINTF("%f ", A(i,j)); PRINTF("\n");}
// //PRINTF("eigen values\n"); for (j=0; j<p; j++) PRINTF("%f ", Aeig.values(j)); PRINTF("\n");
// //PRINTF("B\n"); for (i=0; i<n; i++) {for (j=0; j<p; j++) PRINTF("%f ", B(i,j)); PRINTF("\n");}
//}
// For fastgrid,
// assume X and Y are sorted
// thresholdIdx are 1-based index, which define the grid of thresholds
// For fastgrid2, the meaning of the first two variables are B and r instead
SEXP twoD_gaussian(
SEXP u_X,
SEXP u_x,
SEXP u_Y,
SEXP u_W,
SEXP u_stratified_by,
//SEXP u_thresholdIdx1, SEXP u_thresholdIdx2,
SEXP u_lb, SEXP u_ub,
SEXP u_nBoot,
SEXP u_verbose
){
double* X_dat = REAL(u_X);
double* x_dat = REAL(u_x);
double* Y_dat=REAL(u_Y);
double* W_dat=REAL(u_W);
int* stratified_by_dat = INTEGER(u_stratified_by);
// int *thresholdIdx1=INTEGER(u_thresholdIdx1);
// int *thresholdIdx2=INTEGER(u_thresholdIdx2);
// int n0 = asInteger(u_n0);
// int n1 = asInteger(u_n1);
double lb = asReal(u_lb);
double ub = asReal(u_ub);
int verbose=asInteger(u_verbose);
int nBoot = asInteger(u_nBoot);
const int n = nrows(u_X);
const int p = ncols(u_X); // number of predictors, not including the thresholed variable since u_added is separated out
// int nThresholds1=length(u_thresholdIdx1);
// int nThresholds2=length(u_thresholdIdx2);
//PRINTF("thresholdIdx: "); for (int i=0; i<nThresholds; i++) PRINTF("%i ", thresholdIdx[i]); PRINTF("\n");
Matrix<double,Col,Concrete> Xcol (n, p, X_dat); //The rows and colns are organized in a way now that they can be directly casted into column major, and there is no need to do things as in the JSS paper on sycthe or MCMCpack MCMCmetrop1R.cc
Matrix<double,Row,Concrete> X(Xcol); // convert to row major so that creating bootstrap datasets can be faster and to pass to _grid_search
Matrix<double,Row,Concrete> Y(n, 1, Y_dat); // define as a matrix instead of vector b/c will be used in matrix operation
vector<double> x(x_dat, x_dat + n); // this does not need to be converted into vectors, but better to do so for consistency with bootstrap code
vector<int> stratified_by(stratified_by_dat, stratified_by_dat + n); // this does not need to be converted into vectors, but better to do so for consistency with bootstrap code
vector<double> W(W_dat, W_dat + n); // this does not need to be converted into vectors, but better to do so for consistency with bootstrap code
//vector<double> r(n); // residual vector
// these variables are reused within each bootstrap replicate
Matrix <double,Row,Concrete> Bcusum(n, p);
vector<double> rcusum(n), Wcusum(n), xcusum(n);
int i,j;
if (nBoot<0.1) {
// a single search
// define thresholds and thresholdIdx
int n1=0; for(i=0; i<n; i++) n1+=stratified_by[i];
int n0=n-n1;
int nLower1=(int)round(n0*lb)+1, nUpper1=(int)round(n0*ub);
int nLower2=(int)round(n1*lb)+1, nUpper2=(int)round(n1*ub);
int nThresholds1=nUpper1-nLower1+1;
int nThresholds2=nUpper2-nLower2+1;
vector<int> thresholdIdx1(nThresholds1), thresholdIdx2(nThresholds2);
vector<double> thresholds1 (nThresholds1), thresholds2 (nThresholds2);
for(i=0; i<nThresholds1; i++) {
thresholdIdx1[i]=nLower1+i;
thresholds1[i]=x[thresholdIdx1[i]-1];
}
for(i=0; i<nThresholds2; i++) {
thresholdIdx2[i]=nLower2+i+n0;
thresholds2[i]=x[thresholdIdx2[i]-1];
}
//PRINTF("n0 %d n1 %d\n", n0, n1);
//PRINTF("nThresholds1 %d nThresholds2 %d\n", nThresholds1, nThresholds2);
//for (i=0; i<nThresholds1; i++) PRINTF("%f ", thresholds1[i]); PRINTF("\n");
//for (i=0; i<nThresholds2; i++) PRINTF("%f ", thresholds2[i]); PRINTF("\n");
SEXP _logliks=PROTECT(allocVector(REALSXP, nThresholds1*nThresholds2));
double *logliks=REAL(_logliks);
// compute Y'HY. this is not needed to find e_hat, but good to have for comparison with other estimation methods
// this needs to be done before step 2 since X gets changed by _preprocess
double yhy = ((t(Y) * X) * invpd(crossprod(X)) * (t(X) * Y))(0);
//PRINTF("yhy: %.4f\n", yhy);
// Step 1. Sort
// Data input should be already sorted.
// Step 2. Compute B and r. X is replaced by B when the function is done.
_preprocess(X, Y);
//PRINTF("B\n"); for (int i=0; i<n; i++) {for (int j=0; j<p; j++) PRINTF("%f ", X(i,j)); PRINTF("\n");}
//PRINTF("Y\n"); for (int i=0; i<n; i++) PRINTF("%f ", Y(i)); PRINTF("\n");
_twoD_search(X, Y, x,
W,
stratified_by,
n, p,
n0, n1,
nThresholds1, nThresholds2,
thresholdIdx1, thresholdIdx2,
thresholds1, thresholds2,
Bcusum, rcusum, Wcusum, xcusum,
logliks);
for(i=0; i<nThresholds1*nThresholds2; i++) logliks[i]=logliks[i]+yhy;
if(verbose>0) for(int t1=0; t1<nThresholds1; t1++) { {for(int t2=0; t2<nThresholds2; t2++) PRINTF("%.4f ", logliks[t1+n1*t2]);} PRINTF("\n");}
UNPROTECT(1);
return _logliks;
} else {
// bootstrap
// difference from single search is that we are not return liklihoods but parameter estimates from bootstrap datasets
// output variables
// logliks will not be returned to R, estimates from each bootstrap copy will be stored in coef and returned
// to avoid allocating space for logliks for each bootstrap replicate, we allocate a big enough space just once
double * logliks = (double *) malloc((n*n) * sizeof(double));
SEXP _coef=PROTECT(allocVector(REALSXP, nBoot*(p+2+2)));// p slopes, 2 thresholds and 2 threshold-related slopes
double *coef=REAL(_coef);
// these variables are reused within each bootstrap replicate
vector<int> index(n);
Matrix <double,Row,Concrete> Zb(n,p), Yb(n,1), Xbreg(n,p+2);
vector<double> xb(n), Wb(n), rb(n);
vector<int> stratified_by_b(n);
double e_hat, f_hat;
int chosen;
for (int b=0; b<nBoot; b++) {
// create bootstrap dataset, note that index is 1-based
SampleReplace(n, n, &(index[0]));
// Step 1: sort
sort (index.begin(), index.end());
for (i=0; i<n; i++) { //note that index need to -1 to become 0-based
Zb(i,_)=X(index[i]-1,_);
Yb[i] =Y[index[i]-1];
xb[i] =x[index[i]-1];
Wb[i] =W[index[i]-1];
stratified_by_b[i]=stratified_by[index[i]-1];
}
//for (i=0; i<n; i++) PRINTF("%f ", xb[i]); PRINTF("\n");
//for (i=0; i<n; i++) PRINTF("%d ", stratified_by_b[i]); PRINTF("\n");
//for (i=0; i<n; i++) {for (j=0; j<p; j++) PRINTF("%f ", Zb(i,j)); PRINTF("\n");}
//for (i=0; i<n; i++) { Zb(i,_)=X(i,_); Yb(i)=Y(i); Wb[i]=W[i]; } // debug use, can be used to compare with non-boot
// define thresholds and thresholdIdx
// these need to be redefined for every bootstrap replicate b/c n0 and n1 could change in bootstrap
int n1=0; for(i=0; i<n; i++) n1+=stratified_by_b[i];
int n0=n-n1;
int nLower1=(int)round(n0*lb)+1, nUpper1=(int)round(n0*ub);
int nLower2=(int)round(n1*lb)+1, nUpper2=(int)round(n1*ub);
int nThresholds1=nUpper1-nLower1+1;
int nThresholds2=nUpper2-nLower2+1;
vector<int> thresholdIdx1(nThresholds1), thresholdIdx2(nThresholds2);
vector<double> thresholds1 (nThresholds1), thresholds2 (nThresholds2);
for(i=0; i<nThresholds1; i++) {
thresholdIdx1[i]=nLower1+i;
thresholds1[i]=xb[thresholdIdx1[i]-1];
}
for(i=0; i<nThresholds2; i++) {
thresholdIdx2[i]=nLower2+i+n0;
thresholds2[i]=xb[thresholdIdx2[i]-1];
}
//PRINTF("n0 %d n1 %d\n", n0, n1);
//PRINTF("nThresholds1 %d nThresholds2 %d\n", nThresholds1, nThresholds2);
//for (i=0; i<nThresholds1; i++) PRINTF("%f ", thresholds1[i]); PRINTF("\n");
//for (i=0; i<nThresholds2; i++) PRINTF("%f ", thresholds2[i]); PRINTF("\n");
// Step 2:
_preprocess(Zb, Yb);
// Step 3-5
chosen = _twoD_search(Zb, Yb, xb,
Wb,
stratified_by_b,
n, p,
n0, n1,
nThresholds1, nThresholds2,
thresholdIdx1, thresholdIdx2,
thresholds1, thresholds2,
Bcusum, rcusum, Wcusum, xcusum,
logliks);
e_hat=thresholds1[chosen % nThresholds1];
f_hat=thresholds2[chosen / nThresholds1];
//PRINTF("chosen %d\n", chosen);
//PRINTF("e_hat %f\n", e_hat); PRINTF("f_hat %f\n", f_hat);
// fit model at the selected threshold and save results in coef
// after _preprocess2, Zb and Yb have changed, thus we need to copy from X and Y again
for (i=0; i<n; i++) {
Yb(i,0)=Y(index[i]-1,0);
for (j=0; j<p; j++) Xbreg(i,j)=X(index[i]-1,j);
}
for(i=0; i<n0; i++) {
Xbreg(i,p) = x[index[i]-1]>e_hat?0:x[index[i]-1]-e_hat;
Xbreg(i,p+1) = 0;
}
for(i=n0; i<n; i++) {
Xbreg(i,p) = 0;
Xbreg(i,p+1) = x[index[i]-1]>f_hat?0:x[index[i]-1]-f_hat;
}
//PRINTF("Xbreg\n"); for (i=0; i<n; i++) {for (j=0; j<p+2; j++) PRINTF("%f ", Xbreg(i,j)); PRINTF("\n");}
//PRINTF("Yb\n"); for (i=0; i<n; i++) PRINTF("%f ", Yb(i)); PRINTF("\n");
//PRINTF("Zb\n"); for (i=0; i<n; i++) {for (j=0; j<p; j++) PRINTF("%f ", Zb(i,j)); PRINTF("\n");}
//PRINTF("Yb\n"); for (i=0; i<n; i++) PRINTF("%f ", Yb(i)); PRINTF("\n");
// for (i=0; i<n; i++) { Zb(i,_)=X(i,_); Yb(i)=Y(i); } // debug use
Matrix <> beta_hat = invpd(crossprod(Xbreg)) * (t(Xbreg) * Yb);
//PRINTF("beta_jat\n"); for (i=0; i<p+2; i++) PRINTF("%f ", beta_hat[i]); PRINTF("\n");
for (j=0; j<p+2; j++) coef[b*(p+4)+j]=beta_hat[j];
coef[b*(p+4)+p+2] = e_hat;
coef[b*(p+4)+p+3] = f_hat;
}
UNPROTECT(1);
free(logliks);
return _coef;
}
}
} // end extern C
#endif
//#endif
|
/*
/home/pi/.arduino15/packages/stm32duino/hardware/STM32F1/2020.6.20/cores/maple/libmaple
*/
//#include <Wire.h>
#ifdef MCU_STM32F103C8
auto &ser = Serial1;
#else
auto &ser = Serial;
#endif
#define SID 4
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
#define __IO volatile
#define REG(x) *(volatile uint32_t *)(x)
typedef struct {
__IO u32 CR1; //0x00
__IO u32 CR2; // 0x04
__IO u32 OAR1; //0x08
__IO u32 OAR2; //0x0C
__IO u32 DR; //0x10
__IO u32 SR1; //0x14
__IO u32 SR2; //0x18
__IO u32 CCR; // 0x1C
__IO u32 TRISE; // 0x20
} I2C_t;
#define I2C1_ ((I2C_t*) (0x40005400))
#define I2C2_ ((I2C_t*) (0x40005800))
//#define I2C_ I2C1_
#define I2C_CR1_PE (1<<0)
#define RCC_BASE 0x40021000
#define RCC_APB1ENR *(volatile uint32_t *)(RCC_BASE + 0x1C) // page 148
#define RCC_APB2ENR *(volatile uint32_t *)(RCC_BASE + 0x18)
#define RCC_APB2ENR_AFIOEN (1<<0)
typedef struct
{
__IO uint32_t CRL; // 0x00
__IO uint32_t CRH; // 0x04
__IO uint32_t IDR; // 0x08
__IO uint32_t ODR; // 0x0C
__IO uint32_t BSRR; // 0x10
__IO uint32_t BRR; // 0x14
__IO uint32_t LCKR; //0x18
} GPIO_t;
#define GPIO_BASE 0x40010800
#define GPIOA ((GPIO_t*) (GPIO_BASE + 0x000))
#define GPIOB ((GPIO_t*) (GPIO_BASE + 0x400))
void pu32(char* str, u32 v) {
ser.print(str);
ser.print(v);
ser.print(" 0b");
for (int i = 0; i < 8; i++) {
if (i) ser.print("'");
for (int j = 0; j < 4; j++) {
//u32 x = v & (0b10000000000000000000000000000000);
u32 x = v & (1 << 31);
if (x > 0) {
ser.print(1);
} else {
ser.print(0);
}
v = (v << 1);
}
}
ser.println("");
}
// stm32 i2c pt 1
// https://www.youtube.com/watch?v=TqUzQfMGlfI
// part 2
// https://www.youtube.com/watch?v=ZVeG25cMe58
/* send addr 1 means read, 0 meand write in LSB, but maybe only for AT32C02
*/
#define I2C_CR1_PE (1<<0)
#define RCC_APB1ENR_I2C1EN (1<<21)
#define I2C_CR1_ACK (1<<10)
#define I2C_CR1_START (1<<8)
#define I2C_CR1_STOP (1<<9)
#define I2C_SR1_TXE (1<<7)
#define I2C_SR1_RXNE (1<<6)
#define I2C_SR1_ADDR (1<<1)
void my_init_i2c() // this seems to be correct
{
//RCC->AB1ENR &= ~(RCC_APB1ENR_I2CEN);
//I2C2->CR1 = 0X00;
//I2C2->CR2 = 0X00;
RCC_APB2ENR |= RCC_APB2ENR_IOPBEN | RCC_APB2ENR_AFIOEN;
RCC_APB1ENR |= RCC_APB1ENR_I2C1EN;
I2C1_->CR2 |= 36; // FREQ OF APB1 BUS = 72MHZ/2 = 36MHZ
/* TAKE THE PERIOS OF THE FREQ SET INTO CR2 EX: 1/10MHZ = 100NS
NOW PICK A FREQ YOU WANT THE I2C TO RUN AT (MAX 100KHZ IN STD
MODE) (400KHZ MAX IN FAST MODE)
THEN IF IN STD MODE GET THE PERIOD OF THAT FREQ
EX:1/100KHZ = 10US THEN DIVIDE BY 2 TO GET THE
HTIME BECAUSE THE DUTY CYCLE IS 50% SO HIGH TIME AND LOW TIME
IS THE SAME SO WE JUST DIVIDE PERIOD BY 2 TO GET
5US
THEN CCR REGISTER = 5US/100NS = 50
SOO CCR IS 50, THIS IS THE MAX TIME THE I2C WILL WAIT FOR A
RISE TIME AND NOT NECESSARILY THE RISE TIME THAT IT WILL
ACTUALLY
*/
I2C1_->CCR |= 180; // SPEED TO 100KHZ STD MODE MAX: I2C_PERIOD /2 * ABI = (1/100K/2)*36MHZ
I2C1_->TRISE |= 37; // 1000NS/(CR2 PERIOD=1/36MHZ) = TRISE +1
I2C1_->CR1 |= I2C_CR1_ACK ; // ENABLE ACKS
// stretch mode enabled by default
// 7 bit addressing mode enabled by default
GPIOB->CRL = 0b11111111010010000100010001000100;
I2C1_->CR1 |= I2C_CR1_PE; // ENABLE PERIPHERAL
}
#define RCC_AHBENR REG(RCC_BASE + 0x14)
#define RCC_AHBENR_DMA1EN (1<<0)
#define I2C_CR2_DMAEN (1<<11)
typedef struct {
__IO u32 CCR;
__IO u32 CNDTR;
__IO u32 CPAR;
__IO u32 CMAR;
__IO u32 RESERVED;
} DMA_CHAN_t;
typedef struct
{
__IO u32 ISR;
__IO u32 IFCR;
DMA_CHAN_t CHAN1;
DMA_CHAN_t CHAN2;
DMA_CHAN_t CHAN3;
DMA_CHAN_t CHAN4;
DMA_CHAN_t CHAN5;
DMA_CHAN_t CHAN6;
DMA_CHAN_t CHAN7;
} DMA_t;
//#define GPIO_BASE 0x40010800
#define DMA1 ((DMA_t*) (0x40020000))
#define DMA2 ((DMA_t*) (0x40020400))
#define DMA_CCR_TCIE (1<<1)
#define DMA_CCR_MINC (1<<7)
#define DMA_CCR_EN (1<<0)
#define DMA_CCR_DIR (1<<4)
#define DMA_ISR_TCIF5 (1<<17)
#define DMA_ISR_TCIF7 (1<<25)
#define I2C_SR1_SB (1<<0)
u8 i2c_buff[10];
void i2c_read_dma(u8 sid, u8* buffer, u32 len)
{
//u32 temp =0;
//i2c_buff[0] = 0x00;
//rcc->ahbenr |= RCC_AHBENR_DMA1EN;
RCC_AHBENR |= RCC_AHBENR_DMA1EN;
I2C1_->CR2 |= I2C_CR2_DMAEN;
I2C1_->CR1 |= I2C_CR1_ACK; // ENABLE ACKS
#define CHAN DMA1->CHAN7
//DMA1_CHANNEL5->CMAR = (U32)I2C_BUFF;
CHAN.CMAR = (u32)i2c_buff;
//DMA1_CHANNEL5->CPAR = (U32)&I2C2->DR;
CHAN.CPAR = (u32)(&(I2C1_->DR));
//DMA1_CHANNEL5->CNDTR = len;
CHAN.CNDTR = len;
//DMA1_CHANNEL5->CCR |= DMA_CCR4_TCIE | DMA_CCR5_MINC | DMA_CCR5_EN;
//CHAN.CCR = DMA_CCR_TCIE | DMA_CCR_MINC | DMA_CCR_EN;
//CHAN.CCR |= DMA_CCR_DIR; // added by mcarter . not helps
//DMA1->IFCR |= DMA_ISR_TCIF7; // added by mcarter. hinders-t
CHAN.CCR = DMA_CCR_MINC | DMA_CCR_EN;
I2C1_->CR1 |= I2C_CR1_START;
#define I2C_CR2_LAST (1<<12)
I2C1_->CR2 |= I2C_CR2_LAST; // added mcarter help-f
ser.print(".");
//ser.println(DMA1->ISR & DMA_ISR_TCIF7);
while (!(I2C1_->SR1 & I2C_SR1_SB));
I2C1_->DR = (sid << 1) + 1; // WRITE 0XA0; // SEND ADDR
ser.print("-");
while (!(I2C1_->SR1 & I2C_SR1_ADDR));
u32 temp = I2C1_->SR2;
ser.print("<"); //seems to reach here
while (!(DMA1->ISR & DMA_ISR_TCIF7));
//I2C1_->SR2; // added by mcarter. help-f
ser.print(">"); // no seems to reach here
I2C1_->CR1 |= I2C_CR1_STOP;
DMA1->IFCR |= DMA_ISR_TCIF7; // added by mcarter. hinders-?
CHAN.CCR &= ~DMA_CCR_EN; // added mcarter. Seems to help clear DMA_ISR_TCIF7
}
void i2c_read(u8 sid, u8* buffer, u32 len)
{
I2C1_->CR1 |= I2C_CR1_ACK; // ENABLE ACKS
I2C1_->CR1 |= I2C_CR1_START;
ser.print(".");
while (!(I2C1_->SR1 & I2C_SR1_SB));
I2C1_->DR = (sid << 1); // WRITE 0XA0; // SEND ADDR
while (!(I2C1_->SR1 & I2C_SR1_ADDR));
(void)I2C1_->SR2;
ser.print("1");
I2C1_->DR = (u32)i2c_buff; //ADDRESS TO RWITE TO
while (!(I2C1_->SR1 & I2C_SR1_TXE));
(void)I2C1_->SR2;
ser.print("2");
// COULR DO THIS MULTIPLE TIMES TO SEND LOTS OF DATA
//I2C2->DR = DATA;
while (!(I2C1_->SR1 & I2C_SR1_RXNE));
(void)I2C1_->SR2;
ser.print("3");
I2C1_->CR1 |= I2C_CR1_STOP;
}
// using dma is easier, and seems to be recommended
// I2C is on APB1. runs at half the clock speed. So, if 72MHz, it will run at 36MHz
#ifdef TUTORIAL
VOID I2C_WRITE_SINGLE(U8 SID, I8 MEM_ADDR, U8 DATA)
{
U32 TEMP;
I2C2->CR1 |= I2C2_CR1_START; // GENERATE A START CONDITION
WHILE(!(I2C2->SR1 & I2C_SR1_SB));
I2C2->DR = SID;
WHILE(!(I2C2->SR1 & I2C2_SR1_ADDR));
TEMP = I2C2->SR2;
I2C2->DR = MEM_ADDR; //ADDRESS TO RWITE TO
WHILE(!(I2C2->SR1 & I2C2_SR1_TXE));
// COULR DO THIS MULTIPLE TIMES TO SEND LOTS OF DATA
I2C2->DR = DATA;
WHILE(!(I2C2->SR1 & I2C_SR1_TXE));
I2C2->CR1 |= I2C_CR1_STOP;
}
// taken from stm8
static void begin_i2c_write(uint8_t slave_id)
{
I2C_CR2 |= I2C_CR2_ACK; // set ACK
I2C_CR2 |= I2C_CR2_START; // send start sequence
while (!(I2C_SR1 & I2C_SR1_SB));
I2C_DR = slave_id << 1; // send the address and direction
while (!(I2C_SR1 & I2C_SR1_ADDR));
(void)I2C_SR3; // read SR3 to clear ADDR event bit
}
#endif //TUTORIAL
void setup()
{
ser.begin(115200); // start serial for output
ser.println("i2c master here 5");
//pu32("I2C1_->CR1", I2C1_->CR2);
#if 0
Wire.begin(); // join i2c bus (address optional for master)
#else
my_init_i2c();
#endif
//pu32("I2C1_->CR1", I2C1_->CR2);
}
void loop()
{
static int i = 0;
//goto foo;
ser.println("Begin reading attempt " + String(i++));
i2c_read_dma(SID, 0, 1);
ser.println(i2c_buff[0]); // print the character
//ser.println(i2c_buff[1]); // print the character
delay(1000);
return;
#if 0
foo:
Wire.requestFrom(4, 1); // request 1 byte from slave device address 4
while (Wire.available()) // slave may send less than requested
{
int i = Wire.read(); // receive a byte as character
ser.println(i); // print the character
}
delay(1000);
#endif
}
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Игра, генерирующая случайное число в диапазоне, отбрасывающая повторы
// При первом старте генеруируется случайное число, которое заносится в фиксированный массив.
// Следующее за первым число сравнимается с первым и, если нет повтора, то оно заносится в
// фиксированный массив в следующий индекс и так до n-количество раз.
// Если обнаружен повтор, то программа его игнорирует и возвращается к генерации числа.
// В программе ещё куча отладночной ин-фы.
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
int getRandomNum(int min, int max);
int main() {
using namespace std;
srand(static_cast<unsigned int>(time(0)));
vector<int> arr = {0};
cout << "Содержимое массива до измненения: " << arr[0];
arr.push_back(25); // Вставляем число в массив
cout << "Содержимое массива после измненения: ";
cout << " : " << arr[1];
cout << "\n\n";
int count = 0;
do {
++count;
int randNum = getRandomNum(1, 10); // Генерируем случайное число
cout << randNum << endl;
}
while (count != 10);
return 0;
}
int getRandomNum(int min, int max)
{
// Генерируем рандомное число между значениями min и max
// Предполагается, что функцию srand() уже вызывали
static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0);
// Равномерно распределяем рандомное число в нашем диапазоне
return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}
/*
int arrSize = sizeof(arr) / sizeof(arr[0]); // Определение текущего размера массива
cout << ". Size array: " << arrSize << endl;
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define MAXLEN 111111
struct state {
int len, link;
map<int, int> next;
};
int a[MAXLEN];
state st[MAXLEN * 3];
ULL d[MAXLEN * 3];
int was[MAXLEN * 3];
int sz, last;
void sa_init() {
for (int i = 0; i <= sz; ++i) st[i].next.clear();
sz = last = 0;
st[0].len = 0;
st[0].link = -1;
++sz;
}
void sa_extend (int c) {
int cur = sz++;
st[cur].len = st[last].len + 1;
int p;
for (p=last; p!=-1 && !st[p].next.count(c); p=st[p].link)
st[p].next[c] = cur;
if (p == -1)
st[cur].link = 0;
else {
int q = st[p].next[c];
if (st[p].len + 1 == st[q].len)
st[cur].link = q;
else {
int clone = sz++;
st[clone].len = st[p].len + 1;
st[clone].next = st[q].next;
st[clone].link = st[q].link;
for (; p!=-1 && st[p].next[c]==q; p=st[p].link)
st[p].next[c] = clone;
st[q].link = st[cur].link = clone;
}
}
last = cur;
}
int T;
void dfs(int x) {
was[x] = T + 1;
d[x] = 1;
for (map<int, int>::iterator j = st[x].next.begin(); j != st[x].next.end(); ++j) {
if (was[j->second] != T + 1) dfs(j->second);
d[x] += d[j->second];
}
}
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
scanf("%d", &T);
while (T--) {
int n;
scanf("%d", &n);
sa_init();
scanf("%d", &a[0]);
for (int i = 1; i < n; ++i) {
scanf("%d", &a[i]);
sa_extend(a[i] - a[i - 1] + 100);
}
/*
set<vector<int> > all;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
vector<int> c;
for (int k = i; k < j; ++k) c.push_back(a[k + 1] - a[k]);
all.insert(c);
}
}
cerr << all.size() << endl;
for (int i = 0; i < sz; ++i) {
cerr << i << ": ";
for (map<int, int>::iterator j = st[i].next.begin(); j != st[i].next.end(); ++j) {
cerr << j->first - 100 << " " << j->second << ", ";
}
cerr << endl;
}
*/
dfs(0);
cout << (d[0] - 1) % 1000000009 << endl;
}
return 0;
}
|
class Solution {
public:
int romanToInt(string s) {
unordered_map<string, int> m = {{"I", 1}, {"IV", 3}, {"IX", 8}, {"V", 5}, {"X", 10}, {"XL", 30}, {"XC", 80}, {"L", 50}, {"C", 100}, {"CD", 300}, {"CM", 800}, {"D", 500}, {"M", 1000}};
int r = m[s.substr(0, 1)];
for(int i=1; i<s.size(); ++i){
string two = s.substr(i-1, 2);
string one = s.substr(i, 1);
r += m[two] ? m[two] : m[one];
}
return r;
}
};
|
//大二寒假复习2017.2.13
//最简单的思路60-C输入60-C输出100
#include<iostream>
#include<cstdio>
using namespace std;
class Use_for_quicksort{
public:
int compare;
int store_one;
};
//二分查找
int lef_binary_search(Use_for_quicksort *data,int low,int high
,int be_searched){
for(;low<high;){
int middle=(low+high)>>1;
if(be_searched<data[middle].compare){
high=middle;
}
else if(be_searched>data[middle].compare){
low=middle+1;
}
else{
for(;be_searched==data[middle].compare;middle=middle-1);
middle=middle+1;
return middle;
}
}
if(be_searched>data[low].compare){
return low+1;
}else{
return low;
}
}
int righ_binary_search(Use_for_quicksort *data,int low,int high
,int be_searched){
for(;low<high;){
int middle=(low+high)>>1;
if(be_searched<data[middle].compare){
high=middle;
}
else if(be_searched>data[middle].compare){
low=middle+1;
}
else{
for(;be_searched==data[middle].compare;middle=middle-1);
middle=middle+1;
return middle;
}
}
if(be_searched<data[low].compare){
return low-1;
}else{
return low;
}
}
//quicksort algotithm
int quicksort(Use_for_quicksort *data,int low,int high){
int partition(Use_for_quicksort *data,int low,int high);
if ((high-low)<1){
return 0;
}
int middle=partition(data,low,high-1);
quicksort(data,low,middle);
quicksort(data,middle+1,high);
return 0;
}
int partition(Use_for_quicksort *data,int low,int high){
int backup_low=low;
int backup_high=high;
Use_for_quicksort middle_data=data[low];
for(;low<high;){
for(;low<high;){
if(data[high].compare>middle_data.compare){
high=high-1;
}else{
data[low]=data[high];
low=low+1;
break;
}
}
for(;low<high;){
if(data[low].compare<middle_data.compare){
low=low+1;
}else{
data[high]=data[low];
high=high-1;
break;
}
}
}
int middle=low;
data[low]=middle_data;
low=backup_low;
high=backup_high;
return middle;
}
int main(){
//input of the first line
int n,m;
//cin>>n>>m;
fscanf(stdin, "%d %d", &n, &m);
//input of the second line
Use_for_quicksort* array = new Use_for_quicksort [500100];
for(int i = 0; i < n; ++i){
//cin>>array[i].compare;
fscanf(stdin, "%d", &(array[i].compare));
}
//change this detail for the test data
array[n].compare = 10000002;
//input of the m line
int* lef = new int [500100];
int* righ = new int [500100];
for(int i = 0; i < m; ++i){
//cin>>lef[i]>>righ[i];
fscanf(stdin, "%d %d", &(lef[i]), &(righ[i]));
}
//sort the array
quicksort(array,0,n);
//process
for(int i = 0; i < m; ++i){
int lef_index = lef_binary_search(array, 0, n, lef[i]);
int righ_index = righ_binary_search(array, 0, n, righ[i]);
//cout<<(righ_index - lef_index + 1)<<endl;
fprintf(stdout, "%d\n", (righ_index - lef_index + 1));
}
return 0;
}
|
#include <vector>
#include <memory>
#include <gtest/gtest.h>
#include "ClnUtils.h"
#include "PhoneticService.h"
namespace PticaGovorunTests
{
using namespace PticaGovorun;
struct PhoneticTranscriptionTest : public testing::Test
{
};
TEST_F(PhoneticTranscriptionTest, phoneListToStrConversion)
{
PhoneRegistry phoneReg;
phoneReg.setPalatalSupport(PalatalSupport::AsPalatal);
initPhoneRegistryUk(phoneReg, true, true);
std::vector<PhoneId> phones;
std::string phonesStrIn = "S U1 T1 B2 I";
bool parseOp = parsePhoneList(phoneReg, phonesStrIn, phones);
ASSERT_TRUE(parseOp);
std::string phonesStrOut;
bool toStrOp = phoneListToStr(phoneReg, phones, phonesStrOut);
ASSERT_TRUE(toStrOp);
EXPECT_EQ(phonesStrIn, phonesStrOut);
}
inline void spellTest(const wchar_t* word, const char* expectTranscription, const PhoneRegistry* phoneRegClient = nullptr,
WordPhoneticTranscriber::StressedSyllableIndFunT stressedSyllableIndFun = nullptr)
{
std::unique_ptr<PhoneRegistry> phoneRegLocal;
if (phoneRegClient == nullptr)
{
phoneRegLocal = std::make_unique<PhoneRegistry>();
phoneRegLocal->setPalatalSupport(PalatalSupport::AsPalatal);
initPhoneRegistryUk(*phoneRegLocal, true, true);
}
const PhoneRegistry* phoneReg = phoneRegClient != nullptr ? phoneRegClient : phoneRegLocal.get();
std::vector<PhoneId> phones;
bool spellOp;
const char* errMsg;
std::tie(spellOp, errMsg) = spellWordUk(*phoneReg, word, phones, stressedSyllableIndFun);
ASSERT_TRUE(spellOp);
std::vector<PhoneId> expectPhones;
bool parseOp = parsePhoneList(*phoneReg, expectTranscription, expectPhones);
ASSERT_TRUE(parseOp);
bool ok = expectPhones == phones;
ASSERT_TRUE(ok);
}
TEST_F(PhoneticTranscriptionTest, phoneticSimple1)
{
spellTest(L"рух", "R U1 KH");
}
TEST_F(PhoneticTranscriptionTest, vowelStressCantBeDetermined)
{
spellTest(L"аарон", "A A R O N");
spellTest(L"слова", "S L O V A");
}
TEST_F(PhoneticTranscriptionTest, alwaysDoubleSHCH)
{
spellTest(L"що", "SH CH O1");
}
TEST_F(PhoneticTranscriptionTest, alwaysDoubleYI)
{
spellTest(L"воїн", "V O J I N");
}
TEST_F(PhoneticTranscriptionTest, compoundPhoneDZDZH)
{
// DZ
spellTest(L"дзеркало", "DZ E R K A L O");
// DZH
spellTest(L"бюджет", "B2 U DZH E T");
}
TEST_F(PhoneticTranscriptionTest, compoundPhoneZ)
{
// Z ZH -> ZH ZH
spellTest(L"безжально", "B E ZH ZH A L1 N O");
spellTest(L"зжерли", "ZH ZH E R L Y");
// Z D ZH -> ZH DZH
spellTest(L"з'їзджають", "Z J I ZH DZH A J U T1");
spellTest(L"пизджу", "P Y ZH DZH U");
}
TEST_F(PhoneticTranscriptionTest, compoundPhoneNTSTNTS1K)
{
// N T S T -> N S T
spellTest(L"агентства", "A H E N S T V A");
// N T S1 K -> N S1 K
spellTest(L"студентський", "S T U D E N1 S1 K Y J");
}
TEST_F(PhoneticTranscriptionTest, compoundPhoneS)
{
// S SH -> SH SH
spellTest(L"принісши", "P R Y N1 I SH SH Y");
spellTest(L"сша", "SH SH A1");
//spellTest(L"масштаб", "M A SH T A B"); // alternative=no doubling
// сексшоп [S E K S SH O P] two different words, no doubling
}
TEST_F(PhoneticTranscriptionTest, compoundPhoneST)
{
// S T D -> Z D
spellTest(L"шістдесят", "SH2 I Z D E S1 A T");
// S T S 1 K -> S1 K
spellTest(L"модерністська", "M O D E R N1 I S1 K A");
spellTest(L"нацистська", "N A TS Y S1 K A");
spellTest(L"фашистська", "F A SH Y S1 K A");
// S T S -> S S
spellTest(L"постскриптум", "P O S S K R Y P T U M");
spellTest(L"шістсот", "SH2 I S S O T");
// S T TS -> S TS
spellTest(L"невістці", "N E V2 I S1 TS1 I");
spellTest(L"пастці", "P A S1 TS1 I");
}
TEST_F(PhoneticTranscriptionTest, compoundPhoneTST1STTSTCH)
{
// T S -> TS
spellTest(L"багатство", "B A H A TS T V O");
// T 1 S -> TS
spellTest(L"активізуються", "A K T Y V2 I Z U J U TS1 A");
// T TS -> TS TS
spellTest(L"отця", "O TS1 TS1 A");
spellTest(L"куртці", "K U R TS1 TS1 I");
// T CH -> CH CH
spellTest(L"вітчизна", "V2 I CH CH Y Z N A");
spellTest(L"льотчик", "L1 O CH CH Y K");
}
TEST_F(PhoneticTranscriptionTest, doublePhoneYEYUYAWhenItTheFirstLetter)
{
// first letter is Є Ю Я
spellTest(L"єврей", "J E V R E J");
spellTest(L"юнак", "J U N A K");
spellTest(L"яблуко", "J A B L U K O");
spellTest(L"де-юре", "D E J U R E");
spellTest(L"як-не-як", "J A K N E J A K");
spellTest(L"один-єдиний", "O D Y N J E D Y N Y J");
spellTest(L"по-європейськи", "P O J E V R O P E J S1 K Y");
}
TEST_F(PhoneticTranscriptionTest, doublePhoneYEYUYAAfterApostrophe)
{
spellTest(L"б'є", "B J E1");
spellTest(L"б'ю", "B J U1");
spellTest(L"пір'я", "P2 I R J A");
}
TEST_F(PhoneticTranscriptionTest, doublePhoneYEYUYAAfterSoftSign)
{
spellTest(L"досьє", "D O S1 J E");
spellTest(L"сьюзен", "S1 J U Z E N");
spellTest(L"вільям", "V2 I L1 J A M");
spellTest(L"будь-яка", "B U D1 J A K A");
}
TEST_F(PhoneticTranscriptionTest, doublePhoneYEYUYAAfterVowel)
{
spellTest(L"взаємно", "V Z A J E M N O");
spellTest(L"настою", "N A S T O J U");
spellTest(L"абияк", "A B Y J A K");
spellTest(L"гостює", "H O S1 T1 U J E");
}
TEST_F(PhoneticTranscriptionTest, hardConsonantBeforeVowelE) {
spellTest(L"землею", "Z E M L E J U");
}
TEST_F(PhoneticTranscriptionTest, softConsonantBeforeI)
{
spellTest(L"лікар", "L1 I K A R");
spellTest(L"лісти", "L1 I S T Y");
spellTest(L"рівень", "R1 I V E N1");
spellTest(L"імлі", "I M L1 I");
spellTest(L"віл", "V2 I1 L");
spellTest(L"білка", "B2 I L K A");
}
TEST_F(PhoneticTranscriptionTest, softConsonantBeforeYAYU)
{
spellTest(L"лякати", "L1 A K A T Y");
spellTest(L"буря", "B U R1 A");
spellTest(L"зоря", "Z O R1 A");
spellTest(L"порядок", "P O R1 A D O K");
spellTest(L"рябий", "R1 A B Y J");
spellTest(L"грюкати", "H R1 U K A T Y");
spellTest(L"варю", "V A R1 U");
spellTest(L"бурю", "B U R1 U");
spellTest(L"люди", "L1 U D Y");
spellTest(L"селюк", "S E L1 U K");
}
TEST_F(PhoneticTranscriptionTest, softDoubleConsonantBeforeYAYU)
{
spellTest(L"ілля", "I L1 L1 A");
spellTest(L"моделлю", "M O D E L1 L1 U");
spellTest(L"ллє", "L1 L1 E1");
spellTest(L"суттєво", "S U T1 T1 E V O");
}
TEST_F(PhoneticTranscriptionTest, pairOfConsonantsSoftenEachOther)
{
spellTest(L"кузня", "K U Z1 N1 A");
spellTest(L"сніг", "S1 N1 I1 H");
spellTest(L"молодці", "M O L O T1 TS1 I");
spellTest(L"митці", "M Y TS1 TS1 I");
spellTest(L"радянський", "R A D1 A N1 S1 K Y J");
spellTest(L"гілці", "H2 I L1 TS1 I");
spellTest(L"дні", "D1 N1 I1");
spellTest(L"для", "D1 L1 A1");
spellTest(L"путні", "P U T1 N1 I");
spellTest(L"абстрактні", "A P S T R A K T1 N1 I");
spellTest(L"тліти", "T1 L1 I T Y");
// TODO: exception волзі [V O L Z1 I]
}
TEST_F(PhoneticTranscriptionTest, pairOfConsonantsSoftenEachOtherRecursive)
{
spellTest(L"бесслідно", "B E S1 S1 L1 I D N O");
}
TEST_F(PhoneticTranscriptionTest, pairOfConsonantsDampEachOther_make_unvoice_BP_HKH_DT_ZHSH_ZS) {
// B->P
spellTest(L"необхідно", "N E O P KH2 I D N O");
// H->KH
spellTest(L"легше", "L E KH SH E");
// D->T
spellTest(L"відповідає", "V2 I T P O V2 I D A J E");
spellTest(L"підпис", "P2 I T P Y S");
// ZH->SH
spellTest(L"ліжка", "L1 I SH K A");
// Z->S
spellTest(L"безпосередньо", "B E S P O S E R E D1 N1 O");
spellTest(L"залізти", "Z A L1 I S T Y");
spellTest(L"розповідали", "R O S P O V2 I D A L Y");
spellTest(L"розповсюджувати", "R O S P O V S1 U DZH U V A T Y");
// BP HKH DT ZHSH ZS before soft sign and unvoiced consonant
// D 1 ->T
spellTest(L"дядько", "D1 A T1 K O");
// Z 1 -> S
spellTest(L"абхазька", "A P KH A S1 K A");
spellTest(L"близько", "B L Y S1 K O");
spellTest(L"вузько", "V U S1 K O");
}
TEST_F(PhoneticTranscriptionTest, pairOfConsonantsAmplify_makeVoice_EeachOther) {
// T->D
spellTest(L"боротьба", "B O R O D1 B A");
spellTest(L"отже", "O D ZH E");
spellTest(L"футбол", "F U D B O L");
// K->G
spellTest(L"вокзал", "V O G Z A L");
spellTest(L"екзамен", "E G Z A M E N");
spellTest(L"якби", "J A G B Y");
spellTest(L"аякже", "A J A G ZH E");
spellTest(L"великдень", "V E L Y G D E N1");
// S->Z
spellTest(L"осьде", "O Z1 D E");
spellTest(L"юрисдикції", "J U R Y Z D Y K TS1 I J I");
spellTest(L"лесбіянка", "L E Z B2 I J A N K A");
// CH->DZH
spellTest(L"учбових", "U DZH B O V Y KH");
spellTest(L"лічбі", "L1 I DZH B2 I");
spellTest(L"хоч би", "KH O DZH B Y");
}
TEST_F(PhoneticTranscriptionTest, apostropheInEnUkTransliteration) {
// he's -> хі'з
spellTest(L"хі'з", "KH2 I1 Z"); // apostrophe is ignored
}
TEST_F(PhoneticTranscriptionTest, varyPhoneSoftnessAndStress_NoSoftNoStress) {
PhoneRegistry phoneReg;
bool allowSoftHardConsonant = false;
bool allowVowelStress = false;
initPhoneRegistryUk(phoneReg, allowSoftHardConsonant, allowVowelStress);
spellTest(L"суть", "S U T", &phoneReg);
}
TEST_F(PhoneticTranscriptionTest, varyPhoneSoftnessAndStress_DoSoftNoStress)
{
PhoneRegistry phoneReg;
bool allowSoftHardConsonant = true;
bool allowVowelStress = false;
initPhoneRegistryUk(phoneReg, allowSoftHardConsonant, allowVowelStress);
spellTest(L"суть", "S U T1", &phoneReg);
}
TEST_F(PhoneticTranscriptionTest, varyPhoneSoftnessAndStress_NoSoftDoStress)
{
PhoneRegistry phoneReg;
bool allowSoftHardConsonant = false;
bool allowVowelStress = true;
initPhoneRegistryUk(phoneReg, allowSoftHardConsonant, allowVowelStress);
spellTest(L"суть", "S U1 T", &phoneReg);
}
TEST_F(PhoneticTranscriptionTest, varyPhoneSoftnessAndStress_DoSoftDoStress)
{
PhoneRegistry phoneReg;
bool allowSoftHardConsonant = true;
bool allowVowelStress = true;
initPhoneRegistryUk(phoneReg, allowSoftHardConsonant, allowVowelStress);
spellTest(L"суть", "S U1 T1", &phoneReg);
}
TEST_F(PhoneticTranscriptionTest, palatalConsonantsSupport)
{
PhoneRegistry phoneReg;
bool allowSoftHardConsonant = true;
bool allowVowelStress = true;
initPhoneRegistryUk(phoneReg, allowSoftHardConsonant, allowVowelStress);
phoneReg.setPalatalSupport(PalatalSupport::AsHard);
spellTest(L"бій", "B I1 J", &phoneReg);
phoneReg.setPalatalSupport(PalatalSupport::AsSoft);
spellTest(L"бій", "B1 I1 J", &phoneReg);
phoneReg.setPalatalSupport(PalatalSupport::AsPalatal);
spellTest(L"бій", "B2 I1 J", &phoneReg);
}
TEST_F(PhoneticTranscriptionTest, externalProviderOfStressedSyllable)
{
auto getStressedSyllableIndFun = [](boost::wstring_view word, std::vector<int>& stressedSyllableInds) -> bool
{
if (word.compare(L"тулуб") == 0)
stressedSyllableInds.assign({ 1 });
else if (word.compare(L"укртранснафта") == 0)
stressedSyllableInds.assign({ 0, 1, 2 });
else
return false;
return true;
};
spellTest(L"тулуб", "T U L U1 B", nullptr, getStressedSyllableIndFun);
spellTest(L"укртранснафта", "U1 K R T R A1 N S N A1 F T A", nullptr, getStressedSyllableIndFun);
}
}
// TODO:
// надсилають [N A T S Y L A J U T1] no T+S->TS on the border prefix-suffix
|
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/GlobalVariable.h"
#include <unordered_map>
#include <string>
using namespace llvm;
namespace{
struct countInstrPass:public FunctionPass {
static char ID;
countInstrPass() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override {
Module* mod=F.getParent(); //get the module that contains function F
LLVMContext &context=mod->getContext(); //get module context (what's the difference between mod->getContext() and F.getContext())
for(auto B=F.begin(), BEnd=F.end();B!=BEnd;B++){
std::unordered_map<int,int> dic;
std::vector<int> keys;
std::vector<int> values;
/* in each block, we can statically count the number of instruction in compile time, then use these static information to update global counter by inserting function call the will dynamically executed in runtime*/
for(auto I=B->begin(),IEnd=B->end();I!=IEnd;I++){
if(dic.find(I->getOpcode())==dic.end()){
dic[I->getOpcode()]=1;
}else{
dic[I->getOpcode()]+=1;
}
}
for(auto pair:dic){
keys.push_back(pair.first);
values.push_back(pair.second);
}
/* the place to insert function call is important, can't use Builder(&*B) since this will insert some codes even after the block that contains Return, which will cause unterminated function */
Instruction &lastI=B->back();
IRBuilder<> Builder(&lastI); //thus we should insert the function call before the last instruction in this block, thus Return will happen normally
ConstantInt *Length = Builder.getInt16(dic.size()); //first param
ArrayType* ArrayTy = ArrayType::get(IntegerType::get(F.getContext(), 32), dic.size()); //define the array type, is F.getContext() the same with F.getParent()->getContext() here?
GlobalVariable* GlobalOpcodeArray = new GlobalVariable(*mod,ArrayTy,false,GlobalValue::ExternalLinkage,ConstantDataArray::get(context,keys),"Opcode Array"); //second param
Value* OpcodeArrayPtr = Builder.CreatePointerCast(GlobalOpcodeArray, Type::getInt32PtrTy(context));
GlobalVariable* GlobalCountArray = new GlobalVariable(*mod,ArrayTy,false,GlobalValue::ExternalLinkage,ConstantDataArray::get(context,values),"Count Array"); //third param
Value* CountArrayPtr = Builder.CreatePointerCast(GlobalCountArray, Type::getInt32PtrTy(context));
FunctionCallee countInstrInBlock=mod->getOrInsertFunction("updateInstrInfo",Type::getVoidTy(context),Type::getInt16Ty(context),Type::getInt32PtrTy(context),Type::getInt32PtrTy(context)); //create function handle
std::vector<Value*> args; // CreatCall only takes ArrayRef param, thus create a vector to contain all params of function then convert it to ArrayRef
args.push_back(Length);
args.push_back(OpcodeArrayPtr);
args.push_back(CountArrayPtr);
ArrayRef<Value*> argRef(args);
Builder.CreateCall(countInstrInBlock,argRef); //insert the function
}
/* insert the print function before the last instruction */
BasicBlock &lastB=F.back();
Instruction &lastI=lastB.back();
IRBuilder<> Builder(&lastI);
FunctionCallee printInstr=mod->getOrInsertFunction("printOutInstrInfo",Type::getVoidTy(context)); //create function handle
Builder.CreateCall(printInstr);
return false;
}
};
}
char countInstrPass::ID = 0;
static RegisterPass<countInstrPass> X("cse231-cdi", "Developed to dynamically count the number of instructions in runtime", false /* Only looks at CFG */, false /* Analysis Pass */);
|
#include "ReverseL.h"
namespace WinTetris
{
ReverseL::ReverseL()
{
occupied[0][0] = true;
occupied[1][0] = true;
occupied[1][1] = true;
occupied[1][2] = true;
}
}
|
// Copyright 2012 Yandex
#ifndef LTR_LEARNERS_DECISION_TREE_ID3_LEARNER_H_
#define LTR_LEARNERS_DECISION_TREE_ID3_LEARNER_H_
#include <string>
#include "ltr/learners/decision_tree/decision_tree_learner.h"
#include "ltr/learners/decision_tree/id3_splitter.h"
#include "ltr/learners/decision_tree/sqr_error_quality.h"
using ltr::decision_tree::DecisionTreeLearner;
using ltr::decision_tree::SqrErrorQuality;
using ltr::decision_tree::ID3_Splitter;
using ltr::decision_tree::ConditionsLearner;
using ltr::decision_tree::SplittingQuality;
using std::string;
namespace ltr {
class ID3_Learner : public DecisionTreeLearner {
public:
explicit ID3_Learner(const ParametersContainer& parameters)
: DecisionTreeLearner(parameters) {
this->set_conditions_learner(ConditionsLearner::Ptr(new ID3_Splitter(
parameters.Get<ParametersContainer>("ID3SplitterParams"))));
this->set_splitting_quality(SplittingQuality::Ptr(new SqrErrorQuality(
parameters.Get<ParametersContainer>("SqrErrorQualityParams"))));
}
explicit ID3_Learner(bool split_feature_n_times = false,
int feature_split_count = 100,
int half_summs_step = 5,
int min_vertex_size = 3,
double label_eps = 0.001)
: DecisionTreeLearner(min_vertex_size, label_eps) {
this->set_conditions_learner(ConditionsLearner::Ptr(new ID3_Splitter(
split_feature_n_times, feature_split_count, half_summs_step)));
this->set_splitting_quality(SplittingQuality::Ptr(new SqrErrorQuality()));
}
private:
virtual string getDefaultAlias() const {return "ID3_Learner";}
};
};
#endif // LTR_LEARNERS_DECISION_TREE_ID3_LEARNER_H_
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
/** \file
*
* \brief Implement OpMemEvent and OpMemEventListener objects
*/
#include "core/pch.h"
#ifdef ENABLE_MEMORY_DEBUGGING
#include "modules/memory/src/memory_events.h"
OpMemEventListener::OpMemEventListener(UINT32 eventclasses) :
eventclass_mask(eventclasses)
{
Into(&g_mem_event_listeners);
}
OpMemEventListener::~OpMemEventListener(void)
{
Out();
}
void OpMemEventListener::DeliverMemoryEvent(OpMemEvent* event)
{
UINT32 cls = event->eventclass;
OpMemEventListener* evl =
(OpMemEventListener*)g_mem_event_listeners.First();
while ( evl != 0 )
{
if ( evl->eventclass_mask & cls )
evl->MemoryEvent(event);
evl = (OpMemEventListener*)evl->Suc();
}
}
#endif // ENABLE_MEMORY_DEBUGGING
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Krefting
*/
/**
* @file prefsmanager.h
* Declarations for preference manager framework.
* Please see the generic documentation below for information about this
* framework.
*/
#ifndef PREFSMANAGER_H
#define PREFSMANAGER_H
#include "modules/prefs/prefsapitypes.h"
#include "modules/prefsfile/prefsfile.h"
class OpPrefsCollection;
class OpString_list;
class PrefsSectionInternal;
/** Global PrefsManager object (singleton). */
#define g_prefsManager (g_opera->prefs_module.PrefsManager())
/** The preference manager framework contains the framework for handling
* user customisable settings. The PrefsManager framework collaborates
* with the OpPrefsCollection subclasses to handle the actual preferences.
* They use the PrefsFile interface to actually read and write the
* preferences. How the preferences actually are stored in the file is up
* to the implementation of PrefsFile, PrefsManager and its partner
* classes do not care. See the documentation for the
* <a href="http://wiki.oslo.opera.com/developerwiki/index.php/Prefsfile_module">prefsfile module</a>
* for more information about that.
*
* PrefsManager itself does not store any preferences.
*
* @author Peter Karlsson
* @see OpPrefsCollection
*/
class PrefsManager
{
public:
// -- Get meta data --------------------------------------------------
#ifdef PREFS_READ
/** Retrieve the reader object.
* This will return the reader object associated with the PrefsManager.
* Since outside code is not allowed to tinker with it directly, a
* const pointer is returned.
*/
inline const PrefsFile *GetReader() const { return m_reader; }
#endif
/** Check whether the prefs manager has been initialized. */
inline BOOL IsInitialized() { return m_initialized; }
// -- String-based preferences API -----------------------------------
#ifdef PREFS_HAVE_STRING_API
/** Read a preference using the INI name.
*
* Using this API, you can read any preference using the name in the
* INI file. Since this involves a great number of string comparisons,
* it should only be used in conjunction with APIs exposed to external
* customers. Only known preferences can be read.
*
* @param section INI section name.
* @param key INI key name.
* @param target A place to store the value in.
* @param defval Get default value instead of current value.
* @param host Host for overridden setting, NULL to normal setting.
* @return TRUE if the preference was found and could be read.
*/
BOOL GetPreferenceL(const char *section, const char *key, OpString &target,
BOOL defval = FALSE, const uni_char *host = NULL);
#endif
#if defined PREFS_HAVE_STRING_API && defined PREFS_WRITE
/** Write a preference using the INI name.
*
* Using this API, you can write any preference using the name in the
* INI file. Since this involves a great number of string comparisons,
* it should only be used in conjunction with APIs exposed to external
* customers. Only known preferences can be written.
*
* If "value" contains non-numeric data and the setting you are trying
* to write is an integer preference, this function will leave.
*
* @param section INI section name.
* @param key INI key name.
* @param value Value to write.
* @return TRUE if the preference was found and was writable.
*/
BOOL WritePreferenceL(const char *section, const char *key, const OpStringC value);
# ifdef PREFS_HOSTOVERRIDE
/** Write a site specific preference using the INI name.
*
* Using this API, you can write any preference using the name in the
* INI file. This involves a great number of string comparisons,
* and should be used with care. Only known preferences can be written.
*
* If "value" contains non-numeric data and the setting you are trying
* to write is an integer preference, this function will leave.
*
* @param host host name.
* @param section INI section name.
* @param key INI key name.
* @param value Value to write.
* @param from_user TRUE if the preference is entered by the user.
* @return TRUE if the preference was found and was writable.
*/
BOOL OverridePreferenceL(const uni_char *host, const char *section,
const char *key, const OpStringC value,
BOOL from_user);
/** Remove a specific override for a subset of hosts. This will delete
* the override from the INI file and from memory. The changes will
* not be written to disk until CommitL is called.
*
* @param host Host to delete overrides for (or NULL to match all hosts.)
* @param from_user TRUE if the preference to be deleted was entered by
* the user.
* @return TRUE if an override was removed.
*/
BOOL RemoveOverrideL(const uni_char *host, const char *section,
const char *identifier, BOOL from_user);
# endif
#endif
// -- Enumerator API -------------------------------------------------
#ifdef PREFS_ENUMERATE
/** Retrieve a list of (almost) all available preferences in this
* Opera build, and their current values. The values are the same
* as would be returned when you do GetPreferenceL() on the setting.
*
* Only known preferences are supported, and only those that are
* known at compile time (not dynamic preferences). Only preferences
* in the main preferences file will be exposed.
*
* There is no support for host overrides in this API.
*
* The returned array must be deleted by the caller.
*
* @param sort Whether to sort the list of settings alphabetically.
* @param length Number of entries in the list (output).
* @return A list of available settings.
*/
struct prefssetting *GetPreferencesL(BOOL sort, unsigned int &length) const;
#endif
// -- Host overrides -------------------------------------------------
#ifdef PREFS_HOSTOVERRIDE
# ifdef PREFS_WRITE
/** Remove all overrides for a named host. This will delete all the
* overrides from the INI file and from the memory. The changes will
* not actually be written to disk until CommitL is called.
*
* @param host Host to delete overrides for.
* @param from_user TRUE if the preference to be deleted was entered by
* the user.
* @return FALSE if there was no override set for this host, or if we
* were not allowed to delete it.
*/
BOOL RemoveOverridesL(const uni_char *host, BOOL from_user);
/**
* Remove all overrides for all hosts. CommitL is called after
* each host has been processed.
*
* @param from_user TRUE if the preference to be deleted was entered by the user.
* @return FALSE if there no overrides were set, or if we were not allowed
* to delete them.
*/
BOOL RemoveOverridesAllHostsL(BOOL from_user);
# endif
/** Check if there are overrides available for a named host.
*
* @param host Host to check for overrides.
* @param exact Whether to perform an exact match, or if cascaded
* overrides should be allowed.
* @return Override status.
*/
HostOverrideStatus IsHostOverridden(const uni_char *host, BOOL exact = TRUE);
/** Count the global number of overrides for a specific host.
*
* @param host Host to count overrides for.
* @return Number of overrides.
*/
size_t HostOverrideCount(const uni_char *host);
/** Enable or disable an overridden host. The name matching is always done
* exact.
*
* @param host Host to check for overrides.
* @param active Whether to activate the host.
* @return TRUE if a matching host was found.
*/
BOOL SetHostOverrideActiveL(const uni_char *host, BOOL active = TRUE);
# ifdef PREFS_GETOVERRIDDENHOSTS
/** Retrieve a list of overridden hosts. The returned value is a
* OpString_list listing the host names that have override data.
* The list will contain both enabled and disabled overrides, the
* status should always be checked via IsHostOverridden.
*
* If there are no overridden hosts, this function will return
* a NULL pointer.
*
* @return List of overridden hosts. The pointer must be deleted
* by the caller.
*/
OpString_list *GetOverriddenHostsL();
# endif
# ifdef PREFS_WRITE
/** Only to be called from OpPrefsCollectionWithHostOverride */
void OverrideHostAddedL(const uni_char *);
# endif
#endif // PREFS_HOSTOVERRIDE
// -- Storage --------------------------------------------------------
/** Writes all (changed) preferences to the user preferences file.
* If PREFS_SOFT_COMMIT is set, the commit will probably not make
* changes to the actual file on disk.
*
* Call this method after changing a batch of preferences where
* the user expects the changes to be stored, for instance when
* pressing OK in the preferences dialogue.
*/
inline void CommitL()
{
#if defined PREFS_READ && defined PREFS_WRITE
m_reader->CommitL();
# ifdef PREFS_HOSTOVERRIDE
if (m_overridesreader)
{
m_overridesreader->CommitL();
}
# endif
#endif
}
/** Writes all (changed) preferences to the user preferences file.
* This version will set the forced flag to TRUE, and will save
* changes to disk even if PREFS_SOFT_COMMIT is set.
*
* For normal use, you should call CommitL(). Only call this at
* critical points in the program, for instance just before
* shutting down, or when changing critical data.
*/
inline void CommitForceL()
{
#if defined PREFS_READ && defined PREFS_WRITE
m_reader->CommitL(TRUE);
# ifdef PREFS_HOSTOVERRIDE
if (m_overridesreader)
m_overridesreader->CommitL(TRUE);
# endif
#endif
}
// -- Construction and destruction (module internal use only) --------
/** First-phase constructor.
*
* @param reader Pointer to a fully configured PrefsFile object to
* use. Ownership of this object will be transferred to PrefsManager.
* This pointer may not be NULL unless FEATURE_PREFS_READ is disabled,
* in which case the value is ignored altogether.
*/
explicit PrefsManager(PrefsFile *reader);
/** Second-phase constructor.
* This will initialise PrefsManager and create all the associated
* preference collections.
*/
void ConstructL();
/** Read all preferences.
* This is called initially, after the object is fully configured,
* and before anything is read from any of the collections.
*
* Please note that the collections may not be used before this
* has been called.
*
* Precondition: OpFolderManager must be set up properly with the paths
* that are not configurable by the preferences.
*
* @param info Initialization data.
*/
void ReadAllPrefsL(PrefsModule::PrefsInitInfo *info);
/** Destructor.
*
* Please note that you MUST perform a commit before deleting the
* object, if you do not all outstanding changes will be lost.
*/
~PrefsManager();
private:
BOOL m_initialized; ///< Flag that we are fully initialized
#ifdef PREFS_READ
PrefsFile *m_reader; ///< Associated reader object
#endif
#ifdef PREFS_HOSTOVERRIDE
PrefsSectionInternal *m_overrides; ///< Cached copy of the host override section
# ifdef PREFS_READ
PrefsFile *m_overridesreader; ///< Associated reader object for overrides
# endif
#endif
#ifdef PREFS_ENUMERATE
static int GetPreferencesSort(const void *, const void *);
#endif
};
#endif
|
#include "FontRenderer.h"
#include <iostream>
FontRenderer::FontRenderer() {
fontShader.addShader("shaders/font.vsh", GL_VERTEX_SHADER);
fontShader.addShader("shaders/font.fsh", GL_FRAGMENT_SHADER);
fontShader.start();
fontShader.activateUniform("translation");
fontShader.activateUniform("fontColor");
fontShader.activateUniform("width");
fontShader.activateUniform("edge");
fontShader.activateUniform("borderWidth");
fontShader.activateUniform("borderEdge");
fontShader.activateUniform("borderColor");
fontShader.activateUniform("borderOffset");
fontShader.bindTextureUnit("fontAtlas", 0);
fontShader.stop();
}
void FontRenderer::render(Scene& scene) {
//Prepare Alpha
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
//Start Font Shader
fontShader.start();
//loop Texts in Scene
for(GuiText* text: *scene.guiTexts){
if(text->renderMe){
glBindVertexArray(text->model.vaoId);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
//Set Matrix and Text Values
fontShader.setUniformVariable("translation", text->position);
fontShader.setUniformVariable("fontColor", text->color);
fontShader.setUniformVariable("width", text->width);
fontShader.setUniformVariable("edge", text->edge);
fontShader.setUniformVariable("borderWidth", text->borderWidth);
fontShader.setUniformVariable("borderEdge", text->borderEdge);
fontShader.setUniformVariable("borderColor", text->borderColor);
fontShader.setUniformVariable("borderOffset", text->borderOffset);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, text->font.textureAtlas);
glDrawArrays(GL_TRIANGLES, 0, text->model.elementBufferSize);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
}
//Stop Shader
fontShader.stop();
//Reset GL
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
}
FontRenderer::~FontRenderer() {
}
|
/*
* File: main.cpp
* Author: Daniel Canales
*
* Created on June 24, 2014, 9:15 PM
*/
#include <cstdlib>
#include <iostream>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
float meal = 44.50; //original cost
float tip = .15*meal; //tip price
float tax = .0675*meal; //tax
float total = meal+tip+tax;
cout << "Meal price: " << meal << endl;
cout << "Tax is: " << tax << endl; //cal for tax
cout << "Tip is: " << tip << endl;
cout << "Total is: " << total << endl;
return 0;
}
|
#include "mymainwindow.h"
#include "ui_mymainwindow.h"
MyMainWindow::MyMainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MyMainWindow)
{
ui->setupUi(this);
ui->widget->setFocus();
}
MyMainWindow::~MyMainWindow()
{
delete ui;
}
void MyMainWindow::on_actionQuit_triggered()
{
close();
}
|
#ifndef SHAREDPREFERENCES_H
#define SHAREDPREFERENCES_H
#include <QObject>
#include <QString>
#include <QVariant>
class SharedPreferences : public QObject
{
Q_OBJECT
public:
~SharedPreferences();
static SharedPreferences *getPreferences(QObject *parent = nullptr);
static SharedPreferences *getSharedPreferences(const QString &name, QObject *parent = nullptr);
Q_INVOKABLE QStringList keys() const;
Q_INVOKABLE bool contains(const QString &key) const;
Q_INVOKABLE QVariant value(const QString &key) const;
Q_INVOKABLE QVariantMap data() const;
public slots:
void setValue(const QString &key, const QVariant &value);
void remove(const QString &key);
signals:
void loaded();
void changed(const QString &key, const QVariant &value);
private slots:
void dispatched(const QString &message, const QVariantMap &data);
private:
const QString _id;
QVariantMap _data;
explicit SharedPreferences(const QString &id, QObject *parent = nullptr);
};
#endif // SHAREDPREFERENCES_H
|
/**
* created: 2013-3-22 23:01
* filename: FKStringEx
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#include "../Include/FKVsVer8Define.h"
#include "../Include/FKStringEx.h"
#include <time.h>
#include <malloc.h>
#include <xhash>
#include "../Include/FKThread.h"
//------------------------------------------------------------------------
const char CEasyStrParse::NullChar[4]={0,0,0,0};
//------------------------------------------------------------------------
void CEasyStrParse::ParseParam(int nCount)
{
if (m_pStart && m_pStart[0]!=0 && nCount>0)
{
if (m_pch==NULL || m_pch[0]==0)
{
if (m_pszParams.size()==0){
m_pszParams.push_back(m_pStart);
m_pStart=(char *)&NullChar;
}
return;
}
if ((size_t)nCount<=m_pszParams.size())
{
return;
}
int b_a_idx=-1;
char curch=0;
int tmpidx=0;
int curch_state=0;
char* pread=m_pStart;
char* pwrite=m_pStart;
char* m_laststart=pwrite;
bool isfirstb_a=false;
bool iszychar=false;
while(*pread)
{
curch=*pread;
isfirstb_a=false;
iszychar=false;
switch(curch_state)
{
case 0:
{
tmpidx=0;
while(m_pBAch[tmpidx]){
if (curch==m_pBAch[tmpidx]){
isfirstb_a=true;b_a_idx=tmpidx+1;curch_state=1; break;
}
tmpidx+=2;
}
}
break;
case 1:
{
if ( curch==m_zychr && (b_a_idx>=0 && pread[1]!=0 && pread[1]==m_pBAch[b_a_idx]) ){
iszychar=true;
pread++;
}else if (b_a_idx>=0 && curch==m_pBAch[b_a_idx]){
curch_state=0;
b_a_idx=-1;
}
}
break;
}
if ( !iszychar && (isfirstb_a || curch_state==0) )
{
tmpidx=0;
while(m_pch[tmpidx])
{
if (curch==m_pch[tmpidx])
{
*pwrite='\0';
*pread='\0';
if (m_bokeepnil || m_laststart[0]!=0)
{
m_pszParams.push_back(m_laststart);
m_laststart=pwrite;m_laststart++;
if (m_pszParams.size()>=(size_t)nCount && curch_state==0)
{
m_pStart=pread;m_pStart++;return;
}
else if (pread[1]==0)
{
m_laststart=NULL;
m_pStart=pread;m_pStart++;return;
}
}
else
{
m_laststart=pwrite;m_laststart++;
}
break;
}
tmpidx++;
}
}
*pwrite=*pread;
pread++;
pwrite++;
}
*pwrite=*pread;
if (m_laststart)
{
if (m_laststart[0]!=0)
{
m_pszParams.push_back(m_laststart);
}
m_laststart=NULL;
}
m_pStart=pread;
}
return;
}
//------------------------------------------------------------------------
CEasyStrParse::CEasyStrParse()
{
m_pStart=NULL;
m_pSrcStart=NULL;
m_pch=NULL;
m_pBAch=NULL;
m_psrc=NULL;
m_zychr=0;
m_npsrc_maxlen=0;
m_bokeepnil=false;
}
//------------------------------------------------------------------------
CEasyStrParse::~CEasyStrParse()
{
if (m_psrc){ __mt_char_alloc.deallocate(m_psrc);}
m_psrc=NULL;
m_npsrc_maxlen=0;
}
//------------------------------------------------------------------------
bool CEasyStrParse::SetParseStrEx(const char* psz,char* pszCh,char* pszBAch,char zychr,bool keepnil)
{
size_t nlen=(strlen(psz)+16);
if (m_psrc && m_npsrc_maxlen<nlen)
{
__mt_char_alloc.deallocate(m_psrc);
m_psrc=NULL;
m_npsrc_maxlen=0;
}
if (m_psrc==NULL)
{
m_psrc=(char*)__mt_char_alloc.allocate(nlen);
}
if (m_psrc)
{
m_npsrc_maxlen=nlen;
strcpy_s(m_psrc,nlen,psz);
return SetParseStr(m_psrc,pszCh,pszBAch,zychr,keepnil);
}
return false;
}
//------------------------------------------------------------------------
bool CEasyStrParse::SetParseStr(char* psz,char* pszCh,char* pszBAch,char zychr,bool keepnil){
m_pszParams.clear();
m_pszParams.reserve(8);
m_zychr=zychr;
m_pStart=NULL;
m_pSrcStart=NULL;
m_pch=NULL;
m_pBAch=NULL;
m_bokeepnil=keepnil;
if (SetBAch(pszBAch)){
if (psz){
m_pSrcStart=psz;
m_pStart=psz;
SetCh(pszCh);
return true;
}
else{return false;}
}
return false;
}
//------------------------------------------------------------------------
bool CEasyStrParse::SetCh(char* psz){
m_pch=(char *)&NullChar;
if (psz){ m_pch=psz; return true;}
return false;
}
//------------------------------------------------------------------------
bool CEasyStrParse::SetBAch(char* psz){
m_pBAch=(char *)&NullChar;
if (psz==NULL){ return true;}
else if ((strlen(psz) % 2)==0){m_pBAch=psz;return true;}
return false;
}
//------------------------------------------------------------------------
char* CEasyStrParse::Param(int i)
{
char* pRet=NULL;
i++;
if(i<1){
return m_pSrcStart;
}
if ((size_t)i<=m_pszParams.size()){
pRet= m_pszParams[i-1];
}else{
ParseParam(i);
if ((size_t)i<=m_pszParams.size()){
pRet= m_pszParams[i-1];
}
}
if (pRet==NULL){pRet=(char *)&NullChar;}
return pRet;
}
//------------------------------------------------------------------------
const char* vformat(const char* pszFmt,...)
{
va_list ap;
va_start( ap, pszFmt );
_GET_TLS_LOOPCHARBUF(1024);
_vsnprintf(ptlsbuf,ntlslen,pszFmt,ap);
ptlsbuf[ntlslen-1] = 0;
va_end ( ap );
return ptlsbuf;
}
//------------------------------------------------------------------------
const char* itochina(int i)
{
if ( i>9 ) i = 9;
static char china[10][3]={"零","一","二","三","四","五","六","七","八","九"};
return china[i];
}
//------------------------------------------------------------------------
char* endate2date(char* src)
{
CEasyStrParse parse;
char sztempdate[32];
strcpy_s(sztempdate,sizeof(sztempdate)-1,src);
parse.SetParseStr(sztempdate," ",NULL);
src=parse[0];
int mm=0;
switch(src[0])
{
case 'J':
{
if (src[1]=='a')
mm= 01;
else if (src[2]=='l')
mm= 07;
else
mm= 06;
}
break;
case 'F': mm= 02;break;
case 'M':
{
if (src[2]=='r')
mm= 03;
else
mm= 05;
}
break;
case 'A':
{
if (src[1]=='u')
mm= 04;
else
mm= 8;
}
break;
case 'S': mm= 9;break;
case 'O': mm= 10;break;
case 'N': mm= 11;break;
case 'D': mm= 12;break;
}
_GET_TLS_LOOPCHARBUF(1024);
sprintf_s(ptlsbuf,ntlslen-1,"%s-%2.2d-%s",parse[2],mm,parse[1]);
ptlsbuf[ntlslen-1] = 0;
return ptlsbuf;
}
//------------------------------------------------------------------------
const char* sec2str(int iSecond)
{
int second = iSecond % 60;
int minute = iSecond / 60;
int hour = minute / 60;
int day = hour / 24;
_GET_TLS_LOOPCHARBUF(1024);
if( iSecond < 0 )
{
return "";
}
else if( iSecond < 60 )
{
_snprintf(ptlsbuf,ntlslen-1,"%d 秒",iSecond);
ptlsbuf[ntlslen-1] = 0;
}
else if( iSecond < 60*60 )
{
_snprintf(ptlsbuf,ntlslen-1,"%d分%d秒",minute%60,second);
ptlsbuf[ntlslen-1] = 0;
}
else if( iSecond < 60*60*24 )
{
_snprintf(ptlsbuf,ntlslen-1,"%d小时%d分%d秒",hour,minute%60,second);
ptlsbuf[ntlslen-1] = 0;
}
else
{
_snprintf(ptlsbuf,ntlslen-1,"%d天%d小时%d分%d秒",day,hour%24,minute%60,second);
ptlsbuf[ntlslen-1] = 0;
}
return ptlsbuf;
}
//------------------------------------------------------------------------
char* find_path_dian_houzui(const char* pname)
{
char* p=(char*)strrchr(pname,'.');
if (p && p[1]!='\\' && p[1]!='/'){
const char* p1=safe_max(strrchr(pname,'\\'),strrchr(pname,'/'));
if (p>p1){
return p;
}
};
return NULL;
}
//------------------------------------------------------------------------
const char* extractfiletitle(const char* pname)
{
return changefileext(extractfilename(pname),"");
}
//------------------------------------------------------------------------
const char* extractfilename(const char* pname)
{
if (!pname){return pname;}
const char* p=safe_max(strrchr(pname,'\\'),strrchr(pname,'/'));
if (p){p++;}else{p=pname;}
_GET_TLS_LOOPCHARBUF(1024);
strcpy_s(ptlsbuf,ntlslen-1,p);
ptlsbuf[ntlslen-1] = 0;
return ptlsbuf;
}
//------------------------------------------------------------------------
const char* extractfiledir(const char* pname)
{
if (!pname){return pname;}
_GET_TLS_LOOPCHARBUF(1024);
strcpy_s(ptlsbuf,ntlslen-1,pname);
int nlen=strlen(ptlsbuf);
if (nlen>0)
{
char* p=find_path_dian_houzui(ptlsbuf);
if (p==NULL){if (ptlsbuf[nlen-1]=='\\' || ptlsbuf[nlen-1]=='/'){ptlsbuf[nlen-1]=0;}}
else
{
char* pend=ptlsbuf+nlen-1;
while (pend>=ptlsbuf){if (*pend=='/' || *pend=='\\' ){break;};pend--;};
if (pend<ptlsbuf){ptlsbuf[0]=0;}
else if (pend<p){*pend=0;}
}
}
ptlsbuf[ntlslen-1] = 0;
return ptlsbuf;
}
//------------------------------------------------------------------------
const char* extractfilepath(const char* pname)
{
if (!pname){return pname;}
_GET_TLS_LOOPCHARBUF(1024);
strcpy_s(ptlsbuf,ntlslen-1,pname);
int nlen=strlen(ptlsbuf);
if (nlen>0)
{
char* p=find_path_dian_houzui(ptlsbuf);
if (p==NULL){if (ptlsbuf[nlen-1]!='\\' && ptlsbuf[nlen-1]!='/'){ptlsbuf[nlen]='\\';ptlsbuf[nlen+1]=0;}}
else
{
char* pend=ptlsbuf+nlen-1;
while (pend>=ptlsbuf){if (*pend=='/' || *pend=='\\' ){break;};pend--;};
if (pend<ptlsbuf){ptlsbuf[0]=0;}
else if (pend<p){*(pend+1)=0;}
}
}
ptlsbuf[ntlslen-1] = 0;
return ptlsbuf;
}
//------------------------------------------------------------------------
const char* extractfileext(const char* pname)
{
if (!pname){return pname;}
_GET_TLS_LOOPCHARBUF(1024);
char* p=find_path_dian_houzui(pname);
if (p){p++;strcpy_s(ptlsbuf,ntlslen-1,p);}
else {ptlsbuf[0]=0;};
ptlsbuf[ntlslen-1] = 0;
return ptlsbuf;
}
//------------------------------------------------------------------------
const char* changefileext(const char* pname,const char* pchg){
if (!pname){return pname;}
_GET_TLS_LOOPCHARBUF(1024);
strcpy_s(ptlsbuf,ntlslen-1,pname);
char* p=find_path_dian_houzui(ptlsbuf);
if (p && strlen(pchg)>0 && pchg[0]!='.'){p++;};
if (p){strcpy_s(p,ntlslen-(p-ptlsbuf)-1,pchg);}
return ptlsbuf;
}
//------------------------------------------------------------------------
const char* addfileext(const char* pname,const char* padd,char bchg){
if (!pname || !padd){return pname;}
_GET_TLS_LOOPCHARBUF(1024);
strcpy_s(ptlsbuf,ntlslen-1,pname);
char* p=find_path_dian_houzui(ptlsbuf);
if (p){*p=bchg;}
if (padd[0]!='.'){strncat(ptlsbuf,".",ntlslen-1);}
strncat(ptlsbuf,padd,ntlslen-1);
ptlsbuf[ntlslen-1] = 0;
return ptlsbuf;
}
//------------------------------------------------------------------------
char* getwithtimefilename(char* srcpch){
if (srcpch){
char pch[MAX_PATH]={0};
strcpy_s(pch,sizeof(pch),srcpch);
time_t ti = time(NULL);
tm* t = localtime(&ti);
char szTime[MAX_PATH];
strftime(szTime,MAX_PATH,"%y%m%d%H%M%S",t);
_GET_TLS_LOOPCHARBUF(1024);
char* p=find_path_dian_houzui(pch);
if(p){*p=0;p++;}
else{p="";}
sprintf_s(ptlsbuf,ntlslen-1,"%s_%s.%s\0",pch,szTime,p);
ptlsbuf[ntlslen-1] = 0;
return ptlsbuf;
}
return NULL;
}
//------------------------------------------------------------------------
void replacelashPath(char *str,bool front){
char src=(!front)?'\\':'/';
char dst=front?'\\':'/';
while(*str){
if(*str == src)
*str =dst;
str++;
}
}
//------------------------------------------------------------------------
char* timetostr(time_t time1,char *szTime,int nLen,const char* sformat){
struct tm tm1;
memset(&tm1,0,sizeof(tm1));
_GET_TLS_LOOPCHARBUF(1024);
localtime_s(&tm1,&time1);
sprintf_s( ptlsbuf,ntlslen-1, sformat,tm1.tm_year+1900, tm1.tm_mon+1, tm1.tm_mday,tm1.tm_hour, tm1.tm_min,tm1.tm_sec);
ptlsbuf[ntlslen-1] = 0;
if (szTime)
{
strcpy_s(szTime,nLen,ptlsbuf);
}
return ptlsbuf;
}
//------------------------------------------------------------------------
time_t strtotime(const char * szTime,const char* sformat)
{
if( !szTime )
return 0;
std::string _TimeFormat = szTime;
if( _TimeFormat.find( '/' ) != string::npos )
{
sformat = "%4d/%2d/%2d %2d:%2d:%2d";
}
else
{
sformat = "%4d-%2d-%2d %2d:%2d:%2d";
}
struct tm tm1;
memset(&tm1,0,sizeof(tm1));
time_t time1;
sscanf_s(szTime, sformat,
&tm1.tm_year,
&tm1.tm_mon,
&tm1.tm_mday,
&tm1.tm_hour,
&tm1.tm_min,
&tm1.tm_sec);
tm1.tm_year -= 1900;
tm1.tm_mon --;
tm1.tm_isdst=-1;
time1 = mktime(&tm1);
return time1;
}
//------------------------------------------------------------------------
void str_replace(const char* pszSrc,char* pszDst,int ndlen ,const char* pszOld,const char* pszNew){
const char* p,*q;
char *q1;
int len_old = (int)strlen(pszOld);
int len_new = (int)strlen(pszNew);
int nnext=(int)strlen(pszSrc)+(len_new-len_old);
int l;
q = pszSrc;
q1 = pszDst;
for(;;){
p = strstr(q,pszOld);
if(p == NULL || nnext>=ndlen){
strcpy(q1,q);
break;
}else{
l = (int)(p-q);
memcpy(q1,q,l);
q1 += l;
memcpy(q1,pszNew,len_new);
q1 += len_new;
q = p + len_old;
q1[0]=0;
nnext +=(len_new-len_old);
}
}
}
//------------------------------------------------------------------------
void str_replace(char* pszSrc,const char* pszOld,const char* pszNew)
{
int len = (int)strlen(pszSrc);
STACK_ALLOCA(char*,psz,len*4);
if (psz){
str_replace(pszSrc,psz,len*2,pszOld,pszNew);
strcpy(pszSrc,psz);
}
}
//------------------------------------------------------------------------
void str_replace(char* pszSrc,char cOld,char cNew){
while(*pszSrc){
if((*pszSrc) & 0x80){
if(!(*(pszSrc+1))) break;
pszSrc+=2;
}else{
if(*pszSrc == cOld)
*pszSrc = cNew;
pszSrc++;
}
}
}
//------------------------------------------------------------------------
void str_replace(char* pszSrc,wchar_t cOld,wchar_t cNew){
while(*pszSrc){
if((*pszSrc) & 0x80){
if(!(*(pszSrc+1))) break;
if((*(wchar_t*)pszSrc) == cOld){
(*(wchar_t*)pszSrc) = cNew;
}
pszSrc+=2;
}else{
pszSrc++;
}
}
}
//------------------------------------------------------------------------
std::string str_Replace(std::string &strText,const char *pszSrcText,const char *pszDestText){
char *p = (char*)strstr(strText.c_str(),pszSrcText);
if(!p) return strText;
size_t size = (size_t )(p - strText.c_str());
while(size <= strText.length() - strlen(pszSrcText) || !p)
{
strText.replace(size,strlen(pszSrcText),pszDestText);
if(size_t ( p - strText.c_str()) > strText.length() - 2) break;
p = strstr(p+1,pszSrcText);
if(!p) break;
size = (size_t )(p - strText.c_str()) + 1;
}
return strText;
}
//------------------------------------------------------------------------
void str_del(char* pszSrc,char c){
while(*pszSrc){
if((*pszSrc) & 0x80){
if(!(*(pszSrc+1))) break;
pszSrc+=2;
}else{
if((*pszSrc) == c){
strcpy(pszSrc,pszSrc+1);
}else{
pszSrc++;
}
}
}
}
//------------------------------------------------------------------------
void str_del(char* pszSrc,wchar_t c){
while(*pszSrc){
if((*pszSrc) & 0x80){
if(!(*(pszSrc+1))) break;
if((*(wchar_t*)pszSrc) == c){
strcpy(pszSrc,pszSrc+2);
}else{
pszSrc+=2;
}
}else{
pszSrc++;
}
}
}
//------------------------------------------------------------------------
void str_del(char* pszSrc,int c){
if(c & 0x80)
str_del(pszSrc,(wchar_t)c);
else
str_del(pszSrc,(char)c);
}
//------------------------------------------------------------------------
void str_del_sp( char* pszSrc, char c )
{
char* pszStr = pszSrc;
while ( *pszStr ){
if ( *pszStr == c ){
if ( !(*(pszStr+1)) ){
strcpy( pszSrc, pszStr );
break;
}
if ( *(pszStr+1) == c ){
pszStr++ ;
}else{
strcpy( pszSrc++, pszStr );
pszStr = pszSrc;
}
}else{
if ( (*pszStr) & 0x80 ){
if ( !(*(pszStr+1)) ) break;
pszStr += 2;
}else{
pszStr++ ;
}
pszSrc = pszStr;
}
}
}
//------------------------------------------------------------------------
void str_del_sp_full( char* pszSrc, char c )
{
char* pszStr = pszSrc;
while ( *pszStr ){
if ( *pszStr == c ){
if ( !(*(pszStr+1)) ){
strcpy( pszSrc, pszStr+1 );
break;
}else{
if ( *(pszStr+1) == c ){
pszStr++ ;
}else{
strcpy( pszSrc, ++pszStr );
pszStr = pszSrc;
}
}
}
else{
if ( (*pszStr) & 0x80 ){
if ( !(*(pszStr+1)) ) break;
pszStr += 2;
}else{
pszStr++ ;
}
pszSrc = pszStr;
}
}
}
//------------------------------------------------------------------------
#include <tchar.h>
//------------------------------------------------------------------------
BOOL str_isempty(const char* psz)
{
if(psz == NULL) return TRUE;
while(*psz)
{
if((*psz) & 0x80)
{
if(!(*(psz+1))) break;
if(!_ismbcspace(*((WORD*)psz))) break;
psz+=2;
}
else
{
if(!isspace(*psz)) break;
psz++;
}
}
return (*psz == 0);
}
//------------------------------------------------------------------------
char* str_cpy(char* pszDest,const char* pszSrc,int len){
int i = 0;
char* p = pszDest;
while(*pszSrc){
if((*pszSrc) & 0x80){
if(*(pszSrc+1) == 0) break;
if(len-i <= 2) break;
*(unsigned short*)pszDest = *(const unsigned short*)pszSrc;
pszDest += 2;
pszSrc += 2;
i+=2;
}else{
if(len-i <= 1) break;
*pszDest = *pszSrc;
++pszDest;
++pszSrc;
++i;
}
}
*pszDest = 0;
return p;
}
//------------------------------------------------------------------------
void str_trim_right(char* psz){
char* p = psz;
char* p1 = NULL;
while(*p){
if((*p) & 0x80){
if(iswspace(*((WORD*)p))){
if(p1 == NULL)
p1 = p;
}else{
if(p1)p1 = NULL;
}
p+=2;
}else{
if(isspace(*p)){
if(p1 == NULL)
p1 = p;
}else{
if(p1)p1 = NULL;
}
p++;
}
}
if(p1) *p1 = 0;
}
//------------------------------------------------------------------------
void str_trim_left(char* psz){
char* p = psz;
while(*p){
if((*p) & 0x80){
if(iswspace(*((WORD*)p))){}
else{break;}
p+=2;
}else{
if(isspace(*p)){}
else{break;}
p++;
}
}
strcpy(psz,p);
}
//------------------------------------------------------------------------
void str_trim(char* psz){
str_trim_left(psz);
str_trim_right(psz);
}
//------------------------------------------------------------------------
WORD cA2W(WORD ch){
BYTE wcstr[2];
if(ch & 0x80){
BYTE* p = (BYTE*)&ch;
wcstr[0] = p[1];
wcstr[1] = p[0];
}else{
wcstr[0] = (BYTE)ch;
wcstr[1] = 0;
}
return *(WORD*)wcstr;
}
//------------------------------------------------------------------------
WORD cW2A(WORD ch){
BYTE mbstr[2];
if( ch & 0xff00 ){
BYTE* p = (BYTE*)&ch;
mbstr[0] = p[1];
mbstr[1] = p[0];
}else{
mbstr[0] = (BYTE)(WORD)ch;
mbstr[1] = 0;
}
return *(WORD*)mbstr;
}
//------------------------------------------------------------------------
int AsciiToUnicode(const char * szAscii, wchar_t * szUnicode){
DWORD dwNum = MultiByteToWideChar(CP_ACP,0,szAscii,-1,NULL,0);
dwNum = MultiByteToWideChar(CP_ACP,0,szAscii,-1,szUnicode,dwNum);
szUnicode[dwNum]=0;
return dwNum;
}
//------------------------------------------------------------------------
int UnicodeToAscii(const wchar_t * szUnicode, char * szAscii){
DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,szUnicode,-1,NULL,0,NULL,FALSE);
dwNum = WideCharToMultiByte(CP_OEMCP,NULL,szUnicode,-1,szAscii,dwNum,NULL,FALSE);
szAscii[dwNum]=0;
return dwNum;
}
//------------------------------------------------------------------------
bool isnumber(const char* pstr){
if (!(pstr[0]=='+' || pstr[0]=='-' || (pstr[0]>='0' && pstr[0]<='9'))){ return false; }
int diancount=0;
pstr++;
while(pstr[0]!=0){
if (pstr[0]>='0' && pstr[0]<='9'){
pstr++;
}else if(pstr[0]=='.' && diancount==0){
diancount++;
pstr++;
}else{
return false;
}
}
return true;
}
//------------------------------------------------------------------------
size_t sA2W(wchar_t *wcstr,const char *mbstr,size_t count ){
size_t i = 0;
size_t ret = 0;
while(i < count && mbstr[i]){
if(mbstr[i] & 0x80){
if( i+1 >= count || mbstr[i + 1] == 0) break;
BYTE* p = (BYTE*)&wcstr[ret++];
p[0] = mbstr[i+1];
p[1] = mbstr[i];
i+=2;
}else{
wcstr[ret++] = (WORD)(BYTE)mbstr[i];
i++;
}
}
wcstr[ret] = 0;
return ret;
}
//------------------------------------------------------------------------
size_t sW2A(char *mbstr,const wchar_t *wcstr,size_t count ){
size_t i = 0;
size_t ret = 0;
while( i < count && wcstr[i]){
if(wcstr[i] & 0xff00){
BYTE* p = (BYTE*)&wcstr[i];
mbstr[ret++] = p[1];
mbstr[ret++] = p[0];
i++;
}else{
mbstr[ret++] = (BYTE)(WORD)wcstr[i];
i++;
}
}
mbstr[ret] = 0;
return ret;
}
//------------------------------------------------------------------------
int getcharcount(const char * str){
size_t i = 0;
size_t ret = 0;
while(str[i]){
if(str[i] & 0x80){
if( str[i + 1] == 0) break;
ret++;
i+=2;
}else{
ret++;
i++;
}
}
return ret;
}
//------------------------------------------------------------------------
void str_split(const char* pszSrc,char* pszDst,size_t nDstBufLen,size_t nLineLen){
size_t i;
i =0;
while(*pszSrc){
if((*pszSrc) & 0x80){
if(!(*(pszSrc+1))) break;
if(i+1 >= nLineLen){
if(nDstBufLen < 2) break;
*pszDst++ = '\n';
nDstBufLen--;
i = 0;
}
if(nDstBufLen<3) break;
*pszDst++ = *pszSrc++;
*pszDst++ = *pszSrc++;
nDstBufLen-=2;
i+=2;
}else{
if(i >= nLineLen){
if(nDstBufLen < 2) break;
*pszDst++ = '\n';
nDstBufLen--;
i = 0;
}
if(nDstBufLen < 2) break;
*pszDst++ = *pszSrc++;
nDstBufLen--;
i++;
}
}
*pszDst = 0;
}
//------------------------------------------------------------------------
long str_getnextl(const char* pszString,char** endptr,int base){
char* p;
long l = strtol(pszString,&p,10);
char* result = p;
while( *p ){
++p;
result = p;
strtol(result,&p,base);
if(result != p) break;
}
if(endptr)
*endptr = result;
return l;
}
//------------------------------------------------------------------------
void to_lower(std::string &s){
std::transform(s.begin(), s.end(),
s.begin(),
tolower);
}
//------------------------------------------------------------------------
void to_upper(std::string &s){
std::transform(s.begin(), s.end(),
s.begin(),
toupper);
}
//------------------------------------------------------------------------
size_t string_key_hash::operator()(const std::string &x) const{
#ifdef _NOT_USE_STLPORT
/*stdext::*/hash<const char *> H;
#else
std::hash<const char *> H;
#endif
return H(x.c_str());
}
//------------------------------------------------------------------------
size_t string_key_case_hash::operator()(const std::string &x) const{
ZSTACK_ALLOCA(char*,ptmpbuf,x.length()+1);
strcpy(ptmpbuf,x.c_str());
strlwr(ptmpbuf);
#ifdef _NOT_USE_STLPORT
/*stdext::*/hash<const char *> H;
#else
std::hash<const char *> H;
#endif
return H(ptmpbuf);
}
//------------------------------------------------------------------------
bool string_key_equal::operator()(const std::string &s1, const std::string &s2) const{
return strcmp(s1.c_str(), s2.c_str()) == 0;
}
//------------------------------------------------------------------------
bool string_key_case_equal::operator()(const std::string &s1, const std::string &s2) const{
return stricmp(s1.c_str(), s2.c_str()) == 0;
}
//------------------------------------------------------------------------
size_t pchar_key_hash::operator()(const char* x) const{
#ifdef _NOT_USE_STLPORT
/*stdext::*/hash<const char *> H;
#else
std::hash<const char *> H;
#endif
return H(x);
}
//------------------------------------------------------------------------
size_t pchar_key_case_hash::operator()(const char* x) const{
ZSTACK_ALLOCA(char*,ptmpbuf,strlen(x)+1);
strcpy(ptmpbuf,x);
strlwr(ptmpbuf);
#ifdef _NOT_USE_STLPORT
/*stdext::*/hash<const char *> H;
#else
std::hash<const char *> H;
#endif
return H(ptmpbuf);
}
//------------------------------------------------------------------------
bool pchar_key_equal::operator()(const char* s1, const char* s2) const{
return strcmp(s1, s2) == 0;
}
//------------------------------------------------------------------------
bool pchar_key_case_equal::operator()(const char* s1, const char* s2) const{
return stricmp(s1, s2) == 0;
}
//------------------------------------------------------------------------
|
#include <iostream>
using namespace std;
//Base Class
class Parent
{
public:
int parent_id;
};
//Derived Class 1
class Child1 : public Parent
{
public:
int child1_id;
};
//Derived Class 2
class Child2 : public Child1
{
public:
int child2_id;
};
int main()
{
Child2 obj;
obj.parent_id=1;
obj.child1_id=2;
obj.child2_id=3;
cout<<"Parent is:"<<obj.parent_id<<endl;
cout<<"Child1 is:"<<obj.child1_id<<endl;
cout<<"Child2 is:"<<obj.child2_id;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Markus Johansson
*/
#include "core/pch.h"
#ifdef SESSION_SUPPORT
#include "adjunct/desktop_util/filelogger/desktopfilelogger.h"
#include "adjunct/desktop_util/sessions/opsessionmanager.h"
#include "adjunct/desktop_util/sessions/opsession.h"
#include "adjunct/quick/application/SessionLoadContext.h"
#include "modules/util/opfile/opfile.h"
#include "modules/dochand/win.h"
#include "modules/dochand/winman.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/prefsfile/prefssection.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/util/filefun.h"
#include "modules/util/opfile/opmemfile.h"
#define SESSION_BACKUP_DELAY (5 * 60) // every 5 minutes
#define AUTOSAVE_SESSION_NAME UNI_L("autosave")
#define DATA_BUFFER_LEN 256
void
OpSessionManager::InitL()
{
OP_STATUS rc;
BOOL backup_restored;
OpStatus::Ignore(g_session_manager->RestoreBackupSessionIfNeeded(backup_restored));
TRAP(rc, ScanSessionFolderL());
}
void
OpSessionManager::BackupAutosaveSessionL()
{
OpFile dest; ANCHOR(OpFile, dest);
LEAVE_IF_ERROR(dest.Construct(AUTOSAVE_SESSION_NAME UNI_L(".win.bak"), OPFILE_SESSION_FOLDER));
OpFile src; ANCHOR(OpFile, src);
LEAVE_IF_ERROR(src.Construct(AUTOSAVE_SESSION_NAME UNI_L(".win"), OPFILE_SESSION_FOLDER));
LEAVE_IF_ERROR(dest.CopyContents(&src, FALSE));
m_last_backup_time = op_time(NULL);
}
BOOL
OpSessionManager::NeedAutosaveSessionBackup()
{
time_t time_now = op_time(NULL);
return (m_last_backup_time == 0) || (m_last_backup_time + SESSION_BACKUP_DELAY < time_now);
}
OP_STATUS
OpSessionManager::RestoreBackupSessionIfNeeded(BOOL& backup_restored)
{
backup_restored = FALSE;
OpFile src;
RETURN_IF_ERROR(src.Construct(AUTOSAVE_SESSION_NAME UNI_L(".win.bak"), OPFILE_SESSION_FOLDER));
OpFile dest;
RETURN_IF_ERROR(dest.Construct(AUTOSAVE_SESSION_NAME UNI_L(".win"), OPFILE_SESSION_FOLDER));
BOOL exists;
RETURN_IF_ERROR(src.Exists(exists)); // backup
if(exists)
{
// we have a backup file
RETURN_IF_ERROR(dest.Exists(exists)); // default session
if(exists)
{
bool session_valid = false;
// we have a default session file
OpFileLength len, backup_len;
RETURN_IF_ERROR(dest.GetFileLength(len));
RETURN_IF_ERROR(src.GetFileLength(backup_len));
// if file is too small and it cannot be valid
if(len > 64)
{
// open the session and sniff the content
RETURN_IF_ERROR(dest.Open(OPFILE_READ));
if(dest.IsOpen())
{
OpFileLength bytes_read = 0;
char data_buffer[DATA_BUFFER_LEN];
RETURN_IF_ERROR(dest.Read(data_buffer, DATA_BUFFER_LEN - 1, &bytes_read));
data_buffer[bytes_read] = '\0';
// go through the buffer to see if we have something that resembles a .ini section
for(int i = 0; i < bytes_read - 10; i++)
{
// first section is [session]
if(data_buffer[i] == '[' && op_strncmp(&data_buffer[i+1], "session]", 8) == 0)
{
session_valid = true;
break;
}
}
dest.Close();
}
}
if(!session_valid)
{
// backup file exists and the main session is empty, copy the backup over
RETURN_IF_ERROR(dest.CopyContents(&src, FALSE));
backup_restored = TRUE;
}
}
else
{
// we have no main session file but we do have a backup file, us that
RETURN_IF_ERROR(dest.CopyContents(&src, FALSE));
backup_restored = TRUE;
}
}
return OpStatus::OK;
}
const OpStringC
OpSessionManager::GetSessionNameL(UINT32 index)
{
if( index >= GetSessionCount() )
return 0;
else
return *m_sessions.Get(index);
}
OpSession*
OpSessionManager::ReadSessionL(UINT32 index)
{
if (index >= GetSessionCount() )
return 0;
else
return ReadSessionL(*m_sessions.Get(index));
}
OpSession*
OpSessionManager::ReadSession(UINT32 index)
{
OpSession* session = NULL;
TRAPD(err, session = ReadSessionL(index));
return OpStatus::IsSuccess(err) ? session : NULL;
}
BOOL
OpSessionManager::DeleteSessionL(UINT32 index)
{
OpFile file; ANCHOR(OpFile, file);
OpString filename; ANCHOR(OpString, filename);
if (NULL == m_sessions.Get(index))
{
return FALSE;
}
filename.SetL(*m_sessions.Get(index));
filename.AppendL(UNI_L(".win"));
LEAVE_IF_ERROR(file.Construct(filename.CStr(), OPFILE_SESSION_FOLDER));
BOOL deleted = OpStatus::IsSuccess(file.Delete());
m_sessions.Delete(index);
return deleted;
}
void
OpSessionManager::DeleteAllSessionsL()
{
while (GetSessionCount())
{
DeleteSessionL(0);
}
}
OpSession*
OpSessionManager::CreateSessionL(const OpStringC& name)
{
OpFile file; ANCHOR(OpFile, file);
OpString filename; ANCHOR(OpString, filename);
filename.SetL(name);
filename.AppendL(UNI_L(".win"));
LEAVE_IF_ERROR(file.Construct(filename.CStr(), OPFILE_SESSION_FOLDER));
OpStackAutoPtr<PrefsFile> prefsfile(CreatePrefsFileL(&file));
OpStackAutoPtr<OpSession> session(OP_NEW_L(OpSession, ()));
// we don't want cascading
#ifdef PF_CAP_CASCADE_DISABLE
prefsfile->SetDisableCascade();
#endif // PF_CAP_CASCADE_DISABLE
session->InitL(prefsfile.get());
prefsfile.release();
return session.release();
}
OpSession*
OpSessionManager::CreateSessionFromFileL(const OpFile* file)
{
OpStackAutoPtr<PrefsFile> prefsfile(CreatePrefsFileL(file));
OpStackAutoPtr<OpSession> session(OP_NEW_L(OpSession, ()));
session->InitL(prefsfile.get());
prefsfile.release();
return session.release();
}
OpSession*
OpSessionManager::CreateSessionFromFile(const OpFile* file)
{
OpSession* session = NULL;
TRAPD(err, session = CreateSessionFromFileL(file));
return OpStatus::IsSuccess(err) ? session : NULL;
}
OpSession* OpSessionManager::CreateSessionInMemoryL()
{
OpStackAutoPtr<OpMemFile> memfile(OP_NEW_L(OpMemFile, ()));
OpStackAutoPtr<PrefsFile> prefsfile(CreatePrefsFileL(memfile.get()));
OpStackAutoPtr<OpSession> session(OP_NEW_L(OpSession, ()));
session->InitL(prefsfile.get(), TRUE);
prefsfile.release();
return session.release();
}
void
OpSessionManager::WriteSessionToFileL(OpSession* session, BOOL reset_after_write)
{
if(m_read_only)
{
session->Cancel(); // avoid save in the destructor
return;
}
if(NeedAutosaveSessionBackup())
{
// Don't want to propagate this as writing is more important
TRAPD(err, BackupAutosaveSessionL());
}
session->WriteToFileL(reset_after_write);
}
// private functions below
void
OpSessionManager::ScanSessionFolderL()
{
m_sessions.DeleteAll();
OpStackAutoPtr<OpFolderLister> lister(OpFile::GetFolderLister(OPFILE_SESSION_FOLDER, UNI_L("*.win")));
LEAVE_IF_NULL(lister.get());
while (lister->Next())
{
if (!lister->IsFolder())
{
OpStackAutoPtr<OpString> path(OP_NEW_L(OpString, ()));
const uni_char* filename = lister->GetFileName();
path->SetL(filename, uni_strlen(filename) - 4);
LEAVE_IF_ERROR(m_sessions.Add(path.get()));
path.release();
}
}
}
OpSession*
OpSessionManager::ReadSessionL(const OpStringC& name)
{
OpStackAutoPtr<OpSession> session (CreateSessionL(name));
session->LoadL();
return session.release();
}
OpSession*
OpSessionManager::ReadSession(const OpStringC& name)
{
OpSession* session = NULL;
TRAPD(err, session = ReadSessionL(name));
return OpStatus::IsSuccess(err) ? session : NULL;
}
UINT32
OpSessionManager::GetClosedSessionCount() const
{
return m_session_load_context ? m_session_load_context->GetClosedSessionCount() : 0;
}
OpSession*
OpSessionManager::GetClosedSession(UINT32 i) const
{
return m_session_load_context ? m_session_load_context->GetClosedSession(i) : NULL;
}
void
OpSessionManager::EmptyClosedSessions()
{
if (m_session_load_context)
m_session_load_context->EmptyClosedSessions();
}
PrefsFile*
OpSessionManager::CreatePrefsFileL(const OpFileDescriptor* file)
{
OpStackAutoPtr<OpSessionReader::SessionFileAccessor> accessor(OP_NEW_L(OpSessionReader::SessionFileAccessor, ()));
OpStackAutoPtr<PrefsFile> prefsfile(OP_NEW_L(PrefsFile, (accessor.release())));
prefsfile->ConstructL();
prefsfile->SetFileL(file);
return prefsfile.release();
}
void
OpSessionManager::AddStringToVectorL(OpVector<OpString>& vector, const OpStringC& string)
{
OpStackAutoPtr<OpString> copy(OP_NEW_L(OpString, ()));
LEAVE_IF_ERROR(copy->Set(string));
LEAVE_IF_ERROR(vector.Add(copy.get()));
copy.release();
}
void
OpSessionManager::AddValueToVectorL(OpVector<UINT32>& vector, UINT32 value)
{
UINT32* copy = OP_NEW_L(UINT32, ());
*copy = value;
OP_STATUS status = vector.Add(copy);
if (OpStatus::IsError(status))
{
OP_DELETE(copy);
LEAVE(status);
}
}
#endif // SESSION_SUPPORT
|
#include <bits/stdc++.h>
using namespace std;
struct tNode{
int data;
tNode *left;
tNode *right;
tNode(int x):data(x),left(NULL),right(NULL){}
};
class Solution{
public:
int node_count(tNode *root){
if(root == NULL){
return 0;
}
return 1 + node_count(root->left) + node_count(root->right);
}
};
int main(){
tNode *root = new tNode(1);
root->left = new tNode(2);
root->right = new tNode(3);
Solution handle;
printf("%d\n",handle.node_count(root));
return 0;
}
|
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <deque>
#include<iomanip>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <climits>
#include <cfloat>
#include <ctime>
#include <cmath>
#include <string>
#include <cctype>
#include <cstring>
#include<complex>
#include <algorithm>
using namespace std;
char week[8][5]= {"MON","TUE","WED","THU","FRI","SAT","SUN"};
int mp[310][310];
inline int gcd(int a,int b) {
int tp;
while(b) {
tp=a%b;
a=b;
b=tp;
}
return a;
}
inline int lcm(int a,int b) {
return a*b/gcd(a,b);
}
int guass(int m,int n) {
int row,col,i,j,k,LCM,a,b,x[305],tp;
for(row=0,col=0; row<m&&col<n; row++,col++) {
k=row;
for(i=row+1; i<m; i++)
if(abs(mp[k][col])<abs(mp[i][col]))
k=i;
if(k!=row) {
for(i=col; i<=n; i++)
swap(mp[row][i],mp[k][i]);
}
if(mp[row][col]==0) {
row--;
continue;
}
for(i=row+1; i<m; i++)
if(mp[i][col]) {
LCM=lcm(abs(mp[i][col]),abs(mp[row][col]));
a=LCM/mp[row][col];
b=LCM/mp[i][col];
for(j=col; j<=n; j++)
mp[i][j]=(mp[i][j]*b-mp[row][j]*a)%7;
}
}
for(i=row; i<m; i++)
if(mp[i][n])
return -1;
if(row<n)
return 1;
for(i=n-1; i>=0; i--) {
tp=mp[i][n];
for(j=i+1; j<n; j++)
tp-=mp[i][j]*x[j];
while(tp%mp[i][i])
tp+=7;
x[i]=tp/mp[i][i];
while(x[i]<3)
x[i]+=7;
while(x[i]>9)
x[i]-=7;
}
for(i=0; i<n-1; i++)
printf("%d ",x[i]);
printf("%d\n",x[n-1]);
return 0;
}
int main() {
int m,n,k,a,b;
char st[5],ch[5];
while(scanf("%d%d",&n,&m)&&(m+n)) {
memset(mp,0,sizeof(mp));
for(int j=0; j<m; j++) {
scanf("%d%s%s",&k,st,ch);
for(int i=0; i<7; i++) {
if(strcmp(st,week[i])==0)
a=i;
if(strcmp(ch,week[i])==0)
b=i;
}
mp[j][n]=(b-a+7+1)%7;
for(int i=0; i<k; i++) {
scanf("%d",&a);
mp[j][a-1]++;
mp[j][a-1]%=7;
}
}
k=guass(m,n);
if(k==-1)
printf("Inconsistent data.\n");
else if(k==1)
printf("Multiple solutions.\n");
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
const int siz=1005;
const int INF=0x3f3f3f3f;
int rt=0;
struct node{
int ls,rs;
int val,cnt,siz;
}t[siz];
void add(int s,int v){
if(rt==0){
rt++;
t[rt].val=v;
t[rt].cnt=1;
t[rt].siz=1;
return;
}
t[s].siz++;
if(t[s].val==v){
t[s].cnt++;
return;
}
if(t[s].val<v){
if(t[s].rs!=0)
add(t[s].rs,v);
else{
rt++;
t[s].rs=rt;
t[rt].val=v;
t[rt].cnt=1;
t[rt].siz=1;
}
}
else{
if(t[s].ls!=0)
add(t[s].ls,v);
else{
rt++;
t[s].ls=rt;
t[rt].val=v;
t[rt].cnt=1;
t[rt].siz=1;
}
}
}
int GetPre(int s,int v,int ans){
if(t[s].val>=v){
if(t[s].ls!=0)
return GetPre(t[s].ls,v,ans);
else
return ans;
}
else{
if(t[s].rs==0)
return t[s].val;
else{
if(t[s].cnt!=0)
return GetPre(t[s].rs,v,t[s].val);
else
return GetPre(t[s].rs,v,ans);
}
}
}
int GetNext(int s,int v,int ans){
if(t[s].val<=v){
if(t[s].rs!=0)
return GetNext(t[s].rs,v,ans);
else
return ans;
}
else{
if(t[s].ls==0)
return t[s].val;
else{
if(t[s].cnt!=0)
return GetNext(t[s].ls,v,t[s].val);
else
return GetNext(t[s].ls,v,ans);
}
}
}
int GetValbyRank(int s,int rk){
if(s==0)
return INF;
if(t[t[s].ls].siz>=rk)
return GetValbyRank(t[s].ls,rk);
else if(t[t[s].ls].siz+t[s].cnt>=rk)
return t[s].val;
else
return GetValbyRank(t[s].rs,rk-t[t[s].ls].siz-t[s].cnt);
}
int GetRankbyVal(int s,int v){
if(s==0)
return INF;
if(t[s].val==v)
return t[t[s].ls].siz+1;
else if(t[s].val>v)
return GetRankbyVal(t[s].ls,v);
else
return GetRankbyVal(t[s].rs,v)+t[t[s].ls].siz+t[s].cnt;
}
|
#ifndef GNRENDEROBJECTARRAY_H
#define GNRENDEROBJECTARRAY_H
class GnRenderObject;
class GNMAIN_ENTRY GnRenderObjectArray : public GnMemoryObject
{
enum
{
DEF_MAX_SIZE = 1024,
DEF_GROW_BY = 1024
};
protected:
GnRenderObject** mppkArray;
gtuint mCurrentSize;
gtuint mAllocatedSize;
gtuint mGrowBy;
public:
inline GnRenderObjectArray()
{
mppkArray = NULL;
mCurrentSize = 0;
mAllocatedSize = 0;
mGrowBy = DEF_GROW_BY;
SetAllocatedSize(DEF_MAX_SIZE);
}
inline GnRenderObjectArray(gtuint uiMaxSize, gtuint uiGrowBy)
{
mppkArray = NULL;
mCurrentSize = 0;
mAllocatedSize = 0;
mGrowBy = uiGrowBy;
if (mGrowBy == 0)
mGrowBy = 1;
SetAllocatedSize(uiMaxSize);
}
virtual ~GnRenderObjectArray();
void SetAllocatedSize(gtuint uiSize);
// adds to the end of the array, incrementing count by one
inline void Add(GnRenderObject* kObj)
{
GnAssert(mCurrentSize <= mAllocatedSize);
if (mCurrentSize == mAllocatedSize)
SetAllocatedSize(mAllocatedSize + mGrowBy);
mppkArray[mCurrentSize] = kObj;
mCurrentSize++;
}
inline void RemoveAll()
{
mCurrentSize = 0;
}
inline void SetAt(gtuint uiIndex, GnRenderObject* pObj)
{
GnAssert(uiIndex < mCurrentSize);
mppkArray[uiIndex] = pObj;
}
// uiIndex 인덱스를 지우고 그자리에 마지막에 있던 오브젝트를 집어 넣고
// 사이즈를 줄인다.
inline GnRenderObject* RemoveAtAndFill(gtuint uiIndex)
{
GnAssert(mCurrentSize != 0 && uiIndex < mCurrentSize);
GnRenderObject* deleteObject = mppkArray[uiIndex];
mCurrentSize--;
mppkArray[uiIndex] = mppkArray[mCurrentSize];
return deleteObject;
}
inline GnRenderObject* GetAt(gtuint uiIndex)
{
GnAssert(uiIndex < mCurrentSize);
return mppkArray[uiIndex];
}
inline GnRenderObject& GetAt(gtuint uiIndex) const
{
GnAssert(uiIndex < mCurrentSize);
return *(mppkArray[uiIndex]);
}
inline gtuint GetCount() const
{
return mCurrentSize;
}
inline gtuint GetAllocatedSize() const
{
return mAllocatedSize;
}
inline gtuint GetGrowBy() const
{
return mGrowBy;
}
inline void SetGrowBy(gtuint uiGrowBy)
{
if (uiGrowBy == 0)
mGrowBy = 1;
else
mGrowBy = uiGrowBy;
}
};
#endif // GNRENDEROBJECTARRAY_H
|
#pragma once
#include "ExampleBase.h"
class VertexArray : public ExampleBase
{
private:
GLuint vao;
Shader *shader;
public:
void initGLData() {
const char *className = typeid(*this).name() + 6;
shader = new Shader(className);
glViewport(0, 0, WINDOW_WIDTH - 100, WINDOW_HEIGHT - 100);
GLfloat vertices[] = {
-0.99f, -0.99f, 0.0f,
-0.99f, 0.99f, 0.0f,
0.99f, 0.99f, 0.0f,
-0.98f, -0.99f, 0.0f,
1.f, 0.99f, 0.0f,
1.f, -0.99f, 0.0f
};
GLfloat colors[] = {
1.0f, 0.5f, 0.3f, 1.0f,
0.5f, 0.7f, 1.0f, 1.0f,
0.6f, 0.2f, 0.9f, 1.0f,
0.3f, 0.7f, 0.8f, 1.0f,
0.5f, 0.7f, 1.0f, 1.0f,
1.0f, 0.5f, 0.3f, 1.0f
};
// 创建 buffer 并上传数据
GLuint bo;
glGenBuffers(1, &bo);
glBindBuffer(GL_COPY_WRITE_BUFFER, bo);
glBufferData(GL_COPY_WRITE_BUFFER, sizeof(vertices) + sizeof(colors), nullptr, GL_STATIC_DRAW);
glBufferSubData(GL_COPY_WRITE_BUFFER, 0, sizeof(vertices), vertices);
glBufferSubData(GL_COPY_WRITE_BUFFER, sizeof(vertices), sizeof(colors), colors);
glBindBuffer(GL_COPY_WRITE_BUFFER, 0);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// 把刚才上传了数据的 buffer 绑定到 GL_ARRAY_BUFFER,用以指定属性对应的数据源
glBindBuffer(GL_ARRAY_BUFFER, bo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GL_FLOAT), 0);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GL_FLOAT), (GLvoid *)sizeof(vertices));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void renderLoop() {
glClearColor(0.3f, 0.3f, 0.7f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
shader->use();
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
};
|
#include "VarianceShadowMap.h"
#include "RenderTarget.h"
#include "SceneManager.h"
#include "engine_struct.h"
#include "ResourceManager.h"
#include "pass.h"
#include "RenderSystem.h"
#include "TextureManager.h"
#include "Camera.h"
#include "OPENGL_Include.h"
#include <sstream>
void VarianceShadowMapGenerateEffect::Init()
{
auto& rt_mgr = RenderTargetManager::getInstance();
auto& tm = TextureManager::getInstance();
auto& pm = PassManager::getInstance();
mRenderSystem = GlobalResourceManager::getInstance().m_RenderSystem;
Matrix4 bias(
0.5, 0, 0, 0.5,
0, 0.5, 0, 0.5,
0, 0, 0.5, 0.5,
0, 0, 0, 1);
scale_bias = bias;
createShadowRT();
Camera c;
for (int i = 0; i < LightNum; i++) {
cameras.push_back(c);
}
shadowmap_pass = pm.LoadPass("shadowmap/VSM_prog.json");
shadowmap_pass->UseInstance = true;
blureffect.BlurFloatTexture = true;
blureffect.radius = 1.0;
blureffect.input_color = out_ShadowMapTexture[0];
blureffect.Init();
out_blur = blureffect.out_blur;
}
void VarianceShadowMapGenerateEffect::createShadowRT()
{
auto& rt_mgr = RenderTargetManager::getInstance();
auto& tm = TextureManager::getInstance();
ShadowMapRT = vector<RenderTarget*>(LightNum, NULL);
out_ShadowMapTexture = vector<Texture*>(LightNum, NULL);
out_ShadowMatrix = vector<Matrix4>(LightNum);
for (int i = 0; i < LightNum; i++) {
ShadowMapRT[i] = rt_mgr.CreateRenderTargetFromPreset("basic_float", "effect_vsm"+to_string(i));
ShadowMapRT[i]->width = width;
ShadowMapRT[i]->height = height;
for (auto tex : ShadowMapRT[i]->m_attach_textures) {
tex.second->width = width;
tex.second->height = height;
tex.second->mipmap_mode = Texture::TextureMipmap_None;
}
out_ShadowMapTexture[i] = ShadowMapRT[i]->m_attach_textures["color0"];
out_ShadowMapTexture[i]->setFormat(Texture::RG32F);
ShadowMapRT[i]->createInternalRes();
}
}
void VarianceShadowMapGenerateEffect::Render()
{
SceneManager* scene = SceneContainer::getInstance().get(input_scenename);
auto MainCamera = scene->getCamera(input_cameraname);
RenderQueue queue;
scene->getVisibleRenderQueue_as(MainCamera, queue);
for (int i = 0; i < LightNum; i++) {
Matrix4 view_light = cameras[i].getViewMatrix();
Matrix4 proj_light = cameras[i].getProjectionMatrixDXRH();
shadowmap_pass->mProgram->setProgramConstantData("proj_light", &proj_light[0][0], "mat4", sizeof(Matrix4));
shadowmap_pass->mProgram->setProgramConstantData("view_light", &view_light[0][0], "mat4", sizeof(Matrix4));
shadowmap_pass->mProgram->setProgramConstantData("LinearDepth", &LinearDepth, "int", sizeof(int));
//mRenderSystem->RenderPass(MainCamera, queue, shadowmap_pass, ShadowMapRT[i]);
mRenderSystem->RenderPass(NULL, queue, shadowmap_pass, ShadowMapRT[i]);
//out_ShadowMapTexture[i]->GenerateMipmap();
out_ShadowMatrix[i] = scale_bias*proj_light * view_light;
}
blureffect.Render();
}
void VarianceShadowMapGenerateEffect::CalcShadowMat(Camera& camera, Matrix4& out_shadow_mat)
{
auto view_light = camera.getViewMatrix();
auto proj_light = camera.getProjectionMatrixDXRH();
out_shadow_mat = scale_bias * proj_light * view_light;
}
void VarianceShadowMapGenerateEffect::SetLightCamera(Camera& camera, Vector3 lightpos, Vector3 lookcenter, float width, float height, float tnear, float tfar, bool perspective)
{
Vector3 up(0, 1, 0);
if (up == lookcenter)
up = Vector3(1, 0, 0);
camera.lookAt(lightpos, lookcenter, up);
camera.setFrustum(-width / 2, width / 2, -height / 2, height / 2, tnear, tfar);
if (perspective)
camera.setProjectionType(Camera::PT_PERSPECTIVE);
else
camera.setProjectionType(Camera::PT_ORTHOGONAL);
}
void VarianceShadowMapGenerateEffect::SetLightCamera(int index, LightCameraParam& p)
{
SetLightCamera(cameras[index], p.LightPosition, p.LightPosition + p.LightDir, p.width, p.height, p.Near, p.Far, p.perspective);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Espen Sand
*/
#ifndef X11_DESKTOP_POPUP_MENU_HANDLER_H
#define X11_DESKTOP_POPUP_MENU_HANDLER_H
#include "adjunct/desktop_pi/DesktopPopupMenuHandler.h"
#include "adjunct/desktop_scope/src/generated/g_scope_desktop_window_manager_interface.h"
class OpInputContext;
class PopupMenu;
class X11DesktopPopupMenuHandler : public DesktopPopupMenuHandler
{
public:
X11DesktopPopupMenuHandler() : menu_ctx(0) {}
void OnPopupMenu(const char* popup_name, const PopupPlacement& placement, BOOL point_in_page, INTPTR popup_value, BOOL use_keyboard_context);
BOOL OnAddMenuItem(void* menu, BOOL separator, const uni_char* item_name,
OpWidgetImage* image, const uni_char* shortcut,
const char* sub_menu_name, INTPTR sub_menu_value,
INT32 sub_menu_start, BOOL checked, BOOL selected,
BOOL disabled, BOOL bold, OpInputAction* input_action);
void OnAddShellMenuItems(void* menu, const uni_char* path) {}
BOOL ListPopupMenuInfo(OpScopeDesktopWindowManager_SI::QuickMenuList &out);
/**
* Opens a bookmark context menu.
*
* @param Upper left location of menu in global coordinate
* @parem caller The popup menu from where this menu is called. Can be 0
* @param link_action The link action to be used in the menu
*/
static void ShowBookmarkContextMenu(const OpPoint& pos, PopupMenu* caller, OpInputAction* link_action);
private:
OpInputContext *menu_ctx;
};
#endif // X11_DESKTOP_POPUP_MENU_HANDLER_H
|
#include "Output.h"
Output::Output()
{
//Initialize user interface parameters
UI.width = 1280;
UI.height = 700;
UI.wx = 15;
UI.wy =15;
UI.AppMode = DESIGN; //Design Mode is the default mode
UI.StBrWdth = 50;
UI.TlBrWdth = 50;
UI.MnItWdth = 80;
UI.DrawClr = BLUE;
UI.HiClr = RED;
UI.MsgClr = RED;
UI.ASSGN_WDTH = 150;
UI.ASSGN_HI = 50;
//Create the output window
pWind = CreateWind(UI.width, UI.height, UI.wx, UI.wy);
//Change the title
pWind->ChangeTitle("Programming Techniques Project");
pWind->SetPen(RED,3);
CreateDesignToolBar();
CreateStatusBar();
}
Input* Output::CreateInput()
{
Input* pIn = new Input(pWind);
return pIn;
}
//======================================================================================//
// Interface Functions //
//======================================================================================//
window* Output::CreateWind(int wd, int h, int x, int y)
{
return new window(wd, h, x, y);
}
//////////////////////////////////////////////////////////////////////////////////////////
void Output::CreateStatusBar()
{
pWind->DrawLine(0, UI.height-UI.StBrWdth, UI.width, UI.height-UI.StBrWdth);
}
//////////////////////////////////////////////////////////////////////////////////////////
void Output::clearToolBar()
{
pWind->SetPen(WHITE,5);
pWind->SetBrush(WHITE);
pWind->DrawRectangle(0, 0, UI.width, UI.TlBrWdth);
pWind->DrawRectangle(0, UI.TlBrWdth, UI.MnItWdth, UI.height-UI.StBrWdth);
pWind->DrawLine(UI.MnItWdth, UI.TlBrWdth, UI.MnItWdth, UI.height-UI.StBrWdth);
pWind->SetPen(RED,3);
pWind->DrawLine(0, UI.height-UI.StBrWdth, UI.width, UI.height-UI.StBrWdth);
}
//////////////////////////////////////////////////////////////////////////////////////////
void Output::CreateDesignToolBar()
{
UI.AppMode = DESIGN; //Design Mode
clearToolBar();
int i=0;
//fill the horizontal tool bar
//You can draw the tool bar icons in any way you want.
//This can be better done by storing the images name in an array then draw the toolbar using a "for" loop
pWind->DrawImage("images\\Sim Mode.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Comment.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Copy.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Cut.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Paste.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Move.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Delete.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Resize.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Zoom Out.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Zoom In.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Redo.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Undo.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Load Design.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Save.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\New.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Exit.jpg", i++ * UI.MnItWdth, 0);
//Draw a line under the toolbar
pWind->DrawLine(0, UI.TlBrWdth, UI.width, UI.TlBrWdth);
i=1;
//fill the vertical tool bar
//You can draw the tool bar icons in any way you want.
//This can be better done by storing the images name in an array then draw the toolbar using a "for" loop
pWind->DrawImage("images\\Start.jpg",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\End.jpg",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\Assign Simple.JPG",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\Assign Var.jpg",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\Assign Operator.jpg",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\Condition.jpg",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\Read.jpg",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\Write.jpg",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\Edit Statement.jpg",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\Connector.jpg",0, i++ * UI.TlBrWdth);
pWind->DrawImage("images\\Edit Connector.jpg",0, i++ * UI.TlBrWdth);
//Draw a line beside the toolbar
pWind->DrawLine(UI.MnItWdth, UI.TlBrWdth, UI.MnItWdth, UI.height-UI.StBrWdth);
}
void Output::CreateSimulationToolBar()
{
UI.AppMode = SIMULATION; //Simulation Mode
clearToolBar();
int i=0;
pWind->DrawImage("images\\Design Mode.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Run.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Step.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Generate.jpg", i++ * UI.MnItWdth, 0);
pWind->DrawImage("images\\Exit.jpg", i++ * UI.MnItWdth, 0);
//Draw a line under the toolbar
pWind->DrawLine(0, UI.TlBrWdth, UI.width, UI.TlBrWdth);
///TODO: add code to create the simulation tool bar
}
//////////////////////////////////////////////////////////////////////////////////////////
void Output::ClearStatusBar()
{
//Clear Status bar by drawing a filled white rectangle
pWind->SetPen(RED, 1);
pWind->SetBrush(WHITE);
pWind->DrawRectangle(0, UI.height - UI.StBrWdth, UI.width, UI.height);
}
//////////////////////////////////////////////////////////////////////////////////////////
void Output::ClearDrawArea()
{
pWind->SetPen(WHITE, 1);
pWind->SetBrush(WHITE);
pWind->DrawRectangle(UI.MnItWdth, UI.TlBrWdth, UI.width, UI.height - UI.StBrWdth);
}
//////////////////////////////////////////////////////////////////////////////////////////
void Output::PrintMessage(string msg) //Prints a message on status bar
{
ClearStatusBar(); //First clear the status bar
pWind->SetPen(UI.MsgClr, 50);
pWind->SetFont(20, BOLD , BY_NAME, "Arial");
pWind->DrawString(10, UI.height - UI.StBrWdth/1.5, msg);
}
//======================================================================================//
// Statements Drawing Functions //
//======================================================================================//
//Draw assignment statement and write the "Text" on it
void Output::DrawAssign(Point Left, int width, int height, string Text, bool Selected)
{
if(Selected) //if stat is selected, it should be highlighted
pWind->SetPen(UI.HiClr,3); //use highlighting color
else
pWind->SetPen(UI.DrawClr,3); //use normal color
//Draw the statement block rectangle
pWind->DrawRectangle(Left.x, Left.y, Left.x + width, Left.y + height);
//Write statement text
pWind->SetPen(BLACK, 2);
pWind->DrawString(Left.x+5, Left.y + height/4, Text);
}
////////////////////////////////////////////////////////////////////////////////////////////
//Draw start or end statement
void Output::DrawStart_End(Point Left,int width,int height,string type,bool Selected)
{
if(Selected) //if stat is selected, it should be highlighted
pWind->SetPen(UI.HiClr,3); //use highlighting color
else
pWind->SetPen(UI.DrawClr,3); //use normal color
pWind->DrawEllipse(Left.x,Left.y,Left.x+width,Left.y+height);
pWind->SetPen(BLACK, 2);
pWind->DrawString(Left.x+width/2-21, Left.y+height/2-10, type);
}
////////////////////////////////////////////////////////////////////////////////////////////
//Draw read or write statement
void Output::DrawRead_Write(Point Left,int width, int height,string type, string Text, bool Selected)
{if(Selected) //if stat is selected, it should be highlighted
pWind->SetPen(UI.HiClr,3); //use highlighting color
else
pWind->SetPen(UI.DrawClr,3); //use normal color
int x[4],y[4];
x[0]=Left.x; x[1]=x[0]+width; x[2]=x[1]-50; x[3]=x[0]-50;
y[0]=Left.y; y[1]=y[0]; y[2]=y[0]+height; y[3]=y[2];
pWind->DrawPolygon(x,y,4);
pWind->SetPen(BLACK, 2);
if(type=="READ")
pWind->DrawString(x[0], y[0]+15, "Read "+Text);
else if(type=="WRITE")
pWind->DrawString(x[0], y[0]+15, "Write "+Text);
}
////////////////////////////////////////////////////////////////////////////////////////////
//Draw condition statement
void Output::DrawCondition(Point Top,int width, int height, string Text, bool Selected)
{if(Selected) //if stat is selected, it should be highlighted
pWind->SetPen(UI.HiClr,3); //use highlighting color
else
pWind->SetPen(UI.DrawClr,3); //use normal color
int x[4],y[4];
x[0]=Top.x; x[1]=Top.x-width/2; x[2]=x[0]; x[3]=Top.x+width/2;
y[0]=Top.y; y[1]=Top.y+height/2; y[2]=y[1]+height/2; y[3]=y[1];
pWind->DrawPolygon(x,y,4);
pWind->SetPen(BLACK, 2);
pWind->DrawString(x[1]+50, y[1]-5, Text);
pWind->DrawString(x[1]-10, y[1]-20, "F");
pWind->DrawString(x[3]+5, y[3]-20, "T");
}
//Draw connector
//////////////////////////////////////////////////////////////////////////////////////////
void Output::DrawConnector(Point start,Point end,bool Selected)
{if(Selected) //if stat is selected, it should be highlighted
pWind->SetPen(UI.HiClr,3); //use highlighting color
else
pWind->SetPen(UI.DrawClr,3); //use normal color
if(end.y>start.y)
{
pWind->DrawLine(start.x,start.y,start.x,start.y+10);
pWind->DrawLine(start.x,start.y+10,end.x,start.y+10);
pWind->DrawLine(end.x,start.y+10,end.x,end.y);
pWind->DrawLine(end.x,end.y,end.x+10,end.y-10);
pWind->DrawLine(end.x,end.y,end.x-10,end.y-10);
}
else if(end.y<start.y)
{
if(end.x>start.x)
{
pWind->DrawLine(start.x,start.y,start.x,start.y+10);
pWind->DrawLine(start.x,start.y+10,start.x-150,start.y+10);
pWind->DrawLine(start.x-150,start.y+10,start.x-150,end.y);
pWind->DrawLine(start.x-150,end.y,end.x,end.y);
pWind->DrawLine(end.x,end.y,end.x-10,end.y+10);
pWind->DrawLine(end.x,end.y,end.x-10,end.y-10);
}
else
{
pWind->DrawLine(start.x,start.y,start.x,start.y+10);
pWind->DrawLine(start.x,start.y+10,start.x+150,start.y+10);
pWind->DrawLine(start.x+150,start.y+10,start.x+150,end.y);
pWind->DrawLine(start.x+150,end.y,end.x,end.y);
pWind->DrawLine(end.x,end.y,end.x+10,end.y+10);
pWind->DrawLine(end.x,end.y,end.x+10,end.y-10);
}
}
else
{
if(end.x>start.x)
{
pWind->DrawLine(start.x,start.y,end.x,end.y);
pWind->DrawLine(end.x,end.y,end.x-10,end.y+10);
pWind->DrawLine(end.x,end.y,end.x-10,end.y-10);
}
else
{
pWind->DrawLine(start.x,start.y,end.x,end.y);
pWind->DrawLine(end.x,end.y,end.x+10,end.y+10);
pWind->DrawLine(end.x,end.y,end.x+10,end.y-10);
}
}
}
void Output::DrawExitMsg()
{
pWind->DrawImage("images\\ExitMsg.jpg", UI.width/2-150, UI.height/2-75);
}
void Output::DrawCondMsg()
{
pWind->DrawImage("images\\CondMsg.jpg", UI.width/2-150, UI.height/2-75);
}
window* Output::getwindow()
{
return pWind;
}
///////////////////////////////////////////////////////////////////////////////////////////
Output::~Output()
{
delete pWind;
}
void Output::DrawImage(image *img,Point p1, Point p2)
{
pWind->DrawImage(img,p1.x,p1.y,p2.x,p2.y);
}
|
#ifndef REAL_H
#define REAL_H
class Real{
private:
int numerador;
int denominador;
void reducir();
void setNumerador(int=0);
void setDenominador(int=1);
public:
Real(int =1, int =1);
int getNumerador();
int getDenominador();
void setReal(int = 0, int =1);
void imprimir();
Real suma(Real, Real);
Real resta(Real, Real);
Real multiplicacion(Real, Real);
Real divicion(Real, Real);
};
#endif
|
#include <iostream>
#include <stdlib.h>
using std::cout;
using std::endl;
struct node {
int val;
struct node* next;
};
int main() {
node* head = NULL;
node* second = NULL;
node* third = NULL;
head = (node *)malloc(sizeof(node)); // allocate 3 nodes in the heap
second = (node *)malloc(sizeof(node));
third = (node *)malloc(sizeof(node));
head->val = 1; // setup first node
head->next = second;// note: pointer assignment rule
second->val = 2; // setup second node
second->next = third;
third->val = 3; // setup third link
third->next = NULL;
cout << "Linked List: [" << head->val << ", " << second->val << ", " << third->val << "]" << endl;
node* cur = head;
cout << "Linked List= ";
while(cur != NULL) {
cout << cur->val << " ";
cur= cur->next;
}
cout << endl;
return 0;
}
|
#ifndef APPLICATION_CHATOBSERVERCMD_H
#define APPLICATION_CHATOBSERVERCMD_H
#include "BaseCmd.h"
#include "Commands/CmdCreator/Commands.h"
#include "ChatObjects/ChatUpdates.h"
#include "ChatObjects/MessageStatus.h"
#include "ChatObjects/ChatAction.h"
// Command for chat observe
class ChatObserverCmd : public BaseCmd {
public:
~ChatObserverCmd() override = default;
ChatObserverCmd(int numRequest, const std::optional<std::string>& error,
const std::string& body);
// Execute command
void execute(std::shared_ptr<CallbacksHolder> holder) override;
};
#endif //APPLICATION_CHATOBSERVERCMD_H
|
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <clocale>
using namespace std;
//Тема: Шаблоны функций Задание.Реализуйте шаблонные функции для поиска максимума,
// минимума, сортировки массива(любым алгоритмом сортировки), двоичного поиска в
// массиве, замены элемента массива на переданное значение.
//
// шаблон функции printArray
template <typename MyType>
void printArray(const MyType * array, int count)
{
for (int ix = 0; ix < count; ix++)
cout << array[ix] << " ";
cout << endl;
}
// шаблон функции maxArray
template<typename min>
void maxArray(const min *array, int count)
{
min max=array[0];
for (int i = 0; i < count; i++)
{
if (max < array[i])
{
max = array[i];
}
}
cout << max << endl;
}
// шаблон функции maxArray
template <typename sort>
void SortArray(sort *array, int count)
{
sort temp;
for (int i = 0;i < count;i++)
{
for (int j = count - 1;j > i;j--)
{
if (array[j] < array[j - 1])
{
temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
}
template <typename poisk>
void PoslArray(poisk *array, int count)
{
poisk temp;
cin >> temp;
for (int i = 0; i <count; i++)
{
if (array[i] == temp)
cout << "Индекс Элемента= " << i + 1 << endl;
else
cout << "Элемент не найден" << endl;
}
}
int main()
{
setlocale(LC_ALL, "RUSSIAN");
// размеры массивов
const int iSize = 10,
dSize = 7,
fSize = 10,
cSize = 5;
// массивы разных типов данных
int iArray[iSize] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
double dArray[dSize] = { 1.2345, 2.234, 3.57, 4.67876, 5.346, 6.1545, 7.7682 };
float fArray[fSize] = { 1.34, 2.37, 3.23, 4.8, 5.879, 6.345, 73.434, 8.82, 9.33, 10.4 };
char cArray[cSize] = { "MARS" };
cout << "\t\tPattern of function of an output of an array on the screen\n\n";
// вызов локальной версии функции printArray для типа int через шаблон
cout << "\n Array type int:\n"; printArray(iArray, iSize);
// вызов локальной версии функции printArray для типа double через шаблон
cout << "\n Array type double:\n"; printArray(dArray, dSize);
// вызов локальной версии функции printArray для типа float через шаблон
cout << "\n Array type float:\n"; printArray(fArray, fSize);
// вызов локальной версии функции printArray для типа char через шаблон
cout << "\n Array type char:\n"; printArray(cArray, cSize);
cout << "-----------------------------" << endl;
cout << "Для функции maxArray" << endl;
cout << "\n Array type int:\n"; maxArray(iArray, iSize);
cout << "\n Array type double:\n"; maxArray(dArray, dSize);
cout << "\n Array type float:\n"; maxArray(fArray, fSize);
cout << "\n Array type char:\n";maxArray(cArray, cSize);
cout << "-----------------------------" << endl;
cout << "Для функции sortArray" << endl;
cout << "\n Array type int:\n"; SortArray(iArray, iSize);printArray(iArray, iSize);
cout << "\n Array type double:\n"; SortArray(dArray, dSize);printArray(dArray, dSize);
cout << "\n Array type float:\n"; SortArray(fArray, fSize);printArray(fArray, fSize);
cout << "\n Array type char:\n";SortArray(cArray, cSize);printArray(cArray, cSize);
cout << "-----------------------------" << endl;
cout << "Для функции sortArray" << endl;
cout << "\n Array type int:\n"; PoslArray(iArray, iSize);printArray(iArray, iSize);
cout << "\n Array type double:\n"; PoslArray(dArray, dSize);printArray(dArray, dSize);
cout << "\n Array type float:\n"; PoslArray(fArray, fSize);printArray(fArray, fSize);
cout << "\n Array type char:\n";PoslArray(cArray, cSize);printArray(cArray, cSize);
return 0;
}
|
#include "bricks/core/time.h"
#include "bricks/core/timespan.h"
#if BRICKS_ENV_MINGW
#include <pthread.h>
#undef GetCurrentTime
#endif
#include <time.h>
#include <sys/time.h>
#include <string.h>
#define BRICKS_TIME_CONVERT_NANOSECONDS 1000000000
#define BRICKS_TIME_CONVERT_MICROSECONDS_NANOSECONDS 1000
namespace Bricks {
Time::Time(const struct timespec& spec) :
seconds(spec.tv_sec), nanoseconds(spec.tv_nsec)
{
}
Time::Time(const struct timeval& val) :
seconds(val.tv_sec), nanoseconds((long)val.tv_usec * BRICKS_TIME_CONVERT_MICROSECONDS_NANOSECONDS)
{
}
Time Time::GetCurrentTime()
{
#ifdef CLOCK_REALTIME
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
return Time(spec);
#else
struct timeval val;
gettimeofday(&val, NULL);
return Time(val);
#endif
}
void Time::Normalize()
{
long secs = nanoseconds / BRICKS_TIME_CONVERT_NANOSECONDS;
if (secs) {
seconds += secs;
nanoseconds %= BRICKS_TIME_CONVERT_NANOSECONDS;
}
}
struct timespec Time::GetTimespec() const
{
struct timespec spec;
memset(&spec, 0, sizeof(spec));
spec.tv_sec = seconds;
spec.tv_nsec = nanoseconds;
return spec;
}
struct timeval Time::GetTimeval() const
{
struct timeval val;
memset(&val, 0, sizeof(val));
val.tv_sec = seconds;
val.tv_usec = nanoseconds / BRICKS_TIME_CONVERT_MICROSECONDS_NANOSECONDS;
return val;
}
Time Time::operator +(const Timespan& span) const
{
return Time(*this) += span;
}
Time Time::operator -(const Timespan& span) const
{
return Time(*this) -= span;
}
Time& Time::operator +=(const Timespan& span)
{
int secs = span.AsSeconds();
seconds += secs;
nanoseconds += Timespan::ConvertToNanoseconds(span.GetTicks() - Timespan::ConvertSeconds(secs));
Normalize();
return *this;
}
Time& Time::operator -=(const Timespan& span)
{
int secs = span.AsSeconds();
seconds -= secs;
nanoseconds -= Timespan::ConvertToNanoseconds(span.GetTicks() - Timespan::ConvertSeconds(secs));
Normalize();
return *this;
}
Timespan Time::operator -(const Time& time) const
{
return Timespan(Timespan::ConvertSeconds(seconds - time.seconds) + Timespan::ConvertNanoseconds(nanoseconds - time.nanoseconds));
}
}
|
#include"Hash.h"
|
// Copyright (c) 2013 Nick Porcino, All rights reserved.
// License is MIT: http://opensource.org/licenses/MIT
#include "VarObjArray.h"
#include "LandruVM/Fiber.h"
#include "LandruVM/VarObjStackUtil.h"
namespace Landru {
LANDRU_DECL_FN(VarObjArray, create)
{
std::shared_ptr<VarObjArray> voa = p->stack->top<VarObjArray>();
p->stack->pop();
}
LANDRU_DECL_FN(VarObjArray, pushBack)
{
VarObjArray* o = (VarObjArray*) p->vo.get();
std::shared_ptr<VarObjArray> voa = p->stack->top<VarObjArray>();
p->stack->pop();
o->push_back(voa->get(-1).lock());
}
LANDRU_DECL_TABLE_BEGIN(VarObjArray)
LANDRU_DECL_ENTRY(VarObjArray, create)
LANDRU_DECL_ENTRY(VarObjArray, pushBack)
LANDRU_DECL_TABLE_END(VarObjArray)
} // Landru
|
/**
* author: rasel kibria
* created: 10.07.2020
**/
#include<bits/stdc++.h>
using namespace std;
int main()
{
int driver, i, j;
cin>>driver;
string name;
double result, d;
double score[7];
for(i=0; i<driver; i++)
{
cin>>name>>d;
for(j=0; j<7; j++)
{
cin>>score[j];
}
sort(score, score+7);
// after sorting max will be at index 0 and min will be at index 6
result = (score[1]+score[2]+score[3]+score[4]+score[5])*d;
cout<<name<<" "<<fixed<<setprecision(2)<<result<<"\n";
}
return 0;
}
|
#include "Includes.h"
#include <iostream>
#include <algorithm>
#include <fstream>
#include <sstream>
using namespace std;
void uva10252Main() {
string s;
stringstream ss(s);
while(getline(cin, s) && s!="*") {
string str;
bool isT = true;
ss>>str;
char c = (char)tolower(str[0]);
while(ss>>str) {
if(tolower(str[0]) != c)
isT = false;
}
cout << (isT ? "Y" : "N") << endl;
}
/*string a, b, x;
ofstream of(R"(C:\Users\Asicoder\CLionProjects\untitled\output.txt)");
getline(cin, x);
while(getline(cin, a)) {
getline(cin, b);
cout<<"["<<a<<"]"<<endl;
cout<<"["<<b<<"]"<<endl;
int aw[256] = {};
int bw[256] = {};
string result;
for(int i = 0; i < a.length(); ++i) {
aw[(int)a[i]]++;
}
for(int i = 0; i < b.length(); ++i) {
bw[(int)b[i]]++;
}
for(int i = 0; i < 256; ++i) {
if(aw[i] != 0 && bw[i] != 0) {
for(int j = 0; j < min(aw[i], bw[i]); ++j)
result.push_back((char)i);
}
}
of<<result<<endl;
}*/
}
|
//这次相比原来改进了一下思路,采用了类似广度优先搜索的方法,但还是和原来一样的分数,60 下面的好多超时
//然后想办法加速,看到一个别人的代码,学习了他的邻接表,把那些quicksort,binary_search去了
//然后就70分了 下面超时少了 变成了错误
//暂时先到这里 有空再来
#include<iostream>
#include<cstdio>
using namespace std;
class QUEUE{
public:
QUEUE(int length);//构造函数
int current_size;//队列总元素个数
bool enqueue(int value);//入队
int dequeue();//出队
private:
int max_size;//队列最大长队
int head;//队头下标
int tail;//队尾下标
int * array;//储存元素的数组
};
QUEUE::QUEUE(int length){
current_size = 0;
max_size = length;
head = 0;
tail = 0;
array = new int[length+10];
}
bool QUEUE::enqueue(int value){
if(current_size <= max_size){//此处应为<=而不是<
array[head] = value;
if((max_size -1) == head){
head = 0;
}else{
++head;
}
++current_size;
return true;
}
return false;
}
int QUEUE::dequeue(){
if(current_size > 0){
int temp = array[tail];
if((max_size -1) == tail){
tail = 0;
}else{
++tail;
}
--current_size;
return temp;
}
}
//看了人家的代码,感觉写个邻接表能提速很多,那就写个吧
//Adjacency_list
class Node{
public:
Node();
Node* succ;
int city_name;
};
Node::Node(){
succ = NULL;
city_name = 0;
}
Node* array = new Node[3000010];//改了这里60变为70(2)
int array_index = 0;
class City{
public:
City();
int number;
Node* the_head;
Node* current;
void insertbehind(int value);
};
City::City(){
number = 0;
the_head = &(array[array_index]);
++array_index;
current = the_head;
}
void City::insertbehind(int value){
Node *temp = &(array[array_index]);
++array_index;
temp->city_name = value;
current->succ = temp;
current = temp;
}
int main(){
//输入
int n,m;
fscanf(stdin,"%d %d",&n,&m);
City* city = new City[2000010];//改了这里60变为70(1)
int *find_origin=new int[2000010];
for(int i = 0; i < 2000010; ++i){
find_origin[i] = 0;
}
for (int i = 0; i < m; ++i){
int x, y;
fscanf(stdin, "%d %d", &x, &y);
find_origin[y]=y;//
city[x].insertbehind(y);
}
//找出所有没有被指向的点,也就是可以作为起点的点(这是直接复制过来的,略作修改,就是不放入那个origin数组里面了,直接入队)
QUEUE queue(2000010);
for(int i=1 ;i<=n;++i){
if(i!=find_origin[i]){
queue.enqueue(i);
}
}
//开始拓扑排序,也类似于广度优先搜索
int count = 0;
while(queue.current_size > 0){
++count;
for(int i = 0, j = queue.current_size; i < j; ++i){
int from = queue.dequeue();
Node* a = city[from].the_head;
for(; a->succ != NULL;){//
a = a->succ;
queue.enqueue(a->city_name);
}
}
}
fprintf(stdout,"%d", count);
return 0;
}
|
// $Id$
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
// Contribution from Roger Sayle
#include <vector>
#include <DataStructs/ExplicitBitVect.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/MolOps.h>
#include <boost/flyweight.hpp>
#include <boost/flyweight/no_tracking.hpp>
namespace {
struct Patterns {
RDKit::ROMol *bit_8;
RDKit::ROMol *bit_11;
RDKit::ROMol *bit_13;
RDKit::ROMol *bit_14;
RDKit::ROMol *bit_15;
RDKit::ROMol *bit_16;
RDKit::ROMol *bit_17;
RDKit::ROMol *bit_19;
RDKit::ROMol *bit_20;
RDKit::ROMol *bit_21;
RDKit::ROMol *bit_22;
RDKit::ROMol *bit_23;
RDKit::ROMol *bit_24;
RDKit::ROMol *bit_25;
RDKit::ROMol *bit_26;
RDKit::ROMol *bit_28;
RDKit::ROMol *bit_30;
RDKit::ROMol *bit_31;
RDKit::ROMol *bit_32;
RDKit::ROMol *bit_33;
RDKit::ROMol *bit_34;
RDKit::ROMol *bit_36;
RDKit::ROMol *bit_37;
RDKit::ROMol *bit_38;
RDKit::ROMol *bit_39;
RDKit::ROMol *bit_40;
RDKit::ROMol *bit_41;
RDKit::ROMol *bit_43;
RDKit::ROMol *bit_44;
RDKit::ROMol *bit_45;
RDKit::ROMol *bit_47;
RDKit::ROMol *bit_48;
RDKit::ROMol *bit_49;
RDKit::ROMol *bit_50;
RDKit::ROMol *bit_51;
RDKit::ROMol *bit_52;
RDKit::ROMol *bit_53;
RDKit::ROMol *bit_54;
RDKit::ROMol *bit_55;
RDKit::ROMol *bit_56;
RDKit::ROMol *bit_57;
RDKit::ROMol *bit_58;
RDKit::ROMol *bit_59;
RDKit::ROMol *bit_60;
RDKit::ROMol *bit_61;
RDKit::ROMol *bit_62;
RDKit::ROMol *bit_63;
RDKit::ROMol *bit_64;
RDKit::ROMol *bit_65;
RDKit::ROMol *bit_66;
RDKit::ROMol *bit_67;
RDKit::ROMol *bit_68;
RDKit::ROMol *bit_69;
RDKit::ROMol *bit_70;
RDKit::ROMol *bit_71;
RDKit::ROMol *bit_72;
RDKit::ROMol *bit_73;
RDKit::ROMol *bit_74;
RDKit::ROMol *bit_75;
RDKit::ROMol *bit_76;
RDKit::ROMol *bit_77;
RDKit::ROMol *bit_78;
RDKit::ROMol *bit_79;
RDKit::ROMol *bit_80;
RDKit::ROMol *bit_81;
RDKit::ROMol *bit_82;
RDKit::ROMol *bit_83;
RDKit::ROMol *bit_84;
RDKit::ROMol *bit_85;
RDKit::ROMol *bit_86;
RDKit::ROMol *bit_87;
RDKit::ROMol *bit_89;
RDKit::ROMol *bit_90;
RDKit::ROMol *bit_91;
RDKit::ROMol *bit_92;
RDKit::ROMol *bit_93;
RDKit::ROMol *bit_94;
RDKit::ROMol *bit_95;
RDKit::ROMol *bit_96;
RDKit::ROMol *bit_97;
RDKit::ROMol *bit_98;
RDKit::ROMol *bit_99;
RDKit::ROMol *bit_100;
RDKit::ROMol *bit_101;
RDKit::ROMol *bit_102;
RDKit::ROMol *bit_104;
RDKit::ROMol *bit_105;
RDKit::ROMol *bit_106;
RDKit::ROMol *bit_107;
RDKit::ROMol *bit_108;
RDKit::ROMol *bit_109;
RDKit::ROMol *bit_110;
RDKit::ROMol *bit_111;
RDKit::ROMol *bit_112;
RDKit::ROMol *bit_113;
RDKit::ROMol *bit_114;
RDKit::ROMol *bit_115;
RDKit::ROMol *bit_116;
RDKit::ROMol *bit_117;
RDKit::ROMol *bit_118;
RDKit::ROMol *bit_119;
RDKit::ROMol *bit_120;
RDKit::ROMol *bit_121;
RDKit::ROMol *bit_122;
RDKit::ROMol *bit_123;
RDKit::ROMol *bit_124;
RDKit::ROMol *bit_126;
RDKit::ROMol *bit_127;
RDKit::ROMol *bit_128;
RDKit::ROMol *bit_129;
RDKit::ROMol *bit_131;
RDKit::ROMol *bit_132;
RDKit::ROMol *bit_133;
RDKit::ROMol *bit_135;
RDKit::ROMol *bit_136;
RDKit::ROMol *bit_137;
RDKit::ROMol *bit_138;
RDKit::ROMol *bit_139;
RDKit::ROMol *bit_140;
RDKit::ROMol *bit_141;
RDKit::ROMol *bit_142;
RDKit::ROMol *bit_144;
RDKit::ROMol *bit_145;
RDKit::ROMol *bit_147;
RDKit::ROMol *bit_148;
RDKit::ROMol *bit_149;
RDKit::ROMol *bit_150;
RDKit::ROMol *bit_151;
RDKit::ROMol *bit_152;
RDKit::ROMol *bit_154;
RDKit::ROMol *bit_155;
RDKit::ROMol *bit_156;
RDKit::ROMol *bit_157;
RDKit::ROMol *bit_158;
RDKit::ROMol *bit_162;
RDKit::ROMol *bit_165;
Patterns() :
bit_8(RDKit::SmartsToMol("[!#6!#1]1~*~*~*~1")),
bit_11(RDKit::SmartsToMol("*1~*~*~*~1")),
bit_13(RDKit::SmartsToMol("[#8]~[#7](~[#6])~[#6]")),
bit_14(RDKit::SmartsToMol("[#16]-[#16]")),
bit_15(RDKit::SmartsToMol("[#8]~[#6](~[#8])~[#8]")),
bit_16(RDKit::SmartsToMol("[!#6!#1]1~*~*~1")),
bit_17(RDKit::SmartsToMol("[#6]#[#6]")),
bit_19(RDKit::SmartsToMol("*1~*~*~*~*~*~*~1")),
bit_20(RDKit::SmartsToMol("[#14]")),
bit_21(RDKit::SmartsToMol("[#6]=[#6](~[!#6!#1])~[!#6!#1]")),
bit_22(RDKit::SmartsToMol("*1~*~*~1")),
bit_23(RDKit::SmartsToMol("[#7]~[#6](~[#8])~[#8]")),
bit_24(RDKit::SmartsToMol("[#7]-[#8]")),
bit_25(RDKit::SmartsToMol("[#7]~[#6](~[#7])~[#7]")),
bit_26(RDKit::SmartsToMol("[#6]=@[#6](@*)@*")),
bit_28(RDKit::SmartsToMol("[!#6!#1]~[CH2]~[!#6!#1]")),
bit_30(RDKit::SmartsToMol("[#6]~[!#6!#1](~[#6])(~[#6])~*")),
bit_31(RDKit::SmartsToMol("[!#6!#1]~[F,Cl,Br,I]")),
bit_32(RDKit::SmartsToMol("[#6]~[#16]~[#7]")),
bit_33(RDKit::SmartsToMol("[#7]~[#16]")),
bit_34(RDKit::SmartsToMol("[CH2]=*")),
bit_36(RDKit::SmartsToMol("[#16R]")),
bit_37(RDKit::SmartsToMol("[#7]~[#6](~[#8])~[#7]")),
bit_38(RDKit::SmartsToMol("[#7]~[#6](~[#6])~[#7]")),
bit_39(RDKit::SmartsToMol("[#8]~[#16](~[#8])~[#8]")),
bit_40(RDKit::SmartsToMol("[#16]-[#8]")),
bit_41(RDKit::SmartsToMol("[#6]#[#7]")),
bit_43(RDKit::SmartsToMol("[!#6!#1!H0]~*~[!#6!#1!H0]")),
bit_44(RDKit::SmartsToMol("[!#1;!#6;!#7;!#8;!#9;!#14;!#15;!#16;!#17;!#35;!#53]")),
bit_45(RDKit::SmartsToMol("[#6]=[#6]~[#7]")),
bit_47(RDKit::SmartsToMol("[#16]~*~[#7]")),
bit_48(RDKit::SmartsToMol("[#8]~[!#6!#1](~[#8])~[#8]")),
bit_49(RDKit::SmartsToMol("[!+0]")),
bit_50(RDKit::SmartsToMol("[#6]=[#6](~[#6])~[#6]")),
bit_51(RDKit::SmartsToMol("[#6]~[#16]~[#8]")),
bit_52(RDKit::SmartsToMol("[#7]~[#7]")),
bit_53(RDKit::SmartsToMol("[!#6!#1!H0]~*~*~*~[!#6!#1!H0]")),
bit_54(RDKit::SmartsToMol("[!#6!#1!H0]~*~*~[!#6!#1!H0]")),
bit_55(RDKit::SmartsToMol("[#8]~[#16]~[#8]")),
bit_56(RDKit::SmartsToMol("[#8]~[#7](~[#8])~[#6]")),
bit_57(RDKit::SmartsToMol("[#8R]")),
bit_58(RDKit::SmartsToMol("[!#6!#1]~[#16]~[!#6!#1]")),
bit_59(RDKit::SmartsToMol("[#16]!:*:*")),
bit_60(RDKit::SmartsToMol("[#16]=[#8]")),
bit_61(RDKit::SmartsToMol("*~[#16](~*)~*")),
bit_62(RDKit::SmartsToMol("*@*!@*@*")),
bit_63(RDKit::SmartsToMol("[#7]=[#8]")),
bit_64(RDKit::SmartsToMol("*@*!@[#16]")),
bit_65(RDKit::SmartsToMol("c:n")),
bit_66(RDKit::SmartsToMol("[#6]~[#6](~[#6])(~[#6])~*")),
bit_67(RDKit::SmartsToMol("[!#6!#1]~[#16]")),
bit_68(RDKit::SmartsToMol("[!#6!#1!H0]~[!#6!#1!H0]")),
bit_69(RDKit::SmartsToMol("[!#6!#1]~[!#6!#1!H0]")),
bit_70(RDKit::SmartsToMol("[!#6!#1]~[#7]~[!#6!#1]")),
bit_71(RDKit::SmartsToMol("[#7]~[#8]")),
bit_72(RDKit::SmartsToMol("[#8]~*~*~[#8]")),
bit_73(RDKit::SmartsToMol("[#16]=*")),
bit_74(RDKit::SmartsToMol("[CH3]~*~[CH3]")),
bit_75(RDKit::SmartsToMol("*!@[#7]@*")),
bit_76(RDKit::SmartsToMol("[#6]=[#6](~*)~*")),
bit_77(RDKit::SmartsToMol("[#7]~*~[#7]")),
bit_78(RDKit::SmartsToMol("[#6]=[#7]")),
bit_79(RDKit::SmartsToMol("[#7]~*~*~[#7]")),
bit_80(RDKit::SmartsToMol("[#7]~*~*~*~[#7]")),
bit_81(RDKit::SmartsToMol("[#16]~*(~*)~*")),
bit_82(RDKit::SmartsToMol("*~[CH2]~[!#6!#1!H0]")),
bit_83(RDKit::SmartsToMol("[!#6!#1]1~*~*~*~*~1")),
bit_84(RDKit::SmartsToMol("[NH2]")),
bit_85(RDKit::SmartsToMol("[#6]~[#7](~[#6])~[#6]")),
bit_86(RDKit::SmartsToMol("[C;H2,H3][!#6!#1][C;H2,H3]")),
bit_87(RDKit::SmartsToMol("[F,Cl,Br,I]!@*@*")),
bit_89(RDKit::SmartsToMol("[#8]~*~*~*~[#8]")),
bit_90(RDKit::SmartsToMol("[$([!#6!#1!H0]~*~*~[CH2]~*),$([!#6!#1!H0R]1@[R]@[R]@[CH2R]1),$([!#6!#1!H0]~[R]1@[R]@[CH2R]1)]")),
bit_91(RDKit::SmartsToMol("[$([!#6!#1!H0]~*~*~*~[CH2]~*),$([!#6!#1!H0R]1@[R]@[R]@[R]@[CH2R]1),$([!#6!#1!H0]~[R]1@[R]@[R]@[CH2R]1),$([!#6!#1!H0]~*~[R]1@[R]@[CH2R]1)]")),
bit_92(RDKit::SmartsToMol("[#8]~[#6](~[#7])~[#6]")),
bit_93(RDKit::SmartsToMol("[!#6!#1]~[CH3]")),
bit_94(RDKit::SmartsToMol("[!#6!#1]~[#7]")),
bit_95(RDKit::SmartsToMol("[#7]~*~*~[#8]")),
bit_96(RDKit::SmartsToMol("*1~*~*~*~*~1")),
bit_97(RDKit::SmartsToMol("[#7]~*~*~*~[#8]")),
bit_98(RDKit::SmartsToMol("[!#6!#1]1~*~*~*~*~*~1")),
bit_99(RDKit::SmartsToMol("[#6]=[#6]")),
bit_100(RDKit::SmartsToMol("*~[CH2]~[#7]")),
bit_101(RDKit::SmartsToMol("[$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1)]")),
bit_102(RDKit::SmartsToMol("[!#6!#1]~[#8]")),
bit_104(RDKit::SmartsToMol("[!#6!#1!H0]~*~[CH2]~*")),
bit_105(RDKit::SmartsToMol("*@*(@*)@*")),
bit_106(RDKit::SmartsToMol("[!#6!#1]~*(~[!#6!#1])~[!#6!#1]")),
bit_107(RDKit::SmartsToMol("[F,Cl,Br,I]~*(~*)~*")),
bit_108(RDKit::SmartsToMol("[CH3]~*~*~*~[CH2]~*")),
bit_109(RDKit::SmartsToMol("*~[CH2]~[#8]")),
bit_110(RDKit::SmartsToMol("[#7]~[#6]~[#8]")),
bit_111(RDKit::SmartsToMol("[#7]~*~[CH2]~*")),
bit_112(RDKit::SmartsToMol("*~*(~*)(~*)~*")),
bit_113(RDKit::SmartsToMol("[#8]!:*:*")),
bit_114(RDKit::SmartsToMol("[CH3]~[CH2]~*")),
bit_115(RDKit::SmartsToMol("[CH3]~*~[CH2]~*")),
bit_116(RDKit::SmartsToMol("[$([CH3]~*~*~[CH2]~*),$([CH3]~*1~*~[CH2]1)]")),
bit_117(RDKit::SmartsToMol("[#7]~*~[#8]")),
bit_118(RDKit::SmartsToMol("[$(*~[CH2]~[CH2]~*),$(*1~[CH2]~[CH2]1)]")),
bit_119(RDKit::SmartsToMol("[#7]=*")),
bit_120(RDKit::SmartsToMol("[!#6R]")),
bit_121(RDKit::SmartsToMol("[#7R]")),
bit_122(RDKit::SmartsToMol("*~[#7](~*)~*")),
bit_123(RDKit::SmartsToMol("[#8]~[#6]~[#8]")),
bit_124(RDKit::SmartsToMol("[!#6!#1]~[!#6!#1]")),
bit_126(RDKit::SmartsToMol("*!@[#8]!@*")),
bit_127(RDKit::SmartsToMol("*@*!@[#8]")),
bit_128(RDKit::SmartsToMol("[$(*~[CH2]~*~*~*~[CH2]~*),$([R]1@[CH2R]@[R]@[R]@[R]@[CH2R]1),$(*~[CH2]~[R]1@[R]@[R]@[CH2R]1),$(*~[CH2]~*~[R]1@[R]@[CH2R]1)]")),
bit_129(RDKit::SmartsToMol("[$(*~[CH2]~*~*~[CH2]~*),$([R]1@[CH2]@[R]@[R]@[CH2R]1),$(*~[CH2]~[R]1@[R]@[CH2R]1)]")),
bit_131(RDKit::SmartsToMol("[!#6!#1!H0]")),
bit_132(RDKit::SmartsToMol("[#8]~*~[CH2]~*")),
bit_133(RDKit::SmartsToMol("*@*!@[#7]")),
bit_135(RDKit::SmartsToMol("[#7]!:*:*")),
bit_136(RDKit::SmartsToMol("[#8]=*")),
bit_137(RDKit::SmartsToMol("[!C!cR]")),
bit_138(RDKit::SmartsToMol("[!#6!#1]~[CH2]~*")),
bit_139(RDKit::SmartsToMol("[O!H0]")),
bit_140(RDKit::SmartsToMol("[#8]")),
bit_141(RDKit::SmartsToMol("[CH3]")),
bit_142(RDKit::SmartsToMol("[#7]")),
bit_144(RDKit::SmartsToMol("*!:*:*!:*")),
bit_145(RDKit::SmartsToMol("*1~*~*~*~*~*~1")),
bit_147(RDKit::SmartsToMol("[$(*~[CH2]~[CH2]~*),$([R]1@[CH2R]@[CH2R]1)]")),
bit_148(RDKit::SmartsToMol("*~[!#6!#1](~*)~*")),
bit_149(RDKit::SmartsToMol("[C;H3,H4]")),
bit_150(RDKit::SmartsToMol("*!@*@*!@*")),
bit_151(RDKit::SmartsToMol("[#7!H0]")),
bit_152(RDKit::SmartsToMol("[#8]~[#6](~[#6])~[#6]")),
bit_154(RDKit::SmartsToMol("[#6]=[#8]")),
bit_155(RDKit::SmartsToMol("*!@[CH2]!@*")),
bit_156(RDKit::SmartsToMol("[#7]~*(~*)~*")),
bit_157(RDKit::SmartsToMol("[#6]-[#8]")),
bit_158(RDKit::SmartsToMol("[#6]-[#7]")),
bit_162(RDKit::SmartsToMol("a")),
bit_165(RDKit::SmartsToMol("[R]")) {}
};
boost::flyweight<std::vector<Patterns *>,boost::flyweights::no_tracking> gpats;
void GenerateFP(const RDKit::ROMol &mol,ExplicitBitVect &fp)
{
if(gpats.get().size()==0){
std::vector<Patterns *> ps;
ps.push_back(new Patterns());
gpats = ps;
}
const Patterns &pats=*(gpats.get().front());
PRECONDITION(fp.size()==167,"bad fingerprint");
fp.clearBits();
if(!mol.getNumAtoms()) return;
std::vector<RDKit::MatchVectType> matches;
RDKit::RWMol::ConstAtomIterator atom;
RDKit::MatchVectType match;
unsigned int count;
for (atom=mol.beginAtoms();atom!=mol.endAtoms();++atom)
switch ((*atom)->getAtomicNum()) {
case 3:
case 11:
case 19:
case 37:
case 55:
case 87:
fp.setBit(35);
break;
case 4:
case 12:
case 20:
case 38:
case 56:
case 88:
fp.setBit(10);
break;
case 5:
case 13:
case 31:
case 49:
case 81:
fp.setBit(18);
break;
case 9:
fp.setBit(42);
fp.setBit(134);
break;
case 15:
fp.setBit(29);
break;
case 16:
fp.setBit(88);
break;
case 17:
fp.setBit(103);
fp.setBit(134);
break;
case 21:
case 22:
case 39:
case 40:
case 72:
fp.setBit(5);
break;
case 23:
case 24:
case 25:
case 41:
case 42:
case 43:
case 73:
case 74:
case 75:
fp.setBit(7);
break;
case 26:
case 27:
case 28:
case 44:
case 45:
case 46:
case 76:
case 77:
case 78:
fp.setBit(9);
break;
case 29:
case 30:
case 47:
case 48:
case 79:
case 80:
fp.setBit(12);
break;
case 32:
case 33:
case 34:
case 50:
case 51:
case 52:
case 82:
case 83:
case 84:
fp.setBit(3);
break;
case 35:
fp.setBit(46);
fp.setBit(134);
break;
case 53:
fp.setBit(27);
fp.setBit(134);
break;
case 57:
case 58:
case 59:
case 60:
case 61:
case 62:
case 63:
case 64:
case 65:
case 66:
case 67:
case 68:
case 69:
case 70:
case 71:
fp.setBit(6);
break;
case 89:
case 90:
case 91:
case 92:
case 93:
case 94:
case 95:
case 96:
case 97:
case 98:
case 99:
case 100:
case 101:
case 102:
case 103:
fp.setBit(4);
break;
case 104:
fp.setBit(2);
break;
}
if (RDKit::SubstructMatch(mol,*pats.bit_8,match,true))
fp.setBit(8);
if (RDKit::SubstructMatch(mol,*pats.bit_11,match,true))
fp.setBit(11);
if (RDKit::SubstructMatch(mol,*pats.bit_13,match,true))
fp.setBit(13);
if (RDKit::SubstructMatch(mol,*pats.bit_14,match,true))
fp.setBit(14);
if (RDKit::SubstructMatch(mol,*pats.bit_15,match,true))
fp.setBit(15);
if (RDKit::SubstructMatch(mol,*pats.bit_16,match,true))
fp.setBit(16);
if (RDKit::SubstructMatch(mol,*pats.bit_17,match,true))
fp.setBit(17);
if (RDKit::SubstructMatch(mol,*pats.bit_19,match,true))
fp.setBit(19);
if (RDKit::SubstructMatch(mol,*pats.bit_20,match,true))
fp.setBit(20);
if (RDKit::SubstructMatch(mol,*pats.bit_21,match,true))
fp.setBit(21);
if (RDKit::SubstructMatch(mol,*pats.bit_22,match,true))
fp.setBit(22);
if (RDKit::SubstructMatch(mol,*pats.bit_23,match,true))
fp.setBit(23);
if (RDKit::SubstructMatch(mol,*pats.bit_24,match,true))
fp.setBit(24);
if (RDKit::SubstructMatch(mol,*pats.bit_25,match,true))
fp.setBit(25);
if (RDKit::SubstructMatch(mol,*pats.bit_26,match,true))
fp.setBit(26);
if (RDKit::SubstructMatch(mol,*pats.bit_28,match,true))
fp.setBit(28);
if (RDKit::SubstructMatch(mol,*pats.bit_30,match,true))
fp.setBit(30);
if (RDKit::SubstructMatch(mol,*pats.bit_31,match,true))
fp.setBit(31);
if (RDKit::SubstructMatch(mol,*pats.bit_32,match,true))
fp.setBit(32);
if (RDKit::SubstructMatch(mol,*pats.bit_33,match,true))
fp.setBit(33);
if (RDKit::SubstructMatch(mol,*pats.bit_34,match,true))
fp.setBit(34);
if (RDKit::SubstructMatch(mol,*pats.bit_36,match,true))
fp.setBit(36);
if (RDKit::SubstructMatch(mol,*pats.bit_37,match,true))
fp.setBit(37);
if (RDKit::SubstructMatch(mol,*pats.bit_38,match,true))
fp.setBit(38);
if (RDKit::SubstructMatch(mol,*pats.bit_39,match,true))
fp.setBit(39);
if (RDKit::SubstructMatch(mol,*pats.bit_40,match,true))
fp.setBit(40);
if (RDKit::SubstructMatch(mol,*pats.bit_41,match,true))
fp.setBit(41);
if (RDKit::SubstructMatch(mol,*pats.bit_43,match,true))
fp.setBit(43);
if (RDKit::SubstructMatch(mol,*pats.bit_44,match,true))
fp.setBit(44);
if (RDKit::SubstructMatch(mol,*pats.bit_45,match,true))
fp.setBit(45);
if (RDKit::SubstructMatch(mol,*pats.bit_47,match,true))
fp.setBit(47);
if (RDKit::SubstructMatch(mol,*pats.bit_48,match,true))
fp.setBit(48);
if (RDKit::SubstructMatch(mol,*pats.bit_49,match,true))
fp.setBit(49);
if (RDKit::SubstructMatch(mol,*pats.bit_50,match,true))
fp.setBit(50);
if (RDKit::SubstructMatch(mol,*pats.bit_51,match,true))
fp.setBit(51);
if (RDKit::SubstructMatch(mol,*pats.bit_52,match,true))
fp.setBit(52);
if (RDKit::SubstructMatch(mol,*pats.bit_53,match,true))
fp.setBit(53);
if (RDKit::SubstructMatch(mol,*pats.bit_54,match,true))
fp.setBit(54);
if (RDKit::SubstructMatch(mol,*pats.bit_55,match,true))
fp.setBit(55);
if (RDKit::SubstructMatch(mol,*pats.bit_56,match,true))
fp.setBit(56);
if (RDKit::SubstructMatch(mol,*pats.bit_57,match,true))
fp.setBit(57);
if (RDKit::SubstructMatch(mol,*pats.bit_58,match,true))
fp.setBit(58);
if (RDKit::SubstructMatch(mol,*pats.bit_59,match,true))
fp.setBit(59);
if (RDKit::SubstructMatch(mol,*pats.bit_60,match,true))
fp.setBit(60);
if (RDKit::SubstructMatch(mol,*pats.bit_61,match,true))
fp.setBit(61);
if (RDKit::SubstructMatch(mol,*pats.bit_62,match,true))
fp.setBit(62);
if (RDKit::SubstructMatch(mol,*pats.bit_63,match,true))
fp.setBit(63);
if (RDKit::SubstructMatch(mol,*pats.bit_64,match,true))
fp.setBit(64);
if (RDKit::SubstructMatch(mol,*pats.bit_65,match,true))
fp.setBit(65);
if (RDKit::SubstructMatch(mol,*pats.bit_66,match,true))
fp.setBit(66);
if (RDKit::SubstructMatch(mol,*pats.bit_67,match,true))
fp.setBit(67);
if (RDKit::SubstructMatch(mol,*pats.bit_68,match,true))
fp.setBit(68);
if (RDKit::SubstructMatch(mol,*pats.bit_69,match,true))
fp.setBit(69);
if (RDKit::SubstructMatch(mol,*pats.bit_70,match,true))
fp.setBit(70);
if (RDKit::SubstructMatch(mol,*pats.bit_71,match,true))
fp.setBit(71);
if (RDKit::SubstructMatch(mol,*pats.bit_72,match,true))
fp.setBit(72);
if (RDKit::SubstructMatch(mol,*pats.bit_73,match,true))
fp.setBit(73);
if (RDKit::SubstructMatch(mol,*pats.bit_74,match,true))
fp.setBit(74);
if (RDKit::SubstructMatch(mol,*pats.bit_75,match,true))
fp.setBit(75);
if (RDKit::SubstructMatch(mol,*pats.bit_76,match,true))
fp.setBit(76);
if (RDKit::SubstructMatch(mol,*pats.bit_77,match,true))
fp.setBit(77);
if (RDKit::SubstructMatch(mol,*pats.bit_78,match,true))
fp.setBit(78);
if (RDKit::SubstructMatch(mol,*pats.bit_79,match,true))
fp.setBit(79);
if (RDKit::SubstructMatch(mol,*pats.bit_80,match,true))
fp.setBit(80);
if (RDKit::SubstructMatch(mol,*pats.bit_81,match,true))
fp.setBit(81);
if (RDKit::SubstructMatch(mol,*pats.bit_82,match,true))
fp.setBit(82);
if (RDKit::SubstructMatch(mol,*pats.bit_83,match,true))
fp.setBit(83);
if (RDKit::SubstructMatch(mol,*pats.bit_84,match,true))
fp.setBit(84);
if (RDKit::SubstructMatch(mol,*pats.bit_85,match,true))
fp.setBit(85);
if (RDKit::SubstructMatch(mol,*pats.bit_86,match,true))
fp.setBit(86);
if (RDKit::SubstructMatch(mol,*pats.bit_87,match,true))
fp.setBit(87);
if (RDKit::SubstructMatch(mol,*pats.bit_89,match,true))
fp.setBit(89);
if (RDKit::SubstructMatch(mol,*pats.bit_90,match,true))
fp.setBit(90);
if (RDKit::SubstructMatch(mol,*pats.bit_91,match,true))
fp.setBit(91);
if (RDKit::SubstructMatch(mol,*pats.bit_92,match,true))
fp.setBit(92);
if (RDKit::SubstructMatch(mol,*pats.bit_93,match,true))
fp.setBit(93);
if (RDKit::SubstructMatch(mol,*pats.bit_94,match,true))
fp.setBit(94);
if (RDKit::SubstructMatch(mol,*pats.bit_95,match,true))
fp.setBit(95);
if (RDKit::SubstructMatch(mol,*pats.bit_96,match,true))
fp.setBit(96);
if (RDKit::SubstructMatch(mol,*pats.bit_97,match,true))
fp.setBit(97);
if (RDKit::SubstructMatch(mol,*pats.bit_98,match,true))
fp.setBit(98);
if (RDKit::SubstructMatch(mol,*pats.bit_99,match,true))
fp.setBit(99);
if (RDKit::SubstructMatch(mol,*pats.bit_100,match,true))
fp.setBit(100);
if (RDKit::SubstructMatch(mol,*pats.bit_101,match,true))
fp.setBit(101);
if (RDKit::SubstructMatch(mol,*pats.bit_102,match,true))
fp.setBit(102);
if (RDKit::SubstructMatch(mol,*pats.bit_104,match,true))
fp.setBit(104);
if (RDKit::SubstructMatch(mol,*pats.bit_105,match,true))
fp.setBit(105);
if (RDKit::SubstructMatch(mol,*pats.bit_106,match,true))
fp.setBit(106);
if (RDKit::SubstructMatch(mol,*pats.bit_107,match,true))
fp.setBit(107);
if (RDKit::SubstructMatch(mol,*pats.bit_108,match,true))
fp.setBit(108);
if (RDKit::SubstructMatch(mol,*pats.bit_109,match,true))
fp.setBit(109);
if (RDKit::SubstructMatch(mol,*pats.bit_110,match,true))
fp.setBit(110);
if (RDKit::SubstructMatch(mol,*pats.bit_111,match,true))
fp.setBit(111);
if (RDKit::SubstructMatch(mol,*pats.bit_112,match,true))
fp.setBit(112);
if (RDKit::SubstructMatch(mol,*pats.bit_113,match,true))
fp.setBit(113);
if (RDKit::SubstructMatch(mol,*pats.bit_114,match,true))
fp.setBit(114);
if (RDKit::SubstructMatch(mol,*pats.bit_115,match,true))
fp.setBit(115);
if (RDKit::SubstructMatch(mol,*pats.bit_116,match,true))
fp.setBit(116);
if (RDKit::SubstructMatch(mol,*pats.bit_117,match,true))
fp.setBit(117);
if (RDKit::SubstructMatch(mol,*pats.bit_118,matches,true,true) > 1)
fp.setBit(118);
if (RDKit::SubstructMatch(mol,*pats.bit_119,match,true))
fp.setBit(119);
if (RDKit::SubstructMatch(mol,*pats.bit_120,matches,true,true) > 1)
fp.setBit(120);
if (RDKit::SubstructMatch(mol,*pats.bit_121,match,true))
fp.setBit(121);
if (RDKit::SubstructMatch(mol,*pats.bit_122,match,true))
fp.setBit(122);
if (RDKit::SubstructMatch(mol,*pats.bit_123,match,true))
fp.setBit(123);
count = RDKit::SubstructMatch(mol,*pats.bit_124,matches,true,true);
if (count > 0)
fp.setBit(124);
if (count > 1)
fp.setBit(130);
if (RDKit::SubstructMatch(mol,*pats.bit_126,match,true))
fp.setBit(126);
count = RDKit::SubstructMatch(mol,*pats.bit_127,matches,true,true);
if (count > 1)
fp.setBit(127);
if (count > 0)
fp.setBit(143);
if (RDKit::SubstructMatch(mol,*pats.bit_128,match,true))
fp.setBit(128);
if (RDKit::SubstructMatch(mol,*pats.bit_129,match,true))
fp.setBit(129);
if (RDKit::SubstructMatch(mol,*pats.bit_131,matches,true,true) > 1)
fp.setBit(131);
if (RDKit::SubstructMatch(mol,*pats.bit_132,match,true))
fp.setBit(132);
if (RDKit::SubstructMatch(mol,*pats.bit_133,match,true))
fp.setBit(133);
if (RDKit::SubstructMatch(mol,*pats.bit_135,match,true))
fp.setBit(135);
if (RDKit::SubstructMatch(mol,*pats.bit_136,matches,true,true) > 1)
fp.setBit(136);
if (RDKit::SubstructMatch(mol,*pats.bit_137,match,true))
fp.setBit(137);
count = RDKit::SubstructMatch(mol,*pats.bit_138,matches,true,true);
if (count > 1)
fp.setBit(138);
if (count > 0)
fp.setBit(153);
if (RDKit::SubstructMatch(mol,*pats.bit_139,match,true))
fp.setBit(139);
count = RDKit::SubstructMatch(mol,*pats.bit_140,matches,true,true);
if (count > 3)
fp.setBit(140);
if (count > 2)
fp.setBit(146);
if (count > 1)
fp.setBit(159);
if (count > 0)
fp.setBit(164);
if (RDKit::SubstructMatch(mol,*pats.bit_141,matches,true,true) > 2)
fp.setBit(141);
count = RDKit::SubstructMatch(mol,*pats.bit_142,matches,true,true);
if (count > 1)
fp.setBit(142);
if (count > 0)
fp.setBit(161);
if (RDKit::SubstructMatch(mol,*pats.bit_144,match,true))
fp.setBit(144);
count = RDKit::SubstructMatch(mol,*pats.bit_145,matches,true,true);
if (count > 1)
fp.setBit(145);
if (count > 0)
fp.setBit(163);
if (RDKit::SubstructMatch(mol,*pats.bit_147,match,true))
fp.setBit(147);
if (RDKit::SubstructMatch(mol,*pats.bit_148,match,true))
fp.setBit(148);
count = RDKit::SubstructMatch(mol,*pats.bit_149,matches,true,true);
if (count > 1)
fp.setBit(149);
if (count > 0)
fp.setBit(160);
if (RDKit::SubstructMatch(mol,*pats.bit_150,match,true))
fp.setBit(150);
if (RDKit::SubstructMatch(mol,*pats.bit_151,match,true))
fp.setBit(151);
if (RDKit::SubstructMatch(mol,*pats.bit_152,match,true))
fp.setBit(152);
if (RDKit::SubstructMatch(mol,*pats.bit_154,match,true))
fp.setBit(154);
if (RDKit::SubstructMatch(mol,*pats.bit_155,match,true))
fp.setBit(155);
if (RDKit::SubstructMatch(mol,*pats.bit_156,match,true))
fp.setBit(156);
if (RDKit::SubstructMatch(mol,*pats.bit_157,match,true))
fp.setBit(157);
if (RDKit::SubstructMatch(mol,*pats.bit_158,match,true))
fp.setBit(158);
if (RDKit::SubstructMatch(mol,*pats.bit_162,match,true))
fp.setBit(162);
if (RDKit::SubstructMatch(mol,*pats.bit_165,match,true))
fp.setBit(165);
/* BIT 125 */
RDKit::RingInfo *info = mol.getRingInfo();
unsigned int ringcount = info->numRings();
unsigned int nArom = 0;
for (unsigned int i= 0; i<ringcount; i++) {
bool isArom = true;
const std::vector<int> *ring = &info->bondRings()[i];
std::vector<int>::const_iterator iter;
for (iter=ring->begin(); iter!=ring->end(); ++iter)
if (!mol.getBondWithIdx(*iter)->getIsAromatic()) {
isArom = false;
break;
}
if (isArom) {
if (nArom) {
fp.setBit(125);
break;
} else nArom++;
}
}
/* BIT 166 */
std::vector<int> mapping;
if (RDKit::MolOps::getMolFrags(mol,mapping) > 1)
fp.setBit(166);
}
} //end of local anonymous namespace
namespace RDKit {
namespace MACCSFingerprints {
ExplicitBitVect *getFingerprintAsBitVect(const ROMol &mol){
ExplicitBitVect *fp=new ExplicitBitVect(167);
GenerateFP(mol,*fp);
return fp;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
#include "region_grow.h"
#include <cellogram/navigation.h>
#include <cellogram/boundary_loop.h>
#include <igl/slice.h>
#include <igl/opengl/glfw/Viewer.h>
#include <Eigen/Dense>
#include <algorithm>
#include <queue>
#include <iostream>
////////////////////////////////////////////////////////////////////////////////
namespace cellogram {
// -----------------------------------------------------------------------------
void region_grow(std::vector<std::vector<int>> &Graph, const Eigen::Matrix<bool, 1, Eigen::Dynamic> &crit_pass, Eigen::VectorXi ®ion)
{
int n = crit_pass.size();
int cId = 1;
std::queue<int> Q;
Eigen::VectorXi visited = Eigen::VectorXi::Zero(n);
std::vector<int> id(n, 0);
for (int i = 0; i < n; i++)
{
Q.push(i);
while (!Q.empty())
{
int u = Q.front();
Q.pop();
if (crit_pass(u) && visited(u) == 0)
{
//add connections to queue if not already visited
for (std::vector<int>::iterator it = Graph[u].begin(); it != Graph[u].end(); ++it) {
if (visited(*it) == 0)
{
Q.push(*it);
}
}
id[u] = cId;
}
// set vertex to visited
visited(u) = 1;
//std::cout << i << " - " << crit_pass[i] << " - " << id[u] << " - " << u << std::endl;
}
// While loop left which means that the next vertex found is from a new group
cId++;
}
// Loop through region to clean up IDs
std::vector<int> map = id;
std::sort(map.begin(), map.end());
auto newEnd = std::unique(map.begin(), map.end());
map.erase(newEnd, map.end());
for (int i = 0; i < map.size(); i++)
{
std::replace(id.begin(), id.end(), map[i], i);
}
// Save into eigen format
region = Eigen::VectorXi::Zero(n);
for (int i = 0; i < id.size(); i++)
{
region(i) = id[i];
}
}
// -----------------------------------------------------------------------------
} // namespace cellogram
|
#include <iostream>
class Node{
public:
int value;
Node* next;
public:
void SetValue(int aValue) {
value = aValue;
};
void SetNext(Node* aNext) {
next = aNext;
};
int Value() {
return value;
};
Node* Next() { return next; };
};
class List{
Node *head;
public:
List() {
head = NULL;
}
~List() {
Node* tmp = head;
while(tmp->Next() != nullptr) {
tmp = tmp->Next();
delete tmp;
}
delete head;
}
int len = 0;
void push(int value) {
++len;
Node* newNode = new Node();
newNode->SetValue(value);
newNode->SetNext(NULL);
Node *tmp = head;
if ( tmp != NULL ) {
while ( tmp->Next() != NULL ) {
tmp = tmp->Next();
}
tmp->SetNext(newNode);
}
else {
head = newNode;
}
}
void get() {
std::cout << len;
}
void pop() {
--len;
Node *tmp = head;
Node * mem;
if ( tmp != NULL ) {
while ( tmp->Next() != NULL ) {
mem = tmp;
tmp = tmp->Next();
}
delete tmp;
mem->SetNext(NULL);
}
else {
delete head ;
}
}
void add(int index, int value) {
Node *tmp = head;
if(len > index && index > 0) {
++len;
Node * newNode = new Node;
newNode->SetValue(value);
Node *prev;
for (int i = 0; i < index; ++i) {
prev = tmp;
tmp = tmp->Next();
}
newNode->SetNext(prev->Next());
prev->SetNext(newNode);
} else if(index == len) {
push(value);
} else {
std::cout << "Bad index";
return;
}
}
void Print() {
Node *tmp = head;
do {
std::cout << tmp->Value() << " -> ";
tmp = tmp->Next();
} while ( tmp != NULL );
}
};
int main() {
List list;
list.push(7);
list.push(4);
list.push(74);
list.push(89);
list.push(9);
list.add(5, -96);
std::cout << "\nOur list is_";
list.Print();
std::cout << "\nList length is_";
list.get();
return 0;
}
|
#include "kg/browser/app.hh"
int main(int argc, char ** argv) {
kg::App * app = new kg::App {};
return wxEntry(argc, argv);
}
|
/*
* clickablelabel.h
* A QLabel that we can click on ==> emit a clicked signal.
*
* @author Yoan DUMAS
* @version 1.0
* @date 21/01/2014
*/
#ifndef CLICKABLELABEL_H
#define CLICKABLELABEL_H
#include <QLabel>
#include "rules.h"
class ClickableLabel : public QLabel
{
Q_OBJECT
public:
explicit ClickableLabel(const QString& text ="", QWidget * parent = 0 );
ClickableLabel(position_t pos);
~ClickableLabel();
signals:
void clicked(position_t pos);
protected:
void mouseReleaseEvent(QMouseEvent * event );
private:
position_t pos_;
};
#endif // CLICKABLELABEL_H
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "TwoTheEdgeCharacter.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/Controller.h"
#include "GameFramework/SpringArmComponent.h"
#include "ExtraMovementComponent.h"
#include "PlayerNameHeader.h"
#include "TwoTheEdgePlayerState.h"
#include "Components/TextRenderComponent.h"
#include "Kismet/GameplayStatics.h"
#include "TwoTheEdgeGameMode.h"
//////////////////////////////////////////////////////////////////////////
// ATwoTheEdgeCharacter
class ATwoTheEdgePlayerState;
ATwoTheEdgeCharacter::ATwoTheEdgeCharacter()
{
// Set size for collision capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// set our turn rates for input
BaseTurnRate = 45.f;
BaseLookUpRate = 45.f;
// Don't rotate when the controller rotates. Let that just affect the camera.
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input...
GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate
GetCharacterMovement()->JumpZVelocity = 600.f;
GetCharacterMovement()->AirControl = 0.2f;
// Create a camera boom (pulls in towards the player if there is a collision)
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character
CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller
// Create a follow camera
FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character)
// are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
}
void ATwoTheEdgeCharacter::OnPossessed_Implementation(AController* NewController)
{
PossessedServer(NewController);
}
//////////////////////////////////////////////////////////////////////////
// Input
void ATwoTheEdgeCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
// Set up gameplay key bindings
check(PlayerInputComponent);
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
PlayerInputComponent->BindAxis("MoveForward", this, &ATwoTheEdgeCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &ATwoTheEdgeCharacter::MoveRight);
// We have 2 versions of the rotation bindings to handle different kinds of devices differently
// "turn" handles devices that provide an absolute delta, such as a mouse.
// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("TurnRate", this, &ATwoTheEdgeCharacter::TurnAtRate);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookUpRate", this, &ATwoTheEdgeCharacter::LookUpAtRate);
// handle touch devices
PlayerInputComponent->BindTouch(IE_Pressed, this, &ATwoTheEdgeCharacter::TouchStarted);
PlayerInputComponent->BindTouch(IE_Released, this, &ATwoTheEdgeCharacter::TouchStopped);
// VR headset functionality
PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &ATwoTheEdgeCharacter::OnResetVR);
// Crouch
PlayerInputComponent->BindAction("Crouch", IE_Pressed, this, &ATwoTheEdgeCharacter::DoCrouch);
PlayerInputComponent->BindAction("Crouch", IE_Released, this, &ATwoTheEdgeCharacter::DoUnCrouch);
// Sprint
PlayerInputComponent->BindAction("Sprint", IE_Pressed, this, &ATwoTheEdgeCharacter::Sprint);
PlayerInputComponent->BindAction("Sprint", IE_Released, this, &ATwoTheEdgeCharacter::Walk);
// Forward dash
PlayerInputComponent->BindAction("ForwardDash", IE_Pressed, this, &ATwoTheEdgeCharacter::ForwardDash);
// Respawn
PlayerInputComponent->BindAction("Respawn", IE_Pressed, this, &ATwoTheEdgeCharacter::Respawn);
}
void ATwoTheEdgeCharacter::BeginPlay()
{
Super::BeginPlay();
}
void ATwoTheEdgeCharacter::OnResetVR()
{
UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition();
}
void ATwoTheEdgeCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
Jump();
}
void ATwoTheEdgeCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
StopJumping();
}
void ATwoTheEdgeCharacter::DoCrouch()
{
Crouch(true);
}
void ATwoTheEdgeCharacter::DoUnCrouch()
{
UnCrouch(true);
}
void ATwoTheEdgeCharacter::Sprint()
{
ExtraMovement->Sprint();
OnSprint(true);
}
void ATwoTheEdgeCharacter::Walk()
{
ExtraMovement->Walk();
OnSprint(false);
}
void ATwoTheEdgeCharacter::ForwardDash()
{
ATwoTheEdgePlayerState* CastedPlayerState = GetPlayerState<ATwoTheEdgePlayerState>();
if (CastedPlayerState->DashCharges > 0)
{
if (ExtraMovement->GetDashOnDelay())
{
GEngine->AddOnScreenDebugMessage(-1, 2.f, FColor::Blue, TEXT("Dash on delay"));
return;
}
CastedPlayerState->DashCharges--;
ExtraMovement->ForwardDash();
// Blueprint event.
OnForwardDash();
}
}
void ATwoTheEdgeCharacter::Respawn()
{
// If host
if (HasAuthority())
{
// Shows respawn animation to self and other players.
RespawnOnHost();
}
else
{
// Shows respawn animation to other players.
RespawnOnServer();
// Shows respawn animation to self.
RespawnOnClient();
}
}
void ATwoTheEdgeCharacter::RespawnOnServer_Implementation()
{
OnRespawn();
}
void ATwoTheEdgeCharacter::RespawnOnClient_Implementation()
{
OnRespawn();
}
void ATwoTheEdgeCharacter::RespawnOnHost_Implementation()
{
OnRespawn();
}
void ATwoTheEdgeCharacter::CreatePlayerName_Implementation(APlayerCameraManager* CameraManager)
{
// Hide the player name text if it's the local player.
if (UGameplayStatics::GetPlayerCharacter(GetWorld(), 0) != this)
{
APlayerNameHeader* NameHeader = Cast<APlayerNameHeader>(
GetWorld()->SpawnActor(PlayerNameClass, &GetTransform()));
NameHeader->CameraManager = CameraManager;
// Gets the player name of this pawn's owner.
APlayerState* ThisPlayerState = GetPlayerState();
ATwoTheEdgePlayerState* Re = Cast<ATwoTheEdgePlayerState>(ThisPlayerState);
FString PlayerName;
if (ThisPlayerState)
{
PlayerName = GetPlayerState()->GetPlayerName();
GEngine->AddOnScreenDebugMessage(-1, 2.f, FColor::Red, FString::FromInt(Re->PlayerColour));
}
else
PlayerName = "Nameless";
// Caps the name's length.
PlayerName = PlayerName.Left(15);
NameHeader->Initialise(PlayerName, FColor::Orange, this);
}
}
void ATwoTheEdgeCharacter::TeleportOnServer_Implementation(const FVector& DestLocation, const FRotator& DestRotation)
{
// Movement must be done on server.
TeleportTo(DestLocation, DestRotation);
}
void ATwoTheEdgeCharacter::RequestGrenadeThrow(const int32& GrenadeType)
{
ATwoTheEdgePlayerState* CastedPlayerState = GetPlayerState<ATwoTheEdgePlayerState>();
switch (GrenadeType)
{
case 0:
if (CastedPlayerState->ExplosiveGrenades > 0)
CastedPlayerState->ExplosiveGrenades--;
else
return;
break;
case 1:
if (CastedPlayerState->FreezeGrenades > 0)
CastedPlayerState->FreezeGrenades--;
else
return;
break;
default:
return;
}
// If host
if (HasAuthority())
{
// Shows respawn animation to self and other players.
GrenadeThrowServer(GrenadeType);
}
else
{
// Sending info to server and client works perfectly.
// The problem is sending the info from the server to other clients.
GrenadeThrowServer(GrenadeType);
GrenadeThrowClient(GrenadeType);
}
}
void ATwoTheEdgeCharacter::GrenadeThrowServer_Implementation(const int32& GrenadeType)
{
OnGrenadeThrow(GrenadeType);
}
void ATwoTheEdgeCharacter::GrenadeThrowClient_Implementation(const int32& GrenadeType)
{
OnGrenadeThrow(GrenadeType);
}
void ATwoTheEdgeCharacter::GrenadeThrowNetCast_Implementation(const int32& GrenadeType)
{
OnGrenadeThrow(GrenadeType);
}
void ATwoTheEdgeCharacter::TurnAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void ATwoTheEdgeCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
void ATwoTheEdgeCharacter::MoveForward(float Value)
{
if ((Controller != NULL) && (Value != 0.0f))
{
// find out which way is forward
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get forward vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
AddMovementInput(Direction, Value);
}
}
void ATwoTheEdgeCharacter::MoveRight(float Value)
{
if ( (Controller != NULL) && (Value != 0.0f) )
{
// find out which way is right
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get right vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
// add movement in that direction
AddMovementInput(Direction, Value);
}
}
void ATwoTheEdgeCharacter::Jump()
{
Super::Jump();
OnJump();
}
|
// Copyright <2018> <Tomoyuki Nakabayashi>
// This software is released under the MIT License, see LICENSE.
#ifndef MOCK_LED_CONTROLLER_OS_TIME_H_
#define MOCK_LED_CONTROLLER_OS_TIME_H_
#include <gmock/gmock.h>
#include <cstdint>
#include <os/time.h>
class MOCK_TIME {
public:
MOCK_METHOD0(GET_MSEC_OF_DAY, uint32_t(void));
};
extern MOCK_TIME *mock_time;
extern "C" {
uint32_t GET_MSEC_OF_DAY() {
return mock_time->GET_MSEC_OF_DAY();
}
}
#endif // MOCK_LED_CONTROLLER_OS_TIME_H_
|
#include "windows.h"
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#include "initguid.h"
#include "dbgeng.h"
#include "Registration.h"
#include "IOCallbacks.hpp"
#include "DebugEventCallbacks.hpp"
#include "Common.h"
const TCHAR* REGISTER_POST_MORTEM = TEXT("I");
const TCHAR* UNREGISTER_POST_MORTEM = TEXT("uI");
const TCHAR* PID_OPTION = TEXT("p");
const TCHAR* EID_OPTION = TEXT("e");
const TCHAR* DIR_PATH_OPTION = TEXT("o");
const TCHAR* BASIC_COMMAND_LINE = TEXT("-p %ld -e %ld");
void PrintHelp()
{
_tprintf(TEXT("FuzzwareDBG.exe 2008 (c) dave@fuzzware.net\n"));
_tprintf(TEXT("\n"));
_tprintf(TEXT("Usage:\n"));
_tprintf(TEXT(" FuzzwareDBG [option]\n"));
_tprintf(TEXT("\n"));
_tprintf(TEXT("Options\n"));
_tprintf(TEXT(" -%s [-%s dirpath] Register FuzzwareDBG as the post mortem debugger\n"), REGISTER_POST_MORTEM, DIR_PATH_OPTION);
_tprintf(TEXT(" -%s Unregister FuzzwareDBG as the post mortem debugger\n"), UNREGISTER_POST_MORTEM);
_tprintf(TEXT(" -%s PID [-%s EID][-%s dirpath]\n"), PID_OPTION, EID_OPTION, DIR_PATH_OPTION);
_tprintf(TEXT(" -%s PID Attach to process with given Process Id (PID)\n"), PID_OPTION);
_tprintf(TEXT(" -%s EID Event ID to signal once attached (used by Error Reporting)\n"), EID_OPTION);
_tprintf(TEXT(" -%s dirpath Specify output path, default is exe directory\n"), DIR_PATH_OPTION);
}
/*
* Returns true if the command line option exists, otherwise false
*/
bool CommandLineOptionExists(int argc, TCHAR** argv, const TCHAR* pszOption)
{
for(int i = 1; i < argc; i++)
{
TCHAR* cmd = argv[i];
if((_tcslen(cmd) > 1) && (('/' == *cmd) || ('-' == *cmd)))
{
if(0 == _tcsicmp(cmd + 1, pszOption))
{
return true;
}
}
}
return false;
}
/*
* Finds the command line option and returns the argument following it, if there is one.
* If there is no following argument or the option does not exist, it returns NULL.
*/
TCHAR* CommandLineOptionValue(int argc, TCHAR** argv, const TCHAR* pszOption)
{
for(int i = 1; i < argc; i++)
{
TCHAR* cmd = argv[i];
if((_tcslen(cmd) > 1) && (('/' == *cmd) || ('-' == *cmd)))
{
if(0 == _tcsicmp(cmd + 1, pszOption))
{
if(i + 1 < argc)
return argv[i + 1];
else
return NULL;
}
}
}
return NULL;
}
void ProcessCommandLine(int argc, TCHAR** argv)
{
TCHAR* cmd;
// Try to process the command to register or unregister as the post mortem debugger
if(CommandLineOptionExists(argc, argv, REGISTER_POST_MORTEM))
{
TCHAR szFilename[MAX_PATH];
DWORD ccFilename = GetModuleFileName(NULL, szFilename, MAX_PATH);
if(MAX_PATH == ccFilename)
{
PrintHelp();
_tprintf(TEXT("\n\nThe full path to FuzzwareDBG is too long, it needs to be less than MAX_PATH.\n"));
return;
}
// Construct the basic command line i.e. "fullpathtoexe" -p %ld -e %ld
size_t ccCmdLine = ccFilename + 3 + _tcslen(BASIC_COMMAND_LINE);
TCHAR* pszCmdLine = (TCHAR*)malloc( (ccCmdLine + 1) * sizeof(TCHAR) );
if(NULL == pszCmdLine)
{
_tprintf(TEXT("\n\nOut of memory.\n"));
return;
}
pszCmdLine[0] = TEXT('\0');
StringCchCat(pszCmdLine, ccCmdLine + 1, TEXT("\""));
StringCchCat(pszCmdLine, ccCmdLine + 1, szFilename);
StringCchCat(pszCmdLine, ccCmdLine + 1, TEXT("\" "));
StringCchCat(pszCmdLine, ccCmdLine + 1, BASIC_COMMAND_LINE);
if(CommandLineOptionExists(argc, argv, DIR_PATH_OPTION)) // Check if output directory was specified
{
cmd = CommandLineOptionValue(argc, argv, DIR_PATH_OPTION);
if(NULL != cmd)
{
ccCmdLine += (_tcslen(cmd) + _tcslen(DIR_PATH_OPTION) + 5);
pszCmdLine = (TCHAR*)realloc(pszCmdLine, (ccCmdLine + 1) * sizeof(TCHAR) );
if(NULL == pszCmdLine)
{
_tprintf(TEXT("\n\nOut of memory.\n"));
return;
}
StringCchCat(pszCmdLine, ccCmdLine + 1, TEXT(" -"));
StringCchCat(pszCmdLine, ccCmdLine + 1, DIR_PATH_OPTION);
StringCchCat(pszCmdLine, ccCmdLine + 1, TEXT(" \""));
StringCchCat(pszCmdLine, ccCmdLine + 1, cmd);
StringCchCat(pszCmdLine, ccCmdLine + 1, TEXT("\""));
}
else
{
PrintHelp();
return;
}
}
// Make sure there are no extraneous command line arguments
if((2 == argc) || (4 == argc))
RegisterPostMortem(pszCmdLine);
else
PrintHelp();
free(pszCmdLine);
return;
}
if(CommandLineOptionExists(argc, argv, UNREGISTER_POST_MORTEM))
{
// Make sure there are no extraneous command line arguments
if(2 == argc)
UnregisterPostMortem();
else
PrintHelp();
return;
}
/*
* Assume the command line is wanting us to attach
*/
ULONG ulPID = 0;
bool bUsingEID = false;
HANDLE hEID = NULL;
TCHAR* pcDirPath = NULL;
// Find PID
cmd = CommandLineOptionValue(argc, argv, PID_OPTION);
if(NULL != cmd)
{
// Convert PID to number
ulPID = (ULONG)_tstoi(cmd);
}
else
{
PrintHelp();
return;
}
// Find EID, it is not a mandatory option
cmd = CommandLineOptionValue(argc, argv, EID_OPTION);
if(NULL != cmd)
{
// Convert EID to number
hEID = (HANDLE)_tstoi(argv[4]);
bUsingEID = true;
}
// Get the directory path
cmd = CommandLineOptionValue(argc, argv, DIR_PATH_OPTION);
if(NULL != cmd)
{
// Store directory path
size_t ccDestSize = _tcslen(cmd);
pcDirPath = (TCHAR*)malloc((ccDestSize + 1) * sizeof(TCHAR));
if(NULL == pcDirPath)
{
_tprintf(TEXT("\n\nOut of memory.\n"));
return;
}
StringCchCopy(pcDirPath, ccDestSize + 1, cmd);
pcDirPath[ccDestSize] = 0;
}
else if(CommandLineOptionExists(argc, argv, DIR_PATH_OPTION))
{
PrintHelp();
return;
}
else
{
// Set to default, the directory of the exe
TCHAR szFilename[MAX_PATH];
if(MAX_PATH > GetModuleFileName(NULL, szFilename, MAX_PATH))
{
TCHAR* pcLastSlash = _tcsrchr(szFilename, '\\');
*(pcLastSlash + 1) = 0;
pcDirPath = CopyString(szFilename);
/*size_t iDestSize = _tcslen(szFilename);
pcDirPath = (TCHAR*)malloc((iDestSize + 1) * sizeof(TCHAR));
StringCchCopy(pcDirPath, iDestSize + 1, szFilename);
pcDirPath[iDestSize] = 0;*/
}
else
{
_tprintf(TEXT("\n\nThe full path to FuzzwareDBG is too long, it needs to be less than MAX_PATH.\n"));
return;
}
}
// Check parameter count
int iParamCount = 3; // exe name + -p + PID
if(bUsingEID)
iParamCount += 2;
if(CommandLineOptionExists(argc, argv, DIR_PATH_OPTION))
iParamCount += 2;
if(iParamCount != argc)
{
PrintHelp();
return;
}
/*
* If we get to here we are ready to run the debugger
*/
HRESULT hr;
// We have the PID and the output directory so run debugger
FuzzwareDBG* pFuzzwareDBG = new FuzzwareDBG();
BSTR bstrDirPath;
#ifdef UNICODE
bstrDirPath = SysAllocString(pcDirPath);
#else
wchar_t* pwcDirString = NULL;
int iSize = MultiByteToWideChar(CP_ACP, 0, pcDirPath, -1, pwcDirString, 0);
pwcDirString = (wchar_t*)malloc(iSize * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, pcDirPath, -1, pwcDirString, iSize);
bstrDirPath = SysAllocString(pwcDirString);
free(pwcDirString);
#endif
// Set the output directory
hr = pFuzzwareDBG->SetOutputDir(bstrDirPath);
if(!SUCCEEDED(hr))
{
printf("Failed to set output dir\n");
}
// Set the event to signal after the debugger has attached
if(bUsingEID)
pFuzzwareDBG->SetPMAttachCompleteEvent(hEID);
// Attach and run the process
hr = pFuzzwareDBG->AttachToProcess(ulPID);
hr = pFuzzwareDBG->RunProcess(&ulPID);
// Wait until we have finished debugging
pFuzzwareDBG->WaitForSessionToFinish();
// Clean up
delete pFuzzwareDBG;
free(pcDirPath);
return;
}
int main(int argc, TCHAR** argv)
{
/*
* Check if the command line parameters are asking us to register or unregister
*/
if(2 == argc)
{
if(CommandLineOptionExists(argc, argv, TEXT("RegServer")))
{
if(S_OK != DllRegisterServer())
return 1;
return 0;
}
if(CommandLineOptionExists(argc, argv, TEXT("UnregServer")))
{
if(S_OK != DllUnregisterServer())
return 1;
return 0;
}
// Not sure what this is but it seems to be being passed in.
// 15/5/08 This may be COM thing to indicate to the exe not to create an GUI components
// and execute the exe as if it was embedded in the calling application (apparently
// this similiar to what IE does when running a LocalServer ActiveX control)
if(CommandLineOptionExists(argc, argv, TEXT("Embedding")))
{
//__asm
//{
//int 3;
//}
RegisterClassObject();
return 0;
}
}
/*
* If there are no command line arguments then print out help
*/
if((1 == argc) || (6 == argc) || (argc > 7))
{
PrintHelp();
return 0;
}
else
{
ProcessCommandLine(argc, argv);
}
return 0;
//HRESULT hr;
//IDebugClient2* pIDebugClient2 = NULL;
//hr = DebugCreate(IID_IDebugClient2, (PVOID*)(&pIDebugClient2));
//if(S_OK != hr)
//{
// printf("Could not create IID_IDebugClient2. hr = %#x\n", hr);
// return 0;
//}
//printf("Created IID_IDebugClient2 successfully\n");
//IDebugControl* pIDebugControl = NULL;
//hr = DebugCreate(IID_IDebugControl, (PVOID*)(&pIDebugControl));
//if(S_OK != hr)
//{
// printf("Could not create IID_pIDebugControl. hr = %#x\n", hr);
// return 0;
//}
//printf("Created IID_pIDebugControl successfully\n");
//
///*PDEBUG_EVENT_CALLBACKS poEventCallbacks = NULL;
//hr = pIDebugClient2->GetEventCallbacks(&poEventCallbacks);
//if(S_OK != hr)
//{
// printf("Failed to get event callbacks. hr = %#x\n", hr);
//}
//if(NULL != poEventCallbacks)
//{
// printf("Got event callbacks. add = %#x\n", poEventCallbacks);
//}*/
//IDebugSystemObjects* pIDebugSystemObjects = NULL;
//hr = DebugCreate(IID_IDebugSystemObjects, (PVOID*)(&pIDebugSystemObjects));
//if(S_OK != hr)
//{
// printf("Could not create IID_IDebugSystemObjects. hr = %#x\n", hr);
// return 0;
//}
//DebugEventCallbacks* poDebugEventCallbacks = new DebugEventCallbacks((IDebugClient2*)pIDebugClient2, pIDebugSystemObjects, "");
//hr = pIDebugClient2->SetEventCallbacks((PDEBUG_EVENT_CALLBACKS)poDebugEventCallbacks);
//if(S_OK != hr)
//{
// printf("Failed to set event callbacks. hr = %#x\n", hr);
//}
//IOCallbacks* poIOCallbacks = new IOCallbacks();
//hr = pIDebugClient2->SetInputCallbacks((IDebugInputCallbacks*)poIOCallbacks);
//if(S_OK != hr)
//{
// printf("Failed to set input callbacks. hr = %#x\n", hr);
//}
//hr = pIDebugClient2->SetOutputCallbacks((IDebugOutputCallbacks*)poIOCallbacks);
//if(S_OK != hr)
//{
// printf("Failed to set output callbacks. hr = %#x\n", hr);
//}
//char* line = "\"C:\\Program Files\\Real\\RealPlayer\\realplay.exe\" G:\\Tools\\Fuzzware\\Examples\\Real\\sorted\\smplfsys!RMACreateInstance+0xb74\\mov-ByteLengthOfdref-0-ReplaceInteger-2.mov";
//hr = pIDebugClient2->CreateProcessAndAttach(0, line, DEBUG_PROCESS, 0, 0);
//if(S_OK != hr)
//{
// printf("Failed to create process. hr = %#x\n", hr);
// pIDebugClient2->Release();
// return 0;
//}
//
//hr = pIDebugClient2->CreateProcessAndAttach(0, "\"C:\\Program Files\\Real\\RealPlayer\\realplay.exe\" G:\\Tools\\Fuzzware\\Examples\\Real\\sorted\\smplfsys!RMACreateInstance+0xb74\\mov-ByteLengthOfdref-0-ReplaceInteger-2.mov", DEBUG_PROCESS, 0, 0);
//if(S_OK != hr)
//{
// printf("Failed to create process. hr = %#x\n", hr);
// pIDebugClient2->Release();
// return 0;
//}
//while(1)
//{
// // Should return E_UNEXPECTED when process exits, but maybe also if there is an outstanding request for input
// hr = pIDebugControl->WaitForEvent(0, INFINITE);
// if(S_OK != hr)
// {
// printf("WaitForEvent returned an error. hr = %#x\n", hr);
// break;
// }
// hr = pIDebugControl->SetExecutionStatus(DEBUG_STATUS_GO);
// if(S_OK != hr)
// {
// printf("Failed to set execution status. hr = %#x\n", hr);
// }
// /*hr = pIDebugControl->Execute(DEBUG_OUTCTL_IGNORE, "g", DEBUG_EXECUTE_NOT_LOGGED);
// if(S_OK != hr)
// {
// printf("Failed to execute command. hr = %#x\n", hr);
// }*/
//}
//
//hr = pIDebugClient2->DetachProcesses();
//if(S_OK != hr)
//{
// printf("Failed to detach process. hr = %#x\n", hr);
// return 0;
//}
//pIDebugControl->Release();
//pIDebugClient2->Release();
//return 0;
}
|
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_CORE_MAIN_H_INCLUDED
#define BEAST_CORE_MAIN_H_INCLUDED
/** Represents a command line program's entry point
To use this, derive your class from @ref Main and implement the
function run ();
*/
class Main : public Uncopyable
{
public:
Main ();
virtual ~Main ();
/** Run the program.
You should call this from your @ref main function. Don't put
anything else in there. Instead, do it in your class derived
from Main. For example:
@code
struct MyProgram : Main
{
int run (int argc, char const* const* argv)
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
};
int main (int argc, char const* const* argv)
{
MyProgram program;
return program.runFromMain (argc, argv);
}
@endcode
*/
int runFromMain (int argc, char const* const* argv);
/** Retrieve the instance of the program. */
static Main& getInstance ();
protected:
/** Entry point for running the program.
Subclasses provide the implementation.
*/
virtual int run (int argc, char const* const* argv) = 0;
private:
int runStartupUnitTests ();
private:
static Main* s_instance;
};
#endif
|
// https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
// Better solution
class Solution {
public:
int removeDuplicates(int A[], int n) {
if (n <= 0) {
return 0;
}
int pre = 1, cur = 1;
int occur = 1;
while (cur < n) {
if (A[cur-1] == A[cur]) {
if (occur == 1) {
occur++;
} else if (occur >= 2) {
cur++;
continue;
}
} else {
occur = 1;
}
A[pre++] = A[cur++];
}
return pre;
}
};
// Just acceptable solution
class Solution {
public:
int removeDuplicates(int A[], int n) {
unordered_map<int, int> occurence;
int removed = 0;
for (int i = 0; i < n - removed; i++) {
if (occurence.count(A[i]) == 0) {
occurence.emplace(A[i], 1);
} else if (occurence[A[i]] == 2) {
removed++;
for (int j = i; j < n - 1; j++) {
swap(A[j], A[j+1]);
}
i--; // swapped new value, avoid moving forward
} else { // only found once before
occurence[A[i]]++;
}
}
return n - removed;
}
};
|
// Created on: 2005-10-05
// Created by: Mikhail KLOKOV
// Copyright (c) 2005-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IntTools_BaseRangeSample_HeaderFile
#define _IntTools_BaseRangeSample_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
//! base class for range index management
class IntTools_BaseRangeSample
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT IntTools_BaseRangeSample();
Standard_EXPORT IntTools_BaseRangeSample(const Standard_Integer theDepth);
void SetDepth (const Standard_Integer theDepth) { myDepth = theDepth; }
Standard_Integer GetDepth() const { return myDepth; }
private:
Standard_Integer myDepth;
};
#endif // _IntTools_BaseRangeSample_HeaderFile
|
/* StringMath, homeworkProb2.cpp
author: william hutchinson
date: 20150911
write a program that takes a string containing infix including [(,),+,-,*]
(no obvious division or exponents) and integers and computes the value of the
expression. ex: (2 + 3) * 4 - 2 = 18
*/
#ifndef StringMath_included
#define StringMath_included
class StringMath{
private:
public:
StringMath(); // constructor
~StringMath(); // destructor
bool isOperand(char test); // tests for ints/decimals... in base 10.
bool isOperator(char test); // tests for ()+-*
bool isWhitespace(char test); // tests for spaces, new lines, tabs
double calc(double l,char operation,double r); // does the math
void unspool(char *operators,double *operands,int &opPos);
long parse(const char *input); // because I'm lazy.
long parseLong(const char *input); // lets see if I can dodge string
double parseDouble(const char *input);
};
#endif
|
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved
#ifndef SGFX_FONT_HPP_
#define SGFX_FONT_HPP_
#include <sgfx/sg_font_types.h>
#include "Bitmap.hpp"
namespace sgfx {
/*! \brief Font class
*
*/
class Font {
public:
Font();
/*! \details Returns a string of the available character set */
static const char * charset();
enum {
CHARSET_SIZE = 95
};
/*! \details This methods draws a character (\a c) on the font's
* bitmap and returns a pointer to the bitmap.
* @param c The character to draw
* @param ascii true if c is an ascii character or false the font is an icon font
*
* \return A pointer to a bitmap or zero if the character could not be loaded
*/
virtual const Bitmap & bitmap(char c, bool ascii = true) const = 0;
//Attribute access methods
int offset() const { return m_char.offset; }
int yoffset() const { return m_char.yoffset; }
/*! \details The maximum height of the font. */
virtual sg_size_t get_h() const = 0;
/*! \details Calulate the length (pixels on x-axis) of the specified string */
int calc_len(const char * str) const;
/*! \details Returns the number of characters in the font */
int size() const { return m_hdr.num_chars; }
/*! \details Set the spacing between letters within a word */
inline void set_letter_spacing(sg_size_t spacing){ m_letter_spacing = spacing; }
/*! \detials Returns the spacing of the letters within a word */
inline sg_size_t letter_spacing() const { return m_letter_spacing; }
/*! \details Set the number of pixels in a space between words */
inline void set_space_size(int s){ m_space_size = s; }
/*! \details Returns the number of pixels between words */
inline int space_size() const { return m_space_size; }
/*! \details Set the string pixels in the bitmap
*
* @param str The string to draw (or set)
* @param bitmap The bitmap to draw the string on
* @param point The top left corner to start drawing the string
* @return Zero on success
*/
int set_str(const char * str, Bitmap & bitmap, sg_point_t point) const;
/*! \details Clear the string pixels in the bitmap
*
* @param str The string to draw (or clear)
* @param bitmap The bitmap to draw the string on
* @param point The top left corner to start drawing the string
* @return Zero on success
*/
int clear_str(const char * str, Bitmap & bitmap, sg_point_t point) const;
int set_char(char c, Bitmap & bitmap, sg_point_t point) const;
int clear_char(char c, Bitmap & bitmap, sg_point_t point) const;
protected:
static int to_charset(char ascii);
virtual int load_char(sg_font_char_t & ch, char c, bool ascii) const = 0;
virtual int load_bitmap(const sg_font_char_t & ch) const = 0;
virtual int load_kerning(u16 first, u16 second) const { return 0; }
mutable int m_offset;
mutable sg_font_char_t m_char;
sg_size_t m_letter_spacing;
int m_space_size;
sg_font_hdr_t m_hdr;
private:
};
};
#endif /* SGFX_FONT_HPP_ */
|
#include <iostream>
#include <opencv2/opencv.hpp>
#include "config.h"
#include "tracker.h"
#include "kcftracker.h"
#include "csktracker.h"
#include "stctracker.h"
#include "trackerfactory.h"
using namespace std;
using namespace cv;
Tracker* TrackerFactory::createTracker(const Config& c) {
string name = c["tracker"];
if ("kcf" == name) {
return new KCFTracker();
} else if ("csk" == name) {
return new CSKTracker();
} else if ("stc" == name) {
return new STCTracker();
} else {
return NULL;
}
}
|
// Print the sum of series
// 1 + 12 + 123 + 1234 + ... nterms
#include <iostream>
using namespace std;
int main()
{
int i,j,n,s=0,sum=0;
cout<<"Enter n ";
cin>>n;
for(i = 1;i <= n;i++)
{
s = s * 10 + i;
sum += s;
}
cout<<sum;
return 0;
}
|
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <set>
using namespace std;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
#define int long long int
#define ld long double
#define F first
#define S second
#define P pair <int,int>
#define vi vector <int>
#define vs vector <string>
#define vb vector <bool>
#define all(x) x.begin(),x.end()
#define sz(x) (int)x.size()
#define REP(i,a,b) for(int i=(int)a;i<=(int)b;i++)
#define REV(i,a,b) for(int i=(int)a;i>=(int)b;i--)
#define sp(x,y) fixed<<setprecision(y)<<x
#define pb push_back
#define endl '\n'
const int mod = 1e9 + 7;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
const int N = 1e5 + 5;
int n, m;
int op[N];
void bfs() {
queue <int> q;
q.push(n);
op[n] = 1;
while (!q.empty()) {
int cur = q.front();
q.pop();
int minus = cur - 1;
if (minus > 0 && !op[minus]) {
op[minus] = op[cur] + 1;
q.push(minus);
}
int mult = cur * 2;
if (mult <= 10000 && !op[mult]) {
op[mult] = op[cur] + 1;
q.push(mult);
}
}
}
void solve() {
cin >> n >> m;
bfs();
// REP(i, 1, m)
// cout << op[i] << " ";
cout << op[m] - 1 << endl;
return ;
}
int32_t main() {
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
//int t;cin>>t;while(t--)
solve();
return 0;
}
|
#include<iostream>
#include<vector>
using namespace std;
int main()
{
// Initializing vector with values
vector<int> vect1{1, 2, 3, 4};
// Declaring new vector
vector<int> vect2;
//1.copy vector1 to vector3
vector<int> vect3(vect1);
vector<int> vect4;
vector<int> vect5;
// 2.A loop to copy elements of
// old vector into new vector
// by Iterative method
for (int i=0; i<vect1.size(); i++)
vect2.push_back(vect1[i]);
// 3.Copying vector by copy function
copy(vect1.begin(), vect1.end(), back_inserter(vect4));
//4. copy vect1 to vect5
vect5.assign(vect1.begin(), vect1.end());
cout << "Old vector elements are : ";
for (int i=0; i<vect1.size(); i++)
cout << vect1[i] << " ";
cout << endl;
cout << "New vector2 elements are : ";
for (int i=0; i<vect2.size(); i++)
cout << vect2[i] << " ";
cout<< endl;
cout << "New vector3 elements are : ";
for (int i=0; i<vect3.size(); i++)
cout << vect3[i] << " ";
cout<< endl;
cout << "New vector4 elements are : ";
for (int i=0; i<vect4.size(); i++)
cout << vect4[i] << " ";
cout<< endl;
cout << "New vector5 elements are : ";
for (int i=0; i<vect5.size(); i++)
cout << vect5[i] << " ";
cout<< endl;
// Changing value of vector to show that a new
// copy is created.
vect1[0] = 2;
for (int i=0; i<vect1.size(); i++)
cout << vect1[i] << " ";
cout<<endl;
cout << "The first element of old vector is :";
cout << vect1[0] << endl;
cout << "The first element of new vector is :";
cout << vect2[0] <<endl;
return 0;
}
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Элементарныйе функции для стандартного вывода
// Elementary function for standard output
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include<iostream>
#include<string>
using namespace std;
void word() {
cout << "Ok!" << endl;
}
int num() {
return 70;
}
int sum() {
return 25 + 10;
}
double del() {
return 25.0 / 32.2;
}
string str(string s) {
return s;
}
int sums(int a, int b) {
return a + b;
}
float dels(float a, float b) {
return a / b;
int main() {
word();
cout << dels(25.3, 33.5);
cout << num() << endl;
cout << sum() << endl;
cout << del() << endl;
cout << str("Alex") << endl;
cout << str("Alena") << endl;
cout << str("Hello") + str(", World!") << endl;
cout << sums(25, 25) << endl;
cout << sums(75, 13) << endl;
return 0;
}
// Output:
/*
Ok!
70
35
0.776398
Alex
Alena
Hello, World!
50
88
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
using namespace std;
const int inf = 1e9 + 7;
int a[110],f[110];
int main() {
int t;
scanf("%d",&t);
for (int ca = 1;ca <= t; ca++) {
printf("Case %d:\n",ca);
int n,r = 0;
f[0] = -inf;
scanf("%d",&n);
for (int i = 1;i <= n; i++) {
scanf("%d",&a[i]);
f[i] = max(0,f[i-1]) + a[i];
if (f[i] > f[r]) r = i;
}
int l = r;
while (l > 1 && f[l-1] + a[l] == f[l]) l--;
printf("%d %d %d\n",f[r],l,r);
}
return 0;
}
|
#pragma once
#include <string>
#include <vector>
#include "analytic_gas_disk.h"
#include "fargo_gas_disk.h"
#include "red_type.h"
class pp_disk
{
public:
pp_disk(n_objects_t *n_bodies, gas_disk_model_t g_disk_model, uint32_t id_dev, computing_device_t comp_dev);
pp_disk(std::string& path_data, std::string& path_data_info, gas_disk_model_t g_disk_model, uint32_t id_dev, computing_device_t comp_dev, const var_t* thrshld);
~pp_disk();
//! Copies ODE parameters and variables from the host to the cuda device
void copy_to_device();
void copy_disk_params_to_device();
//! Copies ODE parameters and variables from the cuda device to the host
void copy_to_host();
//! Copies the event data from the cuda device to the host
void copy_event_data_to_host();
//! Set the computing device to calculate the accelerations
/*!
\param device specifies which device will execute the computations
*/
void set_computing_device(computing_device_t device);
computing_device_t get_computing_device() { return comp_dev; }
void set_n_tpb(uint32_t n) { n_tpb = n; }
uint32_t get_n_tpb() { return n_tpb; }
void set_id_dev(uint32_t id) { id_dev = id; }
uint32_t get_id_dev() { return id_dev; }
void set_dt_CPU(uint32_t n) { dt_CPU = n; }
uint32_t get_dt_CPU() { return dt_CPU; }
//! Determines the mass of the central star
/*!
\return The mass of the central star
*/
var_t get_mass_of_star();
//! Returns the number of events during the simulation
uint32_t get_n_total_event();
//! Clears the event_counter (sets to 0)
void clear_event_counter();
//! Sets all event counter to a specific value
/*!
\param field Sets this field
\param value The value to set the field
*/
void set_event_counter(event_counter_name_t field, uint32_t value);
//! Print the data of all bodies
/*!
\param path print the data to this file
\param repres indicates the data representation of the file, i.e. text or binary
*/
void print_data(std::string& path, data_rep_t repres);
//! Print the data of all bodies
/*!
\param path print the data to this file
\param repres indicates the data representation of the file, i.e. text or binary
*/
void print_data_info(std::string& path, data_rep_t repres);
//! Print the event data
/*!
\param path print the data to this file
\param log_f print the data to this stream
*/
void print_event_data(std::string& path, std::ofstream& log_f);
//! Print the classical integrals
/*!
\param sout print the data to this stream
*/
void print_integral_data(std::string& path, pp_disk_t::integral_t& I);
//! From the events it will create a vector containing one entry for each colliding pair with the earliest collision time
void populate_sp_events();
void handle_collision();
void handle_ejection_hit_centrum();
void handle_collision_pair(uint32_t i, pp_disk_t::event_data_t *collision);
void rebuild_vectors();
//! Check all bodies against ejection and hit centrum criterium. The number of detected events are stored in the event_counter member variable.
bool check_for_ejection_hit_centrum();
//! Check collisin between all bodies. The number of detected events are stored in the event_counter member variable.
bool check_for_collision();
//! Check all bodies against ejection and hit centrum criterium. The number of detected events are stored in the event_counter member variable.
void gpu_check_for_ejection_hit_centrum();
void cpu_check_for_ejection_hit_centrum();
void gpu_check_for_collision();
void cpu_check_for_collision();
void cpu_check_for_collision(interaction_bound int_bound, bool SI_NSI, bool SI_TP, bool NSI, bool NSI_TP);
//! Calculates the differentials of variables
/*!
This function is called by the integrator when calculation of the differentials is necessary
\param i Order of the variables to calculate (e.g. 0: velocities, 1: acceleration ...)
\param rr Number of substep, used with higher order methods, like Runge-Kutta
\param curr_t Time
\param r Device vector with position variables
\param v Device vector with velocity variables
\param dy Device vector that will hold the differentials
*/
void calc_dydx(uint32_t i, uint32_t rr, ttt_t curr_t, const var4_t *r, const var4_t *v, var4_t* dy);
//! Calculates the classical integrals of the N-body system
/*!
This function is called by the main while cycle in order to determine the integrals in
\param cpy_to_HOST if true than the data is copied first from the DEVICE to the HOST
\param integrals array that will hold the integrals
*/
void calc_integral(bool cpy_to_HOST, pp_disk_t::integral_t& integrals);
//! Swaps the yout with the y variable, i.e. at the end of an integration step the output will be the input of the next step
void swap();
public:
//! Run a gravitational benchmark on the GPU and determines the number of threads at which the computation is the fastest.
/*!
\return The optimal number of threads per block
*/
uint32_t benchmark(bool verbose);
float benchmark_calc_grav_accel(ttt_t curr_t, uint32_t n_sink, interaction_bound int_bound, const pp_disk_t::body_metadata_t* body_md, const pp_disk_t::param_t* p, const var4_t* r, const var4_t* v, var4_t* a);
void gpu_calc_grav_accel(ttt_t curr_t, const var4_t* r, const var4_t* v, var4_t* dy);
void gpu_calc_drag_accel(ttt_t curr_t, const var4_t* r, const var4_t* v, var4_t* dy);
void cpu_calc_grav_accel(ttt_t curr_t, const var4_t* r, const var4_t* v, var4_t* dy);
void cpu_calc_grav_accel_SI( ttt_t curr_t, interaction_bound int_bound, const pp_disk_t::body_metadata_t* body_md, const pp_disk_t::param_t* p, const var4_t* r, const var4_t* v, var4_t* a);
void cpu_calc_grav_accel_SI( ttt_t curr_t, interaction_bound int_bound, const pp_disk_t::body_metadata_t* body_md, const pp_disk_t::param_t* p, const var4_t* r, const var4_t* v, var4_t* a, pp_disk_t::event_data_t* events, uint32_t *event_counter);
void cpu_calc_grav_accel_NI( ttt_t curr_t, interaction_bound int_bound, const pp_disk_t::body_metadata_t* body_md, const pp_disk_t::param_t* p, const var4_t* r, const var4_t* v, var4_t* a);
void cpu_calc_grav_accel_NI( ttt_t curr_t, interaction_bound int_bound, const pp_disk_t::body_metadata_t* body_md, const pp_disk_t::param_t* p, const var4_t* r, const var4_t* v, var4_t* a, pp_disk_t::event_data_t* events, uint32_t *event_counter);
void cpu_calc_grav_accel_NSI(ttt_t curr_t, interaction_bound int_bound, const pp_disk_t::body_metadata_t* body_md, const pp_disk_t::param_t* p, const var4_t* r, const var4_t* v, var4_t* a);
void cpu_calc_grav_accel_NSI(ttt_t curr_t, interaction_bound int_bound, const pp_disk_t::body_metadata_t* body_md, const pp_disk_t::param_t* p, const var4_t* r, const var4_t* v, var4_t* a, pp_disk_t::event_data_t* events, uint32_t *event_counter);
void cpu_calc_drag_accel(ttt_t curr_t, const var4_t* r, const var4_t* v, var4_t* dy);
void cpu_calc_drag_accel_NSI(ttt_t curr_t, interaction_bound int_bound, const pp_disk_t::body_metadata_t* body_md, const pp_disk_t::param_t* p, const var4_t* r, const var4_t* v, var4_t* a);
//! Test function: prints the data stored in sim_data
/*!
\param comp_dev If CPU than prints the data stored in sim_data on the HOST if GPU than on the device
*/
void print_sim_data(computing_device_t comp_dev);
ttt_t t; //!< time when the variables are valid
ttt_t dt; //!< timestep for the integrator
n_objects_t* n_bodies; //!< struct containing the number of different bodies
pp_disk_t::sim_data_t* sim_data; //!< struct containing all the data of the simulation
gas_disk_model_t g_disk_model;
analytic_gas_disk* a_gd;
fargo_gas_disk* f_gd;
uint32_t n_ejection[ EVENT_COUNTER_NAME_N]; //!< Number of ejection
uint32_t n_hit_centrum[EVENT_COUNTER_NAME_N]; //!< Number of hit centrum
uint32_t n_collision[ EVENT_COUNTER_NAME_N]; //!< Number of collision
uint32_t n_event[ EVENT_COUNTER_NAME_N]; //!< Number of total events
private:
//! Initialize the members to default values
void initialize();
void increment_event_counter(uint32_t *event_counter);
void load_data_info(std::string& path, data_rep_t repres);
void load_data(std::string& path_data, data_rep_t repres);
//! Allocates storage for data on the host and device memory
void allocate_storage();
//! Sets the grid and block for the kernel launch
void set_kernel_launch_param(uint32_t n_data);
//! Transforms the system to barycentric reference frame
void transform_to_bc();
//! Transform the time using the new time unit: 1/k = 58.13244 ...
void transform_time();
//! Transform the velocity using the new time unit: 1/k = 58.13244 ...
void transform_velocity();
uint32_t dt_CPU; //!< The elapsed time since the first start [sec]
uint32_t id_dev; //!< The id of the GPU
computing_device_t comp_dev; //!< The computing device to carry out the calculations (cpu or gpu)
uint32_t n_tpb; //!< The number of thread per block to use for kernel launches
dim3 grid;
dim3 block;
var_t threshold[THRESHOLD_N]; //! Contains the threshold values: hit_centrum_dst, ejection_dst, collision_factor
uint32_t event_counter; //! Number of events occured during the last check
uint32_t* d_event_counter; //! Number of events occured during the last check (stored on the devive)
pp_disk_t::event_data_t* events; //!< Vector on the host containing data for events (one colliding pair multiple occurances)
pp_disk_t::event_data_t* d_events; //!< Vector on the device containing data for events (one colliding pair multiple occurances)
std::vector<pp_disk_t::event_data_t> sp_events; //!< Vector on the host containing data for events but (one colliding pair one occurances)
std::vector<std::string> body_names;
};
|
#ifndef __REPORTLISTPRESENTER_H
#define __REPORTLISTPRESENTER_H
#include "CtrlWindowBase.h"
#include "IReportListView.h"
#include "ReportListModel.h"
namespace wh{
//-----------------------------------------------------------------------------
class ReportListPresenter : public CtrlWindowBase<IReportListView, ReportListModel>
{
sig::scoped_connection connViewUpdateList;
sig::scoped_connection connViewExecReport;
sig::scoped_connection connViewMkReport;
sig::scoped_connection connViewRmReport;
sig::scoped_connection connViewChReport;
sig::scoped_connection connModelUpdate;
sig::scoped_connection connModelMk;
sig::scoped_connection connModelRm;
sig::scoped_connection connModelCh;
void OnListUpdated(const rec::ReportList&);
void OnMkReport(const std::shared_ptr<const rec::ReportItem>&);
void OnRmReport(const std::shared_ptr<const rec::ReportItem>&);
void OnChReport(const std::shared_ptr<const rec::ReportItem>&, const wxString& old_rep_id);
virtual void ConnectView()override;
virtual void DisconnectView()override;
public:
ReportListPresenter(const std::shared_ptr<IReportListView>& view,const std::shared_ptr<ReportListModel>& model);
virtual std::shared_ptr<IViewWindow> GetView()const override;
void UpdateList();
void ExecReport(const wxString& rep_id);
void MkReport();
void RmReport(const wxString& rep_id);
void ChReport(const wxString& rep_id);
virtual void MkView()override;
};
//-----------------------------------------------------------------------------
} // namespace wh{
#endif // __INOTEBOOKVIEW_H
|
#include <string>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <list>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <numeric>
#include <bitset>
#include <deque>
//#include <random>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include <unordered_map>
#include <thread>
const long long LINF = (5e18);
const int INF = (1<<30);
const int sINF = (1<<23);
const int MOD = 1000000007;
const double EPS = 1e-6;
using namespace std;
class PieOrDolphin {
public:
vector <int> Distribute(vector <int> choice1, vector <int> choice2) {
int n = 50;
int m = (int)choice1.size();
vector<int> in(n, 0), out(n, 0);
vector<int> ans(m, 1);
// choice1 -> choice2
for (int i=0; i<m; ++i) {
out[choice1[i]]++;
in[choice2[i]]++;
}
while (true) {
int s = -1;
for (int i=0; i<n; ++i)
if (abs(out[i] - in[i]) >= 2)
s = i;
if (s == -1)
break;
if (in[s] > out[s]) {
for (int i=0; i<m; ++i)
ans[i] = ans[i] == 1 ? 2 : 1;
for (int i=0; i<n; ++i)
swap(in[i], out[i]);
}
vector<int> parent(n, -1), parentEdge(n, -1);
queue<int> que;
que.push(s);
int t = -1;
while (!que.empty()) {
int x = que.front(); que.pop();
if (in[x] > out[x]) {
t = x;
break;
}
for (int i=0; i<m; ++i) {
// u->v
int u,v;
if (ans[i] == 1) {
u = choice1[i];
v = choice2[i];
} else {
u = choice2[i];
v = choice1[i];
}
if (u == x && v != s) {
if (parent[v] != -1)
continue;
parent[v] = x;
parentEdge[v] = i;
que.push(v);
}
}
}
int x = t;
while (parent[x] != -1) {
int i = parentEdge[x];
ans[i] = ans[i] == 1 ? 2 : 1;
int u = parent[x];
in[u]++, out[u]--;
in[x]--, out[x]++;
x = u;
}
}
return ans;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { int Arr0[] = {10, 20, 10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {20, 30, 20}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {2, 2, 1 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(0, Arg2, Distribute(Arg0, Arg1)); }
void test_case_1() { int Arr0[] = {0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {2, 1 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(1, Arg2, Distribute(Arg0, Arg1)); }
void test_case_2() { int Arr0[] = {0, 1, 2, 3, 5, 6, 7, 8}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {8, 7, 6, 5, 3, 2, 1, 0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {2, 2, 2, 2, 2, 2, 2, 2 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(2, Arg2, Distribute(Arg0, Arg1)); }
void test_case_3() { int Arr0[] = {49, 0, 48, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3, 4, 5, 6}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {2, 2, 2, 2 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(3, Arg2, Distribute(Arg0, Arg1)); }
void test_case_4() { int Arr0[] = {21,4,14,0,31,46,1,34,2,3,27,19,47,46,17,11,41,12,31,0,34,18,8,14,23,40,0,18,48,35,42,24,25,32,25,44,17,6,44,34,12,39,43,39,26,
34,10,6,13,2,40,15,16,32,32,29,1,23,8,10,49,22,10,15,40,20,0,30,1,43,33,42,28,39,28,4,38,11,5,1,47,12,0,22,20,33,33,34,18,8,23,6}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {25,5,39,20,44,47,11,49,42,17,25,15,23,11,32,17,24,4,11,47,27,41,40,0,49,27,5,28,6,11,18,0,17,1,0,32,45,28,17,5,13,40,40,25,33,
7,8,32,12,0,39,30,8,39,23,9,8,34,34,37,5,1,24,23,0,29,11,42,29,40,24,18,37,1,21,0,31,47,23,33,45,48,31,11,40,45,24,22,19,26,37,39}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 1, 2, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 1, 1, 2, 2, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 2, 1, 2, 2, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 2, 2, 2, 1 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(4, Arg2, Distribute(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
PieOrDolphin ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include <cstdint>
#include <vector>
#pragma once
class UnificationCoef
{
const uint16_t MAX_VALUE = UINT16_MAX;
private:
double m_startValue = MAX_VALUE;
double m_stopValue = 1;
public:
double GetStartValue();
void SetStartValue(double value);
double GetStopValue();
void SetStopValue(double value);
std::vector<uint16_t> m_coefs;
void Update();
void ClampTo01(double& value);
UnificationCoef(int size, double start_value, double stop_value);
~UnificationCoef();
};
|
/*
Copyright (c) 2015, Vlad Mesco
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DOCUMENT_H
#define DOCUMENT_H
#include "common.h"
#include "note.h"
#include <vector>
#include <list>
#include <sstream>
#include <deque>
#include <functional>
class ICell;
enum class InsertMode_t
{
INSERT,
APPEND,
REPLACE
};
struct Staff
{
std::string name_;
char type_;
unsigned scale_;
char interpolation_;
std::vector<Note> notes_;
};
struct Document // FIXME worry about proper encapsulation later
{
Document();
// interface for renderer
int Duration();
int Position();
int Percentage();
int Max();
bool AtEnd();
struct BufferOp
{
std::function<void(void)> cut;
std::vector<decltype(Staff::notes_)> buffer;
};
BufferOp PreCutSelection();
void Copy();
void Cut();
void Paste();
void Delete();
void NewNote();
InsertMode_t InsertMode() { return insertMode_; }
void SetInsertMode(InsertMode_t im) { insertMode_ = im; }
ICell* Active() { return Cell(active_); }
void SetActive(ICell* c);
void SetActiveToMarked();
void SetMarked(ICell* c);
void SetSelected(ICell* c);
void ClearSelection();
bool GetSelectionBox(int&, int&, int&, int&);
bool IsNoteSelected(ICell* note);
bool IsNoteSelected(int staffIdx, int noteIdx);
void ScrollLeftRight(int);
void ScrollLeft(bool byPage);
void ScrollRight(bool byPage);
void UpdateCache();
void Open(std::istream&);
void Save(std::ostream&);
void InitCells();
void Scroll(size_t col);
ICell* Cell(point_t);
ICell* Cell(int x, int y) { return Cell(point_t(x, y)); }
std::string title_;
std::vector<Staff> staves_;
std::vector<ICell*> cells_;
std::vector<std::vector<int>> cache_;
int scroll_ = 0;
point_t active_ = { 0, 0 }; // screen coords
point_t marked_ = { 0, 0 }; // virtual note coords
point_t selected_ = { 0, 0 }; // virtual note coords
InsertMode_t insertMode_ = InsertMode_t::INSERT;
decltype(BufferOp::buffer) buffer_;
void PushState();
void PopState();
std::deque<std::vector<Staff>> undoStates_;
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.