text
stringlengths 8
6.88M
|
|---|
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1005;
int a[maxn][maxn];
int main() {
int n, m, r, c;
cin >> n >> m >> r >> c;
//while(cin >> n >> m >> r >> c) {
int col = 0, row = 0;
int cnt = 1;
memset(a, 0, sizeof a);
int sum = n*m;
a[row][col] = 1;
while(cnt < sum) {
while(col + 1 < m && !a[row][col + 1]) {
a[row][++col] = ++cnt;
}
while(row + 1 < n && !a[row + 1][col]) {
a[++row][col] = ++cnt;
}
while(col - 1 >= 0 && !a[row][col - 1]) {
a[row][--col] = ++cnt;
}
while(row - 1 >= 0 && !a[row - 1][col]) {
a[--row][col] = ++cnt;
}
}
cout << a[r-1][c-1] << endl;
//}
return 0;
}
|
#pragma once
#include "FwdDecl.h"
#include "Keng/Core/IGlobalEnvironment.h"
#include <memory>
#include <thread>
#include <unordered_map>
#include <vector>
#include <mutex>
namespace keng::core
{
class GlobalEnvironment : public IGlobalEnvironment
{
public:
GlobalEnvironment();
~GlobalEnvironment();
virtual IGlobalSystem& GetGlobalSystem(size_t id) override final;
void RegisterModule(ModulePtr module);
static GlobalEnvironment& PrivateInstance();
Application* CreateApplication();
void DestroyApplication(Application*);
ISystemPtr TryGetSystem(std::string_view name);
private:
std::mutex m_mutex;
std::unordered_map<std::thread::id, ApplicationPtr> m_threadToApplication;
std::vector<ApplicationPtr> m_applications;
std::vector<ModulePtr> m_modules;
};
}
|
#ifndef AWS_NODES_BLOCK_H
#define AWS_NODES_BLOCK_H
/*
* aws/nodes/block.h
* AwesomeScript Block
* Author: Dominykas Djacenka
* Email: Chaosteil@gmail.com
*/
#include <list>
#include "statement.h"
namespace AwS{
namespace Nodes{
class Block : public Statement{
public:
Block(std::list<Statement*>* content)
: Statement(), _content(content){
}
virtual ~Block(){
if(_content){
for(std::list<Statement*>::iterator i = _content->begin(); i != _content->end(); ++i){
if(*i)delete *i;
}
delete _content;
}
}
void translatePhp(std::ostream& output, TranslateSettings& settings) const throw(NodeException){
// output << "{" << std::endl;
for(std::list<Statement*>::iterator i = _content->begin(); i != _content->end(); ++i){
if(*i != NULL)
(*i)->translatePhp(output, settings);
}
// output << "}" << std::endl;
}
private:
std::list<Statement*>* _content;
};
};
};
#endif
|
/*
ID: stevenh6
TASK: concom
LANG: C++
*/
#include <fstream>
#include <string>
#include <vector>
using namespace std;
ofstream fout("concom.out");
ifstream fin("concom.in");
int largest = 0;
int pairs[101][101];
bool previous[101];
int ct[101];
void traverse(int pairsind)
{
if (!previous[pairsind])
{
previous[pairsind] = true;
for (int i = 1; i <= largest; i++)
{
ct[i] += pairs[pairsind][i];
if (ct[i] > 50)
{
traverse(i);
}
}
}
}
int main()
{
pairs[0][0] == 0;
int n;
fin >> n;
for (int i = 0; i < n; i++)
{
int a, b, c;
fin >> a >> b >> c;
if (a > largest) {
largest = a;
}
if (b > largest) {
largest = b;
}
pairs[a][b] = c;
}
for (int i = 1; i <= largest; i++)
{
int n = largest;
while (n > 0) {
previous[largest - n + 1] = false;
ct[largest - n + 1] = 0;
n--;
}
traverse(i);
for (int j = 1; j <= largest; j++)
{
if (j != i && ct[j] > 50)
{
fout << i << " " << j << endl;
}
}
}
}
|
#include "源.h"
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
vector <string> datas;
//得到data数据文件的总长度,告诉用户输入时不要越界
int get_longest() {
ifstream myfile(".\\data.txt");
bool judge = true;
if (!myfile.is_open())
{
judge = false;
cout << "无法打开data.txt数据文件!!" << endl;
}
string temp;
while (judge && (getline(myfile, temp)))
{
datas.push_back(temp);
}
myfile.close();
return datas.size() - 102;//前101个推不到,最后一个也推不到
}
//根据用户需要的行数,来从原data中截取对应行数(从最后开始)
void get_need_shoot(int sum) {
ofstream file_need_shoot(".\\need_shoot.txt", ios::trunc);//使用trunc,每次写入之前先删除原文件
for (int i = datas.size() - sum; i < datas.size(); i++)
{
file_need_shoot << datas[i];
file_need_shoot << endl;
}
file_need_shoot.close();
}
//因为只能从后往前算,所以得到的temp要进行反转,反转后保存为want.txt
void text_incersion() {
vector<string> nums;
ifstream myfile(".\\temp.txt");
ofstream outfile(".\\want.txt", ios::trunc);
bool judge = true;
if (!myfile.is_open())
{
cout << "未成功打开文件" << endl;
judge = false;
}
string temp1;
while (judge && getline(myfile, temp1))
{
nums.push_back(temp1);
}
for (int i = nums.size() - 1; i >= 0; i--)
{
outfile << nums[i];
outfile << endl;
}
myfile.close();
outfile.close();
}
//将want.txt和need_shoot.txt进行命中
void get_shoot() {
ifstream need_shoot(".\\need_shoot.txt");
ifstream myfile(".\\want.txt");
ofstream shooted(".\\been_shoot.txt", ios::trunc);
string temp1, temp2;
bool judge = true;
if (!need_shoot.is_open() && !myfile.is_open())
{
cout << "未成功打开文件aaa" << endl;
judge = false;
}
while (judge && getline(need_shoot, temp1) && getline(myfile, temp2))
{
int s1 = 0;
for (int i = temp1.size() - 29, j = 0; j < 10; i = i + 3, j++)
{
if ((((temp1[i] - 48) * 10 + (temp1[i + 1] - 48)) % 2) == (temp2[j] - 48))
s1 = s1 + 10;
}
shooted << s1;
shooted << " ";
}
need_shoot.close();
myfile.close();
shooted.close();
}
void main1(string filename, int temp)
{
//btnLoadDate("data.txt");
btnLoadDate(filename);
//int temp;
//cout << "你要跑多少行:";
//cin >> temp;
GenParseLsData(temp);
get_longest();
get_need_shoot(temp);
text_incersion();
get_shoot();
datas.clear();
}
|
/* -*- Mode: c++; tab-width: 4; 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.
*/
#include "core/pch.h"
#include "modules/widgets/OpWidget.h"
#include "modules/widgets/WidgetContainer.h"
#include "modules/widgets/OpTextCollection.h"
#ifdef SKIN_SUPPORT
# include "modules/skin/IndpWidgetPainter.h"
#endif
#include "modules/widgets/OpDropDown.h"
void LockedDropDownCloser::CloseLockedDropDowns()
{
const UINT32 locked_dd_count = locked_dropdowns.GetCount();
if (locked_dd_count > 0)
{
for (UINT32 i = 0; i < locked_dd_count; ++i)
{
locked_dropdowns.Get(i)->ClosePopup(TRUE);
}
locked_dropdowns.Clear();
}
}
WidgetsModule::WidgetsModule()
: OperaModule() // dummy, so what's left without #if is still valid
, tcinfo(0)
, widgetpaintermanager(0)
#ifdef WIDGETS_IME_SUPPORT
, im_listener(0)
#endif // WIDGETS_IME_SUPPORT
, widget_globals(0)
, m_delete_lock_count(0)
, m_has_failed_to_post_delete_message(FALSE)
{
}
void
WidgetsModule::InitL(const OperaInitInfo& info)
{
OpWidget::InitializeL();
widgetpaintermanager = OP_NEW_L(OpWidgetPainterManager, ());
tcinfo = OP_NEW_L(OP_TCINFO, ());
#ifdef WIDGETS_IME_SUPPORT
im_listener = OP_NEW_L(WidgetInputMethodListener, ());
im_spawning = FALSE;
#endif // WIDGETS_IME_SUPPORT
#if defined(SKIN_SUPPORT)
widgetpaintermanager->SetPrimaryWidgetPainter(OP_NEW_L(IndpWidgetPainter, ()));
#endif // SKIN_SUPPORT
}
void
WidgetsModule::Destroy()
{
#ifdef WIDGETS_IME_SUPPORT
OP_DELETE(im_listener);
im_listener = NULL;
#endif // WIDGETS_IME_SUPPORT
OP_DELETE(tcinfo);
OP_DELETE(widgetpaintermanager);
widgetpaintermanager = NULL;
if (!m_deleted_widgets.Empty())
{
ClearDeleteWidgetsMessage();
m_deleted_widgets.Clear();
}
OP_ASSERT(!g_main_message_handler->HasCallBack(this, MSG_DELETE_WIDGETS, (MH_PARAM_1)this));
OpWidget::Free();
}
void WidgetsModule::AddExternalListener(OpWidgetExternalListener *listener)
{
listener->Into(&external_listeners);
}
void WidgetsModule::RemoveExternalListener(OpWidgetExternalListener *listener)
{
listener->Out();
}
void WidgetsModule::PostDeleteWidget(OpWidget* widget)
{
if (!m_delete_lock_count && (m_deleted_widgets.Empty() || m_has_failed_to_post_delete_message))
PostDeleteWidgetsMessage();
widget->Into(&m_deleted_widgets);
OP_ASSERT(m_delete_lock_count || g_main_message_handler->HasCallBack(this, MSG_DELETE_WIDGETS, (MH_PARAM_1)this) || m_has_failed_to_post_delete_message);
}
// virtual
void WidgetsModule::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
switch (msg)
{
case MSG_DELETE_WIDGETS:
OP_ASSERT(!m_delete_lock_count);
OP_ASSERT(!m_deleted_widgets.Empty());
m_deleted_widgets.Clear();
g_main_message_handler->UnsetCallBack(this, MSG_DELETE_WIDGETS, par1);
break;
}
}
void WidgetsModule::PostDeleteWidgetsMessage()
{
MH_PARAM_1 p1 = (MH_PARAM_1)this;
OP_ASSERT(!g_main_message_handler->HasCallBack(this, MSG_DELETE_WIDGETS, p1));
OP_ASSERT(!m_delete_lock_count);
m_has_failed_to_post_delete_message = FALSE;
if (OpStatus::IsError(g_main_message_handler->SetCallBack(this, MSG_DELETE_WIDGETS, p1)))
m_has_failed_to_post_delete_message = TRUE;
else if (!g_main_message_handler->PostMessage(MSG_DELETE_WIDGETS, p1, 0))
{
m_has_failed_to_post_delete_message = TRUE;
g_main_message_handler->UnsetCallBack(this, MSG_DELETE_WIDGETS, p1);
}
}
void WidgetsModule::ClearDeleteWidgetsMessage()
{
MH_PARAM_1 p1 = (MH_PARAM_1)this;
OP_ASSERT(g_main_message_handler->HasCallBack(this, MSG_DELETE_WIDGETS, p1));
m_has_failed_to_post_delete_message = FALSE;
g_main_message_handler->RemoveDelayedMessage(MSG_DELETE_WIDGETS, p1, 0);
g_main_message_handler->UnsetCallBack(this, MSG_DELETE_WIDGETS, p1);
}
LockDeletedWidgetsCleanup::LockDeletedWidgetsCleanup()
{
WidgetsModule* wm = &g_opera->widgets_module;
++ wm->m_delete_lock_count;
if (wm->m_delete_lock_count == 1 && !wm->m_deleted_widgets.Empty())
wm->ClearDeleteWidgetsMessage();
OP_ASSERT(!g_main_message_handler->HasCallBack(wm, MSG_DELETE_WIDGETS, (MH_PARAM_1)wm));
}
LockDeletedWidgetsCleanup::~LockDeletedWidgetsCleanup()
{
WidgetsModule* wm = &g_opera->widgets_module;
OP_ASSERT(wm->m_delete_lock_count);
OP_ASSERT(!g_main_message_handler->HasCallBack(wm, MSG_DELETE_WIDGETS, (MH_PARAM_1)wm));
-- wm->m_delete_lock_count;
if (wm->m_delete_lock_count == 0 && !wm->m_deleted_widgets.Empty())
wm->PostDeleteWidgetsMessage();
OP_ASSERT(g_main_message_handler->HasCallBack(wm, MSG_DELETE_WIDGETS, (MH_PARAM_1)wm) ==
(!wm->m_delete_lock_count && !wm->m_deleted_widgets.Empty()));
}
|
/*****************************************************************************
* *
* OpenNI 2.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* 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 ONIPROPERTIES_H
#define ONIPROPERTIES_H
namespace openni
{
// Device properties
enum
{
DEVICE_PROPERTY_FIRMWARE_VERSION = 0, // string
DEVICE_PROPERTY_DRIVER_VERSION = 1, // OniVersion
DEVICE_PROPERTY_HARDWARE_VERSION = 2, // int
DEVICE_PROPERTY_SERIAL_NUMBER = 3, // string
DEVICE_PROPERTY_ERROR_STATE = 4, // ??
DEVICE_PROPERTY_IMAGE_REGISTRATION = 5, // OniImageRegistrationMode
//orbbec
OBEXTENSION_ID_IR_GAIN = 11,
OBEXTENSION_ID_IR_EXP = 12,
OBEXTENSION_ID_LDP_EN = 13,
OBEXTENSION_ID_CAM_PARAMS = 14,
OBEXTENSION_ID_LASER_EN = 15,
OBEXTENSION_ID_SERIALNUMBER = 16,
OBEXTENSION_ID_DEVICETYPE = 17,
OBEXTENSION_ID_UPDATE_FIRMWARE = 18,
// Files
DEVICE_PROPERTY_PLAYBACK_SPEED = 100, // float
DEVICE_PROPERTY_PLAYBACK_REPEAT_ENABLED = 101, // OniBool
};
// Stream properties
enum
{
STREAM_PROPERTY_CROPPING = 0, // OniCropping*
STREAM_PROPERTY_HORIZONTAL_FOV = 1, // float: radians
STREAM_PROPERTY_VERTICAL_FOV = 2, // float: radians
STREAM_PROPERTY_VIDEO_MODE = 3, // OniVideoMode*
STREAM_PROPERTY_MAX_VALUE = 4, // int
STREAM_PROPERTY_MIN_VALUE = 5, // int
STREAM_PROPERTY_STRIDE = 6, // int
STREAM_PROPERTY_MIRRORING = 7, // OniBool
STREAM_PROPERTY_NUMBER_OF_FRAMES = 8, // int
// Camera
STREAM_PROPERTY_AUTO_WHITE_BALANCE = 100, // OniBool
STREAM_PROPERTY_AUTO_EXPOSURE = 101, // OniBool
STREAM_PROPERTY_EXPOSURE = 102, // int
STREAM_PROPERTY_GAIN = 103, // int
STREAM_PROPERTY_SOFTWARE_REGISTRATION = 0x2080FF42, // int
};
// Device commands (for Invoke)
enum
{
DEVICE_COMMAND_SEEK = 1, // OniSeek
};
} // namespace openni
#endif // ONIPROPERTIES_H
|
#pragma once
class BasicObject
{
protected:
int x, y, w, h, FRAMEMAX;
int originalX, originalY, originalW, originalH;
Rect region; //collision region
float frame;
bool exists;
float hp;
float originalHP;
public:
int index;
float deadTimer;
void Reset()
{
x = originalX;
y = originalY;
hp = originalHP;
exists = true;
}
void Draw( BITMAP *destination, BITMAP *source, int offsetX, int offsetY )
{
if ( exists )
{
//masked_blit( source, destination, (int)frame * w, 0, x - offsetX, y - offsetY, w, h );
masked_blit( source, destination, 0, 0, x - offsetX, y - offsetY, w, h );
}
}
void Update();
void IncrementFrame()
{
frame += 0.15f;
if ( frame >= FRAMEMAX )
frame = 0.0f;
}
int X() { return x; }
int Y() { return y; }
int W() { return w; }
int H() { return h; }
int X2() { return x + w; }
int Y2() { return y + h; }
int RX() { return region.x; }
int RY() { return region.y; }
int RW() { return region.w; }
int RH() { return region.h; }
bool Exists() { return exists; }
void Exists( bool val ) { exists = val; }
Rect CollisionRegion() { return region; }
float HP() { return hp; }
void AddHP( float amt )
{
hp += amt;
if ( hp > 100 )
{
hp = 100;
}
}
};
|
#include "Water.hh"
Water::Water(const Map &map)
: map(map),
sizeX(map.getSizeX()), sizeY(map.getSizeY()),
points{std::vector<WaterPoint>(sizeX * sizeY),
std::vector<WaterPoint>(sizeX * sizeY)},
newBuffer(&points[0]),
oldBuffer(&points[1]),
numPasses(4),
dampening(fixed(10) / fixed(160)),
tension(fixed(3) / fixed(10)),
spread(fixed(3) / fixed(4)) {
}
WaterPoint Water::fpoint(const fvec2 &p) const {
assert(p.x >= 0 && p.x < sizeX);
assert(p.y >= 0 && p.y < sizeY);
size_t x1 = p.x.toInt(),
x2 = x1 < sizeX-1 ? x1 + 1 : x1;
size_t y1 = p.y.toInt(),
y2 = y1 < sizeY-1 ? y1 + 1 : y1;
fixed s = p.x - p.x.toInt(),
t = p.y - p.y.toInt();
fixed h11(point(x1, y1).height),
h21(point(x2, y1).height),
h22(point(x2, y2).height),
h12(point(x1, y2).height);
fixed v11(point(x1, y1).velocity),
v21(point(x2, y1).velocity),
v22(point(x2, y2).velocity),
v12(point(x1, y2).velocity);
fixed a11(point(x1, y1).acceleration),
a21(point(x2, y1).acceleration),
a22(point(x2, y2).acceleration),
a12(point(x1, y2).acceleration);
if (s + t <= 1) {
//std::cout << p.x << "|" << p.y << " (" << s << "|" << t << "): " <<h11 << "," << h21 << "," << h22 << "," << h12 << " -> " << h11 + s * (h21 - h11) + t * (h12 - h11) << std::endl;
return WaterPoint(h11 + s * (h21 - h11) + t * (h12 - h11),
v11 + s * (v21 - v11) + t * (v12 - v11),
a11 + s * (a21 - a11) + t * (a12 - a11));
} else {
//std::cout << p.x << "|" << p.y << " (" << s << "|" << t << "): " <<h11 << "," << h21 << "," << h22 << "," << h12 << " => " << h22 + (1-s) * (h12 - h22) + (1-t) * (h21 - h22) << std::endl;
return WaterPoint(h22 + (1-s) * (h12 - h22) + (1-t) * (h21 - h22),
v22 + (1-s) * (v12 - v22) + (1-t) * (v21 - v22),
a22 + (1-s) * (a12 - a22) + (1-t) * (a21 - a22));
}
}
void Water::splash(const Map::Pos &p, fixed speed) {
point(p).velocity += speed;
}
void Water::tick(fixed tickLengthS) {
for (auto &p : *oldBuffer) {
p.previousHeight = p.height;
spring(tickLengthS, p);
}
/*fixed rain = fixed(5) / fixed(1);
point(32,32).velocity += rain;
point(256-32,256-32).velocity += rain;
point(256-32,32).velocity += rain;
point(32,256-32).velocity += rain;*/
// Point-point interaction
for (size_t pass = 0; pass < numPasses; pass++) {
// Copy state to newBuffer
*newBuffer = *oldBuffer;
for (size_t x = 0; x < sizeX; x++) {
for (size_t y = 0; y < sizeY; y++) {
// Propagate from (x,y) to neighboring points
if (x > 0) propagate(tickLengthS, x, y, x-1, y);
if (x < sizeX-1) propagate(tickLengthS, x, y, x+1, y);
if (y > 0) propagate(tickLengthS, x, y, x, y-1);
if (y < sizeY-1) propagate(tickLengthS, x, y, x, y+1);
if (x > 0 && y > 0) propagate(tickLengthS, x, y, x-1, y-1);
if (x < sizeX-1 && y < sizeY-1) propagate(tickLengthS, x, y, x+1, y+1);
if (x < sizeX-1 && y > 0) propagate(tickLengthS, x, y, x+1, y-1);
if (x > 0 && y < sizeY-1) propagate(tickLengthS, x, y, x-1, y+1);
}
}
std::swap(newBuffer, oldBuffer);
}
}
void Water::spring(fixed tickLengthS, WaterPoint &point) {
// Hooke's law with euler integration and dampening
fixed x = point.height - fixed(100);
point.acceleration = -tension * x - dampening * point.velocity;
point.height += point.velocity * tickLengthS;
point.velocity += point.acceleration * tickLengthS;
}
void Water::propagate(fixed tickLengthS,
size_t fromX, size_t fromY,
size_t toX, size_t toY) {
WaterPoint &from(point(fromX, fromY)),
&oldTo(point(toX, toY)),
&newTo((*newBuffer)[toY * sizeX + toX]);
fixed delta = spread * (from.height - oldTo.height);
newTo.velocity += delta * tickLengthS;
newTo.acceleration += delta * tickLengthS;
//newTo.height += delta * tickLengthS;
}
|
// Cheng, Allan
// 996078337
#include <iostream>
using namespace std;
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
void findIP(string, char*);
bool searchNext(string, string, int);
int main(int argc, char *argv[])
{
string input;
ifstream IPfile;
IPfile.open(argv[2]);
while (true)
{
IPfile >> input;
if (IPfile.eof())
break;
findIP(input, argv[1]);
}
IPfile.close();
}
void findIP(string find, char *file)
{
string IP, AS, IP2, AS2;
int bit, byte, divide, remainder, count, count2, num, num2, i;
bool match = false, test;
ifstream DB;
DB.open(file);
while(!DB.eof())
{
DB >> IP >> byte >> AS;
count = 0; num = 0;
while(find[count] != IP[count] && !DB.eof()) //until first number of IP match
DB >> IP >> byte >> AS;
count++;
while (find[count] == IP[count] && find[count] != '.')
count++;
if (find[count] != IP[count]) //until first 8 bytes matches since all prefix >8
continue;
divide = (byte/8) - 1; //attempt to find largest prefix match
remainder = byte % 8;
count++;
count2 = count;
while(match == false) //after first 8 bytes match
{
if (divide == 0 && remainder == 0) //everything is matched
{
match = true;
DB >> IP2 >> bit >> AS2;
while( IP2[count-2] == find[count-2])
{
if (searchNext(find, IP2, bit) == true)
{
IP = IP2;
byte = bit;
AS2 = AS;
}
DB >> IP2 >> bit >> AS2;
}
cout << IP << "/" << byte << " " << AS << " " << find << endl;
return;
}
else if (divide == 0) //remainder != 0
{
num = 0;
while (find[count2] != '.' && count2 < find.length()) //convert 2nd 8bits of input to num
{
num *= 10;
num = num + (find[count2] - 48);
count2++;
}
count2 = count;
num2 = 0;
test = false;
while(test == false)
{
count2 = count;
while (IP[count2] != '.' && count2 < IP.length()) //convert into int
{
num2 *= 10;
num2 = num2 + (IP[count2] - 48);
count2++;
}
unsigned int comp1, comp2, prefix;
prefix = 8 - remainder;
comp1 = num >> prefix;
comp2 = num2 >> prefix;
if (comp1 == comp2)
{
match = true;
test = true;
DB >> IP2 >> bit >> AS2;
while( IP2[count-2] == find[count-2] && !DB.eof())
{
if( searchNext(find, IP2, bit) == true)
{
IP = IP2;
byte = bit;
AS2 = AS;
}
DB >> IP2 >> bit >> AS2;
}
cout << IP << "/" << byte << " " << AS << " " << find << endl;
return;
}
else
{
DB >> IP >> byte >> AS;
divide = (byte/8) - 1;
remainder = byte % 8;
count2 = count;
break;
}
}
} //else if
else //divide > 1 - so match next 8 bits
{
while (divide != 0)
{
while (find[count2] == IP[count2] && find[count2] != '.' && count2 < (find.length()-1))
count2++;
if(find[count2] != IP[count2]) //doesn't match
{
if (DB.eof())
break;
DB >> IP >> byte >> AS;
divide = (byte/8) - 1; //attempt to find largest prefix match
remainder = byte % 8;
count2 = count;
break;
}
else //matched 2nd set of 8 bits
{
divide--;
count2++;
}
}
} //else
}
//exit(0);
}
DB.close();
}
bool searchNext(string input, string IP, int bit)
{
int i = 0, temp, prefix, remain, num = 0, num2 = 0;
unsigned int convert, after, after2;
while (input[i] == IP[i] && input[i] != '.')
i++;
if (input[i] != IP[i])
return false;
prefix = (bit / 8) - 1;
remain = bit % 8;
i++;
while (prefix != 0)
{
while (input[i] == IP[i] && input[i] != '.' && (i < input.length()))
i++;
if(input[i] != IP[i])
return false;
else
prefix--;
i++;
}
if (remain != 0)
{
temp = i;
while (input[i] != '.') //convert 2nd 8 byte into int
{
num *= 10;
num = num + (input[i] - 48);
i++;
}
i = temp;
while (IP[i] != '.')
{
num2 *= 10;
num2 = num2 + (IP[i] - 48);
i++;
}
convert = 8 - remain;
after = num >> convert;
after2 = num2 >> convert;
if (after != after2)
return false;
return true;
}
}
|
Farm[] =
{
//Weapons
{Loot_GROUP, 6, shotgunsingleshot},
{Loot_GROUP, 1, Chainsaws},
{Loot_WEAPON, 1, ItemFishingPole},
//Tools
{Loot_VEHICLE, 5, WeaponHolder_ItemHatchet},
{Loot_GROUP, 4, ToolsBuilding},
//Items
{Loot_MAGAZINE, 1, equip_tent_poles},
{Loot_MAGAZINE, 4, ItemSandbag},
{Loot_MAGAZINE, 1, TrapBear},
{Loot_MAGAZINE, 2, PartPlankPack},
{Loot_MAGAZINE, 1, ItemLightBulb},
//Groups
{Loot_GROUP, 10, AmmoCivilian},
{Loot_GROUP, 1, AttachmentsGeneric},
{Loot_GROUP, 8, Consumable},
{Loot_GROUP, 3, ToolsSurvival},
{Loot_GROUP, 1, JerryCan},
{Loot_GROUP, 1, FuelCan},
{Loot_GROUP, 1, FuelBarrel},
{Loot_GROUP, 6, Generic}
};
FarmSmall[] =
{
{Loot_GROUP, 8, pistols},
{Loot_GROUP, 3, ToolsSurvival},
{Loot_GROUP, 3, VanillaSurvival},
{Loot_GROUP, 5, Trash},
{Loot_GROUP, 8, AmmoCivilian},
{Loot_GROUP, 1, AttachmentsGeneric},
{Loot_GROUP, 5, Consumable},
{Loot_GROUP, 5, GenericSmall}
};
|
/*
* terrain_generator.hpp
*
* Created on: 21 Jan 2012
* Author: sash
*/
#ifndef TERRAIN_GENERATOR_HPP_
#define TERRAIN_GENERATOR_HPP_
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <utility>
#include <cmath>
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <limits.h>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filestream.h"
#include "noise/noise.h"
#include "noise/noisegen.h"
#define DEFAULT_CONFIG_FILE "config.json"
#define DEAFULT_TERRAIN_FILE "terrain.txt"
#define DEFAULT_SIZE 512
#define DEFAULT_VORONOI_SIZE 100
#define DEFAULT_SEA_LEVEL 47//0.588 * 126
#define DEAFULT_SAND_LEVEL 0.7 * 126
#define DEFAULT_SNOW_TOP_LEVEL 0.8 * 126
#define DEAFULT_RIVERS_FILE "rivers.txt"
#define DEFAULT_NO_OF_RIVERS 70
#define DEFAULT_MAX_RIVER_BRANCHES 30
#define DEAFULT_SETTLEMENTS_FILE "settlements.txt"
#define DEFAULT_NO_OF_SETTLEMENTS 30
#define DEFAULT_MIN_DISTANCE_BETWEEN_SETTLEMENTS 400
#define DEAFULT_VEGETATION_FILE "vegetation.txt"
#define DEFAULT_NO_OF_VEGETATION 300
#define DEAFULT_ROOT_RADIUS 2
#define DEAFULT_VEGETATION_GENERATIONS 3
#define DEFAULT_CONTOUR_FILE "contour.txt"
#define DEFAULT_CONTOUR_KF_FILE "contour_kf.map"
//#define KF_MAP_DIRECTORY "map/"
#define KF_MAP_DIRECTORY "C:\\Users\\sashman\\kingdomforge\\data\\map\\"
#define LARGE_BACKGROUND_TILE_SIZE 4
int get_val(int x, int y);
int get_sqr_avg(int x, int y, int l);
int get_dia_avg(int x, int y, int l);
int square_diamond();
void voronoi();
void erosion();
void clear_neg();
void normalise_map();
//standard print
void print_map(FILE* stream);
//xml print
void print_map_xml(FILE* stream);
bool point_above_sealevel(int x, int y);
bool point_above_sandlevel(int x, int y);
bool point_below_snow_top_level(int x, int y);
void settlements();
void print_settlements(FILE* stream);
void rivers();
void print_rivers(FILE* stream);
void contour_map(int sub_map_h, int sub_map_w, bool verbose);
void print_contour(FILE* stream);
void print_kf(FILE* stream);
class RiverPoint {
public:
int x;
int y;
int river_id;
RiverPoint* next;
RiverPoint* branch;
RiverPoint(int x_, int y_, int river_id_) {
x = x_;
y = y_;
river_id = river_id_;
next = 0;
branch = 0;
}
~RiverPoint() {
//delete next;
}
};
void vegetation(bool verbose);
void print_vegetation(FILE* stream);
//Definition of tile types 1
//=====================
// IMPORTANT: Do not change the order of the enums!
//=====================
enum TILE_CASE {
//Misc (not real types)
HIGH_GRASS,
//convex cliff corners
CLIFF_NW_SN, //north -> west turn, south->north increasing incline
CLIFF_NE_SN, //north -> east turn, south->north increasing incline
/*
* lower | higher
* lower \______
* lower lower
*/
CLIFF_SE_NS, //south -> east turn, north->south incline
CLIFF_SW_NS,
//concave cliff corners
CLIFF_SE_SN, //south -> east corner, south->north incline
/*
* higher
* higher ____
* /
* higher | lower
*/
CLIFF_SW_SN,
CLIFF_NW_NS,
CLIFF_NE_NS,
//cliff straights
CLIFF_WE_SN,
CLIFF_NS_WE,
CLIFF_WE_NS,
CLIFF_NS_EW, //along north->south, east->west increasing incline
//other
GRASS,
WATER
//count
,
TILE_COUNT
};
#endif /* TERRAIN_GENERATOR_HPP_ */
|
/*
* Copyright (c) 2001, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
* $Id: delif.c,v 1.1 2001/12/12 10:02:27 adam Exp $
*/
#include "lwip/debug.h"
#include <stdlib.h>
#include "lwip/def.h"
#include "netif/delif.h"
#ifdef linux
#include "netif/tapif.h"
#else /* linux */
#include "netif/tunif.h"
#endif /* linux */
#include "lwip/sys.h"
#define DELIF_INPUT_DROPRATE 0.1
#define DELIF_OUTPUT_DROPRATE 0.1
#define DELIF_INPUT_DELAY 500 /* Miliseconds. */
#define DELIF_OUTPUT_DELAY 500 /* Miliseconds. */
#define DELIF_TIMEOUT 10
struct delif {
err_t (* input)(struct pbuf *p, struct netif *inp);
struct netif *netif;
};
struct delif_pbuf {
struct delif_pbuf *next;
struct pbuf *p;
struct ip_addr *ipaddr;
unsigned int time;
};
static struct delif_pbuf *input_list = NULL;
static struct delif_pbuf *output_list = NULL;
/*-----------------------------------------------------------------------------------*/
static void
delif_input_timeout(void *arg)
{
struct netif *netif;
struct delif *delif;
struct delif_pbuf *dp;
unsigned int timeout, now;
timeout = DELIF_TIMEOUT;
netif = arg;
delif = netif->state;
/* Check if there is anything on the input list. */
dp = input_list;
while(dp != NULL) {
now = sys_now();
if(dp->time <= now) {
delif->input(dp->p, netif);
if(dp->next != NULL) {
if(dp->next->time > now) {
timeout = dp->next->time - now;
} else {
timeout = 0;
}
DEBUGF(DELIF_DEBUG, ("delif_output_timeout: timeout %u.\r", timeout));
}
input_list = dp->next;
free(dp);
dp = input_list;
} else {
dp = dp->next;
}
}
sys_timeout(timeout, delif_input_timeout, arg);
}
/*-----------------------------------------------------------------------------------*/
static void
delif_output_timeout(void *arg)
{
struct netif *netif;
struct delif *delif;
struct delif_pbuf *dp;
unsigned int timeout, now;
timeout = DELIF_TIMEOUT;
netif = arg;
delif = netif->state;
/* Check if there is anything on the output list. */
dp = output_list;
while(dp != NULL) {
now = sys_now();
if(dp->time <= now) {
DEBUGF(DELIF_DEBUG, ("delif_output_timeout: now %u dp->time %u\r",
now, dp->time));
delif->netif->output(delif->netif, dp->p, dp->ipaddr);
if(dp->next != NULL) {
if(dp->next->time > now) {
timeout = dp->next->time - now;
} else {
timeout = 0;
}
DEBUGF(DELIF_DEBUG, ("delif_output_timeout: timeout %u.\r", timeout));
}
pbuf_free(dp->p);
output_list = dp->next;
free(dp);
dp = output_list;
} else {
dp = dp->next;
}
}
sys_timeout(timeout, delif_output_timeout, arg);
}
/*-----------------------------------------------------------------------------------*/
static err_t
delif_output(struct netif *netif, struct pbuf *p, struct ip_addr *ipaddr)
{
struct delif_pbuf *dp, *np;
struct pbuf *q;
int i, j;
char *data;
DEBUGF(DELIF_DEBUG, ("delif_output\r"));
#ifdef DELIF_OUTPUT_DROPRATE
if(((double)rand()/(double)RAND_MAX) < DELIF_OUTPUT_DROPRATE) {
DEBUGF(DELIF_DEBUG, ("delif_output: Packet dropped\r"));
return 0;
}
#endif /* DELIF_OUTPUT_DROPRATE */
DEBUGF(DELIF_DEBUG, ("delif_output\r"));
dp = malloc(sizeof(struct delif_pbuf));
data = malloc(p->tot_len);
i = 0;
for(q = p; q != NULL; q = q->next) {
for(j = 0; j < q->len; j++) {
data[i] = ((char *)q->payload)[j];
i++;
}
}
dp->p = pbuf_alloc(PBUF_LINK, 0, PBUF_ROM);
dp->p->payload = data;
dp->p->len = p->tot_len;
dp->p->tot_len = p->tot_len;
dp->ipaddr = ipaddr;
dp->time = sys_now() + DELIF_OUTPUT_DELAY;
dp->next = NULL;
if(output_list == NULL) {
output_list = dp;
} else {
for(np = output_list; np->next != NULL; np = np->next);
np->next = dp;
}
return ERR_OK;
}
/*-----------------------------------------------------------------------------------*/
static err_t
delif_input(struct pbuf *p, struct netif *inp)
{
struct delif_pbuf *dp, *np;
DEBUGF(DELIF_DEBUG, ("delif_input\r"));
#ifdef DELIF_INPUT_DROPRATE
if(((double)rand()/(double)RAND_MAX) < DELIF_INPUT_DROPRATE) {
DEBUGF(DELIF_DEBUG, ("delif_input: Packet dropped\r"));
pbuf_free(p);
return ERR_OK;
}
#endif /* DELIF_INPUT_DROPRATE */
dp = malloc(sizeof(struct delif_pbuf));
dp->p = p;
dp->time = sys_now() + DELIF_INPUT_DELAY;
dp->next = NULL;
if(input_list == NULL) {
input_list = dp;
} else {
for(np = input_list; np->next != NULL; np = np->next);
np->next = dp;
}
return ERR_OK;
}
/*-----------------------------------------------------------------------------------*/
void
delif_init(struct netif *netif)
{
struct delif *del;
del = malloc(sizeof(struct delif));
netif->state = del;
netif->name[0] = 'd';
netif->name[1] = 'e';
netif->output = delif_output;
del->netif = malloc(sizeof(struct netif));
#ifdef linux
/* tapif_init(del->netif);*/
tunif_init(del->netif);
#else /* linux */
tunif_init(del->netif);
#endif /* linux */
del->input = netif->input;
del->netif->input = delif_input;
sys_timeout(DELIF_TIMEOUT, delif_input_timeout, netif);
sys_timeout(DELIF_TIMEOUT, delif_output_timeout, netif);
}
/*-----------------------------------------------------------------------------------*/
static void
delif_thread(void *arg)
{
struct netif *netif = arg;
struct delif *del;
sys_sem_t sem;
del = netif->state;
#ifdef linux
tapif_init(del->netif);
#else /* linux */
tunif_init(del->netif);
#endif /* linux */
sys_timeout(DELIF_TIMEOUT, delif_input_timeout, netif);
sys_timeout(DELIF_TIMEOUT, delif_output_timeout, netif);
sem = sys_sem_new(0);
sys_sem_wait(sem);
}
/*-----------------------------------------------------------------------------------*/
void
delif_init_thread(struct netif *netif)
{
struct delif *del;
DEBUGF(DELIF_DEBUG, ("delif_init_thread\r"));
del = malloc(sizeof(struct delif));
netif->state = del;
netif->name[0] = 'd';
netif->name[1] = 'e';
netif->output = delif_output;
del->netif = malloc(sizeof(struct netif));
del->netif->ip_addr = netif->ip_addr;
del->netif->gw = netif->gw;
del->netif->netmask = netif->netmask;
del->input = netif->input;
del->netif->input = delif_input;
sys_thread_new(delif_thread, netif);
}
/*-----------------------------------------------------------------------------------*/
|
// 快速排序.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
#include<vector>
#include<random>
#include<algorithm>
void bubsort(vector<int>& a, int len) {
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (a[j] > a[j + 1]) swap(a[j], a[j + 1]);
}
}
}
void printfvec(const vector<int> a) {
for (auto it = a.begin(); it != a.end(); it++) {
cout << *it << ' ';
}
cout << endl;
}
int main()
{
vector<int> test;
for (int i = 0; i < 20; i++) {
test.push_back(rand() % 100);
}
printfvec(test);
bubsort(test, test.size());
printfvec(test);
return 0;
}
|
#include <iostream>
#include <type_traits>
namespace rd
{
namespace ch2
{
/*
* Imagine that we are implementing the std library. A std::iter_swap
* needs to be added to <algorithm>.
*
* see: http://en.cppreference.com/w/cpp/algorithm/iter_swap
*/
/* we start with a naive implementation */
template <class ForwardIterator1, class ForwardIterator2>
void iter_swap0(ForwardIterator1 i1, ForwardIterator2 i2)
{
typename ForwardIterator1::value_type x = *i1;
*i1 = *i2;
*i2 = x;
}
// here's a ForwardIterator type which can be used with the above fcn
// I'm going to make a weird kind of iterator which owns the T
template <class T>
class ForwardIterator
{
T* ref;
public:
using value_type = T; // typedef for consistency
using reference = T&; // typedef for consistency
ForwardIterator(T* t): ref(t) {} // ctor
T& operator*() // deref operator
{
// std::cout << "ref is: " << ref << std::endl;
return *ref;
}
};
/* the above implementation has a problem: if iter_swap0 is given a pointer
* instead of an iterator type, a compile-time error is generated since the
* pointer type does not have a value_type member type
*/
/* we try to resolve this by introducing a traits class for iterators */
template <class Iterator> struct iterator_traits;
template <class ForwardIterator1, class ForwardIterator2>
void iter_swap1(ForwardIterator1 f1, ForwardIterator2 f2)
{
typename iterator_traits<ForwardIterator1>::value_type x = *f1;
*f1 = *f2;
*f2 = x;
}
/* non-intrusively define an iterator_traits specialization */
// template<class T>
// struct iterator_traits<ForwardIterator<T>>
// {
// using value_type = typename ForwardIterator<T>::value_type;
// };
/* another iterator_traits specialization for raw pointers */
template<class T>
struct iterator_traits<T*>
{
using value_type = T;
using reference = T&;
};
/* a shortcut: using the template definition to auto-connect the value_type
* in any iterator base types to the value_type in the traits class
*/
template <class Iterator>
struct iterator_traits
{
using value_type = typename Iterator::value_type;
using reference = typename Iterator::reference;
};
// The type-traits class defined above is used like a function, but at
// compile-time. We call these things "metafunctions".
// However, type-traits models the "Blob" pattern where a set of vaguely
// related types are grouped into a single class, impeding composability.
//
// It would be nicer to use separate metafunctions for this instead.
// Boost-based metafunctions will have a single "foo::type" member type
// which is considered to be the "return value" of the metafunction.
//
// Additionally, if we want to get the numerical value of a integer constant
// wrapper, we can use the "foo::type::value" member. Sometimes however, a
// "foo::value" member can give you the right numerical value (true for all
// boost numerical metafunctions).
/* 2.4 making choices at compile-time
* iter_swap is slow since it doesn't call std::swap(T, T), which needs two
* parameters of the same type as input.
*/
// add specialization of iter_swap1 which calls std::swap
template <class ForwardIterator>
void iter_swap1(ForwardIterator f1, ForwardIterator f2)
{
std::swap(*f1, *f2);
}
// the problem with the above is that it doesn't work with different types
// that have the same value::type (and should therefore be std::swap()-able)
template <bool use_std_swap> struct iter_swap2_impl; // fwd-define swap's impl
template <class ForwardIterator1, class ForwardIterator2>
void iter_swap2(ForwardIterator1 f1, ForwardIterator2 f2)
{
using value_type1 = typename iterator_traits<ForwardIterator1>::value_type;
using value_type2 = typename iterator_traits<ForwardIterator2>::value_type;
using reference1 = typename iterator_traits<ForwardIterator1>::reference;
using reference2 = typename iterator_traits<ForwardIterator2>::reference;
// select impl based on equality of value_types and if reference types are
// real reference types (rather than proxies)
bool const use_std_swap = std::is_same<value_type1, value_type2>::value
&& std::is_reference<reference1>::value
&& std::is_reference<reference2>::value;
// try using a type computation instead??
// using use_std_swap = std::is_same<value_type1, value_type2>::type;
// shell out to the impl, use specialization to select the correct one
iter_swap2_impl<use_std_swap>::do_swap(f1, f2);
}
template <>
struct iter_swap2_impl<false>
{
template <class ForwardIterator1, class ForwardIterator2>
static void do_swap(ForwardIterator1 f1, ForwardIterator2 f2)
{
typename iterator_traits<ForwardIterator1>::value_type x = *f1;
*f1 = *f2;
*f2 = x;
}
};
template <>
struct iter_swap2_impl<true>
{
template <class ForwardIterator1, class ForwardIterator2>
static void do_swap(ForwardIterator1 f1, ForwardIterator2 f2)
{
std::swap(*f1, *f2);
}
};
}
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
int a[50010],p[50010];
int t[50010],n;
int lowbit(int k) {
return k&(-k);
}
void add(int k,int x) {
while (k <= n) {
t[k] += x;
k += lowbit(k);
}
}
int query(int k) {
int ans = 0;
while (k >= 1) {
ans += t[k];
k -= lowbit(k);
}
return ans;
}
int find(int k) {
int ans = 0;
for (int i = 15;i >= 0;i--) {
int ns = ans + (1 << i);
if (ns > n) continue;
if (query(ns) < k) ans = ns;
if (query(ns) == k && query(ns-1) == k-1) {
ans = ns;
break;
}
}
add(ans,-1);
return n+1-ans;
}
int main() {
int t;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
for (int i = 1;i <= n; i++) {
scanf("%d",&a[i]);
add(i,1);
}
for (int i = n;i >= 1; i--) {
int loc = a[i] - a[i-1]+1;
p[i] = find(loc);
}
for (int i = 1;i < n; i++) printf("%d ",p[i]);
printf("%d\n",p[n]);
}
return 0;
}
|
#include <iostream>
#include <string>
bool checkTime(int hour, int minute) {
if(0 <= hour && 12 >= hour && 0 <= minute && 60 >= minute) {
return true;
} else {
return false;
}
}
int main() {
int startHour = 0;
int startMinute = 0;
int endHour = 0;
int endMinute = 0;
int count = 0;
char jam1[5];
char jam2[5];
std::string string2;
std::cout<<"Jam@ mutqagrel hetevyal tesqov. orinak 04:20 \n";
std::cout<<"Mutqagrel skselu jam@ ->";
std::cin>>jam1;
std::cout<<"Mutqagrel avarti jam@ ->";
std::cin>>jam2;
startHour =((int)jam1[0] - (int)'0') * 10 + (int)jam1[1]-(int)'0';
startMinute = ((int)jam1[3] - (int)'0') * 10 + (int)jam1[4] - (int)'0';
endHour =((int)jam2[0] - (int)'0')* 10 + (int)jam2[1] - (int)'0';
endMinute = ((int)jam2[3] - (int)'0') * 10 + (int)jam2[4] - (int)'0';
if(true == checkTime(startHour, startMinute) && true == checkTime(endHour, endMinute)) {
if(startHour > endHour ) {
std::cout<<"Chi znga \n";
} else {
if(7 >= startMinute){
count++;
}
if(7 > endMinute) {
count--;
}
count = count + (endHour - startHour) * 2;
std::cout<<"Kznga "<<count<<" angam \n";
}
} else {
std::cout<<"Sxal mutqagrum \n";
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; 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.
*/
#ifndef OPACCESSIBILITYMANAGER_H
#define OPACCESSIBILITYMANAGER_H
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
#include "modules/pi/OpAccessibilityAdapter.h"
#include "modules/accessibility/accessibilityenums.h"
class OpAccessibleItem;
class AccessibilityManager
{
public:
static AccessibilityManager* GetInstance();
OP_STATUS SendEvent(OpAccessibleItem* sender, Accessibility::Event evt);
OpAccessibilityAdapter* GetAdapterForAccessibleItem(OpAccessibleItem* accessible_item, BOOL create_new = TRUE);
void AccessibleItemRemoved (const OpAccessibleItem* accessible_item);
private:
AccessibilityManager() {}
~AccessibilityManager() {}
AccessibilityManager(const AccessibilityManager&);
AccessibilityManager& operator=(const AccessibilityManager&);
OpPointerHashTable<const OpAccessibleItem, OpAccessibilityAdapter> m_item_adapters;
};
#endif //ACCESSIBILITY_EXTENSION_SUPPORT
#endif //OPACCESSIBILITYMANAGER_H
|
#include<iostream>
#include<algorithm>
#include<vector>
#include<sstream>
using namespace std;
class Solution {
public:
string reverseWords(string s) {
//基本思想:暴力法
//s的第一个单词前面填补一个空格,使得翻转后第一个单词与第二个单词间存在空格
if (s[0] != ' ')
s.insert(0, 1, ' ');
string res;
int i = s.size() - 1, pos;
//从后往前遍历字符串s
while (i >= 0)
{
//遇到单词,将空格+该单词拼接到res,使得每个单词间存在空格
if (s[i] != ' ')
{
pos = i;
while (i >= 0 && s[i] != ' ')
i--;
res += s.substr(i, pos - i + 1);
}
i--;
}
//去掉多的一个空格
if (res[0] == ' ')
res.erase(0, 1);
return res;
}
};
class Solution1 {
public:
string reverseWords(string s) {
//基本思想:用stringstream做
istringstream words(s); //words保存s的一个拷贝
string res, word;
//从流words中读取单词
while (words >> word)
{
res = " " + word + res;
}
//去掉多的一个空格
if (res[0] == ' ')
res.erase(0, 1);
return res;
}
};
int main()
{
Solution1 solute;
string s = "the sky is blue";
cout << solute.reverseWords(s) << endl;
return 0;
}
|
/*
多项式四则
2016.10.19 by kkcckc
*/
#include "multi.h"
void main()
{
int flag;
double x;
mult *head1,*head2;
//hint();
FILE *fp=NULL;
if ((fp=fopen(IPATH,"r"))<0) {cout<<"无法打开输入文件";exit(0);};
ofstream fpp(OPATH,ios::out);
if (!fpp) exit(0);
streambuf *oldbuf = cout.rdbuf(fpp.rdbuf());
fscanf(fp,"%d",&flag);
if (!flag)
{
make (head1);
input (head1,fp);
fscanf(fp,"%lf",&x);
compute(head1,x);
}
else
{
make (head1);make(head2);
input(head1,fp);input(head2,fp);
all_output(head1,head2);
}
fclose(fp);
cout.rdbuf(oldbuf);
fpp.close();
}
|
/*
ReadAnalogVoltage
The ESP8266EX(Which IC D1 board used) integrates a generic purpose 10-bit analog ADC. The ADC range is from 0V to 1.0V
And on the board, we use following circuit:
-----A0
|
220K
|--- ADC
100K
|
GND
so,the input voltage(A0) can be 3.2V, and the A0=3.2*ADC
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 115200 bits per second:
Serial.begin(115200);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 3.2V):
float voltage = sensorValue * (3.2 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
|
#ifndef DNDSEQUENCE_DUP_H
#define DNDSEQUENCE_DUP_H
#include "Icommand.h"
class Dup:public Icreate
{
public:
/*virtual*/~Dup(){}
std::string run(Iwriter &writer, Ireader& reader, dataDNA& containerDna, const Paramcommand& obj);
private:
bool isValid(const Paramcommand& obj);
std::string print(Iwriter& writer, dataDNA& containerDna);
Dna* dup(dataDNA&containerDna, const Paramcommand¶m, size_t idDna);
};
#endif //DNDSEQUENCE_DUP_H
|
#include <iostream>
#include <string>
int main() {
float num1;
char symbal;
float num2;
std::cin>> num1 >> symbal >> num2;
std::cout <<num1<< std::endl;
if (symbal == '+') {
std::cout<< num1 + num2<<std::endl;
} else if (symbal == '-') {
std::cout << num1 - num2;
} else if (symbal == '*') {
std::cout << num1 * num2;
} else if (symbal == '/') {
std::cout <<num1 / num2;
} else {
std::cout << "sxal";
}
return 0;
}
|
#include "Firebase_Client_Version.h"
#if !FIREBASE_CLIENT_VERSION_CHECK(40319)
#error "Mixed versions compilation."
#endif
/**
* Google's Firebase QueryFilter class, QueryFilter.cpp version 1.0.7
*
* This library supports Espressif ESP8266 and ESP32
*
* Created December 19, 2022
*
* This work is a part of Firebase ESP Client library
* Copyright (c) 2023 K. Suwatchai (Mobizt)
*
* The MIT License (MIT)
* Copyright (c) 2023 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "FirebaseFS.h"
#ifdef ENABLE_RTDB
#ifndef FIREBASE_QUERY_FILTER_CPP
#define FIREBASE_QUERY_FILTER_CPP
#include "QueryFilter.h"
QueryFilter::QueryFilter()
{
}
QueryFilter::~QueryFilter()
{
clear();
}
QueryFilter &QueryFilter::clear()
{
_orderBy.clear();
_limitToFirst.clear();
_limitToLast.clear();
_startAt.clear();
_endAt.clear();
_equalTo.clear();
return *this;
}
QueryFilter &QueryFilter::mOrderBy(MB_StringPtr val)
{
_orderBy = (const char *)MBSTRING_FLASH_MCR("\"");
_orderBy += val;
_orderBy += (const char *)MBSTRING_FLASH_MCR("\"");
return *this;
}
QueryFilter &QueryFilter::mLimitToFirst(MB_StringPtr val)
{
_limitToFirst = val;
return *this;
}
QueryFilter &QueryFilter::mLimitToLast(MB_StringPtr val)
{
_limitToLast = val;
return *this;
}
QueryFilter &QueryFilter::mStartAt(MB_StringPtr val, bool isString)
{
if (isString)
_startAt = (const char *)MBSTRING_FLASH_MCR("\"");
_startAt += val;
if (isString)
_startAt += (const char *)MBSTRING_FLASH_MCR("\"");
return *this;
}
QueryFilter &QueryFilter::mEndAt(MB_StringPtr val, bool isString)
{
if (isString)
_endAt = (const char *)MBSTRING_FLASH_MCR("\"");
_endAt += val;
if (isString)
_endAt += (const char *)MBSTRING_FLASH_MCR("\"");
return *this;
}
QueryFilter &QueryFilter::mEqualTo(MB_StringPtr val, bool isString)
{
if (isString)
_equalTo = (const char *)MBSTRING_FLASH_MCR("\"");
_equalTo += val;
if (isString)
_equalTo += (const char *)MBSTRING_FLASH_MCR("\"");
return *this;
}
#endif
#endif //ENABLE
|
/*
* ProgrammersFirst.h
*
* Created on: 2021. 9. 8.
* Author: dhjeong
*/
#ifndef PROGRAMMERSFIRST_H_
#define PROGRAMMERSFIRST_H_
#include <iostream>
#include <vector>
#include <map>
#include <utility>
using namespace std;
class Level1 {
public:
Level1();
virtual ~Level1();
void run() {
std::vector<string> participant;
std::vector<string> completion;
// ["leo", "kiki", "eden"] ["eden", "kiki"] "leo"
// ["marina", "josipa", "nikola", "vinko", "filipa"] ["josipa", "filipa", "marina", "nikola"] "vinko"
// ["mislav", "stanko", "mislav", "ana"] ["stanko", "ana", "mislav"]
participant.push_back("leo");
participant.push_back("kiki");
participant.push_back("eden");
completion.push_back("eden");
completion.push_back("kiki");
printf("%s\n", solution(participant, completion).c_str());
participant.clear();
completion.clear();
participant.push_back("marina");
participant.push_back("josipa");
participant.push_back("nikola");
participant.push_back("vinko");
participant.push_back("filipa");
completion.push_back("josipa");
completion.push_back("filipa");
completion.push_back("marina");
completion.push_back("nikola");
printf("%s\n", solution(participant, completion).c_str());
participant.clear();
completion.clear();
participant.push_back("mislav");
participant.push_back("stanko");
participant.push_back("mislav");
participant.push_back("ana");
completion.push_back("stanko");
completion.push_back("ana");
completion.push_back("mislav");
printf("%s\n", solution(participant, completion).c_str());
}
string solution(vector<string>& participant, vector<string>& completion) {
string answer = "";
map<string, int> pMap;
map<string, int> cMap;
for (unsigned int i = 0; i < participant.size(); i++) {
if (pMap.find(participant[i]) != pMap.end()) {
pMap.find(participant[i])->second++;
} else {
pMap.insert(make_pair(participant[i], 1));
}
}
for (unsigned int i = 0; i < completion.size(); i++) {
if (pMap.find(completion[i]) != pMap.end()) {
pMap.find(completion[i])->second--;
if (pMap.find(completion[i])->second == 0) {
pMap.erase(completion[i]);
}
}
}
answer = pMap.begin()->first;
return answer;
}
};
#endif /* PROGRAMMERSFIRST_H_ */
|
#include <string>
#include <cstdio>
// Table of frequency characters
int Frequency[26];
int hashFunc(char c)
{
return (c-'a');
}
void countFre(string S)
{
for(int i = 0; i < S.length(); ++i)
{
int index = hashFunc(S[i]);
Frequency[index]++;
}
for(int i = 0; i<26;++i)
{
std::cout<< (char)(i+'a')<< ' ' << Frequency[i] << std::endl;
}
}
std::vector <string> hashTable_string[20];
int hashTablesize = 20;
void insert(string s)
{
int index = hashFunc(s);
hashTable_string[index].push_back(s);
}
void search(string s)
{
int index = hashFunc(s);
for(int i = 0; i < hashTable_string[index].size(); ++i)
{
if(hashTable_string[index][i] == s)
{
std::cout<< "is found" << std::endl;
return;
}
}
std::cout<< "is not found" << std::endl;
}
int main(){
return 0;
}
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include "lexer.h"
//#include "lexer.cc"// may need to be included to run properly on some compilers...
#define MAX_TEXT_LINE_LENGTH 128
using namespace std;
int main (int argc, char* argv[])
{
int task;
if (argc < 2)
{
cout << "Error: missing argument\n";
return 1;
}
LexicalAnalyzer lexer;
///////////Holds first two lines////////
Token terminals[255];
Token NonTerms[255];
////////////////////////////////////////
Token lines[255][255];
////////////////////////Task 1///////////////////
string Tnames[255];
string Terms[255];
int occ[255];
memset (occ,-1,255);
////////////////////////////////////////////////
int nolines= 0;
int termIt = 0,b = 0, c = 0;
Terms[c]="!";
//cout<<Terms[c]<<" ";
c++;
while(terminals[b].token_type != HASH){
terminals[termIt] = lexer.GetToken();
//terminals[a].Print();
////task 1/////////////
if(terminals[termIt].token_type == ID){
Tnames[c] = terminals[termIt].lexeme;
Terms[c] = terminals[termIt].lexeme;
occ[c]= 0;
//cout<<Terms[c]<<" ";
c++;
}
////////////////////
termIt++;
b = termIt - 1;
}
int numTerms = c;
//cout<<termIt<<" "<<c<<endl;
//cout<<endl;
b = 0;
int numNons = 0;
while(NonTerms[b].lexeme != "#"){
NonTerms[numNons] = lexer.GetToken();
//NonTerms[a].Print();
/////task 1//////////
// if(terminals[b].token_type == ID && NonTerms[numNons].lexeme.length() > 0){
Tnames[c] = NonTerms[numNons].lexeme;
occ[c] = 0;
//cout<<Tnames[c]<<" ";
c++;
// }
/////////////////////
if(NonTerms[numNons].token_type == HASH)
{
break;
}
numNons++;
b = numNons - 1;
}
//cout<<endl;
//cout<<"--Lines--"<<endl;
int a = 0;
b = 0;
int row = 0, pos = 0;
bool disc[c];
while(lines[row][pos].token_type != DOUBLEHASH){
memset(disc,false,c);
pos = 0;
while(1)
{
lines[row][pos] = lexer.GetToken();
//lines[row][pos].Print();
if(lines[row][pos].token_type == HASH){
if(pos == 2)
{
lines[row][pos].lexeme = "!";
lines[row][pos].token_type = ID;
lines[row][pos+1].lexeme = "#";
lines[row][pos+1].token_type = HASH;
//cout<<lines[row][pos].lexeme<<" ";
break;
}
else
{
break;
}
}
//cout<<lines[row][pos].lexeme<<" ";
/////////////////task 1///////////////////////
int found = 0;
while(found < c)
{
if(lines[row][pos].lexeme.compare(Tnames[found]) == 0)
{
disc[found] = true;
break;
}
found++;
}
////////////////////////////////////
pos++;
}
//cout<<endl;
int z = 0;
while(z<=c){
if(disc[z] == true){
occ[z]++;
}
z++;
}
z=0;
row++;
nolines++;
lines[row][pos] = lexer.GetToken();
if(lines[row][pos].token_type == DOUBLEHASH){
break;
}
else
{
lexer.UngetToken(lines[row][pos]);
}
//cout<<endl;
}
int numRows = row;
bool reachable[c];
memset(reachable,false,c);
//string first[numNons][255];
//string follow[numNons][255];
bool first[numNons][numTerms];
bool follow[numNons][numTerms];
int fillr = 0;
while(fillr<numNons){
int fillc = 0;
while(fillc<numTerms){
first[fillr][fillc] = false; //Easy delim to set for this proj
follow[fillr][fillc] = false;
fillc++;
}
fillr++;
}
bool changed = true;
//cout<<lines[0][0].lexeme<<endl;
//cout<<lines[0][1].lexeme<<endl;
//cout<<lines[0][2].lexeme<<endl;
//cout<<lines[0][3].lexeme<<endl;
///////////First///////////////////
//////////////
string Nons[numNons];
int nn = 0;
int loc = 0;
//////////////////////////////////
while(nn<numNons)
{
Nons[nn] = Tnames[numTerms+nn];
nn++;
}
//cout<<strlen(lines[0][0].lexeme.c_str())<<endl;
/////////////
int curr = 0;
int ran = 0;
//////////////START OF FIRST/////////////////
/////////////////////////////////////////////
/////////////////////////////////////////////
while(changed == true)
{
ran++;
curr = 0;
changed = false;
while(curr < numRows){
//changed = false;
///////////////////find location//////////////////
int x=0;
/////////////////////////////vvv takes care of multiple non term rules on diff lines
while(x < numNons)
{
if(lines[curr][0].lexeme == Nons[x])
{
loc = x;
break;
}
x++;
}
//////////////////////////////////////////////////////////////////
// cout<<Nons[loc]<<" "<<lines[curr][0].lexeme<<endl;
/////////////////////////////////////////////////
bool eps = true;
int epos = 0;
while(eps == true)
{
eps = false;
bool isterm = false;
int tcheck;
for(tcheck = 0; tcheck < numTerms;tcheck++) //Find terminal
{
if(lines[curr][ 2 + epos].lexeme == Terms[tcheck])
{
//cout<<lines[curr][2+epos].lexeme<<" "<<Terms[tcheck]<<endl;
isterm = true;
break;
}
}
if(isterm == true) //////////////////CHECKS 4 TERMINAL
{
//cout<<"IS TERM"<<endl;
if(first[loc][tcheck]!= true)
{
first[loc][tcheck] = true;
changed = true;
}
}
/////////////////////////////////////////////////////////////////
///////////////////NON NON NON NON NON NON////////////////////////
else
{
// cout<<"NON TERM"<<endl;
/////////////////find location of first letter
int xx = 0;
int loc2;
while(xx < numNons)
{
if(lines[curr][ 2 + epos ].lexeme == Nons[xx])
{
loc2 = xx;
break;
}
xx++;
}
////////////////////////////////
///////////////////////////////////////////////////////////////////
for(int y = 1; y < numTerms; y++){
if(first[loc2][y]== true){
if(first[loc][y]!= true){
first[loc][y]=true;
changed = true;
}
}
}
///////////////////////////
if(first[loc2][0] == true){ //if there is epsilon
if(lines[curr][ 2 + epos + 1 ].token_type != ID ){ //check next empty
// cout<<"eend: "<<lines[curr][ 2 + epos + 1 ].lexeme << endl;
if(first[loc][0] != true){
first[loc][0] = true;
changed = true;
}
}
else{ //if not empty move on
epos++;
eps = true;
//cout<<"epstrue: "<< epos << lines[curr][ 2 + epos + 1 ].lexeme <<endl;
}
/////////////////
}
}
}//EPS
curr++;
}
//break;
if(ran>0)
{
//break;
}
}
//cout<<"ran: "<<ran<<endl;
/////////////////////////////////////////
/////////////////FOLLOW//////////////////
follow[0][0] = true; // sets S follow to $ for beginning
bool changef = true;
while(changef == true)
{
int curf = 0;
changef = false;
while(curf < numNons){ //GO through all the Non terminals ie/ SABC
/////////////////////////find curf(current) letter
//cout<<endl;
for(int i = 0;i < numRows;i++) // goes through lines
{
for(int j = 2; lines[i][j].token_type != HASH;j++) // searches line
{
//cout<<"NON Term: "<<Nons[curf]<<" Line:"<<lines[i][j].lexeme;
if(Nons[curf] == lines[i][j].lexeme)
{
//cout<<" match ";
bool epsf = true;
int eposf = 0;
while (epsf == true){
epsf = false;
bool ist = false;
int pp = 0, locf;
// while(pp < numNons) ////check if the follow is a Non terminal
while(pp < numTerms)
{
//if(lines[i][j+1].lexeme == Nons[pp])
//cout<<lines[i][j+1+eposf].lexeme << Terms[pp]<< " ";
if(lines[i][j+1+eposf].lexeme == Terms[pp])
{
//cout<<"found: "<<lines[i][j+1+eposf].lexeme<<endl;
ist = true;
locf = pp;
break;
}
pp++;
}
if(ist == true)
{
//////////add Terminal to follow/////////////
if(follow[curf][locf] != true)
{
//cout<<"adding: "<<Terms[locf]<<endl;
follow[curf][locf] = true;
changef = true;
}
}
else // check NON TERMINAL
{
///////////add first to follow///////////////////////
///////////then check for epsilon////////////////////
//////////finds letters position in first array
bool isNonf = false;
int xy = 0;
int locf2;
while(xy < numNons)
{
//if(lines[curf][ 2 + eposf ].lexeme == Nons[xy])
if(lines[i][j+1+eposf].lexeme == Nons[xy])//if the one after the match is a non
{
locf2 = xy; //gives location of non
isNonf = true;
break;
}
xy++;
}
if(isNonf == true)
{
//cout<<"NON ADD FIRST"<<endl;
////////////////////////////////
//////adds to follow array//////
for(int y = 1; y < numTerms; y++){ // starts at y=1 because of epsilon
if(first[locf2][y] == true){
if(follow[curf][y]!= true){
//cout<<"true"<<endl;
follow[curf][y]=true;
changef = true;
}
}
}
/////////////////////////////////////////////////////////////////
if(first[locf2 + eposf][0] == true)
{
epsf = true;
eposf++;
}
}
else
{
int folLoc;
// cout<<"add follow to follow"<<endl;
for(int y = 0; y < numNons; y++){// for finding location of the NOn term letter
if(lines[i][0].lexeme == Nons[y])//because it was the eol, add follow to follow
{
folLoc = y; //gives location of
break;
}
}
// cout<<folLoc;
for(int y = 0; y < numTerms; y++){ // starts at y=1 because of epsilon
if(follow[folLoc][y] == true){
if(follow[curf][y]!= true){
//cout<<"true"<<endl;
follow[curf][y]=true;
changef = true;
}
}
}
}
}
}////whjle eps == true
}
//cout<<endl;
}
}
curf++;
}
}
//////////////////////////////useless gramar
bool used[numRows];
bool changedU = true;
bool nonsU[numNons];
bool startU = false;
bool usedinS[numNons];
while (changedU == true)
{
changedU = false;
int curU = 0;
changedU = false;
string start = lines[0][0].lexeme;
for(int i = 0;i < numRows;i++) // goes through lines
{
//cout<<"loop"<<endl;
if(lines[i][0].lexeme==start)
{
}
for(int j = 2; lines[i][j].token_type != HASH && lines[i][j].token_type == ID; j++) // searches line
{///////checks each indv line
bool isterm = false, isNon = false;
for(int a = 0; a<numTerms; a++)// check Term
{
if(lines[i][j].lexeme == Terms[a])
{
isterm = true;
if(lines[i][j+1].token_type == HASH &&used[i]!= true ) //check if its a one line term
{
used[i] = true; //line is accepted
changedU = true;
if(lines[i][j].lexeme==start)
{
startU = true;
}
}
//continue; //passed test
}
}
for(int a = 0; a<numNons; a++)// check NON
{
if(lines[i][j].lexeme == Nons[a])
{
if(nonsU[a] == true)
{ //checked if the Non terminates
isNon = true;//nonsU has to be true, otherwise NON can be useless...
if(lines[i][j+1].token_type == HASH && used[i]!= true)
{//and if its the end of the line accept it
used[i] = true; //line is accepted
changedU = true;
if(lines[i][j].lexeme==start)
{
startU = true;
}
}
}
}
}
if(isNon == false && isterm == false)
{
break; //end the line
}
}
}
// curU++;
//}
///////////ADD USELESS GRAMAR
}
////////////////////////////////////////
/*
Note that by convention argv[0] is the name of your executable,
and the first argument to your program is stored in argv[1]
*/
task = atoi(argv[1]);
// TODO: Read the input grammar at this point from standard input
/*
Hint: You can modify and use the lexer from previous project
to read the input. Note that there are only 4 token types needed
for reading the input in this project.
WARNING: You will need to modify lexer.cc and lexer.h to only
support the tokens needed for this project if you are going to
use the lexer.
*/
int f = 1;
switch (task) {
case 1:
// TODO: perform task 1.
while(f<c-1)
{
cout<< Tnames[f] << ": "<< occ[f]<<endl;
f++;
}
break;
case 2:
// TODO: perform task 2.
if(startU = true)
{
for(int i = 1;i < numRows;i++)
{
bool space = false;
for(int j = 0; lines[i][j].token_type != HASH;j++)
{
if(lines[i][j].token_type)
if(used[i] == true)
{
space = true;
if(j==0)
{
cout<<lines[i][j].lexeme;
cout<<" ->";
}
else if(j>1)
{
cout<<" "<<lines[i][j].lexeme;
}
else
{
cout<<lines[i][j].lexeme;
}
}
}
if(space == true)
{
cout<<endl;
}
}
}
break;
case 3:
// TODO: perform task 3.
for(int x = 0;x<numNons;x++)
{
bool comma = false;
cout<<"FIRST("<<Nons[x]<<") = { ";
for(int y = 0;y<numTerms;y++)
{
if(first[x][y]==true)
{
if(comma == true)
{
cout<<", ";
}
comma = true;
if(y==0)
{
cout<<"#";
}
else{cout<<Terms[y];}
}
}
cout<<" }"<<endl;
}
break;
case 4:
// TODO: perform task 4.
for(int x = 0;x<numNons;x++)
{
bool comma = false;
cout<<"FOLLOW("<<Nons[x]<<") = { ";
for(int y = 0;y<numTerms;y++)
{
if(follow[x][y]==true)
{
if(comma == true)
{
cout<<", ";
}
comma = true;
if(y==0)
{
cout<<"$";
}
else{cout<<Terms[y];}
}
}
cout<<" }"<<endl;
}
break;
case 5:
// TODO: perform task 5.
break;
default:
cout << "Error: unrecognized task number " << task << "\n";
break;
}
return 0;
}
|
// Created on: 1994-02-24
// Created by: Laurent BOURESCHE
// Copyright (c) 1994-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 _BRepLProp_HeaderFile
#define _BRepLProp_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <GeomAbs_Shape.hxx>
#include <Standard_Real.hxx>
class BRepAdaptor_Curve;
//! These global functions compute the degree of
//! continuity of a curve built by concatenation of two
//! edges at their junction point.
class BRepLProp
{
public:
DEFINE_STANDARD_ALLOC
//! Computes the regularity at the junction between C1 and
//! C2. The point u1 on C1 and the point u2 on C2 must be
//! confused. tl and ta are the linear and angular
//! tolerance used two compare the derivative.
Standard_EXPORT static GeomAbs_Shape Continuity (const BRepAdaptor_Curve& C1, const BRepAdaptor_Curve& C2, const Standard_Real u1, const Standard_Real u2, const Standard_Real tl, const Standard_Real ta);
//! The same as preceding but using the standard tolerances from package Precision.
Standard_EXPORT static GeomAbs_Shape Continuity (const BRepAdaptor_Curve& C1, const BRepAdaptor_Curve& C2, const Standard_Real u1, const Standard_Real u2);
};
#endif // _BRepLProp_HeaderFile
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
const int N = 222;
struct Tp {
int x, y, i;
bool operator<(const Tp& t) const {
return x < t.x || (x == t.x && y < t.y);
}
} a[N];
int n;
int up[N][N], down[N][N];
bool f[N][N][N];
int p[N][N][N];
int main() {
freopen("division.in", "r", stdin);
freopen("division.out", "w", stdout);
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i].x >> a[i].y;
a[i].i = i + 1;
}
sort(a, a + n);
memset(up, -1, sizeof(up));
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (a[i].x != a[j].x) {
up[i][j] = 0;
down[i][j] = 0;
int A = a[i].y - a[j].y;
int B = a[j].x - a[i].x;
int C = -a[i].x * A - a[i].y * B;
for (int k = i + 1; k < j; ++k) {
int t = A * a[k].x + B * a[k].y + C;
if (t < 0) ++down[i][j];else
if (t > 0) ++up[i][j];else {
up[i][j] = -1;
break;
}
}
}
}
}
int bestscore = 1e9;
int besti = 0, bestj = 0, bestk = 0;
memset(p, -1, sizeof(p));
for (int i = 0; i < n; ++i) {
int u = 0, d = 0, good = 1;
for (int j = 0; j < i; ++j) {
if (a[i].y == a[j].y) {
good = 0;
break;
}
if (a[j].y > a[i].y) ++u;else ++d;
}
if (good)
f[i][u][d] = true;
for (int j = 0; j <= i; ++j)
for (int k = 0; j + k <= i; ++k) if (f[i][j][k]) {
for (int l = i + 1; l < n; ++l) if (up[i][l] != -1) {
f[l][j + up[i][l]][k + down[i][l]] = true;
p[l][j + up[i][l]][k + down[i][l]] = i;
}
}
u = 0, d = 0, good = 1;
for (int j = i + 1; j < n; ++j) {
if (a[i].y == a[j].y) {
good = 0;
break;
}
if (a[j].y > a[i].y) ++u;else ++d;
}
if (good) {
for (int j = 0; j <= i; ++j)
for (int k = 0; j + k <= i; ++k) if (f[i][j][k]) {
int b1 = j + u;
int b2 = k + d;
int b3 = n - b1 - b2;
int score = max(max(b1, b2), b3) - min(min(b1, b2), b3);
if (score < bestscore) {
bestscore = score;
besti = i;
bestj = j;
bestk = k;
}
}
}
}
vector<int> ans;
while (p[besti][bestj][bestk] != -1) {
ans.push_back(besti);
int previ = p[besti][bestj][bestk];
bestj -= up[previ][besti];
bestk -= down[previ][besti];
besti = previ;
}
ans.push_back(besti);
cout << ans.size() << endl;
for (int i = (int)ans.size() - 1; i >= 0; --i) {
cout << a[ ans[i] ].i << " ";
}
cout << endl;
return 0;
}
|
/** Copyright (c) 2018 Mozart Alexander Louis. All rights reserved. */
#ifndef __PARTICLE_UTILS_HXX__
#define __PARTICLE_UTILS_HXX__
/**
* Includes
*/
#include "globals.hxx"
#include "ui/CocosGUI.h"
/**
* Namespaces
*/
using namespace ui;
class ParticleUtils {
public:
/**
* Loads a particle system and auto sets it position.
*
* @param filename ~ Name of the file in the archive.
* @param x ~ X coordinate.
* @param y ~ Y coordinate.
* @param absolute ~ if we should place it in absolute positioning of div positioning.
*
* @returns ~ New paritcle system.
*/
static ParticleSystemQuad* load(const string& filename, float x = 2, float y = 2, bool absolute = false);
/**
* Loads all pariticels in the list and add them to a node container, creating a "compound" particle.
*
* @param list ~ List on names of particle files
* @param x ~ X coordinate.
* @param y ~ Y coordinate.
* @param absolute ~ if we should place it in absolute positioning of div positioning.
*
* @returns ~ Container paritcle system
*/
static Layout* load(initializer_list<string> list, float x = 2, float y = 2, bool absolute = false);
/**
* Stop all pariticels in the node container.
*
* @param container ~ Node containing more than one particle system.
*/
static void stop(Node* container);
private:
/**
* __DISALLOW_IMPLICIT_CONSTRUCTORS__
*/
__DISALLOW_IMPLICIT_CONSTRUCTORS__(ParticleUtils)
};
#endif // __PARTICLE_UTILS_HXX__
|
// MainFrm.cpp : CMainFrame 类的实现
//
#include "stdafx.h"
#include "MyCtrlBar.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
ON_WM_CREATE()
ON_COMMAND(ID_VIEW_SHORT, &CMainFrame::OnViewShort)
ON_COMMAND(ID_VIEW_LONG, &CMainFrame::OnViewLong)
ON_WM_TIMER()
ON_WM_CLOSE()
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, //状态行指示器
ID_SEPARATOR, //显示鼠标横坐标
ID_SEPARATOR, //显示鼠标纵坐标
ID_INDICATOR_CLOCK, //显示系统时间
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame 构造/析构
CMainFrame::CMainFrame()
{
// TODO: 在此添加成员初始化代码
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("未能创建工具栏\n");
return -1; // 未能创建
}
if (!m_wndStatusBar.Create(this))
{
TRACE0("未能创建状态栏\n");
return -1; // 未能创建
}
m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));
// TODO: 如果不需要可停靠工具栏,则删除这三行
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
CMainFrame::OnViewShort();
SetTimer(1, 1000, NULL);//安装定时器,并将其时间间隔设为1000毫秒
m_wndStatusBar.SetPaneInfo(1, ID_SEPARATOR, SBPS_POPOUT, 70);
m_wndStatusBar.SetPaneInfo(2, ID_SEPARATOR, SBPS_POPOUT, 70);
m_wndStatusBar.SetPaneInfo(m_wndStatusBar.CommandToIndex(ID_INDICATOR_CLOCK), ID_INDICATOR_CLOCK, SBPS_POPOUT, 100);
return 0;
}
void CMainFrame::OnClose()
{
KillTimer(1);
CMDIFrameWnd::OnClose();
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CMDIFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return TRUE;
}
// CMainFrame 诊断
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CMDIFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CMDIFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame 消息处理程序
void CMainFrame::OnViewShort(void)
{
//设置工具栏中按钮的个数
m_wndToolBar.SetButtons(NULL, 6);
//设置工具栏中按钮的信息
m_wndToolBar.SetButtonInfo(0, ID_VIEW_LONG, TBBS_BUTTON, 9);
m_wndToolBar.SetButtonInfo(1, ID_SEPARATOR, TBBS_SEPARATOR, 15);
m_wndToolBar.SetButtonInfo(2, ID_FILE_OPEN, TBBS_BUTTON, 1);
m_wndToolBar.SetButtonInfo(3, ID_FILE_SAVE, TBBS_BUTTON, 2);
m_wndToolBar.SetButtonInfo(4, ID_SEPARATOR, TBBS_SEPARATOR, 15);
m_wndToolBar.SetButtonInfo(5, ID_APP_ABOUT, TBBS_BUTTON, 7);
//更新视图
m_wndToolBar.Invalidate();
AfxGetApp()->OnIdle(-1);
}
void CMainFrame::OnViewLong(void)
{
//设置工具栏中按钮的个数
m_wndToolBar.SetButtons(NULL, 11);
//设置工具栏中按钮的信息
m_wndToolBar.SetButtonInfo(0, ID_VIEW_SHORT, TBBS_BUTTON, 8);
m_wndToolBar.SetButtonInfo(1, ID_SEPARATOR, TBBS_SEPARATOR, 15);
m_wndToolBar.SetButtonInfo(2, ID_FILE_NEW, TBBS_BUTTON, 0);
m_wndToolBar.SetButtonInfo(3, ID_FILE_OPEN, TBBS_BUTTON, 1);
m_wndToolBar.SetButtonInfo(4, ID_FILE_SAVE, TBBS_BUTTON, 2);
m_wndToolBar.SetButtonInfo(5, ID_SEPARATOR, TBBS_SEPARATOR, 15);
m_wndToolBar.SetButtonInfo(6, ID_EDIT_CUT, TBBS_BUTTON, 3);
m_wndToolBar.SetButtonInfo(7, ID_EDIT_COPY, TBBS_BUTTON, 4);
m_wndToolBar.SetButtonInfo(8, ID_EDIT_PASTE, TBBS_BUTTON, 5);
m_wndToolBar.SetButtonInfo(9, ID_FILE_PRINT, TBBS_BUTTON, 6);
m_wndToolBar.SetButtonInfo(10, ID_APP_ABOUT, TBBS_BUTTON, 7);
//更新视图
m_wndToolBar.Invalidate();
AfxGetApp()->OnIdle(-1);
}
void CMainFrame::OnTimer(UINT_PTR nIDEvent)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CTime time;
time = CTime::GetCurrentTime();//获取系统时间
CString str = time.Format("%H时%M分%S秒");//设置时间字符串的格式
m_wndStatusBar.SetPaneText(m_wndStatusBar.CommandToIndex(ID_INDICATOR_CLOCK),str);
CMDIFrameWnd::OnTimer(nIDEvent);
}
|
#include <iostream>
int tanpaRekursif(int x, int y) {
int result = 1;
do
{
result = result * x;
y--;
}
while (y > 0);
return result;
}
int pangkat(int x, int y) {
if(y == 0) {
return 1;
}
return x * pangkat(x, y-1);
}
int main () {
/* find power of number (pangkat) w & w/o recursive.
pangkat(2,3)
output 2*2*2 = 8
*/
std::cout << "rekursif :" << pangkat(2,3) << std::endl;
std::cout << "non-rekursiv: " << tanpaRekursif(2,3) << std::endl;
return 0;
}
|
#include<iostream>
using namespace std;
#define MAX 100
#define INFTY 2001
#define WHITE 0
#define GRAY 1
#define BLACK 2
int M[MAX][MAX], d[MAX];
// int p[MAX]; // p[u]はuの親を記録しておく配列だが本文では使う必要ない
void prim(int n){
int color[MAX], u;
// 初期化
for(int i=0; i<n; i++){
color[i] = WHITE;
d[i] = INFTY;
}
d[0] = 0;
//p[0] = -1;
while(true){
int mincost = INFTY;
for(int i=0; i<n; i++){
if(color[i] != BLACK && d[i] < mincost){
mincost = d[i];
u = i;
}
}
if(mincost == INFTY) break;
color[u] = BLACK;
// 次にTに含まれる可能性のあるノードに関して重みを記録する
for(int v=0; v<n; v++){
if(color[v] != BLACK && M[u][v] != INFTY){
if(M[u][v] < d[v]){
d[v] = M[u][v];
//p[v] = u;
color[v] = GRAY;
}
}
}
}
}
int main(void){
int n;
cin >> n;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cin >> M[i][j];
if(M[i][j] == -1) M[i][j] = INFTY;
}
}
prim(n);
// 最小全域木の辺の重みの総和を計算
int u = 0;
int d_sum = 0;
for(int i=0; i<n; i++){
d_sum += d[i];
}
cout << d_sum << endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-1999 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/js/screen.h"
#include "modules/doc/frm_doc.h"
#include "modules/display/vis_dev.h"
/* virtual */ ES_GetState
JS_Screen::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
FramesDocument *doc = GetFramesDocument();
if (!doc)
return GET_FAILED;
VisualDevice *vd = doc->GetVisualDevice();
switch (property_name)
{
case OP_ATOM_height:
DOMSetNumber(value, vd->GetScreenHeight());
return GET_SUCCESS;
case OP_ATOM_width:
DOMSetNumber(value, vd->GetScreenWidth());
return GET_SUCCESS;
case OP_ATOM_availHeight:
DOMSetNumber(value, vd->GetScreenAvailHeight());
return GET_SUCCESS;
case OP_ATOM_availWidth:
DOMSetNumber(value, vd->GetScreenAvailWidth());
return GET_SUCCESS;
case OP_ATOM_colorDepth:
if (value)
{
int colorDepth = vd->GetScreenColorDepth();
if (colorDepth <= 0)
DOMSetUndefined(value);
else
DOMSetNumber(value, colorDepth);
}
return GET_SUCCESS;
case OP_ATOM_pixelDepth:
DOMSetNumber(value, vd->GetScreenPixelDepth());
return GET_SUCCESS;
}
return GET_FAILED;
}
/* virtual */ ES_PutState
JS_Screen::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
if (GetName(property_name, NULL, origining_runtime))
return PUT_READ_ONLY;
else
return PUT_FAILED;
}
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/B.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Controls.Text.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.ITemplateSource.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.ICollapse.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Fuse.Triggers.IValue-1.h>
#include <Fuse.Visual.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.String.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{struct B;}
namespace g{
// public partial sealed class B :2
// {
::g::Fuse::Controls::TextControl_type* B_typeof();
void B__ctor_8_fn(B* __this);
void B__InitializeUX1_fn(B* __this);
void B__New4_fn(B** __retval);
struct B : ::g::Fuse::Controls::Text
{
void ctor_8();
void InitializeUX1();
static B* New4();
};
// }
} // ::g
|
#include <iostream>
#include "argparse.h"
using namespace std;
static vector<string> getArgs(char *argv[]) {
vector<string> actuals;
char **tmp = argv+1;
bool endOptions = false;
while(*tmp) {
if(strcmp(*tmp, "--") == 0) {
actuals.push_back(string(*tmp));
endOptions = true;
++ tmp;
continue;
}
// check if multiple flags passed as one eg -lfia
if(!endOptions && **tmp == '-'
&& strlen(*tmp) > 2 && (*tmp)[1] != '-') {
string multi = *tmp+1;
for(auto &c : multi) {
string arg = "-";
arg += c;
actuals.push_back(arg);
}
}
else {
actuals.push_back(string(*tmp));
}
++ tmp;
}
return move(actuals);
}
ostream &operator<<(ostream &stream, const Argument &arg) {
stream << '\t' << arg.getOpt() << ", " << arg.getOptlong();
if(arg.hasDescription())
stream << "\n\t\t" << arg.getDescription();
return stream;
}
// TODO need to check if an illegal argument
map<string, vector<string>> ArgParse::parseArgv(char *argv[]) {
map<string, vector<string>> argumentMap;
bool endOptions(false);
auto parsedParams = getArgs(argv);
string positionals = "positionals";
string prev = positionals;
string target = "";
vector<string>::iterator it = parsedParams.begin();
while(it != parsedParams.end()) {
// if only parsing positionals from now on
if(it->compare("--") == 0) {
endOptions = true;
++ it;
continue;
}
// if optlong then convert to short
if((*it).find("--") != (*it).npos) {
*it = longToShort[*it];
}
if(!endOptions && (*it)[0] == '-') {
argumentMap[*it] = vector<string> ();
string tmp = *it;
switch(args[tmp].getArgumentType()) {
case Argument::TYPE_OPTION:
it ++;
for(; it != parsedParams.end() && !endOptions && (*it)[0] != '-'; ++ it)
argumentMap[tmp].push_back(*it);
break;
case Argument::TYPE_POSITIONAL:
case Argument::TYPE_FLAG:
default: it ++;
}
}
else {
argumentMap[positionals].push_back(*it);
it ++;
}
if(it == parsedParams.end()) break;
}
return argumentMap;
}
ArgParse::ArgParse(string name, string desc) {
progDesc = desc;
progName = name;
addArg(Argument::ArgumentType::TYPE_FLAG, "-h", "--help",
[&](){
cout << progDesc << '\n' << "usage: " << progName << " "
<< "[" << getFlags() << "]" << '\n';
for(auto &pair : args) {
if(pair.first == "positionals") continue;
cout << args[pair.first] << '\n';
}
});
}
void ArgParse::addArg(Argument::ArgumentType type, string opt,
string optlong, Argument::Function f, string desc) {
longToShort[optlong] = opt;
args[opt] = Argument(type, opt, optlong, f, desc);
}
void ArgParse::parse(char *argv[]) {
actualParameters = parseArgv(argv);
}
void ArgParse::runAll() {
for(auto f : args) {
auto opt = f.first;
auto arg = f.second;
if(f.second.getHasRun()) continue;
if(actualParameters.find(arg.getOpt()) != actualParameters.end()
|| actualParameters.find(arg.getOptlong()) != actualParameters.end()) {
f.second();
arg.setHasRun();
}
}
}
// TODO templatize this for specific actions
void ArgParse::run(string toRun) {
auto arg = args[toRun];
arg.setHasRun();
arg();
}
string ArgParse::getFlags() {
string options;
for(auto a : args) {
if(a.first == "positionals") continue;
options += a.second.getOpt().substr(1);
}
return options;
}
|
#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <Eigen/Core>
#include <igl/polar_dec.h>
#include <igl/polar_svd.h>
namespace py = pybind11;
template<typename float_t>
py::array_t<float_t> inv3(py::array_t<float_t, py::array::c_style> & Ts)
{
auto Ts_buf = Ts.request();
float_t *pT = (float_t*)Ts_buf.ptr;
auto result = py::array_t<float_t, py::array::c_style>(Ts_buf.size);
auto result_buf = result.request();
float_t *pR = (float_t*)result_buf.ptr;
for (size_t idx = 0; idx < Ts_buf.shape[0]; idx++) {
const float_t T00 = pT[0], T01 = pT[1], T02 = pT[2];
const float_t T10 = pT[3], T11 = pT[4], T12 = pT[5];
const float_t T20 = pT[6], T21 = pT[7], T22 = pT[8];
const float_t det = T00 * (T22 * T11 - T21 * T12) \
- T10 * (T22 * T01 - T21 * T02) \
+ T20 * (T12 * T01 - T11 * T02);
const float_t invDet = 1. / det;
pR[0] = (T11 * T22 - T21 * T12) * invDet;
pR[1] = -(T01 * T22 - T02 * T21) * invDet;
pR[2] = (T01 * T12 - T02 * T11) * invDet;
pR[3] = -(T10 * T22 - T12 * T20) * invDet;
pR[4] = (T00 * T22 - T02 * T20) * invDet;
pR[5] = -(T00 * T12 - T10 * T02) * invDet;
pR[6] = (T10 * T21 - T20 * T11) * invDet;
pR[7] = -(T00 * T21 - T20 * T01) * invDet;
pR[8] = (T00 * T11 - T10 * T01) * invDet;
pT += 3*3;
pR += 3*3;
}
return result;
}
template<typename float_t>
py::array_t<float_t> inv2(py::array_t<float_t, py::array::c_style> & Ts)
{
auto Ts_buf = Ts.request();
float_t *pT = (float_t*)Ts_buf.ptr;
auto result = py::array_t<float_t, py::array::c_style>(Ts_buf.size);
auto result_buf = result.request();
float_t *pR = (float_t*)result_buf.ptr;
for (size_t idx = 0; idx < Ts_buf.shape[0]; idx++) {
const float_t T00 = pT[0], T01 = pT[1];
const float_t T10 = pT[2], T11 = pT[3];
const float_t det = T00 * T11 - T01 * T10;
const float_t invDet = 1. / det;
pR[0] = T11 * invDet;
pR[1] = -1 * T01 * invDet;
pR[2] = -1 * T10 * invDet;
pR[3] = T00 * invDet;
pT += 2*2;
pR += 2*2;
}
return result;
}
template<typename float_t>
py::array_t<float_t> matmat(
py::array_t<float_t, py::array::c_style> & a,
py::array_t<float_t, py::array::c_style> & b
)
{
auto a_buf = a.request();
float_t *p_a = (float_t*)a_buf.ptr;
auto b_buf = b.request();
float_t *p_b = (float_t*)b_buf.ptr;
auto result = py::array_t<float_t, py::array::c_style>(
{a_buf.shape[0], a_buf.shape[1], b_buf.shape[2]});
auto result_buf = result.request();
float_t *p_res = (float_t*)result_buf.ptr;
const size_t n_rows_a = a_buf.shape[1];
const size_t n_cols_a = a_buf.shape[2];
const size_t n_rows_b = b_buf.shape[1];
const size_t n_cols_b = b_buf.shape[2];
assert(n_cols_a == n_rows_b);
for (size_t idx = 0; idx < a_buf.shape[0]; idx++) {
for (size_t row_a = 0; row_a < n_rows_a; row_a++) {
for (size_t col_b = 0; col_b < n_cols_b; col_b++) {
float_t sum = 0.0;
for (size_t k = 0; k < n_cols_a; k++) {
const float_t ai = p_a[row_a * n_cols_a + k];
const float_t bi = p_b[k * n_cols_b + col_b];
sum += ai * bi;
}
*p_res = sum;
p_res++;
}
}
p_a += n_cols_a * n_rows_a;
p_b += n_cols_b * n_rows_b;
}
return result;
}
template<typename float_t>
py::array_t<float_t> matvec(
py::array_t<float_t, py::array::c_style> & mats,
py::array_t<float_t, py::array::c_style> & vecs
)
{
auto mats_buf = mats.request();
float_t *p_mats = (float_t*)mats_buf.ptr;
auto vecs_buf = vecs.request();
float_t *p_vecs = (float_t*)vecs_buf.ptr;
auto result = py::array_t<float_t, py::array::c_style>({mats_buf.shape[0], mats_buf.shape[1]});
auto result_buf = result.request();
float_t *p_res = (float_t*)result_buf.ptr;
const size_t mat_stride1 = mats_buf.strides[1] / sizeof(float_t);
for (size_t idx = 0; idx < mats_buf.shape[0]; idx++) {
for (size_t row = 0; row < mats_buf.shape[1]; row++) {
float_t sum = 0.0;
for (size_t k = 0; k < mats_buf.shape[2]; k++) {
sum += *(p_mats++) * p_vecs[k];
}
*p_res = sum;
p_res++;
}
p_vecs += vecs_buf.shape[1];
}
return result;
}
template<typename float_t>
py::array_t<float_t> cross3(
py::array_t<float_t, py::array::c_style> & a,
py::array_t<float_t, py::array::c_style> & b
)
{
auto a_buf = a.request();
float_t *p_a = (float_t*)a_buf.ptr;
auto b_buf = b.request();
float_t *p_b = (float_t*)b_buf.ptr;
auto result = py::array_t<float_t, py::array::c_style>(
{a_buf.shape[0], a_buf.shape[1]});
auto result_buf = result.request();
float_t *p_res = (float_t*)result_buf.ptr;
for (size_t idx = 0; idx < a_buf.shape[0]; idx++) {
const double ax = p_a[0];
const double ay = p_a[1];
const double az = p_a[2];
const double bx = p_b[0];
const double by = p_b[1];
const double bz = p_b[2];
p_res[0] = ay * bz - az * by;
p_res[1] = az * bx - ax * bz;
p_res[2] = ax * by - ay * bx;
p_res += 3;
p_a += 3;
p_b += 3;
}
return result;
}
template<typename float_t>
py::array_t<float_t> multikron(
py::array_t<float_t, py::array::c_style> & a,
py::array_t<float_t, py::array::c_style> & b
)
{
auto a_buf = a.request();
float_t *p_a = (float_t*)a_buf.ptr;
auto b_buf = b.request();
float_t *p_b = (float_t*)b_buf.ptr;
const auto n_rows_a = a_buf.shape[1];
const auto n_cols_a = a_buf.shape[2];
const auto n_rows_b = b_buf.shape[1];
const auto n_cols_b = b_buf.shape[2];
auto result = py::array_t<float_t, py::array::c_style>(
{a_buf.shape[0], n_rows_a * n_rows_b, n_cols_a * n_cols_b});
auto result_buf = result.request();
float_t *p_res = (float_t*)result_buf.ptr;
for (size_t idx = 0; idx < a_buf.shape[0]; idx++) {
// iterate over rows of a
for (size_t row_a = 0; row_a < n_rows_a; row_a++) {
// iterate over rows of b
for (size_t row_b = 0; row_b < n_rows_b; row_b++) {
// iterate over columns of a
for (size_t col_a = 0; col_a < n_cols_a; col_a++) {
// iterate over columns of b
for (size_t col_b = 0; col_b < n_cols_b; col_b++) {
const float_t ai = p_a[row_a * n_cols_a + col_a];
const float_t bi = p_b[row_b * n_cols_b + col_b];
*p_res = ai * bi;
p_res++;
}
}
}
}
// next matrix
p_a += n_cols_a * n_rows_a;
p_b += n_cols_b * n_rows_b;
}
return result;
}
std::tuple<py::array_t<double>, py::array_t<double>>
polarDecompose(py::array_t<double, py::array::c_style> Ms)
{
using RowMat3d = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>;
auto Ms_raw = Ms.unchecked<3>();
// allocate output matrices
auto Rs = py::array_t<double>({Ms_raw.shape(0), 3l, 3l});
auto Rs_raw = Rs.mutable_unchecked<3>();
auto Ss = py::array_t<double>({Ms_raw.shape(0), 3l, 3l});
auto Ss_raw = Ss.mutable_unchecked<3>();
RowMat3d U;
RowMat3d V;
Eigen::Matrix<double,3,1> S;
for (int i = 0; i < Ms_raw.shape(0); ++i) {
const RowMat3d Mi = Eigen::Map<const RowMat3d>(Ms_raw.data(i, 0, 0));
Eigen::Map<RowMat3d> Ri_map(Rs_raw.mutable_data(i, 0, 0));
Eigen::Map<RowMat3d> Si_map(Ss_raw.mutable_data(i, 0, 0));
RowMat3d Ri = Ri_map; // performs copy, since igl::polar_dec does not take Eigen::Map
RowMat3d Si = Si_map;
//igl::polar_dec(Mi, Ri, Si);
igl::polar_svd(Mi, Ri, Si, U, S, V);
// TODO: use igl::polar_svd3x3?
// write back results
Ri_map = Ri;
Si_map = Si;
}
return std::make_tuple(Rs, Ss);
}
PYBIND11_MODULE(_fastmath_ext, m) {
m.def("inv3", &inv3<float>);
m.def("inv3", &inv3<double>);
m.def("inv2", &inv2<float>);
m.def("inv2", &inv2<double>);
m.def("matmat", &matmat<double>);
m.def("matvec", &matvec<double>);
m.def("cross3", &cross3<double>);
m.def("multikron", &multikron<double>);
m.def("polar_dec", &polarDecompose);
}
|
#ifndef APPLICATION_INFOMANAGER_H
#define APPLICATION_INFOMANAGER_H
#include "BaseManager.h"
#include <boost/property_tree/ptree.hpp>
#include "src/server/lib/Connection/BaseConnection.h"
class InfoManager: public BaseManager {
public:
~InfoManager() override = default;
boost::property_tree::ptree getMessageAuthorInfo(boost::property_tree::ptree ¶ms);
boost::property_tree::ptree getChatInfo(boost::property_tree::ptree ¶ms);
boost::property_tree::ptree getUserChatsPreview(boost::property_tree::ptree ¶ms);
};
#endif //APPLICATION_INFOMANAGER_H
|
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int A,B,SOMA;
scanf ("%d", &A);
scanf("%d", &B);
SOMA = A + B;
printf("SOMA = %d\n", SOMA);
return 0;
}
|
#include "ros/ros.h"
#include "geometry_msgs/PoseArray.h"
#include "visualization_msgs/Marker.h"
#include <bitset>
class marker_class
{
ros::Publisher vis_pub;
public:
marker_class(ros::NodeHandle* n):vis_pub()
{
vis_pub = n->advertise<visualization_msgs::Marker>( "visualization_marker", 10);
}
void visCallback(const geometry_msgs::PoseArray::ConstPtr& msg);
};
void marker_class::visCallback(const geometry_msgs::PoseArray::ConstPtr& msg)
{
// namespace pos = msg->poses[0].position;
// namespace ori = msg->poses[0].orientation;
if(!msg->poses.empty())
{
visualization_msgs::Marker marker;
marker.header.frame_id = msg->header.frame_id;//"base_link";
marker.header.stamp = msg->header.stamp;//ros::Time();
marker.ns = "rviz_marker";
marker.id = 252;
marker.type = visualization_msgs::Marker::SPHERE;
marker.action = visualization_msgs::Marker::ADD;
for(int i = 0;i<msg->poses.size();i++)
{
std::bitset<3> num(i);
marker.pose.position.x = msg->poses[i].position.x;
marker.pose.position.y = msg->poses[i].position.y;
marker.pose.position.z = msg->poses[i].position.z;
marker.pose.orientation.x = msg->poses[i].orientation.x;
marker.pose.orientation.y = msg->poses[i].orientation.y;
marker.pose.orientation.z = msg->poses[i].orientation.z;
marker.pose.orientation.w = msg->poses[i].orientation.w;
marker.scale.x = 0.11;
marker.scale.y = 0.1;
marker.scale.z = 0.1;
marker.color.a = 1.0; // Don't forget to set the alpha!
marker.color.r = float(num[0]);
marker.color.g = float(num[1]);
marker.color.b = float(num[2]);
vis_pub.publish( marker );
//ROS_INFO_STREAM("Published "<<i<<" "<<msg->poses.size()<<'\n');
}
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "marker_node");
ros::NodeHandle n;
marker_class M(&n);
ros::Subscriber sub = n.subscribe("/DetectedPersons1_position", 0, &marker_class::visCallback, &M);
ros::spin();
return 0;
}
|
#include "Music.h"
sf::Music Music::backgroundMusic;
void Music::playMusic()
{
backgroundMusic.openFromFile("Sounds/backgroundMusic.ogg");
backgroundMusic.play();
backgroundMusic.setLoop(1);
}
|
#ifndef tmptools__coretools__type_if__hpp
#define tmptools__coretools__type_if__hpp
#include "instance_of.hpp"
namespace tmp {
template <bool Condition, typename T1, typename T2>
struct type_if
: instance_of<T1> {};
template <typename T1, typename T2>
struct type_if<false, T1, T2>
: instance_of<T2> {};
} // tmp
#endif // tmptools__coretools__type_if__hpp
|
/* System includes */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* OpenCL includes */
#include <CL/cl.h>
#include <SFML/>
// #include ” u t i l s . h”
// #include ”bmp−u t i l s . h”
static const int HIST_BINS = 256;
int main(int argc, char **argv)
{
/* Host data */
int *hInputImage = NULL;
int *hOutputHistogram = NULL;
/* Allocate space for the input image and read the data from disk */
int imageRows;
int imageCols;
hInputImage = readBmp("../../Images/cat.bmp", &imageRows, &imageCols);
// const int imageElements = imageRows * imageCols;
// const size_t imageSize = imageElements * sizeof(int);
// /* Allocate space for the histogram on the host */
// const int histogramSize = HIST_BINS * sizeof(int);
// hOutputHistogram = (int *)malloc(histogramSize);
// if (!hOutputHistogram)
// {
// exit(−1);
// }
// /* Use this to check the output of each API call */
// cl_int status;
// /* Get the f i r s t platform */
// cl_platform_id platform;
// status = clGetPlatformIDs(1, &platform, NULL);
// check(status);
// /* Get the f i r s t device */
// cl_device_id device;
// status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device,
// NULL);
// check(status);
// /* Create a context and associate i t with the device */
// cl_context context;
// context = clCreateContext(NULL, 1, &device, NULL, NULL, &status);
// check(status);
// /* Create a command−queue and associate i t with the device */
// cl_command_queue cmdQueue;
// cmdQueue = clCreateCommandQueue(context, device, 0, &status);
// check(status);
// /* Create a buffer object for the input image */
// cl_mem bufInputImage;
// bufInputImage = clCreateBuffer(context, CL_MEM_READ_ONLY,
// imageSize, NULL,
// &status);
// check(status);
// /* Create a buffer object for the output histogram */
// cl_mem bufOutputHistogram;
// bufOutputHistogram = clCreateBuffer(context, CL_MEM_WRITE_ONLY,
// histogramSize, NULL, &status);
// check(status);
// /* Write the input image to the device */
// status = clEnqueueWriteBuffer(cmdQueue, bufInputImage, CL_TRUE,
// 0, imageSize,
// hInputImage, 0, NULL, NULL);
// check(status);
// /* I n i t i a l i z e the output histogram with zeros */
// int zero = 0;
// status = clEnqueueFillBuffer(cmdQueue, bufOutputHistogram, &zero,
// sizeof(int), 0, histogramSize, 0, NULL, NULL);
// check(status);
// /* Create a program with source code */
// char *programSource = readFile(”histogram.cl”);
// size_t programSourceLen = strlen(programSource);
// cl_program program = clCreateProgramWithSource(context, 1,
// (const char **)&programSource, &programSourceLen, &status);
// check(status);
// /* Build ( compile ) the program for the device */
// status = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
// if (status != CL_SUCCESS)
// {
// printCompilerError(program, device);
// exit(−1);
// }
// /* Create the kernel */
// cl_kernel kernel;
// kernel = clCreateKernel(program, ”histogram” , &status);
// check(status);
// /* Set the kernel arguments */
// status = clSetKernelArg(kernel, 0, sizeof(cl_mem), &bufInputImage);
// status |= clSetKernelArg(kernel, 1, sizeof(int), &imageElements);
// status |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &bufOutputHistogram);
// check(status);
// /* Define the index space and work−group size */
// size_t globalWorkSize[1];
// globalWorkSize[0] = 1024;
// size_t localWorkSize[1];
// localWorkSize[0] = 64;
// /* Enqueue the kernel for execution */
// status = clEnqueueNDRangeKernel(cmdQueue, kernel, 1, NULL,
// globalWorkSize, localWorkSize, 0, NULL, NULL);
// check(status);
// /* Read the output histogram buffer to the host */
// status = clEnqueueReadBuffer(cmdQueue, bufOutputHistogram,
// CL_TRUE, 0,
// histogramSize, hOutputHistogram, 0, NULL, NULL);
// check(status);
// .3 Image rotation 83
// /* Free OpenCL resources */
// clReleaseKernel(kernel);
// clReleaseProgram(program);
// clReleaseCommandQueue(cmdQueue);
// clReleaseMemObject(bufInputImage);
// clReleaseMemObject(bufOutputHistogram);
// clReleaseContext(context);
// /* Free host resources */
// free(hInputImage);
// free(hOutputHistogram);
// free(programSource);
// return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
bool nextPermutation(int array[], int size){
int i = size - 1;
while (i > 0 && array[i - 1] >= array[i])
i--;
// Now i is the head index of the suffix
// Are we at the last permutation already?
if (i <= 0)
return false;
// Let array[i - 1] be the pivot
// Find rightmost element that exceeds the pivot
int j = size - 1;
while (array[j] <= array[i - 1])
j--;
// Now the value array[j] will become the new pivot
// Assertion: j >= i
// Swap the pivot with j
int temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;
// Reverse the suffix
j = size - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
// Successfully computed the next permutation
return true;
}
void printArr(int arr[], int size){
for(int i = 0 ; i < size; i++)
std::cout << arr[i];
std::cout << '\n';
}
int main(){
int arr[] = {0,1,2,3,4,5,6,7,8,9};
int size = 10;
int i = 1;
printArr(arr,size);
while(i < 1000000){
nextPermutation(arr,size);
printArr(arr,size);
i++;
}
}
|
/*
Copyright 2021 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.
*/
#include "query_manager.hpp"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <utility>
#include "mock_accelerator_library.hpp"
#include "mock_data_manager.hpp"
#include "mock_fpga_manager.hpp"
#include "mock_memory_manager.hpp"
#include "query_acceleration_constants.hpp"
#include "stream_data_parameters.hpp"
#include "virtual_memory_block.hpp"
using orkhestrafs::core_interfaces::query_scheduling_data::
NodeOperationParameters;
using orkhestrafs::dbmstodspi::QueryManager;
namespace {
class QueryManagerTest : public ::testing::Test {
protected:
std::shared_ptr<QueryNode> base_query_node_;
QueryOperationType base_operation_type_ = QueryOperationType::kJoin;
NodeOperationParameters any_operation_params_ = {{}, {}, {}};
std::string base_node_name_ = "base";
std::vector<std::string> data_files_vector_;
std::vector<QueryNode*> next_nodes_;
std::vector<QueryNode*> previous_nodes_;
std::vector<bool> is_checked_;
void SetUp() override {
base_query_node_ = std::make_shared<QueryNode>(
data_files_vector_, data_files_vector_, base_operation_type_,
next_nodes_, previous_nodes_, any_operation_params_, base_node_name_,
is_checked_);
}
};
// Two links. One link is about current run and the other one is for the second
// run.
TEST_F(QueryManagerTest, DISABLED_GetCurrentLinksReturnsLinks) {
/*std::map<std::string, std::map<int, MemoryReuseTargets>> all_reuse_targets;
std::map<std::string, std::map<int, MemoryReuseTargets>> expected_results;
std::map<int, MemoryReuseTargets> any_reuse_target;
std::map<int, MemoryReuseTargets> expected_reuse_target;
std::string other_node_name = "other";
expected_reuse_target.insert({0, {{other_node_name, 0}}});
auto other_query_node = std::make_shared<QueryNode>(
data_files_vector_, data_files_vector_, base_operation_type_, next_nodes_,
previous_nodes_, any_operation_params_, other_node_name, is_checked_);
all_reuse_targets.insert({base_node_name_, expected_reuse_target});
all_reuse_targets.insert({other_node_name, any_reuse_target});
expected_results.insert({base_node_name_, expected_reuse_target});
QueryManager query_manager_under_test(nullptr);
ASSERT_EQ(expected_results,
query_manager_under_test.GetCurrentLinks(all_reuse_targets));*/
}
// This method should be made smaller and unit tests more fine grain.
TEST_F(QueryManagerTest,
DISABLED_SetupAccelerationNodesForExecutionReturnsExpectedRun) {
// std::unique_ptr<MemoryBlockInterface> output_memory_block =
// std::make_unique<VirtualMemoryBlock>();
// std::unique_ptr<MemoryBlockInterface> input_memory_block =
// std::make_unique<VirtualMemoryBlock>();
// auto *input_physical_address = input_memory_block->GetPhysicalAddress();
// auto *output_physical_address = output_memory_block->GetPhysicalAddress();
// std::string input_filename = "input_file";
// std::string output_filename = "output_file";
// std::vector<std::pair<ColumnDataType, int>> expected_column_defs_vector = {
// {ColumnDataType::kDecimal, 2},
// {ColumnDataType::kDate, 4},
// {ColumnDataType::kDecimal, 1}};
// std::vector<int> column_types = {3, 4, 3};
// std::vector<ColumnDataType> expected_column_types = {
// ColumnDataType::kDecimal, ColumnDataType::kDate,
// ColumnDataType::kDecimal};
// std::vector<int> column_widths = {4, 2, 2};
// std::vector<int> input_projection = {1, 2, 3, 4, 5, 6, 7};
// std::vector<int> output_projection = {2, 1, 3, 4, 5, 6, 7};
// std::vector<int> empty_vector = {};
// std::vector<int> chunk_count = {1};
// std::vector<std::vector<int>> input_stream_specification = {
// input_projection, column_types, column_widths, empty_vector};
// std::vector<std::vector<int>> output_stream_specification = {
// output_projection, column_types, column_widths, chunk_count};
// std::vector<std::vector<int>> empty_operation_params;
// int expected_record_count = 999;
// MockDataManager mock_data_manager;
// EXPECT_CALL(
// mock_data_manager,
// MockWriteDataFromCSVToMemory(input_filename,
// expected_column_defs_vector,
// input_memory_block.get()))
// .WillOnce(testing::Return(expected_record_count));
// EXPECT_CALL(mock_data_manager,
// GetHeaderColumnVector(expected_column_types, column_widths))
// .WillOnce(testing::Return(expected_column_defs_vector))
// .WillOnce(testing::Return(expected_column_defs_vector));
// MockMemoryManager mock_memory_manager;
// EXPECT_CALL(mock_memory_manager, GetAvailableMemoryBlock())
// .WillOnce(
// testing::Return(testing::ByMove(std::move(output_memory_block))))
// .WillOnce(
// testing::Return(testing::ByMove(std::move(input_memory_block))));
// MockAcceleratorLibrary mock_accelerator_library;
// std::pair<int, int> expected_multi_channel_params = {-1, -1};
// EXPECT_CALL(mock_accelerator_library,
// GetMultiChannelParams(true, 0, base_operation_type_,
// empty_operation_params))
// .WillOnce(testing::Return(expected_multi_channel_params));
// EXPECT_CALL(mock_accelerator_library,
// GetMultiChannelParams(false, 0, base_operation_type_,
// empty_operation_params))
// .WillOnce(testing::Return(expected_multi_channel_params));
// std::map<std::string, std::vector<std::unique_ptr<MemoryBlockInterface>>>
// input_memory_blocks;
// std::map<std::string, std::vector<std::unique_ptr<MemoryBlockInterface>>>
// output_memory_blocks;
// std::map<std::string, std::vector<RecordSizeAndCount>> input_stream_sizes;
// std::map<std::string, std::vector<RecordSizeAndCount>> output_stream_sizes;
// base_query_node_->input_data_definition_files.push_back(input_filename);
// base_query_node_->output_data_definition_files.push_back(output_filename);
// base_query_node_->next_nodes.push_back(nullptr);
// base_query_node_->previous_nodes.push_back(std::weak_ptr<QueryNode>());
// base_query_node_->operation_parameters.input_stream_parameters =
// input_stream_specification;
// base_query_node_->operation_parameters.output_stream_parameters =
// output_stream_specification;
// bool check_status = false;
// base_query_node_->is_checked = {check_status};
// int expected_location = 99;
//// TODO: Missing test with composed modules!
// base_query_node_->module_locations = {expected_location};
// QueryManager query_manager_under_test(nullptr);
// auto [query_nodes, result_parameters] =
// query_manager_under_test.SetupAccelerationNodesForExecution(
// &mock_data_manager, &mock_memory_manager, &mock_accelerator_library,
// input_memory_blocks, output_memory_blocks, input_stream_sizes,
// output_stream_sizes, {base_query_node_});
// int expected_stream_id = 0;
// int expected_record_size = 7;
// StreamDataParameters expected_input_stream_param = {
// expected_stream_id, expected_record_size, expected_record_count,
// input_physical_address, input_projection};
// StreamDataParameters expected_output_stream_param = {
// expected_stream_id, expected_record_size, 0,
// output_physical_address, output_projection, chunk_count.at(0)};
// AcceleratedQueryNode expected_query_node = {{expected_input_stream_param},
// {expected_output_stream_param},
// base_operation_type_,
// expected_location,
// {},
// empty_operation_params};
// int expected_stream_index = 0;
// StreamResultParameters expected_result_params = {
// expected_stream_index, expected_stream_id, output_filename,
// check_status, output_stream_specification};
// ASSERT_EQ(1, result_parameters.size());
// ASSERT_EQ(1, result_parameters.at(base_node_name_).size());
// ASSERT_EQ(1, query_nodes.size());
// ASSERT_EQ(expected_query_node, query_nodes.at(0));
// ASSERT_EQ(expected_result_params,
// result_parameters.at(base_node_name_).at(0));
// ASSERT_EQ(1, input_stream_sizes.at(base_node_name_).size());
// ASSERT_EQ(expected_record_size,
// input_stream_sizes.at(base_node_name_).at(0).first);
// ASSERT_EQ(expected_record_count,
// input_stream_sizes.at(base_node_name_).at(0).second);
// ASSERT_EQ(1, output_stream_sizes.at(base_node_name_).size());
// ASSERT_EQ(expected_record_size,
// output_stream_sizes.at(base_node_name_).at(0).first);
// ASSERT_EQ(0, output_stream_sizes.at(base_node_name_).at(0).second);
// ASSERT_EQ(1, input_memory_blocks.at(base_node_name_).size());
// ASSERT_EQ(
// input_physical_address,
// input_memory_blocks.at(base_node_name_).at(0)->GetPhysicalAddress());
// ASSERT_EQ(1, output_memory_blocks.at(base_node_name_).size());
// ASSERT_EQ(
// output_physical_address,
// output_memory_blocks.at(base_node_name_).at(0)->GetPhysicalAddress());
}
TEST_F(QueryManagerTest, DISABLED_LoadNextBitstreamIfNewUsesMemoryManager) {
/*MockMemoryManager mock_memory_manager;
QueryManager query_manager_under_test(nullptr);
Config config;
std::string expected_bitstream_file_name = "test_file";
int expected_memory_space = 10;
config.required_memory_space.insert(
{expected_bitstream_file_name, expected_memory_space});
EXPECT_CALL(
mock_memory_manager,
LoadBitstreamIfNew(expected_bitstream_file_name, expected_memory_space))
.Times(1);
query_manager_under_test.LoadNextBitstreamIfNew(
&mock_memory_manager, expected_bitstream_file_name, config);*/
}
TEST_F(QueryManagerTest, DISABLED_ExecuteAndProcessResultsCallsFPGAManager) {
MockFPGAManager mock_fpga_manager;
std::vector<AcceleratedQueryNode> execution_query_nodes;
std::map<int, std::vector<double>> empty_map;
EXPECT_CALL(mock_fpga_manager, SetupQueryAcceleration(execution_query_nodes))
.Times(1);
EXPECT_CALL(mock_fpga_manager, RunQueryAcceleration(1, empty_map)).Times(1);
std::map<std::string, std::vector<std::unique_ptr<MemoryBlockInterface>>>
output_memory_blocks;
std::map<std::string, std::vector<RecordSizeAndCount>> output_stream_sizes;
std::map<std::string, std::vector<StreamResultParameters>> result_parameters;
MockDataManager mock_data_manager;
QueryManager query_manager_under_test(nullptr);
/*query_manager_under_test.ExecuteAndProcessResults(
&mock_fpga_manager, &mock_data_manager, output_memory_blocks,
output_stream_sizes, result_parameters, execution_query_nodes);*/
}
} // namespace
|
#ifndef FILEWORKER_HPP
#define FILEWORKER_HPP
#include <QObject>
class FileWorker : public QObject
{
Q_OBJECT
public:
explicit FileWorker(QObject *parent = 0);
signals:
public slots:
static bool savePictureToGallery(const QString &sourcePath);
};
#endif // FILEWORKER_HPP
|
// Created on: 1995-02-27
// Created by: Christian CAILLET
// Copyright (c) 1995-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 _Transfer_BinderOfTransientInteger_HeaderFile
#define _Transfer_BinderOfTransientInteger_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Integer.hxx>
#include <Transfer_SimpleBinderOfTransient.hxx>
class Transfer_BinderOfTransientInteger;
DEFINE_STANDARD_HANDLE(Transfer_BinderOfTransientInteger, Transfer_SimpleBinderOfTransient)
//! This type of Binder allows to attach as result, besides a
//! Transient Object, an Integer Value, which can be an Index
//! in the Object if it defines a List, for instance
//!
//! This Binder is otherwise a kind of SimpleBinderOfTransient,
//! i.e. its basic result (for iterators, etc) is the Transient
class Transfer_BinderOfTransientInteger : public Transfer_SimpleBinderOfTransient
{
public:
//! Creates an empty BinderOfTransientInteger; Default value for
//! the integer part is zero
Standard_EXPORT Transfer_BinderOfTransientInteger();
//! Sets a value for the integer part
Standard_EXPORT void SetInteger (const Standard_Integer value);
//! Returns the value set for the integer part
Standard_EXPORT Standard_Integer Integer() const;
DEFINE_STANDARD_RTTIEXT(Transfer_BinderOfTransientInteger,Transfer_SimpleBinderOfTransient)
protected:
private:
Standard_Integer theintval;
};
#endif // _Transfer_BinderOfTransientInteger_HeaderFile
|
#pragma once
#include "Entity.h"
#include "../Components/Transform.h"
#include "../Components/Renderer.h"
#include "../Components/BoxCollider.h"
class dfTile :
public Entity
{
public:
dfTile(void);
virtual ~dfTile(void);
virtual void Init();
virtual void Update();
virtual void InterpretProperty(const char* name, const char* value);
virtual void AddCollision(Collider*);
Transform tf;
Renderer render;
std::vector<Collider*> colliders;
};
|
#pragma once
class Fade;
class AIEditModeSelect :public GameObject
{
public:
~AIEditModeSelect();
bool Start();
void Update();
private:
enum AIMode
{
enVisual,
enPython,
};
SpriteRender* m_spMode[2];
int m_sel = 0;
Fade* m_fade;
};
|
#pragma once
class Gamma {
public:
// Inits the brightness curve with a traditional gamma curve of N^p.
void initPower(float p = 2.6f);
// Inits the brightness curve with an anti log curve of 2^Np - 1.
void initAntiLog(float p = 6);
inline CRGB apply(const CRGB &c) {
return CRGB(_lut[c.r], _lut[c.g], _lut[c.b]);
}
inline void apply(const CRGB &in, CRGB &out) {
out.r = _lut[in.r];
out.g = _lut[in.g];
out.b = _lut[in.b];
}
private:
uint8_t _lut[256];
};
|
// Given a set of distinct integers, S, return all possible subsets.
// Note:
// Elements in a subset must be in non-descending order.
// The solution set must not contain duplicate subsets.
// For example,
// If S = [1,2,3], a solution is:
// [
// [3],
// [1],
// [2],
// [1,2,3],
// [1,3],
// [2,3],
// [1,2],
// []
// ]
//这是排列问题,加上空集
// 0 0 0
// take this one?
/* This a AWSOME solution!!
Number of subsets for {1 , 2 , 3 } = 2^3 .
why ?
case possible outcomes for the set of subsets
1 -> Take or dont take = 2
2 -> Take or dont take = 2
3 -> Take or dont take = 2
therefore , total = 2*2*2 = 2^3 = { { } , {1} , {2} , {3} , {1,2} , {1,3} , {2,3} , {1,2,3} }
Lets assign bits to each outcome -> First bit to 1 , Second bit to 2 and third bit to 3
Take = 1
Dont take = 0
0) 0 0 0 -> Dont take 3 , Dont take 2 , Dont take 1 = { }
1) 0 0 1 -> Dont take 3 , Dont take 2 , take 1 = {1 }
2) 0 1 0 -> Dont take 3 , take 2 , Dont take 1 = { 2 }
3) 0 1 1 -> Dont take 3 , take 2 , take 1 = { 1 , 2 }
4) 1 0 0 -> take 3 , Dont take 2 , Dont take 1 = { 3 }
5) 1 0 1 -> take 3 , Dont take 2 , take 1 = { 1 , 3 }
6) 1 1 0 -> take 3 , take 2 , Dont take 1 = { 2 , 3 }
7) 1 1 1 -> take 3 , take 2 , take 1 = { 1 , 2 , 3 }
In the above logic ,Insert S[i] only if (j>>i)&1 ==true { j E { 0,1,2,3,4,5,6,7 } i = ith element in the input array }
element 1 is inserted only into those places where 1st bit of j is 1
if( j >> 0 &1 ) ==> for above above eg. this is true for sl.no.( j )= 1 , 3 , 5 , 7
element 2 is inserted only into those places where 2nd bit of j is 1
if( j >> 1 &1 ) == for above above eg. this is true for sl.no.( j ) = 2 , 3 , 6 , 7
element 3 is inserted only into those places where 3rd bit of j is 1
if( j >> 2 & 1 ) == for above above eg. this is true for sl.no.( j ) = 4 , 5 , 6 , 7
*/
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end());
int elem_size = S.size();
int subset_sum = pow(2, elem_size);
vector<vector<int>> subset (subset_sum, vector<int>());
for(int i = 0; i < elem_size; i++){
for(int j=0; j < subset_sum; j++){
subset[j].push_back(S[i]);
}
}
return subset;
}
vector<int> mVec;
vector< vector<int> > mRes;
void op(const vector<int>& S, int idx){
if(idx >= S.size()){
mRes.push_back(mVec);
return;
}
op(S, idx + 1);
mVec.push_back(S[idx]);
op(S, idx + 1);
mVec.pop_back();
}
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end());
op(S, 0);
return mRes;
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
struct Tp {
int x, y;
bool operator<(const Tp& B) const {
return x < B.x || (x == B.x && y > B.y);
}
} a[255], b[255];
int del[255];
LD D[255][255];
LL dg[255][255];
pair<LD, int> nei[255][255];
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
int T;
scanf("%d", &T);
while (T--) {
int n, m, w;
scanf("%d%d%d", &n, &m, &w);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &a[i].x, &a[i].y);
}
for (int i = 0; i < m; ++i) {
scanf("%d%d", &b[i].x, &b[i].y);
}
sort(b, b + m);
memset(del, false, sizeof(del));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < i; ++j) {
if (b[j].y >= b[i].y) {
del[j] = true;
}
}
}
int mn = 0;
for (int i = 0; i < m; ++i) if (!del[i])
b[mn++] = b[i];
m = mn;
for (int i = 0; i < n; ++i)
for (int j = i; j < n; ++j)
D[i][j] = D[j][i] = sqrtl(sqr(LL(a[i].x) - a[j].x) + sqr(LL(a[i].y) - a[j].y));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) if (i != j) {
nei[i][j - (i <= j)] = make_pair(D[i][j], j);
}
sort(nei[i], nei[i] + n - 1);
}
LL ans = -1;
memset(dg, 127, sizeof(dg));
priority_queue< pair<LL, pair<int, int> > > q;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) if (a[i].y <= b[j].x) {
dg[i][j] = b[j].y;
q.push(make_pair(-dg[i][j], make_pair(i, j)));
break;
}
}
while (!q.empty()) {
pair<LL, pair<int, int> > t = q.top(); q.pop();
const LL d = -t.first;
const pair<int, int> x = t.second;
if (d != dg[x.first][x.second]) continue;
if (x.first == n) {
ans = d;
break;
}
if (x.second + 1 < m) {
LL dd = d + b[x.second + 1].y - b[x.second].y;
if (dg[x.first][x.second + 1] > dd) {
dg[x.first][x.second + 1] = dd;
q.push(make_pair(-dd, make_pair(x.first, x.second + 1)));
}
}
if (a[x.first].y + b[x.second].x >= w) {
if (dg[n][0] > d) {
dg[n][0] = d;
q.push(make_pair(-d, make_pair(n, 0)));
}
}
pair<LD, int>* nn = nei[x.first];
for (int i = 0, j = 0; j < m && i + 1 < n; ) {
if (nn[i].first - 1e-8 > b[x.second].x + b[j].x) {
++j;
continue;
}
LL dd = d + b[j].y;
if (dg[nn[i].second][j] > dd) {
dg[nn[i].second][j] = dd;
q.push(make_pair(-dd, make_pair(nn[i].second, j)));
}
++i;
}
}
/*
for (int i = 0; i < n; ++i) {
cerr << a[i].x << "," << a[i].y << ": ";
for (int j = 0; j < m; ++j) {
if (dg[i][j] < 1e9) {
cerr << dg[i][j] << " ";
} else {
cerr << "inf ";
}
}
cerr << endl;
}
*/
if (ans == -1) {
puts("impossible");
} else {
cout << ans << endl;
}
}
return 0;
}
|
#include <bits/stdc++.h>
#define REP(i, a, n) for(ll i = ((ll) a); i < ((ll) n); i++)
using namespace std;
typedef long long ll;
/* 1-indexed, [(1, 1), (m, n)] */
template<typename T> class BinaryIndexedTree2D {
vector< vector<T> > vec;
const ll m, n;
public:
BinaryIndexedTree2D(ll _m, ll _n) : vec(_m + 1, vector<T>(_n + 1)), m(_m), n(_n) {}
T query(ll y, ll x) { /* query for [(1, 1), (y, x)] */
T ret = 0;
for(ll i = y; i > 0; i -= i & (-i))
for(ll j = x; j > 0; j -= j & (-j))
ret += vec[i][j];
return ret;
}
void update(ll y, ll x, T k) { /* update for [(1, 1,), (y, x)] */
for(ll i = y; i <= m; i += i & (-i))
for(ll j = x; j <= n; j += j & (-j))
vec[i][j] += k;
}
};
int main(void) {
BinaryIndexedTree2D<ll> bit(5, 4);
REP(i, 0, 5) REP(j, 0, 4) bit.update(i + 1, j + 1, i * j);
cout << bit.query(3, 3) << endl; // 9
cout << bit.query(5, 4) << endl; // 60
bit.update(3, 4, -6);
cout << bit.query(5, 4) << endl; // 54
}
|
#pragma once
#include <PravLib/type_list.h>
#include <lexer/literal_token.hpp>
#include <lexer/rule_token.hpp>
namespace prv {
namespace lex {
template <class Derived, class TokenSpec>
struct identifier_token : rule_token<Derived, TokenSpec> {
static constexpr const char* name = "<identifier>";
};
template <class Token>
struct is_identifier_token : detail::is_token_impl<identifier_token, Token>::value {
};
template <class Token>
struct is_non_identifier_rule_token : std::integral_constant<bool, is_rule_token<Token>::value && !is_identifier_token<Token>::value> {
};
template <char... Char>
struct keyword_token : literal_token<Char...> {
};
#define PRV_LEX_KEYWORD(String) \
PRV_LEX_DETAIL_STRING(prv::lex::keyword_token, String)
template <class Token>
struct is_keyword_token : detail::is_literal_token_impl<keyword_token, Token>::value {
};
template <class Token>
struct is_non_keyword_literal_token : std::integral_constant<bool, is_literal_token<Token>::value && !is_keyword_token<Token>::value> {
};
} // namespace lex
} // namespace prv
|
#include "ProfessionsService.h"
#include <QJsonArray>
#include "Requester/Requester.h"
// :: Constants ::
const QString GET_PROFESSIONS_API = "users/professions";
// :: Lifecycle ::
ProfessionsService::ProfessionsService(QObject *parent)
: BaseService(parent) { }
// :: Public methods ::
void ProfessionsService::getProfessions() const {
auto requester = makeRequesterWithDefaultErrorOutput();
connect(requester, SIGNAL(success(QJsonArray)),
SLOT(onProfessionsJsonGot(QJsonArray)));
requester->sendRequest(GET_PROFESSIONS_API);
}
void ProfessionsService::getProfessions(const std::function<void (const QStringList &)> &receiver) {
auto service = new ProfessionsService();
connect(service, &ProfessionsService::professionsGot, receiver);
connect(service, &ProfessionsService::error,
[receiver](){ receiver(QStringList()); });
connect(service, &ProfessionsService::professionsGot,
service, &ProfessionsService::deleteLater);
connect(service, &ProfessionsService::error,
service, &ProfessionsService::deleteLater);
service->getProfessions();
}
// :: Private slots ::
void ProfessionsService::onProfessionsJsonGot(const QJsonArray &jsonProfessions) const {
QStringList professions;
for (const auto &jsonValue : jsonProfessions) {
if (jsonValue.isString()) {
professions.append(jsonValue.toString());
}
}
emit professionsGot(professions);
}
|
#include "rectangle.hpp"
#include "rectangle.cpp"
#include "gtest/gtest.h"
//CONSTRUCTOR TEST SUITE
TEST(ConstructorTest, NoParameterHeight){
Rectangle rect1;
EXPECT_EQ(rect1.get_height(), 0);
}
TEST(ConstructorTest, NoParameterWidth){
Rectangle rect1;
EXPECT_EQ(rect1.get_width(), 0);
}
TEST(ConstructorTest, ParameterHeight){
Rectangle rect1(2,5);
EXPECT_EQ(rect1.get_height(), 5);
}
TEST(ConstructorTest, ParameterWidth){
Rectangle rect1(2,5);
EXPECT_EQ(rect1.get_width(), 2);
}
TEST(ConstructorTest, NegParameterWidth){
Rectangle rect1(-2,5);
EXPECT_EQ(rect1.get_width(), -2);
}
TEST(ConstructorTest, 0ParameterHeight){
Rectangle rect1(2,0);
EXPECT_EQ(rect1.get_height(), 0);
}
//AREA TEST SUITE
TEST(AreaTest, NoParameter){
Rectangle rect1;
EXPECT_EQ(rect1.area(), 0);
}
TEST(AreaTest, Parameter){
Rectangle rect1(3,6);
EXPECT_EQ(rect1.area(), 18);
}
TEST(AreaTest, NegParameter){
Rectangle rect1(-3,6);
EXPECT_EQ(rect1.area(), -18);
}
TEST(AreaTest, 0Parameter){
Rectangle rect1(0,6);
EXPECT_EQ(rect1.area(), 0);
}
TEST(AreaTest, DoubleNegParameter){
Rectangle rect1(-3,-4);
EXPECT_EQ(rect1.area(), 12);
}
//PERIMETER TEST SUITE
TEST(PerimeterTest, NoParameter){
Rectangle rect1;
EXPECT_EQ(rect1.perimeter(), 0);
}
TEST(PerimeterTest, Parameter){
Rectangle rect1(1, 8);
EXPECT_EQ(rect1.perimeter(), 18);
}
TEST(PerimeterTest, NegParameter){
Rectangle rect1(-5,9);
EXPECT_EQ(rect1.perimeter(), 8);
}
TEST(PerimeterTest, 0Parameter){
Rectangle rect1(13,0);
EXPECT_EQ(rect1.perimeter(), 26);
}
TEST(PerimeterTest, DoubleNegParameter){
Rectangle rect1(-3,-9);
EXPECT_EQ(rect1.perimeter(), -24);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/**
* Copyright 2008 Matthew Graham
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdopt/configuration.h"
using namespace stdopt;
configuration_c::configuration_c()
: m_option()
, m_error( false )
{}
void configuration_c::add( config_option_i &option )
{
m_option[ option.option_name() ] = &option;
}
void configuration_c::parse( std::istream &input )
{
std::string line;
std::string key_chunk;
std::string value_chunk;
std::string key;
std::string value;
while ( ! input.eof() ) {
// reset these for the next line
line.clear();
key_chunk.clear();
value_chunk.clear();
key.clear();
value.clear();
// separate the line into chunks broken by the first '='
getline( input, line );
std::istringstream line_parser( line );
getline( line_parser, key_chunk, '=' );
getline( line_parser, value_chunk );
// parse the key and values out of the chunks
std::istringstream key_parser( key_chunk );
std::istringstream value_parser( value_chunk );
key_parser >> key;
value_parser >> value;
if ( ! ( key.empty() || value.empty() ) ) {
option_map::iterator it( m_option.find( key ) );
if ( it == m_option.end() ) {
// std::cerr << "error";
return;
}
if ( value[ value.length() - 1 ] == '\r' ) {
value.erase( value.length() - 1 );
}
it->second->parse_value( value );
if ( it->second->error() ) {
m_error = true;
return;
}
}
}
}
|
/*
** EPITECH PROJECT, 2019
** OOP_indie_studio_2018
** File description:
** Bomb
*/
#ifndef BOMB_HPP_
#define BOMB_HPP_
#include <vector>
#include <iostream>
#include "Character.hpp"
class Bomb
{
public:
Bomb(int pos_x, int pos_y);
~Bomb();
void KillSomeone();
std::vector<std::string> explosion(std::vector<std::string> map);
protected:
private:
int _pos_x;
int _pos_y;
int _bombsize;
};
#endif /* !BOMB_HPP_ */
|
// Created by: Kirill GAVRILOV
// Copyright (c) 2013-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 OpenGl_VertexBuffer_HeaderFile
#define OpenGl_VertexBuffer_HeaderFile
#include <OpenGl_Buffer.hxx>
#include <Graphic3d_Buffer.hxx>
//! Vertex Buffer Object - is a general storage object for vertex attributes (position, normal, color).
//! Notice that you should use OpenGl_IndexBuffer specialization for array of indices.
class OpenGl_VertexBuffer : public OpenGl_Buffer
{
public:
//! Create uninitialized VBO.
Standard_EXPORT OpenGl_VertexBuffer();
//! Destroy object.
Standard_EXPORT virtual ~OpenGl_VertexBuffer();
//! Return buffer target GL_ARRAY_BUFFER.
Standard_EXPORT virtual unsigned int GetTarget() const Standard_OVERRIDE;
//! Bind this VBO to active GLSL program.
Standard_EXPORT void BindVertexAttrib (const Handle(OpenGl_Context)& theGlCtx,
const unsigned int theAttribLoc) const;
//! Unbind any VBO from active GLSL program.
Standard_EXPORT void UnbindVertexAttrib (const Handle(OpenGl_Context)& theGlCtx,
const unsigned int theAttribLoc) const;
//! Bind this VBO and enable specified attribute in OpenGl_Context::ActiveProgram() or FFP.
//! @param theGlCtx - handle to bound GL context;
//! @param theMode - array mode (GL_VERTEX_ARRAY, GL_NORMAL_ARRAY, GL_COLOR_ARRAY, GL_INDEX_ARRAY, GL_TEXTURE_COORD_ARRAY).
void BindAttribute (const Handle(OpenGl_Context)& theCtx,
const Graphic3d_TypeOfAttribute theMode) const
{
if (IsValid())
{
Bind (theCtx);
bindAttribute (theCtx, theMode, static_cast<int> (myComponentsNb), myDataType, 0, myOffset);
}
}
//! Unbind this VBO and disable specified attribute in OpenGl_Context::ActiveProgram() or FFP.
//! @param theCtx handle to bound GL context
//! @param theMode array mode
void UnbindAttribute (const Handle(OpenGl_Context)& theCtx,
const Graphic3d_TypeOfAttribute theMode) const
{
if (IsValid())
{
Unbind (theCtx);
unbindAttribute (theCtx, theMode);
}
}
public: //! @name advanced methods
//! Setup array pointer - either for active GLSL program OpenGl_Context::ActiveProgram()
//! or for FFP using bindFixed() when no program bound.
Standard_EXPORT static void bindAttribute (const Handle(OpenGl_Context)& theGlCtx,
const Graphic3d_TypeOfAttribute theMode,
const Standard_Integer theNbComp,
const unsigned int theDataType,
const Standard_Integer theStride,
const void* theOffset);
//! Disable GLSL array pointer - either for active GLSL program OpenGl_Context::ActiveProgram()
//! or for FFP using unbindFixed() when no program bound.
Standard_EXPORT static void unbindAttribute (const Handle(OpenGl_Context)& theGlCtx,
const Graphic3d_TypeOfAttribute theMode);
private:
//! Setup FFP array pointer.
Standard_EXPORT static void bindFixed (const Handle(OpenGl_Context)& theGlCtx,
const Graphic3d_TypeOfAttribute theMode,
const Standard_Integer theNbComp,
const unsigned int theDataType,
const Standard_Integer theStride,
const void* theOffset);
//! Disable FFP array pointer.
Standard_EXPORT static void unbindFixed (const Handle(OpenGl_Context)& theGlCtx,
const Graphic3d_TypeOfAttribute theMode);
//! Disable FFP color array pointer.
Standard_EXPORT static void unbindFixedColor (const Handle(OpenGl_Context)& theCtx);
public: //! @name methods for interleaved attributes array
//! @return true if buffer contains per-vertex color attribute
Standard_EXPORT virtual bool HasColorAttribute() const;
//! @return true if buffer contains per-vertex normal attribute
Standard_EXPORT virtual bool HasNormalAttribute() const;
//! Bind all vertex attributes to active program OpenGl_Context::ActiveProgram() or for FFP.
//! Default implementation does nothing.
Standard_EXPORT virtual void BindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const;
//! Bind vertex position attribute only. Default implementation does nothing.
Standard_EXPORT virtual void BindPositionAttribute (const Handle(OpenGl_Context)& theGlCtx) const;
//! Unbind all vertex attributes. Default implementation does nothing.
Standard_EXPORT virtual void UnbindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const;
public:
DEFINE_STANDARD_RTTIEXT(OpenGl_VertexBuffer, OpenGl_Buffer)
};
DEFINE_STANDARD_HANDLE(OpenGl_VertexBuffer, OpenGl_Buffer)
#endif // _OpenGl_VertexBuffer_H__
|
#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include <stdint.h>
#include <inttypes.h>
#include <math.h>
#include "tusb.h"
extern int32_t sin_table[64];
uint64_t from;
void start() { from = time_us_64(); }
void elapsed()
{
uint64_t now = time_us_64();
printf("Elapsed %" PRIu64 " us\n", now - from);
}
int main()
{
stdio_init_all();
while(!tud_cdc_connected()) sleep_ms(250);
//getchar();
puts("\nUsing sine table");
start();
for(int i = 0; i<64; i++) {
volatile int32_t x = sin_table[i];
}
elapsed(); // 12us, or 0.1875us per calc
puts("\nUsing sin() function");
start();
for(int i = 0; i<64; i++) {
volatile float f = sin(i);
};
elapsed(); // 1013us, or 15.8us per calc (expensive!)
puts("\n100 x 100 using floats");
volatile float f1 = 00.0, f2 = 100.0;
start();
for(int i = 0; i< 1000; i++) {
volatile float f = f1 * f2;
}
elapsed(); // 737us, or 0.74us per calc
puts("\n100 x 100 using fixed point");
volatile int32_t i1 = 100 << 7, i2 = 100 << 7, res1;
start();
for(int i = 0; i< 1000; i++) {
res1 = (i1 * i2) >> 7;
}
elapsed(); // 99us, or 0.099us per calc
printf("... expecting 10000: %d\n", res1 >> 7);
assert(false); // doesn't actually assert
puts("\nFinished tests. Halting");
for(;;);
return 0;
}
|
// Created on: 1994-12-22
// Created by: Remi LEQUETTE
// Copyright (c) 1994-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 _BRepTools_Quilt_HeaderFile
#define _BRepTools_Quilt_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <TopTools_IndexedDataMapOfShapeShape.hxx>
class TopoDS_Edge;
class TopoDS_Vertex;
class TopoDS_Shape;
//! A Tool to glue faces at common edges and reconstruct shells.
//!
//! The user designate pairs of common edges using the method Bind.
//! One edge is designated as the edge to use in place of the other one
//! (they are supposed to be geometrically confused, but this not checked).
//! They can be of opposite directions, this is specified by the orientations.
//!
//! The user can add shapes with the Add method, all the faces are registered and copies of faces
//! and edges are made to glue at the bound edges.
//!
//! The user can call the Shells methods to compute a compound of shells from the current set of faces.
//!
//! If no binding is made this class can be used to make shell from faces already sharing their edges.
class BRepTools_Quilt
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT BRepTools_Quilt();
//! Binds <Enew> to be the new edge instead of
//! <Eold>.
//!
//! The faces of the added shape containing <Eold>
//! will be copied to substitute <Eold> by <Enew>.
//!
//! The vertices of <Eold> will be bound to the
//! vertices of <Enew> with the same orientation.
//!
//! If <Eold> and <Enew> have different orientations
//! the curves are considered to be opposite and the
//! pcurves of <Eold> will be copied and reversed in
//! the new faces.
//!
//! <Eold> must belong to the next added shape, <Enew> must belong
//! to a Shape added before.
Standard_EXPORT void Bind (const TopoDS_Edge& Eold, const TopoDS_Edge& Enew);
//! Binds <VNew> to be a new vertex instead of <Vold>.
//!
//! The faces of the added shape containing <Vold>
//! will be copied to substitute <Vold> by <Vnew>.
Standard_EXPORT void Bind (const TopoDS_Vertex& Vold, const TopoDS_Vertex& Vnew);
//! Add the faces of <S> to the Quilt, the faces
//! containing bounded edges are copied.
Standard_EXPORT void Add (const TopoDS_Shape& S);
//! Returns True if <S> has been copied (<S> is a
//! vertex, an edge or a face)
Standard_EXPORT Standard_Boolean IsCopied (const TopoDS_Shape& S) const;
//! Returns the shape substituted to <S> in the Quilt.
Standard_EXPORT const TopoDS_Shape& Copy (const TopoDS_Shape& S) const;
//! Returns a Compound of shells made from the current
//! set of faces. The shells will be flagged as closed
//! or not closed.
Standard_EXPORT TopoDS_Shape Shells() const;
protected:
private:
TopTools_IndexedDataMapOfShapeShape myBounds;
Standard_Boolean hasCopy;
};
#endif // _BRepTools_Quilt_HeaderFile
|
// ___________________________________________________________________________
// ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
// FILE docwin_mousewheel.h
// CREATED
//
// DESCRIPTION
// ___________________________________________________________________________
// ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
//
#ifndef _DOCWIN_MOUSEWHEEL_H_INCLUDED__323219
#define _DOCWIN_MOUSEWHEEL_H_INCLUDED__323219
class OpView;
class OpWindowCommander;
void DocWin_HandleIntelliMouseWheelDown(OpWindowCommander* commander, OpView* view);
BOOL DocWin_HandleIntelliMouseMessages(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
BOOL IsPanning();
void SetPanningBeingActivated(BOOL state);
BOOL PanningBeingActivated();
#endif // _DOCWIN_MOUSEWHEEL_H_INCLUDED__323219 undefined
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Genius.h"
#include "LightsGrid.h"
#include "Lights.h"
// Sets default values
ALightsGrid::ALightsGrid()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
Root = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
RootComponent = Root;
ConstructorHelpers::FObjectFinder<UBlueprint> BlueBP(TEXT("Blueprint'/Game/Blueprint/Blue_BP.Blue_BP'"));
ConstructorHelpers::FObjectFinder<UBlueprint> YellowBP(TEXT("Blueprint'/Game/Blueprint/Yellow_BP.Yellow_BP'"));
ConstructorHelpers::FObjectFinder<UBlueprint> RedBP(TEXT("Blueprint'/Game/Blueprint/Red_BP.Red_BP'"));
ConstructorHelpers::FObjectFinder<UBlueprint> GeenBP(TEXT("Blueprint'/Game/Blueprint/Green_BP.Green_BP'"));
if(BlueBP.Succeeded()){
Blue = Cast<UClass>(BlueBP.Object->GeneratedClass);
}
if(YellowBP.Succeeded()){
Yellow = Cast<UClass>(YellowBP.Object->GeneratedClass);
}
if(RedBP.Succeeded()){
Red = Cast<UClass>(RedBP.Object->GeneratedClass);
}
if(GeenBP.Succeeded()){
Green = Cast<UClass>(GeenBP.Object->GeneratedClass);
}
}
// Called when the game starts or when spawned
void ALightsGrid::BeginPlay()
{
Super::BeginPlay();
/*
float LocationX = 0.0f;
float LocationZ = 0.0f;
UWorld* World = GetWorld();
if (World != nullptr) {
for (int i = 0; i < 4; i++){
FVector Location(LocationX, 0.0f, LocationZ);
FActorSpawnParameters SpawnParameters;
switch (i) {
case 0:
ALights* Light = World->SpawnActor<ALights>(Blue, Location, FRotator::ZeroRotator, SpawnParameters);
LocationX += 250.0f;
break;
case 1:
ALights* Light = World->SpawnActor<ALights>(Yellow, Location, FRotator::ZeroRotator, SpawnParameters);
LocationX += 250.0f;
break;
case 2:
ALights* Light = World->SpawnActor<ALights>(Red, Location, FRotator::ZeroRotator, SpawnParameters);
LocationX += 250.0f;
break;
case 3:
ALights* Light = World->SpawnActor<ALights>(Green, Location, FRotator::ZeroRotator, SpawnParameters);
LocationX += 250.0f;
break;
}
if (i == 1) { LocationZ -= 250.0f; LocationX = 0;}
}
}
*/
}
// Called every frame
void ALightsGrid::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
|
#include "LeftMouseButtonEvent.hpp"
int LeftMouseButtonEvent::getButtonDownCode() {
return MOUSEEVENTF_LEFTDOWN;
}
int LeftMouseButtonEvent::getButtonUpCode() {
return MOUSEEVENTF_LEFTUP;
}
|
#ifndef _ErrorMsg_
#define _ErrorMsg_
class RedisAccess;
class ErrorMsg
{
public:
static ErrorMsg* getInstance();
const char* getErrMsg(int code);
private:
ErrorMsg();
virtual ~ErrorMsg();
public:
void init(const char* file = "");
void initFromBuf(const char *pErrMsg);
bool initFromRedis(RedisAccess &redis, const char* gametag);
private:
bool binit;
};
#define _EMSG_(code) ErrorMsg::getInstance()->getErrMsg(code)
#define ERRMSG(code) ErrorMsg::getInstance()->getErrMsg(code)
#endif
|
#include "Variable.h" // Подключение файла, для работы с токенами и переменными.
int fact(int n) // Функция для вычисления факториала числа.
{ //
if (n < 0) // Если число меньше 0
return 0; // то возвращаем 0.
if (n == 0) // Если число равно 0
return 1; // то возвращаем 1.
else // Иначе
return n * fact(n - 1); // рекурсивно вычисляем факториал.
} //
double expression() // Функция для вычисления выражения.
{ //
double left = term(); // Вызов функции для вычисления левого операнда.
Token t = ts.get(); // Счёт следующего токена.
while (true) //
{ //
switch (t.kind) //
{ //
case '+': // Если потом слудует знак '+'
left += term(); // то выполняем сложение с правым операндом.
t = ts.get(); //
break; //
case '-': // Если потом слудует знак '-'
left -= term(); // то выполняем вычитание с правым операндом.
t = ts.get(); //
break; //
default: //
ts.putback(t); // В иных случаях возвращаем лишь
return left; // значение левого операнда.
} //
} //
} //
double term() // Функция для вычисления терма.
{ //
double left = primary(); // Вызов функции для вычисления левого операнда.
Token t = ts.get(); // Счёт следующего токена.
while (true) //
{ //
switch (t.kind) //
{ //
case '*': // Если потом слудует знак '*'
left *= primary(); // то выполняем умножение на правый операнд.
t = ts.get(); //
break; //
case '/': // Если потом слудует знак '/'
{ //
double d = primary(); // то вычисляем значение правого операнда.
if (d == 0) //
{ // Если оно равно 0,
error("Deviding by zero"); // то возвращаем ошибку.
} //
left /= d; // Иначе выполняем деление.
t = ts.get(); //
break; //
} //
case '%': // Если потом слудует знак '%'
{ //
int i1 = narrow_cast<int>(left); // то преобразуем левый
int i2 = narrow_cast<int>(primary()); // и правый операнды к целым числам.
if (i2 == 0) //
{ // Если правый операнд равен 0,
error("%: deviding by zero"); // то возвращаем ошибку.
} //
left = i1 % i2; // Иначе выполняем деление.
t = ts.get(); //
break; //
} //
default: //
ts.putback(t); // В иных случаях возвращаем лишь
return left; // значение левого операнда.
} //
} //
} //
double primary() // Функция для вычисления первисного значения.
{ //
Token t = ts.get(); // Считывание очередного токена.
switch (t.kind) //
{ // Если он является:
case '(': // скобкой,
{ //
double d = expression(); // то вычисляем вырежение в скобках.
t = ts.get(); // Если следующий токен
if (t.kind != ')') // не является скобкой -
{ //
error("')' is needed"); // возвращаем ошибку;
} //
return d; //
} //
case '@': // символом '@',
{ //
double d = primary(); // то вычисляем следующее первичное значение
if (d < 0) //
{ // Если оно меньше 0 -
error("sqrt: a negative number"); // возвращаем ошибку.
} //
return sqrt(d); // Иначе вычисляем корень.
} //
case '!': // символом '!',
{ //
int d = narrow_cast<int>(primary()); // то вычисляем следующее первичное значение и преобразуем его в целове число.
if (d < 0) //
{ // Если оно меньше 0 -
error("fact: a negative number"); // возвращаем ошибку.
} //
return fact(d); // Иначе вычисляем факториал;
} //
case number: // числом,
return t.value; // то возвращаем число;
case name: // переменной,
return get_value(t.name); // то возвращаем значение переменной;
case '-': // символом '-',
return -primary(); // то возвращаем отрицательное значение
case '+': // символом '+',
return primary(); // то возвращаем значение следующего первичного выражения.
default: // Во всех других случаях
error("expression is needed"); // возвращаем ошибку.
} //
} //
//
|
#ifndef OFXCOMMANDPATTERNTHREADWINH
#define OFXCOMMANDPATTERNTHREADWINH
#include "ofxCommand.h"
#include "ofxCommandProcessor.h"
#include "ofxCommandProcessorThread.h"
#include "ofxCommandProcessorThreadSync.h"
#include <boost/shared_ptr.hpp>
#if defined( __WIN32__ ) || defined( _WIN32 )
#include <windows.h>
#include <process.h>
#include "ofxCommandProcessorThreadSyncWin.h"
class ofxCommandProcessorThreadWin : public ofxCommandProcessor, public ofxCommandProcessorThread {
protected:
HANDLE thread_handle_;
bool thread_active_;
bool running_;
ofxCommandProcessorThreadSyncWin sync_;
public:
ofxCommandProcessorThreadWin();
virtual bool start() {
thread_handle_ = (HANDLE)_beginthread(threadProc,0,this);
return (thread_handle_ != NULL);
}
virtual void sleep(int nMillis);
virtual void join();
//virtual void enqueue(ofxCommand* pCommand);
virtual void enqueue(boost::shared_ptr<ofxCommand> pCommand);
virtual void remove(std::string sName);
virtual void clear();
virtual bool isReady();
virtual void update();
virtual void run();
protected:
static void threadProc(void* lParam) {
ofxCommandProcessorThreadWin* thread = (ofxCommandProcessorThreadWin*)lParam;
if(thread != NULL) {
thread->thread_active_ = true;
thread->run();
thread->thread_active_ = false;
}
_endthread();
}
//virtual ofxCommand* take();
//virtual ofxCommand* take();
boost::shared_ptr<ofxCommand> take();
};
#endif
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** 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.
**
*/
#include "core/pch.h"
#ifdef EXTERNAL_PROTOCOL_SCHEME_SUPPORT
//#define HELLO_WORLD_EPH
#include "modules/url/url_enum.h"
#include "modules/hardcore/mh/messages.h"
#include "modules/url/url_man.h"
#include "modules/url/url_rep.h"
#include "modules/url/url_ds.h"
#include "modules/url/url_pd.h"
#include "modules/url/loadhandler/url_eph.h"
URLType URL_Manager::AddProtocolHandler(const char* name, BOOL allow_as_security_context)
{
if(name == NULL)
return URL_NULL_TYPE;
const protocol_selentry *elm = GetUrlScheme(make_doublebyte_in_tempbuffer(name, op_strlen(name)), TRUE, TRUE, allow_as_security_context);
if (elm == NULL)
return URL_NULL_TYPE;
return elm->real_urltype;
}
BOOL URL_Manager::IsAnExternalProtocolHandler(URLType type)
{
const protocol_selentry *elm = LookUpUrlScheme(type);
return elm && elm->is_external;
}
ExternalProtocolLoadHandler::ExternalProtocolLoadHandler(URL_Rep *url_rep, MessageHandler *mh, URLType type) : URL_LoadHandler(url_rep, mh)
{
buffer.SetIsFIFO();
URL_DataStorage *url_ds = url_rep->GetDataStorage();
if(url_ds && url_ds->GetMessageHandlerList())
{
MsgHndlList::Iterator itr = url_ds->GetMessageHandlerList()->Begin();
MsgHndlList::ConstIterator end = url_ds->GetMessageHandlerList()->End();
for(; (mh == NULL || mh->GetWindow() == NULL) && itr != end; ++itr)
mh = (*itr)->GetMessageHandler();
}
if( !mh || !mh->GetWindow() )
window = NULL;
else
window = mh->GetWindow();
protocol_handler = OP_NEW(GogiProtocolHandler, ( type ));
}
ExternalProtocolLoadHandler::~ExternalProtocolLoadHandler()
{
OP_DELETE(protocol_handler);
}
void ExternalProtocolLoadHandler::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
}
CommState ExternalProtocolLoadHandler::Load()
{
// FIXME:OOM-KILSMO
protocol_handler->StartLoading(url->GetAttribute(URL::KName_Username_Password_Escaped_NOT_FOR_UI).CStr(), this, window,url->GetContextId());
return COMM_LOADING;
}
unsigned ExternalProtocolLoadHandler::ReadData(char *buf, unsigned len)
{
return buffer.ReadDataL((byte *) buf, len);
}
void ExternalProtocolLoadHandler::DeleteComm()
{
}
OP_STATUS ExternalProtocolLoadHandler::DataAvailable(void* data, UINT32 data_len)
{
TRAPD(op_err, buffer.AddContentL((const byte *) data, data_len));
mh->PostMessage(MSG_COMM_DATA_READY, Id(), 0);
return op_err;
}
void ExternalProtocolLoadHandler::LoadingFinished(unsigned int status)
{
url->SetAttribute(URL::KHTTP_Response_Code, status);
mh->PostMessage(MSG_COMM_LOADING_FINISHED, Id(), 0);
}
void ExternalProtocolLoadHandler::LoadingFailed(OP_STATUS error_code, unsigned int status)
{
url->SetAttribute(URL::KHTTP_Response_Code, status);
mh->PostMessage(MSG_COMM_LOADING_FINISHED, Id(), 0);
}
OP_STATUS ExternalProtocolLoadHandler::SetMimeType(const char* mime_type)
{
// We need to set both content type and mime type?
if (mime_type)
{
if( op_strstr( mime_type, "text/" ) == mime_type )
url->SetAttribute(URL::KUnique, TRUE);
return url->SetAttribute(URL::KMIME_ForceContentType, mime_type);
}
return OpStatus::ERR_NULL_POINTER;
}
#endif // EXTERNAL_PROTOCOL_SCHEME_SUPPORT
|
#ifndef LOGGING_HPP
#define LOGGING_HPP
#include <string>
#include "settings.hpp"
#include <boost/log/trivial.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/global_logger_storage.hpp>
#include <boost/log/attributes/named_scope.hpp>
#include <boost/format.hpp>
namespace sp
{
void setup_logging(const settings& st);
typedef boost::format bf;
}
BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(__logger, boost::log::sources::severity_logger<boost::log::trivial::severity_level>)
#define LOG_TRACE BOOST_LOG_SEV(__logger::get(), boost::log::trivial::trace)
#define LOG_DEBUG BOOST_LOG_SEV(__logger::get(), boost::log::trivial::debug)
#define LOG_INFO BOOST_LOG_SEV(__logger::get(), boost::log::trivial::info)
#define LOG_WARNING BOOST_LOG_SEV(__logger::get(), boost::log::trivial::warning)
#define LOG_ERROR BOOST_LOG_SEV(__logger::get(), boost::log::trivial::error)
#define LOG_FATAL BOOST_LOG_SEV(__logger::get(), boost::log::trivial::fatal)
#endif // LOGGING_HPP
|
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QScrollArea> //容器
#include <QFileDialog>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void selectFileDir();
void showPicture();
private:
QLabel *le;
QLineEdit *led;
QPushButton *but1;
QPushButton *but2;
QScrollArea *sca;
};
#endif // WIDGET_H
|
//======================================================================
// Name: Snake.h
// Author: Will Blades
// Function: Class storing the actual snake in the game with its
// relevant member functions. Food items and relative functions
// are also stored in the same class as they make use of the
// the same struct (axis)
//======================================================================
#include <vector>
#include <iostream>
#include "SDL.h"
#ifndef SNAKE_H
#define SNAKE_H
// Defines snake body & food texture size
#define TileIncrement 15
// Screen dimensions defined relative to texture size
#define MAX_WIDTH TileIncrement * 20
#define MAX_HEIGHT TileIncrement * 20
typedef struct axis
{
int xposition;
int yposition;
}axis;
class Snake
{
public:
Snake();
~Snake();
void Move();
void IncrementSnakeSize();
void ChangeDirection(int heading);
bool DetectCollision();
bool FoodDetected();
void NewFood();
std::vector<axis> get_body();
axis get_food();
SDL_Surface* headTexture;
SDL_Surface* bodyTexture;
SDL_Surface* foodTexture;
SDL_Surface* load_image(std::string filename);
private:
std::vector<axis> body;
axis food;
int head_xposition;
int head_yposition;
int direction;
};
#endif
|
#include<iostream>
using namespace std;
void function(int arr[],int size)
{
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
for(int i=0; i<size; i++)
{
for(int j=i+1; j<size; j++)
{
if(arr[j] < arr[i])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i=0;i<size;i++)
{
cout<<arr[i]<<" ";
}
}
int main()
{
int arr[100];
int size;
cout<<" Enter the size of the array : ";
cin>>size;
function(arr,size);
}
|
#include "stdafx.h"
#include "Act_Fire.h"
#include "../MonsterAction.h"
#include "../Monster.h"
#include "../../GameData.h"
Act_Fire::Act_Fire()
{
m_effect = NewGO<CEffect>(0, "eff");
m_ActionId = enFire;
}
bool Act_Fire::Action(Monster * me)
{
if (m_target == nullptr)
return true;
if (m_first)
{
me->anim_extra1();
float mp = me->GetMP();
if (mp < 20)
return true;
mp -= 20;
me->SetMP(mp);
m_pos = m_target->Getpos();
/*CVector3 sc = CVector3::One();
sc *= 5;*/
m_effect->SetScale(m_efs);
m_effect->SetPosition(m_pos);
m_effect->Play(L"Assets/effect/fire1/fire1.efk");
Sound* sound = NewGO<Sound>(0, "snd");
sound->Init(L"Assets/sound/fire2.wav");
sound->Play();
CVector3 v = m_target->Getpos() - me->Getpos();
float cta = atan2f(v.x, v.z);
CQuaternion rot;
rot.SetRotation(CVector3::AxisY(), cta);
me->SetRotation(rot);
m_first = false;
}
else if (!me->isAnimPlay())
{
me->anim_idle();
}
if (m_timer <= m_limit)
{
for (auto mon : g_mons)
{
if (mon == NULL)
break;
CVector3 len = m_pos - mon->Getpos();
if (len.Length() < 25*m_efs.x)
{
mon->DamageEx(me->GetExAttack()* 0.2/3.f);
}
}
m_efs += {0.02f, 0.02f, 0.02f};
m_effect->SetScale(m_efs);
m_timer += IGameTime().GetFrameDeltaTime();
}
else
{
return true;
}
return false;
}
|
/**
* Copyright (c) 2020, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "all_logs_vtab.hh"
#include "base/attr_line.hh"
#include "config.h"
#include "data_parser.hh"
static auto intern_lifetime = intern_string::get_table_lifetime();
all_logs_vtab::all_logs_vtab()
: log_vtab_impl(intern_string::lookup("all_logs")),
alv_msg_meta(intern_string::lookup("log_msg_format"),
value_kind_t::VALUE_TEXT,
logline_value_meta::table_column{0}),
alv_schema_meta(intern_string::lookup("log_msg_schema"),
value_kind_t::VALUE_TEXT,
logline_value_meta::table_column{1})
{
this->alv_msg_meta.lvm_identifier = true;
this->alv_schema_meta.lvm_identifier = true;
}
void
all_logs_vtab::get_columns(std::vector<vtab_column>& cols) const
{
cols.emplace_back(
vtab_column(this->alv_msg_meta.lvm_name.get())
.with_comment(
"The message format with variables replaced by hash marks"));
cols.emplace_back(this->alv_schema_meta.lvm_name.get(),
SQLITE3_TEXT,
"",
true,
"The ID for the message schema");
}
void
all_logs_vtab::extract(logfile* lf,
uint64_t line_number,
logline_value_vector& values)
{
auto& line = values.lvv_sbr;
auto* format = lf->get_format_ptr();
logline_value_vector sub_values;
this->vi_attrs.clear();
sub_values.lvv_sbr = line;
format->annotate(line_number, this->vi_attrs, sub_values, false);
auto body = find_string_attr_range(this->vi_attrs, &SA_BODY);
if (body.lr_start == -1) {
body.lr_start = 0;
body.lr_end = line.length();
}
data_scanner ds(
line.to_string_fragment().sub_range(body.lr_start, body.lr_end));
data_parser dp(&ds);
std::string str;
dp.dp_msg_format = &str;
dp.parse();
values.lvv_values.emplace_back(this->alv_msg_meta, std::move(str));
values.lvv_values.emplace_back(this->alv_schema_meta,
dp.dp_schema_id.to_string());
}
bool
all_logs_vtab::next(log_cursor& lc, logfile_sub_source& lss)
{
return true;
}
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#ifndef BAJKA_IDEVICE_H_
#define BAJKA_IDEVICE_H_
#include <core/Object.h>
#include <util/ReflectionMacros.h>
namespace Sound {
/**
* Główna klasa inicjująca system.
*/
class IDevice : public Core::Object {
public:
d__
virtual ~IDevice () {}
/**
* Inicjuje. Można podać wejściowe dane potrzebne konkretnej implementacji. Na androidzie
* będzie to android_app.
*/
m_ (init)
virtual void init () = 0;
/**
* Debugowe informacje.
*/
virtual void printInfo () = 0;
E_ (IDevice)
};
} /* namespace Sound */
#endif /* IDEVICE_H_ */
|
/*
* Copyright (c) 2011 Dan Wilcox <danomatika@gmail.com>
*
* BSD Simplified License.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*
* See https://github.com/danomatika/ofxAppUtils for documentation
*
*/
#include "testApp.h"
#include "scenes/scenes.h"
//--------------------------------------------------------------
void testApp::setup() {
// setup for nice jaggy-less rendering
ofSetVerticalSync(true);
ofBackground(0, 0, 0);
// setup the render size (working area)
setRenderSize(600, 400);
// turn on transform origin translation and scaling to screen size,
// disable quad warping, and enable aspect ratio and centering when scaling
setTransforms(true, true, false, true, true);
// the control panel is setup automatically, of course you can still change
// all the settings manually here
// add the built in transform control to control panel (adds new panel)
//
// loads and saves control panel settings to "controlPanelSettings.xml"
// in the data folder
addTransformControls();
// load saved control panel settings
// loads and saves to "controlPanelSettings.xml" in the data folder
// or use your own filename
// note: this may override what was set with setTransforms
loadControlSettings();
// load saved quad warper settings
// loads and saves to "quadWarper.xml" in the data folder
// or use your own filename
loadWarpSettings();
// load scenes
particleScene = (ParticleScene*) sceneManager.add(new ParticleScene()); // save pointer
sceneManager.add(new LineScene());
sceneManager.setup(true); // true = setup all the scenes now (not on the fly)
ofSetLogLevel("ofxSceneManager", OF_LOG_VERBOSE); // lets see whats going on inside
// start with a specific scene
// set now to true in order to ignore the scene fade and change now
sceneManager.gotoScene("Lines", true);
lastScene = sceneManager.getCurrentSceneIndex();
// attach scene manager to this ofxApp so it's called automatically,
// you can also call the callbacks (update, draw, keyPressed, etc) manually
// if you don't set it
//
// you can also turn off the auto sceneManager update and draw calls with:
// setSceneManagerUpdate(false);
// setSceneManagerDraw(false);
//
// the input callbacks in your scenes will be called if they are implemented
//
setSceneManager(&sceneManager);
}
//--------------------------------------------------------------
void testApp::update() {
// the control panel and current scene are automatically updated before
// this function
}
//--------------------------------------------------------------
void testApp::draw() {
// the current scene is automatically drawn before this function
// show the render area edges with a white rect
if(bDebug) {
ofNoFill();
ofSetColor(255);
ofSetRectMode(OF_RECTMODE_CORNER);
ofRect(1, 1, getRenderWidth()-2, getRenderHeight()-2);
ofFill();
}
// drop out of the auto transform space back to OF screen space
popTransforms();
// draw current scene info using the ofxBitmapString stream interface
// to ofDrawBitmapString
ofSetColor(200);
ofxBitmapString(12, ofGetHeight()-8)
<< "Current Scene: " << sceneManager.getCurrentSceneIndex()
<< " " << sceneManager.getCurrentSceneName() << endl;
// go back to the auto transform space
//
// this is actually done automatically if the transforms were popped
// before the control panel is drawn, but included here for completeness
pushTransforms();
// the control panel and warp editor are drawn automatically after this
// function
}
// current scene input functions are called automatically before calling these
//--------------------------------------------------------------
void testApp::keyPressed(int key) {
switch (key) {
case 'd':
bDebug = !bDebug;
break;
case 'a':
setAspect(!getAspect());
break;
case 'c':
setCentering(!getCentering());
break;
case 'm':
setMirrorX(!getMirrorX());
break;
case 'n':
setMirrorY(!getMirrorY());
break;
case 'q':
setWarp(!getWarp());
break;
case 'f':
ofToggleFullscreen();
break;
case OF_KEY_LEFT:
sceneManager.prevScene();
break;
case OF_KEY_RIGHT:
sceneManager.nextScene();
break;
case OF_KEY_DOWN:
if(sceneManager.getCurrentScene()) { // returns NULL if no scene selected
lastScene = sceneManager.getCurrentSceneIndex();
}
sceneManager.noScene();
break;
case OF_KEY_UP:
sceneManager.gotoScene(lastScene);
break;
case '-':
if(sceneManager.getCurrentScene() == particleScene) {
particleScene->removeOneParticle();
}
break;
case '=':
if(sceneManager.getCurrentScene() == particleScene) {
particleScene->addOneParticle();
}
break;
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key) {
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y) {
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h) {
// set up transforms with new screen size
setNewScreenSize(w, h);
}
|
#include "LightningTower.h"
#include <glm/gtx/rotate_vector.hpp>
LightningTower::LightningTower(glm::vec3 p) : Tower(LIGHTNINGTOWERCOOLDOWN, LIGHTNINGTOWERRANGE, LIGHTNINGTOWERPRICE, p) {
texture = "LightningTower";
firing = false;
}
LightningTower::~LightningTower()
{
}
void LightningTower::update(double dTime, vector<Enemy*> enemies, vector<Projectile*> *projectiles) {
Tower::update(dTime, enemies, projectiles);
//check if there is an enemy in range and the tower can shoot
Enemy *enemy = findEnemyInRange(enemies);
if (enemy != nullptr && canShoot()) {
//if so, calculate collision and set firing to true, then iterate over enemies to check for collisions
firing = true;
direction = glm::vec2(glm::normalize(position - enemy->getPosition()));
glm::vec3 lightningCollisionLine = position + glm::rotate(glm::vec3(range, 0, 0), (float)(atan2(direction.y, direction.x) * 180 / PI) - 180, glm::vec3(0, 0, 1));;
glm::vec3 collisionNormal = glm::normalize(lightningCollisionLine);
glm::vec3 centerOfLine = lightningCollisionLine / 2.0f;
//damage each enemy, if it is close enough to the lightningCollisionLine
for (int i = 0; i < enemies.size(); i++) {
glm::vec3 centerOfLineToEnemy = enemies[i]->getPosition() - centerOfLine;
glm::vec3 parallelComponent = glm::dot(centerOfLineToEnemy, collisionNormal) * collisionNormal;
glm::vec3 perpendicularComponent = centerOfLineToEnemy - parallelComponent;
float distanceTo = glm::distance(position, enemies[i]->getPosition());
if (glm::length(perpendicularComponent) < range/4 && glm::length(lightningCollisionLine) / 2 > glm::length(parallelComponent)) {//here, we treat the enemy as a circle
enemies[i]->damage(LIGHTNINGDAMAGE);
}
}
resetTimer();
}
else if (timer > LIGHTNINGTOWERCOOLDOWN / 10) { firing = false; }
}
void LightningTower::render(Renderer *renderer)
{
//setup transform matrix for tower
glm::mat4 translationMatrix = glm::translate(position);//translate by position
glm::mat4 scaleMatrix = glm::scale(scale);//scale by scale
glm::mat4 towerTransformationMatrix = translationMatrix * scaleMatrix;//combine transformations
//render tower
renderer->drawSprite(texture, towerTransformationMatrix);
//render lightning if firing
if (firing) {
//these are used by both the lightning texture and the explosion
//this adjusts the scale back to 1,1 from the towers scale, so rotation works properly
glm::mat4 adjustScale = glm::scale(glm::vec3(1 / scale.x, 1 / scale.y, 1 / scale.z));
//rotate according to direction
glm::mat4 orbitRotation = glm::rotate((float)(atan2(direction.y, direction.x) * 180 / PI) - 180, glm::vec3(0, 0, 1));//rotate according to direction
//setup transformations for lightning and then draw
glm::mat4 orbitTranslation = glm::translate(glm::vec3(range/2, 0, 0));//rotate half way out so the sprite is centered
glm::mat4 rotateInPlace = glm::rotate(-90.0f, glm::vec3(0, 0, 1));//adjust it so its not the wrong way around
scaleMatrix = glm::scale(glm::vec3(range/4, range, 1));//scale based on range
glm::mat4 lightningTransformationMatrix = towerTransformationMatrix * adjustScale * orbitRotation * orbitTranslation * rotateInPlace * scaleMatrix;
renderer->drawSprite("lightning1", lightningTransformationMatrix);
//setup transformations for explosion and then draw
orbitTranslation = glm::translate(glm::vec3(range, 0, 0));//translate all the way out
scaleMatrix = glm::scale(glm::vec3(0.1));//scale down
glm::mat4 explosionTransformationMatrix = towerTransformationMatrix * adjustScale * orbitRotation * orbitTranslation * scaleMatrix;
renderer->drawExplosion("lightning2", explosionTransformationMatrix, timer * LIGHTNINGTOWERCOOLDOWN * 10);
}
}
|
//
// Created by Vladimir on 1/20/2020.
//
#ifndef COP_3530__ALGORITHMS__PROTOTYPES_H
#define COP_3530__ALGORITHMS__PROTOTYPES_H
//Prototype Functions (gives the compiler a heads up about the upcoming function):
void navigate_list_forward(node **front);
void navigate_list_backwards(node **rear);
int get_list_size(node **front);
void insert_front(node **front, node **rear, std::string data);
void insert_front_p(node **front, node **rear, void *data);
void insert_rear(node **front, node **rear, std::string data);
void insert_rear_p(node **front, node **rear, void *data);
std::string remove_front_i(node **front, node **rear);
void *remove_front_p(pointer_node **front, pointer_node **rear);
std::string remove_rear_i(node **front, node **rear);
void *remove_rear_p(pointer_node **p_front, pointer_node **p_rear);
bool empty(node **front, bool output_text);
void empty_list(node **front, node **rear);
void reverse_list(node **front, node **rear);
void read_file(node **front, node **rear, const std::string& file_name);
void make_alphanumeric(node **front, node **rear);
#endif //COP_3530__ALGORITHMS__PROTOTYPES_H
|
class ItemPlasticWaterbottleUnfilled : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottleEmpty.paa";
displayName = $STR_EQUIP_NAME_WBPET_01;
descriptionShort = $STR_EQUIP_DESC_WBPET_01;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
class ItemActions
{
class Fill
{
text = $STR_ACTIONS_FILL_W;
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottleDmg : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "z\addons\dayz_communityassets\models\waterbottle_damaged.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottleDamaged.paa";
displayName = $STR_EQUIP_NAME_WBPET_02;
descriptionShort = $STR_EQUIP_DESC_WBPET_02;
sfx = "bandage";
class ItemActions
{
class Crafting
{
text = $STR_ACTIONS_FIX_W;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {};
requiretools[] = {};
output[] = {{"ItemPlasticWaterbottleUnfilled",1}};
input[] = {{"ItemPlasticWaterbottleDmg",1},{"equip_duct_tape",1}};
};
};
};
class ItemPlasticWaterBottle : ItemWaterBottle
{
scope = 2;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle10oz.paa";
displayName = $STR_EQUIP_NAME_WBPET_03;
descriptionShort = $STR_EQUIP_DESC_WBPET_03;
Nutrition[] = {0,0,1000,0};
infectionChance = 0.3;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
};
class ItemPlasticWaterBottleInfected : ItemWaterBottle
{
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle10oz.paa";
infectionChance = 1;
displayName = $STR_EQUIP_NAME_WBPET_03;
descriptionShort = $STR_EQUIP_DESC_WBPET_03;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
};
class ItemPlasticWaterBottleSafe : ItemWaterBottle
{
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle10oz.paa";
infectionChance = 0;
displayName = $STR_EQUIP_NAME_WBPET_03;
descriptionShort = $STR_EQUIP_DESC_WBPET_03;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
};
class ItemPlasticWaterBottleBoiled : ItemWaterBottle
{
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle10oz.paa";
displayName = $STR_EQUIP_NAME_WBPET_04;
descriptionShort = $STR_EQUIP_DESC_WBPET_04;
infectionChance = 0;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Crafting
{
text = $STR_CRAFTING_HERBALDRINK;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {};
requiretools[] = {};
output[] = {{"ItemPlasticWaterBottleHerbal",1}};
input[] = {{"equip_herb_box",1},{"ItemPlasticWaterBottleBoiled",1}};
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
};
};
class ItemPlasticWaterBottleHerbal : ItemWaterBottle
{
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle10oz.paa";
displayName = $STR_EQUIP_NAME_WBPET_05;
descriptionShort = $STR_EQUIP_DESC_WBPET_05;
infectionChance = -0.5;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
};
class ItemPlasticWaterbottle1oz : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE1OZ;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE1OZ_DESC;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle1oz.paa";
wateroz = 1;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,100,0};
infectionChance = 0.03;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle2oz : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE2OZ;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE2OZ_DESC;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle2oz.paa";
wateroz = 2;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,200,0};
infectionChance = 0.06;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle3oz : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE3OZ;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE3OZ_DESC;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle3oz.paa";
wateroz = 3;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,300,0};
infectionChance = 0.09;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle4oz : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE4OZ;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE4OZ_DESC;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle4oz.paa";
wateroz = 4;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,400,0};
infectionChance = 0.12;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle5oz : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE5OZ;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE5OZ_DESC;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle5oz.paa";
wateroz = 5;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,500,0};
infectionChance = 0.15;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle6oz : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE6OZ;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE6OZ_DESC;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle6oz.paa";
wateroz = 6;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,600,0};
infectionChance = 0.18;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle7oz : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE7OZ;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE7OZ_DESC;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle7oz.paa";
wateroz = 7;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,700,0};
infectionChance = 0.21;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle8oz : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE8OZ;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE8OZ_DESC;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle8oz.paa";
wateroz = 8;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,800,0};
infectionChance = 0.24;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle9oz : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE9OZ;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE9OZ_DESC;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle9oz.paa";
wateroz = 9;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,900,0};
infectionChance = 0.27;
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
//inherit from ItemWaterBottle because that's how the crafting script checks required input
class ItemPlasticWaterbottle1ozBoiled : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE1OZBOILED;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE1OZBOILED_DESC;
infectionChance = 0;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle1oz.paa";
wateroz = 1;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,100,0};
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle2ozBoiled : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE2OZBOILED;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE2OZBOILED_DESC;
infectionChance = 0;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle2oz.paa";
wateroz = 2;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,200,0};
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle3ozBoiled : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE3OZBOILED;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE3OZBOILED_DESC;
infectionChance = 0;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle3oz.paa";
wateroz = 3;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,300,0};
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle4ozBoiled : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE4OZBOILED;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE4OZBOILED_DESC;
infectionChance = 0;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle4oz.paa";
wateroz = 4;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,400,0};
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle5ozBoiled : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE5OZBOILED;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE5OZBOILED_DESC;
infectionChance = 0;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle5oz.paa";
wateroz = 5;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,500,0};
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle6ozBoiled : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE6OZBOILED;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE6OZBOILED_DESC;
infectionChance = 0;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle6oz.paa";
wateroz = 6;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,600,0};
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle7ozBoiled : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE7OZBOILED;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE7OZBOILED_DESC;
infectionChance = 0;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle7oz.paa";
wateroz = 7;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,700,0};
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle8ozBoiled : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE8OZBOILED;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE8OZBOILED_DESC;
infectionChance = 0;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle8oz.paa";
wateroz = 8;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,800,0};
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
class ItemPlasticWaterbottle9ozBoiled : ItemWaterBottle
{
displayName = $STR_EPOCH_PET_WATERBOTTLE9OZBOILED;
descriptionShort = $STR_EPOCH_PET_WATERBOTTLE9OZBOILED_DESC;
infectionChance = 0;
model = "z\addons\dayz_communityassets\models\waterbottle.p3d";
picture = "\dayz_epoch_c\icons\plasticwaterbottle\PETwaterbottle9oz.paa";
wateroz = 9;
containerWater = "ItemPlasticWaterbottle";
containerWaterSafe = "ItemPlasticWaterbottleSafe";
containerWaterInfected = "ItemPlasticWaterbottleInfected";
Nutrition[] = {0,0,900,0};
consumeOutput = "ItemPlasticWaterbottleUnfilled";
containerEmpty = "ItemPlasticWaterbottleUnfilled";
class ItemActions
{
class Consume
{
text = $STR_ACTIONS_DRINK2;
script = "spawn player_consume";
};
class Empty
{
text = $STR_EQUIP_NAME_13_EMPTY;
script = "spawn player_emptyContainer";
};
class Fill
{
text = "$STR_ACTIONS_FILL_W";
script = "spawn player_fillWater;";
};
};
};
|
#pragma once
#ifndef DAY_H
#define DAY_H
#include <vector>
#include <string>
#include "event.hpp"
class Day {
private:
std::string date;
std::vector<Event> events;
public:
std::string getDate() { return date; }
void setDate(std::string date) { this->date = date; }
void setEvent(std::string name, std::string description, int startTime, int duration);
int numOfEvents() { return events.size(); }
Event getEvent(int eventNumber);
void addEvent(std::string title, std::string description, int time, int duration);
std::string toString();
Day(std::string date);
Day();
~Day();
};
#endif
|
#include <iostream>
#include "UI/ConsoleManager.h"
#include "Entity/ComplexNumber.h"
#include "Application/KomplexNumberCalculator.h"
int main() {
ConsoleManager consoleManager;
KomplexNumberCalculator calculator;
ComplexNumber* userInput = consoleManager.getUserInput();
char operation = consoleManager.getOperation();
if (operation == '+') {
ComplexNumber result = calculator.plus(userInput[0], userInput[1]);
consoleManager.printResult(result);
} else if (operation == '-') {
ComplexNumber result = calculator.minus(userInput[0], userInput[1]);
consoleManager.printResult(result);
} else if (operation == '*') {
ComplexNumber result = calculator.multiply(userInput[0], userInput[1]);
consoleManager.printResult(result);
} else {
std::cout << "Wrong operation";
return 0;
}
return 0;
}
|
// chebyshev.c
// Andrei Alexandru
// Dec 2005
// Implement Chebysev acceleration following hep-lat/0106016
#include "chebyshev.h"
#include "vector_util.h"
namespace qcd {
// Q is expected to be hermitian
void chebyshev_matmult::remap_poly(vector& src, vector& dest)
{
Q(src, tmp2);
Q(tmp2, tmp);
double factor = 2/(max_eigen*max_eigen);
sc1_times_vec1_plus_sc2_times_vec2(factor, tmp, -(1+factor*cut_eigen*cut_eigen), src, dest);
}
void chebyshev_matmult::operator()(vector& src, vector& dest)
{
int degree = chebyshev_order;
vector rt0(src.desc);
vector rt1(src.desc);
vector rt2(src.desc);
copy_vec1_to_vec2(src, rt0);
vector *t0 = &rt0, *t1 = &rt1, *t2 = &rt2, *ptmp;
remap_poly(src, *t1);
while(degree > 1)
{
remap_poly(*t1, *t2);
sc1_times_vec1_plus_sc2_times_vec2(2, *t2, -1, *t0, *t2);
ptmp = t1;
t1 = t2;
t2 = t0;
t0 = ptmp;
--degree;
}
copy_vec1_to_vec2(*t1, dest);
}
// Chebyshev section
double_complex complex_chebyshevT(const double_complex &x, int degree)
{
double_complex t0 = 1;
double_complex t1, t2, tmp;
t1 = x;
while(degree > 1)
{
t2 = t1 * x;
t2 = 2*t2 - t0;
tmp = t1;
t1 = t2;
t0 = tmp;
--degree;
}
return t1;
}
void chebyshev_matmult_ov::remap_poly(vector& src, vector& dest)
{
hov(src, tmp);
double factor = 2/(max_eigen);
dest = factor * tmp - (1+factor*cut_eigen) * src;
}
void chebyshev_matmult_ov::operator()(vector& src, vector& dest)
{
int degree = chebyshev_order;
vector rt0(src.desc);
vector rt1(src.desc);
vector rt2(src.desc);
rt0 = src;
vector *t0 = &rt0, *t1 = &rt1, *t2=&rt2;
remap_poly(*t0, *t1);
while(degree > 1)
{
remap_poly(*t1, *t2);
*t2 = 2 * (*t2) - *t0;
vector *tmp = t1;
t1 = t2;
t2 = t0;
t0 = tmp;
--degree;
}
dest = *t1;
}
}//end namespace qcd
|
#include "Components.h"
#include "Object.h"
#include "Core.h"
#include "Screen.h"
#include "GUI.h"
std::shared_ptr<Object> Component::GetObject()
{
return object.lock();
}
std::shared_ptr<Core> Component::GetCore()
{
return object.lock()->GetCore();
}
std::shared_ptr<Input> Component::GetInput()
{
return object.lock()->GetCore()->GetInput();
}
std::shared_ptr<GUI> Component::GetGUI()
{
return object.lock()->GetCore()->GetGUI();
}
std::shared_ptr<Screen> Component::GetScreen()
{
return object.lock()->GetCore()->GetScreen();
}
std::shared_ptr<World> Component::GetWorld()
{
return object.lock()->GetCore()->GetWorld();
}
|
#include "PixelShader.h"
PixelShader::PixelShader(std::string_view shaderName)
{
VFMakeShader(shaderName.data(), &pPS);
}
void PixelShader::Bind(VeritasEngine& vin)
{
GetContext(vin)->PSSetShader(pPS.Get());
}
|
#include<iostream>
#include "parent.h"
#include "child.h"
int main(){
Child child;
Parent &cParent = child;
std::cout <<"cParent is a " << cParent.getName() <<std::endl;
return 0;
}
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#include <_root.app18_accessor_ButtonEntry_Value.h>
#include <_root.ButtonEntry.h>
#include <Uno.Bool.h>
#include <Uno.Object.h>
#include <Uno.String.h>
#include <Uno.Type.h>
#include <Uno.UX.IPropertyListener.h>
#include <Uno.UX.PropertyObject.h>
#include <Uno.UX.Selector.h>
static uString* STRINGS[1];
static uType* TYPES[3];
namespace g{
// internal sealed class app18_accessor_ButtonEntry_Value :91
// {
// static generated app18_accessor_ButtonEntry_Value() :91
static void app18_accessor_ButtonEntry_Value__cctor__fn(uType* __type)
{
::g::Uno::UX::Selector_typeof()->Init();
app18_accessor_ButtonEntry_Value::Singleton_ = app18_accessor_ButtonEntry_Value::New1();
app18_accessor_ButtonEntry_Value::_name_ = ::g::Uno::UX::Selector__op_Implicit(::STRINGS[0/*"Value"*/]);
}
static void app18_accessor_ButtonEntry_Value_build(uType* type)
{
::STRINGS[0] = uString::Const("Value");
::TYPES[0] = ::g::ButtonEntry_typeof();
::TYPES[1] = ::g::Uno::String_typeof();
::TYPES[2] = ::g::Uno::Type_typeof();
type->SetFields(0,
::g::Uno::UX::Selector_typeof(), (uintptr_t)&app18_accessor_ButtonEntry_Value::_name_, uFieldFlagsStatic,
::g::Uno::UX::PropertyAccessor_typeof(), (uintptr_t)&app18_accessor_ButtonEntry_Value::Singleton_, uFieldFlagsStatic);
}
::g::Uno::UX::PropertyAccessor_type* app18_accessor_ButtonEntry_Value_typeof()
{
static uSStrong< ::g::Uno::UX::PropertyAccessor_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.BaseDefinition = ::g::Uno::UX::PropertyAccessor_typeof();
options.FieldCount = 2;
options.ObjectSize = sizeof(app18_accessor_ButtonEntry_Value);
options.TypeSize = sizeof(::g::Uno::UX::PropertyAccessor_type);
type = (::g::Uno::UX::PropertyAccessor_type*)uClassType::New("app18_accessor_ButtonEntry_Value", options);
type->fp_build_ = app18_accessor_ButtonEntry_Value_build;
type->fp_ctor_ = (void*)app18_accessor_ButtonEntry_Value__New1_fn;
type->fp_cctor_ = app18_accessor_ButtonEntry_Value__cctor__fn;
type->fp_GetAsObject = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::PropertyObject*, uObject**))app18_accessor_ButtonEntry_Value__GetAsObject_fn;
type->fp_get_Name = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::Selector*))app18_accessor_ButtonEntry_Value__get_Name_fn;
type->fp_get_PropertyType = (void(*)(::g::Uno::UX::PropertyAccessor*, uType**))app18_accessor_ButtonEntry_Value__get_PropertyType_fn;
type->fp_SetAsObject = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::PropertyObject*, uObject*, uObject*))app18_accessor_ButtonEntry_Value__SetAsObject_fn;
type->fp_get_SupportsOriginSetter = (void(*)(::g::Uno::UX::PropertyAccessor*, bool*))app18_accessor_ButtonEntry_Value__get_SupportsOriginSetter_fn;
return type;
}
// public generated app18_accessor_ButtonEntry_Value() :91
void app18_accessor_ButtonEntry_Value__ctor_1_fn(app18_accessor_ButtonEntry_Value* __this)
{
__this->ctor_1();
}
// public override sealed object GetAsObject(Uno.UX.PropertyObject obj) :97
void app18_accessor_ButtonEntry_Value__GetAsObject_fn(app18_accessor_ButtonEntry_Value* __this, ::g::Uno::UX::PropertyObject* obj, uObject** __retval)
{
return *__retval = uPtr(uCast< ::g::ButtonEntry*>(obj, ::TYPES[0/*ButtonEntry*/]))->Value(), void();
}
// public override sealed Uno.UX.Selector get_Name() :94
void app18_accessor_ButtonEntry_Value__get_Name_fn(app18_accessor_ButtonEntry_Value* __this, ::g::Uno::UX::Selector* __retval)
{
return *__retval = app18_accessor_ButtonEntry_Value::_name_, void();
}
// public generated app18_accessor_ButtonEntry_Value New() :91
void app18_accessor_ButtonEntry_Value__New1_fn(app18_accessor_ButtonEntry_Value** __retval)
{
*__retval = app18_accessor_ButtonEntry_Value::New1();
}
// public override sealed Uno.Type get_PropertyType() :96
void app18_accessor_ButtonEntry_Value__get_PropertyType_fn(app18_accessor_ButtonEntry_Value* __this, uType** __retval)
{
return *__retval = ::TYPES[1/*string*/], void();
}
// public override sealed void SetAsObject(Uno.UX.PropertyObject obj, object v, Uno.UX.IPropertyListener origin) :98
void app18_accessor_ButtonEntry_Value__SetAsObject_fn(app18_accessor_ButtonEntry_Value* __this, ::g::Uno::UX::PropertyObject* obj, uObject* v, uObject* origin)
{
uPtr(uCast< ::g::ButtonEntry*>(obj, ::TYPES[0/*ButtonEntry*/]))->SetValue(uCast<uString*>(v, ::TYPES[1/*string*/]), origin);
}
// public override sealed bool get_SupportsOriginSetter() :99
void app18_accessor_ButtonEntry_Value__get_SupportsOriginSetter_fn(app18_accessor_ButtonEntry_Value* __this, bool* __retval)
{
return *__retval = true, void();
}
::g::Uno::UX::Selector app18_accessor_ButtonEntry_Value::_name_;
uSStrong< ::g::Uno::UX::PropertyAccessor*> app18_accessor_ButtonEntry_Value::Singleton_;
// public generated app18_accessor_ButtonEntry_Value() [instance] :91
void app18_accessor_ButtonEntry_Value::ctor_1()
{
ctor_();
}
// public generated app18_accessor_ButtonEntry_Value New() [static] :91
app18_accessor_ButtonEntry_Value* app18_accessor_ButtonEntry_Value::New1()
{
app18_accessor_ButtonEntry_Value* obj1 = (app18_accessor_ButtonEntry_Value*)uNew(app18_accessor_ButtonEntry_Value_typeof());
obj1->ctor_1();
return obj1;
}
// }
} // ::g
|
#ifndef BASEPARSER_H
#define BASEPARSER_H
#include "BasePlaylist.h"
#include <memory>
namespace hls {
class BaseParser {
public:
virtual ~BaseParser();
virtual std::unique_ptr<BasePlaylist> parse(const QByteArray &data) = 0;
protected:
static QString errorReadFromStream();
static QString errorParsePlaylist(int lineNumber, const QString &lineStr);
static int parseVersionTag(const QString &line);
static QString tagValueFromLine(const QString &tag, const QString &line);
static int parseInt(QString str);
static float parseFloat(const QString &str);
};
} // namespace hls
#endif // BASEPARSER
|
#ifndef TIMER_HPP
#define TIMER_HPP
#include "../Common/Configuration.hpp"
#include <chrono>
class Timer final
{
// As of VC2015 std::chrono is using QueryPerformanceCounter internally on Windows
std::chrono::time_point<std::chrono::system_clock> m_start;
std::chrono::time_point<std::chrono::system_clock> m_current;
public:
Timer();
// Returns the amount of time elapsed (in seconds) since the last time reset() was called
f64 elapsed() const;
// Resets the timer, this will affect the elapsed() method
void reset();
};
#endif // TIMER_HPP
|
#ifndef __TC_FILE_MUTEX_H
#define __TC_FILE_MUTEX_H
#include "util/tc_lock.h"
#include <stdio.h>
namespace taf
{
/////////////////////////////////////////////////
// ˵��: �ļ�����
// Author : j@syswin.com
/////////////////////////////////////////////////
/**
* �쳣��
*/
struct TC_FileMutex_Exception : public TC_Lock_Exception
{
TC_FileMutex_Exception(const string &buffer) : TC_Lock_Exception(buffer){};
TC_FileMutex_Exception(const string &buffer, int err) : TC_Lock_Exception(buffer, err){};
~TC_FileMutex_Exception() throw() {};
};
/**
* ���
* ע��:ֻ���ڽ��̼����.
*/
class TC_FileMutex
{
public:
/**
* ���캯��
*/
TC_FileMutex();
/**
* ��������
*/
virtual ~TC_FileMutex();
/**
* ��ʼ���ļ���
* @param filename
*/
void init(const std::string& filename);
/**
* �Ӷ���
*@return int
*/
int rlock();
/**
* �����
* @return int
*/
int unrlock();
/**
* ���Զ���
* @throws TC_FileMutex_Exception
* @return bool : �����ɹ���false, ����false
*/
bool tryrlock();
/**
* ���
* @return int
*/
int wlock();
/**
* ���
*/
int unwlock();
/**
* �����
* @throws TC_FileMutex_Exception
* @return bool : �����ɹ���false, ����false
*/
bool trywlock();
/**
* �
* @return int, 0 ��ȷ
*/
int lock(){return wlock();};
/**
* ���
*/
int unlock();
/**
* ���Խ���
* @throws TC_FileMutex_Exception
* @return int, 0 ��ȷ
*/
bool trylock() {return trywlock();};
protected:
/**
* ������
* @param fd
* @param cmd
* @param type
* @param offset
* @param whence
* @param len
*
* @return int
*/
int lock(int fd, int cmd, int type, off_t offset, int whence, off_t len);
/**
* �Ƿ�������������
* @param fd
* @param type
* @param offset
* @param whence
* @param len
*
* @return bool
*/
bool hasLock(int fd, int type, off_t offset, int whence, off_t len);
private:
int _fd;
};
}
#endif
|
#include <iostream.h>
#include <conio.h>
int binsrch(int arr[], int length, int query){
int hval,lval,mval,pos;
hval=length-1;
lval=0;
while(lval<=hval){
mval=(hval+lval)/2;
if (query==arr[mval]){
pos=mval;
return pos;
}
else if (query>mval) lval = mval + 1;
else if (query<mval) hval = mval-1;
}
return -1;
}
//Compare the next element. Swap is next one is smaller.
void bblsrt(int arr[], int length){
for(int i=0;i < length-1;++i){
for(int j=0;j < length-1;++j){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
//Select each element and compare with the rest of the elements.
//Switch for any other element is smaller.
void inssrt(int arr[], int length){
for(int i=0;i<length;++i){
for(int j=i+1;j<length;++j){
if(arr[j]<arr[i]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
//No idea, the algorithm os that bad/I am too lazy.
//Start with the first element assuming it to be the smallest sorted element so far.
//Compare with the rest of the elements, if
void selsrt(int arr[], int length){
for(int i=0;i<length;++i){
int small=arr[i];
int pos=i;
for(int j=i+1;j<length;++j){
if(arr[j]<small){
small = arr[j];
pos=j;
}
}
int temp = arr[i];
arr[i] = arr[pos];
arr[pos] = temp;
}
}
void main(){
int ch;
int length;
int arr[50];
int query;
int pos;
clrscr();
cout<<"Please enter the total number of enteries.\n";
cin>>length;
cout<<"Please enter the elements of the list.\n";
for(int i=0;i<length;++i) cin>>arr[i];
cout<<"Please choose the sorting algorithm of your choice.\n";
cout<<"1.Bubble Sort\n2.Insertion Sort\n3.Selection Sort\n";
cin>>ch;
switch (ch){
case 1: bblsrt(arr,length);
break;
case 2: inssrt(arr,length);
break;
case 3: selsrt(arr,length);
break;
default: cout<<"Please choose a valid option.\n";
}
cout<<"The sorted list is: \n";
for(i=0;i<length;++i){
cout<<arr[i]<<" ";
}
cout<<"Please enter your query to search the list.\n";
cin>>query;
pos=binsrch(arr,length,query);
if(pos>-1) cout<<"The query :"<<query<<" was found at the position "<<pos+1<<".\n";
else cout<<"Your query was not found.\n";
getch();
}
|
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
const int MAX = 1000000000;
int rec[100000],prime[100000];
int main()
{int n,t = 0;
n = sqrt(MAX)+1;
for (int i = 2;i <= n; i++)
if (!rec[i])
{for (int j = i+i;j <= n; j+=i)
rec[j] = 1;
prime[++t] = i;
}
while (cin >> n)
{int nt = n,ans = 0;
if (n == 1)
{cout << ans << endl;
continue;
}
for (int i = 1;i <= t; i++)
{while (!(n % prime[i]))
{ans = prime[i];
n/=prime[i];
}
if (n < prime[i+1]) break;
}
if (n > ans) ans = n;
cout << nt/ans << endl;
}
return 0;
}
|
#include<iostream>
#include<cmath>
#include<string>
#include<sstream>
using namespace std;
string binary(unsigned long long int);
bool is_palindrome(string);
int main() {
int count = 0;
for(unsigned long long int i = 1; i < 1000000; ++i) {
string str;
stringstream stream;
stream << i;
string bin = binary(i);
str = stream.str();
if(is_palindrome(str) && is_palindrome(bin)) {
cout << str << '\t' << bin << endl;
count += i;
}
}
cout << count << endl;
return 0;
}
string binary(unsigned long long int n) {
string s = "";
int power = 0;
while(int(pow(2, power)) <= n) ++power;
--power;
while(power != -1) {
if(n >= int(pow(2, power))) {
n = n % int(pow(2, power));
s += "1";
}
else s += "0";
--power;
}
return s;
}
bool is_palindrome(string s) {
bool ans = true;
for(int i = 0; i < s.length()/2.0; ++i)
if(s[i] != s[s.length()-1-i]) return false;
return true;
}
|
#pragma once
#include "ResourceManager.h"
#include "EngineUtil.h"
#include "FreeImage.h"
#include <memory>
class Image{
public:
string name;//file name
string filepath;
enum ImageFormat
{
IM_JPEG,
IM_PNG,
IM_TGA,
IM_BMP,
IM_HDR,
IM_TIF,
IM_UNKNOWN
};
enum ImagePixelFormat
{
UNSIGNED_BYTE,
UNSIGNED_SHORT,
UNSIGNED_INT,
UNSIGNED_INT_24_8,
UNSIGNED_CHAR_8_8_8,
UNSIGNED_CHAR_8_8_8_8,
UNSIGNED_CHAR_10_10_10_2,
FLOAT_32,
FLOAT_32_32,
FLOAT_32_32_32,
FLOAT_32_32_32_32,
FLOAT_16_16_16_16,
FLOAT_16_16_16,
UNSIGNED_INT_16_16_16_16,
FormatCount
};
struct FormatInfo
{
int ByteSize;
FormatInfo(int x) { ByteSize = x; }
FormatInfo() {}
};
static vector<FormatInfo> formatInfos;
ImageFormat mImageformat = IM_UNKNOWN;
ImagePixelFormat mPixelformat;
unsigned int width=0, height=0;
unsigned int bpp=0;
vector<BYTE> pdata;
//unique_ptr<unsigned char[]> pdata;
//void * pdata=NULL;
FIBITMAP * fib=NULL;
bool bgra = false;
Image() {};
Image(string filepath);
Image* LoadImage(string filepath, bool flip_vertical = false);
Image* CreateImageFromData(ImagePixelFormat format,int width,int height,void* data,string name="");
static void SaveRGBA32BitsToTif(void* pSrc, string filename, int w, int h);
static void SaveRGBA8BitsToPng(void* pSrc, string filename, int w, int h);
static void SaveRGB32BitsToHdr(void* pSrc, string filename, int w, int h);
bool m_valid = false;
void test();
~Image();
private:
void readDataBytes(FIBITMAP * fib, vector<BYTE>& dst);
ImageFormat getImageFormat(FREE_IMAGE_FORMAT fm);
void ConvertBetweenBGRandRGB(vector<BYTE>& input, int pixel_width,
int pixel_height,int bytes_per_pixel);
};
class ImageHelper {
};
class ImageManager :public ResourceManager<Image*>{
public:
static ImageManager& getInstance()
{
static ImageManager instance;
return instance;
}
Image* CreateImageFromFile(string filepath, bool filp_vertical=false);
vector<Image*> CreateImageListFromFiles(vector<string> paths);
private:
ImageManager(){
}
ImageManager(ImageManager const&); // Don't Implement.
void operator=(ImageManager const&); // Don't implement
};
|
#ifndef LINKEDLIST_H_INCLUDED
#define LINKEDLIST_H_INCLUDED
using namespace std;
struct node
{
int w;
node*next;
};
void wypisz(node *f);
node *buduj(int t[],int n);
#endif // LINKEDLIST_H_INCLUDED
|
#ifndef __INC_MST_HPP
#define __INC_MST_HPP
#include "graph.hpp"
#include "priority_queue.hpp"
#include <limits>
#include <string>
#ifndef _BEGIN_ZHF_LIB
#define _BEGIN_ZHF_LIB namespace zhf_lib{
#endif // !_BEGIN_ZHF_LIB
#ifndef _END_ZHF_LIB
#define _END_ZHF_LIB }
#endif // !_END_ZHF_LIB
_BEGIN_ZHF_LIB
const int IntMax = std::numeric_limits<int>::max();
template <class _Data,
class Weight_Type = unsigned>
class MST_GraphNode
: public _NodeBase<_Data>
{
public:
explicit inline MST_GraphNode(const unsigned id) :_NodeBase<_Data>(id)
{
pi = nullptr;
weight = IntMax;
}
explicit inline MST_GraphNode(const _Data &data, unsigned id) :_NodeBase<_Data>(data, id)
{
pi = nullptr;
weight = IntMax;
}
inline explicit MST_GraphNode(const MST_GraphNode &n)
:_NodeBase<_Data>(n), pi(n.pi), son(n.son), weight(n.weight){ }
virtual MST_GraphNode& operator=(const MST_GraphNode& rhs)
{
if (&rhs != this)
{
delete this->data;
this->data = new _Data(*rhs.data);
this->id = rhs.id;
pi = rhs.pi;
son = rhs.son;
weight = rhs.weight;
}
return *this;
}
MST_GraphNode *pi;
list<MST_GraphNode*>son;
WeightedEdge<Weight_Type> weight;
};
template <class _Data>
class Node_CMP
{
public:
bool operator()(const MST_GraphNode<_Data> *l, const MST_GraphNode<_Data> *r)const
{
return l->weight > r->weight;
}
};
template <class _Data,
class Weight_Type = unsigned>
MST_GraphNode<_Data> *MST(WeightedGraphMatrix<_Data, MST_GraphNode<_Data>, WeightedEdge<Weight_Type>> &graph)
{
typedef MST_GraphNode<_Data> Node;
Node *root = graph.get_node(0);
zhf_lib::PriorityQueue<Node*, Node_CMP<_Data>> Q;
// initial steps
graph.get_node(0)->weight = 0;
graph.get_node(0)->pi = nullptr;
Q.push(graph.get_node(0));
for (unsigned i = 1; i < graph.size(); i++)
{
graph.get_node(i)->weight = IntMax;
graph.get_node(i)->pi = nullptr;
Q.push(graph.get_node(i));
}
while (!Q.empty())
{
MST_GraphNode<_Data> *n = Q.top(); // extract smallest weight vertex
Q.pop();
const vector<bool> adj_vertices = graph.get_adj_vertices(n->get_id());
for (auto iter = adj_vertices.begin(); iter != adj_vertices.end(); iter++)
{
if (*iter) // is a adj vertex
{
_Index new_id = iter - adj_vertices.begin();
if (!Q.has_id(new_id))
{
continue;
}
Node *adj_node = Q.at(new_id);
if (Q.at(new_id)->weight < graph.get_edge_weight(n, adj_node)) // can decrease weight
{
//Node *new_node = adj_node;
adj_node->weight = graph.get_edge_weight(n, adj_node);
Q.change_key(new_id, adj_node);
graph.get_node(new_id)->pi = graph.get_node(n->get_id());
}
}
}
}
for (auto index = 0; index < graph.size(); index++)
{
Node *pi;
if ((pi = graph.get_node(index)->pi) != nullptr)
{
pi->son.push_back(graph.get_node(index));
}
}
return root;
}
template <class _Data,
class Weight_Type = unsigned>
MST_GraphNode<_Data> *MST(WeightedGraphList<_Data, MST_GraphNode<_Data>, WeightedEdge<Weight_Type>> &graph)
{
typedef MST_GraphNode<_Data> Node;
Node *root = graph.get_node(0);
zhf_lib::PriorityQueue<Node*, Node_CMP<_Data>> Q;
// initial steps
graph.get_node(0)->weight = 0;
graph.get_node(0)->pi = nullptr;
Q.push(graph.get_node(0));
for (unsigned i = 1; i < graph.size(); i++)
{
graph.get_node(i)->weight = IntMax;
graph.get_node(i)->pi = nullptr;
Q.push(graph.get_node(i));
}
while (!Q.empty())
{
MST_GraphNode<_Data> *n = Q.top(); // extract smallest weight vertex
Q.pop();
//for(graph.)
}
return root;
}
_END_ZHF_LIB
#endif
|
/*
* This file is part of OctoMap - An Efficient Probabilistic 3D Mapping
* Framework Based on Octrees
* http://octomap.github.io
*
* Copyright (c) 2009-2014, K.M. Wurm and A. Hornung, University of Freiburg
* All rights reserved. License for the viewer octovis: GNU GPL v2
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
#ifndef OCTREEDRAWER_H_
#define OCTREEDRAWER_H_
#include "SceneObject.h"
namespace octomap {
class OcTreeDrawer: public octomap::SceneObject {
public:
OcTreeDrawer();
virtual ~OcTreeDrawer();
void clear();
void draw() const;
// initialization of drawer -------------------------
/// sets a new OcTree that should be drawn by this drawer
void setOcTree(const AbstractOcTree& octree){
octomap::pose6d o; // initialized to (0,0,0) , (0,0,0,1) by default
setOcTree(octree, o, 0);
}
/// sets a new OcTree that should be drawn by this drawer
/// origin specifies a global transformation that should be applied
virtual void setOcTree(const AbstractOcTree& octree, const octomap::pose6d& origin, int map_id_);
// modification of existing drawer ------------------
/// sets a new selection of the current OcTree to be drawn
void setOcTreeSelection(const std::list<octomap::OcTreeVolume>& selectedPoints);
/// clear the visualization of the OcTree selection
void clearOcTreeSelection();
/// sets alpha level for occupied cells
void setAlphaOccupied(double alpha);
void setAlternativeDrawing(bool flag){m_alternativeDrawing = flag;}
void enableOcTree(bool enabled = true);
void enableOcTreeCells(bool enabled = true) { m_update = true; m_drawOccupied = enabled; };
void enableFreespace(bool enabled = true) { m_update = true; m_drawFree = enabled; };
void enableSelection(bool enabled = true) { m_update = true; m_drawSelection = enabled; };
void setMax_tree_depth(unsigned int max_tree_depth) { m_update = true; m_max_tree_depth = max_tree_depth;};
// set new origin (move object)
void setOrigin(octomap::pose6d t);
void enableAxes(bool enabled = true) { m_update = true; m_displayAxes = enabled; };
protected:
//void clearOcTree();
void clearOcTreeStructure();
void drawOctreeGrid() const;
void drawOccupiedVoxels() const;
void drawFreeVoxels() const;
void drawSelection() const;
void drawCubes(GLfloat** cubeArray, unsigned int cubeArraySize,
GLfloat* cubeColorArray = NULL) const;
void drawAxes() const;
//! Initializes the OpenGL visualization for a list of OcTreeVolumes
//! The array is cleared first, if needed
/// rotates cubes to correct reference frame
void generateCubes(const std::list<octomap::OcTreeVolume>& voxels,
GLfloat*** glArray, unsigned int& glArraySize,
octomath::Pose6D& origin,
GLfloat** glColorArray = NULL);
//! clear OpenGL visualization
void clearCubes(GLfloat*** glArray, unsigned int& glArraySize,
GLfloat** glColorArray = NULL);
//! setup OpenGL arrays
void initGLArrays(const unsigned int& num_cubes, unsigned int& glArraySize,
GLfloat*** glArray, GLfloat** glColorArray);
//! setup cube template
void initCubeTemplate(const octomath::Pose6D& origin,
std::vector<octomath::Vector3>& cube_template);
//! add one cube to arrays
unsigned int generateCube(const octomap::OcTreeVolume& v,
const std::vector<octomath::Vector3>& cube_template,
const unsigned int& current_array_idx,
GLfloat*** glArray);
unsigned int setCubeColorHeightmap(const octomap::OcTreeVolume& v,
const unsigned int& current_array_idx,
GLfloat** glColorArray);
unsigned int setCubeColorRGBA(const unsigned char& r, const unsigned char& g,
const unsigned char& b, const unsigned char& a,
const unsigned int& current_array_idx,
GLfloat** glColorArray);
void initOctreeGridVis();
//! OpenGL representation of Octree cells (cubes)
GLfloat** m_occupiedThresArray;
unsigned int m_occupiedThresSize;
GLfloat** m_freeThresArray;
unsigned int m_freeThresSize;
GLfloat** m_occupiedArray;
unsigned int m_occupiedSize;
GLfloat** m_freeArray;
unsigned int m_freeSize;
GLfloat** m_selectionArray;
unsigned int m_selectionSize;
//! Color array for occupied cells (height)
GLfloat* m_occupiedThresColorArray;
GLfloat* m_occupiedColorArray;
//! OpenGL representation of Octree (grid structure)
// TODO: put in its own drawer object!
GLfloat* octree_grid_vertex_array;
unsigned int octree_grid_vertex_size;
std::list<octomap::OcTreeVolume> m_grid_voxels;
bool m_drawOccupied;
bool m_drawOcTreeGrid;
bool m_drawFree;
bool m_drawSelection;
bool m_octree_grid_vis_initialized;
bool m_displayAxes;
bool m_alternativeDrawing;
mutable bool m_update;
unsigned int m_max_tree_depth;
double m_alphaOccupied;
octomap::pose6d origin;
octomap::pose6d initial_origin;
int map_id;
};
}
#endif /* OCTREEDRAWER_H_ */
|
class Mk43_DZ: M60A4_EP1_DZE {
displayName = $STR_DZ_WPN_MK43_NAME;
model = "\RH_mgswp\RH_mk43.p3d";
picture = "\RH_mgswp\inv\mk43.paa";
handAnim[] = {"OFP2_ManSkeleton","\RH_mgswp\Anim\RH_mk43.rtm"};
reloadMagazineSound[] = {"\RH_mgswp\sound\m60e4_reload",0.0562341,1,25};
modes[] = {"manual","close","short","medium","far"};
class manual: Mode_FullAuto
{
recoil = "recoil_auto_machinegun_8outof10";
recoilProne = "recoil_auto_machinegun_prone_5outof10";
dispersion = 0.0008;
begin1[] = {"\RH_mgswp\sound\m60e4",3.16228,1,1500};
begin2[] = {"\RH_mgswp\sound\m60e4-3",3.16228,1,1500};
soundBegin[] = {"begin1",0.33,"begin2",0.33};
soundContinuous = 0;
soundBurst = 0;
minRange = 0;
minRangeProbab = 0.3;
midRange = 5;
midRangeProbab = 0.58;
maxRange = 10;
maxRangeProbab = 0.04;
showToPlayer = 1;
reloadTime = 0.086;
displayName = "";
};
class close: manual
{
burst = 10;
aiRateOfFire = 0.5;
aiRateOfFireDistance = 50;
minRange = 10;
minRangeProbab = 0.05;
midRange = 20;
midRangeProbab = 0.58;
maxRange = 50;
maxRangeProbab = 0.04;
showToPlayer = 0;
};
class short: close
{
burst = 8;
aiRateOfFire = 2;
aiRateOfFireDistance = 300;
minRange = 50;
minRangeProbab = 0.05;
midRange = 150;
midRangeProbab = 0.58;
maxRange = 300;
maxRangeProbab = 0.04;
};
class medium: close
{
burst = 12;
aiRateOfFire = 3;
aiRateOfFireDistance = 600;
minRange = 200;
minRangeProbab = 0.05;
midRange = 400;
midRangeProbab = 0.58;
maxRange = 600;
maxRangeProbab = 0.04;
};
class far: close
{
burst = 16;
aiRateOfFire = 5;
aiRateOfFireDistance = 1000;
minRange = 400;
minRangeProbab = 0.05;
midRange = 600;
midRangeProbab = 0.4;
maxRange = 900;
maxRangeProbab = 0.01;
};
class Attachments
{
Attachment_Holo = "MK43_Holo_DZ";
Attachment_ACOG = "MK43_ACOG_DZ";
};
};
class MK43_Holo_DZ: Mk43_DZ
{
displayName = $STR_DZ_WPN_MK43_HOLO_NAME;
model = "\RH_mgswp\RH_mk43eotech.p3d";
picture = "\RH_mgswp\inv\mk43eotech.paa";
irDistance = 150;
irLaserPos = "laser pos";
irLaserEnd = "laser dir";
class ItemActions
{
class RemoveHolo
{
text = $STR_DZ_ATT_HOLO_RMVE;
script = "; ['Attachment_Holo',_id,'MK43_DZ'] call player_removeAttachment";
};
};
};
class MK43_ACOG_DZ: Mk43_DZ
{
displayName = $STR_DZ_WPN_MK43_ACOG_NAME;
model = "\RH_mgswp\RH_mk43acog.p3d";
picture = "\RH_mgswp\inv\mk43acog.paa";
irDistance = 150;
irLaserPos = "laser pos";
irLaserEnd = "laser dir";
modelOptics = "\Ca\weapons_E\SCAR\ACOG_TA31_optic_4x.p3d";
class OpticsModes
{
class ACOG
{
opticsID = 1;
useModelOptics = true;
opticsFlare = true;
opticsDisablePeripherialVision = true;
opticsZoomMin = 0.0623;
opticsZoomMax = 0.0623;
opticsZoomInit = 0.0623;
distanceZoomMin = 300;
distanceZoomMax = 300;
memoryPointCamera = "opticView";
visionMode[] = {"Normal"};
opticsPPEffects[] = {"OpticsCHAbera3","OpticsBlur3"};
cameraDir = "";
};
class Iron
{
opticsID = 2;
useModelOptics = false;
opticsFlare = false;
opticsDisablePeripherialVision = false;
opticsZoomMin = 0.25;
opticsZoomMax = 1.1;
opticsZoomInit = 0.5;
distanceZoomMin = 100;
distanceZoomMax = 100;
memoryPointCamera = "eye";
visionMode[] = {};
opticsPPEffects[] = {};
cameraDir = "";
};
};
class ItemActions
{
class RemoveACOG
{
text = $STR_DZ_ATT_ACOG_RMVE;
script = "; ['Attachment_ACOG',_id,'MK43_DZ'] call player_removeAttachment";
};
};
};
class MK43_M145_DZ: Mk43_DZ
{
displayName = $STR_DZ_WPN_MK43_M145_NAME;
model = "\RH_mgswp\RH_mk43elcan.p3d";
picture = "\RH_mgswp\inv\mk43elcan.paa";
irDistance = 150;
irLaserPos = "laser pos";
irLaserEnd = "laser dir";
modelOptics = "\Ca\weapons_E\M249\M145.p3d";
class OpticsModes
{
class Scope
{
opticsID = 1;
useModelOptics = 1;
opticsPPEffects[] = {"OpticsCHAbera1","OpticsBlur1"};
memoryPointCamera = "opticView";
visionMode[] = {"Normal"};
opticsFlare = 1;
opticsDisablePeripherialVision = 1;
distanceZoomMin = 300;
distanceZoomMax = 300;
cameraDir = "";
opticsZoomMin = "0.28778/3.4";
opticsZoomMax = "0.28778/3.4";
opticsZoomInit = "0.28778/3.4";
discretefov[] = {};
discreteInitIndex = 0;
};
class CQB: Scope
{
opticsID = 2;
useModelOptics = 0;
opticsPPEffects[] = {};
opticsFlare = 0;
opticsDisablePeripherialVision = 0;
memoryPointCamera = "eye";
visionMode[] = {};
opticsZoomMin = 0.33333;
opticsZoomMax = 1;
opticsZoomInit = "0.33333*2";
discretefov[] = {};
discreteInitIndex = 0;
};
};
class Attachments {};
};
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int arr[100],top,size;
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
int height(struct node *p);
void printlevelorder(struct node *p,int h);
struct node *newnode(int a)
{
struct node *n = (struct node *)malloc(sizeof(struct node));
n->data = a;
n->left = n->right =NULL;
return n;
}
void push(int n)
{
if(top == size-1)
printf("\n stack is full");
else
{
top++;
arr[top] = n;
}
}
void pop()
{
if(top == -1)
printf("\n stack is empty");
else
{
printf("\nthe lement popped is %d",arr[top]);
top--;
}
}
void printtree(struct node *p)
{
if(p==NULL)
return;
else
{
printtree(p->left);
printf("%d\t",p->data);
printtree(p->right);
}
}
void levelorder(struct node *p)
{
int h = height(p);
for(int i=1;i<=h;i++)
{
printf("\n");
printlevelorder(p,i);
}
}
void printlevelorder(struct node *p,int h)
{
if(p == NULL)
{ return;
}
if(h == 1)
{
printf("%d\t",p->data);
push(p->data);
}
else if(h>1)
{
printlevelorder(p->left,h-1);
printlevelorder(p->right,h-1);
}
}
int height(struct node *p)
{
if(p==NULL)
return 0;
else
{
int lh = height(p->left);
int rh = height(p->right);
if(lh>rh)
return lh+1;
else
return rh+1;
}
}
int main()
{
struct node *p = newnode(8);
p->left = newnode(3);
p->right = newnode(9);
p->left->left = newnode(6);
p->left->right = newnode(8);
p->right->left = newnode(4);
p->right->right = newnode(11);
p->left->right->left = newnode(12);
p->left->right->right = newnode(1);
printtree(p);
size = 9;
top = -1;
levelorder(p);
for(int i=0;i<9;i++)
{
pop();
printf("\n");
}
getch();
}
|
#include "cCardStorageCommunity.h"
cCardStorageCommunity::cCardStorageCommunity()
{
}
cCardStorageCommunity::~cCardStorageCommunity()
{
}
|
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
#include "../Weapon.h"
#include "../client/ClientEffect.h"
#ifndef __GAME_PROJECTILE_H__
#include "../Projectile.h"
#endif
const int NAPALM_GUN_NUM_CYLINDERS = 5;
class WeaponNapalmGun : public rvWeapon {
public:
CLASS_PROTOTYPE( WeaponNapalmGun );
WeaponNapalmGun ( void );
~WeaponNapalmGun ( void );
virtual void Spawn ( void );
virtual void Think ( void );
virtual void MuzzleRise ( idVec3 &origin, idMat3 &axis );
virtual void SpectatorCycle ( void );
void Save( idSaveGame *saveFile ) const;
void Restore( idRestoreGame *saveFile );
protected:
void UpdateCylinders(void);
typedef enum {CYLINDER_RESET_POSITION,CYLINDER_MOVE_POSITION, CYLINDER_UPDATE_POSITION } CylinderState;
CylinderState cylinderState;
private:
stateResult_t State_Idle ( const stateParms_t& parms );
stateResult_t State_Fire ( const stateParms_t& parms );
stateResult_t State_Reload ( const stateParms_t& parms );
stateResult_t State_EmptyReload ( const stateParms_t& parms );
stateResult_t Frame_MoveCylinder ( const stateParms_t& parms );
stateResult_t Frame_ResetCylinder ( const stateParms_t& parms );
float cylinderMaxOffsets[NAPALM_GUN_NUM_CYLINDERS];
idInterpolate<float> cylinderOffsets[NAPALM_GUN_NUM_CYLINDERS];
jointHandle_t cylinderJoints[NAPALM_GUN_NUM_CYLINDERS];
int cylinderMoveTime;
int previousAmmo;
bool zoomed;
CLASS_STATES_PROTOTYPE ( WeaponNapalmGun );
};
CLASS_DECLARATION( rvWeapon, WeaponNapalmGun )
END_CLASS
/*
================
WeaponNapalmGun::WeaponNapalmGun
================
*/
WeaponNapalmGun::WeaponNapalmGun( void ) { }
/*
================
WeaponNapalmGun::~WeaponNapalmGun
================
*/
WeaponNapalmGun::~WeaponNapalmGun( void ) { }
/*
================
WeaponNapalmGun::Spawn
================
*/
void WeaponNapalmGun::Spawn( void ) {
assert(viewModel);
idAnimator* animator = viewModel->GetAnimator();
assert(animator);
SetState( "Raise", 0 );
for(int i = 0; i < NAPALM_GUN_NUM_CYLINDERS; ++i)
{
idStr argName = "cylinder_offset";
argName += i;
cylinderMaxOffsets[i] = spawnArgs.GetFloat(argName, "0.0");
argName = "cylinder_joint";
argName += i;
cylinderJoints[i] = animator->GetJointHandle( spawnArgs.GetString( argName, "" ) );
cylinderOffsets[i].Init( gameLocal.time, 0.0f, 0, 0);
}
previousAmmo = AmmoInClip();
cylinderMoveTime = spawnArgs.GetFloat( "cylinderMoveTime", "500" );
cylinderState = CYLINDER_RESET_POSITION;
zoomed = false;
}
/*
================
WeaponNapalmGun::Think
================
*/
void WeaponNapalmGun::Think( void ) {
rvWeapon::Think();
//Check to see if the ammo level has changed.
//This is to account for ammo pickups.
if ( previousAmmo != AmmoInClip() ) {
// don't do this in MP, the weap script doesn't sync the canisters anyway
if ( !gameLocal.isMultiplayer ) {
//change the cylinder state to reflect the new change in ammo.
cylinderState = CYLINDER_MOVE_POSITION;
}
previousAmmo = AmmoInClip();
}
UpdateCylinders();
}
/*
===============
WeaponNapalmGun::MuzzleRise
===============
*/
void WeaponNapalmGun::MuzzleRise( idVec3 &origin, idMat3 &axis ) {
if ( wsfl.zoom )
return;
rvWeapon::MuzzleRise( origin, axis );
}
/*
===============
WeaponNapalmGun::UpdateCylinders
===============
*/
void WeaponNapalmGun::UpdateCylinders(void)
{
idAnimator* animator;
animator = viewModel->GetAnimator();
assert( animator );
float ammoInClip = AmmoInClip();
float clipSize = ClipSize();
if ( clipSize <= idMath::FLOAT_EPSILON ) {
clipSize = maxAmmo;
}
for(int i = 0; i < NAPALM_GUN_NUM_CYLINDERS; ++i)
{
// move the local position of the joint along the x-axis.
float currentOffset = cylinderOffsets[i].GetCurrentValue(gameLocal.time);
switch(cylinderState)
{
case CYLINDER_MOVE_POSITION:
{
float cylinderMaxOffset = cylinderMaxOffsets[i];
float endValue = cylinderMaxOffset * (1.0f - (ammoInClip / clipSize));
cylinderOffsets[i].Init( gameLocal.time, cylinderMoveTime, currentOffset, endValue );
}
break;
case CYLINDER_RESET_POSITION:
{
float cylinderMaxOffset = cylinderMaxOffsets[i];
float endValue = cylinderMaxOffset * (1.0f - (ammoInClip / clipSize));
cylinderOffsets[i].Init( gameLocal.time, 0, endValue, endValue );
}
break;
}
animator->SetJointPos( cylinderJoints[i], JOINTMOD_LOCAL, idVec3( currentOffset, 0.0f, 0.0f ) );
}
cylinderState = CYLINDER_UPDATE_POSITION;
}
/*
=====================
WeaponNapalmGun::Save
=====================
*/
void WeaponNapalmGun::Save( idSaveGame *saveFile ) const
{
for(int i = 0; i < NAPALM_GUN_NUM_CYLINDERS; i++)
{
saveFile->WriteFloat(cylinderMaxOffsets[i]);
saveFile->WriteInterpolate(cylinderOffsets[i]);
saveFile->WriteJoint(cylinderJoints[i]);
}
saveFile->WriteInt(cylinderMoveTime);
saveFile->WriteInt(previousAmmo);
}
/*
=====================
WeaponNapalmGun::Restore
=====================
*/
void WeaponNapalmGun::Restore( idRestoreGame *saveFile ) {
for(int i = 0; i < NAPALM_GUN_NUM_CYLINDERS; i++)
{
saveFile->ReadFloat(cylinderMaxOffsets[i]);
saveFile->ReadInterpolate(cylinderOffsets[i]);
saveFile->ReadJoint(cylinderJoints[i]);
}
saveFile->ReadInt(cylinderMoveTime);
saveFile->ReadInt(previousAmmo);
}
/*
===============================================================================
States
===============================================================================
*/
CLASS_STATES_DECLARATION ( WeaponNapalmGun )
STATE ( "Idle", WeaponNapalmGun::State_Idle)
STATE ( "Fire", WeaponNapalmGun::State_Fire )
STATE ( "Reload", WeaponNapalmGun::State_Reload )
STATE ( "EmptyReload", WeaponNapalmGun::State_EmptyReload )
STATE ( "MoveCylinder", WeaponNapalmGun::Frame_MoveCylinder )
STATE ( "ResetCylinder", WeaponNapalmGun::Frame_ResetCylinder)
END_CLASS_STATES
stateResult_t WeaponNapalmGun::State_Reload( const stateParms_t& parms) {
enum {
STAGE_INIT,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
PlayAnim ( ANIMCHANNEL_ALL, "reload", parms.blendFrames );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_ALL, 0 ) ) {
SetState ( "Idle", 4 );
return SRESULT_DONE;
}
if ( wsfl.lowerWeapon ) {
SetState ( "Lower", 4 );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvWeaponGrenadeLauncher::State_Reload
================
*/
stateResult_t WeaponNapalmGun::State_EmptyReload( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
if ( wsfl.netReload ) {
wsfl.netReload = false;
} else {
NetReload ( );
}
SetStatus ( WP_RELOAD );
PlayAnim ( ANIMCHANNEL_ALL, "reload_empty", parms.blendFrames );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_ALL, 0 ) ) {
AddToClip ( ClipSize() );
cylinderState = CYLINDER_MOVE_POSITION;
SetState ( "Idle", 4 );
return SRESULT_DONE;
}
if ( wsfl.lowerWeapon ) {
SetState ( "Lower", 4 );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
WeaponNapalmGun::State_Idle
================
*/
stateResult_t WeaponNapalmGun::State_Idle( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
if ( AmmoAvailable ( ) ) {
SetStatus ( WP_OUTOFAMMO );
} else {
SetStatus ( WP_READY );
}
if ( wsfl.zoom )
PlayCycle( ANIMCHANNEL_LEGS, "altidle", parms.blendFrames );
else
PlayCycle( ANIMCHANNEL_LEGS, "idle", parms.blendFrames );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( wsfl.lowerWeapon ) {
SetState ( "Lower", 4 );
return SRESULT_DONE;
}
if ( wsfl.zoom && !zoomed ) {
SetState ( "Idle", 4 );
zoomed = true;
return SRESULT_DONE;
}
if ( !wsfl.zoom && zoomed ) {
SetState ( "Idle", 4 );
zoomed = false;
return SRESULT_DONE;
}
if(!clipSize)
{
if ( gameLocal.time > nextAttackTime && wsfl.attack && AmmoAvailable ( ) ) {
SetState ( "Fire", 0 );
return SRESULT_DONE;
}
}
else
{
if ( wsfl.attack && AutoReload() && !AmmoInClip ( ) && AmmoAvailable () ) {
SetState ( "EmptyReload", 4 );
return SRESULT_DONE;
}
if ( wsfl.netReload || (wsfl.reload && AmmoInClip() < ClipSize() && AmmoAvailable()>AmmoInClip()) ) {
SetState ( "EmptyReload", 4 );
return SRESULT_DONE;
}
if ( gameLocal.time > nextAttackTime && wsfl.attack && AmmoInClip ( ) ) {
SetState ( "Fire", 2 );
return SRESULT_DONE;
}
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
WeaponNapalmGun::State_Fire
================
*/
stateResult_t WeaponNapalmGun::State_Fire( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
if ( wsfl.zoom ) {
nextAttackTime = gameLocal.time + (altFireRate * owner->PowerUpModifier ( PMOD_FIRERATE ));
Attack ( true, 1, spread, 0, 1.0f );
PlayAnim ( ANIMCHANNEL_ALL, "idle", parms.blendFrames );
//fireHeld = true;
} else {
nextAttackTime = gameLocal.time + (fireRate * owner->PowerUpModifier ( PMOD_FIRERATE ));
Attack ( false, 1, spread, 0, 1.0f );
int animNum = viewModel->GetAnimator()->GetAnim ( "fire" );
if ( animNum ) {
idAnim* anim;
anim = (idAnim*)viewModel->GetAnimator()->GetAnim ( animNum );
anim->SetPlaybackRate ( (float)anim->Length() / (fireRate * owner->PowerUpModifier ( PMOD_FIRERATE )) );
}
PlayAnim ( ANIMCHANNEL_ALL, "fire", parms.blendFrames );
}
previousAmmo = AmmoInClip();
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_ALL, 0 ) ) {
if ( !wsfl.zoom )
SetState ( "Reload", 4 );
else
SetState ( "Idle", 4 );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
stateResult_t WeaponNapalmGun::Frame_MoveCylinder( const stateParms_t& parms) {
cylinderState = CYLINDER_MOVE_POSITION;
return SRESULT_OK;
}
stateResult_t WeaponNapalmGun::Frame_ResetCylinder( const stateParms_t& parms) {
cylinderState = CYLINDER_RESET_POSITION;
return SRESULT_OK;
}
void WeaponNapalmGun::SpectatorCycle( void ) {
cylinderState = CYLINDER_RESET_POSITION;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.