text
stringlengths 8
6.88M
|
|---|
//这个题第一次看到做隔了一周
//自己那个想法虽然可行,但是不知为啥总是不想去实现
//最后还是参考了别人发现的规律
//行列的字母互换就得出了相反方向旋转的结果
//3 MS 63.84%
//这是顺时针
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int length = matrix.size();
if(length<2){
return;
}
for(int i = 0; i < length/2; ++i){ //列
for(int j = i; j<length-i-1;++j){ //行
int temp = matrix[j][i];
matrix[j][i] = matrix[length-i-1][j];
matrix[length-i-1][j] = matrix[length-j-1][length-i-1];
matrix[length-j-1][length-i-1] = matrix[i][length-j-1];
matrix[i][length-j-1] = temp;
}
}
}
};
/*
//这是逆时针旋转90°
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int length = matrix.size();
if(length<2){
return;
}
for(int i = 0; i < length/2; ++i){ //行
for(int j = i; j<length-i-1;++j){ //列
int temp = matrix[i][j];
matrix[i][j] = matrix[j][length-i-1];
matrix[j][length-i-1] = matrix[length-i-1][length-j-1];
matrix[length-i-1][length-j-1] = matrix[length-j-1][i];
matrix[length-j-1][i] = temp;
}
}
}
};
*/
|
//dfs
class Solution {
public:
string decodeString(string s, int& i) {
string res;
while (i < s.length() && s[i] != ']') {
if (!isdigit(s[i]))
res += s[i++];
else {
int n = 0;
while (i < s.length() && isdigit(s[i]))
n = n * 10 + s[i++] - '0';
i++; // '['
string t = decodeString(s, i);
i++; // ']'
while (n-- > 0)
res += t;
}
}
return res;
}
string decodeString(string s) {
int i = 0;
return decodeString(s, i);
}
};
// stupid way - stack
class Solution {
public:
string decodeString(string s) {
stack<char> stk;
for(char c: s){
if(c == ']'){
string str;
for(;;){
char ch = stk.top();
stk.pop();
if(ch == '[') break;
str += ch;
}
reverse(str.begin(), str.end());
string num;
while(!stk.empty()){
char ch = stk.top();
if(!isdigit(ch)) break;
stk.pop();
num += ch;
}
reverse(num.begin(), num.end());
int cnt = stoi(num);
for(int i = 0; i < cnt; ++i){
for(char c: str){
stk.push(c);
}
}
}else{
stk.push(c);
}
}
string res;
while(!stk.empty()){
char c = stk.top();
stk.pop();
res += c;
}
reverse(res.begin(), res.end());
return res;
}
};
|
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cin >> str;
int sum = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
if ('A' <= str[i] && str[i] <= 'C') {
sum += 3;
} else if ('D' <= str[i] && str[i] <= 'F') {
sum += 4;
} else if ('G' <= str[i] && str[i] <= 'I') {
sum += 5;
} else if ('J' <= str[i] && str[i] <= 'L') {
sum += 6;
} else if ('M' <= str[i] && str[i] <= 'O') {
sum += 7;
} else if ('P' <= str[i] && str[i] <= 'S') {
sum += 8;
} else if ('T' <= str[i] && str[i] <= 'V') {
sum += 9;
} else if ('W' <= str[i] && str[i] <= 'Z') {
sum += 10;
}
}
cout << sum;
return 0;
}
|
/*
* ·´×ªµ¥Á´±í
*/
#include <bits/stdc++.h>
struct ListNode{
ListNode *next;
int data;
ListNode(int x):data(x),next(NULL){}
};
class Solution{
public:
ListNode* list_reverse(ListNode *head){
ListNode *newHead = NULL;
while(head){
ListNode *nextNode = head->next;
head->next = newHead;
newHead = head;
head = nextNode;
}
return newHead;
}
};
int main(){
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
Solution solve;
ListNode *head = &a;
printf("Before reverse:\n");
while(head){
printf("%d\n", head->data);
head = head->next;
}
head = solve.list_reverse(&a);
printf("After reverse:\n");
while(head){
printf("%d\n", head->data);
head = head->next;
}
return 0;
}
|
#include "GameController.h"
GameController::GameController()
{
isRunning = true;
gameState = GameStates::SPLASH_SCREEN;
actualScene = new SplashScreen();
}
void GameController::GoMenu()
{
gameState = GameStates::MENU;
delete actualScene;
actualScene = new Menu();
}
void GameController::GoPlay()
{
gameState = GameStates::PLAY;
delete actualScene;
actualScene = new Play();
}
void GameController::GoRankingAfterMenu()
{
gameState = GameStates::RANKING;
delete actualScene;
actualScene = new Ranking();
}
void GameController::GoRankingAfterPlay()
{
gameState = GameStates::RANKING;
delete actualScene;
actualScene = new Ranking(newPlayerRankingInfo);
}
void GameController::Run()
{
inputs.UpdateInputs();
if (inputs.GetKey(InputKey::QUIT)) gameState = GameStates::EXIT;
switch (gameState)
{
case GameStates::SPLASH_SCREEN:
if (actualScene->state == SceneStates::MENU_SPLASH)
{
GoMenu();
}
break;
case GameStates::MENU:
if (actualScene->state == SceneStates::PLAY_MENU)
{
GoPlay();
}
if (actualScene->state == SceneStates::RANKING_MENU)
{
GoRankingAfterMenu();
}
if (actualScene->state == SceneStates::EXIT_MENU)
{
gameState = GameStates::EXIT;
}
break;
case GameStates::PLAY:
if (actualScene->state == SceneStates::GAME_OVER_PLAY)
{
newPlayerRankingInfo = actualScene->GetPlayerRankingInfo();
GoRankingAfterPlay();
}
break;
case GameStates::RANKING:
if (actualScene->state == SceneStates::BACK_RANKING)
{
GoMenu();
}
break;
case GameStates::EXIT:
isRunning = false;
break;
default:
break;
}
actualScene->Update(inputs.GetInputs(), inputs.GetMousePosition());
Draw();
}
void GameController::Draw()
{
actualScene->Draw();
}
GameController::~GameController()
{
}
|
// Copyright (c) 2020 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/init.hpp>
#include <pika/modules/async.hpp>
#include <pika/modules/threading_base.hpp>
#include <pika/testing.hpp>
#include <atomic>
#include <cstddef>
std::atomic<bool> data_deallocated(false);
struct test_data
{
test_data() = default;
~test_data() { data_deallocated = true; }
};
void test()
{
pika::threads::detail::thread_id_type id = pika::threads::detail::get_self_id();
test_data* p = new test_data;
pika::threads::detail::add_thread_exit_callback(id, [p, id]() {
pika::threads::detail::thread_id_type id1 = pika::threads::detail::get_self_id();
PIKA_TEST_EQ(id1, id);
test_data* p1 = reinterpret_cast<test_data*>(pika::threads::detail::get_thread_data(id1));
PIKA_TEST_EQ(p1, p);
delete p;
});
pika::threads::detail::set_thread_data(id, reinterpret_cast<std::size_t>(p));
}
int pika_main()
{
pika::async(&test).get();
PIKA_TEST(data_deallocated);
return pika::finalize();
}
int main(int argc, char* argv[])
{
PIKA_TEST_EQ_MSG(pika::init(pika_main, argc, argv), 0, "pika main exited with non-zero status");
return 0;
}
|
#include "sum_float_opt.h"
#define INPUT_SIZE (18*18)
#define OUTPUT_SIZE (16*16)
extern "C" {
static void read_input(int* input, hls::stream<hw_uint<32> >& v, const int size) {
for (int i = 0; i < INPUT_SIZE; i++) {
#pragma HLS pipeline II=1
v.write(input[i]);
}
}
static void write_output(int* output, hls::stream<hw_uint<32> >& v, const int size) {
for (int i = 0; i < OUTPUT_SIZE; i++) {
#pragma HLS pipeline II=1
output[i] = v.read();
}
}
void sum_float_opt_accel(int* f_update_0_read_arg, int* u_update_0_read_arg, int* sum_float_update_0_write_arg, const int size) {
#pragma HLS dataflow
#pragma HLS INTERFACE m_axi port = f_update_0_read offset = slave bundle = gmem
#pragma HLS INTERFACE m_axi port = u_update_0_read offset = slave bundle = gmem
#pragma HLS INTERFACE m_axi port = sum_float_update_0_write offset = slave bundle = gmem
#pragma HLS INTERFACE s_axilite port = f_update_0_read bundle = control
#pragma HLS INTERFACE s_axilite port = u_update_0_read bundle = control
#pragma HLS INTERFACE s_axilite port = sum_float_update_0_write bundle = control
#pragma HLS INTERFACE s_axilite port = size bundle = control
#pragma HLS INTERFACE s_axilite port = return bundle = control
static hls::stream<hw_uint<32> > f_off_chip;
static hls::stream<hw_uint<32> > u_off_chip;
static hls::stream<hw_uint<32> > sum_float;
read_input(f_off_chip_arg, f_off_chip, size);
read_input(u_off_chip_arg, u_off_chip, size);
sum_float_opt(f_off_chip, u_off_chip, sum_float);
write_output(sum_float_arg, sum_float, size);
}
}
|
//伸展树
#include<stdio.h>
#include<algorithm>
#define MAXN 100010
#define MAXM 100010
#define Type int
using namespace std;
struct splayTree{
int size,root; // 树的大小和根的编号
int s[MAXN],left[MAXN],right[MAXN]; //儿子个数,左儿子,右儿子
Type data[MAXN]; //节点的值
splayTree () { s[0]=left[0]=right[0]=size=0; root=0; }
/*
void leftrotate(int &);
void rightrotate(int &);
int splay(int &,int );
void insert(int &,int ,Type &w);
Type Delete(int &,Type &);
Type find_th(int &,Type &)
*/
void leftrotate(int &x) //左旋转
{
int y=right[x];
right[x]=left[y];
left[y]=x;
s[y]=s[x];
s[x]=s[left[x]]+s[right[x]]+1;
x=y;
}
void rightrotate(int &x) //右旋转
{
int y=left[x];
left[x]=right[y];
right[y]=x;
s[y]=s[x];
s[x]=s[left[x]]+s[right[x]]+1;
x=y;
}
int splay(int &x,int kth) //核心部分 返回第kth个值,并且把它旋转到根
{
int y,z;
if (s[left[x]]+1==kth) return x;
if (kth<=s[left[x]]){
y=left[x];
if (kth==s[left[y]]+1) return rightrotate(x),y;
if (kth<=s[left[y]]) {
z=splay(left[y],kth);
rightrotate(left[x]);
rightrotate(x);
return z;
}else {
z=splay(right[y],kth-s[y]-1);
leftrotate(left[x]);
rightrotate(x);
return z;
}
} else {
y=right[x];
kth=kth-s[left[x]]-1;
if (kth==s[left[y]]+1) return leftrotate(x),y;
if (kth<=s[left[y]]) {
z=splay(left[y],kth);
rightrotate(right[x]);
leftrotate(x);
return z;
} else {
z=splay(right[y],kth-s[left[y]-1]);
leftrotate(right[x]);
leftrotate(x);
return z;
}
}
}
void insert(int &x,int kth,Type &w) //插入w,并且得到w的位置,然后把w转到根处
{
if (x==0){
x=++size;
data[x]=w;
left[x]=right[x]=0;
s[x]=1;
splay(root,kth+1);
} else {
++s[x];
if (w<data[x]) insert(left[x],kth,w);
else insert(right[x],kth+s[left[x]]+1,w);
}
}
Type Delete(int &x,Type &w) //删除w,借鉴sbt的删除方法
{
--s[x];
if (data[x]==w||w<data[x]&&left[x]==0||w>data[x]&&right[x]==0)
{
Type tmp=data[x];
if (left[x]==0||right[x]==0)
x=left[x]+right[x];
else data[x]=Delete(left[x],data[x]);
return tmp;
}else if (w<data[x]) return Delete(left[x],w);
else return Delete(right[x],w);
}
Type find_th(int &x,int w) //找出w排第几
{
if (s[left[x]]+1==w) return data[x];
else if (w<data[x]) return find_th(left[x],w);
else return find_th(right[x],w-s[left[x]]-1);
}
};
//以上为splay树的主要部分
struct interval{
int x,y,z,num;
};
int root=0,n,m,i,l,r,j;
int abl[MAXN];
interval itr[MAXM];
int ans[MAXM];
bool cmp(const interval &p1,const interval &p2)
{ return p1.x<p2.x; }
inline int max(int x,int y) { return x>y?x:y;}
inline int min(int x,int y) { return x<y?x:y;}
int main()
{
freopen("zoo.in","r",stdin);
freopen("zoo.out","w",stdout);
splayTree zoo;
int i,j;
scanf("%d%d",&n,&m);
for( i=0;i<n;++i) scanf("%d",&abl[i+1]);
for( i=0;i!=m;++i) scanf("%d%d%d",&itr[i].x,&itr[i].y,&itr[i].z),itr[i].num=i;
sort(itr,itr+m,cmp);
for ( i=itr[0].x;i<=itr[0].y;++i)
zoo.insert(zoo.root,0,abl[i]);
for ( i=1;i<m;++i)
{
ans[itr[i-1].num]=zoo.find_th(zoo.root,itr[i-1].z);
for ( j=itr[i-1].x;j<=min(itr[i-1].y,itr[i].x-1);++j)
zoo.Delete(zoo.root,abl[j]);
for ( j=max(itr[i-1].y+1,itr[i].x);j<=itr[i].y;++j)
zoo.insert(zoo.root,0,abl[j]);
}
ans[itr[m-1].num]=zoo.find_th(zoo.root,itr[m-1].z);
for ( i=0;i<m;++i)
printf("%d\n",ans[i]);
return 0;
}
|
#define pii pair<int,int>
vector<vector<pii>> dp;
pii memo(const vector<int> &a,int sum,int i) {
if(i == 0) return {sum,0};
if(dp[sum][i].first != -1) return dp[sum][i];
if(sum-(2*a[i-1])>=0) {
// return <sum,items>
pii l,r;
l = memo(a,sum-(2*a[i-1]),i-1);
r = memo(a,sum,i-1);
if(l.first<r.first) {
//l wins
return dp[sum][i] = {l.first,1+l.second};
}
else if(l.first>r.first) {
//r wins
return dp[sum][i] = r;
}
else {
if(l.second+1<=r.second) {
// l wins
return dp[sum][i] = {l.first,1+l.second};
}
else {
// r wins
return dp[sum][i] = r;
}
}
}
else {
return dp[sum][i] = memo(a,sum,i-1);
}
}
int Solution::solve(const vector<int> &a) {
int sum = 0;
for(int i : a) {
sum += i;
}
dp.assign(sum+1,vector<pii>(a.size()+1,{-1,-1}));
return memo(a,sum,a.size()).second;
}
|
/*
a class used to compute the polygon infomation.
*/
#ifndef H_POLYGONACTION_H
#define H_POLYGONACTION_H
#include "Polygon.h"
#include "math_3d.h"
#include "Math_basics.h"
namespace P_RVD
{
class PolygonAction
{
public:
PolygonAction(Polygon* _p)
{
m_polygon = _p;
weight_sum = 0.0;
}
PolygonAction(){
m_polygon = NULL;
weight_sum = 0.0;
}
/*
get the computing Polygon
*/
Polygon* getPolygon()
{
return m_polygon;
}
/*
clear the PolygonAction to get prepared for the next action.
*/
void clear()
{
m_polygon = NULL;
weight_sum = 0.0;
m_vertex.clear();
vertex_nb = m_vertex.size();
current_weight = 0.0;
current_posTimesWeight = Vector3d(0.0, 0.0, 0.0);
}
/*
set the computing
*/
void setPolygon(Polygon* _p)
{
m_polygon = _p;
vertex_nb = m_polygon->getVertex_nb();
for (int i = 0; i < vertex_nb; ++i)
{
m_vertex.push_back(m_polygon->getVertex(i));
}
}
/*
compute the total weight and centriod times weight
*/
void compute_centriod();
/*
compute the weight of the m_polygon
*/
double compute_weight();
/*
compute the area of the m_polygin
*/
double compute_area();
/*
compute the center of the m_polygon
*/
Vector3d compute_center();
/*
compute a triangle's area by index
_v1, _v2, _v3 represent the indices of m_vertex
*/
double compute_triangle_arae(t_index _v1, t_index _v2, t_index _v3);
/*
get the current_position
*/
Vector3d getCurrentPosition(){ return current_posTimesWeight; }
/*
get the current weight
*/
double getCurrentWeight(){ return current_weight; }
protected:
Polygon* m_polygon;
std::vector<Vertex> m_vertex;
Vertex p;
int vertex_nb;
Vector3d current_posTimesWeight;
double current_weight;
double weight_sum;
};
}
#endif /* H_POLYGONACTION_H */
|
#include "DBManager.hh"
#include "Encounter.hh"
#include "EncounterTemplate.hh"
#include "Unit.hh"
namespace HotaSim {
using namespace std;
using namespace CCC;
Encounter::Encounter(const EncounterTemplate& _tmpl)
: TemplateObject(_tmpl) {
for( const auto& u : tmpl.units ) {
auto unit = tmpl.dbmgr->createObject<Unit>(u.unit_id);
unit->setStack(u.amount);
units.emplace_back(unit);
}
}
SPtrVec<Unit> Encounter::getUnits() const noexcept { return units; }
}
|
//
// HolyHandGrenade.cpp for cpp_indie_studio in /home/lopez_i/cpp_indie_studio/HolyHandGrenade.cpp
//
// Made by Loïc Lopez
// Login <loic.lopez@epitech.eu>
//
// Started on ven. juin 16 10:35:53 2017 Loïc Lopez
// Last update Sun Jun 18 19:54:31 2017 Stanislas Deneubourg
//
#include <iostream>
#include "Worms/HolyHandGrenade.hpp"
HolyHandGrenade::HolyHandGrenade(irr::IrrlichtDevice *device, irrklang::ISoundEngine *soundEngine)
{
this->device = device;
this->soundEngine = soundEngine;
this->chargerNumber = 1;
this->maxSpeedX = 0.2f;
this->actualSpeedX = this->maxSpeedX;
this->maxSpeedY = 0.2f;
this->actualSpeedY = this->maxSpeedY;
this->actualLeftSpeedX = -(this->maxSpeedX);
this->actualLeftSpeedY = -(this->maxSpeedY);
this->updateReverseConstraints = false;
this->updateZeroConstraints = false;
this->throwLeft = false;
this->throwRight = false;
}
HolyHandGrenade::~HolyHandGrenade()
{
}
bool HolyHandGrenade::fire()
{
if (this->chargerNumber > 0)
{
if (this->holyHandGrenadeSceneNode != nullptr)
{
this->chargerNumber--;
if (this->holyHandGrenadeSceneNode->getRotation().Y == 90.0f)
this->throwRight = true;
else
this->throwLeft = true;
return (true);
}
}
return (false);
}
void HolyHandGrenade::showWeapon(const irr::core::vector3df &position, const irr::core::vector3df &rotation)
{
this->holyHandGrenadeSceneNode = this->device->getSceneManager()->addMeshSceneNode
(this->device->getSceneManager()->getMesh("ressources/weapons/HolyHandGrenade/HolyHandGrenade.obj"));
this->holyHandGrenadeSceneNode->setMaterialFlag(irr::video::EMF_LIGHTING, false);
this->holyHandGrenadeSceneNode->setMaterialFlag(irr::video::EMF_NORMALIZE_NORMALS, false);
this->setWeaponRotation(rotation);
this->setWeaponPosition(position);
this->holyHandGrenadeSceneNode->setScale(irr::core::vector3df(0.5, 0.5, 0.5));
this->holyHandGrenadeBox = this->holyHandGrenadeSceneNode->getBoundingBox();
}
void HolyHandGrenade::deleteWeapon()
{
this->holyHandGrenadeSceneNode->getParent()->removeChild(this->holyHandGrenadeSceneNode);
}
void HolyHandGrenade::setWeaponPosition(const irr::core::vector3df &position)
{
irr::f32 yRotation = this->holyHandGrenadeSceneNode->getRotation().Y;
if (yRotation == 90.0f)
this->holyHandGrenadeSceneNode->setPosition(
irr::core::vector3df(position.X + this->holyHandGrenadeBox.getExtent().getLength() / 6,
position.Y + this->holyHandGrenadeBox.getExtent().getLength() / 2,
position.Z - this->holyHandGrenadeBox.getExtent().getLength() / 6));
else if (yRotation == -90.0f)
this->holyHandGrenadeSceneNode->setPosition(
irr::core::vector3df(position.X - this->holyHandGrenadeBox.getExtent().getLength() / 6,
position.Y + this->holyHandGrenadeBox.getExtent().getLength() / 2,
position.Z - this->holyHandGrenadeBox.getExtent().getLength() / 6));
this->startGrenadeX = this->holyHandGrenadeSceneNode->getPosition().X;
}
void HolyHandGrenade::setWeaponRotation(const irr::core::vector3df &rotation)
{
this->holyHandGrenadeSceneNode->setRotation(irr::core::vector3df(rotation.X, -rotation.Y, rotation.Z));
}
bool HolyHandGrenade::updateBullets()
{
return true;
}
bool HolyHandGrenade::updateBullets(std::vector<irr::scene::IMeshSceneNode *> groundObjects)
{
irr::core::vector3df grenadePos = this->holyHandGrenadeSceneNode->getPosition();
int collision = 0;
irr::f32 collisionPos = 0;
if (this->throwRight == true)
{
// SI ON LANCE VERS LA DROITE
if (this->updateZeroConstraints == false)
{
//COLLISION GAUCHE
for (unsigned int i = 0; i < groundObjects.size(); i++)
{
if ((this->holyHandGrenadeSceneNode->getPosition().Y >= groundObjects.at(i)->getPosition().Y - 2.5f)
&& (this->holyHandGrenadeSceneNode->getPosition().Y <= groundObjects.at(i)->getPosition().Y + 2.5f)
&& (this->holyHandGrenadeSceneNode->getPosition().X <= groundObjects.at(i)->getPosition().X + 3.35f)
&& (this->holyHandGrenadeSceneNode->getPosition().X >= groundObjects.at(i)->getPosition().X + 3.25f))
{
collision = 1;
collisionPos = groundObjects.at(i)->getPosition().X + 3.4f;
}
}
if (collision == 1)
{
this->holyHandGrenadeSceneNode->setPosition
(irr::core::vector3d<irr::f32>(collisionPos,
this->holyHandGrenadeSceneNode->getPosition().Y,
this->holyHandGrenadeSceneNode->getPosition().Z));
}
collision = 0;
collisionPos = 0;
//COLLISION DROITE
for (unsigned int i = 0; i < groundObjects.size(); i++)
{
if ((this->holyHandGrenadeSceneNode->getPosition().Y >= groundObjects.at(i)->getPosition().Y - 2.5f)
&& (this->holyHandGrenadeSceneNode->getPosition().Y <= groundObjects.at(i)->getPosition().Y + 2.5f)
&& (this->holyHandGrenadeSceneNode->getPosition().X >= groundObjects.at(i)->getPosition().X - 3.35f)
&& (this->holyHandGrenadeSceneNode->getPosition().X <= groundObjects.at(i)->getPosition().X - 3.25f))
{
collision = 1;
collisionPos = groundObjects.at(i)->getPosition().X - 3.4f;
}
}
if (collision == 1)
{
this->holyHandGrenadeSceneNode->setPosition
(irr::core::vector3d<irr::f32>(collisionPos,
this->holyHandGrenadeSceneNode->getPosition().Y,
this->holyHandGrenadeSceneNode->getPosition().Z));
}
collision = 0;
collisionPos = 0;
//BALLISTIQUE
if (this->actualSpeedY > 0.0f && this->updateReverseConstraints == false)
{
grenadePos.X += this->actualSpeedX;
grenadePos.Y += this->actualSpeedY;
this->holyHandGrenadeSceneNode->setPosition(grenadePos);
this->actualSpeedX -= 0.001f;
this->actualSpeedY -= 0.001f;
}
if (this->actualSpeedY <= 0.0f && this->updateReverseConstraints == false)
{
this->actualSpeedY = 0.0f;
this->updateReverseConstraints = true;
}
if (this->actualSpeedY < this->maxSpeedY && this->updateReverseConstraints == true)
{
grenadePos.X -= this->actualSpeedX;
grenadePos.Y -= this->actualSpeedY;
this->holyHandGrenadeSceneNode->setPosition(grenadePos);
this->actualSpeedX -= 0.001f;
this->actualSpeedY += 0.001f;
}
if (this->actualSpeedY >= this->maxSpeedY)
{
this->actualSpeedY = this->maxSpeedY;
this->actualSpeedX = this->maxSpeedX;
this->updateZeroConstraints = true;
}
}
else
{
for (unsigned int i = 0; i < groundObjects.size(); i++)
{
if ((this->holyHandGrenadeSceneNode->getPosition().Y <= groundObjects.at(i)->getPosition().Y + 0.9)
&& (this->holyHandGrenadeSceneNode->getPosition().Y >= groundObjects.at(i)->getPosition().Y + 0.7)
&& (this->holyHandGrenadeSceneNode->getPosition().X >= groundObjects.at(i)->getPosition().X - 3.0)
&& (this->holyHandGrenadeSceneNode->getPosition().X <= groundObjects.at(i)->getPosition().X + 3.0))
collision = 1;
}
if (collision == 0)
{
this->holyHandGrenadeSceneNode->setPosition
(irr::core::vector3d<irr::f32>(this->holyHandGrenadeSceneNode->getPosition().X,
this->holyHandGrenadeSceneNode->getPosition().Y - 0.1f,
this->holyHandGrenadeSceneNode->getPosition().Z));
}
if (collision == 1)
{
this->updateZeroConstraints = false;
this->updateReverseConstraints = false;
this->throwRight = false;
this->soundEngine->play2D("ressources/sounds/holygrenade.wav");
return false;
}
}
}
else if (this->throwLeft == true)
{
// SI ON LANCE VERS LA GAUCHE
if (this->updateZeroConstraints == false)
{
//COLLISION GAUCHE
for (unsigned int i = 0; i < groundObjects.size(); i++)
{
if ((this->holyHandGrenadeSceneNode->getPosition().Y >= groundObjects.at(i)->getPosition().Y - 0.7f)
&& (this->holyHandGrenadeSceneNode->getPosition().Y <= groundObjects.at(i)->getPosition().Y + 0.7f)
&& (this->holyHandGrenadeSceneNode->getPosition().X <= groundObjects.at(i)->getPosition().X + 3.35f)
&& (this->holyHandGrenadeSceneNode->getPosition().X >= groundObjects.at(i)->getPosition().X + 3.25f))
{
collision = 1;
collisionPos = groundObjects.at(i)->getPosition().X + 3.4f;
}
}
if (collision == 1)
{
this->holyHandGrenadeSceneNode->setPosition
(irr::core::vector3d<irr::f32>(collisionPos,
this->holyHandGrenadeSceneNode->getPosition().Y,
this->holyHandGrenadeSceneNode->getPosition().Z));
}
collision = 0;
collisionPos = 0;
//COLLISION DROITE
for (unsigned int i = 0; i < groundObjects.size(); i++)
{
if ((this->holyHandGrenadeSceneNode->getPosition().Y >= groundObjects.at(i)->getPosition().Y - 0.7f)
&& (this->holyHandGrenadeSceneNode->getPosition().Y <= groundObjects.at(i)->getPosition().Y + 0.7f)
&& (this->holyHandGrenadeSceneNode->getPosition().X >= groundObjects.at(i)->getPosition().X - 3.35f)
&& (this->holyHandGrenadeSceneNode->getPosition().X <= groundObjects.at(i)->getPosition().X - 3.25f))
{
collision = 1;
collisionPos = groundObjects.at(i)->getPosition().X - 3.4f;
}
}
if (collision == 1)
{
this->holyHandGrenadeSceneNode->setPosition
(irr::core::vector3d<irr::f32>(collisionPos,
this->holyHandGrenadeSceneNode->getPosition().Y,
this->holyHandGrenadeSceneNode->getPosition().Z));
}
collision = 0;
collisionPos = 0;
//BALLISTIQUE
if (this->actualSpeedY > 0.0f && this->updateReverseConstraints == false)
{
grenadePos.X += this->actualSpeedX;
grenadePos.Y -= this->actualSpeedY;
this->holyHandGrenadeSceneNode->setPosition(grenadePos);
this->actualSpeedX -= 0.001f;
this->actualSpeedY -= 0.001f;
}
if (this->actualSpeedY <= 0.0f && this->updateReverseConstraints == false)
{
this->actualSpeedY = 0.0f;
this->updateReverseConstraints = true;
}
if (this->actualSpeedY < this->maxSpeedY && this->updateReverseConstraints == true)
{
grenadePos.X -= this->actualSpeedX;
grenadePos.Y += this->actualSpeedY;
this->holyHandGrenadeSceneNode->setPosition(grenadePos);
this->actualSpeedX -= 0.001f;
this->actualSpeedY -= 0.001f;
}
if (this->actualSpeedY >= this->maxSpeedY)
{
this->actualSpeedY = this->maxSpeedY;
this->actualSpeedX = this->maxSpeedX;
this->updateZeroConstraints = true;
}
}
else
{
for (unsigned int i = 0; i < groundObjects.size(); i++)
{
if ((this->holyHandGrenadeSceneNode->getPosition().Y <= groundObjects.at(i)->getPosition().Y + 0.9)
&& (this->holyHandGrenadeSceneNode->getPosition().Y >= groundObjects.at(i)->getPosition().Y + 0.7)
&& (this->holyHandGrenadeSceneNode->getPosition().X >= groundObjects.at(i)->getPosition().X - 3.0)
&& (this->holyHandGrenadeSceneNode->getPosition().X <= groundObjects.at(i)->getPosition().X + 3.0))
collision = 1;
}
if (collision == 0)
{
this->holyHandGrenadeSceneNode->setPosition
(irr::core::vector3d<irr::f32>(this->holyHandGrenadeSceneNode->getPosition().X,
this->holyHandGrenadeSceneNode->getPosition().Y - 0.1f,
this->holyHandGrenadeSceneNode->getPosition().Z));
}
if (collision == 1)
{
this->updateZeroConstraints = false;
this->updateReverseConstraints = false;
this->throwLeft = false;
this->soundEngine->play2D("ressources/sounds/holygrenade.wav");
return (false);
}
}
}
return true;
}
irr::core::vector3df const &HolyHandGrenade::getWeaponRotation() const
{
return this->holyHandGrenadeSceneNode->getRotation();
}
|
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string str1;
cin >> str1;
int count = 0;
for(int i = 0; i < str1.size(); i++)
{
if(str1[i] == 'a' || str1[i] == 'e' ||str1[i] == 'i' || str1[i] == 'o' ||str1[i] == 'u')
{
count++;
}
}
cout << "Vowels are:" << count;
return 0;
}
|
//use array to store
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int n = s.length();
int counts[26] = {0};
for (int i = 0; i < n; i++) {
counts[s[i] - 'a']++;
counts[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++)
if (counts[i]) return false;
return true;
}
};
//use hashmap, slower
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;
unordered_map<char, int> mp;
int n = s.size();
for(int i = 0; i < n; ++i){
++mp[s[i]];
--mp[t[i]];
}
for(auto item: mp){
if(item.second) return false;
}
return true;
}
};
|
#include "Conjunto.h"
template <class T>
Conjunto<T>::Conjunto() {
_raiz = NULL;
}
template <class T>
void Conjunto<T>::vaciar(Conjunto<T>::Nodo *a) {
if(a != NULL){
vaciar(a->izq);
vaciar(a->der);
a->izq = NULL;
a->der = NULL;
delete a;
}
}
template <class T>
Conjunto<T>::~Conjunto() {
vaciar(_raiz);
}
template <class T>
bool Conjunto<T>::perteneceAux(const T &clave, Conjunto<T>::Nodo *a) const {
if(a == NULL){
return false;
} else {
if(a->valor == clave) {
return true;
} else if(clave > a->valor){
return perteneceAux(clave, a->der);
} else {
return perteneceAux(clave, a->izq);
}
}
}
template <class T>
bool Conjunto<T>::pertenece(const T& clave) const {
return perteneceAux(clave, _raiz);
}
template <class T>
void Conjunto<T>::insertarAux(const T& clave, Conjunto<T>::Nodo *a) {
if(clave > a->valor){
if(a->der == NULL){
Nodo* nuevo = new Nodo(clave);
a->der = nuevo;
} else {
return insertarAux(clave, a->der);
}
} else if (clave < a->valor){
if(a->izq == NULL) {
Nodo* nuevo = new Nodo(clave);
a->izq = nuevo;
} else {
return insertarAux(clave, a->izq);
}
}
}
template <class T>
void Conjunto<T>::insertar(const T& clave) {
if(_raiz == NULL) {
Nodo* nuevo = new Nodo(clave);
_raiz = nuevo;
} else {
insertarAux(clave, _raiz);
}
}
template <class T>
void Conjunto<T>::removerAux(const T& clave, Conjunto<T>::Nodo *a, Conjunto<T>::Nodo* anterior) {
if(a != NULL){
if(clave > a->valor && a->der != NULL) {
removerAux(clave, a->der, a);
} else if(clave < a->valor && a->izq != NULL){
removerAux(clave, a->izq, a);
} else {
if(a->izq == NULL && a->der != NULL) {
if(anterior == a) {
_raiz = a->der;
} else if(anterior->der == a) {
anterior->der = a->der;
} else {
anterior->izq = a->der;
}
a->der = NULL;
a->izq = NULL;
delete a;
} else if (a->izq != NULL && a->der == NULL) {
if (anterior == a){
_raiz = a->izq;
} else if(anterior->der == a){
anterior->der = a->izq;
} else {
anterior->izq = a->izq;
}
a->der = NULL;
a->izq = NULL;
delete a;
} else if (a->izq != NULL && a->der != NULL){
Nodo* reemplazante = a->der;
Nodo* antReemplazante;
if(reemplazante->izq == NULL) {
reemplazante->izq = a->izq;
} else {
while(reemplazante->izq != NULL) {
antReemplazante = reemplazante;
reemplazante = reemplazante->izq;
}
antReemplazante->izq = reemplazante->der;
reemplazante->izq = a->izq;
reemplazante->der = a->der;
}
if(anterior == a) {
_raiz = reemplazante;
} else if(anterior->der == a){
anterior->der = reemplazante;
} else {
anterior->izq = reemplazante;
}
a->der = NULL;
a->izq = NULL;
delete a;
} else if (a->izq == NULL && a->der == NULL) {
if(anterior == a) {
a->der = NULL;
a->izq = NULL;
delete a;
_raiz = NULL;
} else if(anterior->der == a){
a->der = NULL;
a->izq = NULL;
delete a;
anterior->der = NULL;
} else {
a->der = NULL;
a->izq = NULL;
delete a;
anterior->izq = NULL;
}
}
}
}
}
template <class T>
void Conjunto<T>::remover(const T& clave) {
if (_raiz != NULL) {
removerAux(clave, _raiz, _raiz);
}
}
template <class T>
const T& Conjunto<T>::siguiente(const T& clave) {
Nodo* actual = _raiz;
Nodo* anterior;
while(actual->valor != clave) {
anterior = actual;
if(clave > actual->valor) {
actual = actual->der;
} else {
actual = actual->izq;
}
}
if(actual->der == NULL) {
return anterior->valor;
} else {
actual = actual->der;
while (actual->izq != NULL) {
actual = actual->izq;
}
return actual->valor;
}
}
template <class T>
const T& Conjunto<T>::minimo() const {
Nodo* actual = _raiz;
while (actual->izq != NULL) {
actual = actual->izq;
}
return actual->valor;
}
template <class T>
const T& Conjunto<T>::maximo() const {
Nodo* actual = _raiz;
while (actual->der != NULL) {
actual = actual->der;
}
return actual->valor;
}
template <class T>
unsigned int Conjunto<T>::cardinalAux(Conjunto<T>::Nodo* a) const{
if(a->der != NULL && a->izq != NULL) {
return 1 + cardinalAux(a->izq) + cardinalAux(a->der);
} else if(a->der == NULL && a->izq != NULL) {
return 1 + cardinalAux(a->izq);
} else if(a->der != NULL && a->izq == NULL) {
return 1 + cardinalAux(a->der);
} else {
return 1;
}
}
template <class T>
unsigned int Conjunto<T>::cardinal() const {
if(_raiz == NULL) {
return 0;
} else {
return cardinalAux(_raiz);
}
}
template <class T>
void Conjunto<T>::mostrar(std::ostream&) const {
assert(false);
}
|
//
// Created by manout on 18-3-23.
//
#include <cmath>
static int count = 0;
__always_inline
int mypow(int n)
{
return static_cast<int>(std::pow(2, n));
}
static int coin(int n, int k, int sum)
{
int pow = mypow(k);
if (sum + pow == n)
{
++count;
}
if (sum + pow < n)
{
coin(n, k + 1, sum);
coin(n, k + 1, sum + pow);
if (sum + 2 * pow < n)
{
coin(n, k + 1, sum + 2 * pow);
}
}
}
int count_coin(int n)
{
count = 0;
coin(n, 0, 0);
return count;
}
|
#ifndef _SERVER_UTILS_HH_
#define _SERVER_UTILS_HH_
#include <stdint.h>
#include <time.h>
#include <string>
uint64_t utime();
time_t utime_seconds(uint64_t t);
std::string format_time(time_t t);
std::string pexec(std::string cmdline);
void stress(double duration, int num_processes);
#endif
|
#ifndef NOTGATE_H
#define NOTGATE_H
#include <agenda.h>
extern Agenda agenda;
class NotGate : public WireListner {
private:
Wire *in;
Wire *out;
unsigned long long delay;
public :
NotGate(Wire *in, Wire *out) {
this->in = in;
this->out = out;
delay = 1;
in->addListner(this);
agenda.addObject(this);
}
virtual void stateChanged() {
if (in->get())
agenda.insert(out, delay, (void*)0);
else
agenda.insert(out, delay, (void*)1);
}
};
class TwoInputGate : public WireListner {
public :
Wire *in1;
Wire *in2;
Wire *out;
int delay;
private :
virtual int calculateOutput() = 0;
public :
TwoInputGate(Wire *w1, Wire *w2, Wire *out):
in1(w1), in2(w2), out(out) {
agenda.addObject(this);
}
virtual void stateChanged() {
bool newValue = calculateOutput();
agenda.insert(out, delay, (void*)newValue);
}
};
class AndGate : public TwoInputGate {
private :
virtual int calculateOutput() {
return (in1->get() && in2->get()) ? 1 : 0;
}
public :
AndGate(Wire *in1, Wire *in2, Wire *out) :
TwoInputGate(in1, in2, out) {}
};
class OrGate : public TwoInputGate {
private :
virtual int calculateOutput() {
return (in1->get() || in2->get()) ? 1 : 0;
}
public :
OrGate(Wire *i1, Wire *i2, Wire *out) :
TwoInputGate(i1, i2, out) {}
};
class XorGate : public TwoInputGate {
private :
virtual int calculateOutput() {
int value = ((in1->get() && in2->get()) ||
(!in1->get() && !in2->get())) ? 0 : 1;
return value;
}
public :
XorGate(Wire *i1, Wire *i2, Wire *out) :
TwoInputGate(i1, i2, out) {}
};
class NandGate : public TwoInputGate {
private :
virtual int calculateOutput() {
return (in1->get() && in2->get()) ? 0 : 1;
}
public :
NandGate(Wire *i1, Wire *i2, Wire *out) :
TwoInputGate(i1, i2, out) {}
};
#endif
|
#include <iostream>
#include <armadillo>
#include <cmath>
#include <vector>
#include "Body.h"
#include "Universe.h"
#include "../../lib/lib.h"
using namespace arma;
using namespace std;
int main(int argc, char *argv[]) {
bool useVerlet = true;
double mass = 1;
double h = 0.0001;
double t_max = 15;
int N = 2;
bool check_for_ejections = (bool) 0;
Universe mysystem;
mysystem.G = 1;
double vx, vy, vz;
vx = vy = vz = 0;
vy = -0.1;
double x = 0;
double y = 0;
double z = 0;
Body b = Body(mass, x, y, z, vx, vy, vz);
mysystem.add_body(b);
vx = vy = vz = 0;
vy = 0.1;
x = 5;
y = 0;
z = 0;
b = Body(mass, x, y, z, vx, vy, vz);
mysystem.add_body(b);
double E0 = mysystem.energy();
mysystem.solve_Verlet(h, t_max, true);
double E1 = mysystem.energy();
cout << "E0 = " << E0 << ", E1 = " << E1 << ", Delta E = " << E1-E0 << ", rel. err. = " << (E1-E0)/E0 << endl;
}
|
#include <iostream>
#include <vector>
#include <bitset>
#include <cmath>
using namespace std;
static const size_t INT_SIZE = sizeof(int) * 8;
static const size_t LONG_SIZE = sizeof(unsigned long) * 8;
class binNum{
public:
binNum(int num){
num_ = num;
}
bool getbit(size_t i){
return num_ & (1 << i);
}
int getNum(){
return num_;
}
private:
int num_;
};
unsigned long lostNum(vector<binNum>& nums, size_t i, bitset<LONG_SIZE> b){
if(nums.empty() || i == INT_SIZE){
return b.to_ulong();
}
int countOne = 0;
int countZero = 0;
for(binNum num: nums){
if(num.getbit(i)){
countOne++;
}else{
countZero++;
}
}
bool isOneAns = countOne < countZero ? true : false;
if(isOneAns){
b.set(i);
}
for(auto it = nums.begin(); it != nums.end(); ){
if(it->getbit(i) && !isOneAns){
nums.erase(it);
}else if(!it->getbit(i) && isOneAns){
nums.erase(it);
}else{
it++;
}
}
return lostNum(nums, i + 1, b);
}
unsigned long lostNum(vector<binNum>& nums){
bitset<LONG_SIZE> b;
return lostNum(nums, 0, b);
}
// うまくいかなかった
unsigned long lostNum2(const vector<binNum>& nums){
vector<int> countOne(INT_SIZE, 0);
for(binNum num: nums){
// cout << "num is " << num.getNum() << endl;
for(int i=0; i<INT_SIZE; i++){
if(num.getbit(i)){
// cout << "i = " << i << ", countOne[i] = " << countOne[i] << endl;
countOne[i]++;
}
}
}
size_t size = nums.size();
bitset<LONG_SIZE> b;
for(int i=0; countOne[i] > 0; i++){
int cycle = size / pow(2, i+1);
// この部分にミスあり
if(countOne[i] != cycle * pow(2, i) + max(0, cycle % (int)pow(2, i))){
// cout << i << endl;
b.set(i);
}
}
return b.to_ulong();
}
int main(void){
vector<binNum> nums = {0, 1, 2, 3, 4, 5, 7, 8, 9, 10};
cout << lostNum(nums) << endl; // 6
nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
cout << lostNum(nums) << endl; // 0
nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16};
cout << lostNum(nums) << endl; // 15
nums = {0, 1, 2, 3, 4, 5, 7, 8, 9, 10};
cout << lostNum2(nums) << endl; // 6
return 0;
}
|
#pragma once
#include <tchar.h>
#include <windows.h>
class Logger
{
public:
Logger(const TCHAR *FileName);
int Write(const TCHAR * Format, ...);
private:
TCHAR m_fileName[MAX_PATH];
Logger(const Logger&);
Logger & operator=(Logger &);
};
|
/*
Copyright 2022 University of Manchester
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.
*/
#pragma once
#include <utility>
#include <vector>
#include "scheduled_module.hpp"
using orkhestrafs::dbmstodspi::ScheduledModule;
namespace orkhestrafs::dbmstodspi {
/**
* @brief Class containing helper methods for configuration differences
* handling.
*/
class BitstreamConfigHelper {
public:
static auto GetResultingConfig(
const std::vector<ScheduledModule>& previous_configuration,
const std::vector<ScheduledModule>& reduced_current_config,
const std::vector<ScheduledModule>& reduced_next_config)
-> std::vector<ScheduledModule>;
static auto GetConfigCompliments(
const std::vector<ScheduledModule>& current_run,
const std::vector<ScheduledModule>& previous_configuration)
-> std::pair<std::vector<ScheduledModule>, std::vector<ScheduledModule>>;
static auto GetOldNonOverlappingModules(
const std::vector<ScheduledModule>& current_run,
const std::vector<ScheduledModule>& previous_configuration)
-> std::vector<ScheduledModule>;
};
} // namespace orkhestrafs::dbmstodspi
|
#ifndef AS64_GMP_H_
#define AS64_GMP_H_
// GMP class
// Generalized movement primitive.
//
#include <gmp_lib/WSoG/WSoG.h>
#include <gmp_lib/utils.h>
#include <gmp_lib/io/file_io.h>
namespace as64_
{
namespace gmp_
{
class GMP
{
// ===================================
// ======= Public Functions ========
// ===================================
public:
/* GMP constructor.
* @param[in] N_kernels: number of kernels
* @param[in] D: damping.
* @param[in] K: stiffness.
* @param[in] kernels_std_scaling: Scaling for std of kernels (optional, default=1).
*/
GMP(unsigned N_kernels, double D, double K, double kernels_std_scaling=1.0);
/* Trains the GMP.
* @param[in] train_method: the training method to use, as a string ('LWR', 'LS').
* @param[in] Time: Row vector with the timestamps of the training data points.
* @param[in] yd_data: Row vector with the desired position.
* @param[out] train_error: The training error expressed as the mse error.
*/
void train(const std::string &train_method, const arma::rowvec &Time, const arma::rowvec &yd_data, double *train_error=0);
void setStiffness(double K_) { this->K = K_; }
void setDamping(double D_) { this->D = D_; }
/* Returns the derivatives of the GMP states.
* @param[in] s: phase variable state, see @Phase.
* @param[in] y: 'y' state of the GMP.
* @param[in] z: 'z' state of the GMP.
* @param[in] y_c: coupling term for the dynamical equation of the 'y' state (optional, default=0).
* @param[in] z_c: coupling term for the dynamical equation of the 'z' state (optional, default=0).
*/
void update(const gmp_::Phase &s, double y, double z, double y_c=0, double z_c=0);
/* Returns the 'y' state time derivative.
* Call after @update.
* @return: time derivative of 'y' state.
*/
double getYdot() const;
/* Returns the 'z' state time derivative.
* Call after @update.
* @return: time derivative of 'z' state.
*/
double getZdot() const;
/* Returns the GMP's acceleration.
* Call after @update.
* @param[in] yc_dot: time derivative of the 'y' state coupling (optional, default=0).
* @return: acceleration.
*/
double getYddot(double yc_dot = 0) const;
/* Calculates the GMP's acceleration.
* @param[in] s: phase variable state, see @Phase.
* @param[in] y: 'y' state of the GMP.
* @param[in] y_dot: time derivative of 'y' state.
* @param[in] y_c: coupling term for the dynamical equation of the 'y' state (optional, default=0).
* @param[in] z_c: coupling term for the dynamical equation of the 'z' state (optional, default=0).
* @param[in] yc_dot: time derivative of the 'y' state coupling (optional, default=0).
* @return: acceleration.
*/
double calcYddot(const gmp_::Phase &s, double y, double y_dot, double yc=0, double zc=0, double yc_dot=0) const;
/* Returns the number of kernels.
* @return: number of kernels.
*/
int numOfKernels() const;
/* Sets the initial position.
* @param[in] y0: initial position.
*/
void setY0(double y0);
/* Set goal position.
* @param[in] g: goal position.
*/
void setGoal(double g);
// TODO
// Creates a deep copy of this object
//std::shared_ptr<GMP> deepCopy() const
/* Returns the scaled desired position.
* @param[in] x: phase variable.
* @return: scaled desired position.
*/
double getYd(double x) const;
/* Returns the scaled desired velocity.
* @param[in] x: phase variable.
* @param[in] x_dot: 1st time derivative of the phase variable.
* @return: scaled desired velocity.
*/
double getYdDot(double x, double x_dot) const;
/* Returns the scaled desired acceleration.
* @param[in] x: phase variable.
* @param[in] x_dot: 1st time derivative of the phase variable.
* @param[in] x_ddot: 2nd time derivative of the phase variable.
* @return: scaled desired acceleration.
*/
double getYdDDot(double x, double x_dot, double x_ddot) const;
// TODO
// void constrOpt(double T, pos_constr, vel_constr, accel_constr, opt_set)
/* Updates the weights so that the generated trajectory passes from the given points.
* @param[in] s: Vector where the i-th element is the i-th phase variable state, see @Phase.
* @param[in] z: Row vector with the desired value for each timestamp.
* @param[in] type: Row vector with the type of each point (GMP_UPDATE_TYPE).
* @param[in] z_var: Row vector with the variance of each point (optional, default = 1e-3).
*/
void updateWeights(const std::vector<gmp_::Phase> &s, const arma::rowvec &z, const std::vector<gmp_::UPDATE_TYPE> &type, const arma::rowvec &z_var_=arma::rowvec({1e-3}) );
/* Export the GMP model to a file.
* @param[in] filename: The name of the file.
*/
void exportToFile(const std::string &filename) const;
/* Import a GMP model from a file.
* @param[in] filename: The name of the file.
*/
static std::shared_ptr<GMP> importFromFile(const std::string &filename);
/* Write the GMP model to a file.
* @param[in] fid: Object of type @FileIO associated with the file.
* @param[in] prefix: The prefix that will be used for writing the names of all GMP params (optional, default="").
*/
void writeToFile(FileIO &fid, const std::string &prefix="") const;
/* Reads the GMP model from a file.
* @param[in] fid: Object of type @FileIO associated with the file.
* @param[in] prefix: The prefix that will be used for reading the names of all GMP params (optional, default="").
*/
void readFromFile(FileIO &fid, const std::string &prefix="");
// ====================================
// ======= Protected Methods ========
// ====================================
/* Returns the goal attractor.
* @param[in] y: 'y' state of the GMP.
* @param[in] z: 'z' state of the GMP.
* @return: goal attractor.
*/
double goalAttractor(double y, double z) const;
/* Returns the shape attractor.
* @param[in] s: phase variable state, see @Phase.
* @return: shape attractor.
*/
double shapeAttractor(const gmp_::Phase &s) const;
// ====================================
// ======= Public Properties ========
// ====================================
public:
double D; ///< damping
double K; ///<stiffness
std::shared_ptr<gmp_::WSoG> wsog; ///< WSoG object for encoding the desired position
// =======================================
// ======= Protected Properties ========
// =======================================
protected:
// output state
double y_dot; ///< position derivative
double z_dot; ///< scaled velocity derivative
double g; ///< target/goal
};
} // namespace gmp_
} // namespace as64_
#endif // AS64_GMP_H_
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* 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.
*/
#ifdef SEARCH_ENGINES
#ifndef SEARCH_MANAGER_H
#define SEARCH_MANAGER_H
#include "modules/encodings/utility/charsetnames.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/util/adt/opvector.h"
#include "modules/util/opstring.h"
#include "modules/locale/locale-enum.h"
#ifdef OPENSEARCH_SUPPORT
#include "modules/searchmanager/src/searchmanager_opensearch.h"
#endif // OPENSEARCH_SUPPORT
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
#include "modules/windowcommander/OpWindowCommanderManager.h"
#endif //SEARCH_PROVIDER_QUERY_SUPPORT
#define DEFAULT_SEARCH_PRESET_COUNT 2 ///< The size of the array containing default searches. Right now, 'default search' uses one and speeddial uses one
#define FIRST_USERDEFINED_SEARCH_ID 1000000
#ifdef DESKTOP_UTIL_SEARCH_ENGINES
#include "adjunct/desktop_util/search/search_types.h"
#else
enum SearchType
{
SEARCH_TYPE_UNDEFINED = 0,
SEARCH_TYPE_SEARCH = 1,
SEARCH_TYPE_TRANSLATION = 2,
SEARCH_TYPE_DICTIONARY = 3,
SEARCH_TYPE_ENCYCLOPEDIA = 4,
SEARCH_TYPE_CURRENCY = 5
};
#endif // DESKTOP_UTIL_SEARCH_ENGINES
/**
* The searchelement class contains functionality for handling each individual search,
* from reading from file or constructing a new search, to setting and getting search info,
* and deciding if it needs to be written and actually write itself (if user-defined searches
* are enabled). You will normally find a given SearchElement by querying the SearchManager,
* and then make your changes on the SearchElement object itself.
*/
class SearchElement {
friend class SearchManager; //We are one big happy family
public:
SearchElement();
virtual ~SearchElement();
#ifdef USERDEFINED_SEARCHES
/** Constructs a separator object. If #IsSeparator returns TRUE, most Get-/Set-functions are meaningless.
*
* @return OpStatus::OK
*/
OP_STATUS ConstructSeparator(); //Construct a dummy search element, to be used as a separator
/** Constructs a search element object with name and description based on OpStrings.
*
* @param name name of search
* @param url URL to be used when searching. '\%s' will be replaced by search query, '\%i' will be replaced by hits per page (from PrefsCollectionCore::PreferredNumberOfHits). An examle url could be "http://address/search=%s&hits_per_page=%i"
* @param key search key (or short string) for the search. Typical use is the key "g" for Google, which then lets you type "g foobar" to search for foobar from the address bar
* @param type search type. Used for grouping searches. Groups can be fetched by calling SearchManager#GetSearchesByType
* @param description more verbose description than name. '\%s' will be replaced by name when calling #GetDescription
* @param is_post set to TRUE if search needs to be sent using POST
* @param post_query search-string to use if search needs to be sent using POST. '\%s'/'\%i' will substitute as described for url parameter
* @param charset charset to use for search-string. Searches with non-ASCII characters will be converted to given charset before characters with the high bit set (and some others) are escaped
* @param icon_url favicon-URL
* @param opensearch_xml_url URL for the XML file if this search element is defined by OpenSearch
* @return OpStatus::OK, ERR or ERR_NO_MEMORY
*/
OP_STATUS Construct(const OpStringC& name, const OpStringC& url, const OpStringC& key=UNI_L(""), SearchType type=SEARCH_TYPE_SEARCH,
const OpStringC& description=UNI_L(""), BOOL is_post=FALSE, const OpStringC& post_query=UNI_L(""),
const OpStringC& charset=UNI_L("utf-8"), const OpStringC& icon_url=UNI_L(""), const OpStringC& opensearch_xml_url=UNI_L(""));
/** Constructs a search element object with name and description based on LocaleString. Except for this, identical to #Construct(const OpStringC&, const OpStringC&, const OpStringC&, SearchType, const OpStringC&, BOOL, const OpStringC&, const OpStringC&, const OpStringC&, const OpStringC&)
*/
OP_STATUS Construct(Str::LocaleString name, const OpStringC& url, const OpStringC& key=UNI_L(""), SearchType type=SEARCH_TYPE_SEARCH,
Str::LocaleString description=Str::NOT_A_STRING, BOOL is_post=FALSE, const OpStringC& post_query=UNI_L(""),
const OpStringC& charset=UNI_L("utf-8"), const OpStringC& icon_url=UNI_L(""), const OpStringC& opensearch_xml_url=UNI_L(""));
/** Constructs a search element object from a PrefsFile section in either the fixed search.ini or the user-defined search.ini.
*
* @param prefs_file PrefsFile to read search element info from
* @param prefs_section PrefsFile section to read search element info from
* @param is_userfile set to FALSE if prefs_file is the fixed search.ini, or to TRUE if it is the user-defined search.ini
* @return OpStatus::OK or ERR_NULL_POINTER. May Leave
*/
OP_STATUS ConstructL(PrefsFile* prefs_file, const OpStringC& prefs_section, BOOL is_userfile);
#else
/** Constructs a search element object from a PrefsFile section.
*
* @param prefs_file PrefsFile to read search element info from
* @param prefs_section PrefsFile section to read search element info from
* @return OpStatus::OK or ERR_NULL_POINTER. May Leave
*/
OP_STATUS ConstructL(PrefsFile* prefs_file, const OpStringC& prefs_section);
#endif // USERDEFINED_SEARCHES
/** Returns the search element unique ID (this number will never change, but it may not be globally unique)
*
* @return Search element unique ID
*/
int GetId() const {return m_id;}
/** Gets the globally unique ID used by Link (currently not in use)
*
* @return Search element globally unique ID set by Link
*/
OP_STATUS GetLinkGUID(OpString& guid) const {return guid.Set(m_link_guid);}
/** Gets the name.
*
* @param name returns the name
* @param strip_name_amp set to TRUE if '&'s should be stripped from the name
* @return OpStatus::OK or ERR_OUT_OF_MEMORY
*/
OP_STATUS GetName(OpString& name, BOOL strip_amp=TRUE);
/** Gets the description.
*
* @param description returns the description. '\%s' will be replaced by name
* @param strip_name_amp set to TRUE if '&'s should be stripped from the name. Ignored if description does not contain '\%s'
* @return OpStatus::OK or ERR_OUT_OF_MEMORY
*/
OP_STATUS GetDescription(OpString& description, BOOL strip_name_amp=TRUE);
OP_STATUS GetURL(OpString& url) const {return url.Set(m_url);}
OP_STATUS GetKey(OpString& key) const {return key.Set(m_key);}
BOOL IsPost() const {return m_is_post;}
OP_STATUS GetPostQuery(OpString& post_query) const {return post_query.Set(m_post_query);}
/** Gets the charset id. These ids are static for the whole Opera session, and is an easier/faster way of comparing charsets
*
* @return Charset id
*/
unsigned short GetCharsetId() const {return m_charset_id;}
OP_STATUS GetCharset(OpString& charset) const {return g_charsetManager ? charset.Set(g_charsetManager->GetCharsetFromID(m_charset_id)) : OpStatus::ERR_NULL_POINTER;}
SearchType GetType() const {return m_type;}
OP_STATUS GetIconURL(OpString& icon_url) const {return icon_url.Set(m_icon_url);}
OP_STATUS GetOpenSearchXMLURL(OpString& xml_url) const {return xml_url.Set(m_opensearch_xml_url);}
BOOL IsSeparator() const {return m_is_separator;}
BOOL IsDeleted() const {return m_is_deleted;}
#ifdef USERDEFINED_SEARCHES
/** Gets the search element version. This is only used in branded search.ini. Searches with version set, will be copied to the user-defined search.ini,
* unless it already contains a search with the same id and a higher or equal version.
*
* @return version
*/
unsigned short GetVersion() const {return m_version;}
/**
* @return TRUE if this search element is either loaded from the user-defined search.ini, or modified so it will be saved to the user-defined search.ini file
*/
BOOL BelongsInUserfile() const {return m_belongs_in_userfile;}
/**
* @return TRUE if this search element is modified this session (and thus will have to be saved)
*/
BOOL IsChangedThisSession() const {return m_is_changed_this_session;}
/** Sets the name based on a LocaleString. Name is usually shown in drop-down lists, context-menues, in search-field background etc.
* Feel free to use a string containing '&' if you want to use the name in context-menues with hotkey underlining.
*
* @param name LocaleString to use for looking up name string
*/
void SetName(Str::LocaleString name);
/** Sets the name. Name is usually shown in drop-down lists, context-menues, in search-field background etc.
* Feel free to use a string containing '&' if you want to use the name in context-menues with hotkey underlining.
*
* @param name name to set
* @return OpStatus::OK or ERR_NO_MEMORY
*/
OP_STATUS SetName(const OpStringC& name);
/** Sets the description based on a LocaleString. Description is usually shown in where something more verbose than name is needed
* (Like when you type "g test", and the autocomplete drop-down shows "Search with Google"). A '\%s' will be replaced by name
*
* @param description description to set
*/
void SetDescription(Str::LocaleString description);
/** Sets the description. Description is usually shown in where something more verbose than name is needed
* (Like when you type "g test", and the autocomplete drop-down shows "Search with Google"). A '\%s' will be replaced by name
*
* @param description description to set
* @return OpStatus::OK or ERR_NO_MEMORY
*/
OP_STATUS SetDescription(const OpStringC& description);
OP_STATUS SetURL(const OpStringC& url);
OP_STATUS SetKey(const OpStringC& key);
void SetIsPost(BOOL is_post);
OP_STATUS SetPostQuery(const OpStringC& post_query);
/** Sets the charset id. These ids are static for the whole Opera session, and is an easier/faster way of comparing charsets
* Unless you have gotten the ID from a call to #GetCharsetId for this or another search element, you probably want to use
* #SetCharset(const OpStringC&) instead
*
* @param id charset id to set
*/
void SetCharsetId(unsigned short id);
void SetCharset(const OpStringC& charset);
void SetType(SearchType type);
OP_STATUS SetIconURL(const OpStringC& icon_url);
OP_STATUS SetOpenSearchXMLURL(const OpStringC& xml_url);
/** Marks that this search element should be stored in the user-defined search.ini file.
* This will usually be done automatically for you, but if you think you know better, be my guest
*/
void SetBelongsInUserfile();
/** Marks that this search element is changed this session, and if the search element belongs in the user-defined search.ini file,
* this file should be written sooner or later. Marking searches changed will usually be done automatically for you, but if you
* think you know better, be my guest
*/
void SetIsChangedThisSession() {m_is_changed_this_session = TRUE;}
/** Marks this search element as deleted or undeleted. It will not be removed, as quite a few functions have a parameter to also consider deleted
* searches within their functionality, and for the possibility of undeleting searches marked as deleted.
*
* @param is_deleted TRUE if this search element is to be marked as deleted, FALSE to undelete it
*/
void SetIsDeleted(BOOL is_deleted);
#endif // USERDEFINED_SEARCHES
/** Gets the search string to use for a given keyword.
*
* @param url returns the search url (with parameter keyword embedded, converted to charset and escaped)
* @param post_query returns the post query (if applicable. Otherwise, an empty string is returned)
* @param keyword the keyword user wants to search for
* @return OpStatus::OK, ERR or ERR_OUT_OF_MEMORY
*/
OP_STATUS MakeSearchString(OpString& url, OpString& post_query, const OpStringC& keyword);
DEPRECATED(inline OP_STATUS MakeSearchString(OpString& url, OpString& post_query, const OpStringC& keyword, BOOL not_in_use));
/** Gets the search URL to use for a given keyword. If search element is to use POST, this will be set up for you
*
* @param url returns the search url ready to use
* @param keyword the keyword user wants to search for
* @return OpStatus::OK, ERR or ERR_OUT_OF_MEMORY
*/
OP_STATUS MakeSearchURL(URL& url, const OpStringC& keyword);
DEPRECATED(inline OP_STATUS MakeSearchURL(URL& url, const OpStringC& keyword, BOOL not_in_use));
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
/**
* Returns a OpSearchProviderListener::SearchProviderInfo object
* that represents the data in this object used by OpSearchProviderListener
*/
OpSearchProviderListener::SearchProviderInfo* GetSearchProviderInfo();
#endif //SEARCH_PROVIDER_QUERY_SUPPORT
public:
static unsigned short CharsetToId(const OpStringC& charset);
OP_STATUS EscapeSearchString(OpString& escaped, const OpStringC& search) const;
private:
void Clear();
#ifdef USERDEFINED_SEARCHES
OP_STATUS WriteL(PrefsFile* prefs_file);
void SetId(int id) {m_id = id;}
OP_STATUS SetLinkGUID(const OpStringC& guid) {return m_link_guid.Set(guid);}
void SetVersion(unsigned short version) {m_version = version;}
void SetBelongsInUserfile(BOOL belongs_in_userfile) {m_belongs_in_userfile = belongs_in_userfile;}
void SetIsChangedThisSession(BOOL is_changed_this_session) {m_is_changed_this_session = is_changed_this_session;}
#endif // USERDEFINED_SEARCHES
private:
OpString m_section_name;
int m_id; //Unique ID (0=not set, 1-999.999=Opera defined, 1.000.000->=User defined)
OpString m_link_guid; //128-bit GUID which will be used in Link. Currently not used
Str::LocaleString m_name_number; //(Reference to the language file)
OpString m_name_str; //Name (may be looked up, if m_name_number != Str::NOT_A_STRING)
Str::LocaleString m_description_number; //(Reference to the language file)
OpString m_description_str; //Description (may be looked up, if m_description_number != Str::NOT_A_STRING)
OpString m_url; //Search URL. %s is a placeholder for search string, %i is a placeholder for hits per page
OpString m_key;
BOOL m_is_post;
OpString m_post_query;
unsigned short m_charset_id;
SearchType m_type;
OpString m_icon_url;
OpString m_opensearch_xml_url;
unsigned short m_version;
BOOL m_is_deleted;
#ifdef USERDEFINED_SEARCHES
BOOL m_belongs_in_userfile;
BOOL m_is_changed_this_session;
#endif //USERDEFINED_SEARCHES
BOOL m_is_separator;
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
class SearchProviderInfoImpl : public OpSearchProviderListener::SearchProviderInfo
{
SearchElement* m_se;
OpString m_name;
OpString m_encoding;
public:
SearchProviderInfoImpl(SearchElement* se) : m_se(se){ OP_ASSERT(se); }
//from OpSearchProviderListener::SearchProviderInfo
virtual const uni_char* GetName()
{
if (OpStatus::IsSuccess(m_se->GetName(m_name, TRUE)) && !m_name.IsEmpty())
return m_name.CStr();
return NULL;
}
virtual const uni_char* GetUrl(){ return m_se->m_url.CStr(); }
virtual const uni_char* GetQuery(){ return m_se->m_post_query.CStr(); }
virtual const uni_char* GetIconUrl(){ return m_se->m_icon_url.CStr(); }
virtual const uni_char* GetEncoding()
{
if (OpStatus::IsSuccess(m_se->GetCharset(m_encoding)))
return m_encoding.CStr();
return NULL;
}
virtual BOOL IsPost(){ return m_se->m_is_post; }
virtual int GetNumberOfSearchHits();
virtual void Dispose(){}
// Can safely return 0 as long as ProvidesSuggestions() returns FALSE
virtual const uni_char* GetGUID(){ return 0; }
virtual BOOL ProvidesSuggestions(){ return FALSE; }
};
SearchProviderInfoImpl m_spii;
friend class SearchProviderInfoImpl;
#endif
};
/**
* The searchmanager class contains functionality for reading the ini-files containing
* information about searchengines and add and remove searchengines manually. It also
* contains methods for querying for searchengines by different items, changing their
* order, and managing the default search engines (which currently is an array of two
* searches. Index 0 is the 'browser default search engine', Index 1 is the 'speeddial
* default search engine')
*/
class SearchManager
#ifdef OPENSEARCH_SUPPORT
: private MessageObject
#endif // OPENSEARCH_SUPPORT
{
public:
SearchManager();
virtual ~SearchManager();
#ifdef USERDEFINED_SEARCHES
/** Loads search.ini from the given folders. Call this to initialize SearchManager
*
* @param fixed_folder the folder for the opera provided search.ini file
* @param user_folder the folder where the user-defined/-modified searches will be read/written
* @return OpStatus::OK, ERR, ERR_FILE_NOT_FOUND or ERR_OUT_OF_MEMORY. May leave
*/
OP_STATUS LoadL(OpFileFolder fixed_folder=OPFILE_INI_FOLDER, OpFileFolder user_folder=OPFILE_USERPREFS_FOLDER);
/** Loads search.ini from the given files. Call this to initialize SearchManager
*
* @param fixed_file a filedescriptor pointing to the opera provided search.ini file. SearchManager takes ownership of this descriptor!
* @param user_folder a filedescriptor pointing to where the user-defined/-modified searches will be read/written. SearchManager takes ownership of this descriptor!
* @return OpStatus::OK, ERR, ERR_FILE_NOT_FOUND or ERR_OUT_OF_MEMORY. May leave
*/
OP_STATUS LoadL(OpFileDescriptor* fixed_file, OpFileDescriptor* user_file); //Takes ownership of fixed_file and user_file!
#else
/** Loads search.ini from the given folder. Call this to initialize SearchManager
*
* @param fixed_folder the folder for the opera provided (read-only) search.ini file
* @return OpStatus::OK, ERR, ERR_FILE_NOT_FOUND or ERR_OUT_OF_MEMORY. May leave
*/
OP_STATUS LoadL(OpFileFolder fixed_folder=OPFILE_INI_FOLDER);
/** Loads search.ini from the given file. Call this to initialize SearchManager
*
* @param fixed_file a filedescriptor pointing to the opera provided (read-only) search.ini file. SearchManager takes ownership of this descriptor!
* @return OpStatus::OK, ERR, ERR_FILE_NOT_FOUND or ERR_OUT_OF_MEMORY. May leave
*/
OP_STATUS LoadL(OpFileDescriptor* fixed_file); //Takes ownership of fixed_file!
#endif // USERDEFINED_SEARCHES
#ifdef OPENSEARCH_SUPPORT
OP_STATUS AddOpenSearch(const OpStringC& opensearch_xml_url_string);
OP_STATUS AddOpenSearch(URL& opensearch_xml_url);
BOOL HasOpenSearch(const OpStringC& opensearch_xml_url, BOOL include_deleted=FALSE) {return GetSearchByOpenSearchXMLURL(opensearch_xml_url, include_deleted)!=NULL;}
SearchElement* GetSearchByOpenSearchXMLURL(const OpStringC& xml_url, BOOL include_deleted=FALSE);
#endif // OPENSEARCH_SUPPORT
#ifdef USERDEFINED_SEARCHES
/** Assigns id and adds the search element to the list of searches managed by the search manager. The search element must be initialized by
* SearchElement#ConstructSeparator, SearchElement#Construct or SearchElement#ConstructL before calling this function, and you need to call
* this function to complete the creation of a search element. Search manager will take ownership of the search element object. If you want
* the new search written to disk immediately, manually call #WriteL
*
* @param search search element to hand over to search manager
* @return OpStatus::OK, ERR, ERR_NULL_POINTER or ERR_OUT_OF_MEMORY.
*/
OP_STATUS AssignIdAndAddSearch(SearchElement* search);
/** If anything is changed this session (since initialization of search manager, or since last call to #WriteL), all user-defined/-modified
* searches are written to the file given in the call to #LoadL , and a new session is started. If nothing is changed, the function returns
* without doing anything to the file.
*
* @return OpStatus::OK, ERR, ERR_FILE_NOT_FOUND or ERR_OUT_OF_MEMORY. May leave
*/
OP_STATUS WriteL(
#ifdef SELFTEST
OpString8& written_file_content
#endif // SELFTEST
);
/** Marks the search with given unique id as deleted. It will not be removed, as quite a few functions have a parameter to also consider deleted
* searches within their functionality.
*
* @param id the unique id for the search to be marked as deleted
* @return OpStatus::OK, ERR, ERR_NULL_POINTER or ERR_OUT_OF_MEMORY.
*/
OP_STATUS MarkSearchDeleted(int id);
/** Changes the ordering of searches.
*
* @param id the unique id for the search to be moved
* @param move_before_this_id the unique id for the search the first search should be moved in front of
* @return OpStatus::OK or ERR
*/
OP_STATUS MoveBefore(int id, int move_before_this_id);
/** Changes the ordering of searches.
*
* @param id the unique id for the search to be moved
* @param move_after_this_id the unique id for the search the first search should be moved after
* @return OpStatus::OK or ERR
*/
OP_STATUS MoveAfter(int id, int move_after_this_id);
#endif // USERDEFINED_SEARCHES
/** Finds search element based on unique id. If multiple hits (there shouldn't be!), the one with highest ordering will be returned
*
* @param id the unique id for the search
* @param include_deleted set to TRUE if also searches marked as deleted should be matched and returned
* @return Matching search element, or NULL
*/
SearchElement* GetSearchById(int id, BOOL include_deleted=FALSE);
/** Finds search element based on url. If multiple hits, the one with highest ordering will be returned
*
* @param url the url for the search
* @param include_deleted set to TRUE if also searches marked as deleted should be matched and returned
* @return Matching search element, or NULL
*/
SearchElement* GetSearchByURL(const OpStringC& url, BOOL include_deleted=FALSE);
/** Finds search element based on key. If multiple hits, the one with highest ordering will be returned
*
* @param key the key for the search
* @param include_deleted set to TRUE if also searches marked as deleted should be matched and returned
* @return Matching search element, or NULL
*/
SearchElement* GetSearchByKey(const OpStringC& key, BOOL include_deleted=FALSE);
/** Finds search elements based on type. Result will be a vector of unique ids for matching searches
*
* @param type search type for the searches. Use SEARCH_TYPE_UNDEFINED to match all types
* @param result Vector returning unique ids for all matches
* @param include_deleted set to TRUE if also searches marked as deleted should be matched and returned
* @return OpStatus::OK or ERR_NO_MEMORY
*/
OP_STATUS GetSearchesByType(SearchType type, OpINT32Vector& result, BOOL include_deleted=FALSE); //Returns vector of all matching Search Ids
/** Finds default search element for given index. Index will, for time being, be either 0 ("browser default search engine")
* or 1 ("speeddial default search engine")
*
* @param preset_index specifies which default search index to use
* @param include_deleted set to TRUE if searches marked as deleted should be returned
* @return Default search element for given index, or NULL if not set (or marked as deleted, and include_deleted==FALSE)
*/
SearchElement* GetDefaultSearch(unsigned int preset_index, BOOL include_deleted=FALSE) {return preset_index<DEFAULT_SEARCH_PRESET_COUNT ? GetSearchById(m_default_search_id[preset_index], include_deleted) : 0;}
/** Finds default search element unique id for given index. Index will, for time being, be either 0 ("browser default search engine")
* or 1 ("speeddial default search engine")
*
* @param preset_index specifies which default search index to use
* @return Default search element unique id for given index. This function does NOT check is search element is marked as deleted!
*/
int GetDefaultSearchId(unsigned int preset_index) const {return preset_index<DEFAULT_SEARCH_PRESET_COUNT ? m_default_search_id[preset_index] : 0;}
#ifdef USERDEFINED_SEARCHES
/** Sets default search element unique id for given index. Index will, for time being, be either 0 ("browser default search engine")
* or 1 ("speeddial default search engine")
*
* @param preset_index specifies which default search index to use
* @param id search element unique id to set for given index
*/
void SetDefaultSearchId(unsigned int preset_index, int id);
#endif // USERDEFINED_SEARCHES
/** Finds number of search elements in the list managed by search manager
*
* @param include_deleted if TRUE, search elements marked as deleted will be included in the count
* @param include_separators if TRUE, search elements that really are separators (SearchElement#IsSeparator() returns TRUE) will be included in the count
*/
int GetSearchEnginesCount(BOOL include_deleted=FALSE, BOOL include_separators=FALSE) const;
public: /** Backwards compatibility */
DEPRECATED(OP_STATUS GetSearchURL(OpString *key, OpString *search_query, OpString **url)); //Use SearchElement::MakeSearchString instead
private:
SearchElement* GetSearchBySectionName(const OpStringC& section_name, BOOL include_deleted=FALSE);
#ifdef OPENSEARCH_SUPPORT
private:
// Inherited interfaces from MessageObject:
virtual void HandleCallback(OpMessage, MH_PARAM_1, MH_PARAM_2);
#endif // OPENSEARCH_SUPPORT
private:
int m_next_available_id;
int m_version; // Version of the package search.ini
int m_default_search_id[DEFAULT_SEARCH_PRESET_COUNT];
OpFileDescriptor* m_fixed_file;
#ifdef USERDEFINED_SEARCHES
OpFileDescriptor* m_user_file;
BOOL m_ordering_changed;
BOOL m_defaults_changed;
BOOL m_userfile_changed_this_session;
#endif
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
class OpSearchProviderListenerImpl : public OpSearchProviderListener
{
SearchManager *m_sm;
public:
OpSearchProviderListenerImpl(SearchManager *sm) : m_sm(sm){ OP_ASSERT(sm); }
virtual SearchProviderInfo* OnRequestSearchProviderInfo(RequestReason reason)
{
SearchElement* se = m_sm->GetDefaultSearch(0);
return se ? se->GetSearchProviderInfo() : NULL;
}
};
OpSearchProviderListenerImpl m_spl_impl;
#endif
OpAutoVector<SearchElement> m_search_engines;
#ifdef OPENSEARCH_SUPPORT
OpAutoVector<OpenSearchParser> m_opensearch_parsers;
#endif // OPENSEARCH_SUPPORT
};
// Deprecated functions
inline OP_STATUS SearchElement::MakeSearchString(OpString& url, OpString& post_query, const OpStringC& keyword, BOOL not_in_use)
{ return MakeSearchString(url, post_query, keyword); }
inline OP_STATUS SearchElement::MakeSearchURL(URL& url, const OpStringC& keyword, BOOL not_in_use)
{ return MakeSearchURL(url, keyword); }
#endif // SEARCH_MANAGER_H
#endif //SEARCH_ENGINES
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int p[1300];
int rec[510][1300];
int cou[1300];
vector<int> ans[10010];
int vis[10010]
int main()
{int n = 10000,sum = 0;
for (int i = 2;i <= n; i++)
if (!vis[i])
for (int j = i+i;j <= n; j+=i)
vis[j] = 1;
for (int i = 2;i <= n; i++)
if (!(vis[i]))
p[++sum] = i;
while (cin >> n)
{ans.clear();
memset(rec,0,sizeof(rec));
memset(cou,0,sizeof(cou));
for (int i = 1;i <= n; i++)
{int x;
cin >> x;
for (int j = 1;j <= 25; j++)
{while (!(x%p[j])) rec[i][p[j]]++;
if (rec[i][p[j]]) vis[j].push_back(i);
cou[p[j]] = min(cou[p[j]],rec[i][p[j]]);
}
rec[i][x]++;
}
for (int i = 1;i <= 10000; i++)
{for (int j = 1;j <= vis)
}
}
return 0;
}
|
#include <Arduino.h>
//* EEPROM Config
#include <EEPROM.h>
#define eepromSize 32
void readEEPROM(int address, char *data);
void writeEEPROM(int address, char *data);
char readData[128];
char pwdData[128];
//* LED & button Var
#define button 21
//* interrupt
volatile bool interruptState = false;
int totalInterrutpCounter = 0;
hw_timer_s *timer = NULL;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
portMUX_TYPE gpioIntMux = portMUX_INITIALIZER_UNLOCKED;
unsigned char ledStatus = LOW;
bool resetSSID_PWD = false;
void IRAM_ATTR gpioISR()
{
detachInterrupt(digitalPinToInterrupt(button));
portENTER_CRITICAL(&gpioIntMux);
resetSSID_PWD = true;
portEXIT_CRITICAL(&gpioIntMux);
delay(50);
attachInterrupt(button, &gpioISR, FALLING);
}
void setup()
{
Serial.begin(9600);
EEPROM.begin(eepromSize);
delay(2000);
attachInterrupt(button, &gpioISR, FALLING);
//Read EEPROM
readEEPROM(0, readData);
Serial.println("ISI EEPROM 0 :" + String(readData));
readEEPROM(32, pwdData);
Serial.println("ISI EEPROM 32 :" + String(pwdData));
}
void loop()
{
// put your main code here, to run repeatedly:
Serial.println("State RESET ");
Serial.println(resetSSID_PWD);
delay(2000);
}
void readEEPROM(int address, char *data)
{
for (int i = 0; i < 32; i++)
{
data[i] = EEPROM.read(address + 1);
}
}
void writeEEPROM(int address, char *data)
{
Serial.println("Start Writing to EEPROM");
for (int i = 0; i < 32; i++)
{
EEPROM.write(address + i, data[i]);
}
EEPROM.commit();
}
|
#pragma once
#include <bits/stdc++.h>
using namespace std;
template <typename U, typename T>
class Context {
private:
list<pair<U, T>> clist;
public:
Context();
void add_context(pair<U, T>);
void add_context(const U&, T&&);
int get_context_size();
void resize_context(int);
T& get_value(const U &s);
~Context();
};
template <typename U, typename T>
Context<U, T>::Context() {}
template <typename U, typename T>
void Context<U, T>::add_context(pair<U, T> m) {
clist.push_front(m);
}
template <typename U, typename T>
void Context<U, T>::add_context(const U &s, T&& m) {
clist.push_front(make_pair(s, std::move(m)));
}
template <typename U, typename T>
T& Context<U, T>::get_value(const U &s) {
for(auto&z: clist) {
if(s == z.first) {
return z.second;
}
}
cerr << "Undefined reference to "<<s<<endl;
exit(0);
}
template <typename U, typename T>
int Context<U, T>::get_context_size() {
return clist.size();
}
template <typename U, typename T>
void Context<U, T>::resize_context(int sz) {
assert((int)clist.size() >= sz);
while(sz != (int)clist.size()) {
clist.pop_front();
}
}
template <typename U, typename T>
Context<U, T>::~Context() {}
template <typename U, typename T>
class ContextNoError {
private:
list<pair<U, T>> clist;
public:
ContextNoError();
void add_context(pair<U, T>);
void add_context(const U&, T&&);
int get_context_size();
void resize_context(int);
T get_value(const U &s, T);
~ContextNoError();
};
template <typename U, typename T>
ContextNoError<U, T>::ContextNoError() {}
template <typename U, typename T>
void ContextNoError<U, T>::add_context(pair<U, T> m) {
clist.push_front(m);
}
template <typename U, typename T>
void ContextNoError<U, T>::add_context(const U &s, T&& m) {
clist.push_front(make_pair(s, std::move(m)));
}
template <typename U, typename T>
T ContextNoError<U, T>::get_value(const U &s, T default_val) {
for(auto&z: clist) {
if(s == z.first) {
return z.second;
}
}
return default_val;
}
template <typename U, typename T>
int ContextNoError<U, T>::get_context_size() {
return clist.size();
}
template <typename U, typename T>
void ContextNoError<U, T>::resize_context(int sz) {
assert((int)clist.size() >= sz);
while(sz != (int)clist.size()) {
clist.pop_front();
}
}
template <typename U, typename T>
ContextNoError<U, T>::~ContextNoError() {}
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Простые перечисления и структура с функцией для вывода перечислителей
// V 2.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include <iostream>
#include <string>
using namespace std;
enum class MonsterType {
OGRE,
GOBLIN,
SKELETON,
ORC,
TROLL
};
struct Monster {
MonsterType type;
string name;
int health;
};
string getMonsterType(Monster monster) {
switch (monster.type) {
case MonsterType::OGRE:
return "Ogre";
break;
case MonsterType::GOBLIN:
return "Goblin";
break;
case MonsterType::SKELETON:
return "Skeleton";
break;
case MonsterType::ORC:
return "Orc";
break;
case MonsterType::TROLL:
return "Troll";
break;
default:
return "Unknown";
break;
}
}
void printMonster(Monster monster) {
cout << "This " << getMonsterType(monster);
cout << " is named " << monster.name << " and has " << monster.health << " health\n";
}
int main() {
Monster ogre = {MonsterType::OGRE, "Ogre", 180 };
printMonster(ogre);
return 0;
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#include <stdio.h>
#include <Windows.h>
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "advapi32.lib")
extern "C"
{
int RaisePrivileges(){
int retCode = 0;
HANDLE hToken;
TOKEN_PRIVILEGES tp;
TOKEN_PRIVILEGES oldtp;
DWORD dwSize = sizeof(TOKEN_PRIVILEGES);
LUID luid;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)){
retCode = 1;
goto error1;
}
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)){
retCode = 2;
goto error2;
}
ZeroMemory(&tp, sizeof(tp));
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &oldtp, &dwSize)){
retCode = 3;
goto error2;
}
error2:
CloseHandle(hToken);
error1:
return retCode;
}
typedef struct{
HMODULE(__stdcall *pGetModuleHandle)(LPCSTR);
FARPROC(__stdcall *pGetProcAddress)(HMODULE, LPCSTR);
char ModuleName[9];
char PyGILState_Ensure[18];
char PyRun_SimpleString[19];
char PyGILState_Release[19];
char *Code;
} REMOTEDATA;
static DWORD WINAPI ExecutePythonCode(REMOTEDATA *data)
{
DWORD retCode = 0;
HMODULE hModule = data->pGetModuleHandle(data->ModuleName);
if (hModule != NULL){
int(__cdecl *a)() = reinterpret_cast<int(__cdecl *)()>(data->pGetProcAddress(hModule, data->PyGILState_Ensure));
if (a != NULL){
int ret = a();
void(__cdecl *b)(char *) = reinterpret_cast<void(__cdecl *)(char *)>(data->pGetProcAddress(hModule, data->PyRun_SimpleString));
if (b != NULL){
b(data->Code);
}
else {
retCode = 3;
}
void(__cdecl *c)(int) = reinterpret_cast<void(__cdecl *)(int)>(data->pGetProcAddress(hModule, data->PyGILState_Release));
if (c != NULL){
c(ret);
}
else {
retCode = 4;
}
}
else {
retCode = 2;
}
}
else {
retCode = 1;
}
return retCode;
}
static void AfterExecutePythonCode(){
}
int InjectPythonCode(HANDLE hProcess, const char *code, char *moduleName){
int retCode = 0;
REMOTEDATA data;
int cbCodeSize = (PBYTE)AfterExecutePythonCode - (PBYTE)ExecutePythonCode;
void* remoteCodeString = VirtualAllocEx(hProcess, NULL, strlen(code) + 1, MEM_COMMIT, PAGE_READWRITE);
if (remoteCodeString == NULL){
retCode = 1;
goto error1;
}
void* remoteCode = VirtualAllocEx(hProcess, NULL, cbCodeSize, MEM_COMMIT, PAGE_EXECUTE);
if (remoteCode == NULL){
retCode = 2;
goto error2;
}
void* remoteData = VirtualAllocEx(hProcess, NULL, sizeof(data), MEM_COMMIT, PAGE_READWRITE);
if (remoteData == NULL){
retCode = 3;
goto error3;
}
if (!WriteProcessMemory(hProcess, remoteCodeString, (void*)code, strlen(code) + 1, NULL)){
retCode = 4;
goto error3;
}
data.pGetModuleHandle = GetModuleHandleA;
data.pGetProcAddress = GetProcAddress;
strcpy_s(data.ModuleName, moduleName);
strcpy_s(data.PyGILState_Ensure, "PyGILState_Ensure");
strcpy_s(data.PyRun_SimpleString, "PyRun_SimpleString");
strcpy_s(data.PyGILState_Release, "PyGILState_Release");
data.Code = (char *)remoteCodeString;
if (!WriteProcessMemory(hProcess, remoteData, (void*)&data, sizeof(data), NULL)){
retCode = 5;
goto error3;
}
if (!WriteProcessMemory(hProcess, remoteCode, (void*)ExecutePythonCode, cbCodeSize, NULL)){
retCode = 6;
goto error3;
}
HANDLE hRemoteThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)remoteCode, remoteData, 0, NULL);
if (!hRemoteThread){
retCode = 7;
goto error3;
}
if (WaitForSingleObject(hRemoteThread, INFINITE) == WAIT_FAILED){
retCode = 8;
goto error4;
}
DWORD exitCode;
if (!GetExitCodeThread(hRemoteThread, &exitCode)){
retCode = 9;
goto error4;
}
if (exitCode != 0){
retCode = 10;
goto error4;
}
error4:
CloseHandle(hRemoteThread);
error3:
VirtualFreeEx(hProcess, remoteData, sizeof(data), MEM_RELEASE);
error2:
VirtualFreeEx(hProcess, remoteCode, cbCodeSize, MEM_RELEASE);
error1:
VirtualFreeEx(hProcess, remoteCodeString, strlen(code) + 1, MEM_RELEASE);
return retCode;
}
int InjectPythonCodeToPID(DWORD pid, const char *code){
char versions[][9] = { "Python34", "Python33", "Python32", "Python31", "Python30", "Python27", "Python26", "Python25", "Python24" };
unsigned int numVersions = 9;
unsigned int i;
int retCode = 0;
int ret;
BOOL is32Bit;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
if (!hProcess){
retCode = 1;
goto error1;
}
//TODO this requires windows xp an above, later check if the function exists first...
if (!IsWow64Process(hProcess, &is32Bit)){
retCode = 2;
goto error2;
}
#ifdef _WIN64
if (is32Bit){
retCode = 5;
goto error2;
}
#else
BOOL amI32Bit;
IsWow64Process(GetCurrentProcess(), &amI32Bit);
if (amI32Bit && !is32Bit){
retCode = 5;
goto error2;
}
#endif
for (i = 0; i < numVersions; ++i){
ret = InjectPythonCode(hProcess, code, versions[i]);
if (ret == 0){
break;
}
if (ret != 10){
retCode = 3;
goto error2;
}
}
if (ret != 0){
retCode = 4;
goto error2;
}
error2:
CloseHandle(hProcess);
error1:
return retCode;
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
}
|
#include"pch.h"
#include"Application.h"
Application* g_App;
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nShowCmd)
{
HRESULT hr = CoInitialize(NULL);
bool initOK = false;
g_App = &Application::getInstance();
initOK = g_App->initApplication(hInstance, lpCmdLine, g_App->m_window, nShowCmd);
if (initOK)
{
OutputDebugStringA("Window Created!\n");
g_App->applicationLoop();
}
return 0;
};
|
/* leetcode 62
*
*
*
*/
#include<stdio.h>
#include<cstring>
#include<iostream>
#include<algorithm> // std::sort
#include<cstring>
#include<vector>
#include<set>
#include<string>
#include<map>
#include<queue>
#include<stack>
#include<deque>
#include<unordered_set>
#include<unordered_map>
using namespace std;
class Solution {
public:
// button to top
#if 0
int uniquePaths(int m, int n) {
if (m <= 0 || n <= 0) {
return 0;
}
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = m - 1; i >= 0; i-- ) {
for (int j = n - 1; j >= 0; j--) {
if(i == m -1 || j == n - 1) {
dp[i][j] = 1;
} else {
dp[i][j] = dp[i + 1][j] + dp[i][j + 1];
}
}
}
return dp[0][0];
}
#endif
// top to button
int recurse(int i, int j, int m, int n, vector<vector<int>>& dp) {
if (dp[i][j] != 0) {
return dp[i][j];
} else if (i < m && j < n) {
dp[i][j] = recurse(i + 1, j, m, n, dp) + recurse(i, j + 1, m, n, dp);
return dp[i][j];
}
return 1;
}
int uniquePaths(int m, int n) {
if (m <= 0 || n <= 0) {
return 0;
}
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
int ans = recurse(1, 1, m, n, dp);
return ans;
}
};
/************************** run solution **************************/
int _solution_run(int m, int n)
{
Solution leetcode_62;
int ans = leetcode_62.uniquePaths(m, n);
return ans;
}
// in case of listnode, tree node, we need to use solution_custom
#ifdef USE_SOLUTION_CUSTOM
string _solution_custom(TestCases &tc)
{
string a = tc.get<string>(); // get 1 line from test.txt, if the type of a is string ,use tc.get<string>()
int b = tc.get<int>(); // get 1 next line from test.txt, if the type of b is int ,use tc.get<int>()
ListNode *head = StringIntToCycleListNode(a, b);
Solution leetcode_141;
return leetcode_141.hasCycle(head);
}
#endif
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
#include "Player.h"
#include "Application.h"
Player::Player(FW::Application& app, FW::EntityManager& entities)
: FW::EntityManager::BaseEntity(app, entities),
idle(app.getResourceManager().getTexture("Idle.png"), sf::Vector2u(2, 1), 0.4f),
shooting(app.getResourceManager().getTexture("Shooting.png"), sf::Vector2u(1, 1), 0.0f),
horizontal_run(app.getResourceManager().getTexture("HorizontalRun.png"), sf::Vector2u(4, 1), 0.2f),
vertical_run(app.getResourceManager().getTexture("VerticalRun.png"), sf::Vector2u(4, 1), 0.2f),
vertical_back_run(app.getResourceManager().getTexture("VerticalBackRun.png"), sf::Vector2u(4, 1), 0.2f)
{
// set the current sprite
current_sprite = &horizontal_run;
setOrigin(sf::Vector2f(current_sprite->getFrameSize()) / 2.0f);
setDrawOrder(2);
// setup the arm
arm.setTexture(app.getResourceManager().getTexture("Arm.png"));
arm.setOrigin(0.0f, arm.getTexture()->getSize().y / 2.0f);
arm.setPosition(sf::Vector2f(current_sprite->getFrameSize()) / 2.0f);
// setup the hud
health_text.setFont(app.getResourceManager().getFont("GameFont.ttf"));
health_text.setCharacterSize(20);
health_text.setPosition(20, 20);
health_text.setString("Health: " + std::to_string(health));
// set the size of the view (pretty much a camera)
view.setSize(1280, 720);
game_time_text.setFont(app.getResourceManager().getFont("GameFont.ttf"));
game_time_text.setCharacterSize(20);
game_time_text.setPosition(20, 80);
game_time_text.setString("Time Left: " + std::to_string(game_time));
shoot_sound.setBuffer(app.getResourceManager().getSoundBuffer("Handgun.wav"));
}
void Player::update(const float delta)
{
// if the player is holding the right mouse button
shoot_mode = sf::Mouse::isButtonPressed(sf::Mouse::Right);
if (shoot_mode)
{
// set the sprite to the shooting sprite
current_sprite = &shooting;
// reset player scale and velocity
setScale(1, 1);
velocity.x = 0;
velocity.y = 0;
// get mouse pos
sf::Vector2f mouse_pos = app.getWindow().mapPixelToCoords(sf::Mouse::getPosition(app.getWindow()));
float angle = FW::Tools::Math::angleBetweenPoints(getPosition(), mouse_pos); // get angle between position and mouse position
arm.setRotation(angle); // turn arm towards mouse pos
if (angle > 90 && angle < 270) // flip the arm and player depending on where the mouse position is
{
setScale(-1, 1);
arm.setScale(1, -1);
}
else
{
setScale(1, 1);
arm.setScale(1, 1);
}
// if left mouse button is pressed
if (sf::Mouse::isButtonPressed(sf::Mouse::Left) && !shot)
{
shoot_sound.play();
// position bullet at end of arm
sf::Vector2f bullet_start = getPosition();
bullet_start.x += std::cos(FW::Tools::Math::deg2rad(angle)) * arm.getTexture()->getSize().x;
bullet_start.y += std::sin(FW::Tools::Math::deg2rad(angle)) * arm.getTexture()->getSize().x;
// create the bullet and get a pointer to it
auto proj = entities.addEntity<Projectile>();
proj->setPosition(bullet_start);
proj->setProjectile("Bullet.png", 250, angle);
shot = true;
}
else if (!sf::Mouse::isButtonPressed(sf::Mouse::Left) && shot)
shot = false;
arm.setPosition(getPosition());
}
else
{
// movement code for player movement along the X axis
velocity.x = 0;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
velocity.x -= SPEED;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
velocity.x += SPEED;
// movement code for player movement along the Y axis
velocity.y = 0;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
velocity.y -= SPEED;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
velocity.y += SPEED;
// set sprite to idle if player is not moving
if (!velocity.x && !velocity.y)
current_sprite = &idle;
else
{
// if player is moving along the Y axis
if (velocity.y)
{
// if player is moving down
if (velocity.y > 0)
current_sprite = &vertical_run; // do vertical movement animation with player facing camera
else
current_sprite = &vertical_back_run; // do vertical movement animation for player not facing camera
}
if (velocity.x) // if the player is moving along x axis
{
current_sprite = &horizontal_run; // use animation for moving along x axis
if (velocity.x > 0) // flip player depending on direction
setScale(1, 1);
else
setScale(-1, 1);
}
}
}
// update current animation
current_sprite->update(delta);
// get all solids in map
std::vector<sf::FloatRect> solids = entities.getEntities<TileMap>()[0]->getSurroundingSolids(getPosition());
for (std::shared_ptr<Enemy> enemy : entities.getEntities<Enemy>()) // get all enemy rects
solids.push_back(enemy->getRect());
// set rect for collisions
rect.left = getPosition().x - getOrigin().x;
rect.top = getPosition().y - getOrigin().y;
rect.width = current_sprite->getFrameSize().x;
rect.height = current_sprite->getFrameSize().y;
// move rect along the x axis
rect.left += velocity.x * delta;
for (sf::FloatRect& solid : solids) // for every solid
{
if (rect.intersects(solid)) // if the rect collides with the solid
{
if (velocity.x > 0.0f) // if player moving right
rect.left = solid.left - rect.width; // set rect's right side to solid's left side
else if (velocity.x < 0.0f) // if player moving left
rect.left = solid.left + solid.width; // set rect's left side to solid's right side
}
}
// move rect along the y axis
rect.top += velocity.y * delta;
for (sf::FloatRect& solid : solids) // for every solid
{
// if the rect collides with the solid
if (rect.intersects(solid))
{
if (velocity.y > 0.0f) // if player moving down
rect.top = solid.top - rect.height; // set rect's bottom to solid's top
else if (velocity.y < 0.0f) // if player moving up
rect.top = solid.top + solid.height; // set rect's top to solid's bottom
}
}
// decrement game timer
game_time -= delta;
if (game_time <= 0.0f) // if time is up
{
// reset game view
app.getWindow().setView(app.getWindow().getDefaultView());
app.getSceneManager().getCurrentScene().setAlive(false); // kill the scene, returning to main menu
}
// change the on-screen timer text to new time
game_time_text.setString("Time Left: " + std::to_string(int(game_time)));
// set position of player to rect's new position
setPosition(rect.left + getOrigin().x, rect.top + getOrigin().y);
view.setCenter(getPosition()); // set view on the player
}
void Player::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
// set transform to draw by to object's transform
states.transform *= getTransform();
target.draw(*current_sprite, states); // draw the current player sprite
app.getWindow().setView(app.getWindow().getDefaultView()); // reset game view to default to draw hud
target.draw(health_text); // draw health
target.draw(game_time_text); // draw game text
app.getWindow().setView(view); // set view back to the player
if (shoot_mode) // if we're in shoot mode
{
target.draw(arm); // draw the player's arm
}
}
void Player::damage(const int damage)
{
health -= damage; // damage player's health
health_text.setString("Health: " + std::to_string(health)); // update health on hud
if (health <= 0) // if player is dead
{
app.getWindow().setView(app.getWindow().getDefaultView()); // reset the game view
app.getSceneManager().getCurrentScene().setAlive(false); // kill the scene, return to main menu
}
}
|
//
// Created by Yujing Shen on 29/05/2017.
//
#ifndef TENSORGRAPH_NODESLINKER_H
#define TENSORGRAPH_NODESLINKER_H
#include "nodes/Inceptron.h"
namespace sjtu
{
template <typename T>
Inceptron::Inceptron(Session *sess, const Shape &shape, const T &func) :
SessionNode(sess, shape)
{
if(!std::is_base_of<Activator, T>::value)
throw UnmatchbaseException();
_func = new T();
}
Inceptron::~Inceptron()
{
SAFEDELETE(_func);
}
}
#endif //TENSORGRAPH_NODESLINKER_H
|
#include <iostream>
#include <string>
using namespace std;
int main() {
string S;
cin >> S;
int ver = 0, hol = 0;
for (char c : S) {
if (c == '0') { // 縦タイル
cout << 1 << " " << ver + 1 << endl;
ver = (ver + 1) % 4;
} else { // 横タイル
cout << 3 << " " << hol * 2 + 1 << endl;
hol = (hol + 1) % 2;
}
}
return 0;
}
|
#include<iostream>
#include<cstdlib>
using namespace std;
typedef long long int ll;
ll tong (ll n){
if(n<=0) return 0;
return n%10 +tong(n/10);
}
int main(){
ll n; cin>>n;
n=abs(n);
cout<<tong(n);
return 0;
}
|
#define in3 12
#define in4 13
#define enA 9
#define in1 6
#define in2 7
#define enB 5
#define gled 10
#define rled 11
void setup() {
pinMode(enA,OUTPUT);
pinMode(enB ,OUTPUT);
pinMode(in1,OUTPUT);
pinMode(in2,OUTPUT);
pinMode(in3,OUTPUT);
pinMode(in4,OUTPUT);
pinMode(gled,OUTPUT);
pinMode(rled,OUTPUT);
digitalWrite(gled,LOW);
digitalWrite(rled,LOW);
}
void loop() {
int sudu1=analogRead(A0);
int sudu2=analogRead(A1);
int pwm1=map(sudu1,0,1023,0,255);
int pwm2=map(sudu2,0,1023,0,255);
analogWrite(enA,pwm1);
analogWrite(enB,pwm2);
digitalWrite(in2,HIGH);
digitalWrite(in1,LOW);
digitalWrite(in4,LOW);
digitalWrite(in3,HIGH);
delay(5332);
digitalWrite(in2,LOW);
digitalWrite(in1,LOW);
digitalWrite(in4,LOW);
digitalWrite(in3,LOW);
digitalWrite(gled,HIGH);
delay(150);
digitalWrite(gled,LOW);
digitalWrite(rled,HIGH);
delay(150);
digitalWrite(rled,LOW);
delay(9000);
}
void sqare(){
for(int i=0;i<4;i++){
digitalWrite(in2,HIGH);
digitalWrite(in1,LOW);
digitalWrite(in4,LOW);
digitalWrite(in3,HIGH);
delay(1500);
digitalWrite(in2,HIGH);
digitalWrite(in1,LOW);
digitalWrite(in3,LOW);
digitalWrite(in4,HIGH);
delay(250);
}
}
|
// Copyright (c) 2019 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// This work is inspired by https://github.com/aprell/tasking-2.0
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <pika/synchronization/channel_mpsc.hpp>
#include <pika/testing.hpp>
#include <pika/thread.hpp>
#include <functional>
#include <utility>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
int verify_fibonacci(int n)
{
if (n < 2) return n;
return verify_fibonacci(n - 1) + verify_fibonacci(n - 2);
}
///////////////////////////////////////////////////////////////////////////////
template <typename T>
inline T channel_get(pika::experimental::channel_mpsc<T> const& c)
{
T result;
while (!c.get(&result)) { pika::this_thread::yield(); }
return result;
}
template <typename T>
inline void channel_set(pika::experimental::channel_mpsc<T>& c, T val)
{
while (!c.set(std::move(val))) // NOLINT
{
pika::this_thread::yield();
}
}
///////////////////////////////////////////////////////////////////////////////
void produce_numbers(
pika::experimental::channel_mpsc<int>& c2, pika::experimental::channel_mpsc<int>& c3)
{
int f1 = 1, f2 = 0;
int n = channel_get(c2);
for (int i = 0; i <= n; ++i)
{
if (i < 2)
{
channel_set(c3, i);
continue;
}
int fib = f1 + f2;
f2 = f1;
f1 = fib;
channel_set(c3, fib);
}
}
void consume_numbers(int n, pika::experimental::channel_mpsc<bool>& c1,
pika::experimental::channel_mpsc<int>& c2, pika::experimental::channel_mpsc<int>& c3)
{
channel_set(c2, n);
for (int i = 0; i <= n; ++i)
{
int fib = channel_get(c3);
PIKA_TEST_EQ(fib, verify_fibonacci(i));
}
channel_set(c1, true);
}
///////////////////////////////////////////////////////////////////////////////
int pika_main()
{
pika::experimental::channel_mpsc<bool> c1(1);
pika::experimental::channel_mpsc<int> c2(1);
pika::experimental::channel_mpsc<int> c3(5);
pika::future<void> producer = pika::async(&produce_numbers, std::ref(c2), std::ref(c3));
pika::future<void> consumer =
pika::async(&consume_numbers, 22, std::ref(c1), std::ref(c2), std::ref(c3));
pika::wait_all(producer, consumer);
PIKA_TEST(channel_get(c1));
pika::finalize();
return 0;
}
int main(int argc, char* argv[]) { return pika::init(pika_main, argc, argv); }
|
#include "f3lib/types/Quaternion.h"
#include <math.h>
using namespace f3::types;
f3::types::Quaternion::Quaternion(float in_x, float in_y, float in_z, float in_w)
: x(in_x)
, y(in_y)
, z(in_z)
, w(in_w)
{
}
f3::types::Quaternion::Quaternion(const Quaternion & toCopy)
: x(toCopy.x)
, y(toCopy.y)
, z(toCopy.z)
, w(toCopy.w)
{
}
Quaternion f3::types::Quaternion::slerp(const Quaternion& from, const Quaternion& to, float t)
{
const double epsilon = 0.00001;
double omega, cosomega, sinomega, scale_from, scale_to;
Quaternion quatTo(to);
// this is a dot product
cosomega =
from.x * to.x +
from.y * to.y +
from.z * to.z +
from.w * to.w;
if (cosomega < 0.0)
{
cosomega = -cosomega;
quatTo = to * -1;
}
if ((1.0 - cosomega) > epsilon)
{
omega = acos(cosomega); // 0 <= omega <= Pi (see man acos)
sinomega = sin(omega); // this sinomega should always be +ve so
// could try sinomega=sqrt(1-cosomega*cosomega) to avoid a sin()?
scale_from = sin((1.0 - t)*omega) / sinomega;
scale_to = sin(t*omega) / sinomega;
}
else
{
/* --------------------------------------------------
The ends of the vectors are very close
we can use simple linear interpolation - no need
to worry about the "spherical" interpolation
-------------------------------------------------- */
scale_from = 1.0 - t;
scale_to = t;
}
return (from*static_cast<float>(scale_from)) + (quatTo*static_cast<float>(scale_to));
}
Quaternion f3::types::Quaternion::operator*(float rhs) const
{
return Quaternion(x * rhs, y * rhs, z * rhs, w * rhs);
}
Quaternion f3::types::Quaternion::operator+(const Quaternion & rhs) const
{
return Quaternion(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w);
}
|
#include <EntityManager.h>
#include <ComponentManager.h>
#include <PrefabsManager.h>
#include <EntityComponentSystem.h>
#include <algorithm>
using namespace breakout;
EntityManager::EntityManager()
{
}
EntityManager::~EntityManager()
{
}
EntityManager& EntityManager::Get()
{
static EntityManager entityManager;
return entityManager;
}
int EntityManager::Create(int entityTypeId)
{
auto foundIt = m_entityTypeStorage.find(entityTypeId);
int id = m_entityIdCounter++;
if (foundIt == m_entityTypeStorage.end())
{
m_entityTypeStorage[entityTypeId] = { id };
return id;
}
foundIt->second.push_back(id);
return id;
}
void EntityManager::Delete(int entityId)
{
auto foundIt = m_entityStorage.find(entityId);
if (foundIt == m_entityStorage.end())
assert(foundIt != m_entityStorage.end());
auto& componentManager = ComponentManager::Get();
auto& prefabManager = PrefabsManager::Get();
auto& ecs = EntityComponentSystem::Get();
for (const auto& componentsIdByType : foundIt->second)
{
if (prefabManager.IsContains(entityId, componentsIdByType.second.second))
{
prefabManager.DeleteEntityId(entityId, componentsIdByType.second.second);
continue;
}
componentManager.Delete(componentsIdByType.first, componentsIdByType.second.first);
ecs.UnbindComponentUniqueId(componentsIdByType.second.second);
}
foundIt->second.clear();
m_entityStorage.erase(foundIt->first);
}
bool EntityManager::IsSameEntityType(EntityTypeId typeId, EntityId entityId) const
{
auto& foundEntityArrIt = m_entityTypeStorage.find(typeId);
assert(foundEntityArrIt != m_entityTypeStorage.end());
auto& entityArr = foundEntityArrIt->second;
return std::binary_search(entityArr.begin(), entityArr.end(), entityId);
}
bool EntityManager::IsExistEntityId(EntityId entityId) const
{
return m_entityStorage.find(entityId) != m_entityStorage.end();
}
|
//hoare's partition
#include <iostream>
using namespace std;
void swap(int arr[],int a,int b){
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
int hpartition(int arr[],int l,int h){
int pivot=arr[l];
int i=l-1;
int j=h+1;
while (true) {
do{
i++;
}
while(arr[i]<pivot);
do{
j--;
}
while(arr[j]>pivot);
if(i>=j){
return j;
}
swap(arr,i,j);
}
}
int main(int argc, char const *argv[]) {
int arr[]={4,5,6,3,8,9,10,1};
int n=sizeof(arr)/sizeof(arr[0]);
int x=hpartition(arr,0,n-1);
std::cout << "Index: "<<x<< '\n';
for (size_t i = 0; i < n; i++) {
/* code */
std::cout << arr[i] << '\t';
}
return 0;
}
|
/*
Generalized Menu Library
OpenMoco MoCoBus Core Libraries
See www.dynamicperception.com for more information
(c) 2008-2012 C.A. Church / Dynamic Perception LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "OMMenuMgr2.h"
/** Constructor
Constructs an OMMenuMgr instance, with a specified root item, and a
specified input type.
@code
#include "OMMenuMgr.h"
...
OMMenuMgr Menu = OMMenuMgr(&rootItem, MENU_ANALOG);
@endcode
@param c_first
A pointer to an OMMenuItem representing the root of the menu
@param c_type
The input type for the menu, either MENU_ANALOG or MENU_DIGITAL
*/
/*change to work with newer gcc*/
//OMMenuMgr::OMMenuMgr(OMMenuItem* c_first, uint8_t c_type) {
OMMenuMgr::OMMenuMgr(const OMMenuItem* c_first, uint8_t c_type) {
m_inputType = c_type;
// m_curParent = c_first;
m_curParent = const_cast<OMMenuItem*>(c_first);
// m_rootItem = c_first;
m_rootItem = const_cast<OMMenuItem*>(c_first);
m_inEdit = false;
m_enable = true;
m_menuActive = false;
m_curSel = 0;
m_draw = 0;
m_exit = 0;
m_holdMod = 1;
memset(m_hist, 0, sizeof(OMMenuItem*) * sizeof(m_hist));
//bcsedlon
m_inEditCnt = 0; //in value edit counter
}
/** Setup Analog Button Input
For UI's with multiple buttons assigned to a single analog pin
(e.g. using a resistor network to report different values), this
method allows you to specify how this pin shall be read.
This method is NOOP if the menu type is not MENU_ANALOG
The digital pin # is specified, along with an array of values and their meanings,
and a threshold for those values. The array of values and meanings should be two-dimensional
with two values in the second dimension, and five rows in the first dimension. The two values
shall represent the integer value of analogRead() assigned to that button, and the button type. e.g.:
@code
const int[5][2] myButtons = { {150, BUTTON_FORWARD},
{250, BUTTON_INCREASE},
{350, BUTTON_DECREASE},
{450, BUTTON_BACK},
{550, BUTTON_SELECT}
};
Menu.setAnalogButtonPin(14, myButtons, 25);
@endcode
@param p_pin
The Arduino Digital Pin to use
@param p_values
The list of button values and function
@param p_thresh
The threshold deviation from the specified value to match the button read. You must provide some
threshold, as the analogRead() values will vary. The range of value to be matched for each button
is between (value - thresh) and (value + thresh). This threshold should be large enough to account
for the variation in your circuit, but by no means should two button values overlap.
*/
void OMMenuMgr::setAnalogButtonPin(uint8_t p_pin, const int p_values[5][2], int p_thresh) {
if( m_inputType != MENU_ANALOG )
return;
m_anaPin = p_pin;
m_anaThresh = p_thresh;
for(uint8_t i = 0; i < 5; i++) {
m_butVals[i][0] = p_values[i][0];
m_butVals[i][1] = p_values[i][1];
}
pinMode(p_pin, INPUT);
digitalWrite(p_pin, HIGH);
}
/** Setup Digital Button Input
For UI's with digital button input (e.g. one digital input per button), this
method allows you to specify the pins for digital input.
An array is passed that defines, for each button, it's digital pin and function.
There must be two dimensions, with five rows and two data elements. The first data
element indicates the Arduino digital pin, and the second element indicates the function.
For example:
@code
const int[5][2] myButtons = { {4, BUTTON_FORWARD},
{5, BUTTON_INCREASE},
{6, BUTTON_DECREASE},
{7, BUTTON_BACK},
{8, BUTTON_SELECT}
};
Menu.setDigitalButtonPins(myButtons);
@endcode
@param p_values
The list of button values and functions
*/
void OMMenuMgr::setDigitalButtonPins(const int p_values[5][2]) {
if( m_inputType != MENU_DIGITAL )
return;
// set all pins as inputs, enable internal pullups
for(uint8_t i = 0; i < 5; i++ ) {
m_butVals[i][0] = p_values[i][0];
m_butVals[i][1] = p_values[i][1];
pinMode(m_butVals[i][0], INPUT);
digitalWrite(m_butVals[i][0], HIGH);
}
}
/** Set Draw Handler Callback
Sets the draw handler callback, see \ref menudisplay "Managing Display" for more
information
@param p_func
A function pointer for the draw handler
*/
void OMMenuMgr::setDrawHandler(void(*p_func)(char*, int, int, int)) {
m_draw = p_func;
}
/** Set Exit Handler Callback
Sets the exit handler callback, see \ref menudisplay "Managing Display" for more
information
@param p_func
A function pointer for the exit handler
*/
void OMMenuMgr::setExitHandler(void(*p_func)()) {
m_exit = p_func;
}
/** Menu Shown State
Whether or not the menu is currently being displayed.
@return
Whether or the menu is currently displayed (true), or not (false)
*/
bool OMMenuMgr::shown() {
return m_menuActive;
}
/** Check for User Input and Handle
Checks to see if any button has been pressed by the user, and reports back
the button pressed, or BUTTON_NONE if none are pressed.
If the menu is enabled and drawn, and any button is pressed, normal handling of the
menu is executed. If the menu is enabled, but not drawn, the menu will be drawn
only if BUTTON_SELECT is pressed. Otherwise, no activity will occur.
@return
The button pressed, one of: BUTTON_NONE, BUTTON_FORWARD, BUTTON_BACK, BUTTON_INCREASE, BUTTON_DECREASE, BUTTON_SELECT
*/
uint8_t OMMenuMgr::checkInput() {
static unsigned long lastTm = millis();
static uint8_t lastKey = BUTTON_NONE;
static uint8_t holdKey = BUTTON_NONE;
static unsigned int held = 0;
// returning to list display after being
// disabled during an action
if( m_forceReturn == true && m_enable ) {
m_forceReturn = false;
_displayList(m_curParent, m_curTarget);
}
// get which button is pressed
int key = BUTTON_NONE;
if( m_inputType == MENU_ANALOG )
key = _checkAnalog();
else
key = _checkDigital();
if( key != lastKey ) {
// did not have two reads in the row with same key,
// thus de-bouncing is not possible
lastKey = key;
holdKey = BUTTON_NONE;
lastTm = millis();
held = 0;
m_holdMod = 1;
return BUTTON_NONE;
}
// enough time for debounce?
if( millis() - lastTm > OM_MENU_DEBOUNCE )
lastTm = millis();
else
return BUTTON_NONE;
// no button is pressed, or the menu display
// is disabled
if( key == BUTTON_NONE || ! m_enable ) {
held = 0;
m_holdMod = 1;
holdKey = BUTTON_NONE;
return key;
}
// if the menu hasn't been drawn, ignore
// interaction features
if( key == BUTTON_SELECT )
m_menuActive = true;
if( ! m_menuActive )
return key;
// when a button is held, like up or down,
// we increase the modifier over time to allow
// the rate at which numbers go up/down to increase
if( key == holdKey ) {
held++;
if( held % 10 )
m_holdMod += 2;
}
else {
holdKey = key;
m_holdMod = 1;
}
_handleButton(key);
return key;
}
/** Enable or Disable Handling of Menu
You may disable handling of menu to allow the class instance to just poll and
report back the currently pressed button. This is particularly useful when
executing actions from menu items, where the user input is needed.
@param p_en
Enable (true), or disable (false) menu display
*/
void OMMenuMgr::enable(bool p_en) {
m_enable = p_en;
}
/** Get Enable Status
Returns the current enable status
@return
Enable status
*/
bool OMMenuMgr::enable() {
return m_enable;
}
/** Set New Root Item
Sets new root item as the base for future calls to checkInput();
@param p_root
A pointer to an OMMenuItem
*/
void OMMenuMgr::setRoot(OMMenuItem* p_root) {
m_rootItem = p_root;
m_curParent = p_root;
}
/** Get Hold Modifier
If a button is held by the user, the hold modifier is increased
every OM_MENU_DEBOUNCE period of time. In between these time
periods, checkInput() returns BUTTON_NONE, to prevent duplication
of input (e.g. bouncing).
By checking this value, you can determine the difference between a
button being held (hold modifier > 1) and debounced, and no button
being pressed. E.g.:
@code
byte button = Menu.checkInput();
unsigned int holdMod = Menu.holdModifier();
if( button == BUTTON_NONE && holdMod > 1 ) {
// last button press is held!
}
else if( button != BUTTON_NONE ) {
// a button is pressed for the first time, or being
// held for the first debounce cycle
}
else {
// no button is pressed at all
}
@endcode
@return
Hold modifier, >= 1
*/
unsigned int OMMenuMgr::holdModifier() {
return m_holdMod;
}
void OMMenuMgr::exitMenu() {
_exitMenu();
}
int OMMenuMgr::_checkAnalog() {
int curVal = analogRead(m_anaPin);
static int lastVal = 0;
// isolate jitter in a single cycle
if( abs(lastVal - curVal) > m_anaThresh ) {
lastVal = curVal;
return(BUTTON_NONE);
}
// check to see which analog button was read
for(byte i = 0; i < 5; i++ ) {
if( curVal > (m_butVals[i][0] - m_anaThresh) && curVal < (m_butVals[i][0] + m_anaThresh) )
return m_butVals[i][1];
}
return BUTTON_NONE;
}
int OMMenuMgr::_checkDigital() {
// check to see which analog button was read
for(byte i = 0; i < 5; i++ ) {
if( digitalRead(m_butVals[i][0]) == LOW )
return m_butVals[i][1];
}
return BUTTON_NONE;
}
void OMMenuMgr::_display(char* p_str, int p_row, int p_col, int p_count) {
if( m_draw != 0 )
m_draw(p_str, p_row, p_col, p_count);
}
// What happens when a button is pressed? Handle this activity
void OMMenuMgr::_handleButton(uint8_t p_key) {
char ch = p_key;
if( p_key == BUTTON_SELECT) { // || p_key == BUTTON_FORWARD ) {
if( m_inEdit ) {
_edit(m_curSel, CHANGE_SAVE, ch);
//_edit(m_curSel, CHANGE_SAVE);
}
else {
if( m_curSel != 0 )
_activate(m_curSel);
else
_activate(m_rootItem);
}
//bcsedlon
m_inEditCnt = 0;
return;
}
// this looks vicious compared to the code below, but it saves nearly 50 bytes of flash space by
// converting three if statements to two using ITE operators
p_key = (p_key == BUTTON_INCREASE ) ? CHANGE_UP : (p_key == BUTTON_DECREASE) ? CHANGE_DOWN : (p_key == BUTTON_BACK) ? CHANGE_ABORT : 0;
//p_key = (p_key == BUTTON_INCREASE ) ? CHANGE_UP : (p_key == BUTTON_DECREASE) ? CHANGE_DOWN : CHANGE_ABORT;
if( m_inEdit ) {
//bcsedlon
m_inEditCnt++;
_edit(m_curSel, p_key, ch);
//_edit(m_curSel, p_key);
}
else {
//bcsedlon
if(p_key == CHANGE_UP || p_key == CHANGE_DOWN || p_key == CHANGE_ABORT)
_menuNav(p_key);
//_menuNav(p_key);
}
/* else if( p_key == BUTTON_INCREASE ) {
if( m_inEdit )
_edit(m_curSel, CHANGE_UP);
else
_menuNav(CHANGE_UP);
}
else if( p_key == BUTTON_DECREASE ) {
if( m_inEdit )
_edit(m_curSel, CHANGE_DOWN);
else
_menuNav(CHANGE_DOWN);
}
else if( p_key == BUTTON_BACK ) {
if( m_inEdit )
_edit(m_curSel, CHANGE_ABORT);
else
_menuNav(CHANGE_ABORT);
}*/
}
// exiting the menu entirely
void OMMenuMgr::_exitMenu() {
m_curParent = m_rootItem;
m_curTarget = 0;
m_menuActive = false;
if( m_exit != 0 )
m_exit();
}
// navigating through menus
void OMMenuMgr::_menuNav(uint8_t p_mode) {
uint8_t childCount = pgm_read_byte(&(m_curParent->targetCount));
childCount--;
if( p_mode == CHANGE_ABORT ) {
// exiting this menu level
m_curSel = 0;
// get previous menu level
OMMenuItem* newItem = _popHist();
if( newItem == 0 ) {
// aborting at root
_exitMenu();
}
else {
m_curParent = newItem;
m_curTarget = 0;
_activate(m_curParent, true);
}
}
// this saves 20 byte of flash versus the code commented out,
// and allows wrapping from top of list to end and frome end to
// the top
else {
m_curTarget += p_mode == CHANGE_UP ? -1 : 1;
m_curTarget = (m_curTarget > childCount && m_curTarget < 255) ? 0 : m_curTarget;
m_curTarget = m_curTarget == 255 ? childCount : m_curTarget;
_displayList(m_curParent, m_curTarget);
/*
m_curTarget += p_mode == CHANGE_UP ? -1 : 1;
m_curTarget = m_curTarget > childCount ? childCount : m_curTarget;
_displayList(m_curParent, m_curTarget);
*/
}
/*else if( p_mode == CHANGE_UP ) {
// don't attempt to move above total list
if( m_curTarget == 0 )
return;
m_curTarget--;
_displayList(m_curParent, m_curTarget);
}
else if( p_mode == CHANGE_DOWN ) {
if( m_curTarget >= childCount )
return;
m_curTarget++;
_displayList(m_curParent, m_curTarget);
} */
}
// activating a menu item
void OMMenuMgr::_activate(OMMenuItem* p_item, bool p_return) {
// get item type
uint8_t type = pgm_read_byte(&(p_item->type));
// process activation based on type
if( type == ITEM_VALUE ) {
m_inEdit = true;
_displayEdit(p_item);
}
else if( type == ITEM_MENU ) {
// sub-menu
if( ! p_return && p_item != m_curParent ) {
_pushHist(m_curParent);
m_curParent = p_item;
m_curTarget = 0;
}
_displayList(p_item, m_curTarget);
}
else if( type == ITEM_ACTION ) {
// this is gnarly, dig? We're pulling a function pointer
// out of progmem
f_valueHandler callback = reinterpret_cast<f_valueHandler>( reinterpret_cast<void*>(pgm_read_word(&(p_item->target)) ));
if( callback != 0 )
callback();
if( m_enable )
_displayList(m_curParent, m_curTarget);
else
m_forceReturn = true;
}
}
// Display list rows on the screen
void OMMenuMgr::_displayList(OMMenuItem* p_item, uint8_t p_target) {
uint8_t childCount = pgm_read_byte(&(p_item->targetCount));
childCount--;
OMMenuItem** items = reinterpret_cast<OMMenuItem**>(reinterpret_cast<void*>(pgm_read_word(&(p_item->target))));
m_curSel = reinterpret_cast<OMMenuItem*>(pgm_read_word(&(items[p_target])));
// loop through display rows
for(byte i = 0; i < OM_MENU_ROWS; i++ ) {
// flush buffer
memset(m_dispBuf, ' ', sizeof(char) * sizeof(m_dispBuf));
int startX = 0;
// display cursor on first row
if( i == 0 ) {
_display((char*) OM_MENU_CURSOR, i, 0, sizeof(char) * sizeof(OM_MENU_CURSOR) - 1);
startX += ( sizeof(char) * sizeof(OM_MENU_CURSOR) - 1 );
}
else {
_display((char*) OM_MENU_NOCURSOR, i, 0, sizeof(char) * sizeof(OM_MENU_NOCURSOR) - 1);
startX += ( sizeof(char) * sizeof(OM_MENU_NOCURSOR) - 1 );
}
// if there's actually an item here, copy it to the display buffer
if( childCount >= p_target + i ) {
// OMMenuItem* item = reinterpret_cast<OMMenuItem*>( pgm_read_word(p_item->target.items[p_target + i]) );
OMMenuItem* item = reinterpret_cast<OMMenuItem*>(pgm_read_word(&(items[p_target + i])));
memcpy_P(m_dispBuf, &( item->label ), sizeof(char) * sizeof(m_dispBuf) );
}
_display(m_dispBuf, i, startX, OM_MENU_COLS);
}
}
// display a value to be edited
void OMMenuMgr::_displayEdit(OMMenuItem* p_item) {
// display label
// copy data to buffer from progmem
memcpy_P(m_dispBuf, &( p_item->label ), sizeof(char) * sizeof(m_dispBuf) );
_display(m_dispBuf, 0, 0, OM_MENU_COLS);
OMMenuValue* value = reinterpret_cast<OMMenuValue*>(reinterpret_cast<void*>(pgm_read_word(&(p_item->target))));
uint8_t type = pgm_read_byte(&(value->type));
void* valPtr = reinterpret_cast<void*>( pgm_read_word(&(value->targetValue)) );
// get current value and squirrel it away for now
// we use temporary variables to avoid all sorts of crazyness should
// we want to port to another platform later, and endianness would
// be a problem if we decided to use one large variable (ulong) and
// then use specific bytes. This takes more memory, but it seems
// a viable trade
if( type == TYPE_BYTE )
m_temp = *reinterpret_cast<uint8_t*>(valPtr);
else if( type == TYPE_UINT || type == TYPE_INT )
m_tempI = *reinterpret_cast<int*>(valPtr);
else if( type == TYPE_LONG || type == TYPE_ULONG )
m_tempL = *reinterpret_cast<long*>(valPtr);
else if( type == TYPE_SELECT ) {
// select types are interesting... We have a list of possible values and
// labels - we need to work that back to an index in the list...
OMMenuSelectValue* sel = reinterpret_cast<OMMenuSelectValue*>(valPtr);
OMMenuSelectListItem** list = reinterpret_cast<OMMenuSelectListItem**>(reinterpret_cast<void*>(pgm_read_word(&(sel->list))));
uint8_t curVal = *reinterpret_cast<uint8_t*>(pgm_read_word(&(sel->targetValue)));
uint8_t count = pgm_read_byte(&(sel->listCount));
// mark to first index by default
m_temp = 0;
// find index of current assigned value (if can be found)
for(uint8_t i = 0; i < count; i++ ) {
OMMenuSelectListItem* item = reinterpret_cast<OMMenuSelectListItem*>(pgm_read_word(&(list[i])));
uint8_t tgt = pgm_read_byte(&(item->value));
if( tgt == curVal )
m_temp = i;
}
_displaySelVal(list, m_temp);
return;
}
else if( type == TYPE_BFLAG ) {
OMMenuValueFlag* flag = reinterpret_cast<OMMenuValueFlag*>(valPtr);
uint8_t* target = reinterpret_cast<uint8_t*>(pgm_read_word(&(flag->flag)));
uint8_t pos = pgm_read_byte(&(flag->pos));
if( *target & (1 << pos) )
m_temp = 1;
else
m_temp = 0;
_displayFlagVal();
return;
}
else if( type >= TYPE_FLOAT ) // always run as last check
m_tempF = *reinterpret_cast<float*>(valPtr);
// throw number on-screen
_displayVoidNum(valPtr, type, 1, 0);
}
// rationalize a way to display any sort of number as a char*, rationalize it buddy, rationalize it good...
void OMMenuMgr::_displayVoidNum(void* p_ptr, uint8_t p_type, int p_row, int p_col) {
// clear out display buffer
memset(m_dispBuf, ' ', sizeof(char) * sizeof(m_dispBuf));
// handle variable precision for float nums
byte floatPrecision = 1;
if( p_type == TYPE_FLOAT_100 )
floatPrecision = 2;
else if( p_type == TYPE_FLOAT_1000 )
floatPrecision = 3;
if( p_type == TYPE_BYTE )
utoa(*reinterpret_cast<uint8_t*>(p_ptr), m_dispBuf, 10);
else if( p_type == TYPE_INT)
itoa(*reinterpret_cast<int*>(p_ptr), m_dispBuf, 10);
else if( p_type == TYPE_UINT )
utoa(*reinterpret_cast<unsigned int*>(p_ptr), m_dispBuf, 10);
else if( p_type == TYPE_LONG)
ltoa(*reinterpret_cast<long*>(p_ptr), m_dispBuf, 10);
else if( p_type == TYPE_ULONG )
ultoa(*reinterpret_cast<unsigned long*>(p_ptr), m_dispBuf, 10);
else if( p_type >= TYPE_FLOAT )
dtostrf(*reinterpret_cast<float*>(p_ptr), floatPrecision + 2, floatPrecision, m_dispBuf);
_display(m_dispBuf, p_row, p_col, sizeof(char) * sizeof(m_dispBuf));
}
// handle modifying temp values based on their type
void OMMenuMgr::_modifyTemp(uint8_t p_type, uint8_t p_mode, long p_min, long p_max, char ch) {
//void OMMenuMgr::_modifyTemp(uint8_t p_type, uint8_t p_mode, long p_min, long p_max) {
//Serial.println(ch);
void* tempNum;
int mod = ( p_mode == MODE_INCREMENT ) ? 1 : -1;
// apply holding rate mod
mod *= m_holdMod;
// handle float precision adjustment
float fmod = (float) mod;
if( p_type == TYPE_FLOAT_10 )
fmod /= 10.0;
else if( p_type == TYPE_FLOAT_100 )
fmod /= 100.0;
else if( p_type == TYPE_FLOAT_1000 )
fmod /= 1000.0;
/*
// manage correct temporary variable change based on type
// and apply floor/ceiling from min/max
if( p_type == TYPE_BYTE ) {
m_temp += mod;
if( p_min != 0 || p_max != 0 )
m_temp = m_temp > p_max ? p_max : ( m_temp < p_min ? p_min : m_temp );
tempNum = reinterpret_cast<void*>(&m_temp);
}
else if( p_type == TYPE_INT ) {
m_tempI += mod;
if( p_min != 0 || p_max != 0 )
m_tempI = m_tempI > p_max ? p_max : ( m_tempI < p_min ? p_min : m_tempI );
tempNum = reinterpret_cast<void*>(&m_tempI);
}
else if( p_type == TYPE_UINT ) {
*reinterpret_cast<unsigned int*>(&m_tempI) += mod;
if( p_min != 0 || p_max != 0 )
m_tempI = m_tempI > p_max ? p_max : ( m_tempI < p_min ? p_min : m_tempI );
tempNum = reinterpret_cast<void*>(&m_tempI);
}
else if( p_type == TYPE_LONG ) {
m_tempL += mod;
if( p_min != 0 || p_max != 0 )
m_tempL = m_tempL > p_max ? p_max : ( m_tempL < p_min ? p_min : m_tempL );
tempNum = reinterpret_cast<void*>(&m_tempL);
}
else if( p_type == TYPE_ULONG ) {
*reinterpret_cast<unsigned long*>(&m_tempL) += mod;
if( p_min != 0 || p_max != 0 )
m_tempL = m_tempL > p_max ? p_max : ( m_tempL < p_min ? p_min : m_tempL );
tempNum = reinterpret_cast<void*>(&m_tempL);
}
else if( p_type >= TYPE_FLOAT ) {
m_tempF += fmod;
if( p_min != 0 || p_max != 0 )
m_tempF = m_tempF > p_max ? p_max : ( m_tempF < p_min ? p_min : m_tempF );
tempNum = reinterpret_cast<void*>(&m_tempF);
}
*/
//bcsedlon
if(ch == 3 || ch == 4) { //MODE_INCREMENT MODE_DECREMENT
m_inEditCnt = 0;
//m_tempI += mod;
m_tempF += fmod;
}
else {
mod = 0;
fmod = 0;
}
//Serial.println(int(ch));
//Serial.println(int(p_mode));
if(ch == 'C')
m_temp = m_tempI = m_tempL = m_tempF = 0;
else if(ch == BUTTON_FORWARD) {
m_temp *= -1;
m_tempI *= -1;
m_tempL *= -1;
m_tempF *= (float)-1.0;
}
else {
ch -= 48;
if(ch >= 0 && ch <= 9) {
if(m_inEditCnt > 1) {
m_temp *= 10;
m_tempI *= 10;
m_tempL *= 10;
m_tempF *= (float)10.0;
}
if(m_inEditCnt == 1) {
m_temp = m_tempI = m_tempL = 0;
m_tempF = (float)0.0;
}
m_temp += ch;
m_tempI += ch;
m_tempL += ch;
//m_tempF += (float)ch;
if( p_type == TYPE_FLOAT_10 )
m_tempF += (float)ch / 10.0;
else if( p_type == TYPE_FLOAT_100 )
m_tempF += (float)ch / 100.0;
else if( p_type == TYPE_FLOAT_1000 )
m_tempF += (float)ch / 1000.0;
}
}
/*
Serial.println(m_temp);
Serial.println(m_tempI);
Serial.println(m_tempL);
Serial.println(m_tempF);
Serial.println();
*/
// manage correct temporary variable change based on type
// and apply floor/ceiling from min/max
if( p_type == TYPE_BYTE ) {
m_temp += mod;
if( p_min != 0 || p_max != 0 )
m_temp = m_temp > p_max ? p_max : ( m_temp < p_min ? p_min : m_temp );
tempNum = reinterpret_cast<void*>(&m_temp);
}
else if( p_type == TYPE_INT ) {
m_tempI += mod;
if( p_min != 0 || p_max != 0 )
m_tempI = m_tempI > p_max ? p_max : ( m_tempI < p_min ? p_min : m_tempI );
tempNum = reinterpret_cast<void*>(&m_tempI);
}
else if( p_type == TYPE_UINT ) {
*reinterpret_cast<unsigned int*>(&m_tempI) += mod;
if( p_min != 0 || p_max != 0 )
m_tempI = m_tempI > p_max ? p_max : ( m_tempI < p_min ? p_min : m_tempI );
tempNum = reinterpret_cast<void*>(&m_tempI);
}
else if( p_type == TYPE_LONG ) {
m_tempL += mod;
if( p_min != 0 || p_max != 0 )
m_tempL = m_tempL > p_max ? p_max : ( m_tempL < p_min ? p_min : m_tempL );
tempNum = reinterpret_cast<void*>(&m_tempL);
}
else if( p_type == TYPE_ULONG ) {
*reinterpret_cast<unsigned long*>(&m_tempL) += mod;
if( p_min != 0 || p_max != 0 )
m_tempL = m_tempL > p_max ? p_max : ( m_tempL < p_min ? p_min : m_tempL );
tempNum = reinterpret_cast<void*>(&m_tempL);
}
else if( p_type >= TYPE_FLOAT ) {
//m_tempF += fmod;
if( p_min != 0 || p_max != 0 )
m_tempF = m_tempF > p_max ? p_max : ( m_tempF < p_min ? p_min : m_tempF );
tempNum = reinterpret_cast<void*>(&m_tempF);
}
/*
Serial.println(m_temp);
Serial.println(m_tempI);
Serial.println(m_tempL);
Serial.println(m_tempF);
Serial.println('-');
*/
// display new temporary value
_displayVoidNum(tempNum, p_type, 1, 0);
}
// display the label value from a select list on the screen
void OMMenuMgr::_displaySelVal(OMMenuSelectListItem** p_list, uint8_t p_idx) {
// clear out display buffer
memset(m_dispBuf, ' ', sizeof(char) * sizeof(m_dispBuf));
// get the actual select list item
OMMenuSelectListItem* item = reinterpret_cast<OMMenuSelectListItem*>(pgm_read_word(&(p_list[p_idx])));
// copy the label contents from flash to the buffer
memcpy_P(m_dispBuf, &( item->label ), sizeof(char) * OM_MENU_LBLLEN );
// display the buffer
_display(m_dispBuf, 1, 0, sizeof(char) * sizeof(m_dispBuf));
}
// modifying a select type value - we cycle through a list of
// values by cycling list index...
void OMMenuMgr::_modifySel(OMMenuValue* p_value, uint8_t p_mode) {
OMMenuSelectValue* sel = reinterpret_cast<OMMenuSelectValue*>(pgm_read_word(&(p_value->targetValue)));
uint8_t count = pgm_read_byte(&(sel->listCount));
OMMenuSelectListItem** list = reinterpret_cast<OMMenuSelectListItem**>(reinterpret_cast<void*>(pgm_read_word(&(sel->list))));
count--;
if( p_mode == MODE_DECREMENT ) {
if(m_temp == 0)
m_temp = count;
else
m_temp--;
}
else if( p_mode == MODE_INCREMENT ) {
if(m_temp == count)
m_temp = 0;
else
m_temp++;
}
_displaySelVal(list, m_temp);
}
// displaying flag parameters
void OMMenuMgr::_displayFlagVal() {
// overwrite buffer
memset(m_dispBuf, ' ', sizeof(char) * sizeof(m_dispBuf));
if( m_temp == 1 )
memcpy(m_dispBuf, (char*) OM_MENU_FLAG_ON, sizeof(char) * sizeof(OM_MENU_FLAG_ON) - 1);
else
memcpy(m_dispBuf, (char*) OM_MENU_FLAG_OFF, sizeof(char) * sizeof(OM_MENU_FLAG_OFF) - 1);
_display(m_dispBuf, 1, 0, sizeof(char) * sizeof(m_dispBuf));
}
// edit operations against a displayed value
void OMMenuMgr::_edit(OMMenuItem* p_item, uint8_t p_type, char ch) {
//void OMMenuMgr::_edit(OMMenuItem* p_item, uint8_t p_type) {
OMMenuValue* thisValue = reinterpret_cast<OMMenuValue*>(pgm_read_word(&(p_item->target)));
uint8_t type = pgm_read_byte(&(thisValue->type));
long min = pgm_read_dword(&(thisValue->min));
long max = pgm_read_dword(&(thisValue->max));
uint8_t mode = (p_type == CHANGE_UP) ? MODE_INCREMENT : MODE_DECREMENT;
if( p_type == CHANGE_ABORT ) {
m_inEdit = false;
_activate(m_curParent, true);
}
else if( p_type == CHANGE_UP || p_type == CHANGE_DOWN || p_type == MODE_NOOP || p_type == 0) {
//else if( p_type == CHANGE_UP || p_type == CHANGE_DOWN || p_type == MODE_NOOP ) {
if( type == TYPE_SELECT ) {
_modifySel(thisValue, mode);
}
else if( type == TYPE_BFLAG ) {
m_temp = (m_temp == 1) ? 0 : 1;
_displayFlagVal();
}
else {
_modifyTemp(type, mode, min, max, ch);
}
//_modifyTemp(type, mode, min, max);
}
else if( p_type == CHANGE_SAVE ) {
void* ptr = reinterpret_cast<void*>(pgm_read_word(&(thisValue->targetValue)));
if( type == TYPE_SELECT ) {
// select is more special than the rest, dig?
// some what convoluted - we get the value stored in the current index (in m_temp) from the list,
// and store it in the byte pointer provided attached to the OMMenuSelectValue
OMMenuSelectValue* sel = reinterpret_cast<OMMenuSelectValue*>(ptr);
OMMenuSelectListItem** list = reinterpret_cast<OMMenuSelectListItem**>(reinterpret_cast<void*>(pgm_read_word(&(sel->list))));
OMMenuSelectListItem* item = reinterpret_cast<OMMenuSelectListItem*>(pgm_read_word(&(list[m_temp])));
uint8_t newVal = pgm_read_byte(&(item->value));
uint8_t* real = reinterpret_cast<uint8_t*>(pgm_read_word(&(sel->targetValue)));
*real = newVal;
_eewrite<uint8_t>(thisValue, newVal);
}
else if( type == TYPE_BFLAG) {
// bflag is special too, we want to set a specific bit based on the current temp value
OMMenuValueFlag* flag = reinterpret_cast<OMMenuValueFlag*>(ptr);
uint8_t* target = reinterpret_cast<uint8_t*>(pgm_read_word(&(flag->flag)));
uint8_t pos = pgm_read_byte(&(flag->pos));
if( m_temp )
*target |= (1 << pos);
else
*target &= (0xFF ^ (1 << pos));
_eewrite<uint8_t>(thisValue, *target);
}
else if( type == TYPE_BYTE) {
*reinterpret_cast<uint8_t*>(ptr) = m_temp;
_eewrite<uint8_t>(thisValue, *reinterpret_cast<uint8_t*>(ptr));
}
else if( type == TYPE_UINT) {
*reinterpret_cast<unsigned int*>(ptr) = *reinterpret_cast<unsigned int*>(&m_tempI);
_eewrite<unsigned int>(thisValue, *reinterpret_cast<unsigned int*>(ptr));
}
else if( type == TYPE_INT ) {
*reinterpret_cast<int*>(ptr) = m_tempI;
_eewrite<int>(thisValue, *reinterpret_cast<int*>(ptr));
}
else if( type == TYPE_ULONG ) {
*reinterpret_cast<unsigned long*>(ptr) = *reinterpret_cast<unsigned long*>(&m_tempL);
_eewrite<unsigned long>(thisValue, *reinterpret_cast<unsigned long*>(ptr));
}
else if( type == TYPE_LONG ) {
*reinterpret_cast<long*>(ptr) = m_tempL;
_eewrite<long>(thisValue, *reinterpret_cast<long*>(ptr));
}
else if( type >= TYPE_FLOAT ) {
*reinterpret_cast<float*>(ptr) = m_tempF;
_eewrite<float>(thisValue, *reinterpret_cast<float*>(ptr));
}
m_inEdit = false;
_activate(m_curParent, true);
}
}
// add a menu level to the history
void OMMenuMgr::_pushHist(OMMenuItem* p_item) {
// note that if you have no room left, you'll lose this
// item - we only store up to MAXDEPTH
for(uint8_t i = 0; i < OM_MENU_MAXDEPTH; i++) {
if( m_hist[i] == 0 ) {
m_hist[i] = p_item;
return;
}
}
}
// remove the latest menu item from the history and return it
OMMenuItem* OMMenuMgr::_popHist() {
// work backwards, remove the first non-zero pointer
// and return it
for(uint8_t i = OM_MENU_MAXDEPTH; i > 0; i--) {
if( m_hist[i-1] != 0 ) {
OMMenuItem* item = m_hist[i-1];
m_hist[i-1] = 0;
return item;
}
}
return 0;
}
|
// FileDialogEx.cpp : 实现文件
//
#include "stdafx.h"
#include "CmnDlg.h"
#include "FileDialogEx.h"
// CFileDialogEx
IMPLEMENT_DYNAMIC(CFileDialogEx, CFileDialog)
CFileDialogEx::CFileDialogEx(BOOL bOpenFileDialog, LPCTSTR lpszDefExt, LPCTSTR lpszFileName,
DWORD dwFlags, LPCTSTR lpszFilter, CWnd* pParentWnd) :
CFileDialog(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd)
{
}
CFileDialogEx::~CFileDialogEx()
{
}
BEGIN_MESSAGE_MAP(CFileDialogEx, CFileDialog)
END_MESSAGE_MAP()
// CFileDialogEx 消息处理程序
BOOL CFileDialogEx::OnInitDialog()
{
CFileDialog::OnInitDialog();
char szText[120];
const UINT iExtraSize = 50;
CWnd *wndDlg = GetParent();
RECT Rect;
wndDlg->GetWindowRect(&Rect);
wndDlg->SetWindowPos(NULL, 0, 0,
Rect.right - Rect.left,
Rect.bottom - Rect.top + iExtraSize,
SWP_NOMOVE);
CWnd *wndComboCtrl = wndDlg->GetDlgItem(cmb1);
wndComboCtrl->GetWindowRect(&Rect);
wndDlg->ScreenToClient(&Rect);
Rect.top += 60;
Rect.bottom += 120;
Rect.left += 50;
m_Combo.Create(WS_CHILD | WS_VISIBLE | CBS_DROPDOWN | CBS_SORT | WS_VSCROLL | WS_TABSTOP, Rect, wndDlg, IDC_MYCOMBOBOX);
m_Combo.SetFont(wndComboCtrl->GetFont(), TRUE);
m_Combo.SetFocus();
CWnd *wndStaticCtrl = wndDlg->GetDlgItem(stc2);
wndStaticCtrl->GetWindowRect(&Rect);
wndDlg->ScreenToClient(&Rect);
Rect.top += 60;
Rect.bottom += 80;
Rect.right += 40;
char* szStr1 = "eYas";
WCHAR wszClassName1[256];
memset(wszClassName1, 0, sizeof(wszClassName1));
MultiByteToWideChar(CP_ACP, 0, szStr1, strlen(szStr1) + 1, wszClassName1, sizeof(wszClassName1) / sizeof(wszClassName1[0]));
m_Static.Create(wszClassName1, WS_CHILD | WS_VISIBLE, Rect, wndDlg, IDC_MYSTATIC);
m_Static.SetFont(wndComboCtrl->GetFont(), TRUE);
for (int i = 0; i < 3; i++)
{
sprintf_s(szText, "MyType%d", i);
wndDlg->SendDlgItemMessageW(IDC_MYCOMBOBOX, CB_INSERTSTRING, (WPARAM)(-1), (LPARAM)(szText));
char* szStr1 = szText;
WCHAR wszClassName1[256];
memset(wszClassName1, 0, sizeof(wszClassName1));
MultiByteToWideChar(CP_ACP, 0, szStr1, strlen(szStr1) + 1, wszClassName1, sizeof(wszClassName1) / sizeof(wszClassName1[0]));
if (m_nMyType == i)
wndDlg->SetDlgItemTextW(IDC_MYCOMBOBOX, wszClassName1);
}
sprintf_s(szText, "My File Type");
szStr1 = szText;
memset(wszClassName1, 0, sizeof(wszClassName1));
MultiByteToWideChar(CP_ACP, 0, szStr1, strlen(szStr1) + 1, wszClassName1, sizeof(wszClassName1) / sizeof(wszClassName1[0]));
wndDlg->SetDlgItemTextW(IDC_MYSTATIC, wszClassName1);
return TRUE;
}
BOOL CFileDialogEx::OnDestroy()
{
CFileDialog::OnDestroy();
char szText[40];
WCHAR wszClassName1[256];
memset(wszClassName1, 0, sizeof(wszClassName1));
MultiByteToWideChar(CP_ACP, 0, szText, strlen(szText) + 1, wszClassName1, sizeof(wszClassName1) / sizeof(wszClassName1[0]));
if (GetParent()->GetDlgItemText(IDC_MYCOMBOBOX, wszClassName1, sizeof(wszClassName1)) > 0)
{
m_nMyType = szText[strlen(szText) - 1] - '0';
}
return TRUE;
}
|
#pragma once
#include <glm/glm.hpp>
class Program
{
public:
~Program();
GLuint getID() const {return id_;}
void load(const std::string& vertexPath, const std::string& fragmentPath);
void setUniform1i(const std::string& name, int val);
void setUniform1f(const std::string& name, float val);
void setUniformVec2(const std::string& name, const glm::vec2& val);
void setUniformVec3(const std::string& name, const glm::vec3& val);
void setUniformTexture(const std::string& name, GLuint tx, GLenum txLevel);
void setUniformCubemapTexture(const std::string& name, GLuint tx, GLenum txLevel);
private:
GLuint id_;
};
|
// Initialize Variables
float pot1 = 0;
float pot2 = 0;
int DesiredSteeringAngle = 0;
int past_steering_angle =0;
int wire_switch = 4;
int PistonState = 0;
unsigned long time_now = 0;
int period = 0;
int period_off = 100;
void setup() {
Serial.begin(9600);
// Configure pullup input resistor to digital pin 4
pinMode(wire_switch,INPUT_PULLUP);
}
void loop() {
// Reads in the values from the potentiometers
pot1 = analogRead(A0);
pot2 = analogRead(A1);
DesiredSteeringAngle = (pot1*120/1023-60) * -1;
// 4 States with three varying speeds, when pot 2 is all the way CCW, piston state = 0 and car does not move
// Off State, no motion
if(pot2 > 1000){
PistonState = 0;
}
// Slow Speed
if(pot2 <= 1000 && pot2 > 666){
period = 600;
if(millis() >= time_now + period && PistonState == 1){
time_now += period;
PistonState = 0;
}
if(millis() >= time_now + period_off && PistonState ==0){
time_now += period_off;
PistonState = 1;
}
}
// Mid Speed
if(pot2 <= 666 && pot2 > 333){
period = 300;
if(millis() >= time_now + period && PistonState == 1){
time_now += period;
PistonState = 0;
}
if(millis() >= time_now + period_off && PistonState ==0){
time_now += period_off;
PistonState = 1;
}
}
// Full Speed
if(pot2 <= 333){
period = 150;
if(millis() >= time_now + period && PistonState == 1){
time_now += period;
PistonState = 0;
}
if(millis() >= time_now + period_off && PistonState ==0){
time_now += period_off;
PistonState = 1;
}S
}
// Kill switch, if wire in digital pin 4 is plugged into ground
if(digitalRead(wire_switch) == 0){
DesiredSteeringAngle = 666;
PistonState = 666;
}
Serial.print(PistonState);
Serial.print(" ");
Serial.println(DesiredSteeringAngle);
}
|
//
// DlibInterface.h
// Author: Michael Bao
// Date: 9/6/2015
//
#pragma once
#include "shared/internal/InternalInterface.h"
#include "dlib/opencv/cv_image.h"
#include "dlib/opencv/to_open_cv.h"
template<typename ImagePixelType>
class DlibInterface: public InternalInterface<dlib::cv_image<ImagePixelType>>
{
public:
static dlib::cv_image<ImagePixelType> ConvertImageToInternalRepresentation(cv::Mat inputImage)
{
dlib::cv_image<ImagePixelType> newImage(inputImage);
return newImage;
}
static cv::Mat ConvertInternalRepresentationToCV(dlib::cv_image<ImagePixelType> inputImage)
{
return dlib::toMat(inputImage);
}
};
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifndef USE_ABOUT_FRAMEWORK
#include "platforms/unix/product/aboutopera.h"
#undef AboutOpera // avoid core-2's bodge messing us up here ...
#include "modules/locale/oplanguagemanager.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "modules/url/uamanager/ua.h"
#include "modules/url/url2.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/prefs/prefsmanager/collections/pc_app.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/prefs/prefsmanager/collections/pc_js.h"
#include "modules/dom/domenvironment.h"
#include "platforms/posix/posix_native_util.h"
#include "platforms/unix/product/config.h"
#ifndef op_strlen
# define op_strlen strlen
#endif
#include <unistd.h> // F_OK for access()
/* <config> Misc configuration defines for this file: */
#if 0 // 1 chose; shall we htmlify registered user and organisation ?
// apparently this causes some problems with cyrillic text - ask Espen.
# include "modules/util/htmlify.h"
# define HTMLIFY_REGISTRANT
#endif // decide whether to htmlify
#define SHOW_USER_AGENT
/* </config> */
namespace { // Local: first the oft-repeated templates (to avoid repetion of UNI_L(...)):
void outASCII( URL& url, const char *txt )
{
/* Use like url.WriteDocumentData(UNI_L(txt)) but without restricting
* txt to be a single string token, without concatenation, as UNI_L
* does. For short texts, the UNI_L form is preferable.
*/
size_t len = op_strlen(txt);
OpString temp; // outside loop, so we only Grow() it once.
while (len > 0)
{
const int chunk = MIN(len, 80);
temp.Set(txt, chunk);
url.WriteDocumentData(temp.CStr());
len -= chunk;
txt += chunk;
}
}
void outRow( URL& url, OpString& name, OpString& value )
{
if (name.HasContent())
{
url.WriteDocumentData(UNI_L("\n <dt>"));
url.WriteDocumentData(name.CStr());
url.WriteDocumentData(UNI_L("</dt>"));
}
url.WriteDocumentData(UNI_L("<dd>"));
if (value.HasContent())
url.WriteDocumentData(value.CStr());
url.WriteDocumentData(UNI_L("</dd>"));
}
void outHeading( URL& url, OpString& heading )
{
url.WriteDocumentData(UNI_L("\n <h2>"));
url.WriteDocumentData(heading.CStr());
url.WriteDocumentData(UNI_L("</h2>\n"));
}
};
// Export:
void AboutOpera::generateData( URL& url )
{
writePreamble( url ); // <html><body> surplus
// <require> each of these should close exactly the HTML tags it opens:
writeVersion( url );
writeUA( url );
writeRegInfo( url );
writePaths( url );
writeSound( url );
writeCredits( url );
// </require>
url.WriteDocumentData(UNI_L("\n\n <address>"));
#ifdef GEIR_MEMORIAL
OP_STATUS rc;
OpString span;
TRAP(rc, g_languageManager->GetStringL(Str::S_DEDICATED_TO, span));
if (OpStatus::IsSuccess(rc))
{
url.WriteDocumentData(UNI_L("<span>"));
// In memory of Geir Ivarsøy.
url.WriteDocumentData(span);
url.WriteDocumentData(UNI_L("</span> "));
}
#endif
outASCII(url, "Copyright © 1995-");
outASCII(url, __DATE__ + 7); // "Mmm dd Year" + 7 == "Year"
outASCII(url, " Opera Software ASA.\n"
"All rights reserved.</address>\n"
"</body>\n</html>\n");
url.WriteDocumentDataFinished();
}
// Private: logical components of the generated data:
void AboutOpera::writePreamble( URL& url )
{
OP_STATUS rc = url.SetAttribute(URL::KMIME_ForceContentType, "text/html;charset=utf-16");
// FIXME: OOM - rc is discarded
uni_char bom = 0xfeff; // unicode byte order mark
url.WriteDocumentData(&bom, 1);
outASCII(url,
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n"
"<html>\n<head>\n <title>");
OpString tmp;
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_ABOUT, tmp));
if (!OpStatus::IsSuccess(rc)) tmp.Set("About Opera");
url.WriteDocumentData(tmp.CStr());
url.WriteDocumentData(UNI_L("</title>\n"));
// Don't mess with tmp until we've re-used it as H1's content
// Style sheet, if any:
OpString pref;
OpFile f;
TRAP(rc, g_pcfiles->GetFileL(PrefsCollectionFiles::StyleAboutFile, f));
if (OpStatus::IsSuccess(rc)) rc = pref.Set(f.GetFullPath());
if (OpStatus::IsSuccess(rc))
{
url.WriteDocumentData(UNI_L(" <link rel=\"stylesheet\" href=\"file://localhost"));
if (pref.FindFirstOf('/') != 0) url.WriteDocumentData(UNI_L("/"));
url.WriteDocumentData(pref.CStr());
url.WriteDocumentData(UNI_L("\" media=\"screen,projection,tv,handheld,print\">\n"));
}
url.WriteDocumentData(UNI_L("</head>\n<body>\n"));
url.WriteDocumentData(UNI_L("<h1>"));
url.WriteDocumentData(tmp.CStr());
url.WriteDocumentData(UNI_L("</h1>\n"));
// Splash image, "<IMG SRC=\"file://localhost/...\">\n", if any.
if (OpStatus::IsSuccess(getSplashImageURL( tmp )))
{
url.WriteDocumentData(UNI_L(" <img src=\""));
url.WriteDocumentData(tmp.CStr());
url.WriteDocumentData(UNI_L("\">\n"));
}
}
void AboutOpera::writeVersion( URL& url )
{
OP_STATUS rc;
OpString tmp;
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDSTR_ABT_VER_INFO_STR, tmp));
if (OpStatus::IsSuccess(rc)) outHeading(url, tmp);
url.WriteDocumentData(UNI_L(" <dl>"));
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDSTR_ABT_VER_STR, tmp));
if (OpStatus::IsSuccess(rc))
{
OpString val;
rc = GetVersion(&val);
if (OpStatus::IsSuccess(rc))
outRow(url, tmp, val);
}
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDSTR_ABT_BUILD_STR, tmp));
if (OpStatus::IsSuccess(rc))
{
OpString val;
rc = GetBuild(&val);
if (OpStatus::IsSuccess(rc))
outRow(url, tmp, val);
}
OpString name;
rc = getPlatformDetails(name, tmp);
if (OpStatus::IsSuccess(rc))
{
OpString label;
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDSTR_ABT_PLATFORM_STR, label));
if (OpStatus::IsSuccess(rc)) // platform
outRow(url, label, name);
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDSTR_ABT_WIN_VER, label));
if (OpStatus::IsSuccess(rc)) // platform version
outRow(url, label, tmp);
}
rc = getToolkitDetails(name, tmp);
if (OpStatus::IsSuccess(rc))
outRow(url, name, tmp);
if (OpStatus::IsSuccess(getJavaVersion( name, tmp )))
outRow(url, name, tmp);
url.WriteDocumentData(UNI_L("\n </dl>\n"));
}
void AboutOpera::writeUA( URL& url )
{
#ifdef SHOW_USER_AGENT
OpString tmp;
TRAPD(rc, g_languageManager->GetStringL(Str::DI_IDLABEL_BROWSERIDENT, tmp));
if (OpStatus::IsSuccess(rc))
{
char useragent[1024];
if (g_uaManager->GetUserAgentStr(useragent, sizeof(useragent),
UA_NotOverridden))
{
OpString val;
rc = val.Set(useragent);
if (OpStatus::IsSuccess(rc))
{
outHeading(url, tmp);
url.WriteDocumentData(UNI_L(" <p>"));
url.WriteDocumentData(val.CStr());
url.WriteDocumentData(UNI_L("</p>\n"));
}
}
}
#endif // SHOW_USER_AGENT
}
void AboutOpera::writePaths( URL& url )
{
OpString type, name;
TRAPD(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_OPERASYSINFO, name));
if (OpStatus::IsSuccess(rc)) outHeading(url, name);
url.WriteDocumentData(UNI_L(" <dl>"));
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_SETTINGS, type));
// This code makes the assumption that we're using PrefsFile and OpFile
# ifdef PREFS_READ
PrefsFile *prefsfile = (PrefsFile *) g_prefsManager->GetReader();
OpFile *inifile = (OpFile *) prefsfile->GetFile();
rc = name.Set(inifile->GetFullPath());
# else
rc = OpStatus::ERR_NOT_SUPPORTED;
# endif
if (OpStatus::IsSuccess(rc))
{
cleanPath(name);
outRow(url, type, name);
}
#ifdef AUTOSAVE_WINDOWS
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_DEFAULTWINFILE, type));
if (OpStatus::IsSuccess(rc))
{
OpFile f;
TRAP(rc, g_pcfiles->GetFileL(PrefsCollectionFiles::WindowsStorageFile, f));
if (OpStatus::IsSuccess(rc)) rc = name.Set(f.GetFullPath());
if (OpStatus::IsSuccess(rc))
{
cleanPath(name);
outRow(url, type, name);
}
}
#endif // AUTOSAVE_WINDOWS
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_HOTLISTFILE, type));
if (OpStatus::IsSuccess(rc))
{
OpFile f;
TRAP(rc, g_pcfiles->GetFileL(PrefsCollectionFiles::HotListFile, f));
if (OpStatus::IsSuccess(rc)) rc = name.Set(f.GetFullPath());
if (OpStatus::IsSuccess(rc))
{
cleanPath(name);
outRow(url, type, name);
}
}
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_OPERADIRECTORY, type));
if (OpStatus::IsSuccess(rc))
{
rc = g_folder_manager->GetFolderPath(OPFILE_HOME_FOLDER, name);
if (OpStatus::IsSuccess(rc))
{
cleanPath(name, TRUE);
outRow(url, type, name);
}
}
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_CACHEDIR, type));
if (OpStatus::IsSuccess(rc))
{
rc = g_folder_manager->GetFolderPath(OPFILE_CACHE_FOLDER, name);
if (OpStatus::IsSuccess(rc))
{
cleanPath(name, TRUE);
outRow(url, type, name);
}
}
#ifdef M2_SUPPORT
TRAP(rc, g_languageManager->GetStringL(Str::S_IDABOUT_HELPDIR, type)); // HELPDIR -> MAILDIR maybe
if (OpStatus::IsSuccess(rc))
{
rc = g_folder_manager->GetFolderPath(OPFILE_MAIL_FOLDER, name);
if (OpStatus::IsSuccess(rc))
{
cleanPath(name, TRUE);
outRow(url, type, name);
}
}
#endif // M2_SUPPORT
if (OpStatus::IsSuccess(getHelpDir(name)))
{
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_HELPDIR, type));
if (OpStatus::IsSuccess(rc))
{
cleanPath(name, TRUE);
outRow(url, type, name);
}
}
// Plugin path:
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_PLUGINPATH, type));
if (OpStatus::IsSuccess(rc))
{
rc = name.Set(g_pcapp->GetStringPref(PrefsCollectionApp::PluginPath));
if (!OpStatus::IsSuccess(rc)) name.Empty();
while (name.Length())
{
int col = name.FindFirstOf(':');
if (col == KNotFound)
{
cleanPath(name, TRUE);
outRow(url, type, name);
name.Empty();
}
else
{
OpString nom;
if (OpStatus::IsSuccess(nom.Set(name.CStr(), col)))
{
cleanPath(nom, TRUE);
outRow(url, type, nom);
}
// else: silent OOM :-(
name.Delete(0, col+1);
}
type.Empty(); // only say "Plugin path:" on first row.
}
#if 0 // 1 do we want to mention plugin path even if empty ? Moose prefers not in bug #206083.
if (type.Length())
{
OP_ASSERT(name.IsEmpty());
outRow(url, type, name); // name is empty, which is what we want here ...
}
#endif // mention plugin path even if empty
}
#ifdef USER_JAVASCRIPT
TRAP(rc, g_languageManager->GetStringL(Str::S_IDABOUT_USERJSFILE, type));
if (OpStatus::IsSuccess(rc))
{
name.SetL(g_pcjs->GetStringPref(PrefsCollectionJS::UserJSFiles));
/* This preference can be a comma-joined sequence of tokens, each of
* which is a directory or file and may have arbitrarily many ;-suffixes
* which may be either greasemonkey or opera (other things may be added
* to this list in future). For now (2005/May, O8) this is unofficial -
* users are told it's just a single file or directory name - so we can
* just display it "as is"; but we'll eventually need to parse it as
* above and display it nicely.
*/
PosixNativeUtil::NativeString native_path (name.CStr());
if (native_path.get() && access(native_path.get(), F_OK) == 0)
{
cleanPath(name, FALSE);
outRow(url, type, name);
}
}
#endif // USER_JAVASCRIPT
#ifdef PREFS_USE_CSS_FOLDER_SCAN
TRAP(rc, g_languageManager->GetStringL(Str::S_USER_CSS_LABEL, type));
if (OpStatus::IsSuccess(rc))
{
OpString tmp_storage;
name.Set(g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_USERPREFSSTYLE_FOLDER, tmp_storage));
cleanPath(name, FALSE);
outRow(url, type, name);
}
#endif // PREFS_USE_CSS_FOLDER_SCAN
url.WriteDocumentData(UNI_L("\n </dl>\n"));
}
void AboutOpera::writeSound( URL& url )
{
OpString hdr, txt;
OP_STATUS st = getSoundDoc( hdr, txt );
if (OpStatus::IsSuccess(st))
{
outHeading(url, hdr);
url.WriteDocumentData(txt.CStr());
}
}
void AboutOpera::writeCredits( URL& url )
{
// #if the UL below is going to get any content
OpString tmp;
TRAPD(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_INCLUDESFROM, tmp));
if (!OpStatus::IsSuccess(rc)) tmp.Set("Third Parties");
outHeading(url, tmp);
/* The following probably all need to be reviewed periodically for
* up-to-date and relevant; in particular, more of them should be #if'd on
* suitable conditions matching whether or not the relevant credit is
* warranted in the present build (c.f. the number<->string one). See the
* developer Wiki's Third_party_code page for authoritative details: *
* https://ssl.opera.com:8008/developerwiki/index.php/Third_party_code
*
* Note, however, that UNI_L() may be a macro and the C preprocessor has
* undefined behaviour if any preprocessor directives appear within a macro
* argument: so you *should not* try to do #if'ing within a single UNI_L()'s
* argument string. Furthermore, since we want the following to be portable
* between platforms with UNI_L either as macro or mediated by unil_convert,
* we can't do string concatenation with UNI_L()s; macro form can't cope
* with several strings inside one UNI_L - TODO: as used below - while the
* unil_convert version breaks if we try to use several adjacent UNI_L()s.
*/
outASCII(
url,
" <ul>\n"
#ifdef MDE_AGFA_SUPPORT
" <li>This product includes software developed by Monotype Imaging Inc.\n"
"Copyright © 2005 Monotype Imaging Inc.<a\n"
"href=\"http://www.monotypeimaging.com\">Monotype Imageing</a></li>\n"
#endif // MDE_AGFA_SUPPORT
#if defined(_NATIVE_SSL_SUPPORT_)
" <li>This product includes software developed by the OpenSSL Project for\n"
" use in the OpenSSL Toolkit. Copyright © 1998-2001\n"
" <a href=\"http://www.openssl.org/\">The OpenSSL Project</a>.\n"
" All rights reserved.</li>\n"
" <li>This product includes cryptographic software written by Eric Young.\n"
" Copyright © 1995-1998 <a\n"
" href=\"mailto:eay@cryptsoft.com\">Eric Young</a></li>\n"
#endif // _NATIVE_SSL_SUPPORT_
#ifdef OPERA_MINI // third-party regexp code, not currently used in any browser product (?)
" <li>This product includes software developed by the University of California,\n"
" Berkeley and its contributors</li>\n"
#endif // check with LTH ...
#ifndef USE_JAYPEG
" <li>The Independent JPEG Group</li>\n"
#endif // USE_JAYPEG
#ifdef USE_ZLIB
" <li>Zlib compression library, developed by Jean-loup Gailly\n"
" and Mark Adler</li>\n" // zlib
#endif
#ifdef EXPAT_XML_PARSER
" <li>James Clark</li>\n" // xml - expat
#endif // EXPAT_XML_PARSER
" <li>Eberhard Mattes</li>\n" // uni_sprintf, uni_sscanf
# ifndef ECMASCRIPT_NO_SPECIAL_DTOA_STRTOD
" <li>Number-to-string and string-to-number conversions are\n"
" covered by the following notice:\n"
" <blockquote>\n"
" <p>The author of this software is David M. Gay.</p>\n"
" <p>Copyright (c) 1991, 2000, 2001 by Lucent Technologies.</p>\n"
" <p>Permission to use, copy, modify, and distribute this software for any\n"
" purpose without fee is hereby granted, provided that this entire notice\n"
" is included in all copies of any software which is or includes a copy\n"
" or modification of this software and in all copies of the supporting\n"
" documentation for such software.</p>\n"
" <p>THIS SOFTWARE IS BEING PROVIDED <q>AS IS</q>,\n"
" WITHOUT ANY EXPRESS OR IMPLIED\n"
" WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY\n"
" REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY\n"
" OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.\n"
" </p>\n"
" </blockquote>\n"
" </li>\n"
# endif // ecmascript number <-> string conversions
# ifdef EXPAT_XML_PARSER
" <li>expat is covered by the following license: \n"
" <blockquote>\n"
" <p>Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd</p>\n"
" <p>Permission is hereby granted, free of charge, to any person obtaining\n"
" a copy of this software and associated documentation files (the\n"
" <q>Software</q>), to deal in the Software without restriction, including\n"
" without limitation the rights to use, copy, modify, merge, publish,\n"
" distribute, sublicense, and/or sell copies of the Software, and to\n"
" permit persons to whom the Software is furnished to do so, subject to\n"
" the following conditions:</p>\n"
" <p>THE SOFTWARE IS PROVIDED <q>AS IS</q>, WITHOUT WARRANTY OF ANY KIND,\n"
" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n"
" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n"
" IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n"
" CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n"
" TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n"
" SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</p>\n"
" </blockquote>\n"
" </li>\n"
# endif
# ifdef SVG_SUPPORT
" <li>Bitstream Vera Fonts are covered by the following license:\n"
" <blockquote>\n"
" <p>Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.\n"
" Bitstream Vera is a trademark of Bitstream, Inc.</p>\n"
" <p>Permission is hereby granted, free of charge, to any person obtaining a\n"
" copy of the fonts accompanying this license (<q>Fonts</q>) and associated\n"
" documentation files (the <q>Font Software</q>), to reproduce and distribute\n"
" the Font Software, including without limitation the rights to use, copy,\n"
" merge, publish, distribute, and/or sell copies of the Font Software, and\n"
" to permit persons to whom the Font Software is furnished to do so, subject\n"
" to the following conditions:</p>\n"
" <p>The above copyright and trademark notices and this permission notice shall\n"
" be included in all copies of one or more of the Font Software typefaces.</p>\n"
" <p>The Font Software may be modified, altered, or added to, and in particular\n"
" the designs of glyphs or characters in the Fonts may be modified and additional\n"
" glyphs or characters may be added to the Fonts, only if the fonts are renamed to\n"
" names not containing either the words <q>Bitstream</q> or the word <q>Vera</q>.</p>\n"
" <p>This License becomes null and void to the extent applicable to Fonts or\n"
" Font Software that has been modified and is distributed under the\n"
" <q>Bitstream Vera</q> names.</p>\n"
" <p>The Font Software may be sold as part of a larger software package but no copy\n"
" of one or more of the Font Software typefaces may be sold by itself.</p>\n"
" <p>THE FONT SOFTWARE IS PROVIDED <q>AS IS</q>,\n"
" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n"
" INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n"
" PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER\n"
" RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM,\n"
" DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL,\n"
" OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n"
" ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER\n"
" DEALINGS IN THE FONT SOFTWARE.</p>\n"
" </blockquote>\n"
" </li>\n"
# endif // SVG_SUPPORT
# ifdef SKIN_SUPPORT
" <li>Nice Graphics ™ by Pål Syvertsen, <a\n"
" href=\"http://www.flottaltsaa.no/\">Flott Altså</a></li>\n"
# endif
" <li>The Elektrans</li>\n" // what about panic ?
" </ul>\n <p>");
TRAP(rc, g_languageManager->GetStringL(Str::SI_IDABOUT_WELOVEYOU, tmp));
if (OpStatus::IsSuccess(rc)) url.WriteDocumentData(tmp.CStr());
url.WriteDocumentData(UNI_L("</p>\n"));
// #endif // the UL got some content.
}
#endif // USE_ABOUT_FRAMEWORK
|
#pragma once
#include <string>
#include <sstream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include "engine/graphics/LTexture.hpp"
class ScoreBoard{
private:
int PlayerScore = 0;
int OtherPlayerScore = 0;
LTexture* gScoreTextTexture = NULL;
std::stringstream scoreText;
LTexture* background = NULL;
TTF_Font *gFont = NULL;
public:
ScoreBoard();
~ScoreBoard();
void reset();
void render();
void loadMedia();
int getPlayerScore();
int getOtherPlayerScore();
void incPlayerScore();
void incOtherPlayerScore();
};
|
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main() {
vector<int> arr(5);
vector<int> nums;
for(int arr_i = 0; arr_i < 5; arr_i++){
cin >> arr[arr_i];
}
for (int i = 0; i < arr.size(); i++) {
int num = arr[i];
arr.erase(arr.begin()+i);
nums.push_back(std::accumulate(arr.begin(), arr.end(), 0));
arr.insert(arr.begin()+i, num);
}
cout << *std::min_element(nums.begin(), nums.end()) << ' ' << *std::max_element(nums.begin(), nums.end());
return 0;
}
|
// Created on: 1991-03-21
// Created by: Philippe DAUTRY
// Copyright (c) 1991-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 _GccAna_Circ2d2TanRad_HeaderFile
#define _GccAna_Circ2d2TanRad_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <GccEnt_Array1OfPosition.hxx>
#include <TColStd_Array1OfInteger.hxx>
#include <Standard_Integer.hxx>
#include <TColgp_Array1OfCirc2d.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <GccEnt_Position.hxx>
class GccEnt_QualifiedCirc;
class GccEnt_QualifiedLin;
class gp_Pnt2d;
class gp_Circ2d;
//! This class implements the algorithms used to
//! create 2d circles tangent to 2
//! points/lines/circles and with a given radius.
//! For each construction methods arguments are:
//! - Two Qualified elements for tangency constraints.
//! (for example EnclosedCirc if we want the
//! solution inside the argument EnclosedCirc).
//! - Two Reals. One (Radius) for the radius and the
//! other (Tolerance) for the tolerance.
//! Tolerance is only used for the limit cases.
//! For example :
//! We want to create a circle inside a circle C1 and
//! inside a circle C2 with a radius Radius and a
//! tolerance Tolerance.
//! If we do not use Tolerance it is impossible to
//! find a solution in the following case : C2 is
//! inside C1 and there is no intersection point
//! between the two circles.
//! With Tolerance it gives a solution if the lowest
//! distance between C1 and C2 is lower than or equal
//! Tolerance.
class GccAna_Circ2d2TanRad
{
public:
DEFINE_STANDARD_ALLOC
//! This method implements the algorithms used to
//! create 2d circles TANgent to two 2d circle with a
//! radius of Radius.
//! It raises NegativeValue if Radius is lower than zero.
Standard_EXPORT GccAna_Circ2d2TanRad(const GccEnt_QualifiedCirc& Qualified1, const GccEnt_QualifiedCirc& Qualified2, const Standard_Real Radius, const Standard_Real Tolerance);
//! This method implements the algorithms used to
//! create 2d circles TANgent to a 2d circle and a 2d line
//! with a radius of Radius.
//! It raises NegativeValue if Radius is lower than zero.
Standard_EXPORT GccAna_Circ2d2TanRad(const GccEnt_QualifiedCirc& Qualified1, const GccEnt_QualifiedLin& Qualified2, const Standard_Real Radius, const Standard_Real Tolerance);
//! This method implements the algorithms used to
//! create 2d circles TANgent to a 2d circle and a point
//! with a radius of Radius.
//! It raises NegativeValue if Radius is lower than zero.
Standard_EXPORT GccAna_Circ2d2TanRad(const GccEnt_QualifiedCirc& Qualified1, const gp_Pnt2d& Point2, const Standard_Real Radius, const Standard_Real Tolerance);
//! This method implements the algorithms used to
//! create 2d circles TANgent to a 2d line and a point
//! with a radius of Radius.
//! It raises NegativeValue if Radius is lower than zero.
Standard_EXPORT GccAna_Circ2d2TanRad(const GccEnt_QualifiedLin& Qualified1, const gp_Pnt2d& Point2, const Standard_Real Radius, const Standard_Real Tolerance);
//! This method implements the algorithms used to
//! create 2d circles TANgent to two 2d lines
//! with a radius of Radius.
//! It raises NegativeValue if Radius is lower than zero.
Standard_EXPORT GccAna_Circ2d2TanRad(const GccEnt_QualifiedLin& Qualified1, const GccEnt_QualifiedLin& Qualified2, const Standard_Real Radius, const Standard_Real Tolerance);
//! This method implements the algorithms used to
//! create 2d circles passing through two points with a
//! radius of Radius.
//! It raises NegativeValue if Radius is lower than zero.
Standard_EXPORT GccAna_Circ2d2TanRad(const gp_Pnt2d& Point1, const gp_Pnt2d& Point2, const Standard_Real Radius, const Standard_Real Tolerance);
//! This method returns True if the algorithm succeeded.
//! Note: IsDone protects against a failure arising from a
//! more internal intersection algorithm, which has reached its numeric limits.
Standard_EXPORT Standard_Boolean IsDone() const;
//! This method returns the number of circles, representing solutions computed by this algorithm.
//! Exceptions
//! StdFail_NotDone if the construction fails. of solutions.
Standard_EXPORT Standard_Integer NbSolutions() const;
//! Returns the solution number Index.
//! Be careful: the Index is only a way to get all the
//! solutions, but is not associated to those outside the context
//! of the algorithm-object. Raises OutOfRange exception if Index is greater
//! than the number of solutions.
//! It raises NotDone if the construction algorithm did not
//! succeed.
Standard_EXPORT gp_Circ2d ThisSolution (const Standard_Integer Index) const;
//! Returns the information about the qualifiers of
//! the tangency arguments concerning the solution number Index.
//! It returns the real qualifiers (the qualifiers given to the
//! constructor method in case of enclosed, enclosing and outside
//! and the qualifiers computedin case of unqualified).
Standard_EXPORT void WhichQualifier (const Standard_Integer Index, GccEnt_Position& Qualif1, GccEnt_Position& Qualif2) const;
//! Returns information about the tangency point between the
//! result number Index and the first argument.
//! ParSol is the intrinsic parameter of the point PntSol on the solution.
//! ParArg is the intrinsic parameter of the point PntSol on the first
//! argument. Raises OutOfRange if Index is greater than the number
//! of solutions.
//! It raises NotDone if the construction algorithm did not succeed
Standard_EXPORT void Tangency1 (const Standard_Integer Index, Standard_Real& ParSol, Standard_Real& ParArg, gp_Pnt2d& PntSol) const;
//! Returns information about the tangency point between the
//! result number Index and the second argument.
//! ParSol is the intrinsic parameter of the point PntSol on
//! the solution.
//! ParArg is the intrinsic parameter of the point PntArg on
//! the second argument. Raises OutOfRange if Index is greater than the number
//! of solutions.
//! It raises NotDone if the construction algorithm did not succeed.
Standard_EXPORT void Tangency2 (const Standard_Integer Index, Standard_Real& ParSol, Standard_Real& ParArg, gp_Pnt2d& PntSol) const;
//! Returns True if the solution number Index is equal to
//! the first argument. Raises OutOfRange if Index is greater than the number
//! of solutions.
//! It raises NotDone if the construction algorithm did not
//! succeed.
Standard_EXPORT Standard_Boolean IsTheSame1 (const Standard_Integer Index) const;
//! Returns True if the solution number Index is equal to
//! the second argument. Raises OutOfRange if Index is greater than the number
//! of solutions.
//! It raises NotDone if the construction algorithm did not succeed.
Standard_EXPORT Standard_Boolean IsTheSame2 (const Standard_Integer Index) const;
protected:
private:
Standard_Boolean WellDone;
GccEnt_Array1OfPosition qualifier1;
GccEnt_Array1OfPosition qualifier2;
TColStd_Array1OfInteger TheSame1;
TColStd_Array1OfInteger TheSame2;
Standard_Integer NbrSol;
TColgp_Array1OfCirc2d cirsol;
TColgp_Array1OfPnt2d pnttg1sol;
TColgp_Array1OfPnt2d pnttg2sol;
TColStd_Array1OfReal par1sol;
TColStd_Array1OfReal par2sol;
TColStd_Array1OfReal pararg1;
TColStd_Array1OfReal pararg2;
};
#endif // _GccAna_Circ2d2TanRad_HeaderFile
|
#pragma once
#include <lexer/tokens/identifier_token.hpp>
#include <lexer/tokens/literal_token.hpp>
#include <lexer/tokens/rule_token.hpp>
#include <lexer/tokens/token.hpp>
namespace prv {
namespace lex {
template <class TokenSpec>
class tokenizer {
using trie = detail::token_spec_trie<TokenSpec>;
static_assert(prv::all_of<TokenSpec, is_token>::value, "invalid types in token specifications");
public:
explicit constexpr tokenizer(const char* ptr, std::size_t size) noexcept
: tokenizer(ptr, ptr + size)
{
}
explicit constexpr tokenizer(const char* begin, const char* end)
: begin_(begin)
, ptr_(begin)
, end_(end)
, last_result_(match_result<TokenSpec>::unmatched())
{
reset(begin);
}
//=== tokenizer functions ===//
/// \returns The current token.
constexpr token<TokenSpec> peek() const noexcept
{
return token<TokenSpec>(last_result_.kind, ptr_, last_result_.bump);
}
/// \returns Whether or not EOF was reached.
/// If this is `true`, `bump()` will have no effect anymore and `peek()` returns EOF.
constexpr bool is_done() const noexcept
{
PRV_LEX_ASSERT(last_result_.bump != 0 || peek().is(eof_token{}));
return last_result_.bump == 0;
}
/// Returns and advances the token.
/// \effects Consumes the current token by calling `bump()`.
/// \returns The current token, before it was consumed.
constexpr token<TokenSpec> get() noexcept
{
auto result = peek();
bump();
return result;
}
/// \effects Consumes the current token, `peek()` will then return the next token.
/// If `is_eof() == true` when calling the function it will replace the current token with
/// EOF.
constexpr void bump() noexcept
{
reset(ptr_ + last_result_.bump);
}
/// \effects Resets the tokenizer to the specified position and parses that token
/// immediately.
constexpr void reset(const char* position) noexcept
{
PRV_LEX_PRECONDITION(begin_ <= position && position <= end_, "position out of range");
ptr_ = position;
last_result_ = trie::try_match(ptr_, end_);
}
//=== getters ===//
/// \returns The beginning of the character range.
constexpr const char* begin_ptr() const noexcept
{
return begin_;
}
/// \returns The current position in the character range.
/// `peek()` returns the token starting at that position.
constexpr const char* current_ptr() const noexcept
{
PRV_LEX_ASSERT(peek().spelling().data() == ptr_);
return ptr_;
}
/// \returns One past the end of the character range.
constexpr const char* end_ptr() const noexcept
{
return end_;
}
private:
const char* begin_{};
const char* ptr_{};
const char* end_{};
match_result<TokenSpec> last_result_;
};
} // namespace lex
} // namespace prv
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
priority_queue<int> G[30010];
bool vis[30010];
void dfs(int k)
{
if (vis[k]) return;
for (int )
}
int main()
{
int t,n,m;
scanf("%d",&t);
while (t--)
{
scanf("%d%d",&n,&m);
memset(vis,false,sizeof(vis));
for (int i = 1;i <= m; i++)
{
int from,to;
scanf("%d%d",&from,&to);
G[to].push(from);
}
int fr = 1;
for (int i = 1;i <= n; i++)
dfs(i);
printf("\n");
}
return 0;
}
|
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
enum Operator {Plus, Minus, Prod, Divi};
class Solution {
public:
int evalRPN(vector<string>& tokens) {
for (string token: tokens) {
if(token == "+") {
calculate(Plus);
} else if(token == "-") {
calculate(Minus);
} else if(token == "*") {
calculate(Prod);
} else if(token == "/") {
calculate(Divi);
} else {
s.push(stoi(token));
}
}
return s.top();
}
private:
stack<int> s;
void calculate(Operator ope) {
int y = s.top();
s.pop();
int x = s.top();
s.pop();
switch(ope) {
case Plus:
s.push(x + y);
break;
case Minus:
s.push(x - y);
break;
case Prod:
s.push(x * y);
break;
case Divi:
s.push(x / y);
break;
}
}
};
int main(void){
Solution s;
vector<string> input = {"2", "1", "+", "3", "*"};
cout << s.evalRPN(input) << endl;
return 0;
}
|
// Created on: 2016-04-07
// Copyright (c) 2016 OPEN CASCADE SAS
// Created by: Oleg AGASHIN
//
// 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 _IMeshTools_MeshBuilder_HeaderFile
#define _IMeshTools_MeshBuilder_HeaderFile
#include <IMeshTools_Context.hxx>
#include <Standard_Type.hxx>
#include <Message_ProgressRange.hxx>
//! Builds mesh for each face of shape without triangulation.
//! In case if some faces of shape have already been triangulated
//! checks deflection of existing polygonal model and re-uses it
//! if deflection satisfies the specified parameter. Otherwise
//! nullifies existing triangulation and build triangulation anew.
//!
//! The following statuses are used:
//! Message_Done1 - algorithm has finished without errors.
//! Message_Fail1 - invalid context.
//! Message_Fail2 - algorithm has faced unexpected error.
//! Message_Fail3 - fail to discretize edges.
//! Message_Fail4 - can't heal discrete model.
//! Message_Fail5 - fail to pre-process model.
//! Message_Fail6 - fail to discretize faces.
//! Message_Fail7 - fail to post-process model.
//! Message_Warn1 - shape contains no objects to mesh.
class IMeshTools_MeshBuilder : public Message_Algorithm
{
public:
//! Constructor.
Standard_EXPORT IMeshTools_MeshBuilder();
//! Constructor.
Standard_EXPORT IMeshTools_MeshBuilder (const Handle (IMeshTools_Context)& theContext);
//! Destructor.
Standard_EXPORT virtual ~IMeshTools_MeshBuilder();
//! Sets context for algorithm.
void SetContext (const Handle (IMeshTools_Context)& theContext)
{
myContext = theContext;
}
//! Gets context of algorithm.
const Handle (IMeshTools_Context)& GetContext () const
{
return myContext;
}
//! Performs meshing to the shape using current context.
Standard_EXPORT virtual void Perform (const Message_ProgressRange& theRange);
DEFINE_STANDARD_RTTIEXT(IMeshTools_MeshBuilder, Message_Algorithm)
private:
Handle (IMeshTools_Context) myContext;
};
#endif
|
#pragma once
#include <tuple>
class QWidget;
class EditUserOutput;
class User;
namespace EditUserAssembler {
std::tuple<QWidget *, EditUserOutput *> assembly(const User &user, QWidget *parent = nullptr);
}
|
#ifndef _EnterPrivateRoomProc_H_
#define _EnterPrivateRoomProc_H_
#include "IProcess.h"
class Table;
class Player;
class EnterPrivateRoomProc :public IProcess
{
public:
EnterPrivateRoomProc();
virtual ~EnterPrivateRoomProc();
virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt ) ;
virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket ,Context* pt ) ;
private:
int sendTabePlayersInfo(Player* player, Table* table, short num, int comuid, short seq);
};
#endif
|
class Category_673 {
class RHIB {
type = "trade_any_boat";
buy[] = {4,"ItemGoldBar10oz"};
sell[] = {2,"ItemGoldBar10oz"};
};
};
class Category_558 {
duplicate = 673;
};
|
/**
\file Selection.cpp
Selection class's implementation
\author Antoine Colmard (2014)
\author Nicolas Prugne (2014)
\copyright 2014 Institut Pascal
*/
#include "Selection.h"
// -----------------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------------
/**
@brief Selection::Selection Selection constructor
@param trajectory Trajectory to put selection on
@param start Selection start point id
@param end Selection end point id
Selection's start id will be lower than Selection's end id
*/
Selection::Selection(Trajectory *trajectory, unsigned int start, unsigned int end)
{
if(start < end)
{
this->start(start);
this->end(end);
}
else
{
this->start(end);
this->end(start);
}
this->trajectory(trajectory);
}
// -----------------------------------------------------------------------------
// GETTERS
// -----------------------------------------------------------------------------
/**
@brief Selection::start Get selection's start point id
@return Start point id
*/
unsigned int Selection::start(void)
{
return this->start_;
}
/**
@brief Selection::end Get selection's end point id
@return End point id
*/
unsigned int Selection::end(void)
{
return this->end_;
}
/**
@brief Selection::start Get selection's trajectory
@return Selection's trajectory
*/
Trajectory *Selection::trajectory()
{
return this->trajectory_;
}
// -----------------------------------------------------------------------------
// SETTERS
// -----------------------------------------------------------------------------
/**
@brief Selection::start Set selection's start point id
@param start Start point id
*/
void Selection::start(unsigned int start)
{
this->start_ = start;
}
/**
@brief Selection::end Set selection's end point id
@param end End point id
*/
void Selection::end(unsigned int end)
{
this->end_ = end;
}
/**
@brief Selection::trajectory Set selection's trajectory
@param trajectory Selection's trajectory
*/
void Selection::trajectory(Trajectory *trajectory)
{
this->trajectory_ = trajectory;
}
|
/* -*- 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.
*/
#ifndef _UPDATE_MAN_H_
#define _UPDATE_MAN_H_
#ifdef UPDATERS_ENABLE_MANAGER
#include "modules/hardcore/mh/mh.h"
/** Basic manager for automatic updaters, which only manages the basic
* end of fetch message.
*
* The end of handling message is set during construction, and posted when PostFinished is called
*
* The object have the following phases:
*
* - Construction (with message specified)
* a callback must be registered in g_main_message_handler for the specified message
* - manager calls StartLoading() to initiate sequence (implemented by subclass)
* - Implementation subclass handles loading
* - Implementation calls PostFinished() with result after all processing is finished
* - Manager deletes the fetcher
*
* If the message is specified the listener must register a callback for
* the specified message and element->Id() as par1; par2 contains the result
*/
class AutoFetch_Element :
public Link
{
private:
/** The message to be posted when finished, par1 is the ID, par2 is the result */
OpMessage finished_msg;
BOOL finished;
unsigned int id;
public:
/** Constructor */
AutoFetch_Element():finished_msg(MSG_NO_MESSAGE), finished(FALSE){id = g_updaters_api->NewUpdaterId();}
/** Construct with message */
void Construct(OpMessage fin_msg){finished_msg = fin_msg;}
/** Destructor */
virtual ~AutoFetch_Element();
/** Start update process */
virtual OP_STATUS StartLoading()=0;
/** Id */
MH_PARAM_1 Id(){return id;}
/** Post the finsihed message with the provided result as par2 */
void PostFinished(MH_PARAM_2 result);
BOOL IsFinished(){return finished;}
AutoFetch_Element *Suc(){return (AutoFetch_Element *) Link::Suc();}
AutoFetch_Element *Pred(){return (AutoFetch_Element *) Link::Pred();}
};
/** Basic manager for handling multiple updaters; used by application using many updaters
*
* When all pending fetchings are finished a message is posted to the owner if one is specified.
* The manager may also be polled to determine if there are active downloads
*
* HandleCallbacks for updaters' finished message must be registered by the implementation
*
* Use:
* - Owner constructs the manager with an optional message, and InitL()s it,
* a callback must be registered in g_main_message_handler for the specified message
* - New fetchers are added using using AddUpdater; this will start the updater
* - When all updaters are finished the specified message (if any) is posted.
*/
class AutoFetch_Manager : public MessageObject
{
private:
/** List of active updaters */
AutoDeleteHead updaters;
/** Specified finished message */
OpMessage fin_msg;
/** ID to send with finished message */
MH_PARAM_1 fin_id;
public:
/** Constructor with optional finished message */
AutoFetch_Manager(OpMessage a_msg=MSG_NO_MESSAGE, MH_PARAM_1 a_id=0):fin_msg(a_msg), fin_id(a_id){};
/** Destructor */
virtual ~AutoFetch_Manager(){g_main_message_handler->UnsetCallBacks(this);};
/** Initialization operation; Must be used; Leaves if error occurs */
virtual void InitL();
/** Handle callbacks; default is to consider any message for an ID as a finished message */
virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
/** Is this manager still loading updates? */
BOOL Active() const {return !updaters.Empty();}
/** Start loading an autoupdater, and register it if it is a fire-and-almost-forget updater */
OP_STATUS AddUpdater(AutoFetch_Element *new_updater, BOOL is_started = FALSE);
/** Remove all loaders */
void Clear(){updaters.Clear();}
/** Clean up finished loaders */
#ifdef UPDATERS_ENABLE_MANAGER_CLEANUP
void Cleanup();
#endif
virtual void OnAllUpdatersFinished();
AutoFetch_Element *First(){return (AutoFetch_Element *) updaters.First();}
};
#endif
#endif //_UPDATE_MAN_H_
|
#ifndef LEVIN_BASE_H
#define LEVIN_BASE_H
#include <boost/function.hpp>
#include <gsl/gsl_linalg.h>
#include "levinFunctions.h"
#include "Bispectrum.hpp"
/**
* Numerical integration of \f[I[F]=\int_a^b\mathrm{d}x\,\langleF,w\rangle\f] using a Levin-type method with n points
* and the basis \f$u_m(x)\f$, \f$m=1,..,n\f$, where \f$F=(f_1(x),...,f_d(x))^{\text{T}}\f$ and \f$w(x)\f$ is a vector of rapidly
* oscillating functions, e. g. Bessel functions.
* Collocation points are \f$x_j=a+(j-1)\frac{b-a}{n-1}\f$, \f$j=1,...,n\f$. The basis functions are the polynomials \f$u_m(x)=\left(\frac{x-\frac{a+b}{2}}{b-a}\right)^{m-1}\f$ by default
* and may be overridden.
*/
class LevinBase
{
protected:
static const double min_sv; // only singular values above this cut are considered
int d; // dimension (length of vector w)
int n; // number of collocation points
double a, b; // integral borders
double* x_j; // collocation points
gsl_matrix* L; // matrix containing the coefficients of the LSE
gsl_vector* y; // right-hand side of the LSE
gsl_vector* c; // solution of the LSE
LevinFunctions* lf; // pointer to an object (of type LevinFunctions) containing w and the matrix A
bool allocated; // true if memory has been allocated for the GSL matrix and vector and the collocation array
void allocate (); // allocates memory for the GSL matrix and vector and the array
void free (); // frees the memory associated with matrix, vector and array
public:
/**
* Constructor initializing the dimension and the necessary functions for the LSE.
*/
LevinBase (int dim, LevinFunctions* LF);
/**
* Copy constructor, assigning the dimension and LevinFunctions pointer. Other member variables remain uninitialized.
*/
LevinBase (const LevinBase& LB);
/**
* Returns a pointer to a copy of the object.
*/
virtual LevinBase* clone () const;
/**
* Destructor.
*/
virtual ~LevinBase ();
/**
* Returns the dimension, i. e. size of vectors F and w.
*/
int getDimension () const;
/**
* Returns the pointer to the LevinFunctions object.
*/
LevinFunctions* getFunctions () const;
/**
* Allocates memory space and calculates coordinates of the collocation points.
*/
void setNodes (double A, double B, int col);
/**
* Sets up the LSE, i. e. calculates the corresponding matrix.
*/
void setUpLSE ();
/**
* Solves the LSE, with the RHS given by F evaluated at the collocation points.
*/
void solveLSE (boost::function<double(double)> F[]);
void solveLSE (double (**F)(double, void*), void* pp);
/**
* Solves the LSE, with the RHS given by \f$F=(f,0,...,0)^{\text{T}}\f$ evaluated at the collocation points.
*/
void solveLSE (const boost::function<double(double)>& f);
void solveLSE (double (*f)(double, void*), void* pp);
/**
* Solves the LSE using an LU decomposition or, if the matrix is singular, a singular value decomposition.
*/
void solveLSE ();
/**
* Returns the i-th component of the function p used to approximate the integral.
*/
double p (int i, double x);
/**
* Calculates an approximation to the integral for kernel F.
*/
double integrate (boost::function<double(double)> F[]);
double integrate (double (**F)(double, void*), void* pp);
/**
* Calculates an approximation to the integral for kernel \f$F=(f,0,...,0)^{\text{T}}\f$.
*/
double integrate (const boost::function<double(double)>& f);
double integrate (double (*f)(double, void*), void* pp);
/**
* Calculates an approximation to the integral for kernel F with the given borders and size.
*/
double integrate (boost::function<double(double)> F[], double A, double B, int col);
double integrate (double (**F)(double, void*), void* pp, double A, double B, int col);
/**
* Calculates an approximation to the integral for kernel \f$F=(f,0,...,0)^{\text{T}}\f$ with the given borders and size.
*/
double integrate (const boost::function<double(double)>& f, double A, double B, int col);
double integrate (double (*f)(double, void*), void* pp, double A, double B, int col);
/**
* m-th basis function \f$u_m(x)\f$; override possible.
*/
virtual double u (int m, double x);
/**
* Derivative of m-th basis function \f$u^{\prime}_m(x)\f$; override possible.
*/
virtual double u_prime (int m, double x);
// ADDED BY CLAUDE
/*
double integrate (TEST_Bispectrum* NLG, void* pp, double A, double B, int col);
double integrate (TEST_Bispectrum* NLG, void* pp);
void solveLSE (TEST_Bispectrum* NLG, void* pp);
*/
};
#endif
|
#include <iostream>
using namespace std;
bool checkWin(int board[][3], int player) {
// horizontal
for (int i = 0; i < 3; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) return true;
}
// vertical
for (int i = 0; i < 3; i++) {
if (board[0][i] == player && board[1][i] == player && board[2][i] == player) return true;
}
// diagonal
if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
(board[0][2] == player && board[1][1] == player && board[2][0] == player))
return true;
return false;
}
// TODO implement function if the game is a tie before last move
bool fillPlace(int board[][3], int x, int y, int value) {
if (x > 2 || x < 0) {
cout << "Invalid x coordinate. Try again.\n";
return false;
} else if (y > 2 || y < 0) {
cout << "Invalid y coordinate. Try again.\n";
return false;
} else if (board[x][y] != 0) {
cout << "Place is already filled. Try again.\n";
return false;
} else {
board[x][y] = value;
return true;
}
}
void initBoard(int board[][3], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = 0;
}
}
}
void printBoard(int board[][3], int size) {
cout << "-----" << endl;
for (int i = 0; i < size; i++) {
for (int j = 0; j < 3; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
cout << "-----" << endl;
}
bool isBoardFilled(int board[][3]) {
bool isFilled = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == 0) isFilled = false;
}
}
return isFilled;
}
int main() {
int board[3][3];
initBoard(board, 3);
printBoard(board, 3);
int playerOnesTurn = true;
while (true) {
int x, y;
if (playerOnesTurn) {
cout << "Player 1's turn" << endl;
do {
cout << "Enter x coordinate: "; cin >> x;
cout << "Enter y coordinate: "; cin >> y;
} while (!fillPlace(board, x, y, 1));
} else {
cout << "Player 2's turn" << endl;
do {
cout << "Enter x coordinate: "; cin >> x;
cout << "Enter y coordinate: "; cin >> y;
} while (!fillPlace(board, x, y, 2));
}
playerOnesTurn = !playerOnesTurn;
if (isBoardFilled(board)) {
cout << "The game is a tie.\n";
break;
}
printBoard(board, 3);
if (checkWin(board, 1)) {
cout << "Player 1 has won\n";
break;
} else if (checkWin(board, 2)) {
cout << "Player 2 has won\n";
break;
}
}
return 0;
}
|
#ifndef INVOKER_H
#define INVOKER_H
#include <cstdlib>
#include "command.h"
class Invoker
{
private:
Command * executor;
Command * undoer;
public:
Invoker(void);
Invoker(Command * executor);
Invoker(Command * executor, Command * undoer);
void execute(void) throw(int&);
void undo(void) throw(int&);
void setExecutor(Command * executor);
void setUndoer(Command * undoer);
};
#endif//INVOKER_H
|
#include <string>
#include <cstdlib>
#include <sstream>
#include "BigQ.h"
//Comparison function object
Sorter::Sorter(OrderMaker &sortorder): _sortorder(sortorder){}
bool Sorter::operator()(Record *i, Record *j){
ComparisonEngine comp;
if(comp.Compare(i, j, &_sortorder) < 0)
return true;
else
return false;
}
Sorter2::Sorter2(OrderMaker &sortorder): _sortorder(sortorder){}
bool Sorter2::operator()(pair<int, Record *> i, pair<int, Record *> j){
ComparisonEngine comp;
if(comp.Compare((i.second), (j.second), &_sortorder) < 0)
return false;
else
return true;
}
int BigQ::cnt = 0;
const char* BigQ::tmpfName() {
const size_t LEN = 10;
std::ostringstream oss;
char rstr[LEN];
genRandom(rstr, LEN);
oss << "biq" << (++cnt) << rstr << ".tmp";
std::string name = oss.str();
return name.c_str();
}
BigQ :: BigQ (Pipe &in, Pipe &out, OrderMaker &sortorder, int runlen):
Qin(in), Qout(out), Qsortorder(sortorder), Qrunlen(runlen), mysorter(sortorder), mysorter2(sortorder) {
//create worker thread
int rc = pthread_create(&worker, NULL, Working, (void *)this);
if(rc){
printf("Error creating worker thread! Return %d\n", rc);
exit(-1);
}
curPage = new Page();
theFile = new File();
theFile->Open(0, (char*)tmpfName()); // need a random name otherwise two or more bigq's would crash
}
BigQ::~BigQ () {
theFile->Close();
delete curPage;
delete theFile;
}
void * BigQ::Working(void *big){
BigQ *inst = (BigQ *)big;
// read data from in pipe sort them into runlen pages
Record temp;
int curSizeInBytes = 0;
int curPageNum = 0;
vector<Record *> record_bunch;
vector<int> runhead;
while((inst->Qin).Remove(&temp)){
char *b = temp.GetBits();
if(curSizeInBytes + ((int *)b)[0] < (PAGE_SIZE -4) * inst->Qrunlen){
//Read to one Run
Record *toput = new Record();
toput->Consume(&temp);
record_bunch.push_back(toput);
curSizeInBytes += ((int *)b)[0];
continue;
}else{
//Sort and Write one Run
sort (record_bunch.begin(), record_bunch.end(), inst->mysorter);
runhead.push_back(curPageNum);
vector<Record *>::iterator it=record_bunch.begin();
while(it!=record_bunch.end()){
if(!(inst->curPage)->Append((*it))){
(inst->theFile)->addPage(inst->curPage);
(inst->curPage)->EmptyItOut();
curPageNum++;
}else{
it++;
}
}
if(!(inst->curPage)->is_empty()){
(inst->theFile)->addPage(inst->curPage);
(inst->curPage)->EmptyItOut();
curPageNum++;
}
//Free Space
for(int i=0; i<record_bunch.size(); i++){
delete record_bunch[i];
}
//Push the one record before write
record_bunch.clear();
Record *toput = new Record();
toput->Consume(&temp);
record_bunch.push_back(toput);
curSizeInBytes = 0;
}
}
if(!record_bunch.empty()){
//Sort and Write Last Run
sort (record_bunch.begin(), record_bunch.end(), inst->mysorter);
runhead.push_back(curPageNum);
vector<Record *>::iterator it=record_bunch.begin();
while(it!=record_bunch.end()){
if(!(inst->curPage)->Append((*it))){
(inst->theFile)->addPage(inst->curPage);
(inst->curPage)->EmptyItOut();
curPageNum++;
}else{
it++;
}
}
if(!(inst->curPage)->is_empty()){
(inst->theFile)->addPage(inst->curPage);
(inst->curPage)->EmptyItOut();
curPageNum++;
}
//Free Space
for(int i=0; i<record_bunch.size(); i++){
delete record_bunch[i];
}
//Push the one record before write
record_bunch.clear();
runhead.push_back(curPageNum);//As sentinel for the last run.
}
// Construct priority queue over sorted runs and dump sorted data
// into the out pipe
priority_queue<pair<int, Record*>, vector<pair<int, Record*> >, Sorter2> PQueue(Sorter2(inst->Qsortorder));
vector<int> runcur(runhead);
vector<Page *> runpagelist;
for(int i=0; i<runhead.size()-1; i++){
Page *temp_P = new Page();
(inst->theFile)->GetPage(temp_P, runhead[i]);
Record *temp_R = new Record();
temp_P->GetFirst(temp_R);
PQueue.push(make_pair(i,temp_R));
runpagelist.push_back(temp_P);
}
while(!PQueue.empty()){
//POP
int temp_I = PQueue.top().first;
Record *temp_R = PQueue.top().second;
PQueue.pop();
(inst->Qout).Insert(temp_R);
//Insert from Next run head
if(!runpagelist[temp_I]->GetFirst(temp_R)){
if(++runcur[temp_I]<runhead[temp_I+1]){
runpagelist[temp_I]->EmptyItOut();
(inst->theFile)->GetPage(runpagelist[temp_I], runcur[temp_I]);
runpagelist[temp_I]->GetFirst(temp_R);
PQueue.push(make_pair(temp_I,temp_R));
}
}else{
PQueue.push(make_pair(temp_I,temp_R));
}
}
for(int i=0; i<runpagelist.size(); i++){
delete runpagelist[i];
}
// finally shut down the out pipe
(inst->Qout).ShutDown ();
}
|
//
// Created by Yujing Shen on 29/05/2017.
//
#include "../../include/nodes/MSENode.h"
namespace sjtu{
MSENode::MSENode(Session *sess, const Shape &shape) :
SessionNode(sess, shape)
{
}
MSENode::~MSENode()
{
}
Node MSENode::forward()
{
const Tensor pred = _port_in[0]->get_data();
const Tensor label = _port_in[1]->get_data();
Tensor loss = _data;
const Shape& _p_shape = pred->get_shape();
const Shape& _l_shape = loss->get_shape();
if(!pred->check_shape(label))
throw ShapeNotMatchException();
if(_p_shape.size() != 2 || _l_shape.size() != 1 || _l_shape[0] != _p_shape[0])
throw ShapeNotMatchException();
Dtype tmp, _err;
for (int i = 0; i < _p_shape[0]; ++i) {
tmp = 0.0;
for(int j = 0; j < _p_shape[1]; ++j){
_err = (*pred)(i, j) - (*label)(i, j);
tmp += _err * _err;
}
tmp /= (Dtype) _p_shape[1] * 2;
(*loss)(i) = tmp;
}
return this;
}
Node MSENode::backward()
{
Tensor d_pred = _port_in[0]->get_diff();
const Tensor pred = _port_in[0]->get_data();
Tensor d_lable = _port_in[1]->get_diff();
const Tensor label = _port_in[1]->get_data();
const Tensor loss = _data;
const Shape& _p_shape = d_pred->get_shape();
const Shape& _l_shape = loss->get_shape();
if(_p_shape.size() != 2 || _l_shape.size() != 1 || _l_shape[0] != _p_shape[0])
throw ShapeNotMatchException();
Dtype tmp, _err;
for (int i = 0; i < _p_shape[0]; ++i)
{
tmp = (*loss)(i);
for (int j = 0; j < _p_shape[1]; ++j)
{
_err = (*pred)(i, j) - (*label)(i, j);
(*d_pred)(i, j) += _err * tmp / (Dtype) _p_shape[1];
(*d_lable)(i, j) += _err * tmp / (Dtype) _p_shape[1];
}
}
return this;
}
Node MSENode::optimize()
{
return this;
}
}
|
// AI_Dijkstra.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "dijkstrasSearch.h"
int main()
{
//structure looks like this
// >N5--1-->N4
// / \
// 1 1
// / \>
// N1--10-->N2--10-->N3
//set up list of nodes
std::list<Pathfinding::Node*> nodes;
//set up node positions
Pathfinding::Node* node1 = new Pathfinding::Node();
node1->position.x = 0;
node1->position.y = 0;
Pathfinding::Node* node2 = new Pathfinding::Node();
node2->position.x = 1;
node2->position.y = 0;
Pathfinding::Node* node3 = new Pathfinding::Node();
node3->position.x = 2;
node3->position.y = 0;
Pathfinding::Node* node4 = new Pathfinding::Node();
node4->position.x = 1.5;
node4->position.y = 1;
Pathfinding::Node* node5 = new Pathfinding::Node();
node5->position.x = 0.5;
node5->position.y = 1;
//set up edges
Edge edge1;
edge1.target = node2;
edge1.cost = 10;
Edge edge2;
edge2.target = node3;
edge2.cost = 10;
Edge edge3;
edge3.target = node3;
edge3.cost = 1;
Edge edge4;
edge4.target = node4;
edge4.cost = 1;
Edge edge5;
edge5.target = node5;
edge5.cost = 1;
node1->connections.push_back(edge1);
node1->connections.push_back(edge5);
node2->connections.push_back(edge2);
node4->connections.push_back(edge3);
node5->connections.push_back(edge4);
nodes.push_back(node1);
nodes.push_back(node2);
nodes.push_back(node3);
nodes.push_back(node4);
nodes.push_back(node5);
dijkstrasSearch(node1, node3);
//clean up
for (auto node : nodes)
{
delete node;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* George Refseth, rfz@opera.com
*/
#include "core/pch.h"
#ifdef M2_SUPPORT
# include "adjunct/desktop_util/opfile/desktop_opfile.h"
# include "adjunct/m2/src/engine/account.h"
# include "adjunct/m2/src/engine/engine.h"
# include "adjunct/m2/src/engine/message.h"
# include "adjunct/m2/src/import/ImporterModel.h"
# include "adjunct/m2/src/import/M1_Prefs.h"
# include "adjunct/m2/src/import/OperaImporter.h"
# include "adjunct/m2/src/util/qp.h"
# include "modules/locale/oplanguagemanager.h"
# include "modules/util/path.h"
# include "modules/util/filefun.h"
# ifdef USE_MAILDIR
typedef const char* MBID;
typedef UINT32 MBATTR;
typedef unsigned char MBTYPE;
# else
typedef UINT32 MBID;
typedef UINT32 MBATTR;
typedef unsigned char MBTYPE;
# endif // USE_MAILDIR
typedef UINT32 MBFolderStatus;
# define MBFS_CREATED_STANDARD 0
# define MBFS_OPEN_OK 0
# define MBFS_CREATED_EXISTS 1
# define MBFS_CREATED_STORAGE_SCANNED 2
# define MBFS_CREATED_ERROR 3
# define MBFS_OPEN_ERROR 3
typedef UINT32 itemAttr;
// These first two has special meaning!
# define ITEM_ATTR_SET 0x80000000
# define ITEM_ATTR_CLEAR 0x40000000
# define ITEM_ATTR_UNREAD 0x00000001
# define ITEM_ATTR_DRAFT 0x00000002
# define ITEM_ATTR_REPLIED 0x00000004
# define ITEM_ATTR_FORWARDED 0x00000008
# define ITEM_ATTR_REDIRECTED 0x00000010
# define ITEM_ATTR_SENT 0x00000020
# define ITEM_ATTR_QUEUED 0x00000040
# define ITEM_ATTR_PENDING 0x00000080
# define ITEM_ATTR_DELETED 0x00000100
# define ITEM_ATTR_ATTACHMENTS 0x00000200
# define ITEM_ATTR_UNSENT 0x00000400
typedef UINT32 Warnings;
# define WARN_ALL 0x00000001
# define WARN_UNREAD 0x00000002
# define WARN_QUEUED 0x00000004
# define WARN_ATTACHMENTS 0x00000008
# define WARN_FOLDERS 0x00000010
# define WARN_ENTIRE_TRASH 0x00000020
# define WARN_ACCOUNTS 0x00000040
typedef UINT32 itemType;
# define ITEM_TYPE_FOLDER 0
# define ITEM_TYPE_MAIL 1
typedef UINT32 MBFolderItemType;
# define MBFIT_FOLDER 0
# define MBFIT_MAIL 1
# define MBFIT_DATA 2
typedef UINT32 MBFolderType;
# define MBFT_FOLDER 0
# define MBFT_INBOX 1
# define MBFT_OUTBOX 2
# define MBFT_SENT 3
# define MBFT_TRASH 4
# define MBFT_LOCAL 5
# define MBFT_ACCOUNT 6
# define MBFT_SEARCH 7
# define MBFT_DRAFTS 8
typedef UINT32 MBInboxAttr;
# define MBIA_DELETE_MESSAGES 0x0001
# define MBIA_SAVE_PASSWORD 0x0002
# define MBIA_PASSWORD_SAVED 0x0004
typedef UINT32 MBFolderAttr;
# define MBFA_FOLDER_EXPANDED 0x8000
# define MBFA_UPDATE_HEADER 0x4000
struct v3indexHeader
{
// The following is identical to v2
char id[28]; // sign that it is a right file
char longname[64]; // Full name of folder
UINT32 spaceUsed;
UINT32 spaceFreed;
UINT32 indexEnd; // position for next index item
UINT32 storeEnd; // position for adding next mail
UINT32 lastSize; // timestamp for the storage file
UINT32 version; // version ID
UINT32 count; // how many mails are in the folder
MBTYPE foldertype; // what type of folder is this?
MBATTR folderattr; // attribytes for this folder
// ------- end of v2 -------
INT32 unread; // number of unread mail in folder
// The following are for future use
UINT32 flags; // reserved1;
UINT32 reserved2; // for future use
UINT32 reserved3; // for future use
UINT32 reserved4; // for future use
UINT32 reserved5; // for future use
UINT32 reserved6; // for future use
UINT32 reserved7; // for future use
UINT32 reserved8; // for future use
UINT32 reserved9; // for future use
UINT32 reserved10; // for future use
};
//********************************************************************
struct v2indexItem
{
UINT32 start; // point to start of item data
UINT32 end; // end of item data + 1
MBATTR attr; // shows read or deleted state
};
//********************************************************************
struct v3indexItem
{
// The following is identical to v2
UINT32 start; // point to start of item data
UINT32 end; // end of item data + 1
MBATTR attr; // shows read or deleted state
// ------- end of v2 -------
UINT32 flags; // Flags (like, has attachments)
UINT32 date;
char state;
char pri;
char from[64];
char subject[64];
UINT32 reserved1;
UINT32 reserved2;
};
//********************************************************************
struct v4indexItem
{
UINT32 start; // point to start of item data
UINT32 end; // end of item data + 1
MBATTR attr; // shows read or deleted state
UINT32 flags; // Flags (like, has attachments)
UINT32 date;
char state;
char pri;
char from[256];
char subject[256];
UINT32 reserved1;
UINT32 reserved2;
};
//********************************************************************
typedef v3indexHeader indexHeader;
//typedef v4indexItem indexItem;
typedef v3indexItem indexItemSmallArray;
typedef v4indexItem indexItemLargeArray;
struct indexItem
{
UINT32 start; // point to start of item data
UINT32 end; // end of item data + 1
MBATTR attr; // shows read or deleted state
UINT32 flags; // Flags (like, has attachments)
};
OperaImporter::OperaImporter()
: m_mboxFile(NULL),
m_idxFile(NULL),
m_accounts_ini(NULL),
m_treePos(-1),
m_inProgress(FALSE),
m_version4(FALSE),
m_isTrashFolder(FALSE)
{
}
OperaImporter::~OperaImporter()
{
OP_DELETE(m_accounts_ini);
GlueFactory* glue_factory = MessageEngine::GetInstance()->GetGlueFactory();
if (m_mboxFile)
{
m_mboxFile->Close();
glue_factory->DeleteOpFile(m_mboxFile);
m_mboxFile = NULL;
}
if (m_idxFile)
{
m_idxFile->Close();
glue_factory->DeleteOpFile(m_idxFile);
m_idxFile = NULL;
}
}
OP_STATUS OperaImporter::ReadMessage(OpFileLength file_pos, UINT32 length, OpString8& message)
{
BOOL result = FALSE;
message.Empty();
if (m_mboxFile && m_mboxFile->SetFilePos(file_pos)==OpStatus::OK)
{
message.Reserve(length + 1);
OpFileLength readLength = 0;
if (m_mboxFile->Read(message.CStr(), length, &readLength) == OpStatus::OK && readLength == length)
{
message.CStr()[length] = '\0';
result = !(m_mboxFile->Eof());
OP_ASSERT(result);
}
}
return result;
}
# define MBFLAG_LARGE_ARRAYS 1 // uses index item version 4
BOOL OperaImporter::OnContinueImport()
{
OP_NEW_DBG("OperaImporter::OnContinueImport", "m2");
if (m_stopImport)
return FALSE;
if (!m_inProgress)
{
if (GetModel()->SequenceIsEmpty(m_sequence))
return FALSE;
ImporterModelItem* item = GetModel()->PullItem(m_sequence);
if (NULL != item)
{
if (OpStatus::IsSuccess(OpenMailBox(item->GetPath())))
{
indexHeader head;
OpFileLength bytes_read = 0;
if (m_idxFile->Read(&head, sizeof(indexHeader), &bytes_read) == OpStatus::OK)
{
m_version4 = (head.flags & MBFLAG_LARGE_ARRAYS);
m_isTrashFolder = (MBFT_TRASH == head.foldertype);
OpString tmp;
tmp.Set(item->GetVirtualPath());
int pos = tmp.FindLastOf('/');
if ((strlen(head.longname) > 0) && (pos != KNotFound))
{
tmp.CStr()[pos + 1] = '\0'; // get rid of short folder name
char* p = NULL;
if ((p = strstr(head.longname, "?B?")) != NULL) // It's NOT Base64, it's QP damn it!
{
*(++p) = 'Q';
}
OpString name;
QPDecode(head.longname, name);
tmp.Append(name); // use long name instead
m_m2FolderPath.Set(tmp);
}
else // fallback: use short name
{
m_m2FolderPath.Set(item->GetVirtualPath());
}
OpString acc;
GetImportAccount(acc);
m_currInfo.Empty();
m_currInfo.Set(acc);
m_currInfo.Append(UNI_L(" - "));
m_currInfo.Append(item->GetName());
if (InResumeCache(m_m2FolderPath))
{
m_idxFile->Close();
GlueFactory* glue_factory = MessageEngine::GetInstance()->GetGlueFactory();
glue_factory->DeleteOpFile(m_idxFile);
m_idxFile = NULL;
m_mboxFile->Close();
glue_factory->DeleteOpFile(m_mboxFile);
m_mboxFile = NULL;
OpString progressInfo, already_imported;
OpStatus::Ignore(progressInfo.Set(m_currInfo));
OpStatus::Ignore(g_languageManager->GetString(Str::S_ALREADY_IMPORTED, already_imported));
OpStatus::Ignore(already_imported.Insert(0, UNI_L(" ")));
OpStatus::Ignore(progressInfo.Append(already_imported));
MessageEngine::GetInstance()->OnImporterProgressChanged(this, progressInfo, 0, 0);
return TRUE;
}
m_totalCount = head.count;
m_count = 0;
MessageEngine::GetInstance()->OnImporterProgressChanged(this, m_currInfo, m_count, m_totalCount);
m_inProgress = TRUE;
}
}
}
}
else
{
OP_DBG(("OperaImporter::OnContinueImport() msg# %u of %u", m_count, m_totalCount));
BOOL eof = FALSE;
//OP_STATUS ret =
ImportSingle(eof); // jant TODO: check return value and issue err msg
if (eof)
{
m_inProgress = FALSE;
}
}
return TRUE;
}
void OperaImporter::OnCancelImport()
{
OP_NEW_DBG("OperaImporter::OnCancelImport", "m2");
OP_DBG(("OperaImporter::OnCancelImport()"));
GlueFactory* glue_factory = MessageEngine::GetInstance()->GetGlueFactory();
if (m_mboxFile)
{
if (m_mboxFile->Close() != OpStatus::OK)
{
}
glue_factory->DeleteOpFile(m_mboxFile);
m_mboxFile = NULL;
}
if (m_idxFile)
{
m_idxFile->Close();
glue_factory->DeleteOpFile(m_idxFile);
m_idxFile = NULL;
}
m_inProgress = FALSE;
}
OP_STATUS OperaImporter::OpenMailBox(const OpStringC& fullPath)
{
OP_NEW_DBG("OperaImporter::OpenMailBox", "m2");
OP_DBG(("OperaImporter::OpenMailBox( %S )", fullPath.CStr()));
OpString tmp;
tmp.Set(fullPath);
tmp.Append(UNI_L(".MBS"));
OP_DELETE(m_mboxFile);
m_mboxFile = OP_NEW(OpFile, ());
if (!m_mboxFile)
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(m_mboxFile->Construct(tmp.CStr()));
RETURN_IF_ERROR(m_mboxFile->Open(OPFILE_READ|OPFILE_SHAREDENYWRITE));
tmp.Set(fullPath);
tmp.Append(UNI_L(".IDX"));
OP_DELETE(m_idxFile);
m_idxFile = OP_NEW(OpFile, ());
if (!m_idxFile)
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(m_idxFile->Construct(tmp.CStr()));
return m_idxFile->Open(OPFILE_READ|OPFILE_SHAREDENYWRITE);
}
OP_STATUS OperaImporter::ImportSingle(BOOL& eof)
{
OP_STATUS ret = OpStatus::OK;
BOOL reallyEof = m_idxFile->Eof();
if (!m_stopImport && !reallyEof)
{
eof = FALSE;
indexItem item;
OpFileLength file_pos;
m_idxFile->GetFilePos(file_pos);
OpFileLength bytesRead = 0;
if (m_idxFile->Read(&item, sizeof(indexItem), &bytesRead) == OpStatus::OK)
{
if (bytesRead != sizeof(indexItem))
{
// This is where we really get to eof the unix way...
// we have read beyond the end of the file..
reallyEof = m_idxFile->Eof();
}
else
{
if (m_version4)
{
m_idxFile->SetFilePos(file_pos + sizeof(indexItemLargeArray));
}
else
{
m_idxFile->SetFilePos(file_pos + sizeof(indexItemSmallArray));
}
if (!(item.attr & ITEM_ATTR_DELETED))
{
OpString8 raw;
if (item.start < item.end && ReadMessage(item.start, item.end - item.start, raw))
{
Message m2_message;
ret = m2_message.Init(m_accountId);
if (OpStatus::IsSuccess(ret))
{
m2_message.SetFlag(Message::IS_READ, (!(item.attr & ITEM_ATTR_UNREAD)) || (item.attr & ITEM_ATTR_SENT));
m2_message.SetFlag(Message::IS_REPLIED, (item.attr & ITEM_ATTR_REPLIED));
m2_message.SetFlag(Message::IS_FORWARDED, (item.attr & ITEM_ATTR_FORWARDED));
m2_message.SetFlag(Message::IS_SENT, (item.attr & ITEM_ATTR_SENT));
m2_message.SetFlag(Message::IS_RESENT, (item.attr & ITEM_ATTR_REDIRECTED));
m2_message.SetFlag(Message::HAS_ATTACHMENT, (item.attr & ITEM_ATTR_ATTACHMENTS));
// needs to be outgoing for outgoing flags to take effect:
m2_message.SetFlag(Message::IS_OUTGOING, ((item.attr & ITEM_ATTR_SENT) || (item.attr & ITEM_ATTR_QUEUED)) );
m_moveCurrentToSent = ((item.attr & ITEM_ATTR_SENT) || (item.attr & ITEM_ATTR_QUEUED));
ret = m2_message.SetRawMessage(raw.CStr());
if (OpStatus::IsSuccess(ret))
{
ret = MessageEngine::GetInstance()->ImportMessage(&m2_message, m_m2FolderPath, m_moveCurrentToSent);
}
}
}
else
{
ret = OpStatus::ERR;
}
}
m_count++;
m_grandTotal++;
MessageEngine::GetInstance()->OnImporterProgressChanged(this, m_currInfo, m_count, m_totalCount);
}
}
else
{
ret = OpStatus::ERR;
}
}
if (m_stopImport || reallyEof)
{
m_idxFile->Close();
GlueFactory* glue_factory = MessageEngine::GetInstance()->GetGlueFactory();
glue_factory->DeleteOpFile(m_idxFile);
m_idxFile = NULL;
m_mboxFile->Close();
glue_factory->DeleteOpFile(m_mboxFile);
m_mboxFile = NULL;
eof = TRUE;
}
if (reallyEof)
{
AddToResumeCache(m_m2FolderPath);
}
return ret;
}
OP_STATUS OperaImporter::ImportMessages()
{
ImporterModelItem* item = GetImportItem();
if (NULL == item)
return OpStatus::ERR;
GetModel()->MakeSequence(m_sequence, item);
OpenPrefsFile();
m_inProgress = FALSE;
return StartImport();
}
OP_STATUS OperaImporter::ImportSettings()
{
OpString accountIni;
if (GetSettingsFileName(accountIni))
{
OP_STATUS ret = OpStatus::ERR;
M1_Preferences account_ini;
if (account_ini.SetFile(accountIni))
{
Account* account = MessageEngine::GetInstance()->CreateAccount();
if (account)
{
account->SetIncomingProtocol(AccountTypes::POP);
account->SetOutgoingProtocol(AccountTypes::SMTP);
account->SetDefaults();
OpString8 str8;
OpString str;
int val = 0;
if (account_ini.GetStringValue("SETTINGS", "FullName", str8))
{
QPDecode(str8, str);
account->SetRealname(str);
}
if (account_ini.GetStringValue("SETTINGS", "Organization", str8))
{
QPDecode(str8, str);
account->SetOrganization(str);
}
if (account_ini.GetStringValue("SETTINGS", "EmailAddress", str8))
{
QPDecode(str8, str);
account->SetEmail(str);
}
if (account_ini.GetStringValue("SETTINGS", "AccountName", str8))
{
QPDecode(str8, str);
account->SetAccountName(str);
}
if (account_ini.GetStringValue("SETTINGS", "ReplyTo", str8))
{
QPDecode(str8, str);
account->SetReplyTo(str);
}
if (account_ini.GetStringValue("INCOMING", "Login", str8))
{
QPDecode(str8, str);
account->SetIncomingUsername(str);
}
if (account_ini.GetStringValue("INCOMING", "Address", str8))
{
QPDecode(str8, str);
account->SetIncomingServername(str);
}
if (account_ini.GetIntegerValue("INCOMING", "Port", val))
{
account->SetIncomingPort(val);
}
if (account_ini.GetIntegerValue("INCOMING", "DeleteFromServer", val))
{
account->SetLeaveOnServer(!(BOOL)val);
}
if (account_ini.GetIntegerValue("INCOMING", "CheckInterval", val))
{
account->SetPollInterval(val * 60);
}
if (account_ini.GetIntegerValue("INCOMING", "CheckAutomation", val))
{
if (0 == val)
{
account->SetPollInterval(0); // quick and dirty...
}
}
if (account_ini.GetIntegerValue("INCOMING", "TLS", val))
{
account->SetUseSecureConnectionIn((BOOL)val);
}
if (account_ini.GetIntegerValue("INCOMING", "PlaySound", val))
{
account->SetSoundEnabled((BOOL)val);
}
if (account_ini.GetStringValue("INCOMING", "SoundFile", str8))
{
QPDecode(str8, str);
account->SetSoundFile(str);
}
if (account_ini.GetStringValue("OUTGOING", "Address", str8))
{
QPDecode(str8, str);
account->SetOutgoingServername(str);
}
if (account_ini.GetIntegerValue("OUTGOING", "Port", val))
{
account->SetOutgoingPort(val);
}
if (account_ini.GetIntegerValue("OUTGOING", "QueueMail", val))
{
account->SetQueueOutgoing((BOOL)val);
}
if (account_ini.GetIntegerValue("OUTGOING", "TLS", val))
{
account->SetUseSecureConnectionOut((BOOL)val);
}
ret = account->Init();
if (OpStatus::IsSuccess(ret))
{
if (account_ini.GetStringValue("OUTGOING", "SignatureFile", str8))
{
QPDecode(str8, str);
GlueFactory* glue_factory = MessageEngine::GetInstance()->GetGlueFactory();
OpFile* sig_file = glue_factory->CreateOpFile(str);
if (sig_file)
{
OP_STATUS err = sig_file->Open(OPFILE_READ|OPFILE_SHAREDENYWRITE);
if (OpStatus::IsError(err))
{
// Try by using filename (leaf) for signature file and look in
// 1: folder for account and at
// 2: mail root
int i = str.FindLastOf('\\');
if (i != KNotFound)
{
OpString sig_path;
OpStringC filename(str.CStr()+i+1);
OpPathDirFileCombine(sig_path, m_folder_path, filename);
glue_factory->DeleteOpFile(sig_file);
sig_file = glue_factory->CreateOpFile(sig_path);
err = sig_file ? sig_file->Open(OPFILE_READ|OPFILE_SHAREDENYWRITE) : OpStatus::ERR_NO_MEMORY;
}
}
if (OpStatus::IsSuccess(err))
{
OpFileLength length;
sig_file->GetFileLength(length);
if (length > 0)
{
char* buf = OP_NEWA(char, length + 1);
OpFileLength bytes_read = 0;
if (buf && sig_file->Read(buf, length, &bytes_read)==OpStatus::OK)
{
OpString signature;
int invalid_inp = 0;
TRAPD(rc, invalid_inp = SetFromEncodingL(&signature, g_op_system_info->GetSystemEncodingL(), buf, length));
if (rc == OpStatus::OK && invalid_inp == 0)
account->SetSignature(signature,FALSE);
OP_DELETEA(buf);
}
}
sig_file->Close();
}
glue_factory->DeleteOpFile(sig_file);
}
}
account->SaveSettings();
m_accountId = account->GetAccountId();
}
}
}
return ret;
}
return OpStatus::ERR;
}
OP_STATUS OperaImporter::Init()
{
OP_STATUS ret = OpStatus::ERR;
GetModel()->DeleteAll();
OpString8 account8;
int i = 0;
while (m_accounts_ini && m_accounts_ini->GetEntry("ACCOUNTS", account8, i++) && !account8.IsEmpty())
{
OpString account;
QPDecode(account8, account);
// TODO: Strip account, it contains garbage.
OpString fullPath;
OpPathDirFileCombine(fullPath, m_folder_path, account);
OpString accountIni;
OpStringC accountFileName(UNI_L("ACCOUNT.INI"));
OpPathDirFileCombine(accountIni, fullPath, accountFileName);
M1_Preferences account_ini;
if (account_ini.SetFile(accountIni))
{
OpString8 str8;
if (account_ini.GetStringValue("SETTINGS", "AccountName", str8))
{
OpString accountName;
QPDecode(str8, accountName);
OpString m2FolderPath, imported;
m2FolderPath.Set(accountName);
OpStatus::Ignore(g_languageManager->GetString(Str::S_IMPORTED, imported));
OpStatus::Ignore(imported.Insert(0, UNI_L(" (")));
OpStatus::Ignore(imported.Append(UNI_L(")")));
OpStatus::Ignore(m2FolderPath.Append(imported));
ImporterModelItem* item = OP_NEW(ImporterModelItem, (OpTypedObject::IMPORT_ACCOUNT_TYPE, accountName, *m_file_list.Get(0), m2FolderPath, UNI_L("")));
if (item)
{
item->SetSettingsFileName(accountIni);
INT32 branch = GetModel()->AddLast(item);
OpPathDirFileCombine(fullPath, m_folder_path, account);
ret = InsertMailBoxes(fullPath, m2FolderPath, branch);
}
}
}
}
return ret;
}
OP_STATUS OperaImporter::InsertMailBoxes(const OpStringC& basePath, const OpStringC& m2FolderPath, INT32 parentIndex)
{
OpString folderIni;
OpStringC folderFileName(UNI_L("FOLDER.INI"));
OpPathDirFileCombine(folderIni, basePath, folderFileName);
M1_Preferences folder_ini;
if (folder_ini.SetFile(folderIni))
{
OpString8 boxName8;
int i = 0;
while (folder_ini.GetEntry("MAILBOXES", boxName8, i++) && !boxName8.IsEmpty())
{
OpString boxName;
QPDecode(boxName8, boxName);
OpString virtualFolder;
virtualFolder.Set(m2FolderPath);
virtualFolder.Append(UNI_L("/"));
virtualFolder.Append(boxName);
OpString fullPath;
OpPathDirFileCombine(fullPath, basePath, boxName);
ImporterModelItem* item = OP_NEW(ImporterModelItem, (OpTypedObject::IMPORT_MAILBOX_TYPE, boxName, fullPath, virtualFolder, UNI_L("")));
if (item)
GetModel()->AddLast(item, parentIndex);
}
OpString8 subFolder8;
i = 0;
while (folder_ini.GetEntry("SUB FOLDERS", subFolder8, i++) && !subFolder8.IsEmpty())
{
OpString subFolder;
subFolder.Set(subFolder8);
OpString fullPath;
OpPathDirFileCombine(fullPath, basePath, subFolder);
InsertSubFolder(fullPath, subFolder, m2FolderPath, parentIndex);
}
}
return OpStatus::OK;
}
OP_STATUS OperaImporter::InsertSubFolder(const OpStringC& basePath,
const OpStringC& folderName,
const OpStringC& m2FolderPath,
INT32 parentIndex)
{
OpString folderIni;
OpStringC folderFileName(UNI_L("FOLDER.INI"));
OpPathDirFileCombine(folderIni, basePath, folderFileName);
M1_Preferences folder_ini;
if (folder_ini.SetFile(folderIni))
{
OpString8 name8;
OpString name;
OpString virtualFolder;
virtualFolder.Set(m2FolderPath);
if (folder_ini.GetStringValue("SETTINGS", "FolderName", name8) && !name8.IsEmpty())
{
QPDecode(name8, name);
virtualFolder.Append("/");
virtualFolder.Append(name);
}
OpString fullPath;
OpPathDirFileCombine(fullPath, basePath, folderName);
ImporterModelItem* item = OP_NEW(ImporterModelItem, (OpTypedObject::IMPORT_FOLDER_TYPE,
(name.IsEmpty()) ? UNI_L("<folder>") : name.CStr(),
fullPath, virtualFolder, UNI_L("")));
if (item)
{
INT32 branch = GetModel()->AddLast(item, parentIndex);
InsertMailBoxes(basePath, virtualFolder, branch);
}
}
return OpStatus::OK;
}
OP_STATUS OperaImporter::AddImportFile(const OpStringC& path)
{
RETURN_IF_ERROR(Importer::AddImportFile(path));
OP_DELETE(m_accounts_ini);
m_accounts_ini = NULL;
OpStackAutoPtr<M1_Preferences> prefs(OP_NEW(M1_Preferences, ()));
RETURN_OOM_IF_NULL(prefs.get());
if (!prefs->SetFile(path))
return OpStatus::ERR;
m_accounts_ini = prefs.release();
m_accounts_ini->GetStringValue("Settings", "DefaultEncoding", m_defaultCharset);
// Define folder path since it is used abundantly
OpString dir;
TRAPD(err, SplitFilenameIntoComponentsL(path, &dir, NULL, NULL));
RETURN_IF_ERROR(err);
return SetImportFolderPath(dir);
}
void OperaImporter::GetDefaultImportFolder(OpString& path)
{
OpString iniPath;
if (GetOperaIni(iniPath))
{
M1_Preferences opera_ini;
opera_ini.SetFile(iniPath);
OpString8 mailRoot8;
if (opera_ini.GetStringValue("Mail", "Mail Root Directory", mailRoot8) && !mailRoot8.IsEmpty())
{
OpString mailRoot;
mailRoot.Set(mailRoot8);
OpStringC iniName(UNI_L("ACCOUNTS.INI"));
OpPathDirFileCombine(path, mailRoot, iniName);
}
}
}
BOOL OperaImporter::GetOperaIni(OpString& fileName)
{
BOOL exists = FALSE;
#ifdef MSWIN
unsigned long size = 1024;
OpString path;
path.Reserve(size);
BrowserUtils* bu = MessageEngine::GetInstance()->GetGlueFactory()->GetBrowserUtils();
if (bu->OpRegReadStrValue(HKEY_CURRENT_USER, UNI_L("Software\\Opera Software"),
UNI_L("Last CommandLine"), path.CStr(), &size) != OpStatus::OK)
{
return FALSE;
}
OP_STATUS ret = OpStatus::OK;
// check if we have a custom commandline with .ini file as parameter
int first = path.FindFirstOf('"');
if (KNotFound != first)
{
int last = path.FindLastOf('"');
OpString iniPath;
path.Set(path.CStr() + first + 1, last - (first + 1));
ret = DesktopOpFileUtils::Exists(path, exists);
}
else
{
first = path.FindI(UNI_L("\\opera.exe"));
if (KNotFound != first)
{
path.CStr()[first] = 0; // get rid of exe-filename
OpString keep;
keep.Set(path);
path.Append(UNI_L("\\opera6.ini"));
ret = DesktopOpFileUtils::Exists(path, exists);
if (ret==OpStatus::OK && !exists) // try older version
{
path.Set(keep);
path.Append(UNI_L("\\opera5.ini"));
ret = DesktopOpFileUtils::Exists(path, exists);
}
}
}
fileName.Set(path);
#endif // MSWIN, TODO: find ini file for other platforms
return exists;
}
BOOL OperaImporter::GetContactsFileName(OpString& fileName)
{
if (m_folder_path.IsEmpty())
return FALSE;
fileName.Set(m_folder_path);
int sep = fileName.FindLastOf(PATHSEPCHAR);
if (sep != KNotFound)
{
fileName.CStr()[sep + 1] = 0;
fileName.Append("contacts.adr");
BOOL exists;
if (DesktopOpFileUtils::Exists(fileName, exists) == OpStatus::OK &&
exists)
{
return TRUE;
}
}
return FALSE;
}
void OperaImporter::QPDecode(const OpStringC8& src, OpString& decoded)
{
if (src.IsEmpty())
return;
const int qp_max_len_decode = 512;
BOOL warn = FALSE;
BOOL err = FALSE;
OpQP::Decode(src, decoded, m_defaultCharset, warn, err);
if (err)
{
// try to convert using native conversion
char* pos = NULL;
if ((pos = (char *)strstr(src.CStr(), "?Q?")) != NULL)
{
// get rid of qp-garbage
char* str = pos + 3;
if ((pos = strstr(str, "?")) != NULL)
{
*(pos) = '\0';
decoded.Reserve(qp_max_len_decode + 1);
TRAPD(rc, SetFromEncodingL(&decoded, g_op_system_info->GetSystemEncodingL(), str, qp_max_len_decode));
}
}
else
{
decoded.Set(src); // give up, use raw
}
}
}
#endif //M2_SUPPORT
|
#include <iostream>
#include <queue>
#include <vector>
int n, m, check[32001];
std::vector<int> next[32001];
std::priority_queue<int> pq;
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::cin >> n >> m;
for(int i = 0; i < m; i++)
{
int A, B;
std::cin >> A >> B;
next[A].push_back(B);
check[B]++;
}
for(int i = 1; i <= n; i++)
{
if(check[i] == 0)
{
pq.push(-i);
}
}
while(!pq.empty())
{
int top = -pq.top();
pq.pop();
std::cout << top << ' ';
for(int x : next[top])
{
check[x]--;
if(check[x] == 0)
{
pq.push(-x);
}
}
}
return 0;
}
|
#pragma once
namespace BeeeOn {
/**
* Very simple evaluator of math expressions. It performs operations
* with left-associativity. Thus, there is no operator precedence
* applicated. Examples:
*
* y = 2 + 5 * 1 - 3 / 2 * 5
* -> 7 * 1 - 3 / 2 * 5
* -> 7 - 3 / 2 * 5
* -> 4 / 2 * 5
* -> 2 * 5
* -> 10
*/
class SimpleCalc {
public:
double evaluate(const std::string &input) const;
protected:
double parseTerm(
std::string::const_iterator &at,
std::string::const_iterator end) const;
char parseOpOrEOF(
std::string::const_iterator &at,
std::string::const_iterator end) const;
void skipWhitespace(
std::string::const_iterator &at,
std::string::const_iterator end) const;
void apply(double &result, char op, double tmp) const;
bool isWhitespace(const char c) const;
bool isOperator(const char c) const;
bool isTerm(const char c) const;
};
}
|
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
#include <random>
#include <chrono>
using namespace std::chrono;
#include <ctime>
// class called stopwatch that uses the chrono header
class StopWatch {
public:
auto StartWatch() {
//Creates the first time point
auto start = steady_clock::now();
return start;
}
auto EndWatch() {
// creates the second time point
auto now = steady_clock::now();
return now;
}
double PrintWatch(time_point<steady_clock> end, time_point<steady_clock>start) {
//makes the elapsed time between timepints be nanoseconds
double elapsed_time = double(duration_cast<nanoseconds>(end-start).count());
//manually convert nanoseconds to seconds for a more accurate StopWatch
cout << elapsed_time/1e9;
return elapsed_time;
}
};
// main file that uses the class StopWatch
int main() {
//Generates a random number between 10 million and 1 Billion
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<>dis(10000000, 1000000000);
StopWatch watch;
cout << "testing: " << dis(gen) << endl;
//Starts the Stopwatch
auto start = watch.StartWatch();
//Prints nothing so that that the console wont be filled with
// empty spaces or random numbers
for (int i = 0; i < dis(gen); i++) {
cout << "";
}
//ends the stopwatch
auto end = watch.EndWatch();
//Prints the time it took to complete the loop
cout << "ended in: ";
watch.PrintWatch(end, start);
cout << " seconds\n";
//starts second stopwatch
auto start2 = watch.StartWatch();
std::vector<int> v(10000000, 9);
// uses binary_search to look for the three in the vector
cout << "looking for a 3... ";
if(std::binary_search(v.begin(), v.end(), 3))
cout << "found!\n"; else cout << "not found.\n";
// ends second stopwatch
auto end2 = watch.StartWatch();
//prints the time it took to find the three
cout << "ended in: ";
watch.PrintWatch(end2, start2);
cout << " seconds\n";
}
|
#include <stdio.h> // basic I/O
#include <stdlib.h>
#include <sys/types.h> // standard system types
#include <netinet/in.h> // Internet address structures
#include <sys/socket.h> // socket API
#include <arpa/inet.h>
#include <netdb.h> // host to IP resolution
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <iostream>
using namespace std;
#define BUFFER_SIZE 256
// prototype
void checkParameters(int argc, char *argv[]);
int openSocket(void);
void bindSocket(int sock_id, struct sockaddr_in srv_ad);
int acceptConn(int s_sock_id, struct sockaddr_in cli_ad);
void recvMessage(int sock_id, char buff[], int buff_size);
void sendMessage(int sock_id, char buff[], int buff_size);
void clearBuffer(char buff[]);
void sendHello(int sock_id);
void printWelcome(int port);
void printAccept(struct sockaddr_in cli_ad);
void printClientDisconnect(void);
bool isExit(char buff[]);
int main(int argc, char *argv[])
{
// variable definitions
int s_sock_fd, c_sock_fd, port;
socklen_t clilen;
struct sockaddr_in srv_ad, cli_ad;
char buff[BUFFER_SIZE];
checkParameters(argc, argv); // check parameters
port = atoi(argv[1]); // getting port no.
s_sock_fd = openSocket(); // open socket
// server details
srv_ad.sin_family = AF_INET;
srv_ad.sin_addr.s_addr = INADDR_ANY;
srv_ad.sin_port = htons(port);
bindSocket(s_sock_fd, srv_ad); // binding socket
printWelcome(port);
listen(s_sock_fd, 5); // starts listening for clients
while (true)
{
c_sock_fd = acceptConn(s_sock_fd, cli_ad); // accepting connection from client
printAccept(cli_ad);
sendHello(c_sock_fd);
do
{
clearBuffer(buff);
cout << "c : ";
recvMessage(c_sock_fd, buff, BUFFER_SIZE);
cout << buff << endl;
} while (isExit(buff));
printClientDisconnect();
close(c_sock_fd);
}
close(s_sock_fd);
return 0;
}
void checkParameters(int argc, char* argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(-1);
}
}
int openSocket(void)
{
int sock_id = socket(AF_INET, SOCK_STREAM, 0);
if (sock_id < 0)
{
cout << "Error : Opening Socket\n";
exit(-1);
}
return sock_id;
}
void bindSocket(int sock_id, struct sockaddr_in srv_ad)
{
int srv_size = sizeof(srv_ad);
if (bind(sock_id, (struct sockaddr *) &srv_ad, srv_size) < 0)
{
cout << "Error : Binding Socket\n";
exit(-1);
}
}
int acceptConn(int s_sock_id, struct sockaddr_in cli_ad)
{
socklen_t clilen;
clilen = sizeof(cli_ad);
int c_sock_id = accept(s_sock_id, (struct sockaddr *) &cli_ad, &clilen);
if (c_sock_id < 0)
{
cout << "Error : Accepting Connection\n";
exit(-1);
}
return c_sock_id;
}
void recvMessage(int sock_id, char buff[], int buff_size)
{
int x = read(sock_id, buff, buff_size);
if (x < 0)
{
cout << "Error : reading from socket failed\n";
exit(-1);
}
}
void sendMessage(int sock_id, char buff[], int buff_size)
{
int x = write(sock_id, buff, buff_size);
if (x < 0)
{
cout << "Error : writing to socket failed\n";
exit(-1);
}
}
void clearBuffer(char buff[])
{
bzero(buff, BUFFER_SIZE);
}
void sendHello(int sock_id)
{
int x = write(sock_id, "Hello from this of the world", 28);
if (x < 0)
{
cout << "Error : writing to socket failed\n";
exit(-1);
}
}
void printWelcome(int port)
{
cout << "\nStarting to run server at port " << port
<< "\n.. creating local listener socket\n"
<< ".. binding socket to port:"<< port
<< "\n.. starting to listen at the port\n"
<< ".. waiting for connection \n\n";
}
void printAccept(struct sockaddr_in cli_ad)
{
cout << "\nClient connected to server...\n\n";
}
void printClientDisconnect(void)
{
cout << "\nBrother please don't go...\n\n"
<< "Listening to clients again... \n\n";
}
bool isExit(char buff[])
{
for (int i = 0; buff[i]; i++)
{
buff[i] = tolower(buff[i]);
}
if (strncmp(buff, "exit", 4) == 0)
{
return false;
}
else
{
return true;
}
}
|
/* -*- 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.
*/
#ifndef ACTUTIL_H
#define ACTUTIL_H
#include "modules/search_engine/ACT.h"
#include "modules/search_engine/BSCache.h"
#if FIRST_CHAR >= 2
#define TRIE_SIZE 254
#else
#define TRIE_SIZE 306
#endif
//#define MAX_OFFSET_VALUE (TRIE_SIZE - 20)
#define MAX_OFFSET_VALUE TRIE_SIZE - 1
/*
* record representing one character in ACT structure
*
* Invariants:
*
* 1) Free nodes
* a) cannot be a word
* b) cannot have a child
* c) cannot be final
* d) offset, id and parent are undefined
*
* 2) Leaf nodes
* a) are final
* b) cannot have a child
* c) offset is undefined
* d) if it is a word, id identifies the word
* e) if it is not a word, tail compression must be in use and id identifies the word
* f) parent is defined, or 0 for the root node
*
* 3) Internal nodes
* a) are not final
* b) must have a disk child, a memory child or an interleaved child determined by offset
* c) if it is a word, id identifies the word
* d) if it is not a word, id is undefined
* e) parent is defined, or 0 for the root node
*/
class TrieNode
{
private:
friend class TrieBranch;
enum Flags
{
Free = 1,
DiskChild = 2,
MemoryChild = 4,
Child = DiskChild | MemoryChild,
Word = 8,
Final = 16
};
TrieNode()
{
mem_child = 0;
flags_parent = Free << 11;
id = 0;
}
int GetFlags() const
{
return flags_parent >> 11;
}
BOOL IsFree() const { return (GetFlags() & Free) != 0; }
BOOL IsWord() const { return (GetFlags() & Word) != 0; }
BOOL IsFinal() const { return (GetFlags() & Final) != 0; }
BOOL HasChild() const { return (GetFlags() & Child) != 0; }
BOOL HasDiskChild() const { return (GetFlags() & DiskChild) != 0; }
BOOL HasMemoryChild() const { return (GetFlags() & MemoryChild) != 0; }
void SetFlags(int f)
{
flags_parent = (UINT16)((flags_parent & 0x7FF) | (f << 11));
OP_ASSERT(!(HasDiskChild() && HasMemoryChild()));
OP_ASSERT(!IsFree() || (!HasChild() && !IsFinal() && !IsWord()));
}
int GetOffset() const
{
OP_ASSERT(!IsFree() && !IsFinal() && !HasChild());
OP_ASSERT(offset + 255 - FIRST_CHAR > 0 && offset < TRIE_SIZE);
return offset;
}
void SetOffset(int offset)
{
OP_ASSERT(offset + 255 - FIRST_CHAR > 0 && offset < TRIE_SIZE);
this->offset = offset;
}
BSCache::Item::DiskId GetDiskChild() const
{
OP_ASSERT(!IsFree() && !IsFinal() && HasDiskChild());
return disk_child;
}
void SetDiskChild(BSCache::Item::DiskId disk_child)
{
this->disk_child = disk_child;
}
TrieBranch *GetMemoryChild() const
{
OP_ASSERT(!IsFree() && !IsFinal() && HasMemoryChild());
return mem_child;
}
void SetMemoryChild(TrieBranch *mem_child)
{
this->mem_child = mem_child;
}
int GetParent() const
{
return flags_parent & 0x7FF;
}
void SetParent(int p)
{
flags_parent = (UINT16)((flags_parent & 0xF800) | p);
}
ACT::WordID GetId() const
{
return id;
}
void SetId(ACT::WordID id)
{
this->id = id;
}
BOOL Equals(const TrieNode& n) const
{
return (flags_parent == n.flags_parent && id == n.id &&
IsFree() ||
((!HasDiskChild() || disk_child == n.disk_child) &&
(!HasMemoryChild() || mem_child == n.mem_child) &&
(HasChild() || IsFinal() || offset == n.offset)));
}
void Pack(char *to);
void Unpack(char *from);
static int GetPackedSize() { return 10; }
// 8B union int offset/int disk_child/* mem_child
// 2B 5b flags, 11b parent
// 4B word id
union {
BSCache::Item::DiskId disk_child;
INT32 offset;
TrieBranch *mem_child;
};
UINT16 flags_parent;
ACT::WordID id;
public:
static int SwitchEndian(void *data, int size, void *user_arg);
};
/*
* one branch in ACT structure, consists of TrieNode[TRIE_SIZE]
*/
class TrieBranch : public BSCache::Item
{
public:
TrieBranch(int id, TrieBranch *rbranch, int rnode, unsigned short nur);
TrieBranch(OpFileLength id, unsigned short nur);
UINT32 NumFilled() const { return (UINT32)data[0].GetId(); }
CHECK_RESULT(virtual OP_STATUS Read(BlockStorage *storage));
CHECK_RESULT(virtual OP_STATUS Write(BlockStorage *storage));
CHECK_RESULT(virtual OP_STATUS Flush(BlockStorage *storage));
virtual void OnIdChange(DiskId new_id, DiskId old_id);
static int GetPackedSize() { return TRIE_SIZE * TrieNode::GetPackedSize(); }
static void MoveNode(TrieBranch* dst, int to, TrieBranch* src, int from, BOOL freeSrc);
#define AR OP_ASSERT(i >= 0 && i < TRIE_SIZE)
BOOL IsFree (int i) const { AR; return data[i].IsFree(); }
BOOL IsWord (int i) const { AR; return data[i].IsWord(); }
BOOL IsFinal (int i) const { AR; return data[i].IsFinal(); }
BOOL HasChild (int i) const { AR; return data[i].HasChild(); }
BOOL HasDiskChild (int i) const { AR; return data[i].HasDiskChild(); }
BOOL HasMemoryChild (int i) const { AR; return data[i].HasMemoryChild(); }
int GetOffset (int i) const { AR; return data[i].GetOffset(); }
DiskId GetDiskChild (int i) const { AR; return data[i].GetDiskChild(); }
TrieBranch* GetMemoryChild (int i) const { AR; return data[i].GetMemoryChild(); }
int GetParent (int i) const { AR; return data[i].GetParent(); }
ACT::WordID GetId (int i) const { AR; return data[i].GetId(); }
void SetFree (int i) { SetFlags(i, TrieNode::Free); }
void SetFinal (int i) { SetFlags(i, TrieNode::Final); }
void SetFinalWord (int i) { SetFlags(i, TrieNode::Final | TrieNode::Word); }
void SetIsWord (int i) { SetFlags(i, (GetFlags(i) & ~TrieNode::Free) | TrieNode::Word); }
void SetIsNotWord (int i) { SetFlags(i, GetFlags(i) & ~TrieNode::Word); }
void SetOffset (int i, int offset);
void SetDiskChild (int i, DiskId disk_child);
void SetMemoryChild (int i, TrieBranch *mem_child);
void SetParent (int i, int p);
void SetId (int i, ACT::WordID id);
#ifdef _DEBUG
static BOOL CheckIntegrity(const TrieBranch *branch, ACT *act);
#endif
private:
TrieBranch *parent_branch;
int parent_pos;
TrieNode data[TRIE_SIZE];
void Pack();
void Unpack();
int GetFlags(int i) const { AR; return data[i].GetFlags(); }
void SetFlags(int i, int f);
void IncNumFilled()
{
OP_ASSERT(data[0].GetId() < TRIE_SIZE-1);
data[0].SetId(data[0].GetId() + 1);
}
void DecNumFilled()
{
OP_ASSERT(data[0].GetId() > 0);
data[0].SetId(data[0].GetId() - 1);
}
#undef AR
};
/*
* keep track of all children of a given parent character
*/
class Fitter : public NonCopyable
{
public:
Fitter()
{
distances = NULL;
size = 0;
reserved_node = -1;
src = NULL;
parent = -1;
}
~Fitter() {Reset();}
void Reset()
{
if (distances != NULL)
{
OP_DELETEA(distances);
distances = NULL;
}
}
CHECK_RESULT(OP_STATUS Parse(TrieBranch *b, int parent));
CHECK_RESULT(OP_STATUS ParseAll(TrieBranch *b));
void AddNode(char node);
int Fit(TrieBranch *b, int start);
int GetSize()
{
if (distances == NULL)
return 0;
return size;
}
int GetOrigin()
{
return size > 0 ? distances[0] : 0;
}
int GetOffset(int pos)
{
return pos == 0 ? 0 : distances[pos];
}
int GetAOffset()
{
if (size <= 0)
return 0;
return reserved_node;
}
private:
int *distances;
int size;
int reserved_node;
TrieBranch *src;
int parent;
};
/*
* pointer to the given character in a branch,
* loads/uloads the branches automatically as needed
*/
class NodePointer
{
public:
NodePointer(const NodePointer ©)
{
BSCache::Item *cp = NULL;
act = copy.act;
if (copy.branch != NULL)
{
act->Load(&cp, copy.branch);
branch = (TrieBranch *)cp;
}
else
branch = NULL;
offset = copy.offset;
parent = copy.parent;
}
NodePointer(ACT *owner)
{
act = owner;
branch = NULL;
offset = -1;
parent = -1;
}
~NodePointer()
{
Reset();
}
NodePointer &operator=(const NodePointer ©)
{
act = copy.act;
Reset(copy.branch);
offset = copy.offset;
parent = copy.parent;
return *this;
}
typedef BSCache::Item::DiskId DiskId;
CHECK_RESULT(OP_STATUS Reset(DiskId block_no));
void Reset(TrieBranch *b = NULL);
BOOL ValidChar(char position);
CHECK_RESULT(OP_STATUS Goto(char position));
CHECK_RESULT(OP_STATUS NewNode(int position));
int GetChildrenSize(int node_parent = 0);
BOOL Reposition(int node_parent = 0, char next_char = 0);
BOOL Merge(int branch_parent);
CHECK_RESULT(OP_STATUS Move(int move_parent));
CHECK_RESULT(OP_STATUS MoveChildren(NodePointer src, NodePointer dst, unsigned char next_char, BOOL *parent_moved));
CHECK_RESULT(static OP_STATUS GetSubTree(char **result, int *count, NodePointer t, int max));
CHECK_RESULT(static OP_STATUS GetSubTree(ACT::WordID *result, int *count, NodePointer t, int max));
CHECK_RESULT(static OP_STATUS GetFirstEntry(ACT::PrefixResult &result, NodePointer t));
CHECK_RESULT(static OP_BOOLEAN GetNextEntry(ACT::PrefixResult &result, NodePointer t, const char *prev_str));
BOOL IsFree () const { return branch->IsFree(offset); }
BOOL IsWord () const { return branch->IsWord(offset); }
BOOL IsFinal () const { return branch->IsFinal(offset); }
BOOL HasChild () const { return branch->HasChild(offset); }
BOOL HasDiskChild () const { return branch->HasDiskChild(offset); }
BOOL HasMemoryChild () const { return branch->HasMemoryChild(offset); }
int GetOffset () const { return branch->GetOffset(offset); }
DiskId GetDiskChild () const { return branch->GetDiskChild(offset); }
TrieBranch* GetMemoryChild () const { return branch->GetMemoryChild(offset); }
int GetParent () const { return branch->GetParent(offset); }
ACT::WordID GetId () const { return branch->GetId(offset); }
void SetFree () { branch->SetFree(offset); }
void SetFinal () { branch->SetFinal(offset); }
void SetFinalWord () { branch->SetFinalWord(offset); }
void SetIsWord () { branch->SetIsWord(offset); }
void SetIsNotWord () { branch->SetIsNotWord(offset); }
void SetOffset (int o) { branch->SetOffset(offset, o); }
void SetDiskChild (DiskId dc) { branch->SetDiskChild(offset, dc); }
void SetMemoryChild (TrieBranch *mc) { branch->SetMemoryChild(offset, mc); }
void SetParent (int p) { branch->SetParent(offset, p); }
void SetId (ACT::WordID id) { branch->SetId(offset, id); }
CHECK_RESULT(OP_STATUS Flush(TrieBranch *branch));
int GetSuperParent(int o)
{
register int p;
while ((p = branch->GetParent(o)) != 0)
o = p;
return o;
}
int GetCurrentParent()
{
return parent;
}
int GetCurrentOffset()
{
return offset;
}
void SetCurrentOffset(int o)
{
offset = o;
}
DiskId GetCurrentBranch()
{
return branch->disk_id;
}
TrieBranch *GetCurrentPointer()
{
return branch;
}
private:
ACT *act;
TrieBranch *branch;
int offset;
int parent;
};
#endif // ACTUTIL_H
|
/*
* Copyright 2019 LogMeIn
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <chrono>
#include <functional>
#include <memory>
#include <vector>
namespace asyncly {
using clock_type = std::chrono::steady_clock;
class IExecutor;
typedef std::shared_ptr<IExecutor> IExecutorPtr;
typedef std::weak_ptr<IExecutor> IExecutorWPtr;
class IScheduler;
typedef std::shared_ptr<IScheduler> ISchedulerPtr;
class IStrand;
typedef std::shared_ptr<IStrand> IStrandPtr;
class IExecutorController;
typedef std::unique_ptr<IExecutorController> IExecutorControllerUPtr;
class SchedulerThread;
using ThreadInitFunction = std::function<void()>;
struct ThreadPoolConfig {
std::vector<ThreadInitFunction> executorInitFunctions;
ThreadInitFunction schedulerInitFunction;
};
struct ThreadConfig {
ThreadInitFunction executorInitFunction;
ThreadInitFunction schedulerInitFunction;
};
}
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <utility>
using namespace std;
//// METHODS TO MANAGE MESSAGE
/**
* Purpose:
* Convert char* to string
* Params:
* - buffer (char *) : array of char.
* Return a string.
*/
string buffertToString(char* buffer){
string s(buffer);
return s;
}
/**
* Purpose:
* segmentation string by delimite
* Params:
* - msg (string) : message will segment.
* - delimiter (string): token to create segmentation in string
* Return a pairt: first is segmentation and other if rest of string.
*/
pair<string, string> segmentationString(string msg, string delimiter){
size_t pos = 0;
pair<string,string> rpta = make_pair("", msg);
if((pos = msg.find(delimiter) ) != string::npos){
rpta.first = msg.substr(0, pos);
msg.erase(0, pos + delimiter.length());
rpta.second = msg;
}
return rpta;
}
/**
* Purpose:
* comparing 2 string are same.
* Params
* - a (string) : message first.
* - b (string) : message second.
* return boolean is same or not.
*/
bool comparingString(string a, string b){
int minSize = min(a.length(), b.length());
bool rpta = true;
for( int idx = 0; idx < minSize; idx++){
if(a[idx] != b[idx]){
rpta = false;
break;
}
}
return rpta;
}
//// METHODS OF SOCKET
/**
* Purpose:
* read message from client.
* Params:
* - connect: id of connection.
* - buffer: buffer to store message.
* - size_buffer: max size of buffer.
* Return message or error
*/
void readSocket(int connect, char buffer[], int size_buffer){
int n = read(connect, buffer, size_buffer);
if(n < 0)
throw string("ERROR reading from socket");
}
/**
* Purpose:
* write message to client.
* Params:
* - connect: id of connection.
* - msg: message of client.
* - size_buffer: max size of buffer.
* Return error or None.
*/
void writeSocket(int connect, const char* msg, int size_buffer)
{
int n = write(connect, msg, size_buffer);
if(n < 0)
throw string("ERROR writing to socket");
}
|
#include "widget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDebug>
#include <QString>
#include <QMessageBox>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->setWindowTitle("多功能计算器");
this->setMinimumSize(400, 200);
this->setMaximumSize(400, 200);
op1 = new QLineEdit(this);
op2 = new QLineEdit(this);
result = new QLineEdit(this);
op1->setAlignment(Qt::AlignCenter);
op2->setAlignment(Qt::AlignCenter);
result->setAlignment(Qt::AlignCenter);
//result->setEnabled(false);
result->setFocusPolicy(Qt::NoFocus);
symbol = new QComboBox(this);
symbol->addItem("+");
symbol->addItem("-");
symbol->addItem("*");
symbol->addItem("/");
symbol->addItem("%");
equal = new QLabel("=", this);
QHBoxLayout *hbox1 = new QHBoxLayout;
hbox1->addWidget(op1);
hbox1->addWidget(symbol);
hbox1->addWidget(op2);
hbox1->addWidget(equal);
hbox1->addWidget(result);
QHBoxLayout *hbox2 = new QHBoxLayout;
btn1 = new QPushButton("计算", this);
btn2 = new QPushButton("清除", this);
hbox2->addStretch();
hbox2->addWidget(btn1);
hbox2->addWidget(btn2);
hbox2->addStretch();
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addLayout(hbox1);
vbox->addLayout(hbox2);
setLayout(vbox);
connect(btn1, SIGNAL(clicked(bool)), this, SLOT(calculatorResult()));
connect(btn2, SIGNAL(clicked(bool)), this, SLOT(clearText()));
}
Widget::~Widget()
{
}
void Widget::calculatorResult()
{
QString str1 = op1->text();
QString str2 = op2->text();
int num, dat1, dat2;
bool ok = true;
if (!str1.isEmpty() && !str2.isEmpty()) {
dat1 = str1.toInt();
dat2 = str2.toInt();
switch (symbol->currentIndex())
{
case 0: {
num = dat1 + dat2;
break;
}
case 1: {
num = dat1 - dat2;
break;
}
case 2: {
num = dat1 * dat2;
break;
}
case 3: {
if (0 != dat1){
num = dat1 / dat2;
} else {
QMessageBox::information(this, "错误信息", "除数不能为0");
ok = false;
}
break;
}
case 4: {
if (0 != dat1){
num = dat1 % dat2;
} else {
QMessageBox::information(this, "错误信息", "除数不能为0");
ok = false;
}
break;
}
}
if (ok) {
result->setText(QString::number(num)); //整数转字符串默认十进制
}
} else {
QMessageBox::information(this, "错误信息", "计算数不能为空");
}
}
void Widget::clearText()
{
op1->clear();
op2->clear();
result->clear();
}
|
#include "positionComponents.h"
positionComponents::positionComponents(float x, float y) {
this->xposition = x;
this->yposition = y;
}
float positionComponents::getxposition() {
return xposition;
}
float positionComponents::getYposition() {
return yposition;
}
|
#include <queue>
#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <vector>
#include <graphicsim.h>
using namespace std;
class taxiway;
extern vector<taxiway*> mainPath;
extern taxiway *rwCommon;
extern vector<taxiway*> toGate;
extern vector<taxiway*> fromGate;
class simEntity{
public:
virtual void wakeup() = 0;
};
class simQueue {
float time;
priority_queue<pair<float,simEntity*>, vector<pair<float,simEntity*> >,
greater<pair<float,simEntity*> > > pq;
public:
simQueue(){time=0;}
void insert(float dT, simEntity *pP){
pq.push(make_pair(time+dT,pP));
}
void process_till_empty(){
pair<float,simEntity*> sqe;
while(!pq.empty() && time < 1000){
sqe = pq.top();
time =sqe.first;
pq.pop();
sqe.second->wakeup();
}
}
ostream & log(){
cout << time << ") ";
return cout;
}
};
extern simQueue sq;
class plane : public Polygon, public simEntity {
public:
static const float pts_body[4][2];
int id;
int arrivalT;
int serviceT;
int segment;
int subsegment;
int timeToSegmentEnd;
int gate;
float stepsize;
void wakeup();
void init(){
setFillColor(COLOR("blue"));
setFill(true);
penDown();
}
plane() : Polygon(0, 0, pts_body, 4){ init();};
plane(int i, int at, int st) : Polygon(pts_body, 4, Position(0,0), 0){
timeToSegmentEnd = 0;
id = i;
arrivalT = at;
segment = -1; // currently before the runway.
subsegment = 0;
serviceT = st;
init();
// hide();
};
bool turnoff(int segment);
void move_along_current_segment();
void process_detour_to_gate();
void process_entry_to_next_segment();
void enter(taxiway *ptw);
};
class resource : public queue<simEntity*>{
public:
simEntity* owner;
resource(){owner = NULL;};
bool reserve(simEntity* pPlane){
if (owner ==NULL)
owner = pPlane;
return owner == pPlane;
}
void await(simEntity* pS){
push(pS); // should be called only if reserve fails.
}
void release(){
if(!empty()){
owner = front();
pop();
owner->wakeup();
}
else owner = NULL;
}
};
class taxiway : public Line, public resource{
public:
int id;
int delay;
taxiway();
taxiway(float xa, float ya, float xb, float yb, int trT,int i)
: Line(Position(xa,ya),Position(xb,yb)){
delay = trT;
id = i;
}
};
const int nGates=10;
const int RW1X1=100, RW1Y1=100, RW1X2=900, RW1Y2=300;
const int RW2X1=100, RW2Y1=300, RW2X2=900, RW2Y2=100;
const int RWXm=500, RWYm=200;
const int TWX1=950, TWY1=500, TWX2=50, TWY2=500;
const int TWYT = 600; // level of the terminals
|
//: C14:Car.cpp
// Public composition
class Engine {
public:
void start() const {}
void rev() const {}
void stop() const {}
};
class Wheel {
public:
void inflate(int psi) const {}
};
class Window {
public:
void rollup() const {}
void rolldown() const {}
};
class Door {
public:
Window window;
void open() const {}
void close() const {}
};
class Vehicle{
public:
Vehicle(int clr) : colour(clr) {}
int colour;
};
class Car : public Vehicle {
public:
Car(int clr) : Vehicle(clr) {}
Engine engine;
Wheel wheel[4];
Door left, right; // 2-door
};
int main() {
Car car(321);
car.left.window.rollup();
car.wheel[0].inflate(72);
} ///:~
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Вычислить удвоенное число, добавить к нему 5 и снова удвоить результат
// а так неправильно!
// int result = 10 << 1 + 5 << 1;
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include<iostream>
using namespace std;
int main() {
int result = ((10 << 1) + 5) << 1; // Удвоение результата деления на 3
cout << result << endl;
return 0;
}
/* Output:
50
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
|
#ifndef FORMAT_H
#define FORMAT_H
#include <codecvt>
#include <locale>
#include <string>
#include <list>
namespace utils {
inline std::wstring s2ws(const std::string &str)
{
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(str);
}
inline std::string ws2s(const std::wstring &wstr)
{
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(wstr);
}
class CFormat
{
public:
CFormat(const std::wstring &format_string);
operator const std::wstring & () const
{
return _formatString;
}
template<typename CType>
CFormat &operator<<(const CType &val)
{
return Arg(val);
}
private:
CFormat &Arg(const wchar_t *str)
{
return Append( std::wstring(str) );
}
CFormat &Arg(const std::wstring &str)
{
return Append(str);
}
CFormat &Arg(const char *str)
{
return Append( s2ws(str) );
}
CFormat &Arg(const unsigned char *str)
{
return Append( s2ws( reinterpret_cast<const char *>(str) ) );
}
CFormat &Arg(const std::string &str)
{
return Append( s2ws(str) );
}
template<typename CType>
CFormat &Arg(const CType &val)
{
return Append( std::to_wstring(val) );
}
CFormat &Append(const std::wstring &arg);
std::list<std::wstring> _tokens;
std::wstring _formatString;
};
} // namespace utils
#endif // FORMAT_H
|
/*
Coded by: Rajendra Jain on March 23 2017.
This is my attempt to create a library of classes dealing with time.
The background work comes from the TimeLib
The Virtual base class TimeClass maintains the methods to maintain manage
time within a local clock. It updates the local clock from a time source every
syncInterval via the virtual function virtual time_t getTimeFromSource()=0;
The derived classes DS1307RTCClass, and NISTClass provide the time every
syncInterval through calls made via getTimeFromSource().
This project is licensed under the terms of the MIT license.
*/
#ifndef _TIMECLASS_
#define _TIMECLASS_ 1
#include <ESP8266WiFi.h>
#include "defines.h"
typedef enum {timeNotSet, timeNeedsSync, timeSet
} timeStatus_t ;
typedef enum {
dowInvalid, dowSunday, dowMonday, dowTuesday,
dowWednesday, dowThursday, dowFriday, dowSaturday
} timeDayOfWeek_t;
typedef enum {
tmSecond, tmMinute, tmHour, tmWday,
tmDay, tmMonth, tmYear, tmNbrFields
} tmByteFields;
typedef struct {
uint8_t Second;
uint8_t Minute;
uint8_t Hour;
uint8_t Wday; // day of week, sunday is day 1
uint8_t Day;
uint8_t Month;
uint8_t Year; // offset from 1970; Seems more like 2000.
} tmElements_t;
class TimeClass{
protected:
TimeClass();
void refreshCache(time_t t);
virtual time_t getTimeFromSource()=0;
/* low level functions to convert to and from system time */
void breakTime(time_t time, tmElements_t &tm); // break time_t into elements
time_t makeTime(tmElements_t &tm, uint16_t _offset); // convert time elements into time_t
private:
//int8_t timeZone;
uint32_t sysTime = 0;
uint32_t prevMillis = 0;
uint32_t nextSyncTime = 0;
timeStatus_t Status = timeNotSet;
char buffer[dt_MAX_STRING_LEN+1]; // must be big enough for longest string and the terminating null
const uint8_t daysInAMonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; //API starts months from 1, this array starts from 0
tmElements_t tm; // a cache of time elements
time_t cacheTime; // the time the cache was updated
uint32_t syncInterval = 300; // default time sync will be attempted after this many seconds
public:
bool isAM(); // returns true if time now is AM
bool isPM(); // returns true if time now is PM
int hourFormat12(); // the hour for the given time in 12 hour format
time_t now(); // return the current time as seconds since Jan 1 1970
void setTime(time_t t);
//void setTime(int hr,int min,int sec,int day, int month, int yr);
void adjustTime(long adjustment);
/* date strings */
char* monthStr(uint8_t month);
char* monthShortStr(uint8_t month);
char* dayStr(uint8_t day);
char* dayShortStr(uint8_t day);
timeStatus_t timeStatus(); // indicates if time has been set and recently synchronized
void init(time_t _syncInterval);//, int8_t _timeZone);
tmElements_t& getTimeElements();
};
#endif //_TIMECLASS_
|
#include "cJailDistrict.h"
#include <iostream>
cJailDistrict::cJailDistrict()
{
}
cJailDistrict::~cJailDistrict()
{
}
bool cJailDistrict::Actioon()
{
std::cout << "cJailDistrict::Actioon()" << std::endl;
return true;
}
|
#include <iostream>
#include <vector>
#include <exception>
#include <thread>
#include <functional>
#include <chrono>
#include <mutex>
#include <condition_variable>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
std::condition_variable CV;
std::mutex TMTX;
bool nextFrame;
bool quit=false;
bool worker(void)
{
cv::VideoCapture cap;
if(cap.open(0) == false) {
std::cout << "never got a chance to execute" << std::endl;
return false;
}
cv::namedWindow("cap");
while(!quit) {
std::unique_lock<std::mutex> lk(TMTX);
CV.wait(lk);
//now we have the data
nextFrame = false;
lk.unlock();
//no need to notify, I am the only dude do this now
cv::Mat img;
cap >> img;
cv::imshow("cap", img); // you don't need waitKeyAnymore
cv::waitKey(1);//you always need this.I don't know why
std::cout << "get a frame" << std::endl;
// CV.notify_one();
}
}
int main(int argc, char *argv[])
{
int manytimes=1000000;
//create our thread as well
std::thread twork(worker);
while(manytimes-- > 0) {
{
std::lock_guard<std::mutex> lk(TMTX);
nextFrame = true;
CV.notify_one();
}
std::this_thread::sleep_for(std::chrono::milliseconds(40));
//std::cout << "sleeped" << std::endl;
}
quit = true;
return 0;
}
|
/** Kabuki SDK
@file /.../Source/Kabuki_SDK-Impl/_G/Layer.h
@author Cale McCollough
@copyright Copyright 2016 Cale McCollough ©
@license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt
@brief This file contains the _G.Layer class.
*/
#include "_G/Layer.h"
using namespace _G;
void Remove ()
{
Prev.Next = Next.Next);
Next.Prev = Prev;
}
/** */
void Draw (_G.Cell& C)
{
Element.Draw (C);
next.Draw (C);
}
|
#pragma once
#include "header.h"
#include "JPGImage.h"
#include "displayableobject.h"
#include "player.h"
#include "templates.h"
class zombie :
public DisplayableObject
{
public:
//zombie(BaseEngine* pEngine, int intZombieType, char zombieFile[12]);
zombie(BaseEngine* pEngine);
~zombie(void);
void Draw();
void DoUpdate(int iCurrentTime);
void zombieAI();
int AImoveX, AImoveY, movementFactor;
char cZombieType;
char filename[12];
bool trackerZombie;
ImageData zombiesprite;
};
|
#define INTERRUPT_PIN 3
#define GREEN_LED 4
#define RED_LED 6
ISR(INT1_vect){
//interrupt handling
//turn on green led when subroutine is called
PORTD |= (1<<GREEN_LED);
delay(10); //hold for 10 milliseconds
cli();
sei();
}
void setup(){
DDRD &= ~(1<<INTERRUPT_PIN);
PORTD |= (1<<INTERRUPT_PIN); //internal pullup
DDRD |= (1 << RED_LED) | (1<<GREEN_LED);
//Serial.begin(9600);
EICRA |= (1<<3) | (0<<2); //falling edge on the pin
EIMSK |= (1<<1); //enable INT1 register
}
void loop(){
if((PIND & (1<<3)) > 0){ //button not pressed
green_off();
}
}
//LED toggle functions to clarify code
void green_off(){
PORTD &= ~(1<<GREEN_LED);
}
void green_on(){
PORTD |= (1<<GREEN_LED);
}
void red_on(){
PORTD |= (1<<RED_LED);
}
void red_off(){
PORTD &= ~(1<<RED_LED);
}
|
/********************************************************************************
** Form generated from reading UI file 'dialog.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_DIALOG_H
#define UI_DIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QGraphicsView>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLCDNumber>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSlider>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
#include "qcustomplot.h"
QT_BEGIN_NAMESPACE
class Ui_Dialog
{
public:
QWidget *layoutWidget;
QGridLayout *gridLayout;
QGraphicsView *graphicsView;
QCustomPlot *Kraft;
QCustomPlot *widget_2;
QCustomPlot *Hastighed;
QWidget *layoutWidget_2;
QVBoxLayout *verticalLayout;
QLabel *laptime;
QLCDNumber *Laptime_number;
QLabel *best_laptime;
QLCDNumber *best_laptime_number;
QLabel *Top_speed;
QLCDNumber *top_speed_number;
QPushButton *Start;
QPushButton *Stop;
QPushButton *Automode;
QSpacerItem *verticalSpacer;
QLabel *label_4;
QSlider *pwm_slider;
void setupUi(QDialog *Dialog)
{
if (Dialog->objectName().isEmpty())
Dialog->setObjectName(QStringLiteral("Dialog"));
Dialog->resize(1157, 698);
Dialog->setMinimumSize(QSize(1157, 0));
Dialog->setMaximumSize(QSize(1157, 16777215));
layoutWidget = new QWidget(Dialog);
layoutWidget->setObjectName(QStringLiteral("layoutWidget"));
layoutWidget->setGeometry(QRect(10, 10, 871, 681));
gridLayout = new QGridLayout(layoutWidget);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
gridLayout->setSizeConstraint(QLayout::SetNoConstraint);
gridLayout->setContentsMargins(0, 0, 0, 0);
graphicsView = new QGraphicsView(layoutWidget);
graphicsView->setObjectName(QStringLiteral("graphicsView"));
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(graphicsView->sizePolicy().hasHeightForWidth());
graphicsView->setSizePolicy(sizePolicy);
gridLayout->addWidget(graphicsView, 0, 0, 1, 1);
Kraft = new QCustomPlot(layoutWidget);
Kraft->setObjectName(QStringLiteral("Kraft"));
gridLayout->addWidget(Kraft, 1, 0, 1, 1);
widget_2 = new QCustomPlot(layoutWidget);
widget_2->setObjectName(QStringLiteral("widget_2"));
gridLayout->addWidget(widget_2, 1, 1, 1, 1);
Hastighed = new QCustomPlot(layoutWidget);
Hastighed->setObjectName(QStringLiteral("Hastighed"));
gridLayout->addWidget(Hastighed, 0, 1, 1, 1);
layoutWidget_2 = new QWidget(Dialog);
layoutWidget_2->setObjectName(QStringLiteral("layoutWidget_2"));
layoutWidget_2->setGeometry(QRect(900, 10, 241, 681));
verticalLayout = new QVBoxLayout(layoutWidget_2);
verticalLayout->setSpacing(6);
verticalLayout->setContentsMargins(11, 11, 11, 11);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalLayout->setSizeConstraint(QLayout::SetNoConstraint);
verticalLayout->setContentsMargins(0, 0, 0, 0);
laptime = new QLabel(layoutWidget_2);
laptime->setObjectName(QStringLiteral("laptime"));
QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Fixed);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(laptime->sizePolicy().hasHeightForWidth());
laptime->setSizePolicy(sizePolicy1);
verticalLayout->addWidget(laptime);
Laptime_number = new QLCDNumber(layoutWidget_2);
Laptime_number->setObjectName(QStringLiteral("Laptime_number"));
QSizePolicy sizePolicy2(QSizePolicy::Minimum, QSizePolicy::Fixed);
sizePolicy2.setHorizontalStretch(0);
sizePolicy2.setVerticalStretch(0);
sizePolicy2.setHeightForWidth(Laptime_number->sizePolicy().hasHeightForWidth());
Laptime_number->setSizePolicy(sizePolicy2);
verticalLayout->addWidget(Laptime_number);
best_laptime = new QLabel(layoutWidget_2);
best_laptime->setObjectName(QStringLiteral("best_laptime"));
sizePolicy1.setHeightForWidth(best_laptime->sizePolicy().hasHeightForWidth());
best_laptime->setSizePolicy(sizePolicy1);
verticalLayout->addWidget(best_laptime);
best_laptime_number = new QLCDNumber(layoutWidget_2);
best_laptime_number->setObjectName(QStringLiteral("best_laptime_number"));
sizePolicy2.setHeightForWidth(best_laptime_number->sizePolicy().hasHeightForWidth());
best_laptime_number->setSizePolicy(sizePolicy2);
verticalLayout->addWidget(best_laptime_number);
Top_speed = new QLabel(layoutWidget_2);
Top_speed->setObjectName(QStringLiteral("Top_speed"));
sizePolicy1.setHeightForWidth(Top_speed->sizePolicy().hasHeightForWidth());
Top_speed->setSizePolicy(sizePolicy1);
verticalLayout->addWidget(Top_speed);
top_speed_number = new QLCDNumber(layoutWidget_2);
top_speed_number->setObjectName(QStringLiteral("top_speed_number"));
sizePolicy2.setHeightForWidth(top_speed_number->sizePolicy().hasHeightForWidth());
top_speed_number->setSizePolicy(sizePolicy2);
verticalLayout->addWidget(top_speed_number);
Start = new QPushButton(layoutWidget_2);
Start->setObjectName(QStringLiteral("Start"));
Start->setMinimumSize(QSize(0, 50));
verticalLayout->addWidget(Start);
Stop = new QPushButton(layoutWidget_2);
Stop->setObjectName(QStringLiteral("Stop"));
Stop->setMinimumSize(QSize(0, 50));
verticalLayout->addWidget(Stop);
Automode = new QPushButton(layoutWidget_2);
Automode->setObjectName(QStringLiteral("Automode"));
Automode->setMinimumSize(QSize(0, 50));
verticalLayout->addWidget(Automode);
verticalSpacer = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer);
label_4 = new QLabel(layoutWidget_2);
label_4->setObjectName(QStringLiteral("label_4"));
sizePolicy1.setHeightForWidth(label_4->sizePolicy().hasHeightForWidth());
label_4->setSizePolicy(sizePolicy1);
verticalLayout->addWidget(label_4);
pwm_slider = new QSlider(layoutWidget_2);
pwm_slider->setObjectName(QStringLiteral("pwm_slider"));
pwm_slider->setOrientation(Qt::Horizontal);
verticalLayout->addWidget(pwm_slider);
retranslateUi(Dialog);
QMetaObject::connectSlotsByName(Dialog);
} // setupUi
void retranslateUi(QDialog *Dialog)
{
Dialog->setWindowTitle(QApplication::translate("Dialog", "Dialog", Q_NULLPTR));
laptime->setText(QApplication::translate("Dialog", "Laptime:", Q_NULLPTR));
best_laptime->setText(QApplication::translate("Dialog", "Best laptime:", Q_NULLPTR));
Top_speed->setText(QApplication::translate("Dialog", "Top speed:", Q_NULLPTR));
Start->setText(QApplication::translate("Dialog", "Start", Q_NULLPTR));
Stop->setText(QApplication::translate("Dialog", "Stop", Q_NULLPTR));
Automode->setText(QApplication::translate("Dialog", "Automode", Q_NULLPTR));
label_4->setText(QApplication::translate("Dialog", "Set duty cycle", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class Dialog: public Ui_Dialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_DIALOG_H
|
#ifndef STACK_HPP
#define STACK_HPP
#include "vector.hpp"
class Stack : private Vector {
public:
void push(int value);
void pop();
void printStack();
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2003 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#include "modules/dom/src/domglobaldata.h"
#include "modules/dom/src/domhtml/htmlelem.h"
/* Along with the atom for a reflected numeric property, we also need to
specify its type and if the property has a default value in case the
attribute is absent or outside of range. See DOM_HTMLElement's
declaration for details on the different type kinds.
The following convenience macros can be used to construct numeric
property 'type descriptors'. */
/** A reflected numeric property for 'atom' at the given type. No explicit
default, meaning 0 will be used. */
#define NUMERIC_TYPE(atom, type) (((unsigned)atom << 4) | ((unsigned)type << 1))
/** A reflected numeric property for 'atom' at the given 'type' and with
a default value. */
#define NUMERIC_TYPE_DEFAULT(atom, type, value) (((unsigned)atom << 4) | ((unsigned)type << 1) | 1), (unsigned)value
/** A no-default 'long' numeric property. */
#define INT_TYPE(atom) NUMERIC_TYPE(atom, DOM_HTMLElement::TYPE_LONG)
/** A no-default 'unsigned long' numeric property. */
#define UINT_TYPE(atom) NUMERIC_TYPE(atom, DOM_HTMLElement::TYPE_ULONG)
/* For string properties, we distinguish the different kinds
of behaviour they have for null (corresponding to the
TreatNullAs WebIDL extended attribute.) A string can either
have TreatNullAs=EmptyString or not. The latter meaning that
a DOMString-valued property should convert the (null) value
to "null" first. The former, that it instead will be "". */
#define STRING_TYPE(atom) (static_cast<unsigned>(atom))
#define STRING_TYPE_NULL_AS_EMPTY(atom) ((static_cast<unsigned>(atom)) | 0x80000000)
static const unsigned string_property_type[] =
{
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned string_property_align[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned string_property_name[] =
{
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned numeric_property_tabIndex[] =
{
INT_TYPE(OP_ATOM_tabIndex),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom boolean_property_disabled[] =
{
OP_ATOM_disabled,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const OpAtom boolean_property_compact[] =
{
OP_ATOM_compact,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned html_string_properties[] =
{
STRING_TYPE(OP_ATOM_version),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned link_string_properties[] =
{
STRING_TYPE(OP_ATOM_charset),
STRING_TYPE(OP_ATOM_href),
STRING_TYPE(OP_ATOM_hreflang),
STRING_TYPE(OP_ATOM_media),
STRING_TYPE(OP_ATOM_rel),
STRING_TYPE(OP_ATOM_rev),
STRING_TYPE(OP_ATOM_target),
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned meta_string_properties[] =
{
STRING_TYPE(OP_ATOM_content),
STRING_TYPE(OP_ATOM_httpEquiv),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_scheme),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned base_string_properties[] =
{
STRING_TYPE(OP_ATOM_href),
STRING_TYPE(OP_ATOM_target),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned isindex_string_properties[] =
{
STRING_TYPE(OP_ATOM_prompt),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned style_string_properties[] =
{
STRING_TYPE(OP_ATOM_media),
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned body_string_properties[] =
{
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_aLink),
STRING_TYPE(OP_ATOM_background),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_bgColor),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_link),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_text),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_vLink),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned form_string_properties[] =
{
STRING_TYPE(OP_ATOM_acceptCharset),
STRING_TYPE(OP_ATOM_action),
STRING_TYPE(OP_ATOM_encoding),
STRING_TYPE(OP_ATOM_enctype),
STRING_TYPE(OP_ATOM_method),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_target),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom form_boolean_properties[] =
{
OP_ATOM_noValidate,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned select_string_properties[] =
{
STRING_TYPE(OP_ATOM_autocomplete),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned select_numeric_properties[] =
{
UINT_TYPE(OP_ATOM_size),
INT_TYPE(OP_ATOM_tabIndex),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom select_boolean_properties[] =
{
OP_ATOM_autofocus,
OP_ATOM_disabled,
OP_ATOM_multiple,
OP_ATOM_required,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned optgroup_string_properties[] =
{
STRING_TYPE(OP_ATOM_label),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned option_string_properties[] =
{
STRING_TYPE(OP_ATOM_label),
STRING_TYPE(OP_ATOM_value),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom option_boolean_properties[] =
{
OP_ATOM_defaultSelected,
OP_ATOM_disabled,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned input_string_properties[] =
{
STRING_TYPE(OP_ATOM_accept),
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_alt),
STRING_TYPE(OP_ATOM_autocomplete),
STRING_TYPE(OP_ATOM_defaultValue),
STRING_TYPE(OP_ATOM_dirName),
STRING_TYPE(OP_ATOM_formAction),
STRING_TYPE(OP_ATOM_formEnctype),
STRING_TYPE(OP_ATOM_formMethod),
STRING_TYPE(OP_ATOM_formTarget),
STRING_TYPE(OP_ATOM_inputmode),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_max),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_min),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_pattern),
STRING_TYPE(OP_ATOM_placeholder),
STRING_TYPE(OP_ATOM_src),
STRING_TYPE(OP_ATOM_step),
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_useMap),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned input_numeric_properties[] =
{
INT_TYPE(OP_ATOM_height),
NUMERIC_TYPE_DEFAULT(OP_ATOM_maxLength, DOM_HTMLElement::TYPE_LONG_NON_NEGATIVE, -1),
NUMERIC_TYPE_DEFAULT(OP_ATOM_size, DOM_HTMLElement::TYPE_ULONG_NON_ZERO, 20),
INT_TYPE(OP_ATOM_tabIndex),
INT_TYPE(OP_ATOM_width),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom input_boolean_properties[] =
{
OP_ATOM_autofocus,
OP_ATOM_checked,
OP_ATOM_defaultChecked,
OP_ATOM_disabled,
OP_ATOM_formNoValidate,
OP_ATOM_indeterminate,
OP_ATOM_multiple,
OP_ATOM_readOnly,
OP_ATOM_required,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned textarea_string_properties[] =
{
STRING_TYPE(OP_ATOM_dirName),
STRING_TYPE(OP_ATOM_inputmode),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_pattern),
STRING_TYPE(OP_ATOM_placeholder),
STRING_TYPE(OP_ATOM_wrap),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned textarea_numeric_properties[] =
{
NUMERIC_TYPE_DEFAULT(OP_ATOM_cols, DOM_HTMLElement::TYPE_ULONG_NON_ZERO, 20),
NUMERIC_TYPE_DEFAULT(OP_ATOM_maxLength, DOM_HTMLElement::TYPE_LONG_NON_NEGATIVE, -1),
NUMERIC_TYPE_DEFAULT(OP_ATOM_rows, DOM_HTMLElement::TYPE_ULONG_NON_ZERO, 2),
INT_TYPE(OP_ATOM_tabIndex),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom textarea_boolean_properties[] =
{
OP_ATOM_autofocus,
OP_ATOM_disabled,
OP_ATOM_readOnly,
OP_ATOM_required,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned button_string_properties[] =
{
STRING_TYPE(OP_ATOM_formAction),
STRING_TYPE(OP_ATOM_formEnctype),
STRING_TYPE(OP_ATOM_formMethod),
STRING_TYPE(OP_ATOM_formTarget),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_value),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom button_boolean_properties[] =
{
OP_ATOM_autofocus,
OP_ATOM_disabled,
OP_ATOM_formNoValidate,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned label_string_properties[] =
{
STRING_TYPE(OP_ATOM_htmlFor),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned legend_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned output_string_properties[] =
{
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned progress_numeric_properties[] =
{
NUMERIC_TYPE_DEFAULT(OP_ATOM_max, DOM_HTMLElement::TYPE_DOUBLE, 1),
NUMERIC_TYPE(OP_ATOM_value, DOM_HTMLElement::TYPE_DOUBLE),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned meter_numeric_properties[] =
{
NUMERIC_TYPE(OP_ATOM_high, DOM_HTMLElement::TYPE_DOUBLE),
NUMERIC_TYPE(OP_ATOM_low, DOM_HTMLElement::TYPE_DOUBLE),
NUMERIC_TYPE(OP_ATOM_max, DOM_HTMLElement::TYPE_DOUBLE),
NUMERIC_TYPE(OP_ATOM_min, DOM_HTMLElement::TYPE_DOUBLE),
NUMERIC_TYPE(OP_ATOM_optimum, DOM_HTMLElement::TYPE_DOUBLE),
NUMERIC_TYPE(OP_ATOM_value, DOM_HTMLElement::TYPE_DOUBLE),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom keygen_boolean_properties[] =
{
OP_ATOM_autofocus,
OP_ATOM_disabled,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned keygen_string_properties[] =
{
STRING_TYPE(OP_ATOM_challenge),
STRING_TYPE(OP_ATOM_keytype),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned olist_numeric_properties[] =
{
INT_TYPE(OP_ATOM_start),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom olist_boolean_properties[] =
{
OP_ATOM_compact,
OP_ATOM_reversed,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned li_numeric_properties[] =
{
INT_TYPE(OP_ATOM_value),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned quote_string_properties[] =
{
STRING_TYPE(OP_ATOM_cite),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned pre_numeric_properties[] =
{
UINT_TYPE(OP_ATOM_width),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned br_string_properties[] =
{
STRING_TYPE(OP_ATOM_clear),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned font_string_properties[] =
{
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_color),
STRING_TYPE(OP_ATOM_face),
STRING_TYPE(OP_ATOM_size),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned hr_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_size),
STRING_TYPE(OP_ATOM_width),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom hr_boolean_properties[] =
{
OP_ATOM_noShade,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned mod_string_properties[] =
{
STRING_TYPE(OP_ATOM_cite),
STRING_TYPE(OP_ATOM_dateTime),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned anchor_string_properties[] =
{
STRING_TYPE(OP_ATOM_charset),
STRING_TYPE(OP_ATOM_coords),
STRING_TYPE(OP_ATOM_href),
STRING_TYPE(OP_ATOM_hreflang),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_rel),
STRING_TYPE(OP_ATOM_rev),
STRING_TYPE(OP_ATOM_shape),
STRING_TYPE(OP_ATOM_target),
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned image_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_alt),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_border),
STRING_TYPE(OP_ATOM_crossOrigin),
STRING_TYPE(OP_ATOM_longDesc),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_src),
STRING_TYPE(OP_ATOM_useMap),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static unsigned image_numeric_properties[] =
{
UINT_TYPE(OP_ATOM_height),
UINT_TYPE(OP_ATOM_hspace),
UINT_TYPE(OP_ATOM_vspace),
UINT_TYPE(OP_ATOM_width),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom image_boolean_properties[] =
{
OP_ATOM_isMap,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned object_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_archive),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_border),
STRING_TYPE(OP_ATOM_classId),
STRING_TYPE(OP_ATOM_code),
STRING_TYPE(OP_ATOM_codeBase),
STRING_TYPE(OP_ATOM_codeType),
STRING_TYPE(OP_ATOM_data),
STRING_TYPE(OP_ATOM_height),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_standby),
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_useMap),
STRING_TYPE(OP_ATOM_width),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned object_numeric_properties[] =
{
UINT_TYPE(OP_ATOM_hspace),
INT_TYPE(OP_ATOM_tabIndex),
UINT_TYPE(OP_ATOM_vspace),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom object_boolean_properties[] =
{
OP_ATOM_declare,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned param_string_properties[] =
{
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_value),
STRING_TYPE(OP_ATOM_valueType),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned applet_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_alt),
STRING_TYPE(OP_ATOM_archive),
STRING_TYPE(OP_ATOM_code),
STRING_TYPE(OP_ATOM_codeBase),
STRING_TYPE(OP_ATOM_height),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_object),
STRING_TYPE(OP_ATOM_width),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned applet_numeric_properties[] =
{
UINT_TYPE(OP_ATOM_hspace),
UINT_TYPE(OP_ATOM_vspace),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned area_string_properties[] =
{
STRING_TYPE(OP_ATOM_alt),
STRING_TYPE(OP_ATOM_coords),
STRING_TYPE(OP_ATOM_href),
STRING_TYPE(OP_ATOM_shape),
STRING_TYPE(OP_ATOM_target),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom area_boolean_properties[] =
{
OP_ATOM_noHref,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned script_string_properties[] =
{
STRING_TYPE(OP_ATOM_charset),
STRING_TYPE(OP_ATOM_src),
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom script_boolean_properties[] =
{
OP_ATOM_defer,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned table_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_bgColor),
STRING_TYPE(OP_ATOM_border),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_cellPadding),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_cellSpacing),
STRING_TYPE(OP_ATOM_frame),
STRING_TYPE(OP_ATOM_rules),
STRING_TYPE(OP_ATOM_summary),
STRING_TYPE(OP_ATOM_width),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned tablecol_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_ch),
STRING_TYPE(OP_ATOM_chOff),
STRING_TYPE(OP_ATOM_vAlign),
STRING_TYPE(OP_ATOM_width),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned tablecol_numeric_properties[] =
{
UINT_TYPE(OP_ATOM_span),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned tablesection_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_ch),
STRING_TYPE(OP_ATOM_chOff),
STRING_TYPE(OP_ATOM_vAlign),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned tablerow_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_bgColor),
STRING_TYPE(OP_ATOM_ch),
STRING_TYPE(OP_ATOM_chOff),
STRING_TYPE(OP_ATOM_height),
STRING_TYPE(OP_ATOM_vAlign),
STRING_TYPE(OP_ATOM_width),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned tablecell_string_properties[] =
{
STRING_TYPE(OP_ATOM_abbr),
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_axis),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_bgColor),
STRING_TYPE(OP_ATOM_ch),
STRING_TYPE(OP_ATOM_chOff),
STRING_TYPE(OP_ATOM_headers),
STRING_TYPE(OP_ATOM_height),
STRING_TYPE(OP_ATOM_scope),
STRING_TYPE(OP_ATOM_vAlign),
STRING_TYPE(OP_ATOM_width),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned tablecell_numeric_properties[] =
{
/* colSpan is currently specified as being limited to non-zero values,
and must consequently throw on setting 0. No one implements that
restriction, so choose to follow that behaviour here. */
NUMERIC_TYPE(OP_ATOM_colSpan, DOM_HTMLElement::TYPE_ULONG),
NUMERIC_TYPE_DEFAULT(OP_ATOM_rowSpan, DOM_HTMLElement::TYPE_ULONG, 1),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom tablecell_boolean_properties[] =
{
OP_ATOM_noWrap,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned frameset_string_properties[] =
{
STRING_TYPE(OP_ATOM_cols),
STRING_TYPE(OP_ATOM_rows),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned frame_string_properties[] =
{
STRING_TYPE(OP_ATOM_frameBorder),
STRING_TYPE(OP_ATOM_longDesc),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_marginHeight),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_marginWidth),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_scrolling),
STRING_TYPE(OP_ATOM_src),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom frame_boolean_properties[] =
{
OP_ATOM_noResize,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned iframe_string_properties[] =
{
STRING_TYPE(OP_ATOM_align),
STRING_TYPE(OP_ATOM_frameBorder),
STRING_TYPE(OP_ATOM_height),
STRING_TYPE(OP_ATOM_longDesc),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_marginHeight),
STRING_TYPE_NULL_AS_EMPTY(OP_ATOM_marginWidth),
STRING_TYPE(OP_ATOM_name),
STRING_TYPE(OP_ATOM_scrolling),
STRING_TYPE(OP_ATOM_src),
STRING_TYPE(OP_ATOM_width),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
#ifdef MEDIA_HTML_SUPPORT
static const OpAtom audio_boolean_properties[] =
{
OP_ATOM_autoplay,
OP_ATOM_controls,
OP_ATOM_defaultMuted,
OP_ATOM_loop,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned audio_string_properties[] =
{
STRING_TYPE(OP_ATOM_preload),
STRING_TYPE(OP_ATOM_src),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned video_numeric_properties[] =
{
UINT_TYPE(OP_ATOM_height),
UINT_TYPE(OP_ATOM_width),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom video_boolean_properties[] =
{
OP_ATOM_autoplay,
OP_ATOM_controls,
OP_ATOM_defaultMuted,
OP_ATOM_loop,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned video_string_properties[] =
{
STRING_TYPE(OP_ATOM_poster),
STRING_TYPE(OP_ATOM_preload),
STRING_TYPE(OP_ATOM_src),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned source_string_properties[] =
{
STRING_TYPE(OP_ATOM_media),
STRING_TYPE(OP_ATOM_src),
STRING_TYPE(OP_ATOM_type),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom track_boolean_properties[] =
{
OP_ATOM_default,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
static const unsigned track_string_properties[] =
{
STRING_TYPE(OP_ATOM_kind),
STRING_TYPE(OP_ATOM_label),
STRING_TYPE(OP_ATOM_src),
STRING_TYPE(OP_ATOM_srclang),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
#endif //MEDIA_HTML_SUPPORT
#ifdef CANVAS_SUPPORT
static const unsigned canvas_numeric_properties[] =
{
UINT_TYPE(OP_ATOM_height),
UINT_TYPE(OP_ATOM_width),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
#endif // CANVAS_SUPPORT
static const unsigned marquee_string_properties[] =
{
STRING_TYPE(OP_ATOM_behavior),
STRING_TYPE(OP_ATOM_direction),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned marquee_numeric_properties[] =
{
UINT_TYPE(OP_ATOM_height),
UINT_TYPE(OP_ATOM_hspace),
INT_TYPE(OP_ATOM_loop),
UINT_TYPE(OP_ATOM_scrollAmount),
UINT_TYPE(OP_ATOM_scrollDelay),
UINT_TYPE(OP_ATOM_vspace),
UINT_TYPE(OP_ATOM_width),
INT_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const unsigned time_string_properties[] =
{
STRING_TYPE(OP_ATOM_dateTime),
STRING_TYPE(OP_ATOM_ABSOLUTELY_LAST_ENUM)
};
static const OpAtom time_boolean_properties[] =
{
OP_ATOM_pubDate,
OP_ATOM_ABSOLUTELY_LAST_ENUM
};
#undef STRING_TYPE
#undef STRING_TYPE_NULL_AS_EMPTY
#undef NUMERIC_TYPE
#undef NUMERIC_TYPE_DEFAULT
#undef INT_TYPE
#undef UINT_TYPE
/* static */ const unsigned *
DOM_HTMLElement::GetTabIndexTypeDescriptor()
{
return numeric_property_tabIndex;
}
#ifdef DOM_NO_COMPLEX_GLOBALS
# define DOM_HTML_PROPERTIES_START() void DOM_htmlProperties_Init(DOM_GlobalData *global_data) { DOM_HTMLElement::SimpleProperties *properties = global_data->htmlProperties;
# define DOM_HTML_PROPERTIES_ITEM(string_, numeric_, boolean_) properties->string = string_; properties->boolean = boolean_; properties->numeric = numeric_; ++properties;
# define DOM_HTML_PROPERTIES_ITEM_LAST(string_, numeric_, boolean_) properties->string = string_; properties->boolean = boolean_; properties->numeric = numeric_;
# define DOM_HTML_PROPERTIES_END() }
#else // DOM_NO_COMPLEX_GLOBALS
# define DOM_HTML_PROPERTIES_START() const DOM_HTMLElement::SimpleProperties g_DOM_htmlProperties[] = {
# define DOM_HTML_PROPERTIES_ITEM(string, numeric, boolean) { string, boolean, numeric },
# define DOM_HTML_PROPERTIES_ITEM_LAST(string, numeric, boolean) { string, boolean, numeric }
# define DOM_HTML_PROPERTIES_END() };
#endif // DOM_NO_COMPLEX_GLOBALS
/* Important: this array must be kept in sync with the enumeration
DOM_Runtime::HTMLElementPrototype. See its definition for what
else it needs to be in sync with. */
DOM_HTML_PROPERTIES_START()
// Unknown
DOM_HTML_PROPERTIES_ITEM(0, 0, 0)
// Html
DOM_HTML_PROPERTIES_ITEM(html_string_properties, 0, 0)
// Head
DOM_HTML_PROPERTIES_ITEM(0, 0, 0)
// Link
DOM_HTML_PROPERTIES_ITEM(link_string_properties, 0, 0)
// Title
DOM_HTML_PROPERTIES_ITEM(0, 0, 0)
// Meta
DOM_HTML_PROPERTIES_ITEM(meta_string_properties, 0, 0)
// Base
DOM_HTML_PROPERTIES_ITEM(base_string_properties, 0, 0)
// IsIndex
DOM_HTML_PROPERTIES_ITEM(isindex_string_properties, 0, 0)
// Style
DOM_HTML_PROPERTIES_ITEM(style_string_properties, 0, 0)
// Body
DOM_HTML_PROPERTIES_ITEM(body_string_properties, 0, 0)
// Form
DOM_HTML_PROPERTIES_ITEM(form_string_properties, 0, form_boolean_properties)
// Select
DOM_HTML_PROPERTIES_ITEM(select_string_properties, select_numeric_properties, select_boolean_properties)
// OptGroup
DOM_HTML_PROPERTIES_ITEM(optgroup_string_properties, 0, boolean_property_disabled)
// Option
DOM_HTML_PROPERTIES_ITEM(option_string_properties, 0, option_boolean_properties)
// Input
DOM_HTML_PROPERTIES_ITEM(input_string_properties, input_numeric_properties, input_boolean_properties)
// TextArea
DOM_HTML_PROPERTIES_ITEM(textarea_string_properties, textarea_numeric_properties, textarea_boolean_properties)
// Button
DOM_HTML_PROPERTIES_ITEM(button_string_properties, numeric_property_tabIndex, button_boolean_properties)
// Label
DOM_HTML_PROPERTIES_ITEM(label_string_properties, 0, 0)
// FieldSet
DOM_HTML_PROPERTIES_ITEM(0, 0, boolean_property_disabled)
// Legend
DOM_HTML_PROPERTIES_ITEM(legend_string_properties, 0, 0)
// Output
DOM_HTML_PROPERTIES_ITEM(output_string_properties, 0, 0)
// DataList
DOM_HTML_PROPERTIES_ITEM(0, 0, 0)
// Progress
DOM_HTML_PROPERTIES_ITEM(0, progress_numeric_properties, 0)
// Meter
DOM_HTML_PROPERTIES_ITEM(0, meter_numeric_properties, 0)
// Keygen
DOM_HTML_PROPERTIES_ITEM(keygen_string_properties, 0, keygen_boolean_properties)
// UList
DOM_HTML_PROPERTIES_ITEM(string_property_type, 0, boolean_property_compact)
// OList
DOM_HTML_PROPERTIES_ITEM(string_property_type, olist_numeric_properties, olist_boolean_properties)
// DList
DOM_HTML_PROPERTIES_ITEM(0, 0, boolean_property_compact)
// Directory
DOM_HTML_PROPERTIES_ITEM(0, 0, boolean_property_compact)
// Menu
DOM_HTML_PROPERTIES_ITEM(0, 0, boolean_property_compact)
// LI
DOM_HTML_PROPERTIES_ITEM(string_property_type, li_numeric_properties, 0)
// Div
DOM_HTML_PROPERTIES_ITEM(string_property_align, 0, 0)
// Paragraph
DOM_HTML_PROPERTIES_ITEM(string_property_align, 0, 0)
// Heading
DOM_HTML_PROPERTIES_ITEM(string_property_align, 0, 0)
// Quote
DOM_HTML_PROPERTIES_ITEM(quote_string_properties, 0, 0)
// Pre
DOM_HTML_PROPERTIES_ITEM(0, pre_numeric_properties, 0)
// Br
DOM_HTML_PROPERTIES_ITEM(br_string_properties, 0, 0)
// Font
DOM_HTML_PROPERTIES_ITEM(font_string_properties, 0, 0)
// HR
DOM_HTML_PROPERTIES_ITEM(hr_string_properties, 0, hr_boolean_properties)
// Mod
DOM_HTML_PROPERTIES_ITEM(mod_string_properties, 0, 0)
#ifdef PARTIAL_XMLELEMENT_SUPPORT // See bug 286692
// Xml
DOM_HTML_PROPERTIES_ITEM(0, 0, 0)
#endif // #ifdef PARTIAL_XMLELEMENT_SUPPORT // See bug 286692
// Anchor
DOM_HTML_PROPERTIES_ITEM(anchor_string_properties, numeric_property_tabIndex, 0)
// Image
DOM_HTML_PROPERTIES_ITEM(image_string_properties, image_numeric_properties, image_boolean_properties)
// Object
DOM_HTML_PROPERTIES_ITEM(object_string_properties, object_numeric_properties, object_boolean_properties)
// Param
DOM_HTML_PROPERTIES_ITEM(param_string_properties, 0, 0)
// Applet
DOM_HTML_PROPERTIES_ITEM(applet_string_properties, applet_numeric_properties, 0)
// Embed
DOM_HTML_PROPERTIES_ITEM(0, 0, 0)
// Map
DOM_HTML_PROPERTIES_ITEM(string_property_name, 0, 0)
// Area
DOM_HTML_PROPERTIES_ITEM(area_string_properties, numeric_property_tabIndex, area_boolean_properties)
// Script
DOM_HTML_PROPERTIES_ITEM(script_string_properties, 0, script_boolean_properties)
// Table
DOM_HTML_PROPERTIES_ITEM(table_string_properties, 0, 0)
// TableCaption
DOM_HTML_PROPERTIES_ITEM(string_property_align, 0, 0)
// TableCol
DOM_HTML_PROPERTIES_ITEM(tablecol_string_properties, tablecol_numeric_properties, 0)
// TableSection
DOM_HTML_PROPERTIES_ITEM(tablesection_string_properties, 0, 0)
// TableRow
DOM_HTML_PROPERTIES_ITEM(tablerow_string_properties, 0, 0)
// TableCell
DOM_HTML_PROPERTIES_ITEM(tablecell_string_properties, tablecell_numeric_properties, tablecell_boolean_properties)
// FrameSet
DOM_HTML_PROPERTIES_ITEM(frameset_string_properties, 0, 0)
// Frame
DOM_HTML_PROPERTIES_ITEM(frame_string_properties, 0, frame_boolean_properties)
// IFrame
DOM_HTML_PROPERTIES_ITEM(iframe_string_properties, 0, frame_boolean_properties)
#ifdef MEDIA_HTML_SUPPORT
// Media
DOM_HTML_PROPERTIES_ITEM(0, 0, 0)
// Audio
DOM_HTML_PROPERTIES_ITEM(audio_string_properties, 0, audio_boolean_properties)
// Video
DOM_HTML_PROPERTIES_ITEM(video_string_properties, video_numeric_properties, video_boolean_properties)
// Source
DOM_HTML_PROPERTIES_ITEM(source_string_properties, 0, 0)
// Track
DOM_HTML_PROPERTIES_ITEM(track_string_properties, 0, track_boolean_properties)
#endif // MEDIA_HTML_SUPPORT
#ifdef CANVAS_SUPPORT
// Canvas
DOM_HTML_PROPERTIES_ITEM(0, canvas_numeric_properties, 0)
#endif // CANVAS_SUPPORT
// Marquee
DOM_HTML_PROPERTIES_ITEM(marquee_string_properties, marquee_numeric_properties, 0)
// Time
DOM_HTML_PROPERTIES_ITEM_LAST(time_string_properties, 0, time_boolean_properties)
DOM_HTML_PROPERTIES_END()
|
//知识点:状态压缩 DP/记忆化搜索
/*
可以使用二进制拆分,
来模拟队列中 牛 的存在情况
以进行状态压缩
如: 9(十进制) = 1001(二进制) ,
表示队列中有第1头和第4头牛
可以使用记忆化搜索
这里打了一个状态压缩DP
数组f[i][j]
表示 队列情况为i,队末为j的队列
满足条件的方案数
状态转移方程: f[i+(1<<(k-1))][k]+=f[i][j];
表示向 队列情况为i,队末为j的队列 的末尾
添加一头编号为k的牛
最后统计出所有满队列的答案总和
即:队列中有n人的队列的答案总和
*/
#include<cstdio>
#include<cctype>
#define int long long
using namespace std;
int n,kkk;
int s[17];
int f[(1<<16)+1][17];
int abs(int a){return a>=0?a:-a;}
signed main()
{
scanf("%lld%lld",&n,&kkk);
for(int i=1;i<=n;i++) //输入顺便初始化
{
scanf("%lld",&s[i]);
f[1<<(i-1)][i]=1;
}
for(int i=1;i<=(1<<n)-1;i++)//枚举队列情况
for(int j=1;j<=n;j++)//枚举队列末尾元素
if( (1<<(j-1))&i )//在队列中
for(int k=1;k<=n;k++)//枚举要添加的元素
if( ((1<<(k-1))&i)==0 && (abs(s[k]-s[j])>kkk) )//不在队列中 且 添加到尾部合法
f[i+(1<<(k-1))][k]+=f[i][j];//进行添加,更新答案
int ans=0;
for(int i=1;i<=n;i++)//统计答案
ans+=f[(1<<n)-1][i];
printf("%lld",ans);
}
|
#include <swDuino.h>
#include <IRremote.h>
swDuino objswDuino;
const int low_duration = 520;
const int high_duration = 1100;
IRsend irsend;
unsigned int receivedCommand[197];
void setup() {
Serial.begin(9600);
}
void loop() {
objswDuino.read(trigger);
}
void trigger(String VARIABLE, String VALUE) {
if (VARIABLE == "ss_command")
{
generateCommand(VALUE);
for (int i = 0; i < 3; i++) {
irsend.sendRaw(receivedCommand, 197, 38);
delay(10);
}
}
}
void generateCommand(String binCom) {
receivedCommand[0] = 3040;
receivedCommand[1] = 4460;
for(int i = 0; i < binCom.length(); i++) {
receivedCommand[i * 2 + 2] = low_duration;
receivedCommand[i * 2 + 3] = low_duration + ((unsigned int) (binCom.charAt(i) - '0')) * high_duration;
}
}
|
/* modified from NAMD */
#ifndef COMPUTEPME_H
#define COMPUTEPME_H
#include "pmetest.h"
#include "PmeBase.h"
#include "Vector.h"
class PmeRealSpace;
class ComputePmeMgr;
class ComputePme { //: public ComputeHomePatches {
public:
ComputePme(const PmetestParams &); //ComputeID c);
virtual ~ComputePme();
void doWork(int natoms, const Vector *position, const double *charge,
Vector *force, double *energy, double *virial);
// energy is length 1, virial is length 9
void ungridForces();
PmetestParams *simParams;
private:
ComputePmeMgr *computePmeMgr;
PmeGrid myGrid;
int qsize, fsize, bsize;
public:
double **q_arr;
private:
char *f_arr;
char *fz_arr;
public:
double energy;
double virial[6];
private:
int resultsRemaining;
PmeRealSpace *myRealSpace;
int numLocalAtoms;
PmeParticle *localData;
Vector *pmeForce;
double *pmeVirial;
PmetestParams storePmeParams;
int useAvgPositions;
};
#endif
|
// Copyright 2020 Fuji-Iot authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef FUJI_TYPES_H_
#define FUJI_TYPES_H_
#include <bits/stdint-uintn.h>
#include <initializer_list>
#include <string>
namespace fuji_iot {
// Defines various operation modes of the AC unit.
enum class mode_t : uint8_t {
UNKNOWN = 0,
FAN = 1,
DRY = 2,
COOL = 3,
HEAT = 4,
AUTO = 5,
};
// Returns human-readable string for AC unit mode.
const std::string ToString(const mode_t &mode);
std::ostream &operator<<(std::ostream &os, const mode_t &mode);
constexpr std::initializer_list<mode_t> all_mode_t = {
mode_t::UNKNOWN, mode_t::FAN, mode_t::DRY,
mode_t::COOL, mode_t::HEAT, mode_t::AUTO,
};
// Defines fan speed of the AC unit.
enum class fan_t : uint8_t {
AUTO = 0,
LOW = 1,
MEDIUM = 2,
HIGH = 3,
MAX = 4,
UNKNOWN = 5,
};
constexpr std::initializer_list<fan_t> all_fan_t = {
fan_t::AUTO, fan_t::LOW, fan_t::MEDIUM,
fan_t::HIGH, fan_t::MAX, fan_t::UNKNOWN,
};
// Returns human-readable string for fan speed.
const std::string ToString(const fan_t &fan);
std::ostream &operator<<(std::ostream &os, const fan_t &fan);
} // namespace fuji_iot
#endif
|
/*
* MacFileHandlerCache.h
* Opera
*
* Created by Adam Minchinton on 5/14/07.
* Copyright 2007 Opera. All rights reserved.
*
*/
#include "modules/util/adt/opvector.h"
#include "modules/pi/OpBitmap.h"
class MacFileHandlerCache
{
public:
OP_STATUS CopyInto(OpVector<OpString>& handlers,
OpVector<OpString>& handler_names,
OpVector<OpBitmap>& handler_icons,
UINT32 icon_size);
OpString m_ext;
OpAutoVector<OpString> m_handlers;
OpAutoVector<OpString> m_handler_names;
OpAutoVector<OpBitmap> m_handler_icons;
};
|
/**
* created: 2013-4-8 13:12
* filename: FKCheckNameSvr
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#include "FKCheckNameSvr.h"
#include "../FKSvr3Common/FKCommonInclude.h"
#include <malloc.h>
#include <Ole2.h>
#include <stdio.h>
#include "Res/resource.h"
//------------------------------------------------------------------------
#pragma warning(disable:4239) //使用了非标准扩展 : “参数” : 从“CCheckNameService::RecycleThreadCallBack::stcheckSession”转换到“zHashManagerBase<valueT,e1>::removeValue_Pred_Base &”
//------------------------------------------------------------------------
#define _SUBSVR_CONN_ 0
#define _STARTSERVICE_LOG_ "FKCheckNameSvr 开始启动服务..."
//------------------------------------------------------------------------
CLD_IocpClientSocket* CCheckNameTcpServices::CreateIocpClient(CMIocpTcpAccepters::CSubAccepter* pAccepter, SOCKET s)
{
FUNCTION_BEGIN;
CCheckNameService* checknamesvr=CCheckNameService::instance();
if (checknamesvr->m_boshutdown|| !checknamesvr->m_boStartService){
return NULL;
}
switch (pAccepter->gettype())
{
case _SUBSVR_CONN_:
{
svrinfomapiter it;
bool bofind = false;
char szremoterip[32];
CLD_Socket::GetRemoteAddress(s,szremoterip,sizeof(szremoterip));
do{
AILOCKT(checknamesvr->cfg_lock);
for (it = checknamesvr->m_svrlistmap.begin(); it != checknamesvr->m_svrlistmap.end(); it++) {
stServerInfo* psvr = &it->second;
if ( stricmp(psvr->szIp, szremoterip) == 0 && (psvr->svr_type==_SUPERGAMESVR_TYPE || psvr->svr_type==_GAMESVR_TYPE || psvr->svr_type==_DBSVR_TYPE || psvr->svr_type==_LOGINSVR_TYPE) ) {
bofind = true;
break;
}
}
}while (false);
if (bofind) {
CSubSvrSession* pqpsocket = new CSubSvrSession(pAccepter, s);
AILOCKT(checknamesvr->m_gamesvrsession);
checknamesvr->m_gamesvrsession.insert(pqpsocket);
return (CLD_IocpClientSocket *) pqpsocket;
} else {
g_logger.warn("%s : %d 非法的服务器连接...", szremoterip, CLD_Socket::GetRemotePort(s));
}
}
break;
}
return NULL;
}
//------------------------------------------------------------------------
void CCheckNameTcpServices::OnIocpClientConnect(CLD_Socket* Socket)
{
FUNCTION_BEGIN;
CMIocpTcpAccepters::CSubAccepter* pAccepter = (CMIocpTcpAccepters::CSubAccepter*) ((CLD_IocpClientSocket*) Socket)->GetAccepter();
if (pAccepter){
g_logger.debug("%s:%d(%s) 连接成功...", Socket->GetRemoteAddress(), Socket->GetRemotePort(), pAccepter->getdis());
}else{
g_logger.debug("%s:%d 连接成功...", Socket->GetRemoteAddress(), Socket->GetRemotePort());
}
}
//------------------------------------------------------------------------
void CCheckNameTcpServices::OnClientDisconnect(CLD_Socket* Socket)
{
FUNCTION_BEGIN;
CMIocpTcpAccepters::CSubAccepter* pAccepter = (CMIocpTcpAccepters::CSubAccepter*) ((CLD_IocpClientSocket*) Socket)->GetAccepter();
switch (pAccepter->gettype())
{
case _SUBSVR_CONN_:
{
CCheckNameService* checknamesvr=CCheckNameService::instance();
CSubSvrSession* pgamesvr=(CSubSvrSession*)Socket;
do {
AILOCKT(checknamesvr->m_gamesvrsession);
checknamesvr->m_gamesvrsession.erase(pgamesvr);
}while(false);
}
break;
}
g_logger.debug("%s:%d(%s) 连接断开...", Socket->GetRemoteAddress(), Socket->GetRemotePort(), pAccepter->getdis());
}
//------------------------------------------------------------------------
void CCheckNameTcpServices::OnClientError(CLD_Socket* Socket, CLD_TErrorEvent ErrEvent, OUT int& nErrCode, char* sErrMsg)
{
FUNCTION_BEGIN;
g_logger.debug("%s:%d 连接异常(%d->%s)...", Socket->GetRemoteAddress(), Socket->GetRemotePort(), nErrCode, sErrMsg);
CMIocpTcpAccepters::CSubAccepter* pAccepter = (CMIocpTcpAccepters::CSubAccepter*) ((CLD_IocpClientSocket*) Socket)->GetAccepter();
if (nErrCode!=0){
switch (pAccepter->gettype())
{
case _SUBSVR_CONN_:
{
((CSubSvrSession*)Socket)->Terminate();
}
break;
}
nErrCode=0;
}
}
//------------------------------------------------------------------------
CCheckNameService::CCheckNameService()
:CWndBase(WND_WIDTH,WND_HEIGHT*2,"Robots")
{
FUNCTION_BEGIN;
m_nZoneid = 0;
m_timeshutdown=0;
m_forceclose=false;
m_niocpworkthreadcount=0;
m_boStartService = false;
m_boshutdown=false;
m_svridx = 0;
m_nTradeid=0;
m_szsvrcfgdburl[0]=0;
m_szgamesvrparamdburl[0]=0;
m_szSvrName[0]=0;
m_szZoneName[0]=0;
m_nZoneid=0;
m_szmanageip[0]=0;
m_manageport=5000;
m_boConnectManage=false;
m_msgProcessThread=NULL;
m_LogicProcessThread=NULL;
m_dwUserOnlyId=0;
m_dwAccountOnlyId=0;
m_dwStrOnlyId=0;
m_iocp.SetRecycleThreadCallBack(RecycleThreadCallBackProxy, this);
m_Svr2SvrLoginCmd.svr_id=m_svridx;
m_Svr2SvrLoginCmd.svr_type=m_svrtype;
LoadLocalConfig();
char szTemp[MAX_PATH];
char szruntime[20];
timetostr(time(NULL),szruntime,20);
sprintf_s(szTemp,MAX_PATH,"CNS[%s : CheckNameSvr](BuildTime: %s)-(RunTime: %s)",m_szSvrName,__BUILD_DATE_TIME__,szruntime);
SetTitle(szTemp);
}
//------------------------------------------------------------------------
HMODULE g_AutoCompleteh=0;
CCheckNameService::~CCheckNameService(){
if (g_AutoCompleteh){
FreeLibrary(g_AutoCompleteh);
g_AutoCompleteh=0;
}
}
//------------------------------------------------------------------------
void CCheckNameService::RecycleThreadCallBack()
{
FUNCTION_BEGIN;
FUNCTION_WRAPPER(true,NULL);
time_t curtime = time(NULL);
if (m_boStartService)
{
static time_t s_timeAction=time(NULL)+2;
if (curtime > s_timeAction && !m_boshutdown)
{
m_TcpConnters.timeAction();
s_timeAction = time(NULL) + 4;
}
static time_t s_timeSaveSvrParam=time(NULL)+60*1;
curtime = time(NULL);
if (curtime > s_timeSaveSvrParam && !m_boshutdown)
{
SaveServerParam( 0 ,3000 );
s_timeSaveSvrParam=time(NULL)+60*1;
}
}
}
//------------------------------------------------------------------------
DWORD WINAPI OnExceptionBeginCallBack(LPEXCEPTION_POINTERS ExceptionInfo)
{
CCheckNameService* psvr=CCheckNameService::instance_readonly();
if (psvr && psvr->m_boStartService==true){ psvr->SaveServerParam(0,100); }
return 0;
}
//------------------------------------------------------------------------
void CCheckNameService::StartService()
{
FUNCTION_BEGIN;
if (!g_onexceptionbegincallback){
minidump_type=minidump_type | MiniDumpWithPrivateReadWriteMemory | MiniDumpWithDataSegs | MiniDumpWithHandleData | MiniDumpWithProcessThreadData;
g_onexceptionbegincallback=&OnExceptionBeginCallBack;
}
if (m_boStartService || !LoadLocalConfig())
return;
g_logger.forceLog(zLogger::zINFO,_STARTSERVICE_LOG_);
stUrlInfo cfgui(0, m_szsvrcfgdburl, true);
CSqlClientHandle* cfgsqlc = cfgui.NewSqlClientHandle();
if (cfgsqlc)
{
if (cfgsqlc->setHandle())
{
m_iocp.Init(m_niocpworkthreadcount);
m_iocp.SetIocpCallBack(true, 500 , 800 , 500);
m_svrdatadb.putURL(_SVR_PARAM_DBHASHCODE_,m_szgamesvrparamdburl,false,16);
if (LoadSvrConfig(cfgsqlc) && LoadServerParam())
{
LoadSysParam(cfgsqlc);
m_boStartService = false;
m_msgProcessThread=CThreadFactory::CreateBindClass(this,&CCheckNameService::SimpleMsgProcessThread,(void*)NULL);
if (m_msgProcessThread)
{
m_msgProcessThread->Start(false);
m_LogicProcessThread=CThreadFactory::CreateBindClass(this,&CCheckNameService::LogicProcessThread,(void*)NULL);
if (m_LogicProcessThread)
{
m_LogicProcessThread->Start(false);
m_boStartService = true;
}
}
if (!m_boStartService)
{
m_boStartService = true;
StopService();
m_boStartService = false;
}
}
else
{
m_boStartService = true;
StopService();
m_boStartService = false;
}
}
cfgsqlc->unsetHandle();
SAFE_DELETE(cfgsqlc);
}
if (m_boStartService)
{
g_logger.forceLog(zLogger::zINFO,"启动服务成功...");
} else {
g_logger.forceLog(zLogger::zINFO,"启动服务失败...");
}
}
//------------------------------------------------------------------------
void CCheckNameService::RefSvrRunInfo(){
FUNCTION_WRAPPER_RESET(true);
if (!m_boshutdown){
CThreadMonitor::getme().DebugPrintAllThreadDebufInfo();
}
}
//------------------------------------------------------------------------
void CCheckNameService::ShutDown()
{
FUNCTION_BEGIN;
if (m_boshutdown){return;}
if (!m_boStartService){return;}
m_boshutdown=true;
CLD_Accepter* pservice=m_TcpServices.getservice(_SUBSVR_CONN_,0);
if (pservice && pservice->GetClientsCount()==0)
{
SaveServerParam(0,0);
}
StopService();
SaveServerParam(0,0);
this->Processmsg();
Sleep(2000);
}
//------------------------------------------------------------------------
void CCheckNameService::StopService()
{
FUNCTION_BEGIN;
if (!m_boStartService) {
return;
}
g_logger.forceLog(zLogger::zINFO,"开始停止服务...");
do {
//AILOCKT(m_toplock);
if (m_LogicProcessThread){ m_LogicProcessThread->Suspend();}
if (m_LogicProcessThread){ m_LogicProcessThread->Resume(); }
}while(false);
do{
AILOCKT(m_gamesvrsession);
m_gamesvrsession.clear();
} while (false);
m_TcpConnters.closeall();
m_TcpServices.closeall();
m_iocp.Uninit();
if (m_msgProcessThread){
m_msgProcessThread->Terminate();
m_msgProcessThread->Waitfor();
SAFE_DELETE(m_msgProcessThread);
}
if (m_LogicProcessThread){
m_LogicProcessThread->Terminate();
m_LogicProcessThread->Waitfor();
SAFE_DELETE(m_LogicProcessThread);
}
m_TcpConnters.clear();
m_TcpServices.clear();
clearpmap2(m_checkstrmap);
m_boStartService = false;
g_logger.forceLog(zLogger::zINFO,"停止服务成功...");
}
//------------------------------------------------------------------------
bool CCheckNameService::LoadLocalConfig()
{
FUNCTION_BEGIN;
CXMLConfigParse config;
config.InitConfig();
if (m_szsvrcfgdburl[0]==0)
{
config.readstr("svrcfg",m_szsvrcfgdburl,sizeof(m_szsvrcfgdburl)-1,"msmdb://game:k3434yiuasdh848@127.0.0.1:0/\".\\db\\mydb_svrcfg.mdb\"");
if (m_szsvrcfgdburl[0]==0)
{
return false;
}
}
if (m_szgamesvrparamdburl[0]==0)
{
config.readstr("chksvrparam",m_szgamesvrparamdburl,sizeof(m_szgamesvrparamdburl)-1,"msmdb://game:k3434yiuasdh848@127.0.0.1:0/\".\\db\\mydb_svrparam.mdb\"");
if (m_szgamesvrparamdburl[0]==0)
{
return false;
}
}
if (m_szSvrName[0]==0)
{
config.readstr("svrname",m_szSvrName,sizeof(m_szSvrName)-1,"测试区");
}
if (m_szmanageip[0]==0)
{
config.readstr("manageip",m_szmanageip,sizeof(m_szmanageip)-1,"127.0.0.1");
}
m_manageport=config.readvalue("manageport",(WORD)5000);
m_boConnectManage=(config.readvalue("openmanage",(BYTE)1)==1);
m_boAutoStart=(config.readvalue("autostart",(BYTE)0)==1);
m_niocpworkthreadcount=safe_min(config.readvalue("iocpworks",(int)0),36);
if (m_svridx==0)
{
m_svridx = config.readvalue("svrid",(WORD)0,true) & 0x7fff;
if (m_svridx==0)
{
return false;
}
}
m_Svr2SvrLoginCmd.svr_id=m_svridx;
return true;
}
//------------------------------------------------------------------------
bool CCheckNameService::LoadSvrConfig(CSqlClientHandle* sqlc)
{
FUNCTION_BEGIN;
if (!sqlc) {
return false;
}
char extip_port[2048] = { 0 };
char dburl[2048] = { 0 };
WORD wtradeid=-1;
dbCol serverinfo_define[] =
{
{_DBC_SO_("gametype", DB_WORD, stServerInfo, wgame_type)},
{_DBC_SO_("zoneid", DB_WORD, stServerInfo, wzoneid)},
{_DBC_SO_("zonename", DB_STR, stServerInfo, szZoneName)},
{_DBC_SO_("id", DB_WORD, stServerInfo, svr_id)},
{_DBC_SO_("type", DB_WORD, stServerInfo, svr_type)},
{_DBC_SO_("name", DB_STR, stServerInfo, szName)},
{_DBC_SO_("ip", DB_STR, stServerInfo, szIp)},
{_DBC_SO_("gatewayport", DB_WORD, stServerInfo, GatewayPort)},
{_DBC_SO_("dbport", DB_WORD, stServerInfo, DBPort)},
{_DBC_SO_("gameport", DB_WORD, stServerInfo, GamePort)},
{_DBC_SO_("subsvrport", DB_WORD, stServerInfo, SubsvrPort)},
{_DBC_SA_("extip_port", DB_STR, extip_port)}, //对客户端开放的 IP 端口
{_DBC_SA_("dburl", DB_STR, dburl)},
{_DBC_MO_NULL_(stServerInfo)},
};
bool boret = false;
int ncount = sqlc->getCount(DB_CONFIG_TBL," deleted=0 ");
if (ncount > 0)
{
ZSTACK_ALLOCA(stServerInfo *, info, (ncount + 1));
int ncur = sqlc->execSelectSql(vformat("select top 1 * from "DB_CONFIG_TBL" where id=%u and type=%u and deleted=0 ", m_svridx, m_svrtype), serverinfo_define, (unsigned char*) info);
if (ncur == 1)
{
strcpy_s(m_szLocalIp, sizeof(m_szLocalIp) - 1, info[0].szIp);
m_subsvrport= info[0].SubsvrPort;
if (m_TcpServices.put(&m_iocp, m_subsvrport, "重复性校验交换端口", _SUBSVR_CONN_, 0, m_szLocalIp) != 0)
{
g_logger.error("重复性校验交换端口 ( %s : %d ) 监听失败...", m_szLocalIp, m_subsvrport);
return false;
}
CEasyStrParse parse1, parse2;
do {
AILOCKT(cfg_lock);
parse1.SetParseStr(dburl, "\x9, ;", "''", NULL);
for (int i = 0; i < parse1.ParamCount(); i++)
{
parse2.SetParseStrEx(parse1[i], "='", "''",NULL);
if (parse2.ParamCount() == 4)
{
int nmaxdb=atoi(parse2[1]);
nmaxdb=(nmaxdb==0)?16:nmaxdb;
nmaxdb=safe_max(nmaxdb,1);
stUrlInfo ui(atoi(parse2[0]), parse2[3],atoi(parse2[2]) != 0,nmaxdb);
if (!ui.geturlerror())
{
if (!m_datadb.putURL(&ui))
{
g_logger.error("重复性校验 数据库 ( %s ) 连接失败...", parse1[i]);
return false;
}
DWORD hashcode = ui.hashcode;
}
else
{
g_logger.error("重复性校验 数据库 ( %s ) 连接失败...", parse1[i]);
return false;
}
}
else
{
g_logger.error("重复性校验 数据库连接字符串 ( %s ) 解析失败...", parse1[i]);
return false;
}
}
}while(false);
boret = true;
}
if (boret)
{
int idx=0;
ncount = sqlc->execSelectSql(vformat("select top %d * from "DB_CONFIG_TBL" where id>0 and id<>%u and deleted=0 ", ncount, m_svridx), serverinfo_define, (unsigned char *) info);
if (ncount > 0 )
{
do
{
AILOCKT(cfg_lock);
m_svrlistmap.clear();
} while (false);
unsigned int idx = 0;
if (boret)
{
for (int i = 0; i < ncount; i++)
{
if ( info[i].svr_type==_SUPERGAMESVR_TYPE || info[i].svr_type==_GAMESVR_TYPE || info[i].svr_type==_DBSVR_TYPE || info[i].svr_type==_LOGINSVR_TYPE )
{
do
{
AILOCKT(cfg_lock);
m_svrlistmap[info[i].svr_marking] = info[i];
} while (false);
}
}
}
}
}
}
return boret;
}
//------------------------------------------------------------------------
bool CCheckNameService::LoadSysParam(CSqlClientHandle* sqlc)
{
FUNCTION_BEGIN;
if (!sqlc) {
return false;
}
m_Svr2SvrLoginCmd.wgame_type=0;
m_Svr2SvrLoginCmd.wzoneid=m_nZoneid;
return true;
}
//------------------------------------------------------------------------
bool CCheckNameService::LoadServerParam(){
FUNCTION_BEGIN;
GETAUTOSQL(CSqlClientHandle *, sqlc, m_svrdatadb, _SVR_PARAM_DBHASHCODE_);
if (!sqlc){ return false; }
int tmp=0;
dbCol svrparam_define[] =
{
{_DBC_SA_("UserOnlyID", DB_DWORD, m_dwUserOnlyId)},
{_DBC_SA_("AccountOnlyID", DB_DWORD, m_dwAccountOnlyId)},
{_DBC_SA_("StrOnlyID", DB_DWORD, m_dwStrOnlyId)},
{_DBC_SA_("PlatformID", DB_DWORD, m_nTradeid )},
{_DBC_SA_("ZoneID", DB_DWORD, m_nZoneid )},
{_DBC_NULL_},
};
const char * TempFormName = "逗你玩儿";
int ncur = sqlc->execSelectSql( vformat("select top 1 * from "DB_CHKSERVERPARAM_TBL" where id=%u and type=%u ", m_svridx, m_svrtype), svrparam_define, (unsigned char*) &tmp );
g_logger.forceLog(zLogger::zINFO,"运营平台[ %s ] ID = %d",TempFormName, m_nTradeid );
if (ncur!=1){ return false; }
if (m_dwUserOnlyId>=_MAX_ONLYID_ || m_dwAccountOnlyId>=_MAX_ONLYID_ || m_dwStrOnlyId>=_MAX_ONLYID_)
{
g_logger.error("UserOnlyID,AccountOnlyID,StrOnlyID 必须都小于 %d",_MAX_ONLYID_);
return false;
}
bool boisok=true;
if (m_dwUserOnlyId < _MIN_ONLYID_ )
{
m_dwUserOnlyId=_random(100)+100;
boisok = false;
}
if ( m_dwAccountOnlyId < _MIN_ONLYID_ )
{
m_dwAccountOnlyId=_random(100)+100;
boisok=false;
}
if (m_dwStrOnlyId<_MIN_ONLYID_)
{
m_dwStrOnlyId=_random(100)+100;
boisok=false;
}
if (!boisok)
{
g_logger.error("useronlyid,accountonlyid,stronlyid 必须都大于 %d",_MIN_ONLYID_);
}else
{
g_logger.forceLog(zLogger::zINFO,"useronlyid: %u accountonlyid: %u stronlyid: %u",m_dwUserOnlyId,m_dwAccountOnlyId,m_dwStrOnlyId);
}
return (boisok && SaveServerParam(0,10));
}
//------------------------------------------------------------------------
bool CCheckNameService::SaveServerParam(int naddtime,int naddid)
{
FUNCTION_BEGIN;
g_logger.forceLog(zLogger::zINFO,"UserOnlyID: %u AccountOnlyID: %u stronlyid: %u write_useronlyid: %u write_accountonlyid: %u write_stronlyid: %u",
m_dwUserOnlyId,m_dwAccountOnlyId,m_dwStrOnlyId,m_dwUserOnlyId+naddid,m_dwAccountOnlyId+naddid,m_dwStrOnlyId+naddid);
GETAUTOSQL(CSqlClientHandle *, sqlc, m_svrdatadb, _SVR_PARAM_DBHASHCODE_);
if (!sqlc){ return false; }
DWORD dwUserOnlyId = m_dwUserOnlyId+naddid;
DWORD dwAccountOnlyId = m_dwAccountOnlyId+naddid;
DWORD dwStrOnlyId = m_dwStrOnlyId+naddid;
if( dwUserOnlyId < 40000 )
{
g_logger.error( " dwUserverOnlyID Error : %d" , dwUserOnlyId );
return false;
}
int tmp=0;
dbCol svrparam_define[] =
{
{_DBC_SA_("id", DB_WORD, m_svridx)},
{_DBC_SA_("type", DB_WORD, m_svrtype)},
{_DBC_SA_("UserOnlyID", DB_DWORD, dwUserOnlyId)},
{_DBC_SA_("AccountOnlyID", DB_DWORD, dwAccountOnlyId)},
{_DBC_SA_("StrOnlyID", DB_DWORD, dwStrOnlyId)},
{_DBC_SA_("PlatformID", DB_DWORD, CCheckNameService::getMe().m_nTradeid)},
{_DBC_SA_("ZoneID", DB_DWORD, m_nZoneid)},
{_DBC_NULL_},
};
int nret=sqlc->execUpdate(DB_CHKSERVERPARAM_TBL, svrparam_define, (unsigned char *) &tmp, vformat(" id=%u and type=%u ", m_svridx, m_svrtype));
if (nret > 0)
{
return true;
}else
{
nret=sqlc->execInsert(DB_CHKSERVERPARAM_TBL, svrparam_define, (unsigned char *) &tmp);
if (nret > 0)
{
return true;
}
}
return false;
}
//------------------------------------------------------------------------
bool CCheckNameService::OnInit()
{
LoadLocalConfig();
if (m_boAutoStart){
OnStartService();
}
return true;
}
//------------------------------------------------------------------------
void CCheckNameService::OnIdle()
{
static time_t lastshow=time(NULL);
if (time(NULL)>lastshow){
SetStatus(0,"type: %d(id: %d) %d:%s",m_svrtype,m_svridx,0,"");
SetStatus(1,"%u/%u:%u:%u(%u:%u:%u)",m_iocp.GetClientCount(),m_iocp.GetAccepterCount(),
m_iocp.GetConnecterCount(),m_iocp.GetWaitRecycleCount(), 0,0,0);
SetStatus(2,"%u: %s",::GetCurrentProcessId(),CThreadMonitor::getme().m_szThreadFlag);
static time_t static_clear_tick=time(NULL)+60*5;
if (time(NULL)>static_clear_tick){
static_clear_tick=time(NULL)+60*5;
}
if (time(NULL)>m_timeshutdown && m_timeshutdown!=0){
g_logger.forceLog(zLogger::zINFO,"服务器执行定时关闭任务: %s",timetostr(m_timeshutdown));
m_timeshutdown=0;
m_forceclose=true;
Close();
}
lastshow=lastshow+1;
}
Sleep(50);
}
//------------------------------------------------------------------------
void CCheckNameService::OnQueryClose(bool& boClose)
{
if (m_boStartService){boClose=false;}
else {return;}
if (m_boshutdown){return;}
this->OnStopService();
}
//------------------------------------------------------------------------
void CCheckNameService::OnUninit()
{
}
//------------------------------------------------------------------------
void CCheckNameService::OnStartService(){
StartService();
if (m_boStartService){EnableCtrl( false );}
}
//------------------------------------------------------------------------
void CCheckNameService::OnStopService(){
if (m_forceclose || (MessageBox(0,"你确定要关闭游戏 全局字符串重复检测服务器 么?","警告",MB_OKCANCEL | MB_DEFBUTTON2)==IDOK)){
if (!m_forceclose){g_logger.forceLog(zLogger::zINFO,"服务器执行手动关闭任务");}
ShutDown();
if (!m_boStartService){EnableCtrl( true );}
this->Close();
}
}
//------------------------------------------------------------------------
void CCheckNameService::OnConfiguration()
{
SetLog(0,"重新加载配置文件...");
}
//------------------------------------------------------------------------
long CCheckNameService::OnTimer( int nTimerID ){
return 0;
}
//------------------------------------------------------------------------
fnSaveGMOrder g_SaveGMOrder=NULL;
//------------------------------------------------------------------------
bool CCheckNameService::OnCommand( char* szCmd )
{
g_SaveGMOrder(szCmd);
g_logger.forceLog(zLogger::zINFO,"服务器管理员执行GM命令 %s",szCmd);
return true;
}
//------------------------------------------------------------------------
long CCheckNameService::OnCommand( int nCmdID )
{
switch ( nCmdID )
{
case IDM_STARTSERVICE: OnStartService(); break;
case IDM_STOPSERVICE: OnStopService(); break;
case IDM_CONFIGURATION: OnConfiguration(); break;
case IDM_CLEARLOG: OnClearLog(); break;
case IDM_DEBUGINFO: RefSvrRunInfo(); break;
case IDM_EXIT: OnExit(); break;
}
return 0;
}
//------------------------------------------------------------------------
bool CCheckNameService::CreateToolbar()
{
TBBUTTON tbBtns[] =
{
{0, IDM_STARTSERVICE, TBSTATE_ENABLED, TBSTYLE_BUTTON},
{1, IDM_STOPSERVICE, TBSTATE_ENABLED, TBSTYLE_BUTTON},
};
int nBtnCnt = sizeof( tbBtns ) / sizeof( tbBtns[0] );
m_hWndToolbar = CreateToolbarEx( m_hWnd, WS_CHILD | WS_VISIBLE | WS_BORDER,
IDC_TOOLBAR, nBtnCnt, m_hInstance, IDB_TOOLBAR,
(LPCTBBUTTON) &tbBtns, nBtnCnt, 16, 16, 16, 16, sizeof( TBBUTTON ) );
m_hCmdEdit = CreateWindow( WC_EDIT, "",WS_CHILD| WS_VISIBLE | ES_WANTRETURN,
nBtnCnt* (16+8)+16, 3, m_nwidth-(nBtnCnt* (16+8)+16), 19, m_hWndToolbar, 0, m_hInstance, this );
INIT_AUTOCOMPLETE(m_hCmdEdit,"AutoComplete.dll","InitAutoComplete","SaveGMOrder",".\\cmdlist\\checknamesvrcmd.txt",g_SaveGMOrder,g_AutoCompleteh);
SetWindowLong( m_hCmdEdit, GWL_USERDATA,(long)this);
m_EditMsgProc=(WNDPROC)SetWindowLong (m_hCmdEdit, GWL_WNDPROC, (long)WinProc);
return m_hWndToolbar ? true : false;
}
//------------------------------------------------------------------------
bool CCheckNameService::Init( HINSTANCE hInstance )
{
m_hInstance = hInstance;
InitCommonControls();
if ( !CreateWnd() || !CreateToolbar() || !CreateList() || !CreateStatus() )
return false;
int pos[ 4 ]={ 300, 480, 620, -1 }; // 100, 200, 300 为间隔
::SendMessage( m_hWndStatus, SB_SETPARTS, (WPARAM)4, (LPARAM)pos );
EnableCtrl( true );
ShowWindow( m_hWnd, SW_SHOWDEFAULT );
if ( !OnInit() )
return false;
return true;
}
//------------------------------------------------------------------------
void CCheckNameService::OnClearLog(){
__super::OnClearLog();
}
//------------------------------------------------------------------------
void CCheckNameService::EnableCtrl( bool bEnableStart )
{
HMENU hMenu = GetSubMenu( GetMenu( m_hWnd ), 0 );
if ( bEnableStart ){
EnableMenuItem( hMenu, IDM_STARTSERVICE, MF_ENABLED | MF_BYCOMMAND );
EnableMenuItem( hMenu, IDM_STOPSERVICE, MF_GRAYED | MF_BYCOMMAND );
EnableMenuItem( hMenu, IDM_CONFIGURATION, MF_ENABLED | MF_BYCOMMAND );
SendMessage( m_hWndToolbar, TB_SETSTATE, IDM_STARTSERVICE,
(LPARAM) MAKELONG( TBSTATE_ENABLED, 0 ) );
SendMessage( m_hWndToolbar, TB_SETSTATE, IDM_STOPSERVICE,
(LPARAM) MAKELONG( TBSTATE_INDETERMINATE, 0 ) );
}else{
EnableMenuItem( hMenu, IDM_STARTSERVICE, MF_GRAYED | MF_BYCOMMAND );
EnableMenuItem( hMenu, IDM_STOPSERVICE, MF_ENABLED | MF_BYCOMMAND );
EnableMenuItem( hMenu, IDM_CONFIGURATION, MF_GRAYED | MF_BYCOMMAND );
SendMessage( m_hWndToolbar, TB_SETSTATE, IDM_STARTSERVICE,
(LPARAM) MAKELONG( TBSTATE_INDETERMINATE, 0 ) );
SendMessage( m_hWndToolbar, TB_SETSTATE, IDM_STOPSERVICE,
(LPARAM) MAKELONG( TBSTATE_ENABLED, 0 ) );
}
}
//------------------------------------------------------------------------
static CIntLock msglock;
//------------------------------------------------------------------------
void __stdcall ShowLogFunc(zLogger::zLevel& level,const char* logtime,const char* msg){
if (msg) {
CCheckNameService::getMe().SetLog(level.showcolor,msg);
}
}
//------------------------------------------------------------------------
void OnCreateInstance(CWndBase *&pWnd)
{
OleInitialize(NULL);
pWnd=CCheckNameService::instance();
CXMLConfigParse config;
config.InitConfig();
int nshowlvl=config.readvalue("showlvl",(int)5);
int nloglvl=config.readvalue("writelvl",(int)3);
char szlogpath[MAX_PATH];
config.readstr("logpath",szlogpath,sizeof(szlogpath)-1,vformat(".\\log\\checknamesvr%d_log\\",CCheckNameService::getMe().m_Svr2SvrLoginCmd.svr_id),true);
g_logger.setLevel(nloglvl, nshowlvl);
g_logger.SetLocalFileBasePath(szlogpath);
g_logger.SetShowLogFunc(ShowLogFunc);
}
//------------------------------------------------------------------------
int OnDestroyInstance( CWndBase *pWnd ){
if ( pWnd ){
CCheckNameService::delMe();
OleUninitialize();
pWnd = NULL;
}
return 0;
}
//------------------------------------------------------------------------
|
#include <iostream>
#include <vector>
#include <memory>
#include <cassert>
#include <random>
#include <iomanip>
#include "Utils/NotNull.hpp"
#include "NodeSpecs.hpp"
#include "NodeBuilders/NodeBuilder.hpp"
#include "NodeBuilders/BinaryNodeBuilder.hpp"
#include "BuilderStorage.hpp"
#include "NetworkBuilder.hpp"
#include "LayeredNetworkBuilder.hpp"
#include "LayeredNetworkBuilders/FullyConnectedLayerSpecs.hpp"
#include "LayeredNetworkBuilders/FullyConnectedLayerBuilder.hpp"
#include "LayeredNetworkBuilders/InputLayerSpecs.hpp"
#include "Utils/MathVectorAdapter.hpp"
#include "StreamOperators.hpp"
#include "Datasets/MnistLoader.hpp"
#include <set>
#include "NormalDistributionGenerator.hpp"
#include "MnistPreprocessedDataSet.hpp"
#include "LearnUtils.hpp"
#include "PassThroughLayerNodeFactories/ReLULayer.hpp"
#include "ModelData.hpp"
int main()
{
std::string imagesPath = "../../../data/train-images-idx3-ubyte";
std::string labelsPath = "../../../data/train-labels-idx1-ubyte";
std::string testImagesPath = "../../../data/t10k-images-idx3-ubyte";
std::string testLabelsPath = "../../../data/t10k-labels-idx1-ubyte";
auto mnistDataset = MnistPreprocessedDataSet<float>(loadMnistDataset(imagesPath, labelsPath));
std::cout << "Learning set: " << mnistDataset.getInputSampleSize() << " " << mnistDataset.getNumSamples() << " " << mnistDataset.getOutputSampleSize() << std::endl;
auto testDataset = MnistPreprocessedDataSet<float>(loadMnistDataset(testImagesPath, testLabelsPath));
std::cout << "Test set: " << testDataset.getInputSampleSize() << " " << testDataset.getNumSamples() << " " << testDataset.getOutputSampleSize() << std::endl;
LayeredNetworkBuilder layeredNetworkBuilder;
auto outLayer = layeredNetworkBuilder.setOutputLayer(FullyConnectedLayerSpecs{
std::make_unique<ReLULayerNodeFactory<BNN_TYPE>>(), mnistDataset.getOutputSampleSize()});
auto hiddenLayer = outLayer->setInputLayer(FullyConnectedLayerSpecs{
std::make_unique<ReLULayerNodeFactory<BNN_TYPE>>(), 32});
hiddenLayer->setInputLayer(InputLayerSpecs{mnistDataset.getInputSampleSize()});
auto network = layeredNetworkBuilder.buildBackPropagationNetwork(0.01f);
if(modelFileExists("model_data.txt"))
{
ModelData<BNN_TYPE> modelData(network->getVariables().size());
modelData.load("model_data.txt");
network->setVariables(modelData.getData());
}
else
{
network->setVariables(NormalDistributionGenerator<BNN_TYPE>(17, 0, 1e-1));
}
using namespace std::chrono;
auto start = steady_clock::now();
BNN_TYPE errorSum{};
for(auto i = 0u; i < 100u; ++i)
{
errorSum = learnEpochParallel(layeredNetworkBuilder, network, mnistDataset, 256, 0.01f, i);
std::cout << "epoch: " << i << " errorSum: " << errorSum << std::endl;
}
auto end = steady_clock::now();
std::cout << "Time taken: " << duration_cast<seconds>(end - start).count() << "s. errorSum: " << errorSum << std::endl;
ModelData<BNN_TYPE> modelData(network->getVariables());
modelData.save("model_data.txt");
// 8231
// TODO
// 4. abstract backprop
// 5. Cross validation 1:10
// 6. Model saving/loading to/from files
// 7. Weights saving/loading for model
//
// zero-centering data! mean centering
// Shuffle training examples at each new epoch
// Normalize input variables (u,o) = (0,1), where u=0
// im2col for convolution
/* gradient check
* http://uvadlc.github.io/lectures/lecture2.pdf
*
* Most dangerous part for new modules -> get gradients wrong
* Compute gradient analytically
* Compute gradient computationally
* Compare (difference should be in 10^-4, 10^-7)
*/
}
|
#ifndef GETSAVEFILENAMEWIDGET_H
#define GETSAVEFILENAMEWIDGET_H
// RsaToolbox
#include <LastPath.h>
// Qt
#include <QWidget>
namespace RsaToolbox {
namespace Ui {
class getSaveFileNameWidget;
}
class getSaveFileNameWidget : public QWidget
{
Q_OBJECT
Q_PROPERTY(QString filePath READ filePath WRITE setFilePath NOTIFY filePathChanged USER true)
public:
explicit getSaveFileNameWidget(QWidget *parent = 0);
~getSaveFileNameWidget();
SharedLastPath lastPath() const;
void setLastPath(SharedLastPath lastPath);
bool isFilters() const;
QString filters() const;
void setFilters(const QString &filters);
bool isFilePath() const;
QString filePath() const;
void setFilePath(const QString &filePath);
private slots:
void on_getButton_clicked();
signals:
void filePathChanged(const QString &filePath);
private:
Ui::getSaveFileNameWidget *ui;
QString _filePath;
QString fileName() const;
QString path() const;
QString _filters;
SharedLastPath _lastPath;
};
} // RsaToolbox
#endif // GETSAVEFILENAMEWIDGET_H
|
//
// Created by wind on 2023/3/28.
//
#include <string.h>
#include "asset_png_decoder.h"
AssetPngDecoder::AssetPngDecoder(AAssetManager* mgr ,char *fName): PngDecoder(fName) {
asset = AAssetManager_open(mgr, fName, AASSET_MODE_STREAMING);
if (asset==NULL){
ALOGE("AssetPngDecoder open assert error");
}else{
ALOGE("AssetPngDecoder open assert success");
}
}
void AssetPngDecoder::pngReadCallback(png_bytep data, png_size_t length) {
AAsset_read(asset,data,length);
}
png_bytep AssetPngDecoder::readHead() {
png_byte* head=new png_byte[8];
AAsset_read(asset,head,8);
return head;
}
AssetPngDecoder::~AssetPngDecoder() {
fClose();
}
void AssetPngDecoder::fClose() {
if (asset){
AAsset_close(asset);
asset=NULL;
}
}
|
#include "Knight.h"
const WeaponType Knight::types = {WeaponType::lance};
Knight::Knight(std::string name):Character()
{
this->setName(name);
this->setHealth(28);
this->setStrength(12);
this->setDefense(7);
this->setSpeed(7);
this->setMovement(6);
this->setSkill(8);
this->setLuck(6);
this->setMagic(0);
this->setResistance(3);
this->setExp(0);
this->setLevel(1);
Lance* lance = new Lance("Lance en bronze", 4, 85, 1, 0, 20, 50, WeaponType::lance);
this->setWeapon(lance);
}
Knight::~Knight()
{
//dtor
}
Knight::Knight(const Knight& other):Character(other)
{
this->setWeapon(other.getWeapon());
}
void Knight::setWeapon(Weapon* weapon)
{
if (weapon->TYPE == types)
Character::setWeapon(weapon);
}
Knight* Knight::clone()const
{
return new Knight(*this);
}
Knight& Knight::operator=(const Knight& rhs)
{
if (this == &rhs) return *this; // handle self assignment
//assignment operator
return *this;
}
std::string Knight::str()const{
stringstream strs;
strs << getName() << endl << "HP : " << getHealth() << endl << "STRENGTH : " << getStrength() << endl
<< "DEFENSE : " << getDefense() << endl << "SPEED : " << getSpeed() << endl << "MOVEMENT : " << getMovement()<< endl << "SKILL : " << getSkill()<< endl <<"RESISTANCE : "<<getResistance()
<< endl <<"MAGIC : "<<getMagic()<< endl <<"LUCK : "<<getLuck()<< endl <<"EXPERIENCE : " <<getExp()<< endl <<"LEVEL : " <<getLevel()<<endl;
return strs.str();
}
//Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus
void Knight::addHealth(){
int tmp= this->getHealth();
int ran=rand();
while (ran>100){
ran=rand();
}
int max;
if(this->getName()=="Axel"){
max=25;
}
else{
max=55;
}
if((tmp>0) && (ran>=max)){
tmp++;
}
this->setHealth(tmp);
}
//Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus
void Knight::addStrength(){
int tmp= this->getStrength();
int ran = rand();
while(ran>100){
ran=rand();
}
int max;
if(this->getName()=="Axel"){
max=45;
}
else{
max=75;
}
if((tmp>0) && (ran>=max)){
tmp++;
}
this->setStrength(tmp);
}
//Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus
void Knight::addDefense(){
int tmp= this->getDefense();
int ran= rand();
while(ran>100){
ran = rand();
}
int max;
if(this->getName()=="Axel"){
max=30;
}
else{
max=80;
}
if((tmp>0) && (ran>=max)){
tmp++;
}
this->setDefense(tmp);
}
//Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus
void Knight::addSpeed(){
int tmp= this->getSpeed();
int ran=rand();
while(ran>100){
ran=rand();
}
int max;
if(this->getName()=="Axel"){
max=75;
}
else{
max=80;
}
if((tmp>0) && (ran>=max)){
tmp++;
}
this->setSpeed(tmp);
}
//Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus
void Knight::addResistance(){
int tmp= this->getResistance();
int ran=rand();
while(ran>100){
ran=rand();
}
int max;
if(this->getName()=="Axel"){
max=10;
}
else{
max=50;
}
if((tmp>0) && (ran>=max)){
tmp++;
}
this->setResistance(tmp);
}
//Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus
void Knight::addMagic(){
int tmp= this->getMagic();
int ran=rand();
while(ran>100){
ran=rand();
}
int max;
if(this->getName()=="Axel"){
max=95;
}
else{
max=100;
}
if((tmp>0) && (ran>=max)){
tmp++;
}
this->setMagic(tmp);
}
//Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus
void Knight::addLuck(){
int tmp= this->getLuck();
int ran=rand();
while(ran>100){
ran=rand();
}
int max;
if(this->getName()=="Axel"){
max=85;
}
else{
max=100;
}
if((tmp>0) && (ran>=max)){
tmp++;
}
this->setLuck(tmp);
}
//Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus
void Knight::addSkill(){
int tmp= this->getSkill();
int ran=rand();
while(ran>100){
ran=rand();
}
int max;
if(this->getName()=="Axel"){
max=90;
}
else{
max=95;
}
if((tmp>0) && (ran>=max)){
tmp++;
}
this->setSkill(tmp);
}
|
#pragma once
#include "RigidBody.h"
#include "Poly.h"
#include <vector>
#include "Transform.h"
using std::vector;
class Stitched :
public RigidBody
{
public:
Stitched(vector<vector<vec2>> const& allVertices, vec2 position, vec2 velocity, float rotation, float fAngVel, float mass, float elasticity, float fFricCoStatic, float fFricCoDynamic, float fDrag, float fAngDrag, glm::vec4 colour);
~Stitched();
void fixedUpdate(vec2 const& gravity, float timeStep);
void makeGizmo();
inline int GetPolyCount() const& { return (int)m_Polys.size(); };
inline Poly* GetPoly(int index) const { return m_Polys[index]; };
private:
Transform m_GlobalTransform;
vector<vec2> m_PolyRelPos;
vector<Poly*> m_Polys;
vec4 m_Colour;
};
|
/********************************************************************************
** Form generated from reading UI file 'classwidget.ui'
**
** Created by: Qt User Interface Compiler version 5.2.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_CLASSWIDGET_H
#define UI_CLASSWIDGET_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTableView>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_ClassWidget
{
public:
QHBoxLayout *horizontalLayout;
QVBoxLayout *verticalLayout;
QPushButton *addClass;
QPushButton *removeClass;
QTableView *tableView;
void setupUi(QWidget *ClassWidget)
{
if (ClassWidget->objectName().isEmpty())
ClassWidget->setObjectName(QStringLiteral("ClassWidget"));
ClassWidget->resize(390, 259);
horizontalLayout = new QHBoxLayout(ClassWidget);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
verticalLayout = new QVBoxLayout();
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
addClass = new QPushButton(ClassWidget);
addClass->setObjectName(QStringLiteral("addClass"));
QIcon icon;
icon.addFile(QStringLiteral(":/HyperML/Resources/add.png"), QSize(), QIcon::Normal, QIcon::Off);
addClass->setIcon(icon);
verticalLayout->addWidget(addClass);
removeClass = new QPushButton(ClassWidget);
removeClass->setObjectName(QStringLiteral("removeClass"));
QIcon icon1;
icon1.addFile(QStringLiteral(":/HyperML/Resources/remove.png"), QSize(), QIcon::Normal, QIcon::Off);
removeClass->setIcon(icon1);
verticalLayout->addWidget(removeClass);
horizontalLayout->addLayout(verticalLayout);
tableView = new QTableView(ClassWidget);
tableView->setObjectName(QStringLiteral("tableView"));
tableView->setSelectionMode(QAbstractItemView::SingleSelection);
tableView->setSelectionBehavior(QAbstractItemView::SelectItems);
horizontalLayout->addWidget(tableView);
retranslateUi(ClassWidget);
QMetaObject::connectSlotsByName(ClassWidget);
} // setupUi
void retranslateUi(QWidget *ClassWidget)
{
ClassWidget->setWindowTitle(QApplication::translate("ClassWidget", "Classes", 0));
#ifndef QT_NO_TOOLTIP
addClass->setToolTip(QApplication::translate("ClassWidget", "Add Class", 0));
#endif // QT_NO_TOOLTIP
addClass->setText(QString());
#ifndef QT_NO_TOOLTIP
removeClass->setToolTip(QApplication::translate("ClassWidget", "Delete Class (and associated ROI)", 0));
#endif // QT_NO_TOOLTIP
removeClass->setText(QString());
} // retranslateUi
};
namespace Ui {
class ClassWidget: public Ui_ClassWidget {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_CLASSWIDGET_H
|
// Created on: 1992-10-14
// Created by: Christophe MARION
// Copyright (c) 1992-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 _HLRBRep_TheCSFunctionOfInterCSurf_HeaderFile
#define _HLRBRep_TheCSFunctionOfInterCSurf_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <gp_Lin.hxx>
#include <gp_Pnt.hxx>
#include <math_FunctionSetWithDerivatives.hxx>
#include <Standard_Boolean.hxx>
#include <math_Vector.hxx>
class HLRBRep_SurfaceTool;
class gp_Lin;
class HLRBRep_LineTool;
class math_Matrix;
class gp_Pnt;
class HLRBRep_TheCSFunctionOfInterCSurf : public math_FunctionSetWithDerivatives
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT HLRBRep_TheCSFunctionOfInterCSurf(const Standard_Address& S, const gp_Lin& C);
Standard_EXPORT Standard_Integer NbVariables() const;
Standard_EXPORT Standard_Integer NbEquations() const;
Standard_EXPORT Standard_Boolean Value (const math_Vector& X, math_Vector& F);
Standard_EXPORT Standard_Boolean Derivatives (const math_Vector& X, math_Matrix& D);
Standard_EXPORT Standard_Boolean Values (const math_Vector& X, math_Vector& F, math_Matrix& D);
Standard_EXPORT const gp_Pnt& Point() const;
Standard_EXPORT Standard_Real Root() const;
Standard_EXPORT const Standard_Address& AuxillarSurface() const;
Standard_EXPORT const gp_Lin& AuxillarCurve() const;
protected:
private:
Standard_Address surface;
gp_Lin curve;
gp_Pnt p;
Standard_Real f;
};
#endif // _HLRBRep_TheCSFunctionOfInterCSurf_HeaderFile
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.