text
stringlengths 8
6.88M
|
|---|
#include <Logger.h>
#include <Serial.h>
#include "gtest/gtest.h"
using ::testing::SafeMatcherCast;
using ::testing::Exactly;
using ::testing::Eq;
TEST(LoggerTest, initialize_CallsSerialBegin) {
int pin = 1234;
SerialMock *pSerialMock = serialMockInstance();
EXPECT_CALL(*pSerialMock, begin(Eq(pin))).Times(Exactly(1));
Logger logger;
logger.initialize(pin);
releaseSerialMock();
}
TEST(LoggerTest, writeLog_CallsSerialPrintln) {
const char *message = "test";
SerialMock *pSerialMock = serialMockInstance();
EXPECT_CALL(*pSerialMock, println(SafeMatcherCast<const char*>(message))).Times(Exactly(1));
Logger logger;
logger.writeLog(message);
releaseSerialMock();
}
|
/* vim: set sw=4 ts=4 et: */
/*
* This file is part of Other Maemo Weather(omweather)
*
* Copyright (C) 2006-2011 Vlad Vasiliev
* Copyright (C) 2010-2011 Tanya Makova
* for the code
*
* Copyright (C) 2008 Andrew Zhilin
* az@pocketpcrussia.com
* for default icon set (Glance)
*
* This software 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.1 of
* the License, or (at your option) any later version.
*
* This software 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 weather-config.h General Public
* License along with this software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
/*******************************************************************************/
#include "countrymodel.h"
CountryModel::CountryModel(QObject *parent): SelectModel(parent)
{
}
void
CountryModel::populate(QString source)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
_list.clear();
std::string path(Core::AbstractConfig::prefix);
path += Core::AbstractConfig::sharePath;
path += "db/";
if (source == "") return ;
QString filename(source);
filename.append(".db");
filename.prepend(path.c_str());
Core::DatabaseSqlite *db;
db = new Core::DatabaseSqlite("");
qDebug() << "filename = " << filename;
if (db) {
db->set_databasename(filename.toStdString());
}else {
qDebug() << "error db";
}
if (!db->open_database()){
qDebug() << "error open database";
return;
}
Core::listdata * list = db->create_countries_list();
Core::listdata::iterator cur;
if (!list)
return;
for (cur=list->begin(); cur<list->end(); cur++){
QString str = QString::fromStdString((*cur).second);
_list.append(new SelectData(str, QString::fromStdString((*cur).first), str.left(1)));
}
endInsertRows();
//reset();
endResetModel();
}
|
#include "Texture2D.h"
#include "Bitmap.h"
#include <stdexcept>
#include <new>
#include <memory>
using namespace std;
static GLenum TextureFormatForBitmapFormat(Bitmap::Format format, bool srgb = false)
{
switch (format) {
case Bitmap::Format_Grayscale: return GL_LUMINANCE;
case Bitmap::Format_GrayscaleAlpha: return GL_LUMINANCE_ALPHA;
case Bitmap::Format_RGB: return srgb ? GL_SRGB : GL_RGB;
case Bitmap::Format_RGBA: return srgb ? GL_SRGB_ALPHA : GL_RGBA;
default: throw std::runtime_error("Unrecognised Bitmap::Format");
}
}
Texture2D::Texture2D(Bitmap *bitmap, GLint minMagFilter, GLint wrapMode)
: _objectId(0)
, _originalWidth(0)
, _originalHeight(0)
{
_initWithBitmap(bitmap, minMagFilter, wrapMode);
}
Texture2D::Texture2D(const std::string &filePath, GLint minMagFilter, GLint wrapMode)
{
shared_ptr<Bitmap> bitmap(new Bitmap(filePath));
_initWithBitmap(bitmap.get(), minMagFilter, wrapMode);
}
void Texture2D::_initWithBitmap(Bitmap *bitmap, GLint minMagFiler, GLint wrapMode)
{
_originalWidth = ((GLfloat)bitmap->width());
_originalHeight = ((GLfloat)bitmap->height());
glGenTextures(1, &_objectId);
glBindTexture(GL_TEXTURE_2D, _objectId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minMagFiler);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, minMagFiler);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
glTexImage2D(GL_TEXTURE_2D, 0, TextureFormatForBitmapFormat(bitmap->format()), (GLsizei)bitmap->width(), (GLsizei)bitmap->height(), 0, TextureFormatForBitmapFormat(bitmap->format()), GL_UNSIGNED_BYTE, bitmap->pixelBuffer());
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture2D::~Texture2D()
{
glDeleteTextures(1, &_objectId);
}
|
/*
* SPDX-FileCopyrightText: (C) 2013-2022 Daniel Nicoletti <dantti12@gmail.com>
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "action.h"
#include "application.h"
#include "common.h"
#include "config.h"
#include "context_p.h"
#include "controller.h"
#include "dispatcher.h"
#include "enginerequest.h"
#include "request.h"
#include "response.h"
#include "stats.h"
#include <QBuffer>
#include <QCoreApplication>
#include <QUrl>
#include <QUrlQuery>
using namespace Cutelyst;
Context::Context(ContextPrivate *priv)
: d_ptr(priv)
{
}
Context::Context(Application *app)
: d_ptr(new ContextPrivate(app, app->engine(), app->dispatcher(), app->plugins()))
{
auto req = new DummyRequest(this);
req->body = new QBuffer(this);
req->body->open(QBuffer::ReadWrite);
req->context = this;
d_ptr->response = new Response(app->defaultHeaders(), req);
d_ptr->request = new Request(req);
d_ptr->request->d_ptr->engine = d_ptr->engine;
}
Context::~Context()
{
delete d_ptr->request;
delete d_ptr->response;
delete d_ptr;
}
bool Context::error() const noexcept
{
Q_D(const Context);
return !d->error.isEmpty();
}
void Context::error(const QString &error)
{
Q_D(Context);
if (error.isEmpty()) {
d->error.clear();
} else {
d->error << error;
qCCritical(CUTELYST_CORE) << error;
}
}
QStringList Context::errors() const noexcept
{
Q_D(const Context);
return d->error;
}
bool Context::state() const noexcept
{
Q_D(const Context);
return d->state;
}
void Context::setState(bool state) noexcept
{
Q_D(Context);
d->state = state;
}
Engine *Context::engine() const noexcept
{
Q_D(const Context);
return d->engine;
}
Application *Context::app() const noexcept
{
Q_D(const Context);
return d->app;
}
Response *Context::response() const noexcept
{
Q_D(const Context);
return d->response;
}
Response *Context::res() const noexcept
{
Q_D(const Context);
return d->response;
}
Action *Context::action() const noexcept
{
Q_D(const Context);
return d->action;
}
QString Context::actionName() const noexcept
{
Q_D(const Context);
return d->action->name();
}
QString Context::ns() const noexcept
{
Q_D(const Context);
return d->action->ns();
}
Request *Context::request() const noexcept
{
Q_D(const Context);
return d->request;
}
Request *Context::req() const noexcept
{
Q_D(const Context);
return d->request;
}
Dispatcher *Context::dispatcher() const noexcept
{
Q_D(const Context);
return d->dispatcher;
}
QString Cutelyst::Context::controllerName() const
{
Q_D(const Context);
return QString::fromLatin1(d->action->controller()->metaObject()->className());
}
Controller *Context::controller() const noexcept
{
Q_D(const Context);
return d->action->controller();
}
Controller *Context::controller(const QString &name) const
{
Q_D(const Context);
return d->dispatcher->controllers().value(name);
}
View *Context::customView() const noexcept
{
Q_D(const Context);
return d->view;
}
View *Context::view(const QString &name) const
{
Q_D(const Context);
return d->app->view(name);
}
View *Context::view(QStringView name) const
{
Q_D(const Context);
return d->app->view(name);
}
bool Context::setCustomView(const QString &name)
{
Q_D(Context);
d->view = d->app->view(name);
return d->view;
}
QVariantHash &Context::stash()
{
Q_D(Context);
return d->stash;
}
QVariant Context::stash(const QString &key) const
{
Q_D(const Context);
return d->stash.value(key);
}
QVariant Context::stash(const QString &key, const QVariant &defaultValue) const
{
Q_D(const Context);
return d->stash.value(key, defaultValue);
}
QVariant Context::stashTake(const QString &key)
{
Q_D(Context);
return d->stash.take(key);
}
bool Context::stashRemove(const QString &key)
{
Q_D(Context);
return d->stash.remove(key);
}
void Context::setStash(const QString &key, const QVariant &value)
{
Q_D(Context);
d->stash.insert(key, value);
}
void Context::setStash(const QString &key, const ParamsMultiMap &map)
{
Q_D(Context);
d->stash.insert(key, QVariant::fromValue(map));
}
QStack<Component *> Context::stack() const noexcept
{
Q_D(const Context);
return d->stack;
}
QUrl Context::uriFor(const QString &path, const QStringList &args, const ParamsMultiMap &queryValues) const
{
Q_D(const Context);
QUrl uri = d->request->uri();
QString _path;
if (path.isEmpty()) {
// ns must NOT return a leading slash
const QString controllerNS = d->action->controller()->ns();
if (!controllerNS.isEmpty()) {
_path.prepend(controllerNS);
}
} else {
_path = path;
}
if (!args.isEmpty()) {
if (_path.compare(u"/") == 0) {
_path += args.join(u'/');
} else {
_path = _path + u'/' + args.join(u'/');
}
}
if (!_path.startsWith(u'/')) {
_path.prepend(u'/');
}
uri.setPath(_path, QUrl::DecodedMode);
QUrlQuery query;
if (!queryValues.isEmpty()) {
// Avoid a trailing '?'
if (queryValues.size()) {
auto it = queryValues.constEnd();
while (it != queryValues.constBegin()) {
--it;
query.addQueryItem(it.key(), it.value());
}
}
}
uri.setQuery(query);
return uri;
}
QUrl Context::uriFor(Action *action, const QStringList &captures, const QStringList &args, const ParamsMultiMap &queryValues) const
{
Q_D(const Context);
QUrl uri;
Action *localAction = action;
if (!localAction) {
localAction = d->action;
}
QStringList localArgs = args;
QStringList localCaptures = captures;
Action *expandedAction = d->dispatcher->expandAction(this, action);
if (expandedAction->numberOfCaptures() > 0) {
while (localCaptures.size() < expandedAction->numberOfCaptures() && localArgs.size()) {
localCaptures.append(localArgs.takeFirst());
}
} else {
QStringList localCapturesAux = localCaptures;
localCapturesAux.append(localArgs);
localArgs = localCapturesAux;
localCaptures = QStringList();
}
const QString path = d->dispatcher->uriForAction(localAction, localCaptures);
if (path.isEmpty()) {
qCWarning(CUTELYST_CORE) << "Can not find action for" << localAction << localCaptures;
return uri;
}
uri = uriFor(path, localArgs, queryValues);
return uri;
}
QUrl Context::uriForAction(const QString &path, const QStringList &captures, const QStringList &args, const ParamsMultiMap &queryValues) const
{
Q_D(const Context);
QUrl uri;
Action *action = d->dispatcher->getActionByPath(path);
if (!action) {
qCWarning(CUTELYST_CORE) << "Can not find action for" << path;
return uri;
}
uri = uriFor(action, captures, args, queryValues);
return uri;
}
bool Context::detached() const noexcept
{
Q_D(const Context);
return d->detached;
}
void Context::detach(Action *action)
{
Q_D(Context);
if (action) {
d->dispatcher->forward(this, action);
} else {
d->detached = true;
}
}
void Context::detachAsync() noexcept
{
Q_D(Context);
++d->actionRefCount;
}
void Context::attachAsync()
{
Q_D(Context);
if (--d->actionRefCount) {
return;
}
if (Q_UNLIKELY(d->engineRequest->status & EngineRequest::Finalized)) {
qCWarning(CUTELYST_ASYNC) << "Trying to async attach to a finalized request! Skipping...";
return;
}
if (d->engineRequest->status & EngineRequest::Async) {
while (d->asyncAction < d->pendingAsync.size()) {
Component *action = d->pendingAsync[d->asyncAction++];
const bool ret = execute(action);
if (d->actionRefCount) {
return;
}
if (!ret) {
break; // we are finished
}
}
Q_EMIT d->app->afterDispatch(this);
finalize();
}
}
bool Context::forward(Component *action)
{
Q_D(Context);
return d->dispatcher->forward(this, action);
}
bool Context::forward(const QString &action)
{
Q_D(Context);
return d->dispatcher->forward(this, action);
}
Action *Context::getAction(const QString &action, const QString &ns) const
{
Q_D(const Context);
return d->dispatcher->getAction(action, ns);
}
QVector<Action *> Context::getActions(const QString &action, const QString &ns) const
{
Q_D(const Context);
return d->dispatcher->getActions(action, ns);
}
QVector<Cutelyst::Plugin *> Context::plugins() const
{
Q_D(const Context);
return d->plugins;
}
bool Context::execute(Component *code)
{
Q_D(Context);
Q_ASSERT_X(code, "Context::execute", "trying to execute a null Cutelyst::Component");
static int recursion = qEnvironmentVariableIsSet("RECURSION") ? qEnvironmentVariableIntValue("RECURSION") : 1000;
if (d->stack.size() >= recursion) {
QString msg = QStringLiteral("Deep recursion detected (stack size %1) calling %2, %3")
.arg(QString::number(d->stack.size()), code->reverse(), code->name());
error(msg);
setState(false);
return false;
}
bool ret;
d->stack.push(code);
if (d->stats) {
const QString statsInfo = d->statsStartExecute(code);
ret = code->execute(this);
// The request might finalize execution before returning
// so it's wise to check for d->stats again
if (d->stats && !statsInfo.isEmpty()) {
d->statsFinishExecute(statsInfo);
}
} else {
ret = code->execute(this);
}
d->stack.pop();
return ret;
}
QLocale Context::locale() const noexcept
{
Q_D(const Context);
return d->locale;
}
void Context::setLocale(const QLocale &locale)
{
Q_D(Context);
d->locale = locale;
}
QVariant Context::config(const QString &key, const QVariant &defaultValue) const
{
Q_D(const Context);
return d->app->config(key, defaultValue);
}
QVariantMap Context::config() const noexcept
{
Q_D(const Context);
return d->app->config();
}
QString Context::translate(const char *context, const char *sourceText, const char *disambiguation, int n) const
{
Q_D(const Context);
return d->app->translate(d->locale, context, sourceText, disambiguation, n);
}
void Context::finalize()
{
Q_D(Context);
if (Q_UNLIKELY(d->engineRequest->status & EngineRequest::Finalized)) {
qCWarning(CUTELYST_CORE) << "Trying to finalize a finalized request! Skipping...";
return;
}
if (d->stats) {
qCDebug(CUTELYST_STATS, "Response Code: %d; Content-Type: %s; Content-Length: %s", d->response->status(), qPrintable(d->response->headers().header(QStringLiteral("CONTENT_TYPE"), QStringLiteral("unknown"))), qPrintable(d->response->headers().header(QStringLiteral("CONTENT_LENGTH"), QStringLiteral("unknown"))));
const double enlapsed = d->engineRequest->elapsed.nsecsElapsed() / 1000000000.0;
QString average;
if (enlapsed == 0.0) {
average = QStringLiteral("??");
} else {
average = QString::number(1.0 / enlapsed, 'f');
average.truncate(average.size() - 3);
}
qCInfo(CUTELYST_STATS) << qPrintable(QStringLiteral("Request took: %1s (%2/s)\n%3")
.arg(QString::number(enlapsed, 'f'),
average,
QString::fromLatin1(d->stats->report())));
delete d->stats;
d->stats = nullptr;
}
d->engineRequest->finalize();
}
QString ContextPrivate::statsStartExecute(Component *code)
{
QString actionName;
// Skip internal actions
if (code->name().startsWith(u'_')) {
return actionName;
}
actionName = code->reverse();
if (qobject_cast<Action *>(code)) {
actionName.prepend(u'/');
}
if (stack.size() > 2) {
actionName = u"-> " + actionName;
actionName = actionName.rightJustified(actionName.size() + stack.size() - 2, QLatin1Char(' '));
}
stats->profileStart(actionName);
return actionName;
}
void ContextPrivate::statsFinishExecute(const QString &statsInfo)
{
stats->profileEnd(statsInfo);
}
void Context::stash(const QVariantHash &unite)
{
Q_D(Context);
auto it = unite.constBegin();
while (it != unite.constEnd()) {
d->stash.insert(it.key(), it.value());
++it;
}
}
#include "moc_context.cpp"
#include "moc_context_p.cpp"
|
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit_msgs/RobotState.h>
#include <fstream>
#include <iostream>
using namespace std;
using namespace Eigen;
int main(int argc, char** argv)
{
ros::init(argc, argv, "convert_points");
ros::AsyncSpinner spinner(1);
spinner.start();
std::string data_folder_path("/home/mohit/vision_ws/src/extrinsic_calibration/data_files/");
geometry_msgs::PointStamped kinect_point_wrt_base_link;
geometry_msgs::PointStamped kinect_point_wrt_wrist2_link;
tf::TransformListener listener;
fstream myfile;
char c;
float a;
myfile.open (data_folder_path + "marker_coordinates_wrt_base_link.txt", std::ios::in);
int num_kinect_points = 0;
while (myfile.get(c))
{
if(c == '\n')
num_kinect_points = num_kinect_points + 1;
}
myfile.close();
MatrixXf points_wrt_kinect(num_kinect_points, 3);
myfile.open (data_folder_path + "marker_coordinates_wrt_base_link.txt", std::ios::in);
int row = 0;
int column = 0;
do
{
myfile >> a;
points_wrt_kinect(row, column) = a;
std::cout << "a " << a << std::endl;
column = column + 1;
column = column % 3;
if(column == 0)
row = row + 1;
if(row == num_kinect_points)
break;
}while (myfile.get(c));
myfile.close();
ofstream myfile2;
myfile2.open (data_folder_path + "marker_coordinates_wrt_wrist2_link.txt", std::ios::out);
for (int i=0; i< num_kinect_points; i=i+1)
{
kinect_point_wrt_base_link.header.frame_id = "ur5_base_link";
kinect_point_wrt_base_link.point.x = points_wrt_kinect(i, 0);
kinect_point_wrt_base_link.point.y = points_wrt_kinect(i, 1);
kinect_point_wrt_base_link.point.z = points_wrt_kinect(i, 2);
std::cout << "\nClicked_point: " << kinect_point_wrt_base_link.point.x << ", "
<< kinect_point_wrt_base_link.point.y << ", "
<< kinect_point_wrt_base_link.point.z << "\n";
listener.waitForTransform( "ur5_ee_link", "ur5_base_link", ros::Time(0), ros::Duration(3));
listener.transformPoint("ur5_ee_link", kinect_point_wrt_base_link, kinect_point_wrt_wrist2_link);
myfile2 << std::setprecision(15) << kinect_point_wrt_wrist2_link.point.x << ", "
<< kinect_point_wrt_wrist2_link.point.y << ", "
<< kinect_point_wrt_wrist2_link.point.z << "\n";
std::cout << "converted_point: " << kinect_point_wrt_wrist2_link.point.x << ", "
<< kinect_point_wrt_wrist2_link.point.y << ", "
<< kinect_point_wrt_wrist2_link.point.z << "\n";
}
myfile2.close();
return 0;
}
|
#ifndef PARALLEL_FOR_H
#define PARALLEL_FOR_H
#include <thread>
#include <dsnutil/dsnutil_cpp_Export.h>
namespace dsn {
void dsnutil_cpp_EXPORT parallel_for(const size_t size, std::function<void(const size_t)> func,
unsigned numThreads = std::thread::hardware_concurrency());
}
#endif // PARALLEL_FOR_H
|
#include "CarService.h"
#include "invalidmanifacturerexeption.h"
#include <iostream>
using namespace std;
CarService::CarService()
{
//ctor
}
void CarService::add_car(const Car& car)
{
if(isValidManufacturer(car) && isValidCarAge(car))
{
car_repo.add_car(car);
}
/// validate car
//cout << car << endl;
}
bool CarService::isValidManufacturer(const Car& car)
{
string manufacturer = car.get_manufacturer();
for(unsigned int i = 0; i < manufacturer.length(); i++)
{
if(!isalpha(manufacturer[i]))
{
throw (InvalidManifacturerExeption());
}
}
return true;
}
bool CarService::isValidCarAge(const Car& car)
{
if(car.get_age() < 0)
{
throw (InvalidAgeOfCarException("The age is not valid!"));
}
return true;
}
|
#ifndef XORSHIROBWGEN_
#define XORSHIROBWGEN_
#include "prng.h"
#include "xorshiro.h"
#include <cmath>
class xorshiroGen{
private:
xorshiro uniform; //oggetto della classe xorshiro
double pi;
double* data ;
double* smeared ;
public:
xorshiroGen();
~xorshiroGen();
double BW(double x, double M0 = 0., double gamma =1.);
double BW_inverse(double M0 = 0., double gamma = 1.);
double BW_hm(double M0 = 0., double gamma = 1.,
double xmin = -10., double xmax = 10.,
double ymin = 0, double ymax = 0.1);
double landau(double x, double mu = 0., double sigma = 1.);
double landau_tc(double mu =0, double sigma = 1,
double xmin = 0, double xmax = 1,
double ymin = 0, double ymax = 0.5);
double gaus(double x, double mu=0, double sigma = 1);
double gaus_tc(double mu =0, double sigma = 1, double xmin = -1, double xmax =1,
double ymin=1, double ymax=1);
double decay(double x, double y, double alpha, double beta, double gamma );
double gauss_bm(double mu, double sigma);
};
#endif
|
/*
problem
: printout stars following rules of example
condition
: 1<=n<=100
Example
-Input
4
-Output
*
* *
* * *
* * * *
*/
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
for(int j=n-i;j>0;j--){
printf(" ");
}
for(int k=1; k<=2*i-1; k++){
if(k%2==1){
printf("*");
}else{
printf(" ");
}
}
printf("\n");
}
}
|
#include <iostream>
#include <memory>
#include "abstractfactory.hpp"
using std::cout;
using std::endl;
using std::shared_ptr;
int main() {
shared_ptr<RoundFactory> rof(new RoundFactory());
shared_ptr<MaskARound> maro(rof->CreateFigureA());
shared_ptr<MaskBRound> mbro(rof->CreateFigureB());
shared_ptr<RecFactory> ref(new RecFactory());
shared_ptr<MaskARec> mare(ref->CreateFigureA());
shared_ptr<MaskBRec> mbre(ref->CreateFigureB());
shared_ptr<TriFactory> tif(new TriFactory());
shared_ptr<MaskATri> matr(tif->CreateFigureA());
shared_ptr<MaskBTri> mbtr(tif->CreateFigureB());
}
|
/*
Copyright (c) 2011 Andrew Wall
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "src\CompositeNotification.h"
#include "src\TestResult.h"
#include "AutoRun.h"
#include <sstream>
namespace TestCompositeNotification{
using gppUnit::equals;
class TestCompositeUtility: public Auto::TestCase, public gppUnit::Notification{
virtual void StartProject(const gppUnit::ProjectDescription&){ wasCalled+=1; }
virtual void EndProject(){ wasCalled+=1; }
gppUnit::CompositeNotification composite;
protected:
void add(){ composite.add(*this); }
size_t wasCalled;
void call(Notification& notify){
notify.StartProject( *(gppUnit::ProjectDescription*)0);
}
void whenCalled(){
call(composite);
}
void callEnd(Notification& notify){
notify.EndProject();
}
void whenEndCalled(){
callEnd(composite);
}
void whenAllCalled(){
gppUnit::Notification* notify=&composite;
notify->StartProject(*(gppUnit::ProjectDescription*)0);
notify->StartClass(*(gppUnit::ClassDescription*)0);
notify->StartMethod(*(gppUnit::MethodDescription*)0);
notify->Result(gppUnit::TestResult());
notify->Exception("EX");
notify->EndMethod();
notify->EndClass();
notify->EndProject();
}
};
class NoComponents: public TestCompositeUtility{
void givenComposite(){
wasCalled=0;
}
void thenNoCallsReceived(){
confirm.that(wasCalled,equals(0),"thenNoCallsReceived");
}
void test(){
givenComposite();
whenCalled();
thenNoCallsReceived();
}
}GPPUNIT_INSTANCE;
class OneComponent: public TestCompositeUtility{
void givenComposite(){
wasCalled=0;
add();
}
void thenOneCallReceived(){
confirm.that(wasCalled,equals(1),"thenOneCallReceived");
}
void test(){
givenComposite();
whenCalled();
thenOneCallReceived();
}
}GPPUNIT_INSTANCE;
class TwiceSelf: public TestCompositeUtility{
void givenComposite(){
wasCalled=0;
add();
add();
}
void thenTwoCallsReceived(){
confirm.that(wasCalled,equals(2),"thenTwoCallsReceived");
}
void test(){
givenComposite();
whenCalled();
thenTwoCallsReceived();
}
}GPPUNIT_INSTANCE;
class ThriceSelf: public TestCompositeUtility{
void givenComposite(){
wasCalled=0;
add();
add();
add();
}
void thenThreeCallsReceived(){
confirm.that(wasCalled,equals(3),"thenThreeCallsReceived");
}
void test(){
givenComposite();
whenEndCalled();
thenThreeCallsReceived();
}
}GPPUNIT_INSTANCE;
class AllMethodsCalled: public TestCompositeUtility{
std::stringstream collect;
virtual void StartProject(const gppUnit::ProjectDescription&){collect << "SP.";}
virtual void StartClass(const gppUnit::ClassDescription&){collect << "SC.";}
virtual void StartMethod(const gppUnit::MethodDescription&){collect << "SM.";}
virtual void Result(const gppUnit::TestResult&){collect << "TR.";}
virtual void Exception(const std::string& what){collect << what << '.';}
virtual void EndMethod(){collect << "EM.";}
virtual void EndClass(){collect << "EC.";}
virtual void EndProject(){collect << "EP.";}
void givenComposite(){
collect.str("");
add();
}
void thenAllMethodsCalled(){
confirm.that(collect,equals("SP.SC.SM.TR.EX.EM.EC.EP."),"thenAllMethodsCalled");
}
void test(){
givenComposite();
whenAllCalled();
thenAllMethodsCalled();
}
}GPPUNIT_INSTANCE;
}
|
/*
this code is the solution of beakjoon #2743.
please refer below url for checking problem.
https://www.acmicpc.net/problem/2743
*/
#include <iostream>
#include <queue>
using namespace std;
int main(void)
{
string input;
cin>>input;
cout<<input.size()<<endl;
}
|
/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.BarCode for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.BarCode for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/
#include "CodabarChecksumMode.h"
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/object_ext.h>
#include <system/object.h>
#include <system/details/dispose_guard.h>
#include <system/environment.h>
#include <system/console.h>
#include <Generation/EncodeTypes/SymbologyEncodeType.h>
#include <Generation/EncodeTypes/EncodeTypes.h>
#include <BarCode.Generation/BarcodeGenerator.h>
#include <BarCode.Generation/GenerationParameters/BaseGenerationParameters.h>
#include <BarCode.Generation/GenerationParameters/BarcodeParameters.h>
#include <BarCode.Generation/GenerationParameters/CaptionParameters.h>
#include <BarCode.Generation/Helpers/FontUnit.h>
#include <BarCode.Generation/Helpers/Unit.h>
#include <BarCode.Generation/GenerationParameters/TextAlignment.h>
#include <drawing/string_alignment.h>
#include <Generation/BarCodeImageFormat.h>
#include <Generation/CodabarChecksumMode.h>
#include <Generation/EnableChecksum.h>
#include <BarCodeRecognition/Recognition/RecognitionSession/DecodeTypes/SingleDecodeType.h>
#include <BarCodeRecognition/Recognition/RecognitionSession/DecodeTypes/DecodeType.h>
#include <BarCodeRecognition/Recognition/RecognitionSession/BarCodeReader.h>
#include <BarCodeRecognition/Recognition/ChecksumValidation.h>
#include "RunExamples.h"
using namespace Aspose::BarCode::Generation;
namespace Aspose {
namespace BarCode {
namespace Examples {
namespace CSharp {
namespace ManageBarCodes {
RTTI_INFO_IMPL_HASH(3347396843u, ::Aspose::BarCode::Examples::CSharp::ManageBarCodes::CodabarChecksumMode, ThisTypeBaseTypesInfo);
void CodabarChecksumMode::Run()
{
//ExStart:ChecksumSupplementData
// The path to the documents directory.
System::String dataDir = RunExamples::GetDataDir_ManageBarCodes();
//Generation
//Instantiate BarcodeGenerator object
System::SharedPtr<BarcodeGenerator> generator = System::MakeObject<BarcodeGenerator>(EncodeTypes::Codabar);
//Set the Code text for the barcode
generator->set_CodeText(u"1234567890");
//Set the EnableChecksum property to yes
generator->get_Parameters()->get_Barcode()->set_IsChecksumEnabled(EnableChecksum::Yes);
//Set the CodabarChecksumMode
generator->get_Parameters()->get_Barcode()->get_Codabar()->set_CodabarChecksumMode(Aspose::BarCode::CodabarChecksumMode::Mod10);
//Save the image on the system
generator->Save(u"Codabar_Mod10.png");
//Recognition
//Initialize reader object
{
System::SharedPtr<Aspose::BarCode::BarCodeRecognition::BarCodeReader> reader = System::MakeObject<Aspose::BarCode::BarCodeRecognition::BarCodeReader>(u"Codabar_Mod10.png", Aspose::BarCode::BarCodeRecognition::DecodeType::Codabar);
// Clearing resources under 'using' statement
System::Details::DisposeGuard<1> __dispose_guard_0({ reader });
// ------------------------------------------
try
{
//Set ChecksumValidation property of the reader to On
reader->set_ChecksumValidation(Aspose::BarCode::BarCodeRecognition::ChecksumValidation::On);
while (reader->Read())
{
//Get code text
System::Console::WriteLine(u"{0}:{1}", reader->GetCodeType(), System::ObjectExt::Box<System::String>(reader->GetCodeText()));
//Get checksum value
System::Console::WriteLine(System::String(u"Checksum:") + reader->GetCheckSum());
}
}
catch (...)
{
__dispose_guard_0.SetCurrentException(std::current_exception());
}
}
//ExEnd:ChecksumSupplementData
}
} // namespace ManageBarCodes
} // namespace CSharp
} // namespace Examples
} // namespace BarCode
} // namespace Aspose
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CELLCYCLETIMESGENERATOR_HPP_
#define CELLCYCLETIMESGENERATOR_HPP_
#include <sstream>
#include "ChasteSerialization.hpp"
#include "RandomNumberGenerator.hpp"
#include "SerializableSingleton.hpp"
/**
* This is a helper class for FixedSequenceCellCycleModel. It comprises a singleton class
* for producing a fixed stream of exponentially distributed G1 durations.
*/
class CellCycleTimesGenerator : public SerializableSingleton<CellCycleTimesGenerator>
{
private:
/** The singleton definition
*/
static CellCycleTimesGenerator* mpInstance;
/**
* The random seed used to generate the series of cell cycle times.
*/
unsigned mRandomSeed;
/**
* The actual sequence of cell cycle times
*/
std::vector<double> mCellCycleTimes;
/**
* This index is used to keep track of where in the sequence mCellCycleTimes
* the simulation currently is. Whenever a cell divides, a new
* cell cycle time gets drawn from mCellCycleTimes and this counter is incremented
* by one.
*/
unsigned mCurrentIndex;
/**
* The rate constant of the exponential distribution used to
* generate mCellCycleTimes.
*/
double mRate;
/**
* A flag that changes from False to True when mCellCycleTimes has been
* generated.
*/
bool mVectorCreated;
/** Needed for serialization. */
friend class boost::serialization::access;
/**
* Serialization of a CellCycleTimesGenerator object must be done with care.
* Do not serialize this singleton directly. Instead, serialize
* the object returned by GetSerializationWrapper.
*
* @param archive the archive
* @param version the current version of this class
*/
template <class Archive>
void serialize(Archive& archive, const unsigned int version)
{
archive& mRandomSeed;
archive& mCellCycleTimes;
archive& mCurrentIndex;
archive& mRate;
archive& mVectorCreated;
}
protected:
/**
* Protected constructor.
* Use Instance() to access the random number generator.
*/
CellCycleTimesGenerator();
public:
/**
* @return a pointer to the CellCycleTimesGenerator object.
* The object is created the first time this method is called.
*/
static CellCycleTimesGenerator* Instance();
/**
* Destroy the current instance of the cell cycle times generator.
* The next call to Instance will create a new instance.
* This method *must* be called before program exit, to avoid a memory
* leak.
*/
static void Destroy();
/**
* Set the random seed for generating the sequence of G1 Durations.
*
* @param randomSeed the new seed
*/
void SetRandomSeed(unsigned randomSeed);
/**
* Get the random seed for generating the sequence.
*
* @returns seed The random seed
*/
unsigned GetRandomSeed();
/**
* Set the rate of the exponential distribution.
*
* @param rate
*/
void SetRate(double rate);
/**
* Get the rate of the exponential distribution.
*
* @returns rate The rate of the distribution.
*/
double GetRate();
/**
* Generate the cell cycle time sequence
*/
void GenerateCellCycleTimeSequence();
/**
* Get the next cell cycle time
*
* @returns next_cell_cycle_time the next cell cycle time in the sequence
*/
double GetNextCellCycleTime();
};
#endif /*CELLCYCLETIMESGENERATOR_HPP_*/
|
#ifndef SIPLASPLAS_REFLECTION_INIT_FILE_{{hash}}_HPP
#define SIPLASPLAS_REFLECTION_INIT_FILE_{{hash}}_HPP
/*
* Reflection initialization file generated from file:
* {{tu.filePath}}
*
* Classes:
{% for class in tu.classes %}
* - From line {{class.cursor.location.line}}: {{class.declKind}} {{class.className}} ({{class.full_qualified_ref}})
{% endfor %}
*/
namespace cpp
{
{% for class in tu.classes %}
template<>
class Reflection<{{class.full_qualified_ref}}>
{
public:
static ::cpp::MetaClassData& reflection() {
static ::cpp::MetaClassData& data = []() -> ::cpp::MetaClassData&
{
::cpp::MetaClass::registerClass<{{class.full_qualified_ref}}>({
{% for field in class.fields %}
::cpp::Field("{{field.name}}", &{{class.full_qualified_ref}}::{{field.name}}, offsetof({{class.full_qualified_ref}}, {{field.name}})),
{% endfor %}
}, {
{% for function in class.functions %}
::cpp::Function("{{function.name}}", &{{class.full_qualified_ref}}::{{function.name}}),
{% endfor %}
});
return ::cpp::MetaClass::getClass<{{class.className}}>();
}();
return data;
}
};
{% endfor %}
}
#endif #define SIPLASPLAS_REFLECTION_INIT_FILE_{{hash}}_HPP
|
// $Id: main.cpp,v 1.9 2016-07-20 21:00:33-07 - - $
#include <cstdlib>
#include <exception>
#include <iostream>
#include <string>
#include <unistd.h>
#include <fstream>
using namespace std;
#include "listmap.h"
#include "xpair.h"
#include "util.h"
//=====================================================================
using str_str_map = listmap<string,string>;
using str_str_pair = str_str_map::value_type;
//using str_str_itr = listmap<string,string>iterator;
//=====================================================================
//=====================================================================
string split(string line) {
size_t first = line.find_first_not_of(' ');
size_t last = line.find_last_not_of(' ');
if(first == string::npos ) return "";
string res = line.substr(first, last - first + 1);
return res;
}
//=====================================================================
//=====================================================================
void scan_options (int argc, char** argv) {
opterr = 0;
for (;;) {
int option = getopt (argc, argv, "@:");
if (option == EOF) break;
switch (option) {
case '@':
traceflags::setflags (optarg);
break;
default:
complain() << "-" << char (optopt) << ": invalid option"
<< endl;
break;
}
}
}
//=====================================================================
void parser(string line, str_str_map& map){
line = split(line);
string key = "";
string value = "";
if ((line[0] == '#' or line.size() == 0)) {
return;
}
size_t pos = line.find_first_of('=');
bool atFront = line.find_first_of('=') == 0;
bool atEnd = line.find_first_of('=') == line.length()-1;
str_str_map::iterator itor;
if(pos == string::npos){
key = line;
itor = map.find(key);
if(itor != map.end() and itor != str_str_map::iterator()){
cout << itor->first << " = " << itor->second
<< endl;
}
else{
cout << key <<": key not found." << endl;
}
}
// ' = '
else if (line.size() == 1 and line[0] == '='){
for(auto itor = map.begin(); itor != map.end(); ++itor){
cout << itor->first << " = " << itor->second
<< endl;
}
}
// case 'key ='
else if (!atFront and atEnd){
key = split(line.substr(0,line.length()-1));
for(auto itor = map.begin(); itor != map.end(); ++itor){
if(key == itor->first){
map.erase(itor);
break;
}
}
}
// 'Key = value'
else if(!atFront and !atEnd){
key = split(line.substr(0,pos));
value = split(line.substr(pos+1));
str_str_pair newPair(key,value);
map.insert(newPair);
cout << key << " = " << value << endl;
}
//case '= value'
else if (atFront and !atEnd){
value = split(line.substr(1));
for(auto itor = map.begin();itor != map.end(); ++itor){
if(value == itor->second){
cout << itor->first << " = " << itor->second
<< endl;
}
}
}
else {
cerr << "Parser Error" << endl;
/*catch (exception& error) {
//cout << "Error in parser! " << endl;
complain() << error.what() << endl;
}*/
}
//}
}
//=====================================================================
//=====================================================================
int main (int argc, char** argv) {
scan_options (argc, argv);
str_str_map test;
string line = "";
int count{0};
if(argc == 1){
while( getline(cin,line)){
if(cin.eof()) break;
}
++count;
cout << count << ": " << line << endl;
parser(line, test);
}
for(auto itor = 1; itor < argc; ++itor){
if(argv[itor] == std::string("-")) {
while(getline(cin,line)){
if(cin.eof()) break;
++count;
cout << argv[itor] << ": " << count
<< ": " << line << endl;
parser(line, test);
}
}
else {
ifstream fstream (argv[itor]);
if(fstream.fail()) cout << "no such file " << endl;
while(getline(fstream, line)){
++count;
cout << argv[itor] << ": " << count
<< ": " << line << endl;
parser(line, test);
}
}
}
/*//sys_info::set_execname (argv[0]);
scan_options (argc, argv);
str_str_map test;
bool need_echo = true;
bool has_equal_sign = false;
string key = "";
string value = "";
//try {
for (;;) {
has_equal_sign = false;
key = "";
value = "";
try {
// Read a line, break at EOF, and echo print the prompt
// if one is needed.
string line;
getline (cin, line);
if (cin.eof()) {
if (need_echo) cout << "^D";
cout << endl;
break;
}
if (need_echo) cout << line << endl;
// Split the line into words and lookup the appropriate
// function. Complain or call it.
if(line.size() > 0)
{
if(line[0] == '#')
{
// Do nothing, a comment.
}
else
{
if(line[0] == '=')
{
if(line.size() == 1)
{
// print all kv pairs
cout << "print all kv pairs\n";
for(str_str_map::iterator it = test.begin(); it != test.end();
++it)
{
cout << it->first << " " << it->second << endl;
}
}
else
{
for(unsigned int i = 1; i < line.size(); i++)
{
value.append(to_string(line[i]));
}
// call function to get all kv pairs with same value
cout << "call function to get all kv pairs with same value\n";
for(str_str_map::iterator it = test.begin(); it != test.end();
++it)
{
if(it->second == value)
{
cout << it->first << " " << it->second << endl;
}
}
}
}
else
{
for(unsigned int i = 0; i < line.size(); i++)
{
if(line[i] == '=')
{
has_equal_sign = true;
continue;
}
if(!has_equal_sign)
{
key.append(to_string(line[i]));
}
else
{
value.append(to_string(line[i]));
}
}
if(!has_equal_sign)
{
//call function to output kv pair with key
auto item = test.find(key);
if(item != str_str_map::iterator()) // key not found
{
cout << key << " " << item->second << endl;
}
else // key found
{
cout << key << ": not found" << endl;
}
}
else
{
if(value != "" && value != " ")
{
//call function to assign kv pair
test.insert(xpair <const string, string> (key,value));
}
else
{
//call function to delete kv pair with key
test.erase(test.find(key));
}
}
}
}
}
}
catch (exception& error) {
// If there is a problem discovered in any function, an
// exn is thrown and printed here.
complain() << error.what() << endl;
}*/
// }
for (char** argp = &argv[optind]; argp != &argv[argc]; ++argp) {
str_str_pair pair (*argp, to_string<int> (argp - argv));
cout << "Before insert: " << pair << endl;
test.insert (pair);
}
return EXIT_SUCCESS;
}
//=====================================================================
|
#ifndef SW_GRAPH_STR_H
#define SW_GRAPH_STR_H
#include"sw_alpha_expansion.h"
#include"sw_dataType.h"
#include "stdlib.h"
#include<vector>
#include<string>
#include<iostream>
using namespace std;
/*********************************class alpha expansion string ********************************/
class alpha_expansion_str: public alpha_expansion_base<string>
{
public:
alpha_expansion_str():alpha_expansion_base(){}
alpha_expansion_str(vector <string> & samples, vector<string>& centers):alpha_expansion_base(samples, centers)
{
}
double data_term(int id, int label);
double smooth_term(int xid, int yid, int xlabel, int ylabel);
void setSimThresh(float thresh){sim_thresh_ = thresh;}
public:
float sim_thresh_;
};
#endif
|
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class book {
public:
string name;
int phone;
int day;
int month;
int year;
int code = { 20 };
int choice;
void reserve()
{
cout << ".............BOOK YOUR ROOM ............." << endl;
cout << "Enter customer name" << endl;
cin >> name;
cout << "Enter your phone " << endl;
cin >> phone;
cout << " of check_in" << " ";
cout << " Enter day " << " ";
cin >> day;
cout << endl;
cout << "Enter month" << " ";
cin >> month;
cout << endl;
cout << "Enter year" << " ";
cin >> year;
cout << endl;
cout << "the date of check_in" << " " << day << "/" << month << "/" << year << endl;
cout << " of check_out" << " ";
cout << " Enter day " << " ";
cin >> day;
cout << endl;
cout << "Enter month" << " ";
cin >> month;
cout << endl;
cout << "Enter year" << " ";
cin >> year;
cout << endl;
cout << "the date of check_out" << " " << day << "/" << month << "/" << year << endl;
cout << endl;
cout << endl;
}
void cancelreservation()
{
cout << "......cancel reservation......" << endl;
cout << "Enter your name" << endl;;
cin >> name;
cout << endl;
cout << "Enter your phone " << endl;
cin >> phone;
cout << endl;
cout << "Please Enter this code here " << "2233" << endl;
cin >> code;
do
{
{
cout << "Your code incorrectred please enter again";
cin >> code;
}
cout << endl;
} while (code != 2233);
if (code == 2233)
{
cout << "Canceld sucssesfuly" << endl;
}
}
};
class Room {
public:
int number_of_room;
int daysOfReservation;
int roomtype;
int sum;
int bedPrice;
int pricePerNight;
int seatPrice;
int status = 0;
int room;
public:
void getroomtype() {
cout << "please choose your room";
cout << endl;
cout << "Enter 1 if you want standerd room";
cout << endl;
cout << "Enter 2 if you want sweet";
cout << endl;
cout << "Enter 3 if you want conference";
cout << endl;
cin >> roomtype;
if (roomtype == 1)
{
cout << "Enter roo num";
cin >> number_of_room;
cout << "Enter dayofreservation" << " ";
cin >> daysOfReservation;
cout << "Enter bedprice" << " ";
cin >> bedPrice;
sum = daysOfReservation * bedPrice;
cout << "price of stay " << " " << sum << endl;
status = 1;
cout << ".............BOOKING COPMLETED.............";
cout << endl;
}
else if (roomtype == 2)
{
cout << "Enter roo num";
cin >> number_of_room;
cout << "Enter dayofreservation" << " ";
cin >> daysOfReservation;
cout << "Enter pricePerNight " << " ";
cin >> pricePerNight;
sum = pricePerNight * daysOfReservation;
cout << "price of stay " << " " << sum << endl;
status = 1;
cout << ".............BOOKING COPMLETED.............";
cout << endl;
}
else if (roomtype == 3)
{
cout << "Enter roo num";
cin >> number_of_room;
cout << "Enter dayofreservation" << " ";
cin >> daysOfReservation;
cout << "Enter seatPrice" << " ";
cin >> seatPrice;
sum = seatPrice * daysOfReservation;
cout << "price of stay " << " " << sum << endl;
status = 1;
cout << ".............BOOKING COPMLETED.............";
cout << endl;
}
}
int checkstatus()
{
cout << "Enter roo num";
cin >> number_of_room;
if(status==1)
{
cout << "room is not avaliable";
return false;
}
else if (status == 0)
{
cout << "room avaliable";
return true;
}
}
};
class standerd :public Room {
protected:
int daysOfReservation;
int numberOfBeds;
int bedPrice;
int priceofreservation;
public:
void set_priceofreservation(int daysOfReservation, int bedPrice)
{
priceofreservation = daysOfReservation * bedPrice;
cout << priceofreservation;
}
int get_priceofreservation()
{
return priceofreservation;
}
};
class Sweet :public Room {
public:
int pricePerNight;
int daysOfReservation;
int priceofreservation;
public:
void set_priceofreservation(int pricePerNight, int daysOfReservation)
{
priceofreservation = daysOfReservation * pricePerNight;
cout << priceofreservation;
}
int get_priceofreservation()
{
return priceofreservation;
}
};
class ConferenceRoom :public Room
{
public:
int daysOfReservation;
int numberOfSeats;
int seatPrice;
int priceofreservation;
public:
void set_priceofreservation(int seatPrice, int daysOfReservation)
{
priceofreservation = daysOfReservation * seatPrice;
cout << priceofreservation;
}
int get_priceofreservation()
{
return priceofreservation;
}
};
class Floor:public Room {
public:
int *roomnum=new int[7];
void getavaliableroom()
{
for (int i = 0; i < 7; i++)
{if(checkstatus()==true)
{
cout << roomnum[i];
cout << endl;
}
}
}
};
int main()
{
int choice;
book t;
Floor s;
Room n;
cout << "Enter 1 if u want to book room" << endl;
cout << "Enter 2 if u want to cancel booking" << endl;
cout << "Enter 3 if u want avaliable" << endl;
cout << "Enter 4 if u want dispaly totalprice" << endl;
cin >> choice;
switch (choice)
{
case 1:
{
t.reserve();
n.checkstatus();
n.getroomtype();
n.checkstatus();
break;
}
case 2:
{
t.cancelreservation();
break;
}
case 3:
{ s.getavaliableroom();
break;
}
case 4:
{
n.getroomtype();
break;
}
return 0;
}
}
|
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <fstream>
#include <iostream>
#include <queue>
#include <set>
#include <vector>
#include <filesystem>
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
template <class T, class S, class C>
S& Container(std::priority_queue<T, S, C>& q) {
struct HackedQueue : private std::priority_queue<T, S, C> {
static S& Container(std::priority_queue<T, S, C>& q) {
return q.*&HackedQueue::c;
}
};
return HackedQueue::Container(q);
}
struct Note
{
double start, end;
int pitch;
Note(double start, double end, int pitch)
{
this->start = start;
this->end = end;
this->pitch = pitch;
}
bool operator<(const Note& other) const { return end > other.end; }
bool operator>(const Note& other) const { return start > other.start; }
};
class Sequence
{
static constexpr unsigned char ON = 0xff;
unsigned char* video_buf; // this is the video sorted in row major order.
unsigned char* final_frame; // this is the last frame that is shown
std::priority_queue<Note> cur_notes;
std::vector<Note> &cur_notes_it = Container(cur_notes);
int mapping[88], widths[88];
int frame = 0;
double scroll_time, tick_rate, tick;
int frame_rate, x_res, y_res, last_frame;
size_t position;
public:
std::priority_queue<Note, std::vector<Note>, std::greater<Note>> seq; // bad practice, but I don't care
Sequence(int length)
{
frame_rate = 24;
x_res = 1080;
y_res = 1920;
scroll_time = 5;
tick = 9.0;
tick_rate = 5.0 / 1080.0;
for (int i {}; i < 88; ++i)
{
mapping[i] = 21 * i;
widths[i] = 18;
}
video_buf = new unsigned char[(size_t)(x_res*y_res*(2 + length/scroll_time))]();
position = 0;
last_frame = frame_rate * length;
}
~Sequence()
{
// delete[] video_buf;
}
unsigned char* get_video_buf()
{
return video_buf;
}
unsigned char* get_cur_frame()
{
return final_frame;
}
void copy_first_frame(unsigned char* first_frame)
{
if (first_frame)
std::memcpy(video_buf, first_frame, x_res*y_res);
}
unsigned char* next()
{
if (frame > last_frame)
return nullptr;
for (int t = frame * tick; t < frame * tick + tick; ++t)
{
double time = t * tick_rate;
// If notes end before the tick, they are removed
while (!cur_notes.empty() and cur_notes.top().end <= time)
cur_notes.pop();
// If notes start before the tick, they are added
while (!seq.empty() and seq.top().start <= time)
{
cur_notes.push(seq.top());
seq.pop();
}
// add the row to the image
unsigned char *cur_row = video_buf + position + x_res*y_res;
for (Note note : cur_notes_it)
for (int offset = 0; offset < widths[note.pitch]; ++offset)
cur_row[mapping[note.pitch] + offset] = ON;
position += y_res;
}
++frame;
final_frame = video_buf + position;
return final_frame;
}
};
int main(int argc, char **argv)
{
std::ifstream input_file;
cv::Mat frame;
unsigned char *tmp, *first_frame = nullptr, *video_buf = nullptr;
char dummy;
double start, end, len;
int pitch, i {};
if (argc > 1)
sleep(std::stoi(argv[1]));
std::filesystem::current_path("/mnt/ramdisk");
while (true)
{
tmp = (unsigned char*)0x1; // this is just a dummy address
while (!input_file.is_open())
input_file.open(std::to_string(i) + ".txt");
input_file >> len;
input_file >> dummy; // avoid errors on empty files
Sequence v(len);
v.copy_first_frame(first_frame);
if (video_buf) delete[] video_buf;
while (input_file.good())
{
input_file >> start;
input_file >> end;
input_file >> pitch;
v.seq.push(Note(start, end, pitch));
}
input_file.close();
std::filesystem::remove(std::to_string(i) + ".txt");
// show videos like here. The file IO should be very fast.
while(tmp)
{
tmp = v.next();
if (!tmp)
break;
frame = cv::Mat(1080, 1920, CV_8U, tmp);
cv::imshow("Image", frame);
if ((char)cv::waitKey(45) == 'q')
return 0;
}
first_frame = v.get_cur_frame();
video_buf = v.get_video_buf();
++i;
}
return 0;
}
|
// LAB1.cpp : Defines the entry point for the console application.
//
#include <stdlib.h>
#include <stdio.h>
#include <cstring>
#include "altbit.h"
//#include "stdafx.h"
// The following allows this to run on Linux
#ifdef linux
#define _TCHAR char
#define scanf_s scanf
#define _tmain main
#endif
/* ******************************************************************
ALTERNATING BIT AND GO-BACK-N NETWORK EMULATOR: VERSION 1.1 J.F.Kurose
This code should be used for PA2, unidirectional or bidirectional
data transfer protocols (from A to B. Bidirectional transfer of data
is for extra credit and is not required). Network properties:
- one way network delay averages five time units (longer if there
are other messages in the channel for GBN), but can be larger
- packets can be corrupted (either the header or the data portion)
or lost, according to user-defined probabilities
- packets will be delivered in the order in which they were sent
(although some can be lost).
**********************************************************************/
#define BIDIRECTIONAL 0 /* change to 1 if you're doing extra credit */
/* and write a routine called B_output */
/* possible events: */
#define TIMER_INTERRUPT 0
#define FROM_LAYER5 1
#define FROM_LAYER3 2
#define OFF 0
#define ON 1
#define A 0
#define B 1
#define MSGSIZE 20
#define TIMEOUT 500
#define ACK "ACK"
#define NACK "NACK"
/* a "msg" is the data unit passed from layer 5 (teachers code) to layer */
/* 4 (students' code). It contains the data (characters) to be delivered */
/* to layer 5 via the students transport level protocol entities. */
struct msg {
char data[MSGSIZE];
};
/* a packet is the data unit passed from layer 4 (students code) to layer */
/* 3 (teachers code). Note the pre-defined packet structure, which all */
/* students must follow. */
struct pkt {
int seqnum;
int acknum;
int checksum;
char payload[MSGSIZE];
};
/*** START Charles Hooper's Code ***/
// Let's store last packet sent so we can resend it later
struct pkt *last_pkt;
struct pkt *last_ack;
int calc_checksum(struct pkt *tgt_pkt)
{
int checksum = 0;
checksum += tgt_pkt->seqnum;
checksum += tgt_pkt->acknum;
for(int i = 0; i < sizeof(tgt_pkt->payload) / sizeof(char); i++)
checksum += tgt_pkt->payload[i];
return checksum;
}
bool pkt_checksum_valid(struct pkt *tgt_pkt)
{
int expectedChecksum = calc_checksum(tgt_pkt);
return (expectedChecksum == tgt_pkt->checksum);
}
struct pkt *make_pkt(int seqnum, char data[MSGSIZE])
{
// make_pkt: Returns a pointer to a newly initialized packet
struct pkt *gen_pkt;
gen_pkt = new struct pkt;
gen_pkt->seqnum = seqnum;
gen_pkt->acknum = 0;
for(int i = 0; i < sizeof(gen_pkt->payload) / sizeof(char); i++) {
gen_pkt->payload[i] = data[i];
}
gen_pkt->checksum = calc_checksum(gen_pkt);
return gen_pkt;
}
void send_ack(int caller, struct pkt *pkt_to_ack)
{
int seqnum = pkt_to_ack->seqnum;
char msg[MSGSIZE] = {'A','C','K',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
struct pkt *ack_pkt = make_pkt(seqnum, msg);
ack_pkt->acknum = pkt_to_ack->seqnum;
tolayer3(caller, *ack_pkt);
}
void send_nack(int caller, struct pkt *pkt_to_nack)
{
int seqnum = pkt_to_nack->seqnum;
char msg[MSGSIZE] = {'N','A','C','K',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
struct pkt *nack_pkt = make_pkt(seqnum, msg);
nack_pkt->acknum = 0;
tolayer3(caller, *nack_pkt);
}
void send_pkt(int caller, struct pkt *pkt_to_send)
{
tolayer3(caller, *pkt_to_send);
starttimer(caller, TIMEOUT);
}
/* called from layer 5, passed the data to be sent to other side */
void A_output(struct msg message)
{
printf("CCH> A_output> Got message\n");
struct pkt *out_pkt;
int seqnum;
seqnum = (last_pkt && last_pkt->seqnum < 1) ? 1 : 0;
out_pkt = make_pkt(seqnum, message.data);
last_pkt = out_pkt;
send_pkt(A, out_pkt);
}
void B_output(struct msg message) /* need be completed only for extra credit */
{
printf("CCH> B_output> Got message\n");
}
/* called from layer 3, when a packet arrives for layer 4 */
void A_input(struct pkt packet)
{
printf("CCH> A_input> Got packet\n");
// isChecksumValid
if(pkt_checksum_valid(&packet)) {
printf("CCH> A_input> Valid checksum\n");
// isACK
if(strncmp(packet.payload, ACK, strlen(ACK)) == 0) {
if(packet.acknum == last_pkt->seqnum) {
printf("CCH> A_input> Received valid ACK\n");
last_ack = &packet;
stoptimer(A);
} else {
// We received an ACK we don't care about
printf("CCH> A_input> Received invalid ACK (ignoring)\n");
}
// isNACK
} else if (strncmp(packet.payload, NACK, strlen(ACK)) == 0) {
printf("CCH> A_input> Received NACK\n");
send_pkt(A, last_pkt);
} else {
// Message
stoptimer(A);
tolayer5(A, packet.payload);
}
} else {
printf("CCH> A_input> Invalid checksum\n");
send_nack(A, &packet);
stoptimer(A);
starttimer(A, TIMEOUT);
return;
}
}
/* called when A's timer goes off */
void A_timerinterrupt(void)
{
printf("CCH> A_timerinterrupt> Called\n");
if(last_ack && (last_ack->acknum < last_pkt->seqnum)) {
printf("CCH> A_timerinterrupt> Packet timed out, resending\n");
send_pkt(A, last_pkt);
}
}
/* the following routine will be called once (only) before any other */
/* entity A routines are called. You can use it to do any initialization */
void A_init(void)
{
printf("CCH> A_init> .\n");
last_pkt = NULL;
last_ack = NULL;
}
/* Note that with simplex transfer from a-to-B, there is no B_output() */
/* called from layer 3, when a packet arrives for layer 4 at B*/
void B_input(struct pkt packet)
{
printf("CCH> B_input> Got packet\n");
// Send ACK
send_ack(B, &packet);
// Pass message to layer 5
tolayer5(B, packet.payload);
}
/* called when B's timer goes off */
void B_timerinterrupt(void)
{
}
/* the following rouytine will be called once (only) before any other */
/* entity B routines are called. You can use it to do any initialization */
void B_init(void)
{
}
/*** END Charles Hooper's Code ***/
/*****************************************************************
***************** NETWORK EMULATION CODE STARTS BELOW ***********
The code below emulates the layer 3 and below network environment:
- emulates the tranmission and delivery (possibly with bit-level corruption
and packet loss) of packets across the layer 3/4 interface
- handles the starting/stopping of a timer, and generates timer
interrupts (resulting in calling students timer handler).
- generates message to be sent (passed from later 5 to 4)
THERE IS NOT REASON THAT ANY STUDENT SHOULD HAVE TO READ OR UNDERSTAND
THE CODE BELOW. YOU SHOLD NOT TOUCH, OR REFERENCE (in your code) ANY
OF THE DATA STRUCTURES BELOW. If you're interested in how I designed
the emulator, you're welcome to look at the code - but again, you should have
to, and you defeinitely should not have to modify
******************************************************************/
struct event {
float evtime; /* event time */
int evtype; /* event type code */
int eventity; /* entity where event occurs */
struct pkt *pktptr; /* ptr to packet (if any) assoc w/ this event */
struct event *prev;
struct event *next;
};
struct event *evlist = NULL; /* the event list */
// my function prototypes for the simulator
/*
int init(void);
float jimsrand(void);
void generate_next_arrival(void);
void insertevent( struct event *p);
void stoptimer(int AorB);
void starttimer(int AorB,float increment);
void tolayer3(int AorB,struct pkt packet);
void tolayer5(int AorB,char datasent[]);
*/
// initialize globals
int TRACE = 1; /* for my debugging */
int nsim = 0; /* number of messages from 5 to 4 so far */
int nsimmax = 0; /* number of msgs to generate, then stop */
float time = 0.000;
float lossprob; /* probability that a packet is dropped */
float corruptprob; /* probability that one bit is packet is flipped */
float lambda; /* arrival rate of messages from layer 5 */
int ntolayer3; /* number sent into layer 3 */
int nlost; /* number lost in media */
int ncorrupt; /* number corrupted by media*/
int _tmain(int argc, _TCHAR* argv[])
{
struct event *eventptr;
struct msg msg2give;
struct pkt pkt2give;
int i,j;
// char c;
init();
A_init();
B_init();
while (1) {
eventptr = evlist; /* get next event to simulate */
if (eventptr==NULL)
goto terminate;
evlist = evlist->next; /* remove this event from event list */
if (evlist!=NULL)
evlist->prev=NULL;
if (TRACE>=2) {
printf("\nEVENT time: %f,",eventptr->evtime);
printf(" type: %d",eventptr->evtype);
if (eventptr->evtype==0)
printf(", timerinterrupt ");
else if (eventptr->evtype==1)
printf(", fromlayer5 ");
else
printf(", fromlayer3 ");
printf(" entity: %d\n",eventptr->eventity);
}
time = eventptr->evtime; /* update time to next event time */
if (nsim==nsimmax)
break; /* all done with simulation */
if (eventptr->evtype == FROM_LAYER5 ) {
generate_next_arrival(); /* set up future arrival */
/* fill in msg to give with string of same letter */
j = nsim % 26;
for (i=0; i<20; i++)
msg2give.data[i] = 97 + j;
if (TRACE>2) {
printf(" MAINLOOP: data given to student: ");
for (i=0; i<20; i++)
printf("%c", msg2give.data[i]);
printf("\n");
}
nsim++;
if (eventptr->eventity == A)
A_output(msg2give);
else
B_output(msg2give);
}
else if (eventptr->evtype == FROM_LAYER3) {
pkt2give.seqnum = eventptr->pktptr->seqnum;
pkt2give.acknum = eventptr->pktptr->acknum;
pkt2give.checksum = eventptr->pktptr->checksum;
for (i=0; i<20; i++)
pkt2give.payload[i] = eventptr->pktptr->payload[i];
if (eventptr->eventity ==A) /* deliver packet by calling */
A_input(pkt2give); /* appropriate entity */
else
B_input(pkt2give);
delete(eventptr->pktptr); /* free the memory for packet */
}
else if (eventptr->evtype == TIMER_INTERRUPT) {
if (eventptr->eventity == A)
A_timerinterrupt();
else
B_timerinterrupt();
}
else {
printf("INTERNAL PANIC: unknown event type \n");
}
delete(eventptr);
}
terminate:
printf(" Simulator terminated at time %f\n after sending %d msgs from layer5\n",time,nsim);
return 0;
}
int init(void) /* initialize the simulator */
{
int i;
float sum, avg;
float jimsrand();
printf("----- Stop and Wait Network Simulator Version 1.1 -------- \n\n");
printf("Enter the number of messages to simulate: ");
scanf_s("%d",&nsimmax);
printf("Enter packet loss probability [enter 0.0 for no loss]:");
scanf_s("%f",&lossprob);
printf("Enter packet corruption probability [0.0 for no corruption]:");
scanf_s("%f",&corruptprob);
printf("Enter average time between messages from sender's layer5 [ > 0.0]:");
scanf_s("%f",&lambda);
printf("Enter TRACE:");
scanf_s("%d",&TRACE);
srand(9999); /* init random number generator */
sum = 0.0; /* test random number generator for students */
for (i=0; i<1000; i++)
sum=sum+jimsrand(); /* jimsrand() should be uniform in [0,1] */
avg = (float)(sum/1000.0);
if (avg < 0.25 || avg > 0.75) {
printf("It is likely that random number generation on your machine\n" );
printf("is different from what this emulator expects. Please take\n");
printf("a look at the routine jimsrand() in the emulator code. Sorry. \n");
return -9;
}
ntolayer3 = 0;
nlost = 0;
ncorrupt = 0;
time=0.0; /* initialize time to 0.0 */
generate_next_arrival(); /* initialize event list */
return 0;
}
/****************************************************************************/
/* jimsrand(): return a float in range [0,1]. The routine below is used to */
/* isolate all random number generation in one location. We assume that the*/
/* system-supplied rand() function return an int in therange [0,mmm] */
/****************************************************************************/
float jimsrand(void)
{
double mmm = 2147483647; /* largest int - MACHINE DEPENDENT!!!!!!!! */
float x; /* individual students may need to change mmm */
x = (float)(rand()/mmm); /* x should be uniform in [0,1] */
return(x);
}
/********************* EVENT HANDLINE ROUTINES *******/
/* The next set of routines handle the event list */
/*****************************************************/
void generate_next_arrival(void)
{
double x,log(),ceil();
struct event *evptr;
char *malloc();
// float ttime;
// int tempint;
if (TRACE>2)
printf(" GENERATE NEXT ARRIVAL: creating new arrival\n");
x = lambda*jimsrand()*2; /* x is uniform on [0,2*lambda] */
/* having mean of lambda */
// evptr = (struct event *)malloc(sizeof(struct event));
evptr = new struct event;
evptr->evtime = (float)(time + x);
evptr->evtype = FROM_LAYER5;
if (BIDIRECTIONAL && (jimsrand()>0.5) )
evptr->eventity = B;
else
evptr->eventity = A;
insertevent(evptr);
}
void insertevent( struct event *p)
{
struct event *q,*qold;
if (TRACE>2) {
printf(" INSERTEVENT: time is %lf\n",time);
printf(" INSERTEVENT: future time will be %lf\n",p->evtime);
}
q = evlist; /* q points to header of list in which p struct inserted */
if (q==NULL) { /* list is empty */
evlist=p;
p->next=NULL;
p->prev=NULL;
}
else {
for (qold = q; q !=NULL && p->evtime > q->evtime; q=q->next)
qold=q;
if (q==NULL) { /* end of list */
qold->next = p;
p->prev = qold;
p->next = NULL;
}
else if (q==evlist) { /* front of list */
p->next=evlist;
p->prev=NULL;
p->next->prev=p;
evlist = p;
}
else { /* middle of list */
p->next=q;
p->prev=q->prev;
q->prev->next=p;
q->prev=p;
}
}
}
void printevlist(void)
{
struct event *q;
// int i;
printf("--------------\nEvent List Follows:\n");
for(q = evlist; q!=NULL; q=q->next) {
printf("Event time: %f, type: %d entity: %d\n",q->evtime,q->evtype,q->eventity);
}
printf("--------------\n");
}
/********************** Student-callable ROUTINES ***********************/
/* called by students routine to cancel a previously-started timer */
void stoptimer(int AorB)
/* A or B is trying to stop timer */
{
struct event *q;//,*qold;
if (TRACE>2)
printf(" STOP TIMER: stopping timer at %f\n",time);
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next) */
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==TIMER_INTERRUPT && q->eventity==AorB) ) {
/* remove this event */
if (q->next==NULL && q->prev==NULL)
evlist=NULL; /* remove first and only event on list */
else if (q->next==NULL) /* end of list - there is one in front */
q->prev->next = NULL;
else if (q==evlist) { /* front of list - there must be event after */
q->next->prev=NULL;
evlist = q->next;
}
else { /* middle of list */
q->next->prev = q->prev;
q->prev->next = q->next;
}
delete(q);
return;
}
printf("Warning: unable to cancel your timer. It wasn't running.\n");
}
void starttimer(int AorB,float increment)
/* A or B is trying to stop timer */
{
struct event *q;
struct event *evptr;
char *malloc();
if (TRACE>2)
printf(" START TIMER: starting timer at %f\n",time);
/* be nice: check to see if timer is already started, if so, then warn */
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next) */
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==TIMER_INTERRUPT && q->eventity==AorB) ) {
printf("Warning: attempt to start a timer that is already started\n");
return;
}
/* create future event for when timer goes off */
// evptr = (struct event *)malloc(sizeof(struct event));
evptr = new struct event;
evptr->evtime = time + increment;
evptr->evtype = TIMER_INTERRUPT;
evptr->eventity = AorB;
insertevent(evptr);
}
/************************** TOLAYER3 ***************/
void tolayer3(int AorB,struct pkt packet)
/* A or B is trying to stop timer */
{
struct pkt *mypktptr;
struct event *evptr,*q;
char *malloc();
float lastime, x, jimsrand();
int i;
ntolayer3++;
/* simulate losses: */
if (jimsrand() < lossprob) {
nlost++;
if (TRACE>0)
printf(" TOLAYER3: packet being lost\n");
return;
}
/* make a copy of the packet student just gave me since he/she may decide */
/* to do something with the packet after we return back to him/her */
//mypktptr = (struct pkt *)malloc(sizeof(struct pkt));
mypktptr = new struct pkt;
mypktptr->seqnum = packet.seqnum;
mypktptr->acknum = packet.acknum;
mypktptr->checksum = packet.checksum;
for (i=0; i<20; i++)
mypktptr->payload[i] = packet.payload[i];
if (TRACE>2) {
printf(" TOLAYER3: seq: %d, ack %d, check: %d ", mypktptr->seqnum,
mypktptr->acknum, mypktptr->checksum);
for (i=0; i<20; i++)
printf("%c",mypktptr->payload[i]);
printf("\n");
}
/* create future event for arrival of packet at the other side */
// evptr = (struct event *)malloc(sizeof(struct event));
evptr = new struct event;
evptr->evtype = FROM_LAYER3; /* packet will pop out from layer3 */
evptr->eventity = (AorB+1) % 2; /* event occurs at other entity */
evptr->pktptr = mypktptr; /* save ptr to my copy of packet */
/* finally, compute the arrival time of packet at the other end.
medium can not reorder, so make sure packet arrives between 1 and 10
time units after the latest arrival time of packets
currently in the medium on their way to the destination */
lastime = time;
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next) */
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==FROM_LAYER3 && q->eventity==evptr->eventity) )
lastime = q->evtime;
evptr->evtime = lastime + 1 + 9*jimsrand();
/* simulate corruption: */
if (jimsrand() < corruptprob) {
ncorrupt++;
if ( (x = jimsrand()) < .75)
mypktptr->payload[0]='Z'; /* corrupt payload */
else if (x < .875)
mypktptr->seqnum = 999999;
else
mypktptr->acknum = 999999;
if (TRACE>0)
printf(" TOLAYER3: packet being corrupted\n");
}
if (TRACE>2)
printf(" TOLAYER3: scheduling arrival on other side\n");
insertevent(evptr);
}
void tolayer5(int AorB,char datasent[])
{
int i;
if (TRACE>2) {
printf(" TOLAYER5: data received: ");
for (i=0; i<20; i++)
printf("%c",datasent[i]);
printf("\n");
}
}
|
#include <cstdio>
#include <climits>
#include <vector>
using namespace std;
const int MAX_M = 100;
const int MAX_N = 100;
const int INF = std::numeric_limits<int>::max(); //2,147,483,647 == 2^31 -1
//INPUT
int M,N;
int X1[MAX_M], Y1[MAX_M];
int X2[MAX_N], Z2[MAX_N];
// slice by x
double width(int* X, int* Y, int n, double x){
double lb = INF, ub = -INF;
for (int i=0; i<n; i++){
double x1 = X[i], y1 = Y[i], x2 = X[(i+1) % n], y2 = Y[(i+1) % n];
// intersects with edge i?
if ( (x1-x) * (x2 -x) <= 0 && x1 != x2){
// intersecting point
double y = y1 + (y2 - y1) * (x - x1) / (x2 - x1);
lb = min (lb, y);
ub = max (ub, y);
}
}
return max(0.0, ub - lb);
}
void solve(){
// enumerate vertices of segments
int min1 = *min_element(X1, X1+M), max1 = *max_element(X1, X1+M);
int min2 = *min_element(X2, X2+N), max2 = *max_element(X2, X2+N);
vector<int> xs;
for(int i=0; i<M; i++) xs.push_back(X1[i]);
for(int i=0; i<N; i++) xs.push_back(X2[i]);
sort(xs.begin(), xs.end());
double res = 0;
for (int i=0; i+1 < xs.size(); i++){
double a = xs[i], b = xs[i+1], c = (a+b)/2;
if (min1 <= c && c <= max1 && min2 <= c && c<= max2) {
// Simpson
double fa = width(X1, Y1, M, a) * width(X2, Z2, N, a);
double fb = width(X1, Y1, M, b) * width(X2, Z2, N, b);
double fc = width(X1, Y1, M, c) * width(X2, Z2, N, c);
res += (b-a) / 6 * (fa + 4 * fc + fb);
}
}
printf("%.10f\n", res);
}
int main(){
//INPUT
M=4,N=3;
X1[0] = 7, Y1[0] = 2;
X1[1] = 3, Y1[1] = 3;
X1[2] = 0, Y1[2] = 2;
X1[3] = 3, Y1[3] = 1;
X2[0] = 4, Z2[0] = 2;
X2[1] = 0, Z2[1] = 1;
X2[2] = 8, Z2[2] = 1;
solve();
}
|
#include <bits/stdc++.h>
#include <time.h>
using namespace std;
#define ll long long
#define ld long double
#define uint unsigned int
#define ull unsigned long long
void print(vector<int> &t) {
for (int i = 0; i < (int)t.size(); ++i)
cout << t[i] << " ";
cout << "\n";
}
ll dp[2001][2001];
ll MOD = 1e9;
int main() {
// freopen("file.in", "r", stdin);
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
for (int i = 0; i < n; ++i) dp[0][i] = 0LL;
for (int i = 0; i < n; ++i) dp[1][i] = 1LL;
for (int c = 2; c <= n; ++c) {
for (int i = 0; i < n; ++i) {
if (i + c - 1 >= n)
break;
dp[c][i] = (dp[c - 1][i] + dp[c - 1][i + 1]);
if (a[i] == a[i + c - 1])
dp[c][i] = (dp[c - 1][i] + dp[c - 1][i + 1] + 1) % MOD;
else
dp[c][i] = (dp[c - 1][i] + dp[c - 1][i + 1] - dp[c - 2][i + 1] + MOD) % MOD;
}
}
cout << dp[n][0] << endl;
return 0;
}
|
/*Ques. 10. Design a scheduler with multilevel queue having two queues which will schedule the processes
on the basis of pre-emptive shortest remaining processing time first algorithm (SROT) followed by a
scheduling in which each process will get 2 units of time to execute. Also note that queue
1 Has higher priority than queue 2
Calculate the average turnaround time and average waiting time for each process.
The input for number of processes and their arrival time, burst time should be given by the user.*/
#include <iostream>
#include <stdio.h>
#include <Windows.h>
struct processes
{
short int arrival, burst, burst_backup, completion = 0, turn_around = 0, waiting = 0, response = 0, queue;
} * process;
short int total_time = 0, time_quantum = 2, processes_count, queue_count;
int get_max_queue()
{
int max = 0;
for (short int index = 0; index < processes_count; index++)
{
if (process[index].queue > max)
{
max = process[index].queue;
}
}
return max;
}
bool all_processes_completed()
{
for (short int index = 0; index < processes_count; index++)
{
if (process[index].burst > 0)
{
return FALSE;
}
}
return TRUE;
}
int get_process_with_less_burst_time_in_queue(int queue)
{
int less_burst_time = 0, process_index = 0;
for (short int index = 0; index < processes_count; index++)
{
if (process[index].burst > 0 && process[index].queue == queue && total_time >= process[index].arrival)
{
less_burst_time = process[index].burst;
process_index = index;
break;
}
}
for (short int index = 0; index < processes_count; index++)
{
if (less_burst_time > process[index].burst && (process[index].burst > 0) && (process[index].queue == queue) && total_time >= process[index].arrival)
{
less_burst_time = process[index].burst;
process_index = index;
}
}
return process_index;
}
int get_queue_with_highest_priority_containing_process()
{
for (int priority = 0; priority <= queue_count; priority++)
{
for (int index = 0; index < processes_count; index++)
{
if (process[index].queue == priority && process[index].burst > 0 && total_time >= process[index].arrival)
{
return process[index].queue;
}
}
}
}
bool all_arrived_processes_completed()
{
for (short int index = 0; index < processes_count; index++)
{
if (process[index].burst > 0 && total_time >= process[index].arrival)
{
return FALSE;
}
}
return TRUE;
}
void execute_processes()
{
while (!all_processes_completed())
{
if (!all_arrived_processes_completed())
{
int process_id = get_process_with_less_burst_time_in_queue(get_queue_with_highest_priority_containing_process());
for (short int time_q = 0; time_q < time_quantum; time_q++)
{
--process[process_id].burst;
++total_time;
printf("\nProcess %d executing...", process_id);
Sleep(1000);
for (short int index = 0; index < processes_count; index++)
{
if (index != process_id && total_time > process[index].arrival && process[index].burst > 0)
{
++process[index].waiting;
}
}
if (process[process_id].burst == 0)
{
process[process_id].completion = total_time;
process[process_id].turn_around = process[process_id].completion - process[process_id].arrival;
printf("\nProcess %d executed", process_id);
break;
}
if (get_queue_with_highest_priority_containing_process() < process[process_id].queue)
{
break;
}
}
}
else
{
++total_time;
}
}
}
int main()
{
printf("Enter Processes Count : ");
scanf("%d", &processes_count);
process = new processes[processes_count];
printf("\nEnter Foramt AT BT QN (Starts from 0)\n");
for (short int index = 0; index < processes_count; index++)
{
printf("\nP%d details : ", index);
scanf("%d %d %d", &process[index].arrival, &process[index].burst, &process[index].queue);
process[index].burst_backup = process[index].burst;
}
system("cls");
queue_count = get_max_queue();
printf("Execution Started : \n");
execute_processes();
printf("\n\nAll Processes executed\n\n");
system("pause");
system("cls");
printf("\n\nProcess : Arival\t Burst\t Queue\t Compt\t Turn\t Waiting\t\n");
printf("__________________________________________________________________\n");
for (short int index = 0; index < processes_count; index++)
{
printf("Process %d : %d\t %d\t %d\t %d\t %d\t %d\n\n", index, process[index].arrival, process[index].burst_backup, process[index].queue, process[index].completion, process[index].turn_around, process[index].waiting);
}
printf("\n__________________________________________________________________\n");
float total_turnaround_time = 0, total_waiting_time = 0;
for (short int index = 0; index < processes_count; index++)
{
total_turnaround_time += process[index].turn_around;
}
total_turnaround_time /= processes_count;
for (short int index = 0; index < processes_count; index++)
{
total_waiting_time += process[index].waiting;
}
total_waiting_time /= processes_count;
printf("\nAverage Turn around Time : %.2f\n", total_turnaround_time);
printf("\nAverage Waiting Time : %.2f\n\n\n", total_waiting_time);
system("pause");
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
|
//
// SMPath.h
// SMFrameWork
//
// Created by SteveMac on 2018. 7. 3..
//
#ifndef SMPath_h
#define SMPath_h
// Bezier 따라 만든거
#include <cocos2d.h>
#include <vector>
class SMPath
{
public:
SMPath();
virtual ~SMPath();
inline int size() {return (int)_vertices.size();}
inline void reset() {_vertices.clear(); _length=0;}
inline float getLength() {return _length;}
void addBack(const cocos2d::Vec2& pt);
void addFront(const cocos2d::Vec2& pt);
const cocos2d::Vec2& getVertex(int index);
const std::vector<cocos2d::Vec2>& getVertices() {return _vertices;}
const cocos2d::Vec2& getLastPosition() { return getVertex(size()-1); }
const float getLastAngle();
SMPath getSubPath(float t);
void setLine(const cocos2d::Vec2& origin, const cocos2d::Vec2& destination);
void setRect(const cocos2d::Vec2& origin, const cocos2d::Vec2& destination);
void setCircle(const cocos2d::Vec2& center, float radius, float angle, int segments);
void setQuadBezier(const cocos2d::Vec2& origin, const cocos2d::Vec2& control, const cocos2d::Vec2& destination, int segments);
void setCubicBezier(const cocos2d::Vec2& origin, const cocos2d::Vec2& control1, const cocos2d::Vec2& control2, const cocos2d::Vec2& destination, int segments);
protected:
void postProcess();
float calculateLength(const std::vector<cocos2d::Vec2>& vertices);
private:
std::vector<cocos2d::Vec2> _vertices;
float _length;
};
#endif /* SMPath_h */
|
/*
* 길 찾기 게임
* 전무로 승진한 라이언은 기분이 너무 좋아 프렌즈를 이끌고 특별 휴가를 가기로 했다.
* 내친김에 여행 계획까지 구상하던 라이언은 재미있는 게임을 생각해냈고 역시 전무로 승진할만한 인재라고 스스로에게 감탄했다.
*
* 라이언이 구상한(그리고 아마도 라이언만 즐거울만한) 게임은, 카카오 프렌즈를 두 팀으로 나누고,
* 각 팀이 같은 곳을 다른 순서로 방문하도록 해서 먼저 순회를 마친 팀이 승리하는 것이다.
*
* 그냥 지도를 주고 게임을 시작하면 재미가 덜해지므로, 라이언은 방문할 곳의 2차원 좌표 값을 구하고
* 각 장소를 이진트리의 노드가 되도록 구성한 후, 순회 방법을 힌트로 주어 각 팀이 스스로 경로를 찾도록 할 계획이다.
*
* 라이언은 아래와 같은 특별한 규칙으로 트리 노드들을 구성한다.
* 트리를 구성하는 모든 노드의 x, y 좌표 값은 정수이다.
* 모든 노드는 서로 다른 x값을 가진다.
* 같은 레벨(level)에 있는 노드는 같은 y 좌표를 가진다.
* 자식 노드의 y 값은 항상 부모 노드보다 작다.
* 임의의 노드 V의 왼쪽 서브 트리(left subtree)에 있는 모든 노드의 x값은 V의 x값보다 작다.
* 임의의 노드 V의 오른쪽 서브 트리(right subtree)에 있는 모든 노드의 x값은 V의 x값보다 크다.
*
* 다행히 두 팀 모두 머리를 모아 분석한 끝에 라이언의 의도를 간신히 알아차렸다.
*
* 곤경에 빠진 카카오 프렌즈를 위해 이진트리를 구성하는 노드들의 좌표가 담긴 배열 nodeinfo가 매개변수로 주어질 때,
* 노드들로 구성된 이진트리를 전위 순회, 후위 순회한 결과를 2차원 배열에 순서대로 담아 return 하도록 solution 함수를 완성하자.
*
* https://programmers.co.kr/learn/courses/30/lessons/42892
*/
#include <algorithm>
#include <vector>
using namespace std;
class node
{
public:
int i;
int x, y;
node *left = nullptr;
node *right = nullptr;
node(int i, int x, int y) : i(i), x(x), y (y) {}
void add(node *other)
{
if (other->x < x)
{
if (left)
left->add(other);
else
left = other;
}
else
{
if (right)
right->add(other);
else
right = other;
}
}
void preorder(vector<int> &ans)
{
ans.push_back(i);
if (left)
left->preorder(ans);
if (right)
right->preorder(ans);
}
void postorder(vector<int> &ans)
{
if (left)
left->postorder(ans);
if (right)
right->postorder(ans);
ans.push_back(i);
}
};
vector<vector<int>> solution(vector<vector<int>> nodeinfo) {
vector<vector<int>> answer(2, vector<int>());
for (int i = 0; i < nodeinfo.size(); ++i)
nodeinfo[i].push_back(i+1);
sort(nodeinfo.begin(), nodeinfo.end(), [](const vector<int> &a, const vector<int> &b)
{
if (a[1] == b[1])
return a[0] < b[0];
return a[1] > b[1];
} );
node base(nodeinfo[0][2], nodeinfo[0][0], nodeinfo[0][1]);
for (int i = 1; i < nodeinfo.size(); ++i)
{
node *new_node = new node(nodeinfo[i][2], nodeinfo[i][0], nodeinfo[i][1]);
base.add(new_node);
}
base.preorder(answer[0]);
base.postorder(answer[1]);
return answer;
}
|
#include <cstddef>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (!head) return head;
ListNode *l1 = head, *l2;
int count = 0;
while (l1) {
++count;
l1 = l1->next;
}
k = k % count;
l1 = head;
l2 = head;
for (int i = 0; i < k; ++i) {
l2 = l2->next;
}
while (l2) {
l1 = l1->next;
l2 = l2->next;
}
ListNode *res = new ListNode(0);
ListNode *ln = res;
while (l1) {
ln->next = new ListNode(l1->val);
ln = ln->next;
l1 = l1->next;
}
ListNode *l3 = head;
for (int i = 0; i < (count - k); ++i) {
ln->next = new ListNode(l3->val);
ln = ln->next;
l3 = l3->next;
}
ln->next = NULL;
ln = ln->next;
return res->next;
}
};
|
#pragma once
// Warning disabled ---
#pragma warning( disable : 4577 ) // Warning that exceptions are disabled
#pragma warning( disable : 4530 )
#include <windows.h>
#include <stdio.h>
#include <utility>
#include <experimental\filesystem>
#include <string>
#define LOG_OUT(format, ...) log(__FILE__, __LINE__, format, __VA_ARGS__);
void log(const char file[], int line, const char* format, ...);
#define CAP(n) ((n <= 0.0f) ? n=0.0f : (n >= 1.0f) ? n=1.0f : n=n)
#define DEGTORAD 0.0174532925199432957f
#define RADTODEG 57.295779513082320876f
#define HAVE_M_PI
#define RELEASE( x )\
{\
if( x != nullptr )\
{\
delete x;\
x = nullptr;\
}\
}
typedef unsigned int uint;
std::string GetFile(const char * path, bool take_extension = true);
std::string GetExtension(const char * path);
const char* GetCExtension(const char * path);
float RandomNumber(float min = INT_MIN, float max = INT_MAX);
enum update_status
{
UPDATE_CONTINUE = 1,
UPDATE_STOP,
UPDATE_ERROR
};
// Configuration -----------
#define SCREEN_WIDTH 1280
#define SCREEN_HEIGHT 1024
#define SCREEN_SIZE 1
#define WIN_FULLSCREEN false
#define WIN_RESIZABLE true
#define WIN_BORDERLESS false
#define WIN_FULLSCREEN_DESKTOP false
#define VSYNC true
#define TITLE "3D Physics Playground"
|
#include<bits/stdc++.h>
using namespace std;
bool used[1001][1001];
bool Y[1001], X[1001];
pair< int, pair<int,int> > p[1000010];
int main(){
int n,m;
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++) for(int j=0;j<m;j++){
int t;
scanf("%d",&t);
p[m*i+j] = {-t,{i,j}};
}
sort(p,p+n*m);
long long ans = 0ll;
for(int i=0;i<n*m;i++){
int y = p[i].second.first;
int x = p[i].second.second;
int val = -p[i].first;
if(Y[y]==1&&X[x]==1) ans += val;
else Y[y] = X[x] = 1;
}
printf("%lld",ans);
}
|
//-----------------------------------------------------------------------------
// File: XBUtil.h
//
// Desc: Shortcut macros and helper functions for the XBox samples
//
// Hist: 11.01.00 - New for November XDK release
// 12.01.00 - Moved input code to XBInput.cpp
// 12.15.00 - Changes for December XDK release
// 12.09.02 - Added a DrawRect() function
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef XBUTIL_H
#define XBUTIL_H
#include <xtl.h>
#include <tchar.h>
#include <assert.h>
//-----------------------------------------------------------------------------
// g0at3r's Added
//-----------------------------------------------------------------------------
#include <string>
using namespace std;
void GetXboxNick();
int RandomNumber(int iMin, int iMax);
float RandomNumber(float fMin, float fMax);
void DrawTexturedQuad(LPDIRECT3DTEXTURE8 pTexture, int iLeft, int iRight, int iTop, int iBottom, int iDestLeft, int iDestRight, int iDestTop, int iDestBottom);
string XGetDriveSize(char Drive);
string XGetDriveFree(char Drive);
string XMakeNiceNumber(ULONGLONG &u64Value, TCHAR tcComma);
DWORD StringToDWORD(string sValue);
//-----------------------------------------------------------------------------
// Miscellaneous helper macros
//-----------------------------------------------------------------------------
// For deleting and releasing objects
#define SAFE_DELETE(p) { delete (p); (p)=NULL; }
#define SAFE_DELETE_ARRAY(p) { delete[] (p); (p)=NULL; }
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
#ifdef _DEBUG
#define OUTPUT_DEBUG_STRING(s) OutputDebugStringA(s)
#else
#define OUTPUT_DEBUG_STRING(s) (VOID)(s)
#endif
//-----------------------------------------------------------------------------
// Name: XBUtil_DebugPrint()
// Desc: For printing to the debugger with formatting.
//-----------------------------------------------------------------------------
void XBUtil_DebugPrint( const char *buf, ... );
// For converting a FLOAT to a DWORD (useful for SetRenderState() calls)
inline DWORD FtoDW( FLOAT f ) { return *((DWORD*)&f); }
//-----------------------------------------------------------------------------
// Name: XBUtil_SetMediaPath() and XBUtil_FindMediaFile()
// Desc: Functions for setting a media path and returning a valid path to a
// media file.
//-----------------------------------------------------------------------------
VOID XBUtil_SetMediaPath( const CHAR* strPath );
HRESULT XBUtil_FindMediaFile( CHAR* strPath, const CHAR* strFilename );
//-----------------------------------------------------------------------------
// Name: XBox specifc counters
// Desc: The CPU runs at 733MHz, therefore
// Time in micro seconds = ticks / 733MHz = ticks * 3/2200
// Note: using DOUBLE to maintain percision
// See "A Note On Timers" whitepaper
//-----------------------------------------------------------------------------
__forceinline __int64 GetMachineTime() { __asm rdtsc }
__forceinline __int64 GetTimeInMicroSeconds() { return GetMachineTime()*3/2200;}
__forceinline DOUBLE GetTimeInSeconds() { return GetTimeInMicroSeconds() / 1000000.0;}
//-----------------------------------------------------------------------------
// Name: XBUtil_Timer()
// Desc: Performs timer operations. Use the following commands:
// TIMER_RESET - to reset the timer
// TIMER_START - to start the timer
// TIMER_STOP - to stop (or pause) the timer
// TIMER_ADVANCE - to advance the timer by 0.1 seconds
// TIMER_RETRACT - to retract the timer by 0.1 seconds
// TIMER_GETABSOLUTETIME - to get the absolute system time
// TIMER_GETAPPTIME - to get the current time
//-----------------------------------------------------------------------------
enum TIMER_COMMAND { TIMER_RESET, TIMER_START, TIMER_STOP,
TIMER_ADVANCE, TIMER_RETRACT,
TIMER_GETABSOLUTETIME, TIMER_GETAPPTIME };
FLOAT XBUtil_Timer( TIMER_COMMAND command );
//-----------------------------------------------------------------------------
// Name: XBUtil_DrawRect()
// Desc: Draws an outlined, filled rectangle
//-----------------------------------------------------------------------------
VOID XBUtil_DrawRect( FLOAT x1, FLOAT y1, FLOAT x2, FLOAT y2, DWORD dwFillColor, DWORD dwOutlineColor );
VOID XBUtil_DrawCustomRect( FLOAT fTLX, FLOAT fTLY, FLOAT fTRX, FLOAT fTRY, FLOAT fBLX, FLOAT fBLY,
FLOAT fBRX, FLOAT fBRY, DWORD dwFillColor, DWORD dwOutlineColor, int iOutlineSize = 1 );
//-----------------------------------------------------------------------------
// Name: XBUtil_InitMaterial()
// Desc: Initializes a D3DMATERIAL8 structure, setting the diffuse and ambient
// colors. It does not set emissive or specular colors.
//-----------------------------------------------------------------------------
VOID XBUtil_InitMaterial( D3DMATERIAL8& mtrl, FLOAT r=0.0f, FLOAT g=0.0f,
FLOAT b=0.0f, FLOAT a=1.0f );
//-----------------------------------------------------------------------------
// Name: XBUtil_InitLight()
// Desc: Initializes a D3DLIGHT structure, setting the light position. The
// diffuse color is set to white, specular and ambient left as black.
//-----------------------------------------------------------------------------
VOID XBUtil_InitLight( D3DLIGHT8& light, D3DLIGHTTYPE ltType,
FLOAT x=0.0f, FLOAT y=0.0f, FLOAT z=0.0f );
//-----------------------------------------------------------------------------
// Name: XBUtil_CreateTexture()
// Desc: Helper function to create a texture.
//-----------------------------------------------------------------------------
HRESULT XBUtil_CreateTexture( LPDIRECT3DDEVICE8 pd3dDevice, const CHAR* strTexture,
LPDIRECT3DTEXTURE8* ppTexture, D3DFORMAT d3dFormat = D3DFMT_UNKNOWN );
//-----------------------------------------------------------------------------
// Name: XBUtil_UnswizzleTexture() / XBUtil_SwizzleTexture()
// Desc: Unswizzles / swizzles a texture before it gets unlocked. Note: this
// operation is typically very slow.
//-----------------------------------------------------------------------------
VOID XBUtil_UnswizzleTexture2D( D3DLOCKED_RECT* pLock, const D3DSURFACE_DESC* pDesc );
VOID XBUtil_UnswizzleTexture3D( D3DLOCKED_BOX* pLock, const D3DVOLUME_DESC* pDesc );
VOID XBUtil_SwizzleTexture2D( D3DLOCKED_RECT* pLock, const D3DSURFACE_DESC* pDesc );
VOID XBUtil_SwizzleTexture3D( D3DLOCKED_BOX* pLock, const D3DVOLUME_DESC* pDesc );
//-----------------------------------------------------------------------------
// Name: XBUtil_CreateVertexShader()
// Desc: Creates a file-based vertex shader
//-----------------------------------------------------------------------------
HRESULT XBUtil_CreateVertexShader( const CHAR* strFilename,
const DWORD* pdwVertexDecl,
DWORD* pdwVertexShader );
//-----------------------------------------------------------------------------
// Name: XBUtil_CreatePixelShader()
// Desc: Creates a file-based pixel shader
//-----------------------------------------------------------------------------
HRESULT XBUtil_CreatePixelShader( const CHAR* strFilename, DWORD* pdwPixelShader );
//-----------------------------------------------------------------------------
// Name: XBUtil_VectorToRGBA()
// Desc: Converts a normal into an RGBA vector.
//-----------------------------------------------------------------------------
inline D3DCOLOR XBUtil_VectorToRGBA( const D3DXVECTOR3* v, FLOAT fHeight = 1.0f )
{
D3DCOLOR r = (D3DCOLOR)( ( v->x + 1.0f ) * 127.5f );
D3DCOLOR g = (D3DCOLOR)( ( v->y + 1.0f ) * 127.5f );
D3DCOLOR b = (D3DCOLOR)( ( v->z + 1.0f ) * 127.5f );
D3DCOLOR a = (D3DCOLOR)( 255.0f * fHeight );
return( (a<<24L) + (r<<16L) + (g<<8L) + (b<<0L) );
}
//-----------------------------------------------------------------------------
// Name: XBUtil_GetCubeMapViewMatrix()
// Desc: Returns a view matrix for rendering to a face of a cube map.
//-----------------------------------------------------------------------------
D3DXMATRIX XBUtil_GetCubeMapViewMatrix( DWORD dwFace );
//-----------------------------------------------------------------------------
// Name: XBUtil_CreateNormalizationCubeMap()
// Desc: Creates a cube map and fills it with normalized RGBA vectors.
//-----------------------------------------------------------------------------
HRESULT XBUtil_CreateNormalizationCubeMap( DWORD dwSize,
LPDIRECT3DCUBETEXTURE8* ppCubeMap );
//-----------------------------------------------------------------------------
// Name: XBUtil_DumpSurface()
// Desc: Writes the contents of a surface (32-bit only) to a .tga file. This
// could be a back buffer, texture, or any other 32-bit surface.
//-----------------------------------------------------------------------------
HRESULT XBUtil_DumpSurface( LPDIRECT3DSURFACE8 pSurface, const CHAR* strFileName,
BOOL bSurfaceIsTiled = FALSE );
//-----------------------------------------------------------------------------
// Name: XBUtil_EvaluateHermite()
// Desc: Evaluate a cubic parametric equation. Returns the point at u on a
// Hermite curve.
//-----------------------------------------------------------------------------
D3DXVECTOR3 XBUtil_EvaluateHermite( const D3DXVECTOR3& p0, const D3DXVECTOR3& p1,
const D3DXVECTOR3& v0, const D3DXVECTOR3& v1,
FLOAT u );
//-----------------------------------------------------------------------------
// Name: XBUtil_EvaluateCatmullRom()
// Desc: Evaluate a cubic parametric equation. Returns the point at u on a
// Catmull-Rom curve.
//-----------------------------------------------------------------------------
D3DXVECTOR3 XBUtil_EvaluateCatmullRom( const D3DXVECTOR3& p1, const D3DXVECTOR3& p2,
const D3DXVECTOR3& p3, const D3DXVECTOR3& p4,
FLOAT u );
//-----------------------------------------------------------------------------
// Name: XBUtil_GetSplinePoint()
// Desc: Returns a point on a spline. The spline is defined by an array of
// points, and the point and tangent returned are located at position t
// on the spline, where 0 < t < dwNumSplinePts.
//-----------------------------------------------------------------------------
VOID XBUtil_GetSplinePoint( const D3DXVECTOR3* pSpline, DWORD dwNumSplinePts, FLOAT t,
D3DXVECTOR3* pvPoint, D3DXVECTOR3* pvTangent );
//-----------------------------------------------------------------------------
// Name: XBUtil_RenderSpline()
// Desc: For debugging purposes, visually renders a spline.
//-----------------------------------------------------------------------------
VOID XBUtil_RenderSpline( const D3DXVECTOR3* pSpline, DWORD dwNumSplinePts,
DWORD dwColor, BOOL bRenderAxes );
//-----------------------------------------------------------------------------
// Name: XBUtil_DeclaratorFromFVF()
// Desc: Create a vertex declaration from an FVF. Registers are assigned as
// follows:
// v0 = Vertex position
// v1 = Vertex blend weights
// v2 = Vertex normal
// v3 = Vertex diffuse color
// v4 = Vertex specular color
// // v5 = Vertex fog (no FVF code)
// // v6 = Vertex pointsize (no FVF code)
// // v7 = Vertex back diffuse color (no FVF code)
// // v8 = Vertex back specular color (no FVF code)
// v9-v12 = Vertex texture coords
//-----------------------------------------------------------------------------
HRESULT XBUtil_DeclaratorFromFVF( DWORD dwFVF,
DWORD Declaration[MAX_FVF_DECL_SIZE] );
//-----------------------------------------------------------------------------
// Name: XBUtil_GetWide()
// Desc: Convert CHAR string to WCHAR string. dwMax includes the null byte.
// Never copies more than dwMax-1 characters into strWide.
// Ex: GetWide( "abc", strWide, 3 ) gives strWide = L"ab"
//-----------------------------------------------------------------------------
VOID XBUtil_GetWide( const CHAR* strThin, WCHAR* strWide, DWORD dwMax );
//-----------------------------------------------------------------------------
// Name: XBUtil_LoadFile()
// Desc: Loads the specified file into a newly allocated buffer. Note that
// dwSize is the size of the actual data, which is not necessarily the
// size of the buffer. Caller is expected to free the buffer using free().
//-----------------------------------------------------------------------------
HRESULT XBUtil_LoadFile( const CHAR* strFile, VOID** ppFileData,
DWORD* pdwSize = NULL );
#endif // XBUTIL_H
|
/*****
描述
编写程序,将大于整数m且紧靠m的k个素数输出(k小于10)。
关于输入
输入为一行,包括两个整数,第一个为整数m,第二个为个数k
关于输出
输出为一行,即满足条件的k个素数
例子输入
3 4
例子输出
5 7 11 13
*****/
#include <iostream>
using namespace std;
#define MAX_N 10000
int prime[MAX_N] = {2, 3, 5, 7}, n_prime = 4;
bool check_prime(int num)
{
for (int i = 0; i < n_prime && prime[i] < num; i++)
if (num % prime[i] == 0)
return false;
if (prime[n_prime-1] < num)
prime[n_prime++] = num;
return true;
}
int main()
{
int m, k;
bool whitespace = false;
cin >> m >> k;
for (int i = prime[n_prime-1] + 2; i <= m; i += 2)
check_prime(i);
for (int i = m + 1; k > 0; i++)
if (check_prime(i))
{
if (whitespace)
cout << " ";
else
whitespace = true;
cout << i;
k--;
}
return 0;
}
|
#include "device.h"
#include "pin.h"
#include "spi.h"
#include "flexio.h"
#include "intrpt.h"
#include "delay.h"
#include "spisoft.h"
#ifndef XPT2046_H
#define XPT2046_H
const uint8_t channelY = 0x90;
const uint8_t channelX = 0xD0;
class Xpt2046
{
private:
using modeF= void (Xpt2046::*) ();
//variables
uint16_t x, y;
uint16_t Xmin, Ymin, dX, dY;
uint8_t ptrF;
static modeF func [3];
public:
Pin cs;
Spi * spiDriver;
Spis * softDriver;
Flexio * fDriver;
Intrpt irq;
public:
Xpt2046 (Spi &, Gpio::Port cs_, uint16_t csp, Gpio::Port irq_, uint16_t irqp);
Xpt2046 (Spis &, Gpio::Port irq_, uint16_t irqp);
Xpt2046 (Flexio &, Gpio::Port cs_, uint16_t csp, Gpio::Port irq_, uint16_t irqp);
void getData ();
void getDataSpi ();
void getDataSoft ();
uint16_t & getX ();
uint16_t & getY ();
uint16_t & getdX ();
uint16_t & getdY ();
void clearFlag ();
};
#endif
|
/**
* $Source: /backup/cvsroot/project/pnids/zdk/zls/zfc/SmartPointer.hpp,v $
*
* $Date: 2001/11/14 17:25:10 $
*
* $Revision: 1.3 $
*
* $Name: $
*
* $Author: zls $
*
* Copyright(C) since 1998 by Albert Zheng - 郑立松, All Rights Reserved.
*
* lisong.zheng@gmail.com
*
* $State: Exp $
*/
#ifndef _ZLS_zfc_SmartPointer_hpp_
#define _ZLS_zfc_SmartPointer_hpp_
#include <zls/zfc/Manifest.h>
#include <zls/zfc/CMutex.hpp>
// Begin namespace 'zfc::'
ZLS_BEGIN_NAMESPACE(zfc)
/**
* This is a base class to be used in conjunction with the CSmartPointerT class.
*
* @todo 为什么不直接在CReferenceCounter中加入增加、减少"计数器"的method或operator呢?
* 这是因为CReferenceCounter将作为所有需要"引用计数"的class的一个基类,如果将这些增加、
* 减少"计数器"的method或operator放置在public区,则有可能在派生类中会无意地override了
* 它们。为了效率的原因,这些代码我使用inline的方式。
*/
class CReferenceCounter {
private:
/**
* 隐藏掉copy constructor和assignment operator,因为我不允许这种操作.
*
* @note 如果派生类需要copy constructor和assignment operator,在用户自己没有
* 编写的情况下compiler会替用户编写一个,但是它甚至连基类CReferenceCounter
* 以及CReferenceCounter::_ciReferMutex都想copy,这时编译时肯定报错,这正是
* 我所希望的,因为采用"引用计数"技术后的copy语义是不应该能copy"引用计数"的,
* 而应该只copy派生类的"内容",因此用户必须自己定义一个copy constructor和
* assignment operator.
*/
CReferenceCounter(const CReferenceCounter &);
CReferenceCounter & operator=(const CReferenceCounter &);
long _lReferenceCount;
#if defined(ENABLE_THREADS) && !defined(WIN32)
CMutex _ciReferMutex;
#endif
public:
/**
* 自杀method.
*
* @note 2001/5/9:在做ZLang时发现,如果类采用"public virtual"继承时,则
* CSmartPointerT<虚基类>的delete将使free()函数抱怨:
* <pre>
* zlang in free(): warning: modified (chunk-) pointer.
* </pre>
* 因此我引进这个自杀method,让采用虚继承的派生类可以通过重实现它来正确
* 地调用delete。如果不是采用虚继承的派生类则不用再重实现它.
*/
virtual void SelfDestruct()
{ delete this; }
CReferenceCounter()
: _lReferenceCount(0)
{ }
virtual ~CReferenceCounter()
{ }
template <class T, bool bNeedThreadMutex> friend class CSmartPointerT;
};
#ifdef ENABLE_THREADS
#define __LOCK_REFERENCE_COUNTER \
if (bNeedThreadMutex) \
{ _pciTarget->_ciReferMutex.Lock(); }
#define __UNLOCK_REFERENCE_COUNTER \
if (bNeedThreadMutex) \
{ _pciTarget->_ciReferMutex.Unlock(); }
#define __WIN32_INCREMENT_REFERENCE_COUNTER \
InterlockedIncrement(&_pciTarget->_lReferenceCount)
#define __WIN32_DECREMENT_REFERENCE_COUNTER \
InterlockedDecrement(&_pciTarget->_lReferenceCount)
#else
#define __LOCK_REFERENCE_COUNTER
#define __UNLOCK_REFERENCE_COUNTER
#define __WIN32_INCREMENT_REFERENCE_COUNTER \
++_pciTarget->_lReferenceCount
#define __WIN32_DECREMENT_REFERENCE_COUNTER \
--_pciTarget->_lReferenceCount
#endif
/**
* This class is a handle to a reference counted object. This ensures
* that the object is deleted when it is no longer referenced.
*/
template <class T, bool bNeedThreadMutex = true>
class CSmartPointerT {
private:
T * _pciTarget; // Referenced object
public:
CSmartPointerT(T * pciTarget = 0);
CSmartPointerT(const CSmartPointerT<T, bNeedThreadMutex> & rautoOther);
/**
* Destructor.
* Deletes object when reference count drops to zero.
*/
~CSmartPointerT();
/**
* Assignment operator.
*/
CSmartPointerT<T, bNeedThreadMutex> & operator=(T * pciOther);
CSmartPointerT<T, bNeedThreadMutex> & operator=(const CSmartPointerT<T, bNeedThreadMutex> & rautoOther);
/**
* Equality and inequality.
*/
bool operator==(const CSmartPointerT<T, bNeedThreadMutex> & rautoOther) const
{
return (_pciTarget == rautoOther._pciTarget);
}
bool operator!=(const CSmartPointerT<T, bNeedThreadMutex> & rautoOther) const
{
return (_pciTarget != rautoOther._pciTarget);
}
/**
* Logical not operator and bool operator.
* For testing whether are we referring to a valid pointer ?
*/
bool operator!() const
{
return (_pciTarget == 0);
}
operator bool() const
{
return (_pciTarget != 0);
}
/**
* Make access to the pointer intuitive.
*/
T * operator->()
{
return (_pciTarget);
}
const T * operator->() const
{
return (_pciTarget);
}
T * get()
{
return (_pciTarget);
}
const T * get() const
{
return (_pciTarget);
}
T & operator*()
{
return (*_pciTarget);
}
const T & operator*() const
{
return (*_pciTarget);
}
/**
* De-reference.
*/
void DeReference();
};
template <class T, bool bNeedThreadMutex>
CSmartPointerT<T, bNeedThreadMutex>::CSmartPointerT(T * pciTarget)
: _pciTarget(pciTarget)
{
if (_pciTarget != 0)
{
//
// Boost reference count.
//
#ifdef WIN32
__WIN32_INCREMENT_REFERENCE_COUNTER;
#else
__LOCK_REFERENCE_COUNTER;
++_pciTarget->_lReferenceCount;
__UNLOCK_REFERENCE_COUNTER;
#endif
}
}
template <class T, bool bNeedThreadMutex>
CSmartPointerT<T, bNeedThreadMutex>::~CSmartPointerT()
{
#ifdef WIN32
if (_pciTarget != 0 && __WIN32_DECREMENT_REFERENCE_COUNTER == 0)
{
//::delete _pciTarget;
// 2001/5/9: 改为调用virtual SelfDestruct()
_pciTarget->SelfDestruct();
}
#else
if (_pciTarget != 0)
{
bool bDeleteIt = false;
__LOCK_REFERENCE_COUNTER;
if (--_pciTarget->_lReferenceCount == 0)
bDeleteIt = true;
/*
* 为什么要引进bDeleteIt呢,这是怕如果Leave Mutex后再判断_pciTarget->_lReferenceCount
* 为0否可能会存在着边界效应。其实如果CReferenceCounter有自己的DecreaseCounter()方法的
* 话,则DecreaseCounter()方法可能要如下:
*
* int CReferenceCounter::DecreaseCounter()
* {
* _ciReferMutex.Lock();
* int n = --_pciTarget->_lReferenceCount; // 一定要有临时变量,否则还是会有边界效应
* _ciReferMutex.Unlock();
* return n;
* }
*/
__UNLOCK_REFERENCE_COUNTER;
if (bDeleteIt)
{
//::delete _pciTarget;
// 2001/5/9: 改为调用virtual SelfDestruct()
_pciTarget->SelfDestruct();
}
}
#endif
}
template <class T, bool bNeedThreadMutex>
CSmartPointerT<T, bNeedThreadMutex>::CSmartPointerT(const CSmartPointerT<T, bNeedThreadMutex> & rautoOther)
: _pciTarget(rautoOther._pciTarget)
{
if (_pciTarget != 0)
{
//
// Boost reference count.
//
#ifdef WIN32
__WIN32_INCREMENT_REFERENCE_COUNTER;
#else
__LOCK_REFERENCE_COUNTER;
++_pciTarget->_lReferenceCount;
__UNLOCK_REFERENCE_COUNTER;
#endif
}
}
template <class T, bool bNeedThreadMutex>
CSmartPointerT<T, bNeedThreadMutex> &
CSmartPointerT<T, bNeedThreadMutex>::operator=(T * pciOther)
{
if (_pciTarget == pciOther)
return (*this);
#ifdef WIN32
if (_pciTarget != 0 && __WIN32_DECREMENT_REFERENCE_COUNTER == 0)
{
//::delete _pciTarget;
// 2001/5/9: 改为调用virtual SelfDestruct()
_pciTarget->SelfDestruct();
}
// Copy pciOther.
_pciTarget = pciOther; /* 这里在thread环境中还是有问题,怎么改进呢? */
// Boost reference count.
if (_pciTarget != 0) /* 这里在thread环境中还是有问题,怎么改进呢? */
__WIN32_INCREMENT_REFERENCE_COUNTER;
#else
if (_pciTarget != 0)
{
//
// Time to clean out object?
//
bool bDeleteIt = false;
__LOCK_REFERENCE_COUNTER;
if (--_pciTarget->_lReferenceCount == 0)
bDeleteIt = true;
__UNLOCK_REFERENCE_COUNTER;
if (bDeleteIt)
{
//::delete _pciTarget;
// 2001/5/9: 改为调用virtual SelfDestruct()
_pciTarget->SelfDestruct();
}
}
// Copy pciOther.
_pciTarget = pciOther;
// Boost reference count.
if (_pciTarget != 0)
{
__LOCK_REFERENCE_COUNTER;
++_pciTarget->_lReferenceCount;
__UNLOCK_REFERENCE_COUNTER;
}
#endif
return (*this);
}
template <class T, bool bNeedThreadMutex>
CSmartPointerT<T, bNeedThreadMutex> &
CSmartPointerT<T, bNeedThreadMutex>::operator=(const CSmartPointerT<T, bNeedThreadMutex> & rautoOther)
{
if (_pciTarget == rautoOther._pciTarget)
return (*this);
#ifdef WIN32
if (_pciTarget != 0 && __WIN32_DECREMENT_REFERENCE_COUNTER == 0)
{
//::delete _pciTarget;
// 2001/5/9: 改为调用virtual SelfDestruct()
_pciTarget->SelfDestruct();
}
// Copy rautoOther's referenced-pointer.
_pciTarget = rautoOther._pciTarget;
// Boost reference count.
if (_pciTarget != 0)
__WIN32_INCREMENT_REFERENCE_COUNTER;
#else
if (_pciTarget != 0)
{
//
// Time to clean out object?
//
bool bDeleteIt = false;
__LOCK_REFERENCE_COUNTER;
if (--_pciTarget->_lReferenceCount == 0)
bDeleteIt = true;
__UNLOCK_REFERENCE_COUNTER;
if (bDeleteIt)
{
//::delete _pciTarget;
// 2001/5/9: 改为调用virtual SelfDestruct()
_pciTarget->SelfDestruct();
}
}
// Copy rautoOther's referenced-pointer.
_pciTarget = rautoOther._pciTarget;
// Boost reference count.
if (_pciTarget != 0)
{
__LOCK_REFERENCE_COUNTER;
++_pciTarget->_lReferenceCount;
__UNLOCK_REFERENCE_COUNTER;
}
#endif
return (*this);
}
template <class T, bool bNeedThreadMutex>
void CSmartPointerT<T, bNeedThreadMutex>::DeReference()
{
#ifdef WIN32
if (_pciTarget != 0 && __WIN32_DECREMENT_REFERENCE_COUNTER == 0)
{
//::delete _pciTarget;
// 2001/5/9: 改为调用virtual SelfDestruct()
_pciTarget->SelfDestruct();
}
#else
if (_pciTarget != 0)
{
bool bDeleteIt = false;
__LOCK_REFERENCE_COUNTER;
if (--_pciTarget->_lReferenceCount == 0)
bDeleteIt = true;
__UNLOCK_REFERENCE_COUNTER;
if (bDeleteIt)
{
//::delete _pciTarget;
// 2001/5/9: 改为调用virtual SelfDestruct()
_pciTarget->SelfDestruct();
}
}
#endif
_pciTarget = 0;
}
ZLS_END_NAMESPACE
#endif
|
#include "../headers/operateuror.h"
const OperateurOR& OperateurOR::evaluate(Pile& pile) const
{
if (pile.taille() >= getArite()) {
try
{
dynamic_cast<Entier&>(pile.top());
}
catch(exception&)
{
throw ComputerException("Erreur : mauvais arguments");
}
Entier& N2 = dynamic_cast<Entier&>(pile.top());
pile.pop();
try
{
dynamic_cast<Entier&>(pile.top());
}
catch(exception&)
{
pile.push(N2);
throw ComputerException("Erreur : mauvais arguments");
}
Entier& N1 = dynamic_cast<Entier&>(pile.top());
pile.pop();
QString res;
if(static_cast<int>(N1.getValue()) != 0 || static_cast<int>(N2.getValue()) != 0)
{
res = "1";
}
else
{
res = "0";
}
Expression& e = ExpressionManager::getInstance().addExpression(res);
//ajout sur la pile
pile.push(e);
QString message;
message = N1.toString() + " " + this->getSymbole() + " " + N2.toString() + " = " + pile.top().toString();
pile.setMessage(message);
//sauvegarde des arguments
QVector<QString> args;
args.push_back(N1.toString());
args.push_back(N2.toString());
pile.setLastArgs(args);
}
else
{
throw ComputerException("Erreur : pas assez d'arguments");
}
return *this;
}
|
#include<bits/stdc++.h>
using namespace std;
struct Queue
{
int size1;
int front1;
int rear1;
int *Q;
};
void create(struct Queue *q,int size)
{
q->size1=size;
q->front1=q->rear1=0;
q->Q=(int*)malloc(q->size1*sizeof(int));
}
void enqueue(struct Queue *q,int x)
{
if((q->rear1+1)%q->size1==q->front1)
{
cout<<"Queue is Full"<<endl;
}
else
{
q->rear1=(q->rear1+1)%q->size1;
q->Q[q->rear1]=x;
}
}
int dequeue(struct Queue *q)
{
int x=-1;
if(q->front1==q->rear1)
cout<<"Queue is empty"<<endl;
else
{
q->front1=(q->front1+1)%q->size1;
x=q->Q[q->front1];
}
return -1;
}
void Display(struct Queue q)
{
int i=q.Q[q.front1+1];
do
{
cout<<q.Q[i]<<" ";
i=(i+1)%q.size1;
}while(i!=(q.rear1+1));
}
int main()
{
struct Queue q;
create(&q,6);
enqueue(&q,1);
enqueue(&q,2);
enqueue(&q,3);
enqueue(&q,4);
Display(q);
enqueue(&q,16);
cout<<endl;
Display(q);
}
|
/*************************************************************************
> File Name: heap_sort.cpp
> Author:
> Mail:
> Created Time: Sat 11 Jul 2020 08:57:29 AM CST
************************************************************************/
#include<iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <vector>
using namespace std;
#define swap(a, b) { \
__typeof(a) __temp = a; \
a = b, b = __temp; \
}
void up_maintain(int *arr, int ind) {
while (ind > 1 && arr[ind] > arr[ind >> 1]) {
swap(arr[ind], arr[ind >> 1]);
ind >>= 1;
}
return ;
}
void down_maintain(int *arr, int ind, int n) {
int temp;
while (ind * 2 <= n) {
temp = ind;
if (arr[ind << 1] > arr[temp]) temp = ind << 1;
if ((ind << 1 | 1) <= n && arr[ind << 1 | 1] > arr[temp]) temp = (ind << 1 | 1);
if (temp == ind) break;
swap(arr[ind], arr[temp]);
ind = temp;
}
return ;
}
void heap_sort(int *arr, int l, int r) {
int *brr = arr + l - 1, n = r - l + 1;
for (int i = 2; i <= n; i++) {
up_maintain(brr, i);
}
for (int i = n; i > 1; i--) {
swap(brr[1], brr[i]);
down_maintain(brr, 1, i - 1);
}
return ;
}
#undef swap
|
//
// Created by 98595 on 2020/4/18.
// 蓝桥杯校赛模拟
//问题描述
// 给定三个整数 a, b, c,如果一个整数既不是 a 的整数倍也不是 b 的整数倍还不是 c 的整数倍,则这个数称为反倍数。
// 请问在 1 至 n 中有多少个反倍数。
//输入格式
// 输入的第一行包含一个整数 n。
// 第二行包含三个整数 a, b, c,相邻两个数之间用一个空格分隔。
//输出格式
// 输出一行包含一个整数,表示答案。
//样例输入
//30
//2 3 6
//样例输出
//10
//样例说明
// 以下这些数满足要求:1, 5, 7, 11, 13, 17, 19, 23, 25, 29。
//评测用例规模与约定
// 对于 40% 的评测用例,1 <= n <= 10000。
// 对于 80% 的评测用例,1 <= n <= 100000。
// 对于所有评测用例,1 <= n <= 1000000,1 <= a <= n,1 <= b <= n,1 <= c <= n。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define cin ios::sync_with_stdio(false); cin
typedef unsigned long long ll;
ll n;
ll a, b, c;
int main() {
cin >> n;
cin >> a >> b >> c;
ll ans = 0;
for (ll i = 1; i <= n; ++ i) {
if (i % a != 0 && i % b != 0 && i % c != 0) {
++ ans;
}
}
cout << ans << '\n';
return 0;
}
|
#ifndef QUEUE_LIST
#define QUEUE_LIST
#include "../list/list.h"
template <typename T> class queue : public List<T> {
public:
void enqueue ( const T &e ) { insertAsLast ( e );}
T dequeue () { return remove ( this->first() );}
T &front () { return this->first()->data; }
};
#endif /* ifndef QUEUE_LIST */
|
/***************************************************************************
Copyright (c) 2020 Philip Fortier
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.
***************************************************************************/
#include "stdafx.h"
#include "DecompileScript.h"
#include "CompiledScript.h"
#include "DecompilerCore.h"
#include "ScriptOMAll.h"
#include "AutoDetectVariableNames.h"
#include "SCO.h"
#include "GameFolderHelper.h"
#include "DecompilerResults.h"
#include "format.h"
#include "DecompilerConfig.h"
#include "Vocab000.h"
#include "AppState.h"
using namespace sci;
using namespace std;
const char InvalidLookupError[] = "LOOKUP_ERROR";
void DecompileObject(const CompiledObject &object,
sci::Script &script,
DecompileLookups &lookups,
const std::vector<BYTE> &scriptResource,
const std::vector<CodeSection> &codeSections,
const std::set<uint16_t> &codePointersTO)
{
lookups.EndowWithProperties(&object);
uint16_t superClassScriptNum;
if (lookups.GetSpeciesScriptNumber(object.GetSuperClass(), superClassScriptNum))
{
lookups.TrackUsingScript(superClassScriptNum);
}
unique_ptr<ClassDefinition> pClass = std::make_unique<ClassDefinition>();
pClass->SetScript(&script);
pClass->SetInstance(object.IsInstance());
pClass->SetName(object.GetName());
pClass->SetSuperClass(lookups.LookupClassName(object.GetSuperClass()));
pClass->SetPublic(object.IsPublic);
vector<uint16_t> propertySelectorList;
vector<CompiledVarValue> speciesPropertyValueList;
bool fSuccess = lookups.LookupSpeciesPropertyListAndValues(object.GetSpecies(), propertySelectorList, speciesPropertyValueList);
if (!fSuccess && !object.IsInstance())
{
// We're a class - our species is ourself
propertySelectorList = object.GetProperties();
speciesPropertyValueList = object.GetPropertyValues();
fSuccess = true;
}
if (fSuccess)
{
assert(propertySelectorList.size() == speciesPropertyValueList.size());
size_t size1 = propertySelectorList.size();
size_t size2 = object.GetPropertyValues().size();
size_t numberOfProps = min(size1, size2);
if (size1 != size2)
{
// TODO: Output a warning... mismatched prop sizes.
}
for (size_t i = object.GetNumberOfDefaultSelectors(propertySelectorList, lookups.GetNameSelector()); i < numberOfProps; i++)
{
const CompiledVarValue &propValue = object.GetPropertyValues()[i];
// If this is an instance, look up the species values, and only
// include those that are different.
if (!object.IsInstance() || (propValue.value != speciesPropertyValueList[i].value))
{
unique_ptr<ClassProperty> prop = make_unique<ClassProperty>();
prop->SetName(lookups.LookupSelectorName(propertySelectorList[i]));
PropertyValue value;
ICompiledScriptSpecificLookups::ObjectType type;
std::string saidOrString;
if (!propValue.isObjectOrString || !lookups.LookupScriptThing(propValue.value, type, saidOrString))
{
assert(!propValue.isObjectOrString && "We should have resolved some token for this property value");
// Just give it a number
uint16_t number = propValue.value;
value.SetValue(number);
if (lookups.GetDecompilerConfig()->IsBitfieldProperty(prop->GetName()))
{
value._fHex = true;
}
else if (number >= 32768)
{
// A good bet that it's negative
value.Negate();
}
}
else
{
// REVIEW: we could provide a hit here when we shouldn't... oh well.
// Use ValueType::Token, since the ' or " is already provided in the string.
value.SetValue(saidOrString, _ScriptObjectTypeToPropertyValueType(type));
}
prop->SetValue(value);
pClass->AddProperty(move(prop));
}
}
} // else make ERROR
// Methods
const vector<uint16_t> &functionSelectors = object.GetMethods();
const vector<uint16_t> &functionOffsetsTO = object.GetMethodCodePointersTO();
assert(functionSelectors.size() == functionOffsetsTO.size());
for (size_t i = 0; i < functionSelectors.size() && !lookups.DecompileResults().IsAborted(); i++)
{
// Now the code.
set<uint16_t>::const_iterator functionIndex = find(codePointersTO.begin(), codePointersTO.end(), functionOffsetsTO[i]);
if (functionIndex != codePointersTO.end())
{
CodeSection section;
if (FindStartEndCode(functionIndex, codePointersTO, codeSections, section))
{
const BYTE *pStartCode = &scriptResource[section.begin];
const BYTE *pEndCode = &scriptResource[section.end];
const BYTE *pEndScript = &scriptResource[0] + scriptResource.size();
std::unique_ptr<MethodDefinition> pMethod = std::make_unique<MethodDefinition>();
pMethod->SetOwnerClass(pClass.get());
pMethod->SetScript(&script);
pMethod->SetName(lookups.LookupSelectorName(functionSelectors[i]));
DecompileRaw(*pMethod, lookups, pStartCode, pEndCode, pEndScript, functionOffsetsTO[i]);
pClass->AddMethod(std::move(pMethod));
}
}
}
script.AddClass(std::move(pClass));
lookups.EndowWithProperties(nullptr);
}
const uint16_t BogusSQ5Export = 0x3af;
void DecompileFunction(const CompiledScript &compiledScript, ProcedureDefinition &func, DecompileLookups &lookups, uint16_t wCodeOffsetTO, const set<uint16_t> &sortedCodePointersTO)
{
lookups.EndowWithProperties(lookups.GetPossiblePropertiesForProc(wCodeOffsetTO));
set<uint16_t>::const_iterator codeStartIt = sortedCodePointersTO.find(wCodeOffsetTO);
assert(codeStartIt != sortedCodePointersTO.end());
bool isValidFunctionPointer = (*codeStartIt < compiledScript.GetRawBytes().size()) && (*codeStartIt != BogusSQ5Export);
CodeSection section;
if (isValidFunctionPointer && FindStartEndCode(codeStartIt, sortedCodePointersTO, compiledScript._codeSections, section))
{
const BYTE *pBegin = &compiledScript.GetRawBytes()[section.begin];
const BYTE *pEnd = &compiledScript.GetRawBytes()[section.end];
const BYTE *pEndScript = compiledScript.GetEndOfRawBytes();
DecompileRaw(func, lookups, pBegin, pEnd, pEndScript, wCodeOffsetTO);
if (lookups.WasPropertyRequested() && lookups.GetPossiblePropertiesForProc(wCodeOffsetTO))
{
const CompiledObject *object = static_cast<const CompiledObject *>(lookups.GetPossiblePropertiesForProc(wCodeOffsetTO));
// This procedure is "of" this object
func.SetClass(object->GetName());
}
}
else
{
// Make a function stub
func.AddSignature(make_unique<FunctionSignature>());
lookups.DecompileResults().AddResult(DecompilerResultType::Warning, fmt::format("Invalid function offset: {0:04x}", *codeStartIt));
}
lookups.EndowWithProperties(nullptr);
}
void InsertHeaders(Script &script)
{
// For decompiling, we don't need game.sh yet (since we're not creating it is still TBD)
script.AddInclude("sci.sh");
}
void DetermineAndInsertUsings(const GameFolderHelper &helper, Script &script, DecompileLookups &lookups)
{
for (uint16_t usingScript : lookups.GetValidUsings())
{
script.AddUse(helper.FigureOutName(ResourceType::Script, usingScript, NoBase36));
}
}
// e.g. of the form "proc255_3", or "localproc_0b2a", where localproc_0b2a is actually an exported procedure.
// If true, returns the script number and export index so we can look up the real name.
bool _IsUndeterminedPublicProc(const CompiledScript &compiledScript, const std::string &procName, uint16_t &script, uint16_t &index)
{
script = 0;
index = 0;
if (0 == procName.compare(0, 4, "proc"))
{
string rest = procName.substr(4, string::npos);
// This needs to be of the form [number]_[number]
size_t position = 0;
int scriptNumber = stoi(rest, &position);
if ((position > 0) && (position < rest.size()))
{
if (rest[position] == '_')
{
rest = rest.substr(position + 1, string::npos);
int indexNumber = stoi(rest, &position);
script = (uint16_t)scriptNumber;
index = (uint16_t)indexNumber;
return true;
}
}
}
else if (0 == procName.compare(0, 10, "localproc_"))
{
string rest = procName.substr(10, string::npos);
size_t position = 0;
int offset = stoi(rest, &position, 16);
if (position == rest.size()) // Consumed whole thing
{
// Find the offset of this proc. If it's also a public export, count it as so.
int indexNumber;
if (compiledScript.IsExportAProcedure((uint16_t)offset, &indexNumber))
{
script = compiledScript.GetScriptNumber();
index = (uint16_t)indexNumber;
return true;
}
}
}
return false;
}
class ResolveProcedureCalls : public IExploreNode
{
public:
ResolveProcedureCalls(const GameFolderHelper &helper, DecompileLookups &lookups, const CompiledScript &compiledScript, unordered_map<int, unique_ptr<CSCOFile>> &scoMap) :
_scoMap(scoMap), _compiledScript(compiledScript), _helper(helper), _lookups(lookups) {}
void ExploreNode(SyntaxNode &node, ExploreNodeState state) override
{
if (state == ExploreNodeState::Pre)
{
ProcedureCall *procCall = SafeSyntaxNode<ProcedureCall>(&node);
if (procCall)
{
uint16_t scriptNumber, index;
if (_IsUndeterminedPublicProc(_compiledScript, procCall->GetName(), scriptNumber, index))
{
CSCOFile *sco = _EnsureSCO(scriptNumber);
if (sco)
{
string newProcName = sco->GetExportName(index);
assert(!newProcName.empty());
if (!newProcName.empty())
{
procCall->SetName(newProcName);
}
}
else
{
// In the case when we don't have an .sco file yet (first compile), if this
// was actually a local call instruction (but is an exported public proc, as we now know),
// use the public proc name for it temporarily
if (procCall->GetName() != _GetPublicProcedureName(scriptNumber, index))
{
procCall->SetName(_GetPublicProcedureName(scriptNumber, index));
}
}
}
}
// We need to handle this for ASM too
Asm *asmStatement = SafeSyntaxNode<Asm>(&node);
if (asmStatement)
{
string instruction = asmStatement->GetName();
if (instruction == "call" || instruction == "callb" || instruction == "calle")
{
SyntaxNode *procNameNode = asmStatement->GetStatements()[0].get();
PropertyValue *value = SafeSyntaxNode<PropertyValue>(procNameNode);
uint16_t scriptNumber, index;
assert(value->GetType() == ValueType::Token);
if (_IsUndeterminedPublicProc(_compiledScript, value->GetStringValue(), scriptNumber, index))
{
CSCOFile *sco = _EnsureSCO(scriptNumber);
if (sco)
{
string newProcName = sco->GetExportName(index);
assert(!newProcName.empty());
if (!newProcName.empty())
{
value->SetValue(newProcName, ValueType::Token);
}
}
}
}
}
}
}
private:
CSCOFile *_EnsureSCO(uint16_t script)
{
if (_scoMap.find(script) == _scoMap.end())
{
_scoMap[script] = move(GetExistingSCOFromScriptNumber(_helper, script, _lookups.GetSelectorTable()));
}
return _scoMap.at(script).get();
}
DecompileLookups &_lookups;
const GameFolderHelper &_helper;
unordered_map<int, unique_ptr<CSCOFile>> &_scoMap;
const CompiledScript &_compiledScript;
};
// This pulls in the required .sco files to find the public procedure names
void ResolvePublicProcedureCalls(DecompileLookups &lookups, const GameFolderHelper &helper, Script &script, const CompiledScript &compiledScript)
{
unordered_map<int, unique_ptr<CSCOFile>> scoMap;
scoMap[script.GetScriptNumber()] = move(GetExistingSCOFromScriptNumber(helper, script.GetScriptNumber(), lookups.GetSelectorTable()));
// First let's resolve the exports
CSCOFile *thisSCO = scoMap.at(script.GetScriptNumber()).get();
if (thisSCO)
{
for (auto &proc : script.GetProceduresNC())
{
uint16_t scriptNumber, index;
if (proc->IsPublic() && _IsUndeterminedPublicProc(compiledScript, proc->GetName(), scriptNumber, index))
{
assert(scriptNumber == script.GetScriptNumber());
string newProcName = thisSCO->GetExportName(index);
assert(!newProcName.empty());
if (newProcName.empty())
{
proc->SetName(newProcName);
}
}
}
}
// Now the actual calls, which could be to any script
ResolveProcedureCalls resolveProcCalls(helper, lookups, compiledScript, scoMap);
script.Traverse(resolveProcCalls);
}
class ResolveVariableValues : public IExploreNode
{
public:
ResolveVariableValues(const IDecompilerConfig &config) : _config(config) {}
void ExploreNode(SyntaxNode &node, ExploreNodeState state) override
{
if (state == ExploreNodeState::Pre)
{
SwitchStatement *switchStatement = SafeSyntaxNode<SwitchStatement>(&node);
if (switchStatement)
{
_config.ResolveSwitchStatementValues(*switchStatement);
}
BinaryOp *binaryOp = SafeSyntaxNode<BinaryOp>(&node);
if (binaryOp)
{
_config.ResolveBinaryOpValues(*binaryOp);
}
}
}
private:
const IDecompilerConfig &_config;
};
Script *Decompile(const GameFolderHelper &helper, const CompiledScript &compiledScript, DecompileLookups &lookups, const Vocab000 *pWords)
{
unique_ptr<Script> pScript = std::make_unique<Script>();
pScript->SyntaxVersion = 2;
ScriptId scriptId;
scriptId.SetLanguage(helper.Language);
scriptId.SetResourceNumber(compiledScript.GetScriptNumber());
pScript->SetScriptId(scriptId);
compiledScript.PopulateSaidStrings(pWords);
// Synonyms
if (compiledScript._synonyms.size() > 0)
{
for (const auto &syn : compiledScript._synonyms)
{
unique_ptr<Synonym> pSynonym = std::make_unique<Synonym>();
pSynonym->MainWord = _FindPreferredWord(pWords->Lookup(syn.first));
for (auto &theSyn : syn.second)
{
pSynonym->Synonyms.push_back(_FindPreferredWord(pWords->Lookup(theSyn)));
}
pScript->AddSynonym(std::move(pSynonym));
}
}
// Now its time for code.
// Make an index of code pointers by looking at the object methods
set<uint16_t> codePointersTO;
for (auto &object : compiledScript._objects)
{
const vector<uint16_t> &methodPointersTO = object->GetMethodCodePointersTO();
codePointersTO.insert(methodPointersTO.begin(), methodPointersTO.end());
}
// and the exported procedures
for (size_t i = 0; i < compiledScript._exportsTO.size(); i++)
{
uint16_t wCodeOffset = compiledScript._exportsTO[i];
// Export offsets could point to objects too - we're only interested in code pointers, so
// check that it's not an object
if (compiledScript.IsExportAProcedure(wCodeOffset))
{
codePointersTO.insert(wCodeOffset);
}
}
// and finally, the most difficult of all, we'll need to scan though for any call calls...
// those would be our internal procs
set<uint16_t> internalProcOffsetsTO = compiledScript.FindInternalCallsTO();
// Before adding these though, remove any exports from the internalProcOffsets.
for (const auto &exporty : compiledScript._exportsTO)
{
if (compiledScript.IsExportAProcedure(exporty)) // Exported objects can have the same address as a proc, we need to make sure we don't omit a proc because of that.
{
set<uint16_t>::iterator internalsIndex = find(internalProcOffsetsTO.begin(), internalProcOffsetsTO.end(), exporty);
if (internalsIndex != internalProcOffsetsTO.end())
{
// Remove this guy.
internalProcOffsetsTO.erase(internalsIndex);
}
}
}
// Now add the internal guys to the full list
codePointersTO.insert(internalProcOffsetsTO.begin(), internalProcOffsetsTO.end());
// Now we know the length of each code segment (assuming none overlap)
// Spit out code segments:
// First, the objects (instances, classes)
for (auto &object : compiledScript._objects)
{
#ifdef FORCE_FILE993TOFILE
//Force script 993 class 0 to be "File"
if (compiledScript.GetScriptNumber() == 993)
{
string objName = (*object).GetName();
if (objName == "Class_993_0" || objName == "gamefile.sh")
(*object).AdjustName("File");
}
#endif
DecompileObject(*object, *pScript, lookups, compiledScript.GetRawBytes(), compiledScript._codeSections, codePointersTO);
if (lookups.DecompileResults().IsAborted())
{
break;
}
}
map<int, string> exportSlotToName;
// Now the exported procedures.
for (size_t i = 0; i < compiledScript._exportsTO.size() && !lookups.DecompileResults().IsAborted(); i++)
{
// _exportsTO, in addition to containing code pointers for public procedures, also
// contains the Rm/Room class. Filter these out by ignoring code pointers which point outside
// the codesegment.
uint16_t exportPointer = compiledScript._exportsTO[i];
if (compiledScript.IsExportAProcedure(exportPointer))
{
std::unique_ptr<ProcedureDefinition> pProc = std::make_unique<ProcedureDefinition>();
pProc->SetScript(pScript.get());
pProc->SetName(lookups.ReverseLookupPublicExportName(compiledScript.GetScriptNumber(), (uint16_t)i));
exportSlotToName[i] = pProc->GetName();
pProc->SetPublic(true);
DecompileFunction(compiledScript, *pProc, lookups, exportPointer, codePointersTO);
pScript->AddProcedure(std::move(pProc));
}
else if ((exportPointer == 0) || (exportPointer == KQ5CD_BadExport))
{
// Valid.
}
else
{
// It should be an object
CompiledObject *object = compiledScript.GetObjectForExport(exportPointer);
if (object)
{
exportSlotToName[i] = object->GetName();
}
assert(object);
}
}
// Now the internal procedures (REVIEW - possibly overlap with exported ones)
for (uint16_t offset : internalProcOffsetsTO)
{
if (lookups.DecompileResults().IsAborted())
{
break;
}
std::unique_ptr<ProcedureDefinition> pProc = make_unique<ProcedureDefinition>();
pProc->SetScript(pScript.get());
pProc->SetName(_GetProcNameFromScriptOffset(offset));
pProc->SetPublic(false);
DecompileFunction(compiledScript, *pProc, lookups, offset, codePointersTO);
pScript->AddProcedure(std::move(pProc));
}
if (!lookups.DecompileResults().IsAborted())
{
AddLocalVariablesToScript(*pScript, compiledScript, lookups, compiledScript._localVars);
// Load this script's SCO, and main's SCO (assuming this isn't main)
unique_ptr<CSCOFile> mainSCO;
if (compiledScript.GetScriptNumber() != 0)
{
mainSCO = GetExistingSCOFromScriptNumber(helper, 0, lookups.GetSelectorTable());
}
unique_ptr<CSCOFile> oldScriptSCO = GetExistingSCOFromScriptNumber(helper, compiledScript.GetScriptNumber(), lookups.GetSelectorTable());
vector<pair<string, string>> mainDirtyRenames;
AutoDetectVariableNames(*pScript, lookups.GetDecompilerConfig(), mainSCO.get(), oldScriptSCO.get(), mainDirtyRenames);
ResolvePublicProcedureCalls(lookups, helper, *pScript, compiledScript);
MassageProcedureCalls(lookups, *pScript);
if (lookups.GetDecompilerConfig())
{
ResolveVariableValues resolveVariableValues(*lookups.GetDecompilerConfig());
pScript->Traverse(resolveVariableValues);
}
InsertHeaders(*pScript);
DetermineAndInsertUsings(helper, *pScript, lookups);
for (auto &pair : exportSlotToName)
{
unique_ptr<ExportEntry> entry = make_unique<ExportEntry>(pair.first, pair.second);
pScript->GetExports().push_back(move(entry));
}
// Decompiling always generates an SCO. Any pertinent info from the old SCO should be transfered
// to the new one based extracting info from the script.
std::unique_ptr<CSCOFile> scoFile = SCOFromScriptAndCompiledScript(*pScript, compiledScript);
SaveSCOFile(helper, *scoFile);
// We may have added some global info to main's SCO. Save that now.
if (!mainDirtyRenames.empty())
{
lookups.DecompileResults().AddResult(DecompilerResultType::Important, "Updating global variables in script 0");
lookups.DecompileResults().SetGlobalVarsUpdated(mainDirtyRenames);
SaveSCOFile(helper, *mainSCO);
}
}
return pScript.release();
}
|
/*
Copyright (C) 2011 Tal Pupko TalP@tauex.tau.ac.il.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gainLossModel.h"
/********************************************************************************************
gainLossModel
Note: All gainLossOptions parameter are sent
to the c'tor as a preperation for the model to be part of the Lib.
*********************************************************************************************/
gainLossModel::gainLossModel(const MDOUBLE m1, const Vdouble freq, bool isRootFreqEQstationary, bool isReversible, bool isHGT_normal_Pij, bool isHGT_with_Q):
_gain(m1),_freq(freq),_isRootFreqEQstationary(isRootFreqEQstationary),_isReversible(isReversible),_isHGT_normal_Pij(isHGT_normal_Pij),_isHGT_with_Q(isHGT_with_Q),_q2pt(NULL){
if (freq.size() != alphabetSize())
errorMsg::reportError("Error in gainLossModel, size of frequency vector must be as in alphabet");
for(int i=0; i<freq.size(); ++i)
if(freq[i]<0 || freq[i]>1)
errorMsg::reportError("Freq not within [0,1]\n");
if(!_isHGT_with_Q){_gain = 0;}
resizeMatrix(_Q,alphabetSize(),alphabetSize());
updateQ(_isReversible);
//setTheta(_freq[1]); // no Need
if(_isRootFreqEQstationary) {
setTheta(getMu1()/(getMu1()+getMu2()));
}
}
/********************************************************************************************
*********************************************************************************************/
gainLossModel& gainLossModel::operator=(const gainLossModel &other){
if (this != &other) { // Check for self-assignment
if (_q2pt) delete _q2pt;
if (other._q2pt != NULL)
_q2pt = (q2pt*)(other._q2pt->clone());
}
_isReversible = other.isReversible();
_isRootFreqEQstationary = other.isRootFreqEQstationary();
_isHGT_normal_Pij = other.isHGT_normal_Pij();
_isHGT_with_Q = other.isHGT_with_Q();
_gain = other._gain;
_freq = other._freq;
_Q = other._Q;
return *this;
}
/********************************************************************************************
*********************************************************************************************/
void gainLossModel::setMu1(const MDOUBLE val, bool isReversible) {
if(_isHGT_with_Q) {_gain = val;}
updateQ(isReversible);
if(_isRootFreqEQstationary) {
setTheta(getMu1()/(getMu1()+getMu2()));
}
//if(gainLossOptions::_isNormalizeQ) // part of update Q
// normalizeQ();
}
/********************************************************************************************
*********************************************************************************************/
MDOUBLE gainLossModel::setTheta(const MDOUBLE val) {
if(val<0 || val>1)
errorMsg::reportError("Freq not within [0,1]\n");
_freq[1]=val;
_freq[0]= 1-val;
MDOUBLE normFactor = updateQ(_isReversible);
return normFactor;
}
/********************************************************************************************
*********************************************************************************************/
MDOUBLE gainLossModel::updateQ(bool isReversible){
MDOUBLE normFactor=1;
_Q[0][1] = _gain;
_Q[0][0] = -_Q[0][1];
if (isReversible) {
_Q[1][0] = _Q[0][1] * _freq[0] / _freq[1]; // m1*pi0/pi1
_Q[1][1] = -_Q[1][0];
}
//else{
// _Q[1][0] = 1; //To be overwritten by gainLossModelNonReversible
// _Q[1][1] = -1; //To be overwritten by gainLossModelNonReversible
//}
if (gainLossOptions::_gainEQloss) {
_Q[1][0] = _gain;
_Q[1][1] = -_Q[1][0];
}
if (gainLossOptions::_gainLossRateAreFreq) {
_Q[1][0] = 1 - _gain;
_Q[1][1] = -_Q[1][0];
}
for (int i=0; i<_Q.size();i++) {
MDOUBLE sum = _Q[i][0]+_Q[i][1];
if ((abs(sum)>err_allow_for_pijt_function()))
errorMsg::reportError("Error in gainLossModel::updateQ, sum of row is not 0");
}
//if (isReversible){
// if (!_q2pt)
// _q2pt = new q2pt();
// _q2pt->fillFromRateMatrix(_freq,_Q);
//}
if(gainLossOptions::_isNormalizeQ && !gainLossOptions::_gainLossDist && (_Q[1][0]>0)) //
normFactor= normalizeQ();
return normFactor;
}
/********************************************************************************************
*********************************************************************************************/
const MDOUBLE gainLossModel::freq(const int i) const {
if (i >= _freq.size())
errorMsg::reportError("Error in gainLossModel::freq, i > size of frequency vector");
return _freq[i];
}
/********************************************************************************************
// normalize Q so that sum of changes = 1
*********************************************************************************************/
MDOUBLE gainLossModel::normalizeQ(){
MDOUBLE norm_factor=0.0;
for (int i=0;i<_Q.size();i++)
norm_factor+=(_freq[i]*_Q[i][i]);
MDOUBLE fac = -1.0/norm_factor;
_Q = multiplyMatrixByScalar(_Q,fac);
return fac;
}
/********************************************************************************************
*********************************************************************************************/
void gainLossModel::norm(const MDOUBLE scale)
{
for (int i=0; i < _Q.size(); ++i) {
for (int j=0; j < _Q.size(); ++j) {
_Q[i][j] *= scale;
}
}
}
/********************************************************************************************
*********************************************************************************************/
MDOUBLE gainLossModel::sumPijQij(){
MDOUBLE sum=0.0;
for (int i=0; i < _Q.size(); ++i) {
sum -= (_Q[i][i])*_freq[i];
}
return sum;
}
/********************************************************************************************
Pij_t - Based on Analytic solution
*********************************************************************************************/
const MDOUBLE gainLossModel::Pij_t(const int i,const int j, const MDOUBLE d) const {
MDOUBLE gain = getMu1();
MDOUBLE loss = getMu2();
MDOUBLE eigenvalue = -(gain + loss);
bool withHGT = isHGT_normal_Pij();
MDOUBLE noHGTfactor = 0.0001;
VVdouble Pt;
resizeMatrix(Pt,_Q.size(),_Q.size());
int caseNum = i + j*2;
switch (caseNum) {
case 0 : Pt[0][0] = loss/(-eigenvalue) + exp(eigenvalue*d)*(1 - loss/(-eigenvalue)); break;
case 1 : Pt[1][0] = loss/(-eigenvalue) - exp(eigenvalue*d)*(1 - gain/(-eigenvalue)); break;
case 2 : if(withHGT)
{ Pt[0][1] = gain/(-eigenvalue) - exp(eigenvalue*d)*(1 - loss/(-eigenvalue));}
else
{ Pt[0][1] = (gain/(-eigenvalue) - exp(eigenvalue*d)*(1 - loss/(-eigenvalue)))*noHGTfactor;} break;
case 3 : Pt[1][1] = gain/(-eigenvalue) + exp(eigenvalue*d)*(1 - gain/(-eigenvalue)); break;
}
MDOUBLE val = (Pt[i][j]);
if (!pijt_is_prob_value(val)){
string err = "Error in gainLossModelNonReversible::Pij_t, pijt <0 or >1. val=";
err+=double2string(val);
err+=" d=";
err+=double2string(d);
LOG(4,<<err<<endl); //errorMsg::reportError(err);
}
if(!(val>VERYSMALL))
val = VERYSMALL;
LOG(10,<<"for gain "<<gain<<" loss "<<loss<<" P"<<i<<j<<"("<<d<<") "<<val<<endl;)
return val;
}
/********************************************************************************************
dPij_t - Based on Analytic solution
*********************************************************************************************/
const MDOUBLE gainLossModel::dPij_dt(const int i,const int j, const MDOUBLE d) const {
MDOUBLE gain = getMu1();;
MDOUBLE loss = getMu2();;
MDOUBLE eigenvalue = -(gain + loss);
VVdouble Pt;
resizeMatrix(Pt,_Q.size(),_Q.size());
int caseNum = i + j*2;
switch (caseNum) {
case 0 : Pt[0][0] = exp(eigenvalue*d)*(eigenvalue + loss); break;
case 1 : Pt[1][0] = -(exp(eigenvalue*d)*(eigenvalue + gain)); break;
case 2 : Pt[0][1] = -(exp(eigenvalue*d)*(eigenvalue + loss)); break;
case 3 : Pt[1][1] = exp(eigenvalue*d)*(eigenvalue + gain); break;
}
MDOUBLE val = (Pt[i][j]);
//if (!pijt_is_prob_value(val)){
// string err = "Error in gainLossModelNonReversible::dPij_t_dt, pijt <0 or >1. val=";
// err+=double2string(val);
// err+=" d=";
// err+=double2string(d);
// LOG(6,<<err<<endl); //errorMsg::reportError(err);
//}
return val;
}
/********************************************************************************************
d2Pij_dt2 - Based on Analytic solution
*********************************************************************************************/
const MDOUBLE gainLossModel::d2Pij_dt2(const int i,const int j, const MDOUBLE d) const {
MDOUBLE gain = getMu1();;
MDOUBLE loss = getMu2();;
MDOUBLE eigenvalue = -(gain + loss);
VVdouble Pt;
resizeMatrix(Pt,_Q.size(),_Q.size());
int caseNum = i + j*2;
switch (caseNum) {
case 0 : Pt[0][0] = exp(eigenvalue*d)*(eigenvalue + loss)*eigenvalue; break;
case 1 : Pt[1][0] = -(exp(eigenvalue*d)*(eigenvalue + gain))*eigenvalue; break;
case 2 : Pt[0][1] = -(exp(eigenvalue*d)*(eigenvalue + loss))*eigenvalue; break;
case 3 : Pt[1][1] = exp(eigenvalue*d)*(eigenvalue + gain)*eigenvalue; break;
}
MDOUBLE val = (Pt[i][j]);
//if (!pijt_is_prob_value(val)){
// string err = "Error in gainLossModelNonReversible::d2Pij_t_dt2, pijt <0 or >1. val=";
// err+=double2string(val);
// LOG(6,<<err<<endl); //errorMsg::reportError(err);
//}
return val;
}
/********************************************************************************************
non reversible model
updateQ
*********************************************************************************************/
//void gainLossModelNonReversible::updateQ(){
// //gainLossModel::updateQ(false);
// _Q[1][1] = -_loss;
// _Q[1][0] = _loss;
// //normalizeQ();
//}
/********************************************************************************************
Pij_t - converging series
IMPORTANT NOTE: this function is VERY inefficient. It calculates all of Pt for every call of Pijt
this is unimportant for a small dataset (one position) but pre-processing should be done for larger datasets:
SOLUTION: save the computed Pijt matrix each time it is called. In every call of Pij_t, check if a saved value exists
*********************************************************************************************/
//const MDOUBLE gainLossModelNonReversible::Pij_t(const int i,const int j, const MDOUBLE d) const {
//
// VVdoubleRep QdblRep;
// resizeMatrix(QdblRep,_Q.size(),_Q.size());
// for (int row=0;row<_Q.size();row++){
// for (int col=0;col<_Q[row].size();col++)
// QdblRep[row][col]=convert(_Q[row][col]);
// }
// VVdoubleRep Qt = multiplyMatrixByScalar(QdblRep,d);
// VVdoubleRep unit;
// unitMatrix(unit,_Q.size());
// VVdoubleRep Pt = add(unit,Qt) ; // I + Qt
// VVdoubleRep Qt_power = Qt;
// doubleRep old_val = Pt[i][j];
// doubleRep diff(1.0);
// int n=2;
// while ((diff>err_allow_for_pijt_function()) || (!pijt_is_prob_value(convert(Pt[i][j])))){//(abs(old_val-new_val) > err_allow_for_pijt_function()){
// old_val = Pt[i][j];
// Qt_power = multiplyMatrixes(Qt_power,multiplyMatrixByScalar(Qt,1.0/n));
// Pt= add(Pt,Qt_power); // I + Qt + Qt^2/2! + .... + Qt^n/n!
//
// diff = Pt[i][j]-old_val; // difference is measured by diff between P[0][0] vals (a little primitive...)
// if (diff<0) diff=-diff;
// n++;
// if (n>200) {
// string err = "Error in gainLossModelNonReversible::Pij_t, too many (>n=200) iterations for t = " + double2string(d);
// cerr<<diff<<endl;
// errorMsg::reportError(err);
// }
// }
// MDOUBLE val = convert(Pt[i][j]);
// if (!pijt_is_prob_value(val))
// errorMsg::reportError("Error in gainLossModelNonReversible::Pij_t, pijt <0 or >1");
// LOG(10,<<"for gain "<<getMu1()<<" loss "<<getMu2()<<" P"<<i<<j<<"("<<d<<") "<<val<<endl;)
//
// return val;
//}
//
|
#ifndef QQUICKFOLDERLISTMODEL_H
#define QQUICKFOLDERLISTMODEL_H
class QQuickFolderListModel
{
public:
QQuickFolderListModel();
};
#endif // QQUICKFOLDERLISTMODEL_H
|
/* Copyright (C) 2015 Willi Menapace <willi.menapace@gmail.com>, Simone Lorengo - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Willi Menapace <willi.menapace@gmail.com>
*/
#include "GlobalDefines.h"
#ifdef OFFBOARD
#include <stdlib.h>
#include <iostream>
/**
* Effettua un test del funzionamento di XBeeATCommand
*
* @param parameters nome del file contenente i parametri di inizializzazione del test strutturato esattamente come il costruttore
* @param verification nome delfile contenente il pacchetto corretto che deve essere inviato al modulo XBee
*/
void xBeeATCommandTest(std::string parameters, std::string verification);
/**
* Effettua un test del funzionamento di XBeeTransmitRequest
*
* @param parameters nome del file contenente i parametri di inizializzazione del test strutturato esattamente come il costruttore
* @param verification nome delfile contenente il pacchetto corretto che deve essere inviato al modulo XBee
*/
void xBeeTransmitRequestTest(std::string parameters, std::string verification);
/**
* Effettua un test del funzionamento di XBeeRemoteATCommand
*
* @param parameters nome del file contenente i parametri di inizializzazione del test strutturato esattamente come il costruttore
* @param verification nome delfile contenente il pacchetto corretto che deve essere inviato al modulo XBee
*/
void xBeeRemoteATCommandTest(std::string parameters, std::string verification);
#endif //OFFBOARD
|
#ifndef __CAR_H__
#define __CAR_H__
#include "rectangle.h"
#include "obstacle.h"
#include "runrl.h"
#include "rl.h"
#include "GLFW/glfw3.h"
#include "glm.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xmath.hpp"
#include <cmath>
#include <unordered_map>
#include <string>
#include <algorithm>
const float car_vel_max = 200.0f;
const float car_omega_max = 3.14f;
class Car : public Drawable, public Movable, public RLRunnable
{
public:
Car(Shader &shader, Rectangle &rec) :
_shader(shader), _rec(rec), _vel(0.0f), _rl(this) { this->init(); };
Car(Shader &shader, Rectangle &rec, float vel):
_shader(shader), _rec(rec), _vel(vel), _rl(this) { this->init(); };
void init();
void update(float dt);
void draw();
void draw(size_t cur_state_index);
void recalcSubRecPos();
void move(const glm::vec3 &to);
void runRL();
double scoreRL();
void reset();
void color(const glm::vec3 &new_color);
void accelerate(float scale = 1.0f);
void decelerate(float scale = 1.0f);
void moveForward(float dt);
void turnLeft(float scale = 1.0f);
void turnRight(float scale = 1.0f);
void processInput(GLFWwindow *window);
void setGoal(const glm::vec3 &goal) { this->_goal = goal; };
void setObstacle(Obstacle &ob) { this->_ob = ob; this->_has_ob = true; };
void trainRL(float sim_time, float dt);
// std::unordered_map<std::string, std::vector<std::vector<double>>> runRL(float sim_time, float dt);
void printStates();
void printActions();
size_t curStatesSize() { return _rl_state_vec.size(); };
size_t curActionsSize() { return _rl_action_vec.size(); };
void forceToMoveTo(const glm::vec3 &to) { this->move(to - this->_rec.tl()); };
void forceToRotateTo(const float theta) { this->_theta = theta; };
void saveModel(const std::string &outfile) { this->_rl.save(outfile); };
void loadModel(const std::string &infile) { this->_rl.load(infile); };
void setFLTime(float sim_time, float dt)
{
this->_rl_sim_time = sim_time;
this->_rl_dt = dt;
}
private:
Shader _shader;
Rectangle& _rec, _rec_sub;
float _vel = 1.0f;
float _theta = 0.0f;
float _omega = 0.0f;
float _car_radius = 0.0f;
glm::vec3 _color = glm::vec3(0.0f);
glm::vec3 _main_sub_center_vec = glm::vec3(0.0f);
glm::vec3 _initial_car_center = glm::vec3(0.0f);
glm::vec3 _initial_car_bl, _initial_car_br, _initial_car_tl, _initial_car_tr;
glm::vec3 _goal = glm::vec3(0.0f);
RL _rl;
Obstacle _ob;
bool _has_ob = false;
float _rl_sim_time, _rl_dt;
std::vector<std::vector<double>> _rl_state_vec, _rl_action_vec;
};
#endif
|
#ifndef GRAPHICSDEVICECREATOR_H_
#define GRAPHICSDEVICECREATOR_H_
#include <memory>
#include <string>
namespace revel
{
namespace renderer
{
//forward decl
class GraphicsDevice;
class GraphicsDeviceCreator
{
public:
GraphicsDeviceCreator();
~GraphicsDeviceCreator();
/**
* @brief Create a render device.
*
* @param api The API (OpenGL / DirectX) used by the device.
*/
static std::unique_ptr<GraphicsDevice> create_device(const std::string& api);
};
} // ::revel::renderer
} // ::revel
#endif // GRAPHICSDEVICECREATOR_H_
|
#include "stdafx.h"
#include "InputHandler.h"
using namespace GraphicsEngine;
InputHandler::InputHandler() :
m_keys({})
{
}
|
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxv = 512;
const int INF = 0x3fffffff;
int n, m, st, ed, weight[maxv], G[maxv][maxv];
int d[maxv], w[maxv], num[maxv];
bool vis[maxv] = {false};
void Dijkstra(int st)
{
fill(d, d + maxv, INF);
fill(w, w + maxv, 0);
fill(num, num + maxv, 0);
d[st] = 0;
w[st] = weight[st];
num[st] = 1;
// 外循环,取当前距离起点最近的节点,要把所有节点都取完,最后得到的是起点距离所有点的最短路径
// 单源最短路问题
// 不是n-1,因为这里取一个点代表用该点作为中介点优化到其他点的距离
// Bellman-Ford算法才是n-1,因为取n的话就已经成环
for (int i = 0; i < n; i++)
{
int u = -1, MIN = INF;
for (int j = 0; j < n; j++)
{
if (vis[j] == false && d[j] < MIN)
{
u = j;
MIN = d[j];
}
}
// 在未访问的节点即vis[j] == false的节点中,找不到距离小于INF的,说明剩下的节点都不连通
if (u == -1)
return;
vis[u] = true;
for (int v = 0; v < n; v++)
{
// 注意这里访问的概念,不是说被更新过,这里的更新并不会把它设置成被访问
// 而是指最外层循环时该点被取出来,是当时距离最小的点
if (vis[v] == false && G[u][v] != INF)
{
if (d[u] + G[u][v] < d[v])
{
d[v] = d[u] + G[u][v];
w[v] = w[u] + weight[v];
num[v] = num[u];
}
else if (d[u] + G[u][v] == d[v])
{
if (w[u] + weight[v] > w[v])
{
w[v] = w[u] + weight[v];
}
num[v] += num[u];
}
}
}
}
}
int main()
{
scanf("%d%d%d%d", &n, &m, &st, &ed);
for (int i = 0; i < n; i++)
scanf("%d", &weight[i]);
fill(G[0], G[0] + maxv * maxv, INF);
for (int i = 0; i < m; i++)
{
int u, v;
scanf("%d%d", &u, &v);
scanf("%d", &G[u][v]);
G[v][u] = G[u][v];
}
Dijkstra(st);
printf("%d %d\n", num[ed], w[ed]);
}
|
#include <cstdio>
int main() {
int n, m; scanf("%d %d", &n, &m);
int ans = n, tmp = n;
while (tmp >=m) {
ans += tmp / m;
tmp /= m;
}
printf("%d", ans);
return 0;
}
|
#pragma once
#include "SteeringBehaviour.h"
class Approach :
public SteeringBehaviour
{
public:
Approach(Boid* parent, sf::Vector2f* target, float weight = 1.0f);
sf::Vector2f CalculateSteeringForce() override;
const sf::Vector2f* target;
};
|
#ifndef DEUS_PERFORMANCETESTS_UTIL_HPP_
#define DEUS_PERFORMANCETESTS_UTIL_HPP_
#include <cstddef>
#include <deus/Constants.hpp>
#include <deus/UnicodeView.hpp>
namespace deus_perf_util
{
//------------------------------------------------------------------------------
// ENUMERATORS
//------------------------------------------------------------------------------
enum class StringSize
{
kShort,
kMedium,
kLong,
kExtraLong,
kMixed
};
//------------------------------------------------------------------------------
// FUNCTIONS
//------------------------------------------------------------------------------
// Resets all generator functions
void clear_generators();
// Generates a random sequence of dynamically allocated strings of deterministic
// lengths.
void gen_rand_dyn_strs(
deus::Encoding encoding,
deus_perf_util::StringSize string_size);
// Returns the next randomly generated dynamically allocated string in the
// the sequence. note: the gen_rand_dyn_strs function must have been called
// first
const char* get_next_rand_dyn_str(std::size_t& byte_length);
// Generates a random sequence of dynamically allocated strings of deterministic
// length store within UnicodeViews.
void gen_rand_dyn_views(
deus::Encoding encoding,
deus_perf_util::StringSize string_size);
// Returns the next randomly generated dynamically allocated string inside a
// view in the sequence. note: the gen_rand_dyn_views function must have been
// called first
const deus::UnicodeView& get_next_rand_dyn_view();
} // namespace deus_perf_util
#endif
|
#include <sstream>
#include <iostream>
#include <fstream>
#include <openssl/sha.h>
#include <iomanip>
using namespace std;
SHA256_CTX sha256;
unsigned char my_hash[SHA256_DIGEST_LENGTH];
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
//See https://github.com/FreeRDP/FreeRDP-WebConnect/blob/master/wsgate/base64.cpp for origin
string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
int main(int argc, char **argv){
if (argc<2) return -1;
ifstream is;
int BLOCK = 1024;
streampos pos;
is.open(argv[1], ios::in | ios::binary);
SHA256_Init(&sha256);
if (is) {
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char * buffer = new char [BLOCK];
while(is){
is.read(buffer, BLOCK);
SHA256_Update(&sha256,buffer,is.gcount());
}
is.close();
delete[] buffer;
} else {
cout << "Unable to open file";
return 0;
}
SHA256_Final(my_hash, &sha256);
cout << "sha2:" << base64_encode(my_hash, SHA256_DIGEST_LENGTH) << endl;
return 0;
}
|
#include<omp.h>
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<string>
#include<sstream>
#include<iomanip>
#include<ctime>
#include<sys/ioctl.h>
#include<unistd.h>
#include <linux/perf_event.h>
//#include <linux/hw_breakpoint.h>
#include<stdint.h>
#include<sys/syscall.h>
#include<cstring>
#include<errno.h>
using namespace std;
#define N 10
#define M 1.0f
#define R 0.5f
#define G 6.67*1e-11f
#define XMAX 100.0f
#define YMAX 200.0f
#define ZMAX 400.0f
#define SEED 2
#define dt 0.005f
#define RUN 60*60
#define NUM_THREADS 48
#define CYCLES 0
#define CACHE_REF 1
#define CACHE_MIS 2
#define L1D_R_AC 3
#define L1D_R_MIS 4
#define PERF_GROUP1 0
#define PERF_GROUP2 3
#define ACTIVE_GROUP 3
#define DEBUG(fd,err) if(fd==-1){ \
cerr<<"Unable to open "<<err<<". Exiting."; \
exit(EXIT_FAILURE); \
}
#define CACHE_LINE_SIZE 64
typedef struct triplet{
double first;
double second;
double third;
triplet():first(0.0f),second(0.0f),third(0.0f){}
triplet(double f,double s,double t): first(f),second(s),third(t){}
}triplet;
struct read_format{
uint64_t nr; /* The number of events */
struct{
uint64_t value; /* The value of the event */
uint64_t id; /* if PERF_FORMAT_ID */
}values[];
};
void printStatToFile(struct read_format*,ofstream&,vector<uint64_t>&);
vector<int> init_perf(vector<uint64_t>&);
void printToFile(vector<triplet>&,ofstream&);
ostream& operator <<(ostream&,triplet&);
|
#ifndef _VEC_H
#define _VEC_H
struct Vec {
double x,y,z;
Vec() {
x = 0.0;
y = 0.0;
z = 0.0;
}
Vec(double x0, double y0, double z0) {
x = x0;
y = y0;
z = z0;
}
Vec(double v0) {
x = y = z = v0;
}
Vec operator+(const Vec& vec3) const {
return Vec(x+vec3.x,y+vec3.y,z+vec3.z);
}
Vec operator-(const Vec& vec3) const {
return Vec(x-vec3.x,y-vec3.y,z-vec3.z);
}
Vec& operator+=(const Vec& vec3) {
x+=vec3.x;
y+=vec3.y;
z+=vec3.z;
return *this;
}
Vec& operator-=(const Vec& vec3) {
x-=vec3.x;
y-=vec3.y;
z-=vec3.z;
return *this;
}
// Skal‰rprodukt
double operator*(const Vec &vec3) const {
return x*vec3.x + y*vec3.y + z*vec3.z;
}
Vec operator*(double s) const {
return Vec((s*x), (s*y), (s*z));
}
Vec& operator*=(double s) {
x*=s;
y*=s;
z*=s;
return *this;
}
Vec& operator/=(double s) {
return *this *= 1.0/s;
}
Vec operator/(double s) const {
double invS = 1.0/s;
return Vec(x*invS, y*invS, z*invS);
}
double length(void)
{
return sqrt(x*x+y*y+z*z);
}
// Normalisera vektor
Vec& Normalize() {
double len = sqrt( x*x + y*y + z*z );
x /= len;
y /= len;
z /= len;
return *this;
}
Vec cross(Vec b)
{
return Vec(y*b.z-z*b.y,-1*(x*b.z-z*b.x),x*b.y-y*b.x);
}
~Vec() {}
};
std::ostream& operator<<(std::ostream& o, const Vec& obj)
{
return o << "[" << obj.x << " " << obj.y << " " << obj.z << "]";
};
#endif
|
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include <mpdef/tree_node.hpp>
#include <boost/hana.hpp>
namespace hana = boost::hana;
int main()
{
// Comparable
{
BOOST_HANA_CONSTANT_ASSERT(hana::equal(
mpdef::make_tree_node(hana::type_c<void>,
hana::make_map(
mpdef::make_tree_node(hana::int_c<1>, hana::int_c<-1>),
mpdef::make_tree_node(hana::int_c<2>, hana::int_c<-2>)
)
)
,
mpdef::make_tree_node(hana::type_c<void>,
hana::make_map(
mpdef::make_tree_node(hana::int_c<2>, hana::int_c<-2>),
mpdef::make_tree_node(hana::int_c<1>, hana::int_c<-1>)
)
)
));
}
// Product
{
constexpr auto x = mpdef::make_tree_node(hana::int_c<1>, hana::int_c<-1>);
BOOST_HANA_CONSTANT_ASSERT(hana::equal(hana::first(x), hana::int_c<1>));
BOOST_HANA_CONSTANT_ASSERT(hana::equal(hana::second(x), hana::int_c<-1>));
}
{
constexpr auto pred = hana::compose(hana::equal.to(hana::int_c<1>), hana::first);
constexpr auto xs = hana::make_tuple(
mpdef::make_tree_node(hana::int_c<1>, hana::int_c<-1>),
mpdef::make_tree_node(hana::int_c<2>, hana::int_c<-2>)
);
BOOST_HANA_CONSTANT_ASSERT(hana::equal(
hana::filter(xs, pred),
hana::make_tuple(mpdef::make_tree_node(hana::int_c<1>, hana::int_c<-1>))
));
}
}
|
#pragma once
#include <vector>
#include <functional>
class Function {
using xn_t = std::vector<double>;
public:
Function(std::function<double(xn_t const&)> func, std::function<xn_t(xn_t const&)> grad);
Function(std::vector<double> const& func, std::function<xn_t(xn_t const&)> grad);
double operator()(xn_t const& x);
xn_t gradient_at(xn_t const& x);
static double dot_product(xn_t const& x, xn_t const& y);
size_t get_counter() const;
size_t get_gradient_counter() const;
~Function();
private:
enum class FuncType {
NORMAL,
LINEAR,
};
FuncType ft;
std::function<double(xn_t const&)> func;
std::vector<double> lin_func;
std::function<xn_t(xn_t const&)> grad;
size_t counter = 0;
size_t gradient_counter = 0;
};
|
/*
* SPDX-FileCopyrightText: 2017 Rolf Eike Beer <eike@sf-mail.de>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include "josm_presets_p.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dirent.h>
#include <fdguard.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <memory>
#include <numeric>
#include <stack>
#include <strings.h>
#include <sys/stat.h>
#include <unordered_map>
#include "osm2go_annotations.h"
#include <osm2go_platform.h>
#include "osm2go_stl.h"
#ifndef LIBXML_TREE_ENABLED
#error "Tree not enabled in libxml"
#endif
typedef std::unordered_map<std::string, presets_item *> ChunkMap;
/* --------------------- presets.xml parsing ----------------------- */
std::string josm_icon_name_adjust(const char *name) {
size_t len = strlen(name);
if(likely(len > 4)) {
const char * const ext = name + len - 4;
/* the icon loader uses names without extension */
if(strcasecmp(ext, ".png") == 0 || strcasecmp(ext, ".svg") == 0)
len -= 4;
}
return std::string(name, len);
}
namespace {
std::string __attribute__((nonnull(1)))
josm_icon_name_adjust(const char *name, const std::string &basepath, int basedirfd)
{
struct stat st;
if(fstatat(basedirfd, name, &st, 0) == 0 && S_ISREG(st.st_mode))
return basepath + name;
return ::josm_icon_name_adjust(name);
}
typedef std::vector<std::pair<presets_item_t::item_type, std::string> > TypeStrMap;
TypeStrMap
type_map_init()
{
TypeStrMap ret(5);
TypeStrMap::size_type pos = 0;
ret[pos++] = TypeStrMap::value_type(presets_item_t::TY_WAY, "way");
ret[pos++] = TypeStrMap::value_type(presets_item_t::TY_NODE, "node");
ret[pos++] = TypeStrMap::value_type(presets_item_t::TY_RELATION, "relation");
ret[pos++] = TypeStrMap::value_type(presets_item_t::TY_CLOSED_WAY, "closedway");
ret[pos++] = TypeStrMap::value_type(presets_item_t::TY_MULTIPOLYGON, "multipolygon");
return ret;
}
class find_type {
const char * const type;
const char sep;
public:
explicit inline find_type(const char *t, const char s) : type(t), sep(s) {}
inline bool operator()(const TypeStrMap::value_type &v)
{
const size_t tlen = v.second.size();
return strncmp(v.second.c_str(), type, tlen) == 0 && type[tlen] == sep;
}
};
int
josm_type_bit(const char *type, char sep)
{
static const TypeStrMap types = type_map_init();
const TypeStrMap::const_iterator itEnd = types.end();
const TypeStrMap::const_iterator it = std::find_if(types.begin(), itEnd,
find_type(type, sep));
if(likely(it != itEnd))
return it->first;
// This prints the remaining string even if a separator follows. Who cares.
printf("WARNING: unexpected type %s\n", type);
return 0;
}
/* parse a comma seperated list of types and set their bits */
unsigned int
josm_type_parse(const char *type)
{
unsigned int type_mask = 0;
if(type == nullptr)
return presets_item_t::TY_ALL;
for(const char *ntype = strchr(type, ',');
ntype != nullptr; ntype = strchr(type, ',')) {
type_mask |= josm_type_bit(type, ',');
type = ntype + 1;
}
type_mask |= josm_type_bit(type, '\0');
return type_mask;
}
// custom find to avoid memory allocations for std::string
template<typename T>
struct str_map_find {
const char * const name;
explicit str_map_find(const char * n)
: name(n) {}
bool operator()(const typename T::value_type &p) {
return (strcmp(p.name, name) == 0);
}
};
class PresetSax {
public:
enum State {
DocStart,
TagPresets,
TagGroup,
TagItem,
TagChunk,
TagReference,
TagPresetLink,
TagKey,
TagText,
TagCombo,
TagMultiselect,
TagListEntry,
TagCheck,
TagLabel,
TagSpace,
TagSeparator,
TagLink,
TagRoles,
TagRole,
IntermediateTag, ///< tag itself is ignored, but childs are processed
UnknownTag
};
// this maps the XML tag name to the target state and the list of allowed source states
struct StateChange {
StateChange(const char *nm, State os, const std::vector<State> &ns)
: name(nm), oldState(os), newStates(ns) {}
const char *name;
State oldState;
std::vector<State> newStates;
};
typedef std::vector<StateChange> StateMap;
static const StateMap &preset_state_map();
private:
xmlSAXHandler handler;
// not a stack because that can't be iterated
std::vector<State> state;
std::stack<presets_item_t *> items; // the current item stack (i.e. menu layout)
std::stack<presets_element_t *> widgets; // the current widget stack (i.e. dialog layout)
presets_items_internal &presets;
const std::string &basepath;
const int basedirfd;
const std::vector<std::string> &langs;
bool resolvePresetLink(presets_element_link* link, const std::string &id);
/**
* @brief dump out the current object stack
* @param before message to print before the stack listing
* @param after0 first message to print after the stack listing
* @param after1 second message to print after the stack listing
*
* The line is always terminated with a LF.
*/
void dumpState(const char *before = nullptr, const char *after0 = nullptr, const char *after1 = nullptr) const;
public:
explicit PresetSax(presets_items_internal &p, const std::string &b, int basefd);
bool parse(const std::string &filename);
ChunkMap chunks;
typedef std::vector<std::pair<presets_element_link *, std::string> > LLinks;
ChunkMap itemsNames;
LLinks laterLinks; ///< unresolved preset_link references
private:
struct find_link_ref {
PresetSax &px;
explicit find_link_ref(PresetSax &p) : px(p) {}
void operator()(LLinks::value_type &l);
};
void characters(const char *ch, int len);
static void cb_characters(void *ts, const xmlChar *ch, int len) {
static_cast<PresetSax *>(ts)->characters(reinterpret_cast<const char *>(ch), len);
}
void startElement(const char *name, const char **attrs);
static void cb_startElement(void *ts, const xmlChar *name, const xmlChar **attrs) {
static_cast<PresetSax *>(ts)->startElement(reinterpret_cast<const char *>(name),
reinterpret_cast<const char **>(attrs));
}
void endElement(const xmlChar *name);
static void cb_endElement(void *ts, const xmlChar *name) {
static_cast<PresetSax *>(ts)->endElement(name);
}
/**
* @brief find attribute with the given name
* @param attrs the attribute list to search
* @param name the key to look for
* @param useLang if localized keys should be preferred
* @returns the attribute string if present
*
* If the attribute is present but the string is empty a nullptr is returned.
*/
const char *findAttribute(const char **attrs, const char *name, bool useLang = true) const;
// it's not worth the effort to convert this to an unordered_map as it has very few members
typedef std::map<const char *, const char *> AttrMap;
/**
* @brief find the attributes with the given names
* @param attrs the attribute list to search
* @param names the keys to look for
* @param count elements in names
* @param langflags if localized keys should be preferred (bitwise positions of entries in names)
* @returns the found keys
*/
AttrMap findAttributes(const char **attrs, const char **names, unsigned int count, unsigned int langflags = 0) const;
};
PresetSax::StateMap
preset_state_map_init()
{
PresetSax::StateMap map;
#if __cplusplus >= 201103L
#define STATE_VECTOR_START(n, N) const std::vector<PresetSax::State> n =
#define STATE_VECTOR_END(n)
# define VECTOR_ONE(a) { a }
#else
#define STATE_VECTOR_START(n, N) const std::array<PresetSax::State, N> n##_ref = {
#define STATE_VECTOR_END(n) }; const std::vector<PresetSax::State> n(n##_ref.begin(), n##_ref.end())
# define VECTOR_ONE(a) std::vector<PresetSax::State>(1, (a))
#endif
STATE_VECTOR_START(item_chunks, 2) { PresetSax::TagChunk, PresetSax::TagItem } STATE_VECTOR_END(item_chunks);
STATE_VECTOR_START(item_refs, 5) { PresetSax::TagChunk, PresetSax::TagItem, PresetSax::TagCombo, PresetSax::TagMultiselect, PresetSax::TagRoles } STATE_VECTOR_END(item_refs);
STATE_VECTOR_START(pr_gr, 2) { PresetSax::TagPresets, PresetSax::TagGroup } STATE_VECTOR_END(pr_gr);
STATE_VECTOR_START(selectables, 3) { PresetSax::TagCombo, PresetSax::TagMultiselect, PresetSax::TagChunk } STATE_VECTOR_END(selectables);
STATE_VECTOR_START(roles_chunks, 2) { PresetSax::TagRoles, PresetSax::TagChunk } STATE_VECTOR_END(roles_chunks);
#define MAPFILL 20
map.reserve(MAPFILL);
map.push_back(PresetSax::StateMap::value_type("presets", PresetSax::TagPresets, VECTOR_ONE(PresetSax::DocStart)));
map.push_back(PresetSax::StateMap::value_type("chunk", PresetSax::TagChunk, VECTOR_ONE(PresetSax::TagPresets)));
map.push_back(PresetSax::StateMap::value_type("group", PresetSax::TagGroup, pr_gr));
// ignore the case of standalone items and separators for now as it does not happen yet
map.push_back(PresetSax::StateMap::value_type("item", PresetSax::TagItem, VECTOR_ONE(PresetSax::TagGroup)));
map.push_back(PresetSax::StateMap::value_type("separator", PresetSax::TagSeparator, VECTOR_ONE(PresetSax::TagGroup)));
map.push_back(PresetSax::StateMap::value_type("reference", PresetSax::TagReference, item_refs));
map.push_back(PresetSax::StateMap::value_type("preset_link", PresetSax::TagPresetLink, item_chunks));
map.push_back(PresetSax::StateMap::value_type("key", PresetSax::TagKey, item_chunks));
map.push_back(PresetSax::StateMap::value_type("text", PresetSax::TagText, item_chunks));
map.push_back(PresetSax::StateMap::value_type("combo", PresetSax::TagCombo, item_chunks));
map.push_back(PresetSax::StateMap::value_type("multiselect", PresetSax::TagMultiselect, item_chunks));
map.push_back(PresetSax::StateMap::value_type("list_entry", PresetSax::TagListEntry, selectables));
map.push_back(PresetSax::StateMap::value_type("check", PresetSax::TagCheck, item_chunks));
map.push_back(PresetSax::StateMap::value_type("label", PresetSax::TagLabel, item_chunks));
map.push_back(PresetSax::StateMap::value_type("space", PresetSax::TagSpace, item_chunks));
map.push_back(PresetSax::StateMap::value_type("link", PresetSax::TagLink, item_chunks));
map.push_back(PresetSax::StateMap::value_type("roles", PresetSax::TagRoles, item_chunks));
map.push_back(PresetSax::StateMap::value_type("role", PresetSax::TagRole, roles_chunks));
map.push_back(PresetSax::StateMap::value_type("checkgroup", PresetSax::IntermediateTag, item_chunks));
map.push_back(PresetSax::StateMap::value_type("optional", PresetSax::IntermediateTag, item_chunks));
// make sure the one-time reservation is the correct size
assert(map.size() == MAPFILL);
return map;
}
const PresetSax::StateMap &PresetSax::preset_state_map()
{
static const PresetSax::StateMap map = preset_state_map_init();
return map;
}
// Map back a state to it's string. Only used for debug messages.
struct name_find {
const PresetSax::State state;
explicit inline name_find(PresetSax::State s) : state(s) {}
inline bool operator()(const PresetSax::StateMap::value_type &p) const {
return p.oldState == state;
}
};
void
dumpTag(PresetSax::State st)
{
if(st == PresetSax::UnknownTag || st == PresetSax::IntermediateTag) {
printf("*/");
} else {
const PresetSax::StateMap &tags = PresetSax::preset_state_map();
const PresetSax::StateMap::const_iterator nitEnd = tags.end();
const PresetSax::StateMap::const_iterator nit = std::find_if(tags.begin(), nitEnd, name_find(st));
assert(nit != nitEnd);
printf("%s/", nit->name);
}
}
void
PresetSax::dumpState(const char *before, const char *after0, const char *after1) const
{
if(before != nullptr)
printf("%s ", before);
std::for_each(std::next(state.begin()), state.end(), dumpTag);
if(after0 != nullptr) {
fputs(after0, stdout);
if(after1 != nullptr)
fputs(after1, stdout);
} else {
assert_null(after1);
}
puts("");
}
/**
* @brief get the user language strings from environment
*/
const std::vector<std::string> &userLangs()
{
static std::vector<std::string> lcodes;
if(lcodes.empty()) {
const char *lcm = getenv("LC_MESSAGES");
if(lcm == nullptr || *lcm == '\0')
lcm = getenv("LANG");
if(lcm != nullptr && *lcm != '\0') {
std::string lc = lcm;
std::string::size_type d = lc.find('.');
if(d != std::string::npos)
lc.erase(d);
lcodes.push_back(lc + '.');
d = lc.find('_');
if(d != std::string::npos)
lcodes.push_back(lc.substr(0, d) + '.');
}
}
return lcodes;
}
PresetSax::PresetSax(presets_items_internal &p, const std::string &b, int basefd)
: presets(p)
, basepath(b)
, basedirfd(basefd)
, langs(userLangs())
{
memset(&handler, 0, sizeof(handler));
handler.characters = cb_characters;
handler.startElement = cb_startElement;
handler.endElement = cb_endElement;
state.push_back(DocStart);
}
struct find_link_parent {
const presets_element_link *link;
explicit find_link_parent(const presets_element_link *l) : link(l) {}
bool operator()(presets_item_t *t);
inline bool operator()(const ChunkMap::value_type &p) {
return operator()(p.second);
}
};
bool find_link_parent::operator()(presets_item_t *t)
{
if(t->type & presets_item_t::TY_GROUP) {
const presets_item_group * const gr = static_cast<presets_item_group *>(t);
return std::any_of(gr->items.begin(), gr->items.end(), *this);
}
if(!t->isItem())
return false;
presets_item * const item = static_cast<presets_item *>(t);
const std::vector<presets_element_t *>::iterator it = std::find(item->widgets.begin(),
item->widgets.end(),
link);
if(it == item->widgets.end())
return false;
item->widgets.erase(it);
delete link;
link = nullptr;
return true;
}
void PresetSax::find_link_ref::operator()(PresetSax::LLinks::value_type &l)
{
if(unlikely(!px.resolvePresetLink(l.first, l.second))) {
printf("found preset_link with unmatched preset_name '%s'\n", l.second.c_str());
// delete the link widget everywhere it was inserted
find_link_parent fc(l.first);
const std::vector<presets_item_t *>::const_iterator itEnd = px.presets.items.end();
if(std::none_of(std::cbegin(px.presets.items), itEnd, fc)) {
const ChunkMap::const_iterator cit = std::find_if(px.chunks.begin(), px.chunks.end(), fc);
assert(cit != px.chunks.end());
}
}
}
bool PresetSax::parse(const std::string &filename)
{
if (xmlSAXUserParseFile(&handler, this, filename.c_str()) != 0)
return false;
std::for_each(laterLinks.begin(), laterLinks.end(), find_link_ref(*this));
return state.size() == 1;
}
bool PresetSax::resolvePresetLink(presets_element_link *link, const std::string &id)
{
const ChunkMap::const_iterator it = itemsNames.find(id);
// these references may also target items that will only be added later
if(it == itemsNames.end())
return false;
link->item = it->second;
return true;
}
void PresetSax::characters(const char *ch, int len)
{
for(int pos = 0; pos < len; pos++)
if(unlikely(!isspace(ch[pos]))) {
printf("unhandled character data: %*.*s state %i\n", len, len, ch, state.back());
return;
}
}
// check if the given string starts with the iterator value
struct matchHead {
const char * const a;
matchHead(const char *attr) : a(attr) {}
inline bool operator()(const std::string &l) {
return strncmp(a, l.c_str(), l.size()) == 0;
}
};
const char *PresetSax::findAttribute(const char **attrs, const char *name, bool useLang) const {
// If the entire key matches name this is the non-localized (i.e. fallback)
// key. Continue search to find a localized text, if no other is found return
// the defaut one.
const char *c = nullptr;
for(unsigned int i = 0; attrs[i] != nullptr; i += 2) {
// Check if the given attribute begins with one of the preferred language
// codes. If yes, skip over the language code and check this one.
const char *a = attrs[i];
if (useLang) {
const std::vector<std::string>::const_iterator itEnd = langs.end();
const std::vector<std::string>::const_iterator it = std::find_if(std::cbegin(langs), itEnd, matchHead(a));
if (it != itEnd)
a += it->size();
}
if(strcmp(a, name) == 0) {
const char *ret;
if(*(attrs[i + 1]) == '\0')
ret = nullptr;
else
ret = attrs[i + 1];
if(a != attrs[i])
return ret;
c = ret;
}
}
return c;
}
PresetSax::AttrMap PresetSax::findAttributes(const char **attrs, const char **names, unsigned int count, unsigned int langflags) const
{
AttrMap ret;
for(unsigned int i = 0; attrs[i] != nullptr; i += 2) {
// Check if the given attribute begins with one of the preferred language
// codes. If yes, skip over the language code and check this one.
const char *a = attrs[i];
bool isLoc = false;
const std::vector<std::string>::const_iterator itEnd = langs.end();
const std::vector<std::string>::const_iterator it = std::find_if(std::cbegin(langs), itEnd, matchHead(a));
if (it != itEnd) {
a += it->size();
isLoc = true;
}
for(unsigned int j = 0; j < count; j++) {
if(strcmp(a, names[j]) == 0) {
// if this is localized and no localization was permitted: skip
if(isLoc && !(langflags & (1 << j)))
continue;
if(*(attrs[i + 1]) != '\0') {
// if this is localized: store, if not, store only if nothing in map right now
if(isLoc || ret.find(names[j]) == ret.end())
ret[names[j]] = attrs[i + 1];
}
}
}
}
return ret;
}
#define NULL_OR_VAL(a) ((a) ? (a) : std::string())
#define NULL_OR_MAP_STR(it) ((it) != aitEnd ? (it)->second : std::string())
#define NULL_OR_MAP_VAL(it) ((it) != aitEnd ? (it)->second : nullptr)
bool
not_intermediate(PresetSax::State st)
{
return st != PresetSax::IntermediateTag;
}
void PresetSax::startElement(const char *name, const char **attrs)
{
const StateMap &tags = preset_state_map();
StateMap::const_iterator it = std::find_if(tags.begin(), tags.end(),
str_map_find<StateMap>(name));
if(it == tags.end()) {
dumpState("found unhandled", name);
state.push_back(UnknownTag);
return;
}
// ignore IntermediateTag when checking for valid parent tags
State oldState = state.back();
if(oldState == IntermediateTag) {
const std::vector<State>::const_reverse_iterator ritEnd = state.rend();
const std::vector<State>::const_reverse_iterator rit =
std::find_if(static_cast<std::vector<State>::const_reverse_iterator>(state.rbegin()),
ritEnd, not_intermediate);
if(likely(rit != ritEnd))
oldState = *rit;
}
if(std::find(it->newStates.begin(), it->newStates.end(), oldState) ==
it->newStates.end()) {
dumpState("found unexpected", name);
state.push_back(UnknownTag);
return;
}
presets_element_t *widget = nullptr;
switch(it->oldState) {
case IntermediateTag:
break;
case DocStart:
case UnknownTag:
assert_unreachable();
case TagPresets:
break;
case TagChunk: {
const char *id = findAttribute(attrs, "id", false);
presets_item *item = new presets_item(presets_item_t::TY_ALL, NULL_OR_VAL(id));
items.push(item);
break;
}
case TagGroup: {
std::array<const char *, 2> names = { { "name", "icon" } };
const AttrMap &a = findAttributes(attrs, names.data(), names.size(), 1);
const AttrMap::const_iterator aitEnd = a.end();
const std::string &nm = NULL_OR_MAP_STR(a.find("name"));
const AttrMap::const_iterator icit = a.find("icon");
std::string ic;
if(icit != aitEnd)
ic = josm_icon_name_adjust(icit->second, basepath, basedirfd);
presets_item_group *group = new presets_item_group(0,
items.empty() ? nullptr : static_cast<presets_item_group *>(items.top()),
nm, ic);
if(items.empty())
presets.items.push_back(group);
else
static_cast<presets_item_group *>(items.top())->items.push_back(group);
items.push(group);
break;
}
case TagSeparator: {
assert(!items.empty());
assert(items.top()->type & presets_item_t::TY_GROUP);
presets_item_separator *sep = new presets_item_separator();
static_cast<presets_item_group *>(items.top())->items.push_back(sep);
items.push(sep);
break;
}
case TagItem: {
std::array<const char *, 4> names = { { "name", "type", "icon", "preset_name_label" } };
const AttrMap &a = findAttributes(attrs, names.data(), names.size(), 1);
const AttrMap::const_iterator aitEnd = a.end();
AttrMap::const_iterator ait = a.find("preset_name_label");
bool addEditName = ait != aitEnd && (strcmp(ait->second, "true") == 0);
ait = a.find("icon");
std::string ic;
if(ait != aitEnd)
ic = josm_icon_name_adjust(ait->second, basepath, basedirfd);
const char *tp = NULL_OR_MAP_VAL(a.find("type"));
const std::string &n = NULL_OR_MAP_STR(a.find("name"));
presets_item *item = new presets_item(josm_type_parse(tp), n, ic,
addEditName);
assert((items.top()->type & presets_item_t::TY_GROUP) != 0);
static_cast<presets_item_group *>(items.top())->items.push_back(item);
items.push(item);
if(likely(!n.empty())) {
// search again: the key must be the unlocalized name here
itemsNames[findAttribute(attrs, "name", false)] = item;
} else {
dumpState("found", "item without name");
}
break;
}
case TagPresetLink: {
const char *id = findAttribute(attrs, "preset_name", false);
presets_element_link *link = new presets_element_link();
assert(!items.empty());
assert(items.top()->isItem());
presets_item *item = static_cast<presets_item *>(items.top());
// make sure not to insert it as a stale link in case the item is invalid,
// as that would be deleted on it's end tag and a stale reference would remain
// in laterLinks
if(likely(!item->name.empty())) {
if(unlikely(!id)) {
dumpState("found", "preset_link without preset_name");
} else {
if(!resolvePresetLink(link, id))
// these references may also target items that will only be added later
laterLinks.push_back(LLinks::value_type(link, id));
}
item->widgets.push_back(link);
}
widgets.push(link);
break;
}
case TagReference: {
const char *id = findAttribute(attrs, "ref", false);
presets_item *ref = nullptr;
if(unlikely(!id)) {
dumpState("found", "reference without ref");
} else {
const ChunkMap::const_iterator ait = chunks.find(id);
if(unlikely(ait == chunks.end())) {
dumpState("found", "reference with unresolved ref ", id);
} else {
ref = ait->second;
// if this is a reference to something that only contains list_entries, then just copy them over
if(ref->widgets.size() == 1 && ref->widgets.front()->type == WIDGET_TYPE_CHUNK_LIST_ENTRIES &&
(widgets.top()->type == WIDGET_TYPE_COMBO || widgets.top()->type == WIDGET_TYPE_MULTISELECT)) {
presets_element_selectable * const selitem = static_cast<presets_element_selectable *>(widgets.top());
const presets_element_list_entry_chunks * const lechunk = static_cast<presets_element_list_entry_chunks *>(ref->widgets.front());
selitem->values.reserve(selitem->values.size() + lechunk->values.size());
std::copy(lechunk->values.begin(), lechunk->values.end(), std::back_inserter(selitem->values));
selitem->display_values.reserve(selitem->display_values.size() + lechunk->display_values.size());
std::copy(lechunk->display_values.begin(), lechunk->display_values.end(), std::back_inserter(selitem->display_values));
// same for role entries
} else if (ref->widgets.size() == 1 && ref->widgets.front()->type == WIDGET_TYPE_CHUNK_ROLE_ENTRIES) {
presets_element_role_entry_chunks * const selitem = static_cast<presets_element_role_entry_chunks *>(ref->widgets.front());
assert(items.top()->isItem());
presets_item * const target = static_cast<presets_item *>(items.top());
std::copy(selitem->roles.begin(), selitem->roles.end(), std::back_inserter(target->roles));
}
}
}
widgets.push(new presets_element_reference(ref));
break;
}
case TagLabel: {
const char *text = findAttribute(attrs, "text");
widgets.push(new presets_element_label(NULL_OR_VAL(text)));
// do not push to items, will be done in endElement()
break;
}
case TagSpace:
assert(!items.empty());
#ifndef FREMANTLE
widget = new presets_element_separator();
#endif
break;
case TagText: {
std::array<const char *, 4> names = { { "key", "text", "default", "match" } };
const AttrMap &a = findAttributes(attrs, names.data(), names.size(), 2);
const AttrMap::const_iterator aitEnd = a.end();
const std::string &key = NULL_OR_MAP_STR(a.find("key"));
const std::string &text = NULL_OR_MAP_STR(a.find("text"));
const std::string &def = NULL_OR_MAP_STR(a.find("default"));
const char *match = NULL_OR_MAP_VAL(a.find("match"));
widget = new presets_element_text(key, text, def, match);
break;
}
case TagKey: {
const char *key = nullptr;
const char *value = nullptr;
const char *match = nullptr;
for(unsigned int i = 0; attrs[i] != nullptr; i += 2) {
if(strcmp(attrs[i], "key") == 0) {
key = attrs[i + 1];
} else if(strcmp(attrs[i], "value") == 0) {
value = attrs[i + 1];
} else if(strcmp(attrs[i], "match") == 0) {
match = attrs[i + 1];
}
}
widget = new presets_element_key(NULL_OR_VAL(key), NULL_OR_VAL(value),
match);
break;
}
case TagCheck: {
std::array<const char *, 5> names = { { "key", "text", "value_on", "match", "default" } };
const AttrMap &a = findAttributes(attrs, names.data(), names.size(), 2);
const AttrMap::const_iterator aitEnd = a.end();
const std::string &key = NULL_OR_MAP_STR(a.find("key"));
const std::string &text = NULL_OR_MAP_STR(a.find("text"));
const std::string &von = NULL_OR_MAP_STR(a.find("value_on"));
const char *match = NULL_OR_MAP_VAL(a.find("match"));
bool on = NULL_OR_MAP_STR(a.find("default")) == "on";
widget = new presets_element_checkbox(key, text, on, match, von);
break;
}
case TagLink: {
assert(!items.empty());
assert(items.top()->isItem());
presets_item * const item = static_cast<presets_item *>(items.top());
std::array<const char *, 2> names = { { "wiki", "href" } };
const AttrMap &a = findAttributes(attrs, names.data(), names.size(), 2);
const AttrMap::const_iterator aitEnd = a.end();
const std::string &href = NULL_OR_MAP_STR(a.find("href"));
const std::string &wiki = NULL_OR_MAP_STR(a.find("wiki"));
if(unlikely(href.empty() && wiki.empty())) {
dumpState("ignoring", "link without href and wiki");
} else {
if(likely(item->link.empty())) {
if(!wiki.empty())
item->link = "https://wiki.openstreetmap.org/wiki/" + wiki;
else
item->link = href;
} else {
dumpState("found surplus", "link");
}
}
break;
}
case TagCombo: {
std::array<const char *, 8> names = { { "key", "text", "display_values", "match", "default", "delimiter", "values", "editable" } };
const AttrMap &a = findAttributes(attrs, names.data(), names.size(), 6);
const AttrMap::const_iterator aitEnd = a.end();
const std::string &key = NULL_OR_MAP_STR(a.find("key"));
const std::string &text = NULL_OR_MAP_STR(a.find("text"));
const std::string &def = NULL_OR_MAP_STR(a.find("default"));
const char *match = NULL_OR_MAP_VAL(a.find("match"));
const char *display_values= NULL_OR_MAP_VAL(a.find("display_values"));
const char *values = NULL_OR_MAP_VAL(a.find("values"));
const char *del = NULL_OR_MAP_VAL(a.find("delimiter"));
const AttrMap::const_iterator ait = a.find("editable");
bool editable = ait == aitEnd || (strcmp(ait->second, "false") != 0);
char delimiter = ',';
if(del != nullptr) {
if(unlikely(strlen(del) != 1))
dumpState("found", "combo with invalid delimiter ", del);
else
delimiter = *del;
}
if(unlikely(!values && display_values)) {
dumpState("found", "combo with display_values but not values");
display_values = nullptr;
}
widget = new presets_element_combo(key, text, def, match,
presets_element_selectable::split_string(values, delimiter),
presets_element_selectable::split_string(display_values, delimiter),
editable);
break;
}
case TagMultiselect: {
std::array<const char *, 8> names = { { "key", "text", "display_values", "match", "default", "delimiter", "values", "rows" } };
const AttrMap &a = findAttributes(attrs, names.data(), names.size(), 6);
const AttrMap::const_iterator aitEnd = a.end();
const std::string &key = NULL_OR_MAP_STR(a.find("key"));
const std::string &text = NULL_OR_MAP_STR(a.find("text"));
const std::string &def = NULL_OR_MAP_STR(a.find("default"));
const char *match = NULL_OR_MAP_VAL(a.find("match"));
const char *display_values= NULL_OR_MAP_VAL(a.find("display_values"));
const char *values = NULL_OR_MAP_VAL(a.find("values"));
const char *del = NULL_OR_MAP_VAL(a.find("delimiter"));
const char *rowstr = NULL_OR_MAP_VAL(a.find("rows"));
char delimiter = ';';
if(del != nullptr) {
if(unlikely(strlen(del) != 1))
dumpState("found", "combo with invalid delimiter ", del);
else
delimiter = *del;
}
if(unlikely(!values && display_values)) {
dumpState("found", "combo with display_values but not values");
display_values = nullptr;
}
unsigned int rows = 0;
if(rowstr != nullptr) {
char *endp;
rows = strtoul(rowstr, &endp, 10);
if(unlikely(*endp != '\0')) {
dumpState("ignoring invalid count value of", "rows");
rows = 0;
}
}
widget = new presets_element_multiselect(key, text, def, match, delimiter,
presets_element_selectable::split_string(values, delimiter),
presets_element_selectable::split_string(display_values, delimiter), rows);
break;
}
case TagListEntry: {
assert(!items.empty());
presets_element_selectable *sel;
if(oldState == TagChunk) {
// to store list_entries we need a special container as they are not standalone items
presets_item * const pit = static_cast<presets_item *>(items.top());
if(pit->widgets.empty())
pit->widgets.push_back(new presets_element_list_entry_chunks());
assert_cmpnum(pit->widgets.size(), 1);
assert_cmpnum(pit->widgets.back()->type, WIDGET_TYPE_CHUNK_LIST_ENTRIES);
sel = static_cast<presets_element_selectable *>(pit->widgets.back());
} else {
assert(!widgets.empty());
assert(widgets.top()->type == WIDGET_TYPE_COMBO || widgets.top()->type == WIDGET_TYPE_MULTISELECT);
sel = static_cast<presets_element_selectable *>(widgets.top());
}
std::array<const char *, 2> names = { { "display_value", "value" } };
const AttrMap &a = findAttributes(attrs, names.data(), names.size(), 3);
const AttrMap::const_iterator aitEnd = a.end();
const char *value = NULL_OR_MAP_VAL(a.find("value"));
if(unlikely(!value)) {
dumpState("found", "list_entry without value");
} else {
sel->values.push_back(value);
const char *dv = NULL_OR_MAP_VAL(a.find("display_value"));
// make sure there is always a string to show, in case all elements have the
// default value the list will be cleared when the containing widget tag is
// closed
sel->display_values.push_back(dv == nullptr ? value : dv);
}
break;
}
case TagRoles:
assert(!items.empty());
break;
case TagRole: {
assert(!items.empty());
assert(items.top()->isItem());
std::vector<presets_item::role> *roles;
if(oldState == TagChunk) {
// to store role entries we need a special container as they are not standalone items
presets_item * const pit = static_cast<presets_item *>(items.top());
if(pit->widgets.empty())
pit->widgets.push_back(new presets_element_role_entry_chunks());
assert_cmpnum(pit->widgets.size(), 1);
assert_cmpnum(pit->widgets.back()->type, WIDGET_TYPE_CHUNK_ROLE_ENTRIES);
roles = &static_cast<presets_element_role_entry_chunks *>(pit->widgets.back())->roles;
} else {
presets_item * const item = static_cast<presets_item *>(items.top());
roles = &item->roles;
}
std::array<const char *, 4> names = { { "key", "type", "count", "regexp" } };
const AttrMap &a = findAttributes(attrs, names.data(), names.size(), 0);
const AttrMap::const_iterator aitEnd = a.end();
// ignore roles marked as regexp, this is not implemented yet
if(likely(a.find("regexp") == aitEnd)) {
const std::string &key = NULL_OR_MAP_STR(a.find("key"));
const char *tp = NULL_OR_MAP_VAL(a.find("type"));
const char *cnt = NULL_OR_MAP_VAL(a.find("count"));
unsigned int count = 0;
if(cnt != nullptr) {
char *endp;
count = strtoul(cnt, &endp, 10);
if(unlikely(*endp != '\0')) {
dumpState("ignoring invalid count value of", "role");
count = 0;
}
}
roles->push_back(presets_item::role(key, josm_type_parse(tp), count));
}
break;
}
}
state.push_back(it->oldState);
if(widget != nullptr) {
assert(!items.empty());
assert(items.top()->isItem());
widgets.push(widget);
static_cast<presets_item *>(items.top())->widgets.push_back(widget);
}
}
void PresetSax::endElement(const xmlChar *name)
{
if(state.back() == UnknownTag) {
state.pop_back();
return;
}
const StateMap &tags = preset_state_map();
StateMap::const_iterator it = std::find_if(tags.begin(), tags.end(),
str_map_find<StateMap>(reinterpret_cast<const char *>(name)));
assert(it != tags.end() || state.back() == UnknownTag);
assert(state.back() == it->oldState);
state.pop_back();
switch(it->oldState) {
case DocStart:
case UnknownTag:
assert_unreachable();
case TagLink:
case TagListEntry:
case TagPresets:
case IntermediateTag:
case TagRoles:
case TagRole:
break;
case TagItem: {
assert_cmpnum(0, widgets.size());
assert(!items.empty());
assert(items.top()->isItem());
presets_item * const item = static_cast<presets_item *>(items.top());
items.pop();
if(unlikely(item->name.empty())) {
/* silently delete, was warned about before */
delete item;
break;
} else {
// update the group type
assert(!items.empty());
presets_item_t * const group = items.top();
assert((group->type & presets_item_t::TY_GROUP) != 0);
*const_cast<unsigned int *>(&group->type) |= item->type;
if(unlikely(!item->roles.empty() && (item->type & (presets_item_t::TY_RELATION | presets_item_t::TY_MULTIPOLYGON)) == 0)) {
dumpState("found", "item with roles, but type does not match relations or multipolygons");
item->roles.clear();
}
break;
}
}
case TagSeparator:
assert(!items.empty());
assert_cmpnum(items.top()->type, presets_item_t::TY_SEPARATOR);
items.pop();
break;
case TagGroup: {
assert(!items.empty());
const presets_item_t * const item = items.top();
assert((item->type & presets_item_t::TY_GROUP) != 0);
items.pop();
// update the parent group type
if(!items.empty()) {
presets_item_t * const group = items.top();
assert((group->type & presets_item_t::TY_GROUP) != 0);
*const_cast<unsigned int *>(&group->type) |= item->type;
}
break;
}
case TagChunk: {
assert(!items.empty());
std::unique_ptr<presets_item> chunk(static_cast<presets_item *>(items.top()));
assert_cmpnum(chunk->type, presets_item_t::TY_ALL);
items.pop();
if(unlikely(chunk->name.empty())) {
dumpState("ignoring", "chunk without id");
return;
}
const std::string &id = chunk->name;
if(unlikely(chunks.find(id) != chunks.end()))
dumpState("ignoring", "chunk with duplicate id ", id.c_str());
else
chunks[id] = chunk.release();
// if this was a top level chunk no active widgets should remain
assert(!items.empty() || widgets.empty());
break;
}
case TagReference: {
assert(!items.empty());
assert(items.top()->isItem());
assert(!widgets.empty());
std::unique_ptr<presets_element_reference> ref(static_cast<presets_element_reference *>(widgets.top()));
widgets.pop();
assert_cmpnum(ref->type, WIDGET_TYPE_REFERENCE);
if(unlikely(ref->item == nullptr)) {
// if this is just a collection of elements that has been inserted
// then drop the pseudo widget, all information is in the actual item now
} else if(ref->item->widgets.size() == 1 && ref->item->widgets.front()->type >= WIDGET_TYPE_CHUNK_CONTAINER) {
} else
static_cast<presets_item *>(items.top())->widgets.push_back(ref.release());
break;
}
case TagLabel: {
assert(!items.empty());
assert(!widgets.empty());
std::unique_ptr<presets_element_label> label(static_cast<presets_element_label *>(widgets.top()));
widgets.pop();
if(unlikely(label->text.empty()))
dumpState("ignoring", "label without text");
else
static_cast<presets_item *>(items.top())->widgets.push_back(label.release());
break;
}
case TagSpace:
assert(!items.empty());
#ifndef FREMANTLE
assert(!widgets.empty());
widgets.pop();
#endif
break;
case TagCombo: {
assert(!items.empty());
assert(!widgets.empty());
presets_element_combo * const combo = static_cast<presets_element_combo *>(widgets.top());
widgets.pop();
if(unlikely(combo->key.empty())) {
dumpState("ignoring", "combo without key");
delete combo;
}
// this usually happens when the list if filled by <list_entry> tags and
// none of that has a display_value given
if(unlikely(combo->values == combo->display_values))
combo->display_values.clear();
break;
}
case TagMultiselect: {
assert(!items.empty());
assert(!widgets.empty());
presets_element_multiselect * const ms = static_cast<presets_element_multiselect *>(widgets.top());
widgets.pop();
if(unlikely(ms->key.empty())) {
dumpState("ignoring", "multiselect without key");
delete ms;
}
// this usually happens when the list if filled by <list_entry> tags and
// none of that has a display_value given
if(unlikely(ms->values == ms->display_values))
ms->display_values.clear();
break;
}
case TagText:
case TagKey:
case TagCheck:
case TagPresetLink:
assert(!items.empty());
assert(!widgets.empty());
widgets.pop();
break;
}
}
inline presets_item_t *
chunkFromPair(const ChunkMap::value_type &p)
{
return p.second;
}
} // namespace
bool presets_items_internal::addFile(const std::string &filename, const std::string &basepath, int basefd)
{
printf("... %s\n", filename.c_str());
PresetSax p(*this, basepath, basefd);
if(!p.parse(filename))
return false;
// now move all chunks to the presets list
chunks.reserve(chunks.size() + p.chunks.size());
std::transform(p.chunks.begin(), p.chunks.end(), std::back_inserter(chunks), chunkFromPair);
return true;
}
void presets_items_internal::lru_update(const presets_item_t *item)
{
const std::vector<const presets_item_t *>::iterator litBegin = lru.begin();
const std::vector<const presets_item_t *>::iterator litEnd = lru.end();
const std::vector<const presets_item_t *>::iterator lit = std::find(litBegin, litEnd, item);
if(lit == litEnd) {
// drop the oldest ones if too many
if(lru.size() >= LRU_MAX)
lru.resize(LRU_MAX - 1);
lru.insert(litBegin, item);
// if it is already the first item in the list nothing is to do
} else if(lit != litBegin) {
// move to front
std::rotate(litBegin, lit, lit + 1);
}
}
presets_items *presets_items::load()
{
printf("Loading JOSM presets ...\n");
std::unique_ptr<presets_items_internal> presets(std::make_unique<presets_items_internal>());
const std::string &filename = find_file("defaultpresets.xml");
if(likely(!filename.empty()))
presets->addFile(filename, std::string(), -1);
// check for user presets
dirguard dir(osm2go_platform::userdatapath());
if(dir.valid()) {
dirent *d;
std::string xmlname;
while ((d = dir.next()) != nullptr) {
if(d->d_type != DT_DIR && d->d_type != DT_UNKNOWN)
continue;
if(strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0)
continue;
dirguard pdir(dir, d->d_name);
if(likely(pdir.valid())) {
// find first XML file inside those directories
dirent *pd;
while ((pd = pdir.next()) != nullptr) {
if(pd->d_type == DT_DIR)
continue;
const size_t nlen = strlen(pd->d_name);
if(nlen > 4 && strcasecmp(pd->d_name + nlen - 4, ".xml") == 0) {
presets->addFile(pdir.path() + pd->d_name, pdir.path(), pdir.dirfd());
break;
}
}
}
}
}
if(unlikely(presets->items.empty()))
return nullptr;
return presets.release();
}
/* ----------------------- cleaning up --------------------- */
struct MatchValue {
MatchValue(const char *n, presets_element_t::Match m) : name(n), match(m) {}
const char *name;
presets_element_t::Match match;
};
presets_element_t::Match presets_element_t::parseMatch(const char *matchstring, Match def)
{
if(matchstring == nullptr)
return def;
typedef std::vector<MatchValue> VMap;
static VMap matches;
if(unlikely(matches.empty())) {
matches.push_back(VMap::value_type("none", MatchIgnore));
matches.push_back(VMap::value_type("key", MatchKey));
matches.push_back(VMap::value_type("key!", MatchKey_Force));
matches.push_back(VMap::value_type("keyvalue", MatchKeyValue));
matches.push_back(VMap::value_type("keyvalue!", MatchKeyValue_Force));
}
const VMap::const_iterator itEnd = matches.end();
const VMap::const_iterator it = std::find_if(std::cbegin(matches),
itEnd, str_map_find<VMap>(matchstring));
return (it == itEnd) ? def : it->match;
}
presets_element_t::presets_element_t(presets_element_type_t t, Match m, const std::string &k, const std::string &txt)
: type(t)
, key(k)
, text(txt)
, match(m)
{
}
bool presets_element_t::is_interactive() const
{
switch(type) {
case WIDGET_TYPE_LABEL:
case WIDGET_TYPE_SEPARATOR:
case WIDGET_TYPE_SPACE:
case WIDGET_TYPE_KEY:
return false;
default:
return true;
}
}
presets_element_t::attach_key *presets_element_t::attach(preset_attach_context &,
const std::string &) const
{
return nullptr;
}
std::string presets_element_t::getValue(presets_element_t::attach_key *) const
{
assert_unreachable();
}
int presets_element_t::matches(const osm_t::TagMap &tags, bool) const
{
if(match == MatchIgnore)
return 0;
const osm_t::TagMap::const_iterator itEnd = tags.end();
const osm_t::TagMap::const_iterator it = tags.find(key);
if(it == itEnd) {
switch(match) {
case MatchKey:
case MatchKeyValue:
return 0;
default:
return -1;
}
}
if(match == MatchKey || match == MatchKey_Force)
return 1;
if(matchValue(it->second))
return 1;
return match == MatchKeyValue_Force ? -1 : 0;
}
presets_element_text::presets_element_text(const std::string &k, const std::string &txt,
const std::string &deflt, const char *m)
: presets_element_t(WIDGET_TYPE_TEXT, parseMatch(m), k, txt)
, def(deflt)
{
}
presets_element_selectable::presets_element_selectable(presets_element_type_t t, const std::string &k,
const std::string &txt, const std::string &deflt,
const char *m, std::vector<std::string> vals,
std::vector<std::string> dvals, bool canEdit)
: presets_element_t(t, parseMatch(m), k, txt)
, def(deflt)
, values(std::move(vals))
, display_values(std::move(dvals))
, editable(canEdit)
{
if (!display_values.empty()) {
size_t dsz = display_values.size();
const size_t vsz = values.size();
// catch mismatches of the array sizes
if (unlikely(dsz < vsz)) {
printf("WARNING: got %zu values, but %zu display_values, filling with values\n", vsz, dsz);
// simply use the values as display_values as it would have happened on empty display_values list
while (dsz < vsz)
display_values.push_back(values[dsz++]);
} else if (unlikely(dsz > vsz)) {
// drop the superfluous values at the back
printf("WARNING: got %zu values, but %zu display_values, truncating\n", vsz, dsz);
display_values.resize(vsz);
}
}
}
std::vector<std::string> presets_element_selectable::split_string(const char *str, const char delimiter)
{
std::vector<std::string> ret;
if(str == nullptr)
return ret;
const char *c, *p = str;
while((c = strchr(p, delimiter)) != nullptr) {
ret.push_back(std::string(p, c - p));
p = c + 1;
}
/* attach remaining string as last value */
ret.push_back(p);
// this vector will never be appended to again, so shrink it to the size
// that is actually needed
shrink_to_fit(ret);
return ret;
}
presets_element_combo::presets_element_combo(const std::string &k, const std::string &txt,
const std::string &deflt, const char *m,
std::vector<std::string> vals, std::vector<std::string> dvals,
bool canEdit)
: presets_element_selectable(WIDGET_TYPE_COMBO, k, txt, deflt, m, std::move(vals), std::move(dvals), canEdit)
{
}
presets_element_multiselect::presets_element_multiselect(const std::string &k, const std::string &txt,
const std::string &deflt, const char *m, char del,
std::vector<std::string> vals,
std::vector<std::string> dvals, unsigned int rws)
: presets_element_selectable(WIDGET_TYPE_MULTISELECT, k, txt, deflt, m, std::move(vals), std::move(dvals), false)
, delimiter(del)
#ifndef FREMANTLE
, rows_height(rws == 0 ? std::min(8, static_cast<int>(values.size())) : rws)
#endif
{
#ifdef FREMANTLE
(void)rws;
#endif
}
presets_element_list_entry_chunks::presets_element_list_entry_chunks()
: presets_element_selectable(WIDGET_TYPE_CHUNK_LIST_ENTRIES, std::string(), std::string(),
std::string(), nullptr, std::vector<std::string>(), std::vector<std::string>(), false)
{
}
presets_element_role_entry_chunks::presets_element_role_entry_chunks()
: presets_element_selectable(WIDGET_TYPE_CHUNK_ROLE_ENTRIES, std::string(), std::string(),
std::string(), nullptr, std::vector<std::string>(), std::vector<std::string>(), false)
{
}
presets_element_key::presets_element_key(const std::string &k, const std::string &val,
const char *m)
: presets_element_t(WIDGET_TYPE_KEY, parseMatch(m, MatchKeyValue_Force), k)
, value(val)
{
}
presets_element_checkbox::presets_element_checkbox(const std::string &k, const std::string &txt,
bool deflt, const char *m, const std::string &von)
: presets_element_t(WIDGET_TYPE_CHECK, parseMatch(m), k, txt)
, def(deflt)
, value_on(von)
{
}
bool presets_element_reference::is_interactive() const
{
return std::any_of(item->widgets.begin(), item->widgets.end(), presets_element_t::isInteractive);
}
unsigned int presets_element_reference::rows() const
{
return std::accumulate(item->widgets.begin(), item->widgets.end(), 0, widget_rows);
}
presets_item::~presets_item()
{
std::for_each(widgets.begin(), widgets.end(), std::default_delete<presets_element_t>());
}
presets_item_group::presets_item_group(const unsigned int types, presets_item_group *p,
const std::string &n, const std::string &ic)
: presets_item_named(types | TY_GROUP, n, ic), parent(p)
{
assert(p == nullptr || ((p->type & TY_GROUP) != 0));
}
presets_item_group::~presets_item_group()
{
std::for_each(items.begin(), items.end(), std::default_delete<presets_item_t>());
}
presets_items_internal::presets_items_internal()
: presets_items()
{
lru.reserve(LRU_MAX);
}
presets_items_internal::~presets_items_internal()
{
std::for_each(items.begin(), items.end(), std::default_delete<presets_item_t>());
std::for_each(chunks.begin(), chunks.end(), std::default_delete<presets_item_t>());
}
|
#include "conn_check.h"
#include "System_config.h"
#ifndef CONN_REFRESH_VALUE
#define CONN_REFRESH_VALUE 60
#endif
//static UI counters[PROTO_MAX_ID + 1];
void ProtoConnCheck::update_counters(void)
{
// for( UI i = 0; i <= PROTO_MAX_ID; i++)
// {
// if (counters[i])
// counters[i]--;
// }
}
bool ProtoConnCheck::is_good_conn(protocol_id_t proto_id)
{
// if (((proto_id <= PROTO_MAX_ID) && (counters[proto_id])) || (OWN_PROTOCOL_ID == proto_id))
// return true;
// else
// return false;
return true;
}
void ProtoConnCheck::reset_counter(protocol_id_t proto_id)
{
// if (proto_id <= PROTO_MAX_ID)
// {
// counters[proto_id] = CONN_REFRESH_VALUE;
// }
}
|
#include "graphics\Singularity.Graphics.h"
namespace Singularity
{
namespace Graphics
{
class OctTreeRenderIterator : public Singularity::Graphics::IRenderIterator
{
private:
#pragma region Variables
OctTreeRenderGraph* m_pGraph;
OctTreeRenderGraph::OctNode* m_pStart;
#pragma endregion
#pragma region Constructors and Finalizers
OctTreeRenderIterator(OctTreeRenderGraph* graph, OctTreeRenderGraph::OctNode* node);
~OctTreeRenderIterator() { }
#pragma endregion
public:
#pragma region Methods
const unsigned Get_Size() const;
Renderer* Get_Renderer() const;
#pragma endregion
#pragma region Methods
void Reset();
Renderer* Next();
IRenderIterator& Split(int count = -1);
#pragma endregion
friend class OctTreeRenderGraph;
};
}
}
|
//
// Created by roundedglint585 on 10/4/19.
//
#define STB_IMAGE_IMPLEMENTATION
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "include/Fractal.h"
constexpr uint32_t width = 800;
constexpr uint32_t height = 600;
int main() {
Fractal fractal(width, height);
fractal.init();
fractal.run();
return 0;
}
|
//auto create by tocpp.rb, plz don't modify it!
//2013-10-23 14:19:45 +0800
#include "TemplateHero.h"
using std::string;
TemplateHero::TemplateHero()
{
m_sn = 0;
m_LevelUpIncAttack = 0;
m_LevelUpIncDefence = 0;
m_LevelUpIncHP = 0;
m_LevelUpIncEnergy = 0;
}
bool TemplateHero::ReadJsonImpl(const CSJson::Value& obj)
{
//
getJsonVal(obj["sn"], m_sn);
//引用的兵种模版
getJsonVal(obj["Arm"], m_Arm);
//英雄的品质
getJsonVal(obj["Quality"], (int&)m_Quality);
//升级后提升攻击
getJsonVal(obj["LevelUpIncAttack"], m_LevelUpIncAttack);
//升级后提升防御
getJsonVal(obj["LevelUpIncDefence"], m_LevelUpIncDefence);
//升级后提升HP
getJsonVal(obj["LevelUpIncHP"], m_LevelUpIncHP);
//升级后提升能量
getJsonVal(obj["LevelUpIncEnergy"], m_LevelUpIncEnergy);
return true;
}
|
#pragma once
#include "vector3.h"
class Ray
{
public:
Ray();
Ray(const Vector3& inOrigin, const Vector3& inDirection);
const Vector3& GetOrigin() const { return origin; }
const Vector3& GetDirection() const { return direction; }
Vector3 PointAt(float t) const;
public:
Vector3 origin;
Vector3 direction;
};
|
#include "Login.hpp"
Login::Login(std::string cor,std::string contra){
correo = cor;
contrasena = contra;
}
Login::Login(std::string* jsonLogin){
Json::Reader readerJson;
Json::Value login;
if(!readerJson.parse(*jsonLogin,login)) // Se verifica que se realice correctamente la conversion
{
std::cout << "Error en la conversión de documento Json a Objeto Json\n"
<< readerJson.getFormattedErrorMessages();
}else{
correo = login.get("correo", "Not Found" ).asString(); //id del atacado
contrasena = login.get("contrasena", "Not Found" ).asString(); ;//id del atacante
}
}
std::string Login::confirmarConexion(std::string* jsonLogin){
Json::Reader readerJson;
Json::Value logi;
Json::Value datos;
std::string error;
std::string dataUsuario;
Json::FastWriter writer;
if(!readerJson.parse(*jsonLogin,logi)) // Se verifica que se realice correctamente la conversion
{
std::cout << "Error en la conversión de documento Json a Objeto Json\n"
<< readerJson.getFormattedErrorMessages();
}else{
error = logi.get("error", "Not_Found" ).asString();
if(error == "Not_Found")
{
datos = logi.get("response", "Not Found");
dataUsuario = writer.write(datos);
return dataUsuario;
}
}
return "NULL";
}
std::string Login::getLoginJson(){
Json::Value login; // Objeto que almacena la estructura Json
Json::FastWriter writer; //Conversor de Objeto Json a String Json
// En el objeto json se crean campos "clave":"valor"
login["correo"] = correo;
login["contrasena"] = contrasena;
// Se convierte el Objeto Json a formato String
return writer.write(login);
}
std::string Login::getCorreo(){
return correo;
}
std::string Login::getContrasena(){
return contrasena;
}
|
// Copyright ⓒ 2020 Valentyn Bondarenko. All rights reserved.
#include <StdAfx.hpp>
#include <Sound2D.hpp>
#include <FileSystem.hpp>
#include <Log.hpp>
namespace be::sound
{
}
|
#include <stdio.h>
#include <deque>
#include <iostream>
using namespace std;
typedef unsigned long long int ulld;
ulld max(ulld a, ulld b)
{
if (a > b)
{
return a;
}
return b;
}
int main(int argc, char const *argv[])
{
ulld noInputs;
ulld maximumSum;
scanf("%lld", &noInputs);
scanf("%lld", &maximumSum);
deque<ulld> dq;
ulld currentNumber = 0;
ulld maximumPossibleSum = 0;
ulld currentDqSum = 0;
ulld tempSum = 0;
bool bestAchieved = false;
for (ulld i = 0 ; i < noInputs ; i++)
{
scanf("%lld", ¤tNumber);
tempSum = currentDqSum + currentNumber;
if (tempSum == maximumSum)
{
printf("%lld\n", maximumSum);
bestAchieved = true;
break;
}
else if (tempSum < maximumSum)
{
// cout << "Adding: " << currentNumber << endl;
currentDqSum += currentNumber;
dq.push_back(currentNumber);
}
else
{
maximumPossibleSum = max(maximumPossibleSum, currentDqSum);
while (!dq.empty() && currentDqSum + currentNumber > maximumSum)
{
ulld frontNum = dq.front();
// cout << "Removing: " << frontNum << endl;
currentDqSum -= frontNum;
dq.pop_front();
}
// cout << "Adding: " << currentNumber << endl;
currentDqSum += currentNumber;
dq.push_back(currentNumber);
}
}
if (!bestAchieved)
{
printf("%lld\n", max(currentDqSum, maximumPossibleSum));
}
}
|
#include "bonus_tiempo.h"
#include "../../recursos.h"
using namespace App_Juego_ObjetoJuego;
using namespace App_Graficos;
using namespace App;
const float Bonus_tiempo::CANTIDAD_TIEMPO_DEFECTO=10.0f;
Bonus_tiempo::Bonus_tiempo(float x, float y, float t):
Objeto_juego_I(),
Actor(x, y, W, H),
tiempo(t)
{
}
unsigned short int Bonus_tiempo::obtener_profundidad_ordenacion()const
{
return 10;
}
unsigned int Bonus_tiempo::obtener_ciclos_representable()const
{
return 1;
}
void Bonus_tiempo::transformar_bloque(App_Graficos::Bloque_transformacion_representable &b)const
{
using namespace App_Definiciones;
const auto& f=b.obtener_frame(animaciones::sprites, animaciones_sprites::bonus_tiempo, 0);
b.establecer_tipo(Bloque_transformacion_representable::tipos::tr_bitmap);
b.establecer_alpha(255);
b.establecer_recurso(Recursos_graficos::rt_juego);
b.establecer_recorte(f.x, f.y, f.w, f.h);
b.establecer_posicion(acc_espaciable_x()+f.desp_x, acc_espaciable_y()+f.desp_y, W, H);
}
void Bonus_tiempo::efecto_colision(App_Interfaces::Efecto_colision_recogedor_I& ec)
{
ec.sumar_tiempo(tiempo);
mut_borrar(true);
using namespace App_Audio;
insertar_reproducir(Info_audio_reproducir(
Info_audio_reproducir::t_reproduccion::simple,
Info_audio_reproducir::t_sonido::repetible,
App::Recursos_audio::rs_recoger_bonus, 127, 127));
}
void Bonus_tiempo::generar_objetos(App_Interfaces::Factoria_objetos_juego_I& f)
{
if(es_borrar())
{
f.fabricar_fantasma_bonus_tiempo(acc_espaciable_x(), acc_espaciable_y(), 0.8f, 10);
}
}
|
#include "definiciones.h"
#include <stdexcept>
using namespace App_Definiciones;
App_Definiciones::direcciones App_Definiciones::obtener_direccion_contraria(App_Definiciones::direcciones s)
{
switch(s)
{
case App_Definiciones::direcciones::arriba: return App_Definiciones::direcciones::abajo; break;
case App_Definiciones::direcciones::abajo: return App_Definiciones::direcciones::arriba; break;
case App_Definiciones::direcciones::derecha: return App_Definiciones::direcciones::izquierda; break;
case App_Definiciones::direcciones::izquierda: return App_Definiciones::direcciones::derecha; break;
default: return App_Definiciones::direcciones::nada; break;
}
}
App_Definiciones::direcciones App_Definiciones::operator|(App_Definiciones::direcciones a, App_Definiciones::direcciones b)
{
return static_cast<App_Definiciones::direcciones>(static_cast<int>(a) | static_cast<int>(b));
}
App_Definiciones::direcciones App_Definiciones::operator&(App_Definiciones::direcciones a, App_Definiciones::direcciones b)
{
return static_cast<App_Definiciones::direcciones>(static_cast<int>(a) & static_cast<int>(b));
}
bool App_Definiciones::es_direccion_pura(App_Definiciones::direcciones dir)
{
switch(dir)
{
case App_Definiciones::direcciones::arriba:
case App_Definiciones::direcciones::abajo:
case App_Definiciones::direcciones::derecha:
case App_Definiciones::direcciones::izquierda:
return true;
break;
case App_Definiciones::direcciones::nada:
default:
return false;
break;
}
}
App_Definiciones::direcciones App_Definiciones::convertir_en_direccion(int v)
{
if(v < 0 && v > 15)
/* (direcciones::arriba |
direcciones::derecha |
direcciones::abajo |
direcciones::izquierda))*/
{
throw std::runtime_error("Casting inválido de enter a App_Definiciones::direcciones");
}
return static_cast<App_Definiciones::direcciones>(v);
/*
switch(v)
{
case 1: return direcciones::arriba; break;
case 2: return direcciones::derecha; break;
case 4: return direcciones::abajo; break;
case 8: return direcciones::izquierda; break;
default: return direcciones::nada; break;
}
*/
}
|
#pragma once
#include "CIL/mat/mat.h"
namespace cil {
enum RotateFlags {
ROTATE_90_CLOCKWISE = 0, // Rotate 90 degrees clockwise
ROTATE_180 = 1, // Rotate 180 degrees clockwise
ROTATE_90_COUNTERCLOCKWISE = 2, // Rotate 270 degrees clockwise
};
void flip(InputArray _src, OutputArray _dst, int flip_mode);
void transpose(InputArray _src, OutputArray _dst);
void rotate(InputArray _src, OutputArray _dst, int rotateMode);
}
|
#include "containers.h"
#include "csvstream.h"
#include <iostream>
#include <algorithm>
#include <iterator>
/**
* @brief Display the content of a map
*
* @param st_count: Reference to map with key-> states, value-> count
*/
void Display_by_State(std::map<std::string, int> &st_count)
{
int total = 0;
// Iterate over the map using c++11 range based for loop
for (std::pair<std::string, int> element : st_count)
{
// std::cout << element.first << " :: " << element.second << std::endl;
// Or more explicitly
// Accessing KEY from element
std::string word = element.first;
// Accessing VALUE from element.
int count = element.second;
std::cout << word << " :: " << count << std::endl;
total += count;
}
std::cout << "A total of "<< total << " records for all states" << std::endl;
}
void Load_Data(std::vector<Data> &data, const std::string &input_file)
{
csvstream csvinput(input_file);
std::map<std::string, std::string> row;
Data temp;
while (csvinput >> row)
{
// The key is the column name
// std::cout << row["id"] << "," << row["name"] //TODO: unfinished
// << "," << row["animal"] << std::endl;
temp.id = row["id"];
temp.gender = row["gender"];
temp.school = row["school"];
temp.state = row["state"];
data.push_back(temp); //load Data struct into vector
}
}
|
#include <irtkImage.h>
#include <irtkMatrix.h>
char *input_name = NULL;
char *output_name = NULL;
void usage(){
cout << "csv2mat [csvFile] [rows] [cols] [outputFile.mat]" << endl;
cout << "csv file must be space separated." << endl;
exit(1);
}
int main(int argc, char **argv){
if (argc < 5){
usage();
}
int i, j, rows, cols;
input_name = argv[1];
argc--;
argv++;
rows = atoi(argv[1]);
argc--;
argv++;
cols = atoi(argv[1]);
argc--;
argv++;
output_name = argv[1];
argc--;
argv++;
irtkMatrix m;
m.Initialize(rows, cols);
ifstream in(input_name);
for (i = 0; i < rows; i++){
for (j = 0; j < cols; j++){
in >> m(i, j);
}
}
m.Print();
m.Write(output_name);
}
|
//
// Created by hw730 on 2020/6/8.
//
#ifndef DEFENCE_GAME_MONSTER_H
#define DEFENCE_GAME_MONSTER_H
#include "Position.h"
class Monster {
static int geneId(){static int id = 0;id++;return id;}
public:
//constructor
Monster():
id(geneId())
{}
//getters
int getHP(){return HP;}
int getSpeed(){return speed;}
int getMoney(){return money;}
Position& getPos(){return pos;}
int getId(){return id;}
int getDamage(){return damage;}
//setters
void setHP(int k){HP = k;}
void setSpeed(int k){speed = k;}
void setMoney(int k){money = k;}
void setDamage(int k){damage = k;}
void setPosition(int x,int y){pos = Position(x,y);}
private:
int HP;
int speed;
int money;
int damage;
const int id;
Position pos;
};
#endif //DEFENCE_GAME_MONSTER_H
|
#ifndef ARR_ASSIGN_I_H
#define ARR_ASSIGN_I_H
#include "instruction.h"
#include "varregister.h"
#include "arrayregister.h"
#include "../visitors/codevisitor.h"
#include <string>
using namespace std;
/**
* An array assignment assigns a value to a slot of an array
*/
class ArrayAssignmentI: public Instruction {
public:
ArrayAssignmentI(ArrayRegister* array,VarRegister* index,VarRegister* value);
~ArrayAssignmentI();
string toString() const;
//accessors
ArrayRegister* getArrayRegister() const { return array_; }
VarRegister* getIndex() const { return index_; }
VarRegister* getValue() const { return value_; }
//mutators
void setArrayRegister(ArrayRegister* array) {
delete array_;
array_ = array;
}
void setIndex(VarRegister* index) {
delete index_;
index_ = index;
}
void setValue(VarRegister* value) {
delete index_;
value_ = value;
}
void accept(CodeVisitor* v) {
Instruction::accept(v);
v->visitArrayAssInstruction(this);
}
private:
ArrayRegister* array_;
VarRegister* index_;
VarRegister* value_;
};
#endif
|
class point{
public:
float m;
vect c,s,a;
vect ff;
point(){
m = 1.0f;
}
void force(vect af){
a += af/m;
}
void frict(vect aff){
ff += aff;
}
vect frict(){
if(ff*ff==0.0f){return ff;}//to avoid division by zero
float afv = sqrt(ff*ff);
vect an = ff/afv;
vect ls = s - (s*an)*an;
float lsv;
vect lsd;
if(ls*ls!=0.0f){//analogically
lsv = sqrt(ls*ls);
lsd = ls/lsv;
}
if(lsv*m>=afv*sec){
a -= lsd*afv/m;
return lsd*afv;
}
vect lf = a*m - ((a*m)*an)*an;
float lfv = sqrt((lf+ls*m/sec)*(lf+ls*m/sec));
vect lfd;
if(lfv!=0.0f){
lfd = (lf+ls*m/sec)/lfv;//analogically
}
if(lfv>=afv){
a -= lfd*afv/m;
return lfd*afv;
}
a -= ls/sec + lf/m;
return ls*m/sec + lf;
}
void step(){
frict();
ff.nul();
s += a*sec;
c += s*sec;
a.nul();
}
};
class vertex{
public:
vect c,s,f;
float ff;
void force(vect af){
f += af;
}
void frict(float aff){
ff += aff;
}
vect frict(){
return -ff*s;
}
void clean(){
f.nul();
ff = 0.0f;
}
};
class ori{
public:
vect f,t,r;//front/top/right directions
vect s,a;//speed and axis of rotation/acceleration of rotation and axis of acceleration
vect j;//moments of inertions/next on front/top/side directions
ori(){
j.set(1.0f,1.0f,1.0f);
}
void step(){
s += a*sec;
//getting axis and angle from superposition of them
vect ax = s*sec;
float an = sqrt(ax*ax);
ax = ax/an;
f = rotate(f,an,ax);
t = rotate(t,an,ax);
r = f^t;
a.nul();
}
void force(vect aforce, vect aarm){//force and arm
vect lfm = aarm^aforce; //force moment
moment(lfm);
}
void moment(vect lfm){
if(lfm*lfm==0.0f){return;}//to avoid division by zero
vect lax(lfm*r,lfm*f,lfm*t);//moment in local coordinates
a += lfm*(lax*lax/(lax.x*j.x*lax.x + lax.y*j.y*lax.y + lax.z*j.z*lax.z));//force moment / computed inertia moment
}
};
float ressor_directed_hardness = 1.0f,
ressor_directed_amortization = 1.0f,
ressor_deviated_hardness = 16.0f,
ressor_deviated_amortization = 0.98f,
ressor_oversize_linear_hardness = 8.0f,
ressor_oversize_quadratic_hardness = 16.0f,
ressor_oversize_amortization = 0.96f;
class ressor{
public:
vect dir;//direction
vertex * fv;//fix vertex
point * cv;//control vertex
float bal,mln,har,amr;//balance length, maximal length, hardness, amortization coefficient
ressor(){
fv = NULL;
cv = NULL;
}
void interact(){
if(fv!=NULL&&cv!=NULL){
vect dist = cv->c-fv->c;
vect luft = dist-(dist*dir)*dir;
float dev = dist*dir;
vect spd = cv->s-fv->s;
vect drs = spd*dir*dir;
vect dvs = spd - drs;
vect frc = ressor_directed_hardness*har*(dev-bal)*dir
+ har*ressor_deviated_hardness*luft;
if(dev<0.0f){
frc += ressor_oversize_linear_hardness*har*(dev-0.0f)*dir
- ressor_oversize_quadratic_hardness*har*(0.0f-dev)*(0.0f-dev)*dir;
}
if(dev>mln){
frc += ressor_oversize_linear_hardness*har*(dev-mln)*dir
+ ressor_oversize_quadratic_hardness*har*(dev-mln)*(dev-mln)*dir;
}
fv->force(frc);
cv->force(-frc);
}
}
void amortize(){
if(fv!=NULL&&cv!=NULL){
vect dist = cv->c-fv->c;
vect luft = dist-(dist*dir)*dir;
float dev = dist*dir;
vect spd = cv->s-fv->s;
vect drs = spd*dir*dir;
vect dvs = spd - drs;
float fir = cv->m/sec;
vect frc = ressor_directed_amortization*amr*drs*fir
+ ressor_deviated_amortization*dvs*fir;
if(dev<0.0f){
frc += ressor_oversize_amortization*drs;
}
if(dev>mln){
frc += ressor_oversize_amortization*drs;
}
fv->force(frc);
cv->force(-frc);
}
}
};
class wheel{
public:
point c;//point of a wheel
vect nor,top;//normal to wheel plane, top of wheel
float p,s,a,in;//angular position, speed, acceleration, inertia moment
float wf,lf,kf;//wheel dry/liquid friction/ koeff of friction of a rubber
bool st;//stop wheel rotating
float rad,hvd,thc;
vect ff;
void force(vect af){
c.force(af);
}
void frict(vect aff){
ff += aff*kf;
}
void frict(){
if(ff*ff==0.0f){return;}//to avoid division by zero
float afv = sqrt(ff*ff);
vect an = ff/afv;
vect ss = c.s + ((s*nor)^(an*rad));
vect ls = ss - (ss*an)*an;
float lsv;
vect lsd;
if(ls*ls!=0.0f){//analogically
lsv = sqrt(ls*ls);
lsd = ls/lsv;
}
if(lsv*c.m>=afv*sec){
c.a -= lsd*afv/c.m;
a += nor*(((lsd*afv)^(an*rad))/in);
return;
}
vect lf = c.a*c.m - ((c.a*c.m)*an)*an;
float lfv = sqrt((lf+ls*c.m/sec)*(lf+ls*c.m/sec));
vect lfd;
if(lfv!=0.0f){
lfd = (lf+ls*c.m/sec)/lfv;//analogically
}
if(lfv>=afv){
c.a -= lfd*afv/c.m;
a += nor*(((lfd*afv)^(an*rad))/in);
return;
}
c.a -= ls/sec + lf/c.m;
a += nor*(((ls*c.m/sec+lf)^(an*rad))/in);
return;
}
void step(){
float fd,fv;//force direction/ force value
if(s/sec+a>=0.0f){fd = 1.0f; fv = s/sec+a;}
else{fd = -1.0f; fv = -s/sec-a;}
if(fv > wf/in){a -= fd*wf/in;}
else{a -= a + s/sec;}
frict();
ff.nul();
c.step();
if(st){a -= a + s/sec;}
s += a*sec;
p += s*sec;
a = 0.0f;
}
};
class solid{
public:
point c;//center of a mass
ori o;//orientation
vertex * v, * bv;//vertexes of solid body/builded coords of vertexes/next I need to add polygons here
unsigned int nv;//in v orientation x - left, y - front, z - top sides
solid(){
nv = 0;
}
void build(){
for(unsigned int i=0;i<nv;i++){
bv[i].c = v[i].c.x*o.r + v[i].c.y*o.f + v[i].c.z*o.t + c.c;
bv[i].s = c.s + (o.s^(bv[i].c-c.c));
}
}
void frict(){
vect sfr,smr;//summary force and moment resistance
for(unsigned int i=0;i<nv;i++){
vect tfr = bv[i].frict();
sfr += tfr;
smr += (bv[i].c-c.c)^tfr;
}
c.force(sfr);
o.moment(smr);
}
void step(){
for(unsigned int i=0;i<nv;i++){
c.force(bv[i].f);
o.force(bv[i].f,bv[i].c-c.c);//force and arm
}
//frict();
for(unsigned int i=0;i<nv;i++){
bv[i].clean();
}
c.step();
o.step();
build();
}
};
|
/*
* Author : BurningTiles
* Problem : Death Battle
* File : F.cpp
*/
#include <iostream>
#include <cmath>
#define ll long long
using namespace std;
ll gcd(ll a, ll b){
return (b==0)? a : gcd(b, a%b);
}
ll fact(ll x){
return (x<2)? 1 : x*fact(x-1);
}
ll nCr(ll n, ll r){
return fact(n)/(fact(n-r)*fact(r));
}
int main(){
ll tt, A, H, L1, L2, M, C, temp, k, z, temp1, div;
cin >> tt;
while(tt--){
cin >> A >> H >> L1 >> L2 >> M >> C;
temp = 0;
div = pow(L2,M);
if(M*(A+C) < H){
cout << "RIP" << endl;
continue;
}
k=0; z=M*A;
while(z<H){
z += C;
++k;
}
for(int i=k; i<=M; ++i){
if(i==0) temp += pow(L2-L1,M);
else if(i==M) temp += pow(L1,i);
else temp += pow(L1,i)*pow(L2-L1,M-i)*nCr(M,i);
}
temp1 = gcd(temp,div);
cout << (temp/temp1) << '/' << (div/temp1);
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
int fibonacci(int x){
if(x <= 1)
return x;
else
return (fibonacci(x-1)+fibonacci(x-2));
}
int main()
{
int x;
cin >> x;
x = fibonacci(x);
cout << x << endl;
}
|
// This file has been generated by Py++.
#ifndef GUIContextRenderTargetEventArgs_hpp__pyplusplus_wrapper
#define GUIContextRenderTargetEventArgs_hpp__pyplusplus_wrapper
void register_GUIContextRenderTargetEventArgs_class();
#endif//GUIContextRenderTargetEventArgs_hpp__pyplusplus_wrapper
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
// This program was prepared by the Regents of the University of California
// at Los Alamos National Laboratory (the University) under Contract No.
// W-7405-ENG-36 with the U.S. Department of Energy (DOE). The University has
// certain rights in the program pursuant to the contract and the program
// should not be copied or distributed outside your organization. All rights
// in the program are reserved by the DOE and the University. Neither the U.S.
// Government nor the University makes any warranty, express or implied, or
// assumes any liability or responsibility for the use of this software
//-----------------------------------------------------------------------------
// Class:
// IterateScheduler<SerialAsync>
// Iterate<SerialAsync>
// DataObject<SerialAsync>
//-----------------------------------------------------------------------------
/*
LIBRARY:
SerialAsync
CLASSES: IterateScheduler
CLASSES: DataObject
CLASSES: Iterate
OVERVIEW
SerialAsync IterateScheduler is a policy template to create a
dependence graphs and executes the graph respecting the
dependencies without using threads. There is no parallelism,
but Iterates may be executed out-of-order with respect to the
program text.
-----------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// Overview:
// Smarts classes for times when you want no threads but you do want
// dataflow evaluation.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Typedefs:
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes:
//-----------------------------------------------------------------------------
#include "Threads/IterateSchedulers/SerialAsync.h"
namespace Smarts {
std::list<RunnablePtr_t> SystemContext::workQueueMessages_m;
std::list<RunnablePtr_t> SystemContext::workQueue_m;
#if POOMA_MPI
const int SystemContext::max_requests;
MPI_Request SystemContext::requests_m[SystemContext::max_requests];
std::map<int, SystemContext::IteratePtr_t> SystemContext::allocated_requests_m;
std::set<int> SystemContext::free_requests_m;
#endif
std::stack<int> IterateScheduler<SerialAsync>::generationStack_m;
}
//////////////////////////////////////////////////////////////////////
/***************************************************************************
* $RCSfile: SerialAsync.cmpl.cpp,v $ $Author: richard $
* $Revision: 1.5 $ $Date: 2004/11/01 18:17:08 $
***************************************************************************/
|
#pragma once
#include "EventLoopThreadPool.h"
#include "Acceptor.h"
#include "Buffer.h"
#include "EventLoop.h"
START_NAMESPACE
class Connection;
class TcpServer {
public:
using MessageCallback = std::function<void(std::shared_ptr<Connection>, Buffer&)>;
using ConnectionCallback = std::function<void(std::shared_ptr<Connection>)>;
using CloseCallback = std::function<void(std::shared_ptr<Connection>)>;
using WriteFinishCallback = std::function<void(std::shared_ptr<Connection>)>;
using ConnectionMaps = std::unordered_map<int, std::shared_ptr<Connection>>;
TcpServer(uint16_t port, int workThread);
void setMessageCallback(const MessageCallback& func) { messageCallback_ = func; }
void setConnectionCallback(const ConnectionCallback& func) { connectionCallback_ = func; }
void setCloseCallback(const CloseCallback& func) { closeCallback_ = func; }
void setWriteFinishCallback(const WriteFinishCallback& func) { writeFinishCallback_ = func; }
void start();
private:
void onAccept(int conn);
void onClose(std::shared_ptr<Connection> conn);
void onWriteFinish(std::shared_ptr<Connection> conn);
EventLoop mainLoop_;
Acceptor acceptor_;
EventLoopThreadPool threadPool_;
MessageCallback messageCallback_;
ConnectionCallback connectionCallback_;
CloseCallback closeCallback_;
WriteFinishCallback writeFinishCallback_;
ConnectionMaps connections_;
};
END_NAMESPACE
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Devices.Geolocation.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::Devices::Geolocation {
struct WINRT_EBO CivicAddress :
Windows::Devices::Geolocation::ICivicAddress
{
CivicAddress(std::nullptr_t) noexcept {}
};
struct WINRT_EBO GeoboundingBox :
Windows::Devices::Geolocation::IGeoboundingBox
{
GeoboundingBox(std::nullptr_t) noexcept {}
GeoboundingBox(const Windows::Devices::Geolocation::BasicGeoposition & northwestCorner, const Windows::Devices::Geolocation::BasicGeoposition & southeastCorner);
GeoboundingBox(const Windows::Devices::Geolocation::BasicGeoposition & northwestCorner, const Windows::Devices::Geolocation::BasicGeoposition & southeastCorner, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeReferenceSystem);
GeoboundingBox(const Windows::Devices::Geolocation::BasicGeoposition & northwestCorner, const Windows::Devices::Geolocation::BasicGeoposition & southeastCorner, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeReferenceSystem, uint32_t spatialReferenceId);
static Windows::Devices::Geolocation::GeoboundingBox TryCompute(iterable<Windows::Devices::Geolocation::BasicGeoposition> positions);
static Windows::Devices::Geolocation::GeoboundingBox TryCompute(iterable<Windows::Devices::Geolocation::BasicGeoposition> positions, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeRefSystem);
static Windows::Devices::Geolocation::GeoboundingBox TryCompute(iterable<Windows::Devices::Geolocation::BasicGeoposition> positions, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeRefSystem, uint32_t spatialReferenceId);
};
struct WINRT_EBO Geocircle :
Windows::Devices::Geolocation::IGeocircle
{
Geocircle(std::nullptr_t) noexcept {}
Geocircle(const Windows::Devices::Geolocation::BasicGeoposition & position, double radius);
Geocircle(const Windows::Devices::Geolocation::BasicGeoposition & position, double radius, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeReferenceSystem);
Geocircle(const Windows::Devices::Geolocation::BasicGeoposition & position, double radius, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeReferenceSystem, uint32_t spatialReferenceId);
};
struct WINRT_EBO Geocoordinate :
Windows::Devices::Geolocation::IGeocoordinate,
impl::require<Geocoordinate, Windows::Devices::Geolocation::IGeocoordinateWithPositionData, Windows::Devices::Geolocation::IGeocoordinateWithPoint, Windows::Devices::Geolocation::IGeocoordinateWithPositionSourceTimestamp>
{
Geocoordinate(std::nullptr_t) noexcept {}
};
struct WINRT_EBO GeocoordinateSatelliteData :
Windows::Devices::Geolocation::IGeocoordinateSatelliteData
{
GeocoordinateSatelliteData(std::nullptr_t) noexcept {}
};
struct WINRT_EBO Geolocator :
Windows::Devices::Geolocation::IGeolocator,
impl::require<Geolocator, Windows::Devices::Geolocation::IGeolocatorWithScalarAccuracy, Windows::Devices::Geolocation::IGeolocator2>
{
Geolocator(std::nullptr_t) noexcept {}
Geolocator();
static Windows::Foundation::IAsyncOperation<winrt::Windows::Devices::Geolocation::GeolocationAccessStatus> RequestAccessAsync();
static Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Geolocation::Geoposition>> GetGeopositionHistoryAsync(const Windows::Foundation::DateTime & startTime);
static Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Geolocation::Geoposition>> GetGeopositionHistoryAsync(const Windows::Foundation::DateTime & startTime, const Windows::Foundation::TimeSpan & duration);
static bool IsDefaultGeopositionRecommended();
static void DefaultGeoposition(const optional<Windows::Devices::Geolocation::BasicGeoposition> & value);
static Windows::Foundation::IReference<Windows::Devices::Geolocation::BasicGeoposition> DefaultGeoposition();
};
struct WINRT_EBO Geopath :
Windows::Devices::Geolocation::IGeopath
{
Geopath(std::nullptr_t) noexcept {}
Geopath(iterable<Windows::Devices::Geolocation::BasicGeoposition> positions);
Geopath(iterable<Windows::Devices::Geolocation::BasicGeoposition> positions, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeReferenceSystem);
Geopath(iterable<Windows::Devices::Geolocation::BasicGeoposition> positions, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeReferenceSystem, uint32_t spatialReferenceId);
};
struct WINRT_EBO Geopoint :
Windows::Devices::Geolocation::IGeopoint
{
Geopoint(std::nullptr_t) noexcept {}
Geopoint(const Windows::Devices::Geolocation::BasicGeoposition & position);
Geopoint(const Windows::Devices::Geolocation::BasicGeoposition & position, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeReferenceSystem);
Geopoint(const Windows::Devices::Geolocation::BasicGeoposition & position, Windows::Devices::Geolocation::AltitudeReferenceSystem altitudeReferenceSystem, uint32_t spatialReferenceId);
};
struct WINRT_EBO Geoposition :
Windows::Devices::Geolocation::IGeoposition,
impl::require<Geoposition, Windows::Devices::Geolocation::IGeoposition2>
{
Geoposition(std::nullptr_t) noexcept {}
};
struct WINRT_EBO PositionChangedEventArgs :
Windows::Devices::Geolocation::IPositionChangedEventArgs
{
PositionChangedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO StatusChangedEventArgs :
Windows::Devices::Geolocation::IStatusChangedEventArgs
{
StatusChangedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO VenueData :
Windows::Devices::Geolocation::IVenueData
{
VenueData(std::nullptr_t) noexcept {}
};
}
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Devices::Printers::Extensions {
struct IPrint3DWorkflow;
struct IPrint3DWorkflow2;
struct IPrint3DWorkflowPrintRequestedEventArgs;
struct IPrint3DWorkflowPrinterChangedEventArgs;
struct IPrintExtensionContextStatic;
struct IPrintNotificationEventDetails;
struct IPrintTaskConfiguration;
struct IPrintTaskConfigurationSaveRequest;
struct IPrintTaskConfigurationSaveRequestedDeferral;
struct IPrintTaskConfigurationSaveRequestedEventArgs;
struct Print3DWorkflow;
struct Print3DWorkflowPrintRequestedEventArgs;
struct Print3DWorkflowPrinterChangedEventArgs;
struct PrintNotificationEventDetails;
struct PrintTaskConfiguration;
struct PrintTaskConfigurationSaveRequest;
struct PrintTaskConfigurationSaveRequestedDeferral;
struct PrintTaskConfigurationSaveRequestedEventArgs;
}
namespace Windows::Devices::Printers::Extensions {
struct IPrint3DWorkflow;
struct IPrint3DWorkflow2;
struct IPrint3DWorkflowPrintRequestedEventArgs;
struct IPrint3DWorkflowPrinterChangedEventArgs;
struct IPrintExtensionContextStatic;
struct IPrintNotificationEventDetails;
struct IPrintTaskConfiguration;
struct IPrintTaskConfigurationSaveRequest;
struct IPrintTaskConfigurationSaveRequestedDeferral;
struct IPrintTaskConfigurationSaveRequestedEventArgs;
struct Print3DWorkflow;
struct Print3DWorkflowPrintRequestedEventArgs;
struct Print3DWorkflowPrinterChangedEventArgs;
struct PrintExtensionContext;
struct PrintNotificationEventDetails;
struct PrintTaskConfiguration;
struct PrintTaskConfigurationSaveRequest;
struct PrintTaskConfigurationSaveRequestedDeferral;
struct PrintTaskConfigurationSaveRequestedEventArgs;
}
namespace Windows::Devices::Printers::Extensions {
template <typename T> struct impl_IPrint3DWorkflow;
template <typename T> struct impl_IPrint3DWorkflow2;
template <typename T> struct impl_IPrint3DWorkflowPrintRequestedEventArgs;
template <typename T> struct impl_IPrint3DWorkflowPrinterChangedEventArgs;
template <typename T> struct impl_IPrintExtensionContextStatic;
template <typename T> struct impl_IPrintNotificationEventDetails;
template <typename T> struct impl_IPrintTaskConfiguration;
template <typename T> struct impl_IPrintTaskConfigurationSaveRequest;
template <typename T> struct impl_IPrintTaskConfigurationSaveRequestedDeferral;
template <typename T> struct impl_IPrintTaskConfigurationSaveRequestedEventArgs;
}
namespace Windows::Devices::Printers::Extensions {
enum class Print3DWorkflowDetail
{
Unknown = 0,
ModelExceedsPrintBed = 1,
UploadFailed = 2,
InvalidMaterialSelection = 3,
InvalidModel = 4,
ModelNotManifold = 5,
InvalidPrintTicket = 6,
};
enum class Print3DWorkflowStatus
{
Abandoned = 0,
Canceled = 1,
Failed = 2,
Slicing = 3,
Submitted = 4,
};
}
}
|
// alignas_alignof.cpp
// compile with: cl /EHsc alignas_alignof.cpp
#include <iostream>
struct alignas(16) Bar
{
int i; // 4 bytes
int n; // 4 bytes
alignas(4) char arr[3]; // This wull make sure that arr will stat at a 4 byte boundary
short s; // 2 bytes
};
struct alignas(4) Bar_2
{
int i; // 4 bytes
int n; // 4 bytes
alignas(4) char arr[3];
short s; // 2 bytes
};
struct alignas(4) Bar_3
{
int i; // 4 bytes
int n; // 4 bytes
alignas(4) char arr[3];
char s; // 1 byte
};
struct alignas(16) Bar_4
{
int i; // 4 bytes
int n; // 4 bytes
char arr[3]; // no allignment
short s; // 2 bytes
};
struct Bar_5
{
int i; // 4 bytes
int n; // 4 bytes
char arr[3]; // no allignment
short s; // 2 bytes
};
int main()
{
std::cout << " alignof(Bar) " << alignof(Bar) << " sizeof(Bar) " << sizeof(Bar) << std::endl; // output: 16 // because "struct alignas(16)" size should be a multiple of 16
std::cout << " alignof(Bar_2) " << alignof(Bar_2) << " sizeof(Bar_2) " << sizeof(Bar_2) << std::endl; // output: 16 // because "struct alignas(4)" size should be a multiple of 4
std::cout << " alignof(Bar_3) " << alignof(Bar_3) << " sizeof(Bar_3) " << sizeof(Bar_3) << std::endl; // output: 12 // because "struct alignas(4)" size should be a multiple of 4
std::cout << " alignof(Bar_4) " << alignof(Bar_4) << " sizeof(Bar_4) " << sizeof(Bar_4) << std::endl; // output: 16 // because "struct alignas(16)" size should be a multiple of 16
std::cout << " alignof(Bar_5) " << alignof(Bar_5) << " sizeof(Bar_5) " << sizeof(Bar_5) << std::endl; // output: 16 // because max variable size is 4 byte. Whole strucutre will be alignas(4)
}
|
#line 2 "Gen_hlslang.cpp"
#line 4 "Gen_hlslang.cpp"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
typedef uint64_t flex_uint64_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
extern yy_size_t yyleng;
extern FILE *yyin, *yyout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
yy_size_t yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static yy_size_t yy_n_chars; /* number of characters read into yy_ch_buf */
yy_size_t yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void yyrestart (FILE *input_file );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
void yy_delete_buffer (YY_BUFFER_STATE b );
void yy_flush_buffer (YY_BUFFER_STATE b );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
void yypop_buffer_state (void );
static void yyensure_buffer_stack (void );
static void yy_load_buffer_state (void );
static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len );
void *yyalloc (yy_size_t );
void *yyrealloc (void *,yy_size_t );
void yyfree (void * );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define yywrap(n) 1
#define YY_SKIP_YYWRAP
typedef unsigned char YY_CHAR;
FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
typedef int yy_state_type;
extern int yylineno;
int yylineno = 1;
extern char *yytext;
#define yytext_ptr yytext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
yyleng = (yy_size_t) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 189
#define YY_END_OF_BUFFER 190
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[487] =
{ 0,
0, 0, 0, 0, 190, 188, 187, 187, 171, 188,
177, 182, 166, 167, 175, 174, 163, 172, 170, 176,
137, 137, 164, 160, 178, 165, 179, 183, 129, 168,
169, 181, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 161, 180, 162, 173, 186, 189, 188, 185,
157, 0, 184, 143, 151, 146, 141, 149, 139, 150,
140, 132, 138, 0, 142, 131, 135, 136, 0, 133,
137, 0, 137, 158, 154, 156, 155, 159, 129, 147,
153, 129, 129, 129, 129, 129, 129, 129, 129, 7,
129, 129, 129, 129, 129, 129, 129, 129, 129, 10,
12, 129, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 129, 129, 148, 152, 185, 0, 132, 0,
1, 131, 0, 131, 135, 136, 0, 130, 134, 144,
145, 102, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 129, 129, 129, 129, 8, 129, 129, 129,
129, 17, 129, 129, 129, 129, 13, 129, 129, 129,
129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
0, 132, 0, 131, 130, 134, 22, 129, 126, 129,
129, 129, 129, 129, 129, 11, 105, 129, 129, 129,
129, 110, 56, 129, 129, 18, 69, 70, 71, 129,
120, 129, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 129, 129, 129, 129, 129, 108, 25, 129,
19, 129, 129, 129, 129, 129, 21, 129, 129, 23,
75, 76, 77, 5, 103, 2, 129, 129, 129, 129,
129, 26, 61, 15, 57, 58, 59, 60, 129, 14,
129, 129, 129, 129, 129, 129, 129, 129, 129, 121,
129, 129, 129, 129, 129, 129, 129, 129, 20, 72,
73, 74, 129, 104, 129, 128, 129, 129, 9, 129,
129, 129, 122, 117, 62, 63, 64, 65, 16, 66,
67, 68, 129, 129, 129, 113, 129, 79, 129, 129,
109, 116, 129, 28, 129, 125, 3, 24, 101, 111,
129, 129, 129, 129, 129, 78, 129, 129, 112, 27,
129, 129, 129, 129, 129, 129, 129, 38, 39, 40,
41, 42, 43, 44, 45, 46, 129, 129, 129, 129,
91, 129, 95, 106, 4, 129, 129, 6, 118, 47,
48, 49, 50, 51, 52, 53, 54, 55, 29, 30,
31, 32, 33, 34, 35, 36, 37, 129, 129, 114,
80, 129, 129, 129, 129, 129, 129, 107, 129, 129,
129, 129, 123, 115, 119, 127, 81, 83, 88, 129,
129, 129, 96, 97, 129, 129, 129, 129, 129, 129,
129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 92, 89, 129, 99, 98, 129, 129, 129,
129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
129, 124, 129, 129, 129, 100, 129, 85, 129, 129,
86, 129, 129, 129, 82, 84, 87, 129, 129, 129,
129, 93, 129, 94, 90, 0
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 4, 5, 1, 1, 6, 7, 1, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 21, 21, 22, 22, 23, 24, 25,
26, 27, 28, 1, 29, 30, 31, 32, 33, 34,
35, 36, 35, 35, 35, 37, 35, 35, 35, 35,
35, 38, 39, 40, 41, 35, 35, 42, 35, 35,
43, 1, 44, 45, 46, 1, 47, 48, 49, 50,
51, 52, 53, 54, 55, 35, 56, 57, 58, 59,
60, 61, 35, 62, 63, 64, 65, 66, 67, 68,
69, 70, 71, 72, 73, 74, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_int32_t yy_meta[75] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
2, 2, 1, 1, 1, 1, 1, 1, 2, 2,
2, 2, 2, 2, 3, 3, 3, 3, 3, 3,
3, 3, 1, 1, 1, 3, 2, 2, 2, 2,
2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
1, 1, 1, 1
} ;
static yyconst flex_int16_t yy_base[492] =
{ 0,
0, 0, 74, 0, 730, 731, 731, 731, 703, 723,
701, 142, 731, 731, 700, 139, 731, 138, 136, 151,
164, 154, 731, 731, 134, 699, 136, 731, 0, 731,
731, 143, 661, 127, 147, 148, 134, 170, 663, 675,
160, 661, 673, 132, 654, 148, 667, 179, 169, 181,
177, 663, 731, 183, 731, 731, 731, 731, 701, 0,
731, 710, 731, 731, 731, 731, 731, 731, 731, 731,
731, 240, 731, 711, 731, 279, 210, 320, 266, 731,
731, 0, 0, 687, 731, 731, 731, 686, 0, 731,
731, 653, 650, 658, 645, 660, 647, 653, 641, 638,
639, 636, 636, 642, 630, 637, 634, 631, 637, 0,
185, 634, 628, 633, 635, 625, 639, 639, 171, 628,
625, 614, 192, 628, 195, 627, 616, 619, 620, 209,
623, 628, 193, 621, 731, 731, 0, 303, 731, 672,
731, 0, 347, 731, 731, 731, 286, 362, 252, 731,
731, 0, 617, 626, 608, 608, 147, 623, 620, 620,
616, 608, 614, 601, 612, 615, 0, 601, 608, 604,
593, 369, 604, 594, 604, 595, 0, 597, 595, 596,
585, 588, 586, 596, 582, 215, 581, 583, 579, 579,
590, 589, 575, 258, 583, 578, 572, 585, 587, 576,
327, 383, 390, 405, 731, 731, 309, 576, 0, 568,
566, 574, 563, 580, 569, 0, 0, 563, 573, 573,
558, 0, 373, 562, 556, 0, 0, 0, 0, 557,
0, 563, 554, 559, 564, 559, 550, 550, 554, 546,
549, 553, 548, 557, 556, 547, 538, 0, 0, 552,
411, 541, 541, 546, 545, 537, 0, 532, 544, 0,
0, 0, 0, 0, 0, 0, 535, 536, 530, 540,
531, 0, 425, 429, 0, 521, 520, 519, 535, 0,
533, 516, 522, 527, 531, 531, 515, 519, 526, 0,
524, 526, 521, 509, 518, 524, 508, 518, 0, 0,
0, 0, 506, 0, 508, 0, 504, 510, 0, 499,
499, 512, 0, 514, 0, 492, 491, 490, 0, 489,
488, 487, 332, 414, 432, 0, 507, 0, 506, 493,
0, 0, 500, 0, 488, 0, 0, 0, 0, 0,
485, 497, 495, 488, 494, 0, 487, 492, 0, 0,
485, 435, 442, 445, 448, 451, 454, 0, 0, 0,
0, 0, 0, 0, 0, 0, 492, 491, 488, 476,
458, 486, 460, 0, 0, 486, 484, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 483, 482, 0,
0, 500, 499, 498, 488, 495, 464, 0, 494, 493,
483, 490, 0, 0, 0, 0, 483, 451, 483, 490,
488, 454, 0, 0, 487, 485, 461, 441, 448, 214,
450, 467, 459, 448, 461, 453, 445, 426, 440, 429,
438, 435, 437, 443, 417, 0, 0, 408, 409, 390,
378, 379, 354, 217, 361, 362, 337, 326, 334, 329,
323, 0, 316, 323, 315, 0, 292, 0, 288, 271,
0, 272, 254, 240, 0, 0, 0, 234, 213, 181,
150, 0, 123, 0, 0, 731, 504, 506, 508, 511,
165
} ;
static yyconst flex_int16_t yy_def[492] =
{ 0,
486, 1, 486, 3, 486, 486, 486, 486, 486, 487,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 21, 486, 486, 486, 486, 486, 486, 488, 486,
486, 486, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 486, 486, 486, 486, 486, 486, 486, 489,
486, 487, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 490, 486, 486, 21, 486, 486, 486,
486, 491, 22, 486, 486, 486, 486, 486, 488, 486,
486, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 486, 486, 489, 486, 486, 490,
486, 76, 486, 486, 486, 486, 486, 486, 491, 486,
486, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
486, 486, 486, 486, 486, 486, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
488, 488, 488, 488, 488, 0, 486, 486, 486, 486,
486
} ;
static yyconst flex_int16_t yy_nxt[806] =
{ 0,
6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 22, 22, 22,
22, 22, 23, 24, 25, 26, 27, 28, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 30, 31, 32, 29, 33, 34, 35, 36,
37, 38, 39, 40, 41, 29, 42, 43, 44, 45,
46, 47, 48, 49, 50, 51, 52, 29, 29, 29,
53, 54, 55, 56, 6, 57, 58, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 59, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 60, 60, 60, 60, 60, 60, 60, 60,
60, 60, 60, 60, 60, 60, 6, 6, 6, 60,
60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
60, 60, 60, 60, 6, 6, 6, 6, 65, 68,
70, 72, 72, 72, 72, 72, 72, 72, 84, 85,
73, 87, 88, 71, 69, 74, 149, 66, 90, 83,
83, 83, 83, 83, 83, 83, 75, 76, 114, 77,
77, 77, 77, 77, 77, 78, 93, 91, 94, 485,
101, 115, 102, 95, 117, 486, 79, 80, 98, 80,
81, 103, 99, 96, 81, 82, 97, 100, 135, 211,
212, 110, 118, 484, 79, 80, 104, 80, 111, 125,
81, 486, 126, 180, 105, 120, 106, 132, 81, 107,
127, 82, 121, 122, 181, 129, 133, 128, 185, 130,
483, 170, 123, 131, 171, 124, 145, 198, 172, 199,
145, 486, 188, 186, 136, 72, 72, 72, 72, 72,
72, 72, 189, 194, 482, 440, 145, 441, 463, 243,
464, 195, 138, 139, 145, 139, 147, 486, 147, 244,
481, 148, 148, 148, 148, 148, 148, 148, 206, 480,
138, 139, 206, 139, 142, 142, 142, 142, 142, 142,
142, 148, 148, 148, 148, 148, 148, 148, 206, 252,
479, 143, 144, 201, 144, 201, 206, 253, 202, 202,
202, 202, 202, 202, 202, 260, 261, 262, 263, 143,
144, 478, 144, 76, 477, 78, 78, 78, 78, 78,
78, 78, 202, 202, 202, 202, 202, 202, 202, 358,
359, 360, 79, 80, 476, 80, 146, 203, 475, 203,
146, 474, 204, 204, 204, 204, 204, 204, 204, 473,
79, 80, 472, 80, 471, 470, 146, 148, 148, 148,
148, 148, 148, 148, 146, 226, 227, 228, 229, 275,
276, 277, 278, 469, 468, 205, 467, 205, 202, 202,
202, 202, 202, 202, 202, 204, 204, 204, 204, 204,
204, 204, 466, 205, 465, 205, 139, 462, 139, 230,
204, 204, 204, 204, 204, 204, 204, 299, 300, 301,
302, 361, 362, 363, 139, 461, 139, 460, 144, 459,
144, 315, 316, 317, 318, 319, 320, 321, 322, 364,
365, 366, 380, 381, 382, 458, 144, 457, 144, 383,
384, 385, 386, 387, 388, 389, 390, 391, 392, 393,
394, 395, 396, 397, 402, 403, 404, 409, 410, 428,
456, 455, 454, 453, 452, 451, 450, 449, 405, 429,
411, 448, 447, 446, 445, 406, 430, 412, 444, 443,
442, 439, 438, 407, 62, 62, 62, 89, 89, 137,
137, 140, 140, 140, 437, 436, 435, 434, 433, 432,
431, 427, 426, 425, 424, 423, 422, 421, 420, 419,
418, 417, 416, 415, 414, 413, 408, 401, 400, 399,
398, 379, 378, 377, 376, 375, 374, 373, 372, 371,
370, 369, 368, 367, 357, 356, 355, 354, 353, 352,
351, 350, 349, 348, 347, 346, 345, 344, 343, 342,
341, 340, 339, 338, 337, 336, 335, 334, 333, 332,
331, 330, 329, 328, 327, 326, 325, 324, 323, 314,
313, 312, 311, 310, 309, 308, 307, 306, 305, 304,
303, 298, 297, 296, 295, 294, 293, 292, 291, 290,
289, 288, 287, 286, 285, 284, 283, 282, 281, 280,
279, 274, 273, 272, 271, 270, 269, 268, 267, 266,
265, 264, 259, 258, 257, 256, 255, 254, 251, 250,
249, 248, 247, 246, 245, 242, 241, 240, 239, 238,
237, 236, 235, 234, 233, 232, 231, 225, 224, 223,
222, 221, 220, 219, 218, 217, 216, 215, 214, 213,
210, 209, 208, 207, 141, 200, 197, 196, 193, 192,
191, 190, 187, 184, 183, 182, 179, 178, 177, 176,
175, 174, 173, 169, 168, 167, 166, 165, 164, 163,
162, 161, 160, 159, 158, 157, 156, 155, 154, 153,
152, 151, 150, 141, 63, 74, 134, 119, 116, 113,
112, 109, 108, 92, 86, 67, 64, 63, 61, 486,
5, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486
} ;
static yyconst flex_int16_t yy_chk[806] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 12, 16,
18, 19, 19, 19, 19, 19, 19, 19, 25, 25,
20, 27, 27, 18, 16, 20, 491, 12, 32, 22,
22, 22, 22, 22, 22, 22, 20, 21, 44, 21,
21, 21, 21, 21, 21, 21, 34, 32, 34, 483,
37, 44, 37, 35, 46, 22, 21, 21, 36, 21,
21, 37, 36, 35, 21, 21, 35, 36, 54, 157,
157, 41, 46, 481, 21, 21, 38, 21, 41, 49,
21, 22, 49, 119, 38, 48, 38, 51, 21, 38,
49, 21, 48, 48, 119, 50, 51, 49, 123, 50,
480, 111, 48, 50, 111, 48, 77, 133, 111, 133,
77, 77, 125, 123, 54, 72, 72, 72, 72, 72,
72, 72, 125, 130, 479, 430, 77, 430, 454, 186,
454, 130, 72, 72, 77, 72, 79, 77, 79, 186,
478, 79, 79, 79, 79, 79, 79, 79, 149, 474,
72, 72, 149, 72, 76, 76, 76, 76, 76, 76,
76, 147, 147, 147, 147, 147, 147, 147, 149, 194,
473, 76, 76, 138, 76, 138, 149, 194, 138, 138,
138, 138, 138, 138, 138, 207, 207, 207, 207, 76,
76, 472, 76, 78, 470, 78, 78, 78, 78, 78,
78, 78, 201, 201, 201, 201, 201, 201, 201, 323,
323, 323, 78, 78, 469, 78, 78, 143, 467, 143,
78, 465, 143, 143, 143, 143, 143, 143, 143, 464,
78, 78, 463, 78, 461, 460, 78, 148, 148, 148,
148, 148, 148, 148, 78, 172, 172, 172, 172, 223,
223, 223, 223, 459, 458, 148, 457, 148, 202, 202,
202, 202, 202, 202, 202, 203, 203, 203, 203, 203,
203, 203, 456, 148, 455, 148, 202, 453, 202, 172,
204, 204, 204, 204, 204, 204, 204, 251, 251, 251,
251, 324, 324, 324, 202, 452, 202, 451, 204, 450,
204, 273, 273, 273, 273, 274, 274, 274, 274, 325,
325, 325, 352, 352, 352, 449, 204, 448, 204, 353,
353, 353, 354, 354, 354, 355, 355, 355, 356, 356,
356, 357, 357, 357, 371, 371, 371, 373, 373, 418,
445, 444, 443, 442, 441, 440, 439, 438, 371, 418,
373, 437, 436, 435, 434, 371, 418, 373, 433, 432,
431, 429, 428, 371, 487, 487, 487, 488, 488, 489,
489, 490, 490, 490, 427, 426, 425, 422, 421, 420,
419, 417, 412, 411, 410, 409, 407, 406, 405, 404,
403, 402, 399, 398, 377, 376, 372, 370, 369, 368,
367, 351, 348, 347, 345, 344, 343, 342, 341, 335,
333, 330, 329, 327, 322, 321, 320, 318, 317, 316,
314, 312, 311, 310, 308, 307, 305, 303, 298, 297,
296, 295, 294, 293, 292, 291, 289, 288, 287, 286,
285, 284, 283, 282, 281, 279, 278, 277, 276, 271,
270, 269, 268, 267, 259, 258, 256, 255, 254, 253,
252, 250, 247, 246, 245, 244, 243, 242, 241, 240,
239, 238, 237, 236, 235, 234, 233, 232, 230, 225,
224, 221, 220, 219, 218, 215, 214, 213, 212, 211,
210, 208, 200, 199, 198, 197, 196, 195, 193, 192,
191, 190, 189, 188, 187, 185, 184, 183, 182, 181,
180, 179, 178, 176, 175, 174, 173, 171, 170, 169,
168, 166, 165, 164, 163, 162, 161, 160, 159, 158,
156, 155, 154, 153, 140, 134, 132, 131, 129, 128,
127, 126, 124, 122, 121, 120, 118, 117, 116, 115,
114, 113, 112, 109, 108, 107, 106, 105, 104, 103,
102, 101, 100, 99, 98, 97, 96, 95, 94, 93,
92, 88, 84, 74, 62, 59, 52, 47, 45, 43,
42, 40, 39, 33, 26, 15, 11, 10, 9, 5,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486, 486, 486, 486, 486, 486,
486, 486, 486, 486, 486
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int yy_flex_debug;
int yy_flex_debug = 0;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "hlslang.l"
/*-*-C++-*-
// Copyright (c) The HLSL2GLSLFork Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.txt file.
*/
/* Based on
ANSI C grammar, Lex specification
In 1985, Jeff Lee published this Lex specification together with a Yacc
grammar for the April 30, 1985 ANSI C draft. Tom Stockfisch reposted
both to net.sources in 1987; that original, as mentioned in the answer
to question 17.25 of the comp.lang.c FAQ, can be ftp'ed from ftp.uu.net,
file usenet/net.sources/ansi.c.grammar.Z.
I intend to keep this version as close to the current C Standard grammar
as possible; please let me know if you discover discrepancies.
Jutta Degener, 1995
*/
#line 34 "hlslang.l"
#define YY_NO_UNISTD_H
#include <stdio.h>
#include <stdlib.h>
#include "ParseHelper.h"
using namespace hlslang;
#include "hlslang_tab.h"
/* windows only pragma */
#ifdef _MSC_VER
#pragma warning(disable : 4102)
#endif
namespace hlslang {
int yy_input(char* buf, int max_size);
}
static TSourceLoc lexlineno = { 0, 0 };
extern int yyparse(TParseContext&);
#define YY_DECL int yylex(YYSTYPE* pyylval,TParseContext& parseContext)
#define YY_INPUT(buf,result,max_size) (result = yy_input(buf, max_size))
#line 844 "Gen_hlslang.cpp"
#define INITIAL 0
#define FIELDS 1
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (void );
int yyget_debug (void );
void yyset_debug (int debug_flag );
YY_EXTRA_TYPE yyget_extra (void );
void yyset_extra (YY_EXTRA_TYPE user_defined );
FILE *yyget_in (void );
void yyset_in (FILE * in_str );
FILE *yyget_out (void );
void yyset_out (FILE * out_str );
yy_size_t yyget_leng (void );
char *yyget_text (void );
int yyget_lineno (void );
void yyset_lineno (int line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (void );
#else
extern int yywrap (void );
#endif
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO fwrite( yytext, yyleng, 1, yyout )
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
yy_size_t n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
#line 66 "hlslang.l"
#line 1027 "Gen_hlslang.cpp"
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_load_buffer_state( );
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = (yy_c_buf_p);
/* Support of yytext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 487 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_current_state != 486 );
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_find_action:
yy_act = yy_accept[yy_current_state];
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
/* rule 1 can match eol */
YY_RULE_SETUP
#line 67 "hlslang.l"
{ /* ?? carriage and/or line-feed? */ };
YY_BREAK
case 2:
YY_RULE_SETUP
#line 69 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(CONST_QUAL); }
YY_BREAK
case 3:
YY_RULE_SETUP
#line 70 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(STATIC_QUAL); }
YY_BREAK
case 4:
YY_RULE_SETUP
#line 71 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(UNIFORM); }
YY_BREAK
case 5:
YY_RULE_SETUP
#line 73 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(BREAK); }
YY_BREAK
case 6:
YY_RULE_SETUP
#line 74 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(CONTINUE); }
YY_BREAK
case 7:
YY_RULE_SETUP
#line 75 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(DO); }
YY_BREAK
case 8:
YY_RULE_SETUP
#line 76 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(FOR); }
YY_BREAK
case 9:
YY_RULE_SETUP
#line 77 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(WHILE); }
YY_BREAK
case 10:
YY_RULE_SETUP
#line 79 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(IF); }
YY_BREAK
case 11:
YY_RULE_SETUP
#line 80 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(ELSE); }
YY_BREAK
case 12:
YY_RULE_SETUP
#line 82 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(IN_QUAL); }
YY_BREAK
case 13:
YY_RULE_SETUP
#line 83 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(OUT_QUAL); }
YY_BREAK
case 14:
YY_RULE_SETUP
#line 84 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(INOUT_QUAL); }
YY_BREAK
case 15:
YY_RULE_SETUP
#line 86 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FLOAT_TYPE); }
YY_BREAK
case 16:
YY_RULE_SETUP
#line 87 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FLOAT_TYPE); }
YY_BREAK
case 17:
YY_RULE_SETUP
#line 88 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(INT_TYPE); }
YY_BREAK
case 18:
YY_RULE_SETUP
#line 89 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(INT_TYPE); }
YY_BREAK
case 19:
YY_RULE_SETUP
#line 90 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(INT_TYPE); /* @TODO proper unsigned int? */ }
YY_BREAK
case 20:
YY_RULE_SETUP
#line 91 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(INT_TYPE); }
YY_BREAK
case 21:
YY_RULE_SETUP
#line 92 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(VOID_TYPE); }
YY_BREAK
case 22:
YY_RULE_SETUP
#line 93 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(BOOL_TYPE); }
YY_BREAK
case 23:
YY_RULE_SETUP
#line 94 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(BOOL_TYPE); }
YY_BREAK
case 24:
YY_RULE_SETUP
#line 95 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(STRING_TYPE); }
YY_BREAK
case 25:
YY_RULE_SETUP
#line 96 "hlslang.l"
{ pyylval->lex.line = lexlineno; pyylval->lex.b = true; return(BOOLCONSTANT); }
YY_BREAK
case 26:
YY_RULE_SETUP
#line 97 "hlslang.l"
{ pyylval->lex.line = lexlineno; pyylval->lex.b = false; return(BOOLCONSTANT); }
YY_BREAK
case 27:
YY_RULE_SETUP
#line 99 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(DISCARD); }
YY_BREAK
case 28:
YY_RULE_SETUP
#line 100 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(RETURN); }
YY_BREAK
case 29:
YY_RULE_SETUP
#line 102 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(MATRIX2x2); }
YY_BREAK
case 30:
YY_RULE_SETUP
#line 103 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(MATRIX2x3); }
YY_BREAK
case 31:
YY_RULE_SETUP
#line 104 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(MATRIX2x4); }
YY_BREAK
case 32:
YY_RULE_SETUP
#line 106 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(MATRIX3x2); }
YY_BREAK
case 33:
YY_RULE_SETUP
#line 107 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(MATRIX3x3); }
YY_BREAK
case 34:
YY_RULE_SETUP
#line 108 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(MATRIX3x4); }
YY_BREAK
case 35:
YY_RULE_SETUP
#line 110 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(MATRIX4x2); }
YY_BREAK
case 36:
YY_RULE_SETUP
#line 111 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(MATRIX4x3); }
YY_BREAK
case 37:
YY_RULE_SETUP
#line 112 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(MATRIX4x4); }
YY_BREAK
case 38:
YY_RULE_SETUP
#line 114 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HMATRIX2x2); }
YY_BREAK
case 39:
YY_RULE_SETUP
#line 115 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HMATRIX2x3); }
YY_BREAK
case 40:
YY_RULE_SETUP
#line 116 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HMATRIX2x4); }
YY_BREAK
case 41:
YY_RULE_SETUP
#line 118 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HMATRIX3x2); }
YY_BREAK
case 42:
YY_RULE_SETUP
#line 119 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HMATRIX3x3); }
YY_BREAK
case 43:
YY_RULE_SETUP
#line 120 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HMATRIX3x4); }
YY_BREAK
case 44:
YY_RULE_SETUP
#line 122 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HMATRIX4x2); }
YY_BREAK
case 45:
YY_RULE_SETUP
#line 123 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HMATRIX4x3); }
YY_BREAK
case 46:
YY_RULE_SETUP
#line 124 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HMATRIX4x4); }
YY_BREAK
case 47:
YY_RULE_SETUP
#line 126 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FMATRIX2x2); }
YY_BREAK
case 48:
YY_RULE_SETUP
#line 127 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FMATRIX2x3); }
YY_BREAK
case 49:
YY_RULE_SETUP
#line 128 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FMATRIX2x4); }
YY_BREAK
case 50:
YY_RULE_SETUP
#line 130 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FMATRIX3x2); }
YY_BREAK
case 51:
YY_RULE_SETUP
#line 131 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FMATRIX3x3); }
YY_BREAK
case 52:
YY_RULE_SETUP
#line 132 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FMATRIX3x4); }
YY_BREAK
case 53:
YY_RULE_SETUP
#line 134 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FMATRIX4x2); }
YY_BREAK
case 54:
YY_RULE_SETUP
#line 135 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FMATRIX4x3); }
YY_BREAK
case 55:
YY_RULE_SETUP
#line 136 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FMATRIX4x4); }
YY_BREAK
case 56:
YY_RULE_SETUP
#line 138 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HALF_TYPE); }
YY_BREAK
case 57:
YY_RULE_SETUP
#line 139 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(HALF_TYPE); }
YY_BREAK
case 58:
YY_RULE_SETUP
#line 140 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (HVEC2); }
YY_BREAK
case 59:
YY_RULE_SETUP
#line 141 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (HVEC3); }
YY_BREAK
case 60:
YY_RULE_SETUP
#line 142 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (HVEC4); }
YY_BREAK
case 61:
YY_RULE_SETUP
#line 144 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FIXED_TYPE); }
YY_BREAK
case 62:
YY_RULE_SETUP
#line 145 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return(FIXED_TYPE); }
YY_BREAK
case 63:
YY_RULE_SETUP
#line 146 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (FVEC2); }
YY_BREAK
case 64:
YY_RULE_SETUP
#line 147 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (FVEC3); }
YY_BREAK
case 65:
YY_RULE_SETUP
#line 148 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (FVEC4); }
YY_BREAK
case 66:
YY_RULE_SETUP
#line 150 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (VEC2); }
YY_BREAK
case 67:
YY_RULE_SETUP
#line 151 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (VEC3); }
YY_BREAK
case 68:
YY_RULE_SETUP
#line 152 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (VEC4); }
YY_BREAK
case 69:
YY_RULE_SETUP
#line 153 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (IVEC2); }
YY_BREAK
case 70:
YY_RULE_SETUP
#line 154 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (IVEC3); }
YY_BREAK
case 71:
YY_RULE_SETUP
#line 155 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (IVEC4); }
YY_BREAK
case 72:
YY_RULE_SETUP
#line 156 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (IVEC2); /* @TODO proper unsigned type? */ }
YY_BREAK
case 73:
YY_RULE_SETUP
#line 157 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (IVEC3); }
YY_BREAK
case 74:
YY_RULE_SETUP
#line 158 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (IVEC4); }
YY_BREAK
case 75:
YY_RULE_SETUP
#line 159 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (BVEC2); }
YY_BREAK
case 76:
YY_RULE_SETUP
#line 160 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (BVEC3); }
YY_BREAK
case 77:
YY_RULE_SETUP
#line 161 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (BVEC4); }
YY_BREAK
case 78:
YY_RULE_SETUP
#line 163 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (VECTOR); }
YY_BREAK
case 79:
YY_RULE_SETUP
#line 164 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (MATRIX); }
YY_BREAK
case 80:
YY_RULE_SETUP
#line 165 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return (REGISTER); }
YY_BREAK
case 81:
YY_RULE_SETUP
#line 167 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLER1D; }
YY_BREAK
case 82:
YY_RULE_SETUP
#line 168 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLER1DSHADOW; }
YY_BREAK
case 83:
YY_RULE_SETUP
#line 169 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLER2D; }
YY_BREAK
case 84:
YY_RULE_SETUP
#line 170 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLER2DSHADOW; }
YY_BREAK
case 85:
YY_RULE_SETUP
#line 171 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLER2DARRAY; }
YY_BREAK
case 86:
YY_RULE_SETUP
#line 172 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLER2D_HALF; }
YY_BREAK
case 87:
YY_RULE_SETUP
#line 173 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLER2D_FLOAT; }
YY_BREAK
case 88:
YY_RULE_SETUP
#line 174 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLER3D; }
YY_BREAK
case 89:
YY_RULE_SETUP
#line 175 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLERRECT; }
YY_BREAK
case 90:
YY_RULE_SETUP
#line 176 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLERRECTSHADOW; }
YY_BREAK
case 91:
YY_RULE_SETUP
#line 178 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLERGENERIC; }
YY_BREAK
case 92:
YY_RULE_SETUP
#line 179 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLERCUBE; }
YY_BREAK
case 93:
YY_RULE_SETUP
#line 180 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLERCUBE_HALF; }
YY_BREAK
case 94:
YY_RULE_SETUP
#line 181 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLERCUBE_FLOAT; }
YY_BREAK
case 95:
YY_RULE_SETUP
#line 183 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return TEXTURE; }
YY_BREAK
case 96:
YY_RULE_SETUP
#line 184 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return TEXTURE; }
YY_BREAK
case 97:
YY_RULE_SETUP
#line 185 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return TEXTURE; }
YY_BREAK
case 98:
YY_RULE_SETUP
#line 186 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return TEXTURE; }
YY_BREAK
case 99:
YY_RULE_SETUP
#line 187 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return TEXTURE; }
YY_BREAK
case 100:
YY_RULE_SETUP
#line 188 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = true; return SAMPLERSTATE; }
YY_BREAK
case 101:
YY_RULE_SETUP
#line 190 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(STRUCT); }
YY_BREAK
case 102:
YY_RULE_SETUP
#line 192 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 103:
YY_RULE_SETUP
#line 194 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 104:
YY_RULE_SETUP
#line 195 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 105:
YY_RULE_SETUP
#line 196 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 106:
YY_RULE_SETUP
#line 197 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 107:
YY_RULE_SETUP
#line 198 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 108:
YY_RULE_SETUP
#line 199 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 109:
YY_RULE_SETUP
#line 200 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 110:
YY_RULE_SETUP
#line 202 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 111:
YY_RULE_SETUP
#line 203 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 112:
YY_RULE_SETUP
#line 204 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 113:
YY_RULE_SETUP
#line 206 "hlslang.l"
{ /* just ignore it PaReservedWord(); return 0; */ }
YY_BREAK
case 114:
YY_RULE_SETUP
#line 207 "hlslang.l"
{ /* just ignore it PaReservedWord(); return 0; */ }
YY_BREAK
case 115:
YY_RULE_SETUP
#line 208 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 116:
YY_RULE_SETUP
#line 209 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 117:
YY_RULE_SETUP
#line 210 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 118:
YY_RULE_SETUP
#line 211 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 119:
YY_RULE_SETUP
#line 212 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 120:
YY_RULE_SETUP
#line 214 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 121:
YY_RULE_SETUP
#line 215 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 122:
YY_RULE_SETUP
#line 216 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 123:
YY_RULE_SETUP
#line 217 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 124:
YY_RULE_SETUP
#line 219 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 125:
YY_RULE_SETUP
#line 221 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 126:
YY_RULE_SETUP
#line 222 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 127:
YY_RULE_SETUP
#line 224 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 128:
YY_RULE_SETUP
#line 225 "hlslang.l"
{ PaReservedWord(); return 0; }
YY_BREAK
case 129:
YY_RULE_SETUP
#line 227 "hlslang.l"
{
pyylval->lex.line = lexlineno;
pyylval->lex.string = NewPoolTString(yytext);
return PaIdentOrType(*pyylval->lex.string, parseContext, pyylval->lex.symbol);
}
YY_BREAK
case 130:
YY_RULE_SETUP
#line 233 "hlslang.l"
{ pyylval->lex.line = lexlineno; pyylval->lex.f = static_cast<float>(atof(yytext)); return(FLOATCONSTANT); }
YY_BREAK
case 131:
YY_RULE_SETUP
#line 234 "hlslang.l"
{ pyylval->lex.line = lexlineno; pyylval->lex.f = static_cast<float>(atof(yytext)); return(FLOATCONSTANT); }
YY_BREAK
case 132:
YY_RULE_SETUP
#line 235 "hlslang.l"
{ pyylval->lex.line = lexlineno; pyylval->lex.f = static_cast<float>(atof(yytext)); return(FLOATCONSTANT); }
YY_BREAK
case 133:
YY_RULE_SETUP
#line 236 "hlslang.l"
{ pyylval->lex.line = lexlineno; pyylval->lex.f = static_cast<float>(atof(yytext)); return(FLOATCONSTANT); }
YY_BREAK
case 134:
YY_RULE_SETUP
#line 238 "hlslang.l"
{ pyylval->lex.line = lexlineno; pyylval->lex.i = strtol(yytext, 0, 0); return(INTCONSTANT); }
YY_BREAK
case 135:
YY_RULE_SETUP
#line 239 "hlslang.l"
{ pyylval->lex.line = lexlineno; pyylval->lex.i = strtol(yytext, 0, 0); return(INTCONSTANT); }
YY_BREAK
case 136:
YY_RULE_SETUP
#line 240 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.error(lexlineno, "Invalid Octal number.", yytext, "", ""); parseContext.recover(); return 0;}
YY_BREAK
case 137:
YY_RULE_SETUP
#line 241 "hlslang.l"
{ pyylval->lex.line = lexlineno; pyylval->lex.i = strtol(yytext, 0, 0); return(INTCONSTANT); }
YY_BREAK
case 138:
YY_RULE_SETUP
#line 247 "hlslang.l"
{ int ret = PaParseComment(pyylval->lex.line, parseContext); if (!ret) return ret; }
YY_BREAK
case 139:
YY_RULE_SETUP
#line 249 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(ADD_ASSIGN); }
YY_BREAK
case 140:
YY_RULE_SETUP
#line 250 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(SUB_ASSIGN); }
YY_BREAK
case 141:
YY_RULE_SETUP
#line 251 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(MUL_ASSIGN); }
YY_BREAK
case 142:
YY_RULE_SETUP
#line 252 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(DIV_ASSIGN); }
YY_BREAK
case 143:
YY_RULE_SETUP
#line 253 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(MOD_ASSIGN); }
YY_BREAK
case 144:
YY_RULE_SETUP
#line 254 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(LEFT_ASSIGN); }
YY_BREAK
case 145:
YY_RULE_SETUP
#line 255 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(RIGHT_ASSIGN); }
YY_BREAK
case 146:
YY_RULE_SETUP
#line 256 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(AND_ASSIGN); }
YY_BREAK
case 147:
YY_RULE_SETUP
#line 257 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(XOR_ASSIGN); }
YY_BREAK
case 148:
YY_RULE_SETUP
#line 258 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(OR_ASSIGN); }
YY_BREAK
case 149:
YY_RULE_SETUP
#line 260 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(INC_OP); }
YY_BREAK
case 150:
YY_RULE_SETUP
#line 261 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(DEC_OP); }
YY_BREAK
case 151:
YY_RULE_SETUP
#line 262 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(AND_OP); }
YY_BREAK
case 152:
YY_RULE_SETUP
#line 263 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(OR_OP); }
YY_BREAK
case 153:
YY_RULE_SETUP
#line 264 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(XOR_OP); }
YY_BREAK
case 154:
YY_RULE_SETUP
#line 265 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(LE_OP); }
YY_BREAK
case 155:
YY_RULE_SETUP
#line 266 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(GE_OP); }
YY_BREAK
case 156:
YY_RULE_SETUP
#line 267 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(EQ_OP); }
YY_BREAK
case 157:
YY_RULE_SETUP
#line 268 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(NE_OP); }
YY_BREAK
case 158:
YY_RULE_SETUP
#line 269 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(LEFT_OP); }
YY_BREAK
case 159:
YY_RULE_SETUP
#line 270 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(RIGHT_OP); }
YY_BREAK
case 160:
YY_RULE_SETUP
#line 271 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = false; return(SEMICOLON); }
YY_BREAK
case 161:
YY_RULE_SETUP
#line 272 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = false; return(LEFT_BRACE); }
YY_BREAK
case 162:
YY_RULE_SETUP
#line 273 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(RIGHT_BRACE); }
YY_BREAK
case 163:
YY_RULE_SETUP
#line 274 "hlslang.l"
{ pyylval->lex.line = lexlineno; if (parseContext.inTypeParen) parseContext.lexAfterType = false; return(COMMA); }
YY_BREAK
case 164:
YY_RULE_SETUP
#line 275 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(COLON); }
YY_BREAK
case 165:
YY_RULE_SETUP
#line 276 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = false; return(EQUAL); }
YY_BREAK
case 166:
YY_RULE_SETUP
#line 277 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.lexAfterType = false; parseContext.inTypeParen = true; return(LEFT_PAREN); }
YY_BREAK
case 167:
YY_RULE_SETUP
#line 278 "hlslang.l"
{ pyylval->lex.line = lexlineno; parseContext.inTypeParen = false; return(RIGHT_PAREN); }
YY_BREAK
case 168:
YY_RULE_SETUP
#line 279 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(LEFT_BRACKET); }
YY_BREAK
case 169:
YY_RULE_SETUP
#line 280 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(RIGHT_BRACKET); }
YY_BREAK
case 170:
YY_RULE_SETUP
#line 281 "hlslang.l"
{ BEGIN(FIELDS); return(DOT); }
YY_BREAK
case 171:
YY_RULE_SETUP
#line 282 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(BANG); }
YY_BREAK
case 172:
YY_RULE_SETUP
#line 283 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(DASH); }
YY_BREAK
case 173:
YY_RULE_SETUP
#line 284 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(TILDE); }
YY_BREAK
case 174:
YY_RULE_SETUP
#line 285 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(PLUS); }
YY_BREAK
case 175:
YY_RULE_SETUP
#line 286 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(STAR); }
YY_BREAK
case 176:
YY_RULE_SETUP
#line 287 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(SLASH); }
YY_BREAK
case 177:
YY_RULE_SETUP
#line 288 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(PERCENT); }
YY_BREAK
case 178:
YY_RULE_SETUP
#line 289 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(LEFT_ANGLE); }
YY_BREAK
case 179:
YY_RULE_SETUP
#line 290 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(RIGHT_ANGLE); }
YY_BREAK
case 180:
YY_RULE_SETUP
#line 291 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(VERTICAL_BAR); }
YY_BREAK
case 181:
YY_RULE_SETUP
#line 292 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(CARET); }
YY_BREAK
case 182:
YY_RULE_SETUP
#line 293 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(AMPERSAND); }
YY_BREAK
case 183:
YY_RULE_SETUP
#line 294 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(QUESTION); }
YY_BREAK
case 184:
/* rule 184 can match eol */
YY_RULE_SETUP
#line 296 "hlslang.l"
{ pyylval->lex.line = lexlineno; return(STRINGCONSTANT); }
YY_BREAK
case 185:
YY_RULE_SETUP
#line 298 "hlslang.l"
{
BEGIN(INITIAL);
pyylval->lex.line = lexlineno;
pyylval->lex.string = NewPoolTString(yytext);
return FIELD_SELECTION; }
YY_BREAK
case 186:
YY_RULE_SETUP
#line 303 "hlslang.l"
{}
YY_BREAK
case 187:
/* rule 187 can match eol */
YY_RULE_SETUP
#line 306 "hlslang.l"
{ }
YY_BREAK
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(FIELDS):
#line 307 "hlslang.l"
{ (&parseContext)->AfterEOF = true; yy_delete_buffer(YY_CURRENT_BUFFER); yyterminate();}
YY_BREAK
case 188:
YY_RULE_SETUP
#line 308 "hlslang.l"
{ parseContext.infoSink.info << "FLEX: Unknown char " << yytext << "\n";
return 0; }
YY_BREAK
case 189:
YY_RULE_SETUP
#line 311 "hlslang.l"
ECHO;
YY_BREAK
#line 2068 "Gen_hlslang.cpp"
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( yywrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = (yytext_ptr);
register int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
yy_size_t num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
yy_size_t new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
register yy_state_type yy_current_state;
register char *yy_cp;
yy_current_state = (yy_start);
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 487 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
register int yy_is_jam;
register char *yy_cp = (yy_c_buf_p);
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 487 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 486);
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
yy_size_t offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart(yyin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( ) )
return 0;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve yytext */
(yy_hold_char) = *++(yy_c_buf_p);
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_init_buffer(YY_CURRENT_BUFFER,input_file );
yy_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void yy_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
*
*/
void yy_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree((void *) b->yy_ch_buf );
yyfree((void *) b );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
yy_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void yy_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
yyensure_buffer_stack();
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void yypop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (void)
{
yy_size_t num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (yyconst char * yystr )
{
return yy_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param bytes the byte buffer to scan
* @param len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n, i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) yyalloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = (yy_hold_char); \
(yy_c_buf_p) = yytext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int yyget_lineno (void)
{
return yylineno;
}
/** Get the input stream.
*
*/
FILE *yyget_in (void)
{
return yyin;
}
/** Get the output stream.
*
*/
FILE *yyget_out (void)
{
return yyout;
}
/** Get the length of the current token.
*
*/
yy_size_t yyget_leng (void)
{
return yyleng;
}
/** Get the current token.
*
*/
char *yyget_text (void)
{
return yytext;
}
/** Set the current line number.
* @param line_number
*
*/
void yyset_lineno (int line_number )
{
yylineno = line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
*
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * in_str )
{
yyin = in_str ;
}
void yyset_out (FILE * out_str )
{
yyout = out_str ;
}
int yyget_debug (void)
{
return yy_flex_debug;
}
void yyset_debug (int bdebug )
{
yy_flex_debug = bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state();
}
/* Destroy the stack itself. */
yyfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *yyrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void yyfree (void * ptr )
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 311 "hlslang.l"
#include "preprocessor/mojoshader.h"
#define __MOJOSHADER_INTERNAL__ 1
#include "preprocessor/mojoshader_internal.h"
#include <cstring>
static hlmojo_Preprocessor* g_cpp;
static TParseContext* g_parseContext;
const TSourceLoc gNullSourceLoc = { NULL, 0 };
static int cpp_get_token (hlmojo_Preprocessor* pp, char* buf, int maxSize)
{
const char *tokstr = NULL;
unsigned int len = 0;
Token token = TOKEN_UNKNOWN;
tokstr = hlmojo_preprocessor_nexttoken (pp, &len, &token);
if (tokstr == NULL)
return 0;
if (hlmojo_preprocessor_outofmemory(pp))
{
g_parseContext->error (gNullSourceLoc, "out of memory", "", "");
GlobalParseContext->recover();
buf[0] = 0;
return 0;
}
unsigned int line = 0;
const char* fname = hlmojo_preprocessor_sourcepos (pp, &line);
TSourceLoc loc;
loc.file = fname;
loc.line = line;
SetLineNumber (loc, lexlineno);
if (token == TOKEN_PREPROCESSING_ERROR)
{
g_parseContext->error (lexlineno, tokstr, "", "");
GlobalParseContext->recover();
buf[0] = 0;
}
else
{
if (len >= maxSize)
{
return maxSize;
}
else if (len > 0)
{
memcpy (buf, tokstr, len+1);
return len;
}
return 0;
}
return 0;
} // cpp_get_token
namespace hlslang {
//
// The YY_INPUT macro just calls this. Maybe this could be just put into
// the macro directly.
//
int yy_input(char* buf, int max_size)
{
int len;
if ((len = cpp_get_token(g_cpp, buf, max_size)) == 0)
return 0;
if (len >= max_size)
YY_FATAL_ERROR( "input buffer overflow, can't enlarge buffer because scanner uses REJECT" );
//debug code to dump the token stream to stdout
//buf[len] = '\0';
//printf( ":: %s\n", buf);
buf[len] = ' ';
return len+1;
}
int IncludeOpenCallback(MOJOSHADER_hlslang_includeType inctype,
const char *fname, const char *parentfname, const char *parent,
const char **outdataPtr, unsigned int *outbytesPtr,
MOJOSHADER_hlslang_malloc m, MOJOSHADER_hlslang_free f, void *d)
{
Hlsl2Glsl_ParseCallbacks* callbacks = reinterpret_cast<Hlsl2Glsl_ParseCallbacks*>(d);
std::string out;
if (callbacks->includeOpenCallback &&
!callbacks->includeOpenCallback(inctype == MOJOSHADER_hlslang_INCLUDETYPE_SYSTEM,
fname, parentfname, parent, out, callbacks->data))
{
return 0;
}
char* outdata = (char*) m(out.size() + 1, NULL);
std::memcpy(outdata, out.data(), out.size()+1);
*outdataPtr = outdata;
*outbytesPtr = out.size();
return 1;
}
void IncludeCloseCallback(const char *data,
MOJOSHADER_hlslang_malloc m, MOJOSHADER_hlslang_free f, void *d)
{
Hlsl2Glsl_ParseCallbacks* callbacks = reinterpret_cast<Hlsl2Glsl_ParseCallbacks*>(d);
if (callbacks->includeCloseCallback)
callbacks->includeCloseCallback(data, callbacks->data);
f(const_cast<char*>(data), NULL);
}
//
// Parse a string using yyparse. We set up globals used by
// yywrap.
//
// Returns 0 for success, as per yyparse().
//
int PaParseString(char* source, TParseContext& parseContextLocal, Hlsl2Glsl_ParseCallbacks* callbacks)
{
int sourceLen;
if (!source) {
parseContextLocal.error(gNullSourceLoc, "Null shader source string", "", "");
parseContextLocal.recover();
return 1;
}
sourceLen = (int) strlen(source);
MOJOSHADER_hlslang_includeOpen openCallback = NULL;
MOJOSHADER_hlslang_includeClose closeCallback = NULL;
void* data = NULL;
if (callbacks)
{
openCallback = IncludeOpenCallback;
closeCallback = IncludeCloseCallback;
data = callbacks;
}
hlmojo_Preprocessor* pp = hlmojo_preprocessor_start("", source, sourceLen,
openCallback,
closeCallback,
NULL, // defines
0, // define count
MOJOSHADER_hlslang_internal_malloc,
MOJOSHADER_hlslang_internal_free,
data);
g_cpp = pp;
g_parseContext = &parseContextLocal;
yyrestart(0);
(&parseContextLocal)->AfterEOF = false;
lexlineno.file = NULL;
lexlineno.line = 1;
int result = 0;
if (sourceLen >= 0)
{
yyparse(parseContextLocal);
if (parseContextLocal.recoveredFromError || parseContextLocal.numErrors > 0)
result = 1;
else
result = 0;
}
else
{
result = 0;
}
hlmojo_preprocessor_end (pp);
g_cpp = NULL;
g_parseContext = NULL;
return result;
}
void yyerror(TParseContext& parseContext, const char *s)
{
GlobalParseContext->error(lexlineno, "syntax error", GlobalParseContext->AfterEOF ? "" : yytext, s, "");
GlobalParseContext->recover();
}
void PaReservedWord()
{
GlobalParseContext->error(lexlineno, "Reserved word.", yytext, "", "");
GlobalParseContext->recover();
}
int PaIdentOrType(TString& id, TParseContext& parseContextLocal, TSymbol*& symbol)
{
symbol = parseContextLocal.symbolTable.find(id);
if (parseContextLocal.lexAfterType == false && symbol && symbol->isVariable()) {
TVariable* variable = static_cast<TVariable*>(symbol);
if (variable->isUserType()) {
parseContextLocal.lexAfterType = true;
return TYPE_NAME;
}
}
return IDENTIFIER;
}
int PaParseComment(TSourceLoc &lineno, TParseContext& parseContextLocal)
{
int transitionFlag = 0;
int nextChar;
while (transitionFlag != 2) {
nextChar = yyinput();
if (nextChar == '\n')
lineno.line++;
switch (nextChar) {
case '*' :
transitionFlag = 1;
break;
case '/' : /* if star is the previous character, then it is the end of comment */
if (transitionFlag == 1) {
return 1 ;
}
break;
case EOF :
/* Raise error message here */
parseContextLocal.error(lexlineno, "End of shader found before end of comment.", "", "", "");
GlobalParseContext->recover();
return YY_NULL;
default : /* Any other character will be a part of the comment */
transitionFlag = 0;
}
}
return 1;
}
void setInitialState()
{
yy_start = 1;
}
} // namespace
|
/*
* 8 September 2016
* Il Guastafeste - Stereo
* Ivan Iovine
*
* Call for Residency - Casa Jasmina / Maker Faire Rome
*/
#include <WiFi101.h>
#include <ArduinoCloud.h>
// variables for WLAN Communication
char *ssid = "";
char *pass = "";
// arduino cloud settings and credentials
const char userName[] = "dummknopf";
const char thingName[] = "ilguastafestestereo";
const char thingId[] = "4f9ccd39-013d-4619-a526-6fa5545b50d7";
const char thingPsw[] = "9b4510e3-31f3-4083-9aa7-d69bfc8b72f3";
// variable to set the gain
int pinGain0 = 5;
int pinGain1 = 4;
int shutRight = 3; // variable to shut down the right speaker
int shutLeft = 2; // variable to shut down the left speaker
int potVal; // variable to read the potentiometer
//Check Variables for time and set state
int step1 = 0;
int step2 = 0;
int step3 = 0;
int countState = 0;
// build a new object for the wifi client
WiFiSSLClient sslClient;
// build a new object "ilguastafestestereo"
ArduinoCloudThing ilguastafestestereo;
void setup() {
Serial.begin(9600);
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
// unsuccessful, retry in 4 seconds
Serial.print("failed ... ");
delay(4000);
Serial.print("retrying ... ");
}
ilguastafestestereo.begin(thingName, userName, thingId, thingPsw, sslClient);
ilguastafestestereo.enableDebug();
// define the properties
ilguastafestestereo.addProperty("ilguastafestestereoslave", CHARSTRING, RW);
ilguastafestestereo.addExternalProperty("ilguastafestetrombetta","ilguastafestemaster",CHARSTRING);
}
void loop() {
potVal = map(analogRead(A1),0,1023,1024,0);
ilguastafestestereo.poll();
countState = setStates();
switch(countState){
case 0:
step1 = 0;
step2 = 0;
digitalWrite(shutRight, HIGH);
digitalWrite(shutLeft, HIGH);
digitalWrite(pinGain0, LOW);
digitalWrite(pinGain1, LOW);
setVolume(potVal);
Serial.println("Let's Start!");
break;
case 1:
step1++;
Serial.println(step1);
if(step1 < 15000)
{
digitalWrite(shutRight, HIGH);
digitalWrite(shutLeft, HIGH);
analogWrite(pinGain0, HIGH);
analogWrite(pinGain1, HIGH);
Serial.println("Step 1");
}
else
{
setVolume(potVal);
}
break;
case 2:
step2++;
Serial.println(step2);
if(step2 < 15000)
{
digitalWrite(shutRight, HIGH);
digitalWrite(shutLeft, HIGH);
analogWrite(pinGain0, HIGH);
analogWrite(pinGain1, HIGH);
Serial.println("Step 2");
}
else
{
setVolume(potVal);
}
break;
case 3:
analogWrite(shutRight, HIGH);
analogWrite(shutLeft, HIGH);
Serial.println("Step 3");
delay(2000);
step1 = 0;
step2 = 0;
break;
default:
// Nothing to do here
break;
}
Serial.println(countState);
}
int setStates()
{
//Serial.println(ilguastafestestereo.readProperty("ilguastafestetrombetta","ilguastafestemaster"));
if(ilguastafestestereo.readProperty("ilguastafestetrombetta","ilguastafestemaster") == "loud")
{
return 1;
}
else if(ilguastafestestereo.readProperty("ilguastafestetrombetta","ilguastafestemaster") == "tooloud")
{
return 2;
}
else if(ilguastafestestereo.readProperty("ilguastafestetrombetta","ilguastafestemaster") == "partyisover")
{
return 3;
}
else if(ilguastafestestereo.readProperty("ilguastafestetrombetta","ilguastafestemaster") == "restart")
{
return 0;
}
else
{
return 0;
}
}
void setVolume(int p)
{
Serial.println(p);
if(p >= 0 && p < 2)
{
Serial.println("Shut Down");
//Shut Down
digitalWrite(pinGain0, LOW);
digitalWrite(pinGain1, LOW);
analogWrite(shutRight, HIGH);
analogWrite(shutLeft, HIGH);
}
else if(p > 2 && p < 350)
{
Serial.println("MID-LOW Volume");
//MID-LOW Volume
digitalWrite(pinGain0, LOW);
digitalWrite(pinGain1, LOW);
analogWrite(shutRight, LOW);
digitalWrite(shutLeft, HIGH);
}
else if(p > 350 && p < 700)
{
Serial.println("MID-HIGH Volume");
//MID-HIGH Volume
digitalWrite(pinGain0, LOW);
digitalWrite(pinGain1, LOW);
digitalWrite(shutRight, HIGH);
analogWrite(shutLeft, HIGH);
}
else if (p > 700 && p < 1024)
{
Serial.println("HIGH Volume");
//HIGH Volume
digitalWrite(pinGain0, LOW);
digitalWrite(pinGain1, LOW);
digitalWrite(shutRight, HIGH);
digitalWrite(shutLeft, HIGH);
}
else
{
// Nothing to do here
}
}
|
#include "Collisions.h"
#include <iostream>
#include <windows.h>
Collisions::Collisions()
{}
Collisions::~Collisions()
{}
BOX Collisions::GetSweptBroadphaseBox(BOX b)
{
BOX broadphasebox = BOX();
broadphasebox.x = b._velocityX > 0 ? b.x : b.x + b._velocityX;
broadphasebox.y = b._velocityY > 0 ? b.y : b.y + b._velocityY;
broadphasebox.width = b._velocityX > 0 ? b._velocityX + b.width : b.width - b._velocityX;
broadphasebox.height = b._velocityY > 0 ? b._velocityY + b.height : b.height - b._velocityY;
return broadphasebox;
}
bool Collisions::isCollision(BOX b1, BOX b2)
{
return !(b1.x + b1.width < b2.x || b1.x > b2.x + b2.width || b1.y + b1.height < b2.y || b1.y > b2.y + b2.height);
}
float Collisions::SweptAABB(BOX b1, BOX b2, float& normalx, float& normaly, float dt)
{
float dxEntry, dxExit;
float dyEntry, dyExit;
if (b1._velocityX > 0.0f)
{
dxEntry = b2.x - (b1.x + b1.width);
dxExit = (b2.x + b2.width) - b1.x;
}
else
{
dxEntry = (b2.x + b2.width) - b1.x;
dxExit = b2.x - (b1.x + b1.width);
}
if (b1._velocityY > 0.0f)
{
dyEntry = b2.y - (b1.y + b1.height);
dyExit = (b2.y + b2.height) - b1.y;
}
else
{
dyEntry = (b2.y + b2.height) - b1.y;
dyExit = b2.y - (b1.y + b1.height);
}
float txEntry, txExit;
float tyEntry, tyExit;
if (b1._velocityX == 0.0f)
{
txEntry = -std::numeric_limits<float>::infinity();
txExit = std::numeric_limits<float>::infinity();
}
else
{
txEntry = dxEntry / (b1._velocityX*dt);//thêm dt chỗ này lấy tỉ lệ nè, mà khoảng cách chia vận tốc sai. Phải là khoảng cách chia khoảng cách đi được trong farm đó
txExit = dxExit / (b1._velocityX*dt);//
}
if (b1._velocityY == 0.0f)
{
tyEntry = -std::numeric_limits<float>::infinity();
tyExit = std::numeric_limits<float>::infinity();
}
else
{
tyEntry = dyEntry / (b1._velocityY*dt);//thêm dt
tyExit = dyExit / (b1._velocityY*dt);//
}
float entryTime = max(txEntry, tyEntry);
float exitTime = min(txExit, tyExit);
if (entryTime > exitTime || (txEntry < 0.0f && tyEntry < 0.0f) || txEntry > 1.0f || tyEntry > 1.0f)
{
normalx = 0.0f;
normaly = 0.0f;
return 1.0f;
}
if (txEntry > tyEntry)
{
if (dxEntry < 0.0f)
{
normalx = 1.0f;
normaly = 0.0f;
}
else
{
normalx = -1.0f;
normaly = 0.0f;
}
}
else
{
if (dyEntry < 0.0f)
{
normalx = 0.0f;
normaly = 1.0f;
}
else
{
normalx = 0.0f;
normaly = -1.0f;
}
}
return entryTime;
}
|
#include <bits/stdc++.h>
#define MAX_V 1000
#define INF_NUM 100000000
using namespace std;
using ii = pair<int,int>;
vector<ii> G[MAX_V];
int distances[MAX_V];
int dijkstra(int source, int destiny,int N){
fill(distances, distances + N + 1,INF_NUM);
priority_queue<ii,vector<ii>,greater<ii>> tovisit;
distances[source] = 0;
tovisit.push(ii(distances[source],source));
while(!tovisit.empty()){
auto d = tovisit.top().first;
auto v = tovisit.top().second;
tovisit.pop();
if(d > distances[v]) continue;
for(auto i:G[v]){
auto i_v = i.first;
auto i_d = i.second;
if(distances[v] + i_d < distances[i_v]){
distances[i_v] = distances[v] + i_d;
tovisit.push(ii(distances[i_v], i_v));
}
}
}
return distances[destiny];
}
int main(){
int a,b,c,d,e;
a = 0;
b = 1;
c = 2;
d = 3;
e = 4;
G[a].push_back(ii(b,4));
G[a].push_back(ii(c,2));
G[b].push_back(ii(c,3));
G[c].push_back(ii(b,1));
G[b].push_back(ii(d,2));
G[b].push_back(ii(e,3));
G[c].push_back(ii(d,4));
G[c].push_back(ii(e,5));
G[e].push_back(ii(d,1));
cout << dijkstra(a,a,e) << endl;
cout << dijkstra(a,b,e) << endl;
cout << dijkstra(a,c,e) << endl;
cout << dijkstra(a,d,e) << endl;
cout << dijkstra(a,e,e) << endl;
cout << dijkstra(c,d,e) << endl;
cout << dijkstra(d,e,e) << endl;
return 0;
}
|
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main() {
srand(time(0));
double x = rand() / (double)RAND_MAX;
double y = rand() / (double)RAND_MAX;
cout << x << " " << y;
return 0;
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
*
* Chaste tutorial - this page gets automatically changed to a wiki page
* DO NOT remove the comments below, and if the code has to be changed in
* order to run, please check the comments are still accurate
*
*
*/
#ifndef TESTWRITINGTESTTUTORIAL_HPP_
#define TESTWRITINGTESTTUTORIAL_HPP_
/*
* = Writing tests =
* We do not use `int main()` methods in Chaste. Instead, we write ''tests'', which are run using !CxxTest.
* Tests are used both as:
* (i) part of the testing environment - every class in the source code has an equivalent test file which tests each aspect of its functionality, making use of the `TS_ASSERT`s as described below; and
* (ii) for experimental work, which involve writing a 'test' as below but generally without `TS_ASSERT`s.
*
* This tutorial shows how to write a test using !CxxTest. Note that the full code is given at the bottom of the page.
*/
/* First, the following header file needs to be included.*/
#include <cxxtest/TestSuite.h>
/*
* Now we have to define a class containing the tests. It is sensible to name the class with the same name as the file name. The class should inherit from {{{CxxTest::TestSuite}}}.
*/
class TestWritingTestsTutorial: public CxxTest::TestSuite
{
/*
* Now we define some tests, which must be '''public''', begin with the word 'Test', return {{{void}}}, and take in no parameters.
*/
public:
void TestOnePlusOneEqualsTwo()
{
/*
* To test whether two integers are equal, we can use the macro {{{TS_ASSERT_EQUALS}}}.
*/
int some_number = 1 + 1;
TS_ASSERT_EQUALS(some_number, 2);
/*
* To test whether two numbers are equal to within a certain (absolute) tolerance we can use {{{TS_ASSERT_DELTA}}}.
* This should almost always be used when comparing two {{{double}}}s. (See also class:CompareDoubles for more
* advanced comparisons.)
*/
double another_number = 1.000001 + 1.0001;
TS_ASSERT_DELTA(another_number, 2.0, 1e-2);
}
/*
* This second test shows some of the other {{{TS_ASSERT}}} macros that are available.
* The {{{}} part of the signature is there to make sure that full details of any
* uncaught exceptions are reported.
*/
void TestSomeOtherStuff()
{
TS_ASSERT(1==1); // however, it is better to use TS_ASSERT_EQUALS, below
TS_ASSERT_EQUALS((true||false), true);
TS_ASSERT_DIFFERS(1.348329534564385643543957436, 1.348329534564395643543957436);
TS_ASSERT_LESS_THAN(2.71828183, 3.14159265); // Note: to test if x is greater than y, use TS_ASSERT_LESS_THAN(y,x)
TS_ASSERT_LESS_THAN_EQUALS(-1e100, 1e100);
TS_ASSERT_THROWS_ANYTHING(throw 0;); // normally you would put a function call inside the brackets
unsigned x;
// The following TS_ASSERT_THROWS_NOTHING may be useful if you want to be certain that there are no uncaught exceptions
TS_ASSERT_THROWS_NOTHING(x=1;); // normally you would put a function call inside the brackets
TS_ASSERT_EQUALS(x, 1u); //Note that x and 1u are of the same type: unsigned integer
}
/* Other useful macros include `TS_ASSERT_THROWS_THIS` and `TS_ASSERT_THROWS_CONTAINS` for testing exception
* messages.
*
* Note that methods that don't start with 'Test' are compiled but not run. So, if you want to stop a single
* test running, just put an 'x' or a 'donot' (for instance) before its name.
*/
void donotTestThis()
{
TS_ASSERT_EQUALS(1, 2);
TS_ASSERT_EQUALS(1u, 2u);
TS_ASSERT_EQUALS(1.0, 2.0);
}
};
/*
*
* To run this code, first copy it into a file, say, called `TestWritingTests.hpp` in the directory `global/test/`.
* Second, add the full name of your new file to the relevant continuous test pack, say `[path/to/Chaste]/global/test/ContinuousTestPack.txt`.
* Third, from the command line, run
{{{
#!sh
cd [path/to/ChasteBuild]
ccmake [path/to/Chaste]
}}}
* Then press `c` to configure, `e` to exit, and `g` to generate. Finally, run
{{{
#!sh
make global
ctest -V -R TestWritingTests
}}}
*/
#endif /*TESTWRITINGTESTTUTORIAL_HPP_*/
|
#ifndef CPPAST_INTERFACE
#define CPPAST_INTERFACE
#include "AstInterface.h"
class CPPAstInterface : public AstInterface
{
public:
CPPAstInterface(AstInterfaceImpl* _impl) : AstInterface(_impl) {}
//! Check if $n$ is a data member access operator; If yes, grab the object and the field name
bool IsMemberAccess( const AstNodePtr& n, AstNodePtr* obj = 0,
std::string* fieldname = 0);
//Check if $_s$ is a method call; if yes, grab relevant info.
bool IsMemberFunctionCall( const AstNodePtr& n,
AstNodePtr* obj = 0,
std::string* funcname = 0,
AstNodePtr* access = 0,
AstInterface::AstNodeList* args = 0);
AstNodePtr CreateFunctionCall( const AstNodePtr& func,
const AstInterface::AstNodeList& args);
//! Check whether $n$ is a pointer or reference variable reference.
bool IsPointerVariable( const AstNodePtr& n);
AstNodePtr GetVarScope( const AstNodePtr& n);
bool IsPlusPlus( const AstNodePtr& s, AstNodePtr* opd = 0);
};
#endif
|
#include "push.h"
//============================Log===================================
Log::Log(const char *path){
char *pathname=new char[strlen(path)+5]();
strcpy(pathname,path);
file=fopen(strcat(pathname,"/log"),"a");
delete pathname;
}
Log::~Log(){fclose(file);}
void Log::printf(const char *format,...){
time(&t);
tmp=localtime(&t);
strftime(buff,20,"%F %T",tmp);
fprintf(file,"%s ",buff);
va_list args;
va_start(args,format);
vfprintf(file, format, args);
va_end(args);
fflush(file);
}
void Log::flush(){
fflush(file);
}
//============================function===================================
long getCurrentTime(){
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
int set_tcp_keepalive(int sockfd){
int optval = 1;
return setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));
}
int set_tcp_keepalive_cfg(int sockfd, const struct KeepConfig *cfg){
int rc;
//first turn on keepalive
rc = set_tcp_keepalive(sockfd);
if (rc != 0) {
return rc;
}
//set the keepalive options
rc = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT, &cfg->keepcnt, sizeof cfg->keepcnt);
if (rc != 0) {
return rc;
}
rc = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &cfg->keepidle, sizeof cfg->keepidle);
if (rc != 0) {
return rc;
}
rc = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &cfg->keepintvl, sizeof cfg->keepintvl);
if (rc != 0) {
return rc;
}
return 0;
}
int initTcpServer(const char * port){
struct addrinfo *aip;
struct addrinfo hint;
int fd;
memset(&hint,0,sizeof(hint));
hint.ai_flags=AI_PASSIVE;
hint.ai_socktype=SOCK_STREAM;
hint.ai_canonname=NULL;
hint.ai_addr=NULL;
hint.ai_next=NULL;
if((getaddrinfo(NULL,port,&hint,&aip))!=0){
return -1;
}
if((fd=socket(aip->ai_addr->sa_family,SOCK_STREAM,0))<0){
return -1;
}
if((bind(fd,aip->ai_addr,aip->ai_addrlen))<0){
close(fd);
return -1;
}
if((listen(fd,128))<0){
close(fd);
return -1;
}
return fd;
}
int initTcpClient(const char *ip,const char *port){
struct addrinfo *aip;
struct addrinfo hint;
memset(&hint,0,sizeof(hint));
hint.ai_flags=0;
hint.ai_socktype=SOCK_STREAM;
hint.ai_canonname=NULL;
hint.ai_addr=NULL;
hint.ai_next=NULL;
if(getaddrinfo(ip,port,&hint,&aip)!=0){
return -1;
}
int fd;
if((fd=socket(AF_INET,SOCK_STREAM,0))<0)
return -1;
if(connect(fd,aip->ai_addr,aip->ai_addrlen)==0)
return fd;
close(fd);
return -1;
}
int daemonize(const char *cmd){
int i,fd0,fd1,fd2;
pid_t pid;
struct rlimit rl;
struct sigaction sa;
//clear file creation mask.
umask(0);
//get maximum number of file descriptors.
if(getrlimit(RLIMIT_NOFILE,&rl)<0)
return -1;
//become a session leader to lose controlling TTY.
if((pid=fork())<0)
return -1;
else if(pid!=0) //parent
exit(0);
setsid();
//ensure future opens won't allocate controlling TTYs.
sa.sa_handler=SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags=0;
if(sigaction(SIGHUP,&sa,NULL)<0)
return -1;
if((pid=fork())<0)
return -1;
else if(pid!=0) //parent
exit(0);
//change the current working directory to the root so
//we won't prevent file systems from being unmounted.
// if(chdir("/")<0)
// return -1;
//close all open file descriptors.
if(rl.rlim_max==RLIM_INFINITY)
rl.rlim_max=1024;
for(i=0;i<rl.rlim_max;i++)
close(i);
//attach file descriptors 0,1,and 2 to /dev/null.
fd0=open("/dev/null",O_RDWR);
fd1=dup(0);
fd2=dup(0);
//initialize the log file.
openlog(cmd,LOG_CONS,LOG_USER);
if(fd0!=0 || fd1!=1 || fd2!=2){
syslog(LOG_ERR,"unexpected file descriptors %d %d %d",fd0,fd1,fd2);
exit(1);
}
}
|
#ifndef __ANIMATOR_H__
#define __ANIMATOR_H__
#include <string>
#include <vector>
#include "VehicleBase.h"
//==========================================================================
//* This code requires that the VehicleBase class be a super class of
//* any vehicle class(es).
//*
//* Usage:
//* - construct an instance of Animator, passing the number of sections
//* prior to the intersection (e.g., 8 will result in a lane of
//* (8*2) + 2 = 18 sections)
//* - construct four std::vector<VehicleBase*>, one for each direction
//* of westbound, easbound, southbound, and northbound
//* - assign a _pointer_ to each VehicleBase vehicle in your simulation
//* into the entry in the vector corresponding to the section(s)
//* occupied by that vehicle
//* - call each of setVehiclesNorthbound, setVehiclesSouthbound,
//* setVehiclesEastbound, and setVehiclesWestbound, passing the
//* corresponding std::vector<VehicleBase*>
//* - call setLightEastWest and setLightNorthSouth passing the appropriate
//* color (either LightColor::green, LightColor::yellow, LightColor::red)
//* - call draw(), passing in the value of the simulation time clock
//* - then repeat:
//* - update each std::vector<VehicleBase*> appropriately
//* - call each of setVehiclesNorthbound, setVehiclesSouthbound,
//* setVehiclesEastbound, and setVehiclesWestbound, passing the
//* corresponding std::vector<VehicleBase*>
//* - if appropriate, call setLightEastWest and setLightNorthSouth passing
//* the updated color
//* - call draw(), passing in the value of the simulation time clock
//*
//* - added enum classes Direction, VehicleType, and LightColor in
//* VehicleBase.cpp
//* - changed coloring so that originally east/west-bound vehicles are colored
//* via background and originally nort/south-bound vehicles are colored via
//* foreground
//* - added capability for traffic lights display (north/south lights are
//* identical, as are east/west lights)
//==========================================================================
class Animator
{
private:
static int DIGITS_TO_DRAW;
static std::string SECTION_BOUNDARY_EW;
static std::string EMPTY_SECTION;
static const std::string SECTION_BOUNDARY_NS;
static const std::string ERROR_MSG;
static const std::string COLOR_RED_FG;
static const std::string COLOR_GREEN_FG;
static const std::string COLOR_BLUE_FG;
static const std::string COLOR_RED_BG;
static const std::string COLOR_GREEN_BG;
static const std::string COLOR_BLUE_BG;
static const std::string COLOR_YELLOW_BG;
static const std::string COLOR_RESET;
static std::string GREEN_LIGHT;
static std::string YELLOW_LIGHT;
static std::string RED_LIGHT;
std::vector<bool> vehiclesAreSet; // 0:north 1:west 2:south 3:east
int numSectionsBefore;
std::string getVehicleColor(VehicleBase* vptr);
std::string createLight(LightColor color);
std::string getTrafficLight(Direction direction);
void drawNorthPortion(int time);
void drawEastbound();
void drawEastWestBoundary();
void drawWestbound();
void drawSouthPortion();
LightColor northSouthLightColor;
LightColor eastWestLightColor;
std::vector<VehicleBase*> eastToWest;
std::vector<VehicleBase*> westToEast;
std::vector<VehicleBase*> northToSouth;
std::vector<VehicleBase*> southToNorth;
public:
static int MAX_VEHICLE_COUNT;
Animator(int numSectionsBeforeIntersection);
~Animator();
inline void setLightNorthSouth(LightColor color)
{ northSouthLightColor = color; }
inline void setLightEastWest(LightColor color)
{ eastWestLightColor = color; }
inline void setVehiclesNorthbound(std::vector<VehicleBase*> vehicles)
{ southToNorth = vehicles; vehiclesAreSet[0] = true; }
inline void setVehiclesWestbound(std::vector<VehicleBase*> vehicles)
{ eastToWest = vehicles; vehiclesAreSet[1] = true; }
inline void setVehiclesSouthbound(std::vector<VehicleBase*> vehicles)
{ northToSouth = vehicles; vehiclesAreSet[2] = true; }
inline void setVehiclesEastbound(std::vector<VehicleBase*> vehicles)
{ westToEast = vehicles; vehiclesAreSet[3] = true; }
void draw(int time);
};
#endif
|
//
// Created by wqy on 19-11-18.
//
#include "Process.h"
namespace esc{
void Process::setProcessName(string _processName) {
this->processName = _processName;
}
void Process::setAttributes(list<esc::Attribute *> _attributes) {
this->attributes = _attributes;
}
void Process::addAttribute(esc::Attribute *_attribute) {
this->attributes.push_back(_attribute);
}
void Process::setSignals(list<esc::Signal *> _signals) {
this->signals = _signals;
}
void Process::addSignals(esc::Signal *_signal) {
this->signals.push_back(_signal);
}
void Process::setFST(esc::FiniteStateMachine *_fst) {
this->fst = _fst;
}
}
|
#include <iostream>
#include <vector>
using namespace std;
int min(int a, int b, int c) {
return min(a, min(b, c));
}
int m(char a, char b) {
if (a == b) {
return 0;
}
return 1;
}
int main() {
string string1, string2;
cin >> string1 >> string2;
vector<vector<int>> dp(string1.size() + 1, vector<int>(string2.size() + 1));
for (int i = 0; i < string1.size() + 1; i++) {
for (int j = 0; j < string2.size() + 1; j++) {
if (j == 0 && i == 0) {
dp[i][j] = 0;
} else if (j == 0 && i > 0) {
dp[i][j] = i;
} else if (i == 0 && j > 0) {
dp[i][j] = j;
} else {
dp[i][j] = min(dp[i][j - 1] + 1,
dp[i - 1][j] + 1,
dp[i - 1][j - 1] + m(string1[i - 1], string2[j - 1]));
}
}
}
cout << dp[string1.size()][string2.size()];
return 0;
}
|
// Copyright (c) 2019, Alliance for Sustainable Energy, LLC
// 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 copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include "pugixml.hpp"
#include "model.hpp"
int main(int argc, char* argv[])
{
if (argc < 2) {
std::cerr << "usage: airflownetwork <xml>" << std::endl;
return 1;
}
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(argv[1]);
if (!result) {
std::cerr << "Failed to load XML file name \"" << argv[1] << '\"' << std::endl;
}
std::string root_name{ "AirflowNetwork" };
auto afn = doc.child(root_name.c_str());
if (!afn) {
std::cerr << "Failed to find root AirflowNetwork node" << std::endl;
return 1;
}
airflownetwork::Model<size_t, airflownetwork::properties::AIRNET> model("main");
if (!model.load(afn)) {
std::cerr << "Failed to load AirflowNetwork model" << std::endl;
for (auto& mesg : model.errors) {
std::cerr << mesg << std::endl;
}
return 1;
}
int element_count = 0;
std::cout << "Elements ------------- " << std::endl;
for (auto& el : model.powerlaw_elements) {
++element_count;
std::cout << "\tPower Law:" << el.name << std::endl;
}
std::cout << "Found " << element_count << " Element(s)" << std::endl;
int material_count = 0;
std::cout << "Materials ------------ " << std::endl;
for (auto& el : model.materials) {
++material_count;
std::cout << "\tMaterial:" << el.name << std::endl;
}
std::cout << "Found " << material_count << " Material(s)" << std::endl;
int node_count = 0;
std::cout << "Nodes ---------------- " << std::endl;
for (auto& el : model.simulated_nodes) {
std::cout << "\tSimulated:" << el.name << " [" << el.index << ']' << std::endl;
++node_count;
}
for (auto& el : model.fixed_nodes) {
std::cout << "\tFixed:" << el.name << " [" << el.index << ']' << std::endl;
++node_count;
}
for (auto& el : model.calculated_nodes) {
std::cout << "\tCalculated:" << el.name << " [" << el.index << ']' << std::endl;
++node_count;
}
/*
auto nodes = afn.child("Nodes");
if (nodes) {
for (pugi::xml_node el : nodes.children("Node")) {
++node_count;
std::string name;
auto attr = el.attribute("ID");
if (attr) {
name = attr.as_string();
} else {
// Error
}
std::cout << '\t' << name << '(' << name.length() << ')' << std::endl;
//for (auto i = 0; i < name.length(); i++) {
// std::cout << std::hex << (short)name[i] << std::endl;
//}
}
}
*/
std::cout << "Found " << node_count << " Node(s)" << std::endl;
int link_count = 0;
std::cout << "Links ---------------- " << std::endl;
for (auto& el : model.links) {
++link_count;
std::cout << '\t' << el.name << '(' << el.node0.name << "--" << el.element.name << "-->" << el.node1.name << "), ["
<< el.index0 << ',' << el.index1 << ']' << std::endl;
}
std::cout << "Found " << link_count << " Link(s)" << std::endl;
if (!model.validate_network()) {
for (auto& mesg : model.errors) {
std::cerr << mesg << std::endl;
}
return 1;
}
model.linear_initialize();
//model.save("out.xml");
model.open_output("output");
model.write_output(0.0);
model.steady_solve();
model.write_output(0.0);
model.close_output();
return 0;
}
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Francisco Eduardo Balart Sanchez <balart40@hotmail.com>
* This is a extended documentation of the original file manet-2015.cc provided
* by Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
* At: http://www.uio.no/studier/emner/matnat/ifi/INF5090/h15/timeplan/handouts/
*/
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/mobility-module.h"
#include "ns3/stats-module.h"
#include "ns3/wifi-module.h"
#include "ns3/internet-module.h"
//#include "ns3/point-to-point-module.h"
#include "ns3/olsr-module.h"
#include "ns3/netanim-module.h"
#include <iostream>
// declares a logging component called febalart_manet_v1 that allows you to enable and
// disable console message logging by reference to the name
NS_LOG_COMPONENT_DEFINE ("febalart_manet_v1");
// This groups all ns-3-related declarations in a scope outside the global namespace
using namespace ns3;
// Simulation parameters
int nodeSpacing = 100; // meters
int cols = 5;
int numNodes = 25;
int sourceNode = 0;
int destinationNode = 24;
int packetRate = 20; // packet per second
int packetSize = 500; // bytes
bool enablePcap = true;// Generate pcap file containing link-level data
// stored as prefix-nodeid-deviceid.pcap
bool showSimTime = true;
int duration = 600; // seconds
int seed = 1;
int run = 1;
// To show simulated time. Sent to STDERR to separation
// from other output (e.g., visualization trace)
void PrintSeconds(void) {
std::cerr << Simulator::Now() << std::endl;
Simulator::Schedule(Seconds(1), &PrintSeconds);
}
void RouteChange(std::string source, uint32_t size) {
std::cout << "Routechange at " << source << ", new size: " << size << std::endl;
}
int main (int argc, char *argv[])
{
// Default time resolution is in nano seconds NS but also is available
// Y, D, H, MIN, S, MS, US, NS, PS, FS
// year, day, hours, minutes, seconds, miliseconds, nano seconds, pico seconds, femto seconds
Time::SetResolution (Time::NS);
// setting verbosity for logs
// Level asssociated macro enable with
// LOG_ERROR -> NS_LOG_ERROR -> LOG_LEVEL_ERROR
// LOG_WARN -> NS_LOG_WARN -> LOG_LEVEL_WARN
// LOG_DEBUG -> NS_LOG_DEBUG -> LOG_LEVEL_DEBUG
// LOG_INFO -> NS_LOG_INFO -> LOG_LEVEL_INFO
// LOG_FUNCTION -> NS_LOG_FUNCTION -> LOG_LEVEL_FUNCTION
// NS_LOG_FUNCTION_NOARGS
// LOG_LOGIC -> NS_LOG_LOGIC -> LOG_LEVEL_LOGIC
// LOG_ALL -> no associated macro -> LOG_LEVEL_ALL
// EXAMPLE: LOG_LEVEL_INFO will enable msgs provyded by NS_LOG DEBUG, WARN and ERROR macros
//LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
//LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
LogComponentEnable ("febalart_manet_v1", LOG_LEVEL_INFO);
// Obtain command line arguments
CommandLine cmd;
cmd.AddValue ("cols", "Columns of nodes", cols);
cmd.AddValue ("numnodes", "Number of nodes", numNodes);
cmd.AddValue ("spacing", "Spacing between neighbouring nodes", nodeSpacing);
cmd.AddValue ("duration", "Duration of simulation", duration);
cmd.AddValue ("seed", "Random seed for simulation", seed);
cmd.AddValue ("run", "Simulation run", run);
cmd.AddValue ("packetrate", "Packets transmitted per second", packetRate);
cmd.AddValue ("packetsize", "Packet size", packetSize);
cmd.AddValue ("sourcenode", "Number of source node", sourceNode);
cmd.AddValue ("destinationnode", "Number of destination node", destinationNode);
cmd.AddValue ("showtime", "Whether or not to show simulation as simulation progresses (default = true)", showSimTime);
cmd.Parse (argc,argv);
int rows = ((int) numNodes / cols) + 1;
// Set default parameter values
// If the size of the PSDU is bigger than this value, we fragment it such that the size of the fragments are equal or smaller
Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
// If the size of the PSDU is bigger than this value, we use an RTS/CTS handshake before sending the data frame
Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2200"));
// Set random seed and run number
SeedManager::SetSeed (seed);
SeedManager::SetRun(run);
// create instance of nodecontainer called "nodes"
// originally NodeContainer c
NodeContainer nodes;
// create numNodes nodes
nodes.Create (numNodes);
// Set up physical and mac layers
WifiHelper wifi = WifiHelper::Default ();
// Function receives enum which is mapped according below
// WIFI_PHY_STANDARD_80211a -> OFDM PHY for the 5 GHz band (Clause 17)
// WIFI_PHY_STANDARD_80211b -> DSSS PHY (Clause 15) and HR/DSSS PHY (Clause 18
// WIFI_PHY_STANDARD_80211g -> ERP-OFDM PHY (Clause 19, Section 19.5)
// WIFI_PHY_STANDARD_80211_10MHZ -> OFDM PHY for the 5 GHz band (Clause 17 with 10 MHz channel bandwidth)
// WIFI_PHY_STANDARD_80211_5MHZ -> OFDM PHY for the 5 GHz band (Clause 17 with 5 MHz channel bandwidth)
// WIFI_PHY_STANDARD_holland -> This is intended to be the configuration used in this paper: Gavin Holland, Nitin Vaidya and Paramvir
// Bahl, "A Rate-Adaptive MAC Protocol for Multi-Hop Wireless Networks", in Proc.
// WIFI_PHY_STANDARD_80211n_2_4GHZ -> HT OFDM PHY for the 2.4 GHz band (clause 20)
// WIFI_PHY_STANDARD_80211n_5GHZ -> HT OFDM PHY for the 2.4 GHz band (clause 20)
// WIFI_PHY_STANDARD_80211ac -> VHT OFDM PHY (clause 22)
wifi.SetStandard (WIFI_PHY_STANDARD_80211g);
// Also available ns3::MinstrelHtWifiManager,
// ns3::MinstrelWifiManager,
// ns3::AparfWifiManager,
// ns3::ArfWifiManager, -> ARF rate control algorithm (Automatic Rate Fallback)
// ns3::AarfcdWifiManager,
// ns3::RraaWifiManager,
// ns3::ParfWifiManager,
// ns3::ArfWifiManager,
// ns3::IdealWifiManager,
// ns3::OnoeWifiManager,
// ns3::AmrrWifiManager,
// ns3::CaraWifiManager,
// ns3::AarfWifiManager,
// ns3::ConstantRateWifiManager.
wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
// Create non QoS-enabled MAC layer for a ns3::WifiNetDevice
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
// This class can create MACs of type: with QosSupported attribute set to False
// ns3::ApWifiMac
// ns3::StaWifiMac
// ns3::AdhocWifiMac
wifiMac.SetType ("ns3::AdhocWifiMac");
// Create and manage PHY objets for the Yans model
// YAN: Yet Another Network at http://cutebugs.net/files/wns2-yans.pdf
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
// Manage and create wifi channel objects for tha yans model
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
// Create another manager for PHY objects of Yans model called phy equal to the already created wifiphy
YansWifiPhyHelper phy = wifiPhy;
// Every PHY created by a call to install is associated with this channel
// wifichannel create a new channel
phy.SetChannel (wifiChannel.Create ());
// Create wifi network with PHY helper for PHY objects, MAC helper for MAC objects and Nodes on which a wifi device will be created
// install used is the one that use c nodes
NetDeviceContainer devices = wifi.Install (phy, wifiMac, nodes);
if(enablePcap)
wifiPhy.EnablePcap ("febalart_manet_v1", devices);
// Set up routing and Internet stack
// Also available: OlsrHelper, AodvHelper,
ns3::OlsrHelper olsr;
// aggregate IP/TCP/UDP functionality to existing Nodes
InternetStackHelper internet;
// routing helper during install, create object of tyep ns3::Ipv4RoutingProtocol per Node
internet.SetRoutingHelper(olsr);
// for each node the input container aggregate implementatoin of ns3::Ipv4,Ipv6,Udp,Tcp classes
internet.Install (nodes);
// Assign addresses
Ipv4AddressHelper address;
// Ipv4Adress network, Ipv4Mask Maskm Ipv4Address base = 0.0.0.1
address.SetBase ("10.0.0.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
// Server/Receiver
// create udpserverhelper number is supposed to be the port the server will wait on for incomming packets
UdpServerHelper server (4000);
ApplicationContainer apps = server.Install (nodes.Get(destinationNode));
// start at second 1
apps.Start (Seconds (1));
// stop at the duration specified
apps.Stop (Seconds (duration - 1));
// Client/Sender
UdpClientHelper client (interfaces.GetAddress (destinationNode), 4000);
client.SetAttribute ("MaxPackets", UintegerValue (100000000));
// interval of packets sent
client.SetAttribute ("Interval", TimeValue (Seconds(1 / ((double) packetRate))));
client.SetAttribute ("PacketSize", UintegerValue (packetSize));
apps = client.Install (nodes.Get (sourceNode));
apps.Start (Seconds (1));
apps.Stop (Seconds (duration - 1));
// Set up mobility
MobilityHelper mobility;
// There is also available ns3::GridPositionAllocator, ns3::UniformDiscPositionAllocator, ns3::RandomDiscPositionAllocator,
// ns3::RandomBoxPositionAllocator, ns3::RandomRectanglePositionAllocator, ns3::FixedRoomPositionAllocator, ns3::GridPositionAllocator,
// ns3::SameRoomPositionAllocator, ns3::RandomRoomPositionAllocator, ns3::ListPositionAllocator, and ns3::RandomBuildingPositionAllocator.
mobility.SetPositionAllocator ("ns3::GridPositionAllocator","MinX", DoubleValue (1.0),"MinY", DoubleValue (1.0),
"DeltaX", DoubleValue(nodeSpacing),"DeltaY", DoubleValue (nodeSpacing),"GridWidth", UintegerValue (cols));
// There is also vailable ns3: ConstantAccelerationMobilityModel ConstantPositionMobilityModel ConstantVelocityHelper
// ConstantVelocityMobilityModel GaussMarkovMobilityModel GeographicPositions GridPositionAllocator HierarchicalMobilityModel
// ListPositionAllocator MobilityHelper MobilityModel Ns2MobilityHelper
mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel","Bounds",
RectangleValue (Rectangle (0,(cols * nodeSpacing) + 1, 0,(rows * nodeSpacing) + 1)),
"Speed", StringValue("ns3::UniformRandomVariable[Min=5.0,Max=10.0]"),
"Distance", DoubleValue(30));
mobility.Install (nodes);
// Schedule final events and start simulation
// Print simulated time
if(showSimTime)
Simulator::Schedule(Seconds(1), &PrintSeconds);
Simulator::Stop(Seconds(duration));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
|
/***************************************************************************
Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD
FileName: RTPPacketResender.h
Description: RTPPacketResender class to buffer and track(缓存并追踪)re-transmits of RTP packets..
Comment: copy from Darwin Streaming Server 5.5.5
Author: taoyunxing@dadimedia.com
Version: v1.0.0.1
CreateDate: 2010-08-16
LastUpdate: 2011-07-03
****************************************************************************/
#ifndef __RTP_PACKET_RESENDER_H__
#define __RTP_PACKET_RESENDER_H__
#include "RTPBandwidthTracker.h"/* 用于拥塞控制 */
#include "PLDoubleLinkedList.h"
#include "DssStopwatch.h"
#include "UDPSocket.h"
#include "OSMemory.h"
#include "OSBufferPool.h"
#include "OSMutex.h"
/* 调试开关,必须关闭,否则会在点播结束后再打开,会造成段错误 */
#define RTP_PACKET_RESENDER_DEBUGGING 0
class MyAckListLog;
/* 重传RTP包结构体,记录了一个重传RTP Packet的相关信息,但没有存放真正的包数据 */
class RTPResenderEntry
{
public:
/* 存放重传包的数据的指针,它指向外部的缓存片段队列OSBufferPool(每个缓存片段是1600字节),当该大小超过1600字节时,要再专门分配一块special buffer来存放该数据 */
void* fPacketData;
/* 重传包的实际大小 */
UInt32 fPacketSize;
/* 是特地分配的专门缓存(在OSBufferPool之外)吗?参见RTPPacketResender::GetEmptyEntry() */
Bool16 fIsSpecialBuffer;
/* 过期时间,超过了当前RTO */
SInt64 fExpireTime;
/* 当加入该重传RTP包时的当前时间戳,用于计算超时,参见RTPPacketResender::AddPacket() */
SInt64 fAddedTime;
/* 该包的RTO,由fBandwidthTracker->CurRetransmitTimeout()得到,参见RTPPacketResender::AddPacket() */
SInt64 fOrigRetransTimeout;
/* 该RTP包重传次数,参见RTPPacketResender::AckPacket()/ResendDueEntries() */
UInt32 fNumResends;
/* 该RTP重传包的序列号,参见RTPPacketResender::GetEmptyEntry()/AddPacket() */
UInt16 fSeqNum;
#if RTP_PACKET_RESENDER_DEBUGGING
/* 当加入该RTP包时,包数组的大小 */
UInt32 fPacketArraySizeWhenAdded;
#endif
};
class RTPPacketResender
{
public:
RTPPacketResender();
~RTPPacketResender();
// These must be called before using the object,参见RTPStream::Setup()
void SetDestination(UDPSocket* inOutputSocket, UInt32 inDestAddr, UInt16 inDestPort);
/* 设置fBandwidthTracker */
void SetBandwidthTracker(RTPBandwidthTracker* inTracker) { fBandwidthTracker = inTracker; }
// AddPacket adds a new packet to the resend queue. This will not send the packet.AddPacket itself is not thread safe.
void AddPacket( void * rtpPacket, UInt32 packetSize, SInt32 ageLimitInMsec );
// Acks a packet. Also not thread safe.
void AckPacket( UInt16 sequenceNumber, SInt64& inCurTimeInMsec );
// Resends outstanding packets in the queue. Guess what. Not thread safe.
void ResendDueEntries();
// Clear outstanding packets - if we no longer care about any of the outstanding, unacked packets
void ClearOutstandingPackets();
// ACCESSORS
Bool16 IsFlowControlled() { return fBandwidthTracker->IsFlowControlled(); }/* 是否采用流控?实质上引用的是RTPBandwithTracker::IsFlowControlled() */
SInt32 GetMaxPacketsInList() { return fMaxPacketsInList; }
SInt32 GetNumPacketsInList() { return fPacketsInList; }
SInt32 GetNumResends() { return fNumResends; }
static UInt32 GetNumRetransmitBuffers() { return sBufferPool.GetTotalNumBuffers(); }/* 对OSBufferPool的查询,得到UDP buffer个数,参见QTSServerInterface::GetNumUDPBuffers() */
static UInt32 GetWastedBufferBytes() { return sNumWastedBytes; }/* 参见QTSServerInterface::GetNumWastedBytes() */
#if RTP_PACKET_RESENDER_DEBUGGING
void SetDebugInfo(UInt32 trackID, UInt16 remoteRTCPPort, UInt32 curPacketDelay);
void SetLog( StrPtrLen *logname );
UInt32 SpillGuts(UInt32 inBytesSentThisInterval);
void LogClose(SInt64 inTimeSpentInFlowControl);
void logprintf( const char * format, ... ); /* 写日志文件,并打印日志信息到屏幕 */
#else
void SetLog( StrPtrLen * /*logname*/) {}
#endif
private:
// Tracking the capacity of the network
/************************** 用于拥塞控制的类 ***********************/
/* 在RUDP传输过程中,RTPPacketResender类和RTPBandwidthTracker类是保证QoS的至关重要的两个类。 */
RTPBandwidthTracker* fBandwidthTracker;
/************************** 用于拥塞控制的类 ***********************/
// Who to send to
UDPSocket* fSocket;/* 给对方client发送RTP数据的Server端的socket(对) */
UInt32 fDestAddr;/* client端的ip&port */
UInt16 fDestPort;
/* 已经重传重传包的总词数,注意RTPResenderEntry中也有一个同名的量 */
UInt32 fNumResends; // how many total retransmitted packets
/* 丢弃包总数=因超时太多不把其放在重发队列里的包个数+已在队列里但被放弃重发的包个数。 */
UInt32 fNumExpired; // how many total packets dropped,过期包总数
/* 过期了,不在重发包数组中,但收到Ack的包的总个数,参见RTPPacketResender::AckPacket() */
UInt32 fNumAcksForMissingPackets; // how many acks received in the case where the packet was not in the list
/* 总的重传次数,不管是否真的重传,参见RTPPacketResender::AddPacket() */
UInt32 fNumSent; // how many packets sent
#if RTP_PACKET_RESENDER_DEBUGGING
MyAckListLog *fLogger; /* 用到的日志文件类 */
UInt32 fTrackID; /* RTPStream所在track ID */
UInt16 fRemoteRTCPPort; /* Client端的RTCP端口 */
UInt32 fCurrentPacketDelay;/* 当前RTP数据包的延时 */
DssDurationTimer fInfoDisplayTimer;
#endif
RTPResenderEntry* fPacketArray; /* 重传包数组,引用上面的RTP Resender Packet类对象 */
UInt32 fPacketArraySize; /* 上述重传包数组的大小,default值为64,增量是32,所以只能为64,92,...,参见RTPPacketResender::RTPPacketResender()/GetEmptyEntry() */
UInt32 fPacketArrayMask;
UInt32 fMaxPacketsInList;/* 似乎很少用到,链表中的最大包大小 */
UInt32 fPacketsInList; /* 在重传包数组中当前存放数据包的个数,从1计数,注意这个量非常重要!! */
UInt16 fStartSeqNum; /* 起始包的序列号 */
UInt16 fHighestSeqNum;/* 重传包的最大序列号 */
UInt32 fLastUsed; /* 下次复用的重传RTP包的Index,从0开始,参见RTPPacketResender::GetEmptyEntry() */
OSMutex fPacketQMutex;/* 重传包队列的Mutex */
/* 由索引或序列号检索重传包数组中的重传包 */
RTPResenderEntry* GetEntryByIndex(UInt16 inIndex);
RTPResenderEntry* GetEntryBySeqNum(UInt16 inSeqNum);
/* 在重传包数组中找到一个EmptyEntry,存放指定的RTP重传包信息,同时将它的包数据存入OSBufferPool,或者是另外创建的special buffer */
RTPResenderEntry* GetEmptyEntry(UInt16 inSeqNum, UInt32 inPacketSize);
void ReallocatePacketArray(); /* 没有源码实现 */
void UpdateCongestionWindow(SInt32 bytesToOpenBy );/* 没有源码实现 */
void RemovePacket(RTPResenderEntry* inEntry); /* 没有源码实现 */
/* 找到第一个入参指定的重传包位置,移其数据进OSBufferPool.若第二个入参指明要重用该包位置,缩减重传包数组,经最后元移到当前包位置;若不重用该位置,
则直接清空窗口数据 */
void RemovePacket(UInt32 packetIndex, Bool16 reuse=true);
static OSBufferPool sBufferPool; /* 存放重传包队列中重传包的真正数据的缓存池,用到OSBufferPool类 */
static unsigned int sNumWastedBytes;/* 统计浪费的字节总数(每个包未填满的部分之和) */
};
#endif //__RTP_PACKET_RESENDER_H__
|
#include <iostream>
#include <queue>
using namespace std;
class Node
{
public :
int value;
Node* left; //allocate size = 8 byte
Node* right;
};
class BinarySearchTree
{
public :
Node* root;
BinarySearchTree()
{
root = NULL; //to set to 0
}
void Insert(int value)
{
Insert(root, value);
}
void Insert(Node* &node, int value)
{
//! if the node is NULL, create a new node
if(node == NULL)
{
node = new Node();
node->value = value;
node->left = NULL;
node->right = NULL;
cout << "Node address : " << &node << endl;
cout << "Node value : " << node->value << endl;
}
else if(value < node->value)
{
cout << value << " Left " << &(node->left) << endl;
Insert(node->left, value);//! recursive function -- a function that call itself
}
else
{
cout << value << " Right " << &(node->right) << endl;
Insert(node->right, value);
}
}
void DisplayBFSLevelOrder(Node* node)
{
queue<Node*> b;
if(node)
{
b.push(node);
}
while(!b.empty())
{
Node* node = b.front();
cout << node->value << endl;
if(node->left)
{
b.push(node->left);
}
if(node->right)
{
b.push(node->right);
}
b.pop();
}
//! 1. Always try to go left first
//! 2. If there are no more left, then display current node
//! 3. Then try to go right first
//! 4. If has not been displayed yet, then display current node
}
void DisplayDFSPreOrder(Node* node)
{
bool isDisplayed = false;
cout << node->value << endl;
if(node->left != NULL)
{
DisplayDFSPreOrder(node->left);
}
if(node->right != NULL)
{
DisplayDFSPreOrder(node->right);
}
}
void DisplayDFSInOrder(Node* node)
{
bool isDisplayed = false;
if(node->left != NULL)
{
DisplayDFSInOrder(node->left);
}
cout << node->value << endl;
if(node->right != NULL)
{
DisplayDFSInOrder(node->right);
}
}
void DisplayDFSPostOrder(Node* node)
{
bool isDisplayed = false;
if(node->left != NULL)
{
DisplayDFSPostOrder(node->left);
}
if(node->right != NULL)
{
DisplayDFSPostOrder(node->right);
}
cout << node->value << endl;
}
};
int main()
{
BinarySearchTree* tree = new BinarySearchTree();
tree->Insert(43);
tree->Insert(17);
tree->Insert(52);
tree->Insert(8);
tree->Insert(12);
tree->Insert(29);
tree->Insert(65);
tree->Insert(93);
tree->Insert(58);
tree->Insert(77);
tree->Insert(2);
tree->Insert(84);
cout << endl;
cout << "==============================" << endl;
cout << " *Display BFS Level Order* " << endl;
cout << "==============================" << endl;
tree->DisplayBFSLevelOrder(tree->root);
cout << endl;
cout << "==============================" << endl;
cout << " *Display DFS Pre Order* " << endl;
cout << "==============================" << endl;
tree->DisplayDFSPreOrder(tree->root);
cout << endl;
cout << "==============================" << endl;
cout << " *Display DFS In Order* " << endl;
cout << "==============================" << endl;
tree->DisplayDFSInOrder(tree->root);
cout << endl;
cout << "==============================" << endl;
cout << " *Display DFS Post Order* " << endl;
cout << "==============================" << endl;
tree->DisplayDFSPostOrder(tree->root);
return 0;
}
//! Name : Muhamad Luqman bin Shamsuddin
//! Student ID : 0114642
|
/*
* Copyright 2016-2017 Flatiron Institute, Simons Foundation
*
* 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 MVTEMPLATESVIEW2PANEL_H
#define MVTEMPLATESVIEW2PANEL_H
#include "paintlayer.h"
#include <QWidget>
#include <mda.h>
#include <mvcontext.h>
class MVTemplatesView2PanelPrivate;
class MVTemplatesView2Panel : public PaintLayer {
public:
friend class MVTemplatesView2PanelPrivate;
MVTemplatesView2Panel();
virtual ~MVTemplatesView2Panel();
void setTemplate(const Mda& X);
void setElectrodeGeometry(const ElectrodeGeometry& geom);
void setVerticalScaleFactor(double factor);
void setChannelColors(const QList<QColor>& colors);
void setColors(const QMap<QString, QColor>& colors);
void setCurrent(bool val);
void setSelected(bool val);
void setTitle(const QString& txt);
void setFiringRateDiskDiameter(double val);
protected:
void paint(QPainter* painter) Q_DECL_OVERRIDE;
private:
MVTemplatesView2PanelPrivate* d;
};
#endif // MVTEMPLATESVIEW2PANEL_H
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CorriasBuistSMCModified_HPP_
#define CorriasBuistSMCModified_HPP_
#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>
#include "AbstractCardiacCell.hpp"
#include "AbstractStimulusFunction.hpp"
/**
* This class is a modified version of the model of a gastric
* Smooth Muscle Cell.
*
* Reference publication is:
*
* Corrias A, Buist ML.
* "A quantitative model of gastric smooth muscle cellular activation."
* Ann Biomed Eng. 2007 Sep;35(9):1595-607. Epub 2007 May 8.
*
* Modifications include:
* - ability to include/exclude built-in fake ICC stimulus
* - ability to set K+ channels-affecting CO concentrations
*/
class CorriasBuistSMCModified : public AbstractCardiacCell
{
friend class boost::serialization::access;
/**
* Boost Serialization method for archiving/checkpointing.
* Archives the object and its member variables.
*
* @param archive The boost archive.
* @param version The current version of this class.
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
archive & boost::serialization::base_object<AbstractCardiacCell >(*this);
}
private:
/**
* Scale factor for CO-affected currents
* Note that this the number that multiply the currents, hence it is not [CO],
* but a function of [CO] (for example, 2.8*[CO] - 0.1)
*/
double mScaleFactorCarbonMonoxide;
/**
* True if the fake built-in ICC stimulus is present
*/
bool mFakeIccStimulusPresent;
double Cm;/**< membrane capacitance, pF*/
double Asurf_in_cm_square;/**< Surface area in cm^2*/
double Asurf;/**< surface area (mm^2)*/
double VolCell;/**< cell volume (mm^3)*/
double hCa;/**< conc for half inactivation of fCa */
double sCa;/**< lope factor for inactivation of fCa */
/* concentrations */
double Ki; /**< intra K conc (mM)*/
double Nai; /**< intra Na conc (mM)*/
double ACh; /**< acetylcholine conc (mM)*/
double CaiRest; /**< baseline Ca conc (mM)*/
/* maximum conductances*/
double gLVA_max; /**< max conductance of ILVA*/ // (0.18 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
double gCaL_max; /**< max conductance of ICaL*/ // (65.0 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
double gBK_max; /**< max conductance of IBK)*/ // (45.7 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
double gKb_max; /**< max conductance of IKb*/ // (0.0144 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
double gKA_max; /**< max conductance of IKA*/ // (9.0 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
double gKr_max; /**< max conductance of IKr*/ // (35.0 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
double gNa_max; /**< max conductance of INa*/ // (3.0 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
double gnsCC_max; /**< max conductance of InsCC*/ // (50.0 nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
double gcouple; /**< coupling conductance bewteen fake ICC and SMC*/ // 1.3 nS * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
double JCaExt_max; /**< max flux of CaSR (mM/ms)*/
/* Temperature corrections */
double Q10Ca; /**< (dim)*/
double Q10K; /**< (dim)*/ //1.365
double Q10Na; /**< (dim)*/
double Texp; /**< (degK)*/
double T_correct_Ca ;/**< temperature correction for Ca (dim)*/
double T_correct_K ; /**< temperature correction for K (dim)*/
double T_correct_Na;/**< temperature correction for Na (dim)*/
double T_correct_gBK; /**< temperature correction for gBK*/ // (nS) * 1e-6 (mS/nS) / Asurf (mm2) = mS/mm2
/* Nernst potentials */
double EK; /**< Nernst potential for K (mV)*/
double ENa ; /**< Nernst potential for Na (mV)*/
double EnsCC; /**< Nernst potential for nsCC (mV)*/
double Ca_o; /**< mM */
double K_o; /**< mM */
double Na_o; /**< mM */
/* Nernst parameters */
double R; /**< pJ/nmol/K*/
double T; /**< degK*/
double F; /**< nC/nmol*/
double FoRT; /**< 1/mV*/
double RToF; /**< mV*/
public:
/**
* Constructor
*
* @param pSolver is a pointer to the ODE solver
* @param pIntracellularStimulus is a pointer to the intracellular stimulus
*/
CorriasBuistSMCModified(boost::shared_ptr<AbstractIvpOdeSolver> pSolver, boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus);
/**
* Destructor
*/
~CorriasBuistSMCModified();
/**
* Now empty
*/
void VerifyStateVariables();
/**
* Calculates the ionic current
*
* @param pStateVariables the state variables of this model
* @return the total ionic current
*/
double GetIIonic(const std::vector<double>* pStateVariables=NULL);
/**
* Compute the RHS of the FitHugh-Nagumo system of ODEs
*
* @param time the current time, in milliseconds
* @param rY current values of the state variables
* @param rDY to be filled in with derivatives
*/
void EvaluateYDerivatives(double time, const std::vector<double>& rY, std::vector<double>& rDY);
/**
* Set whether we want the fake ICC stimulus or not.
* It changes the member variable mFakeIccStimulusPresent (which is true by default).
*
* @param present - true if we want the fake ICC stimulus, false otherwise
*/
void SetFakeIccStimulusPresent(bool present);
/**
* @return true if the fake ICC stimulus is present
*/
bool GetFakeIccStimulusPresent();
/**
* @return the Carbon Monoxide scale for
*/
double SetCarbonMonoxideScaleFactor();
/**
* Set the carbon monoxide scale factor.
* This will multiply the following currents: I_kr, I_Ka, Ibk
*
* @param scaleFactor the scale factor that multiply the currents.
*/
void SetCarbonMonoxideScaleFactor(double scaleFactor);
/**
* @return the Carbon Monoxide scale factor
*/
double GetCarbonMonoxideScaleFactor();
};
// Needs to be included last
#include "SerializationExportWrapper.hpp"
CHASTE_CLASS_EXPORT(CorriasBuistSMCModified)
namespace boost
{
namespace serialization
{
template<class Archive>
inline void save_construct_data(
Archive & ar, const CorriasBuistSMCModified * t, const unsigned int fileVersion)
{
const boost::shared_ptr<AbstractIvpOdeSolver> p_solver = t->GetSolver();
const boost::shared_ptr<AbstractStimulusFunction> p_stimulus = t->GetStimulusFunction();
ar << p_solver;
ar << p_stimulus;
}
template<class Archive>
inline void load_construct_data(
Archive & ar, CorriasBuistSMCModified * t, const unsigned int fileVersion)
{
boost::shared_ptr<AbstractIvpOdeSolver> p_solver;
boost::shared_ptr<AbstractStimulusFunction> p_stimulus;
ar >> p_solver;
ar >> p_stimulus;
::new(t)CorriasBuistSMCModified(p_solver, p_stimulus);
}
}
}
#endif // CorriasBuistSMCModified_HPP_
|
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
list<int> li{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int main() {
// 鉴规氢 立辟
for (auto it = li.begin(); it != li.end(); it++) {
printf("%d, ", *it);
}
// 开规氢 立辟
for (auto it = li.end(); it!=li.begin(); it--) {
--it;
}
auto it = li.begin();
// return X
advance(it, 3);
puts("");
printf("advaned 3 : %d\n", *it);
// return it
list<int>::iterator it2 = next(it, 2);
printf("next 2 : %d\n", *it2);
// return it
list<int>::iterator it3 = prev(it2, 1);
printf("prev 1 : %d\n", *it3);
auto it4 = li.begin();
(*it4)=0;
printf("it value change : %d\n", *it4);
return 0;
}
|
#include <cstdint>
#include "Types.hpp"
//#include "NewOrder.cpp"
const int32_t warehouses=5;
int32_t random(){ return rand();}
int32_t urand(int32_t min,int32_t max) {
return (random()%(max-min+1))+min;
}
int32_t urandexcept(int32_t min,int32_t max,int32_t v) {
if (max<=min)
return min;
int32_t r=(random()%(max-min))+min;
if (r>=v)
return r+1; else
return r;
}
int32_t nurand(int32_t A,int32_t x,int32_t y) {
return ((((random()%A)|(random()%(y-x+1)+x))+42)%(y-x+1))+x;
}
void newOrderRandom(Timestamp now,int32_t w_id) {
int32_t d_id=urand(1,1);
int32_t c_id=nurand(1023,1,3000);
int32_t ol_cnt=urand(5,15);
int32_t supware[15];
int32_t itemid[15];
int32_t qty[15];
for (int32_t i=0; i<ol_cnt; i++) {
if (urand(1,100)>1)
supware[i]=w_id; else
supware[i]=urandexcept(1,warehouses,w_id);
itemid[i]=nurand(8191,1,100000);
qty[i]=urand(1,10);
}
newOrder(w_id,d_id,c_id,ol_cnt,supware,itemid,qty,now);
}
int main(){
customer_loader();
stock_loader();
orderline_loader();
order_loader();
warehouse_loader();
district_loader();
history_loader();
neworder_loader();
item_loader();
Timestamp now = time(NULL);
int32_t w_id = (int32_t)random();
newOrderRandom(now,w_id);
return 0;
}
|
#ifndef LIGHT_H
#define LIGHT_H
#include "SceneGraph.hpp"
#include <glm/glm.hpp>
class DirLight : public Light
{
public:
DirLight(const glm::vec3 & inDir, const glm::vec3 & inColor);
glm::vec3 color;
glm::vec3 dir;
};
#endif
|
#include "SuffixTree.h"
SuffixTree::SuffixTree(const char* dotFileName) {
dotFile = NULL;
if(dotFileName)
dotFile = fopen(dotFileName, "w");
}
void SuffixTree::serialize(Compressor* compressor) {
//Escreve o tamanho do texto e o texto
compressor->feedRawBits(n, 32);
int tot = n + nodes.size(), saved = 0, percentageToPrint = 0;
for(int i = 0; i < n; ++i) {
compressor->feedRawBits(text[i], 8);
++saved;
if(percentageToPrint <= saved) {
printf("\r%.2lf%% concluído", double(saved)/tot * 100);
fflush(stdout);
percentageToPrint += tot/10;
}
}
int sizeOfIntegers = SIZE_IN_BITS(int(n-1));
//Escreve a quantidade de nós
compressor->feedRawBits(nodes.size(), 32);
/*
* Preciso de uma fila de inteiros que possa comportar,
* no pior caso, todos os nós da árvore. Mas, ao invés
* de criar um outro array ou utilizar uma queue<int>
* da STL de c++, vou reutilizar o vector 'nodes'.
* Mais precisamente, vou utilizar o campo 'sl'
* dos nós. Note que esse campo não é mais necessário.
*/
int ini = 0, end = 0; //início e fim da fila
//Serializa a raiz
compressor->feedRawBits(nodes[0].start, sizeOfIntegers);
compressor->feedRawBits(nodes[0].end, sizeOfIntegers);
nodes[end++].sl = 0; //coloquei o '0' na fila
++saved;
while(ini < end) { //fila não vazia
int cur = nodes[ini++].sl; //pega a cabeça da fila e a remove
for(int nt = nodes[cur].firstChild; nt != -1; nt = nodes[nt].sibling) {
compressor->feedRawBits(0,1);
compressor->feedRawBits(nodes[nt].start, sizeOfIntegers);
compressor->feedRawBits(nodes[nt].end == -1 ? n-1 : nodes[nt].end, sizeOfIntegers);
nodes[end++].sl = nt; //coloca 'nt' na fila
++saved;
if(percentageToPrint <= saved) {
printf("\r%.2lf%% concluído", double(saved)/tot * 100);
fflush(stdout);
percentageToPrint += tot/10;
}
}
compressor->feedRawBits(1,1);
}
printf("\n");
}
void SuffixTree::deserialize(Decompressor* decompressor) {
n = decompressor->readBits(32);
int tot = n, percentageToPrint = 0;
char* tmp = new char[n];
for(int i = 0; i < n; ++i) {
tmp[i] = decompressor->readBits(8);
if(i >= percentageToPrint) {
printf("\rDescomprimindo string ... %.2lf%% concluído", 100 * double(i) / tot);
fflush(stdout);
percentageToPrint += n / 10;
}
}
printf("\n");
tmp[n-1] = 0;
text = tmp;
int totalOfNodes = decompressor->readBits(32), sizeOfIntegers = SIZE_IN_BITS(int(n-1));
nodes.resize(totalOfNodes);
tot = totalOfNodes, percentageToPrint = 0;
queue<int> queue;
int start = decompressor->readBits(sizeOfIntegers), end = decompressor->readBits(sizeOfIntegers), curSize = 1;
nodes[0] = SuffixTreeNode(start, end);
queue.push(0);
while(!queue.empty()) {
bool endOfChildren = decompressor->readBits(1);
if(endOfChildren)
queue.pop();
else {
start = decompressor->readBits(sizeOfIntegers);
end = decompressor->readBits(sizeOfIntegers);
nodes[curSize] = SuffixTreeNode(start, end);
nodes[queue.front()].addChild(curSize, nodes[curSize]);
queue.push(curSize++);
if(curSize >= percentageToPrint) {
printf("\rDescomprimindo restante do índice ... %.2lf%% concluído", 100 * double(curSize) / tot);
fflush(stdout);
percentageToPrint += tot / 10;
}
}
}
printf("\n");
percentageToPrint = 0;
for(int i = nodes.size() - 1; i >= 0; --i) {
if((tot-i) >= percentageToPrint) {
printf("\rFinalizando estrutura de dados ... %.2lf%% concluído", 100 * double(i) / tot);
fflush(stdout);
percentageToPrint += tot / 10;
}
if(nodes[i].firstChild == -1)
nodes[i].leaves = 1;
else {
nodes[i].leaves = 0;
for(int nt = nodes[i].firstChild; nt != -1; nt = nodes[nt].sibling)
nodes[i].leaves += nodes[nt].leaves;
}
}
printf("\n\n\n");
}
void SuffixTree::build(const char* text, size_t n) {
this->text = text;
this->n = n;
insertNodeIntoTree(0, 0); //A raiz
ImplicitPointer current(0, 1, 0);
int tot = n, built = 0, percentageToPrint = 0;
for(int i = 0; i < n; ++i){
++built;
if(percentageToPrint <= built) {
printf("\rÁrvore %.2lf%% concluída", double(built)/tot * 100);
fflush(stdout);
percentageToPrint += tot/10;
}
int wprime = -1;
int w;
bool isTerm;
for(w = split(current, text[i], &isTerm); !isTerm; w = split(current, text[i], &isTerm)) {
//Cria uma folha representando o sufixo [i..] e 'pendura' em w
int leaf = insertNodeIntoTree(i, -1);
assert(nodes.at(w).getChild(text[i], text, nodes) == -1 && "O no atual jah tem o caracter que esta sendo acrescentado!");
nodes.at(w).addChild(leaf, nodes.at(leaf));
if(wprime != -1)
nodes.at(wprime).sl = w;
wprime = w;
if(current.v == 0 && !current.isImplicit()) {
isTerm = false; //Sinaliza que o terminador não existe
break;
}
current = followSuffixLink(current);
canonise(current);
}
assert(wprime == -1 || !current.isImplicit());
if(!current.isImplicit() && wprime != -1)
nodes.at(wprime).sl = current.v;
//Desce do terminador, se ele existir, utilizando a aresta certa
if(isTerm) {
if(current.isImplicit()) //Deve ser sempre verdade que current.end = i - 1
++current.end;
else
current.st = current.end = i;
}
canonise(current);
printTree(i);
}
printf("\n");
if(dotFile)
fclose(dotFile);
}
int SuffixTree::split(ImplicitPointer prt, char ch, bool* isTerm){
if(prt.isImplicit()) {
int toIdx = nodes.at(prt.v).getChild(text[prt.st], text, nodes);
*isTerm = text[nodes.at(toIdx).start + prt.strSize()] == ch;
if(*isTerm)
return prt.v;
else {//Aqui 'prt' se torna explícito
int w = insertNodeIntoTree(nodes.at(toIdx).start, nodes.at(toIdx).start + prt.strSize() - 1); //O novo locus explícito de 'prt'. A aresta (prt.v, w) é um prefixo de (prt.v, to)
nodes.at(toIdx).start += prt.strSize(); //a futura aresta (w, to) é um sufixo da antiga aresta (prt.v, w)
nodes.at(w).firstChild = toIdx; //pendura 'to' em 'w'
//É preciso substituir 'to' por 'w' na lista de adjacência de 'prt.v'
nodes.at(w).sibling = nodes.at(toIdx).sibling;
if(nodes.at(prt.v).firstChild == toIdx)
nodes.at(prt.v).firstChild = w;
else {
int prev = -1, cur = nodes.at(prt.v).firstChild;
while(cur != toIdx) {
prev = cur;
cur = nodes.at(cur).sibling;
}
nodes.at(prev).sibling = w;
}
nodes.at(toIdx).sibling = -1;
return w;
}
} else { //Não é implícito.
*isTerm = (nodes.at(prt.v).getChild(ch, text, nodes) != -1);
return prt.v;
}
}
ImplicitPointer SuffixTree::followSuffixLink(ImplicitPointer prt){
if(prt.v != 0)
prt.v = nodes[prt.v].sl;
else
++prt.st;
assert(prt.v != -1);
return prt;
}
void SuffixTree::canonise(ImplicitPointer& prt){
while(prt.isImplicit()) {
int from = prt.v, to = nodes.at(from).getChild(text[prt.st], text, nodes);
int size = (nodes.at(to).end == -1? n-1 : nodes.at(to).end) - nodes.at(to).start + 1;
if(size <= prt.strSize()){
prt.st += size;
prt.v = to;
}else
break;
}
}
int SuffixTree::insertNodeIntoTree(int lblStart, int lblEnd) {
int newNodeIdx = nodes.size();
nodes.push_back(SuffixTreeNode(lblStart, lblEnd));
nodes[newNodeIdx].sl = -1;
return newNodeIdx;
}
void SuffixTree::findMatchings(const char* pat, size_t m, bool countOnly) {
int i = 0; //tamanho do prefixo de pat já casado
int cur = 0; //locus do vértice logo abaixo do locus de 'pat'
int height = 0; //altura do vértice 'cur'
while(i < m){//enquanto o padrão não foi todo consumido
cur = nodes.at(cur).getChild(pat[i], text, nodes);
if(cur == -1) //não dá para estender o padrão
break;
height += nodes.at(cur).end - nodes.at(cur).start + 1;
//Tenta consumir os caracteres da aresta
int j = nodes.at(cur).start;
while(i < m && j <= nodes.at(cur).end && pat[i] == text[j])
++i, ++j;
//Houve um mismatch
if(i < m && j <= nodes.at(cur).end)
break;
}
int occs = 0;
if(i == m)
occs = nodes.at(cur).leaves;
printf("%d ocorrências encontradas\n", occs);
//imprime as ocorrências
if(!countOnly && i == m) {
Printer printer(text, n, pat, m);
getMatchings(pat, m, nodes.at(cur), height, printer); //Registra todas as ocorrências do padrão. Para isso é preciso achar todas as folhas abaixo de 'cur'
printer.print();//imprime as ocorrências
}
}
/*
* Registra todas as ocorrências do padrão no texto
*/
void SuffixTree::getMatchings(const char* pat, size_t m, SuffixTreeNode& node, int nodeHeight, Printer& printer) {
if(node.isLeaf()) //É folha
printer.addMatching(n-nodeHeight);
else {
for(int nt = node.firstChild; nt != -1; nt = nodes.at(nt).sibling){
SuffixTreeNode& next = nodes.at(nt);
int edgeSize = next.end - next.start + 1;
getMatchings(pat, m, next, nodeHeight + edgeSize, printer);
}
}
}
void SuffixTree::printTree(int step) {
if(!dotFile)
return;
fprintf(dotFile, "digraph Tree_%d{\n", step);
for(int i = 0; i < nodes.size(); ++i)
fprintf(dotFile, "%d [label=\"%d\"]\n", i, i);
_printTreeRec(0, step);
fprintf(dotFile, "}\n");
}
void SuffixTree::_printTreeRec(int cur, int step){
SuffixTreeNode& node = nodes.at(cur);
if(nodes[cur].sl != -1)
fprintf(dotFile, "%d -> %d [style=dotted,color=red]\n", cur, nodes[cur].sl);
for(int nt = node.firstChild; nt != -1; nt = nodes.at(nt).sibling){
SuffixTreeNode& next = nodes.at(nt);
int labelSize = (next.end == -1 ? step : next.end) - next.start + 1;
if(step == n-1 && next.end == -1) { //o caractere '$' faz parte do label
fprintf(dotFile, "%d -> %d [label=\"%.*s", cur, nt, labelSize-1, text+next.start);
fprintf(dotFile, "$\"]\n");
} else
fprintf(dotFile, "%d -> %d [label=\"%.*s\"]\n", cur, nt, labelSize, text + next.start);
_printTreeRec(nt, step);
}
}
|
// Complete the reverse function below.
/*
* For your reference:
*
* DoublyLinkedListNode {
* int data;
* DoublyLinkedListNode* next;
* DoublyLinkedListNode* prev;
* };
*
*/
DoublyLinkedListNode* reverse(DoublyLinkedListNode* head) {
if (head == NULL)
return head;
DoublyLinkedListNode* itrNode = head;
DoublyLinkedListNode* prvNode = NULL;
// find last node
bool done = false;
while(!done)
{
if (itrNode->next == NULL)
{
done = true;
head = itrNode;
}
else
{
itrNode = itrNode->next;
}
}
done = false;
while (!done)
{
prvNode= itrNode->prev;
itrNode->prev = itrNode->next;
itrNode->next = prvNode;
if (itrNode->next == NULL)
{
done = true;
}
else
{
itrNode = itrNode->next;
}
}
return head;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.