text
stringlengths 8
6.88M
|
|---|
////////////////////////////////////////////////////////////////////////////////
//
// (C) Andy Thomason 2012-2014
//
// Modular Framework for OpenGLES2 rendering on multiple platforms.
//
namespace octet {
/// Scene containing a box with octet.
class example_rollercoaster : public app {
// scene for drawing box
ref<visual_scene> app_scene;
collada_builder loader;
public:
/// this is called when we construct the class before everything is initialised.
example_rollercoaster(int argc, char **argv) : app(argc, argv) {
}
/// this is called once OpenGL is initialized
void app_init() {
app_scene = new visual_scene();
app_scene->create_default_camera_and_lights();
scene_node *cam = app_scene->get_camera_instance(0)->get_node();
cam->loadIdentity();
cam->translate(vec3(0, 20, 4));
cam->rotate(-90, vec3(1, 0, 0));
if (!loader.load_xml("assets/rollercoaster.dae")) {
printf("failed to load file!\n");
exit(1);
}
resource_dict dict;
loader.get_resources(dict);
// note that this call will dump the code below to log.txt
dict.dump_assets(log(""));
scene_node *trough = dict.get_scene_node("trough");
scene_node *Camera = dict.get_scene_node("Camera");
material *default_material = dict.get_material("default_material");
material *Material_material = dict.get_material("Material-material");
mesh *trough_mesh_Material_material = dict.get_mesh("trough-mesh+Material-material");
visual_scene *Scene = dict.get_visual_scene("Scene");
scene_node *Lamp = dict.get_scene_node("Lamp");
scene_node *start = dict.get_scene_node("start");
mat4t location;
location.translate(vec3(0, 0, 0));
location.rotateX90();
material *red = new material(vec4(1, 0, 0, 1));
app_scene->add_shape(location, trough_mesh_Material_material, red, false);
material *blue = new material(vec4(0, 0, 1, 1));
mesh_sphere *sphere = new mesh_sphere(vec3(0, 0, 0), 0.2f);
for (int i = -10; i <= 10; ++i) {
for (int j = -10; j <= 10; ++j) {
mat4t location;
location.translate((float)i, 5, (float)j);
app_scene->add_shape(location, sphere, blue, true);
}
}
}
/// this is called to draw the world
void draw_world(int x, int y, int w, int h) {
int vx = 0, vy = 0;
get_viewport_size(vx, vy);
app_scene->begin_render(vx, vy);
// update matrices. assume 30 fps.
app_scene->update(1.0f/30);
// draw the scene
app_scene->render((float)vx / vy);
}
};
}
|
#include <iostream>
#include <armadillo>
#include <cmath>
#include <vector>
#include "Body.h"
#include "Universe.h"
#include "../../lib/lib.h"
using namespace arma;
using namespace std;
int main(int argc, char *argv[]) {
bool useVerlet = true;
if (argc < 5) {
cout << "Usage: ./main.x h tmax N check_for_ejections [verlet/rk4]" << endl;
exit(1);
}
double h = atof(argv[1]);
double t_max = atof(argv[2]);
int N = atoi(argv[3]);
bool check_for_ejections = (bool) atoi(argv[4]);
if (argc > 5) {
string arg5 (argv[5]);
if (arg5 == "rk4")
useVerlet = false;
}
Universe mysystem;
long idum = -1;
const double R0 = 20;
const double M0 = 1;
const double t_crunch = 1;
for (int i = 0; i < N; i++) {
double mass = abs(10*M0 + M0 * gaussian_deviate(&idum));
double vx, vy, vz;
vx = vy = vz = 0;
double phi = 2*M_PI * ran2(&idum);
double r = R0 * pow(ran2(&idum), 1/3.);
double theta = acos( 1 - 2*ran2(&idum) );
double x = r * sin(theta)*cos(phi);
double y = r * sin(theta)*sin(phi);
double z = r * cos(theta);
Body b = Body(mass, x, y, z, vx, vy, vz);
mysystem.add_body(b);
}
double totalmass = 0;
for (int i = 0; i < N; i++) {
totalmass += mysystem.all_bodies[i].mass;
}
double rho0 = totalmass / (4.0 * M_PI * pow(R0, 3) / 3);
mysystem.G = 3*M_PI / (32 * t_crunch*t_crunch * rho0);
mysystem.R0 = R0;
t_max = t_max*t_crunch;
double E0 = mysystem.energy();
if (useVerlet)
mysystem.solve_Verlet(h, t_max, check_for_ejections);
else
mysystem.solve_RK4(h, t_max, check_for_ejections);
double E1 = mysystem.energy();
cout << "E0 = " << E0 << ", E1 = " << E1 << ", Delta E = " << E1-E0 << ", rel. err. = " << (E1-E0)/E0 << endl;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 2011-2011 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Jonny Rein Eriksen
**
*/
#include "core/pch.h"
#include "modules/url/protocols/comm.h"
#include "modules/url/url_man.h"
#include "modules/url/url_dns_man.h"
#include "modules/url/url_socket_wrapper.h"
UrlDNSManager::UrlDNSManager()
{
}
UrlDNSManager::~UrlDNSManager()
{
}
void UrlDNSManager::PreDestructStep()
{
resolver_list.Clear();
}
UrlDNSManager *UrlDNSManager::CreateL()
{
return OP_NEW_L(UrlDNSManager, ());
}
OP_STATUS UrlDNSManager::Resolve(ServerName *server_name, OpHostResolverListener *object
#if defined(OPERA_PERFORMANCE) || defined (SCOPE_RESOURCE_MANAGER)
, BOOL prefetch /*= TRUE*/
#endif // OPERA_PERFORMANCE || SCOPE_RESOURCE_MANAGER
)
{
OP_STATUS status = OpStatus::OK;
ResolverListenerListItem *tempListener = NULL;
// Check if we are already looking up this server name.
ResolverListItem *temp = (ResolverListItem *) resolver_list.First();
while (temp)
{
if (temp->server_name == server_name)
break;
temp = (ResolverListItem *) temp->Suc();
}
tempListener = OP_NEW(ResolverListenerListItem, ());
if (!tempListener)
return OpStatus::ERR_NO_MEMORY;
tempListener->object = object;
if (!temp)
{
temp = OP_NEW(ResolverListItem, ());
if (!temp)
{
OP_DELETE(tempListener);
return OpStatus::ERR_NO_MEMORY;
}
OpString hostname;
if(OpStatus::IsError(status = hostname.Set((const char*)server_name->Name())) || OpStatus::IsError(status = SocketWrapper::CreateHostResolver(&temp->resolver, this)))
{
OP_DELETE(tempListener);
OP_DELETE(temp);
return status;
}
temp->server_name = server_name;
#if defined(OPERA_PERFORMANCE) || defined (SCOPE_RESOURCE_MANAGER)
temp->prefetch = prefetch;
temp->time_dns_request_started = g_op_time_info->GetRuntimeMS();
#endif // OPERA_PERFORMANCE || SCOPE_RESOURCE_MANAGER
temp->Into(&resolver_list);
server_name->SetIsResolvingHost(TRUE);
tempListener->Into(&temp->resolver_listener_list);
status = temp->resolver->Resolve(hostname.CStr());
}
else
tempListener->Into(&temp->resolver_listener_list);
#if defined(OPERA_PERFORMANCE) || defined (SCOPE_RESOURCE_MANAGER)
if (temp->prefetch && !prefetch)
{
// Prefetch of this dns address was already in progress.
// But now the comm loading part is starting and this
// is the point in time that dns lookup would normally start.
// Log the time saved so far.
double time_dns_request_completed = g_op_time_info->GetRuntimeMS();
double ts = time_dns_request_completed - temp->time_dns_request_started;
urlManager->GetNetworkStatisticsManager()->addDNSDelay(ts);
temp->prefetch = prefetch;
}
#endif // OPERA_PERFORMANCE || SCOPE_RESOURCE_MANAGER
return status;
}
ResolverListItem *UrlDNSManager::FindResolverListItem(OpHostResolver* aHostResolver)
{
ResolverListItem *temp = (ResolverListItem *) resolver_list.First();
while (temp)
{
if (temp->resolver == aHostResolver)
return temp;
temp = (ResolverListItem *) temp->Suc();
}
return NULL;
}
void UrlDNSManager::OnHostResolved(OpHostResolver* aHostResolver)
{
OP_ASSERT(aHostResolver);
if(!aHostResolver)
return;
ResolverListItem *temp = FindResolverListItem(aHostResolver);
if (temp)
{
temp->server_name->SetIsResolvingHost(FALSE);
#if defined(OPERA_PERFORMANCE) || defined(SCOPE_RESOURCE_MANAGER)
if (temp->prefetch)
{
//We managed to complete the resolve before the Comm code even started connecting to the server. Log time saved
double time_dns_request_completed = g_op_time_info->GetRuntimeMS();
double ts = time_dns_request_completed - temp->time_dns_request_started;
urlManager->GetNetworkStatisticsManager()->addDNSDelay(ts);
}
#endif // OPERA_PERFORMANCE || SCOPE_RESOURCE_MANAGER
temp->server_name->SetCrossNetwork(FALSE);
UINT count = aHostResolver->GetAddressCount();
for (UINT i = 0; i < count; ++i)
{
OpStackAutoPtr<OpSocketAddress> a(NULL);
OpSocketAddress *a1;
RAISE_AND_RETURN_VOID_IF_ERROR(OpSocketAddress::Create(&a1));
a.reset(a1);
RAISE_AND_RETURN_VOID_IF_ERROR(aHostResolver->GetAddress(a.get(), i));
OpSocketAddressNetType current_nettype = a->GetNetType();
OP_STATUS op_err;
if (i == 0)
{
op_err = temp->server_name->SetSocketAddress(a.get());
if (op_err == OpStatus::ERR_OUT_OF_RANGE)
{
temp->server_name->SetCrossNetwork(TRUE);
temp->server_name->SetAttemptedNetType(current_nettype);
}
else
RAISE_AND_RETURN_VOID_IF_ERROR(op_err);
}
else
{
op_err = temp->server_name->AddSocketAddress(a.release());
if(op_err == OpStatus::ERR_OUT_OF_RANGE)
{
temp->server_name->SetCrossNetwork(TRUE);
if(current_nettype < temp->server_name->GetAttemptedNetType())
temp->server_name->SetAttemptedNetType(current_nettype);
}
else
RAISE_AND_RETURN_VOID_IF_ERROR(op_err);
}
}
temp->notifying_listeners = TRUE;
ResolverListenerListItem *tempListener = (ResolverListenerListItem *) temp->resolver_listener_list.First();
while (tempListener)
{
ResolverListenerListItem *nextListener = (ResolverListenerListItem *) tempListener->Suc();;
if (tempListener->object)
tempListener->object->OnHostResolved(aHostResolver);
tempListener = nextListener;
}
temp->notifying_listeners = FALSE;
// the temp object can be deleted during OnHostResolved above
temp = FindResolverListItem(aHostResolver);
if (temp == NULL)
return;
tempListener = (ResolverListenerListItem *) temp->resolver_listener_list.First();
while (tempListener)
{
ResolverListenerListItem *oldListener = tempListener;
tempListener = (ResolverListenerListItem *) tempListener->Suc();
oldListener->Out();
OP_DELETE(oldListener);
}
temp->Out();
OP_DELETE(temp);
}
}
void UrlDNSManager::OnHostResolverError(OpHostResolver* aHostResolver, OpHostResolver::Error aError)
{
ResolverListItem *temp = FindResolverListItem(aHostResolver);
if (temp)
{
temp->notifying_listeners = TRUE;
ResolverListenerListItem *tempListener = (ResolverListenerListItem *) temp->resolver_listener_list.First();
while (tempListener)
{
ResolverListenerListItem *nextListener = (ResolverListenerListItem *) tempListener->Suc();;
if (tempListener->object)
tempListener->object->OnHostResolverError(aHostResolver, aError);
tempListener = nextListener;
}
temp->notifying_listeners = FALSE;
// the temp object can be deleted during OnHostResolverError above
temp = FindResolverListItem(aHostResolver);
if (temp == NULL)
return;
tempListener = (ResolverListenerListItem *) temp->resolver_listener_list.First();
while (tempListener)
{
ResolverListenerListItem *oldListener = tempListener;
tempListener = (ResolverListenerListItem *) tempListener->Suc();
oldListener->Out();
OP_DELETE(oldListener);
}
temp->Out();
OP_DELETE(temp);
}
}
void UrlDNSManager::RemoveListener(ServerName *server_name, OpHostResolverListener *object)
{
// Check if we are already looking up this server name.
ResolverListItem *temp = (ResolverListItem *) resolver_list.First();
while (temp)
{
if (temp->server_name == server_name)
break;
temp = (ResolverListItem *) temp->Suc();
}
if (temp)
{
ResolverListenerListItem *tempListener = (ResolverListenerListItem *) temp->resolver_listener_list.First();
while (tempListener)
{
ResolverListenerListItem *oldListener = tempListener;
tempListener = (ResolverListenerListItem *) tempListener->Suc();
if (oldListener->object == object)
{
oldListener->Out();
OP_DELETE(oldListener);
break;
}
}
if (temp->resolver_listener_list.Empty() && !temp->notifying_listeners)
{
temp->Out();
OP_DELETE(temp);
}
}
}
#ifdef SCOPE_RESOURCE_MANAGER
double UrlDNSManager::GetPrefetchTimeSpent(const ServerName* server_name)
{
if(!server_name)
return 0;
ResolverListItem *temp = (ResolverListItem *) resolver_list.First();
while (temp)
{
if (temp->server_name == server_name)
break;
temp = (ResolverListItem *) temp->Suc();
}
if (temp)
return g_op_time_info->GetRuntimeMS() - temp->time_dns_request_started;
return 0;
}
#endif // SCOPE_RESOURCE_MANAGER
|
// Created on: 1999-03-22
// Created by: Xuan PHAM PHU
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepTool_mkTondgE_HeaderFile
#define _TopOpeBRepTool_mkTondgE_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Face.hxx>
#include <gp_Dir.hxx>
#include <gp_Pnt2d.hxx>
#include <TopTools_DataMapOfShapeReal.hxx>
#include <Standard_Integer.hxx>
#include <TopTools_ListOfShape.hxx>
class TopOpeBRepTool_mkTondgE
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT TopOpeBRepTool_mkTondgE();
Standard_EXPORT Standard_Boolean Initialize (const TopoDS_Edge& dgE, const TopoDS_Face& F, const gp_Pnt2d& uvi, const TopoDS_Face& Fi);
Standard_EXPORT Standard_Boolean SetclE (const TopoDS_Edge& clE);
Standard_EXPORT Standard_Boolean IsT2d() const;
Standard_EXPORT Standard_Boolean SetRest (const Standard_Real pari, const TopoDS_Edge& Ei);
Standard_EXPORT Standard_Integer GetAllRest (TopTools_ListOfShape& lEi);
Standard_EXPORT Standard_Boolean MkTonE (Standard_Integer& mkT, Standard_Real& par1, Standard_Real& par2);
Standard_EXPORT Standard_Boolean MkTonE (const TopoDS_Edge& Ei, Standard_Integer& mkT, Standard_Real& par1, Standard_Real& par2);
protected:
private:
TopoDS_Edge mydgE;
TopoDS_Face myF;
TopoDS_Edge myclE;
gp_Dir mydirINcle;
TopoDS_Face myFi;
gp_Pnt2d myuvi;
Standard_Boolean isT2d;
TopTools_DataMapOfShapeReal myEpari;
Standard_Boolean hasRest;
gp_Dir myngf;
gp_Dir myngfi;
};
#endif // _TopOpeBRepTool_mkTondgE_HeaderFile
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
/**
* Desc£ºÅäÖĂÊư¾Ư¼ÓÔØÆ÷
* Author£º StevenZhai
* Date£º 2018-1-2018/01/23
* Time£º11£º43
*/
class GameObjectLoader
{
public:
GameObjectLoader();
~GameObjectLoader();
public:
//bool LoadConfigData(const FString& file);
bool LoadAll();
bool ClearAll();
};
|
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "TransferCmd.h"
#include "Common/Base58.h"
#include "Common/StringTools.h"
#include "CryptoNoteCore/CryptoNoteTools.h"
#include "CryptoNoteCore/CryptoNoteBasicImpl.h"
using namespace logging;
namespace cn
{
transfer_cmd::transfer_cmd(const cn::Currency& currency, std::string remote_fee_address) :
m_currency(currency),
m_remote_address(remote_fee_address),
fake_outs_count(0),
fee(currency.minimumFeeV2()) {
}
bool transfer_cmd::parseTx(LoggerRef& logger, const std::vector<std::string> &args)
{
ArgumentReader<std::vector<std::string>::const_iterator> ar(args.begin(), args.end());
try
{
/* Parse the remaining arguments */
while (!ar.eof())
{
auto arg = ar.next();
if (arg.size() && arg[0] == '-')
{
const auto& value = ar.next();
bool ttl_to_str = common::fromString(value, ttl) || ttl < 1 || ttl * 60 > m_currency.mempoolTxLiveTime();
if (arg == "-p" && !createTxExtraWithPaymentId(value, extra))
{
logger(ERROR, BRIGHT_RED) << "payment ID has invalid format: \"" << value << "\", expected 64-character string";
return false;
}
else if (arg == "-m")
{
messages.emplace_back(value);
}
else if (arg == "-ttl" && !ttl_to_str)
{
logger(ERROR, BRIGHT_RED) << "TTL has invalid format: \"" << value << "\", " <<
"enter time from 1 to " << (m_currency.mempoolTxLiveTime() / 60) << " minutes";
return false;
}
}
else
{
/* Integrated address check */
if (arg.length() == 186)
{
std::string paymentID;
std::string spendPublicKey;
std::string viewPublicKey;
const uint64_t paymentIDLen = 64;
/* Extract the payment id */
std::string decoded;
uint64_t prefix;
if (tools::base_58::decode_addr(arg, prefix, decoded))
paymentID = decoded.substr(0, paymentIDLen);
/* Validate and add the payment ID to extra */
if (!createTxExtraWithPaymentId(paymentID, extra))
{
logger(ERROR, BRIGHT_RED) << "Integrated payment ID has invalid format: \"" << paymentID << "\", expected 64-character string";
return false;
}
/* create the address from the public keys */
std::string keys = decoded.substr(paymentIDLen, std::string::npos);
cn::AccountPublicAddress addr;
cn::BinaryArray ba = common::asBinaryArray(keys);
if (!cn::fromBinaryArray(addr, ba))
return true;
std::string address = cn::getAccountAddressAsStr(cn::parameters::CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX, addr);
arg = address;
}
WalletLegacyTransfer destination;
WalletLegacyTransfer feeDestination;
cn::TransactionDestinationEntry de;
std::string aliasUrl;
if (!m_currency.parseAccountAddressString(arg, de.addr))
aliasUrl = arg;
auto value = ar.next();
bool ok = m_currency.parseAmount(value, de.amount);
if (!ok || 0 == de.amount)
{
logger(ERROR, BRIGHT_RED) << "amount is wrong: " << arg << ' ' << value <<
", expected number from 0 to " << m_currency.formatAmount(cn::parameters::MONEY_SUPPLY);
return false;
}
if (aliasUrl.empty())
{
destination.address = arg;
destination.amount = de.amount;
dsts.push_back(destination);
}
else
{
aliases[aliasUrl].emplace_back(WalletLegacyTransfer{"", static_cast<int64_t>(de.amount)});
}
/* Remote node transactions fees are 10000 X */
if (!m_remote_address.empty())
{
destination.address = m_remote_address;
destination.amount = 10000;
dsts.push_back(destination);
}
}
}
if (dsts.empty() && aliases.empty())
{
logger(ERROR, BRIGHT_RED) << "At least one destination address is required";
return false;
}
}
catch (const std::exception& e)
{
logger(ERROR, BRIGHT_RED) << e.what();
return false;
}
return true;
}
}
|
///////////////////////////////////////////////////////////////////////
// SizeFileMgr.cpp - Find sizes of files matching specified patterns //
// //
// Jim Fawcett, CSE687 - Object Oriented Design, Fall 2018 //
///////////////////////////////////////////////////////////////////////
#include "SizeFileMgr.h"
#include "FileSystem.h"
#define STATIC_LIB
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <sstream>
#include <algorithm>
void usage()
{
std::cout << "\n usage: FileSizes path [/s] [pattern]* [numFiles]";
std::cout << "\n path = relative or absolute path of starting directory";
std::cout << "\n /s for recursive search";
std::cout << "\n pattern is a pattern string of the form *.h, *.log, etc.";
std::cout << "\n numFiles is the number of files displayed";
std::cout << "\n Example: FileSizes ../.. /s *.h *.cpp *.txt 25";
std::cout << "\n";
}
bool SizeFileMgr::processCmdLine(int argc, char** argv)
{
if (argc < 2)
{
usage();
return false;
}
path_ = FileSystem::Path::getFullFileSpec(argv[1]);
if (!FileSystem::Directory::exists(path_))
{
std::cout << "\n " << path_ << " does not exist\n";
return false;
}
std::cout << "\n FileSizes";
std::cout << "\n " << path_;
for (int i = 2; i < argc; ++i)
{
std::cout << ", " << argv[i];
if (std::string(argv[i]) == "/s")
{
recursive_ = true;
}
else if (std::string(argv[i]) == "/r")
{
reverse_ = true;
}
else if (argv[i][0] == '/')
{
std::cout << "\n unknown option";
}
else
{
size_t numFiles = atoi(argv[i]);
if (numFiles == 0)
{
addPattern(argv[i]);
}
else
{
numFiles_ = numFiles;
}
}
}
std::cout << "\n";
return true;
}
SizeFileMgr::SizeFileMgr(const Path& path = "") : path_(path)
{
patterns_.push_back("*.*");
}
bool SizeFileMgr::changePath(const Path& path)
{
if (FileSystem::Directory::exists(path))
{
path_ = path;
return true;
}
return false;
}
void SizeFileMgr::addPattern(const std::string& patt)
{
if (patterns_.size() == 1 && patterns_[0] == "*.*")
patterns_.pop_back();
patterns_.push_back(patt);
}
void SizeFileMgr::search()
{
std::string fullPath = FileSystem::Path::getFullFileSpec(path_);
if (recursive_)
find(fullPath);
else
{
for (auto patt : patterns_)
{
std::vector<std::string> files = FileSystem::Directory::getFiles(fullPath, patt);
for (auto file : files)
{
std::string fileSpec = fullPath + "\\" + file;
FileSystem::FileInfo fi(fileSpec);
Size size = fi.size();
if (size > largest_) largest_ = size;
if (size < smallest_) smallest_ = size;
std::pair<size_t, std::string> item = { size, fileSpec };
store_.insert(item);
}
}
}
}
void SizeFileMgr::find(const Path& path)
{
for (auto patt : patterns_)
{
std::vector<std::string> files = FileSystem::Directory::getFiles(path, patt);
for (auto f : files)
{
std::string fileSpec = path + "\\" + f;
FileSystem::FileInfo fi(fileSpec);
Size size = fi.size();
if (size > largest_) largest_ = size;
if (size < smallest_) smallest_ = size;
std::pair<size_t, std::string> item = { size, fileSpec };
store_.insert(item);
}
}
std::vector<std::string> subdirs = FileSystem::Directory::getDirectories(path);
for (auto d : subdirs)
{
if (d != "." && d != "..")
{
//std::cout << "\n -- found dir: " << d;
find(path + "\\" + d);
}
}
}
void SizeFileMgr::showProcessed()
{
std::cout << "\n\n Processed " << store_.size() << " files";
size_t numDisplayed = std::min<size_t>(numFiles_, store_.size());
if (numDisplayed == 0)
numDisplayed = store_.size();
std::cout << "\n Displayed " << numDisplayed << " files";
std::cout << "\n largest size = " << largest_;
std::cout << "\n smallest size = " << smallest_;
}
void SizeFileMgr::forwardDisplay()
{
size_t count = 0;
for (auto iter = store_.begin(); iter != store_.end(); ++iter)
{
++count;
if (count > numFiles_ && numFiles_ > 0)
break;
std::cout << "\n " << std::setw(15) << iter->first << " " << iter->second;
}
showProcessed();
std::cout << "\n";
}
void SizeFileMgr::reverseDisplay()
{
size_t count = 0;
for (auto iter = store_.rbegin(); iter != store_.rend(); ++iter)
{
++count;
if (count > numFiles_ && numFiles_ > 0)
break;
std::cout << "\n " << std::setw(15) << iter->first << " " << iter->second;
}
showProcessed();
std::cout << "\n";
}
void SizeFileMgr::display()
{
if (reverse_)
reverseDisplay();
else
forwardDisplay();
}
#ifdef TEST_SIZEFILEMGR
#include <map>
#include <iostream>
#include <functional>
#include "../Utilities/Utilities.h"
using Size = size_t;
using Path = std::string;
using File = std::string;
int main(int argc, char* argv[])
{
SizeFileMgr fm;
if (!fm.processCmdLine(argc, argv))
{
std::cout << "\n command line parsing failed\n\n";
return 1;
}
fm.search();
fm.display();
std::cout << "\n\n";
return 0;
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "LinkStyleDialog.h"
# include "modules/display/styl_man.h"
#include "modules/style/css.h"
#include "modules/display/color.h"
#include "modules/dochand/winman.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#include "modules/prefs/prefsmanager/collections/pc_fontcolor.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
void LinkStyleDialog::Init(DesktopWindow* parent_window)
{
Dialog::Init(parent_window);
}
void LinkStyleDialog::OnInit()
{
SetWidgetValue("Underline_link_checkbox", g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasUnderline));
SetWidgetValue("Color_link_checkbox", g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasColor));
SetWidgetValue("Strikethrough_link_checkbox", g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasStrikeThrough));
SetWidgetValue("Border_links_checkbox", g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasFrame));
SetWidgetValue("Underline_visited_checkbox", g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::VisitedLinkHasUnderline));
SetWidgetValue("Color_visited_checkbox", g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::VisitedLinkHasColor));
SetWidgetValue("Strikethrough_visited_checkbox",g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::VisitedLinkHasStrikeThrough));
short days, hours;
char tmpexp[5];
days = g_pcnet->GetIntegerPref(PrefsCollectionNetwork::FollowedLinkExpireDays);
hours= g_pcnet->GetIntegerPref(PrefsCollectionNetwork::FollowedLinkExpireHours);
sprintf(tmpexp, "%d", days);
SetWidgetText("Mark_visited_days_edit", tmpexp);
sprintf(tmpexp, "%d", hours);
SetWidgetText("Mark_visited_hours_edit", tmpexp);
}
void LinkStyleDialog::OnColorSelected(COLORREF color)
{
OpWidget* widget = NULL;
if (m_choose_visited)
{
widget = GetWidgetByName("Color_visited_button");
}
else
{
widget = GetWidgetByName("Color_link_button");
}
if (widget)
{
widget->SetBackgroundColor(color);
}
}
UINT32 LinkStyleDialog::OnOk()
{
OpWidget* widget = NULL;
widget = GetWidgetByName("Color_visited_button");
if (widget)
{
COLORREF color = 0;
color = widget->GetBackgroundColor(color);
g_pcfontscolors->WriteColorL(OP_SYSTEM_COLOR_VISITED_LINK, color);
}
widget = GetWidgetByName("Color_link_button");
if (widget)
{
COLORREF color = 0;
color = widget->GetBackgroundColor(color);
g_pcfontscolors->WriteColorL(OP_SYSTEM_COLOR_LINK, color);
}
BOOL underline=FALSE;
BOOL italic=FALSE;
BOOL color=FALSE;
BOOL bold=FALSE;
BOOL strikethrough=FALSE;
BOOL button=FALSE;
underline = GetWidgetValue("Underline_visited_checkbox");
color = GetWidgetValue("Color_visited_checkbox");
strikethrough = GetWidgetValue("Strikethrough_visited_checkbox");
TRAPD(err, g_pcdisplay->WriteIntegerL(PrefsCollectionDisplay::VisitedLinkHasColor, color));
TRAP(err, g_pcdisplay->WriteIntegerL(PrefsCollectionDisplay::VisitedLinkHasUnderline, underline));
TRAP(err, g_pcdisplay->WriteIntegerL(PrefsCollectionDisplay::VisitedLinkHasStrikeThrough, strikethrough));
underline = GetWidgetValue("Underline_link_checkbox");
color = GetWidgetValue("Color_link_checkbox");
strikethrough = GetWidgetValue("Strikethrough_link_checkbox");
button = GetWidgetValue("Border_links_checkbox");
g_pcdisplay->WriteIntegerL(PrefsCollectionDisplay::LinkHasColor, color);
g_pcdisplay->WriteIntegerL(PrefsCollectionDisplay::LinkHasUnderline, underline);
g_pcdisplay->WriteIntegerL(PrefsCollectionDisplay::LinkHasStrikeThrough, strikethrough);
g_pcdisplay->WriteIntegerL(PrefsCollectionDisplay::LinkHasFrame, button);
#ifdef DISPLAY_CAP_STYLE_IS_LAYOUTSTYLE
LayoutStyle *styl;
#else // DISPLAY_CAP_STYLE_IS_LAYOUTSTYLE
Style *styl;
#endif // DISPLAY_CAP_STYLE_IS_LAYOUTSTYLE
styl = styleManager->GetStyle(HE_A);
PresentationAttr pres = styl->GetPresentationAttr();
if (color)
{
pres.Color = g_pcfontscolors->GetColor(OP_SYSTEM_COLOR_LINK);
}
else
pres.Color = USE_DEFAULT_COLOR;
pres.Bold = bold;
pres.Italic = italic;
pres.Underline = underline;
pres.StrikeOut = strikethrough;
//pres.Frame = button;
styl->SetPresentationAttr(pres);
OP_MEMORY_VAR short days = -1, hours = -1;
OpString num;
GetWidgetText("Mark_visited_days_edit", num);
if (num.HasContent())
days = uni_atoi(num.CStr());
GetWidgetText("Mark_visited_hours_edit", num);
if (num.HasContent())
hours = uni_atoi(num.CStr());
TRAP(err, g_pcnet->WriteIntegerL(PrefsCollectionNetwork::FollowedLinkExpireDays, days));
TRAP(err, g_pcnet->WriteIntegerL(PrefsCollectionNetwork::FollowedLinkExpireHours, hours));
windowManager->UpdateWindows(TRUE);
return 0;
}
BOOL LinkStyleDialog::OnInputAction(OpInputAction* action)
{
switch (action->GetAction())
{
case OpInputAction::ACTION_CHOOSE_LINK_COLOR:
{
COLORREF color = 0;
OpColorChooser* chooser = NULL;
m_choose_visited = action->GetActionData() == 1;
if (OpStatus::IsSuccess(OpColorChooser::Create(&chooser)))
{
chooser->Show(color, this, this);
OP_DELETE(chooser);
}
break;
}
default:
break;
}
return Dialog::OnInputAction(action);
}
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
int n, m;
/**
* Heap[] 存储的是堆
* mapper 存储值为i的节点在Heap[]中的下标
*/
int Heap[maxn];
map<int, int> mapper;
/**
* 建堆操作,将temp调整到堆中正确的位置
* temp是要插入到堆中的值,idx是它所在的下标
*/
void addNode(int temp, int idx) {
while (idx > 1 && temp < Heap[idx / 2]) {
Heap[idx] = Heap[idx / 2];
idx /= 2;
}
Heap[idx] = temp;
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++) {
int t; cin >> t;
//插入到堆中
addNode(t, i);
}
//存储映射关系
for (int i = 1; i <= n; i++) mapper[Heap[i]] = i;
while (m--) {
int x, y;
string s, s1, s2, s3, s4;
cin >> x >> s;
if (s == "is") {
cin >> s1 >> s2;
s3 = s1 + s2;
if (s3 == "theroot") {
//根节点的判断
printf("%c\n", (mapper[x] == 1) ? 'T' : 'F');
} else if (s3 == "theparent") {
//父亲节点的判断
cin >> s4 >> y;
printf("%c\n", (mapper[x] == mapper[y]/2) ? 'T' : 'F');
} else {
//子节点的判断
cin >> s4 >> y;
printf("%c\n", (mapper[x]/2 == mapper[y]) ? 'T' : 'F');
}
} else {
//兄弟的节点的判读
cin >> y >> s1 >> s2;
printf("%c\n", (mapper[x]/2 == mapper[y]/2) ? 'T' : 'F');
}
}
return 0;
}
|
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "SciFiSideScroller/SciFiSideScrollerGameMode.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeSciFiSideScrollerGameMode() {}
// Cross Module References
SCIFISIDESCROLLER_API UClass* Z_Construct_UClass_ASciFiSideScrollerGameMode_NoRegister();
SCIFISIDESCROLLER_API UClass* Z_Construct_UClass_ASciFiSideScrollerGameMode();
ENGINE_API UClass* Z_Construct_UClass_AGameModeBase();
UPackage* Z_Construct_UPackage__Script_SciFiSideScroller();
// End Cross Module References
void ASciFiSideScrollerGameMode::StaticRegisterNativesASciFiSideScrollerGameMode()
{
}
UClass* Z_Construct_UClass_ASciFiSideScrollerGameMode_NoRegister()
{
return ASciFiSideScrollerGameMode::StaticClass();
}
struct Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_AGameModeBase,
(UObject* (*)())Z_Construct_UPackage__Script_SciFiSideScroller,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Info Rendering MovementReplication Replication Actor Input Movement Collision Rendering Utilities|Transformation" },
{ "IncludePath", "SciFiSideScrollerGameMode.h" },
{ "ModuleRelativePath", "SciFiSideScrollerGameMode.h" },
{ "ShowCategories", "Input|MouseInput Input|TouchInput" },
};
#endif
const FCppClassTypeInfoStatic Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<ASciFiSideScrollerGameMode>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics::ClassParams = {
&ASciFiSideScrollerGameMode::StaticClass,
"Game",
&StaticCppClassTypeInfo,
DependentSingletons,
nullptr,
nullptr,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
0,
0,
0,
0x008802ACu,
METADATA_PARAMS(Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_ASciFiSideScrollerGameMode()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(ASciFiSideScrollerGameMode, 3181265041);
template<> SCIFISIDESCROLLER_API UClass* StaticClass<ASciFiSideScrollerGameMode>()
{
return ASciFiSideScrollerGameMode::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_ASciFiSideScrollerGameMode(Z_Construct_UClass_ASciFiSideScrollerGameMode, &ASciFiSideScrollerGameMode::StaticClass, TEXT("/Script/SciFiSideScroller"), TEXT("ASciFiSideScrollerGameMode"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(ASciFiSideScrollerGameMode);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
|
#ifndef SIMGRAPHICS_EXAMPLES_FRAMEWORK_H
#define SIMGRAPHICS_EXAMPLES_FRAMEWORK_H
#include "include/SimRoot.h"
#include "include/SimRenderDevice.h"
#include "SimExamples/SimVertex.h"
#include <d3dx9.h>
#include <DxErr.h>
const D3DCOLOR WHITE = D3DCOLOR_XRGB(255, 255, 255);
const D3DCOLOR RED = D3DCOLOR_XRGB(255, 0, 0);
const D3DCOLOR GREEN = D3DCOLOR_XRGB(0, 255, 0);
const D3DCOLOR BLUE = D3DCOLOR_XRGB(0, 0, 255);
const D3DCOLOR YELLOW = D3DCOLOR_XRGB(255, 255, 0);
const D3DCOLOR MEGENTA = D3DCOLOR_XRGB(255, 0, 255);
const D3DCOLOR CYAN = D3DCOLOR_XRGB(0, 255, 255);
const D3DCOLOR BLACK = D3DCOLOR_XRGB(0, 0, 0);
#if defined(DEBUG) | defined(_DEBUG)
#ifndef HR
#define HR(x) \
{ \
HRESULT hr = x; \
if (FAILED(hr)) { \
DXTrace(__FILE__, __LINE__, hr, TEXT(#x), TRUE); \
} \
}
#endif
#else
#ifndef HR
#define HR(x) x;
#endif
#endif
class Framework : public sim::DeviceEvent{
public:
Framework(HINSTANCE app_instance, const char* init_file);
virtual ~Framework();
void Run();
virtual void InitSceneBefore();
virtual void UpdateScene(float dt);
virtual void DrawScene();
// from DeviceEvent
virtual void OnLostDevice();
virtual void OnResetDevice();
protected:
sim::Root* root_;
sim::RenderDevice* render_device_;
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
int N, a,b,ini,fin,med,resp,e,f,meno,maxo;
int arr[1005];
int main() {
cin >> N;
for(int i=1; i<=N;i++){
cin >> arr[i];
}
cin >> a >> b;
meno = min(a,b);
maxo = max(a,b);
for(int i=1; i<=N;i++){
if (arr[i] >= meno && arr[i] <= maxo)resp++;
}
cout << resp;
return 0;
}
|
// Created on: 1992-11-25
// Created by: Julia DOROVSKIKH
// Copyright (c) 1992-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _XmlObjMgt_Array1_HeaderFile
#define _XmlObjMgt_Array1_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <XmlObjMgt_Element.hxx>
#include <Standard_Integer.hxx>
#include <XmlObjMgt_DOMString.hxx>
//! The class Array1 represents unidimensional
//! array of fixed size known at run time.
//! The range of the index is user defined.
//! Warning: Programs clients of such class must be independent
//! of the range of the first element. Then, a C++ for
//! loop must be written like this
//! for (i = A->Lower(); i <= A->Upper(); i++)
class XmlObjMgt_Array1
{
public:
DEFINE_STANDARD_ALLOC
//! Create an array of lower bound <Low> and
//! upper bound <Up>. Range error is raised
//! when <Up> is less than <Low>.
Standard_EXPORT XmlObjMgt_Array1(const Standard_Integer Low, const Standard_Integer Up);
//! for restoration from DOM_Element which is child of
//! theParent:
//! <theParent ...>
//! <theName ...>
Standard_EXPORT XmlObjMgt_Array1(const XmlObjMgt_Element& theParent, const XmlObjMgt_DOMString& theName);
//! Create DOM_Element representing the array, under 'theParent'
Standard_EXPORT void CreateArrayElement (XmlObjMgt_Element& theParent, const XmlObjMgt_DOMString& theName);
//! Returns the DOM element of <me>.
const XmlObjMgt_Element& Element() const;
//! Returns the number of elements of <me>.
Standard_Integer Length() const;
//! Returns the lower bound.
Standard_Integer Lower() const;
//! Returns the upper bound.
Standard_Integer Upper() const;
//! Set the <Index>th element of the array to <Value>.
Standard_EXPORT void SetValue (const Standard_Integer Index, XmlObjMgt_Element& Value);
//! Returns the value of <Index>th element of the array.
Standard_EXPORT XmlObjMgt_Element Value (const Standard_Integer Index) const;
protected:
private:
XmlObjMgt_Element myElement;
Standard_Integer myFirst;
Standard_Integer myLast;
};
#include <XmlObjMgt_Array1.lxx>
#endif // _XmlObjMgt_Array1_HeaderFile
|
#ifndef CPROFILEDB_H
#define CPROFILEDB_H
#include <YouMeCommon/CrossPlatformDefine/PlatformDef.h>
#include <SqliteOperator.h>
const XString s_szProfileTableName[] = {
__XT("settings")};
const XString CREATE_TABLE_SETTINGS = \
__XT("create table settings(key text,value text)");
const XString szProfileCreateTableSQL[] = {
CREATE_TABLE_SETTINGS
};
class CProfileDB
{
public:
bool getSetting(const std::string& strKey, XString& strValue);
bool setSetting(const std::string& strKey, const XString& strValue);
CProfileDB(const XString& strDbPath);
private:
//±¾µØdb
youmecommon::CSqliteDb m_sqliteDb;
};
#endif // CPROFILEDB_H
|
#include "Config.hpp"
#include <algorithm>
using namespace std;
using namespace libconfig;
const char *confFile = CONFIG_FILE_NAME;
static Setting &openConfFile(Config &cfg);
static Setting &openConfFile(Config &cfg) {
// Read the file. If there is an error, report it and exit.
try {
cfg.readFile(confFile);
}
catch(const FileIOException &fioex) {
cout << "Conf file not found. Creating" << endl;
// std::cerr << "I/O error while reading conf file." << std::endl;
// return(EXIT_FAILURE);
}
catch(const ParseException &pex) {
std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine()
<< " - " << pex.getError() << std::endl;
exit(EXIT_FAILURE);
}
Setting &root = cfg.getRoot();
return root;
}
static void writeConfFile(Config &cfg);
static void writeConfFile(Config &cfg) {
try {
cfg.writeFile(confFile);
// cout << "Configurations saved OK." << endl;
}
catch(const FileIOException &fioex) {
cerr << "I/O error while writing file: " << confFile << endl;
exit(EXIT_FAILURE);
}
}
/******************************************************************************/
// UNIT
ConfUnit::ConfUnit(void) {
this->ID = "";
this->alias = "";
this->serverIP = "";
this->bkpServerIP = "";
this->latitude = 0.0;
this->longitude = 0.0;
this->address = "";
}
ConfUnit::~ConfUnit(void) {}
void ConfUnit::save(void) {
Config cfg;
Setting &root = openConfFile(cfg);
if(root.exists("Unit"))
root.remove("Unit");
root.add("Unit", Setting::TypeGroup);
Setting &unit = root["Unit"];
// Create the new Unit entry.
unit.add("ID", Setting::TypeString) = this->ID;
unit.add("alias", Setting::TypeString) = this->alias;
unit.add("serverIP", Setting::TypeString) = this->serverIP;
unit.add("bkpServerIP", Setting::TypeString) = this->bkpServerIP;
unit.add("latitude", Setting::TypeFloat) = this->latitude;
unit.add("longitude", Setting::TypeFloat) = this->longitude;
unit.add("address", Setting::TypeString) = this->address;
writeConfFile(cfg);
}
void ConfUnit::load(void) {
Config cfg;
(void) openConfFile(cfg);
try {
cfg.lookupValue("Unit.ID", this->ID);
cfg.lookupValue("Unit.alias", this->alias);
cfg.lookupValue("Unit.serverIP", this->serverIP);
cfg.lookupValue("Unit.bkpServerIP", this->bkpServerIP);
cfg.lookupValue("Unit.latitude", this->latitude);
cfg.lookupValue("Unit.longitude", this->longitude);
cfg.lookupValue("Unit.address", this->address);
}
catch(const SettingNotFoundException &nfex) {
cerr << "Unit info corrupted in configuration file." << endl;
}
}
/******************************************************************************/
// ConfCamera
ConfCamera::ConfCamera(void) {
this->ID = -1;
this->unitID = -1;
this->alias = "" ;
this->north = -1.0;
this->physicalParameters = nullptr;
}
ConfCamera::~ConfCamera(void) {
}
void ConfCamera::save(const list<ConfCamera> cameras) {
Config cfg;
Setting &root = openConfFile(cfg);
if(root.exists("Cameras"))
root.remove("Cameras");
root.add("Cameras", Setting::TypeList);
Setting &s_cameras = root["Cameras"];
for(auto _camera:cameras) {
Setting &s_camera = s_cameras.add(Setting::TypeGroup);
// Create the new Camera entry.
s_camera.add("ID", Setting::TypeInt) = _camera.ID;
s_camera.add("unitID", Setting::TypeString) = _camera.unitID;
s_camera.add("alias", Setting::TypeString) = _camera.alias;
s_camera.add("north", Setting::TypeFloat) = _camera.north;
}
writeConfFile(cfg);
}
void ConfCamera::load(list<ConfCamera> &cameras) {
Config cfg;
Setting &root = openConfFile(cfg);
for(int i = 0; i < root["Cameras"].getLength(); i++) {
Setting &s_camera = root["Cameras"][i];
cameras.push_back(ConfCamera());
try {
s_camera.lookupValue("ID", cameras.back().ID);
s_camera.lookupValue("unitID", cameras.back().unitID);
s_camera.lookupValue("alias", cameras.back().alias);
s_camera.lookupValue("north", cameras.back().north);
}
catch(const SettingNotFoundException &nfex) {
cerr << "Camera info corrupted in configuration file." << endl;
}
}
}
/******************************************************************************/
//ROI
ConfROI::ConfROI(void) {
}
ConfROI::~ConfROI(void) {
}
void ConfROI::save(const list<ConfROI> ROIs) {
Config cfg;
Setting &root = openConfFile(cfg);
if(root.exists("ROIs"))
root.remove("ROIs");
root.add("ROIs", Setting::TypeList);
Setting &rois = root["ROIs"];
for(auto _roi:ROIs) {
Setting &roi = rois.add(Setting::TypeGroup);
// Create the new ROI entry.
roi.add("ID", Setting::TypeInt) = _roi.ID;
roi.add("name", Setting::TypeString) = _roi.name;
roi.add("positiveWayName", Setting::TypeString) = _roi.positiveWayName;
roi.add("negativeWayName", Setting::TypeString) = _roi.negativeWayName;
//Setting PTS
Setting &pts = roi.add("PT", Setting::TypeList);
for (int i = 0; i < (sizeof(_roi.PTs) / sizeof(_roi.PTs[0])); i++) {
Setting &edge = pts.add(Setting::TypeArray);
for (int j = 0; i < (sizeof(_roi.PTs[0])/sizeof(_roi.PTs[0][0])); j++) {
edge.add(Setting::TypeInt) = _roi.PTs[i][j];
}
}
//Setting Detection Points
Setting &dtpts = roi.add("DTPT", Setting::TypeList);
for (int i = 0; i < (sizeof(_roi.DTPTs) / sizeof(_roi.DTPTs[0])); i++) {
Setting &edge = dtpts.add(Setting::TypeArray);
for (int j = 0; i < (sizeof(_roi.DTPTs[0])/sizeof(_roi.DTPTs[0][0])); j++) {
edge.add(Setting::TypeInt) = _roi.DTPTs[i][j];
}
}
roi.add("cameraID", Setting::TypeInt) = _roi.cameraID;
}
writeConfFile(cfg);
}
void ConfROI::load(list<ConfROI> &ROIs) {
Config cfg;
Setting &root = openConfFile(cfg);
for(int i = 0; i < root["ROIs"].getLength(); i++) {
Setting &roi = root["ROIs"][i];
ROIs.push_back(ConfROI());
try {
roi.lookupValue("ID", ROIs.back().ID);
roi.lookupValue("name", ROIs.back().name);
roi.lookupValue("positiveWayName", ROIs.back().positiveWayName);
roi.lookupValue("negativeWayName", ROIs.back().negativeWayName);
for(int j = 0; j < roi["PT"].getLength(); j++) {
Setting &pt = roi["PT"][j];
ROIs.back().PTs[j][0] = pt[0];
ROIs.back().PTs[j][1] = pt[1];
}
for(int j = 0; j < roi["DTPT"].getLength(); j++) {
Setting &pt = roi["DTPT"][j];
ROIs.back().DTPTs[j][0] = pt[0];
ROIs.back().DTPTs[j][1] = pt[1];
}
roi.lookupValue("cameraID", ROIs.back().cameraID);
}
catch(const SettingNotFoundException &nfex) {
cerr << "ROI [" << i << "] info corrupted in configuration " <<
"file." << endl;
}
}
}
/******************************************************************************/
// ConfEvent
ConfEvent::ConfEvent(void) {
this->ID = -1;
this->processorID = -1;
this->timestamp = "";
this->way = -9;
this->blob = nullptr;
}
ConfEvent::~ConfEvent(void) {
// free(this->blob);
this->blob = nullptr;
}
void ConfEvent::save(void) {
Config cfg;
Setting &root = openConfFile(cfg);
if(root.exists("Event"))
root.remove("Event");
root.add("Event", Setting::TypeGroup);
Setting &event = root["Event"];
// Create the new Camera entry.
event.add("ID", Setting::TypeInt) = this->ID;
event.add("processorID", Setting::TypeInt) = this->processorID;
event.add("timestamp", Setting::TypeString) = this->timestamp;
event.add("way", Setting::TypeInt) = this->way;
writeConfFile(cfg);
}
void ConfEvent::load(void) {
Config cfg;
(void) openConfFile(cfg);
try {
cfg.lookupValue("Event.ID", this->ID);
cfg.lookupValue("Event.processorID", this->processorID);
cfg.lookupValue("Event.timestamp", this->timestamp);
cfg.lookupValue("Event.way", this->way);
}
catch(const SettingNotFoundException &nfex) {
cerr << "Event info corrupted in configuration file." << endl;
}
}
/******************************************************************************/
//Processor
ConfProcessor::ConfProcessor(void) {
this->ID = -1;
this->processorType = "";
this->idROI = -1;
}
ConfProcessor::~ConfProcessor(void) {
}
void ConfProcessor::save(const list<ConfProcessor> processors) {
Config cfg;
Setting &root = openConfFile(cfg);
printf("salvando processors\n");
if(root.exists("Processors"))
root.remove("Processors");
root.add("Processors", Setting::TypeList);
Setting &s_processors = root["Processors"];
for(auto _processor:processors) {
Setting &s_processor = s_processors.add(Setting::TypeGroup);
// Create the new Camera entry.
s_processor.add("ID", Setting::TypeInt) = _processor.ID;
s_processor.add("processorType", Setting::TypeString) =
_processor.processorType;
s_processor.add("idROI", Setting::TypeInt) = _processor.idROI;
}
printf("salvou processors\n");
writeConfFile(cfg);
}
void ConfProcessor::load(list<ConfProcessor> &processors) {
Config cfg;
Setting &root = openConfFile(cfg);
for(int i = 0; i < root["Processors"].getLength(); i++) {
Setting &s_processors = root["Processors"][i];
processors.push_back(ConfProcessor());
try {
s_processors.lookupValue("ID", processors.back().ID);
s_processors.lookupValue("processorType",
processors.back().processorType);
s_processors.lookupValue("idROI", processors.back().idROI);
}
catch(const SettingNotFoundException &nfex) {
cerr << "Processor info corrupted in configuration file." << endl;
}
}
}
int ConfProcessor::getProperty(list<ConfProcessor> &processors, std::string property) {
Config cfg;
Setting &root = openConfFile(cfg);
int propertyVal = 0;
for(int i = 0; i < root["Processors"].getLength(); i++) {
Setting &s_processors = root["Processors"][i];
try {
int id;
s_processors.lookupValue("ID", id);
if (id == this->ID) {
s_processors.lookupValue(property, propertyVal);
break;
}
}
catch(const SettingNotFoundException &nfex) {
cerr << "Processor info corrupted in configuration file." << endl;
}
}
return propertyVal;
}
/******************************************************************************/
//ProcessorType
ConfProcessorType::ConfProcessorType(void) {
this->ID = -1;
this->name = -1;
}
ConfProcessorType::~ConfProcessorType(void) {
}
void ConfProcessorType::save(void) {
Config cfg;
Setting &root = openConfFile(cfg);
if(root.exists("ProcessorType"))
root.remove("ProcessorType");
root.add("ProcessorType", Setting::TypeGroup);
Setting &processorType = root["ProcessorType"];
// Create the new Camera entry.
processorType.add("ID", Setting::TypeInt) = this->ID;
processorType.add("name", Setting::TypeInt) = this->name;
writeConfFile(cfg);
}
void ConfProcessorType::load(void) {
Config cfg;
(void) openConfFile(cfg);
try {
cfg.lookupValue("ProcessorType.ID", this->ID);
cfg.lookupValue("ProcessorType.name", this->name);
}
catch(const SettingNotFoundException &nfex) {
cerr << "ProcessorType info corrupted in configuration file." << endl;
}
}
/******************************************************************************/
// CONFIG
Conf::Conf(void) {}
Conf::~Conf(void) {}
void Conf::save(void) {
this->unit.save();
ConfCamera::save(this->cameras);
ConfROI::save(this->ROIs);
this->event.save();
ConfProcessor::save(this->processors);
this->processorType.save();
}
void Conf::load(void) {
this->unit.load();
ConfCamera::load(this->cameras);
ConfROI::load(this->ROIs);
this->event.load();
ConfProcessor::load(this->processors);
this->processorType.load();
}
/*----------------------------------------------------------------------------*/
// UNIT
// setters
void Conf::unitID(const string ID) { this->unit.ID = ID; }
void Conf::unitAlias(const string alias) { this->unit.alias = alias; }
void Conf::unitServerIP(const string IP) { this->unit.serverIP = IP; }
void Conf::unitBkpServerIP(const string IP) { this->unit.bkpServerIP = IP; }
void Conf::unitLatitude(const float lat) { this->unit.latitude = lat; }
void Conf::unitLongitude(const float lon) { this->unit.longitude = lon; }
void Conf::unitAddress(const string addr) { this->unit.address = addr; }
// getters
string Conf::unitID(void) { return this->unit.ID; }
string Conf::unitAlias(void) { return this->unit.alias; }
string Conf::unitServerIP(void) { return this->unit.serverIP; }
string Conf::unitBkpServerIP(void) { return this->unit.bkpServerIP; }
float Conf::unitLatitude(void) { return this->unit.latitude; }
float Conf::unitLongitude(void) { return this->unit.longitude; }
string Conf::unitAddress(void) { return this->unit.address; }
/*----------------------------------------------------------------------------*/
// CAMERA
void Conf::newCamera(void) { this->cameras.push_back(ConfCamera()); }
int Conf::lenCamera(void) { return this->cameras.size(); }
ConfCamera &Conf::searchCamera(const int id) {
int i = 0;
for (auto &&_camera:this->cameras) {
if(i++ == id) {
return _camera;
}
}
cerr << "No camera " << id << " found." << endl;
exit(EXIT_FAILURE);
}
// setters
void Conf::cameraID(const int id, const int ID) {
this->searchCamera(id).ID = ID;
}
void Conf::cameraUnitID(const int id, const string ID) {
this->searchCamera(id).unitID = ID;
}
void Conf::cameraAlias(const int id, const string alias) {
this->searchCamera(id).alias = alias;
}
void Conf::cameraNorth(const int id, const float north) {
this->searchCamera(id).north = north;
}
//void Conf::cameraPhysicalParameters(const void *physicalParameters) {
// ConfCamera _roi = this->searchROI(id);
// this->camera.physicalParameters = (void *) physicalParameters; } //XXX
// getters
int Conf::cameraID(const int id) {
return this->searchCamera(id).ID;
}
string Conf::cameraUnitID(const int id) {
return this->searchCamera(id).unitID;
}
string Conf::cameraAlias(const int id) {
return this->searchCamera(id).alias;
}
float Conf::cameraNorth(const int id) {
return this->searchCamera(id).north;
}
//void *Conf::cameraPhysicalParameters(void) {
// return this->camera.physicalParameters; } //XXX
/*----------------------------------------------------------------------------*/
// ROI
void Conf::newROI(void) { this->ROIs.push_back(ConfROI()); }
int Conf::lenROI(void) { return this->ROIs.size(); }
ConfROI &Conf::searchROI(const int id) {
int i = 0;
for (auto &&_roi:this->ROIs) {
if(i++ == id) {
return _roi;
}
}
cerr << "No roi " << id << " found." << endl;
exit(EXIT_FAILURE);
}
// setters
void Conf::roiID(const int id, const int ID) {
this->searchROI(id).ID = ID;
}
void Conf::roiName(const int id, const string name) {
this->searchROI(id).name = name;
}
void Conf::roiPositiveWayName(const int id, const string positiveWayName) {
this->searchROI(id).positiveWayName = positiveWayName;
}
void Conf::roiNegativeWayName(const int id, const string negativeWayName) {
this->searchROI(id).negativeWayName = negativeWayName;
}
#include <string.h>
void Conf::roiSetPTs(const int id, const int PTs[4][2]) {
ConfROI &_roi = this->searchROI(id);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
_roi.PTs[i][j] = PTs[i][j];
}
};
}
void Conf::roiSetDTPTs(const int id, const int PTs[2][2]) {
ConfROI &_roi = this->searchROI(id);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
_roi.DTPTs[i][j] = PTs[i][j];
}
};
}
void Conf::roiCameraID(const int id, const int cameraID) {
this->searchROI(id).cameraID = cameraID;
}
// getters
int Conf::roiID(const int id) {
return this->searchROI(id).ID;
}
string Conf::roiName(const int id) {
return this->searchROI(id).name;
}
string Conf::roiPositiveWayName(const int id) {
return this->searchROI(id).positiveWayName;
}
string Conf::roiNegativeWayName(const int id) {
return this->searchROI(id).negativeWayName;
}
void Conf::roiGetPTs(const int id, int PTs[4][2]) {
ConfROI &_roi = this->searchROI(id);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
PTs[i][j] = _roi.PTs[i][j];
}
}
}
void Conf::roiGetDTPTs(const int id, int PTs[2][2]) {
ConfROI &_roi = this->searchROI(id);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
PTs[i][j] = _roi.DTPTs[i][j];
}
};
}
int Conf::roiCameraID(const int id) {
return this->searchROI(id).cameraID;
}
/*----------------------------------------------------------------------------*/
// EVENT
// setters
void Conf::eventID(const int ID) { this->event.ID = ID; }
void Conf::eventProcessorID(const int ID) { this->event.processorID = ID;}
void Conf::eventTimeStamp(const string ts) { this->event.timestamp = ts; }
void Conf::eventWay(const int way) { this->event.way = way; }
void Conf::eventBlob(const void *blob) { this->event.blob = (void *) blob; }
// getters
int Conf::eventID(void) { return this->event.ID; }
int Conf::eventProcessorID(void) { return this->event.processorID; }
string Conf::eventTimeStamp(void) { return this->event.timestamp; }
int Conf::eventWay(void) { return this->event.way; }
void *Conf::eventBlob(void) { return this->event.blob; }
/*----------------------------------------------------------------------------*/
// PROCESSOR
void Conf::newProcessor(void) { this->processors.push_back(ConfProcessor()); }
int Conf::lenProcessor(void) { return this->processors.size(); }
ConfProcessor &Conf::searchProcessor(const int id) {
int i = 0;
for (auto &&_processor:this->processors) {
if(i++ == id) {
return _processor;
}
}
cerr << "No processor " << id << " found." << endl;
exit(EXIT_FAILURE);
}
// setters
void Conf::processorID(const int id, const int ID) {
this->searchProcessor(id).ID = ID;
}
void Conf::processorProcessorType(const int id, const string processorType) {
this->searchProcessor(id).processorType = processorType;
}
void Conf::processorIdROI(const int id, const int idROI) {
this->searchProcessor(id).idROI = idROI;
}
// getters
int Conf::processorID(const int id) {
return this->searchProcessor(id).ID;
}
string Conf::processorProcessorType(const int id) {
return this->searchProcessor(id).processorType;
}
int Conf::processorIdROI(const int id) {
return this->searchProcessor(id).idROI;
}
int Conf::processorIntConf(const int id, std::string propertyName) {
auto processor = this->searchProcessor(id);
return processor.getProperty(this->processors, propertyName);
}
/*----------------------------------------------------------------------------*/
// PROCESSOR_TYPE
// setters
void Conf::processorTypeID(const int ID) { this->processorType.ID = ID; }
void Conf::processorTypeName(const int name) { this->processorType.name = name;}
// getters
int Conf::processorTypeID(void) { return this->processorType.ID; }
int Conf::processorTypeName(void) { return this->processorType.name; }
|
#include "kinect.hpp"
using namespace mik;
// Saves 10 frames to disk
int main(int, char*[]) {
Kinect kinect(KinectConfig{}); // Default config
kinect.save_frames(10); // saves frames in both kinect and GestureNet formats
return 0;
}
|
#include "graph.h"
#include <cstdlib>
#include <stdio.h>
// I pledge on my honor that I have abided by the Stevens Honor System
// Conner Zeigman Daniel Kramer
struct Graph::Node{
Node* next;
int vert;
float weight;
};
Graph::Graph(int n, int rep){
type = rep;
if (n < 1){
numVertices = 1;
}
else{
numVertices = n;
}
if(type == 1){
list = new Node*[numVertices];
for (int i = 0; i < numVertices; i++){
list[i] = NULL;
}
}
else{
type = 0;
matrix = new float[numVertices * numVertices];
for (int i = 0; i < numVertices * numVertices; i++){
// matrix[i] represents the weight of a certain edge
matrix[i] = INFINITY;
}
}
}
Graph::~Graph(){
if (type == 1){
for (int i = 0; i < numVertices; i++){
Node* current = list[i];
if (current != NULL){
while(current -> next != NULL){
Node* hold = current;
current = current -> next;
delete hold;
}
}
delete current;
}
}
else{
delete[] matrix;
}
}
Graph* Graph::cloneGraph(int rep){
if (rep == 1 || rep == 0){
Graph* copy = new Graph(numVertices, rep);
for (int i = 0; i < numVertices; i++){
int j = 0;
int *putToNode = successors(i);
while (putToNode[j] != -1){
copy -> addEdge(i, putToNode[j], edge(i, putToNode[j]));
j++;
}
}
return copy;
}
else{
return NULL;
}
}
int Graph::numVerts(){
return numVertices;
}
bool Graph::addEdge(int source, int target, float w){
if (w == INFINITY || w < 0){
return false;
}
if (source >= numVertices || source < 0 || target >= numVertices || target < 0){
return false;
}
if (type == 1){
if (list[source] == NULL){
list[source] = new Node();
list[source] -> next = NULL;
list[source] -> vert = target;
list[source] -> weight = w;
return true;
}
else{
Node* current = list[source];
while (current -> next != NULL){
if (current -> next -> vert == target){
return false;
}
current = current -> next;
}
current -> next = new Node();
current -> next -> next = NULL;
current -> next -> vert = target;
current -> next -> weight = w;
return true;
}
}
else{
int index = numVertices * source + target;
if (matrix[index] != INFINITY){
return false;
}
matrix[index] = w;
return true;
}
}
bool Graph::delEdge(int source, int target){
if (source >= numVertices || source < 0 || target >= numVertices || target < 0){
return false;
}
if (type == 1){
if (list[source] == NULL){
return false;
}
Node* current = list[source];
if (current -> vert == target){
list[source] = current -> next;
delete current;
return true;
}
while (current -> next != NULL && current -> next -> vert != target){
current = current -> next;
}
if (current -> next == NULL){
return false;
}
current -> next = current -> next -> next;
return true;
}
else{
int index = numVertices * source + target;
if (matrix[index] == INFINITY){
return false;
}
matrix[index] = INFINITY;
return true;
}
}
float Graph::edge(int source, int target){
if (source >= numVertices || source < 0 || target >= numVertices || target < 0){
return -1.0;
}
if (type == 1){
if (list[source] == NULL){
return INFINITY;
}
Node* current = list[source];
if (current -> vert == target){
return current -> weight;
}
while (current -> next != NULL && current -> next -> vert != target){
current = current -> next;
}
if (current -> next == NULL){
return INFINITY;
}
return current -> next -> weight;
}
else{
return matrix[numVertices * source + target];
}
}
int* Graph::successors(int source){
if (source < 0 || source >= numVertices){
return NULL;
}
int size = numVertices + 1;
int* suc = (int*)malloc(size * sizeof(int));
int count = 0;
if (type == 1){
Node* current = list[source];
while (current != NULL){
suc[count] = current -> vert;
count++;
current = current -> next;
}
}
else{
int index = source * numVertices;
for (int i = index; i < index + numVertices; i++){
// not going into this if statement
if (matrix[i] != INFINITY){
suc[count] = i % numVertices;
count++;
}
}
}
suc[count] = -1;
return suc;
}
int* Graph::predecessors(int target){
if (target < 0 || target >= numVertices){
return NULL;
}
int size = numVertices + 1;
int* pred = (int*)malloc(size * sizeof(int));
int count = 0;
if (type == 1){
for(int i = 0; i < numVertices; i++){
Node* current = list[i];
while (current != NULL){
if (current -> vert == target){
pred[count] = i;
count++;
}
current = current -> next;
}
}
}
else{
for (int i = target; i < numVertices * numVertices; i += numVertices){
if (matrix[i] != INFINITY){
pred[count] = i / numVertices;
count++;
}
}
}
pred[count] = -1;
return pred;
}
|
// Created on: 2016-04-07
// Copyright (c) 2016 OPEN CASCADE SAS
// Created by: Oleg AGASHIN
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IMeshData_ParametersListArrayAdaptor_HeaderFile
#define _IMeshData_ParametersListArrayAdaptor_HeaderFile
#include <Standard_Transient.hxx>
//! Auxiliary tool representing adaptor interface for child classes of
//! IMeshData_ParametersList to be used in tools working on NCollection_Array structure.
template<class ParametersListPtrType>
class IMeshData_ParametersListArrayAdaptor : public Standard_Transient
{
public:
//! Constructor. Initializes tool by the given parameters.
IMeshData_ParametersListArrayAdaptor(
const ParametersListPtrType& theParameters)
: myParameters (theParameters)
{
}
//! Destructor.
virtual ~IMeshData_ParametersListArrayAdaptor()
{
}
//! Returns lower index in parameters array.
Standard_Integer Lower() const
{
return 0;
}
//! Returns upper index in parameters array.
Standard_Integer Upper() const
{
return myParameters->ParametersNb() - 1;
}
//! Returns value of the given index.
Standard_Real Value(const Standard_Integer theIndex) const
{
return myParameters->GetParameter(theIndex);
}
private:
IMeshData_ParametersListArrayAdaptor (
const IMeshData_ParametersListArrayAdaptor<ParametersListPtrType>& theOther);
void operator=(const IMeshData_ParametersListArrayAdaptor<ParametersListPtrType>& theOther);
const ParametersListPtrType myParameters;
};
#endif
|
#include <Rcpp.h>
#include <RcppParallel.h>
using namespace RcppParallel;
// [[Rcpp::depends(RcppParallel)]]
struct getElement : public Worker {
// input vector to read from
const std::vector< std::string > myVector;
// output vector to write to
std::vector< std::string > retVector;
std::string myString;
// initialize input and output vectors
getElement(const std::vector< std::string > myVector, std::vector< std::string > &retVector)
: myVector(myVector), retVector(retVector) {}
// function call operator that work for the specified range (begin/end)
void operator()(std::size_t begin, std::size_t end) {
// Rcpp::Rcout << "Value: " << begin << "\n";
for (std::size_t i = begin; i < end; i++) {
// Rcpp::checkUserInterrupt();
retVector[i] = "blah";
// retVector[i] = myVector[i];
// myString = myVector[i];
// retVector[i] = myString;
// retVector[i] = i;
// Rcpp::Rcout << "Value: " << myString << "\n";
// Rcpp::Rcout << "Value: " << retVector[i] << "\n";
}
}
};
// [[Rcpp::export]]
Rcpp::StringVector rcpp_parallel_delimitString(Rcpp::StringVector myVector) {
// Because Rcpp data structures are not thread safe
// we'll use std::vector for input and output.
std::vector< std::string > tmpVector1(myVector.size());
std::vector< std::string > tmpVector2(myVector.size());
// Convert Rcpp::StringVector to std::vector.
unsigned int i;
std::string tmpString;
for(i=0; i<myVector.size(); i++){
// Rcpp::checkUserInterrupt();
tmpString = myVector[i];
tmpVector1[i] = tmpString;
}
// Create the worker
getElement getElement(tmpVector1, tmpVector2);
// Call it with parallelFor
parallelFor(0, tmpVector1.size() - 1, getElement);
// allocate the string we will return
Rcpp::StringVector retVector(tmpVector2.size());
// Copy to Rcpp container to send back to R.
retVector = tmpVector2;
return retVector;
}
|
//
// Created by manout on 18-5-6.
//
#include <bits/stdc++.h>
using namespace std;
int numberOf1(int n)
{
size_t tmp = static_cast<size_t>(n);
tmp =
- ((tmp >> 1) & 033333333333)
- ((tmp >> 2) & 011111111111);
tmp = (tmp + (tmp >> 3)) & 030707070707;
return static_cast<int>(tmp % 63);
}
|
#ifndef WIDGETWAVE_HH_
#define WIDGETWAVE_HH_
#include "WidgetAudioView.hh"
/** A scrollable view of the audio wave. */
class WidgetWave : public WidgetAudioView
{
public:
/**
* \param parent Parent widget.
* \param rect Rectangle area of the widget.
* \param audio_input Source of audio data.
* \param pixels_per_second Time resolution. */
WidgetWave(PG_Widget *parent,
const PG_Rect &rect,
AudioInputController *audio_input,
unsigned int pixels_per_second);
virtual ~WidgetWave() { };
virtual void initialize();
protected:
virtual void draw_screen_vector(SDL_Surface *surface, unsigned int x);
private:
Uint32 m_foreground_color; //!< Color of the wave.
};
#endif /*WIDGETWAVE_HH_*/
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define MOD 1000000007
int n, x;
int a[111];
int cnt[111];
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
cin >> n;
// for (int i = 0; i < n; ++i) a[i] = (i + 1) % n;
for (int i = 0; i < n; ++i) a[i] = i;
do {
int c = 0;
vector<char> was(n, false);
for (int i = 0; i < n; ++i) {
if (!was[i]) {
int x = a[i];
while (x != i) {
was[x] = true;
x = a[x];
}
was[x] = true;
++c;
}
}
cnt[c]++;
} while (next_permutation(a, a + n));
for (int i = 1; i <= n; ++i) {
cerr << i << ": " << cnt[i] << endl;
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
FILE* in = fopen("input.txt", "w");
srand(time(NULL));
//fprintf(in, "%d\n", 50000000 );
//fprintf(in, "%d\n", 9878 );
for (long long i = 0; i < 50000 ; i++)
{
fprintf(in, "1 %d %d\n", rand(),rand() );
}
// for (long long i = 0; i < 1000 ; i++)
// fprintf(in, "%d\n", 1 + (rand()) % (100000) );
fclose(in);
return 0;
}
|
#ifndef __PAGEACTLIST_H
#define __PAGEACTPLIST_H
#include "CtrlWindowBase.h"
//#include "MAct.h"
#include "VActCtrlPanel.h"
namespace wh{
//---------------------------------------------------------------------------
class ModelPageActList : public IModelWindow
{
std::shared_ptr<MActArray> mWhModel = std::make_shared<MActArray>();
public:
ModelPageActList(const std::shared_ptr<rec::PageAct>& usr)
{
}
virtual void UpdateTitle()override
{
sigUpdateTitle("Действия", ResMgr::GetInstance()->m_ico_act24);
}
virtual void Load(const boost::property_tree::wptree& page_val)override
{
//using ptree = boost::property_tree::wptree;
//ptree::value_type page = *page_val.begin();
//auto name = page.first.c_str();
//int val1 = page.second.get<int>("id", 0);
//int val2 = page_val.get<int>("CtrlPageActList.id", 0);
}
virtual void Save(boost::property_tree::wptree& page_val)override
{
using ptree = boost::property_tree::wptree;
ptree content;
//content.put("id", (int)-1);
page_val.push_back(std::make_pair(L"CtrlPageActList", content));
//page_val.put("CtrlPageActList.id", 33);
}
wh::SptrIModel GetWhModel()const
{
return std::dynamic_pointer_cast<IModel>(mWhModel);
}
};
//---------------------------------------------------------------------------
class ViewPageActList : public IViewWindow
{
view::VActCtrlPanel* mPanel;
public:
ViewPageActList(std::shared_ptr<IViewNotebook> parent)
{
mPanel = new view::VActCtrlPanel(parent->GetWnd());
}
virtual wxWindow* GetWnd()const override { return mPanel; }
void SetWhModel(const wh::SptrIModel& wh_model)const{ mPanel->SetModel(wh_model); }
};
//---------------------------------------------------------------------------
class CtrlPageActList : public CtrlWindowBase<ViewPageActList, ModelPageActList>
{
public:
CtrlPageActList(std::shared_ptr<ViewPageActList> view
, std::shared_ptr<ModelPageActList> model)
:CtrlWindowBase(view, model)
{
view->SetWhModel(model->GetWhModel());
model->GetWhModel()->Load();
}
};
//---------------------------------------------------------------------------
} //namespace wh{
#endif // __IMVP_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef _PLUGIN_SUPPORT_
#include "modules/pi/OpSystemInfo.h"
#include "modules/auth/auth_basic.h"
#include "modules/doc/frm_doc.h"
#include "modules/doc/html_doc.h"
#include "modules/dochand/win.h"
#include "modules/dochand/winman.h"
#include "modules/formats/argsplit.h"
#include "modules/formats/hdsplit.h"
#include "modules/formats/uri_escape.h"
#include "modules/forms/form.h"
#include "modules/hardcore/mh/messages.h"
#include "modules/memtools/stacktraceguard.h"
#include "modules/ns4plugins/src/plugin.h"
#include "modules/ns4plugins/src/pluginglobals.h"
#include "modules/ns4plugins/src/pluginhandler.h"
#include "modules/ns4plugins/src/pluginmemoryhandler.h"
#include "modules/ns4plugins/src/pluginscript.h"
#include "modules/ns4plugins/src/pluginstream.h"
#include "modules/prefs/prefsmanager/collections/pc_js.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/security_manager/include/security_manager.h"
#include "modules/url/uamanager/ua.h"
#include "modules/upload/upload.h"
#include "modules/url/tools/url_util.h"
#include "modules/url/url_man.h"
#include "modules/viewers/viewers.h"
#include "modules/windowcommander/src/WindowCommander.h"
#ifdef WINGOGI
#include "platforms/wingogi/pi_impl/wingogipluginwindow.h"
#endif // WINGOGI
#ifdef _MACINTOSH_
#include "platforms/mac/pi/plugins/MacOpPluginWindow.h"
#endif
#ifdef WINGOGI
#include "platforms/wingogi/pi_impl/wingogipluginutils.h"
#endif // WINGOGI
#define FUNC_ENTRY(func_name) NPN_##func_name
#define VERSION_ENTRY (NP_VERSION_MAJOR << 8) + NP_VERSION_MINOR
#ifdef HAS_COMPLEX_GLOBALS
# define FUNC_MAP_START() const NPNetscapeFuncs g_operafuncs = {
# define FUNC_SIZE_ENTRY() sizeof(NPNetscapeFuncs)
# define FUNC_VERSION_ENTRY() VERSION_ENTRY
# define FUNC_MAP_ENTRY(field, func_name) FUNC_ENTRY(func_name)
# define FUNC_MAP_ENTRY_NULL(field) NULL
# define FUNC_MAP_END() };
#else // HAS_COMPLEX_GLOBALS
# define FUNC_MAP_START() void init_operafuncs() {\
NPNetscapeFuncs *tmp_map = g_opera->ns4plugins_module.m_operafuncs;
# define FUNC_SIZE_ENTRY() tmp_map->size = sizeof(NPNetscapeFuncs)
# define FUNC_VERSION_ENTRY() tmp_map->version = VERSION_ENTRY
# define FUNC_MAP_ENTRY(field, func_name) tmp_map->field = FUNC_ENTRY(func_name)
# define FUNC_MAP_ENTRY_NULL(field) tmp_map->field = NULL
# define FUNC_MAP_END() ;}
#endif // HAS_COMPLEX_GLOBALS
FUNC_MAP_START()
FUNC_SIZE_ENTRY(),
FUNC_VERSION_ENTRY(),
FUNC_MAP_ENTRY(geturl, GetURL),
FUNC_MAP_ENTRY(posturl, PostURL),
FUNC_MAP_ENTRY(requestread, RequestRead),
FUNC_MAP_ENTRY(newstream, NewStream),
FUNC_MAP_ENTRY(write, Write),
FUNC_MAP_ENTRY(destroystream, DestroyStream),
FUNC_MAP_ENTRY(status, Status),
FUNC_MAP_ENTRY(uagent, UserAgent),
FUNC_MAP_ENTRY(memalloc, MemAlloc),
FUNC_MAP_ENTRY(memfree, MemFree),
FUNC_MAP_ENTRY(memflush, MemFlush),
FUNC_MAP_ENTRY(reloadplugins, ReloadPlugins),
FUNC_MAP_ENTRY(getJavaEnv, GetJavaEnv),
FUNC_MAP_ENTRY(getJavaPeer, GetJavaPeer),
FUNC_MAP_ENTRY(geturlnotify, GetURLNotify),
FUNC_MAP_ENTRY(posturlnotify, PostURLNotify),
FUNC_MAP_ENTRY(getvalue, GetValue), // Some new functions introduced in NS4.0
FUNC_MAP_ENTRY(setvalue, SetValue),
FUNC_MAP_ENTRY(invalidaterect, InvalidateRect),
FUNC_MAP_ENTRY(invalidateregion, InvalidateRegion),
FUNC_MAP_ENTRY(forceredraw, ForceRedraw),
FUNC_MAP_ENTRY(getstringidentifier, GetStringIdentifier),
FUNC_MAP_ENTRY(getstringidentifiers, GetStringIdentifiers),
FUNC_MAP_ENTRY(getintidentifier, GetIntIdentifier),
FUNC_MAP_ENTRY(identifierisstring, IdentifierIsString),
FUNC_MAP_ENTRY(utf8fromidentifier, UTF8FromIdentifier),
FUNC_MAP_ENTRY(intfromidentifier, IntFromIdentifier),
FUNC_MAP_ENTRY(createobject, CreateObject),
FUNC_MAP_ENTRY(retainobject, RetainObject),
FUNC_MAP_ENTRY(releaseobject, ReleaseObject),
FUNC_MAP_ENTRY(invoke, Invoke),
FUNC_MAP_ENTRY(invokeDefault, InvokeDefault),
FUNC_MAP_ENTRY(evaluate, Evaluate),
FUNC_MAP_ENTRY(getproperty, GetProperty),
FUNC_MAP_ENTRY(setproperty, SetProperty),
FUNC_MAP_ENTRY(removeproperty, RemoveProperty),
FUNC_MAP_ENTRY(hasproperty, HasProperty),
FUNC_MAP_ENTRY(hasmethod, HasMethod),
FUNC_MAP_ENTRY(releasevariantvalue, ReleaseVariantValue),
FUNC_MAP_ENTRY(setexception, SetException),
FUNC_MAP_ENTRY(pushpopupsenabledstate, PushPopupsEnabledState),
FUNC_MAP_ENTRY(poppopupsenabledstate, PopPopupsEnabledState),
FUNC_MAP_ENTRY(enumerate, Enumerate),
FUNC_MAP_ENTRY(pluginthreadasynccall, PluginThreadAsyncCall),
FUNC_MAP_ENTRY(construct, Construct),
FUNC_MAP_ENTRY(getvalueforurl, GetValueForURL),
FUNC_MAP_ENTRY(setvalueforurl, SetValueForURL),
FUNC_MAP_ENTRY(getauthenticationinfo, GetAuthenticationInfo),
FUNC_MAP_ENTRY(scheduletimer, ScheduleTimer),
FUNC_MAP_ENTRY(unscheduletimer, UnscheduleTimer),
FUNC_MAP_ENTRY(popupcontextmenu, PopUpContextMenu),
FUNC_MAP_ENTRY(convertpoint, ConvertPoint),
FUNC_MAP_ENTRY(handleevent, HandleEvent),
FUNC_MAP_ENTRY(unfocusinstance, UnfocusInstance),
// Opera currently doesn't have this function implemented. For discussion on
// the matter, please see: http://critic.oslo.osa/showcomment?chain=3639
FUNC_MAP_ENTRY_NULL(urlredirectresponse)
FUNC_MAP_END()
#ifdef HAS_SET_HTTP_DATA
OP_STATUS PreparePostURL(URL& url, const char* buf, const uint32 len, const NPBool file)
{
OP_STATUS stat = OpStatus::OK;
url.SetHTTP_Method(HTTP_METHOD_POST);
#if defined(NS4P_DISABLE_HTTP_COMPRESS) && defined(URL_ALLOW_DISABLE_COMPRESS)
stat = url.SetAttribute(URL::KDisableCompress,TRUE);
#endif // NS4P_DISABLE_HTTP_COMPRESS && URL_ALLOW_DISABLE_COMPRESS
if (OpStatus::IsSuccess(stat) && file)
{
OpAutoPtr<Upload_TemporaryURL> upload_url(OP_NEW(Upload_TemporaryURL, ()));
RETURN_OOM_IF_NULL(upload_url.get());
RETURN_IF_LEAVE(upload_url->InitL(make_doublebyte_in_tempbuffer(buf, len), NULL, TRUE));
// disable content-disposition
RETURN_IF_LEAVE(upload_url->AccessHeaders().HeaderSetEnabledL("Content-Disposition", FALSE));
RETURN_IF_LEAVE(upload_url->PrepareUploadL(UPLOAD_BINARY_NO_CONVERSION));
url.SetHTTP_Data(upload_url.release(), TRUE);
}
else
{
OpAutoPtr<Upload_BinaryBuffer> upload_buf(OP_NEW(Upload_BinaryBuffer, ()));
RETURN_OOM_IF_NULL(upload_buf.get());
RETURN_IF_LEAVE(upload_buf->InitL((unsigned char *) buf, len, UPLOAD_COPY_EXTRACT_HEADERS));
RETURN_IF_LEAVE(upload_buf->PrepareUploadL(UPLOAD_BINARY_NO_CONVERSION));
url.SetHTTP_Data(upload_buf.release(), TRUE);
stat = OpStatus::OK;
}
// Probably want to call the equivalent of url.SetRequestedExternally(TRUE); ???
return stat;
}
#endif // HAS_SET_HTTP_DATA
/* PrepareGetURL() extracts the http request header name and value pairs from the src buffer received
from the plugin and convert it into the URL_Custom_Header required by the URL module.
The logic is mainly fetched from Header_List::ExtractHeadersL()
*/
OP_STATUS PrepareGetURL(URL& url, const char* src)
{
OP_ASSERT(src);
int len = op_strlen(src);
const char *pos = src;
char token;
int i;
for(i=0; i<len; i++)
{
token = *(pos++);
if(token < 0x20)
{
if(token == '\n')
{
if(i == len-1 || *pos == '\n')
break;
if(*pos != '\r')
continue;
i++;
pos++;
if(i == len-1 || *pos == '\n')
break;
}
else if(token != '\t' && token != '\r')
return OpStatus::OK;
}
}
if(i < len)
{
HeaderList headers;
ANCHOR(HeaderList, headers);
#if defined(NS4P_DISABLE_HTTP_COMPRESS) && defined(URL_ALLOW_DISABLE_COMPRESS)
RETURN_IF_ERROR(url.SetAttribute(URL::KDisableCompress,TRUE));
#endif // NS4P_DISABLE_HTTP_COMPRESS && URL_ALLOW_DISABLE_COMPRESS
((unsigned char *)src)[i+1] = '\0';
RETURN_IF_ERROR(headers.SetValue((char *) src));
HeaderEntry *item = headers.First();
while(item)
{
URL_Custom_Header header_item;
RETURN_IF_ERROR(header_item.name.Set(item->Name()));
RETURN_IF_ERROR(header_item.value.Set(item->Value()));
RETURN_IF_ERROR(url.SetAttribute(URL::KAddHTTPHeader, &header_item));
item = item->Suc();
}
}
return OpStatus::OK;
}
/* Rule for resolving URLs:
a URL should always be resolved in the context of the URL of the plugin that
issued the GetURL call.
*/
NPError PluginGetURL(BYTE type, NPP instance, const char* url_name, const char* url_target, uint32 len, const char* buf, NPBool file, void* notifyData, NPBool unique, const char* headers)
{
BOOL only_notification = FALSE; // url is loaded in another window, no streaming, notification is sent to the plugin
OP_ASSERT((!(type & PLUGIN_POST) || unique) && "Post urls must be retrieved from url API with unique = TRUE");
Plugin* plugin = NULL;
if (OpNS4PluginHandler::GetHandler())
plugin = ((PluginHandler*)OpNS4PluginHandler::GetHandler())->FindPlugin(instance);
if (!plugin)
return NPERR_NO_ERROR;
if (!url_name || !*url_name)
return NPERR_INVALID_URL;
FramesDocument* frames_doc = plugin->GetDocument();
if (!frames_doc)
return NPERR_GENERIC_ERROR;
Window* window = frames_doc->GetWindow();
if (!window)
return NPERR_GENERIC_ERROR;
#ifdef SUPPORT_VISUAL_ADBLOCK
if (url_target && frames_doc->GetHtmlDocument() && frames_doc->GetHtmlDocument()->GetWindow()->GetContentBlockEditMode())
{
HTML_Element* hlm = plugin->GetHtmlElement();
URL* img_url = hlm->GetEMBED_URL();
URL url;
if (!img_url)
{
url = hlm->GetImageURL(FALSE);
if (!url.IsEmpty())
img_url = &url;
}
if (img_url)
{
if (!frames_doc->GetIsURLBlocked(*img_url))
{
OpString s;
RETURN_NPERR_IF_ERROR(img_url->GetAttribute(URL::KUniName_Username_Password_Hidden, s, FALSE));
if (WindowCommander *win_com = frames_doc->GetWindow()->GetWindowCommander())
win_com->GetDocumentListener()->OnContentBlocked(win_com, s.CStr());
frames_doc->AddToURLBlockedList(*img_url);
hlm->MarkDirty(frames_doc, TRUE, TRUE);
if (plugin->GetPluginWindow())
frames_doc->GetVisualDevice()->ShowPluginWindow(plugin->GetPluginWindow(), FALSE);
}
}
return NPERR_NO_ERROR;
}
#endif // SUPPORT_VISUAL_ADBLOCK
/* Determine the url */
URL url = plugin->DetermineURL(type, url_name, !!unique);
if (url.IsEmpty())
return OpStatus::ERR;
#if MAX_PLUGIN_CACHE_LEN>0
url.SetAttribute(URL::KUseStreamCache, 1);
#endif
/* Prepare for loading */
if (type & PLUGIN_POST)
{
RETURN_NPERR_IF_ERROR(PreparePostURL(url, buf, len, file));
}
else if (headers)
{
RETURN_NPERR_IF_ERROR(PrepareGetURL(url, headers));
}
/* Determine the target window, if any, and load the data */
if (url_target)
{
#ifdef GADGET_SUPPORT
if (window->GetGadget() && url.Type() == URL_FILE) // security restriction
return NPERR_GENERIC_ERROR;
#endif // GADGET_SUPPORT
const uni_char* win_name = NULL;
BOOL open_in_other_window = FALSE;
BOOL user_activated = FALSE;
if (op_stricmp("_new", url_target) == 0 ||
op_stricmp("_blank", url_target) == 0)
{
win_name = UNI_L("_blank");
open_in_other_window = TRUE;
}
else if (op_stricmp("_current", url_target) == 0 ||
op_stricmp("_self", url_target) == 0)
{
win_name = UNI_L("_self");
}
else if (op_stricmp("_parent", url_target) == 0 ||
op_stricmp("_top", url_target) == 0)
{
win_name = make_doublebyte_in_tempbuffer(url_target, op_strlen(url_target));
}
else
{
win_name = make_doublebyte_in_tempbuffer(url_target, op_strlen(url_target));
user_activated = TRUE; // always open named window, regardless of user interaction with the plugin
}
if (win_name && url.Type() != URL_JAVASCRIPT)
{
BOOL plugin_unrequested_popup = TRUE;
if (plugin->GetPluginfuncs()->version >= NPVERS_HAS_POPUPS_ENABLED_STATE && plugin->GetPopupEnabledState()) // allow pop-ups according to user settings specified through plugin
{
user_activated = TRUE;
}
else if (plugin->IsPopupsEnabled())
{
user_activated = TRUE;
plugin->SetPopupsEnabled(FALSE);
}
if (user_activated && g_pcjs->GetIntegerPref(PrefsCollectionJS::IgnoreUnrequestedPopups))
{
plugin_unrequested_popup = FALSE;
}
int sub_win_id = -1;
RETURN_NPERR_IF_ERROR(g_windowManager->OpenURLNamedWindow(url, window, frames_doc, sub_win_id, win_name, user_activated, open_in_other_window, FALSE, FALSE, FALSE, NULL, plugin_unrequested_popup));
}
if (win_name)
only_notification = (type & PLUGIN_NOTIFY) != 0; // url is loaded in another named window
}
/* continue loading and notifying */
if (url_target && url.Type() != URL_JAVASCRIPT)
{
if (only_notification) // url is loaded in another window without streaming, notification is sent to the plugin when finished loading
{
PluginStream* dummy;
RETURN_NPERR_IF_ERROR(plugin->AddStream(dummy, url, (type & PLUGIN_NOTIFY) != 0, notifyData, only_notification));
}
}
else
{
if (url.Type() == URL_JAVASCRIPT)
{
RETURN_NPERR_IF_ERROR(frames_doc->ConstructDOMEnvironment());
if (!frames_doc->GetDOMEnvironment()->IsEnabled())
return NPERR_GENERIC_ERROR;
OpString stream_url;
RETURN_NPERR_IF_ERROR(url.GetAttribute(URL::KUniName_Username_Password_Hidden, stream_url));
// 'script' must be copied because the URL module may use its temporary
// storage space for something else after GetUniName is called. But note
// that the same operation is repeated in the code below for the sync case.
// It's possible that it would be helpful to avoid doing the operation twice.
URL tmpurl;
if (plugin->GetEmbedSrcUrl())
tmpurl = plugin->GetEmbedSrcUrl()->GetURL();
OpSecurityContext source(tmpurl);
OpSecurityContext target(frames_doc);
target.AddText(stream_url.CStr());
BOOL allowed = FALSE;
RETURN_NPERR_IF_ERROR(OpSecurityManager::CheckSecurity(OpSecurityManager::PLUGIN_RUNSCRIPT, source, target, allowed));
if (!allowed)
return NPERR_GENERIC_ERROR;
if (!url_target) // stream creation only for JS URL without window, then the result is streamed to the plugin
{
PluginStream* new_stream;
RETURN_NPERR_IF_ERROR(plugin->AddStream(new_stream, url, (type & PLUGIN_NOTIFY) != 0, notifyData, FALSE));
if (plugin->GetPluginfuncs()->version >= NP_VERSION_MINOR_14)
{ // NP_VERSION_MINOR_14 is the first version supporting the new scripting api.
OpString decoded_stream_url(stream_url);
UriUnescape::ReplaceChars(decoded_stream_url.CStr(), UriUnescape::All);
NPVariant result;
BOOL eval_success = SynchronouslyEvaluateJavascriptURL(plugin, frames_doc, decoded_stream_url.CStr(), result);
// Result is guaranteed to be of a string type if evaluation succeeded.
if (eval_success)
RETURN_NPERR_IF_ERROR(new_stream->New(plugin, NULL, result.value.stringValue.UTF8Characters, result.value.stringValue.UTF8Length));
PluginReleaseExternalValue(result);
return eval_success ? NPERR_NO_ERROR : NPERR_GENERIC_ERROR;
}
}
BOOL user_activated = FALSE;
if (plugin->GetPluginfuncs()->version >= NPVERS_HAS_POPUPS_ENABLED_STATE && plugin->GetPopupEnabledState())
{
if (g_pcjs->GetIntegerPref(PrefsCollectionJS::IgnoreUnrequestedPopups)) // allow pop-ups according to user settings specified through plugin
user_activated = TRUE;
}
else if (plugin->IsPopupsEnabled())
{
if (g_pcjs->GetIntegerPref(PrefsCollectionJS::IgnoreUnrequestedPopups))
user_activated = TRUE;
plugin->SetPopupsEnabled(FALSE);
}
RETURN_NPERR_IF_ERROR(frames_doc->ESOpenJavascriptURL(url, FALSE, TRUE, FALSE, TRUE, NULL, user_activated));
return NPERR_NO_ERROR;
}
PluginStream* new_stream = NULL;
RETURN_NPERR_IF_ERROR(plugin->AddStream(new_stream, url, (type & PLUGIN_NOTIFY) != 0, notifyData, FALSE));
#ifdef WEB_TURBO_MODE
RETURN_NPERR_IF_ERROR(url.SetAttribute(URL::KTurboBypassed, TRUE));
#endif // WEB_TURBO_MODE
#if defined(NS4P_DISABLE_HTTP_COMPRESS) && defined(URL_ALLOW_DISABLE_COMPRESS)
RETURN_NPERR_IF_ERROR(url.SetAttribute(URL::KDisableCompress,TRUE));
#endif // NS4P_DISABLE_HTTP_COMPRESS && URL_ALLOW_DISABLE_COMPRESS
// Send the URL of the plugin as the referrer
URL ref_url;
if (plugin->GetHtmlElement()->Type() == HE_EMBED) // Possible values are HE_EMBED, HE_OBJECT and HE_APPLET
{
URL *embed_url = plugin->GetHtmlElement()->GetEMBED_URL(frames_doc->GetLogicalDocument());
if (embed_url)
ref_url = *embed_url;
}
else if (plugin->GetHtmlElement()->Type() == HE_OBJECT)
{
URL *object_url = plugin->GetHtmlElement()->GetUrlAttr(ATTR_DATA, NS_IDX_HTML, frames_doc->GetLogicalDocument());
if (object_url)
ref_url = *object_url;
}
else
{
OP_ASSERT(plugin->GetHtmlElement()->Type() == HE_APPLET);
URL *applet_url = plugin->GetHtmlElement()->GetUrlAttr(ATTR_CODE, NS_IDX_HTML, frames_doc->GetLogicalDocument());
if (applet_url)
ref_url = *applet_url;
}
if (!ref_url.IsEmpty())
{
URL redirected_url = ref_url.GetAttribute(URL::KMovedToURL, URL::KFollowRedirect);
if (!redirected_url.IsEmpty())
ref_url = redirected_url;
}
else
ref_url = plugin->GetBaseURL();
# ifdef _DEBUG
OP_NEW_DBG("PluginGetURL", "pluginloading");
plugin->m_loading_streams++;
OP_DBG((" (%d/%d) Starting loading of %s", plugin->m_loading_streams, plugin->m_loaded_streams, url.GetName(FALSE, PASSWORD_SHOW)));
# endif // _DEBUG
URL_NormalLoad load_policy;
#ifdef URL_FILTER
// Checks if content_filter rules allow this URL
if (url.Type() != URL_JAVASCRIPT)
RETURN_NPERR_IF_ERROR(frames_doc->ConstructDOMEnvironment());
ServerName *doc_sn = url.GetServerName();
URLFilterDOMListenerOverride lsn_over(frames_doc->GetDOMEnvironment(), NULL);
HTMLLoadContext load_ctx(RESOURCE_OBJECT_SUBREQUEST, doc_sn, &lsn_over, window->GetType() == WIN_TYPE_GADGET);
BOOL allowed = FALSE;
RETURN_VALUE_IF_ERROR(g_urlfilter->CheckURL(&url, allowed, NULL, &load_ctx), NPERR_GENERIC_ERROR);
if (!allowed)
return NPERR_GENERIC_ERROR;
#endif // URL_FILTER
RETURN_NPERR_IF_ERROR(plugin->LoadDocument(url, ref_url, load_policy, new_stream));
}
return NPERR_NO_ERROR;
}
NPError __export NPN_GetURL(NPP instance, const char* url_name, const char* window)
{
OP_NEW_DBG("NPN_GetURL", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NPERR_INVALID_PARAM;
}
BOOL unique = g_pcnet->GetIntegerPref(PrefsCollectionNetwork::DiskCacheSize) == 0;
#if MAX_PLUGIN_CACHE_LEN>0
unique = TRUE;
#endif // MAX_PLUGIN_CACHE_LEN>0
NPError ret = PluginGetURL(PLUGIN_URL, instance, url_name, window, 0, NULL, FALSE, NULL, unique, NULL);
return ret;
}
NPError __export NPN_PostURL(NPP instance, const char* url_name, const char* window, uint32_t len, const char* buf, NPBool file)
{
OP_NEW_DBG("NPN_PostURL", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NPERR_INVALID_PARAM;
}
Plugin* plugin = NULL;
NPError ret = NPERR_NO_ERROR;
if (!url_name
#ifdef _MACINTOSH_
|| *url_name == 0
#endif
)
return NPERR_INVALID_URL;
if (OpNS4PluginHandler::GetHandler())
plugin = ((PluginHandler*)OpNS4PluginHandler::GetHandler())->FindPlugin(instance);
if (plugin && plugin->GetDocument())
{
int security_status = plugin->GetDocument()->GetURL().GetAttribute(URL::KSecurityStatus);
if (security_status != SECURITY_STATE_NONE && security_status != SECURITY_STATE_UNKNOWN
#ifdef SELFTEST
&& !plugin->GetDocument()->GetURL().GetAttribute(URL::KIsGeneratedBySelfTests)
#endif // SELFTEST
)
{
if (OpStatus::IsError(plugin->HandlePostRequest(PLUGIN_POST, url_name, window, len, buf, file)))
ret = NPERR_GENERIC_ERROR;
}
else
ret = PluginGetURL(PLUGIN_POST, instance, url_name, window, len, buf, file, NULL, TRUE, NULL);
}
else
ret = NPERR_GENERIC_ERROR;
return ret;
}
/**
* Request byte range(s) or seek from active stream. Invoked by plug-in.
*
* Our current implementation, though it may at first glance appear partially
* complete, is in reality spotty at best.
*
* 1. The API requires that we support fetching separate byte ranges,
* which we clearly do not (see PluginStream::RequestRead.)
*
* 2. What has been partially implemented, is seeking by way of receiving one
* zero-interval byte range indicating the seek offset. This was added by
* ohrn@opera.com for basic Flash Lite support. The implementation was
* supported by a set of network patches (pre-PPP), but not all of these were
* accepted. It is quite likely that this implementation is completely non-
* functional and can be dropped.
*/
NPError __export NPN_RequestRead(NPStream* stream, NPByteRange* rangeList)
{
OP_NEW_DBG("NPN_RequestRead", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NPERR_INVALID_PARAM;
}
if (stream && rangeList)
return static_cast<PluginStream *>(stream->ndata)->RequestRead(rangeList);
else
return NPERR_INVALID_PARAM;
}
NPError __export NPN_NewStream(NPP instance, NPMIMEType type, const char* window, NPStream** stream)
{
OP_NEW_DBG("NPN_NewStream", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NPERR_INVALID_PARAM;
}
return NPERR_GENERIC_ERROR;
}
int32_t __export NPN_Write(NPP instance, NPStream* stream, int32_t len, void* buffer)
{
OP_NEW_DBG("NPN_Write", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return 0;
}
return NPERR_GENERIC_ERROR;
}
NPError __export NPN_DestroyStream(NPP instance, NPStream* stream, NPReason reason)
{
OP_NEW_DBG("NPN_DestroyStream", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NPERR_INVALID_PARAM;
}
if (stream)
{
Plugin* plugin = NULL;
if (OpNS4PluginHandler::GetHandler())
plugin = ((PluginHandler*)OpNS4PluginHandler::GetHandler())->FindPlugin(instance);
if (plugin)
{
if (OpStatus::IsError(plugin->InterruptStream(stream, reason)))
return NPERR_GENERIC_ERROR;
}
else
return NPERR_INVALID_PLUGIN_ERROR;
}
else
return NPERR_GENERIC_ERROR;
return NPERR_NO_ERROR;
}
void __export NPN_Status(NPP instance, const char* message)
{
OP_NEW_DBG("NPN_Status", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return;
}
Plugin* plugin = NULL;
if (OpNS4PluginHandler::GetHandler())
plugin = ((PluginHandler*)OpNS4PluginHandler::GetHandler())->FindPlugin(instance);
if (plugin && plugin->GetDocument() && plugin->GetDocument()->GetWindow())
{
OpString tmp_str;
OP_STATUS stat = tmp_str.Set(message);
if (OpStatus::IsError(stat))
{ // The plug-in interface does not define a return value for the NPN_Status call.
if (OpStatus::IsMemoryError(stat))
g_memory_manager->RaiseCondition(stat);
else
OpStatus::Ignore(stat);
}
else
plugin->GetDocument()->GetWindow()->SetMessage(tmp_str.CStr());
}
}
const char* __export NPN_UserAgent(NPP instance)
{
OP_NEW_DBG("NPN_UserAgent", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NULL;
}
int len = 0;
#ifdef NS4P_WINDOWLESS_MACROMEDIA_WORKAROUND
Plugin* plug = g_pluginhandler && instance ? g_pluginhandler->FindPlugin(instance) : NULL;
if ((plug && plug->SpoofUA()) || (!plug && g_pluginhandler && g_pluginhandler->SpoofUA()))
len = g_uaManager->GetUserAgentStr(g_agent, sizeof(g_agent), NULL, NULL, UA_MozillaOnly);
else
#endif // NS4P_WINDOWLESS_MACROMEDIA_WORKAROUND
len = g_uaManager->GetUserAgentStr(g_agent, sizeof(g_agent), NULL, NULL, UA_Opera);
if (len > 0)
{
return g_agent;
}
return NULL;
}
void* __export NPN_MemAlloc(uint32_t size)
{
OP_NEW_DBG("NPN_MemAlloc", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
// It seems to be semi-allowed to run this in the wrong thread
// so until we know more, we just log it.
}
return PluginMemoryHandler::GetHandler()->Malloc(size);
}
void __export NPN_MemFree(void* ptr)
{
OP_NEW_DBG("NPN_MemFree", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
// It seems to be semi-allowed to run this in the wrong thread
// so until we know more, we just log it.
}
PluginMemoryHandler::GetHandler()->Free(ptr);
}
uint32_t __export NPN_MemFlush(uint32_t size)
{
OP_NEW_DBG("NPN_MemFlush", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
// It seems to be semi-allowed to run this in the wrong thread
// so until we know more, we just log it.
}
return 0;
}
void __export NPN_ReloadPlugins(NPBool reloadPages)
{
OP_NEW_DBG("NPN_ReloadPlugins", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return;
}
OpStatus::Ignore(g_plugin_viewers->RefreshPluginViewers(FALSE));
return;
}
// *** When JAVA is READY
/**
* NPN_GetJavaEnv() and NPN_GetJavaPeer() was a parts of the now deprecated FEATURE_NETSCAPE4_LIVECONNECT
* which has been replaced by the FEATURE_JAVA_PLUGIN + the Oracle Java NPAPI plugin. We retain these stubs
* only because they are listed in the upstream npapi headers. */
void* __export NPN_GetJavaEnv(void)
{
OP_NEW_DBG("NPN_GetJavaEnv", "ns4p");
IN_CALL_FROM_PLUGIN
return 0;
}
/**
* See note on NPN_GetJavaEnv().
*/
void* __export NPN_GetJavaPeer(NPP instance)
{
OP_NEW_DBG("NPN_GetJavaPeer", "ns4p");
IN_CALL_FROM_PLUGIN
return 0;
}
// *** When JAVA is READY END
NPError __export NPN_GetURLNotify(NPP instance, const char* url_name, const char* window, void* notifyData)
{
OP_NEW_DBG("NPN_GetURLNotify", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NPERR_INVALID_PARAM;
}
BOOL unique = g_pcnet->GetIntegerPref(PrefsCollectionNetwork::DiskCacheSize) == 0;
#if MAX_PLUGIN_CACHE_LEN>0
unique = TRUE;
#endif // MAX_PLUGIN_CACHE_LEN>0
return PluginGetURL(PLUGIN_URL|PLUGIN_NOTIFY, instance, url_name, window, 0, NULL, FALSE, notifyData, unique, NULL);
}
NPError __export NPN_PostURLNotify(NPP instance, const char* url_name, const char* window, uint32_t len, const char* buf, NPBool file, void* notifyData)
{
OP_NEW_DBG("NPN_PostURLNotify", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NPERR_INVALID_PARAM;
}
Plugin* plugin = NULL;
NPError ret = NPERR_NO_ERROR;
if (!url_name
#ifdef _MACINTOSH_
|| *url_name == 0
#endif
)
return NPERR_INVALID_URL;
if (OpNS4PluginHandler::GetHandler())
plugin = ((PluginHandler*)OpNS4PluginHandler::GetHandler())->FindPlugin(instance);
if (plugin && plugin->GetDocument())
{
int security_status = plugin->GetDocument()->GetURL().GetAttribute(URL::KSecurityStatus);
if (security_status != SECURITY_STATE_NONE && security_status != SECURITY_STATE_UNKNOWN
#ifdef SELFTEST
&& !plugin->GetDocument()->GetURL().GetAttribute(URL::KIsGeneratedBySelfTests)
#endif // SELFTEST
)
{
if (OpStatus::IsError(plugin->HandlePostRequest(PLUGIN_POST|PLUGIN_NOTIFY, url_name, window, len, buf, file, notifyData)))
ret = NPERR_GENERIC_ERROR;
}
else
ret = PluginGetURL(PLUGIN_POST|PLUGIN_NOTIFY, instance, url_name, window, len, buf, file, notifyData, TRUE, NULL);
}
else
ret = NPERR_GENERIC_ERROR;
return ret;
}
NPError __export NPN_GetValue(NPP instance, NPNVariable variable, void *value)
{
OP_NEW_DBG("NPN_GetValue", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NPERR_INVALID_PARAM;
}
NPError result = NPERR_NO_ERROR;
#ifdef USE_PLUGIN_EVENT_API
if (!instance && OpNS4PluginAdapter::GetValueStatic(variable, value, &result))
return result;
#endif // USE_PLUGIN_EVENT_API
Plugin* plug = NULL;
if (OpNS4PluginHandler::GetHandler())
plug = ((PluginHandler*)OpNS4PluginHandler::GetHandler())->FindPlugin(instance);
if (plug)
{
FramesDocument* frames_doc = plug->GetDocument();
if (!frames_doc)
return NPERR_GENERIC_ERROR;
#ifdef USE_PLUGIN_EVENT_API
if (plug->GetPluginAdapter()->GetValue(variable, value, &result))
return result;
#endif // USE_PLUGIN_EVENT_API
switch (variable)
{
#ifndef USE_PLUGIN_EVENT_API
case NPNVnetscapeWindow:
#ifdef MSWIN
if (plug->GetWindow())
*((void**)value) = (void*)::GetParent((HWND)plug->GetWindow());
else
{
#ifdef VEGA_OPPAINTER_SUPPORT
WindowsOpWindow* tw = ((WindowsOpView*)frames_doc->GetVisualDevice()->view->GetOpView())->GetNativeWindow();
HWND hwnd = tw?tw->m_hwnd:NULL;
#else
HWND hwnd = ((WindowsOpView*)frames_doc->GetVisualDevice()->view->GetOpView())->hwnd;
#endif
*((void**)value) = hwnd;
}
#elif defined(WINGOGI)
*((void**)value) = GetParentWindowHandle();
#else
*((void**)value) = 0;
#endif // MSWIN
break;
#endif // !USE_PLUGIN_EVENT_API
case NPNVjavascriptEnabledBool:
*((BOOL*)value) = g_pcjs->GetIntegerPref(PrefsCollectionJS::EcmaScriptEnabled, plug->GetHostName());
break;
case NPNVasdEnabledBool:
*((BOOL*)value) = FALSE;
break;
case NPNVisOfflineBool:
*((BOOL*)value) = !!g_pcnet->GetIntegerPref(PrefsCollectionNetwork::OfflineMode);
break;
case NPNVWindowNPObject:
*((void**)value) = plug->GetWindowNPObject();
break;
case NPNVPluginElementNPObject:
*((void**)value) = plug->GetPluginElementNPObject();
break;
case NPNVSupportsXEmbedBool:
*((BOOL*)value) = FALSE;
break;
case NPNVSupportsWindowless:
*(static_cast<NPBool *>(value)) = TRUE;
break;
case NPNVprivateModeBool:
*(static_cast<NPBool *>(value)) = plug->GetDocument()->GetWindow()->GetPrivacyMode();
break;
case NPNVsupportsAdvancedKeyHandling:
*(static_cast<NPBool *>(value)) = FALSE;
break;
case NPNVdocumentOrigin:
if (OpStatus::IsError(plug->GetOrigin(static_cast<char**>(value))))
result = NPERR_GENERIC_ERROR;
break;
default:
result = NPERR_GENERIC_ERROR; // Follow Firefox when handling unknown variable value
break;
}
}
else if (variable == NPNVserviceManager)
// Obsolete - not supported.
result = NPERR_GENERIC_ERROR;
else
result = NPERR_INVALID_PLUGIN_ERROR;
return result;
}
NPError __export NPN_SetValue(NPP instance, NPPVariable variable, void *value)
{
OP_NEW_DBG("NPN_SetValue", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return NPERR_INVALID_PARAM;
}
Plugin* plugin = NULL;
if (OpNS4PluginHandler::GetHandler())
plugin = ((PluginHandler*)OpNS4PluginHandler::GetHandler())->FindPlugin(instance);
if (!plugin)
return NPERR_INVALID_PLUGIN_ERROR;
#ifdef USE_PLUGIN_EVENT_API
NPError result;
if (plugin->GetPluginAdapter()->SetValue(variable, value, &result))
return result;
#endif // USE_PLUGIN_EVENT_API
switch (variable)
{
#ifndef NS4P_ALL_PLUGINS_ARE_WINDOWLESS
case NPPVpluginWindowBool:
plugin->SetWindowless(!value);
// Assume that plugin wants to be transparent when setting windowless mode.
// Required for Silverlight which does not set NPPVpluginTransparentBool.
plugin->SetTransparent(!value);
break;
#endif // !NS4P_ALL_PLUGINS_ARE_WINDOWLESS
case NPPVpluginTransparentBool:
plugin->SetTransparent(!!value);
break;
case NPPVpluginUrlRequestsDisplayedBool:
plugin->SetPluginUrlRequestsDisplayed(!!value);
break;
#ifdef _MACINTOSH_
case NPPVpluginDrawingModel:
{
NPDrawingModel model = static_cast<NPDrawingModel>(reinterpret_cast<intptr_t>(value));
plugin->SetDrawingModel(model);
if (model == NPDrawingModelCoreAnimation || model == NPDrawingModelInvalidatingCoreAnimation)
plugin->SetCoreAnimation(TRUE);
break;
}
#endif // _MACINTOSH_
default:
return NPERR_GENERIC_ERROR; // Follow Firefox when handling unknown variable value
}
return NPERR_NO_ERROR;
}
void __export NPN_InvalidateRect(NPP instance, NPRect *invalidRect)
{
OP_NEW_DBG("NPN_InvalidateRect", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return;
}
Plugin* plugin = g_pluginhandler ? g_pluginhandler->FindPlugin(instance) : NULL;
if (plugin)
{
plugin->Invalidate(invalidRect);
}
}
void __export NPN_InvalidateRegion(NPP instance, NPRegion invalidRegion)
{
OP_NEW_DBG("NPN_InvalidateRegion", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return;
}
#ifdef USE_PLUGIN_EVENT_API
Plugin* plugin = g_pluginhandler ? g_pluginhandler->FindPlugin(instance) : NULL;
if (plugin)
{
NPRect invalidRect;
if (plugin->GetPluginAdapter()->ConvertPlatformRegionToRect(invalidRegion, invalidRect))
plugin->Invalidate(&invalidRect);
}
#endif // USE_PLUGIN_EVENT_API
}
void __export NPN_ForceRedraw(NPP instance)
{
OP_NEW_DBG("NPN_ForceRedraw", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return;
}
Plugin* plugin = g_pluginhandler ? g_pluginhandler->FindPlugin(instance) : NULL;
if (plugin && plugin->GetDocument() && plugin->GetDocument()->GetVisualDevice())
plugin->GetDocument()->GetVisualDevice()->GetView()->Sync();
}
void __export NPN_PushPopupsEnabledState(NPP instance, NPBool enabled)
{
OP_NEW_DBG("NPN_PushPopupsEnabledState", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return;
}
Plugin* plugin = OpNS4PluginHandler::GetHandler() ? ((PluginHandler*)OpNS4PluginHandler::GetHandler())->FindPlugin(instance) : NULL;
if (plugin)
plugin->PushPopupsEnabledState(enabled);
return;
}
void __export NPN_PopPopupsEnabledState(NPP instance)
{
OP_NEW_DBG("NPN_PopPopupsEnabledState", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
return;
}
Plugin* plugin = OpNS4PluginHandler::GetHandler() ? ((PluginHandler*)OpNS4PluginHandler::GetHandler())->FindPlugin(instance) : NULL;
if (plugin)
plugin->PopPopupsEnabledState();
return;
}
NPError AllocateString(const char* buf, char **value, uint32_t *len)
{
unsigned buf_len = 0;
if (buf)
{
buf_len = op_strlen(buf);
*value = static_cast<char *>(PluginMemoryHandler::GetHandler()->Malloc(sizeof(char)*(buf_len + 1)));
if (!*value)
return NPERR_OUT_OF_MEMORY_ERROR;
op_strncpy(*value, buf, buf_len);
}
(*value)[buf_len] = '\0';
*len = buf_len;
return NPERR_NO_ERROR;
}
NPError __export NPN_GetValueForURL(NPP instance, NPNURLVariable variable, const char *url_name, char **value, uint32_t *len)
{
OP_NEW_DBG("NPN_GetValueForURL", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
// It seems to be semi-allowed to run this in the wrong thread
// so until we know more, we just log it.
}
NPError np_stat = NPERR_NO_ERROR;
OP_STATUS op_stat = OpStatus::OK;
Plugin* plug = g_pluginhandler && instance ? g_pluginhandler->FindPlugin(instance) : NULL;
if (plug)
{
if ((variable == NPNURLVCookie || variable == NPNURLVProxy) && value && len)
{
*len = 0;
if (url_name)
{
URL url = g_url_api->GetURL(url_name);
if (variable == NPNURLVCookie)
{ // read cookie string into buffer
const char *OP_MEMORY_VAR buf = NULL;
int version, max_version;
BOOL have_password = FALSE;
BOOL have_authentication = FALSE;
TRAP(op_stat, buf = g_url_api->GetCookiesL( url, version, max_version,
!!url.GetAttribute(URL::KHavePassword),
!!url.GetAttribute(URL::KHaveAuthentication),
have_password, have_authentication));
if (OpStatus::IsError(op_stat))
np_stat = OpStatus::IsMemoryError(op_stat) ? NPERR_OUT_OF_MEMORY_ERROR : NPERR_GENERIC_ERROR;
else if (buf)
np_stat = AllocateString(buf, value, len);
}
else
{ // NPNURLVProxy
OpString8 proxy;
#ifdef SUPPORT_AUTO_PROXY_CONFIGURATION
/* temporary disable fetching of automatic proxy configuration, as it requires asynchronous
fetching of information. Disapproved during code review.
if (g_pcnet->IsAutomaticProxyOn() &&
g_pcnet->GetStringPref(PrefsCollectionNetwork::AutomaticProxyConfigURL).CStr() &&
plug->GetDocument())
{ // use the automatic proxy configuration setting.
// Note that determining proxy information is url data storage dependant code, so the url must be loaded
op_stat = plug->GetDocument()->LoadInline(&url, plug->GetHtmlElement(), EMBED_INLINE, TRUE, TRUE);
if (OpStatus::IsSuccess(op_stat))
op_stat = url.GetAttribute(URL::KHTTPProxy, proxy);
np_stat = OpStatus::IsError(op_stat) ? (OpStatus::IsMemoryError(op_stat) ? NPERR_OUT_OF_MEMORY_ERROR : NPERR_GENERIC_ERROR) : NPERR_NO_ERROR;
}*/
#endif // SUPPORT_AUTO_PROXY_CONFIGURATION
if (np_stat == NPERR_NO_ERROR)
{
if (proxy.IsEmpty())
{ // check if any other proxy information is available from Prefs (no need to load the url)
if (ServerName *sn = (ServerName*)url.GetAttribute(URL::KServerName, NULL))
{
const uni_char* proxy_url = urlManager->GetProxy(sn, url.Type());
int proxy_len = proxy_url ? uni_strlen(proxy_url) : 0;
if (proxy_len > 0)
{
OP_STATUS conversion_stat = proxy.SetUTF8FromUTF16(proxy_url, proxy_len);
np_stat = OpStatus::IsError(conversion_stat) ? (OpStatus::IsMemoryError(conversion_stat) ? NPERR_OUT_OF_MEMORY_ERROR : NPERR_GENERIC_ERROR) : NPERR_NO_ERROR;
}
}
else
np_stat = NPERR_INVALID_URL;
}
if (np_stat == NPERR_NO_ERROR)
{
if (proxy.IsEmpty() || op_stricmp(proxy.CStr(), "DIRECT") == 0)
{ // default return value is "DIRECT"
np_stat = AllocateString("DIRECT", value, len);
}
else
{ // add "PROXY " before the proxy string
OpString8 add_proxy;
if (OpStatus::IsSuccess(op_stat = add_proxy.Set("PROXY ")) &&
OpStatus::IsSuccess(op_stat = add_proxy.Append(proxy.CStr())))
np_stat = AllocateString(add_proxy.CStr(), value, len);
else
np_stat = OpStatus::IsMemoryError(op_stat) ? NPERR_OUT_OF_MEMORY_ERROR : NPERR_GENERIC_ERROR;
}
}
}
}
}
else
np_stat = NPERR_INVALID_URL;
}
else
np_stat = NPERR_INVALID_PARAM;
}
else
np_stat = NPERR_INVALID_INSTANCE_ERROR;
return np_stat;
}
NPError __export NPN_SetValueForURL(NPP instance, NPNURLVariable variable, const char *url_name, const char *value, uint32_t len)
{
OP_NEW_DBG("NPN_SetValueForURL", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
// It seems to be semi-allowed to run this in the wrong thread
// so until we know more, we just log it.
}
/* Require valid plug-in instance parameter. */
if (!g_pluginhandler || !instance || !g_pluginhandler->FindPlugin(instance))
return NPERR_INVALID_INSTANCE_ERROR;
/* Require non-empty cookie. */
if (variable != NPNURLVCookie || !value || !len)
return NPERR_INVALID_PARAM;
/* Require non-empty, known and valid URL. */
if (!url_name || !*url_name)
return NPERR_INVALID_URL;
URL url = g_url_api->GetURL(url_name);
if (url.GetAttribute(URL::KHostName).IsEmpty())
return NPERR_INVALID_URL;
/* Make a null-terminated copy of the argument. */
char* val = OP_NEWA(char, len + 1);
if (!val)
return NPERR_OUT_OF_MEMORY_ERROR;
op_memcpy(val, value, len);
val[len] = 0;
// Build a list of cookie parameters, separated by ";", and check if the cookie contains the
// "httponly" parameter, which means that the cookie should be ignored, following Mozilla.
OP_STATUS op_stat = OpStatus::OK;
ParameterList p_list; ANCHOR(ParameterList, p_list);
TRAP(op_stat, p_list.SetValueL(val, PARAM_SEP_SEMICOLON | PARAM_ONLY_SEP));
if (OpStatus::IsSuccess(op_stat))
{
BOOL p_httponly = FALSE;
Parameters* p = p_list.First();
while (p && !p_httponly)
{
p_httponly = op_stricmp(p->Name(), "httponly") == 0;
p = p->Suc();
}
if (!p_httponly)
{ // Store the cookie value as received from the plug-in.
OpString8 cookie;
op_stat = cookie.Set(value, len);
if (OpStatus::IsSuccess(op_stat))
TRAP(op_stat, g_url_api->HandleSingleCookieL(url, cookie, cookie, 0));
}
}
OP_DELETEA(val);
if (OpStatus::IsMemoryError(op_stat))
return NPERR_OUT_OF_MEMORY_ERROR;
return OpStatus::IsError(op_stat) ? NPERR_GENERIC_ERROR : NPERR_NO_ERROR;
}
NPError __export NPN_GetAuthenticationInfo(NPP instance, const char *protocol, const char *host, int32_t port, const char *scheme, const char *realm, char **username, uint32_t *ulen, char **password, uint32_t *plen)
{
OP_NEW_DBG("NPN_GetAuthenticationInfo", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
// It seems to be semi-allowed to run this in the wrong thread
// so until we know more, we just log it.
}
NPError np_stat = NPERR_NO_ERROR;
Plugin* plug = g_pluginhandler && instance ? g_pluginhandler->FindPlugin(instance) : NULL;
if (plug)
{
if (instance && protocol && host && scheme && realm && username && ulen && password && plen)
{
const OpStringC8 sname(host);
if (ServerName *sn = static_cast<ServerName *>(g_url_api->GetServerName(sname)))
{
URLType url_type = g_opera->url_module.g_urlManager->MapUrlType(protocol);
if (url_type == URL_HTTP || url_type == URL_HTTPS)
{
AuthElm* auth = sn->Get_Auth(realm, port, NULL, url_type, AUTH_SCHEME_HTTP_UNKNOWN, 0);
if (!auth) // different input authentication scheme parameter for proxy authentication
auth = sn->Get_Auth(realm, port, NULL, url_type, AUTH_SCHEME_HTTP_PROXY, 0);
if (auth && auth->GetUser() && auth->GetPassword())
{
if ((np_stat = AllocateString(auth->GetUser(), username, ulen)) == NPERR_NO_ERROR)
np_stat = AllocateString(auth->GetPassword(), password, plen);
}
}
else
np_stat = NPERR_GENERIC_ERROR;
}
else
np_stat = NPERR_GENERIC_ERROR;
}
else
np_stat = NPERR_INVALID_PARAM;
}
else
np_stat = NPERR_INVALID_INSTANCE_ERROR;
return np_stat;
}
uint32_t __export NPN_ScheduleTimer(NPP instance, uint32_t interval, NPBool repeat, void (*timerFunc)(NPP npp, uint32_t timerID))
{
OP_NEW_DBG("NPN_ScheduleTimer", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
}
uint32_t timerID = 0;
if (g_pluginhandler && instance)
{
timerID = g_pluginhandler->ScheduleTimer(instance, interval, !!repeat, timerFunc);
}
return timerID;
}
void __export NPN_UnscheduleTimer(NPP instance, uint32_t timerID)
{
OP_NEW_DBG("NPN_UnscheduleTimer", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
}
if (g_pluginhandler)
{
g_pluginhandler->UnscheduleTimer(timerID);
}
}
NPError __export NPN_PopUpContextMenu(NPP instance, NPMenu* menu)
{
OP_NEW_DBG("NPN_PopUpContextMenu", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
}
NPError np_stat = NPERR_GENERIC_ERROR;
Plugin* plugin = g_pluginhandler ? g_pluginhandler->FindPlugin(instance) : NULL;
#ifdef USE_PLUGIN_EVENT_API
if (plugin && plugin->GetPluginWindow())
if (OpStatus::IsSuccess(plugin->GetPluginWindow()->PopUpContextMenu(menu)))
np_stat = NPERR_NO_ERROR;
#endif
return np_stat;
}
NPBool __export NPN_ConvertPoint(NPP instance, double sourceX, double sourceY, NPCoordinateSpace sourceSpace, double* destX, double* destY, NPCoordinateSpace destSpace)
{
OP_NEW_DBG("NPN_ConvertPoint", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
{
OP_DBG(("Function call from a plugin on the wrong thread"));
}
Plugin* plugin = g_pluginhandler ? g_pluginhandler->FindPlugin(instance) : NULL;
#ifdef USE_PLUGIN_EVENT_API
if (plugin && plugin->GetPluginWindow())
if (OpStatus::IsSuccess(plugin->GetPluginWindow()->ConvertPoint(sourceX, sourceY, sourceSpace, destX, destY, destSpace)))
return TRUE;
#endif
return FALSE;
}
NPBool __export NPN_HandleEvent(NPP instance, void *event, NPBool handled)
{
OP_NEW_DBG("NPN_HandleEvent", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
OP_DBG(("Function call from a plugin on the wrong thread"));
// Stub
return FALSE;
}
NPBool __export NPN_UnfocusInstance(NPP instance, NPFocusDirection direction)
{
OP_NEW_DBG("NPN_UnfocusInstance", "ns4p");
IN_CALL_FROM_PLUGIN
if (!g_op_system_info->IsInMainThread())
OP_DBG(("Function call from a plugin on the wrong thread"));
// Stub
return FALSE;
}
#endif // _PLUGIN_SUPPORT_
|
#include <iostream>
#include <cstdlib>
using namespace std;
int main (int argc, char* argv[]){
int a;
int b;
if (argc > 1){
a = atoi(argv[1]);
b = atoi(argv[2]);
}else{
cout << "Enter the first number: "<< endl;
cin >> a;
cout << "Enter the second number: "<< endl;
cin >> b;
}
if (b > a) {
int temp = b;
b = a;
a = temp;
}
int r = 1;
while (r != 0) {
r = a % b;
a = b;
b = r;
}
cout << "GCD is " << a << endl;
return EXIT_SUCCESS;
}
|
#ifndef TIGER_H
#define TIGER_H
#include "animal.h"
using namespace std;
class Tiger : public Animal{
private:
protected:
public:
//! Template for function header, DO NOT TOUCH
/******************************************************
** Function:
** Description:
** Parameters: NA
** Pre-conditions: NA
** Post-conditions: NA
******************************************************/
//! Functions of the class
/******************************************************
** Function: Tiger
** Description: Simple constructor for the tiger class.
** Parameters: NA
** Pre-conditions: NA
** Post-conditions: NA
******************************************************/
Tiger();
};
#endif
|
/*
access the sample web page at http://esp32fs.local
edit the page by going to http://esp32fs.local/edit
*/
#include <Wire.h>
#include <ESP.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Arduino.h>
#include <WiFiClientSecure.h>
#include <WebSocketsServer.h>
#include <ArduinoJson.h>
//#include <Preferences.h>
//Preferences preferences;
//#define FILESYSTEM SPIFFS
//#define FORMAT_FILESYSTEM true
#define FILESYSTEM SPIFFS
// You only need to format the filesystem once
#define FORMAT_FILESYSTEM true
//#define DBG_OUTPUT_PORT Serial
#if FILESYSTEM == FFat
#include <FFat.h>
#endif
#if FILESYSTEM == SPIFFS
#include <SPIFFS.h>
#endif
WebServer server(80);
//holds the current upload
File fsUploadFile;
#include "var.h"
#include "FSys.h"
#include "gpio.h"
#include "config.h"
#include "WifiSet.h"
WebSocketsServer webSocket = WebSocketsServer(81);
#include "i2cS.h"
#include "clock.h"
#include "mqtt.h"
#include "json.h"
#include "websocet.h"
#include "serial.h"
#include "wewebFS.h"
#include "sleep.h"
#include "buttons.h"
long stopaleep;
int count=0;
TaskHandle_t Task1;
TaskHandle_t Task2;
void setup(void) {
FILESYSTEM.begin();
Wire.begin(22,21);//22=SDA,21=SCL
AllPinSetup();
restoreConfig();
setSerial();
setFILESYSTEM();
setupButtons();
print_wakeup_touchpad();
print_wakeup_reason();
if (settingMode == false) {setupSTAmode(); }
else{TimerInterup=0;setupAPmode();}
serverINIT();
if (settingMode == false) { getNTPtime(); printLocalTime();}
//TFTsetup();
//here the list of headers to be recorded
const char * headerkeys[] = {"User-Agent", "Cookie"} ;
size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*);
//ask server to track these headers
server.collectHeaders(headerkeys, headerkeyssize);
server.begin();
Serial.println("HTTP server started");
if(mqttOnOff==1 && NETstatus!=0 && settingMode == false){MqttSetup();}
stopaleep=5000+millis();
//dubgIO(IO12);
websocetsetup();
// readFile("/config.txt");
// readFile("/2GPIO.txt");
// MqttTimer=millis()+5000;
Serial.println(xPortGetCoreID());
//create a task that will be executed in the Task1code() function, with priority 1 and executed on core 0
xTaskCreatePinnedToCore(
Task1code, /* Task function. */
"Task1", /* name of task. */
10000, /* Stack size of task */
NULL, /* parameter of the task */
1, /* priority of the task */
&Task1, /* Task handle to keep track of created task */
0); /* pin task to core 0 */
delay(500);
//create a task that will be executed in the Task2code() function, with priority 1 and executed on core 1
xTaskCreatePinnedToCore(
Task2code, /* Task function. */
"Task2", /* name of task. */
10000, /* Stack size of task */
NULL, /* parameter of the task */
2, /* priority of the task */
&Task2, /* Task handle to keep track of created task */
1); /* pin task to core 1 */
delay(500);
}
void Task1code( void * pvParameters ){
Serial.print("Task1 running on core ");
Serial.println(xPortGetCoreID());
// FILESYSTEM.format();
//MqttRipetM=millis() + (MqttrRipet*60)*1000;
for (;;) // A Task shall never return or exit.
{
delay(10);
buttonRun();
if( settingMode == false && WiFi.status() != WL_CONNECTED){ setupSTAmode();}
// else{TimerInterup=0;setupAPmode();}
if(mqttOnOff==1 && NETstatus!=0 && settingMode == false && MqttTimer<millis()){
if (!client.connected() && MqttTimerCountrer < 3) {reconnect();MqttTimer=millis()+5000;}
else{ MqttTimerCountrer = 0;client.loop();}
}
if( mqttConnection==1 && MQttRiperOnOff==1 && MqttRipetM < millis()){
MqttRipetM = millis() + (MqttrRipet*60)*1000;
MqttSendAll();
}
if( mqttConnection==1 && mqttferstmsg==0 && MqttMsgOnWekup==1 ){
MqttSendAll();
mqttferstmsg=1;
}
server.handleClient();
}
}
void Task2code( void * pvParameters ){
Serial.print("Task2 running on core ");
Serial.println(xPortGetCoreID());
for (;;)
{
delay(10);
interupSendMsg();
if(buad>=0 && buad<=12 ){serialEvent();}
webSocketloop();
if(stopaleep<millis()){sleeper();}
}
}
void loop(void) { }
|
#include "utils/functions.hpp"
#include <cppunit/extensions/HelperMacros.h>
#include <string>
namespace nora {
namespace test {
class functions_test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(functions_test);
CPPUNIT_TEST(test);
CPPUNIT_TEST_SUITE_END();
public:
void test();
};
CPPUNIT_TEST_SUITE_REGISTRATION(functions_test);
void functions_test::test() {
int a = 0;
functions<void> funcs;
funcs.add([&a] {a++;});
funcs();
CPPUNIT_ASSERT_EQUAL(1, a);
auto fi = funcs.add([&a] {a++;});
funcs();
CPPUNIT_ASSERT_EQUAL(3, a);
funcs.remove(fi);
funcs();
CPPUNIT_ASSERT_EQUAL(4, a);
}
}
}
|
//
// updater.h
// auto updater
//
// Created by FancyZero on 13-4-18.
//
//
#ifndef __auto_updater__updater__
#define __auto_updater__updater__
#include <iostream>
#include <string>
#include <vector>
class download_manager;
struct file_list_item
{
file_list_item()
:compressed(false)
{
}
bool compressed;
std::string hash;
std::string local_path;
std::string src_url;
std::string collection;
};
typedef std::vector<file_list_item> FILE_LIST;
struct file_list
{
public:
const file_list_item* get_file_list_item( const std::string& local_path );
bool load_from_file( const std::string& filename );
void add_item( const file_list_item& item );
FILE_LIST m_list;
};
class update_manager
{
public:
update_manager();
~update_manager();
/*
获取某个 文件集合(collection) 的更新列表
//如果 collection 为空,则表示包含所有文件
*/
bool download_files( const file_list& fl );
file_list get_update_list( const std::string& collection );
std::string get_full_path( const std::string& local_path );
bool load_file_list( const std::string& filename );
void set_download_manager( download_manager* man )
{
m_download_manager = man;
}
void set_root_path( const std::string& path )
{
m_root_path = path;
}
bool update_file_collection( const std::string& collection );
bool is_update_finished();
bool update_file_list( const std::string& url, const std::string& local_file, const std::string& hash );
protected:
download_manager* m_download_manager;
std::string m_root_path;
file_list m_file_list;
};
#endif /* defined(__auto_updater__updater__) */
|
#pragma once
namespace aeEngineSDK
{
class AE_GRAPHICS_EXPORT aeInputLayout : public aeGraphicsResource
{
protected:
aeInputLayout();
INPUTLAYOUT_DATA* m_pData;
friend class aeGraphicsAPI;
friend class aeRenderer;
public:
aeInputLayout(const aeInputLayout& S);
virtual ~aeInputLayout();
void Release();
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef PREF_ACCESSORS_H
#define PREF_ACCESSORS_H
/**
* @file
* Generic preference accessors.
* @author Wojciech Dzierzanowski (wdzierzanowski)
*/
#include "modules/prefs/prefsmanager/collections/pc_files.h"
namespace PrefUtils
{
/**
* Reads from and writes to a single integer preference.
*/
class IntegerAccessor
{
public:
virtual ~IntegerAccessor() {}
/**
* @return the current preference value
*/
virtual int GetPref() = 0;
/**
* Sets a new preference value.
*
* @param value the new value
* @return status
*/
virtual OP_STATUS SetPref(int value) = 0;
};
/**
* Implements IntegerAccessor for some preference collection type.
* @param C preference collection type
*/
template <typename C>
class IntegerAccessorImpl : public IntegerAccessor
{
public:
typedef typename C::integerpref PrefType;
/**
* Constructs an accessor that will read from and write to a specific
* integer preference in a specific collection.
*
* @param collection the preference collection
* @param preference the preference in @a collection
*/
IntegerAccessorImpl(C& collection, PrefType preference)
: m_collection(collection), m_preference(preference) {}
virtual int GetPref() { return m_collection.GetIntegerPref(m_preference); }
virtual OP_STATUS SetPref(int value)
{
RETURN_IF_LEAVE(m_collection.WriteIntegerL(m_preference, value));
return OpStatus::OK;
}
private:
C& m_collection;
PrefType m_preference;
};
/**
* Reads from and writes to a single string preference.
*/
class StringAccessor
{
public:
virtual ~StringAccessor() {}
/**
* @param value receives the current preference value
* @return status
*/
virtual OP_STATUS GetPref(OpString& value) = 0;
/**
* Sets a new preference value.
*
* @param value the new value
* @return status
*/
virtual OP_STATUS SetPref(const OpStringC& value) = 0;
};
/**
* Implements StringAccessor for some preference collection type.
* @param C preference collection type
*/
template <typename C>
class StringAccessorImpl : public StringAccessor
{
public:
typedef typename C::stringpref PrefType;
/**
* Constructs an accessor that will read from and write to a specific
* string preference in a specific collection.
*
* @param collection the preference collection
* @param preference the preference in @a collection
*/
StringAccessorImpl(C& collection, PrefType preference)
: m_collection(collection), m_preference(preference) {}
virtual OP_STATUS GetPref(OpString& value)
{
return value.Set(m_collection.GetStringPref(m_preference));
}
virtual OP_STATUS SetPref(const OpStringC& value)
{
RETURN_IF_LEAVE(m_collection.WriteStringL(m_preference, value));
return OpStatus::OK;
}
private:
C& m_collection;
PrefType m_preference;
};
/**
* A StringAccessor accessing the file preference collection.
*/
class FilePathAccessor : public StringAccessor
{
public:
/**
* Constructs an accessor that will read from and write to a specific
* file preference in PrefsCollectionFiles.
*
* @param preference the preference
*/
explicit FilePathAccessor(PrefsCollectionFiles::filepref preference) : m_preference(preference) {}
virtual OP_STATUS GetPref(OpString& value)
{
return value.Set(g_pcfiles->GetFile(m_preference)->GetFullPath());
}
virtual OP_STATUS SetPref(const OpStringC& value)
{
OpFile file;
RETURN_IF_ERROR(file.Construct(value));
RETURN_IF_LEAVE(g_pcfiles->WriteFilePrefL(m_preference, &file));
return OpStatus::OK;
}
private:
PrefsCollectionFiles::filepref m_preference;
};
}
#endif // PREF_ACCESSORS_H
|
#ifndef __CHATTY_BUFFER_H__
#define __CHATTY_BUFFER_H__
namespace chatty {
namespace net {
class Buffer {};
} // namespace net
} // namespace chatty
#endif // __CHATTY_BUFFER_H__
|
/*
* Copyright (c) 2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_FIXED_MERGE_EXCHANGE_NETWORK_SORTER_H_
#define CPPSORT_FIXED_MERGE_EXCHANGE_NETWORK_SORTER_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <array>
#include <cstddef>
#include <functional>
#include <iterator>
#include <type_traits>
#include <utility>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
#include <cpp-sort/utility/sorting_networks.h>
#include "../detail/attributes.h"
#include "../detail/bitops.h"
#include "../detail/empty_sorter.h"
#include "../detail/iterator_traits.h"
#include "../detail/make_array.h"
namespace cppsort
{
////////////////////////////////////////////////////////////
// Adapter
template<std::size_t N>
struct merge_exchange_network_sorter;
namespace detail
{
template<typename DifferenceType>
constexpr auto merge_exchange_pairs_number(DifferenceType n) noexcept
-> DifferenceType
{
DifferenceType nb_pairs = 0;
DifferenceType t = detail::ceil_log2(n);
for (DifferenceType p = 1 << (t - 1); p > 0; p /= 2) {
DifferenceType q = 1 << (t - 1);
DifferenceType r = 0;
DifferenceType d = p;
while (d > 0) {
for (DifferenceType i = 0; i < n - d; ++i) {
if ((i & p) == r) {
++nb_pairs;
}
}
d = q - p;
q /= 2;
r = p;
}
}
return nb_pairs;
}
template<std::size_t N>
struct merge_exchange_network_sorter_impl
{
template<typename DifferenceType=std::ptrdiff_t>
CPPSORT_ATTRIBUTE_NODISCARD
static constexpr auto index_pairs()
-> auto
{
constexpr DifferenceType n = N;
constexpr DifferenceType nb_pairs = merge_exchange_pairs_number(n);
utility::index_pair<DifferenceType> pairs[nb_pairs] = {};
std::size_t current_pair_idx = 0;
DifferenceType t = detail::ceil_log2(n);
for (DifferenceType p = 1 << (t - 1); p > 0; p /= 2) {
DifferenceType q = 1 << (t - 1);
DifferenceType r = 0;
DifferenceType d = p;
while (d > 0) {
for (DifferenceType i = 0; i < n - d; ++i) {
if ((i & p) == r) {
pairs[current_pair_idx] = { i, i + d };
++current_pair_idx;
}
}
d = q - p;
q /= 2;
r = p;
}
}
return cppsort::detail::make_array(pairs);
}
template<
typename RandomAccessIterator,
typename Compare = std::less<>,
typename Projection = utility::identity,
typename = std::enable_if_t<is_projection_iterator_v<
Projection, RandomAccessIterator, Compare
>>
>
constexpr auto operator()(RandomAccessIterator first, RandomAccessIterator,
Compare compare={}, Projection projection={}) const
-> void
{
using difference_type = difference_type_t<RandomAccessIterator>;
auto pairs = index_pairs<difference_type>();
utility::swap_index_pairs(first, pairs, std::move(compare), std::move(projection));
}
};
template<>
struct merge_exchange_network_sorter_impl<0u>:
cppsort::detail::empty_network_sorter_impl
{};
template<>
struct merge_exchange_network_sorter_impl<1u>:
cppsort::detail::empty_network_sorter_impl
{};
}
template<std::size_t N>
struct merge_exchange_network_sorter:
sorter_facade<detail::merge_exchange_network_sorter_impl<N>>
{};
////////////////////////////////////////////////////////////
// Sorter traits
template<std::size_t N>
struct sorter_traits<merge_exchange_network_sorter<N>>
{
using iterator_category = std::random_access_iterator_tag;
using is_always_stable = std::false_type;
};
template<>
struct fixed_sorter_traits<merge_exchange_network_sorter>
{
using iterator_category = std::random_access_iterator_tag;
using is_always_stable = std::false_type;
};
}
#endif // CPPSORT_FIXED_MERGE_EXCHANGE_NETWORK_SORTER_H_
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int n, reverse=0, temp;
scanf("%d",&n);
temp=n;
while(temp!=0)
{
reverse = reverse*10;
reverse = reverse+temp%10;
temp = temp/10;
}
if(n==reverse)
printf("%d is Palindrome.\n",n);
else
printf("This is noT Palindrome.\n");
return 0;
}
|
//
// Created by abel_ on 23-08-2021.
//
#include <bits/stdc++.h>
using namespace std;
int main() {
map<string,int> m;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
m[s]++;
}
for(auto pr : m){
cout << pr.first << " " << pr.second << endl;
}
}
|
// RsaToolbox
#include "Vna.h"
using namespace RsaToolbox;
// Qt
#include <QCoreApplication>
#include <QDir>
#include <QVector>
void main()
{
Vna vna(ConnectionType::VisaTcpConnection, "127.0.0.1");
// Start from instrument preset
vna.preset();
vna.pause();
// Channel 1 interface
// Optional. Could also use
// vna.channel(index).<method>(..)
VnaChannel ch1 = vna.channel(1);
// Configure balanced ports
// Logical Port 1: Physical ports (1, 3);
// Logical Port 2: Physical ports (2, 4);
ch1.createBalancedPort(1, 1, 3);
ch1.createBalancedPort(2, 2, 4);
// Set sweep type
ch1.setSweepType(VnaChannel::SweepType::Linear);
// Set sweep settings manually
VnaLinearSweep ch1Sweep = ch1.linearSweep();
ch1Sweep.setStart(10, SiPrefix::Mega); // 10 MHz
ch1Sweep.setStop (20, SiPrefix::Giga); // 20 GHz
ch1Sweep.setPoints(2000);
ch1Sweep.setIfbandwidth(1, SiPrefix::Kilo); // 1 KHz
ch1Sweep.setPower(0); // 0 dBm
// ...Alternatively:
// Set harmonic sweep settings.
// Time domain traces require
// harmonic frequency settings.
//
// For this example,
// Result:
// Start: 10 MHz
// Stop: 20 GHz
// Points: 2000
// Spacing: 10 MHz
// Each frequency point is a harmonic of 10 MHz
const double stop_Hz = 20e9;
const uint points = 2000;
ch1Sweep.createHarmonicGrid(stop_Hz, points);
// Create a new channel
// with next index
uint nextIndex = vna.createChannel();
// Create a new channel
// with a specifix index
vna.createChannel(3);
// Copy a channel
// Note: when creating a
// channel, new channel has
// same settings as last
// active channel.
ch1.select(); // Now active
vna.createChannel(4); // Copy of 1
// Save measurement to
// snp file on host computer
// Formats:
// DecibelDegrees
// MagnitudeDegrees
// RealImaginary
QDir src(SOURCE_DIR);
QVector<uint> ports;
ports << 1 << 2 << 3 << 4;
ch1Sweep.measureToSnpLocally(src.filePath("filename.s4p"), ports, ComplexFormat::RealImaginary);
}
|
/**
* Functions related to integral images
*
* @version $Version: 2018.11.13$
* @copyright Copyright (c) 2004-present, Mauricio Villegas <mauricio_ville@yahoo.com>
* @license MIT License
*/
#include "intimg.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int malloc_II1( int imW, int imH, II1*** _II, char clr )
{ return mmem(imW,imH,sizeof(II1),clr,(char***)_II); }
int malloc_II2( int imW, int imH, II2*** _II, char clr )
{ return mmem(imW,imH,sizeof(II2),clr,(char***)_II); }
int compII12_graym(gray** img, gray** alph, int imgW, int imgH, II1** ii1, II2** ii2, II1** cnt) {
int x,y;
if(imgW*imgH>66051 && sizeof(II2)<=4)
fprintf(stderr,"compII12_graym: warning: posible II overflow.\n");
if(alph!=NULL)
for(y=0;y<imgH;y++)
for(x=0;x<imgW;x++)
if(alph[y][x]==0)
img[y][x]=0;
if(alph!=NULL)
cnt[0][0] = alph[0][0] ? 1 : 0;
ii1[0][0] = (II1)img[0][0];
if(ii2!=NULL)
ii2[0][0] = (II2)img[0][0]*(II2)img[0][0];
for(y=1;y<imgH;y++) {
if(alph!=NULL)
cnt[y][0] = cnt[y-1][0] + ( alph[y][0] ? 1 : 0 );
ii1[y][0] = ii1[y-1][0]+(II1)img[y][0];
if(ii2!=NULL)
ii2[y][0] = ii2[y-1][0]+(II2)img[y][0]*(II2)img[y][0];
}
for(x=1;x<imgW;x++) {
if(alph!=NULL)
cnt[0][x] = cnt[0][x-1] + ( alph[0][x] ? 1 : 0 );
ii1[0][x] = ii1[0][x-1]+(II1)img[0][x];
if(ii2!=NULL)
ii2[0][x] = ii2[0][x-1]+(II2)img[0][x]*(II2)img[0][x];
}
for(y=1;y<imgH;y++)
for(x=1;x<imgW;x++) {
if(alph!=NULL)
cnt[y][x] = cnt[y-1][x]+cnt[y][x-1]-cnt[y-1][x-1] + ( alph[y][x] ? 1 : 0 );
ii1[y][x] = ii1[y-1][x]+ii1[y][x-1]-ii1[y-1][x-1]+(II1)img[y][x];
if(ii2!=NULL)
ii2[y][x] = ii2[y-1][x]+ii2[y][x-1]-ii2[y-1][x-1]+(II2)img[y][x]*(II2)img[y][x];
}
return EXIT_SUCCESS;
}
int cropsum_II(II1** ii1, int xmin, int ymin, int cropW, int cropH) {
int xminm1 = xmin-1;
int yminm1 = ymin-1;
int xmax = xminm1+cropW;
int ymax = yminm1+cropH;
II1 S1 = ii1[ymax][xmax];
if(yminm1>-1) {
S1 -= ii1[yminm1][xmax];
if(xminm1>-1)
S1 += ii1[yminm1][xminm1]-ii1[ymax][xminm1];
}
else if(xminm1>-1)
S1 -= ii1[ymax][xminm1];
return S1;
}
int mean_II(II1** ii1, II1** cnt, int xmin, int ymin, int cropW, int cropH, float* _mean) {
int xminm1 = xmin-1;
int yminm1 = ymin-1;
int xmax = xminm1+cropW;
int ymax = yminm1+cropH;
II1 S1 = ii1[ymax][xmax];
if(yminm1>-1) {
S1 -= ii1[yminm1][xmax];
if(xminm1>-1)
S1 += ii1[yminm1][xminm1]-ii1[ymax][xminm1];
}
else if(xminm1>-1)
S1 -= ii1[ymax][xminm1];
int numpix;
if(cnt!=NULL) {
numpix = cnt[ymax][xmax];
if(yminm1>-1) {
numpix -= cnt[yminm1][xmax];
if(xminm1>-1)
numpix += cnt[yminm1][xminm1]-cnt[ymax][xminm1];
}
else if(xminm1>-1)
numpix -= cnt[ymax][xminm1];
}
else
numpix = cropW*cropH;
*_mean = (float)((int)S1)/((float)numpix);
return EXIT_SUCCESS;
}
int sd_II(II1** ii1, II2** ii2, II1** cnt, int xmin, int ymin, int cropW, int cropH, float* _sd) {
int xminm1 = xmin-1;
int yminm1 = ymin-1;
int xmax = xminm1+cropW;
int ymax = yminm1+cropH;
II1 S1 = ii1[ymax][xmax];
II2 S2 = ii2[ymax][xmax];
if(yminm1>-1) {
S1 -= ii1[yminm1][xmax];
S2 -= ii2[yminm1][xmax];
if(xminm1>-1) {
S1 += ii1[yminm1][xminm1]-ii1[ymax][xminm1];
S2 += ii2[yminm1][xminm1]-ii2[ymax][xminm1];
}
}
else if(xminm1>-1) {
S1 -= ii1[ymax][xminm1];
S2 -= ii2[ymax][xminm1];
}
int numpix;
if(cnt!=NULL) {
numpix = cnt[ymax][xmax];
if(yminm1>-1) {
numpix -= cnt[yminm1][xmax];
if(xminm1>-1)
numpix += cnt[yminm1][xminm1]-cnt[ymax][xminm1];
}
else if(xminm1>-1)
numpix -= cnt[ymax][xminm1];
}
else
numpix = cropW*cropH;
float mean = (float)S1/(float)numpix;
if(((float)S2/(float)numpix - mean*mean) <= 0.0)
*_sd = 0;
else
*_sd = sqrt((float)S2/(float)numpix - mean*mean);
return EXIT_SUCCESS;
}
int meanSd_II(II1** ii1, II2** ii2, II1** cnt, int xmin, int ymin, int cropW, int cropH, float* _mean, float* _sd) {
int xminm1 = xmin-1;
int yminm1 = ymin-1;
int xmax = xminm1+cropW;
int ymax = yminm1+cropH;
II1 S1 = ii1[ymax][xmax];
II2 S2 = ii2[ymax][xmax];
if(yminm1>-1) {
S1 -= ii1[yminm1][xmax];
S2 -= ii2[yminm1][xmax];
if(xminm1>-1) {
S1 += ii1[yminm1][xminm1]-ii1[ymax][xminm1];
S2 += ii2[yminm1][xminm1]-ii2[ymax][xminm1];
}
}
else if(xminm1>-1) {
S1 -= ii1[ymax][xminm1];
S2 -= ii2[ymax][xminm1];
}
int numpix;
if(cnt!=NULL) {
numpix = cnt[ymax][xmax];
if(yminm1>-1) {
numpix -= cnt[yminm1][xmax];
if(xminm1>-1)
numpix += cnt[yminm1][xminm1]-cnt[ymax][xminm1];
}
else if(xminm1>-1)
numpix -= cnt[ymax][xminm1];
}
else
numpix = cropW*cropH;
*_mean = (float)((int)S1)/((float)numpix);
if(((float)S2/(float)numpix-(*_mean)*(*_mean)) <= 0.0)
*_sd = 0;
else
*_sd = sqrt((float)S2/(float)numpix-(*_mean)*(*_mean));
return EXIT_SUCCESS;
}
static inline void meanSdCW_II(int x, int y, int imgW, int imgH, II1** ii1, II2** ii2, II1** cnt, int winS, float* _mean, float* _sd) {
int ymin = y-winS;
ymin = ymin<0?0:ymin;
int ymax = y+winS;
ymax = ymax>=imgH?imgH-1:ymax;
int xmin = x-winS;
xmin = xmin<0?0:xmin;
int xmax = x+winS;
xmax = xmax>=imgW?imgW-1:xmax;
meanSd_II(ii1,ii2,cnt,xmin,ymin,xmax-xmin+1,ymax-ymin+1,_mean,_sd);
}
/*int enhSauvola_pixelm(pixel** img, gray** alph, int imgW, int imgH, int winW, float prm, float slp) {
gray** gimg = NULL;
II1** cnt = NULL;
II1** ii1 = NULL;
II2** ii2 = NULL;
int err = 0;
err += malloc_graym(imgW,imgH,&gimg,FALSE);
err += malloc_II1(imgW,imgH,&ii1,FALSE);
err += malloc_II2(imgW,imgH,&ii2,FALSE);
if(alph!=NULL)
err += malloc_II1(imgW,imgH,&cnt,FALSE);
if( err ) {
fprintf(stderr,"enhSauvola_pixelm: error: unable to reserve memory\n");
return EXIT_FAILURE;
}
int n;
for( n=imgW*imgH-1; n>=0; n-- )
gimg[0][n] = img[0][n].r;
if( enhSauvola_graym(gimg,alph,imgW,imgH,&ii1,&ii2,&cnt,winW,prm,slp) )
return EXIT_FAILURE;
for( n=imgW*imgH-1; n>=0; n-- ) {
img[0][n].r = gimg[0][n];
gimg[0][n] = img[0][n].g;
}
if( enhSauvola_graym(gimg,alph,imgW,imgH,&ii1,&ii2,&cnt,winW,prm,slp) )
return EXIT_FAILURE;
for( n=imgW*imgH-1; n>=0; n-- ) {
img[0][n].g = gimg[0][n];
gimg[0][n] = img[0][n].b;
}
if( enhSauvola_graym(gimg,alph,imgW,imgH,&ii1,&ii2,&cnt,winW,prm,slp) )
return EXIT_FAILURE;
for( n=imgW*imgH-1; n>=0; n-- )
img[0][n].b = gimg[0][n];
free(gimg);
free(ii1);
free(ii2);
if(alph!=NULL)
free(cnt);
return EXIT_SUCCESS;
}*/
static inline gray enhSauvola_single(int x, int y, gray** img, gray** alph, int imgW, int imgH, II1** ii1, II2** ii2, II1** cnt, int winS, float prm, float slp, float rng) {
if(alph!=NULL && alph[y][x]==0)
return (gray)255;
float mu,sd;
meanSdCW_II(x,y,imgW,imgH,ii1,ii2,cnt,winS,&mu,&sd);
float thr = mu*(1+prm*((sd/rng)-1));
if(slp==0.0) {
if(img[y][x]>thr)
return (gray)255;
else
return (gray)0;
}
else if(sd>1e-4) {
float m = 255.0/(2*slp*sd);
float c = 128-m*thr;
return limit_gray(m*img[y][x]+c);
}
else {
float fact=1.05;
float W;
for( W=fact*winS; W<2*imgW && W<2*imgH; W*=fact ) {
int winS = (int)(W+0.5);
float mu,sd;
meanSdCW_II(x,y,imgW,imgH,ii1,ii2,cnt,winS,&mu,&sd);
float thr = mu*(1+prm*((sd/rng)-1));
if(sd>1e-4) {
float m = 255.0/(2*slp*sd);
float c = 128-m*thr;
return limit_gray(m*img[y][x]+c);
}
}
}
return (gray)255;
}
static inline gray enhWolf_single(int x, int y, gray** img, gray** alph, int imgW, int imgH, II1** ii1, II2** ii2, II1** cnt, int winS, float prm, float slp, float rng, gray minv) {
if(alph!=NULL && alph[y][x]==0)
return (gray)255;
float mu,sd;
meanSdCW_II(x,y,imgW,imgH,ii1,ii2,cnt,winS,&mu,&sd);
float thr = (1-prm)*mu+prm*minv+prm*(sd/rng)*(mu-minv);
if(slp==0.0) {
if(img[y][x]>thr)
return (gray)255;
else
return (gray)0;
}
else if(sd>1e-4) {
float m = 255.0/(2*slp*sd);
float c = 128-m*thr;
return limit_gray(m*img[y][x]+c);
}
else {
float fact=1.05;
float W;
for( W=fact*winS; W<2*imgW && W<2*imgH; W*=fact ) {
int winS = (int)(W+0.5);
float mu,sd;
meanSdCW_II(x,y,imgW,imgH,ii1,ii2,cnt,winS,&mu,&sd);
float thr = (1-prm)*mu+prm*minv+prm*(sd/rng)*(mu-minv);
if(sd>1e-4) {
float m = 255.0/(2*slp*sd);
float c = 128-m*thr;
return limit_gray(m*img[y][x]+c);
}
}
}
return (gray)255;
}
static inline void minValmaxStd(gray** img, gray** alph, int imgW, int imgH, II1** ii1, II2** ii2, II1** cnt, int winS, gray* _minval, float* _maxstd) {
gray minval = 255;
float maxstd = 0.0;
int y;
for ( y=imgH-1; y>=0; y-- ) {
gray *imgy = img[y];
gray *alphy = alph!=NULL ? alph[y] : NULL;
int x;
for ( x=imgW-1; x>=0; x-- ) {
if( alph==NULL || alphy[x]!=0 ) {
float mu,sd;
meanSdCW_II(x,y,imgW,imgH,ii1,ii2,cnt,winS,&mu,&sd);
maxstd = maxstd < sd ? sd : maxstd ;
}
minval = minval > imgy[x] ? imgy[x] : minval ;
}
}
*_minval = minval;
*_maxstd = maxstd;
}
/*int enhSauvola_graym(gray** img, gray** alph, int imgW, int imgH, II1*** _ii1, II2*** _ii2, II1*** _cnt, int winW, float prm, float slp) {
if(*_ii1==NULL || *_ii2==NULL) {
int err = 0;
err += malloc_II1(imgW,imgH,_ii1,FALSE);
err += malloc_II2(imgW,imgH,_ii2,FALSE);
if(alph!=NULL)
err += malloc_II1(imgW,imgH,_cnt,FALSE);
if(err) {
fprintf(stderr,"enhSauvola_graym: error: unable to reserve memory\n");
return EXIT_FAILURE;
}
_ii1[0][imgH-1][imgW-1]=0;
}
if(_ii1[0][imgH-1][imgW-1]==0)
compII12_graym(img,alph,imgW,imgH,*_ii1,*_ii2,alph==NULL?NULL:*_cnt);
winW = winW/2;
II1 **cnt = alph==NULL ? NULL : *_cnt;
gray minval;
float maxstd;
minValmaxStd(img,alph,imgW,imgH,*_ii1,*_ii2,cnt,winW,&minval,&maxstd);
//maxsd = 128.0;
int y;
for(y=imgH-1;y>=0;y--) {
gray *imgy = img[y];
int x;
for(x=imgW-1;x>=0;x--)
imgy[x] = enhSauvola_single(x,y,img,alph,imgW,imgH,*_ii1,*_ii2,cnt,winW,prm,slp,maxstd);
}
return EXIT_SUCCESS;
}*/
int enhLocal_graym(gray** img, gray** alph, int imgW, int imgH, II1*** _ii1, II2*** _ii2, II1*** _cnt, int winW, float prm, float slp, int type) {
if(*_ii1==NULL || *_ii2==NULL) {
int err = 0;
err += malloc_II1(imgW,imgH,_ii1,FALSE);
err += malloc_II2(imgW,imgH,_ii2,FALSE);
if(alph!=NULL)
err += malloc_II1(imgW,imgH,_cnt,FALSE);
if(err) {
fprintf(stderr,"enhLocal_graym: error: unable to reserve memory\n");
return EXIT_FAILURE;
}
_ii1[0][imgH-1][imgW-1]=0;
}
if(_ii1[0][imgH-1][imgW-1]==0)
compII12_graym(img,alph,imgW,imgH,*_ii1,*_ii2,alph==NULL?NULL:*_cnt);
winW = winW/2;
II1 **cnt = alph==NULL ? NULL : *_cnt;
gray minval = 0;
float maxstd = 128.0;
if ( type == ENH_SAUVOLA_SDMAX || type == ENH_WOLF )
minValmaxStd(img,alph,imgW,imgH,*_ii1,*_ii2,cnt,winW,&minval,&maxstd);
int y;
for(y=imgH-1;y>=0;y--) {
gray *imgy = img[y];
int x;
for(x=imgW-1;x>=0;x--) {
if ( type == ENH_SAUVOLA || type == ENH_SAUVOLA_SDMAX )
imgy[x] = enhSauvola_single(x,y,img,alph,imgW,imgH,*_ii1,*_ii2,cnt,winW,prm,slp,maxstd);
else
imgy[x] = enhWolf_single(x,y,img,alph,imgW,imgH,*_ii1,*_ii2,cnt,winW,prm,slp,maxstd,minval);
}
}
return EXIT_SUCCESS;
}
int enhSauvola_sample_prm_graym(gray** img, gray** alph, int imgW, int imgH, II1*** _ii1, II2*** _ii2, II1*** _cnt, int winW, float slp, double *_prm, int subsamp, float prmthr) {
if(*_ii1==NULL || *_ii2==NULL) {
int err = 0;
err += malloc_II1(imgW,imgH,_ii1,FALSE);
err += malloc_II2(imgW,imgH,_ii2,FALSE);
if(alph!=NULL)
err += malloc_II1(imgW,imgH,_cnt,FALSE);
if(err) {
fprintf(stderr,"enhSauvola_sample_prm_graym: error: unable to reserve memory\n");
return EXIT_FAILURE;
}
_ii1[0][imgH-1][imgW-1]=0;
}
if(_ii1[0][imgH-1][imgW-1]==0)
compII12_graym(img,alph,imgW,imgH,*_ii1,*_ii2,alph==NULL?NULL:*_cnt);
winW = winW/2;
II1 **cnt = alph==NULL ? NULL : *_cnt;
static int Nprm = 10;
static int bins = 32;
static double histfact = 1.0/8.0;
float prms[] = { 0.02, 0.04, 0.06, 0.08, 0.12, 0.16, 0.20, 0.24, 0.32, 0.48 };
int hist[bins];
float histvals[bins];
//*_prm = 0.0;
int n;
for(n=0;n<Nprm;n++) {
float prm = prms[n];
int hcnt = 0;
int y;
for(y=bins-1;y>=0;y--)
hist[y] = 0;
for(y=imgH-1;y>=0;y-=subsamp) {
int x;
for(x=imgW-1;x>=0;x-=subsamp) {
if(alph!=NULL && alph[y][x]==0)
continue;
gray v = enhSauvola_single(x,y,img,alph,imgW,imgH,*_ii1,*_ii2,cnt,winW,prm,slp,128.0);
hist[(int)(v*histfact)]++;
hcnt++;
}
}
histvals[n] = hist[bins-2]/(double)hcnt;
//fprintf(stderr,"histval[ %.2f ] -> %.6f\n",prm,histvals[n]);
if( histvals[n] < prmthr ) {
//fprintf(stderr,"stopping\n");
//if(*_prm==0.0)
*_prm = prm;
return EXIT_SUCCESS;
}
}
double vmax = 0.0;
double vmin = 1.0;
for(n=0;n<Nprm;n++) {
if( vmax < histvals[n] )
vmax = histvals[n];
if( vmin > histvals[n] )
vmin = histvals[n];
}
double thr = (1.0/Nprm)*(vmax-vmin)+vmin;
for(n=0;n<Nprm-1;n++) {
if( histvals[n] < thr ||
histvals[n] == vmin ) {
//fprintf(stderr,"stopping at %.2f\n",prms[n]);
//if(*_prm==0.0)
*_prm = prms[n];
return EXIT_SUCCESS;
}
}
return EXIT_FAILURE;
}
/*
int maskExtend_graym(gray **img, gray **alph, int imgW, int imgH, int winW, float prm, float seR) {
gray **tmp;
int err = clone_graym(img,imgW,imgH,&tmp);
if(err) {
fprintf(stderr,"maskExtend_graym: error: unable to reserve memory\n");
return err;
}
II1** ii1 = NULL;
II2** ii2 = NULL;
err = enhSauvola_graym(tmp,NULL,imgW,imgH,&ii1,&ii2,NULL, winW, prm, 0);
if(err!=EXIT_SUCCESS) {
free(tmp);
return err;
}
free(ii1);
free(ii2);
SE *se;
//err = seCircle(seR,0,0,1,&se);
err = seCircle(seR,TRUE,FALSE,&se,NULL);
if(err) {
free(tmp);
return err;
}
err = morpherode_graym(tmp,imgW,imgH,se,tmp);
if(err!=EXIT_SUCCESS) {
free(tmp);
return err;
}
free(se);
int n;
for(n=imgW*imgH-1;n>=0;n--)
if(alph[0][n]==0 && tmp[0][n]!=0)
alph[0][n] = 255;
free(tmp);
return EXIT_SUCCESS;
}
*/
/*
int rgbm2graym_winproj(pixel** img, int imgW, int imgH, II1*** _ii1, II2*** _ii2, gray** out, float* base, int D) {
float min = base[0];
float rang = base[1];
int winW = base[D-1];
pixel *imgv = img[0];
gray *outv = out[0];
base = base+3;
D -= 3;
winW /= 2;
if(*_ii1==NULL || *_ii2==NULL) {
int err = 0;
err += malloc_II1(imgW,imgH,_ii1,0);
err += malloc_II2(imgW,imgH,_ii2,0);
if(err) {
fprintf(stderr,"rgbm2graym_proj_musd: error: unable to reserve memory\n");
return EXIT_FAILURE;
}
compII12_graym(img,NULL,imgW,imgH,*_ii1,*_ii2,NULL);
}
float gamma = 0;
if( D==6 || D==21 ) {
gamma = base[D-1];
rang = 1/(rang-min);
D --;
}
else
rang = IMGIO_GRAYMAX/(rang-min);
int x,y;
float pv;
switch(D) {
case 5:
for(y=imgH-1;y>=0;y--) {
imgv = img[y];
outv = out[y];
int ymin = y-winW < 0 ? 0 : y-winW;
int ymax = y+winW >= imgH-1 ? imgH-1 : y+winW;
for(x=imgW-1;x>=0;x--) {
pixel p = imgv[x];
int xmin = x-winW < 0 ? 0 : x-winW;
int xmax = x+winW >= imgW-1 ? imgW-1 : x+winW;
float mu,sd;
meanSd_II(*_ii1,*_ii2,NULL,xmin,ymin,xmax-xmin+1,ymax-ymin+1,&mu,&sd);
//fprintf(file," format 1: MIN MAX fR fG fB fM fS [GAM] WINW\n");
pv =
base[0]*p.r + base[1]*p.g + base[2]*p.b + base[3]*mu + base[4]*sd;
if(gamma)
outv[x] = limit_gray( IMGIO_GRAYMAX*gamma_correct(rang*(pv-min),gamma)+0.5 );
else
outv[x] = limit_gray( rang*(pv-min)+0.5 );
}
}
break;
case 20:
for(y=imgH-1;y>=0;y--) {
imgv = img[y];
outv = out[y];
int ymin = y-winW < 0 ? 0 : y-winW;
int ymax = y+winW >= imgH-1 ? imgH-1 : y+winW;
for(x=imgW-1;x>=0;x--) {
pixel p = imgv[x];
int xmin = x-winW < 0 ? 0 : x-winW;
int xmax = x+winW >= imgW-1 ? imgW-1 : x+winW;
float mu,sd;
meanSd_II(*_ii1,*_ii2,NULL,xmin,ymin,xmax-xmin+1,ymax-ymin+1,&mu,&sd);
//fprintf(file," format 2: MIN MAX fR fG fB fRG fGB fRB fRR fGG fBB fM fS fMS fMR fMG fMB fSR fSG fSB fMM fSS [GAM] WINW\n");
pv =
base[0]*p.r + base[1]*p.g + base[2]*p.b +
base[3]*p.r*p.g + base[4]*p.g*p.b + base[5]*p.r*p.b +
base[6]*p.r*p.r + base[7]*p.g*p.g + base[8]*p.b*p.b +
base[9]*mu + base[10]*sd + base[11]*mu*sd +
base[12]*mu*p.r + base[13]*mu*p.g + base[14]*mu*p.b +
base[15]*sd*p.r + base[16]*sd*p.g + base[17]*sd*p.b +
base[18]*mu*mu + base[19]*sd*sd;
if(gamma)
outv[x] = limit_gray( IMGIO_GRAYMAX*gamma_correct(rang*(pv-min),gamma)+0.5 );
else
outv[x] = limit_gray( rang*(pv-min)+0.5 );
}
}
break;
default:
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
*/
|
#ifndef CLASSTABLE_H
#define CLASSTABLE_H
#include <QStandardItemModel>
#include <QColorDialog>
#include "hmldefinitions.h"
class ClassTableModel : public QStandardItemModel
{
Q_OBJECT
public:
ClassTableModel(QObject *parent = 0);
~ClassTableModel();
QStringList getClassNames();
bool textAlreadyExists(QStandardItem* pItem);
void renameClass(QStandardItem* pItem);
signals:
void colorChanged(QModelIndex index);
public slots:
void addClass();
void onColorSelection(QModelIndex index);
protected:
};
#endif // CLASSTABLE_H
|
#pragma once
#include "SceneManager.h"
#include "Button.h"
class Menu : public SceneManager
{
private:
Button playButton;
Button soundButton;
Button rankingButton;
Button exitButton;
public:
Menu();
void Update(bool * _keys, Vec2 _mousePosition);
PlayerRankingInfo GetPlayerRankingInfo();
void Draw();
~Menu();
};
|
#include <octomap/octomap.h>
#include "testing.h"
using namespace std;
using namespace octomap;
using namespace octomath;
int main(int /*argc*/, char** /*argv*/) {
float res = 0.01f;
OcTree tree(res);
EXPECT_EQ(tree.size(), 0);
tree.prune();
EXPECT_EQ(tree.size(), 0);
point3d singlePt(-0.05f, -0.02f, 1.0f);
OcTreeKey singleKey;
tree.coordToKeyChecked(singlePt, singleKey);
OcTreeNode* singleNode = tree.updateNode(singleKey, true);
EXPECT_TRUE(singleNode);
EXPECT_EQ(singleNode, tree.search(singlePt));
OcTreeKey key;
// check all neighbors, none should exist:
for (key[2] = singleKey[2] - 1; key[2] <= singleKey[2] + 1; ++key[2]){
for (key[1] = singleKey[1] - 1; key[1] <= singleKey[1] + 1; ++key[1]){
for (key[0] = singleKey[0] - 1; key[0] <= singleKey[0] + 1; ++key[0]){
if (key != singleKey){
OcTreeNode* node = tree.search(key);
EXPECT_FALSE(node);
} else {
OcTreeNode* node = tree.search(key);
EXPECT_TRUE(node);
EXPECT_EQ(singleNode, node);
}
}
}
}
// pruning should do nothing:
tree.prune();
for (key[2] = singleKey[2] - 1; key[2] <= singleKey[2] + 1; ++key[2]){
for (key[1] = singleKey[1] - 1; key[1] <= singleKey[1] + 1; ++key[1]){
for (key[0] = singleKey[0] - 1; key[0] <= singleKey[0] + 1; ++key[0]){
if (key != singleKey){
OcTreeNode* node = tree.search(key);
EXPECT_FALSE(node);
} else {
OcTreeNode* node = tree.search(key);
EXPECT_TRUE(node);
EXPECT_EQ(singleNode, node);
}
}
}
}
// node + 1 branch of depth 16
EXPECT_EQ(tree.calcNumNodes(), tree.size());
EXPECT_EQ(tree.size(), 17);
// create diagonal neighbor in same parent node
OcTreeKey singleKey2 = singleKey;
singleKey2[0] +=1;
singleKey2[1] +=1;
singleKey2[2] +=1;
OcTreeNode* singleNode2 = tree.updateNode(singleKey2, true);
EXPECT_TRUE(singleNode2);
for (key[2] = singleKey[2] - 1; key[2] <= singleKey[2] + 1; ++key[2]){
for (key[1] = singleKey[1] - 1; key[1] <= singleKey[1] + 1; ++key[1]){
for (key[0] = singleKey[0] - 1; key[0] <= singleKey[0] + 1; ++key[0]){
if (key == singleKey){
OcTreeNode* node = tree.search(key);
EXPECT_TRUE(node);
EXPECT_EQ(singleNode, node);
} else if (key == singleKey2){
OcTreeNode* node = tree.search(key);
EXPECT_TRUE(node);
EXPECT_EQ(singleNode2, node);
} else{
OcTreeNode* node = tree.search(key);
EXPECT_FALSE(node);
}
}
}
}
EXPECT_EQ(tree.calcNumNodes(), tree.size());
EXPECT_EQ(tree.size(), 18); // one more leaf at lowest level
// pruning should do nothing:
tree.prune();
for (key[2] = singleKey[2] - 1; key[2] <= singleKey[2] + 1; ++key[2]){
for (key[1] = singleKey[1] - 1; key[1] <= singleKey[1] + 1; ++key[1]){
for (key[0] = singleKey[0] - 1; key[0] <= singleKey[0] + 1; ++key[0]){
if (key == singleKey){
OcTreeNode* node = tree.search(key);
EXPECT_TRUE(node);
EXPECT_EQ(singleNode, node);
} else if (key == singleKey2){
OcTreeNode* node = tree.search(key);
EXPECT_TRUE(node);
EXPECT_EQ(singleNode2, node);
} else{
OcTreeNode* node = tree.search(key);
EXPECT_FALSE(node);
}
}
}
}
EXPECT_EQ(tree.calcNumNodes(), tree.size());
EXPECT_EQ(tree.size(), 18);
//tree.write("pruning_test_out0.ot");
// fill the complete octant, should auto-prune
tree.updateNode(OcTreeKey(singleKey[0]+1, singleKey[1]+0, singleKey[2]+0), true);
tree.updateNode(OcTreeKey(singleKey[0]+1, singleKey[1]+1, singleKey[2]+0), true);
tree.updateNode(OcTreeKey(singleKey[0]+0, singleKey[1]+1, singleKey[2]+0), true);
tree.updateNode(OcTreeKey(singleKey[0]+0, singleKey[1]+0, singleKey[2]+1), true);
tree.updateNode(OcTreeKey(singleKey[0]+1, singleKey[1]+0, singleKey[2]+1), true);
EXPECT_EQ(tree.size(), 23);
// last node should trigger auto-pruning:
OcTreeNode* prunedNode = tree.updateNode(OcTreeKey(singleKey[0]+0, singleKey[1]+1, singleKey[2]+1), true);
EXPECT_EQ(tree.size(), 16);
// all queries should now end up at same parent node:
OcTreeNode* parentNode = tree.search(singleKey);
OcTreeNode* parentNode2 = tree.search(singleKey2);
EXPECT_EQ(parentNode, parentNode2);
// test pointer returned by updateNode (pruned)
EXPECT_EQ(prunedNode, parentNode);
//tree.write("pruning_test_out1.ot");
// now test larger volume pruning:
for (float x=0.005f; x <= 0.32f; x+=res){
for (float y=0.005f; y <= 0.32f; y+=res){
for (float z=0.005f; z <= 0.32f; z+=res){
OcTreeNode* node = tree.updateNode(point3d(x,y,z), true);
EXPECT_TRUE(node);
EXPECT_TRUE(tree.isNodeOccupied(node));
}
}
}
EXPECT_EQ(tree.calcNumNodes(), tree.size());
EXPECT_EQ(27, tree.size());
// TODO: replace with test for lazy eval?
tree.prune();
EXPECT_EQ(tree.calcNumNodes(), tree.size());
EXPECT_EQ(27, tree.size());
tree.expand();
EXPECT_EQ(tree.calcNumNodes(), tree.size());
EXPECT_EQ(37483, tree.size());
tree.prune();
EXPECT_EQ(27, tree.size());
// test expansion:
for (float x=0.005f; x <= 0.32f; x+=res){
for (float y=0.005f; y <= 0.32f; y+=res){
for (float z=0.005f; z <= 0.32f; z+=res){
OcTreeNode* node = tree.search(point3d(x,y,z));
EXPECT_TRUE(node);
EXPECT_TRUE(tree.isNodeOccupied(node));
}
}
}
tree.coordToKeyChecked(point3d(0.1f, 0.1f, 0.1f), singleKey);
EXPECT_TRUE(tree.updateNode(singleKey, true));
for (float x=0.005f; x <= 0.32f; x+=res){
for (float y=0.005f; y <= 0.32f; y+=res){
for (float z=0.005f; z <= 0.32f; z+=res){
OcTreeNode* node = tree.search(point3d(x,y,z));
EXPECT_TRUE(node);
EXPECT_TRUE(tree.isNodeOccupied(node));
}
}
}
EXPECT_EQ(tree.calcNumNodes(), tree.size());
EXPECT_EQ(67, tree.size());
// test deletion / pruning of single nodes
{
std::cout << "\nCreating / deleting nodes\n===============================\n";
size_t initialSize = tree.size();
EXPECT_EQ(initialSize, tree.calcNumNodes());
EXPECT_EQ(initialSize, 67);
point3d newCoord(-2.0, -2.0, -2.0);
OcTreeNode* newNode = tree.updateNode(newCoord, true);
EXPECT_TRUE(newNode != NULL);
size_t insertedSize = tree.size();
std::cout << "Size after one insertion: " << insertedSize << std::endl;
EXPECT_EQ(insertedSize, tree.calcNumNodes());
EXPECT_EQ(insertedSize, 83);
// find parent of newly inserted node:
OcTreeNode* parentNode = tree.search(newCoord, tree.getTreeDepth() -1);
EXPECT_TRUE(parentNode);
EXPECT_TRUE(tree.nodeHasChildren(parentNode));
// only one child exists:
for (size_t i = 0; i < 7; ++i){
EXPECT_FALSE(tree.nodeChildExists(parentNode, i));
}
EXPECT_TRUE(tree.nodeChildExists(parentNode, 7));
// create another new node manually:
OcTreeNode* newNodeCreated = tree.createNodeChild(parentNode, 0);
EXPECT_TRUE(newNodeCreated != NULL);
EXPECT_TRUE(tree.nodeChildExists(parentNode, 0));
const float value = 0.123f;
newNodeCreated->setValue(value);
tree.write("pruning_test_edited.ot");
EXPECT_EQ(tree.size(), tree.calcNumNodes());
EXPECT_EQ(tree.size(), insertedSize+1);
tree.prune();
EXPECT_EQ(tree.calcNumNodes(), insertedSize+1);
tree.deleteNodeChild(parentNode, 0);
tree.deleteNodeChild(parentNode, 7);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
EXPECT_EQ(tree.size(), insertedSize-1);
tree.prune();
EXPECT_EQ(tree.size(), tree.calcNumNodes());
EXPECT_EQ(tree.size(), insertedSize-1);
tree.expandNode(parentNode);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
EXPECT_EQ(tree.size(), insertedSize+7);
EXPECT_TRUE(tree.pruneNode(parentNode));
EXPECT_EQ(tree.size(), tree.calcNumNodes());
EXPECT_EQ(tree.size(), insertedSize-1);
}
tree.write("pruning_test_out.ot");
{
std::cout << "\nClearing tree / recursive delete\n===============================\n";
OcTree emptyTree(0.1234);
EXPECT_EQ(emptyTree.size(), 0);
emptyTree.clear();
EXPECT_EQ(emptyTree.size(), emptyTree.calcNumNodes());
EXPECT_EQ(emptyTree.size(), 0);
tree.clear();
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.prune();
EXPECT_EQ(tree.size(), 0);
}
tree.write("pruning_test_out.ot");
std::cerr << "Test successful.\n";
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int t;
while(cin>>t)
{
int i, a;
for(i=1; i<=t; i++)
{
cin>>a;
if(360%(180-a)==0)cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
return 0;
}
|
#include "rules.h"
rules::rules()
{
}
rules::rules(float width, float height)
{
if (!font.loadFromFile("arial.ttf"))
{
//handle error
}
menu[0].setFont(font);
menu[0].setColor(sf::Color::Red);
menu[0].setString("Press 'A' key to return to menu" );
menu[0].setPosition(sf::Vector2f(0, 500));
menu[0].setCharacterSize(40);
selectedItemIndex = 0;
}
void rules::draw(sf::RenderWindow &window)
{
for (int i = 0; i < MAX_NUMBER_OF_ITEMS; i++)
{
window.draw(menu[i]);
}
}
rules::~rules()
{
}
void rules::printRules()
{
sf::Font font;
if (!font.loadFromFile("arial.ttf"))
{
std::cout << " i cannot find." << std::endl;
}
else
{
std::cout << "it works" << std::endl;
}
sf::Text text;
sf::Text row1;
// TITLE
text.setFont(font);
text.setString("Rules to Farm Wars");
text.setCharacterSize(50);
text.setColor(sf::Color::Red);
text.setStyle(sf::Text::Bold | sf::Text::Underlined);
text.setPosition(75, 0);
//TITLE
//ROW1
row1.setFont(font);
row1.setString("1.Controls are W-A-S-D\n2.The highlighted blue boxes are where the units can go\nRed boxes are where the unit can attack\n4.Depending on the unit\nthe attack and potential distance is different\n5.Information relating to each unit will be shown on the top left screen\n6.The side that loses all units first loses");
row1.setCharacterSize(20);
row1.setColor(sf::Color::Red);
row1.setStyle(sf::Text::Bold);
row1.setPosition(0, 100);
//ROW1
sf::RenderWindow window(sf::VideoMode(600, 600), "Rules");
rules rules(window.getSize().x, window.getSize().y);
sf::Texture texture;
sf::Sprite background;
sf::Texture text1;
sf::Sprite rules2;
if (!texture.loadFromFile("background1.jpg"))
{
std::cout << " i cannot find. " << std::endl;
}
else
{
std::cout << "It works" << std::endl;
}
background.setTexture(texture);
background.setPosition(-300, 0);
if (!text1.loadFromFile("rules.png"))
{
std::cout << " i cannot find. " << std::endl;
}
else
{
std::cout << "It works" << std::endl;
}
rules2.setTexture(text1);
rules2.setPosition(60, 0);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::EventType::Closed)
{
window.close();
}
switch (event.type)
{
case sf::Event::KeyReleased:
switch (event.key.code)
{
case sf::Keyboard::Return:
switch (rules.GetPressedItem())
{
case 0:
std::cout << "Press the 'A' key to return to main menu" << std::endl;
break;
case sf::Event::TextEntered:
if (event.text.unicode < 128)
{
//why the fuck does 'A'||'a' key close the window
//i guess i will use this as an intended implementation
//std::cout << (char)event.text.unicode;
printf("%49[^\n]", event.text.unicode);
}
}
break;
case sf::Event::Closed:
window.close();
break;
}
}
window.clear();
window.draw(background);
//draw
//window.draw(text);
window.draw(row1);
//draw
//rules2.setcha
rules.draw(window);
window.draw(rules2);
window.display();
}
}
}
|
#include <iostream>
using namespace std;
int main()
{
long long a1, b1, a2, b2, t;
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> a1 >> b1 >> a2 >> b2;
if (a1 != b2)
cout << a1 << " " << b2 << endl;
else
cout << a1 << " " << b2 - 1 << endl;
}
}
|
#include <iostream>
#include <cstdio>
#include <memory.h>
#include <assert.h>
#include <algorithm>
#include <cmath>
#include <set>
#include <stack>
#include <cstdlib>
#include <vector>
using namespace std;
struct Tp {
int x, y;
} man[2222];
int n, m, k, s;
int b[22][22];
struct Te {
int x, y, f, c;
} e[222222];
int en = 0;
vector<int> g[22222];
int D[22222], st[22222], P[22222];
int best[22222], was[22222];
void add(int x, int y, int f, int c) {
//cerr << x << " " << y << " " << f << " " << c << endl;
e[en].x = x;
e[en].y = y;
e[en].f = f;
e[en].c = c;
g[x].push_back(en);
++en;
e[en].x = y;
e[en].y = x;
e[en].f = 0;
e[en].c = -c;
g[y].push_back(en);
++en;
}
vector<int> out;
int wasit[22222], IT = 0;
bool dfs(int mani) {
if (was[mani]) return true;
if (wasit[mani] == IT) return true;
wasit[mani] = IT;
pair<int, pair<int, int> > bestp = make_pair(2e9, make_pair(-1, -1));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) if (!b[i][j]) {
pair<int, pair<int, int> > p = make_pair( abs(i - man[mani].x) + abs(j - man[mani].y), make_pair(i, j) );
if (p < bestp) {
bestp = p;
}
}
}
int fid = (bestp.second.first - 1) * m + bestp.second.second;
if (best[fid] == 0 || dfs(best[fid])) {
if (!b[bestp.second.first][bestp.second.second]) {
b[bestp.second.first][bestp.second.second] = 1;
was[mani] = 1;
out.push_back(mani);
return true;
}
}
return false;
}
int main() {
freopen("agrarian.in", "r", stdin);
freopen("agrarian.out", "w", stdout);
scanf("%d%d%d%d", &n, &m, &k, &s);
for (int i = 1; i <= k; ++i) {
scanf("%d%d", &man[i].x, &man[i].y);
b[man[i].x][man[i].y] = 1;
}
for (int i = 0; i < s; ++i) {
int x, y;
scanf("%d%d", &x, &y);
b[x][y] = 1;
}
int S = 0;
int F = k + n * m + 1;
for (int i = 1; i <= k; ++i) {
add(0, i, 1, 0);
for (int j = 1; j <= n; ++j)
for (int jj = 1; jj <= m; ++jj)
if (!b[j][jj]) {
add(i, (j - 1) * m + jj + k, 1, abs(man[i].x - j) + abs(man[i].y - jj));
}
}
for (int j = 1; j <= n; ++j)
for (int jj = 1; jj <= m; ++jj)
if (!b[j][jj]) {
add((j - 1) * m + jj + k, F, 1, 0);
}
while (true) {
deque<int> q;
for (int i = S; i <= F; ++i) {
D[i] = 1e9;
st[i] = 0;
}
q.push_back(S);
D[S] = 0;
st[S] = 1;
while (!q.empty()) {
int x = q.front(); q.pop_front();
st[x] = 2;
for (int i = 0; i < (int)g[x].size(); ++i) {
const Te& E = e[g[x][i]];
if (E.f > 0 && D[E.y] > D[x] + E.c) {
D[E.y] = D[x] + E.c;
P[E.y] = g[x][i];
if (st[E.y] == 0) {
q.push_back(E.y);
} else
if (st[E.y] == 2) {
q.push_front(E.y);
}
st[E.y] = 1;
}
}
}
if (D[F] >= 1e9) break;
int x = F;
while (x != S) {
--e[P[x]].f;
++e[P[x] ^ 1].f;
x = e[P[x]].x;
}
}
for (int i = 1; i <= k; ++i) {
for (int j = 0; j < (int)g[i].size(); ++j) {
if (e[g[i][j]].f == 0) {
best[ e[g[i][j]].y - k ] = i;
break;
}
}
}
while (out.size() < k) {
for (int i = 1; i <= k; ++i) if (!was[i]) {
++IT;
dfs(i);
}
}
for (int i = 0; i < out.size(); ++i)
cout << out[i] << " ";
cout << endl;
sort(out.begin(), out.end());
assert(out.size() == k);
for (int i = 0; i < out.size(); ++i)
assert(out[i] == i + 1);
return 0;
}
|
#include "settings.h"
#include "ui_settings.h"
bool bold = false;
bool italic = false;
bool underline = false;
QColor color;
Settings::Settings(QWidget *parent) :
QDialog(parent),
ui(new Ui::Settings)
{
ui->setupUi(this);
}
Settings::~Settings()
{
delete ui;
}
void Settings::on_fontName_currentIndexChanged(const QString &arg1)
{
emit fontChanged(arg1);
}
void Settings::on_fontSize_valueChanged(int arg1)
{
// można dobrać się do tej wartości w ten sposób
emit fontSizeChanged(ui->fontSize->value());
}
void Settings::on_fontBold_clicked()
{
bold = !bold;
emit fontBoldSet(bold);
}
void Settings::on_fontItalic_clicked()
{
italic = !italic;
emit fontItalicSet(italic);
}
void Settings::on_fontUnderline_clicked()
{
underline = !underline;
emit fontUnderlineSet(underline);
}
void Settings::on_fontColorR_valueChanged(int arg1)
{
color.setRed(arg1);
emit fontColorChanged(color.red(),color.green(),color.blue());
}
void Settings::on_fontColorG_valueChanged(int arg1)
{
color.setGreen(arg1);
emit fontColorChanged(color.red(),color.green(),color.blue());
}
void Settings::on_fontColorB_valueChanged(int arg1)
{
color.setBlue(arg1);
emit fontColorChanged(color.red(),color.green(),color.blue());
}
void Settings::setBasicSettins(QTextEdit *edit)
{
ui->fontName->setFont(edit->currentFont());
ui->fontSize->setValue((int)edit->font().pointSize());
// pomijamy sprawdzenie czy jest bold, italic i underline bo nie jest
ui->fontColorR->setValue(edit->textColor().red());
ui->fontColorG->setValue(edit->textColor().green());
ui->fontColorB->setValue(edit->textColor().blue());
}
|
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
#ifdef USE_CUBLAS
#include <cuda_runtime.h>
#include "cublas_v2.h"
#include "cusparse.h"
#endif
#define DGEMM_RESTRICT __restrict__
#if defined(USE_MKL)
#include <mkl.h>
#endif
#if defined(USE_LAPACK)
#include <lapacke.h>
#include <cblas.h>
#endif
#include <omp.h>
#include "lib_csr.h"
int main(int argc, char *argv[])
{
int M, N, index = 0, blocksize;
int block_width;
double *A, *blockVectorX;
double *at, *bt;
double residualTolerance = 0.0001;
long maxIterations = 10;
int constraintStyle = 0; //operatorB not used
long iterationNumber;
int info;
//cout settings
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
stringstream s(argv[1]);
s >> blocksize;
// stringstream s1(argv[2]);
// s1 >> block_width;
cout << "# of RHS Vectors: " << blocksize << endl; //" Block Width: " << block_width << endl;
int currentBlockSize = blocksize, prevCurrentBlockSize = blocksize;
//----- lib spmm params
char matdescra[6];
char transA = 'n';
matdescra[0] = 'g';
matdescra[1] = 'l';
matdescra[2] = 'u';
matdescra[3] = 'c';
double alpha = 1.0, beta = 0.0;
//---- dportf_ & dsygv_ params
const char jobvl = 'N';
const char jobvr = 'V';
const char jobz = 'V';
const char uplo = 'U';
const char uplo_dlacpy = ' ';
const int itype = 1;
double work_query;
int lwork;
double *work;
int i,j,k;
double *xrem;
double *acsr;
block<double> *matrixBlock;
char *filename = argv[2] ;
wblk = block_width;
// read_custom(filename,xrem);
//read_custom_csr(filename, acsr);
// printf("Finish Reading CUS file\n");
// *--------- Reading CSR from binary file ---------* //
ifstream file(filename, ios::in|ios::binary);
if (file.is_open())
{
file.read ((char*)&numrows,sizeof(numrows));
cout << "row: "<<numrows<<endl;
file.read(reinterpret_cast<char*>(&numcols), sizeof(numcols));
cout << "colum: " << numcols << endl;
file.read(reinterpret_cast<char*>(&nnonzero), sizeof(nnonzero));
cout << "non zero: " << nnonzero << endl;
ia = (int *) malloc((numrows + 1) * sizeof(int)); //colsptr
ja = (int *) malloc(nnonzero * sizeof(int)); //irem
acsr = (double *) malloc(nnonzero * sizeof(double)); //xrem
// file.read(reinterpret_cast<char*>(ia), (numrows + 1) * sizeof(int));
// cout << "finished reading ia"<<endl;
// file.read(reinterpret_cast<char*>(ja), nnonzero * sizeof(int));
// cout << "finished reading ja"<<endl;
// file.read(reinterpret_cast<char*>(acsr), nnonzero * sizeof(double));
// cout << "finished reading acsr"<<endl;
i = 0;
while(!file.eof() && i <= numrows)
{
file.read(reinterpret_cast<char*>(&j), sizeof(j)); //irem(j)
ia[i++] = j;
}
cout << "finished reading ia"<<endl;
i = 0;
while(!file.eof() && i < nnonzero)
{
file.read(reinterpret_cast<char*>(&j), sizeof(j)); //irem(j)
ja[i++] = j;
}
cout << "finished reading ja"<<endl;
i = 0;
double d;
while(!file.eof() && i < nnonzero)
{
file.read(reinterpret_cast<char*>(&d), sizeof(d)); //irem(j)
acsr[i++] = d;
}
cout << "finished reading acsr"<<endl;
}
file.close();
cout << "ia[0]: " << ia[0] << " ia[last]: " << ia[numrows] << endl;
cout << "ja[0]: " << ja[0] << " ja[last]: " << ja[nnonzero-1] << endl;
cout << "acsr[0]: " << acsr[0] << " acsr[last]: " << acsr[nnonzero-1] << endl;
printf("numrows: %d numcols: %d nnonzero: %d\n", numrows, numcols, nnonzero);
#pragma omp parallel
#pragma omp master
{
nthrds = omp_get_num_threads();
}
//-- deleting CSC storage memory ------
//delete []colptrs;
//delete []irem;
//delete []xrem;
M = numrows;
N = numcols;
//timing variables
int numTasks = 18;
vector<string> function_name{"LOOPS", "X*Y", "Xt*Y", "ADD", "SUB", "MULT", "SPMM", "GET", "UPDATE", "dsygv", "DLACPY", "INVERSE", "TRANSPOSE", "mat_copy", "dpotrf", "memset", "SUMSQRT", "diag"};
double **taskTiming = (double **) malloc(sizeof(double *) * maxIterations);
for(i = 0 ; i < maxIterations ; i++)
taskTiming[i] = (double *) malloc(sizeof(double) * numTasks);
#pragma omp parallel for default(shared) private(j)
for(i = 0 ; i < maxIterations ; i++)
{
for(j = 0 ; j < numTasks ; j++)
{
taskTiming[i][j] = 0.0;
}
}
double tstart, tend, temp1Time;
double loop_start_time = 0, loop_finish_time = 0;
double iteraton_time = 0, iteraton_start_time = 0;
blockVectorX = (double *) malloc(M * blocksize * sizeof(double));
int job_dcsrcsc[] = {1, 0, 0, 0, 0, 1};
int dcsrcsc_info = -1;
// acsr = (double *) malloc(nnonzero * sizeof(double)); //new double[nnonzero](); //xrem
// ja = (int *) malloc(nnonzero * sizeof(int)); //new int[nnonzero](); //irem
// ia = (int *) malloc((numrows + 1) * sizeof(int)); //new int[numrows + 1](); //colsptr
tstart = omp_get_wtime();
// mkl_dcsrcsc(job_dcsrcsc, &numrows, acsr, ja, ia, xrem, irem, colptrs, &dcsrcsc_info);
//printf("mkl_dcsrcsc: %lf sec.\n", omp_get_wtime() - tstart);
//-- deleting CSC storage memory ------
// delete []colptrs;
// delete []irem;
// delete []xrem;
//std::fstream blockVectorXfile("MatX100.txt", std::ios_base::in);
srand(0);
//#pragma omp parallel for private(j) default(shared)
for(i = 0 ; i < M ; i++)
{
for(j = 0 ; j < blocksize ; j++)
{
//blockVectorXfile>>blockVectorX[i*blocksize+j];
blockVectorX[i * blocksize + j] = (double)rand()/(double)RAND_MAX;
//blockVectorX[i*blocksize+j]= -1.00 + rand() % 2 ;
}
}
//cout<<"finished reading X"<<endl;
//******** memory allocation for matrices ********
double *blockVectorAX = (double *) malloc(M * blocksize * sizeof(double));
double *blockVectorR = (double *) malloc(M * blocksize * sizeof(double));
double *blockVectorAR = (double *) malloc(M * blocksize * sizeof(double));
double *blockVectorP = (double *) malloc(M * blocksize * sizeof(double));
double *blockVectorAP = (double *) malloc(M * blocksize * sizeof(double));
double *activeBlockVectorR = (double *) malloc(M * currentBlockSize * sizeof(double));
double *activeBlockVectorAR = (double *) malloc(M * currentBlockSize * sizeof(double));
double *activeBlockVectorP = (double *) malloc(M * currentBlockSize * sizeof(double));
double *activeBlockVectorAP = (double *) malloc(M * currentBlockSize * sizeof(double));
double *temp3 = (double *) malloc(M * currentBlockSize * sizeof(double));
double *newX = (double *) malloc(M * blocksize * sizeof(double));
int gramASize = blocksize + currentBlockSize + currentBlockSize;
double *gramA = (double *) malloc(gramASize * gramASize * sizeof(double));
double *gramB = (double *) malloc(gramASize * gramASize * sizeof(double));
double *eigen_value;
//--- modified new
//double *newAX = new double[M*blocksize]();
//double *temp1 = new double[M*blocksize]();
//double *newActP = new double[M*currentBlockSize]();
//double *tempMultResult=new double[M*currentBlockSize]();
double *residualNorms = (double *) malloc(blocksize * sizeof(double));
double *gramPBP = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *trans_gramPBP = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *temp2 = (double *) malloc(currentBlockSize * blocksize * sizeof(double));
double *gramRBR = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *trans_gramRBR = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *gramXAR = (double *) malloc(currentBlockSize * blocksize * sizeof(double));
double *transGramXAR = (double *) malloc(currentBlockSize * blocksize * sizeof(double));
double *gramRAR = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *transGramRAR = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *gramXAP = (double *) malloc(currentBlockSize * blocksize * sizeof(double));
double *transGramXAP = (double *) malloc(currentBlockSize * blocksize * sizeof(double));
double *transGramRAP= (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *gramRAP = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *gramPAP= (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *identity_PAP = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *gramXBP = (double *) malloc(currentBlockSize * blocksize * sizeof(double));
double *transGramXBP = (double *) malloc(currentBlockSize * blocksize * sizeof(double));
double *transGramRBP = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *identity_BB = (double *) malloc(blocksize * blocksize * sizeof(double));
double *gramRBP = (double *) malloc(currentBlockSize * currentBlockSize * sizeof(double));
double *zeros_B_CB = (double *) malloc(currentBlockSize * blocksize * sizeof(double));
double *zeros_CB_B = (double *) malloc(currentBlockSize * blocksize * sizeof(double));
std::memset(zeros_B_CB, 0.0, blocksize * currentBlockSize * sizeof(double));
std::memset(zeros_CB_B, 0.0, blocksize * currentBlockSize * sizeof(double));
// saveLamda[blocksize * maxIterations]
double **saveLamda = (double **) malloc(blocksize * maxIterations * sizeof(double *));
for(i = 0 ; i < blocksize ; i++)
saveLamda[i] = (double *) malloc(maxIterations * sizeof(double));
for(i = 0 ; i < blocksize ; i++)
for(j = 0 ; j < maxIterations ; j++)
saveLamda[i][j] = 0.0;
double *loopTime = (double *) malloc(maxIterations * sizeof(double));
for(i = 0 ; i < maxIterations ; i++)
loopTime[i] = 0;
//cout<<"Allocation 8"<<endl;
//cout<<"Total allocation time: "<<omp_get_wtime()-allocation_time<<" sec."<<endl;
//---- if 9 ----
//gramXBX=blockVectorX'*blockVectorX;
//[gramXBX,cholFlag]=chol(gramXBX);
//blockVectorX = blockVectorX/gramXBX;
double *gramXBX = new double[blocksize * blocksize]();
cblas_dgemm(CblasRowMajor,CblasTrans,CblasNoTrans,blocksize,blocksize,M,1.0,blockVectorX,blocksize,blockVectorX,blocksize,0.0,gramXBX,blocksize);
//_XTY(blockVectorX, blockVectorX, gramXBX, M, blocksize, blocksize, block_width);
int cholFlag;
//making the lower part of gramXBX zero
//-- changing LAPACKE_dpotrf to dpotrf_
// double *trans_gramXBX = new double[blocksize * blocksize]();
// transpose(gramXBX, trans_gramXBX, blocksize, blocksize);
// dpotrf_( &uplo, &blocksize, trans_gramXBX, &blocksize, &info );
// if(info != 0 )
// {
// cout<<"dpotrf: chol error!"<<endl;
// //exit(1);
// }
// transpose(trans_gramXBX, gramXBX, blocksize, blocksize);
// delete []trans_gramXBX;
info = LAPACKE_dpotrf(LAPACK_ROW_MAJOR , 'U' , blocksize , gramXBX , blocksize);
if(info != 0)
cout << "dpotrf: chol error!" << endl;
#pragma omp parallel for private(j) default(shared)
for(i = 0 ; i < blocksize ; i++)
{
for(j = 0 ; j < i ; j++)
{
gramXBX[i * blocksize + j] = 0.0;
}
}
double *tempGramXBX = new double[blocksize * blocksize]();
//int copyGramXBX = LAPACKE_dlacpy(LAPACK_ROW_MAJOR,' ',blocksize,blocksize,gramXBX,blocksize,tempGramXBX,blocksize);
custom_dlacpy(gramXBX, tempGramXBX, blocksize, blocksize);
inverse(tempGramXBX, blocksize, blocksize);
cblas_dgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans, M, blocksize, blocksize,1.0,blockVectorX, blocksize,tempGramXBX,blocksize,0.0, newX,blocksize);
//copyResult=LAPACKE_dlacpy(LAPACK_ROW_MAJOR,' ',M,blocksize,tempResult,blocksize,blockVectorX,blocksize);
custom_dlacpy(newX, blockVectorX, M, blocksize);
delete []tempGramXBX;
// if 17
// blockVectorAX = operatorA*blockVectorX;
//std::memset(blockVectorAX, 0.0, sizeof(blockVectorAX));
//tstart = omp_get_wtime();
#pragma omp parallel for private(j) default(shared)
for(i = 0; i < M ; i++)
{
for(j = 0 ; j < blocksize ; j++)
{
blockVectorAX[i * blocksize + j] = 0.0;
}
}
//taskTiming[0] += (omp_get_wtime() - tstart); //SETZERO : 0
//mkl_dcscmm(&transA, &M, &blocksize, &N, &alpha, matdescra, xrem, irem, colptrs, colptrs+1, blockVectorX, &blocksize, &beta, blockVectorAX, &blocksize);
//mkl_dcsrmm(&transA, &M, &blocksize, &N, &alpha, matdescra, acsr, ja, ia, ia+1, blockVectorX, &blocksize, &beta, blockVectorAX, &blocksize);
//spmm_blkcoord(numrows, numcols, blocksize, nthrds, blockVectorX, blockVectorAX, matrixBlock);
spmm_csr(numrows, numcols, blocksize, ia, ja, acsr, blockVectorX, blockVectorAX);
//gramXAX = full(blockVectorX'*blockVectorAX);
double *gramXAX=new double[blocksize*blocksize]();
cblas_dgemm(CblasRowMajor,CblasTrans,CblasNoTrans,blocksize,blocksize,M,1.0,blockVectorX,blocksize,blockVectorAX,blocksize,0.0,gramXAX,blocksize);
//_XTY(blockVectorX, blockVectorAX, gramXAX, M, blocksize, blocksize, block_width);
//gramXAX = (gramXAX + gramXAX')*0.5;
double *transGramXAX=new double[blocksize*blocksize]();
transpose(gramXAX,transGramXAX, blocksize, blocksize);
make_identity_mat(identity_BB,blocksize, blocksize);
make_identity_mat(identity_PAP, currentBlockSize, currentBlockSize); //--> used in loop
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, blocksize, blocksize, blocksize, 0.5, transGramXAX, blocksize, identity_BB, blocksize, 0.5, gramXAX, blocksize);
free(transGramXAX);
// double *temp_GramXAX = new double[blocksize*blocksize]();
// transpose(gramXAX, temp_GramXAX, blocksize, blocksize);
// //dummy call: work size query
// lwork = -1;
// double *tempLambda = new double[blocksize]();
// dsygv_(&itype, &jobz, &uplo, &blocksize, temp_GramXAX, &blocksize, identity_BB, &blocksize, tempLambda, &work_query, &lwork, &info);
// if(info != 0)
// {
// cout<<"Error in dummy call"<<endl;
// //exit(1);
// }
// lwork = (int) work_query;
// work = new double[lwork]();
// dsygv_(&itype, &jobz, &uplo, &blocksize, temp_GramXAX, &blocksize, identity_BB, &blocksize, tempLambda, work, &lwork, &info);
// if(info != 0)
// {
// printf( "The algorithm failed to compute eigenvalues.\n" );
// }
// transpose(temp_GramXAX, gramXAX, blocksize, blocksize);
// free(temp_GramXAX);
// free(work);
//[coordX,gramXAX]=eig(gramXAX,eye(blockSize));
//lambda=diag(gramXAX);
double *tempLambda = new double[blocksize]();
info = LAPACKE_dsygv(LAPACK_ROW_MAJOR, itype, jobz, uplo, blocksize, gramXAX, blocksize, identity_BB, blocksize, tempLambda);
if(info != 0)
cout << "Error in dummy call" << endl;
double *lambda = (double *) malloc(blocksize * blocksize * sizeof(double));
diag(tempLambda, lambda, blocksize);
free(tempLambda);
//note: after applying dsyevd_ function gramXAX will be coordX
//blockVectorX = blockVectorX*coordX; //after this, dimension of blockVectorX will be M*blocksize
//blockVectorAX = blockVectorAX*coordX; //blockVectorAX will remain M*blocksize
//double *newBlockVectorX=new double[M*blocksize]();
double *coordX;
cblas_dgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,M,blocksize,blocksize,1.0,blockVectorX,blocksize,gramXAX,blocksize,0.0,newX,blocksize);
//copyResult=LAPACKE_dlacpy(LAPACK_ROW_MAJOR,' ',M,blocksize,newBlockVectorX,blocksize,blockVectorX,blocksize); //blockVectorX=newBlockVectorX
custom_dlacpy(newX, blockVectorX, M, blocksize);
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, blocksize, blocksize, 1.00, blockVectorAX, blocksize, gramXAX, blocksize, 0.00, newX, blocksize);
custom_dlacpy(newX, blockVectorAX, M, blocksize);
free(gramXAX);
int *activeMask = (int *) malloc(blocksize * sizeof(int));
#pragma omp parallel for
for(i = 0 ; i < blocksize ; i++)
activeMask[i] = 1;
iteraton_start_time = omp_get_wtime();
int activeRSize = 0, activePSize = 0, explicitGramFlag = 0, restart = 0;
//======== creadting device pointers for GPU start ==========//
#if defined( USE_CUBLAS )
int h = omp_get_initial_device();
int t = omp_get_default_device();
int status;
double *d_blockVectorP, *d_blockVectorR, *d_blockVectorX, *d_blockVectorAX;
double *d_blockVectorAP, *d_lambda;
double *d_activeBlockVectorR, *d_activeBlockVectorAR, *d_temp2, *d_temp3;
double *d_activeBlockVectorP, *d_activeBlockVectorAP;
double *d_gramRBR, *d_gramPBP, *d_gramXAR, *d_gramRAR;
double *d_identity_PAP, *d_transGramRAR, *d_gramXAP;
double *d_gramPAP, *d_gramRAP, *d_gramXBP, *d_gramRBP;
double *d_coordX, *d_newX;
double *d_xrem, *d_residualNorms;
int *d_irem, *d_colptrs, *d_activeMask;
double *d_gramA, *d_gramB, *d_transGramXAR, *d_transGramXAP, *d_transGramRAP;
double *d_identity_BB, *d_zeros_B_CB, *d_transGramXBP, *d_transGramRBP;
const double cudaAlpha = 1.0;
const double cudaBeta = 0.0;
const double cudaBetaOne = 1.0;
cublasStatus_t cubstat;
cusparseStatus_t status1;
cublasHandle_t handle;
cudaError_t cuberror;
cusparseMatDescr_t descr = 0;
cusparseHandle_t cusparseHandle = 0;
d_blockVectorX = (double *) omp_target_alloc(M * blocksize * sizeof(double), t);
if(d_blockVectorX == NULL){ printf("omp_target_alloc Filed d_blockVectorX\n"); return 0; }
d_blockVectorAX = (double *) omp_target_alloc(M * blocksize * sizeof(double), t);
if(d_blockVectorAX == NULL){ printf("omp_target_alloc Filed d_blockVectorAX\n"); return 0; }
d_blockVectorR = (double *) omp_target_alloc (M * blocksize * sizeof(double), t);
if(d_blockVectorR == NULL){ printf("omp_target_alloc Filed d_blockVectorR\n"); return 0; }
d_blockVectorP = (double *) omp_target_alloc (M * blocksize * sizeof(double), t);
if(d_blockVectorP == NULL){ printf("omp_target_alloc Filed d_blockVectorP\n"); return 0; }
d_blockVectorAP = (double *) omp_target_alloc (M * blocksize * sizeof(double), t);
if(d_blockVectorAP == NULL){ printf("omp_target_alloc Filed d_blockVectorAP\n"); return 0; }
d_newX = (double *) omp_target_alloc(M * blocksize * sizeof(double), t);
if(d_newX == NULL){ printf("omp_target_alloc Filed d_newX\n"); return 0; }
d_activeBlockVectorR = (double *) omp_target_alloc(M * currentBlockSize * sizeof(double), t);
if(d_activeBlockVectorR == NULL){ printf("omp_target_alloc Filed d_activeBlockVectorR\n"); return 0; }
d_activeBlockVectorAR = (double *) omp_target_alloc(M * currentBlockSize * sizeof(double), t);
if(d_activeBlockVectorAR == NULL){ printf("omp_target_alloc Filed d_activeBlockVectorAR\n"); return 0; }
d_activeBlockVectorP = (double *) omp_target_alloc (M * currentBlockSize * sizeof(double), t);
if(d_activeBlockVectorP == NULL){ printf("omp_target_alloc Filed d_activeBlockVectorP\n"); return 0; }
d_activeBlockVectorAP = (double *) omp_target_alloc(M * currentBlockSize * sizeof(double), t);
if(d_activeBlockVectorAP == NULL){ printf("omp_target_alloc Filed d_activeBlockVectorAP\n"); return 0; }
d_temp3 = (double *) omp_target_alloc(M * currentBlockSize * sizeof(double), t);
if(d_temp3 == NULL){ printf("omp_target_alloc Filed d_temp3\n"); return 0; }
d_temp2 = (double *) omp_target_alloc(blocksize * currentBlockSize * sizeof(double), t);
if(d_temp2 == NULL){ printf("omp_target_alloc Filed d_temp2\n"); return 0; }
d_lambda = (double *) omp_target_alloc(blocksize * blocksize * sizeof(double), t);
if(d_lambda == NULL){ printf("omp_target_alloc Filed d_lambda\n"); return 0; }
d_gramRBR = (double *) omp_target_alloc (currentBlockSize * currentBlockSize * sizeof(double), t);
if(d_gramRBR == NULL ){ printf("omp_target_alloc Filed d_gramRBR\n"); return 0; }
d_gramPBP = (double *) omp_target_alloc (currentBlockSize * currentBlockSize * sizeof(double), t);
if(d_gramPBP == NULL){ printf("omp_target_alloc Filed d_gramPBP\n"); return 0; }
d_gramXAR = (double *) omp_target_alloc (blocksize * currentBlockSize * sizeof(double), t);
if(d_gramXAR == NULL){ printf("omp_target_alloc Filed d_gramXAR\n"); return 0; }
d_gramRAR = (double *) omp_target_alloc (currentBlockSize * currentBlockSize * sizeof(double), t);
if(d_gramRAR == NULL){ printf("omp_target_alloc Filed d_gramRAR\n"); return 0; }
d_transGramRAR = (double *) omp_target_alloc (currentBlockSize * currentBlockSize * sizeof(double), t);
if(d_transGramRAR == NULL){ printf("omp_target_alloc Filed d_transGramRAR\n"); return 0; }
d_identity_PAP = (double *) omp_target_alloc (currentBlockSize * currentBlockSize * sizeof(double), t);
if(d_identity_PAP == NULL){ printf("omp_target_alloc Filed d_identity_PAP\n"); return 0; }
d_identity_BB = (double *) omp_target_alloc(blocksize * blocksize * sizeof(double), t);
if(d_identity_BB == NULL){ printf("omp_target_alloc Filed d_identity_BB\n"); return 0; }
d_zeros_B_CB = (double *) omp_target_alloc (blocksize * currentBlockSize * sizeof(double), t);
if(d_zeros_B_CB == NULL){ printf("omp_target_alloc Filed d_zeros_B_CB\n"); return 0; }
d_gramXAP = (double *) omp_target_alloc(blocksize * currentBlockSize * sizeof(double), t);
if(d_gramXAP == NULL){ printf("omp_target_alloc Filed d_gramXAP\n"); return 0; }
d_gramPAP = (double *) omp_target_alloc(currentBlockSize * currentBlockSize * sizeof(double), t);
if(d_gramPAP == NULL){ printf("omp_target_alloc Filed d_gramPAP\n"); return 0; }
d_gramRAP = (double *) omp_target_alloc (currentBlockSize * currentBlockSize * sizeof(double), t);
if(d_gramRAP == NULL){ printf("omp_target_alloc Filed d_gramRAP\n"); return 0; }
d_gramXBP = (double *) omp_target_alloc (blocksize * currentBlockSize * sizeof(double), t);
if(d_gramXBP == NULL){ printf("omp_target_alloc Filed d_gramXBP\n"); return 0; }
d_gramRBP = (double *) omp_target_alloc(currentBlockSize * currentBlockSize * sizeof(double), t);
if( d_gramRBP == NULL ){ printf("omp_target_alloc Filed d_gramRBP\n"); return 0; }
d_xrem = (double *) omp_target_alloc(nnonzero * sizeof(double), t);
if(d_xrem == NULL){ printf("omp_target_alloc Filed d_xrem\n"); return 0; }
d_irem = (int *) omp_target_alloc(nnonzero * sizeof(int), t);
if(d_irem == NULL){ printf("omp_target_alloc Filed d_irem\n"); return 0; }
d_colptrs = (int *) omp_target_alloc ((numrows+1) * sizeof(int), t);
if(d_colptrs == NULL){ printf("omp_target_alloc Filed d_colptrs\n"); return 0; }
d_activeMask = (int *) omp_target_alloc(blocksize * sizeof(int), t);
if(d_activeMask == NULL){ printf("omp_target_alloc Filed d_activeMask\n"); return 0; }
d_residualNorms = (double *) omp_target_alloc(blocksize * sizeof(double), t);
if(d_residualNorms == NULL){ printf("omp_target_alloc Filed d_residualNorms\n"); return 0; }
d_gramA = (double *) omp_target_alloc(gramASize * gramASize * sizeof(double), t);
if(d_gramA == NULL){ printf("omp_target_alloc Filed d_gramA\n"); return 0; }
d_gramB = (double *) omp_target_alloc(gramASize * gramASize * sizeof(double), t);
if(d_gramB == NULL){ printf("omp_target_alloc Filed d_gramB\n"); return 0; }
d_transGramXAR = (double *) omp_target_alloc(currentBlockSize * blocksize * sizeof(double), t);
if(d_transGramXAR == NULL){ printf("omp_target_alloc Filed d_transGramXAR\n"); return 0; }
d_transGramXAP = (double *) omp_target_alloc(currentBlockSize * blocksize * sizeof(double), t);
if(d_transGramXAP == NULL){ printf("omp_target_alloc Filed d_transGramXAP\n"); return 0; }
d_transGramRAP = (double *) omp_target_alloc(currentBlockSize * currentBlockSize * sizeof(double), t);
if(d_transGramRAP == NULL){ printf("omp_target_alloc Filed d_transGramRAP\n"); return 0; }
d_transGramXBP = (double *) omp_target_alloc (currentBlockSize * blocksize * sizeof(double), t);
if(d_transGramXBP == NULL){ printf("omp_target_alloc Filed d_transGramXBP\n"); return 0; }
d_transGramRBP = (double *) omp_target_alloc(currentBlockSize * currentBlockSize * sizeof(double), t);
if(d_transGramRBP == NULL){ printf("omp_target_alloc Filed d_transGramRBP\n"); return 0; }
status = omp_target_memcpy(d_xrem, acsr, nnonzero * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed xrem ==> %d\n", cuberror); return 0; }
status = omp_target_memcpy(d_irem, ja, nnonzero * sizeof(int), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed irem ==> %d\n", cuberror); return 0; }
status = omp_target_memcpy(d_colptrs, ia, (numrows + 1) * sizeof(int), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed d_colptrs ==> %d\n", cuberror); return 0; }
/* initialize cusparse library */
status1 = cusparseCreate(&cusparseHandle);
if (status1 != CUSPARSE_STATUS_SUCCESS)
{
printf("CUSPARSE Library initialization failed");
return 1;
}
/* create and setup matrix descriptor */
status1 = cusparseCreateMatDescr(&descr);
if (status1 != CUSPARSE_STATUS_SUCCESS)
{
printf("Matrix descriptor initialization failed");
return 1;
}
cusparseSetMatType(descr, CUSPARSE_MATRIX_TYPE_GENERAL);
cusparseSetMatIndexBase(descr, CUSPARSE_INDEX_BASE_ZERO);
cubstat = cublasCreate(&handle);
if( cubstat != CUBLAS_STATUS_SUCCESS ){ printf("HandleCreationFailure\n"); return 0; }
#endif
// cout << "Here " << endl;
//======== creadting device pointers for GPU end ==========//
#if defined(USE_CUBLAS)
status = omp_target_memcpy(d_identity_PAP, identity_PAP, currentBlockSize * currentBlockSize * sizeof(double), 0, 0 , t, h);
if( status != 0 ){ printf("cudaMemcpy failed identity_PAP ==> %d\n", cuberror); return 0; }
status = omp_target_memcpy(d_identity_BB, identity_BB, blocksize * blocksize * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed identity_BB ==> %d\n", cuberror); return 0; }
status = omp_target_memcpy(d_zeros_B_CB, zeros_B_CB, blocksize * currentBlockSize * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed d_zeros_B_CB ==> %d\n", cuberror); return 0; }
status = omp_target_memcpy(d_blockVectorX, blockVectorX, M * blocksize * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed blockVectorX ==> %d\n", cuberror); return 0; }
status = omp_target_memcpy(d_blockVectorAX, blockVectorAX, M * blocksize * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed blockVectorAX ==> %d\n", cuberror); return 0; }
status = omp_target_memcpy(d_blockVectorP, blockVectorP, M * blocksize * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed d_blockVectorP ==> %d\n", cuberror); return 0; }
status = omp_target_memcpy(d_blockVectorAP, blockVectorAP, M * blocksize * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed d_blockVectorAP ==> %d\n", cuberror); return 0; }
cudaDeviceSynchronize();
#endif
// cout << "Here 2" << endl;
//loop starts here
for(iterationNumber = 1 ; iterationNumber <= maxIterations ; iterationNumber++)
{
printf("**---------------- iterationNumber : %ld ----------------**\n", iterationNumber);
// for(i = 0 ; i < numTaks ; i++)
// taskTiming[i] = 0;
// cout << "\niterationNumber: " << iterationNumber << endl;
loop_start_time = omp_get_wtime();
//if 12 nested if
//blockVectorR = blockVectorAX - blockVectorX*spdiags(lambda,0,blockSize,blockSize);
#if defined(USE_CPU)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, blocksize, blocksize, 1.0, blockVectorX, blocksize, lambda,blocksize, 0.0, blockVectorR, blocksize); //XY code 1
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
// cuberror = cudaMemcpy(d_blockVectorX, blockVectorX, M * blocksize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed blockVectorX ==> %d\n", cuberror); return 0; }
cubstat = cublasSetMatrix (blocksize, blocksize, sizeof(double), lambda, blocksize, d_lambda, blocksize); //copy_lambda
if( cubstat != CUBLAS_STATUS_SUCCESS ){ printf("SetMatrixFailure lambda\n"); return 0; }
cudaDeviceSynchronize();
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, blocksize, M, blocksize,
&cudaAlpha, d_lambda, blocksize, d_blockVectorX, blocksize, &cudaBeta, d_blockVectorR, blocksize); //xy_1
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-1: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
// printf("iterationNumber : %ld blockVectorR ==>\n", iterationNumber);
// print_mat(blockVectorR, 2, blocksize);
// printf("\n");
#if defined(USE_OPENACC)
// cuberror = cudaMemcpy(d_blockVectorAX, blockVectorAX, M * blocksize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed blockVectorAX ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
mat_sub_GPU_v2(d_blockVectorAX, d_blockVectorR, d_blockVectorR , M, blocksize); //sub_1
taskTiming[iterationNumber - 1][4] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
#pragma omp target is_device_ptr(d_residualNorms)
#pragma omp teams distribute parallel for //setzero(RN)
for(i = 0 ; i < blocksize ; i++)
d_residualNorms[i] = 0.0;
taskTiming[iterationNumber - 1][0] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
mat_mult_GPU_v2(d_blockVectorR, d_blockVectorR, d_newX, M, blocksize); //mult_1
taskTiming[iterationNumber - 1][5] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
sum_sqrt_GPU_v2(d_newX, d_residualNorms, M, blocksize); //norm
taskTiming[iterationNumber - 1][16] += (omp_get_wtime() - tstart);
// tstart = omp_get_wtime();
// update_activeMask_OpenACC(d_activeMask, d_residualNorms, residualTolerance, blocksize);
// taskTiming[iterationNumber - 1][8] += (omp_get_wtime() - tstart); //UPDATE : 8
// cuberror = cudaMemcpy(blockVectorR, d_blockVectorR, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed blockVectorR: %d\n", cuberror);}
cuberror = cudaMemcpy(residualNorms, d_residualNorms, blocksize * sizeof(double), cudaMemcpyDeviceToHost);
if( cuberror != 0 ){ printf("cudaMemcpy failed activeMask: %d\n", cuberror);}
cudaDeviceSynchronize();
#endif
#if defined(USE_CPU)
tstart = omp_get_wtime();
mat_sub(blockVectorAX, d_blockVectorR, d_blockVectorR , M, blocksize); //SUB : 4
taskTiming[iterationNumber - 1][4] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
#pragma omp parallel for default(shared)
for(i = 0 ; i < blocksize ; i++)
residualNorms[i] = 0.0;
taskTiming[iterationNumber - 1][0] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
mat_mult(blockVectorR, blockVectorR, newX, M, blocksize); //MULT : 5
taskTiming[iterationNumber - 1][5] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
sum_sqrt(newX, residualNorms, M, blocksize);
taskTiming[iterationNumber - 1][16] += (omp_get_wtime() - tstart);
#endif
//residualNorms=full(sqrt(sum(conj(blockVectorR).*blockVectorR)'));
//residualNormsHistory(1:blockSize,iterationNumber)=residualNorms;
//activeMask = full(residualNorms > residualTolerance) & activeMask;
tstart = omp_get_wtime();
update_activeMask(activeMask, residualNorms, residualTolerance, blocksize);
taskTiming[iterationNumber - 1][8] += (omp_get_wtime() - tstart); //UPDATE : 8
//currentBlockSize = sum(activeMask);
currentBlockSize = 0;
tstart = omp_get_wtime();
for(i = 0 ; i < blocksize ; i++)
currentBlockSize += activeMask[i];
taskTiming[iterationNumber - 1][0] += (omp_get_wtime() - tstart);
if(currentBlockSize == 0)
{
cout << "converge!!" << endl;
break;
}
//if loop-17
//blockVectorR(:,activeMask) = blockVectorR(:,activeMask) - ...
// blockVectorX*(blockVectorX'*blockVectorR(:,activeMask));
#if defined(USE_CPU)
tstart = omp_get_wtime();
getActiveBlockVector(activeBlockVectorR, activeMask, blockVectorR, M, blocksize, currentBlockSize); //GET: 7
taskTiming[iterationNumber - 1][7] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
status = omp_target_memcpy(d_activeMask, activeMask, blocksize * sizeof(int), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed activeMask ==> %d\n", cuberror); return 0; }
cudaDeviceSynchronize();
tstart = omp_get_wtime();
getActiveBlockVector_GPU_v2(d_activeBlockVectorR, d_activeMask, d_blockVectorR, M, blocksize, currentBlockSize); //GET: 7
taskTiming[iterationNumber - 1][7] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(activeBlockVectorR, d_activeBlockVectorR, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorR: %d\n", cuberror);}
#endif
//blockVectorX'*blockVectorR(:,activeMask) -> temp2 is the result
// tstart = omp_get_wtime();
// std::memset(temp2, 0.0, sizeof(temp2));
// taskTiming[iterationNumber - 1][15] += (omp_get_wtime() - tstart);
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor,CblasTrans,CblasNoTrans, blocksize, currentBlockSize, M, 1.0, blockVectorX, blocksize, activeBlockVectorR, currentBlockSize,0.0, temp2, currentBlockSize); //XTY : 2
//_XTY(blockVectorX, activeBlockVectorR, temp2, M, blocksize, currentBlockSize, block_width);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
// cuberror = cudaMemcpy(d_blockVectorX, blockVectorX, M * blocksize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed blockVectorX ==> %d\n", cuberror); return 0; }
// cuberror = cudaMemcpy(d_activeBlockVectorR, activeBlockVectorR, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed blockVectorX ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, blocksize, M,
&cudaAlpha, d_activeBlockVectorR, currentBlockSize, d_blockVectorX, blocksize, &cudaBeta, d_temp2, currentBlockSize); //XY code 1
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-2: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
//d_temp2 is used in next operation no need to copy id back to host
// cuberror = cudaMemcpy(temp2, d_temp2, blocksize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed temp2: %d\n", cuberror);}
#endif
// printf("iterationNumber : %ld temp2 ==>\n", iterationNumber);
// print_mat(temp2, 2, currentBlockSize);
// printf("\n");
//temp3 = blockVectorX * temp2
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, currentBlockSize, blocksize, 1.0, blockVectorX, blocksize, temp2, currentBlockSize, 0.0, temp3, currentBlockSize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_CUBLAS)
//d_blockVectorX and d_temp2 are already in the device mem space, no need to copy them again.
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, currentBlockSize, M, blocksize,
&cudaAlpha, d_temp2, currentBlockSize, d_blockVectorX, blocksize, &cudaBeta, d_temp3, currentBlockSize); //XY code 1
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-3: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
//sending d_temp2 and d_temp3 to host mem space.
// cuberror = cudaMemcpy(temp2, d_temp2, blocksize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed temp2: %d\n", cuberror);}
// cuberror = cudaMemcpy(temp3, d_temp3, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed temp3: %d\n", cuberror);}
#endif
// printf("iterationNumber : %ld temp3 ==>\n", iterationNumber);
// print_mat(temp3, 2, currentBlockSize);
// printf("\n");
#if defined(USE_CPU)
tstart = omp_get_wtime();
mat_sub(activeBlockVectorR, temp3, activeBlockVectorR, M, currentBlockSize);
taskTiming[iterationNumber - 1][4] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
tstart = omp_get_wtime();
mat_sub_GPU_v2(d_activeBlockVectorR, d_temp3, d_activeBlockVectorR, M, currentBlockSize);
taskTiming[iterationNumber - 1][4] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(activeBlockVectorR, d_activeBlockVectorR, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorR: %d\n", cuberror);}
#endif
// tstart = omp_get_wtime();
// updateBlockVector(activeBlockVectorR, activeMask, blockVectorR, M, blocksize, currentBlockSize); //UPDATE: 8
// taskTiming[8] += (omp_get_wtime() - tstart);
//------- if 18 ------
//gramRBR=blockVectorR(:,activeMask)'*blockVectorR(:,activeMask); //blockVectorR(:,activeMask) ->activeBlockVectorR
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor,CblasTrans,CblasNoTrans, currentBlockSize, currentBlockSize, M, 1.0, activeBlockVectorR, currentBlockSize, activeBlockVectorR, currentBlockSize, 0.0,gramRBR, currentBlockSize);
//_XTY(activeBlockVectorR, activeBlockVectorR, gramRBR, M, currentBlockSize, currentBlockSize, block_width);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
// cuberror = cudaMemcpy(d_activeBlockVectorR, activeBlockVectorR, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("==> 634: cudaMemcpy failed activeBlockVectorR ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, currentBlockSize, M,
&cudaAlpha, d_activeBlockVectorR, currentBlockSize, d_activeBlockVectorR, currentBlockSize, &cudaBeta, d_gramRBR, currentBlockSize); //XY code 1
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-4: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
cuberror = cudaMemcpy(gramRBR, d_gramRBR, currentBlockSize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
if( cuberror != 0 ){ printf("cudaMemcpy failed d_gramRBR: %d\n", cuberror);}
cudaDeviceSynchronize();
#endif
//[gramRBR,cholFlag]=chol(gramRBR);
// tstart = omp_get_wtime();
// transpose(gramRBR, trans_gramRBR, currentBlockSize, currentBlockSize);
// taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
// tstart = omp_get_wtime();
// dpotrf_( &uplo, ¤tBlockSize, trans_gramRBR, ¤tBlockSize, &info );
// taskTiming[iterationNumber - 1][14] += (omp_get_wtime() - tstart);
// if(info != 0)
// {
// cout<<"dportf_ error 2!!"<<endl;
// break;
// }
// tstart = omp_get_wtime();
// transpose(trans_gramRBR, gramRBR, currentBlockSize, currentBlockSize);
// taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
info = LAPACKE_dpotrf(LAPACK_ROW_MAJOR , 'U' , currentBlockSize , gramRBR , currentBlockSize);
taskTiming[iterationNumber - 1][14] += (omp_get_wtime() - tstart);
if(info != 0)
cout << "dportf_ error 2!!" << endl;
tstart = omp_get_wtime();
#pragma omp parallel for private(j) default(shared)
for(i = 0 ; i < currentBlockSize ; i++)
{
for(j = 0 ; j < i ; j++)
{
gramRBR[i * currentBlockSize + j] = 0.0;
}
}
taskTiming[iterationNumber - 1][0] += (omp_get_wtime() - tstart);
//------- if 18 nested if -----
if(info == 0)
{
tstart = omp_get_wtime();
inverse(gramRBR, currentBlockSize, currentBlockSize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, currentBlockSize, currentBlockSize, 1.0, activeBlockVectorR, currentBlockSize, gramRBR, currentBlockSize, 0.0, temp3, currentBlockSize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
//d_activeBlockVectorR is already in device memory and activeBlockVectorR has not been changed since then.
status = omp_target_memcpy(d_gramRBR, gramRBR, currentBlockSize * currentBlockSize * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed d_gramRBR ==> %d\n", cuberror); return 0; }
cudaDeviceSynchronize();
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, currentBlockSize, M, currentBlockSize,
&cudaAlpha, d_gramRBR, currentBlockSize, d_activeBlockVectorR, currentBlockSize, &cudaBeta, d_temp3, currentBlockSize); //XY code 1
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-5: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
//cuberror = cudaMemcpy(temp3, d_temp3, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
//if( cuberror != 0 ){ printf("cudaMemcpy failed temp3: %d\n", cuberror);}
#endif
#if defined(USE_CPU)
tstart = omp_get_wtime();
custom_dlacpy(temp3, activeBlockVectorR, M, currentBlockSize); //DLACPY: 11
taskTiming[iterationNumber - 1][10] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
updateBlockVector(activeBlockVectorR, activeMask, blockVectorR, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][8] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
tstart = omp_get_wtime();
custom_dlacpy_GPU(d_temp3, d_activeBlockVectorR, M, currentBlockSize); //DLACPY: 11
taskTiming[iterationNumber - 1][10] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
updateBlockVector_GPU(d_activeBlockVectorR, d_activeMask, d_blockVectorR, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][8] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(activeBlockVectorR, d_activeBlockVectorR, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_activeBlockVectorR: %d\n", cuberror);}
// cuberror = cudaMemcpy(blockVectorR, d_blockVectorR, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed blockVectorR: %d\n", cuberror);}
#endif
// printf("iterationNumber : %ld activeBlockVectorR ==>\n", iterationNumber);
// print_mat(activeBlockVectorR, 2, currentBlockSize);
// printf("\n");
// printf("iterationNumber : %ld blockVectorR ==>\n", iterationNumber);
// print_mat(blockVectorR, 2, blocksize);
// printf("\n");
} //end if
#if defined(USE_BLAS)
tstart = omp_get_wtime();
#pragma omp parallel for private(j) default(shared)
for(i = 0; i < M ; i++)
{
for(j = 0 ; j < currentBlockSize ; j++)
{
activeBlockVectorAR[i * currentBlockSize + j] = 0.0;
}
}
taskTiming[iterationNumber - 1][0] += (omp_get_wtime() - tstart); //SETZERO : 0
tstart = omp_get_wtime();
//mkl_dcscmm(&transA, &M, ¤tBlockSize, &M, &alpha, matdescra, xrem, irem, colptrs, colptrs+1, activeBlockVectorR, ¤tBlockSize, &beta, activeBlockVectorAR, ¤tBlockSize);
//mkl_dcsrmm(&transA, &M, ¤tBlockSize, &M, &alpha, matdescra, acsr, ja, ia, ia+1, activeBlockVectorR, ¤tBlockSize, &beta, activeBlockVectorAR, ¤tBlockSize);
spmm_csr(numrows, numcols, currentBlockSize, ia, ja, acsr, activeBlockVectorR, activeBlockVectorAR);
taskTiming[iterationNumber - 1][6] += (omp_get_wtime() - tstart); //SPMM 6
#endif
#if defined(USE_CUBLAS)
tstart = omp_get_wtime();
//transpose(activeBlockVectorR, newX, currentBlockSize, M);
transpose_GPU(d_activeBlockVectorR, d_newX, currentBlockSize, M);
taskTiming[iterationNumber - 1][6] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(d_activeBlockVectorR, newX, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorR ==> %d\n", cuberror); return 0; }
// tstart = omp_get_wtime();
// custom_dlacpy_OpenACC(d_newX, d_activeBlockVectorR, M, currentBlockSize); //DLACPY: 11
// taskTiming[iterationNumber - 1][10] += (omp_get_wtime() - tstart);
// cudaError_t cudaStat1 = cudaMemset((void *)d_activeBlockVectorAR, 0, M * currentBlockSize * sizeof(double));
// if (cudaStat1 != cudaSuccess) { printf("Memset on Device failed"); return 1; }
tstart = omp_get_wtime();
status1 = cusparseDcsrmm(cusparseHandle, CUSPARSE_OPERATION_NON_TRANSPOSE, M, currentBlockSize, M,
nnonzero, &cudaAlpha, descr, d_xrem, d_colptrs, d_irem,
d_newX, M, &cudaBeta, d_temp3, M);
if (status1 != CUSPARSE_STATUS_SUCCESS)
printf("cusparseDcsrmm status: %d\n", status);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][6] += (omp_get_wtime() - tstart);
// cudaDeviceSynchronize();
//printf("SpMM status: %d\n", status);
// cuberror = cudaMemcpy(d_activeBlockVectorR, activeBlockVectorR, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorR ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
transpose_GPU(d_temp3, d_activeBlockVectorAR, M, currentBlockSize);
taskTiming[iterationNumber - 1][6] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(activeBlockVectorAR, d_activeBlockVectorAR, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorAR: %d\n", cuberror);}
#endif
if(iterationNumber > 1)
{
//if 20 first nested if
// gramPBP=blockVectorP(:,activeMask)'*blockVectorP(:,activeMask);
#if defined(USE_CPU)
tstart = omp_get_wtime();
getActiveBlockVector(activeBlockVectorP, activeMask, blockVectorP, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][7] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
// cuberror = cudaMemcpy(d_blockVectorP, blockVectorP, M * blocksize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_blockVectorP ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
getActiveBlockVector_GPU_v2(d_activeBlockVectorP, d_activeMask, d_blockVectorP, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][7] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(activeBlockVectorP, d_activeBlockVectorP, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorP: %d\n", cuberror);}
#endif
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, currentBlockSize, currentBlockSize, M, 1.0, activeBlockVectorP, currentBlockSize, activeBlockVectorP, currentBlockSize, 0.0, gramPBP, currentBlockSize);
//_XTY(activeBlockVectorP, activeBlockVectorP, gramPBP, M, currentBlockSize, currentBlockSize, block_width);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
//cuberror = cudaMemcpy(d_activeBlockVectorP, activeBlockVectorP, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
//if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorP ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, currentBlockSize, M,
&cudaAlpha, d_activeBlockVectorP, currentBlockSize, d_activeBlockVectorP, currentBlockSize, &cudaBeta, d_gramPBP, currentBlockSize); //XY
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-6: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
status = omp_target_memcpy(gramPBP, d_gramPBP, currentBlockSize * currentBlockSize * sizeof(double), 0, 0, h, t);
if( status != 0 ){ printf("cudaMemcpy failed d_gramRBR: %d\n", cuberror);}
cudaDeviceSynchronize();
#endif
// tstart = omp_get_wtime();
// transpose(gramPBP, trans_gramPBP, currentBlockSize, currentBlockSize);
// taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
// tstart = omp_get_wtime();
// dpotrf_( &uplo, ¤tBlockSize, trans_gramPBP, ¤tBlockSize, &info );
// taskTiming[iterationNumber - 1][14] += (omp_get_wtime() - tstart);
// if(info != 0)
// {
// cout<<"dportf_ error 3"<<endl;
// break;
// }
// tstart = omp_get_wtime();
// transpose(trans_gramPBP, gramPBP, currentBlockSize, currentBlockSize);
// taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
info = LAPACKE_dpotrf(LAPACK_ROW_MAJOR , 'U' , currentBlockSize , gramPBP , currentBlockSize);
taskTiming[iterationNumber - 1][14] += (omp_get_wtime() - tstart);
if(info != 0)
cout<<"dportf_ error 3"<<endl;
//making the lower part of gramPBP zero
tstart = omp_get_wtime();
#pragma omp parallel for private(j) default(shared)
for(i = 0 ; i < currentBlockSize ; i++)
{
for(j = 0 ; j < i ; j++)
{
gramPBP[i * currentBlockSize + j] = 0.0;
}
}
taskTiming[iterationNumber - 1][0] += (omp_get_wtime() - tstart);
if(info == 0)
{
//if 20 first nested if 2
// blockVectorP(:,activeMask) = blockVectorP(:,activeMask)/gramPBP;
tstart = omp_get_wtime();
inverse(gramPBP, currentBlockSize, currentBlockSize);
taskTiming[iterationNumber - 1][11] += (omp_get_wtime() - tstart);
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, currentBlockSize, currentBlockSize, 1.0, activeBlockVectorP, currentBlockSize, gramPBP, currentBlockSize, 0.0, temp3, currentBlockSize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_CUBLAS)
//d_activeBlockVectorP is already in the device mem space
status = omp_target_memcpy(d_gramPBP, gramPBP, currentBlockSize * currentBlockSize * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed gramPBP ==> %d\n", cuberror); return 0; }
cudaDeviceSynchronize();
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, currentBlockSize, M, currentBlockSize,
&cudaAlpha, d_gramPBP, currentBlockSize, d_activeBlockVectorP, currentBlockSize, &cudaBeta, d_temp3, currentBlockSize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-7: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
//cuberror = cudaMemcpy(temp3, d_temp3, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
//if( cuberror != 0 ){ printf("cudaMemcpy failed d_temp3: %d\n", cuberror);}
#endif
#if defined(USE_CPU)
tstart = omp_get_wtime();
custom_dlacpy(temp3, activeBlockVectorP, M, currentBlockSize);
taskTiming[iterationNumber -1][10] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
updateBlockVector(activeBlockVectorP, activeMask, blockVectorP, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][8] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
tstart = omp_get_wtime();
custom_dlacpy_GPU(d_temp3, d_activeBlockVectorP, M, currentBlockSize);
taskTiming[iterationNumber -1][10] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
updateBlockVector_GPU(d_activeBlockVectorP, d_activeMask, d_blockVectorP, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][8] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(activeBlockVectorP, d_activeBlockVectorP, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorP: %d\n", cuberror);}
// cuberror = cudaMemcpy(blockVectorP, d_blockVectorP, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed blockVectorP: %d\n", cuberror);}
#endif
#if defined(USE_CPU)
//blockVectorAP(:,activeMask) = blockVectorAP(:,activeMask)/gramPBP;
tstart = omp_get_wtime();
getActiveBlockVector(activeBlockVectorAP, activeMask, blockVectorAP, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][7] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
// cuberror = cudaMemcpy(d_blockVectorAP, blockVectorAP, M * blocksize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_blockVectorAP ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
getActiveBlockVector_GPU_v2(d_activeBlockVectorAP, d_activeMask, d_blockVectorAP, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][7] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(activeBlockVectorAP, d_activeBlockVectorAP, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorAP: %d\n", cuberror);}
#endif
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, currentBlockSize, currentBlockSize, 1.0, activeBlockVectorAP, currentBlockSize, gramPBP, currentBlockSize, 0.0, temp3, currentBlockSize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
//d_gramPBP is already in the device mem space
//cuberror = cudaMemcpy(d_activeBlockVectorAP, activeBlockVectorAP, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
//if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorAP ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, currentBlockSize, M, currentBlockSize,
&cudaAlpha, d_gramPBP, currentBlockSize, d_activeBlockVectorAP, currentBlockSize, &cudaBeta, d_temp3, currentBlockSize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-8: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
//cuberror = cudaMemcpy(temp3, d_temp3, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
//if( cuberror != 0 ){ printf("cudaMemcpy failed d_temp3: %d\n", cuberror);}
#endif
#if defined(USE_CPU)
tstart = omp_get_wtime();
custom_dlacpy(temp3, activeBlockVectorAP, M, currentBlockSize);
taskTiming[iterationNumber - 1][10] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
updateBlockVector(activeBlockVectorAP, activeMask, blockVectorAP, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][8] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
tstart = omp_get_wtime();
custom_dlacpy_GPU(d_temp3, d_activeBlockVectorAP, M, currentBlockSize);
taskTiming[iterationNumber - 1][10] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
updateBlockVector_GPU(d_activeBlockVectorAP, d_activeMask, d_blockVectorAP, M, blocksize, currentBlockSize);
taskTiming[iterationNumber - 1][8] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(activeBlockVectorAP, d_activeBlockVectorAP, M * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorAP: %d\n", cuberror);}
// cuberror = cudaMemcpy(blockVectorAP, d_blockVectorAP, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorAP: %d\n", cuberror);}
#endif
} //end if info
else
{
cout << "BLOPEX:lobpcg:DirectionNotFullRank...The direction matrix is not full rank." << endl;
}
} //end outer if
//restart=1;
//The Raileight-Ritz method for [blockVectorX blockVectorR blockVectorP]
//------ if 21
int flag = 1;
tstart = omp_get_wtime();
for(i = 0 ; i < blocksize ; i++)
{
//cout<<"residualNorms[i] :"<<residualNorms[i]<<endl;
if(residualNorms[i] < 4.0538e-10)
{
flag = 0;
break;
}
}
if(flag == 0)
explicitGramFlag = 1;
else
explicitGramFlag = 0;
activeRSize = currentBlockSize;
//---- if 22 -----
//cout<<"if 22"<<endl;
if(iterationNumber == 1)
{
activePSize = 0;
restart = 1;
//cout<<"restart: "<<restart<<endl;
}
else
{
activePSize = currentBlockSize;
restart = 0;
}
// cout << "Here 3" << endl;
taskTiming[iterationNumber - 1][0] += (omp_get_wtime() - tstart);
//gramXAR=full(blockVectorAX'*blockVectorR(:,activeMask));
//gramRAR=full(blockVectorAR(:,activeMask)'*blockVectorR(:,activeMask));
//gramRAR=(gramRAR'+gramRAR)*0.5;
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor,CblasTrans, CblasNoTrans, blocksize, currentBlockSize, M, 1.0, blockVectorAX, blocksize, activeBlockVectorR, currentBlockSize, 0.0, gramXAR, currentBlockSize);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_CUBLAS)
// cuberror = cudaMemcpy(d_activeBlockVectorR, activeBlockVectorR, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("==> 920: cudaMemcpy failed activeBlockVectorR ==> %d\n", cuberror); return 0; }
// cuberror = cudaMemcpy(d_blockVectorAX, blockVectorAX, M * blocksize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed blockVectorAX ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, blocksize, M,
&cudaAlpha, d_activeBlockVectorR, currentBlockSize, d_blockVectorAX, blocksize, &cudaBeta, d_gramXAR, currentBlockSize); //XY
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-9: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(gramXAR, d_gramXAR, blocksize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_gramXAR: %d\n", cuberror);}
#endif
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor,CblasTrans, CblasNoTrans, currentBlockSize, currentBlockSize, M, 1.0, activeBlockVectorAR, currentBlockSize, activeBlockVectorR, currentBlockSize, 0.0, gramRAR, currentBlockSize);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_CUBLAS)
//d_activeBlockVectorR := already in the device mem. space
// cuberror = cudaMemcpy(d_activeBlockVectorAR, activeBlockVectorAR, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorAR ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, currentBlockSize, M,
&cudaAlpha, d_activeBlockVectorR, currentBlockSize, d_activeBlockVectorAR, currentBlockSize, &cudaBeta, d_gramRAR, currentBlockSize); //XY
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-10: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(gramRAR, d_gramRAR, currentBlockSize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_gramRAR: %d\n", cuberror);}
#endif
#if defined(USE_BLAS)
tstart = omp_get_wtime();
transpose(gramRAR, transGramRAR, currentBlockSize, currentBlockSize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, currentBlockSize, currentBlockSize, currentBlockSize, 0.5, transGramRAR, currentBlockSize, identity_PAP, currentBlockSize, 0.5, gramRAR, currentBlockSize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
//d_gramRAR is already in the device mem space
double cudaAlphaHalf = 0.5, cudaBetaHalf = 0.5;
tstart = omp_get_wtime();
transpose_GPU(d_gramRAR, d_transGramRAR, currentBlockSize, currentBlockSize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(d_transGramRAR, transGramRAR, currentBlockSize * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed transGramRAR ==> %d\n", cuberror); return 0; }
// cuberror = cudaMemcpy(d_identity_PAP, identity_PAP, currentBlockSize * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed identity_PAP ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, currentBlockSize, currentBlockSize, currentBlockSize,
&cudaAlphaHalf, d_identity_PAP, currentBlockSize, d_transGramRAR, currentBlockSize, &cudaBetaHalf, d_gramRAR, currentBlockSize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-11: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(gramRAR, d_gramRAR, currentBlockSize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_gramRAR: %d\n", cuberror);}
// cout << "Here 4" << endl;
#endif
//--- cond_try for loop -----
for(int cond_try = 1 ; cond_try <=2 ; cond_try++)
{
if(restart == 0) //---- if 24 ----
{
if(restart == 0)
{
// cout << "Here 4-1" << endl;
//gramXAP=full(blockVectorAX'*blockVectorP(:,activeMask));
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, blocksize, currentBlockSize, M, 1.0, blockVectorAX, blocksize, activeBlockVectorP, currentBlockSize, 0.0, gramXAP, currentBlockSize);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
//d_blockVectorAX is already in the device mem space
// cuberror = cudaMemcpy(d_activeBlockVectorP, activeBlockVectorP, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorP ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, blocksize, M,
&cudaAlpha, d_activeBlockVectorP, currentBlockSize, d_blockVectorAX, blocksize, &cudaBeta, d_gramXAP, currentBlockSize);
// cudaDeviceSynchronize();
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-12: %d\n",cubstat);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(gramXAP, d_gramXAP, blocksize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed gramXAP: %d\n", cuberror);}
#endif
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, currentBlockSize, currentBlockSize, M, 1.0, activeBlockVectorAR, currentBlockSize, activeBlockVectorP, currentBlockSize, 0.0, gramRAP, currentBlockSize);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
//d_activeBlockVectorP & d_activeBlockVectorAR are already in the device mem space
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, currentBlockSize, M,
&cudaAlpha, d_activeBlockVectorP, currentBlockSize, d_activeBlockVectorAR, currentBlockSize, &cudaBeta, d_gramRAP, currentBlockSize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-13: %d\n",cubstat);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(gramRAP, d_gramRAP, currentBlockSize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed gramRAP: %d\n", cuberror);}
#endif
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, currentBlockSize, currentBlockSize, M, 1.0, activeBlockVectorAP, currentBlockSize, activeBlockVectorP, currentBlockSize, 0.0, gramPAP, currentBlockSize);
//_XTY(activeBlockVectorAP, activeBlockVectorP, gramPAP, M, currentBlockSize, currentBlockSize, block_width);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
//d_activeBlockVectorP is already in the device mem space
// cuberror = cudaMemcpy(d_activeBlockVectorAP, activeBlockVectorAP, M * currentBlockSize * sizeof(double), cudaMemcpyHostToDevice);
// if( cuberror != 0 ){ printf("cudaMemcpy failed activeBlockVectorAP ==> %d\n", cuberror); return 0; }
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, currentBlockSize, M,
&cudaAlpha, d_activeBlockVectorP, currentBlockSize, d_activeBlockVectorAP, currentBlockSize, &cudaBeta, d_gramPAP, currentBlockSize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-14: %d\n",cubstat);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
//d_gramPAP is used in the next operation
#endif
//gramPAP=(gramPAP'+gramPAP)*0.5;
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, currentBlockSize, currentBlockSize, currentBlockSize, 0.5, gramPAP, currentBlockSize, identity_PAP, currentBlockSize, 0.5, gramPAP, currentBlockSize);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
//d_gramPAP is in the device memory
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, currentBlockSize, currentBlockSize,
&cudaAlphaHalf, d_identity_PAP, currentBlockSize, d_gramPAP, currentBlockSize, &cudaBetaHalf, d_gramPAP, currentBlockSize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-15: %d\n",cubstat);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(gramPAP, d_gramPAP, blocksize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed gramPAP: %d\n", cuberror);}
#endif
if(explicitGramFlag == 1)
{
cout<<"nested if 24"<<endl;
}
else
{
//cout<<"if 24 nested if 1 else"<<endl;
//gramA = [ diag(lambda) gramXAR gramXAP
// gramXAR' gramRAR gramRAP
// gramXAP' gramRAP' gramPAP ];
cudaDeviceSynchronize();
gramASize = blocksize + currentBlockSize + currentBlockSize;
// cout << "Here 5" << endl;
//gramA = new double[gramASize * gramASize]();
#if defined(USE_CPU)
tstart = omp_get_wtime();
mat_copy(lambda, blocksize, blocksize, gramA, 0, 0, gramASize);
mat_copy(gramXAR, blocksize, currentBlockSize, gramA, 0, blocksize, gramASize);
mat_copy(gramXAP, blocksize, currentBlockSize, gramA, 0, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
transpose(gramXAR, transGramXAR, currentBlockSize, blocksize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
mat_copy(transGramXAR, currentBlockSize, blocksize, gramA, blocksize, 0, gramASize);
mat_copy(gramRAR, currentBlockSize, currentBlockSize, gramA, blocksize, blocksize, gramASize);
mat_copy(gramRAP, currentBlockSize, currentBlockSize, gramA, blocksize, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
transpose(gramXAP, transGramXAP, currentBlockSize, blocksize);
transpose(gramRAP, transGramRAP, currentBlockSize, currentBlockSize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
mat_copy(transGramXAP, currentBlockSize, blocksize, gramA, blocksize+currentBlockSize, 0, gramASize);
mat_copy(transGramRAP, currentBlockSize, currentBlockSize, gramA, blocksize+currentBlockSize, blocksize, gramASize);
mat_copy(gramPAP, currentBlockSize, currentBlockSize, gramA, blocksize+currentBlockSize, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
tstart = omp_get_wtime();
mat_copy_GPU(d_lambda, blocksize, blocksize, d_gramA, 0, 0, gramASize);
mat_copy_GPU(d_gramXAR, blocksize, currentBlockSize, d_gramA, 0, blocksize, gramASize);
mat_copy_GPU(d_gramXAP, blocksize, currentBlockSize, d_gramA, 0, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
transpose_GPU(d_gramXAR, d_transGramXAR, currentBlockSize, blocksize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
mat_copy_GPU(d_transGramXAR, currentBlockSize, blocksize, d_gramA, blocksize, 0, gramASize);
tstart = omp_get_wtime();
mat_copy_GPU(d_gramRAR, currentBlockSize, currentBlockSize, d_gramA, blocksize, blocksize, gramASize);
mat_copy_GPU(d_gramRAP, currentBlockSize, currentBlockSize, d_gramA, blocksize, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
transpose_GPU(d_gramXAP, d_transGramXAP, currentBlockSize, blocksize);
transpose_GPU(d_gramRAP, d_transGramRAP, currentBlockSize, currentBlockSize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
mat_copy_GPU(d_transGramXAP, currentBlockSize, blocksize, d_gramA, blocksize+currentBlockSize, 0, gramASize);
mat_copy_GPU(d_transGramRAP, currentBlockSize, currentBlockSize, d_gramA, blocksize+currentBlockSize, blocksize, gramASize);
mat_copy_GPU(d_gramPAP, currentBlockSize, currentBlockSize, d_gramA, blocksize+currentBlockSize, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
status = omp_target_memcpy(gramA, d_gramA, gramASize * gramASize * sizeof(double), 0, 0, h, t);
if( status != 0 ){ printf("cudaMemcpy failed gramA: %d\n", cuberror);}
#endif
// tstart = omp_get_wtime();
// mat_copy(lambda, blocksize, blocksize, gramA, 0, 0, gramASize);
// mat_copy(gramXAR, blocksize, currentBlockSize, gramA, 0, blocksize, gramASize);
// mat_copy(gramXAP, blocksize, currentBlockSize, gramA, 0, blocksize+currentBlockSize, gramASize);
// taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
// tstart = omp_get_wtime();
// transpose(gramXAR, transGramXAR, currentBlockSize, blocksize);
// taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
// tstart = omp_get_wtime();
// mat_copy(transGramXAR, currentBlockSize, blocksize, gramA, blocksize, 0, gramASize);
// mat_copy(gramRAR, currentBlockSize, currentBlockSize, gramA, blocksize, blocksize, gramASize);
// mat_copy(gramRAP, currentBlockSize, currentBlockSize, gramA, blocksize, blocksize+currentBlockSize, gramASize);
// taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
// tstart = omp_get_wtime();
// transpose(gramXAP, transGramXAP, currentBlockSize, blocksize);
// transpose(gramRAP, transGramRAP, currentBlockSize, currentBlockSize);
// taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
// tstart = omp_get_wtime();
// mat_copy(transGramXAP, currentBlockSize, blocksize, gramA, blocksize+currentBlockSize, 0, gramASize);
// mat_copy(transGramRAP, currentBlockSize, currentBlockSize, gramA, blocksize+currentBlockSize, blocksize, gramASize);
// mat_copy(gramPAP, currentBlockSize, currentBlockSize, gramA, blocksize+currentBlockSize, blocksize+currentBlockSize, gramASize);
// taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
} //end else
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, blocksize, currentBlockSize, M, 1.0, blockVectorX, blocksize, activeBlockVectorP, currentBlockSize, 0.0, gramXBP, currentBlockSize);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
//d_gramPAP is in the device memory
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, blocksize, M,
&cudaAlpha, d_activeBlockVectorP, currentBlockSize, d_blockVectorX, blocksize, &cudaBeta, d_gramXBP, currentBlockSize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-16: %d\n",cubstat);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(gramXBP, d_gramXBP, blocksize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed gramXBP: %d\n", cuberror);}
// cudaDeviceSynchronize();
#endif
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, currentBlockSize, currentBlockSize, M, 1.0, activeBlockVectorR, currentBlockSize, activeBlockVectorP, currentBlockSize, 0.0, gramRBP, currentBlockSize);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_CUBLAS)
//d_gramPAP is in the device memory
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, currentBlockSize, currentBlockSize, M,
&cudaAlpha, d_activeBlockVectorP, currentBlockSize, d_activeBlockVectorR, currentBlockSize, &cudaBeta, d_gramRBP, currentBlockSize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-17: %d\n",cubstat);
taskTiming[iterationNumber - 1][2] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(gramRBP, d_gramRBP, currentBlockSize * currentBlockSize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed gramXBP: %d\n", cuberror);}
#endif
if(explicitGramFlag==1)
{
cout << "if 24 nested if 3" << endl;
}
else
{
// cout << "Here 6" << endl;
//cout<<"if 24 nested if 3 else"<<endl;
//gramB=[eye(blockSize) zeros(blockSize,activeRSize) gramXBP
// zeros(blockSize,activeRSize)' eye(activeRSize) gramRBP
// gramXBP' gramRBP' eye(activePSize) ];
//gramB = new double[gramASize * gramASize];
cudaDeviceSynchronize();
#if defined(USE_CPU)
tstart = omp_get_wtime();
mat_copy(identity_BB, blocksize, blocksize, gramB, 0, 0, gramASize);
mat_copy(zeros_B_CB, blocksize, currentBlockSize, gramB, 0, blocksize, gramASize);
mat_copy(gramXBP, blocksize, currentBlockSize, gramB, 0, blocksize+currentBlockSize, gramASize);
mat_copy(zeros_CB_B, activeRSize, blocksize, gramB, blocksize, 0, gramASize);
mat_copy(identity_PAP, activeRSize, activeRSize, gramB, blocksize, blocksize, gramASize);
mat_copy(gramRBP, currentBlockSize, currentBlockSize, gramB, blocksize, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
transpose(gramXBP, transGramXBP, currentBlockSize, blocksize);
transpose(gramRBP, transGramRBP, currentBlockSize, currentBlockSize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
mat_copy(transGramXBP, currentBlockSize, blocksize, gramB, blocksize+currentBlockSize, 0, gramASize);
mat_copy(transGramRBP, currentBlockSize, currentBlockSize, gramB, blocksize+currentBlockSize, blocksize, gramASize);
mat_copy(identity_PAP, activePSize, activePSize, gramB, blocksize+currentBlockSize, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
tstart = omp_get_wtime();
mat_copy_GPU(d_identity_BB, blocksize, blocksize, d_gramB, 0, 0, gramASize);
mat_copy_GPU(d_zeros_B_CB, blocksize, currentBlockSize, d_gramB, 0, blocksize, gramASize);
mat_copy_GPU(d_gramXBP, blocksize, currentBlockSize, d_gramB, 0, blocksize+currentBlockSize, gramASize);
mat_copy_GPU(d_zeros_B_CB, activeRSize, blocksize, d_gramB, blocksize, 0, gramASize);
mat_copy_GPU(d_identity_PAP, activeRSize, activeRSize, d_gramB, blocksize, blocksize, gramASize);
mat_copy_GPU(d_gramRBP, currentBlockSize, currentBlockSize, d_gramB, blocksize, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
transpose_GPU(d_gramXBP, d_transGramXBP, currentBlockSize, blocksize);
transpose_GPU(d_gramRBP, d_transGramRBP, currentBlockSize, currentBlockSize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
mat_copy_GPU(d_transGramXBP, currentBlockSize, blocksize, d_gramB, blocksize+currentBlockSize, 0, gramASize);
mat_copy_GPU(d_transGramRBP, currentBlockSize, currentBlockSize, d_gramB, blocksize+currentBlockSize, blocksize, gramASize);
mat_copy_GPU(d_identity_PAP, activePSize, activePSize, d_gramB, blocksize+currentBlockSize, blocksize+currentBlockSize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
status = omp_target_memcpy(gramB, d_gramB, gramASize * gramASize * sizeof(double), 0 , 0 , h, t);
if( status != 0 ){ printf("cudaMemcpy failed gramB: %d\n", cuberror);}
#endif
}
} //inner if end
} //outer if end
else //---- if 24 else ----
{
if(explicitGramFlag == 1 ) //--- if 24 else nested if --
{
//cout<<"if 24 else nested if"<<endl;
//gramA = [ gramXAX gramXAR
// gramXAR' gramRAR ];
//gramB = [ gramXBX gramXBR
// gramXBR' eye(activeRSize) ];
}
else //--- if 24 else nested else;
{
//cout<<"if 24 else nested else"<<endl;
//gramA = [ diag(lambda) gramXAR
// gramXAR' gramRAR ];
//gramB = eye(blockSize+activeRSize);
cudaDeviceSynchronize();
// cout << "Here 7" << endl;
gramASize = blocksize + activeRSize;
//gramA = new double[gramASize * gramASize]();
#if defined(USE_CPU)
tstart = omp_get_wtime();
mat_copy(lambda, blocksize, blocksize, gramA, 0, 0, gramASize);
mat_copy(gramXAR, blocksize, currentBlockSize, gramA, 0, blocksize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
transpose(gramXAR, transGramXAR, currentBlockSize, blocksize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
mat_copy(transGramXAR, currentBlockSize, blocksize, gramA, blocksize, 0, gramASize);
mat_copy(gramRAR, currentBlockSize, currentBlockSize, gramA, blocksize, blocksize, gramASize);
#endif
#if defined(USE_OPENACC)
tstart = omp_get_wtime();
mat_copy_GPU(d_lambda, blocksize, blocksize, d_gramA, 0, 0, gramASize);
mat_copy_GPU(d_gramXAR, blocksize, currentBlockSize, d_gramA, 0, blocksize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
transpose_GPU(d_gramXAR, d_transGramXAR, currentBlockSize, blocksize);
taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
tstart = omp_get_wtime();
mat_copy_GPU(d_transGramXAR, currentBlockSize, blocksize, d_gramA, blocksize, 0, gramASize);
mat_copy_GPU(d_gramRAR, currentBlockSize, currentBlockSize, d_gramA, blocksize, blocksize, gramASize);
status = omp_target_memcpy(gramA, d_gramA, gramASize * gramASize * sizeof(double), 0, 0, h, t);
if( status != 0 ){ printf("cudaMemcpy failed gramA: %d\n", cuberror);}
#endif
//gramB = new double[gramASize * gramASize]();
make_identity_mat(gramB, gramASize, gramASize);
taskTiming[iterationNumber - 1][13] += (omp_get_wtime() - tstart);
// cout << "Here 8" << endl;
}
} //end else
//--------- if 25 part of it ------
//cout<<"if 25 part of it"<<endl;
if(cond_try == 1 && ~restart)
{
//cout<<"if 25 else-> break from here"<<endl;
//restart=1;
break;
}
}//inner loop finish here
//tstart = omp_get_wtime();
cudaDeviceSynchronize();
eigen_value = new double[gramASize]();
tstart = omp_get_wtime();
info = LAPACKE_dsygv(LAPACK_ROW_MAJOR, itype, jobz, uplo, gramASize, gramA, gramASize, gramB, gramASize, eigen_value);
taskTiming[iterationNumber - 1][9] += (omp_get_wtime() - tstart);
// cout << "Here 9" << endl;
// double *trans_gramA = new double[gramASize * gramASize]();
// double *trans_gramB = new double[gramASize * gramASize]();
// tstart = omp_get_wtime();
// transpose(gramA, trans_gramA, gramASize, gramASize);
// transpose(gramB, trans_gramB, gramASize, gramASize);
// taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
// tstart = omp_get_wtime();
// lwork = -1;
// dsygv_(&itype, &jobz, &uplo, &gramASize, trans_gramA, &gramASize, trans_gramB, &gramASize, eigen_value, &work_query, &lwork, &info);
// if(info != 0)
// cout<<"Error in dummy call"<<endl;
// lwork = (int) work_query;
// work = new double[lwork]();
// dsygv_(&itype, &jobz, &uplo, &gramASize, trans_gramA, &gramASize, trans_gramB, &gramASize, eigen_value, work, &lwork, &info);
// taskTiming[iterationNumber - 1][9] += (omp_get_wtime() - tstart);
// if(info != 0)
// cout<<"Error in eigen value calculation"<<endl;
// tstart = omp_get_wtime();
// transpose(trans_gramA, gramA, gramASize, gramASize);
// transpose(trans_gramB, gramB, gramASize, gramASize);
// taskTiming[iterationNumber - 1][12] += (omp_get_wtime() - tstart);
// delete []trans_gramA;
// delete []trans_gramB;
if( info != 0 )
{
printf("LAPACKE_dsygv error: The algorithm failed to compute eigenvalues.\n" );
break;
}
tstart = omp_get_wtime();
diag(eigen_value, lambda, blocksize);
taskTiming[iterationNumber - 1][17] += (omp_get_wtime() - tstart);
// cout << "Here 10" << endl;
int column = 0;
coordX = new double[gramASize * blocksize]();
tstart = omp_get_wtime();
for(j = 0 ; column < blocksize && j < gramASize ; j++)
{
#pragma omp parallel for default(shared)
for(i = 0 ; i < gramASize ; i++)
{
coordX[i * blocksize + column] = gramA[i * gramASize + j];
}
column++;
}
taskTiming[iterationNumber - 1][0] += (omp_get_wtime() - tstart);
//taskTiming[9] += (omp_get_wtime() - tstart);
#if defined(USE_CUBLAS)
//copying d_coordX to the device memoery for the following operations.
d_coordX = (double *) omp_target_alloc(gramASize * blocksize * sizeof(double), t);
if( d_coordX == NULL ){ printf("omp_target_alloc Filed d_coordX\n"); return 0; }
status = omp_target_memcpy(d_coordX, coordX, gramASize * blocksize * sizeof(double), 0, 0, t, h);
if( status != 0 ){ printf("cudaMemcpy failed d_coordX ==> %d\n", cuberror); return 0; }
cudaDeviceSynchronize();
#endif
if(restart == 0)
{
// partil result- part1:- blockVectorP = blockVectorR(:,activeMask)*coordX(blockSize+1:blockSize+activeRSize,:)
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, blocksize, currentBlockSize, 1.0, activeBlockVectorR, currentBlockSize, coordX+(blocksize*blocksize), blocksize, 0.0, blockVectorP, blocksize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, blocksize, M, currentBlockSize,
&cudaAlpha, d_coordX+(blocksize*blocksize), blocksize, d_activeBlockVectorR, currentBlockSize, &cudaBeta, d_blockVectorP, blocksize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-18: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
/*blockVectorP = blockVectorR(:,activeMask)*coordX(blockSize+1:blockSize+activeRSize,:) + blockVectorP(:,activeMask)*coordX(blockSize+activeRSize+1:blockSize+activeRSize+activePSize,:); */
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, blocksize, currentBlockSize, 1.0, activeBlockVectorP, currentBlockSize, coordX+((blocksize+currentBlockSize)*blocksize), blocksize, 1.0, blockVectorP, blocksize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, blocksize, M, currentBlockSize,
&cudaAlpha, d_coordX+((blocksize+currentBlockSize)*blocksize), blocksize, d_activeBlockVectorP, currentBlockSize, &cudaBetaOne, d_blockVectorP, blocksize);
// cuberror = cudaMemcpy(blockVectorP, d_blockVectorP, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_blockVectorP: %d\n", cuberror);}
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-19: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
/*blockVectorAP = blockVectorAR(:,activeMask)*coordX(blockSize+1:blockSize+activeRSize,:) + blockVectorAP(:,activeMask)*coordX(blockSize+activeRSize+1:blockSize + activeRSize+activePSize,:);*/
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, blocksize, currentBlockSize, 1.0, activeBlockVectorAR, currentBlockSize, coordX+(blocksize*blocksize), blocksize, 0.0, blockVectorAP, blocksize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, blocksize, M, currentBlockSize,
&cudaAlpha, d_coordX+(blocksize*blocksize), blocksize, d_activeBlockVectorAR, currentBlockSize, &cudaBeta, d_blockVectorAP, blocksize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-20: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, blocksize, currentBlockSize, 1.0, activeBlockVectorAP, currentBlockSize, coordX+((blocksize+currentBlockSize)*blocksize), blocksize, 1.0, blockVectorAP, blocksize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, blocksize, M, currentBlockSize,
&cudaAlpha, d_coordX+((blocksize+currentBlockSize)*blocksize), blocksize, d_activeBlockVectorAP, currentBlockSize, &cudaBetaOne, d_blockVectorAP, blocksize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-21: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(blockVectorAP, d_blockVectorAP, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_blockVectorAP: %d\n", cuberror);}
#endif
}
else
{
// blockVectorP = blockVectorR(:,activeMask)*...
// coordX(blockSize+1:blockSize+activeRSize,:);
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor,CblasNoTrans, CblasNoTrans, M, blocksize, activeRSize, 1.0, activeBlockVectorR, currentBlockSize, coordX+(blocksize*blocksize), blocksize, 0.0, blockVectorP, blocksize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, blocksize, M, currentBlockSize,
&cudaAlpha, d_coordX+(blocksize*blocksize), blocksize, d_activeBlockVectorR, currentBlockSize, &cudaBeta, d_blockVectorP, blocksize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-22: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(blockVectorP, d_blockVectorP, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_blockVectorP: %d\n", cuberror);}
#endif
//blockVectorAP = blockVectorAR(:,activeMask)*coordX(blockSize+1:blockSize+activeRSize,:);
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor,CblasNoTrans, CblasNoTrans, M, blocksize, activeRSize, 1.0, activeBlockVectorAR, currentBlockSize, coordX+(blocksize*blocksize), blocksize, 0.0, blockVectorAP, blocksize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, blocksize, M, currentBlockSize,
&cudaAlpha, d_coordX+(blocksize*blocksize), blocksize, d_activeBlockVectorAR, currentBlockSize, &cudaBeta, d_blockVectorAP, blocksize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-22: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(blockVectorAP, d_blockVectorAP, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_blockVectorAP: %d\n", cuberror);}
#endif
}
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, blocksize, blocksize, 1.0, blockVectorX, blocksize, coordX, blocksize, 0.0, newX, blocksize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, blocksize, M, blocksize,
&cudaAlpha, d_coordX, blocksize, d_blockVectorX, blocksize, &cudaBeta, d_newX, blocksize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-23: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(newX, d_newX, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_newX: %d\n", cuberror);}
//cudaDeviceSynchronize();
#endif
#if defined(USE_BLAS)
tstart = omp_get_wtime();
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, blocksize, blocksize, 1.0, blockVectorAX, blocksize, coordX, blocksize, 0.0, newX, blocksize);
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
#endif
#if defined( USE_CUBLAS )
tstart = omp_get_wtime();
cubstat = cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, blocksize, M, blocksize,
&cudaAlpha, d_coordX, blocksize, d_blockVectorAX, blocksize, &cudaBeta, d_temp3, blocksize);
if(cubstat != CUBLAS_STATUS_SUCCESS)
printf("cublasDgemm status-24: %d\n",cubstat);
cudaDeviceSynchronize();
taskTiming[iterationNumber - 1][1] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(temp3, d_temp3, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_temp3: %d\n", cuberror);}
//cudaDeviceSynchronize();
#endif
#if defined(USE_CPU)
tstart = omp_get_wtime();
mat_addition(newX, blockVectorP, blockVectorX, M, blocksize);
taskTiming[iterationNumber - 1][3] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
cudaDeviceSynchronize();
tstart = omp_get_wtime();
mat_addition_GPU(d_newX, d_blockVectorP, d_blockVectorX, M, blocksize);
taskTiming[iterationNumber - 1][3] += (omp_get_wtime() - tstart);
// cuberror = cudaMemcpy(blockVectorX, d_blockVectorX, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_blockVectorX: %d\n", cuberror);}
//cudaDeviceSynchronize();
#endif
#if defined(USE_CPU)
tstart = omp_get_wtime();
mat_addition(temp3, blockVectorAP, blockVectorAX, M, blocksize);
taskTiming[iterationNumber - 1][3] += (omp_get_wtime() - tstart);
#endif
#if defined(USE_OPENACC)
tstart = omp_get_wtime();
mat_addition_GPU(d_temp3, d_blockVectorAP, d_blockVectorAX, M, blocksize);
taskTiming[iterationNumber - 1][3] += (omp_get_wtime() - tstart);
// cudaDeviceSynchronize();
// cuberror = cudaMemcpy(blockVectorAX, d_blockVectorAX, M * blocksize * sizeof(double), cudaMemcpyDeviceToHost);
// if( cuberror != 0 ){ printf("cudaMemcpy failed d_blockVectorAX: %d\n", cuberror);}
cudaDeviceSynchronize();
#endif
//temp1Time=omp_get_wtime();
delete []eigen_value;
// delete []work;
//delete []gramA;
//delete []gramB;
delete []coordX;
#if defined( USE_CUBLAS )
omp_target_free(d_coordX, t);
cudaDeviceSynchronize();
#endif
prevCurrentBlockSize = currentBlockSize;
loopTime[iterationNumber - 1] = omp_get_wtime() - loop_start_time;
for(i = 0 ; i < blocksize ; i++)
{
saveLamda[i][iterationNumber - 1] = lambda[i * blocksize + i];
}
/*printf("%10s %.6lf sec.\n", "SETZERO", taskTiming[0]);
printf("%10s %.6lf sec.\n", "XY", taskTiming[1]);
printf("%10s %.6lf sec.\n", "XTY", taskTiming[2]);
printf("%10s %.6lf sec.\n", "ADD", taskTiming[3]);
printf("%10s %.6lf sec.\n", "SUB", taskTiming[4]);
printf("%10s %.6lf sec.\n", "MULT", taskTiming[5]);
printf("%10s %.6lf sec.\n", "SPMM", taskTiming[6]);
printf("%10s %.6lf sec.\n", "GET", taskTiming[7]);
printf("%10s %.6lf sec.\n", "UPDATE", taskTiming[8]);
printf("%10s %.6lf sec.\n", "EIGEN", taskTiming[9]);
printf("%10s %.6lf sec.\n", "DLACPY", taskTiming[10]);*/
} //loop ends
#if defined(USE_CUBLAS)
omp_target_free(d_blockVectorX, t);
omp_target_free(d_blockVectorAX, t);
omp_target_free(d_blockVectorR, t);
omp_target_free(d_blockVectorP, t);
omp_target_free(d_blockVectorAP, t);
omp_target_free(d_newX, t);
omp_target_free(d_activeBlockVectorR, t);
omp_target_free(d_activeBlockVectorAR, t);
omp_target_free(d_activeBlockVectorP, t);
omp_target_free(d_activeBlockVectorAP, t);
omp_target_free(d_temp3, t);
omp_target_free(d_temp2, t);
omp_target_free(d_lambda, t);
omp_target_free(d_gramRBR, t);
omp_target_free(d_gramPBP, t);
omp_target_free(d_gramXAR, t);
omp_target_free(d_gramRAR, t);
omp_target_free(d_gramXAP, t);
omp_target_free(d_gramPAP, t);
omp_target_free(d_gramRAP, t);
omp_target_free(d_gramXBP, t);
omp_target_free(d_gramRBP, t);
cublasDestroy(handle);
#endif
//iteraton_time = omp_get_wtime() - iteraton_start_time;
// cout << "Total iterations: " << iterationNumber -1 << endl;
//cout << "Total Execution time: " << iteraton_time << " sec." << endl;
//printf("LoopTime: \n");
double totalSum = 0;
for(j = 3 ; j < maxIterations ; j++)
{
totalSum += loopTime[j];
printf("%.4lf,", loopTime[j]);
//if(j != maxIterations - 1)
// printf(",");
}
printf("%.4lf", totalSum/(maxIterations-3));
printf("\n");
//printing eigen values
for(i = 0 ; i < blocksize ; i++)
{
for(j = 0 ; j < maxIterations ; j++)
{
printf("%.4lf", saveLamda[i][j]);
if(j != maxIterations - 1)
printf(",");
}
printf("\n");
}
double avgTotal = 0.0;
for(j = 0 ; j < numTasks ; j++)
{
totalSum = 0.0;
for(i = 3 ; i < maxIterations ; i++)
{
totalSum += taskTiming[i][j];
}
avgTotal += totalSum/(maxIterations - 3);
printf("%s,%.6lf\n", function_name[j].c_str(), totalSum/(maxIterations - 3));
}
printf("Kernel Total,%.6lf\n", avgTotal);
return 0;
}
|
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>
using namespace std;
map<char, int> hand = {{'R', 0}, {'S', 1}, {'P', 2}};
class BIT {
public:
// 要素数N、値vで初期化
explicit BIT(int N, int v) : V_NUM(N) {
data.resize(N);
fill(data.begin(), data.end(), v);
}
// [1, i]の総和を求める
int query(int i) {
int ret = 0;
while (i > 0) {
ret += data[i];
i -= (i & -i);
}
return ret;
}
// data[i]にv可算
void update(int i, int v) {
while (i < V_NUM) {
data[i] += v;
i += (i & -i);
}
}
int V_NUM;
vector<int> data;
};
int main() {
int N, Q;
string S;
cin >> N >> Q >> S;
S = "$" + S;
vector<BIT> bit(3, BIT(N + 1, 0));
vector<set<int>> pos(3);
for (int i = 1; i <= N; ++i) {
bit[hand[S[i]]].update(i, 1);
pos[hand[S[i]]].insert(i);
}
for (int q = 0; q <= Q; ++q) {
int lose = 0;
int emp = 0;
for (int h = 0; h < 3; ++h) {
if (pos[h].empty()) ++emp;
}
if (emp == 1) {
for (int h = 0; h < 3; ++h) {
if (pos[h].empty() || pos[(h + 1) % 3].empty()) continue;
lose = pos[(h + 1) % 3].size();
}
} else if (emp == 0) {
for (int h = 0; h < 3; ++h) {
int w = (h + 1) % 3, l = (h + 2) % 3;
int wpos = *(pos[w].begin()), lpos = *(pos[l].begin());
lose += max(0, bit[h].query(wpos) - bit[h].query(lpos));
wpos = *(--pos[w].end()), lpos = *(--pos[l].end());
lose += max(0, bit[h].query(lpos) - bit[h].query(wpos));
}
}
cout << N - lose << endl;
if (q == Q) break;
int p;
char c;
cin >> p >> c;
bit[hand[S[p]]].update(p, -1);
pos[hand[S[p]]].erase(p);
bit[hand[c]].update(p, 1);
pos[hand[c]].insert(p);
S[p] = c;
}
return 0;
}
|
#include "graphimpl.h"
#include "coveragecalculator.h"
#include <string>
#include <iostream>
#include <regex>
#include <string>
struct Data
{
bool mIsRed;
};
bool checkIsRed(const Data & data)
{
return data.mIsRed;
}
bool isSmaller(const size_t & w1, const size_t & w2)
{
return w1 < w2;
}
template<typename T>
void customQuickSort(T *array, size_t sizeOfArray)
{
T supportElement = array[sizeOfArray / 2];
size_t i = 0;
size_t j = sizeOfArray - 1;
do
{
do
{
++i;
}while(array[i] <= supportElement && i < sizeOfArray);
do
{
--j;
}while(array[j] >= supportElement && j >= 0);
if(i <= j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}while(i <= j);
if(j > 0)
{
customQuickSort(array, j);
}
if(i < sizeOfArray)
{
customQuickSort(array + i, sizeOfArray - i);
}
}
int main()
{
size_t N = 3;
int *A = new int[N];
for (size_t i = 0; i < N; ++i)
{
A[i] = rand() % 10;
}
//customQuickSort<int>(A, N);
std::unordered_set<std::string> mPropertiesNeeded {"one", "two", "three", "four", "six"};
CoverageCalculator<int, std::string> calc(mPropertiesNeeded.begin(), mPropertiesNeeded.end());
std::unordered_set<std::string> s1 {"one"};
calc.addObject(1, s1.begin(), s1.end());
std::unordered_set<std::string> s2 {"two"};
calc.addObject(2, s2.begin(), s2.end());
std::unordered_set<std::string> s3 {"three"};
calc.addObject(3, s3.begin(), s3.end());
std::unordered_set<std::string> s4 {"four"};
calc.addObject(4, s4.begin(), s4.end());
std::unordered_set<std::string> s5 {"five"};
calc.addObject(5, s5.begin(), s5.end());
std::unordered_set<int> result = calc.calculateCoverage();
/*std::string begin = "begin";
Data d1;
d1.mIsRed = false;
std::string A = "A";
Data d2;
d2.mIsRed = false;
std::string B = "B";
Data d3;
d3.mIsRed = false;
std::string end = "end";
Data d4;
d4.mIsRed = true;
IGraph<std::string, Data, size_t> *graph = new GraphImpl<std::string, Data>();
graph->addNode(begin, std::move(d1));
graph->addNode(A, std::move(d2));
graph->addNode(B, std::move(d3));
graph->addNode(end, std::move(d4));
bool resAddEdge1 = graph->addEdge(begin, A, 6);
bool resAddEdge2 = graph->addEdge(begin, B, 2);
bool resAddEdge3 = graph->addEdge(B, A, 3);
bool resAddEdge4 = graph->addEdge(A, end, 1);
bool resAddEdge5 = graph->addEdge(B, end, 5);
std::pair<bool, std::string> res1 = breadthFirstSearch<std::string, Data>(*graph, begin, checkIsRed);
std::pair<bool, std::vector<std::string>> res2 = DijkstraAlgorithm<std::string, Data, size_t>(*graph, begin, end, isSmaller);*/
return 0;
}
|
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <set>
#include <stack>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cstdlib>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n, 0);
vector<int> m(n, 0);
int res = 0, index = 0;
for (int i = 0; i < n; i++) {
cin >> v[i];
m[v[i]] = i;
}
while (true) {
if (m[0] != 0) {
swap(v[m[0]], v[m[m[0]]]);
swap(m[0], m[m[0]]);
res++;
}
else {
bool finish = true;
for (int i = index; i < v.size(); i++) {
if (v[i] != i) {
swap(m[0], m[v[i]]);
swap(v[i], v[0]);
res++;
finish = false;
index = i;
break;
}
}
if (finish) break;
}
}
cout << res;
return 0;
}
|
//////////////////////////////////////////////////////////
// main.cpp //
// FluidSimulation2D //
// //
// Created by nana on 6/4/15. //
// Copyright (c) 2015 na. All rights reserved. //
//////////////////////////////////////////////////////////
#include <iostream>
#include <GLUT/GLUT.h>
#include <math.h>
using namespace std;
#define N 128 // the resolution size of grid
#define M_SIZE (N+2)*(N+2) // the size of grid
#define IX(i,j) ((i)+(N+2)*(j)) // index of the float array, i and j are the horizontal and vertical component in Cartesian coordinates
#define SWAP(x0,x) {float *temp=x0; x0=x; x=temp;} // x0 is the cause, x is the effect
float *u;
float *v;
float *u_init;
float *v_init;
float *fx;
float *fy;
float *dens[3];
float *dens_init[3];
float visc = 10;
float dt = 0.1;
float diff = 0.1;
float xmult=3,ymult=3;
int currentButton=0,currentColor=1;
/**
* Set the boundary condition
* @param b: b=1 horizontal component of velocity on the vertical wall
* b=2 vertical component of velocity on the horizontal wall
* @param var: density or velocity or pressure array
*/
void setBnd(int b,float* var){
for (int i=1; i<=N; i++) {
var[IX(0, i)] = b == 1 ? -var[IX(1, i)] : var[IX(1, i)];
var[IX(N+1, i)] = b == 1 ? -var[IX(N, i)] : var[IX(N, i)];
var[IX(i, 0)] = b == 2 ? -var[IX(i, 1)] : var[IX(i, 1)];
var[IX(i, N+1)] = b == 2 ? -var[IX(i, N)] : var[IX(i, N)];
}
var[IX(0, 0)] = 0.5 * (var[IX(1, 0)] + var[IX(0, 1)]);
var[IX(0, N+1)] = 0.5 * (var[IX(1, N+1)] + var[IX(0, N)]);
var[IX(N+1, 0)] = 0.5 * (var[IX(N, 0)] + var[IX(N+1, 1)]);
var[IX(N+1, N+1)] = 0.5 *(var[IX(N, N+1)] + var[IX(N+1, N)]);
}
/**
* This is to implement the force term
* assume that the source for a given frame is provided in the array source[]
* source[] is filled in by the mouse movement which detects source of density
*/
void addSource(float* cell, float* source, float dt) {
for (int i=0; i<M_SIZE; i++) {
cell[i] += dt * source[i];
}
}
/**
* This is to implement the diffusion term
* @param current: current moument cell density
* @param previous: previous moument cell density
* @param diff: diffusion coefficient
* @param dt: time interval
* use Gauss-Seidel Relaxation
* iteration times: k=20
*/
void diffuse(int b, float* current, float* previous, float diff, float dt) {
float a = dt * diff * N * N;
for (int k=0; k<20; k++) {
for (int i=1; i<=N; i++) {
for (int j=1; j<=N; j++) {
current[IX(i, j)] = (previous[IX(i, j)] + a*(current[IX(i-1, j)] + current[IX(i+1, j)]
+ current[IX(i, j-1)] + current[IX(i, j+1)])) / (1 + 4 * a);
}
}
}
setBnd(b,current);
}
/**
* This is to implement the advection term
* @param current: current moment cell density
* @param previous: previous moment cell density
* @param u: the first coordinate of velocity field
* @param v: the second coordinate of velocity field
* @param dt: time interval
* use Bilinear interpolation
* lerp is the linear interpolation function
*/
float lerp(float a, float b, float t)
{
return (1-t)*a + t*b;
}
void advect(int b,float* current,float* previous,float* u,float* v,float dt){
float dt0 = dt*(float)N;
for (int i=1; i<=N; i++) {
for (int j=1; j<=N; j++) {
float x = (float)i - dt0 * u[IX(i,j)];
float y = (float)j - dt0 * v[IX(i,j)];
// make sure not to flow out the boundary
if (x < 0.5) x = 0.5;
if (x > N + 0.5) x = N + 0.5;
if (y < 0.5) y = 0.5;
if (y > N + 0.5) y = N + 0.5;
// get the nearest four neighbors
int i0 = (int)x;
// int i1 = i0 + 1;
int j0 = (int)y;
// int j1 = j0 + 1;
// get the four coefficient in bilinear interpolation
/*float s0 = i1 - x;
float s1 = x - i0;
float t0 = j1 - y;
float t1 = y - j0;*/
//float s1 = x - i0;
//float s0 = 1 - s1;
//float t1 = y - j0;
//float t0 = 1 - t1;
//
//// bilinear interpolation
//current[IX(i, j)] = s0 * (t0 * previous[IX(i0, j0)] + t1 * previous[IX(i0, j1)]) +
// s1 * (t0 * previous[IX(i1, j0)] + t1 * previous[IX(i1, j1)]);
float cx = x - i0;
float cy = y - j0;
float v00 = previous[IX(i0,j0)];
float v01 = previous[IX(i0+1,j0)];
float v10 = previous[IX(i0,j0+1)];
float v11 = previous[IX(i0+1,j0+1)];
// multiply 0.99 is to decay the velocity and density
// otherwise the screen will full of fluid and add more as the mouse move
current[IX(i,j)] = 0.99*lerp(lerp(v00,v01,cx),
lerp(v10,v11,cx),
cy);
}
}
setBnd(b,current);
}
/**
* Here we have to solve a possion equation which leads to a sparse linear system for the unknow field
* Gauss-Seidel Relaxation is efficient to solve the equation
* @param u,v: two components of the 2-dimension velocity field
* Laplacian p = (...)/h^2 = Div u* = (...)/2h
* multiply the h^2 to the right side of the equation
*/
void project(float *u, float *v, float *p, float *div) {
int i, j, k;
float h = 1.0/(float)N;
// get the divergence of u*
for (i=1; i<=N; i++) {
for (j=1; j<=N; j++) {
div[IX(i, j)] = 0.5 * h * (u[IX(i+1, j)] - u[IX(i-1, j)] + v[IX(i, j+1)] - v[IX(i, j-1)]);
p[IX(i, j)] = 0;
}
}
// set the divergence and pressure on boundary, should be the same with the nearest fluid cell, so we let b=0
setBnd(0, div);
setBnd(0, p);
// Gauss-Seidel Relaxation, solve the poisson equation to get the pressure term
for (k=0; k<200; k++) {
for (i=1; i<=N; i++) {
for (j=1; j<=N; j++) {
p[IX(i, j)] = (p[IX(i-1, j)] + p[IX(i+1, j)] + p[IX(i, j-1)] + p[IX(i, j+1)] - div[IX(i, j)]) / 4.0;
}
}
setBnd(0, p);
}
// since we got the pressure term frome above
// then replace it in the equation to solve the next time step divergence-free velocity field
// u^{n+1} = u* - grad p
for (i=1; i<=N; i++) {
for (j=1; j<=N; j++) {
u[IX(i, j)] -= 0.5 * (p[IX(i+1, j)] - p[IX(i-1, j)]) / h;
v[IX(i, j)] -= 0.5 * (p[IX(i, j+1)] - p[IX(i, j-1)]) / h;
}
}
// set the boundary condition
setBnd(1, u);
setBnd(2, v);
}
/**
* Update the density during a step of dt
* @param x0: the given force or source
* @param x: the density of the cell during a step of dt update, the effect result of source
* @param u: first component of velocity
* @param v: second component of velocity
*/
void densStep(float* x[], float* x0[], float* u, float* v, float diff, float dt) {
for (int m=0; m<3; m++) {
//diffuse(0,x[m],x0[m],diff,dt);
//SWAP(x0[m],x[m]);
advect(0, x[m], x0[m], u, v, dt);
SWAP(x0[m], x[m]);
}
}
/**
* Update the velocity field during a step of dt
* @param u0, v0: the given velocity field
* @param u, v: the velocity field during a step of dt update
* @param dt: time step interval
* @param visc: viscosity coefficient
*/
void velStep(float *u, float *v, float *u0, float *v0, float visc, float dt) {
//// update the velocity field
//SWAP(u0, u);
//SWAP(v0, v);
//
//diffuse(1, u, u0, visc, dt);
//diffuse(2, v, v0, visc, dt);
//
//// make the velocity field divergence-free for next step
//project(u, v, u0, v0);
memset(u, sizeof(float)*M_SIZE, 0);
memset(v, sizeof(float)*M_SIZE, 0);
// advection for the velocity field itself
advect(1, u, u0, u0, v0, dt);
advect(2, v, v0, u0, v0, dt);
//addSource(u, fx, dt);
//addSource(v, fy, dt);
//memset(fx, sizeof(float)*M_SIZE, 0);
//memset(fy, sizeof(float)*M_SIZE, 0);
// make the velocity field divergence-free for next time step
project(u, v, u0, v0);
// update for next step
//SWAP(u0, u);
//SWAP(v0, v);
memcpy(u0, u, sizeof(float)*M_SIZE);
memcpy(v0, v, sizeof(float)*M_SIZE);
}
/**********************************************************************************************
* *
* *
* Display Part Starts Here *
* *
* *
**********************************************************************************************/
void fluidMainLoop(void) {
velStep(u, v, u_init, v_init, visc, dt);
densStep(dens, dens_init, u_init, v_init, diff, dt);
}
void draw_dens(void) {
// solve fluid
fluidMainLoop();
// draw function
float c[3];
glClear(GL_COLOR_BUFFER_BIT);
for (int y=0; y<=N; y++) {
for (int x=0; x<=N; x++) {
// display color of density
for (int m=0; m<3; m++) {
c[m] = dens_init[m][IX(x,y)]/255.0;
}
if(c[0]==0 && c[1]==0 && c[2]==0) continue; // do not draw black color
glColor3f(c[0], c[1], c[2]);
glRecti(x, N-y, x+1, N-y+1);
}
}
glutSwapBuffers();
glutPostRedisplay();
}
void reshape(int w,int h) {
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, N, 0, N, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
xmult = w/(GLfloat)N;
ymult = h/(GLfloat)N;
}
/**********************************************************************************************
* *
* *
* Interaction Part Starts Here *
* *
* *
**********************************************************************************************/
int mouseButtons;
int mouseOldX;
int mouseOldY;
// detect the state of mouse
void mouse(int button,int state,int x,int y) {
if (state == GLUT_DOWN) {
mouseButtons |= 1<<button;
}
else if (state == GLUT_UP) {
mouseButtons = 0;
}
mouseOldX = x;
mouseOldY = y;
glutPostRedisplay();
}
// decide the action when mouse move
void mouseMove(int x,int y) {
float dx = (float)(x - mouseOldX);
float dy = (float)(y - mouseOldY);
if (mouseButtons == 1) {
float coordx = x/500.0;
float coordy = y/500.0;
int buffer_i = coordx * N;
int buffer_j = coordy * N;
printf("%d,%d\n", buffer_i,buffer_j);
for (int ii = max(buffer_i-3, 1); ii <= min(buffer_i+3, N); ii++) {
for (int jj = max(buffer_j-3,1); jj <= min(buffer_j+3,N); jj++) {
// set the color to the position where mouse button is click down
dens_init[0][IX(ii,jj)] = rand()%256;
dens_init[1][IX(ii,jj)] = rand()%256;
dens_init[2][IX(ii,jj)] = rand()%256;
// add force to the position to the direction where mouse move
u_init[IX(ii,jj)] += dt*0.5*dx;
v_init[IX(ii,jj)] += dt*0.5*dy;
}
}
glutPostRedisplay();
}
else {
memset(fx, sizeof(float)*M_SIZE, 0);
memset(fy, sizeof(float)*M_SIZE, 0);
glutPostRedisplay();
}
mouseOldX = x;
mouseOldY = y;
}
int main(int argc, char* argv[]) {
int i, j;
u = new float[M_SIZE];
v = new float[M_SIZE];
fx = new float[M_SIZE];
fy = new float[M_SIZE];
u_init = new float[M_SIZE];
v_init = new float[M_SIZE];
for (j=0;j<3;j++) {
dens[j] = new float[M_SIZE];
dens_init[j] = new float[M_SIZE];
}
if (dens[0]==NULL || dens[1]==NULL || dens[2]==NULL || dens_init[0]==NULL || dens_init[1]==NULL || dens_init[2]==NULL) {
cout << "Memory Allocation Failure.";
exit(1);
}
for (i=0; i<M_SIZE; i++) {
u[i] = 0.0;
v[i] = 0.0;
u_init[i] = 0.0;
v_init[i] = 0.0;
for (j=0; j<3; j++) {
dens[j][i] = 0.0;
dens_init[j][i] = 0.0;
}
}
// GLUT
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("Fluid Simulation 2D");
glClearColor(0,0,0,0);
glShadeModel(GL_FLAT);
glOrtho(0,N,0,N,-1,1);
glutDisplayFunc(draw_dens);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMotionFunc(mouseMove);
glutMainLoop();
free(u);
free(v);
free(u_init);
free(v_init);
free(dens);
free(dens_init);
}
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// Author: Tatparya Shankar
// Return sum of digits of a number
int getSumOfDigits( int n )
{
int dig;
int sum = 0;
while( n > 0 )
{
dig = n % 10;
sum += dig;
n /= 10;
}
return sum;
}
void identifySmith( int n )
{
int sum;
// Get sum of digits in n
sum = getSumOfDigits( n );
cout << sum << endl;
// Prime factorize n
int factorSum = 0;
int i = 2;
// Prime factorization
while( i < sqrt( n ) )
{
if( n % i == 0 )
{
n /= i;
factorSum += getSumOfDigits( i );
}
else
{
i++;
}
}
if( n > 1 )
{
factorSum += getSumOfDigits( n );
}
// Final test
if( factorSum == sum )
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
}
int main()
{
int n;
cin >> n;
// Check if smiths Number
identifySmith( n );
return 0;
}
|
#ifndef _CS2420_DFS_GRAPH_H
#define _CS2420_DFS_GRAPH_H
#include "graph.h"
#include <algorithm>
namespace cs2420 {
enum class VColor { WHITE, GREY, BLACK };
struct VertexAttr {
VColor color = VColor::WHITE;
int strime = 0;
int ftime = 0;
};
class DepthFirstSearch {
public:
DepthFirstSearch(Graph& g) : g(g), attr(new VertexAttr[g.V()]{}){
for(int v = 0; v < g.V(); v++){
if(attr[v].color == VColor::WHITE){
dfs(v);
}
}
}
std::vector<int> preOrder() { return pre; }
std::vector<int> postOrder() { return post; }
std::vector<int> topologicalOrder() {
if(!g.directed()) throw std::runtime_error("Graph must be directed");
std::vector<int> t = post;
std::reverse(t.begin(), t.end());
return t;
}
~DepthFirstSearch() { delete [] attr; }
private:
Graph& g;
VertexAttr* attr;
std::vector<int> pre, post;
void dfs(int u){
static int time = 0;
attr[u].strime = ++time;
attr[u].color = VColor::GREY;
pre.push_back(u);
for(int v : g.adjList(u)){
if(attr[v].color == VColor::WHITE){
dfs(v);
}
}
attr[u].color = VColor::BLACK;
attr[u].ftime = ++time;
post.push_back(u);
}
};
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
*/
#ifndef LOG_SENDER_H
#define LOG_SENDER_H
class Upload_OpString8;
/** @brief Class for setting up and sending crash logs to Opera
*/
class LogSender : private MessageObject
{
public:
class Listener
{
public:
virtual ~Listener() {}
/** Called when the log sender starts sending a log over HTTP */
virtual void OnSendingStarted(LogSender* sender) = 0;
/** Called when the log sender has succeeded sending a log over HTTP */
virtual void OnSendSucceeded(LogSender* sender) = 0;
/** Called when the log sender has failed sending a log over HTTP.
* @note the log can be resent by calling LogSender::Send again.
*/
virtual void OnSendFailed(LogSender* sender) = 0;
};
/** Constructor
* @param wants_crashpage Whether Opera should display a page with crash information
* after restarting if sending the log succeeds
*/
LogSender(bool wants_crashpage) : m_wants_crashpage(wants_crashpage), m_crash_time(0), m_listener(NULL) {}
~LogSender();
/** @param listener Listener that gets events from this log sender
* @ref LogSender::Listener
*/
void SetListener(Listener* listener) { m_listener = listener; }
/** @param url URL the user was visiting when the crash occured
*/
OP_STATUS SetURL(OpStringC16 url) { return m_url.SetUTF8FromUTF16(url); }
/** @param email Email address at which the user can be contacted for further questions
*/
OP_STATUS SetEmail(OpStringC16 email) { return m_email.SetUTF8FromUTF16(email); }
/** @param comments Comments on this crash from the user
*/
OP_STATUS SetComments(OpStringC16 comments) { return m_comments.SetUTF8FromUTF16(comments); }
/** @param path (absolute) path to the log file to send, or path to a whole folder to zip up and send.
*/
OP_STATUS SetLogFile(OpStringC16 path) { return m_dmp_path.Set(path); }
/** @return the log file or folder used in this log sender
*/
OpStringC GetLogFile() const { return m_dmp_path; }
/** @param crash_time Time at which the crash happened (UTC, unix time format)
*/
void SetCrashTime(time_t crash_time) { m_crash_time = crash_time; }
/** Send the log to Opera
* @return see @ref OP_STATUS.
* @note On error, sending can be retried by calling this function again. It's not necessary to do
* setup again when this happens.
*/
OP_STATUS Send();
private:
URL SetupUploadL();
OP_STATUS ZipLogFile();
void SetFormKeyValueL(Upload_OpString8* element, OpStringC8 key, OpStringC8 value);
void Reset();
void ResetUpload();
// From MessageObject
virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
bool m_wants_crashpage;
OpString8 m_email;
OpString8 m_url;
OpString8 m_comments;
OpString m_dmp_path;
OpString m_zip_path;
time_t m_crash_time;
URL_InUse m_uploading_url;
Listener* m_listener;
};
#endif // LOG_SENDER_H
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define show(x) for(auto i: x){cout << i << " ";}
#define showm(m) for(auto i: m){cout << m.x << " ";}
typedef long long ll;
typedef pair<int, int> P;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
int main()
{
string s;
cin >> s;
int ans = 0;
vector<int> dp(2, 0);
vector<int> old_dp(2, 0);
rep(i, s.size()){
int num = s[i] - '0';
if (i == 0) {old_dp[0] = (10-num)+1; old_dp[1] = num; continue;}
dp[0] = min(old_dp[0] + (10-num)-1, old_dp[1]+(10-num)+1);
dp[1] = min(old_dp[0], old_dp[1]) + num;
old_dp = dp;
}
cout << min(old_dp[0],old_dp[1]) << endl;
}
|
#include "board.h"
#include "resource.h"
#include <string>
using std::string;
using std::to_string;
board::board(logger *l) {
_log = l;
// Allocate 18 regions
for (int i =0; i<=18; i++) {
region *r = new region();
r->id(i);
_regions.push_back(r);
}
_log->debug("regions allocated");
}
void board::dump_board() {
for (auto r: _regions) {
_log->debug("region: " + std::to_string(r->id())
+ " resource: " + resource_name(r->resource_type())
+ " selector: " + std::to_string(r->selector()));
string m = string("neighbors:");
for (auto n: _neighbors[r->id()]) {
m += " " + to_string(n);
}//end for (auto n: _neighbors[])
_log->debug(m);
}//end for (auto r: _regions)
}//end dump_board()
void board::initialize(bool rnd) {
if (rnd) {
initialize_random();
}
else {
initialize_default();
}
_initialize_neighbors();
}
void board::_make_neighbors(int r1, int r2) {
_log->debug(string(__FUNCTION__) + ": " + to_string(r1) + "-" + to_string(r2));
auto m = _neighbors.find(r1);
if (m != _neighbors.end()) {
_log->debug("found r1(" + to_string(r1) + "): searching neighbors");
for (auto& n: _neighbors[r1]) {
if (n == r2) {
_log->debug("found neighbor r2(" + to_string(r2) + "): not adding neighbor");
return;
}
}//end for (auto& n: _neighbors[r1])
_log->debug("did not find r2(" + to_string(r2) + "): adding neighbor");
}
else {
_log->debug("did not find r1(" + to_string(r1) + "): adding first neighbor");
}//end if (m != _neighbors.end())
_neighbors[r1].push_back(r2);
}//end _make_neighbor(int r1, int r2)
int board::_ring_max(int ring) {
if (ring > 1) {
return _ring_max(ring-1) + (ring * 6);
}
return (ring * 6);
}
void board::_initialize_neighbors() {
int ring = 1;
//int rgn=0;
//do ring 1
int ring_max = _ring_max(ring);
for (int i=0; i<ring_max; i++) {
int r_id = i + 1;
// Add region 0
_make_neighbors(r_id, 0);
_make_neighbors(0, r_id);
// Add i-1, i.e., (i+5)%ring_max
int pre = ((i+5) % ring_max) +1;
_make_neighbors(r_id, pre);
_make_neighbors(pre, r_id);
//Add i+1, i.e., (i+1)%ring_max
int post = ((i+1) % ring_max) +1;
_make_neighbors(r_id, post);
_make_neighbors(post, r_id);
// Add neighbors from next ring
// The next radial neighbor is 2*r_id + 6
int nnr = 2*r_id + 6;
_make_neighbors(r_id, nnr);
_make_neighbors(nnr, r_id);
// need to update ring_max for next ring
// Add nnr-1 (nnr > 1)
pre = nnr-1;
_make_neighbors(r_id, pre);
_make_neighbors(pre, r_id);
//Add i+1, i.e., (i+1)%ring_max
//FIXME: doesn't wrap correctly
//Range is 7..18, so let's reset to 0-based counting
int k = nnr-7;
//post = ((k+1) % _ring_max(ring+1)) +7;
post = ((k+1) % ((ring+1)*6)) +7;
_log->debug("nnr=" + to_string(nnr) + " k=" + to_string(k)
+ " post=" + to_string(post));
_make_neighbors(r_id, post);
_make_neighbors(post, r_id);
}//end for (int i=0; i<ring_max; i++)
}
void board::initialize_random() {
//Not implemented
_log->debug(string(__FUNCTION__) + "(): not implemented");
initialize_default();
}
void board::initialize_default() {
_log->debug(string(__FUNCTION__) + "()");
// Set the region type
for (auto r: _regions) {
switch(r->id()) {
case (1): case(9): case(15):
r->resource_type(brick);
break;
case(2): case(12): case(16): case(18):
r->resource_type(wood);
break;
case(3): case(6): case(8):
r->resource_type(ore);
break;
case(4): case(11): case(13): case(17):
r->resource_type(cattle);
break;
case(5): case(7): case(10): case(14):
r->resource_type(wheat);
break;
default:
r->resource_type(none);
r->robber_hideout(true);
}//end switch(r->id())
// Set the resource rate (dice value: 2 - 12)
switch (r->id()) {
case(17):
_fortune[2].push_back(r);
r->selector(2);
break;
case(1): case(15):
_fortune[3].push_back(r);
r->selector(3);
break;
case(4): case(9):
_fortune[4].push_back(r);
r->selector(4);
break;
case(3): case(18):
_fortune[5].push_back(r);
r->selector(5);
break;
case(2): case(16):
_fortune[6].push_back(r);
r->selector(6);
break;
case(0):
//r->selector(0);
break;
case(8): case(14):
_fortune[8].push_back(r);
r->selector(8);
break;
case(6): case(12):
_fortune[9].push_back(r);
r->selector(9);
break;
case(7): case(13):
_fortune[10].push_back(r);
r->selector(10);
break;
case(5): case(10):
_fortune[11].push_back(r);
r->selector(11);
break;
case(11):
_fortune[12].push_back(r);
r->selector(12);
break;
}//end switch(r->id())
}//end for (auto r: _regions)
// Set the neighbors
//
// Locate initial towns, 1 per player
}
bool board::build_town() {
return true;
}
bool board::build_road() {
return true;
}
void board::collect_resources(int k) {
_log->debug(string(__FUNCTION__) + "()");
for (auto r: _fortune[k]) {
_log->debug("collecting resource (" + resource_name(r->resource_type()) + ") from region "
+ std::to_string(r->id()));
// does the region have any towns
// add points to any players
}
}//collect_resources()
|
//
// Created by 송지원 on 2020/06/03.
//
//#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, x, t;
cin >> n >> x;
while (n--) {
cin >> t;
if (t<x) cout << t << ' ';
}
}
|
#include "PimplTest.h"
#include "Pimpl.h"
using namespace common::util::tests;
class TestClass
{
public:
TestClass()
{
}
explicit TestClass(int value1, const QString& value2 = QString())
: impl_(value1, value2)
{
}
int getValue() const
{
return impl_->value1_;
}
QString getValueString() const
{
return impl_->value2_;
}
QString concatenate() const
{
return impl_->concatenate();
}
private:
struct Impl
{
int value1_;
QString value2_;
Impl()
: value1_(50)
{
}
Impl(int value)
: value1_(value)
{
}
Impl(int value1, const QString& value2)
: value1_(value1),
value2_(value2)
{
}
QString concatenate() const
{
return QString("%1-%2").arg(value1_).arg(value2_);
}
};
common::util::Pimpl<Impl> impl_;
};
void PimplTest::pimplConstructionTest()
{
TestClass instance;
QCOMPARE(50, instance.getValue());
TestClass instance1(5);
QCOMPARE(5, instance1.getValue());
TestClass instance2(3, "TestString");
QCOMPARE(instance2.getValue(), 3);
QCOMPARE(instance2.getValueString(), QString("TestString"));
QCOMPARE(instance2.concatenate(), QString("3-TestString"));
}
void PimplTest::pimplCopyTest()
{
TestClass test(20, "TestCopy");
TestClass testConstruct = test;
QCOMPARE(testConstruct.getValue(), 20);
QCOMPARE(testConstruct.getValueString(), QString("TestCopy"));
QCOMPARE(testConstruct.concatenate(), QString("20-TestCopy"));
TestClass testAssign(50, "Initial");
testAssign = test;
QCOMPARE(testAssign.getValue(), 20);
QCOMPARE(testAssign.getValueString(), QString("TestCopy"));
QCOMPARE(testAssign.concatenate(), QString("20-TestCopy"));
}
DECLARE_TEST(PimplTest)
|
#ifndef PERSONAJE_H
#define PERSONAJE_H
#include <iostream>
using namespace std;
class Personaje
{
public:
int vida;
int ataque;
void logica();
void dibujar();
Personaje();
virtual ~Personaje();
protected:
private:
};
#endif // PERSONAJE_H
|
#ifndef A_HPP
#define A_HPP
#include <iostream>
class A {
public:
A(char d);
A(const A&);
virtual ~A();
A& operator=(const A&);
void show();
private:
char data;
};
#endif
|
/* XMRig
* Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* 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 "base/kernel/config/BaseConfig.h"
#include "3rdparty/rapidjson/document.h"
#include "base/io/json/Json.h"
#include "base/io/log/Log.h"
#include "base/io/log/Tags.h"
#include "base/kernel/interfaces/IJsonReader.h"
#include "base/net/dns/Dns.h"
#include "version.h"
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <uv.h>
#ifdef XMRIG_FEATURE_TLS
# include <openssl/opensslv.h>
#endif
#ifdef XMRIG_FEATURE_HWLOC
# include "backend/cpu/Cpu.h"
#endif
namespace xmrig {
#ifdef XMRIG_FEATURE_MO_BENCHMARK
const char *BaseConfig::kAlgoPerf = "algo-perf";
#endif
const char *BaseConfig::kApi = "api";
const char *BaseConfig::kApiId = "id";
const char *BaseConfig::kApiWorkerId = "worker-id";
const char *BaseConfig::kAutosave = "autosave";
const char *BaseConfig::kBackground = "background";
#ifdef XMRIG_FEATURE_MO_BENCHMARK
const char *BaseConfig::kBenchAlgoTime = "bench-algo-time";
#endif
const char *BaseConfig::kColors = "colors";
const char *BaseConfig::kDryRun = "dry-run";
const char *BaseConfig::kHttp = "http";
const char *BaseConfig::kLogFile = "log-file";
const char *BaseConfig::kPrintTime = "print-time";
#ifdef XMRIG_FEATURE_MO_BENCHMARK
const char *BaseConfig::kRebenchAlgo = "rebench-algo";
#endif
const char *BaseConfig::kSyslog = "syslog";
const char *BaseConfig::kTitle = "title";
const char *BaseConfig::kUserAgent = "user-agent";
const char *BaseConfig::kVerbose = "verbose";
const char *BaseConfig::kWatch = "watch";
#ifdef XMRIG_FEATURE_TLS
const char *BaseConfig::kTls = "tls";
#endif
} // namespace xmrig
bool xmrig::BaseConfig::read(const IJsonReader &reader, const char *fileName)
{
m_fileName = fileName;
if (reader.isEmpty()) {
return false;
}
m_autoSave = reader.getBool(kAutosave, m_autoSave);
m_background = reader.getBool(kBackground, m_background);
m_dryRun = reader.getBool(kDryRun, m_dryRun);
# ifdef XMRIG_FEATURE_MO_BENCHMARK
m_rebenchAlgo = reader.getBool(kRebenchAlgo, m_rebenchAlgo);
# endif
m_syslog = reader.getBool(kSyslog, m_syslog);
m_watch = reader.getBool(kWatch, m_watch);
m_logFile = reader.getString(kLogFile);
m_userAgent = reader.getString(kUserAgent);
m_printTime = std::min(reader.getUint(kPrintTime, m_printTime), 3600U);
m_title = reader.getValue(kTitle);
# ifdef XMRIG_FEATURE_TLS
m_tls = reader.getValue(kTls);
# endif
Log::setColors(reader.getBool(kColors, Log::isColors()));
# ifdef XMRIG_FEATURE_MO_BENCHMARK
m_benchAlgoTime = reader.getInt(kBenchAlgoTime, m_benchAlgoTime);
# endif
setVerbose(reader.getValue(kVerbose));
const auto &api = reader.getObject(kApi);
if (api.IsObject()) {
m_apiId = Json::getString(api, kApiId);
m_apiWorkerId = Json::getString(api, kApiWorkerId);
}
m_http.load(reader.getObject(kHttp));
m_pools.load(reader);
Dns::set(reader.getObject(DnsConfig::kField));
return m_pools.active() > 0;
}
bool xmrig::BaseConfig::save()
{
if (m_fileName.isNull()) {
return false;
}
rapidjson::Document doc;
getJSON(doc);
if (Json::save(m_fileName, doc)) {
LOG_NOTICE("%s " WHITE_BOLD("configuration saved to: \"%s\""), Tags::config(), m_fileName.data());
return true;
}
return false;
}
void xmrig::BaseConfig::printVersions()
{
char buf[256] = { 0 };
# if defined(__clang__)
snprintf(buf, sizeof buf, "clang/%d.%d.%d", __clang_major__, __clang_minor__, __clang_patchlevel__);
# elif defined(__GNUC__)
snprintf(buf, sizeof buf, "gcc/%d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
# elif defined(_MSC_VER)
snprintf(buf, sizeof buf, "MSVC/%d", MSVC_VERSION);
# endif
Log::print(GREEN_BOLD(" * ") WHITE_BOLD("%-13s") CYAN_BOLD("%s/%s") WHITE_BOLD(" %s"), "ABOUT", APP_NAME, APP_VERSION, buf);
std::string libs;
# if defined(XMRIG_FEATURE_TLS)
{
# if defined(LIBRESSL_VERSION_TEXT)
snprintf(buf, sizeof buf, "LibreSSL/%s ", LIBRESSL_VERSION_TEXT + 9);
libs += buf;
# elif defined(OPENSSL_VERSION_TEXT)
constexpr const char *v = &OPENSSL_VERSION_TEXT[8];
snprintf(buf, sizeof buf, "OpenSSL/%.*s ", static_cast<int>(strchr(v, ' ') - v), v);
libs += buf;
# endif
}
# endif
# if defined(XMRIG_FEATURE_HWLOC)
libs += Cpu::info()->backend();
# endif
Log::print(GREEN_BOLD(" * ") WHITE_BOLD("%-13slibuv/%s %s"), "LIBS", uv_version_string(), libs.c_str());
}
void xmrig::BaseConfig::setVerbose(const rapidjson::Value &value)
{
if (value.IsBool()) {
Log::setVerbose(value.GetBool() ? 1 : 0);
}
else if (value.IsUint()) {
Log::setVerbose(value.GetUint());
}
}
|
#pragma once
#include <QThread>
#include <list>
#include <mutex>
class XDecode;
struct AVPacket;
class XDecodeThread :
public QThread
{
public:
XDecodeThread();
virtual ~XDecodeThread();
public:
//数据传入队列处理
virtual void Push(AVPacket* pkt);
//Seek位置的时候需要将当前队列的数据清空
virtual void Clear();
//清理资源,关闭线程
virtual void Close();
//去除一帧数据,并出栈,如果没有返回NULL
virtual AVPacket* Pop();
protected:
XDecode* decode;
//最大队列
int nMaxList = 100;
bool isExit = false;
std::list<AVPacket*> packList;
std::mutex dmux;
};
|
#ifndef POISSON_RGB_H
#define POISSON_RGB_H
#include "filter.h"
#include "poissonSolverRGB.h"
class PoissonRGB : public Filter {
public:
PoissonRGB();
FILTER_API void apply();
FILTER_API void connected();
FILTER_API void disconnected();
FILTER_API void reloadShaders();
FILTER_API inline unsigned int nbInputs () const {return 3;}
FILTER_API inline unsigned int nbOutputs() const {return 1;}
FILTER_API inline QString inputName(int i) const {
switch(i) {
case 0: return "Gx (Gx(r),Gx(b),Gx(b))";
case 1: return "Gy (Gy(r),Gy(b),Gy(b))";
case 2: return "Dirichlet - if(v>=0) (D(r),D(b),D(b))";
default: return "";
}
}
// we wont use our FBOs here
FILTER_API virtual void initFBO() {}
FILTER_API virtual void cleanFBO() {}
FILTER_API std::ostream &save(std::ostream &stream);
FILTER_API std::istream &load(std::istream &stream);
private:
PoissonSolverRGB _p;
bool _initialized;
};
extern "C" {
FILTER_API Filter *createFilter();
FILTER_API std::string filterName();
FILTER_API std::string filterDescription();
}
#endif // POISSON_RGB_H
|
#ifndef M01_ENUMS_AND_DEFS_HPP
#define M01_ENUMS_AND_DEFS_HPP
// Frontend connection initial buffer size.
#define M01_FRONTEND_CONN_INITIAL_BUF_SIZE 128
// Custom [M01 app] object type enumeration.
// Every user object assigned to uv's [handle->data]
// must have fist field [M01ObjType user_obj_type].
typedef enum {
M01OBJ_FRONTEND_CONN_CONTEXT = 1,
} M01ObjType;
#endif // M01_ENUMS_AND_DEFS_HPP
|
#include <iostream>
using namespace std;
struct Rect { //Create a structure
int length;
int width;
Rect(int length, int width) {
this -> length = length;
this -> width = width;
}
int area() {
return length * width;
}
};
void print(int * arr, int size) { //print the array
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
void calculateAreas(Rect * array, int * arrAreas, int size) { //calculate the area of rectangle
for (int i = 0; i < size; ++i) {
arrAreas[i] = array[i].area();
}
}
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++) {
L[i] = arr[l + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[m + 1 + j];
}
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r) {
if (l < r) {
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main() {
const int size = 5;
Rect array[size] {{9, 10}, {5,5}, {7,1}, {7,100}, {1,11}};
int arrAreas[size];
calculateAreas(array, arrAreas, size);
cout << "Unsorted array: \n";
print(arrAreas, size);
cout << "\n";
mergeSort(arrAreas, 0, size - 1);
cout << "Sorted array: \n";
print(arrAreas, size);
return 0;
}
|
// Created on: 2009-04-06
// Created by: Sergey ZARITCHNY
// Copyright (c) 2009-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TDataXtd_Plane_HeaderFile
#define _TDataXtd_Plane_HeaderFile
#include <TDataStd_GenericEmpty.hxx>
class TDF_Label;
class gp_Pln;
class TDataXtd_Plane;
DEFINE_STANDARD_HANDLE(TDataXtd_Plane, TDataStd_GenericEmpty)
//! The basis to define a plane attribute.
//! Warning: Use TDataXtd_Geometry attribute to retrieve the
//! gp_Pln of the Plane attribute
class TDataXtd_Plane : public TDataStd_GenericEmpty
{
public:
//! class methods
//! =============
//!
//! Returns the GUID for plane attributes.
Standard_EXPORT static const Standard_GUID& GetID();
//! Finds or creates the plane attribute defined by
//! the label label.
//! Warning
//! If you are creating the attribute with this syntax, a
//! planar face should already be associated with label.
Standard_EXPORT static Handle(TDataXtd_Plane) Set (const TDF_Label& label);
//! Finds, or creates, a Plane attribute and sets <P> as
//! generated the associated NamedShape.
//! Plane methods
//! =============
Standard_EXPORT static Handle(TDataXtd_Plane) Set (const TDF_Label& label, const gp_Pln& P);
Standard_EXPORT TDataXtd_Plane();
Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE;
Standard_EXPORT virtual Standard_OStream& Dump (Standard_OStream& anOS) const Standard_OVERRIDE;
DEFINE_DERIVED_ATTRIBUTE(TDataXtd_Plane, TDataStd_GenericEmpty)
protected:
private:
};
#endif // _TDataXtd_Plane_HeaderFile
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int test, amount, total=0;
string word;
scanf("%d",&test);
getchar();
while(test--)
{
cin>>word;
if(word=="donate")
{
scanf("%d",&amount);
total+=amount;
}
else
printf("%d\n",total);
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) Opera Software ASA 2006 - 2011
*
* Web server implementation
*/
#include "core/pch.h"
#ifdef WEBSERVER_SUPPORT
#include "modules/viewers/viewers.h"
#include "modules/webserver/src/resources/webserver_file.h"
#include "modules/webserver/webserver_request.h"
#include "modules/pi/system/OpLowLevelFile.h"
#include "modules/webserver/webserver-api.h"
#include "modules/webserver/webserver_resources.h"
#include "modules/util/tempbuf.h"
#include "modules/util/opfile/opfile.h"
#include "modules/webserver/src/webservercore/webserver_connection.h"
#include "modules/util/gen_str.h"
#include "modules/stdlib/util/opdate.h"
#include "modules/pi/OpLocale.h"
#include "modules/util/datefun.h"
#include "modules/formats/uri_escape.h"
#include "modules/formats/hdsplit.h"
#include "modules/formats/argsplit.h"
#include "modules/url/protocols/http1.h"
WebserverResourceDescriptor_Static::WebserverResourceDescriptor_Static(BOOL isFile)
: m_isFile(isFile)
{
}
/*static*/
WebserverResourceDescriptor_Static* WebserverResourceDescriptor_Static::Make(const OpStringC &realPath, const OpStringC &virtualPath)
{
OP_ASSERT(realPath.CStr() != NULL);
OP_ASSERT(!realPath.IsEmpty());
if (realPath.IsEmpty())
{
return NULL;
}
BOOL is_file = FALSE;
if (realPath[realPath.Length() - 1] != '/')
{
OpFile file;
BOOL found;
if (OpStatus::IsMemoryError(file.Construct(realPath.CStr(), OPFILE_ABSOLUTE_FOLDER)) || OpStatus::IsMemoryError(file.Exists(found)))
{
return NULL;
}
else if (found == TRUE)
{
OpFileInfo::Mode mode;
if (OpStatus::IsMemoryError(file.GetMode(mode)))
{
return NULL;
}
else
{
is_file = (mode == OpFileInfo::FILE ? TRUE : FALSE);
}
}
}
WebserverResourceDescriptor_Static *staticResource = OP_NEW(WebserverResourceDescriptor_Static, (is_file));
if (staticResource &&
OpStatus::IsError(staticResource->m_resourceRealPath.Construct(realPath)) ||
OpStatus::IsError(staticResource->m_resourceVirtualPath.ConstructFromURL(virtualPath))
)
{
OP_DELETE(staticResource);
staticResource = NULL;
}
return staticResource;
}
const uni_char* WebserverResourceDescriptor_Static::GetResourceRealPath() const
{
return m_resourceRealPath.GetPathAndFileNamePointer();
}
WebServerResourceType WebserverResourceDescriptor_Static::GetResourceType() const
{
return WEB_RESOURCE_TYPE_STATIC;
}
WebResource_File::WebResource_File(WebServerConnection *service, OpFile *file, WebserverRequest *requestObject)
: WebResource(service, requestObject)
, m_file(file)
{
m_bytes_served=0;
}
/* virtual */
WebResource_File::~WebResource_File()
{
if (m_file != NULL)
{
m_file->Close();
}
OP_DELETE(m_file);
}
/* FIXME : use CharsetDetector to detect the charset in the file */
/* static */ OP_STATUS
WebResource_File::Make(WebResource *&webresource, WebServerConnection *service, const OpStringC16 &subServerRequestString, WebserverRequest *requestObject, WebserverResourceDescriptor_Static *resource, WebServerFailure *result)
{
webresource = NULL;
WebServerMethod method = requestObject->GetHttpMethod();
const uni_char *request_resource_name = subServerRequestString.CStr();
OpString escaped;
escaped.Set(request_resource_name);
UriUnescape::ReplaceChars(escaped.CStr(), UriUnescape::LocalfileUrlUtf8 | UriUnescape::All);
request_resource_name = escaped.CStr();
while (*request_resource_name == '/')
request_resource_name++;
const uni_char *resource_descriptor_name = resource->GetResourceVirtualPath();
while (*resource_descriptor_name == '/')
resource_descriptor_name++;
unsigned int descriptor_name_length = uni_strlen(resource_descriptor_name);
if (descriptor_name_length != 0)
{
/* if resource_descriptor_name is not "" check that request_resource_name == resource_descriptor_name */
//const uni_char *end_of_request_resource_name = uni_strpbrk(request_resource_name, UNI_L("/?#"));
// Check for a perfect match
const uni_char *end_of_request_resource_name = uni_strpbrk(subServerRequestString.CStr(), UNI_L("/?#"));
unsigned int request_resource_name_length = end_of_request_resource_name ? end_of_request_resource_name - subServerRequestString.CStr() : uni_strlen(request_resource_name);
if (request_resource_name_length != descriptor_name_length || uni_strncmp(request_resource_name, resource_descriptor_name, descriptor_name_length) != 0)
{
// Check for a partial perfect match
end_of_request_resource_name = uni_strpbrk(subServerRequestString.CStr(), UNI_L("?#"));
request_resource_name_length = end_of_request_resource_name ? end_of_request_resource_name - subServerRequestString.CStr() : uni_strlen(request_resource_name);
if (request_resource_name_length != descriptor_name_length || uni_strncmp(request_resource_name, resource_descriptor_name, descriptor_name_length) != 0)
{
// Not perfect match with a directory: check for approx match
if( request_resource_name_length < descriptor_name_length+1 ||
request_resource_name[descriptor_name_length] != '/' ||
uni_strncmp(request_resource_name, resource_descriptor_name, descriptor_name_length) != 0)
{
*result = WEB_FAIL_FILE_NOT_AVAILABLE;
return OpStatus::OK;
}
}
}
}
const uni_char *resource_subpath = request_resource_name + uni_strlen(resource_descriptor_name);
const uni_char *end_of_filename = uni_strpbrk(resource_subpath, UNI_L("?#"));
unsigned int resource_subpath_length = end_of_filename ? end_of_filename - resource_subpath : uni_strlen(resource_subpath);
if (resource->IsFile() && resource_subpath_length > 0)
{
*result = WEB_FAIL_FILE_NOT_AVAILABLE;
return OpStatus::OK;
}
if (method != WEB_METH_GET && method != WEB_METH_POST && method != WEB_METH_HEAD)
{
*result = WEB_FAIL_METHOD_NOT_SUPPORTED;
return OpStatus::OK;
}
OpString resourceName;
RETURN_IF_ERROR(resourceName.Set(resource_subpath, resource_subpath_length));
OpString path;
RETURN_IF_ERROR(WebserverFileName::SecurePathConcat(path, resource->GetResourceRealPath(), TRUE));
if (resource->IsFile() == FALSE)
{
RETURN_IF_ERROR(WebserverFileName::SecurePathConcat(path, resourceName, TRUE));
}
if (path.Find("../") != KNotFound || path.Find("/..") != KNotFound) /* In case any of the security checks have failed. */
{
OP_ASSERT(!"Path resolving has failed!. Contact the Core owner of the webserver module.");
*result = WEB_FAIL_FILE_NOT_AVAILABLE;
return OpStatus::OK;
}
unsigned int length = path.Length();
uni_char *pathstr = path.CStr();
if (length > 0 && pathstr[length - 1] == '/')
{
RETURN_IF_ERROR(path.Append("index.html"));
}
#ifdef SYS_CAP_NETWORK_FILESYSTEM_BACKSLASH_PATH
pathstr = path.CStr();
for (unsigned int i = 0; i < length ; i++)
{
if (pathstr[i] == '/')
pathstr[i] = '\\';
}
#endif //SYS_CAP_NETWORK_FILESYSTEM_BACKSLASH_PATH
OpFile *file;
if ((file = OP_NEW(OpFile, ())) == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
OpAutoPtr<OpFile> file_anchor(file);
BOOL found = FALSE;
OP_STATUS status;
RETURN_IF_MEMORY_ERROR(status = file->Construct(path.CStr(), OPFILE_ABSOLUTE_FOLDER));
RETURN_IF_MEMORY_ERROR(file->Exists(found));
if (found == FALSE)
{
*result = WEB_FAIL_FILE_NOT_AVAILABLE;
return OpStatus::OK;
}
RETURN_IF_ERROR(file->Open(OPFILE_READ));
OpFileInfo::Mode mode;
RETURN_IF_ERROR(file->GetMode(mode));
if (mode == OpFileInfo::DIRECTORY)
{
*result = WEB_FAIL_REDIRECT_TO_DIRECTORY;
RETURN_IF_ERROR(file->Close());
return OpStatus::OK;
}
*result = WEB_FAIL_GENERIC;
WebResource_File *fileResource = NULL;
fileResource = OP_NEW(WebResource_File, (service, file_anchor.release(), requestObject));
if (fileResource == NULL)
{
OP_DELETE(file);
return OpStatus::ERR_NO_MEMORY;
}
OpAutoPtr<WebResource_File> fileResource_anchor(fileResource);
/*We find the mime type*/
OpString charExtension;
OpString8 content_type;
RETURN_IF_ERROR(charExtension.Set(StrFileExt(path.CStr())));
if (charExtension.IsEmpty() == FALSE)
{
// Automatically set the Content-Type only if it is not been already set
//if(!service->IsResponseHeaderPresent("Content-Type"))
RETURN_IF_ERROR(service->GetResponseHeader("Content-Type", content_type));
if(!content_type.Compare(DEFAULT_CONTENT_TYPE) || content_type.Length()==0)
{
Viewer* viewer = NULL;
if (OpStatus::IsError(g_viewers->FindViewerByFilename(path.CStr(), viewer)))
{
viewer = NULL;
}
else if (viewer)
{
RETURN_IF_ERROR(fileResource->AddResponseHeader(UNI_L("Content-Type"), viewer->GetContentTypeString()));
}
}
}
/*End of finding mime type*/
OpFileLength filelength;
RETURN_IF_ERROR(file->GetFileLength(filelength));
/* Range header */
HeaderList *headerlist = requestObject->GetClientHeaderList();
HeaderEntry *rangeHeader = NULL;
if (headerlist && (rangeHeader = headerlist->GetHeader("Range")) != NULL )
{
ParameterList *RangeParameters = NULL;
RETURN_IF_LEAVE(RangeParameters = rangeHeader->GetParametersL((PARAM_SEP_COMMA | PARAM_STRIP_ARG_QUOTES), KeywordIndex_HTTP_General_Parameters));
Parameters *rangeBytesParameter = NULL;
if (RangeParameters && RangeParameters->ParameterExists(HTTP_General_Tag_Bytes, PARAMETER_ASSIGNED_ONLY))
{
rangeBytesParameter = RangeParameters->GetParameterByID(HTTP_General_Tag_Bytes, PARAMETER_ANY);
if (rangeBytesParameter)
{
HTTPRange range;
RETURN_IF_ERROR(range.Parse(rangeBytesParameter->Value(), TRUE, filelength));
if (range.GetStart() != FILE_LENGTH_NONE && range.GetEnd()!=FILE_LENGTH_NONE && range.GetStart() < filelength && range.GetEnd() >= range.GetStart())
{
RETURN_IF_MEMORY_ERROR(status = fileResource->m_file->SetFilePos(range.GetStart()));
if (OpStatus::IsError(status) == FALSE)
{
OpString byteString;
OpString8 temp_val;
RETURN_IF_ERROR(byteString.Set(UNI_L("bytes ")));
RETURN_IF_ERROR(g_op_system_info->OpFileLengthToString(range.GetStart(), &temp_val));
RETURN_IF_ERROR(byteString.Append(temp_val));
RETURN_IF_ERROR(byteString.Append(UNI_L("-")));
RETURN_IF_ERROR(g_op_system_info->OpFileLengthToString(range.GetEnd(), &temp_val));
RETURN_IF_ERROR(byteString.Append(temp_val));
RETURN_IF_ERROR(byteString.Append(UNI_L("/")));
RETURN_IF_ERROR(g_op_system_info->OpFileLengthToString(filelength, &temp_val));
RETURN_IF_ERROR(byteString.Append(temp_val));
RETURN_IF_ERROR(fileResource->AddResponseHeader(UNI_L("Content-Range"), byteString.CStr()));
RETURN_IF_ERROR(fileResource->SetResponseCode(206));
fileResource->m_totalResourceLength = range.GetEnd() - range.GetStart()+1;
filelength = fileResource->m_totalResourceLength;
}
else
{
fileResource->m_file->SetFilePos(0);
}
}
}
}
}
else
{
fileResource->m_totalResourceLength = filelength;
}
RETURN_IF_ERROR(fileResource->AddResponseHeader(UNI_L("Accept-Ranges"), UNI_L("bytes")));
/* end of range header */
/* file length header */
OpString val;
OpString8 temp_val;
RETURN_IF_ERROR(g_op_system_info->OpFileLengthToString(filelength, &temp_val));
RETURN_IF_ERROR(val.Set(temp_val));
RETURN_IF_ERROR(fileResource->AddResponseHeader(UNI_L("Content-Length"), val.CStr()));
/* end of file length header */
RETURN_IF_ERROR(service->StartServingData());
webresource = fileResource_anchor.release();
*result = WEB_FAIL_NO_FAILURE;
return OpStatus::OK;
}
/* virtual */ OP_STATUS
WebResource_File::GetLastModified(time_t &date)
{
/*We find the last time files was modified*/
if (!m_file)
{
return OpStatus::ERR;
}
RETURN_IF_ERROR(m_file->GetLastModified(date));
return OpStatus::OK;
}
/* virtual */ OP_STATUS
WebResource_File::GetETag(OpString8 &etag)
{
OpString temp;
time_t last_modified;
if (!m_file)
{
return OpStatus::ERR;
}
OpString8 temp_val;
OpFileLength len;
m_file->GetFileLength(len);
RETURN_IF_ERROR(g_op_system_info->OpFileLengthToString(len, &temp_val));
temp.Set("\"");
temp.Append(temp_val);
uni_char dateString[70]; /* ARRAY OK 2009-11-18 jonnyr */
GetLastModified(last_modified);
if (last_modified)
{
struct tm* file_time = op_gmtime(&last_modified);
FMakeDate(*file_time,"\247D\247M\247Y\247h\247m\247s\"", dateString, 68);
temp.Append(dateString);
}
etag.Set(temp.CStr());
return OpStatus::OK;
}
/* virtual */ OP_STATUS
WebResource_File::HandleIncommingData(const char *incommingData, UINT32 length, BOOL lastData)
{
return OpStatus::OK;
}
/* virtual */ OP_BOOLEAN
WebResource_File::FillBuffer(char *buffer, unsigned int bufferSize, unsigned int &FilledDataSize)
{
OP_ASSERT( m_file != NULL );
OpFileLength nbytes;
OpFileLength bytes_to_read=bufferSize - FilledDataSize;
if(bytes_to_read>m_totalResourceLength-m_bytes_served)
bytes_to_read=m_totalResourceLength-m_bytes_served;
RETURN_IF_ERROR(m_file->Read(buffer + FilledDataSize, bytes_to_read, &nbytes));
FilledDataSize += (unsigned long)nbytes;
m_bytes_served+=nbytes;
return ( m_bytes_served<m_totalResourceLength && m_file->Eof() == FALSE) ? OpBoolean::IS_TRUE : OpBoolean::IS_FALSE;
}
#endif // WEBSERVER_SUPPORT
|
#include "messages.h"
RectObject::RectObject(const QString &text, qreal x, qreal y, qreal width, qreal height, QBrush brush, QGraphicsItem *parent)
: QGraphicsObject(parent)
, m_text(text)
, m_rect(x, y, width, height)
, m_pen(brush.color().lighter(), 3.0)
, m_brush(brush)
{
setFlag(QGraphicsItem::ItemClipsToShape, true);
}
QRectF RectObject::boundingRect() const
{
// here we only want the size of the children and not the size of the children of the children...
qreal halfpw = m_pen.widthF() / 2;
QRectF rect = m_rect;
if (halfpw > 0.0)
rect.adjust(-halfpw, -halfpw, halfpw, halfpw);
return rect;
}
void RectObject::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setPen(m_pen);
painter->setBrush(m_brush);
painter->drawRect(m_rect);
painter->setPen(Qt::black);
QFont f;
f.setPixelSize(m_rect.height());
painter->setFont(f);
painter->drawText(m_rect, Qt::AlignCenter, m_text);
}
ViewObject::ViewObject(QGraphicsObject *parent)
: QGraphicsObject(parent)
{
}
QRectF ViewObject::boundingRect() const
{
QRectF rect;
foreach (QGraphicsItem *item, childItems())
rect |= item->boundingRect().translated(item->pos());
return rect;
}
void ViewObject::paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*)
{
}
ListObject::ListObject(const QSizeF &size, bool useTouch)
{
qDebug() << "Size: " << size.height() << " " << size.width();
m_size = size;
setFlag(QGraphicsItem::ItemClipsChildrenToShape, true);
// grab gesture via Touch or Mouse events
QScroller::grabGesture(this, useTouch ? QScroller::TouchGesture : QScroller::LeftMouseButtonGesture);
// this needs to be QGraphicsOBJECT - otherwise gesture recognition
// will not work for the parent of the viewport (in this case the
// list)
m_viewport = new ViewObject(this);
}
QGraphicsObject * ListObject::viewport() const
{
return m_viewport;
}
bool ListObject::event(QEvent *e)
{
switch (e->type()) {
case QEvent::ScrollPrepare: {
QScrollPrepareEvent *se = static_cast<QScrollPrepareEvent *>(e);
se->setViewportSize(m_size);
QRectF br = m_viewport->boundingRect();
se->setContentPosRange(QRectF(0, 0,
qMax(qreal(0), br.width() - m_size.width()),
qMax(qreal(0), br.height() - m_size.height())));
se->setContentPos(-m_viewport->pos());
se->accept();
return true;
}
case QEvent::Scroll: {
QScrollEvent *se = static_cast<QScrollEvent *>(e);
m_viewport->setPos(-se->contentPos() - se->overshootDistance());
return true;
}
default:
break;
}
return QGraphicsObject::event(e);
}
bool ListObject::sceneEvent(QEvent *e)
{
switch (e->type()) {
case QEvent::TouchBegin: {
// We need to return true for the TouchBegin here in the
// top-most graphics object - otherwise gestures in our parent
// objects will NOT work at all (the accept() flag is already
// set due to our setAcceptTouchEvents(true) call in the c'tor
return true;
}
case QEvent::GraphicsSceneMousePress: {
// We need to return true for the MousePress here in the
// top-most graphics object - otherwise gestures in our parent
// objects will NOT work at all (the accept() flag is already
// set to true by Qt)
return true;
}
default:
break;
}
return QGraphicsObject::sceneEvent(e);
}
QRectF ListObject::boundingRect() const
{
return QRectF(0, 0, m_size.width() + 3, m_size.height());
}
void ListObject::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setPen(QPen(QColor(100, 100, 100), 3.0));
painter->drawRect(QRectF(1.5, 1.5, m_size.width() - 3, m_size.height() - 3));
}
QSizeF ListObject::getSize() const
{
return m_size;
}
MessagesArea::MessagesArea(bool useTouch)
{
m_scene = new QGraphicsScene();
layout = new QVBoxLayout(this);
msgNum = 0;
mainList = new ListObject(QSizeF(400, 900), useTouch);
mainList->setObjectName(QLatin1String("MainList"));
m_scene->addItem(mainList);
/*for (int i=0; i<10; i++) {
ListObject *childList = new ListObject(QSizeF(mainList->getSize().width()/3, mainList->getSize().height()), useTouch);
childList->setObjectName(QString("ChildList %1").arg(i));
addMessage(childList);
childList->setParentItem(mainList->viewport());
childList->setPos(i*mainList->getSize().width()/3, 0);
}*/
mainList->viewport()->setPos(0, 0);
m_view = new QGraphicsView(m_scene);
layout->addWidget(m_view);
this->setLayout(layout);
m_scene->setSceneRect(0, 0, m_view->viewport()->width(), m_view->viewport()->height());
}
void MessagesArea::addMessage(QString &m)
{
qreal h = 30;
++msgNum;
QColor color = QColor(115, 115, 115);
qDebug() << "Adding with text: " << m;
QGraphicsItem *rect = new RectObject(m, 0, 0, mainList->getSize().width() - 6, h - 3, QBrush(color), mainList->viewport());
qDebug() << "MSG SIZE: " << rect->boundingRect().width() << rect->boundingRect().height();
rect->setPos(10, msgNum*h);
qDebug() << "MSG NEW: " << rect->boundingRect().x() << rect->boundingRect().y();
mainList->viewport()->setPos(0, 0);
}
void MessagesArea::resizeEvent(QResizeEvent *e)
{
// resize the scene according to our own size to prevent scrolling
qDebug() << "RESIZE: " << m_view->viewport()->width() << " " << m_view->viewport()->height();
m_scene->setSceneRect(0, 0, m_view->viewport()->width(), m_view->viewport()->height());
QWidget::resizeEvent(e);
}
|
#ifndef STRAT_GAME_MAP_HH
#define STRAT_GAME_MAP_HH
#include "util/Fixed.hh"
#include <entityx/entityx.h>
#include <glm/glm.hpp>
#include <cstring>
#include <cassert>
#include <vector>
struct GridPoint {
glm::ivec2 pos;
size_t height;
mutable bool dirty;
GridPoint()
: height(0),
dirty(false) {
}
};
// The map holds all the information about the terrain
// that is needed for the game logic simulation.
struct Map {
typedef glm::uvec2 Pos;
Map(size_t sizeX, size_t sizeY);
size_t getSizeX() const { return sizeX; }
size_t getSizeY() const { return sizeY; }
Pos getSize() const {
return Pos(sizeX, sizeY);
}
size_t getMaxHeight() const { return maxHeight; }
bool isPoint(const Pos &p) const {
return p.x < sizeX && p.y < sizeY;
}
bool isPoint(size_t x, size_t y) const {
return isPoint(Map::Pos(x, y));
}
GridPoint &point(size_t x, size_t y) {
assert(x < sizeX);
assert(y < sizeY);
return points[y * sizeX + x];
}
const GridPoint &point(size_t x, size_t y) const {
assert(x < sizeX);
assert(y < sizeY);
return points[y * sizeX + x];
}
GridPoint &point(const Pos &p) {
return point(p.x, p.y);
}
const GridPoint &point(const Pos &p) const {
return point(p.x, p.y);
}
static Map generate(size_t sizeX, size_t sizeY,
size_t heightLimit, size_t seed);
template<typename F>
void forNeighbors(const Pos &p, F f) {
assert(isPoint(p));
if (p.y > 0) f(point(p.x, p.y-1));
if (p.y < sizeY - 1) f(point(p.x, p.y+1));
if (p.x > 0) f(point(p.x-1, p.y));
if (p.x < sizeX - 1) f(point(p.x+1, p.y));
if (p.x > 0 && p.y > 0) f(point(p.x-1, p.y-1));
if (p.x > 0 && p.y < sizeY-1) f(point(p.x-1, p.y+1));
if (p.x < sizeX-1 && p.y > 0) f(point(p.x+1, p.y-1));
if (p.x < sizeX-1 && p.y < sizeY-1) f(point(p.x+1, p.y+1));
}
template<typename F>
void forRectangle(const Pos &p, const Pos &s, F f) {
assert(isPoint(p));
assert(isPoint(p + s));
for (size_t x = p.x; x <= p.x + s.x; x++)
for (size_t y = p.y; y <= p.y + s.y; y++)
f(point(x, y));
}
template<typename F>
void forRectangle(const Pos &p, const Pos &s, F f) const {
assert(isPoint(p));
assert(isPoint(p + s));
for (size_t x = p.x; x <= p.x + s.x; x++)
for (size_t y = p.y; y <= p.y + s.y; y++)
f(point(x, y));
}
void tick(fixed tickLengthS);
private:
size_t sizeX;
size_t sizeY;
size_t maxHeight;
std::vector<GridPoint> points; // 2d array
};
#endif
|
#include<iostream>
#include<cstdlib>
using namespace std;
struct node{
int data;
struct node* next;
};
struct node *head;
void insert(int data)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data;
newnode->next=NULL;
struct node *temp=head;
if(head==NULL)
{
head=newnode;
return;
}
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
}
void display(){
struct node* temp=head;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
int main()
{
int ele;
cin>>ele;
while(1)
{
if(ele<0){
break;
}
insert(ele);
}
cout<<"Before inserting the value:"<<endl;
display();
return 0;
}
|
#pragma once
#using <mscorlib.dll>
#include "llvm/IR/GlobalValue.h"
#include "Constant.h"
namespace LLVM
{
ref class PointerType;
ref class Module;
ref class Value;
public ref class GlobalValue
: public Constant
{
public:
enum class LinkageTypes
{
ExternalLinkage = 0,
AvailableExternallyLinkage,
LinkOnceAnyLinkage,
LinkOnceODRLinkage,
LinkOnceODRAutoHideLinkage,
WeakAnyLinkage,
WeakODRLinkage,
AppendingLinkage,
InternalLinkage,
PrivateLinkage,
LinkerPrivateLinkage,
LinkerPrivateWeakLinkage,
DLLImportLinkage,
DLLExportLinkage,
ExternalWeakLinkage,
CommonLinkage
};
enum class VisibilityTypes
{
DefaultVisibility = 0,
HiddenVisibility,
ProtectedVisibility
};
internal:
llvm::GlobalValue *base;
protected:
GlobalValue(llvm::GlobalValue *base);
internal:
static inline GlobalValue ^_wrap(llvm::GlobalValue *base);
public:
!GlobalValue();
virtual ~GlobalValue();
//
unsigned getAlignment();
void setAlignment(unsigned Align);
bool hasUnnamedAddr();
void setUnnamedAddr(bool Val);
GlobalValue::VisibilityTypes getVisibility();
bool hasDefaultVisibility();
bool hasHiddenVisibility();
bool hasProtectedVisibility();
void setVisibility(VisibilityTypes V);
bool hasSection();
// const std::string &getSection();
void setSection(System::String ^S);
// bool use_empty_except_constants();
inline PointerType ^getType();
static GlobalValue::LinkageTypes getLinkOnceLinkage(bool ODR);
static GlobalValue::LinkageTypes getWeakLinkage(bool ODR);
static bool isExternalLinkage(LinkageTypes Linkage);
static bool isAvailableExternallyLinkage(LinkageTypes Linkage);
static bool isLinkOnceLinkage(LinkageTypes Linkage);
static bool isLinkOnceODRAutoHideLinkage(LinkageTypes Linkage);
static bool isWeakLinkage(LinkageTypes Linkage);
static bool isAppendingLinkage(LinkageTypes Linkage);
static bool isInternalLinkage(LinkageTypes Linkage);
static bool isPrivateLinkage(LinkageTypes Linkage);
static bool isLinkerPrivateLinkage(LinkageTypes Linkage);
static bool isLinkerPrivateWeakLinkage(LinkageTypes Linkage);
static bool isLocalLinkage(LinkageTypes Linkage);
static bool isDLLImportLinkage(LinkageTypes Linkage);
static bool isDLLExportLinkage(LinkageTypes Linkage);
static bool isExternalWeakLinkage(LinkageTypes Linkage);
static bool isCommonLinkage(LinkageTypes Linkage);
static bool isDiscardableIfUnused(LinkageTypes Linkage);
static bool mayBeOverridden(LinkageTypes Linkage);
static bool isWeakForLinker(LinkageTypes Linkage);
bool hasExternalLinkage();
bool hasAvailableExternallyLinkage();
bool hasLinkOnceLinkage();
bool hasLinkOnceODRAutoHideLinkage();
bool hasWeakLinkage();
bool hasAppendingLinkage();
bool hasInternalLinkage();
bool hasPrivateLinkage();
bool hasLinkerPrivateLinkage();
bool hasLinkerPrivateWeakLinkage();
bool hasLocalLinkage();
bool hasDLLImportLinkage();
bool hasDLLExportLinkage();
bool hasExternalWeakLinkage();
bool hasCommonLinkage();
void setLinkage(LinkageTypes LT);
GlobalValue::LinkageTypes getLinkage();
bool isDiscardableIfUnused();
bool mayBeOverridden();
bool isWeakForLinker();
virtual void copyAttributesFrom(GlobalValue ^Src);
bool isMaterializable();
bool isDematerializable();
bool Materialize();
void Dematerialize();
virtual void destroyConstant() override;
bool isDeclaration();
virtual void removeFromParent();
virtual void eraseFromParent();
inline Module ^getParent();
// inline const Module *getParent();
static inline bool classof(Value ^V);
};
}
|
#include <fstream>
#include "cp18_1_opt.h"
int main() {
ofstream in_pix("input_pixels_regression_result_cp18_1_opt.txt");
ofstream fout("regression_result_cp18_1_opt.txt");
HWStream<hw_uint<16> > raw_update_0_read;
HWStream<hw_uint<16> > cp18_1_update_0_write;
// Loading input data
// cmap : { raw_update_0[root = 0, raw_0, raw_1] -> raw_oc[0, 0] : -3 <= raw_0 <= 1924 and -3 <= raw_1 <= 1084 }
// read map: { raw_oc[0, 0] -> raw_update_0[root = 0, raw_0, raw_1] : -3 <= raw_0 <= 1924 and -3 <= raw_1 <= 1084 }
// rng : { raw_update_0[root = 0, raw_0, raw_1] : -3 <= raw_0 <= 1924 and -3 <= raw_1 <= 1084 }
for (int i = 0; i < 2097664; i++) {
hw_uint<16> in_val;
set_at<0*16, 16, 16>(in_val, 1*i + 0);
in_pix << in_val << endl;
raw_update_0_read.write(in_val);
}
cp18_1_opt(raw_update_0_read, cp18_1_update_0_write);
for (int i = 0; i < 2073600; i++) {
hw_uint<16> actual = cp18_1_update_0_write.read();
auto actual_lane_0 = actual.extract<0*16, 15>();
fout << actual_lane_0 << endl;
}
in_pix.close();
fout.close();
return 0;
}
|
//: C15:PureVirtualDefinitions.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Definicje czysto wirtualnych funkcji
// klasy podstawowej
#include <iostream>
using namespace std;
class Pet {
public:
virtual void speak() const = 0;
virtual void eat() const = 0;
// Czysto wirtualna funkcja nie moze byc funkcja inline:
//! virtual void sleep() const = 0 {}
};
// W porzadku, funkcja nie jest zdefiniowana jako funkcja inline
void Pet::eat() const {
cout << "Pet::eat()" << endl;
}
void Pet::speak() const {
cout << "Pet::speak()" << endl;
}
class Dog : public Pet {
public:
// Wykorzystanie wspolnego kodu klasy Pet:
void speak() const { Pet::speak(); }
void eat() const { Pet::eat(); }
};
int main() {
Dog simba; // Pies Richarda
simba.speak();
simba.eat();
} ///:~
|
// Created on: 1999-11-26
// Created by: Andrey BETENEV
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepBasic_ProductConceptContext_HeaderFile
#define _StepBasic_ProductConceptContext_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepBasic_ApplicationContextElement.hxx>
class TCollection_HAsciiString;
class StepBasic_ApplicationContext;
class StepBasic_ProductConceptContext;
DEFINE_STANDARD_HANDLE(StepBasic_ProductConceptContext, StepBasic_ApplicationContextElement)
//! Representation of STEP entity ProductConceptContext
class StepBasic_ProductConceptContext : public StepBasic_ApplicationContextElement
{
public:
//! Empty constructor
Standard_EXPORT StepBasic_ProductConceptContext();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aApplicationContextElement_Name, const Handle(StepBasic_ApplicationContext)& aApplicationContextElement_FrameOfReference, const Handle(TCollection_HAsciiString)& aMarketSegmentType);
//! Returns field MarketSegmentType
Standard_EXPORT Handle(TCollection_HAsciiString) MarketSegmentType() const;
//! Set field MarketSegmentType
Standard_EXPORT void SetMarketSegmentType (const Handle(TCollection_HAsciiString)& MarketSegmentType);
DEFINE_STANDARD_RTTIEXT(StepBasic_ProductConceptContext,StepBasic_ApplicationContextElement)
protected:
private:
Handle(TCollection_HAsciiString) theMarketSegmentType;
};
#endif // _StepBasic_ProductConceptContext_HeaderFile
|
#include "TriangleMesh.h"
#include <iostream>
#include "ObjLoader.h"
using namespace std;
using namespace CGLA;
using namespace GLGraphics;
namespace Mesh {
vector<GLuint> TriangleMesh::convert_sub_meshes_to_triangle_indices(DrawCall &drawCall, bool removeDegenerate){
vector<GLuint> indices = drawCall.indices;
vector<GLuint> trianleIndices;
if (drawCall.renderMode == GL_TRIANGLES){
return indices;
} else if (drawCall.renderMode != GL_TRIANGLE_STRIP){
cerr << "Unsupported rendermode for recompute_normals. Only GL_TRIANGLES and GL_TRIANGLE_STRIP supported." << endl;
return trianleIndices;
}
int even = 1;
trianleIndices.push_back(indices[0]);
trianleIndices.push_back(indices[1]);
trianleIndices.push_back(indices[2]);
for (int i=3;i<indices.size();i++){
if (removeDegenerate){
if (indices[i-1] == indices[i] ||
indices[i-2] == indices[i] ||
indices[i-1] == indices[i-2]){
continue;
}
}
if ((i % 2) == even) {
trianleIndices.push_back(indices[i-1]);
trianleIndices.push_back(indices[i-2]);
trianleIndices.push_back(indices[i]);
} else {
trianleIndices.push_back(indices[i-2]);
trianleIndices.push_back(indices[i-1]);
trianleIndices.push_back(indices[i]);
}
}
return trianleIndices;
}
void TriangleMesh::recompute_normals(const char* positionName, const char *normalName){
vector<Vec3f> normals;
for (int i=0;i<vertexCount;i++) {
normals.push_back(Vec3f(0.0, 0.0, 0.0));
}
vector<Vec3f> vertex;
DataVector vertexRaw = vertexAttributes[positionName];
for (int i=0;i< vertexCount;i++){
DataUnion data = vertexRaw.vector[i];
vertex.push_back(Vec3f(data.vec[0], data.vec[1], data.vec[2]));
}
if (drawCalls.size()==0 && debug){
cout << "warn - no draw calls "<< endl;
}
for (std::vector<DrawCall>::iterator iter = drawCalls.begin(); iter != drawCalls.end(); iter++){
DrawCall &drawCall = *iter;
vector<GLuint> triangles = convert_sub_meshes_to_triangle_indices(drawCall);
size_t triangleCount = triangles.size()/3;
for (int a = 0; a < triangleCount; a++) {
GLuint i1 = triangles[a * 3];
GLuint i2 = triangles[a * 3 + 1];
GLuint i3 = triangles[a * 3 + 2];
Vec3f v1 = vertex[i1];
Vec3f v2 = vertex[i2];
Vec3f v3 = vertex[i3];
Vec3f v1v2 = normalize(v2 - v1);
Vec3f v1v3 = normalize(v3 - v1);
Vec3f v2v3 = normalize(v3 - v2);
Vec3f normal = normalize(cross(v1v2, v1v3));
float weight1 = acos(max(-1.0f, min(1.0f, dot(v1v2, v1v3))));
float weight2 = M_PI - acos(max(-1.0f, min(1.0f, dot(v1v2, v2v3))));
normals[i1] += normal * weight1;
normals[i2] += normal * weight2;
normals[i3] += normal * (M_PI - weight1 - weight2);
}
}
for (int i=0;i<vertexCount;i++) {
normals[i] = normalize(normals[i]);
}
add(normalName, normals);
}
bool TriangleMesh::load(const string &filename, bool do_recompute_normals){
vector<Vec3f> outPositions;
vector<Vec3f> outNormal;
vector<Vec2f> outUv;
vector<vector<GLuint> > outIndices;
vector<Material> outMaterials;
bool loaded = ObjLoader::load_object(filename.c_str(),
&outPositions,
&outIndices,
&outMaterials,
&outNormal,
&outUv,
1.0f);
if (!loaded){
return false;
}
add("vertex", outPositions);
if (outNormal.size()>0){
add("normal", outNormal);
}
if (outUv.size()>0){
add("texcoord", outUv);
}
for (unsigned int i=0;i<outIndices.size();i++){
add_draw_call(outIndices[i], outMaterials[i], GL_TRIANGLES);
}
if (do_recompute_normals){
recompute_normals();
}
build_vertex_array_object();
return true;
}
void TriangleMesh::check_vertex_size(size_t vertexAttributeSize) {
if (vertexCount != 0 && vertexCount != vertexAttributeSize && debug){
cout << "invalid vertex attribute size" << endl;
}
vertexCount = static_cast<int>(vertexAttributeSize);
}
void TriangleMesh::add(const string &name, vector<int> &vertexAttributesI){
check_vertex_size(vertexAttributesI.size());
DataVector dataVector = {GL_INT, sizeof(int), 1, std::vector<DataUnion>()};
DataUnion d;
for (unsigned int i=0;i<vertexAttributesI.size();i++){
d.i[0] = vertexAttributesI[i];
dataVector.vector.push_back(d);
}
vertexAttributes[name] = dataVector;
}
void TriangleMesh::add(const string &name, vector<float> &vertexAttributesF){
check_vertex_size(vertexAttributesF.size());
DataVector dataVector = {GL_FLOAT, sizeof(float), 1, std::vector<DataUnion>()};
DataUnion d;
for (unsigned int i=0;i<vertexAttributesF.size();i++){
d.vec[0] = vertexAttributesF[i];
dataVector.vector.push_back(d);
}
vertexAttributes[name] = dataVector;
}
void TriangleMesh::add(const string &name, vector<Vec2f> &vertexAttributesV2){
check_vertex_size(vertexAttributesV2.size());
DataVector dataVector = {GL_FLOAT, sizeof(float)*2, 2, std::vector<DataUnion>()};
DataUnion d;
for (unsigned int i=0;i<vertexAttributesV2.size();i++){
d.vec[0] = vertexAttributesV2[i][0];
d.vec[1] = vertexAttributesV2[i][1];
dataVector.vector.push_back(d);
}
vertexAttributes[name] = dataVector;
}
void TriangleMesh::add(const string &name, vector<Vec3f> &vertexAttributesV3){
check_vertex_size(vertexAttributesV3.size());
DataVector dataVector = {GL_FLOAT, sizeof(float)*3, 3, std::vector<DataUnion>()};
DataUnion d;
for (unsigned int i=0;i<vertexAttributesV3.size();i++){
d.vec[0] = vertexAttributesV3[i][0];
d.vec[1] = vertexAttributesV3[i][1];
d.vec[2] = vertexAttributesV3[i][2];
dataVector.vector.push_back(d);
}
vertexAttributes[name] = dataVector;
}
void TriangleMesh::add(const string &name, vector<Vec4f> &vertexAttributesV4){
check_vertex_size(vertexAttributesV4.size());
DataVector dataVector = {GL_FLOAT, sizeof(float)*4, 4, std::vector<DataUnion>()};
DataUnion d;
for (unsigned int i=0;i<vertexAttributesV4.size();i++){
d.vec[0] = vertexAttributesV4[i][0];
d.vec[1] = vertexAttributesV4[i][1];
d.vec[2] = vertexAttributesV4[i][2];
d.vec[3] = vertexAttributesV4[i][3];
dataVector.vector.push_back(d);
}
vertexAttributes[name] = dataVector;
}
void TriangleMesh::add_draw_call(vector<GLuint> &indices, Material &material, GLenum renderMode){
int offset = 0;
if (drawCalls.size()>0){
offset = drawCalls[drawCalls.size()-1].offset + drawCalls[drawCalls.size()-1].count * sizeof(GLuint);
}
DrawCall c = {
indices,
material,
renderMode,
(int)indices.size(),
offset
};
drawCalls.push_back(c);
}
void copy_to_interleaved_data(DataUnion& data, vector<unsigned char> &interleavedData, int bytes){
assert(bytes<=16);
for (int i=0;i<bytes;i++){
interleavedData.push_back(data.raw[i]);
}
}
void TriangleMesh::map_data_to_shader_vertex_attributes(GLGraphics::ShaderProgram *shader){
// map data to shader vertex attributes
for (unsigned int i=0;i<names.size();i++){
GLint location;
if (shader != NULL){
location = shader->get_attrib_location(names[i].c_str());
} else {
location = ShaderProgramDraw::get_generic_attrib_location(names[i].c_str());
}
if (location != -1){
glEnableVertexAttribArray(location);
glVertexAttribPointer(location, componentSize[i], componentType[i], GL_FALSE, stride, (const GLvoid *)offset[i]);
} else if (debug){
cout << "Cannot find vertex attribute location "<<names[i].c_str() << " in shader" << endl;
}
}
}
void TriangleMesh::build_vertex_array_object(GLGraphics::ShaderProgram *shader){
// create interleaved data
vector<unsigned char> interleavedData;
vector<int> sizeInBytes;
offset.clear();
componentType.clear();
componentSize.clear(); // 1 for float, 2 for Vec2f, etc,
names.clear();
stride = 0;
// do the actual interleaving of the data
for (int i=0;i<vertexCount;i++){
for (std::map<std::string, DataVector>::iterator it = vertexAttributes.begin();it != vertexAttributes.end();it++){
int numberOfComponents = it->second.components;
int size = it->second.size;
copy_to_interleaved_data(it->second.vector[i], interleavedData, size);
if (i==0){
offset.push_back(stride);
stride += size;
sizeInBytes.push_back(size);
names.push_back(it->first);
componentType.push_back(it->second.glType);
componentSize.push_back(numberOfComponents);
}
}
}
#ifndef QT_OPENGL_ES_2
glGenVertexArrays(1, &vertexArrayObject);
glBindVertexArray(vertexArrayObject);
#endif
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
// upload to vertex buffer
glBufferData(GL_ARRAY_BUFFER, stride * vertexCount, &(interleavedData[0]), GL_STATIC_DRAW);
#ifndef QT_OPENGL_ES_2
map_data_to_shader_vertex_attributes(shader);
#endif
// concatenate all indices
std::vector<GLuint> elementArrayBuffer;
for (std::vector<DrawCall>::iterator iter = drawCalls.begin();iter != drawCalls.end(); iter++){
elementArrayBuffer.insert(elementArrayBuffer.end(),iter->indices.begin(), iter->indices.end() );
}
glGenBuffers(1, &vertexElementArrayBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexElementArrayBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*elementArrayBuffer.size(), &(elementArrayBuffer[0]), GL_STATIC_DRAW);
for (std::vector<DrawCall>::iterator iter = drawCalls.begin();iter != drawCalls.end(); iter++){
iter->material.tex_map.gl_init();
}
initialized = true;
#ifndef QT_OPENGL_ES_2
glBindVertexArray(0);
#endif
}
void TriangleMesh::render(ShaderProgramDraw &shader){
if (!initialized){
if (debug){
cout << "TriangleMesh::render(): Vertex array not built" << endl;
}
return;
}
#ifndef QT_OPENGL_ES_2
glBindVertexArray(vertexArrayObject);
#else
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexElementArrayBuffer);
map_data_to_shader_vertex_attributes(&shader);
#endif
for (std::vector<DrawCall>::iterator iter = drawCalls.begin();iter != drawCalls.end(); iter++){
shader.set_material(iter->material.diffuse, iter->material.specular, iter->material.shininess);
shader.use_texture(GL_TEXTURE_2D, "tex", iter->material.tex_map.get_id(), 0);
glDrawElements(iter->renderMode, iter->count, GL_UNSIGNED_INT, reinterpret_cast<GLvoid*>( iter->offset));
}
}
void TriangleMesh::renderDirect(GLGraphics::ShaderProgram &){
if (!initialized){
if (debug){
cout << "TriangleMesh::render(): Vertex array not built" << endl;
}
return;
}
#ifndef QT_OPENGL_ES_2
glBindVertexArray(vertexArrayObject);
#else
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexElementArrayBuffer);
map_data_to_shader_vertex_attributes(&shader);
#endif
for (std::vector<DrawCall>::iterator iter = drawCalls.begin();iter != drawCalls.end(); iter++){
glDrawElements(iter->renderMode, iter->count, GL_UNSIGNED_INT, reinterpret_cast<GLvoid*>( iter->offset));
}
}
}
|
#include <iostream>
#include <iomanip>
int main()
{
const int tArreglo = 11;
int n[tArreglo] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "Distribucion Calificaciones" << std::endl;
for (int i = 0; i < tArreglo; i++)
{
if (i == 0)
std::cout << "0-9";
else if (i == 10)
std::cout << " 100: ";
else
std::cout << i * 10 << "-" << (i * 10) + 9 << ": ";
for (int estrellas = 0; estrellas < n[i]; estrellas++)
std::cout << '*';
std::cout<<std::endl;
}
return 0;
}
|
#include "utils.hpp"
#include "activity_ptts.hpp"
#include "actor_ptts.hpp"
#include "rank_ptts.hpp"
#include "lottery_ptts.hpp"
#include "item_ptts.hpp"
#include "quest_ptts.hpp"
#include "recharge_ptts.hpp"
#include "shop_ptts.hpp"
#include "utils/time_utils.hpp"
#include "mail_ptts.hpp"
#include "origin_ptts.hpp"
namespace nora {
namespace config {
activity_login_days_ptts& activity_login_days_ptts_instance() {
static activity_login_days_ptts inst;
return inst;
}
void activity_login_days_ptts_set_funcs() {
activity_login_days_ptts_instance().check_func_ = [] (const auto& ptt) {
if (!check_events(ptt.events())) {
CONFIG_ELOG << ptt.day() << " check events failed";
}
};
activity_login_days_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!verify_events(ptt.events())) {
CONFIG_ELOG << ptt.day() << " verify events failed";
}
};
}
activity_online_time_ptts& activity_online_time_ptts_instance() {
static activity_online_time_ptts inst;
return inst;
}
void activity_online_time_ptts_set_funcs() {
activity_online_time_ptts_instance().check_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.rewards()) {
if (!check_events(i.events())) {
CONFIG_ELOG << ptt.day() << " check reward events failed";
}
}
};
activity_online_time_ptts_instance().modify_func_ = [] (auto& ptt) {
uint32_t minutes = 0;
for (auto& i : *ptt.mutable_rewards()) {
minutes += i.minutes();
i.set_minutes(minutes);
}
};
activity_online_time_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.rewards()) {
if (!verify_events(i.events())) {
CONFIG_ELOG << ptt.day() << " verify reward events failed";
}
}
};
}
activity_seven_days_ptts& activity_seven_days_ptts_instance() {
static activity_seven_days_ptts inst;
return inst;
}
void activity_seven_days_ptts_set_funcs() {
activity_seven_days_ptts_instance().check_func_ = [] (const auto& ptt) {
if (ptt.fuli_size() != 7) {
CONFIG_ELOG << ptt.begin_day() << " need 7 fuli, got " << ptt.fuli_size();
}
if (ptt.quests_size() != 7) {
CONFIG_ELOG << ptt.begin_day() << " need 7 quests, got " << ptt.quests_size();
}
if (ptt.goods_size() != 7) {
CONFIG_ELOG << ptt.begin_day() << " need 7 goods, got " << ptt.goods_size();
}
};
activity_seven_days_ptts_instance().modify_func_ = [] (auto& ptt) {
modify_events_by_conditions(ptt.reward().conditions(), *ptt.mutable_reward()->mutable_male_events());
modify_events_by_conditions(ptt.reward().conditions(), *ptt.mutable_reward()->mutable_female_events());
};
activity_seven_days_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (auto i = 0; i < ptt.goods_size(); ++i) {
const auto& good = ptt.goods(i);
if (!PTTS_HAS(shop, good.shop())) {
CONFIG_ELOG << ptt.begin_day() << " shop not exist " << good.shop();
}
auto& shop_ptt = PTTS_GET(shop, good.shop());
auto found = false;
for (auto j = 0; j < good.shop_goods_size(); ++j) {
auto shop_good = good.shop_goods(j);
for (auto& k : *shop_ptt.mutable_goods()) {
if (k.id() == shop_good) {
k.set__activity_seven_days_begin_day(ptt.begin_day());
k.set__activity_seven_days_day(i);
found = true;
break;
}
}
if (!found) {
CONFIG_ELOG << ptt.begin_day() << " shop good not exist " << good.shop() << " " << shop_good;
}
}
}
for (const auto& i : ptt.fuli()) {
for (auto j : i.quests()) {
if (!PTTS_HAS(quest, j)) {
CONFIG_ELOG << ptt.begin_day() << " fuli quest not exist " << j;
continue;
}
auto& quest_ptt = PTTS_GET(quest, j);
quest_ptt.set__activity_seven_days_fuli_quest(true);
}
}
for (const auto& i : ptt.quests()) {
for (auto j : i.quests()) {
if (!PTTS_HAS(quest, j)) {
CONFIG_ELOG << ptt.begin_day() << " quest not exist " << j;
continue;
}
auto& quest_ptt = PTTS_GET(quest, j);
quest_ptt.set__activity_seven_days_quest(true);
}
}
};
}
activity_everyday_libao_ptts& activity_everyday_libao_ptts_instance() {
static activity_everyday_libao_ptts inst;
return inst;
}
void activity_everyday_libao_ptts_set_funcs() {
activity_everyday_libao_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(recharge, ptt.recharge())) {
CONFIG_ELOG << ptt.id() << " verify everyday libao invalid recharge id " << ptt.recharge();
return;
}
auto& recharge_ptt = PTTS_GET(recharge, ptt.recharge());
recharge_ptt.set__activity_everyday_libao(ptt.id());
};
}
activity_qiandao_ptts& activity_qiandao_ptts_instance() {
static activity_qiandao_ptts inst;
return inst;
}
void activity_qiandao_ptts_set_funcs() {
activity_qiandao_ptts_instance().check_func_ = [] (const auto& ptt) {
set<int> big_month { 1, 3, 5, 7, 8, 10, 12 };
set<int> little_month { 4, 6, 9, 11 };
if (big_month.count(ptt.month()) > 0) {
if (ptt.rewards_size() != 31) {
CONFIG_ELOG << ptt.month() << " rewards size error, need 31, got " << ptt.rewards_size();
}
} else if (little_month.count(ptt.month()) > 0) {
if (ptt.rewards_size() != 30) {
CONFIG_ELOG << ptt.month() << " rewards size error, need 30, got " << ptt.rewards_size();
}
} else {
if (ptt.month() == 2) {
if (ptt.rewards_size() != 29) {
CONFIG_ELOG << ptt.month() << " rewards size error, need 29, got " << ptt.rewards_size();
}
} else {
CONFIG_ELOG << ptt.month() << " error month";
}
}
for (const auto& i : ptt.rewards()) {
if (!check_condevents(i.qiandao_events())) {
CONFIG_ELOG << ptt.month() << " check qiandao events failed";
}
if (!check_conditions(i.buqian_conditions())) {
CONFIG_ELOG << ptt.month() << " check buqian conditions failed";
}
if (!check_events(i.leiqian_events())) {
CONFIG_ELOG << ptt.month() << " check leiji events failed";
}
}
};
activity_qiandao_ptts_instance().modify_func_ = [] (auto& ptt) {
for (auto& i : *ptt.mutable_rewards()) {
auto *events = i.mutable__buqian_events();
modify_events_by_conditions(i.buqian_conditions(), *events);
}
};
activity_qiandao_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.rewards()) {
if (!verify_condevents(i.qiandao_events())) {
CONFIG_ELOG << ptt.month() << " verify qiandao events failed";
}
if (!verify_conditions(i.buqian_conditions())) {
CONFIG_ELOG << ptt.month() << " verify buqian conditions failed";
}
if (!verify_events(i.leiqian_events())) {
CONFIG_ELOG << ptt.month() << " verify leiji events failed";
}
}
};
}
activity_chaozhi_libao_ptts& activity_chaozhi_libao_ptts_instance() {
static activity_chaozhi_libao_ptts inst;
return inst;
}
void activity_chaozhi_libao_ptts_set_funcs() {
activity_chaozhi_libao_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (auto i : ptt.resource_recharges()) {
if (!PTTS_HAS(recharge, i)) {
CONFIG_ELOG << ptt.id() << " resource_recharges not exist " << i;
}
auto& recharge_ptt = PTTS_GET(recharge, i);
recharge_ptt.set__activity_chaozhi_resource_libao(ptt.id());
}
for (auto i : ptt.huanzhuang_recharges()) {
if (!PTTS_HAS(recharge, i)) {
CONFIG_ELOG << ptt.id() << " fashion_recharges not exist " << i;
}
auto& recharge_ptt = PTTS_GET(recharge, i);
recharge_ptt.set__activity_chaozhi_huanzhuang_libao(ptt.id());
}
};
}
activity_first_recharge_ptts& activity_first_recharge_ptts_instance() {
static activity_first_recharge_ptts inst;
return inst;
}
void activity_first_recharge_ptts_set_funcs() {
}
activity_emperor_qianzhuang_ptts& activity_emperor_qianzhuang_ptts_instance() {
static activity_emperor_qianzhuang_ptts inst;
return inst;
}
void activity_emperor_qianzhuang_ptts_set_funcs() {
}
activity_emperor_qianzhuang_logic_ptts& activity_emperor_qianzhuang_logic_ptts_instance() {
static activity_emperor_qianzhuang_logic_ptts inst;
return inst;
}
void activity_emperor_qianzhuang_logic_ptts_set_funcs() {
}
activity_vip_qianzhuang_ptts& activity_vip_qianzhuang_ptts_instance() {
static activity_vip_qianzhuang_ptts inst;
return inst;
}
void activity_vip_qianzhuang_ptts_set_funcs() {
}
activity_vip_qianzhuang_logic_ptts& activity_vip_qianzhuang_logic_ptts_instance() {
static activity_vip_qianzhuang_logic_ptts inst;
return inst;
}
void activity_vip_qianzhuang_logic_ptts_set_funcs() {
}
activity_fund_ptts& activity_fund_ptts_instance() {
static activity_fund_ptts inst;
return inst;
}
void activity_fund_ptts_set_funcs() {
}
activity_limit_libao_ptts& activity_limit_libao_ptts_instance() {
static activity_limit_libao_ptts inst;
return inst;
}
void activity_limit_libao_ptts_set_funcs() {
activity_limit_libao_ptts_instance().check_func_ = [] (const auto& ptt) {
if (!check_conditions(ptt.conditions())) {
CONFIG_ELOG << ptt.id() << " check limit libao conditions failed";
}
};
activity_limit_libao_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(recharge, ptt.recharge())) {
CONFIG_ELOG << ptt.id() << " verify limit libao invalid recharge id " << ptt.recharge();
return;
}
auto& recharge_ptt = PTTS_GET(recharge, ptt.recharge());
recharge_ptt.set__activity_limit_libao(ptt.id());
};
}
activity_festival_ptts& activity_festival_ptts_instance() {
static activity_festival_ptts inst;
return inst;
}
void activity_festival_ptts_set_funcs() {
activity_festival_ptts_instance().check_func_ = [] (const auto& ptt) {
if (ptt.exchange_size() > 0) {
for (const auto& i : ptt.exchange()) {
if (!check_conditions(i.conditions())) {
CONFIG_ELOG << ptt.id() << " check festival commons conditions failed";
}
}
}
};
activity_festival_ptts_instance().modify_func_ = [] (auto& ptt) {
if (ptt.exchange_size() > 0) {
for (auto& i : *ptt.mutable_exchange()) {
modify_events_by_conditions(i.conditions(), *i.mutable_events());
}
}
};
activity_festival_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(shop, ptt.shop())) {
CONFIG_ELOG << ptt.id() << " no such shop " << ptt.shop();
} else {
auto& shop_ptt = PTTS_GET(shop, ptt.shop());
shop_ptt.set__activity_festival(ptt.id());
}
for (auto i : ptt.recharge()) {
if (!PTTS_HAS(quest, i)) {
CONFIG_ELOG << ptt.id() << " no such quest " << i;
} else {
auto& quest_ptt = PTTS_GET(quest, i);
quest_ptt.set__activity_festival_recharge_quest(true);
}
}
for (auto i : ptt.fuli()) {
if (!PTTS_HAS(quest, i)) {
CONFIG_ELOG << ptt.id() << " no such quest " << i;
} else {
auto& quest_ptt = PTTS_GET(quest, i);
quest_ptt.set__activity_festival_fuli_quest(true);
}
}
};
}
activity_seventh_day_rank_award_ptts& activity_seventh_day_rank_award_ptts_instance() {
static activity_seventh_day_rank_award_ptts inst;
return inst;
}
void activity_seventh_day_rank_award_ptts_set_funcs() {
activity_seventh_day_rank_award_ptts_instance().check_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.rank_awards()) {
if (!check_events(i.award_events())) {
CONFIG_ELOG << pd::rank_type_Name(ptt.rank_type()) << " check award_events failed";
}
}
if (!check_events(ptt.comfort_award())) {
CONFIG_ELOG << pd::rank_type_Name(ptt.rank_type()) << " check comfort_award failed";
}
};
activity_seventh_day_rank_award_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(mail, ptt.mail_id())) {
CONFIG_ELOG << pd::rank_type_Name(ptt.rank_type()) << " mail table not exist mail_id " << ptt.mail_id();
}
if (!PTTS_HAS(origin, ptt.origin_pttid())) {
CONFIG_ELOG << pd::rank_type_Name(ptt.rank_type()) << " origin table not exist origin_pttid " << ptt.origin_pttid();
}
};
}
activity_prize_wheel_ptts& activity_prize_wheel_ptts_instance() {
static activity_prize_wheel_ptts inst;
return inst;
}
void activity_prize_wheel_ptts_set_funcs() {
activity_prize_wheel_ptts_instance().check_func_ = [] (const auto& ptt) {
if (!check_events(ptt.start_events())) {
CONFIG_ELOG << ptt.id() << " check start events failed";
}
if (!check_events(ptt.finish_events())) {
CONFIG_ELOG << ptt.id() << " check finish events failed";
}
for (const auto& i : ptt.prize_wheels()) {
if (!check_conditions(i.conditions())) {
CONFIG_ELOG << ptt.id() << " check conditions failed";
}
if (!check_events(i.events())) {
CONFIG_ELOG << ptt.id() << " check events failed";
}
}
};
activity_prize_wheel_ptts_instance().modify_func_ = [] (auto& ptt) {
for (auto& i : *ptt.mutable_prize_wheels()) {
modify_events_by_conditions(i.conditions(), *i.mutable_events());
}
};
activity_prize_wheel_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!verify_events(ptt.start_events())) {
CONFIG_ELOG << ptt.id() << " verify start events failed";
}
if (!verify_events(ptt.finish_events())) {
CONFIG_ELOG << ptt.id() << " verify finish events failed";
}
for (const auto& i : ptt.prize_wheels()) {
if (!verify_conditions(i.conditions())) {
CONFIG_ELOG << ptt.id() << " verify conditions failed";
}
if (!verify_events(i.events())) {
CONFIG_ELOG << ptt.id() << " verify events failed";
}
}
};
}
activity_discount_goods_ptts& activity_discount_goods_ptts_instance() {
static activity_discount_goods_ptts inst;
return inst;
}
void activity_discount_goods_ptts_set_funcs() {
activity_discount_goods_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(shop, ptt.shop_pttid())) {
CONFIG_ELOG << ptt.id() << " shop table not exist " << ptt.shop_pttid();
} else {
auto& shop_ptt = PTTS_GET(shop, ptt.shop_pttid());
shop_ptt.set__discount_activity_id(ptt.id());
}
};
}
activity_shop_recharge_ptts& activity_shop_recharge_ptts_instance() {
static activity_shop_recharge_ptts inst;
return inst;
}
void activity_shop_recharge_ptts_set_funcs() {
}
activity_continue_recharge_ptts& activity_continue_recharge_ptts_instance() {
static activity_continue_recharge_ptts inst;
return inst;
}
void activity_continue_recharge_ptts_set_funcs() {
activity_continue_recharge_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.quests()) {
if (!PTTS_HAS(quest, i.auto_quest())) {
CONFIG_ELOG << ptt.id() << " has not quest " << i.auto_quest();
}
if (!PTTS_HAS(quest, i.event_quest())) {
CONFIG_ELOG << ptt.id() << " has not quest " << i.event_quest();
} else {
auto& quest_ptt = PTTS_GET(quest, i.event_quest());
quest_ptt.set__activity_continue_recharge_quest(true);
}
}
};
}
activity_daiyanren_ptts& activity_daiyanren_ptts_instance() {
static activity_daiyanren_ptts inst;
return inst;
}
void activity_daiyanren_ptts_set_funcs() {
activity_daiyanren_ptts_instance().check_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.reward()) {
if (!check_events(i.events())) {
CONFIG_ELOG << ptt.id() << " check reward events failed";
}
}
};
activity_daiyanren_ptts_instance().modify_func_ = [] (auto& ptt) {
set<uint32_t> check_finish_quests;
for (auto i : ptt.fuli_quests()) {
if (PTTS_HAS(quest, i)) {
auto quests = quest_to_all_quests(i);
check_finish_quests.insert(quests.begin(), quests.end());
}
}
for (auto i : check_finish_quests) {
ptt.add__check_finish_quests(i);
}
};
activity_daiyanren_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(mail, ptt.reward_mail())) {
CONFIG_ELOG << ptt.id() << " reward table not exist " << ptt.reward_mail();
}
for (const auto& i : ptt.reward()) {
if (!verify_events(i.events())) {
CONFIG_ELOG << ptt.id() << " verify reward events failed";
}
}
for (auto i : ptt.fuli_quests()) {
if (!PTTS_HAS(quest, i)) {
CONFIG_ELOG << ptt.id() << " fuli quests not exist " << i;
} else {
auto& quest_ptt = PTTS_GET(quest, i);
quest_ptt.set__activity_daiyanren_fuli_quest(true);
}
}
for (auto i : ptt.duihuan_quests()) {
if (!PTTS_HAS(quest, i)) {
CONFIG_ELOG << ptt.id() << " duihuan quests not exist " << i;
} else {
auto& quest_ptt = PTTS_GET(quest, i);
quest_ptt.set__activity_daiyanren_duihuan_quest(true);
}
}
};
}
activity_limit_play_ptts& activity_limit_play_ptts_instance() {
static activity_limit_play_ptts inst;
return inst;
}
void activity_limit_play_ptts_set_funcs() {
activity_limit_play_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.quests()) {
if (!PTTS_HAS(quest, i.auto_quest())) {
CONFIG_ELOG << ptt.id() << " has not quest " << i.auto_quest();
}
if (!PTTS_HAS(quest, i.event_quest())) {
CONFIG_ELOG << ptt.id() << " has not quest " << i.event_quest();
} else {
auto& quest_ptt = PTTS_GET(quest, i.event_quest());
quest_ptt.set__activity_limit_play_quest(true);
}
}
};
}
activity_leiji_recharge_ptts& activity_leiji_recharge_ptts_instance() {
static activity_leiji_recharge_ptts inst;
return inst;
}
void activity_leiji_recharge_ptts_set_funcs() {
activity_leiji_recharge_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.quests()) {
if (!PTTS_HAS(quest, i.auto_quest())) {
CONFIG_ELOG << ptt.id() << " has not quest " << i.auto_quest();
continue;
}
if (!PTTS_HAS(quest, i.event_quest())) {
CONFIG_ELOG << ptt.id() << " has not quest " << i.event_quest();
continue;
}
auto& quest_ptt = PTTS_GET(quest, i.event_quest());
quest_ptt.set__activity_leiji_recharge_quest(true);
}
};
}
activity_leiji_consume_ptts& activity_leiji_consume_ptts_instance() {
static activity_leiji_consume_ptts inst;
return inst;
}
void activity_leiji_consume_ptts_set_funcs() {
activity_leiji_consume_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.quests()) {
if (!PTTS_HAS(quest, i.auto_quest())) {
CONFIG_ELOG << ptt.id() << " has not quest " << i.auto_quest();
continue;
}
if (!PTTS_HAS(quest, i.event_quest())) {
CONFIG_ELOG << ptt.id() << " has not quest " << i.event_quest();
continue;
}
auto& quest_ptt = PTTS_GET(quest, i.event_quest());
quest_ptt.set__activity_leiji_consume_quest(true);
}
};
}
activity_tea_party_ptts& activity_tea_party_ptts_instance() {
static activity_tea_party_ptts inst;
return inst;
}
void activity_tea_party_ptts_set_funcs() {
activity_tea_party_ptts_instance().check_func_ = [] (const auto& ptt) {
if (!check_events(ptt.start_events())) {
CONFIG_ELOG << ptt.id() << " check start events failed";
}
if (!check_events(ptt.finish_events())) {
CONFIG_ELOG << ptt.id() << " check finish events failed";
}
for (const auto& i : ptt.favor_rewards()) {
if (!check_conditions(i.conditions())) {
CONFIG_ELOG << ptt.id() << " check favor reward conditions failed";
}
if (!check_events(i.events())) {
CONFIG_ELOG << ptt.id() << " check favor reward events failed";
}
}
};
activity_tea_party_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(actor, ptt.actor())) {
CONFIG_ELOG << ptt.id() << " actor not exist " << ptt.actor();
}
if (!PTTS_HAS(lottery, ptt.lottery())) {
CONFIG_ELOG << ptt.id() << " lottery not exist " << ptt.lottery();
} else {
auto& lottery_ptt = PTTS_GET(lottery, ptt.lottery());
lottery_ptt.set__activity_tea_party(ptt.id());
}
for (const auto& i : ptt.favor_rewards()) {
if (!verify_conditions(i.conditions())) {
CONFIG_ELOG << ptt.id() << " verify favor reward conditions failed";
}
if (!verify_events(i.events())) {
CONFIG_ELOG << ptt.id() << " verify favor reward events failed";
}
}
if (!verify_events(ptt.start_events())) {
CONFIG_ELOG << ptt.id() << " verify start events failed";
}
if (!verify_events(ptt.finish_events())) {
CONFIG_ELOG << ptt.id() << " verify finish events failed";
}
if (!PTTS_HAS(rank_reward, ptt.rank_reward())) {
CONFIG_ELOG << ptt.id() << " rank reward not exist " << ptt.rank_reward();
}
};
}
activity_logic_ptts& activity_logic_ptts_instance() {
static activity_logic_ptts inst;
return inst;
}
void activity_logic_ptts_set_funcs() {
activity_logic_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(mail, ptt.continue_recharge_mail())) {
CONFIG_ELOG << ptt.id() << " has not mail " << ptt.continue_recharge_mail();
}
if (!PTTS_HAS(mail, ptt.limit_play_mail())) {
CONFIG_ELOG << ptt.id() << " has not mail " << ptt.limit_play_mail();
}
if (!PTTS_HAS(mail, ptt.leiji_recharge_mail())) {
CONFIG_ELOG << ptt.id() << " has not mail " << ptt.leiji_recharge_mail();
}
if (!PTTS_HAS(mail, ptt.festival_mail())) {
CONFIG_ELOG << ptt.id() << " has not mail " << ptt.festival_mail();
}
if (!PTTS_HAS(mail, ptt.leiji_consume_mail())) {
CONFIG_ELOG << ptt.id() << " has not mail " << ptt.leiji_consume_mail();
}
if (!PTTS_HAS(activity_leiji_recharge, ptt.activity_start().leiji_recharge())) {
CONFIG_ELOG << ptt.id() << " has not activity leiji recharge " << ptt.activity_start().leiji_recharge();
}
if (!PTTS_HAS(activity_leiji_consume, ptt.activity_start().leiji_consume())) {
CONFIG_ELOG << ptt.id() << " has not activity leiji consume " << ptt.activity_start().leiji_consume();
}
if (!PTTS_HAS(activity_tea_party, ptt.activity_start().tea_party())) {
CONFIG_ELOG << ptt.id() << " has not activity tea party " << ptt.activity_start().tea_party();
}
};
}
}
}
|
#include "CityDetails.h"
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#include <string>
using namespace std;
int n, sum, mul, s[100];
float ave;
int input() {
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &s[i]);
}
void solve() {
sum = 0;
mul = 1;
for (int i = 0; i < n; i++) {
sum += s[i];
mul *= s[i];
}
}
int output() {
ave = sum/n;
printf("%f %d\n", ave, mul);
}
int main()
{
int ntest, itest;
freopen("tieuhoc2.inp", "r", stdin);
scanf("%d", &ntest);
for (int itest = 0; itest < ntest; itest++) {
input();
solve();
output();
}
getchar();
return 0;
}
|
#include "FileDownload.hpp"
FileDownload::FileDownload(ResponseContext& ctx, BufferChain& writeChain, struct stat *file) : HttpResponse(ctx)
{
int fd;
if ((fd = open(_route.c_str(), O_RDONLY)) != -1)
{
setLastModified(file);
setContentType();
setCharset();
_contentLength = file->st_size;
setServerName();
setContentLocation();
std::string* buff;
buff = getRawHeaders();
writeChain.pushBack(buff);
}
else
{
throw HttpError(INTERNAL_SERVER_ERROR);
}
_streamReadFd = fd;
_state.read = DONE;
_state.readStream = READY;
}
FileDownload::~FileDownload()
{
}
|
// Copyright (c) 2020 Thomas Heller
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/execution_base/receiver.hpp>
#include <pika/execution_base/sender.hpp>
#include <pika/testing.hpp>
#include <cstddef>
#include <exception>
#include <functional>
#include <string>
#include <type_traits>
#include <utility>
namespace ex = pika::execution::experimental;
static std::size_t friend_tag_invoke_connect_calls = 0;
static std::size_t tag_invoke_connect_calls = 0;
struct non_sender_1
{
};
struct non_sender_2
{
template <template <class...> class Variant>
using error_types = Variant<>;
static constexpr bool sends_done = false;
};
struct non_sender_3
{
template <template <class...> class Tuple, template <class...> class Variant>
using value_types = Variant<Tuple<>>;
static constexpr bool sends_done = false;
};
struct non_sender_4
{
template <template <class...> class Tuple, template <class...> class Variant>
using value_types = Variant<Tuple<>>;
template <template <class...> class Variant>
using error_types = Variant<>;
};
struct non_sender_5
{
static constexpr bool sends_done = false;
};
struct non_sender_6
{
template <template <class...> class Variant>
using error_types = Variant<>;
};
struct non_sender_7
{
template <template <class...> class Tuple, template <class...> class Variant>
using value_types = Variant<Tuple<>>;
};
struct receiver
{
friend void tag_invoke(ex::set_error_t, receiver&&, std::exception_ptr) noexcept {}
friend void tag_invoke(ex::set_stopped_t, receiver&&) noexcept {}
friend void tag_invoke(ex::set_value_t, receiver&& r, int v) noexcept { r.i.get() = v; }
friend constexpr ex::empty_env tag_invoke(ex::get_env_t, receiver const&) noexcept
{
return {};
}
std::reference_wrapper<int> i;
};
struct sender_1
{
template <template <class...> class Tuple, template <class...> class Variant>
using value_types = Variant<Tuple<int>>;
template <template <class...> class Variant>
using error_types = Variant<std::exception_ptr>;
static constexpr bool sends_done = false;
using completion_signatures =
ex::completion_signatures<ex::set_value_t(int), ex::set_error_t(std::exception_ptr)>;
struct operation_state
{
receiver r;
friend void tag_invoke(ex::start_t, operation_state& os) noexcept
{
ex::set_value(std::move(os.r), 4711);
};
};
friend operation_state tag_invoke(ex::connect_t, sender_1&&, receiver r)
{
++friend_tag_invoke_connect_calls;
return {r};
}
};
struct sender_2
{
template <template <class...> class Tuple, template <class...> class Variant>
using value_types = Variant<Tuple<int>>;
template <template <class...> class Variant>
using error_types = Variant<std::exception_ptr>;
static constexpr bool sends_done = false;
using completion_signatures =
ex::completion_signatures<ex::set_value_t(int), ex::set_error_t(std::exception_ptr)>;
struct operation_state
{
receiver r;
friend void tag_invoke(ex::start_t, operation_state& os) noexcept
{
ex::set_value(std::move(os.r), 4711);
};
};
};
sender_2::operation_state tag_invoke(ex::connect_t, sender_2, receiver r)
{
++tag_invoke_connect_calls;
return {r};
}
static std::size_t void_receiver_set_value_calls = 0;
struct void_receiver
{
friend void tag_invoke(ex::set_error_t, void_receiver&&, std::exception_ptr) noexcept {}
friend void tag_invoke(ex::set_stopped_t, void_receiver&&) noexcept {}
friend void tag_invoke(ex::set_value_t, void_receiver&&) noexcept
{
++void_receiver_set_value_calls;
}
friend constexpr ex::empty_env tag_invoke(ex::get_env_t, void_receiver const&) noexcept
{
return {};
}
};
#if !defined(PIKA_HAVE_STDEXEC)
template <typename Sender>
constexpr bool unspecialized(...)
{
return false;
}
template <typename Sender>
constexpr bool unspecialized(typename ex::sender_traits<Sender>::__unspecialized*)
{
return true;
}
#endif
int main()
{
#if !defined(PIKA_HAVE_STDEXEC)
static_assert(unspecialized<void>(nullptr), "void should not have sender_traits");
static_assert(
unspecialized<std::nullptr_t>(nullptr), "std::nullptr_t should not have sender_traits");
static_assert(unspecialized<int>(nullptr), "non_sender_1 should not have sender_traits");
static_assert(unspecialized<double>(nullptr), "non_sender_1 should not have sender_traits");
static_assert(
unspecialized<non_sender_1>(nullptr), "non_sender_1 should not have sender_traits");
static_assert(
unspecialized<non_sender_2>(nullptr), "non_sender_2 should not have sender_traits");
static_assert(
unspecialized<non_sender_3>(nullptr), "non_sender_3 should not have sender_traits");
static_assert(
unspecialized<non_sender_4>(nullptr), "non_sender_4 should not have sender_traits");
static_assert(
unspecialized<non_sender_5>(nullptr), "non_sender_5 should not have sender_traits");
static_assert(
unspecialized<non_sender_6>(nullptr), "non_sender_6 should not have sender_traits");
static_assert(
unspecialized<non_sender_7>(nullptr), "non_sender_7 should not have sender_traits");
static_assert(!unspecialized<sender_1>(nullptr), "sender_1 should have sender_traits");
static_assert(!unspecialized<sender_2>(nullptr), "sender_2 should have sender_traits");
#endif
static_assert(!ex::is_sender_v<void>, "void is not a sender");
static_assert(!ex::is_sender_v<std::nullptr_t>, "std::nullptr_t is not a sender");
static_assert(!ex::is_sender_v<int>, "int is not a sender");
static_assert(!ex::is_sender_v<double>, "double is not a sender");
static_assert(!ex::is_sender_v<non_sender_1>, "non_sender_1 is not a sender");
static_assert(!ex::is_sender_v<non_sender_2>, "non_sender_2 is not a sender");
static_assert(!ex::is_sender_v<non_sender_3>, "non_sender_3 is not a sender");
static_assert(!ex::is_sender_v<non_sender_4>, "non_sender_4 is not a sender");
static_assert(!ex::is_sender_v<non_sender_5>, "non_sender_5 is not a sender");
static_assert(!ex::is_sender_v<non_sender_6>, "non_sender_6 is not a sender");
static_assert(!ex::is_sender_v<non_sender_7>, "non_sender_7 is not a sender");
static_assert(ex::is_sender_v<sender_1>, "sender_1 is a sender");
static_assert(ex::is_sender_v<sender_2>, "sender_2 is a sender");
static_assert(ex::is_sender_to_v<sender_1, receiver>, "sender_1 is a sender to receiver");
static_assert(ex::is_sender_to_v<sender_1, receiver>, "sender_1 is a sender to receiver");
static_assert(
!ex::is_sender_to_v<sender_1, non_sender_1>, "sender_1 is not a sender to non_sender_1");
static_assert(!ex::is_sender_to_v<sender_1, sender_1>, "sender_1 is not a sender to sender_1");
static_assert(ex::is_sender_to_v<sender_2, receiver>, "sender_2 is a sender to receiver");
static_assert(
!ex::is_sender_to_v<sender_2, non_sender_2>, "sender_2 is not a sender to non_sender_2");
static_assert(!ex::is_sender_to_v<sender_2, sender_2>, "sender_2 is not a sender to sender_2");
{
int i = 1;
receiver r1{i};
auto os = ex::connect(sender_1{}, std::move(r1));
ex::start(os);
PIKA_TEST_EQ(i, 4711);
PIKA_TEST_EQ(friend_tag_invoke_connect_calls, std::size_t(1));
PIKA_TEST_EQ(tag_invoke_connect_calls, std::size_t(0));
}
{
int i = 1;
receiver r2{i};
auto os = ex::connect(sender_2{}, std::move(r2));
ex::start(os);
PIKA_TEST_EQ(i, 4711);
PIKA_TEST_EQ(friend_tag_invoke_connect_calls, std::size_t(1));
PIKA_TEST_EQ(tag_invoke_connect_calls, std::size_t(1));
}
return 0;
}
|
/**
* Copyright (c) 2022, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file readline_context.hh
*/
#ifndef readline_context_hh
#define readline_context_hh
#include <set>
#include <string>
#include <readline/history.h>
#include "base/lnav.console.hh"
#include "base/result.h"
#include "help_text.hh"
class attr_line_t;
struct exec_context;
typedef void (*readline_highlighter_t)(attr_line_t& line, int x);
/**
* Container for information related to different readline contexts. Since
* lnav uses readline for different inputs, we need a way to keep things like
* history and tab-completions separate.
*/
class readline_context {
public:
typedef Result<std::string, lnav::console::user_message> (*command_func_t)(
exec_context& ec, std::string cmdline, std::vector<std::string>& args);
typedef std::string (*prompt_func_t)(exec_context& ec,
const std::string& cmdline);
typedef struct _command_t {
const char* c_name;
command_func_t c_func;
struct help_text c_help;
prompt_func_t c_prompt{nullptr};
_command_t(const char* name,
command_func_t func,
help_text help = {},
prompt_func_t prompt = nullptr) noexcept
: c_name(name), c_func(func), c_help(std::move(help)),
c_prompt(prompt)
{
}
_command_t(command_func_t func) noexcept : c_name("anon"), c_func(func)
{
}
} command_t;
typedef std::map<std::string, command_t*> command_map_t;
readline_context(std::string name,
command_map_t* commands = nullptr,
bool case_sensitive = true);
const std::string& get_name() const { return this->rc_name; }
void load();
void save();
void add_possibility(const std::string& type, const std::string& value)
{
this->rc_possibilities[type].insert(value);
}
void rem_possibility(const std::string& type, const std::string& value)
{
this->rc_possibilities[type].erase(value);
}
void clear_possibilities(const std::string& type)
{
this->rc_possibilities[type].clear();
}
bool is_case_sensitive() const { return this->rc_case_sensitive; }
readline_context& set_append_character(int ch)
{
this->rc_append_character = ch;
return *this;
}
int get_append_character() const
{
return this->rc_append_character;
}
readline_context& set_highlighter(readline_highlighter_t hl)
{
this->rc_highlighter = hl;
return *this;
}
readline_context& set_quote_chars(const char* qc)
{
this->rc_quote_chars = qc;
return *this;
}
readline_context& with_readline_var(char** var, const char* val)
{
this->rc_vars.emplace_back(var, val);
return *this;
}
readline_highlighter_t get_highlighter() const
{
return this->rc_highlighter;
}
static int command_complete(int, int);
std::map<std::string, std::string> rc_prefixes;
private:
static char** attempted_completion(const char* text, int start, int end);
static char* completion_generator(const char* text, int state);
static readline_context* loaded_context;
static std::set<std::string>* arg_possibilities;
struct readline_var {
readline_var(char** dst, const char* val)
{
this->rv_dst.ch = dst;
this->rv_val.ch = val;
}
union {
char** ch;
} rv_dst;
union {
const char* ch;
} rv_val;
};
std::string rc_name;
HISTORY_STATE rc_history;
std::map<std::string, std::set<std::string>> rc_possibilities;
std::map<std::string, std::vector<std::string>> rc_prototypes;
bool rc_case_sensitive;
int rc_append_character;
const char* rc_quote_chars;
readline_highlighter_t rc_highlighter;
std::vector<readline_var> rc_vars;
};
#endif
|
#ifndef __MATH_FFT_H__
#define __MATH_FFT_H__
/*
===============================================================================
Fast Fourier Transform
===============================================================================
*/
// complex number
typedef struct {
float re;
float im;
} cpxFloat_t;
class idFFT {
public:
// RAVEN BEGIN
// jscott: added stride to 1D, created 2D
static void FFT1D( cpxFloat_t *data, int N, int ISI, int stride = 1 );
static void FFT2D( cpxFloat_t *data, int N, int ISI );
static void FFT3D( cpxFloat_t *data, int N, int ISI );
// RAVEN END
};
#endif /* !__MATH_FFT_H__ */
|
#include<bits/stdc++.h>
using namespace std;
int main(){
double a=0.5, b=10.5;
int c=215,d;
char e='A';
printf("%lf + %lf = %lf dayo!\n",a,b,a+b);
d=c+11;
printf("c is %d!! add 11 de %d dayo!!\n",c,d);
printf("e is \"%c\" dayo!!!\n",e);
}
|
#include<string.h>
#include<iostream>
#include<vector>
using namespace std;
static int diffMax = 100;
// for sake of learning, im not using std max lib :(
int getMax(vector<int> arr)
{
int max = 0;
for(int i = 0; i < arr.size(); i++)
{
if(max < arr[i])
max = arr[i];
}
return max;
}
vector<int> countDuplicate(vector<int> arr)
{
vector<int> temp;
temp.assign(200000, 0);
for(int i=0; i< arr.size(); i++)
{
int index = arr[i];
temp[index] += 1;
}
return temp;
}
vector<int> missingNumbers(vector<int> arr, vector<int> brr) {
vector<int> temp;
vector<int> result1 = countDuplicate(arr);
vector<int> result2 = countDuplicate(brr);
int max = getMax(brr);
for(int i=max-100; i<= max; i++){
if((result1[i] ^ result2[i]) != 0) // filter duplicate
{
temp.push_back(i);
}
}
return temp;
}
int main()
{
int n = 10;
vector<int> n1 = {203, 204, 205, 206, 207, 208, 203, 204, 205, 206};
int z = 13;
vector<int> z2 = {203, 204, 204, 205, 206, 207, 205, 208, 203, 206, 205, 206, 204};
vector<int> result = missingNumbers(n1, z2);
for (int i = 0; i < result.size(); i++)
{
cout << result[i] << ' ';
}
return 0;
}
|
#pragma once
#include "../Component.h"
#include <glm/glm.hpp>
class Camera : public Component {
public:
Camera(float fov, float aspect, float zNear, float zFar);
~Camera() {};
glm::mat4 getViewMatrix();
glm::mat4 getProjectionMatrix();
glm::mat4 getViewProjectionMatrix();
void input(float delta);
virtual void addToRenderingEngine(RenderingEngine* renderingEngine);
private:
glm::mat4 m_viewMatrix;
glm::mat4 m_projectionMatrix;
glm::vec3 cameraPos;
glm::vec3 cameraFront;
glm::vec3 cameraUp;
glm::vec2 center;
float m_sensitivity;
float m_fov;
float m_aspect;
float m_zNear;
float m_zFar;
float yaw;
float pitch;
float fov;
};
|
/*
* Copyright(c) 2017-2019 WindSoul Network Technology, Inc. All rights reserved.
*/
/**
* Desc: 游戏逻辑相关的常量
* Author:
* Date: 2018-04-23
* Time: 21:17
*/
#ifndef __LogicConstants_H__
#define __LogicConstants_H__
#include "CoreMinimal.h"
#include <DataContainer.pb.h>
namespace LogicConstants
{
//****************************** 视角 begin ********************************
static float SLIDER_LEAVE_RANGE_PERCENT_THRESHOLD_W = 0.6f;
static float SLIDER_RETURN_RANGE_PERCENT_THRESHOLD_H = 0.6f;
static float SLIDER_SCREEN_RADIUS_THRESHOLD = 300.f;
static float SLIDER_SCREEN_RADIUS_MAX = 500.f;
static float SLIDER_INIT_SPEED = 100.f;
static float SLIDER_ACCELERATE = 100.f;
static float SLIDER_BASE_WORLD_DISTANCE = 500.f;
static int SLIDER_OUT_FIRE_PADDING = 10;
static int SLIDER_IN_FIRE_PADDING = 250;
//****************************** 视角 end ********************************
//****************************** 武器 begin ********************************
//暴击倍数
static float DAMAGE_CRIT_TIMES = 1.f;
static float ONE_SHOOT_CLICK_TIME_THRESHOLD = 300.f;
//****************************** 武器 end ********************************
//****************************** 掉落 begin ********************************
//捡道具的有效距离
static const float PICK_ITEM_DIST = 150.f;
//显示道具特效的有效距离
static const float DROW_ITEM_PARTICLE_DIST = 2000.f;
//掉道具时的距离
static const float DROP_ITEM_DIST = 100.f;
//初始化时的默认Z轴高度
static const float DROP_ITEM_INIT_LOC_Z = 50.f;
////初始化时的有效坐标检测半径
static const float DROP_ITEM_LOC_CHECK_RADIUS = 200.f;
//****************************** 掉落 end ********************************
//****************************** 掉落 begin ********************************
//空手状态的武器ID
static const FString EMPYT_WEAPON_ID = TEXT("i_wea_empty_hand");
//****************************** 掉落 end ********************************
//****************************** 背包 begin ******************************
static const FString INIT_BAG_ID = TEXT("i_bag_0");
static const int32 INIT_BAG_CAPACITY = 12;
void InitConstants()
{
if (const ::proto::global_config_camera* config = GameObjectManager<proto::global_config_camera>::Instance().FindGameObject("gcc_001"))
{
SLIDER_LEAVE_RANGE_PERCENT_THRESHOLD_W = config->leave_range_percent_threshold_width();
SLIDER_RETURN_RANGE_PERCENT_THRESHOLD_H = config->return_range_percent_threshold_height();
SLIDER_INIT_SPEED = config->translate_init_speed();
SLIDER_ACCELERATE = config->translate_accelerate();
}
if (const ::proto::global_config_weapon* config = GameObjectManager<proto::global_config_weapon>::Instance().FindGameObject("gcw_001"))
{
DAMAGE_CRIT_TIMES = config->crit_times();
}
}
};
#endif
|
/**
CS 460 Final Project MCmain.cpp
Purpose: Approximate Pi using Leibniz' Formula
@author Marcus Corbin
@version 1.0 01/04/2020
*/
// Includes
#include <iostream>
#include <cstdlib>
#include <math.h>
#include <stdlib.h>
#include <pthread.h>
// Standard Namespace
using namespace std;
// Global Variables
long double sum1, newSum;
/**
Creates a thread and uses Leibniz' Formula to calculate sum.
@param params Passed in array from main
@return sum of the calculated formula
*/
void *threadFunc(void *params)
{
// Thread Variables
long double sum;
int n;
// Bring in the values from main
int *value = (int *)params;
//cout << "N value: " << value[0] << endl; // N value
//cout << "Total Threads: " << value[1] << endl; // Thread numbers
cout << "Thread #: " << value[2] << endl; // Thread #
// For Loop to calculate Leibniz' Formula
for (n = 0; n < value[0]/value[1]; n++)
{
sum = pow(-1, n) * (1.0 / (2.0*n + 1.0));
sum1 += sum;
}
newSum = 4.0*(sum1 / value[1]); // Multiply by 4 to get Pi Sum
cout << "The sum is: " << newSum << endl << endl; // Output current Sum
pthread_exit(NULL); // End Thread
}
/**
Main code that get's user input
@param argc Contains number of arguments passed into program.
@param argv Array of argument strings
@return Approximation of Pi using values from user.
*/
int main( int argc, char *argv[] )
{
int i;
int val[3];
// Let user know what the program is
cout << "Pi Approximation using Leibniz's formula" << endl;
cout << "----------------------------------------" << endl;
cout.precision(17); // Set the precision so more decimal places are shown
// Ask user for value of n
cout << "How many (n) iterations to check?: ";
cin >> val[0];
cout << endl;
// Ask user how many threads to create
cout << "How many threads to create? : ";
cin >> val[1];
cout << endl;
// Thread definition
pthread_t tid[val[1]];
// For loop used to create number of threads per user's input
for (i = 0; i < val[1]; i++)
{
val[2] = i; // This will be used for the Thread number
pthread_create(&tid[i], NULL, threadFunc, (void *)val); // Create a thread
pthread_join(tid[i], NULL); // Wait till thread finishes
}
// Last line of terminal
cout << endl << "Pi Approx: " << newSum << endl << endl;
// End Code
pthread_exit(NULL);
}
|
#include<iostream>
#include<vector>
using namespace std;
long int s,d,sum;
vector<long int> output;
long int sum5(int j)
{
long int sm=0;
for(int i=0;i<5;i++,j--)
{
sm+=output[j];
}
return sm;
}
void build5()
{
int i;
for(i=0;i<5;i++)
output.push_back(s);
for(i=4;i>=0;i--)
{
output[i]=d;
if(sum5(4)<0)break;
}
sum+=sum5(4);
}
void backtrack(int j)
{
if(j==11)
return;
output.push_back(s);
if(sum5(j+1)<0)
{
sum+=s;
backtrack(j+1);
}
else
{
output.pop_back();
output.push_back(d);
sum+=d;
backtrack(j+1);
}
}
int main()
{
while(cin>>s)
{
output.clear();
sum=0;
cin>>d;
d=(-1)*d;
build5();
backtrack(4);
if(sum>0)cout<<sum<<endl;
else cout<<"Deficit\n";
}
return 0;
}
|
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
bool is;
char s[105];
node * next[128];
}nod[500005],*root;
int num,n;
char s[10005];
node * cre()
{
node * p = &nod[num++];
for(int i=0;i<128;++i)
p->next[i] = NULL;
p->is = NULL;
return p;
}
char str[1005];
void ins()
{
int k,n = 0;
node * p = root;
for(int i=0;s[i];++i)
{
if(s[i]=='\\'){
p->is = 1;
str[n] = 0;
strcpy(p->s,str);
k = n = 0;
}
else {
k = s[i];
str[n++] = s[i];
}
if(p->next[k]==NULL) p->next[k] = cre();
p = p->next[k];
}
str[n] = 0;
strcpy(p->s,str);
p->is = 1;
}
void dfs(node * p,int k)
{
if(p->is){
for(int i=0;i<k;++i)
putchar(' ');
printf("%s\n",p->s);
if(p->next[0]) dfs(p->next[0],k+1);
for(int i=1;i<128;++i)
if(p->next[i])
dfs(p->next[i],k);
return;
}
for(int i=0;i<128;++i)
if(p->next[i])
dfs(p->next[i],k);
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
num = 0;
root = cre();
for(int i=0;i<n;++i){
scanf("%s",s);
ins();
}
for(int i=0;i<128;++i)
if(root->next[i])
dfs(root->next[i],0);
}
return 0;
}
/*
void dfs(node * loc,int t,int k,int x)
{
if(t==0){
for(int i=0;i<128;++i)
if(loc->next[i])
dfs(loc->next[i],i,k,x);
return;
}
//printf("%d\n",x);
s[x] = (char)t;
if(loc->is){
s[x+1] = 0;
for(int i=0;i<k;++i)
putchar(' ');
printf("%s\n",s);
//memset(s,0,sizeof(s));
//if(loc->next[0]) dfs(loc->next[0],0,k+1,0);
for(int i=0;i<128;++i)
if(loc->next[i])
dfs(loc->next[i],i,k+1,0);
}else {
for(int i=0;i<128;++i)
if(loc->next[i])
dfs(loc->next[i],i,k,x+1);
}
return;
}
*/
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include "blueprintresolver.h"
#include "featureexecutor.h"
#include "properties.h"
#include "matchdata.h"
#include "matchdatalayout.h"
#include "feature_resolver.h"
#include <vespa/vespalib/stllike/string.h>
#include <vespa/vespalib/util/array.h>
#include <set>
#include <vector>
namespace search {
namespace fef {
/**
* A rank program is able to lazily calculate a set of feature
* values. In order to access (and thereby calculate) output features
* you typically use the get_seeds function to resolve the predefined
* set of output features. Each feature value will be wrapped in a
* LazyValue object that can be realized for a specific docid. The
* rank program also owns the MatchData used to store unpacked
* term-field match information. Note that you need unpack any
* relevant posting information into the MatchData object before
* trying to resolve lazy values.
**/
class RankProgram
{
private:
RankProgram(const RankProgram &) = delete;
RankProgram &operator=(const RankProgram &) = delete;
using MappedValues = std::map<const NumberOrObject *, LazyValue>;
using ValueSet = std::set<const NumberOrObject *>;
BlueprintResolver::SP _resolver;
MatchData::UP _match_data;
vespalib::Stash _hot_stash;
vespalib::Stash _cold_stash;
std::vector<FeatureExecutor *> _executors;
MappedValues _unboxed_seeds;
ValueSet _is_const;
bool check_const(const NumberOrObject *value) const { return (_is_const.count(value) == 1); }
bool check_const(FeatureExecutor *executor, const std::vector<BlueprintResolver::FeatureRef> &inputs) const;
void run_const(FeatureExecutor *executor);
void unbox(BlueprintResolver::FeatureRef seed);
FeatureResolver resolve(const BlueprintResolver::FeatureMap &features, bool unbox_seeds) const;
public:
typedef std::unique_ptr<RankProgram> UP;
/**
* Create a new rank program backed by the given resolver.
*
* @param resolver description on how to set up executors
**/
RankProgram(BlueprintResolver::SP resolver);
~RankProgram();
size_t num_executors() const { return _executors.size(); }
/**
* Set up this rank program by creating the needed feature
* executors and wiring them together. This function will also
* create the MatchData to be used for iterator unpacking as well
* as pre-calculating all constant features.
**/
void setup(const MatchDataLayout &mdl,
const IQueryEnvironment &queryEnv,
const Properties &featureOverrides = Properties());
/**
* Expose the MatchData used when creating search iterators as it
* is where all iterators should unpack their match information.
**/
MatchData &match_data() { return *_match_data; }
const MatchData &match_data() const { return *_match_data; }
/**
* Obtain the names and storage locations of all seed features for
* this rank program. Programs for ranking phases will only have a
* single seed while programs used for summary features or
* scraping will have multiple seeds.
*
* @params unbox_seeds make sure seeds values are numbers
**/
FeatureResolver get_seeds(bool unbox_seeds = true) const;
/**
* Obtain the names and storage locations of all features for this
* rank program. This method is intended for debugging and
* testing.
*
* @params unbox_seeds make sure seeds values are numbers
**/
FeatureResolver get_all_features(bool unbox_seeds = true) const;
};
} // namespace fef
} // namespace search
|
#include <NetworkModel/NetworkModel/IOCP/IOCP.hpp>
#include <Functions/Functions/MySQL/MySQL.hpp>
#include "CharacterProcessor.h"
#include "../RESULT.h"
extern FUNCTIONS::MYSQL::CMySQLPool g_DBPool;
void PACKET::CHARINFO::PacketProcessor(FUNCTIONS::CIRCULARQUEUE::QUEUEDATA::CPacketQueueData* const Data) {
using namespace NETWORKMODEL;
if (CCHARINFO AccountInfo; Data) {
NETWORK::UTIL::PACKET::DeSerialize(Data->m_PacketStructure, AccountInfo);
switch (auto Owner = reinterpret_cast<IOCP::DETAIL::CONNECTION*>(Data->m_Owner); AccountInfo.m_MessageType) {
case ECHARINFOMESSAGETYPE::EMT_CREATE:
ProcessNewCharacter(Owner, AccountInfo);
break;
case ECHARINFOMESSAGETYPE::EMT_GETLIST:
ProcessGetList(Owner, AccountInfo);
break;
}
}
}
void PACKET::CHARINFO::ProcessNewCharacter(const NETWORKMODEL::IOCP::DETAIL::CONNECTION* const Owner, const CCHARINFO& Data) {
using namespace FUNCTIONS::UTIL;
if (auto Connector = ::g_DBPool.GetConnection("fh_database"); Owner && Owner->m_Session) {
auto SearchResult = MYSQL::SearchData("account", MYSQL::DETAIL::SELECTDATA({ "id", '\'' + std::string(Data.m_NICKNAME) + '\'', '\'' + std::to_string(Data.m_CHARACTERTYPE) + '\'' }, { MYSQL::MakeCondition(MYSQL::DETAIL::ECONDITIONTYPE::ECT_LIKE, MYSQL::DETAIL::ELOGICALTYPE::ELT_NONE, "user_id", Data.m_ID) }));
auto Result = MYSQL::ExecuteQuery(Connector.get(), MYSQL::InsertNewData("characters", { MYSQL::DETAIL::INSERTDATA("account_id"), MYSQL::DETAIL::INSERTDATA("nickname"), MYSQL::DETAIL::INSERTDATA("char_type") }, SearchResult));
int CharacterID = 0;
auto Lambda = [&CharacterID](sql::ResultSet* const Result) {
while (Result && Result->next()) {
CharacterID = Result->getInt("id");
}
};
CRESULT ResultPacket;
if (Result == MYSQL::DUPLICATEVALUE) {
ResultPacket = CRESULT(ERESULTMESSAGETYPE::EMT_FAIL, EPACKETPROTOCOL::EPPT_CHARINFO, ECHARINFOMESSAGETYPE::EMT_CREATE, "Duplicate Nickname!");
}
else if (Result == MYSQL::NOTEXISTREFTABLE) {
ResultPacket = CRESULT(ERESULTMESSAGETYPE::EMT_FAIL, EPACKETPROTOCOL::EPPT_CHARINFO, ECHARINFOMESSAGETYPE::EMT_CREATE, "ID is not exist!");
}
else if (!MYSQL::ExecuteQuery(Connector.get(), MYSQL::SearchData("characters", { MYSQL::DETAIL::SELECTDATA({ "characters.id" }, { MYSQL::MakeCondition(MYSQL::DETAIL::ECONDITIONTYPE::ECT_LIKE, MYSQL::DETAIL::ELOGICALTYPE::ELT_NONE, "nickname", Data.m_NICKNAME) }) }), Lambda)) {
CCHARINFO SendPacket(ECHARINFOMESSAGETYPE::EMT_CREATE, 0, nullptr, nullptr, 0, { CHARACTER(CharacterID, nullptr, Data.m_CHARACTERTYPE, 0) });
Owner->m_Session->Send(NETWORK::UTIL::PACKET::Serialize(SendPacket));
return;
}
Owner->m_Session->Send(NETWORK::UTIL::PACKET::Serialize(ResultPacket));
}
}
void PACKET::CHARINFO::ProcessGetList(const NETWORKMODEL::IOCP::DETAIL::CONNECTION* const Owner, const CCHARINFO& Data) {
using namespace FUNCTIONS::UTIL;
std::vector<CHARACTER> m_CharInfoList;
bool bIsFind = false;
auto SearchResultLambda = [&bIsFind, &m_CharInfoList](sql::ResultSet* const Result) {
while (Result && Result->next()) {
m_CharInfoList.emplace_back(Result->getInt(1), Result->getString(2).c_str(), Result->getInt(3), 0);
}
};
if (auto Connector = ::g_DBPool.GetConnection("fh_database"); Owner && Owner->m_Session) {
if (!MYSQL::ExecuteQuery(Connector.get(), MYSQL::SearchData("characters JOIN account", MYSQL::DETAIL::SELECTDATA({ "characters.id", "nickname", "char_type" }, { MYSQL::MakeCondition(MYSQL::DETAIL::ECONDITIONTYPE::ECT_LIKE, MYSQL::DETAIL::ELOGICALTYPE::ELT_AND, "account.user_id", Data.m_ID), MYSQL::MakeCondition(MYSQL::DETAIL::ECONDITIONTYPE::ECT_LIKE, MYSQL::DETAIL::ELOGICALTYPE::ELT_NONE, "account.id", "characters.account_id") })), SearchResultLambda)) {
CCHARINFO SendPacket(ECHARINFOMESSAGETYPE::EMT_GETLIST, Data.m_ACCOUNTID, "", "", 0, m_CharInfoList);
auto Packet = NETWORK::UTIL::PACKET::Serialize(SendPacket);
Owner->m_Session->Send(Packet);
}
else {
CRESULT SendPacket(ERESULTMESSAGETYPE::EMT_FAIL, EPACKETPROTOCOL::EPPT_CHARINFO, ECHARINFOMESSAGETYPE::EMT_GETLIST, "Unknown Error!");
auto Packet = NETWORK::UTIL::PACKET::Serialize(SendPacket);
Owner->m_Session->Send(Packet);
}
}
}
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <sstream>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <map>
typedef long long LL;
typedef unsigned long long ULL;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
int mark[222], x, y, yy[222], pp[222], xx[222], ans = 0, pr[222], kk = 0, n, k;
void Mark(int x, int k, int pr = -1) {
mark[x] = true;
if (k)
for (int i = xx[x]; i; i = pp[i]) {
int y = yy[i];
if (y == pr) continue;
Mark(y, k - 1, x);
}
}
void dfs(int x) {
for (int i = xx[x]; i; i = pp[i]) {
int y = yy[i];
if (y == pr[x]) continue;
pr[y] = x;
dfs(y);
}
if (!mark[y]) {
++ans;
int xx = x, cc = k;
while (pr[xx] != -1 && cc > 0) {
cc--;
xx = pr[xx];
}
Mark(xx, k);
}
}
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
cin >> n >> k;
for (int i = 1; i < n; ++i) {
cin >> x >> y;
yy[++kk] = y, pp[kk] = xx[x], xx[x] = kk;
yy[++kk] = x, pp[kk] = xx[y], xx[y] = kk;
}
pr[1] = -1;
dfs(1);
cout << ans << endl;
return 0;
}
|
#ifndef BG_H
#define BG_H
#include <QImage>
#include <QRect>
class Bg
{
public:
Bg();
~Bg();
public:
void resetState(); //spawn
QRect getRect();
void setRect(QRect);
QImage & getImage();
QImage image;
QRect rect;
int position;
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef VEGA3DDEVICE_H
#define VEGA3DDEVICE_H
#ifdef VEGA_SUPPORT
#include "modules/libvega/vegafixpoint.h"
#include "modules/libvega/vegatransform.h"
#include "modules/libvega/vegapixelstore.h"
#include "modules/libvega/vegarefcount.h"
#ifdef VEGA_BACKENDS_USE_BLOCKLIST
# include "platforms/vega_backends/vega_blocklist_device.h"
#endif // VEGA_BACKENDS_USE_BLOCKLIST
class VEGASWBuffer;
class VEGAWindow;
class OpRect;
#if defined(VEGA_3DDEVICE) || defined(CANVAS3D_SUPPORT)
class VEGA3dContextLostListener : public Link
{
public:
virtual ~VEGA3dContextLostListener()
{}
virtual void OnContextLost() = 0;
virtual void OnContextRestored() = 0;
};
/** A 3d render target. This cannot be used directly, you should create either
* a texture with the render target flag set or a window. */
class VEGA3dRenderTarget
{
public:
VEGA3dRenderTarget(){}
virtual ~VEGA3dRenderTarget(){}
/** Render target type. Supported types are window and texture. */
enum TargetType
{
VEGA3D_RT_WINDOW,
VEGA3D_RT_TEXTURE
};
/** @returns the width of the render target. */
virtual unsigned int getWidth() = 0;
/** @returns the width of the render target. */
virtual unsigned int getHeight() = 0;
/** @returns the type of render target. */
virtual TargetType getType() = 0;
#ifdef VEGA_NATIVE_FONT_SUPPORT
virtual void flushFonts(){}
#endif
};
/** Abstract interface to a window with 3d rendering capabilities.
* A 3dWindow is a render target which has a present function. */
class VEGA3dWindow : public VEGA3dRenderTarget
{
public:
virtual ~VEGA3dWindow(){}
/** Make the rendered content visible. Swap for double buffering. */
virtual void present(const OpRect* updateRects, unsigned int numRects) = 0;
/** Resize the backbuffer. */
virtual OP_STATUS resizeBackbuffer(unsigned int width, unsigned int height) = 0;
virtual TargetType getType(){return VEGA3D_RT_WINDOW;}
/** Optional functionality to access backbuffer of this window
* This is used if the platform code needs to access the backbuffer data for some reason,
* such as updating a transparent window on windows. */
/** Copy the backbuffer to specificed pixel store, slow but always work, should be
* used as fallback */
virtual OP_STATUS readBackbuffer(VEGAPixelStore*){return OpStatus::ERR;}
/** Get dc of backbuffer, can be very effecient since readback might be avoided, can also
* fail even when a valid dc handle is returned. Check the validity of pixels before use.*/
virtual void* getBackbufferHandle(){return NULL;}
virtual void releaseBackbufferHandle(void* handle){}
};
/** Abstract interface to a texture in the 3d hardware. */
class VEGA3dTexture : public VEGARefCount
{
protected:
VEGA3dTexture()
{}
virtual ~VEGA3dTexture()
{}
public:
/** Color format of the render target. INTENSITY8 has only one component
* which is considered the r, g, b and alpha component.
* LUMINANCE8 also has one component which is considered r g and b
* component. Alpha is 1. */
enum ColorFormat
{
FORMAT_RGBA8888,
FORMAT_RGB888,
FORMAT_RGBA4444,
FORMAT_RGBA5551,
FORMAT_RGB565,
FORMAT_ALPHA8,
FORMAT_LUMINANCE8,
FORMAT_LUMINANCE8_ALPHA8
};
/** Texture wrapping mode. Used when the texture coordinates is not
* in the 0..1 range. */
enum WrapMode
{
WRAP_REPEAT = 0,
WRAP_REPEAT_MIRROR,
WRAP_CLAMP_EDGE
};
enum FilterMode
{
FILTER_NEAREST = 0,
FILTER_LINEAR,
FILTER_NEAREST_MIPMAP_NEAREST,
FILTER_LINEAR_MIPMAP_NEAREST,
FILTER_NEAREST_MIPMAP_LINEAR,
FILTER_LINEAR_MIPMAP_LINEAR
};
enum CubeSide
{
CUBE_SIDE_NONE,
CUBE_SIDE_POS_X,
CUBE_SIDE_NEG_X,
CUBE_SIDE_POS_Y,
CUBE_SIDE_NEG_Y,
CUBE_SIDE_POS_Z,
CUBE_SIDE_NEG_Z,
NUM_CUBE_SIDES
};
enum MipMapHint
{
HINT_DONT_CARE,
HINT_FASTEST,
HINT_NICEST
};
/** Updates the image data in the texture with rgba data.
* @param x x offset of the image data
* @param y y offset of the image data
* @param pixels the actual pixel data
* @param rowAlignment used to make sure the size (in bytes) of each scanline is a multiple of this value
* @param side Side in the cube map to update or CUBE_SIDE_NONE if a regular 2d texture.
* @param level Mipmap level to update.
* @param yFlip if true, flip y-axis of source data when copying
* @param premultiplyAlpha if true, premultiply source data with its alpha value
* @returns OpStatus::OK if the image was updated, an error otherwise. */
virtual OP_STATUS update(unsigned int x, unsigned int y, const VEGASWBuffer* pixels, int rowAlignment = 4, CubeSide side = CUBE_SIDE_NONE, int level = 0, bool yFlip = false, bool premultiplyAlpha = false) = 0;
/** Updates the image data in the texture with intensity/luminance data.
* @param x x offset of the image data
* @param y y offset of the image data
* @param w width of the image data
* @param h height of the image data
* @param pixels the actual pixel data
* @param rowAlignment specifies how rows are aligned, 1, 2, 4 or 8 bytes.
* @param side Side in the cube map to update or CUBE_SIDE_NONE if a regular 2d texture.
* @param level Mipmap level to update.
* @param yFlip if true, flip y-axis of source data when copying
* @param premultiplyAlpha if true, premultiply source data with its alpha value
* @returns OpStatus::OK if the image was updated, an error otherwise. */
virtual OP_STATUS update(unsigned int x, unsigned int y, unsigned int w, unsigned int h, UINT8* pixels, unsigned int rowAlignment = 1, CubeSide side = CUBE_SIDE_NONE, int level = 0, bool yFlip = false, bool premultiplyAlpha = false) = 0;
/** Updates the image data in the texture with intensity/luminance data.
* @param x x offset of the image data
* @param y y offset of the image data
* @param w width of the image data
* @param h height of the image data
* @param pixels the actual pixel data
* @param rowAlignment specifies how rows are aligned, 1, 2, 4 or 8 bytes.
* @param side Side in the cube map to update or CUBE_SIDE_NONE if a regular 2d texture.
* @param level Mipmap level to update.
* @param yFlip if true, flip y-axis of source data when copying
* @param premultiplyAlpha if true, premultiply source data with its alpha value
* @returns OpStatus::OK if the image was updated, an error otherwise. */
virtual OP_STATUS update(unsigned int x, unsigned int y, unsigned int w, unsigned int h, UINT16* pixels, unsigned int rowAlignment = 1, CubeSide side = CUBE_SIDE_NONE, int level = 0, bool yFlip = false, bool premultiplyAlpha = false) = 0;
/** Generates mipmap levels for the texture.
* @returns OpStatus::OK if the image was updated, an error otherwise. */
virtual OP_STATUS generateMipMaps(MipMapHint hint = HINT_DONT_CARE) = 0;
/** @return the width of the texture. */
virtual unsigned int getWidth() = 0;
/** @return the height of the texture. */
virtual unsigned int getHeight() = 0;
/** @returns the format of the texture. */
virtual ColorFormat getFormat() = 0;
/** Set the wrapping mode. */
virtual void setWrapMode(WrapMode swrap, WrapMode twrap) = 0;
virtual WrapMode getWrapModeS() = 0;
virtual WrapMode getWrapModeT() = 0;
virtual OP_STATUS setFilterMode(FilterMode minFilter, FilterMode magFilter) = 0;
virtual FilterMode getMinFilter() = 0;
virtual FilterMode getMagFilter() = 0;
OP_STATUS slowPathUpdate(unsigned int w, unsigned int h, void *&pixels, unsigned int rowAlignment, bool yFlip, bool premultiplyAlpha, VEGAPixelStoreFormat storeFormat, VEGAPixelStoreFormat requestedFormat);
};
class VEGA3dRenderbufferObject : public VEGARefCount
{
protected:
VEGA3dRenderbufferObject()
{}
virtual ~VEGA3dRenderbufferObject()
{}
public:
enum ColorFormat
{
FORMAT_RGBA8, // RGBA8 is not supported on OpenGL ES, so be very careful about using it
FORMAT_RGBA4,
FORMAT_RGB565,
FORMAT_RGB5_A1,
FORMAT_STENCIL8,
FORMAT_DEPTH16,
FORMAT_DEPTH16_STENCIL8
};
virtual unsigned int getWidth() = 0;
virtual unsigned int getHeight() = 0;
virtual ColorFormat getFormat() = 0;
virtual unsigned int getNumSamples() = 0;
virtual unsigned int getRedBits() = 0;
virtual unsigned int getGreenBits() = 0;
virtual unsigned int getBlueBits() = 0;
virtual unsigned int getAlphaBits() = 0;
virtual unsigned int getDepthBits() = 0;
virtual unsigned int getStencilBits() = 0;
};
class VEGA3dFramebufferObject : public VEGA3dRenderTarget, public VEGARefCount
{
protected:
VEGA3dFramebufferObject()
{}
virtual ~VEGA3dFramebufferObject()
{}
public:
virtual TargetType getType(){return VEGA3D_RT_TEXTURE;}
/** Attach a resource to the fbo. If attaching fails the fbo acts as if attach*(NULL) was called. */
virtual OP_STATUS attachColor(VEGA3dTexture* color, VEGA3dTexture::CubeSide side = VEGA3dTexture::CUBE_SIDE_NONE) = 0;
virtual OP_STATUS attachColor(VEGA3dRenderbufferObject* color) = 0;
virtual OP_STATUS attachDepth(VEGA3dRenderbufferObject* depth) = 0;
virtual OP_STATUS attachStencil(VEGA3dRenderbufferObject* stencil) = 0;
virtual OP_STATUS attachDepthStencil(VEGA3dRenderbufferObject* depthStencil) = 0;
virtual VEGA3dTexture* getAttachedColorTexture() = 0;
virtual VEGA3dRenderbufferObject* getAttachedColorBuffer() = 0;
virtual VEGA3dRenderbufferObject* getAttachedDepthStencilBuffer() = 0;
virtual unsigned int getRedBits() = 0;
virtual unsigned int getGreenBits() = 0;
virtual unsigned int getBlueBits() = 0;
virtual unsigned int getAlphaBits() = 0;
virtual unsigned int getDepthBits() = 0;
virtual unsigned int getStencilBits() = 0;
virtual unsigned int getSubpixelBits() = 0;
virtual unsigned int getSampleBuffers() = 0;
virtual unsigned int getSamples() = 0;
};
/** Abstract interface for a vertex or index buffer in the 3d hardware. */
class VEGA3dBuffer : public VEGARefCount
{
protected:
VEGA3dBuffer()
{}
virtual ~VEGA3dBuffer(){}
public:
/** Describes the usage pattern of a buffer.
*
* Mostly, which usage specifier is used makes no difference to
* the observed behaviour of the buffer. It only affects the
* performance. However, some usage specifiers will also change
* the behaviour, so make sure to read the documentation of the
* usage specifier you intend to use carefully.
*
* - STREAM buffers are typically only used once (or a few times)
* before being rewritten with new data.
*
* - STATIC buffers are typically initialized once (or
* infrequently) and then used many times.
*
* - DYNAMIC buffers are "plain old memory". The data is
* typically modified and used freely.
*
* - STREAM_DISCARD buffers have the same basic usage pattern as
* STREAM, but adds a behavioural change: every time any
* modification is done to any part of the buffer, the data in
* the rest of the buffer becomes undefined.
*/
enum Usage
{
STREAM_DISCARD,
STREAM,
STATIC,
DYNAMIC
};
/** Modify parts of the buffer data.
*
* Any use of the buffer before calling this method will see the
* old data, and any use of the buffer after calling this method
* will see the new data.
*
* @param offset offset (in bytes) from start of buffer to first
* byte to be modified
* @param size the number of bytes of data to copy
* @param data pointer to the new data that will be copied into
* the data store
* @return OpStatus::OK on success, an error otherwise.
*/
virtual OP_STATUS writeAtOffset(unsigned int offset, unsigned int size, void* data) = 0;
/** DEPRECATED alias for writeAtOffset(), for backwards
* compatibility. Will hopefully be removed one day.
*
* TODO: Add the COREAPI_DEPRECATED() macro. But that can wait a
* bit. No need to introduce a host of new warnings for everyone
* immediately.
*/
OP_STATUS update(unsigned int offset, unsigned int size, void* data)
{ return writeAtOffset(offset, size, data); }
/** This method does the exact same thing as writeAtOffset(index *
* elm_size, elm_count * elm_size, data). However, 'index' is
* chosen by this method rather than being passed in as a
* parameter.
*
* This difference allows this method to potentially choose more
* efficient mechanisms to modify the data. For example, by
* choosing parts of memory that are less likely to cause
* synchronization stalls.
*
* Note that the offset will be returned as an "index" rather
* than an "offset". That is, to find out how many bytes into
* the buffer the data was written, you have to multiply 'index'
* by 'elm_size'.
*
* The offset chosen will be aligned to the nearest multiple of
* 'elm_size' (in bytes). Also, the index returned will be a
* multiple of 4, as this allows the data to be used with
* getQuadIndexBuffer().
*
* This method potentially has higher performance than
* writeAtOffset(). So if it is easy to use this method instead
* of writeAtOffset(), it is recommended to use this method.
*
* But keep in mind that this method may overwrite random parts
* of the buffer. If this is something you need to write code to
* deal with, it is probably better to use writeAtOffset().
*
* As a corollary to that, if you use this method, chances are
* that the buffer you use should probably be STREAM_DISCARD.
*
* Using STREAM_DISCARD instead of STREAM is likely to give
* higher performance in most cases (and will never be worse),
* regardless of which of these methods you use. So if your
* buffer is a STREAM buffer, please check if the buffer can be
* changed to a STREAM_DISCARD buffer instead. (For other usage
* hints, the usage pattern itself may dominate the performance,
* so switching to STREAM_DISCARD is less likely to be a good
* idea.)
*
* @param elm_count the number of indices/vertices to add.
* @param elm_size the size of one index/vertex (in bytes).
* @param data pointer to the new data that will be copied into
* the data store
* @param index returns the index of the first vertex/index modified.
* @return OpStatus::OK on success, an error otherwise.
*/
virtual OP_STATUS writeAnywhere(unsigned int elm_count, unsigned int elm_size, void* data, unsigned int& index) = 0;
/** @returns the size of the buffer in bytes. */
virtual unsigned int getSize() = 0;
};
class VEGA3dVertexLayout : public VEGARefCount
{
protected:
VEGA3dVertexLayout()
{}
virtual ~VEGA3dVertexLayout(){}
public:
/** Type of vertex data
* - FLOATx is x floats
* - USHORTx is x 16-bit unsigned integers
* - SHORTx is x 16-bit signed integers
* - UBYTEx is x 8-bit unsigned integers
* - BYTEx is x 8-bit signed integers */
enum VertexType
{
FLOAT4,
FLOAT3,
FLOAT2,
FLOAT1,
USHORT4,
USHORT3,
USHORT2,
USHORT1,
SHORT4,
SHORT3,
SHORT2,
SHORT1,
UBYTE4,
UBYTE3,
UBYTE2,
UBYTE1,
BYTE4,
BYTE3,
BYTE2,
BYTE1,
NO_TYPE
};
/** Add an attribute data source at index 'index'.
For GL, this is the same index that's used with vertexAttrib*() and
enable/disableVertexAttribArray(). For D3D10, it's the semantic index
that will be used in the input layout specification (e.g. "foo :
TEXCOORD<n>". */
virtual OP_STATUS addComponent(VEGA3dBuffer* buffer, unsigned int index, unsigned int offset, unsigned int stride, VertexType type, bool normalize) = 0;
/* Add a constant attribute data source at index 'index'. */
virtual OP_STATUS addConstComponent(unsigned int index, float* values) = 0;
#ifdef CANVAS3D_SUPPORT
/** For backends that use the D3DAttribModel model, add a binding for the
attribute with name 'name' in the shader. */
virtual OP_STATUS addBinding(const char *name, VEGA3dBuffer* buffer, unsigned int offset, unsigned int stride, VertexType type, bool normalize)
{
OP_ASSERT(!"Not implemented");
return OpStatus::ERR;
}
/* For backends that use the D3DAttribModel model, add a constant binding
for the attribute with name 'name' in the shader. */
virtual OP_STATUS addConstBinding(const char *name, float* values)
{
OP_ASSERT(!"Not implemented");
return OpStatus::ERR;
}
#endif // CANVAS3D_SUPPORT
};
class VEGA3dRenderState
{
public:
/** Blend operations used by blend functions. */
enum BlendOp
{
BLEND_OP_ADD = 0,
BLEND_OP_SUB,
BLEND_OP_REVERSE_SUB,
NUM_BLEND_OPS
};
/** Blend weight used by blend functions. */
enum BlendWeight
{
BLEND_ONE = 0,
BLEND_ZERO,
BLEND_SRC_ALPHA,
BLEND_ONE_MINUS_SRC_ALPHA,
BLEND_DST_ALPHA,
BLEND_ONE_MINUS_DST_ALPHA,
BLEND_SRC_COLOR,
BLEND_ONE_MINUS_SRC_COLOR,
BLEND_DST_COLOR,
BLEND_ONE_MINUS_DST_COLOR,
BLEND_CONSTANT_COLOR,
BLEND_ONE_MINUS_CONSTANT_COLOR,
BLEND_CONSTANT_ALPHA,
BLEND_ONE_MINUS_CONSTANT_ALPHA,
BLEND_SRC_ALPHA_SATURATE,
BLEND_EXTENDED_SRC1_COLOR,
BLEND_EXTENDED_SRC1_ALPHA,
BLEND_EXTENDED_ONE_MINUS_SRC1_COLOR,
BLEND_EXTENDED_ONE_MINUS_SRC1_ALPHA,
NUM_BLEND_WEIGHTS
};
/** Depth test functions used by the 3d device. */
enum DepthFunc
{
DEPTH_NEVER = 0,
DEPTH_EQUAL,
DEPTH_LESS,
DEPTH_LEQUAL,
DEPTH_GREATER,
DEPTH_GEQUAL,
DEPTH_NOTEQUAL,
DEPTH_ALWAYS,
NUM_DEPTH_FUNCS
};
/** Stencil test functions used by the 3d device. */
enum StencilFunc
{
STENCIL_LESS = 0,
STENCIL_LEQUAL,
STENCIL_GREATER,
STENCIL_GEQUAL,
STENCIL_EQUAL,
STENCIL_NOTEQUAL,
STENCIL_ALWAYS,
STENCIL_NEVER,
NUM_STENCIL_FUNCS
};
/** Stencil operations used to modify stencil data. If the operation
* is set to increase/decrease wrap and it is not supported the
* non wrapping equivalent will be used instead. */
enum StencilOp
{
STENCIL_KEEP = 0,
STENCIL_INVERT,
STENCIL_INCR,
STENCIL_DECR,
STENCIL_ZERO,
STENCIL_REPLACE,
STENCIL_INCR_WRAP,
STENCIL_DECR_WRAP,
NUM_STENCIL_OPS
};
/** Faces to cull. */
enum Face
{
FACE_BACK = 0,
FACE_FRONT,
NUM_FACES
};
VEGA3dRenderState();
virtual ~VEGA3dRenderState();
/** Set the current blend mode. */
void enableBlend(bool enabled);
bool isBlendEnabled();
/** Set the constant blend color. */
void setBlendColor(float r, float g, float b, float a);
void getBlendColor(float& r, float& g, float& b, float& a);
/** Set the blend operation to modify the blend mode. */
void setBlendEquation(BlendOp op, BlendOp opA = NUM_BLEND_OPS);
void getBlendEquation(BlendOp& op, BlendOp& opA);
/** Set the blend weights to modify the blend mode. */
void setBlendFunc(BlendWeight src, BlendWeight dst, BlendWeight srcA = NUM_BLEND_WEIGHTS, BlendWeight dstA = NUM_BLEND_WEIGHTS);
void getBlendFunc(BlendWeight& src, BlendWeight& dst, BlendWeight& srcA, BlendWeight& dstA);
/** Set the color mask for the r, g, b and a color planes. */
void setColorMask(bool r, bool g, bool b, bool a);
void getColorMask(bool& r, bool& g, bool& b, bool& a);
/** Set the culling and enable/disable culling. */
void enableCullFace(bool enabled);
bool isCullFaceEnabled();
void setCullFace(Face face);
void getCullFace(Face& face);
/** Set the depth test function and enable/disable depth testing. */
void enableDepthTest(bool enabled);
bool isDepthTestEnabled();
void setDepthFunc(DepthFunc test);
void getDepthFunc(DepthFunc& test);
void enableDepthWrite(bool write);
bool isDepthWriteEnabled();
void enableDither(bool enable);
bool isDitherEnabled();
void enablePolygonOffsetFill(bool enable);
bool isPolygonOffsetFillEnabled();
void polygonOffset(float factor, float units);
void enableSampleToAlphaCoverage(bool enable);
bool isSampleToAlphaCoverageEnabled();
void enableSampleCoverage(bool enable);
bool isSampleCoverageEnabled();
void sampleCoverage(bool invert, float value);
void lineWidth(float w);
float getLineWidth();
float getPolygonOffsetFactor();
float getPolygonOffsetUnits();
bool getSampleCoverageInvert();
float getSampleCoverageValue();
/** Change the front face. */
void setFrontFaceCCW(bool front);
bool isFrontFaceCCW();
/** Set the stencil test function and enable/disable stencil testing. */
void enableStencil(bool enabled);
bool isStencilEnabled();
void setStencilFunc(StencilFunc func, StencilFunc funcBack, unsigned int reference, unsigned int mask);
void getStencilFunc(StencilFunc& func, StencilFunc& funcBack, unsigned int& reference, unsigned int& mask);
/** Set the stencil write mask. */
void setStencilWriteMask(unsigned int mask);
void getStencilWriteMask(unsigned int& mask);
/** Set the stencil update operation. */
void setStencilOp(StencilOp fail, StencilOp zFail, StencilOp pass, StencilOp failBack = NUM_STENCIL_OPS, StencilOp zFailBack = NUM_STENCIL_OPS, StencilOp passBack = NUM_STENCIL_OPS);
void getStencilOp(StencilOp& fail, StencilOp& zFail, StencilOp& pass, StencilOp& failBack, StencilOp& zFailBack, StencilOp& passBack);
/** Enable/disable stencil testing. */
void enableScissor(bool enabled);
bool isScissorEnabled();
void clearChanged(){m_changed = false;}
bool isChanged(){return m_changed;}
bool colorMaskChanged(const VEGA3dRenderState& current);
bool blendColorChanged(const VEGA3dRenderState& current);
bool blendEquationChanged(const VEGA3dRenderState& current);
bool blendFuncChanged(const VEGA3dRenderState& current);
/** @returns true if the blend has changed compared to current.
* Always returns false if blend is disabled.
* This does _not_ include enable/disable changes. */
bool blendChanged(const VEGA3dRenderState& current);
/** @returns true if the blend has changed compared to current.
* Always returns false if blend is disabled.
* This does _not_ include enable/disable changes. */
bool cullFaceChanged(const VEGA3dRenderState& current);
/** @returns true if the depth test has changed compared to current.
* Always returns false if depth test is disabled.
* This does _not_ include enable/disable changes. */
bool depthFuncChanged(const VEGA3dRenderState& current);
/** @retval true if either the 'offset' or the 'units' value as set
* by polygonOffset() has changed compared to 'current'. */
bool polygonOffsetChanged(const VEGA3dRenderState& current) const;
/** @returns true if the depth test has changed compared to current.
* Always returns false if stencil is disabled.
* This does _not_ include enable/disable changes. */
bool stencilChanged(const VEGA3dRenderState& current);
virtual bool isImplementationSpecific(){return false;}
private:
bool m_changed;
bool m_blendEnabled;
BlendOp m_blendOp;
BlendOp m_blendOpA;
BlendWeight m_blendSrc;
BlendWeight m_blendDst;
BlendWeight m_blendSrcA;
BlendWeight m_blendDstA;
float m_blendConstColor[4];
bool m_colorMaskR;
bool m_colorMaskG;
bool m_colorMaskB;
bool m_colorMaskA;
bool m_cullFaceEnabled;
Face m_cullFace;
bool m_depthTestEnabled;
DepthFunc m_depthTest;
bool m_depthWriteEnabled;
bool m_isFrontFaceCCW;
bool m_stencilEnabled;
StencilFunc m_stencilTest;
StencilFunc m_stencilTestBack;
unsigned int m_stencilReference;
unsigned int m_stencilMask;
unsigned int m_stencilWriteMask;
StencilOp m_stencilOpFail;
StencilOp m_stencilOpZFail;
StencilOp m_stencilOpPass;
StencilOp m_stencilOpFailBack;
StencilOp m_stencilOpZFailBack;
StencilOp m_stencilOpPassBack;
bool m_scissorEnabled;
bool m_ditherEnabled;
bool m_polygonOffsetFillEnabled;
float m_polygonOffsetFactor;
float m_polygonOffsetUnits;
bool m_sampleToAlphaCoverageEnabled;
bool m_sampleCoverageEnabled;
bool m_sampleCoverageInvert;
float m_sampleCoverageValue;
float m_lineWidth;
};
#ifdef CANVAS3D_SUPPORT
/** Vertex or fragment shader */
class VEGA3dShader
{
public:
virtual ~VEGA3dShader() {}
virtual BOOL isFragmentShader() = 0;
virtual BOOL isVertexShader() = 0;
};
#endif // CANVAS3D_SUPPORT
class VEGA3dShaderProgram : public VEGARefCount
{
protected:
VEGA3dShaderProgram() : m_orthoWidth(-1), m_orthoHeight(-1), m_worldProjLocation(-1)
{}
virtual ~VEGA3dShaderProgram() {}
public:
// SHADER_<S>_<T>
enum WrapMode
{
WRAP_REPEAT_REPEAT = 0,
WRAP_REPEAT_MIRROR,
WRAP_REPEAT_CLAMP,
WRAP_MIRROR_REPEAT,
WRAP_MIRROR_MIRROR,
WRAP_MIRROR_CLAMP,
WRAP_CLAMP_REPEAT,
WRAP_CLAMP_MIRROR,
WRAP_CLAMP_CLAMP,
WRAP_MODE_COUNT // last!
};
static WrapMode GetWrapMode(VEGA3dTexture* tex)
{
return tex ? (WrapMode)(3*tex->getWrapModeS() + tex->getWrapModeT()) : WRAP_CLAMP_CLAMP;
}
enum ShaderType
{
SHADER_VECTOR2D = 0,
// 8 extra blends
SHADER_VECTOR2DTEXGEN,
// 8 extra blends
SHADER_VECTOR2DTEXGENRADIAL,
SHADER_VECTOR2DTEXGENRADIALSIMPLE,
SHADER_TEXT2D,
SHADER_TEXT2DTEXGEN,
SHADER_TEXT2DEXTBLEND,
SHADER_TEXT2DEXTBLENDTEXGEN,
SHADER_TEXT2D_INTERPOLATE,
SHADER_TEXT2DTEXGEN_INTERPOLATE,
SHADER_TEXT2DEXTBLEND_INTERPOLATE,
SHADER_TEXT2DEXTBLENDTEXGEN_INTERPOLATE,
SHADER_COLORMATRIX,
SHADER_COMPONENTTRANSFER,
SHADER_DISPLACEMENT,
SHADER_LUMINANCE_TO_ALPHA,
SHADER_SRGB_TO_LINEARRGB,
SHADER_LINEARRGB_TO_SRGB,
SHADER_MERGE_ARITHMETIC,
SHADER_MERGE_MULTIPLY,
SHADER_MERGE_SCREEN,
SHADER_MERGE_DARKEN,
SHADER_MERGE_LIGHTEN,
SHADER_LIGHTING_DISTANTLIGHT,
SHADER_LIGHTING_POINTLIGHT,
SHADER_LIGHTING_SPOTLIGHT,
SHADER_LIGHTING_MAKE_BUMP,
SHADER_CONVOLVE_GEN_16,
// 1 extra blend
SHADER_CONVOLVE_GEN_16_BIAS,
// 1 extra blend
SHADER_CONVOLVE_GEN_25_BIAS,
// 1 extra blend
SHADER_MORPHOLOGY_DILATE_15,
// 1 extra blend
SHADER_MORPHOLOGY_ERODE_15,
// 1 extra blend
SHADER_CUSTOM,
NUM_SHADERS,
NUM_ACTUAL_SHADERS = NUM_SHADERS + 8/* blends of vector2d */ + 8/* blends of vector2dtexgen */ + 3/* blends of convolve* */ + 2/* blends of morphology* */
};
/** returns the shader index of the combination of type and mode, which are
* assumed to be a valid combination. useful eg when keeping an array of
* NUM_ACTUAL_SHADERS shaders.
* @param type the shader type
* @param mode the shader mode
* @return the index of the shader with combination of type and mode
*/
static size_t GetShaderIndex(ShaderType type, WrapMode mode);
enum ShaderLanguage
{
SHADER_GLSL = 1,
SHADER_GLSL_ES,
SHADER_HLSL_9,
SHADER_HLSL_10
};
virtual ShaderType getShaderType() = 0;
#ifdef CANVAS3D_SUPPORT
/** For custom shaders. */
virtual OP_STATUS addShader(VEGA3dShader* shader) = 0;
virtual OP_STATUS removeShader(VEGA3dShader* shader) = 0;
/// NOTE: may overwrite global 2k temp-buffer
virtual OP_STATUS link(OpString *info_log) = 0;
virtual OP_STATUS setAsRenderTarget(VEGA3dRenderTarget *target) = 0;
virtual OP_STATUS validate() = 0;
virtual bool isValid() = 0;
virtual unsigned int getNumInputs() = 0;
virtual unsigned int getNumConstants() = 0;
// Remember to update nComponentsForType as well if you change this!
enum ConstantType
{
SHDCONST_FLOAT = 0,
SHDCONST_FLOAT2,
SHDCONST_FLOAT3,
SHDCONST_FLOAT4,
SHDCONST_INT,
SHDCONST_INT2,
SHDCONST_INT3,
SHDCONST_INT4,
SHDCONST_BOOL,
SHDCONST_BOOL2,
SHDCONST_BOOL3,
SHDCONST_BOOL4,
SHDCONST_MAT2,
SHDCONST_MAT3,
SHDCONST_MAT4,
SHDCONST_SAMP2D,
SHDCONST_SAMPCUBE,
SHDCONST_NONE,
N_SHDCONSTS
};
// Maps vector and matrix ConstantType's to the number of components
// (floats or ints) in the type. Maps sampler types to 1 and SHDCONST_NONE
// to 0.
static const unsigned nComponentsForType[N_SHDCONSTS];
virtual unsigned int getInputMaxLength() = 0;
virtual unsigned int getConstantMaxLength() = 0;
/* Returns the names of the n attributes of the program (in some arbitrary
order) for idx = 0..n-1.
@retval OpStatus::OK if idx < n and no error occurs.
@retval OpStatus::ERR otherwise. */
/// NOTE: may overwrite global 2k temp-buffer
virtual OP_STATUS indexToAttributeName(unsigned idx, const char **name) = 0;
/** NOTE: may overwrite global 2k temp-buffer
* NOTE2: this function differs from glGetActiveUniform in that the
* returned name does _NOT_ end with "[0]" for array constants. */
virtual OP_STATUS getConstantDescription(unsigned int idx, ConstantType* type, unsigned int* size, const char** name) = 0;
virtual OP_STATUS setInputLocation(const char* name, int idx) { OP_ASSERT(!"Not implemented. Only used for OpenGL-style attributes."); return OpStatus::ERR; }
#endif // CANVAS3D_SUPPORT
virtual int getConstantLocation(const char* name) = 0;
/** Change the value of a shader constant (uniform). This may only be called when the
* shader program is bound. */
virtual OP_STATUS setScalar(int idx, float val) = 0;
virtual OP_STATUS setScalar(int idx, int val) = 0;
virtual OP_STATUS setScalar(int idx, float* val, int count = 1) = 0;
virtual OP_STATUS setScalar(int idx, int* val, int count = 1) = 0;
virtual OP_STATUS setVector2(int idx, float* val, int count = 1) = 0;
virtual OP_STATUS setVector2(int idx, int* val, int count = 1) = 0;
virtual OP_STATUS setVector3(int idx, float* val, int count = 1) = 0;
virtual OP_STATUS setVector3(int idx, int* val, int count = 1) = 0;
virtual OP_STATUS setVector4(int idx, float* val, int count = 1) = 0;
virtual OP_STATUS setVector4(int idx, int* val, int count = 1) = 0;
virtual OP_STATUS setMatrix2(int idx, float* val, int count = 1, bool transpose = false) = 0;
virtual OP_STATUS setMatrix3(int idx, float* val, int count = 1, bool transpose = false) = 0;
virtual OP_STATUS setMatrix4(int idx, float* val, int count = 1, bool transpose = false) = 0;
#ifdef CANVAS3D_SUPPORT
virtual OP_STATUS getConstantValue(int idx, float* val, VEGA3dShaderProgram::ConstantType type, int arrayIndex) = 0;
virtual OP_STATUS getConstantValue(int idx, int* val, VEGA3dShaderProgram::ConstantType type, int arrayIndex) = 0;
#endif // CANVAS3D_SUPPORT
OP_STATUS setOrthogonalProjection();
OP_STATUS setOrthogonalProjection(unsigned int width, unsigned int height);
void invalidateOrthogonalProjection(){m_orthoWidth = -1; m_orthoHeight = -1;}
/** Sub classes may implement this in order to signal that the
* last projection matrix returned by
* VEGA3dDevice::loadOrthogonalProjection is no longer valid.
* @returns true if loadOrthogonalProjection needs to be called
* and false otherwise. */
virtual bool orthogonalProjectionNeedsUpdate() { return false; }
#ifdef CANVAS3D_SUPPORT
virtual bool isAttributeActive(int /* idx */)
{
OP_ASSERT(!"Not implemented. Only used for VEGA3dDevice::GLAttribModel.");
return false;
}
#endif // CANVAS3D_SUPPORT
private:
int m_orthoWidth;
int m_orthoHeight;
int m_worldProjLocation;
};
#ifdef VEGA_BACKENDS_USE_BLOCKLIST
struct VEGABlocklistFileEntry;
# define VEGA_3D_BLOCKLIST_ENTRY_DECL VEGABlocklistFileEntry* blocklist_entry
# define VEGA_3D_BLOCKLIST_ENTRY_PASS blocklist_entry
#else // VEGA_BACKENDS_USE_BLOCKLIST
# define VEGA_3D_BLOCKLIST_ENTRY_DECL
# define VEGA_3D_BLOCKLIST_ENTRY_PASS
#endif // VEGA_BACKENDS_USE_BLOCKLIST
/** Abstract interface to a hardware 3d device. */
class VEGA3dDevice
#ifdef VEGA_BACKENDS_USE_BLOCKLIST
: public VEGABlocklistDevice
#endif // VEGA_BACKENDS_USE_BLOCKLIST
{
public:
enum UseCase
{
For2D, ///< create/use the device unless blocked for 2D
For3D, ///< create/use the device unless blocked for 3D
Force ///< create/use the device if at all possible
};
/** Used in the WebGL implementation.
Represents how samplers in shaders map to texture units for the
back-end.
In the SamplersAreTextureUnits model, each sampler corresponds to a
texture unit and cannot be reassigned to a different texture unit. To
set a sampler in this model, we set its corresponding texture unit. D3D
uses this model.
In the SamplerValuesAreTextureUnits model, samplers are variables, and
the value of a sampler determines the texture unit from which the
texture will be taken. OpenGL uses this model.
This information is used e.g. when mapping the "virtual" WebGL texture
units onto the back-end's texture units. */
enum SamplerModel
{
SamplersAreTextureUnits,
SamplerValuesAreTextureUnits
};
/** Used in the WebGL implementation.
Represents different models for handling attributes in the back-end,
which influence how we do things in the front-end.
In the GLAttribModel model, we have a number of independent attribute
data sources (configured with e.g. vertexAttrib[Pointer]()) that
shaders bind to (using e.g. bindAttribLocation()). The natural (and
likely most efficient) approach here is to simply sync these data
sources between the front-end and the back-end.
In the D3DAttribModel model, we lack this level of indirection, and
resources are bound directly to shader inputs using input layouts. The
natural approach here is to simply bind each data source directly to
the attribute (if any) that uses it.
To be able to accommodate both models, we virtualize the attribute data
sources in the WebGL front-end and delay setting up shader inputs in
the way appropriate for each model until draw time. */
enum AttribModel
{
GLAttribModel,
D3DAttribModel
};
// Functionality associated with creation
private:
friend class VEGA3dDeviceFactory;
/** Called from public blend of VEGA3dDeviceFactory::Create.
* Takes care of blocklist status and calls Construct.
* @param use_case under what circumstances to create a device
*/
OP_STATUS ConstructDevice(UseCase use_case);
protected:
/// Creation of VEGA3dDevice is done through VEGA3dDeviceFactory
VEGA3dDevice();
/** First-level init - called from private blend of of
* VEGA3dDeviceFactory::Create. This function should initialize
* the device enough so that VEGABlocklistDevice::DataProvider can
* do what it should.
*/
virtual OP_STATUS Init() = 0;
/// Second-level init - should initialize the device completely.
virtual OP_STATUS Construct(VEGA_3D_BLOCKLIST_ENTRY_DECL) = 0;
public:
virtual ~VEGA3dDevice();
/// should always be called before deleting
virtual void Destroy(){}
#ifdef VEGA_BACKENDS_USE_BLOCKLIST
// cludge: allow VEGABlocklistDevice to call VEGA3dDevice::ConstructDevice
virtual OP_STATUS Construct3dDevice() { return ConstructDevice(For2D); }
friend class VEGABlocklistDevice;
#endif // VEGA_BACKENDS_USE_BLOCKLIST
/// for opera:gpu - generate info for all available backends
static OP_STATUS GenerateBackendInfo(class OperaGPU* gpu);
/** Check if the device can be used for the given use case
* @param use_case the desired use of the device
*/
OP_STATUS CheckUseCase(UseCase use_case);
void RegisterContextLostListener(VEGA3dContextLostListener* list){list->Into(&m_contextLostListeners);}
void UnregisterContextLostListener(VEGA3dContextLostListener* list){list->Out();}
/** @returns a short name used to describe the renderer.
* For example "GL"*/
virtual const uni_char* getName() = 0;
/** @returns a slightly longer string used to describe this renderer.
* For example "OpenGL ES 2.0". */
virtual const uni_char* getDescription() const = 0;
/// @return the device type id of the device - see VEGA3dDeviceFactory::Create
virtual unsigned int getDeviceType() const = 0;
/** @return the current sampler model - see VEGA3dDevice::SamplerModel */
virtual SamplerModel getSamplerModel() const = 0;
/** @return the current attribute model - see VEGA3dDevice::AttribModel */
virtual AttribModel getAttribModel() const = 0;
/** @return true if the device is capable of creating multisampled
* renderbuffers. */
virtual bool supportsMultisampling() = 0;
/** Flush makes sure the current drawing operations are finished but they do not have to be presented. */
virtual void flush() = 0;
enum Primitive
{
PRIMITIVE_TRIANGLE = 0,
PRIMITIVE_TRIANGLE_STRIP,
PRIMITIVE_POINT,
PRIMITIVE_LINE,
PRIMITIVE_LINE_LOOP, // NEVER use this with a DX9/10 backend as it goes to a slow case.
PRIMITIVE_LINE_STRIP,
PRIMITIVE_TRIANGLE_FAN, // NEVER use this with a DX10 backend as it goes to a slow case.
NUM_PRIMITIVES
};
/** Create a new render state instance to keep track of and
* change all rendering states. If copyCurrentState is true the
* initial state will be the state currently used by the renderer. */
virtual OP_STATUS createRenderState(VEGA3dRenderState** state, bool copyCurrentState) = 0;
/** Set a new rendering state as active. If the same state is
* set as active and it has not changed nothing should happen. */
virtual OP_STATUS setRenderState(VEGA3dRenderState* state) = 0;
/** @ Returns true if the extended blend functions are available, false otherwise. */
virtual bool hasExtendedBlend() = 0;
/** Set the current scissor rect. This is only used when the current state
* has scissor enabled. */
virtual void setScissor(int x, int y, unsigned int w, unsigned int h) = 0;
/** Clear the buffers.
* @param color clear the color buffer
* @param depth clear the depth buffer
* @param stencil clear the stencil buffer */
virtual void clear(bool color, bool depth, bool stencil, UINT32 colorVal, float depthVal, int stencilVal) = 0;
/** Bind a texture. binding NULL will disable texture mapping. */
virtual void setTexture(unsigned int unit, VEGA3dTexture* tex) = 0;
virtual void setCubeTexture(unsigned int unit, VEGA3dTexture* tex) = 0;
/** Get the maximum number of vertex attributes that can be used. */
virtual unsigned int getMaxVertexAttribs() const = 0;
/** Get what size of temporary vertex buffers should be used. */
virtual unsigned int getVertexBufferSize() const {return VEGA_TEMP_VERTEX_BUFFER_SIZE;}
virtual void getAliasedPointSizeRange(float &low, float &high) = 0;
virtual void getAliasedLineWidthRange(float &low, float &high) = 0;
virtual unsigned int getMaxCubeMapTextureSize() const = 0;
virtual unsigned int getMaxFragmentUniformVectors() const = 0;
virtual unsigned int getMaxRenderBufferSize() const = 0;
virtual unsigned int getMaxTextureSize() const = 0;
virtual unsigned int getMaxMipLevel() const = 0;
virtual unsigned int getMaxVaryingVectors() const = 0;
virtual unsigned int getMaxVertexTextureUnits() const = 0;
virtual unsigned int getMaxFragmentTextureUnits() const = 0;
virtual unsigned int getMaxCombinedTextureUnits() const = 0;
virtual unsigned int getMaxVertexUniformVectors() const = 0;
virtual void getMaxViewportDims(int &w, int &h) const = 0;
/// max number of samples supported by GPU (for RGBA32)
virtual unsigned int getMaxQuality() const = 0;
unsigned int getDefaultQuality()
{
const unsigned int q = getMaxQuality();
return q <= VEGA_DEFAULT_QUALITY ? q : VEGA_DEFAULT_QUALITY;
}
/** Return the shader language + version the programs are expected as. */
virtual VEGA3dShaderProgram::ShaderLanguage getShaderLanguage(unsigned int &version) = 0;
/** A (flat) namespace of extensions that a backend might be
asked if it supports. */
enum Extension
{
OES_STANDARD_DERIVATIVES = 0,
OES_TEXTURE_NPOT,
MAX_EXTENSIONS
};
virtual bool supportsExtension(Extension e) { return false; }
/** Create a shader of type <shdtype>
* SHADER_CONVOLVE_GEN_25_BIAS will fail to initialize for DirectX 10 Level 9.1 hardware*/
virtual OP_STATUS createShaderProgram(VEGA3dShaderProgram** shader, VEGA3dShaderProgram::ShaderType shdtype, VEGA3dShaderProgram::WrapMode shdmode) = 0;
/** Set the shader to use. If NULL then the
* device will switch back to fixed-function operation. */
virtual OP_STATUS setShaderProgram(VEGA3dShaderProgram* shader) = 0;
/** Get the current shader program used by the device.
* @returns the current shader program. */
virtual VEGA3dShaderProgram* getCurrentShaderProgram() = 0;
#ifdef CANVAS3D_SUPPORT
/** Attribute names and their known size (in 'float' units.) */
struct AttributeData
{
char* name;
unsigned int size;
};
virtual OP_STATUS createShader(VEGA3dShader** shader, BOOL fragmentShader, const char* source, unsigned int attribute_count, AttributeData *attributes, OpString *info_log) = 0;
#endif // CANVAS3D_SUPPORT
/** Draw primitives from the vertex array described by the vertex
* layout. */
virtual OP_STATUS drawPrimitives(Primitive type, VEGA3dVertexLayout* layout, unsigned int firstVert, unsigned int numVerts) = 0;
/** Draw primitives from the vertex array described by the vertex
* layout using the indices in the index buffer. */
virtual OP_STATUS drawIndexedPrimitives(Primitive type, VEGA3dVertexLayout* verts, VEGA3dBuffer* ibuffer, unsigned int bytesPerInd, unsigned int firstInd, unsigned int numInd) = 0;
/** Create a texture. If width and height are not power of two they might be rounded up to nearest power of two,
* but the content width/height will be the specified values. */
virtual OP_STATUS createTexture(VEGA3dTexture** texture, unsigned int width, unsigned int height, VEGA3dTexture::ColorFormat fmt, bool mipmaps = false, bool as_rendertarget = true) = 0;
virtual OP_STATUS createCubeTexture(VEGA3dTexture** texture, unsigned int size, VEGA3dTexture::ColorFormat fmt, bool mipmaps = false, bool as_rendertarget = true) = 0;
virtual OP_STATUS createFramebuffer(VEGA3dFramebufferObject** fbo) = 0;
virtual OP_STATUS createRenderbuffer(VEGA3dRenderbufferObject** rbo, unsigned int width, unsigned int height, VEGA3dRenderbufferObject::ColorFormat, int multisampleQuality = 0) = 0;
/** Copy the currently bound multisample framebuffer to the given non-multisample
* framebuffer. */
virtual OP_STATUS resolveMultisample(VEGA3dRenderTarget* rt, unsigned int x, unsigned int y, unsigned int w, unsigned int h) = 0;
#ifdef VEGA_3DDEVICE
/** Create a window which can be used as a target for 3d rendering. */
virtual OP_STATUS createWindow(VEGA3dWindow** win, VEGAWindow* nativeWin) = 0;
#endif // VEGA_3DDEVICE
/** Create a buffer of the specified size and usage. A buffer can be used as either a
* vertex buffer or an index buffer.
* @param buffer the created buffer.
* @param size the size of the buffer.
* @param usage the usage of the buffer (stream, dynamic or static).
* @param deferredUpdate the buffer may be used with non aligned data and non-float types which may cause it to be rearranged.
* @returns OpStatus::OK on success, an error otherwise. */
virtual OP_STATUS createBuffer(VEGA3dBuffer** buffer, unsigned int size, VEGA3dBuffer::Usage usage, bool indexBuffer, bool deferredUpdate = false) = 0;
/** Create a vertex layout which is used to map buffers to the shader. */
virtual OP_STATUS createVertexLayout(VEGA3dVertexLayout** layout, VEGA3dShaderProgram* sprog) = 0;
/** Set the current render target. */
virtual OP_STATUS setRenderTarget(VEGA3dRenderTarget* rt, bool changeViewport = true) = 0;
/** @returns the current render target. */
virtual VEGA3dRenderTarget* getRenderTarget() = 0;
/** Change the viewport used for rendering. */
virtual void setViewport(int viewportX, int viewportY, int viewportWidth, int viewportHeight, float viewportNear, float viewportFar) = 0;
/** Load an orthogonal transform from 0,0 to width,height for the current render target.
* @param transform the transform t store the projection matrix in. */
virtual void loadOrthogonalProjection(VEGATransform3d& transform) = 0;
/** Load an orthogonal transform from 0,0 to width,height.
* @param transform the transform t store the projection matrix in.
* @param w the width of the render target
* @param h the height of the render target */
virtual void loadOrthogonalProjection(VEGATransform3d& transform, unsigned int w, unsigned int h) = 0;
/** Framebuffer data parameters representing an area of the frame buffer. */
struct FramebufferData
{
VEGAPixelStore pixels;
unsigned int x;
unsigned int y;
unsigned int w;
unsigned int h;
void* privateData;
};
/** Lock a rect in the frame buffer. The data parameter passed to this
* function must contain x, y, w and h parameters to specify which area
* of the framebuffer to get.
* @param data area to get from the framebuffer and resulting data
* array.
* @param readPixels require the pixels to be read. It is much faster
* if this parameter is false, so use false if you are only going to
* write data.
* @returns OpStatus::OK on success, an error otherwise. */
virtual OP_STATUS lockRect(FramebufferData* data, bool readPixels) = 0;
/** Unlock a rectangle locked by lockRect.
* @param data the buffer to unlock.
* @param modified write the data back to the framebuffer. Set this to
* false if there is no need to update the framebuffer since updating it
* is slow. */
virtual void unlockRect(FramebufferData* data, bool modified) = 0;
/** Copy the current frame buffer to a texture.
* @param tex the texture to copy framebuffer data to.
* @param side Side in the cube map to update or CUBE_SIDE_NONE if a regular 2d texture.
* @param level the miplevel to copy framebuffer data to.
* @param texx, texy the coord in the texture which the framebuffer
* data will be copied to.
* @param x, y, w, h the rectangle in the framebuffer data to copy.
* @return OpStatus::OK on success, an error otherwise. */
virtual OP_STATUS copyToTexture(VEGA3dTexture* tex, VEGA3dTexture::CubeSide side, int level, int texx, int texy, int x, int y, unsigned int w, unsigned int h) = 0;
/** Mark the entire rendertarget as clean. Called by the platform
* implementation of the 3d device. */
void validate()
{
invalidLeft = ~0u;
invalidTop = ~0u;
invalidRight = 0;
invalidBottom = 0;
}
/** Make a section of the rendertarget invalid. Called by vega. */
void invalidate(unsigned int left, unsigned int top, unsigned int right, unsigned int bottom)
{
if (right > invalidRight)
invalidRight = right;
if (bottom > invalidBottom)
invalidBottom = bottom;
if (left < invalidLeft)
invalidLeft = left;
if (top < invalidTop)
invalidTop = top;
}
/** Create filters using special hardware accelerated apply functions.
* If a filter does not support any special hardware acceleration (such
* as shaders), just return OpStatus::ERR to create a software fallback
* (or in some cases hardware accelerated fallback without shaders). */
virtual OP_STATUS createMergeFilter(class VEGAFilterMerge** f){return OpStatus::ERR;}
virtual OP_STATUS createConvolveFilter(class VEGAFilterConvolve** f){return OpStatus::ERR;}
virtual OP_STATUS createMorphologyFilter(class VEGAFilterMorphology** f){return OpStatus::ERR;}
virtual OP_STATUS createGaussianFilter(class VEGAFilterGaussian** f){return OpStatus::ERR;}
virtual OP_STATUS createLightingFilter(class VEGAFilterLighting** f){return OpStatus::ERR;}
virtual OP_STATUS createColorTransformFilter(class VEGAFilterColorTransform** f){return OpStatus::ERR;}
virtual OP_STATUS createDisplaceFilter(class VEGAFilterDisplace** f){return OpStatus::ERR;}
virtual bool fullNPotSupport() = 0;
// Small helper functions for 3d devices
/** Check if a number is a power of two. */
static inline bool isPow2(unsigned int n)
{
return !(n&(n-1));
}
/** @returns the nearest power of two greater than the number. */
static inline unsigned int pow2_ceil(unsigned int n)
{
if (!(n&(n-1)))
return n;
while (n&(n-1))
n&=(n-1);
return n<<1;
}
/** @returns the nearest power of two less than the number. */
static inline unsigned int pow2_floor(unsigned int n)
{
while (n&(n-1))
n&=(n-1);
return n;
}
/** @returns the integer log2 of the number defined in the range n > 0. */
static inline unsigned int ilog2_floor(unsigned int n)
{
unsigned int i = 0;
while (n > 1)
{
n /= 2;
++i;
}
return i;
}
struct Vega2dVertex
{
float x, y;
float s, t;
UINT32 color;
};
/** Convert a vega color to a color in the native representation used
* by the 3d hardware. */
virtual UINT32 convertToNativeColor(UINT32 color) = 0;
OP_STATUS createDefault2dObjects();
void destroyDefault2dObjects();
/** Get a temporary buffer of at least the requested size if one exists, otherwise returns NULL. */
VEGA3dBuffer* getTempBuffer(unsigned int size);
/** Return an index buffer representing quads in an order resembling triangle fans using 6 indices per quad.
* If the requested size is too large NULL will be returned. */
VEGA3dBuffer* getQuadIndexBuffer(unsigned int numverts);
/** Create a vertex layout for Vega2dVertex usable with the specified shader type.
* This is a helper function to allow the 3d device to cache better, so use it if possible. */
OP_STATUS createVega2dVertexLayout(VEGA3dVertexLayout** layout, VEGA3dShaderProgram::ShaderType shdtype);
/** Get buffers for storing triangle indices. */
void getTriangleIndexBuffers(VEGA3dBuffer** triangleIndexBuffer, unsigned short** triangleIndices)
{ *triangleIndexBuffer = m_triangleIndexBuffer; *triangleIndices = m_triangleIndices; }
/** Returns the number of triangle indices the triangle index buffer can hold */
unsigned int getTriangleIndexBufferSize() { return 3*(VEGA_TEMP_VERTEX_BUFFER_SIZE-2); }
/** Get a temporary rgba texture which can be used as a render target
* with a size of at least w x h to use the copy to texture moveRect.
* @returns a temporary texture or NULL on failure. */
VEGA3dTexture* getTempTexture(unsigned int minWidth, unsigned int minHeight);
VEGA3dFramebufferObject* getTempTextureRenderTarget();
VEGA3dTexture* getAlphaTexture();
UINT8* getAlphaTextureBuffer();
VEGA3dTexture* createTempTexture2(unsigned int minWidth, unsigned int minHeight);
VEGA3dFramebufferObject* createTempTexture2RenderTarget();
VEGA3dRenderState* getDefault2dRenderState(){return m_default2dRenderState;}
VEGA3dRenderState* getDefault2dNoBlendRenderState(){return m_default2dNoBlendRenderState;}
VEGA3dRenderState* getDefault2dNoBlendNoScissorRenderState(){return m_default2dNoBlendNoScissorRenderState;}
virtual bool getHighPrecisionFragmentSupport() const { return true; }
#ifdef VEGA_ENABLE_PERF_EVENTS
/** Insert a marker into the render command stream for debugging and performance usage. */
virtual void SetPerfMarker(const uni_char *marker) = 0;
/** Insert markers to bracket an event in the render command stream for debugging and performance usage. */
virtual void BeginPerfEvent(const uni_char *marker) = 0;
virtual void EndPerfEvent() = 0;
#endif //VEGA_ENABLE_PERF_EVENTS
protected:
unsigned int invalidLeft, invalidTop;
unsigned int invalidRight, invalidBottom;
VEGA3dBuffer* m_tempBuffer;
VEGA3dBuffer* m_ibuffer;
VEGA3dTexture* m_tempTexture;
VEGA3dFramebufferObject* m_tempFramebuffer;
VEGA3dTexture* m_alphaTexture;
UINT8* m_alphaTextureBuffer;
VEGA3dTexture* m_tempTexture2;
VEGA3dFramebufferObject* m_tempFramebuffer2;
VEGA3dVertexLayout* m_2dVertexLayout;
VEGA3dRenderState* m_default2dRenderState;
VEGA3dRenderState* m_default2dNoBlendRenderState;
VEGA3dRenderState* m_default2dNoBlendNoScissorRenderState;
OpVector<VEGA3dRenderState> m_renderStateStack;
/** GPU representation of triangle indices, used to batch indexed
* triangles - updated from flushBatches if needed */
VEGA3dBuffer* m_triangleIndexBuffer;
/** buffer for all triangle indices, synced to
* m_triangleIndexBuffer from flushBatches */
unsigned short* m_triangleIndices;
Head m_contextLostListeners;
#ifdef VEGA_BACKENDS_USE_BLOCKLIST
VEGABlocklistDevice::BlocklistStatus m_blocklistStatus2D, m_blocklistStatus3D;
#endif
};
#ifdef VEGA_3DDEVICE
# define VEGA_3D_NATIVE_WIN_NAME nativeWin
# define VEGA_3D_NATIVE_WIN_DECL , VEGAWindow* VEGA_3D_NATIVE_WIN_NAME = NULL
# define VEGA_3D_NATIVE_WIN_PASS , VEGA_3D_NATIVE_WIN_NAME
#else // VEGA_3DDEVICE
# define VEGA_3D_NATIVE_WIN_NAME
# define VEGA_3D_NATIVE_WIN_DECL
# define VEGA_3D_NATIVE_WIN_PASS
#endif // VEGA_3DDEVICE
/** Factory class for creating VEGA3dDevices. Creation of a 3d device
* is somewhat convoluted, mainly for two reasons:
*
* - Some platforms provide several possible backends (eg OpenGL, D3D).
*
* - Backends may be blocklisted based on information fetched from the
backend itself, requiring a two-level init phase.
*
* Users of this API just call the public blend of Create, and can
* ignore the details. Internally the creation process is as follows:
*
* - API user calls public blend of Create.
*
* - This will call private blend of Create (implemented by platform)
requesting a specific device type/backend, which performs
first-level initialization by calling VEGA3dDevice::Init.
*
* - If first-level initialization succeeds
VEGA3dDevice::ConstructDevice is called. This checks blocklist
status, and if not blocked calls VEGA3dDevice::Construct to
completely initialize device.
*
* The internal steps are repeated until a device is created, or until
* there are no more device types/backends to try.
*/
class VEGA3dDeviceFactory
{
public:
/** Fetch number of blends of 3d device that can be created - to be implemented by platform.
* @return the number of different devices that can be created using this factory
*/
static unsigned int DeviceTypeCount();
/** Fetch name of device - shown on opera:gpu
* @param dev the device for which to fetch name
*/
static const uni_char* DeviceTypeString(UINT16 device_type_index);
/** Create a 3d device. This is only called once to create the
* global 3d device instance. Will call below blend of Create
* taking device_type_index, starting with index 0 and continuing
* until a device was successfully created or all valid indices
* have been tried.
* @param dev the device to create
* @param use_case under what circumstances to create a device
* @param nativeWin the native window which is used by VegaOpPainter.
* This is sent to make it possible to use it for initializing the 3d
* context.
*/
static OP_STATUS Create(VEGA3dDevice** dev, VEGA3dDevice::UseCase use_case
VEGA_3D_NATIVE_WIN_DECL);
private:
/** Allocate and initialize a specific blend of 3d device - to be
* implemented by platform. This is first-level init only, proper
* construction is made through Construct. Implementation should
* call VEGA3dDevice::Init, which should initialize enough so that
* VEGABlocklistDevice::DataProvider can do what it should.
* @param device_type_index the index of the device to create - must be less than DeviceTypeCount
* @param dev the device to create
* @param nativeWin the native window which is used by VegaOpPainter.
* This is sent to make it possible to use it for initializing the 3d
* context.
*/
static OP_STATUS Create(unsigned int device_type_index,
VEGA3dDevice** dev VEGA_3D_NATIVE_WIN_DECL);
#ifdef VEGA_BACKENDS_USE_BLOCKLIST
friend class VEGABlocklistDevice;
#endif // VEGA_BACKENDS_USE_BLOCKLIST
};
#ifdef VEGA_3DDEVICE
# undef VEGA_3D_NATIVE_WIN_DECL
# define VEGA_3D_NATIVE_WIN_DECL , VEGAWindow* VEGA_3D_NATIVE_WIN_NAME
#endif // VEGA_3DDEVICE
#endif // VEGA_3DDEVICE || CANVAS3D_SUPPORT
#endif // VEGA_SUPPORT
#endif // VEGA3DDEVICE_H
|
#include "demon.h"
const sf::IntRect Demon::DOWN[4] = {sf::IntRect(19,12,77,93), sf::IntRect(16,132,77,211), sf::IntRect(21,247,82,330), sf::IntRect(19,351,77,429)};
const sf::IntRect Demon::DIE[6] = {sf::IntRect(15, 886, 90, 984),
sf::IntRect(146, 886, 220, 986),
sf::IntRect(280, 900, 345, 970),
sf::IntRect(410, 898, 476, 972),
sf::IntRect(525, 911, 590, 974),
sf::IntRect(623, 933, 684, 974)};
Demon::Demon(sf::Vector2f position, int life, int dmg, int speed, string path) : Enemy(position, life, dmg, speed, path)
{
this->setAnimation(DOWN[this->getState()]);
}
Demon::Demon(const Demon &d):Enemy(d)
{
}
void Demon::changeState()
{
this->setState(this->getState()+1);
if(this->getState()>=4)
this->setState();
}
void Demon::move(Direction d)
{
this->setCycle(this->getCycle()+1);
if (d == Top)
this->getSprite().Move(0, -(this->getSpeed()));
if (d == Bottom)
this->getSprite().Move(0, (this->getSpeed()));
if (d == Left)
this->getSprite().Move(-(this->getSpeed()), 0);
if (d == Right)
this->getSprite().Move((this->getSpeed()), 0);
if(this->getCycle()%10==0)
{
this->changeState();
this->getSprite().SetSubRect(DOWN[this->getState()]);
}
}
void Demon::attack()
{
}
void Demon::die(int i)
{
if(this->IsDead() && i%5==0 && this->getState()<6){
this->getSprite().SetSubRect(DIE[this->getState()]);
this->setState(this->getState()+1);
}
}
|
#include<iostream>
#include<math.h>
using namespace std;
typedef unsigned long long int ll;
bool kt(ll n){
if(sqrt(n) == (ll)sqrt(n)) return true;
else return false;
}
int main(){
ll n;
cin >> n;
if(kt(n)) cout << "yes";
else cout << "no";
return 0;
}
|
/*
Overview: Dijkstra's shortest path algorithm has been used to find the shortest path
and for second shortest path Yen's algorithm has been used in the assignment
which is also the modification of Dijkstra's algorithm.
For Dijkstra set class has been used to keep track of the repeatation of
Nodes/vertices. Second, min heap has been used to get minimum out of all
vertices. Third, adjacency list is created from the GraphData.csv and the
adjacency list is two-dimensional doubly link list, which saves memory
as well as time and also saves time of shifting when removed from middle, as
nodes can be deleted from middle too. The initial work, i.e. reading from file
and making graph/adjacency list is done in the function named general().
Moreover, the user interface, the calculation of shortest path and second
shortest path has been calculated in the class graph. Also, the final
paths are stored in the three-dimensional linked list and looped out
to find the second shortest of all at a time in Yen's algorithm.
Finally, the requirement of templatizing the code has been kept on the
priority thourgh out the code.
*/
#pragma once
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
template<typename T, typename U>
class sNodeData;
template<typename T, typename U>
class pNodeData;
/*
Implementation of set.
It will be used in Dijkstra to prevent repeatation of vertices.
*/
template<class T>
class Set {
private:
T *arr;
int size;
int currentPosition;
public:
// default constructor
Set<T>() {
arr = NULL;
size = 0;
currentPosition = 0;
}
// parameterized constructor by the default size of 100
Set<T>(int size = 100) {
if (size == 0) {
size = size + 1;
}
arr = new T[size];
for (int i = 0; i < size; i++) {
arr[i] = "\0";
}
this->size = size;
currentPosition = 0;
}
// function to check whether the set is empty or not
bool isEmpty() {
if (currentPosition == 0) {
return true;
}
return false;
}
/* function for adding the new item in the set.
The set in Dijkstra's algorithm is made size specfic
and because of it, it never reaches the limit and
it keeps the code safe from shifting the elements
of set.
*/
void addItem(T item) {
if (currentPosition == size) {
T *tempArr = new T[size];
for (int i = 0; i < size; i++) {
tempArr[i] = arr[i];
}
delete[] arr;
arr = new T[size * 2];
for (int i = 0; i < size; i++) {
arr[i] = tempArr[i];
}
delete[] tempArr;
arr[currentPosition] = item;
currentPosition++;
size = size * 2;
} else {
arr[currentPosition] = item;
currentPosition++;
}
}
// function used in Dijkstra to get to know about the presence of the element in the set
bool isAlreadyInSet(T item) {
if (!isEmpty()) {
for (int i = 0; i < currentPosition; i++) {
if (arr[i] == item) {
return true;
}
}
}
return false;
}
// returns current size of the set
int getSize() const {
return size;
}
int getCurrentPosition() const {
return currentPosition;
}
void ascendingOrder() {
for (int i = 0; i < currentPosition; i++) {
for (int j = 0; j < currentPosition; j++) {
if (arr[i] < arr[j]) {
T temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
// function to print the set and has been used while testing
void Print() {
for (int i = 0; i < currentPosition; i++) {
cout << arr[i] << " ";
}
}
};
/*
Implementation of min heap which has been used in Dijkstra's algorithm
to find shortest path.
*/
template<typename T, typename U>
class minHeap {
private:
int heapSize;
T *data;
U *names;
int currentSize;
public:
//constructor
minHeap(int capacity) {
heapSize = capacity + 1;
data = new T[capacity + 1];
names = new U[capacity + 1];
currentSize = 1;
}
// function to if the heap is empty or not
bool isEmpty() {
if (currentSize == 1)
return true;
return false;
}
// return parent
int getParent(int index) {
return floor(static_cast<double>(index / 2));
}
// returns right child
int getRightChild(int index) {
return (2 * index) + 1;
}
// returns left child
int getLeftChild(int index) {
return 2 * index;
}
// inserts key while following the rules of insertion if the min heap
void insertKey(T key, U city) {
data[currentSize] = key;
names[currentSize] = city;
currentSize++;
int i = currentSize - 1;
while (i != 1 && data[getParent(i)] > data[i]) {
// swapping keys
T tempData = data[i];
data[i] = data[getParent(i)];
data[getParent(i)] = tempData;
//swapping names wrt to keys
U tempName = names[i];
names[i] = names[getParent(i)];
names[getParent(i)] = tempName;
i = getParent(i);
}
}
// function to assist the main function used for deletion of min value
void deleteMinInnerProcess(int minIndex) {
int left = getLeftChild(minIndex);
int right = getRightChild(minIndex);
int smallestValue = minIndex;
if (left < currentSize && data[left] < data[minIndex]) {
smallestValue = left;
}
if (right < currentSize && data[right] < data[smallestValue]) {
smallestValue = right;
}
if (smallestValue != minIndex) {
T tempData = data[minIndex];
data[minIndex] = data[smallestValue];
data[smallestValue] = tempData;
U tempName = names[minIndex];
names[minIndex] = names[smallestValue];
names[smallestValue] = tempName;
deleteMinInnerProcess(smallestValue);
}
}
// function to delete the min value
U deleteMin(T &minValue) {
if (currentSize != 1) {
if (currentSize == 2) {
currentSize--;
minValue = data[1];
return names[currentSize];
} else {
U storeReturnValue = names[1];
minValue = data[1];
currentSize--;
data[1] = data[currentSize];
names[1] = names[currentSize];
deleteMinInnerProcess(1);
return storeReturnValue;
}
} else
cout << "\nHeap is empty!\n";
}
// return min value which will always be on the first index
U getMin() {
if (currentSize != 1) {
return names[1];
} else {
cout << "Heap is Empty\n";
}
}
// returns the distance of given city
T getDistance(U cityName, int &cityIndex) {
//searching for distance of given city
for (int i = 1; i < currentSize; i++) {
if (names[i].compare(cityName) == 0) {
cityIndex = i;
return data[i];
}
}
}
// sets the distance of given index
void setDistance(int index, T distance) {
data[index] = distance;
while (index != 1 && data[getParent(index)] > data[index]) {
T tempData = data[index];
data[index] = data[getParent(index)];
data[getParent(index)] = tempData;
U tempName = names[index];
names[index] = names[getParent(index)];
names[getParent(index)] = tempName;
index = getParent(index);
}
}
// function for displaying min heap. Was used for testing
void display() {
for (int i = 1; i < currentSize; i++) {
cout << data[i] << " " << names[i] << endl;
}
}
};
// Node for doubly link list
template<typename T>
class Node {
public:
T data;
Node<T> *Next;
Node<T> *Prev;
Node() {
Next = NULL;
Prev = NULL;
}
};
// implementation of the doubly link list
template<class T>
class list {
private:
Node<T> *Head;
Node<T> *Tail;
int size;
public:
list() {
Head = NULL;
Tail = NULL;
size = 1;
}
Node<T>* getHead() const {
return Head;
}
Node<T>* getTail() const {
return Tail;
}
bool isEmpty() {
if (Head == NULL)
return true;
else
return false;
}
// inserts the data item at specific index
void insertAt(const T &newDataItem, int index) {
Node<T> *newNode = new Node<T>;
newNode->data = newDataItem;
if (index > 1 && isEmpty())
cout << "index out of range";
else {
Node<T> *currNode = Head;
int currIndex = 2;
while (currNode && index > currIndex) {
currNode = currNode->Next;
currIndex++;
}
if (index > currIndex - 1 && !currNode)
cout << "index out of range";
else {
if (index == 1 && isEmpty()) {
newNode->Next = NULL;
newNode->Prev = NULL;
Head = newNode;
Tail = newNode;
} else if (index == 1) {
newNode->Next = currNode;
Head = newNode;
if (!currNode->Next)
Tail = currNode;
} else if (currNode->Next == NULL) {
newNode->Next = currNode->Next;
newNode->Prev = currNode;
currNode->Next = newNode;
currNode = currNode->Next;
Tail = currNode;
} else {
newNode->Next = currNode->Next;
currNode->Next = newNode;
newNode->Next->Prev = newNode;
newNode->Prev = currNode;
}
size++;
}
}
}
// removes data item from the specific index
void removeAt(int index) {
if (index <= 0)
return;
int currIdx = 1;
Node<T>*current = Head;
while (current->Next && index > currIdx) {
current = current->Next;
currIdx++;
}
if (index > currIdx) {
cout << "index out of range" << endl;
return;
}
if (current) {
if (current->Prev && index == currIdx) {
Node<T>*oldNode = current;
oldNode->Prev->Next = oldNode->Next;
if (oldNode->Next) {
oldNode->Next->Prev = oldNode->Prev;
}
current = oldNode->Prev;
if (!current->Next)
Tail = current;
delete oldNode;
} else {
if (current->Next) {
Head = current->Next;
Head->Prev = NULL;
if (!Head->Next)
Tail = current;
delete current;
} else {
Head = NULL;
Tail = NULL;
}
}
}
this->size--;
}
// removes data item from the end
void remove() {
Node<T>*current = Head;
while (current->Next) {
current = current->Next;
}
if (current) {
if (current->Prev) {
Node<T>*oldNode = current;
oldNode->Prev->Next = oldNode->Next;
current = oldNode->Prev;
Tail = current;
delete oldNode;
} else {
if (current->Next) {
Head = current->Next;
Head->Prev = NULL;
delete current;
Tail = Head;
} else {
Head = NULL;
Tail = NULL;
}
}
}
size--;
}
// inserts data item at the end
void insert(T newDataItem) {
if (!Head) {
Head = new Node<T>;
Head->data = newDataItem;
Head->Next = NULL;
Head->Prev = NULL;
Tail = Head;
return;
} else {
Node<T>*current = Head;
while (current->Next) {
current = current->Next;
}
Node<T>*newNode = new Node<T>;
newNode->data = newDataItem;
newNode->Prev = current;
newNode->Next = current->Next;
newNode->Prev->Next = newNode;
current = newNode;
Tail = current;
}
size++;
}
// returns size
int getSize() {
return size;
}
// displays link list
void displayList() {
if (!isEmpty()) {
Node<T> *currNode = Head;
while (currNode) {
currNode->data.display();
currNode = currNode->Next;
}
} else
cout << "List is already Empty";
}
};
/* following are the data nodes used to create various things throughtout the code*/
template<typename T, typename U>
class sNodeData {
public:
T adjCityName;
U adjCityDistance;
sNodeData() {
adjCityName = "";
adjCityDistance = 0;
}
void insertSNodeData(T name, U distance) {
adjCityName = name;
adjCityDistance = distance;
}
void display() {
cout << "|" << adjCityName << " ";
cout << adjCityDistance << "| ";
}
};
template<typename T>
class singleCity {
public:
T city;
singleCity() {
city = "";
}
void insertPathData(T city) {
this->city = city;
}
void display() {
cout << "|" << city << "|-->";
}
};
template<typename T, typename U>
class Path {
public:
list<T> pathCityToCity;
U distanceCityToCity;
Path() {
distanceCityToCity = 0;
}
Path(list<U> pathCityToCitySourceData, U distanceCityToCity) {
pathCityToCity = pathCityToCitySourceData;
this->distanceCityToCity = distanceCityToCity;
}
void display() {
pathCityToCity.displayList();
cout << "Distance: [" << distanceCityToCity << "]" << endl;
}
};
template<typename T, typename U>
class pNodeData {
public:
T cityName;
list<U> adjNodes;
pNodeData() {
cityName = "";
}
pNodeData(T name, list<U> adjNodesSourceData) {
cityName = name;
adjNodes = adjNodesSourceData;
}
void display() {
cout << cityName << "--> ";
adjNodes.displayList();
cout << endl;
}
};
template<typename T>
class shortestPathsNodes {
public:
list<T> shortestPaths;
shortestPathsNodes() {
}
shortestPathsNodes(list<T> shortestPathsSourceData) {
shortestPaths = shortestPathsSourceData;
}
void display() {
shortestPaths.displayList();
}
};
// class which has adjacency list as a member variable and
// handles user interface as well as the finding of shortest
// and second shortest paths.
template<typename T, typename U, typename V>
class graph {
public:
list<V> adjacencyList;
// function for inseting the node
void insert(V primaryNode) {
adjacencyList.insert(primaryNode);
}
void display() {
adjacencyList.displayList();
}
// function adds the new city the adjacency list
void addNewCity(T newCity) {
V newCityInTheAdjacencyList;
newCityInTheAdjacencyList.cityName = newCity;
adjacencyList.insert(newCityInTheAdjacencyList);
}
/*
checks whether the city is already present in the graph or not
if No then it returns -1 and if yes then it returns its location
*/
int isCityAlreadyPresent(T newCityName) {
int count = 1;
Node<V> *currentNode = adjacencyList.getHead();
if (!adjacencyList.isEmpty()) {
while (currentNode) {
if (currentNode->data.cityName == newCityName) {
return count;
}
currentNode = currentNode->Next;
count++;
}
} else {
return -1;
}
return -1;
}
// function which checks that the edged city is already present or not
int isEdgedCityAlreadyPresent(Node<V> *currentNode, T edgedCityName) {
Node<sNodeData<T, U>> *adjNodesCurrentNode =
currentNode->data.adjNodes.getHead();
int count = 1;
while (adjNodesCurrentNode) {
if (adjNodesCurrentNode->data.adjCityName == edgedCityName) {
return count;
}
adjNodesCurrentNode = adjNodesCurrentNode->Next;
count++;
}
return -1;
}
// function which removes all the thinks in the adjacency list with the given city name
void removeAllLinks(T cityName) {
if (!adjacencyList.isEmpty()) {
Node<V> *currentNode = adjacencyList.getHead();
while (currentNode) {
int count = 1;
Node<sNodeData<T, U>> *innerCurrentNode =
currentNode->data.adjNodes.getHead();
while (innerCurrentNode) {
if (innerCurrentNode->data.adjCityName == cityName) {
currentNode->data.adjNodes.removeAt(count);
break;
}
innerCurrentNode = innerCurrentNode->Next;
count++;
}
currentNode = currentNode->Next;
}
}
}
// inserts the new edge
void insertEdge(sNodeData<T, U> s, T cityName) {
Node<V> *currentNode = adjacencyList.getHead();
while (currentNode) {
if (currentNode->data.cityName == cityName) {
currentNode->data.adjNodes.insert(s);
}
currentNode = currentNode->Next;
}
}
// removes the edge between two cities
void removeEdge(T mainNodeName, T innerListNodeName) {
Node<V> *currentNode = adjacencyList.getHead();
while (currentNode) {
if (currentNode->data.cityName == mainNodeName) {
int isEdgedCityAlreadyPresentCheck = isEdgedCityAlreadyPresent(
currentNode, innerListNodeName);
if (isEdgedCityAlreadyPresentCheck == -1) {
cout << "No such link with this city";
} else {
currentNode->data.adjNodes.removeAt(
isEdgedCityAlreadyPresentCheck);
}
}
currentNode = currentNode->Next;
}
}
// returns graph size
int getAdjacencyListSize() {
int count = 0;
Node<V> *currentNode = adjacencyList.getHead();
while (currentNode) {
count++;
currentNode = currentNode->Next;
}
return count;
}
// recursive function which has been implemented to get the path from source to destination
void printPath(T *parentArray, int destination, T *verticesArray,
int verticesArraySize, int choice,
Path<singleCity<T>, U> &singleCityPathAndDistance,
singleCity<T> & storeSingleCity) {
if (parentArray[destination] == "\0") {
return;
}
int i = 0;
for (; i < verticesArraySize; i++) {
if (verticesArray[i] == parentArray[destination]) {
destination = i;
break;
}
}
if (choice == 2) {
storeSingleCity.insertPathData(verticesArray[destination]);
singleCityPathAndDistance.pathCityToCity.insert(storeSingleCity);
}
printPath(parentArray, destination, verticesArray, verticesArraySize,
choice, singleCityPathAndDistance, storeSingleCity);
if (choice == 1 || choice == 3) {
storeSingleCity.insertPathData(verticesArray[destination]);
singleCityPathAndDistance.pathCityToCity.insert(storeSingleCity);
}
}
// implementation of dijkstra's algorithm to find the shortest path
list<Path<singleCity<T>, U>> runDijkstra(T nameOfCity, int choice,
T sink) {
int adjacencyListSize = getAdjacencyListSize();
Set<T> s(adjacencyListSize);
minHeap<U, T> m(adjacencyListSize);
T *parentArray = new T[adjacencyListSize];
T *verticesArray = new T[adjacencyListSize];
U *updatedDistances = new U[adjacencyListSize];
Node<V> *currentNode = adjacencyList.getHead();
int i = 0;
// inserting 0 as distance of the city from where to start in the min heap
// and 2147483648 as infinity to all other cities
while (currentNode) {
if (currentNode->data.cityName.compare(nameOfCity) == 0) {
m.insertKey(0, currentNode->data.cityName);
parentArray[i] = "\0";
verticesArray[i] = currentNode->data.cityName;
} else {
m.insertKey(2147483648, currentNode->data.cityName);
parentArray[i] = "\0";
verticesArray[i] = currentNode->data.cityName;
}
currentNode = currentNode->Next;
i++;
}
T vertex = "";
// runs untill the min heap is not empty
while (!m.isEmpty()) {
vertex = m.getMin();
// storing the vertex in the set if it is not already present
if (!s.isAlreadyInSet(vertex))
s.addItem(vertex);
currentNode = adjacencyList.getHead();
while (currentNode) {
if (currentNode->data.cityName.compare(vertex) == 0) {
Node<sNodeData<T, U>> *innerCurrentNode =
currentNode->data.adjNodes.getHead();
while (innerCurrentNode) {
int vertexIndex;
int neighbhorIndex;
U vertexDistance = m.getDistance(vertex, vertexIndex);
U neighbhorDistance = m.getDistance(
innerCurrentNode->data.adjCityName,
neighbhorIndex);
// condition to check if the vertex is not already in the set
// and vertecdistance from the min heap + its distance from adjacency list
// if less than the distance of the neihbour of the vertex or not.
// if yes, then replace the distance.
if (!s.isAlreadyInSet(
innerCurrentNode->data.adjCityName)
&& (vertexDistance
+ innerCurrentNode->data.adjCityDistance)
< neighbhorDistance) {
m.setDistance(neighbhorIndex,
(vertexDistance
+ innerCurrentNode->data.adjCityDistance));
for (int j = 0; j < adjacencyListSize; j++) {
if (verticesArray[j].compare(
innerCurrentNode->data.adjCityName)
== 0) {
parentArray[j] = vertex;
break;
}
}
}
innerCurrentNode = innerCurrentNode->Next;
}
break;
}
currentNode = currentNode->Next;
}
// getting minimum value and the city with min value and deleting from the min heap
U storeMinValue;
T storeMinCity = m.deleteMin(storeMinValue);
// updating the distance of the mincity
for (int i = 0; i < adjacencyListSize; i++) {
if (verticesArray[i].compare(storeMinCity) == 0) {
updatedDistances[i] = storeMinValue;
break;
}
}
}
// two- dimensional link list to store all paths to return it later
list<Path<singleCity<T>, U>> paths;
// if choice is 1 or 2 then it stores the path from all the cities to specific city and vice versa
if (choice == 1 || choice == 2) {
for (int i = 0; i < adjacencyListSize; i++) {
singleCity<T> storeSingleCity;
Path<singleCity<T>, U> pathAndDistanceNode;
if (verticesArray[i] != nameOfCity) {
if (choice == 1) {
printPath(parentArray, i, verticesArray,
adjacencyListSize, choice, pathAndDistanceNode,
storeSingleCity);
if (updatedDistances[i] == 2147483648) {
storeSingleCity.insertPathData(verticesArray[i]);
pathAndDistanceNode.pathCityToCity.insert(
storeSingleCity);
pathAndDistanceNode.distanceCityToCity =
updatedDistances[i];
paths.insert(pathAndDistanceNode);
} else {
storeSingleCity.insertPathData(verticesArray[i]);
pathAndDistanceNode.pathCityToCity.insert(
storeSingleCity);
pathAndDistanceNode.distanceCityToCity =
updatedDistances[i];
paths.insert(pathAndDistanceNode);
}
}
if (choice == 2) {
if (updatedDistances[i] == 2147483648) {
storeSingleCity.insertPathData(verticesArray[i]);
pathAndDistanceNode.pathCityToCity.insert(
storeSingleCity);
pathAndDistanceNode.distanceCityToCity =
updatedDistances[i];
paths.insert(pathAndDistanceNode);
}
else {
storeSingleCity.insertPathData(verticesArray[i]);
pathAndDistanceNode.pathCityToCity.insert(
storeSingleCity);
}
printPath(parentArray, i, verticesArray,
adjacencyListSize, choice, pathAndDistanceNode,
storeSingleCity);
if (updatedDistances[i] != 2147483648) {
pathAndDistanceNode.distanceCityToCity =
updatedDistances[i];
paths.insert(pathAndDistanceNode);
}
}
}
}
return paths;
}
// if choice is 3 which means it will store the path from one city to another
if (choice == 3) {
for (int i = 0; i < adjacencyListSize; i++) {
singleCity<T> storeSingleCity;
Path<singleCity<T>, U> pathAndDistanceNode;
if (verticesArray[i] == sink) {
printPath(parentArray, i, verticesArray, adjacencyListSize,
choice, pathAndDistanceNode, storeSingleCity);
if (updatedDistances[i] == 2147483648) {
storeSingleCity.insertPathData(verticesArray[i]);
pathAndDistanceNode.pathCityToCity.insert(
storeSingleCity);
pathAndDistanceNode.distanceCityToCity =
updatedDistances[i];
paths.insert(pathAndDistanceNode);
} else {
storeSingleCity.insertPathData(verticesArray[i]);
pathAndDistanceNode.pathCityToCity.insert(
storeSingleCity);
pathAndDistanceNode.distanceCityToCity =
updatedDistances[i];
paths.insert(pathAndDistanceNode);
}
break;
}
}
// returning path list
return paths;
}
}
// returns the weight of the edge between two cities in the adjacency list
int getDistance(T city1, T city2) {
Node<V> *currentNode = adjacencyList.getHead();
while (currentNode) {
if (city1.compare(currentNode->data.cityName) == 0) {
Node<sNodeData<T, U>> *innerCurrentNode =
currentNode->data.adjNodes.getHead();
while (innerCurrentNode) {
if (innerCurrentNode->data.adjCityName.compare(city2)
== 0) {
return innerCurrentNode->data.adjCityDistance;
}
innerCurrentNode = innerCurrentNode->Next;
}
}
currentNode = currentNode->Next;
}
}
// Yen's algo implemented to get the second shortest path
// it first stores the shortest paths in the three-dimensional
// doubly linked list to also handle the distances from one city to many
// and looping through them to get the second shortest path of all
void runYen(T cityName, int choice, int k, string sink) {
list<shortestPathsNodes<Path<singleCity<T>, U>>> kShortestPaths;
shortestPathsNodes<Path<singleCity<T>,U>> firstShortestPath(runDijkstra(cityName,choice,sink));
kShortestPaths.insert(firstShortestPath); // it will store the k shortest path and first path is already stored
// temporary adjacency list is created which will be used later to store the original
// adjacency list to use it in the process. It also helps to get the original
// graph to be unaltered at the end of the process of finding the second shortest
// path.
list <V> tempAdjacencyList;
Node <shortestPathsNodes<Path<singleCity<T>,U>>> *OuterCurrentNode= kShortestPaths.getHead();
Node <Path<singleCity<T>,U>> *InnerCurrentNode= OuterCurrentNode->data.shortestPaths.getHead();
while (InnerCurrentNode)
{
if (InnerCurrentNode->data.distanceCityToCity!=2147483648)
{
sink = InnerCurrentNode->data.pathCityToCity.getTail()->data.city;
list <Path<singleCity<T>,U>> alternativePaths;
for (int i=0;i<=InnerCurrentNode->data.pathCityToCity.getSize()-2;i++)
{
Node <singleCity<T>> *currNode=InnerCurrentNode->data.pathCityToCity.getHead(); // to get spurNode A[0].node(i)
list <singleCity<T>> rootPath;
singleCity<T> currCity;
int distance=0;
string spurNode="";
// storing the root path and spurNode
for (int j=0;j<=i;j++)
{
currCity.city=currNode->data.city;
rootPath.insert(currCity);
if (j!=i)
{
distance+=getDistance(currNode->data.city,currNode->Next->data.city);
}
if (j==i)
{
spurNode=currNode->data.city;
}
currNode=currNode->Next;
}
bool flag=true;
Node <singleCity<T>> *checkCityNode=InnerCurrentNode->data.pathCityToCity.getHead();
Node <singleCity<T>> *rootPathNode = rootPath.getHead();
// check whether the root path is the part of the shortest path founded
while (rootPathNode)
{
if (rootPathNode->data.city!=checkCityNode->data.city)
{
flag=false;
break;
}
checkCityNode=checkCityNode->Next;
rootPathNode=rootPathNode->Next;
}
// if yes then remove the edge of spur node and next to it
if (flag)
{
// copying original adjacency list in the temp adjacency list to
// use the original in the process and then getting it returned
// to its original state.
Node <V> *adjacencyListCopyNode= adjacencyList.getHead();
while (adjacencyListCopyNode)
{
list <sNodeData<T,U>> copySNodeList;
Node <sNodeData<T,U>> *copySNode=adjacencyListCopyNode->data.adjNodes.getHead();
while (copySNode)
{
sNodeData <T,U> copySNodeData;
copySNodeData.insertSNodeData(copySNode->data.adjCityName,copySNode->data.adjCityDistance);
copySNodeList.insert(copySNodeData);
copySNode=copySNode->Next;
}
pNodeData<T,sNodeData<T,U>> copyPNodeData;
copyPNodeData.cityName=adjacencyListCopyNode->data.cityName;
copyPNodeData.adjNodes=copySNodeList;
tempAdjacencyList.insert(copyPNodeData);
adjacencyListCopyNode=adjacencyListCopyNode->Next;
}
// removing edges of city1 with city2 and vice versa
removeEdge(currNode->Prev->data.city,currNode->data.city);
removeEdge(currNode->data.city,currNode->Prev->data.city);
}
// also remove the nodes of the root path except the spur Node from the adjacency list
rootPathNode = rootPath.getHead();
while (rootPathNode->data.city!=spurNode)
{
adjacencyList.removeAt(isCityAlreadyPresent(rootPathNode->data.city));
removeAllLinks(rootPathNode->data.city);
rootPathNode=rootPathNode->Next;
}
// running dijkstra to find the shortest path from spur node
list <Path<singleCity<T>,U>> spurPath=runDijkstra(spurNode,3,sink);
Node <singleCity<T>> *spurPathNode=spurPath.getHead()->data.pathCityToCity.getHead();
singleCity<T> spurPathNodeData;
spurPathNode=spurPathNode->Next;
// combining the root path and spur path found by running dijkstra on it
while (spurPathNode)
{
spurPathNodeData.insertPathData(spurPathNode->data.city);
rootPath.insert(spurPathNodeData);
spurPathNode=spurPathNode->Next;
}
Path<singleCity<T>,U> pathNode;
// adding distances of root path and spur path to get the total distance
pathNode.distanceCityToCity=spurPath.getHead()->data.distanceCityToCity+distance;
pathNode.pathCityToCity=rootPath;
alternativePaths.insert(pathNode);
// deleting the original adjacency list
Node <V> *adjacencyListCopyNode= adjacencyList.getHead();
while (adjacencyListCopyNode)
{
int size=adjacencyListCopyNode->data.adjNodes.getSize();
Node <sNodeData<T,U>> *copySNode=adjacencyListCopyNode->data.adjNodes.getHead();
while (size>0 && copySNode)
{
adjacencyListCopyNode->data.adjNodes.remove();
size--;
}
adjacencyListCopyNode=adjacencyListCopyNode->Next;
}
while (!adjacencyList.isEmpty())
{
adjacencyList.remove();
}
// getting back to its original condition by assigning it the tempAdjacency list stored before
adjacencyListCopyNode= tempAdjacencyList.getHead();
while (adjacencyListCopyNode)
{
list <sNodeData<T,U>> copySNodeList;
Node <sNodeData<T,U>> *copySNode=adjacencyListCopyNode->data.adjNodes.getHead();
while (copySNode)
{
sNodeData <T,U> copySNodeData;
copySNodeData.insertSNodeData(copySNode->data.adjCityName,copySNode->data.adjCityDistance);
copySNodeList.insert(copySNodeData);
copySNode=copySNode->Next;
}
pNodeData<T,sNodeData<T,U>> copyPNodeData;
copyPNodeData.cityName=adjacencyListCopyNode->data.cityName;
copyPNodeData.adjNodes=copySNodeList;
adjacencyList.insert(copyPNodeData);
adjacencyListCopyNode=adjacencyListCopyNode->Next;
}
// deleting temp graph/adjacency list
adjacencyListCopyNode= tempAdjacencyList.getHead();
while (adjacencyListCopyNode)
{
int size=adjacencyListCopyNode->data.adjNodes.getSize();
Node <sNodeData<T,U>> *copySNode=adjacencyListCopyNode->data.adjNodes.getHead();
while (size>0 && copySNode)
{
adjacencyListCopyNode->data.adjNodes.remove();
size--;
}
adjacencyListCopyNode=adjacencyListCopyNode->Next;
}
adjacencyListCopyNode= tempAdjacencyList.getHead();
while (!tempAdjacencyList.isEmpty())
{
tempAdjacencyList.remove();
}
}
// sorting all the spur paths to get shortest of all which will be second shortest path
for(int i =0; i<alternativePaths.getSize() - 1; i++)
{
Node<Path<singleCity<T>,U>>* nodeForSorting = alternativePaths.getHead();
for(int j = 0; j<alternativePaths.getSize() - i - 1; j++)
{
Node<Path<singleCity<T>,U>>* tempNode = new Node<Path<singleCity<T>,U>>;
if(nodeForSorting->data.distanceCityToCity > nodeForSorting->Next->data.distanceCityToCity)
{
tempNode->data = nodeForSorting->data;
nodeForSorting->data = nodeForSorting->Next->data;
nodeForSorting->Next->data = tempNode->data;
}
nodeForSorting = nodeForSorting->Next;
}
}
// displaying shortest and second shorest paths
cout<<"Shortest Path: ";
InnerCurrentNode->data.display();
if (alternativePaths.getHead()->data.distanceCityToCity != 2147483648){
cout<<"Second Shortest Path: ";
alternativePaths.getHead()->data.display();
}
else
cout<<"No Second Shortest Path of "<<alternativePaths.getHead()->data.pathCityToCity.getHead()->data.city<<" Exists With "<<sink<<endl;
cout<<endl;
}
else
{
cout<<"No Shortest Path Exists With "<<InnerCurrentNode->data.pathCityToCity.getHead()->data.city<<endl<<endl;
}
InnerCurrentNode=InnerCurrentNode->Next;
}
}
// function which handles the user interface and given input and calls respecive functions
void performOperation() {
int choice;
cin>>choice;
if (choice==0) {
cout<<"______________________________________________________________________________________________________________________"<<endl;
adjacencyList.displayList();
cout<<"______________________________________________________________________________________________________________________"<<endl<<endl;
}
if (choice==1) {
string newCity="";
cout<<"Please input the name of the city you want to add\n";
cin.ignore();
getline(cin,newCity);
if (isCityAlreadyPresent(newCity)==-1) {
addNewCity(newCity);
cout<<"New city added. Press 0 to see the updated graph."<<endl<<endl;
}
else {
cout<<"This city is already present\n";
}
}
if (choice==2) {
string cityName="";
cout<<"Please input the name of the city you want to remove\n";
cin.ignore();
getline(cin,cityName);
if (isCityAlreadyPresent(cityName)==-1) {
cout<<"The given city doesn't exist\n";
}
else {
adjacencyList.removeAt(isCityAlreadyPresent(cityName));
removeAllLinks(cityName);
cout<<"City Deleted. Press 0 to see the updated graph."<<endl<<endl;
}
}
if (choice==3) {
string cityName="";
cout<<"Please input the name of the city to which you want to add an edge of other city\n";
cin.ignore();
getline(cin,cityName);
if (isCityAlreadyPresent(cityName)==-1) {
cout<<"No such city exists";
}
else {
T edgeCityName="";
U edgeCityDistance;
cout<<"Please Enter the name of the city which is to be edged with the entered city\n";
getline(cin,edgeCityName);
bool flag=false;
Node <V> *currentNode=adjacencyList.getHead();
while (currentNode)
{
if (cityName.compare(currentNode->data.cityName)==0){
Node <sNodeData<T,U>> * innerCurrentNode = currentNode->data.adjNodes.getHead();
while (innerCurrentNode)
{
if (edgeCityName.compare(innerCurrentNode->data.adjCityName)==0){
flag=true;
break;
}
innerCurrentNode=innerCurrentNode->Next;
}
break;
}
currentNode=currentNode->Next;
}
if (!flag){
if (edgeCityName.compare(cityName)!=0){
if (isCityAlreadyPresent(edgeCityName)==-1) {
cout<<"\nCan't add an edge of the city which is not in the list\n";
}
else {
cout<<"\nPlease Enter the distance\n";
cin>>edgeCityDistance;
while (edgeCityDistance<=0) {
cout<<"\nPlease Enter appropriate distance\n";
cin>>edgeCityDistance;
}
sNodeData<T,U> s;
s.insertSNodeData(edgeCityName,edgeCityDistance);
insertEdge(s,cityName);
s.insertSNodeData(cityName,edgeCityDistance);
insertEdge(s,edgeCityName);
cout<<"Edge added. Press 0 to see the updated graph"<<endl<<endl;
}
}
else{
cout<<"Can't add the edge with the city itself! "<<endl;
}
}
else
{
cout<<"Edge is already present!"<<endl;
}
}
}
if (choice==4) {
string cityName="";
cout<<"Please input the name of the city of which you want to remove an edge of other city\n";
cin.ignore();
getline(cin,cityName);
if (isCityAlreadyPresent(cityName)==-1) {
cout<<"No such city exists";
}
else {
string edgeCityName="";
cout<<"Please Enter the name of the other city\n";
getline(cin,edgeCityName);
removeEdge(cityName,edgeCityName);
removeEdge(edgeCityName,cityName);
cout<<"Edge removed. Press 0 to see the updated graph"<<endl<<endl;
}
}
if (choice == 5) {
string cityName="";
cout<<"Please Enter the name of the city\n";
cin.ignore();
getline(cin,cityName);
cout<<endl;
if (isCityAlreadyPresent(cityName)==-1) {
cout<<"Sorry, city doesn't exist\n";
}
else {
runYen (cityName,1,2,"");
}
}
if (choice ==6)
{
string cityName="";
cout<<"Please Enter the name of the city\n";
cin.ignore();
getline(cin,cityName);
cout<<endl;
if (isCityAlreadyPresent(cityName)==-1) {
cout<<"Sorry, city doesn't exist\n";
}
else {
runYen (cityName,2,2,"");
}
}
if (choice ==7)
{
string cityName="";
cout<<"Please Enter the name of the city\n";
cin.ignore();
getline(cin,cityName);
cout<<endl;
if (isCityAlreadyPresent(cityName)==-1) {
cout<<"Sorry, city doesn't exist\n";
}
else {
string secondCityName="";
cout<<"Please Enter the name of the second city\n";
getline(cin,secondCityName);
cout<<endl;
if (isCityAlreadyPresent(secondCityName)==-1) {
cout<<"Sorry, city doesn't exist\n";
}
else
{
runYen (cityName,3,2,secondCityName);
}
}
}
}
// menu
void displayMenu() {
cout<<"Please choose the operation you want to perform\n"<<
"0) Show the graph \n"<<
"1) Insert a city\n"<<
"2) Remove a city\n"<<
"3) Insert an edge in an existing city\n"<<
"4) Remove an edge from an existing city\n"<<
"5) Compute Shortest and Second Shortest Distance From a City to All Other Cities\n"<<
"6) Compute Shortest and Second Shortest Distance from All Other Cities to Specific City\n"<<
"7) Compute Shortest and Second Shortest distance between two cities\n"<<endl;
performOperation();
}
};
// function in which the data from the given file is read
// and graph/ adjacencylist is created.
template<typename T, typename U>
void general(string path) {
graph<T, U, pNodeData<T, sNodeData<T, U>>> g;
ifstream readFile (path);
string line;
if (readFile.is_open()) {
getline(readFile, line);
}
line+='\0';
int citiesCount=0;
for (int i=0;line[i]!='\0';i++) {
if (line[i]==',') {
citiesCount++;
}
}
T *cities=new T [citiesCount];
int j=0;
for (int i=1;i<line.length();i++) {
while (line[i]!=',' && line[i]!='\0') {
cities[j]+=line[i];
i++;
}
j++;
}
int outerCondition=0;
while (outerCondition<citiesCount) {
getline(readFile,line);
line+='\0';
int pNodeDataStringCount=0;
for (int i=0;line[i]!='\0';i++) {
if (line[i]==',') {
pNodeDataStringCount++;
}
}
T *pNodeDataString= new T [pNodeDataStringCount+1];
j=0;
for (int i=0;i<line.length();i++) {
while (line[i]!=',' && line[i]!='\0') {
pNodeDataString[j]+=line[i];
i++;
}
j++;
}
T cityName;
list <sNodeData<T,U>> adjNodesSource;
for (int i=0;i<pNodeDataStringCount+1;i++) {
if (i==0) {
cityName=pNodeDataString[i];
}
else {
if (stoi(pNodeDataString[i])>0) {
sNodeData <T,U> s1;
s1.insertSNodeData(cities[i-1],stoi(pNodeDataString[i]));
adjNodesSource.insert(s1);
}
}
}
pNodeData <T,sNodeData<T,U>> p(cityName,adjNodesSource);
g.insert(p);
outerCondition++;
}
while (true) {
g.displayMenu();
}
}
|
//
// FileVarObj.h
// Landru
//
// Created by Nick Porcino on 2014 01/1.
//
//
#pragma once
#include "LandruVM/VarObj.h"
namespace Landru {
class FileVarObj : public Landru::VarObj
{
public:
FileVarObj(const char* name);
virtual ~FileVarObj();
size_t size() const;
uint8_t* data() const;
VAROBJ_FACTORY(file, FileVarObj)
LANDRU_DECL_BINDING_BEGIN
LANDRU_DECL_BINDING(read)
LANDRU_DECL_BINDING(size)
LANDRU_DECL_BINDING_END
class Detail;
Detail* detail;
};
} // Landru
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.