text stringlengths 54 60.6k |
|---|
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
*
* Condor Software Copyright Notice
* Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE.TXT file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/* Dummy definition of ZZZ_dc_sinful to be included in Condor
libraries where needed. */
#include "condor_common.h"
char* global_dc_sinful() { return 0; }
bool global_dc_set_cookie(int len, unsigned char* data) { return false; }
bool global_dc_get_cookie(int &len, unsigned char* &data) { return false; }
<commit_msg>remove warnings<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
*
* Condor Software Copyright Notice
* Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE.TXT file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
/* Dummy definition of ZZZ_dc_sinful to be included in Condor
libraries where needed. */
#include "condor_common.h"
char* global_dc_sinful() { return 0; }
bool global_dc_set_cookie(int, unsigned char*) { return false; }
bool global_dc_get_cookie(int &, unsigned char* &) { return false; }
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Path_test.C,v 1.12.30.3 2007/06/21 19:44:53 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
#include <BALLTestConfig.h>
///////////////////////////
#include <BALL/SYSTEM/path.h>
///////////////////////////
START_TEST(Path, "$Id: Path_test.C,v 1.12.30.3 2007/06/21 19:44:53 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
::chdir(BALL_TEST_DATA_PATH(..));
CHECK(Path())
Path* p = new Path();
TEST_NOT_EQUAL(p, 0)
delete p;
RESULT
Path p;
String data_suffix1("/data/");
String data_suffix2("/data/");
data_suffix2[0] = FileSystem::PATH_SEPARATOR;
data_suffix2[5] = FileSystem::PATH_SEPARATOR;
String x_test("XXXXX");
x_test += FileSystem::PATH_SEPARATOR + "XXXXX";
String x_test_quoted(x_test + FileSystem::PATH_SEPARATOR);
CHECK(string getDataPath())
STATUS(p.getDataPath())
TEST_EQUAL(String(p.getDataPath()).hasSuffix(data_suffix1)
|| String(p.getDataPath()).hasSuffix(data_suffix2), true)
RESULT
CHECK(void setDataPath(const string& path))
p.setDataPath(x_test);
TEST_EQUAL(p.getDataPath(), x_test_quoted);
RESULT
CHECK(void addDataPath(const string& path))
p.addDataPath(x_test);
STATUS(p.getDataPath())
TEST_EQUAL(String(p.getDataPath()).hasSubstring(x_test_quoted), true)
TEST_EQUAL(String(p.getDataPath()).hasSuffix(x_test_quoted), true)
RESULT
CHECK(string getDefaultDataPath())
TEST_EQUAL(String(p.getDefaultDataPath()).hasSuffix(data_suffix1)
|| String(p.getDefaultDataPath()).hasSuffix(data_suffix2), true)
RESULT
CHECK(string find(const string& name))
Path p1;
p1.reset();
String file = String("fragments") + FileSystem::PATH_SEPARATOR + "Fragments.db";
TEST_NOT_EQUAL(p1.find(file), "")
file = "Fragments.db";
TEST_EQUAL(p1.find(file), "")
file = "Path_test.C";
TEST_EQUAL(p1.find(file), "Path_test.C");
file = String("TEST") + FileSystem::PATH_SEPARATOR + "Path_test.C";
TEST_EQUAL(p1.find(file), "Path_test.C");
file = String("xxx") + FileSystem::PATH_SEPARATOR + "Path_test.C";
TEST_EQUAL(p1.find(file), "Path_test.C");
file = "Path_testX.C";
TEST_EQUAL(p1.find(file), "");
RESULT
CHECK(string findStrict(const string& name))
Path p1;
TEST_NOT_EQUAL(p1.find("fragments/Fragments.db"), "")
TEST_EQUAL(p1.find("Fragments.db"), "")
TEST_EQUAL(String(p1.getDataPath()+"TEST/Path_test.C"), String(p1.getDataPath()+"TEST/Path_test.C"))
TEST_EQUAL(p1.findStrict("Path_test.C"), "Path_test.C")
TEST_EQUAL(p1.findStrict("/TEST/Path_test.C"), "");
TEST_EQUAL(p1.findStrict("/xxx/Path_test.C"), "");
RESULT
CHECK([extra]Singleton)
Path p1;
Path p2;
p1.reset();
STATUS(p1.getDataPath())
TEST_EQUAL(String(p1.getDataPath()).hasSuffix(data_suffix1)
|| String(p1.getDataPath()).hasSuffix(data_suffix2), true)
p1.setDataPath(x_test);
TEST_EQUAL(p1.getDataPath(), x_test_quoted)
TEST_EQUAL(p2.getDataPath(), x_test_quoted)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>On Windows, ::chdir => ::_chdir<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Path_test.C,v 1.12.30.3 2007/06/21 19:44:53 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
#include <BALLTestConfig.h>
///////////////////////////
#include <BALL/SYSTEM/path.h>
///////////////////////////
START_TEST(Path, "$Id: Path_test.C,v 1.12.30.3 2007/06/21 19:44:53 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
#ifdef BALL_COMPILER_MSVC
# define chdir _chdir
#endif
::chdir(BALL_TEST_DATA_PATH(..));
CHECK(Path())
Path* p = new Path();
TEST_NOT_EQUAL(p, 0)
delete p;
RESULT
Path p;
String data_suffix1("/data/");
String data_suffix2("/data/");
data_suffix2[0] = FileSystem::PATH_SEPARATOR;
data_suffix2[5] = FileSystem::PATH_SEPARATOR;
String x_test("XXXXX");
x_test += FileSystem::PATH_SEPARATOR + "XXXXX";
String x_test_quoted(x_test + FileSystem::PATH_SEPARATOR);
CHECK(string getDataPath())
STATUS(p.getDataPath())
TEST_EQUAL(String(p.getDataPath()).hasSuffix(data_suffix1)
|| String(p.getDataPath()).hasSuffix(data_suffix2), true)
RESULT
CHECK(void setDataPath(const string& path))
p.setDataPath(x_test);
TEST_EQUAL(p.getDataPath(), x_test_quoted);
RESULT
CHECK(void addDataPath(const string& path))
p.addDataPath(x_test);
STATUS(p.getDataPath())
TEST_EQUAL(String(p.getDataPath()).hasSubstring(x_test_quoted), true)
TEST_EQUAL(String(p.getDataPath()).hasSuffix(x_test_quoted), true)
RESULT
CHECK(string getDefaultDataPath())
TEST_EQUAL(String(p.getDefaultDataPath()).hasSuffix(data_suffix1)
|| String(p.getDefaultDataPath()).hasSuffix(data_suffix2), true)
RESULT
CHECK(string find(const string& name))
Path p1;
p1.reset();
String file = String("fragments") + FileSystem::PATH_SEPARATOR + "Fragments.db";
TEST_NOT_EQUAL(p1.find(file), "")
file = "Fragments.db";
TEST_EQUAL(p1.find(file), "")
file = "Path_test.C";
TEST_EQUAL(p1.find(file), "Path_test.C");
file = String("TEST") + FileSystem::PATH_SEPARATOR + "Path_test.C";
TEST_EQUAL(p1.find(file), "Path_test.C");
file = String("xxx") + FileSystem::PATH_SEPARATOR + "Path_test.C";
TEST_EQUAL(p1.find(file), "Path_test.C");
file = "Path_testX.C";
TEST_EQUAL(p1.find(file), "");
RESULT
CHECK(string findStrict(const string& name))
Path p1;
TEST_NOT_EQUAL(p1.find("fragments/Fragments.db"), "")
TEST_EQUAL(p1.find("Fragments.db"), "")
TEST_EQUAL(String(p1.getDataPath()+"TEST/Path_test.C"), String(p1.getDataPath()+"TEST/Path_test.C"))
TEST_EQUAL(p1.findStrict("Path_test.C"), "Path_test.C")
TEST_EQUAL(p1.findStrict("/TEST/Path_test.C"), "");
TEST_EQUAL(p1.findStrict("/xxx/Path_test.C"), "");
RESULT
CHECK([extra]Singleton)
Path p1;
Path p2;
p1.reset();
STATUS(p1.getDataPath())
TEST_EQUAL(String(p1.getDataPath()).hasSuffix(data_suffix1)
|| String(p1.getDataPath()).hasSuffix(data_suffix2), true)
p1.setDataPath(x_test);
TEST_EQUAL(p1.getDataPath(), x_test_quoted)
TEST_EQUAL(p2.getDataPath(), x_test_quoted)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|> |
<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "base/sys_info.h"
#include "base/cpuid_util.h"
#include "base/strings/string_util.h"
#include <algorithm>
#include <cstring>
namespace base {
// static
std::string SysInfo::processorName()
{
CpuidUtil cpuidUtil;
cpuidUtil.get(0x80000000);
uint32_t max_leaf = cpuidUtil.eax();
if (max_leaf < 0x80000002)
return std::string();
max_leaf = std::min(max_leaf, 0x80000004);
char buffer[49];
memset(&buffer[0], 0, sizeof(buffer));
for (uint32_t leaf = 0x80000002, offset = 0; leaf <= max_leaf; ++leaf, offset += 16)
{
cpuidUtil.get(leaf);
uint32_t eax = cpuidUtil.eax();
uint32_t ebx = cpuidUtil.ebx();
uint32_t ecx = cpuidUtil.ecx();
uint32_t edx = cpuidUtil.edx();
memcpy(&buffer[offset + 0], &eax, sizeof(eax));
memcpy(&buffer[offset + 4], &ebx, sizeof(ebx));
memcpy(&buffer[offset + 8], &ecx, sizeof(ecx));
memcpy(&buffer[offset + 12], &edx, sizeof(edx));
}
std::string result(buffer);
removeChars(&result, "(TM)");
removeChars(&result, "(tm)");
removeChars(&result, "(R)");
removeChars(&result, "CPU");
removeChars(&result, "Quad-Core Processor");
removeChars(&result, "Six-Core Processor");
removeChars(&result, "Eight-Core Processor");
std::string_view at("@");
auto sub = find_end(result.begin(), result.end(), at.begin(), at.end());
if (sub != result.end())
result.erase(sub - 1, result.end());
return collapseWhitespaceASCII(result, true);
}
// static
std::string SysInfo::processorVendor()
{
CpuidUtil cpuidUtil;
cpuidUtil.get(0x00000000);
uint32_t ebx = cpuidUtil.ebx();
uint32_t ecx = cpuidUtil.ecx();
uint32_t edx = cpuidUtil.edx();
char buffer[13];
memset(&buffer[0], 0, sizeof(buffer));
memcpy(&buffer[0], &ebx, sizeof(ebx));
memcpy(&buffer[4], &edx, sizeof(edx));
memcpy(&buffer[8], &ecx, sizeof(ecx));
std::string vendor = collapseWhitespaceASCII(buffer, true);
if (vendor == "GenuineIntel")
return "Intel Corporation";
else if (vendor == "AuthenticAMD" || vendor == "AMDisbetter!")
return "Advanced Micro Devices, Inc.";
else if (vendor == "CentaurHauls")
return "Centaur";
else if (vendor == "CyrixInstead")
return "Cyrix";
else if (vendor == "TransmetaCPU" || vendor == "GenuineTMx86")
return "Transmeta";
else if (vendor == "Geode by NSC")
return "National Semiconductor";
else if (vendor == "NexGenDriven")
return "NexGen";
else if (vendor == "RiseRiseRise")
return "Rise";
else if (vendor == "SiS SiS SiS")
return "SiS";
else if (vendor == "UMC UMC UMC")
return "UMC";
else if (vendor == "VIA VIA VIA")
return "VIA";
else if (vendor == "Vortex86 SoC")
return "Vortex";
else if (vendor == "KVMKVMKVMKVM")
return "KVM";
else if (vendor == "Microsoft Hv")
return "Microsoft Hyper-V or Windows Virtual PC";
else if (vendor == "VMwareVMware")
return "VMware";
else if (vendor == "XenVMMXenVMM")
return "Xen HVM";
else
return vendor;
}
} // namespace base
<commit_msg>cpuid available only for x86 family.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "base/sys_info.h"
#include "base/cpuid_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include <algorithm>
#include <cstring>
namespace base {
// static
std::string SysInfo::processorName()
{
#if defined(ARCH_CPU_X86_FAMILY)
CpuidUtil cpuidUtil;
cpuidUtil.get(0x80000000);
uint32_t max_leaf = cpuidUtil.eax();
if (max_leaf < 0x80000002)
return std::string();
max_leaf = std::min(max_leaf, 0x80000004);
char buffer[49];
memset(&buffer[0], 0, sizeof(buffer));
for (uint32_t leaf = 0x80000002, offset = 0; leaf <= max_leaf; ++leaf, offset += 16)
{
cpuidUtil.get(leaf);
uint32_t eax = cpuidUtil.eax();
uint32_t ebx = cpuidUtil.ebx();
uint32_t ecx = cpuidUtil.ecx();
uint32_t edx = cpuidUtil.edx();
memcpy(&buffer[offset + 0], &eax, sizeof(eax));
memcpy(&buffer[offset + 4], &ebx, sizeof(ebx));
memcpy(&buffer[offset + 8], &ecx, sizeof(ecx));
memcpy(&buffer[offset + 12], &edx, sizeof(edx));
}
std::string result(buffer);
removeChars(&result, "(TM)");
removeChars(&result, "(tm)");
removeChars(&result, "(R)");
removeChars(&result, "CPU");
removeChars(&result, "Quad-Core Processor");
removeChars(&result, "Six-Core Processor");
removeChars(&result, "Eight-Core Processor");
std::string_view at("@");
auto sub = find_end(result.begin(), result.end(), at.begin(), at.end());
if (sub != result.end())
result.erase(sub - 1, result.end());
return collapseWhitespaceASCII(result, true);
#else
NOTIMPLEMENTED();
return std::string();
#endif
}
// static
std::string SysInfo::processorVendor()
{
#if defined(ARCH_CPU_X86_FAMILY)
CpuidUtil cpuidUtil;
cpuidUtil.get(0x00000000);
uint32_t ebx = cpuidUtil.ebx();
uint32_t ecx = cpuidUtil.ecx();
uint32_t edx = cpuidUtil.edx();
char buffer[13];
memset(&buffer[0], 0, sizeof(buffer));
memcpy(&buffer[0], &ebx, sizeof(ebx));
memcpy(&buffer[4], &edx, sizeof(edx));
memcpy(&buffer[8], &ecx, sizeof(ecx));
std::string vendor = collapseWhitespaceASCII(buffer, true);
if (vendor == "GenuineIntel")
return "Intel Corporation";
else if (vendor == "AuthenticAMD" || vendor == "AMDisbetter!")
return "Advanced Micro Devices, Inc.";
else if (vendor == "CentaurHauls")
return "Centaur";
else if (vendor == "CyrixInstead")
return "Cyrix";
else if (vendor == "TransmetaCPU" || vendor == "GenuineTMx86")
return "Transmeta";
else if (vendor == "Geode by NSC")
return "National Semiconductor";
else if (vendor == "NexGenDriven")
return "NexGen";
else if (vendor == "RiseRiseRise")
return "Rise";
else if (vendor == "SiS SiS SiS")
return "SiS";
else if (vendor == "UMC UMC UMC")
return "UMC";
else if (vendor == "VIA VIA VIA")
return "VIA";
else if (vendor == "Vortex86 SoC")
return "Vortex";
else if (vendor == "KVMKVMKVMKVM")
return "KVM";
else if (vendor == "Microsoft Hv")
return "Microsoft Hyper-V or Windows Virtual PC";
else if (vendor == "VMwareVMware")
return "VMware";
else if (vendor == "XenVMMXenVMM")
return "Xen HVM";
else
return vendor;
#else
NOTIMPLEMENTED();
return std::string();
#endif
}
} // namespace base
<|endoftext|> |
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************/
#include <geos/io.h>
#undef DEBUG_WKB_WRITER
namespace geos {
void
WKBWriter::write(const Geometry &g, ostream &os)
{
outStream = &os;
switch (g.getGeometryTypeId()) {
case GEOS_POINT:
return writePoint((Point &)g);
case GEOS_LINESTRING:
case GEOS_LINEARRING:
return writeLineString((LineString &)g);
case GEOS_POLYGON:
return writePolygon((Polygon &)g);
case GEOS_MULTIPOINT:
case GEOS_MULTILINESTRING:
case GEOS_MULTIPOLYGON:
case GEOS_GEOMETRYCOLLECTION:
return writeGeometryCollection(
(GeometryCollection &)g,
WKBConstants::wkbGeometryCollection);
default:
Assert::shouldNeverReachHere("Unknown Geometry type");
}
}
void
WKBWriter::writePoint(const Point &g)
{
if (g.isEmpty()) throw new
IllegalArgumentException("Empty Points cannot be represented in WKB");
writeByteOrder();
writeGeometryType(WKBConstants::wkbPoint);
writeCoordinateSequence(*(g.getCoordinatesRO()), false);
}
void
WKBWriter::writeLineString(const LineString &g)
{
writeByteOrder();
writeGeometryType(WKBConstants::wkbLineString);
writeCoordinateSequence(*(g.getCoordinatesRO()), true);
}
void
WKBWriter::writePolygon(const Polygon &g)
{
writeByteOrder();
writeGeometryType(WKBConstants::wkbPolygon);
int nholes = g.getNumInteriorRing();
writeInt(nholes+1);
writeCoordinateSequence(*(g.getExteriorRing()->getCoordinatesRO()),
true);
for (int i=0; i<nholes; i++)
writeCoordinateSequence(
*(g.getInteriorRingN(i)->getCoordinatesRO()),
true);
}
void
WKBWriter::writeGeometryCollection(const GeometryCollection &g,
int wkbtype)
{
writeByteOrder();
writeGeometryType(wkbtype);
int ngeoms = g.getNumGeometries();
writeInt(ngeoms);
for (int i=0; i<ngeoms; i++)
write(*(g.getGeometryN(i)), *outStream);
}
void
WKBWriter::writeByteOrder()
{
outStream->write(reinterpret_cast<char*>(&byteOrder), 1);
}
void
WKBWriter::writeGeometryType(int typeId)
{
writeInt(typeId);
}
void
WKBWriter::writeInt(int val)
{
outStream->write(reinterpret_cast<char *>(&val), 4);
}
void
WKBWriter::writeCoordinateSequence(const CoordinateSequence &cs,
bool sized)
{
int size = cs.getSize();
bool is3d=false;
if ( cs.getDimension() > 2 && outputDimension > 2) is3d = true;
if (sized) writeInt(size);
for (int i=0; i<size; i++) writeCoordinate(cs, i, is3d);
}
void
WKBWriter::writeCoordinate(const CoordinateSequence &cs, int idx,
bool is3d)
{
#if DEBUG_WKB_WRITER
cout<<"writeCoordinate: X:"<<cs.getX(idx)<<" Y:"<<cs.getY(idx)<<endl;
#endif
ByteOrderValues::putDouble(cs.getX(idx), buf, byteOrder);
outStream->write(reinterpret_cast<char *>(buf), 8);
ByteOrderValues::putDouble(cs.getY(idx), buf, byteOrder);
outStream->write(reinterpret_cast<char *>(buf), 8);
if ( is3d )
{
ByteOrderValues::putDouble(
cs.getOrdinate(idx, CoordinateSequence::X),
buf, byteOrder);
outStream->write(reinterpret_cast<char *>(buf), 8);
}
}
} // namespace geos
<commit_msg>Fixed bug writing WKB for all Multi* geoms as Collections.<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************/
#include <geos/io.h>
#undef DEBUG_WKB_WRITER
namespace geos {
void
WKBWriter::write(const Geometry &g, ostream &os)
{
outStream = &os;
switch (g.getGeometryTypeId()) {
case GEOS_POINT:
return writePoint((Point &)g);
case GEOS_LINESTRING:
case GEOS_LINEARRING:
return writeLineString((LineString &)g);
case GEOS_POLYGON:
return writePolygon((Polygon &)g);
case GEOS_MULTIPOINT:
return writeGeometryCollection(
(GeometryCollection &)g,
WKBConstants::wkbMultiPoint);
case GEOS_MULTILINESTRING:
return writeGeometryCollection(
(GeometryCollection &)g,
WKBConstants::wkbMultiLineString);
case GEOS_MULTIPOLYGON:
return writeGeometryCollection(
(GeometryCollection &)g,
WKBConstants::wkbMultiPolygon);
case GEOS_GEOMETRYCOLLECTION:
return writeGeometryCollection(
(GeometryCollection &)g,
WKBConstants::wkbGeometryCollection);
default:
Assert::shouldNeverReachHere("Unknown Geometry type");
}
}
void
WKBWriter::writePoint(const Point &g)
{
if (g.isEmpty()) throw new
IllegalArgumentException("Empty Points cannot be represented in WKB");
writeByteOrder();
writeGeometryType(WKBConstants::wkbPoint);
writeCoordinateSequence(*(g.getCoordinatesRO()), false);
}
void
WKBWriter::writeLineString(const LineString &g)
{
writeByteOrder();
writeGeometryType(WKBConstants::wkbLineString);
writeCoordinateSequence(*(g.getCoordinatesRO()), true);
}
void
WKBWriter::writePolygon(const Polygon &g)
{
writeByteOrder();
writeGeometryType(WKBConstants::wkbPolygon);
int nholes = g.getNumInteriorRing();
writeInt(nholes+1);
writeCoordinateSequence(*(g.getExteriorRing()->getCoordinatesRO()),
true);
for (int i=0; i<nholes; i++)
writeCoordinateSequence(
*(g.getInteriorRingN(i)->getCoordinatesRO()),
true);
}
void
WKBWriter::writeGeometryCollection(const GeometryCollection &g,
int wkbtype)
{
writeByteOrder();
writeGeometryType(wkbtype);
int ngeoms = g.getNumGeometries();
writeInt(ngeoms);
for (int i=0; i<ngeoms; i++)
write(*(g.getGeometryN(i)), *outStream);
}
void
WKBWriter::writeByteOrder()
{
outStream->write(reinterpret_cast<char*>(&byteOrder), 1);
}
void
WKBWriter::writeGeometryType(int typeId)
{
writeInt(typeId);
}
void
WKBWriter::writeInt(int val)
{
outStream->write(reinterpret_cast<char *>(&val), 4);
}
void
WKBWriter::writeCoordinateSequence(const CoordinateSequence &cs,
bool sized)
{
int size = cs.getSize();
bool is3d=false;
if ( cs.getDimension() > 2 && outputDimension > 2) is3d = true;
if (sized) writeInt(size);
for (int i=0; i<size; i++) writeCoordinate(cs, i, is3d);
}
void
WKBWriter::writeCoordinate(const CoordinateSequence &cs, int idx,
bool is3d)
{
#if DEBUG_WKB_WRITER
cout<<"writeCoordinate: X:"<<cs.getX(idx)<<" Y:"<<cs.getY(idx)<<endl;
#endif
ByteOrderValues::putDouble(cs.getX(idx), buf, byteOrder);
outStream->write(reinterpret_cast<char *>(buf), 8);
ByteOrderValues::putDouble(cs.getY(idx), buf, byteOrder);
outStream->write(reinterpret_cast<char *>(buf), 8);
if ( is3d )
{
ByteOrderValues::putDouble(
cs.getOrdinate(idx, CoordinateSequence::X),
buf, byteOrder);
outStream->write(reinterpret_cast<char *>(buf), 8);
}
}
} // namespace geos
<|endoftext|> |
<commit_before>#include "tools/cabana/binaryview.h"
#include <QApplication>
#include <QHeaderView>
#include <QPainter>
#include "tools/cabana/canmessages.h"
// BinaryView
const int CELL_HEIGHT = 30;
BinaryView::BinaryView(QWidget *parent) : QTableView(parent) {
model = new BinaryViewModel(this);
setModel(model);
setItemDelegate(new BinaryItemDelegate(this));
horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
horizontalHeader()->hide();
verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// replace selection model
auto old_model = selectionModel();
setSelectionModel(new BinarySelectionModel(model));
delete old_model;
QObject::connect(model, &QAbstractItemModel::modelReset, [this]() {
setFixedHeight((CELL_HEIGHT + 1) * std::min(model->rowCount(), 8) + 2);
});
}
void BinaryView::mouseReleaseEvent(QMouseEvent *event) {
QTableView::mouseReleaseEvent(event);
if (auto indexes = selectedIndexes(); !indexes.isEmpty()) {
int start_bit = indexes.first().row() * 8 + indexes.first().column();
int size = indexes.back().row() * 8 + indexes.back().column() - start_bit + 1;
emit cellsSelected(start_bit, size);
}
}
void BinaryView::setMessage(const QString &message_id) {
msg_id = message_id;
model->setMessage(message_id);
resizeRowsToContents();
clearSelection();
updateState();
}
void BinaryView::updateState() {
model->updateState();
}
// BinaryViewModel
void BinaryViewModel::setMessage(const QString &message_id) {
msg_id = message_id;
beginResetModel();
items.clear();
row_count = 0;
dbc_msg = dbc()->msg(msg_id);
if (dbc_msg) {
row_count = dbc_msg->size;
items.resize(row_count * column_count);
for (int i = 0; i < dbc_msg->sigs.size(); ++i) {
const auto &sig = dbc_msg->sigs[i];
const int start = sig.is_little_endian ? sig.start_bit : bigEndianBitIndex(sig.start_bit);
const int end = start + sig.size - 1;
for (int j = start; j <= end; ++j) {
int idx = column_count * (j / 8) + j % 8;
if (idx >= items.size()) {
qWarning() << "signal " << sig.name.c_str() << "out of bounds.start_bit:" << sig.start_bit << "size:" << sig.size;
break;
}
if (j == start) {
sig.is_little_endian ? items[idx].is_lsb = true : items[idx].is_msb = true;
} else if (j == end) {
sig.is_little_endian ? items[idx].is_msb = true : items[idx].is_lsb = true;
}
items[idx].bg_color = QColor(getColor(i));
}
}
}
endResetModel();
}
QModelIndex BinaryViewModel::index(int row, int column, const QModelIndex &parent) const {
return createIndex(row, column, (void *)&items[row * column_count + column]);
}
Qt::ItemFlags BinaryViewModel::flags(const QModelIndex &index) const {
return (index.column() == column_count - 1) ? Qt::ItemIsEnabled : Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
void BinaryViewModel::updateState() {
auto prev_items = items;
const auto &binary = can->lastMessage(msg_id).dat;
// data size may changed.
if (!dbc_msg && binary.size() != row_count) {
beginResetModel();
row_count = binary.size();
items.clear();
items.resize(row_count * column_count);
endResetModel();
}
char hex[3] = {'\0'};
for (int i = 0; i < std::min(binary.size(), row_count); ++i) {
for (int j = 0; j < column_count - 1; ++j) {
items[i * column_count + j].val = QChar((binary[i] >> (7 - j)) & 1 ? '1' : '0');
}
hex[0] = toHex(binary[i] >> 4);
hex[1] = toHex(binary[i] & 0xf);
items[i * column_count + 8].val = hex;
}
for (int i = 0; i < items.size(); ++i) {
if (i >= prev_items.size() || prev_items[i].val != items[i].val) {
auto idx = index(i / column_count, i % column_count);
emit dataChanged(idx, idx);
}
}
}
QVariant BinaryViewModel::headerData(int section, Qt::Orientation orientation, int role) const {
if (orientation == Qt::Vertical) {
switch (role) {
case Qt::DisplayRole: return section + 1;
case Qt::SizeHintRole: return QSize(30, CELL_HEIGHT);
case Qt::TextAlignmentRole: return Qt::AlignCenter;
}
}
return {};
}
// BinarySelectionModel
void BinarySelectionModel::select(const QItemSelection &selection, QItemSelectionModel::SelectionFlags command) {
QItemSelection new_selection = selection;
if (auto indexes = selection.indexes(); !indexes.isEmpty()) {
auto [begin_idx, end_idx] = (QModelIndex[]){indexes.first(), indexes.back()};
for (int row = begin_idx.row(); row <= end_idx.row(); ++row) {
int left_col = (row == begin_idx.row()) ? begin_idx.column() : 0;
int right_col = (row == end_idx.row()) ? end_idx.column() : 7;
new_selection.merge({model()->index(row, left_col), model()->index(row, right_col)}, command);
}
}
QItemSelectionModel::select(new_selection, command);
}
// BinaryItemDelegate
BinaryItemDelegate::BinaryItemDelegate(QObject *parent) : QStyledItemDelegate(parent) {
// cache fonts and color
small_font.setPointSize(6);
bold_font.setBold(true);
highlight_color = QApplication::style()->standardPalette().color(QPalette::Active, QPalette::Highlight);
}
QSize BinaryItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
QSize sz = QStyledItemDelegate::sizeHint(option, index);
return {sz.width(), CELL_HEIGHT};
}
void BinaryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
auto item = (const BinaryViewModel::Item *)index.internalPointer();
painter->save();
// TODO: highlight signal cells on mouse over
painter->fillRect(option.rect, option.state & QStyle::State_Selected ? highlight_color : item->bg_color);
if (index.column() == 8) {
painter->setFont(bold_font);
}
painter->drawText(option.rect, Qt::AlignCenter, item->val);
if (item->is_msb || item->is_lsb) {
painter->setFont(small_font);
painter->drawText(option.rect, Qt::AlignHCenter | Qt::AlignBottom, item->is_msb ? "MSB" : "LSB");
}
painter->restore();
}
<commit_msg>cabana: fix binary view for can-fd<commit_after>#include "tools/cabana/binaryview.h"
#include <QApplication>
#include <QHeaderView>
#include <QPainter>
#include "tools/cabana/canmessages.h"
// BinaryView
const int CELL_HEIGHT = 30;
BinaryView::BinaryView(QWidget *parent) : QTableView(parent) {
model = new BinaryViewModel(this);
setModel(model);
setItemDelegate(new BinaryItemDelegate(this));
horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
horizontalHeader()->hide();
verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// replace selection model
auto old_model = selectionModel();
setSelectionModel(new BinarySelectionModel(model));
delete old_model;
QObject::connect(model, &QAbstractItemModel::modelReset, [this]() {
setFixedHeight((CELL_HEIGHT + 1) * std::min(model->rowCount(), 64) + 2);
});
}
void BinaryView::mouseReleaseEvent(QMouseEvent *event) {
QTableView::mouseReleaseEvent(event);
if (auto indexes = selectedIndexes(); !indexes.isEmpty()) {
int start_bit = indexes.first().row() * 8 + indexes.first().column();
int size = indexes.back().row() * 8 + indexes.back().column() - start_bit + 1;
emit cellsSelected(start_bit, size);
}
}
void BinaryView::setMessage(const QString &message_id) {
msg_id = message_id;
model->setMessage(message_id);
resizeRowsToContents();
clearSelection();
updateState();
}
void BinaryView::updateState() {
model->updateState();
}
// BinaryViewModel
void BinaryViewModel::setMessage(const QString &message_id) {
msg_id = message_id;
beginResetModel();
items.clear();
row_count = 0;
dbc_msg = dbc()->msg(msg_id);
if (dbc_msg) {
row_count = dbc_msg->size;
items.resize(row_count * column_count);
for (int i = 0; i < dbc_msg->sigs.size(); ++i) {
const auto &sig = dbc_msg->sigs[i];
const int start = sig.is_little_endian ? sig.start_bit : bigEndianBitIndex(sig.start_bit);
const int end = start + sig.size - 1;
for (int j = start; j <= end; ++j) {
int idx = column_count * (j / 8) + j % 8;
if (idx >= items.size()) {
qWarning() << "signal " << sig.name.c_str() << "out of bounds.start_bit:" << sig.start_bit << "size:" << sig.size;
break;
}
if (j == start) {
sig.is_little_endian ? items[idx].is_lsb = true : items[idx].is_msb = true;
} else if (j == end) {
sig.is_little_endian ? items[idx].is_msb = true : items[idx].is_lsb = true;
}
items[idx].bg_color = QColor(getColor(i));
}
}
}
endResetModel();
}
QModelIndex BinaryViewModel::index(int row, int column, const QModelIndex &parent) const {
return createIndex(row, column, (void *)&items[row * column_count + column]);
}
Qt::ItemFlags BinaryViewModel::flags(const QModelIndex &index) const {
return (index.column() == column_count - 1) ? Qt::ItemIsEnabled : Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
void BinaryViewModel::updateState() {
auto prev_items = items;
const auto &binary = can->lastMessage(msg_id).dat;
// data size may changed.
if (!dbc_msg && binary.size() != row_count) {
beginResetModel();
row_count = binary.size();
items.clear();
items.resize(row_count * column_count);
endResetModel();
}
char hex[3] = {'\0'};
for (int i = 0; i < std::min(binary.size(), row_count); ++i) {
for (int j = 0; j < column_count - 1; ++j) {
items[i * column_count + j].val = QChar((binary[i] >> (7 - j)) & 1 ? '1' : '0');
}
hex[0] = toHex(binary[i] >> 4);
hex[1] = toHex(binary[i] & 0xf);
items[i * column_count + 8].val = hex;
}
for (int i = 0; i < items.size(); ++i) {
if (i >= prev_items.size() || prev_items[i].val != items[i].val) {
auto idx = index(i / column_count, i % column_count);
emit dataChanged(idx, idx);
}
}
}
QVariant BinaryViewModel::headerData(int section, Qt::Orientation orientation, int role) const {
if (orientation == Qt::Vertical) {
switch (role) {
case Qt::DisplayRole: return section + 1;
case Qt::SizeHintRole: return QSize(30, CELL_HEIGHT);
case Qt::TextAlignmentRole: return Qt::AlignCenter;
}
}
return {};
}
// BinarySelectionModel
void BinarySelectionModel::select(const QItemSelection &selection, QItemSelectionModel::SelectionFlags command) {
QItemSelection new_selection = selection;
if (auto indexes = selection.indexes(); !indexes.isEmpty()) {
auto [begin_idx, end_idx] = (QModelIndex[]){indexes.first(), indexes.back()};
for (int row = begin_idx.row(); row <= end_idx.row(); ++row) {
int left_col = (row == begin_idx.row()) ? begin_idx.column() : 0;
int right_col = (row == end_idx.row()) ? end_idx.column() : 7;
new_selection.merge({model()->index(row, left_col), model()->index(row, right_col)}, command);
}
}
QItemSelectionModel::select(new_selection, command);
}
// BinaryItemDelegate
BinaryItemDelegate::BinaryItemDelegate(QObject *parent) : QStyledItemDelegate(parent) {
// cache fonts and color
small_font.setPointSize(6);
bold_font.setBold(true);
highlight_color = QApplication::style()->standardPalette().color(QPalette::Active, QPalette::Highlight);
}
QSize BinaryItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
QSize sz = QStyledItemDelegate::sizeHint(option, index);
return {sz.width(), CELL_HEIGHT};
}
void BinaryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
auto item = (const BinaryViewModel::Item *)index.internalPointer();
painter->save();
// TODO: highlight signal cells on mouse over
painter->fillRect(option.rect, option.state & QStyle::State_Selected ? highlight_color : item->bg_color);
if (index.column() == 8) {
painter->setFont(bold_font);
}
painter->drawText(option.rect, Qt::AlignCenter, item->val);
if (item->is_msb || item->is_lsb) {
painter->setFont(small_font);
painter->drawText(option.rect, Qt::AlignHCenter | Qt::AlignBottom, item->is_msb ? "MSB" : "LSB");
}
painter->restore();
}
<|endoftext|> |
<commit_before>/*
* HyPerConnection.hpp
*
* Created on: Oct 21, 2008
* Author: Craig Rasmussen
*/
#ifndef HYPERCONN_HPP_
#define HYPERCONN_HPP_
#include "PVConnection.h"
#include "../columns/InterColComm.hpp"
#include "../include/pv_types.h"
#include "../io/PVParams.hpp"
#include "../layers/HyPerLayer.hpp"
#include "../utils/Timer.hpp"
#define PROTECTED_NUMBER 13
#define MAX_ARBOR_LIST (1+MAX_NEIGHBORS)
namespace PV {
class HyPerCol;
class HyPerLayer;
class ConnectionProbe;
/**
* A PVConnection identifies a connection between two layers
*/
typedef struct {
int delay; // current output delay in the associated f ring buffer (should equal fixed delay + varible delay for valid connection)
int fixDelay; // fixed output delay. TODO: should be float
int varDelayMin; // minimum variable conduction delay
int varDelayMax; // maximum variable conduction delay
int numDelay;
int isGraded; //==1, release is stochastic with prob = (activity <= 1), default is 0 (no graded release)
float vel; // conduction velocity in position units (pixels) per time step--added by GTK
float rmin; // minimum connection distance
float rmax; // maximum connection distance
} PVConnParams;
class HyPerConn {
public:
HyPerConn();
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, const char * filename);
virtual ~HyPerConn();
virtual int deliver(Publisher * pub, PVLayerCube * cube, int neighbor);
virtual int insertProbe(ConnectionProbe * p);
virtual int outputState(float time, bool last=false);
virtual int updateState(float time, float dt);
virtual int updateWeights(int axonId);
inline int numberOfAxonalArborLists() {return numAxonalArborLists;}
virtual int numWeightPatches(int arbor);
virtual int numDataPatches(int arbor);
virtual int writeWeights(float time, bool last=false);
virtual int writeWeights(PVPatch ** patches, int numPatches,
const char * filename, float time, bool last);
virtual int writeTextWeights(const char * filename, int k);
virtual int writePostSynapticWeights(float time, bool last=false);
int readWeights(const char * filename);
virtual PVPatch ** readWeights(PVPatch ** patches, int numPatches,
const char * filename);
virtual PVPatch * getWeights(int kPre, int arbor);
virtual PVPatch * getPlasticityIncrement(int k, int arbor);
inline PVLayerCube * getPlasticityDecrement() {return pDecr;}
inline PVPatch ** weights(int neighbor) {return wPatches[neighbor];}
inline const char * getName() {return name;}
inline int getDelay() {return params->delay;}
virtual float minWeight() {return 0.0;}
virtual float maxWeight() {return wMax;}
inline int xPatchSize() {return nxp;}
inline int yPatchSize() {return nyp;}
inline int fPatchSize() {return nfp;}
inline PVAxonalArbor * axonalArbor(int kPre, int neighbor)
{return &axonalArborList[neighbor][kPre];}
HyPerLayer * preSynapticLayer() {return pre;}
HyPerLayer * postSynapticLayer() {return post;}
int getConnectionId() {return connId;}
void setConnectionId(int id) {connId = id;}
int setParams(PVParams * params, PVConnParams * p);
PVPatch ** convertPreSynapticWeights(float time);
int preSynapticPatchHead(int kxPost, int kyPost, int kfPost, int * kxPre, int * kyPre);
int postSynapticPatchHead(int kPre,
int * kxPostOut, int * kyPostOut, int * kfPostOut,
int * dxOut, int * dyOut, int * nxpOut, int * nypOut);
virtual int gauss2DCalcWeights(PVPatch * wp, int kPre, int noPost,
int numFlanks, float shift, float rotate, float aspect, float sigma,
float r2Max, float strength);
virtual int cocircCalcWeights(PVPatch * wp, int kPre, int noPre, int noPost,
float sigma_cocirc, float sigma_kurve, float sigma_chord, float delta_theta_max,
float cocirc_self, float delta_radius_curvature, int numFlanks, float shift,
float aspect, float rotate, float sigma, float r2Max, float strength);
virtual PVPatch ** normalizeWeights(PVPatch ** patches, int numPatches);
virtual int kernelIndexToPatchIndex(int kernelIndex, int * kxPatchIndex = NULL,
int * kyPatchIndex = NULL, int * kfPatchIndex = NULL);
virtual int patchIndexToKernelIndex(int patchIndex, int * kxKernelIndex = NULL,
int * kyKernelIndex = NULL, int * kfKernelIndex = NULL);
protected:
HyPerLayer * pre;
HyPerLayer * post;
HyPerCol * parent;
PVLayerCube * pDecr; // plasticity decrement variable (Mi) for pre-synaptic layer
PVPatch ** pIncr; // list of stdp patches Psij variable
PVPatch ** wPatches[MAX_ARBOR_LIST]; // list of weight patches, one set per neighbor
PVPatch ** wPostPatches; // post-synaptic linkage of weights
PVAxonalArbor * axonalArborList[MAX_ARBOR_LIST]; // list of axonal arbors for each neighbor
ChannelType channel; // which channel of the post to update (e.g. inhibit)
int connId; // connection id
char * name;
int nxp, nyp, nfp; // size of weight dimensions
int numParams;
PVConnParams * params;
int numAxonalArborLists; // number of axonal arbors (weight patches) for presynaptic layer
// STDP parameters for modifying weights
float ampLTP; // long term potentiation amplitude
float ampLTD; // long term depression amplitude
float tauLTP;
float tauLTD;
float dWMax;
float wMax;
float wMin;
int numProbes;
ConnectionProbe ** probes; // probes used to output data
bool stdpFlag; // presence of spike timing dependent plasticity
bool ioAppend; // controls opening of binary files
float wPostTime; // time of last conversion to wPostPatches
float writeTime; // time of next output
float writeStep; // output time interval
Timer * update_timer;
protected:
virtual int setPatchSize(const char * filename);
int patchSizeFromFile(const char * filename);
virtual int checkPatchSize(int patchSize, int scalePre, int scalePost, char dim);
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, ChannelType channel, const char * filename);
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, ChannelType channel);
int initialize_base();
int initialize(const char * filename);
int initializeSTDP();
virtual PVPatch ** initializeWeights(PVPatch ** patches, int numPatches,
const char * filename);
// PVPatch ** initializeRandomWeights(PVPatch ** patches, int numPatches, int seed);
PVPatch ** initializeRandomWeights(PVPatch ** patches, int numPatches);
PVPatch ** initializeSmartWeights(PVPatch ** patches, int numPatches);
virtual PVPatch ** initializeDefaultWeights(PVPatch ** patches, int numPatches);
PVPatch ** initializeGaussian2DWeights(PVPatch ** patches, int numPatches);
PVPatch ** initializeCocircWeights(PVPatch ** patches, int numPatches);
virtual PVPatch ** createWeights(PVPatch ** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch);
PVPatch ** createWeights(PVPatch ** patches);
virtual PVPatch ** allocWeights(PVPatch ** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch);
PVPatch ** allocWeights(PVPatch ** patches);
int uniformWeights(PVPatch * wp, float wMin, float wMax);
int gaussianWeights(PVPatch * wp, float mean, float stdev);
// int uniformWeights(PVPatch * wp, float wMin, float wMax, int * seed);
// int gaussianWeights(PVPatch * wp, float mean, float stdev, int * seed);
int smartWeights(PVPatch * wp, int k);
virtual int checkPVPFileHeader(Communicator * comm, const PVLayerLoc * loc, int params[], int numParams);
virtual int checkWeightsHeader(const char * filename, int wgtParams[]);
virtual int deleteWeights();
virtual int createAxonalArbors();
// static member functions
public:
static PVPatch ** createPatches(int numBundles, int nx, int ny, int nf)
{
PVPatch ** patches = (PVPatch**) malloc(numBundles*sizeof(PVPatch*));
for (int i = 0; i < numBundles; i++) {
patches[i] = pvpatch_inplace_new(nx, ny, nf);
}
return patches;
}
static int deletePatches(int numBundles, PVPatch ** patches)
{
for (int i = 0; i < numBundles; i++) {
pvpatch_inplace_delete(patches[i]);
}
free(patches);
return 0;
}
};
} // namespace PV
#endif /* HYPERCONN_HPP_ */
<commit_msg>Modified class to include local Wmax variables, and their dynamic evolution, in the post synaptic layer.<commit_after>/*
* HyPerConnection.hpp
*
* Created on: Oct 21, 2008
* Author: Craig Rasmussen
*/
#ifndef HYPERCONN_HPP_
#define HYPERCONN_HPP_
#include "PVConnection.h"
#include "../columns/InterColComm.hpp"
#include "../include/pv_types.h"
#include "../io/PVParams.hpp"
#include "../layers/HyPerLayer.hpp"
#include "../utils/Timer.hpp"
#define PROTECTED_NUMBER 13
#define MAX_ARBOR_LIST (1+MAX_NEIGHBORS)
namespace PV {
class HyPerCol;
class HyPerLayer;
class ConnectionProbe;
/**
* A PVConnection identifies a connection between two layers
*/
typedef struct {
int delay; // current output delay in the associated f ring buffer (should equal fixed delay + varible delay for valid connection)
int fixDelay; // fixed output delay. TODO: should be float
int varDelayMin; // minimum variable conduction delay
int varDelayMax; // maximum variable conduction delay
int numDelay;
int isGraded; //==1, release is stochastic with prob = (activity <= 1), default is 0 (no graded release)
float vel; // conduction velocity in position units (pixels) per time step--added by GTK
float rmin; // minimum connection distance
float rmax; // maximum connection distance
} PVConnParams;
class HyPerConn {
public:
HyPerConn();
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, const char * filename);
virtual ~HyPerConn();
virtual int deliver(Publisher * pub, PVLayerCube * cube, int neighbor);
virtual int insertProbe(ConnectionProbe * p);
virtual int outputState(float time, bool last=false);
virtual int updateState(float time, float dt);
virtual int updateWmax();
virtual int updateWeights(int axonId);
inline int numberOfAxonalArborLists() {return numAxonalArborLists;}
virtual int numWeightPatches(int arbor);
virtual int numDataPatches(int arbor);
virtual int writeWeights(float time, bool last=false);
virtual int writeWeights(PVPatch ** patches, int numPatches,
const char * filename, float time, bool last);
virtual int writeTextWeights(const char * filename, int k);
virtual int writePostSynapticWeights(float time, bool last=false);
int readWeights(const char * filename);
virtual PVPatch ** readWeights(PVPatch ** patches, int numPatches,
const char * filename);
virtual PVPatch * getWeights(int kPre, int arbor);
virtual PVPatch * getPlasticityIncrement(int k, int arbor);
inline PVLayerCube * getPlasticityDecrement() {return pDecr;}
inline PVPatch ** weights(int neighbor) {return wPatches[neighbor];}
inline const char * getName() {return name;}
inline int getDelay() {return params->delay;}
virtual float minWeight() {return 0.0;}
virtual float maxWeight() {return wMax;}
inline int xPatchSize() {return nxp;}
inline int yPatchSize() {return nyp;}
inline int fPatchSize() {return nfp;}
inline PVAxonalArbor * axonalArbor(int kPre, int neighbor)
{return &axonalArborList[neighbor][kPre];}
HyPerLayer * preSynapticLayer() {return pre;}
HyPerLayer * postSynapticLayer() {return post;}
int getConnectionId() {return connId;}
void setConnectionId(int id) {connId = id;}
int setParams(PVParams * params, PVConnParams * p);
PVPatch ** convertPreSynapticWeights(float time);
int preSynapticPatchHead(int kxPost, int kyPost, int kfPost, int * kxPre, int * kyPre);
int postSynapticPatchHead(int kPre,
int * kxPostOut, int * kyPostOut, int * kfPostOut,
int * dxOut, int * dyOut, int * nxpOut, int * nypOut);
virtual int gauss2DCalcWeights(PVPatch * wp, int kPre, int noPost,
int numFlanks, float shift, float rotate, float aspect, float sigma,
float r2Max, float strength);
virtual int cocircCalcWeights(PVPatch * wp, int kPre, int noPre, int noPost,
float sigma_cocirc, float sigma_kurve, float sigma_chord, float delta_theta_max,
float cocirc_self, float delta_radius_curvature, int numFlanks, float shift,
float aspect, float rotate, float sigma, float r2Max, float strength);
virtual PVPatch ** normalizeWeights(PVPatch ** patches, int numPatches);
virtual int kernelIndexToPatchIndex(int kernelIndex, int * kxPatchIndex = NULL,
int * kyPatchIndex = NULL, int * kfPatchIndex = NULL);
virtual int patchIndexToKernelIndex(int patchIndex, int * kxKernelIndex = NULL,
int * kyKernelIndex = NULL, int * kfKernelIndex = NULL);
protected:
HyPerLayer * pre;
HyPerLayer * post;
HyPerCol * parent;
PVLayerCube * pDecr; // plasticity decrement variable (Mi) for pre-synaptic layer
PVPatch ** pIncr; // list of stdp patches Psij variable
PVPatch ** wPatches[MAX_ARBOR_LIST]; // list of weight patches, one set per neighbor
PVPatch ** wPostPatches; // post-synaptic linkage of weights
PVAxonalArbor * axonalArborList[MAX_ARBOR_LIST]; // list of axonal arbors for each neighbor
bool localWmaxFlag; // presence of rate dependent wMax;
pvdata_t * Wmax; // adaptive upper STDP weight boundary
float alphaW; // params in Wmax dynamics.
float gammaW;
float averageR; // predefined average rate
FILE * wmaxFP;
ChannelType channel; // which channel of the post to update (e.g. inhibit)
int connId; // connection id
char * name;
int nxp, nyp, nfp; // size of weight dimensions
int numParams;
PVConnParams * params;
int numAxonalArborLists; // number of axonal arbors (weight patches) for presynaptic layer
// STDP parameters for modifying weights
float ampLTP; // long term potentiation amplitude
float ampLTD; // long term depression amplitude
float tauLTP;
float tauLTD;
float dWMax;
float wMax;
float wMin;
int numProbes;
ConnectionProbe ** probes; // probes used to output data
bool stdpFlag; // presence of spike timing dependent plasticity
bool ioAppend; // controls opening of binary files
float wPostTime; // time of last conversion to wPostPatches
float writeTime; // time of next output
float writeStep; // output time interval
Timer * update_timer;
protected:
virtual int setPatchSize(const char * filename);
int patchSizeFromFile(const char * filename);
virtual int checkPatchSize(int patchSize, int scalePre, int scalePost, char dim);
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, ChannelType channel, const char * filename);
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, ChannelType channel);
int initialize_base();
int initialize(const char * filename);
int initializeSTDP();
virtual PVPatch ** initializeWeights(PVPatch ** patches, int numPatches,
const char * filename);
// PVPatch ** initializeRandomWeights(PVPatch ** patches, int numPatches, int seed);
PVPatch ** initializeRandomWeights(PVPatch ** patches, int numPatches);
PVPatch ** initializeSmartWeights(PVPatch ** patches, int numPatches);
virtual PVPatch ** initializeDefaultWeights(PVPatch ** patches, int numPatches);
PVPatch ** initializeGaussian2DWeights(PVPatch ** patches, int numPatches);
PVPatch ** initializeCocircWeights(PVPatch ** patches, int numPatches);
virtual PVPatch ** createWeights(PVPatch ** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch);
PVPatch ** createWeights(PVPatch ** patches);
virtual PVPatch ** allocWeights(PVPatch ** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch);
PVPatch ** allocWeights(PVPatch ** patches);
int uniformWeights(PVPatch * wp, float wMin, float wMax);
int gaussianWeights(PVPatch * wp, float mean, float stdev);
// int uniformWeights(PVPatch * wp, float wMin, float wMax, int * seed);
// int gaussianWeights(PVPatch * wp, float mean, float stdev, int * seed);
int smartWeights(PVPatch * wp, int k);
virtual int checkPVPFileHeader(Communicator * comm, const PVLayerLoc * loc, int params[], int numParams);
virtual int checkWeightsHeader(const char * filename, int wgtParams[]);
virtual int deleteWeights();
virtual int createAxonalArbors();
// static member functions
public:
static PVPatch ** createPatches(int numBundles, int nx, int ny, int nf)
{
PVPatch ** patches = (PVPatch**) malloc(numBundles*sizeof(PVPatch*));
for (int i = 0; i < numBundles; i++) {
patches[i] = pvpatch_inplace_new(nx, ny, nf);
}
return patches;
}
static int deletePatches(int numBundles, PVPatch ** patches)
{
for (int i = 0; i < numBundles; i++) {
pvpatch_inplace_delete(patches[i]);
}
free(patches);
return 0;
}
};
} // namespace PV
#endif /* HYPERCONN_HPP_ */
<|endoftext|> |
<commit_before>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#include "numpy_interop.hpp"
#if DYND_NUMPY_INTEROP
#include <numpy/arrayobject.h>
#include <numpy/arrayscalars.h>
#include <dynd/kernels/assignment_kernels.hpp>
#include <dynd/func/elwise.hpp>
#include <dynd/kernels/tuple_assignment_kernels.hpp>
#include <dynd/types/base_struct_type.hpp>
#include <dynd/memblock/array_memory_block.hpp>
#include "copy_to_numpy_arrfunc.hpp"
#include "copy_to_pyobject_arrfunc.hpp"
#include "utility_functions.hpp"
using namespace std;
using namespace dynd;
using namespace pydynd;
namespace {
struct strided_of_numpy_arrmeta {
fixed_dim_type_arrmeta sdt[NPY_MAXDIMS];
copy_to_numpy_arrmeta am;
};
} // anonymous namespace
/**
* This sets up a ckernel to copy from a dynd array
* to a numpy array. The destination numpy array is
* represented by dst_tp being ``void`` and the dst_arrmeta
* being a pointer to the ``PyArray_Descr *`` of the type for the destination.
*/
intptr_t copy_to_numpy_ck::instantiate(
const arrfunc_type_data *self_af, const ndt::arrfunc_type *af_tp,
char *DYND_UNUSED(data), void *ckb, intptr_t ckb_offset,
const dynd::ndt::type &dst_tp, const char *dst_arrmeta, intptr_t nsrc,
const dynd::ndt::type *src_tp, const char *const *src_arrmeta,
kernel_request_t kernreq, const eval::eval_context *ectx,
const dynd::nd::array &kwds, const std::map<dynd::nd::string, dynd::ndt::type> &tp_vars)
{
if (dst_tp.get_type_id() != void_type_id) {
stringstream ss;
ss << "Cannot instantiate arrfunc with signature ";
ss << af_tp << " with types (";
ss << src_tp[0] << ") -> " << dst_tp;
throw type_error(ss.str());
}
PyObject *dst_obj = *reinterpret_cast<PyObject *const *>(dst_arrmeta);
uintptr_t dst_alignment = reinterpret_cast<const uintptr_t *>(dst_arrmeta)[1];
PyArray_Descr *dtype = reinterpret_cast<PyArray_Descr *>(dst_obj);
if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_HASOBJECT)) {
// If there is no object type in the numpy type, get the dynd equivalent
// type and use it to do the copying
ndt::type dst_view_tp = ndt_type_from_numpy_dtype(dtype, dst_alignment);
return make_assignment_kernel(NULL, NULL, ckb, ckb_offset, dst_view_tp,
NULL, src_tp[0], src_arrmeta[0], kernreq,
ectx, dynd::nd::array());
} else if (PyDataType_ISOBJECT(dtype)) {
const arrfunc_type_data *af =
static_cast<dynd::nd::arrfunc>(nd::copy_to_pyobject).get();
return af->instantiate(
af, static_cast<dynd::nd::arrfunc>(nd::copy_to_pyobject).get_type(),
NULL, ckb, ckb_offset, ndt::make_type<void>(), NULL, nsrc, src_tp,
src_arrmeta, kernreq, ectx, dynd::nd::array(), tp_vars);
} else if (PyDataType_HASFIELDS(dtype)) {
if (src_tp[0].get_kind() != struct_kind &&
src_tp[0].get_kind() != tuple_kind) {
stringstream ss;
pyobject_ownref dtype_str(PyObject_Str((PyObject *)dtype));
ss << "Cannot assign from source dynd type " << src_tp[0]
<< " to numpy type " << pystring_as_string(dtype_str.get());
throw invalid_argument(ss.str());
}
// Get the fields out of the numpy dtype
vector<PyArray_Descr *> field_dtypes_orig;
vector<string> field_names_orig;
vector<size_t> field_offsets_orig;
extract_fields_from_numpy_struct(dtype, field_dtypes_orig, field_names_orig,
field_offsets_orig);
intptr_t field_count = field_dtypes_orig.size();
if (field_count !=
src_tp[0].extended<ndt::base_tuple_type>()->get_field_count()) {
stringstream ss;
pyobject_ownref dtype_str(PyObject_Str((PyObject *)dtype));
ss << "Cannot assign from source dynd type " << src_tp[0]
<< " to numpy type " << pystring_as_string(dtype_str.get());
throw invalid_argument(ss.str());
}
// Permute the numpy fields to match with the dynd fields
vector<PyArray_Descr *> field_dtypes;
vector<size_t> field_offsets;
if (src_tp[0].get_kind() == struct_kind) {
field_dtypes.resize(field_count);
field_offsets.resize(field_count);
for (intptr_t i = 0; i < field_count; ++i) {
intptr_t src_i =
src_tp[0].extended<ndt::base_struct_type>()->get_field_index(
field_names_orig[i]);
if (src_i >= 0) {
field_dtypes[src_i] = field_dtypes_orig[i];
field_offsets[src_i] = field_offsets_orig[i];
} else {
stringstream ss;
pyobject_ownref dtype_str(PyObject_Str((PyObject *)dtype));
ss << "Cannot assign from source dynd type " << src_tp[0]
<< " to numpy type " << pystring_as_string(dtype_str.get());
throw invalid_argument(ss.str());
}
}
} else {
// In the tuple case, use position instead of name
field_dtypes.swap(field_dtypes_orig);
field_offsets.swap(field_offsets_orig);
}
vector<ndt::type> dst_fields_tp(field_count, ndt::make_type<void>());
vector<copy_to_numpy_arrmeta> dst_arrmeta_values(field_count);
vector<const char *> dst_fields_arrmeta(field_count);
for (intptr_t i = 0; i < field_count; ++i) {
dst_arrmeta_values[i].dst_dtype = field_dtypes[i];
dst_arrmeta_values[i].dst_alignment = dst_alignment | field_offsets[i];
dst_fields_arrmeta[i] =
reinterpret_cast<const char *>(&dst_arrmeta_values[i]);
}
const uintptr_t *src_arrmeta_offsets =
src_tp[0].extended<ndt::base_tuple_type>()->get_arrmeta_offsets_raw();
shortvector<const char *> src_fields_arrmeta(field_count);
for (intptr_t i = 0; i != field_count; ++i) {
src_fields_arrmeta[i] = src_arrmeta[0] + src_arrmeta_offsets[i];
}
return make_tuple_unary_op_ckernel(
self_af, af_tp, ckb, ckb_offset, field_count, &field_offsets[0],
&dst_fields_tp[0], &dst_fields_arrmeta[0],
src_tp[0].extended<ndt::base_tuple_type>()->get_data_offsets(src_arrmeta[0]),
src_tp[0].extended<ndt::base_tuple_type>()->get_field_types_raw(),
src_fields_arrmeta.get(), kernreq, ectx);
} else {
stringstream ss;
ss << "TODO: implement assign from source dynd type " << src_tp[0]
<< " to numpy type " << pyobject_repr((PyObject *)dtype);
throw invalid_argument(ss.str());
}
}
dynd::nd::arrfunc pydynd::copy_to_numpy::make()
{
return dynd::nd::functional::elwise(
dynd::nd::arrfunc::make<copy_to_numpy_ck>(ndt::type("(Any) -> void"), 0));
}
struct pydynd::copy_to_numpy pydynd::copy_to_numpy;
void pydynd::array_copy_to_numpy(PyArrayObject *dst_arr,
const dynd::ndt::type &src_tp,
const char *src_arrmeta, const char *src_data,
const dynd::eval::eval_context *ectx)
{
intptr_t dst_ndim = PyArray_NDIM(dst_arr);
intptr_t src_ndim = src_tp.get_ndim();
uintptr_t dst_alignment = reinterpret_cast<uintptr_t>(PyArray_DATA(dst_arr));
strided_of_numpy_arrmeta dst_am_holder;
const char *dst_am = reinterpret_cast<const char *>(
&dst_am_holder.sdt[NPY_MAXDIMS - dst_ndim]);
// Fill in metadata for a multi-dim strided array, corresponding
// to the numpy array, with a void type at the end for the numpy
// specific data.
for (intptr_t i = 0; i < dst_ndim; ++i) {
fixed_dim_type_arrmeta &am = dst_am_holder.sdt[NPY_MAXDIMS - dst_ndim + i];
am.stride = PyArray_STRIDE(dst_arr, (int)i);
dst_alignment |= static_cast<uintptr_t>(am.stride);
am.dim_size = PyArray_DIM(dst_arr, (int)i);
}
ndt::type dst_tp =
ndt::make_type(dst_ndim, PyArray_SHAPE(dst_arr), ndt::make_type<void>());
dst_am_holder.am.dst_dtype = PyArray_DTYPE(dst_arr);
dst_am_holder.am.dst_alignment = dst_alignment;
// TODO: This is a hack, need a proper way to pass this dst param
intptr_t tmp_dst_arrmeta_size =
dst_ndim * sizeof(fixed_dim_type_arrmeta) + sizeof(copy_to_numpy_arrmeta);
nd::array tmp_dst(dynd::make_array_memory_block(tmp_dst_arrmeta_size));
tmp_dst.get_ndo()->m_type = ndt::type(dst_tp).release();
tmp_dst.get_ndo()->m_flags = nd::read_access_flag | nd::write_access_flag;
if (dst_tp.get_arrmeta_size() > 0) {
memcpy(tmp_dst.get_arrmeta(), dst_am, tmp_dst_arrmeta_size);
}
tmp_dst.get_ndo()->m_data_pointer = (char *)PyArray_DATA(dst_arr);
char *src_data_nonconst = const_cast<char *>(src_data);
copy_to_numpy(1, &src_tp, &src_arrmeta, &src_data_nonconst,
kwds("dst", tmp_dst));
}
#endif // DYND_NUMPY_INTEROP
<commit_msg>Update copy_to_numpy_arrfunc.cpp<commit_after>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#include "numpy_interop.hpp"
#if DYND_NUMPY_INTEROP
#include <numpy/arrayobject.h>
#include <numpy/arrayscalars.h>
#include <dynd/kernels/assignment_kernels.hpp>
#include <dynd/func/elwise.hpp>
#include <dynd/kernels/tuple_assignment_kernels.hpp>
#include <dynd/types/base_struct_type.hpp>
#include <dynd/memblock/array_memory_block.hpp>
#include "copy_to_numpy_arrfunc.hpp"
#include "copy_to_pyobject_arrfunc.hpp"
#include "utility_functions.hpp"
using namespace std;
using namespace dynd;
using namespace pydynd;
namespace {
struct strided_of_numpy_arrmeta {
fixed_dim_type_arrmeta sdt[NPY_MAXDIMS];
copy_to_numpy_arrmeta am;
};
} // anonymous namespace
/**
* This sets up a ckernel to copy from a dynd array
* to a numpy array. The destination numpy array is
* represented by dst_tp being ``void`` and the dst_arrmeta
* being a pointer to the ``PyArray_Descr *`` of the type for the destination.
*/
intptr_t copy_to_numpy_ck::instantiate(
const arrfunc_type_data *self_af, const dynd::ndt::arrfunc_type *af_tp,
char *DYND_UNUSED(data), void *ckb, intptr_t ckb_offset,
const dynd::ndt::type &dst_tp, const char *dst_arrmeta, intptr_t nsrc,
const dynd::ndt::type *src_tp, const char *const *src_arrmeta,
kernel_request_t kernreq, const eval::eval_context *ectx,
const dynd::nd::array &kwds, const std::map<dynd::nd::string, dynd::ndt::type> &tp_vars)
{
if (dst_tp.get_type_id() != void_type_id) {
stringstream ss;
ss << "Cannot instantiate arrfunc with signature ";
ss << af_tp << " with types (";
ss << src_tp[0] << ") -> " << dst_tp;
throw type_error(ss.str());
}
PyObject *dst_obj = *reinterpret_cast<PyObject *const *>(dst_arrmeta);
uintptr_t dst_alignment = reinterpret_cast<const uintptr_t *>(dst_arrmeta)[1];
PyArray_Descr *dtype = reinterpret_cast<PyArray_Descr *>(dst_obj);
if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_HASOBJECT)) {
// If there is no object type in the numpy type, get the dynd equivalent
// type and use it to do the copying
ndt::type dst_view_tp = ndt_type_from_numpy_dtype(dtype, dst_alignment);
return make_assignment_kernel(NULL, NULL, ckb, ckb_offset, dst_view_tp,
NULL, src_tp[0], src_arrmeta[0], kernreq,
ectx, dynd::nd::array());
} else if (PyDataType_ISOBJECT(dtype)) {
const arrfunc_type_data *af =
static_cast<dynd::nd::arrfunc>(nd::copy_to_pyobject).get();
return af->instantiate(
af, static_cast<dynd::nd::arrfunc>(nd::copy_to_pyobject).get_type(),
NULL, ckb, ckb_offset, ndt::make_type<void>(), NULL, nsrc, src_tp,
src_arrmeta, kernreq, ectx, dynd::nd::array(), tp_vars);
} else if (PyDataType_HASFIELDS(dtype)) {
if (src_tp[0].get_kind() != struct_kind &&
src_tp[0].get_kind() != tuple_kind) {
stringstream ss;
pyobject_ownref dtype_str(PyObject_Str((PyObject *)dtype));
ss << "Cannot assign from source dynd type " << src_tp[0]
<< " to numpy type " << pystring_as_string(dtype_str.get());
throw invalid_argument(ss.str());
}
// Get the fields out of the numpy dtype
vector<PyArray_Descr *> field_dtypes_orig;
vector<string> field_names_orig;
vector<size_t> field_offsets_orig;
extract_fields_from_numpy_struct(dtype, field_dtypes_orig, field_names_orig,
field_offsets_orig);
intptr_t field_count = field_dtypes_orig.size();
if (field_count !=
src_tp[0].extended<ndt::base_tuple_type>()->get_field_count()) {
stringstream ss;
pyobject_ownref dtype_str(PyObject_Str((PyObject *)dtype));
ss << "Cannot assign from source dynd type " << src_tp[0]
<< " to numpy type " << pystring_as_string(dtype_str.get());
throw invalid_argument(ss.str());
}
// Permute the numpy fields to match with the dynd fields
vector<PyArray_Descr *> field_dtypes;
vector<size_t> field_offsets;
if (src_tp[0].get_kind() == struct_kind) {
field_dtypes.resize(field_count);
field_offsets.resize(field_count);
for (intptr_t i = 0; i < field_count; ++i) {
intptr_t src_i =
src_tp[0].extended<ndt::base_struct_type>()->get_field_index(
field_names_orig[i]);
if (src_i >= 0) {
field_dtypes[src_i] = field_dtypes_orig[i];
field_offsets[src_i] = field_offsets_orig[i];
} else {
stringstream ss;
pyobject_ownref dtype_str(PyObject_Str((PyObject *)dtype));
ss << "Cannot assign from source dynd type " << src_tp[0]
<< " to numpy type " << pystring_as_string(dtype_str.get());
throw invalid_argument(ss.str());
}
}
} else {
// In the tuple case, use position instead of name
field_dtypes.swap(field_dtypes_orig);
field_offsets.swap(field_offsets_orig);
}
vector<ndt::type> dst_fields_tp(field_count, ndt::make_type<void>());
vector<copy_to_numpy_arrmeta> dst_arrmeta_values(field_count);
vector<const char *> dst_fields_arrmeta(field_count);
for (intptr_t i = 0; i < field_count; ++i) {
dst_arrmeta_values[i].dst_dtype = field_dtypes[i];
dst_arrmeta_values[i].dst_alignment = dst_alignment | field_offsets[i];
dst_fields_arrmeta[i] =
reinterpret_cast<const char *>(&dst_arrmeta_values[i]);
}
const uintptr_t *src_arrmeta_offsets =
src_tp[0].extended<ndt::base_tuple_type>()->get_arrmeta_offsets_raw();
shortvector<const char *> src_fields_arrmeta(field_count);
for (intptr_t i = 0; i != field_count; ++i) {
src_fields_arrmeta[i] = src_arrmeta[0] + src_arrmeta_offsets[i];
}
return make_tuple_unary_op_ckernel(
self_af, af_tp, ckb, ckb_offset, field_count, &field_offsets[0],
&dst_fields_tp[0], &dst_fields_arrmeta[0],
src_tp[0].extended<ndt::base_tuple_type>()->get_data_offsets(src_arrmeta[0]),
src_tp[0].extended<ndt::base_tuple_type>()->get_field_types_raw(),
src_fields_arrmeta.get(), kernreq, ectx);
} else {
stringstream ss;
ss << "TODO: implement assign from source dynd type " << src_tp[0]
<< " to numpy type " << pyobject_repr((PyObject *)dtype);
throw invalid_argument(ss.str());
}
}
dynd::nd::arrfunc pydynd::copy_to_numpy::make()
{
return dynd::nd::functional::elwise(
dynd::nd::arrfunc::make<copy_to_numpy_ck>(ndt::type("(Any) -> void"), 0));
}
struct pydynd::copy_to_numpy pydynd::copy_to_numpy;
void pydynd::array_copy_to_numpy(PyArrayObject *dst_arr,
const dynd::ndt::type &src_tp,
const char *src_arrmeta, const char *src_data,
const dynd::eval::eval_context *ectx)
{
intptr_t dst_ndim = PyArray_NDIM(dst_arr);
intptr_t src_ndim = src_tp.get_ndim();
uintptr_t dst_alignment = reinterpret_cast<uintptr_t>(PyArray_DATA(dst_arr));
strided_of_numpy_arrmeta dst_am_holder;
const char *dst_am = reinterpret_cast<const char *>(
&dst_am_holder.sdt[NPY_MAXDIMS - dst_ndim]);
// Fill in metadata for a multi-dim strided array, corresponding
// to the numpy array, with a void type at the end for the numpy
// specific data.
for (intptr_t i = 0; i < dst_ndim; ++i) {
fixed_dim_type_arrmeta &am = dst_am_holder.sdt[NPY_MAXDIMS - dst_ndim + i];
am.stride = PyArray_STRIDE(dst_arr, (int)i);
dst_alignment |= static_cast<uintptr_t>(am.stride);
am.dim_size = PyArray_DIM(dst_arr, (int)i);
}
ndt::type dst_tp =
ndt::make_type(dst_ndim, PyArray_SHAPE(dst_arr), ndt::make_type<void>());
dst_am_holder.am.dst_dtype = PyArray_DTYPE(dst_arr);
dst_am_holder.am.dst_alignment = dst_alignment;
// TODO: This is a hack, need a proper way to pass this dst param
intptr_t tmp_dst_arrmeta_size =
dst_ndim * sizeof(fixed_dim_type_arrmeta) + sizeof(copy_to_numpy_arrmeta);
nd::array tmp_dst(dynd::make_array_memory_block(tmp_dst_arrmeta_size));
tmp_dst.get_ndo()->m_type = ndt::type(dst_tp).release();
tmp_dst.get_ndo()->m_flags = nd::read_access_flag | nd::write_access_flag;
if (dst_tp.get_arrmeta_size() > 0) {
memcpy(tmp_dst.get_arrmeta(), dst_am, tmp_dst_arrmeta_size);
}
tmp_dst.get_ndo()->m_data_pointer = (char *)PyArray_DATA(dst_arr);
char *src_data_nonconst = const_cast<char *>(src_data);
copy_to_numpy(1, &src_tp, &src_arrmeta, &src_data_nonconst,
kwds("dst", tmp_dst));
}
#endif // DYND_NUMPY_INTEROP
<|endoftext|> |
<commit_before>/* BSD 2-Clause License
Copyright (c) 2016, Doi Yusuke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstring> // for memset
#include <sstream> // for error massage
#include <stdexcept>
#include <unordered_map> // for cashe
#include <fcntl.h> // for open FLAGS
#include <unistd.h> // for tty checks
#include "core.hpp"
template<typename T, typename... Args>
inline std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
ics::Core::Core(const std::string& path, speed_t baudrate)
: fd {open(path.c_str(), O_RDWR | O_NOCTTY)},
oldTio {}
{
if (fd < 0)
throw std::runtime_error {"Cannot open deveice"};
try {
if (!isatty(fd))
throw std::invalid_argument {"Not tty device"};
if (tcgetattr(fd, &oldTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
auto newTio = getTermios(); // forward reference
if (cfsetispeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (cfsetospeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (tcsetattr(fd, TCSANOW, &newTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
} catch (...) {
close(fd);
throw;
}
}
ics::Core::~Core() noexcept
{
if (fd < 0) return;
closeThis();
}
ics::Core::Core(Core&& rhs) noexcept
: fd {rhs.fd},
oldTio(rhs.oldTio) // for Ubuntu14.04 compiler
{
rhs.fd = -1;
}
ics::Core& ics::Core::operator=(Core&& rhs) noexcept
{
if (fd != rhs.fd) {
closeThis();
fd = rhs.fd;
oldTio = rhs.oldTio;
rhs.fd = -1;
}
return *this;
}
std::unique_ptr<ics::Core> ics::Core::getCore(const std::string& path, speed_t baudrate)
{
return make_unique<Core>(path, baudrate);
}
void ics::Core::communicate(const Container& tx, Container& rx)
{
write(fd, tx.data(), tx.size()); // send
for (auto& receive : rx) read(fd, &receive, 1); // receive
// check section
auto receive = rx.cbegin();
for (const auto& send : tx) {
if (send != *receive) {
std::stringstream ss;
ss << "Receive falied(loopback):" << receive - rx.cbegin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive);
throw std::runtime_error {ss.str()};
}
++receive;
}
}
void ics::Core::communicateID(const IDContainerTx& tx, IDContainerRx& rx)
{
write(fd, tx.data(), tx.size()); // send
for (auto& receive : rx) read(fd, &receive, 1); // receive
// check section
auto receive = rx.cbegin();
for (const auto& send : tx) {
if (send != *receive) {
std::stringstream ss;
ss << "Receive falied(loopback):" << receive - rx.cbegin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive);
throw std::runtime_error {ss.str()};
}
++receive;
}
if ((tx[0] & 0xE0) != (*receive & 0xE0)) throw std::runtime_error {"Receive failed: invalid target data"};
}
void ics::Core::closeThis() const noexcept
{
tcsetattr(fd, TCSANOW, &oldTio);
close(fd);
}
termios ics::Core::getTermios() noexcept
{
termios newTio;
std::memset(&newTio, 0, sizeof(newTio));
newTio.c_iflag = 0;
newTio.c_oflag = 0;
newTio.c_cflag = CS8 | CREAD | CLOCAL | PARENB;
newTio.c_lflag = 0;
newTio.c_cc[VMIN] = 1;
newTio.c_cc[VTIME] = 1;
return newTio;
}
<commit_msg>Reformat constructor of Core<commit_after>/* BSD 2-Clause License
Copyright (c) 2016, Doi Yusuke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstring> // for memset
#include <sstream> // for error massage
#include <stdexcept>
#include <unordered_map> // for cashe
#include <fcntl.h> // for open FLAGS
#include <unistd.h> // for tty checks
#include "core.hpp"
template<typename T, typename... Args>
inline std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
ics::Core::Core(const std::string& path, speed_t baudrate)
: fd {open(path.c_str(), O_RDWR | O_NOCTTY)},
oldTio {}
{
if (fd < 0)
throw std::runtime_error {"Cannot open deveice"};
try {
if (!isatty(fd))
throw std::invalid_argument {"Not tty device"};
if (tcgetattr(fd, &oldTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
auto newTio = getTermios(); // forward reference
if (cfsetispeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (cfsetospeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (tcsetattr(fd, TCSANOW, &newTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
} catch (...) {
close(fd);
throw;
}
}
ics::Core::~Core() noexcept
{
if (fd < 0) return;
closeThis();
}
ics::Core::Core(Core&& rhs) noexcept
: fd {rhs.fd},
oldTio(rhs.oldTio) // for Ubuntu14.04 compiler
{
rhs.fd = -1;
}
ics::Core& ics::Core::operator=(Core&& rhs) noexcept
{
if (fd != rhs.fd) {
closeThis();
fd = rhs.fd;
oldTio = rhs.oldTio;
rhs.fd = -1;
}
return *this;
}
std::unique_ptr<ics::Core> ics::Core::getCore(const std::string& path, speed_t baudrate)
{
return make_unique<Core>(path, baudrate);
}
void ics::Core::communicate(const Container& tx, Container& rx)
{
write(fd, tx.data(), tx.size()); // send
for (auto& receive : rx) read(fd, &receive, 1); // receive
// check section
auto receive = rx.cbegin();
for (const auto& send : tx) {
if (send != *receive) {
std::stringstream ss;
ss << "Receive falied(loopback):" << receive - rx.cbegin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive);
throw std::runtime_error {ss.str()};
}
++receive;
}
}
void ics::Core::communicateID(const IDContainerTx& tx, IDContainerRx& rx)
{
write(fd, tx.data(), tx.size()); // send
for (auto& receive : rx) read(fd, &receive, 1); // receive
// check section
auto receive = rx.cbegin();
for (const auto& send : tx) {
if (send != *receive) {
std::stringstream ss;
ss << "Receive falied(loopback):" << receive - rx.cbegin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive);
throw std::runtime_error {ss.str()};
}
++receive;
}
if ((tx[0] & 0xE0) != (*receive & 0xE0)) throw std::runtime_error {"Receive failed: invalid target data"};
}
void ics::Core::closeThis() const noexcept
{
tcsetattr(fd, TCSANOW, &oldTio);
close(fd);
}
termios ics::Core::getTermios() noexcept
{
termios newTio;
std::memset(&newTio, 0, sizeof(newTio));
newTio.c_iflag = 0;
newTio.c_oflag = 0;
newTio.c_cflag = CS8 | CREAD | CLOCAL | PARENB;
newTio.c_lflag = 0;
newTio.c_cc[VMIN] = 1;
newTio.c_cc[VTIME] = 1;
return newTio;
}
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_FUNCTION_CONSTANT_HH
#define DUNE_STUFF_FUNCTION_CONSTANT_HH
#include <dune/stuff/common/parameter/tree.hh>
#include "interfaces.hh"
namespace Dune {
namespace Stuff {
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimCols, int rangeDimRows >
class FunctionConstantBase
: public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimCols, rangeDimRows >
, public TimedependentFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimCols, rangeDimRows >
{
typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimCols, rangeDimRows > BaseType;
public:
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRangeCols = BaseType::dimRangeCols;
static const unsigned int dimRangeRows = BaseType::dimRangeRows;
typedef typename BaseType::RangeType RangeType;
FunctionConstantBase(const RangeFieldType& constant)
: constant_(constant)
{}
FunctionConstantBase(const RangeType& constant)
: constant_(constant)
{}
static std::string static_id()
{
return BaseType::static_id() + ".constant";
}
virtual int order() const
{
return 0;
}
virtual std::string name() const
{
return static_id();
}
virtual void evaluate(const DomainType& /*arg*/, RangeType& ret) const
{
ret = constant_;
}
virtual void evaluate(const DomainType& /*arg*/, const double& /*t*/, RangeType& ret) const
{
ret = constant_;
}
private:
const RangeType constant_;
}; // class FunctionConstantBase
// forward, to allow for specialization
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols = 1 >
class FunctionConstant
{
public:
FunctionConstant() = delete;
}; // class FunctionConstant
template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class FunctionConstant< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
: public FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
{
typedef FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > BaseType;
public:
typedef FunctionConstant< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > ThisType;
typedef typename BaseType::RangeFieldType RangeFieldType;
typedef typename BaseType::RangeType RangeType;
FunctionConstant(const RangeFieldType& constant)
: BaseType(constant)
{}
FunctionConstant(const RangeType& constant)
: BaseType(constant)
{}
using BaseType::static_id;
static Dune::ParameterTree defaultSettings(const std::string subName = "")
{
Dune::ParameterTree description;
description["value"] = "1.0";
if (subName.empty())
return description;
else {
Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
extendedDescription.add(description, subName);
return extendedDescription;
}
} // ... defaultSettings(...)
static ThisType* create(const DSC::ExtendedParameterTree settings = defaultSettings())
{
return new ThisType(settings.get< RangeFieldType >("value", RangeFieldType(0)));
} // ... create(...)
}; // class FunctionConstant< ..., 1 >
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_FUNCTION_CONSTANT_HH
<commit_msg>[dune.stuff.functions] adjusted FunctionConstant for matrixvalued functions, corrected order of rangeDimRows and rangeDimCols<commit_after>#ifndef DUNE_STUFF_FUNCTION_CONSTANT_HH
#define DUNE_STUFF_FUNCTION_CONSTANT_HH
#include <dune/stuff/common/parameter/tree.hh>
#include "interfaces.hh"
namespace Dune {
namespace Stuff {
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class FunctionConstantBase
: public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols >
, public TimedependentFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols >
{
typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols > BaseType;
public:
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRangeCols = BaseType::dimRangeCols;
static const unsigned int dimRangeRows = BaseType::dimRangeRows;
typedef typename BaseType::RangeType RangeType;
FunctionConstantBase(const RangeFieldType& constant)
: constant_(constant)
{}
FunctionConstantBase(const RangeType& constant)
: constant_(constant)
{}
static std::string static_id()
{
return BaseType::static_id() + ".constant";
}
virtual int order() const
{
return 0;
}
virtual std::string name() const
{
return static_id();
}
virtual void evaluate(const DomainType& /*arg*/, RangeType& ret) const
{
ret = constant_;
}
virtual void evaluate(const DomainType& /*arg*/, const double& /*t*/, RangeType& ret) const
{
ret = constant_;
}
using BaseType::localFunction;
private:
const RangeType constant_;
}; // class FunctionConstantBase
// forward, to allow for specialization
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols = 1 >
class FunctionConstant
: public FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols >
{
typedef FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols > BaseType;
public:
typedef FunctionConstant< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols > ThisType;
typedef typename BaseType::RangeFieldType RangeFieldType;
typedef typename BaseType::RangeType RangeType;
FunctionConstant(const RangeFieldType& constant)
: BaseType(constant)
{}
FunctionConstant(const RangeType& constant)
: BaseType(constant)
{}
using BaseType::localFunction;
}; // class FunctionConstant
template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class FunctionConstant< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
: public FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >
{
typedef FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > BaseType;
public:
typedef FunctionConstant< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > ThisType;
typedef typename BaseType::RangeFieldType RangeFieldType;
typedef typename BaseType::RangeType RangeType;
FunctionConstant(const RangeFieldType& constant)
: BaseType(constant)
{}
FunctionConstant(const RangeType& constant)
: BaseType(constant)
{}
using BaseType::static_id;
static Dune::ParameterTree defaultSettings(const std::string subName = "")
{
Dune::ParameterTree description;
description["value"] = "1.0";
if (subName.empty())
return description;
else {
Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
extendedDescription.add(description, subName);
return extendedDescription;
}
} // ... defaultSettings(...)
static ThisType* create(const DSC::ExtendedParameterTree settings = defaultSettings())
{
return new ThisType(settings.get< RangeFieldType >("value", RangeFieldType(0)));
} // ... create(...)
}; // class FunctionConstant< ..., 1 >
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_FUNCTION_CONSTANT_HH
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH
#define DUNE_STUFF_GRID_PROVIDER_CUBE_HH
// system
#include <sstream>
#include <type_traits>
#include <boost/assign/list_of.hpp>
// dune-common
#include <dune/common/parametertree.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>
// dune-grid
#include <dune/grid/utility/structuredgridfactory.hh>
#include <dune/grid/yaspgrid.hh>
#include <dune/grid/alugrid.hh>
#include <dune/grid/sgrid.hh>
#include <dune/grid/common/mcmgmapper.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>
namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {
/**
* \brief Creates a grid of a cube in various dimensions.
*
* Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3
* dimensions. Tested with
* <ul><li> \c YASPGRID, \c variant 1, dim = 1, 2, 3,
* <li> \c SGRID, \c variant 1, dim = 1, 2, 3,
* <li> \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3,
* <li> \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and
* <li> \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.</ul>
* \tparam GridImp
* Type of the underlying grid.
* \tparam variant
* Type of the codim 0 elements:
* <ul><li>\c 1: cubes
* <li>2: simplices</ul>
**/
template< typename GridImp, int variant >
class GenericCube
{
public:
//! Type of the provided grid.
typedef GridImp GridType;
//! Dimension of the provided grid.
static const unsigned int dim = GridType::dimension;
//! Type of the grids coordinates.
typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType;
//! Unique identifier: \c stuff.grid.provider.cube
static const std::string id;
/**
* \brief Creates a cube.
* \param[in] paramTree
* A Dune::ParameterTree containing
* <ul><li> the following keys directly or
* <li> a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.</ul>
* The actual keys are:
* <ul><li> \c lowerLeft: \a double that is used as a lower left corner in each dimension.
* <li> \c upperRight: \a double that is used as an upper right corner in each dimension.
* <li> \c numElements.D \a int to denote the number of elements in direction of dimension D (has to be given for each dimension seperately).
* <li> \c level: \a int level of refinement. If given, overrides numElements and creates \f$ 2^level \f$ elements per dimension.
* </ul>
**/
GenericCube(const Dune::ParameterTree paramTree)
: lowerLeft_(0.0),
upperRight_(1.0)
{
// select subtree (if necessary)
Dune::ParameterTree paramTree_ = paramTree;
if (paramTree.hasSub(id))
paramTree_ = paramTree.sub(id);
// get outer bounds
const double lowerLeft = paramTree_.get("lowerLeft", 0.0);
const double upperRight = paramTree_.get("upperRight", 1.0);
assert(lowerLeft < upperRight);
lowerLeft_ = lowerLeft;
upperRight_ = upperRight;
// get number of elements per dim
if (paramTree.hasKey("level"))
std::fill(std::begin(numElements_), std::end(numElements_), std::pow(2, paramTree.get("level", 1)));
else {
for (unsigned int d = 0; d < dim; ++d) {
std::stringstream s;
s << "numElements." << d;
numElements_[d] = paramTree.get(s.str(), 1);
}
}
buildGrid();
} // Cube(const Dune::ParameterTree& paramTree)
/**
* \brief Creates a cube.
* \param[in] lowerLeft
* A vector that is used as a lower left corner.
* \param[in] upperRight
* A vector that is used as a upper right corner.
* \param[in] level (optional)
* Level of refinement (see constructor for details).
**/
GenericCube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1)
: lowerLeft_(lowerLeft),
upperRight_(upperRight)
{
std::fill(numElements_.begin(), numElements_.end(), std::pow(2, level));
buildGrid();
}
/**
* \brief Creates a cube.
* \param[in] lowerLeft
* A double that is used as a lower left corner in each dimension.
* \param[in] upperRight
* A double that is used as a upper right corner in each dimension.
* \param[in] level (optional)
* Level of refinement (see constructor for details).
**/
GenericCube(const double lowerLeft, const double upperRight, const int level = 1)
: lowerLeft_(lowerLeft),
upperRight_(upperRight)
{
std::fill(std::begin(numElements_), std::end(numElements_), std::pow(2, level));
buildGrid();
}
/**
\brief Creates a cube. This signature allows to prescribe anisotopic refinement
\param[in] lowerLeft
A double that is used as a lower left corner in each dimension.
\param[in] upperRight
A double that is used as a upper right corner in each dimension.
\param[in] elements_per_dim number of elements in each dimension.
can contain 0 to dim elements (missing dimension are initialized to 1)
\tparam Coord anything that CoordinateType allows to copy construct from
\tparam ContainerType some sequence type that functions with std::begin/end
\tparam T an unsigned integral Type
**/
template < class Coord, class ContainerType >
GenericCube(const Coord lowerLeft, const Coord upperRight,
const ContainerType elements_per_dim = boost::assign::list_of<typename ContainerType::value_type>().repeat(GridType::dimensionworld,typename ContainerType::value_type(1)) )
: lowerLeft_(lowerLeft),
upperRight_(upperRight)
{
static_assert(std::is_unsigned<typename ContainerType::value_type>::value
&& std::is_integral<typename ContainerType::value_type>::value,
"only unsigned integral number of elements per dimension allowed");
//base init in case input is shorter
std::fill(std::begin(numElements_), std::end(numElements_), 1);
std::copy(std::begin(elements_per_dim), std::end(elements_per_dim), std::begin(numElements_));
buildGrid();
}
/**
\brief Provides access to the created grid.
\return Reference to the grid.
**/
GridType& grid()
{
return *grid_;
}
/**
* \brief Provides const access to the created grid.
* \return Reference to the grid.
**/
const GridType& grid() const
{
return *grid_;
}
const CoordinateType& lowerLeft() const
{
return lowerLeft_;
}
const CoordinateType& upperRight() const
{
return upperRight_;
}
private:
template< int dim >
struct P0Layout
{
bool DUNE_DEPRECATED_MSG("geometries should be passed by value") contains(Dune::GeometryType& geometry)
{
return geometry.dim() == dim;
}
bool contains(const Dune::GeometryType geometry)
{
return geometry.dim() == dim;
}
}; // layout class for codim 0 mapper
public:
/**
* \brief Visualizes the grid using Dune::VTKWriter.
* \param[in] filename
**/
void visualize(const std::string filename = id + ".grid") const
{
// grid view
typedef typename GridType::LeafGridView GridView;
GridView gridView = grid().leafView();
// mapper
Dune::LeafMultipleCodimMultipleGeomTypeMapper< GridType, P0Layout > mapper(grid());
std::vector< double > data(mapper.size());
// walk the grid
typedef typename GridView::template Codim<0>::Iterator ElementIterator;
typedef typename GridView::template Codim<0>::Entity ElementType;
typedef typename ElementType::LeafIntersectionIterator FacetIteratorType;
for (ElementIterator it = gridView.template begin<0>(); it != gridView.template end<0>(); ++it) {
ElementType& element = *it;
data[mapper.map(element)] = 0.0;
int numberOfBoundarySegments = 0;
bool isOnBoundary = false;
// walk the intersections
for (FacetIteratorType facet = element.ileafbegin();
facet != element.ileafend();
++facet) {
if (!facet->neighbor() && facet->boundary()){
isOnBoundary = true;
numberOfBoundarySegments += 1;
data[mapper.map(element)] += double(facet->boundaryId());
}
} // walk the intersections
if (isOnBoundary) {
data[mapper.map(element)] /= double(numberOfBoundarySegments);
}
} // walk the grid
// write to vtk
Dune::VTKWriter< GridView > vtkwriter(gridView);
vtkwriter.addCellData(data, "boundaryId");
vtkwriter.write(filename, Dune::VTK::ascii);
} // void visualize(const std::string filename = id + ".grid") const
private:
void buildGrid()
{
switch (variant) {
case 1:
grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements_);
break;
case 2:
grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements_);
break;
default:
DUNE_THROW(Dune::NotImplemented, "Variant " << variant << " not valid (only 1 and 2 are).");
}
return;
} // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight)
CoordinateType lowerLeft_;
CoordinateType upperRight_;
Dune::array< unsigned int, dim > numElements_;
Dune::shared_ptr< GridType > grid_;
}; // class GenericCube
template< typename GridImp, int variant >
const std::string GenericCube< GridImp, variant >::id = "stuff.grid.provider.cube";
template< typename GridType >
struct ElementVariant {
static const int id = 2;
};
template< int dim >
struct ElementVariant< Dune::YaspGrid< dim > > {
static const int id = 1;
};
template< int dim >
struct ElementVariant< Dune::SGrid< dim, dim > > {
static const int id = 1;
};
#ifdef HAVE_ALUGRID
template< int dim >
struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > {
static const int id = 1;
};
#endif
// default implementation of a cube for any grid
// tested for
// dim = 2
// ALUGRID_SIMPLEX, variant 2
// ALUGRID_CONFORM, variant 2
// dim = 3
// ALUGRID_SIMPLEX, variant 2
template< typename GridType >
class Cube
: public GenericCube< GridType, ElementVariant<GridType>::id >
{
private:
typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType;
public:
typedef typename BaseType::CoordinateType CoordinateType;
Cube(const Dune::ParameterTree& paramTree)
: BaseType(paramTree)
{}
Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1)
: BaseType(lowerLeft, upperRight, level)
{}
Cube(const double lowerLeft, const double upperRight, const int level = 1)
: BaseType(lowerLeft, upperRight, level)
{}
template < class Coord, class ContainerType >
Cube(const Coord lowerLeft, const Coord upperRight,
const ContainerType elements_per_dim = boost::assign::list_of<typename ContainerType::value_type>().repeat(GridType::dimensionworld,typename ContainerType::value_type(1)) )
: BaseType(lowerLeft, upperRight, elements_per_dim)
{}
}; // class Cube
template< typename GridType >
class UnitCube
: public Cube< GridType >
{
private:
typedef Cube< GridType > BaseType;
public:
UnitCube(const Dune::ParameterTree& paramTree)
: BaseType(0.0, 1.0, paramTree.get("level", 1))
{}
UnitCube(const int level = 1)
: BaseType(0.0, 1.0, level)
{}
}; // class UnitCube
} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH
<commit_msg>[grid.provider.cube] removed what does not work with gcc-4.4<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH
#define DUNE_STUFF_GRID_PROVIDER_CUBE_HH
// system
#include <sstream>
#include <type_traits>
#include <boost/assign/list_of.hpp>
// dune-common
#include <dune/common/parametertree.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>
// dune-grid
#include <dune/grid/utility/structuredgridfactory.hh>
#include <dune/grid/yaspgrid.hh>
#include <dune/grid/alugrid.hh>
#include <dune/grid/sgrid.hh>
#include <dune/grid/common/mcmgmapper.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>
namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {
/**
* \brief Creates a grid of a cube in various dimensions.
*
* Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3
* dimensions. Tested with
* <ul><li> \c YASPGRID, \c variant 1, dim = 1, 2, 3,
* <li> \c SGRID, \c variant 1, dim = 1, 2, 3,
* <li> \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3,
* <li> \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and
* <li> \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.</ul>
* \tparam GridImp
* Type of the underlying grid.
* \tparam variant
* Type of the codim 0 elements:
* <ul><li>\c 1: cubes
* <li>2: simplices</ul>
**/
template< typename GridImp, int variant >
class GenericCube
{
public:
//! Type of the provided grid.
typedef GridImp GridType;
//! Dimension of the provided grid.
static const unsigned int dim = GridType::dimension;
//! Type of the grids coordinates.
typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType;
//! Unique identifier: \c stuff.grid.provider.cube
static const std::string id;
/**
* \brief Creates a cube.
* \param[in] paramTree
* A Dune::ParameterTree containing
* <ul><li> the following keys directly or
* <li> a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.</ul>
* The actual keys are:
* <ul><li> \c lowerLeft: \a double that is used as a lower left corner in each dimension.
* <li> \c upperRight: \a double that is used as an upper right corner in each dimension.
* <li> \c numElements.D \a int to denote the number of elements in direction of dimension D (has to be given for each dimension seperately).
* <li> \c level: \a int level of refinement. If given, overrides numElements and creates \f$ 2^level \f$ elements per dimension.
* </ul>
**/
GenericCube(const Dune::ParameterTree paramTree)
: lowerLeft_(0.0),
upperRight_(1.0)
{
// select subtree (if necessary)
Dune::ParameterTree paramTree_ = paramTree;
if (paramTree.hasSub(id))
paramTree_ = paramTree.sub(id);
// get outer bounds
const double lowerLeft = paramTree_.get("lowerLeft", 0.0);
const double upperRight = paramTree_.get("upperRight", 1.0);
assert(lowerLeft < upperRight);
lowerLeft_ = lowerLeft;
upperRight_ = upperRight;
// get number of elements per dim
if (paramTree.hasKey("level"))
std::fill(numElements_.begin(), numElements_.end(), std::pow(2, paramTree.get("level", 1)));
else {
for (unsigned int d = 0; d < dim; ++d) {
std::stringstream s;
s << "numElements." << d;
numElements_[d] = paramTree.get(s.str(), 1);
}
}
buildGrid();
} // Cube(const Dune::ParameterTree& paramTree)
/**
* \brief Creates a cube.
* \param[in] lowerLeft
* A vector that is used as a lower left corner.
* \param[in] upperRight
* A vector that is used as a upper right corner.
* \param[in] level (optional)
* Level of refinement (see constructor for details).
**/
GenericCube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1)
: lowerLeft_(lowerLeft),
upperRight_(upperRight)
{
std::fill(numElements_.begin(), numElements_.end(), std::pow(2, level));
buildGrid();
}
/**
* \brief Creates a cube.
* \param[in] lowerLeft
* A double that is used as a lower left corner in each dimension.
* \param[in] upperRight
* A double that is used as a upper right corner in each dimension.
* \param[in] level (optional)
* Level of refinement (see constructor for details).
**/
GenericCube(const double lowerLeft, const double upperRight, const int level = 1)
: lowerLeft_(lowerLeft),
upperRight_(upperRight)
{
std::fill(numElements_.begin(), numElements_.end(), std::pow(2, level));
buildGrid();
}
/**
\brief Creates a cube. This signature allows to prescribe anisotopic refinement
\param[in] lowerLeft
A double that is used as a lower left corner in each dimension.
\param[in] upperRight
A double that is used as a upper right corner in each dimension.
\param[in] elements_per_dim number of elements in each dimension.
can contain 0 to dim elements (missing dimension are initialized to 1)
\tparam Coord anything that CoordinateType allows to copy construct from
\tparam ContainerType some sequence type that functions with std::begin/end
\tparam T an unsigned integral Type
**/
template < class Coord, class ContainerType >
GenericCube(const Coord lowerLeft, const Coord upperRight,
const ContainerType elements_per_dim = boost::assign::list_of<typename ContainerType::value_type>().repeat(GridType::dimensionworld,typename ContainerType::value_type(1)) )
: lowerLeft_(lowerLeft),
upperRight_(upperRight)
{
static_assert(std::is_unsigned<typename ContainerType::value_type>::value
&& std::is_integral<typename ContainerType::value_type>::value,
"only unsigned integral number of elements per dimension allowed");
//base init in case input is shorter
std::fill(numElements_.begin(), numElements_.end(), 1);
std::copy(elements_per_dim.begin(), elements_per_dim.end(), numElements_.begin());
buildGrid();
}
/**
\brief Provides access to the created grid.
\return Reference to the grid.
**/
GridType& grid()
{
return *grid_;
}
/**
* \brief Provides const access to the created grid.
* \return Reference to the grid.
**/
const GridType& grid() const
{
return *grid_;
}
const CoordinateType& lowerLeft() const
{
return lowerLeft_;
}
const CoordinateType& upperRight() const
{
return upperRight_;
}
private:
template< int dim >
struct P0Layout
{
bool DUNE_DEPRECATED_MSG("geometries should be passed by value") contains(Dune::GeometryType& geometry)
{
return geometry.dim() == dim;
}
bool contains(const Dune::GeometryType geometry)
{
return geometry.dim() == dim;
}
}; // layout class for codim 0 mapper
public:
/**
* \brief Visualizes the grid using Dune::VTKWriter.
* \param[in] filename
**/
void visualize(const std::string filename = id + ".grid") const
{
// grid view
typedef typename GridType::LeafGridView GridView;
GridView gridView = grid().leafView();
// mapper
Dune::LeafMultipleCodimMultipleGeomTypeMapper< GridType, P0Layout > mapper(grid());
std::vector< double > data(mapper.size());
// walk the grid
typedef typename GridView::template Codim<0>::Iterator ElementIterator;
typedef typename GridView::template Codim<0>::Entity ElementType;
typedef typename ElementType::LeafIntersectionIterator FacetIteratorType;
for (ElementIterator it = gridView.template begin<0>(); it != gridView.template end<0>(); ++it) {
ElementType& element = *it;
data[mapper.map(element)] = 0.0;
int numberOfBoundarySegments = 0;
bool isOnBoundary = false;
// walk the intersections
for (FacetIteratorType facet = element.ileafbegin();
facet != element.ileafend();
++facet) {
if (!facet->neighbor() && facet->boundary()){
isOnBoundary = true;
numberOfBoundarySegments += 1;
data[mapper.map(element)] += double(facet->boundaryId());
}
} // walk the intersections
if (isOnBoundary) {
data[mapper.map(element)] /= double(numberOfBoundarySegments);
}
} // walk the grid
// write to vtk
Dune::VTKWriter< GridView > vtkwriter(gridView);
vtkwriter.addCellData(data, "boundaryId");
vtkwriter.write(filename, Dune::VTK::ascii);
} // void visualize(const std::string filename = id + ".grid") const
private:
void buildGrid()
{
switch (variant) {
case 1:
grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements_);
break;
case 2:
grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements_);
break;
default:
DUNE_THROW(Dune::NotImplemented, "Variant " << variant << " not valid (only 1 and 2 are).");
}
return;
} // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight)
CoordinateType lowerLeft_;
CoordinateType upperRight_;
Dune::array< unsigned int, dim > numElements_;
Dune::shared_ptr< GridType > grid_;
}; // class GenericCube
template< typename GridImp, int variant >
const std::string GenericCube< GridImp, variant >::id = "stuff.grid.provider.cube";
template< typename GridType >
struct ElementVariant {
static const int id = 2;
};
template< int dim >
struct ElementVariant< Dune::YaspGrid< dim > > {
static const int id = 1;
};
template< int dim >
struct ElementVariant< Dune::SGrid< dim, dim > > {
static const int id = 1;
};
#ifdef HAVE_ALUGRID
template< int dim >
struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > {
static const int id = 1;
};
#endif
// default implementation of a cube for any grid
// tested for
// dim = 2
// ALUGRID_SIMPLEX, variant 2
// ALUGRID_CONFORM, variant 2
// dim = 3
// ALUGRID_SIMPLEX, variant 2
template< typename GridType >
class Cube
: public GenericCube< GridType, ElementVariant<GridType>::id >
{
private:
typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType;
public:
typedef typename BaseType::CoordinateType CoordinateType;
Cube(const Dune::ParameterTree& paramTree)
: BaseType(paramTree)
{}
Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1)
: BaseType(lowerLeft, upperRight, level)
{}
Cube(const double lowerLeft, const double upperRight, const int level = 1)
: BaseType(lowerLeft, upperRight, level)
{}
template < class Coord, class ContainerType >
Cube(const Coord lowerLeft, const Coord upperRight,
const ContainerType elements_per_dim = boost::assign::list_of<typename ContainerType::value_type>().repeat(GridType::dimensionworld,typename ContainerType::value_type(1)) )
: BaseType(lowerLeft, upperRight, elements_per_dim)
{}
}; // class Cube
template< typename GridType >
class UnitCube
: public Cube< GridType >
{
private:
typedef Cube< GridType > BaseType;
public:
UnitCube(const Dune::ParameterTree& paramTree)
: BaseType(0.0, 1.0, paramTree.get("level", 1))
{}
UnitCube(const int level = 1)
: BaseType(0.0, 1.0, level)
{}
}; // class UnitCube
} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH
<|endoftext|> |
<commit_before>//
// Originally written by BjÃrn Fahller (bjorn@fahller.se)
// Modified by Jeff Bush
//
// No rights claimed. The sources are released to the public domain
//
// For license information, please refer to <http://unlicense.org>
//
#include <setjmp.h>
#include <stdlib.h>
#include <iostream>
#include <ostream>
#include <forward_list>
namespace basic {
struct stack_frame { jmp_buf buf; };
std::forward_list<stack_frame> stack;
#define GOSUB \
if (!(setjmp((basic::stack.emplace_front(),basic::stack.front().buf)) \
&& (basic::stack.pop_front(),true))) \
goto
#define RETURN if (basic::stack.empty()) return 0; longjmp(basic::stack.front().buf, 1)
template <typename T, typename U>
struct separator
{
static char const *str() { return ""; }
};
template <typename T>
struct separator<T,T>
{
static char const *str() { return ","; }
};
void type_mismatch() {
std::cout << "Type mismatch error\n";
exit(1);
}
class variant
{
public:
variant(double _numval)
: isnum(true),
numval(_numval)
{}
variant(int _numval)
: isnum(true),
numval(_numval)
{}
variant(const std::string _strval)
: isnum(false),
strval(_strval)
{}
variant(const char *_strval)
: isnum(false),
strval(_strval)
{}
variant toString() const {
if (isnum)
return variant(std::to_string(numval));
else
return *this;
}
variant toNum() const {
if (!isnum)
return variant(stod(strval));
else
return *this;
}
variant &operator=(const variant ©from) {
isnum = copyfrom.isnum;
numval = copyfrom.numval;
strval = copyfrom.strval;
return *this;
}
variant &operator=(double newval) {
isnum = true;
numval = newval;
return *this;
}
variant &operator=(const char *_strval) {
isnum = false;
strval = _strval;
return *this;
}
variant operator+(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return variant(numval + op.numval);
else
return variant(strval + op.strval);
}
variant operator-(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval - op.numval);
}
variant operator*(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval * op.numval);
}
variant operator/(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval / op.numval);
}
bool operator>(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval > op.numval;
else
return strval > op.strval;
}
bool operator>=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval >= op.numval;
else
return strval >= op.strval;
}
bool operator<(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval < op.numval;
else
return strval < op.strval;
}
bool operator<=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval <= op.numval;
else
return strval <= op.strval;
}
bool operator!=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval != op.numval;
else
return strval != op.strval;
}
bool operator==(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval == op.numval;
else
return strval == op.strval;
}
bool isnum;
double numval;
std::string strval;
};
class printer
{
public:
printer &operator,(const char *s) {
std::cout << s;
return *this;
}
const printer &operator,(const variant &v) const {
if (v.isnum)
std::cout << v.numval;
else
std::cout << v.strval;
return *this;
}
~printer() { std::cout << std::endl; }
};
class input
{
public:
input& operator,(char const *s) {
std::cout << s << std::flush;
return *this;
}
input& operator,(variant& v) {
if (v.isnum)
std::cin >> v.numval;
else
std::cin >> v.strval;
return *this;
}
};
#define INPUT basic::input(),
#define PRINT basic::printer(),
#define IF if (
#define THEN )
#define LET basic::variant
#define GOTO goto
#define FOR { basic::variant& for_loop_variable =
#define TO ; \
{ \
jmp_buf for_loop_top; \
bool for_loop_exit = false; \
while (!for_loop_exit) \
{ \
if (setjmp(for_loop_top) == 0) \
{ \
basic::variant for_loop_step=1; \
basic::variant const for_loop_endval=
#define STEP ; \
for_loop_step=
#define NEXT for_loop_variable=for_loop_variable+for_loop_step; \
for_loop_exit=( ( for_loop_step > 0 \
&& for_loop_variable > for_loop_endval) \
||( for_loop_step < 0 \
&& for_loop_variable < for_loop_endval)); \
longjmp(for_loop_top, 1); \
} \
} \
} \
}
#define VAL(x) x.toNum()
#define STR(x) x.toString()
} // namespace basic
<commit_msg>cleaned up trailing whitespace<commit_after>//
// Originally written by BjÃrn Fahller (bjorn@fahller.se)
// Modified by Jeff Bush
//
// No rights claimed. The sources are released to the public domain
//
// For license information, please refer to <http://unlicense.org>
//
#include <setjmp.h>
#include <stdlib.h>
#include <iostream>
#include <ostream>
#include <forward_list>
namespace basic {
struct stack_frame { jmp_buf buf; };
std::forward_list<stack_frame> stack;
#define GOSUB \
if (!(setjmp((basic::stack.emplace_front(),basic::stack.front().buf)) \
&& (basic::stack.pop_front(),true))) \
goto
#define RETURN if (basic::stack.empty()) return 0; longjmp(basic::stack.front().buf, 1)
template <typename T, typename U>
struct separator
{
static char const *str() { return ""; }
};
template <typename T>
struct separator<T,T>
{
static char const *str() { return ","; }
};
void type_mismatch() {
std::cout << "Type mismatch error\n";
exit(1);
}
class variant
{
public:
variant(double _numval)
: isnum(true),
numval(_numval)
{}
variant(int _numval)
: isnum(true),
numval(_numval)
{}
variant(const std::string _strval)
: isnum(false),
strval(_strval)
{}
variant(const char *_strval)
: isnum(false),
strval(_strval)
{}
variant toString() const {
if (isnum)
return variant(std::to_string(numval));
else
return *this;
}
variant toNum() const {
if (!isnum)
return variant(stod(strval));
else
return *this;
}
variant &operator=(const variant ©from) {
isnum = copyfrom.isnum;
numval = copyfrom.numval;
strval = copyfrom.strval;
return *this;
}
variant &operator=(double newval) {
isnum = true;
numval = newval;
return *this;
}
variant &operator=(const char *_strval) {
isnum = false;
strval = _strval;
return *this;
}
variant operator+(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return variant(numval + op.numval);
else
return variant(strval + op.strval);
}
variant operator-(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval - op.numval);
}
variant operator*(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval * op.numval);
}
variant operator/(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval / op.numval);
}
bool operator>(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval > op.numval;
else
return strval > op.strval;
}
bool operator>=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval >= op.numval;
else
return strval >= op.strval;
}
bool operator<(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval < op.numval;
else
return strval < op.strval;
}
bool operator<=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval <= op.numval;
else
return strval <= op.strval;
}
bool operator!=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval != op.numval;
else
return strval != op.strval;
}
bool operator==(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval == op.numval;
else
return strval == op.strval;
}
bool isnum;
double numval;
std::string strval;
};
class printer
{
public:
printer &operator,(const char *s) {
std::cout << s;
return *this;
}
const printer &operator,(const variant &v) const {
if (v.isnum)
std::cout << v.numval;
else
std::cout << v.strval;
return *this;
}
~printer() { std::cout << std::endl; }
};
class input
{
public:
input& operator,(char const *s) {
std::cout << s << std::flush;
return *this;
}
input& operator,(variant& v) {
if (v.isnum)
std::cin >> v.numval;
else
std::cin >> v.strval;
return *this;
}
};
#define INPUT basic::input(),
#define PRINT basic::printer(),
#define IF if (
#define THEN )
#define LET basic::variant
#define GOTO goto
#define FOR { basic::variant& for_loop_variable =
#define TO ; \
{ \
jmp_buf for_loop_top; \
bool for_loop_exit = false; \
while (!for_loop_exit) \
{ \
if (setjmp(for_loop_top) == 0) \
{ \
basic::variant for_loop_step=1; \
basic::variant const for_loop_endval=
#define STEP ; \
for_loop_step=
#define NEXT for_loop_variable=for_loop_variable+for_loop_step; \
for_loop_exit=( ( for_loop_step > 0 \
&& for_loop_variable > for_loop_endval) \
||( for_loop_step < 0 \
&& for_loop_variable < for_loop_endval)); \
longjmp(for_loop_top, 1); \
} \
} \
} \
}
#define VAL(x) x.toNum()
#define STR(x) x.toString()
} // namespace basic
<|endoftext|> |
<commit_before>#include "demo.hpp"
#include "engine/gl/shader.hpp"
#include "engine/core/log.hpp"
#include "engine/extern/imgui.h"
#include <chrono>
#include <random>
constexpr auto k_maxNumObjects = 400u;
constexpr auto k_initialNumObjects = 32u;
constexpr auto k_avg = 20u;
std::default_random_engine generator;
std::uniform_real_distribution<float> distribution(0.f, 1.f);
Demo::Demo(const glm::uvec2 & size)
: m_engine{size, "monoEngine Demo", true},
m_prog{"demo prog"},
m_fbo{"demo fbo"},
m_colorTex{"demo color tex"},
m_depthTex{"demo depth tex"},
m_vbo{"demo vbo"},
m_ibo{"demo ibo"},
m_modelMatrixBuffer{"demo ssbo"},
m_vao{"demo vao"},
m_numObjects{k_initialNumObjects}
{
init(size);
}
void Demo::init(const glm::uvec2 & size) {
m_cam.setRatio(static_cast<float>(size.x) / static_cast<float>(size.y));
m_cam.setFov(glm::radians(45.f));
m_cam.translate({0.f, 0.f, 3.f});
// shader
#ifdef _WIN32
gl::Shader vert("../shader/test/instancedraw.vert", "instance_vert");
gl::Shader frag("../shader/test/color.frag", "color_frag");
#else
gl::Shader vert("shader/test/instancedraw.vert", "instance_vert");
gl::Shader frag("shader/test/color.frag", "color_frag");
#endif
m_prog.attachShader(vert);
m_prog.attachShader(frag);
// vbo (pos3 and norm3 interleaved)
std::vector<GLfloat> vec = {
-1.f, -1.f, 1.f,
0.f, 0.f, 1.f,
1.f, -1.f, 1.f,
0.f, 0.f, 1.f,
1.f, 1.f, 1.f,
0.f, 0.f, 1.f,
-1.f, 1.f, 1.f,
0.f, 0.f, 1.f,
-1.f, -1.f, -1.f,
-1.f, 0.f, 0.f,
-1.f, -1.f, 1.f,
-1.f, 0.f, 0.f,
-1.f, 1.f, 1.f,
-1.f, 0.f, 0.f,
-1.f, 1.f, -1.f,
-1.f, 0.f, 0.f,
1.f, -1.f, -1.f,
0.f, 0.f, -1.f,
-1.f, -1.f, -1.f,
0.f, 0.f, -1.f,
-1.f, 1.f, -1.f,
0.f, 0.f, -1.f,
1.f, 1.f, -1.f,
0.f, 0.f, -1.f,
1.f, -1.f, 1.f,
1.f, 0.f, 0.f,
1.f, -1.f, -1.f,
1.f, 0.f, 0.f,
1.f, 1.f, -1.f,
1.f, 0.f, 0.f,
1.f, 1.f, 1.f,
1.f, 0.f, 0.f,
-1.f, 1.f, 1.f,
0.f, 1.f, 0.f,
1.f, 1.f, 1.f,
0.f, 1.f, 0.f,
1.f, 1.f, -1.f,
0.f, 1.f, 0.f,
-1.f, 1.f, -1.f,
0.f, 1.f, 0.f,
1.f, -1.f, -1.f,
0.f, -1.f, 0.f,
-1.f, -1.f, -1.f,
0.f, -1.f, 0.f,
-1.f, -1.f, 1.f,
0.f, -1.f, 0.f,
1.f, -1.f, 1.f,
0.f, -1.f, 0.f
};
m_vbo.createImmutableStorage(static_cast<unsigned int>(vec.size()) * sizeof(GLfloat), 0, vec.data());
// ibo
std::vector<GLushort> idx = {
0, 1, 2,
2, 3, 0,
4, 5, 6,
6, 7, 4,
8, 9, 10,
10, 11, 8,
12, 13, 14,
14, 15, 12,
16, 17, 18,
18, 19, 16,
20, 21, 22,
22, 23, 20
};
m_ibo.createImmutableStorage(static_cast<unsigned int>(vec.size()) * sizeof(GLushort), 0, idx.data());
// vao
m_vao.bind();
m_vao.enableAttribBinding(0);
m_vao.enableAttribBinding(1);
m_vao.bindVertexBuffer(0, m_vbo, 0, 6 * sizeof(GLfloat));
m_vao.bindVertexFormat(0, 0, 3, GL_FLOAT, GL_FALSE, 0);
m_vao.bindVertexFormat(0, 1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat));
m_vao.bindElementBuffer(m_ibo);
// keys
m_engine.getInputPtr()->addKeyFunc([&](const int key, const int, const int action, const int mods){
if (key == GLFW_KEY_W && (action == GLFW_PRESS || action == GLFW_REPEAT)) {
if ((mods & GLFW_MOD_SHIFT) != 0) {
m_cam.translateLocal({0.f, 0.f, -0.5f});
} else {
m_cam.translateLocal({0.f, 0.f, -0.05f});
}
}
if (key == GLFW_KEY_S && (action == GLFW_PRESS || action == GLFW_REPEAT)) {
if ((mods & GLFW_MOD_SHIFT) != 0) {
m_cam.translateLocal({0.f, 0.f, 0.5f});
} else {
m_cam.translateLocal({0.f, 0.f, 0.05f});
}
}
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(m_engine.getWindowPtr()->getGLFWWindow(), GL_TRUE);
}
});
// modelMatrixBuffer
m_modelMatrixBuffer.createImmutableStorage(k_maxNumObjects * k_maxNumObjects * sizeof(glm::mat4),
GL_MAP_WRITE_BIT | GL_DYNAMIC_STORAGE_BIT);
m_objects.resize(k_maxNumObjects * k_maxNumObjects);
orderModels();
setModelMatrices();
m_colorTex.createImmutableStorage(size.x, size.y, GL_RGBA32F);
m_depthTex.createImmutableStorage(size.x, size.y, GL_DEPTH_COMPONENT32F);
m_fbo.attachTexture(GL_COLOR_ATTACHMENT0, m_colorTex, 0);
m_fbo.attachTexture(GL_DEPTH_ATTACHMENT, m_depthTex, 0);
if (!m_fbo.isComplete(GL_FRAMEBUFFER)) {
LOG_WARNING("demo has incomplete fbo!");
}
}
void Demo::orderModels() {
const auto scale = 2.f / m_numObjects;
auto i = 0u;
for (auto & obj : m_objects) {
obj.resetScale();
obj.resetMoves();
obj.scale({scale * 0.33f, scale * 0.33f, scale * 0.33f});
const auto y = i / m_numObjects;
const auto x = i % m_numObjects;
obj.moveTo({-1.f + scale * (x + 0.5f), -1.f + scale * (y + 0.5f), 0.f});
i++;
}
}
void Demo::setModelMatrices() {
void * voidPtr = m_modelMatrixBuffer.map(0, m_numObjects * m_numObjects, GL_MAP_WRITE_BIT);
auto * ptr = reinterpret_cast<glm::mat4 *>(voidPtr);
auto count = 0u;
for (const auto & obj : m_objects) {
*ptr = obj.getModelMatrix();
++ptr;
if (++count > m_numObjects * m_numObjects) break;
}
m_modelMatrixBuffer.unmap();
}
double Demo::getAverageMs(const std::deque<GLuint64> & deque) {
auto avg = 0.0;
for (const auto & t : deque) {
avg += static_cast<long double>(t) * 0.000001;
}
avg /= deque.size();
return avg;
}
double Demo::getAverageMs(const std::deque<double> & deque) {
auto avg = 0.0;
for (const auto & t : deque) {
avg += t;
}
avg /= deque.size();
return avg;
}
bool Demo::render() {
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
m_timer.start();
// setup shader
m_prog.use();
m_prog["col"] = glm::vec3{1.f, 0.f, 0.f};
m_prog["ViewProj"] = m_cam.getProjMatrix() * m_cam.getViewMatrix();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_modelMatrixBuffer);
// draw
m_fbo.bind();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_fbo.draw({GL_COLOR_ATTACHMENT0});
m_vao.bind();
glDrawElementsInstanced(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0,
static_cast<GLsizei>(m_numObjects * m_numObjects));
m_fbo.unbind();
const auto size = static_cast<glm::ivec2>(m_engine.getWindowPtr()->getFrameBufferSize());
m_fbo.blitAttachment(GL_COLOR_ATTACHMENT0, {0, 0, size.x, size.y});
// stop timer
m_timeDeque.emplace_back(m_timer.stop());
static auto ms = 0.0;
if (m_timeDeque.size() == k_avg) {
ms = getAverageMs(m_timeDeque);
m_timeDeque.erase(m_timeDeque.begin(), m_timeDeque.begin() + k_avg / 2);
}
// rotate objects
const auto start = std::chrono::system_clock::now();
for (auto i = 0u; i < m_numObjects * m_numObjects; ++i) {
m_objects[i].rotate(0.03f,
{distribution(generator), distribution(generator), distribution(generator)});
m_objects[i].rotateAround(0.01f, {0.f, 1.f, 0.f});
}
setModelMatrices();
std::chrono::duration<double> tmp = std::chrono::system_clock::now() - start;
m_cpuTimeDeque.emplace_back(tmp.count() * 1000.0);
static auto ms_cpu = 0.0;
if (m_cpuTimeDeque.size() == k_avg) {
ms_cpu = getAverageMs(m_cpuTimeDeque);
m_cpuTimeDeque.erase(m_cpuTimeDeque.begin(), m_cpuTimeDeque.begin() + k_avg / 2);
}
// Gui
m_engine.getGuiPtr()->update();
int numObj = static_cast<int>(m_numObjects);
ImGui::SliderInt("numObjects", &numObj, 1, k_maxNumObjects);
if (m_numObjects != static_cast<unsigned int>(numObj)) {
m_numObjects = static_cast<unsigned int>(numObj);
orderModels();
setModelMatrices();
}
ImGui::Columns(2, "time", true);
ImGui::Text("ms gpu");
ImGui::NextColumn();
ImGui::Text("%f", ms);
ImGui::NextColumn();
ImGui::Text("fps");
ImGui::NextColumn();
ImGui::Text("%d", static_cast<unsigned int>(1000.0 / ms));
ImGui::NextColumn();
ImGui::Text("ms cpu");
ImGui::NextColumn();
ImGui::Text("%f", ms_cpu);
ImGui::NextColumn();
m_engine.getGuiPtr()->render();
return m_engine.render();
}
<commit_msg>using threads to speed up<commit_after>#include "demo.hpp"
#include "engine/gl/shader.hpp"
#include "engine/core/log.hpp"
#include "engine/extern/imgui.h"
#include <chrono>
#include <random>
#include <future>
constexpr auto k_maxNumObjects = 400u;
constexpr auto k_initialNumObjects = 32u;
constexpr auto k_avg = 20u;
std::default_random_engine generator;
std::uniform_real_distribution<float> distribution(0.f, 1.f);
Demo::Demo(const glm::uvec2 & size)
: m_engine{size, "monoEngine Demo", true},
m_prog{"demo prog"},
m_fbo{"demo fbo"},
m_colorTex{"demo color tex"},
m_depthTex{"demo depth tex"},
m_vbo{"demo vbo"},
m_ibo{"demo ibo"},
m_modelMatrixBuffer{"demo ssbo"},
m_vao{"demo vao"},
m_numObjects{k_initialNumObjects}
{
init(size);
}
void Demo::init(const glm::uvec2 & size) {
m_cam.setRatio(static_cast<float>(size.x) / static_cast<float>(size.y));
m_cam.setFov(glm::radians(45.f));
m_cam.translate({0.f, 0.f, 3.f});
// shader
#ifdef _WIN32
gl::Shader vert("../shader/test/instancedraw.vert", "instance_vert");
gl::Shader frag("../shader/test/color.frag", "color_frag");
#else
gl::Shader vert("shader/test/instancedraw.vert", "instance_vert");
gl::Shader frag("shader/test/color.frag", "color_frag");
#endif
m_prog.attachShader(vert);
m_prog.attachShader(frag);
// vbo (pos3 and norm3 interleaved)
std::vector<GLfloat> vec = {
-1.f, -1.f, 1.f,
0.f, 0.f, 1.f,
1.f, -1.f, 1.f,
0.f, 0.f, 1.f,
1.f, 1.f, 1.f,
0.f, 0.f, 1.f,
-1.f, 1.f, 1.f,
0.f, 0.f, 1.f,
-1.f, -1.f, -1.f,
-1.f, 0.f, 0.f,
-1.f, -1.f, 1.f,
-1.f, 0.f, 0.f,
-1.f, 1.f, 1.f,
-1.f, 0.f, 0.f,
-1.f, 1.f, -1.f,
-1.f, 0.f, 0.f,
1.f, -1.f, -1.f,
0.f, 0.f, -1.f,
-1.f, -1.f, -1.f,
0.f, 0.f, -1.f,
-1.f, 1.f, -1.f,
0.f, 0.f, -1.f,
1.f, 1.f, -1.f,
0.f, 0.f, -1.f,
1.f, -1.f, 1.f,
1.f, 0.f, 0.f,
1.f, -1.f, -1.f,
1.f, 0.f, 0.f,
1.f, 1.f, -1.f,
1.f, 0.f, 0.f,
1.f, 1.f, 1.f,
1.f, 0.f, 0.f,
-1.f, 1.f, 1.f,
0.f, 1.f, 0.f,
1.f, 1.f, 1.f,
0.f, 1.f, 0.f,
1.f, 1.f, -1.f,
0.f, 1.f, 0.f,
-1.f, 1.f, -1.f,
0.f, 1.f, 0.f,
1.f, -1.f, -1.f,
0.f, -1.f, 0.f,
-1.f, -1.f, -1.f,
0.f, -1.f, 0.f,
-1.f, -1.f, 1.f,
0.f, -1.f, 0.f,
1.f, -1.f, 1.f,
0.f, -1.f, 0.f
};
m_vbo.createImmutableStorage(static_cast<unsigned int>(vec.size()) * sizeof(GLfloat), 0, vec.data());
// ibo
std::vector<GLushort> idx = {
0, 1, 2,
2, 3, 0,
4, 5, 6,
6, 7, 4,
8, 9, 10,
10, 11, 8,
12, 13, 14,
14, 15, 12,
16, 17, 18,
18, 19, 16,
20, 21, 22,
22, 23, 20
};
m_ibo.createImmutableStorage(static_cast<unsigned int>(vec.size()) * sizeof(GLushort), 0, idx.data());
// vao
m_vao.bind();
m_vao.enableAttribBinding(0);
m_vao.enableAttribBinding(1);
m_vao.bindVertexBuffer(0, m_vbo, 0, 6 * sizeof(GLfloat));
m_vao.bindVertexFormat(0, 0, 3, GL_FLOAT, GL_FALSE, 0);
m_vao.bindVertexFormat(0, 1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat));
m_vao.bindElementBuffer(m_ibo);
// keys
m_engine.getInputPtr()->addKeyFunc([&](const int key, const int, const int action, const int mods){
if (key == GLFW_KEY_W && (action == GLFW_PRESS || action == GLFW_REPEAT)) {
if ((mods & GLFW_MOD_SHIFT) != 0) {
m_cam.translateLocal({0.f, 0.f, -0.5f});
} else {
m_cam.translateLocal({0.f, 0.f, -0.05f});
}
}
if (key == GLFW_KEY_S && (action == GLFW_PRESS || action == GLFW_REPEAT)) {
if ((mods & GLFW_MOD_SHIFT) != 0) {
m_cam.translateLocal({0.f, 0.f, 0.5f});
} else {
m_cam.translateLocal({0.f, 0.f, 0.05f});
}
}
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(m_engine.getWindowPtr()->getGLFWWindow(), GL_TRUE);
}
});
// modelMatrixBuffer
m_modelMatrixBuffer.createImmutableStorage(k_maxNumObjects * k_maxNumObjects * sizeof(glm::mat4),
GL_MAP_WRITE_BIT | GL_DYNAMIC_STORAGE_BIT);
m_objects.resize(k_maxNumObjects * k_maxNumObjects);
orderModels();
setModelMatrices();
m_colorTex.createImmutableStorage(size.x, size.y, GL_RGBA32F);
m_depthTex.createImmutableStorage(size.x, size.y, GL_DEPTH_COMPONENT32F);
m_fbo.attachTexture(GL_COLOR_ATTACHMENT0, m_colorTex, 0);
m_fbo.attachTexture(GL_DEPTH_ATTACHMENT, m_depthTex, 0);
if (!m_fbo.isComplete(GL_FRAMEBUFFER)) {
LOG_WARNING("demo has incomplete fbo!");
}
}
void Demo::orderModels() {
const auto scale = 2.f / m_numObjects;
auto i = 0u;
for (auto & obj : m_objects) {
obj.resetScale();
obj.resetMoves();
obj.scale({scale * 0.33f, scale * 0.33f, scale * 0.33f});
const auto y = i / m_numObjects;
const auto x = i % m_numObjects;
obj.moveTo({-1.f + scale * (x + 0.5f), -1.f + scale * (y + 0.5f), 0.f});
i++;
}
}
void Demo::setModelMatrices() {
void * voidPtr = m_modelMatrixBuffer.map(0, m_numObjects * m_numObjects, GL_MAP_WRITE_BIT);
auto * ptr = reinterpret_cast<glm::mat4 *>(voidPtr);
auto count = 0u;
for (const auto & obj : m_objects) {
*ptr = obj.getModelMatrix();
++ptr;
if (++count > m_numObjects * m_numObjects) break;
}
m_modelMatrixBuffer.unmap();
}
double Demo::getAverageMs(const std::deque<GLuint64> & deque) {
auto avg = 0.0;
for (const auto & t : deque) {
avg += static_cast<long double>(t) * 0.000001;
}
avg /= deque.size();
return avg;
}
double Demo::getAverageMs(const std::deque<double> & deque) {
auto avg = 0.0;
for (const auto & t : deque) {
avg += t;
}
avg /= deque.size();
return avg;
}
bool Demo::render() {
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
m_timer.start();
// setup shader
m_prog.use();
m_prog["col"] = glm::vec3{1.f, 0.f, 0.f};
m_prog["ViewProj"] = m_cam.getProjMatrix() * m_cam.getViewMatrix();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_modelMatrixBuffer);
// draw
m_fbo.bind();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_fbo.draw({GL_COLOR_ATTACHMENT0});
m_vao.bind();
glDrawElementsInstanced(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0,
static_cast<GLsizei>(m_numObjects * m_numObjects));
m_fbo.unbind();
const auto size = static_cast<glm::ivec2>(m_engine.getWindowPtr()->getFrameBufferSize());
m_fbo.blitAttachment(GL_COLOR_ATTACHMENT0, {0, 0, size.x, size.y});
// stop timer
m_timeDeque.emplace_back(m_timer.stop());
static auto ms = 0.0;
if (m_timeDeque.size() == k_avg) {
ms = getAverageMs(m_timeDeque);
m_timeDeque.erase(m_timeDeque.begin(), m_timeDeque.begin() + k_avg / 2);
}
// rotate objects
const auto start = std::chrono::system_clock::now();
const auto t = std::thread::hardware_concurrency();
if (t <= 1) {
for (auto i = 0u; i < m_numObjects * m_numObjects; ++i) {
m_objects[i].rotate(0.03f,
{ distribution(generator), distribution(generator), distribution(generator) });
m_objects[i].rotateAround(0.01f, { 0.f, 1.f, 0.f });
}
}
else {
const auto parFunc = [&](unsigned int from, unsigned int to) {
for (auto i = from; i < to; ++i) {
m_objects[i].rotate(0.03f,
{ distribution(generator), distribution(generator), distribution(generator) });
m_objects[i].rotateAround(0.01f, { 0.f, 1.f, 0.f });
}
};
std::vector<std::future<void>> futures;
futures.reserve(t);
const auto step = m_numObjects * m_numObjects / t;
for (auto j = 0u; j < t; ++j) {
futures.emplace_back(std::async(std::launch::async, parFunc, j * step, j == t - 1 ? m_numObjects * m_numObjects : (j + 1) * step));
}
for (const auto & f : futures) {
f.wait();
}
}
setModelMatrices();
std::chrono::duration<double> tmp = std::chrono::system_clock::now() - start;
m_cpuTimeDeque.emplace_back(tmp.count() * 1000.0);
static auto ms_cpu = 0.0;
if (m_cpuTimeDeque.size() == k_avg) {
ms_cpu = getAverageMs(m_cpuTimeDeque);
m_cpuTimeDeque.erase(m_cpuTimeDeque.begin(), m_cpuTimeDeque.begin() + k_avg / 2);
}
// Gui
m_engine.getGuiPtr()->update();
int numObj = static_cast<int>(m_numObjects);
ImGui::SliderInt("numObjects", &numObj, 1, k_maxNumObjects);
if (m_numObjects != static_cast<unsigned int>(numObj)) {
m_numObjects = static_cast<unsigned int>(numObj);
orderModels();
setModelMatrices();
}
ImGui::Columns(2, "time", true);
ImGui::Text("ms gpu");
ImGui::NextColumn();
ImGui::Text("%f", ms);
ImGui::NextColumn();
ImGui::Text("fps");
ImGui::NextColumn();
ImGui::Text("%d", static_cast<unsigned int>(1000.0 / ms));
ImGui::NextColumn();
ImGui::Text("ms cpu");
ImGui::NextColumn();
ImGui::Text("%f", ms_cpu);
ImGui::NextColumn();
m_engine.getGuiPtr()->render();
return m_engine.render();
}
<|endoftext|> |
<commit_before>#include "engine/allocator.h"
#include "engine/crt.h"
#include "engine/atomic.h"
#include "engine/page_allocator.h"
#include "engine/os.h"
namespace Lumix
{
PageAllocator::~PageAllocator()
{
ASSERT(allocated_count == 0);
void* p = free_pages;
while (p) {
void* tmp = p;
memcpy(&p, p, sizeof(p)); //-V579
OS::memRelease(tmp);
}
}
void PageAllocator::lock()
{
mutex.enter();
}
void PageAllocator::unlock()
{
mutex.exit();
}
void* PageAllocator::allocate(bool lock)
{
if (lock) mutex.enter();
++allocated_count;
if (free_pages) {
void* tmp = free_pages;
memcpy(&free_pages, free_pages, sizeof(free_pages)); //-V579
if (lock) mutex.exit();
return tmp;
}
++reserved_count;
if (lock) mutex.exit();
void* mem = OS::memReserve(PAGE_SIZE);
ASSERT(intptr_t(mem) % PAGE_SIZE == 0);
OS::memCommit(mem, PAGE_SIZE);
return mem;
}
void PageAllocator::deallocate(void* mem, bool lock)
{
if (lock) mutex.enter();
--allocated_count;
memcpy(mem, &free_pages, sizeof(free_pages));
free_pages = mem;
if (lock) mutex.exit();
}
} // namespace Lumix<commit_msg>fixed win build<commit_after>#include "engine/allocator.h"
#include "engine/crt.h"
#include "engine/atomic.h"
#include "engine/page_allocator.h"
#include "engine/os.h"
namespace Lumix
{
PageAllocator::~PageAllocator()
{
ASSERT(allocated_count == 0);
void* p = free_pages;
while (p) {
void* tmp = p;
memcpy(&p, p, sizeof(p)); //-V579
OS::memRelease(tmp);
}
}
void PageAllocator::lock()
{
mutex.enter();
}
void PageAllocator::unlock()
{
mutex.exit();
}
void* PageAllocator::allocate(bool lock)
{
if (lock) mutex.enter();
++allocated_count;
if (free_pages) {
void* tmp = free_pages;
memcpy(&free_pages, free_pages, sizeof(free_pages)); //-V579
if (lock) mutex.exit();
return tmp;
}
++reserved_count;
if (lock) mutex.exit();
void* mem = OS::memReserve(PAGE_SIZE);
ASSERT(uintptr(mem) % PAGE_SIZE == 0);
OS::memCommit(mem, PAGE_SIZE);
return mem;
}
void PageAllocator::deallocate(void* mem, bool lock)
{
if (lock) mutex.enter();
--allocated_count;
memcpy(mem, &free_pages, sizeof(free_pages));
free_pages = mem;
if (lock) mutex.exit();
}
} // namespace Lumix<|endoftext|> |
<commit_before>#include "api.h"
#include "n2np/relay.h"
#include "n2np/node.h"
#include "webm/videodev.h"
#include "webm/vpxdecoder.h"
#include "webm/vpxencoder.h"
#include "webm/videoframe.h"
#include "dht/node.h"
#include <strings.h>
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>
#define LightGreen "\033[01;33m"
#define LightBlue "\033[01;34m"
#define Restore "\033[0m"
using namespace Epyx;
class Demo;
class Displayer :public Epyx::N2NP::Module
{
public:
Displayer(Demo *demo, const std::string& pseudo_ext);
virtual void fromN2NP(Epyx::N2NP::Node& node, Epyx::N2NP::NodeId from, const char* data, unsigned int size);
private:
Demo *demo;
std::string pseudo_ext;
};
class VideoDisplayer :public Epyx::N2NP::Module
{
public:
VideoDisplayer(Demo *demo);
virtual void fromN2NP(Epyx::N2NP::Node& node, Epyx::N2NP::NodeId from, const char* data, unsigned int size);
private:
Demo *demo;
};
class SenderAndUIThread :public Thread
{
public:
SenderAndUIThread(Demo* demo);
virtual void run();
private:
Demo* demo;
};
class Demo
{
public:
Demo(Epyx::N2NP::Node *node);
bool run();
void updateDisplay();
void receive(const std::string& pseudo, const std::string& msg, bool isMe = false);
void stop();
void newFrame(const webm::FramePacket& fpkt);
webm::VideoFrame vframe;
Epyx::N2NP::Node *node;
N2NP::NodeId remoteNodeid;
private:
// Clear screen
void clear();
// Setup terminal to be char-by-char instead of line-by-line
void configureTerm();
std::string msg;
webm::VpxDecoder decoder;
std::string historique;
Mutex histomut;
std::string pseudo;
bool vframe_inited;
bool running;
};
Displayer::Displayer(Demo *demo, const std::string& pseudo_ext)
:demo(demo), pseudo_ext(pseudo_ext) {
EPYX_ASSERT(demo != NULL);
}
void Displayer::fromN2NP(Epyx::N2NP::Node& node, Epyx::N2NP::NodeId from, const char* data, unsigned int size) {
demo->receive(pseudo_ext, data);
demo->updateDisplay();
}
VideoDisplayer::VideoDisplayer(Demo* demo)
:demo(demo) {
}
void VideoDisplayer::fromN2NP(Epyx::N2NP::Node& node, Epyx::N2NP::NodeId from, const char* data, unsigned int size) {
Epyx::GTTParser parser;
parser.eat(data, size);
GTTPacket* gttpkt = parser.getPacket();
webm::FramePacket fpkt(*gttpkt);
demo->newFrame(fpkt);
delete gttpkt;
}
SenderAndUIThread::SenderAndUIThread(Demo* demo)
:Thread("UI"), demo(demo) {
}
void SenderAndUIThread::run() {
webm::VideoDev vdev(640, 480, 30);
webm::VpxEncoder encoder(640, 480, 400);
vpx_image_t rawImage;
vpx_img_alloc(&rawImage, IMG_FMT_YV12, 640, 480, 1);
bool vdev_started = vdev.start_capture();
while(! demo->vframe.checkSDLQuitAndEvents()) {
if(vdev_started && vdev.get_frame(&rawImage)) {
struct timeval tv;
int gettimeofday_status = gettimeofday(&tv, NULL);
EPYX_ASSERT(gettimeofday_status == 0);
long int utime = tv.tv_sec * 1000 + tv.tv_usec;
encoder.encode(rawImage, utime, 0);
webm::FramePacket* fpkt;
while ((fpkt = encoder.getPacket()) != NULL) {
char* netdata;
unsigned long netsize = fpkt->build(&netdata);
demo->node->send(demo->remoteNodeid, "VIDEO", netdata, netsize);
}
}
usleep(1000);
}
demo->stop();
}
Demo::Demo(Epyx::N2NP::Node *node)
:vframe(640, 480, "Epyx Chat"), node(node), vframe_inited(false) {
}
bool Demo::run() {
EPYX_ASSERT(node != NULL);
// Log in
std::cout << "Entrez votre pseudo : ";
std::cin >> pseudo;
// Create DHT node
DHT::Id id(DHT::Id::INIT_RANDOM);
DHT::Node *dhtNode = new DHT::Node(id, *node, "DHT");
node->addModule("DHT", dhtNode);
// Send ping ro the relay
N2NP::NodeId relayNodeId("self", node->getId().getRelay());
DHT::Peer relayPeer(relayNodeId);
dhtNode->sendPing(relayPeer);
VideoDisplayer videoModule(this);
node->addModule("VIDEO", &videoModule);
// Wait the ping to be proceeded
sleep(1);
if (!dhtNode->setValueSync(Demo::pseudo, node->getId().toString())) {
std::cerr << "Impossible d'enregistrer une valeur !" << std::endl;
return false;
}
// Ask remote ID
std::string pseudo_ext;
std::cout << "Entrez le pseudo que vous voulez contacter : ";
std::cin >> pseudo_ext;
// Retreive remote node ID
std::string remoteNodeidStr;
while (!dhtNode->getValueSync(pseudo_ext, remoteNodeidStr)) {
std::cout << "En attente...\n";
sleep(1);
}
remoteNodeid = N2NP::NodeId(remoteNodeidStr);
log::debug << pseudo_ext << " est dans " << remoteNodeid << log::endl;
// Add displayer module to my N2NP node
Displayer displayModule(this, pseudo_ext);
node->addModule("DISPLAY", &displayModule);
// Let's run !
running = true;
vframe.init();
vframe_inited = true;
SenderAndUIThread ui_thread(this);
ui_thread.start();
unsigned char c;
configureTerm();
while (running) {
updateDisplay();
read(STDIN_FILENO, &c, 1);
if(c==8 || c== 127||c==126){
if(msg.length()>=1)
msg.erase(msg.length()-1);
}
else
msg.append(1, c);
if (c == '\n') {
node->send(remoteNodeid, "DISPLAY", msg.c_str(), msg.length() + 1);
receive(pseudo, msg, true);
msg.assign("");
}
}
return true;
}
void Demo::stop() {
running = false;
}
void Demo::newFrame(const webm::FramePacket& fpkt) {
decoder.decode(fpkt);
vpx_image_t *img = decoder.getFrame();
if (img != NULL && vframe_inited) {
vframe.showFrame(img);
}
}
void Demo::clear() {
system("clear");
}
void Demo::configureTerm() {
struct termios tios;
tcgetattr(STDIN_FILENO, &tios);
//tcflag_t old_c_lflag = tios.c_lflag;
tios.c_lflag &= ~ICANON;
tcsetattr(STDIN_FILENO, TCSANOW, &tios);
}
void Demo::receive(const std::string& pseudo, const std::string& msg, bool isMe) {
histomut.lock();
historique.append(isMe ? LightBlue : LightGreen)
.append(std::string("<").append(pseudo).append(std::string("> : "))
.append(msg)).append(Restore);
histomut.unlock();
}
void Demo::updateDisplay() {
// Display
clear();
std::cout << historique;
std::cout << "<" << pseudo << "> : " << msg;
fflush(stdout);
}
int main(int argc, char **argv) {
try {
Epyx::API epyx;
epyx.setNetWorkers(50);
// Create my node
if (argc < 2) {
std::cerr << "You need to tell me the relay I am intented to connect." << std::endl;
return 1;
}
Epyx::Address relayAddr(argv[1]);
Epyx::N2NP::Node *node = new Epyx::N2NP::Node(relayAddr);
epyx.addNode(node);
if (!node->waitReady(5000)) {
Epyx::log::error << "Initialisation of node took too much time"
<< Epyx::log::endl;
epyx.destroyAllNodes();
epyx.destroyRelay(2000);
return 1;
}
// Now start demo
Demo demo(node);
demo.run();
} catch (Epyx::Exception e) {
std::cout << e << std::endl;
}
return 0;
}
<commit_msg>just add a welcome scene to be user friendly. can just comment the welcome() fonction to disable it<commit_after>#include "api.h"
#include "n2np/relay.h"
#include "n2np/node.h"
#include "webm/videodev.h"
#include "webm/vpxdecoder.h"
#include "webm/vpxencoder.h"
#include "webm/videoframe.h"
#include "dht/node.h"
#include <strings.h>
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>
#define LightBlue "\033[00;34m"
#define Yellow "\033[00;32m"
#define LightGreenBold "\033[01;33m"
#define LightBlueBold "\033[01;34m"
#define MagentaBold "\033[01;35m"
#define Restore "\033[0m"
using namespace Epyx;
class Demo;
class Displayer :public Epyx::N2NP::Module
{
public:
Displayer(Demo *demo, const std::string& pseudo_ext);
virtual void fromN2NP(Epyx::N2NP::Node& node, Epyx::N2NP::NodeId from, const char* data, unsigned int size);
private:
Demo *demo;
std::string pseudo_ext;
};
class VideoDisplayer :public Epyx::N2NP::Module
{
public:
VideoDisplayer(Demo *demo);
virtual void fromN2NP(Epyx::N2NP::Node& node, Epyx::N2NP::NodeId from, const char* data, unsigned int size);
private:
Demo *demo;
};
class SenderAndUIThread :public Thread
{
public:
SenderAndUIThread(Demo* demo);
virtual void run();
private:
Demo* demo;
};
class Demo
{
public:
Demo(Epyx::N2NP::Node *node);
bool run();
void updateDisplay();
void receive(const std::string& pseudo, const std::string& msg, bool isMe = false);
void stop();
void newFrame(const webm::FramePacket& fpkt);
webm::VideoFrame vframe;
Epyx::N2NP::Node *node;
N2NP::NodeId remoteNodeid;
private:
// Clear screen
void clear();
// Setup terminal to be char-by-char instead of line-by-line
void configureTerm();
std::string msg;
webm::VpxDecoder decoder;
std::string historique;
Mutex histomut;
std::string pseudo;
bool vframe_inited;
bool running;
};
Displayer::Displayer(Demo *demo, const std::string& pseudo_ext)
:demo(demo), pseudo_ext(pseudo_ext) {
EPYX_ASSERT(demo != NULL);
}
void Displayer::fromN2NP(Epyx::N2NP::Node& node, Epyx::N2NP::NodeId from, const char* data, unsigned int size) {
demo->receive(pseudo_ext, data);
demo->updateDisplay();
}
VideoDisplayer::VideoDisplayer(Demo* demo)
:demo(demo) {
}
void VideoDisplayer::fromN2NP(Epyx::N2NP::Node& node, Epyx::N2NP::NodeId from, const char* data, unsigned int size) {
Epyx::GTTParser parser;
parser.eat(data, size);
GTTPacket* gttpkt = parser.getPacket();
webm::FramePacket fpkt(*gttpkt);
demo->newFrame(fpkt);
delete gttpkt;
}
SenderAndUIThread::SenderAndUIThread(Demo* demo)
:Thread("UI"), demo(demo) {
}
void SenderAndUIThread::run() {
webm::VideoDev vdev(640, 480, 30);
webm::VpxEncoder encoder(640, 480, 400);
vpx_image_t rawImage;
vpx_img_alloc(&rawImage, IMG_FMT_YV12, 640, 480, 1);
bool vdev_started = vdev.start_capture();
while(! demo->vframe.checkSDLQuitAndEvents()) {
if(vdev_started && vdev.get_frame(&rawImage)) {
struct timeval tv;
int gettimeofday_status = gettimeofday(&tv, NULL);
EPYX_ASSERT(gettimeofday_status == 0);
long int utime = tv.tv_sec * 1000 + tv.tv_usec;
encoder.encode(rawImage, utime, 0);
webm::FramePacket* fpkt;
while ((fpkt = encoder.getPacket()) != NULL) {
char* netdata;
unsigned long netsize = fpkt->build(&netdata);
demo->node->send(demo->remoteNodeid, "VIDEO", netdata, netsize);
}
}
usleep(1000);
}
demo->stop();
}
Demo::Demo(Epyx::N2NP::Node *node)
:vframe(640, 480, "Epyx Chat"), node(node), vframe_inited(false) {
}
bool Demo::run() {
EPYX_ASSERT(node != NULL);
// Log in
std::cout << "Entrez votre pseudo : ";
std::cin >> pseudo;
// Create DHT node
DHT::Id id(DHT::Id::INIT_RANDOM);
DHT::Node *dhtNode = new DHT::Node(id, *node, "DHT");
node->addModule("DHT", dhtNode);
// Send ping ro the relay
N2NP::NodeId relayNodeId("self", node->getId().getRelay());
DHT::Peer relayPeer(relayNodeId);
dhtNode->sendPing(relayPeer);
VideoDisplayer videoModule(this);
node->addModule("VIDEO", &videoModule);
// Wait the ping to be proceeded
sleep(1);
if (!dhtNode->setValueSync(Demo::pseudo, node->getId().toString())) {
std::cerr << "Impossible d'enregistrer une valeur !" << std::endl;
return false;
}
// Ask remote ID
std::string pseudo_ext;
std::cout << "Entrez le pseudo que vous voulez contacter : ";
std::cin >> pseudo_ext;
// Retreive remote node ID
std::string remoteNodeidStr;
while (!dhtNode->getValueSync(pseudo_ext, remoteNodeidStr)) {
std::cout << "En attente...\n";
sleep(1);
}
remoteNodeid = N2NP::NodeId(remoteNodeidStr);
log::debug << pseudo_ext << " est dans " << remoteNodeid << log::endl;
// Add displayer module to my N2NP node
Displayer displayModule(this, pseudo_ext);
node->addModule("DISPLAY", &displayModule);
// Let's run !
running = true;
vframe.init();
vframe_inited = true;
SenderAndUIThread ui_thread(this);
ui_thread.start();
unsigned char c;
configureTerm();
while (running) {
updateDisplay();
read(STDIN_FILENO, &c, 1);
if(c==8 || c== 127||c==126){
if(msg.length()>=1)
msg.erase(msg.length()-1);
}
else
msg.append(1, c);
if (c == '\n') {
node->send(remoteNodeid, "DISPLAY", msg.c_str(), msg.length() + 1);
receive(pseudo, msg, true);
msg.assign("");
}
}
return true;
}
void Demo::stop() {
running = false;
}
void Demo::newFrame(const webm::FramePacket& fpkt) {
decoder.decode(fpkt);
vpx_image_t *img = decoder.getFrame();
if (img != NULL && vframe_inited) {
vframe.showFrame(img);
}
}
void Demo::clear() {
system("clear");
}
void Demo::configureTerm() {
struct termios tios;
tcgetattr(STDIN_FILENO, &tios);
//tcflag_t old_c_lflag = tios.c_lflag;
tios.c_lflag &= ~ICANON;
tcsetattr(STDIN_FILENO, TCSANOW, &tios);
}
void Demo::receive(const std::string& pseudo, const std::string& msg, bool isMe) {
histomut.lock();
historique.append(isMe ? LightBlueBold : LightGreenBold)
.append(std::string("<").append(pseudo).append(std::string("> : "))
.append(msg)).append(Restore);
histomut.unlock();
}
void Demo::updateDisplay() {
// Display
clear();
std::cout << historique;
std::cout << "<" << pseudo << "> : " << msg;
fflush(stdout);
}
void welcome(void);
int main(int argc, char **argv) {
try {
welcome();
Epyx::API epyx;
epyx.setNetWorkers(50);
// Create my node
if (argc < 2) {
std::cerr << "You need to tell me the relay I am intented to connect." << std::endl;
return 1;
}
Epyx::Address relayAddr(argv[1]);
Epyx::N2NP::Node *node = new Epyx::N2NP::Node(relayAddr);
epyx.addNode(node);
if (!node->waitReady(5000)) {
Epyx::log::error << "Initialisation of node took too much time"
<< Epyx::log::endl;
epyx.destroyAllNodes();
epyx.destroyRelay(2000);
return 1;
}
// Now start demo
Demo demo(node);
demo.run();
} catch (Epyx::Exception e) {
std::cout << e << std::endl;
}
return 0;
}
void welcome(void)
{
system("clear");
std::cout<<Yellow;
std::cout<<" "<<std::endl;
std::cout<<" "<<std::endl;
std::cout<<" Welcome to ";
std::cout<<MagentaBold;
std::cout<<"EPYX";
std::cout<<Yellow;
std::cout<<" ! "<<std::endl;
std::cout<<" "<<std::endl;
std::cout<<" "<<std::endl;
std::cout<<" A Fancy Free Net Environment ┊ ┊ ┊ ┊┊ ┊ ┊ "<<std::endl;
std::cout<<" ┊ ┊ ┊ ┊┊ ┆ ┊ "<<std::endl;
std::cout<<" ☆ ┊ ☆ ┊☆ ┆ ┊ "<<std::endl;
std::cout<<" ☆ ☆ ┆ ┊ "<<std::endl;
std::cout<<" │★☆ ╮。。... ☆ ┊ "<<std::endl;
std::cout<<" ╭╯☆★☆★╭╯。。... ┊ "<<std::endl;
std::cout<<" ╰╮★☆★╭╯。。。... ┊ "<<std::endl;
std::cout<<" │☆╭—╯ ☆ "<<std::endl;
std::cout<<" ╭╯╭╯ "<<std::endl;
std::cout<<" ╔╝★╚╗ "<<std::endl;
std::cout<<" ║★☆★║╔═══╗ ╔═══╗ ╔═══╗ ╔═══╗ "<<std::endl;
std::cout<<" ║☆★☆║║ E ║ ║ P ║ ║ Y ║ ║ X ║ "<<std::endl;
std::cout<<" ◢◎══◎╝╚◎═◎╝═╚◎═◎╝═╚◎═◎╝═╚◎═◎╝ "<<std::endl;
std::cout << Restore;
fflush(stdout);
sleep(1);
system("clear");
}<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <cstdlib>
#include <ctime>
#ifdef __clang__
#pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
#endif
#include <rapidjson/document.h>
#include <picojson.h>
#include <rabbit.hpp>
void print(int score, const std::string& title, const std::string& url)
{
std::cerr << "(" << score << ") " << title << " - " << url << std::endl;
}
template <typename Bench>
struct runner
{
Bench bench;
std::string json;
int score;
int try_count;
runner(const std::string& json)
: json(json)
, score(0)
, try_count(0)
{}
void run(int n)
{
try
{
std::clock_t t = std::clock();
while (n-- > 0)
bench(json);
score += (std::clock() - t);
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
++try_count;
}
void disp() const
{
std::cout << bench.name() << " " << "score: " << (score / try_count) << std::endl;
}
};
struct rapidjson_bench
{
std::string name() const { return "rapidjson"; }
void operator()(const std::string& json) const
{
rapidjson::Document doc;
if (doc.Parse<0>(json.c_str()).HasParseError())
throw std::runtime_error("parse_error");
const rapidjson::Value& children = doc["data"]["children"];
for (rapidjson::Value::ConstValueIterator it = children.Begin(); it != children.End(); ++it)
{
const rapidjson::Value& data = (*it)["data"];
print(data["score"].GetInt(), data["title"].GetString(), data["url"].GetString());
}
}
};
struct picojson_bench
{
std::string name() const { return "picojson "; }
void operator()(const std::string& json) const
{
picojson::value v;
std::string error;
std::string::const_iterator it = json.begin();
picojson::parse(v, it, json.end(), &error);
if (!error.empty())
throw std::runtime_error(error);
const picojson::array& children = v.get("data").get("children").get<picojson::array>();
for (picojson::array::const_iterator it = children.begin(); it != children.end(); ++it)
{
const picojson::value& data = it->get("data");
print(data.get("score").get<double>(), data.get("title").get<std::string>(), data.get("url").get<std::string>());
}
}
};
struct rabbit_bench
{
std::string name() const { return "rabbit "; }
void operator()(const std::string& json) const
{
rabbit::document doc;
try { doc.parse(json); } catch (...) { throw; }
rabbit::const_array children = doc["data"]["children"];
for (rabbit::array::const_iterator it = children.begin(); it != children.end(); ++it)
{
rabbit::const_object data = it->at("data");
print(data["score"].as(), data["title"].as(), data["url"].as());
}
}
};
int main(int argc, char** argv)
{
int n = 1000;
if (argc >= 2) n = std::atoi(argv[1]);
std::ifstream ifs("hot.json");
std::istreambuf_iterator<char> it(ifs), last;
std::string json = std::string(it, last);
runner<rapidjson_bench> r1(json);
runner<picojson_bench> r2(json);
runner<rabbit_bench> r3(json);
int i = 1;
while (true)
{
std::cout << i << " trying...";
r1.run(n);
r2.run(n);
r3.run(n);
std::cout << "OK" << std::endl;
r1.disp();
r2.disp();
r3.disp();
std::cout << "---" << std::endl;
++i;
}
}
<commit_msg>change bench order<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <cstdlib>
#include <ctime>
#ifdef __clang__
#pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
#endif
#include <rapidjson/document.h>
#include <picojson.h>
#include <rabbit.hpp>
void print(int score, const std::string& title, const std::string& url)
{
std::cerr << "(" << score << ") " << title << " - " << url << std::endl;
}
template <typename Bench>
struct runner
{
Bench bench;
std::string json;
int score;
int try_count;
runner(const std::string& json)
: json(json)
, score(0)
, try_count(0)
{}
void run(int n)
{
try
{
std::clock_t t = std::clock();
while (n-- > 0)
bench(json);
score += (std::clock() - t);
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
++try_count;
}
void disp() const
{
std::cout << bench.name() << " " << "score: " << (score / try_count) << std::endl;
}
};
struct rapidjson_bench
{
std::string name() const { return "rapidjson"; }
void operator()(const std::string& json) const
{
rapidjson::Document doc;
if (doc.Parse<0>(json.c_str()).HasParseError())
throw std::runtime_error("parse_error");
const rapidjson::Value& children = doc["data"]["children"];
for (rapidjson::Value::ConstValueIterator it = children.Begin(); it != children.End(); ++it)
{
const rapidjson::Value& data = (*it)["data"];
print(data["score"].GetInt(), data["title"].GetString(), data["url"].GetString());
}
}
};
struct rabbit_bench
{
std::string name() const { return "rabbit "; }
void operator()(const std::string& json) const
{
rabbit::document doc;
try { doc.parse(json); } catch (...) { throw; }
rabbit::const_array children = doc["data"]["children"];
for (rabbit::array::const_iterator it = children.begin(); it != children.end(); ++it)
{
rabbit::const_object data = it->at("data");
print(data["score"].as(), data["title"].as(), data["url"].as());
}
}
};
struct picojson_bench
{
std::string name() const { return "picojson "; }
void operator()(const std::string& json) const
{
picojson::value v;
std::string error;
std::string::const_iterator it = json.begin();
picojson::parse(v, it, json.end(), &error);
if (!error.empty())
throw std::runtime_error(error);
const picojson::array& children = v.get("data").get("children").get<picojson::array>();
for (picojson::array::const_iterator it = children.begin(); it != children.end(); ++it)
{
const picojson::value& data = it->get("data");
print(data.get("score").get<double>(), data.get("title").get<std::string>(), data.get("url").get<std::string>());
}
}
};
int main(int argc, char** argv)
{
int n = 1000;
if (argc >= 2) n = std::atoi(argv[1]);
std::ifstream ifs("hot.json");
std::istreambuf_iterator<char> it(ifs), last;
std::string json = std::string(it, last);
runner<rapidjson_bench> r1(json);
runner<rabbit_bench> r2(json);
runner<picojson_bench> r3(json);
int i = 1;
while (true)
{
std::cout << i << " trying...";
r1.run(n);
r2.run(n);
r3.run(n);
std::cout << "OK" << std::endl;
r1.disp();
r2.disp();
r3.disp();
std::cout << "---" << std::endl;
++i;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <thread>
#include <map>
#include <chrono>
#include <ctime>
#include "bench.hpp"
#include "concurrent_counter.hpp"
#include "transactional.hpp"
#include "lock.hpp"
using namespace bench;
long hammerArray(counter::ConcurrentCounter *counter, int nthreads, int nwrites, bool isTx) {
std::thread threads[nthreads];
timer::time_point start_time = timer::now();
// seed prng with time
srand((unsigned)time(nullptr));
sync::ThreadState ts;
spinlock_t ts_lock;
for (int thread_id = 0; thread_id < nthreads; ++thread_id) {
threads[thread_id] = std::thread([thread_id, nwrites, counter, &ts, &ts_lock]() {
int sz = counter->size();
for (int times = 0; times < nwrites; ++times) {
int idx = rand() % sz;
counter->increment(idx);
}
{
//sync::TransactionalScope xact(ts_lock, true);
ts += sync::TransactionalScope::getStats();
//sync::TransactionalScope::printStats();
}
});
}
for (int i = 0; i < nthreads; ++i) {
threads[i].join();
}
timer::time_point end_time = timer::now();
if (isTx) {
sync::TransactionalScope::printStats(ts);
}
return std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count();
}
int main(void) {
std::size_t num_elements = 128;
int nthreads = 8, nwrites = 1000000;
// Initialize all impls for testing
std::map<Impl, counter::ConcurrentCounter*> impls;
impls[NoSync] = new counter::IncorrectConcurrentCounter(num_elements);
impls[Coarse] = new counter::CoarseConcurrentCounter(num_elements);
impls[Fine] = new counter::CoarseConcurrentCounter(num_elements);
impls[RTMAdaptiveCoarse] = new counter::RTMCoarseConcurrentCounter(num_elements);
impls[RTMAdaptiveFine] = new counter::RTMFineConcurrentCounter(num_elements);
impls[RTMNaive] = new counter::RTMConcurrentCounter(num_elements);
// run benchmarks on each array and print output
for (auto& impl : impls) {
bool isRTM = (impl.first >= RTMAdaptiveCoarse) && (impl.first <= RTMAdaptiveFine);
auto run_time = hammerArray(impl.second, nthreads, nwrites, isRTM);
int total_recorded = impl.second->total();
int total_expected = nthreads * nwrites;
// i should really be using the std::chrono time conversions but this code is low priority
auto avg = run_time / (double)total_recorded;
int missing = total_recorded - total_expected;
std::cout << "Implementation: " << ImplStr[impl.first] << std::endl;
std::cout << "Elapsed Time (ms): " << (double)run_time * 0.001 << std::endl;
std::cout << "Avg (ns): " << avg * 1000 << std::endl;
std::cout << "Total = " << total_recorded << "\tExpected = " << total_expected << std::endl;
std::cout << ((total_recorded == total_expected) ?
"All writes were recorded." :
((missing<0) ?
(std::string("There were ") + std::to_string(-missing) + std::string(" missing writes!")) :
(std::string("There were ") + std::to_string(missing) + std::string(" writes that should NOT have occured. This should never happen.")))) << std::endl;
delete impl.second;
}
}
<commit_msg>output CSV<commit_after>#include <iostream>
#include <cstdlib>
#include <thread>
#include <map>
#include <chrono>
#include <ctime>
#include "bench.hpp"
#include "concurrent_counter.hpp"
#include "transactional.hpp"
#include "lock.hpp"
using namespace bench;
long hammerArray(counter::ConcurrentCounter *counter, int nthreads, int nwrites, bool isTx) {
std::thread threads[nthreads];
timer::time_point start_time = timer::now();
// seed prng with time
srand((unsigned)time(nullptr));
sync::ThreadState ts;
spinlock_t ts_lock;
for (int thread_id = 0; thread_id < nthreads; ++thread_id) {
threads[thread_id] = std::thread([thread_id, nwrites, counter, &ts, &ts_lock]() {
int sz = counter->size();
for (int times = 0; times < nwrites; ++times) {
int idx = rand() % sz;
counter->increment(idx);
}
{
//sync::TransactionalScope xact(ts_lock, true);
ts += sync::TransactionalScope::getStats();
//sync::TransactionalScope::printStats();
}
});
}
for (int i = 0; i < nthreads; ++i) {
threads[i].join();
}
timer::time_point end_time = timer::now();
//if (isTx) {
//sync::TransactionalScope::printStats(ts);
//}
return std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count();
}
int main(void) {
std::size_t max_elements = 4096;
int nthreads = 8, nwrites = 1000000;
// Print CSV headers
std::cout << "Implementation,NumElements,TimeMillis,ThroughputWPerSec,AvgNanos" << std::endl;
std::string DELIM(",");
for (std::size_t num_elements = 1; num_elements <= max_elements; num_elements *= 2) {
// Initialize all impls for testing
std::map<Impl, counter::ConcurrentCounter*> impls;
//impls[NoSync] = new counter::IncorrectConcurrentCounter(num_elements);
impls[Coarse] = new counter::CoarseConcurrentCounter(num_elements);
impls[Fine] = new counter::CoarseConcurrentCounter(num_elements);
impls[RTMAdaptiveCoarse] = new counter::RTMCoarseConcurrentCounter(num_elements);
impls[RTMAdaptiveFine] = new counter::RTMFineConcurrentCounter(num_elements);
impls[RTMNaive] = new counter::RTMConcurrentCounter(num_elements);
// run benchmarks on each array and print output
for (auto& impl : impls) {
bool isRTM = (impl.first >= RTMAdaptiveCoarse) && (impl.first <= RTMAdaptiveFine);
auto run_time = hammerArray(impl.second, nthreads, nwrites, isRTM);
int total_recorded = impl.second->total();
int total_expected = nthreads * nwrites;
// i should really be using the std::chrono time conversions but this code is low priority
auto avg = run_time / (double)total_recorded;
int missing = total_recorded - total_expected;
std::cout << ImplStr[impl.first] << DELIM;
std::cout << num_elements << DELIM;
std::cout << (double)run_time * 0.001 << DELIM;
std::cout << avg * 1000 << std::endl;
if (total_recorded != total_expected) {
std::cerr << "ERROR: MISSING WRITES!!!" << std::endl;
}
// std::cout << "Total = " << total_recorded << "\tExpected = " << total_expected << std::endl;
// std::cout << ((total_recorded == total_expected) ?
// "All writes were recorded." :
// ((missing<0) ?
// (std::string("There were ") + std::to_string(-missing) + std::string(" missing writes!")) :
// (std::string("There were ") + std::to_string(missing) + std::string(" writes that should NOT have occured. This should never happen.")))) << std::endl;
delete impl.second;
}
}
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2010 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrBufferAllocPool.h"
#include "GrTypes.h"
#include "GrVertexBuffer.h"
#include "GrIndexBuffer.h"
#include "GrGpu.h"
#if GR_DEBUG
#define VALIDATE validate
#else
static void VALIDATE(bool x = false) {}
#endif
// page size
#define GrBufferAllocPool_MIN_BLOCK_SIZE ((size_t)1 << 12)
GrBufferAllocPool::GrBufferAllocPool(GrGpu* gpu,
BufferType bufferType,
bool frequentResetHint,
size_t blockSize,
int preallocBufferCnt) :
fBlocks(GrMax(8, 2*preallocBufferCnt)) {
GrAssert(NULL != gpu);
fGpu = gpu;
fGpu->ref();
fGpuIsReffed = true;
fBufferType = bufferType;
fFrequentResetHint = frequentResetHint;
fBufferPtr = NULL;
fMinBlockSize = GrMax(GrBufferAllocPool_MIN_BLOCK_SIZE, blockSize);
fBytesInUse = 0;
fPreallocBuffersInUse = 0;
fFirstPreallocBuffer = 0;
for (int i = 0; i < preallocBufferCnt; ++i) {
GrGeometryBuffer* buffer = this->createBuffer(fMinBlockSize);
if (NULL != buffer) {
*fPreallocBuffers.append() = buffer;
buffer->ref();
}
}
}
GrBufferAllocPool::~GrBufferAllocPool() {
VALIDATE();
if (fBlocks.count()) {
GrGeometryBuffer* buffer = fBlocks.back().fBuffer;
if (buffer->isLocked()) {
buffer->unlock();
}
}
while (!fBlocks.empty()) {
destroyBlock();
}
fPreallocBuffers.unrefAll();
releaseGpuRef();
}
void GrBufferAllocPool::releaseGpuRef() {
if (fGpuIsReffed) {
fGpu->unref();
fGpuIsReffed = false;
}
}
void GrBufferAllocPool::reset() {
VALIDATE();
fBytesInUse = 0;
if (fBlocks.count()) {
GrGeometryBuffer* buffer = fBlocks.back().fBuffer;
if (buffer->isLocked()) {
buffer->unlock();
}
}
while (!fBlocks.empty()) {
destroyBlock();
}
if (fPreallocBuffers.count()) {
// must set this after above loop.
fFirstPreallocBuffer = (fFirstPreallocBuffer + fPreallocBuffersInUse) %
fPreallocBuffers.count();
}
fCpuData.reset(fGpu->getCaps().fBufferLockSupport ? 0 : fMinBlockSize);
GrAssert(0 == fPreallocBuffersInUse);
VALIDATE();
}
void GrBufferAllocPool::unlock() {
VALIDATE();
if (NULL != fBufferPtr) {
BufferBlock& block = fBlocks.back();
if (block.fBuffer->isLocked()) {
block.fBuffer->unlock();
} else {
size_t flushSize = block.fBuffer->sizeInBytes() - block.fBytesFree;
flushCpuData(fBlocks.back().fBuffer, flushSize);
}
fBufferPtr = NULL;
}
VALIDATE();
}
#if GR_DEBUG
void GrBufferAllocPool::validate(bool unusedBlockAllowed) const {
if (NULL != fBufferPtr) {
GrAssert(!fBlocks.empty());
if (fBlocks.back().fBuffer->isLocked()) {
GrGeometryBuffer* buf = fBlocks.back().fBuffer;
GrAssert(buf->lockPtr() == fBufferPtr);
} else {
GrAssert(fCpuData.get() == fBufferPtr);
}
} else {
GrAssert(fBlocks.empty() || !fBlocks.back().fBuffer->isLocked());
}
size_t bytesInUse = 0;
for (int i = 0; i < fBlocks.count() - 1; ++i) {
GrAssert(!fBlocks[i].fBuffer->isLocked());
}
for (int i = 0; i < fBlocks.count(); ++i) {
size_t bytes = fBlocks[i].fBuffer->sizeInBytes() - fBlocks[i].fBytesFree;
bytesInUse += bytes;
GrAssert(bytes || unusedBlockAllowed);
}
GrAssert(bytesInUse == fBytesInUse);
if (unusedBlockAllowed) {
GrAssert((fBytesInUse && !fBlocks.empty()) ||
(!fBytesInUse && (fBlocks.count() < 2)));
} else {
GrAssert((0 == fBytesInUse) == fBlocks.empty());
}
}
#endif
void* GrBufferAllocPool::makeSpace(size_t size,
size_t alignment,
const GrGeometryBuffer** buffer,
size_t* offset) {
VALIDATE();
GrAssert(NULL != buffer);
GrAssert(NULL != offset);
if (NULL != fBufferPtr) {
BufferBlock& back = fBlocks.back();
size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree;
size_t pad = GrSizeAlignUpPad(usedBytes,
alignment);
if ((size + pad) <= back.fBytesFree) {
usedBytes += pad;
*offset = usedBytes;
*buffer = back.fBuffer;
back.fBytesFree -= size + pad;
fBytesInUse += size;
return (void*)(reinterpret_cast<intptr_t>(fBufferPtr) + usedBytes);
}
}
// We could honor the space request using by a partial update of the current
// VB (if there is room). But we don't currently use draw calls to GL that
// allow the driver to know that previously issued draws won't read from
// the part of the buffer we update. Also, the GL buffer implementation
// may be cheating on the actual buffer size by shrinking the buffer on
// updateData() if the amount of data passed is less than the full buffer
// size.
if (!createBlock(size)) {
return NULL;
}
GrAssert(NULL != fBufferPtr);
*offset = 0;
BufferBlock& back = fBlocks.back();
*buffer = back.fBuffer;
back.fBytesFree -= size;
fBytesInUse += size;
VALIDATE();
return fBufferPtr;
}
int GrBufferAllocPool::currentBufferItems(size_t itemSize) const {
VALIDATE();
if (NULL != fBufferPtr) {
const BufferBlock& back = fBlocks.back();
size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree;
size_t pad = GrSizeAlignUpPad(usedBytes, itemSize);
return (back.fBytesFree - pad) / itemSize;
} else if (fPreallocBuffersInUse < fPreallocBuffers.count()) {
return fMinBlockSize / itemSize;
}
return 0;
}
int GrBufferAllocPool::preallocatedBuffersRemaining() const {
return fPreallocBuffers.count() - fPreallocBuffersInUse;
}
int GrBufferAllocPool::preallocatedBufferCount() const {
return fPreallocBuffers.count();
}
void GrBufferAllocPool::putBack(size_t bytes) {
VALIDATE();
while (bytes) {
// caller shouldnt try to put back more than they've taken
GrAssert(!fBlocks.empty());
BufferBlock& block = fBlocks.back();
size_t bytesUsed = block.fBuffer->sizeInBytes() - block.fBytesFree;
if (bytes >= bytesUsed) {
bytes -= bytesUsed;
fBytesInUse -= bytesUsed;
// if we locked a vb to satisfy the make space and we're releasing
// beyond it, then unlock it.
if (block.fBuffer->isLocked()) {
block.fBuffer->unlock();
}
this->destroyBlock();
} else {
block.fBytesFree += bytes;
fBytesInUse -= bytes;
bytes = 0;
break;
}
}
VALIDATE();
}
bool GrBufferAllocPool::createBlock(size_t requestSize) {
size_t size = GrMax(requestSize, fMinBlockSize);
GrAssert(size >= GrBufferAllocPool_MIN_BLOCK_SIZE);
VALIDATE();
BufferBlock& block = fBlocks.push_back();
if (size == fMinBlockSize &&
fPreallocBuffersInUse < fPreallocBuffers.count()) {
uint32_t nextBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer) %
fPreallocBuffers.count();
block.fBuffer = fPreallocBuffers[nextBuffer];
block.fBuffer->ref();
++fPreallocBuffersInUse;
} else {
block.fBuffer = this->createBuffer(size);
if (NULL == block.fBuffer) {
fBlocks.pop_back();
return false;
}
}
block.fBytesFree = size;
if (NULL != fBufferPtr) {
GrAssert(fBlocks.count() > 1);
BufferBlock& prev = fBlocks.fromBack(1);
if (prev.fBuffer->isLocked()) {
prev.fBuffer->unlock();
} else {
flushCpuData(prev.fBuffer,
prev.fBuffer->sizeInBytes() - prev.fBytesFree);
}
fBufferPtr = NULL;
}
GrAssert(NULL == fBufferPtr);
if (fGpu->getCaps().fBufferLockSupport &&
size > GR_GEOM_BUFFER_LOCK_THRESHOLD &&
(!fFrequentResetHint || requestSize > GR_GEOM_BUFFER_LOCK_THRESHOLD)) {
fBufferPtr = block.fBuffer->lock();
}
if (NULL == fBufferPtr) {
fBufferPtr = fCpuData.reset(size);
}
VALIDATE(true);
return true;
}
void GrBufferAllocPool::destroyBlock() {
GrAssert(!fBlocks.empty());
BufferBlock& block = fBlocks.back();
if (fPreallocBuffersInUse > 0) {
uint32_t prevPreallocBuffer = (fPreallocBuffersInUse +
fFirstPreallocBuffer +
(fPreallocBuffers.count() - 1)) %
fPreallocBuffers.count();
if (block.fBuffer == fPreallocBuffers[prevPreallocBuffer]) {
--fPreallocBuffersInUse;
}
}
GrAssert(!block.fBuffer->isLocked());
block.fBuffer->unref();
fBlocks.pop_back();
fBufferPtr = NULL;
}
void GrBufferAllocPool::flushCpuData(GrGeometryBuffer* buffer,
size_t flushSize) {
GrAssert(NULL != buffer);
GrAssert(!buffer->isLocked());
GrAssert(fCpuData.get() == fBufferPtr);
GrAssert(flushSize <= buffer->sizeInBytes());
if (fGpu->getCaps().fBufferLockSupport &&
flushSize > GR_GEOM_BUFFER_LOCK_THRESHOLD) {
void* data = buffer->lock();
if (NULL != data) {
memcpy(data, fBufferPtr, flushSize);
buffer->unlock();
return;
}
}
buffer->updateData(fBufferPtr, flushSize);
}
GrGeometryBuffer* GrBufferAllocPool::createBuffer(size_t size) {
if (kIndex_BufferType == fBufferType) {
return fGpu->createIndexBuffer(size, true);
} else {
GrAssert(kVertex_BufferType == fBufferType);
return fGpu->createVertexBuffer(size, true);
}
}
////////////////////////////////////////////////////////////////////////////////
GrVertexBufferAllocPool::GrVertexBufferAllocPool(GrGpu* gpu,
bool frequentResetHint,
size_t bufferSize,
int preallocBufferCnt)
: GrBufferAllocPool(gpu,
kVertex_BufferType,
frequentResetHint,
bufferSize,
preallocBufferCnt) {
}
void* GrVertexBufferAllocPool::makeSpace(GrVertexLayout layout,
int vertexCount,
const GrVertexBuffer** buffer,
int* startVertex) {
GrAssert(vertexCount >= 0);
GrAssert(NULL != buffer);
GrAssert(NULL != startVertex);
size_t vSize = GrDrawTarget::VertexSize(layout);
size_t offset = 0; // assign to suppress warning
const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning
void* ptr = INHERITED::makeSpace(vSize * vertexCount,
vSize,
&geomBuffer,
&offset);
*buffer = (const GrVertexBuffer*) geomBuffer;
GrAssert(0 == offset % vSize);
*startVertex = offset / vSize;
return ptr;
}
bool GrVertexBufferAllocPool::appendVertices(GrVertexLayout layout,
int vertexCount,
const void* vertices,
const GrVertexBuffer** buffer,
int* startVertex) {
void* space = makeSpace(layout, vertexCount, buffer, startVertex);
if (NULL != space) {
memcpy(space,
vertices,
GrDrawTarget::VertexSize(layout) * vertexCount);
return true;
} else {
return false;
}
}
int GrVertexBufferAllocPool::preallocatedBufferVertices(GrVertexLayout layout) const {
return INHERITED::preallocatedBufferSize() /
GrDrawTarget::VertexSize(layout);
}
int GrVertexBufferAllocPool::currentBufferVertices(GrVertexLayout layout) const {
return currentBufferItems(GrDrawTarget::VertexSize(layout));
}
////////////////////////////////////////////////////////////////////////////////
GrIndexBufferAllocPool::GrIndexBufferAllocPool(GrGpu* gpu,
bool frequentResetHint,
size_t bufferSize,
int preallocBufferCnt)
: GrBufferAllocPool(gpu,
kIndex_BufferType,
frequentResetHint,
bufferSize,
preallocBufferCnt) {
}
void* GrIndexBufferAllocPool::makeSpace(int indexCount,
const GrIndexBuffer** buffer,
int* startIndex) {
GrAssert(indexCount >= 0);
GrAssert(NULL != buffer);
GrAssert(NULL != startIndex);
size_t offset = 0; // assign to suppress warning
const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning
void* ptr = INHERITED::makeSpace(indexCount * sizeof(uint16_t),
sizeof(uint16_t),
&geomBuffer,
&offset);
*buffer = (const GrIndexBuffer*) geomBuffer;
GrAssert(0 == offset % sizeof(uint16_t));
*startIndex = offset / sizeof(uint16_t);
return ptr;
}
bool GrIndexBufferAllocPool::appendIndices(int indexCount,
const void* indices,
const GrIndexBuffer** buffer,
int* startIndex) {
void* space = makeSpace(indexCount, buffer, startIndex);
if (NULL != space) {
memcpy(space, indices, sizeof(uint16_t) * indexCount);
return true;
} else {
return false;
}
}
int GrIndexBufferAllocPool::preallocatedBufferIndices() const {
return INHERITED::preallocatedBufferSize() / sizeof(uint16_t);
}
int GrIndexBufferAllocPool::currentBufferIndices() const {
return currentBufferItems(sizeof(uint16_t));
}
<commit_msg><commit_after>
/*
* Copyright 2010 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrBufferAllocPool.h"
#include "GrTypes.h"
#include "GrVertexBuffer.h"
#include "GrIndexBuffer.h"
#include "GrGpu.h"
#if GR_DEBUG
#define VALIDATE validate
#else
static void VALIDATE(bool x = false) {}
#endif
// page size
#define GrBufferAllocPool_MIN_BLOCK_SIZE ((size_t)1 << 12)
GrBufferAllocPool::GrBufferAllocPool(GrGpu* gpu,
BufferType bufferType,
bool frequentResetHint,
size_t blockSize,
int preallocBufferCnt) :
fBlocks(GrMax(8, 2*preallocBufferCnt)) {
GrAssert(NULL != gpu);
fGpu = gpu;
fGpu->ref();
fGpuIsReffed = true;
fBufferType = bufferType;
fFrequentResetHint = frequentResetHint;
fBufferPtr = NULL;
fMinBlockSize = GrMax(GrBufferAllocPool_MIN_BLOCK_SIZE, blockSize);
fBytesInUse = 0;
fPreallocBuffersInUse = 0;
fFirstPreallocBuffer = 0;
for (int i = 0; i < preallocBufferCnt; ++i) {
GrGeometryBuffer* buffer = this->createBuffer(fMinBlockSize);
if (NULL != buffer) {
*fPreallocBuffers.append() = buffer;
buffer->ref();
}
}
}
GrBufferAllocPool::~GrBufferAllocPool() {
VALIDATE();
if (fBlocks.count()) {
GrGeometryBuffer* buffer = fBlocks.back().fBuffer;
if (buffer->isLocked()) {
buffer->unlock();
}
}
while (!fBlocks.empty()) {
destroyBlock();
}
fPreallocBuffers.unrefAll();
releaseGpuRef();
}
void GrBufferAllocPool::releaseGpuRef() {
if (fGpuIsReffed) {
fGpu->unref();
fGpuIsReffed = false;
}
}
void GrBufferAllocPool::reset() {
VALIDATE();
fBytesInUse = 0;
if (fBlocks.count()) {
GrGeometryBuffer* buffer = fBlocks.back().fBuffer;
if (buffer->isLocked()) {
buffer->unlock();
}
}
while (!fBlocks.empty()) {
destroyBlock();
}
if (fPreallocBuffers.count()) {
// must set this after above loop.
fFirstPreallocBuffer = (fFirstPreallocBuffer + fPreallocBuffersInUse) %
fPreallocBuffers.count();
}
// we may have created a large cpu mirror of a large VB. Reset the size
// to match our pre-allocated VBs.
fCpuData.reset(fMinBlockSize);
GrAssert(0 == fPreallocBuffersInUse);
VALIDATE();
}
void GrBufferAllocPool::unlock() {
VALIDATE();
if (NULL != fBufferPtr) {
BufferBlock& block = fBlocks.back();
if (block.fBuffer->isLocked()) {
block.fBuffer->unlock();
} else {
size_t flushSize = block.fBuffer->sizeInBytes() - block.fBytesFree;
flushCpuData(fBlocks.back().fBuffer, flushSize);
}
fBufferPtr = NULL;
}
VALIDATE();
}
#if GR_DEBUG
void GrBufferAllocPool::validate(bool unusedBlockAllowed) const {
if (NULL != fBufferPtr) {
GrAssert(!fBlocks.empty());
if (fBlocks.back().fBuffer->isLocked()) {
GrGeometryBuffer* buf = fBlocks.back().fBuffer;
GrAssert(buf->lockPtr() == fBufferPtr);
} else {
GrAssert(fCpuData.get() == fBufferPtr);
}
} else {
GrAssert(fBlocks.empty() || !fBlocks.back().fBuffer->isLocked());
}
size_t bytesInUse = 0;
for (int i = 0; i < fBlocks.count() - 1; ++i) {
GrAssert(!fBlocks[i].fBuffer->isLocked());
}
for (int i = 0; i < fBlocks.count(); ++i) {
size_t bytes = fBlocks[i].fBuffer->sizeInBytes() - fBlocks[i].fBytesFree;
bytesInUse += bytes;
GrAssert(bytes || unusedBlockAllowed);
}
GrAssert(bytesInUse == fBytesInUse);
if (unusedBlockAllowed) {
GrAssert((fBytesInUse && !fBlocks.empty()) ||
(!fBytesInUse && (fBlocks.count() < 2)));
} else {
GrAssert((0 == fBytesInUse) == fBlocks.empty());
}
}
#endif
void* GrBufferAllocPool::makeSpace(size_t size,
size_t alignment,
const GrGeometryBuffer** buffer,
size_t* offset) {
VALIDATE();
GrAssert(NULL != buffer);
GrAssert(NULL != offset);
if (NULL != fBufferPtr) {
BufferBlock& back = fBlocks.back();
size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree;
size_t pad = GrSizeAlignUpPad(usedBytes,
alignment);
if ((size + pad) <= back.fBytesFree) {
usedBytes += pad;
*offset = usedBytes;
*buffer = back.fBuffer;
back.fBytesFree -= size + pad;
fBytesInUse += size;
return (void*)(reinterpret_cast<intptr_t>(fBufferPtr) + usedBytes);
}
}
// We could honor the space request using by a partial update of the current
// VB (if there is room). But we don't currently use draw calls to GL that
// allow the driver to know that previously issued draws won't read from
// the part of the buffer we update. Also, the GL buffer implementation
// may be cheating on the actual buffer size by shrinking the buffer on
// updateData() if the amount of data passed is less than the full buffer
// size.
if (!createBlock(size)) {
return NULL;
}
GrAssert(NULL != fBufferPtr);
*offset = 0;
BufferBlock& back = fBlocks.back();
*buffer = back.fBuffer;
back.fBytesFree -= size;
fBytesInUse += size;
VALIDATE();
return fBufferPtr;
}
int GrBufferAllocPool::currentBufferItems(size_t itemSize) const {
VALIDATE();
if (NULL != fBufferPtr) {
const BufferBlock& back = fBlocks.back();
size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree;
size_t pad = GrSizeAlignUpPad(usedBytes, itemSize);
return (back.fBytesFree - pad) / itemSize;
} else if (fPreallocBuffersInUse < fPreallocBuffers.count()) {
return fMinBlockSize / itemSize;
}
return 0;
}
int GrBufferAllocPool::preallocatedBuffersRemaining() const {
return fPreallocBuffers.count() - fPreallocBuffersInUse;
}
int GrBufferAllocPool::preallocatedBufferCount() const {
return fPreallocBuffers.count();
}
void GrBufferAllocPool::putBack(size_t bytes) {
VALIDATE();
while (bytes) {
// caller shouldnt try to put back more than they've taken
GrAssert(!fBlocks.empty());
BufferBlock& block = fBlocks.back();
size_t bytesUsed = block.fBuffer->sizeInBytes() - block.fBytesFree;
if (bytes >= bytesUsed) {
bytes -= bytesUsed;
fBytesInUse -= bytesUsed;
// if we locked a vb to satisfy the make space and we're releasing
// beyond it, then unlock it.
if (block.fBuffer->isLocked()) {
block.fBuffer->unlock();
}
this->destroyBlock();
} else {
block.fBytesFree += bytes;
fBytesInUse -= bytes;
bytes = 0;
break;
}
}
VALIDATE();
}
bool GrBufferAllocPool::createBlock(size_t requestSize) {
size_t size = GrMax(requestSize, fMinBlockSize);
GrAssert(size >= GrBufferAllocPool_MIN_BLOCK_SIZE);
VALIDATE();
BufferBlock& block = fBlocks.push_back();
if (size == fMinBlockSize &&
fPreallocBuffersInUse < fPreallocBuffers.count()) {
uint32_t nextBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer) %
fPreallocBuffers.count();
block.fBuffer = fPreallocBuffers[nextBuffer];
block.fBuffer->ref();
++fPreallocBuffersInUse;
} else {
block.fBuffer = this->createBuffer(size);
if (NULL == block.fBuffer) {
fBlocks.pop_back();
return false;
}
}
block.fBytesFree = size;
if (NULL != fBufferPtr) {
GrAssert(fBlocks.count() > 1);
BufferBlock& prev = fBlocks.fromBack(1);
if (prev.fBuffer->isLocked()) {
prev.fBuffer->unlock();
} else {
flushCpuData(prev.fBuffer,
prev.fBuffer->sizeInBytes() - prev.fBytesFree);
}
fBufferPtr = NULL;
}
GrAssert(NULL == fBufferPtr);
if (fGpu->getCaps().fBufferLockSupport &&
size > GR_GEOM_BUFFER_LOCK_THRESHOLD &&
(!fFrequentResetHint || requestSize > GR_GEOM_BUFFER_LOCK_THRESHOLD)) {
fBufferPtr = block.fBuffer->lock();
}
if (NULL == fBufferPtr) {
fBufferPtr = fCpuData.reset(size);
}
VALIDATE(true);
return true;
}
void GrBufferAllocPool::destroyBlock() {
GrAssert(!fBlocks.empty());
BufferBlock& block = fBlocks.back();
if (fPreallocBuffersInUse > 0) {
uint32_t prevPreallocBuffer = (fPreallocBuffersInUse +
fFirstPreallocBuffer +
(fPreallocBuffers.count() - 1)) %
fPreallocBuffers.count();
if (block.fBuffer == fPreallocBuffers[prevPreallocBuffer]) {
--fPreallocBuffersInUse;
}
}
GrAssert(!block.fBuffer->isLocked());
block.fBuffer->unref();
fBlocks.pop_back();
fBufferPtr = NULL;
}
void GrBufferAllocPool::flushCpuData(GrGeometryBuffer* buffer,
size_t flushSize) {
GrAssert(NULL != buffer);
GrAssert(!buffer->isLocked());
GrAssert(fCpuData.get() == fBufferPtr);
GrAssert(flushSize <= buffer->sizeInBytes());
if (fGpu->getCaps().fBufferLockSupport &&
flushSize > GR_GEOM_BUFFER_LOCK_THRESHOLD) {
void* data = buffer->lock();
if (NULL != data) {
memcpy(data, fBufferPtr, flushSize);
buffer->unlock();
return;
}
}
buffer->updateData(fBufferPtr, flushSize);
}
GrGeometryBuffer* GrBufferAllocPool::createBuffer(size_t size) {
if (kIndex_BufferType == fBufferType) {
return fGpu->createIndexBuffer(size, true);
} else {
GrAssert(kVertex_BufferType == fBufferType);
return fGpu->createVertexBuffer(size, true);
}
}
////////////////////////////////////////////////////////////////////////////////
GrVertexBufferAllocPool::GrVertexBufferAllocPool(GrGpu* gpu,
bool frequentResetHint,
size_t bufferSize,
int preallocBufferCnt)
: GrBufferAllocPool(gpu,
kVertex_BufferType,
frequentResetHint,
bufferSize,
preallocBufferCnt) {
}
void* GrVertexBufferAllocPool::makeSpace(GrVertexLayout layout,
int vertexCount,
const GrVertexBuffer** buffer,
int* startVertex) {
GrAssert(vertexCount >= 0);
GrAssert(NULL != buffer);
GrAssert(NULL != startVertex);
size_t vSize = GrDrawTarget::VertexSize(layout);
size_t offset = 0; // assign to suppress warning
const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning
void* ptr = INHERITED::makeSpace(vSize * vertexCount,
vSize,
&geomBuffer,
&offset);
*buffer = (const GrVertexBuffer*) geomBuffer;
GrAssert(0 == offset % vSize);
*startVertex = offset / vSize;
return ptr;
}
bool GrVertexBufferAllocPool::appendVertices(GrVertexLayout layout,
int vertexCount,
const void* vertices,
const GrVertexBuffer** buffer,
int* startVertex) {
void* space = makeSpace(layout, vertexCount, buffer, startVertex);
if (NULL != space) {
memcpy(space,
vertices,
GrDrawTarget::VertexSize(layout) * vertexCount);
return true;
} else {
return false;
}
}
int GrVertexBufferAllocPool::preallocatedBufferVertices(GrVertexLayout layout) const {
return INHERITED::preallocatedBufferSize() /
GrDrawTarget::VertexSize(layout);
}
int GrVertexBufferAllocPool::currentBufferVertices(GrVertexLayout layout) const {
return currentBufferItems(GrDrawTarget::VertexSize(layout));
}
////////////////////////////////////////////////////////////////////////////////
GrIndexBufferAllocPool::GrIndexBufferAllocPool(GrGpu* gpu,
bool frequentResetHint,
size_t bufferSize,
int preallocBufferCnt)
: GrBufferAllocPool(gpu,
kIndex_BufferType,
frequentResetHint,
bufferSize,
preallocBufferCnt) {
}
void* GrIndexBufferAllocPool::makeSpace(int indexCount,
const GrIndexBuffer** buffer,
int* startIndex) {
GrAssert(indexCount >= 0);
GrAssert(NULL != buffer);
GrAssert(NULL != startIndex);
size_t offset = 0; // assign to suppress warning
const GrGeometryBuffer* geomBuffer = NULL; // assign to suppress warning
void* ptr = INHERITED::makeSpace(indexCount * sizeof(uint16_t),
sizeof(uint16_t),
&geomBuffer,
&offset);
*buffer = (const GrIndexBuffer*) geomBuffer;
GrAssert(0 == offset % sizeof(uint16_t));
*startIndex = offset / sizeof(uint16_t);
return ptr;
}
bool GrIndexBufferAllocPool::appendIndices(int indexCount,
const void* indices,
const GrIndexBuffer** buffer,
int* startIndex) {
void* space = makeSpace(indexCount, buffer, startIndex);
if (NULL != space) {
memcpy(space, indices, sizeof(uint16_t) * indexCount);
return true;
} else {
return false;
}
}
int GrIndexBufferAllocPool::preallocatedBufferIndices() const {
return INHERITED::preallocatedBufferSize() / sizeof(uint16_t);
}
int GrIndexBufferAllocPool::currentBufferIndices() const {
return currentBufferItems(sizeof(uint16_t));
}
<|endoftext|> |
<commit_before><commit_msg>Fixed performance issues when falling back to raster for sub-pixmaps.<commit_after><|endoftext|> |
<commit_before>// This program converts a set of images to a lmdb/leveldb by storing them
// as Datum proto buffers.
// Usage:
// convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME
//
// where ROOTFOLDER is the root folder that holds all the images, and LISTFILE
// should be a list of files as well as their labels, in the format as
// subfolder1/file1.JPEG 7
// ....
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <utility>
#include <vector>
#include "boost/scoped_ptr.hpp"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/db.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/rng.hpp"
using namespace caffe; // NOLINT(build/namespaces)
using std::pair;
using boost::scoped_ptr;
DEFINE_bool(gray, false,
"When this option is on, treat images as grayscale ones");
DEFINE_bool(shuffle, false,
"Randomly shuffle the order of images and their labels");
DEFINE_string(backend, "lmdb",
"The backend {lmdb, leveldb} for storing the result");
DEFINE_int32(resize_width, 0, "Width images are resized to");
DEFINE_int32(resize_height, 0, "Height images are resized to");
DEFINE_bool(check_size, false,
"When this option is on, check that all the datum have the same size");
DEFINE_bool(encoded, false,
"When this option is on, the encoded image will be save in datum");
DEFINE_string(encode_type, "",
"Optional: What type should we encode the image as ('png','jpg',...).");
int main(int argc, char** argv) {
::google::InitGoogleLogging(argv[0]);
#ifndef GFLAGS_GFLAGS_H_
namespace gflags = google;
#endif
gflags::SetUsageMessage("Convert a set of images to the leveldb/lmdb\n"
"format used as input for Caffe.\n"
"Usage:\n"
" convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n"
"The ImageNet dataset for the training demo is at\n"
" http://www.image-net.org/download-images\n");
gflags::ParseCommandLineFlags(&argc, &argv, true);
if (argc < 4) {
gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset");
return 1;
}
const bool is_color = !FLAGS_gray;
const bool check_size = FLAGS_check_size;
const bool encoded = FLAGS_encoded;
const string encode_type = FLAGS_encode_type;
std::ifstream infile(argv[2]);
std::vector<std::pair<std::string, int> > lines;
std::string filename;
int label;
while (infile >> filename >> label) {
lines.push_back(std::make_pair(filename, label));
}
if (FLAGS_shuffle) {
// randomly shuffle data
LOG(INFO) << "Shuffling data";
shuffle(lines.begin(), lines.end());
}
LOG(INFO) << "A total of " << lines.size() << " images.";
if (encode_type.size() && !encoded)
LOG(INFO) << "encode_type specified, assuming encoded=true.";
int resize_height = std::max<int>(0, FLAGS_resize_height);
int resize_width = std::max<int>(0, FLAGS_resize_width);
// Create new DB
scoped_ptr<db::DB> db(db::GetDB(FLAGS_backend));
db->Open(argv[3], db::NEW);
scoped_ptr<db::Transaction> txn(db->NewTransaction());
// Storing to db
std::string root_folder(argv[1]);
Datum datum;
int count = 0;
const int kMaxKeyLength = 256;
char key_cstr[kMaxKeyLength];
int data_size = 0;
bool data_size_initialized = false;
for (int line_id = 0; line_id < lines.size(); ++line_id) {
bool status;
std::string enc = encode_type;
if (encoded && !enc.size()) {
// Guess the encoding type from the file name
string fn = lines[line_id].first;
size_t p = fn.rfind('.');
if ( p == fn.npos )
LOG(WARNING) << "Failed to guess the encoding of '" << fn << "'";
enc = fn.substr(p);
std::transform(enc.begin(), enc.end(), enc.begin(), ::tolower);
}
status = ReadImageToDatum(root_folder + lines[line_id].first,
lines[line_id].second, resize_height, resize_width, is_color,
enc, &datum);
if (status == false) continue;
if (check_size) {
if (!data_size_initialized) {
data_size = datum.channels() * datum.height() * datum.width();
data_size_initialized = true;
} else {
const std::string& data = datum.data();
CHECK_EQ(data.size(), data_size) << "Incorrect data field size "
<< data.size();
}
}
// sequential
int length = snprintf(key_cstr, kMaxKeyLength, "%08d_%s", line_id,
lines[line_id].first.c_str());
// Put in db
string out;
CHECK(datum.SerializeToString(&out));
txn->Put(string(key_cstr, length), out);
if (++count % 1000 == 0) {
// Commit db
txn->Commit();
txn.reset(db->NewTransaction());
LOG(ERROR) << "Processed " << count << " files.";
}
}
// write the last batch
if (count % 1000 != 0) {
txn->Commit();
LOG(ERROR) << "Processed " << count << " files.";
}
return 0;
}
<commit_msg>Show output from convert_imageset tool<commit_after>// This program converts a set of images to a lmdb/leveldb by storing them
// as Datum proto buffers.
// Usage:
// convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME
//
// where ROOTFOLDER is the root folder that holds all the images, and LISTFILE
// should be a list of files as well as their labels, in the format as
// subfolder1/file1.JPEG 7
// ....
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <utility>
#include <vector>
#include "boost/scoped_ptr.hpp"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/db.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/rng.hpp"
using namespace caffe; // NOLINT(build/namespaces)
using std::pair;
using boost::scoped_ptr;
DEFINE_bool(gray, false,
"When this option is on, treat images as grayscale ones");
DEFINE_bool(shuffle, false,
"Randomly shuffle the order of images and their labels");
DEFINE_string(backend, "lmdb",
"The backend {lmdb, leveldb} for storing the result");
DEFINE_int32(resize_width, 0, "Width images are resized to");
DEFINE_int32(resize_height, 0, "Height images are resized to");
DEFINE_bool(check_size, false,
"When this option is on, check that all the datum have the same size");
DEFINE_bool(encoded, false,
"When this option is on, the encoded image will be save in datum");
DEFINE_string(encode_type, "",
"Optional: What type should we encode the image as ('png','jpg',...).");
int main(int argc, char** argv) {
::google::InitGoogleLogging(argv[0]);
// Print output to stderr (while still logging)
FLAGS_alsologtostderr = 1;
#ifndef GFLAGS_GFLAGS_H_
namespace gflags = google;
#endif
gflags::SetUsageMessage("Convert a set of images to the leveldb/lmdb\n"
"format used as input for Caffe.\n"
"Usage:\n"
" convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n"
"The ImageNet dataset for the training demo is at\n"
" http://www.image-net.org/download-images\n");
gflags::ParseCommandLineFlags(&argc, &argv, true);
if (argc < 4) {
gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset");
return 1;
}
const bool is_color = !FLAGS_gray;
const bool check_size = FLAGS_check_size;
const bool encoded = FLAGS_encoded;
const string encode_type = FLAGS_encode_type;
std::ifstream infile(argv[2]);
std::vector<std::pair<std::string, int> > lines;
std::string filename;
int label;
while (infile >> filename >> label) {
lines.push_back(std::make_pair(filename, label));
}
if (FLAGS_shuffle) {
// randomly shuffle data
LOG(INFO) << "Shuffling data";
shuffle(lines.begin(), lines.end());
}
LOG(INFO) << "A total of " << lines.size() << " images.";
if (encode_type.size() && !encoded)
LOG(INFO) << "encode_type specified, assuming encoded=true.";
int resize_height = std::max<int>(0, FLAGS_resize_height);
int resize_width = std::max<int>(0, FLAGS_resize_width);
// Create new DB
scoped_ptr<db::DB> db(db::GetDB(FLAGS_backend));
db->Open(argv[3], db::NEW);
scoped_ptr<db::Transaction> txn(db->NewTransaction());
// Storing to db
std::string root_folder(argv[1]);
Datum datum;
int count = 0;
const int kMaxKeyLength = 256;
char key_cstr[kMaxKeyLength];
int data_size = 0;
bool data_size_initialized = false;
for (int line_id = 0; line_id < lines.size(); ++line_id) {
bool status;
std::string enc = encode_type;
if (encoded && !enc.size()) {
// Guess the encoding type from the file name
string fn = lines[line_id].first;
size_t p = fn.rfind('.');
if ( p == fn.npos )
LOG(WARNING) << "Failed to guess the encoding of '" << fn << "'";
enc = fn.substr(p);
std::transform(enc.begin(), enc.end(), enc.begin(), ::tolower);
}
status = ReadImageToDatum(root_folder + lines[line_id].first,
lines[line_id].second, resize_height, resize_width, is_color,
enc, &datum);
if (status == false) continue;
if (check_size) {
if (!data_size_initialized) {
data_size = datum.channels() * datum.height() * datum.width();
data_size_initialized = true;
} else {
const std::string& data = datum.data();
CHECK_EQ(data.size(), data_size) << "Incorrect data field size "
<< data.size();
}
}
// sequential
int length = snprintf(key_cstr, kMaxKeyLength, "%08d_%s", line_id,
lines[line_id].first.c_str());
// Put in db
string out;
CHECK(datum.SerializeToString(&out));
txn->Put(string(key_cstr, length), out);
if (++count % 1000 == 0) {
// Commit db
txn->Commit();
txn.reset(db->NewTransaction());
LOG(INFO) << "Processed " << count << " files.";
}
}
// write the last batch
if (count % 1000 != 0) {
txn->Commit();
LOG(INFO) << "Processed " << count << " files.";
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resmgr.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 20:16:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TOOLS_RESMGR_HXX
#define _TOOLS_RESMGR_HXX
#ifndef INCLUDED_TOOLSDLLAPI_H
#include "tools/toolsdllapi.h"
#endif
#ifndef INCLUDED_I18NPOOL_LANG_H
#include <i18npool/lang.h>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _REF_HXX
#include <tools/ref.hxx>
#endif
#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#define CREATEVERSIONRESMGR_NAME( Name ) #Name MAKE_NUMSTR( SUPD )
#define CREATEVERSIONRESMGR( Name ) ResMgr::CreateResMgr( CREATEVERSIONRESMGR_NAME( Name ) )
#define LOCALE_MAX_FALLBACK 6
#include <vector>
class SvStream;
class InternalResMgr;
// -----------------
// - RSHEADER_TYPE -
// -----------------
// Definition der Struktur, aus denen die Resource aufgebaut ist
struct RSHEADER_TYPE
{
private:
sal_uInt32 nId; // Identifier der Resource
RESOURCE_TYPE nRT; // Resource Typ
sal_uInt32 nGlobOff; // Globaler Offset
sal_uInt32 nLocalOff; // Lokaler Offset
public:
inline sal_uInt32 GetId(); // Identifier der Resource
inline RESOURCE_TYPE GetRT(); // Resource Typ
inline sal_uInt32 GetGlobOff(); // Globaler Offset
inline sal_uInt32 GetLocalOff(); // Lokaler Offset
};
// ----------
// - ResMgr -
// ----------
typedef void (*ResHookProc)( UniString& rStr );
// ----------
// - ResMgr -
// ----------
// Initialisierung
#define RC_NOTYPE 0x00
// Globale Resource
#define RC_GLOBAL 0x01
#define RC_AUTORELEASE 0x02
#define RC_NOTFOUND 0x04
#define RC_FALLBACK_DOWN 0x08
#define RC_FALLBACK_UP 0x10
class Resource;
class ResMgr;
struct ImpRCStack
{
// pResource and pClassRes equal NULL: resource was not loaded
RSHEADER_TYPE * pResource; // pointer to resource
void * pClassRes; // pointer to class specified init data
short Flags; // resource status
void * aResHandle; // Resource-Identifier from InternalResMgr
const Resource* pResObj; // pointer to Resource object
sal_uInt32 nId; // ResId used for error message
ResMgr* pResMgr; // ResMgr for Resource pResObj
void Clear();
void Init( ResMgr * pMgr, const Resource * pObj, sal_uInt32 nId );
};
class TOOLS_DLLPUBLIC ResMgr
{
private:
InternalResMgr* pImpRes;
std::vector< ImpRCStack > aStack; // resource context stack
int nCurStack;
ResMgr* pFallbackResMgr; // fallback ResMgr in case the Resource
// was not contained in this ResMgr
ResMgr* pOriginalResMgr; // the res mgr that fell back to this
// stack level
TOOLS_DLLPRIVATE void incStack();
TOOLS_DLLPRIVATE void decStack();
TOOLS_DLLPRIVATE const ImpRCStack * StackTop( sal_uInt32 nOff = 0 ) const
{
return (((int)nOff >= nCurStack) ? NULL : &aStack[nCurStack-nOff]);
}
TOOLS_DLLPRIVATE void Init( const rtl::OUString& rFileName );
TOOLS_DLLPRIVATE ResMgr( InternalResMgr * pImp );
#ifdef DBG_UTIL
TOOLS_DLLPRIVATE static void RscError_Impl( const sal_Char* pMessage, ResMgr* pResMgr,
RESOURCE_TYPE nRT, sal_uInt32 nId,
std::vector< ImpRCStack >& rResStack, int nDepth );
#endif
// called from within GetResource() if a resource could not be found
TOOLS_DLLPRIVATE ResMgr* CreateFallbackResMgr( const ResId& rId, const Resource* pResource );
// creates a 1k sized buffer set to zero for unfound resources
// used in case RC_NOTFOUND
static void* pEmptyBuffer;
TOOLS_DLLPRIVATE static void* getEmptyBuffer();
// the next two methods are needed to prevent the string hook called
// with the res mgr mutex locked
// like GetString, but doesn't call the string hook
TOOLS_DLLPRIVATE static sal_uInt32 GetStringWithoutHook( UniString& rStr, const BYTE* pStr );
// like ReadString but doesn't call the string hook
TOOLS_DLLPRIVATE UniString ReadStringWithoutHook();
public:
static void DestroyAllResMgr(); // Wird gerufen, wenn App beendet wird
~ResMgr();
// Sprachabhaengige Ressource Library
static const sal_Char* GetLang( LanguageType& eLanguage, USHORT nPrio = 0 ); //depricated! see "tools/source/rc/resmgr.cxx"
static ResMgr* SearchCreateResMgr( const sal_Char* pPrefixName,
com::sun::star::lang::Locale& rLocale );
static ResMgr* CreateResMgr( const sal_Char* pPrefixName,
com::sun::star::lang::Locale aLocale = com::sun::star::lang::Locale( rtl::OUString(),
rtl::OUString(),
rtl::OUString()));
// Testet ob Resource noch da ist
void TestStack( const Resource * );
// ist Resource verfuegbar
BOOL IsAvailable( const ResId& rId,
const Resource* = NULL) const;
// Resource suchen und laden
BOOL GetResource( const ResId& rId, const Resource * = NULL );
static void * GetResourceSkipHeader( const ResId& rResId, ResMgr ** ppResMgr );
// Kontext freigeben
void PopContext( const Resource* = NULL );
// Resourcezeiger erhoehen
void* Increment( sal_uInt32 nSize );
// Groesse ein Objektes in der Resource
static sal_uInt32 GetObjSize( RSHEADER_TYPE* pHT )
{ return( pHT->GetGlobOff() ); }
// Liefert einen String aus der Resource
static sal_uInt32 GetString( UniString& rStr, const BYTE* pStr );
// Groesse eines Strings in der Resource
static sal_uInt32 GetStringSize( sal_uInt32 nLen )
{ nLen++; return (nLen + nLen%2); }
static sal_uInt32 GetStringSize( const BYTE* pStr );
// return a int64
static sal_uInt64 GetUInt64( void* pDatum );
// Gibt einen long zurueck
static INT32 GetLong( void * pLong );
// return a short
static INT16 GetShort( void * pShort );
// Gibt einen Zeiger auf die Resource zurueck
void * GetClass();
RSHEADER_TYPE * CreateBlock( const ResId & rId );
// Gibt die verbleibende Groesse zurueck
sal_uInt32 GetRemainSize();
const rtl::OUString&GetFileName() const;
INT16 ReadShort();
INT32 ReadLong();
UniString ReadString();
// generate auto help id for current resource stack
ULONG GetAutoHelpId();
static void SetReadStringHook( ResHookProc pProc );
static ResHookProc GetReadStringHook();
static void SetDefaultLocale( const com::sun::star::lang::Locale& rLocale );
// #if 0 // _SOLAR__PRIVATE
rtl::OUString ImplGetPrefix();
com::sun::star::lang::Locale ImplGetLocale();
static ResMgr* ImplCreateResMgr( InternalResMgr* pImpl ) { return new ResMgr( pImpl ); }
// #endif
};
inline sal_uInt32 RSHEADER_TYPE::GetId()
{
return (sal_uInt32)ResMgr::GetLong( &nId );
}
inline RESOURCE_TYPE RSHEADER_TYPE::GetRT()
{
return (RESOURCE_TYPE)ResMgr::GetLong( &nRT );
}
inline sal_uInt32 RSHEADER_TYPE::GetGlobOff()
{
return (sal_uInt32)ResMgr::GetLong( &nGlobOff );
}
inline sal_uInt32 RSHEADER_TYPE::GetLocalOff()
{
return (sal_uInt32)ResMgr::GetLong( &nLocalOff );
}
#endif // _SV_RESMGR_HXX
<commit_msg>INTEGRATION: CWS resmgrnocopy (1.2.82); FILE MERGED 2007/12/05 12:50:50 pl 1.2.82.1: #i83169# noncopyable ResMgr<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resmgr.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2007-12-12 13:14:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TOOLS_RESMGR_HXX
#define _TOOLS_RESMGR_HXX
#ifndef INCLUDED_TOOLSDLLAPI_H
#include "tools/toolsdllapi.h"
#endif
#ifndef INCLUDED_I18NPOOL_LANG_H
#include <i18npool/lang.h>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _REF_HXX
#include <tools/ref.hxx>
#endif
#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#define CREATEVERSIONRESMGR_NAME( Name ) #Name MAKE_NUMSTR( SUPD )
#define CREATEVERSIONRESMGR( Name ) ResMgr::CreateResMgr( CREATEVERSIONRESMGR_NAME( Name ) )
#define LOCALE_MAX_FALLBACK 6
#include <vector>
class SvStream;
class InternalResMgr;
// -----------------
// - RSHEADER_TYPE -
// -----------------
// Definition der Struktur, aus denen die Resource aufgebaut ist
struct RSHEADER_TYPE
{
private:
sal_uInt32 nId; // Identifier der Resource
RESOURCE_TYPE nRT; // Resource Typ
sal_uInt32 nGlobOff; // Globaler Offset
sal_uInt32 nLocalOff; // Lokaler Offset
public:
inline sal_uInt32 GetId(); // Identifier der Resource
inline RESOURCE_TYPE GetRT(); // Resource Typ
inline sal_uInt32 GetGlobOff(); // Globaler Offset
inline sal_uInt32 GetLocalOff(); // Lokaler Offset
};
// ----------
// - ResMgr -
// ----------
typedef void (*ResHookProc)( UniString& rStr );
// ----------
// - ResMgr -
// ----------
// Initialisierung
#define RC_NOTYPE 0x00
// Globale Resource
#define RC_GLOBAL 0x01
#define RC_AUTORELEASE 0x02
#define RC_NOTFOUND 0x04
#define RC_FALLBACK_DOWN 0x08
#define RC_FALLBACK_UP 0x10
class Resource;
class ResMgr;
struct ImpRCStack
{
// pResource and pClassRes equal NULL: resource was not loaded
RSHEADER_TYPE * pResource; // pointer to resource
void * pClassRes; // pointer to class specified init data
short Flags; // resource status
void * aResHandle; // Resource-Identifier from InternalResMgr
const Resource* pResObj; // pointer to Resource object
sal_uInt32 nId; // ResId used for error message
ResMgr* pResMgr; // ResMgr for Resource pResObj
void Clear();
void Init( ResMgr * pMgr, const Resource * pObj, sal_uInt32 nId );
};
class TOOLS_DLLPUBLIC ResMgr
{
private:
InternalResMgr* pImpRes;
std::vector< ImpRCStack > aStack; // resource context stack
int nCurStack;
ResMgr* pFallbackResMgr; // fallback ResMgr in case the Resource
// was not contained in this ResMgr
ResMgr* pOriginalResMgr; // the res mgr that fell back to this
// stack level
TOOLS_DLLPRIVATE void incStack();
TOOLS_DLLPRIVATE void decStack();
TOOLS_DLLPRIVATE const ImpRCStack * StackTop( sal_uInt32 nOff = 0 ) const
{
return (((int)nOff >= nCurStack) ? NULL : &aStack[nCurStack-nOff]);
}
TOOLS_DLLPRIVATE void Init( const rtl::OUString& rFileName );
TOOLS_DLLPRIVATE ResMgr( InternalResMgr * pImp );
#ifdef DBG_UTIL
TOOLS_DLLPRIVATE static void RscError_Impl( const sal_Char* pMessage, ResMgr* pResMgr,
RESOURCE_TYPE nRT, sal_uInt32 nId,
std::vector< ImpRCStack >& rResStack, int nDepth );
#endif
// called from within GetResource() if a resource could not be found
TOOLS_DLLPRIVATE ResMgr* CreateFallbackResMgr( const ResId& rId, const Resource* pResource );
// creates a 1k sized buffer set to zero for unfound resources
// used in case RC_NOTFOUND
static void* pEmptyBuffer;
TOOLS_DLLPRIVATE static void* getEmptyBuffer();
// the next two methods are needed to prevent the string hook called
// with the res mgr mutex locked
// like GetString, but doesn't call the string hook
TOOLS_DLLPRIVATE static sal_uInt32 GetStringWithoutHook( UniString& rStr, const BYTE* pStr );
// like ReadString but doesn't call the string hook
TOOLS_DLLPRIVATE UniString ReadStringWithoutHook();
static ResMgr* ImplCreateResMgr( InternalResMgr* pImpl ) { return new ResMgr( pImpl ); }
//No copying
ResMgr(const ResMgr&);
ResMgr& operator=(const ResMgr&);
public:
static void DestroyAllResMgr(); // Wird gerufen, wenn App beendet wird
~ResMgr();
// Sprachabhaengige Ressource Library
static const sal_Char* GetLang( LanguageType& eLanguage, USHORT nPrio = 0 ); //depricated! see "tools/source/rc/resmgr.cxx"
static ResMgr* SearchCreateResMgr( const sal_Char* pPrefixName,
com::sun::star::lang::Locale& rLocale );
static ResMgr* CreateResMgr( const sal_Char* pPrefixName,
com::sun::star::lang::Locale aLocale = com::sun::star::lang::Locale( rtl::OUString(),
rtl::OUString(),
rtl::OUString()));
// Testet ob Resource noch da ist
void TestStack( const Resource * );
// ist Resource verfuegbar
BOOL IsAvailable( const ResId& rId,
const Resource* = NULL) const;
// Resource suchen und laden
BOOL GetResource( const ResId& rId, const Resource * = NULL );
static void * GetResourceSkipHeader( const ResId& rResId, ResMgr ** ppResMgr );
// Kontext freigeben
void PopContext( const Resource* = NULL );
// Resourcezeiger erhoehen
void* Increment( sal_uInt32 nSize );
// Groesse ein Objektes in der Resource
static sal_uInt32 GetObjSize( RSHEADER_TYPE* pHT )
{ return( pHT->GetGlobOff() ); }
// Liefert einen String aus der Resource
static sal_uInt32 GetString( UniString& rStr, const BYTE* pStr );
// Groesse eines Strings in der Resource
static sal_uInt32 GetStringSize( sal_uInt32 nLen )
{ nLen++; return (nLen + nLen%2); }
static sal_uInt32 GetStringSize( const BYTE* pStr );
// return a int64
static sal_uInt64 GetUInt64( void* pDatum );
// Gibt einen long zurueck
static INT32 GetLong( void * pLong );
// return a short
static INT16 GetShort( void * pShort );
// Gibt einen Zeiger auf die Resource zurueck
void * GetClass();
RSHEADER_TYPE * CreateBlock( const ResId & rId );
// Gibt die verbleibende Groesse zurueck
sal_uInt32 GetRemainSize();
const rtl::OUString&GetFileName() const;
INT16 ReadShort();
INT32 ReadLong();
UniString ReadString();
// generate auto help id for current resource stack
ULONG GetAutoHelpId();
static void SetReadStringHook( ResHookProc pProc );
static ResHookProc GetReadStringHook();
static void SetDefaultLocale( const com::sun::star::lang::Locale& rLocale );
};
inline sal_uInt32 RSHEADER_TYPE::GetId()
{
return (sal_uInt32)ResMgr::GetLong( &nId );
}
inline RESOURCE_TYPE RSHEADER_TYPE::GetRT()
{
return (RESOURCE_TYPE)ResMgr::GetLong( &nRT );
}
inline sal_uInt32 RSHEADER_TYPE::GetGlobOff()
{
return (sal_uInt32)ResMgr::GetLong( &nGlobOff );
}
inline sal_uInt32 RSHEADER_TYPE::GetLocalOff()
{
return (sal_uInt32)ResMgr::GetLong( &nLocalOff );
}
#endif // _SV_RESMGR_HXX
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <string>
#include "globals.h"
#include "profiler.h"
#include "stacktraces.h"
static Profiler *prof;
FILE *Globals::OutFile;
void JNICALL OnThreadStart(jvmtiEnv *jvmti_env, JNIEnv *jni_env,
jthread thread) {
Accessors::SetCurrentJniEnv(jni_env);
}
void JNICALL OnThreadEnd(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread) {
}
// This has to be here, or the VM turns off class loading events.
// And AsyncGetCallTrace needs class loading events to be turned on!
void JNICALL OnClassLoad(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread,
jclass klass) {}
// Calls GetClassMethods on a given class to force the creation of
// jmethodIDs of it.
void CreateJMethodIDsForClass(jvmtiEnv *jvmti, jclass klass) {
jint method_count;
JvmtiScopedPtr<jmethodID> methods(jvmti);
jvmtiError e = jvmti->GetClassMethods(klass, &method_count, methods.GetRef());
if (e != JVMTI_ERROR_NONE && e != JVMTI_ERROR_CLASS_NOT_PREPARED) {
// JVMTI_ERROR_CLASS_NOT_PREPARED is okay because some classes may
// be loaded but not prepared at this point.
JvmtiScopedPtr<char> ksig(jvmti);
JVMTI_ERROR((jvmti->GetClassSignature(klass, ksig.GetRef(), NULL)));
fprintf(
stderr,
"Failed to create method IDs for methods in class %s with error %d ",
ksig.Get(), e);
}
}
void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jni_env, jthread thread) {
// Forces the creation of jmethodIDs of the classes that had already
// been loaded (eg java.lang.Object, java.lang.ClassLoader) and
// OnClassPrepare() misses.
jint class_count;
JvmtiScopedPtr<jclass> classes(jvmti);
JVMTI_ERROR((jvmti->GetLoadedClasses(&class_count, classes.GetRef())));
jclass *classList = classes.Get();
for (int i = 0; i < class_count; ++i) {
jclass klass = classList[i];
CreateJMethodIDsForClass(jvmti, klass);
}
prof->Start();
}
void JNICALL OnClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *jni_env,
jthread thread, jclass klass) {
// We need to do this to "prime the pump", as it were -- make sure
// that all of the methodIDs have been initialized internally, for
// AsyncGetCallTrace. I imagine it slows down class loading a mite,
// but honestly, how fast does class loading have to be?
CreateJMethodIDsForClass(jvmti_env, klass);
}
void JNICALL OnVMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) {
prof->Stop();
prof->DumpToFile(Globals::OutFile);
}
static bool PrepareJvmti(jvmtiEnv *jvmti) {
// Set the list of permissions to do the various internal VM things
// we want to do.
jvmtiCapabilities caps;
memset(&caps, 0, sizeof(caps));
caps.can_generate_all_class_hook_events = 1;
caps.can_get_source_file_name = 1;
caps.can_get_line_numbers = 1;
caps.can_get_bytecodes = 1;
caps.can_get_constant_pool = 1;
jvmtiCapabilities all_caps;
int error;
if (JVMTI_ERROR_NONE ==
(error = jvmti->GetPotentialCapabilities(&all_caps))) {
// This makes sure that if we need a capability, it is one of the
// potential capabilities. The technique isn't wonderful, but it
// is compact and as likely to be compatible between versions as
// anything else.
char *has = reinterpret_cast<char *>(&all_caps);
const char *should_have = reinterpret_cast<const char *>(&caps);
for (int i = 0; i < sizeof(all_caps); i++) {
if ((should_have[i] != 0) && (has[i] == 0)) {
return false;
}
}
// This adds the capabilities.
if ((error = jvmti->AddCapabilities(&caps)) != JVMTI_ERROR_NONE) {
fprintf(stderr, "Failed to add capabilities with error %d\n", error);
return false;
}
}
return true;
}
static bool RegisterJvmti(jvmtiEnv *jvmti) {
// Create the list of callbacks to be called on given events.
jvmtiEventCallbacks *callbacks = new jvmtiEventCallbacks();
memset(callbacks, 0, sizeof(jvmtiEventCallbacks));
callbacks->ThreadStart = &OnThreadStart;
callbacks->ThreadEnd = &OnThreadEnd;
callbacks->VMInit = &OnVMInit;
callbacks->VMDeath = &OnVMDeath;
callbacks->ClassLoad = &OnClassLoad;
callbacks->ClassPrepare = &OnClassPrepare;
JVMTI_ERROR_1(
(jvmti->SetEventCallbacks(callbacks, sizeof(jvmtiEventCallbacks))),
false);
jvmtiEvent events[] = {JVMTI_EVENT_CLASS_LOAD, JVMTI_EVENT_CLASS_PREPARE,
JVMTI_EVENT_THREAD_END, JVMTI_EVENT_THREAD_START,
JVMTI_EVENT_VM_DEATH, JVMTI_EVENT_VM_INIT};
size_t num_events = sizeof(events) / sizeof(jvmtiEvent);
// Enable the callbacks to be triggered when the events occur.
// Events are enumerated in jvmstatagent.h
for (int i = 0; i < num_events; i++) {
JVMTI_ERROR_1(
(jvmti->SetEventNotificationMode(JVMTI_ENABLE, events[i], NULL)),
false);
}
return true;
}
static void SetFileFromOption(char *key, char *equals) {
char *name_begin = equals + 1;
char *name_end;
if ((name_end = strchr(equals, ',')) == NULL) {
name_end = equals + strlen(equals);
}
int len = name_end - name_begin;
char *file_name = new char[len];
strncpy(file_name, name_begin, len);
if (strcmp(file_name, "stderr") == 0) {
Globals::OutFile = stderr;
} else if (strcmp(file_name, "stdout") == 0) {
Globals::OutFile = stdout;
} else {
Globals::OutFile = fopen(file_name, "w+");
if (Globals::OutFile == NULL) {
fprintf(stderr, "Could not open file %s: ", file_name);
perror(NULL);
exit(1);
}
}
delete[] file_name;
}
static void ParseArguments(char *options) {
char *key = options;
for (char *next = options; next != NULL;
next = strchr((key = next + 1), ',')) {
char *equals = strchr(key, '=');
if (equals == NULL) {
fprintf(stderr, "No value for key %s\n", key);
continue;
}
if (strncmp(key, "file", equals - key) == 0) {
SetFileFromOption(key, equals);
}
}
if (Globals::OutFile == NULL) {
char path[PATH_MAX];
if (getcwd(path, PATH_MAX) == NULL) {
fprintf(stderr, "cwd too long?\n");
exit(0);
}
size_t pathlen = strlen(path);
strncat(path, kDefaultOutFile, PATH_MAX - pathlen);
Globals::OutFile = fopen(path, "w+");
}
}
AGENTEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options,
void *reserved) {
int err;
jvmtiEnv *jvmti;
ParseArguments(options);
if ((err = (vm->GetEnv(reinterpret_cast<void **>(&jvmti), JVMTI_VERSION))) !=
JNI_OK) {
fprintf(stderr, "JNI Error %d\n", err);
return 1;
}
if (!PrepareJvmti(jvmti)) {
fprintf(stderr, "Failed to initialize JVMTI. Continuing...\n");
return 0;
}
if (!RegisterJvmti(jvmti)) {
fprintf(stderr, "Failed to enable JVMTI events. Continuing...\n");
// We fail hard here because we may have failed in the middle of
// registering callbacks, which will leave the system in an
// inconsistent state.
return 1;
}
Asgct::SetAsgct(Accessors::GetJvmFunction<ASGCTType>("AsyncGetCallTrace"));
prof = new Profiler(jvmti);
return 0;
}
AGENTEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) {}
<commit_msg>Include missing path separator, and include necessary to runcompile with Fedora 19.<commit_after>#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include "globals.h"
#include "profiler.h"
#include "stacktraces.h"
static Profiler *prof;
FILE *Globals::OutFile;
void JNICALL OnThreadStart(jvmtiEnv *jvmti_env, JNIEnv *jni_env,
jthread thread) {
Accessors::SetCurrentJniEnv(jni_env);
}
void JNICALL OnThreadEnd(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread) {
}
// This has to be here, or the VM turns off class loading events.
// And AsyncGetCallTrace needs class loading events to be turned on!
void JNICALL OnClassLoad(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread,
jclass klass) {}
// Calls GetClassMethods on a given class to force the creation of
// jmethodIDs of it.
void CreateJMethodIDsForClass(jvmtiEnv *jvmti, jclass klass) {
jint method_count;
JvmtiScopedPtr<jmethodID> methods(jvmti);
jvmtiError e = jvmti->GetClassMethods(klass, &method_count, methods.GetRef());
if (e != JVMTI_ERROR_NONE && e != JVMTI_ERROR_CLASS_NOT_PREPARED) {
// JVMTI_ERROR_CLASS_NOT_PREPARED is okay because some classes may
// be loaded but not prepared at this point.
JvmtiScopedPtr<char> ksig(jvmti);
JVMTI_ERROR((jvmti->GetClassSignature(klass, ksig.GetRef(), NULL)));
fprintf(
stderr,
"Failed to create method IDs for methods in class %s with error %d ",
ksig.Get(), e);
}
}
void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jni_env, jthread thread) {
// Forces the creation of jmethodIDs of the classes that had already
// been loaded (eg java.lang.Object, java.lang.ClassLoader) and
// OnClassPrepare() misses.
jint class_count;
JvmtiScopedPtr<jclass> classes(jvmti);
JVMTI_ERROR((jvmti->GetLoadedClasses(&class_count, classes.GetRef())));
jclass *classList = classes.Get();
for (int i = 0; i < class_count; ++i) {
jclass klass = classList[i];
CreateJMethodIDsForClass(jvmti, klass);
}
prof->Start();
}
void JNICALL OnClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *jni_env,
jthread thread, jclass klass) {
// We need to do this to "prime the pump", as it were -- make sure
// that all of the methodIDs have been initialized internally, for
// AsyncGetCallTrace. I imagine it slows down class loading a mite,
// but honestly, how fast does class loading have to be?
CreateJMethodIDsForClass(jvmti_env, klass);
}
void JNICALL OnVMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) {
prof->Stop();
prof->DumpToFile(Globals::OutFile);
}
static bool PrepareJvmti(jvmtiEnv *jvmti) {
// Set the list of permissions to do the various internal VM things
// we want to do.
jvmtiCapabilities caps;
memset(&caps, 0, sizeof(caps));
caps.can_generate_all_class_hook_events = 1;
caps.can_get_source_file_name = 1;
caps.can_get_line_numbers = 1;
caps.can_get_bytecodes = 1;
caps.can_get_constant_pool = 1;
jvmtiCapabilities all_caps;
int error;
if (JVMTI_ERROR_NONE ==
(error = jvmti->GetPotentialCapabilities(&all_caps))) {
// This makes sure that if we need a capability, it is one of the
// potential capabilities. The technique isn't wonderful, but it
// is compact and as likely to be compatible between versions as
// anything else.
char *has = reinterpret_cast<char *>(&all_caps);
const char *should_have = reinterpret_cast<const char *>(&caps);
for (int i = 0; i < sizeof(all_caps); i++) {
if ((should_have[i] != 0) && (has[i] == 0)) {
return false;
}
}
// This adds the capabilities.
if ((error = jvmti->AddCapabilities(&caps)) != JVMTI_ERROR_NONE) {
fprintf(stderr, "Failed to add capabilities with error %d\n", error);
return false;
}
}
return true;
}
static bool RegisterJvmti(jvmtiEnv *jvmti) {
// Create the list of callbacks to be called on given events.
jvmtiEventCallbacks *callbacks = new jvmtiEventCallbacks();
memset(callbacks, 0, sizeof(jvmtiEventCallbacks));
callbacks->ThreadStart = &OnThreadStart;
callbacks->ThreadEnd = &OnThreadEnd;
callbacks->VMInit = &OnVMInit;
callbacks->VMDeath = &OnVMDeath;
callbacks->ClassLoad = &OnClassLoad;
callbacks->ClassPrepare = &OnClassPrepare;
JVMTI_ERROR_1(
(jvmti->SetEventCallbacks(callbacks, sizeof(jvmtiEventCallbacks))),
false);
jvmtiEvent events[] = {JVMTI_EVENT_CLASS_LOAD, JVMTI_EVENT_CLASS_PREPARE,
JVMTI_EVENT_THREAD_END, JVMTI_EVENT_THREAD_START,
JVMTI_EVENT_VM_DEATH, JVMTI_EVENT_VM_INIT};
size_t num_events = sizeof(events) / sizeof(jvmtiEvent);
// Enable the callbacks to be triggered when the events occur.
// Events are enumerated in jvmstatagent.h
for (int i = 0; i < num_events; i++) {
JVMTI_ERROR_1(
(jvmti->SetEventNotificationMode(JVMTI_ENABLE, events[i], NULL)),
false);
}
return true;
}
static void SetFileFromOption(char *key, char *equals) {
char *name_begin = equals + 1;
char *name_end;
if ((name_end = strchr(equals, ',')) == NULL) {
name_end = equals + strlen(equals);
}
int len = name_end - name_begin;
char *file_name = new char[len];
strncpy(file_name, name_begin, len);
if (strcmp(file_name, "stderr") == 0) {
Globals::OutFile = stderr;
} else if (strcmp(file_name, "stdout") == 0) {
Globals::OutFile = stdout;
} else {
Globals::OutFile = fopen(file_name, "w+");
if (Globals::OutFile == NULL) {
fprintf(stderr, "Could not open file %s: ", file_name);
perror(NULL);
exit(1);
}
}
delete[] file_name;
}
static void ParseArguments(char *options) {
char *key = options;
for (char *next = options; next != NULL;
next = strchr((key = next + 1), ',')) {
char *equals = strchr(key, '=');
if (equals == NULL) {
fprintf(stderr, "No value for key %s\n", key);
continue;
}
if (strncmp(key, "file", equals - key) == 0) {
SetFileFromOption(key, equals);
}
}
if (Globals::OutFile == NULL) {
char path[PATH_MAX];
if (getcwd(path, PATH_MAX) == NULL) {
fprintf(stderr, "cwd too long?\n");
exit(0);
}
size_t pathlen = strlen(path);
strncat(path, "/", PATH_MAX - pathlen);
strncat(path, kDefaultOutFile, PATH_MAX - pathlen);
Globals::OutFile = fopen(path, "w+");
}
}
AGENTEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options,
void *reserved) {
int err;
jvmtiEnv *jvmti;
ParseArguments(options);
if ((err = (vm->GetEnv(reinterpret_cast<void **>(&jvmti), JVMTI_VERSION))) !=
JNI_OK) {
fprintf(stderr, "JNI Error %d\n", err);
return 1;
}
if (!PrepareJvmti(jvmti)) {
fprintf(stderr, "Failed to initialize JVMTI. Continuing...\n");
return 0;
}
if (!RegisterJvmti(jvmti)) {
fprintf(stderr, "Failed to enable JVMTI events. Continuing...\n");
// We fail hard here because we may have failed in the middle of
// registering callbacks, which will leave the system in an
// inconsistent state.
return 1;
}
Asgct::SetAsgct(Accessors::GetJvmFunction<ASGCTType>("AsyncGetCallTrace"));
prof = new Profiler(jvmti);
return 0;
}
AGENTEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) {}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2010, John Wiegley. 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 New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "utils.h"
namespace ledger {
straccstream _ctxt_accum;
std::ostringstream _ctxt_buffer;
straccstream _desc_accum;
std::ostringstream _desc_buffer;
string error_context()
{
string context = _ctxt_buffer.str();
_ctxt_buffer.clear();
_ctxt_buffer.str("");
return context;
}
string file_context(const path& file, const std::size_t line)
{
std::ostringstream buf;
buf << '"' << file.string() << "\", line " << line << ": ";
return buf.str();
}
string line_context(const string& line,
const string::size_type pos,
const string::size_type end_pos)
{
std::ostringstream buf;
buf << " " << line << "\n";
if (pos != 0) {
buf << " ";
if (end_pos == 0) {
for (string::size_type i = 0; i < pos; i += 1)
buf << " ";
buf << "^";
} else {
for (string::size_type i = 0; i < end_pos; i += 1) {
if (i >= pos)
buf << "^";
else
buf << " ";
}
}
}
return buf.str();
}
string source_context(const path& file,
const istream_pos_type pos,
const istream_pos_type end_pos,
const string& prefix)
{
const std::streamoff len = end_pos - pos;
if (! len || file == path("/dev/stdin"))
return _("<no source context>");
assert(len > 0);
assert(len < 8192);
std::ostringstream out;
ifstream in(file);
in.seekg(pos, std::ios::beg);
scoped_array<char> buf(new char[static_cast<std::size_t>(len) + 1]);
in.read(buf.get(), static_cast<std::streamsize>(len));
assert(in.gcount() == static_cast<std::streamsize>(len));
buf[static_cast<std::size_t>(len)] = '\0';
bool first = true;
for (char * p = std::strtok(buf.get(), "\n");
p;
p = std::strtok(NULL, "\n")) {
if (first)
first = false;
else
out << '\n';
out << prefix << p;
}
return out.str();
}
} // namespace ledger
<commit_msg>Corrected the type of a cast<commit_after>/*
* Copyright (c) 2003-2010, John Wiegley. 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 New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "utils.h"
namespace ledger {
straccstream _ctxt_accum;
std::ostringstream _ctxt_buffer;
straccstream _desc_accum;
std::ostringstream _desc_buffer;
string error_context()
{
string context = _ctxt_buffer.str();
_ctxt_buffer.clear();
_ctxt_buffer.str("");
return context;
}
string file_context(const path& file, const std::size_t line)
{
std::ostringstream buf;
buf << '"' << file.string() << "\", line " << line << ": ";
return buf.str();
}
string line_context(const string& line,
const string::size_type pos,
const string::size_type end_pos)
{
std::ostringstream buf;
buf << " " << line << "\n";
if (pos != 0) {
buf << " ";
if (end_pos == 0) {
for (string::size_type i = 0; i < pos; i += 1)
buf << " ";
buf << "^";
} else {
for (string::size_type i = 0; i < end_pos; i += 1) {
if (i >= pos)
buf << "^";
else
buf << " ";
}
}
}
return buf.str();
}
string source_context(const path& file,
const istream_pos_type pos,
const istream_pos_type end_pos,
const string& prefix)
{
const std::streamoff len = end_pos - pos;
if (! len || file == path("/dev/stdin"))
return _("<no source context>");
assert(len > 0);
assert(len < 8192);
std::ostringstream out;
ifstream in(file);
in.seekg(pos, std::ios::beg);
scoped_array<char> buf(new char[static_cast<std::size_t>(len) + 1]);
in.read(buf.get(), static_cast<std::streamsize>(len));
assert(in.gcount() == static_cast<std::streamsize>(len));
buf[static_cast<std::ptrdiff_t>(len)] = '\0';
bool first = true;
for (char * p = std::strtok(buf.get(), "\n");
p;
p = std::strtok(NULL, "\n")) {
if (first)
first = false;
else
out << '\n';
out << prefix << p;
}
return out.str();
}
} // namespace ledger
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "graph.h"
#include <assert.h>
#include <stdio.h>
#include "build_log.h"
#include "depfile_parser.h"
#include "disk_interface.h"
#include "explain.h"
#include "manifest_parser.h"
#include "metrics.h"
#include "state.h"
#include "util.h"
bool Node::Stat(DiskInterface* disk_interface) {
METRIC_RECORD("node stat");
mtime_ = disk_interface->Stat(path_);
return mtime_ > 0;
}
bool DependencyScan::RecomputeDirty(Edge* edge, string* err) {
bool dirty = false;
edge->outputs_ready_ = true;
if (!edge->rule_->depfile().empty()) {
if (!LoadDepFile(edge, err)) {
if (!err->empty())
return false;
EXPLAIN("Edge targets are dirty because depfile '%s' is missing",
edge->EvaluateDepFile().c_str());
dirty = true;
}
}
// Visit all inputs; we're dirty if any of the inputs are dirty.
Node* most_recent_input = NULL;
for (vector<Node*>::iterator i = edge->inputs_.begin();
i != edge->inputs_.end(); ++i) {
if ((*i)->StatIfNecessary(disk_interface_)) {
if (Edge* in_edge = (*i)->in_edge()) {
if (!RecomputeDirty(in_edge, err))
return false;
} else {
// This input has no in-edge; it is dirty if it is missing.
if (!(*i)->exists())
EXPLAIN("%s has no in-edge and is missing", (*i)->path().c_str());
(*i)->set_dirty(!(*i)->exists());
}
}
// If an input is not ready, neither are our outputs.
if (Edge* in_edge = (*i)->in_edge()) {
if (!in_edge->outputs_ready_)
edge->outputs_ready_ = false;
}
if (!edge->is_order_only(i - edge->inputs_.begin())) {
// If a regular input is dirty (or missing), we're dirty.
// Otherwise consider mtime.
if ((*i)->dirty()) {
EXPLAIN("%s is dirty", (*i)->path().c_str());
dirty = true;
} else {
if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime()) {
most_recent_input = *i;
}
}
}
}
// We may also be dirty due to output state: missing outputs, out of
// date outputs, etc. Visit all outputs and determine whether they're dirty.
if (!dirty) {
string command = edge->EvaluateCommand(true);
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
(*i)->StatIfNecessary(disk_interface_);
if (RecomputeOutputDirty(edge, most_recent_input, command, *i)) {
dirty = true;
break;
}
}
}
// Finally, visit each output to mark off that we've visited it, and update
// their dirty state if necessary.
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
(*i)->StatIfNecessary(disk_interface_);
if (dirty)
(*i)->MarkDirty();
}
// If an edge is dirty, its outputs are normally not ready. (It's
// possible to be clean but still not be ready in the presence of
// order-only inputs.)
// But phony edges with no inputs have nothing to do, so are always
// ready.
if (dirty && !(edge->is_phony() && edge->inputs_.empty()))
edge->outputs_ready_ = false;
return true;
}
bool DependencyScan::RecomputeOutputDirty(Edge* edge,
Node* most_recent_input,
const string& command,
Node* output) {
if (edge->is_phony()) {
// Phony edges don't write any output. Outputs are only dirty if
// there are no inputs and we're missing the output.
return edge->inputs_.empty() && !output->exists();
}
BuildLog::LogEntry* entry = 0;
// Dirty if we're missing the output.
if (!output->exists()) {
EXPLAIN("output %s doesn't exist", output->path().c_str());
return true;
}
// Dirty if the output is older than the input.
if (most_recent_input && output->mtime() < most_recent_input->mtime()) {
// If this is a restat rule, we may have cleaned the output with a restat
// rule in a previous run and stored the most recent input mtime in the
// build log. Use that mtime instead, so that the file will only be
// considered dirty if an input was modified since the previous run.
TimeStamp most_recent_stamp = most_recent_input->mtime();
if (edge->rule_->restat() && build_log() &&
(entry = build_log()->LookupByOutput(output->path()))) {
if (entry->restat_mtime < most_recent_stamp) {
EXPLAIN("restat of output %s older than most recent input %s (%d vs %d)",
output->path().c_str(), most_recent_input->path().c_str(),
entry->restat_mtime, most_recent_stamp);
return true;
}
} else {
EXPLAIN("output %s older than most recent input %s (%d vs %d)",
output->path().c_str(), most_recent_input->path().c_str(),
output->mtime(), most_recent_stamp);
return true;
}
}
// May also be dirty due to the command changing since the last build.
// But if this is a generator rule, the command changing does not make us
// dirty.
if (!edge->rule_->generator() && build_log()) {
if (entry || (entry = build_log()->LookupByOutput(output->path()))) {
if (BuildLog::LogEntry::HashCommand(command) != entry->command_hash) {
EXPLAIN("command line changed for %s", output->path().c_str());
return true;
}
}
if (!entry) {
EXPLAIN("command line not found in log for %s", output->path().c_str());
return true;
}
}
return false;
}
bool Edge::AllInputsReady() const {
for (vector<Node*>::const_iterator i = inputs_.begin();
i != inputs_.end(); ++i) {
if ((*i)->in_edge() && !(*i)->in_edge()->outputs_ready())
return false;
}
return true;
}
/// An Env for an Edge, providing $in and $out.
struct EdgeEnv : public Env {
explicit EdgeEnv(Edge* edge) : edge_(edge) {}
virtual string LookupVariable(const string& var);
/// Given a span of Nodes, construct a list of paths suitable for a command
/// line. XXX here is where shell-escaping of e.g spaces should happen.
string MakePathList(vector<Node*>::iterator begin,
vector<Node*>::iterator end,
char sep);
Edge* edge_;
};
string EdgeEnv::LookupVariable(const string& var) {
if (var == "in" || var == "in_newline") {
int explicit_deps_count = edge_->inputs_.size() - edge_->implicit_deps_ -
edge_->order_only_deps_;
return MakePathList(edge_->inputs_.begin(),
edge_->inputs_.begin() + explicit_deps_count,
var == "in" ? ' ' : '\n');
} else if (var == "out") {
return MakePathList(edge_->outputs_.begin(),
edge_->outputs_.end(),
' ');
} else if (edge_->env_) {
return edge_->env_->LookupVariable(var);
} else {
// XXX should we warn here?
return string();
}
}
string EdgeEnv::MakePathList(vector<Node*>::iterator begin,
vector<Node*>::iterator end,
char sep) {
string result;
for (vector<Node*>::iterator i = begin; i != end; ++i) {
if (!result.empty())
result.push_back(sep);
const string& path = (*i)->path();
if (path.find(" ") != string::npos) {
result.append("\"");
result.append(path);
result.append("\"");
} else {
result.append(path);
}
}
return result;
}
string Edge::EvaluateCommand(bool incl_rsp_file) {
EdgeEnv env(this);
string command = rule_->command().Evaluate(&env);
if (incl_rsp_file && HasRspFile())
command += ";rspfile=" + GetRspFileContent();
return command;
}
string Edge::EvaluateDepFile() {
EdgeEnv env(this);
return rule_->depfile().Evaluate(&env);
}
string Edge::GetDescription() {
EdgeEnv env(this);
return rule_->description().Evaluate(&env);
}
bool Edge::HasRspFile() {
return !rule_->rspfile().empty();
}
string Edge::GetRspFile() {
EdgeEnv env(this);
return rule_->rspfile().Evaluate(&env);
}
string Edge::GetRspFileContent() {
EdgeEnv env(this);
return rule_->rspfile_content().Evaluate(&env);
}
bool DependencyScan::LoadDepFile(Edge* edge, string* err) {
METRIC_RECORD("depfile load");
string path = edge->EvaluateDepFile();
string content = disk_interface_->ReadFile(path, err);
if (!err->empty())
return false;
// On a missing depfile: return false and empty *err.
if (content.empty())
return false;
DepfileParser depfile;
string depfile_err;
if (!depfile.Parse(&content, &depfile_err)) {
*err = path + ": " + depfile_err;
return false;
}
// Check that this depfile matches the edge's output.
Node* first_output = edge->outputs_[0];
StringPiece opath = StringPiece(first_output->path());
if (opath != depfile.out_) {
*err = "expected depfile '" + path + "' to mention '" +
first_output->path() + "', got '" + depfile.out_.AsString() + "'";
return false;
}
// Preallocate space in edge->inputs_ to be filled in below.
edge->inputs_.insert(edge->inputs_.end() - edge->order_only_deps_,
depfile.ins_.size(), 0);
edge->implicit_deps_ += depfile.ins_.size();
vector<Node*>::iterator implicit_dep =
edge->inputs_.end() - edge->order_only_deps_ - depfile.ins_.size();
// Add all its in-edges.
for (vector<StringPiece>::iterator i = depfile.ins_.begin();
i != depfile.ins_.end(); ++i, ++implicit_dep) {
if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, err))
return false;
Node* node = state_->GetNode(*i);
*implicit_dep = node;
node->AddOutEdge(edge);
// If we don't have a edge that generates this input already,
// create one; this makes us not abort if the input is missing,
// but instead will rebuild in that circumstance.
if (!node->in_edge()) {
Edge* phony_edge = state_->AddEdge(&State::kPhonyRule);
node->set_in_edge(phony_edge);
phony_edge->outputs_.push_back(node);
// RecomputeDirty might not be called for phony_edge if a previous call
// to RecomputeDirty had caused the file to be stat'ed. Because previous
// invocations of RecomputeDirty would have seen this node without an
// input edge (and therefore ready), we have to set outputs_ready_ to true
// to avoid a potential stuck build. If we do call RecomputeDirty for
// this node, it will simply set outputs_ready_ to the correct value.
phony_edge->outputs_ready_ = true;
}
}
return true;
}
void Edge::Dump(const char* prefix) const {
printf("%s[ ", prefix);
for (vector<Node*>::const_iterator i = inputs_.begin();
i != inputs_.end() && *i != NULL; ++i) {
printf("%s ", (*i)->path().c_str());
}
printf("--%s-> ", rule_->name().c_str());
for (vector<Node*>::const_iterator i = outputs_.begin();
i != outputs_.end() && *i != NULL; ++i) {
printf("%s ", (*i)->path().c_str());
}
printf("] 0x%p\n", this);
}
bool Edge::is_phony() const {
return rule_ == &State::kPhonyRule;
}
void Node::Dump(const char* prefix) const {
printf("%s <%s 0x%p> mtime: %d%s, (:%s), ",
prefix, path().c_str(), this,
mtime(), mtime() ? "" : " (:missing)",
dirty() ? " dirty" : " clean");
if (in_edge()) {
in_edge()->Dump("in-edge: ");
} else {
printf("no in-edge\n");
}
printf(" out edges:\n");
for (vector<Edge*>::const_iterator e = out_edges().begin();
e != out_edges().end() && *e != NULL; ++e) {
(*e)->Dump(" +- ");
}
}
<commit_msg>trailing whitespace<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "graph.h"
#include <assert.h>
#include <stdio.h>
#include "build_log.h"
#include "depfile_parser.h"
#include "disk_interface.h"
#include "explain.h"
#include "manifest_parser.h"
#include "metrics.h"
#include "state.h"
#include "util.h"
bool Node::Stat(DiskInterface* disk_interface) {
METRIC_RECORD("node stat");
mtime_ = disk_interface->Stat(path_);
return mtime_ > 0;
}
bool DependencyScan::RecomputeDirty(Edge* edge, string* err) {
bool dirty = false;
edge->outputs_ready_ = true;
if (!edge->rule_->depfile().empty()) {
if (!LoadDepFile(edge, err)) {
if (!err->empty())
return false;
EXPLAIN("Edge targets are dirty because depfile '%s' is missing",
edge->EvaluateDepFile().c_str());
dirty = true;
}
}
// Visit all inputs; we're dirty if any of the inputs are dirty.
Node* most_recent_input = NULL;
for (vector<Node*>::iterator i = edge->inputs_.begin();
i != edge->inputs_.end(); ++i) {
if ((*i)->StatIfNecessary(disk_interface_)) {
if (Edge* in_edge = (*i)->in_edge()) {
if (!RecomputeDirty(in_edge, err))
return false;
} else {
// This input has no in-edge; it is dirty if it is missing.
if (!(*i)->exists())
EXPLAIN("%s has no in-edge and is missing", (*i)->path().c_str());
(*i)->set_dirty(!(*i)->exists());
}
}
// If an input is not ready, neither are our outputs.
if (Edge* in_edge = (*i)->in_edge()) {
if (!in_edge->outputs_ready_)
edge->outputs_ready_ = false;
}
if (!edge->is_order_only(i - edge->inputs_.begin())) {
// If a regular input is dirty (or missing), we're dirty.
// Otherwise consider mtime.
if ((*i)->dirty()) {
EXPLAIN("%s is dirty", (*i)->path().c_str());
dirty = true;
} else {
if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime()) {
most_recent_input = *i;
}
}
}
}
// We may also be dirty due to output state: missing outputs, out of
// date outputs, etc. Visit all outputs and determine whether they're dirty.
if (!dirty) {
string command = edge->EvaluateCommand(true);
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
(*i)->StatIfNecessary(disk_interface_);
if (RecomputeOutputDirty(edge, most_recent_input, command, *i)) {
dirty = true;
break;
}
}
}
// Finally, visit each output to mark off that we've visited it, and update
// their dirty state if necessary.
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
(*i)->StatIfNecessary(disk_interface_);
if (dirty)
(*i)->MarkDirty();
}
// If an edge is dirty, its outputs are normally not ready. (It's
// possible to be clean but still not be ready in the presence of
// order-only inputs.)
// But phony edges with no inputs have nothing to do, so are always
// ready.
if (dirty && !(edge->is_phony() && edge->inputs_.empty()))
edge->outputs_ready_ = false;
return true;
}
bool DependencyScan::RecomputeOutputDirty(Edge* edge,
Node* most_recent_input,
const string& command,
Node* output) {
if (edge->is_phony()) {
// Phony edges don't write any output. Outputs are only dirty if
// there are no inputs and we're missing the output.
return edge->inputs_.empty() && !output->exists();
}
BuildLog::LogEntry* entry = 0;
// Dirty if we're missing the output.
if (!output->exists()) {
EXPLAIN("output %s doesn't exist", output->path().c_str());
return true;
}
// Dirty if the output is older than the input.
if (most_recent_input && output->mtime() < most_recent_input->mtime()) {
// If this is a restat rule, we may have cleaned the output with a restat
// rule in a previous run and stored the most recent input mtime in the
// build log. Use that mtime instead, so that the file will only be
// considered dirty if an input was modified since the previous run.
TimeStamp most_recent_stamp = most_recent_input->mtime();
if (edge->rule_->restat() && build_log() &&
(entry = build_log()->LookupByOutput(output->path()))) {
if (entry->restat_mtime < most_recent_stamp) {
EXPLAIN("restat of output %s older than most recent input %s (%d vs %d)",
output->path().c_str(), most_recent_input->path().c_str(),
entry->restat_mtime, most_recent_stamp);
return true;
}
} else {
EXPLAIN("output %s older than most recent input %s (%d vs %d)",
output->path().c_str(), most_recent_input->path().c_str(),
output->mtime(), most_recent_stamp);
return true;
}
}
// May also be dirty due to the command changing since the last build.
// But if this is a generator rule, the command changing does not make us
// dirty.
if (!edge->rule_->generator() && build_log()) {
if (entry || (entry = build_log()->LookupByOutput(output->path()))) {
if (BuildLog::LogEntry::HashCommand(command) != entry->command_hash) {
EXPLAIN("command line changed for %s", output->path().c_str());
return true;
}
}
if (!entry) {
EXPLAIN("command line not found in log for %s", output->path().c_str());
return true;
}
}
return false;
}
bool Edge::AllInputsReady() const {
for (vector<Node*>::const_iterator i = inputs_.begin();
i != inputs_.end(); ++i) {
if ((*i)->in_edge() && !(*i)->in_edge()->outputs_ready())
return false;
}
return true;
}
/// An Env for an Edge, providing $in and $out.
struct EdgeEnv : public Env {
explicit EdgeEnv(Edge* edge) : edge_(edge) {}
virtual string LookupVariable(const string& var);
/// Given a span of Nodes, construct a list of paths suitable for a command
/// line. XXX here is where shell-escaping of e.g spaces should happen.
string MakePathList(vector<Node*>::iterator begin,
vector<Node*>::iterator end,
char sep);
Edge* edge_;
};
string EdgeEnv::LookupVariable(const string& var) {
if (var == "in" || var == "in_newline") {
int explicit_deps_count = edge_->inputs_.size() - edge_->implicit_deps_ -
edge_->order_only_deps_;
return MakePathList(edge_->inputs_.begin(),
edge_->inputs_.begin() + explicit_deps_count,
var == "in" ? ' ' : '\n');
} else if (var == "out") {
return MakePathList(edge_->outputs_.begin(),
edge_->outputs_.end(),
' ');
} else if (edge_->env_) {
return edge_->env_->LookupVariable(var);
} else {
// XXX should we warn here?
return string();
}
}
string EdgeEnv::MakePathList(vector<Node*>::iterator begin,
vector<Node*>::iterator end,
char sep) {
string result;
for (vector<Node*>::iterator i = begin; i != end; ++i) {
if (!result.empty())
result.push_back(sep);
const string& path = (*i)->path();
if (path.find(" ") != string::npos) {
result.append("\"");
result.append(path);
result.append("\"");
} else {
result.append(path);
}
}
return result;
}
string Edge::EvaluateCommand(bool incl_rsp_file) {
EdgeEnv env(this);
string command = rule_->command().Evaluate(&env);
if (incl_rsp_file && HasRspFile())
command += ";rspfile=" + GetRspFileContent();
return command;
}
string Edge::EvaluateDepFile() {
EdgeEnv env(this);
return rule_->depfile().Evaluate(&env);
}
string Edge::GetDescription() {
EdgeEnv env(this);
return rule_->description().Evaluate(&env);
}
bool Edge::HasRspFile() {
return !rule_->rspfile().empty();
}
string Edge::GetRspFile() {
EdgeEnv env(this);
return rule_->rspfile().Evaluate(&env);
}
string Edge::GetRspFileContent() {
EdgeEnv env(this);
return rule_->rspfile_content().Evaluate(&env);
}
bool DependencyScan::LoadDepFile(Edge* edge, string* err) {
METRIC_RECORD("depfile load");
string path = edge->EvaluateDepFile();
string content = disk_interface_->ReadFile(path, err);
if (!err->empty())
return false;
// On a missing depfile: return false and empty *err.
if (content.empty())
return false;
DepfileParser depfile;
string depfile_err;
if (!depfile.Parse(&content, &depfile_err)) {
*err = path + ": " + depfile_err;
return false;
}
// Check that this depfile matches the edge's output.
Node* first_output = edge->outputs_[0];
StringPiece opath = StringPiece(first_output->path());
if (opath != depfile.out_) {
*err = "expected depfile '" + path + "' to mention '" +
first_output->path() + "', got '" + depfile.out_.AsString() + "'";
return false;
}
// Preallocate space in edge->inputs_ to be filled in below.
edge->inputs_.insert(edge->inputs_.end() - edge->order_only_deps_,
depfile.ins_.size(), 0);
edge->implicit_deps_ += depfile.ins_.size();
vector<Node*>::iterator implicit_dep =
edge->inputs_.end() - edge->order_only_deps_ - depfile.ins_.size();
// Add all its in-edges.
for (vector<StringPiece>::iterator i = depfile.ins_.begin();
i != depfile.ins_.end(); ++i, ++implicit_dep) {
if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, err))
return false;
Node* node = state_->GetNode(*i);
*implicit_dep = node;
node->AddOutEdge(edge);
// If we don't have a edge that generates this input already,
// create one; this makes us not abort if the input is missing,
// but instead will rebuild in that circumstance.
if (!node->in_edge()) {
Edge* phony_edge = state_->AddEdge(&State::kPhonyRule);
node->set_in_edge(phony_edge);
phony_edge->outputs_.push_back(node);
// RecomputeDirty might not be called for phony_edge if a previous call
// to RecomputeDirty had caused the file to be stat'ed. Because previous
// invocations of RecomputeDirty would have seen this node without an
// input edge (and therefore ready), we have to set outputs_ready_ to true
// to avoid a potential stuck build. If we do call RecomputeDirty for
// this node, it will simply set outputs_ready_ to the correct value.
phony_edge->outputs_ready_ = true;
}
}
return true;
}
void Edge::Dump(const char* prefix) const {
printf("%s[ ", prefix);
for (vector<Node*>::const_iterator i = inputs_.begin();
i != inputs_.end() && *i != NULL; ++i) {
printf("%s ", (*i)->path().c_str());
}
printf("--%s-> ", rule_->name().c_str());
for (vector<Node*>::const_iterator i = outputs_.begin();
i != outputs_.end() && *i != NULL; ++i) {
printf("%s ", (*i)->path().c_str());
}
printf("] 0x%p\n", this);
}
bool Edge::is_phony() const {
return rule_ == &State::kPhonyRule;
}
void Node::Dump(const char* prefix) const {
printf("%s <%s 0x%p> mtime: %d%s, (:%s), ",
prefix, path().c_str(), this,
mtime(), mtime() ? "" : " (:missing)",
dirty() ? " dirty" : " clean");
if (in_edge()) {
in_edge()->Dump("in-edge: ");
} else {
printf("no in-edge\n");
}
printf(" out edges:\n");
for (vector<Edge*>::const_iterator e = out_edges().begin();
e != out_edges().end() && *e != NULL; ++e) {
(*e)->Dump(" +- ");
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
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 the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/assert.hpp"
#include "zlib.h"
#include <vector>
#include <string>
namespace
{
enum
{
FTEXT = 0x01,
FHCRC = 0x02,
FEXTRA = 0x04,
FNAME = 0x08,
FCOMMENT = 0x10,
FRESERVED = 0xe0,
GZIP_MAGIC0 = 0x1f,
GZIP_MAGIC1 = 0x8b
};
}
namespace libtorrent
{
// returns -1 if gzip header is invalid or the header size in bytes
int gzip_header(const char* buf, int size)
{
TORRENT_ASSERT(buf != 0);
TORRENT_ASSERT(size > 0);
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf);
const int total_size = size;
// The zip header cannot be shorter than 10 bytes
if (size < 10) return -1;
// check the magic header of gzip
if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1;
int method = buffer[2];
int flags = buffer[3];
// check for reserved flag and make sure it's compressed with the correct metod
if (method != Z_DEFLATED || (flags & FRESERVED) != 0) return -1;
// skip time, xflags, OS code
size -= 10;
buffer += 10;
if (flags & FEXTRA)
{
int extra_len;
if (size < 2) return -1;
extra_len = (buffer[1] << 8) | buffer[0];
if (size < (extra_len+2)) return -1;
size -= (extra_len + 2);
buffer += (extra_len + 2);
}
if (flags & FNAME)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FCOMMENT)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FHCRC)
{
if (size < 2) return -1;
size -= 2;
buffer += 2;
}
return total_size - size;
}
bool inflate_gzip(
char const* in
, int size
, std::vector<char>& buffer
, int maximum_size
, std::string& error)
{
TORRENT_ASSERT(maximum_size > 0);
int header_len = gzip_header(in, size);
if (header_len < 0)
{
error = "invalid gzip header in tracker response";
return true;
}
// start off with one kilobyte and grow
// if needed
buffer.resize(1024);
// initialize the zlib-stream
z_stream str;
// subtract 8 from the end of the buffer since that's CRC32 and input size
// and those belong to the gzip file
str.avail_in = (int)size - header_len - 8;
str.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(in + header_len));
str.next_out = reinterpret_cast<Bytef*>(&buffer[0]);
str.avail_out = (int)buffer.size();
str.zalloc = Z_NULL;
str.zfree = Z_NULL;
str.opaque = 0;
// -15 is really important. It will make inflate() not look for a zlib header
// and just deflate the buffer
if (inflateInit2(&str, -15) != Z_OK)
{
error = "gzip out of memory";
return true;
}
// inflate and grow inflate_buffer as needed
int ret = inflate(&str, Z_SYNC_FLUSH);
while (ret == Z_OK)
{
if (str.avail_out == 0)
{
if (buffer.size() >= (unsigned)maximum_size)
{
inflateEnd(&str);
error = "response too large";
return true;
}
int new_size = (int)buffer.size() * 2;
if (new_size > maximum_size)
new_size = maximum_size;
int old_size = (int)buffer.size();
buffer.resize(new_size);
str.next_out = reinterpret_cast<Bytef*>(&buffer[old_size]);
str.avail_out = new_size - old_size;
}
ret = inflate(&str, Z_SYNC_FLUSH);
}
buffer.resize(buffer.size() - str.avail_out);
inflateEnd(&str);
if (ret != Z_STREAM_END)
{
error = "gzip error";
return true;
}
// commit the resulting buffer
return false;
}
}
<commit_msg>removed invalid assert<commit_after>/*
Copyright (c) 2007, Arvid Norberg
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 the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/assert.hpp"
#include "zlib.h"
#include <vector>
#include <string>
namespace
{
enum
{
FTEXT = 0x01,
FHCRC = 0x02,
FEXTRA = 0x04,
FNAME = 0x08,
FCOMMENT = 0x10,
FRESERVED = 0xe0,
GZIP_MAGIC0 = 0x1f,
GZIP_MAGIC1 = 0x8b
};
}
namespace libtorrent
{
// returns -1 if gzip header is invalid or the header size in bytes
int gzip_header(const char* buf, int size)
{
TORRENT_ASSERT(buf != 0);
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf);
const int total_size = size;
// The zip header cannot be shorter than 10 bytes
if (size < 10) return -1;
// check the magic header of gzip
if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1;
int method = buffer[2];
int flags = buffer[3];
// check for reserved flag and make sure it's compressed with the correct metod
if (method != Z_DEFLATED || (flags & FRESERVED) != 0) return -1;
// skip time, xflags, OS code
size -= 10;
buffer += 10;
if (flags & FEXTRA)
{
int extra_len;
if (size < 2) return -1;
extra_len = (buffer[1] << 8) | buffer[0];
if (size < (extra_len+2)) return -1;
size -= (extra_len + 2);
buffer += (extra_len + 2);
}
if (flags & FNAME)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FCOMMENT)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FHCRC)
{
if (size < 2) return -1;
size -= 2;
buffer += 2;
}
return total_size - size;
}
bool inflate_gzip(
char const* in
, int size
, std::vector<char>& buffer
, int maximum_size
, std::string& error)
{
TORRENT_ASSERT(maximum_size > 0);
int header_len = gzip_header(in, size);
if (header_len < 0)
{
error = "invalid gzip header in tracker response";
return true;
}
// start off with one kilobyte and grow
// if needed
buffer.resize(1024);
// initialize the zlib-stream
z_stream str;
// subtract 8 from the end of the buffer since that's CRC32 and input size
// and those belong to the gzip file
str.avail_in = (int)size - header_len - 8;
str.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(in + header_len));
str.next_out = reinterpret_cast<Bytef*>(&buffer[0]);
str.avail_out = (int)buffer.size();
str.zalloc = Z_NULL;
str.zfree = Z_NULL;
str.opaque = 0;
// -15 is really important. It will make inflate() not look for a zlib header
// and just deflate the buffer
if (inflateInit2(&str, -15) != Z_OK)
{
error = "gzip out of memory";
return true;
}
// inflate and grow inflate_buffer as needed
int ret = inflate(&str, Z_SYNC_FLUSH);
while (ret == Z_OK)
{
if (str.avail_out == 0)
{
if (buffer.size() >= (unsigned)maximum_size)
{
inflateEnd(&str);
error = "response too large";
return true;
}
int new_size = (int)buffer.size() * 2;
if (new_size > maximum_size)
new_size = maximum_size;
int old_size = (int)buffer.size();
buffer.resize(new_size);
str.next_out = reinterpret_cast<Bytef*>(&buffer[old_size]);
str.avail_out = new_size - old_size;
}
ret = inflate(&str, Z_SYNC_FLUSH);
}
buffer.resize(buffer.size() - str.avail_out);
inflateEnd(&str);
if (ret != Z_STREAM_END)
{
error = "gzip error";
return true;
}
// commit the resulting buffer
return false;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2018 The Bitcoin Unlimited developers
Copyright (c) 2014 Gavin Andresen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "iblt.h"
#include "hash.h"
#include "iblt_params.h"
#include <cassert>
#include <iostream>
#include <list>
#include <sstream>
#include <utility>
static const size_t N_HASHCHECK = 11;
// mask that can be reduced to reduce the number of checksum bits in the IBLT
// -- ANY VALUE OTHER THAN 0xffffffff IS FOR TESTING ONLY! --
static const uint32_t KEYCHECK_MASK = 0xffffffff;
static inline uint32_t keyChecksumCalc(const std::vector<uint8_t> &kvec)
{
return MurmurHash3(N_HASHCHECK, kvec) & KEYCHECK_MASK;
}
template <typename T>
std::vector<uint8_t> ToVec(T number)
{
std::vector<uint8_t> v(sizeof(T));
for (size_t i = 0; i < sizeof(T); i++)
{
v.at(i) = (number >> i * 8) & 0xff;
}
return v;
}
bool HashTableEntry::isPure() const
{
if (count == 1 || count == -1)
{
uint32_t check = keyChecksumCalc(ToVec(keySum));
return (keyCheck == check);
}
return false;
}
bool HashTableEntry::empty() const { return (count == 0 && keySum == 0 && keyCheck == 0); }
void HashTableEntry::addValue(const std::vector<uint8_t> &v)
{
if (v.empty())
{
return;
}
if (valueSum.size() < v.size())
{
valueSum.resize(v.size());
}
for (size_t i = 0; i < v.size(); i++)
{
valueSum[i] ^= v[i];
}
}
CIblt::CIblt()
{
n_hash = 1;
is_modified = false;
version = 0;
}
CIblt::CIblt(size_t _expectedNumEntries) : is_modified(false), version(0) { CIblt::resize(_expectedNumEntries); }
CIblt::CIblt(const CIblt &other) : is_modified(false), version(0)
{
n_hash = other.n_hash;
hashTable = other.hashTable;
}
CIblt::~CIblt() {}
void CIblt::reset()
{
size_t size = this->size();
hashTable.clear();
hashTable.resize(size);
is_modified = false;
}
uint64_t CIblt::size() { return hashTable.size(); }
void CIblt::resize(size_t _expectedNumEntries)
{
assert(is_modified == false);
CIblt::n_hash = OptimalNHash(_expectedNumEntries);
// reduce probability of failure by increasing by overhead factor
size_t nEntries = (size_t)(_expectedNumEntries * OptimalOverhead(_expectedNumEntries));
// ... make nEntries exactly divisible by n_hash
while (n_hash * (nEntries / n_hash) != nEntries)
++nEntries;
hashTable.resize(nEntries);
}
void CIblt::_insert(int plusOrMinus, uint64_t k, const std::vector<uint8_t> &v)
{
if (!n_hash)
return;
size_t bucketsPerHash = hashTable.size() / n_hash;
if (!bucketsPerHash)
return;
std::vector<uint8_t> kvec = ToVec(k);
const uint32_t kchk = keyChecksumCalc(kvec);
for (size_t i = 0; i < n_hash; i++)
{
size_t startEntry = i * bucketsPerHash;
uint32_t h = MurmurHash3(i, kvec);
HashTableEntry &entry = hashTable.at(startEntry + (h % bucketsPerHash));
entry.count += plusOrMinus;
entry.keySum ^= k;
entry.keyCheck ^= kchk;
if (entry.empty())
{
entry.valueSum.clear();
}
else
{
entry.addValue(v);
}
}
is_modified = true;
}
void CIblt::insert(uint64_t k, const std::vector<uint8_t> &v) { _insert(1, k, v); }
void CIblt::erase(uint64_t k, const std::vector<uint8_t> &v) { _insert(-1, k, v); }
bool CIblt::get(uint64_t k, std::vector<uint8_t> &result) const
{
result.clear();
if (!n_hash)
return false;
size_t bucketsPerHash = hashTable.size() / n_hash;
if (!bucketsPerHash)
return false;
std::vector<uint8_t> kvec = ToVec(k);
for (size_t i = 0; i < n_hash; i++)
{
size_t startEntry = i * bucketsPerHash;
uint32_t h = MurmurHash3(i, kvec);
const HashTableEntry &entry = hashTable.at(startEntry + (h % bucketsPerHash));
if (entry.empty())
{
// Definitely not in table. Leave
// result empty, return true.
return true;
}
else if (entry.isPure())
{
if (entry.keySum == k)
{
// Found!
result.assign(entry.valueSum.begin(), entry.valueSum.end());
return true;
}
else
{
// Definitely not in table.
return true;
}
}
}
// Don't know if k is in table or not; "peel" the IBLT to try to find
// it:
CIblt peeled = *this;
size_t nErased = 0;
for (size_t i = 0; i < peeled.hashTable.size(); i++)
{
HashTableEntry &entry = peeled.hashTable.at(i);
if (entry.isPure())
{
if (entry.keySum == k)
{
// Found!
result.assign(entry.valueSum.begin(), entry.valueSum.end());
return true;
}
++nErased;
// NOTE: Need to create a copy of valueSum here as entry is just a reference!
std::vector<uint8_t> vec = entry.valueSum;
peeled._insert(-entry.count, entry.keySum, vec);
}
}
if (nErased > 0)
{
// Recurse with smaller IBLT
return peeled.get(k, result);
}
return false;
}
bool CIblt::listEntries(std::set<std::pair<uint64_t, std::vector<uint8_t> > > &positive,
std::set<std::pair<uint64_t, std::vector<uint8_t> > > &negative) const
{
CIblt peeled = *this;
size_t nErased = 0;
do
{
nErased = 0;
for (size_t i = 0; i < peeled.hashTable.size(); i++)
{
HashTableEntry &entry = peeled.hashTable.at(i);
if (entry.isPure())
{
if (entry.count == 1)
{
positive.insert(std::make_pair(entry.keySum, entry.valueSum));
}
else
{
negative.insert(std::make_pair(entry.keySum, entry.valueSum));
}
// NOTE: Need to create a copy of valueSum here as entry is just a reference!
std::vector<uint8_t> vec = entry.valueSum;
peeled._insert(-entry.count, entry.keySum, vec);
++nErased;
}
}
} while (nErased > 0);
if (!n_hash)
return false;
size_t peeled_bucketsPerHash = peeled.hashTable.size() / n_hash;
if (!peeled_bucketsPerHash)
return false;
// If any buckets for one of the hash functions is not empty,
// then we didn't peel them all:
for (size_t i = 0; i < peeled_bucketsPerHash; i++)
{
if (peeled.hashTable.at(i).empty() != true)
return false;
}
return true;
}
CIblt CIblt::operator-(const CIblt &other) const
{
// IBLT's must be same params/size:
assert(hashTable.size() == other.hashTable.size());
CIblt result(*this);
for (size_t i = 0; i < hashTable.size(); i++)
{
HashTableEntry &e1 = result.hashTable.at(i);
const HashTableEntry &e2 = other.hashTable.at(i);
e1.count -= e2.count;
e1.keySum ^= e2.keySum;
e1.keyCheck ^= e2.keyCheck;
if (e1.empty())
{
e1.valueSum.clear();
}
else
{
e1.addValue(e2.valueSum);
}
}
return result;
}
// For debugging during development:
std::string CIblt::DumpTable() const
{
std::ostringstream result;
result << "count keySum keyCheckMatch\n";
for (size_t i = 0; i < hashTable.size(); i++)
{
const HashTableEntry &entry = hashTable.at(i);
result << entry.count << " " << entry.keySum << " ";
result << (keyChecksumCalc(ToVec(entry.keySum)) == entry.keyCheck ? "true" : "false");
result << "\n";
}
return result.str();
}
size_t CIblt::OptimalNHash(size_t expectedNumEntries) { return CIbltParams::Lookup(expectedNumEntries).numhashes; }
float CIblt::OptimalOverhead(size_t expectedNumEntries) { return CIbltParams::Lookup(expectedNumEntries).overhead; }
<commit_msg>iblt: ensure peeling process eventually halts (#1223)<commit_after>/*
Copyright (c) 2018 The Bitcoin Unlimited developers
Copyright (c) 2014 Gavin Andresen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "iblt.h"
#include "hash.h"
#include "iblt_params.h"
#include <cassert>
#include <iostream>
#include <list>
#include <sstream>
#include <utility>
static const size_t N_HASHCHECK = 11;
// It's extremely unlikely that an IBLT will decode with fewer
// than 1 cell for every 10 items.
static const float MIN_OVERHEAD = 0.1;
// mask that can be reduced to reduce the number of checksum bits in the IBLT
// -- ANY VALUE OTHER THAN 0xffffffff IS FOR TESTING ONLY! --
static const uint32_t KEYCHECK_MASK = 0xffffffff;
static inline uint32_t keyChecksumCalc(const std::vector<uint8_t> &kvec)
{
return MurmurHash3(N_HASHCHECK, kvec) & KEYCHECK_MASK;
}
template <typename T>
std::vector<uint8_t> ToVec(T number)
{
std::vector<uint8_t> v(sizeof(T));
for (size_t i = 0; i < sizeof(T); i++)
{
v.at(i) = (number >> i * 8) & 0xff;
}
return v;
}
bool HashTableEntry::isPure() const
{
if (count == 1 || count == -1)
{
uint32_t check = keyChecksumCalc(ToVec(keySum));
return (keyCheck == check);
}
return false;
}
bool HashTableEntry::empty() const { return (count == 0 && keySum == 0 && keyCheck == 0); }
void HashTableEntry::addValue(const std::vector<uint8_t> &v)
{
if (v.empty())
{
return;
}
if (valueSum.size() < v.size())
{
valueSum.resize(v.size());
}
for (size_t i = 0; i < v.size(); i++)
{
valueSum[i] ^= v[i];
}
}
CIblt::CIblt()
{
n_hash = 1;
is_modified = false;
version = 0;
}
CIblt::CIblt(size_t _expectedNumEntries) : is_modified(false), version(0) { CIblt::resize(_expectedNumEntries); }
CIblt::CIblt(const CIblt &other) : is_modified(false), version(0)
{
n_hash = other.n_hash;
hashTable = other.hashTable;
}
CIblt::~CIblt() {}
void CIblt::reset()
{
size_t size = this->size();
hashTable.clear();
hashTable.resize(size);
is_modified = false;
}
uint64_t CIblt::size() { return hashTable.size(); }
void CIblt::resize(size_t _expectedNumEntries)
{
assert(is_modified == false);
CIblt::n_hash = OptimalNHash(_expectedNumEntries);
// reduce probability of failure by increasing by overhead factor
size_t nEntries = (size_t)(_expectedNumEntries * OptimalOverhead(_expectedNumEntries));
// ... make nEntries exactly divisible by n_hash
while (n_hash * (nEntries / n_hash) != nEntries)
++nEntries;
hashTable.resize(nEntries);
}
void CIblt::_insert(int plusOrMinus, uint64_t k, const std::vector<uint8_t> &v)
{
if (!n_hash)
return;
size_t bucketsPerHash = hashTable.size() / n_hash;
if (!bucketsPerHash)
return;
std::vector<uint8_t> kvec = ToVec(k);
const uint32_t kchk = keyChecksumCalc(kvec);
for (size_t i = 0; i < n_hash; i++)
{
size_t startEntry = i * bucketsPerHash;
uint32_t h = MurmurHash3(i, kvec);
HashTableEntry &entry = hashTable.at(startEntry + (h % bucketsPerHash));
entry.count += plusOrMinus;
entry.keySum ^= k;
entry.keyCheck ^= kchk;
if (entry.empty())
{
entry.valueSum.clear();
}
else
{
entry.addValue(v);
}
}
is_modified = true;
}
void CIblt::insert(uint64_t k, const std::vector<uint8_t> &v) { _insert(1, k, v); }
void CIblt::erase(uint64_t k, const std::vector<uint8_t> &v) { _insert(-1, k, v); }
bool CIblt::get(uint64_t k, std::vector<uint8_t> &result) const
{
result.clear();
if (!n_hash)
return false;
size_t bucketsPerHash = hashTable.size() / n_hash;
if (!bucketsPerHash)
return false;
std::vector<uint8_t> kvec = ToVec(k);
for (size_t i = 0; i < n_hash; i++)
{
size_t startEntry = i * bucketsPerHash;
uint32_t h = MurmurHash3(i, kvec);
const HashTableEntry &entry = hashTable.at(startEntry + (h % bucketsPerHash));
if (entry.empty())
{
// Definitely not in table. Leave
// result empty, return true.
return true;
}
else if (entry.isPure())
{
if (entry.keySum == k)
{
// Found!
result.assign(entry.valueSum.begin(), entry.valueSum.end());
return true;
}
else
{
// Definitely not in table.
return true;
}
}
}
// Don't know if k is in table or not; "peel" the IBLT to try to find
// it:
CIblt peeled = *this;
size_t nErased = 0;
for (size_t i = 0; i < peeled.hashTable.size(); i++)
{
HashTableEntry &entry = peeled.hashTable.at(i);
if (entry.isPure())
{
if (entry.keySum == k)
{
// Found!
result.assign(entry.valueSum.begin(), entry.valueSum.end());
return true;
}
++nErased;
// NOTE: Need to create a copy of valueSum here as entry is just a reference!
std::vector<uint8_t> vec = entry.valueSum;
peeled._insert(-entry.count, entry.keySum, vec);
}
}
if (nErased > 0)
{
// Recurse with smaller IBLT
return peeled.get(k, result);
}
return false;
}
bool CIblt::listEntries(std::set<std::pair<uint64_t, std::vector<uint8_t> > > &positive,
std::set<std::pair<uint64_t, std::vector<uint8_t> > > &negative) const
{
CIblt peeled = *this;
size_t nErased = 0;
size_t nTotalErased = 0;
do
{
nErased = 0;
for (size_t i = 0; i < peeled.hashTable.size(); i++)
{
HashTableEntry &entry = peeled.hashTable.at(i);
if (entry.isPure())
{
if (entry.count == 1)
{
positive.insert(std::make_pair(entry.keySum, entry.valueSum));
}
else
{
negative.insert(std::make_pair(entry.keySum, entry.valueSum));
}
// NOTE: Need to create a copy of valueSum here as entry is just a reference!
std::vector<uint8_t> vec = entry.valueSum;
peeled._insert(-entry.count, entry.keySum, vec);
++nErased;
}
}
nTotalErased += nErased;
} while (nErased > 0 && nTotalErased < peeled.hashTable.size() / MIN_OVERHEAD);
if (!n_hash)
return false;
size_t peeled_bucketsPerHash = peeled.hashTable.size() / n_hash;
if (!peeled_bucketsPerHash)
return false;
// If any buckets for one of the hash functions is not empty,
// then we didn't peel them all:
for (size_t i = 0; i < peeled_bucketsPerHash; i++)
{
if (peeled.hashTable.at(i).empty() != true)
return false;
}
return true;
}
CIblt CIblt::operator-(const CIblt &other) const
{
// IBLT's must be same params/size:
assert(hashTable.size() == other.hashTable.size());
CIblt result(*this);
for (size_t i = 0; i < hashTable.size(); i++)
{
HashTableEntry &e1 = result.hashTable.at(i);
const HashTableEntry &e2 = other.hashTable.at(i);
e1.count -= e2.count;
e1.keySum ^= e2.keySum;
e1.keyCheck ^= e2.keyCheck;
if (e1.empty())
{
e1.valueSum.clear();
}
else
{
e1.addValue(e2.valueSum);
}
}
return result;
}
// For debugging during development:
std::string CIblt::DumpTable() const
{
std::ostringstream result;
result << "count keySum keyCheckMatch\n";
for (size_t i = 0; i < hashTable.size(); i++)
{
const HashTableEntry &entry = hashTable.at(i);
result << entry.count << " " << entry.keySum << " ";
result << (keyChecksumCalc(ToVec(entry.keySum)) == entry.keyCheck ? "true" : "false");
result << "\n";
}
return result.str();
}
size_t CIblt::OptimalNHash(size_t expectedNumEntries) { return CIbltParams::Lookup(expectedNumEntries).numhashes; }
float CIblt::OptimalOverhead(size_t expectedNumEntries) { return CIbltParams::Lookup(expectedNumEntries).overhead; }
<|endoftext|> |
<commit_before>/**
* @file CommunicationLayer.hpp
* @ingroup index
* @author Patrick Flick <patrick.flick@gmail.com>
* @author Tony Pan <tpan@gatech.edu>
* @brief descr
*
* Copyright (c) TODO
*
* TODO add Licence
*/
#ifndef BLISS_COMMUNICATION_LAYER_HPP
#define BLISS_COMMUNICATION_LAYER_HPP
#include <mpi.h>
//#include <omp.h>
// C stdlib includes
#include <assert.h>
// STL includes
#include <vector>
#include <queue>
#include <mutex>
// system includes
// TODO: make this system indepenedent!?
#include <unistd.h> // for usleep()
// BLISS includes
#include <concurrent/threadsafe_queue.hpp>
#include <concurrent/concurrent.hpp>
#include <io/message_buffers.hpp>
typedef bliss::io::MessageBuffers<bliss::concurrent::THREAD_SAFE> BuffersType;
struct ReceivedMessage
{
uint8_t* data;
std::size_t count;
int tag;
int src;
ReceivedMessage(uint8_t* data, std::size_t count, int tag, int src)
: data(data), count(count), tag(tag), src(src) {}
ReceivedMessage() = default;
};
// TODO: rename (either this or the ReceivedMessage) for identical naming scheme
struct SendQueueElement
{
typename bliss::io::MessageBuffers<bliss::concurrent::THREAD_SAFE>::BufferIdType bufferId;
int tag;
int dst;
SendQueueElement(bliss::io::MessageBuffers<bliss::concurrent::THREAD_SAFE>::BufferIdType _id, int _tag, int _dst)
: bufferId(_id), tag(_tag), dst(_dst) {}
SendQueueElement() = delete;
};
class CommunicationLayer
{
public:
constexpr static int default_tag = 0;
protected:
// request, data pointer, data size
std::queue<std::pair<MPI_Request, ReceivedMessage> > recvInProgress;
// request, data pointer, tag
std::queue<std::pair<MPI_Request, SendQueueElement> > sendInProgress;
/// Outbound message structure, Multiple-Producer-Single-Consumer queue
/// consumed by the internal MPI-comm thread
bliss::concurrent::ThreadSafeQueue<SendQueueElement> sendQueue;
// Inbound message structure, Single-Producer-Multiple-Consumer queue
// produced by the internal MPI-comm thread
bliss::concurrent::ThreadSafeQueue<ReceivedMessage> recvQueue;
// outbound temporary data buffer type for the producer threads. ThreadSafe version for now.
typedef bliss::io::MessageBuffers<bliss::concurrent::THREAD_SAFE> BuffersType;
// outbound temporary data buffers. one per tag.
std::unordered_map<int, BuffersType> buffers;
typedef typename bliss::io::MessageBuffers<bliss::concurrent::THREAD_SAFE>::BufferIdType BufferIdType;
mutable std::mutex mutex;
public:
CommunicationLayer (const MPI_Comm& communicator, const int comm_size)
: sendQueue(2 * omp_get_num_threads()), recvQueue(2 * comm_size),
comm(communicator)
{
// init communicator rank and size
MPI_Comm_size(comm, &commSize);
assert(comm_size == commSize);
MPI_Comm_rank(comm, &commRank);
}
virtual ~CommunicationLayer ();
void sendMessage(const void* data, std::size_t count, int dst_rank, int tag=default_tag)
{
/// if there isn't already a tag listed, add the MessageBuffers for that tag.
// multiple threads may call this.
std::unique_lock<std::mutex> lock(mutex);
if (buffers.find(tag) == buffers.end())
buffers[tag] = std::move(BuffersType(commSize, 8192));
lock.unlock();
/// try to append the new data - repeat until successful.
/// along the way, if a full buffer's id is returned, queue it for send.
BufferIdType fullId = -1;
while (!buffers[tag].append(data, count, dst_rank, fullId)) {
// repeat until success;
if (fullId != -1) {
// have a full buffer - put in send queue.
SendQueueElement v(fullId, tag, dst_rank);
while (!sendQueue.tryPush(std::move(v))) {
usleep(20);
}
}
usleep(20);
}
/// that's it.
}
void flush(int tag)
{
// flush out all the send buffers matching a particular tag.
int i = 0;
for (auto id : buffers[tag].getActiveIds()) {
if (id != -1) {
SendQueueElement v(id, tag, i);
while (!sendQueue.tryPush(std::move(v))) {
usleep(20);
}
}
}
}
//
void commThread()
{
// TODO: implement termination condition
while(true)
{
// first clean up finished operations
finishReceives();
finishSends();
// start pending receives
tryStartReceive();
// start pending sends
tryStartSend();
}
}
void tryStartReceive()
{
/// probe for messages
int hasMessage = 0;
MPI_Status status;
MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, comm, &hasMessage, &status);
if (hasMessage > 0) {
int src = status.MPI_SOURCE;
int tag = status.MPI_TAG;
int received_count;
MPI_Get_count(&status, MPI_UNSIGNED_CHAR, &received_count);
/*
if (tag == MPIBufferType::END_TAG) {
// end of messaging.
MPI_Recv(nullptr, received_count, MPI_UNSIGNED_CHAR, src, tag, comm, MPI_STATUS_IGNORE);
#pragma omp atomic
--mpi_senders;
printf("RECV rank %d receiving END signal %d from %d, num sanders remaining is %d\n", rank, received, src, mpi_senders);
#pragma omp flush(mpi_senders)
} else {
*/
// receive the message data bytes into a vector of bytes
uint8_t* msg_data = new uint8_t[received_count];
MPI_Request req;
MPI_Irecv(msg_data, received_count, MPI_UNSIGNED_CHAR, src, tag, comm, &req);
// insert into the in-progress queue
std::tuple<MPI_Request, ReceivedMessage> msg(req, ReceivedMessage(msg_data, received_count, tag, src));
recvInProgress.push(std::move(msg));
// }
}
}
void tryStartSend()
{
// try to get the send element
SendQueueElement se;
if (sendQueue.tryPop(se)) {
auto data = buffers[se.tag].getBackBuffer(se.bufferId).getData();
auto count = buffers[se.tag].getBackBuffer(se.bufferId).getSize();
if (se.dst == commRank) {
// local, directly handle by creating an output object and directly
// insert into the recv queue
uint8_t* array = new uint8_t[count];
memcpy(array, data, count);
ReceivedMessage msg(array, count, se.tag, se.dst);
while(!recvQueue.tryPush(std::move(msg))) {
usleep(50);
}
// finished inserting. release the buffer
buffers[se.tag].releaseBuffer(se.bufferId);
} else {
MPI_Request req;
MPI_Isend(data, count, MPI_UINT8_T, se.dst, se.tag, comm, &req);
sendInProgress.push(std::move(std::pair<MPI_Request, SendQueueElement>(req, se)));
}
}
}
void finishSends()
{
int finished = 0;
while(!sendInProgress.empty())
{
std::pair<MPI_Request, SendQueueElement>& front = sendInProgress.front();
MPI_Test(&front.first, &finished, MPI_STATUS_IGNORE);
if (finished)
{
// cleanup, i.e., release the buffer back into the pool
buffers[front.second.tag].releaseBuffer(front.second.bufferId);
sendInProgress.pop();
}
else
{
break;
}
}
}
// Not thread safe
void finishReceives()
{
int finished = 0;
MPI_Status status;
while(!recvInProgress.empty())
{
std::pair<MPI_Request, ReceivedMessage>& front = recvInProgress.front();
MPI_Test(&std::get<0>(front), &finished, &status);
if (finished)
{
assert(front.second.tag == status.MPI_TAG);
assert(front.second.src == status.MPI_SOURCE);
// add the received messages into the recvQueue
// ReceivedMessage msg(std::get<1>(front), std::get<2>(front),
// status.MPI_TAG, status.MPI_SOURCE);
// TODO: (maybe) one queue per tag?? Where does this
// sorting/categorizing happen?
while (!recvQueue.tryPush(std::move(front.second))) {
usleep(50);
}
// remove moved element
recvInProgress.pop();
}
else
{
// stop receiving for now
break;
}
}
}
int getCommSize() const
{
return commSize;
}
int getCommRank() const
{
return commRank;
}
void callbackThread()
{
// TODO: add termination condition
while(true)
{
// get next element from the queue, wait if none is available
ReceivedMessage msg;
recvQueue.waitAndPop(msg);
// TODO: check if the tag exists as callback function
// call the matching callback function
(callbackFunctions[msg.tag])(msg.data, msg.count, msg.src);
delete [] msg.data;
}
}
// adding the callback function with signature:
// void(uint8_t* msg, std::size_t count, int fromRank)
void addReceiveCallback(int tag, std::function<void(uint8_t*, std::size_t, int)> callbackFunction)
{
if (callbackFunctions.empty())
{
// this is the first registered callback, thus spawn the callback
// executer thread
// TODO
}
// add the callback function to a lookup table
callbackFunctions[tag] = callbackFunction;
}
/*
// active receiving (by polling) for when there is no callback set
// these must be thread-safe!
Message receiveAnyOne();
std::vector<message> receiveAnyAll();
Message receiveOne(tag);
std::vector<message> receiveAll(tag);
*/
private:
/* data */
/// The MPI Communicator object for this communication layer
MPI_Comm comm;
/// Registry of callback functions, mapped to by the associated tags
std::map<int,std::function<void(uint8_t*, std::size_t, int)> > callbackFunctions;
/// The MPI Communicator size
int commSize;
/// The MPI Communicator rank
int commRank;
};
#endif // BLISS_COMMUNICATION_LAYER_HPP
<commit_msg>WIP: CommLayer stop conditions.<commit_after>/**
* @file CommunicationLayer.hpp
* @ingroup index
* @author Patrick Flick <patrick.flick@gmail.com>
* @author Tony Pan <tpan@gatech.edu>
* @brief descr
*
* Copyright (c) TODO
*
* TODO add Licence
*/
#ifndef BLISS_COMMUNICATION_LAYER_HPP
#define BLISS_COMMUNICATION_LAYER_HPP
#include <mpi.h>
//#include <omp.h>
// C stdlib includes
#include <assert.h>
// STL includes
#include <vector>
#include <queue>
#include <mutex>
// system includes
// TODO: make this system indepenedent!?
#include <unistd.h> // for usleep()
// BLISS includes
#include <concurrent/threadsafe_queue.hpp>
#include <concurrent/concurrent.hpp>
#include <io/message_buffers.hpp>
typedef bliss::io::MessageBuffers<bliss::concurrent::THREAD_SAFE> BuffersType;
struct ReceivedMessage
{
uint8_t* data;
std::size_t count;
int tag;
int src;
ReceivedMessage(uint8_t* data, std::size_t count, int tag, int src)
: data(data), count(count), tag(tag), src(src) {}
ReceivedMessage() = default;
};
// TODO: rename (either this or the ReceivedMessage) for identical naming scheme
struct SendQueueElement
{
typename BuffersType::BufferIdType bufferId;
int tag;
int dst;
SendQueueElement(BuffersType::BufferIdType _id, int _tag, int _dst)
: bufferId(_id), tag(_tag), dst(_dst) {}
SendQueueElement() = delete;
};
class CommunicationLayer
{
public:
constexpr static int default_tag = 0;
protected:
// request, data pointer, data size
std::queue<std::pair<MPI_Request, ReceivedMessage> > recvInProgress;
// request, data pointer, tag
std::queue<std::pair<MPI_Request, SendQueueElement> > sendInProgress;
/// Outbound message structure, Multiple-Producer-Single-Consumer queue
/// consumed by the internal MPI-comm thread
bliss::concurrent::ThreadSafeQueue<SendQueueElement> sendQueue;
// Inbound message structure, Single-Producer-Multiple-Consumer queue
// produced by the internal MPI-comm thread
bliss::concurrent::ThreadSafeQueue<ReceivedMessage> recvQueue;
// outbound temporary data buffer type for the producer threads. ThreadSafe version for now.
typedef BuffersType BuffersType;
// outbound temporary data buffers. one per tag.
std::unordered_map<int, BuffersType> buffers;
typedef typename BuffersType::BufferIdType BufferIdType;
mutable std::mutex mutex;
public:
CommunicationLayer (const MPI_Comm& communicator, const int comm_size)
: sendQueue(2 * omp_get_num_threads()), recvQueue(2 * comm_size),
comm(communicator)
{
// init communicator rank and size
MPI_Comm_size(comm, &commSize);
assert(comm_size == commSize);
MPI_Comm_rank(comm, &commRank);
}
virtual ~CommunicationLayer ();
void sendMessage(const void* data, std::size_t count, int dst_rank, int tag=default_tag)
{
/// if there isn't already a tag listed, add the MessageBuffers for that tag.
// multiple threads may call this.
std::unique_lock<std::mutex> lock(mutex);
if (buffers.find(tag) == buffers.end())
buffers[tag] = std::move(BuffersType(commSize, 8192));
lock.unlock();
/// try to append the new data - repeat until successful.
/// along the way, if a full buffer's id is returned, queue it for send.
BufferIdType fullId = -1;
while (!buffers[tag].append(data, count, dst_rank, fullId)) {
// repeat until success;
if (fullId != -1) {
// have a full buffer - put in send queue.
SendQueueElement v(fullId, tag, dst_rank);
// while (!sendQueue.tryPush(std::move(v))) {
// usleep(20);
// }
sendQueue.waitAndPush(std::move(v));
}
usleep(20);
}
/// that's it.
}
void flush(int tag)
{
// flush out all the send buffers matching a particular tag.
int i = 0;
for (auto id : buffers[tag].getActiveIds()) {
if (id != -1) {
SendQueueElement v(id, tag, i);
// while (!sendQueue.tryPush(std::move(v))) {
// usleep(20);
// }
sendQueue.waitAndPush(std::move(v));
}
}
/// mark as no more coming in.
}
//
void commThread()
{
// TODO: implement termination condition
while(true)
{
// first clean up finished operations
finishReceives();
finishSends();
// start pending receives
tryStartReceive();
// start pending sends
tryStartSend();
}
}
void tryStartReceive()
{
/// probe for messages
int hasMessage = 0;
MPI_Status status;
MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, comm, &hasMessage, &status);
if (hasMessage > 0) {
int src = status.MPI_SOURCE;
int tag = status.MPI_TAG;
int received_count;
MPI_Get_count(&status, MPI_UNSIGNED_CHAR, &received_count);
/*
if (tag == MPIBufferType::END_TAG) {
// end of messaging.
MPI_Recv(nullptr, received_count, MPI_UNSIGNED_CHAR, src, tag, comm, MPI_STATUS_IGNORE);
#pragma omp atomic
--mpi_senders;
printf("RECV rank %d receiving END signal %d from %d, num sanders remaining is %d\n", rank, received, src, mpi_senders);
#pragma omp flush(mpi_senders)
} else {
*/
// receive the message data bytes into a vector of bytes
uint8_t* msg_data = new uint8_t[received_count];
MPI_Request req;
MPI_Irecv(msg_data, received_count, MPI_UNSIGNED_CHAR, src, tag, comm, &req);
// insert into the in-progress queue
std::pair<MPI_Request, ReceivedMessage> msg(req, ReceivedMessage(msg_data, received_count, tag, src));
recvInProgress.push(std::move(msg));
// }
}
}
void tryStartSend()
{
// try to get the send element
SendQueueElement se;
if (sendQueue.tryPop(se)) {
auto data = buffers[se.tag].getBackBuffer(se.bufferId).getData();
auto count = buffers[se.tag].getBackBuffer(se.bufferId).getSize();
if (se.dst == commRank) {
// local, directly handle by creating an output object and directly
// insert into the recv queue
uint8_t* array = new uint8_t[count];
memcpy(array, data, count);
ReceivedMessage msg(array, count, se.tag, se.dst);
while(!recvQueue.tryPush(std::move(msg))) {
usleep(50);
}
// finished inserting. release the buffer
buffers[se.tag].releaseBuffer(se.bufferId);
} else {
MPI_Request req;
MPI_Isend(data, count, MPI_UINT8_T, se.dst, se.tag, comm, &req);
sendInProgress.push(std::move(std::pair<MPI_Request, SendQueueElement>(req, se)));
}
}
}
void finishSends()
{
int finished = 0;
while(!sendInProgress.empty())
{
std::pair<MPI_Request, SendQueueElement>& front = sendInProgress.front();
MPI_Test(&front.first, &finished, MPI_STATUS_IGNORE);
if (finished)
{
// cleanup, i.e., release the buffer back into the pool
buffers[front.second.tag].releaseBuffer(front.second.bufferId);
sendInProgress.pop();
}
else
{
break;
}
}
}
// Not thread safe
void finishReceives()
{
int finished = 0;
MPI_Status status;
while(!recvInProgress.empty())
{
std::pair<MPI_Request, ReceivedMessage>& front = recvInProgress.front();
MPI_Test(&std::get<0>(front), &finished, &status);
if (finished)
{
assert(front.second.tag == status.MPI_TAG);
assert(front.second.src == status.MPI_SOURCE);
// add the received messages into the recvQueue
// ReceivedMessage msg(std::get<1>(front), std::get<2>(front),
// status.MPI_TAG, status.MPI_SOURCE);
// TODO: (maybe) one queue per tag?? Where does this
// sorting/categorizing happen?
while (!recvQueue.tryPush(std::move(front.second))) {
usleep(50);
}
// remove moved element
recvInProgress.pop();
}
else
{
// stop receiving for now
break;
}
}
}
int getCommSize() const
{
return commSize;
}
int getCommRank() const
{
return commRank;
}
void callbackThread()
{
// TODO: add termination condition
while(true)
{
// get next element from the queue, wait if none is available
ReceivedMessage msg;
recvQueue.waitAndPop(msg);
// TODO: check if the tag exists as callback function
// call the matching callback function
(callbackFunctions[msg.tag])(msg.data, msg.count, msg.src);
delete [] msg.data;
}
}
// adding the callback function with signature:
// void(uint8_t* msg, std::size_t count, int fromRank)
void addReceiveCallback(int tag, std::function<void(uint8_t*, std::size_t, int)> callbackFunction)
{
if (callbackFunctions.empty())
{
// this is the first registered callback, thus spawn the callback
// executer thread
// TODO
}
// add the callback function to a lookup table
callbackFunctions[tag] = callbackFunction;
}
/*
// active receiving (by polling) for when there is no callback set
// these must be thread-safe!
Message receiveAnyOne();
std::vector<message> receiveAnyAll();
Message receiveOne(tag);
std::vector<message> receiveAll(tag);
*/
private:
/* data */
/// The MPI Communicator object for this communication layer
MPI_Comm comm;
/// Registry of callback functions, mapped to by the associated tags
std::map<int,std::function<void(uint8_t*, std::size_t, int)> > callbackFunctions;
/// The MPI Communicator size
int commSize;
/// The MPI Communicator rank
int commRank;
};
#endif // BLISS_COMMUNICATION_LAYER_HPP
<|endoftext|> |
<commit_before>#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <Log.h>
#include <Call.h>
#include "CodeGen.h"
#include "Compiler.h"
using namespace std;
using namespace llvm;
namespace Snowy
{
const Log Compiler::log = Log("Compiler");
Compiler::Compiler()
{
context = new LLVMContext();
}
Compiler::~Compiler()
{
delete context;
}
Value* Compiler::get_exit_value(Value* last_val)
{
Value* zero = ConstantInt::get(*context, APInt(32, 0, false));
if (last_val == NULL) {
log.debug("Last value was NULL. Setting exit code to 0");
return zero;
}
llvm::Type *retType = last_val->getType();
if (retType->isIntegerTy(32)) {
log.debug("Last value was i32. Setting exit code to last_val");
return last_val;
} else {
log.debug("Last value was not i32. Setting exit code to 0");
return ConstantInt::get(*context, APInt(32, 0, false));
}
}
Module* Compiler::compile(Node* n)
{
log.info("Compiling");
IRBuilder<>* builder = new IRBuilder<>(*context);
Module *TheModule = new Module("org.default", *context);
TheModule->setTargetTriple("x86_64-unknown-linux-gnu");
CodeGen codeGen = CodeGen(builder, TheModule);
llvm::Type* int8_ptr_type = llvm::Type::getInt8PtrTy(*context);
llvm::Type* int32_type = IntegerType::get(*context, 32);
// puts
std::vector<llvm::Type*> puts_args(1, int8_ptr_type);
FunctionType *puts_ft = FunctionType::get(llvm::Type::getInt32Ty(*context), puts_args, false);
Function* puts_fn = Function::Create(puts_ft, Function::ExternalLinkage, "puts", TheModule);
codeGen.registerFunction(puts_fn);
// atoi
Function* atoi_fn = Function::Create(puts_ft, Function::ExternalLinkage, "atoi", TheModule);
codeGen.registerFunction(atoi_fn);
// printf
std::vector<llvm::Type*>printf_ft_args;
printf_ft_args.push_back(int8_ptr_type);
FunctionType* printf_ft = FunctionType::get(int32_type, printf_ft_args, true);
Function* printf_fn = Function::Create(printf_ft, Function::ExternalLinkage, "printf", TheModule);
codeGen.registerFunction(printf_fn);
// main
std::vector<llvm::Type*> main_args;
// int argc
main_args.push_back(IntegerType::get(*context, 32));
// char** argv
PointerType* char_star_type = PointerType::get(IntegerType::get(*context, 8), 0);
PointerType* char_star_arr_type = PointerType::get(char_star_type, 0);
main_args.push_back(char_star_arr_type);
// prototype
FunctionType *main_ft = FunctionType::get(llvm::Type::getInt32Ty(*context), main_args, false);
// function
Function *main_fn = Function::Create(main_ft, Function::ExternalLinkage, "main", TheModule);
Function::arg_iterator args = main_fn->arg_begin();
Value* int32_ac = args++;
int32_ac->setName("argc_val");
Value* ptr_av = args++;
ptr_av->setName("argv_val");
BasicBlock *main_block = BasicBlock::Create(*context, "main_block", main_fn);
builder->SetInsertPoint(main_block);
llvm::Type* mem_type = int32_ac->getType();
ConstantInt* mem_count = builder->getInt32(1);
AllocaInst* mem = builder->CreateAlloca(mem_type, mem_count, "argc");
/* StoreInst* stored = */ builder->CreateStore(int32_ac, mem);
codeGen.registerValue("argc", mem);
Node* current = n;
Value* value = NULL;
while (current != NULL) {
value = current->compile(codeGen);
current = current->getNext();
}
builder->SetInsertPoint(main_block);
builder->CreateRet(get_exit_value(value));
delete builder;
if (log.isLogLevel(DEBUG)) {
TheModule->dump();
}
write(TheModule);
module = TheModule;
return TheModule;
}
void Compiler::write(const Module *m)
{
const char* filename = "program.bc";
log.info("Writing program to '%s'. Compile with clang program.bc -o program", filename);
std::error_code errorInfo;
raw_fd_ostream myfile(filename, errorInfo, llvm::sys::fs::F_None);
WriteBitcodeToFile(m, myfile);
}
}
<commit_msg>Add getenv C function<commit_after>#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <Log.h>
#include <Call.h>
#include "CodeGen.h"
#include "Compiler.h"
using namespace std;
using namespace llvm;
namespace Snowy
{
const Log Compiler::log = Log("Compiler");
Compiler::Compiler()
{
context = new LLVMContext();
}
Compiler::~Compiler()
{
delete context;
}
Value* Compiler::get_exit_value(Value* last_val)
{
Value* zero = ConstantInt::get(*context, APInt(32, 0, false));
if (last_val == NULL) {
log.debug("Last value was NULL. Setting exit code to 0");
return zero;
}
llvm::Type *retType = last_val->getType();
if (retType->isIntegerTy(32)) {
log.debug("Last value was i32. Setting exit code to last_val");
return last_val;
} else {
log.debug("Last value was not i32. Setting exit code to 0");
return ConstantInt::get(*context, APInt(32, 0, false));
}
}
Module* Compiler::compile(Node* n)
{
log.info("Compiling");
IRBuilder<>* builder = new IRBuilder<>(*context);
Module *TheModule = new Module("org.default", *context);
TheModule->setTargetTriple("x86_64-unknown-linux-gnu");
CodeGen codeGen = CodeGen(builder, TheModule);
llvm::Type* int8_ptr_type = llvm::Type::getInt8PtrTy(*context);
llvm::Type* int32_type = IntegerType::get(*context, 32);
// puts
std::vector<llvm::Type*> puts_args(1, int8_ptr_type);
FunctionType *puts_ft = FunctionType::get(llvm::Type::getInt32Ty(*context), puts_args, false);
Function* puts_fn = Function::Create(puts_ft, Function::ExternalLinkage, "puts", TheModule);
codeGen.registerFunction(puts_fn);
// atoi
Function* atoi_fn = Function::Create(puts_ft, Function::ExternalLinkage, "atoi", TheModule);
codeGen.registerFunction(atoi_fn);
// getenv
std::vector<llvm::Type*> getenv_args(1, int8_ptr_type);
FunctionType *getenv_ft = FunctionType::get(int8_ptr_type, getenv_args, false);
Function* getenv_fn = Function::Create(getenv_ft, Function::ExternalLinkage, "getenv", TheModule);
codeGen.registerFunction(getenv_fn);
// printf
std::vector<llvm::Type*>printf_ft_args;
printf_ft_args.push_back(int8_ptr_type);
FunctionType* printf_ft = FunctionType::get(int32_type, printf_ft_args, true);
Function* printf_fn = Function::Create(printf_ft, Function::ExternalLinkage, "printf", TheModule);
codeGen.registerFunction(printf_fn);
// main
std::vector<llvm::Type*> main_args;
// int argc
main_args.push_back(IntegerType::get(*context, 32));
// char** argv
PointerType* char_star_type = PointerType::get(IntegerType::get(*context, 8), 0);
PointerType* char_star_arr_type = PointerType::get(char_star_type, 0);
main_args.push_back(char_star_arr_type);
// prototype
FunctionType *main_ft = FunctionType::get(llvm::Type::getInt32Ty(*context), main_args, false);
// function
Function *main_fn = Function::Create(main_ft, Function::ExternalLinkage, "main", TheModule);
Function::arg_iterator args = main_fn->arg_begin();
Value* int32_ac = args++;
int32_ac->setName("argc_val");
Value* ptr_av = args++;
ptr_av->setName("argv_val");
BasicBlock *main_block = BasicBlock::Create(*context, "main_block", main_fn);
builder->SetInsertPoint(main_block);
llvm::Type* mem_type = int32_ac->getType();
ConstantInt* mem_count = builder->getInt32(1);
AllocaInst* mem = builder->CreateAlloca(mem_type, mem_count, "argc");
builder->CreateStore(int32_ac, mem);
codeGen.registerValue("argc", mem);
mem_type = ptr_av->getType();
mem_count = builder->getInt32(1);
mem = builder->CreateAlloca(mem_type, mem_count, "argv");
builder->CreateStore(ptr_av, mem);
codeGen.registerValue("argv", mem);
Node* current = n;
Value* value = NULL;
while (current != NULL) {
value = current->compile(codeGen);
current = current->getNext();
}
builder->SetInsertPoint(main_block);
builder->CreateRet(get_exit_value(value));
delete builder;
if (log.isLogLevel(DEBUG)) {
TheModule->dump();
}
write(TheModule);
module = TheModule;
return TheModule;
}
void Compiler::write(const Module *m)
{
const char* filename = "program.bc";
log.info("Writing program to '%s'. Compile with clang program.bc -o program", filename);
std::error_code errorInfo;
raw_fd_ostream myfile(filename, errorInfo, llvm::sys::fs::F_None);
WriteBitcodeToFile(m, myfile);
}
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define __STDC_CONSTANT_MACROS
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/transcoder.h>
#include <algorithm>
#include <vector>
#include <apr_strings.h>
#include <log4cxx/helpers/pool.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#include <cctype>
#include <iterator>
#include <apr.h>
//LOG4CXX-417: need stdlib.h for atoi on some systems.
#ifdef APR_HAVE_STDLIB_H
#include <stdlib.h>
#endif
using namespace log4cxx;
using namespace log4cxx::helpers;
bool StringHelper::equalsIgnoreCase(const LogString& s1, const logchar* upper, const logchar* lower) {
for (LogString::const_iterator iter = s1.begin();
iter != s1.end();
iter++, upper++, lower++) {
if (*iter != *upper && *iter != * lower) return false;
}
return (*upper == 0);
}
bool StringHelper::equalsIgnoreCase(const LogString& s1, const LogString& upper, const LogString& lower) {
LogString::const_iterator u = upper.begin();
LogString::const_iterator l = lower.begin();
LogString::const_iterator iter = s1.begin();
for (;
iter != s1.end() && u != upper.end() && l != lower.end();
iter++, u++, l++) {
if (*iter != *u && *iter != *l) return false;
}
return u == upper.end() && iter == s1.end();
}
LogString StringHelper::toLowerCase(const LogString& s)
{
LogString d;
std::transform(s.begin(), s.end(),
std::insert_iterator<LogString>(d, d.begin()), tolower);
return d;
}
LogString StringHelper::trim(const LogString& s)
{
LogString::size_type pos = s.find_first_not_of(' ');
if (pos == std::string::npos)
{
return LogString();
}
LogString::size_type n = s.find_last_not_of(' ') - pos + 1;
return s.substr(pos, n);
}
bool StringHelper::startsWith(const LogString& s, const LogString& prefix)
{
return s.compare(0, prefix.length(), prefix) == 0;
}
bool StringHelper::endsWith(const LogString& s, const LogString& suffix)
{
if (suffix.length() <= s.length()) {
return s.compare(s.length() - suffix.length(), suffix.length(), suffix) == 0;
}
return false;
}
int StringHelper::toInt(const LogString& s) {
std::string as;
Transcoder::encode(s, as);
return atoi(as.c_str());
}
log4cxx_int64_t StringHelper::toInt64(const LogString& s) {
std::string as;
Transcoder::encode(s, as);
return apr_atoi64(as.c_str());
}
void StringHelper::toString(int n, Pool& pool, LogString& s) {
char* fmt = pool.itoa(n);
Transcoder::decode(fmt, s);
}
void StringHelper::toString(bool val, LogString& dst) {
if (val) {
dst.append(LOG4CXX_STR("true"));
} else {
dst.append(LOG4CXX_STR("false"));
}
}
void StringHelper::toString(log4cxx_int64_t n, Pool& pool, LogString& dst) {
if (n >= INT_MIN && n <= INT_MAX) {
toString((int) n, pool, dst);
} else {
const log4cxx_int64_t BILLION = APR_INT64_C(1000000000);
int billions = (int) (n / BILLION);
char* upper = pool.itoa(billions);
int remain = (int) (n - billions * BILLION);
if (remain < 0) remain *= -1;
char* lower = pool.itoa(remain);
Transcoder::decode(upper, dst);
dst.append(9 - strlen(lower), 0x30 /* '0' */);
Transcoder::decode(lower, dst);
}
}
void StringHelper::toString(size_t n, Pool& pool, LogString& s) {
toString((log4cxx_int64_t) n, pool, s);
}
LogString StringHelper::format(const LogString& pattern, const std::vector<LogString>& params) {
LogString result;
int i = 0;
while(pattern[i] != 0) {
if (pattern[i] == 0x7B /* '{' */ && pattern[i + 1] >= 0x30 /* '0' */ &&
pattern[i + 1] <= 0x39 /* '9' */ && pattern[i + 2] == 0x7D /* '}' */) {
int arg = pattern[i + 1] - 0x30 /* '0' */;
result = result + params[arg];
i += 3;
} else {
result = result + pattern[i];
i++;
}
}
return result;
}
<commit_msg>Synced the behavior of startsWith and endsWith, because some old compilers like Borland C++ Builder 5 could throw out_of_range exceptions if prefix was larger than the source string and we can short circuit the comparison in that case anyways.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define __STDC_CONSTANT_MACROS
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/transcoder.h>
#include <algorithm>
#include <vector>
#include <apr_strings.h>
#include <log4cxx/helpers/pool.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>
#include <cctype>
#include <iterator>
#include <apr.h>
//LOG4CXX-417: need stdlib.h for atoi on some systems.
#ifdef APR_HAVE_STDLIB_H
#include <stdlib.h>
#endif
using namespace log4cxx;
using namespace log4cxx::helpers;
bool StringHelper::equalsIgnoreCase(const LogString& s1, const logchar* upper, const logchar* lower) {
for (LogString::const_iterator iter = s1.begin();
iter != s1.end();
iter++, upper++, lower++) {
if (*iter != *upper && *iter != * lower) return false;
}
return (*upper == 0);
}
bool StringHelper::equalsIgnoreCase(const LogString& s1, const LogString& upper, const LogString& lower) {
LogString::const_iterator u = upper.begin();
LogString::const_iterator l = lower.begin();
LogString::const_iterator iter = s1.begin();
for (;
iter != s1.end() && u != upper.end() && l != lower.end();
iter++, u++, l++) {
if (*iter != *u && *iter != *l) return false;
}
return u == upper.end() && iter == s1.end();
}
LogString StringHelper::toLowerCase(const LogString& s)
{
LogString d;
std::transform(s.begin(), s.end(),
std::insert_iterator<LogString>(d, d.begin()), tolower);
return d;
}
LogString StringHelper::trim(const LogString& s)
{
LogString::size_type pos = s.find_first_not_of(' ');
if (pos == std::string::npos)
{
return LogString();
}
LogString::size_type n = s.find_last_not_of(' ') - pos + 1;
return s.substr(pos, n);
}
bool StringHelper::startsWith(const LogString& s, const LogString& prefix)
{
if (s.length() < prefix.length())
{
return false;
}
return s.compare(0, prefix.length(), prefix) == 0;
}
bool StringHelper::endsWith(const LogString& s, const LogString& suffix)
{
if (suffix.length() <= s.length()) {
return s.compare(s.length() - suffix.length(), suffix.length(), suffix) == 0;
}
return false;
}
int StringHelper::toInt(const LogString& s) {
std::string as;
Transcoder::encode(s, as);
return atoi(as.c_str());
}
log4cxx_int64_t StringHelper::toInt64(const LogString& s) {
std::string as;
Transcoder::encode(s, as);
return apr_atoi64(as.c_str());
}
void StringHelper::toString(int n, Pool& pool, LogString& s) {
char* fmt = pool.itoa(n);
Transcoder::decode(fmt, s);
}
void StringHelper::toString(bool val, LogString& dst) {
if (val) {
dst.append(LOG4CXX_STR("true"));
} else {
dst.append(LOG4CXX_STR("false"));
}
}
void StringHelper::toString(log4cxx_int64_t n, Pool& pool, LogString& dst) {
if (n >= INT_MIN && n <= INT_MAX) {
toString((int) n, pool, dst);
} else {
const log4cxx_int64_t BILLION = APR_INT64_C(1000000000);
int billions = (int) (n / BILLION);
char* upper = pool.itoa(billions);
int remain = (int) (n - billions * BILLION);
if (remain < 0) remain *= -1;
char* lower = pool.itoa(remain);
Transcoder::decode(upper, dst);
dst.append(9 - strlen(lower), 0x30 /* '0' */);
Transcoder::decode(lower, dst);
}
}
void StringHelper::toString(size_t n, Pool& pool, LogString& s) {
toString((log4cxx_int64_t) n, pool, s);
}
LogString StringHelper::format(const LogString& pattern, const std::vector<LogString>& params) {
LogString result;
int i = 0;
while(pattern[i] != 0) {
if (pattern[i] == 0x7B /* '{' */ && pattern[i + 1] >= 0x30 /* '0' */ &&
pattern[i + 1] <= 0x39 /* '9' */ && pattern[i + 2] == 0x7D /* '}' */) {
int arg = pattern[i + 1] - 0x30 /* '0' */;
result = result + params[arg];
i += 3;
} else {
result = result + pattern[i];
i++;
}
}
return result;
}
<|endoftext|> |
<commit_before>/*
c2ffi
Copyright (C) 2013 Ryan Pavlik
This file is part of c2ffi.
c2ffi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <llvm/Support/Host.h>
#include <llvm/ADT/IntrusiveRefCntPtr.h>
#include <clang/Basic/DiagnosticOptions.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/FrontendTool/Utils.h>
#include <clang/Basic/TargetOptions.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Basic/Diagnostic.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/Parse/Parser.h>
#include <clang/Parse/ParseAST.h>
#include <sys/stat.h>
#include "c2ffi/init.h"
#include "c2ffi/opt.h"
using namespace c2ffi;
void c2ffi::add_include(clang::CompilerInstance &ci, const char *path, bool is_angled,
bool show_error) {
struct stat buf;
if(stat(path, &buf) < 0 || !S_ISDIR(buf.st_mode)) {
if(show_error) {
std::cerr << "Error: Not a directory: ";
if(is_angled)
std::cerr << "-i ";
else
std::cerr << "-I ";
std::cerr << path << std::endl;
exit(1);
}
return;
}
const clang::DirectoryEntry *dirent = ci.getFileManager().getDirectory(path);
clang::DirectoryLookup lookup(dirent, clang::SrcMgr::C_System, false);
ci.getPreprocessor().getHeaderSearchInfo()
.AddSearchPath(lookup, is_angled);
}
void c2ffi::add_includes(clang::CompilerInstance &ci,
c2ffi::IncludeVector &v, bool is_angled,
bool show_error) {
for(c2ffi::IncludeVector::iterator i = v.begin(); i != v.end(); i++)
add_include(ci, (*i).c_str(), is_angled, show_error);
}
void c2ffi::init_ci(config &c, clang::CompilerInstance &ci) {
using clang::DiagnosticOptions;
using clang::TextDiagnosticPrinter;
using clang::TargetOptions;
using clang::TargetInfo;
ci.getInvocation().setLangDefaults(ci.getLangOpts(), c.kind, c.std);
DiagnosticOptions *dopt = new DiagnosticOptions;
TextDiagnosticPrinter *tpd =
new TextDiagnosticPrinter(llvm::errs(), dopt, false);
ci.createDiagnostics(tpd);
std::shared_ptr<TargetOptions> pto =
std::shared_ptr<TargetOptions>(new TargetOptions());
if(c.arch == "")
pto->Triple = llvm::sys::getDefaultTargetTriple();
else
pto->Triple = c.arch;
TargetInfo *pti = TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto);
ci.setTarget(pti);
ci.createFileManager();
ci.createSourceManager(ci.getFileManager());
ci.createPreprocessor(clang::TU_Complete);
ci.getPreprocessorOpts().UsePredefines = false;
ci.getPreprocessorOutputOpts().ShowCPP = c.preprocess_only;
ci.getPreprocessor().setPreprocessedOutput(c.preprocess_only);
}
<commit_msg>Slight hack to better handle -msvc platform triple; should be moved/extended/etc at some point.<commit_after>/*
c2ffi
Copyright (C) 2013 Ryan Pavlik
This file is part of c2ffi.
c2ffi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
c2ffi 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 c2ffi. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <llvm/Support/Host.h>
#include <llvm/ADT/IntrusiveRefCntPtr.h>
#include <clang/Basic/DiagnosticOptions.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/FrontendTool/Utils.h>
#include <clang/Basic/TargetOptions.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Basic/Diagnostic.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/Parse/Parser.h>
#include <clang/Parse/ParseAST.h>
#include <sys/stat.h>
#include "c2ffi/init.h"
#include "c2ffi/opt.h"
using namespace c2ffi;
void c2ffi::add_include(clang::CompilerInstance &ci, const char *path, bool is_angled,
bool show_error) {
struct stat buf;
if(stat(path, &buf) < 0 || !S_ISDIR(buf.st_mode)) {
if(show_error) {
std::cerr << "Error: Not a directory: ";
if(is_angled)
std::cerr << "-i ";
else
std::cerr << "-I ";
std::cerr << path << std::endl;
exit(1);
}
return;
}
const clang::DirectoryEntry *dirent = ci.getFileManager().getDirectory(path);
clang::DirectoryLookup lookup(dirent, clang::SrcMgr::C_System, false);
ci.getPreprocessor().getHeaderSearchInfo()
.AddSearchPath(lookup, is_angled);
}
void c2ffi::add_includes(clang::CompilerInstance &ci,
c2ffi::IncludeVector &v, bool is_angled,
bool show_error) {
for(c2ffi::IncludeVector::iterator i = v.begin(); i != v.end(); i++)
add_include(ci, (*i).c_str(), is_angled, show_error);
}
void c2ffi::init_ci(config &c, clang::CompilerInstance &ci) {
using clang::DiagnosticOptions;
using clang::TextDiagnosticPrinter;
using clang::TargetOptions;
using clang::TargetInfo;
DiagnosticOptions *dopt = new DiagnosticOptions;
TextDiagnosticPrinter *tpd =
new TextDiagnosticPrinter(llvm::errs(), dopt, false);
ci.createDiagnostics(tpd);
std::shared_ptr<TargetOptions> pto =
std::shared_ptr<TargetOptions>(new TargetOptions());
if(c.arch == "")
pto->Triple = llvm::sys::getDefaultTargetTriple();
else
pto->Triple = c.arch;
TargetInfo *pti = TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto);
clang::LangOptions &lo = ci.getLangOpts();
switch(pti->getTriple().getEnvironment()) {
case llvm::Triple::EnvironmentType::GNU:
lo.GNUMode = 1;
break;
case llvm::Triple::EnvironmentType::MSVC:
lo.MSVCCompat = 1;
lo.MicrosoftExt = 1;
break;
default:
std::cerr << "c2ffi warning: Unhandled environment: '"
<< pti->getTriple().getEnvironmentName().str()
<< "' for triple '" << c.arch
<< "'" << std::endl;
}
ci.getInvocation().setLangDefaults(lo, c.kind, c.std);
ci.setTarget(pti);
ci.createFileManager();
ci.createSourceManager(ci.getFileManager());
ci.createPreprocessor(clang::TU_Complete);
ci.getPreprocessorOpts().UsePredefines = false;
ci.getPreprocessorOutputOpts().ShowCPP = c.preprocess_only;
ci.getPreprocessor().setPreprocessedOutput(c.preprocess_only);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Jakob Sinclair
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "kemi.hpp"
Kemi::Kemi()
{
;
}
Kemi::~Kemi()
{
m_Table.clear();
m_Elements.clear();
}
float Kemi::MolarMass(std::string Atoms[], int n)
{
try {
float MolarMass = 0.0f;
for (int i = 0; i < n; i++) {
int e = m_Elements[Atoms[i]];
MolarMass += m_Table[e - 1].AtmMass;
}
return MolarMass;
}
catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
return 0.0f;
}
float Kemi::Mass(std::string Atoms[], int n, float s)
{
float Mass = 0.0f;
float MolarMassAtoms = MolarMass(Atoms, n);
Mass = MolarMassAtoms * s;
return Mass;
}
float Kemi::Substance(std::string Atoms[], int n, float m)
{
float Substance = 0.0f;
float MolarMassAtoms = MolarMass(Atoms, n);
Substance = m / MolarMassAtoms;
return Substance;
}
/*
* Creates a periodic table from a file.
* Format to follow inside the file:
* Abbrevation_of_the_element Atomic_Number Atomic_Mass Metal_or_not
* Example: H 1 1.008 N
*/
void Kemi::Init(std::string File)
{
std::ifstream file_buffer;
file_buffer.open(File);
try {
if (!file_buffer.is_open()) {
Error file_error;
throw file_error.set_error("Could not load file " + File + '!');
} else {
std::string line = "";
int i = 0;
while (std::getline(file_buffer, line)) {
m_Table.emplace_back(Element());
int c = 0;
while (line[c] != ' ') {
m_Table[i].Name += line[c];
c++;
}
m_Elements[m_Table[i].Name] = i + 1;
c++;
while (line[c] != ' ') {
m_Table[i].No *= 10;
m_Table[i].No += line[c] - '0';
c++;
}
c++;
int p = -1;
bool point = false;
while (line[c] != ' ') {
if (line[c] == '.') {
point = true;
} else if (point == true) {
m_Table[i].AtmMass += (float)((line[c] - '0') * pow(10, p));
p--;
} else {
m_Table[i].AtmMass *= 10;
m_Table[i].AtmMass += (float)(line[c] - '0');
}
c++;
}
if (line[line.size() - 1] == 'N') {
m_Table[i].Property = type::NonMetal;
} else if (line[line.size() - 1] == 'M') {
m_Table[i].Property = type::Metal;
} else {
m_Table[i].Property = type::TransitionMetal;
}
i++;
}
}
}
catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
}
/*Handles user input and events and corresponds with the correct functions*/
void Kemi::Run()
{
bool quit = false;
while (!quit) {
int c = 0;
std::vector<std::string> atoms;
std::string answer;
std::cin >> answer;
if (answer == "q") {
quit = true;
} else if (answer == "molar") {
if (atoms.size() > 0)
atoms.clear();
while (!std::cin.fail()) {
std::cin >> answer;
auto it = m_Elements.find(answer);
if (it != m_Elements.end()) {
atoms.push_back(answer);
} else if (answer == "done") {
break;
}
}
float Result = MolarMass(atoms.data(), atoms.size());
std::cout << "Molar Mass: " << Result
<< " g/mol." << std::endl;
} else if (answer == "substance") {
if (atoms.size() > 0)
atoms.clear();
while (!std::cin.fail()) {
std::cin >> answer;
auto it = m_Elements.find(answer);
if (it != m_Elements.end()) {
atoms.push_back(answer);
} else if (answer == "done") {
break;
}
}
float tmp;
std::cout << "Enter mass: ";
std::cin >> tmp;
float Result = Substance(atoms.data(), atoms.size(), tmp);
std::cout << "Amount of substance: " << Result
<< " molar." << std::endl;
} else if (answer == "mass") {
if (atoms.size() > 0)
atoms.clear();
while (!std::cin.fail()) {
std::cin >> answer;
auto it = m_Elements.find(answer);
if (it != m_Elements.end()) {
atoms.push_back(answer);
} else if (answer == "done") {
break;
}
}
float tmp;
std::cout << "Enter amount of substance: ";
std::cin >> tmp;
float Result = Mass(atoms.data(), atoms.size(), tmp);
std::cout << "Mass: " << Result
<< " g." << std::endl;
}
}
}<commit_msg>Added a little bit of user friendliness.<commit_after>/*
Copyright (c) 2016 Jakob Sinclair
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "kemi.hpp"
Kemi::Kemi()
{
;
}
Kemi::~Kemi()
{
m_Table.clear();
m_Elements.clear();
}
float Kemi::MolarMass(std::string Atoms[], int n)
{
try {
float MolarMass = 0.0f;
for (int i = 0; i < n; i++) {
int e = m_Elements[Atoms[i]];
MolarMass += m_Table[e - 1].AtmMass;
}
return MolarMass;
}
catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
return 0.0f;
}
float Kemi::Mass(std::string Atoms[], int n, float s)
{
float Mass = 0.0f;
float MolarMassAtoms = MolarMass(Atoms, n);
Mass = MolarMassAtoms * s;
return Mass;
}
float Kemi::Substance(std::string Atoms[], int n, float m)
{
float Substance = 0.0f;
float MolarMassAtoms = MolarMass(Atoms, n);
Substance = m / MolarMassAtoms;
return Substance;
}
/*
* Creates a periodic table from a file.
* Format to follow inside the file:
* Abbrevation_of_the_element Atomic_Number Atomic_Mass Metal_or_not
* Example: H 1 1.008 N
*/
void Kemi::Init(std::string File)
{
std::ifstream file_buffer;
file_buffer.open(File);
try {
if (!file_buffer.is_open()) {
Error file_error;
throw file_error.set_error("Could not load file " + File + '!');
} else {
std::string line = "";
int i = 0;
while (std::getline(file_buffer, line)) {
m_Table.emplace_back(Element());
int c = 0;
while (line[c] != ' ') {
m_Table[i].Name += line[c];
c++;
}
m_Elements[m_Table[i].Name] = i + 1;
c++;
while (line[c] != ' ') {
m_Table[i].No *= 10;
m_Table[i].No += line[c] - '0';
c++;
}
c++;
int p = -1;
bool point = false;
while (line[c] != ' ') {
if (line[c] == '.') {
point = true;
} else if (point == true) {
m_Table[i].AtmMass += (float)((line[c] - '0') * pow(10, p));
p--;
} else {
m_Table[i].AtmMass *= 10;
m_Table[i].AtmMass += (float)(line[c] - '0');
}
c++;
}
if (line[line.size() - 1] == 'N') {
m_Table[i].Property = type::NonMetal;
} else if (line[line.size() - 1] == 'M') {
m_Table[i].Property = type::Metal;
} else {
m_Table[i].Property = type::TransitionMetal;
}
i++;
}
}
}
catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
}
/*Handles user input and events and corresponds with the correct functions*/
void Kemi::Run()
{
std::cout << "Enter a command(mass, molar or substance): " << std::endl;
bool quit = false;
while (!quit) {
int c = 0;
std::vector<std::string> atoms;
std::string answer;
std::cin >> answer;
if (answer == "q") {
quit = true;
} else if (answer == "molar") {
std::cout << "Enter the abreviations for all the atoms(write \"done\" when you are done): "
<< std::endl;
if (atoms.size() > 0)
atoms.clear();
while (!std::cin.fail()) {
std::cin >> answer;
auto it = m_Elements.find(answer);
if (it != m_Elements.end()) {
atoms.push_back(answer);
} else if (answer == "done") {
break;
}
}
float Result = MolarMass(atoms.data(), atoms.size());
std::cout << "Molar Mass: " << Result
<< " g/mol." << std::endl;
} else if (answer == "substance") {
std::cout << "Enter the abreviations for all the atoms(write \"done\" when you are done): "
<< std::endl;
if (atoms.size() > 0)
atoms.clear();
while (!std::cin.fail()) {
std::cin >> answer;
auto it = m_Elements.find(answer);
if (it != m_Elements.end()) {
atoms.push_back(answer);
} else if (answer == "done") {
break;
}
}
float tmp;
std::cout << "Enter mass: ";
std::cin >> tmp;
float Result = Substance(atoms.data(), atoms.size(), tmp);
std::cout << "Amount of substance: " << Result
<< " molar." << std::endl;
} else if (answer == "mass") {
std::cout << "Enter the abreviations for all the atoms(write \"done\" when you are done): "
<< std::endl;
if (atoms.size() > 0)
atoms.clear();
while (!std::cin.fail()) {
std::cin >> answer;
auto it = m_Elements.find(answer);
if (it != m_Elements.end()) {
atoms.push_back(answer);
} else if (answer == "done") {
break;
}
}
float tmp;
std::cout << "Enter amount of substance: ";
std::cin >> tmp;
float Result = Mass(atoms.data(), atoms.size(), tmp);
std::cout << "Mass: " << Result
<< " g." << std::endl;
}
}
}<|endoftext|> |
<commit_before>#ifndef __LUA_RAPIDJSION_LUACOMPAT_H__
#define __LUA_RAPIDJSION_LUACOMPAT_H__
#include <cmath>
#include <lua.hpp>
namespace luax {
inline void setfuncs(lua_State* L, const luaL_Reg* funcs) {
#if LUA_VERSION_NUM >= 502 // LUA 5.2 or above
luaL_setfuncs(L, funcs, 0);
#else
luaL_register(L, NULL, funcs);
#endif
}
inline size_t rawlen(lua_State* L, int idx) {
#if LUA_VERSION_NUM >= 502
return lua_rawlen(L, idx);
#else
return lua_objlen(L, idx);
#endif
}
inline int absindex(lua_State *L, int idx) {
#if LUA_VERSION_NUM >= 502
return lua_absindex(L, idx);
#else
if (i < 0 && i > LUA_REGISTRYINDEX)
idx += lua_gettop(L) + 1;
return idx;
#endif
}
inline bool isinteger(lua_State* L, int idx, int64_t* out = NULL)
{
#if LUA_VERSION_NUM >= 503
if (lua_isinteger(L, idx)) // but it maybe not detect all integers.
{
if (out)
*out = lua_tointeger(L, idx);
return true;
}
#endif
double intpart;
if (std::modf(lua_tonumber(L, idx), &intpart) == 0.0)
{
if (std::numeric_limits<lua_Integer>::min() <= intpart
&& intpart <= std::numeric_limits<lua_Integer>::max())
{
if (out)
*out = static_cast<int64_t>(intpart);
return true;
}
}
return false;
}
inline int typerror(lua_State* L, int narg, const char* tname) {
#if LUA_VERSION_NUM < 502
return luaL_typerror(L, narg, tname);
#else
const char *msg = lua_pushfstring(L, "%s expected, got %s",
tname, luaL_typename(L, narg));
return luaL_argerror(L, narg, msg);
#endif
}
inline bool optboolfield(lua_State* L, int idx, const char* name, bool def)
{
bool v = def;
int t = lua_type(L, idx);
if (t != LUA_TTABLE && t != LUA_TNONE)
luax::typerror(L, idx, "table");
if (t != LUA_TNONE) {
lua_getfield(L, idx, name); // [field]
if (!lua_isnoneornil(L, -1))
v = lua_toboolean(L, -1) != 0;;
lua_pop(L, 1);
}
return v;
}
inline int optintfield(lua_State* L, int idx, const char* name, int def)
{
int v = def;
lua_getfield(L, idx, name); // [field]
if (lua_isnumber(L, -1))
v = static_cast<int>(lua_tointeger(L, -1));
lua_pop(L, 1);
return v;
}
}
#endif // __LUA_RAPIDJSION_LUACOMPAT_H__
<commit_msg>Fix code for 5.1.<commit_after>#ifndef __LUA_RAPIDJSION_LUACOMPAT_H__
#define __LUA_RAPIDJSION_LUACOMPAT_H__
#include <cmath>
#include <lua.hpp>
namespace luax {
inline void setfuncs(lua_State* L, const luaL_Reg* funcs) {
#if LUA_VERSION_NUM >= 502 // LUA 5.2 or above
luaL_setfuncs(L, funcs, 0);
#else
luaL_register(L, NULL, funcs);
#endif
}
inline size_t rawlen(lua_State* L, int idx) {
#if LUA_VERSION_NUM >= 502
return lua_rawlen(L, idx);
#else
return lua_objlen(L, idx);
#endif
}
inline int absindex(lua_State *L, int idx) {
#if LUA_VERSION_NUM >= 502
return lua_absindex(L, idx);
#else
if (idx < 0 && idx > LUA_REGISTRYINDEX)
idx += lua_gettop(L) + 1;
return idx;
#endif
}
inline bool isinteger(lua_State* L, int idx, int64_t* out = NULL)
{
#if LUA_VERSION_NUM >= 503
if (lua_isinteger(L, idx)) // but it maybe not detect all integers.
{
if (out)
*out = lua_tointeger(L, idx);
return true;
}
#endif
double intpart;
if (std::modf(lua_tonumber(L, idx), &intpart) == 0.0)
{
if (std::numeric_limits<lua_Integer>::min() <= intpart
&& intpart <= std::numeric_limits<lua_Integer>::max())
{
if (out)
*out = static_cast<int64_t>(intpart);
return true;
}
}
return false;
}
inline int typerror(lua_State* L, int narg, const char* tname) {
#if LUA_VERSION_NUM < 502
return luaL_typerror(L, narg, tname);
#else
const char *msg = lua_pushfstring(L, "%s expected, got %s",
tname, luaL_typename(L, narg));
return luaL_argerror(L, narg, msg);
#endif
}
inline bool optboolfield(lua_State* L, int idx, const char* name, bool def)
{
bool v = def;
int t = lua_type(L, idx);
if (t != LUA_TTABLE && t != LUA_TNONE)
luax::typerror(L, idx, "table");
if (t != LUA_TNONE) {
lua_getfield(L, idx, name); // [field]
if (!lua_isnoneornil(L, -1))
v = lua_toboolean(L, -1) != 0;;
lua_pop(L, 1);
}
return v;
}
inline int optintfield(lua_State* L, int idx, const char* name, int def)
{
int v = def;
lua_getfield(L, idx, name); // [field]
if (lua_isnumber(L, -1))
v = static_cast<int>(lua_tointeger(L, -1));
lua_pop(L, 1);
return v;
}
}
#endif // __LUA_RAPIDJSION_LUACOMPAT_H__
<|endoftext|> |
<commit_before>#include <boost/scoped_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/container/vector.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <ibotpp/loader.hpp>
#include <ibotpp/bot.hpp>
#include "config.h"
void worker_main(boost::shared_ptr<boost::asio::io_service> io_service) {
io_service->run();
}
int main(int argc, char *argv[]) {
ibotpp::loader loader;
auto module = loader.load("test.cpp");
std::cout << "name = " << module->name << std::endl;
auto io_service = boost::make_shared<boost::asio::io_service>();
auto work = boost::make_shared<boost::asio::io_service::work>(*io_service);
auto strand = boost::make_shared<boost::asio::io_service::strand>(*io_service);
boost::thread_group workers;
for(unsigned int w = 0; w < CONFIG_NUM_WORKERS; ++w) {
workers.create_thread(boost::bind(&worker_main, io_service));
}
ibotpp::bot bot(io_service, strand, CONFIG_HOST, CONFIG_PORT);
work.reset();
workers.join_all();
return 0;
}
<commit_msg>main: remove unused includes<commit_after>#include <boost/make_shared.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <ibotpp/loader.hpp>
#include <ibotpp/bot.hpp>
#include "config.h"
void worker_main(boost::shared_ptr<boost::asio::io_service> io_service) {
io_service->run();
}
int main(int argc, char *argv[]) {
ibotpp::loader loader;
auto module = loader.load("test.cpp");
std::cout << "name = " << module->name << std::endl;
auto io_service = boost::make_shared<boost::asio::io_service>();
auto work = boost::make_shared<boost::asio::io_service::work>(*io_service);
auto strand = boost::make_shared<boost::asio::io_service::strand>(*io_service);
boost::thread_group workers;
for(unsigned int w = 0; w < CONFIG_NUM_WORKERS; ++w) {
workers.create_thread(boost::bind(&worker_main, io_service));
}
ibotpp::bot bot(io_service, strand, CONFIG_HOST, CONFIG_PORT);
work.reset();
workers.join_all();
return 0;
}
<|endoftext|> |
<commit_before>#include <FS.h>
#include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient.git
// define default values for the mqtt server, the values are going to be
// overwriten by the config file
char mqtt_server[40];
char mqtt_port[6] = "8080";
char mqtt_topic[40] = "/YOURMQTTPATH/NAME";
WiFiClient wifi_client;
PubSubClient mqtt_client(wifi_client);
// flag if we need to write data
bool shouldSaveConfig = false;
/** callback notifying us of changes within the WifiManager, write config back
* to file
*/
void saveConfigCallback () {
shouldSaveConfig = true;
}
/** Load the /config.bin file and read the values for mqtt_server, mqtt_port
* and mqtt_topic.
*/
void loadConfigFromFile() {
if (SPIFFS.begin()) {
if (SPIFFS.exists("/config.bin")) {
//file exists, reading and loading
File configFile = SPIFFS.open("/config.bin", "r");
if (configFile) {
configFile.readBytes(mqtt_server, sizeof(char)*40);
configFile.readBytes(mqtt_port, sizeof(char)*6);
configFile.readBytes(mqtt_topic, sizeof(char)*40);
}
}
}
}
/** Save custom config values mqtt_server, mqtt_port and mqtt_topic to config
* file (/config.bin)
*/
void saveConfigToFile() {
File configFile = SPIFFS.open("/config.bin", "w");
configFile.write((uint8_t*)mqtt_server, sizeof(char)*40);
configFile.write((uint8_t*)mqtt_port, sizeof(char)*6);
configFile.write((uint8_t*)mqtt_topic, sizeof(char)*40);
configFile.close();
}
/** Setup WifiManager and add the mqtt_* paramters as custom parameters */
void setupWifiManager() {
WiFiManagerParameter param_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter param_mqtt_port("port", "mqtt port", mqtt_port, 5);
WiFiManagerParameter param_mqtt_topic("topic", "mqtt topic", mqtt_topic, 40);
WiFiManager wifiManager;
wifiManager.addParameter(¶m_mqtt_server);
wifiManager.addParameter(¶m_mqtt_port);
wifiManager.addParameter(¶m_mqtt_topic);
if(!wifiManager.autoConnect("MqttButtonLed", "1234")) {
// failed setup of wifi reset ESP and hope more luck next time
ESP.reset();
}
//read updated parameters
strcpy(mqtt_server, param_mqtt_server.getValue());
strcpy(mqtt_port, param_mqtt_port.getValue());
strcpy(mqtt_topic, param_mqtt_topic.getValue());
}
/** Callback from MqttServer when getting a new message */
void mqttCallback(char* topic, byte* payload, unsigned int length) {
}
/** Setup the Mqtt connection */
void setupMqtt() {
int port = strtol(mqtt_port, NULL, 10);
mqtt_client.setServer(mqtt_server, port);
mqtt_client.setCallback(mqttCallback);
}
/** The setup entry point, gets called on start up */
void setup() {
loadConfigFromFile();
setupWifiManager();
if (shouldSaveConfig) {
saveConfigToFile();
}
setupMqtt();
}
/** The main loop to run. */
void loop() {
if (!mqtt_client.connected()) {
reconnect();
}
mqtt_client.loop();
}
<commit_msg>add pin usage and mqtt_client subscribe<commit_after>#include <FS.h>
#include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient.git
#define PIN_01 0
#define PIN_02 1
#define PIN_03 3
#define PIN_04 4
#define PIN_05 5
#define PIN_06 12
#define PIN_07 13
#define PIN_08 14
#define PIN_09 15
#define PIN_19 16
// define default values for the mqtt server, the values are going to be
// overwriten by the config file
char mqtt_server[40];
char mqtt_port[6] = "8080";
char mqtt_client_name[40] = "CLIENTNAME";
char mqtt_topic[40] = "/YOURMQTTPATH/NAME";
WiFiClient wifi_client;
PubSubClient mqtt_client(wifi_client);
uint16_t status = 0;
// flag if we need to write data
bool shouldSaveConfig = false;
/** callback notifying us of changes within the WifiManager, write config back
* to file
*/
void saveConfigCallback () {
shouldSaveConfig = true;
}
/** Load the /config.bin file and read the values for mqtt_server, mqtt_port
* and mqtt_topic.
*/
void loadConfigFromFile() {
if (SPIFFS.begin()) {
if (SPIFFS.exists("/config.bin")) {
//file exists, reading and loading
File configFile = SPIFFS.open("/config.bin", "r");
if (configFile) {
configFile.readBytes(mqtt_server, sizeof(char)*40);
configFile.readBytes(mqtt_port, sizeof(char)*6);
configFile.readBytes(mqtt_topic, sizeof(char)*40);
configFile.readBytes(mqtt_client_name, sizeof(char)*40);
}
}
}
}
/** Save custom config values mqtt_server, mqtt_port and mqtt_topic to config
* file (/config.bin)
*/
void saveConfigToFile() {
File configFile = SPIFFS.open("/config.bin", "w");
configFile.write((uint8_t*)mqtt_server, sizeof(char)*40);
configFile.write((uint8_t*)mqtt_port, sizeof(char)*6);
configFile.write((uint8_t*)mqtt_topic, sizeof(char)*40);
configFile.write((uint8_t*)mqtt_client_name, sizeof(char)*40);
configFile.close();
}
/** Setup WifiManager and add the mqtt_* paramters as custom parameters */
void setupWifiManager() {
WiFiManagerParameter param_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter param_mqtt_port("port", "mqtt port", mqtt_port, 5);
WiFiManagerParameter param_mqtt_topic("topic", "mqtt topic", mqtt_topic, 40);
WiFiManagerParameter param_mqtt_client_name("client name", "mqtt client name", mqtt_client_name, 40);
WiFiManager wifiManager;
wifiManager.addParameter(¶m_mqtt_server);
wifiManager.addParameter(¶m_mqtt_port);
wifiManager.addParameter(¶m_mqtt_topic);
wifiManager.addParameter(¶m_mqtt_client_name);
if(!wifiManager.autoConnect("MqttButtonLed", "1234")) {
// failed setup of wifi reset ESP and hope more luck next time
ESP.reset();
}
//read updated parameters
strcpy(mqtt_server, param_mqtt_server.getValue());
strcpy(mqtt_port, param_mqtt_port.getValue());
strcpy(mqtt_topic, param_mqtt_topic.getValue());
strcpy(mqtt_client_name, param_mqtt_client_name.getValue());
}
/** Callback from MqttServer when getting a new message */
void mqttCallback(char* topic, byte* payload, unsigned int length) {
}
/** Setup the Mqtt connection */
void setupMqtt() {
int port = strtol(mqtt_port, NULL, 10);
mqtt_client.setServer(mqtt_server, port);
mqtt_client.setCallback(mqttCallback);
}
void interruptOne();
void interruptTwo();
void interruptThree();
void interruptFour();
/** Setup all the inputs and outputs */
void setupIOPins() {
pinMode(PIN_01, OUTPUT);
pinMode(PIN_02, OUTPUT);
pinMode(PIN_03, OUTPUT);
pinMode(PIN_04, OUTPUT);
pinMode(PIN_05, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_05), interruptOne, FALLING);
attachInterrupt(digitalPinToInterrupt(PIN_06), interruptTwo, FALLING);
attachInterrupt(digitalPinToInterrupt(PIN_07), interruptThree, FALLING);
attachInterrupt(digitalPinToInterrupt(PIN_08), interruptFour, FALLING);
}
/** The setup entry point, gets called on start up */
void setup() {
loadConfigFromFile();
setupWifiManager();
if (shouldSaveConfig) {
saveConfigToFile();
}
setupMqtt();
}
/** Reconnect mqtt client and subscribe if necessary */
void reconnect() {
while(!mqtt_client.connected()) {
if (mqtt_client.connect(mqtt_client_name)) {
mqtt_client.subscribe(mqtt_topic); // TODO add /in to topic
} else {
delay(1000);
}
}
}
/** The main loop to run. */
void loop() {
if (!mqtt_client.connected()) {
reconnect();
}
mqtt_client.loop();
if ((status & PIN_05) == PIN_05) {
mqtt_client.publish(mqtt_topic, "1"); // TODO add /out to topic
status ^= PIN_05;
}
}
<|endoftext|> |
<commit_before>/*
VROOM (Vehicle Routing Open-source Optimization Machine)
Copyright (C) 2015, Julien Coupey
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 <string>
#include <sstream>
#include <unistd.h>
#include "./structures/typedefs.h"
#include "./heuristics/tsp_strategy.h"
void display_usage(){
std::string usage = "VROOM Copyright (C) 2015, Julien Coupey\n";
usage += "This program is distributed under the terms of the GNU General Public\n";
usage += "License, version 3, and comes with ABSOLUTELY NO WARRANTY.\n";
std::cout << usage << std::endl;
exit(0);
}
int main(int argc, char **argv){
// Default options.
cl_args_t cl_args;
cl_args.loader = 0;
cl_args.geometry = false;
cl_args.osrm_address = "0.0.0.0";
cl_args.osrm_port = 5000;
// Parsing command-line arguments.
const char* optString = "a:egi:o:p:vh?";
int opt = getopt(argc, argv, optString);
while(opt != -1) {
switch(opt){
case 'a':
cl_args.osrm_address = optarg;
break;
case 'e':
cl_args.loader = 1;
break;
case 'g':
cl_args.geometry = true;
break;
case 'h':
display_usage();
break;
case 'i':
cl_args.input_file = optarg;
break;
case 'o':
cl_args.output_file = optarg;
break;
case 'p':
cl_args.osrm_port = strtol(optarg, nullptr, 10);
break;
case 'v':
cl_args.verbose = true;
break;
default:
break;
}
opt = getopt(argc, argv, optString);
}
if(cl_args.input_file.empty()){
// Getting list of locations from command-line.
if(argc == optind){
// Missing argument!
display_usage();
}
cl_args.locations = argv[optind];
}
else{
// Getting list of locations from input file. Fast way to get the
// file content as a string, not meant for large files...
std::ifstream ifs (cl_args.input_file, std::ifstream::in);
std::stringstream buffer;
buffer << ifs.rdbuf();
cl_args.locations = buffer.str();
}
try{
solve_atsp(cl_args);
}
catch(const custom_exception& e){
std::cout << "Error: " << e.get_message() << std::endl;
exit(1);
}
return 0;
}
<commit_msg>Display proper usage and command-line options.<commit_after>/*
VROOM (Vehicle Routing Open-source Optimization Machine)
Copyright (C) 2015, Julien Coupey
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 <string>
#include <sstream>
#include <unistd.h>
#include "./structures/typedefs.h"
#include "./heuristics/tsp_strategy.h"
void display_usage(){
std::string usage = "VROOM Copyright (C) 2015, Julien Coupey\n";
usage += "Usage :\n\tvroom [OPTION]... \"loc=lat,lon&loc=lat,lon[&loc=lat,lon...]\"";
usage += "\n\tvroom [OPTION]... -i FILE\n";
usage += "Options:\n";
usage += "\t-a=ADDRESS\t OSRM server address (\"0.0.0.0\")\n";
usage += "\t-p=PORT,\t OSRM listening port (5000)\n";
usage += "\t-g,\t\t get detailed route geometry for the solution\n";
usage += "\t-e,\t\t use eulidean distance rather than travel times\n\t\t\t from OSRM\n";
usage += "\t-o=OUTPUT,\t output file name\n";
usage += "\t-i=FILE,\t read locations list from FILE rather than from\n\t\t\t command-line\n";
usage += "\t-v,\t\t turn on verbose output\n";
usage += "\nThis program is distributed under the terms of the GNU General Public\n";
usage += "License, version 3, and comes with ABSOLUTELY NO WARRANTY.\n";
std::cout << usage << std::endl;
exit(0);
}
int main(int argc, char **argv){
// Default options.
cl_args_t cl_args;
cl_args.loader = 0;
cl_args.geometry = false;
cl_args.osrm_address = "0.0.0.0";
cl_args.osrm_port = 5000;
// Parsing command-line arguments.
const char* optString = "a:egi:o:p:vh?";
int opt = getopt(argc, argv, optString);
while(opt != -1) {
switch(opt){
case 'a':
cl_args.osrm_address = optarg;
break;
case 'e':
cl_args.loader = 1;
break;
case 'g':
cl_args.geometry = true;
break;
case 'h':
display_usage();
break;
case 'i':
cl_args.input_file = optarg;
break;
case 'o':
cl_args.output_file = optarg;
break;
case 'p':
cl_args.osrm_port = strtol(optarg, nullptr, 10);
break;
case 'v':
cl_args.verbose = true;
break;
default:
break;
}
opt = getopt(argc, argv, optString);
}
if(cl_args.input_file.empty()){
// Getting list of locations from command-line.
if(argc == optind){
// Missing argument!
display_usage();
}
cl_args.locations = argv[optind];
}
else{
// Getting list of locations from input file. Fast way to get the
// file content as a string, not meant for large files...
std::ifstream ifs (cl_args.input_file, std::ifstream::in);
std::stringstream buffer;
buffer << ifs.rdbuf();
cl_args.locations = buffer.str();
}
try{
solve_atsp(cl_args);
}
catch(const custom_exception& e){
std::cout << "Error: " << e.get_message() << std::endl;
exit(1);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <Wt/WApplication>
#include <Wt/WBreak>
#include <Wt/WContainerWidget>
#include <Wt/WLineEdit>
#include <Wt/WPushButton>
#include <Wt/WText>
#include <Wt/WLabel>
#include "core/muda.h"
#include "core/context.h"
#include "wtui/mudalistwidget.h"
using namespace Wt;
using boost::bind;
using boost::mem_fn;
namespace m = mempko::muda;
namespace mm = mempko::muda::model;
namespace mc = mempko::muda::context;
namespace mt = mempko::muda::wt;
class app : public WApplication
{
public:
app(const WEnvironment& env);
private:
void login_screen();
void startup_muda_screen();
void create_header_ui();
void all_view();
void now_view();
void later_view();
void done_view();
void note_view();
WContainerWidget* create_menu();
private:
void add_new_now_muda();
void add_new_later_muda();
void add_new_done_muda();
void add_new_note_muda();
mm::muda_ptr add_new_muda();
void add_muda_to_list_widget(mm::muda_ptr muda);
private:
bool filter_by_all(mm::muda_ptr muda);
bool filter_by_now(mm::muda_ptr muda);
bool filter_by_later(mm::muda_ptr muda);
bool filter_by_done(mm::muda_ptr muda);
bool filter_by_note(mm::muda_ptr muda);
private:
void save_mudas();
void load_mudas();
private:
//login widgets
WLineEdit* _muda_file_edit;
std::string _muda_file;
private:
//muda widgets
WLineEdit* _new_muda;
mm::muda_list _mudas;
mt::muda_list_widget* _muda_list_widget;
};
app::app(const WEnvironment& env) :
WApplication(env),
_muda_file("global")
{
login_screen();
}
void app::login_screen()
{
root()->clear();
WHBoxLayout* layout = new WHBoxLayout;
layout->addWidget(new WLabel("Muda List:"), 0, AlignMiddle);
layout->addWidget( _muda_file_edit = new WLineEdit(_muda_file), 0, AlignMiddle);
_muda_file_edit->setFocus();
_muda_file_edit->setStyleClass("muda");
WPushButton* b = new WPushButton("Load");
layout->addWidget(b, 0, AlignMiddle);
layout->addStretch();
b->clicked().connect(bind(&app::startup_muda_screen, this));
_muda_file_edit->enterPressed().connect(bind(&app::startup_muda_screen, this));
root()->setLayout(layout);
}
void app::startup_muda_screen()
{
_muda_file = _muda_file_edit->text().narrow();
setTitle(_muda_file);
load_mudas();
all_view();
}
void app::all_view()
{
root()->clear();
create_header_ui();
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_now_muda, this));
//create muda list widget
_muda_list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_all, this, _1), root());
_muda_list_widget->when_model_updated(bind(&app::save_mudas, this));
}
void app::now_view()
{
root()->clear();
create_header_ui();
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_now_muda, this));
//create muda list widget
_muda_list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_now, this, _1), root());
_muda_list_widget->when_model_updated(bind(&app::save_mudas, this));
}
void app::later_view()
{
root()->clear();
create_header_ui();
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_later_muda, this));
//create muda list widget
_muda_list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_later, this, _1), root());
_muda_list_widget->when_model_updated(bind(&app::save_mudas, this));
}
void app::done_view()
{
root()->clear();
create_header_ui();
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_done_muda, this));
//create muda list widget
_muda_list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_done, this, _1), root());
_muda_list_widget->when_model_updated(bind(&app::save_mudas, this));
}
void app::note_view()
{
root()->clear();
create_header_ui();
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_note_muda, this));
//create muda list widget
_muda_list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_note, this, _1), root());
_muda_list_widget->when_model_updated(bind(&app::save_mudas, this));
}
void app::save_mudas()
{
std::ofstream o(_muda_file.c_str());
boost::archive::xml_oarchive oa(o);
oa << BOOST_SERIALIZATION_NVP(_mudas);
}
void app::load_mudas()
{
std::ifstream i(_muda_file.c_str());
if(!i) return;
boost::archive::xml_iarchive ia(i);
ia >> BOOST_SERIALIZATION_NVP(_mudas);
}
WLabel* create_menu_label(WString text, WString css_class)
{
WLabel* l = new WLabel(text);
l->setStyleClass(css_class);
l->resize(WLength(100, WLength::Percentage), WLength::Auto);
return l;
}
WContainerWidget* app::create_menu()
{
WLabel* all = create_menu_label("all", "btn muda-all-button");
all->clicked().connect (bind(&app::all_view, this));
WLabel* now = create_menu_label("now", "btn muda-now-button");
now->clicked().connect (bind(&app::now_view, this));
WLabel* later = create_menu_label("later", "btn muda-later-button");
later->clicked().connect (bind(&app::later_view, this));
WLabel* done = create_menu_label("done", "btn muda-done-button");
done->clicked().connect (bind(&app::done_view, this));
WLabel* note = create_menu_label("note", "btn muda-note-button");
note->clicked().connect (bind(&app::note_view, this));
WLabel* menu[] = { all, now, later, done, note};
unsigned int total = 5;
unsigned int last = total - 1;
WContainerWidget* tabs = new WContainerWidget();
WHBoxLayout* layout = new WHBoxLayout();
layout->setSpacing(0);
for(int w = 0; w < total-1; ++w)
{
layout->addWidget(menu[w]);
layout->setStretchFactor(menu[w], 1);
layout->addSpacing(WLength(8, WLength::Pixel));
}
layout->addWidget(menu[last]);
layout->setStretchFactor(menu[last], 1);
layout->setContentsMargins(0,0,0,0);
tabs->setLayout(layout);
tabs->setStyleClass("menu-container");
return tabs;
}
void app::create_header_ui()
{
WContainerWidget* menu = create_menu();
root()->addWidget(menu);
_new_muda = new WLineEdit();
_new_muda->resize(WLength(100, WLength::Percentage), WLength::Auto);
_new_muda->setStyleClass("new-muda");
WHBoxLayout* hbox = new WHBoxLayout();
hbox->setSpacing(0);
hbox->addWidget(_new_muda);
hbox->setContentsMargins(0,0,0,0);
WContainerWidget* container = new WContainerWidget();
container->setLayout(hbox);
root()->addWidget(container);
}
bool app::filter_by_all(mm::muda_ptr muda)
{
return true;
}
bool app::filter_by_now(mm::muda_ptr muda)
{
BOOST_ASSERT(muda);
return muda->type().state() == m::NOW;
}
bool app::filter_by_later(mm::muda_ptr muda)
{
BOOST_ASSERT(muda);
return muda->type().state() == m::LATER;
}
bool app::filter_by_done(mm::muda_ptr muda)
{
BOOST_ASSERT(muda);
return muda->type().state() == m::DONE;
}
bool app::filter_by_note(mm::muda_ptr muda)
{
BOOST_ASSERT(muda);
return muda->type().state() == m::NOTE;
}
mm::muda_ptr app::add_new_muda()
{
BOOST_ASSERT(_new_muda);
//create new muda and add it to muda list
mm::muda_ptr muda(new mm::muda);
mc::modify_muda_text modify_text(*muda, _new_muda->text());
modify_text();
mc::add_muda add(muda, _mudas);
add();
return muda;
}
void app::add_new_now_muda()
{
BOOST_ASSERT(_new_muda);
mm::muda_ptr muda = add_new_muda();
muda->type().now();
add_muda_to_list_widget(muda);
}
void app::add_new_later_muda()
{
BOOST_ASSERT(_new_muda);
mm::muda_ptr muda = add_new_muda();
muda->type().later();
add_muda_to_list_widget(muda);
}
void app::add_new_done_muda()
{
BOOST_ASSERT(_new_muda);
mm::muda_ptr muda = add_new_muda();
muda->type().done();
add_muda_to_list_widget(muda);
}
void app::add_new_note_muda()
{
BOOST_ASSERT(_new_muda);
mm::muda_ptr muda = add_new_muda();
muda->type().note();
add_muda_to_list_widget(muda);
}
void app::add_muda_to_list_widget(mm::muda_ptr muda)
{
BOOST_ASSERT(muda);
_muda_list_widget->add_muda(muda);
_new_muda->setText(L"");
save_mudas();
}
WApplication *create_application(const WEnvironment& env)
{
WApplication* a = new app(env);
a->useStyleSheet("style.css");
a->setTitle("Muda");
return a;
}
int main(int argc, char **argv)
{
return WRun(argc, argv, &create_application);
}
<commit_msg>disconnected slots from sockets<commit_after>#include <fstream>
#include <Wt/WApplication>
#include <Wt/WBreak>
#include <Wt/WContainerWidget>
#include <Wt/WLineEdit>
#include <Wt/WPushButton>
#include <Wt/WText>
#include <Wt/WLabel>
#include "core/muda.h"
#include "core/context.h"
#include "wtui/mudalistwidget.h"
using namespace Wt;
using boost::bind;
using boost::mem_fn;
namespace m = mempko::muda;
namespace mm = mempko::muda::model;
namespace mc = mempko::muda::context;
namespace mt = mempko::muda::wt;
class app : public WApplication
{
public:
app(const WEnvironment& env);
private:
void login_screen();
void startup_muda_screen();
void create_header_ui();
void all_view();
void now_view();
void later_view();
void done_view();
void note_view();
WContainerWidget* create_menu();
private:
void add_new_now_muda(mt::muda_list_widget* mudas);
void add_new_later_muda(mt::muda_list_widget* mudas);
void add_new_done_muda(mt::muda_list_widget* mudas);
void add_new_note_muda(mt::muda_list_widget* mudas);
mm::muda_ptr add_new_muda();
void add_muda_to_list_widget(mm::muda_ptr muda, mt::muda_list_widget*);
private:
bool filter_by_all(mm::muda_ptr muda);
bool filter_by_now(mm::muda_ptr muda);
bool filter_by_later(mm::muda_ptr muda);
bool filter_by_done(mm::muda_ptr muda);
bool filter_by_note(mm::muda_ptr muda);
private:
void save_mudas();
void load_mudas();
private:
//login widgets
WLineEdit* _muda_file_edit;
std::string _muda_file;
boost::signals2::connection _when_model_updated_connection;
private:
//muda widgets
WLineEdit* _new_muda;
mm::muda_list _mudas;
};
app::app(const WEnvironment& env) :
WApplication(env),
_muda_file("global")
{
login_screen();
}
void app::login_screen()
{
root()->clear();
WHBoxLayout* layout = new WHBoxLayout;
layout->addWidget(new WLabel("Muda List:"), 0, AlignMiddle);
layout->addWidget( _muda_file_edit = new WLineEdit(_muda_file), 0, AlignMiddle);
_muda_file_edit->setFocus();
_muda_file_edit->setStyleClass("muda");
WPushButton* b = new WPushButton("Load");
layout->addWidget(b, 0, AlignMiddle);
layout->addStretch();
b->clicked().connect(bind(&app::startup_muda_screen, this));
_muda_file_edit->enterPressed().connect(bind(&app::startup_muda_screen, this));
root()->setLayout(layout);
}
void app::startup_muda_screen()
{
_muda_file = _muda_file_edit->text().narrow();
setTitle(_muda_file);
load_mudas();
all_view();
}
void app::all_view()
{
_when_model_updated_connection.disconnect();
root()->clear();
create_header_ui();
//create muda list widget
mt::muda_list_widget* list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_all, this, _1), root());
_when_model_updated_connection = list_widget->when_model_updated(bind(&app::save_mudas, this));
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_now_muda, this, list_widget));
}
void app::now_view()
{
_when_model_updated_connection.disconnect();
root()->clear();
create_header_ui();
//create muda list widget
mt::muda_list_widget* list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_now, this, _1), root());
_when_model_updated_connection = list_widget->when_model_updated(bind(&app::save_mudas, this));
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_now_muda, this, list_widget));
}
void app::later_view()
{
_when_model_updated_connection.disconnect();
root()->clear();
create_header_ui();
//create muda list widget
mt::muda_list_widget* list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_later, this, _1), root());
_when_model_updated_connection = list_widget->when_model_updated(bind(&app::save_mudas, this));
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_later_muda, this, list_widget));
}
void app::done_view()
{
_when_model_updated_connection.disconnect();
root()->clear();
create_header_ui();
//create muda list widget
mt::muda_list_widget* list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_done, this, _1), root());
_when_model_updated_connection = list_widget->when_model_updated(bind(&app::save_mudas, this));
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_done_muda, this, list_widget));
}
void app::note_view()
{
_when_model_updated_connection.disconnect();
root()->clear();
create_header_ui();
//create muda list widget
mt::muda_list_widget* list_widget = new mt::muda_list_widget(_mudas, bind(&app::filter_by_note, this, _1), root());
_when_model_updated_connection = list_widget->when_model_updated(bind(&app::save_mudas, this));
//add muda when enter is pressed
_new_muda->enterPressed().connect
(bind(&app::add_new_note_muda, this, list_widget));
}
void app::save_mudas()
{
std::ofstream o(_muda_file.c_str());
boost::archive::xml_oarchive oa(o);
oa << BOOST_SERIALIZATION_NVP(_mudas);
}
void app::load_mudas()
{
std::ifstream i(_muda_file.c_str());
if(!i) return;
boost::archive::xml_iarchive ia(i);
ia >> BOOST_SERIALIZATION_NVP(_mudas);
}
WLabel* create_menu_label(WString text, WString css_class)
{
WLabel* l = new WLabel(text);
l->setStyleClass(css_class);
l->resize(WLength(100, WLength::Percentage), WLength::Auto);
return l;
}
WContainerWidget* app::create_menu()
{
WLabel* all = create_menu_label("all", "btn muda-all-button");
all->clicked().connect (bind(&app::all_view, this));
WLabel* now = create_menu_label("now", "btn muda-now-button");
now->clicked().connect (bind(&app::now_view, this));
WLabel* later = create_menu_label("later", "btn muda-later-button");
later->clicked().connect (bind(&app::later_view, this));
WLabel* done = create_menu_label("done", "btn muda-done-button");
done->clicked().connect (bind(&app::done_view, this));
WLabel* note = create_menu_label("note", "btn muda-note-button");
note->clicked().connect (bind(&app::note_view, this));
WLabel* menu[] = { all, now, later, done, note};
unsigned int total = 5;
unsigned int last = total - 1;
WContainerWidget* tabs = new WContainerWidget();
WHBoxLayout* layout = new WHBoxLayout();
layout->setSpacing(0);
for(int w = 0; w < total-1; ++w)
{
layout->addWidget(menu[w]);
layout->setStretchFactor(menu[w], 1);
layout->addSpacing(WLength(8, WLength::Pixel));
}
layout->addWidget(menu[last]);
layout->setStretchFactor(menu[last], 1);
layout->setContentsMargins(0,0,0,0);
tabs->setLayout(layout);
tabs->setStyleClass("menu-container");
return tabs;
}
void app::create_header_ui()
{
WContainerWidget* menu = create_menu();
root()->addWidget(menu);
_new_muda = new WLineEdit();
_new_muda->resize(WLength(100, WLength::Percentage), WLength::Auto);
_new_muda->setStyleClass("new-muda");
WHBoxLayout* hbox = new WHBoxLayout();
hbox->setSpacing(0);
hbox->addWidget(_new_muda);
hbox->setContentsMargins(0,0,0,0);
WContainerWidget* container = new WContainerWidget();
container->setLayout(hbox);
root()->addWidget(container);
}
bool app::filter_by_all(mm::muda_ptr muda)
{
return true;
}
bool app::filter_by_now(mm::muda_ptr muda)
{
BOOST_ASSERT(muda);
return muda->type().state() == m::NOW;
}
bool app::filter_by_later(mm::muda_ptr muda)
{
BOOST_ASSERT(muda);
return muda->type().state() == m::LATER;
}
bool app::filter_by_done(mm::muda_ptr muda)
{
BOOST_ASSERT(muda);
return muda->type().state() == m::DONE;
}
bool app::filter_by_note(mm::muda_ptr muda)
{
BOOST_ASSERT(muda);
return muda->type().state() == m::NOTE;
}
mm::muda_ptr app::add_new_muda()
{
BOOST_ASSERT(_new_muda);
//create new muda and add it to muda list
mm::muda_ptr muda(new mm::muda);
mc::modify_muda_text modify_text(*muda, _new_muda->text());
modify_text();
mc::add_muda add(muda, _mudas);
add();
return muda;
}
void app::add_new_now_muda(mt::muda_list_widget* mudas)
{
BOOST_ASSERT(_new_muda);
mm::muda_ptr muda = add_new_muda();
muda->type().now();
add_muda_to_list_widget(muda, mudas);
}
void app::add_new_later_muda(mt::muda_list_widget* mudas)
{
BOOST_ASSERT(_new_muda);
mm::muda_ptr muda = add_new_muda();
muda->type().later();
add_muda_to_list_widget(muda, mudas);
}
void app::add_new_done_muda(mt::muda_list_widget* mudas)
{
BOOST_ASSERT(_new_muda);
mm::muda_ptr muda = add_new_muda();
muda->type().done();
add_muda_to_list_widget(muda, mudas);
}
void app::add_new_note_muda(mt::muda_list_widget* mudas)
{
BOOST_ASSERT(_new_muda);
mm::muda_ptr muda = add_new_muda();
muda->type().note();
add_muda_to_list_widget(muda, mudas);
}
void app::add_muda_to_list_widget(mm::muda_ptr muda, mt::muda_list_widget* list_widget)
{
BOOST_ASSERT(muda);
list_widget->add_muda(muda);
_new_muda->setText(L"");
save_mudas();
}
WApplication *create_application(const WEnvironment& env)
{
WApplication* a = new app(env);
a->useStyleSheet("style.css");
a->setTitle("Muda");
return a;
}
int main(int argc, char **argv)
{
return WRun(argc, argv, &create_application);
}
<|endoftext|> |
<commit_before>#include <thread>
#include <iostream>
#include <unistd.h>
#include "exemodel/serveree.h"
#include "exemodel/clientee.h"
#include "exemodel/poller.h"
#include "exemodel/poll_tools.h"
using namespace exemodel;
class CSvr : public poller {
private:
typedef CSvr self_t;
public:
CSvr(uint16_t port)
: poller()
, m_svr(port)
{
m_svr.connect(&self_t::__handler, this);
this->add(m_svr);
}
virtual ~CSvr()
{
this->del(m_svr);
}
private:
void __handler(serveree::args_t & args)
{
char buf[100] = { '\0' };
args.ctx.read(buf, 100);
std::cout << "server recved from" << args.ctx._idx_() << ": " << buf << std::endl;
}
private:
serveree m_svr;
};
class CClient : public poller {
private:
typedef CClient self_t;
public:
CClient(uint32_t ip, uint16_t port)
: m_client(ip, port)
{
m_client.connect(&self_t::__handler, this);
this->add(m_client);
}
virtual ~CClient()
{
this->del(m_client);
}
private:
void __handler(clientee::args_t & args)
{
char buf[100] = { '\0' };
args.ctx.read(buf, 100);
std::cout << "client recved: " << buf << std::endl;
args.ctx.write("world", 6);
}
private:
clientee m_client;
};
int main(void)
{
CSvr svr(5900);
CClient client(0x7F000001, 5900);
std::thread th1(&CSvr::run, std::ref(svr));
std::thread th2(&CClient::run, std::ref(client));
th1.join();
th2.join();
return 0;
}
<commit_msg>remove src/main.cpp<commit_after><|endoftext|> |
<commit_before>#include <vector>
#include <sstream>
#include <experimental/optional>
#include "windows.h"
#include "Objbase.h"
#include "Shlobj.h"
using namespace std;
using namespace std::experimental;
TCHAR select_directory_path[MAX_PATH];
// TODO: A lot of error detection and handling is missing.
class COM {
public:
COM() {
if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) != S_OK)
throw runtime_error("Failed to initialize COM.");
}
~COM() {
CoUninitialize();
}
};
optional<string> select_directory() {
BROWSEINFO browseinfo {};
browseinfo.pszDisplayName = select_directory_path;
browseinfo.lpszTitle = "Please select directory containing the bin files.";
browseinfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON;
PIDLIST_ABSOLUTE idlist = SHBrowseForFolder(&browseinfo);
if (idlist == nullptr) {
return {};
}
else {
if (!SHGetPathFromIDList(idlist, select_directory_path)) {
CoTaskMemFree(idlist);
throw runtime_error("SHGetPathFromIDList failed.");
};
CoTaskMemFree(idlist);
return select_directory_path;
}
}
vector<string> find_bin_files(string directory) {
vector<string> result;
string search_path(directory);
search_path += "\\*.bin";
WIN32_FIND_DATA search_data {};
HANDLE search_handle = FindFirstFile(search_path.c_str(), &search_data);
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
result.emplace_back(search_data.cFileName);
while (FindNextFile(search_handle, &search_data)) {
result.emplace_back(search_data.cFileName);
}
FindClose(search_handle);
}
return result;
}
string generate_cuesheet(vector<string> files) {
stringstream ss;
if (files.size() > 0) {
ss << "FILE \"" << files.at(0) << "\" BINARY\n";
ss << " TRACK 01 MODE2/2352\n";
ss << " INDEX 01 00:00:00\n";
for(size_t track = 1; track < files.size(); ++track) {
ss << "FILE \"" << files.at(track) << "\" BINARY\n";
ss << " TRACK 0" << track << " AUDIO\n";
ss << " INDEX 00 00:00:00\n";
ss << " INDEX 01 00:02:00\n";
};
}
return ss.str();
}
string generate_cuesheet_filename(vector<string> files) {
return "Cuesheet.cue";
}
int main(int argc, const char* argv[]) {
COM com;
auto dir = select_directory();
if (dir) {
auto files = find_bin_files(*dir);
if (files.empty()) {
MessageBox(nullptr, "No bin files found in the selected directory.", "Error", MB_OK | MB_ICONERROR);
} else {
auto cuesheet = generate_cuesheet(files);
string filename = generate_cuesheet_filename(files);
}
}
return 0;
}
<commit_msg>Check if cuesheet file exists<commit_after>#include <vector>
#include <sstream>
#include <experimental/optional>
#include "windows.h"
#include "Objbase.h"
#include "Shlobj.h"
using namespace std;
using namespace std::experimental;
TCHAR select_directory_path[MAX_PATH];
// TODO: A lot of error detection and handling is missing.
class COM {
public:
COM() {
if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) != S_OK)
throw runtime_error("Failed to initialize COM.");
}
~COM() {
CoUninitialize();
}
};
optional<string> select_directory() {
BROWSEINFO browseinfo {};
browseinfo.pszDisplayName = select_directory_path;
browseinfo.lpszTitle = "Please select directory containing the bin files.";
browseinfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON;
PIDLIST_ABSOLUTE idlist = SHBrowseForFolder(&browseinfo);
if (idlist == nullptr) {
return {};
}
else {
if (!SHGetPathFromIDList(idlist, select_directory_path)) {
CoTaskMemFree(idlist);
throw runtime_error("SHGetPathFromIDList failed.");
};
CoTaskMemFree(idlist);
return select_directory_path;
}
}
vector<string> find_bin_files(string directory) {
vector<string> result;
string search_path(directory);
search_path += "\\*.bin";
WIN32_FIND_DATA search_data {};
HANDLE search_handle = FindFirstFile(search_path.c_str(), &search_data);
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
result.emplace_back(search_data.cFileName);
while (FindNextFile(search_handle, &search_data)) {
result.emplace_back(search_data.cFileName);
}
FindClose(search_handle);
}
return result;
}
string generate_cuesheet(vector<string> files) {
stringstream ss;
if (files.size() > 0) {
ss << "FILE \"" << files.at(0) << "\" BINARY\n";
ss << " TRACK 01 MODE2/2352\n";
ss << " INDEX 01 00:00:00\n";
for(size_t track = 1; track < files.size(); ++track) {
ss << "FILE \"" << files.at(track) << "\" BINARY\n";
ss << " TRACK 0" << track << " AUDIO\n";
ss << " INDEX 00 00:00:00\n";
ss << " INDEX 01 00:02:00\n";
};
}
return ss.str();
}
string generate_cuesheet_filename(vector<string> files) {
return "Cuesheet.cue";
}
bool file_exists(string filename) {
WIN32_FIND_DATA find_data {};
HANDLE search_handle = FindFirstFile(filename.c_str(), &find_data);
auto error_code = GetLastError();
FindClose(search_handle);
if (error_code == ERROR_FILE_NOT_FOUND) return false;
if (error_code == ERROR_SUCCESS) return true;
throw runtime_error("File existence check failed.");
}
int main(int argc, const char* argv[]) {
COM com;
auto dir = select_directory();
if (dir) {
auto files = find_bin_files(*dir);
if (files.empty()) {
MessageBox(nullptr, "No bin files found in the selected directory.", "Error", MB_OK | MB_ICONERROR);
} else {
auto cuesheet = generate_cuesheet(files);
string filename = generate_cuesheet_filename(files);
if (file_exists(filename)) {
MessageBox(nullptr, "A cuesheet file already exists. Do you want to overwrite it?", "File exists", MB_YESNO | MB_ICONWARNING);
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// 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.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <iostream>
#include <string>
#include <exception>
#include <vector>
#include <msgpack.hpp>
#include <jubatus/core/common/big_endian.hpp>
#include <jubatus/core/common/jsonconfig/config.hpp>
#include <jubatus/core/common/jsonconfig/cast.hpp>
#include <jubatus/util/data/serialization/unordered_map.h>
#include <jubatus/util/text/json.h>
#include <jubatus/util/lang/cast.h>
#include "third_party/cmdline/cmdline.h"
#include "jubatus/dump/classifier.hpp"
#include "jubatus/dump/recommender.hpp"
#include "jubatus/dump/anomaly.hpp"
#include "jubatus/dump/nearest_neighbor.hpp"
#include "jubatus/dump/unsupported.hpp"
using std::runtime_error;
using jubatus::core::common::read_big_endian;
using jubatus::util::lang::lexical_cast;
using jubatus::util::text::json::from_json;
namespace jubatus {
namespace dump {
struct model {
std::string type_;
jubatus::core::common::jsonconfig::config config_;
std::vector<char> user_data_;
};
void read(std::ifstream& ifs, model& m) {
// TODO(unno): This implementation ignores checksums, version, and all other
// check codes. We need to re-implemenet such process like
// jubatus::server::framework::save_server/load_server, or to use these
// methods to show file format errors.
ifs.exceptions(std::ifstream::failbit);
std::vector<char> system_data_buf;
try {
char header_buf[48];
ifs.read(header_buf, 48);
uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
system_data_buf.resize(system_data_size);
ifs.read(&system_data_buf[0], system_data_size);
uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
m.user_data_.resize(user_data_size);
ifs.read(&m.user_data_[0], user_data_size);
} catch (std::ios_base::failure& e) {
throw runtime_error("Input stream reached end of file.");
}
if (ifs.peek() != -1) {
std::ifstream::pos_type pos = ifs.tellg();
throw runtime_error("Input stream remains. Position: " +
lexical_cast<std::string>(pos));
}
ifs.close();
msgpack::unpacked msg;
msgpack::unpack(&msg, system_data_buf.data(), system_data_buf.size());
msgpack::object system_data = msg.get();
std::string config;
system_data.via.array.ptr[2].convert(&m.type_);
system_data.via.array.ptr[4].convert(&config);
m.config_ = jubatus::core::common::jsonconfig::config(
jubatus::util::lang::lexical_cast<
jubatus::util::text::json::json>(config));
}
template <typename T, typename D>
void dump(model& m, jubatus::util::text::json::json& js) {
msgpack::unpacked msg_user;
msgpack::unpack(&msg_user, m.user_data_.data(), m.user_data_.size());
// obj[0] is the version of the saved model file
T data;
msg_user.get().via.array.ptr[1].convert(&data);
D dump(data);
js = jubatus::util::text::json::to_json(dump);
}
int run(const std::string& path) try {
std::ifstream ifs(path.c_str());
if (!ifs) {
throw runtime_error("Cannot open: " + path);
}
model m;
jubatus::util::text::json::json js;
try {
read(ifs, m);
} catch (const std::exception& e) {
throw runtime_error(std::string("invalid model file structure: ") +
e.what());
}
if (m.type_ == "classifier") {
std::string method;
from_json<std::string>(m.config_["method"].get(), method);
if (method != "NN") {
dump<classifier<linear_classifier>,
classifier_dump<linear_classifier, linear_classifier_dump> >(m, js);
} else {
throw runtime_error("classifier method \"" + method +
"\" is not supported for dump");
}
} else if (m.type_ == "regression") {
// same model data structure as classifier
dump<classifier<local_storage>,
classifier_dump<local_storage, local_storage_dump> >(m, js);
} else if (m.type_ == "recommender") {
std::string method;
from_json<std::string>(m.config_["method"].get(), method);
if (method == "inverted_index") {
dump<recommender<inverted_index>,
recommender_dump<inverted_index_recommender_dump> >(m, js);
} else {
throw runtime_error("recommender method \"" + method +
"\" is not supported for dump");
}
} else if (m.type_ == "anomaly") {
std::string method, backend_method;
from_json<std::string>(m.config_["method"].get(), method);
from_json<std::string>(m.config_["parameter"]["method"].get(),
backend_method);
if (method == "lof") {
if (backend_method == "inverted_index") {
dump<
anomaly<lof<inverted_index> >,
anomaly_dump<lof<inverted_index>, lof_dump<
inverted_index, inverted_index_recommender_dump> > >(m, js);
} else {
std::cerr << "Warning: backend recommender method \""
<< backend_method << "\" is not supported for dump"
<< std::endl;
dump<
anomaly<lof<unsupported_data> >,
anomaly_dump<lof<unsupported_data>, lof_dump<
unsupported_data, unsupported_data_dump> > >(m, js);
}
} else {
std::cerr << "Warning: anomaly method \""
<< method << "\" is not fully supported for dump"
<< std::endl;
dump<
anomaly<unsupported_data>,
anomaly_dump<unsupported_data, unsupported_data_dump> >(m, js);
}
} else if (m.type_ == "nearest_neighbor") {
dump<nearest_neighbor, nearest_neighbor_dump>(m, js);
} else {
throw runtime_error("type \"" + m.type_ +
"\" is not supported for dump");
}
js.pretty(std::cout, true);
return 0;
} catch (const std::exception& e) {
std::cerr << "Error: failed to dump \"" << path
<< "\": " << e.what() << std::endl;
return -1;
}
} // namespace dump
} // namespace jubatus
int main(int argc, char* argv[]) {
cmdline::parser p;
p.add<std::string>("input", 'i', "Input file");
p.parse_check(argc, argv);
return jubatus::dump::run(p.get<std::string>("input"));
}
<commit_msg>fix classifier unsupported method list<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// 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.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <iostream>
#include <string>
#include <exception>
#include <vector>
#include <msgpack.hpp>
#include <jubatus/core/common/big_endian.hpp>
#include <jubatus/core/common/jsonconfig/config.hpp>
#include <jubatus/core/common/jsonconfig/cast.hpp>
#include <jubatus/util/data/serialization/unordered_map.h>
#include <jubatus/util/text/json.h>
#include <jubatus/util/lang/cast.h>
#include "third_party/cmdline/cmdline.h"
#include "jubatus/dump/classifier.hpp"
#include "jubatus/dump/recommender.hpp"
#include "jubatus/dump/anomaly.hpp"
#include "jubatus/dump/nearest_neighbor.hpp"
#include "jubatus/dump/unsupported.hpp"
using std::runtime_error;
using jubatus::core::common::read_big_endian;
using jubatus::util::lang::lexical_cast;
using jubatus::util::text::json::from_json;
namespace jubatus {
namespace dump {
struct model {
std::string type_;
jubatus::core::common::jsonconfig::config config_;
std::vector<char> user_data_;
};
void read(std::ifstream& ifs, model& m) {
// TODO(unno): This implementation ignores checksums, version, and all other
// check codes. We need to re-implemenet such process like
// jubatus::server::framework::save_server/load_server, or to use these
// methods to show file format errors.
ifs.exceptions(std::ifstream::failbit);
std::vector<char> system_data_buf;
try {
char header_buf[48];
ifs.read(header_buf, 48);
uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
system_data_buf.resize(system_data_size);
ifs.read(&system_data_buf[0], system_data_size);
uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
m.user_data_.resize(user_data_size);
ifs.read(&m.user_data_[0], user_data_size);
} catch (std::ios_base::failure& e) {
throw runtime_error("Input stream reached end of file.");
}
if (ifs.peek() != -1) {
std::ifstream::pos_type pos = ifs.tellg();
throw runtime_error("Input stream remains. Position: " +
lexical_cast<std::string>(pos));
}
ifs.close();
msgpack::unpacked msg;
msgpack::unpack(&msg, system_data_buf.data(), system_data_buf.size());
msgpack::object system_data = msg.get();
std::string config;
system_data.via.array.ptr[2].convert(&m.type_);
system_data.via.array.ptr[4].convert(&config);
m.config_ = jubatus::core::common::jsonconfig::config(
jubatus::util::lang::lexical_cast<
jubatus::util::text::json::json>(config));
}
template <typename T, typename D>
void dump(model& m, jubatus::util::text::json::json& js) {
msgpack::unpacked msg_user;
msgpack::unpack(&msg_user, m.user_data_.data(), m.user_data_.size());
// obj[0] is the version of the saved model file
T data;
msg_user.get().via.array.ptr[1].convert(&data);
D dump(data);
js = jubatus::util::text::json::to_json(dump);
}
int run(const std::string& path) try {
std::ifstream ifs(path.c_str());
if (!ifs) {
throw runtime_error("Cannot open: " + path);
}
model m;
jubatus::util::text::json::json js;
try {
read(ifs, m);
} catch (const std::exception& e) {
throw runtime_error(std::string("invalid model file structure: ") +
e.what());
}
if (m.type_ == "classifier") {
std::string method;
from_json<std::string>(m.config_["method"].get(), method);
if (method != "NN" && method != "nearest_neighbor" &&
method != "cosine" && method != "euclidean") {
dump<classifier<linear_classifier>,
classifier_dump<linear_classifier, linear_classifier_dump> >(m, js);
} else {
throw runtime_error("classifier method \"" + method +
"\" is not supported for dump");
}
} else if (m.type_ == "regression") {
// same model data structure as classifier
dump<classifier<local_storage>,
classifier_dump<local_storage, local_storage_dump> >(m, js);
} else if (m.type_ == "recommender") {
std::string method;
from_json<std::string>(m.config_["method"].get(), method);
if (method == "inverted_index") {
dump<recommender<inverted_index>,
recommender_dump<inverted_index_recommender_dump> >(m, js);
} else {
throw runtime_error("recommender method \"" + method +
"\" is not supported for dump");
}
} else if (m.type_ == "anomaly") {
std::string method, backend_method;
from_json<std::string>(m.config_["method"].get(), method);
from_json<std::string>(m.config_["parameter"]["method"].get(),
backend_method);
if (method == "lof") {
if (backend_method == "inverted_index") {
dump<
anomaly<lof<inverted_index> >,
anomaly_dump<lof<inverted_index>, lof_dump<
inverted_index, inverted_index_recommender_dump> > >(m, js);
} else {
std::cerr << "Warning: backend recommender method \""
<< backend_method << "\" is not supported for dump"
<< std::endl;
dump<
anomaly<lof<unsupported_data> >,
anomaly_dump<lof<unsupported_data>, lof_dump<
unsupported_data, unsupported_data_dump> > >(m, js);
}
} else {
std::cerr << "Warning: anomaly method \""
<< method << "\" is not fully supported for dump"
<< std::endl;
dump<
anomaly<unsupported_data>,
anomaly_dump<unsupported_data, unsupported_data_dump> >(m, js);
}
} else if (m.type_ == "nearest_neighbor") {
dump<nearest_neighbor, nearest_neighbor_dump>(m, js);
} else {
throw runtime_error("type \"" + m.type_ +
"\" is not supported for dump");
}
js.pretty(std::cout, true);
return 0;
} catch (const std::exception& e) {
std::cerr << "Error: failed to dump \"" << path
<< "\": " << e.what() << std::endl;
return -1;
}
} // namespace dump
} // namespace jubatus
int main(int argc, char* argv[]) {
cmdline::parser p;
p.add<std::string>("input", 'i', "Input file");
p.parse_check(argc, argv);
return jubatus::dump::run(p.get<std::string>("input"));
}
<|endoftext|> |
<commit_before>/**
* Project
* # # # ###### ######
* # # # # # # # #
* # # # # # # # #
* ### # # ###### ######
* # # ####### # # # #
* # # # # # # # #
* # # # # # # # #
*
* Copyright (c) 2014, Project KARR
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <vg/openvg.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>
#include <bgfx.h>
#include <bgfxplatform.h>
#include <nanovg.h>
#include <nanovg_gl.h>
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include "ArduinoDataPacket.h"
#include "Instrument.h"
#include "SerialConnection.h"
#include "TestInput.h"
#include "Knight_Industries.C"
using namespace KARR;
using namespace std;
/* Globals */
NVGcontext *gNanoVGContext = nullptr;
/* Statics */
static const int w = 1024;
static const int h = 600;
static SDL_Window *sSdlWindow = nullptr;
static SerialConnection sArduinoConnection;
static std::vector<Instrument *> sInstruments;
static ArduinoDataPacket sDataPacket;
void handleKeyboard(unsigned char key, int x, int y) {
if (key == 27)
exit(0);
}
void KARRArduinoProtocol(const ArduinoDataPacket &packet) {
if (packet.version == 7) {
sInstruments[Instrument::IID_REVS]->update(packet.analog[0]);
sInstruments[Instrument::IID_SPEED]->update(packet.analog[1]);
sInstruments[Instrument::IID_FUEL_LEVEL]->update(packet.analog[2]);
sInstruments[Instrument::IID_BOOST_LEVEL]->update(packet.analog[3]);
}
}
void handleCommunication() {
{ /* Read data from Arduino */
if (sArduinoConnection.isOpened()) {
memset(&sDataPacket, '\0', sizeof(ArduinoDataPacket));
if (sArduinoConnection.read((void *)&sDataPacket, sizeof(ArduinoDataPacket))) {
// Update data
KARRArduinoProtocol(sDataPacket);
}
}
}
}
void handleDisplay() {
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, w, h);
// This dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
bgfx::submit(0);
// Use debug font to print information about this example.
bgfx::dbgTextClear();
bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld");
bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text.");
nvgBeginFrame(gNanoVGContext, w, h, 1.0f);
for (Instrument *instrument : sInstruments) {
if (instrument)
instrument->draw();
}
nvgEndFrame(gNanoVGContext);
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
}
int initScreen() {
SDL_InitSubSystem(SDL_INIT_VIDEO);
sSdlWindow = SDL_CreateWindow("karr",
SDL_WINDOWPOS_UNDEFINED , SDL_WINDOWPOS_UNDEFINED,
w , h , SDL_WINDOW_SHOWN);
bgfx::sdlSetWindow(sSdlWindow);
bgfx::init();
bgfx::reset(w, h, BGFX_RESET_VSYNC);
gNanoVGContext = nvgCreateGLES2(0);
assert(gNanoVGContext);
// Set view 0 clear state.
bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH,
0x303030ff, 1.0f, 0);
return 0;
}
void deinitScreen() {
nvgDeleteGLES2(gNanoVGContext);
// Shutdown bgfx.
bgfx::shutdown();
SDL_DestroyWindow(sSdlWindow);
SDL_Quit();
}
void initInstruments() {
boost::filesystem::path instrumentsXMLPath(""); // TODO get path
boost::property_tree::ptree instrumentsTree;
boost::property_tree::read_xml(instrumentsXMLPath.string(), instrumentsTree, boost::property_tree::xml_parser::no_comments);
// Parse into a temp vector.
std::vector<Instrument *> instruments;
Instrument::ParseInstruments(instrumentsTree, instruments);
// Determine max id for size.
Instrument::InstrumentId maxId = Instrument::IID_UNKNOWN;
for (Instrument *instr : instruments) {
if (instr->getId() > maxId)
maxId = instr->getId();
}
// Populate the instruments with the parsed. May result in sparse vector.
if (maxId > -1 && maxId < 1024) {
sInstruments.resize(maxId + 1, nullptr);
for (Instrument *instr : instruments) {
sInstruments[instr->getId()] = instr;
}
}
}
void deinitInstruments() {
for (Instrument *instr : sInstruments) {
delete instr;
}
}
void initCommunication() {
sArduinoConnection.open("/dev/ttyAMA0");
}
void deinitCommunication() {
sArduinoConnection.close();
}
void cleanup() {
deinitCommunication();
deinitInstruments();
deinitScreen();
}
int main(int argc, char** argv) {
atexit(cleanup);
SDL_Init(0);
initScreen();
initInstruments();
initCommunication();
TestInput::run();
do {
SDL_Event event;
if (SDL_PollEvent(&event)) {
// Do something with event
}
handleCommunication();
handleDisplay();
} while (1);
return 0;
}
<commit_msg>Set up the OpenGL window properly.<commit_after>/**
* Project
* # # # ###### ######
* # # # # # # # #
* # # # # # # # #
* ### # # ###### ######
* # # ####### # # # #
* # # # # # # # #
* # # # # # # # #
*
* Copyright (c) 2014, Project KARR
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <vg/openvg.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>
#include <bgfx.h>
#include <bgfxplatform.h>
#include <nanovg.h>
#include <nanovg_gl.h>
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include "ArduinoDataPacket.h"
#include "Instrument.h"
#include "SerialConnection.h"
#include "TestInput.h"
#include "Knight_Industries.C"
using namespace KARR;
using namespace std;
/* Globals */
NVGcontext *gNanoVGContext = nullptr;
/* Statics */
static const int w = 1024;
static const int h = 600;
static SDL_Window *sSdlWindow = nullptr;
static SDL_GLContext sGLContext;
static SerialConnection sArduinoConnection;
static std::vector<Instrument *> sInstruments;
static ArduinoDataPacket sDataPacket;
void handleKeyboard(unsigned char key, int x, int y) {
if (key == 27)
exit(0);
}
void KARRArduinoProtocol(const ArduinoDataPacket &packet) {
if (packet.version == 7) {
sInstruments[Instrument::IID_REVS]->update(packet.analog[0]);
sInstruments[Instrument::IID_SPEED]->update(packet.analog[1]);
sInstruments[Instrument::IID_FUEL_LEVEL]->update(packet.analog[2]);
sInstruments[Instrument::IID_BOOST_LEVEL]->update(packet.analog[3]);
}
}
void handleCommunication() {
{ /* Read data from Arduino */
if (sArduinoConnection.isOpened()) {
memset(&sDataPacket, '\0', sizeof(ArduinoDataPacket));
if (sArduinoConnection.read((void *)&sDataPacket, sizeof(ArduinoDataPacket))) {
// Update data
KARRArduinoProtocol(sDataPacket);
}
}
}
}
void handleDisplay() {
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, w, h);
// This dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
bgfx::submit(0);
// Use debug font to print information about this example.
bgfx::dbgTextClear();
bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld");
bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text.");
nvgBeginFrame(gNanoVGContext, w, h, 1.0f);
for (Instrument *instrument : sInstruments) {
if (instrument)
instrument->draw();
}
nvgEndFrame(gNanoVGContext);
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
}
int initScreen() {
SDL_InitSubSystem(SDL_INIT_VIDEO);
if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2) < 0)
abort();
if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0) < 0)
abort();
if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES) < 0)
abort();
sSdlWindow = SDL_CreateWindow("karr",
SDL_WINDOWPOS_UNDEFINED , SDL_WINDOWPOS_UNDEFINED,
w , h , SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
sGLContext = SDL_GL_CreateContext(sSdlWindow);
bgfx::sdlSetWindow(sSdlWindow);
bgfx::init();
bgfx::reset(w, h, BGFX_RESET_VSYNC);
gNanoVGContext = nvgCreateGLES2(0);
assert(gNanoVGContext);
// Set view 0 clear state.
bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH,
0x303030ff, 1.0f, 0);
return 0;
}
void deinitScreen() {
nvgDeleteGLES2(gNanoVGContext);
// Shutdown bgfx.
bgfx::shutdown();
SDL_GL_DeleteContext(sGLContext);
SDL_DestroyWindow(sSdlWindow);
SDL_Quit();
}
void initInstruments() {
boost::filesystem::path instrumentsXMLPath(""); // TODO get path
boost::property_tree::ptree instrumentsTree;
boost::property_tree::read_xml(instrumentsXMLPath.string(), instrumentsTree, boost::property_tree::xml_parser::no_comments);
// Parse into a temp vector.
std::vector<Instrument *> instruments;
Instrument::ParseInstruments(instrumentsTree, instruments);
// Determine max id for size.
Instrument::InstrumentId maxId = Instrument::IID_UNKNOWN;
for (Instrument *instr : instruments) {
if (instr->getId() > maxId)
maxId = instr->getId();
}
// Populate the instruments with the parsed. May result in sparse vector.
if (maxId > -1 && maxId < 1024) {
sInstruments.resize(maxId + 1, nullptr);
for (Instrument *instr : instruments) {
sInstruments[instr->getId()] = instr;
}
}
}
void deinitInstruments() {
for (Instrument *instr : sInstruments) {
delete instr;
}
}
void initCommunication() {
sArduinoConnection.open("/dev/ttyAMA0");
}
void deinitCommunication() {
sArduinoConnection.close();
}
void cleanup() {
deinitCommunication();
deinitInstruments();
deinitScreen();
}
int main(int argc, char** argv) {
atexit(cleanup);
SDL_Init(0);
initScreen();
initInstruments();
initCommunication();
TestInput::run();
do {
SDL_Event event;
if (SDL_PollEvent(&event)) {
// Do something with event
}
handleCommunication();
handleDisplay();
} while (1);
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <compile_time.hpp>
namespace myspace
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE(int)
REGISTER_TYPE(float)
REGISTER_TYPE(double)
REGISTER_TYPE_END()
}
template <class T>
void p(T)
{
puts(__PRETTY_FUNCTION__);
}
int
main()
{
p(myspace::instantiated_compile_time_infos());
for(auto str : myspace::type_name_array_holder::value)
{
std::cout << str << '\n';
}
for(auto& cti : myspace::type_info_array_holder::value)
{
std::cout << cti.name << " : " << cti.size << '\n';
}
}
<commit_msg>Add example of type director. modified: src/main.cpp<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <compile_time.hpp>
namespace myspace
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE(int)
REGISTER_TYPE(float)
REGISTER_TYPE(double)
REGISTER_TYPE_END()
}
template <class T>
void p(T)
{
puts(__PRETTY_FUNCTION__);
}
class director
{
public:
template <class NameHolder, class TypeInfoHolder>
director(NameHolder, TypeInfoHolder)
: names_(std::begin(NameHolder::value), std::end(NameHolder::value)),
type_infos_(std::begin(TypeInfoHolder::value),
std::end(TypeInfoHolder::value))
{
}
std::vector<std::string>::const_iterator
names_begin() const
{
return names_.cbegin();
}
std::vector<std::string>::const_iterator
names_end() const
{
return names_.cend();
}
private:
std::vector<std::string> names_;
std::vector<shadow::type_info> type_infos_;
};
static const director thedir((myspace::type_name_array_holder()),
myspace::type_info_array_holder());
int
main()
{
for(auto i = thedir.names_begin(); i != thedir.names_end(); ++i)
{
std::cout << *i << '\n';
}
}
<|endoftext|> |
<commit_before>/* main.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*/
#include <cmath>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include "individual/individual.hpp"
#include "problem/problem.hpp"
int test_runner() {
// basic test runner
using individual::Individual;
using problem::pairs;
using problem::Problem;
std::ifstream test_file("test/cs472.dat");
if (!test_file.is_open()) return 1;
pairs values;
while (!test_file.eof()) {
// fill values vector with (x, y) pairs
int x;
double y;
test_file >> x >> y;
values.emplace_back(std::make_tuple(x, y));
}
// create Problem and population of Individuals
const int population_size = 4096;
const int tree_depth = 4;
const Problem problem(values, tree_depth);
std::vector<Individual> population;
for (int i = 0; i < population_size; ++i)
population.emplace_back(Individual(problem));
// find Individual with lowest "fitness" AKA error from populaiton
Individual best = *std::min_element(population.begin(), population.end(), [](const Individual & a, const Individual & b)->bool {return a.get_fitness() < b.get_fitness();});
// calculate sum of fitnesses
double total_fitness = std::accumulate(population.begin(), population.end(), 0., [](const double & a, const Individual & b)->double const {return a + b.get_fitness();});
// caclulate sum of tree sizes
int total_size = std::accumulate(population.begin(), population.end(), 0, [](const int & a, const Individual & b)->double const {return a + b.get_total();});
// print results
best.print_formula();
best.print_calculation();
std::cout << "Average fitness: " << total_fitness / population.size() << std::endl;
std::cout << "Average size: " << total_size / population.size() << std::endl;
return 0;
}
int main() {
return test_runner();
}
<commit_msg>Updating test depth/population size<commit_after>/* main.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*/
#include <cmath>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include "individual/individual.hpp"
#include "problem/problem.hpp"
int test_runner() {
// basic test runner
using individual::Individual;
using problem::pairs;
using problem::Problem;
std::ifstream test_file("test/cs472.dat");
if (!test_file.is_open()) return 1;
pairs values;
while (!test_file.eof()) {
// fill values vector with (x, y) pairs
int x;
double y;
test_file >> x >> y;
values.emplace_back(std::make_tuple(x, y));
}
// create Problem and population of Individuals
const int population_size = 128;
const int tree_depth = 3;
const Problem problem(values, tree_depth);
std::vector<Individual> population;
for (int i = 0; i < population_size; ++i)
population.emplace_back(Individual(problem));
// find Individual with lowest "fitness" AKA error from populaiton
Individual best = *std::min_element(population.begin(), population.end(), [](const Individual & a, const Individual & b)->bool {return a.get_fitness() < b.get_fitness();});
// calculate sum of fitnesses
double total_fitness = std::accumulate(population.begin(), population.end(), 0., [](const double & a, const Individual & b)->double const {return a + b.get_fitness();});
// caclulate sum of tree sizes
int total_size = std::accumulate(population.begin(), population.end(), 0, [](const int & a, const Individual & b)->double const {return a + b.get_total();});
// print results
best.print_formula();
best.print_calculation();
std::cout << "Average fitness: " << total_fitness / population.size() << std::endl;
std::cout << "Average size: " << total_size / population.size() << std::endl;
return 0;
}
int main() {
return test_runner();
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "init.h"
#include "util.h"
#include "version.h"
using std::chrono::duration;
using std::chrono::steady_clock;
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::map;
using std::setprecision;
using std::size_t;
using std::stoi;
using std::string;
using std::stringstream;
using std::to_string;
using std::unique_ptr;
using std::vector;
void DoProcessing(vector<string> *i,
const unique_ptr<map<string, vector<string>>> &m_token,
const unique_ptr<map<string, vector<string>>> &v_token,
const unique_ptr<vector<vector<string>>> &patterns) {
for (size_t it = 0; it < i->size(); ++it) {
// input vector size checks
if (i->size() <= 1) {
break;
}
// punctuation checks
if (i->at(it).back() == ',') { // (.+),
i->at(it).pop_back();
continue;
} else if ((i->at(it).back()) == '.' &&
(i->at(it).at(i->at(it).size() - 2)) != '.') { // (.+)(?!(\.+)\.)
i->at(it).pop_back();
continue;
} else if (i->at(it).find("\'") != string::npos) { // (.*\'.*) i.e. contractions
MergeTokens(i, it);
continue;
}
// string length checks
if (CheckStringLength(i->at(it), 6)) { // don't process if word is longer than 6-char
continue;
}
// word pattern matches
vector<string> *match = nullptr;
string modifier{};
for (auto &&p : *patterns) { // loop patterns
if (match != nullptr) {
break;
}
match = &p;
for (size_t iit = 0; iit < p.size(); ++iit) { // loop pattern tokens
modifier = "";
string pattern{ReadTokenType(p.at(iit))};
if (pattern.at(0) == 'T') {
if (StringIsMatch(i->at(it + iit), m_token->at(pattern.substr(1, pattern.size())))) {
continue;
}
} else if (pattern.at(0) == 'L') {
if (StringIsMatch(i->at(it + iit), {pattern.substr(1, pattern.size())})) {
continue;
}
} else if (pattern.at(0) == 'W') {
continue;
} else if (pattern.at(0) == 'V') {
if (pattern.at(1) == 'W') {
if (SearchVerbTokens(i->at(it + iit), v_token)) {
continue;
}
} else {
if (SearchVerbTokens(i->at(it + iit), v_token, pattern.substr(1, pattern.size()))) {
continue;
}
}
} else if ((pattern.at(0) == 'M') && (pattern.find("VERSION") == string::npos)) {
modifier = pattern.substr(1, pattern.size());
continue;
}
match = nullptr;
break;
}
}
if (match != nullptr) {
for (size_t l = 1; l < match->size(); ++l)
if (modifier != "") {
++l;
if (modifier.substr(0, 2) == "l=") {
MergeTokens(i, it, stoi(modifier.substr(2, modifier.size())));
} else {
MergeTokens(i, it);
}
} else {
MergeTokens(i, it);
}
}
}
}
void OutputHelp(const char c[]) {
cout << "Usage: " << c << " [OPTION]..." << endl;
cout << "Converts a sentence to line-delimited phrases" << endl << endl;
cout << " -t, --token=[FILE]\tset token file path to [FILE]" << endl;
cout << " -p, --pattern=[FILE]\tset pattern file path to [FILE]" << endl;
cout << " --help\t\tdisplay this help and exit" << endl;
cout << " --version\t\toutput version information and exit" << endl;
}
int main(int argc, char *argv[]) {
// read input arguments
vector<string> argvec{};
if (argc > 1) {
for (int i = 1; i < argc; i++) {
argvec.emplace_back(argv[i]);
}
}
// analyze command line switches
string token_src = "../tokens";
string pattern_src = "../patterns";
for (size_t i = 0; i < argvec.size(); ++i) {
if (argvec.at(i) == "-t") {
token_src = argvec.at(++i);
} else if (argvec.at(i) == "-p") {
pattern_src = argvec.at(++i);
} else if (argvec.at(i).substr(0, 6) == "--token=") {
token_src = argvec.at(i).substr(6, argvec.at(i).size());
} else if (argvec.at(i).substr(0, 10) == "--pattern=") {
pattern_src = argvec.at(++i);
} else if (argvec.at(i) == "--help") {
OutputHelp(argv[0]);
return 0;
} else if (argvec.at(i) == "--version") {
cout << "Amyspeak " << kBuildString << endl;
cout << "Copyright (C) 2017 Derppening" << endl;
cout << "Written by David Mak." << endl;
return 0;
}
}
if (token_src.at(0) != '.' && token_src.at(1) != '.') {
token_src.insert(0, "./");
}
if (pattern_src.at(0) != '.' && pattern_src.at(1) != '.') {
pattern_src.insert(0, "./");
}
cout << "Reading tokens from " << token_src << endl;
cout << "Reading patterns from " << pattern_src << endl;
// see if the files exist
unique_ptr<ifstream> token_file(new ifstream(token_src));
if (!token_file->is_open()) {
cout << "Error: Tokens file not found. Exiting." << endl;
return 0;
}
unique_ptr<ifstream> pattern_file(new ifstream(pattern_src));
if (!pattern_file->is_open()) {
cout << "Error: Patterns file not found. Exiting." << endl;
return 0;
}
auto time = steady_clock::now();
// read and save normal tokens
cout << "Initializing tokens... ";
auto tokens = ParseTokens(*token_file);
auto token_pos = ParseTokenCategories(*tokens);
auto match_tokens = ConstructMatchingTokens(*tokens, *token_pos);
cout << "Done." << endl;
// read and save verb tokens
cout << "Initializing verb tokens... ";
unique_ptr<map<string, vector<string>>> match_verbs = nullptr;
for (auto &&i : *token_pos) {
if (i.second == "verb") {
match_verbs = ConstructVerbToken(*tokens, i.first);
break;
}
}
if (match_verbs == nullptr) {
cout << "Not found." << endl;
} else {
cout << "Done." << endl;
}
const string token_version_string = ReadTokensVersion(*tokens);
tokens.reset(nullptr);
token_file.reset(nullptr);
token_pos.reset(nullptr);
// read and save patterns
cout << "Initializing patterns... ";
auto patterns = ParsePatterns(*pattern_file, match_tokens, match_verbs);
const string pattern_version_string = ReadPatternsVersion(*patterns);
cout << "Done." << endl;
pattern_file.reset(nullptr);
if (token_version_string != "") {
cout << "Tokens library version: " << token_version_string << endl;
}
if (pattern_version_string != "") {
cout << "Patterns library version: " << pattern_version_string << endl;
}
auto time_taken = duration<double, std::milli>(steady_clock::now() - time);
cout << setprecision(4) << "Initialization complete. Took "
<< time_taken.count() << " ms." << endl << endl;
cout << "Type ':clear' to clear the console, "<< endl
<< " ':q' to quit." << endl;
while (true) {
cout << "> ";
string input;
getline(cin, input);
if (input == ":q") break;
string buf{};
stringstream ss_buf(input);
vector<string> input_tokens;
while (ss_buf >> buf) {
input_tokens.emplace_back(buf);
}
// do processing
if (input_tokens.size() == 1) {
if (input_tokens.at(0) == "exit") {
cout << "Type ':q' to quit" << endl;
continue;
} else if (input_tokens.at(0) == ":clear") {
if (system("cls")) {
system("clear");
}
continue;
}
}
DoProcessing(&input_tokens, match_tokens, match_verbs, patterns);
OutputTokens(input_tokens);
}
return 0;
}
<commit_msg>Use stoul instead of stoi for string to int conversion<commit_after>#include <algorithm>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "init.h"
#include "util.h"
#include "version.h"
using std::chrono::duration;
using std::chrono::steady_clock;
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::map;
using std::setprecision;
using std::size_t;
using std::stoul;
using std::string;
using std::stringstream;
using std::to_string;
using std::unique_ptr;
using std::vector;
void DoProcessing(vector<string> *i,
const unique_ptr<map<string, vector<string>>> &m_token,
const unique_ptr<map<string, vector<string>>> &v_token,
const unique_ptr<vector<vector<string>>> &patterns) {
for (size_t it = 0; it < i->size(); ++it) {
// input vector size checks
if (i->size() <= 1) {
break;
}
// punctuation checks
if (i->at(it).back() == ',') { // (.+),
i->at(it).pop_back();
continue;
} else if ((i->at(it).back()) == '.' &&
(i->at(it).at(i->at(it).size() - 2)) != '.') { // (.+)(?!(\.+)\.)
i->at(it).pop_back();
continue;
} else if (i->at(it).find("\'") != string::npos) { // (.*\'.*) i.e. contractions
MergeTokens(i, it);
continue;
}
// string length checks
if (CheckStringLength(i->at(it), 6)) { // don't process if word is longer than 6-char
continue;
}
// word pattern matches
vector<string> *match = nullptr;
string modifier{};
for (auto &&p : *patterns) { // loop patterns
if (match != nullptr) {
break;
}
match = &p;
for (size_t iit = 0; iit < p.size(); ++iit) { // loop pattern tokens
modifier = "";
string pattern{ReadTokenType(p.at(iit))};
if (pattern.at(0) == 'T') {
if (StringIsMatch(i->at(it + iit), m_token->at(pattern.substr(1, pattern.size())))) {
continue;
}
} else if (pattern.at(0) == 'L') {
if (StringIsMatch(i->at(it + iit), {pattern.substr(1, pattern.size())})) {
continue;
}
} else if (pattern.at(0) == 'W') {
continue;
} else if (pattern.at(0) == 'V') {
if (pattern.at(1) == 'W') {
if (SearchVerbTokens(i->at(it + iit), v_token)) {
continue;
}
} else {
if (SearchVerbTokens(i->at(it + iit), v_token, pattern.substr(1, pattern.size()))) {
continue;
}
}
} else if ((pattern.at(0) == 'M') && (pattern.find("VERSION") == string::npos)) {
modifier = pattern.substr(1, pattern.size());
continue;
}
match = nullptr;
break;
}
}
if (match != nullptr) {
for (size_t l = 1; l < match->size(); ++l)
if (modifier != "") {
++l;
if (modifier.substr(0, 2) == "l=") {
MergeTokens(i, it, stoul(modifier.substr(2, modifier.size())));
} else {
MergeTokens(i, it);
}
} else {
MergeTokens(i, it);
}
}
}
}
void OutputHelp(const char c[]) {
cout << "Usage: " << c << " [OPTION]..." << endl;
cout << "Converts a sentence to line-delimited phrases" << endl << endl;
cout << " -t, --token=[FILE]\tset token file path to [FILE]" << endl;
cout << " -p, --pattern=[FILE]\tset pattern file path to [FILE]" << endl;
cout << " --help\t\tdisplay this help and exit" << endl;
cout << " --version\t\toutput version information and exit" << endl;
}
int main(int argc, char *argv[]) {
// read input arguments
vector<string> argvec{};
if (argc > 1) {
for (int i = 1; i < argc; i++) {
argvec.emplace_back(argv[i]);
}
}
// analyze command line switches
string token_src = "../tokens";
string pattern_src = "../patterns";
for (size_t i = 0; i < argvec.size(); ++i) {
if (argvec.at(i) == "-t") {
token_src = argvec.at(++i);
} else if (argvec.at(i) == "-p") {
pattern_src = argvec.at(++i);
} else if (argvec.at(i).substr(0, 6) == "--token=") {
token_src = argvec.at(i).substr(6, argvec.at(i).size());
} else if (argvec.at(i).substr(0, 10) == "--pattern=") {
pattern_src = argvec.at(++i);
} else if (argvec.at(i) == "--help") {
OutputHelp(argv[0]);
return 0;
} else if (argvec.at(i) == "--version") {
cout << "Amyspeak " << kBuildString << endl;
cout << "Copyright (C) 2017 Derppening" << endl;
cout << "Written by David Mak." << endl;
return 0;
}
}
if (token_src.at(0) != '.' && token_src.at(1) != '.') {
token_src.insert(0, "./");
}
if (pattern_src.at(0) != '.' && pattern_src.at(1) != '.') {
pattern_src.insert(0, "./");
}
cout << "Reading tokens from " << token_src << endl;
cout << "Reading patterns from " << pattern_src << endl;
// see if the files exist
unique_ptr<ifstream> token_file(new ifstream(token_src));
if (!token_file->is_open()) {
cout << "Error: Tokens file not found. Exiting." << endl;
return 0;
}
unique_ptr<ifstream> pattern_file(new ifstream(pattern_src));
if (!pattern_file->is_open()) {
cout << "Error: Patterns file not found. Exiting." << endl;
return 0;
}
auto time = steady_clock::now();
// read and save normal tokens
cout << "Initializing tokens... ";
auto tokens = ParseTokens(*token_file);
auto token_pos = ParseTokenCategories(*tokens);
auto match_tokens = ConstructMatchingTokens(*tokens, *token_pos);
cout << "Done." << endl;
// read and save verb tokens
cout << "Initializing verb tokens... ";
unique_ptr<map<string, vector<string>>> match_verbs = nullptr;
for (auto &&i : *token_pos) {
if (i.second == "verb") {
match_verbs = ConstructVerbToken(*tokens, i.first);
break;
}
}
if (match_verbs == nullptr) {
cout << "Not found." << endl;
} else {
cout << "Done." << endl;
}
const string token_version_string = ReadTokensVersion(*tokens);
tokens.reset(nullptr);
token_file.reset(nullptr);
token_pos.reset(nullptr);
// read and save patterns
cout << "Initializing patterns... ";
auto patterns = ParsePatterns(*pattern_file, match_tokens, match_verbs);
const string pattern_version_string = ReadPatternsVersion(*patterns);
cout << "Done." << endl;
pattern_file.reset(nullptr);
if (token_version_string != "") {
cout << "Tokens library version: " << token_version_string << endl;
}
if (pattern_version_string != "") {
cout << "Patterns library version: " << pattern_version_string << endl;
}
auto time_taken = duration<double, std::milli>(steady_clock::now() - time);
cout << setprecision(4) << "Initialization complete. Took "
<< time_taken.count() << " ms." << endl << endl;
cout << "Type ':clear' to clear the console, "<< endl
<< " ':q' to quit." << endl;
while (true) {
cout << "> ";
string input;
getline(cin, input);
if (input == ":q") break;
string buf{};
stringstream ss_buf(input);
vector<string> input_tokens;
while (ss_buf >> buf) {
input_tokens.emplace_back(buf);
}
// do processing
if (input_tokens.size() == 1) {
if (input_tokens.at(0) == "exit") {
cout << "Type ':q' to quit" << endl;
continue;
} else if (input_tokens.at(0) == ":clear") {
if (system("cls")) {
system("clear");
}
continue;
}
}
DoProcessing(&input_tokens, match_tokens, match_verbs, patterns);
OutputTokens(input_tokens);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "MyMallocator.hpp"
#include <type_traits>
#include "vector.hpp"
void ConstructorTest();
void AssignmentTest();
void IteratorTest();
void DimensionTest();
void AccessorTest();
void AddRemoveTest();
void RelationalTest();
template<typename T, typename A, int N>
void PrintMyVec(const custom_std::vector<T, A>&, const char(&)[N]);
template<typename T>
using allocator_type = MyMallocator<T>;
template<typename T>
using vec_type = custom_std::vector < T, allocator_type<T> >;
template class custom_std::vector < int, allocator_type<int> >;
template class custom_std::vector < bool, allocator_type<bool> >;
int main()
{
std::cout.sync_with_stdio(false);
ConstructorTest();
AssignmentTest();
IteratorTest();
DimensionTest();
AccessorTest();
AddRemoveTest();
RelationalTest();
std::cin.get();
}
void ConstructorTest()
{
allocator_type<int> alloc;
vec_type<int> v1;
vec_type<int> v2(alloc);
vec_type<int> v3(10);
vec_type<int> v4(10, 11);
vec_type<int> v5(v3.begin(), v3.end());
vec_type<int> v6(v4);
vec_type<int> v7(std::move(v5));
vec_type<int> v8(v4, alloc);
vec_type<int> v9(std::move(v3), alloc);
vec_type<int> v10{ 11, 22, 33, 44, 55, 66 };
(void)v1, (void)v2, (void)v6, (void)v7,
(void)v8, (void)v9, (void)v10;
}
void AssignmentTest()
{
vec_type<int> v1;
vec_type<int> v2;
vec_type<int> v3;
v1 = v2;
v2 = std::move(v3);
v3 = { 1, 2, 4, 8, 16, 32, 64, 128, 256 };
v1.assign(v3.begin(), v3.end());
v2.assign(16, 42);
v3.assign({ 1992304, 5707245, 234985, 2626, 666 });
}
void IteratorTest()
{
struct X { int a; };
vec_type<X> v(1);
auto allocInstance = v.get_allocator();
auto i1 = v.begin();
(void)v.end();
auto i3 = v.rbegin();
(void)v.rend();
auto i5 = v.cbegin();
(void)v.cend();
auto i7 = v.crbegin();
(void)v.crend();
(void)*i1, (void)*i3, (void)*i5, (void)*i7;
(void)i1->a, (void)i3->a, (void)i5->a, (void)i7->a;
(void)++i1, (void)++i3, (void)++i5, (void)++i7;
(void)i1++, (void)i3++, (void)i5++, (void)i7++;
(void)--i1, (void)--i3, (void)--i5, (void)--i7;
(void)i1--, (void)i3--, (void)i5--, (void)i7--;
(void)(i1 + 1), (void)(i3 + 1), (void)(i5 + 1), (void)(i7 + 1);
(void)(i1 - 1), (void)(i3 - 1), (void)(i5 - 1), (void)(i7 - 1);
(void)(i1 - i1), (void)(i3 - i3), (void)(i5 - i5), (void)(i7 - i7);
i1 = i1, i3 = i3, i5 = i5, i7 = i7;
auto i2 = i1;
auto i4 = i3;
auto i6 = i5;
auto i8 = i7;
i2[0], i4[0], i6[0], i8[0];
i2 == i2, i4 == i4, i6 == i6, i8 == i8;
i2 < i2, i4 < i4, i6 < i6, i8 < i8;
(void)allocInstance;
}
void DimensionTest()
{
vec_type<int> v;
v.size();
v.max_size();
v.resize(32);
v.resize(64, 42);
v.capacity();
v.empty();
v.reserve(1024);
v.shrink_to_fit();
}
void AccessorTest()
{
vec_type<int> v(32, 42);
const vec_type<int>& vr = v;
v[0], vr[0], v.at(0), vr.at(0);
v.front(), vr.front(), v.back(), vr.back();
v.data(), vr.data();
}
void AddRemoveTest()
{
vec_type<int> v1;
int a = 24;
v1.emplace_back(42);
v1.push_back(a);
v1.push_back(42);
v1.pop_back();
v1.emplace(v1.begin(), 11);
v1.insert(v1.end() - 1, a);
v1.insert(v1.end() - 1, 33);
v1.insert(v1.end(), 16, 24);
int vs[] = {2, 4, 6, 8, 10};
v1.insert(v1.end(), vs, vs + std::extent<decltype(vs)>());
v1.erase(v1.begin() + v1.size() / 2);
v1.erase(v1.begin(), v1.begin() + v1.size() / 3);
vec_type<int> v2;
v2.swap(v1);
v2.clear();
}
void RelationalTest()
{
vec_type<int> v1{ 3, 5, 6, 6, 9, 23, 11 };
vec_type<int> v2{ 3, 5, 6, 6, 9, 23, 15 };
v1 == v1;
v1 == v2;
v1 != v2;
v1 < v2;
v1 > v2;
v1 <= v1;
v2 >= v2;
}
template<typename T, typename A, int N>
void PrintMyVec(const custom_std::vector<T, A>& v, const char(&name)[N])
{
using std::cout;
using std::endl;
cout << name << '(' << v.size() << ", " << v.capacity() << ')' << " {";
for (const auto& x : v)
{
cout << x << ", ";
}
cout << "}" << endl;
}
<commit_msg>Added coverage tests for vector<bool>. Updated the printing helper to take a callable for formatting the output (boolean output specifically).<commit_after>#include <iostream>
#include "MyMallocator.hpp"
#include <type_traits>
#include "vector.hpp"
void ConstructorTest();
void AssignmentTest();
void IteratorTest();
void DimensionTest();
void AccessorTest();
void AddRemoveTest();
void RelationalTest();
template<typename T, typename A, typename F, int N>
void PrintMyVec(const custom_std::vector<T, A>&, const char(&)[N], F);
template<typename T>
using allocator_type = MyMallocator<T>;
template<typename T>
using vec_type = custom_std::vector < T, allocator_type<T> >;
template class custom_std::vector < int, allocator_type<int> >;
template class custom_std::vector < bool, allocator_type<bool> >;
int main()
{
std::cout.sync_with_stdio(false);
ConstructorTest();
AssignmentTest();
IteratorTest();
DimensionTest();
AccessorTest();
AddRemoveTest();
RelationalTest();
std::cin.get();
}
void ConstructorTest()
{
{
allocator_type<int> alloc;
vec_type<int> v1;
vec_type<int> v2(alloc);
vec_type<int> v3(10);
vec_type<int> v4(10, 11);
vec_type<int> v5(v3.begin(), v3.end());
vec_type<int> v6(v4);
vec_type<int> v7(std::move(v5));
vec_type<int> v8(v4, alloc);
vec_type<int> v9(std::move(v3), alloc);
vec_type<int> v10{ 11, 22, 33, 44, 55, 66 };
(void)v1, (void)v2, (void)v6, (void)v7,
(void)v8, (void)v9, (void)v10;
}
{
allocator_type<bool> alloc;
vec_type<bool> v1;
vec_type<bool> v2(alloc);
vec_type<bool> v3(10);
vec_type<bool> v4(10, false);
vec_type<bool> v5(v3.begin(), v3.end());
vec_type<bool> v6(v4);
vec_type<bool> v7(std::move(v5));
vec_type<bool> v8(v4, alloc);
vec_type<bool> v9(std::move(v3), alloc);
vec_type<bool> v10{ true, false, false, true, true };
(void)v1, (void)v2, (void)v6, (void)v7,
(void)v8, (void)v9, (void)v10;
}
}
void AssignmentTest()
{
{
vec_type<int> v1;
vec_type<int> v2;
vec_type<int> v3;
v1 = v2;
v2 = std::move(v3);
v3 = { 1, 2, 4, 8, 16, 32, 64, 128, 256 };
v1.assign(v3.begin(), v3.end());
v2.assign(16, 42);
v3.assign({ 1992304, 5707245, 234985, 2626, 666 });
}
{
vec_type<bool> v1;
vec_type<bool> v2;
vec_type<bool> v3;
v1 = v2;
v2 = std::move(v3);
v3 = { false, true, true, true, true, false, false, true };
v1.assign(v3.begin(), v3.end());
v2.assign(16, true);
v3.assign({ false, false, true, true, true, false, true });
}
}
void IteratorTest()
{
{
struct X { int a; };
vec_type<X> v(1);
auto allocInstance = v.get_allocator();
auto i1 = v.begin();
(void)v.end();
auto i3 = v.rbegin();
(void)v.rend();
auto i5 = v.cbegin();
(void)v.cend();
auto i7 = v.crbegin();
(void)v.crend();
(void)*i1, (void)*i3, (void)*i5, (void)*i7;
(void)i1->a, (void)i3->a, (void)i5->a, (void)i7->a;
(void)++i1, (void)++i3, (void)++i5, (void)++i7;
(void)i1++, (void)i3++, (void)i5++, (void)i7++;
(void)--i1, (void)--i3, (void)--i5, (void)--i7;
(void)i1--, (void)i3--, (void)i5--, (void)i7--;
(void)(i1 + 1), (void)(i3 + 1), (void)(i5 + 1), (void)(i7 + 1);
(void)(i1 - 1), (void)(i3 - 1), (void)(i5 - 1), (void)(i7 - 1);
(void)(i1 - i1), (void)(i3 - i3), (void)(i5 - i5), (void)(i7 - i7);
i1 = i1, i3 = i3, i5 = i5, i7 = i7;
auto i2 = i1;
auto i4 = i3;
auto i6 = i5;
auto i8 = i7;
i2[0], i4[0], i6[0], i8[0];
i2 == i2, i4 == i4, i6 == i6, i8 == i8;
i2 < i2, i4 < i4, i6 < i6, i8 < i8;
(void)allocInstance;
}
{
vec_type<bool> v(1);
auto allocInstance = v.get_allocator();
auto i1 = v.begin();
(void)v.end();
auto i3 = v.rbegin();
(void)v.rend();
auto i5 = v.cbegin();
(void)v.cend();
auto i7 = v.crbegin();
(void)v.crend();
(void)*i1, (void)*i3, (void)*i5, (void)*i7;
(void)++i1, (void)++i3, (void)++i5, (void)++i7;
(void)i1++, (void)i3++, (void)i5++, (void)i7++;
(void)--i1, (void)--i3, (void)--i5, (void)--i7;
(void)i1--, (void)i3--, (void)i5--, (void)i7--;
(void)(i1 + 1), (void)(i3 + 1), (void)(i5 + 1), (void)(i7 + 1);
(void)(i1 - 1), (void)(i3 - 1), (void)(i5 - 1), (void)(i7 - 1);
(void)(i1 - i1), (void)(i3 - i3), (void)(i5 - i5), (void)(i7 - i7);
i1 = i1, i3 = i3, i5 = i5, i7 = i7;
auto i2 = i1;
auto i4 = i3;
auto i6 = i5;
auto i8 = i7;
i2[0], i4[0], i6[0], i8[0];
i2 == i2, i4 == i4, i6 == i6, i8 == i8;
i2 < i2, i4 < i4, i6 < i6, i8 < i8;
(void)allocInstance;
}
}
void DimensionTest()
{
{
vec_type<int> v;
v.size();
v.max_size();
v.resize(32);
v.resize(64, 42);
v.capacity();
v.empty();
v.reserve(1024);
v.shrink_to_fit();
}
{
vec_type<bool> v;
v.size();
v.max_size();
v.resize(32);
v.resize(64, true);
v.capacity();
v.empty();
v.reserve(1024);
v.shrink_to_fit();
}
}
void AccessorTest()
{
{
vec_type<int> v(32, 42);
const vec_type<int>& vr = v;
v[0], vr[0], v.at(0), vr.at(0);
v.front(), vr.front(), v.back(), vr.back();
v.data(), vr.data();
}
{
vec_type<bool> v(32, true);
const vec_type<bool>& vr = v;
v[0], vr[0], v.at(0), vr.at(0);
v.front(), vr.front(), v.back(), vr.back();
v.flip();
}
}
void AddRemoveTest()
{
{
vec_type<int> v1;
int a = 24;
v1.emplace_back(42);
v1.push_back(a);
v1.push_back(42);
v1.pop_back();
v1.emplace(v1.begin(), 11);
v1.insert(v1.end() - 1, a);
v1.insert(v1.end() - 1, 33);
v1.insert(v1.end(), 16, 24);
int vs[] = { 2, 4, 6, 8, 10 };
v1.insert(v1.end(), vs, vs + std::extent<decltype(vs)>());
v1.erase(v1.begin() + v1.size() / 2);
v1.erase(v1.begin(), v1.begin() + v1.size() / 3);
vec_type<int> v2;
v2.swap(v1);
v2.clear();
}
{
vec_type<bool> v1;
bool a = true;
v1.push_back(a);
v1.push_back(false);
v1.pop_back();
v1.insert(v1.end() - 1, a);
v1.insert(v1.end() - 1, false);
v1.insert(v1.end(), 16, true);
bool vs[] = { false, false, false, false, true };
v1.insert(v1.end(), vs, vs + std::extent<decltype(vs)>());
vec_type<bool>::swap(v1[0], v1[3]);
v1.erase(v1.begin() + v1.size() / 2);
v1.erase(v1.begin(), v1.begin() + v1.size() / 3);
vec_type<bool> v2;
v2.swap(v1);
v2.clear();
}
}
void RelationalTest()
{
{
vec_type<int> v1{ 3, 5, 6, 6, 9, 23, 11 };
vec_type<int> v2{ 3, 5, 6, 6, 9, 23, 15 };
v1 == v1;
v1 == v2;
v1 != v2;
v1 < v2;
v1 > v2;
v1 <= v1;
v2 >= v2;
}
{
vec_type<bool> v1{ false, false, false, true, true, true, true };
vec_type<bool> v2{ false, false, false, true, false, true, true };
v1 == v1;
v1 == v2;
v1 != v2;
v1 < v2;
v1 > v2;
v1 <= v1;
v2 >= v2;
}
}
template<typename T, typename A, typename F, int N>
//requires F is callable and return type can be put to std::cout
void PrintMyVec(const custom_std::vector<T, A>& v, const char(&name)[N], F fmt)
{
using std::cout;
using std::endl;
cout << name << '(' << v.size() << ", " << v.capacity() << ')' << " {";
for (const auto& x : v)
{
cout << fmt() << x << ", ";
}
cout << "}" << endl;
}
<|endoftext|> |
<commit_before>/* Copyright 2014 Dietrich Epp.
This file is part of Legend of Feleria. Legend of Feleria is
licensed under the terms of the 2-clause BSD license. For more
information, see LICENSE.txt. */
#include "sg/entry.h"
#include "sg/event.h"
#include "sg/keycode.h"
#include "sg/mixer.h"
#include "sg/record.h"
#include "game/game.hpp"
#include "graphics/system.hpp"
#include "sg/cvar.h"
using Base::Log;
namespace {
struct sg_cvar_string cv_level;
Game::Game *game;
Graphics::System *graphics;
}
void sg_game_init(void) {
sg_mixer_start();
sg_cvar_defstring(nullptr, "level", "Initial level.",
&cv_level, "ch1", 0);
game = new Game::Game;
if (!game->load()) {
Log::abort("Could not load game data.");
}
if (!game->start_level(cv_level.value)) {
Log::abort("Could not load level.");
}
}
void sg_game_destroy(void) {}
void sg_game_getinfo(struct sg_game_info *info) {
info->name = "Legend of Feleria";
}
void sg_game_event(union sg_event *evt) {
switch (evt->common.type) {
case SG_EVENT_VIDEO_INIT:
if (graphics) {
delete graphics;
graphics = nullptr;
}
graphics = new Graphics::System;
if (!graphics->load(*game)) {
Log::abort("Could not load graphics data.");
}
break;
case SG_EVENT_KDOWN:
switch (evt->key.key) {
case KEY_Backslash:
sg_record_screenshot();
return;
case KEY_F10:
sg_record_start(evt->common.time);
return;
case KEY_F11:
sg_record_stop();
return;
}
break;
default:
break;
}
game->handle_event(*evt);
}
void sg_game_draw(int width, int height, double time) {
sg_mixer_settime(time);
game->update(time);
sg_mixer_commit();
graphics->draw(width, height, *game);
}
<commit_msg>Change default resolution to 1080p<commit_after>/* Copyright 2014 Dietrich Epp.
This file is part of Legend of Feleria. Legend of Feleria is
licensed under the terms of the 2-clause BSD license. For more
information, see LICENSE.txt. */
#include "sg/entry.h"
#include "sg/event.h"
#include "sg/keycode.h"
#include "sg/mixer.h"
#include "sg/record.h"
#include "game/game.hpp"
#include "graphics/system.hpp"
#include "sg/cvar.h"
using Base::Log;
namespace {
struct sg_cvar_string cv_level;
Game::Game *game;
Graphics::System *graphics;
}
void sg_game_init(void) {
sg_mixer_start();
sg_cvar_defstring(nullptr, "level", "Initial level.",
&cv_level, "ch1", 0);
game = new Game::Game;
if (!game->load()) {
Log::abort("Could not load game data.");
}
if (!game->start_level(cv_level.value)) {
Log::abort("Could not load level.");
}
}
void sg_game_destroy(void) {}
void sg_game_getinfo(struct sg_game_info *info) {
info->name = "Legend of Feleria";
info->default_width = 1920;
info->default_height = 1080;
}
void sg_game_event(union sg_event *evt) {
switch (evt->common.type) {
case SG_EVENT_VIDEO_INIT:
if (graphics) {
delete graphics;
graphics = nullptr;
}
graphics = new Graphics::System;
if (!graphics->load(*game)) {
Log::abort("Could not load graphics data.");
}
break;
case SG_EVENT_KDOWN:
switch (evt->key.key) {
case KEY_Backslash:
sg_record_screenshot();
return;
case KEY_F10:
sg_record_start(evt->common.time);
return;
case KEY_F11:
sg_record_stop();
return;
}
break;
default:
break;
}
game->handle_event(*evt);
}
void sg_game_draw(int width, int height, double time) {
sg_mixer_settime(time);
game->update(time);
sg_mixer_commit();
graphics->draw(width, height, *game);
}
<|endoftext|> |
<commit_before>#include <sys/wait.h>
#include "process.h"
int main(int argc, char *argv[]) {
EventLoop loop;
CHECK_UNIX(Fork(loop, []() {
Sandbox("/tmp", {
{"/bin", "/bin"},
{"/lib", "/lib"},
{"/lib64", "/lib64"},
{"/usr", "/usr"},
});
CHECK_UNIX(Fork([]() {
CHECK(getpid() == 1);
ChildContext context;
context.input_behavior.emplace(STDIN_FILENO, INHERIT_STREAM);
context.output_behavior.emplace(STDOUT_FILENO, INHERIT_STREAM);
context.output_behavior.emplace(STDERR_FILENO, INHERIT_STREAM);
LaunchChild("/bin/bash", {"bunny"}, context).wait();
}));
wait(NULL);
}));
wait(NULL);
loop.run();
}
<commit_msg>grumb<commit_after>#include <sys/wait.h>
#include "process.h"
int main(int argc, char *argv[]) {
EventLoop loop;
CHECK_UNIX(Fork(loop, []() {
Sandbox("/tmp", {
{"/bin", "/bin"},
{"/lib", "/lib"},
{"/lib64", "/lib64"},
{"/usr", "/usr"},
});
ChildContext context;
context.input_behavior.emplace(STDIN_FILENO, INHERIT_STREAM);
context.output_behavior.emplace(STDOUT_FILENO, INHERIT_STREAM);
context.output_behavior.emplace(STDERR_FILENO, INHERIT_STREAM);
LaunchChild("/bin/bash", {"bunny"}, context).wait();
}));
wait(NULL);
loop.run();
}
<|endoftext|> |
<commit_before>//
// main.cpp
// Spin Wave Fit
//
// Created by Hahn, Steven E. on 1/7/13.
// Copyright (c) 2013 Oak Ridge National Laboratory. All rights reserved.
//
#define _USE_MATH_DEFINES
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <Eigen/Dense>
#include "SpinWavePlot.h"
#include "Initializer.h"
#include <boost/thread.hpp>
#include <boost/atomic.hpp>
#include <boost/program_options.hpp>
#include <boost/progress.hpp>
using namespace boost;
namespace po = boost::program_options;
using namespace std;
using namespace Eigen;
class ThreadClass {
public:
boost::atomic<int> npoints,nproc,points;
boost::atomic<double> min,max;
boost::atomic<int> pointsDone,nextPoint;
MatrixXd figure;
boost::mutex io_mutex; // The iostreams are not guaranteed to be thread-safe!
ThreadClass(int n) // Constructor
{
#if EIGEN_WORLD_VERSION >= 3 && EIGEN_MAJOR_VERSION >= 1
Eigen::initParallel();
#endif
nproc.store(n);
npoints.store(26);
pointsDone.store(0);
nextPoint.store(0);
points.store(21);
figure.setZero(points.load(),npoints.load());
min.store(0.0);
max.store(80.0);
}
~ThreadClass()
{
}
// Destructor
void Run(int i, Init& four_sl)
{
boost::unique_lock<boost::mutex> scoped_lock(io_mutex);
SW_Builder builder = four_sl.get_builder();
scoped_lock.unlock();
double x0,y0,z0,x1,y1,z1;
x0=2.0;x1=2.0;
y0=-1.5;y1=1.5;
z0=-3.0;z1=-3.0;
TwoDimGaussian resinfo;
resinfo.a = 1109.0;
resinfo.b = 0.0;
resinfo.c = 0.48;
resinfo.tol = 1.0e-2;
resinfo.direction = 1;
resinfo.SW = builder.Create_Element();
axes_info axesinfo;
axesinfo.x = true;
axesinfo.y = true;
axesinfo.z = true;
axesinfo.dx = 0.2;
axesinfo.dy = 0.05;
axesinfo.dz = 0.2;
axesinfo.tol = 1.0e-2;
/*double x0,y0,z0,x1,y1,z1;
x0=3.0;x1=3.0;
y0=0.0;y1=0.0;
z0=-4.0;z1=4.0;
TwoDimGaussian resinfo;
resinfo.a = 579.7;
resinfo.b = -20.0;
resinfo.c = 1.3;
resinfo.tol = 1.0e-1;
resinfo.direction = 2;
resinfo.builder = builder;
axes_info axesinfo;
axesinfo.x = true;
axesinfo.y = true;
axesinfo.z = true;
axesinfo.dx = 0.2;
axesinfo.dy = 0.2;
axesinfo.dz = 0.05;
axesinfo.tol = 1.0e-1;
*/
double tmin = min.load();
double tmax = max.load();
int tpoints = points.load();
int tnpoints = npoints.load();
TwoDimensionResolutionFunction res(resinfo, tmin,tmax, tpoints);
IntegrateAxes tmp(axesinfo,res,tmin,tmax,tpoints);
//for(int m=i;m<tnpoints;m=m+tnproc)
while (true)
{
int m = nextPoint.load();
if (m >= tnpoints)
{
break;
}
//cout << m << endl;
nextPoint.fetch_add(1);
double x = x0 + (x1-x0)*m/(tnpoints-1);
double y = y0 + (y1-y0)*m/(tnpoints-1);
double z = z0 + (z1-z0)*m/(tnpoints-1);
//cout << "Pos." << endl;
//scoped_lock.lock();
//cout << "**** " << x << " " << y << " " << z << endl;
//scoped_lock.unlock();
vector<double> val = tmp.getCut(x,y,z);
for(int n=0;n<tpoints;n++)
{
figure(n,m) = val[n];
}
pointsDone.fetch_add(1);
}
}
};
int main(int argc, char * argv[])
{
string filename;
int n_threads;
try {
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("input", po::value<string>(), "set input filename")
("threads", po::value<int>(), "set number of threads")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
if (vm.count("input")) {
cout << "input filename was set to "
<< vm["input"].as<string>() << ".\n";
filename = vm["input"].as<string>();
} else {
cout << "input filename was not set.\n";
return 1;
}
if (vm.count("threads")) {
cout << "Using "
<< vm["threads"].as<int>() << " processors.\n";
n_threads = vm["threads"].as<int>();
} else {
cout << "number of threads was not set. Using 1 processor.\n";
n_threads = 1;
}
}
catch(std::exception& e) {
cerr << "error: " << e.what() << "\n";
return 1;
}
catch(...) {
cerr << "Exception of unknown type!\n";
}
Init four_sl(filename);
boost::thread_group g;
ThreadClass tc(n_threads);
for (int i=0;i<n_threads;i++)
{
boost::thread *t = new boost::thread(&ThreadClass::Run, &tc, i, four_sl);
g.add_thread(t);
}
boost::unique_lock<boost::mutex> scoped_lock(tc.io_mutex);
scoped_lock.unlock();
double npoints = tc.npoints;
boost::progress_display show_progress(npoints);
int pointsDone = 0;
while(pointsDone < npoints)
{
sleep(1);
int diff = tc.pointsDone.load() - pointsDone;
if (diff > 0)
{
scoped_lock.lock();
show_progress += diff;
scoped_lock.unlock();
pointsDone = tc.pointsDone.load();
}
//cout << pointsDone << endl;
}
g.join_all();
std::ofstream file("test.txt");
if (file.is_open())
{
file << tc.figure << '\n';
}
return 0;
}
<commit_msg>Revert "switched mutex to atomic operations"<commit_after>//
// main.cpp
// Spin Wave Fit
//
// Created by Hahn, Steven E. on 1/7/13.
// Copyright (c) 2013 Oak Ridge National Laboratory. All rights reserved.
//
#define _USE_MATH_DEFINES
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <Eigen/Dense>
#include "SpinWavePlot.h"
#include "Initializer.h"
#include <boost/thread.hpp>
#include <boost/program_options.hpp>
#include <boost/progress.hpp>
using namespace boost;
namespace po = boost::program_options;
using namespace std;
using namespace Eigen;
class ThreadClass {
public:
int npoints,nproc,points;
double min,max;
int pointsDone,nextPoint;
MatrixXd figure;
boost::mutex io_mutex,np_mutex; // The iostreams are not guaranteed to be thread-safe!
ThreadClass(int n) // Constructor
{
#if EIGEN_WORLD_VERSION >= 3 && EIGEN_MAJOR_VERSION >= 1
Eigen::initParallel();
#endif
nproc = n;
npoints = 101;
pointsDone = 0;
nextPoint = 0;
points = 81;
figure.setZero(points,npoints);
min = 0.0;
max = 80.0;
}
~ThreadClass()
{
}
// Destructor
void Run(int i, Init& four_sl)
{
boost::unique_lock<boost::mutex> scoped_lock(io_mutex);
SW_Builder builder = four_sl.get_builder();
scoped_lock.unlock();
boost::unique_lock<boost::mutex> np_lock(np_mutex);
np_lock.unlock();
double x0,y0,z0,x1,y1,z1;
x0=2.0;x1=2.0;
y0=-1.5;y1=1.5;
z0=-3.0;z1=-3.0;
TwoDimGaussian resinfo;
resinfo.a = 1109.0;
resinfo.b = 0.0;
resinfo.c = 0.48;
resinfo.tol = 1.0e-2;
resinfo.direction = 1;
resinfo.SW = builder.Create_Element();
axes_info axesinfo;
axesinfo.x = true;
axesinfo.y = true;
axesinfo.z = true;
axesinfo.dx = 0.2;
axesinfo.dy = 0.05;
axesinfo.dz = 0.2;
axesinfo.tol = 1.0e-2;
/*double x0,y0,z0,x1,y1,z1;
x0=3.0;x1=3.0;
y0=0.0;y1=0.0;
z0=-4.0;z1=4.0;
TwoDimGaussian resinfo;
resinfo.a = 579.7;
resinfo.b = -20.0;
resinfo.c = 1.3;
resinfo.tol = 1.0e-1;
resinfo.direction = 2;
resinfo.builder = builder;
axes_info axesinfo;
axesinfo.x = true;
axesinfo.y = true;
axesinfo.z = true;
axesinfo.dx = 0.2;
axesinfo.dy = 0.2;
axesinfo.dz = 0.05;
axesinfo.tol = 1.0e-1;
*/
scoped_lock.lock();
double tmin = min;
double tmax = max;
int tpoints = points;
int tnpoints = npoints;
scoped_lock.unlock();
TwoDimensionResolutionFunction res(resinfo, tmin,tmax, tpoints);
IntegrateAxes tmp(axesinfo,res,tmin,tmax,tpoints);
//for(int m=i;m<tnpoints;m=m+tnproc)
while (true)
{
np_lock.lock();
int m = nextPoint;
if (m >= npoints)
{
break;
}
nextPoint++;
//cout << m << endl;
np_lock.unlock();
double x = x0 + (x1-x0)*m/(tnpoints-1);
double y = y0 + (y1-y0)*m/(tnpoints-1);
double z = z0 + (z1-z0)*m/(tnpoints-1);
//cout << "Pos." << endl;
//scoped_lock.lock();
//cout << "**** " << x << " " << y << " " << z << endl;
//scoped_lock.unlock();
vector<double> val = tmp.getCut(x,y,z);
for(int n=0;n<tpoints;n++)
{
figure(n,m) = val[n];
}
scoped_lock.lock();
pointsDone++;
scoped_lock.unlock();
}
}
};
int main(int argc, char * argv[])
{
string filename;
int n_threads;
try {
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("input", po::value<string>(), "set input filename")
("threads", po::value<int>(), "set number of threads")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
if (vm.count("input")) {
cout << "input filename was set to "
<< vm["input"].as<string>() << ".\n";
filename = vm["input"].as<string>();
} else {
cout << "input filename was not set.\n";
return 1;
}
if (vm.count("threads")) {
cout << "Using "
<< vm["threads"].as<int>() << " processors.\n";
n_threads = vm["threads"].as<int>();
} else {
cout << "number of threads was not set. Using 1 processor.\n";
n_threads = 1;
}
}
catch(std::exception& e) {
cerr << "error: " << e.what() << "\n";
return 1;
}
catch(...) {
cerr << "Exception of unknown type!\n";
}
Init four_sl(filename);
boost::thread_group g;
ThreadClass tc(n_threads);
for (int i=0;i<n_threads;i++)
{
boost::thread *t = new boost::thread(&ThreadClass::Run, &tc, i, four_sl);
g.add_thread(t);
}
boost::unique_lock<boost::mutex> scoped_lock(tc.io_mutex);
double npoints = tc.npoints;
scoped_lock.unlock();
boost::progress_display show_progress(npoints);
int pointsDone = 0;
while(pointsDone < npoints)
{
sleep(1);
scoped_lock.lock();
int diff = tc.pointsDone - pointsDone;
pointsDone = tc.pointsDone;
//cout << pointsDone << endl;
scoped_lock.unlock();
show_progress += diff;
}
g.join_all();
std::ofstream file("test.txt");
if (file.is_open())
{
file << tc.figure << '\n';
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
/*
// Deprecated function call.
int sizefunc(char* commandstream, const char* delim){
int i;
char* p = strtok(commandstream, delim);
for (i = 0; p!= NULL; p = strtok(NULL, delim) ){
++i;
}
return (i+1);
}
*/
bool checkforexit(char ** &commandList, char* commands, const char* pk){
int c = 0;
bool exiting = false;
char* par = strtok(commands, pk);
for (c = 0; par != NULL; ++c, par = strtok(NULL, pk)){
commandList[c] = par;
}
return exiting;
//cout << "CommandList@" << it << ": " << commandList[it] << endl; }
}
char ** changeToArray(char ** commandList, char* commands, const char* parser){
int it = 0;
char* pkey = strtok(commands, parser);
for (it = 0; pkey != NULL; ++it, pkey = strtok(NULL, parser)){
commandList[it] = pkey;
//cout << "CommandList@" << it << ": " << commandList[it] << endl;
}
//cout << "it is @ " << it << endl;
commandList[it] = NULL;
return commandList;
}
int main()
{
string user_stream;
char * parsedString = NULL;
char * username = getlogin();
const char * parr = " ";
//const char * andL = "&&";
//const char * orL = "||";
//const char * semiL = ";";
char host[100];
gethostname(host, 100);
//Introductory Message to make sure shell is running.
cout << "Hello, and welcome to Kevin's shell." << endl;
while(1){
// Prints out the username and hostname if it exists.
if (username){
cout << username << "@" << host;
}
cout << "$ ";
//Gets line for user stream.
getline(cin, user_stream);
if (user_stream == "exit"){
cout << "Thank you for using the program.\n";
exit(1);
}
int hashpos = user_stream.find('#');
if (hashpos != -1){
user_stream.erase(hashpos);
}
//Parsing the string using strdup to change from const char* to char*
parsedString = strdup(user_stream.c_str());
char ** command = new char *[sizeof(parsedString)+1];
command = changeToArray(command, parsedString, parr);
int pid = fork();
if (pid == -1){
perror("Fork failed");
}
else if (pid == 0){
if(execvp( (const char*) command [0] , (char* const*) command) == -1){
perror("Unable to perform request.");
}
}
else{
wait(NULL);
/*
if (checkforexit(commandstream, parsedString, parr)){
cout << "Thank you for using rshell. Goodbye.\n";
exit(1);
}
*/
}
}
return 0;
}
<commit_msg>wtf am i doing<commit_after>#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
/*
// Deprecated function call.
int sizefunc(char* commandstream, const char* delim){
int i;
char* p = strtok(commandstream, delim);
for (i = 0; p!= NULL; p = strtok(NULL, delim) ){
++i;
}
return (i+1);
}
*/
// NEED TO CHECK MY MAC AND SEE IF THE CODE IS ON THERE.
// OTHERWISE I MIGHT BE SCREWED.
bool checkforexit(char ** &commandList, char* commands, const char* pk){
int c = 0;
bool exiting = false;
char* par = strtok(commands, pk);
for (c = 0; par != NULL; ++c, par = strtok(NULL, pk)){
commandList[c] = par;
}
return exiting;
//cout << "CommandList@" << it << ": " << commandList[it] << endl; }
}
char ** changeToArray(char ** commandList, char* commands, const char* parser){
int it = 0;
char* pkey = strtok(commands, parser);
for (it = 0; pkey != NULL; ++it, pkey = strtok(NULL, parser)){
commandList[it] = pkey;
//cout << "CommandList@" << it << ": " << commandList[it] << endl;
}
//cout << "it is @ " << it << endl;
commandList[it] = NULL;
return commandList;
}
int main()
{
string user_stream;
char * parsedString = NULL;
char * username = getlogin();
const char * parr = " ";
//const char * andL = "&&";
//const char * orL = "||";
//const char * semiL = ";";
char host[100];
gethostname(host, 100);
//Introductory Message to make sure shell is running.
cout << "Hello, and welcome to Kevin's shell." << endl;
while(1){
// Prints out the username and hostname if it exists.
if (username){
cout << username << "@" << host;
}
cout << "$ ";
//Gets line for user stream.
getline(cin, user_stream);
if (user_stream == "exit"){
cout << "Thank you for using the program.\n";
exit(1);
}
int hashpos = user_stream.find('#');
if (hashpos != -1){
user_stream.erase(hashpos);
}
//Parsing the string using strdup to change from const char* to char*
parsedString = strdup(user_stream.c_str());
char ** command = new char *[sizeof(parsedString)+1];
command = changeToArray(command, parsedString, parr);
int pid = fork();
if (pid == -1){
perror("Fork failed");
}
else if (pid == 0){
if(execvp( (const char*) command [0] , (char* const*) command) == -1){
perror("Unable to perform request.");
}
}
else{
wait(NULL);
/*
if (checkforexit(commandstream, parsedString, parr)){
cout << "Thank you for using rshell. Goodbye.\n";
exit(1);
}
*/
}
}
return 0;
}
<|endoftext|> |
<commit_before>// See LICENSE for details.
#include <math.h>
#include <stdlib.h>
#include <GL/freeglut.h>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
#include <windows.h>
#endif // to make it work on Windows, too
#include <iostream>
#include "Camera.h"
#include "RoadRollerGame.h"
int g_clientWidth, g_lastClientWidth = 800;
int g_clientHeight, g_lastClientHeight = 480;
int g_clientPositionX = 100;
int g_clientPositionY = 100;
bool g_windowed = true;
bool g_keystates[256];
int g_lastMouseX = 0;
int g_lastMouseY = 0;
float g_pitch = 0.0f;
float g_yaw = 0.0f;
bool g_pointerWarped = true;
float g_time = 0.0f;
float g_timeElapsed = 0.0f;
float g_deltaT = 0.1f;
Camera* currentCam = nullptr;
Camera roamingCam;
RoadRollerGame game;
void handleMouseInput(float deltaX, float deltaY)
{
g_yaw += deltaX;
g_pitch += deltaY;
if (g_pitch > 74.9f) { g_pitch = 74.9f; }
if (g_pitch < -74.9f) { g_pitch = -74.9f; }
if (currentCam != nullptr) {
currentCam->rotate(g_yaw, g_pitch);
}
}
void handleKeyboardInput(bool keyStates[])
{
float cameraSpeed = 0.0001f;
if (keyStates['w']) {
roamingCam.move(roamingCam.frontDir * cameraSpeed);
}
if (keyStates['s'])
{
roamingCam.move(roamingCam.frontDir * -1.0f * cameraSpeed);
}
if (keyStates['a'])
{
roamingCam.move((roamingCam.frontDir % roamingCam.upDir).normalize() * -1.0f * cameraSpeed);
}
if (keyStates['d'])
{
roamingCam.move((roamingCam.frontDir % roamingCam.upDir).normalize() * cameraSpeed);
}
}
void simulateWorld(float timeStart, float timeEnd)
{
if (timeStart - g_timeElapsed >= 10000.0f)
{
g_timeElapsed = timeStart;
}
for (float tCurrent = timeStart; tCurrent < timeEnd; tCurrent += g_deltaT)
{
handleKeyboardInput(g_keystates);
float deltaT = ((g_deltaT < (timeEnd - tCurrent)) ? (g_deltaT) : (timeEnd - tCurrent));
game.update(deltaT, tCurrent - g_timeElapsed);
}
}
void onKeyboard(unsigned char key, int x, int y)
{
// for repeated presses
if (key == 'w' || key == 's' || key == 'a' || key == 'd')
{
g_keystates[key] = true;
}
// for one-time keypresses
switch (key)
{
case 'c':
game.startNextChicken();
break;
case 'f':
game.accelerateRoller();
break;
case 'n':
game.setStillRoller();
break;
case 'b':
game.deccelerateRoller();
break;
case '\x1b': // that's the 'Esc' key
glutLeaveMainLoop();
break;
default: break;
}
}
void onKeyUp(unsigned char key, int x, int y) {
if (key == 'w' || key == 's' || key == 'a' || key == 'd')
{
g_keystates[key] = false;
}
}
void onKeyboardSpecial(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_F1:
// switches to dashboard cam
currentCam = &(game.inCam);
break;
case GLUT_KEY_F2:
// switches to chase cam
currentCam = &(game.chaseCam);
break;
case GLUT_KEY_F3:
// switches to free cam
roamingCam.eyePos = currentCam->eyePos;
roamingCam.frontDir = currentCam->frontDir;
currentCam = &roamingCam;
break;
case GLUT_KEY_F4:
// toggles (the still windowed) fullscreen
if (g_windowed) {
g_clientPositionX = glutGet(GLUT_WINDOW_X);
g_clientPositionY = glutGet(GLUT_WINDOW_Y);
// hides the window's borders, puts it to (0,0), sets its size to match the current desktop resolution
glutFullScreen();
g_windowed = false;
}
else
{
glutPositionWindow(g_clientPositionX, g_clientPositionY);
glutReshapeWindow(g_lastClientWidth, g_lastClientHeight);
g_windowed = true;
}
break;
default: break;
}
currentCam->viewportWidth = g_clientWidth;
currentCam->viewportHeight = g_clientHeight;
currentCam->setProjectionMatrix();
glutPostRedisplay();
}
void onMouseMotion(int x, int y)
{
if (!g_pointerWarped) {
float mouseSensitivity = 0.233f;
float deltaX = (x - g_lastMouseX) * mouseSensitivity;
float deltaY = (g_lastMouseY - y) * mouseSensitivity;
handleMouseInput(deltaX, deltaY);
g_pointerWarped = true;
glutWarpPointer(100, 100);
g_lastMouseX = 100; // x;
g_lastMouseY = 100; // y;
glutPostRedisplay();
}
else
{
// to prevent infinite callbacks caused by previous glutWarpPointer(...) call
g_pointerWarped = false;
}
}
void onReshape(int newWidth, int newHeight)
{
g_lastClientWidth = g_clientWidth;
g_lastClientHeight = g_clientHeight;
g_clientWidth = newWidth;
g_clientHeight = newHeight;
if (currentCam != nullptr) {
currentCam->setViewport(0, 0, newWidth, newHeight);
}
}
void onInitialization()
{
glutWarpPointer(100, 100);
glutSetCursor(GLUT_CURSOR_NONE);
glutIgnoreKeyRepeat(true);
// sets GL_MODELVIEW and GL_PROJECTION matrices to identity matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glShadeModel(GL_SMOOTH);
printf("Game initialization\n");
roamingCam.viewportWidth = g_clientWidth;
roamingCam.viewportHeight = g_clientHeight;
roamingCam.setProjectionMatrix();
roamingCam.setModelViewMatrix();
currentCam = &roamingCam;
game.build();
currentCam = &game.chaseCam;
printf("Roadroller game initialized\n");
glutPostRedisplay();
}
void onIdle()
{
float oldTime = g_time;
g_time = glutGet(GLUT_ELAPSED_TIME);
simulateWorld(oldTime, g_time);
glutPostRedisplay();
}
void onDisplay()
{
glClearColor(0.0f, 0.604f, 0.804f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (currentCam != nullptr) {
currentCam->setProjectionMatrix();
currentCam->setModelViewMatrix();
}
glColor3f(1.0f, 1.0f, 1.0f);
glPushMatrix();
game.render();
glPopMatrix();
glutSwapBuffers();
}
void onExit()
{
currentCam = nullptr;
#if defined(_DEBUG) && (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
_CrtDumpMemoryLeaks();
#endif
printf("Shutting down...");
}
/**
* The entry point for the application.
* @param argc the number of arguments passed to the application
* @param argv array of strings containing the arguments that was passed to the application
* @return 0 after normal execution.
*/
int main(int argc, char **argv) {
printf("Roadrolla' application startup\n");
#if defined(_DEBUG) && (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
SetConsoleTitle(TEXT("Roadrolla' console"));
#endif
printf("Graphics initialization\n");
glutInit(&argc, argv);
glutInitWindowSize(g_clientWidth, g_clientHeight);
glutInitWindowPosition(g_clientPositionX, g_clientPositionY);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Roadrolla'");
atexit(onExit);
printf("GL Vendor: %s\n", glGetString(GL_VENDOR));
printf("GL Renderer: %s\n", glGetString(GL_RENDERER));
printf("GL Version: %s\n", glGetString(GL_VERSION));
printf("OpenGL initializated\n");
// performs initializing tasks
onInitialization();
// registers event handlers
glutDisplayFunc(onDisplay);
glutIdleFunc(onIdle);
glutKeyboardFunc(onKeyboard);
glutKeyboardUpFunc(onKeyUp);
glutSpecialFunc(onKeyboardSpecial);
glutPassiveMotionFunc(onMouseMotion);
glutReshapeFunc(onReshape);
printf("Roadrolla' application initializated, entering main loop ... \n");
glutMainLoop();
onExit();
#if defined(_DEBUG) && (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
_CrtDumpMemoryLeaks();
#endif
return 0;
}<commit_msg>Fixed Clang warnings on unsigned/char conversations<commit_after>// See LICENSE for details.
#include <math.h>
#include <stdlib.h>
#include <GL/freeglut.h>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
#include <windows.h>
#endif // to make it work on Windows, too
#include <iostream>
#include "Camera.h"
#include "RoadRollerGame.h"
int g_clientWidth, g_lastClientWidth = 800;
int g_clientHeight, g_lastClientHeight = 480;
int g_clientPositionX = 100;
int g_clientPositionY = 100;
bool g_windowed = true;
bool g_keystates[256];
int g_lastMouseX = 0;
int g_lastMouseY = 0;
float g_pitch = 0.0f;
float g_yaw = 0.0f;
bool g_pointerWarped = true;
float g_time = 0.0f;
float g_timeElapsed = 0.0f;
float g_deltaT = 0.1f;
Camera* currentCam = nullptr;
Camera roamingCam;
RoadRollerGame game;
void handleMouseInput(float deltaX, float deltaY)
{
g_yaw += deltaX;
g_pitch += deltaY;
if (g_pitch > 74.9f) { g_pitch = 74.9f; }
if (g_pitch < -74.9f) { g_pitch = -74.9f; }
if (currentCam != nullptr) {
currentCam->rotate(g_yaw, g_pitch);
}
}
void handleKeyboardInput(bool keyStates[])
{
float cameraSpeed = 0.0001f;
unsigned char w = 'w';
if (keyStates[w]) {
roamingCam.move(roamingCam.frontDir * cameraSpeed);
}
unsigned char s = 's';
if (keyStates[s])
{
roamingCam.move(roamingCam.frontDir * -1.0f * cameraSpeed);
}
unsigned char a = 'a';
if (keyStates[a])
{
roamingCam.move((roamingCam.frontDir % roamingCam.upDir).normalize() * -1.0f * cameraSpeed);
}
unsigned char d = 'd';
if (keyStates[d])
{
roamingCam.move((roamingCam.frontDir % roamingCam.upDir).normalize() * cameraSpeed);
}
}
void simulateWorld(float timeStart, float timeEnd)
{
if (timeStart - g_timeElapsed >= 10000.0f)
{
g_timeElapsed = timeStart;
}
for (float tCurrent = timeStart; tCurrent < timeEnd; tCurrent += g_deltaT)
{
handleKeyboardInput(g_keystates);
float deltaT = ((g_deltaT < (timeEnd - tCurrent)) ? (g_deltaT) : (timeEnd - tCurrent));
game.update(deltaT, tCurrent - g_timeElapsed);
}
}
void onKeyboard(unsigned char key, int x, int y)
{
// for repeated presses
if (key == 'w' || key == 's' || key == 'a' || key == 'd')
{
g_keystates[key] = true;
}
// for one-time keypresses
switch (key)
{
case 'c':
game.startNextChicken();
break;
case 'f':
game.accelerateRoller();
break;
case 'n':
game.setStillRoller();
break;
case 'b':
game.deccelerateRoller();
break;
case '\x1b': // that's the 'Esc' key
glutLeaveMainLoop();
break;
default: break;
}
}
void onKeyUp(unsigned char key, int x, int y) {
if (key == 'w' || key == 's' || key == 'a' || key == 'd')
{
g_keystates[key] = false;
}
}
void onKeyboardSpecial(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_F1:
// switches to dashboard cam
currentCam = &(game.inCam);
break;
case GLUT_KEY_F2:
// switches to chase cam
currentCam = &(game.chaseCam);
break;
case GLUT_KEY_F3:
// switches to free cam
roamingCam.eyePos = currentCam->eyePos;
roamingCam.frontDir = currentCam->frontDir;
currentCam = &roamingCam;
break;
case GLUT_KEY_F4:
// toggles (the still windowed) fullscreen
if (g_windowed) {
g_clientPositionX = glutGet(GLUT_WINDOW_X);
g_clientPositionY = glutGet(GLUT_WINDOW_Y);
// hides the window's borders, puts it to (0,0), sets its size to match the current desktop resolution
glutFullScreen();
g_windowed = false;
}
else
{
glutPositionWindow(g_clientPositionX, g_clientPositionY);
glutReshapeWindow(g_lastClientWidth, g_lastClientHeight);
g_windowed = true;
}
break;
default: break;
}
currentCam->viewportWidth = g_clientWidth;
currentCam->viewportHeight = g_clientHeight;
currentCam->setProjectionMatrix();
glutPostRedisplay();
}
void onMouseMotion(int x, int y)
{
if (!g_pointerWarped) {
float mouseSensitivity = 0.233f;
float deltaX = (x - g_lastMouseX) * mouseSensitivity;
float deltaY = (g_lastMouseY - y) * mouseSensitivity;
handleMouseInput(deltaX, deltaY);
g_pointerWarped = true;
glutWarpPointer(100, 100);
g_lastMouseX = 100; // x;
g_lastMouseY = 100; // y;
glutPostRedisplay();
}
else
{
// to prevent infinite callbacks caused by previous glutWarpPointer(...) call
g_pointerWarped = false;
}
}
void onReshape(int newWidth, int newHeight)
{
g_lastClientWidth = g_clientWidth;
g_lastClientHeight = g_clientHeight;
g_clientWidth = newWidth;
g_clientHeight = newHeight;
if (currentCam != nullptr) {
currentCam->setViewport(0, 0, newWidth, newHeight);
}
}
void onInitialization()
{
glutWarpPointer(100, 100);
glutSetCursor(GLUT_CURSOR_NONE);
glutIgnoreKeyRepeat(true);
// sets GL_MODELVIEW and GL_PROJECTION matrices to identity matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glShadeModel(GL_SMOOTH);
printf("Game initialization\n");
roamingCam.viewportWidth = g_clientWidth;
roamingCam.viewportHeight = g_clientHeight;
roamingCam.setProjectionMatrix();
roamingCam.setModelViewMatrix();
currentCam = &roamingCam;
game.build();
currentCam = &game.chaseCam;
printf("Roadroller game initialized\n");
glutPostRedisplay();
}
void onIdle()
{
float oldTime = g_time;
g_time = glutGet(GLUT_ELAPSED_TIME);
simulateWorld(oldTime, g_time);
glutPostRedisplay();
}
void onDisplay()
{
glClearColor(0.0f, 0.604f, 0.804f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (currentCam != nullptr) {
currentCam->setProjectionMatrix();
currentCam->setModelViewMatrix();
}
glColor3f(1.0f, 1.0f, 1.0f);
glPushMatrix();
game.render();
glPopMatrix();
glutSwapBuffers();
}
void onExit()
{
currentCam = nullptr;
#if defined(_DEBUG) && (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
_CrtDumpMemoryLeaks();
#endif
printf("Shutting down...");
}
/**
* The entry point for the application.
* @param argc the number of arguments passed to the application
* @param argv array of strings containing the arguments that was passed to the application
* @return 0 after normal execution.
*/
int main(int argc, char **argv) {
printf("Roadrolla' application startup\n");
#if defined(_DEBUG) && (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
SetConsoleTitle(TEXT("Roadrolla' console"));
#endif
printf("Graphics initialization\n");
glutInit(&argc, argv);
glutInitWindowSize(g_clientWidth, g_clientHeight);
glutInitWindowPosition(g_clientPositionX, g_clientPositionY);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Roadrolla'");
atexit(onExit);
printf("GL Vendor: %s\n", glGetString(GL_VENDOR));
printf("GL Renderer: %s\n", glGetString(GL_RENDERER));
printf("GL Version: %s\n", glGetString(GL_VERSION));
printf("OpenGL initializated\n");
// performs initializing tasks
onInitialization();
// registers event handlers
glutDisplayFunc(onDisplay);
glutIdleFunc(onIdle);
glutKeyboardFunc(onKeyboard);
glutKeyboardUpFunc(onKeyUp);
glutSpecialFunc(onKeyboardSpecial);
glutPassiveMotionFunc(onMouseMotion);
glutReshapeFunc(onReshape);
printf("Roadrolla' application initializated, entering main loop ... \n");
glutMainLoop();
onExit();
#if defined(_DEBUG) && (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
_CrtDumpMemoryLeaks();
#endif
return 0;
}<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright (C) 2011-2012 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* TeapotNet 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "main.h"
#include "map.h"
#include "sha512.h"
#include "store.h"
#include "tracker.h"
#include "http.h"
#include "config.h"
#include "core.h"
#include "user.h"
#include "directory.h"
using namespace tpot;
Mutex tpot::LogMutex;
int main(int argc, char** argv)
{
try {
Log("main", "Starting...");
srand(time(NULL));
const String configFileName = "config.txt";
Config::Load(configFileName);
Config::Default("tracker", "teapotnet.org");
Config::Default("port", "8480");
Config::Default("tracker_port", "8488");
Config::Default("interface_port", "8080");
Config::Default("profiles_dir", "profiles");
Config::Default("static_dir", "static");
Config::Save(configFileName);
StringMap args;
String last;
for(int i=1; i<argc; ++i)
{
String str(argv[i]);
if(str.empty()) continue;
if(str[0] == '-')
{
if(!last.empty()) args[last] = "";
if(str[0] == '-') str.ignore();
if(!str.empty() && str[0] == '-') str.ignore();
if(str.empty())
{
std::cerr<<"Invalid option: "<<argv[i]<<std::endl;
return 1;
}
last = str;
}
else {
if(last.empty()) args[str] = "";
else {
args[last] = str;
last.clear();
}
}
}
Tracker *tracker = NULL;
if(args.contains("tracker"))
{
if(args["tracker"].empty())
args["tracker"] = Config::Get("tracker_port");
int port;
args["tracker"] >> port;
tracker = new Tracker(port);
tracker->start();
}
// Starting interface
String sifport = Config::Get("interface_port");
if(args.contains("ifport")) sifport = args["ifport"];
int ifport;
sifport >> ifport;
Interface::Instance = new Interface(ifport);
Interface::Instance->start();
// Starting core
String sport = Config::Get("port");
if(args.contains("port")) sport = args["port"];
int port;
sport >> port;
Core::Instance = new Core(port);
Core::Instance->start();
if(!Directory::Exist(Config::Get("profiles_dir")))
Directory::Create(Config::Get("profiles_dir"));
Directory profilesDir(Config::Get("profiles_dir"));
while(profilesDir.nextFile())
{
if(profilesDir.fileIsDir())
{
String name = profilesDir.fileName();
User *user;
try {
user = new User(name);
}
catch(const std::exception &e)
{
Log("main", "ERROR: Unable to load user \"" + name + "\": " + e.what());
continue;
}
user->start();
sleep(1);
}
}
String usersFileName = "users.txt";
File usersFile;
if(File::Exist(usersFileName))
{
usersFile.open(usersFileName, File::Read);
String line;
while(usersFile.readLine(line))
{
String &name = line;
String password = name.cut(' ');
name.trim();
password.trim();
User *user = new User(name, password);
user->start();
sleep(1);
line.clear();
}
usersFile.close();
}
usersFile.open(usersFileName, File::Truncate);
usersFile.close();
Core::Instance->join();
Log("main", "Finished");
return 0;
}
catch(const std::exception &e)
{
Log("main", String("ERROR: ") + e.what());
return 1;
}
}
<commit_msg>Corrected bug with empty line in users.txt<commit_after>/*************************************************************************
* Copyright (C) 2011-2012 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* TeapotNet 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "main.h"
#include "map.h"
#include "sha512.h"
#include "store.h"
#include "tracker.h"
#include "http.h"
#include "config.h"
#include "core.h"
#include "user.h"
#include "directory.h"
using namespace tpot;
Mutex tpot::LogMutex;
int main(int argc, char** argv)
{
try {
Log("main", "Starting...");
srand(time(NULL));
const String configFileName = "config.txt";
Config::Load(configFileName);
Config::Default("tracker", "teapotnet.org");
Config::Default("port", "8480");
Config::Default("tracker_port", "8488");
Config::Default("interface_port", "8080");
Config::Default("profiles_dir", "profiles");
Config::Default("static_dir", "static");
Config::Save(configFileName);
StringMap args;
String last;
for(int i=1; i<argc; ++i)
{
String str(argv[i]);
if(str.empty()) continue;
if(str[0] == '-')
{
if(!last.empty()) args[last] = "";
if(str[0] == '-') str.ignore();
if(!str.empty() && str[0] == '-') str.ignore();
if(str.empty())
{
std::cerr<<"Invalid option: "<<argv[i]<<std::endl;
return 1;
}
last = str;
}
else {
if(last.empty()) args[str] = "";
else {
args[last] = str;
last.clear();
}
}
}
Tracker *tracker = NULL;
if(args.contains("tracker"))
{
if(args["tracker"].empty())
args["tracker"] = Config::Get("tracker_port");
int port;
args["tracker"] >> port;
tracker = new Tracker(port);
tracker->start();
}
// Starting interface
String sifport = Config::Get("interface_port");
if(args.contains("ifport")) sifport = args["ifport"];
int ifport;
sifport >> ifport;
Interface::Instance = new Interface(ifport);
Interface::Instance->start();
// Starting core
String sport = Config::Get("port");
if(args.contains("port")) sport = args["port"];
int port;
sport >> port;
Core::Instance = new Core(port);
Core::Instance->start();
if(!Directory::Exist(Config::Get("profiles_dir")))
Directory::Create(Config::Get("profiles_dir"));
Directory profilesDir(Config::Get("profiles_dir"));
while(profilesDir.nextFile())
{
if(profilesDir.fileIsDir())
{
String name = profilesDir.fileName();
User *user;
try {
user = new User(name);
}
catch(const std::exception &e)
{
Log("main", "ERROR: Unable to load user \"" + name + "\": " + e.what());
continue;
}
user->start();
sleep(1);
}
}
String usersFileName = "users.txt";
File usersFile;
if(File::Exist(usersFileName))
{
usersFile.open(usersFileName, File::Read);
String line;
while(usersFile.readLine(line))
{
String &name = line;
name.trim();
String password = name.cut(' ');
password.trim();
if(name.empty()) continue;
User *user = new User(name, password);
user->start();
sleep(1);
line.clear();
}
usersFile.close();
}
usersFile.open(usersFileName, File::Truncate);
usersFile.close();
Core::Instance->join();
Log("main", "Finished");
return 0;
}
catch(const std::exception &e)
{
Log("main", String("ERROR: ") + e.what());
return 1;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "application.h"
#include "mainwindow.h"
#include <QNetworkProxy>
#include <QSettings>
#include <QUrl>
#include <Irc>
static void setApplicationProxy(QUrl url)
{
if (!url.isEmpty()) {
if (url.port() == -1)
url.setPort(8080);
QNetworkProxy proxy(QNetworkProxy::HttpProxy, url.host(), url.port(), url.userName(), url.password());
QNetworkProxy::setApplicationProxy(proxy);
}
}
int main(int argc, char* argv[])
{
Application app(argc, argv);
MainWindow window;
QStringList args = app.arguments();
QUrl proxy;
int index = args.indexOf("-proxy");
if (index != -1)
proxy = QUrl(args.value(index + 1));
else
proxy = QUrl(qgetenv("http_proxy"));
if (!proxy.isEmpty())
setApplicationProxy(proxy);
QByteArray encoding;
index = args.indexOf("-encoding");
if (index != -1)
encoding = args.value(index + 1).toLocal8Bit();
else if (!qgetenv("COMMUNI_ENCODING").isEmpty())
encoding = qgetenv("COMMUNI_ENCODING");
if (!encoding.isEmpty())
Application::setEncoding(encoding);
window.show();
return app.exec();
}
<commit_msg>Add a workaround for butt ugly fonts in OS X Mavericks<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "application.h"
#include "mainwindow.h"
#include <QNetworkProxy>
#include <QSettings>
#include <QFont>
#include <QUrl>
#include <Irc>
static void setApplicationProxy(QUrl url)
{
if (!url.isEmpty()) {
if (url.port() == -1)
url.setPort(8080);
QNetworkProxy proxy(QNetworkProxy::HttpProxy, url.host(), url.port(), url.userName(), url.password());
QNetworkProxy::setApplicationProxy(proxy);
}
}
int main(int argc, char* argv[])
{
#ifdef Q_OS_MAC
// QTBUG-32789 - GUI widgets use the wrong font on OS X Mavericks
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
#endif
Application app(argc, argv);
MainWindow window;
QStringList args = app.arguments();
QUrl proxy;
int index = args.indexOf("-proxy");
if (index != -1)
proxy = QUrl(args.value(index + 1));
else
proxy = QUrl(qgetenv("http_proxy"));
if (!proxy.isEmpty())
setApplicationProxy(proxy);
QByteArray encoding;
index = args.indexOf("-encoding");
if (index != -1)
encoding = args.value(index + 1).toLocal8Bit();
else if (!qgetenv("COMMUNI_ENCODING").isEmpty())
encoding = qgetenv("COMMUNI_ENCODING");
if (!encoding.isEmpty())
Application::setEncoding(encoding);
window.show();
return app.exec();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <locale>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <uriparser/Uri.h>
#include <SQLiteCpp/SQLiteCpp.h>
#define DB_PATH "/srv/http/data/vbus.sqlite"
typedef std::unordered_map<std::string, std::string> parameterMap;
parameterMap* parseURL(const std::string& url);
void printCsvResult(SQLite::Statement& query, std::ostream& stream, bool isFirstRow);
void printJsonResult(SQLite::Statement& query, std::ostream& stream, bool isFirstRow);
void find_and_replace(std::string& source, std::string const& find, std::string const& replace)
{
for(std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos;)
{
source.replace(i, find.length(), replace);
i += replace.length();
}
}
// See: http://stackoverflow.com/questions/15220861/how-can-i-set-the-comma-to-be-a-decimal-point
class punct_facet: public std::numpunct<char>
{
protected: char do_decimal_point() const { return '.'; }
};
int main(int argc, char const *argv[])
{
// Set decimal seperator to '.'
std::cout.imbue(std::locale(std::cout.getloc(), new punct_facet()));
// Print HTTP header
std::cout << "Content-type: text/comma-separated-values\r\n"
<< "Cache-Control: no-cache, no-store, must-revalidate\r\n"
<< "Pragma: no-cache\r\n"
<< "Expires: 0\r\n"
<< "Access-Control-Allow-Origin: *\r\n\r\n";
std::unique_ptr<parameterMap> requestParameter;
try
{
SQLite::Database db(DB_PATH);
auto request_uri = std::getenv("REQUEST_URI");
if (request_uri != nullptr)
{
requestParameter.reset(parseURL(std::string(request_uri)));
}
else {
requestParameter.reset(new parameterMap());
}
// Set default parameter
if (requestParameter->count("timespan") == 0) { (*requestParameter)["timespan"] = "-1 hour"; }
if (requestParameter->count("format") == 0) { (*requestParameter)["format"] = "csv"; }
SQLite::Statement query(db, "SELECT "
"datetime(time, 'localtime') as time, "
"temp1, temp2, temp3, temp4, pump1, pump2 "
"FROM data "
"WHERE time > (SELECT DATETIME('now', ?)) "
"ORDER BY id");
query.bind(1, (*requestParameter)["timespan"]);
if ((*requestParameter)["format"] == "csv")
{
std::cout << "Datum,Ofen,Speicher-unten,Speicher-oben,Heizung,Ventil-Ofen,Ventil-Heizung" << std::endl;
}
else if ((*requestParameter)["format"] == "json")
{
std::cout << "{ \"data\": [" << std::endl;
}
bool isFirstRow = true;
while (query.executeStep())
{
if ((*requestParameter)["format"] == "csv")
{
printCsvResult(query, std::cout, isFirstRow);
}
else if ((*requestParameter)["format"] == "json")
{
printJsonResult(query, std::cout, isFirstRow);
}
isFirstRow = false;
}
if ((*requestParameter)["format"] == "json")
{
std::cout << std::endl<< "] }" << std::endl;
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
void printCsvResult(SQLite::Statement& query, std::ostream& stream, bool isFirstRow)
{
stream << query.getColumn(0).getText() << ","
<< query.getColumn(1).getDouble() << ","
<< query.getColumn(2).getDouble() << ","
<< query.getColumn(3).getDouble() << ","
<< query.getColumn(4).getDouble() << ","
<< query.getColumn(5).getInt() << ","
<< query.getColumn(6).getInt() << std::endl;
}
void printJsonResult(SQLite::Statement& query, std::ostream& stream, bool isFirstRow)
{
if (!isFirstRow) {
stream << "," << std::endl;
}
stream << "{ \"timestamp\": \"" << query.getColumn(0).getText() << "\" ,"
<< "\"temp1\": " << query.getColumn(1).getDouble() << ","
<< "\"temp2\": " << query.getColumn(2).getDouble() << ","
<< "\"temp3\": " << query.getColumn(3).getDouble() << ","
<< "\"temp4\": " << query.getColumn(4).getDouble() << ","
<< "\"valve1\": " << query.getColumn(5).getInt() << ","
<< "\"valve2\": " << query.getColumn(6).getInt() << "}";
}
parameterMap* parseURL(const std::string& url)
{
UriParserStateA state;
UriUriA uri;
state.uri = &uri;
if (uriParseUriA(&state, url.c_str()) != URI_SUCCESS)
{
uriFreeUriMembersA(&uri);
return new std::unordered_map<std::string, std::string>();
}
UriQueryListA* queryList;
int itemCount;
if (uriDissectQueryMallocA(&queryList, &itemCount, uri.query.first, uri.query.afterLast) == URI_SUCCESS)
{
auto parameter = new parameterMap();
auto& current = queryList;
do
{
if (queryList->value != nullptr) {
(*parameter)[queryList->key] = queryList->value;
}
else {
(*parameter)[queryList->key] = std::string("");
}
current = queryList->next;
} while (current != nullptr);
uriFreeQueryListA(queryList);
uriFreeUriMembersA(&uri);
return parameter;
}
return new std::unordered_map<std::string, std::string>();
}
<commit_msg>Add option for single result<commit_after>#include <iostream>
#include <locale>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <uriparser/Uri.h>
#include <SQLiteCpp/SQLiteCpp.h>
#define DB_PATH "/srv/http/data/vbus.sqlite"
#define SELECT_TIMESPAN "SELECT " \
"datetime(time, 'localtime') as time, " \
"temp1, temp2, temp3, temp4, pump1, pump2 " \
"FROM data " \
"WHERE time > (SELECT DATETIME('now', ?)) " \
"ORDER BY id"
#define SELECT_SINGLE "SELECT " \
"datetime(time, 'localtime') as time, " \
"temp1, temp2, temp3, temp4, pump1, pump2 " \
"FROM data " \
"ORDER BY id DESC LIMIT 1"
typedef std::unordered_map<std::string, std::string> parameterMap;
parameterMap* parseURL(const std::string& url);
void printCsvResult(SQLite::Statement& query, std::ostream& stream, bool isFirstRow);
void printJsonResult(SQLite::Statement& query, std::ostream& stream, bool isFirstRow);
void find_and_replace(std::string& source, std::string const& find, std::string const& replace)
{
for(std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos;)
{
source.replace(i, find.length(), replace);
i += replace.length();
}
}
// See: http://stackoverflow.com/questions/15220861/how-can-i-set-the-comma-to-be-a-decimal-point
class punct_facet: public std::numpunct<char>
{
protected: char do_decimal_point() const { return '.'; }
};
int main(int argc, char const *argv[])
{
// Set decimal seperator to '.'
std::cout.imbue(std::locale(std::cout.getloc(), new punct_facet()));
// Print HTTP header
std::cout << "Content-type: text/comma-separated-values\r\n"
<< "Cache-Control: no-cache, no-store, must-revalidate\r\n"
<< "Pragma: no-cache\r\n"
<< "Expires: 0\r\n"
<< "Access-Control-Allow-Origin: *\r\n\r\n";
std::unique_ptr<parameterMap> requestParameter;
try
{
SQLite::Database db(DB_PATH);
auto request_uri = std::getenv("REQUEST_URI");
if (request_uri != nullptr)
{
requestParameter.reset(parseURL(std::string(request_uri)));
}
else {
requestParameter.reset(new parameterMap());
}
// Set default parameter
if (requestParameter->count("timespan") == 0) { (*requestParameter)["timespan"] = "-1 hour"; }
if (requestParameter->count("format") == 0) { (*requestParameter)["format"] = "csv"; }
std::unique_ptr<SQLite::Statement> query;
if ((*requestParameter)["timespan"] == "single")
{
query.reset(new SQLite::Statement(db, SELECT_SINGLE));
}
else {
query.reset(new SQLite::Statement(db, SELECT_TIMESPAN));
query->bind(1, (*requestParameter)["timespan"]);
}
if ((*requestParameter)["format"] == "csv")
{
std::cout << "Datum,Ofen,Speicher-unten,Speicher-oben,Heizung,Ventil-Ofen,Ventil-Heizung" << std::endl;
}
else if ((*requestParameter)["format"] == "json")
{
std::cout << "{ \"data\": [" << std::endl;
}
bool isFirstRow = true;
while (query->executeStep())
{
if ((*requestParameter)["format"] == "csv")
{
printCsvResult(*query, std::cout, isFirstRow);
}
else if ((*requestParameter)["format"] == "json")
{
printJsonResult(*query, std::cout, isFirstRow);
}
isFirstRow = false;
}
if ((*requestParameter)["format"] == "json")
{
std::cout << std::endl<< "] }" << std::endl;
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
void printCsvResult(SQLite::Statement& query, std::ostream& stream, bool isFirstRow)
{
stream << query.getColumn(0).getText() << ","
<< query.getColumn(1).getDouble() << ","
<< query.getColumn(2).getDouble() << ","
<< query.getColumn(3).getDouble() << ","
<< query.getColumn(4).getDouble() << ","
<< query.getColumn(5).getInt() << ","
<< query.getColumn(6).getInt() << std::endl;
}
void printJsonResult(SQLite::Statement& query, std::ostream& stream, bool isFirstRow)
{
if (!isFirstRow) {
stream << "," << std::endl;
}
stream << "{ \"timestamp\": \"" << query.getColumn(0).getText() << "\" ,"
<< "\"temp1\": " << query.getColumn(1).getDouble() << ","
<< "\"temp2\": " << query.getColumn(2).getDouble() << ","
<< "\"temp3\": " << query.getColumn(3).getDouble() << ","
<< "\"temp4\": " << query.getColumn(4).getDouble() << ","
<< "\"valve1\": " << query.getColumn(5).getInt() << ","
<< "\"valve2\": " << query.getColumn(6).getInt() << "}";
}
parameterMap* parseURL(const std::string& url)
{
UriParserStateA state;
UriUriA uri;
state.uri = &uri;
if (uriParseUriA(&state, url.c_str()) != URI_SUCCESS)
{
uriFreeUriMembersA(&uri);
return new std::unordered_map<std::string, std::string>();
}
UriQueryListA* queryList;
int itemCount;
if (uriDissectQueryMallocA(&queryList, &itemCount, uri.query.first, uri.query.afterLast) == URI_SUCCESS)
{
auto parameter = new parameterMap();
auto& current = queryList;
do
{
if (queryList->value != nullptr) {
(*parameter)[queryList->key] = queryList->value;
}
else {
(*parameter)[queryList->key] = std::string("");
}
current = queryList->next;
} while (current != nullptr);
uriFreeQueryListA(queryList);
uriFreeUriMembersA(&uri);
return parameter;
}
return new std::unordered_map<std::string, std::string>();
}<|endoftext|> |
<commit_before>/*! \file main.cpp
* \brief Program to run the grid code. */
#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"
#define OUTPUT
//#define CPU_TIME
int main(int argc, char *argv[])
{
// timing variables
double start_total, stop_total, start_step, stop_step;
#ifdef CPU_TIME
double stop_init, init_min, init_max, init_avg;
double start_bound, stop_bound, bound_min, bound_max, bound_avg;
double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
double init, bound, hydro;
init = bound = hydro = 0;
#endif //CPU_TIME
// start the total time
start_total = get_time();
/* Initialize MPI communication */
#ifdef MPI_CHOLLA
InitializeChollaMPI(&argc, &argv);
#endif /*MPI_CHOLLA*/
Real dti = 0; // inverse time step, 1.0 / dt
// input parameter variables
char *param_file;
struct parameters P;
int nfile = 0; // number of output files
Real outtime = 0; // current output time
// read in command line arguments
if (argc != 2)
{
chprintf("usage: %s <parameter_file>\n", argv[0]);
chexit(-1);
} else {
param_file = argv[1];
}
// create the grid
Grid3D G;
// read in the parameters
parse_params (param_file, &P);
// and output to screen
chprintf ("Parameter values: nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
chprintf ("Output directory: %s\n", P.outdir);
// initialize the grid
G.Initialize(&P);
chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);
// Set initial conditions and calculate first dt
chprintf("Setting initial conditions...\n");
G.Set_Initial_Conditions(P);
chprintf("Initial conditions set.\n");
// set main variables for Read_Grid inital conditions
if (strcmp(P.init, "Read_Grid") == 0) {
dti = C_cfl / G.H.dt;
outtime += G.H.t;
nfile = P.nfile*P.nfull;
}
#ifdef CPU_TIME
G.Timer.Initialize();
#endif
#ifdef GRAVITY
G.Initialize_Gravity(&P);
G.Compute_Gravitational_Potential();
#endif
// set boundary conditions (assign appropriate values to ghost cells)
chprintf("Setting boundary conditions...\n");
G.Set_Boundary_Conditions(P);
chprintf("Boundary conditions set.\n");
chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
chprintf("Ratio of specific heats gamma = %f\n",gama);
chprintf("Nstep = %d Timestep = %f Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);
#ifdef OUTPUT
if (strcmp(P.init, "Read_Grid") != 0) {
// write the initial conditions to file
chprintf("Writing initial conditions to file...\n");
WriteData(G, P, nfile);
}
// add one to the output file count
nfile++;
#endif //OUTPUT
// increment the next output time
outtime += P.outstep;
#ifdef CPU_TIME
stop_init = get_time();
init = stop_init - start_total;
#ifdef MPI_CHOLLA
init_min = ReduceRealMin(init);
init_max = ReduceRealMax(init);
init_avg = ReduceRealAvg(init);
chprintf("Init min: %9.4f max: %9.4f avg: %9.4f\n", init_min, init_max, init_avg);
#else
printf("Init %9.4f\n", init);
#endif //MPI_CHOLLA
#endif //CPU_TIME
// Evolve the grid, one timestep at a time
chprintf("Starting calculations.\n");
while (G.H.t < P.tout)
//while (G.H.n_step < 1)
{
chprintf("n_step: %d \n", G.H.n_step + 1 );
// get the start time
start_step = get_time();
// calculate the timestep
G.set_dt(dti);
if (G.H.t + G.H.dt > outtime)
{
G.H.dt = outtime - G.H.t;
}
#ifdef MPI_CHOLLA
G.H.dt = ReduceRealMin(G.H.dt);
#endif
// Advance the grid by one timestep
dti = G.Update_Hydro_Grid();
// update the time
G.H.t += G.H.dt;
// add one to the timestep count
G.H.n_step++;
// set boundary conditions for next time step
G.Set_Boundary_Conditions_All(P);
#ifdef CPU_TIME
G.Timer.Print_Times();
#endif
// get the time to compute the total timestep
stop_step = get_time();
stop_total = get_time();
G.H.t_wall = stop_total-start_total;
#ifdef MPI_CHOLLA
G.H.t_wall = ReduceRealMax(G.H.t_wall);
#endif
chprintf("n_step: %d sim time: %10.7f sim timestep: %7.4e timestep time = %9.3f ms total time = %9.4f s\n\n",
G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);
if (G.H.t == outtime)
{
#ifdef OUTPUT
/*output the grid data*/
WriteData(G, P, nfile);
// add one to the output file count
nfile++;
#endif //OUTPUT
// update to the next output time
outtime += P.outstep;
}
/*
// check for failures
for (int i=G.H.n_ghost; i<G.H.nx-G.H.n_ghost; i++) {
for (int j=G.H.n_ghost; j<G.H.ny-G.H.n_ghost; j++) {
for (int k=G.H.n_ghost; k<G.H.nz-G.H.n_ghost; k++) {
int id = i + j*G.H.nx + k*G.H.nx*G.H.ny;
if (G.C.density[id] < 0.0 || G.C.density[id] != G.C.density[id]) {
printf("Failure in cell %d %d %d. Density %e\n", i, j, k, G.C.density[id]);
#ifdef MPI_CHOLLA
MPI_Finalize();
chexit(-1);
#endif
exit(0);
}
}
}
}
*/
} /*end loop over timesteps*/
// free the grid
G.Reset();
#ifdef MPI_CHOLLA
MPI_Finalize();
#endif /*MPI_CHOLLA*/
return 0;
}
<commit_msg>grav potential computed every timestep after hydro_update<commit_after>/*! \file main.cpp
* \brief Program to run the grid code. */
#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"
#define OUTPUT
//#define CPU_TIME
int main(int argc, char *argv[])
{
// timing variables
double start_total, stop_total, start_step, stop_step;
#ifdef CPU_TIME
double stop_init, init_min, init_max, init_avg;
double start_bound, stop_bound, bound_min, bound_max, bound_avg;
double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
double init, bound, hydro;
init = bound = hydro = 0;
#endif //CPU_TIME
// start the total time
start_total = get_time();
/* Initialize MPI communication */
#ifdef MPI_CHOLLA
InitializeChollaMPI(&argc, &argv);
#endif /*MPI_CHOLLA*/
Real dti = 0; // inverse time step, 1.0 / dt
// input parameter variables
char *param_file;
struct parameters P;
int nfile = 0; // number of output files
Real outtime = 0; // current output time
// read in command line arguments
if (argc != 2)
{
chprintf("usage: %s <parameter_file>\n", argv[0]);
chexit(-1);
} else {
param_file = argv[1];
}
// create the grid
Grid3D G;
// read in the parameters
parse_params (param_file, &P);
// and output to screen
chprintf ("Parameter values: nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
chprintf ("Output directory: %s\n", P.outdir);
// initialize the grid
G.Initialize(&P);
chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);
// Set initial conditions and calculate first dt
chprintf("Setting initial conditions...\n");
G.Set_Initial_Conditions(P);
chprintf("Initial conditions set.\n");
// set main variables for Read_Grid inital conditions
if (strcmp(P.init, "Read_Grid") == 0) {
dti = C_cfl / G.H.dt;
outtime += G.H.t;
nfile = P.nfile*P.nfull;
}
#ifdef CPU_TIME
G.Timer.Initialize();
#endif
#ifdef GRAVITY
G.Initialize_Gravity(&P);
#endif
#ifdef GRAVITY
G.Compute_Gravitational_Potential( &P);
#endif
// set boundary conditions (assign appropriate values to ghost cells)
chprintf("Setting boundary conditions...\n");
G.Set_Boundary_Conditions(P);
chprintf("Boundary conditions set.\n");
chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
chprintf("Ratio of specific heats gamma = %f\n",gama);
chprintf("Nstep = %d Timestep = %f Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);
#ifdef OUTPUT
if (strcmp(P.init, "Read_Grid") != 0) {
// write the initial conditions to file
chprintf("Writing initial conditions to file...\n");
WriteData(G, P, nfile);
}
// add one to the output file count
nfile++;
#endif //OUTPUT
// increment the next output time
outtime += P.outstep;
#ifdef CPU_TIME
stop_init = get_time();
init = stop_init - start_total;
#ifdef MPI_CHOLLA
init_min = ReduceRealMin(init);
init_max = ReduceRealMax(init);
init_avg = ReduceRealAvg(init);
chprintf("Init min: %9.4f max: %9.4f avg: %9.4f\n", init_min, init_max, init_avg);
#else
printf("Init %9.4f\n", init);
#endif //MPI_CHOLLA
#endif //CPU_TIME
// Evolve the grid, one timestep at a time
chprintf("Starting calculations.\n");
while (G.H.t < P.tout)
//while (G.H.n_step < 1)
{
chprintf("n_step: %d \n", G.H.n_step + 1 );
// get the start time
start_step = get_time();
// calculate the timestep
G.set_dt(dti);
if (G.H.t + G.H.dt > outtime)
{
G.H.dt = outtime - G.H.t;
}
#ifdef MPI_CHOLLA
G.H.dt = ReduceRealMin(G.H.dt);
#endif
// Advance the grid by one timestep
dti = G.Update_Hydro_Grid();
// update the time
G.H.t += G.H.dt;
#ifdef GRAVITY
//Compute Gravitational potential for next step
G.Compute_Gravitational_Potential( &P);
#endif
// add one to the timestep count
G.H.n_step++;
// set boundary conditions for next time step
G.Set_Boundary_Conditions_All(P);
#ifdef CPU_TIME
G.Timer.Print_Times();
#endif
// get the time to compute the total timestep
stop_step = get_time();
stop_total = get_time();
G.H.t_wall = stop_total-start_total;
#ifdef MPI_CHOLLA
G.H.t_wall = ReduceRealMax(G.H.t_wall);
#endif
chprintf("n_step: %d sim time: %10.7f sim timestep: %7.4e timestep time = %9.3f ms total time = %9.4f s\n\n",
G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);
if (G.H.t == outtime)
{
#ifdef OUTPUT
/*output the grid data*/
WriteData(G, P, nfile);
// add one to the output file count
nfile++;
#endif //OUTPUT
// update to the next output time
outtime += P.outstep;
}
/*
// check for failures
for (int i=G.H.n_ghost; i<G.H.nx-G.H.n_ghost; i++) {
for (int j=G.H.n_ghost; j<G.H.ny-G.H.n_ghost; j++) {
for (int k=G.H.n_ghost; k<G.H.nz-G.H.n_ghost; k++) {
int id = i + j*G.H.nx + k*G.H.nx*G.H.ny;
if (G.C.density[id] < 0.0 || G.C.density[id] != G.C.density[id]) {
printf("Failure in cell %d %d %d. Density %e\n", i, j, k, G.C.density[id]);
#ifdef MPI_CHOLLA
MPI_Finalize();
chexit(-1);
#endif
exit(0);
}
}
}
}
*/
} /*end loop over timesteps*/
// free the grid
G.Reset();
#ifdef MPI_CHOLLA
MPI_Finalize();
#endif /*MPI_CHOLLA*/
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 1992-$THISYEAR$ $TROLLTECH$. All rights reserved.
**
** This file is part of $PRODUCT$.
**
** $CPP_LICENSE$
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include "main.h"
#include "cppheadergenerator.h"
#include "cppimplgenerator.h"
#include "javagenerator.h"
#include "metainfogenerator.h"
#include "reporthandler.h"
#include "metajavabuilder.h"
#include "typesystem.h"
#include "classlistgenerator.h"
#include "qdocgenerator.h"
#include "uiconverter.h"
#include <QDir>
void generatePriFile(const QString &base_dir, const QString &sub_dir,
const MetaJavaClassList &classes,
MetaInfoGenerator *info_generator);
void dumpMetaJavaTree(const MetaJavaClassList &classes);
void test_typeparser(const QString &signature);
int main(int argc, char *argv[])
{
QString default_file = "tests/dummy.h";
QString default_system = "build_all.txt";
QString fileName;
QString typesystemFileName;
QString out_dir = "..";
QString pp_file = ".preprocessed.tmp";
QStringList rebuild_classes;
QString doc_dir = "../../main/doc/jdoc";
QString ui_file_name;
bool print_stdout = false;
bool no_java = false;
bool no_cpp_h = false;
bool no_cpp_impl = false;
bool no_metainfo = false;
bool display_help = false;
bool dump_object_tree = false;
bool build_class_list = false;
bool build_qdoc_japi = false;
bool docs_enabled = false;
bool do_ui_convert = false;
for (int i=1; i<argc; ++i) {
QString arg(argv[i]);
if (arg.startsWith("--no-suppress-warnings")) {
TypeDatabase *db = TypeDatabase::instance();
db->setSuppressWarnings(false);
} else if (arg.startsWith("--output-directory=")) {
out_dir = arg.mid(19);
} else if (arg.startsWith("--print-stdout")) {
print_stdout = true;
} else if (arg.startsWith("--debug-level=")) {
QString level = arg.mid(14);
if (level == "sparse")
ReportHandler::setDebugLevel(ReportHandler::SparseDebug);
else if (level == "medium")
ReportHandler::setDebugLevel(ReportHandler::MediumDebug);
else if (level == "full")
ReportHandler::setDebugLevel(ReportHandler::FullDebug);
} else if (arg.startsWith("--no-java")) {
no_java = true;
} else if (arg.startsWith("--no-cpp-h")) {
no_cpp_h = true;
} else if (arg.startsWith("--no-cpp-impl")) {
no_cpp_impl = true;
} else if (arg.startsWith("--build-class-list")) {
build_class_list = true;
} else if (arg.startsWith("--build-qdoc-japi")) {
no_java = true;
no_cpp_h = true;
no_cpp_impl = true;
no_metainfo = true;
build_qdoc_japi = true;
} else if (arg.startsWith("--no-metainfo")) {
no_metainfo = true;
} else if (arg.startsWith("--help") || arg.startsWith("-h") || arg.startsWith("-?")) {
display_help = true;
} else if (arg.startsWith("--dump-object-tree")) {
dump_object_tree = true;
} else if (arg.startsWith("--rebuild-only")) {
Q_ASSERT(argc > i);
QStringList classes = QString(argv[i+1]).split(",", QString::SkipEmptyParts);
TypeDatabase::instance()->setRebuildClasses(classes);
++i;
} else if (arg.startsWith("--jdoc-dir")) {
Q_ASSERT(argc < i);
doc_dir = argv[++i];
} else if (arg.startsWith("--jdoc-enabled")) {
docs_enabled = true;
} else if (arg.startsWith("--convert-to-jui=")) {
ui_file_name = arg.mid(17);
do_ui_convert = true;
if (!QFileInfo(ui_file_name).exists()) {
printf(".ui file '%s' does not exist\n", qPrintable(ui_file_name));
display_help = true;
}
} else {
if (fileName.isEmpty())
fileName = QString(argv[i]);
else
typesystemFileName = QString(argv[i]);
}
}
if (fileName.isEmpty())
fileName = default_file;
if (typesystemFileName.isEmpty())
typesystemFileName = default_system;
display_help = display_help || fileName.isEmpty() || typesystemFileName.isEmpty();
if (display_help) {
printf("Usage:\n %s [options] header-file typesystem-file\n", argv[0]);
printf("Available options:\n");
printf(" --debug-level=[sparse|medium|full]\n"
" --dump-object-tree \n"
" --help, -h or -? \n"
" --no-cpp-h \n"
" --no-cpp-impl \n"
" --no-java \n"
" --no-metainfo \n"
" --no-suppress-warnings \n"
" --output-directory=[dir] \n"
" --print-stdout \n"
" --ui-to-jui=[.ui-filename] \n"
);
return 0;
}
if (!TypeDatabase::instance()->parseFile(typesystemFileName))
qFatal("Cannot parse file: '%s'", qPrintable(typesystemFileName));
if (!Preprocess::preprocess(fileName, pp_file)) {
fprintf(stderr, "Preprocessor failed on file: '%s'\n", qPrintable(fileName));
return 1;
}
// Building the code inforamation...
ReportHandler::setContext("MetaJavaBuilder");
MetaJavaBuilder builder;
builder.setFileName(pp_file);
builder.build();
if (dump_object_tree) {
dumpMetaJavaTree(builder.classes());
return 0;
}
// Ui conversion...
if (do_ui_convert) {
UiConverter converter;
converter.setClasses(builder.classes());
converter.convertToJui(ui_file_name);
return 0;
}
// Code generation
QList<Generator *> generators;
JavaGenerator *java_generator = 0;
CppHeaderGenerator *cpp_header_generator = 0;
CppImplGenerator *cpp_impl_generator = 0;
MetaInfoGenerator *metainfo = 0;
QStringList contexts;
if (build_qdoc_japi) {
generators << new QDocGenerator;
contexts << "QDocGenerator";
}
if (!no_java) {
java_generator = new JavaGenerator;
java_generator->setDocumentationDirectory(doc_dir);
java_generator->setDocumentationEnabled(docs_enabled);
generators << java_generator;
contexts << "JavaGenerator";
}
if (!no_cpp_h) {
cpp_header_generator = new CppHeaderGenerator;
generators << cpp_header_generator;
contexts << "CppHeaderGenerator";
}
if (!no_cpp_impl) {
cpp_impl_generator = new CppImplGenerator;
generators << cpp_impl_generator;
contexts << "CppImplGenerator";
}
if (!no_metainfo) {
metainfo = new MetaInfoGenerator;
generators << metainfo;
contexts << "MetaInfoGenerator";
}
if (build_class_list) {
generators << new ClassListGenerator;
contexts << "ClassListGenerator";
}
for (int i=0; i<generators.size(); ++i) {
Generator *generator = generators.at(i);
ReportHandler::setContext(contexts.at(i));
generator->setOutputDirectory(out_dir);
generator->setClasses(builder.classes());
if (print_stdout)
generator->printClasses();
else
generator->generate();
}
no_metainfo = metainfo == 0 || metainfo->numGenerated() == 0;
if (!no_cpp_impl || !no_cpp_h || !no_metainfo) {
generatePriFile(out_dir, "cpp", builder.classes(),
metainfo);
}
printf("Classes in typesystem: %d\n"
"Generated:\n"
" - java......: %d\n"
" - cpp-impl..: %d\n"
" - cpp-h.....: %d\n"
" - meta-info.: %d\n",
builder.classes().size(),
java_generator ? java_generator->numGenerated() : 0,
cpp_impl_generator ? cpp_impl_generator->numGenerated() : 0,
cpp_header_generator ? cpp_header_generator->numGenerated() : 0,
metainfo ? metainfo->numGenerated() : 0);
printf("Done, %d warnings (%d known issues)\n", ReportHandler::warningCount(),
ReportHandler::suppressedCount());
}
QFile *openPriFile(const QString &base_dir, const QString &sub_dir, const MetaJavaClass *cls)
{
QString pro_file_name = cls->package().replace(".", "_") + "/" + cls->package().replace(".", "_") + ".pri";
if (!sub_dir.isEmpty())
pro_file_name = sub_dir + "/" + pro_file_name;
if (!base_dir.isEmpty())
pro_file_name = base_dir + "/" + pro_file_name;
QFile *pro_file = new QFile(pro_file_name);
if (!pro_file->open(QIODevice::WriteOnly)) {
ReportHandler::warning(QString("failed to open %1 for writing...") .arg(pro_file_name));
return 0;
}
return pro_file;
}
void generatePriFile(const QString &base_dir, const QString &sub_dir,
const MetaJavaClassList &classes,
MetaInfoGenerator *info_generator)
{
QHash<QString, QFile *> fileHash;
foreach (const MetaJavaClass *cls, classes) {
if (!(cls->typeEntry()->codeGeneration() & TypeEntry::GenerateCpp))
continue;
QString meta_info_stub = info_generator->filenameStub();
if (info_generator == 0 || info_generator->generated(cls) == 0)
meta_info_stub = QString();
QTextStream s;
QFile *f = fileHash.value(cls->package(), 0);
if (f == 0) {
f = openPriFile(base_dir, sub_dir, cls);
fileHash.insert(cls->package(), f);
s.setDevice(f);
if (!meta_info_stub.isEmpty()) {
s << "HEADERS += $$PWD/" << meta_info_stub << ".h" << endl;
}
s << "SOURCES += \\" << endl;
if (!meta_info_stub.isEmpty()) {
s << " " << "$$PWD/" << meta_info_stub << ".cpp \\" << endl;
s << " $$PWD/qtjambi_libraryinitializer.cpp \\" << endl;
}
} else {
s.setDevice(f);
}
if (!cls->isNamespace() && !cls->isInterface() && !cls->typeEntry()->isVariant())
s << " " << "$$PWD/qtjambishell_" << cls->name() << ".cpp \\" << endl;
}
foreach (QFile *f, fileHash.values()) {
QTextStream s(f);
s << endl << "HEADERS += \\" << endl;
}
foreach (const MetaJavaClass *cls, classes) {
if (!(cls->typeEntry()->codeGeneration() & TypeEntry::GenerateCpp))
continue;
QFile *f = fileHash.value(cls->package(), 0);
Q_ASSERT(f);
QTextStream s(f);
bool shellfile = (cls->generateShellClass() || cls->queryFunctions(MetaJavaClass::Signals).size() > 0)
&& !cls->isNamespace() && !cls->isInterface() && !cls->typeEntry()->isVariant();
/*bool shellfile = (!cls->isNamespace() && !cls->isInterface() && cls->hasVirtualFunctions()
&& !cls->typeEntry()->isVariant()) */
if (shellfile)
s << " $$PWD/qtjambishell_" << cls->name() << ".h \\" << endl;
}
foreach (QFile *f, fileHash.values()) {
f->close();
delete f;
}
}
void dumpMetaJavaAttributes(const MetaJavaAttributes *attr)
{
if (attr->isNative()) printf(" native");
if (attr->isAbstract()) printf(" abstract");
if (attr->isFinalInJava()) printf(" final(java)");
if (attr->isFinalInCpp()) printf(" final(cpp)");
if (attr->isStatic()) printf(" static");
if (attr->isPrivate()) printf(" private");
if (attr->isProtected()) printf(" protected");
if (attr->isPublic()) printf(" public");
if (attr->isFriendly()) printf(" friendly");
}
void dumpMetaJavaType(const MetaJavaType *type)
{
if (!type) {
printf("[void]");
} else {
printf("[type: %s", qPrintable(type->typeEntry()->qualifiedCppName()));
if (type->isReference()) printf(" &");
int indirections = type->indirections();
if (indirections) printf(" %s", qPrintable(QString(indirections, '*')));
printf(", %s", qPrintable(type->typeEntry()->qualifiedJavaName()));
if (type->isPrimitive()) printf(" primitive");
if (type->isEnum()) printf(" enum");
if (type->isQObject()) printf(" q_obj");
if (type->isNativePointer()) printf(" n_ptr");
if (type->isJavaString()) printf(" java_string");
if (type->isConstant()) printf(" const");
printf("]");
}
}
void dumpMetaJavaArgument(const MetaJavaArgument *arg)
{
printf(" ");
dumpMetaJavaType(arg->type());
printf(" %s", qPrintable(arg->argumentName()));
if (!arg->defaultValueExpression().isEmpty())
printf(" = %s", qPrintable(arg->defaultValueExpression()));
printf("\n");
}
void dumpMetaJavaFunction(const MetaJavaFunction *func)
{
printf(" %s() - ", qPrintable(func->name()));
dumpMetaJavaType(func->type());
dumpMetaJavaAttributes(func);
if (func->isConstant()) printf(" const");
printf("\n arguments:\n");
foreach (MetaJavaArgument *arg, func->arguments())
dumpMetaJavaArgument(arg);
}
void dumpMetaJavaClass(const MetaJavaClass *cls)
{
printf("\nclass: %s, package: %s\n", qPrintable(cls->name()), qPrintable(cls->package()));
if (cls->hasVirtualFunctions())
printf(" shell based\n");
printf(" baseclass: %s\n", qPrintable(cls->baseClassName()));
printf(" interfaces:");
foreach (MetaJavaClass *iface, cls->interfaces())
printf(" %s", qPrintable(iface->name()));
printf("\n");
printf(" attributes:");
dumpMetaJavaAttributes(cls);
printf("\n functions:\n");
foreach (const MetaJavaFunction *func, cls->functions())
dumpMetaJavaFunction(func);
// printf("\n fields:\n");
// foreach (const MetaJavaField *field, cls->fields())
// dumpMetaJavaField(field);
// printf("\n enums:\n");
// foreach (const MetaJavaEnum *e, cls->enums())
// dumpMetaJavaEnum(e);
}
void dumpMetaJavaTree(const MetaJavaClassList &classes)
{
foreach (MetaJavaClass *cls, classes) {
dumpMetaJavaClass(cls);
}
}
<commit_msg>(split) report bad usage<commit_after>/****************************************************************************
**
** Copyright (C) 1992-$THISYEAR$ $TROLLTECH$. All rights reserved.
**
** This file is part of $PRODUCT$.
**
** $CPP_LICENSE$
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include "main.h"
#include "cppheadergenerator.h"
#include "cppimplgenerator.h"
#include "javagenerator.h"
#include "metainfogenerator.h"
#include "reporthandler.h"
#include "metajavabuilder.h"
#include "typesystem.h"
#include "classlistgenerator.h"
#include "qdocgenerator.h"
#include "uiconverter.h"
#include <QDir>
void generatePriFile(const QString &base_dir, const QString &sub_dir,
const MetaJavaClassList &classes,
MetaInfoGenerator *info_generator);
void dumpMetaJavaTree(const MetaJavaClassList &classes);
void test_typeparser(const QString &signature);
int main(int argc, char *argv[])
{
QString default_file = "tests/dummy.h";
QString default_system = "build_all.txt";
QString fileName;
QString typesystemFileName;
QString out_dir = "..";
QString pp_file = ".preprocessed.tmp";
QStringList rebuild_classes;
QString doc_dir = "../../main/doc/jdoc";
QString ui_file_name;
bool print_stdout = false;
bool no_java = false;
bool no_cpp_h = false;
bool no_cpp_impl = false;
bool no_metainfo = false;
bool display_help = false;
bool dump_object_tree = false;
bool build_class_list = false;
bool build_qdoc_japi = false;
bool docs_enabled = false;
bool do_ui_convert = false;
for (int i=1; i<argc; ++i) {
QString arg(argv[i]);
if (arg.startsWith("--no-suppress-warnings")) {
TypeDatabase *db = TypeDatabase::instance();
db->setSuppressWarnings(false);
} else if (arg.startsWith("--output-directory=")) {
out_dir = arg.mid(19);
} else if (arg.startsWith("--print-stdout")) {
print_stdout = true;
} else if (arg.startsWith("--debug-level=")) {
QString level = arg.mid(14);
if (level == "sparse")
ReportHandler::setDebugLevel(ReportHandler::SparseDebug);
else if (level == "medium")
ReportHandler::setDebugLevel(ReportHandler::MediumDebug);
else if (level == "full")
ReportHandler::setDebugLevel(ReportHandler::FullDebug);
} else if (arg.startsWith("--no-java")) {
no_java = true;
} else if (arg.startsWith("--no-cpp-h")) {
no_cpp_h = true;
} else if (arg.startsWith("--no-cpp-impl")) {
no_cpp_impl = true;
} else if (arg.startsWith("--build-class-list")) {
build_class_list = true;
} else if (arg.startsWith("--build-qdoc-japi")) {
no_java = true;
no_cpp_h = true;
no_cpp_impl = true;
no_metainfo = true;
build_qdoc_japi = true;
} else if (arg.startsWith("--no-metainfo")) {
no_metainfo = true;
} else if (arg.startsWith("--help") || arg.startsWith("-h") || arg.startsWith("-?")) {
display_help = true;
} else if (arg.startsWith("--dump-object-tree")) {
dump_object_tree = true;
} else if (arg.startsWith("--rebuild-only")) {
Q_ASSERT(argc > i);
QStringList classes = QString(argv[i+1]).split(",", QString::SkipEmptyParts);
TypeDatabase::instance()->setRebuildClasses(classes);
++i;
} else if (arg.startsWith("--jdoc-dir")) {
Q_ASSERT(argc < i);
doc_dir = argv[++i];
} else if (arg.startsWith("--jdoc-enabled")) {
docs_enabled = true;
} else if (arg.startsWith("--convert-to-jui=")) {
ui_file_name = arg.mid(17);
do_ui_convert = true;
if (!QFileInfo(ui_file_name).exists()) {
printf(".ui file '%s' does not exist\n", qPrintable(ui_file_name));
display_help = true;
}
} else {
if (fileName.isEmpty())
fileName = QString(argv[i]);
else if (typesystemFileName.isEmpty())
typesystemFileName = QString(argv[i]);
else {
display_help = true;
}
}
}
if (fileName.isEmpty())
fileName = default_file;
if (typesystemFileName.isEmpty())
typesystemFileName = default_system;
display_help = display_help || fileName.isEmpty() || typesystemFileName.isEmpty();
if (display_help) {
printf("Usage:\n %s [options] header-file typesystem-file\n", argv[0]);
printf("Available options:\n");
printf(" --debug-level=[sparse|medium|full]\n"
" --dump-object-tree \n"
" --help, -h or -? \n"
" --no-cpp-h \n"
" --no-cpp-impl \n"
" --no-java \n"
" --no-metainfo \n"
" --no-suppress-warnings \n"
" --output-directory=[dir] \n"
" --print-stdout \n"
" --ui-to-jui=[.ui-filename] \n"
);
return 0;
}
if (!TypeDatabase::instance()->parseFile(typesystemFileName))
qFatal("Cannot parse file: '%s'", qPrintable(typesystemFileName));
if (!Preprocess::preprocess(fileName, pp_file)) {
fprintf(stderr, "Preprocessor failed on file: '%s'\n", qPrintable(fileName));
return 1;
}
// Building the code inforamation...
ReportHandler::setContext("MetaJavaBuilder");
MetaJavaBuilder builder;
builder.setFileName(pp_file);
builder.build();
if (dump_object_tree) {
dumpMetaJavaTree(builder.classes());
return 0;
}
// Ui conversion...
if (do_ui_convert) {
UiConverter converter;
converter.setClasses(builder.classes());
converter.convertToJui(ui_file_name);
return 0;
}
// Code generation
QList<Generator *> generators;
JavaGenerator *java_generator = 0;
CppHeaderGenerator *cpp_header_generator = 0;
CppImplGenerator *cpp_impl_generator = 0;
MetaInfoGenerator *metainfo = 0;
QStringList contexts;
if (build_qdoc_japi) {
generators << new QDocGenerator;
contexts << "QDocGenerator";
}
if (!no_java) {
java_generator = new JavaGenerator;
java_generator->setDocumentationDirectory(doc_dir);
java_generator->setDocumentationEnabled(docs_enabled);
generators << java_generator;
contexts << "JavaGenerator";
}
if (!no_cpp_h) {
cpp_header_generator = new CppHeaderGenerator;
generators << cpp_header_generator;
contexts << "CppHeaderGenerator";
}
if (!no_cpp_impl) {
cpp_impl_generator = new CppImplGenerator;
generators << cpp_impl_generator;
contexts << "CppImplGenerator";
}
if (!no_metainfo) {
metainfo = new MetaInfoGenerator;
generators << metainfo;
contexts << "MetaInfoGenerator";
}
if (build_class_list) {
generators << new ClassListGenerator;
contexts << "ClassListGenerator";
}
for (int i=0; i<generators.size(); ++i) {
Generator *generator = generators.at(i);
ReportHandler::setContext(contexts.at(i));
generator->setOutputDirectory(out_dir);
generator->setClasses(builder.classes());
if (print_stdout)
generator->printClasses();
else
generator->generate();
}
no_metainfo = metainfo == 0 || metainfo->numGenerated() == 0;
if (!no_cpp_impl || !no_cpp_h || !no_metainfo) {
generatePriFile(out_dir, "cpp", builder.classes(),
metainfo);
}
printf("Classes in typesystem: %d\n"
"Generated:\n"
" - java......: %d\n"
" - cpp-impl..: %d\n"
" - cpp-h.....: %d\n"
" - meta-info.: %d\n",
builder.classes().size(),
java_generator ? java_generator->numGenerated() : 0,
cpp_impl_generator ? cpp_impl_generator->numGenerated() : 0,
cpp_header_generator ? cpp_header_generator->numGenerated() : 0,
metainfo ? metainfo->numGenerated() : 0);
printf("Done, %d warnings (%d known issues)\n", ReportHandler::warningCount(),
ReportHandler::suppressedCount());
}
QFile *openPriFile(const QString &base_dir, const QString &sub_dir, const MetaJavaClass *cls)
{
QString pro_file_name = cls->package().replace(".", "_") + "/" + cls->package().replace(".", "_") + ".pri";
if (!sub_dir.isEmpty())
pro_file_name = sub_dir + "/" + pro_file_name;
if (!base_dir.isEmpty())
pro_file_name = base_dir + "/" + pro_file_name;
QFile *pro_file = new QFile(pro_file_name);
if (!pro_file->open(QIODevice::WriteOnly)) {
ReportHandler::warning(QString("failed to open %1 for writing...") .arg(pro_file_name));
return 0;
}
return pro_file;
}
void generatePriFile(const QString &base_dir, const QString &sub_dir,
const MetaJavaClassList &classes,
MetaInfoGenerator *info_generator)
{
QHash<QString, QFile *> fileHash;
foreach (const MetaJavaClass *cls, classes) {
if (!(cls->typeEntry()->codeGeneration() & TypeEntry::GenerateCpp))
continue;
QString meta_info_stub = info_generator->filenameStub();
if (info_generator == 0 || info_generator->generated(cls) == 0)
meta_info_stub = QString();
QTextStream s;
QFile *f = fileHash.value(cls->package(), 0);
if (f == 0) {
f = openPriFile(base_dir, sub_dir, cls);
fileHash.insert(cls->package(), f);
s.setDevice(f);
if (!meta_info_stub.isEmpty()) {
s << "HEADERS += $$PWD/" << meta_info_stub << ".h" << endl;
}
s << "SOURCES += \\" << endl;
if (!meta_info_stub.isEmpty()) {
s << " " << "$$PWD/" << meta_info_stub << ".cpp \\" << endl;
s << " $$PWD/qtjambi_libraryinitializer.cpp \\" << endl;
}
} else {
s.setDevice(f);
}
if (!cls->isNamespace() && !cls->isInterface() && !cls->typeEntry()->isVariant())
s << " " << "$$PWD/qtjambishell_" << cls->name() << ".cpp \\" << endl;
}
foreach (QFile *f, fileHash.values()) {
QTextStream s(f);
s << endl << "HEADERS += \\" << endl;
}
foreach (const MetaJavaClass *cls, classes) {
if (!(cls->typeEntry()->codeGeneration() & TypeEntry::GenerateCpp))
continue;
QFile *f = fileHash.value(cls->package(), 0);
Q_ASSERT(f);
QTextStream s(f);
bool shellfile = (cls->generateShellClass() || cls->queryFunctions(MetaJavaClass::Signals).size() > 0)
&& !cls->isNamespace() && !cls->isInterface() && !cls->typeEntry()->isVariant();
/*bool shellfile = (!cls->isNamespace() && !cls->isInterface() && cls->hasVirtualFunctions()
&& !cls->typeEntry()->isVariant()) */
if (shellfile)
s << " $$PWD/qtjambishell_" << cls->name() << ".h \\" << endl;
}
foreach (QFile *f, fileHash.values()) {
f->close();
delete f;
}
}
void dumpMetaJavaAttributes(const MetaJavaAttributes *attr)
{
if (attr->isNative()) printf(" native");
if (attr->isAbstract()) printf(" abstract");
if (attr->isFinalInJava()) printf(" final(java)");
if (attr->isFinalInCpp()) printf(" final(cpp)");
if (attr->isStatic()) printf(" static");
if (attr->isPrivate()) printf(" private");
if (attr->isProtected()) printf(" protected");
if (attr->isPublic()) printf(" public");
if (attr->isFriendly()) printf(" friendly");
}
void dumpMetaJavaType(const MetaJavaType *type)
{
if (!type) {
printf("[void]");
} else {
printf("[type: %s", qPrintable(type->typeEntry()->qualifiedCppName()));
if (type->isReference()) printf(" &");
int indirections = type->indirections();
if (indirections) printf(" %s", qPrintable(QString(indirections, '*')));
printf(", %s", qPrintable(type->typeEntry()->qualifiedJavaName()));
if (type->isPrimitive()) printf(" primitive");
if (type->isEnum()) printf(" enum");
if (type->isQObject()) printf(" q_obj");
if (type->isNativePointer()) printf(" n_ptr");
if (type->isJavaString()) printf(" java_string");
if (type->isConstant()) printf(" const");
printf("]");
}
}
void dumpMetaJavaArgument(const MetaJavaArgument *arg)
{
printf(" ");
dumpMetaJavaType(arg->type());
printf(" %s", qPrintable(arg->argumentName()));
if (!arg->defaultValueExpression().isEmpty())
printf(" = %s", qPrintable(arg->defaultValueExpression()));
printf("\n");
}
void dumpMetaJavaFunction(const MetaJavaFunction *func)
{
printf(" %s() - ", qPrintable(func->name()));
dumpMetaJavaType(func->type());
dumpMetaJavaAttributes(func);
if (func->isConstant()) printf(" const");
printf("\n arguments:\n");
foreach (MetaJavaArgument *arg, func->arguments())
dumpMetaJavaArgument(arg);
}
void dumpMetaJavaClass(const MetaJavaClass *cls)
{
printf("\nclass: %s, package: %s\n", qPrintable(cls->name()), qPrintable(cls->package()));
if (cls->hasVirtualFunctions())
printf(" shell based\n");
printf(" baseclass: %s\n", qPrintable(cls->baseClassName()));
printf(" interfaces:");
foreach (MetaJavaClass *iface, cls->interfaces())
printf(" %s", qPrintable(iface->name()));
printf("\n");
printf(" attributes:");
dumpMetaJavaAttributes(cls);
printf("\n functions:\n");
foreach (const MetaJavaFunction *func, cls->functions())
dumpMetaJavaFunction(func);
// printf("\n fields:\n");
// foreach (const MetaJavaField *field, cls->fields())
// dumpMetaJavaField(field);
// printf("\n enums:\n");
// foreach (const MetaJavaEnum *e, cls->enums())
// dumpMetaJavaEnum(e);
}
void dumpMetaJavaTree(const MetaJavaClassList &classes)
{
foreach (MetaJavaClass *cls, classes) {
dumpMetaJavaClass(cls);
}
}
<|endoftext|> |
<commit_before>// $Id$
/*
Copyright (c) 2007-2010, Trustees of The Leland Stanford Junior University
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 the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*/
/*main.cpp
*
*The starting point of the network simulator
*-Include all network header files
*-initilize the network
*-initialize the traffic manager and set it to run
*
*
*/
#include <sys/time.h>
#include <string>
#include <cstdlib>
#include <iostream>
#include <fstream>
#ifdef USE_GUI
#include <QApplication>
#include "bgui.hpp"
#endif
#include <sstream>
#include "booksim.hpp"
#include "routefunc.hpp"
#include "traffic.hpp"
#include "booksim_config.hpp"
#include "trafficmanager.hpp"
#include "random_utils.hpp"
#include "network.hpp"
#include "injection.hpp"
#include "power_module.hpp"
///////////////////////////////////////////////////////////////////////////////
//include new network here//
#include "singlenet.hpp"
#include "kncube.hpp"
#include "fly.hpp"
#include "isolated_mesh.hpp"
#include "cmesh.hpp"
#include "cmeshx2.hpp"
#include "flatfly_onchip.hpp"
#include "qtree.hpp"
#include "tree4.hpp"
#include "fattree.hpp"
#include "anynet.hpp"
#include "dragonfly.hpp"
///////////////////////////////////////////////////////////////////////////////
//Global declarations
//////////////////////
/* the current traffic manager instance */
TrafficManager * trafficManager = NULL;
int GetSimTime() {
return trafficManager->getTime();
}
class Stats;
Stats * GetStats(const std::string & name) {
Stats* test = trafficManager->getStats(name);
if(test == 0){
cout<<"warning statistics "<<name<<" not found"<<endl;
}
return test;
}
/* printing activity factor*/
bool gPrintActivity;
int gK;//radix
int gN;//dimension
int gC;//concentration
int gNodes;
//generate nocviewer trace
bool gTrace;
ostream * gWatchOut;
#ifdef USE_GUI
bool gGUIMode = false;
#endif
/////////////////////////////////////////////////////////////////////////////
bool AllocatorSim( BookSimConfig const & config )
{
vector<Network *> net;
string topo = config.GetStr( "topology" );
int networks = config.GetInt("physical_subnetworks");
/*To include a new network, must register the network here
*add an else if statement with the name of the network
*/
net.resize(networks);
for (int i = 0; i < networks; ++i) {
ostringstream name;
name << "network_" << i;
if ( topo == "torus" ) {
KNCube::RegisterRoutingFunctions() ;
net[i] = new KNCube( config, name.str(), false );
} else if ( topo == "mesh" ) {
KNCube::RegisterRoutingFunctions() ;
net[i] = new KNCube( config, name.str(), true );
} else if ( topo == "cmesh" ) {
CMesh::RegisterRoutingFunctions() ;
net[i] = new CMesh( config, name.str() );
} else if ( topo == "cmeshx2" ) {
CMeshX2::RegisterRoutingFunctions() ;
net[i] = new CMeshX2( config, name.str() );
} else if ( topo == "fly" ) {
KNFly::RegisterRoutingFunctions() ;
net[i] = new KNFly( config, name.str() );
} else if ( topo == "single" ) {
SingleNet::RegisterRoutingFunctions() ;
net[i] = new SingleNet( config, name.str() );
} else if ( topo == "isolated_mesh" ) {
IsolatedMesh::RegisterRoutingFunctions() ;
net[i] = new IsolatedMesh( config, name.str() );
} else if ( topo == "qtree" ) {
QTree::RegisterRoutingFunctions() ;
net[i] = new QTree( config, name.str() );
} else if ( topo == "tree4" ) {
Tree4::RegisterRoutingFunctions() ;
net[i] = new Tree4( config, name.str() );
} else if ( topo == "fattree" ) {
FatTree::RegisterRoutingFunctions() ;
net[i] = new FatTree( config, name.str() );
} else if ( topo == "flatfly" ) {
FlatFlyOnChip::RegisterRoutingFunctions() ;
net[i] = new FlatFlyOnChip( config, name.str() );
} else if ( topo == "anynet"){
AnyNet::RegisterRoutingFunctions() ;
net[i] = new AnyNet(config, name.str());
} else if ( topo == "dragonflynew"){
DragonFlyNew::RegisterRoutingFunctions() ;
net[i] = new DragonFlyNew(config, name.str());
}else {
cerr << "Unknown topology " << topo << endl;
exit(-1);
}
/*legacy code that insert random faults in the networks
*not sure how to use this
*/
if ( config.GetInt( "link_failures" ) ) {
net[i]->InsertRandomFaults( config );
}
}
/*tcc and characterize are legacy
*not sure how to use them
*/
assert(trafficManager == NULL);
trafficManager = new TrafficManager( config, net ) ;
/*Start the simulation run
*/
double total_time; /* Amount of time we've run */
struct timeval start_time, end_time; /* Time before/after user code */
total_time = 0.0;
gettimeofday(&start_time, NULL);
bool result = trafficManager->Run() ;
gettimeofday(&end_time, NULL);
total_time = ((double)(end_time.tv_sec) + (double)(end_time.tv_usec)/1000000.0)
- ((double)(start_time.tv_sec) + (double)(start_time.tv_usec)/1000000.0);
cout<<"Total run time "<<total_time<<endl;
///Power analysis
if(config.GetInt("sim_power")==1){
Power_Module * pnet = new Power_Module(net[0], trafficManager, config);
pnet->run();
delete pnet;
}
for (int i=0; i<networks; ++i)
delete net[i];
delete trafficManager;
trafficManager = NULL;
return result;
}
int main( int argc, char **argv )
{
BookSimConfig config;
#ifdef USE_GUI
for(int i = 1; i < argc; ++i) {
string arg(argv[i]);
if(arg=="-g"){
gGUIMode = true;
break;
}
}
#endif
if ( !ParseArgs( &config, argc, argv ) ) {
#ifdef USE_GUI
if(gGUIMode){
cout<< "No config file found"<<endl;
cout<< "Usage: " << argv[0] << " configfile... [param=value...]" << endl;
cout<< "GUI is using default parameters instead"<<endl;
} else {
#endif
cerr << "Usage: " << argv[0] << " configfile... [param=value...]" << endl;
return 0;
#ifdef USE_GUI
}
#endif
}
/*initialize routing, traffic, injection functions
*/
InitializeRoutingMap( config );
InitializeTrafficMap( config );
InitializeInjectionMap( config );
gPrintActivity = (config.GetInt("print_activity")==1);
gTrace = (config.GetInt("viewer trace")==1);
string watch_out_file = config.GetStr( "watch_out" );
if(watch_out_file == "") {
gWatchOut = NULL;
} else if(watch_out_file == "-") {
gWatchOut = &cout;
} else {
gWatchOut = new ofstream(watch_out_file.c_str());
}
/*configure and run the simulator
*/
#ifdef USE_GUI
if(gGUIMode){
cout<<"GUI Mode\n";
QApplication app(argc, argv);
BooksimGUI * bs = new BooksimGUI();
//transfer all the contorl and data to the gui, go to bgui.cpp for the rest
bs->RegisterAllocSim(&AllocatorSim,&config);
bs->setGeometry(100, 100, 1200, 355);
bs->show();
return app.exec();
}
#endif
bool result = AllocatorSim( config );
return result ? -1 : 0;
}
<commit_msg>fix typo in parameter name<commit_after>// $Id$
/*
Copyright (c) 2007-2010, Trustees of The Leland Stanford Junior University
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 the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*/
/*main.cpp
*
*The starting point of the network simulator
*-Include all network header files
*-initilize the network
*-initialize the traffic manager and set it to run
*
*
*/
#include <sys/time.h>
#include <string>
#include <cstdlib>
#include <iostream>
#include <fstream>
#ifdef USE_GUI
#include <QApplication>
#include "bgui.hpp"
#endif
#include <sstream>
#include "booksim.hpp"
#include "routefunc.hpp"
#include "traffic.hpp"
#include "booksim_config.hpp"
#include "trafficmanager.hpp"
#include "random_utils.hpp"
#include "network.hpp"
#include "injection.hpp"
#include "power_module.hpp"
///////////////////////////////////////////////////////////////////////////////
//include new network here//
#include "singlenet.hpp"
#include "kncube.hpp"
#include "fly.hpp"
#include "isolated_mesh.hpp"
#include "cmesh.hpp"
#include "cmeshx2.hpp"
#include "flatfly_onchip.hpp"
#include "qtree.hpp"
#include "tree4.hpp"
#include "fattree.hpp"
#include "anynet.hpp"
#include "dragonfly.hpp"
///////////////////////////////////////////////////////////////////////////////
//Global declarations
//////////////////////
/* the current traffic manager instance */
TrafficManager * trafficManager = NULL;
int GetSimTime() {
return trafficManager->getTime();
}
class Stats;
Stats * GetStats(const std::string & name) {
Stats* test = trafficManager->getStats(name);
if(test == 0){
cout<<"warning statistics "<<name<<" not found"<<endl;
}
return test;
}
/* printing activity factor*/
bool gPrintActivity;
int gK;//radix
int gN;//dimension
int gC;//concentration
int gNodes;
//generate nocviewer trace
bool gTrace;
ostream * gWatchOut;
#ifdef USE_GUI
bool gGUIMode = false;
#endif
/////////////////////////////////////////////////////////////////////////////
bool AllocatorSim( BookSimConfig const & config )
{
vector<Network *> net;
string topo = config.GetStr( "topology" );
int networks = config.GetInt("physical_subnetworks");
/*To include a new network, must register the network here
*add an else if statement with the name of the network
*/
net.resize(networks);
for (int i = 0; i < networks; ++i) {
ostringstream name;
name << "network_" << i;
if ( topo == "torus" ) {
KNCube::RegisterRoutingFunctions() ;
net[i] = new KNCube( config, name.str(), false );
} else if ( topo == "mesh" ) {
KNCube::RegisterRoutingFunctions() ;
net[i] = new KNCube( config, name.str(), true );
} else if ( topo == "cmesh" ) {
CMesh::RegisterRoutingFunctions() ;
net[i] = new CMesh( config, name.str() );
} else if ( topo == "cmeshx2" ) {
CMeshX2::RegisterRoutingFunctions() ;
net[i] = new CMeshX2( config, name.str() );
} else if ( topo == "fly" ) {
KNFly::RegisterRoutingFunctions() ;
net[i] = new KNFly( config, name.str() );
} else if ( topo == "single" ) {
SingleNet::RegisterRoutingFunctions() ;
net[i] = new SingleNet( config, name.str() );
} else if ( topo == "isolated_mesh" ) {
IsolatedMesh::RegisterRoutingFunctions() ;
net[i] = new IsolatedMesh( config, name.str() );
} else if ( topo == "qtree" ) {
QTree::RegisterRoutingFunctions() ;
net[i] = new QTree( config, name.str() );
} else if ( topo == "tree4" ) {
Tree4::RegisterRoutingFunctions() ;
net[i] = new Tree4( config, name.str() );
} else if ( topo == "fattree" ) {
FatTree::RegisterRoutingFunctions() ;
net[i] = new FatTree( config, name.str() );
} else if ( topo == "flatfly" ) {
FlatFlyOnChip::RegisterRoutingFunctions() ;
net[i] = new FlatFlyOnChip( config, name.str() );
} else if ( topo == "anynet"){
AnyNet::RegisterRoutingFunctions() ;
net[i] = new AnyNet(config, name.str());
} else if ( topo == "dragonflynew"){
DragonFlyNew::RegisterRoutingFunctions() ;
net[i] = new DragonFlyNew(config, name.str());
}else {
cerr << "Unknown topology " << topo << endl;
exit(-1);
}
/*legacy code that insert random faults in the networks
*not sure how to use this
*/
if ( config.GetInt( "link_failures" ) ) {
net[i]->InsertRandomFaults( config );
}
}
/*tcc and characterize are legacy
*not sure how to use them
*/
assert(trafficManager == NULL);
trafficManager = new TrafficManager( config, net ) ;
/*Start the simulation run
*/
double total_time; /* Amount of time we've run */
struct timeval start_time, end_time; /* Time before/after user code */
total_time = 0.0;
gettimeofday(&start_time, NULL);
bool result = trafficManager->Run() ;
gettimeofday(&end_time, NULL);
total_time = ((double)(end_time.tv_sec) + (double)(end_time.tv_usec)/1000000.0)
- ((double)(start_time.tv_sec) + (double)(start_time.tv_usec)/1000000.0);
cout<<"Total run time "<<total_time<<endl;
///Power analysis
if(config.GetInt("sim_power")==1){
Power_Module * pnet = new Power_Module(net[0], trafficManager, config);
pnet->run();
delete pnet;
}
for (int i=0; i<networks; ++i)
delete net[i];
delete trafficManager;
trafficManager = NULL;
return result;
}
int main( int argc, char **argv )
{
BookSimConfig config;
#ifdef USE_GUI
for(int i = 1; i < argc; ++i) {
string arg(argv[i]);
if(arg=="-g"){
gGUIMode = true;
break;
}
}
#endif
if ( !ParseArgs( &config, argc, argv ) ) {
#ifdef USE_GUI
if(gGUIMode){
cout<< "No config file found"<<endl;
cout<< "Usage: " << argv[0] << " configfile... [param=value...]" << endl;
cout<< "GUI is using default parameters instead"<<endl;
} else {
#endif
cerr << "Usage: " << argv[0] << " configfile... [param=value...]" << endl;
return 0;
#ifdef USE_GUI
}
#endif
}
/*initialize routing, traffic, injection functions
*/
InitializeRoutingMap( config );
InitializeTrafficMap( config );
InitializeInjectionMap( config );
gPrintActivity = (config.GetInt("print_activity")==1);
gTrace = (config.GetInt("viewer_trace")==1);
string watch_out_file = config.GetStr( "watch_out" );
if(watch_out_file == "") {
gWatchOut = NULL;
} else if(watch_out_file == "-") {
gWatchOut = &cout;
} else {
gWatchOut = new ofstream(watch_out_file.c_str());
}
/*configure and run the simulator
*/
#ifdef USE_GUI
if(gGUIMode){
cout<<"GUI Mode\n";
QApplication app(argc, argv);
BooksimGUI * bs = new BooksimGUI();
//transfer all the contorl and data to the gui, go to bgui.cpp for the rest
bs->RegisterAllocSim(&AllocatorSim,&config);
bs->setGeometry(100, 100, 1200, 355);
bs->show();
return app.exec();
}
#endif
bool result = AllocatorSim( config );
return result ? -1 : 0;
}
<|endoftext|> |
<commit_before>#include "main.hpp"
#include <cstring>
#include <iostream>
#include <sstream>
#include <locale>
using namespace std;
int main(int argc, const char* argv[]) {
// Print help
if (argc == 1 || strcmp(argv[0], "--help") == 0) {
cout << "Headerize is a tool to convert resource files to headers for inclusion in C/C++ projects." << endl
<< "Usage:" << endl
<< "Headerize input output" << endl;
return 0;
}
// Get input and output names.
string inputName = argv[1];
string outputName;
if (argc > 2)
outputName = argv[2];
else
outputName = inputName + ".hzz";
// Read input file.
ifstream inFile(inputName.c_str(), ios::binary | ios::ate);
char* buffer;
unsigned int size;
if (inFile.is_open()) {
size = inFile.tellg();
buffer = new char[size];
inFile.seekg(0, ios::beg);
inFile.read(buffer, size);
inFile.close();
} else {
cout << "Couldn't open " << inputName << "." << endl;
return 1;
}
// Write output file.
ofstream outFile(outputName.c_str(), ios::trunc);
if (outFile.is_open()) {
writeHeader(outFile, inputName);
writeData(outFile, inputName, buffer, size);
writeFooter(outFile);
outFile.close();
} else {
cout << "Couldn't open " << outputName << " for writing." << endl;
}
return 0;
}
void writeHeader(ofstream& outFile, const string& inputName) {
outFile << "#ifndef " << includeGuard(inputName) << endl
<< "#define " << includeGuard(inputName) << endl << endl;
}
void writeData(ofstream& outFile, const string& inputName, const char* fileContents, unsigned int fileLength) {
outFile << "const char* " << variableName(inputName) << " = { ";
for (unsigned int i=0; i<fileLength; i++) {
outFile << charToHex(fileContents[i]);
if (i < fileLength-1)
outFile << ", ";
}
outFile << " };" << endl
<< "const unsigned int " << variableName(inputName) << "_LENGTH = " << fileLength << ";" << endl;
}
void writeFooter(ofstream& outFile) {
outFile << endl << "#endif" << endl;
}
string variableName(string inputName) {
// Get base filename.
std::size_t found = inputName.find_last_of("/\\");
inputName = inputName.substr(found+1);
// Convert to upper case and replace . with _.
for (string::size_type i=0; i<inputName.length(); i++) {
inputName[i] = toupper(inputName[i]);
if (inputName[i] == '.')
inputName[i] = '_';
}
return inputName;
}
string includeGuard(string inputName) {
return variableName(inputName) + "_HZZ";
}
string charToHex(char character) {
string result = "0x";
ostringstream convert;
convert << std::hex << static_cast<int>(character);
return result + convert.str();
}
<commit_msg>Fix array<commit_after>#include "main.hpp"
#include <cstring>
#include <iostream>
#include <sstream>
#include <locale>
using namespace std;
int main(int argc, const char* argv[]) {
// Print help
if (argc == 1 || strcmp(argv[0], "--help") == 0) {
cout << "Headerize is a tool to convert resource files to headers for inclusion in C/C++ projects." << endl
<< "Usage:" << endl
<< "Headerize input output" << endl;
return 0;
}
// Get input and output names.
string inputName = argv[1];
string outputName;
if (argc > 2)
outputName = argv[2];
else
outputName = inputName + ".hzz";
// Read input file.
ifstream inFile(inputName.c_str(), ios::binary | ios::ate);
char* buffer;
unsigned int size;
if (inFile.is_open()) {
size = inFile.tellg();
buffer = new char[size];
inFile.seekg(0, ios::beg);
inFile.read(buffer, size);
inFile.close();
} else {
cout << "Couldn't open " << inputName << "." << endl;
return 1;
}
// Write output file.
ofstream outFile(outputName.c_str(), ios::trunc);
if (outFile.is_open()) {
writeHeader(outFile, inputName);
writeData(outFile, inputName, buffer, size);
writeFooter(outFile);
outFile.close();
} else {
cout << "Couldn't open " << outputName << " for writing." << endl;
}
return 0;
}
void writeHeader(ofstream& outFile, const string& inputName) {
outFile << "#ifndef " << includeGuard(inputName) << endl
<< "#define " << includeGuard(inputName) << endl << endl;
}
void writeData(ofstream& outFile, const string& inputName, const char* fileContents, unsigned int fileLength) {
outFile << "const char " << variableName(inputName) << "[] = { ";
for (unsigned int i=0; i<fileLength; i++) {
outFile << charToHex(fileContents[i]);
if (i < fileLength-1)
outFile << ", ";
}
outFile << " };" << endl
<< "const unsigned int " << variableName(inputName) << "_LENGTH = " << fileLength << ";" << endl;
}
void writeFooter(ofstream& outFile) {
outFile << endl << "#endif" << endl;
}
string variableName(string inputName) {
// Get base filename.
std::size_t found = inputName.find_last_of("/\\");
inputName = inputName.substr(found+1);
// Convert to upper case and replace . with _.
for (string::size_type i=0; i<inputName.length(); i++) {
inputName[i] = toupper(inputName[i]);
if (inputName[i] == '.')
inputName[i] = '_';
}
return inputName;
}
string includeGuard(string inputName) {
return variableName(inputName) + "_HZZ";
}
string charToHex(char character) {
string result = "0x";
ostringstream convert;
convert << std::hex << static_cast<int>(character);
return result + convert.str();
}
<|endoftext|> |
<commit_before>#include <graphics/types.h>
#include <graphics/exceptions.h>
#include <log/log.h>
#include <lodepng.h>
int main(int argc, char **argv) {
try {
graphics::Window window;
window.activate();
// initialize resources
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLint vx_data[8];
GLfloat tx_data[8];
GLuint v_vbo;
GLuint t_vbo;
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glGenBuffers(1, &v_vbo);
glBindBuffer(GL_ARRAY_BUFFER, v_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof vx_data, nullptr, GL_STREAM_DRAW);
glVertexAttribIPointer(0, 2, GL_INT, 0, 0);
glGenBuffers(1, &t_vbo);
glBindBuffer(GL_ARRAY_BUFFER, t_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof tx_data, nullptr, GL_STREAM_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
const char *const VERTEX_SHADER_CODE =
"#version 330 core\n"
"layout(location = 0) in ivec2 position;\n"
"layout(location = 1) in vec2 i_texcoord;\n"
"out vec2 texcoord;\n"
"uniform ivec2[2] viewcoords;\n"
"uniform float depth = 0.0;\n"
"void main() {\n"
// convert screen space to NDC
// world space (pixels) = position
// screen space = world space - vpos
// 0-1 coordinates = screen space / vsize
// -1-1 coordinates = 2 * 0-1coords - 1
" gl_Position = vec4(vec2(position - viewcoords[0]) / vec2(viewcoords[1]) * vec2(2.0, -2.0) - vec2(1.0, -1.0), 0.0, 1.0);\n"
" texcoord = i_texcoord;\n"
"}\n",
*const FRAGMENT_SHADER_CODE =
"#version 330 core\n"
"uniform sampler2D tex;\n"
"in vec2 texcoord;\n"
"out vec4 color;\n"
"void main() {\n"
" color = texture(tex, texcoord);\n"
"}\n";
glShaderSource(vs, 1, &VERTEX_SHADER_CODE, NULL);
glShaderSource(fs, 1, &FRAGMENT_SHADER_CODE, NULL);
glCompileShader(vs);
glCompileShader(fs);
// TODO: check status and info log
GLuint prog = glCreateProgram();
glAttachShader(prog, vs);
glAttachShader(prog, fs);
glLinkProgram(prog);
// TODO: check status and info log
glDetachShader(prog, vs);
glDetachShader(prog, fs);
glDeleteShader(vs);
glDeleteShader(fs);
glUseProgram(prog);
// set uniforms
GLuint vcloc = glGetUniformLocation(prog, "viewcoords");
GLint ibuffer[4] = {0, 0, 0, 0};
ibuffer[2] = window.getWidth();
ibuffer[3] = window.getHeight();
glUniform2iv(vcloc, 2, ibuffer);
// load texture
graphics::Texture tex("texture.png");
tex.activate();
GLuint tex_loc = glGetUniformLocation(prog, "tex");
glProgramUniform1i(prog, tex_loc, 0);
// game loop
while (window.running()) {
window.clear();
// update VBOs
vx_data[0] = 0;
vx_data[1] = 0;
vx_data[2] = 320;
vx_data[3] = 0;
vx_data[4] = 0;
vx_data[5] = 320;
vx_data[6] = 320;
vx_data[7] = 320;
tx_data[0] = 0.0f;
tx_data[1] = 0.0f;
tx_data[2] = 1.0f;
tx_data[3] = 0.0f;
tx_data[4] = 0.0f;
tx_data[5] = 1.0f;
tx_data[6] = 1.0f;
tx_data[7] = 1.0f;
// upload data
glBindBuffer(GL_ARRAY_BUFFER, v_vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof vx_data, vx_data);
glBindBuffer(GL_ARRAY_BUFFER, t_vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof tx_data, tx_data);
// update viewport
ibuffer[2] = window.getWidth();
ibuffer[3] = window.getHeight();
glUniform2iv(vcloc, 2, ibuffer);
// draw
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// swap buffers
window.swapBuffers();
window.waitEvents();
}
glDeleteBuffers(1, &v_vbo);
glDeleteBuffers(1, &t_vbo);
glDeleteVertexArrays(1, &vao);
} catch (const graphics::WindowCreationError &e) {
LOG_ERR(e.what());
return 1;
} catch (const std::exception &e) {
LOG_ERR("Critical failure: ", e.what());
return 1;
}
return 0;
}
<commit_msg>Use single VBO<commit_after>#include <graphics/types.h>
#include <graphics/exceptions.h>
#include <log/log.h>
#include <lodepng.h>
int main(int argc, char **argv) {
try {
graphics::Window window;
window.activate();
// initialize resources
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLint vx_data[16];
GLfloat *const tx_data = static_cast<GLfloat *>(vx_data + 8);
GLuint v_vbo;
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glGenBuffers(1, &v_vbo);
glBindBuffer(GL_ARRAY_BUFFER, v_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof vx_data, nullptr, GL_STREAM_DRAW);
glVertexAttribIPointer(0, 2, GL_INT, 0, 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, static_cast<GLvoid *>(static_cast<GLint *>(0) + 8));
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
const char *const VERTEX_SHADER_CODE =
"#version 330 core\n"
"layout(location = 0) in ivec2 position;\n"
"layout(location = 1) in vec2 i_texcoord;\n"
"out vec2 texcoord;\n"
"uniform ivec2[2] viewcoords;\n"
"uniform float depth = 0.0;\n"
"void main() {\n"
// convert screen space to NDC
// world space (pixels) = position
// screen space = world space - vpos
// 0-1 coordinates = screen space / vsize
// -1-1 coordinates = 2 * 0-1coords - 1
" gl_Position = vec4(vec2(position - viewcoords[0]) / vec2(viewcoords[1]) * vec2(2.0, -2.0) - vec2(1.0, -1.0), 0.0, 1.0);\n"
" texcoord = i_texcoord;\n"
"}\n",
*const FRAGMENT_SHADER_CODE =
"#version 330 core\n"
"uniform sampler2D tex;\n"
"in vec2 texcoord;\n"
"out vec4 color;\n"
"void main() {\n"
" color = texture(tex, texcoord);\n"
"}\n";
glShaderSource(vs, 1, &VERTEX_SHADER_CODE, NULL);
glShaderSource(fs, 1, &FRAGMENT_SHADER_CODE, NULL);
glCompileShader(vs);
glCompileShader(fs);
// TODO: check status and info log
GLuint prog = glCreateProgram();
glAttachShader(prog, vs);
glAttachShader(prog, fs);
glLinkProgram(prog);
// TODO: check status and info log
glDetachShader(prog, vs);
glDetachShader(prog, fs);
glDeleteShader(vs);
glDeleteShader(fs);
glUseProgram(prog);
// set uniforms
GLuint vcloc = glGetUniformLocation(prog, "viewcoords");
GLint ibuffer[4] = {0, 0, 0, 0};
ibuffer[2] = window.getWidth();
ibuffer[3] = window.getHeight();
glUniform2iv(vcloc, 2, ibuffer);
// load texture
graphics::Texture tex("texture.png");
tex.activate();
GLuint tex_loc = glGetUniformLocation(prog, "tex");
glProgramUniform1i(prog, tex_loc, 0);
// game loop
while (window.running()) {
window.clear();
// update VBOs
vx_data[0] = 0;
vx_data[1] = 0;
vx_data[2] = 320;
vx_data[3] = 0;
vx_data[4] = 0;
vx_data[5] = 320;
vx_data[6] = 320;
vx_data[7] = 320;
tx_data[0] = 0.0f;
tx_data[1] = 0.0f;
tx_data[2] = 1.0f;
tx_data[3] = 0.0f;
tx_data[4] = 0.0f;
tx_data[5] = 1.0f;
tx_data[6] = 1.0f;
tx_data[7] = 1.0f;
// upload data
glBindBuffer(GL_ARRAY_BUFFER, v_vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof vx_data, vx_data);
// update viewport
ibuffer[2] = window.getWidth();
ibuffer[3] = window.getHeight();
glUniform2iv(vcloc, 2, ibuffer);
// draw
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// swap buffers
window.swapBuffers();
window.waitEvents();
}
glDeleteBuffers(1, &v_vbo);
glDeleteVertexArrays(1, &vao);
} catch (const graphics::WindowCreationError &e) {
LOG_ERR(e.what());
return 1;
} catch (const std::exception &e) {
LOG_ERR("Critical failure: ", e.what());
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <vector>
#include <sstream>
#include <experimental/optional>
#include "windows.h"
#include "Objbase.h"
#include "Shlobj.h"
using namespace std;
using namespace std::experimental;
TCHAR select_directory_path[MAX_PATH];
// TODO: A lot of error detection and handling is missing.
class COM {
public:
COM() {
if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) != S_OK)
throw runtime_error("Failed to initialize COM.");
}
~COM() {
CoUninitialize();
}
};
optional<string> select_directory() {
BROWSEINFO browseinfo {};
browseinfo.pszDisplayName = select_directory_path;
browseinfo.lpszTitle = "Please select directory containing the bin files.";
browseinfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON;
PIDLIST_ABSOLUTE idlist = SHBrowseForFolder(&browseinfo);
if (idlist == nullptr) {
return {};
}
else {
if (!SHGetPathFromIDList(idlist, select_directory_path)) {
CoTaskMemFree(idlist);
throw runtime_error("SHGetPathFromIDList failed.");
};
CoTaskMemFree(idlist);
return select_directory_path;
}
}
vector<string> find_bin_files(string directory) {
vector<string> result;
string search_path(directory);
search_path += "\\*.bin";
WIN32_FIND_DATA search_data {};
HANDLE search_handle = FindFirstFile(search_path.c_str(), &search_data);
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
result.emplace_back(search_data.cFileName);
while (FindNextFile(search_handle, &search_data)) {
result.emplace_back(search_data.cFileName);
}
FindClose(search_handle);
}
return result;
}
string generate_cuesheet(vector<string> files) {
stringstream ss;
if (files.size() > 0) {
ss << "FILE \"" << files.at(0) << "\" BINARY\n";
ss << " TRACK 01 MODE2/2352\n";
ss << " INDEX 01 00:00:00\n";
for(size_t track = 1; track < files.size(); ++track) {
ss << "FILE \"" << files.at(track) << "\" BINARY\n";
ss << " TRACK 0" << track << " AUDIO\n";
ss << " INDEX 00 00:00:00\n";
ss << " INDEX 01 00:02:00\n";
};
}
return ss.str();
}
string generate_cuesheet_filename(vector<string> files) {
return "Cuesheet.cue";
}
bool file_exists(string filename) {
WIN32_FIND_DATA find_data {};
HANDLE search_handle = FindFirstFile(filename.c_str(), &find_data);
auto error_code = GetLastError();
FindClose(search_handle);
if (error_code == ERROR_FILE_NOT_FOUND) return false;
if (error_code == ERROR_SUCCESS) return true;
throw runtime_error("File existence check failed.");
}
int main(int argc, const char* argv[]) {
try {
COM com;
auto dir = select_directory();
if (dir) {
auto files = find_bin_files(*dir);
if (files.empty()) {
MessageBox(nullptr, "No bin files found in the selected directory.", "Error", MB_OK | MB_ICONERROR);
}
else {
auto cuesheet = generate_cuesheet(files);
string filename = generate_cuesheet_filename(files);
string full_filename = *dir + '\\' + filename;
if (file_exists(full_filename)) {
MessageBox(nullptr, "A cuesheet file already exists. Do you want to overwrite it?", "File exists", MB_YESNO | MB_ICONWARNING);
}
MessageBox(nullptr, cuesheet.c_str(), "Cuesheet", MB_OK | MB_ICONINFORMATION);
}
}
}
catch (const exception& e) {
MessageBox(nullptr, "Win32 error occured.", "Error", MB_OK | MB_ICONERROR);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Fix cuesheet file existence bug<commit_after>#include <cstdlib>
#include <vector>
#include <sstream>
#include <experimental/optional>
#include "windows.h"
#include "Objbase.h"
#include "Shlobj.h"
using namespace std;
using namespace std::experimental;
TCHAR select_directory_path[MAX_PATH];
// TODO: A lot of error detection and handling is missing.
class COM {
public:
COM() {
if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) != S_OK)
throw runtime_error("Failed to initialize COM.");
}
~COM() {
CoUninitialize();
}
};
optional<string> select_directory() {
BROWSEINFO browseinfo {};
browseinfo.pszDisplayName = select_directory_path;
browseinfo.lpszTitle = "Please select directory containing the bin files.";
browseinfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON;
PIDLIST_ABSOLUTE idlist = SHBrowseForFolder(&browseinfo);
if (idlist == nullptr) {
return {};
}
else {
if (!SHGetPathFromIDList(idlist, select_directory_path)) {
CoTaskMemFree(idlist);
throw runtime_error("SHGetPathFromIDList failed.");
};
CoTaskMemFree(idlist);
return select_directory_path;
}
}
vector<string> find_bin_files(string directory) {
vector<string> result;
string search_path(directory);
search_path += "\\*.bin";
WIN32_FIND_DATA search_data {};
HANDLE search_handle = FindFirstFile(search_path.c_str(), &search_data);
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
result.emplace_back(search_data.cFileName);
while (FindNextFile(search_handle, &search_data)) {
result.emplace_back(search_data.cFileName);
}
FindClose(search_handle);
}
return result;
}
string generate_cuesheet(vector<string> files) {
stringstream ss;
if (files.size() > 0) {
ss << "FILE \"" << files.at(0) << "\" BINARY\n";
ss << " TRACK 01 MODE2/2352\n";
ss << " INDEX 01 00:00:00\n";
for(size_t track = 1; track < files.size(); ++track) {
ss << "FILE \"" << files.at(track) << "\" BINARY\n";
ss << " TRACK 0" << track << " AUDIO\n";
ss << " INDEX 00 00:00:00\n";
ss << " INDEX 01 00:02:00\n";
};
}
return ss.str();
}
string generate_cuesheet_filename(vector<string> files) {
return "Cuesheet.cue";
}
bool file_exists(string filename) {
WIN32_FIND_DATA find_data {};
HANDLE search_handle = FindFirstFile(filename.c_str(), &find_data);
auto error_code = GetLastError();
FindClose(search_handle);
if (error_code == ERROR_FILE_NOT_FOUND) return false;
if (error_code == ERROR_NO_MORE_FILES) return true;
throw error_code;
}
int main(int argc, const char* argv[]) {
try {
COM com;
auto dir = select_directory();
if (dir) {
auto files = find_bin_files(*dir);
if (files.empty()) {
MessageBox(nullptr, "No bin files found in the selected directory.", "Error", MB_OK | MB_ICONERROR);
}
else {
auto cuesheet = generate_cuesheet(files);
string filename = generate_cuesheet_filename(files);
string full_filename = *dir + '\\' + filename;
if (file_exists(full_filename)) {
MessageBox(nullptr, "A cuesheet file already exists. Do you want to overwrite it?", "File exists", MB_YESNO | MB_ICONWARNING);
}
MessageBox(nullptr, cuesheet.c_str(), "Cuesheet", MB_OK | MB_ICONINFORMATION);
}
}
}
catch (const exception& e) {
MessageBox(nullptr, e.what(), "Error", MB_OK | MB_ICONERROR);
return EXIT_FAILURE;
}
catch (DWORD error_code) {
LPSTR buffer = nullptr;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&buffer), 0, nullptr);
MessageBox(nullptr, buffer, "Error", MB_OK | MB_ICONERROR);
LocalFree(buffer);
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2015 nabijaczleweli
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include <sqlite3.h>
#include <functional>
#include <iostream>
#include <cstdlib>
#include <random>
#include <string>
#include <vector>
#include <mutex>
using namespace std;
struct db_t {
sqlite3 * db;
db_t() : db(nullptr) {
sqlite3_open("number-game.db", &db);
sqlite3_exec(db, "CREATE TABLE scores(name string, score int);", nullptr, nullptr, nullptr);
}
~db_t() {
sqlite3_close(db);
}
operator sqlite3 *() {
return db;
}
};
void play_game(db_t & db) {
int desired = 420;
int guessed = desired - 1;
unsigned int tries = 0;
cout << desired << '\n';
while(guessed != desired) {
++tries;
string guesseds;
while(guesseds.empty()) {
cout << "Enter the number: ";
cin >> guesseds;
if(guesseds.find_first_not_of("0123456789") == string::npos)
guessed = atoi(guesseds.c_str());
else {
cout << "That ain't no number!\n";
guesseds.clear();
}
}
if(guessed != desired) {
cout << "Incorrect! Your number is too ";
if(guessed < desired)
cout << "small";
else if(guessed > desired)
cout << "big";
cout << '\n';
}
}
cout << "Congratulations! You guessed the number in " << tries << " tr" << ((tries > 1) ? "ies" : +"y") << "!\n"
<< "Enter your name: ";
string name;
cin.ignore(); // Necessary, because reasons
getline(cin, name);
auto statement = sqlite3_mprintf("INSERT INTO scores VALUES(%Q, %u);", name.c_str(), tries);
sqlite3_exec(db, statement, nullptr, nullptr, nullptr);
sqlite3_free(statement);
}
void display_highscores(db_t & db) {
static const auto outputscore = [](char ** values) { cout << values[1] << ":\t" << values[0] << '\n'; };
once_flag header_printed;
sqlite3_exec(db, "SELECT * FROM scores ORDER BY score;", [](void * data, int, char ** values, char ** names) {
call_once(*static_cast<once_flag *>(data), [&]() {
cout << "Entries have the format:\n";
outputscore(names);
});
outputscore(values);
return 0;
}, &header_printed, nullptr);
}
int main() {
static const vector<pair<function<void(db_t &)>, string>> menu({{play_game, "Play game"}, {display_highscores, "Show highscores"}, {[](auto &) {}, "Quit"}});
string idxs;
while(idxs.empty()) {
cout << "What do you want to do?\n";
size_t idx{};
for(const auto & item : menu)
cout << "\t" << idx++ << ". " << item.second << '\n';
cout << "Enter one of the above numbers: ";
cin >> idxs;
if((idxs.find_first_not_of("0123456789") != string::npos) || ((idx = strtoul(idxs.c_str(), nullptr, 10)) >= menu.size())) {
cout << '\n';
idxs.clear();
continue;
}
cout << '\n';
db_t db;
menu[idx].first(db);
}
}
<commit_msg>Use a more natural indexing scheme for menu<commit_after>// The MIT License (MIT)
// Copyright (c) 2015 nabijaczleweli
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include <sqlite3.h>
#include <functional>
#include <iostream>
#include <cstdlib>
#include <random>
#include <string>
#include <vector>
#include <mutex>
using namespace std;
struct db_t {
sqlite3 * db;
db_t() : db(nullptr) {
sqlite3_open("number-game.db", &db);
sqlite3_exec(db, "CREATE TABLE scores(name string, score int);", nullptr, nullptr, nullptr);
}
~db_t() {
sqlite3_close(db);
}
operator sqlite3 *() {
return db;
}
};
void play_game(db_t & db) {
int desired = 420;
int guessed = desired - 1;
unsigned int tries = 0;
cout << desired << '\n';
while(guessed != desired) {
++tries;
string guesseds;
while(guesseds.empty()) {
cout << "Enter the number: ";
cin >> guesseds;
if(guesseds.find_first_not_of("0123456789") == string::npos)
guessed = atoi(guesseds.c_str());
else {
cout << "That ain't no number!\n";
guesseds.clear();
}
}
if(guessed != desired) {
cout << "Incorrect! Your number is too ";
if(guessed < desired)
cout << "small";
else if(guessed > desired)
cout << "big";
cout << '\n';
}
}
cout << "Congratulations! You guessed the number in " << tries << " tr" << ((tries > 1) ? "ies" : +"y") << "!\n"
<< "Enter your name: ";
string name;
cin.ignore(); // Necessary, because reasons
getline(cin, name);
auto statement = sqlite3_mprintf("INSERT INTO scores VALUES(%Q, %u);", name.c_str(), tries);
sqlite3_exec(db, statement, nullptr, nullptr, nullptr);
sqlite3_free(statement);
}
void display_highscores(db_t & db) {
static const auto outputscore = [](char ** values) { cout << values[1] << ":\t" << values[0] << '\n'; };
once_flag header_printed;
sqlite3_exec(db, "SELECT * FROM scores ORDER BY score;", [](void * data, int, char ** values, char ** names) {
call_once(*static_cast<once_flag *>(data), [&]() {
cout << "Entries have the format:\n";
outputscore(names);
});
outputscore(values);
return 0;
}, &header_printed, nullptr);
}
int main() {
static const vector<pair<function<void(db_t &)>, string>> menu({{play_game, "Play game"}, {display_highscores, "Show highscores"}, {[](auto &) {}, "Quit"}});
string idxs;
while(idxs.empty()) {
cout << "What do you want to do?\n";
size_t idx = 1;
for(const auto & item : menu)
cout << "\t" << idx++ << ". " << item.second << '\n';
cout << "Enter one of the above numbers: ";
cin >> idxs;
if((idxs.find_first_not_of("0123456789") != string::npos) || ((idx = strtoul(idxs.c_str(), nullptr, 10)) > menu.size())) {
cout << '\n';
idxs.clear();
continue;
}
cout << '\n';
db_t db;
menu[idx - 1].first(db);
}
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <vector>
#include <sstream>
#include <experimental/optional>
#include "windows.h"
#include "Objbase.h"
#include "Shlobj.h"
using namespace std;
using namespace std::experimental;
TCHAR select_directory_path[MAX_PATH];
// TODO: A lot of error detection and handling is missing.
class COM {
public:
COM() {
if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) != S_OK)
throw runtime_error("Failed to initialize COM.");
}
~COM() {
CoUninitialize();
}
};
optional<string> select_directory() {
BROWSEINFO browseinfo {};
browseinfo.pszDisplayName = select_directory_path;
browseinfo.lpszTitle = "Please select directory containing the bin files.";
browseinfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON;
PIDLIST_ABSOLUTE idlist = SHBrowseForFolder(&browseinfo);
if (idlist == nullptr) {
return {};
}
else {
if (!SHGetPathFromIDList(idlist, select_directory_path)) {
CoTaskMemFree(idlist);
throw runtime_error("SHGetPathFromIDList failed.");
};
CoTaskMemFree(idlist);
return select_directory_path;
}
}
vector<string> find_bin_files(string directory) {
vector<string> result;
string search_path(directory);
search_path += "\\*.bin";
WIN32_FIND_DATA search_data {};
HANDLE search_handle = FindFirstFile(search_path.c_str(), &search_data);
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
result.emplace_back(search_data.cFileName);
while (FindNextFile(search_handle, &search_data)) {
result.emplace_back(search_data.cFileName);
}
FindClose(search_handle);
}
return result;
}
string generate_cuesheet(vector<string> files) {
stringstream ss;
if (files.size() > 0) {
ss << "FILE \"" << files.at(0) << "\" BINARY\n";
ss << " TRACK 01 MODE2/2352\n";
ss << " INDEX 01 00:00:00\n";
for(size_t track = 1; track < files.size(); ++track) {
ss << "FILE \"" << files.at(track) << "\" BINARY\n";
ss << " TRACK 0" << track << " AUDIO\n";
ss << " INDEX 00 00:00:00\n";
ss << " INDEX 01 00:02:00\n";
};
}
return ss.str();
}
string generate_cuesheet_filename(vector<string> files) {
return "Cuesheet.cue";
}
bool file_exists(string filename) {
WIN32_FIND_DATA find_data {};
HANDLE search_handle = FindFirstFile(filename.c_str(), &find_data);
auto error_code = GetLastError();
FindClose(search_handle);
if (error_code == ERROR_FILE_NOT_FOUND) return false;
if (error_code == ERROR_NO_MORE_FILES) return true;
throw error_code;
}
int main(int argc, const char* argv[]) {
try {
COM com;
auto dir = select_directory();
if (dir) {
auto files = find_bin_files(*dir);
if (files.empty()) {
MessageBox(nullptr, "No bin files found in the selected directory.", "Error", MB_OK | MB_ICONERROR);
}
else {
auto cuesheet = generate_cuesheet(files);
string filename = generate_cuesheet_filename(files);
string full_filename = *dir + '\\' + filename;
if (file_exists(full_filename)) {
MessageBox(nullptr, "A cuesheet file already exists. Do you want to overwrite it?", "File exists", MB_YESNO | MB_ICONWARNING);
}
MessageBox(nullptr, cuesheet.c_str(), "Cuesheet", MB_OK | MB_ICONINFORMATION);
}
}
}
catch (const exception& e) {
MessageBox(nullptr, e.what(), "Error", MB_OK | MB_ICONERROR);
return EXIT_FAILURE;
}
catch (DWORD error_code) {
LPSTR buffer = nullptr;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&buffer), 0, nullptr);
MessageBox(nullptr, buffer, "Error", MB_OK | MB_ICONERROR);
LocalFree(buffer);
}
return EXIT_SUCCESS;
}
<commit_msg>Application respect overwrite warning<commit_after>#include <cstdlib>
#include <vector>
#include <sstream>
#include <experimental/optional>
#include "windows.h"
#include "Objbase.h"
#include "Shlobj.h"
using namespace std;
using namespace std::experimental;
TCHAR select_directory_path[MAX_PATH];
// TODO: A lot of error detection and handling is missing.
class COM {
public:
COM() {
if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) != S_OK)
throw runtime_error("Failed to initialize COM.");
}
~COM() {
CoUninitialize();
}
};
optional<string> select_directory() {
BROWSEINFO browseinfo {};
browseinfo.pszDisplayName = select_directory_path;
browseinfo.lpszTitle = "Please select directory containing the bin files.";
browseinfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON;
PIDLIST_ABSOLUTE idlist = SHBrowseForFolder(&browseinfo);
if (idlist == nullptr) {
return {};
}
else {
if (!SHGetPathFromIDList(idlist, select_directory_path)) {
CoTaskMemFree(idlist);
throw runtime_error("SHGetPathFromIDList failed.");
};
CoTaskMemFree(idlist);
return string(select_directory_path);
}
}
vector<string> find_bin_files(string directory) {
vector<string> result;
string search_path(directory);
search_path += "\\*.bin";
WIN32_FIND_DATA search_data {};
HANDLE search_handle = FindFirstFile(search_path.c_str(), &search_data);
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
result.emplace_back(search_data.cFileName);
while (FindNextFile(search_handle, &search_data)) {
result.emplace_back(search_data.cFileName);
}
FindClose(search_handle);
}
return result;
}
string generate_cuesheet(vector<string> files) {
stringstream ss;
if (files.size() > 0) {
ss << "FILE \"" << files.at(0) << "\" BINARY\n";
ss << " TRACK 01 MODE2/2352\n";
ss << " INDEX 01 00:00:00\n";
for(size_t track = 1; track < files.size(); ++track) {
ss << "FILE \"" << files.at(track) << "\" BINARY\n";
ss << " TRACK 0" << track << " AUDIO\n";
ss << " INDEX 00 00:00:00\n";
ss << " INDEX 01 00:02:00\n";
};
}
return ss.str();
}
string generate_cuesheet_filename(vector<string> files) {
return "Cuesheet.cue";
}
bool file_exists(string filename) {
WIN32_FIND_DATA find_data {};
HANDLE search_handle = FindFirstFile(filename.c_str(), &find_data);
auto error_code = GetLastError();
FindClose(search_handle);
if (error_code == ERROR_FILE_NOT_FOUND) return false;
if (error_code == ERROR_NO_MORE_FILES) return true;
throw error_code;
}
int main(int argc, const char* argv[]) {
try {
COM com;
auto dir = select_directory();
if (dir) {
auto files = find_bin_files(*dir);
if (files.empty()) {
MessageBox(nullptr, "No bin files found in the selected directory.", "Error", MB_OK | MB_ICONERROR);
}
else {
auto cuesheet = generate_cuesheet(files);
string filename = generate_cuesheet_filename(files);
string full_filename = *dir + '\\' + filename;
bool write_file = true;
if (file_exists(full_filename) &&
(MessageBox(nullptr, "A cuesheet file already exists. Do you want to overwrite it?", "File exists", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) == IDNO)) {
write_file = false;
}
if (write_file) MessageBox(nullptr, cuesheet.c_str(), "Cuesheet", MB_OK | MB_ICONINFORMATION);
}
}
}
catch (const exception& e) {
MessageBox(nullptr, e.what(), "Error", MB_OK | MB_ICONERROR);
return EXIT_FAILURE;
}
catch (DWORD error_code) {
LPSTR buffer = nullptr;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&buffer), 0, nullptr);
MessageBox(nullptr, buffer, "Error", MB_OK | MB_ICONERROR);
LocalFree(buffer);
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* The MIT License
*
* Copyright (c) 2010 OTClient, https://github.com/edubart/otclient
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <prerequisites.h>
#include <core/engine.h>
#include <core/configs.h>
#include <core/resources.h>
#include <core/platform.h>
#include <core/dispatcher.h>
#include <ui/uiskins.h>
#include <script/luascript.h>
#include <ui/uicontainer.h>
#include "protocollogin.h"
void signal_handler(int sig)
{
static bool stopping = false;
switch(sig) {
case SIGTERM:
case SIGINT:
if(!stopping) {
stopping = true;
g_engine.onClose();
}
break;
}
}
void loadDefaultConfigs()
{
// default size
int defWidth = 550;
int defHeight = 450;
g_configs.set("window x", (Platform::getDisplayWidth() - defWidth)/2);
g_configs.set("window y", (Platform::getDisplayHeight() - defHeight)/2);
g_configs.set("window width", defWidth);
g_configs.set("window height", defHeight);
g_configs.set("window maximized", false);
}
void saveConfigs()
{
g_configs.set("window x", Platform::getWindowX());
g_configs.set("window y", Platform::getWindowY());
g_configs.set("window width", Platform::getWindowWidth());
g_configs.set("window height", Platform::getWindowHeight());
g_configs.set("window maximized", Platform::isWindowMaximized());
g_configs.save();
}
#ifdef WIN32_NO_CONSOLE
#include <windows.h>
int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow)
{
std::vector<std::string> args;
boost::split(args, lpszArgument, boost::is_any_of(std::string(" ")));
#else
int main(int argc, const char *argv[])
{
std::vector<std::string> args;
for(int i=0;i<argc;++i)
args.push_back(argv[i]);
#endif
ProtocolLogin login;
login.login("tibialua0", "lua123456");
logInfo("OTClient 0.2.0");
// install exit signal handler
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
// init platform stuff
Platform::init("OTClient");
// load resources paths
g_resources.init(args[0].c_str());
// load configurations
loadDefaultConfigs();
if(!g_configs.load("config.yml"))
logInfo("Could not read configuration file, default configurations will be used.");
// create the window
Platform::createWindow(g_configs.get("window x"), g_configs.get("window y"),
g_configs.get("window width"), g_configs.get("window height"),
550, 450,
g_configs.get("window maximized"));
Platform::setWindowTitle("OTClient");
//Platform::setVsync();
// init engine
g_engine.init();
g_engine.enableFpsCounter();
// load ui skins
g_uiSkins.load("lightness");
// load script modules
g_lua.loadAllModules();
Platform::showWindow();
// main loop, run everything
g_engine.run();
// terminate stuff
g_engine.terminate();
g_uiSkins.terminate();
saveConfigs();
Platform::terminate();
g_resources.terminate();
return 0;
}
<commit_msg>remove connection code from main<commit_after>/* The MIT License
*
* Copyright (c) 2010 OTClient, https://github.com/edubart/otclient
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <prerequisites.h>
#include <core/engine.h>
#include <core/configs.h>
#include <core/resources.h>
#include <core/platform.h>
#include <core/dispatcher.h>
#include <ui/uiskins.h>
#include <script/luascript.h>
#include <ui/uicontainer.h>
void signal_handler(int sig)
{
static bool stopping = false;
switch(sig) {
case SIGTERM:
case SIGINT:
if(!stopping) {
stopping = true;
g_engine.onClose();
}
break;
}
}
void loadDefaultConfigs()
{
// default size
int defWidth = 550;
int defHeight = 450;
g_configs.set("window x", (Platform::getDisplayWidth() - defWidth)/2);
g_configs.set("window y", (Platform::getDisplayHeight() - defHeight)/2);
g_configs.set("window width", defWidth);
g_configs.set("window height", defHeight);
g_configs.set("window maximized", false);
}
void saveConfigs()
{
g_configs.set("window x", Platform::getWindowX());
g_configs.set("window y", Platform::getWindowY());
g_configs.set("window width", Platform::getWindowWidth());
g_configs.set("window height", Platform::getWindowHeight());
g_configs.set("window maximized", Platform::isWindowMaximized());
g_configs.save();
}
#ifdef WIN32_NO_CONSOLE
#include <windows.h>
int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow)
{
std::vector<std::string> args;
boost::split(args, lpszArgument, boost::is_any_of(std::string(" ")));
#else
int main(int argc, const char *argv[])
{
std::vector<std::string> args;
for(int i=0;i<argc;++i)
args.push_back(argv[i]);
#endif
logInfo("OTClient 0.2.0");
// install exit signal handler
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
// init platform stuff
Platform::init("OTClient");
// load resources paths
g_resources.init(args[0].c_str());
// load configurations
loadDefaultConfigs();
if(!g_configs.load("config.yml"))
logInfo("Could not read configuration file, default configurations will be used.");
// create the window
Platform::createWindow(g_configs.get("window x"), g_configs.get("window y"),
g_configs.get("window width"), g_configs.get("window height"),
550, 450,
g_configs.get("window maximized"));
Platform::setWindowTitle("OTClient");
//Platform::setVsync();
// init engine
g_engine.init();
g_engine.enableFpsCounter();
// load ui skins
g_uiSkins.load("lightness");
// load script modules
g_lua.loadAllModules();
Platform::showWindow();
// main loop, run everything
g_engine.run();
// terminate stuff
g_engine.terminate();
g_uiSkins.terminate();
saveConfigs();
Platform::terminate();
g_resources.terminate();
return 0;
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
//#include <QtCore>
#include <QApplication>
#include <QtWidgets>
//#include <QLabel>
//#include <Qt Gui>
int main(int argc, char *argv[]) {
// ::testing::InitGoogleTest(&argc, argv);
QApplication app(argc, argv);
QDialog *dialog = new QDialog;
QLabel *label = new QLabel(dialog);
label->setText("<font color=red>Hello, World!</font>");
dialog->show();
return app.exec();
// return RUN_ALL_TESTS();
}
<commit_msg>remove comments<commit_after>#include "gtest/gtest.h"
#include <QApplication>
#include <QtWidgets>
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
QApplication app(argc, argv);
QDialog *dialog = new QDialog;
QLabel *label = new QLabel(dialog);
label->setText("<font color=red>Hello, World!</font>");
dialog->show();
app.exec();
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <cmath>
#include "NAOS/ellipsoidSurfacePoints.hpp"
#include "NAOS/cubicRoot.hpp"
#include "NAOS/constants.hpp"
#include "NAOS/ellipsoidGravitationalAcceleration.hpp"
#include "NAOS/orbiterEquationsOfMotion.hpp"
#include "NAOS/rk4.hpp"
#include "NAOS/basicMath.hpp"
int main( const int numberOfInputs, const char* inputArguments[ ] )
{
// Open file to store points data for the surface of an ellipsoid.
std::ostringstream ellipsoidSurfacePointsFile;
ellipsoidSurfacePointsFile << "../../data/ellipsoidSurfacePoints.csv";
// Physical parameters for Asteroid Eros, all in SI units, modelled as an ellipsoid.
const double alpha = 20.0 * 1.0e3;
const double beta = 7.0 * 1.0e3;
const double gamma = 7.0 * 1.0e3;
const double density = 3.2 * ( 10.0e-3 ) / ( 10.0e-6 );
const double mass = ( 4.0 * naos::PI / 3.0 ) * density * alpha * beta * gamma;
const double gravitationalParameter = naos::GRAVITATIONAL_CONSTANT * mass;
const double Wx = 0.0; // rotational rate around principal x axis [rad/s]
const double Wy = 0.0; // rotational rate around principal y axis [rad/s]
const double Wz = 0.00033118202125129593; // rotational rate around principal z axis [rad/s]
naos::Vector3 W { Wx, Wy, Wz };
// Generate surface coordinates for the Asteroid
const double stepSizeAzimuthDegree = 10.0;
const double stepSizeElevationDegree = 10.0;
naos::computeEllipsoidSurfacePoints( alpha, beta, gamma,
stepSizeAzimuthDegree, stepSizeElevationDegree,
ellipsoidSurfacePointsFile );
// Test functionality of the maximum real root for a cubic polynomial, compare results with
// wolfram alpha.
const double maxRealRootTest1 = naos::computeMaxRealCubicRoot( -7.0, 4.0, 12.0 );
std::cout << "max Real Root Test 1 = " << maxRealRootTest1 << std::endl;
const double maxRealRootTest2 = naos::computeMaxRealCubicRoot( ( 3.0 / 2.0 ),
( -11.0 / 2.0 ),
( -3.0 ) );
std::cout << "max Real Root Test 2 = " << maxRealRootTest2 << std::endl;
// Test evaluation of gravitational acceleration using previously computed surface points.
std::ifstream ellipsoidSurfacePoints;
ellipsoidSurfacePoints.open( "../../data/ellipsoidSurfacePoints.csv" );
// Extract the column headers first from the surface points file
std::string headers;
std::getline( ellipsoidSurfacePoints, headers );
// Extract numeric data, calculate the gravitational acceleration at all those points and save
// it in a CSV file
double xCoordinate = 0.0;
double yCoordinate = 0.0;
double zCoordinate = 0.0;
double latitude = 0.0;
double longitude = 0.0;
double range = 0.0;
std::string numberString;
naos::Vector3 gravitationalAcceleration { 0.0, 0.0, 0.0 };
std::ofstream ellipsoidSurfaceAccelerationFile;
ellipsoidSurfaceAccelerationFile.open( "../../data/ellipsoidSurfaceAcceleration.csv" );
ellipsoidSurfaceAccelerationFile << "Ux" << "," << "Uy" << "," << "Uz" << ",";
ellipsoidSurfaceAccelerationFile << "U" << "," << "latitude" << "," << "longitude" << std::endl;
while( std::getline( ellipsoidSurfacePoints, numberString, ',' ) )
{
xCoordinate = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString, ',' );
yCoordinate = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString, ',' );
zCoordinate = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString, ',' );
latitude = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString, ',' );
longitude = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString );
range = std::stod( numberString );
naos::computeEllipsoidGravitationalAcceleration( alpha, beta, gamma,
gravitationalParameter,
xCoordinate,
yCoordinate,
zCoordinate,
gravitationalAcceleration );
ellipsoidSurfaceAccelerationFile << gravitationalAcceleration[ 0 ] << ",";
ellipsoidSurfaceAccelerationFile << gravitationalAcceleration[ 1 ] << ",";
ellipsoidSurfaceAccelerationFile << gravitationalAcceleration[ 2 ] << ",";
double accelerationMagnitude =
std::sqrt( gravitationalAcceleration[ 0 ] * gravitationalAcceleration[ 0 ]
+ gravitationalAcceleration[ 1 ] * gravitationalAcceleration[ 1 ]
+ gravitationalAcceleration[ 2 ] * gravitationalAcceleration[ 2 ] );
ellipsoidSurfaceAccelerationFile << accelerationMagnitude << ",";
ellipsoidSurfaceAccelerationFile << latitude << "," << longitude << std::endl;
}
ellipsoidSurfacePoints.close( );
ellipsoidSurfaceAccelerationFile.close( );
// Use RK4 integrator to evaluate the equations of motion for an orbiter around a uniformly
// rotating triaxial ellipsoid (URE). Store the solutions for the entire time of integration in
// a CSV file.
std::ofstream eomOrbiterUREFile;
eomOrbiterUREFile.open( "../../data/eomOrbiterURESolution.csv" );
eomOrbiterUREFile << "x" << "," << "y" << "," << "z" << ",";
eomOrbiterUREFile << "vx" << "," << "vy" << "," << "vz" << "," << "t" << std::endl;
// Specify initial values for the state vector of the orbiter in SI units.
naos::Vector6 initialStateVector( 6 );
// The positions given below correspond to a point on the surface of asteroid Eros.
initialStateVector[ naos::xPositionIndex ] = 13268.2789633788;
initialStateVector[ naos::yPositionIndex ] = 2681.15555091642;
initialStateVector[ naos::zPositionIndex ] = 4499.51326780578;
// Linear velocity of the surface point due to rotation of the asteroid
naos::Vector3 particlePosition { initialStateVector[ naos::xPositionIndex ],
initialStateVector[ naos::yPositionIndex ],
initialStateVector[ naos::zPositionIndex ] };
naos::Vector3 particleSurfaceVelocity( 3 );
particleSurfaceVelocity = naos::crossProduct< naos::Vector3 > ( particlePosition, W );
// Get the initial velocity of the particle, 2 times the linear surface velocity.
initialStateVector[ naos::xVelocityIndex ] = 2 * particleSurfaceVelocity[ 0 ];
initialStateVector[ naos::yVelocityIndex ] = 2 * particleSurfaceVelocity[ 1 ];
initialStateVector[ naos::zVelocityIndex ] = 2 * particleSurfaceVelocity[ 2 ];
// Specify the step size value [s]
double stepSize = 0.01;
// Specify the integration time limits [s]
const double tStart = 0.0;
const double tEnd = 1000.0;
double tCurrent = tStart;
// Save initial values in the CSV file
eomOrbiterUREFile << initialStateVector[ naos::xPositionIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::yPositionIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::zPositionIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::xVelocityIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::yVelocityIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::zVelocityIndex ] << ",";
eomOrbiterUREFile << tCurrent << std::endl;
// Define a vector to store latest/current state values in the integration loop
naos::Vector6 currentStateVector = initialStateVector;
// Define a vector to store the integrated state vector values
naos::Vector6 nextStateVector = initialStateVector;
// Start the integration outer loop
while( tCurrent != tEnd )
{
// calculate the new time value
double tNext = tCurrent + stepSize;
// check if the next time value is greater than the final time value
if( tNext > tEnd )
{
// make the next time value equal to the final time value and recalculate the step size
tNext = tEnd;
stepSize = tEnd - tCurrent;
}
// Evaluate gravitational acceleration values at the current state values
naos::Vector3 currentGravAcceleration( 3 );
naos::computeEllipsoidGravitationalAcceleration( alpha, beta, gamma,
gravitationalParameter,
currentStateVector[ naos::xPositionIndex ],
currentStateVector[ naos::yPositionIndex ],
currentStateVector[ naos::zPositionIndex ],
currentGravAcceleration );
// Create an object of the struct containing the equations of motion (in this case the eom
// for an orbiter around a uniformly rotating tri-axial ellipsoid) and initialize it to the
// values of the constant angular rate of the ellipsoidal asteroid and the current
// gravitational accelerations
naos::eomOrbiterURE derivatives( Wz, currentGravAcceleration );
// Run an instance of RK4 integrator to evaluate the state at the next time value
naos::rk4< naos::Vector6, naos::eomOrbiterURE > ( currentStateVector,
tCurrent,
stepSize,
nextStateVector,
derivatives );
// Check if the new state is valid or not i.e. the particle/orbiter is not
// inside the surface of the asteroid. If it is then terminate the outer loop. Evaluate the
// function phi(x,y,z;0) and check if it has a positive sign (i.e. point is outside)
double xCoordinateSquare = nextStateVector[ naos::xPositionIndex ]
* nextStateVector[ naos::xPositionIndex ];
double yCoordinateSquare = nextStateVector[ naos::yPositionIndex ]
* nextStateVector[ naos::yPositionIndex ];
double zCoordinateSquare = nextStateVector[ naos::zPositionIndex ]
* nextStateVector[ naos::zPositionIndex ];
double phiCheck = xCoordinateSquare / ( alpha * alpha )
+ yCoordinateSquare / ( beta * beta )
+ zCoordinateSquare / ( gamma * gamma )
- 1.0;
if( phiCheck <= 0.0 )
{
// point is either inside or on the surface of the ellipsoid, so terminate the
// simulator and exit the outer loop after saving the data.
eomOrbiterUREFile << nextStateVector[ naos::xPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::yPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::zPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::xVelocityIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::yVelocityIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::zVelocityIndex ] << ",";
eomOrbiterUREFile << tNext << std::endl;
std::cout << std::endl;
std::cout << "Particle at or inside the ellipsoidal surface" << std::endl;
break;
}
// Store the integrated state values in the CSV file
eomOrbiterUREFile << nextStateVector[ naos::xPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::yPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::zPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::xVelocityIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::yVelocityIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::zVelocityIndex ] << ",";
eomOrbiterUREFile << tNext << std::endl;
// save the new state values in the vector of current state values. these will be used in
// the next loop iteration
tCurrent = tNext;
currentStateVector = nextStateVector;
}
return EXIT_SUCCESS;
}
<commit_msg>change initial velocity guess for orbiter to 1m/s in all three directions<commit_after>/*
* Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <cmath>
#include "NAOS/ellipsoidSurfacePoints.hpp"
#include "NAOS/cubicRoot.hpp"
#include "NAOS/constants.hpp"
#include "NAOS/ellipsoidGravitationalAcceleration.hpp"
#include "NAOS/orbiterEquationsOfMotion.hpp"
#include "NAOS/rk4.hpp"
#include "NAOS/basicMath.hpp"
int main( const int numberOfInputs, const char* inputArguments[ ] )
{
// Open file to store points data for the surface of an ellipsoid.
std::ostringstream ellipsoidSurfacePointsFile;
ellipsoidSurfacePointsFile << "../../data/ellipsoidSurfacePoints.csv";
// Physical parameters for Asteroid Eros, all in SI units, modelled as an ellipsoid.
const double alpha = 20.0 * 1.0e3;
const double beta = 7.0 * 1.0e3;
const double gamma = 7.0 * 1.0e3;
const double density = 3.2 * ( 10.0e-3 ) / ( 10.0e-6 );
const double mass = ( 4.0 * naos::PI / 3.0 ) * density * alpha * beta * gamma;
const double gravitationalParameter = naos::GRAVITATIONAL_CONSTANT * mass;
const double Wx = 0.0; // rotational rate around principal x axis [rad/s]
const double Wy = 0.0; // rotational rate around principal y axis [rad/s]
const double Wz = 0.00033118202125129593; // rotational rate around principal z axis [rad/s]
naos::Vector3 W { Wx, Wy, Wz };
// Generate surface coordinates for the Asteroid
const double stepSizeAzimuthDegree = 10.0;
const double stepSizeElevationDegree = 10.0;
naos::computeEllipsoidSurfacePoints( alpha, beta, gamma,
stepSizeAzimuthDegree, stepSizeElevationDegree,
ellipsoidSurfacePointsFile );
// Test functionality of the maximum real root for a cubic polynomial, compare results with
// wolfram alpha.
const double maxRealRootTest1 = naos::computeMaxRealCubicRoot( -7.0, 4.0, 12.0 );
std::cout << "max Real Root Test 1 = " << maxRealRootTest1 << std::endl;
const double maxRealRootTest2 = naos::computeMaxRealCubicRoot( ( 3.0 / 2.0 ),
( -11.0 / 2.0 ),
( -3.0 ) );
std::cout << "max Real Root Test 2 = " << maxRealRootTest2 << std::endl;
// Test evaluation of gravitational acceleration using previously computed surface points.
std::ifstream ellipsoidSurfacePoints;
ellipsoidSurfacePoints.open( "../../data/ellipsoidSurfacePoints.csv" );
// Extract the column headers first from the surface points file
std::string headers;
std::getline( ellipsoidSurfacePoints, headers );
// Extract numeric data, calculate the gravitational acceleration at all those points and save
// it in a CSV file
double xCoordinate = 0.0;
double yCoordinate = 0.0;
double zCoordinate = 0.0;
double latitude = 0.0;
double longitude = 0.0;
double range = 0.0;
std::string numberString;
naos::Vector3 gravitationalAcceleration { 0.0, 0.0, 0.0 };
std::ofstream ellipsoidSurfaceAccelerationFile;
ellipsoidSurfaceAccelerationFile.open( "../../data/ellipsoidSurfaceAcceleration.csv" );
ellipsoidSurfaceAccelerationFile << "Ux" << "," << "Uy" << "," << "Uz" << ",";
ellipsoidSurfaceAccelerationFile << "U" << "," << "latitude" << "," << "longitude" << std::endl;
while( std::getline( ellipsoidSurfacePoints, numberString, ',' ) )
{
xCoordinate = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString, ',' );
yCoordinate = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString, ',' );
zCoordinate = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString, ',' );
latitude = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString, ',' );
longitude = std::stod( numberString );
std::getline( ellipsoidSurfacePoints, numberString );
range = std::stod( numberString );
naos::computeEllipsoidGravitationalAcceleration( alpha, beta, gamma,
gravitationalParameter,
xCoordinate,
yCoordinate,
zCoordinate,
gravitationalAcceleration );
ellipsoidSurfaceAccelerationFile << gravitationalAcceleration[ 0 ] << ",";
ellipsoidSurfaceAccelerationFile << gravitationalAcceleration[ 1 ] << ",";
ellipsoidSurfaceAccelerationFile << gravitationalAcceleration[ 2 ] << ",";
double accelerationMagnitude =
std::sqrt( gravitationalAcceleration[ 0 ] * gravitationalAcceleration[ 0 ]
+ gravitationalAcceleration[ 1 ] * gravitationalAcceleration[ 1 ]
+ gravitationalAcceleration[ 2 ] * gravitationalAcceleration[ 2 ] );
ellipsoidSurfaceAccelerationFile << accelerationMagnitude << ",";
ellipsoidSurfaceAccelerationFile << latitude << "," << longitude << std::endl;
}
ellipsoidSurfacePoints.close( );
ellipsoidSurfaceAccelerationFile.close( );
// Use RK4 integrator to evaluate the equations of motion for an orbiter around a uniformly
// rotating triaxial ellipsoid (URE). Store the solutions for the entire time of integration in
// a CSV file.
std::ofstream eomOrbiterUREFile;
eomOrbiterUREFile.open( "../../data/eomOrbiterURESolution.csv" );
eomOrbiterUREFile << "x" << "," << "y" << "," << "z" << ",";
eomOrbiterUREFile << "vx" << "," << "vy" << "," << "vz" << "," << "t" << std::endl;
// Specify initial values for the state vector of the orbiter in SI units.
naos::Vector6 initialStateVector( 6 );
// The positions given below correspond to a point on the surface of asteroid Eros.
initialStateVector[ naos::xPositionIndex ] = 13268.2789633788;
initialStateVector[ naos::yPositionIndex ] = 2681.15555091642;
initialStateVector[ naos::zPositionIndex ] = 4499.51326780578;
// Linear velocity of the surface point due to rotation of the asteroid
naos::Vector3 particlePosition { initialStateVector[ naos::xPositionIndex ],
initialStateVector[ naos::yPositionIndex ],
initialStateVector[ naos::zPositionIndex ] };
naos::Vector3 particleSurfaceVelocity( 3 );
particleSurfaceVelocity = naos::crossProduct< naos::Vector3 > ( particlePosition, W );
// Get the initial velocity of the particle.
// initialStateVector[ naos::xVelocityIndex ] = 20 * particleSurfaceVelocity[ 0 ];
// initialStateVector[ naos::yVelocityIndex ] = 20 * particleSurfaceVelocity[ 1 ];
// initialStateVector[ naos::zVelocityIndex ] = 20 * particleSurfaceVelocity[ 2 ];
initialStateVector[ naos::xVelocityIndex ] = 1.0;
initialStateVector[ naos::yVelocityIndex ] = 1.0;
initialStateVector[ naos::zVelocityIndex ] = 1.0;
// Specify the step size value [s]
double stepSize = 0.01;
// Specify the integration time limits [s]
const double tStart = 0.0;
const double tEnd = 1000.0;
double tCurrent = tStart;
// Save initial values in the CSV file
eomOrbiterUREFile << initialStateVector[ naos::xPositionIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::yPositionIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::zPositionIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::xVelocityIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::yVelocityIndex ] << ",";
eomOrbiterUREFile << initialStateVector[ naos::zVelocityIndex ] << ",";
eomOrbiterUREFile << tCurrent << std::endl;
// Define a vector to store latest/current state values in the integration loop
naos::Vector6 currentStateVector = initialStateVector;
// Define a vector to store the integrated state vector values
naos::Vector6 nextStateVector = initialStateVector;
// Start the integration outer loop
while( tCurrent != tEnd )
{
// calculate the new time value
double tNext = tCurrent + stepSize;
// check if the next time value is greater than the final time value
if( tNext > tEnd )
{
// make the next time value equal to the final time value and recalculate the step size
tNext = tEnd;
stepSize = tEnd - tCurrent;
}
// Evaluate gravitational acceleration values at the current state values
naos::Vector3 currentGravAcceleration( 3 );
naos::computeEllipsoidGravitationalAcceleration( alpha, beta, gamma,
gravitationalParameter,
currentStateVector[ naos::xPositionIndex ],
currentStateVector[ naos::yPositionIndex ],
currentStateVector[ naos::zPositionIndex ],
currentGravAcceleration );
// Create an object of the struct containing the equations of motion (in this case the eom
// for an orbiter around a uniformly rotating tri-axial ellipsoid) and initialize it to the
// values of the constant angular rate of the ellipsoidal asteroid and the current
// gravitational accelerations
naos::eomOrbiterURE derivatives( Wz, currentGravAcceleration );
// Run an instance of RK4 integrator to evaluate the state at the next time value
naos::rk4< naos::Vector6, naos::eomOrbiterURE > ( currentStateVector,
tCurrent,
stepSize,
nextStateVector,
derivatives );
// Check if the new state is valid or not i.e. the particle/orbiter is not
// inside the surface of the asteroid. If it is then terminate the outer loop. Evaluate the
// function phi(x,y,z;0) and check if it has a positive sign (i.e. point is outside)
double xCoordinateSquare = nextStateVector[ naos::xPositionIndex ]
* nextStateVector[ naos::xPositionIndex ];
double yCoordinateSquare = nextStateVector[ naos::yPositionIndex ]
* nextStateVector[ naos::yPositionIndex ];
double zCoordinateSquare = nextStateVector[ naos::zPositionIndex ]
* nextStateVector[ naos::zPositionIndex ];
double phiCheck = xCoordinateSquare / ( alpha * alpha )
+ yCoordinateSquare / ( beta * beta )
+ zCoordinateSquare / ( gamma * gamma )
- 1.0;
if( phiCheck <= 0.0 )
{
// point is either inside or on the surface of the ellipsoid, so terminate the
// simulator and exit the outer loop after saving the data.
eomOrbiterUREFile << nextStateVector[ naos::xPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::yPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::zPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::xVelocityIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::yVelocityIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::zVelocityIndex ] << ",";
eomOrbiterUREFile << tNext << std::endl;
std::cout << std::endl;
std::cout << "Houston, we've got a problem!" << std::endl;
std::cout << "Particle at or inside the ellipsoidal surface" << std::endl;
std::cout << "Event occurence at: " << tNext << " seconds" << std::endl;
break;
}
// Store the integrated state values in the CSV file
eomOrbiterUREFile << nextStateVector[ naos::xPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::yPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::zPositionIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::xVelocityIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::yVelocityIndex ] << ",";
eomOrbiterUREFile << nextStateVector[ naos::zVelocityIndex ] << ",";
eomOrbiterUREFile << tNext << std::endl;
// save the new state values in the vector of current state values. these will be used in
// the next loop iteration
tCurrent = tNext;
currentStateVector = nextStateVector;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <errno.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <vector>
#include <pwd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
string shell_prompt(); //prototype for prompt function
int cmd_interpreter(string); //prototype for command interpreter
void input_redir(vector<string>); //prototype for input redirection function
int input_helper(string, string);
void output_redir(vector<string>); //prototype for output redirection function
int output_helper(string, string);
int main (int argc, char** argv)
{
while(true)
{
vector<string> inVector;
string input;
input = shell_prompt();
//while (inVector.back() != "")
if (input == "exit")
{
cout << "Exiting rshell." << endl;
exit(0);
}
else
{
char_separator<char> sep(";", "|&#<>");
string t;
tokenizer< char_separator<char> > tokens(input, sep);
BOOST_FOREACH(t, tokens)
{
//TODO do different things depending on delimiters in vector
inVector.push_back(t);
} //end BOOST_FOREACH
bool comment_sentinel = true;
bool pipe_sentinel = false;
for (unsigned i = 0; i < inVector.size(); i++) //go through vector of commands - looking for comments
{
if(comment_sentinel) //if a comment sign is not found, execute
{
string in = inVector.at(i);
cerr << "[ " << in << " ]" << endl;
if (in.at(0) == '#')
{
comment_sentinel = false;
}
else
{
for (unsigned k = 0; k < inVector.size(); k++)
{
if (inVector.at(k).at(0) == '&')
{
//TODO: remove later and fix
}
else if (inVector.at(k).at(0) == '|')
{
if (inVector.at(i + 1).at(0) == '|') //likely to go out of range if at end of command
{
pipe_sentinel = true;
}
if (pipe_sentinel)
{
//TODO: remove later and fix
}
}
else if (inVector.at(k).at(0) == '<')
{
//input redirection
// cerr << "we indir i hope" << endl;
input_redir(inVector);
//input_redir handles
comment_sentinel = false; //force a skip
break;
}
else if (inVector.at(k).at(0) == '>')
{
//output redirection
// cerr << "we outdir i hope" << endl;
output_redir(inVector);
//output_redir function handles this
comment_sentinel = false; //force a skip
break;
}
else
{
; //nothing
continue;
}
}
cmd_interpreter(in);
}
}
//TODO: this is for connectors
// check if the current in.at(0) character equals a connector
// if it does, check if the next one equals a connector
// if it does, run both commands
// check return values of both commands
// ????
// profit
}//endfor
}//endif
}//endwhile
return 0;
}
void input_redir(vector<string> input)
{
//handles all of input redirection
for (unsigned i = 0; i < input.size(); i++)
{
if (input.at(i).at(0) == '<')
{
// cerr << "we input now" << endl;
input_helper(input.at(i-1), input.at(i+1));
}
}
}
int input_helper(string one, string two)
{
int pid = fork();
if (pid == 0)
{
//child
//open close dup
if (open(two.c_str(), O_RDONLY) != -1)
{
if(close(0) != -1) //stdin
{
if(dup(0) != -1)
{
//cerr << one << endl;
cmd_interpreter(one);
return 1;
}
else
{
perror("dup");
exit(1);
}
}
else
{
perror("close");
exit(1);
}
}
else
{
perror("open");
exit(1);
}
if (close(0) == -1)
{
perror("close");
exit(1);
}
}
else
{
//parent
// close(0);
if (waitpid(-1, NULL, 0) == -1)
{
perror("waitpid");
exit(1);
}
if(close(0) == -1)
{
perror("close");
exit(1);
}
return 1;
}
return 0;
}
void output_redir(vector<string> input)
{
//handles all output redirection
for (unsigned i = 0; i < input.size(); i++)
{
//iterate through vector and finds redirection
if (input.at(i).at(0) == '>')
{
// cerr << "we output now" << endl;
output_helper(input.at(i-1), input.at(i+1));
}
}
}
int output_helper(string one, string two)
{
cerr << one << " " << two << endl;
int pid = fork();
if (pid == 0)
{
//child
//open close dup
if (open(two.c_str(), O_WRONLY | O_CREAT) != -1)
{
if(close(1) != -1) //stdin
{
if(dup(1) != -1)
{
cmd_interpreter(one);
return 1;
}
else
{
perror("dup");
exit(1);
}
}
else
{
perror("close");
exit(1);
}
}
else
{
perror("open");
exit(1);
}
if (close(1) == -1)
{
perror("close");
exit(1);
}
}
else
{
//parent
// close(1);
if (waitpid(-1, NULL, 0) == -1)
{
perror("waitpid");
exit(1);
}
if (close(1) == -1)
{
perror("close");
exit(1);
}
return 1;
}
return 0;
}
int cmd_interpreter(string input)//, char** argv)
{
//parse command to seperate command and parameters
//int len = input.length();
vector<string> invector;
string t;
char_separator<char> sep(" ");
tokenizer< char_separator<char> > tokens(input, sep);
//int i = 0;
BOOST_FOREACH(t, tokens) //tokenize input string with flags to seperate items
{
invector.push_back(t);
}
unsigned len = invector.size();
const char** cinput = new const char*[len+2];
const char* program = invector.at(0).c_str();
cinput[0] = program;
for(unsigned i = 1; i < 1 + len; i++)
{
cinput[i] = invector[i].c_str();
}
cinput[len] = '\0';
// int pipefd[
int pid = fork();
if(pid == 0)
{
if (execvp(program, (char**)cinput) == -1)
{
perror("execvp"); // throw an error
exit(1);
}
else
{
return 1;
}
}
else
{
//append stuff here
//parent wait
if (waitpid(-1, NULL, 0) == -1)
{
perror("waitpid");
exit(1);
}
}
return 0;
}
string shell_prompt()
{
string in;
//TODO - error checking for getlogin and gethostname
//implement later
// struct utsname name;
// errno = 0;
// uname(&name)
/*
char name[256];
int maxlen = 64;
if (!gethostname(name, maxlen))
{
string strname(name);
cout << getlogin() << "@" << name << "$ "; //custom prompt with hostname and login name
cin >> in;
}
else
{
perror("gethostname"); //throw error if not found
}
*/
cout << "rshell$ ";
getline(cin, in);
cin.clear();
return in;
}
<commit_msg>remove debug line also I wanted to make a small change to feel better<commit_after>#include <errno.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <vector>
#include <pwd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
string shell_prompt(); //prototype for prompt function
int cmd_interpreter(string); //prototype for command interpreter
void input_redir(vector<string>); //prototype for input redirection function
int input_helper(string, string);
void output_redir(vector<string>); //prototype for output redirection function
int output_helper(string, string);
int main (int argc, char** argv)
{
while(true)
{
vector<string> inVector;
string input;
input = shell_prompt();
//while (inVector.back() != "")
if (input == "exit")
{
cout << "Exiting rshell." << endl;
exit(0);
}
else
{
char_separator<char> sep(";", "|&#<>");
string t;
tokenizer< char_separator<char> > tokens(input, sep);
BOOST_FOREACH(t, tokens)
{
//TODO do different things depending on delimiters in vector
inVector.push_back(t);
} //end BOOST_FOREACH
bool comment_sentinel = true;
bool pipe_sentinel = false;
for (unsigned i = 0; i < inVector.size(); i++) //go through vector of commands - looking for comments
{
if(comment_sentinel) //if a comment sign is not found, execute
{
string in = inVector.at(i);
// cerr << "[ " << in << " ]" << endl;
if (in.at(0) == '#')
{
comment_sentinel = false;
}
else
{
for (unsigned k = 0; k < inVector.size(); k++)
{
if (inVector.at(k).at(0) == '&')
{
//TODO: remove later and fix
}
else if (inVector.at(k).at(0) == '|')
{
if (inVector.at(i + 1).at(0) == '|') //likely to go out of range if at end of command
{
pipe_sentinel = true;
}
if (pipe_sentinel)
{
//TODO: remove later and fix
}
}
else if (inVector.at(k).at(0) == '<')
{
//input redirection
// cerr << "we indir i hope" << endl;
input_redir(inVector);
//input_redir handles
comment_sentinel = false; //force a skip
break;
}
else if (inVector.at(k).at(0) == '>')
{
//output redirection
// cerr << "we outdir i hope" << endl;
output_redir(inVector);
//output_redir function handles this
comment_sentinel = false; //force a skip
break;
}
else
{
; //nothing
continue;
}
}
cmd_interpreter(in);
}
}
//TODO: this is for connectors
// check if the current in.at(0) character equals a connector
// if it does, check if the next one equals a connector
// if it does, run both commands
// check return values of both commands
// ????
// profit
}//endfor
}//endif
}//endwhile
return 0;
}
void input_redir(vector<string> input)
{
//handles all of input redirection
for (unsigned i = 0; i < input.size(); i++)
{
if (input.at(i).at(0) == '<')
{
// cerr << "we input now" << endl;
input_helper(input.at(i-1), input.at(i+1));
}
}
}
int input_helper(string one, string two)
{
int pid = fork();
if (pid == 0)
{
//child
//open close dup
if (open(two.c_str(), O_RDONLY) != -1)
{
if(close(0) != -1) //stdin
{
if(dup(0) != -1)
{
//cerr << one << endl;
cmd_interpreter(one);
return 1;
}
else
{
perror("dup");
exit(1);
}
}
else
{
perror("close");
exit(1);
}
}
else
{
perror("open");
exit(1);
}
if (close(0) == -1)
{
perror("close");
exit(1);
}
}
else
{
//parent
// close(0);
if (waitpid(-1, NULL, 0) == -1)
{
perror("waitpid");
exit(1);
}
if(close(0) == -1)
{
perror("close");
exit(1);
}
return 1;
}
return 0;
}
void output_redir(vector<string> input)
{
//handles all output redirection
for (unsigned i = 0; i < input.size(); i++)
{
//iterate through vector and finds redirection
if (input.at(i).at(0) == '>')
{
// cerr << "we output now" << endl;
output_helper(input.at(i-1), input.at(i+1));
}
}
}
int output_helper(string one, string two)
{
cerr << one << " " << two << endl;
int pid = fork();
if (pid == 0)
{
//child
//open close dup
if (open(two.c_str(), O_WRONLY | O_CREAT) != -1)
{
if(close(1) != -1) //stdin
{
if(dup(1) != -1)
{
cmd_interpreter(one);
return 1;
}
else
{
perror("dup");
exit(1);
}
}
else
{
perror("close");
exit(1);
}
}
else
{
perror("open");
exit(1);
}
if (close(1) == -1)
{
perror("close");
exit(1);
}
}
else
{
//parent
// close(1);
if (waitpid(-1, NULL, 0) == -1)
{
perror("waitpid");
exit(1);
}
if (close(1) == -1)
{
perror("close");
exit(1);
}
return 1;
}
return 0;
}
int cmd_interpreter(string input)//, char** argv)
{
//parse command to seperate command and parameters
//int len = input.length();
vector<string> invector;
string t;
char_separator<char> sep(" ");
tokenizer< char_separator<char> > tokens(input, sep);
//int i = 0;
BOOST_FOREACH(t, tokens) //tokenize input string with flags to seperate items
{
invector.push_back(t);
}
unsigned len = invector.size();
const char** cinput = new const char*[len+2];
const char* program = invector.at(0).c_str();
cinput[0] = program;
for(unsigned i = 1; i < 1 + len; i++)
{
cinput[i] = invector[i].c_str();
}
cinput[len] = '\0';
// int pipefd[
int pid = fork();
if(pid == 0)
{
if (execvp(program, (char**)cinput) == -1)
{
perror("execvp"); // throw an error
exit(1);
}
else
{
return 1;
}
}
else
{
//append stuff here
//parent wait
if (waitpid(-1, NULL, 0) == -1)
{
perror("waitpid");
exit(1);
}
}
return 0;
}
string shell_prompt()
{
string in;
//TODO - error checking for getlogin and gethostname
//implement later
// struct utsname name;
// errno = 0;
// uname(&name)
/*
char name[256];
int maxlen = 64;
if (!gethostname(name, maxlen))
{
string strname(name);
cout << getlogin() << "@" << name << "$ "; //custom prompt with hostname and login name
cin >> in;
}
else
{
perror("gethostname"); //throw error if not found
}
*/
cout << "rshell$ ";
getline(cin, in);
cin.clear();
return in;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/network/protocol/http/client.hpp>
using namespace std;
using namespace boost::network;
int
main(void)
{
http::client::request request("http://povilasb.com");
request << header("Connection", "close");
http::client client_;
http::client::response response = client_.get(request);
std::string body_ = body(response);
cout << body_ << '\n';
return 0;
}
<commit_msg>Refactors code.<commit_after>#include <iostream>
#include <string>
#include <boost/network/protocol/http/client.hpp>
namespace net = boost::network;
namespace http = net::http;
int
main(void)
{
http::client::request request("http://povilasb.com");
request << net::header("Connection", "close");
http::client client_;
http::client::response response = client_.get(request);
std::string body_ = http::body(response);
std::cout << body_ << '\n';
return 0;
}
<|endoftext|> |
<commit_before>#ifndef _NODE_H
#define _NODE_H
#include <vector>
class Node{
private:
union Content{
double idX; //var
double value; //const
int function; //func1 ou func2
};
//não sei se enum e union deveriam ser globais ou declaradas dentro
//do node. A principio, acho que não é de interesse de nenhuma outra
//função acessar estas informação, mas pode ser que eu esteja enganado.
Content C;
int tipo; //recebe o índice do content
Node *left;
Node *right;
public:
Node();
~Node();
double eval(std::vector<double> x);
void print_node_d();
Node *get_copy();
};
#endif
<commit_msg>1.2.1 Fix<commit_after>#ifndef _NODE_H
#define _NODE_H
#include <vector>
class Node{
private:
union Content{
double idX; //var
double value; //const
int function; //func1 ou func2
};
//não sei se enum e union deveriam ser globais ou declaradas dentro
//do node. A principio, acho que não é de interesse de nenhuma outra
//função acessar estas informação, mas pode ser que eu esteja enganado.
Content C;
int tipo; //recebe o índice do content
Node *left;
Node *right;
public:
Node(bool);
~Node();
double eval(std::vector<double> x);
void print_node_d();
Node *get_copy();
};
#endif
<|endoftext|> |
<commit_before>#include <vector>
#include <boost/make_shared.hpp>
#include <boost/unordered_set.hpp>
#include <boost/container/vector.hpp>
#include <dart/collision/collision.h>
#include <dart/dynamics/dynamics.h>
#include <ompl/base/StateSpace.h>
#include <ompl/base/SpaceInformation.h>
#include <ompl/base/StateValidityChecker.h>
#include <ompl/base/spaces/RealVectorStateSpace.h>
#include <ompl/base/spaces/SO2StateSpace.h>
using ::dart::dynamics::DegreeOfFreedom;
using ::ompl::base::StateSpacePtr;
class DARTGeometricStateSpace;
typedef boost::shared_ptr<DARTGeometricStateSpace> DARTGeometricStateSpacePtr;
class DARTGeometricStateSpace : ::ompl::base::CompoundStateSpace {
public:
typedef ::ompl::base::CompoundStateSpace::StateType StateType;
DARTGeometricStateSpace(
::std::vector<DegreeOfFreedom *> const &dofs,
::std::vector<double> const &weights,
::dart::collision::CollisionDetector *collision_detector);
void ApplyState(StateType const *state);
bool IsInCollision();
private:
::std::vector<DegreeOfFreedom *> dofs_;
::boost::container::vector<bool> is_circular_;
::boost::unordered_set<::dart::dynamics::Skeleton *> skeletons_;
::dart::collision::CollisionDetector *collision_detector_;
static bool IsDOFCircular(DegreeOfFreedom const *dof);
};
DARTGeometricStateSpace::DARTGeometricStateSpace(
std::vector<DegreeOfFreedom *> const &dofs,
std::vector<double> const &weights,
::dart::collision::CollisionDetector *collision_detector)
: dofs_(dofs)
, is_circular_(dofs.size())
, collision_detector_(collision_detector)
{
using ::boost::make_shared;
using ::ompl::base::RealVectorStateSpace;
using ::ompl::base::SO2StateSpace;
BOOST_ASSERT(dofs.size() == weights.size());
for (size_t idof = 0; idof < dofs.size(); ++idof) {
DegreeOfFreedom *dof = dofs[idof];
double const &weight = weights[idof];
// Construct a one-dimensional state space for each DOF. Add them, in
// the same order as "dofs", to this CompoundStateSpace.
bool &is_circular = is_circular_[idof];
is_circular = IsDOFCircular(dof);
if (is_circular) {
addSubspace(make_shared<SO2StateSpace>(), weight);
} else {
auto const state_space = make_shared<RealVectorStateSpace>(1);
state_space->setName(dof->getName());
state_space->setBounds(
dof->getPositionLowerLimit(),
dof->getPositionUpperLimit()
);
addSubspace(state_space, weight);
}
// Build a list of all Skeleton's influenced by these joints.
skeletons_.insert(dof->getSkeleton());
}
}
void DARTGeometricStateSpace::ApplyState(StateType const *state)
{
using ::dart::dynamics::Skeleton;
typedef ::ompl::base::SO2StateSpace::StateType SO2State;
typedef ::ompl::base::RealVectorStateSpace::StateType RealVectorState;
// Update joint values.
for (size_t idof = 0; idof < dofs_.size(); ++idof) {
double value;
if (is_circular_[idof]) {
value = (*state)[idof]->as<SO2State>()->value;
} else {
value = (*state)[idof]->as<RealVectorState>()->values[0];
}
dofs_[idof]->setPosition(value);
}
// Compute forward kinematics.
for (Skeleton *skeleton : skeletons_) {
skeleton->computeForwardKinematics(true, false, false);
}
}
bool DARTGeometricStateSpace::IsInCollision()
{
return collision_detector_->detectCollision(false, false);
}
bool DARTGeometricStateSpace::IsDOFCircular(DegreeOfFreedom const *dof)
{
// TODO: How do we tell if a DOF is circular?
return false;
}
// ---
class DARTGeometricStateValidityChecker : ::ompl::base::StateValidityChecker {
public:
typedef ::ompl::base::State State;
DARTGeometricStateValidityChecker(
::ompl::base::SpaceInformation *space_info);
DARTGeometricStateValidityChecker(
::ompl::base::SpaceInformationPtr const &space_info);
virtual bool isValid(State const *state) const;
virtual double clearance(State const *state) const;
virtual double clearance(State const *state, State *validState,
bool &validStateAvailable) const;
private:
DARTGeometricStateSpace *state_space_;
};
DARTGeometricStateValidityChecker::DARTGeometricStateValidityChecker(
::ompl::base::SpaceInformation *space_info)
: ::ompl::base::StateValidityChecker(space_info)
//, state_space_(space_info->getStateSpace()->as<DARTGeometricStateSpace>())
{
}
DARTGeometricStateValidityChecker::DARTGeometricStateValidityChecker(
::ompl::base::SpaceInformationPtr const &space_info)
: ::ompl::base::StateValidityChecker(space_info)
//, state_space_(space_info->getStateSpace()->as<DARTGeometricStateSpace>())
{
}
bool DARTGeometricStateValidityChecker::isValid(State const *state) const
{
typedef DARTGeometricStateSpace::StateType DARTState;
state_space_->ApplyState(state->as<DARTState>());
return !state_space_->IsInCollision();
}
// ---
<commit_msg>Tweaks to OMPL.<commit_after>#include <vector>
#include <boost/make_shared.hpp>
#include <boost/unordered_set.hpp>
#include <boost/container/vector.hpp>
#include <dart/collision/collision.h>
#include <dart/dynamics/dynamics.h>
#include <ompl/base/StateSpace.h>
#include <ompl/base/SpaceInformation.h>
#include <ompl/base/StateValidityChecker.h>
#include <ompl/base/spaces/RealVectorStateSpace.h>
#include <ompl/base/spaces/SO2StateSpace.h>
using ::dart::dynamics::DegreeOfFreedom;
using ::ompl::base::StateSpacePtr;
class DARTGeometricStateSpace;
typedef boost::shared_ptr<DARTGeometricStateSpace> DARTGeometricStateSpacePtr;
class DARTGeometricStateSpace : public ::ompl::base::CompoundStateSpace {
public:
DARTGeometricStateSpace(
::std::vector<DegreeOfFreedom *> const &dofs,
::std::vector<double> const &weights,
::dart::collision::CollisionDetector *collision_detector);
void ApplyState(StateType const *state);
bool IsInCollision();
private:
::std::vector<DegreeOfFreedom *> dofs_;
::boost::container::vector<bool> is_circular_;
::boost::unordered_set<::dart::dynamics::Skeleton *> skeletons_;
::dart::collision::CollisionDetector *collision_detector_;
static bool IsDOFCircular(DegreeOfFreedom const *dof);
};
DARTGeometricStateSpace::DARTGeometricStateSpace(
std::vector<DegreeOfFreedom *> const &dofs,
std::vector<double> const &weights,
::dart::collision::CollisionDetector *collision_detector)
: dofs_(dofs)
, is_circular_(dofs.size())
, collision_detector_(collision_detector)
{
using ::boost::make_shared;
using ::ompl::base::RealVectorStateSpace;
using ::ompl::base::SO2StateSpace;
BOOST_ASSERT(dofs.size() == weights.size());
for (size_t idof = 0; idof < dofs.size(); ++idof) {
DegreeOfFreedom *dof = dofs[idof];
double const &weight = weights[idof];
// Construct a one-dimensional state space for each DOF. Add them, in
// the same order as "dofs", to this CompoundStateSpace.
bool &is_circular = is_circular_[idof];
is_circular = IsDOFCircular(dof);
if (is_circular) {
addSubspace(make_shared<SO2StateSpace>(), weight);
} else {
auto const state_space = make_shared<RealVectorStateSpace>(1);
state_space->setName(dof->getName());
state_space->setBounds(
dof->getPositionLowerLimit(),
dof->getPositionUpperLimit()
);
addSubspace(state_space, weight);
}
// Build a list of all Skeleton's influenced by these joints.
skeletons_.insert(dof->getSkeleton());
}
}
void DARTGeometricStateSpace::ApplyState(StateType const *state)
{
using ::dart::dynamics::Skeleton;
typedef ::ompl::base::SO2StateSpace::StateType SO2State;
typedef ::ompl::base::RealVectorStateSpace::StateType RealVectorState;
// Update joint values.
for (size_t idof = 0; idof < dofs_.size(); ++idof) {
double value;
if (is_circular_[idof]) {
value = (*state)[idof]->as<SO2State>()->value;
} else {
value = (*state)[idof]->as<RealVectorState>()->values[0];
}
dofs_[idof]->setPosition(value);
}
// Compute forward kinematics.
for (Skeleton *skeleton : skeletons_) {
skeleton->computeForwardKinematics(true, false, false);
}
}
bool DARTGeometricStateSpace::IsInCollision()
{
// TODO: We should only collision check the BodyNodes that are related to
// this state space.
return collision_detector_->detectCollision(false, false);
}
bool DARTGeometricStateSpace::IsDOFCircular(DegreeOfFreedom const *dof)
{
// TODO: How do we tell if a DOF is circular?
return false;
}
// ---
class DARTGeometricStateValidityChecker : public ::ompl::base::StateValidityChecker {
public:
DARTGeometricStateValidityChecker(
::ompl::base::SpaceInformation *space_info);
DARTGeometricStateValidityChecker(
::ompl::base::SpaceInformationPtr const &space_info);
virtual bool isValid(::ompl::base::State const *state) const;
private:
DARTGeometricStateSpace *state_space_;
};
DARTGeometricStateValidityChecker::DARTGeometricStateValidityChecker(
::ompl::base::SpaceInformation *space_info)
: ::ompl::base::StateValidityChecker(space_info)
, state_space_(space_info->getStateSpace()->as<DARTGeometricStateSpace>())
{
}
DARTGeometricStateValidityChecker::DARTGeometricStateValidityChecker(
::ompl::base::SpaceInformationPtr const &space_info)
: ::ompl::base::StateValidityChecker(space_info)
, state_space_(space_info->getStateSpace()->as<DARTGeometricStateSpace>())
{
}
bool DARTGeometricStateValidityChecker::isValid(
::ompl::base::State const *state) const
{
typedef DARTGeometricStateSpace::StateType DARTState;
state_space_->ApplyState(state->as<DARTState>());
return !state_space_->IsInCollision();
}
// ---
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2013 Plenluno All rights reserved.
#include <libnode/path.h>
#include <libj/symbol.h>
#include <libj/string_buffer.h>
#ifdef LIBJ_PF_WINDOWS
#include <libj/platform/windows.h>
#else
#include <unistd.h>
#endif
#include <assert.h>
namespace libj {
namespace node {
namespace path {
String::CPtr normalize(String::CPtr path) {
LIBJ_STATIC_SYMBOL_DEF(symCurrent, ".");
LIBJ_STATIC_SYMBOL_DEF(symParent, "..");
if (!path) return String::create();
Boolean absolute = false;
Boolean endsWithSep = false;
JsArray::Ptr dirs = JsArray::create();
Size len = path->length();
for (Size i = 0; i < len;) {
Size idx = path->indexOf('/', i);
if (idx == 0) {
absolute = true;
} else if (idx != i) {
String::CPtr dir;
if (idx == NO_POS) {
dir = path->substring(i);
} else {
dir = path->substring(i, idx);
}
if (dir->compareTo(symParent) == 0) {
Size numDirs = dirs->size();
if (numDirs > 0 &&
dirs->get(numDirs - 1).compareTo(symParent) != 0) {
dirs->remove(numDirs - 1);
} else {
dirs->add(dir);
}
} else if (dir->compareTo(symCurrent) != 0) {
dirs->add(dir);
}
}
if (idx == NO_POS) {
endsWithSep = false;
i = len;
} else {
endsWithSep = true;
i = idx + 1;
}
}
StringBuffer::Ptr normal = StringBuffer::create();
if (absolute)
normal->append(sep());
Size numDirs = dirs->size();
for (Size i = 0; i < numDirs; i++) {
if (i) normal->append(sep());
normal->append(dirs->get(i));
}
if (numDirs > 0 && endsWithSep)
normal->append(sep());
if (normal->length() == 0) {
return symCurrent;
} else {
return normal->toString();
}
}
String::CPtr join(JsArray::CPtr paths) {
LIBJ_STATIC_SYMBOL_DEF(symCurrent, ".");
if (!paths) return symCurrent;
StringBuffer::Ptr joined = StringBuffer::create();
Size len = paths->length();
Boolean first = true;
for (Size i = 0; i < len; i++) {
String::CPtr path = toCPtr<String>(paths->get(i));
if (path) {
if (first) {
first = false;
} else {
joined->append(sep());
}
joined->append(path);
}
}
return normalize(joined->toString());
}
static String::CPtr getCwd() {
const Size kMax = 8192;
char dir[kMax];
getcwd(dir, kMax);
return String::create(dir);
}
String::CPtr resolve(JsArray::CPtr paths) {
if (!paths) return getCwd();
StringBuffer::Ptr resolved = StringBuffer::create();
resolved->append(getCwd());
Size len = paths->length();
for (Size i = 0; i < len; i++) {
String::CPtr path = toCPtr<String>(paths->get(i));
if (path) {
if (path->startsWith(sep())) {
resolved = StringBuffer::create();
} else {
resolved->append(sep());
}
resolved->append(path);
}
}
return normalize(resolved->toString());
}
String::CPtr relative(String::CPtr from, String::CPtr to) {
// TODO(plenluno): implement
return String::create();
}
String::CPtr dirname(String::CPtr path) {
LIBJ_STATIC_SYMBOL_DEF(symCurrent, ".");
if (!path) return symCurrent;
String::CPtr base = basename(path);
Size baseLen = base->length();
Size pathLen = path->length();
if (baseLen == pathLen) {
return symCurrent;
} else {
Size sepPos = pathLen - baseLen - 1;
assert(path->charAt(sepPos) == '/');
if (sepPos) {
return path->substring(0, sepPos);
} else { // path[0] is '/'
return sep();
}
}
}
String::CPtr basename(String::CPtr path) {
LIBJ_STATIC_CONST_STRING_DEF(strDoubleSep, sep()->concat(sep()));
if (!path) return String::create();
if (path->compareTo(sep()) == 0) return String::create();
if (path->compareTo(strDoubleSep) == 0) return String::create();
Size lastIndex;
Size len = path->length();
if (path->endsWith(sep())) {
Size from = len - sep()->length() - 1;
lastIndex = path->lastIndexOf(sep(), from);
} else {
lastIndex = path->lastIndexOf(sep());
}
String::CPtr base;
if (lastIndex == NO_POS) {
base = path;
} else {
base = path->substring(lastIndex + 1);
}
return base;
}
String::CPtr extname(String::CPtr path) {
if (!path) return String::create();
String::CPtr base = basename(path);
if (base->endsWith(sep())) return String::create();
Size lastIndex = NO_POS;
if (base->length() > 1)
lastIndex = base->lastIndexOf('.');
String::CPtr ext;
if (lastIndex == NO_POS) {
ext = String::create();
} else {
ext = base->substring(lastIndex);
}
return ext;
}
String::CPtr sep() {
LIBJ_STATIC_SYMBOL_DEF(symSep, "/");
return symSep;
}
} // namespace path
} // namespace node
} // namespace libj
<commit_msg>fix a build error<commit_after>// Copyright (c) 2012-2013 Plenluno All rights reserved.
#include <libnode/path.h>
#include <libj/symbol.h>
#include <libj/string_buffer.h>
#ifdef LIBJ_PF_WINDOWS
#include <libj/platform/windows.h>
#else
#include <unistd.h>
#endif
#include <assert.h>
namespace libj {
namespace node {
namespace path {
String::CPtr normalize(String::CPtr path) {
LIBJ_STATIC_SYMBOL_DEF(symCurrent, ".");
LIBJ_STATIC_SYMBOL_DEF(symParent, "..");
if (!path) return String::create();
Boolean absolute = false;
Boolean endsWithSep = false;
JsArray::Ptr dirs = JsArray::create();
Size len = path->length();
for (Size i = 0; i < len;) {
Size idx = path->indexOf('/', i);
if (idx == 0) {
absolute = true;
} else if (idx != i) {
String::CPtr dir;
if (idx == NO_POS) {
dir = path->substring(i);
} else {
dir = path->substring(i, idx);
}
if (dir->compareTo(symParent) == 0) {
Size numDirs = dirs->size();
if (numDirs > 0 &&
dirs->get(numDirs - 1).compareTo(symParent) != 0) {
dirs->remove(numDirs - 1);
} else {
dirs->add(dir);
}
} else if (dir->compareTo(symCurrent) != 0) {
dirs->add(dir);
}
}
if (idx == NO_POS) {
endsWithSep = false;
i = len;
} else {
endsWithSep = true;
i = idx + 1;
}
}
StringBuffer::Ptr normal = StringBuffer::create();
if (absolute)
normal->append(sep());
Size numDirs = dirs->size();
for (Size i = 0; i < numDirs; i++) {
if (i) normal->append(sep());
normal->append(dirs->get(i));
}
if (numDirs > 0 && endsWithSep)
normal->append(sep());
if (normal->length() == 0) {
return symCurrent;
} else {
return normal->toString();
}
}
String::CPtr join(JsArray::CPtr paths) {
LIBJ_STATIC_SYMBOL_DEF(symCurrent, ".");
if (!paths) return symCurrent;
StringBuffer::Ptr joined = StringBuffer::create();
Size len = paths->length();
Boolean first = true;
for (Size i = 0; i < len; i++) {
String::CPtr path = toCPtr<String>(paths->get(i));
if (path) {
if (first) {
first = false;
} else {
joined->append(sep());
}
joined->append(path);
}
}
return normalize(joined->toString());
}
static String::CPtr getCwd() {
const Size kMax = 8192;
char dir[kMax];
getcwd(dir, kMax);
return String::create(dir);
}
String::CPtr resolve(JsArray::CPtr paths) {
if (!paths) return getCwd();
StringBuffer::Ptr resolved = StringBuffer::create();
resolved->append(getCwd());
Size len = paths->length();
for (Size i = 0; i < len; i++) {
String::CPtr path = toCPtr<String>(paths->get(i));
if (path) {
if (path->startsWith(sep())) {
resolved = StringBuffer::create();
} else {
resolved->append(sep());
}
resolved->append(path);
}
}
return normalize(resolved->toString());
}
String::CPtr relative(String::CPtr from, String::CPtr to) {
// TODO(plenluno): implement
return String::create();
}
String::CPtr dirname(String::CPtr path) {
LIBJ_STATIC_SYMBOL_DEF(symCurrent, ".");
if (!path) return symCurrent;
String::CPtr base = basename(path);
Size baseLen = base->length();
Size pathLen = path->length();
if (baseLen == pathLen) {
return symCurrent;
} else {
Size sepPos = pathLen - baseLen - 1;
assert(path->charAt(sepPos) == '/');
if (sepPos) {
return path->substring(0, sepPos);
} else { // path[0] is '/'
return sep();
}
}
}
String::CPtr basename(String::CPtr path) {
LIBJ_STATIC_CONST_STRING_DEF(strDoubleSep, "//");
if (!path) return String::create();
if (path->compareTo(sep()) == 0) return String::create();
if (path->compareTo(strDoubleSep) == 0) return String::create();
Size lastIndex;
Size len = path->length();
if (path->endsWith(sep())) {
Size from = len - sep()->length() - 1;
lastIndex = path->lastIndexOf(sep(), from);
} else {
lastIndex = path->lastIndexOf(sep());
}
String::CPtr base;
if (lastIndex == NO_POS) {
base = path;
} else {
base = path->substring(lastIndex + 1);
}
return base;
}
String::CPtr extname(String::CPtr path) {
if (!path) return String::create();
String::CPtr base = basename(path);
if (base->endsWith(sep())) return String::create();
Size lastIndex = NO_POS;
if (base->length() > 1)
lastIndex = base->lastIndexOf('.');
String::CPtr ext;
if (lastIndex == NO_POS) {
ext = String::create();
} else {
ext = base->substring(lastIndex);
}
return ext;
}
String::CPtr sep() {
LIBJ_STATIC_SYMBOL_DEF(symSep, "/");
return symSep;
}
} // namespace path
} // namespace node
} // namespace libj
<|endoftext|> |
<commit_before>/**
* \file perft.cc
* \author Jason Fernandez
* \date 11/10/2022
*/
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <memory.h>
#include <stdexcept>
#include <string>
#include <thread>
#include "argparse/argparse.hpp"
#include "superstring/superstring.h"
#include "chess/command_dispatcher.h"
#include "chess/position.h"
#include "chess/movegen.h"
#include "chess/stdio_channel.h"
/**
* @brief PERFormance Test
*/
class Perft final {
public:
/**
* @brief Constructor
*
* @param channel Channel to listen for user commands
*/
explicit Perft(std::shared_ptr<chess::InputStreamChannel> channel)
: dispatcher_(),
input_channel_(channel),
max_depth_(0),
position_() {
dispatcher_.RegisterCommand(
"divide",
std::bind(&Perft::HandleCommandDivide, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"help",
std::bind(&Perft::HandleCommandHelp, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"move",
std::bind(&Perft::HandleCommandMove, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"perft",
std::bind(&Perft::HandleCommandPerft, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"position",
std::bind(&Perft::HandleCommandPosition, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"quit",
std::bind(&Perft::HandleCommandQuit, this,
std::placeholders::_1));
input_channel_->emit_ =
std::bind(&chess::CommandDispatcher::HandleCommand,
&dispatcher_,
std::placeholders::_1);
position_.Reset();
}
private:
/**
* @brief Handle the "divide" command
*
* @param args Arguments to this command
*
* @return True on success
*/
bool HandleCommandDivide(const std::vector<std::string>& args) {
if (!args.empty()) {
std::size_t parsed_depth, nodes;
try {
parsed_depth = std::stoul(args[0]);
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return false;
}
const auto start = std::chrono::steady_clock::now();
if (position_.ToMove() == chess::Player::kWhite) {
nodes = Divide<chess::Player::kWhite>(&position_, parsed_depth);
} else {
nodes = Divide<chess::Player::kBlack>(&position_, parsed_depth);
}
const auto stop = std::chrono::steady_clock::now();
const std::size_t ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
stop - start).count();
std::cout << "Nodes=" << nodes << " Time=" << ms
<< "ms" << std::endl;
return true;
} else {
std::cout << "usage: divide <depth>" << std::endl;
return false;
}
}
/**
* @brief Handle the "help" command
*
* @return True on success
*/
bool HandleCommandHelp(const std::vector<std::string>& ) {
return true;
}
/**
* @brief Handle the "move" command
*
* @param args Arguments to this command
*
* @return True on success
*/
bool HandleCommandMove(const std::vector<std::string>& args) {
return true;
}
/**
* @brief Handle the "perft" command
*
* @param args Arguments to this command
*
* @return True on success
*/
bool HandleCommandPerft(const std::vector<std::string>& args) {
if (!args.empty()) {
std::size_t parsed_depth, nodes;
try {
parsed_depth = std::stoul(args[0]);
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return false;
}
max_depth_ = parsed_depth;
const auto start = std::chrono::steady_clock::now();
if (position_.ToMove() == chess::Player::kWhite) {
nodes = Trace<chess::Player::kWhite>(&position_, 0);
} else {
nodes = Trace<chess::Player::kBlack>(&position_, 0);
}
const auto stop = std::chrono::steady_clock::now();
const std::size_t ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
stop - start).count();
std::cout << "Nodes=" << nodes << " Time=" << ms
<< "ms" << std::endl;
return true;
} else {
std::cout << "usage: perft <depth>" << std::endl;
return false;
}
}
/**
* @brief Handle the "position" command
*
* @param args Arguments to this command
*
* @return True on success
*/
bool HandleCommandPosition(const std::vector<std::string>& args) {
const std::string fen =
jfern::superstring::build(" ", args.begin(), args.end());
const chess::Position::FenError error = position_.Reset(fen);
if (error != chess::Position::FenError::kSuccess) {
std::cout << "Rejected: " << chess::Position::ErrorToString(error)
<< std::endl;
return false;
}
return true;
}
/**
* @brief Handle the "quit" command
*
* @return True on success
*/
bool HandleCommandQuit(const std::vector<std::string>& ) {
input_channel_->Close();
return true;
}
/**
* Run divide() on the specified player
*
* @param pos The root position
* @param depth Maximum recursive depth, in plies
*
* @return The total node count
*/
template <chess::Player P>
std::size_t Divide(chess::Position* pos, std::size_t depth) {
max_depth_ = depth;
std::size_t total_nodes = 0;
std::uint32_t moves[chess::kMaxMoves];
const std::size_t n_moves = !pos->InCheck<P>() ?
chess::GenerateLegalMoves<P>(*pos, moves) :
chess::GenerateCheckEvasions<P>(*pos, moves);
for (std::size_t i = 0; i < n_moves; i++) {
const std::uint32_t move = moves[i];
pos->MakeMove<P>(move, 0);
const std::uint64_t nodes =
Trace<chess::util::opponent<P>()>(pos, 1);
pos->UnMakeMove<P>(move, 0);
// Display the size of this subtree
const chess::Square orig = chess::util::ExtractFrom(move);
const chess::Square dest = chess::util::ExtractTo(move);
const chess::Piece promoted = chess::util::ExtractPromoted(move);
std::cout << chess::kSquareStr[orig]
<< chess::kSquareStr[dest];
if (promoted != chess::Piece::EMPTY) {
std::cout << "=" << chess::util::PieceToChar(promoted);
}
std::cout << " " << nodes << std::endl;
total_nodes += nodes;
}
std::cout << "Moves=" << n_moves << std::endl;
return total_nodes;
}
/**
* @brief Internal recursive routine
*
* @tparam P The player whose turn it is at this depth
*
* @param pos The current position
* @param depth The current depth
*/
template <chess::Player P>
std::size_t Trace(chess::Position* pos, std::uint32_t depth) {
std::uint32_t moves[chess::kMaxMoves];
if (depth >= max_depth_) return 1u;
const std::size_t n_moves = !pos->InCheck<P>() ?
chess::GenerateLegalMoves<P>(*pos, moves) :
chess::GenerateCheckEvasions<P>(*pos, moves);
if (depth+1 >= max_depth_) return n_moves;
std::uint64_t nodes = 0;
for (std::size_t i = 0; i < n_moves; i++) {
const std::uint32_t move = moves[i];
pos->MakeMove<P>(move, depth);
nodes += Trace<chess::util::opponent<P>()>(pos, depth+1);
pos->UnMakeMove<P>(move, depth);
}
return nodes;
}
/**
* Handles user commands
*/
chess::CommandDispatcher dispatcher_;
/**
* Channel to listen for commands
*/
std::shared_ptr<chess::InputStreamChannel>
input_channel_;
/**
* Maximum recursive trace depth
*/
std::size_t max_depth_;
/**
* The position on which to run perft calculations
*/
chess::Position position_;
};
/**
* @brief Parse command line and run this program
*
* @param parser Command line parser
*
* @return True on success
*/
bool go(const argparse::ArgumentParser& parser) {
auto channel = std::make_shared<chess::StdinChannel>(true);
Perft perft(channel);
while (!channel->IsClosed()) channel->Poll();
return true;
}
int main(int argc, char** argv) {
argparse::ArgumentParser parser("perft");
try {
parser.parse_args(argc, argv);
} catch (const std::runtime_error& error) {
std::cerr << error.what() << std::endl;
std::cerr << parser;
return EXIT_FAILURE;
}
return go(parser) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>Remove unused argument<commit_after>/**
* \file perft.cc
* \author Jason Fernandez
* \date 11/10/2022
*/
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <memory.h>
#include <stdexcept>
#include <string>
#include <thread>
#include "argparse/argparse.hpp"
#include "superstring/superstring.h"
#include "chess/command_dispatcher.h"
#include "chess/position.h"
#include "chess/movegen.h"
#include "chess/stdio_channel.h"
/**
* @brief PERFormance Test
*/
class Perft final {
public:
/**
* @brief Constructor
*
* @param channel Channel to listen for user commands
*/
explicit Perft(std::shared_ptr<chess::InputStreamChannel> channel)
: dispatcher_(),
input_channel_(channel),
max_depth_(0),
position_() {
dispatcher_.RegisterCommand(
"divide",
std::bind(&Perft::HandleCommandDivide, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"help",
std::bind(&Perft::HandleCommandHelp, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"move",
std::bind(&Perft::HandleCommandMove, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"perft",
std::bind(&Perft::HandleCommandPerft, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"position",
std::bind(&Perft::HandleCommandPosition, this,
std::placeholders::_1));
dispatcher_.RegisterCommand(
"quit",
std::bind(&Perft::HandleCommandQuit, this,
std::placeholders::_1));
input_channel_->emit_ =
std::bind(&chess::CommandDispatcher::HandleCommand,
&dispatcher_,
std::placeholders::_1);
position_.Reset();
}
private:
/**
* @brief Handle the "divide" command
*
* @param args Arguments to this command
*
* @return True on success
*/
bool HandleCommandDivide(const std::vector<std::string>& args) {
if (!args.empty()) {
std::size_t parsed_depth, nodes;
try {
parsed_depth = std::stoul(args[0]);
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return false;
}
const auto start = std::chrono::steady_clock::now();
if (position_.ToMove() == chess::Player::kWhite) {
nodes = Divide<chess::Player::kWhite>(&position_, parsed_depth);
} else {
nodes = Divide<chess::Player::kBlack>(&position_, parsed_depth);
}
const auto stop = std::chrono::steady_clock::now();
const std::size_t ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
stop - start).count();
std::cout << "Nodes=" << nodes << " Time=" << ms
<< "ms" << std::endl;
return true;
} else {
std::cout << "usage: divide <depth>" << std::endl;
return false;
}
}
/**
* @brief Handle the "help" command
*
* @return True on success
*/
bool HandleCommandHelp(const std::vector<std::string>& ) {
return true;
}
/**
* @brief Handle the "move" command
*
* @param args Arguments to this command
*
* @return True on success
*/
bool HandleCommandMove(const std::vector<std::string>& args) {
return true;
}
/**
* @brief Handle the "perft" command
*
* @param args Arguments to this command
*
* @return True on success
*/
bool HandleCommandPerft(const std::vector<std::string>& args) {
if (!args.empty()) {
std::size_t parsed_depth, nodes;
try {
parsed_depth = std::stoul(args[0]);
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return false;
}
max_depth_ = parsed_depth;
const auto start = std::chrono::steady_clock::now();
if (position_.ToMove() == chess::Player::kWhite) {
nodes = Trace<chess::Player::kWhite>(&position_, 0);
} else {
nodes = Trace<chess::Player::kBlack>(&position_, 0);
}
const auto stop = std::chrono::steady_clock::now();
const std::size_t ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
stop - start).count();
std::cout << "Nodes=" << nodes << " Time=" << ms
<< "ms" << std::endl;
return true;
} else {
std::cout << "usage: perft <depth>" << std::endl;
return false;
}
}
/**
* @brief Handle the "position" command
*
* @param args Arguments to this command
*
* @return True on success
*/
bool HandleCommandPosition(const std::vector<std::string>& args) {
const std::string fen =
jfern::superstring::build(" ", args.begin(), args.end());
const chess::Position::FenError error = position_.Reset(fen);
if (error != chess::Position::FenError::kSuccess) {
std::cout << "Rejected: " << chess::Position::ErrorToString(error)
<< std::endl;
return false;
}
return true;
}
/**
* @brief Handle the "quit" command
*
* @return True on success
*/
bool HandleCommandQuit(const std::vector<std::string>& ) {
input_channel_->Close();
return true;
}
/**
* Run divide() on the specified player
*
* @param pos The root position
* @param depth Maximum recursive depth, in plies
*
* @return The total node count
*/
template <chess::Player P>
std::size_t Divide(chess::Position* pos, std::size_t depth) {
max_depth_ = depth;
std::size_t total_nodes = 0;
std::uint32_t moves[chess::kMaxMoves];
const std::size_t n_moves = !pos->InCheck<P>() ?
chess::GenerateLegalMoves<P>(*pos, moves) :
chess::GenerateCheckEvasions<P>(*pos, moves);
for (std::size_t i = 0; i < n_moves; i++) {
const std::uint32_t move = moves[i];
pos->MakeMove<P>(move, 0);
const std::uint64_t nodes =
Trace<chess::util::opponent<P>()>(pos, 1);
pos->UnMakeMove<P>(move, 0);
// Display the size of this subtree
const chess::Square orig = chess::util::ExtractFrom(move);
const chess::Square dest = chess::util::ExtractTo(move);
const chess::Piece promoted = chess::util::ExtractPromoted(move);
std::cout << chess::kSquareStr[orig]
<< chess::kSquareStr[dest];
if (promoted != chess::Piece::EMPTY) {
std::cout << "=" << chess::util::PieceToChar(promoted);
}
std::cout << " " << nodes << std::endl;
total_nodes += nodes;
}
std::cout << "Moves=" << n_moves << std::endl;
return total_nodes;
}
/**
* @brief Internal recursive routine
*
* @tparam P The player whose turn it is at this depth
*
* @param pos The current position
* @param depth The current depth
*/
template <chess::Player P>
std::size_t Trace(chess::Position* pos, std::uint32_t depth) {
std::uint32_t moves[chess::kMaxMoves];
if (depth >= max_depth_) return 1u;
const std::size_t n_moves = !pos->InCheck<P>() ?
chess::GenerateLegalMoves<P>(*pos, moves) :
chess::GenerateCheckEvasions<P>(*pos, moves);
if (depth+1 >= max_depth_) return n_moves;
std::uint64_t nodes = 0;
for (std::size_t i = 0; i < n_moves; i++) {
const std::uint32_t move = moves[i];
pos->MakeMove<P>(move, depth);
nodes += Trace<chess::util::opponent<P>()>(pos, depth+1);
pos->UnMakeMove<P>(move, depth);
}
return nodes;
}
/**
* Handles user commands
*/
chess::CommandDispatcher dispatcher_;
/**
* Channel to listen for commands
*/
std::shared_ptr<chess::InputStreamChannel>
input_channel_;
/**
* Maximum recursive trace depth
*/
std::size_t max_depth_;
/**
* The position on which to run perft calculations
*/
chess::Position position_;
};
/**
* @brief Parse command line and run this program
*
* @return True on success
*/
bool go(const argparse::ArgumentParser& ) {
auto channel = std::make_shared<chess::StdinChannel>(true);
Perft perft(channel);
while (!channel->IsClosed()) channel->Poll();
return true;
}
int main(int argc, char** argv) {
argparse::ArgumentParser parser("perft");
try {
parser.parse_args(argc, argv);
} catch (const std::runtime_error& error) {
std::cerr << error.what() << std::endl;
std::cerr << parser;
return EXIT_FAILURE;
}
return go(parser) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include <fstream>
#include "openmc/plot.h"
#include "openmc/constants.h"
#include "openmc/settings.h"
#include "openmc/error.h"
#include "openmc/particle.h"
#include "openmc/geometry.h"
#include "openmc/cell.h"
#include "openmc/material.h"
#include "openmc/string_functions.h"
#include "openmc/mesh.h"
namespace openmc {
const int RED = 1;
const int GREEN = 2;
const int BLUE = 3;
const int WHITE[3] = {255, 255, 255};
const int NULLRGB[3] = {0, 0, 0};
//===============================================================================
// RUN_PLOT controls the logic for making one or many plots
//===============================================================================
int openmc_plot_geometry() {
int err;
for (auto i : n_plots) {
ObjectPlot* pl = plots[i];
std::stringstream ss;
ss << "Processing plot " << pl->id << ": "
<< pl->path_plot << "...";
write_message(ss.str(), 5);
if (PLOT_TYPE::SLICE == pl->type) {
// create 2D image
// create_ppm(pl);
continue;
} else if (PLOT_TYPE::VOXEL == pl->type) {
// create voxel file for 3D viewing
// create_voxel(pl);
continue;
}
}
return 0;
}
//===============================================================================
// CREATE_PPM creates an image based on user input from a plots.xml <plot>
// specification in the portable pixmap format (PPM)
//===============================================================================
void create_ppm(ObjectPlot* pl) {
int width = pl->pixels[0];
int height = pl->pixels[1];
double in_pixel = (pl->width[0])/double(width);
double out_pixel = (pl->width[1])/double(height);
std::vector< std::vector< std::vector<int> > > data;
data.resize(width);
for (auto & i : data) {
i.resize(height);
for (auto & j : i) {
j.resize(3);
}
}
int in_i, out_i;
double xyz[3];
if (PLOT_BASIS::XY == pl->basis) {
in_i = 0;
out_i = 1;
xyz[0] = pl->origin[0] - pl->width[0] / TWO;
xyz[1] = pl->origin[1] + pl->width[1] / TWO;
xyz[2] = pl->origin[2];
} else if (PLOT_BASIS::XZ == pl->basis) {
in_i = 0;
out_i = 2;
xyz[0] = pl->origin[0] - pl->width[0] / TWO;
xyz[1] = pl->origin[1];
xyz[2] = pl->origin[2] + pl->width[1] / TWO;
} else if (PLOT_BASIS::YZ == pl->basis) {
in_i = 1;
out_i = 2;
xyz[0] = pl->origin[0];
xyz[1] = pl->origin[1] - pl->width[0] / TWO;
xyz[2] = pl->origin[2] + pl->width[1] / TWO;
}
double dir[3] = {HALF, HALF, HALF};
Particle *p = new Particle();
p->initialize();
std::copy(xyz, xyz+3, p->coord[0].xyz);
std::copy(dir, dir+3, p->coord[0].uvw);
p->coord[0].universe = openmc_root_universe;
// local variables
int rgb[3];
int id;
for (int y = 0; y < height; y++) {
p->coord[0].xyz[out_i] = xyz[out_i] - out_pixel*(y);
for (int x = 0; x < width; x++) {
p->coord[0].xyz[in_i] = xyz[in_i] + in_pixel*(x);
position_rgb(p, pl, rgb, id);
data[x][y][0] = rgb[0];
data[x][y][1] = rgb[1];
data[x][y][2] = rgb[2];
}
}
if (pl->index_meshlines_mesh >= 0) { draw_mesh_lines(pl, data); }
output_ppm(pl, data);
}
//===============================================================================
// POSITION_RGB computes the red/green/blue values for a given plot with the
// current particle's position
//===============================================================================
void position_rgb(Particle* p, ObjectPlot* pl, int rgb[3], int &id) {
bool found_cell;
p->n_coord = 1;
found_cell = find_cell(p, 0);
int j = p->n_coord - 1;
if (settings::check_overlaps) { check_cell_overlap(p); }
// Set coordinate level if specified
if (pl->level >= 0) {j = pl->level + 1;}
Cell* c;
if (!found_cell) {
// If no cell, revert to default color
std::copy(pl->not_found.rgb,
pl->not_found.rgb + 3,
rgb);
id = -1;
} else {
if (PLOT_COLOR_BY::MATS == pl->color_by) {
// Assign color based on material
c = cells[p->coord[j].cell];
if (c->type_ == FILL_UNIVERSE) {
// If we stopped on a middle universe level, treat as if not found
std::copy(pl->not_found.rgb,
pl->not_found.rgb + 3,
rgb);
id = -1;
} else if (p->material == MATERIAL_VOID) {
// By default, color void cells white
std::copy(WHITE, WHITE+3, rgb);
id = -1;
} else {
std::copy(pl->colors[p->material - 1].rgb,
pl->colors[p->material - 1].rgb + 3,
rgb);
id = materials[p->material - 1]->id;
}
} else if (PLOT_COLOR_BY::CELLS == pl->color_by) {
// Assign color based on cell
std::copy(pl->colors[p->coord[j].cell].rgb,
pl->colors[p->coord[j].cell].rgb + 3,
rgb);
id = cells[p->coord[j].cell]->id_;
} else {
std::copy(NULLRGB, NULLRGB+3, rgb);
id = -1;
}
} // endif found_cell
}
//===============================================================================
// OUTPUT_PPM writes out a previously generated image to a PPM file
//===============================================================================
void output_ppm(ObjectPlot* pl,
const std::vector< std::vector< std::vector<int> > > &data)
{
// Open PPM file for writing
std::string fname = std::string(pl->path_plot);
fname = strtrim(fname);
std::ofstream of;
of.open(fname);
// Write header
of << "P6" << std::endl;
of << pl->pixels[0] << " " << pl->pixels[1] << std::endl;
of << "255" << std::endl;
of.close();
of.open(fname, std::ios::binary | std::ios::app);
// Write color for each pixel
for (int y = 0; y < pl->pixels[1]; y++) {
for (int x = 0; x < pl->pixels[0]; x++) {
std::vector<int> rgb = data[x][y];
of.write((char*)&rgb[0], 1);
of.write((char*)&rgb[1], 1);
of.write((char*)&rgb[2], 1);
}
}
// Close file
of.close();
}
//===============================================================================
// DRAW_MESH_LINES draws mesh line boundaries on an image
//===============================================================================
void draw_mesh_lines(ObjectPlot *pl,
std::vector< std::vector< std::vector<int> > > &data) {
std::vector<int> rgb; rgb.resize(3);
rgb[0] = pl->meshlines_color.rgb[0];
rgb[1] = pl->meshlines_color.rgb[1];
rgb[2] = pl->meshlines_color.rgb[2];
int outer, inner;
switch(pl->basis){
case PLOT_BASIS::XY :
outer = 0;
inner = 1;
break;
case PLOT_BASIS::XZ :
outer = 0;
inner = 2;
break;
case PLOT_BASIS::YZ :
outer = 1;
inner = 2;
break;
}
double xyz_ll_plot[3], xyz_ur_plot[3];
std::copy((double*)&pl->origin, (double*)&pl->origin + 3, xyz_ll_plot);
std::copy((double*)&pl->origin, (double*)&pl->origin + 3, xyz_ur_plot);
xyz_ll_plot[outer] = pl->origin[outer] - pl->width[0] / TWO;
xyz_ll_plot[inner] = pl->origin[inner] - pl->width[1] / TWO;
xyz_ur_plot[outer] = pl->origin[outer] + pl->width[0] / TWO;
xyz_ur_plot[inner] = pl->origin[inner] + pl->width[1] / TWO;
int width[3];
width[0] = xyz_ur_plot[0] - xyz_ll_plot[0];
width[1] = xyz_ur_plot[1] - xyz_ll_plot[1];
width[2] = xyz_ur_plot[2] - xyz_ll_plot[2];
auto &m = meshes[pl->index_meshlines_mesh];
int ijk_ll[3], ijk_ur[3];
bool in_mesh;
m->get_indices(Position(xyz_ll_plot), &(ijk_ll[0]), &in_mesh);
m->get_indices(Position(xyz_ur_plot), &(ijk_ur[0]), &in_mesh);
double frac;
int outrange[3], inrange[3];
double xyz_ll[3], xyz_ur[3];
// sweep through all meshbins on this plane and draw borders
for (int i = ijk_ll[outer]; i < ijk_ur[outer]; i++) {
for (int j = ijk_ll[inner]; j < ijk_ur[inner]; j++) {
// check if we're in the mesh for this ijk
if (i > 0 && i <= m->shape_[outer] && j >0 && j <= m->shape_[inner] ) {
// get xyz's of lower left and upper right of this mesh cell
xyz_ll[outer] = m->lower_left_[outer] + m->width_[outer] * (i - 1);
xyz_ll[inner] = m->lower_left_[inner] + m->width_[inner] * (j - 1);
xyz_ur[outer] = m->lower_left_[outer] + m->width_[outer] * i;
xyz_ur[inner] = m->lower_left_[inner] + m->width_[inner] * j;
// map the xyz ranges to pixel ranges
frac = (xyz_ll[outer] - xyz_ll_plot[outer]) / width[outer];
outrange[0] = int(frac * double(pl->pixels[0]));
frac = (xyz_ur[outer] - xyz_ll_plot[outer]) / width[outer];
outrange[1] = int(frac * double(pl->pixels[0]));
frac = (xyz_ur[inner] - xyz_ll_plot[inner]) / width[inner];
inrange[0] = int((ONE - frac) * (double)pl->pixels[1]);
frac = (xyz_ll[inner] - xyz_ll_plot[inner]) / width[inner];
inrange[1] = int((ONE - frac) * (double)pl->pixels[1]);
// draw lines
for (int out_ = outrange[0]; out_ < outrange[1]; out_++) {
for (int plus = 0; plus < pl->meshlines_width; plus++) {
data[out_ + 1][inrange[0] + plus + 1] = rgb;
data[out_ + 1][inrange[1] + plus + 1] = rgb;
data[out_ + 1][inrange[0] - plus + 1] = rgb;
data[out_ + 1][inrange[1] - plus + 1] = rgb;
}
}
for (int in_ = inrange[0]; in_ < inrange[1]; in_++) {
for (int plus = 0; plus < pl->meshlines_width; plus++) {
data[outrange[0] + plus + 1][in_ + 1] = rgb;
data[outrange[1] + plus + 1][in_ + 1] = rgb;
data[outrange[0] - plus + 1][in_ + 1] = rgb;
data[outrange[1] - plus + 1][in_ + 1] = rgb;
}
}
} // end if(in mesh)
}
} // end outer loops
}
void
voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
hid_t* memspace)
{
// Create dataspace/dataset for voxel data
*dspace = H5Screate_simple(3, dims, nullptr);
*dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
H5P_DEFAULT, H5P_DEFAULT);
// Create dataspace for a slice of the voxel
hsize_t dims_slice[2] {dims[1], dims[2]};
*memspace = H5Screate_simple(2, dims_slice, nullptr);
// Select hyperslab in dataspace
hsize_t start[3] {0, 0, 0};
hsize_t count[3] {1, dims[1], dims[2]};
H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
}
void
voxel_write_slice(int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf)
{
hssize_t offset[3] {x - 1, 0, 0};
H5Soffset_simple(dspace, offset);
H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf);
}
void
voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
{
H5Dclose(dset);
H5Sclose(dspace);
H5Sclose(memspace);
}
} // namespace openmc
<commit_msg>Making mesh lines some minimal width.<commit_after>#include <fstream>
#include "openmc/plot.h"
#include "openmc/constants.h"
#include "openmc/settings.h"
#include "openmc/error.h"
#include "openmc/particle.h"
#include "openmc/geometry.h"
#include "openmc/cell.h"
#include "openmc/material.h"
#include "openmc/string_functions.h"
#include "openmc/mesh.h"
namespace openmc {
const int RED = 1;
const int GREEN = 2;
const int BLUE = 3;
const int WHITE[3] = {255, 255, 255};
const int NULLRGB[3] = {0, 0, 0};
//===============================================================================
// RUN_PLOT controls the logic for making one or many plots
//===============================================================================
int openmc_plot_geometry() {
int err;
for (auto i : n_plots) {
ObjectPlot* pl = plots[i];
std::stringstream ss;
ss << "Processing plot " << pl->id << ": "
<< pl->path_plot << "...";
write_message(ss.str(), 5);
if (PLOT_TYPE::SLICE == pl->type) {
// create 2D image
// create_ppm(pl);
continue;
} else if (PLOT_TYPE::VOXEL == pl->type) {
// create voxel file for 3D viewing
// create_voxel(pl);
continue;
}
}
return 0;
}
//===============================================================================
// CREATE_PPM creates an image based on user input from a plots.xml <plot>
// specification in the portable pixmap format (PPM)
//===============================================================================
void create_ppm(ObjectPlot* pl) {
int width = pl->pixels[0];
int height = pl->pixels[1];
double in_pixel = (pl->width[0])/double(width);
double out_pixel = (pl->width[1])/double(height);
std::vector< std::vector< std::vector<int> > > data;
data.resize(width);
for (auto & i : data) {
i.resize(height);
for (auto & j : i) {
j.resize(3);
}
}
int in_i, out_i;
double xyz[3];
if (PLOT_BASIS::XY == pl->basis) {
in_i = 0;
out_i = 1;
xyz[0] = pl->origin[0] - pl->width[0] / TWO;
xyz[1] = pl->origin[1] + pl->width[1] / TWO;
xyz[2] = pl->origin[2];
} else if (PLOT_BASIS::XZ == pl->basis) {
in_i = 0;
out_i = 2;
xyz[0] = pl->origin[0] - pl->width[0] / TWO;
xyz[1] = pl->origin[1];
xyz[2] = pl->origin[2] + pl->width[1] / TWO;
} else if (PLOT_BASIS::YZ == pl->basis) {
in_i = 1;
out_i = 2;
xyz[0] = pl->origin[0];
xyz[1] = pl->origin[1] - pl->width[0] / TWO;
xyz[2] = pl->origin[2] + pl->width[1] / TWO;
}
double dir[3] = {HALF, HALF, HALF};
Particle *p = new Particle();
p->initialize();
std::copy(xyz, xyz+3, p->coord[0].xyz);
std::copy(dir, dir+3, p->coord[0].uvw);
p->coord[0].universe = openmc_root_universe;
// local variables
int rgb[3];
int id;
for (int y = 0; y < height; y++) {
p->coord[0].xyz[out_i] = xyz[out_i] - out_pixel*(y);
for (int x = 0; x < width; x++) {
p->coord[0].xyz[in_i] = xyz[in_i] + in_pixel*(x);
position_rgb(p, pl, rgb, id);
data[x][y][0] = rgb[0];
data[x][y][1] = rgb[1];
data[x][y][2] = rgb[2];
}
}
if (pl->index_meshlines_mesh >= 0) { draw_mesh_lines(pl, data); }
output_ppm(pl, data);
}
//===============================================================================
// POSITION_RGB computes the red/green/blue values for a given plot with the
// current particle's position
//===============================================================================
void position_rgb(Particle* p, ObjectPlot* pl, int rgb[3], int &id) {
bool found_cell;
p->n_coord = 1;
found_cell = find_cell(p, 0);
int j = p->n_coord - 1;
if (settings::check_overlaps) { check_cell_overlap(p); }
// Set coordinate level if specified
if (pl->level >= 0) {j = pl->level + 1;}
Cell* c;
if (!found_cell) {
// If no cell, revert to default color
std::copy(pl->not_found.rgb,
pl->not_found.rgb + 3,
rgb);
id = -1;
} else {
if (PLOT_COLOR_BY::MATS == pl->color_by) {
// Assign color based on material
c = cells[p->coord[j].cell];
if (c->type_ == FILL_UNIVERSE) {
// If we stopped on a middle universe level, treat as if not found
std::copy(pl->not_found.rgb,
pl->not_found.rgb + 3,
rgb);
id = -1;
} else if (p->material == MATERIAL_VOID) {
// By default, color void cells white
std::copy(WHITE, WHITE+3, rgb);
id = -1;
} else {
std::copy(pl->colors[p->material - 1].rgb,
pl->colors[p->material - 1].rgb + 3,
rgb);
id = materials[p->material - 1]->id;
}
} else if (PLOT_COLOR_BY::CELLS == pl->color_by) {
// Assign color based on cell
std::copy(pl->colors[p->coord[j].cell].rgb,
pl->colors[p->coord[j].cell].rgb + 3,
rgb);
id = cells[p->coord[j].cell]->id_;
} else {
std::copy(NULLRGB, NULLRGB+3, rgb);
id = -1;
}
} // endif found_cell
}
//===============================================================================
// OUTPUT_PPM writes out a previously generated image to a PPM file
//===============================================================================
void output_ppm(ObjectPlot* pl,
const std::vector< std::vector< std::vector<int> > > &data)
{
// Open PPM file for writing
std::string fname = std::string(pl->path_plot);
fname = strtrim(fname);
std::ofstream of;
of.open(fname);
// Write header
of << "P6" << std::endl;
of << pl->pixels[0] << " " << pl->pixels[1] << std::endl;
of << "255" << std::endl;
of.close();
of.open(fname, std::ios::binary | std::ios::app);
// Write color for each pixel
for (int y = 0; y < pl->pixels[1]; y++) {
for (int x = 0; x < pl->pixels[0]; x++) {
std::vector<int> rgb = data[x][y];
of.write((char*)&rgb[0], 1);
of.write((char*)&rgb[1], 1);
of.write((char*)&rgb[2], 1);
}
}
// Close file
of.close();
}
//===============================================================================
// DRAW_MESH_LINES draws mesh line boundaries on an image
//===============================================================================
void draw_mesh_lines(ObjectPlot *pl,
std::vector< std::vector< std::vector<int> > > &data) {
std::vector<int> rgb; rgb.resize(3);
rgb[0] = pl->meshlines_color.rgb[0];
rgb[1] = pl->meshlines_color.rgb[1];
rgb[2] = pl->meshlines_color.rgb[2];
int outer, inner;
switch(pl->basis){
case PLOT_BASIS::XY :
outer = 0;
inner = 1;
break;
case PLOT_BASIS::XZ :
outer = 0;
inner = 2;
break;
case PLOT_BASIS::YZ :
outer = 1;
inner = 2;
break;
}
double xyz_ll_plot[3], xyz_ur_plot[3];
std::copy((double*)&pl->origin, (double*)&pl->origin + 3, xyz_ll_plot);
std::copy((double*)&pl->origin, (double*)&pl->origin + 3, xyz_ur_plot);
xyz_ll_plot[outer] = pl->origin[outer] - pl->width[0] / TWO;
xyz_ll_plot[inner] = pl->origin[inner] - pl->width[1] / TWO;
xyz_ur_plot[outer] = pl->origin[outer] + pl->width[0] / TWO;
xyz_ur_plot[inner] = pl->origin[inner] + pl->width[1] / TWO;
int width[3];
width[0] = xyz_ur_plot[0] - xyz_ll_plot[0];
width[1] = xyz_ur_plot[1] - xyz_ll_plot[1];
width[2] = xyz_ur_plot[2] - xyz_ll_plot[2];
auto &m = meshes[pl->index_meshlines_mesh];
int ijk_ll[3], ijk_ur[3];
bool in_mesh;
m->get_indices(Position(xyz_ll_plot), &(ijk_ll[0]), &in_mesh);
m->get_indices(Position(xyz_ur_plot), &(ijk_ur[0]), &in_mesh);
double frac;
int outrange[3], inrange[3];
double xyz_ll[3], xyz_ur[3];
// sweep through all meshbins on this plane and draw borders
for (int i = ijk_ll[outer]; i < ijk_ur[outer]; i++) {
for (int j = ijk_ll[inner]; j < ijk_ur[inner]; j++) {
// check if we're in the mesh for this ijk
if (i > 0 && i <= m->shape_[outer] && j >0 && j <= m->shape_[inner] ) {
// get xyz's of lower left and upper right of this mesh cell
xyz_ll[outer] = m->lower_left_[outer] + m->width_[outer] * (i - 1);
xyz_ll[inner] = m->lower_left_[inner] + m->width_[inner] * (j - 1);
xyz_ur[outer] = m->lower_left_[outer] + m->width_[outer] * i;
xyz_ur[inner] = m->lower_left_[inner] + m->width_[inner] * j;
// map the xyz ranges to pixel ranges
frac = (xyz_ll[outer] - xyz_ll_plot[outer]) / width[outer];
outrange[0] = int(frac * double(pl->pixels[0]));
frac = (xyz_ur[outer] - xyz_ll_plot[outer]) / width[outer];
outrange[1] = int(frac * double(pl->pixels[0]));
frac = (xyz_ur[inner] - xyz_ll_plot[inner]) / width[inner];
inrange[0] = int((ONE - frac) * (double)pl->pixels[1]);
frac = (xyz_ll[inner] - xyz_ll_plot[inner]) / width[inner];
inrange[1] = int((ONE - frac) * (double)pl->pixels[1]);
// draw lines
for (int out_ = outrange[0]; out_ < outrange[1]; out_++) {
for (int plus = 0; plus <= pl->meshlines_width; plus++) {
data[out_ + 1][inrange[0] + plus + 1] = rgb;
data[out_ + 1][inrange[1] + plus + 1] = rgb;
data[out_ + 1][inrange[0] - plus + 1] = rgb;
data[out_ + 1][inrange[1] - plus + 1] = rgb;
}
}
for (int in_ = inrange[0]; in_ < inrange[1]; in_++) {
for (int plus = 0; plus <= pl->meshlines_width; plus++) {
data[outrange[0] + plus + 1][in_ + 1] = rgb;
data[outrange[1] + plus + 1][in_ + 1] = rgb;
data[outrange[0] - plus + 1][in_ + 1] = rgb;
data[outrange[1] - plus + 1][in_ + 1] = rgb;
}
}
} // end if(in mesh)
}
} // end outer loops
}
void
voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
hid_t* memspace)
{
// Create dataspace/dataset for voxel data
*dspace = H5Screate_simple(3, dims, nullptr);
*dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
H5P_DEFAULT, H5P_DEFAULT);
// Create dataspace for a slice of the voxel
hsize_t dims_slice[2] {dims[1], dims[2]};
*memspace = H5Screate_simple(2, dims_slice, nullptr);
// Select hyperslab in dataspace
hsize_t start[3] {0, 0, 0};
hsize_t count[3] {1, dims[1], dims[2]};
H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
}
void
voxel_write_slice(int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf)
{
hssize_t offset[3] {x - 1, 0, 0};
H5Soffset_simple(dspace, offset);
H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf);
}
void
voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
{
H5Dclose(dset);
H5Sclose(dspace);
H5Sclose(memspace);
}
} // namespace openmc
<|endoftext|> |
<commit_before>#include <iostream>
#include <3pp/mpc/mpc.h>
int main(int argc, char **argv)
{
if (argc <= 1) {
std::cout << "Usage: " << argv[0] << "file\n";
return 1;
}
mpc_parser_t* Comment = mpc_new("comment");
mpc_parser_t* Indent = mpc_new("indent");
mpc_parser_t* Newline = mpc_new("newline");
mpc_parser_t* WhiteSpace = mpc_new("ws");
mpc_parser_t* OptionalWhiteSpace = mpc_new("ows");
mpc_parser_t* Number = mpc_new("number");
mpc_parser_t* Operator = mpc_new("operator");
mpc_parser_t* Expr = mpc_new("expr");
mpc_parser_t* Body = mpc_new("body");
mpc_parser_t* Identifier = mpc_new("identifier");
mpc_parser_t* TypeIdent = mpc_new("typeident");
mpc_parser_t* Import = mpc_new("import");
mpc_parser_t* MethodRet = mpc_new("methodret");
mpc_parser_t* MethodDef = mpc_new("methoddef");
mpc_parser_t* ParamDef = mpc_new("paramdef");
mpc_parser_t* String = mpc_new("string");
mpc_parser_t* Args = mpc_new("args");
mpc_parser_t* Lexp = mpc_new("lexp");
mpc_parser_t* Factor = mpc_new("factor");
mpc_parser_t* MethodCall = mpc_new("methodcall");
mpc_parser_t* MapIndex = mpc_new("mapindex");
mpc_parser_t* ListItem = mpc_new("listitem");
mpc_parser_t* MapItem = mpc_new("mapitem");
mpc_parser_t* TupleMap = mpc_new("tuplemap");
mpc_parser_t* MapItems = mpc_new("mapitems");
mpc_parser_t* ListItems = mpc_new("listitems");
mpc_parser_t* List = mpc_new("list");
mpc_parser_t* Namespacedef = mpc_new("namespacedef");
mpc_parser_t* MatchCase = mpc_new("matchcase");
mpc_parser_t* Match = mpc_new("match");
mpc_parser_t* Assignment = mpc_new("assignment");
mpc_parser_t* Stmt = mpc_new("stmt");
mpc_parser_t* Term = mpc_new("term");
mpc_parser_t* Const = mpc_new("const");
mpc_parser_t* Pure = mpc_new("pure");
mpc_parser_t* NolangPure = mpc_new("nolangpure");
mpc_err_t* err = mpca_lang(MPCA_LANG_WHITESPACE_SENSITIVE,
"comment : /(#|\\/\\/)[^\\r\\n]*/ | /\\/\\*[^\\*]*(\\*[^\\/][^\\*]*)*\\*\\// ;"
"indent : \" \" ;"
"newline : '\\n' | '\\0';"
"ws : /[' ']+/ ;"
"ows : /[' '\\t\\n]*/ ;"
"identifier : /[A-Za-z_][A-Za-z0-9_-]*/ ;"
"typeident : <identifier> <ows> ':' <ows> <identifier> ;"
"number : /[0-9]+/ ;"
"string : /\"(\\\\.|[^\"])*\"/ | /\'(\\\\.|[^\'])*\'/ ; "
"operator : '+' | '-' | '*' | '/' ;"
"import : \"import\" <ws> <identifier> <newline>;"
"const : \"const\" <assignment> <newline>;"
"methodret : <ows> ':' <ows> <identifier> ;"
"methoddef : (<pure> <ws>)? <identifier> <ows> <args>? <methodret>? <ows> \"=>\" (<newline>|<ws>) <body> ;"
"paramdef : <typeident>? <ows> (',' <ows> <typeident>)*; "
"args : '(' <paramdef>? ')'; "
"factor : <namespacedef> | '(' <lexp> ')' | <number> | <string> | <identifier>; "
"term : <factor> <ows> (('*' | '/' | \"div\" | \"mod\" | \"rem\") <ows> <factor>)*;"
"lexp : <term> <ows> (('+' | '-') <ows> <term>)* ; "
"expr : <list> | <lexp>;"
"methodcall : '(' (<expr> <ows> (',' <ows> <expr>)*)? ')';"
"mapindex : '[' <expr> ']';"
"listitem : <expr>;"
"mapitem : <string> <ows> ':' <ows> <expr> ;"
"tuplemap : '(' <string> <ows> ',' <ows> <lexp> ')';"
"mapitems : (<tuplemap> | <mapitem>) <ows> (',' <ows> (<tuplemap> | <mapitem>)) *;"
"listitems : <listitem> (<ows> ',' <ows> <listitem>) *;"
"list : '[' <ows> (<mapitems> | <listitems>)? <ows> ']';"
"namespacedef : <identifier> ('.' <identifier>)* (<methodcall> | <mapindex>)?;"
"assignment : <typeident> <ws> '=' <ws> <expr>;"
"matchcase : <indent>+ (<identifier> | <number> | <string> | '?') <ows> ':' <ows> <stmt> <newline>;"
"match : \"match\" <ws> (<identifier> | <namespacedef>) <ows> \"=>\" <ows> (<newline>|<ws>) <matchcase>+;"
"stmt : <match> | <assignment> | <namespacedef> | <list> | <expr>;"
"body : ((<indent>+ (<stmt> | <comment>))? <newline>)* ;"
"pure : \"pure\" ;"
"nolangpure : /^/ (<import> | <const> | <comment> | <methoddef> | <newline>)* /$/ ;"
,
Comment, Indent, Newline, WhiteSpace, OptionalWhiteSpace,
Identifier, TypeIdent,
Number, String,
Operator,
Import, Const,
MethodRet, MethodDef, ParamDef, Args,
Factor, Term, Lexp,
Expr, MethodCall,
MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,
Namespacedef,
Assignment, MatchCase, Match, Stmt,
Body, Pure,
NolangPure, NULL);
// expr : <number> | '(' <operator> <expr>+ ')' ;
if (err != NULL) {
mpc_err_print(err);
mpc_err_delete(err);
exit(1);
}
mpc_result_t r;
if (mpc_parse_contents(argv[1], NolangPure, &r)) {
/* On Success Print the AST */
mpc_ast_print(static_cast<mpc_ast_t*>(r.output));
mpc_ast_delete(static_cast<mpc_ast_t*>(r.output));
} else {
/* Otherwise Print the Error */
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
mpc_cleanup(15,
Identifier, TypeIdent, Number, String,
Operator,
MethodDef, ParamDef, Args,
Factor, Term, Lexp,
Expr, Body, Pure,
NolangPure);
return 0;
}
<commit_msg>Refactor<commit_after>#include <iostream>
#include <3pp/mpc/mpc.h>
int main(int argc, char **argv)
{
if (argc <= 1) {
std::cout << "Usage: " << argv[0] << "file\n";
return 1;
}
mpc_parser_t* Comment = mpc_new("comment");
mpc_parser_t* Indent = mpc_new("indent");
mpc_parser_t* Newline = mpc_new("newline");
mpc_parser_t* WhiteSpace = mpc_new("ws");
mpc_parser_t* OptionalWhiteSpace = mpc_new("ows");
mpc_parser_t* Number = mpc_new("number");
mpc_parser_t* Operator = mpc_new("operator");
mpc_parser_t* FactorOperator = mpc_new("factorop");
mpc_parser_t* TermOperator = mpc_new("termop");
mpc_parser_t* Expr = mpc_new("expr");
mpc_parser_t* Body = mpc_new("body");
mpc_parser_t* Identifier = mpc_new("identifier");
mpc_parser_t* TypeIdent = mpc_new("typeident");
mpc_parser_t* Import = mpc_new("import");
mpc_parser_t* MethodRet = mpc_new("methodret");
mpc_parser_t* MethodDef = mpc_new("methoddef");
mpc_parser_t* ParamDef = mpc_new("paramdef");
mpc_parser_t* String = mpc_new("string");
mpc_parser_t* Args = mpc_new("args");
mpc_parser_t* Lexp = mpc_new("lexp");
mpc_parser_t* Factor = mpc_new("factor");
mpc_parser_t* MethodCall = mpc_new("methodcall");
mpc_parser_t* MapIndex = mpc_new("mapindex");
mpc_parser_t* ListItem = mpc_new("listitem");
mpc_parser_t* MapItem = mpc_new("mapitem");
mpc_parser_t* TupleMap = mpc_new("tuplemap");
mpc_parser_t* MapItems = mpc_new("mapitems");
mpc_parser_t* ListItems = mpc_new("listitems");
mpc_parser_t* List = mpc_new("list");
mpc_parser_t* Namespacedef = mpc_new("namespacedef");
mpc_parser_t* MatchCase = mpc_new("matchcase");
mpc_parser_t* Match = mpc_new("match");
mpc_parser_t* Assignment = mpc_new("assignment");
mpc_parser_t* Stmt = mpc_new("stmt");
mpc_parser_t* Term = mpc_new("term");
mpc_parser_t* Const = mpc_new("const");
mpc_parser_t* Pure = mpc_new("pure");
mpc_parser_t* TopLevel = mpc_new("toplevel");
mpc_parser_t* NolangPure = mpc_new("nolangpure");
mpc_err_t* err = mpca_lang(MPCA_LANG_WHITESPACE_SENSITIVE,
"comment : /(#|\\/\\/)[^\\r\\n]*/"
" | /\\/\\*[^\\*]*(\\*[^\\/][^\\*]*)*\\*\\// ;"
"indent : ' ' ' '+ ;"
"newline : '\\n';"
"ws : /[' ']+/ ;"
"ows : /[' '\\t]*/ ;"
"identifier : /[A-Za-z_][A-Za-z0-9_-]*/ ;"
"typeident : <identifier> <ows> ':' <ows> <identifier> ;"
"number : /[0-9]+/ ;"
"string : /\"(\\\\.|[^\"])*\"/ "
" | /\'(\\\\.|[^\'])*\'/ ; "
"operator : '+' | '-' | '*' | '/' ;"
"factorop : '*'"
" | '/'"
" | \"div\""
" | \"mod\""
" | \"rem\";"
"termop : '+'"
" | '-';"
"import : \"import\" <ws> <identifier> <newline>;"
"const : \"const\" <ws> <assignment> <newline>;"
"methodret : <ows> ':' <ows> <identifier> ;"
"methoddef : (<pure> <ws>)? <identifier> <ows> <args>? <methodret>? <ows> \"=>\" (<newline>|<ws>) <body> ;"
"paramdef : <typeident>? <ows> (',' <ows> <typeident>)*; "
"args : '(' <paramdef>? ')'; "
"factor : <namespacedef>"
" | '(' <lexp> ')'"
" | <number>"
" | <string>"
" | <identifier>; "
"term : <factor> (<ows> <factorop> <ows> <factor>)*;"
"lexp : <term> (<ows> <termop> <ows> <term>)* ; "
"expr : <list>"
" | <lexp>;"
"methodcall : '(' (<expr> (',' <ows> <expr>)*)? ')';"
"mapindex : '[' <expr> ']';"
"listitem : <expr>;"
"mapitem : <string> <ows> ':' <ows> <expr> ;"
"tuplemap : '(' <string> <ows> ',' <ows> <lexp> ')';"
"mapitems : (<tuplemap> | <mapitem>) <ows> (',' <ows> (<tuplemap> | <mapitem>)) *;"
"listitems : <listitem> (<ows> ',' <ows> <listitem>) *;"
"list : '[' <ows> (<mapitems> | <listitems>)? <ows> ']' ;"
"namespacedef : <identifier> ('.' <identifier>)* (<methodcall> | <mapindex>)?;"
"assignment : <typeident> <ws> '=' <ws> <expr>;"
"matchcase : <indent> (<identifier> | <number> | <string> | '?') <ows> ':' <ows> <stmt>;"
//"match : \"match\" <ws> (<identifier> | <namespacedef>) <ows> \"=>\" <newline> <matchcase>+;"
"match : \"match\" <ws> <stmt> <ows> \"=>\" <newline> <matchcase>+;"
"stmt : <match>"
" | <assignment>"
" | <namespacedef>"
" | <list>"
" | <expr>"
" | <comment>;"
"body : ((<indent>+ <stmt>)? <newline>)* ;"
"pure : \"pure\" ;"
"toplevel : <import>"
" | <const>"
" | <comment>"
" | <methoddef>"
" | <newline>;"
"nolangpure : /^/ <toplevel>* /$/;"
,
Comment, Indent, Newline, WhiteSpace, OptionalWhiteSpace,
Identifier, TypeIdent,
Number, String,
Operator, FactorOperator, TermOperator,
Import, Const,
MethodRet, MethodDef, ParamDef, Args,
Factor, Term, Lexp,
Expr, MethodCall,
MapIndex, ListItem, MapItem, TupleMap, MapItems, ListItems, List,
Namespacedef,
Assignment, MatchCase, Match,
Stmt,
Body, Pure,
TopLevel, NolangPure, NULL);
// expr : <number> | '(' <operator> <expr>+ ')' ;
if (err != NULL) {
mpc_err_print(err);
mpc_err_delete(err);
exit(1);
}
mpc_result_t r;
if (mpc_parse_contents(argv[1], NolangPure, &r)) {
/* On Success Print the AST */
mpc_ast_print(static_cast<mpc_ast_t*>(r.output));
mpc_ast_delete(static_cast<mpc_ast_t*>(r.output));
} else {
/* Otherwise Print the Error */
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
mpc_cleanup(15,
Identifier, TypeIdent, Number, String,
Operator, FactorOperator, TermOperator,
MethodDef, ParamDef, Args,
Factor, Term, Lexp,
Expr, Body, Pure,
NolangPure);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive 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.
*
* cclive 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 "config.h"
#include <sstream>
#include <vector>
#include <iomanip>
#include <map>
#include <pcrecpp.h>
#include "except.h"
#include "log.h"
#include "opts.h"
#include "util.h"
#include "quvi.h"
QuviMgr::QuviMgr()
: quvi(NULL)
{
}
// Keeps -Weffc++ happy.
QuviMgr::QuviMgr(const QuviMgr&)
: quvi(NULL)
{
}
// Ditto.
QuviMgr&
QuviMgr::operator=(const QuviMgr&) {
return *this;
}
QuviMgr::~QuviMgr() {
quvi_close(&quvi);
}
static void
handle_error(QUVIcode rc) {
std::stringstream s;
s << "quvi: "
<< quvi_strerror(quvimgr.handle(),rc);
switch (rc) {
case QUVI_NOSUPPORT:
throw NoSupportException(s.str());
case QUVI_PCRE:
throw ParseException(s.str());
default:
break;
}
throw QuviException(s.str());
}
static int
status_callback(long param, void *data) {
quvi_word status = quvi_loword(param);
quvi_word type = quvi_hiword(param);
switch (status) {
case QUVIS_FETCH:
switch (type) {
default:
logmgr.cout()
<< "fetch "
<< static_cast<char *>(data)
<< " ...";
break;
case QUVIST_CONFIG:
logmgr.cout()
<< "fetch config ...";
break;
case QUVIST_PLAYLIST:
logmgr.cout()
<< "fetch playlist ...";
break;
case QUVIST_DONE:
logmgr.cout()
<< "done."
<< std::endl;
break;
}
break;
case QUVIS_VERIFY:
switch (type) {
default:
logmgr.cout()
<< "verify video link ...";
break;
case QUVIST_DONE:
logmgr.cout()
<< "done."
<< std::endl;
break;
}
break;
}
logmgr.cout() << std::flush;
return 0;
}
void
QuviMgr::init() {
QUVIcode rc = quvi_init(&quvi);
if (rc != QUVI_OK)
handle_error(rc);
quvi_setopt(quvi,
QUVIOPT_STATUSFUNCTION, status_callback);
}
quvi_t
QuviMgr::handle() const {
return quvi;
}
void
QuviMgr::curlHandle(CURL **curl) {
assert(curl != 0);
quvi_getinfo(quvi, QUVII_CURL, curl);
}
// QuviVideo
QuviVideo::QuviVideo()
: length (0),
pageLink (""),
id (""),
title (""),
link (""),
suffix (""),
contentType(""),
hostId (""),
initial (0),
filename ("")
{
}
QuviVideo::QuviVideo(const std::string& url)
: length (0),
pageLink (url),
id (""),
title (""),
link (""),
suffix (""),
contentType(""),
hostId (""),
initial (0),
filename ("")
{
}
QuviVideo::QuviVideo(const QuviVideo& o)
: length (o.length),
pageLink (o.pageLink),
id (o.id),
title (o.title),
link (o.link),
suffix (o.suffix),
contentType(o.contentType),
hostId (o.hostId),
initial (o.initial),
filename (o.filename)
{
}
QuviVideo&
QuviVideo::operator=(const QuviVideo& o) {
length = o.length;
pageLink= o.pageLink;
id = o.id;
title = o.title;
link = o.link;
suffix = o.suffix;
contentType = o.contentType;
hostId = o.hostId;
initial = o.initial;
filename= o.filename;
return *this;
}
QuviVideo::~QuviVideo() {
}
void
QuviVideo::parse(std::string url /*=""*/) {
if (url.empty())
url = pageLink;
assert(!url.empty());
const Options opts =
optsmgr.getOptions();
if (opts.format_given) {
quvi_setopt(quvimgr.handle(),
QUVIOPT_FORMAT, opts.format_arg);
}
CURL *curl = 0;
quvimgr.curlHandle(&curl);
assert(curl != 0);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,
opts.connect_timeout_arg);
curl_easy_setopt(curl, CURLOPT_TIMEOUT,
opts.connect_timeout_socks_arg);
quvi_video_t video;
QUVIcode rc =
quvi_parse(quvimgr.handle(),
const_cast<char*>(url.c_str()), &video);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 0L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L);
if (rc != QUVI_OK)
handle_error(rc);
quvi_getprop(video, QUVIP_LENGTH, &length);
#define _getprop(id,dst) \
do { quvi_getprop(video, id, &s); dst = s; } while (0)
char *s; // _getprop uses this.
_getprop(QUVIP_PAGELINK, pageLink);
_getprop(QUVIP_ID, id);
_getprop(QUVIP_TITLE, title);
_getprop(QUVIP_LINK, link);
_getprop(QUVIP_SUFFIX, suffix);
_getprop(QUVIP_CONTENTTYPE, contentType);
_getprop(QUVIP_HOSTID, hostId);
#undef _getstr
quvi_parse_close(&video);
formatOutputFilename();
}
static int video_num = 0;
void
QuviVideo::formatOutputFilename() {
const Options opts = optsmgr.getOptions();
if (!opts.output_video_given) {
std::stringstream b;
if (opts.number_videos_given) {
b << std::setw(4)
<< std::setfill('0')
<< ++video_num
<< "_";
}
customOutputFilenameFormatter(b);
filename = b.str();
typedef unsigned int _uint;
for (register _uint i=1;
i<INT_MAX && !opts.overwrite_given; ++i) {
initial = Util::fileExists(filename);
if (initial == 0)
break;
else if (initial >= length)
throw NothingToDoException();
else {
if (opts.continue_given)
break;
}
std::stringstream tmp;
tmp << b.str() << "." << i;
filename = tmp.str();
}
}
else {
initial = Util::fileExists(opts.output_video_arg);
if (initial >= length)
throw NothingToDoException();
if (opts.overwrite_given)
initial = 0;
filename = opts.output_video_arg;
}
if (!opts.continue_given)
initial = 0;
}
void
QuviVideo::customOutputFilenameFormatter(
std::stringstream& b)
{
const Options opts = optsmgr.getOptions();
std::string fmt = opts.filename_format_arg;
std::string _id = this->id;
Util::subStrReplace(_id, "-", "_");
std::string _title = title;
#ifdef _1_
// Convert predefined HTML character entities.
Util::fromHtmlEntities(_title);
#endif
// Apply --regexp.
if (opts.regexp_given)
applyTitleRegexp(_title);
// Remove leading and trailing whitespace.
pcrecpp::RE("^[\\s]+", pcrecpp::UTF8())
.Replace("", &_title);
pcrecpp::RE("\\s+$", pcrecpp::UTF8())
.Replace("", &_title);
// Replace format specifiers.
Util::subStrReplace(fmt, "%t", _title.empty() ? _id : _title);
Util::subStrReplace(fmt, "%i", _id);
Util::subStrReplace(fmt, "%h", hostId);
Util::subStrReplace(fmt, "%s", suffix);
b << fmt;
}
void
QuviVideo::applyTitleRegexp(std::string& src) {
const Options opts =
optsmgr.getOptions();
if (opts.find_all_given) {
pcrecpp::StringPiece sp(src);
pcrecpp::RE re(opts.regexp_arg, pcrecpp::UTF8());
src.clear();
std::string s;
while (re.FindAndConsume(&sp, &s))
src += s;
}
else {
std::string tmp = src;
src.clear();
pcrecpp::RE(opts.regexp_arg, pcrecpp::UTF8())
.PartialMatch(tmp, &src);
}
}
const double&
QuviVideo::getLength() const {
return length;
}
const std::string&
QuviVideo::getPageLink() const {
return pageLink;
}
const std::string&
QuviVideo::getId() const {
return id;
}
const std::string&
QuviVideo::getTitle() const {
return title;
}
const std::string&
QuviVideo::getLink() const {
return link;
}
const std::string&
QuviVideo::getSuffix() const {
return suffix;
}
const std::string&
QuviVideo::getContentType() const {
return contentType;
}
const std::string&
QuviVideo::getHostId() const {
return hostId;
}
const double&
QuviVideo::getInitial() const {
return initial;
}
const std::string&
QuviVideo::getFilename() const {
return filename;
}
void
QuviVideo::updateInitial() {
initial = Util::fileExists(filename);
if (initial >= length)
throw NothingToDoException();
}
<commit_msg>cleanup output file naming loop.<commit_after>/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive 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.
*
* cclive 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 "config.h"
#include <sstream>
#include <vector>
#include <iomanip>
#include <map>
#include <pcrecpp.h>
#include "except.h"
#include "log.h"
#include "opts.h"
#include "util.h"
#include "quvi.h"
QuviMgr::QuviMgr()
: quvi(NULL)
{
}
// Keeps -Weffc++ happy.
QuviMgr::QuviMgr(const QuviMgr&)
: quvi(NULL)
{
}
// Ditto.
QuviMgr&
QuviMgr::operator=(const QuviMgr&) {
return *this;
}
QuviMgr::~QuviMgr() {
quvi_close(&quvi);
}
static void
handle_error(QUVIcode rc) {
std::stringstream s;
s << "quvi: "
<< quvi_strerror(quvimgr.handle(),rc);
switch (rc) {
case QUVI_NOSUPPORT:
throw NoSupportException(s.str());
case QUVI_PCRE:
throw ParseException(s.str());
default:
break;
}
throw QuviException(s.str());
}
static int
status_callback(long param, void *data) {
quvi_word status = quvi_loword(param);
quvi_word type = quvi_hiword(param);
switch (status) {
case QUVIS_FETCH:
switch (type) {
default:
logmgr.cout()
<< "fetch "
<< static_cast<char *>(data)
<< " ...";
break;
case QUVIST_CONFIG:
logmgr.cout()
<< "fetch config ...";
break;
case QUVIST_PLAYLIST:
logmgr.cout()
<< "fetch playlist ...";
break;
case QUVIST_DONE:
logmgr.cout()
<< "done."
<< std::endl;
break;
}
break;
case QUVIS_VERIFY:
switch (type) {
default:
logmgr.cout()
<< "verify video link ...";
break;
case QUVIST_DONE:
logmgr.cout()
<< "done."
<< std::endl;
break;
}
break;
}
logmgr.cout() << std::flush;
return 0;
}
void
QuviMgr::init() {
QUVIcode rc = quvi_init(&quvi);
if (rc != QUVI_OK)
handle_error(rc);
quvi_setopt(quvi,
QUVIOPT_STATUSFUNCTION, status_callback);
}
quvi_t
QuviMgr::handle() const {
return quvi;
}
void
QuviMgr::curlHandle(CURL **curl) {
assert(curl != 0);
quvi_getinfo(quvi, QUVII_CURL, curl);
}
// QuviVideo
QuviVideo::QuviVideo()
: length (0),
pageLink (""),
id (""),
title (""),
link (""),
suffix (""),
contentType(""),
hostId (""),
initial (0),
filename ("")
{
}
QuviVideo::QuviVideo(const std::string& url)
: length (0),
pageLink (url),
id (""),
title (""),
link (""),
suffix (""),
contentType(""),
hostId (""),
initial (0),
filename ("")
{
}
QuviVideo::QuviVideo(const QuviVideo& o)
: length (o.length),
pageLink (o.pageLink),
id (o.id),
title (o.title),
link (o.link),
suffix (o.suffix),
contentType(o.contentType),
hostId (o.hostId),
initial (o.initial),
filename (o.filename)
{
}
QuviVideo&
QuviVideo::operator=(const QuviVideo& o) {
length = o.length;
pageLink= o.pageLink;
id = o.id;
title = o.title;
link = o.link;
suffix = o.suffix;
contentType = o.contentType;
hostId = o.hostId;
initial = o.initial;
filename= o.filename;
return *this;
}
QuviVideo::~QuviVideo() {
}
void
QuviVideo::parse(std::string url /*=""*/) {
if (url.empty())
url = pageLink;
assert(!url.empty());
const Options opts =
optsmgr.getOptions();
if (opts.format_given) {
quvi_setopt(quvimgr.handle(),
QUVIOPT_FORMAT, opts.format_arg);
}
CURL *curl = 0;
quvimgr.curlHandle(&curl);
assert(curl != 0);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,
opts.connect_timeout_arg);
curl_easy_setopt(curl, CURLOPT_TIMEOUT,
opts.connect_timeout_socks_arg);
quvi_video_t video;
QUVIcode rc =
quvi_parse(quvimgr.handle(),
const_cast<char*>(url.c_str()), &video);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 0L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L);
if (rc != QUVI_OK)
handle_error(rc);
quvi_getprop(video, QUVIP_LENGTH, &length);
#define _getprop(id,dst) \
do { quvi_getprop(video, id, &s); dst = s; } while (0)
char *s; // _getprop uses this.
_getprop(QUVIP_PAGELINK, pageLink);
_getprop(QUVIP_ID, id);
_getprop(QUVIP_TITLE, title);
_getprop(QUVIP_LINK, link);
_getprop(QUVIP_SUFFIX, suffix);
_getprop(QUVIP_CONTENTTYPE, contentType);
_getprop(QUVIP_HOSTID, hostId);
#undef _getstr
quvi_parse_close(&video);
formatOutputFilename();
}
static int video_num = 0;
void
QuviVideo::formatOutputFilename() {
const Options opts = optsmgr.getOptions();
if (!opts.output_video_given) {
std::stringstream b;
if (opts.number_videos_given) {
b << std::setw(4)
<< std::setfill('0')
<< ++video_num
<< "_";
}
customOutputFilenameFormatter(b);
filename = b.str();
if (!opts.overwrite_given) {
for (int i=1; i<INT_MAX; ++i) {
initial = Util::fileExists(filename);
if (initial == 0)
break;
else if (initial >= length)
throw NothingToDoException();
else {
if (opts.continue_given)
break;
}
std::stringstream tmp;
tmp << b.str() << "." << i;
filename = tmp.str();
}
}
}
else {
initial = Util::fileExists(opts.output_video_arg);
if (initial >= length)
throw NothingToDoException();
if (opts.overwrite_given)
initial = 0;
filename = opts.output_video_arg;
}
if (!opts.continue_given)
initial = 0;
}
void
QuviVideo::customOutputFilenameFormatter(
std::stringstream& b)
{
const Options opts = optsmgr.getOptions();
std::string fmt = opts.filename_format_arg;
std::string _id = this->id;
Util::subStrReplace(_id, "-", "_");
std::string _title = title;
#ifdef _1_
// Convert predefined HTML character entities.
Util::fromHtmlEntities(_title);
#endif
// Apply --regexp.
if (opts.regexp_given)
applyTitleRegexp(_title);
// Remove leading and trailing whitespace.
pcrecpp::RE("^[\\s]+", pcrecpp::UTF8())
.Replace("", &_title);
pcrecpp::RE("\\s+$", pcrecpp::UTF8())
.Replace("", &_title);
// Replace format specifiers.
Util::subStrReplace(fmt, "%t", _title.empty() ? _id : _title);
Util::subStrReplace(fmt, "%i", _id);
Util::subStrReplace(fmt, "%h", hostId);
Util::subStrReplace(fmt, "%s", suffix);
b << fmt;
}
void
QuviVideo::applyTitleRegexp(std::string& src) {
const Options opts =
optsmgr.getOptions();
if (opts.find_all_given) {
pcrecpp::StringPiece sp(src);
pcrecpp::RE re(opts.regexp_arg, pcrecpp::UTF8());
src.clear();
std::string s;
while (re.FindAndConsume(&sp, &s))
src += s;
}
else {
std::string tmp = src;
src.clear();
pcrecpp::RE(opts.regexp_arg, pcrecpp::UTF8())
.PartialMatch(tmp, &src);
}
}
const double&
QuviVideo::getLength() const {
return length;
}
const std::string&
QuviVideo::getPageLink() const {
return pageLink;
}
const std::string&
QuviVideo::getId() const {
return id;
}
const std::string&
QuviVideo::getTitle() const {
return title;
}
const std::string&
QuviVideo::getLink() const {
return link;
}
const std::string&
QuviVideo::getSuffix() const {
return suffix;
}
const std::string&
QuviVideo::getContentType() const {
return contentType;
}
const std::string&
QuviVideo::getHostId() const {
return hostId;
}
const double&
QuviVideo::getInitial() const {
return initial;
}
const std::string&
QuviVideo::getFilename() const {
return filename;
}
void
QuviVideo::updateInitial() {
initial = Util::fileExists(filename);
if (initial >= length)
throw NothingToDoException();
}
<|endoftext|> |
<commit_before>#include <xcb/xcb.h>
#include <cstdio>
#include <ev++.h>
#include <cstring>
#include <memory>
#include <wordexp.h>
#include <basedir.h>
#include <basedir_fs.h>
#include <getopt.h>
#include "rwte/config.h"
#include "rwte/renderer.h"
#include "rwte/rwte.h"
#include "rwte/logging.h"
#include "rwte/sigwatcher.h"
#include "rwte/term.h"
#include "rwte/tty.h"
#include "rwte/window.h"
#include "lua/config.h"
#include "lua/state.h"
#include "lua/logging.h"
#include "lua/term.h"
#include "lua/window.h"
#include "rwte/version.h"
// globals
Window window;
Options options;
Rwte rwte;
std::unique_ptr<Term> g_term;
std::unique_ptr<Tty> g_tty;
lua_State * g_L = NULL;
#define LOGGER() (logging::get("rwte"))
#define MIN(a, b) ((a) < (b)? (a) : (b))
#define MAX(a, b) ((a) < (b)? (b) : (a))
// default values to use if we don't have
// a default value in config
static const float DEFAULT_BLINK_RATE = 0.6;
Options::Options() :
cmd(0),
title("rwte"),
noalt(false)
{ }
Rwte::Rwte() :
m_lua(std::make_shared<lua::State>())
{
m_lua->openlibs();
m_child.set<Rwte,&Rwte::childcb>(this);
m_flush.set<Rwte,&Rwte::flushcb>(this);
m_blink.set<Rwte,&Rwte::blinkcb>(this);
}
void Rwte::resize(uint16_t width, uint16_t height)
{
if (width == 0)
width = window.width();
if (height == 0)
height = window.height();
if (window.width() != width || window.height() != height)
{
window.resize(width, height);
g_term->resize(window.cols(), window.rows());
if (g_tty)
g_tty->resize();
}
}
void Rwte::watch_child(pid_t pid)
{
LOGGER()->debug("watching child {}", pid);
m_child.start(pid);
}
void Rwte::refresh()
{
if (!m_flush.is_active())
m_flush.start(1.0/60.0);
}
void Rwte::start_blink()
{
if (!m_blink.is_active())
{
float rate = lua::config::get_float(
"blink_rate", DEFAULT_BLINK_RATE);
m_blink.start(rate, rate);
}
else
{
// reset the timer if it's already active
// (so we don't blink until idle)
m_blink.stop();
m_blink.start();
}
}
void Rwte::stop_blink()
{
if (m_blink.is_active())
m_blink.stop();
}
void Rwte::childcb(ev::child &w, int)
{
if (!WIFEXITED(w.rstatus) || WEXITSTATUS(w.rstatus))
LOGGER()->warn("child finished with error {}", w.rstatus);
else
LOGGER()->info("child exited");
w.loop.break_loop(ev::ALL);
}
void Rwte::flushcb(ev::timer &, int)
{
window.draw();
}
void Rwte::blinkcb(ev::timer &, int)
{
g_term->blink();
}
static void add_to_search_path(lua::State *L, const std::vector<std::string>& searchpaths, bool for_lua)
{
if (L->type(-1) != LUA_TSTRING)
{
LOGGER()->warn("package.path is not a string");
return;
}
for (auto& searchpath : searchpaths)
{
L->pushstring(fmt::format(";{}{}", searchpath,
for_lua? "/?.lua" : "/?.so"));
if (for_lua)
{
L->pushstring(fmt::format(";{}/?/init.lua", searchpath,
for_lua? "/?.lua" : "/?.so"));
// pushed two, concat them with string already on stack
L->concat(3);
}
else
{
// pushed one, concat it with string already on stack
L->concat(2);
}
}
// add rwte lib path
if (for_lua)
{
L->pushstring(
";" RWTE_LIB_PATH "/?.lua"
";" RWTE_LIB_PATH "/?/init.lua");
L->concat(2);
}
else
{
L->pushstring(";" RWTE_LIB_PATH "/?.so");
L->concat(2);
}
}
static bool run_file(lua::State *L, const char *path)
{
if (L->loadfile(path) || L->pcall(0, 0, 0))
{
LOGGER()->error("lua config error: {}", L->tostring(-1));
L->pop(1);
return false;
}
else
return true;
}
static bool run_config(lua::State *L, xdgHandle *xdg, const char *confpatharg)
{
// try specified path first
if (confpatharg)
{
if (run_file(L, confpatharg))
return true;
else
LOGGER()->warn("unable to run specified config ({}); "
"running config.lua", confpatharg);
}
// try paths from xdgConfigFind
char *paths = xdgConfigFind("rwte/config.lua", xdg);
// paths from xdgConfigFind are null-terminated, with
// empty string at the end (double null)
char *tmp = paths;
while (*tmp)
{
if (run_file(L, tmp))
return true;
tmp += std::strlen(tmp) + 1;
}
std::free(paths);
// finally try CONFIG_FILE
// use wordexp to expand possible ~ in the path
wordexp_t exp_result;
wordexp(CONFIG_FILE, &exp_result, 0);
bool result = run_file(L, exp_result.we_wordv[0]);
wordfree(&exp_result);
return result;
}
static void exit_help(int code)
{
fprintf((code == EXIT_SUCCESS) ? stdout : stderr,
"Usage: rwte [options] [-- args]\n"
" -c, --config FILE overrides config file\n"
" -a, --noalt disables alt screens\n"
" -f, --font FONT pango font string\n"
" -g, --geometry GEOM window geometry; colsxrows, e.g.,\n"
" \"80x24\" (the default)\n"
" -t, --title TITLE window title; defaults to rwte\n"
" -n, --name NAME window name; defaults to $TERM\n"
" -w, --winclass CLASS overrides window class\n"
" -e, --exe COMMAND command to execute instead of shell;\n"
" if specified, any arguments to the\n"
" command may be specified after a \"--\"\n"
" -o, --out OUT writes all io to this file;\n"
" \"-\" means stdout\n"
" -l, --line LINE use a tty line instead of creating a\n"
" new pty; LINE is expected to be the\n"
" device\n"
" -h, --help show help\n"
" -b, --bench run config and exit\n"
" -v, --version show version and exit\n");
exit(code);
}
static void exit_version()
{
fprintf(stdout, "rwte %s\n", version_string());
exit(EXIT_SUCCESS);
}
static bool parse_geometry(const char *g, int *cols, int *rows)
{
// parse cols
char *end = nullptr;
int c = strtol(g, &end, 10);
if (c > 0 && *end == 'x')
{
// move past x
end++;
// parse rows
int r = strtol(end, &end, 10);
if (r > 0 && *end == 0)
{
*cols = c;
*rows = r;
return true;
}
}
return false;
}
int main(int argc, char *argv[])
{
auto L = rwte.lua();
// register internal modules, logging first
register_lualogging(L.get());
register_luaterm(L.get());
register_luawindow(L.get());
// feed lua our args
L->newtable();
for (int i = 0; i < argc; i++)
{
L->pushstring(argv[i]);
L->seti(-2, i+1);
}
L->setglobal("args");
static struct option long_options[] =
{
{"config", required_argument, nullptr, 'c'},
{"winclass", required_argument, nullptr, 'w'},
{"noalt", no_argument, nullptr, 'a'},
{"font", required_argument, nullptr, 'f'},
{"geometry", required_argument, nullptr, 'g'}, // colsxrows, e.g., 80x24
{"title", required_argument, nullptr, 't'},
{"name", required_argument, nullptr, 'n'},
{"exe", required_argument, nullptr, 'e'},
{"out", required_argument, nullptr, 'o'},
{"line", required_argument, nullptr, 'l'},
{"help", no_argument, nullptr, 'h'},
{"bench", no_argument, nullptr, 'b'},
{"version", no_argument, nullptr, 'v'},
{nullptr, 0, nullptr, 0}
};
const char *confpath = nullptr;
int opt;
int cols = 0, rows = 0;
bool got_exe = false;
bool got_bench = false;
bool got_title = false;
while ((opt = getopt_long(argc, argv, "-c:w:af:g:t:n:o:l:hbve:",
long_options, NULL)) != -1)
{
switch (opt)
{
case 'c':
confpath = optarg;
break;
case 'w':
options.winclass = optarg;
break;
case 'a':
options.noalt = true;
break;
case 'f':
options.font = optarg;
break;
case 'g':
if (!parse_geometry(optarg, &cols, &rows))
LOGGER()->warn("ignoring invalid geometry '{}'", optarg);
break;
case 't':
options.title = optarg;
got_title = true;
break;
case 'n':
options.winname = optarg;
break;
case 'o':
options.io = optarg;
break;
case 'l':
options.line = optarg;
break;
case 'h':
exit_help(EXIT_SUCCESS);
break;
case 'b':
got_bench = true;
break;
case 'v':
exit_version();
break;
case 'e':
// todo: handle -e
LOGGER()->info("exe: {}", optarg);
got_exe = true;
break;
case 1:
fprintf(stderr, "%s: invalid arg -- '%s'\n",
argv[0], argv[optind-1]);
default:
exit_help(EXIT_FAILURE);
}
}
// todo: handle these with -e
if (optind < argc)
{
LOGGER()->info("non-option args:");
while (optind < argc)
LOGGER()->info("{}", argv[optind++]);
}
{
// Get XDG basedir data
xdgHandle xdg;
xdgInitHandle(&xdg);
// make a list of pachage search paths
std::vector<std::string> searchpaths;
const char *const *xdgconfigdirs = xdgSearchableConfigDirectories(&xdg);
for(; *xdgconfigdirs; xdgconfigdirs++)
{
// append /rwte to each dir
std::string path = *xdgconfigdirs;
path += "/rwte";
searchpaths.push_back(path);
}
// add search paths to lua world
L->getglobal("package");
if (L->istable(-1))
{
L->getfield(-1, "path");
add_to_search_path(L.get(), searchpaths, true);
L->setfield(-2, "path");
L->getfield(-1, "cpath");
add_to_search_path(L.get(), searchpaths, false);
L->setfield(-2, "cpath");
}
else
LOGGER()->error("package is not a table");
L->pop();
// find and run configuration file
if (!run_config(L.get(), &xdg, confpath))
LOGGER()->fatal("could not find/run config.lua");
xdgWipeHandle(&xdg);
}
// nothing else to do if bench arg was specified
if (got_bench)
return 0;
// if a title was passed on command line, then
// use that rather than checking lua config
if (!got_title)
{
L->getglobal("config");
if (L->istable(-1))
{
L->getfield(-1, "title");
std::string title = L->tostring(-1);
if (!title.empty())
options.title = title;
L->pop();
}
else
LOGGER()->fatal("expected 'config' to be table");
L->pop();
}
// get cols and rows, default to 80x24
if (cols == 0 || rows == 0)
{
L->getglobal("config");
L->getfield(-1, "default_cols");
cols = L->tointegerdef(-1, 80);
L->getfield(-2, "default_rows");
rows = L->tointegerdef(-1, 24);
L->pop(3);
}
cols = MAX(cols, 1);
rows = MAX(rows, 1);
// get ready, loop!
ev::default_loop main_loop;
g_term = std::make_unique<Term>(cols, rows);
// todo: width and height are arbitrary
if (!window.create(cols, rows))
return 1;
{
SigWatcher sigwatcher;
main_loop.run();
}
window.destroy();
LOGGER()->debug("exiting");
return 0;
}
<commit_msg>Made long_options const.<commit_after>#include <xcb/xcb.h>
#include <cstdio>
#include <ev++.h>
#include <cstring>
#include <memory>
#include <wordexp.h>
#include <basedir.h>
#include <basedir_fs.h>
#include <getopt.h>
#include "rwte/config.h"
#include "rwte/renderer.h"
#include "rwte/rwte.h"
#include "rwte/logging.h"
#include "rwte/sigwatcher.h"
#include "rwte/term.h"
#include "rwte/tty.h"
#include "rwte/window.h"
#include "lua/config.h"
#include "lua/state.h"
#include "lua/logging.h"
#include "lua/term.h"
#include "lua/window.h"
#include "rwte/version.h"
// globals
Window window;
Options options;
Rwte rwte;
std::unique_ptr<Term> g_term;
std::unique_ptr<Tty> g_tty;
lua_State * g_L = NULL;
#define LOGGER() (logging::get("rwte"))
#define MIN(a, b) ((a) < (b)? (a) : (b))
#define MAX(a, b) ((a) < (b)? (b) : (a))
// default values to use if we don't have
// a default value in config
static const float DEFAULT_BLINK_RATE = 0.6;
Options::Options() :
cmd(0),
title("rwte"),
noalt(false)
{ }
Rwte::Rwte() :
m_lua(std::make_shared<lua::State>())
{
m_lua->openlibs();
m_child.set<Rwte,&Rwte::childcb>(this);
m_flush.set<Rwte,&Rwte::flushcb>(this);
m_blink.set<Rwte,&Rwte::blinkcb>(this);
}
void Rwte::resize(uint16_t width, uint16_t height)
{
if (width == 0)
width = window.width();
if (height == 0)
height = window.height();
if (window.width() != width || window.height() != height)
{
window.resize(width, height);
g_term->resize(window.cols(), window.rows());
if (g_tty)
g_tty->resize();
}
}
void Rwte::watch_child(pid_t pid)
{
LOGGER()->debug("watching child {}", pid);
m_child.start(pid);
}
void Rwte::refresh()
{
if (!m_flush.is_active())
m_flush.start(1.0/60.0);
}
void Rwte::start_blink()
{
if (!m_blink.is_active())
{
float rate = lua::config::get_float(
"blink_rate", DEFAULT_BLINK_RATE);
m_blink.start(rate, rate);
}
else
{
// reset the timer if it's already active
// (so we don't blink until idle)
m_blink.stop();
m_blink.start();
}
}
void Rwte::stop_blink()
{
if (m_blink.is_active())
m_blink.stop();
}
void Rwte::childcb(ev::child &w, int)
{
if (!WIFEXITED(w.rstatus) || WEXITSTATUS(w.rstatus))
LOGGER()->warn("child finished with error {}", w.rstatus);
else
LOGGER()->info("child exited");
w.loop.break_loop(ev::ALL);
}
void Rwte::flushcb(ev::timer &, int)
{
window.draw();
}
void Rwte::blinkcb(ev::timer &, int)
{
g_term->blink();
}
static void add_to_search_path(lua::State *L, const std::vector<std::string>& searchpaths, bool for_lua)
{
if (L->type(-1) != LUA_TSTRING)
{
LOGGER()->warn("package.path is not a string");
return;
}
for (auto& searchpath : searchpaths)
{
L->pushstring(fmt::format(";{}{}", searchpath,
for_lua? "/?.lua" : "/?.so"));
if (for_lua)
{
L->pushstring(fmt::format(";{}/?/init.lua", searchpath,
for_lua? "/?.lua" : "/?.so"));
// pushed two, concat them with string already on stack
L->concat(3);
}
else
{
// pushed one, concat it with string already on stack
L->concat(2);
}
}
// add rwte lib path
if (for_lua)
{
L->pushstring(
";" RWTE_LIB_PATH "/?.lua"
";" RWTE_LIB_PATH "/?/init.lua");
L->concat(2);
}
else
{
L->pushstring(";" RWTE_LIB_PATH "/?.so");
L->concat(2);
}
}
static bool run_file(lua::State *L, const char *path)
{
if (L->loadfile(path) || L->pcall(0, 0, 0))
{
LOGGER()->error("lua config error: {}", L->tostring(-1));
L->pop(1);
return false;
}
else
return true;
}
static bool run_config(lua::State *L, xdgHandle *xdg, const char *confpatharg)
{
// try specified path first
if (confpatharg)
{
if (run_file(L, confpatharg))
return true;
else
LOGGER()->warn("unable to run specified config ({}); "
"running config.lua", confpatharg);
}
// try paths from xdgConfigFind
char *paths = xdgConfigFind("rwte/config.lua", xdg);
// paths from xdgConfigFind are null-terminated, with
// empty string at the end (double null)
char *tmp = paths;
while (*tmp)
{
if (run_file(L, tmp))
return true;
tmp += std::strlen(tmp) + 1;
}
std::free(paths);
// finally try CONFIG_FILE
// use wordexp to expand possible ~ in the path
wordexp_t exp_result;
wordexp(CONFIG_FILE, &exp_result, 0);
bool result = run_file(L, exp_result.we_wordv[0]);
wordfree(&exp_result);
return result;
}
static void exit_help(int code)
{
fprintf((code == EXIT_SUCCESS) ? stdout : stderr,
"Usage: rwte [options] [-- args]\n"
" -c, --config FILE overrides config file\n"
" -a, --noalt disables alt screens\n"
" -f, --font FONT pango font string\n"
" -g, --geometry GEOM window geometry; colsxrows, e.g.,\n"
" \"80x24\" (the default)\n"
" -t, --title TITLE window title; defaults to rwte\n"
" -n, --name NAME window name; defaults to $TERM\n"
" -w, --winclass CLASS overrides window class\n"
" -e, --exe COMMAND command to execute instead of shell;\n"
" if specified, any arguments to the\n"
" command may be specified after a \"--\"\n"
" -o, --out OUT writes all io to this file;\n"
" \"-\" means stdout\n"
" -l, --line LINE use a tty line instead of creating a\n"
" new pty; LINE is expected to be the\n"
" device\n"
" -h, --help show help\n"
" -b, --bench run config and exit\n"
" -v, --version show version and exit\n");
exit(code);
}
static void exit_version()
{
fprintf(stdout, "rwte %s\n", version_string());
exit(EXIT_SUCCESS);
}
static bool parse_geometry(const char *g, int *cols, int *rows)
{
// parse cols
char *end = nullptr;
int c = strtol(g, &end, 10);
if (c > 0 && *end == 'x')
{
// move past x
end++;
// parse rows
int r = strtol(end, &end, 10);
if (r > 0 && *end == 0)
{
*cols = c;
*rows = r;
return true;
}
}
return false;
}
int main(int argc, char *argv[])
{
auto L = rwte.lua();
// register internal modules, logging first
register_lualogging(L.get());
register_luaterm(L.get());
register_luawindow(L.get());
// feed lua our args
L->newtable();
for (int i = 0; i < argc; i++)
{
L->pushstring(argv[i]);
L->seti(-2, i+1);
}
L->setglobal("args");
static const struct option long_options[] =
{
{"config", required_argument, nullptr, 'c'},
{"winclass", required_argument, nullptr, 'w'},
{"noalt", no_argument, nullptr, 'a'},
{"font", required_argument, nullptr, 'f'},
{"geometry", required_argument, nullptr, 'g'}, // colsxrows, e.g., 80x24
{"title", required_argument, nullptr, 't'},
{"name", required_argument, nullptr, 'n'},
{"exe", required_argument, nullptr, 'e'},
{"out", required_argument, nullptr, 'o'},
{"line", required_argument, nullptr, 'l'},
{"help", no_argument, nullptr, 'h'},
{"bench", no_argument, nullptr, 'b'},
{"version", no_argument, nullptr, 'v'},
{nullptr, 0, nullptr, 0}
};
const char *confpath = nullptr;
int opt;
int cols = 0, rows = 0;
bool got_exe = false;
bool got_bench = false;
bool got_title = false;
while ((opt = getopt_long(argc, argv, "-c:w:af:g:t:n:o:l:hbve:",
long_options, NULL)) != -1)
{
switch (opt)
{
case 'c':
confpath = optarg;
break;
case 'w':
options.winclass = optarg;
break;
case 'a':
options.noalt = true;
break;
case 'f':
options.font = optarg;
break;
case 'g':
if (!parse_geometry(optarg, &cols, &rows))
LOGGER()->warn("ignoring invalid geometry '{}'", optarg);
break;
case 't':
options.title = optarg;
got_title = true;
break;
case 'n':
options.winname = optarg;
break;
case 'o':
options.io = optarg;
break;
case 'l':
options.line = optarg;
break;
case 'h':
exit_help(EXIT_SUCCESS);
break;
case 'b':
got_bench = true;
break;
case 'v':
exit_version();
break;
case 'e':
// todo: handle -e
LOGGER()->info("exe: {}", optarg);
got_exe = true;
break;
case 1:
fprintf(stderr, "%s: invalid arg -- '%s'\n",
argv[0], argv[optind-1]);
default:
exit_help(EXIT_FAILURE);
}
}
// todo: handle these with -e
if (optind < argc)
{
LOGGER()->info("non-option args:");
while (optind < argc)
LOGGER()->info("{}", argv[optind++]);
}
{
// Get XDG basedir data
xdgHandle xdg;
xdgInitHandle(&xdg);
// make a list of pachage search paths
std::vector<std::string> searchpaths;
const char *const *xdgconfigdirs = xdgSearchableConfigDirectories(&xdg);
for(; *xdgconfigdirs; xdgconfigdirs++)
{
// append /rwte to each dir
std::string path = *xdgconfigdirs;
path += "/rwte";
searchpaths.push_back(path);
}
// add search paths to lua world
L->getglobal("package");
if (L->istable(-1))
{
L->getfield(-1, "path");
add_to_search_path(L.get(), searchpaths, true);
L->setfield(-2, "path");
L->getfield(-1, "cpath");
add_to_search_path(L.get(), searchpaths, false);
L->setfield(-2, "cpath");
}
else
LOGGER()->error("package is not a table");
L->pop();
// find and run configuration file
if (!run_config(L.get(), &xdg, confpath))
LOGGER()->fatal("could not find/run config.lua");
xdgWipeHandle(&xdg);
}
// nothing else to do if bench arg was specified
if (got_bench)
return 0;
// if a title was passed on command line, then
// use that rather than checking lua config
if (!got_title)
{
L->getglobal("config");
if (L->istable(-1))
{
L->getfield(-1, "title");
std::string title = L->tostring(-1);
if (!title.empty())
options.title = title;
L->pop();
}
else
LOGGER()->fatal("expected 'config' to be table");
L->pop();
}
// get cols and rows, default to 80x24
if (cols == 0 || rows == 0)
{
L->getglobal("config");
L->getfield(-1, "default_cols");
cols = L->tointegerdef(-1, 80);
L->getfield(-2, "default_rows");
rows = L->tointegerdef(-1, 24);
L->pop(3);
}
cols = MAX(cols, 1);
rows = MAX(rows, 1);
// get ready, loop!
ev::default_loop main_loop;
g_term = std::make_unique<Term>(cols, rows);
// todo: width and height are arbitrary
if (!window.create(cols, rows))
return 1;
{
SigWatcher sigwatcher;
main_loop.run();
}
window.destroy();
LOGGER()->debug("exiting");
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
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 the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <numeric>
#include <algorithm>
#include "libtorrent/stat.hpp"
namespace libtorrent {
void stat_channel::second_tick(int tick_interval_ms)
{
if (m_counter == 0) return;
int sample = int(size_type(m_counter) * 1000 / tick_interval_ms);
TORRENT_ASSERT(sample >= 0);
m_average = m_average * 3 / 4 + sample / 4;
m_counter = 0;
}
}
<commit_msg>one last stats fix<commit_after>/*
Copyright (c) 2003, Arvid Norberg
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 the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <numeric>
#include <algorithm>
#include "libtorrent/stat.hpp"
namespace libtorrent {
void stat_channel::second_tick(int tick_interval_ms)
{
int sample = int(size_type(m_counter) * 1000 / tick_interval_ms);
TORRENT_ASSERT(sample >= 0);
m_average = m_average * 3 / 4 + sample / 4;
m_counter = 0;
}
}
<|endoftext|> |
<commit_before>/**
* @file sync.cpp
* @brief Class for synchronizing local and remote trees
*
* (c) 2013 by Mega Limited, Wellsford, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega/sync.h"
#include "mega/megaapp.h"
#include "mega/transfer.h"
namespace mega {
// new Syncs are automatically inserted into the session's syncs list
// a full read of the subtree is initiated
Sync::Sync(MegaClient* cclient, string* crootpath, Node* remotenode, int ctag)
{
client = cclient;
tag = ctag;
localbytes = 0;
localnodes[FILENODE] = 0;
localnodes[FOLDERNODE] = 0;
state = SYNC_INITIALSCAN;
localroot.init(this,FOLDERNODE,NULL,crootpath);
localroot.setnode(remotenode);
sync_it = client->syncs.insert(client->syncs.end(),this);
dirnotify = client->fsaccess->newdirnotify(crootpath);
scan(crootpath,NULL);
}
Sync::~Sync()
{
// prevent remote mass deletion while rootlocal destructor runs
state = SYNC_CANCELED;
client->syncs.erase(sync_it);
client->syncactivity = true;
}
void Sync::changestate(syncstate newstate)
{
if (newstate != state)
{
client->app->syncupdate_state(this,newstate);
state = newstate;
}
}
// walk path and return corresponding LocalNode and its parent
// path must not start with a separator and be relative to the sync root
// NULL: no match
LocalNode* Sync::localnodebypath(string* localpath, LocalNode** parent)
{
const char* ptr = localpath->data();
const char* end = localpath->data()+localpath->size();
const char* nptr = ptr;
LocalNode* l = &localroot;
size_t separatorlen = client->fsaccess->localseparator.size();
localnode_map::iterator it;
string t;
for (;;)
{
if (nptr == end || !memcmp(nptr,client->fsaccess->localseparator.data(),separatorlen))
{
if (parent) *parent = l;
t.assign(ptr,nptr-ptr);
if ((it = l->children.find(&t)) == l->children.end() && (it = l->schildren.find(&t)) == l->schildren.end()) return NULL;
l = it->second;
if (nptr == end) return l;
ptr = nptr+separatorlen;
nptr = ptr;
}
else nptr += separatorlen;
}
}
// determine sync state of path
pathstate_t Sync::pathstate(string* localpath)
{
LocalNode* l = localnodebypath(localpath);
if (!l) return PATHSTATE_NOTFOUND;
if (l->node) return PATHSTATE_SYNCED;
if (l->transfer && l->transfer->slot) return PATHSTATE_SYNCING;
return PATHSTATE_PENDING;
}
// scan localpath, add or update child nodes, call recursively for folder nodes
// localpath must be prefixed with Sync
void Sync::scan(string* localpath, FileAccess* fa)
{
DirAccess* da;
string localname, name;
size_t baselen;
baselen = dirnotify->localbasepath.size()+client->fsaccess->localseparator.size();
if (baselen > localpath->size()) baselen = localpath->size();
da = client->fsaccess->newdiraccess();
// scan the dir, mark all items with a unique identifier
if (da->dopen(localpath,fa,false))
{
while (da->dnext(&localname))
{
name = localname;
client->fsaccess->local2name(&name);
// check if this record is to be ignored
if (client->app->sync_syncable(name.c_str(),localpath,&localname))
{
// new or existing record: place at the end of the queue
dirnotify->pathq[DirNotify::DIREVENTS].resize(dirnotify->pathq[DirNotify::DIREVENTS].size()+1);
dirnotify->pathq[DirNotify::DIREVENTS].back().assign(*localpath,baselen,string::npos);
if (dirnotify->pathq[DirNotify::DIREVENTS].back().size()) dirnotify->pathq[DirNotify::DIREVENTS].back().append(client->fsaccess->localseparator);
dirnotify->pathq[DirNotify::DIREVENTS].back().append(localname);
}
}
}
delete da;
}
// check local path
// path references a new FOLDERNODE: returns created node
// path references a existing FILENODE: returns node
// otherwise, returns NULL
LocalNode* Sync::checkpath(string* localpath)
{
FileAccess* fa;
bool newnode = false, changed = false;
bool isroot;
LocalNode* l;
LocalNode* parent;
string tmppath;
client->fsaccess->local2path(localpath,&tmppath);
isroot = !localpath->size();
l = isroot ? &localroot : localnodebypath(localpath,&parent);
// prefix localpath with sync's base path
if (!isroot) localpath->insert(0,client->fsaccess->localseparator);
localpath->insert(0,dirnotify->localbasepath);
// attempt to open/type this file, bail if unsuccessful
fa = client->fsaccess->newfileaccess();
if (fa->fopen(localpath,true,false))
{
if (!isroot)
{
// has the file or directory been overwritten since the last scan?
if (l)
{
if ((fa->fsidvalid && l->fsid_it != client->fsidnode.end() && l->fsid != fa->fsid) || l->type != fa->type)
{
l->setnotseen(l->notseen+1);
l = NULL;
}
else
{
l->setnotseen(0);
l->scanseqno = scanseqno;
}
}
// new node
if (!l)
{
// rename or move of existing node?
handlelocalnode_map::iterator it;
if (fa->fsidvalid && (it = client->fsidnode.find(fa->fsid)) != client->fsidnode.end())
{
client->app->syncupdate_local_move(this,it->second->name.c_str(),tmppath.c_str());
// (in case of a move, this synchronously updates l->parent and l->node->parent)
it->second->setnameparent(parent,localpath);
// unmark possible deletion
it->second->setnotseen(0);
}
else
{
// this is a new node: add
l = new LocalNode;
l->init(this,fa->type,parent,localpath);
if (fa->fsidvalid) l->setfsid(fa->fsid);
newnode = true;
}
}
}
if (l)
{
// detect file changes or recurse into new subfolders
if (l->type == FOLDERNODE)
{
if (newnode)
{
scan(localpath,fa);
client->app->syncupdate_local_folder_addition(this,tmppath.c_str());
}
else l = NULL;
}
else
{
if (isroot) changestate(SYNC_FAILED); // root node cannot be a file
else
{
if (l->size > 0) localbytes -= l->size;
if (l->genfingerprint(fa)) changed = true;
if (l->size > 0) localbytes += l->size;
if (newnode) client->app->syncupdate_local_file_addition(this,tmppath.c_str());
else if (changed) client->app->syncupdate_local_file_change(this,tmppath.c_str());
}
}
}
if (changed || newnode)
{
client->syncadded.insert(l->syncid);
client->syncactivity = true;
}
}
else
{
if (fa->retry)
{
// fopen() signals that the failure is potentially transient - do nothing, but request a recheck
dirnotify->pathq[DirNotify::RETRY].resize(dirnotify->pathq[DirNotify::RETRY].size()+1);
dirnotify->pathq[DirNotify::RETRY].back().assign(localpath->data()+dirnotify->localbasepath.size()+client->fsaccess->localseparator.size(),localpath->size()-dirnotify->localbasepath.size()-client->fsaccess->localseparator.size());
}
else if (l)
{
client->syncactivity = true;
if (l->scanseqno != scanseqno) l->setnotseen(1);
}
l = NULL;
}
delete fa;
return l;
}
// add or refresh local filesystem item from scan stack, add items to scan stack
void Sync::procscanq(int q)
{
while (dirnotify->pathq[q].size())
{
string* localpath = &dirnotify->pathq[q].front();
LocalNode* l = checkpath(localpath);
dirnotify->pathq[q].pop_front();
// we return control to the application in case a filenode was encountered
// (in order to avoid lengthy blocking episodes due to multiple fingerprint calculations)
if (l && l->type == FILENODE) break;
}
if (dirnotify->pathq[q].size()) client->syncactivity = true;
else if (!dirnotify->pathq[!q].size()) scanseqno++; // all queues empty: new scan sweep begins
}
} // namespace
<commit_msg>Sync: Stop outbound transfer upon local deletion<commit_after>/**
* @file sync.cpp
* @brief Class for synchronizing local and remote trees
*
* (c) 2013 by Mega Limited, Wellsford, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega/sync.h"
#include "mega/megaapp.h"
#include "mega/transfer.h"
namespace mega {
// new Syncs are automatically inserted into the session's syncs list
// a full read of the subtree is initiated
Sync::Sync(MegaClient* cclient, string* crootpath, Node* remotenode, int ctag)
{
client = cclient;
tag = ctag;
localbytes = 0;
localnodes[FILENODE] = 0;
localnodes[FOLDERNODE] = 0;
state = SYNC_INITIALSCAN;
localroot.init(this,FOLDERNODE,NULL,crootpath);
localroot.setnode(remotenode);
sync_it = client->syncs.insert(client->syncs.end(),this);
dirnotify = client->fsaccess->newdirnotify(crootpath);
scan(crootpath,NULL);
}
Sync::~Sync()
{
// prevent remote mass deletion while rootlocal destructor runs
state = SYNC_CANCELED;
client->syncs.erase(sync_it);
client->syncactivity = true;
}
void Sync::changestate(syncstate newstate)
{
if (newstate != state)
{
client->app->syncupdate_state(this,newstate);
state = newstate;
}
}
// walk path and return corresponding LocalNode and its parent
// path must not start with a separator and be relative to the sync root
// NULL: no match
LocalNode* Sync::localnodebypath(string* localpath, LocalNode** parent)
{
const char* ptr = localpath->data();
const char* end = localpath->data()+localpath->size();
const char* nptr = ptr;
LocalNode* l = &localroot;
size_t separatorlen = client->fsaccess->localseparator.size();
localnode_map::iterator it;
string t;
for (;;)
{
if (nptr == end || !memcmp(nptr,client->fsaccess->localseparator.data(),separatorlen))
{
if (parent) *parent = l;
t.assign(ptr,nptr-ptr);
if ((it = l->children.find(&t)) == l->children.end() && (it = l->schildren.find(&t)) == l->schildren.end()) return NULL;
l = it->second;
if (nptr == end) return l;
ptr = nptr+separatorlen;
nptr = ptr;
}
else nptr += separatorlen;
}
}
// determine sync state of path
pathstate_t Sync::pathstate(string* localpath)
{
LocalNode* l = localnodebypath(localpath);
if (!l) return PATHSTATE_NOTFOUND;
if (l->node) return PATHSTATE_SYNCED;
if (l->transfer && l->transfer->slot) return PATHSTATE_SYNCING;
return PATHSTATE_PENDING;
}
// scan localpath, add or update child nodes, call recursively for folder nodes
// localpath must be prefixed with Sync
void Sync::scan(string* localpath, FileAccess* fa)
{
DirAccess* da;
string localname, name;
size_t baselen;
baselen = dirnotify->localbasepath.size()+client->fsaccess->localseparator.size();
if (baselen > localpath->size()) baselen = localpath->size();
da = client->fsaccess->newdiraccess();
// scan the dir, mark all items with a unique identifier
if (da->dopen(localpath,fa,false))
{
while (da->dnext(&localname))
{
name = localname;
client->fsaccess->local2name(&name);
// check if this record is to be ignored
if (client->app->sync_syncable(name.c_str(),localpath,&localname))
{
// new or existing record: place at the end of the queue
dirnotify->pathq[DirNotify::DIREVENTS].resize(dirnotify->pathq[DirNotify::DIREVENTS].size()+1);
dirnotify->pathq[DirNotify::DIREVENTS].back().assign(*localpath,baselen,string::npos);
if (dirnotify->pathq[DirNotify::DIREVENTS].back().size()) dirnotify->pathq[DirNotify::DIREVENTS].back().append(client->fsaccess->localseparator);
dirnotify->pathq[DirNotify::DIREVENTS].back().append(localname);
}
}
}
delete da;
}
// check local path
// path references a new FOLDERNODE: returns created node
// path references a existing FILENODE: returns node
// otherwise, returns NULL
LocalNode* Sync::checkpath(string* localpath)
{
FileAccess* fa;
bool newnode = false, changed = false;
bool isroot;
LocalNode* l;
LocalNode* parent;
string tmppath;
client->fsaccess->local2path(localpath,&tmppath);
isroot = !localpath->size();
l = isroot ? &localroot : localnodebypath(localpath,&parent);
// prefix localpath with sync's base path
if (!isroot) localpath->insert(0,client->fsaccess->localseparator);
localpath->insert(0,dirnotify->localbasepath);
// attempt to open/type this file, bail if unsuccessful
fa = client->fsaccess->newfileaccess();
if (fa->fopen(localpath,true,false))
{
if (!isroot)
{
// has the file or directory been overwritten since the last scan?
if (l)
{
if ((fa->fsidvalid && l->fsid_it != client->fsidnode.end() && l->fsid != fa->fsid) || l->type != fa->type)
{
l->setnotseen(l->notseen+1);
l = NULL;
}
else
{
l->setnotseen(0);
l->scanseqno = scanseqno;
}
}
// new node
if (!l)
{
// rename or move of existing node?
handlelocalnode_map::iterator it;
if (fa->fsidvalid && (it = client->fsidnode.find(fa->fsid)) != client->fsidnode.end())
{
client->app->syncupdate_local_move(this,it->second->name.c_str(),tmppath.c_str());
// (in case of a move, this synchronously updates l->parent and l->node->parent)
it->second->setnameparent(parent,localpath);
// unmark possible deletion
it->second->setnotseen(0);
}
else
{
// this is a new node: add
l = new LocalNode;
l->init(this,fa->type,parent,localpath);
if (fa->fsidvalid) l->setfsid(fa->fsid);
newnode = true;
}
}
}
if (l)
{
// detect file changes or recurse into new subfolders
if (l->type == FOLDERNODE)
{
if (newnode)
{
scan(localpath,fa);
client->app->syncupdate_local_folder_addition(this,tmppath.c_str());
}
else l = NULL;
}
else
{
if (isroot) changestate(SYNC_FAILED); // root node cannot be a file
else
{
if (l->size > 0) localbytes -= l->size;
if (l->genfingerprint(fa)) changed = true;
if (l->size > 0) localbytes += l->size;
if (newnode) client->app->syncupdate_local_file_addition(this,tmppath.c_str());
else if (changed) client->app->syncupdate_local_file_change(this,tmppath.c_str());
}
}
}
if (changed || newnode)
{
client->syncadded.insert(l->syncid);
client->syncactivity = true;
}
}
else
{
if (fa->retry)
{
// fopen() signals that the failure is potentially transient - do nothing, but request a recheck
dirnotify->pathq[DirNotify::RETRY].resize(dirnotify->pathq[DirNotify::RETRY].size()+1);
dirnotify->pathq[DirNotify::RETRY].back().assign(localpath->data()+dirnotify->localbasepath.size()+client->fsaccess->localseparator.size(),localpath->size()-dirnotify->localbasepath.size()-client->fsaccess->localseparator.size());
}
else if (l)
{
// immediately stop outgoing transfer, if any
if (l->transfer) client->stopxfer(l);
client->syncactivity = true;
if (l->scanseqno != scanseqno) l->setnotseen(1);
}
l = NULL;
}
delete fa;
return l;
}
// add or refresh local filesystem item from scan stack, add items to scan stack
void Sync::procscanq(int q)
{
while (dirnotify->pathq[q].size())
{
string* localpath = &dirnotify->pathq[q].front();
LocalNode* l = checkpath(localpath);
dirnotify->pathq[q].pop_front();
// we return control to the application in case a filenode was encountered
// (in order to avoid lengthy blocking episodes due to multiple fingerprint calculations)
if (l && l->type == FILENODE) break;
}
if (dirnotify->pathq[q].size()) client->syncactivity = true;
else if (!dirnotify->pathq[!q].size()) scanseqno++; // all queues empty: new scan sweep begins
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sync.h"
#include "util.h"
#include <stdio.h>
#include <boost/thread.hpp>
#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
printf("LOCKCONTENTION: %s\n", pszName);
printf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */
#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
// Thread 1 locks A, then B, then C
// Thread 2 locks D, then C, then A
// --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//
struct CLockLocation {
CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn)
{
mutexName = pszName;
sourceFile = pszFile;
sourceLine = nLine;
fTry = fTryIn;
}
std::string ToString() const
{
return mutexName + " " + sourceFile + ":" + ToString(sourceLine) + (fTry ? " (TRY)" : "");
}
bool fTry;
private:
std::string mutexName;
std::string sourceFile;
int sourceLine;
};
typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
typedef std::map<std::pair<void*, void*>, LockStack> LockOrders;
typedef std::set<std::pair<void*, void*> > InvLockOrders;
struct LockData {
// Very ugly hack: as the global constructs and destructors run single
// threaded, we use this boolean to know whether LockData still exists,
// as DeleteLock can get called by global CCriticalSection destructors
// after LockData disappears.
bool available;
LockData() : available(true) {}
~LockData() { available = false; }
LockOrders lockorders;
InvLockOrders invlockorders;
boost::mutex dd_mutex;
} static lockdata;
boost::thread_specific_ptr<LockStack> lockstack;
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
printf("POTENTIAL DEADLOCK DETECTED\n");
printf("Previous lock order was:\n");
for (const std::pair<void*, CLockLocation> & i : s2) {
if (i.first == mismatch.first) {
printf(" (1)");
}
if (i.first == mismatch.second) {
printf(" (2)");
}
printf(" %s\n", i.second.ToString());
}
printf("Current lock order is:\n");
for (const std::pair<void*, CLockLocation> & i : s1) {
if (i.first == mismatch.first) {
printf(" (1)");
}
if (i.first == mismatch.second) {
printf(" (2)");
}
printf(" %s\n", i.second.ToString());
}
assert(false);
}
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
if (lockstack.get() == NULL)
lockstack.reset(new LockStack);
boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);
(*lockstack).push_back(std::make_pair(c, locklocation));
for (const std::pair<void*, CLockLocation> & i : (*lockstack)) {
if (i.first == c)
break;
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
if (lockdata.lockorders.count(p1))
continue;
lockdata.lockorders[p1] = (*lockstack);
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
lockdata.invlockorders.insert(p2);
if (lockdata.lockorders.count(p2))
potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);
}
}
static void pop_lock()
{
(*lockstack).pop_back();
}
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry);
}
void LeaveCritical()
{
pop_lock();
}
std::string LocksHeld()
{
std::string result;
for (const std::pair<void*, CLockLocation> & i : *lockstack)
result += i.second.ToString() + std::string("\n");
return result;
}
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
{
for (const std::pair<void*, CLockLocation> & i : *lockstack)
if (i.first == cs)
return;
fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str());
abort();
}
void DeleteLock(void* cs)
{
if (!lockdata.available) {
// We're already shutting down.
return;
}
boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);
std::pair<void*, void*> item = std::make_pair(cs, (void*)0);
LockOrders::iterator it = lockdata.lockorders.lower_bound(item);
while (it != lockdata.lockorders.end() && it->first.first == cs) {
std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);
lockdata.invlockorders.erase(invitem);
lockdata.lockorders.erase(it++);
}
InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);
while (invit != lockdata.invlockorders.end() && invit->first == cs) {
std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);
lockdata.lockorders.erase(invinvitem);
lockdata.invlockorders.erase(invit++);
}
}
#endif /* DEBUG_LOCKORDER */
<commit_msg>Fix build errors when using DEBUG_LOCKORDER define.<commit_after>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sync.h"
#include "util.h"
#include <stdio.h>
#include <boost/thread.hpp>
#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
printf("LOCKCONTENTION: %s\n", pszName);
printf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */
#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
// Thread 1 locks A, then B, then C
// Thread 2 locks D, then C, then A
// --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//
struct CLockLocation {
CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn)
{
mutexName = pszName;
sourceFile = pszFile;
sourceLine = nLine;
fTry = fTryIn;
}
std::string ToString() const
{
return mutexName + " " + sourceFile + ":" + ::ToString(sourceLine) + (fTry ? " (TRY)" : "");
}
bool fTry;
private:
std::string mutexName;
std::string sourceFile;
int sourceLine;
};
typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
typedef std::map<std::pair<void*, void*>, LockStack> LockOrders;
typedef std::set<std::pair<void*, void*> > InvLockOrders;
struct LockData {
// Very ugly hack: as the global constructs and destructors run single
// threaded, we use this boolean to know whether LockData still exists,
// as DeleteLock can get called by global CCriticalSection destructors
// after LockData disappears.
bool available;
LockData() : available(true) {}
~LockData() { available = false; }
LockOrders lockorders;
InvLockOrders invlockorders;
boost::mutex dd_mutex;
} static lockdata;
boost::thread_specific_ptr<LockStack> lockstack;
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
printf("POTENTIAL DEADLOCK DETECTED\n");
printf("Previous lock order was:\n");
for (const std::pair<void*, CLockLocation> & i : s2) {
if (i.first == mismatch.first) {
printf(" (1)");
}
if (i.first == mismatch.second) {
printf(" (2)");
}
printf(" %s\n", i.second.ToString().c_str());
}
printf("Current lock order is:\n");
for (const std::pair<void*, CLockLocation> & i : s1) {
if (i.first == mismatch.first) {
printf(" (1)");
}
if (i.first == mismatch.second) {
printf(" (2)");
}
printf(" %s\n", i.second.ToString().c_str());
}
assert(false);
}
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
if (lockstack.get() == NULL)
lockstack.reset(new LockStack);
boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);
(*lockstack).push_back(std::make_pair(c, locklocation));
for (const std::pair<void*, CLockLocation> & i : (*lockstack)) {
if (i.first == c)
break;
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
if (lockdata.lockorders.count(p1))
continue;
lockdata.lockorders[p1] = (*lockstack);
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
lockdata.invlockorders.insert(p2);
if (lockdata.lockorders.count(p2))
potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);
}
}
static void pop_lock()
{
(*lockstack).pop_back();
}
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry);
}
void LeaveCritical()
{
pop_lock();
}
std::string LocksHeld()
{
std::string result;
for (const std::pair<void*, CLockLocation> & i : *lockstack)
result += i.second.ToString() + std::string("\n");
return result;
}
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
{
for (const std::pair<void*, CLockLocation> & i : *lockstack)
if (i.first == cs)
return;
fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str());
abort();
}
void DeleteLock(void* cs)
{
if (!lockdata.available) {
// We're already shutting down.
return;
}
boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);
std::pair<void*, void*> item = std::make_pair(cs, (void*)0);
LockOrders::iterator it = lockdata.lockorders.lower_bound(item);
while (it != lockdata.lockorders.end() && it->first.first == cs) {
std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);
lockdata.invlockorders.erase(invitem);
lockdata.lockorders.erase(it++);
}
InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);
while (invit != lockdata.invlockorders.end() && invit->first == cs) {
std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);
lockdata.lockorders.erase(invinvitem);
lockdata.invlockorders.erase(invit++);
}
}
#endif /* DEBUG_LOCKORDER */
<|endoftext|> |
<commit_before>
#ifdef _WIN32
#define _UNICODE 1
#define UNICODE 1
#endif
#define BOOST_TEST_MODULE SlipRock module
#ifdef _MSC_VER
#include <boost/test/included/unit_test.hpp>
#else
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#endif
#include "../include/sliprock.h"
#include "sliprock_internals.h"
#include "stringbuf.h"
#include <csignal>
#include <exception>
#include <mutex>
#include <stdexcept>
#include <stdlib.h>
#include <thread>
#ifdef _WIN32
#define address pipename
#include <windows.h>
#endif
#ifndef BOOST_TEST
#define BOOST_TEST BOOST_CHECK
#endif
#ifndef _WIN32
typedef int HANDLE;
#include <pthread.h>
#define INVALID_HANDLE_VALUE (-1)
#endif
static uint32_t sliprock_getpid(void) {
#ifdef _WIN32
return GetCurrentProcessId();
#else
return (uint32_t)getpid();
#endif
}
struct set_on_close {
set_on_close(std::mutex &m, bool &b) : boolean(b), mut(m) {}
~set_on_close() {
std::unique_lock<std::mutex> locker{mut};
boolean = true;
}
private:
bool &boolean;
std::mutex &mut;
};
template <size_t size>
bool client(char (&buf)[size], SliprockConnection *con, bool &finished,
std::mutex &mutex) {
set_on_close closer(mutex, finished);
char buf2[size + 1] = {0};
bool read_succeeded = false;
SliprockHandle fd_ = (SliprockHandle)INVALID_HANDLE_VALUE;
#ifndef _WIN32
BOOST_TEST(system("ls -a ~/.sliprock") == 0);
#endif
SliprockReceiver *receiver;
int x = sliprock_open("dummy_valr", sizeof("dummy_val") - 1,
sliprock_getpid(), &receiver);
BOOST_TEST(x == 0);
BOOST_REQUIRE(x == 0);
MADE_IT;
x = sliprock_connect(receiver, &fd_);
BOOST_TEST(x == 0);
BOOST_REQUIRE(x == 0);
MADE_IT;
HANDLE fd = (HANDLE)fd_;
#ifdef _WIN32
DWORD read;
BOOST_TEST(0 != ReadFile(fd, buf2, sizeof buf, &read, nullptr));
BOOST_TEST(read == sizeof buf);
BOOST_TEST(0 != WriteFile(fd, buf2, sizeof buf, &read, nullptr));
BOOST_TEST(read == sizeof buf);
FlushFileBuffers(fd);
#else
if (fd >= 0) {
BOOST_TEST(sizeof buf == read(fd, buf2, sizeof buf));
BOOST_TEST(sizeof buf == write(fd, buf2, sizeof buf));
}
#endif
// static_assert(sizeof buf2 == sizeof buf, "Buffer size mismatch");
static_assert(sizeof con->address == sizeof receiver->sock,
"Connection size mismatch");
BOOST_TEST(memcmp(&buf2[0], &buf[0], sizeof buf) == 0);
fwrite(buf, 1, sizeof buf, stderr);
fwrite(buf2, 1, sizeof buf2, stderr);
#ifndef _WIN32
BOOST_TEST((int)fd > -1);
#endif
read_succeeded = true;
BOOST_TEST(0 == memcmp(reinterpret_cast<void *>(&receiver->sock),
reinterpret_cast<void *>(&con->address),
sizeof con->address));
BOOST_TEST(read_succeeded == true);
BOOST_TEST(receiver != static_cast<SliprockReceiver *>(nullptr));
#ifndef _WIN32
BOOST_TEST(close(fd) == 0);
#else
BOOST_TEST(CloseHandle(fd) != 0);
#endif
sliprock_close_receiver(receiver);
return read_succeeded;
}
template <size_t n>
bool server(char (&buf)[n], SliprockConnection *con, bool &finished,
std::mutex &mutex) {
set_on_close closer(mutex, finished);
MADE_IT;
SliprockHandle handle_;
int err = sliprock_accept(con, &handle_);
if (err != 0) {
fprintf(stderr, "error code %d\n", err);
return false;
}
auto handle = (HANDLE)handle_;
MADE_IT;
if (handle == INVALID_HANDLE_VALUE)
return false;
MADE_IT;
char buf3[sizeof buf];
#ifndef _WIN32
if (write(handle, buf, sizeof buf) != sizeof buf)
return false;
MADE_IT;
if (read(handle, buf3, sizeof buf) != sizeof buf)
return false;
MADE_IT;
if (close(handle))
return false;
MADE_IT;
#else
DWORD written;
MADE_IT;
if (WriteFile(handle, buf, sizeof buf, &written, NULL) == 0)
return false;
if (!FlushFileBuffers(handle))
return false;
MADE_IT;
if (written != sizeof buf3)
return false;
MADE_IT;
if (ReadFile(handle, buf3, sizeof buf3, &written, NULL) == 0)
return false;
if (!CloseHandle(handle))
return false;
MADE_IT;
#endif
bool x = !memcmp(buf3, buf, sizeof buf);
finished = true;
return x;
}
#ifndef _WIN32
static void donothing(int _) {
(void)_;
return;
}
static_assert(std::is_same<std::thread::native_handle_type, pthread_t>(),
"Mismatched native handle type!");
#elif 0
static_assert(std::is_same<std::thread::native_handle_type, HANDLE>(),
"Mismatched native handle type!");
#endif
// Interrupt a thread IF read_done is true, ensuring that lock is held
// when reading its value.
static void interrupt_thread(std::mutex &lock, const bool &read_done,
std::thread &thread) {
std::unique_lock<std::mutex> locker(lock);
if (!read_done) {
#ifndef _WIN32
pthread_kill(thread.native_handle(), SIGPIPE);
#elif _MSC_VER
CancelSynchronousIo(thread.native_handle());
#else
(void)thread;
#endif
}
}
BOOST_AUTO_TEST_CASE(can_create_connection) {
#ifndef _WIN32
struct sigaction sigact;
memset(&sigact, 0, sizeof sigact);
sigact.sa_handler = donothing;
sigemptyset(&sigact.sa_mask);
sigaddset(&sigact.sa_mask, SIGPIPE);
sigaction(SIGPIPE, &sigact, nullptr);
BOOST_TEST(system("rm -rf -- \"$HOME/.sliprock\" /tmp/sliprock.*") == 0);
#endif
SliprockConnection *con = nullptr;
int x = sliprock_socket("dummy_val", sizeof("dummy_val") - 1, &con);
BOOST_TEST(x == 0);
BOOST_REQUIRE(x == 0);
std::mutex lock, lock2;
bool read_done = false, write_done = false;
char buf[] = "Test message!\n";
bool write_succeeded = false, read_succeeded = false;
std::thread thread([&]() {
if (!(read_succeeded = server(buf, con, read_done, lock2)))
perror("sliprock_server");
});
std::thread thread2(
[&]() { write_succeeded = client(buf, con, write_done, lock); });
auto interrupter = std::thread{[&]() {
#ifndef _WIN32
struct timespec q = {1, 0};
nanosleep(&q, nullptr);
#else
Sleep(10000);
#endif
interrupt_thread(lock2, read_done, thread);
interrupt_thread(lock, write_done, thread2);
}};
thread.join();
thread2.join();
#ifdef _WIN32
interrupter.detach();
#else
interrupter.join();
#endif
BOOST_TEST(write_succeeded);
BOOST_TEST(read_succeeded);
sliprock_close(con);
}
// BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Log before interrupting a thread<commit_after>
#ifdef _WIN32
#define _UNICODE 1
#define UNICODE 1
#endif
#define BOOST_TEST_MODULE SlipRock module
#ifdef _MSC_VER
#include <boost/test/included/unit_test.hpp>
#else
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#endif
#include "../include/sliprock.h"
#include "sliprock_internals.h"
#include "stringbuf.h"
#include <csignal>
#include <exception>
#include <mutex>
#include <stdexcept>
#include <stdlib.h>
#include <thread>
#ifdef _WIN32
#define address pipename
#include <windows.h>
#endif
#ifndef BOOST_TEST
#define BOOST_TEST BOOST_CHECK
#endif
#ifndef _WIN32
typedef int HANDLE;
#include <pthread.h>
#define INVALID_HANDLE_VALUE (-1)
#endif
static uint32_t sliprock_getpid(void) {
#ifdef _WIN32
return GetCurrentProcessId();
#else
return (uint32_t)getpid();
#endif
}
struct set_on_close {
set_on_close(std::mutex &m, bool &b) : boolean(b), mut(m) {}
~set_on_close() {
std::unique_lock<std::mutex> locker{mut};
boolean = true;
}
private:
bool &boolean;
std::mutex &mut;
};
template <size_t size>
bool client(char (&buf)[size], SliprockConnection *con, bool &finished,
std::mutex &mutex) {
set_on_close closer(mutex, finished);
char buf2[size + 1] = {0};
bool read_succeeded = false;
SliprockHandle fd_ = (SliprockHandle)INVALID_HANDLE_VALUE;
#ifndef _WIN32
BOOST_TEST(system("ls -a ~/.sliprock") == 0);
#endif
SliprockReceiver *receiver;
int x = sliprock_open("dummy_valr", sizeof("dummy_val") - 1,
sliprock_getpid(), &receiver);
BOOST_TEST(x == 0);
BOOST_REQUIRE(x == 0);
MADE_IT;
x = sliprock_connect(receiver, &fd_);
BOOST_TEST(x == 0);
BOOST_REQUIRE(x == 0);
MADE_IT;
HANDLE fd = (HANDLE)fd_;
#ifdef _WIN32
DWORD read;
BOOST_TEST(0 != ReadFile(fd, buf2, sizeof buf, &read, nullptr));
BOOST_TEST(read == sizeof buf);
BOOST_TEST(0 != WriteFile(fd, buf2, sizeof buf, &read, nullptr));
BOOST_TEST(read == sizeof buf);
FlushFileBuffers(fd);
#else
if (fd >= 0) {
BOOST_TEST(sizeof buf == read(fd, buf2, sizeof buf));
BOOST_TEST(sizeof buf == write(fd, buf2, sizeof buf));
}
#endif
// static_assert(sizeof buf2 == sizeof buf, "Buffer size mismatch");
static_assert(sizeof con->address == sizeof receiver->sock,
"Connection size mismatch");
BOOST_TEST(memcmp(&buf2[0], &buf[0], sizeof buf) == 0);
fwrite(buf, 1, sizeof buf, stderr);
fwrite(buf2, 1, sizeof buf2, stderr);
#ifndef _WIN32
BOOST_TEST((int)fd > -1);
#endif
read_succeeded = true;
BOOST_TEST(0 == memcmp(reinterpret_cast<void *>(&receiver->sock),
reinterpret_cast<void *>(&con->address),
sizeof con->address));
BOOST_TEST(read_succeeded == true);
BOOST_TEST(receiver != static_cast<SliprockReceiver *>(nullptr));
#ifndef _WIN32
BOOST_TEST(close(fd) == 0);
#else
BOOST_TEST(CloseHandle(fd) != 0);
#endif
sliprock_close_receiver(receiver);
return read_succeeded;
}
template <size_t n>
bool server(char (&buf)[n], SliprockConnection *con, bool &finished,
std::mutex &mutex) {
set_on_close closer(mutex, finished);
MADE_IT;
SliprockHandle handle_;
int err = sliprock_accept(con, &handle_);
if (err != 0) {
fprintf(stderr, "error code %d\n", err);
return false;
}
auto handle = (HANDLE)handle_;
MADE_IT;
if (handle == INVALID_HANDLE_VALUE)
return false;
MADE_IT;
char buf3[sizeof buf];
#ifndef _WIN32
if (write(handle, buf, sizeof buf) != sizeof buf)
return false;
MADE_IT;
if (read(handle, buf3, sizeof buf) != sizeof buf)
return false;
MADE_IT;
if (close(handle))
return false;
MADE_IT;
#else
DWORD written;
MADE_IT;
if (WriteFile(handle, buf, sizeof buf, &written, NULL) == 0)
return false;
if (!FlushFileBuffers(handle))
return false;
MADE_IT;
if (written != sizeof buf3)
return false;
MADE_IT;
if (ReadFile(handle, buf3, sizeof buf3, &written, NULL) == 0)
return false;
if (!CloseHandle(handle))
return false;
MADE_IT;
#endif
bool x = !memcmp(buf3, buf, sizeof buf);
finished = true;
return x;
}
#ifndef _WIN32
static void donothing(int _) {
(void)_;
return;
}
static_assert(std::is_same<std::thread::native_handle_type, pthread_t>(),
"Mismatched native handle type!");
#elif 0
static_assert(std::is_same<std::thread::native_handle_type, HANDLE>(),
"Mismatched native handle type!");
#endif
// Interrupt a thread IF read_done is true, ensuring that lock is held
// when reading its value.
static void interrupt_thread(std::mutex &lock, const bool &read_done,
std::thread &thread) {
std::unique_lock<std::mutex> locker(lock);
if (!read_done) {
#ifndef _WIN32
pthread_kill(thread.native_handle(), SIGPIPE);
#elif _MSC_VER
CancelSynchronousIo(thread.native_handle());
#else
(void)thread;
#endif
}
}
BOOST_AUTO_TEST_CASE(can_create_connection) {
#ifndef _WIN32
struct sigaction sigact;
memset(&sigact, 0, sizeof sigact);
sigact.sa_handler = donothing;
sigemptyset(&sigact.sa_mask);
sigaddset(&sigact.sa_mask, SIGPIPE);
sigaction(SIGPIPE, &sigact, nullptr);
BOOST_TEST(system("rm -rf -- \"$HOME/.sliprock\" /tmp/sliprock.*") == 0);
#endif
SliprockConnection *con = nullptr;
int x = sliprock_socket("dummy_val", sizeof("dummy_val") - 1, &con);
BOOST_TEST(x == 0);
BOOST_REQUIRE(x == 0);
std::mutex lock, lock2;
bool read_done = false, write_done = false;
char buf[] = "Test message!\n";
bool write_succeeded = false, read_succeeded = false;
std::thread thread([&]() {
if (!(read_succeeded = server(buf, con, read_done, lock2)))
perror("sliprock_server");
});
std::thread thread2(
[&]() { write_succeeded = client(buf, con, write_done, lock); });
auto interrupter = std::thread{[&]() {
#ifndef _WIN32
struct timespec q = {1, 0};
nanosleep(&q, nullptr);
#else
Sleep(10000);
#endif
sliprock_trace("Interrupting thread\n");
interrupt_thread(lock2, read_done, thread);
interrupt_thread(lock, write_done, thread2);
}};
thread.join();
thread2.join();
#ifdef _WIN32
interrupter.detach();
#else
interrupter.join();
#endif
BOOST_TEST(write_succeeded);
BOOST_TEST(read_succeeded);
sliprock_close(con);
}
// BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>// timer.cc
// Implements the Timer class
#include "timer.h"
#include <string>
#include <iostream>
#include "error.h"
#include "logger.h"
#include "material.h"
namespace cyclus {
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::RunSim() {
CLOG(LEV_INFO1) << "Simulation set to run from start="
<< start_date_ << " to end=" << end_date_;
time_ = start_time_;
CLOG(LEV_INFO1) << "Beginning simulation";
while (date_ < endDate()) {
if (date_.day() == 1) {
CLOG(LEV_INFO2) << "Current date: " << date_ << " Current time: " << time_ <<
" {";
CLOG(LEV_DEBUG3) << "The list of current tick listeners is: " <<
ReportListeners();
if (decay_interval_ > 0 && time_ > 0 && time_ % decay_interval_ == 0) {
Material::DecayAll(time_);
}
// provides robustness when listeners are added during ticks/tocks
for (int i = 0; i < new_tickers_.size(); ++i) {
tick_listeners_.push_back(new_tickers_[i]);
}
new_tickers_.clear();
SendTick();
SendResolve();
}
int eom_day = LastDayOfMonth();
for (int i = 1; i < eom_day + 1; i++) {
SendDailyTasks();
if (i == eom_day) {
SendTock();
CLOG(LEV_INFO2) << "}";
}
date_ += boost::gregorian::days(1);
}
time_++;
}
// initiate deletion of models that don't have parents.
// dealloc will propogate through hierarchy as models delete their children
int count = 0;
while (Model::GetModelList().size() > 0) {
Model* model = Model::GetModelList().at(count);
try {
model->parent();
} catch (ValueError err) {
delete model;
count = 0;
continue;
}
count++;
}
}
int Timer::LastDayOfMonth() {
int lastDay =
boost::gregorian::gregorian_calendar::end_of_month_day(date_.year(),
date_.month());
return lastDay;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string Timer::ReportListeners() {
std::string report = "";
for (std::vector<TimeAgent*>::iterator agent = tick_listeners_.begin();
agent != tick_listeners_.end();
agent++) {
report += (*agent)->name() + " ";
}
return report;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::SendResolve() {
for (std::vector<MarketModel*>::iterator agent = resolve_listeners_.begin();
agent != resolve_listeners_.end();
agent++) {
CLOG(LEV_INFO3) << "Sending resolve to Model ID=" << (*agent)->id()
<< ", name=" << (*agent)->name() << " {";
(*agent)->Resolve();
CLOG(LEV_INFO3) << "}";
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::SendTick() {
for (std::vector<TimeAgent*>::iterator agent = tick_listeners_.begin();
agent != tick_listeners_.end();
agent++) {
CLOG(LEV_INFO3) << "Sending tick to Model ID=" << (*agent)->id()
<< ", name=" << (*agent)->name() << " {";
(*agent)->HandleTick(time_);
CLOG(LEV_INFO3) << "}";
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::SendTock() {
for (std::vector<TimeAgent*>::iterator agent = tick_listeners_.begin();
agent != tick_listeners_.end();
agent++) {
CLOG(LEV_INFO3) << "Sending tock to Model ID=" << (*agent)->id()
<< ", name=" << (*agent)->name() << " {";
(*agent)->HandleTock(time_);
CLOG(LEV_INFO3) << "}";
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::SendDailyTasks() {
for (std::vector<TimeAgent*>::iterator agent = tick_listeners_.begin();
agent != tick_listeners_.end();
agent++) {
(*agent)->HandleDailyTasks(time_, date_.day());
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::RegisterTickListener(TimeAgent* agent) {
CLOG(LEV_INFO2) << "Model ID=" << agent->id() << ", name=" << agent->name()
<< " has registered to receive 'ticks' and 'tocks'.";
new_tickers_.push_back(agent);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::RegisterResolveListener(MarketModel* agent) {
CLOG(LEV_INFO2) << "Model ID=" << agent->id() << ", name=" << agent->name()
<< " has registered to receive 'resolves'.";
resolve_listeners_.push_back(agent);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int Timer::time() {
return time_;
}
void Timer::Reset() {
resolve_listeners_.clear();
tick_listeners_.clear();
decay_interval_ = 0;
month0_ = 0;
year0_ = 0;
start_time_ = 0;
time_ = 0;
dur_ = 0;
start_date_ = boost::gregorian::date();
end_date_ = boost::gregorian::date();
date_ = boost::gregorian::date();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::Initialize(Context* ctx, int dur, int m0, int y0, int start,
int decay, std::string handle) {
if (m0 < 1 || m0 > 12) {
throw ValueError("Invalid month0; must be between 1 and 12 (inclusive).");
}
if (y0 < 1942) {
throw ValueError("Invalid year0; the first man-made nuclear reactor was build in 1942");
}
if (y0 > 2063) {
throw ValueError("Invalid year0; why start a simulation after we've got warp drive?: http://en.wikipedia.org/wiki/Warp_drive#Development_of_the_backstory");
}
if (decay > dur) {
throw ValueError("Invalid decay interval; no decay occurs if the interval is greater than the simulation duriation. For no decay, use -1 .");
}
decay_interval_ = decay;
month0_ = m0;
year0_ = y0;
start_time_ = start;
time_ = start;
dur_ = dur;
start_date_ = boost::gregorian::date(year0_, month0_, 1);
end_date_ = GetEndDate(start_date_, dur_);
date_ = boost::gregorian::date(start_date_);
LogTimeData(ctx, handle);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
boost::gregorian::date Timer::GetEndDate(boost::gregorian::date startDate,
int dur_) {
boost::gregorian::date endDate(startDate);
endDate += boost::gregorian::months(dur_ - 1);
endDate += boost::gregorian::days(
boost::gregorian::gregorian_calendar::end_of_month_day(endDate.year(),
endDate.month()) - 1);
return endDate;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int Timer::dur() {
return dur_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Timer::Timer() :
time_(0),
start_time_(0),
dur_(0),
decay_interval_(0),
month0_(0),
year0_(0) { }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int Timer::ConvertDate(int month, int year) {
return (year - year0_) * 12 + (month - month0_) + start_time_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::pair<int, int> Timer::ConvertDate(int time) {
int month = (time - start_time_) % 12 + 1;
int year = (time - start_time_ - (month - 1)) / 12 + year0_;
return std::make_pair(month, year);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::LogTimeData(Context* ctx, std::string handle) {
ctx->NewEvent("SimulationTimeInfo")
->AddVal("SimHandle", handle)
->AddVal("InitialYear", year0_)
->AddVal("InitialMonth", month0_)
->AddVal("SimulationStart", start_time_)
->AddVal("Duration", dur_)
->Record();
}
} // namespace cyclus
<commit_msg>re-added missing decay interval from output db<commit_after>// timer.cc
// Implements the Timer class
#include "timer.h"
#include <string>
#include <iostream>
#include "error.h"
#include "logger.h"
#include "material.h"
namespace cyclus {
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::RunSim() {
CLOG(LEV_INFO1) << "Simulation set to run from start="
<< start_date_ << " to end=" << end_date_;
time_ = start_time_;
CLOG(LEV_INFO1) << "Beginning simulation";
while (date_ < endDate()) {
if (date_.day() == 1) {
CLOG(LEV_INFO2) << "Current date: " << date_ << " Current time: " << time_ <<
" {";
CLOG(LEV_DEBUG3) << "The list of current tick listeners is: " <<
ReportListeners();
if (decay_interval_ > 0 && time_ > 0 && time_ % decay_interval_ == 0) {
Material::DecayAll(time_);
}
// provides robustness when listeners are added during ticks/tocks
for (int i = 0; i < new_tickers_.size(); ++i) {
tick_listeners_.push_back(new_tickers_[i]);
}
new_tickers_.clear();
SendTick();
SendResolve();
}
int eom_day = LastDayOfMonth();
for (int i = 1; i < eom_day + 1; i++) {
SendDailyTasks();
if (i == eom_day) {
SendTock();
CLOG(LEV_INFO2) << "}";
}
date_ += boost::gregorian::days(1);
}
time_++;
}
// initiate deletion of models that don't have parents.
// dealloc will propogate through hierarchy as models delete their children
int count = 0;
while (Model::GetModelList().size() > 0) {
Model* model = Model::GetModelList().at(count);
try {
model->parent();
} catch (ValueError err) {
delete model;
count = 0;
continue;
}
count++;
}
}
int Timer::LastDayOfMonth() {
int lastDay =
boost::gregorian::gregorian_calendar::end_of_month_day(date_.year(),
date_.month());
return lastDay;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string Timer::ReportListeners() {
std::string report = "";
for (std::vector<TimeAgent*>::iterator agent = tick_listeners_.begin();
agent != tick_listeners_.end();
agent++) {
report += (*agent)->name() + " ";
}
return report;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::SendResolve() {
for (std::vector<MarketModel*>::iterator agent = resolve_listeners_.begin();
agent != resolve_listeners_.end();
agent++) {
CLOG(LEV_INFO3) << "Sending resolve to Model ID=" << (*agent)->id()
<< ", name=" << (*agent)->name() << " {";
(*agent)->Resolve();
CLOG(LEV_INFO3) << "}";
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::SendTick() {
for (std::vector<TimeAgent*>::iterator agent = tick_listeners_.begin();
agent != tick_listeners_.end();
agent++) {
CLOG(LEV_INFO3) << "Sending tick to Model ID=" << (*agent)->id()
<< ", name=" << (*agent)->name() << " {";
(*agent)->HandleTick(time_);
CLOG(LEV_INFO3) << "}";
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::SendTock() {
for (std::vector<TimeAgent*>::iterator agent = tick_listeners_.begin();
agent != tick_listeners_.end();
agent++) {
CLOG(LEV_INFO3) << "Sending tock to Model ID=" << (*agent)->id()
<< ", name=" << (*agent)->name() << " {";
(*agent)->HandleTock(time_);
CLOG(LEV_INFO3) << "}";
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::SendDailyTasks() {
for (std::vector<TimeAgent*>::iterator agent = tick_listeners_.begin();
agent != tick_listeners_.end();
agent++) {
(*agent)->HandleDailyTasks(time_, date_.day());
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::RegisterTickListener(TimeAgent* agent) {
CLOG(LEV_INFO2) << "Model ID=" << agent->id() << ", name=" << agent->name()
<< " has registered to receive 'ticks' and 'tocks'.";
new_tickers_.push_back(agent);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::RegisterResolveListener(MarketModel* agent) {
CLOG(LEV_INFO2) << "Model ID=" << agent->id() << ", name=" << agent->name()
<< " has registered to receive 'resolves'.";
resolve_listeners_.push_back(agent);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int Timer::time() {
return time_;
}
void Timer::Reset() {
resolve_listeners_.clear();
tick_listeners_.clear();
decay_interval_ = 0;
month0_ = 0;
year0_ = 0;
start_time_ = 0;
time_ = 0;
dur_ = 0;
start_date_ = boost::gregorian::date();
end_date_ = boost::gregorian::date();
date_ = boost::gregorian::date();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::Initialize(Context* ctx, int dur, int m0, int y0, int start,
int decay, std::string handle) {
if (m0 < 1 || m0 > 12) {
throw ValueError("Invalid month0; must be between 1 and 12 (inclusive).");
}
if (y0 < 1942) {
throw ValueError("Invalid year0; the first man-made nuclear reactor was build in 1942");
}
if (y0 > 2063) {
throw ValueError("Invalid year0; why start a simulation after we've got warp drive?: http://en.wikipedia.org/wiki/Warp_drive#Development_of_the_backstory");
}
if (decay > dur) {
throw ValueError("Invalid decay interval; no decay occurs if the interval is greater than the simulation duriation. For no decay, use -1 .");
}
decay_interval_ = decay;
month0_ = m0;
year0_ = y0;
start_time_ = start;
time_ = start;
dur_ = dur;
start_date_ = boost::gregorian::date(year0_, month0_, 1);
end_date_ = GetEndDate(start_date_, dur_);
date_ = boost::gregorian::date(start_date_);
LogTimeData(ctx, handle);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
boost::gregorian::date Timer::GetEndDate(boost::gregorian::date startDate,
int dur_) {
boost::gregorian::date endDate(startDate);
endDate += boost::gregorian::months(dur_ - 1);
endDate += boost::gregorian::days(
boost::gregorian::gregorian_calendar::end_of_month_day(endDate.year(),
endDate.month()) - 1);
return endDate;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int Timer::dur() {
return dur_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Timer::Timer() :
time_(0),
start_time_(0),
dur_(0),
decay_interval_(0),
month0_(0),
year0_(0) { }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int Timer::ConvertDate(int month, int year) {
return (year - year0_) * 12 + (month - month0_) + start_time_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::pair<int, int> Timer::ConvertDate(int time) {
int month = (time - start_time_) % 12 + 1;
int year = (time - start_time_ - (month - 1)) / 12 + year0_;
return std::make_pair(month, year);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Timer::LogTimeData(Context* ctx, std::string handle) {
ctx->NewEvent("SimulationTimeInfo")
->AddVal("SimHandle", handle)
->AddVal("InitialYear", year0_)
->AddVal("InitialMonth", month0_)
->AddVal("SimulationStart", start_time_)
->AddVal("Duration", dur_)
->AddVal("DecayInterval", decay_interval_)
->Record();
}
} // namespace cyclus
<|endoftext|> |
<commit_before>#include "uart.h"
uart::uart(void): ls()
{
ls.open("/dev/ttySO", 9600);
}
void uart::write(std::vector<std::uint8_t>* request)
{
int nbBytes = sizeof(request);
ls.write(request,nbBytes);
ls.flush();
}
void uart::write(std::uint16_t request){
char a,b;
a = (char) (request &0xff);
b = (char) ((request >> 8)&0xff);
ls.writeChar(a);
ls.writeChar(b);
ls.flush();
}
std::uint8_t uart::read(void)
{
std::uint8_t response = 0;
ls.read(&response, 1);
ls.flush();
return response;
}
std::uint16_t uart::read_16(void)
{
std::uint16_t retval = 0;
std::uint8_t temp[2];
ls.read(&temp,2);
retval = temp[0] | (temp[1]<<8);
return retval;
}
<commit_msg>possibly fixed a long-standing mistake.<commit_after>#include "uart.h"
uart::uart(void): ls()
{
ls.open("/dev/ttyAMA0", 9600);
}
void uart::write(std::vector<std::uint8_t>* request)
{
int nbBytes = sizeof(request);
ls.write(request,nbBytes);
ls.flush();
}
void uart::write(std::uint16_t request){
char a,b;
a = (char) (request &0xff);
b = (char) ((request >> 8)&0xff);
ls.writeChar(a);
ls.writeChar(b);
ls.flush();
}
std::uint8_t uart::read(void)
{
std::uint8_t response = 0;
ls.read(&response, 1);
ls.flush();
return response;
}
std::uint16_t uart::read_16(void)
{
std::uint16_t retval = 0;
std::uint8_t temp[2];
ls.read(&temp,2);
retval = temp[0] | (temp[1]<<8);
return retval;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
// If <iostream> is included, put it after <stdio.h>, because it includes
// <stdio.h>, and therefore would ignore the _WITH_GETLINE.
#ifdef FREEBSD
#define _WITH_GETLINE
#endif
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdint.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <errno.h>
#include <signal.h>
#include <sys/select.h>
#include <Date.h>
#include <text.h>
#include <main.h>
#include <i18n.h>
#include <util.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Uses std::getline, because std::cin eats leading whitespace, and that means
// that if a newline is entered, std::cin eats it and never returns from the
// "std::cin >> answer;" line, but it does display the newline. This way, with
// std::getline, the newline can be detected, and the prompt re-written.
bool confirm (const std::string& question)
{
std::vector <std::string> options;
options.push_back (STRING_UTIL_CONFIRM_YES);
options.push_back (STRING_UTIL_CONFIRM_NO);
std::string answer;
std::vector <std::string> matches;
do
{
std::cout << question
<< STRING_UTIL_CONFIRM_YN;
std::getline (std::cin, answer);
answer = std::cin.eof() ? STRING_UTIL_CONFIRM_NO : lowerCase (trim (answer));
autoComplete (answer, options, matches, 1); // Hard-coded 1.
}
while (matches.size () != 1);
return matches[0] == STRING_UTIL_CONFIRM_YES ? true : false;
}
////////////////////////////////////////////////////////////////////////////////
// 0 = no
// 1 = yes
// 2 = all
// 3 = quit
int confirm4 (const std::string& question)
{
std::vector <std::string> options;
options.push_back (STRING_UTIL_CONFIRM_YES_U);
options.push_back (STRING_UTIL_CONFIRM_YES);
options.push_back (STRING_UTIL_CONFIRM_NO);
options.push_back (STRING_UTIL_CONFIRM_ALL_U);
options.push_back (STRING_UTIL_CONFIRM_ALL);
options.push_back (STRING_UTIL_CONFIRM_QUIT);
std::string answer;
std::vector <std::string> matches;
do
{
std::cout << question
<< " ("
<< options[1] << "/"
<< options[2] << "/"
<< options[4] << "/"
<< options[5]
<< ") ";
std::getline (std::cin, answer);
answer = trim (answer);
autoComplete (answer, options, matches, 1); // Hard-coded 1.
}
while (matches.size () != 1);
if (matches[0] == STRING_UTIL_CONFIRM_YES_U) return 1;
else if (matches[0] == STRING_UTIL_CONFIRM_YES) return 1;
else if (matches[0] == STRING_UTIL_CONFIRM_ALL_U) return 2;
else if (matches[0] == STRING_UTIL_CONFIRM_ALL) return 2;
else if (matches[0] == STRING_UTIL_CONFIRM_QUIT) return 3;
else return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Convert a quantity in seconds to a more readable format.
std::string formatBytes (size_t bytes)
{
char formatted[24];
if (bytes >= 995000000) sprintf (formatted, "%.1f %s", (bytes / 1000000000.0), STRING_UTIL_GIBIBYTES);
else if (bytes >= 995000) sprintf (formatted, "%.1f %s", (bytes / 1000000.0), STRING_UTIL_MEBIBYTES);
else if (bytes >= 995) sprintf (formatted, "%.1f %s", (bytes / 1000.0), STRING_UTIL_KIBIBYTES);
else sprintf (formatted, "%d %s", (int)bytes, STRING_UTIL_BYTES);
return commify (formatted);
}
////////////////////////////////////////////////////////////////////////////////
int autoComplete (
const std::string& partial,
const std::vector<std::string>& list,
std::vector<std::string>& matches,
int minimum/* = 1*/)
{
matches.clear ();
// Handle trivial case.
unsigned int length = partial.length ();
if (length)
{
std::vector <std::string>::const_iterator item;
for (item = list.begin (); item != list.end (); ++item)
{
// An exact match is a special case. Assume there is only one exact match
// and return immediately.
if (partial == *item)
{
matches.clear ();
matches.push_back (*item);
return 1;
}
// Maintain a list of partial matches.
else if (length >= (unsigned) minimum &&
length <= item->length () &&
partial == item->substr (0, length))
matches.push_back (*item);
}
}
return matches.size ();
}
// Handle the generation of UUIDs on FreeBSD in a separate implementation
// of the uuid () function, since the API is quite different from Linux's.
// Also, uuid_unparse_lower is not needed on FreeBSD, because the string
// representation is always lowercase anyway.
// For the implementation details, refer to
// http://svnweb.freebsd.org/base/head/sys/kern/kern_uuid.c
#ifdef FREEBSD
const std::string uuid ()
{
uuid_t id;
uint32_t status;
char *buffer (0);
uuid_create (&id, &status);
uuid_to_string (&id, &buffer, &status);
std::string res (buffer);
free (buffer);
return res;
}
#else
////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_UUID_UNPARSE_LOWER
// Older versions of libuuid don't have uuid_unparse_lower(), only uuid_unparse()
void uuid_unparse_lower (uuid_t uu, char *out)
{
uuid_unparse (uu, out);
// Characters in out are either 0-9, a-z, '-', or A-Z. A-Z is mapped to
// a-z by bitwise or with 0x20, and the others already have this bit set
for (size_t i = 0; i < 36; ++i) out[i] |= 0x20;
}
#endif
const std::string uuid ()
{
uuid_t id;
uuid_generate (id);
char buffer[100] = {0};
uuid_unparse_lower (id, buffer);
// Bug found by Steven de Brouwer.
buffer[36] = '\0';
return std::string (buffer);
}
#endif
////////////////////////////////////////////////////////////////////////////////
// On Solaris no flock function exists.
#ifdef SOLARIS
int flock (int fd, int operation)
{
struct flock fl;
switch (operation & ~LOCK_NB)
{
case LOCK_SH:
fl.l_type = F_RDLCK;
break;
case LOCK_EX:
fl.l_type = F_WRLCK;
break;
case LOCK_UN:
fl.l_type = F_UNLCK;
break;
default:
errno = EINVAL;
return -1;
}
fl.l_whence = 0;
fl.l_start = 0;
fl.l_len = 0;
return fcntl (fd, (operation & LOCK_NB) ? F_SETLK : F_SETLKW, &fl);
}
#endif
////////////////////////////////////////////////////////////////////////////////
// Run a binary with args, capturing output.
int execute (
const std::string& executable,
const std::vector <std::string>& args,
const std::string& input,
std::string& output)
{
pid_t pid;
int pin[2], pout[2];
fd_set rfds, wfds;
struct timeval tv;
int select_retval, read_retval, write_retval;
char buf[16384];
unsigned int written;
const char* input_cstr = input.c_str ();
if (signal (SIGPIPE, SIG_IGN) == SIG_ERR) // Handled locally with EPIPE.
throw std::string (std::strerror (errno));
if (pipe (pin) == -1)
throw std::string (std::strerror (errno));
if (pipe (pout) == -1)
throw std::string (std::strerror (errno));
if ((pid = fork ()) == -1)
throw std::string (std::strerror (errno));
if (pid == 0)
{
// This is only reached in the child
close (pin[1]); // Close the write end of the input pipe.
close (pout[0]); // Close the read end of the output pipe.
if (dup2 (pin[0], STDIN_FILENO) == -1)
throw std::string (std::strerror (errno));
if (dup2 (pout[1], STDOUT_FILENO) == -1)
throw std::string (std::strerror (errno));
char** argv = new char* [args.size () + 1];
for (unsigned int i = 0; i < args.size (); ++i)
argv[i] = (char*) args[i].c_str ();
argv[args.size ()] = NULL;
_exit (execvp (executable.c_str (), argv));
}
// This is only reached in the parent
close (pin[0]); // Close the read end of the input pipe.
close (pout[1]); // Close the write end of the output pipe.
if (input.size () == 0)
{
// Nothing to send to the child, close the pipe early.
close (pin[1]);
}
read_retval = -1;
written = 0;
while (read_retval != 0 || input.size () != written)
{
FD_ZERO (&rfds);
if (read_retval != 0)
{
FD_SET (pout[0], &rfds);
}
FD_ZERO (&wfds);
if (input.size () != written)
{
FD_SET (pin[1], &wfds);
}
tv.tv_sec = 5;
tv.tv_usec = 0;
select_retval = select (std::max (pout[0], pin[1]) + 1, &rfds, &wfds, NULL, &tv);
if (select_retval == -1)
throw std::string (std::strerror (errno));
if (FD_ISSET (pin[1], &wfds))
{
write_retval = write (pin[1], input_cstr + written, input.size () - written);
if (write_retval == -1)
{
if (errno == EPIPE)
{
// Child died (or closed the pipe) before reading all input.
// We don't really care; pretend we wrote it all.
write_retval = input.size () - written;
}
else
{
throw std::string (std::strerror (errno));
}
}
written += write_retval;
if (written == input.size ())
{
// Let the child know that no more input is coming by closing the pipe.
close (pin[1]);
}
}
if (FD_ISSET (pout[0], &rfds))
{
read_retval = read (pout[0], &buf, sizeof(buf)-1);
if (read_retval == -1)
throw std::string (std::strerror (errno));
buf[read_retval] = '\0';
output += buf;
}
}
close (pout[0]); // Close the read end of the output pipe.
int status = -1;
if (wait (&status) == -1)
throw std::string (std::strerror (errno));
if (WIFEXITED (status))
{
status = WEXITSTATUS (status);
}
else
{
throw std::string ("Error: Could not get Hook exit status!");
}
if (signal (SIGPIPE, SIG_DFL) == SIG_ERR) // We're done, return to default.
throw std::string (std::strerror (errno));
return status;
}
// Collides with std::numeric_limits methods
#undef max
////////////////////////////////////////////////////////////////////////////////
// Accept a list of projects, and return an indented list
// that reflects the hierarchy.
//
// Input - "one"
// "one.two"
// "one.two.three"
// "one.four"
// "two"
// Output - "one"
// " one.two"
// " one.two.three"
// " one.four"
// "two"
//
// There are two optional arguments, 'whitespace', and 'delimiter',
//
// - whitespace is the string used to build the prefixes of indented items.
// - defaults to two spaces, " "
// - delimiter is the character used to split up projects into subprojects.
// - defaults to the period, '.'
//
const std::string indentProject (
const std::string& project,
const std::string& whitespace /* = " " */,
char delimiter /* = '.' */)
{
// Count the delimiters in *i.
std::string prefix = "";
std::string::size_type pos = 0;
std::string::size_type lastpos = 0;
while ((pos = project.find (delimiter, pos + 1)) != std::string::npos)
{
if (pos != project.size () - 1)
{
prefix += whitespace;
lastpos = pos;
}
}
std::string child = "";
if (lastpos == 0)
child = project;
else
child = project.substr (lastpos + 1);
return prefix + child;
}
////////////////////////////////////////////////////////////////////////////////
const std::vector <std::string> extractParents (
const std::string& project,
const char& delimiter /* = '.' */)
{
std::vector <std::string> vec;
std::string::size_type pos = 0;
std::string::size_type copyUntil = 0;
while ((copyUntil = project.find (delimiter, pos + 1)) != std::string::npos)
{
if (copyUntil != project.size () - 1)
vec.push_back (project.substr (0, copyUntil));
pos = copyUntil;
}
return vec;
}
////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_TIMEGM
time_t timegm (struct tm *tm)
{
time_t ret;
char *tz;
tz = getenv ("TZ");
setenv ("TZ", "UTC", 1);
tzset ();
ret = mktime (tm);
if (tz)
setenv ("TZ", tz, 1);
else
unsetenv ("TZ");
tzset ();
return ret;
}
#endif
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Code Cleanup<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
// If <iostream> is included, put it after <stdio.h>, because it includes
// <stdio.h>, and therefore would ignore the _WITH_GETLINE.
#ifdef FREEBSD
#define _WITH_GETLINE
#endif
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdint.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <errno.h>
#include <signal.h>
#include <sys/select.h>
#include <Date.h>
#include <text.h>
#include <main.h>
#include <i18n.h>
#include <util.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Uses std::getline, because std::cin eats leading whitespace, and that means
// that if a newline is entered, std::cin eats it and never returns from the
// "std::cin >> answer;" line, but it does display the newline. This way, with
// std::getline, the newline can be detected, and the prompt re-written.
bool confirm (const std::string& question)
{
std::vector <std::string> options;
options.push_back (STRING_UTIL_CONFIRM_YES);
options.push_back (STRING_UTIL_CONFIRM_NO);
std::string answer;
std::vector <std::string> matches;
do
{
std::cout << question
<< STRING_UTIL_CONFIRM_YN;
std::getline (std::cin, answer);
answer = std::cin.eof() ? STRING_UTIL_CONFIRM_NO : lowerCase (trim (answer));
autoComplete (answer, options, matches, 1); // Hard-coded 1.
}
while (matches.size () != 1);
return matches[0] == STRING_UTIL_CONFIRM_YES ? true : false;
}
////////////////////////////////////////////////////////////////////////////////
// 0 = no
// 1 = yes
// 2 = all
// 3 = quit
int confirm4 (const std::string& question)
{
std::vector <std::string> options;
options.push_back (STRING_UTIL_CONFIRM_YES_U);
options.push_back (STRING_UTIL_CONFIRM_YES);
options.push_back (STRING_UTIL_CONFIRM_NO);
options.push_back (STRING_UTIL_CONFIRM_ALL_U);
options.push_back (STRING_UTIL_CONFIRM_ALL);
options.push_back (STRING_UTIL_CONFIRM_QUIT);
std::string answer;
std::vector <std::string> matches;
do
{
std::cout << question
<< " ("
<< options[1] << "/"
<< options[2] << "/"
<< options[4] << "/"
<< options[5]
<< ") ";
std::getline (std::cin, answer);
answer = trim (answer);
autoComplete (answer, options, matches, 1); // Hard-coded 1.
}
while (matches.size () != 1);
if (matches[0] == STRING_UTIL_CONFIRM_YES_U) return 1;
else if (matches[0] == STRING_UTIL_CONFIRM_YES) return 1;
else if (matches[0] == STRING_UTIL_CONFIRM_ALL_U) return 2;
else if (matches[0] == STRING_UTIL_CONFIRM_ALL) return 2;
else if (matches[0] == STRING_UTIL_CONFIRM_QUIT) return 3;
else return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Convert a quantity in seconds to a more readable format.
std::string formatBytes (size_t bytes)
{
char formatted[24];
if (bytes >= 995000000) sprintf (formatted, "%.1f %s", (bytes / 1000000000.0), STRING_UTIL_GIBIBYTES);
else if (bytes >= 995000) sprintf (formatted, "%.1f %s", (bytes / 1000000.0), STRING_UTIL_MEBIBYTES);
else if (bytes >= 995) sprintf (formatted, "%.1f %s", (bytes / 1000.0), STRING_UTIL_KIBIBYTES);
else sprintf (formatted, "%d %s", (int)bytes, STRING_UTIL_BYTES);
return commify (formatted);
}
////////////////////////////////////////////////////////////////////////////////
int autoComplete (
const std::string& partial,
const std::vector<std::string>& list,
std::vector<std::string>& matches,
int minimum/* = 1*/)
{
matches.clear ();
// Handle trivial case.
unsigned int length = partial.length ();
if (length)
{
std::vector <std::string>::const_iterator item;
for (item = list.begin (); item != list.end (); ++item)
{
// An exact match is a special case. Assume there is only one exact match
// and return immediately.
if (partial == *item)
{
matches.clear ();
matches.push_back (*item);
return 1;
}
// Maintain a list of partial matches.
else if (length >= (unsigned) minimum &&
length <= item->length () &&
partial == item->substr (0, length))
matches.push_back (*item);
}
}
return matches.size ();
}
// Handle the generation of UUIDs on FreeBSD in a separate implementation
// of the uuid () function, since the API is quite different from Linux's.
// Also, uuid_unparse_lower is not needed on FreeBSD, because the string
// representation is always lowercase anyway.
// For the implementation details, refer to
// http://svnweb.freebsd.org/base/head/sys/kern/kern_uuid.c
#ifdef FREEBSD
const std::string uuid ()
{
uuid_t id;
uint32_t status;
char *buffer (0);
uuid_create (&id, &status);
uuid_to_string (&id, &buffer, &status);
std::string res (buffer);
free (buffer);
return res;
}
#else
////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_UUID_UNPARSE_LOWER
// Older versions of libuuid don't have uuid_unparse_lower(), only uuid_unparse()
void uuid_unparse_lower (uuid_t uu, char *out)
{
uuid_unparse (uu, out);
// Characters in out are either 0-9, a-z, '-', or A-Z. A-Z is mapped to
// a-z by bitwise or with 0x20, and the others already have this bit set
for (size_t i = 0; i < 36; ++i) out[i] |= 0x20;
}
#endif
const std::string uuid ()
{
uuid_t id;
uuid_generate (id);
char buffer[100] = {0};
uuid_unparse_lower (id, buffer);
// Bug found by Steven de Brouwer.
buffer[36] = '\0';
return std::string (buffer);
}
#endif
////////////////////////////////////////////////////////////////////////////////
// On Solaris no flock function exists.
#ifdef SOLARIS
int flock (int fd, int operation)
{
struct flock fl;
switch (operation & ~LOCK_NB)
{
case LOCK_SH:
fl.l_type = F_RDLCK;
break;
case LOCK_EX:
fl.l_type = F_WRLCK;
break;
case LOCK_UN:
fl.l_type = F_UNLCK;
break;
default:
errno = EINVAL;
return -1;
}
fl.l_whence = 0;
fl.l_start = 0;
fl.l_len = 0;
return fcntl (fd, (operation & LOCK_NB) ? F_SETLK : F_SETLKW, &fl);
}
#endif
////////////////////////////////////////////////////////////////////////////////
// Run a binary with args, capturing output.
int execute (
const std::string& executable,
const std::vector <std::string>& args,
const std::string& input,
std::string& output)
{
pid_t pid;
int pin[2], pout[2];
fd_set rfds, wfds;
struct timeval tv;
int select_retval, read_retval, write_retval;
char buf[16384];
unsigned int written;
const char* input_cstr = input.c_str ();
if (signal (SIGPIPE, SIG_IGN) == SIG_ERR) // Handled locally with EPIPE.
throw std::string (std::strerror (errno));
if (pipe (pin) == -1)
throw std::string (std::strerror (errno));
if (pipe (pout) == -1)
throw std::string (std::strerror (errno));
if ((pid = fork ()) == -1)
throw std::string (std::strerror (errno));
if (pid == 0)
{
// This is only reached in the child
close (pin[1]); // Close the write end of the input pipe.
close (pout[0]); // Close the read end of the output pipe.
if (dup2 (pin[0], STDIN_FILENO) == -1)
throw std::string (std::strerror (errno));
if (dup2 (pout[1], STDOUT_FILENO) == -1)
throw std::string (std::strerror (errno));
char** argv = new char* [args.size () + 1];
for (unsigned int i = 0; i < args.size (); ++i)
argv[i] = (char*) args[i].c_str ();
argv[args.size ()] = NULL;
_exit (execvp (executable.c_str (), argv));
}
// This is only reached in the parent
close (pin[0]); // Close the read end of the input pipe.
close (pout[1]); // Close the write end of the output pipe.
if (input.size () == 0)
{
// Nothing to send to the child, close the pipe early.
close (pin[1]);
}
read_retval = -1;
written = 0;
while (read_retval != 0 || input.size () != written)
{
FD_ZERO (&rfds);
if (read_retval != 0)
{
FD_SET (pout[0], &rfds);
}
FD_ZERO (&wfds);
if (input.size () != written)
{
FD_SET (pin[1], &wfds);
}
tv.tv_sec = 5;
tv.tv_usec = 0;
select_retval = select (std::max (pout[0], pin[1]) + 1, &rfds, &wfds, NULL, &tv);
if (select_retval == -1)
throw std::string (std::strerror (errno));
if (FD_ISSET (pin[1], &wfds))
{
write_retval = write (pin[1], input_cstr + written, input.size () - written);
if (write_retval == -1)
{
if (errno == EPIPE)
{
// Child died (or closed the pipe) before reading all input.
// We don't really care; pretend we wrote it all.
write_retval = input.size () - written;
}
else
{
throw std::string (std::strerror (errno));
}
}
written += write_retval;
if (written == input.size ())
{
// Let the child know that no more input is coming by closing the pipe.
close (pin[1]);
}
}
if (FD_ISSET (pout[0], &rfds))
{
read_retval = read (pout[0], &buf, sizeof(buf)-1);
if (read_retval == -1)
throw std::string (std::strerror (errno));
buf[read_retval] = '\0';
output += buf;
}
}
close (pout[0]); // Close the read end of the output pipe.
int status = -1;
if (wait (&status) == -1)
throw std::string (std::strerror (errno));
if (WIFEXITED (status))
{
status = WEXITSTATUS (status);
}
else
{
throw std::string ("Error: Could not get Hook exit status!");
}
if (signal (SIGPIPE, SIG_DFL) == SIG_ERR) // We're done, return to default.
throw std::string (std::strerror (errno));
return status;
}
// Collides with std::numeric_limits methods
#undef max
////////////////////////////////////////////////////////////////////////////////
// Accept a list of projects, and return an indented list
// that reflects the hierarchy.
//
// Input - "one"
// "one.two"
// "one.two.three"
// "one.four"
// "two"
// Output - "one"
// " one.two"
// " one.two.three"
// " one.four"
// "two"
//
// There are two optional arguments, 'whitespace', and 'delimiter',
//
// - whitespace is the string used to build the prefixes of indented items.
// - defaults to two spaces, " "
// - delimiter is the character used to split up projects into subprojects.
// - defaults to the period, '.'
//
const std::string indentProject (
const std::string& project,
const std::string& whitespace /* = " " */,
char delimiter /* = '.' */)
{
// Count the delimiters in *i.
std::string prefix = "";
std::string::size_type pos = 0;
std::string::size_type lastpos = 0;
while ((pos = project.find (delimiter, pos + 1)) != std::string::npos)
{
if (pos != project.size () - 1)
{
prefix += whitespace;
lastpos = pos;
}
}
std::string child = "";
if (lastpos == 0)
child = project;
else
child = project.substr (lastpos + 1);
return prefix + child;
}
////////////////////////////////////////////////////////////////////////////////
const std::vector <std::string> extractParents (
const std::string& project,
const char& delimiter /* = '.' */)
{
std::vector <std::string> vec;
std::string::size_type pos = 0;
std::string::size_type copyUntil = 0;
while ((copyUntil = project.find (delimiter, pos + 1)) != std::string::npos)
{
if (copyUntil != project.size () - 1)
vec.push_back (project.substr (0, copyUntil));
pos = copyUntil;
}
return vec;
}
////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_TIMEGM
time_t timegm (struct tm *tm)
{
time_t ret;
char *tz;
tz = getenv ("TZ");
setenv ("TZ", "UTC", 1);
tzset ();
ret = mktime (tm);
if (tz)
setenv ("TZ", tz, 1);
else
unsetenv ("TZ");
tzset ();
return ret;
}
#endif
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#ifndef UTIL_HPP
#define UTIL_HPP
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <typeinfo>
#include <functional>
#define abs(x) (x < 0 ? -x : x)
#define UNUSED(expr) (void)(expr)
#define ALL(container) std::begin(container), std::end(container)
typedef long long int64;
typedef unsigned long long uint64;
typedef unsigned int uint;
template<typename T>
void println(T thing) {
std::cout << thing << std::endl;
}
template<typename T>
void print(T thing) {
std::cout << thing;
}
template<typename T, typename... Args>
void println(T thing, Args... args) {
if (sizeof...(args) == 1) {
print(thing);
print(" ");
print(args...);
std::cout << std::endl;
return;
}
print(thing);
print(" ");
print(args...);
}
template<typename T, typename... Args>
void print(T thing, Args... args) {
print(thing);
print(" ");
print(args...);
}
template<typename T>
bool contains(std::vector<T> vec, T item) {
return std::find(vec.begin(), vec.end(), item) != vec.end();
}
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
for (auto obj : vec) {
os << obj << " ";
}
return os;
}
template<typename T>
struct PtrUtil {
typedef std::shared_ptr<T> Link;
typedef std::weak_ptr<T> WeakLink;
template<typename... Args>
static Link make(Args... args) {
return std::make_shared<T>(args...);
}
template<typename U>
static inline bool isSameType(std::shared_ptr<U> link) {
return typeid(T) == typeid(*link);
}
template<typename U>
static inline Link dynPtrCast(std::shared_ptr<U> link) {
return std::dynamic_pointer_cast<T>(link);
}
};
template<typename T>
struct VectorHash {
std::size_t operator()(const std::vector<T>& vec) const {
std::size_t seed = vec.size();
std::hash<T> hash;
for (const T& i : vec) {
seed ^= hash(i) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
std::string getAddressStringFrom(const void* ptr) {
return std::to_string(reinterpret_cast<std::uintptr_t>(ptr));
}
#endif
<commit_msg>Return a hex string in getAddressStringFrom<commit_after>#ifndef UTIL_HPP
#define UTIL_HPP
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <typeinfo>
#include <functional>
#define abs(x) (x < 0 ? -x : x)
#define UNUSED(expr) (void)(expr)
#define ALL(container) std::begin(container), std::end(container)
typedef long long int64;
typedef unsigned long long uint64;
typedef unsigned int uint;
template<typename T>
void println(T thing) {
std::cout << thing << std::endl;
}
template<typename T>
void print(T thing) {
std::cout << thing;
}
template<typename T, typename... Args>
void println(T thing, Args... args) {
if (sizeof...(args) == 1) {
print(thing);
print(" ");
print(args...);
std::cout << std::endl;
return;
}
print(thing);
print(" ");
print(args...);
}
template<typename T, typename... Args>
void print(T thing, Args... args) {
print(thing);
print(" ");
print(args...);
}
template<typename T>
bool contains(std::vector<T> vec, T item) {
return std::find(vec.begin(), vec.end(), item) != vec.end();
}
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
for (auto obj : vec) {
os << obj << " ";
}
return os;
}
template<typename T>
struct PtrUtil {
typedef std::shared_ptr<T> Link;
typedef std::weak_ptr<T> WeakLink;
template<typename... Args>
static Link make(Args... args) {
return std::make_shared<T>(args...);
}
template<typename U>
static inline bool isSameType(std::shared_ptr<U> link) {
return typeid(T) == typeid(*link);
}
template<typename U>
static inline Link dynPtrCast(std::shared_ptr<U> link) {
return std::dynamic_pointer_cast<T>(link);
}
};
template<typename T>
struct VectorHash {
std::size_t operator()(const std::vector<T>& vec) const {
std::size_t seed = vec.size();
std::hash<T> hash;
for (const T& i : vec) {
seed ^= hash(i) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
std::string getAddressStringFrom(const void* ptr) {
std::stringstream ss;
ss << "0x" << std::hex << reinterpret_cast<std::uintptr_t>(ptr);
return ss.str();
}
#endif
<|endoftext|> |
<commit_before>//---------------------------------------------------------
// Copyright 2015 Ontario Institute for Cancer Research
// Written by Matei David (matei@cs.toronto.edu)
//---------------------------------------------------------
// Reference:
// http://stackoverflow.com/questions/14086417/how-to-write-custom-input-stream-in-c
#ifndef __ZSTR_HPP
#define __ZSTR_HPP
#include <cassert>
#include <fstream>
#include <sstream>
#include <zlib.h>
#include "strict_fstream.hpp"
namespace zstr
{
static const std::size_t default_buff_size = (std::size_t)1 << 20;
/// Exception class thrown by failed zlib operations.
class Exception
: public std::exception
{
public:
Exception(z_stream * zstrm_p, int ret)
: _msg("zlib: ")
{
switch (ret)
{
case Z_STREAM_ERROR:
_msg += "Z_STREAM_ERROR: ";
break;
case Z_DATA_ERROR:
_msg += "Z_DATA_ERROR: ";
break;
case Z_MEM_ERROR:
_msg += "Z_MEM_ERROR: ";
break;
case Z_VERSION_ERROR:
_msg += "Z_VERSION_ERROR: ";
break;
case Z_BUF_ERROR:
_msg += "Z_BUF_ERROR: ";
break;
default:
std::ostringstream oss;
oss << ret;
_msg += "[" + oss.str() + "]: ";
break;
}
_msg += zstrm_p->msg;
}
Exception(const std::string msg) : _msg(msg) {}
const char * what() const noexcept { return _msg.c_str(); }
private:
std::string _msg;
}; // class Exception
namespace detail
{
class z_stream_wrapper
: public z_stream
{
public:
z_stream_wrapper(bool _is_input, int _level, int _window_bits)
: is_input(_is_input)
{
this->zalloc = Z_NULL;
this->zfree = Z_NULL;
this->opaque = Z_NULL;
int ret;
if (is_input)
{
this->avail_in = 0;
this->next_in = Z_NULL;
ret = inflateInit2(this, _window_bits ? _window_bits : 15+32);
}
else
{
ret = deflateInit2(this, _level, Z_DEFLATED, _window_bits ? _window_bits : 15+16, 8, Z_DEFAULT_STRATEGY);
}
if (ret != Z_OK) throw Exception(this, ret);
}
~z_stream_wrapper()
{
if (is_input)
{
inflateEnd(this);
}
else
{
deflateEnd(this);
}
}
private:
bool is_input;
}; // class z_stream_wrapper
} // namespace detail
class istreambuf
: public std::streambuf
{
public:
istreambuf(std::streambuf * _sbuf_p,
std::size_t _buff_size = default_buff_size, bool _auto_detect = true, int _window_bits = 0)
: sbuf_p(_sbuf_p),
zstrm_p(nullptr),
buff_size(_buff_size),
auto_detect(_auto_detect),
auto_detect_run(false),
is_text(false),
window_bits(_window_bits)
{
assert(sbuf_p);
in_buff = new char [buff_size];
in_buff_start = in_buff;
in_buff_end = in_buff;
out_buff = new char [buff_size];
setg(out_buff, out_buff, out_buff);
}
istreambuf(const istreambuf &) = delete;
istreambuf(istreambuf &&) = default;
istreambuf & operator = (const istreambuf &) = delete;
istreambuf & operator = (istreambuf &&) = default;
virtual ~istreambuf()
{
delete [] in_buff;
delete [] out_buff;
if (zstrm_p) delete zstrm_p;
}
virtual std::streambuf::int_type underflow()
{
if (this->gptr() == this->egptr())
{
// pointers for free region in output buffer
char * out_buff_free_start = out_buff;
do
{
// read more input if none available
if (in_buff_start == in_buff_end)
{
// empty input buffer: refill from the start
in_buff_start = in_buff;
std::streamsize sz = sbuf_p->sgetn(in_buff, buff_size);
in_buff_end = in_buff + sz;
if (in_buff_end == in_buff_start) break; // end of input
}
// auto detect if the stream contains text or deflate data
if (auto_detect && ! auto_detect_run)
{
auto_detect_run = true;
unsigned char b0 = *reinterpret_cast< unsigned char * >(in_buff_start);
unsigned char b1 = *reinterpret_cast< unsigned char * >(in_buff_start + 1);
// Ref:
// http://en.wikipedia.org/wiki/Gzip
// http://stackoverflow.com/questions/9050260/what-does-a-zlib-header-look-like
is_text = ! (in_buff_start + 2 <= in_buff_end
&& ((b0 == 0x1F && b1 == 0x8B) // gzip header
|| (b0 == 0x78 && (b1 == 0x01 // zlib header
|| b1 == 0x9C
|| b1 == 0xDA))));
}
if (is_text)
{
// simply swap in_buff and out_buff, and adjust pointers
assert(in_buff_start == in_buff);
std::swap(in_buff, out_buff);
out_buff_free_start = in_buff_end;
in_buff_start = in_buff;
in_buff_end = in_buff;
}
else
{
// run inflate() on input
if (! zstrm_p) zstrm_p = new detail::z_stream_wrapper(true, Z_DEFAULT_COMPRESSION, window_bits);
zstrm_p->next_in = reinterpret_cast< decltype(zstrm_p->next_in) >(in_buff_start);
zstrm_p->avail_in = in_buff_end - in_buff_start;
zstrm_p->next_out = reinterpret_cast< decltype(zstrm_p->next_out) >(out_buff_free_start);
zstrm_p->avail_out = (out_buff + buff_size) - out_buff_free_start;
int ret = inflate(zstrm_p, Z_NO_FLUSH);
// process return code
if (ret != Z_OK && ret != Z_STREAM_END) throw Exception(zstrm_p, ret);
// update in&out pointers following inflate()
in_buff_start = reinterpret_cast< decltype(in_buff_start) >(zstrm_p->next_in);
in_buff_end = in_buff_start + zstrm_p->avail_in;
out_buff_free_start = reinterpret_cast< decltype(out_buff_free_start) >(zstrm_p->next_out);
assert(out_buff_free_start + zstrm_p->avail_out == out_buff + buff_size);
// if stream ended, deallocate inflator
if (ret == Z_STREAM_END)
{
delete zstrm_p;
zstrm_p = nullptr;
}
}
} while (out_buff_free_start == out_buff);
// 2 exit conditions:
// - end of input: there might or might not be output available
// - out_buff_free_start != out_buff: output available
this->setg(out_buff, out_buff, out_buff_free_start);
}
return this->gptr() == this->egptr()
? traits_type::eof()
: traits_type::to_int_type(*this->gptr());
}
private:
std::streambuf * sbuf_p;
char * in_buff;
char * in_buff_start;
char * in_buff_end;
char * out_buff;
detail::z_stream_wrapper * zstrm_p;
std::size_t buff_size;
bool auto_detect;
bool auto_detect_run;
bool is_text;
int window_bits;
static const std::size_t default_buff_size = (std::size_t)1 << 20;
}; // class istreambuf
class ostreambuf
: public std::streambuf
{
public:
ostreambuf(std::streambuf * _sbuf_p,
std::size_t _buff_size = default_buff_size, int _level = Z_DEFAULT_COMPRESSION, int _window_bits = 0)
: sbuf_p(_sbuf_p),
zstrm_p(new detail::z_stream_wrapper(false, _level, _window_bits)),
buff_size(_buff_size)
{
assert(sbuf_p);
in_buff = new char [buff_size];
out_buff = new char [buff_size];
setp(in_buff, in_buff + buff_size);
}
ostreambuf(const ostreambuf &) = delete;
ostreambuf(ostreambuf &&) = default;
ostreambuf & operator = (const ostreambuf &) = delete;
ostreambuf & operator = (ostreambuf &&) = default;
int deflate_loop(int flush)
{
while (true)
{
zstrm_p->next_out = reinterpret_cast< decltype(zstrm_p->next_out) >(out_buff);
zstrm_p->avail_out = buff_size;
int ret = deflate(zstrm_p, flush);
if (ret != Z_OK && ret != Z_STREAM_END && ret != Z_BUF_ERROR) throw Exception(zstrm_p, ret);
std::streamsize sz = sbuf_p->sputn(out_buff, reinterpret_cast< decltype(out_buff) >(zstrm_p->next_out) - out_buff);
if (sz != reinterpret_cast< decltype(out_buff) >(zstrm_p->next_out) - out_buff)
{
// there was an error in the sink stream
return -1;
}
if (ret == Z_STREAM_END || ret == Z_BUF_ERROR || sz == 0)
{
break;
}
}
return 0;
}
virtual ~ostreambuf()
{
// flush the zlib stream
//
// NOTE: Errors here (sync() return value not 0) are ignored, because we
// cannot throw in a destructor. This mirrors the behaviour of
// std::basic_filebuf::~basic_filebuf(). To see an exception on error,
// close the ofstream with an explicit call to close(), and do not rely
// on the implicit call in the destructor.
//
sync();
delete [] in_buff;
delete [] out_buff;
delete zstrm_p;
}
virtual std::streambuf::int_type overflow(std::streambuf::int_type c = traits_type::eof())
{
zstrm_p->next_in = reinterpret_cast< decltype(zstrm_p->next_in) >(pbase());
zstrm_p->avail_in = pptr() - pbase();
while (zstrm_p->avail_in > 0)
{
int r = deflate_loop(Z_NO_FLUSH);
if (r != 0)
{
setp(nullptr, nullptr);
return traits_type::eof();
}
}
setp(in_buff, in_buff + buff_size);
return traits_type::eq_int_type(c, traits_type::eof()) ? traits_type::eof() : sputc(c);
}
virtual int sync()
{
// first, call overflow to clear in_buff
overflow();
if (! pptr()) return -1;
// then, call deflate asking to finish the zlib stream
zstrm_p->next_in = nullptr;
zstrm_p->avail_in = 0;
if (deflate_loop(Z_FINISH) != 0) return -1;
deflateReset(zstrm_p);
return 0;
}
private:
std::streambuf * sbuf_p;
char * in_buff;
char * out_buff;
detail::z_stream_wrapper * zstrm_p;
std::size_t buff_size;
}; // class ostreambuf
class istream
: public std::istream
{
public:
istream(std::istream & is,
std::size_t _buff_size = default_buff_size, bool _auto_detect = true, int _window_bits = 0)
: std::istream(new istreambuf(is.rdbuf(), _buff_size, _auto_detect, _window_bits))
{
exceptions(std::ios_base::badbit);
}
explicit istream(std::streambuf * sbuf_p)
: std::istream(new istreambuf(sbuf_p))
{
exceptions(std::ios_base::badbit);
}
virtual ~istream()
{
delete rdbuf();
}
}; // class istream
class ostream
: public std::ostream
{
public:
ostream(std::ostream & os,
std::size_t _buff_size = default_buff_size, int _level = Z_DEFAULT_COMPRESSION, int _window_bits = 0)
: std::ostream(new ostreambuf(os.rdbuf(), _buff_size, _level, _window_bits))
{
exceptions(std::ios_base::badbit);
}
explicit ostream(std::streambuf * sbuf_p)
: std::ostream(new ostreambuf(sbuf_p))
{
exceptions(std::ios_base::badbit);
}
virtual ~ostream()
{
delete rdbuf();
}
}; // class ostream
namespace detail
{
template < typename FStream_Type >
struct strict_fstream_holder
{
strict_fstream_holder(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
: _fs(filename, mode)
{}
FStream_Type _fs;
}; // class strict_fstream_holder
} // namespace detail
class ifstream
: private detail::strict_fstream_holder< strict_fstream::ifstream >,
public std::istream
{
public:
explicit ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
: detail::strict_fstream_holder< strict_fstream::ifstream >(filename, mode),
std::istream(new istreambuf(_fs.rdbuf()))
{
exceptions(std::ios_base::badbit);
}
virtual ~ifstream()
{
if (rdbuf()) delete rdbuf();
}
}; // class ifstream
class ofstream
: private detail::strict_fstream_holder< strict_fstream::ofstream >,
public std::ostream
{
public:
explicit ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
: detail::strict_fstream_holder< strict_fstream::ofstream >(filename, mode | std::ios_base::binary),
std::ostream(new ostreambuf(_fs.rdbuf()))
{
exceptions(std::ios_base::badbit);
}
virtual ~ofstream()
{
if (rdbuf()) delete rdbuf();
}
}; // class ofstream
} // namespace zstr
#endif
<commit_msg>fix when installed to system<commit_after>//---------------------------------------------------------
// Copyright 2015 Ontario Institute for Cancer Research
// Written by Matei David (matei@cs.toronto.edu)
//---------------------------------------------------------
// Reference:
// http://stackoverflow.com/questions/14086417/how-to-write-custom-input-stream-in-c
#ifndef __ZSTR_HPP
#define __ZSTR_HPP
#include <cassert>
#include <fstream>
#include <sstream>
#include <zlib.h>
#include <strict_fstream.hpp>
namespace zstr
{
static const std::size_t default_buff_size = (std::size_t)1 << 20;
/// Exception class thrown by failed zlib operations.
class Exception
: public std::exception
{
public:
Exception(z_stream * zstrm_p, int ret)
: _msg("zlib: ")
{
switch (ret)
{
case Z_STREAM_ERROR:
_msg += "Z_STREAM_ERROR: ";
break;
case Z_DATA_ERROR:
_msg += "Z_DATA_ERROR: ";
break;
case Z_MEM_ERROR:
_msg += "Z_MEM_ERROR: ";
break;
case Z_VERSION_ERROR:
_msg += "Z_VERSION_ERROR: ";
break;
case Z_BUF_ERROR:
_msg += "Z_BUF_ERROR: ";
break;
default:
std::ostringstream oss;
oss << ret;
_msg += "[" + oss.str() + "]: ";
break;
}
_msg += zstrm_p->msg;
}
Exception(const std::string msg) : _msg(msg) {}
const char * what() const noexcept { return _msg.c_str(); }
private:
std::string _msg;
}; // class Exception
namespace detail
{
class z_stream_wrapper
: public z_stream
{
public:
z_stream_wrapper(bool _is_input, int _level, int _window_bits)
: is_input(_is_input)
{
this->zalloc = Z_NULL;
this->zfree = Z_NULL;
this->opaque = Z_NULL;
int ret;
if (is_input)
{
this->avail_in = 0;
this->next_in = Z_NULL;
ret = inflateInit2(this, _window_bits ? _window_bits : 15+32);
}
else
{
ret = deflateInit2(this, _level, Z_DEFLATED, _window_bits ? _window_bits : 15+16, 8, Z_DEFAULT_STRATEGY);
}
if (ret != Z_OK) throw Exception(this, ret);
}
~z_stream_wrapper()
{
if (is_input)
{
inflateEnd(this);
}
else
{
deflateEnd(this);
}
}
private:
bool is_input;
}; // class z_stream_wrapper
} // namespace detail
class istreambuf
: public std::streambuf
{
public:
istreambuf(std::streambuf * _sbuf_p,
std::size_t _buff_size = default_buff_size, bool _auto_detect = true, int _window_bits = 0)
: sbuf_p(_sbuf_p),
zstrm_p(nullptr),
buff_size(_buff_size),
auto_detect(_auto_detect),
auto_detect_run(false),
is_text(false),
window_bits(_window_bits)
{
assert(sbuf_p);
in_buff = new char [buff_size];
in_buff_start = in_buff;
in_buff_end = in_buff;
out_buff = new char [buff_size];
setg(out_buff, out_buff, out_buff);
}
istreambuf(const istreambuf &) = delete;
istreambuf(istreambuf &&) = default;
istreambuf & operator = (const istreambuf &) = delete;
istreambuf & operator = (istreambuf &&) = default;
virtual ~istreambuf()
{
delete [] in_buff;
delete [] out_buff;
if (zstrm_p) delete zstrm_p;
}
virtual std::streambuf::int_type underflow()
{
if (this->gptr() == this->egptr())
{
// pointers for free region in output buffer
char * out_buff_free_start = out_buff;
do
{
// read more input if none available
if (in_buff_start == in_buff_end)
{
// empty input buffer: refill from the start
in_buff_start = in_buff;
std::streamsize sz = sbuf_p->sgetn(in_buff, buff_size);
in_buff_end = in_buff + sz;
if (in_buff_end == in_buff_start) break; // end of input
}
// auto detect if the stream contains text or deflate data
if (auto_detect && ! auto_detect_run)
{
auto_detect_run = true;
unsigned char b0 = *reinterpret_cast< unsigned char * >(in_buff_start);
unsigned char b1 = *reinterpret_cast< unsigned char * >(in_buff_start + 1);
// Ref:
// http://en.wikipedia.org/wiki/Gzip
// http://stackoverflow.com/questions/9050260/what-does-a-zlib-header-look-like
is_text = ! (in_buff_start + 2 <= in_buff_end
&& ((b0 == 0x1F && b1 == 0x8B) // gzip header
|| (b0 == 0x78 && (b1 == 0x01 // zlib header
|| b1 == 0x9C
|| b1 == 0xDA))));
}
if (is_text)
{
// simply swap in_buff and out_buff, and adjust pointers
assert(in_buff_start == in_buff);
std::swap(in_buff, out_buff);
out_buff_free_start = in_buff_end;
in_buff_start = in_buff;
in_buff_end = in_buff;
}
else
{
// run inflate() on input
if (! zstrm_p) zstrm_p = new detail::z_stream_wrapper(true, Z_DEFAULT_COMPRESSION, window_bits);
zstrm_p->next_in = reinterpret_cast< decltype(zstrm_p->next_in) >(in_buff_start);
zstrm_p->avail_in = in_buff_end - in_buff_start;
zstrm_p->next_out = reinterpret_cast< decltype(zstrm_p->next_out) >(out_buff_free_start);
zstrm_p->avail_out = (out_buff + buff_size) - out_buff_free_start;
int ret = inflate(zstrm_p, Z_NO_FLUSH);
// process return code
if (ret != Z_OK && ret != Z_STREAM_END) throw Exception(zstrm_p, ret);
// update in&out pointers following inflate()
in_buff_start = reinterpret_cast< decltype(in_buff_start) >(zstrm_p->next_in);
in_buff_end = in_buff_start + zstrm_p->avail_in;
out_buff_free_start = reinterpret_cast< decltype(out_buff_free_start) >(zstrm_p->next_out);
assert(out_buff_free_start + zstrm_p->avail_out == out_buff + buff_size);
// if stream ended, deallocate inflator
if (ret == Z_STREAM_END)
{
delete zstrm_p;
zstrm_p = nullptr;
}
}
} while (out_buff_free_start == out_buff);
// 2 exit conditions:
// - end of input: there might or might not be output available
// - out_buff_free_start != out_buff: output available
this->setg(out_buff, out_buff, out_buff_free_start);
}
return this->gptr() == this->egptr()
? traits_type::eof()
: traits_type::to_int_type(*this->gptr());
}
private:
std::streambuf * sbuf_p;
char * in_buff;
char * in_buff_start;
char * in_buff_end;
char * out_buff;
detail::z_stream_wrapper * zstrm_p;
std::size_t buff_size;
bool auto_detect;
bool auto_detect_run;
bool is_text;
int window_bits;
static const std::size_t default_buff_size = (std::size_t)1 << 20;
}; // class istreambuf
class ostreambuf
: public std::streambuf
{
public:
ostreambuf(std::streambuf * _sbuf_p,
std::size_t _buff_size = default_buff_size, int _level = Z_DEFAULT_COMPRESSION, int _window_bits = 0)
: sbuf_p(_sbuf_p),
zstrm_p(new detail::z_stream_wrapper(false, _level, _window_bits)),
buff_size(_buff_size)
{
assert(sbuf_p);
in_buff = new char [buff_size];
out_buff = new char [buff_size];
setp(in_buff, in_buff + buff_size);
}
ostreambuf(const ostreambuf &) = delete;
ostreambuf(ostreambuf &&) = default;
ostreambuf & operator = (const ostreambuf &) = delete;
ostreambuf & operator = (ostreambuf &&) = default;
int deflate_loop(int flush)
{
while (true)
{
zstrm_p->next_out = reinterpret_cast< decltype(zstrm_p->next_out) >(out_buff);
zstrm_p->avail_out = buff_size;
int ret = deflate(zstrm_p, flush);
if (ret != Z_OK && ret != Z_STREAM_END && ret != Z_BUF_ERROR) throw Exception(zstrm_p, ret);
std::streamsize sz = sbuf_p->sputn(out_buff, reinterpret_cast< decltype(out_buff) >(zstrm_p->next_out) - out_buff);
if (sz != reinterpret_cast< decltype(out_buff) >(zstrm_p->next_out) - out_buff)
{
// there was an error in the sink stream
return -1;
}
if (ret == Z_STREAM_END || ret == Z_BUF_ERROR || sz == 0)
{
break;
}
}
return 0;
}
virtual ~ostreambuf()
{
// flush the zlib stream
//
// NOTE: Errors here (sync() return value not 0) are ignored, because we
// cannot throw in a destructor. This mirrors the behaviour of
// std::basic_filebuf::~basic_filebuf(). To see an exception on error,
// close the ofstream with an explicit call to close(), and do not rely
// on the implicit call in the destructor.
//
sync();
delete [] in_buff;
delete [] out_buff;
delete zstrm_p;
}
virtual std::streambuf::int_type overflow(std::streambuf::int_type c = traits_type::eof())
{
zstrm_p->next_in = reinterpret_cast< decltype(zstrm_p->next_in) >(pbase());
zstrm_p->avail_in = pptr() - pbase();
while (zstrm_p->avail_in > 0)
{
int r = deflate_loop(Z_NO_FLUSH);
if (r != 0)
{
setp(nullptr, nullptr);
return traits_type::eof();
}
}
setp(in_buff, in_buff + buff_size);
return traits_type::eq_int_type(c, traits_type::eof()) ? traits_type::eof() : sputc(c);
}
virtual int sync()
{
// first, call overflow to clear in_buff
overflow();
if (! pptr()) return -1;
// then, call deflate asking to finish the zlib stream
zstrm_p->next_in = nullptr;
zstrm_p->avail_in = 0;
if (deflate_loop(Z_FINISH) != 0) return -1;
deflateReset(zstrm_p);
return 0;
}
private:
std::streambuf * sbuf_p;
char * in_buff;
char * out_buff;
detail::z_stream_wrapper * zstrm_p;
std::size_t buff_size;
}; // class ostreambuf
class istream
: public std::istream
{
public:
istream(std::istream & is,
std::size_t _buff_size = default_buff_size, bool _auto_detect = true, int _window_bits = 0)
: std::istream(new istreambuf(is.rdbuf(), _buff_size, _auto_detect, _window_bits))
{
exceptions(std::ios_base::badbit);
}
explicit istream(std::streambuf * sbuf_p)
: std::istream(new istreambuf(sbuf_p))
{
exceptions(std::ios_base::badbit);
}
virtual ~istream()
{
delete rdbuf();
}
}; // class istream
class ostream
: public std::ostream
{
public:
ostream(std::ostream & os,
std::size_t _buff_size = default_buff_size, int _level = Z_DEFAULT_COMPRESSION, int _window_bits = 0)
: std::ostream(new ostreambuf(os.rdbuf(), _buff_size, _level, _window_bits))
{
exceptions(std::ios_base::badbit);
}
explicit ostream(std::streambuf * sbuf_p)
: std::ostream(new ostreambuf(sbuf_p))
{
exceptions(std::ios_base::badbit);
}
virtual ~ostream()
{
delete rdbuf();
}
}; // class ostream
namespace detail
{
template < typename FStream_Type >
struct strict_fstream_holder
{
strict_fstream_holder(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
: _fs(filename, mode)
{}
FStream_Type _fs;
}; // class strict_fstream_holder
} // namespace detail
class ifstream
: private detail::strict_fstream_holder< strict_fstream::ifstream >,
public std::istream
{
public:
explicit ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in)
: detail::strict_fstream_holder< strict_fstream::ifstream >(filename, mode),
std::istream(new istreambuf(_fs.rdbuf()))
{
exceptions(std::ios_base::badbit);
}
virtual ~ifstream()
{
if (rdbuf()) delete rdbuf();
}
}; // class ifstream
class ofstream
: private detail::strict_fstream_holder< strict_fstream::ofstream >,
public std::ostream
{
public:
explicit ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out)
: detail::strict_fstream_holder< strict_fstream::ofstream >(filename, mode | std::ios_base::binary),
std::ostream(new ostreambuf(_fs.rdbuf()))
{
exceptions(std::ios_base::badbit);
}
virtual ~ofstream()
{
if (rdbuf()) delete rdbuf();
}
}; // class ofstream
} // namespace zstr
#endif
<|endoftext|> |
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_UTILITIES_HH__
#define __RAPICORN_UTILITIES_HH__
#include <rapicorn-core.hh>
#include <typeinfo>
#if !defined __RAPICORN_CLIENTAPI_HH_ && !defined __RAPICORN_UITHREAD_HH__ && !defined __RAPICORN_BUILD__
#error Only <rapicorn.hh> can be included directly.
#endif
/* --- internally used macros --- */
#ifdef __RAPICORN_BUILD__
// convenience macros
#define MakeNamedCommand RAPICORN_MakeNamedCommand
#endif
namespace Rapicorn {
/* --- standard utlities --- */
//template<typename T> inline const T& min (const T &a, const T &b) { return ::std::min<T> (a, b); }
//template<typename T> inline const T& max (const T &a, const T &b) { return ::std::min<T> (a, b); }
using ::std::min;
using ::std::max;
inline double min (double a, int64 b) { return min<double> (a, b); }
inline double min (int64 a, double b) { return min<double> (a, b); }
inline double max (double a, int64 b) { return max<double> (a, b); }
inline double max (int64 a, double b) { return max<double> (a, b); }
/* --- exceptions --- */
struct Exception : std::exception {
public:
explicit Exception (const String &s1, const String &s2 = String(), const String &s3 = String(), const String &s4 = String(),
const String &s5 = String(), const String &s6 = String(), const String &s7 = String(), const String &s8 = String());
void set (const String &s);
virtual const char* what () const throw() { return reason ? reason : "out of memory"; }
/*Copy*/ Exception (const Exception &e);
/*Des*/ ~Exception () throw();
private:
Exception& operator= (const Exception&);
char *reason;
};
struct NullPointer : std::exception {};
/* allow 'dothrow' as function argument analogous to 'nothrow' */
extern const std::nothrow_t dothrow; /* indicate "with exception" semantics */
using std::nothrow_t;
using std::nothrow;
/* --- derivation assertions --- */
template<class Derived, class Base>
struct EnforceDerivedFrom {
EnforceDerivedFrom (Derived *derived = 0,
Base *base = 0)
{ base = derived; }
};
template<class Derived, class Base>
struct EnforceDerivedFrom<Derived*,Base*> {
EnforceDerivedFrom (Derived *derived = 0,
Base *base = 0)
{ base = derived; }
};
template<class Derived, class Base> void // ex: assert_derived_from<Child, Base>();
assert_derived_from (void)
{
EnforceDerivedFrom<Derived, Base> assertion;
}
/* --- derivation checks --- */
template<class Child, class Base>
class CheckDerivedFrom {
static bool is_derived (void*) { return false; }
static bool is_derived (Base*) { return true; }
public:
static bool is_derived () { return is_derived ((Child*) (0)); }
};
template<class Child, class Base>
struct CheckDerivedFrom<Child*,Base*> : CheckDerivedFrom<Child,Base> {};
template<class Derived, class Base> bool
is_derived () // ex: if (is_derived<Child, Base>()) ...; */
{
return CheckDerivedFrom<Derived,Base>::is_derived();
}
/* --- type dereferencing --- */
template<typename Type> struct Dereference;
template<typename Type> struct Dereference<Type*> {
typedef Type* Pointer;
typedef Type Value;
};
template<typename Type> struct Dereference<Type*const> {
typedef Type* Pointer;
typedef Type Value;
};
template<typename Type> struct Dereference<const Type*> {
typedef const Type* Pointer;
typedef const Type Value;
};
template<typename Type> struct Dereference<const Type*const> {
typedef const Type* Pointer;
typedef const Type Value;
};
/* --- PointerIterator - iterator object from pointer --- */
template<typename Value>
class PointerIterator {
protected:
Value *current;
public:
typedef std::random_access_iterator_tag iterator_category;
typedef Value value_type;
typedef ptrdiff_t difference_type;
typedef Value* pointer;
typedef Value& reference;
public:
explicit PointerIterator () : current() {}
explicit PointerIterator (value_type *v) : current (v) {}
/*Copy*/ PointerIterator (const PointerIterator &x) : current (x.current) {}
Value* base() const { return current; }
reference operator* () const { return *current; }
pointer operator-> () const { return &(operator*()); }
PointerIterator& operator++ () { ++current; return *this; }
PointerIterator operator++ (int) { PointerIterator tmp = *this; ++current; return tmp; }
PointerIterator& operator-- () { --current; return *this; }
PointerIterator operator-- (int) { PointerIterator tmp = *this; --current; return tmp; }
PointerIterator operator+ (difference_type n) const { return PointerIterator (current + n); }
PointerIterator& operator+= (difference_type n) { current += n; return *this; }
PointerIterator operator- (difference_type n) const { return PointerIterator (current - n); }
PointerIterator& operator-= (difference_type n) { current -= n; return *this; }
reference operator[] (difference_type n) const { return *(*this + n); }
};
template<typename Value> PointerIterator<Value>
pointer_iterator (Value * const val)
{ return PointerIterator<Value> (val); }
template<typename Value> inline bool
operator== (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() == y.base(); }
template<typename Value> inline bool
operator!= (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() != y.base(); }
template<typename Value> inline bool
operator< (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() < y.base(); }
template<typename Value> inline bool
operator<= (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() <= y.base(); }
template<typename Value> inline bool
operator> (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() > y.base(); }
template<typename Value> inline bool
operator>= (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() >= y.base(); }
template<typename Value> inline typename PointerIterator<Value>::difference_type
operator- (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() - y.base(); }
template<typename Value> inline PointerIterator<Value>
operator+ (typename PointerIterator<Value>::difference_type n, const PointerIterator<Value> &x)
{ return x.operator+ (n); }
/* --- ValueIterator - dereferencing iterator --- */
template<class Iterator> struct ValueIterator : public Iterator {
typedef Iterator iterator_type;
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::difference_type difference_type;
typedef typename Iterator::value_type pointer;
typedef typename Dereference<pointer>::Value value_type;
typedef value_type& reference;
Iterator base () const { return *this; }
reference operator* () const { return *Iterator::operator*(); }
pointer operator-> () const { return *Iterator::operator->(); }
ValueIterator& operator= (const Iterator &it) { Iterator::operator= (it); return *this; }
explicit ValueIterator (Iterator it) : Iterator (it) {}
/*Copy*/ ValueIterator (const ValueIterator &dup) : Iterator (dup.base()) {}
/*Con*/ ValueIterator () : Iterator() {}
template<typename Iter>
/*Con*/ ValueIterator (const ValueIterator<Iter> &src) : Iterator (src.base()) {}
};
template<class Iterator> ValueIterator<Iterator>
value_iterator (const Iterator &iter)
{ return ValueIterator<Iterator> (iter); }
template<class Iterator> inline bool
operator== (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() == y.base(); }
template<class Iterator> inline bool
operator!= (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() != y.base(); }
template<class Iterator> inline bool
operator< (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() < y.base(); }
template<class Iterator> inline bool
operator<= (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() <= y.base(); }
template<class Iterator> inline bool
operator> (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() > y.base(); }
template<class Iterator> inline bool
operator>= (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() >= y.base(); }
template<class Iterator> inline typename ValueIterator<Iterator>::difference_type
operator- (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() - y.base(); }
template<class Iterator> inline ValueIterator<Iterator>
operator+ (typename ValueIterator<Iterator>::difference_type n, const ValueIterator<Iterator> &x)
{ return x.operator+ (n); }
/* --- IteratorRange (iterator range wrappers) --- */
template<class Iterator> class IteratorRange {
Iterator ibegin, iend;
public:
typedef Iterator iterator;
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::difference_type difference_type;
typedef typename Iterator::reference reference;
typedef typename Iterator::pointer pointer;
explicit IteratorRange (const Iterator &cbegin, const Iterator &cend) :
ibegin (cbegin), iend (cend)
{}
explicit IteratorRange()
{}
iterator begin() const { return ibegin; }
iterator end() const { return iend; }
bool done() const { return ibegin == iend; }
bool has_next() const { return ibegin != iend; }
reference operator* () const { return ibegin.operator*(); }
pointer operator-> () const { return ibegin.operator->(); }
IteratorRange& operator++ () { ibegin.operator++(); return *this; }
IteratorRange operator++ (int) { IteratorRange dup (*this); ibegin.operator++(); return dup; }
bool operator== (const IteratorRange &w) const
{
return ibegin == w.begin && iend == w.end;
}
bool operator!= (const IteratorRange &w) const
{
return ibegin != w.begin || iend != w.end;
}
};
template<class Iterator> IteratorRange<Iterator>
iterator_range (const Iterator &begin, const Iterator &end)
{
return IteratorRange<Iterator> (begin, end);
}
/* --- ValueIteratorRange (iterator range wrappers) --- */
template<class Iterator> class ValueIteratorRange {
Iterator ibegin, iend;
public:
typedef Iterator iterator;
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type pointer;
// typedef typeof (*(pointer) 0) value_type;
typedef typename Dereference<pointer>::Value value_type;
typedef typename Iterator::difference_type difference_type;
typedef value_type& reference;
explicit ValueIteratorRange (const Iterator &cbegin, const Iterator &cend) :
ibegin (cbegin), iend (cend)
{}
explicit ValueIteratorRange()
{}
iterator begin() const { return ibegin; }
iterator end() const { return iend; }
bool done() const { return ibegin == iend; }
bool has_next() const { return ibegin != iend; }
reference operator* () const { return *ibegin.operator*(); }
pointer operator-> () const { return ibegin.operator*(); }
ValueIteratorRange& operator++ () { ibegin.operator++(); return *this; }
ValueIteratorRange operator++ (int) { ValueIteratorRange dup (*this); ibegin.operator++(); return dup; }
bool operator== (const ValueIteratorRange &w) const
{
return ibegin == w.begin && iend == w.end;
}
bool operator!= (const ValueIteratorRange &w) const
{
return ibegin != w.begin || iend != w.end;
}
};
template<class Iterator> ValueIteratorRange<Iterator>
value_iterator_range (const Iterator &begin, const Iterator &end)
{
return ValueIteratorRange<Iterator> (begin, end);
}
} // Rapicorn
#endif /* __RAPICORN_UTILITIES_HH__ */
<commit_msg>UI: use 'noexcept' instead of deprecated old throw() syntax<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_UTILITIES_HH__
#define __RAPICORN_UTILITIES_HH__
#include <rapicorn-core.hh>
#include <typeinfo>
#if !defined __RAPICORN_CLIENTAPI_HH_ && !defined __RAPICORN_UITHREAD_HH__ && !defined __RAPICORN_BUILD__
#error Only <rapicorn.hh> can be included directly.
#endif
/* --- internally used macros --- */
#ifdef __RAPICORN_BUILD__
// convenience macros
#define MakeNamedCommand RAPICORN_MakeNamedCommand
#endif
namespace Rapicorn {
/* --- standard utlities --- */
//template<typename T> inline const T& min (const T &a, const T &b) { return ::std::min<T> (a, b); }
//template<typename T> inline const T& max (const T &a, const T &b) { return ::std::min<T> (a, b); }
using ::std::min;
using ::std::max;
inline double min (double a, int64 b) { return min<double> (a, b); }
inline double min (int64 a, double b) { return min<double> (a, b); }
inline double max (double a, int64 b) { return max<double> (a, b); }
inline double max (int64 a, double b) { return max<double> (a, b); }
/* --- exceptions --- */
struct Exception : std::exception {
public:
explicit Exception (const String &s1, const String &s2 = String(), const String &s3 = String(), const String &s4 = String(),
const String &s5 = String(), const String &s6 = String(), const String &s7 = String(), const String &s8 = String());
void set (const String &s);
virtual const char* what () const noexcept { return reason ? reason : "out of memory"; }
/*Copy*/ Exception (const Exception &e);
/*Des*/ ~Exception () noexcept;
private:
Exception& operator= (const Exception&);
char *reason;
};
struct NullPointer : std::exception {};
/* allow 'dothrow' as function argument analogous to 'nothrow' */
extern const std::nothrow_t dothrow; /* indicate "with exception" semantics */
using std::nothrow_t;
using std::nothrow;
/* --- derivation assertions --- */
template<class Derived, class Base>
struct EnforceDerivedFrom {
EnforceDerivedFrom (Derived *derived = 0,
Base *base = 0)
{ base = derived; }
};
template<class Derived, class Base>
struct EnforceDerivedFrom<Derived*,Base*> {
EnforceDerivedFrom (Derived *derived = 0,
Base *base = 0)
{ base = derived; }
};
template<class Derived, class Base> void // ex: assert_derived_from<Child, Base>();
assert_derived_from (void)
{
EnforceDerivedFrom<Derived, Base> assertion;
}
/* --- derivation checks --- */
template<class Child, class Base>
class CheckDerivedFrom {
static bool is_derived (void*) { return false; }
static bool is_derived (Base*) { return true; }
public:
static bool is_derived () { return is_derived ((Child*) (0)); }
};
template<class Child, class Base>
struct CheckDerivedFrom<Child*,Base*> : CheckDerivedFrom<Child,Base> {};
template<class Derived, class Base> bool
is_derived () // ex: if (is_derived<Child, Base>()) ...; */
{
return CheckDerivedFrom<Derived,Base>::is_derived();
}
/* --- type dereferencing --- */
template<typename Type> struct Dereference;
template<typename Type> struct Dereference<Type*> {
typedef Type* Pointer;
typedef Type Value;
};
template<typename Type> struct Dereference<Type*const> {
typedef Type* Pointer;
typedef Type Value;
};
template<typename Type> struct Dereference<const Type*> {
typedef const Type* Pointer;
typedef const Type Value;
};
template<typename Type> struct Dereference<const Type*const> {
typedef const Type* Pointer;
typedef const Type Value;
};
/* --- PointerIterator - iterator object from pointer --- */
template<typename Value>
class PointerIterator {
protected:
Value *current;
public:
typedef std::random_access_iterator_tag iterator_category;
typedef Value value_type;
typedef ptrdiff_t difference_type;
typedef Value* pointer;
typedef Value& reference;
public:
explicit PointerIterator () : current() {}
explicit PointerIterator (value_type *v) : current (v) {}
/*Copy*/ PointerIterator (const PointerIterator &x) : current (x.current) {}
Value* base() const { return current; }
reference operator* () const { return *current; }
pointer operator-> () const { return &(operator*()); }
PointerIterator& operator++ () { ++current; return *this; }
PointerIterator operator++ (int) { PointerIterator tmp = *this; ++current; return tmp; }
PointerIterator& operator-- () { --current; return *this; }
PointerIterator operator-- (int) { PointerIterator tmp = *this; --current; return tmp; }
PointerIterator operator+ (difference_type n) const { return PointerIterator (current + n); }
PointerIterator& operator+= (difference_type n) { current += n; return *this; }
PointerIterator operator- (difference_type n) const { return PointerIterator (current - n); }
PointerIterator& operator-= (difference_type n) { current -= n; return *this; }
reference operator[] (difference_type n) const { return *(*this + n); }
};
template<typename Value> PointerIterator<Value>
pointer_iterator (Value * const val)
{ return PointerIterator<Value> (val); }
template<typename Value> inline bool
operator== (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() == y.base(); }
template<typename Value> inline bool
operator!= (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() != y.base(); }
template<typename Value> inline bool
operator< (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() < y.base(); }
template<typename Value> inline bool
operator<= (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() <= y.base(); }
template<typename Value> inline bool
operator> (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() > y.base(); }
template<typename Value> inline bool
operator>= (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() >= y.base(); }
template<typename Value> inline typename PointerIterator<Value>::difference_type
operator- (const PointerIterator<Value> &x, const PointerIterator<Value> &y)
{ return x.base() - y.base(); }
template<typename Value> inline PointerIterator<Value>
operator+ (typename PointerIterator<Value>::difference_type n, const PointerIterator<Value> &x)
{ return x.operator+ (n); }
/* --- ValueIterator - dereferencing iterator --- */
template<class Iterator> struct ValueIterator : public Iterator {
typedef Iterator iterator_type;
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::difference_type difference_type;
typedef typename Iterator::value_type pointer;
typedef typename Dereference<pointer>::Value value_type;
typedef value_type& reference;
Iterator base () const { return *this; }
reference operator* () const { return *Iterator::operator*(); }
pointer operator-> () const { return *Iterator::operator->(); }
ValueIterator& operator= (const Iterator &it) { Iterator::operator= (it); return *this; }
explicit ValueIterator (Iterator it) : Iterator (it) {}
/*Copy*/ ValueIterator (const ValueIterator &dup) : Iterator (dup.base()) {}
/*Con*/ ValueIterator () : Iterator() {}
template<typename Iter>
/*Con*/ ValueIterator (const ValueIterator<Iter> &src) : Iterator (src.base()) {}
};
template<class Iterator> ValueIterator<Iterator>
value_iterator (const Iterator &iter)
{ return ValueIterator<Iterator> (iter); }
template<class Iterator> inline bool
operator== (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() == y.base(); }
template<class Iterator> inline bool
operator!= (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() != y.base(); }
template<class Iterator> inline bool
operator< (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() < y.base(); }
template<class Iterator> inline bool
operator<= (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() <= y.base(); }
template<class Iterator> inline bool
operator> (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() > y.base(); }
template<class Iterator> inline bool
operator>= (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() >= y.base(); }
template<class Iterator> inline typename ValueIterator<Iterator>::difference_type
operator- (const ValueIterator<Iterator> &x, const ValueIterator<Iterator> &y)
{ return x.base() - y.base(); }
template<class Iterator> inline ValueIterator<Iterator>
operator+ (typename ValueIterator<Iterator>::difference_type n, const ValueIterator<Iterator> &x)
{ return x.operator+ (n); }
/* --- IteratorRange (iterator range wrappers) --- */
template<class Iterator> class IteratorRange {
Iterator ibegin, iend;
public:
typedef Iterator iterator;
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::difference_type difference_type;
typedef typename Iterator::reference reference;
typedef typename Iterator::pointer pointer;
explicit IteratorRange (const Iterator &cbegin, const Iterator &cend) :
ibegin (cbegin), iend (cend)
{}
explicit IteratorRange()
{}
iterator begin() const { return ibegin; }
iterator end() const { return iend; }
bool done() const { return ibegin == iend; }
bool has_next() const { return ibegin != iend; }
reference operator* () const { return ibegin.operator*(); }
pointer operator-> () const { return ibegin.operator->(); }
IteratorRange& operator++ () { ibegin.operator++(); return *this; }
IteratorRange operator++ (int) { IteratorRange dup (*this); ibegin.operator++(); return dup; }
bool operator== (const IteratorRange &w) const
{
return ibegin == w.begin && iend == w.end;
}
bool operator!= (const IteratorRange &w) const
{
return ibegin != w.begin || iend != w.end;
}
};
template<class Iterator> IteratorRange<Iterator>
iterator_range (const Iterator &begin, const Iterator &end)
{
return IteratorRange<Iterator> (begin, end);
}
/* --- ValueIteratorRange (iterator range wrappers) --- */
template<class Iterator> class ValueIteratorRange {
Iterator ibegin, iend;
public:
typedef Iterator iterator;
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type pointer;
// typedef typeof (*(pointer) 0) value_type;
typedef typename Dereference<pointer>::Value value_type;
typedef typename Iterator::difference_type difference_type;
typedef value_type& reference;
explicit ValueIteratorRange (const Iterator &cbegin, const Iterator &cend) :
ibegin (cbegin), iend (cend)
{}
explicit ValueIteratorRange()
{}
iterator begin() const { return ibegin; }
iterator end() const { return iend; }
bool done() const { return ibegin == iend; }
bool has_next() const { return ibegin != iend; }
reference operator* () const { return *ibegin.operator*(); }
pointer operator-> () const { return ibegin.operator*(); }
ValueIteratorRange& operator++ () { ibegin.operator++(); return *this; }
ValueIteratorRange operator++ (int) { ValueIteratorRange dup (*this); ibegin.operator++(); return dup; }
bool operator== (const ValueIteratorRange &w) const
{
return ibegin == w.begin && iend == w.end;
}
bool operator!= (const ValueIteratorRange &w) const
{
return ibegin != w.begin || iend != w.end;
}
};
template<class Iterator> ValueIteratorRange<Iterator>
value_iterator_range (const Iterator &begin, const Iterator &end)
{
return ValueIteratorRange<Iterator> (begin, end);
}
} // Rapicorn
#endif /* __RAPICORN_UTILITIES_HH__ */
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> i = {2,3,4,5,6};
for(auto it = i.begin(); it!=i.end(); ++it)
{
if(*it > 3)
{
i.erase(it);
}
/*if(*it == 5)
{
i.erase(it);
}*/
}
for(auto it = i.begin(); it!=i.end(); ++it)
{
cout<<*it<<" ";
}
return 1;
}<commit_msg>partial implementation of faster non-messy dynamic element elimination from a vector<commit_after>#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> i = {2,3,4,5,6};
for(auto it = i.begin(); it!=i.end(); ++it)
{
if(*it > 3)
{
*it = i.back();
}
/*if(*it == 5)
{
i.erase(it);
}*/
}
for(auto it = i.begin(); it!=i.end(); ++it)
{
cout<<*it<<" ";
}
return 1;
}<|endoftext|> |
<commit_before>// Copyright (c) 2011-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/wallet.h>
#include <qt/receivecoinsdialog.h>
#include <qt/forms/ui_receivecoinsdialog.h>
#include <qt/addresstablemodel.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/receiverequestdialog.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/walletmodel.h>
#include <QAction>
#include <QCursor>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiveCoinsDialog),
columnResizingFixer(nullptr),
model(nullptr),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->clearButton->setIcon(QIcon());
ui->receiveButton->setIcon(QIcon());
ui->showRequestButton->setIcon(QIcon());
ui->removeRequestButton->setIcon(QIcon());
} else {
ui->clearButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
ui->receiveButton->setIcon(_platformStyle->SingleColorIcon(":/icons/receiving_addresses"));
ui->showRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/edit"));
ui->removeRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
}
// context menu actions
QAction *copyURIAction = new QAction(tr("Copy URI"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyMessageAction = new QAction(tr("Copy message"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyURIAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(copyAmountAction);
// context menu signals
connect(ui->recentRequestsView, &QWidget::customContextMenuRequested, this, &ReceiveCoinsDialog::showMenu);
connect(copyURIAction, &QAction::triggered, this, &ReceiveCoinsDialog::copyURI);
connect(copyLabelAction, &QAction::triggered, this, &ReceiveCoinsDialog::copyLabel);
connect(copyMessageAction, &QAction::triggered, this, &ReceiveCoinsDialog::copyMessage);
connect(copyAmountAction, &QAction::triggered, this, &ReceiveCoinsDialog::copyAmount);
connect(ui->clearButton, &QPushButton::clicked, this, &ReceiveCoinsDialog::clear);
}
void ReceiveCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
_model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);
connect(_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &ReceiveCoinsDialog::updateDisplayUnit);
updateDisplayUnit();
QTableView* tableView = ui->recentRequestsView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(_model->getRecentRequestsTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Amount, AMOUNT_MINIMUM_COLUMN_WIDTH);
connect(tableView->selectionModel(),
&QItemSelectionModel::selectionChanged, this,
&ReceiveCoinsDialog::recentRequestsView_selectionChanged);
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);
if (model->wallet().getDefaultAddressType() == OutputType::BECH32) {
ui->useBech32->setCheckState(Qt::Checked);
} else {
ui->useBech32->setCheckState(Qt::Unchecked);
}
// Set the button to be enabled or disabled based on whether the wallet can give out new addresses.
ui->receiveButton->setEnabled(model->wallet().canGetAddresses());
// Enable/disable the receive button if the wallet is now able/unable to give out new addresses.
connect(model, &WalletModel::canGetAddressesChanged, [this] {
ui->receiveButton->setEnabled(model->wallet().canGetAddresses());
});
}
}
ReceiveCoinsDialog::~ReceiveCoinsDialog()
{
delete ui;
}
void ReceiveCoinsDialog::clear()
{
ui->reqAmount->clear();
ui->reqLabel->setText("");
ui->reqMessage->setText("");
updateDisplayUnit();
}
void ReceiveCoinsDialog::reject()
{
clear();
}
void ReceiveCoinsDialog::accept()
{
clear();
}
void ReceiveCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void ReceiveCoinsDialog::on_receiveButton_clicked()
{
if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())
return;
QString address;
QString label = ui->reqLabel->text();
/* Generate new receiving address */
OutputType address_type;
if (ui->useBech32->isChecked()) {
address_type = OutputType::BECH32;
} else {
address_type = model->wallet().getDefaultAddressType();
if (address_type == OutputType::BECH32) {
address_type = OutputType::P2SH_SEGWIT;
}
}
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type);
switch(model->getAddressTableModel()->getEditStatus())
{
case AddressTableModel::EditStatus::OK: {
// Success
SendCoinsRecipient info(address, label,
ui->reqAmount->value(), ui->reqMessage->text());
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModel(model);
dialog->setInfo(info);
dialog->show();
/* Store request for later reference */
model->getRecentRequestsTableModel()->addNewRequest(info);
break;
}
case AddressTableModel::EditStatus::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::EditStatus::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not generate new %1 address").arg(QString::fromStdString(FormatOutputType(address_type))),
QMessageBox::Ok, QMessageBox::Ok);
break;
// These aren't valid return values for our action
case AddressTableModel::EditStatus::INVALID_ADDRESS:
case AddressTableModel::EditStatus::DUPLICATE_ADDRESS:
case AddressTableModel::EditStatus::NO_CHANGES:
assert(false);
}
clear();
}
void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setModel(model);
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
// Enable Show/Remove buttons only if anything is selected.
bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();
ui->showRequestButton->setEnabled(enable);
ui->removeRequestButton->setEnabled(enable);
}
void ReceiveCoinsDialog::on_showRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
for (const QModelIndex& index : selection) {
on_recentRequestsView_doubleClicked(index);
}
}
void ReceiveCoinsDialog::on_removeRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());
}
// We override the virtual resizeEvent of the QWidget to adjust tables column
// sizes as the tables width is proportional to the dialogs width.
void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);
}
QModelIndex ReceiveCoinsDialog::selectedRow()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return QModelIndex();
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return QModelIndex();
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
return firstIndex;
}
// copy column of selected row to clipboard
void ReceiveCoinsDialog::copyColumnToClipboard(int column)
{
QModelIndex firstIndex = selectedRow();
if (!firstIndex.isValid()) {
return;
}
GUIUtil::setClipboard(model->getRecentRequestsTableModel()->index(firstIndex.row(), column).data(Qt::EditRole).toString());
}
// context menu
void ReceiveCoinsDialog::showMenu(const QPoint &point)
{
if (!selectedRow().isValid()) {
return;
}
contextMenu->exec(QCursor::pos());
}
// context menu action: copy URI
void ReceiveCoinsDialog::copyURI()
{
QModelIndex sel = selectedRow();
if (!sel.isValid()) {
return;
}
const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel();
const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient);
GUIUtil::setClipboard(uri);
}
// context menu action: copy label
void ReceiveCoinsDialog::copyLabel()
{
copyColumnToClipboard(RecentRequestsTableModel::Label);
}
// context menu action: copy message
void ReceiveCoinsDialog::copyMessage()
{
copyColumnToClipboard(RecentRequestsTableModel::Message);
}
// context menu action: copy amount
void ReceiveCoinsDialog::copyAmount()
{
copyColumnToClipboard(RecentRequestsTableModel::Amount);
}
<commit_msg>Disable generating BECH32 addresses from the UI<commit_after>// Copyright (c) 2011-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/wallet.h>
#include <qt/receivecoinsdialog.h>
#include <qt/forms/ui_receivecoinsdialog.h>
#include <qt/addresstablemodel.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/receiverequestdialog.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/walletmodel.h>
#include <QAction>
#include <QCursor>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiveCoinsDialog),
columnResizingFixer(nullptr),
model(nullptr),
platformStyle(_platformStyle)
{
ui->setupUi(this);
if (!_platformStyle->getImagesOnButtons()) {
ui->clearButton->setIcon(QIcon());
ui->receiveButton->setIcon(QIcon());
ui->showRequestButton->setIcon(QIcon());
ui->removeRequestButton->setIcon(QIcon());
} else {
ui->clearButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
ui->receiveButton->setIcon(_platformStyle->SingleColorIcon(":/icons/receiving_addresses"));
ui->showRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/edit"));
ui->removeRequestButton->setIcon(_platformStyle->SingleColorIcon(":/icons/remove"));
}
// context menu actions
QAction *copyURIAction = new QAction(tr("Copy URI"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyMessageAction = new QAction(tr("Copy message"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyURIAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(copyAmountAction);
// context menu signals
connect(ui->recentRequestsView, &QWidget::customContextMenuRequested, this, &ReceiveCoinsDialog::showMenu);
connect(copyURIAction, &QAction::triggered, this, &ReceiveCoinsDialog::copyURI);
connect(copyLabelAction, &QAction::triggered, this, &ReceiveCoinsDialog::copyLabel);
connect(copyMessageAction, &QAction::triggered, this, &ReceiveCoinsDialog::copyMessage);
connect(copyAmountAction, &QAction::triggered, this, &ReceiveCoinsDialog::copyAmount);
connect(ui->clearButton, &QPushButton::clicked, this, &ReceiveCoinsDialog::clear);
}
void ReceiveCoinsDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel())
{
_model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);
connect(_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &ReceiveCoinsDialog::updateDisplayUnit);
updateDisplayUnit();
QTableView* tableView = ui->recentRequestsView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(_model->getRecentRequestsTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);
tableView->setColumnWidth(RecentRequestsTableModel::Amount, AMOUNT_MINIMUM_COLUMN_WIDTH);
connect(tableView->selectionModel(),
&QItemSelectionModel::selectionChanged, this,
&ReceiveCoinsDialog::recentRequestsView_selectionChanged);
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);
if (model->wallet().getDefaultAddressType() == OutputType::BECH32) {
ui->useBech32->setCheckState(Qt::Checked);
} else {
ui->useBech32->setCheckState(Qt::Unchecked);
// Dogecoin: Don't allow the user to generate BECH32 addresses as we don't support them except for test networks.
// If you need to test, override the default on the command line.
ui->useBech32->setEnabled(false);
}
// Set the button to be enabled or disabled based on whether the wallet can give out new addresses.
ui->receiveButton->setEnabled(model->wallet().canGetAddresses());
// Enable/disable the receive button if the wallet is now able/unable to give out new addresses.
connect(model, &WalletModel::canGetAddressesChanged, [this] {
ui->receiveButton->setEnabled(model->wallet().canGetAddresses());
});
}
}
ReceiveCoinsDialog::~ReceiveCoinsDialog()
{
delete ui;
}
void ReceiveCoinsDialog::clear()
{
ui->reqAmount->clear();
ui->reqLabel->setText("");
ui->reqMessage->setText("");
updateDisplayUnit();
}
void ReceiveCoinsDialog::reject()
{
clear();
}
void ReceiveCoinsDialog::accept()
{
clear();
}
void ReceiveCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void ReceiveCoinsDialog::on_receiveButton_clicked()
{
if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())
return;
QString address;
QString label = ui->reqLabel->text();
/* Generate new receiving address */
OutputType address_type;
if (ui->useBech32->isChecked()) {
address_type = OutputType::BECH32;
} else {
address_type = model->wallet().getDefaultAddressType();
if (address_type == OutputType::BECH32) {
address_type = OutputType::P2SH_SEGWIT;
}
}
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type);
switch(model->getAddressTableModel()->getEditStatus())
{
case AddressTableModel::EditStatus::OK: {
// Success
SendCoinsRecipient info(address, label,
ui->reqAmount->value(), ui->reqMessage->text());
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModel(model);
dialog->setInfo(info);
dialog->show();
/* Store request for later reference */
model->getRecentRequestsTableModel()->addNewRequest(info);
break;
}
case AddressTableModel::EditStatus::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::EditStatus::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not generate new %1 address").arg(QString::fromStdString(FormatOutputType(address_type))),
QMessageBox::Ok, QMessageBox::Ok);
break;
// These aren't valid return values for our action
case AddressTableModel::EditStatus::INVALID_ADDRESS:
case AddressTableModel::EditStatus::DUPLICATE_ADDRESS:
case AddressTableModel::EditStatus::NO_CHANGES:
assert(false);
}
clear();
}
void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setModel(model);
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
// Enable Show/Remove buttons only if anything is selected.
bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();
ui->showRequestButton->setEnabled(enable);
ui->removeRequestButton->setEnabled(enable);
}
void ReceiveCoinsDialog::on_showRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
for (const QModelIndex& index : selection) {
on_recentRequestsView_doubleClicked(index);
}
}
void ReceiveCoinsDialog::on_removeRequestButton_clicked()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return;
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());
}
// We override the virtual resizeEvent of the QWidget to adjust tables column
// sizes as the tables width is proportional to the dialogs width.
void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);
}
QModelIndex ReceiveCoinsDialog::selectedRow()
{
if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())
return QModelIndex();
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
if(selection.empty())
return QModelIndex();
// correct for selection mode ContiguousSelection
QModelIndex firstIndex = selection.at(0);
return firstIndex;
}
// copy column of selected row to clipboard
void ReceiveCoinsDialog::copyColumnToClipboard(int column)
{
QModelIndex firstIndex = selectedRow();
if (!firstIndex.isValid()) {
return;
}
GUIUtil::setClipboard(model->getRecentRequestsTableModel()->index(firstIndex.row(), column).data(Qt::EditRole).toString());
}
// context menu
void ReceiveCoinsDialog::showMenu(const QPoint &point)
{
if (!selectedRow().isValid()) {
return;
}
contextMenu->exec(QCursor::pos());
}
// context menu action: copy URI
void ReceiveCoinsDialog::copyURI()
{
QModelIndex sel = selectedRow();
if (!sel.isValid()) {
return;
}
const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel();
const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient);
GUIUtil::setClipboard(uri);
}
// context menu action: copy label
void ReceiveCoinsDialog::copyLabel()
{
copyColumnToClipboard(RecentRequestsTableModel::Label);
}
// context menu action: copy message
void ReceiveCoinsDialog::copyMessage()
{
copyColumnToClipboard(RecentRequestsTableModel::Message);
}
// context menu action: copy amount
void ReceiveCoinsDialog::copyAmount()
{
copyColumnToClipboard(RecentRequestsTableModel::Amount);
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "FedReplicaManager.h"
#include "ReplicaThread.h"
#include "Nebula.h"
#include "Client.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
const time_t FedReplicaManager::xmlrpc_timeout_ms = 10000;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
FedReplicaManager::FedReplicaManager(LogDB * d): ReplicaManager(), logdb(d)
{
pthread_mutex_init(&mutex, 0);
am.addListener(this);
};
/* -------------------------------------------------------------------------- */
FedReplicaManager::~FedReplicaManager()
{
Nebula& nd = Nebula::instance();
std::map<int, ZoneServers *>::iterator it;
for ( it = zones.begin() ; it != zones.end() ; ++it )
{
delete it->second;
}
zones.clear();
if ( nd.is_federation_master() )
{
stop_replica_threads();
}
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::apply_log_record(int index, int prev,
const std::string& sql)
{
int rc;
pthread_mutex_lock(&mutex);
int last_index = logdb->last_federated();
if ( prev != last_index )
{
rc = last_index;
pthread_mutex_unlock(&mutex);
return rc;
}
std::ostringstream oss(sql);
if ( logdb->exec_federated_wr(oss, index) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
pthread_mutex_unlock(&mutex);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * frm_loop(void *arg)
{
FedReplicaManager * fedrm;
if ( arg == 0 )
{
return 0;
}
fedrm = static_cast<FedReplicaManager *>(arg);
NebulaLog::log("FRM",Log::INFO,"Federation Replica Manger started.");
fedrm->am.loop();
NebulaLog::log("FRM",Log::INFO,"Federation Replica Manger stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::start()
{
int rc;
pthread_attr_t pattr;
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
NebulaLog::log("FRM",Log::INFO,"Starting Federation Replica Manager...");
rc = pthread_create(&frm_thread, &pattr, frm_loop,(void *) this);
return rc;
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::finalize_action(const ActionRequest& ar)
{
NebulaLog::log("FRM", Log::INFO, "Federation Replica Manager...");
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::update_zones(std::vector<int>& zone_ids)
{
Nebula& nd = Nebula::instance();
ZonePool * zpool = nd.get_zonepool();
vector<int>::iterator it;
int zone_id = nd.get_zone_id();
if ( zpool->list_zones(zone_ids) != 0 )
{
return;
}
pthread_mutex_lock(&mutex);
int last_index = logdb->last_federated();
zones.clear();
for (it = zone_ids.begin() ; it != zone_ids.end(); )
{
if ( *it == zone_id )
{
it = zone_ids.erase(it);
}
else
{
Zone * zone = zpool->get(*it, true);
if ( zone == 0 )
{
it = zone_ids.erase(it);
}
else
{
std::string zedp;
zone->get_template_attribute("ENDPOINT", zedp);
zone->unlock();
ZoneServers * zs = new ZoneServers(*it, last_index, zedp);
zones.insert(make_pair(*it, zs));
++it;
}
}
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::add_zone(int zone_id)
{
std::ostringstream oss;
std::string zedp;
Nebula& nd = Nebula::instance();
ZonePool * zpool = nd.get_zonepool();
Zone * zone = zpool->get(zone_id, true);
if ( zone == 0 )
{
return;
}
zone->get_template_attribute("ENDPOINT", zedp);
zone->unlock();
pthread_mutex_lock(&mutex);
int last_index = logdb->last_federated();
ZoneServers * zs = new ZoneServers(zone_id, last_index, zedp);
zones.insert(make_pair(zone_id, zs));
oss << "Starting federation replication thread for slave: " << zone_id;
NebulaLog::log("FRM", Log::INFO, oss);
add_replica_thread(zone_id);
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::delete_zone(int zone_id)
{
std::ostringstream oss;
std::map<int, ZoneServers *>::iterator it;
pthread_mutex_lock(&mutex);
it = zones.find(zone_id);
if ( it == zones.end() )
{
return;
}
delete it->second;
zones.erase(it);
oss << "Stopping replication thread for slave: " << zone_id;
NebulaLog::log("FRM", Log::INFO, oss);
delete_replica_thread(zone_id);
pthread_mutex_unlock(&mutex);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ReplicaThread * FedReplicaManager::thread_factory(int zone_id)
{
return new FedReplicaThread(zone_id);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::get_next_record(int zone_id, std::string& zedp,
LogDBRecord& lr, std::string& error)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it == zones.end() )
{
pthread_mutex_unlock(&mutex);
return -1;
}
ZoneServers * zs = it->second;
zedp = zs->endpoint;
if ( zs->next == -1 )
{
zs->next= logdb->last_federated();
}
if ( zs->last == zs->next )
{
pthread_mutex_unlock(&mutex);
return -1;
}
int rc = logdb->get_log_record(zs->next, lr);
if ( rc == -1 )
{
std::ostringstream oss;
oss << "Failed to load federation log record " << zs->next
<< " for zone " << zs->zone_id;
error = oss.str();
}
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::replicate_success(int zone_id)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it == zones.end() )
{
pthread_mutex_unlock(&mutex);
return;
}
ZoneServers * zs = it->second;
zs->last = zs->next;
zs->next = logdb->next_federated(zs->next);
if ( zs->next != -1 )
{
ReplicaManager::replicate(zone_id);
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::replicate_failure(int zone_id, int last_zone)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it != zones.end() )
{
ZoneServers * zs = it->second;
if ( last_zone >= 0 )
{
zs->last = last_zone;
zs->next = logdb->next_federated(zs->last);
}
if ( zs->next != -1 )
{
ReplicaManager::replicate(zone_id);
}
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::xmlrpc_replicate_log(int zone_id, bool& success,
int& last, std::string& error)
{
static const std::string replica_method = "one.zone.fedreplicate";
std::string secret, zedp;
int xml_rc = 0;
LogDBRecord lr;
if ( get_next_record(zone_id, zedp, lr, error) != 0 )
{
return -1;
}
int prev_index = logdb->previous_federated(lr.index);
// -------------------------------------------------------------------------
// Get parameters to call append entries on follower
// -------------------------------------------------------------------------
if ( Client::read_oneauth(secret, error) == -1 )
{
return -1;
}
xmlrpc_c::value result;
xmlrpc_c::paramList replica_params;
replica_params.add(xmlrpc_c::value_string(secret));
replica_params.add(xmlrpc_c::value_int(lr.index));
replica_params.add(xmlrpc_c::value_int(prev_index));
replica_params.add(xmlrpc_c::value_string(lr.sql));
// -------------------------------------------------------------------------
// Do the XML-RPC call
// -------------------------------------------------------------------------
xml_rc = Client::client()->call(zedp, replica_method, replica_params,
xmlrpc_timeout_ms, &result, error);
if ( xml_rc == 0 )
{
vector<xmlrpc_c::value> values;
values = xmlrpc_c::value_array(result).vectorValueValue();
success = xmlrpc_c::value_boolean(values[0]);
if ( success ) //values[2] = error code (string)
{
last = xmlrpc_c::value_int(values[1]);
}
else
{
error = xmlrpc_c::value_string(values[1]);
last = xmlrpc_c::value_int(values[3]);
}
}
else
{
std::ostringstream ess;
ess << "Error replicating log entry " << lr.index << " on zone "
<< zone_id << " (" << zedp << "): " << error;
NebulaLog::log("FRM", Log::ERROR, error);
error = ess.str();
}
return xml_rc;
}
<commit_msg>Fix log message<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "FedReplicaManager.h"
#include "ReplicaThread.h"
#include "Nebula.h"
#include "Client.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
const time_t FedReplicaManager::xmlrpc_timeout_ms = 10000;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
FedReplicaManager::FedReplicaManager(LogDB * d): ReplicaManager(), logdb(d)
{
pthread_mutex_init(&mutex, 0);
am.addListener(this);
};
/* -------------------------------------------------------------------------- */
FedReplicaManager::~FedReplicaManager()
{
Nebula& nd = Nebula::instance();
std::map<int, ZoneServers *>::iterator it;
for ( it = zones.begin() ; it != zones.end() ; ++it )
{
delete it->second;
}
zones.clear();
if ( nd.is_federation_master() )
{
stop_replica_threads();
}
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::apply_log_record(int index, int prev,
const std::string& sql)
{
int rc;
pthread_mutex_lock(&mutex);
int last_index = logdb->last_federated();
if ( prev != last_index )
{
rc = last_index;
pthread_mutex_unlock(&mutex);
return rc;
}
std::ostringstream oss(sql);
if ( logdb->exec_federated_wr(oss, index) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
pthread_mutex_unlock(&mutex);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * frm_loop(void *arg)
{
FedReplicaManager * fedrm;
if ( arg == 0 )
{
return 0;
}
fedrm = static_cast<FedReplicaManager *>(arg);
NebulaLog::log("FRM",Log::INFO,"Federation Replica Manger started.");
fedrm->am.loop();
NebulaLog::log("FRM",Log::INFO,"Federation Replica Manger stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
int FedReplicaManager::start()
{
int rc;
pthread_attr_t pattr;
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
NebulaLog::log("FRM",Log::INFO,"Starting Federation Replica Manager...");
rc = pthread_create(&frm_thread, &pattr, frm_loop,(void *) this);
return rc;
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::finalize_action(const ActionRequest& ar)
{
NebulaLog::log("FRM", Log::INFO, "Federation Replica Manager...");
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::update_zones(std::vector<int>& zone_ids)
{
Nebula& nd = Nebula::instance();
ZonePool * zpool = nd.get_zonepool();
vector<int>::iterator it;
int zone_id = nd.get_zone_id();
if ( zpool->list_zones(zone_ids) != 0 )
{
return;
}
pthread_mutex_lock(&mutex);
int last_index = logdb->last_federated();
zones.clear();
for (it = zone_ids.begin() ; it != zone_ids.end(); )
{
if ( *it == zone_id )
{
it = zone_ids.erase(it);
}
else
{
Zone * zone = zpool->get(*it, true);
if ( zone == 0 )
{
it = zone_ids.erase(it);
}
else
{
std::string zedp;
zone->get_template_attribute("ENDPOINT", zedp);
zone->unlock();
ZoneServers * zs = new ZoneServers(*it, last_index, zedp);
zones.insert(make_pair(*it, zs));
++it;
}
}
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::add_zone(int zone_id)
{
std::ostringstream oss;
std::string zedp;
Nebula& nd = Nebula::instance();
ZonePool * zpool = nd.get_zonepool();
Zone * zone = zpool->get(zone_id, true);
if ( zone == 0 )
{
return;
}
zone->get_template_attribute("ENDPOINT", zedp);
zone->unlock();
pthread_mutex_lock(&mutex);
int last_index = logdb->last_federated();
ZoneServers * zs = new ZoneServers(zone_id, last_index, zedp);
zones.insert(make_pair(zone_id, zs));
oss << "Starting federation replication thread for slave: " << zone_id;
NebulaLog::log("FRM", Log::INFO, oss);
add_replica_thread(zone_id);
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::delete_zone(int zone_id)
{
std::ostringstream oss;
std::map<int, ZoneServers *>::iterator it;
pthread_mutex_lock(&mutex);
it = zones.find(zone_id);
if ( it == zones.end() )
{
return;
}
delete it->second;
zones.erase(it);
oss << "Stopping replication thread for slave: " << zone_id;
NebulaLog::log("FRM", Log::INFO, oss);
delete_replica_thread(zone_id);
pthread_mutex_unlock(&mutex);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ReplicaThread * FedReplicaManager::thread_factory(int zone_id)
{
return new FedReplicaThread(zone_id);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::get_next_record(int zone_id, std::string& zedp,
LogDBRecord& lr, std::string& error)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it == zones.end() )
{
pthread_mutex_unlock(&mutex);
return -1;
}
ZoneServers * zs = it->second;
zedp = zs->endpoint;
if ( zs->next == -1 )
{
zs->next= logdb->last_federated();
}
if ( zs->last == zs->next )
{
pthread_mutex_unlock(&mutex);
return -1;
}
int rc = logdb->get_log_record(zs->next, lr);
if ( rc == -1 )
{
std::ostringstream oss;
oss << "Failed to load federation log record " << zs->next
<< " for zone " << zs->zone_id;
error = oss.str();
}
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void FedReplicaManager::replicate_success(int zone_id)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it == zones.end() )
{
pthread_mutex_unlock(&mutex);
return;
}
ZoneServers * zs = it->second;
zs->last = zs->next;
zs->next = logdb->next_federated(zs->next);
if ( zs->next != -1 )
{
ReplicaManager::replicate(zone_id);
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
void FedReplicaManager::replicate_failure(int zone_id, int last_zone)
{
pthread_mutex_lock(&mutex);
std::map<int, ZoneServers *>::iterator it = zones.find(zone_id);
if ( it != zones.end() )
{
ZoneServers * zs = it->second;
if ( last_zone >= 0 )
{
zs->last = last_zone;
zs->next = logdb->next_federated(zs->last);
}
if ( zs->next != -1 )
{
ReplicaManager::replicate(zone_id);
}
}
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedReplicaManager::xmlrpc_replicate_log(int zone_id, bool& success,
int& last, std::string& error)
{
static const std::string replica_method = "one.zone.fedreplicate";
std::string secret, zedp;
int xml_rc = 0;
LogDBRecord lr;
if ( get_next_record(zone_id, zedp, lr, error) != 0 )
{
return -1;
}
int prev_index = logdb->previous_federated(lr.index);
// -------------------------------------------------------------------------
// Get parameters to call append entries on follower
// -------------------------------------------------------------------------
if ( Client::read_oneauth(secret, error) == -1 )
{
return -1;
}
xmlrpc_c::value result;
xmlrpc_c::paramList replica_params;
replica_params.add(xmlrpc_c::value_string(secret));
replica_params.add(xmlrpc_c::value_int(lr.index));
replica_params.add(xmlrpc_c::value_int(prev_index));
replica_params.add(xmlrpc_c::value_string(lr.sql));
// -------------------------------------------------------------------------
// Do the XML-RPC call
// -------------------------------------------------------------------------
xml_rc = Client::client()->call(zedp, replica_method, replica_params,
xmlrpc_timeout_ms, &result, error);
if ( xml_rc == 0 )
{
vector<xmlrpc_c::value> values;
values = xmlrpc_c::value_array(result).vectorValueValue();
success = xmlrpc_c::value_boolean(values[0]);
if ( success ) //values[2] = error code (string)
{
last = xmlrpc_c::value_int(values[1]);
}
else
{
error = xmlrpc_c::value_string(values[1]);
last = xmlrpc_c::value_int(values[3]);
}
}
else
{
std::ostringstream ess;
ess << "Error replicating log entry " << lr.index << " on zone "
<< zone_id << " (" << zedp << "): " << error;
NebulaLog::log("FRM", Log::ERROR, ess);
error = ess.str();
}
return xml_rc;
}
<|endoftext|> |
<commit_before>//
// yas_audio_graph_avf_au.cpp
//
#include "yas_audio_graph_avf_au.h"
#include <cpp_utils/yas_cf_utils.h>
#include <cpp_utils/yas_fast_each.h>
#include "yas_audio_rendering_connection.h"
#include "yas_audio_time.h"
using namespace yas;
audio::graph_avf_au::graph_avf_au(graph_node_args &&args, AudioComponentDescription const &acd)
: _node(graph_node::make_shared(std::move(args))), _raw_au(audio::avf_au::make_shared(acd)) {
this->_node->chain(graph_node::method::prepare_rendering)
.perform([this](auto const &) {
this->_node->set_render_handler([raw_au = this->_raw_au](node_render_args args) {
raw_au->render({.buffer = args.buffer, .bus_idx = args.bus_idx, .time = args.time},
[&args](avf_au::render_args input_args) {
if (args.source_connections.count(input_args.bus_idx) > 0) {
rendering_connection const &connection =
args.source_connections.at(input_args.bus_idx);
connection.render(input_args.buffer, input_args.time);
}
});
});
})
.end()
->add_to(this->_pool);
this->_node->chain(graph_node::method::will_reset)
.perform([this](auto const &) { this->_will_reset(); })
.end()
->add_to(this->_pool);
manageable_graph_node::cast(this->_node)->set_setup_handler([this]() { this->_initialize_raw_au(); });
manageable_graph_node::cast(this->_node)->set_teardown_handler([this]() { this->_uninitialize_raw_au(); });
this->_raw_au->load_state_chain().send_to(this->_load_state).sync()->add_to(this->_pool);
}
audio::graph_avf_au::~graph_avf_au() = default;
audio::graph_avf_au::load_state audio::graph_avf_au::state() const {
return this->_load_state->raw();
}
audio::avf_au_ptr const &audio::graph_avf_au::raw_au() const {
return this->_raw_au;
}
void audio::graph_avf_au::_initialize_raw_au() {
this->_raw_au->initialize();
}
void audio::graph_avf_au::_uninitialize_raw_au() {
this->_raw_au->uninitialize();
}
audio::graph_node_ptr const &audio::graph_avf_au::node() const {
return this->_node;
}
chaining::chain_sync_t<audio::graph_avf_au::load_state> audio::graph_avf_au::load_state_chain() const {
return this->_load_state->chain();
}
chaining::chain_unsync_t<audio::graph_avf_au::connection_method> audio::graph_avf_au::connection_chain() const {
return this->_connection_notifier->chain();
}
void audio::graph_avf_au::_will_reset() {
this->_raw_au->reset();
}
void audio::graph_avf_au::_update_unit_connections() {
auto const &raw_au = this->_raw_au;
bool const is_initialized = raw_au->is_initialized();
if (is_initialized) {
this->_uninitialize_raw_au();
}
this->_connection_notifier->notify(connection_method::will_update);
auto const input_bus_count = raw_au->input_bus_count();
if (input_bus_count > 0) {
auto each = make_fast_each(input_bus_count);
while (yas_each_next(each)) {
uint32_t const bus_idx = yas_each_index(each);
if (auto connection = manageable_graph_node::cast(this->_node)->input_connection(bus_idx)) {
raw_au->set_input_format(connection->format(), bus_idx);
}
}
}
auto const output_bus_count = raw_au->output_bus_count();
if (output_bus_count > 0) {
auto each = make_fast_each(output_bus_count);
while (yas_each_next(each)) {
uint32_t const bus_idx = yas_each_index(each);
if (auto connection = manageable_graph_node::cast(this->_node)->output_connection(bus_idx)) {
raw_au->set_output_format(connection->format(), bus_idx);
}
}
}
this->_connection_notifier->notify(connection_method::did_update);
if (is_initialized) {
this->_initialize_raw_au();
}
}
audio::graph_avf_au_ptr audio::graph_avf_au::make_shared(OSType const type, OSType const sub_type) {
return graph_avf_au::make_shared(AudioComponentDescription{
.componentType = type,
.componentSubType = sub_type,
.componentManufacturer = kAudioUnitManufacturer_Apple,
.componentFlags = 0,
.componentFlagsMask = 0,
});
}
audio::graph_avf_au_ptr audio::graph_avf_au::make_shared(AudioComponentDescription const &acd) {
return graph_avf_au::make_shared({.acd = acd, .node_args = {.input_bus_count = 1, .output_bus_count = 1}});
}
audio::graph_avf_au_ptr audio::graph_avf_au::make_shared(graph_avf_au::args &&args) {
return graph_avf_au_ptr(new graph_avf_au{std::move(args.node_args), args.acd});
}
#pragma mark -
std::string yas::to_string(audio::graph_avf_au::load_state const &state) {
switch (state) {
case audio::graph_avf_au::load_state::unload:
return "unload";
case audio::graph_avf_au::load_state::loaded:
return "loaded";
case audio::graph_avf_au::load_state::failed:
return "failed";
}
}
<commit_msg>update_unit_connections<commit_after>//
// yas_audio_graph_avf_au.cpp
//
#include "yas_audio_graph_avf_au.h"
#include <cpp_utils/yas_cf_utils.h>
#include <cpp_utils/yas_fast_each.h>
#include "yas_audio_rendering_connection.h"
#include "yas_audio_time.h"
using namespace yas;
audio::graph_avf_au::graph_avf_au(graph_node_args &&args, AudioComponentDescription const &acd)
: _node(graph_node::make_shared(std::move(args))), _raw_au(audio::avf_au::make_shared(acd)) {
this->_node->chain(graph_node::method::prepare_rendering)
.perform([this](auto const &) {
this->_update_unit_connections();
this->_node->set_render_handler([raw_au = this->_raw_au](node_render_args args) {
raw_au->render({.buffer = args.buffer, .bus_idx = args.bus_idx, .time = args.time},
[&args](avf_au::render_args input_args) {
if (args.source_connections.count(input_args.bus_idx) > 0) {
rendering_connection const &connection =
args.source_connections.at(input_args.bus_idx);
connection.render(input_args.buffer, input_args.time);
}
});
});
})
.end()
->add_to(this->_pool);
this->_node->chain(graph_node::method::will_reset)
.perform([this](auto const &) { this->_will_reset(); })
.end()
->add_to(this->_pool);
manageable_graph_node::cast(this->_node)->set_setup_handler([this]() { this->_initialize_raw_au(); });
manageable_graph_node::cast(this->_node)->set_teardown_handler([this]() { this->_uninitialize_raw_au(); });
this->_raw_au->load_state_chain().send_to(this->_load_state).sync()->add_to(this->_pool);
}
audio::graph_avf_au::~graph_avf_au() = default;
audio::graph_avf_au::load_state audio::graph_avf_au::state() const {
return this->_load_state->raw();
}
audio::avf_au_ptr const &audio::graph_avf_au::raw_au() const {
return this->_raw_au;
}
void audio::graph_avf_au::_initialize_raw_au() {
this->_raw_au->initialize();
}
void audio::graph_avf_au::_uninitialize_raw_au() {
this->_raw_au->uninitialize();
}
audio::graph_node_ptr const &audio::graph_avf_au::node() const {
return this->_node;
}
chaining::chain_sync_t<audio::graph_avf_au::load_state> audio::graph_avf_au::load_state_chain() const {
return this->_load_state->chain();
}
chaining::chain_unsync_t<audio::graph_avf_au::connection_method> audio::graph_avf_au::connection_chain() const {
return this->_connection_notifier->chain();
}
void audio::graph_avf_au::_will_reset() {
this->_raw_au->reset();
}
void audio::graph_avf_au::_update_unit_connections() {
auto const &raw_au = this->_raw_au;
bool const is_initialized = raw_au->is_initialized();
if (is_initialized) {
this->_uninitialize_raw_au();
}
this->_connection_notifier->notify(connection_method::will_update);
auto const input_bus_count = raw_au->input_bus_count();
if (input_bus_count > 0) {
auto each = make_fast_each(input_bus_count);
while (yas_each_next(each)) {
uint32_t const bus_idx = yas_each_index(each);
if (auto connection = manageable_graph_node::cast(this->_node)->input_connection(bus_idx)) {
raw_au->set_input_format(connection->format(), bus_idx);
}
}
}
auto const output_bus_count = raw_au->output_bus_count();
if (output_bus_count > 0) {
auto each = make_fast_each(output_bus_count);
while (yas_each_next(each)) {
uint32_t const bus_idx = yas_each_index(each);
if (auto connection = manageable_graph_node::cast(this->_node)->output_connection(bus_idx)) {
raw_au->set_output_format(connection->format(), bus_idx);
}
}
}
this->_connection_notifier->notify(connection_method::did_update);
if (is_initialized) {
this->_initialize_raw_au();
}
}
audio::graph_avf_au_ptr audio::graph_avf_au::make_shared(OSType const type, OSType const sub_type) {
return graph_avf_au::make_shared(AudioComponentDescription{
.componentType = type,
.componentSubType = sub_type,
.componentManufacturer = kAudioUnitManufacturer_Apple,
.componentFlags = 0,
.componentFlagsMask = 0,
});
}
audio::graph_avf_au_ptr audio::graph_avf_au::make_shared(AudioComponentDescription const &acd) {
return graph_avf_au::make_shared({.acd = acd, .node_args = {.input_bus_count = 1, .output_bus_count = 1}});
}
audio::graph_avf_au_ptr audio::graph_avf_au::make_shared(graph_avf_au::args &&args) {
return graph_avf_au_ptr(new graph_avf_au{std::move(args.node_args), args.acd});
}
#pragma mark -
std::string yas::to_string(audio::graph_avf_au::load_state const &state) {
switch (state) {
case audio::graph_avf_au::load_state::unload:
return "unload";
case audio::graph_avf_au::load_state::loaded:
return "loaded";
case audio::graph_avf_au::load_state::failed:
return "failed";
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// Reaper
///
/// Copyright (c) 2015-2020 Thibault Schueller
/// This file is distributed under the MIT License
////////////////////////////////////////////////////////////////////////////////
#include "Debug.h"
#include "core/Assert.h"
namespace Reaper
{
namespace
{
template <typename HandleType>
void SetDebugName(VkDevice device, VkObjectType handleType, HandleType handle, const char* name)
{
const VkDebugUtilsObjectNameInfoEXT debugNameInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
nullptr, handleType, reinterpret_cast<u64>(handle), name};
Assert(vkSetDebugUtilsObjectNameEXT(device, &debugNameInfo) == VK_SUCCESS);
}
} // namespace
// Use preprocessor to generate specializations
#define DEFINE_SET_DEBUG_NAME_SPECIALIZATION(vk_handle_type, vk_enum_value) \
void VulkanSetDebugName(VkDevice device, vk_handle_type handle, const char* name) \
{ \
SetDebugName(device, vk_enum_value, handle, name); \
}
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkInstance, VK_OBJECT_TYPE_INSTANCE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkPhysicalDevice, VK_OBJECT_TYPE_PHYSICAL_DEVICE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDevice, VK_OBJECT_TYPE_DEVICE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkQueue, VK_OBJECT_TYPE_QUEUE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkSemaphore, VK_OBJECT_TYPE_SEMAPHORE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkCommandBuffer, VK_OBJECT_TYPE_COMMAND_BUFFER)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkFence, VK_OBJECT_TYPE_FENCE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDeviceMemory, VK_OBJECT_TYPE_DEVICE_MEMORY)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkBuffer, VK_OBJECT_TYPE_BUFFER)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkImage, VK_OBJECT_TYPE_IMAGE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkEvent, VK_OBJECT_TYPE_EVENT)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkQueryPool, VK_OBJECT_TYPE_QUERY_POOL)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkBufferView, VK_OBJECT_TYPE_BUFFER_VIEW)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkImageView, VK_OBJECT_TYPE_IMAGE_VIEW)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkShaderModule, VK_OBJECT_TYPE_SHADER_MODULE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkPipelineCache, VK_OBJECT_TYPE_PIPELINE_CACHE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkPipelineLayout, VK_OBJECT_TYPE_PIPELINE_LAYOUT)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkRenderPass, VK_OBJECT_TYPE_RENDER_PASS)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkPipeline, VK_OBJECT_TYPE_PIPELINE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDescriptorSetLayout, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkSampler, VK_OBJECT_TYPE_SAMPLER)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDescriptorPool, VK_OBJECT_TYPE_DESCRIPTOR_POOL)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDescriptorSet, VK_OBJECT_TYPE_DESCRIPTOR_SET)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkFramebuffer, VK_OBJECT_TYPE_FRAMEBUFFER)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkCommandPool, VK_OBJECT_TYPE_COMMAND_POOL)
// Command buffer helpers
void VulkanInsertDebugLabel(VkCommandBuffer commandBuffer, const char* name)
{
// Color is supported but we're not using it
const VkDebugUtilsLabelEXT debugLabelInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr, name, {}};
vkCmdInsertDebugUtilsLabelEXT(commandBuffer, &debugLabelInfo);
}
void VulkanBeginDebugLabel(VkCommandBuffer commandBuffer, const char* name)
{
// Color is supported but we're not using it
const VkDebugUtilsLabelEXT debugLabelInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr, name, {}};
vkCmdBeginDebugUtilsLabelEXT(commandBuffer, &debugLabelInfo);
}
void VulkanEndDebugLabel(VkCommandBuffer commandBuffer)
{
vkCmdEndDebugUtilsLabelEXT(commandBuffer);
}
VulkanDebugLabelCmdBufferScope::VulkanDebugLabelCmdBufferScope(VkCommandBuffer commandBuffer, const char* name)
: m_commandBuffer(commandBuffer)
{
VulkanBeginDebugLabel(commandBuffer, name);
}
VulkanDebugLabelCmdBufferScope::~VulkanDebugLabelCmdBufferScope()
{
VulkanEndDebugLabel(m_commandBuffer);
}
// Queue helpers
void VulkanInsertQueueDebugLabel(VkQueue queue, const char* name)
{
// Color is supported but we're not using it
const VkDebugUtilsLabelEXT debugLabelInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr, name, {}};
vkQueueInsertDebugUtilsLabelEXT(queue, &debugLabelInfo);
}
void VulkanBeginQueueDebugLabel(VkQueue queue, const char* name)
{
// Color is supported but we're not using it
const VkDebugUtilsLabelEXT debugLabelInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr, name, {}};
vkQueueBeginDebugUtilsLabelEXT(queue, &debugLabelInfo);
}
void VulkanEndQueueDebugLabel(VkQueue queue)
{
vkQueueEndDebugUtilsLabelEXT(queue);
}
VulkanQueueDebugLabelScope::VulkanQueueDebugLabelScope(VkQueue queue, const char* name)
: m_queue(queue)
{
VulkanBeginQueueDebugLabel(queue, name);
}
VulkanQueueDebugLabelScope::~VulkanQueueDebugLabelScope()
{
VulkanEndQueueDebugLabel(m_queue);
}
} // namespace Reaper
<commit_msg>vulkan: fix release build<commit_after>////////////////////////////////////////////////////////////////////////////////
/// Reaper
///
/// Copyright (c) 2015-2020 Thibault Schueller
/// This file is distributed under the MIT License
////////////////////////////////////////////////////////////////////////////////
#include "Debug.h"
#include "core/Assert.h"
#define REAPER_VULKAN_DEBUG REAPER_DEBUG
namespace Reaper
{
namespace
{
template <typename HandleType>
void SetDebugName(VkDevice device, VkObjectType handleType, HandleType handle, const char* name)
{
const VkDebugUtilsObjectNameInfoEXT debugNameInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
nullptr, handleType, reinterpret_cast<u64>(handle), name};
#if REAPER_VULKAN_DEBUG
Assert(vkSetDebugUtilsObjectNameEXT(device, &debugNameInfo) == VK_SUCCESS);
#endif
}
} // namespace
// Use preprocessor to generate specializations
#define DEFINE_SET_DEBUG_NAME_SPECIALIZATION(vk_handle_type, vk_enum_value) \
void VulkanSetDebugName(VkDevice device, vk_handle_type handle, const char* name) \
{ \
SetDebugName(device, vk_enum_value, handle, name); \
}
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkInstance, VK_OBJECT_TYPE_INSTANCE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkPhysicalDevice, VK_OBJECT_TYPE_PHYSICAL_DEVICE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDevice, VK_OBJECT_TYPE_DEVICE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkQueue, VK_OBJECT_TYPE_QUEUE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkSemaphore, VK_OBJECT_TYPE_SEMAPHORE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkCommandBuffer, VK_OBJECT_TYPE_COMMAND_BUFFER)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkFence, VK_OBJECT_TYPE_FENCE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDeviceMemory, VK_OBJECT_TYPE_DEVICE_MEMORY)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkBuffer, VK_OBJECT_TYPE_BUFFER)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkImage, VK_OBJECT_TYPE_IMAGE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkEvent, VK_OBJECT_TYPE_EVENT)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkQueryPool, VK_OBJECT_TYPE_QUERY_POOL)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkBufferView, VK_OBJECT_TYPE_BUFFER_VIEW)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkImageView, VK_OBJECT_TYPE_IMAGE_VIEW)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkShaderModule, VK_OBJECT_TYPE_SHADER_MODULE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkPipelineCache, VK_OBJECT_TYPE_PIPELINE_CACHE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkPipelineLayout, VK_OBJECT_TYPE_PIPELINE_LAYOUT)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkRenderPass, VK_OBJECT_TYPE_RENDER_PASS)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkPipeline, VK_OBJECT_TYPE_PIPELINE)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDescriptorSetLayout, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkSampler, VK_OBJECT_TYPE_SAMPLER)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDescriptorPool, VK_OBJECT_TYPE_DESCRIPTOR_POOL)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkDescriptorSet, VK_OBJECT_TYPE_DESCRIPTOR_SET)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkFramebuffer, VK_OBJECT_TYPE_FRAMEBUFFER)
DEFINE_SET_DEBUG_NAME_SPECIALIZATION(VkCommandPool, VK_OBJECT_TYPE_COMMAND_POOL)
// Command buffer helpers
void VulkanInsertDebugLabel(VkCommandBuffer commandBuffer, const char* name)
{
// Color is supported but we're not using it
const VkDebugUtilsLabelEXT debugLabelInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr, name, {}};
#if REAPER_VULKAN_DEBUG
vkCmdInsertDebugUtilsLabelEXT(commandBuffer, &debugLabelInfo);
#endif
}
void VulkanBeginDebugLabel(VkCommandBuffer commandBuffer, const char* name)
{
// Color is supported but we're not using it
const VkDebugUtilsLabelEXT debugLabelInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr, name, {}};
#if REAPER_VULKAN_DEBUG
vkCmdBeginDebugUtilsLabelEXT(commandBuffer, &debugLabelInfo);
#endif
}
void VulkanEndDebugLabel(VkCommandBuffer commandBuffer)
{
#if REAPER_VULKAN_DEBUG
vkCmdEndDebugUtilsLabelEXT(commandBuffer);
#endif
}
VulkanDebugLabelCmdBufferScope::VulkanDebugLabelCmdBufferScope(VkCommandBuffer commandBuffer, const char* name)
: m_commandBuffer(commandBuffer)
{
VulkanBeginDebugLabel(commandBuffer, name);
}
VulkanDebugLabelCmdBufferScope::~VulkanDebugLabelCmdBufferScope()
{
VulkanEndDebugLabel(m_commandBuffer);
}
// Queue helpers
void VulkanInsertQueueDebugLabel(VkQueue queue, const char* name)
{
// Color is supported but we're not using it
const VkDebugUtilsLabelEXT debugLabelInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr, name, {}};
#if REAPER_VULKAN_DEBUG
vkQueueInsertDebugUtilsLabelEXT(queue, &debugLabelInfo);
#endif
}
void VulkanBeginQueueDebugLabel(VkQueue queue, const char* name)
{
// Color is supported but we're not using it
const VkDebugUtilsLabelEXT debugLabelInfo = {VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr, name, {}};
#if REAPER_VULKAN_DEBUG
vkQueueBeginDebugUtilsLabelEXT(queue, &debugLabelInfo);
#endif
}
void VulkanEndQueueDebugLabel(VkQueue queue)
{
#if REAPER_VULKAN_DEBUG
vkQueueEndDebugUtilsLabelEXT(queue);
#endif
}
VulkanQueueDebugLabelScope::VulkanQueueDebugLabelScope(VkQueue queue, const char* name)
: m_queue(queue)
{
VulkanBeginQueueDebugLabel(queue, name);
}
VulkanQueueDebugLabelScope::~VulkanQueueDebugLabelScope()
{
VulkanEndQueueDebugLabel(m_queue);
}
} // namespace Reaper
<|endoftext|> |
<commit_before>#include "client_manager.hpp"
#include <map>
#include <vector>
#include <enet-plus/enet.hpp>
#include <base/macros.hpp>
#include <base/pstdint.hpp>
#include "entity.hpp"
namespace bm {
Client::Client(enet::Peer* peer, Player* entity) : peer(peer), entity(entity) {
CHECK(peer != NULL);
}
Client::~Client() {
delete peer;
}
ClientManager::ClientManager() { }
ClientManager::~ClientManager() {
std::map<uint32_t, Client*>::iterator i;
for(i = _clients.begin(); i != _clients.end(); ++i) {
delete i->second;
}
}
void ClientManager::AddClient(uint32_t id, Client* client) {
CHECK(_clients.count(id) == 0);
_clients[id] = client;
}
Client* ClientManager::GetClient(uint32_t id) {
CHECK(_clients.count(id) == 1);
return _clients[id];
}
void ClientManager::DeleteClient(uint32_t id, bool deallocate) {
CHECK(_clients.count(id) == 1);
if(deallocate) {
delete _clients[id];
}
_clients.erase(id);
}
void ClientManager::DisconnectClient(uint32_t id) {
CHECK(_clients.count(id) == 1);
_clients[id]->peer->Disconnect();
}
std::map<uint32_t, Client*>* ClientManager::GetClients() {
return &_clients;
}
void ClientManager::DeleteClients(const std::vector<uint32_t>& input, bool deallocate) {
size_t size = input.size();
for(size_t i = 0; i < size; i++) {
DeleteClient(input[i], deallocate);
}
}
void ClientManager::DisconnectClients(const std::vector<uint32_t>& input) {
size_t size = input.size();
for(size_t i = 0; i < size; i++) {
DisconnectClient(input[i]);
}
}
} // namespace bm
<commit_msg>Double delete fixed.<commit_after>#include "client_manager.hpp"
#include <map>
#include <vector>
#include <enet-plus/enet.hpp>
#include <base/macros.hpp>
#include <base/pstdint.hpp>
#include "entity.hpp"
namespace bm {
Client::Client(enet::Peer* peer, Player* entity) : peer(peer), entity(entity) {
CHECK(peer != NULL);
}
Client::~Client() { }
ClientManager::ClientManager() { }
ClientManager::~ClientManager() {
std::map<uint32_t, Client*>::iterator i;
for(i = _clients.begin(); i != _clients.end(); ++i) {
delete i->second;
}
}
void ClientManager::AddClient(uint32_t id, Client* client) {
CHECK(_clients.count(id) == 0);
_clients[id] = client;
}
Client* ClientManager::GetClient(uint32_t id) {
CHECK(_clients.count(id) == 1);
return _clients[id];
}
void ClientManager::DeleteClient(uint32_t id, bool deallocate) {
CHECK(_clients.count(id) == 1);
if(deallocate) {
delete _clients[id];
}
_clients.erase(id);
}
void ClientManager::DisconnectClient(uint32_t id) {
CHECK(_clients.count(id) == 1);
_clients[id]->peer->Disconnect();
}
std::map<uint32_t, Client*>* ClientManager::GetClients() {
return &_clients;
}
void ClientManager::DeleteClients(const std::vector<uint32_t>& input, bool deallocate) {
size_t size = input.size();
for(size_t i = 0; i < size; i++) {
DeleteClient(input[i], deallocate);
}
}
void ClientManager::DisconnectClients(const std::vector<uint32_t>& input) {
size_t size = input.size();
for(size_t i = 0; i < size; i++) {
DisconnectClient(input[i]);
}
}
} // namespace bm
<|endoftext|> |
<commit_before>//===-- AVRMCAsmInfo.cpp - AVR asm properties -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the AVRMCAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "AVRMCAsmInfo.h"
#include "llvm/ADT/Triple.h"
namespace llvm {
AVRMCAsmInfo::AVRMCAsmInfo(const Triple &TT) {
PointerSize = 2;
CalleeSaveStackSlotSize = 2;
CommentString = ";";
PrivateGlobalPrefix = ".L";
UsesELFSectionDirectiveForBSS = true;
UseIntegratedAssembler = true;
}
} // end of namespace llvm
<commit_msg>[AVR] Fix the build<commit_after>//===-- AVRMCAsmInfo.cpp - AVR asm properties -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the AVRMCAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "AVRMCAsmInfo.h"
#include "llvm/ADT/Triple.h"
namespace llvm {
AVRMCAsmInfo::AVRMCAsmInfo(const Triple &TT) {
CodePointerSize = 2;
CalleeSaveStackSlotSize = 2;
CommentString = ";";
PrivateGlobalPrefix = ".L";
UsesELFSectionDirectiveForBSS = true;
UseIntegratedAssembler = true;
}
} // end of namespace llvm
<|endoftext|> |
<commit_before>#include <sstream>
#include <cstring>
#include "server/db/transaction.h"
#include "server/db/connection.h"
using namespace Batyr::Db;
Transaction::Transaction(Connection * _connection)
: logger(Poco::Logger::get("Db::Transaction")),
connection(_connection),
rollback(false)
{
poco_debug(logger, "BEGIN");
// start transaction
exec("begin;");
}
Transaction::~Transaction()
{
auto transactionStatus = PQtransactionStatus(connection->pgconn);
if (rollback || (transactionStatus == PQTRANS_INERROR) || (transactionStatus == PQTRANS_UNKNOWN)) {
poco_debug(logger, "ROLLBACK");
exec("rollback;");
}
else {
poco_debug(logger, "COMMIT");
exec("commit;");
}
// run all exitSqls
for(auto exitSql: exitSqls) {
try {
poco_debug(logger, "Running Exit SQL: " + exitSql);
exec(exitSql);
}
catch(DbError &e) {
poco_warning(logger, "Transaction Exit SQL failed: "+exitSql);
}
}
exitSqls.clear();
}
PGresultPtr
Transaction::exec(const std::string _sql)
{
PGresultPtr result( PQexec(connection->pgconn, _sql.c_str()), PQclear);
checkResult(result);
return std::move(result);
}
PGresultPtr
Transaction::execParams(const std::string _sql, int nParams, const Oid *paramTypes,
const char * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
{
PGresultPtr result( PQexecParams(connection->pgconn, _sql.c_str(),
nParams,
paramTypes,
paramValues,
paramLengths,
paramFormats,
resultFormat
), PQclear);
checkResult(result);
return std::move(result);
}
void
Transaction::checkResult(PGresultPtr & res)
{
if (!res) {
std::string msg = "query result was null: " + std::string(PQerrorMessage(connection->pgconn));
poco_error(logger, msg.c_str());
rollback = true;
throw DbError(msg);
}
auto resStatus = PQresultStatus(res.get());
if (resStatus == PGRES_FATAL_ERROR) {
char * sqlstate = PQresultErrorField(res.get(), PG_DIAG_SQLSTATE);
char * msg_primary = PQresultErrorField(res.get(), PG_DIAG_MESSAGE_PRIMARY);
std::stringstream msgstream;
msgstream << "query failed: " << msg_primary << " [sqlstate: " << sqlstate << "]";
poco_error(logger, msgstream.str().c_str());
rollback = true;
throw DbError(msgstream.str());
}
}
void
Transaction::createTempTable(const std::string existingTableName, const std::string tempTableName)
{
std::stringstream querystream;
poco_debug(logger, "creating table " + tempTableName + " based on " + existingTableName);
// use a simple select into and not table inheritance
querystream << "select * into temporary " << tempTableName
<< " from " << existingTableName << " limit 0";
std::string query = querystream.str();
// postgresql drops temporary tables when the connections ends. But the temporary
// tables are not needed anymore when the transaction ends. ensuring that they
// are dropped immetiately after the end of the transaction
std::stringstream dropTableStream;
dropTableStream << "drop table if exists " << tempTableName;
exitSqls.push_back(dropTableStream.str());
// create the temporary table
exec(query);
}
FieldMap
Transaction::getTableFields(const std::string tableName)
{
FieldMap fieldMap;
const char *paramValues[1] = { tableName.c_str() };
int paramLengths[1] = { static_cast<int>(tableName.length()) };
auto res = execParams(
"select pa.attname, pt.typname, pt.oid, coalesce(is_pk.is_pk, 'N')::text as is_pk"
" from pg_catalog.pg_attribute pa"
" join pg_catalog.pg_class pc on pc.oid=pa.attrelid and pa.attnum>0"
" join pg_catalog.pg_type pt on pt.oid=pa.atttypid"
" left join ("
" select pcs.conrelid as relid, unnest(conkey) as attnum, 'Y'::text as is_pk "
" from pg_catalog.pg_constraint pcs"
" where pcs.contype = 'p'"
" ) is_pk on is_pk.relid = pt.oid and is_pk.attnum=pa.attnum"
" where pc.oid = $1::regclass::oid",
1, NULL, paramValues, paramLengths, NULL, 1);
for (int i; i < PQntuples(res.get()); i++) {
auto attname = PQgetvalue(res.get(), i, 0);
auto typname = PQgetvalue(res.get(), i, 1);
auto oid = PQgetvalue(res.get(), i, 2);
auto isPk = PQgetvalue(res.get(), i, 3);
auto field = &fieldMap[attname];
if (!field->name.empty()) {
throw DbError("Tables with multiple columns with the same name are not supported. Column: "+std::string(attname));
}
field->name = attname;
field->pgTypeName = typname;
field->pgTypeOid = std::atoi(oid);
field->isPrimaryKey = (std::strcmp(isPk,"Y") == 0);
}
return fieldMap;
}
<commit_msg>fixing typo in primarykey determination<commit_after>#include <sstream>
#include <cstring>
#include "server/db/transaction.h"
#include "server/db/connection.h"
using namespace Batyr::Db;
Transaction::Transaction(Connection * _connection)
: logger(Poco::Logger::get("Db::Transaction")),
connection(_connection),
rollback(false)
{
poco_debug(logger, "BEGIN");
// start transaction
exec("begin;");
}
Transaction::~Transaction()
{
auto transactionStatus = PQtransactionStatus(connection->pgconn);
if (rollback || (transactionStatus == PQTRANS_INERROR) || (transactionStatus == PQTRANS_UNKNOWN)) {
poco_debug(logger, "ROLLBACK");
exec("rollback;");
}
else {
poco_debug(logger, "COMMIT");
exec("commit;");
}
// run all exitSqls
for(auto exitSql: exitSqls) {
try {
poco_debug(logger, "Running Exit SQL: " + exitSql);
exec(exitSql);
}
catch(DbError &e) {
poco_warning(logger, "Transaction Exit SQL failed: "+exitSql);
}
}
exitSqls.clear();
}
PGresultPtr
Transaction::exec(const std::string _sql)
{
PGresultPtr result( PQexec(connection->pgconn, _sql.c_str()), PQclear);
checkResult(result);
return std::move(result);
}
PGresultPtr
Transaction::execParams(const std::string _sql, int nParams, const Oid *paramTypes,
const char * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
{
PGresultPtr result( PQexecParams(connection->pgconn, _sql.c_str(),
nParams,
paramTypes,
paramValues,
paramLengths,
paramFormats,
resultFormat
), PQclear);
checkResult(result);
return std::move(result);
}
void
Transaction::checkResult(PGresultPtr & res)
{
if (!res) {
std::string msg = "query result was null: " + std::string(PQerrorMessage(connection->pgconn));
poco_error(logger, msg.c_str());
rollback = true;
throw DbError(msg);
}
auto resStatus = PQresultStatus(res.get());
if (resStatus == PGRES_FATAL_ERROR) {
char * sqlstate = PQresultErrorField(res.get(), PG_DIAG_SQLSTATE);
char * msg_primary = PQresultErrorField(res.get(), PG_DIAG_MESSAGE_PRIMARY);
std::stringstream msgstream;
msgstream << "query failed: " << msg_primary << " [sqlstate: " << sqlstate << "]";
poco_error(logger, msgstream.str().c_str());
rollback = true;
throw DbError(msgstream.str());
}
}
void
Transaction::createTempTable(const std::string existingTableName, const std::string tempTableName)
{
std::stringstream querystream;
poco_debug(logger, "creating table " + tempTableName + " based on " + existingTableName);
// use a simple select into and not table inheritance
querystream << "select * into temporary " << tempTableName
<< " from " << existingTableName << " limit 0";
std::string query = querystream.str();
// postgresql drops temporary tables when the connections ends. But the temporary
// tables are not needed anymore when the transaction ends. ensuring that they
// are dropped immetiately after the end of the transaction
std::stringstream dropTableStream;
dropTableStream << "drop table if exists " << tempTableName;
exitSqls.push_back(dropTableStream.str());
// create the temporary table
exec(query);
}
FieldMap
Transaction::getTableFields(const std::string tableName)
{
FieldMap fieldMap;
const char *paramValues[1] = { tableName.c_str() };
int paramLengths[1] = { static_cast<int>(tableName.length()) };
auto res = execParams(
"select pa.attname, pt.typname, pt.oid, coalesce(is_pk.is_pk, 'N')::text as is_pk"
" from pg_catalog.pg_attribute pa"
" join pg_catalog.pg_class pc on pc.oid=pa.attrelid and pa.attnum>0"
" join pg_catalog.pg_type pt on pt.oid=pa.atttypid"
" left join ("
" select pcs.conrelid as relid, unnest(conkey) as attnum, 'Y'::text as is_pk "
" from pg_catalog.pg_constraint pcs"
" where pcs.contype = 'p'"
" ) is_pk on is_pk.relid = pc.oid and is_pk.attnum=pa.attnum"
" where pc.oid = $1::regclass::oid",
1, NULL, paramValues, paramLengths, NULL, 1);
for (int i; i < PQntuples(res.get()); i++) {
auto attname = PQgetvalue(res.get(), i, 0);
auto typname = PQgetvalue(res.get(), i, 1);
auto oid = PQgetvalue(res.get(), i, 2);
auto isPk = PQgetvalue(res.get(), i, 3);
auto field = &fieldMap[attname];
if (!field->name.empty()) {
throw DbError("Tables with multiple columns with the same name are not supported. Column: "+std::string(attname));
}
field->name = attname;
field->pgTypeName = typname;
field->pgTypeOid = std::atoi(oid);
field->isPrimaryKey = (std::strcmp(isPk,"Y") == 0);
}
return fieldMap;
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <array>
#include <chrono>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <sys/stat.h>
#include "simulation.h"
#include "codes/codes.h"
namespace detail {
inline bool file_exists(const std::string &fname) {
struct stat buf;
return (stat(fname.c_str(), &buf) != -1);
}
}
static std::array<double, 131> rates{
{ 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11,
0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22,
0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.30, 0.31, 0.32, 0.33,
0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.40, 0.41, 0.42, 0.43, 0.44,
0.45, 0.46, 0.47, 0.48, 0.49, 0.50, 0.51, 0.52, 0.53, 0.54, 0.55,
0.56, 0.57, 0.58, 0.59, 0.60, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66,
0.67, 0.68, 0.69, 0.70, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77,
0.78, 0.79, 0.800, 0.807, 0.817, 0.827, 0.837, 0.846, 0.855, 0.864, 0.872,
0.880, 0.887, 0.894, 0.900, 0.907, 0.913, 0.918, 0.924, 0.929, 0.934, 0.938,
0.943, 0.947, 0.951, 0.954, 0.958, 0.961, 0.964, 0.967, 0.970, 0.972, 0.974,
0.976, 0.978, 0.980, 0.982, 0.983, 0.984, 0.985, 0.986, 0.987, 0.988, 0.989,
0.990, 0.991, 0.992, 0.993, 0.994, 0.995, 0.996, 0.997, 0.998, 0.999 }
};
static std::array<double, 131> limits = {
{ -1.548, -1.531, -1.500, -1.470, -1.440, -1.409, -1.378, -1.347, -1.316,
-1.285, -1.254, -1.222, -1.190, -1.158, -1.126, -1.094, -1.061, -1.028,
-0.995, -0.963, -0.928, -0.896, -0.861, -0.827, -0.793, -0.757, -0.724,
-0.687, -0.651, -0.616, -0.579, -0.544, -0.507, -0.469, -0.432, -0.394,
-0.355, -0.314, -0.276, -0.236, -0.198, -0.156, -0.118, -0.074, -0.032,
0.010, 0.055, 0.097, 0.144, 0.188, 0.233, 0.279, 0.326, 0.374,
0.424, 0.474, 0.526, 0.574, 0.628, 0.682, 0.734, 0.791, 0.844,
0.904, 0.960, 1.021, 1.084, 1.143, 1.208, 1.275, 1.343, 1.412,
1.483, 1.554, 1.628, 1.708, 1.784, 1.867, 1.952, 2.045, 2.108,
2.204, 2.302, 2.402, 2.503, 2.600, 2.712, 2.812, 2.913, 3.009,
3.114, 3.205, 3.312, 3.414, 3.500, 3.612, 3.709, 3.815, 3.906,
4.014, 4.115, 4.218, 4.304, 4.425, 4.521, 4.618, 4.725, 4.841,
4.922, 5.004, 5.104, 5.196, 5.307, 5.418, 5.484, 5.549, 5.615,
5.681, 5.756, 5.842, 5.927, 6.023, 6.119, 6.234, 6.360, 6.495,
6.651, 6.837, 7.072, 7.378, 7.864 }
};
static constexpr double ebno(const double rate) {
if (rate <= 0.800) {
const size_t index = static_cast<size_t>(rate * 100);
return limits.at(index);
} else if (rate >= 0.999) {
return limits.back();
} else {
const size_t offset = 80;
const size_t index = static_cast<size_t>(std::distance(
std::cbegin(rates),
std::find_if(std::cbegin(rates) + offset, std::cend(rates) - 1,
[=](const double r) { return r >= rate; })));
return limits.at(index);
}
}
static std::ofstream open_file(const std::string &fname) {
if (detail::file_exists(fname)) {
std::ostringstream os;
os << "File " << fname << " already exists.";
throw std::runtime_error(os.str());
}
std::ofstream log_file(fname.c_str(), std::ofstream::out);
return log_file;
}
double awgn_simulation::sigma(const double eb_no) const {
return 1.0f / sqrt((2 * decoder.rate() * pow(10, eb_no / 10.0)));
}
awgn_simulation::awgn_simulation(const class decoder &decoder_,
const double step_, const uint64_t seed_)
: decoder(decoder_), step(step_), seed(seed_) {}
void awgn_simulation::operator()() {
const size_t wer_width = std::numeric_limits<double>::digits10;
const size_t ebno_width = 6;
std::ofstream log_file(open_file(decoder.to_string() + ".log"));
std::vector<float> b(decoder.n());
log_file << std::setw(ebno_width + 1) << "ebno"
<< " ";
log_file << std::setw(wer_width + 6) << "wer" << std::endl;
const size_t tmp = static_cast<size_t>(ebno(decoder.rate()) / step);
const double start = (tmp + (1.0 / step)) * step;
const double max = std::max(8.0, start) + step / 2;
/* TODO round ebno() up to next step */
for (double eb_no = start; eb_no < max; eb_no += step) {
std::normal_distribution<float> distribution(
1.0, static_cast<float>(sigma(eb_no)));
auto noise = std::bind(std::ref(distribution), std::ref(generator));
size_t word_errors = 0;
size_t samples = 10000;
std::cout << std::this_thread::get_id() << " " << decoder.to_string()
<< ": E_b/N_0 = " << eb_no << " with " << samples << " … ";
std::cout.flush();
auto start_time = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < samples; i++) {
std::generate(std::begin(b), std::end(b), noise);
try {
auto result = decoder.correct(b);
if (std::any_of(std::cbegin(result), std::cend(result),
[](const auto &bit) { return bool(bit); })) {
word_errors++;
}
}
catch (const decoding_failure &) {
word_errors++;
}
}
auto end_time = std::chrono::high_resolution_clock::now();
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
end_time - start_time).count();
std::cout << seconds << " s" << std::endl;
log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width)
<< std::defaultfloat << eb_no << " ";
log_file << std::setw(wer_width + 1) << std::setprecision(wer_width)
<< std::scientific << static_cast<double>(word_errors) / samples
<< std::endl;
}
}
bitflip_simulation::bitflip_simulation(const class decoder &decoder_,
const size_t errors_)
: decoder(decoder_), errors(errors_) {}
void bitflip_simulation::operator()() const {
const size_t wer_width = std::numeric_limits<double>::digits10;
const size_t ebno_width = 6;
std::ofstream log_file(open_file(decoder.to_string() + ".log"));
log_file << std::setw(ebno_width + 1) << "errors"
<< " ";
log_file << std::setw(wer_width + 6) << "wer" << std::endl;
const size_t length = decoder.n();
for (size_t error = 0; error <= errors; error++) {
size_t patterns = 0;
size_t word_errors = 0;
std::vector<int> b;
std::fill_n(std::back_inserter(b), length - error, 0);
std::fill_n(std::back_inserter(b), error, 1);
std::cout << std::this_thread::get_id() << " " << decoder.to_string()
<< ": errors = " << error << " … ";
std::cout.flush();
auto start = std::chrono::high_resolution_clock::now();
do {
std::vector<float> x;
x.reserve(length);
std::transform(std::cbegin(b), std::cend(b), std::back_inserter(x),
[](const auto &bit) { return -2 * bit + 1; });
patterns++;
try {
auto result = decoder.correct(x);
if (std::any_of(std::cbegin(result), std::cend(result),
[](const auto &bit) { return bool(bit); })) {
word_errors++;
}
}
catch (const decoding_failure &) {
word_errors++;
}
} while (std::next_permutation(std::begin(b), std::end(b)));
auto end = std::chrono::high_resolution_clock::now();
auto seconds =
std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
std::cout << seconds << " s " << word_errors << " " << patterns
<< std::endl;
log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width)
<< std::defaultfloat << error << " ";
log_file << std::setw(wer_width + 1) << std::setprecision(wer_width)
<< std::scientific << static_cast<double>(word_errors) / patterns
<< std::endl;
}
}
std::atomic_bool thread_pool::running{ true };
std::mutex thread_pool::lock;
std::condition_variable thread_pool::cv;
std::list<std::function<void(void)> > thread_pool::queue;
thread_pool::thread_pool() {
for (unsigned i = 0; i < std::thread::hardware_concurrency(); i++) {
pool.emplace_back(std::bind(&thread_pool::thread_function, this));
}
}
thread_pool::~thread_pool() {
running = false;
cv.notify_all();
for (auto &&t : pool)
t.join();
}
void thread_pool::thread_function() const {
for (;;) {
bool have_work = false;
std::function<void(void)> work;
{
std::unique_lock<std::mutex> m(lock);
/*
* empty running wait
* 0 0 0
* 0 1 0
* 1 0 0
* 1 1 1
*/
cv.wait(m, [&]() { return !(queue.empty() && running); });
if (!queue.empty()) {
work = queue.front();
queue.pop_front();
have_work = true;
}
}
if (have_work) {
try {
work();
}
catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
} else if (!running) {
return;
}
}
}
<commit_msg>Disable global-ctor/exit-time-dtor warning for static members<commit_after>#include <cmath>
#include <array>
#include <chrono>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <sys/stat.h>
#include "simulation.h"
#include "codes/codes.h"
namespace detail {
inline bool file_exists(const std::string &fname) {
struct stat buf;
return (stat(fname.c_str(), &buf) != -1);
}
}
static std::array<double, 131> rates{
{ 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11,
0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22,
0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.30, 0.31, 0.32, 0.33,
0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.40, 0.41, 0.42, 0.43, 0.44,
0.45, 0.46, 0.47, 0.48, 0.49, 0.50, 0.51, 0.52, 0.53, 0.54, 0.55,
0.56, 0.57, 0.58, 0.59, 0.60, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66,
0.67, 0.68, 0.69, 0.70, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77,
0.78, 0.79, 0.800, 0.807, 0.817, 0.827, 0.837, 0.846, 0.855, 0.864, 0.872,
0.880, 0.887, 0.894, 0.900, 0.907, 0.913, 0.918, 0.924, 0.929, 0.934, 0.938,
0.943, 0.947, 0.951, 0.954, 0.958, 0.961, 0.964, 0.967, 0.970, 0.972, 0.974,
0.976, 0.978, 0.980, 0.982, 0.983, 0.984, 0.985, 0.986, 0.987, 0.988, 0.989,
0.990, 0.991, 0.992, 0.993, 0.994, 0.995, 0.996, 0.997, 0.998, 0.999 }
};
static std::array<double, 131> limits = {
{ -1.548, -1.531, -1.500, -1.470, -1.440, -1.409, -1.378, -1.347, -1.316,
-1.285, -1.254, -1.222, -1.190, -1.158, -1.126, -1.094, -1.061, -1.028,
-0.995, -0.963, -0.928, -0.896, -0.861, -0.827, -0.793, -0.757, -0.724,
-0.687, -0.651, -0.616, -0.579, -0.544, -0.507, -0.469, -0.432, -0.394,
-0.355, -0.314, -0.276, -0.236, -0.198, -0.156, -0.118, -0.074, -0.032,
0.010, 0.055, 0.097, 0.144, 0.188, 0.233, 0.279, 0.326, 0.374,
0.424, 0.474, 0.526, 0.574, 0.628, 0.682, 0.734, 0.791, 0.844,
0.904, 0.960, 1.021, 1.084, 1.143, 1.208, 1.275, 1.343, 1.412,
1.483, 1.554, 1.628, 1.708, 1.784, 1.867, 1.952, 2.045, 2.108,
2.204, 2.302, 2.402, 2.503, 2.600, 2.712, 2.812, 2.913, 3.009,
3.114, 3.205, 3.312, 3.414, 3.500, 3.612, 3.709, 3.815, 3.906,
4.014, 4.115, 4.218, 4.304, 4.425, 4.521, 4.618, 4.725, 4.841,
4.922, 5.004, 5.104, 5.196, 5.307, 5.418, 5.484, 5.549, 5.615,
5.681, 5.756, 5.842, 5.927, 6.023, 6.119, 6.234, 6.360, 6.495,
6.651, 6.837, 7.072, 7.378, 7.864 }
};
static constexpr double ebno(const double rate) {
if (rate <= 0.800) {
const size_t index = static_cast<size_t>(rate * 100);
return limits.at(index);
} else if (rate >= 0.999) {
return limits.back();
} else {
const size_t offset = 80;
const size_t index = static_cast<size_t>(std::distance(
std::cbegin(rates),
std::find_if(std::cbegin(rates) + offset, std::cend(rates) - 1,
[=](const double r) { return r >= rate; })));
return limits.at(index);
}
}
static std::ofstream open_file(const std::string &fname) {
if (detail::file_exists(fname)) {
std::ostringstream os;
os << "File " << fname << " already exists.";
throw std::runtime_error(os.str());
}
std::ofstream log_file(fname.c_str(), std::ofstream::out);
return log_file;
}
double awgn_simulation::sigma(const double eb_no) const {
return 1.0f / sqrt((2 * decoder.rate() * pow(10, eb_no / 10.0)));
}
awgn_simulation::awgn_simulation(const class decoder &decoder_,
const double step_, const uint64_t seed_)
: decoder(decoder_), step(step_), seed(seed_) {}
void awgn_simulation::operator()() {
const size_t wer_width = std::numeric_limits<double>::digits10;
const size_t ebno_width = 6;
std::ofstream log_file(open_file(decoder.to_string() + ".log"));
std::vector<float> b(decoder.n());
log_file << std::setw(ebno_width + 1) << "ebno"
<< " ";
log_file << std::setw(wer_width + 6) << "wer" << std::endl;
const size_t tmp = static_cast<size_t>(ebno(decoder.rate()) / step);
const double start = (tmp + (1.0 / step)) * step;
const double max = std::max(8.0, start) + step / 2;
/* TODO round ebno() up to next step */
for (double eb_no = start; eb_no < max; eb_no += step) {
std::normal_distribution<float> distribution(
1.0, static_cast<float>(sigma(eb_no)));
auto noise = std::bind(std::ref(distribution), std::ref(generator));
size_t word_errors = 0;
size_t samples = 10000;
std::cout << std::this_thread::get_id() << " " << decoder.to_string()
<< ": E_b/N_0 = " << eb_no << " with " << samples << " … ";
std::cout.flush();
auto start_time = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < samples; i++) {
std::generate(std::begin(b), std::end(b), noise);
try {
auto result = decoder.correct(b);
if (std::any_of(std::cbegin(result), std::cend(result),
[](const auto &bit) { return bool(bit); })) {
word_errors++;
}
}
catch (const decoding_failure &) {
word_errors++;
}
}
auto end_time = std::chrono::high_resolution_clock::now();
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
end_time - start_time).count();
std::cout << seconds << " s" << std::endl;
log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width)
<< std::defaultfloat << eb_no << " ";
log_file << std::setw(wer_width + 1) << std::setprecision(wer_width)
<< std::scientific << static_cast<double>(word_errors) / samples
<< std::endl;
}
}
bitflip_simulation::bitflip_simulation(const class decoder &decoder_,
const size_t errors_)
: decoder(decoder_), errors(errors_) {}
void bitflip_simulation::operator()() const {
const size_t wer_width = std::numeric_limits<double>::digits10;
const size_t ebno_width = 6;
std::ofstream log_file(open_file(decoder.to_string() + ".log"));
log_file << std::setw(ebno_width + 1) << "errors"
<< " ";
log_file << std::setw(wer_width + 6) << "wer" << std::endl;
const size_t length = decoder.n();
for (size_t error = 0; error <= errors; error++) {
size_t patterns = 0;
size_t word_errors = 0;
std::vector<int> b;
std::fill_n(std::back_inserter(b), length - error, 0);
std::fill_n(std::back_inserter(b), error, 1);
std::cout << std::this_thread::get_id() << " " << decoder.to_string()
<< ": errors = " << error << " … ";
std::cout.flush();
auto start = std::chrono::high_resolution_clock::now();
do {
std::vector<float> x;
x.reserve(length);
std::transform(std::cbegin(b), std::cend(b), std::back_inserter(x),
[](const auto &bit) { return -2 * bit + 1; });
patterns++;
try {
auto result = decoder.correct(x);
if (std::any_of(std::cbegin(result), std::cend(result),
[](const auto &bit) { return bool(bit); })) {
word_errors++;
}
}
catch (const decoding_failure &) {
word_errors++;
}
} while (std::next_permutation(std::begin(b), std::end(b)));
auto end = std::chrono::high_resolution_clock::now();
auto seconds =
std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
std::cout << seconds << " s " << word_errors << " " << patterns
<< std::endl;
log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width)
<< std::defaultfloat << error << " ";
log_file << std::setw(wer_width + 1) << std::setprecision(wer_width)
<< std::scientific << static_cast<double>(word_errors) / patterns
<< std::endl;
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wexit-time-destructors"
std::atomic_bool thread_pool::running{ true };
std::mutex thread_pool::lock;
std::condition_variable thread_pool::cv;
std::list<std::function<void(void)> > thread_pool::queue;
#pragma clang diagnostic pop
thread_pool::thread_pool() {
for (unsigned i = 0; i < std::thread::hardware_concurrency(); i++) {
pool.emplace_back(std::bind(&thread_pool::thread_function, this));
}
}
thread_pool::~thread_pool() {
running = false;
cv.notify_all();
for (auto &&t : pool)
t.join();
}
void thread_pool::thread_function() const {
for (;;) {
bool have_work = false;
std::function<void(void)> work;
{
std::unique_lock<std::mutex> m(lock);
/*
* empty running wait
* 0 0 0
* 0 1 0
* 1 0 0
* 1 1 1
*/
cv.wait(m, [&]() { return !(queue.empty() && running); });
if (!queue.empty()) {
work = queue.front();
queue.pop_front();
have_work = true;
}
}
if (have_work) {
try {
work();
}
catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
} else if (!running) {
return;
}
}
}
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/executable.h"
#include "tensorflow/compiler/xla/legacy_flags/debug_options_flags.h"
#include "tensorflow/compiler/xla/service/hlo_graph_dumper.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/env.h"
namespace xla {
StatusOr<std::vector<perftools::gputools::DeviceMemoryBase>>
Executable::ExecuteOnStreams(
tensorflow::gtl::ArraySlice<const ServiceExecutableRunOptions> run_options,
tensorflow::gtl::ArraySlice<
tensorflow::gtl::ArraySlice<perftools::gputools::DeviceMemoryBase>>
arguments) {
TF_RET_CHECK(run_options.size() == arguments.size());
if (run_options.size() == 1) {
TF_ASSIGN_OR_RETURN(auto result,
ExecuteOnStream(&run_options[0], arguments[0],
/*hlo_execution_profile=*/nullptr));
return std::vector<perftools::gputools::DeviceMemoryBase>({result});
}
std::vector<perftools::gputools::DeviceMemoryBase> return_values(
run_options.size());
for (size_t i = 0; i < run_options.size(); ++i) {
// We cannot BlockHostUntilDone() on the already-launched executions in case
// of error, since if the executions communicate, the initially launched
// executions may never complete if not all executions are running.
TF_ASSIGN_OR_RETURN(return_values[i],
ExecuteAsyncOnStream(&run_options[i], arguments[i]));
}
for (const auto& options : run_options) {
TF_RET_CHECK(options.stream() != nullptr);
options.stream()->BlockHostUntilDone();
}
return return_values;
}
Status Executable::DumpSessionModule() {
TF_RET_CHECK(dumping());
const string& directory_path =
module_config().debug_options().xla_dump_executions_to();
VersionedComputationHandle versioned_handle = entry_computation_handle();
// This filename does not include the version number because the computation
// is only ever executed at one version.
string filename = tensorflow::strings::Printf(
"computation_%lld__%s__execution_%lld", versioned_handle.handle.handle(),
session_module_->entry().name().c_str(), ++execution_count_);
return Executable::DumpToDirectory(directory_path, filename,
*session_module_);
}
// Removes illegal characters from filenames.
static void SanitizeFilename(string* name) {
for (char& c : *name) {
if (c == '/' || c == '\\' || c == '[' || c == ']') {
c = '_';
}
}
}
/* static */ Status Executable::DumpToDirectory(
const string& directory_path, string filename,
const SessionModule& session_module) {
tensorflow::Env* env = tensorflow::Env::Default();
if (!env->IsDirectory(directory_path).ok()) {
TF_RETURN_IF_ERROR(env->CreateDir(directory_path));
}
SanitizeFilename(&filename);
string file_path = tensorflow::io::JoinPath(directory_path, filename);
return tensorflow::WriteBinaryProto(env, file_path, session_module);
}
} // namespace xla
<commit_msg>When dumping XLA computations, use RecursivelyCreateDir instead of CreateDir.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/executable.h"
#include "tensorflow/compiler/xla/legacy_flags/debug_options_flags.h"
#include "tensorflow/compiler/xla/service/hlo_graph_dumper.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/env.h"
namespace xla {
StatusOr<std::vector<perftools::gputools::DeviceMemoryBase>>
Executable::ExecuteOnStreams(
tensorflow::gtl::ArraySlice<const ServiceExecutableRunOptions> run_options,
tensorflow::gtl::ArraySlice<
tensorflow::gtl::ArraySlice<perftools::gputools::DeviceMemoryBase>>
arguments) {
TF_RET_CHECK(run_options.size() == arguments.size());
if (run_options.size() == 1) {
TF_ASSIGN_OR_RETURN(auto result,
ExecuteOnStream(&run_options[0], arguments[0],
/*hlo_execution_profile=*/nullptr));
return std::vector<perftools::gputools::DeviceMemoryBase>({result});
}
std::vector<perftools::gputools::DeviceMemoryBase> return_values(
run_options.size());
for (size_t i = 0; i < run_options.size(); ++i) {
// We cannot BlockHostUntilDone() on the already-launched executions in case
// of error, since if the executions communicate, the initially launched
// executions may never complete if not all executions are running.
TF_ASSIGN_OR_RETURN(return_values[i],
ExecuteAsyncOnStream(&run_options[i], arguments[i]));
}
for (const auto& options : run_options) {
TF_RET_CHECK(options.stream() != nullptr);
options.stream()->BlockHostUntilDone();
}
return return_values;
}
Status Executable::DumpSessionModule() {
TF_RET_CHECK(dumping());
const string& directory_path =
module_config().debug_options().xla_dump_executions_to();
VersionedComputationHandle versioned_handle = entry_computation_handle();
// This filename does not include the version number because the computation
// is only ever executed at one version.
string filename = tensorflow::strings::Printf(
"computation_%lld__%s__execution_%lld", versioned_handle.handle.handle(),
session_module_->entry().name().c_str(), ++execution_count_);
return Executable::DumpToDirectory(directory_path, filename,
*session_module_);
}
// Removes illegal characters from filenames.
static void SanitizeFilename(string* name) {
for (char& c : *name) {
if (c == '/' || c == '\\' || c == '[' || c == ']') {
c = '_';
}
}
}
/* static */ Status Executable::DumpToDirectory(
const string& directory_path, string filename,
const SessionModule& session_module) {
tensorflow::Env* env = tensorflow::Env::Default();
if (!env->IsDirectory(directory_path).ok()) {
// NB! CreateDir does not work reliably with multiple XLA threads -- two
// threads can race to observe the absence of the dump directory and
// simultaneously try to create it, causing the "losing" thread to get a
// "directory already exists" error.
TF_RETURN_IF_ERROR(env->RecursivelyCreateDir(directory_path));
}
SanitizeFilename(&filename);
string file_path = tensorflow::io::JoinPath(directory_path, filename);
return tensorflow::WriteBinaryProto(env, file_path, session_module);
}
} // namespace xla
<|endoftext|> |
<commit_before>#include "lib_tilemap.h"
#include <stdio.h>
namespace TileMap {
template<class TColor>
bool Scene<TColor>::isRectFree(const int x1, const int y1, const int x2, const int y2) const {
if (!flagmap.isValid()) return true;
const uint8_t tileSizeBits = tileset.tileSizeBits;
const int16_t tileX1 = x1 >> tileSizeBits;
const int16_t tileY1 = y1 >> tileSizeBits;
const int16_t tileX2 = x2 >> tileSizeBits;
const int16_t tileY2 = y2 >> tileSizeBits;
const uint8_t width = tilemaps[0].getWidth();
const uint8_t height = tilemaps[0].getHeight();
for (int tileX = tileX1;tileX <= tileX2; tileX+=1) {
for (int tileY = tileY1;tileY <= tileY2; tileY+=1) {
if (tileX < 0 || tileY < 0 || tileX >= width || tileY >= height) {
continue;
}
const uint8_t tileIndex = flagmap.get(tileX,tileY);
if (tileIndex != 255) return false;
}
}
return true;
}
template<class TColor>
bool Scene<TColor>::isPixelFree(const int x, const int y, uint8_t& tileIndexOut) const {
if (!flagmap.isValid()) return true;
const uint8_t tileSizeBits = tileset.tileSizeBits;
const int16_t tileX = x >> tileSizeBits;
const int16_t tileY = y >> tileSizeBits;
const uint8_t width = tilemaps[0].getWidth();
const uint8_t height = tilemaps[0].getHeight();
if (tileX < 0 || tileY < 0 || tileX >= width || tileY >= height) {
return true;
}
const uint8_t tileIndex = flagmap.get(tileX,tileY);
/*const uint8_t tileIndex = foreground.get(tileX,tileY);
if (tileIndex == 255) {
return true;
}
const uint8_t subX = x & ((1<<tileSizeBits)-1);
const uint8_t subY = y & ((1<<tileSizeBits)-1);
const bool transparent = tileset.foreground.isTransparent(
((tileIndex & 0xf) << tileSizeBits) + subX,
((tileIndex >> 4) << tileSizeBits) + subY);
if (transparent) return true;
tileIndexOut = tileIndex;*/
return tileIndex == 255;
}
template<class TColor>
Math::Vector2D16 Scene<TColor>::moveOut(const Math::Vector2D16& pos, const uint8_t distleft, const uint8_t distright, const uint8_t disttop, const uint8_t distbottom) const {
uint8_t tileIndex;
if (isPixelFree(pos.x,pos.y,tileIndex)) return pos;
uint8_t right = 0, left = 0, up = 0, down = 0;
uint8_t rightIndex = 0, leftIndex = 0, upIndex = 0, downIndex = 0;
while (right < 32 && !isPixelFree(pos.x + right, pos.y, rightIndex)) right += 1;
while (left < 32 && !isPixelFree(pos.x - left, pos.y, leftIndex)) left += 1;
while (up < 32 && !isPixelFree(pos.x, pos.y - up, upIndex)) up += 1;
while (down < 32 && !isPixelFree(pos.x, pos.y + down, downIndex)) down += 1;
if (right - distleft < left - distright && right - distleft < down - disttop && right - distleft < up - distbottom) return pos + Math::Vector2D16(right, 0);
if (left - distright < down - disttop && left - distright < up - distbottom) return pos + Math::Vector2D16(-left, 0);
if (up - distbottom <= down - disttop) return pos + Math::Vector2D16(0, -up);
return pos + Math::Vector2D16(0, down);
}
template<class TColor>
Math::Vector2D16 Scene<TColor>::moveOut(const Math::Vector2D16& pos) const {
return moveOut(pos,0,0,0,0);
}
template class Scene<uint8_t>;
template class Scene<uint16_t>;
}
<commit_msg>More detail rich colission detection<commit_after>#include "lib_tilemap.h"
#include <stdio.h>
namespace TileMap {
static bool isRectIntersectingRect(int ax1,int ay1,int ax2,int ay2, int bx1, int by1, int bx2, int by2) {
return !(ax2 <= bx1 || bx2 <= ax1 || ay2 <= by1 || by2 <= ay1);
}
template<class TColor>
bool Scene<TColor>::isRectFree(const int x1, const int y1, const int x2, const int y2) const {
if (!flagmap.isValid()) return true;
const uint8_t tileSizeBits = tileset.tileSizeBits;
const uint8_t tileSize = 1 << tileSizeBits;
const int16_t tileX1 = x1 >> tileSizeBits;
const int16_t tileY1 = y1 >> tileSizeBits;
const int16_t tileX2 = x2 >> tileSizeBits;
const int16_t tileY2 = y2 >> tileSizeBits;
const uint8_t width = tilemaps[0].getWidth();
const uint8_t height = tilemaps[0].getHeight();
for (int tileX = tileX1;tileX <= tileX2; tileX+=1)
{
for (int tileY = tileY1;tileY <= tileY2; tileY+=1)
{
if (tileX < 0 || tileY < 0 || tileX >= width || tileY >= height) {
continue;
}
const uint8_t tileIndex = flagmap.get(tileX,tileY);
if (tileIndex != 255)
{
int16_t left= tileX << tileSizeBits;
int16_t top = tileY << tileSizeBits;
switch(tileIndex) {
case 0:
return false;
case 5: // top half blocked
//printf("%d,%d : %d,%d | %d,%d : %d,%d\n",x1,y1,x2,y2, left,top,left+tileSize,top+tileSize/2);
if (isRectIntersectingRect(x1,y1,x2,y2, left,top,left+tileSize,top+tileSize/2)) {
return false;
}
break;
case 6: // bottom half blocked
if (isRectIntersectingRect(x1,y1,x2,y2, left,top+tileSize/2,left+tileSize,top+tileSize)) {
return false;
}
break;
case 7: // left half blocked
if (isRectIntersectingRect(x1,y1,x2,y2, left,top,left+tileSize/2,top+tileSize)) {
return false;
}
break;
case 8: // right half blocked
if (isRectIntersectingRect(x1,y1,x2,y2, left+tileSize/2,top,left+tileSize,top+tileSize)) {
return false;
}
break;
default:
printf("unhandled flagmap id: %d\n",tileIndex);
}
}
}
}
return true;
}
template<class TColor>
bool Scene<TColor>::isPixelFree(const int x, const int y, uint8_t& tileIndexOut) const {
if (!flagmap.isValid()) return true;
const uint8_t tileSizeBits = tileset.tileSizeBits;
const int16_t tileX = x >> tileSizeBits;
const int16_t tileY = y >> tileSizeBits;
const uint8_t width = tilemaps[0].getWidth();
const uint8_t height = tilemaps[0].getHeight();
if (tileX < 0 || tileY < 0 || tileX >= width || tileY >= height) {
return true;
}
const uint8_t tileIndex = flagmap.get(tileX,tileY);
/*const uint8_t tileIndex = foreground.get(tileX,tileY);
if (tileIndex == 255) {
return true;
}
const uint8_t subX = x & ((1<<tileSizeBits)-1);
const uint8_t subY = y & ((1<<tileSizeBits)-1);
const bool transparent = tileset.foreground.isTransparent(
((tileIndex & 0xf) << tileSizeBits) + subX,
((tileIndex >> 4) << tileSizeBits) + subY);
if (transparent) return true;
tileIndexOut = tileIndex;*/
return tileIndex == 255;
}
template<class TColor>
Math::Vector2D16 Scene<TColor>::moveOut(const Math::Vector2D16& pos, const uint8_t distleft, const uint8_t distright, const uint8_t disttop, const uint8_t distbottom) const {
uint8_t tileIndex;
if (isPixelFree(pos.x,pos.y,tileIndex)) return pos;
uint8_t right = 0, left = 0, up = 0, down = 0;
uint8_t rightIndex = 0, leftIndex = 0, upIndex = 0, downIndex = 0;
while (right < 32 && !isPixelFree(pos.x + right, pos.y, rightIndex)) right += 1;
while (left < 32 && !isPixelFree(pos.x - left, pos.y, leftIndex)) left += 1;
while (up < 32 && !isPixelFree(pos.x, pos.y - up, upIndex)) up += 1;
while (down < 32 && !isPixelFree(pos.x, pos.y + down, downIndex)) down += 1;
if (right - distleft < left - distright && right - distleft < down - disttop && right - distleft < up - distbottom) return pos + Math::Vector2D16(right, 0);
if (left - distright < down - disttop && left - distright < up - distbottom) return pos + Math::Vector2D16(-left, 0);
if (up - distbottom <= down - disttop) return pos + Math::Vector2D16(0, -up);
return pos + Math::Vector2D16(0, down);
}
template<class TColor>
Math::Vector2D16 Scene<TColor>::moveOut(const Math::Vector2D16& pos) const {
return moveOut(pos,0,0,0,0);
}
template class Scene<uint8_t>;
template class Scene<uint16_t>;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: helpmerge.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-01-19 17:58:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// local includes
#include "export.hxx"
#include "xmlparse.hxx"
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>
#include <hash_map>
#include <memory> /* auto_ptr */
#include "tools/isofallback.hxx"
#include <vector>
/// This Class is responsible for extracting/merging OpenOffice XML Helpfiles
class HelpParser
{
private:
bool bUTF8;
ByteString sHelpFile;
/// Copy fallback language String (ENUS,DE) into position of the numeric language iso code
/// @PRECOND 0 < langIdx_in < MAX_IDX
void FillInFallbacks( LangHashMap& rElem_out, ByteString sLangIdx_in );
/// Debugmethod, prints the content of the map to stdout
static void Dump( LangHashMap* rElem_in , const ByteString sKey_in );
/// Debugmethod, prints the content of the map to stdout
static void Dump( XMLHashMap* rElem_in ) ;
public:
HelpParser( const ByteString &rHelpFile, bool bUTF8 );
~HelpParser(){};
/// Method creates/append a SDF file with the content of a parsed XML file
/// @PRECOND rHelpFile is valid
bool CreateSDF( const ByteString &rSDFFile_in, const ByteString &rPrj_in, const ByteString &rRoot_in );
/// Method merges the String from the SDFfile into XMLfile. Both Strings must
/// point to existing files.
bool Merge( const ByteString &rSDFFile_in, const ByteString &rDestinationFile_in );
bool Merge( const ByteString &rSDFFile, const ByteString &rPathX , const ByteString &rPathY , bool bISO );
private:
ByteString GetOutpath( const ByteString& rPathX , const ByteString& sCur , const ByteString& rPathY );
void Process( LangHashMap* aLangHM , ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile );
void ProcessHelp( LangHashMap* aLangHM , ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile );
void MakeDir( const ByteString& sPath );
};
<commit_msg>INTEGRATION: CWS hc2opti (1.3.12); FILE MERGED 2006/02/24 17:10:21 ihi 1.3.12.3: #i55666# hc2 build speedup 2006/02/14 15:34:29 ihi 1.3.12.2: RESYNC: (1.3-1.4); FILE MERGED 2006/02/14 13:02:05 ihi 1.3.12.1: #i55666# hc2 build speedup prototype<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: helpmerge.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-03-29 13:25:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// local includes
#include "export.hxx"
#include "xmlparse.hxx"
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>
#include <hash_map>
#include <memory> /* auto_ptr */
#include "tools/isofallback.hxx"
#include <vector>
/// This Class is responsible for extracting/merging OpenOffice XML Helpfiles
class HelpParser
{
private:
bool bUTF8;
bool bHasInputList;
ByteString sHelpFile;
/// Copy fallback language String (ENUS,DE) into position of the numeric language iso code
/// @PRECOND 0 < langIdx_in < MAX_IDX
void FillInFallbacks( LangHashMap& rElem_out, ByteString sLangIdx_in );
/// Debugmethod, prints the content of the map to stdout
static void Dump( LangHashMap* rElem_in , const ByteString sKey_in );
/// Debugmethod, prints the content of the map to stdout
static void Dump( XMLHashMap* rElem_in ) ;
public:
HelpParser( const ByteString &rHelpFile, bool bUTF8 , bool bHasInputList );
~HelpParser(){};
/// Method creates/append a SDF file with the content of a parsed XML file
/// @PRECOND rHelpFile is valid
bool CreateSDF( const ByteString &rSDFFile_in, const ByteString &rPrj_in, const ByteString &rRoot_in );
static void parse_languages( std::vector<ByteString>& aLanguages , MergeDataFile& aMergeDataFile );
/// Method merges the String from the SDFfile into XMLfile. Both Strings must
/// point to existing files.
//bool Merge( const ByteString &rSDFFile_in, const ByteString &rDestinationFile_in , const std::vector<ByteString>& aLanguages , MergeDataFile& aMergeDataFile );
bool Merge( const ByteString &rSDFFile_in, const ByteString &rDestinationFile_in , ByteString& sLanguage , MergeDataFile& aMergeDataFile );
bool Merge( const ByteString &rSDFFile, const ByteString &rPathX , const ByteString &rPathY , bool bISO
, const std::vector<ByteString>& aLanguages , MergeDataFile& aMergeDataFile , bool bCreateDir );
private:
ByteString GetOutpath( const ByteString& rPathX , const ByteString& sCur , const ByteString& rPathY );
bool MergeSingleFile( XMLFile* file , MergeDataFile& aMergeDataFile , const ByteString& sLanguage , ByteString sPath );
;
void Process( LangHashMap* aLangHM , const ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile );
void ProcessHelp( LangHashMap* aLangHM , const ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile );
void MakeDir( const ByteString& sPath );
};
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/common/shape.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
namespace tflite {
namespace gpu {
namespace {
struct GetAxisByIndexFunc {
template <Layout T>
Axis operator()() const {
return GetAxis<T>(index);
}
int32_t index;
};
struct GetIndexByAxisFunc {
template <Layout T>
int operator()() const {
return GetAxisIndex<T>(axis);
}
Axis axis;
};
struct NumAxisFunc {
template <Layout T>
int operator()() const {
return Size<T>();
}
};
} // namespace
std::string ToString(Axis axis) {
switch (axis) {
case Axis::BATCH:
return "batch";
case Axis::CHANNELS:
return "channels";
case Axis::INPUT_CHANNELS:
return "input_channels";
case Axis::OUTPUT_CHANNELS:
return "output_channels";
case Axis::HEIGHT:
return "height";
case Axis::WIDTH:
return "width";
case Axis::VALUE:
return "value";
case Axis::UNKNOWN:
return "unknown";
}
return "undefined";
}
std::string ToString(Layout layout) {
switch (layout) {
case Layout::SCALAR:
return "scalar";
case Layout::LINEAR:
return "linear";
case Layout::HW:
return "hw";
case Layout::CHW:
return "chw";
case Layout::HWC:
return "hwc";
case Layout::OHWI:
return "ohwi";
case Layout::IHWO:
return "ihwo";
case Layout::OIHW:
return "oihw";
case Layout::IOHW:
return "iohw";
case Layout::BHWC:
return "bhwc";
case Layout::UNKNOWN:
return "unknown";
}
return "undefined";
}
Axis GetAxis(Layout layout, int32_t index) {
return DispatchByLayout(layout, GetAxisByIndexFunc{index});
}
int GetAxisIndex(Layout layout, Axis axis) {
return DispatchByLayout(layout, GetIndexByAxisFunc{axis});
}
int Size(Layout layout) { return DispatchByLayout(layout, NumAxisFunc()); }
std::string ToString(const Shape& s) {
return absl::StrCat("{", ToString(s.layout), ", {",
absl::StrJoin(s.dimensions, ", "), "}}");
}
template <>
int64_t StrongShape<Layout::OHWI>::LinearIndex(
const std::array<int32_t, 4>& coordinates) const {
int64_t index = coordinates[0];
index = index * StrongShape::get(1) + coordinates[1];
index = index * StrongShape::get(2) + coordinates[2];
index = index * StrongShape::get(3) + coordinates[3];
return index;
}
} // namespace gpu
} // namespace tflite
<commit_msg>Remove unused code<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/common/shape.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
namespace tflite {
namespace gpu {
namespace {
struct GetAxisByIndexFunc {
template <Layout T>
Axis operator()() const {
return GetAxis<T>(index);
}
int32_t index;
};
struct GetIndexByAxisFunc {
template <Layout T>
int operator()() const {
return GetAxisIndex<T>(axis);
}
Axis axis;
};
struct NumAxisFunc {
template <Layout T>
int operator()() const {
return Size<T>();
}
};
} // namespace
std::string ToString(Axis axis) {
switch (axis) {
case Axis::BATCH:
return "batch";
case Axis::CHANNELS:
return "channels";
case Axis::INPUT_CHANNELS:
return "input_channels";
case Axis::OUTPUT_CHANNELS:
return "output_channels";
case Axis::HEIGHT:
return "height";
case Axis::WIDTH:
return "width";
case Axis::VALUE:
return "value";
case Axis::UNKNOWN:
return "unknown";
}
return "undefined";
}
std::string ToString(Layout layout) {
switch (layout) {
case Layout::SCALAR:
return "scalar";
case Layout::LINEAR:
return "linear";
case Layout::HW:
return "hw";
case Layout::CHW:
return "chw";
case Layout::HWC:
return "hwc";
case Layout::OHWI:
return "ohwi";
case Layout::IHWO:
return "ihwo";
case Layout::OIHW:
return "oihw";
case Layout::IOHW:
return "iohw";
case Layout::BHWC:
return "bhwc";
case Layout::UNKNOWN:
return "unknown";
}
return "undefined";
}
Axis GetAxis(Layout layout, int32_t index) {
return DispatchByLayout(layout, GetAxisByIndexFunc{index});
}
int GetAxisIndex(Layout layout, Axis axis) {
return DispatchByLayout(layout, GetIndexByAxisFunc{axis});
}
int Size(Layout layout) { return DispatchByLayout(layout, NumAxisFunc()); }
std::string ToString(const Shape& s) {
return absl::StrCat("{", ToString(s.layout), ", {",
absl::StrJoin(s.dimensions, ", "), "}}");
}
} // namespace gpu
} // namespace tflite
<|endoftext|> |
<commit_before>
#include "gtest/gtest.h"
#include "TEnum.h"
#include "TEnumConstant.h"
#include "TMemFile.h"
#include "TTree.h"
#include "TBranch.h"
#include "TBasket.h"
#include <vector>
static const Int_t gSampleEvents = 100;
void CreateSampleFile(TMemFile *&f)
{
f = new TMemFile("tbasket_test.root", "CREATE");
ASSERT_TRUE(f != nullptr);
ASSERT_FALSE(f->IsZombie());
TTree t1("t1", "Simple tree for testing.");
ASSERT_FALSE(t1.IsZombie());
Int_t idx;
t1.Branch("idx", &idx, "idx/I");
for (idx = 0; idx < gSampleEvents; idx++) {
t1.Fill();
}
t1.Write();
}
void VerifySampleFile(TFile *f)
{
TTree *tree = nullptr;
f->GetObject("t1", tree);
ASSERT_TRUE(tree != nullptr);
Int_t saved_idx;
tree->SetBranchAddress("idx", &saved_idx);
EXPECT_EQ(tree->GetEntries(), gSampleEvents);
for (Int_t idx = 0; idx < tree->GetEntries(); idx++) {
tree->GetEntry(idx);
EXPECT_EQ(idx, saved_idx);
}
}
TEST(TBasket, IOBits)
{
EXPECT_EQ(static_cast<Int_t>(TBasket::EIOBits::kSupported) |
static_cast<Int_t>(TBasket::EUnsupportedIOBits::kUnsupported),
(1 << static_cast<Int_t>(TBasket::kIOBitCount)) - 1);
EXPECT_EQ(
static_cast<Int_t>(TBasket::EIOBits::kSupported) & static_cast<Int_t>(TBasket::EUnsupportedIOBits::kUnsupported), 0);
TClass *cl = TClass::GetClass("TBasket");
ASSERT_NE(cl, nullptr);
TEnum *eIOBits = (TEnum *)cl->GetListOfEnums()->FindObject("EIOBits");
ASSERT_NE(eIOBits, nullptr);
Int_t supported = static_cast<Int_t>(TBasket::EIOBits::kSupported);
Bool_t foundSupported = false;
for (auto constant : TRangeStaticCast<TEnumConstant>(eIOBits->GetConstants())) {
if (!strcmp(constant->GetName(), "kSupported")) {
foundSupported = true;
continue;
}
EXPECT_EQ(constant->GetValue() & supported, constant->GetValue());
supported -= constant->GetValue();
}
EXPECT_TRUE(foundSupported);
EXPECT_EQ(supported, 0);
TEnum *eUnsupportedIOBits = (TEnum *)cl->GetListOfEnums()->FindObject("EUnsupportedIOBits");
ASSERT_NE(eUnsupportedIOBits, nullptr);
Int_t unsupported = static_cast<Int_t>(TBasket::EUnsupportedIOBits::kUnsupported);
Bool_t foundUnsupported = false;
for (auto constant : TRangeStaticCast<TEnumConstant>(eUnsupportedIOBits->GetConstants())) {
if (!strcmp(constant->GetName(), "kUnsupported")) {
foundUnsupported = true;
continue;
}
EXPECT_EQ(constant->GetValue() & unsupported, constant->GetValue());
unsupported -= constant->GetValue();
}
EXPECT_TRUE(foundUnsupported);
EXPECT_EQ(unsupported, 0);
}
// Basic "sanity check" test -- can we create and delete trees?
TEST(TBasket, CreateAndDestroy)
{
std::vector<char> memBuffer;
TMemFile *f;
CreateSampleFile(f);
f->Close();
Long64_t maxsize = f->GetSize();
memBuffer.reserve(maxsize);
f->CopyTo(&memBuffer[0], maxsize);
delete f;
TMemFile f2("tbasket_test.root", &memBuffer[0], maxsize, "READ");
ASSERT_FALSE(f2.IsZombie());
VerifySampleFile(&f2);
}
// Create a TTree, pull out a TBasket.
TEST(TBasket, CreateAndGetBasket)
{
TMemFile *f;
CreateSampleFile(f);
ASSERT_FALSE(f->IsZombie());
TTree *tree = nullptr;
f->GetObject("t1", tree);
ASSERT_NE(tree, nullptr);
ASSERT_FALSE(tree->IsZombie());
TBranch *br = tree->GetBranch("idx");
ASSERT_NE(br, nullptr);
ASSERT_FALSE(br->IsZombie());
TBasket *basket = br->GetBasket(0);
ASSERT_NE(basket, nullptr);
ASSERT_FALSE(basket->IsZombie());
EXPECT_EQ(basket->GetNevBuf(), gSampleEvents);
VerifySampleFile(f);
f->Close();
delete f;
}
TEST(TBasket, TestUnsupportedIO)
{
TMemFile *f;
// Create a file; not using the CreateSampleFile helper as
// we must corrupt the basket here.
f = new TMemFile("tbasket_test.root", "CREATE");
ASSERT_NE(f, nullptr);
ASSERT_FALSE(f->IsZombie());
TTree t1("t1", "Simple tree for testing.");
ASSERT_FALSE(t1.IsZombie());
Int_t idx;
t1.Branch("idx", &idx, "idx/I");
for (idx = 0; idx < gSampleEvents; idx++) {
t1.Fill();
}
TBranch *br = t1.GetBranch("idx");
ASSERT_NE(br, nullptr);
TBasket *basket = br->GetBasket(0);
ASSERT_NE(basket, nullptr);
TClass *cl = basket->IsA();
ASSERT_NE(cl, nullptr);
Long_t offset = cl->GetDataMemberOffset("fIOBits");
ASSERT_GT(offset, 0); // 0 can be returned on error
UChar_t *ioBits = reinterpret_cast<UChar_t *>(reinterpret_cast<char *>(basket) + offset);
EXPECT_EQ(*ioBits, 0);
// This tests that at least one bit in the bitset is available.
// When we are down to one bitset, we'll have to expand the field.
UChar_t unsupportedbits = ~static_cast<UChar_t>(TBasket::EIOBits::kSupported);
EXPECT_TRUE(unsupportedbits);
*ioBits = unsupportedbits & ((1 << 7) - 1); // Last bit should always be clear.
br->FlushBaskets();
t1.Write();
f->Close();
std::vector<char> memBuffer;
Long64_t maxsize = f->GetSize();
memBuffer.reserve(maxsize);
f->CopyTo(&memBuffer[0], maxsize);
TMemFile f2("tbasket_test.root", &memBuffer[0], maxsize, "READ");
TTree *tree;
f2.GetObject("t1", tree);
ASSERT_NE(tree, nullptr);
ASSERT_FALSE(tree->IsZombie());
br = tree->GetBranch("idx");
ASSERT_NE(br, nullptr);
basket = br->GetBasket(0);
// Getting the basket should fail here and an error should have been triggered.
ASSERT_EQ(basket, nullptr);
}
<commit_msg>Header in alphabetically order.<commit_after>
#include "gtest/gtest.h"
#include "TBasket.h"
#include "TBranch.h"
#include "TEnum.h"
#include "TEnumConstant.h"
#include "TMemFile.h"
#include "TTree.h"
#include <vector>
static const Int_t gSampleEvents = 100;
void CreateSampleFile(TMemFile *&f)
{
f = new TMemFile("tbasket_test.root", "CREATE");
ASSERT_TRUE(f != nullptr);
ASSERT_FALSE(f->IsZombie());
TTree t1("t1", "Simple tree for testing.");
ASSERT_FALSE(t1.IsZombie());
Int_t idx;
t1.Branch("idx", &idx, "idx/I");
for (idx = 0; idx < gSampleEvents; idx++) {
t1.Fill();
}
t1.Write();
}
void VerifySampleFile(TFile *f)
{
TTree *tree = nullptr;
f->GetObject("t1", tree);
ASSERT_TRUE(tree != nullptr);
Int_t saved_idx;
tree->SetBranchAddress("idx", &saved_idx);
EXPECT_EQ(tree->GetEntries(), gSampleEvents);
for (Int_t idx = 0; idx < tree->GetEntries(); idx++) {
tree->GetEntry(idx);
EXPECT_EQ(idx, saved_idx);
}
}
TEST(TBasket, IOBits)
{
EXPECT_EQ(static_cast<Int_t>(TBasket::EIOBits::kSupported) |
static_cast<Int_t>(TBasket::EUnsupportedIOBits::kUnsupported),
(1 << static_cast<Int_t>(TBasket::kIOBitCount)) - 1);
EXPECT_EQ(
static_cast<Int_t>(TBasket::EIOBits::kSupported) & static_cast<Int_t>(TBasket::EUnsupportedIOBits::kUnsupported), 0);
TClass *cl = TClass::GetClass("TBasket");
ASSERT_NE(cl, nullptr);
TEnum *eIOBits = (TEnum *)cl->GetListOfEnums()->FindObject("EIOBits");
ASSERT_NE(eIOBits, nullptr);
Int_t supported = static_cast<Int_t>(TBasket::EIOBits::kSupported);
Bool_t foundSupported = false;
for (auto constant : TRangeStaticCast<TEnumConstant>(eIOBits->GetConstants())) {
if (!strcmp(constant->GetName(), "kSupported")) {
foundSupported = true;
continue;
}
EXPECT_EQ(constant->GetValue() & supported, constant->GetValue());
supported -= constant->GetValue();
}
EXPECT_TRUE(foundSupported);
EXPECT_EQ(supported, 0);
TEnum *eUnsupportedIOBits = (TEnum *)cl->GetListOfEnums()->FindObject("EUnsupportedIOBits");
ASSERT_NE(eUnsupportedIOBits, nullptr);
Int_t unsupported = static_cast<Int_t>(TBasket::EUnsupportedIOBits::kUnsupported);
Bool_t foundUnsupported = false;
for (auto constant : TRangeStaticCast<TEnumConstant>(eUnsupportedIOBits->GetConstants())) {
if (!strcmp(constant->GetName(), "kUnsupported")) {
foundUnsupported = true;
continue;
}
EXPECT_EQ(constant->GetValue() & unsupported, constant->GetValue());
unsupported -= constant->GetValue();
}
EXPECT_TRUE(foundUnsupported);
EXPECT_EQ(unsupported, 0);
}
// Basic "sanity check" test -- can we create and delete trees?
TEST(TBasket, CreateAndDestroy)
{
std::vector<char> memBuffer;
TMemFile *f;
CreateSampleFile(f);
f->Close();
Long64_t maxsize = f->GetSize();
memBuffer.reserve(maxsize);
f->CopyTo(&memBuffer[0], maxsize);
delete f;
TMemFile f2("tbasket_test.root", &memBuffer[0], maxsize, "READ");
ASSERT_FALSE(f2.IsZombie());
VerifySampleFile(&f2);
}
// Create a TTree, pull out a TBasket.
TEST(TBasket, CreateAndGetBasket)
{
TMemFile *f;
CreateSampleFile(f);
ASSERT_FALSE(f->IsZombie());
TTree *tree = nullptr;
f->GetObject("t1", tree);
ASSERT_NE(tree, nullptr);
ASSERT_FALSE(tree->IsZombie());
TBranch *br = tree->GetBranch("idx");
ASSERT_NE(br, nullptr);
ASSERT_FALSE(br->IsZombie());
TBasket *basket = br->GetBasket(0);
ASSERT_NE(basket, nullptr);
ASSERT_FALSE(basket->IsZombie());
EXPECT_EQ(basket->GetNevBuf(), gSampleEvents);
VerifySampleFile(f);
f->Close();
delete f;
}
TEST(TBasket, TestUnsupportedIO)
{
TMemFile *f;
// Create a file; not using the CreateSampleFile helper as
// we must corrupt the basket here.
f = new TMemFile("tbasket_test.root", "CREATE");
ASSERT_NE(f, nullptr);
ASSERT_FALSE(f->IsZombie());
TTree t1("t1", "Simple tree for testing.");
ASSERT_FALSE(t1.IsZombie());
Int_t idx;
t1.Branch("idx", &idx, "idx/I");
for (idx = 0; idx < gSampleEvents; idx++) {
t1.Fill();
}
TBranch *br = t1.GetBranch("idx");
ASSERT_NE(br, nullptr);
TBasket *basket = br->GetBasket(0);
ASSERT_NE(basket, nullptr);
TClass *cl = basket->IsA();
ASSERT_NE(cl, nullptr);
Long_t offset = cl->GetDataMemberOffset("fIOBits");
ASSERT_GT(offset, 0); // 0 can be returned on error
UChar_t *ioBits = reinterpret_cast<UChar_t *>(reinterpret_cast<char *>(basket) + offset);
EXPECT_EQ(*ioBits, 0);
// This tests that at least one bit in the bitset is available.
// When we are down to one bitset, we'll have to expand the field.
UChar_t unsupportedbits = ~static_cast<UChar_t>(TBasket::EIOBits::kSupported);
EXPECT_TRUE(unsupportedbits);
*ioBits = unsupportedbits & ((1 << 7) - 1); // Last bit should always be clear.
br->FlushBaskets();
t1.Write();
f->Close();
std::vector<char> memBuffer;
Long64_t maxsize = f->GetSize();
memBuffer.reserve(maxsize);
f->CopyTo(&memBuffer[0], maxsize);
TMemFile f2("tbasket_test.root", &memBuffer[0], maxsize, "READ");
TTree *tree;
f2.GetObject("t1", tree);
ASSERT_NE(tree, nullptr);
ASSERT_FALSE(tree->IsZombie());
br = tree->GetBranch("idx");
ASSERT_NE(br, nullptr);
basket = br->GetBasket(0);
// Getting the basket should fail here and an error should have been triggered.
ASSERT_EQ(basket, nullptr);
}
<|endoftext|> |
<commit_before>// Check that the `atos` symbolizer works.
// RUN: %clangxx_asan -O0 %s -o %t
// RUN: %env_asan_opts=verbosity=2 ASAN_SYMBOLIZER_PATH=$(which atos) not %run %t 2>&1 | FileCheck %s
// Path returned by `which atos` is invalid on iOS.
// UNSUPPORTED: ios
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
char *x = (char*)malloc(10 * sizeof(char));
memset(x, 0, 10);
int res = x[argc];
free(x);
free(x + argc - 1); // BOOM
// CHECK: Using atos at user-specified path:
// CHECK: AddressSanitizer: attempting double-free{{.*}}in thread T0
// CHECK: #0 0x{{.*}} in {{.*}}free
// CHECK: #1 0x{{.*}} in main {{.*}}atos-symbolizer.cc:[[@LINE-4]]
// CHECK: freed by thread T0 here:
// CHECK: #0 0x{{.*}} in {{.*}}free
// CHECK: #1 0x{{.*}} in main {{.*}}atos-symbolizer.cc:[[@LINE-8]]
// CHECK: allocated by thread T0 here:
// CHECK: atos-symbolizer.cc:[[@LINE-13]]
return res;
}
<commit_msg>Mark the atos-symbolizer test as unsupported on i386-darwin<commit_after>// Check that the `atos` symbolizer works.
// RUN: %clangxx_asan -O0 %s -o %t
// RUN: %env_asan_opts=verbosity=2 ASAN_SYMBOLIZER_PATH=$(which atos) not %run %t 2>&1 | FileCheck %s
// Path returned by `which atos` is invalid on iOS.
// UNSUPPORTED: ios, i386-darwin
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
char *x = (char*)malloc(10 * sizeof(char));
memset(x, 0, 10);
int res = x[argc];
free(x);
free(x + argc - 1); // BOOM
// CHECK: Using atos at user-specified path:
// CHECK: AddressSanitizer: attempting double-free{{.*}}in thread T0
// CHECK: #0 0x{{.*}} in {{.*}}free
// CHECK: #1 0x{{.*}} in main {{.*}}atos-symbolizer.cc:[[@LINE-4]]
// CHECK: freed by thread T0 here:
// CHECK: #0 0x{{.*}} in {{.*}}free
// CHECK: #1 0x{{.*}} in main {{.*}}atos-symbolizer.cc:[[@LINE-8]]
// CHECK: allocated by thread T0 here:
// CHECK: atos-symbolizer.cc:[[@LINE-13]]
return res;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: vi.cpp
// Purpose: Implementation of class wxExSTC vi mode
// Author: Anton van Wezenbeek
// Created: 2009-11-21
// RCS-ID: $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/extension/stc.h>
#include <wx/extension/frd.h>
#if wxUSE_GUI
void wxExSTC::OnKeyVi(wxKeyEvent& event)
{
if(
!event.ShiftDown() &&
!event.ControlDown())
{
m_viCommand += event.GetUnicodeKey();
}
int repeat = atoi(m_viCommand.c_str());
if (repeat == 0)
{
repeat++;
}
bool handled_command = true;
if (m_viCommand.EndsWith("CW"))
{
for (int i = 0; i < repeat; i++) WordRightExtend();
m_viInsertMode = true;
}
else if (m_viCommand.EndsWith("DD"))
{
for (int i = 0; i < repeat; i++) LineDelete();
}
else if (m_viCommand.EndsWith("DW"))
{
for (int i = 0; i < repeat; i++) DelWordRight();
}
else if (m_viCommand.EndsWith("YY"))
{
const int line = LineFromPosition(GetCurrentPos());
const int start = PositionFromLine(line);
const int end = GetLineEndPosition(line + repeat);
CopyRange(start, end);
}
else
{
if (!event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case '0':
if (m_viCommand.length() == 1)
{
Home();
}
else
{
handled_command = false;
}
break;
case 'A': m_viInsertMode = true; CharRight(); break;
case 'B': for (int i = 0; i < repeat; i++) WordLeft(); break;
case 'G': DocumentStart(); break;
case 'H': for (int i = 0; i < repeat; i++) CharLeft(); break;
case 'I': m_viInsertMode = true; break;
case 'J': for (int i = 0; i < repeat; i++) LineDown(); break;
case 'K': for (int i = 0; i < repeat; i++) LineUp(); break;
case 'L': for (int i = 0; i < repeat; i++) CharRight(); break;
case 'N':
for (int i = 0; i < repeat; i++)
FindNext(wxExFindReplaceData::Get()->GetFindString());
case 'P':
{
const int pos = GetCurrentPos();
LineDown();
Home();
Paste();
GotoPos(pos);
}
break;
case 'W': for (int i = 0; i < repeat; i++) WordRight(); break;
case 'U': Undo(); break;
case 'X': DeleteBack(); break;
case '/':
{
wxASSERT(wxTheApp != NULL);
wxWindow* window = wxTheApp->GetTopWindow();
wxASSERT(window != NULL);
wxFrame* frame = wxDynamicCast(window, wxFrame);
wxASSERT(frame != NULL);
wxPostEvent(frame,
wxCommandEvent(wxEVT_COMMAND_MENU_SELECTED, wxID_FIND));
}
break;
// Repeat last text changing command.
case '.':
break;
case '[':
case ']':
{
const int brace_match = BraceMatch(GetCurrentPos());
if (brace_match != wxSTC_INVALID_POSITION)
{
GotoPos(brace_match);
}
}
break;
default:
handled_command = false;
}
}
else if (event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'A': m_viInsertMode = true; LineEnd(); break;
case 'D': DelLineRight(); break;
case 'G':
if (repeat > 1)
{
GotoLine(repeat - 1);
}
else
{
DocumentEnd();
}
break;
case 'N':
for (int i = 0; i < repeat; i++)
FindNext(wxExFindReplaceData::Get()->GetFindString(), false);
break;
case 'P':
{
LineUp();
Home();
Paste();
}
break;
// Reverse case current char.
case '1': // TODO: Should be ~, that does not work
{
wxString text(GetTextRange(GetCurrentPos(), GetCurrentPos() + 1));
wxIslower(text[0]) ? text.UpperCase(): text.LowerCase();
wxStyledTextCtrl::Replace(GetCurrentPos(), GetCurrentPos() + 1, text);
CharRight();
}
break;
case '4': LineEnd(); break; // $
case '[': ParaUp(); break; // {
case ']': ParaDown(); break; // }
default:
handled_command = false;
}
}
else if (event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'B': for (int i = 0; i < repeat; i++) PageUp(); break;
case 'E': for (int i = 0; i < repeat; i++) LineScrollUp(); break;
case 'F': for (int i = 0; i < repeat; i++) PageDown(); break;
case 'Y': for (int i = 0; i < repeat; i++) LineScrollDown(); break;
default:
handled_command = false;
}
}
else
{
wxFAIL;
}
}
if (handled_command)
{
m_viCommand.clear();
}
}
#endif // wxUSE_GUI
<commit_msg>added : command handling<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: vi.cpp
// Purpose: Implementation of class wxExSTC vi mode
// Author: Anton van Wezenbeek
// Created: 2009-11-21
// RCS-ID: $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/textdlg.h>
#include <wx/extension/stc.h>
#include <wx/extension/frd.h>
#if wxUSE_GUI
void wxExSTC::OnKeyVi(wxKeyEvent& event)
{
if(
!event.ShiftDown() &&
!event.ControlDown())
{
m_viCommand += event.GetUnicodeKey();
}
int repeat = atoi(m_viCommand.c_str());
if (repeat == 0)
{
repeat++;
}
bool handled_command = true;
if (m_viCommand.EndsWith("CW"))
{
for (int i = 0; i < repeat; i++) WordRightExtend();
m_viInsertMode = true;
}
else if (m_viCommand.EndsWith("DD"))
{
for (int i = 0; i < repeat; i++) LineDelete();
}
else if (m_viCommand.EndsWith("DW"))
{
for (int i = 0; i < repeat; i++) DelWordRight();
}
else if (m_viCommand.EndsWith("YY"))
{
const int line = LineFromPosition(GetCurrentPos());
const int start = PositionFromLine(line);
const int end = GetLineEndPosition(line + repeat);
CopyRange(start, end);
}
else
{
if (!event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case '0':
if (m_viCommand.length() == 1)
{
Home();
}
else
{
handled_command = false;
}
break;
case 'A': m_viInsertMode = true; CharRight(); break;
case 'B': for (int i = 0; i < repeat; i++) WordLeft(); break;
case 'G': DocumentStart(); break;
case 'H': for (int i = 0; i < repeat; i++) CharLeft(); break;
case 'I': m_viInsertMode = true; break;
case 'J': for (int i = 0; i < repeat; i++) LineDown(); break;
case 'K': for (int i = 0; i < repeat; i++) LineUp(); break;
case 'L': for (int i = 0; i < repeat; i++) CharRight(); break;
case 'N':
for (int i = 0; i < repeat; i++)
FindNext(wxExFindReplaceData::Get()->GetFindString());
case 'P':
{
const int pos = GetCurrentPos();
LineDown();
Home();
Paste();
GotoPos(pos);
}
break;
case 'W': for (int i = 0; i < repeat; i++) WordRight(); break;
case 'U': Undo(); break;
case 'X': DeleteBack(); break;
case '/':
{
wxASSERT(wxTheApp != NULL);
wxWindow* window = wxTheApp->GetTopWindow();
wxASSERT(window != NULL);
wxFrame* frame = wxDynamicCast(window, wxFrame);
wxASSERT(frame != NULL);
wxPostEvent(frame,
wxCommandEvent(wxEVT_COMMAND_MENU_SELECTED, wxID_FIND));
}
break;
// Repeat last text changing command.
case '.':
break;
case '[':
case ']':
{
const int brace_match = BraceMatch(GetCurrentPos());
if (brace_match != wxSTC_INVALID_POSITION)
{
GotoPos(brace_match);
}
}
break;
default:
handled_command = false;
}
}
else if (event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'A': m_viInsertMode = true; LineEnd(); break;
case 'D': DelLineRight(); break;
case 'G':
if (repeat > 1)
{
GotoLine(repeat - 1);
}
else
{
DocumentEnd();
}
break;
case 'N':
for (int i = 0; i < repeat; i++)
FindNext(wxExFindReplaceData::Get()->GetFindString(), false);
break;
case 'P':
{
LineUp();
Home();
Paste();
}
break;
// Reverse case current char.
case '1': // TODO: Should be ~, that does not work
{
wxString text(GetTextRange(GetCurrentPos(), GetCurrentPos() + 1));
wxIslower(text[0]) ? text.UpperCase(): text.LowerCase();
wxStyledTextCtrl::Replace(GetCurrentPos(), GetCurrentPos() + 1, text);
CharRight();
}
break;
case '4': LineEnd(); break; // $
case '[': ParaUp(); break; // {
case ']': ParaDown(); break; // }
case ';': // :
{
wxTextEntryDialog dlg(this, ":", "vi");
if (dlg.ShowModal())
{
const wxString value = dlg.GetValue();
if (atoi(value.c_str()) != 0)
{
GotoLine(atoi(value.c_str()));
}
}
}
default:
handled_command = false;
}
}
else if (event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'B': for (int i = 0; i < repeat; i++) PageUp(); break;
case 'E': for (int i = 0; i < repeat; i++) LineScrollUp(); break;
case 'F': for (int i = 0; i < repeat; i++) PageDown(); break;
case 'Y': for (int i = 0; i < repeat; i++) LineScrollDown(); break;
default:
handled_command = false;
}
}
else
{
wxFAIL;
}
}
if (handled_command)
{
m_viCommand.clear();
}
}
#endif // wxUSE_GUI
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: vi.cpp
// Purpose: Implementation of class wxExSTC vi mode
// Author: Anton van Wezenbeek
// Created: 2009-11-21
// RCS-ID: $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/textdlg.h>
#include <wx/tokenzr.h>
#include <wx/extension/vi.h>
#include <wx/extension/stc.h>
#if wxUSE_GUI
wxExVi::wxExVi(wxExSTC* stc)
: m_STC(stc)
, m_InsertMode(true)
{
ResetInsertMode();
}
void wxExVi::Delete(
const wxString& begin_address,
const wxString& end_address)
{
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->Cut();
}
void wxExVi::LineEditor(const wxString& command)
{
if (command.empty())
{
// Do nothing.
}
if (command == "$")
{
m_STC->DocumentEnd();
}
else if (command == ".=")
{
m_STC->CallTipShow(
m_STC->GetCurrentPos(),
wxString::Format("%d", m_STC->GetCurrentLine() + 1));
}
else if (command.IsNumber())
{
m_STC->GotoLine(atoi(command.c_str()) - 1);
}
else if (command.StartsWith("w"))
{
m_STC->FileSave();
}
else
{
// [address] m destination
// [address] s [/pattern/replacement/] [options] [count]
wxStringTokenizer tkz(command, "dmsy");
const wxString address = tkz.GetNextToken();
const wxChar cmd = tkz.GetLastDelimiter();
wxString begin_address;
wxString end_address;
if (address == ".")
{
begin_address = address;
end_address = address;
}
else if (address == "%")
{
begin_address = "1";
end_address = "$";
}
else
{
begin_address = address.BeforeFirst(',');
end_address = address.AfterFirst(',');
}
switch (cmd)
{
case 'd':
Delete(begin_address, end_address);
break;
case 'm':
Move(begin_address, end_address, tkz.GetNextToken());
break;
case 's':
{
wxStringTokenizer tkz(tkz.GetNextToken(), "/");
tkz.GetNextToken(); // skip empty token
const wxString pattern = tkz.GetNextToken();
const wxString replacement = tkz.GetNextToken();
Substitute(begin_address, end_address, pattern, replacement);
}
break;
case 'y':
Yank(begin_address, end_address);
break;
}
}
}
void wxExVi::Move(
const wxString& begin_address,
const wxString& end_address,
const wxString& destination)
{
const int dest_line = ToLineNumber(destination);
if (dest_line == 0)
{
return;
}
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->BeginUndoAction();
m_STC->Cut();
m_STC->GotoLine(dest_line - 1);
m_STC->Paste();
m_STC->EndUndoAction();
}
void wxExVi::OnKey(wxKeyEvent& event)
{
if(
!event.ShiftDown() &&
!event.ControlDown())
{
m_Command += event.GetUnicodeKey();
}
int repeat = atoi(m_Command.c_str());
if (repeat == 0)
{
repeat++;
}
bool handled_command = true;
// Handle multichar commands.
if (m_Command.EndsWith("CW"))
{
for (int i = 0; i < repeat; i++) m_STC->WordRightExtend();
SetInsertMode();
}
else if (m_Command.EndsWith("DD"))
{
const int line = m_STC->LineFromPosition(m_STC->GetCurrentPos());
const int start = m_STC->PositionFromLine(line);
const int end = m_STC->GetLineEndPosition(line + repeat - 1);
m_STC->SetSelectionStart(start);
m_STC->SetSelectionEnd(end);
m_STC->Cut();
}
else if (m_Command.EndsWith("DW"))
{
m_STC->BeginUndoAction();
for (int i = 0; i < repeat; i++) m_STC->DelWordRight();
m_STC->EndUndoAction();
}
else if (m_Command.Matches("*F?"))
{
for (int i = 0; i < repeat; i++) m_STC->FindNext(m_Command.Last());
}
else if (m_Command.EndsWith("YY"))
{
const int line = m_STC->LineFromPosition(m_STC->GetCurrentPos());
const int start = m_STC->PositionFromLine(line);
const int end = m_STC->GetLineEndPosition(line + repeat - 1);
m_STC->CopyRange(start, end);
}
else
{
if (!event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case '0':
if (m_Command.length() == 1)
{
m_STC->Home();
}
else
{
handled_command = false;
}
break;
case 'A': SetInsertMode(); m_STC->CharRight(); break;
case 'B': for (int i = 0; i < repeat; i++) m_STC->WordLeft(); break;
case 'G': m_STC->DocumentStart(); break;
case 'H':
case WXK_LEFT:
for (int i = 0; i < repeat; i++) m_STC->CharLeft();
break;
case 'I': SetInsertMode(); break;
case 'J':
case WXK_DOWN:
for (int i = 0; i < repeat; i++) m_STC->LineDown();
break;
case 'K':
case WXK_UP:
for (int i = 0; i < repeat; i++) m_STC->LineUp();
break;
case 'L':
case ' ':
case WXK_RIGHT:
for (int i = 0; i < repeat; i++) m_STC->CharRight();
break;
case 'N':
for (int i = 0; i < repeat; i++)
m_STC->FindNext(m_STC->GetSearchText());
break;
case 'P':
{
const int pos = m_STC->GetCurrentPos();
m_STC->LineDown();
m_STC->Home();
m_STC->Paste();
m_STC->GotoPos(pos);
}
break;
case 'W': for (int i = 0; i < repeat; i++) m_STC->WordRight(); break;
case 'U': m_STC->Undo(); break;
case 'X': m_STC->DeleteBack(); break;
case '/':
{
wxTextEntryDialog dlg(
m_STC,
"/",
"vi",
m_STC->GetSearchText());
if (dlg.ShowModal() == wxID_OK)
{
m_STC->FindNext(dlg.GetValue());
}
}
break;
// Repeat last text changing command.
case '.':
break;
case '[':
case ']':
{
const int brace_match = m_STC->BraceMatch(m_STC->GetCurrentPos());
if (brace_match != wxSTC_INVALID_POSITION)
{
m_STC->GotoPos(brace_match);
}
}
break;
case WXK_RETURN:
m_STC->LineDown();
break;
default:
handled_command = false;
}
}
else if (event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'A': SetInsertMode(); m_STC->LineEnd(); break;
case 'D': m_STC->DelLineRight(); break;
case 'G':
if (repeat > 1)
{
m_STC->GotoLine(repeat - 1);
}
else
{
m_STC->DocumentEnd();
}
break;
case 'N':
for (int i = 0; i < repeat; i++)
m_STC->FindNext(m_STC->GetSearchText(), false);
break;
case 'P':
{
m_STC->LineUp();
m_STC->Home();
m_STC->Paste();
}
break;
// Reverse case current char.
case '1': // TODO: Should be ~, that does not work
{
wxString text(m_STC->GetTextRange(
m_STC->GetCurrentPos(),
m_STC->GetCurrentPos() + 1));
wxIslower(text[0]) ? text.UpperCase(): text.LowerCase();
m_STC->wxStyledTextCtrl::Replace(
m_STC->GetCurrentPos(),
m_STC->GetCurrentPos() + 1,
text);
m_STC->CharRight();
}
break;
case '4': m_STC->LineEnd(); break; // $
case '[': m_STC->ParaUp(); break; // {
case ']': m_STC->ParaDown(); break; // }
case ';': // :
{
wxTextEntryDialog dlg(m_STC, ":", "vi");
if (dlg.ShowModal() == wxID_OK)
{
LineEditor(dlg.GetValue());
}
}
break;
case '/':
{
wxTextEntryDialog dlg(
m_STC,
"?",
"vi",
m_STC->GetSearchText());
if (dlg.ShowModal() == wxID_OK)
{
m_STC->FindNext(dlg.GetValue(), false);
}
}
break;
default:
handled_command = false;
}
}
else if (event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'B': for (int i = 0; i < repeat; i++) m_STC->PageUp(); break;
case 'E': for (int i = 0; i < repeat; i++) m_STC->LineScrollUp(); break;
case 'F': for (int i = 0; i < repeat; i++) m_STC->PageDown(); break;
case 'Y': for (int i = 0; i < repeat; i++) m_STC->LineScrollDown(); break;
default:
handled_command = false;
}
}
else
{
wxFAIL;
}
}
if (handled_command)
{
m_Command.clear();
}
}
void wxExVi::ResetInsertMode()
{
if (m_InsertMode)
{
m_InsertMode = false;
}
}
void wxExVi::SetInsertMode()
{
m_InsertMode = true;
}
bool wxExVi::SetSelection(
const wxString& begin_address,
const wxString& end_address)
{
const int begin_line = ToLineNumber(begin_address);
const int end_line = ToLineNumber(end_address);
if (begin_line == 0 || end_line == 0)
{
return false;
}
m_STC->SetSelectionStart(m_STC->PositionFromLine(begin_line - 1));
m_STC->SetSelectionEnd(m_STC->GetLineEndPosition(end_line - 1));
return true;
}
void wxExVi::Substitute(
const wxString& begin_address,
const wxString& end_address,
const wxString& pattern,
const wxString& replacement)
{
m_STC->SetSearchFlags(wxSTC_FIND_REGEXP);
const int begin_line = ToLineNumber(begin_address);
const int end_line = ToLineNumber(end_address);
if (begin_line == 0 || end_line == 0)
{
return;
}
m_STC->BeginUndoAction();
m_STC->SetTargetStart(m_STC->PositionFromLine(begin_line - 1));
m_STC->SetTargetEnd(m_STC->GetLineEndPosition(end_line - 1));
while (m_STC->SearchInTarget(pattern) > 0)
{
const int start = m_STC->GetTargetStart();
const int length = m_STC->ReplaceTarget(replacement);
m_STC->SetTargetStart(start + length);
m_STC->SetTargetEnd(m_STC->GetLineEndPosition(end_line - 1));
}
m_STC->EndUndoAction();
}
int wxExVi::ToLineNumber(const wxString& address) const
{
if (address == "$")
{
return m_STC->GetLineCount();
}
wxString filtered_address(address);
int dot = 0;
if (filtered_address.Contains("."))
{
dot = m_STC->GetCurrentLine();
filtered_address.Replace(".", "");
if (!filtered_address.IsNumber()) return 0;
}
const int line_no = dot + atoi(filtered_address.c_str());
if (line_no < 0)
{
return 0;
}
return line_no;
}
void wxExVi::Yank(
const wxString& begin_address,
const wxString& end_address)
{
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->Copy();
}
#endif // wxUSE_GUI
<commit_msg>fixed error<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: vi.cpp
// Purpose: Implementation of class wxExSTC vi mode
// Author: Anton van Wezenbeek
// Created: 2009-11-21
// RCS-ID: $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/textdlg.h>
#include <wx/tokenzr.h>
#include <wx/extension/vi.h>
#include <wx/extension/stc.h>
#if wxUSE_GUI
wxExVi::wxExVi(wxExSTC* stc)
: m_STC(stc)
, m_InsertMode(true)
{
ResetInsertMode();
}
void wxExVi::Delete(
const wxString& begin_address,
const wxString& end_address)
{
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->Cut();
}
void wxExVi::LineEditor(const wxString& command)
{
if (command.empty())
{
// Do nothing.
}
if (command == "$")
{
m_STC->DocumentEnd();
}
else if (command == ".=")
{
m_STC->CallTipShow(
m_STC->GetCurrentPos(),
wxString::Format("%d", m_STC->GetCurrentLine() + 1));
}
else if (command.IsNumber())
{
m_STC->GotoLine(atoi(command.c_str()) - 1);
}
else if (command.StartsWith("w"))
{
m_STC->FileSave();
}
else
{
// [address] m destination
// [address] s [/pattern/replacement/] [options] [count]
wxStringTokenizer tkz(command, "dmsy");
const wxString address = tkz.GetNextToken();
const wxChar cmd = tkz.GetLastDelimiter();
wxString begin_address;
wxString end_address;
if (address == ".")
{
begin_address = address;
end_address = address;
}
else if (address == "%")
{
begin_address = "1";
end_address = "$";
}
else
{
begin_address = address.BeforeFirst(',');
end_address = address.AfterFirst(',');
}
switch (cmd)
{
case 'd':
Delete(begin_address, end_address);
break;
case 'm':
Move(begin_address, end_address, tkz.GetString());
break;
case 's':
{
wxStringTokenizer tkz(tkz.GetString(), "/");
tkz.GetNextToken(); // skip empty token
const wxString pattern = tkz.GetNextToken();
const wxString replacement = tkz.GetNextToken();
Substitute(begin_address, end_address, pattern, replacement);
}
break;
case 'y':
Yank(begin_address, end_address);
break;
}
}
}
void wxExVi::Move(
const wxString& begin_address,
const wxString& end_address,
const wxString& destination)
{
const int dest_line = ToLineNumber(destination);
if (dest_line == 0)
{
return;
}
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->BeginUndoAction();
m_STC->Cut();
m_STC->GotoLine(dest_line - 1);
m_STC->Paste();
m_STC->EndUndoAction();
}
void wxExVi::OnKey(wxKeyEvent& event)
{
if(
!event.ShiftDown() &&
!event.ControlDown())
{
m_Command += event.GetUnicodeKey();
}
int repeat = atoi(m_Command.c_str());
if (repeat == 0)
{
repeat++;
}
bool handled_command = true;
// Handle multichar commands.
if (m_Command.EndsWith("CW"))
{
for (int i = 0; i < repeat; i++) m_STC->WordRightExtend();
SetInsertMode();
}
else if (m_Command.EndsWith("DD"))
{
const int line = m_STC->LineFromPosition(m_STC->GetCurrentPos());
const int start = m_STC->PositionFromLine(line);
const int end = m_STC->GetLineEndPosition(line + repeat - 1);
m_STC->SetSelectionStart(start);
m_STC->SetSelectionEnd(end);
m_STC->Cut();
}
else if (m_Command.EndsWith("DW"))
{
m_STC->BeginUndoAction();
for (int i = 0; i < repeat; i++) m_STC->DelWordRight();
m_STC->EndUndoAction();
}
else if (m_Command.Matches("*F?"))
{
for (int i = 0; i < repeat; i++) m_STC->FindNext(m_Command.Last());
}
else if (m_Command.EndsWith("YY"))
{
const int line = m_STC->LineFromPosition(m_STC->GetCurrentPos());
const int start = m_STC->PositionFromLine(line);
const int end = m_STC->GetLineEndPosition(line + repeat - 1);
m_STC->CopyRange(start, end);
}
else
{
if (!event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case '0':
if (m_Command.length() == 1)
{
m_STC->Home();
}
else
{
handled_command = false;
}
break;
case 'A': SetInsertMode(); m_STC->CharRight(); break;
case 'B': for (int i = 0; i < repeat; i++) m_STC->WordLeft(); break;
case 'G': m_STC->DocumentStart(); break;
case 'H':
case WXK_LEFT:
for (int i = 0; i < repeat; i++) m_STC->CharLeft();
break;
case 'I': SetInsertMode(); break;
case 'J':
case WXK_DOWN:
for (int i = 0; i < repeat; i++) m_STC->LineDown();
break;
case 'K':
case WXK_UP:
for (int i = 0; i < repeat; i++) m_STC->LineUp();
break;
case 'L':
case ' ':
case WXK_RIGHT:
for (int i = 0; i < repeat; i++) m_STC->CharRight();
break;
case 'N':
for (int i = 0; i < repeat; i++)
m_STC->FindNext(m_STC->GetSearchText());
break;
case 'P':
{
const int pos = m_STC->GetCurrentPos();
m_STC->LineDown();
m_STC->Home();
m_STC->Paste();
m_STC->GotoPos(pos);
}
break;
case 'W': for (int i = 0; i < repeat; i++) m_STC->WordRight(); break;
case 'U': m_STC->Undo(); break;
case 'X': m_STC->DeleteBack(); break;
case '/':
{
wxTextEntryDialog dlg(
m_STC,
"/",
"vi",
m_STC->GetSearchText());
if (dlg.ShowModal() == wxID_OK)
{
m_STC->FindNext(dlg.GetValue());
}
}
break;
// Repeat last text changing command.
case '.':
break;
case '[':
case ']':
{
const int brace_match = m_STC->BraceMatch(m_STC->GetCurrentPos());
if (brace_match != wxSTC_INVALID_POSITION)
{
m_STC->GotoPos(brace_match);
}
}
break;
case WXK_RETURN:
m_STC->LineDown();
break;
default:
handled_command = false;
}
}
else if (event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'A': SetInsertMode(); m_STC->LineEnd(); break;
case 'D': m_STC->DelLineRight(); break;
case 'G':
if (repeat > 1)
{
m_STC->GotoLine(repeat - 1);
}
else
{
m_STC->DocumentEnd();
}
break;
case 'N':
for (int i = 0; i < repeat; i++)
m_STC->FindNext(m_STC->GetSearchText(), false);
break;
case 'P':
{
m_STC->LineUp();
m_STC->Home();
m_STC->Paste();
}
break;
// Reverse case current char.
case '1': // TODO: Should be ~, that does not work
{
wxString text(m_STC->GetTextRange(
m_STC->GetCurrentPos(),
m_STC->GetCurrentPos() + 1));
wxIslower(text[0]) ? text.UpperCase(): text.LowerCase();
m_STC->wxStyledTextCtrl::Replace(
m_STC->GetCurrentPos(),
m_STC->GetCurrentPos() + 1,
text);
m_STC->CharRight();
}
break;
case '4': m_STC->LineEnd(); break; // $
case '[': m_STC->ParaUp(); break; // {
case ']': m_STC->ParaDown(); break; // }
case ';': // :
{
wxTextEntryDialog dlg(m_STC, ":", "vi");
if (dlg.ShowModal() == wxID_OK)
{
LineEditor(dlg.GetValue());
}
}
break;
case '/':
{
wxTextEntryDialog dlg(
m_STC,
"?",
"vi",
m_STC->GetSearchText());
if (dlg.ShowModal() == wxID_OK)
{
m_STC->FindNext(dlg.GetValue(), false);
}
}
break;
default:
handled_command = false;
}
}
else if (event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'B': for (int i = 0; i < repeat; i++) m_STC->PageUp(); break;
case 'E': for (int i = 0; i < repeat; i++) m_STC->LineScrollUp(); break;
case 'F': for (int i = 0; i < repeat; i++) m_STC->PageDown(); break;
case 'Y': for (int i = 0; i < repeat; i++) m_STC->LineScrollDown(); break;
default:
handled_command = false;
}
}
else
{
wxFAIL;
}
}
if (handled_command)
{
m_Command.clear();
}
}
void wxExVi::ResetInsertMode()
{
if (m_InsertMode)
{
m_InsertMode = false;
}
}
void wxExVi::SetInsertMode()
{
m_InsertMode = true;
}
bool wxExVi::SetSelection(
const wxString& begin_address,
const wxString& end_address)
{
const int begin_line = ToLineNumber(begin_address);
const int end_line = ToLineNumber(end_address);
if (begin_line == 0 || end_line == 0)
{
return false;
}
m_STC->SetSelectionStart(m_STC->PositionFromLine(begin_line - 1));
m_STC->SetSelectionEnd(m_STC->GetLineEndPosition(end_line - 1));
return true;
}
void wxExVi::Substitute(
const wxString& begin_address,
const wxString& end_address,
const wxString& pattern,
const wxString& replacement)
{
m_STC->SetSearchFlags(wxSTC_FIND_REGEXP);
const int begin_line = ToLineNumber(begin_address);
const int end_line = ToLineNumber(end_address);
if (begin_line == 0 || end_line == 0)
{
return;
}
m_STC->BeginUndoAction();
m_STC->SetTargetStart(m_STC->PositionFromLine(begin_line - 1));
m_STC->SetTargetEnd(m_STC->GetLineEndPosition(end_line - 1));
while (m_STC->SearchInTarget(pattern) > 0)
{
const int start = m_STC->GetTargetStart();
const int length = m_STC->ReplaceTarget(replacement);
m_STC->SetTargetStart(start + length);
m_STC->SetTargetEnd(m_STC->GetLineEndPosition(end_line - 1));
}
m_STC->EndUndoAction();
}
int wxExVi::ToLineNumber(const wxString& address) const
{
if (address == "$")
{
return m_STC->GetLineCount() + 1;
}
wxString filtered_address(address);
int dot = 0;
if (filtered_address.Contains("."))
{
dot = m_STC->GetCurrentLine() + 1;
filtered_address.Replace(".", "");
if (!filtered_address.IsNumber()) return 0;
}
const int line_no = dot + atoi(filtered_address.c_str());
if (line_no < 0)
{
return 0;
}
return line_no;
}
void wxExVi::Yank(
const wxString& begin_address,
const wxString& end_address)
{
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->Copy();
}
#endif // wxUSE_GUI
<|endoftext|> |
<commit_before>/*
* AttentionalFocusCB.cc
*
* Copyright (C) 2014 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com> July 2014
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "AttentionalFocusCB.h"
using namespace opencog;
bool AttentionalFocusCB::node_match(Handle& node1, Handle& node2) {
HandleSeq af_handle_seq;
_atom_space->getHandleSetInAttentionalFocus(back_inserter(af_handle_seq));
bool not_match = true;
if (af_handle_seq.empty()) {
std::cout << "[INFO]:No atom in AF looking for more node..."
<< std::endl;
return true; //not a match
} else {
for (std::vector<Handle>::const_iterator j = af_handle_seq.begin();
j != af_handle_seq.end(); ++j) {
Handle h(*j);
//select atom not in AF [what other criteria can we have here ?]
if (node2 == h) {
not_match = false;
break;
}
}
bool AttentionalFocusCB::node_match(Handle& node1, Handle& node2) {
if (node1 == node2
and node2->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
return false;
} else {
return true;
}
}
bool AttentionalFocusCB::link_match(LinkPtr& lpat, LinkPtr& lsoln) {
if (DefaultPatternMatchCB::link_match(lpat, lsoln)) {
return true;
}
if (lsoln->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
return false;
} else {
return true;
}
}
IncomingSet AttentionalFocusCB::get_incoming_set(Handle h) {
const IncomingSet &incoming_set = h->getIncomingSet();
IncomingSet filtered_set;
for (IncomingSet::const_iterator i = incoming_set.begin();
i != incoming_set.end(); ++i) {
Handle candidate_handle(*i);
if (candidate_handle->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
filtered_set.push_back(LinkCast(candidate_handle));
}
}
// if none is in AF
if (filtered_set.empty()) {
//xxx what shall we do here?, return the default or return empty ?
filtered_set = incoming_set;
}
std::sort(filtered_set.begin(), filtered_set.end(), compare_sti); //sort by STI for better performance
return filtered_set;
}
<commit_msg>changed node_match implementation<commit_after>/*
* AttentionalFocusCB.cc
*
* Copyright (C) 2014 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com> July 2014
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "AttentionalFocusCB.h"
using namespace opencog;
bool AttentionalFocusCB::node_match(Handle& node1, Handle& node2) {
if (node1 == node2
and node2->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
return false;
} else {
return true;
}
}
bool AttentionalFocusCB::link_match(LinkPtr& lpat, LinkPtr& lsoln) {
if (DefaultPatternMatchCB::link_match(lpat, lsoln)) {
return true;
}
if (lsoln->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
return false;
} else {
return true;
}
}
IncomingSet AttentionalFocusCB::get_incoming_set(Handle h) {
const IncomingSet &incoming_set = h->getIncomingSet();
IncomingSet filtered_set;
for (IncomingSet::const_iterator i = incoming_set.begin();
i != incoming_set.end(); ++i) {
Handle candidate_handle(*i);
if (candidate_handle->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
filtered_set.push_back(LinkCast(candidate_handle));
}
}
// if none is in AF
if (filtered_set.empty()) {
//xxx what shall we do here?, return the default or return empty ?
filtered_set = incoming_set;
}
std::sort(filtered_set.begin(), filtered_set.end(), compare_sti); //sort by STI for better performance
return filtered_set;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.