answer
stringlengths 15
1.25M
|
|---|
#include "Common/Options.h"
#include "Tests/PrintError.h"
const bool expectedToPass = false;
int main()
{
#if defined(USE_DBC)
int errcode = 0;
char dummyArgs[100];
char *dummyPtrs[10];
psocOptionHandle handle;
bool ok;
struct psocOptStruct opts[5] = {
{ '3', "three", 1, "", "repeat the loop three times" },
{ 'a', "address", 0, "QUASAR_ADDRESS", "tcp/ip port number of the server" },
{ 'x', "", 1, "DISPLAY", "X display to use" },
{ 'v', "verbose", 1, "", "try to explain what is going on" },
{ 'z', "zzz", 1, "", "go to sleep..." }
};
ok = <API key>( 5, opts, &handle );
if ( ok != true ) {
ERROR_EXIT( expectedToPass, NULL, ; );
}
strcpy( dummyArgs, "OptionTest2 --address 12345 -v --zzz" );
/* <API key> */
dummyPtrs[0] = dummyArgs;
dummyPtrs[1] = &dummyArgs[12];
dummyPtrs[2] = &dummyArgs[22];
dummyPtrs[3] = &dummyArgs[28];
dummyPtrs[4] = &dummyArgs[31];
dummyArgs[11] = 0;
dummyArgs[21] = 0;
dummyArgs[27] = 0;
dummyArgs[30] = 0;
errcode = <API key>( handle, 5, dummyPtrs, 1 );
if ( errcode != 0 ) {
ERROR_EXIT( expectedToPass, NULL, ; );
}
<API key>( NULL, 'a' );
ERROR_EXIT( expectedToPass, NULL, ; );
#else
return 1;
#endif
}
|
<?php
defined('_JEXEC') or die;
$row = $this->row;
$announcement = $this->announcement;
?>
<tr>
<td class="nowrap hidden-xs">
<?php echo $announcement->displayField('created', 'date_today'); ?>
</td>
<td class="nowrap">
<div class="overflow">
<?php echo JHtml::_('kunenaforum.link', $announcement->getUri(), $announcement->displayField('title'),
null, 'follow'); ?>
</div>
</td>
<?php if ($this->checkbox) : ?>
<td class="center">
<?php if ($this->canPublish()) echo JHtml::_('kunenagrid.published', $row, $announcement->published, '', true); ?>
</td>
<td class="center">
<?php if ($this->canEdit()) echo JHtml::_('kunenagrid.task', $row, 'tick.png', JText::_('COM_KUNENA_ANN_EDIT'),
'edit', '', true); ?>
</td>
<td class="center">
<?php if ($this->canDelete()) echo JHtml::_('kunenagrid.task', $row, 'publish_x.png',
JText::_('<API key>'), 'delete', '', true); ?>
</td>
<td>
<?php echo $announcement->getAuthor()->username; ?>
</td>
<?php endif; ?>
<td class="center hidden-xs">
<?php echo $announcement->displayField('id'); ?>
</td>
<?php if ($this->checkbox) : ?>
<td class="center">
<?php echo JHtml::_('kunenagrid.id', $row, $announcement->id); ?>
</td>
<?php endif; ?>
</tr>
|
#ifndef ADBLOCKICON_H
#define ADBLOCKICON_H
#include "qzcommon.h"
#include "clickablelabel.h"
#include "adblockrule.h"
class QMenu;
class QUrl;
class BrowserWindow;
class QUPZILLA_EXPORT AdBlockIcon : public ClickableLabel
{
Q_OBJECT
public:
explicit AdBlockIcon(BrowserWindow* window, QWidget* parent = 0);
~AdBlockIcon();
void popupBlocked(const QString &ruleString, const QUrl &url);
QAction* menuAction();
public slots:
void setEnabled(bool enabled);
void createMenu(QMenu* menu = 0);
private slots:
void showMenu(const QPoint &pos);
void toggleCustomFilter();
void animateIcon();
void stopAnimation();
private:
BrowserWindow* m_window;
QAction* m_menuAction;
QVector<QPair<AdBlockRule*, QUrl> > m_blockedPopups;
QTimer* m_flashTimer;
int m_timerTicks;
bool m_enabled;
};
#endif // ADBLOCKICON_H
|
// opening-tag.hpp
// Started 14 Aug 2018
#pragma once
#include <string>
#include <boost/spirit/include/qi.hpp>
namespace client {
// namespace fusion = boost::fusion;
// namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
template<typename Iterator>
struct opening_tag : qi::grammar<Iterator, mini_xml_tag(), ascii::space_type>
{
qi::rule<Iterator, mini_xml_tag(), ascii::space_type> start;
qi::rule<Iterator, std::string(), ascii::space_type> head;
qi::rule<Iterator, std::string(), ascii::space_type> tail;
opening_tag()
: base_type{ start }
{
head %= qi::lexeme[+ascii::alnum];
tail %= qi::no_skip[*(qi::char_ - '>')];
start %= qi::lit('<') >> head >> tail >> qi::lit('>');
}
};
}
|
// NScD Oak Ridge National Laboratory, European Spallation Source
// & Institut Laue - Langevin
#ifndef <API key>
#define <API key>
#include "MantidGeometry/Math/Algebra.h"
#include "MantidGeometry/Objects/MeshObject.h"
#include "MantidGeometry/Objects/MeshObjectCommon.h"
#include "MantidGeometry/Objects/ShapeFactory.h"
#include "MantidGeometry/Objects/Track.h"
#include "MantidGeometry/Rendering/GeometryHandler.h"
#include "MantidKernel/Material.h"
#include "MantidKernel/MersenneTwister.h"
#include "MantidTestHelpers/<API key>.h"
#include "MockRNG.h"
#include <cxxtest/TestSuite.h>
#include <Poco/DOM/AutoPtr.h>
#include <Poco/DOM/Document.h>
using namespace Mantid;
using namespace Geometry;
using Mantid::Kernel::V3D;
namespace {
std::unique_ptr<MeshObject> createCube(const double size, const V3D ¢re) {
/**
* Create cube of side length size with specified centre,
* parellel to axes and non-negative vertex coordinates.
*/
double min = 0.0 - 0.5 * size;
double max = 0.5 * size;
std::vector<V3D> vertices;
vertices.emplace_back(centre + V3D(max, max, max));
vertices.emplace_back(centre + V3D(min, max, max));
vertices.emplace_back(centre + V3D(max, min, max));
vertices.emplace_back(centre + V3D(min, min, max));
vertices.emplace_back(centre + V3D(max, max, min));
vertices.emplace_back(centre + V3D(min, max, min));
vertices.emplace_back(centre + V3D(max, min, min));
vertices.emplace_back(centre + V3D(min, min, min));
std::vector<uint32_t> triangles;
// top face of cube - z max
triangles.insert(triangles.end(), {0, 1, 2});
triangles.insert(triangles.end(), {2, 1, 3});
// right face of cube - x max
triangles.insert(triangles.end(), {0, 2, 4});
triangles.insert(triangles.end(), {4, 2, 6});
// back face of cube - y max
triangles.insert(triangles.end(), {0, 4, 1});
triangles.insert(triangles.end(), {1, 4, 5});
// bottom face of cube - z min
triangles.insert(triangles.end(), {7, 5, 6});
triangles.insert(triangles.end(), {6, 5, 4});
// left face of cube - x min
triangles.insert(triangles.end(), {7, 3, 5});
triangles.insert(triangles.end(), {5, 3, 1});
// front fact of cube - y min
triangles.insert(triangles.end(), {7, 6, 3});
triangles.insert(triangles.end(), {3, 6, 2});
// Use efficient constructor
std::unique_ptr<MeshObject> retVal = Mantid::Kernel::make_unique<MeshObject>(
std::move(triangles), std::move(vertices), Mantid::Kernel::Material());
return retVal;
}
std::unique_ptr<MeshObject> createCube(const double size) {
/**
* Create cube of side length size with vertex at origin,
* parellel to axes and non-negative vertex coordinates.
*/
return createCube(size, V3D(0.5 * size, 0.5 * size, 0.5 * size));
}
std::unique_ptr<MeshObject> createOctahedron() {
/**
* Create octahedron with vertices on the axes at -1 & +1.
*/
// The octahedron is made slightly bigger than this to
// ensure interior points are not rounded to be outside
// Opposite vertices have indices differing by 3.
double u = 1.0000000001;
std::vector<V3D> vertices;
vertices.emplace_back(V3D(u, 0, 0));
vertices.emplace_back(V3D(0, u, 0));
vertices.emplace_back(V3D(0, 0, u));
vertices.emplace_back(V3D(-u, 0, 0));
vertices.emplace_back(V3D(0, -u, 0));
vertices.emplace_back(V3D(0, 0, -u));
std::vector<uint32_t> triangles;
// +++ face
triangles.insert(triangles.end(), {0, 1, 2});
//++- face
triangles.insert(triangles.end(), {0, 5, 1});
// +-- face
triangles.insert(triangles.end(), {0, 4, 5});
// +-+ face
triangles.insert(triangles.end(), {0, 2, 4});
triangles.insert(triangles.end(), {3, 5, 4});
// --+ face
triangles.insert(triangles.end(), {3, 4, 2});
// -++ face
triangles.insert(triangles.end(), {3, 2, 1});
// -+- face
triangles.insert(triangles.end(), {3, 1, 5});
// Use flexible constructor
std::unique_ptr<MeshObject> retVal = Mantid::Kernel::make_unique<MeshObject>(
triangles, vertices, Mantid::Kernel::Material());
return retVal;
}
std::unique_ptr<MeshObject> createLShape() {
/**
* Create an L shape with vertices at
* (0,0,Z) (2,0,Z) (2,1,Z) (1,1,Z) (1,2,Z) & (0,2,Z),
* where Z = 0 or 1.
*/
std::vector<V3D> vertices;
vertices.emplace_back(V3D(0, 0, 0));
vertices.emplace_back(V3D(2, 0, 0));
vertices.emplace_back(V3D(2, 1, 0));
vertices.emplace_back(V3D(1, 1, 0));
vertices.emplace_back(V3D(1, 2, 0));
vertices.emplace_back(V3D(0, 2, 0));
vertices.emplace_back(V3D(0, 0, 1));
vertices.emplace_back(V3D(2, 0, 1));
vertices.emplace_back(V3D(2, 1, 1));
vertices.emplace_back(V3D(1, 1, 1));
vertices.emplace_back(V3D(1, 2, 1));
vertices.emplace_back(V3D(0, 2, 1));
std::vector<uint32_t> triangles;
// z min
triangles.insert(triangles.end(), {0, 5, 1});
triangles.insert(triangles.end(), {1, 3, 2});
triangles.insert(triangles.end(), {3, 5, 4});
// z max
triangles.insert(triangles.end(), {6, 7, 11});
triangles.insert(triangles.end(), {11, 9, 10});
triangles.insert(triangles.end(), {9, 7, 8});
// y min
triangles.insert(triangles.end(), {0, 1, 6});
triangles.insert(triangles.end(), {6, 1, 7});
// x max
triangles.insert(triangles.end(), {1, 2, 7});
triangles.insert(triangles.end(), {7, 2, 8});
// y mid
triangles.insert(triangles.end(), {2, 3, 8});
triangles.insert(triangles.end(), {8, 3, 9});
// x mid
triangles.insert(triangles.end(), {3, 4, 9});
triangles.insert(triangles.end(), {9, 4, 10});
// y max
triangles.insert(triangles.end(), {4, 5, 10});
triangles.insert(triangles.end(), {10, 5, 11});
// x min
triangles.insert(triangles.end(), {5, 0, 11});
triangles.insert(triangles.end(), {11, 0, 6});
// Use efficient constructor
std::unique_ptr<MeshObject> retVal = Mantid::Kernel::make_unique<MeshObject>(
std::move(triangles), std::move(vertices), Mantid::Kernel::Material());
return retVal;
}
} // namespace
class MeshObjectTest : public CxxTest::TestSuite {
public:
void testConstructor() {
std::vector<V3D> vertices;
vertices.emplace_back(V3D(0, 0, 0));
vertices.emplace_back(V3D(1, 0, 0));
vertices.emplace_back(V3D(0, 1, 0));
vertices.emplace_back(V3D(0, 0, 1));
std::vector<uint32_t> triangles;
triangles.insert(triangles.end(), {1, 2, 3});
triangles.insert(triangles.end(), {2, 1, 0});
triangles.insert(triangles.end(), {3, 0, 1});
triangles.insert(triangles.end(), {0, 3, 2});
// Test flexible constructor
<API key>(
MeshObject(triangles, vertices, Mantid::Kernel::Material()));
// Test eficient constructor
<API key>(MeshObject(
std::move(triangles), std::move(vertices), Mantid::Kernel::Material()));
}
void testClone() {
auto geom_obj = createOctahedron();
std::unique_ptr<IObject> cloned;
<API key>(cloned.reset(geom_obj->clone()));
TS_ASSERT(cloned);
}
void testMaterial() {
using Mantid::Kernel::Material;
std::vector<V3D> vertices;
vertices.emplace_back(V3D(0, 0, 0));
vertices.emplace_back(V3D(1, 0, 0));
vertices.emplace_back(V3D(0, 1, 0));
vertices.emplace_back(V3D(0, 0, 1));
std::vector<uint32_t> triangles;
triangles.insert(triangles.end(), {1, 2, 3});
triangles.insert(triangles.end(), {2, 1, 0});
triangles.insert(triangles.end(), {3, 0, 1});
triangles.insert(triangles.end(), {0, 3, 2});
auto testMaterial =
Material("arm", PhysicalConstants::getNeutronAtom(13), 45.0);
// Test material through flexible constructor
auto obj1 = Mantid::Kernel::make_unique<MeshObject>(triangles, vertices,
testMaterial);
TSM_ASSERT_DELTA("Expected a number density of 45", 45.0,
obj1->material().numberDensity(), 1e-12);
// Test material through efficient constructor
auto obj2 = Mantid::Kernel::make_unique<MeshObject>(
std::move(triangles), std::move(vertices), testMaterial);
TSM_ASSERT_DELTA("Expected a number density of 45", 45.0,
obj2->material().numberDensity(), 1e-12);
}
void <API key>() {
using Mantid::Kernel::Material;
auto testMaterial =
Material("arm", PhysicalConstants::getNeutronAtom(13), 45.0);
auto geom_obj = createOctahedron();
std::unique_ptr<IObject> cloned_obj;
<API key>(
cloned_obj.reset(geom_obj->cloneWithMaterial(testMaterial)));
TSM_ASSERT_DELTA("Expected a number density of 45", 45.0,
cloned_obj->material().numberDensity(), 1e-12);
}
void testHasValidShape() {
auto geom_obj = createCube(1.0);
TS_ASSERT(geom_obj->hasValidShape());
}
void <API key>() {
auto geom_obj = createCube(4.1);
const double tolerance(1e-10);
const BoundingBox &bbox = geom_obj->getBoundingBox();
TS_ASSERT_DELTA(bbox.xMax(), 4.1, tolerance);
TS_ASSERT_DELTA(bbox.yMax(), 4.1, tolerance);
TS_ASSERT_DELTA(bbox.zMax(), 4.1, tolerance);
TS_ASSERT_DELTA(bbox.xMin(), 0.0, tolerance);
TS_ASSERT_DELTA(bbox.yMin(), 0.0, tolerance);
TS_ASSERT_DELTA(bbox.zMin(), 0.0, tolerance);
}
void <API key>() {
auto geom_obj = createOctahedron();
const double tolerance(1e-10);
const BoundingBox &bbox = geom_obj->getBoundingBox();
TS_ASSERT_DELTA(bbox.xMax(), 1.0, tolerance);
TS_ASSERT_DELTA(bbox.yMax(), 1.0, tolerance);
TS_ASSERT_DELTA(bbox.zMax(), 1.0, tolerance);
TS_ASSERT_DELTA(bbox.xMin(), -1.0, tolerance);
TS_ASSERT_DELTA(bbox.yMin(), -1.0, tolerance);
TS_ASSERT_DELTA(bbox.zMin(), -1.0, tolerance);
}
void <API key>() {
auto geom_obj = createLShape();
const double tolerance(1e-10);
const BoundingBox &bbox = geom_obj->getBoundingBox();
TS_ASSERT_DELTA(bbox.xMax(), 2.0, tolerance);
TS_ASSERT_DELTA(bbox.yMax(), 2.0, tolerance);
TS_ASSERT_DELTA(bbox.zMax(), 1.0, tolerance);
TS_ASSERT_DELTA(bbox.xMin(), 0.0, tolerance);
TS_ASSERT_DELTA(bbox.yMin(), 0.0, tolerance);
TS_ASSERT_DELTA(bbox.zMin(), 0.0, tolerance);
}
void testInterceptCubeX() {
std::vector<Link> expectedResults;
auto geom_obj = createCube(4.0);
Track track(V3D(-10, 1, 1), V3D(1, 0, 0));
// format = startPoint, endPoint, total distance so far
expectedResults.emplace_back(
Link(V3D(0, 1, 1), V3D(4, 1, 1), 14.0, *geom_obj));
checkTrackIntercept(std::move(geom_obj), track, expectedResults);
}
void testInterceptCubeXY() {
std::vector<Link> expectedResults;
auto geom_obj = createCube(4.0);
Track track(V3D(-8, -6, 1), V3D(0.8, 0.6, 0));
// format = startPoint, endPoint, total distance so far
expectedResults.emplace_back(
Link(V3D(0, 0, 1), V3D(4, 3, 1), 15.0, *geom_obj));
checkTrackIntercept(std::move(geom_obj), track, expectedResults);
}
void <API key>() {
std::vector<Link>
expectedResults; // left empty as there are no expected results
auto geom_obj = createCube(4.0);
V3D dir(1., 1., 0.);
dir.normalize();
Track track(V3D(-10, 0, 0), dir);
checkTrackIntercept(std::move(geom_obj), track, expectedResults);
}
void <API key>() {
std::vector<Link> expectedResults;
auto geom_obj = createOctahedron();
Track track(V3D(-10, 0.2, 0.2), V3D(1, 0, 0));
// format = startPoint, endPoint, total distance so far
expectedResults.emplace_back(
Link(V3D(-0.6, 0.2, 0.2), V3D(0.6, 0.2, 0.2), 10.6, *geom_obj));
checkTrackIntercept(std::move(geom_obj), track, expectedResults);
}
void <API key>() {
std::vector<Link> expectedResults;
auto geom_obj = createOctahedron();
Track track(V3D(-10, 0.2, 0.0), V3D(1, 0, 0));
// format = startPoint, endPoint, total distance so far
expectedResults.emplace_back(
Link(V3D(-0.8, 0.2, 0.0), V3D(0.8, 0.2, 0.0), 10.8, *geom_obj));
checkTrackIntercept(std::move(geom_obj), track, expectedResults);
}
void <API key>() {
std::vector<Link> expectedResults;
auto geom_obj = createOctahedron();
Track track(V3D(-10, 0.0, 0.0), V3D(1, 0, 0));
// format = startPoint, endPoint, total distance so far
expectedResults.emplace_back(
Link(V3D(-1.0, 0.0, 0.0), V3D(1.0, 0.0, 0.0), 11.0, *geom_obj));
checkTrackIntercept(std::move(geom_obj), track, expectedResults);
}
void <API key>() {
std::vector<Link> expectedResults;
auto geom_obj = createLShape();
V3D dir(1., -1., 0.);
dir.normalize();
Track track(V3D(0, 2.5, 0.5), dir);
// format = startPoint, endPoint, total distance so far
expectedResults.emplace_back(
Link(V3D(0.5, 2, 0.5), V3D(1, 1.5, 0.5), 1.4142135, *geom_obj));
expectedResults.emplace_back(
Link(V3D(1.5, 1, 0.5), V3D(2, 0.5, 0.5), 2.828427, *geom_obj));
checkTrackIntercept(std::move(geom_obj), track, expectedResults);
}
void <API key>() {
std::vector<Link>
expectedResults; // left empty as there are no expected results
auto geom_obj = createLShape();
// Passes through convex hull of L-Shape
Track track(V3D(1.1, 1.1, -1), V3D(0, 0, 1));
checkTrackIntercept(std::move(geom_obj), track, expectedResults);
}
void <API key>()
/**
Test a track going through two objects
*/
{
auto object1 = createCube(2.0, V3D(0.0, 0.0, 0.0));
auto object2 = createCube(2.0, V3D(5.5, 0.0, 0.0));
Track TL(Kernel::V3D(-5, 0, 0), Kernel::V3D(1, 0, 0));
// CARE: This CANNOT be called twice
TS_ASSERT(object1->interceptSurface(TL) != 0);
TS_ASSERT(object2->interceptSurface(TL) != 0);
std::vector<Link> expectedResults;
expectedResults.emplace_back(
Link(V3D(-1, 0, 0), V3D(1, 0, 0), 6, *object1));
expectedResults.emplace_back(
Link(V3D(4.5, 0, 0), V3D(6.5, 0, 0), 11.5, *object2));
checkTrackIntercept(TL, expectedResults);
}
void <API key>()
/**
Test a track going through two objects
*/
{
auto object1 = createCube(2.0, V3D(0.0, 0.0, 0.0));
auto object2 = createCube(4.0, V3D(3.0, 0.0, 0.0));
Track TL(Kernel::V3D(-5, 0, 0), Kernel::V3D(1, 0, 0));
// CARE: This CANNOT be called twice
TS_ASSERT(object1->interceptSurface(TL) != 0);
TS_ASSERT(object2->interceptSurface(TL) != 0);
std::vector<Link> expectedResults;
expectedResults.emplace_back(
Link(V3D(-1, 0, 0), V3D(1, 0, 0), 6, *object1));
expectedResults.emplace_back(
Link(V3D(1, 0, 0), V3D(5, 0, 0), 10.0, *object2));
checkTrackIntercept(TL, expectedResults);
}
void checkTrackIntercept(Track &track,
const std::vector<Link> &expectedResults) {
size_t index = 0;
for (auto it = track.cbegin(); it != track.cend(); ++it) {
if (index < expectedResults.size()) {
TS_ASSERT_DELTA(it->distFromStart, expectedResults[index].distFromStart,
1e-6);
TS_ASSERT_DELTA(it->distInsideObject,
expectedResults[index].distInsideObject, 1e-6);
TS_ASSERT_EQUALS(it->componentID, expectedResults[index].componentID);
TS_ASSERT_EQUALS(it->entryPoint, expectedResults[index].entryPoint);
TS_ASSERT_EQUALS(it->exitPoint, expectedResults[index].exitPoint);
}
++index;
}
TS_ASSERT_EQUALS(index, expectedResults.size());
}
void checkTrackIntercept(IObject_uptr obj, Track &track,
const std::vector<Link> &expectedResults) {
int unitCount = obj->interceptSurface(track);
TS_ASSERT_EQUALS(unitCount, expectedResults.size());
checkTrackIntercept(track, expectedResults);
}
void testIsOnSideCube() {
auto geom_obj = createCube(1.0);
// inside
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.5)), false); // centre
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.1, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.9, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.1)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.9)), false);
// on the faces
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.1, 0.9)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.1, 0.0, 0.9)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.9, 0.1)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.1, 1.0, 0.9)), true);
// on the edges
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.5, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.1, 1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.9, 0.0)), true);
// on the vertices
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 1.0, 1.0)), true);
// out side
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.1, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, -0.1, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, -0.1)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.1, 0.0, 1.1)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.3, 0.9, 0.0)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-3.3, 2.0, 0.9)), false);
}
void testIsValidCube() {
auto geom_obj = createCube(1.0);
// inside
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.5)), true); // centre
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.1, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.9, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.1)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.9)), true);
// on the faces
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.1, 0.9)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.1, 0.0, 0.9)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.9, 0.1)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.1, 1.0, 0.9)), true);
// on the edges
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.5, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.1, 1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.9, 0.0)), true);
// on the vertices
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 1.0, 1.0)), true);
// out side
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.1, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, -0.1, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, -0.1)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.1, 0.0, 1.1)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.3, 0.9, 0.0)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-3.3, 2.0, 0.9)), false);
}
void <API key>() {
auto geom_obj = createOctahedron();
// inside
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 0.0)), false); // centre
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.2, 0.2)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.2, 0.5, -0.2)), false);
// on face
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.3, 0.2)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, -0.3, 0.2)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.4, -0.4, -0.2)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.4, 0.3, 0.3)), true);
// on edge
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, -0.5, -0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.7, 0.0, 0.3)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.7, 0.0, -0.3)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.8, 0.2, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.8, 0.2, 0.0)), true);
// on vertex
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-1.0, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, -1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 0.0, -1.0)), true);
// out side
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.35, 0.35, 0.35)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.35, -0.35, -0.35)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.35, 0.35, 0.35)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(-0.35, 0.35, -0.35)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(2.0, 2.0, 0.0)), false);
}
void <API key>() {
auto geom_obj = createOctahedron();
// inside
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 0.0)), true); // centre
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.2, 0.2)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.2, 0.5, -0.2)), true);
// on face
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.3, 0.2)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, -0.3, 0.2)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.4, -0.4, -0.2)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.4, 0.3, 0.3)), true);
// on edge
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, -0.5, -0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.7, 0.0, 0.3)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.7, 0.0, -0.3)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.8, 0.2, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.8, 0.2, 0.0)), true);
// on vertex
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-1.0, 0.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, -1.0, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 0.0, -1.0)), true);
// out side
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.35, 0.35, 0.35)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.35, -0.35, -0.35)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.35, 0.35, 0.35)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(-0.35, 0.35, -0.35)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(2.0, 2.0, 0.0)), false);
}
void testIsOnSideLShape() {
auto geom_obj = createLShape();
// inside
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.5, 0.5, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.5, 0.5)), false);
// on front and back
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.5, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.5, 0.5, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 1.5, 1.0)), true);
// on sides
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 0.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.0, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(2.0, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 2.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.5, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.0, 1.5, 0.5)), true);
// out side
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(0.5, 0.5, 1.5)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(2.0, 2.0, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(2.0, 2.0, 0.0)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.1, 1.1, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isOnSide(V3D(1.1, 1.1, 1.0)), false);
}
void testIsValidLShape() {
auto geom_obj = createLShape();
// inside
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.5, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.5, 0.5)), true);
// on front and back
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.5, 0.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.5, 0.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.5, 0.5, 1.0)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 1.5, 1.0)), true);
// on sides
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 0.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.0, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(2.0, 0.5, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 2.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.5, 1.0, 0.5)), true);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.0, 1.5, 0.5)), true);
// out side
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(0.5, 0.5, 1.5)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(2.0, 2.0, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(2.0, 2.0, 0.0)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.1, 1.1, 0.5)), false);
TS_ASSERT_EQUALS(geom_obj->isValid(V3D(1.1, 1.1, 1.0)), false);
}
void <API key>() {
auto geom_obj = createCube(1.0);
// entry or exit on the normal
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(1, 0, 0)),
1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(-1, 0, 0)),
-1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 0.5, 0.5), V3D(1, 0, 0)),
-1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 0.5, 0.5), V3D(-1, 0, 0)),
1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.5), V3D(0, 1, 0)),
1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.5), V3D(0, -1, 0)),
-1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 1.0, 0.5), V3D(0, 1, 0)),
-1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 1.0, 0.5), V3D(0, -1, 0)),
1);
// glancing blow on edge
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.0, 0.5), V3D(1, -1, 0)),
0);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.0), V3D(0, -1, 1)),
0);
// entry of exit on edge
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.0, 0.5), V3D(1, 1, 0)),
1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(0.0, 0.0, 0.5), V3D(-1, -1, 0)), -1);
// not on the normal
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(0.5, 0.5, 0)), 1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(1.0, 0.5, 0.5), V3D(0.5, 0.5, 0)), -1);
}
void <API key>() {
auto geom_obj = createOctahedron();
// entry or exit on the normal
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.2, 0.3, 0.5), V3D(1, 1, 1)),
-1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(0.2, 0.3, 0.5), V3D(-1, -1, -1)), 1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(-0.2, -0.3, -0.5), V3D(1, 1, 1)), 1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(-0.2, -0.3, -0.5), V3D(-1, -1, -1)), -1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(0.5, 0.2, -0.3), V3D(1, 1, -1)), -1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(0.5, 0.2, -0.3), V3D(-1, -1, 1)), 1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(-0.5, -0.2, 0.3), V3D(1, 1, -1)), 1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(-0.5, -0.2, 0.3), V3D(-1, -1, 1)), -1);
// glancing blow on edge
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(1, 0, 0)),
0);
// entry or exit at edge
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, -0.5, 0.5), V3D(0, 1, 0)),
1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.5, 0.5), V3D(0, 1, 0)),
-1);
// not on the normal
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.2, 0.3, 0.5), V3D(0, 1, 0)),
-1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.2, -0.3, 0.5), V3D(0, 1, 0)),
1);
}
void <API key>() {
auto geom_obj = createLShape();
// entry or exit on the normal
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 1.5, 0.5), V3D(1, 0, 0)),
1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 1.5, 0.5), V3D(-1, 0, 0)),
-1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 1.5, 0.5), V3D(1, 0, 0)),
-1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 1.5, 0.5), V3D(-1, 0, 0)),
1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 2.0, 0.5), V3D(0, 1, 0)),
-1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 2.0, 0.5), V3D(0, -1, 0)),
1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.5), V3D(0, 1, 0)),
1);
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.5, 0.0, 0.5), V3D(0, -1, 0)),
-1);
// glancing blow on edge
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(0.0, 0.0, 0.5), V3D(1, -1, 0)),
0);
// glancing blow on edge from inside
TS_ASSERT_EQUALS(geom_obj->calcValidType(V3D(1.0, 1.0, 0.5), V3D(1, -1, 0)),
0);
// not on the normal
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(1.0, 1.5, 0.5), V3D(0.5, 0.5, 0)), -1);
TS_ASSERT_EQUALS(
geom_obj->calcValidType(V3D(1.0, 1.5, 0.5), V3D(-0.5, 0.5, 0)), 1);
}
void testFindPointInCube() {
auto geom_obj = createCube(1.0);
Kernel::V3D pt;
TS_ASSERT_EQUALS(geom_obj->getPointInObject(pt), 1);
<API key>(0.0, pt.X());
<API key>(pt.X(), 1.0);
<API key>(0.0, pt.Y());
<API key>(pt.Y(), 1.0);
<API key>(0.0, pt.Z());
<API key>(pt.Z(), 1.0);
}
void <API key>() {
auto geom_obj = createOctahedron();
Kernel::V3D pt;
TS_ASSERT_EQUALS(geom_obj->getPointInObject(pt), 1);
<API key>(fabs(pt.X()) + fabs(pt.Y()) + fabs(pt.Z()), 1.0);
}
void <API key>() {
auto geom_obj = createLShape();
Kernel::V3D pt;
TS_ASSERT_EQUALS(geom_obj->getPointInObject(pt), 1);
<API key>(0.0, pt.X());
<API key>(pt.X(), 2.0);
<API key>(0.0, pt.Y());
<API key>(pt.Y(), 2.0);
<API key>(0.0, pt.Z());
<API key>(pt.Z(), 1.0);
TS_ASSERT(pt.X() <= 1.0 || pt.Y() <= 1.0)
}
void <API key>() {
using namespace ::testing;
// Generate "random" sequence
MockRNG rng;
Sequence rand;
EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.45));
EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.55));
EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.65));
// Random sequence set up so as to give point (0.90, 1.10, 0.65)
auto geom_obj = createLShape();
size_t maxAttempts(1);
V3D point;
<API key>(
point = geom_obj-><API key>(rng, maxAttempts));
const double tolerance(1e-10);
TS_ASSERT_DELTA(0.90, point.X(), tolerance);
TS_ASSERT_DELTA(1.10, point.Y(), tolerance);
TS_ASSERT_DELTA(0.65, point.Z(), tolerance);
}
void <API key>() {
using namespace ::testing;
// Generate "random" sequence
MockRNG rng;
Sequence rand;
EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.1));
EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.2));
EXPECT_CALL(rng, nextValue()).InSequence(rand).WillOnce(Return(0.3));
// Random sequence set up so as to give point (-0.8, -0.6, -0.4),
// which is outside the octahedron
auto geom_obj = createOctahedron();
size_t maxAttempts(1);
TS_ASSERT_THROWS(geom_obj-><API key>(rng, maxAttempts),
std::runtime_error);
}
void testVolumeOfCube() {
double size = 3.7;
auto geom_obj = createCube(size);
TS_ASSERT_DELTA(geom_obj->volume(), size * size * size, 1e-6)
}
void <API key>() {
auto geom_obj = createOctahedron();
TS_ASSERT_DELTA(geom_obj->volume(), 4.0 / 3.0, 1e-3)
}
void testVolumeOfLShape() {
auto geom_obj = createLShape();
TS_ASSERT_DELTA(geom_obj->volume(), 3.0, 1e-6)
// 3.5 is the volume of the convex hull
// 4.0 is the volume of the bounding box
}
void testSolidAngleCube()
/**
Test solid angle calculation for a cube.
*/
{
auto geom_obj = createCube(1.0); // Cube centre at 0.5, 0.5, 0.5
double satol = 1e-3; // tolerance for solid angle
// solid angle at distance 0.5 should be 4pi/6 by symmetry
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(1.5, 0.5, 0.5)), M_PI * 2.0 / 3.0,
satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(-0.5, 0.5, 0.5)), M_PI * 2.0 / 3.0,
satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 1.5, 0.5)), M_PI * 2.0 / 3.0,
satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, -0.5, 0.5)), M_PI * 2.0 / 3.0,
satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 0.5, 1.5)), M_PI * 2.0 / 3.0,
satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 0.5, -0.5)), M_PI * 2.0 / 3.0,
satol);
}
void <API key>()
/**
Test solid angle calculation for a cube that is scaled.
*/
{
auto geom_obj = createCube(2.0);
auto scale = V3D(0.5, 0.5, 0.5);
double satol = 1e-3; // tolerance for solid angle
// solid angle at distance 0.5 should be 4pi/6 by symmetry
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(1.5, 0.5, 0.5), scale),
M_PI * 2.0 / 3.0, satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(-0.5, 0.5, 0.5), scale),
M_PI * 2.0 / 3.0, satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 1.5, 0.5), scale),
M_PI * 2.0 / 3.0, satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, -0.5, 0.5), scale),
M_PI * 2.0 / 3.0, satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 0.5, 1.5), scale),
M_PI * 2.0 / 3.0, satol);
TS_ASSERT_DELTA(geom_obj->solidAngle(V3D(0.5, 0.5, -0.5), scale),
M_PI * 2.0 / 3.0, satol);
}
void <API key>()
/* Here we test the output functions used in rendering */
{
auto geom_obj = createOctahedron();
TS_ASSERT_EQUALS(geom_obj->numberOfTriangles(), 8);
TS_ASSERT_EQUALS(geom_obj->numberOfVertices(), 6);
<API key>(geom_obj->getTriangles());
<API key>(geom_obj->getVertices());
}
void testRotation()
/* Test Rotating a mesh */
{
auto lShape = createLShape();
const double valueList[] = {0, -1, 0, 1, 0, 0, 0, 0, 1};
const std::vector<double> rotationMatrix =
std::vector<double>(std::begin(valueList), std::end(valueList));
const Kernel::Matrix<double> rotation =
Kernel::Matrix<double>(rotationMatrix);
const double checkList[] = {0, 0, 0, 0, 2, 0, -1, 2, 0, -1, 1, 0,
-2, 1, 0, -2, 0, 0, 0, 0, 1, 0, 2, 1,
-1, 2, 1, -1, 1, 1, -2, 1, 1, -2, 0, 1};
auto checkVector =
std::vector<double>(std::begin(checkList), std::end(checkList));
<API key>(lShape->rotate(rotation));
auto rotated = lShape->getVertices();
TS_ASSERT_DELTA(rotated, checkVector, 1e-8);
}
void testTranslation()
/* Test Translating a mesh */
{
auto octahedron = createOctahedron();
V3D translation = V3D(1, 2, 3);
const double checkList[] = {2, 2, 3, 1, 3, 3, 1, 2, 4,
0, 2, 3, 1, 1, 3, 1, 2, 2};
auto checkVector =
std::vector<double>(std::begin(checkList), std::end(checkList));
<API key>(octahedron->translate(translation));
auto moved = octahedron->getVertices();
TS_ASSERT_DELTA(moved, checkVector, 1e-8);
}
};
// Performance tests
class <API key> : public CxxTest::TestSuite {
public:
// This pair of boilerplate methods prevent the suite being created statically
// This means the constructor isn't called when running other tests
static <API key> *createSuite() {
return new <API key>();
}
static void destroySuite(<API key> *suite) { delete suite; }
<API key>()
: rng(200000), octahedron(createOctahedron()), lShape(createLShape()),
smallCube(createCube(0.2)) {
testPoints = create_test_points();
testRays = create_test_rays();
translation = <API key>();
rotation = <API key>();
}
void test_rotate(const Kernel::Matrix<double> &) {
const size_t number(10000);
for (size_t i = 0; i < number; ++i) {
octahedron->rotate(rotation);
}
}
void test_translate(Kernel::V3D) {
const size_t number(10000);
for (size_t i = 0; i < number; ++i) {
octahedron->translate(translation);
}
}
void test_isOnSide() {
const size_t number(10000);
for (size_t i = 0; i < number; ++i) {
octahedron->isOnSide(testPoints[i % testPoints.size()]);
}
}
void test_isValid() {
const size_t number(10000);
for (size_t i = 0; i < number; ++i) {
octahedron->isValid(testPoints[i % testPoints.size()]);
}
}
void test_calcValidType() {
const size_t number(10000);
for (size_t i = 0; i < number; ++i) {
size_t j = i % testRays.size();
octahedron->calcValidType(testRays[j].startPoint(),
testRays[j].direction());
}
}
void <API key>() {
const size_t number(10000);
Track testRay;
for (size_t i = 0; i < number; ++i) {
octahedron->interceptSurface(testRays[i % testRays.size()]);
}
}
void test_solid_angle() {
const size_t number(10000);
for (size_t i = 0; i < number; ++i) {
smallCube->solidAngle(testPoints[i % testPoints.size()]);
}
}
void <API key>() {
const size_t number(10000);
for (size_t i = 0; i < number; ++i) {
smallCube->solidAngle(testPoints[i % testPoints.size()],
V3D(0.5, 1.33, 1.5));
}
}
void test_volume() {
const size_t numberOfRuns(10000);
for (size_t i = 0; i < numberOfRuns; ++i) {
octahedron->volume();
lShape->volume();
}
}
void <API key>() {
const size_t numberOfRuns(1000);
V3D pDummy;
for (size_t i = 0; i < numberOfRuns; ++i) {
octahedron->getPointInObject(pDummy);
lShape->getPointInObject(pDummy);
smallCube->getPointInObject(pDummy);
}
}
void <API key>() {
const size_t npoints(6000);
const size_t maxAttempts(500);
for (size_t i = 0; i < npoints; ++i) {
octahedron-><API key>(rng, maxAttempts);
}
}
void <API key>() {
const size_t npoints(6000);
const size_t maxAttempts(500);
for (size_t i = 0; i < npoints; ++i) {
lShape-><API key>(rng, maxAttempts);
}
}
void <API key>() {
const size_t numberOfRuns(30000);
for (size_t i = 0; i < numberOfRuns; ++i) {
octahedron->getVertices();
octahedron->getTriangles();
lShape->getVertices();
lShape->getTriangles();
}
}
V3D create_test_point(size_t index, size_t dimension) {
// Create a test point with coordinates within [-1.0, 0.0]
// for applying to octahedron
V3D output;
double interval = 1.0 / static_cast<double>(dimension - 1);
output.setX((static_cast<double>(index % dimension)) * interval);
index /= dimension;
output.setY((static_cast<double>(index % dimension)) * interval);
index /= dimension;
output.setZ((static_cast<double>(index % dimension)) * interval);
return output;
}
std::vector<V3D> create_test_points() {
// Create a vector of test points
size_t dim = 5;
size_t num = dim * dim * dim;
std::vector<V3D> output;
output.reserve(num);
for (size_t i = 0; i < num; ++i) {
output.push_back(create_test_point(i, dim));
}
return output;
}
Track create_test_ray(size_t index, size_t startDim, size_t dirDim) {
// create a test ray
const V3D shift(0.01, -1.0 / 77, -1.0 / 117);
V3D startPoint = create_test_point(index, startDim);
V3D direction = V3D(0.0, 0.0, 0.0) - create_test_point(index, dirDim);
direction += shift; // shift to avoid divide by zero error
direction.normalize();
return Track(startPoint, direction);
}
std::vector<Track> create_test_rays() {
size_t sDim = 3;
size_t dDim = 2;
size_t num = sDim * sDim * sDim * dDim * dDim * dDim;
std::vector<Track> output;
output.reserve(num);
for (size_t i = 0; i < num; ++i) {
output.push_back(create_test_ray(i, sDim, dDim));
}
return output;
}
V3D <API key>() {
V3D translate = Kernel::V3D(5, 5, 15);
return translate;
}
Kernel::Matrix<double> <API key>() {
double valueList[] = {0, -1, 0, 1, 0, 0, 0, 0, 1};
const std::vector<double> rotationMatrix =
std::vector<double>(std::begin(valueList), std::end(valueList));
Kernel::Matrix<double> rotation = Kernel::Matrix<double>(rotationMatrix);
return rotation;
}
private:
Mantid::Kernel::MersenneTwister rng;
std::unique_ptr<MeshObject> octahedron;
std::unique_ptr<MeshObject> lShape;
std::unique_ptr<MeshObject> smallCube;
std::vector<V3D> testPoints;
std::vector<Track> testRays;
V3D translation;
Kernel::Matrix<double> rotation;
};
#endif // <API key>
|
//: pony/PartyFavor.java
package pokepon.pony;
import pokepon.enums.*;
/** Party Favor
* Good def and spa, lacks Hp and Speed
*
* @author silverweed
*/
public class PartyFavor extends Pony {
public PartyFavor(int _level) {
super(_level);
name = "Party Favor";
type[0] = Type.LAUGHTER;
type[1] = Type.HONESTY;
race = Race.UNICORN;
sex = Sex.MALE;
baseHp = 60;
baseAtk = 80;
baseDef = 100;
baseSpatk = 100;
baseSpdef = 80;
baseSpeed = 60;
/* Learnable Moves */
learnableMoves.put("Tackle",1);
learnableMoves.put("Hidden Talent",1);
learnableMoves.put("Mirror Pond",1);
learnableMoves.put("Dodge",1);
}
}
|
using System;
namespace GalleryServerPro.Business.Interfaces
{
<summary>
A collection of <see cref="IUserAccount" /> objects.
</summary>
public interface <API key> : System.Collections.Generic.ICollection<IUserAccount>
{
<summary>
Gets a list of user names for accounts in the collection. This is equivalent to iterating through each <see cref="IUserAccount" />
and compiling a string array of the <see cref="IUserAccount.UserName" /> properties.
</summary>
<returns>Returns a string array of user names of accounts in the collection.</returns>
string[] GetUserNames();
<summary>
Sort the objects in this collection based on the <see cref="IUserAccount.UserName" /> property.
</summary>
void Sort();
<summary>
Adds the user accounts to the current collection.
</summary>
<param name="userAccounts">The user accounts to add to the current collection.</param>
<exception cref="<API key>">Thrown when <paramref name="userAccounts" /> is null.</exception>
void AddRange(System.Collections.Generic.IEnumerable<IUserAccount> userAccounts);
<summary>
Gets a reference to the <see cref="IUserAccount" /> object at the specified index position.
</summary>
<param name="indexPosition">An integer specifying the position of the object within this collection to
return. Zero returns the first item.</param>
<returns>Returns a reference to the <see cref="IUserAccount" /> object at the specified index position.</returns>
IUserAccount this[Int32 indexPosition]
{
get;
set;
}
<summary>
Searches for the specified object and returns the zero-based index of the first occurrence within the collection.
</summary>
<param name="gallery">The user account to locate in the collection. The value can be a null
reference (Nothing in Visual Basic).</param>
<returns>The zero-based index of the first occurrence of a user account within the collection, if found;
otherwise, 1. </returns>
Int32 IndexOf(IUserAccount gallery);
<overloads>
Determines whether a user is a member of the collection.
</overloads>
<summary>
Determines whether the <paramref name="item"/> is a member of the collection. An object is considered a member
of the collection if they both have the same <see cref="IUserAccount.UserName" />.
</summary>
<param name="item">An <see cref="IUserAccount"/> to determine whether it is a member of the current collection.</param>
<returns>Returns <c>true</c> if <paramref name="item"/> is a member of the current collection;
otherwise returns <c>false</c>.</returns>
new bool Contains(IUserAccount item);
<summary>
Determines whether a user account with the specified <paramref name="userName"/> is a member of the collection.
</summary>
<param name="userName">The user name that uniquely identifies the user.</param>
<returns>Returns <c>true</c> if <paramref name="userName"/> is a member of the current collection;
otherwise returns <c>false</c>.</returns>
bool Contains(string userName);
<summary>
Adds the specified user account.
</summary>
<param name="item">The user account to add.</param>
new void Add(IUserAccount item);
<summary>
Find the user account in the collection that matches the specified <paramref name="userName" />. If no matching object is found,
null is returned.
</summary>
<param name="userName">The user name that uniquely identifies the user.</param>
<returns>Returns an <see cref="IUserAccount" />object from the collection that matches the specified <paramref name="userName" />,
or null if no matching object is found.</returns>
IUserAccount FindByUserName(string userName);
<summary>
Finds the users whose <see cref="IUserAccount.UserName" /> begins with the specified <paramref name="<API key>" />.
This method can be used to find a set of users that match the first few characters of a string. Returns an empty collection if
no matches are found. The match is case-insensitive. Example: If <paramref name="<API key>" />="Rob", this method
returns users with names like "Rob", "Robert", and "robert" but not names such as "Boston Rob".
</summary>
<param name="<API key>">A string to match against the beginning of a <see cref="IUserAccount.UserName" />. Do not
specify a wildcard character. If value is null or an empty string, all users are returned.</param>
<returns>Returns an <see cref="<API key>" />object from the collection where the <see cref="IUserAccount.UserName" />
begins with the specified <paramref name="<API key>" />, or an empty collection if no matching object is found.</returns>
<API key> FindAllByUserName(string <API key>);
}
}
|
var Base = require("./../plugin");
module.exports = class extends Base {
<API key>(self, rival) {
return true;
}
<API key>(self, rival) {
return true;
}
}
|
// JIST (Java In Simulation Time) Project
// Timestamp: <EntityRef.java Sun 2005/03/13 11:10:16 barr rimbase.rimonbarr.com>
package jist.runtime;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationHandler;
import java.rmi.RemoteException;
/**
* Stores a reference to a (possibly remote) Entity object. A reference
* consists of a serialized reference to a Controller and an index within that
* Controller.
*
* @author Rimon Barr <barr+jist@cs.cornell.edu>
* @version $Id: EntityRef.java,v 1.1 2007/04/09 18:49:26 drchoffnes Exp $
* @since JIST1.0
*/
public class EntityRef implements InvocationHandler
{
/**
* NULL reference constant.
*/
public static final EntityRef NULL = new EntityRefDist(null, -1);
/**
* Entity index within Controller.
*/
private final int index;
/**
* Initialise a new entity reference with given
* Controller and Entity IDs.
*
* @param index entity ID
*/
public EntityRef(int index)
{
this.index = index;
}
/**
* Return entity reference hashcode.
*
* @return entity reference hashcode
*/
public int hashCode()
{
return index;
}
/**
* Test object equality.
*
* @param o object to test equality
* @return object equality
*/
public boolean equals(Object o)
{
if(o==null) return false;
if(!(o instanceof EntityRef)) return false;
EntityRef er = (EntityRef)o;
if(index!=er.index) return false;
return true;
}
/**
* Return controller of referenced entity.
*
* @return controller of referenced entity
*/
public ControllerRemote getController()
{
if(Main.SINGLE_CONTROLLER)
{
return Controller.activeController;
}
else
{
throw new RuntimeException("multiple controllers");
}
}
/**
* Return index of referenced entity.
*
* @return index of referenced entity
*/
public int getIndex()
{
return index;
}
/**
* Return toString of referenced entity.
*
* @return toString of referenced entity
*/
public String toString()
{
try
{
return "EntityRef:"+getController().toStringEntity(getIndex());
}
catch(java.rmi.RemoteException e)
{
throw new RuntimeException(e);
}
}
/**
* Return class of referenced entity.
*
* @return class of referenced entity
*/
public Class getClassRef()
{
try
{
return getController().getEntityClass(getIndex());
}
catch(java.rmi.RemoteException e)
{
throw new RuntimeException(e);
}
}
// proxy entities
/** boolean type for null return. */
private static final Boolean RET_BOOLEAN = new Boolean(false);
/** byte type for null return. */
private static final Byte RET_BYTE = new Byte((byte)0);
/** char type for null return. */
private static final Character RET_CHARACTER = new Character((char)0);
/** double type for null return. */
private static final Double RET_DOUBLE = new Double((double)0);
/** float type for null return. */
private static final Float RET_FLOAT = new Float((float)0);
/** int type for null return. */
private static final Integer RET_INTEGER = new Integer(0);
/** long type for null return. */
private static final Long RET_LONG = new Long(0);
/** short type for null return. */
private static final Short RET_SHORT = new Short((short)0);
/**
* Called whenever a proxy entity reference is invoked. Schedules the call
* at the appropriate Controller.
*
* @param proxy proxy entity reference object whose method was invoked
* @param method method invoked on entity reference object
* @param args arguments of the method invocation
* @return result of blocking event; null return for non-blocking events
* @throws Throwable whatever was thrown by blocking events; never for non-blocking events
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
try
{
if(Rewriter.<API key>(method))
// todo: make Object methods blocking
//|| method.getDeclaringClass()==Object.class)
{
return blockingInvoke(proxy, method, args);
}
else
{
// schedule a simulation event
if(Main.SINGLE_CONTROLLER)
{
Controller.activeController.addEvent(method, this, args);
}
else
{
getController().addEvent(method, this, args);
}
return null;
}
}
catch(RemoteException e)
{
throw new JistException("distributed simulation failure", e);
}
}
/**
* Helper method: called whenever a BLOCKING method on proxy entity reference
* is invoked. Schedules the call at the appropriate Controller.
*
* @param proxy proxy entity reference object whose method was invoked
* @param method method invoked on entity reference object
* @param args arguments of the method invocation
* @return result of blocking event
* @throws Throwable whatever was thrown by blocking events
*/
private Object blockingInvoke(Object proxy, Method method, Object[] args) throws Throwable
{
Controller c = Controller.getActiveController();
if(c.isModeRestoreInst())
{
// restore complete
if(Controller.log.isDebugEnabled())
{
Controller.log.debug("restored event state!");
}
// return callback result
return c.clearRestoreState();
}
else
{
// calling blocking method
c.registerCallEvent(method, this, args);
// todo: darn Java; this junk slows down proxies
Class ret = method.getReturnType();
if(ret==Void.TYPE)
{
return null;
}
else if(ret.isPrimitive())
{
String retName = ret.getName();
switch(retName.charAt(0))
{
case 'b':
switch(retName.charAt(1))
{
case 'o': return RET_BOOLEAN;
case 'y': return RET_BYTE;
default: throw new RuntimeException("unknown return type");
}
case 'c': return RET_CHARACTER;
case 'd': return RET_DOUBLE;
case 'f': return RET_FLOAT;
case 'i': return RET_INTEGER;
case 'l': return RET_LONG;
case 's': return RET_SHORT;
default: throw new RuntimeException("unknown return type");
}
}
else
{
return null;
}
}
}
} // class: EntityRef
|
#!/usr/bin/env python
"""The setup and build script for the python-telegram-bot library."""
import codecs
import os
from setuptools import setup, find_packages
def requirements():
"""Build the requirements list for this project"""
requirements_list = []
with open('requirements.txt') as requirements:
for install in requirements:
requirements_list.append(install.strip())
return requirements_list
packages = find_packages(exclude=['tests*'])
with codecs.open('README.rst', 'r', 'utf-8') as fd:
fn = os.path.join('telegram', 'version.py')
with open(fn) as fh:
code = compile(fh.read(), fn, 'exec')
exec(code)
setup(name='python-telegram-bot',
version=__version__,
author='Leandro Toledo',
author_email='devs@python-telegram-bot.org',
license='LGPLv3',
url='https://python-telegram-bot.org/',
keywords='python telegram bot api wrapper',
description="We have made you a wrapper you can't refuse",
long_description=fd.read(),
packages=packages,
install_requires=requirements(),
extras_require={
'json': 'ujson',
'socks': 'PySocks'
},
<API key>=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat',
'Topic :: Internet',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],)
|
#!/bin/bash -e
. ../../../blfs.comm
build_src() {
srcfil=URI-1.65.tar.gz
srcdir=URI-1.65
<API key>
}
gen_control() {
cat > $DEBIANDIR/control << EOF
$PKGHDR
Description: Uniform Resource Identifiers (absolute and relative)
This module implements the URI class. Objects of this class represent
"Uniform Resource Identifier references" as specified in RFC 2396 (and
updated by RFC 2732). A Uniform Resource Identifier is a compact string of
characters that identifies an abstract or physical resource. A Uniform
Resource Identifier can be further classified as either a Uniform Resource
Locator (URL) or a Uniform Resource Name (URN). The distinction between URL
and URN does not matter to the URI class interface. A "URI-reference" is a
URI that may have additional information attached in the form of a fragment
identifier.
EOF
}
build
|
package se.sics.asdistances;
import se.sics.asdistances.ASDistances;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.*;
public class ASDistancesTest {
ASDistances distances = null;
public ASDistancesTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
distances = ASDistances.getInstance();
}
@After
public void tearDown() {
}
@Test
public void testGetDistance() {
System.out.println("Distance: " + distances.getDistance("193.10.67.148", "85.226.78.233"));
}
}
|
#include "cmilitwostateselect.h"
#include "<API key>.h"
#include "cengine.h"
#include "ctextout.h"
void CMili2McuController::DoUpdateLogicView(const CEngineModel *engine) {
if (engine->CurrentMcuType() == CEngineModel::MILI_MCU)
mView->UpdateLogicView(engine);
}
void CMili2McuController::DoUpdateMemoryView(const CEngineModel *engine) {
if (engine->CurrentMcuType() == CEngineModel::MILI_MCU)
mView->UpdateMemoryView(engine);
}
void CMili2McuController::DoUpdateHintsView(const CEngineModel *engine) {
if (engine->CurrentMcuType() == CEngineModel::MILI_MCU)
mView->UpdateHintsView(engine);
}
CMiliTwoStateSelect::CMiliTwoStateSelect(QWidget *parent) :
QWidget(parent),
ui(new Ui::CMiliTwoStateSelect),
mMcuController(this)
{
ui->setupUi(this);
}
CMiliTwoStateSelect::~CMiliTwoStateSelect()
{
delete ui;
}
void CMiliTwoStateSelect::UpdateMemoryView(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
UpdateRG(engine);
}
void CMiliTwoStateSelect::UpdateLogicView(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
UpdateMS1(engine);
UpdateMS2(engine);
UpdateY(engine);
}
void CMiliTwoStateSelect::UpdateHintsView(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
ui->mRgMsbNoHint->setText(CTextOut::FormatDec(engine->StateDim() - 1));
ui->mYDimHint->setText(CTextOut::FormatDec(engine->McuControlOutputDim()));
ui->mMs1MsbHint->setText(QString("p%1").arg(CTextOut::FormatDec(engine->McuControlInputDim() - 1)));
ui->mMs2MsbHint->setText(CTextOut::FormatDec(engine->McuControlOutputDim() + engine->StateDim() - 1));
}
void CMiliTwoStateSelect::UpdateRG(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
const CRegister *rg = engine->CurrentMcu()->Register(CMiliAutomate::<API key>);
unsigned int stateDim = engine->StateDim();
ui->mRgVal->setText(CTextOut::FormatHex(rg->Output(), stateDim));
ui->mSVal->setText(CTextOut::FormatHex(rg->Output(), stateDim));
}
void CMiliTwoStateSelect::UpdateMS1(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
const CMultiplexor *mux = engine->CurrentMcu()->Multiplexor(CMiliAutomate::GROUP_MUX_INDEX);
ui->mMS1P0Val->setText(CTextOut::FormatBin(mux->Input(0), 1));
ui->mMS1P1Val->setText(CTextOut::FormatBin(mux->Input(1), 1));
unsigned int lastIndex = engine->McuControlInputDim() - 1;
ui->mMS1PnVal->setText(CTextOut::FormatBin(mux->Input(lastIndex).AsInt(), 1));
ui->mMs1SelVal->setText(CTextOut::FormatHex(mux->InputIndex(), mux->IndexDim()));
ui->mMs1Val->setText(CTextOut::FormatBin(mux->Output().AsInt(), 1));
}
void CMiliTwoStateSelect::UpdateMS2(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
const CMultiplexor *mux = engine->CurrentMcu()->Multiplexor(CMiliAutomate::STATE_MUX_INDEX);
ui->mMS2S0Val->setText(CTextOut::FormatHex(mux->Input(0)));
ui->mMS2S1Val->setText(CTextOut::FormatHex(mux->Input(1)));
ui->mMs2SVal->setText(CTextOut::FormatHex(mux->Output()));
mux = engine->CurrentMcu()->Multiplexor(CMiliAutomate::CONTROL_MUX_INDEX);
ui->mMS2Y0Val->setText(CTextOut::FormatHex(mux->Input(0)));
ui->mMS2Y1Val->setText(CTextOut::FormatHex(mux->Input(1)));
ui->mMs2YVal->setText(CTextOut::FormatHex(mux->Output()));
}
void CMiliTwoStateSelect::UpdateY(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
ui->mYVal->setText(CTextOut::FormatHex(engine->CurrentMcu()->ControlOutput()));
}
|
#creativeblock {
clear:both;
border-bottom: 1px #1d649d solid;
border: 5px solid #f1f1f1;
padding: 1%;
margin: 1%;
}
#feaimg img{
width: 30%;
float:left;
padding-right: 2%;
}
#featitle {
font-size: larger;
font-weight: bold;
color: #1d649d;
}
#featitle a {
color: #1d649d;
}
#feacontent {
}
#feacontent a {
color: #1d649d;
}
|
#ifndef <API key>
#define <API key>
#include <satellites/<API key>.h>
#include <vector>
namespace gr {
namespace satellites {
class <API key> : public <API key>
{
private:
const size_t d_threshold;
const size_t d_step;
std::vector<uint8_t> d_syncword;
public:
<API key>(int threshold, const std::string& syncword, int step);
~<API key>();
// Where all the action really happens
int work(int noutput_items,
<API key>& input_items,
gr_vector_void_star& output_items);
};
} // namespace satellites
} // namespace gr
#endif /* <API key> */
|
/* This file is part of the program and library */
/* fuer Informationstechnik Berlin */
/* along with SCIP; see the file COPYING. If not email to scip@zib.de. */
/**@file struct_concsolver.h
* @ingroup INTERNALAPI
* @brief datastructures for concurrent solvers
* @author Robert Lion Gottwald
*/
#ifndef <API key>
#define <API key>
#include "scip/def.h"
#include "scip/type_concsolver.h"
#include "scip/type_clock.h"
#ifdef __cplusplus
extern "C" {
#endif
/** concurrent solver data structure */
struct SCIP_ConcSolverType
{
int ninstances; /**< number of instances created from this concurrent solver type */
SCIP_Real prefprio; /**< the weight of the concurrent */
char* name; /**< name of concurrent solver */
<API key>* data; /**< user data of concurrent solver type */
<API key> ((*<API key>)); /**< creates an instance of the concurrent solver */
<API key> ((*<API key>)); /**< destroys an instance of the concurrent solver */
<API key> ((*concsolverinitseeds)); /**< initialize random seeds of concurrent solver */
<API key> ((*concsolverexec)); /**< execution method of concurrent solver */
<API key> ((*<API key>));/**< copies the solving data */
<API key> ((*concsolverstop)); /**< terminate solving in concurrent solver */
<API key> ((*concsolversyncwrite)); /**< synchronization method of concurrent solver for sharing it's data */
<API key> ((*concsolversyncread)); /**< synchronization method of concurrent solver for reading shared data */
<API key> ((*<API key>));/**< frees user data of concurrent solver type */
};
/** concurrent solver data structure */
struct SCIP_ConcSolver
{
SCIP_CONCSOLVERTYPE* type; /**< type of this concurrent solver */
int idx; /**< index of initialized exernal solver */
char* name; /**< name of concurrent solver */
SCIP_CONCSOLVERDATA* data; /**< user data of concurrent solver */
SCIP_SYNCDATA* syncdata; /**< most recent synchronization data that has been read */
SCIP_Longint nsyncs; /**< total number of synchronizations */
SCIP_Real timesincelastsync; /**< time since the last synchronization */
SCIP_Real syncdelay; /**< current delay of synchronization data */
SCIP_Real syncfreq; /**< current synchronization frequency of the concurrent solver */
SCIP_Real solvingtime; /**< solving time with wall clock */
SCIP_Bool stopped; /**< flag to store if the concurrent solver has been stopped
* through the SCIPconcsolverStop function */
SCIP_Longint nlpiterations; /**< number of lp iterations the concurrent solver used */
SCIP_Longint nnodes; /**< number of nodes the concurrent solver used */
SCIP_Longint nsolsrecvd; /**< number of solutions the concurrent solver received */
SCIP_Longint nsolsshared; /**< number of solutions the concurrent solver found */
SCIP_Longint ntighterbnds; /**< number of tighter global variable bounds the concurrent solver received */
SCIP_Longint ntighterintbnds; /**< number of tighter global variable bounds the concurrent solver received
* on integer variables */
SCIP_CLOCK* totalsynctime; /**< total time used for synchronization, including idle time */
};
#ifdef __cplusplus
}
#endif
#endif
|
class Cartridge : property<Cartridge> {
public:
enum class Mode : unsigned {
Normal,
BsxSlotted,
Bsx,
SufamiTurbo,
SuperGameBoy,
};
enum class Region : unsigned {
NTSC,
PAL,
};
//assigned externally to point to file-system datafiles (msu1 and serial)
//example: "/path/to/filename.sfc" would set this to "/path/to/filename"
readwrite<string> basename;
readonly<bool> loaded;
readonly<unsigned> crc32;
readonly<string> sha256;
readonly<Mode> mode;
readonly<Region> region;
readonly<unsigned> ram_size;
readonly<bool> has_bsx_slot;
readonly<bool> has_superfx;
readonly<bool> has_sa1;
readonly<bool> has_necdsp;
readonly<bool> has_srtc;
readonly<bool> has_sdd1;
readonly<bool> has_spc7110;
readonly<bool> has_spc7110rtc;
readonly<bool> has_cx4;
readonly<bool> has_obc1;
readonly<bool> has_st0018;
readonly<bool> has_msu1;
readonly<bool> has_serial;
struct Mapping {
Memory *memory;
MMIO *mmio;
Bus::MapMode mode;
unsigned banklo;
unsigned bankhi;
unsigned addrlo;
unsigned addrhi;
unsigned offset;
unsigned size;
Mapping();
Mapping(Memory&);
Mapping(MMIO&);
};
array<Mapping> mapping;
void load(Mode, const lstring&);
void unload();
void serialize(serializer&);
Cartridge();
~Cartridge();
private:
void parse_xml(const lstring&);
void parse_xml_cartridge(const char*);
void parse_xml_bsx(const char*);
void <API key>(const char*, bool);
void parse_xml_gameboy(const char*);
void xml_parse_rom(xml_element&);
void xml_parse_ram(xml_element&);
void xml_parse_icd2(xml_element&);
void xml_parse_superfx(xml_element&);
void xml_parse_sa1(xml_element&);
void xml_parse_necdsp(xml_element&);
void xml_parse_bsx(xml_element&);
void <API key>(xml_element&);
void <API key>(xml_element&);
void xml_parse_srtc(xml_element&);
void xml_parse_sdd1(xml_element&);
void xml_parse_spc7110(xml_element&);
void xml_parse_cx4(xml_element&);
void xml_parse_obc1(xml_element&);
void xml_parse_setarisc(xml_element&);
void xml_parse_msu1(xml_element&);
void xml_parse_serial(xml_element&);
void xml_parse_address(Mapping&, const string&);
void xml_parse_mode(Mapping&, const string&);
};
namespace memory {
extern MappedRAM cartrom, cartram, cartrtc;
extern MappedRAM bsxflash, bsxram, bsxpram;
extern MappedRAM stArom, stAram;
extern MappedRAM stBrom, stBram;
};
extern Cartridge cartridge;
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '<API key>'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='is_create',
),
migrations.RemoveField(
model_name='userprofile',
name='is_delete',
),
migrations.RemoveField(
model_name='userprofile',
name='is_modify',
),
]
|
#pragma once
#include "storm/storage/memorystructure/<API key>.h"
namespace storm {
namespace storage {
enum class <API key> { Trivial, FixedCounter, SelectiveCounter, FixedRing, SelectiveRing, SettableBits, Full };
std::string toString(<API key> const& pattern);
class <API key> {
public:
// Builds a memory structure with the given pattern and the given number of states.
<API key> build(<API key> pattern, uint64_t numStates) const;
// Builds a memory structure that consists of just a single memory state
<API key> buildTrivialMemory() const;
// Builds a memory structure that consists of a chain of the given number of states.
// Every state has exactly one transition to the next state. The last state has just a selfloop.
<API key> <API key>(uint64_t numStates) const;
// Builds a memory structure that consists of a chain of the given number of states.
// Every state has a selfloop and a transition to the next state. The last state just has a selfloop.
<API key> <API key>(uint64_t numStates) const;
// Builds a memory structure that consists of a ring of the given number of states.
// Every state has a transition to the successor state
<API key> <API key>(uint64_t numStates) const;
// Builds a memory structure that consists of a ring of the given number of states.
// Every state has a transition to the successor state and a selfloop
<API key> <API key>(uint64_t numStates) const;
// Builds a memory structure that represents floor(log(numStates)) bits that can only be set from zero to one or from zero to zero.
<API key> <API key>(uint64_t numStates) const;
// Builds a memory structure that consists of the given number of states which are fully connected.
<API key> <API key>(uint64_t numStates) const;
};
} // namespace storage
} // namespace storm
|
package nl.hyranasoftware.githubupdater.domain;
import com.fasterxml.jackson.annotation.<API key>;
import java.util.Objects;
import org.joda.time.DateTime;
/**
*
* @author danny_000
*/
@<API key>(ignoreUnknown = true)
public class Asset {
String url;
String <API key>;
int id;
String name;
String label;
String state;
String content_type;
long size;
long download_count;
DateTime created_at;
DateTime updated_at;
GithubUser uploader;
public Asset() {
}
public Asset(String url, String <API key>, int id, String name, String label, String state, String content_type, long size, long download_count, DateTime created_at, DateTime updated_at, GithubUser uploader) {
this.url = url;
this.<API key> = <API key>;
this.id = id;
this.name = name;
this.label = label;
this.state = state;
this.content_type = content_type;
this.size = size;
this.download_count = download_count;
this.created_at = created_at;
this.updated_at = updated_at;
this.uploader = uploader;
}
public String getState() {
return state;
}
public String getUrl() {
return url;
}
public String <API key>() {
return <API key>;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getLabel() {
return label;
}
public String getContent_type() {
return content_type;
}
public long getSize() {
return size;
}
public long getDownload_count() {
return download_count;
}
public DateTime getCreated_at() {
return created_at;
}
public DateTime getUpdated_at() {
return updated_at;
}
public GithubUser getUploader() {
return uploader;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + Objects.hashCode(this.content_type);
hash = 79 * hash + (int) (this.download_count ^ (this.download_count >>> 32));
hash = 79 * hash + Objects.hashCode(this.created_at);
hash = 79 * hash + Objects.hashCode(this.updated_at);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Asset other = (Asset) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.content_type, other.content_type)) {
return false;
}
return true;
}
@Override
public String toString(){
return this.name;
}
}
|
#ifndef _HTTP_REQUEST_H_
#define _HTTP_REQUEST_H_
#include <fstream>
#include <boost/shared_ptr.hpp>
class CHttpConnection;
#include "../pugixml/pugixml.hpp"
typedef void CURL;
// Shared_ptr typedef
typedef boost::shared_ptr<pugi::xml_document> XmlDocumentPtr;
/**
* greebo: An object representing a single HttpRequest, holding
* the result (string) and status information.
*
* Use the Perform() method to execute the request.
*/
class CHttpRequest
{
public:
enum RequestStatus
{
NOT_PERFORMED_YET,
OK, // successful
IN_PROGRESS,
FAILED,
ABORTED,
};
private:
// The connection we're working with
CHttpConnection& _conn;
// The URL we're supposed to query
std::string _url;
std::vector<char> _buffer;
// The curl handle
CURL* _handle;
// The current state
RequestStatus _status;
std::string _destFilename;
std::ofstream _destStream;
// True if we should cancel the download
bool _cancelFlag;
double _progress;
public:
CHttpRequest(CHttpConnection& conn, const std::string& url);
CHttpRequest(CHttpConnection& conn, const std::string& url, const std::string& destFilename);
// Callbacks for CURL
static size_t WriteMemoryCallback(void* ptr, size_t size, size_t nmemb, CHttpRequest* self);
static size_t WriteFileCallback(void* ptr, size_t size, size_t nmemb, CHttpRequest* self);
static int CHttpRequest::TDMHttpProgressFunc(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow);
RequestStatus GetStatus();
// Perform the request
void Perform();
void Cancel();
// Between 0.0 and 1.0
double GetProgressFraction();
// Returns the result string
std::string GetResultString();
// Returns the result as XML document
XmlDocumentPtr GetResultXml();
private:
void InitRequest();
void UpdateProgress();
};
typedef boost::shared_ptr<CHttpRequest> CHttpRequestPtr;
#endif /* _HTTP_REQUEST_H_ */
|
ModX Revolution 2.5.0 = <API key>
ModX Revolution 2.3.3 = <API key>
ModX Revolution 2.3.2 = <API key>
MODX Revolution 2.2.8 = <API key>
MODX Revolution 2.5.2 = <API key>
|
#include "RocksIndex.hh"
#include <stdlib.h>
#include <iostream>
// Get command line arguments for array size (100M) and number of trials (1M)
void arrayArgs(int argc, char* argv[], objectId_t& asize, int& reps) {
asize = (argc>1) ? strtoull(argv[1], 0, 0) : 100000000;
reps = (argc>2) ? strtol(argv[2], 0, 0) : 1000000;
}
// Main program goes here
int main(int argc, char* argv[]) {
objectId_t arraySize;
int queryTrials;
arrayArgs(argc, argv, arraySize, queryTrials);
std::cout << "RocksDB Table " << arraySize << " elements, " << queryTrials
<< " trials" << std::endl;
RocksIndex rocks(2); // Verbosity
rocks.CreateTable(arraySize);
rocks.ExerciseTable(queryTrials);
}
|
#!/usr/bin/env bash
. test_common.sh
id=process
rm -f $id.out
ln -s "$test_base/test/$id.data.in" . 2>/dev/null
test_server_start $id test
pid=$!
hector_client_set PE_test.run 1
hector_client -c "PROCESS PE_test" $HECTOR_HOST <$id.data.in >$id.data.out
hector_client_wait M_simple[0].items 1000
hector_client_set PE_test.run 0
<API key>
wait $!
md5sum <$id.data.out >$id.log.result
if [ -L $id.data.in ]; then
rm $id.data.in
fi
test_compare_result $id
exit $?
|
/**
* @file
*/
#ifndef <API key>
#define <API key>
#include <dds/core/types.hpp>
#include <dds/core/LengthUnlimited.hpp>
#include <dds/core/Duration.hpp>
// DDS Policy Classes
namespace org
{
namespace opensplice
{
namespace core
{
namespace policy
{
/**
* @internal The purpose of this QoS is to allow the application to attach additional
* information to the created Entity objects such that when a remote application
* discovers their existence it can access that information and use it for its
* own purposes. One possible use of this QoS is to attach security credentials
* or some other information that can be used by the remote application to
* authenticate the source. In combination with operations such as
* ignore_participant, ignore_publication, ignore_subscription,
* and ignore_topic these QoS can assist an application to define and enforce
* its own security policies. The use of this QoS is not limited to security,
* rather it offers a simple, yet flexible extensibility mechanism.
*/
class UserData
{
public:
/**
* @internal Create a <code>UserData</code> instance with an empty user data.
*/
UserData() : value_() { }
/**
* @internal Create a <code>UserData</code> instance.
*
* @param seq the sequence of octet representing the user data
*/
explicit UserData(const dds::core::ByteSeq& seq) : value_(seq) { }
/**
* @internal Set the value for the user data.
*
* @param seq a sequence of octet representing the user data.
*/
void value(const dds::core::ByteSeq& seq)
{
value_ = seq;
}
/**
* @internal Get/Set the user data.
*
* @return the sequence of octet representing the user data
*/
dds::core::ByteSeq& value()
{
return value_;
}
/**
* @internal Get the user data.
*
* @return the sequence of octet representing the user data
*/
const dds::core::ByteSeq& value() const
{
return value_;
}
bool operator ==(const UserData& other) const
{
return other.value() == value_;
}
private:
dds::core::ByteSeq value_;
};
/**
* @internal The purpose of this QoS is to allow the application to attach additional
* information to the created Publisher or Subscriber.
* The value of the GROUP_DATA is available to the application on the
* DataReader and DataWriter entities and is propagated by means of the
* built-in topics. This QoS can be used by an application combination with
* the DataReaderListener and DataWriterListener to implement matching policies
* similar to those of the PARTITION QoS except the decision can be made based
* on an application-defined policy.
*/
class GroupData
{
public:
/**
* @internal Create a <code>GroupData</code> instance.
*/
GroupData() : value_() { }
/**
* @internal Create a <code>GroupData</code> instance.
*
* @param seq the group data value
*/
explicit GroupData(const dds::core::ByteSeq& seq) : value_(seq) { }
/**
* @internal Set the value for this <code>GroupData</code>
*
* @param seq the group data value
*/
void value(const dds::core::ByteSeq& seq)
{
value_ = seq;
}
/**
* @internal Get/Set the value for this <code>GroupData</code>
*
* @return the group data value
*/
dds::core::ByteSeq& value()
{
return value_;
}
/**
* @internal Get the value for this <code>GroupData</code>
*
* @return the group data value
*/
const dds::core::ByteSeq& value() const
{
return value_;
}
bool operator ==(const GroupData& other) const
{
return other.value() == value_;
}
private:
dds::core::ByteSeq value_;
};
/**
* @internal The purpose of this QoS is to allow the application to attach additional
* information to the created Topic such that when a remote application
* discovers their existence it can examine the information and use it in
* an application-defined way. In combination with the listeners on the
* DataReader and DataWriter as well as by means of operations such as
* ignore_topic, these QoS can assist an application to extend the provided QoS.
*/
class TopicData
{
public:
TopicData() : value_() { }
explicit TopicData(const dds::core::ByteSeq& seq) : value_(seq) { }
void value(const dds::core::ByteSeq& seq)
{
value_ = seq;
}
const dds::core::ByteSeq& value() const
{
return value_;
}
dds::core::ByteSeq& value()
{
return value_;
}
bool operator ==(const TopicData& other) const
{
return other.value() == value_;
}
private:
dds::core::ByteSeq value_;
};
class EntityFactory
{
public:
EntityFactory() {}
explicit EntityFactory(bool auto_enable)
: auto_enable_(auto_enable) { }
void auto_enable(bool on)
{
auto_enable_ = on;
}
bool auto_enable() const
{
return auto_enable_;
}
bool& auto_enable()
{
return auto_enable_;
}
bool operator ==(const EntityFactory& other) const
{
return other.auto_enable() == auto_enable_;
}
private:
bool auto_enable_;
};
/**
* @internal The purpose of this QoS is to allow the application to take advantage of
* transports capable of sending messages with different priorities.
* This policy is considered a hint. The policy depends on the ability of the
* underlying transports to set a priority on the messages they send.
* Any value within the range of a 32-bit signed integer may be chosen;
* higher values indicate higher priority. However, any further interpretation
* of this policy is specific to a particular transport and a particular
* implementation of the Service. For example, a particular transport is
* permitted to treat a range of priority values as equivalent to one another.
* It is expected that during transport configuration the application would
* provide a mapping between the values of the TRANSPORT_PRIORITY set on
* DataWriter and the values meaningful to each transport. This mapping would
* then be used by the infrastructure when propagating the data written by
* the DataWriter.
*/
class TransportPriority
{
public:
TransportPriority() {}
explicit TransportPriority(uint32_t prio) : value_(prio) { }
public:
void value(uint32_t prio)
{
value_ = prio;
}
uint32_t value() const
{
return value_;
}
uint32_t& value()
{
return value_;
}
bool operator ==(const TransportPriority& other) const
{
return other.value() == value_;
}
private:
uint32_t value_;
};
class Lifespan
{
public:
Lifespan() {}
explicit Lifespan(const dds::core::Duration& d) : duration_(d) { }
public:
void duration(const dds::core::Duration& d)
{
duration_ = d;
}
const dds::core::Duration duration() const
{
return duration_;
}
dds::core::Duration& duration()
{
return duration_;
}
bool operator ==(const Lifespan& other) const
{
return other.duration() == duration_;
}
private:
dds::core::Duration duration_;
};
class Deadline
{
public:
Deadline() {}
explicit Deadline(const dds::core::Duration& d) : period_(d) { }
public:
void period(const dds::core::Duration& d)
{
period_ = d;
}
const dds::core::Duration period() const
{
return period_;
}
bool operator ==(const Deadline& other) const
{
return other.period() == period_;
}
private:
dds::core::Duration period_;
};
class LatencyBudget
{
public:
LatencyBudget() {}
explicit LatencyBudget(const dds::core::Duration& d) : duration_(d) { }
public:
void duration(const dds::core::Duration& d)
{
duration_ = d;
}
const dds::core::Duration duration() const
{
return duration_;
}
dds::core::Duration& duration()
{
return duration_;
}
bool operator ==(const LatencyBudget& other) const
{
return other.duration() == duration_;
}
private:
dds::core::Duration duration_;
};
class TimeBasedFilter
{
public:
TimeBasedFilter() {}
explicit TimeBasedFilter(const dds::core::Duration& min_separation)
: min_sep_(min_separation) { }
public:
void min_separation(const dds::core::Duration& ms)
{
min_sep_ = ms;
}
const dds::core::Duration min_separation() const
{
return min_sep_;
}
dds::core::Duration& min_separation()
{
return min_sep_;
}
bool operator ==(const TimeBasedFilter& other) const
{
return other.min_separation() == min_sep_;
}
private:
dds::core::Duration min_sep_;
};
class Partition
{
public:
Partition() {}
explicit Partition(const std::string& partition) : name_()
{
name_.push_back(partition);
}
explicit Partition(const dds::core::StringSeq& partitions)
: name_(partitions) { }
public:
void name(const std::string& partition)
{
name_.clear();
name_.push_back(partition);
}
void name(const dds::core::StringSeq& partitions)
{
name_ = partitions;
}
const dds::core::StringSeq& name() const
{
return name_;
}
dds::core::StringSeq& name()
{
return name_;
}
bool operator ==(const Partition& other) const
{
return other.name() == name_;
}
private:
dds::core::StringSeq name_;
};
class Ownership
{
public:
public:
Ownership() {}
Ownership(dds::core::policy::OwnershipKind::Type kind) : kind_(kind) { }
public:
void kind(dds::core::policy::OwnershipKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::OwnershipKind::Type kind() const
{
return kind_;
}
dds::core::policy::OwnershipKind::Type& kind()
{
return kind_;
}
bool operator ==(const Ownership& other) const
{
return other.kind() == kind_;
}
private:
dds::core::policy::OwnershipKind::Type kind_;
};
#ifdef <API key>
class OwnershipStrength
{
public:
OwnershipStrength() {}
explicit OwnershipStrength(int32_t s) : s_(s) { }
int32_t strength() const
{
return s_;
}
int32_t& strength()
{
return s_;
}
void strength(int32_t s)
{
s_ = s;
}
bool operator ==(const OwnershipStrength& other) const
{
return other.strength() == s_;
}
private:
int32_t s_;
};
#endif // <API key>
class WriterDataLifecycle
{
public:
WriterDataLifecycle() {}
WriterDataLifecycle(bool autodispose)
: autodispose_(autodispose) { }
bool autodispose() const
{
return autodispose_;
}
bool& autodispose()
{
return autodispose_;
}
void autodispose(bool b)
{
autodispose_ = b;
}
bool operator ==(const WriterDataLifecycle& other) const
{
return other.autodispose() == autodispose_;
}
private:
bool autodispose_;
};
class ReaderDataLifecycle
{
public:
ReaderDataLifecycle() {}
ReaderDataLifecycle(const dds::core::Duration& nowriter_delay,
const dds::core::Duration& <API key>)
: <API key>(nowriter_delay),
<API key>(<API key>) { }
public:
const dds::core::Duration <API key>() const
{
return <API key>;
}
void <API key>(const dds::core::Duration& d)
{
<API key> = d;
}
const dds::core::Duration <API key>() const
{
return <API key>;
}
void <API key>(const dds::core::Duration& d)
{
<API key> = d;
}
bool operator ==(const ReaderDataLifecycle& other) const
{
return other.<API key>() == <API key> &&
other.<API key>() == <API key>();
}
private:
dds::core::Duration <API key>;
dds::core::Duration <API key>;
};
class Durability
{
public:
public:
Durability() {}
Durability(dds::core::policy::DurabilityKind::Type kind) : kind_(kind) { }
public:
void durability(dds::core::policy::DurabilityKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::DurabilityKind::Type durability() const
{
return kind_;
}
dds::core::policy::DurabilityKind::Type& durability()
{
return kind_;
}
void kind(dds::core::policy::DurabilityKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::DurabilityKind::Type& kind()
{
return kind_;
}
dds::core::policy::DurabilityKind::Type kind() const
{
return kind_;
}
bool operator ==(const Durability& other) const
{
return other.kind() == kind_;
}
public:
dds::core::policy::DurabilityKind::Type kind_;
};
class Presentation
{
public:
Presentation() {}
Presentation(dds::core::policy::<API key>::Type access_scope,
bool coherent_access,
bool ordered_access)
: access_scope_(access_scope),
coherent_access_(coherent_access),
ordered_access_(ordered_access)
{ }
void access_scope(dds::core::policy::<API key>::Type as)
{
access_scope_ = as;
}
dds::core::policy::<API key>::Type& access_scope()
{
return access_scope_;
}
dds::core::policy::<API key>::Type access_scope() const
{
return access_scope_;
}
void coherent_access(bool on)
{
coherent_access_ = on;
}
bool& coherent_access()
{
return coherent_access_;
}
bool coherent_access() const
{
return coherent_access_;
}
void ordered_access(bool on)
{
ordered_access_ = on;
}
bool& ordered_access()
{
return ordered_access_;
}
bool ordered_access() const
{
return ordered_access_;
}
bool operator ==(const Presentation& other) const
{
return other.access_scope() == access_scope_ &&
other.coherent_access() == coherent_access_ &&
other.ordered_access() == ordered_access_;
}
private:
dds::core::policy::<API key>::Type access_scope_;
bool coherent_access_;
bool ordered_access_;
};
class Reliability
{
public:
public:
Reliability() {}
Reliability(dds::core::policy::ReliabilityKind::Type kind,
const dds::core::Duration& max_blocking_time)
: kind_(kind),
max_blocking_time_(max_blocking_time) { }
public:
void kind(dds::core::policy::ReliabilityKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::ReliabilityKind::Type kind() const
{
return kind_;
}
void max_blocking_time(const dds::core::Duration& d)
{
max_blocking_time_ = d;
}
const dds::core::Duration max_blocking_time() const
{
return max_blocking_time_;
}
bool operator ==(const Reliability& other) const
{
return other.kind() == kind_ &&
other.max_blocking_time() == max_blocking_time_;
}
private:
dds::core::policy::ReliabilityKind::Type kind_;
dds::core::Duration max_blocking_time_;
};
class DestinationOrder
{
public:
DestinationOrder() {};
explicit DestinationOrder(dds::core::policy::<API key>::Type kind)
: kind_(kind) { }
public:
void kind(dds::core::policy::<API key>::Type kind)
{
kind_ = kind;
}
dds::core::policy::<API key>::Type& kind()
{
return kind_;
}
dds::core::policy::<API key>::Type kind() const
{
return kind_;
}
bool operator ==(const DestinationOrder& other) const
{
return other.kind() == kind_;
}
private:
dds::core::policy::<API key>::Type kind_;
};
class History
{
public:
History() {}
History(dds::core::policy::HistoryKind::Type kind, int32_t depth)
: kind_(kind),
depth_(depth)
{ }
dds::core::policy::HistoryKind::Type kind() const
{
return kind_;
}
dds::core::policy::HistoryKind::Type& kind()
{
return kind_;
}
void kind(dds::core::policy::HistoryKind::Type kind)
{
kind_ = kind;
}
int32_t depth() const
{
return depth_;
}
int32_t& depth()
{
return depth_;
}
void depth(int32_t depth)
{
depth_ = depth;
}
bool operator ==(const History& other) const
{
return other.kind() == kind_ &&
other.depth() == depth_;
}
private:
dds::core::policy::HistoryKind::Type kind_;
int32_t depth_;
};
class ResourceLimits
{
public:
ResourceLimits() {}
ResourceLimits(int32_t max_samples,
int32_t max_instances,
int32_t <API key>)
: max_samples_(max_samples),
max_instances_(max_instances),
<API key>(<API key>)
{ }
public:
void max_samples(int32_t samples)
{
max_samples_ = samples;
}
int32_t& max_samples()
{
return max_samples_;
}
int32_t max_samples() const
{
return max_samples_;
}
void max_instances(int32_t max_instances)
{
max_instances_ = max_instances;
}
int32_t& max_instances()
{
return max_instances_;
}
int32_t max_instances() const
{
return max_instances_;
}
void <API key>(int32_t <API key>)
{
<API key> = <API key>;
}
int32_t& <API key>()
{
return <API key>;
}
int32_t <API key>() const
{
return <API key>;
}
bool operator ==(const ResourceLimits& other) const
{
return other.max_samples() == max_samples_ &&
other.max_instances() == max_instances_ &&
other.<API key>() == <API key>;
}
private:
int32_t max_samples_;
int32_t max_instances_;
int32_t <API key>;
};
class Liveliness
{
public:
public:
Liveliness() {}
Liveliness(dds::core::policy::LivelinessKind::Type kind,
dds::core::Duration lease_duration)
: kind_(kind),
lease_duration_(lease_duration)
{ }
void kind(dds::core::policy::LivelinessKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::LivelinessKind::Type& kind()
{
return kind_;
}
dds::core::policy::LivelinessKind::Type kind() const
{
return kind_;
}
void lease_duration(const dds::core::Duration& lease_duration)
{
lease_duration_ = lease_duration;
}
dds::core::Duration& lease_duration()
{
return lease_duration_;
}
const dds::core::Duration lease_duration() const
{
return lease_duration_;
}
bool operator ==(const Liveliness& other) const
{
return other.kind() == kind_ &&
other.lease_duration() == lease_duration_;
}
private:
dds::core::policy::LivelinessKind::Type kind_;
dds::core::Duration lease_duration_;
};
#ifdef <API key>
class DurabilityService
{
public:
DurabilityService() {}
DurabilityService(const dds::core::Duration& <API key>,
dds::core::policy::HistoryKind::Type history_kind,
int32_t history_depth,
int32_t max_samples,
int32_t max_instances,
int32_t <API key>)
: cleanup_delay_(<API key>),
history_kind_(history_kind),
history_depth_(history_depth),
max_samples_(max_samples),
max_instances_(max_instances),
<API key>(<API key>)
{ }
public:
void <API key>(const dds::core::Duration& d)
{
cleanup_delay_ = d;
}
const dds::core::Duration <API key>() const
{
return cleanup_delay_;
}
void history_kind(dds::core::policy::HistoryKind::Type kind)
{
history_kind_ = kind;
}
dds::core::policy::HistoryKind::Type history_kind() const
{
return history_kind_;
}
void history_depth(int32_t depth)
{
history_depth_ = depth;
}
int32_t history_depth() const
{
return history_depth_;
}
void max_samples(int32_t max_samples)
{
max_samples_ = max_samples;
}
int32_t max_samples() const
{
return max_samples_;
}
void max_instances(int32_t max_instances)
{
max_instances_ = max_instances;
}
int32_t max_instances() const
{
return max_instances_;
}
void <API key>(int32_t <API key>)
{
<API key> = <API key>;
}
int32_t <API key>() const
{
return <API key>;
}
bool operator ==(const DurabilityService& other) const
{
return other.<API key>() == cleanup_delay_ &&
other.history_kind() == history_kind_ &&
other.history_depth() == history_depth_ &&
other.max_samples() == max_samples_ &&
other.max_instances() == max_instances_ &&
other.<API key>() == <API key>;
}
private:
dds::core::Duration cleanup_delay_;
dds::core::policy::HistoryKind::Type history_kind_;
int32_t history_depth_;
int32_t max_samples_;
int32_t max_instances_;
int32_t <API key>;
};
#endif // <API key>
#ifdef <API key>
class DataRepresentation { };
#endif // <API key>
#ifdef <API key>
class <API key> { };
#endif // <API key>
}
}
}
} // namespace org::opensplice::core::policy
#endif /* <API key> */
|
<!DOCTYPE html PUBLIC "-
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.6">
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="typedefs_1.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Cargando...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!
createResults();
--></script>
<div class="SRStatus" id="Searching">Buscando...</div>
<div class="SRStatus" id="NoMatches">Nada coincide</div>
<script type="text/javascript"><!
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
|
<?php
namespace Paged;
class ViewList extends PluginView {
public function getList(){
$list = parent::getList();
$list_new = array();
foreach ($list as $item)
$list_new[] = Template::getTemplate('list.php', array($item));
return $list_new;
}
public function getPack(){
return Template::getTemplate('list_pack.php', $this->getList());
}
public function showPack(){
Template::showTemplate('list_pack.php', $this->getList());
}
}
|
import io
import openpyxl
from django.test import (
Client, TestCase
)
from django.urls import reverse
from core.models import (
User, Batch, Section, Election, Candidate, CandidateParty,
CandidatePosition, Vote, VoterProfile, Setting, UserType
)
class ResultsExporter(TestCase):
"""
Tests the results xlsx exporter view.
This subview may only process requests from logged in admin users. Other
users will be redirected to '/'. This will also only accept GET requests.
GET requests may have an election`parameter whose value must be the id
of an election. The lack of an election parameter will result in the
results of all elections to be exported, with each election having its
own worksheet. Other URL parameters will be ignored. Invalid election
parameter values, e.g. non-existent election IDs and non-integer parameters,
will return an error message.
View URL: '/results/export'
"""
@classmethod
def setUpTestData(cls):
batch_num = 0
section_num = 0
voter_num = 0
party_num = 0
position_num = 0
candidate_num = 0
num_elections = 2
voters = list()
positions = dict()
for i in range(num_elections):
election = Election.objects.create(name='Election {}'.format(i))
positions[str(election.name)] = list()
num_batches = 2
for j in range(num_batches):
batch = Batch.objects.create(year=batch_num, election=election)
batch_num += 1
num_sections = 2 if j == 0 else 1
for k in range(num_sections):
section = Section.objects.create(
section_name=str(section_num)
)
section_num += 1
num_students = 2
for l in range(num_students):
voter = User.objects.create(
username='user{}'.format(voter_num),
first_name=str(voter_num),
last_name=str(voter_num),
type=UserType.VOTER
)
voter.set_password('voter')
voter.save()
voter_num += 1
VoterProfile.objects.create(
user=voter,
batch=batch,
section=section
)
voters.append(voter)
num_positions = 3
for i in range(num_positions):
position = CandidatePosition.objects.create(
position_name='Position {}'.format(position_num),
election=election
)
positions[str(election.name)].append(position)
position_num += 1
num_parties = 3
for j in range(num_parties):
party = CandidateParty.objects.create(
party_name='Party {}'.format(party_num),
election=election
)
party_num += 1
if j != 2: # Let every third party have no candidates.
num_positions = 3
for k in range(num_positions):
position = positions[str(election.name)][k]
candidate = Candidate.objects.create(
user=voters[candidate_num],
party=party,
position=position,
election=election
)
Vote.objects.create(
user=voters[candidate_num],
candidate=candidate,
election=election
)
candidate_num += 1
# Let's give one candidate an additional vote to really make sure that
# we all got the correct number of votes.
Vote.objects.create(
user=voters[0],
# NOTE: The voter in voter[1] is a Position 1 candidate of
# Party 1, where the voter in voter[0] is a member.
candidate=Candidate.objects.get(user=voters[1]),
election=Election.objects.get(name='Election 0')
)
_admin = User.objects.create(username='admin', type=UserType.ADMIN)
_admin.set_password('root')
_admin.save()
def setUp(self):
self.client.login(username='admin', password='root')
def <API key>(self):
self.client.logout()
response = self.client.get(reverse('results-export'), follow=True)
self.assertRedirects(response, '/?next=%2Fadmin%2Fresults')
def <API key>(self):
self.client.logout()
self.client.login(username='user0', password='voter')
response = self.client.get(reverse('results-export'), follow=True)
self.assertRedirects(response, reverse('index'))
def <API key>(self):
response = self.client.get(reverse('results-export'))
self.assertEqual(response.status_code, 200)
self.assertEqual(
response['Content-Disposition'],
'attachment; filename="Election Results.xlsx"'
)
wb = openpyxl.load_workbook(io.BytesIO(response.content))
self.assertEqual(len(wb.worksheets), 2)
# Check first worksheet.
ws = wb.worksheets[0]
self.assertEqual(wb.sheetnames[0], 'Election 0')
row_count = ws.max_row
col_count = ws.max_column
self.assertEqual(row_count, 25)
self.assertEqual(col_count, 5)
self.assertEqual(str(ws.cell(1, 1).value), 'Election 0 Results')
self.assertEqual(str(ws.cell(2, 1).value), 'Candidates')
cellContents = [
'Position 0',
'Party 0',
'0, 0',
'Party 1',
'3, 3',
'Party 2',
'None',
'Position 1',
'Party 0',
'1, 1',
'Party 1',
'4, 4',
'Party 2',
'None',
'Position 2',
'Party 0',
'2, 2',
'Party 1',
'5, 5',
'Party 2',
'None'
]
for cellIndex, content in enumerate(cellContents, 5):
self.assertEqual(str(ws.cell(cellIndex, 1).value), content)
self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes')
self.assertEqual(str(ws.cell(3, 2).value), '0')
self.assertEqual(str(ws.cell(4, 2).value), '0') # Section
self.assertEqual(str(ws.cell(7, 2).value), '1')
self.assertEqual(str(ws.cell(9, 2).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 2).value), '2')
self.assertEqual(str(ws.cell(16, 2).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 2).value), '0')
self.assertEqual(str(ws.cell(23, 2).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(4, 3).value), '1') # Section
self.assertEqual(str(ws.cell(7, 3).value), '0')
self.assertEqual(str(ws.cell(9, 3).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 3).value), '0')
self.assertEqual(str(ws.cell(16, 3).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 3).value), '1')
self.assertEqual(str(ws.cell(23, 3).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 4).value), '1')
self.assertEqual(str(ws.cell(4, 4).value), '2') # Section
self.assertEqual(str(ws.cell(7, 4).value), '0')
self.assertEqual(str(ws.cell(9, 4).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 4).value), '0')
self.assertEqual(str(ws.cell(16, 4).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 4).value), '0')
self.assertEqual(str(ws.cell(23, 4).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes')
self.assertEqual(str(ws.cell(7, 5).value), '1')
self.assertEqual(str(ws.cell(9, 5).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 5).value), '2')
self.assertEqual(str(ws.cell(16, 5).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 5).value), '1')
self.assertEqual(str(ws.cell(23, 5).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
# Check second worksheet.
ws = wb.worksheets[1]
self.assertEqual(wb.sheetnames[1], 'Election 1')
row_count = ws.max_row
col_count = ws.max_column
self.assertEqual(row_count, 25)
self.assertEqual(col_count, 5)
self.assertEqual(str(ws.cell(1, 1).value), 'Election 1 Results')
self.assertEqual(str(ws.cell(2, 1).value), 'Candidates')
self.assertEqual(str(ws.cell(2, 1).value), 'Candidates')
cellContents = [
'Position 3',
'Party 3',
'6, 6',
'Party 4',
'9, 9',
'Party 5',
'None',
'Position 4',
'Party 3',
'7, 7',
'Party 4',
'10, 10',
'Party 5',
'None',
'Position 5',
'Party 3',
'8, 8',
'Party 4',
'11, 11',
'Party 5',
'None'
]
for cellIndex, content in enumerate(cellContents, 5):
self.assertEqual(str(ws.cell(cellIndex, 1).value), content)
self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes')
self.assertEqual(str(ws.cell(3, 2).value), '2')
self.assertEqual(str(ws.cell(4, 2).value), '3') # Section
self.assertEqual(str(ws.cell(7, 2).value), '1')
self.assertEqual(str(ws.cell(9, 2).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 2).value), '1')
self.assertEqual(str(ws.cell(16, 2).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 2).value), '0')
self.assertEqual(str(ws.cell(23, 2).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(4, 3).value), '4') # Section
self.assertEqual(str(ws.cell(7, 3).value), '0')
self.assertEqual(str(ws.cell(9, 3).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 3).value), '0')
self.assertEqual(str(ws.cell(16, 3).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 3).value), '1')
self.assertEqual(str(ws.cell(23, 3).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 4).value), '3')
self.assertEqual(str(ws.cell(4, 4).value), '5') # Section
self.assertEqual(str(ws.cell(7, 4).value), '0')
self.assertEqual(str(ws.cell(9, 4).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 4).value), '0')
self.assertEqual(str(ws.cell(16, 4).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 4).value), '0')
self.assertEqual(str(ws.cell(23, 4).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes')
self.assertEqual(str(ws.cell(7, 5).value), '1')
self.assertEqual(str(ws.cell(9, 5).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 5).value), '1')
self.assertEqual(str(ws.cell(16, 5).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 5).value), '1')
self.assertEqual(str(ws.cell(23, 5).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
def <API key>(self):
response = self.client.get(
reverse('results-export'),
{ 'election': str(Election.objects.get(name='Election 0').id) }
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response['Content-Disposition'],
'attachment; filename="Election 0 Results.xlsx"'
)
wb = openpyxl.load_workbook(io.BytesIO(response.content))
self.assertEqual(len(wb.worksheets), 1)
# Check first worksheet.
ws = wb.worksheets[0]
self.assertEqual(wb.sheetnames[0], 'Election 0')
row_count = ws.max_row
col_count = ws.max_column
self.assertEqual(row_count, 25)
self.assertEqual(col_count, 5)
self.assertEqual(str(ws.cell(1, 1).value), 'Election 0 Results')
self.assertEqual(str(ws.cell(2, 1).value), 'Candidates')
cellContents = [
'Position 0',
'Party 0',
'0, 0',
'Party 1',
'3, 3',
'Party 2',
'None',
'Position 1',
'Party 0',
'1, 1',
'Party 1',
'4, 4',
'Party 2',
'None',
'Position 2',
'Party 0',
'2, 2',
'Party 1',
'5, 5',
'Party 2',
'None'
]
for cellIndex, content in enumerate(cellContents, 5):
self.assertEqual(str(ws.cell(cellIndex, 1).value), content)
self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes')
self.assertEqual(str(ws.cell(3, 2).value), '0')
self.assertEqual(str(ws.cell(4, 2).value), '0') # Section
self.assertEqual(str(ws.cell(7, 2).value), '1')
self.assertEqual(str(ws.cell(9, 2).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 2).value), '2')
self.assertEqual(str(ws.cell(16, 2).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 2).value), '0')
self.assertEqual(str(ws.cell(23, 2).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(4, 3).value), '1') # Section
self.assertEqual(str(ws.cell(7, 3).value), '0')
self.assertEqual(str(ws.cell(9, 3).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 3).value), '0')
self.assertEqual(str(ws.cell(16, 3).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 3).value), '1')
self.assertEqual(str(ws.cell(23, 3).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 4).value), '1')
self.assertEqual(str(ws.cell(4, 4).value), '2') # Section
self.assertEqual(str(ws.cell(7, 4).value), '0')
self.assertEqual(str(ws.cell(9, 4).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 4).value), '0')
self.assertEqual(str(ws.cell(16, 4).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 4).value), '0')
self.assertEqual(str(ws.cell(23, 4).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes')
self.assertEqual(str(ws.cell(7, 5).value), '1')
self.assertEqual(str(ws.cell(9, 5).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 5).value), '2')
self.assertEqual(str(ws.cell(16, 5).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 5).value), '1')
self.assertEqual(str(ws.cell(23, 5).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
def <API key>(self):
response = self.client.get(
reverse('results-export'),
{ 'election': '69' },
HTTP_REFERER=reverse('results'),
follow=True
)
messages = list(response.context['messages'])
self.assertEqual(
messages[0].message,
'You specified an ID for a non-existent election.'
)
self.assertRedirects(response, reverse('results'))
def <API key>(self):
response = self.client.get(
reverse('results-export'),
{ 'election': 'hey' },
HTTP_REFERER=reverse('results'),
follow=True
)
messages = list(response.context['messages'])
self.assertEqual(
messages[0].message,
'You specified a non-integer election ID.'
)
self.assertRedirects(response, reverse('results'))
def <API key>(self):
response = self.client.get(
reverse('results-export'),
{ 'election': '69' },
HTTP_REFERER=reverse('results'),
follow=True
)
messages = list(response.context['messages'])
self.assertEqual(
messages[0].message,
'You specified an ID for a non-existent election.'
)
self.assertRedirects(response, reverse('results'))
def <API key>(self):
response = self.client.get(
reverse('results-export'),
{ 'election': 'hey' },
HTTP_REFERER=reverse('results'),
follow=True
)
messages = list(response.context['messages'])
self.assertEqual(
messages[0].message,
'You specified a non-integer election ID.'
)
self.assertRedirects(response, reverse('results'))
|
#include "unit_vector.h"
namespace geometry
{
template class UnitVector<double>;
template const UnitVector<double> operator-(const UnitVector<double> &rhs);
}
|
<?php
defined('_JEXEC') or die('Restricted access');
require_once( <API key>.DS.'helpers'.DS.'jobboard_list.php' );
jimport( 'joomla.application.component.view');
jimport('joomla.utilities.date');
class JobboardViewList extends JView
{
function display($tpl = null) {
if(!JobBoardListHelper::rssEnabled()) jexit(JText::_('<API key>') );
$catid = $this->selcat;
$keywd = $this->keysrch;
$document =& JFactory::getDocument();
$document->setLink(JRoute::_('index.php?option=com_jobboard&selcat='.$catid));
// get category name
$db =& JFactory::getDBO();
$query = 'SELECT '.$db->nameQuote('type').' FROM '.$db->nameQuote('#<API key>').' WHERE '.$db->nameQuote('id').' = '.$catid;
$db->setQuery($query);
$seldesc = $db->loadResult();
// get "show location" settings:
$query = 'SELECT '.$db->nameQuote('use_location').' FROM '.$db->nameQuote('#__jobboard_config').' WHERE '.$db->nameQuote('id').' = 1';
$db->setQuery($query);
$use_location = $db->loadResult();
// get the items to add to the feed
$where = ($catid == 1)? '' : ' WHERE c.'.$db->nameQuote('id').' = '.$catid;
$tag_include = strlen($keywd);
if($tag_include > 0 && $catid == 1) {
$tag_requested = $this->checkTagRequest($keywd);
$where .= ($tag_requested <> '')? " WHERE j.".$db->nameQuote('job_tags')." LIKE '%{$tag_requested}%' " : '';
}
$limit = 10;
$where .= ' AND (DATE_FORMAT(j.expiry_date,"%Y-%m-%d") >= CURDATE() OR DATE_FORMAT(j.expiry_date,"%Y-%m-%d") = 0000-00-00) ';
$query = 'SELECT
j.`id`
, j.`post_date`
, j.`job_title`
, j.`job_type`
, j.`country`
, c.`type` AS category
, cl.`description` AS job_level
, j.`description`
, j.`city`
FROM
`#__jobboard_jobs` AS j
INNER JOIN `#<API key>` AS c
ON (j.`category` = c.`id`)
INNER JOIN `#<API key>` AS cl
ON (j.`career_level` = cl.`id`)
'.$where.'
ORDER BY j.`post_date` DESC LIMIT '.$limit;
$db->setQuery($query);
$rows = $db->loadObjectList();
$site_name = $_SERVER['SERVER_NAME'];
if($tag_requested <> ''){
$document->setDescription(JText::_('JOBS_WITH').' "'.ucfirst($tag_requested).'" '.JText::_('KEYWD_TAG'));
$rss_title = $site_name. ': '.JText::_('JOBS_WITH').' "'.ucfirst($tag_requested).'" ';
}else {
$document->setDescription(JText::_('RSS_LATEST_JOBS').': '.$seldesc );
$rss_title = $site_name. ': '.JText::_('RSS_LATEST_JOBS').': '.$seldesc;
}
$document->setTitle($rss_title);
foreach ($rows as $row)
{
// create a new feed item
$job = new JFeedItem();
// assign values to the item
$job_date = new JDate($row->post_date);
$job_pubDate = new JDate();
$job->category = $row->category ;
$job->date = $job_date->toRFC822();
$job->description = $this->trimDescr(html_entity_decode($this->escape($row->description)), '.');
$link = htmlentities('index.php?option=com_jobboard&view=job&id='.$row->id);
$job->link = JRoute::_($link);
$job->pubDate = $job_pubDate->toRFC822();
if($use_location) {
$job_location = ($row->country <> 266)? ', '.$row->city : ', '.JText::_('WORK_FROM_ANYWHERE');
} else $job_location = '';
$job->title = JText::_('JOB_VACANCY').': '.html_entity_decode($this->escape($row->job_title.$job_location.' ('.JText::_($row->job_type).')'));
// add item to the feed
$document->addItem($job);
}
}
function checkTagRequest($keywd) {
$key_array = explode( ',' , $keywd);
return (count($key_array) == 1)? $this->escape(trim(strtolower ( $key_array[0]) ) ) : '';
}
function trimDescr($descr, $delim){
$first_bit = strstr($descr, '.', true);
$remainder = strstr($descr, '.');
return $first_bit.'. '.strstr(substr($remainder, 1), '.', true).' ...';
}
}
?>
|
package eieio
import (
"context"
"fmt"
"github.com/spatialmodel/inmap/emissions/slca"
"github.com/spatialmodel/inmap/emissions/slca/eieio/eieiorpc"
"github.com/spatialmodel/inmap/internal/hash"
"gonum.org/v1/gonum/mat"
)
type emissionsRequest struct {
demand *mat.VecDense
industries *Mask
pol slca.Pollutant
year Year
loc Location
aqm string
}
// Emissions returns spatially-explicit emissions caused by the
// specified economic demand. Emitters
// specifies the emitters emissions should be calculated for.
// If emitters == nil, combined emissions for all emitters are calculated.
func (e *SpatialEIO) Emissions(ctx context.Context, request *eieiorpc.EmissionsInput) (*eieiorpc.Vector, error) {
e.loadEmissionsOnce.Do(func() {
var c string
if e.EIEIOCache != "" {
c = e.EIEIOCache + "/individual"
}
e.emissionsCache = loadCacheOnce(func(ctx context.Context, request interface{}) (interface{}, error) {
r := request.(*emissionsRequest)
return e.emissions(ctx, r.demand, r.industries, r.aqm, r.pol, r.year, r.loc) // Actually calculate the emissions.
}, 1, e.MemCacheSize, c, vectorMarshal, vectorUnmarshal)
})
req := &emissionsRequest{
demand: rpc2vec(request.Demand),
industries: rpc2mask(request.Emitters),
pol: slca.Pollutant(request.Emission),
year: Year(request.Year),
loc: Location(request.Location),
aqm: request.AQM,
}
rr := e.emissionsCache.NewRequest(ctx, req, "emissions_"+hash.Hash(req))
resultI, err := rr.Result()
if err != nil {
return nil, err
}
return vec2rpc(resultI.(*mat.VecDense)), nil
}
// emissions returns spatially-explicit emissions caused by the
// specified economic demand. industries
// specifies the industries emissions should be calculated for.
// If industries == nil, combined emissions for all industries are calculated.
func (e *SpatialEIO) emissions(ctx context.Context, demand *mat.VecDense, industries *Mask, aqm string, pol slca.Pollutant, year Year, loc Location) (*mat.VecDense, error) {
// Calculate emission factors. matrix dimension: [# grid cells, # industries]
ef, err := e.emissionFactors(ctx, aqm, pol, year)
if err != nil {
return nil, err
}
// Calculate economic activity. vector dimension: [# industries, 1]
activity, err := e.economicImpactsSCC(demand, year, loc)
if err != nil {
return nil, err
}
if industries != nil {
// Set activity in industries we're not interested in to zero.
industries.Mask(activity)
}
r, _ := ef.Dims()
emis := mat.NewVecDense(r, nil)
emis.MulVec(ef, activity)
return emis, nil
}
// EmissionsMatrix returns spatially- and industry-explicit emissions caused by the
// specified economic demand. In the result matrix, the rows represent air quality
// model grid cells and the columns represent emitters.
func (e *SpatialEIO) EmissionsMatrix(ctx context.Context, request *eieiorpc.<API key>) (*eieiorpc.Matrix, error) {
ef, err := e.emissionFactors(ctx, request.AQM, slca.Pollutant(request.Emission), Year(request.Year)) // rows = grid cells, cols = industries
if err != nil {
return nil, err
}
activity, err := e.economicImpactsSCC(array2vec(request.Demand.Data), Year(request.Year), Location(request.Location)) // rows = industries
if err != nil {
return nil, err
}
r, c := ef.Dims()
emis := mat.NewDense(r, c, nil)
emis.Apply(func(_, j int, v float64) float64 {
// Multiply each emissions factor column by the corresponding activity row.
return v * activity.At(j, 0)
}, ef)
return mat2rpc(emis), nil
}
// emissionFactors returns spatially-explicit emissions per unit of economic
// production for each industry. In the result matrix, the rows represent
// air quality model grid cells and the columns represent industries.
func (e *SpatialEIO) emissionFactors(ctx context.Context, aqm string, pol slca.Pollutant, year Year) (*mat.Dense, error) {
e.loadEFOnce.Do(func() {
e.emissionFactorCache = loadCacheOnce(e.<API key>, 1, 1, e.EIEIOCache,
matrixMarshal, matrixUnmarshal)
})
key := fmt.Sprintf("emissionFactors_%s_%v_%d", aqm, pol, year)
rr := e.emissionFactorCache.NewRequest(ctx, aqmPolYear{aqm: aqm, pol: pol, year: year}, key)
resultI, err := rr.Result()
if err != nil {
return nil, fmt.Errorf("eieio.emissionFactors: %s: %v", key, err)
}
return resultI.(*mat.Dense), nil
}
// emissionFactors returns spatially-explicit emissions per unit of economic
// production for each industry. In the result matrix, the rows represent
// air quality model grid cells and the columns represent industries.
func (e *SpatialEIO) <API key>(ctx context.Context, request interface{}) (interface{}, error) {
aqmpolyear := request.(aqmPolYear)
prod, err := e.<API key>(aqmpolyear.year)
if err != nil {
return nil, err
}
var emisFac *mat.Dense
for i, refTemp := range e.SpatialRefs {
if len(refTemp.SCCs) == 0 {
return nil, fmt.Errorf("bea: industry %d; no SCCs", i)
}
ref := refTemp
ref.EmisYear = int(aqmpolyear.year)
ref.AQM = aqmpolyear.aqm
industryEmis, err := e.CSTConfig.EmissionsSurrogate(ctx, aqmpolyear.pol, &ref)
if err != nil {
return nil, err
}
if i == 0 {
emisFac = mat.NewDense(industryEmis.Shape[0], len(e.SpatialRefs), nil)
}
for r, v := range industryEmis.Elements {
// The emissions factor is the industry emissions divided by the
// industry economic production.
if p := prod.At(i, 0); p != 0 {
emisFac.Set(r, i, v/prod.At(i, 0))
}
}
}
return emisFac, nil
}
|
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.02 at 08:05:16 PM CEST
package net.ramso.dita.concept;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.<API key>;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "synblk.class", propOrder = {
"title",
"<API key>"
})
@XmlSeeAlso({
Synblk.class
})
public class SynblkClass {
protected Title title;
@XmlElements({
@XmlElement(name = "groupseq", type = Groupseq.class),
@XmlElement(name = "groupchoice", type = Groupchoice.class),
@XmlElement(name = "groupcomp", type = Groupcomp.class),
@XmlElement(name = "fragref", type = Fragref.class),
@XmlElement(name = "synnote", type = Synnote.class),
@XmlElement(name = "synnoteref", type = Synnoteref.class),
@XmlElement(name = "fragment", type = Fragment.class)
})
protected List<java.lang.Object> <API key>;
@XmlAttribute(name = "outputclass")
protected String outputclass;
@XmlAttribute(name = "xtrc")
protected String xtrc;
@XmlAttribute(name = "xtrf")
protected String xtrf;
@XmlAttribute(name = "base")
protected String base;
@XmlAttribute(name = "rev")
protected String rev;
@XmlAttribute(name = "importance")
protected ImportanceAttsClass importance;
@XmlAttribute(name = "status")
protected StatusAttsClass status;
@XmlAttribute(name = "props")
protected String props;
@XmlAttribute(name = "platform")
protected String platform;
@XmlAttribute(name = "product")
protected String product;
@XmlAttribute(name = "audience")
protected String audienceMod;
@XmlAttribute(name = "otherprops")
protected String otherprops;
@XmlAttribute(name = "translate")
protected YesnoAttClass translate;
@XmlAttribute(name = "lang", namespace = "http:
protected String lang;
@XmlAttribute(name = "dir")
protected DirAttsClass dir;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(<API key>.class)
@XmlSchemaType(name = "NMTOKEN")
protected String id;
@XmlAttribute(name = "conref")
protected String conref;
@XmlAttribute(name = "conrefend")
protected String conrefend;
@XmlAttribute(name = "conaction")
protected ConactionAttClass conaction;
@XmlAttribute(name = "conkeyref")
protected String conkeyref;
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link Title }
*
*/
public Title getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link Title }
*
*/
public void setTitle(Title value) {
this.title = value;
}
/**
* Gets the value of the <API key> property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the <API key> property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* <API key>().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Groupseq }
* {@link Groupchoice }
* {@link Groupcomp }
* {@link Fragref }
* {@link Synnote }
* {@link Synnoteref }
* {@link Fragment }
*
*
*/
public List<java.lang.Object> <API key>() {
if (<API key> == null) {
<API key> = new ArrayList<java.lang.Object>();
}
return this.<API key>;
}
/**
* Gets the value of the outputclass property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOutputclass() {
return outputclass;
}
/**
* Sets the value of the outputclass property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOutputclass(String value) {
this.outputclass = value;
}
/**
* Gets the value of the xtrc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrc() {
return xtrc;
}
/**
* Sets the value of the xtrc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrc(String value) {
this.xtrc = value;
}
/**
* Gets the value of the xtrf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrf() {
return xtrf;
}
/**
* Sets the value of the xtrf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrf(String value) {
this.xtrf = value;
}
/**
* Gets the value of the base property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBase() {
return base;
}
/**
* Sets the value of the base property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBase(String value) {
this.base = value;
}
/**
* Gets the value of the rev property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRev() {
return rev;
}
/**
* Sets the value of the rev property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRev(String value) {
this.rev = value;
}
/**
* Gets the value of the importance property.
*
* @return
* possible object is
* {@link ImportanceAttsClass }
*
*/
public ImportanceAttsClass getImportance() {
return importance;
}
/**
* Sets the value of the importance property.
*
* @param value
* allowed object is
* {@link ImportanceAttsClass }
*
*/
public void setImportance(ImportanceAttsClass value) {
this.importance = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link StatusAttsClass }
*
*/
public StatusAttsClass getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link StatusAttsClass }
*
*/
public void setStatus(StatusAttsClass value) {
this.status = value;
}
/**
* Gets the value of the props property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProps() {
return props;
}
/**
* Sets the value of the props property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProps(String value) {
this.props = value;
}
/**
* Gets the value of the platform property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPlatform() {
return platform;
}
/**
* Sets the value of the platform property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlatform(String value) {
this.platform = value;
}
/**
* Gets the value of the product property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProduct() {
return product;
}
/**
* Sets the value of the product property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProduct(String value) {
this.product = value;
}
/**
* Gets the value of the audienceMod property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAudienceMod() {
return audienceMod;
}
/**
* Sets the value of the audienceMod property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAudienceMod(String value) {
this.audienceMod = value;
}
/**
* Gets the value of the otherprops property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOtherprops() {
return otherprops;
}
/**
* Sets the value of the otherprops property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOtherprops(String value) {
this.otherprops = value;
}
/**
* Gets the value of the translate property.
*
* @return
* possible object is
* {@link YesnoAttClass }
*
*/
public YesnoAttClass getTranslate() {
return translate;
}
/**
* Sets the value of the translate property.
*
* @param value
* allowed object is
* {@link YesnoAttClass }
*
*/
public void setTranslate(YesnoAttClass value) {
this.translate = value;
}
/**
* Gets the value of the lang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLang() {
return lang;
}
/**
* Sets the value of the lang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLang(String value) {
this.lang = value;
}
/**
* Gets the value of the dir property.
*
* @return
* possible object is
* {@link DirAttsClass }
*
*/
public DirAttsClass getDir() {
return dir;
}
/**
* Sets the value of the dir property.
*
* @param value
* allowed object is
* {@link DirAttsClass }
*
*/
public void setDir(DirAttsClass value) {
this.dir = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the conref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConref() {
return conref;
}
/**
* Sets the value of the conref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConref(String value) {
this.conref = value;
}
/**
* Gets the value of the conrefend property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConrefend() {
return conrefend;
}
/**
* Sets the value of the conrefend property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConrefend(String value) {
this.conrefend = value;
}
/**
* Gets the value of the conaction property.
*
* @return
* possible object is
* {@link ConactionAttClass }
*
*/
public ConactionAttClass getConaction() {
return conaction;
}
/**
* Sets the value of the conaction property.
*
* @param value
* allowed object is
* {@link ConactionAttClass }
*
*/
public void setConaction(ConactionAttClass value) {
this.conaction = value;
}
/**
* Gets the value of the conkeyref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConkeyref() {
return conkeyref;
}
/**
* Sets the value of the conkeyref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConkeyref(String value) {
this.conkeyref = value;
}
}
|
<?php
/**
* @file
* Unit test of <API key>.
*/
use MediaWiki\Moderation\<API key>;
require_once __DIR__ . "/autoload.php";
/**
* @group Database
*/
class <API key> extends <API key> {
use <API key>;
/** @var string[] */
protected $tablesUsed = [ 'moderation', 'user' ];
/**
* Verify that <API key> marks the database row as rejected and returns 1.
* @covers MediaWiki\Moderation\<API key>
*/
public function testRejectOne() {
$moderator = User::createNew( 'Some moderator' );
$modid = $this->makeDbRow();
// Create and run the Consequence.
$consequence = new <API key>( $modid, $moderator );
$rejectedCount = $consequence->run();
$this->assertSame( 1, $rejectedCount );
// Check the state of the database.
$this->assertWasRejected( $modid, $moderator );
}
/**
* Verify that <API key> returns 0 for an already rejected edit.
* @covers MediaWiki\Moderation\<API key>
*/
public function testNoopRejectOne() {
$moderator = User::createNew( 'Some moderator' );
$modid = $this->makeDbRow();
// Create and run the Consequence.
$consequence1 = new <API key>( $modid, $moderator );
$consequence1->run();
$consequence2 = new <API key>( $modid, $moderator );
$rejectedCount = $consequence2->run();
$this->assertSame( 0, $rejectedCount );
// Despite $consequence2 doing nothing, the row should still be marked as rejected.
$this->assertWasRejected( $modid, $moderator );
}
/**
* Verify that <API key> does nothing if DB row is marked as merged or rejected.
* @param array $fields Passed to $dbw->update( 'moderation', ... ) before the test.
* @covers MediaWiki\Moderation\<API key>
* @dataProvider <API key>
*/
public function <API key>( array $fields ) {
$moderator = User::createNew( 'Some moderator' );
$modid = $this->makeDbRow();
$dbw = wfGetDB( DB_MASTER );
$dbw->update( 'moderation', $fields, [ 'mod_id' => $modid ], __METHOD__ );
// Create and run the Consequence.
$consequence = new <API key>( $modid, $moderator );
$rejectedCount = $consequence->run();
$this->assertSame( 0, $rejectedCount );
}
/**
* Provide datasets for <API key>() runs.
* @return array
*/
public function <API key>() {
return [
'already rejected' => [ [ 'mod_rejected' => 1 ] ],
'already merged' => [ [ 'mod_merged_revid' => 1234 ] ]
];
}
/**
* Assert that the change was marked as rejected in the database.
* @param int $modid
* @param User $moderator
*/
private function assertWasRejected( $modid, User $moderator ) {
$this->assertSelect( 'moderation',
[
'mod_rejected',
'<API key>',
'<API key>',
'mod_preloadable',
'mod_rejected_batch',
'mod_rejected_auto'
],
[ 'mod_id' => $modid ],
[ [
1,
$moderator->getId(),
$moderator->getName(),
$modid, // mod_preloadable
0, // mod_rejected_batch
0, // mod_rejected_auto
] ]
);
}
}
|
package org.n52.series.db.beans.parameter;
import java.util.HashMap;
import java.util.Map;
public abstract class Parameter<T> {
private long parameterId;
private long fkId;
private String name;
private T value;
public Map<String, Object> toValueMap() {
Map<String, Object> valueMap = new HashMap<>();
valueMap.put("name", getName());
valueMap.put("value", getValue());
return valueMap;
}
public long getParameterId() {
return parameterId;
}
public void setParameterId(long parameterId) {
this.parameterId = parameterId;
}
public long getFkId() {
return fkId;
}
public void setFkId(long fkId) {
this.fkId = fkId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSetName() {
return getName() != null;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public boolean isSetValue() {
return getValue() != null;
}
}
|
/* glpapi16.c (basic graph and network routines) */
#include "glpapi.h"
/* CAUTION: DO NOT CHANGE THE LIMITS BELOW */
#define NV_MAX 100000000 /* = 100*10^6 */
/* maximal number of vertices in the graph */
#define NA_MAX 500000000 /* = 500*10^6 */
/* maximal number of arcs in the graph */
/***********************************************************************
* NAME
*
* glp_create_graph - create graph
*
* SYNOPSIS
*
* glp_graph *glp_create_graph(int v_size, int a_size);
*
* DESCRIPTION
*
* The routine creates a new graph, which initially is empty, i.e. has
* no vertices and arcs.
*
* The parameter v_size specifies the size of data associated with each
* vertex of the graph (0 to 256 bytes).
*
* The parameter a_size specifies the size of data associated with each
* arc of the graph (0 to 256 bytes).
*
* RETURNS
*
* The routine returns a pointer to the graph created. */
static void create_graph(glp_graph *G, int v_size, int a_size)
{ G->pool = dmp_create_pool();
G->name = NULL;
G->nv_max = 50;
G->nv = G->na = 0;
G->v = xcalloc(1+G->nv_max, sizeof(glp_vertex *));
G->index = NULL;
G->v_size = v_size;
G->a_size = a_size;
return;
}
glp_graph *glp_create_graph(int v_size, int a_size)
{ glp_graph *G;
if (!(0 <= v_size && v_size <= 256))
xerror("glp_create_graph: v_size = %d; invalid size of vertex "
"data\n", v_size);
if (!(0 <= a_size && a_size <= 256))
xerror("glp_create_graph: a_size = %d; invalid size of arc dat"
"a\n", a_size);
G = xmalloc(sizeof(glp_graph));
create_graph(G, v_size, a_size);
return G;
}
/***********************************************************************
* NAME
*
* glp_set_graph_name - assign (change) graph name
*
* SYNOPSIS
*
* void glp_set_graph_name(glp_graph *G, const char *name);
*
* DESCRIPTION
*
* The routine glp_set_graph_name assigns a symbolic name specified by
* the character string name (1 to 255 chars) to the graph.
*
* If the parameter name is NULL or an empty string, the routine erases
* the existing symbolic name of the graph. */
void glp_set_graph_name(glp_graph *G, const char *name)
{ if (G->name != NULL)
{ dmp_free_atom(G->pool, G->name, strlen(G->name)+1);
G->name = NULL;
}
if (!(name == NULL || name[0] == '\0'))
{ int j;
for (j = 0; name[j] != '\0'; j++)
{ if (j == 256)
xerror("glp_set_graph_name: graph name too long\n");
if (iscntrl((unsigned char)name[j]))
xerror("glp_set_graph_name: graph name contains invalid "
"character(s)\n");
}
G->name = dmp_get_atom(G->pool, strlen(name)+1);
strcpy(G->name, name);
}
return;
}
/***********************************************************************
* NAME
*
* glp_add_vertices - add new vertices to graph
*
* SYNOPSIS
*
* int glp_add_vertices(glp_graph *G, int nadd);
*
* DESCRIPTION
*
* The routine glp_add_vertices adds nadd vertices to the specified
* graph. New vertices are always added to the end of the vertex list,
* so ordinal numbers of existing vertices remain unchanged.
*
* Being added each new vertex is isolated (has no incident arcs).
*
* RETURNS
*
* The routine glp_add_vertices returns an ordinal number of the first
* new vertex added to the graph. */
int glp_add_vertices(glp_graph *G, int nadd)
{ int i, nv_new;
if (nadd < 1)
xerror("glp_add_vertices: nadd = %d; invalid number of vertice"
"s\n", nadd);
if (nadd > NV_MAX - G->nv)
xerror("glp_add_vertices: nadd = %d; too many vertices\n",
nadd);
/* determine new number of vertices */
nv_new = G->nv + nadd;
/* increase the room, if necessary */
if (G->nv_max < nv_new)
{ glp_vertex **save = G->v;
while (G->nv_max < nv_new)
{ G->nv_max += G->nv_max;
xassert(G->nv_max > 0);
}
G->v = xcalloc(1+G->nv_max, sizeof(glp_vertex *));
memcpy(&G->v[1], &save[1], G->nv * sizeof(glp_vertex *));
xfree(save);
}
/* add new vertices to the end of the vertex list */
for (i = G->nv+1; i <= nv_new; i++)
{ glp_vertex *v;
G->v[i] = v = dmp_get_atom(G->pool, sizeof(glp_vertex));
v->i = i;
v->name = NULL;
v->entry = NULL;
if (G->v_size == 0)
v->data = NULL;
else
{ v->data = dmp_get_atom(G->pool, G->v_size);
memset(v->data, 0, G->v_size);
}
v->temp = NULL;
v->in = v->out = NULL;
}
/* set new number of vertices */
G->nv = nv_new;
/* return the ordinal number of the first vertex added */
return nv_new - nadd + 1;
}
void glp_set_vertex_name(glp_graph *G, int i, const char *name)
{ /* assign (change) vertex name */
glp_vertex *v;
if (!(1 <= i && i <= G->nv))
xerror("glp_set_vertex_name: i = %d; vertex number out of rang"
"e\n", i);
v = G->v[i];
if (v->name != NULL)
{ if (v->entry != NULL)
{ xassert(G->index != NULL);
avl_delete_node(G->index, v->entry);
v->entry = NULL;
}
dmp_free_atom(G->pool, v->name, strlen(v->name)+1);
v->name = NULL;
}
if (!(name == NULL || name[0] == '\0'))
{ int k;
for (k = 0; name[k] != '\0'; k++)
{ if (k == 256)
xerror("glp_set_vertex_name: i = %d; vertex name too lon"
"g\n", i);
if (iscntrl((unsigned char)name[k]))
xerror("glp_set_vertex_name: i = %d; vertex name contain"
"s invalid character(s)\n", i);
}
v->name = dmp_get_atom(G->pool, strlen(name)+1);
strcpy(v->name, name);
if (G->index != NULL)
{ xassert(v->entry == NULL);
v->entry = avl_insert_node(G->index, v->name);
avl_set_node_link(v->entry, v);
}
}
return;
}
/***********************************************************************
* NAME
*
* glp_add_arc - add new arc to graph
*
* SYNOPSIS
*
* glp_arc *glp_add_arc(glp_graph *G, int i, int j);
*
* DESCRIPTION
*
* The routine glp_add_arc adds a new arc to the specified graph.
*
* The parameters i and j specify the ordinal numbers of, resp., tail
* and head vertices of the arc. Note that self-loops and multiple arcs
* are allowed.
*
* RETURNS
*
* The routine glp_add_arc returns a pointer to the arc added. */
glp_arc *glp_add_arc(glp_graph *G, int i, int j)
{ glp_arc *a;
if (!(1 <= i && i <= G->nv))
xerror("glp_add_arc: i = %d; tail vertex number out of range\n"
, i);
if (!(1 <= j && j <= G->nv))
xerror("glp_add_arc: j = %d; head vertex number out of range\n"
, j);
if (G->na == NA_MAX)
xerror("glp_add_arc: too many arcs\n");
a = dmp_get_atom(G->pool, sizeof(glp_arc));
a->tail = G->v[i];
a->head = G->v[j];
if (G->a_size == 0)
a->data = NULL;
else
{ a->data = dmp_get_atom(G->pool, G->a_size);
memset(a->data, 0, G->a_size);
}
a->temp = NULL;
a->t_prev = NULL;
a->t_next = G->v[i]->out;
if (a->t_next != NULL) a->t_next->t_prev = a;
a->h_prev = NULL;
a->h_next = G->v[j]->in;
if (a->h_next != NULL) a->h_next->h_prev = a;
G->v[i]->out = G->v[j]->in = a;
G->na++;
return a;
}
/***********************************************************************
* NAME
*
* glp_del_vertices - delete vertices from graph
*
* SYNOPSIS
*
* void glp_del_vertices(glp_graph *G, int ndel, const int num[]);
*
* DESCRIPTION
*
* The routine glp_del_vertices deletes vertices along with all
* incident arcs from the specified graph. Ordinal numbers of vertices
* to be deleted should be placed in locations num[1], ..., num[ndel],
* ndel > 0.
*
* Note that deleting vertices involves changing ordinal numbers of
* other vertices remaining in the graph. New ordinal numbers of the
* remaining vertices are assigned under the assumption that the
* original order of vertices is not changed. */
void glp_del_vertices(glp_graph *G, int ndel, const int num[])
{ glp_vertex *v;
int i, k, nv_new;
/* scan the list of vertices to be deleted */
if (!(1 <= ndel && ndel <= G->nv))
xerror("glp_del_vertices: ndel = %d; invalid number of vertice"
"s\n", ndel);
for (k = 1; k <= ndel; k++)
{ /* take the number of vertex to be deleted */
i = num[k];
/* obtain pointer to i-th vertex */
if (!(1 <= i && i <= G->nv))
xerror("glp_del_vertices: num[%d] = %d; vertex number out o"
"f range\n", k, i);
v = G->v[i];
/* check that the vertex is not marked yet */
if (v->i == 0)
xerror("glp_del_vertices: num[%d] = %d; duplicate vertex nu"
"mbers not allowed\n", k, i);
/* erase symbolic name assigned to the vertex */
glp_set_vertex_name(G, i, NULL);
xassert(v->name == NULL);
xassert(v->entry == NULL);
/* free vertex data, if allocated */
if (v->data != NULL)
dmp_free_atom(G->pool, v->data, G->v_size);
/* delete all incoming arcs */
while (v->in != NULL)
glp_del_arc(G, v->in);
/* delete all outgoing arcs */
while (v->out != NULL)
glp_del_arc(G, v->out);
/* mark the vertex to be deleted */
v->i = 0;
}
/* delete all marked vertices from the vertex list */
nv_new = 0;
for (i = 1; i <= G->nv; i++)
{ /* obtain pointer to i-th vertex */
v = G->v[i];
/* check if the vertex is marked */
if (v->i == 0)
{ /* it is marked, delete it */
dmp_free_atom(G->pool, v, sizeof(glp_vertex));
}
else
{ /* it is not marked, keep it */
v->i = ++nv_new;
G->v[v->i] = v;
}
}
/* set new number of vertices in the graph */
G->nv = nv_new;
return;
}
/***********************************************************************
* NAME
*
* glp_del_arc - delete arc from graph
*
* SYNOPSIS
*
* void glp_del_arc(glp_graph *G, glp_arc *a);
*
* DESCRIPTION
*
* The routine glp_del_arc deletes an arc from the specified graph.
* The arc to be deleted must exist. */
void glp_del_arc(glp_graph *G, glp_arc *a)
{ /* some sanity checks */
xassert(G->na > 0);
xassert(1 <= a->tail->i && a->tail->i <= G->nv);
xassert(a->tail == G->v[a->tail->i]);
xassert(1 <= a->head->i && a->head->i <= G->nv);
xassert(a->head == G->v[a->head->i]);
/* remove the arc from the list of incoming arcs */
if (a->h_prev == NULL)
a->head->in = a->h_next;
else
a->h_prev->h_next = a->h_next;
if (a->h_next == NULL)
;
else
a->h_next->h_prev = a->h_prev;
/* remove the arc from the list of outgoing arcs */
if (a->t_prev == NULL)
a->tail->out = a->t_next;
else
a->t_prev->t_next = a->t_next;
if (a->t_next == NULL)
;
else
a->t_next->t_prev = a->t_prev;
/* free arc data, if allocated */
if (a->data != NULL)
dmp_free_atom(G->pool, a->data, G->a_size);
/* delete the arc from the graph */
dmp_free_atom(G->pool, a, sizeof(glp_arc));
G->na
return;
}
/***********************************************************************
* NAME
*
* glp_erase_graph - erase graph content
*
* SYNOPSIS
*
* void glp_erase_graph(glp_graph *G, int v_size, int a_size);
*
* DESCRIPTION
*
* The routine glp_erase_graph erases the content of the specified
* graph. The effect of this operation is the same as if the graph
* would be deleted with the routine glp_delete_graph and then created
* anew with the routine glp_create_graph, with exception that the
* handle (pointer) to the graph remains valid. */
static void delete_graph(glp_graph *G)
{ dmp_delete_pool(G->pool);
xfree(G->v);
if (G->index != NULL) avl_delete_tree(G->index);
return;
}
void glp_erase_graph(glp_graph *G, int v_size, int a_size)
{ if (!(0 <= v_size && v_size <= 256))
xerror("glp_erase_graph: v_size = %d; invalid size of vertex d"
"ata\n", v_size);
if (!(0 <= a_size && a_size <= 256))
xerror("glp_erase_graph: a_size = %d; invalid size of arc data"
"\n", a_size);
delete_graph(G);
create_graph(G, v_size, a_size);
return;
}
/***********************************************************************
* NAME
*
* glp_delete_graph - delete graph
*
* SYNOPSIS
*
* void glp_delete_graph(glp_graph *G);
*
* DESCRIPTION
*
* The routine glp_delete_graph deletes the specified graph and frees
* all the memory allocated to this program object. */
void glp_delete_graph(glp_graph *G)
{ delete_graph(G);
xfree(G);
return;
}
void glp_create_v_index(glp_graph *G)
{ /* create vertex name index */
glp_vertex *v;
int i;
if (G->index == NULL)
{ G->index = avl_create_tree(avl_strcmp, NULL);
for (i = 1; i <= G->nv; i++)
{ v = G->v[i];
xassert(v->entry == NULL);
if (v->name != NULL)
{ v->entry = avl_insert_node(G->index, v->name);
avl_set_node_link(v->entry, v);
}
}
}
return;
}
int glp_find_vertex(glp_graph *G, const char *name)
{ /* find vertex by its name */
AVLNODE *node;
int i = 0;
if (G->index == NULL)
xerror("glp_find_vertex: vertex name index does not exist\n");
if (!(name == NULL || name[0] == '\0' || strlen(name) > 255))
{ node = avl_find_node(G->index, name);
if (node != NULL)
i = ((glp_vertex *)avl_get_node_link(node))->i;
}
return i;
}
void glp_delete_v_index(glp_graph *G)
{ /* delete vertex name index */
int i;
if (G->index != NULL)
{ avl_delete_tree(G->index), G->index = NULL;
for (i = 1; i <= G->nv; i++) G->v[i]->entry = NULL;
}
return;
}
/***********************************************************************
* NAME
*
* glp_read_graph - read graph from plain text file
*
* SYNOPSIS
*
* int glp_read_graph(glp_graph *G, const char *fname);
*
* DESCRIPTION
*
* The routine glp_read_graph reads a graph from a plain text file.
*
* RETURNS
*
* If the operation was successful, the routine returns zero. Otherwise
* it prints an error message and returns non-zero. */
int glp_read_graph(glp_graph *G, const char *fname)
{ glp_data *data;
jmp_buf jump;
int nv, na, i, j, k, ret;
glp_erase_graph(G, G->v_size, G->a_size);
xprintf("Reading graph from `%s'...\n", fname);
data = glp_sdf_open_file(fname);
if (data == NULL)
{ ret = 1;
goto done;
}
if (setjmp(jump))
{ ret = 1;
goto done;
}
glp_sdf_set_jump(data, jump);
nv = glp_sdf_read_int(data);
if (nv < 0)
glp_sdf_error(data, "invalid number of vertices\n");
na = glp_sdf_read_int(data);
if (na < 0)
glp_sdf_error(data, "invalid number of arcs\n");
xprintf("Graph has %d vert%s and %d arc%s\n",
nv, nv == 1 ? "ex" : "ices", na, na == 1 ? "" : "s");
if (nv > 0) glp_add_vertices(G, nv);
for (k = 1; k <= na; k++)
{ i = glp_sdf_read_int(data);
if (!(1 <= i && i <= nv))
glp_sdf_error(data, "tail vertex number out of range\n");
j = glp_sdf_read_int(data);
if (!(1 <= j && j <= nv))
glp_sdf_error(data, "head vertex number out of range\n");
glp_add_arc(G, i, j);
}
xprintf("%d lines were read\n", glp_sdf_line(data));
ret = 0;
done: if (data != NULL) glp_sdf_close_file(data);
return ret;
}
/***********************************************************************
* NAME
*
* glp_write_graph - write graph to plain text file
*
* SYNOPSIS
*
* int glp_write_graph(glp_graph *G, const char *fname).
*
* DESCRIPTION
*
* The routine glp_write_graph writes the specified graph to a plain
* text file.
*
* RETURNS
*
* If the operation was successful, the routine returns zero. Otherwise
* it prints an error message and returns non-zero. */
int glp_write_graph(glp_graph *G, const char *fname)
{ XFILE *fp;
glp_vertex *v;
glp_arc *a;
int i, count, ret;
xprintf("Writing graph to `%s'...\n", fname);
fp = xfopen(fname, "w"), count = 0;
if (fp == NULL)
{ xprintf("Unable to create `%s' - %s\n", fname, xerrmsg());
ret = 1;
goto done;
}
xfprintf(fp, "%d %d\n", G->nv, G->na), count++;
for (i = 1; i <= G->nv; i++)
{ v = G->v[i];
for (a = v->out; a != NULL; a = a->t_next)
xfprintf(fp, "%d %d\n", a->tail->i, a->head->i), count++;
}
xfflush(fp);
if (xferror(fp))
{ xprintf("Write error on `%s' - %s\n", fname, xerrmsg());
ret = 1;
goto done;
}
xprintf("%d lines were written\n", count);
ret = 0;
done: if (fp != NULL) xfclose(fp);
return ret;
}
/* eof */
|
#pragma once
#ifndef <API key>
#define <API key>
class Mesh;
class SMSH_File;
struct MeshCPUData;
struct MeshNodeData;
struct MeshRequest;
namespace Engine::priv {
class PublicMesh;
class MeshImportedData;
class MeshLoader;
class <API key>;
class <API key>;
};
#include <serenity/resources/mesh/animation/AnimationData.h>
#include <serenity/system/Macros.h>
#include <serenity/utils/Utils.h>
namespace Engine::priv {
class MeshSkeleton final {
friend class ::Mesh;
friend struct ::MeshCPUData;
friend class ::SMSH_File;
friend class Engine::priv::MeshLoader;
friend class Engine::priv::AnimationData;
friend class Engine::priv::PublicMesh;
friend class Engine::priv::<API key>;
friend class Engine::priv::<API key>;
public:
using AnimationDataMap = Engine::<API key><std::string, uint16_t>;
private:
AnimationDataMap m_AnimationMapping; //maps an animation name to its data
glm::mat4 <API key> = glm::mat4{ 1.0f };
std::vector<BoneInfo> m_BoneInfo;
std::vector<AnimationData> m_AnimationData;
void clear() noexcept {
<API key> = glm::mat4{ 1.0f };
}
template<typename ... ARGS>
int <API key>(std::string_view animName, ARGS&&... args) {
if (hasAnimation(animName)) {
return -1;
}
const uint16_t index = static_cast<uint16_t>(m_AnimationData.size());
m_AnimationMapping.emplace(std::piecewise_construct, std::forward_as_tuple(animName), std::forward_as_tuple(index));
m_AnimationData.emplace_back(std::forward<ARGS>(args)...);
<API key>("Added animation: " << animName);
return index;
}
public:
MeshSkeleton() = default;
MeshSkeleton(const aiMesh&, const aiScene&, MeshRequest&, Engine::priv::MeshImportedData&);
MeshSkeleton(const MeshSkeleton&) = delete;
MeshSkeleton& operator=(const MeshSkeleton&) = delete;
MeshSkeleton(MeshSkeleton&&) noexcept = default;
MeshSkeleton& operator=(MeshSkeleton&&) = default;
[[nodiscard]] inline AnimationDataMap& getAnimationData() noexcept { return m_AnimationMapping; }
[[nodiscard]] inline uint16_t numBones() const noexcept { return (uint16_t)m_BoneInfo.size(); }
[[nodiscard]] inline uint32_t numAnimations() const noexcept { return (uint32_t)m_AnimationData.size(); }
[[nodiscard]] inline bool hasAnimation(std::string_view animName) const noexcept { return m_AnimationMapping.contains(animName); }
inline void setBoneOffsetMatrix(uint16_t boneIdx, glm::mat4&& matrix) noexcept { m_BoneInfo[boneIdx].BoneOffset = std::move(matrix); }
inline uint16_t getAnimationIndex(std::string_view animName) const noexcept { return m_AnimationMapping.find(animName)->second; }
int addAnimation(std::string_view animName, const aiAnimation& anim, MeshRequest& request) {
return <API key>(animName, anim, request);
}
int addAnimation(std::string_view animName, AnimationData&& animationData) {
return <API key>(animName, std::move(animationData));
}
};
};
#endif
|
package com.mortensickel.measemulator;
import com.google.android.gms.common.api.*;
import android.content.Context;
import android.text.*;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.animation.*;
import android.app.*;
import android.os.*;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.*;
import android.view.View.*;
import android.location.Location;
import android.util.Log;
import com.google.android.gms.location.*;
import com.google.android.gms.common.*;
import android.preference.*;
import android.view.*;
import android.content.*;
import android.net.Uri;
// import org.apache.http.impl.execchain.*;
// Todo over a certain treshold, change calibration factor
// TODO settable calibration factor
// TODO finish icons
// DONE location
// DONE input background and source. Calculate activity from distance
// TODO Use distribution map
// DONE add settings menu
// TODO generic skin
// TODO handle pause and shutdown
public class MainActivity extends Activity
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.<API key>,LocationListener
{
/*
AUTOMESS:
0.44 pps = 0.1uSv/h
ca 16. pulser pr nSv
*/
boolean poweron=false;
long shutdowntime=0;
long meastime;
TextView tvTime,tvPulsedata, tvPause,tvAct, tvDoserate;
long starttime = 0;
public long pulses=0;
Integer mode=0;
final Integer MAXMODE=3;
final int MODE_OFF=0;
final int MODE_MOMENTANDOSE=1;
final int MODE_DOSERATE=2;
final int MODE_DOSE=3;
public final String TAG="measem";
double calibration=4.4;
public Integer sourceact=1;
protected long lastpulses=0;
public boolean gpsenabled = true;
public Context context;
public Integer gpsinterval=2000;
private GoogleApiClient gac;
private Location here,there;
protected LocationRequest loreq;
private LinearLayout llDebuginfo;
private Double background=0.0;
private float sourcestrength=1000;
private boolean showDebug=false;
private final String PULSES="pulses";
@Override
public void onConnectionFailed(ConnectionResult p1)
{
// TODO: Implement this method
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putLong(PULSES,pulses);
//savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void <API key>(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.<API key>(savedInstanceState);
// Restore state members from saved instance
pulses = savedInstanceState.getLong(PULSES);
//mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL);
}
protected void <API key>(){
loreq = new LocationRequest();
loreq.setInterval(gpsinterval);
loreq.setFastestInterval(100);
loreq.setPriority(LocationRequest.<API key>);
}
protected void <API key>(){
if(loreq==null){
<API key>();
}
LocationServices.FusedLocationApi.<API key>(gac,loreq,this);
}
public void ConnectionCallbacks(){
}
@Override
public void onLocationChanged(Location p1)
{
here=p1;
double distance=here.distanceTo(there);
sourceact=(int)Math.round(background+sourcestrength/(distance*distance));
tvAct.setText(String.valueOf(sourceact));
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// TODO: Implement this method
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean <API key>(MenuItem item)
{
switch (item.getItemId()){
case R.id.mnuSettings:
Intent intent=new Intent();
intent.setClass(MainActivity.this,<API key>.class);
<API key>(intent,0);
return true;
case R.id.mnuSaveLoc:
saveLocation();
return true;
case R.id.mnuShowLoc:
showLocation();
return true;
}
return super.<API key>(item);
}
protected void showLocation(){
String lat=String.valueOf(there.getLatitude());
String lon=String.valueOf(there.getLongitude());
Toast.makeText(<API key>(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show();
try {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q=loc:"+lat+","+lon));
startActivity(myIntent);
} catch (<API key> e) {
Toast.makeText(this, "No application can handle this request.",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
protected void saveLocation(){
Location LastLocation = LocationServices.FusedLocationApi.getLastLocation(
gac);
if (LastLocation != null) {
String lat=String.valueOf(LastLocation.getLatitude());
String lon=String.valueOf(LastLocation.getLongitude());
Toast.makeText(<API key>(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show();
there=LastLocation;
SharedPreferences sp = PreferenceManager.<API key>(this);
//SharedPreferences sp=this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor ed=sp.edit();
ed.putString("Latitude",lat);
ed.putString("Longitude",lon);
ed.apply();
ed.commit();
}else{
Toast.makeText(<API key>(),getString(R.string.CouldNotGetLocation), Toast.LENGTH_LONG).show();
}
}
@Override
public void onConnected(Bundle p1)
{
Location loc = LocationServices.FusedLocationApi.getLastLocation(gac);
if(loc != null){
here=loc;
}
}
@Override
public void <API key>(int p1)
{
// TODO: Implement this method
}
protected void onStart(){
gac.connect();
super.onStart();
}
protected void onStop(){
gac.disconnect();
super.onStop();
}
//this posts a message to the main thread from our timertask
//and updates the textfield
final Handler h = new Handler(new Callback() {
@Override
public boolean handleMessage(Message msg) {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
if(seconds>0){
double display=0;
if( mode==MODE_MOMENTANDOSE){
if (lastpulses==0 || (lastpulses>pulses)){
display=0;
}else{
display=((pulses-lastpulses)/calibration);
}
lastpulses=pulses;
}
if (mode==MODE_DOSERATE){
display=(double)pulses/(double)seconds/calibration;
}
if (mode==MODE_DOSE){
display=(double)pulses/calibration/3600;
}
tvDoserate.setText(String.format("%.2f",display));
}
if(showDebug){
int minutes = seconds / 60;
seconds = seconds % 60;
tvTime.setText(String.format("%d:%02d", minutes, seconds));
}
return false;
}
});
//runs without timer - reposting itself after a random interval
Handler h2 = new Handler();
Runnable run = new Runnable() {
@Override
public void run() {
int n=1;
long pause=pause(getInterval());
h2.postDelayed(run,pause);
if(showDebug){
tvPause.setText(String.format("%d",pause));
}
receivepulse(n);
}
};
public Integer getInterval(){
Integer act=sourceact;
if(act==0){
act=1;
}
Integer interval=5000/act;
if (interval==0){
interval=1;
}
return(interval);
}
public long pause(Integer interval){
double pause=interval;
if(interval > 5){
Random rng=new Random();
pause=rng.nextGaussian();
Integer sd=interval/4;
pause=pause*sd+interval;
if(pause<0){pause=0;}
}
return((long)pause);
}
public void receivepulse(int n){
LinearLayout myText = (LinearLayout) findViewById(R.id.llLed );
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(20); //You can manage the time of the blink with this parameter
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(0);
myText.startAnimation(anim);
pulses=pulses+1;
Double sdev=Math.sqrt(pulses);
if(showDebug){
tvPulsedata.setText(String.format("%d - %.1f - %.0f %%",pulses,sdev,sdev/pulses*100));
}
}
//tells handler to send a message
class firstTask extends TimerTask {
@Override
public void run() {
h.sendEmptyMessage(0);
}
}
@Override
protected void onResume()
{
// TODO: Implement this method
super.onResume();
SharedPreferences sharedPref = PreferenceManager.<API key>(this);
// lowprobCutoff = (double)sharedPref.getFloat("<API key>", 1)/100;
readPrefs();
//XlowprobCutoff=
}
private void readPrefs(){
SharedPreferences sharedPref = PreferenceManager.<API key>(this);
String ret=sharedPref.getString("Latitude", "10");
Double lat= Double.parseDouble(ret);
ret=sharedPref.getString("Longitude", "60");
Double lon= Double.parseDouble(ret);
there.setLatitude(lat);
there.setLongitude(lon);
ret=sharedPref.getString("backgroundValue", "1");
background= Double.parseDouble(ret)/200;
showDebug=sharedPref.getBoolean("showDebug", false);
debugVisible(showDebug);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
readPrefs();
}
Timer timer = new Timer();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context=this;
loadPref(context);
/*SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
double lat = getResources().get;
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
// getString(R.string.preference_file_key), Context.MODE_PRIVATE);
*/
there = new Location("dummyprovider");
there.setLatitude(59.948509);
there.setLongitude(10.602627);
llDebuginfo=(LinearLayout)findViewById(R.id.llDebuginfo);
llDebuginfo.setVisibility(View.GONE);
gac=new GoogleApiClient.Builder(this).<API key>(this).<API key>(this).addApi(LocationServices.API).build();
tvTime = (TextView)findViewById(R.id.tvTime);
tvPulsedata = (TextView)findViewById(R.id.tvPulsedata);
tvPause = (TextView)findViewById(R.id.tvPause);
tvDoserate = (TextView)findViewById(R.id.etDoserate);
tvAct=(EditText)findViewById(R.id.activity);
tvAct.<API key>(activityTW);
switchMode(mode);
Button b = (Button)findViewById(R.id.btPower);
b.setOnClickListener(onOffClick);
b=(Button)findViewById(R.id.btMode);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
modechange(v);
}
});
b=(Button)findViewById(R.id.btLight);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDebug=!showDebug;
}
});
}
@Override
public void onPause() {
super.onPause();
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
}
TextWatcher activityTW = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
String act=tvAct.getText().toString();
if(act.equals("")){act="1";}
sourceact=Integer.parseInt(act);
// TODO better errorchecking.
// TODO disable if using geolocation
}};
View.OnClickListener onOffClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(poweron){
long now=System.currentTimeMillis();
if(now> shutdowntime && now < shutdowntime+500){
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
pulses=0;
poweron=false;
mode=MODE_OFF;
switchMode(mode);
}
shutdowntime = System.currentTimeMillis()+500;
}else{
shutdowntime=0;
starttime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new firstTask(), 0,500);
<API key>();
h2.postDelayed(run, pause(getInterval()));
mode=1;
switchMode(mode);
poweron=true;
}
}
};
private void debugVisible(Boolean show){
View debug=findViewById(R.id.llDebuginfo);
if(show){
debug.setVisibility(View.VISIBLE);
}else{
debug.setVisibility(View.GONE);
}
}
public void loadPref(Context ctx){
//SharedPreferences shpref=PreferenceManager.<API key>(ctx);
PreferenceManager.setDefaultValues(ctx, R.xml.preferences, false);
}
public void modechange(View v){
if(mode > 0){
mode++;
if (mode > MAXMODE){
mode=1;
}
switchMode(mode);}
}
public void switchMode(int mode){
int unit=0;
switch(mode){
case MODE_MOMENTANDOSE:
unit= R.string.ugyh;
break;
case MODE_DOSERATE:
unit = R.string.ugyhint;
break;
case MODE_DOSE:
unit = R.string.ugy;
break;
case MODE_OFF:
unit= R.string.blank;
tvDoserate.setText("");
break;
}
TextView tv=(TextView)findViewById(R.id.etUnit);
tv.setText(unit);
}
}
|
<?php
// Esercizio: un numero che si dimezza sempre
header('Content-Type: text/plain');
ini_set('display_errors', true); // MAI in produzione!!!
ini_set('html_errors', 0);
/**
* Questa classe continua a dividere
* il suo stato interno per un valore dato.
*/
class invert
{
/**
* Il valore corrente
* @var integer
*/
public $val = 1;
/**
* Il divisore
* @var integer
*/
protected $_divisor = 3;
/**
* Esegue la divisione e restituisce il risultato
* @return integer
*/
public function div()
{
$this->val = $this->val / $this->_divisor;
return $this->val;
}
/**
* Imposta il valore del divisore
* @param integer $divisor
* @return void
*/
public function setDivisor($divisor)
{
if ($divisor) {
$this->_divisor = $divisor;
} else {
// Prendo dei provvedimenti
}
}
}
$sempreMeno = new invert;
while ($sempreMeno->val > 1e-5) {
echo $sempreMeno->div(), PHP_EOL;
}
// Tento di impostare un nuovo divisore...
$sempreMeno->_divisor = 2;
// ...ma devo usare la funzione
$sempreMeno->setDivisor(2);
echo $sempreMeno->div(), PHP_EOL;
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
abstract class CI_DB_utility {
/**
* Database object
*
* @var object
*/
protected $db;
/**
* List databases statement
*
* @var string
*/
protected $_list_databases = FALSE;
/**
* OPTIMIZE TABLE statement
*
* @var string
*/
protected $_optimize_table = FALSE;
/**
* REPAIR TABLE statement
*
* @var string
*/
protected $_repair_table = FALSE;
/**
* Class constructor
*
* @param object &$db Database object
* @return void
*/
public function __construct(&$db)
{
$this->db =& $db;
log_message('debug', 'Database Utility Class Initialized');
}
/**
* List databases
*
* @return array
*/
public function list_databases()
{
// Is there a cached result?
if (isset($this->db->data_cache['db_names']))
{
return $this->db->data_cache['db_names'];
}
elseif ($this->_list_databases === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('<API key>') : FALSE;
}
$this->db->data_cache['db_names'] = array();
$query = $this->db->query($this->_list_databases);
if ($query === FALSE)
{
return $this->db->data_cache['db_names'];
}
for ($i = 0, $query = $query->result_array(), $c = count($query); $i < $c; $i++)
{
$this->db->data_cache['db_names'][] = current($query[$i]);
}
return $this->db->data_cache['db_names'];
}
/**
* Determine if a particular database exists
*
* @param string $database_name
* @return bool
*/
public function database_exists($database_name)
{
return in_array($database_name, $this->list_databases());
}
/**
* Optimize Table
*
* @param string $table_name
* @return mixed
*/
public function optimize_table($table_name)
{
if ($this->_optimize_table === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('<API key>') : FALSE;
}
$query = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name)));
if ($query !== FALSE)
{
$query = $query->result_array();
return current($query);
}
return FALSE;
}
/**
* Optimize Database
*
* @return mixed
*/
public function optimize_database()
{
if ($this->_optimize_table === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('<API key>') : FALSE;
}
$result = array();
foreach ($this->db->list_tables() as $table_name)
{
$res = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name)));
if (is_bool($res))
{
return $res;
}
// Build the result array...
$res = $res->result_array();
$res = current($res);
$key = str_replace($this->db->database.'.', '', current($res));
$keys = array_keys($res);
unset($res[$keys[0]]);
$result[$key] = $res;
}
return $result;
}
/**
* Repair Table
*
* @param string $table_name
* @return mixed
*/
public function repair_table($table_name)
{
if ($this->_repair_table === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('<API key>') : FALSE;
}
$query = $this->db->query(sprintf($this->_repair_table, $this->db->escape_identifiers($table_name)));
if (is_bool($query))
{
return $query;
}
$query = $query->result_array();
return current($query);
}
/**
* Generate CSV from a query result object
*
* @param object $query Query result object
* @param string $delim Delimiter (default: ,)
* @param string $newline Newline character (default: \n)
* @param string $enclosure Enclosure (default: ")
* @return string
*/
public function csv_from_result($query, $delim = ',', $newline = "\n", $enclosure = '"')
{
if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
{
show_error('You must submit a valid result object');
}
$out = '';
// First generate the headings from the table column names
foreach ($query->list_fields() as $name)
{
$out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
}
$out = substr(rtrim($out), 0, -strlen($delim)).$newline;
// Next blast through the result array and build out the rows
while ($row = $query->unbuffered_row('array'))
{
foreach ($row as $item)
{
$out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
}
$out = substr(rtrim($out), 0, -strlen($delim)).$newline;
}
return $out;
}
/**
* Generate XML data from a query result object
*
* @param object $query Query result object
* @param array $params Any preferences
* @return string
*/
public function xml_from_result($query, $params = array())
{
if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
{
show_error('You must submit a valid result object');
}
// Set our default values
foreach (array('root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t") as $key => $val)
{
if ( ! isset($params[$key]))
{
$params[$key] = $val;
}
}
// Create variables for convenience
extract($params);
// Load the xml helper
get_instance()->load->helper('xml');
// Generate the result
$xml = '<'.$root.'>'.$newline;
while ($row = $query->unbuffered_row())
{
$xml .= $tab.'<'.$element.'>'.$newline;
foreach ($row as $key => $val)
{
$xml .= $tab.$tab.'<'.$key.'>'.xml_convert($val).'</'.$key.'>'.$newline;
}
$xml .= $tab.'</'.$element.'>'.$newline;
}
return $xml.'</'.$root.'>'.$newline;
}
/**
* Database Backup
*
* @param array $params
* @return void
*/
public function backup($params = array())
{
// If the parameters have not been submitted as an
// array then we know that it is simply the table
// name, which is a valid short cut.
if (is_string($params))
{
$params = array('tables' => $params);
}
// Set up our default preferences
$prefs = array(
'tables' => array(),
'ignore' => array(),
'filename' => '',
'format' => 'gzip', // gzip, zip, txt
'add_drop' => TRUE,
'add_insert' => TRUE,
'newline' => "\n",
'foreign_key_checks' => TRUE
);
// Did the user submit any preferences? If so set them....
if (count($params) > 0)
{
foreach ($prefs as $key => $val)
{
if (isset($params[$key]))
{
$prefs[$key] = $params[$key];
}
}
}
// Are we backing up a complete database or individual tables?
// If no table names were submitted we'll fetch the entire table list
if (count($prefs['tables']) === 0)
{
$prefs['tables'] = $this->db->list_tables();
}
// Validate the format
if ( ! in_array($prefs['format'], array('gzip', 'zip', 'txt'), TRUE))
{
$prefs['format'] = 'txt';
}
// Is the encoder supported? If not, we'll either issue an
// error or use plain text depending on the debug settings
if (($prefs['format'] === 'gzip' && ! @function_exists('gzencode'))
OR ($prefs['format'] === 'zip' && ! @function_exists('gzcompress')))
{
if ($this->db->db_debug)
{
return $this->db->display_error('<API key>');
}
$prefs['format'] = 'txt';
}
// Was a Zip file requested?
if ($prefs['format'] === 'zip')
{
// Set the filename if not provided (only needed with Zip files)
if ($prefs['filename'] === '')
{
$prefs['filename'] = (count($prefs['tables']) === 1 ? $prefs['tables'] : $this->db->database)
.date('Y-m-d_H-i', time()).'.sql';
}
else
{
// If they included the .zip file extension we'll remove it
if (preg_match('|.+?\.zip$|', $prefs['filename']))
{
$prefs['filename'] = str_replace('.zip', '', $prefs['filename']);
}
// Tack on the ".sql" file extension if needed
if ( ! preg_match('|.+?\.sql$|', $prefs['filename']))
{
$prefs['filename'] .= '.sql';
}
}
// Load the Zip class and output it
$CI =& get_instance();
$CI->load->library('zip');
$CI->zip->add_data($prefs['filename'], $this->_backup($prefs));
return $CI->zip->get_zip();
}
elseif ($prefs['format'] === 'txt') // Was a text file requested?
{
return $this->_backup($prefs);
}
elseif ($prefs['format'] === 'gzip') // Was a Gzip file requested?
{
return gzencode($this->_backup($prefs));
}
return;
}
}
/* End of file DB_utility.php */
/* Location: ./system/database/DB_utility.php */
|
from mercurial import cmdutil
_hgignore_content = """\
syntax: glob
*~
*.pyc
*.pyo
*.bak
cache/*
databases/*
sessions/*
errors/*
"""
def commit():
app = request.args[0]
path = apath(app, r=request)
uio = ui.ui()
uio.quiet = True
if not os.environ.get('HGUSER') and not uio.config("ui", "username"):
os.environ['HGUSER'] = 'web2py@localhost'
try:
r = hg.repository(ui=uio, path=path)
except:
r = hg.repository(ui=uio, path=path, create=True)
hgignore = os.path.join(path, '.hgignore')
if not os.path.exists(hgignore):
open(hgignore, 'w').write(_hgignore_content)
form = FORM('Comment:',INPUT(_name='comment',requires=IS_NOT_EMPTY()),
INPUT(_type='submit',_value='Commit'))
if form.accepts(request.vars,session):
oldid = r[r.lookup('.')]
cmdutil.addremove(r)
r.commit(text=form.vars.comment)
if r[r.lookup('.')] == oldid:
response.flash = 'no changes'
files = r[r.lookup('.')].files()
return dict(form=form,files=TABLE(*[TR(file) for file in files]),repo=r)
|
package cz.geokuk.core.napoveda;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.net.<API key>;
import java.net.URL;
import cz.geokuk.core.program.FConst;
import cz.geokuk.framework.Action0;
import cz.geokuk.util.process.BrowserOpener;
/**
* @author Martin Veverka
*
*/
public class ZadatProblemAction extends Action0 {
private static final long serialVersionUID = -<API key>;
/**
* @param aBoard
*/
public ZadatProblemAction() {
super("Zadat problém ...");
putValue(SHORT_DESCRIPTION, "Zobrazí stránku na code.google.com, která umožní zadat chybu v Geokuku nebo požadavek na novou funkcionalitu.");
putValue(MNEMONIC_KEY, KeyEvent.VK_P);
}
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(final ActionEvent aE) {
try {
BrowserOpener.displayURL(new URL(FConst.POST_PROBLEM_URL));
} catch (final <API key> e) {
throw new RuntimeException(e);
}
}
}
|
package instance;
import java.util.ArrayList;
public class Parser
{
private ArrayList<ArrayList<String>> m_relationals;
private ArrayList<String[]> m_equalities;
int m_pos;
public Parser()
{
m_relationals = new ArrayList<ArrayList<String>>();
m_equalities = new ArrayList<String[]>();
m_pos=0;
}
public void flush()
{
m_pos = 0;
m_relationals.clear();
m_equalities.clear();
}
public boolean <API key>(char c)
{
return ((c>='A' && c<='Z') ||
(c>='0' && c<='9') ||
(c=='_'));
}
public boolean charIsValidForTerm(char c)
{
return ((c>='a' && c<='z') ||
(c>='0' && c<='9') ||
(c=='_') ||
(c=='.') );
}
public ArrayList<String> parseAtom(String line)
{
ArrayList<String> list = new ArrayList<String>();
String relation="";
while (m_pos<line.length())
{
if (<API key>(line.charAt(m_pos)))
{
relation+=line.charAt(m_pos);
m_pos++;
}
else if (line.charAt(m_pos)=='(')
{
m_pos++;
list.add(relation);
parseTerms(line, list);
return list;
}
else
{
m_pos++;
}
}
return null;
}
public void parseTerms(String line, ArrayList<String> list)
{
while (m_pos<line.length())
{
if (line.charAt(m_pos) == ')')
{
m_pos++;
return;
}
else if (!charIsValidForTerm(line.charAt(m_pos)))
m_pos++;
else
{
String term=parseSingleTerm(line);
list.add(term);
}
}
}
public String parseSingleTerm(String line)
{
String term="";
while (m_pos<line.length() && charIsValidForTerm(line.charAt(m_pos)))
{
term+=line.charAt(m_pos);
m_pos++;
}
return term;
}
public void parseRelationals(String line)
{
m_pos = 0;
while (m_pos<line.length())
{
if (line.charAt(m_pos)<'A' || line.charAt(m_pos)>'Z')
m_pos++;
else
{
ArrayList<String> relStr = parseAtom(line);
m_relationals.add(relStr);
}
}
}
public void parseEqualities(String line)
{
m_pos = 0;
while (m_pos<line.length())
{
if (!charIsValidForTerm(line.charAt(m_pos)))
m_pos++;
else parseEquality(line);
}
}
public void parseEquality(String line)
{
String[] terms=new String[2];
terms[0] = parseSingleTerm(line);
while (m_pos<line.length() && !charIsValidForTerm(line.charAt(m_pos)))
m_pos++;
terms[1] = parseSingleTerm(line);
m_equalities.add(terms);
}
public ArrayList<String[]> getEqualities()
{
return m_equalities;
}
public ArrayList<ArrayList<String>> getRelationals()
{
return m_relationals;
}
public ArrayList<String> parseProvenance(String line)
{
ArrayList<String> provList = new ArrayList<String>();
while (m_pos < line.length())
{
while (!charIsValidForTerm(line.charAt(m_pos)))
m_pos++;
String term = parseSingleTerm(line);
if (!(term.equals("")))
{
provList.add(term);
}
}
return provList;
}
}
|
(function() {
'use strict';
angular
.module('app.grid')
.service('<API key>', <API key>)
.service('GridUtils',GridUtils)
.factory('GridFactory',GridFactory)
;
GridFactory.$inject = ['modelNode','$q','$filter'];
function GridFactory(modelNode,$q,$filter) {
return {
buildGrid: function (option) {
return new Grid(option,modelNode,$q,$filter);
}
}
}
function Grid(option,modelNode,$q,$filter) {
var self = this;
this.page = angular.extend({size: 9, no: 1}, option.page);
this.sort = {
column: option.sortColumn || '_id',
direction: option.sortDirection ||-1,
toggle: function (column) {
if (column.sortable) {
if (this.column === column.name) {
this.direction = -this.direction || -1;
} else {
this.column = column.name;
this.direction = -1;
}
self.paging();
}
}
};
this.searchForm = option.searchForm;
this.rows = [];
this.rawData = [];
this.modelling = false;
this.model = option.model;
if (angular.isString(this.model)) {
this.model = modelNode.services[this.model];
}
if (!this.model)
this.model = angular.noop;
var promise;
if (angular.isFunction(this.model)) {
this.model = this.model();
}
promise = $q.when(this.model).then(function (ret) {
if (angular.isArray(ret)) {
self.rawData = ret;
}
else {
self.modelling = true;
}
self.setData = setData;
self.query = query;
self.paging = paging;
return self;
});
return promise;
function setData(data) {
self.rawData = data;
}
function query(param) {
var queryParam = angular.extend({}, self.searchForm, param);
if (self.modelling) {
self.rows = self.model.page(self.page, queryParam, null, (self.sort.direction > 0 ? '' : '-') + self.sort.column);
//totals
self.model.totals(queryParam).$promise.then(function (ret) {
self.page.totals = ret.totals;
});
}
else {
if (self.rawData)
self.rows = $filter('filter')(self.rawData, queryParam);
}
}
function paging() {
if (this.modelling) {
this.query();
}
}
}
<API key>.$inject = ['Utils'];
function <API key>(Utils) {
this.query = query;
this.find = find;
this.one = one;
this.save = save;
this.update = update;
this.remove = remove;
this._demoData_ = [];
function query(refresh) {
refresh = this._demoData_.length == 0 || refresh;
if (refresh) {
this._demoData_.length = 0;
var MAX_NUM = 10 * 50;
for (var i = 0; i < MAX_NUM; ++i) {
var id = Utils.rand(0, MAX_NUM);
this._demoData_.push({
id: i + 1,
name: 'Name' + id,
followers: Utils.rand(0, 100 * 1000 * 1000),
birthday: moment().subtract(Utils.rand(365, 365 * 50), 'day').toDate(),
summary: '' + i,
income: Utils.rand(1000, 100000)
});
}
}
return this._demoData_;
}
function one(properties) {
return _.findWhere(this._demoData_, properties);
}
function find(id) {
return _.find(this._demoData_, function (item) {
return item.id == id;
});
}
$resourcesave
function save(data) {
this._demoData_.push(_.defaults(data, {}));
//if (id != 'new') {
// var dest = _.bind(find, this, id);
// _.extend(dest, data);
//else {
}
function update(id,data){
var dest = _.bind(find, this, id);
_.extend(dest, data);
}
function remove(ids) {
console.log(this._demoData_.length);
this._demoData_ = _.reject(this._demoData_, function (item) {
return _.contains(ids, item.id);
});
console.log(this._demoData_.length);
}
}
GridUtils.$inject = ['$filter','ViewUtils'];
function GridUtils($filter,ViewUtils) {
return {
paging: paging,
totals: totals,
hide: hide,
width: width,
toggleOrderClass: toggleOrderClass,
noResultsColspan: noResultsColspan,
revertNumber: revertNumber,
calcAge: calcAge,
formatter: formatter,
populateFilter: populateFilter,
boolFilter: boolFilter,
diFilter: diFilter,
repeatInfoCombo: repeatInfoCombo,
orFilter: orFilter
};
function paging(items, vm) {
if (!items)
return [];
if(vm.serverPaging){
vm.paged = items;
}
else{
var offset = (vm.page.no - 1) * vm.page.size;
vm.paged = items.slice(offset, offset + vm.page.size);
/totals
vm.page.totals = items.length;
}
return vm.paged;
}
function totals(items,filter,vm) {
if (!items)
return 0;
if (vm.serverPaging) {
return vm.page.totals;
}
else {
return items.length || 0
}
}
function hide(column) {
if (!column)
return true;
return column.hidden === true;
}
function width(column) {
if (!column)
return 0;
return column.width || 100;
}
function toggleOrderClass(direction) {
if (direction === -1)
return "<API key>";
else
return "<API key>";
}
function noResultsColspan(vm) {
if (!vm || !vm.columns)
return 1;
return 1 + vm.columns.length - _.where(vm.columns, {hidden: true}).length;
}
function revertNumber(num,notConvert) {
if (num && !notConvert) {
return -num;
}
return num;
}
function calcAge(rowValue) {
return ViewUtils.age(rowValue)
}
function formatter(rowValue, columnName, columns) {
var one = _.findWhere(columns, {name: columnName});
if(one && !one.hidden) {
if (one.formatterData) {
if(_.isArray(rowValue)){
return _.map(rowValue,function(o){
return one.formatterData[o];
});
}
else{
return one.formatterData[rowValue];
}
}
}
return rowValue;
}
function populateFilter(rowValue, key) {
key = key || 'name';
if(_.isArray(rowValue)){
return _.map(rowValue,function(o){
console.log(o);
return ViewUtils.getPropery(o, key);
});
}
else{
return ViewUtils.getPropery(o, key);
}
return rowValue;
}
function boolFilter(rowValue){
return {"1": "", "0": "", "true": "", "false": ""}[rowValue];
}
function diFilter(rowValue,di) {
if (_.isArray(rowValue)) {
return _.map(rowValue, function (o) {
return di[o] || (_.findWhere(di, {value: rowValue}) || {}).name;
});
}
else {
return di[rowValue] || (_.findWhere(di, {value: rowValue}) || {}).name;
}
}
function repeatInfoCombo(repeatValues, repeat_start) {
if (_.isArray(repeatValues) && repeatValues.length > 0) {
return _.map(repeatValues, function (r) {
return r + repeat_start;
}).join('\r\n');
} else {
return repeat_start;
}
}
/**
* AngularJS default filter with the following expression:
* "person in people | filter: {name: $select.search, age: $select.search}"
* performs a AND between 'name: $select.search' and 'age: $select.search'.
* We want to perform a OR.
*/
function orFilter(items, props) {
var out = [];
if (_.isArray(items)) {
_.each(items,function (item) {
var itemMatches = false;
var keys = Object.keys(props);
for (var i = 0; i < keys.length; i++) {
var prop = keys[i];
var text = props[prop].toLowerCase();
if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
itemMatches = true;
break;
}
}
if (itemMatches) {
out.push(item);
}
});
} else {
// Let the output be the input untouched
out = items;
}
return out;
};
}
})();
|
package com.test.ipetrov.start;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.<API key>;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.<API key>;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@<API key>
@EnableWebMvc
@ComponentScan(basePackages = {"com.test.ipetrov.configuration",
"com.test.ipetrov.portal"})
@<API key>(basePackages = "com.test.ipetrov")
public class Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Application.class, args);
}
}
|
import { Pipeline, Step } from '@ephox/agar';
import { Arr } from '@ephox/katamari';
import { LegacyUnit } from '@ephox/mcagar';
import Serializer from 'tinymce/core/api/dom/Serializer';
import DOMUtils from 'tinymce/core/api/dom/DOMUtils';
import TrimHtml from 'tinymce/core/dom/TrimHtml';
import ViewBlock from '../../module/test/ViewBlock';
import Zwsp from 'tinymce/core/text/Zwsp';
import { UnitTest } from '@ephox/bedrock';
declare const escape: any;
UnitTest.asynctest('browser.tinymce.core.dom.SerializerTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
const suite = LegacyUnit.createSuite();
const DOM = DOMUtils.DOM;
const viewBlock = ViewBlock();
const teardown = function () {
viewBlock.update('');
};
const addTeardown = function (steps) {
return Arr.bind(steps, function (step) {
return [step, Step.sync(teardown)];
});
};
suite.test('Schema rules', function () {
let ser = Serializer({ fix_list_elements : true });
ser.setRules('@[id|title|class|style],div,img[src|alt|-style|border],span,hr');
DOM.setHTML('test', '<img title="test" src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" alt="test" ' +
'border="0" style="border: 1px solid red" class="test" /><span id="test2">test</span><hr />');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<img title="test" class="test" src="tinymce/ui/img/raster.gif" ' +
'alt="test" border="0" /><span id="test2">test</span><hr />', 'Global rule'
);
ser.setRules('*a[*],em/i[*],strong/b[*i*]');
DOM.setHTML('test', '<a href="test" data-mce-href="test">test</a><strong title="test" class="test">test2</strong><em title="test">test3</em>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<a href="test">test</a><strong title="test">test2</strong><em title="test">' +
'test3</em>', 'Wildcard rules');
ser.setRules('br,hr,input[type|name|value],div[id],span[id],strong/b,a,em/i,a[!href|!name],img[src|border=0|title={$uid}]');
DOM.setHTML('test', '<br /><hr /><input type="text" name="test" value="val" class="no" />' +
'<span id="test2" class="no"><b class="no">abc</b><em class="no">123</em></span>123<a href="file.html" ' +
'data-mce-href="file.html">link</a><a name="anchor"></a><a>no</a><img src="tinymce/ui/img/raster.gif" ' +
'data-mce-src="tinymce/ui/img/raster.gif" />');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<div id="test"><br /><hr /><input type="text" name="test" value="val" />' +
'<span id="test2"><strong>abc</strong><em>123</em></span>123<a href="file.html">link</a>' +
'<a name="anchor"></a>no<img src="tinymce/ui/img/raster.gif" border="0" title="mce_0" /></div>', 'Output name and attribute rules');
ser.setRules('img[src|border=0|alt=]');
DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" border="0" alt="" />');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<img src="tinymce/ui/img/raster.gif" border="0" alt="" />', 'Default attribute with empty value');
ser.setRules('img[src|border=0|alt=],div[style|id],*[*]');
DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" /><hr />');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<img src="tinymce/ui/img/raster.gif" border="0" alt="" /><hr />'
);
ser = Serializer({
valid_elements : 'img[src|border=0|alt=]',
<API key> : 'div[id],img[src|alt=]'
});
DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" alt="" />');
LegacyUnit.equal(
ser.serialize(DOM.get('test')),
'<div id="test"><img src="tinymce/ui/img/raster.gif" alt="" /></div>'
);
ser = Serializer({ invalid_elements : 'hr,br' });
DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" /><hr /><br />');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<img src="tinymce/ui/img/raster.gif" />'
);
});
suite.test('<API key> (default)', function () {
const ser = Serializer({ });
DOM.setHTML('test', '<a href="a" target="_blank">a</a><a href="b" target="_blank">b</a>');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<a href="a" target="_blank" rel="noopener">a</a><a href="b" target="_blank" rel="noopener">b</a>'
);
DOM.setHTML('test', '<a href="a" rel="lightbox" target="_blank">a</a><a href="b" rel="lightbox" target="_blank">b</a>');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<a href="a" target="_blank" rel="lightbox noopener">a</a><a href="b" target="_blank" rel="lightbox noopener">b</a>'
);
DOM.setHTML('test', '<a href="a" rel="lightbox x" target="_blank">a</a><a href="b" rel="lightbox x" target="_blank">b</a>');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<a href="a" target="_blank" rel="lightbox noopener x">a</a><a href="b" target="_blank" rel="lightbox noopener x">b</a>'
);
DOM.setHTML('test', '<a href="a" rel="noopener a" target="_blank">a</a>');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<a href="a" target="_blank" rel="noopener a">a</a>'
);
DOM.setHTML('test', '<a href="a" rel="a noopener b" target="_blank">a</a>');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<a href="a" target="_blank" rel="a noopener b">a</a>'
);
});
suite.test('<API key> (disabled)', function () {
const ser = Serializer({ <API key>: true });
DOM.setHTML('test', '<a href="a" target="_blank">a</a><a href="b" target="_blank">b</a>');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<a href="a" target="_blank">a</a><a href="b" target="_blank">b</a>'
);
});
suite.test('format tree', function () {
const ser = Serializer({ });
DOM.setHTML('test', 'a');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { format: 'tree' }).name,
'body'
);
});
suite.test('Entity encoding', function () {
let ser;
ser = Serializer({ entity_encoding : 'numeric' });
DOM.setHTML('test', '<>&" åäö');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '<>&" åäö');
ser = Serializer({ entity_encoding : 'named' });
DOM.setHTML('test', '<>&" åäö');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '<>&" åäö');
ser = Serializer({ entity_encoding : 'named+numeric', entities : '160,nbsp,34,quot,38,amp,60,lt,62,gt' });
DOM.setHTML('test', '<>&" åäö');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '<>&" åäö');
ser = Serializer({ entity_encoding : 'raw' });
DOM.setHTML('test', '<>&" åäö');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '<>&"\u00a0\u00e5\u00e4\u00f6');
});
suite.test('Form elements (general)', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules(
'form[method],label[for],input[type|name|value|checked|disabled|readonly|length|maxlength],select[multiple],' +
'option[value|selected],textarea[name|disabled|readonly]'
);
DOM.setHTML('test', '<input type="text" />');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="text" />');
DOM.setHTML('test', '<input type="text" value="text" length="128" maxlength="129" />');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="text" value="text" length="128" maxlength="129" />');
DOM.setHTML('test', '<form method="post"><input type="hidden" name="method" value="get" /></form>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<form method="post"><input type="hidden" name="method" value="get" /></form>');
DOM.setHTML('test', '<label for="test">label</label>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<label for="test">label</label>');
DOM.setHTML('test', '<input type="checkbox" value="test" /><input type="button" /><textarea></textarea>');
// Edge will add an empty input value so remove that to normalize test since it doesn't break anything
LegacyUnit.equal(
ser.serialize(DOM.get('test')).replace(/ value=""/g, ''),
'<input type="checkbox" value="test" /><input type="button" /><textarea></textarea>'
);
});
suite.test('Form elements (checkbox)', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('form[method],label[for],input[type|name|value|checked|disabled|readonly|length|maxlength],select[multiple],option[value|selected]');
DOM.setHTML('test', '<input type="checkbox" value="1">');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" />');
DOM.setHTML('test', '<input type="checkbox" value="1" checked disabled readonly>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" checked="checked" disabled="disabled" readonly="readonly" />');
DOM.setHTML('test', '<input type="checkbox" value="1" checked="1" disabled="1" readonly="1">');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" checked="checked" disabled="disabled" readonly="readonly" />');
DOM.setHTML('test', '<input type="checkbox" value="1" checked="true" disabled="true" readonly="true">');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" checked="checked" disabled="disabled" readonly="readonly" />');
});
suite.test('Form elements (select)', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('form[method],label[for],input[type|name|value|checked|disabled|readonly|length|maxlength],select[multiple],option[value|selected]');
DOM.setHTML('test', '<select><option value="1">test1</option><option value="2" selected>test2</option></select>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select><option value="1">test1</option><option value="2" selected="selected">test2</option></select>');
DOM.setHTML('test', '<select><option value="1">test1</option><option selected="1" value="2">test2</option></select>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select><option value="1">test1</option><option value="2" selected="selected">test2</option></select>');
DOM.setHTML('test', '<select><option value="1">test1</option><option value="2" selected="true">test2</option></select>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select><option value="1">test1</option><option value="2" selected="selected">test2</option></select>');
DOM.setHTML('test', '<select multiple></select>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select multiple="multiple"></select>');
DOM.setHTML('test', '<select multiple="multiple"></select>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select multiple="multiple"></select>');
DOM.setHTML('test', '<select multiple="1"></select>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select multiple="multiple"></select>');
DOM.setHTML('test', '<select></select>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select></select>');
});
suite.test('List elements', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('ul[compact],ol,li');
DOM.setHTML('test', '<ul compact></ul>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul compact="compact"></ul>');
DOM.setHTML('test', '<ul compact="compact"></ul>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul compact="compact"></ul>');
DOM.setHTML('test', '<ul compact="1"></ul>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul compact="compact"></ul>');
DOM.setHTML('test', '<ul></ul>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul></ul>');
DOM.setHTML('test', '<ol><li>a</li><ol><li>b</li><li>c</li></ol><li>e</li></ol>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ol><li>a<ol><li>b</li><li>c</li></ol></li><li>e</li></ol>');
});
suite.test('Tables', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('table,tr,td[nowrap]');
DOM.setHTML('test', '<table><tr><td></td></tr></table>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td></td></tr></table>');
DOM.setHTML('test', '<table><tr><td nowrap></td></tr></table>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td nowrap="nowrap"></td></tr></table>');
DOM.setHTML('test', '<table><tr><td nowrap="nowrap"></td></tr></table>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td nowrap="nowrap"></td></tr></table>');
DOM.setHTML('test', '<table><tr><td nowrap="1"></td></tr></table>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td nowrap="nowrap"></td></tr></table>');
});
suite.test('Styles', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('*[*]');
DOM.setHTML('test', '<span style="border: 1px solid red" data-mce-style="border: 1px solid red;">test</span>');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: true }), '<span style="border: 1px solid red;">test</span>');
});
suite.test('Comments', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('*[*]');
DOM.setHTML('test', '<!-- abc -->');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: true }), '<!-- abc -->');
});
suite.test('Non HTML elements and attributes', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('*[*]');
ser.schema.addValidChildren('+div[prefix:test]');
DOM.setHTML('test', '<div test:attr="test">test</div>');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '<div test:attr="test">test</div>');
DOM.setHTML('test', 'test1<prefix:test>Test</prefix:test>test2');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: true }), 'test1<prefix:test>Test</prefix:test>test2');
});
suite.test('Padd empty elements', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('
DOM.setHTML('test', '<p>test</p><p></p>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>test</p><p> </p>');
});
suite.test('Padd empty elements with BR', function () {
const ser = Serializer({ padd_empty_with_br: true });
ser.setRules('#p,table,tr,#td,br');
DOM.setHTML('test', '<p>a</p><p></p>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>a</p><p><br /></p>');
DOM.setHTML('test', '<p>a</p><table><tr><td><br></td></tr></table>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>a</p><table><tr><td><br /></td></tr></table>');
});
suite.test('Do not padd empty elements with padded children', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('#p,#span,b');
DOM.setHTML('test', '<p><span></span></p><p><b><span></span></b></p>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p><span> </span></p><p><b><span> </span></b></p>');
});
suite.test('Remove empty elements', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('-p');
DOM.setHTML('test', '<p>test</p><p></p>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>test</p>');
});
suite.test('Script with non JS type attribute', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<s' + 'cript type="mylanguage"></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript type="mylanguage"></s' + 'cript>');
});
suite.test('Script with tags inside a comment with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<s' + 'cript>// <img src="test"><a href="#"></a></s' + 'cript>');
LegacyUnit.equal(
ser.serialize(DOM.get('test')).replace(/\r/g, ''),
'<s' + 'cript>// <![CDATA[\n// <img src="test"><a href="#"></a>\n// ]]></s' + 'cript>'
);
});
suite.test('Script with tags inside a comment', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<s' + 'cript>// <img src="test"><a href="#"></a></s' + 'cript>');
LegacyUnit.equal(
ser.serialize(DOM.get('test')).replace(/\r/g, ''),
'<s' + 'cript>// <img src="test"><a href="#"></a></s' + 'cript>'
);
});
suite.test('Script with less than with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<s' + 'cript>1 < 2;</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>');
});
suite.test('Script with less than', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<s' + 'cript>1 < 2;</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>1 < 2;</s' + 'cript>');
});
suite.test('Script with type attrib and less than with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<s' + 'cript type="text/javascript">1 < 2;</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script type="text/javascript">// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>');
});
suite.test('Script with type attrib and less than', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<s' + 'cript type="text/javascript">1 < 2;</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script type=\"text/javascript\">1 < 2;</script>');
});
suite.test('Script with whitespace in beginning/end with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n</s' + 'cript>');
LegacyUnit.equal(
ser.serialize(DOM.get('test')).replace(/\r/g, ''),
'<s' + 'cript>// <![CDATA[\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n// ]]></s' + 'cript>'
);
});
suite.test('Script with whitespace in beginning/end', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n</s' + 'cript>');
LegacyUnit.equal(
ser.serialize(DOM.get('test')).replace(/\r/g, ''),
'<script>\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n</script>'
);
});
suite.test('Script with a HTML comment and less than with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script><!-- 1 < 2; // --></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>');
});
suite.test('Script with a HTML comment and less than', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script><!-- 1 < 2; // --></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script><!-- 1 < 2; // --></script>');
});
suite.test('Script with white space in beginning, comment and less than with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>\n\n<!-- 1 < 2;\n\n--></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>');
});
suite.test('Script with white space in beginning, comment and less than', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>\n\n<!-- 1 < 2;\n\n--></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>\n\n<!-- 1 < 2;\n\n--></script>');
});
suite.test('Script with comments and cdata with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>// <![CDATA[1 < 2; // ]]></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>');
});
suite.test('Script with comments and cdata', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>// <![CDATA[1 < 2; // ]]></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>// <![CDATA[1 < 2; // ]]></script>');
});
suite.test('Script with cdata with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script><![CDATA[1 < 2; ]]></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>');
});
suite.test('Script with cdata', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script><![CDATA[1 < 2; ]]></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script><![CDATA[1 < 2; ]]></script>');
});
suite.test('Script whitespace in beginning/end and cdata with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>\n\n<![CDATA[\n\n1 < 2;\n\n]]>\n\n</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>');
});
suite.test('Script whitespace in beginning/end and cdata', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>\n\n<![CDATA[\n\n1 < 2;\n\n]]>\n\n</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>\n\n<![CDATA[\n\n1 < 2;\n\n]]>\n\n</script>');
});
suite.test('Whitespace preserve in pre', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('pre');
DOM.setHTML('test', '<pre> </pre>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<pre> </pre>');
});
suite.test('Script with src attr', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script src="test.js" data-mce-src="test.js"></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<s' + 'cript src="test.js"></s' + 'cript>');
});
suite.test('Script with HTML comment, comment and CDATA with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script><!--// <![CDATA[var hi = "hello";// ]]>--></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>');
});
suite.test('Script with HTML comment, comment and CDATA', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script><!--// <![CDATA[var hi = "hello";// ]]>--></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script><!--// <![CDATA[var hi = \"hello\";// ]]>--></script>');
});
suite.test('Script with block comment around cdata with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>/* <![CDATA[ */\nvar hi = "hello";\n/* ]]> */</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>');
});
suite.test('Script with block comment around cdata', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>/* <![CDATA[ */\nvar hi = "hello";\n/* ]]> */</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>/* <![CDATA[ */\nvar hi = \"hello\";\n/* ]]> */</script>');
});
suite.test('Script with html comment and block comment around cdata with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script><!-- /* <![CDATA[ */\nvar hi = "hello";\n/* ]]>*/--></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>');
});
suite.test('Script with html comment and block comment around cdata', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script><!-- /* <![CDATA[ */\nvar hi = "hello";\n/* ]]>*/--></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script><!-- /* <![CDATA[ */\nvar hi = \"hello\";\n/* ]]>*/--></script>');
});
suite.test('Script with line comment and html comment with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>// <!--\nvar hi = "hello";\n// --></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>');
});
suite.test('Script with line comment and html comment', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>// <!--\nvar hi = "hello";\n// --></s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <!--\nvar hi = \"hello\";\n// --></script>');
});
suite.test('Script with block comment around html comment with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>\nvar hi = "hello";\n</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>');
});
suite.test('Script with block comment around html comment', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('script[type|language|src]');
DOM.setHTML('test', '<script>\nvar hi = "hello";\n</s' + 'cript>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>\nvar hi = \"hello\";\n</script>');
});
suite.test('Protected blocks', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('noscript[test]');
DOM.setHTML('test', '<!--mce:protected ' + escape('<noscript test="test"><br></noscript>') + '
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<noscript test="test"><br></noscript>');
DOM.setHTML('test', '<!--mce:protected ' + escape('<noscript><br></noscript>') + '
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<noscript><br></noscript>');
DOM.setHTML('test', '<!--mce:protected ' + escape('<noscript><!-- text --><br></noscript>') + '-->');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<noscript><!-- text --><br></noscript>');
});
suite.test('Style with whitespace at beginning with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]', element_format: 'xhtml' });
ser.setRules('style');
DOM.setHTML('test', '<style> body { background:#fff }</style>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style><!--\n body { background:#fff }\n--></style>');
});
suite.test('Style with whitespace at beginning', function () {
const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]' });
ser.setRules('style');
DOM.setHTML('test', '<style> body { background:#fff }</style>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style> body { background:#fff }</style>');
});
suite.test('Style with cdata with element_format: xhtml', function () {
const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]', element_format: 'xhtml' });
ser.setRules('style');
DOM.setHTML('test', '<style>\r\n<![CDATA[\r\n body { background:#fff }]]></style>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style><!--\nbody { background:#fff }\n--></style>');
});
suite.test('Style with cdata', function () {
const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]' });
ser.setRules('style');
DOM.setHTML('test', '<style>\r\n<![CDATA[\r\n body { background:#fff }]]></style>');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style>\n<![CDATA[\n body { background:#fff }]]></style>');
});
suite.test('CDATA', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('span');
DOM.setHTML('test', '123<!--[CDATA[<test>]]-->abc');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '123<![CDATA[<test>]]>abc');
DOM.setHTML('test', '123<!--[CDATA[<te\n\nst>]]-->abc');
LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '123<![CDATA[<te\n\nst>]]>abc');
});
suite.test('BR at end of blocks', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('ul,li,br');
DOM.setHTML('test', '<ul><li>test<br /></li><li>test<br /></li><li>test<br /></li></ul>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul><li>test</li><li>test</li><li>test</li></ul>');
});
suite.test('Map elements', function () {
const ser = Serializer({ fix_list_elements : true });
ser.setRules('map[id|name],area[shape|coords|href|target|alt]');
DOM.setHTML(
'test',
'<map id="planetmap" name="planetmap"><area shape="rect" coords="0,0,82,126" href="sun.htm" data-mce-href="sun.htm" target="_blank" alt="sun" /></map>'
);
LegacyUnit.equal(
ser.serialize(DOM.get('test')).toLowerCase(),
'<map id="planetmap" name="planetmap"><area shape="rect" coords="0,0,82,126" href="sun.htm" target="_blank" alt="sun" /></map>'
);
});
suite.test('Custom elements', function () {
const ser = Serializer({
custom_elements: 'custom1,~custom2',
valid_elements: 'custom1,custom2'
});
document.createElement('custom1');
document.createElement('custom2');
DOM.setHTML('test', '<p><custom1>c1</custom1><custom2>c2</custom2></p>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<custom1>c1</custom1><custom2>c2</custom2>');
});
suite.test('Remove internal classes', function () {
const ser = Serializer({
valid_elements: 'span[class]'
});
DOM.setHTML('test', '<span class="a mce-item-X mce-item-selected b"></span>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class="a b"></span>');
DOM.setHTML('test', '<span class="a mce-item-X"></span>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class="a"></span>');
DOM.setHTML('test', '<span class="mce-item-X"></span>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span></span>');
DOM.setHTML('test', '<span class="mce-item-X b"></span>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class=" b"></span>');
DOM.setHTML('test', '<span class="b mce-item-X"></span>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class="b"></span>');
});
suite.test('Restore tabindex', function () {
const ser = Serializer({
valid_elements: 'span[tabindex]'
});
DOM.setHTML('test', '<span data-mce-tabindex="42"></span>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span tabindex="42"></span>');
});
suite.test('Trailing BR (IE11)', function () {
const ser = Serializer({
valid_elements: 'p,br'
});
DOM.setHTML('test', '<p>a</p><br><br>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>a</p>');
DOM.setHTML('test', 'a<br><br>');
LegacyUnit.equal(ser.serialize(DOM.get('test')), 'a');
});
suite.test('addTempAttr', function () {
const ser = Serializer({});
ser.addTempAttr('data-x');
ser.addTempAttr('data-y');
DOM.setHTML('test', '<p data-x="1" data-y="2" data-z="3">a</p>');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: 1 }), '<p data-z="3">a</p>');
LegacyUnit.equal(TrimHtml.trimExternal(ser, '<p data-x="1" data-y="2" data-z="3">a</p>'), '<p data-z="3">a</p>');
});
suite.test('addTempAttr same attr twice', function () {
const ser1 = Serializer({});
const ser2 = Serializer({});
ser1.addTempAttr('data-x');
ser2.addTempAttr('data-x');
DOM.setHTML('test', '<p data-x="1" data-z="3">a</p>');
LegacyUnit.equal(ser1.serialize(DOM.get('test'), { getInner: 1 }), '<p data-z="3">a</p>');
LegacyUnit.equal(TrimHtml.trimExternal(ser1, '<p data-x="1" data-z="3">a</p>'), '<p data-z="3">a</p>');
LegacyUnit.equal(ser2.serialize(DOM.get('test'), { getInner: 1 }), '<p data-z="3">a</p>');
LegacyUnit.equal(TrimHtml.trimExternal(ser2, '<p data-x="1" data-z="3">a</p>'), '<p data-z="3">a</p>');
});
suite.test('trim data-mce-bougs="all"', function () {
const ser = Serializer({});
DOM.setHTML('test', 'a<p data-mce-bogus="all">b</p>c');
LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: 1 }), 'ac');
LegacyUnit.equal(TrimHtml.trimExternal(ser, 'a<p data-mce-bogus="all">b</p>c'), 'ac');
});
suite.test('zwsp should not be treated as contents', function () {
const ser = Serializer({ });
DOM.setHTML('test', '<p>' + Zwsp.ZWSP + '</p>');
LegacyUnit.equal(
ser.serialize(DOM.get('test'), { getInner: true }),
'<p> </p>'
);
});
viewBlock.attach();
viewBlock.get().id = 'test';
Pipeline.async({}, addTeardown(suite.toSteps({})), function () {
viewBlock.detach();
success();
}, failure);
});
|
<?php
/**
* Core Class To Style RAD Builder Components
* @author Abhin Sharma
* @dependency none
* @since IOA Framework V1
*/
if(!class_exists('RADStyler'))
{
class RADStyler
{
function registerbgColor($key='' ,$target='')
{
$code ='<h5 class="sub-styler-title">'.__('Set Background Color','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">';
$code .= getIOAInput(array(
"label" => __("Background Color",'ioa') ,
"name" => $key."_bg_color" ,
"default" => "" ,
"type" => "colorpicker",
"description" => "",
"length" => 'small',
"value" => "" ,
"data" => array(
"target" => $target ,
"property" => "background-color"
)
));
return $code.'</div>';
}
function registerBorder($key='' ,$target='')
{
$code ='<h5 class="sub-styler-title">'.__('Set Border','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">';
$code .= getIOAInput(array(
"label" => __("Top Border Color",'ioa') ,
"name" => $key."_tbr_color" ,
"default" => "" ,
"type" => "colorpicker",
"description" => "",
"length" => 'small',
"value" => "" ,
"data" => array(
"target" => $target ,
"property" => "border-top-color"
)
));
$code .= getIOAInput(array(
"label" => __("Top Border Size(ex : 1px)",'ioa') ,
"name" => $key."_tbr_width" ,
"default" => "" ,
"type" => "text",
"description" => "",
"length" => 'small',
"class" => ' rad_style_property ',
"value" => "0px" ,
"data" => array(
"target" => $target ,
"property" => "border-top-width"
)
));
$code .= getIOAInput(array(
"label" => __("Bottom Border Color",'ioa') ,
"name" => $key."_bbr_color" ,
"default" => "" ,
"type" => "colorpicker",
"description" => "",
"length" => 'small',
"value" => "" ,
"data" => array(
"target" => $target ,
"property" => "border-bottom-color"
)
));
$code .= getIOAInput(array(
"label" => __("Bottom Border Size(ex : 1px)",'ioa') ,
"name" => $key."_bbr_width" ,
"default" => "" ,
"type" => "text",
"description" => "",
"length" => 'small',
"class" => ' rad_style_property ',
"value" => "0px" ,
"data" => array(
"target" => $target ,
"property" => "border-bottom-width"
)
));
return $code.'</div>';
}
function registerbgImage($key ,$target)
{
$code ='<h5 class="sub-styler-title">'.__('Set Background Image','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">';
$code .= getIOAInput(array(
"label" => __("Add Background Image",'ioa') ,
"name" => $key."_bg_image" ,
"default" => "" ,
"type" => "upload",
"description" => "" ,
"length" => 'small' ,
"title" => __("Use as Background Image",'ioa'),
"std" => "",
"button" => __("Add Image",'ioa'),
"class" => ' rad_style_property ',
"data" => array(
"target" => $target ,
"property" => "background-image"
)
) );
$code .= getIOAInput(array(
"label" => __("Background Position",'ioa') ,
"name" => $key."_bgposition" ,
"default" => "top left" ,
"type" => "select",
"class" => ' rad_style_property ',
"description" => "" ,
"length" => 'medium' ,
"options" => array("top left","top right","bottom left","bottom right","center top","center center","center bottom","center left","center right"),
"data" => array(
"target" => $target ,
"property" => "background-position"
)
) );
$code .= getIOAInput(array(
"label" => __("Background Cover",'ioa') ,
"name" => $key."_bgcover" ,
"default" => "auto" ,
"type" => "select",
"class" => ' rad_style_property ',
"description" => "" ,
"length" => 'medium' ,
"options" => array("auto","contain","cover"),
"data" => array(
"target" => $target ,
"property" => "background-size"
)
) );
$code .= getIOAInput(array(
"label" => __("Background Repeat",'ioa') ,
"name" => $key."_bgrepeat" ,
"default" => "repeat" ,
"type" => "select",
"description" => "" ,
"length" => 'medium' ,
"options" => array("repeat","repeat-x","repeat-y","no-repeat"),
"class" => ' rad_style_property ',
"data" => array(
"target" => $target ,
"property" => "background-repeat"
)
) );
$code .= getIOAInput(array(
"label" => __("Background Scroll",'ioa') ,
"name" => $key."_bgscroll" ,
"default" => "" ,
"type" => "select",
"description" => "" ,
"length" => 'medium' ,
"options" => array("scroll","fixed"),
"class" => ' rad_style_property ',
"data" => array(
"target" => $target ,
"property" => "<API key>"
)
) );
return $code.'</div>';
}
function registerbgGradient($key ,$target)
{
$code ='<h5 class="sub-styler-title">'.__('Set Background Gradient','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix"><a class="set-rad-gradient button-default" href="">'.__('Apply','ioa').'</a> ';
$code .= getIOAInput(array(
"label" => __("Use Background Gradient",'ioa') ,
"name" => $key."_gradient_dir" ,
"default" => "no" ,
"type" => "select",
"description" => "" ,
"length" => 'small' ,
"options" => array("horizontal" => __("Horizontal",'ioa'),"vertical"=> __("Vertical",'ioa'),"diagonaltl" => __("Diagonal Top Left",'ioa'),"diagonalbr" => __("Diagonal Bottom Right",'ioa') ),
"class" => ' hasGradient dir ',
"data" => array(
"target" => $target ,
"property" => "removable"
)
) );
$code .= getIOAInput(array(
"label" => __("Select Start Background Color for title area",'ioa') ,
"name" => $key."_grstart" ,
"default" => " << " ,
"type" => "colorpicker",
"description" => " " ,
"length" => 'small' ,
"alpha" => false,
"class" => ' hasGradient grstart no_listen ',
"data" => array(
"target" => $target ,
"property" => "background-image"
)
) );
$code .= getIOAInput(array(
"label" => __("Select Start Background Color for title area",'ioa') ,
"name" => $key."_grend" ,
"default" => " << " ,
"type" => "colorpicker",
"description" => " " ,
"length" => 'small' ,
"alpha" => false,
"class" => ' hasGradient grend no_listen ',
"data" => array(
"target" => $target ,
"property" => "background-image"
)
) );
return $code.'</div>';
}
}
}
|
#if defined (_MSC_VER) && !defined (_WIN64)
#pragma warning(disable:4244) // boost::number_distance::distance()
// converts 64 to 32 bits integers
#endif
#include <CGAL/<API key>.h>
#include <CGAL/IO/read_xyz_points.h>
#include <CGAL/Point_with_normal_3.h>
#include <CGAL/property_map.h>
#include <CGAL/Shape_detection_3.h>
#include <CGAL/Timer.h>
#include <iostream>
#include <fstream>
// Type declarations
typedef CGAL::<API key> Kernel;
typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal;
typedef std::vector<Point_with_normal> Pwn_vector;
typedef CGAL::<API key><Point_with_normal> Point_map;
typedef CGAL::<API key><Point_with_normal> Normal_map;
// In <API key> the basic types, i.e., Point and Vector types
// as well as iterator type and property maps, are defined.
typedef CGAL::Shape_detection_3::<API key>
<Kernel, Pwn_vector, Point_map, Normal_map> Traits;
typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac;
typedef CGAL::Shape_detection_3::Region_growing<Traits> Region_growing;
typedef CGAL::Shape_detection_3::Plane<Traits> Plane;
struct Timeout_callback
{
mutable int nb;
mutable CGAL::Timer timer;
const double limit;
Timeout_callback(double limit) : nb(0), limit(limit)
{
timer.start();
}
bool operator()(double advancement) const
{
// Avoid calling time() at every single iteration, which could
// impact performances very badly
++ nb;
if (nb % 1000 != 0)
return true;
// If the limit is reach, interrupt the algorithm
if (timer.time() > limit)
{
std::cerr << "Algorithm takes too long, exiting ("
<< 100. * advancement << "% done)" << std::endl;
return false;
}
return true;
}
};
// This program both works for RANSAC and Region Growing
template <typename ShapeDetection>
int run(const char* filename)
{
Pwn_vector points;
std::ifstream stream(filename);
if (!stream ||
!CGAL::read_xyz_points(stream,
std::back_inserter(points),
CGAL::parameters::point_map(Point_map()).
normal_map(Normal_map())))
{
std::cerr << "Error: cannot read file cube.pwn" << std::endl;
return EXIT_FAILURE;
}
ShapeDetection shape_detection;
shape_detection.set_input(points);
shape_detection.template add_shape_factory<Plane>();
// Create callback that interrupts the algorithm if it takes more than half a second
Timeout_callback timeout_callback(0.5);
// Detects registered shapes with default parameters.
shape_detection.detect(typename ShapeDetection::Parameters(),
timeout_callback);
return EXIT_SUCCESS;
}
int main (int argc, char** argv)
{
if (argc > 1 && std::string(argv[1]) == "-r")
{
std::cout << "Efficient RANSAC" << std::endl;
return run<Efficient_ransac> ((argc > 2) ? argv[2] : "data/cube.pwn");
}
std::cout << "Region Growing" << std::endl;
return run<Region_growing> ((argc > 1) ? argv[1] : "data/cube.pwn");
}
|
public class Rectangulo {
public int Base;
public int Altura;
//aqui llamamos las dos variables que utilizaremos.
Rectangulo(int Base, int Altura)
{
this.Base = Base;
this.Altura = Altura;
}
//COmo pueden observar aqui se obtiene la base y se asigna el valor de la base.
int getBase ()
{
return Base;
}
//aqui devolvemos ese valor
void setBase (int Base)
{
this.Base = Base;
}
//aqui de igual forma se obtiene la altura y se le asigna el valor
int getAltura ()
{
return Altura;
}
//aqui devuelve el valor de la altura
void setAltura (int Altura)
{
this.Altura = Altura;
}
//aqui con una formula matematica se obtiene el perimetro hacemos una suma y una multiplicacion
int getPerimetro()
{
return 2*(Base+Altura);
}
//aqui solo se hace un calculo matematico como la multiplicacion
int getArea()
{
return Base*Altura;
}
}
|
package uturismu.dao;
import uturismu.dto.Booking;
/**
* @author "<API key>" team.
*
*/
public interface BookingDao extends GenericDao<Booking> {
}
|
/**
* Module dependencies.
*/
var express = require('express')
, http = require('http')
, path = require('path')
, mongo = require('mongodb')
, format = require('util').format;
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
var server = new mongo.Server("localhost", 27017, {auto_reconnect: true});
var dbManager = new mongo.Db("applique-web", server, {safe:true});
dbManager.open(function(err, db) {
require('./routes/index')(app, db);
app.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
});
|
#include "cmdlineparser.h"
#include "cppcheck.h"
#include "cppcheckexecutor.h"
#include "filelister.h"
#include "path.h"
#include "settings.h"
#include "timer.h"
#include "check.h"
#include "threadexecutor.h" // Threading model
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib> // EXIT_FAILURE
#ifdef HAVE_RULES
// xml is used for rules
#include <tinyxml2.h>
#endif
static void AddFilesToList(const std::string& FileList, std::vector<std::string>& PathNames)
{
// To keep things initially simple, if the file can't be opened, just be silent and move on.
std::istream *Files;
std::ifstream Infile;
if (FileList.compare("-") == 0) { // read from stdin
Files = &std::cin;
} else {
Infile.open(FileList.c_str());
Files = &Infile;
}
if (Files && *Files) {
std::string FileName;
while (std::getline(*Files, FileName)) { // next line
if (!FileName.empty()) {
PathNames.push_back(FileName);
}
}
}
}
static void AddInclPathsToList(const std::string& FileList, std::list<std::string>* PathNames)
{
// To keep things initially simple, if the file can't be opened, just be silent and move on.
std::ifstream Files(FileList.c_str());
if (Files) {
std::string PathName;
while (std::getline(Files, PathName)) { // next line
if (!PathName.empty()) {
PathName = Path::<API key>(PathName);
PathName = Path::<API key>(PathName);
// If path doesn't end with / or \, add it
#if GCC_VERSION >= 40600
if (PathName.back() != '/')
#else
if (PathName[PathName.size() - 1] != '/')
#endif
PathName += '/';
PathNames->push_back(PathName);
}
}
}
}
static void AddPathsToSet(const std::string& FileName, std::set<std::string>* set)
{
std::list<std::string> templist;
AddInclPathsToList(FileName, &templist);
set->insert(templist.begin(), templist.end());
}
CmdLineParser::CmdLineParser(Settings *settings)
: _settings(settings)
, _showHelp(false)
, _showVersion(false)
, _showErrorMessages(false)
, _exitAfterPrint(false)
{
}
void CmdLineParser::PrintMessage(const std::string &message)
{
std::cout << message << std::endl;
}
void CmdLineParser::PrintMessage(const char* message)
{
std::cout << message << std::endl;
}
bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[])
{
bool def = false;
bool maxconfigs = false;
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
if (std::strcmp(argv[i], "--version") == 0) {
_showVersion = true;
_exitAfterPrint = true;
return true;
}
// Flag used for various purposes during debugging
else if (std::strcmp(argv[i], "--debug") == 0)
_settings->debug = _settings->debugwarnings = true;
// Show --debug output after the first simplifications
else if (std::strcmp(argv[i], "--debug-normal") == 0)
_settings->debugnormal = true;
// Show debug warnings
else if (std::strcmp(argv[i], "--debug-warnings") == 0)
_settings->debugwarnings = true;
// dump cppcheck data
else if (std::strcmp(argv[i], "--dump") == 0)
_settings->dump = true;
// (Experimental) exception handling inside cppcheck client
else if (std::strcmp(argv[i], "--exception-handling") == 0)
_settings->exceptionHandling = true;
else if (std::strncmp(argv[i], "--exception-handling=", 21) == 0) {
_settings->exceptionHandling = true;
const std::string <API key> = &(argv[i][21]);
CppCheckExecutor::setExceptionOutput((<API key>=="stderr") ? stderr : stdout);
}
// Inconclusive checking
else if (std::strcmp(argv[i], "--inconclusive") == 0)
_settings->inconclusive = true;
// Enforce language (--language=, -x)
else if (std::strncmp(argv[i], "--language=", 11) == 0 || std::strcmp(argv[i], "-x") == 0) {
std::string str;
if (argv[i][2]) {
str = argv[i]+11;
} else {
i++;
if (i >= argc || argv[i][0] == '-') {
PrintMessage("cppcheck: No language given to '-x' option.");
return false;
}
str = argv[i];
}
if (str == "c")
_settings->enforcedLang = Settings::C;
else if (str == "c++")
_settings->enforcedLang = Settings::CPP;
else {
PrintMessage("cppcheck: Unknown language '" + str + "' enforced.");
return false;
}
}
// Filter errors
else if (std::strncmp(argv[i], "--<API key>=", 24) == 0) {
// <API key>=filename.txt
std::string filename = 24 + argv[i];
std::ifstream f(filename.c_str());
if (!f.is_open()) {
PrintMessage("cppcheck: Couldn't open the file: \"" + filename + "\".");
return false;
}
const std::string errmsg(_settings->nofail.parseFile(f));
if (!errmsg.empty()) {
PrintMessage(errmsg);
return false;
}
}
// Filter errors
else if (std::strncmp(argv[i], "--suppressions-list=", 20) == 0) {
std::string filename = argv[i]+20;
std::ifstream f(filename.c_str());
if (!f.is_open()) {
std::string message("cppcheck: Couldn't open the file: \"");
message += filename;
message += "\".";
if (std::count(filename.begin(), filename.end(), ',') > 0 ||
std::count(filename.begin(), filename.end(), '.') > 1) {
// If user tried to pass multiple files (we can only guess that)
// e.g. like this: --suppressions-list=a.txt,b.txt
// print more detailed error message to tell user how he can solve the problem
message += "\nIf you want to pass two files, you can do it e.g. like this:";
message += "\n cppcheck --suppressions-list=a.txt --suppressions-list=b.txt file.cpp";
}
PrintMessage(message);
return false;
}
const std::string errmsg(_settings->nomsg.parseFile(f));
if (!errmsg.empty()) {
PrintMessage(errmsg);
return false;
}
}
else if (std::strncmp(argv[i], "--suppress=", 11) == 0) {
std::string suppression = argv[i]+11;
const std::string errmsg(_settings->nomsg.addSuppressionLine(suppression));
if (!errmsg.empty()) {
PrintMessage(errmsg);
return false;
}
}
// Enables inline suppressions.
else if (std::strcmp(argv[i], "--inline-suppr") == 0)
_settings->inlineSuppressions = true;
// Verbose error messages (configuration info)
else if (std::strcmp(argv[i], "-v") == 0 || std::strcmp(argv[i], "--verbose") == 0)
_settings->verbose = true;
// Force checking of files that have "too many" configurations
else if (std::strcmp(argv[i], "-f") == 0 || std::strcmp(argv[i], "--force") == 0)
_settings->force = true;
// Output relative paths
else if (std::strcmp(argv[i], "-rp") == 0 || std::strcmp(argv[i], "--relative-paths") == 0)
_settings->relativePaths = true;
else if (std::strncmp(argv[i], "-rp=", 4) == 0 || std::strncmp(argv[i], "--relative-paths=", 17) == 0) {
_settings->relativePaths = true;
if (argv[i][argv[i][3]=='='?4:17] != 0) {
std::string paths = argv[i]+(argv[i][3]=='='?4:17);
for (;;) {
std::string::size_type pos = paths.find(';');
if (pos == std::string::npos) {
_settings->basePaths.push_back(Path::<API key>(paths));
break;
} else {
_settings->basePaths.push_back(Path::<API key>(paths.substr(0, pos)));
paths.erase(0, pos + 1);
}
}
} else {
PrintMessage("cppcheck: No paths specified for the '" + std::string(argv[i]) + "' option.");
return false;
}
}
// Write results in results.xml
else if (std::strcmp(argv[i], "--xml") == 0)
_settings->xml = true;
// Define the XML file version (and enable XML output)
else if (std::strncmp(argv[i], "--xml-version=", 14) == 0) {
std::string numberString(argv[i]+14);
std::istringstream iss(numberString);
if (!(iss >> _settings->xml_version)) {
PrintMessage("cppcheck: argument to '--xml-version' is not a number.");
return false;
}
if (_settings->xml_version < 0 || _settings->xml_version > 2) {
// We only have xml versions 1 and 2
PrintMessage("cppcheck: '--xml-version' can only be 1 or 2.");
return false;
}
// Enable also XML if version is set
_settings->xml = true;
}
// Only print something when there are errors
else if (std::strcmp(argv[i], "-q") == 0 || std::strcmp(argv[i], "--quiet") == 0)
_settings->quiet = true;
// Append user-defined code to checked source code
else if (std::strncmp(argv[i], "--append=", 9) == 0) {
const std::string filename = 9 + argv[i];
if (!_settings->append(filename)) {
PrintMessage("cppcheck: Couldn't open the file: \"" + filename + "\".");
return false;
}
}
// Check configuration
else if (std::strcmp(argv[i], "--check-config") == 0) {
_settings->checkConfiguration = true;
}
// Check library definitions
else if (std::strcmp(argv[i], "--check-library") == 0) {
_settings->checkLibrary = true;
}
else if (std::strncmp(argv[i], "--enable=", 9) == 0) {
const std::string errmsg = _settings->addEnabled(argv[i] + 9);
if (!errmsg.empty()) {
PrintMessage(errmsg);
return false;
}
// when "style" is enabled, also enable "warning", "performance" and "portability"
if (_settings->isEnabled("style")) {
_settings->addEnabled("warning");
_settings->addEnabled("performance");
_settings->addEnabled("portability");
}
}
// --error-exitcode=1
else if (std::strncmp(argv[i], "--error-exitcode=", 17) == 0) {
std::string temp = argv[i]+17;
std::istringstream iss(temp);
if (!(iss >> _settings->exitCode)) {
_settings->exitCode = 0;
PrintMessage("cppcheck: Argument must be an integer. Try something like '--error-exitcode=1'.");
return false;
}
}
// User define
else if (std::strncmp(argv[i], "-D", 2) == 0) {
std::string define;
// "-D define"
if (std::strcmp(argv[i], "-D") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
PrintMessage("cppcheck: argument to '-D' is missing.");
return false;
}
define = argv[i];
}
// "-Ddefine"
else {
define = 2 + argv[i];
}
// No "=", append a "=1"
if (define.find('=') == std::string::npos)
define += "=1";
if (!_settings->userDefines.empty())
_settings->userDefines += ";";
_settings->userDefines += define;
def = true;
}
// User undef
else if (std::strncmp(argv[i], "-U", 2) == 0) {
std::string undef;
// "-U undef"
if (std::strcmp(argv[i], "-U") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
PrintMessage("cppcheck: argument to '-U' is missing.");
return false;
}
undef = argv[i];
}
// "-Uundef"
else {
undef = 2 + argv[i];
}
_settings->userUndefs.insert(undef);
}
else if (std::strcmp(argv[i], "-E") == 0) {
_settings->preprocessOnly = true;
}
// Include paths
else if (std::strncmp(argv[i], "-I", 2) == 0) {
std::string path;
// "-I path/"
if (std::strcmp(argv[i], "-I") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
PrintMessage("cppcheck: argument to '-I' is missing.");
return false;
}
path = argv[i];
}
// "-Ipath/"
else {
path = 2 + argv[i];
}
path = Path::<API key>(path);
path = Path::<API key>(path);
// If path doesn't end with / or \, add it
#if GCC_VERSION >= 40600
if (path.back() != '/')
#else
if (path[path.size() - 1] != '/')
#endif
path += '/';
_settings->includePaths.push_back(path);
} else if (std::strncmp(argv[i], "--include=", 10) == 0) {
std::string path = argv[i] + 10;
path = Path::<API key>(path);
_settings->userIncludes.push_back(path);
} else if (std::strncmp(argv[i], "--includes-file=", 16) == 0) {
// open this file and read every input file (1 file name per line)
AddInclPathsToList(16 + argv[i], &_settings->includePaths);
} else if (std::strncmp(argv[i], "--config-exclude=",17) ==0) {
std::string path = argv[i] + 17;
path = Path::<API key>(path);
_settings->configExcludePaths.insert(path);
} else if (std::strncmp(argv[i], "--<API key>=", 23) == 0) {
// open this file and read every input file (1 file name per line)
AddPathsToSet(23 + argv[i], &_settings->configExcludePaths);
}
// file list specified
else if (std::strncmp(argv[i], "--file-list=", 12) == 0) {
// open this file and read every input file (1 file name per line)
AddFilesToList(12 + argv[i], _pathnames);
}
// Ignored paths
else if (std::strncmp(argv[i], "-i", 2) == 0) {
std::string path;
// "-i path/"
if (std::strcmp(argv[i], "-i") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
PrintMessage("cppcheck: argument to '-i' is missing.");
return false;
}
path = argv[i];
}
// "-ipath/"
else {
path = 2 + argv[i];
}
if (!path.empty()) {
path = Path::<API key>(path);
path = Path::<API key>(path);
path = Path::simplifyPath(path);
if (FileLister::isDirectory(path)) {
// If directory name doesn't end with / or \, add it
#if GCC_VERSION >= 40600
if (path.back() != '/')
#else
if (path[path.size() - 1] != '/')
#endif
path += '/';
}
_ignoredPaths.push_back(path);
}
}
// --library
else if (std::strncmp(argv[i], "--library=", 10) == 0) {
if (!CppCheckExecutor::tryLoadLibrary(_settings->library, argv[0], argv[i]+10))
return false;
}
// Report progress
else if (std::strcmp(argv[i], "--report-progress") == 0) {
_settings->reportProgress = true;
}
// --std
else if (std::strcmp(argv[i], "--std=posix") == 0) {
_settings->standards.posix = true;
} else if (std::strcmp(argv[i], "--std=c89") == 0) {
_settings->standards.c = Standards::C89;
} else if (std::strcmp(argv[i], "--std=c99") == 0) {
_settings->standards.c = Standards::C99;
} else if (std::strcmp(argv[i], "--std=c11") == 0) {
_settings->standards.c = Standards::C11;
} else if (std::strcmp(argv[i], "--std=c++03") == 0) {
_settings->standards.cpp = Standards::CPP03;
} else if (std::strcmp(argv[i], "--std=c++11") == 0) {
_settings->standards.cpp = Standards::CPP11;
}
// Output formatter
else if (std::strcmp(argv[i], "--template") == 0 ||
std::strncmp(argv[i], "--template=", 11) == 0) {
// "--template path/"
if (argv[i][10] == '=')
_settings->outputFormat = argv[i] + 11;
else if ((i+1) < argc && argv[i+1][0] != '-') {
++i;
_settings->outputFormat = argv[i];
} else {
PrintMessage("cppcheck: argument to '--template' is missing.");
return false;
}
if (_settings->outputFormat == "gcc")
_settings->outputFormat = "{file}:{line}: {severity}: {message}";
else if (_settings->outputFormat == "vs")
_settings->outputFormat = "{file}({line}): {severity}: {message}";
else if (_settings->outputFormat == "edit")
_settings->outputFormat = "{file} +{line}: {severity}: {message}";
}
// Checking threads
else if (std::strncmp(argv[i], "-j", 2) == 0) {
std::string numberString;
// "-j 3"
if (std::strcmp(argv[i], "-j") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
PrintMessage("cppcheck: argument to '-j' is missing.");
return false;
}
numberString = argv[i];
}
else
numberString = argv[i]+2;
std::istringstream iss(numberString);
if (!(iss >> _settings->jobs)) {
PrintMessage("cppcheck: argument to '-j' is not a number.");
return false;
}
if (_settings->jobs > 10000) {
// This limit is here just to catch typos. If someone has
// need for more jobs, this value should be increased.
PrintMessage("cppcheck: argument for '-j' is allowed to be 10000 at max.");
return false;
}
} else if (std::strncmp(argv[i], "-l", 2) == 0) {
std::string numberString;
// "-l 3"
if (std::strcmp(argv[i], "-l") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
PrintMessage("cppcheck: argument to '-l' is missing.");
return false;
}
numberString = argv[i];
}
else
numberString = argv[i]+2;
std::istringstream iss(numberString);
if (!(iss >> _settings->loadAverage)) {
PrintMessage("cppcheck: argument to '-l' is not a number.");
return false;
}
}
// print all possible error messages..
else if (std::strcmp(argv[i], "--errorlist") == 0) {
_showErrorMessages = true;
_settings->xml = true;
_exitAfterPrint = true;
}
// documentation..
else if (std::strcmp(argv[i], "--doc") == 0) {
std::ostringstream doc;
// Get documentation..
for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) {
const std::string& name((*it)->name());
const std::string info((*it)->classInfo());
if (!name.empty() && !info.empty())
doc << "## " << name << " ##\n"
<< info << "\n";
}
std::cout << doc.str();
_exitAfterPrint = true;
return true;
}
// show timing information..
else if (std::strncmp(argv[i], "--showtime=", 11) == 0) {
const std::string showtimeMode = argv[i] + 11;
if (showtimeMode == "file")
_settings->showtime = SHOWTIME_FILE;
else if (showtimeMode == "summary")
_settings->showtime = SHOWTIME_SUMMARY;
else if (showtimeMode == "top5")
_settings->showtime = SHOWTIME_TOP5;
else if (showtimeMode.empty())
_settings->showtime = SHOWTIME_NONE;
else {
std::string message("cppcheck: error: unrecognized showtime mode: \"");
message += showtimeMode;
message += "\". Supported modes: file, summary, top5.";
PrintMessage(message);
return false;
}
}
#ifdef HAVE_RULES
// Rule given at command line
else if (std::strncmp(argv[i], "--rule=", 7) == 0) {
Settings::Rule rule;
rule.pattern = 7 + argv[i];
_settings->rules.push_back(rule);
}
// Rule file
else if (std::strncmp(argv[i], "--rule-file=", 12) == 0) {
tinyxml2::XMLDocument doc;
if (doc.LoadFile(12+argv[i]) == tinyxml2::XML_SUCCESS) {
tinyxml2::XMLElement *node = doc.FirstChildElement();
for (; node && strcmp(node->Value(), "rule") == 0; node = node->NextSiblingElement()) {
Settings::Rule rule;
tinyxml2::XMLElement *tokenlist = node->FirstChildElement("tokenlist");
if (tokenlist)
rule.tokenlist = tokenlist->GetText();
tinyxml2::XMLElement *pattern = node->FirstChildElement("pattern");
if (pattern) {
rule.pattern = pattern->GetText();
}
tinyxml2::XMLElement *message = node->FirstChildElement("message");
if (message) {
tinyxml2::XMLElement *severity = message->FirstChildElement("severity");
if (severity)
rule.severity = Severity::fromString(severity->GetText());
tinyxml2::XMLElement *id = message->FirstChildElement("id");
if (id)
rule.id = id->GetText();
tinyxml2::XMLElement *summary = message->FirstChildElement("summary");
if (summary)
rule.summary = summary->GetText() ? summary->GetText() : "";
}
if (!rule.pattern.empty())
_settings->rules.push_back(rule);
}
}
}
#endif
// Specify platform
else if (std::strncmp(argv[i], "--platform=", 11) == 0) {
std::string platform(11+argv[i]);
if (platform == "win32A")
_settings->platform(Settings::Win32A);
else if (platform == "win32W")
_settings->platform(Settings::Win32W);
else if (platform == "win64")
_settings->platform(Settings::Win64);
else if (platform == "unix32")
_settings->platform(Settings::Unix32);
else if (platform == "unix64")
_settings->platform(Settings::Unix64);
else if (platform == "native")
_settings->platform(Settings::Unspecified);
else if (!_settings->platformFile(platform)) {
std::string message("cppcheck: error: unrecognized platform: \"");
message += platform;
message += "\".";
PrintMessage(message);
return false;
}
}
// Set maximum number of #ifdef configurations to check
else if (std::strncmp(argv[i], "--max-configs=", 14) == 0) {
_settings->force = false;
std::istringstream iss(14+argv[i]);
if (!(iss >> _settings->maxConfigs)) {
PrintMessage("cppcheck: argument to '--max-configs=' is not a number.");
return false;
}
if (_settings->maxConfigs < 1) {
PrintMessage("cppcheck: argument to '--max-configs=' must be greater than 0.");
return false;
}
maxconfigs = true;
}
// Print help
else if (std::strcmp(argv[i], "-h") == 0 || std::strcmp(argv[i], "--help") == 0) {
_pathnames.clear();
_showHelp = true;
_exitAfterPrint = true;
break;
}
else {
std::string message("cppcheck: error: unrecognized command line option: \"");
message += argv[i];
message += "\".";
PrintMessage(message);
return false;
}
}
else {
std::string path = Path::<API key>(argv[i]);
path = Path::<API key>(path);
_pathnames.push_back(path);
}
}
if (_settings->force)
_settings->maxConfigs = ~0U;
else if ((def || _settings->preprocessOnly) && !maxconfigs)
_settings->maxConfigs = 1U;
if (_settings->isEnabled("unusedFunction") && _settings->jobs > 1) {
PrintMessage("cppcheck: unusedFunction check can't be used with '-j' option. Disabling unusedFunction check.");
}
if (_settings->inconclusive && _settings->xml && _settings->xml_version == 1U) {
PrintMessage("cppcheck: inconclusive messages will not be shown, because the old xml format is not compatible. It's recommended to use the new xml format (use --xml-version=2).");
}
if (argc <= 1) {
_showHelp = true;
_exitAfterPrint = true;
}
if (_showHelp) {
PrintHelp();
return true;
}
// Print error only if we have "real" command and expect files
if (!_exitAfterPrint && _pathnames.empty()) {
PrintMessage("cppcheck: No C or C++ source files found.");
return false;
}
// Use paths _pathnames if no base paths for relative path output are given
if (_settings->basePaths.empty() && _settings->relativePaths)
_settings->basePaths = _pathnames;
return true;
}
void CmdLineParser::PrintHelp()
{
std::cout << "Cppcheck - A tool for static C/C++ code analysis\n"
"\n"
"Syntax:\n"
" cppcheck [OPTIONS] [files or paths]\n"
"\n"
"If a directory is given instead of a filename, *.cpp, *.cxx, *.cc, *.c++, *.c,\n"
"*.tpp, and *.txx files are checked recursively from the given directory.\n\n"
"Options:\n"
" --append=<file> This allows you to provide information about functions\n"
" by providing an implementation for them.\n"
" --check-config Check cppcheck configuration. The normal code\n"
" analysis is disabled by this flag.\n"
" --check-library Show information messages when library files have\n"
" incomplete info.\n"
" --config-exclude=<dir>\n"
" Path (prefix) to be excluded from configuration\n"
" checking. Preprocessor configurations defined in\n"
" headers (but not sources) matching the prefix will not\n"
" be considered for evaluation.\n"
" --<API key>=<file>\n"
" A file that contains a list of config-excludes\n"
" --dump Dump xml data for each translation unit. The dump\n"
" files have the extension .dump and contain ast,\n"
" tokenlist, symboldatabase, valueflow.\n"
" -D<ID> Define preprocessor symbol. Unless --max-configs or\n"
" --force is used, Cppcheck will only check the given\n"
" configuration when -D is used.\n"
" Example: '-DDEBUG=1 -D__cplusplus'.\n"
" -U<ID> Undefine preprocessor symbol. Use -U to explicitly\n"
" hide certain #ifdef <ID> code paths from checking.\n"
" Example: '-UDEBUG'\n"
" -E Print preprocessor output on stdout and don't do any\n"
" further processing.\n"
" --enable=<id> Enable additional checks. The available ids are:\n"
" * all\n"
" Enable all checks. It is recommended to only\n"
" use --enable=all when the whole program is\n"
" scanned, because this enables unusedFunction.\n"
" * warning\n"
" Enable warning messages\n"
" * style\n"
" Enable all coding style checks. All messages\n"
" with the severities 'style', 'performance' and\n"
" 'portability' are enabled.\n"
" * performance\n"
" Enable performance messages\n"
" * portability\n"
" Enable portability messages\n"
" * information\n"
" Enable information messages\n"
" * unusedFunction\n"
" Check for unused functions. It is recommend\n"
" to only enable this when the whole program is\n"
" scanned.\n"
" * missingInclude\n"
" Warn if there are missing includes. For\n"
" detailed information, use '--check-config'.\n"
" Several ids can be given if you separate them with\n"
" commas. See also --std\n"
" --error-exitcode=<n> If errors are found, integer [n] is returned instead of\n"
" the default '0'. '" << EXIT_FAILURE << "' is returned\n"
" if arguments are not valid or if no input files are\n"
" provided. Note that your operating system can modify\n"
" this value, e.g. '256' can become '0'.\n"
" --errorlist Print a list of all the error messages in XML format.\n"
" --<API key>=<file>\n"
" Used when certain messages should be displayed but\n"
" should not cause a non-zero exitcode.\n"
" --file-list=<file> Specify the files to check in a text file. Add one\n"
" filename per line. When file is '-,' the file list will\n"
" be read from standard input.\n"
" -f, --force Force checking of all configurations in files. If used\n"
" together with '--max-configs=', the last option is the\n"
" one that is effective.\n"
" -h, --help Print this help.\n"
" -I <dir> Give path to search for include files. Give several -I\n"
" parameters to give several paths. First given path is\n"
" searched for contained header files first. If paths are\n"
" relative to source files, this is not needed.\n"
" --includes-file=<file>\n"
" Specify directory paths to search for included header\n"
" files in a text file. Add one include path per line.\n"
" First given path is searched for contained header\n"
" files first. If paths are relative to source files,\n"
" this is not needed.\n"
" --include=<file>\n"
" Force inclusion of a file before the checked file. Can\n"
" be used for example when checking the Linux kernel,\n"
" where autoconf.h needs to be included for every file\n"
" compiled. Works the same way as the GCC -include\n"
" option.\n"
" -i <dir or file> Give a source file or source file directory to exclude\n"
" from the check. This applies only to source files so\n"
" header files included by source files are not matched.\n"
" Directory name is matched to all parts of the path.\n"
" --inconclusive Allow that Cppcheck reports even though the analysis is\n"
" inconclusive.\n"
" There are false positives with this option. Each result\n"
" must be carefully investigated before you know if it is\n"
" good or bad.\n"
" --inline-suppr Enable inline suppressions. Use them by placing one or\n"
" more comments, like: '// cppcheck-suppress warningId'\n"
" on the lines before the warning to suppress.\n"
" -j <jobs> Start <jobs> threads to do the checking simultaneously.\n"
#ifdef <API key>
" -l <load> Specifies that no new threads should be started if\n"
" there are other threads running and the load average is\n"
" at least <load>.\n"
#endif
" --language=<language>, -x <language>\n"
" Forces cppcheck to check all files as the given\n"
" language. Valid values are: c, c++\n"
" --library=<cfg>\n"
" Load file <cfg> that contains information about types\n"
" and functions. With such information Cppcheck\n"
" understands your your code better and therefore you\n"
" get better results. The std.cfg file that is\n"
" distributed with Cppcheck is loaded automatically.\n"
" For more information about library files, read the\n"
" manual.\n"
" --max-configs=<limit>\n"
" Maximum number of configurations to check in a file\n"
" before skipping it. Default is '12'. If used together\n"
" with '--force', the last option is the one that is\n"
" effective.\n"
" --platform=<type>, --platform=<file>\n"
" Specifies platform specific types and sizes. The\n"
" available builtin platforms are:\n"
" * unix32\n"
" 32 bit unix variant\n"
" * unix64\n"
" 64 bit unix variant\n"
" * win32A\n"
" 32 bit Windows ASCII character encoding\n"
" * win32W\n"
" 32 bit Windows UNICODE character encoding\n"
" * win64\n"
" 64 bit Windows\n"
" * native\n"
" Unspecified platform. Type sizes of host system\n"
" are assumed, but no further assumptions.\n"
" -q, --quiet Do not show progress reports.\n"
" -rp, --relative-paths\n"
" -rp=<paths>, --relative-paths=<paths>\n"
" Use relative paths in output. When given, <paths> are\n"
" used as base. You can separate multiple paths by ';'.\n"
" Otherwise path where source files are searched is used.\n"
" We use string comparison to create relative paths, so\n"
" using e.g. ~ for home folder does not work. It is\n"
" currently only possible to apply the base paths to\n"
" files that are on a lower level in the directory tree.\n"
" --report-progress Report progress messages while checking a file.\n"
#ifdef HAVE_RULES
" --rule=<rule> Match regular expression.\n"
" --rule-file=<file> Use given rule file. For more information, see: \n"
" http://sourceforge.net/projects/cppcheck/files/Articles/\n"
#endif
" --std=<id> Set standard.\n"
" The available options are:\n"
" * posix\n"
" POSIX compatible code\n"
" * c89\n"
" C code is C89 compatible\n"
" * c99\n"
" C code is C99 compatible\n"
" * c11\n"
" C code is C11 compatible (default)\n"
" * c++03\n"
" C++ code is C++03 compatible\n"
" * c++11\n"
" C++ code is C++11 compatible (default)\n"
" More than one --std can be used:\n"
" 'cppcheck --std=c99 --std=posix file.c'\n"
" --suppress=<spec> Suppress warnings that match <spec>. The format of\n"
" <spec> is:\n"
" [error id]:[filename]:[line]\n"
" The [filename] and [line] are optional. If [error id]\n"
" is a wildcard '*', all error ids match.\n"
" --suppressions-list=<file>\n"
" Suppress warnings listed in the file. Each suppression\n"
" is in the same format as <spec> above.\n"
" --template='<text>' Format the error messages. E.g.\n"
" '{file}:{line},{severity},{id},{message}' or\n"
" '{file}({line}):({severity}) {message}' or\n"
" '{callstack} {message}'\n"
" Pre-defined templates: gcc, vs, edit.\n"
" -v, --verbose Output more detailed error information.\n"
" --version Print out version number.\n"
" --xml Write results in xml format to error stream (stderr).\n"
" --xml-version=<version>\n"
" Select the XML file version. Currently versions 1 and\n"
" 2 are available. The default version is 1."
"\n"
"Example usage:\n"
" # Recursively check the current folder. Print the progress on the screen and\n"
" # write errors to a file:\n"
" cppcheck . 2> err.txt\n"
"\n"
" # Recursively check ../myproject/ and don't print progress:\n"
" cppcheck --quiet ../myproject/\n"
"\n"
" # Check test.cpp, enable all checks:\n"
" cppcheck --enable=all --inconclusive --std=posix test.cpp\n"
"\n"
" # Check f.cpp and search include files from inc1/ and inc2/:\n"
" cppcheck -I inc1/ -I inc2/ f.cpp\n"
"\n"
"For more information:\n"
" http://cppcheck.net/manual.pdf\n";
}
|
/**
* @file vtkFileWriter.h
* @brief Writes a vtk data file using the legacy format
*
* @details This library implements a light weight legacy vtk
* format writer. This is intended to be used as a part of the
* dx2vtk program.
*
* @author David J. Warne (david.warne@qut.edu.au)
* @author High Performance Computing and Research Support
* @author Queensland University of Technology
*
*/
#ifndef __VTKFILEWRITER_H
#define __VTKFILEWRITER_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <endian.h>
/*data types*/
#define VTK_ASCII 0
#define VTK_BINARY 1
#define H2BE32(buf,size) \
{ \
int iii; \
uint32_t * buf32; \
buf32 = (uint32_t *)(buf); \
for(iii=0;iii<(size);iii++) \
{ \
buf32[iii] = htobe32(buf32[iii]); \
} \
} \
#define BE2H32(buf,size) \
{ \
int iii; \
uint32_t * buf32; \
buf32 = (uint32_t *)(buf); \
for(iii=0;iii<(size);iii++) \
{ \
buf32[iii] = be32toh(buf32[iii]); \
} \
} \
/*geometry*/
#define <API key> 0
#define VTK_STRUCTURED_GRID 1
#define <API key> 2
#define VTK_POLYDATA 3
#define <API key> 4
#define VTK_FIELD 5
#define VTK_VERTEX 1
#define VTK_POLY_VERTEX 2
#define VTK_LINE 3
#define VTK_POLY_LINE 4
#define VTK_TRIANGLE 5
#define VTK_TRIANGLE_STRIP 6
#define VTK_POLYGON 7
#define VTK_PIXEL 8
#define VTK_QUAD 9
#define VTK_TETRA 10
#define VTK_VOXEL 11
#define VTK_HEXAHEDRON 12
#define VTK_WEDGE 13
#define VTK_PYRAMID 14
#define VTK_QUADRATIC_EDGE 21
#define <API key> 22
#define VTK_QUADRATIC_QUAD 23
#define VTK_QUADRATIC_TETRA 24
#define <API key> 25
#define VTK_VERSION "4.2"
#define VTK_TITLE_LENGTH 256
#define VTK_DIM 3
#define VTK_INT 0
#define VTK_FLOAT 1
#define VTK_SUCCESS 1
#define VTK_MEMORY_ERROR 0
#define <API key> -1
#define <API key> -2
#define <API key> -3
#define <API key> -4
#define <API key> -5
#define VTK_FILE_ERROR -6
#ifndef VTK_TYPE_DEFAULT
#define VTK_TYPE_DEFAULT VTK_ASCII
#endif
typedef struct vtkDataFile_struct vtkDataFile;
typedef struct <API key> unstructuredGrid;
typedef struct <API key> structuredPoints;
typedef struct polydata_struct polydata;
typedef struct vtkData_struct vtkData;
typedef struct scalar_struct scalar;
typedef struct vector_struct vector;
struct scalar_struct {
char name[32];
int type;
void * data;
};
struct vector_struct {
char name[32];
int type;
void *data;
};
struct vtkData_struct {
int numScalars;
int numColorScalars;
int numLookupTables;
int numVectors;
int numNormals;
int numTextureCoords;
int numTensors;
int numFields;
int size;
/** @todo for now only support scalars and vectors */
scalar *scalar_data;
vector *vector_data;
};
struct vtkDataFile_struct {
FILE *fp;
char vtkVersion[4]; /*header version*/
char title[VTK_TITLE_LENGTH];
unsigned char dataType;
unsigned char geometry;
void * dataset;
vtkData * pointdata;
vtkData * celldata;
};
struct <API key> {
int dimensions[VTK_DIM];
float origin[VTK_DIM];
float spacing[VTK_DIM];
};
struct <API key> {
int dimensions[VTK_DIM];
int numPoints;
float *points; // numpoints*3;
};
struct polydata_struct{
int numPoints;
float * points;
int numPolygons;
int *numVerts;
int *polygons;
};
struct <API key>{
int dimensions[VTK_DIM];
int numX;
int numY;
int numZ;
float *X_coordinates;
float *Y_coordinates;
float *Z_coordinates;
};
struct <API key>{
int numPoints;
float * points;
int numCells;
int cellSize;
int *cells;
int *numVerts;
int *cellTypes;
};
/*function prototypes */
int VTK_Open(vtkDataFile *file, char * filename);
int VTK_Write(vtkDataFile *file);
int <API key>(FILE *fp,unstructuredGrid *ug,char type);
int VTK_WritePolydata(FILE *fp,polydata *pd,char type);
int <API key>(FILE *fp,structuredPoints *sp,char type);
int VTK_WriteData(FILE *fp,vtkData *data,char type);
int VTK_Close(vtkDataFile*file);
#endif
|
#ifndef __SKE_H
#define __SKE_H
#include <linux/input/matrix_keypad.h>
/* register definitions for SKE peripheral */
#define SKE_CR 0x00
#define SKE_VAL0 0x04
#define SKE_VAL1 0x08
#define SKE_DBCR 0x0C
#define SKE_IMSC 0x10
#define SKE_RIS 0x14
#define SKE_MIS 0x18
#define SKE_ICR 0x1C
/*
* Keypad module
*/
/**
* struct <API key> - structure for platform specific data
* @init: pointer to keypad init function
* @exit: pointer to keypad deinitialisation function
* @keymap_data: matrix scan code table for keycodes
* @krow: maximum number of rows
* @kcol: maximum number of columns
* @debounce_ms: platform specific debounce time
* @no_autorepeat: flag for auto repetition
* @wakeup_enable: allow waking up the system
*/
struct <API key>
{
int (*init)(void);
int (*exit)(void);
const struct matrix_keymap_data *keymap_data;
u8 krow;
u8 kcol;
u8 debounce_ms;
bool no_autorepeat;
bool wakeup_enable;
};
#endif /*__SKE_KPD_H*/
|
// MSGRTickConnection.h
// wehuibao
#import <Foundation/Foundation.h>
typedef enum {
<API key>=0,
<API key>,
<API key>,
<API key>,
<API key>
} <API key>;
@class MSGRTickConnection;
@protocol <API key> <NSObject>
@optional
- (void)connectionLost:(MSGRTickConnection *)connection;
- (void)connection:(MSGRTickConnection *)connection error:(NSError *)error;
@required
- (void)<API key>:(MSGRTickConnection *)connection;
- (void)connection:(MSGRTickConnection *)connection receivedPacket:(id)packet withDirective:(NSString *)directive;
@end
@interface MSGRTickConnection: NSObject<NSStreamDelegate>
@property (nonatomic) <API key> state;
@property (nonatomic) BOOL loginOK;
@property (nonatomic, weak) id<<API key>> delegate;
- (void)connect;
- (void)close;
- (void)sendPacket:(id)packet directive:(NSString *)directive;
@end
|
#include <algorithm>
#include <string>
#include <simul.hpp>
#include <server.hpp>
#include <jtrace.hpp>
#include <task.hpp>
#include <task.hpp>
#include <waitinstr.hpp>
namespace RTSim {
using namespace std;
using namespace MetaSim;
// Init globals
JavaTrace::TRACE_ENDIANESS JavaTrace::endianess = <API key>;
string JavaTrace::version = "1.2";
JavaTrace::JavaTrace(const char *name, bool tof, unsigned long int limit)
:Trace(name, Trace::BINARY, tof), taskList(10)
{
if (endianess == <API key>) probeEndianess();
const char cver[] = "version 1.2";
if (toFile) _os.write(cver, sizeof(cver));
filenum = 0;
fileLimit = limit;
}
JavaTrace::~JavaTrace()
{
// WARNING: the data vector is cleared but its content isn't. It
// must be deleted manually (close).
if (toFile) Trace::close();
else data.clear();
}
void JavaTrace::probeEndianess(void)
{
// Used for endianess check (Big/Little!)
static char const big_endian[] = {
static_cast<char const>(0xff),
static_cast<char const>(0),
static_cast<char const>(0xff),
static_cast<char const>(0)};
static int const probe = 0xff00ff00;
int *probePtr = (int *)(big_endian);
if (*probePtr == probe) endianess = TRACE_BIG_ENDIAN;
else endianess = TRACE_LITTLE_ENDIAN;
//DBGFORCE("Endianess: " << (endianess == TRACE_LITTLE_ENDIAN ? "Little\n" : "Big\n"));
}
void JavaTrace::close()
{
if (toFile) Trace::close();
else {
for (unsigned int i = 0; i < data.size(); i++) delete data[i];
data.clear();
}
}
void JavaTrace::record(Event* e)
{
DBGENTER(_JTRACE_DBG_LEV);
TaskEvt* ee = dynamic_cast<TaskEvt*>(e);
if (ee == NULL) {
DBGPRINT("The event is not a TaskEvt");
return;
}
Task* task = ee->getTask();
if (task != NULL) {
vector<int>::const_iterator p = find(taskList.begin(), taskList.end(),
task->getID());
if (p == taskList.end()) {
TraceNameEvent* a = new TraceNameEvent(ee->getLastTime(),
task->getID(), task->getName());
if (toFile) a->write(_os);
else data.push_back(a);
taskList.push_back(task->getID());
}
}
// at this point we have to see what kind of event it is...
if (dynamic_cast<ArrEvt*>(e) != NULL) {
DBGPRINT("ArrEvt");
ArrEvt* tae = dynamic_cast<ArrEvt*>(e);
TraceArrEvent* a = new TraceArrEvent(e->getLastTime(), task->getID());
if (toFile) a->write(_os);
else data.push_back(a);
Task* rttask = dynamic_cast<Task*>(task);
if (rttask) {
TraceDlineSetEvent* b = new TraceDlineSetEvent(tae->getLastTime(),
rttask->getID(),
rttask->getDeadline());
if (toFile) b->write(_os);
else data.push_back(b);
}
} else if (dynamic_cast<EndEvt*>(e) != NULL) {
DBGPRINT("EndEvt");
EndEvt* tee = dynamic_cast<EndEvt*>(e);
TraceEndEvent* a = new TraceEndEvent(tee->getLastTime(), task->getID(),
tee->getCPU());
if (toFile) a->write(_os);
else data.push_back(a);
} else if (dynamic_cast<DeschedEvt*>(e) != NULL) {
DBGPRINT("DeschedEvt");
DeschedEvt *tde = dynamic_cast<DeschedEvt *>(e);
TraceDeschedEvent* a = new TraceDeschedEvent(tde->getLastTime(),
task->getID(),
tde->getCPU());
if (toFile) a->write(_os);
else data.push_back(a);
} else if (dynamic_cast<WaitEvt*>(e) != NULL) {
DBGPRINT("WaitEvt");
WaitEvt* we = dynamic_cast<WaitEvt*>(e);
//WaitInstr* instr = dynamic_cast<WaitInstr*>(we->getInstr());
WaitInstr* instr = we->getInstr();
string res = instr->getResource();
TraceWaitEvent* a = new TraceWaitEvent(we->getLastTime(),
task->getID(), res);
if (toFile) a->write(_os);
else data.push_back(a);
} else if (dynamic_cast<SignalEvt*>(e) != NULL) {
DBGPRINT("SignalEvt");
SignalEvt* se = dynamic_cast<SignalEvt*>(e);
//SignalInstr* instr = dynamic_cast<SignalInstr*>(se->getInstr());
SignalInstr* instr = se->getInstr();
string res = instr->getResource();
TraceSignalEvent* a = new TraceSignalEvent(se->getLastTime(),
task->getID(), res);
if (toFile) a->write(_os);
else data.push_back(a);
} else if (dynamic_cast<SchedEvt*>(e) != NULL) {
DBGPRINT("SchedEvt");
SchedEvt* tse = dynamic_cast<SchedEvt*>(e);
TraceSchedEvent* a = new TraceSchedEvent(tse->getLastTime(),
task->getID(), tse->getCPU());
if (toFile) a->write(_os);
else data.push_back(a);
// } else if (dynamic_cast<DlinePostEvt*>(e) != NULL) {
// DBGPRINT("DlinePostEvt");
// DlinePostEvt* dpe = dynamic_cast<DlinePostEvt*>(e);
// TraceDlinePostEvent* a = new TraceDlinePostEvent(dpe->getLastTime(),
// task->getID(),
// dpe->getPrevDline(),
// dpe->getPostDline());
// if (toFile) a->write(_os);
// else data.push_back(a);
} else if (dynamic_cast<DeadEvt*>(e) != NULL) {
DBGPRINT("DlineMissEvt");
DeadEvt* de = dynamic_cast<DeadEvt*>(e);
TraceDlineMissEvent* a = new TraceDlineMissEvent(de->getLastTime(),
task->getID());
if (toFile) a->write(_os);
else data.push_back(a);
}
if (toFile) _os.flush();
}
}
|
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.http import <API key>
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
def centres(request):
#PythonCenter
return render(request, 'centres/centres.html')
def upload(request):
return render(request, 'centres/upload.html')
def uploadfile(request):
import os
if request.method == "POST": # POST
myFile =request.FILES.get("myfile", None) # None
if not myFile:
#return HttpResponse("no files for upload!")
return render(request, 'centres/upload.html',{'what':'no file for upload!'})
upfile = open(os.path.join("D:\\xHome\\data\\upload",myFile.name),'wb+')
for chunk in myFile.chunks():
upfile.write(chunk)
upfile.close()
#return HttpResponse("upload over!")
return render(request, 'centres/upload.html', {'what':'upload over!'})
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Super Martin: Globals</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Super Martin
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.6 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li class="current"><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li class="current"><a href="globals.html"><span>All</span></a></li>
<li><a href="globals_func.html"><span>Functions</span></a></li>
<li><a href="globals_defs.html"><span>Macros</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="globals.html#index_a"><span>a</span></a></li>
<li><a href="globals_b.html#index_b"><span>b</span></a></li>
<li><a href="globals_c.html#index_c"><span>c</span></a></li>
<li><a href="globals_d.html#index_d"><span>d</span></a></li>
<li><a href="globals_e.html#index_e"><span>e</span></a></li>
<li><a href="globals_f.html#index_f"><span>f</span></a></li>
<li><a href="globals_g.html#index_g"><span>g</span></a></li>
<li><a href="globals_i.html#index_i"><span>i</span></a></li>
<li><a href="globals_j.html#index_j"><span>j</span></a></li>
<li><a href="globals_k.html#index_k"><span>k</span></a></li>
<li><a href="globals_l.html#index_l"><span>l</span></a></li>
<li><a href="globals_m.html#index_m"><span>m</span></a></li>
<li><a href="globals_n.html#index_n"><span>n</span></a></li>
<li class="current"><a href="globals_o.html#index_o"><span>o</span></a></li>
<li><a href="globals_p.html#index_p"><span>p</span></a></li>
<li><a href="globals_r.html#index_r"><span>r</span></a></li>
<li><a href="globals_s.html#index_s"><span>s</span></a></li>
<li><a href="globals_t.html#index_t"><span>t</span></a></li>
<li><a href="globals_u.html#index_u"><span>u</span></a></li>
<li><a href="globals_w.html#index_w"><span>w</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Macros</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
<div class="textblock">Here is a list of all documented functions, variables, defines, enums, and typedefs with links to the documentation:</div>
<h3><a class="anchor" id="index_o"></a>- o -</h3><ul>
<li>openFile()
: <a class="el" href="file_8c.html#<API key>">file.c</a>
, <a class="el" href="file_8h.html#<API key>">file.h</a>
</li>
<li>openLevel()
: <a class="el" href="file__level_8h.html#<API key>">file_level.h</a>
, <a class="el" href="file__level_8c.html#<API key>">file_level.c</a>
</li>
<li>optionMenu()
: <a class="el" href="menu__option_8c.html#<API key>">menu_option.c</a>
, <a class="el" href="menu__option_8h.html#<API key>">menu_option.h</a>
</li>
<li>outOfList()
: <a class="el" href="enemies_8h.html#<API key>">enemies.h</a>
, <a class="el" href="enemies_8c.html#<API key>">enemies.c</a>
</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Mon Jun 2 2014 17:19:18 for Super Martin by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.6
</small></address>
</body>
</html>
|
import cv2
import numpy as np
np.set_printoptions(threshold=np.nan)
import util as util
import edge_detect
import lineseg
import drawedgelist
# img = cv2.imread("img/Slide2.jpg", 0)
img = cv2.imread("unsorted/Unit Tests/lambda.png", 0)
im_size = img.shape
returnedCanny = cv2.Canny(img, 50, 150, apertureSize = 3)
cv2.imshow("newcanny", returnedCanny)
skel_dst = util.morpho(returnedCanny)
out = edge_detect.mask_contours(edge_detect.create_img(skel_dst))
res = []
# print(np.squeeze(out[0]))
# print(out[0][0])
for i in range(len(out)):
# Add the first point to the end so the shape closes
current = np.squeeze(out[i])
# print('current', current)
# print('first', out[i][0])
if current.shape[0] > 2:
# res.append(np.concatenate((current, out[i][0])))
# print(res[-1])
res.append(current)
# print(np.concatenate((np.squeeze(out[i]), out[i][0])))
res = np.array(res)
util.sqz_contours(res)
res = lineseg.lineseg(np.array([res[1]]), tol=5)
print(res, "res")
"""
for x in range(len(res)):
for y in range(lan ):
"""
drawedgelist.drawedgelist(res, img)
"""
seglist = []
for i in range(res.shape[0]):
# print('shape', res[i].shape)
if res[i].shape[0] > 2:
# print(res[i])
# print(res[i][0])
seglist.append(np.concatenate((res[i], [res[i][0]])))
else:
seglist.append(res[i])
seglist = np.array(seglist)
"""
#print(seglist, "seglist")
#print(len(seglist), "seglist len")
#print(seglist.shape, "seglistshape")
#drawedgelist.drawedgelist(seglist)
|
"use strict";
module.exports = function <API key>( baseUrl,
app,
opts ){
var controller = opts.controller;
var listRouter = app.route( baseUrl );
if( opts.all ){
listRouter = listRouter.all( opts.all );
}
if( opts.list ){
listRouter.get( opts.list );
}
if( opts.create ){
listRouter.post( opts.create );
}
listRouter.get( controller.list )
.post( controller.create );
var resourceRouter = app.route( baseUrl + "/:_id" );
if( opts.all ){
resourceRouter.all( opts.all );
}
if( opts.retrieve ){
resourceRouter.get(opts.retrieve);
}
if(opts.update){
resourceRouter.patch(opts.update);
}
if(opts.remove){
resourceRouter.delete(opts.remove);
}
resourceRouter.get( controller.retrieve )
.patch( controller.update )
.delete( controller.remove );
return {
list: listRouter,
resources: resourceRouter
};
};
|
package it.ads.activitiesmanager.model.dao;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
//Segnala che si tratta di una classe DAO (o Repository)
@Repository
//Significa che tutti i metodi della classe sono definiti come @Transactional
@Transactional
public abstract class AbstractDao<T extends Serializable> {
private Class<T> c;
@PersistenceContext
EntityManager em;
public final void setClass(Class<T> c){
this.c = c;
}
public T find(Integer id) {
return em.find(c,id);
}
public List<T> findAll(){
String SELECT = "SELECT * FROM " + c.getName();
Query query = em.createQuery(SELECT);
return query.getResultList();
}
public void save(T entity){
em.persist(entity);
}
public void update(T entity){
em.merge(entity);
}
public void delete(T entity){
em.remove(entity);
}
public void deleteById(Integer id){
T entity = find(id);
delete(entity);
}
}
|
#include "VRConstructionKit.h"
#include "selection/VRSelector.h"
#include "core/objects/geometry/VRGeometry.h"
#include "core/objects/material/VRMaterial.h"
#include "core/utils/toString.h"
#include "core/utils/VRFunction.h"
#include "core/setup/devices/VRDevice.h"
#include "core/setup/devices/VRSignal.h"
using namespace OSG;
VRConstructionKit::VRConstructionKit() {
snapping = VRSnappingEngine::create();
selector = VRSelector::create();
onSnap = VRSnappingEngine::VRSnapCb::create("on_snap_callback", bind(&VRConstructionKit::on_snap, this, placeholders::_1));
snapping->getSignalSnap()->add(onSnap);
}
VRConstructionKit::~VRConstructionKit() {}
<API key> VRConstructionKit::create() { return <API key>(new VRConstructionKit()); }
void VRConstructionKit::clear() {
objects.clear();
selector->clear();
snapping->clear();
}
VRSnappingEnginePtr VRConstructionKit::getSnappingEngine() { return snapping; }
VRSelectorPtr VRConstructionKit::getSelector() { return selector; }
vector<VRObjectPtr> VRConstructionKit::getObjects() {
vector<VRObjectPtr> res;
for (auto m : objects) res.push_back(m.second);
return res;
}
bool VRConstructionKit::on_snap(VRSnappingEngine::EventSnapWeakPtr we) {
if (!doConstruction) return true;
auto e = we.lock();
if (!e) return true;
if (!e->snap) { breakup(e->o1); return true; }
if (!e->o1 || !e->o2) return true;
VRObjectPtr p1 = e->o1->getDragParent();
VRObjectPtr p2 = e->o2->getParent();
if (p1 == 0 || p2 == 0) return true;
if (p1 == p2) if (p1->hasTag("kit_group")) return true;
if (p2->hasTag("kit_group")) {
e->o1->rebaseDrag(p2);
e->o1->setPickable(false);
e->o2->setPickable(false);
e->o1->setWorldMatrix(e->m);
return true;
}
VRTransformPtr group = VRTransform::create("kit_group");
group->setPersistency(0);
group->setPickable(true);
group->addAttachment("kit_group", 0);
p2->addChild(group);
e->o1->rebaseDrag(group);
Matrix4d m = e->o2->getWorldMatrix();
e->o2->switchParent(group);
e->o1->setPickable(false);
e->o2->setPickable(false);
e->o1->setWorldMatrix(e->m);
e->o2->setWorldMatrix(m);
return true;
}
int VRConstructionKit::ID() {
static int i = 0; i++;
return i;
}
void VRConstructionKit::breakup(VRTransformPtr obj) {
if (!doConstruction) return;
if (obj == 0) return;
auto p = obj->getParent();
if (p == 0) return;
if (p->hasTag("kit_group")) {
obj->switchParent( p->getParent() );
obj->setPickable(true);
return;
}
p = obj->getDragParent();
if (p == 0) return;
if (p->hasTag("kit_group")) {
obj->rebaseDrag( p->getParent() );
obj->setPickable(true);
}
}
int VRConstructionKit::addAnchorType(float size, Color3f color) {
auto g = VRGeometry::create("anchor");
string bs = toString(size);
g->setPrimitive("Box " + bs + " " + bs + " " + bs + " 1 1 1");
auto m = VRMaterial::create("anchor");
m->setDiffuse(color);
g->setMaterial(m);
int id = ID();
anchors[id] = g;
return id;
}
void VRConstructionKit::toggleConstruction(bool active) {
doConstruction = active;
}
void VRConstructionKit::addObject(VRTransformPtr t) {
objects[t.get()] = t;
snapping->addObject(t);
}
void VRConstructionKit::remObject(VRTransformPtr t) {
objects.erase(t.get());
snapping->remObject(t);
}
VRGeometryPtr VRConstructionKit::addObjectAnchor(VRTransformPtr t, int a, Vec3d pos, float radius) {
if (!anchors.count(a)) return 0;
Vec3d d(0,1,0);
Vec3d u(1,0,0);
VRGeometryPtr anc = static_pointer_cast<VRGeometry>(anchors[a]->duplicate());
anc->setTransform(pos, d, u);
anc->show();
anc->switchParent(t);
snapping->addObjectAnchor(t, anc);
snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(Vec3d(), d, u), radius, 0, t );
//snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(Vec3d(), Vec3d(1,0,0), Vec3d(0,1,0)), radius, 0, t );
//snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(), radius, 0, t );
return anc;
}
|
## A Vim plugin offers Nginx/Openresty syntax highlight and directives completion

This little plugin offers:
1. syntax highlight for Nginx configuration, with addition OpenResty enhancement.
1. syntax highlight for LuaJIT source file, with adddition OpenResty API highlight.
1. syntax-based directives completion.
# Support version
This plugin supports OpenResty v1.21.4.
# How to use
First of all, install this plugin with your favorite plugin manager.
The syntax highlight is enabled once your file is detected as Nginx configuration.
If Vim doesn't recognize the file type, you could add this to your `.vimrc`:
autocmd BufRead,BufNewFile <API key>(s) set filetype=nginx
For example, `autocmd BufRead,BufNewFile nginx_*.conf.tpl set filetype=nginx`.
To complete the directives, type part of the word and then type `Ctrl+x Ctrl+o` to trigger it.
If you are using [YouCompleteMe](https://github.com/Valloric/YouCompleteMe), set `let g:<API key> = 1` in your `.vimrc`.
# Known issue
There is a limit to render Lua snippet inside `_by_lua_block` directives. You need to close the block with `}` in separate line, and `}` should have
the same indent with the `{`. It is a hack to distinguish from `}` of the inner Lua snippet.
Anyway, if your configuration is in good format, the highlight should work smoothly.
|
#include "Ares.h"
/*
Description:
Function that is called when the library is loaded, use this as an entry point.
*/
int __attribute__((constructor)) Ares() {
SDL2::SetupSwapWindow();
return 0;
}
|
#!/usr/bin/env python
# setup of the grid parameters
# default queue used for training
training_queue = { 'queue':'q1dm', 'memfree':'16G', 'pe_opt':'pe_mth 2', 'hvmem':'8G', 'io_big':True }
# the queue that is used solely for the final ISV training step
isv_training_queue = { 'queue':'q1wm', 'memfree':'32G', 'pe_opt':'pe_mth 4', 'hvmem':'8G' }
# number of audio files that one job should preprocess
<API key> = 1000
preprocessing_queue = {}
# number of features that one job should extract
<API key> = 600
extraction_queue = { 'queue':'q1d', 'memfree':'8G' }
# number of features that one job should project
<API key> = 600
projection_queue = { 'queue':'q1d', 'hvmem':'8G', 'memfree':'8G' }
# number of models that one job should enroll
<API key> = 20
enrol_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True }
# number of models that one score job should process
<API key> = 20
score_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True }
grid_type = 'local' # on Idiap grid
|
package ca.six.tomato.util;
import org.json.JSONArray;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.<API key>;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowEnvironment;
import java.io.File;
import ca.six.tomato.BuildConfig;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
@RunWith(<API key>.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class DataUtilsTest {
@Test
public void testFile() {
File dstFile = ShadowEnvironment.<API key>();
assertTrue(dstFile.exists());
System.out.println("szw isDirectory = " + dstFile.isDirectory()); //=> true
System.out.println("szw isExisting = " + dstFile.exists()); //=> true
System.out.println("szw path = " + dstFile.getPath());
}
@Test
public void testWriteString(){
File dstFile = ShadowEnvironment.<API key>();
String path = dstFile.getPath() +"/tmp";
DataUtilKt.write("abc", path);
String ret = DataUtilKt.read(path, false);
assertEquals("abc", ret);
}
@Test
public void testWriteJSON(){
File dstFile = ShadowEnvironment.<API key>();
String path = dstFile.getPath() +"/tmp";
String content = " {\"clock\": \"clock1\", \"work\": 40, \"short\": 5, \"long\": 15}\n" +
" {\"clock\": \"clock2\", \"work\": 30, \"short\": 5, \"long\": 15}\n" +
" {\"clock\": \"clock3\", \"work\": 45, \"short\": 5, \"long\": 15}";
DataUtilKt.write(content, path);
JSONArray ret = DataUtilKt.read(path);
System.out.println("szw, ret = "+ret.toString());
assertNotNull(ret);
}
}
|
/*
* The basic test codes to check the AnglogIn.
*/
#include "mbed.h"
static AnalogIn ain_x(A6); // connect joistics' x axis to A6 pin of mbed
static AnalogIn ain_y(A5); // connect joistics' y axis to A5 pin of mbed
static void printAnalogInput(AnalogIn *xin, AnalogIn *yin)
{
uint8_t point[2] = { 0 };
point[0] = (uint8_t)(xin->read()*100.0f + 0.5);
point[1] = (uint8_t)(yin->read()*100.0f + 0.5);
printf("x: %d, y: %d\n", point[0], point[1]);
}
int main()
{
while(1)
{
printAnalogInput(&ain_x, &ain_y);
wait(0.2f);
}
}
|
/*jslint browser: true, nomen: true, sloppy: true*/
/*globals Backbone, Crashmapper */
/**
* @param {Object} options
* @constructor
* @extends Backbone.View
*/
Crashmapper.AppView = Backbone.View.extend({
id: 'app',
/**
* @this {Crashmapper.AppView}
*/
initialize: function () {
this.about = new Crashmapper.AboutView({}).render();
this.about.$el.appendTo(this.$el).hide();
this.map = new Crashmapper.MapView({});
this.map.$el.appendTo(this.$el);
},
/**
* @this {Crashmapper.AppView}
*/
render: function () {
return this;
}
});
|
FROM golang:alpine AS builder
RUN apk add --update git && go get github.com/fffaraz/microdns
FROM alpine:latest
COPY --from=builder /go/bin/microdns /usr/local/bin
ENTRYPOINT ["microdns"]
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Safir.Dob.Typesystem
{
<summary>
Base class for all Containers.
<para/>
This class contains common functionality for all Containers.
Basically this amounts to the interface for nullability and
the change flag.
</summary>
abstract public class ContainerBase
{
<summary>
Default Constructor.
<para/>
Construct a container that is not changed.
</summary>
public ContainerBase()
{
m_bIsChanged = false;
}
<summary>
Is the container set to null?
</summary>
<returns>True if the container is set to null.</returns>
abstract public bool IsNull();
<summary>
Set the container to null.
</summary>
abstract public void SetNull();
<summary>
Is the change flag set on the container?
<para/>
The change flag gets updated every time the contained value changes.
<para/>
Note: If this is a container containing objects this call will recursively
check change flags in the contained objects.
</summary>
<returns> True if the containers change flag is set.</returns>
virtual public bool IsChanged()
{
return m_bIsChanged;
}
<summary>
Set the containers change flag.
<para/>
It should be fairly unusual for an application to have to use this
operation. There is nothing dangerous about it, but are you sure this
is the operation you were after?
<para/>
The change flag is how receivers of objects can work out what the
sender really wanted done on the object.
<para/>
Note: If this is a container containing one or more objects this call
will recursively set all the change flags in the contained objects.
</summary>
<param name="changed">The value to set the change flag(s) to.</param>
virtual public void SetChanged(bool changed)
{
m_bIsChanged = changed;
}
#region Cloning
<summary>
Create a copy of the Container.
<para>
This method is deprecated.
</para>
</summary>
public dynamic Clone()
{
return this.DeepClone();
}
<summary>
Copy.
</summary>
<param name="other">Other ContainerBase.</param>
virtual public void Copy(ContainerBase other)
{
ShallowCopy(other);
}
#endregion
<summary>
Flag accessible from subclasses.
</summary>
protected internal bool m_bIsChanged;
virtual internal void ShallowCopy(ContainerBase other)
{
if (this.GetType() != other.GetType())
{
throw new <API key>("Invalid call to Copy, containers are not of same type");
}
m_bIsChanged = other.m_bIsChanged;
}
}
}
|
#!/usr/bin/python2
# -*- coding: utf-8 -*-
# coding=utf-8
import unittest
from datetime import datetime
from lib.escala import Escala
import dirs
dirs.DEFAULT_DIR = dirs.TestDir()
class FrameTest(unittest.TestCase):
def setUp(self):
self.escala = Escala('fixtures/escala.xml')
self.dir = dirs.TestDir()
self.maxDiff = None
def tearDown(self):
pass
def <API key>(self):
p_voo = self.escala.escalas[0]
self.assertEqual(p_voo.activity_date, datetime(2013, 3, 1, 11, 36))
self.assertEqual(p_voo.present_location, 'VCP')
self.assertEqual(p_voo.flight_no, '4148')
self.assertEqual(p_voo.origin, 'VCP')
self.assertEqual(p_voo.destination, 'GYN')
self.assertEqual(p_voo.actype, 'E95')
self.assertTrue(p_voo.checkin)
self.assertEqual(p_voo.checkin_time, datetime(2013, 3, 1, 10, 36))
self.assertEqual(p_voo.std, datetime(2013, 3, 1, 13, 13))
self.assertEqual(p_voo.sta, datetime(2013, 3, 1, 11, 36))
self.assertEqual(p_voo.activity_info, 'AD4148')
self.assertFalse(p_voo.duty_design)
def <API key>(self):
p_voo = self.escala.escalas[17]
self.assertEqual(p_voo.activity_date, datetime(2013, 10, 28, 3, 0))
self.assertEqual(p_voo.present_location, 'VCP')
self.assertEqual(p_voo.flight_no, None)
self.assertEqual(p_voo.origin, 'VCP')
self.assertEqual(p_voo.destination, 'VCP')
self.assertEqual(p_voo.activity_info, 'P04')
self.assertEqual(p_voo.actype, None)
self.assertEqual(p_voo.sta, datetime(2013, 10, 28, 3, 0))
self.assertEqual(p_voo.std, datetime(2013, 10, 28, 15, 0))
self.assertFalse(p_voo.checkin)
self.assertEqual(p_voo.checkin_time, None)
self.assertFalse(p_voo.duty_design)
def <API key>(self):
p_voo = self.escala.escalas[18]
self.assertEqual(p_voo.activity_date, datetime(2013, 10, 29, 4, 58))
self.assertEqual(p_voo.present_location, 'VCP')
self.assertEqual(p_voo.flight_no, '4050')
self.assertEqual(p_voo.origin, 'VCP')
self.assertEqual(p_voo.destination, 'FLN')
self.assertEqual(p_voo.activity_info, 'AD4050')
self.assertEqual(p_voo.actype, 'E95')
self.assertEqual(p_voo.sta, datetime(2013, 10, 29, 4, 58))
self.assertEqual(p_voo.std, datetime(2013, 10, 29, 6, 15))
self.assertTrue(p_voo.checkin)
self.assertEqual(p_voo.checkin_time, datetime(2013, 10, 29, 5, 8))
self.assertFalse(p_voo.duty_design)
self.assertEqual(p_voo.horas_de_voo, '1:17')
def <API key>(self):
p_voo = self.escala.escalas[25]
self.assertFalse(p_voo.checkin)
self.assertEqual(p_voo.checkin_time, None)
self.assertEqual(p_voo.flight_no, '2872')
self.assertEqual(p_voo.activity_info, 'AD2872')
def <API key>(self):
s_horas = {
'h_diurno': '6:40',
'h_noturno': '6:47',
'h_total_voo': '13:27',
'h_faixa2': '0:00',
'h_sobreaviso': '40:00',
'h_reserva': '29:13'
}
self.assertEqual(self.escala.soma_horas(), s_horas)
def test_ics(self):
"""
Check ICS output
"""
escala = Escala('fixtures/escala_ics.xml')
f_result = open(self.dir.get_data_dir() + 'fixtures/escala.ics')
self.assertEqual(escala.ics(), f_result.read())
f_result.close()
def test_csv(self):
"""
Check CSV output
"""
f_result = open(self.dir.get_data_dir() + 'fixtures/escala.csv')
self.assertEqual(self.escala.csv(), f_result.read())
f_result.close()
def main():
unittest.main()
if __name__ == '__main__':
main()
|
package net.thevpc.upa.impl;
import net.thevpc.upa.*;
import net.thevpc.upa.impl.transform.<API key>;
import net.thevpc.upa.impl.util.NamingStrategy;
import net.thevpc.upa.impl.util.<API key>;
import net.thevpc.upa.impl.util.PlatformUtils;
import net.thevpc.upa.types.*;
import net.thevpc.upa.exceptions.UPAException;
import net.thevpc.upa.filters.FieldFilter;
import net.thevpc.upa.types.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public abstract class AbstractField extends AbstractUPAObject implements Field, Comparable<Object> {
protected Entity entity;
protected EntityItem parent;
protected DataType dataType;
protected Formula persistFormula;
protected int persistFormulaOrder;
protected Formula updateFormula;
protected int updateFormulaOrder;
protected Formula queryFormula;
protected Object defaultObject;
protected SearchOperator searchOperator = SearchOperator.DEFAULT;
protected DataTypeTransform typeTransform;
protected HashMap<String, Object> properties;
protected FlagSet<UserFieldModifier> userModifiers = FlagSets.noneOf(UserFieldModifier.class);
protected FlagSet<UserFieldModifier> <API key> = FlagSets.noneOf(UserFieldModifier.class);
protected FlagSet<FieldModifier> effectiveModifiers = FlagSets.noneOf(FieldModifier.class);
protected boolean closed;
protected Object unspecifiedValue = UnspecifiedValue.DEFAULT;
private AccessLevel persistAccessLevel = AccessLevel.READ_WRITE;
private AccessLevel updateAccessLevel = AccessLevel.READ_WRITE;
private AccessLevel readAccessLevel = AccessLevel.READ_WRITE;
private ProtectionLevel <API key> = ProtectionLevel.PUBLIC;
private ProtectionLevel <API key> = ProtectionLevel.PUBLIC;
private ProtectionLevel readProtectionLevel = ProtectionLevel.PUBLIC;
private FieldPersister fieldPersister;
private PropertyAccessType accessType;
private List<Relationship> <API key>;
private List<Relationship> <API key>;
private boolean <API key> = false;
private Object _typeDefaultObject = false;
protected AbstractField() {
}
@Override
public String getAbsoluteName() {
return (getEntity() == null ? "?" : getEntity().getName()) + "." + getName();
}
public EntityItem getParent() {
return parent;
}
public void setParent(EntityItem item) {
EntityItem old = this.parent;
EntityItem recent = item;
<API key>.firePropertyChange("parent", old, recent);
this.parent = item;
<API key>.firePropertyChange("parent", old, recent);
}
@Override
public void commitModelChanges() {
<API key> = <API key>();
<API key> = <API key>();
}
public boolean is(FieldFilter filter) throws UPAException {
return filter.accept(this);
}
public boolean isId() throws UPAException {
return getModifiers().contains(FieldModifier.ID);
}
@Override
public boolean isGeneratedId() throws UPAException {
if (!isId()) {
return false;
}
Formula persistFormula = getPersistFormula();
return (persistFormula != null);
}
public boolean isMain() throws UPAException {
return getModifiers().contains(FieldModifier.MAIN);
}
@Override
public boolean isSystem() {
return getModifiers().contains(FieldModifier.SYSTEM);
}
public boolean isSummary() throws UPAException {
return getModifiers().contains(FieldModifier.SUMMARY);
}
public List<Relationship> <API key>() {
return <API key>;
}
public List<Relationship> <API key>() {
return <API key>;
}
protected List<Relationship> <API key>() {
List<Relationship> relations = new ArrayList<Relationship>();
for (Relationship r : getPersistenceUnit().<API key>(getEntity())) {
Field entityField = r.getSourceRole().getEntityField();
if (entityField != null && entityField.equals(this)) {
relations.add(r);
} else {
List<Field> fields = r.getSourceRole().getFields();
for (Field field : fields) {
if (field.equals(this)) {
relations.add(r);
}
}
}
}
return PlatformUtils.trimToSize(relations);
}
protected List<Relationship> <API key>() {
List<Relationship> relations = new ArrayList<Relationship>();
for (Relationship r : getPersistenceUnit().<API key>(getEntity())) {
Field entityField = r.getSourceRole().getEntityField();
if (entityField != null && entityField.equals(this)) {
relations.add(r);
} else {
List<Field> fields = r.getSourceRole().getFields();
for (Field field : fields) {
if (field.equals(this)) {
relations.add(r);
}
}
}
}
return PlatformUtils.trimToSize(relations);
}
public void setFormula(Formula formula) {
setPersistFormula(formula);
setUpdateFormula(formula);
}
@Override
public void setFormula(String formula) {
setFormula(formula == null ? null : new ExpressionFormula(formula));
}
public void setPersistFormula(Formula formula) {
this.persistFormula = formula;
}
public void setUpdateFormula(Formula formula) {
this.updateFormula = formula;
}
@Override
public void setFormulaOrder(int order) {
<API key>(order);
<API key>(order);
}
public int <API key>() {
return updateFormulaOrder;
}
@Override
public void <API key>(int order) {
this.updateFormulaOrder = order;
}
public int <API key>() {
return persistFormulaOrder;
}
@Override
public void <API key>(int order) {
this.persistFormulaOrder = order;
}
public Formula getUpdateFormula() {
return updateFormula;
}
@Override
public void setUpdateFormula(String formula) {
setUpdateFormula(formula == null ? null : new ExpressionFormula(formula));
}
public Formula getSelectFormula() {
return queryFormula;
}
@Override
public void setSelectFormula(String formula) {
setSelectFormula(formula == null ? null : new ExpressionFormula(formula));
}
public void setSelectFormula(Formula queryFormula) {
this.queryFormula = queryFormula;
}
// public boolean isRequired() throws UPAException {
// return (!isReadOnlyOnPersist() || !isReadOnlyOnUpdate()) && !getDataType().isNullable();
public String getPath() {
EntityItem parent = getParent();
return parent == null ? ("/" + getName()) : (parent.getPath() + "/" + getName());
}
@Override
public PersistenceUnit getPersistenceUnit() {
return entity.getPersistenceUnit();
}
public Formula getPersistFormula() {
return persistFormula;
}
@Override
public void setPersistFormula(String formula) {
setPersistFormula(formula == null ? null : new ExpressionFormula(formula));
}
public Entity getEntity() {
return entity;
}
public void setEntity(Entity entity) {
this.entity = entity;
}
public DataType getDataType() {
return dataType;
}
/**
* called by <API key> / Table You should not use it
*
* @param datatype datatype
*/
@Override
public void setDataType(DataType datatype) {
this.dataType = datatype;
if (!getDataType().isNullable()) {
_typeDefaultObject = getDataType().getDefaultValue();
} else {
_typeDefaultObject = null;
}
}
public Object getDefaultValue() {
if (<API key>) {
Object o = ((CustomDefaultObject) defaultObject).getObject();
if (o == null) {
o = _typeDefaultObject;
}
return o;
} else {
Object o = defaultObject;
if (o == null) {
o = _typeDefaultObject;
}
return o;
}
}
public Object getDefaultObject() {
return defaultObject;
}
/**
* called by <API key> / Table You should not use it
*
* @param o default value witch may be san ObjectHandler
*/
public void setDefaultObject(Object o) {
defaultObject = o;
if (o instanceof CustomDefaultObject) {
<API key> = true;
}
}
public FlagSet<FieldModifier> getModifiers() {
return effectiveModifiers;
}
public void <API key>(FlagSet<FieldModifier> effectiveModifiers) {
this.effectiveModifiers = effectiveModifiers;
}
// public void addModifiers(long modifiers) {
// setModifiers(getModifiers() | modifiers);
// public void removeModifiers(long modifiers) {
// setModifiers(getModifiers() & ~modifiers);
// public Expression getExpression() {
// return formula == null ? null : formula.getExpression();
@Override
public boolean equals(Object other) {
return !(other == null || !(other instanceof Field)) && compareTo(other) == 0;
}
public int compareTo(Object other) {
if (other == this) {
return 0;
}
if (other == null) {
return 1;
}
Field f = (Field) other;
NamingStrategy comp = <API key>.getNamingStrategy(getEntity().getPersistenceUnit().<API key>());
String s1 = entity != null ? comp.getUniformValue(entity.getName()) : "";
String s2 = f.getName() != null ? comp.getUniformValue(f.getEntity().getName()) : "";
int i = s1.compareTo(s2);
if (i != 0) {
return i;
} else {
String s3 = getName() != null ? comp.getUniformValue(getName()) : "";
String s4 = f.getName() != null ? comp.getUniformValue(f.getName()) : "";
i = s3.compareTo(s4);
return i;
}
}
@Override
public FlagSet<UserFieldModifier> getUserModifiers() {
return userModifiers;
}
// public void resetModifiers() {
// modifiers = 0;
public void setUserModifiers(FlagSet<UserFieldModifier> modifiers) {
this.userModifiers = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers;
}
@Override
public FlagSet<UserFieldModifier> <API key>() {
return <API key>;
}
public void <API key>(FlagSet<UserFieldModifier> modifiers) {
this.<API key> = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers;
}
@Override
public String toString() {
return getAbsoluteName();
}
@Override
public void close() throws UPAException {
this.closed = true;
}
public boolean isClosed() {
return closed;
}
@Override
public Object getUnspecifiedValue() {
return unspecifiedValue;
}
@Override
public void setUnspecifiedValue(Object o) {
this.unspecifiedValue = o;
}
public Object <API key>() {
final Object fuv = getUnspecifiedValue();
if (UnspecifiedValue.DEFAULT.equals(fuv)) {
return getDataType().<API key>();
} else {
return fuv;
}
}
public boolean isUnspecifiedValue(Object value) {
Object v = <API key>();
return (v == value || (v != null && v.equals(value)));
}
public AccessLevel <API key>() {
return persistAccessLevel;
}
public void <API key>(AccessLevel persistAccessLevel) {
if (PlatformUtils.<API key>(AccessLevel.class, persistAccessLevel)) {
persistAccessLevel = AccessLevel.READ_WRITE;
}
this.persistAccessLevel = persistAccessLevel;
}
public AccessLevel <API key>() {
return updateAccessLevel;
}
public void <API key>(AccessLevel updateAccessLevel) {
if (PlatformUtils.<API key>(AccessLevel.class, updateAccessLevel)) {
updateAccessLevel = AccessLevel.READ_WRITE;
}
this.updateAccessLevel = updateAccessLevel;
}
public AccessLevel getReadAccessLevel() {
return readAccessLevel;
}
public void setReadAccessLevel(AccessLevel readAccessLevel) {
if (PlatformUtils.<API key>(AccessLevel.class, readAccessLevel)) {
readAccessLevel = AccessLevel.READ_ONLY;
}
if (readAccessLevel == AccessLevel.READ_WRITE) {
readAccessLevel = AccessLevel.READ_ONLY;
}
this.readAccessLevel = readAccessLevel;
}
public void setAccessLevel(AccessLevel accessLevel) {
<API key>(accessLevel);
<API key>(accessLevel);
setReadAccessLevel(accessLevel);
}
public ProtectionLevel <API key>() {
return <API key>;
}
public void <API key>(ProtectionLevel <API key>) {
if (PlatformUtils.<API key>(ProtectionLevel.class, <API key>)) {
<API key> = ProtectionLevel.PUBLIC;
}
this.<API key> = <API key>;
}
public ProtectionLevel <API key>() {
return <API key>;
}
public void <API key>(ProtectionLevel <API key>) {
if (PlatformUtils.<API key>(ProtectionLevel.class, <API key>)) {
<API key> = ProtectionLevel.PUBLIC;
}
this.<API key> = <API key>;
}
public ProtectionLevel <API key>() {
return readProtectionLevel;
}
public void <API key>(ProtectionLevel readProtectionLevel) {
if (PlatformUtils.<API key>(ProtectionLevel.class, readProtectionLevel)) {
readProtectionLevel = ProtectionLevel.PUBLIC;
}
this.readProtectionLevel = readProtectionLevel;
}
public void setProtectionLevel(ProtectionLevel persistLevel) {
<API key>(persistLevel);
<API key>(persistLevel);
<API key>(persistLevel);
}
public SearchOperator getSearchOperator() {
return searchOperator;
}
public void setSearchOperator(SearchOperator searchOperator) {
this.searchOperator = searchOperator;
}
public FieldPersister getFieldPersister() {
return fieldPersister;
}
public void setFieldPersister(FieldPersister fieldPersister) {
this.fieldPersister = fieldPersister;
}
public DataTypeTransform getTypeTransform() {
return typeTransform;
}
@Override
public DataTypeTransform <API key>() {
DataTypeTransform t = getTypeTransform();
if (t == null) {
DataType d = getDataType();
if (d != null) {
t = new <API key>(d);
}
}
return t;
}
public void setTypeTransform(DataTypeTransform transform) {
this.typeTransform = transform;
}
public PropertyAccessType <API key>() {
return accessType;
}
public void <API key>(PropertyAccessType accessType) {
this.accessType = accessType;
}
@Override
public Object getMainValue(Object instance) {
Object v = getValue(instance);
if (v != null) {
Relationship <API key> = <API key>();
if (<API key> != null) {
v = <API key>.getTargetEntity().getBuilder().getMainValue(v);
}
}
return v;
}
@Override
public Object getValue(Object instance) {
if (instance instanceof Document) {
return ((Document) instance).getObject(getName());
}
return getEntity().getBuilder().getProperty(instance, getName());
}
@Override
public void setValue(Object instance, Object value) {
getEntity().getBuilder().setProperty(instance, getName(), value);
}
@Override
public void check(Object value) {
getDataType().check(value, getName(), null);
}
@Override
public boolean isManyToOne() {
return getDataType() instanceof ManyToOneType;
}
@Override
public boolean isOneToOne() {
return getDataType() instanceof OneToOneType;
}
@Override
public <API key> <API key>() {
DataType dataType = getDataType();
if (dataType instanceof ManyToOneType) {
return (<API key>) ((ManyToOneType) dataType).getRelationship();
}
return null;
}
@Override
public <API key> <API key>() {
DataType dataType = getDataType();
if (dataType instanceof OneToOneType) {
return (<API key>) ((OneToOneType) dataType).getRelationship();
}
return null;
}
protected void fillFieldInfo(FieldInfo i) {
Field f = this;
fillObjectInfo(i);
DataTypeInfo dataType = f.getDataType() == null ? null : f.getDataType().getInfo();
if (dataType != null) {
UPAI18n d = getPersistenceGroup().getI18nOrDefault();
if (f.getDataType() instanceof EnumType) {
List<Object> values = ((EnumType) f.getDataType()).getValues();
StringBuilder v = new StringBuilder();
for (Object o : values) {
if (v.length() > 0) {
v.append(",");
}
v.append(d.getEnum(o));
}
dataType.getProperties().put("titles", String.valueOf(v));
}
}
i.setDataType(dataType);
i.setId(f.isId());
i.setGeneratedId(f.isGeneratedId());
i.setModifiers(f.getModifiers().toArray());
i.<API key>(f.<API key>());
i.<API key>(f.<API key>());
i.setReadAccessLevel(f.getReadAccessLevel());
i.<API key>(f.<API key>());
i.<API key>(f.<API key>());
i.<API key>(f.<API key>());
i.<API key>(f.<API key>());
i.<API key>(f.<API key>());
i.<API key>(f.<API key>());
i.setMain(f.isMain());
i.setSystem(f.getModifiers().contains(FieldModifier.SYSTEM));
i.setSummary(f.isSummary());
i.setManyToOne(f.isManyToOne());
i.<API key>(f.<API key>());
Relationship r = f.<API key>();
i.<API key>(r == null ? null : r.getName());
}
@Override
public AccessLevel <API key>(AccessMode mode) {
if (!PlatformUtils.<API key>(AccessMode.class, mode)) {
switch (mode) {
case READ:
return <API key>();
case PERSIST:
return <API key>();
case UPDATE:
return <API key>();
}
}
return AccessLevel.INACCESSIBLE;
}
@Override
public AccessLevel getAccessLevel(AccessMode mode) {
if (!PlatformUtils.<API key>(AccessMode.class, mode)) {
switch (mode) {
case READ:
return getReadAccessLevel();
case PERSIST:
return <API key>();
case UPDATE:
return <API key>();
}
}
return AccessLevel.INACCESSIBLE;
}
@Override
public ProtectionLevel getProtectionLevel(AccessMode mode) {
if (!PlatformUtils.<API key>(AccessMode.class, mode)) {
switch (mode) {
case READ:
return <API key>();
case PERSIST:
return <API key>();
case UPDATE:
return <API key>();
}
}
return ProtectionLevel.PRIVATE;
}
public AccessLevel <API key>() {
if (isSystem()) {
return AccessLevel.INACCESSIBLE;
}
AccessLevel al = <API key>();
ProtectionLevel pl = <API key>();
if (PlatformUtils.<API key>(AccessLevel.class, al)) {
al = AccessLevel.READ_WRITE;
}
if (PlatformUtils.<API key>(ProtectionLevel.class, pl)) {
pl = ProtectionLevel.PUBLIC;
}
boolean hasFormula = getPersistFormula() != null;
if (al == AccessLevel.READ_WRITE && hasFormula) {
al = AccessLevel.READ_ONLY;
}
switch (al) {
case INACCESSIBLE: {
break;
}
case READ_ONLY: {
switch (pl) {
case PRIVATE: {
al = AccessLevel.INACCESSIBLE;
break;
}
case PROTECTED: {
break;
}
case PUBLIC: {
break;
}
}
break;
}
case READ_WRITE: {
switch (pl) {
case PRIVATE: {
al = AccessLevel.READ_ONLY;
break;
}
case PROTECTED: {
if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) {
al = AccessLevel.READ_ONLY;
}
break;
}
case PUBLIC: {
break;
}
}
break;
}
}
if (al != AccessLevel.INACCESSIBLE) {
if (isGeneratedId()) {
al = AccessLevel.INACCESSIBLE;
}
if (!getModifiers().contains(FieldModifier.PERSIST_DEFAULT)) {
al = AccessLevel.INACCESSIBLE;
}
}
return al;
}
public AccessLevel <API key>() {
if (isSystem()) {
return AccessLevel.INACCESSIBLE;
}
AccessLevel al = <API key>();
ProtectionLevel pl = <API key>();
if (PlatformUtils.<API key>(AccessLevel.class, al)) {
al = AccessLevel.READ_WRITE;
}
if (PlatformUtils.<API key>(ProtectionLevel.class, pl)) {
pl = ProtectionLevel.PUBLIC;
}
boolean hasFormula = getUpdateFormula() != null;
if (al == AccessLevel.READ_WRITE && hasFormula) {
al = AccessLevel.READ_ONLY;
}
switch (al) {
case INACCESSIBLE: {
break;
}
case READ_ONLY: {
switch (pl) {
case PRIVATE: {
al = AccessLevel.INACCESSIBLE;
break;
}
case PROTECTED: {
if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) {
al = AccessLevel.INACCESSIBLE;
}
break;
}
case PUBLIC: {
break;
}
}
break;
}
case READ_WRITE: {
switch (pl) {
case PRIVATE: {
al = AccessLevel.READ_ONLY;
break;
}
case PROTECTED: {
if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) {
al = AccessLevel.READ_ONLY;
}
if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) {
al = AccessLevel.INACCESSIBLE;
}
break;
}
case PUBLIC: {
break;
}
}
break;
}
}
if (isId() && al == AccessLevel.READ_WRITE) {
al = AccessLevel.READ_ONLY;
}
if (getModifiers().contains(FieldModifier.UPDATE_DEFAULT)) {
} else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) {
if (al == AccessLevel.READ_WRITE) {
al = AccessLevel.READ_ONLY;
}
} else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) {
if (al == AccessLevel.READ_WRITE) {
al = AccessLevel.READ_ONLY;
}
}
return al;
}
public AccessLevel <API key>() {
if (isSystem()) {
return AccessLevel.INACCESSIBLE;
}
AccessLevel al = getReadAccessLevel();
ProtectionLevel pl = <API key>();
if (PlatformUtils.<API key>(AccessLevel.class, al)) {
al = AccessLevel.READ_WRITE;
}
if (PlatformUtils.<API key>(ProtectionLevel.class, pl)) {
pl = ProtectionLevel.PUBLIC;
}
if (al == AccessLevel.READ_WRITE) {
al = AccessLevel.READ_ONLY;
}
if (al == AccessLevel.READ_ONLY) {
if (!getModifiers().contains(FieldModifier.SELECT)) {
al = AccessLevel.INACCESSIBLE;
}
}
switch (al) {
case INACCESSIBLE: {
break;
}
case READ_ONLY: {
switch (pl) {
case PRIVATE: {
al = AccessLevel.INACCESSIBLE;
break;
}
case PROTECTED: {
if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) {
al = AccessLevel.INACCESSIBLE;
}
break;
}
case PUBLIC: {
break;
}
}
break;
}
}
return al;
}
}
|
#include "../../VM/Handler/Opcode8030Handler.h"
#include "../../VM/Script.h"
namespace Falltergeist
{
namespace VM
{
namespace Handler
{
Opcode8030::Opcode8030(VM::Script *script, std::shared_ptr<ILogger> logger) : OpcodeHandler(script)
{
this->logger = std::move(logger);
}
void Opcode8030::_run()
{
logger->debug() << "[8030] [*] op_while(address, condition)" << std::endl;
auto condition = _script->dataStack()->popLogical();
if (!condition) {
_script->setProgramCounter(_script->dataStack()->popInteger());
}
}
}
}
}
|
MT19937AR_OBJ = mt19937ar.o
MT19937AR_H = mt19937ar.h
.PHONY : all clean help
all: $(MT19937AR_OBJ)
clean:
@echo " CLEAN mt19937ar"
@rm -rf *.o
help:
@echo "possible targets are 'all' 'clean' 'help'"
@echo "'all' - builds $(MT19937AR_OBJ)"
@echo "'clean' - deletes $(MT19937AR_OBJ)"
@echo "'help' - outputs this message"
%.o: %.c $(MT19937AR_H)
@echo " CC $<"
@gcc -flto -fuse-linker-plugin -ffat-lto-objects -flto -fuse-linker-plugin -g -O2 -pipe -ffast-math -Wall -<API key> -Wno-clobbered -Wempty-body -Wno-switch -<API key> -Wshadow -fno-strict-aliasing -DMAXCONN=16384 -I../common -DHAS_TLS -DHAVE_SETRLIMIT -DHAVE_STRNLEN -I/usr/include -<API key> -c $(OUTPUT_OPTION) $<
|
#include "report_mib_feature.h"
#include "<API key>.h"
#include "report_manager.h"
#include "protocol.h"
#include "bus_slave.h"
#include "momo_config.h"
#include "report_log.h"
#include "report_comm_stream.h"
#include "system_log.h"
#include <string.h>
#define <API key> 160 //( 4 * ( ( <API key> + 2 ) / 3) )
extern char <API key>[<API key>+1];
static void <API key>(void)
{
set_momo_state_flag( <API key>, true );
<API key>();
}
static void <API key>(void)
{
set_momo_state_flag( <API key>, false );
<API key>();
}
static void <API key>(void)
{
<API key>( get_momo_state_flag( <API key> ) );
}
static void send_report(void)
{
taskloop_add( post_report, NULL );
}
static void <API key>(void)
{
<API key>( plist_get_int16(0) );
}
static void <API key>(void)
{
<API key>( current_momo_state.report_config.report_interval );
}
static void set_reporting_route(void)
{
update_report_route( (plist_get_int16(0) >> 8) & 0xFF
, plist_get_int16(0) & 0xFF
, (const char*)plist_get_buffer(1)
, <API key>() );
}
static void get_reporting_route(void)
{
const char* route = get_report_route( ( plist_get_int16(0) >> 8 ) & 0xFF );
if ( !route )
{
bus_slave_seterror( kUnknownError );
return;
}
uint8 start = plist_get_int16(0) & 0xFF;
uint8 len = strlen( route ) - start;
if ( len < 0 )
{
bus_slave_seterror( kCallbackError );
return;
}
if ( len > kBusMaxMessageSize )
len = kBusMaxMessageSize;
<API key>( route + start, len );
}
static void set_reporting_apn(void)
{
set_gprs_apn( (const char*)plist_get_buffer(0), <API key>() );
}
static void get_reporting_apn(void)
{
<API key>( current_momo_state.report_config.gprs_apn, strlen(current_momo_state.report_config.gprs_apn) );
}
static void set_reporting_flags(void)
{
current_momo_state.report_config.report_flags = plist_get_int16(0);
}
static void get_reporting_flags(void)
{
<API key>( current_momo_state.report_config.report_flags );
}
static void <API key>(void)
{
current_momo_state.report_config.bulk_aggregates = plist_get_int16(0);
current_momo_state.report_config.interval_aggregates = plist_get_int16(1);
}
static void <API key>(void)
{
plist_set_int16( 0, current_momo_state.report_config.bulk_aggregates );
plist_set_int16( 1, current_momo_state.report_config.interval_aggregates );
bus_slave_setreturn( pack_return_status( kNoMIBError, 4 ) );
}
static void build_report()
{
construct_report();
}
static void get_report()
{
uint16 offset = plist_get_int16(0);
memcpy(plist_get_buffer(0), <API key>+offset, 20);
bus_slave_setreturn( pack_return_status(kNoMIBError, 20 ));
}
static void <API key>(void)
{
<API key>( current_momo_state.report_config.transmit_sequence );
}
static BYTE report_buffer[<API key>];
static void read_report_log_mib(void)
{
uint16 index = plist_get_int16(0);
uint16 offset = plist_get_int16(1);
if ( offset >= <API key> )
{
bus_slave_seterror( kCallbackError );
return;
}
uint8 length = <API key> - offset;
if ( length > kBusMaxMessageSize )
length = kBusMaxMessageSize;
if ( report_log_read( index, (void*)&report_buffer, 1 ) == 0 )
{
// No more entries
bus_slave_seterror( kCallbackError );
return;
}
<API key>( report_buffer+offset, length );
}
static void <API key>(void)
{
<API key>( report_log_count() );
}
static void <API key>(void)
{
report_log_clear();
}
static void <API key>(void)
{
<API key>();
}
static void <API key>(void)
{
<API key>();
}
<API key>(reporting) {
{ 0x00, send_report, plist_spec_empty() },
{ 0x01, <API key>, plist_spec_empty() },
{ 0x02, <API key>, plist_spec_empty() },
{ 0x03, <API key>, plist_spec(1, false) },
{ 0x04, <API key>, plist_spec_empty() },
{ 0x05, set_reporting_route, plist_spec(1, true) },
{ 0x06, get_reporting_route, plist_spec(1, false) },
{ 0x07, set_reporting_flags, plist_spec(1, false) },
{ 0x08, get_reporting_flags, plist_spec_empty() },
{ 0x09, <API key>, plist_spec(2, false) },
{ 0x0A, <API key>, plist_spec_empty() },
{ 0x0B, <API key>, plist_spec_empty() },
{ 0x0C, build_report, plist_spec_empty() },
{ 0x0D, get_report, plist_spec(1, false) },
{ 0x0E, <API key>, plist_spec_empty() },
{ 0x0F, read_report_log_mib, plist_spec(2, false) },
{ 0x10, <API key>, plist_spec_empty() },
{ 0x11, <API key>, plist_spec_empty() },
{ 0x12, init_report_config, plist_spec_empty() },
{ 0x13, set_reporting_apn, plist_spec(0,true) },
{ 0x14, get_reporting_apn, plist_spec_empty() },
{ 0xF0, <API key>, plist_spec_empty() },
{ 0xF1, <API key>, plist_spec_empty() }
};
DEFINE_MIB_FEATURE(reporting);
|
<?php
class <API key> {
public function __construct() {
}
/**
* Short Description. (use period)
*
* Long Description.
*
* @since 1.0.0
*/
public static function activate() {
require_once( WC_RBP_INC . 'helpers/class-version-check.php' );
require_once( WC_RBP_INC . 'helpers/class-dependencies.php' );
if( <API key>(WC_RBP_DEPEN) ) {
<API key>::activation_check('3.7');
$message = '<h3> <center> ' . __("Thank you for installing <strong>Role Based Price For WooCommerce</strong> : <strong>Version 3.0 </strong>", WC_RBP_TXT) . '</center> </h3>';
$message .= '<p>' . __("We have worked entire 1 year to improve our plugin to best of our ability and we hope you will enjoy working with it. We are always open for your sugestions and feature requests", WC_RBP_TXT) . '</p>';
$message .= '</hr>';
$message .= '<p>' . __("If you have installed <strong>WPRB</strong> for the 1st time or upgrading from <strong> Version 2.8.7</strong> then you will need to update its' settings once again or this plugin will not function properly. ", WC_RBP_TXT);
$url = admin_url('admin.php?page=<API key>');
$message .= '<a href="' . $url . '" class="button button-primary">' . __("Click Here to update the settings", WC_RBP_TXT) . '</a> </p>';
wc_rbp_admin_update($message, 1, 'activate_message', array(), array( 'wraper' => FALSE, 'times' => 1 ));
set_transient('<API key>', TRUE, 60);
} else {
if( is_plugin_active(WC_RBP_FILE) ) {
deactivate_plugins(WC_RBP_FILE);
}
wp_die(<API key>());
}
}
}
|
<!-- jQuery -->
<script src="<?php echo base_url('assets/frontend/js/jquery.js') ?>"></script>
<!-- Bootstrap Core JavaScript -->
<script src="<?php echo base_url('assets/frontend/js/bootstrap.min.js') ?>"></script>
<!-- Contact Form JavaScript -->
<!-- Do not edit these files! In order to set the email address and subject line for the contact form go to the bin/contact_me.php file. -->
<script src="<?php echo base_url('assets/frontend/js/<API key>.js') ?>"></script>
<script src="<?php echo base_url('assets/frontend/js/contact_me.js') ?>"></script>
<script>
$('.carousel').carousel({
interval: 5000 //changes the speed
})
</script>
<!-- DATA TABLE SCRIPTS -->
<script src="<?php echo base_url('assets/backend/js/dataTables/jquery.dataTables.js') ?>"></script>
<script src="<?php echo base_url('assets/backend/js/dataTables/dataTables.bootstrap.js') ?>"></script>
<script>
$(document).ready(function () {
$('#dataTables-example').dataTable();
});
</script>
<script type="text/javascript">
CKEDITOR.replace( 'editor1', {
on: {
instanceReady: function( ev ) {
// Output paragraphs as <p>Text</p>.
this.dataProcessor.writer.setRules( 'p', {
indent: false,
breakBeforeOpen: true,
breakAfterOpen: false,
breakBeforeClose: false,
breakAfterClose: true
});
}
}
});</script>
|
<?php
class <API key> extends <API key>
{
public function loadTinyMce()
{
$cfg = oxRegistry::getConfig();
$blEnabled = in_array($this->getActiveClassName(), $cfg->getConfigParam("aTinyMCE_classes"));
$blPlainCms = in_array($cfg->getActiveView()->getViewDataElement("edit")-><API key>->value, $cfg->getConfigParam("aTinyMCE_plaincms"));
$blFilemanager = $cfg->getConfigParam("<API key>");
if (!$blEnabled) return false;
if ($blPlainCms) return oxRegistry::getLang()->translateString("<API key>");
// processing editor config & other stuff
$sLang = oxRegistry::getLang()->getLanguageAbbr(oxRegistry::getLang()->getTplLanguage());
// array to assign shops lang abbreviations to lang file names of tinymce: <API key> => fileName (without .js )
$aLang = array(
"cs" => "cs",
"da" => "da",
"de" => "de",
"fr" => "fr_FR",
"it" => "it",
"nl" => "nl",
"ru" => "ru"
);
// default config
$aDefaultConfig = array(
'force_br_newlines' => 'false',
'force_p_newlines' => 'false',
'forced_root_block' => '""',
'selector' => '"textarea:not(.mceNoEditor)"',
'language' => '"' . ( in_array($sLang, $aLang) ? $aLang[$sLang] : 'en' ) . '"',
//'<API key>' => '"' . (in_array($sLang, $aLang) ? $aLang[$sLang] : 'en') . '"',
'nowrap' => 'false',
'entity_encoding' => '"raw"',
'height' => 300,
'menubar' => 'false',
'document_base_url' => '"' . $this->getBaseDir() . '"',
'relative_urls' => 'false',
'<API key>' => 'window.innerWidth',
'<API key>' => 'window.innerHeight-90',
'code_dialog_width' => 'window.innerWidth-50',
'code_dialog_height' => 'window.innerHeight-130',
'image_advtab' => 'true',
'imagetools_toolbar' => '"rotateleft rotateright | flipv fliph | editimage imageoptions"',
'<API key>' => 'true',
'<API key>' => '[ "%d.%m.%Y", "%H:%M" ]',
'<API key>' => 'true',
'<API key>' => '400',
'<API key>' => '"urlconverter"',
'<API key>' => '"' . md5($_SERVER['DOCUMENT_ROOT']) . '"',
'tinymcehelper' => '"' . $this->getSelfActionLink() . 'renderPartial=1"'
);
if ($blFilemanager) {
$aDefaultConfig['<API key>'] = '"../modules/bla/bla-tinymce/fileman/"';
$aDefaultConfig['<API key>'] = '"' . md5($_SERVER['HTTP_HOST']) . '"';
$oUS = oxRegistry::get("oxUtilsServer");
$oUS->setOxCookie("filemanagerkey", md5($_SERVER['DOCUMENT_ROOT'] . $oUS->getOxCookie("admin_sid")));
}
//merging with onfig override
$aConfig = ( $aOverrideConfig = $this->_getTinyCustConfig() ) ? array_merge($aDefaultConfig, $aOverrideConfig) : $aDefaultConfig;
// default plugins and their buttons
$aDefaultPlugins = array(
'advlist' => '', // '' = plugin has no buttons
'anchor' => 'anchor',
'autolink' => '',
'autoresize' => '',
'charmap' => 'charmap',
'code' => 'code',
'colorpicker' => '',
'hr' => 'hr',
'image' => 'image',
'imagetools' => '',
'insertdatetime' => 'insertdatetime',
'link' => 'link unlink',
'lists' => '',
'media' => 'media',
'nonbreaking' => 'nonbreaking',
'pagebreak' => 'pagebreak',
'paste' => 'pastetext',
'preview' => 'preview',
'searchreplace' => 'searchreplace',
'table' => 'table',
'textcolor' => 'forecolor backcolor',
'visualblocks' => '',
//'visualchars' => 'visualchars',
'wordcount' => '',
'oxfullscreen' => 'fullscreen', //custom fullscreen plugin
//'oxwidget' => 'widget'
//'oxgetseourl' => 'yolo' //custom seo url plugin // wip
);
// plugins for newsletter emails
if ($this->getActiveClassName() == "newsletter_main") {
$aDefaultPlugins["legacyoutput"] = "false";
$aDefaultPlugins["fullpage"] = "fullpage";
}
// override for active plugins
$aOverridePlugins = $cfg->getConfigParam("aTinyMCE_plugins");
$aPlugins = ( empty( $aOverridePlugins ) || !is_array($aOverridePlugins) ) ? $aDefaultPlugins : array_merge($aDefaultPlugins, $aOverridePlugins);
$aPlugins = array_filter($aPlugins, function ( $value ) {
return $value !== "false";
});
// array keys von $aPlugins enthalten aktive plugins
$aConfig['plugins'] = '"' . implode(' ', array_keys($aPlugins)) . '"';
// external plugins
$aConfig['external_plugins'] = '{ "oxfullscreen":"' . $this->getModuleUrl('bla-tinymce', 'plugins/oxfullscreen/plugin.js') . '" ';
//$aConfig['external_plugins'] .= ', "oxwidget":"' . $this->getModuleUrl('bla-tinymce', 'plugins/oxwidget/plugin.js') . '" ';
if ($blFilemanager) $aConfig['external_plugins'] .= ',"roxy":"' . $this->getModuleUrl('bla-tinymce', 'plugins/roxy/plugin.js') . '" ';
//$aConfig['external_plugins'] .= ',"oxgetseourl":"' . $this->getModuleUrl('bla-tinymce', 'plugins/oxgetseourl/plugin.js') . '" ';
if ($aExtPlugins = $this->_getTinyExtPlugins()) {
foreach ($aExtPlugins AS $plugin => $file) {
$aConfig['external_plugins'] .= ', "' . $plugin . '": "' . $file . '" ';
}
}
$aConfig['external_plugins'] .= ' }';
// default toolbar buttons
$aDefaultButtons = array(
"undo redo",
"cut copy paste",
"bold italic underline strikethrough",
"alignleft aligncenter alignright alignjustify",
"bullist numlist",
"outdent indent",
"blockquote",
"subscript",
"superscript",
"formatselect",
"removeformat",
"fontselect",
"fontsizeselect"
);
$aOverrideButtons = oxRegistry::getConfig()->getConfigParam("aTinyMCE_buttons");
$aButtons = ( empty( $aOverrideButtons ) || !is_array($aOverrideButtons) ) ? $aDefaultButtons : $aOverrideButtons;
// plugin buttons
$aPluginButtons = array_filter($aPlugins);
$aCustomButtons = $this-><API key>();
$aButtons = array_merge(array_filter($aButtons), array_filter($aPluginButtons), array_filter($aCustomButtons));
$aConfig['toolbar'] = '"' . implode(" | ", $aButtons) . '"';
// compile the whole config stuff
$sConfig = '';
foreach ($aConfig AS $param => $value) {
$sConfig .= "$param: $value, ";
}
// add init script
$sInit = 'tinymce.init({ ' . $sConfig . ' });';
$<API key> = 'function <API key>(sIdent) {
var editor = tinymce.get("editor_"+sIdent);
var content = (editor && !editor.isHidden()) ? editor.getContent() : document.getElementById("editor_"+sIdent).value;
document.getElementsByName("editval[" + sIdent + "]").item(0).value = content.replace(/\[{([^\]]*?)}\]/g, function(m) { return m.replace(/>/g, ">").replace(/</g, "<").replace(/&/g, "&") });
return true;
}
var origCopyLongDesc = copyLongDesc;
copyLongDesc = function(sIdent) {
if ( <API key>( sIdent ) ) return;
console.log("tinymce disabled, copy content from regular textarea");
origCopyLongDesc( sIdent );
}';
$sUrlConverter = 'function urlconverter(url, node, on_save) {
console.log(tinyMCE.activeEditor);
if(url.indexOf("[{") == 0) return url;
return (tinyMCE.activeEditor.settings.relative_urls) ? tinyMCE.activeEditor.documentBaseURI.toRelative(url) : tinyMCE.activeEditor.documentBaseURI.toAbsolute(url);
}';
// adding scripts to template
$smarty = oxRegistry::get("oxUtilsView")->getSmarty();
$sSufix = ( $smarty->_tpl_vars["<API key>"] ) ? '_dynamic' : '';
$aScript = (array)$cfg->getGlobalParameter('scripts' . $sSufix);
$aScript[] = $<API key>;
$aScript[] = $sUrlConverter;
$aScript[] = $sInit;
$cfg->setGlobalParameter('scripts' . $sSufix, $aScript);
$aInclude = (array)$cfg->getGlobalParameter('includes' . $sSufix);
$aExtjs = $cfg->getConfigParam('aTinyMCE_extjs');
if (!empty( $aExtjs ) && is_array($aExtjs)) foreach ($aExtjs as $key => $js) $aInclude[3][] = $js;
$aInclude[3][] = $this->getModuleUrl('bla-tinymce', 'tinymce/tinymce.min.js');
$cfg->setGlobalParameter('includes' . $sSufix, $aInclude);
return '<li style="margin-left: 50px;"><button style="border: 1px solid #0089EE; color: #0089EE;padding: 3px 10px; margin-top: -10px; background: white;" ' .
'onclick="tinymce.each(tinymce.editors, function(editor) { if(editor.isHidden()) { editor.show(); } else { editor.hide(); } });"><span>' .
oxRegistry::getLang()->translateString('BLA_TINYMCE_TOGGLE') . '</span></button></li>';
// javascript:tinymce.execCommand(\'mceToggleEditor\',false,\'editor1\');
}
protected function <API key>()
{
$aControls = ( method_exists(get_parent_class(__CLASS__), __FUNCTION__) ) ? parent::<API key>() : array();
return $aControls;
}
protected function _getTinyExtPlugins()
{
$aPlugins = oxRegistry::getConfig()->getConfigParam("<API key>");
if (method_exists(get_parent_class(__CLASS__), __FUNCTION__)) {
$aPlugins = array_merge(parent::_getTinyExtPlugins(), $aPlugins);
}
return $aPlugins;
}
protected function _getTinyCustConfig()
{
$aConfig = oxRegistry::getConfig()->getConfigParam("aTinyMCE_config");
if (method_exists(get_parent_class(__CLASS__), __FUNCTION__)) {
$aConfig = array_merge(parent::_getTinyCustConfig(), $aConfig);
}
return $aConfig;
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nerdz.Messenger.Controller;
using Nerdz.Messages;
using Nerdz;
namespace Tests.Controller
{
public class DummyUI : IMessengerView
{
private Credentials credentials;
private <API key> controller;
public <API key> Controller
{
set
{
controller = value;
}
get
{
return controller;
}
}
public void UpdateConversations(System.Collections.Generic.List<Nerdz.Messages.IConversation> conversations)
{
Console.WriteLine("Conversations: ");
foreach (IConversation c in conversations)
{
Console.WriteLine(c);
}
}
public void UpdateMessages(System.Collections.Generic.List<Nerdz.Messages.IMessage> messages)
{
Console.WriteLine("Messages: ");
foreach (IMessage m in messages)
{
Console.WriteLine(m);
}
}
public void ShowLogin()
{
Console.WriteLine("Username: ");
string username = "new user input from textbox";
Console.WriteLine("Password: ");
string password = "password input from textbox";
credentials = new Credentials(username, password);
}
public void ClearConversations()
{
Console.WriteLine("\n\n\nConversations list cleaned\n\n");
}
public void ClearConversation()
{
Console.WriteLine("\n\nConversation cleaned\n\n");
}
public void DisplayError(string error)
{
Console.Error.WriteLine("[!] " + error);
}
public void <API key>(string error)
{
Console.Error.WriteLine("CRITICAL: " + error);
}
public int <API key>()
{
return 0;
}
}
[TestClass]
public class <API key>
{
static private IMessengerView view;
static private <API key> controller;
[TestMethod]
public void NewController()
{
Credentials c = new Credentials(0, "wrongpass");
view = new DummyUI();
try
{
controller = new MessengerController(view, c);
}
catch (LoginException)
{
Console.WriteLine("Wrong username and password (OK!)");
}
c = new Credentials("admin", "adminadmin");
controller = new MessengerController(view, c);
}
[TestMethod]
public void <API key>()
{
controller.Conversations();
}
[TestMethod]
public void <API key>()
{
controller.Conversation(0); // exists, no exception expected
}
[ExpectedException(typeof(CriticalException))]
[TestMethod]
public void <API key>()
{
controller.Conversation(110);
}
[TestMethod]
public void TestSendOK()
{
controller.Send("Gaben", "great app :>");
// user nessuno exists, no exception expected
}
[ExpectedException(typeof(BadStatusException))]
[TestMethod]
public void TestSendFAIL()
{
controller.Send("94949494", "great app :>");
// numeric username can't exists, so this test shoudl fail
}
[TestMethod]
public void TestLogout()
{
controller.Logout();
}
}
}
|
#include "<API key>.h"
#include "<API key>.h"
#include <<API key>>
#include <QNetworkReply>
#ifdef INDEPENDENT_DEBUG
#include <QDebug>
#endif
const int <API key>::MAX_REDIRECTS = 8;
const QString <API key>::BASE_URL("http:
const QString <API key>::ICON_URL("http:
const QByteArray <API key>::USER_AGENT("Wget/1.13.4 (linux-gnu)");
<API key>::<API key>(QObject *parent) :
FeedRequest(parent),
m_request(0),
m_nam(0),
m_status(Idle),
m_results(0),
m_redirects(0)
{
}
QString <API key>::errorString() const {
return m_errorString;
}
void <API key>::setErrorString(const QString &e) {
m_errorString = e;
#ifdef INDEPENDENT_DEBUG
if (!e.isEmpty()) {
qDebug() << "<API key>::error." << e;
}
#endif
}
QByteArray <API key>::result() const {
return m_buffer.data();
}
void <API key>::setResult(const QByteArray &r) {
m_buffer.open(QBuffer::WriteOnly);
m_buffer.write(r);
m_buffer.close();
}
FeedRequest::Status <API key>::status() const {
return m_status;
}
void <API key>::setStatus(FeedRequest::Status s) {
if (s != status()) {
m_status = s;
emit statusChanged(s);
}
}
bool <API key>::cancel() {
if (status() == Active) {
if ((m_request) && (m_request->status() == ArticleRequest::Active)) {
m_request->cancel();
}
else {
setStatus(Canceled);
emit finished(this);
}
}
return true;
}
bool <API key>::getFeed(const QVariantMap &settings) {
if (status() == Active) {
return false;
}
setStatus(Active);
setResult(QByteArray());
setErrorString(QString());
m_settings = settings;
m_results = 0;
m_redirects = 0;
QString url(BASE_URL);
const QString section = m_settings.value("section").toString();
if (!section.isEmpty()) {
url.append("/");
url.append(section);
}
url.append("/rss");
#ifdef INDEPENDENT_DEBUG
qDebug() << "<API key>::getFeed(). URL:" << url;
#endif
QNetworkRequest request(url);
request.setRawHeader("User-Agent", USER_AGENT);
QNetworkReply *reply = <API key>()->get(request);
connect(reply, SIGNAL(finished()), this, SLOT(checkFeed()));
connect(this, SIGNAL(finished(FeedRequest*)), reply, SLOT(deleteLater()));
return true;
}
void <API key>::checkFeed() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
setErrorString(tr("Network error"));
setStatus(Error);
emit finished(this);
return;
}
const QString redirect = getRedirect(reply);
if (!redirect.isEmpty()) {
if (m_redirects < MAX_REDIRECTS) {
reply->deleteLater();
followRedirect(redirect, SLOT(checkFeed()));
}
else {
setErrorString(tr("Maximum redirects reached"));
setStatus(Error);
emit finished(this);
}
return;
}
switch (reply->error()) {
case QNetworkReply::NoError:
break;
case QNetworkReply::<API key>:
setStatus(Canceled);
emit finished(this);
return;
default:
setErrorString(reply->errorString());
setStatus(Error);
emit finished(this);
return;
}
m_parser.setContent(reply->readAll());
if (m_parser.readChannel()) {
writeStartFeed();
writeFeedTitle(m_parser.title());
writeFeedUrl(m_parser.url());
const bool fetchFullArticle = m_settings.value("fetchFullArticle", true).toBool();
const QDateTime lastUpdated = m_settings.value("lastUpdated").toDateTime();
if (fetchFullArticle) {
if (m_parser.readNextArticle()) {
if (m_parser.date() > lastUpdated) {
reply->deleteLater();
getArticle(m_parser.url());
}
else {
writeEndFeed();
setStatus(Ready);
emit finished(this);
}
return;
}
writeEndFeed();
}
else {
const int max = m_settings.value("maxResults", 20).toInt();
while((m_results < max) && (m_parser.readNextArticle()) && (m_parser.date() > lastUpdated)) {
++m_results;
writeStartItem();
writeItemAuthor(m_parser.author());
writeItemBody(m_parser.description());
writeItemCategories(m_parser.categories());
writeItemDate(m_parser.date());
writeItemEnclosures(m_parser.enclosures());
writeItemTitle(m_parser.title());
writeItemUrl(m_parser.url());
writeEndItem();
}
writeEndFeed();
setStatus(Ready);
emit finished(this);
return;
}
}
setErrorString(m_parser.errorString());
setStatus(Error);
emit finished(this);
}
void <API key>::getArticle(const QString &url) {
#ifdef INDEPENDENT_DEBUG
qDebug() << "<API key>::getArticle(). URL:" << url;
#endif
articleRequest()->getArticle(url, m_settings);
}
void <API key>::checkArticle(ArticleRequest *request) {
if (request->status() == ArticleRequest::Canceled) {
setStatus(Canceled);
emit finished(this);
return;
}
++m_results;
if (request->status() == ArticleRequest::Ready) {
const ArticleResult article = request->result();
writeStartItem();
writeItemAuthor(article.author.isEmpty() ? m_parser.author() : article.author);
writeItemBody(article.body.isEmpty() ? m_parser.description() : article.body);
writeItemCategories(article.categories.isEmpty() ? m_parser.categories() : article.categories);
writeItemDate(article.date.isNull() ? m_parser.date() : article.date);
writeItemEnclosures(article.enclosures.isEmpty() ? m_parser.enclosures() : article.enclosures);
writeItemTitle(article.title.isEmpty() ? m_parser.title() : article.title);
writeItemUrl(article.url.isEmpty() ? m_parser.url() : article.url);
writeEndItem();
}
#ifdef INDEPENDENT_DEBUG
else {
qDebug() << "<API key>::checkArticle(). Error:" << request->errorString();
}
#endif
if ((m_results < m_settings.value("maxResults", 20).toInt()) && (m_parser.readNextArticle())
&& (m_parser.date() > m_settings.value("lastUpdated").toDateTime())) {
getArticle(m_parser.url());
return;
}
#ifdef INDEPENDENT_DEBUG
qDebug() << "<API key>::checkArticle(). No more new articles";
#endif
writeEndFeed();
setStatus(Ready);
emit finished(this);
}
void <API key>::followRedirect(const QString &url, const char *slot) {
#ifdef INDEPENDENT_DEBUG
qDebug() << "<API key>::followRedirect(). URL:" << url;
#endif
++m_redirects;
QNetworkRequest request(url);
request.setRawHeader("User-Agent", USER_AGENT);
QNetworkReply *reply = <API key>()->get(request);
connect(reply, SIGNAL(finished()), this, slot);
connect(this, SIGNAL(finished(FeedRequest*)), reply, SLOT(deleteLater()));
}
QString <API key>::getRedirect(const QNetworkReply *reply) {
QString redirect = QString::fromUtf8(reply->rawHeader("Location"));
if ((!redirect.isEmpty()) && (!redirect.startsWith("http"))) {
const QUrl url = reply->url();
if (redirect.startsWith("/")) {
redirect.prepend(url.scheme() + "://" + url.authority());
}
else {
redirect.prepend(url.scheme() + "://" + url.authority() + "/");
}
}
return redirect;
}
void <API key>::writeStartFeed() {
#ifdef INDEPENDENT_DEBUG
qDebug() << "<API key>::writeStartFeed()";
#endif
m_buffer.open(QBuffer::WriteOnly);
m_writer.setDevice(&m_buffer);
m_writer.writeStartDocument();
m_writer.writeStartElement("rss");
m_writer.writeAttribute("version", "2.0");
m_writer.writeAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
m_writer.writeAttribute("xmlns:content", "http://purl.org/rss/1.0/modules/content/");
m_writer.writeStartElement("channel");
m_writer.writeTextElement("description", tr("News articles from The Independent"));
m_writer.writeStartElement("image");
m_writer.writeTextElement("url", ICON_URL);
m_writer.writeEndElement();
m_buffer.close();
}
void <API key>::writeEndFeed() {
#ifdef INDEPENDENT_DEBUG
qDebug() << "<API key>::writeEndFeed()";
#endif
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeEndElement();
m_writer.writeEndElement();
m_writer.writeEndDocument();
m_buffer.close();
}
void <API key>::writeFeedTitle(const QString &title) {
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeStartElement("title");
m_writer.writeCDATA(title);
m_writer.writeEndElement();
m_buffer.close();
}
void <API key>::writeFeedUrl(const QString &url) {
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeTextElement("link", url);
m_buffer.close();
}
void <API key>::writeStartItem() {
#ifdef INDEPENDENT_DEBUG
qDebug() << "<API key>::writeStartItem(). Item" << m_results << "of"
<< m_settings.value("maxResults", 20).toInt();
#endif
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeStartElement("item");
m_buffer.close();
}
void <API key>::writeEndItem() {
#ifdef INDEPENDENT_DEBUG
qDebug() << "<API key>::writeEndItem(). Item" << m_results << "of"
<< m_settings.value("maxResults", 20).toInt();
#endif
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeEndElement();
m_buffer.close();
}
void <API key>::writeItemAuthor(const QString &author) {
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeTextElement("dc:creator", author);
m_buffer.close();
}
void <API key>::writeItemBody(const QString &body) {
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeStartElement("content:encoded");
m_writer.writeCDATA(body);
m_writer.writeEndElement();
m_buffer.close();
}
void <API key>::writeItemCategories(const QStringList &categories) {
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
foreach (const QString &category, categories) {
m_writer.writeTextElement("category", category);
}
m_buffer.close();
}
void <API key>::writeItemDate(const QDateTime &date) {
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeTextElement("dc:date", date.toString(Qt::ISODate));
m_buffer.close();
}
void <API key>::writeItemEnclosures(const QVariantList &enclosures) {
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
foreach (const QVariant &e, enclosures) {
const QVariantMap enclosure = e.toMap();
m_writer.writeStartElement("enclosure");
m_writer.writeAttribute("url", enclosure.value("url").toString());
m_writer.writeAttribute("type", enclosure.value("type").toString());
m_writer.writeEndElement();
}
m_buffer.close();
}
void <API key>::writeItemTitle(const QString &title) {
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeStartElement("title");
m_writer.writeCDATA(title);
m_writer.writeEndElement();
m_buffer.close();
}
void <API key>::writeItemUrl(const QString &url) {
m_buffer.open(QBuffer::WriteOnly | QBuffer::Append);
m_writer.writeTextElement("link", url);
m_buffer.close();
}
<API key>* <API key>::articleRequest() {
if (!m_request) {
m_request = new <API key>(this);
connect(m_request, SIGNAL(finished(ArticleRequest*)), this, SLOT(checkArticle(ArticleRequest*)));
}
return m_request;
}
<API key>* <API key>::<API key>() {
if (!m_nam) {
m_nam = new <API key>(this);
}
return m_nam;
}
|
{% if <API key> %}
<form id="signin-form" method="post" action="{{ settings.LOGIN_URL }}">
{{ macros.<API key>(csrf_token) }}
{{ login_form.next }}
{{ login_form.persona_assertion }}
<input
type='hidden'
name='login_provider_name'
value='{{ <API key>.name }}'
/>
<input
name="{{ <API key>.name }}"
type="submit"
class="{{ <API key>.type }}"
value="{% trans login_name=<API key>.name|capitalize %}Sign in via {{ login_name }}{% endtrans %}"
/>
</form>
{% else %}
<a href="{{ settings.LOGIN_URL }}?next={{ request.path|clean_login_url|escape }}"
>{% trans %}Hi there! Please sign in{% endtrans %}</a>
{% endif %}
|
package com.dmtools.webapp.config;
import com.dmtools.webapp.config.locale.<API key>;
import org.springframework.boot.bind.<API key>;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.<API key>;
import org.springframework.web.servlet.i18n.<API key>;
@Configuration
public class LocaleConfiguration extends <API key> implements EnvironmentAware {
@SuppressWarnings("unused")
private <API key> propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new <API key>(environment, "spring.messages.");
}
@Bean(name = "localeResolver")
public LocaleResolver localeResolver() {
<API key> <API key> = new <API key>();
<API key>.setCookieName("<API key>");
return <API key>;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
<API key> <API key> = new <API key>();
<API key>.setParamName("language");
registry.addInterceptor(<API key>);
}
}
|
/**
* This class is generated by jOOQ
*/
package com.aviafix.db.generated.tables.pojos;
import java.io.Serializable;
import java.time.LocalDate;
import javax.annotation.Generated;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http:
"jOOQ version:3.8.5"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class <API key> implements Serializable {
private static final long serialVersionUID = 1444342293;
private Integer ETID;
private Integer CREDITCARDNUM;
private LocalDate EXPDATE;
private Integer CODE;
private String CARDHOLDERNAME;
private Double AMOUNT;
public <API key>() {}
public <API key>(<API key> value) {
this.ETID = value.ETID;
this.CREDITCARDNUM = value.CREDITCARDNUM;
this.EXPDATE = value.EXPDATE;
this.CODE = value.CODE;
this.CARDHOLDERNAME = value.CARDHOLDERNAME;
this.AMOUNT = value.AMOUNT;
}
public <API key>(
Integer ETID,
Integer CREDITCARDNUM,
LocalDate EXPDATE,
Integer CODE,
String CARDHOLDERNAME,
Double AMOUNT
) {
this.ETID = ETID;
this.CREDITCARDNUM = CREDITCARDNUM;
this.EXPDATE = EXPDATE;
this.CODE = CODE;
this.CARDHOLDERNAME = CARDHOLDERNAME;
this.AMOUNT = AMOUNT;
}
public Integer ETID() {
return this.ETID;
}
public void ETID(Integer ETID) {
this.ETID = ETID;
}
public Integer CREDITCARDNUM() {
return this.CREDITCARDNUM;
}
public void CREDITCARDNUM(Integer CREDITCARDNUM) {
this.CREDITCARDNUM = CREDITCARDNUM;
}
public LocalDate EXPDATE() {
return this.EXPDATE;
}
public void EXPDATE(LocalDate EXPDATE) {
this.EXPDATE = EXPDATE;
}
public Integer CODE() {
return this.CODE;
}
public void CODE(Integer CODE) {
this.CODE = CODE;
}
public String CARDHOLDERNAME() {
return this.CARDHOLDERNAME;
}
public void CARDHOLDERNAME(String CARDHOLDERNAME) {
this.CARDHOLDERNAME = CARDHOLDERNAME;
}
public Double AMOUNT() {
return this.AMOUNT;
}
public void AMOUNT(Double AMOUNT) {
this.AMOUNT = AMOUNT;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("<API key> (");
sb.append(ETID);
sb.append(", ").append(CREDITCARDNUM);
sb.append(", ").append(EXPDATE);
sb.append(", ").append(CODE);
sb.append(", ").append(CARDHOLDERNAME);
sb.append(", ").append(AMOUNT);
sb.append(")");
return sb.toString();
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>src\fork\box2d\collision\b2Manifold.js - Box2D Port Fork API</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png" title="Box2D Port Fork API"></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: 1.0.0</em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/b2AABB.html">b2AABB</a></li>
<li><a href="../classes/b2Body.html">b2Body</a></li>
<li><a href="../classes/b2BodyDef.html">b2BodyDef</a></li>
<li><a href="../classes/b2Bound.html">b2Bound</a></li>
<li><a href="../classes/b2BoundValues.html">b2BoundValues</a></li>
<li><a href="../classes/b2BoxDef.html">b2BoxDef</a></li>
<li><a href="../classes/b2BufferedPair.html">b2BufferedPair</a></li>
<li><a href="../classes/b2CircleContact.html">b2CircleContact</a></li>
<li><a href="../classes/b2CircleDef.html">b2CircleDef</a></li>
<li><a href="../classes/b2CircleShape.html">b2CircleShape</a></li>
<li><a href="../classes/b2Collision.html">b2Collision</a></li>
<li><a href="../classes/b2CollisionFilter.html">b2CollisionFilter</a></li>
<li><a href="../classes/b2Conservative.html">b2Conservative</a></li>
<li><a href="../classes/b2Contact.html">b2Contact</a></li>
<li><a href="../classes/b2ContactConstraint.html">b2ContactConstraint</a></li>
<li><a href="../classes/<API key>.html"><API key></a></li>
<li><a href="../classes/b2ContactID.html">b2ContactID</a></li>
<li><a href="../classes/b2ContactManager.html">b2ContactManager</a></li>
<li><a href="../classes/b2ContactNode.html">b2ContactNode</a></li>
<li><a href="../classes/b2ContactPoint.html">b2ContactPoint</a></li>
<li><a href="../classes/b2ContactRegister.html">b2ContactRegister</a></li>
<li><a href="../classes/b2ContactSolver.html">b2ContactSolver</a></li>
<li><a href="../classes/b2Distance.html">b2Distance</a></li>
<li><a href="../classes/b2DistanceJoint.html">b2DistanceJoint</a></li>
<li><a href="../classes/b2DistanceJointDef.html">b2DistanceJointDef</a></li>
<li><a href="../classes/b2GearJoint.html">b2GearJoint</a></li>
<li><a href="../classes/b2GearJointDef.html">b2GearJointDef</a></li>
<li><a href="../classes/b2Island.html">b2Island</a></li>
<li><a href="../classes/b2Jacobian.html">b2Jacobian</a></li>
<li><a href="../classes/b2Joint.html">b2Joint</a></li>
<li><a href="../classes/b2JointDef.html">b2JointDef</a></li>
<li><a href="../classes/b2JointNode.html">b2JointNode</a></li>
<li><a href="../classes/b2Manifold.html">b2Manifold</a></li>
<li><a href="../classes/b2MassData.html">b2MassData</a></li>
<li><a href="../classes/b2Mat22.html">b2Mat22</a></li>
<li><a href="../classes/b2Math.html">b2Math</a></li>
<li><a href="../classes/b2MouseJoint.html">b2MouseJoint</a></li>
<li><a href="../classes/b2MouseJointDef.html">b2MouseJointDef</a></li>
<li><a href="../classes/b2NullContact.html">b2NullContact</a></li>
<li><a href="../classes/b2OBB.html">b2OBB</a></li>
<li><a href="../classes/b2Pair.html">b2Pair</a></li>
<li><a href="../classes/b2PairCallback.html">b2PairCallback</a></li>
<li><a href="../classes/b2PairManager.html">b2PairManager</a></li>
<li><a href="../classes/<API key>.html"><API key></a></li>
<li><a href="../classes/b2PolyContact.html">b2PolyContact</a></li>
<li><a href="../classes/b2PolyDef.html">b2PolyDef</a></li>
<li><a href="../classes/b2PolyShape.html">b2PolyShape</a></li>
<li><a href="../classes/b2PrismaticJoint.html">b2PrismaticJoint</a></li>
<li><a href="../classes/b2PrismaticJointDef.html">b2PrismaticJointDef</a></li>
<li><a href="../classes/b2Proxy.html">b2Proxy</a></li>
<li><a href="../classes/b2PulleyJoint.html">b2PulleyJoint</a></li>
<li><a href="../classes/b2PulleyJointDef.html">b2PulleyJointDef</a></li>
<li><a href="../classes/b2RevoluteJoint.html">b2RevoluteJoint</a></li>
<li><a href="../classes/b2RevoluteJointDef.html">b2RevoluteJointDef</a></li>
<li><a href="../classes/b2Settings.html">b2Settings</a></li>
<li><a href="../classes/b2Shape.html">b2Shape</a></li>
<li><a href="../classes/b2ShapeDef.html">b2ShapeDef</a></li>
<li><a href="../classes/b2TimeStep.html">b2TimeStep</a></li>
<li><a href="../classes/b2Vec2.html">b2Vec2</a></li>
<li><a href="../classes/b2World.html">b2World</a></li>
<li><a href="../classes/b2WorldListener.html">b2WorldListener</a></li>
<li><a href="../classes/ClipVertex.html">ClipVertex</a></li>
<li><a href="../classes/Features.html">Features</a></li>
</ul>
<ul id="api-modules" class="apis modules">
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1 class="file-heading">File: src\fork\box2d\collision\b2Manifold.js</h1>
<div class="file">
<pre class="code prettyprint linenums">
/**
* A manifold for two touching convex shapes.
*
* @class b2Manifold
* @constructor
*/
var b2Manifold = function () {
this.points = new Array(b2Settings.<API key>);
for (var i = 0; i < b2Settings.<API key>; i++){
this.points[i] = new b2ContactPoint();
}
this.normal = new b2Vec2();
};
b2Manifold.prototype =
{
points: null,
normal: null,
pointCount: 0
};
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/../api.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/apidocs.js"></script>
</body>
</html>
|
from test_support import *
# this test calls a prover which is correctly configured but whose execution
# gives an error (here: the prover executable doesn't exist). The intent is to
# test the output of gnatprove in this specific case
prove_all(prover=["plop"], opt=["--why3-conf=test.conf"])
|
import altConnect from '<API key>/altConnect';
import { STATUS_OK } from 'app-constants';
import ItemStore from 'stores/ItemStore';
import ProgressBar from '../components/ProgressBar';
const mapStateToProps = ({ itemState }) => ({
progress: itemState.readingPercentage,
hidden: itemState.status !== STATUS_OK,
});
mapStateToProps.stores = { ItemStore };
export default altConnect(mapStateToProps)(ProgressBar);
// WEBPACK FOOTER //
// ./src/js/app/modules/item/containers/<API key>.js
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using VPL;
namespace LimnorDesigner
{
<summary>
load primary types and Type into the treeview for selection for creating Attribute
</summary>
public partial class TypeSelector : UserControl
{
public Type SelectedType;
<API key> _svc;
public TypeSelector()
{
InitializeComponent();
}
public void <API key>(<API key> service, EnumWebRunAt runAt, Type initSelection)
{
_svc = service;
treeView1.<API key>(runAt, initSelection);
treeView1.AfterSelect += new <API key>(<API key>);
treeView1.Click += new EventHandler(treeView1_Click);
treeView1.KeyPress += new <API key>(treeView1_KeyPress);
}
void treeView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
if (_svc != null)
{
_svc.CloseDropDown();
}
}
}
void treeView1_Click(object sender, EventArgs e)
{
if (_svc != null)
{
_svc.CloseDropDown();
}
}
void <API key>(object sender, TreeViewEventArgs e)
{
TreeNodeClassType tnct = e.Node as TreeNodeClassType;
if (tnct != null)
{
SelectedType = tnct.OwnerDataType;
}
}
public static Bitmap GetTypeImageByName(string name)
{
if (string.CompareOrdinal("Number", name) == 0)
{
return Resources._decimal;
}
if (string.CompareOrdinal("String", name) == 0)
{
return Resources.abc;
}
if (string.CompareOrdinal("Array", name) == 0)
{
return Resources._array.ToBitmap();
}
if (string.CompareOrdinal("DateTime", name) == 0)
{
return Resources.date;
}
if (string.CompareOrdinal("TimeSpan", name) == 0)
{
return Resources.date;
}
return Resources._decimal;
}
public static TypeSelector <API key>(<API key> service, EnumWebRunAt runAt, Type initSelection)
{
TypeSelector dlg = new TypeSelector();
dlg.<API key>(service, runAt, initSelection);
return dlg;
}
}
}
|
package net.mcviral.dev.plugins.comjail.events;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.plugin.Plugin;
import net.mcviral.dev.plugins.comjail.main.JailController;
public class TeleportEvent implements Listener{
@SuppressWarnings("unused")
private Plugin plugin;
private JailController jailcontroller;
public TeleportEvent(Plugin mplugin, JailController mjailcontroller){
plugin = mplugin;
jailcontroller = mjailcontroller;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerTeleport(PlayerTeleportEvent event){
if (jailcontroller.isJailed(event.getPlayer().getUniqueId())){
if (!event.getPlayer().hasPermission("jail.override")){
event.setCancelled(true);
event.getPlayer().sendMessage("[" + ChatColor.BLUE + "GUARD" + ChatColor.WHITE + "] " + ChatColor.RED + "You are jailed, you may not teleport.");
}
}
}
}
|
package se.solit.timeit.resources;
import java.net.URI;
import java.net.URISyntaxException;
import javax.servlet.http.HttpSession;
import javax.ws.rs.<API key>;
import javax.ws.rs.core.Response;
public class BaseResource
{
protected <API key> redirect(String destination) throws URISyntaxException
{
URI uri = new URI(destination);
Response response = Response.seeOther(uri).build();
return new <API key>(response);
}
/**
* Set message to show the message in the next shown View.
*
* @param session
* @param message
*/
protected void setMessage(HttpSession session, String message)
{
session.setAttribute("message", message);
}
}
|
Copyright (c) 2012 Ecma International. All rights reserved.
Ecma International makes this code available under the terms and conditions set
forth on http:
"Use Terms"). Any redistribution of this code must retain the above
copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.3/15.3.2/15.3.2.1/15.3.2.1-11-8-s.js
* @description Strict Mode - SyntaxError is not thrown if a function is created using a Function constructor that has two identical parameters, which are separated by a unique parameter name and there is no explicit 'use strict' in the function constructor's body
* @onlyStrict
*/
function testcase() {
"use strict";
var foo = new Function("baz", "qux", "baz", "return 0;");
return true;
}
runTestCase(testcase);
|
package petascope.wcs2.handlers;
import static petascope.wcs2.extensions.FormatExtension.MIME_XML;
/**
* Bean holding the response from executing a request operation.
*
* @author <a href="mailto:d.misev@jacobs-university.de">Dimitar Misev</a>
*/
public class Response {
private final byte[] data;
private final String xml;
private final String mimeType;
private final int exit_code;
private static final int DEFAULT_CODE = 200;
// constructrs
public Response(byte[] data) {
this(data, null, null, DEFAULT_CODE);
}
public Response(byte[] data, int code) {
this(data, null, null, code);
}
public Response(String xml) {
this(null, xml, null); //FormatExtension.MIME_GML);
}
public Response(String xml, int code) {
this(null, xml, MIME_XML, code);
}
public Response(byte[] data, String xml, String mimeType) {
this(data, xml, mimeType, DEFAULT_CODE);
}
public Response(byte[] data, String xml, String mimeType, int code) {
this.data = data;
this.xml = xml;
this.mimeType = mimeType;
this.exit_code = code;
}
// interface
public byte[] getData() {
return data;
}
public String getMimeType() {
return mimeType;
}
public String getXml() {
return xml;
}
public int getExitCode() {
return exit_code;
}
}
|
function <API key>(selector)
{
$(document).ready(function(){
var checkforloadedcats = [];
var firstImage = $(selector).find('img').filter(':first');
if(firstImage.length > 0){
checkforloadedcats[selector] = setInterval(function() {
var image = firstImage.get(0);
if (image.complete || image.readyState == 'complete' || image.readyState == 4) {
clearInterval(checkforloadedcats[selector]);
$(selector).flexslider({
namespace: "",
animation: "slide",
easing: "easeInQuart",
slideshow: false,
animationLoop: false,
animationSpeed: 700,
pauseOnHover: true,
controlNav: false,
itemWidth: 238,
minItems: flexmin,
maxItems: flexmax,
move: 0 });
}
}, 20);
}
$(window).resize(function() {
try {
$(selector).flexslider(0);
if($('#center_column').width()<=280){ $(selector).data('flexslider').setOpts({minItems: 1, maxItems: 1});
}
else if($('#center_column').width()<=440){ $(selector).data('flexslider').setOpts({minItems: grid_size_ms, maxItems: grid_size_ms});}
else if($('#center_column').width()<963){ $(selector).data('flexslider').setOpts({minItems: grid_size_sm, maxItems: grid_size_sm});}
else if($('#center_column').width()>=1240){ $(selector).data('flexslider').setOpts({minItems: grid_size_lg, maxItems: grid_size_lg});}
else if($('#center_column').width()>=963){ $(selector).data('flexslider').setOpts({minItems: grid_size_md, maxItems: grid_size_md});}
} catch(e) {
// handle all your exceptions here
}
});
});
}
|
<?php
/**
* Skeleton subclass for performing query and update operations on the 'transaction' table.
*
*
*
* This class was autogenerated by Propel 1.4.2 on:
*
* Sun Jul 17 20:02:37 2011
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package lib.model.basic
*/
class TransactionPeer extends BaseTransactionPeer
{
} // TransactionPeer
|
from itertools import combinations
def is_good(n):
return 1 + ((int(n) - 1) % 9) == 9
def <API key>(n):
subsequences = []
combinations_list = []
index = 4
#Generate all combinations
while index > 0:
combinations_list.append(list(combinations(str(n), index)))
index -= 1
#Formatting combinations
for index in combinations_list:
for combination in index:
subsequences.append(''.join(combination))
return subsequences
if __name__ == '__main__':
#The modulo
modulo = ((10 ** 9) + 7)
#Get number of cases
cases = int(raw_input())
while cases > 0:
value = raw_input()
good_subsequences = 0
for sub in <API key>(value):
if is_good(sub):
good_subsequences += 1
print (good_subsequences % modulo)-1
cases -= 1
|
<!
This is a more advanced example of using the each function in jQuery.
The idea here is that the handling function can choose to return false
in which case the 'each' loop is stopped and no further DOM elements
are processed. You can use this in order to find a specific element, process
only a prefix of the elements and more.
Mark Veltzer <mark.veltzer@gmail.com>
<html>
<head>
<script src='/jquery.js'></script>
<script>
$(document).ready(function() {
$('#mybutton').click(function() {
$('li').each(function(index,element) {
if(element!=this) {
throw new String('what ?!?');
}
$(this).text($(this).text()+'-'+index);
if(Math.random()<0.2) {
return false;
} else {
return true;
}
});
});
});
</script>
</head>
<body>
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
<li>f</li>
<li>g</li>
<li>h</li>
<li>i</li>
</ul>
<button id='mybutton'>Push me to process <b>some</b> of the elements!</button>
</body>
</html>
|
#coding=utf-8
import unittest
import HTMLTestRunner
import time
from config import globalparam
from public.common import sendmail
def run():
test_dir = './testcase'
suite = unittest.defaultTestLoader.discover(start_dir=test_dir,pattern='test*.py')
now = time.strftime('%Y-%m-%d_%H_%M_%S')
reportname = globalparam.report_path + '\\' + 'TestResult' + now + '.html'
with open(reportname,'wb') as f:
runner = HTMLTestRunner.HTMLTestRunner(
stream=f,
title='',
description='Test the import testcase'
)
runner.run(suite)
time.sleep(3)
mail = sendmail.SendMail()
mail.send()
if __name__=='__main__':
run()
|
package com.hacks.collegebarter.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hacks.collegebarter.R;
import com.hacks.collegebarter.navdrawer.MainAppActivity;
public class TradeboardFragment extends Fragment{
public static final String ARG_SECTION_NUMBER = "section_number";
// Following constructor
public TradeboardFragment() {
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, 0);
this.setArguments(bundle);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tradeboard_fragment, container,
false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainAppActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
}
|
#ifndef <API key>
#define <API key>
#include <drm/generate_fac_vb.h>
#include "drm_util.h"
namespace gr {
namespace drm {
class <API key> : public generate_fac_vb
{
private:
transm_params* d_tp;
unsigned short d_tf_ctr; // transmission frame counter
public:
<API key>(transm_params* tp);
~<API key>();
void init_data(unsigned char* data); // set FAC bitstream according to config parameters (see DRM standard chapter 6.3)
void increment_tf_ctr(); // increments tf_ctr and takes account of wraparound;
// Where all the action really happens
int work(int noutput_items,
<API key> &input_items,
gr_vector_void_star &output_items);
};
} // namespace drm
} // namespace gr
#endif /* <API key> */
|
# -*- coding: utf-8 -*-
from pyload.plugin.internal.DeadCrypter import DeadCrypter
class FiredriveCom(DeadCrypter):
__name = "FiredriveCom"
__type = "crypter"
__version = "0.03"
__pattern = r'https?://(?:www\.)?(firedrive|putlocker)\.com/share/.+'
__config = [] #@TODO: Remove in 0.4.10
__description = """Firedrive.com folder decrypter plugin"""
__license = "GPLv3"
__authors = [("Walter Purcaro", "vuolter@gmail.com")]
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Portal.BLL.Concrete.Multimedia.AdjusterParam;
using Portal.BLL.Concrete.Multimedia.Adjusters;
using Portal.BLL.Concrete.Multimedia.Builder;
using Portal.Domain.BackendContext.Entity;
namespace Portal.BLL.Tests.MultimediaTests
{
[TestClass]
public class <API key>
{
[TestMethod]
public void <API key>()
{
//Arrange
const string imageFormat = "imageFormat";
const string contentType = "contentType";
var screenshotAdjuster = new Mock<IScreenshotAdjuster>();
var builder = new <API key>(screenshotAdjuster.Object);
var <API key> = new <API key>();
var screenshotParm = new ScreenshotParam();
screenshotAdjuster.Setup(m => m.<API key>(<API key>)).Returns(screenshotParm);
//Act
var processedScreenshot = builder.<API key>(<API key>, imageFormat, contentType);
//Assert
Assert.AreEqual(screenshotParm,processedScreenshot.ScreenshotParam);
Assert.AreEqual(imageFormat, processedScreenshot.ImageFormat);
Assert.AreEqual(contentType,processedScreenshot.ContentType);
}
}
}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>GNU Radio 3.6.4.2 C++ API: <API key> Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">GNU Radio 3.6.4.2 C++ API
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('<API key>.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pro-methods">Protected Member Functions</a> |
<a href="#friends">Friends</a> </div>
<div class="headertitle">
<div class="title"><API key> Class Reference<div class="ingroups"><a class="el" href="group__source__blk.html">Signal Sources</a></div></div> </div>
</div><!--header
<div class="contents">
<!-- doxytag: class="<API key>" --><!-- doxytag: inherits="gr_sync_block" -->
<p>Read stream from file descriptor.
<a href="<API key>.html#details">More...</a></p>
<p><code>#include <<a class="el" href="<API key>.html"><API key>.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for <API key>:</div>
<div class="dyncontent">
<div class="center">
<img src="<API key>.png" usemap="#<API key>" alt=""/>
<map id="<API key>" name="<API key>">
<area href="<API key>.html" alt="gr_sync_block" shape="rect" coords="0,56,158,80"/>
<area href="structgr__block.html" alt="gr_block" shape="rect" coords="0,0,158,24"/>
</map>
</div></div>
<p><a href="<API key>.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">~<API key></a> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">work</a> (int noutput_items, <API key> &input_items, gr_vector_void_star &output_items)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">just like <a class="el" href="structgr__block.html#<API key>" title="compute output items from input items">gr_block::general_work</a>, only this arranges to call consume_each for you <a href="#<API key>"></a><br/></td></tr>
<tr><td colspan="2"><h2><a name="pro-methods"></a>
Protected Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> (size_t itemsize, int fd, <a class="el" href="stdbool_8h.html#<API key>">bool</a> repeat)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">read_items</a> (char *buf, int nitems)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">handle_residue</a> (char *buf, int nbytes_read)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="volk_8tmpl_8h.html#<API key>">void</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">flush_residue</a> ()</td></tr>
<tr><td colspan="2"><h2><a name="friends"></a>
Friends</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="gr__core__api_8h.html#<API key>">GR_CORE_API</a> <br class="typebreak"/>
<a class="el" href="<API key>.html"><API key></a> </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> (size_t itemsize, int fd, <a class="el" href="stdbool_8h.html#<API key>">bool</a> repeat)</td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>Read stream from file descriptor. </p>
</div><hr/><h2>Constructor & Destructor Documentation</h2>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="<API key>::<API key>" ref="<API key>" args="(size_t itemsize, int fd, bool repeat)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="<API key>.html#<API key>"><API key>::<API key></a> </td>
<td>(</td>
<td class="paramtype">size_t </td>
<td class="paramname"><em>itemsize</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>fd</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="stdbool_8h.html#<API key>">bool</a> </td>
<td class="paramname"><em>repeat</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="<API key>::~<API key>" ref="<API key>" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="<API key>.html#<API key>"><API key>::~<API key></a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="<API key>::flush_residue" ref="<API key>" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="volk_8tmpl_8h.html#<API key>">void</a> <a class="el" href="<API key>.html#<API key>"><API key>::flush_residue</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="<API key>::handle_residue" ref="<API key>" args="(char *buf, int nbytes_read)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="<API key>.html#<API key>"><API key>::handle_residue</a> </td>
<td>(</td>
<td class="paramtype">char * </td>
<td class="paramname"><em>buf</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>nbytes_read</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="<API key>::read_items" ref="<API key>" args="(char *buf, int nitems)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="<API key>.html#<API key>"><API key>::read_items</a> </td>
<td>(</td>
<td class="paramtype">char * </td>
<td class="paramname"><em>buf</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>nitems</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="<API key>::work" ref="<API key>" args="(int noutput_items, <API key> &input_items, gr_vector_void_star &output_items)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="<API key>.html#<API key>"><API key>::work</a> </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>noutput_items</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><API key> & </td>
<td class="paramname"><em>input_items</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">gr_vector_void_star & </td>
<td class="paramname"><em>output_items</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>just like <a class="el" href="structgr__block.html#<API key>" title="compute output items from input items">gr_block::general_work</a>, only this arranges to call consume_each for you </p>
<p>The user must override work to define the signal processing code </p>
<p>Reimplemented from <a class="el" href="<API key>.html#<API key>">gr_sync_block</a>.</p>
</div>
</div>
<hr/><h2>Friends And Related Function Documentation</h2>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="<API key>::<API key>" ref="<API key>" args="(size_t itemsize, int fd, bool repeat)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="gr__core__api_8h.html#<API key>">GR_CORE_API</a> <a class="el" href="<API key>.html"><API key></a> <a class="el" href="<API key>.html#<API key>"><API key></a> </td>
<td>(</td>
<td class="paramtype">size_t </td>
<td class="paramname"><em>itemsize</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>fd</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="stdbool_8h.html#<API key>">bool</a> </td>
<td class="paramname"><em>repeat</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [friend]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="<API key>.html"><API key>.h</a></li>
</ul>
</div><!-- contents -->
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="<API key>.html"><API key></a> </li>
<li class="footer">Generated on Mon Oct 14 2013 11:58:16 for GNU Radio 3.6.4.2 C++ API by
<a href="http:
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li>
</ul>
</div>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.