hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
04bd4cb2e908d4b5de7878dbc8d0327b3e0a6a2b | 1,140 | cc | C++ | lib/far/manifest.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | lib/far/manifest.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | lib/far/manifest.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "garnet/lib/far/manifest.h"
#include <stdio.h>
#include "garnet/lib/far/archive_entry.h"
#include "garnet/lib/far/archive_writer.h"
#include "lib/fxl/files/file.h"
#include "lib/fxl/strings/split_string.h"
namespace archive {
bool ReadManifest(fxl::StringView path, ArchiveWriter* writer) {
std::string manifest;
if (!files::ReadFileToString(path.ToString(), &manifest)) {
fprintf(stderr, "error: Faile to read '%s'\n", path.ToString().c_str());
return false;
}
std::vector<fxl::StringView> lines =
fxl::SplitString(manifest, "\n", fxl::WhiteSpaceHandling::kKeepWhitespace,
fxl::SplitResult::kSplitWantNonEmpty);
for (const auto& line : lines) {
size_t offset = line.find('=');
if (offset == std::string::npos)
continue;
writer->Add(ArchiveEntry(line.substr(offset + 1).ToString(),
line.substr(0, offset).ToString()));
}
return true;
}
} // namespace archive
| 29.230769 | 80 | 0.666667 | PowerOlive |
04c38aa757ac89e639ef2dc40de352a9681f2ef4 | 1,509 | cpp | C++ | Sources/Kore/Display.cpp | foundry2D/Kinc | 890baf38d0be53444ebfdeac8662479b23d169ea | [
"Zlib"
] | 203 | 2019-05-30T22:40:19.000Z | 2022-03-16T22:01:09.000Z | Sources/Kore/Display.cpp | foundry2D/Kinc | 890baf38d0be53444ebfdeac8662479b23d169ea | [
"Zlib"
] | 136 | 2019-06-01T04:39:33.000Z | 2022-03-14T12:38:03.000Z | Sources/Kore/Display.cpp | foundry2D/Kinc | 890baf38d0be53444ebfdeac8662479b23d169ea | [
"Zlib"
] | 211 | 2019-06-05T12:22:57.000Z | 2022-03-24T08:44:18.000Z | #include "Display.h"
#include <kinc/display.h>
using namespace Kore;
namespace {
const int MAXIMUM_DISPLAYS = 16;
Display displays[MAXIMUM_DISPLAYS];
}
void Display::init() {
kinc_display_init();
}
Display *Display::primary() {
displays[kinc_primary_display()]._index = kinc_primary_display();
return &displays[kinc_primary_display()];
}
Display *Display::get(int index) {
displays[index]._index = index;
return &displays[index];
}
int Display::count() {
return kinc_count_displays();
}
bool Display::available() {
return kinc_display_available(_index);
}
const char *Display::name() {
return kinc_display_name(_index);
}
int Display::x() {
return kinc_display_current_mode(_index).x;
}
int Display::y() {
return kinc_display_current_mode(_index).y;
}
int Display::width() {
return kinc_display_current_mode(_index).width;
}
int Display::height() {
return kinc_display_current_mode(_index).height;
}
int Display::frequency() {
return kinc_display_current_mode(_index).frequency;
}
int Display::pixelsPerInch() {
return kinc_display_current_mode(_index).pixels_per_inch;
}
DisplayMode Display::availableMode(int index) {
DisplayMode mode;
kinc_display_mode_t kMode = kinc_display_available_mode(_index, index);
mode.width = kMode.width;
mode.height = kMode.height;
mode.frequency = kMode.frequency;
mode.bitsPerPixel = kMode.bits_per_pixel;
return mode;
}
int Display::countAvailableModes() {
return kinc_display_count_available_modes(_index);
}
Display::Display() {}
| 19.597403 | 72 | 0.75613 | foundry2D |
04c4cf9b035e7b5eed86758e88bb173463ee2b0d | 2,162 | cpp | C++ | openbmc_modules/phosphor-fan-presence/monitor/main.cpp | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | 14 | 2021-11-04T07:47:37.000Z | 2022-03-21T10:10:30.000Z | openbmc_modules/phosphor-fan-presence/monitor/main.cpp | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | null | null | null | openbmc_modules/phosphor-fan-presence/monitor/main.cpp | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | /**
* Copyright © 2017 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "argument.hpp"
#include "fan.hpp"
#include "system.hpp"
#include "trust_manager.hpp"
#include <sdbusplus/bus.hpp>
#include <sdeventplus/event.hpp>
#include <sdeventplus/source/signal.hpp>
#include <stdplus/signal.hpp>
using namespace phosphor::fan::monitor;
int main(int argc, char* argv[])
{
auto event = sdeventplus::Event::get_default();
auto bus = sdbusplus::bus::new_default();
phosphor::fan::util::ArgumentParser args(argc, argv);
if (argc != 2)
{
args.usage(argv);
return 1;
}
Mode mode;
if (args["init"] == "true")
{
mode = Mode::init;
}
else if (args["monitor"] == "true")
{
mode = Mode::monitor;
}
else
{
args.usage(argv);
return 1;
}
// Attach the event object to the bus object so we can
// handle both sd_events (for the timers) and dbus signals.
bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
System system(mode, bus, event);
#ifdef MONITOR_USE_JSON
// Enable SIGHUP handling to reload JSON config
stdplus::signal::block(SIGHUP);
sdeventplus::source::Signal signal(event, SIGHUP,
std::bind(&System::sighupHandler,
&system, std::placeholders::_1,
std::placeholders::_2));
#endif
if (mode == Mode::init)
{
// Fans were initialized to be functional, exit
return 0;
}
return event.loop();
}
| 27.025 | 80 | 0.618409 | Eyerunmyden |
04c6e26e243767d876a118491c35ca4de1595f39 | 32,524 | cpp | C++ | miniapps/meshing/mesh-explorer.cpp | liruipeng/mfem | bf3f1f1327f064baae40693256c9559feae1a99a | [
"BSD-3-Clause"
] | null | null | null | miniapps/meshing/mesh-explorer.cpp | liruipeng/mfem | bf3f1f1327f064baae40693256c9559feae1a99a | [
"BSD-3-Clause"
] | 1 | 2020-04-21T00:30:35.000Z | 2020-04-21T00:32:28.000Z | miniapps/meshing/mesh-explorer.cpp | liruipeng/mfem | bf3f1f1327f064baae40693256c9559feae1a99a | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
//
// -----------------------------------------------------
// Mesh Explorer Miniapp: Explore and manipulate meshes
// -----------------------------------------------------
//
// This miniapp is a handy tool to examine, visualize and manipulate a given
// mesh. Some of its features are:
//
// - visualizing of mesh materials and individual mesh elements
// - mesh scaling, randomization, and general transformation
// - manipulation of the mesh curvature
// - the ability to simulate parallel partitioning
// - quantitative and visual reports of mesh quality
//
// Compile with: make mesh-explorer
//
// Sample runs: mesh-explorer
// mesh-explorer -m ../../data/beam-tri.mesh
// mesh-explorer -m ../../data/star-q2.mesh
// mesh-explorer -m ../../data/disc-nurbs.mesh
// mesh-explorer -m ../../data/escher-p3.mesh
// mesh-explorer -m ../../data/mobius-strip.mesh
#include "mfem.hpp"
#include <fstream>
#include <limits>
#include <cstdlib>
using namespace mfem;
using namespace std;
// This transformation can be applied to a mesh with the 't' menu option.
void transformation(const Vector &p, Vector &v)
{
// simple shear transformation
double s = 0.1;
if (p.Size() == 3)
{
v(0) = p(0) + s*p(1) + s*p(2);
v(1) = p(1) + s*p(2) + s*p(0);
v(2) = p(2);
}
else if (p.Size() == 2)
{
v(0) = p(0) + s*p(1);
v(1) = p(1) + s*p(0);
}
else
{
v = p;
}
}
// This function is used with the 'r' menu option, sub-option 'l' to refine a
// mesh locally in a region, defined by return values <= region_eps.
double region_eps = 1e-8;
double region(const Vector &p)
{
const double x = p(0), y = p(1);
// here we describe the region: (x <= 1/4) && (y >= 0) && (y <= 1)
return std::max(std::max(x - 0.25, -y), y - 1.0);
}
// The projection of this function can be plotted with the 'l' menu option
double f(const Vector &p)
{
double x = p(0);
double y = p.Size() > 1 ? p(1) : 0.0;
double z = p.Size() > 2 ? p(2) : 0.0;
if (1)
{
// torus in the xy-plane
const double r_big = 2.0;
const double r_small = 1.0;
return hypot(r_big - hypot(x, y), z) - r_small;
}
if (0)
{
// sphere at the origin:
const double r = 1.0;
return hypot(hypot(x, y), z) - r;
}
}
Mesh *read_par_mesh(int np, const char *mesh_prefix)
{
Mesh *mesh;
Array<Mesh *> mesh_array;
mesh_array.SetSize(np);
for (int p = 0; p < np; p++)
{
ostringstream fname;
fname << mesh_prefix << '.' << setfill('0') << setw(6) << p;
ifgzstream meshin(fname.str().c_str());
if (!meshin)
{
cerr << "Can not open mesh file: " << fname.str().c_str()
<< '!' << endl;
for (p--; p >= 0; p--)
{
delete mesh_array[p];
}
return NULL;
}
mesh_array[p] = new Mesh(meshin, 1, 0);
// set element and boundary attributes to be the processor number + 1
if (1)
{
for (int i = 0; i < mesh_array[p]->GetNE(); i++)
{
mesh_array[p]->GetElement(i)->SetAttribute(p+1);
}
for (int i = 0; i < mesh_array[p]->GetNBE(); i++)
{
mesh_array[p]->GetBdrElement(i)->SetAttribute(p+1);
}
}
}
mesh = new Mesh(mesh_array, np);
for (int p = 0; p < np; p++)
{
delete mesh_array[np-1-p];
}
mesh_array.DeleteAll();
return mesh;
}
// Given a 3D mesh, produce a 2D mesh consisting of its boundary elements.
Mesh *skin_mesh(Mesh *mesh)
{
// Determine mapping from vertex to boundary vertex
Array<int> v2v(mesh->GetNV());
v2v = -1;
for (int i = 0; i < mesh->GetNBE(); i++)
{
Element *el = mesh->GetBdrElement(i);
int *v = el->GetVertices();
int nv = el->GetNVertices();
for (int j = 0; j < nv; j++)
{
v2v[v[j]] = 0;
}
}
int nbvt = 0;
for (int i = 0; i < v2v.Size(); i++)
{
if (v2v[i] == 0)
{
v2v[i] = nbvt++;
}
}
// Create a new mesh for the boundary
Mesh * bmesh = new Mesh(mesh->Dimension() - 1, nbvt, mesh->GetNBE(),
0, mesh->SpaceDimension());
// Copy vertices to the boundary mesh
nbvt = 0;
for (int i = 0; i < v2v.Size(); i++)
{
if (v2v[i] >= 0)
{
double *c = mesh->GetVertex(i);
bmesh->AddVertex(c);
nbvt++;
}
}
// Copy elements to the boundary mesh
int bv[4];
for (int i = 0; i < mesh->GetNBE(); i++)
{
Element *el = mesh->GetBdrElement(i);
int *v = el->GetVertices();
int nv = el->GetNVertices();
for (int j = 0; j < nv; j++)
{
bv[j] = v2v[v[j]];
}
switch (el->GetGeometryType())
{
case Geometry::SEGMENT:
bmesh->AddSegment(bv, el->GetAttribute());
break;
case Geometry::TRIANGLE:
bmesh->AddTriangle(bv, el->GetAttribute());
break;
case Geometry::SQUARE:
bmesh->AddQuad(bv, el->GetAttribute());
break;
default:
break; /// This should not happen
}
}
bmesh->FinalizeTopology();
// Copy GridFunction describing nodes if present
if (mesh->GetNodes())
{
FiniteElementSpace *fes = mesh->GetNodes()->FESpace();
const FiniteElementCollection *fec = fes->FEColl();
if (dynamic_cast<const H1_FECollection*>(fec))
{
FiniteElementCollection *fec_copy =
FiniteElementCollection::New(fec->Name());
FiniteElementSpace *fes_copy =
new FiniteElementSpace(*fes, bmesh, fec_copy);
GridFunction *bdr_nodes = new GridFunction(fes_copy);
bdr_nodes->MakeOwner(fec_copy);
bmesh->NewNodes(*bdr_nodes, true);
Array<int> vdofs;
Array<int> bvdofs;
Vector v;
for (int i=0; i<mesh->GetNBE(); i++)
{
fes->GetBdrElementVDofs(i, vdofs);
mesh->GetNodes()->GetSubVector(vdofs, v);
fes_copy->GetElementVDofs(i, bvdofs);
bdr_nodes->SetSubVector(bvdofs, v);
}
}
else
{
cout << "\nDiscontinuous nodes not yet supported" << endl;
}
}
return bmesh;
}
int main (int argc, char *argv[])
{
int np = 0;
const char *mesh_file = "../../data/beam-hex.mesh";
bool refine = true;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to visualize.");
args.AddOption(&np, "-np", "--num-proc",
"Load mesh from multiple processors.");
args.AddOption(&refine, "-ref", "--refinement", "-no-ref", "--no-refinement",
"Prepare the mesh for refinement or not.");
args.Parse();
if (!args.Good())
{
if (!args.Help())
{
args.PrintError(cout);
cout << endl;
}
cout << "Visualize and manipulate a serial mesh:\n"
<< " mesh-explorer -m <mesh_file>\n"
<< "Visualize and manipulate a parallel mesh:\n"
<< " mesh-explorer -np <#proc> -m <mesh_prefix>\n" << endl
<< "All Options:\n";
args.PrintHelp(cout);
return 1;
}
args.PrintOptions(cout);
Mesh *mesh;
Mesh *bdr_mesh = NULL;
if (np <= 0)
{
mesh = new Mesh(mesh_file, 1, refine);
}
else
{
mesh = read_par_mesh(np, mesh_file);
if (mesh == NULL)
{
return 3;
}
}
int dim = mesh->Dimension();
int sdim = mesh->SpaceDimension();
FiniteElementCollection *bdr_attr_fec = NULL;
FiniteElementCollection *attr_fec;
if (dim == 2)
{
attr_fec = new Const2DFECollection;
}
else
{
bdr_attr_fec = new Const2DFECollection;
attr_fec = new Const3DFECollection;
}
int print_char = 1;
while (1)
{
if (print_char)
{
cout << endl;
mesh->PrintCharacteristics();
cout << "boundary attribs :";
for (int i = 0; i < mesh->bdr_attributes.Size(); i++)
{
cout << ' ' << mesh->bdr_attributes[i];
}
cout << '\n' << "material attribs :";
for (int i = 0; i < mesh->attributes.Size(); i++)
{
cout << ' ' << mesh->attributes[i];
}
cout << endl;
cout << "mesh curvature : ";
if (mesh->GetNodalFESpace() != NULL)
{
cout << mesh->GetNodalFESpace()->FEColl()->Name() << endl;
}
else
{
cout << "NONE" << endl;
}
}
print_char = 0;
cout << endl;
cout << "What would you like to do?\n"
"r) Refine\n"
"c) Change curvature\n"
"s) Scale\n"
"t) Transform\n"
"j) Jitter\n"
"v) View\n"
"m) View materials\n"
"b) View boundary\n"
"e) View elements\n"
"h) View element sizes, h\n"
"k) View element ratios, kappa\n"
"l) Plot a function\n"
"x) Print sub-element stats\n"
"f) Find physical point in reference space\n"
"p) Generate a partitioning\n"
"o) Reorder elements\n"
"S) Save in MFEM format\n"
"V) Save in VTK format (only linear and quadratic meshes)\n"
"q) Quit\n"
#ifdef MFEM_USE_ZLIB
"Z) Save in MFEM format with compression\n"
#endif
"--> " << flush;
char mk;
cin >> mk;
if (!cin) { break; }
if (mk == 'q')
{
break;
}
if (mk == 'r')
{
cout <<
"Choose type of refinement:\n"
"s) standard refinement with Mesh::UniformRefinement()\n"
"b) Mesh::UniformRefinement() (bisection for tet meshes)\n"
"u) uniform refinement with a factor\n"
"g) non-uniform refinement (Gauss-Lobatto) with a factor\n"
"l) refine locally using the region() function\n"
"--> " << flush;
char sk;
cin >> sk;
switch (sk)
{
case 's':
mesh->UniformRefinement();
// Make sure tet-only meshes are marked for local refinement.
mesh->Finalize(true);
break;
case 'b':
mesh->UniformRefinement(1); // ref_algo = 1
break;
case 'u':
case 'g':
{
cout << "enter refinement factor --> " << flush;
int ref_factor;
cin >> ref_factor;
if (ref_factor <= 1 || ref_factor > 32) { break; }
int ref_type = (sk == 'u') ? BasisType::ClosedUniform :
BasisType::GaussLobatto;
Mesh *rmesh = new Mesh(mesh, ref_factor, ref_type);
delete mesh;
mesh = rmesh;
break;
}
case 'l':
{
Vector pt;
Array<int> marked_elements;
for (int i = 0; i < mesh->GetNE(); i++)
{
// check all nodes of the element
IsoparametricTransformation T;
mesh->GetElementTransformation(i, &T);
for (int j = 0; j < T.GetPointMat().Width(); j++)
{
T.GetPointMat().GetColumnReference(j, pt);
if (region(pt) <= region_eps)
{
marked_elements.Append(i);
break;
}
}
}
mesh->GeneralRefinement(marked_elements);
break;
}
}
print_char = 1;
}
if (mk == 'c')
{
int p;
cout << "enter new order for mesh curvature --> " << flush;
cin >> p;
mesh->SetCurvature(p > 0 ? p : -p, p <= 0);
print_char = 1;
}
if (mk == 's')
{
double factor;
cout << "scaling factor ---> " << flush;
cin >> factor;
GridFunction *nodes = mesh->GetNodes();
if (nodes == NULL)
{
for (int i = 0; i < mesh->GetNV(); i++)
{
double *v = mesh->GetVertex(i);
v[0] *= factor;
v[1] *= factor;
if (dim == 3)
{
v[2] *= factor;
}
}
}
else
{
*nodes *= factor;
}
print_char = 1;
}
if (mk == 't')
{
mesh->Transform(transformation);
print_char = 1;
}
if (mk == 'j')
{
double jitter;
cout << "jitter factor ---> " << flush;
cin >> jitter;
GridFunction *nodes = mesh->GetNodes();
if (nodes == NULL)
{
cerr << "The mesh should have nodes, introduce curvature first!\n";
}
else
{
FiniteElementSpace *fespace = nodes->FESpace();
GridFunction rdm(fespace);
rdm.Randomize();
rdm -= 0.5; // shift to random values in [-0.5,0.5]
rdm *= jitter;
// compute minimal local mesh size
Vector h0(fespace->GetNDofs());
h0 = infinity();
{
Array<int> dofs;
for (int i = 0; i < fespace->GetNE(); i++)
{
fespace->GetElementDofs(i, dofs);
for (int j = 0; j < dofs.Size(); j++)
{
h0(dofs[j]) = std::min(h0(dofs[j]), mesh->GetElementSize(i));
}
}
}
// scale the random values to be of order of the local mesh size
for (int i = 0; i < fespace->GetNDofs(); i++)
{
for (int d = 0; d < dim; d++)
{
rdm(fespace->DofToVDof(i,d)) *= h0(i);
}
}
char move_bdr = 'n';
cout << "move boundary nodes? [y/n] ---> " << flush;
cin >> move_bdr;
// don't perturb the boundary
if (move_bdr == 'n')
{
Array<int> vdofs;
for (int i = 0; i < fespace->GetNBE(); i++)
{
fespace->GetBdrElementVDofs(i, vdofs);
for (int j = 0; j < vdofs.Size(); j++)
{
rdm(vdofs[j]) = 0.0;
}
}
}
*nodes += rdm;
}
print_char = 1;
}
if (mk == 'x')
{
int sd, nz = 0;
DenseMatrix J(dim);
double min_det_J, max_det_J, min_det_J_z, max_det_J_z;
double min_kappa, max_kappa, max_ratio_det_J_z;
min_det_J = min_kappa = infinity();
max_det_J = max_kappa = max_ratio_det_J_z = -infinity();
cout << "subdivision factor ---> " << flush;
cin >> sd;
Array<int> bad_elems_by_geom(Geometry::NumGeom);
bad_elems_by_geom = 0;
for (int i = 0; i < mesh->GetNE(); i++)
{
Geometry::Type geom = mesh->GetElementBaseGeometry(i);
ElementTransformation *T = mesh->GetElementTransformation(i);
RefinedGeometry *RefG = GlobGeometryRefiner.Refine(geom, sd, 1);
IntegrationRule &ir = RefG->RefPts;
min_det_J_z = infinity();
max_det_J_z = -infinity();
for (int j = 0; j < ir.GetNPoints(); j++)
{
T->SetIntPoint(&ir.IntPoint(j));
Geometries.JacToPerfJac(geom, T->Jacobian(), J);
double det_J = J.Det();
double kappa =
J.CalcSingularvalue(0) / J.CalcSingularvalue(dim-1);
min_det_J_z = fmin(min_det_J_z, det_J);
max_det_J_z = fmax(max_det_J_z, det_J);
min_kappa = fmin(min_kappa, kappa);
max_kappa = fmax(max_kappa, kappa);
}
max_ratio_det_J_z =
fmax(max_ratio_det_J_z, max_det_J_z/min_det_J_z);
min_det_J = fmin(min_det_J, min_det_J_z);
max_det_J = fmax(max_det_J, max_det_J_z);
if (min_det_J_z <= 0.0)
{
nz++;
bad_elems_by_geom[geom]++;
}
}
cout << "\nbad elements = " << nz;
if (nz)
{
cout << " -- ";
Mesh::PrintElementsByGeometry(dim, bad_elems_by_geom, cout);
}
cout << "\nmin det(J) = " << min_det_J
<< "\nmax det(J) = " << max_det_J
<< "\nglobal ratio = " << max_det_J/min_det_J
<< "\nmax el ratio = " << max_ratio_det_J_z
<< "\nmin kappa = " << min_kappa
<< "\nmax kappa = " << max_kappa << endl;
}
if (mk == 'f')
{
DenseMatrix point_mat(sdim,1);
cout << "\npoint in physical space ---> " << flush;
for (int i = 0; i < sdim; i++)
{
cin >> point_mat(i,0);
}
Array<int> elem_ids;
Array<IntegrationPoint> ips;
// physical -> reference space
mesh->FindPoints(point_mat, elem_ids, ips);
cout << "point in reference space:";
if (elem_ids[0] == -1)
{
cout << " NOT FOUND!\n";
}
else
{
cout << " element " << elem_ids[0] << ", ip =";
cout << " " << ips[0].x;
if (sdim > 1)
{
cout << " " << ips[0].y;
if (sdim > 2)
{
cout << " " << ips[0].z;
}
}
cout << endl;
}
}
if (mk == 'o')
{
cout << "What type of reordering?\n"
"g) Gecko edge-product minimization\n"
"h) Hilbert spatial sort\n"
"--> " << flush;
char rk;
cin >> rk;
Array<int> ordering, tentative;
if (rk == 'h')
{
mesh->GetHilbertElementOrdering(ordering);
mesh->ReorderElements(ordering);
}
else if (rk == 'g')
{
int outer, inner, window, period;
cout << "Enter number of outer iterations (default 5): " << flush;
cin >> outer;
cout << "Enter number of inner iterations (default 4): " << flush;
cin >> inner;
cout << "Enter window size (default 4, beware of exponential cost): "
<< flush;
cin >> window;
cout << "Enter period for window size increment (default 2): "
<< flush;
cin >> period;
double best_cost = infinity();
for (int i = 0; i < outer; i++)
{
int seed = i+1;
double cost = mesh->GetGeckoElementOrdering(
tentative, inner, window, period, seed, true);
if (cost < best_cost)
{
ordering = tentative;
best_cost = cost;
}
}
cout << "Final cost: " << best_cost << endl;
mesh->ReorderElements(ordering);
}
}
// These are most of the cases that open a new GLVis window
if (mk == 'm' || mk == 'b' || mk == 'e' || mk == 'v' || mk == 'h' ||
mk == 'k' || mk == 'p')
{
Array<int> bdr_part;
Array<int> part(mesh->GetNE());
FiniteElementSpace *bdr_attr_fespace = NULL;
FiniteElementSpace *attr_fespace =
new FiniteElementSpace(mesh, attr_fec);
GridFunction bdr_attr;
GridFunction attr(attr_fespace);
if (mk == 'm')
{
for (int i = 0; i < mesh->GetNE(); i++)
{
part[i] = (attr(i) = mesh->GetAttribute(i)) - 1;
}
}
if (mk == 'b')
{
if (dim == 3)
{
delete bdr_mesh;
bdr_mesh = skin_mesh(mesh);
bdr_attr_fespace =
new FiniteElementSpace(bdr_mesh, bdr_attr_fec);
bdr_part.SetSize(bdr_mesh->GetNE());
bdr_attr.SetSpace(bdr_attr_fespace);
for (int i = 0; i < bdr_mesh->GetNE(); i++)
{
bdr_part[i] = (bdr_attr(i) = bdr_mesh->GetAttribute(i)) - 1;
}
}
else
{
attr = 1.0;
}
}
if (mk == 'v')
{
attr = 1.0;
}
if (mk == 'e')
{
Array<int> coloring;
srand(time(0));
double a = double(rand()) / (double(RAND_MAX) + 1.);
int el0 = (int)floor(a * mesh->GetNE());
cout << "Generating coloring starting with element " << el0+1
<< " / " << mesh->GetNE() << endl;
mesh->GetElementColoring(coloring, el0);
for (int i = 0; i < coloring.Size(); i++)
{
attr(i) = coloring[i];
}
cout << "Number of colors: " << attr.Max() + 1 << endl;
for (int i = 0; i < mesh->GetNE(); i++)
{
// part[i] = i; // checkerboard element coloring
attr(i) = part[i] = i; // coloring by element number
}
}
if (mk == 'h')
{
DenseMatrix J(dim);
double h_min, h_max;
h_min = infinity();
h_max = -h_min;
for (int i = 0; i < mesh->GetNE(); i++)
{
int geom = mesh->GetElementBaseGeometry(i);
ElementTransformation *T = mesh->GetElementTransformation(i);
T->SetIntPoint(&Geometries.GetCenter(geom));
Geometries.JacToPerfJac(geom, T->Jacobian(), J);
attr(i) = J.Det();
if (attr(i) < 0.0)
{
attr(i) = -pow(-attr(i), 1.0/double(dim));
}
else
{
attr(i) = pow(attr(i), 1.0/double(dim));
}
h_min = min(h_min, attr(i));
h_max = max(h_max, attr(i));
}
cout << "h_min = " << h_min << ", h_max = " << h_max << endl;
}
if (mk == 'k')
{
DenseMatrix J(dim);
for (int i = 0; i < mesh->GetNE(); i++)
{
int geom = mesh->GetElementBaseGeometry(i);
ElementTransformation *T = mesh->GetElementTransformation(i);
T->SetIntPoint(&Geometries.GetCenter(geom));
Geometries.JacToPerfJac(geom, T->Jacobian(), J);
attr(i) = J.CalcSingularvalue(0) / J.CalcSingularvalue(dim-1);
}
}
if (mk == 'p')
{
int *partitioning = NULL, np;
cout << "What type of partitioning?\n"
"c) Cartesian\n"
"s) Simple 1D split of the element sequence\n"
"0) METIS_PartGraphRecursive (sorted neighbor lists)\n"
"1) METIS_PartGraphKway (sorted neighbor lists)"
" (default)\n"
"2) METIS_PartGraphVKway (sorted neighbor lists)\n"
"3) METIS_PartGraphRecursive\n"
"4) METIS_PartGraphKway\n"
"5) METIS_PartGraphVKway\n"
"--> " << flush;
char pk;
cin >> pk;
if (pk == 'c')
{
int nxyz[3];
cout << "Enter nx: " << flush;
cin >> nxyz[0]; np = nxyz[0];
if (mesh->Dimension() > 1)
{
cout << "Enter ny: " << flush;
cin >> nxyz[1]; np *= nxyz[1];
if (mesh->Dimension() > 2)
{
cout << "Enter nz: " << flush;
cin >> nxyz[2]; np *= nxyz[2];
}
}
partitioning = mesh->CartesianPartitioning(nxyz);
}
else if (pk == 's')
{
cout << "Enter number of processors: " << flush;
cin >> np;
partitioning = new int[mesh->GetNE()];
for (int i = 0; i < mesh->GetNE(); i++)
{
partitioning[i] = i * np / mesh->GetNE();
}
}
else
{
int part_method = pk - '0';
if (part_method < 0 || part_method > 5)
{
continue;
}
cout << "Enter number of processors: " << flush;
cin >> np;
partitioning = mesh->GeneratePartitioning(np, part_method);
}
if (partitioning)
{
const char part_file[] = "partitioning.txt";
ofstream opart(part_file);
opart << "number_of_elements " << mesh->GetNE() << '\n'
<< "number_of_processors " << np << '\n';
for (int i = 0; i < mesh->GetNE(); i++)
{
opart << partitioning[i] << '\n';
}
cout << "Partitioning file: " << part_file << endl;
Array<int> proc_el(np);
proc_el = 0;
for (int i = 0; i < mesh->GetNE(); i++)
{
proc_el[partitioning[i]]++;
}
int min_el = proc_el[0], max_el = proc_el[0];
for (int i = 1; i < np; i++)
{
if (min_el > proc_el[i])
{
min_el = proc_el[i];
}
if (max_el < proc_el[i])
{
max_el = proc_el[i];
}
}
cout << "Partitioning stats:\n"
<< " "
<< setw(12) << "minimum"
<< setw(12) << "average"
<< setw(12) << "maximum"
<< setw(12) << "total" << '\n';
cout << " elements "
<< setw(12) << min_el
<< setw(12) << double(mesh->GetNE())/np
<< setw(12) << max_el
<< setw(12) << mesh->GetNE() << endl;
}
else
{
continue;
}
for (int i = 0; i < mesh->GetNE(); i++)
{
attr(i) = part[i] = partitioning[i];
}
delete [] partitioning;
}
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
if (sol_sock.is_open())
{
sol_sock.precision(14);
if (sdim == 2)
{
sol_sock << "fem2d_gf_data_keys\n";
if (mk != 'p')
{
mesh->Print(sol_sock);
}
else
{
// NURBS meshes do not support PrintWithPartitioning
if (mesh->NURBSext)
{
mesh->Print(sol_sock);
for (int i = 0; i < mesh->GetNE(); i++)
{
attr(i) = part[i];
}
}
else
{
mesh->PrintWithPartitioning(part, sol_sock, 1);
}
}
attr.Save(sol_sock);
sol_sock << "RjlmAb***********";
if (mk == 'v')
{
sol_sock << "e";
}
else
{
sol_sock << "\n";
}
}
else
{
sol_sock << "fem3d_gf_data_keys\n";
if (mk == 'v' || mk == 'h' || mk == 'k')
{
mesh->Print(sol_sock);
}
else if (mk == 'b')
{
bdr_mesh->Print(sol_sock);
bdr_attr.Save(sol_sock);
sol_sock << "mcaaA";
// Switch to a discrete color scale
sol_sock << "pppppp" << "pppppp" << "pppppp";
}
else
{
// NURBS meshes do not support PrintWithPartitioning
if (mesh->NURBSext)
{
mesh->Print(sol_sock);
for (int i = 0; i < mesh->GetNE(); i++)
{
attr(i) = part[i];
}
}
else
{
mesh->PrintWithPartitioning(part, sol_sock);
}
}
if (mk != 'b')
{
attr.Save(sol_sock);
sol_sock << "maaA";
if (mk == 'v')
{
sol_sock << "aa";
}
else
{
sol_sock << "\n";
}
}
}
sol_sock << flush;
}
else
{
cout << "Unable to connect to "
<< vishost << ':' << visport << endl;
}
delete attr_fespace;
delete bdr_attr_fespace;
}
if (mk == 'l')
{
// Project and plot the function 'f'
int p;
FiniteElementCollection *fec = NULL;
cout << "Enter projection space order: " << flush;
cin >> p;
if (p >= 1)
{
fec = new H1_FECollection(p, mesh->Dimension(),
BasisType::GaussLobatto);
}
else
{
fec = new DG_FECollection(-p, mesh->Dimension(),
BasisType::GaussLegendre);
}
FiniteElementSpace fes(mesh, fec);
GridFunction level(&fes);
FunctionCoefficient coeff(f);
level.ProjectCoefficient(coeff);
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
if (sol_sock.is_open())
{
sol_sock.precision(14);
sol_sock << "solution\n" << *mesh << level << flush;
}
else
{
cout << "Unable to connect to "
<< vishost << ':' << visport << endl;
}
delete fec;
}
if (mk == 'S')
{
const char mesh_file[] = "mesh-explorer.mesh";
ofstream omesh(mesh_file);
omesh.precision(14);
mesh->Print(omesh);
cout << "New mesh file: " << mesh_file << endl;
}
if (mk == 'V')
{
const char mesh_file[] = "mesh-explorer.vtk";
ofstream omesh(mesh_file);
omesh.precision(14);
mesh->PrintVTK(omesh);
cout << "New VTK mesh file: " << mesh_file << endl;
}
#ifdef MFEM_USE_ZLIB
if (mk == 'Z')
{
const char mesh_file[] = "mesh-explorer.mesh.gz";
ofgzstream omesh(mesh_file, "zwb9");
omesh.precision(14);
mesh->Print(omesh);
cout << "New mesh file: " << mesh_file << endl;
}
#endif
}
delete bdr_attr_fec;
delete attr_fec;
delete bdr_mesh;
delete mesh;
return 0;
}
| 30.114815 | 82 | 0.432388 | liruipeng |
04cc4144cb271c7f973845fba2c60cfc12d382c7 | 2,145 | cpp | C++ | linear_structures/linked_list/138_copy-list-with-random-pointer.cpp | b1tank/leetcode | 0b71eb7a4f52291ff072b1280d6b76e68f7adfee | [
"MIT"
] | null | null | null | linear_structures/linked_list/138_copy-list-with-random-pointer.cpp | b1tank/leetcode | 0b71eb7a4f52291ff072b1280d6b76e68f7adfee | [
"MIT"
] | null | null | null | linear_structures/linked_list/138_copy-list-with-random-pointer.cpp | b1tank/leetcode | 0b71eb7a4f52291ff072b1280d6b76e68f7adfee | [
"MIT"
] | null | null | null | // Author: b1tank
// Email: b1tank@outlook.com
//=================================
/*
138_copy-list-with-random-pointer LeetCode
Solution:
- hashmap
- "DNA" replication
- for the original linked list: cut and splice
*/
#include <iostream>
#include <unordered_map>
using namespace std;
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;
Node* cur{head};
// duplicate each node in chain
while (cur) {
Node* tmp = new Node(cur->val);
tmp->next = cur->next;
cur->next = tmp;
cur = cur->next->next;
}
// assign random link for each duplicated node
cur = head;
while (cur) {
cur->next->random = cur->random ? cur->random->next : nullptr;
cur = cur->next->next;
}
// split the chain into two
cur = head;
Node* cur2 = head->next;
Node* res = head->next;
while (cur && cur->next) {
cur->next = cur->next->next;
cur = cur->next;
if (cur2->next) {
cur2->next = cur2->next->next;
cur2 = cur2->next;
}
}
return res;
// Node* res = new Node(0);
// unordered_map<Node*, Node*> m;
//
// Node* cur{head};
// Node* cur_r{res};
// while (cur != nullptr) {
// cur_r->next = new Node(cur->val);
// cur_r = cur_r->next;
// m[cur] = cur_r;
//
// cur = cur->next;
// }
// cur = head;
// cur_r = res->next;
// while (cur != nullptr) {
// cur_r->random = m[cur->random];
// cur_r = cur_r->next;
// cur = cur->next;
// }
// return res->next;
}
};
| 23.315217 | 75 | 0.432168 | b1tank |
04cf10c8d7b9239671878a836a5f185023f89963 | 9,532 | cpp | C++ | modules/gapi/src/streaming/onevpl/accelerators/surface/dx11_frame_adapter.cpp | nowireless/opencv | 1fcc4c74fefee4f845c0d57799163a1cbf36f654 | [
"Apache-2.0"
] | 56,632 | 2016-07-04T16:36:08.000Z | 2022-03-31T18:38:14.000Z | modules/gapi/src/streaming/onevpl/accelerators/surface/dx11_frame_adapter.cpp | nowireless/opencv | 1fcc4c74fefee4f845c0d57799163a1cbf36f654 | [
"Apache-2.0"
] | 13,593 | 2016-07-04T13:59:03.000Z | 2022-03-31T21:04:51.000Z | modules/gapi/src/streaming/onevpl/accelerators/surface/dx11_frame_adapter.cpp | nowireless/opencv | 1fcc4c74fefee4f845c0d57799163a1cbf36f654 | [
"Apache-2.0"
] | 54,986 | 2016-07-04T14:24:38.000Z | 2022-03-31T22:51:18.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2021 Intel Corporation
#include "streaming/onevpl/accelerators/surface/dx11_frame_adapter.hpp"
#include "streaming/onevpl/accelerators/dx11_alloc_resource.hpp"
#include "streaming/onevpl/accelerators/surface/surface.hpp"
#include "logger.hpp"
#ifdef HAVE_ONEVPL
#include "streaming/onevpl/onevpl_export.hpp"
#ifdef HAVE_INF_ENGINE
// For IE classes (ParamMap, etc)
#include <inference_engine.hpp>
#endif // HAVE_INF_ENGINE
namespace cv {
namespace gapi {
namespace wip {
namespace onevpl {
void lock_mid(mfxMemId mid, mfxFrameData &data, MediaFrame::Access mode) {
LockAdapter* alloc_data = reinterpret_cast<LockAdapter *>(mid);
if (mode == MediaFrame::Access::R) {
alloc_data->read_lock(mid, data);
} else {
alloc_data->write_lock(mid, data);
}
}
void unlock_mid(mfxMemId mid, mfxFrameData &data, MediaFrame::Access mode) {
LockAdapter* alloc_data = reinterpret_cast<LockAdapter*>(data.MemId);
if (mode == MediaFrame::Access::R) {
alloc_data->unlock_read(mid, data);
} else {
alloc_data->unlock_write(mid, data);
}
}
VPLMediaFrameDX11Adapter::VPLMediaFrameDX11Adapter(std::shared_ptr<Surface> surface):
parent_surface_ptr(surface) {
GAPI_Assert(parent_surface_ptr && "Surface is nullptr");
const Surface::info_t& info = parent_surface_ptr->get_info();
Surface::data_t& data = parent_surface_ptr->get_data();
GAPI_LOG_DEBUG(nullptr, "surface: " << parent_surface_ptr->get_handle() <<
", w: " << info.Width << ", h: " << info.Height <<
", p: " << data.Pitch);
switch(info.FourCC)
{
case MFX_FOURCC_I420:
throw std::runtime_error("MediaFrame doesn't support I420 type");
break;
case MFX_FOURCC_NV12:
frame_desc.fmt = MediaFormat::NV12;
break;
default:
throw std::runtime_error("MediaFrame unknown 'fmt' type: " + std::to_string(info.FourCC));
}
frame_desc.size = cv::Size{info.Width, info.Height};
LockAdapter* alloc_data = reinterpret_cast<LockAdapter*>(data.MemId);
alloc_data->set_adaptee(this);
parent_surface_ptr->obtain_lock();
}
VPLMediaFrameDX11Adapter::~VPLMediaFrameDX11Adapter() {
// Each VPLMediaFrameDX11Adapter releases mfx surface counter
// The last VPLMediaFrameDX11Adapter releases shared Surface pointer
// The last surface pointer releases workspace memory
Surface::data_t& data = parent_surface_ptr->get_data();
LockAdapter* alloc_data = reinterpret_cast<LockAdapter*>(data.MemId);
alloc_data->set_adaptee(nullptr);
parent_surface_ptr->release_lock();
}
cv::GFrameDesc VPLMediaFrameDX11Adapter::meta() const {
return frame_desc;
}
MediaFrame::View VPLMediaFrameDX11Adapter::access(MediaFrame::Access mode) {
Surface::data_t& data = parent_surface_ptr->get_data();
const Surface::info_t& info = parent_surface_ptr->get_info();
void* frame_id = reinterpret_cast<void*>(this);
GAPI_LOG_DEBUG(nullptr, "START lock frame in surface: " << parent_surface_ptr->get_handle() <<
", frame id: " << frame_id);
// lock MT
lock_mid(data.MemId, data, mode);
GAPI_LOG_DEBUG(nullptr, "FINISH lock frame in surface: " << parent_surface_ptr->get_handle() <<
", frame id: " << frame_id);
using stride_t = typename cv::MediaFrame::View::Strides::value_type;
stride_t pitch = static_cast<stride_t>(data.Pitch);
// NB: make copy for some copyable object, because access release may be happened
// after source/pool destruction, so we need a copy
auto parent_surface_ptr_copy = parent_surface_ptr;
switch(info.FourCC) {
case MFX_FOURCC_I420:
{
GAPI_Assert(data.Y && data.U && data.V && "MFX_FOURCC_I420 frame data is nullptr");
cv::MediaFrame::View::Ptrs pp = { data.Y, data.U, data.V, nullptr };
cv::MediaFrame::View::Strides ss = { pitch, pitch / 2, pitch / 2, 0u };
return cv::MediaFrame::View(std::move(pp), std::move(ss),
[parent_surface_ptr_copy,
frame_id, mode] () {
parent_surface_ptr_copy->obtain_lock();
auto& data = parent_surface_ptr_copy->get_data();
GAPI_LOG_DEBUG(nullptr, "START unlock frame in surface: " << parent_surface_ptr_copy->get_handle() <<
", frame id: " << frame_id);
unlock_mid(data.MemId, data, mode);
GAPI_LOG_DEBUG(nullptr, "FINISH unlock frame in surface: " << parent_surface_ptr_copy->get_handle() <<
", frame id: " << frame_id);
parent_surface_ptr_copy->release_lock();
});
}
case MFX_FOURCC_NV12:
{
if (!data.Y || !data.UV) {
GAPI_LOG_WARNING(nullptr, "Empty data detected!!! for surface: " << parent_surface_ptr->get_handle() <<
", frame id: " << frame_id);
}
GAPI_Assert(data.Y && data.UV && "MFX_FOURCC_NV12 frame data is nullptr");
cv::MediaFrame::View::Ptrs pp = { data.Y, data.UV, nullptr, nullptr };
cv::MediaFrame::View::Strides ss = { pitch, pitch, 0u, 0u };
return cv::MediaFrame::View(std::move(pp), std::move(ss),
[parent_surface_ptr_copy,
frame_id, mode] () {
parent_surface_ptr_copy->obtain_lock();
auto& data = parent_surface_ptr_copy->get_data();
GAPI_LOG_DEBUG(nullptr, "START unlock frame in surface: " << parent_surface_ptr_copy->get_handle() <<
", frame id: " << frame_id);
unlock_mid(data.MemId, data, mode);
GAPI_LOG_DEBUG(nullptr, "FINISH unlock frame in surface: " << parent_surface_ptr_copy->get_handle() <<
", frame id: " << frame_id);
parent_surface_ptr_copy->release_lock();
});
}
break;
default:
throw std::runtime_error("MediaFrame unknown 'fmt' type: " + std::to_string(info.FourCC));
}
}
cv::util::any VPLMediaFrameDX11Adapter::blobParams() const {
#ifdef HAVE_INF_ENGINE
GAPI_Assert(false && "VPLMediaFrameDX11Adapter::blobParams() is not fully operable "
"in G-API streaming. Please waiting for future PRs");
Surface::data_t& data = parent_surface_ptr->get_data();
NativeHandleAdapter* native_handle_getter = reinterpret_cast<NativeHandleAdapter*>(data.MemId);
mfxHDLPair handle{};
native_handle_getter->get_handle(data.MemId, reinterpret_cast<mfxHDL&>(handle));
InferenceEngine::ParamMap params{{"SHARED_MEM_TYPE", "VA_SURFACE"},
{"DEV_OBJECT_HANDLE", handle.first},
{"COLOR_FORMAT", InferenceEngine::ColorFormat::NV12},
{"VA_PLANE",
static_cast<DX11AllocationItem::subresource_id_t>(
reinterpret_cast<uint64_t>(
reinterpret_cast<DX11AllocationItem::subresource_id_t *>(
handle.second)))}};//,
const Surface::info_t& info = parent_surface_ptr->get_info();
InferenceEngine::TensorDesc tdesc({InferenceEngine::Precision::U8,
{1, 3, static_cast<size_t>(info.Height),
static_cast<size_t>(info.Width)},
InferenceEngine::Layout::NCHW});
return std::make_pair(tdesc, params);
#else
GAPI_Assert(false && "VPLMediaFrameDX11Adapter::blobParams() is not implemented");
#endif // HAVE_INF_ENGINE
}
void VPLMediaFrameDX11Adapter::serialize(cv::gapi::s11n::IOStream&) {
GAPI_Assert(false && "VPLMediaFrameDX11Adapter::serialize() is not implemented");
}
void VPLMediaFrameDX11Adapter::deserialize(cv::gapi::s11n::IIStream&) {
GAPI_Assert(false && "VPLMediaFrameDX11Adapter::deserialize() is not implemented");
}
DXGI_FORMAT VPLMediaFrameDX11Adapter::get_dx11_color_format(uint32_t mfx_fourcc) {
switch (mfx_fourcc) {
case MFX_FOURCC_NV12:
return DXGI_FORMAT_NV12;
case MFX_FOURCC_YUY2:
return DXGI_FORMAT_YUY2;
case MFX_FOURCC_RGB4:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case MFX_FOURCC_P8:
case MFX_FOURCC_P8_TEXTURE:
return DXGI_FORMAT_P8;
case MFX_FOURCC_ARGB16:
case MFX_FOURCC_ABGR16:
return DXGI_FORMAT_R16G16B16A16_UNORM;
case MFX_FOURCC_P010:
return DXGI_FORMAT_P010;
case MFX_FOURCC_A2RGB10:
return DXGI_FORMAT_R10G10B10A2_UNORM;
case DXGI_FORMAT_AYUV:
case MFX_FOURCC_AYUV:
return DXGI_FORMAT_AYUV;
default:
return DXGI_FORMAT_UNKNOWN;
}
}
} // namespace onevpl
} // namespace wip
} // namespace gapi
} // namespace cv
#endif // HAVE_ONEVPL
| 40.909871 | 119 | 0.612988 | nowireless |
04cf3a724b45ffe62e0feec5d62ea5f71ba6a7ac | 6,590 | cpp | C++ | cppcryptfs/ui/certutil.cpp | RiseT/cppcryptfs | ee7722ec2b6bd2b7550622b767ff4850981f9301 | [
"MIT"
] | 410 | 2016-06-13T16:49:12.000Z | 2022-03-31T21:55:39.000Z | cppcryptfs/ui/certutil.cpp | RiseT/cppcryptfs | ee7722ec2b6bd2b7550622b767ff4850981f9301 | [
"MIT"
] | 151 | 2016-06-17T18:18:53.000Z | 2022-03-22T00:03:53.000Z | cppcryptfs/ui/certutil.cpp | RiseT/cppcryptfs | ee7722ec2b6bd2b7550622b767ff4850981f9301 | [
"MIT"
] | 44 | 2016-07-02T19:12:58.000Z | 2022-03-09T01:35:04.000Z |
/*
cppcryptfs : user-mode cryptographic virtual overlay filesystem.
Copyright (C) 2016-2019 Bailey Brown (github.com/bailey27/cppcryptfs)
cppcryptfs is based on the design of gocryptfs (github.com/rfjakob/gocryptfs)
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "stdafx.h"
#include <Softpub.h>
#include <wincrypt.h>
#include <wintrust.h>
// Link with the Wintrust.lib file.
#pragma comment (lib, "wintrust")
bool VerifyEmbeddedSignature(LPCWSTR pwszSourceFile)
{
LONG lStatus;
// Initialize the WINTRUST_FILE_INFO structure.
WINTRUST_FILE_INFO FileData;
memset(&FileData, 0, sizeof(FileData));
FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
FileData.pcwszFilePath = pwszSourceFile;
FileData.hFile = NULL;
FileData.pgKnownSubject = NULL;
/*
WVTPolicyGUID specifies the policy to apply on the file
WINTRUST_ACTION_GENERIC_VERIFY_V2 policy checks:
1) The certificate used to sign the file chains up to a root
certificate located in the trusted root certificate store. This
implies that the identity of the publisher has been verified by
a certification authority.
2) In cases where user interface is displayed (which this example
does not do), WinVerifyTrust will check for whether the
end entity certificate is stored in the trusted publisher store,
implying that the user trusts content from this publisher.
3) The end entity certificate has sufficient permission to sign
code, as indicated by the presence of a code signing EKU or no
EKU.
*/
GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
WINTRUST_DATA WinTrustData;
// Initialize the WinVerifyTrust input data structure.
// Default all fields to 0.
memset(&WinTrustData, 0, sizeof(WinTrustData));
WinTrustData.cbStruct = sizeof(WinTrustData);
// Use default code signing EKU.
WinTrustData.pPolicyCallbackData = NULL;
// No data to pass to SIP.
WinTrustData.pSIPClientData = NULL;
// Disable WVT UI.
WinTrustData.dwUIChoice = WTD_UI_NONE;
// No revocation checking.
WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
// Verify an embedded signature on a file.
WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
// Verify action.
WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY;
// Verification sets this value.
WinTrustData.hWVTStateData = NULL;
// Not used.
WinTrustData.pwszURLReference = NULL;
// This is not applicable if there is no UI because it changes
// the UI to accommodate running applications instead of
// installing applications.
WinTrustData.dwUIContext = 0;
// Set pFile.
WinTrustData.pFile = &FileData;
// WinVerifyTrust verifies signatures as specified by the GUID
// and Wintrust_Data.
lStatus = WinVerifyTrust(
static_cast<HWND>(INVALID_HANDLE_VALUE),
&WVTPolicyGUID,
&WinTrustData);
bool bRet = lStatus == ERROR_SUCCESS;
#if 0 // this code is not needed, but left in for future reference
DWORD dwLastError;
switch (lStatus) {
case ERROR_SUCCESS:
/*
Signed file:
- Hash that represents the subject is trusted.
- Trusted publisher without any verification errors.
- UI was disabled in dwUIChoice. No publisher or
time stamp chain errors.
- UI was enabled in dwUIChoice and the user clicked
"Yes" when asked to install and run the signed
subject.
*/
wprintf_s(L"The file \"%s\" is signed and the signature "
L"was verified.\n",
pwszSourceFile);
break;
case TRUST_E_NOSIGNATURE:
// The file was not signed or had a signature
// that was not valid.
// Get the reason for no signature.
dwLastError = GetLastError();
if (TRUST_E_NOSIGNATURE == dwLastError ||
TRUST_E_SUBJECT_FORM_UNKNOWN == dwLastError ||
TRUST_E_PROVIDER_UNKNOWN == dwLastError) {
// The file was not signed.
wprintf_s(L"The file \"%s\" is not signed.\n",
pwszSourceFile);
} else {
// The signature was not valid or there was an error
// opening the file.
wprintf_s(L"An unknown error occurred trying to "
L"verify the signature of the \"%s\" file.\n",
pwszSourceFile);
}
break;
case TRUST_E_EXPLICIT_DISTRUST:
// The hash that represents the subject or the publisher
// is not allowed by the admin or user.
wprintf_s(L"The signature is present, but specifically "
L"disallowed.\n");
break;
case TRUST_E_SUBJECT_NOT_TRUSTED:
// The user clicked "No" when asked to install and run.
wprintf_s(L"The signature is present, but not "
L"trusted.\n");
break;
case CRYPT_E_SECURITY_SETTINGS:
/*
The hash that represents the subject or the publisher
was not explicitly trusted by the admin and the
admin policy has disabled user trust. No signature,
publisher or time stamp errors.
*/
wprintf_s(L"CRYPT_E_SECURITY_SETTINGS - The hash "
L"representing the subject or the publisher wasn't "
L"explicitly trusted by the admin and admin policy "
L"has disabled user trust. No signature, publisher "
L"or timestamp errors.\n");
break;
default:
// The UI was disabled in dwUIChoice or the admin policy
// has disabled user trust. lStatus contains the
// publisher or time stamp chain error.
wprintf_s(L"Error is: 0x%x.\n",
lStatus);
break;
}
#endif // #if 0
// Any hWVTStateData must be released by a call with close.
WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE;
lStatus = WinVerifyTrust(
NULL,
&WVTPolicyGUID,
&WinTrustData);
return bRet;
}
| 30.509259 | 78 | 0.726707 | RiseT |
04d19bf9db73b0092e647a6310b8fa8531f1bb61 | 1,943 | cpp | C++ | src/entities/Entity.cpp | MatthiasvZ/Gesneria | c60f041460a0c3f91a2d0cd34c7e2209fefdee9e | [
"Unlicense"
] | null | null | null | src/entities/Entity.cpp | MatthiasvZ/Gesneria | c60f041460a0c3f91a2d0cd34c7e2209fefdee9e | [
"Unlicense"
] | null | null | null | src/entities/Entity.cpp | MatthiasvZ/Gesneria | c60f041460a0c3f91a2d0cd34c7e2209fefdee9e | [
"Unlicense"
] | null | null | null | #include "Entity.h"
Entity::Entity(float x, float y, float hitboxSize)
: x(x), y(y), hitboxSize(hitboxSize), acceleration(0.0f), velocity(0.0f), angle(0.0f), speedCap(0.0f), frictionF(0.0f), active(true)
{
}
void Entity::moveTo(float x, float y)
{
this->x = x;
this->y = y;
updateVertices();
}
void Entity::moveRelative(float x, float y)
{
this->x += x;
this->y += y;
updateVertices();
}
void Entity::updateVertices()
{
vertices =
{
this->x - hitboxSize, this->y - hitboxSize, 0.0f, 0.0f,
this->x - hitboxSize, this->y + hitboxSize, 0.0f, 1.0f,
this->x + hitboxSize, this->y + hitboxSize, 1.0f, 1.0f,
this->x + hitboxSize, this->y - hitboxSize, 1.0f, 0.0f
};
}
#include <iostream>
void Entity::updatePosL(float deltaTime)
{
updatePosL(deltaTime, angle);
}
void Entity::updatePosL(float deltaTime, float newAngle)
{
angle = newAngle;
const float movementX = speedCap * deltaTime * cos(angle);
const float movementY = speedCap * deltaTime * sin(angle);
x += movementX;
y += movementY;
updateVertices();
}
void Entity::updatePosQ(float deltaTime)
{
updatePosQ(deltaTime, angle);
}
void Entity::updatePosQ(float deltaTime, float newAngle)
{
const float movementX = 0.5f * acceleration * deltaTime * deltaTime * cos(newAngle) + velocity * deltaTime * cos(angle);
const float movementY = 0.5f * acceleration * deltaTime * deltaTime * sin(newAngle) + velocity * deltaTime * sin(angle);
angle = atan2(movementY, movementX);
x += movementX;
y += movementY;
//std::cerr << "angle = " << angle << std::endl;
//std::cerr << "vel = " << velocity << ", std::abs(vel) = " << std::abs(velocity) << std::endl;
const float friction = ρAir * frictionF * velocity * std::abs(velocity);
velocity = std::max(std::min(velocity + acceleration * deltaTime - friction, speedCap), -speedCap);
updateVertices();
}
| 26.986111 | 136 | 0.633042 | MatthiasvZ |
04d1c85a059cc0a0a32789802d9a2314fd2503ca | 3,157 | cc | C++ | third_party/tflite_support/src/tensorflow_lite_support/custom_ops/kernel/sentencepiece/optimized_decoder_test.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/tflite_support/src/tensorflow_lite_support/custom_ops/kernel/sentencepiece/optimized_decoder_test.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | third_party/tflite_support/src/tensorflow_lite_support/custom_ops/kernel/sentencepiece/optimized_decoder_test.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/custom_ops/kernel/sentencepiece/optimized_decoder.h"
#include <fstream>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "src/sentencepiece.pb.h"
#include "src/sentencepiece_processor.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow_lite_support/custom_ops/kernel/sentencepiece/model_converter.h"
namespace tflite {
namespace ops {
namespace custom {
namespace sentencepiece {
namespace internal {
tensorflow::Status TFReadFileToString(const std::string& filepath,
std::string* data) {
return tensorflow::ReadFileToString(tensorflow::Env::Default(),
/*test_path*/ filepath, data);
}
absl::Status StdReadFileToString(const std::string& filepath,
std::string* data) {
std::ifstream infile(filepath);
if (!infile.is_open()) {
return absl::NotFoundError(
absl::StrFormat("Error when opening %s", filepath));
}
std::string contents((std::istreambuf_iterator<char>(infile)),
(std::istreambuf_iterator<char>()));
data->append(contents);
infile.close();
return absl::OkStatus();
}
} // namespace internal
namespace {
static char kConfigFilePath[] =
"tensorflow_lite_support/custom_ops/kernel/"
"sentencepiece/testdata/sentencepiece.model";
TEST(OptimizedEncoder, ConfigConverter) {
std::string config;
auto status = internal::StdReadFileToString(kConfigFilePath, &config);
ASSERT_TRUE(status.ok());
::sentencepiece::SentencePieceProcessor processor;
ASSERT_OK(processor.LoadFromSerializedProto(config));
const auto converted_model = ConvertSentencepieceModelForDecoder(config);
const std::string test_string("Hello world!\\xF0\\x9F\\x8D\\x95");
::sentencepiece::SentencePieceText reference_encoded;
CHECK_OK(processor.Encode(test_string, &reference_encoded));
std::vector<int> encoded_vector;
encoded_vector.reserve(reference_encoded.pieces_size());
for (const auto& piece : reference_encoded.pieces()) {
encoded_vector.push_back(piece.id());
}
std::string ref_decoded;
ASSERT_OK(processor.Decode(encoded_vector, &ref_decoded));
const auto decoded = DecodeString(encoded_vector, converted_model.data());
ASSERT_EQ(decoded.type, DecoderResultType::SUCCESS);
ASSERT_EQ(ref_decoded, decoded.decoded);
}
} // namespace
} // namespace sentencepiece
} // namespace custom
} // namespace ops
} // namespace tflite
| 34.692308 | 86 | 0.713969 | zealoussnow |
04d3892ce1f9010dd8d3b6675ad7d8e02b095211 | 652 | cpp | C++ | math/two_sat/gen/cycle_unsat.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 290 | 2019-06-06T22:20:36.000Z | 2022-03-27T12:45:04.000Z | math/two_sat/gen/cycle_unsat.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 536 | 2019-06-06T18:25:36.000Z | 2022-03-29T11:46:36.000Z | math/two_sat/gen/cycle_unsat.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 82 | 2019-06-06T18:17:55.000Z | 2022-03-21T07:40:31.000Z | #include "random.h"
#include <iostream>
using namespace std;
int main(int, char* argv[]) {
long long seed = atoll(argv[1]);
auto gen = Random(seed);
int n = 500'000 - 2;
int m = 500'000;
printf("p cnf %d %d\n", n, m);
// all same
for (int i = 1; i < n; i++) {
printf("%d %d 0\n", i, - (i + 1));
}
printf("%d -1 0\n", n);
// some pair, both true(= all true)
int a = gen.uniform(1, n);
int b = gen.uniform(1, n);
printf("%d %d 0\n", a, b);
// some pair, both false(= all false)
a = gen.uniform(-n, -1);
b = gen.uniform(-n, -1);
printf("%d %d 0\n", a, b);
return 0;
}
| 20.375 | 42 | 0.48773 | tko919 |
04d3b8565fc9d41b44169ea856f352d83d8d5623 | 2,482 | cpp | C++ | src/objects/boid/Bird.cpp | asilvaigor/opengl_winter | 0081c6ee39d493eb4f9e0ac92222937062866776 | [
"MIT"
] | 1 | 2020-04-24T22:55:51.000Z | 2020-04-24T22:55:51.000Z | src/objects/boid/Bird.cpp | asilvaigor/opengl_winter | 0081c6ee39d493eb4f9e0ac92222937062866776 | [
"MIT"
] | null | null | null | src/objects/boid/Bird.cpp | asilvaigor/opengl_winter | 0081c6ee39d493eb4f9e0ac92222937062866776 | [
"MIT"
] | null | null | null | //
// Created by Aloysio Galvão Lopes on 2020-05-30.
//
#include "utils/Texture.h"
#include "Bird.h"
std::vector<GLuint> Bird::textures;
Bird::Bird(Shaders &shaders, vcl::vec3 pos, float scale, vcl::vec3 speed, float turning) :
Object(true), dp(speed), turining(turning),
bird("../src/assets/models/bird.fbx", shaders["mesh"]) {
position = pos;
if (textures.empty()) {
Texture feathers("bird");
textures.push_back(feathers.getId());
}
bird.set_textures(textures);
bird.set_animation("bird|fly");
animationTime = 0;
}
void Bird::drawMesh(vcl::camera_scene &camera) {
bird.set_light(lights[0]);
// TODO add scaling to birds
// TODO Add bounding sphere
orientation = vcl::rotation_euler(dp, turining);
vcl::mat4 transform = {orientation, position};
// Bird draw
bird.transform(transform);
bird.draw(camera, animationTime);
}
void Bird::update(float time) {
vcl::vec3 projDpo = {odp.x, odp.y, 1};
vcl::vec3 projNdp = {ndp.x, ndp.y, 1};
float targetAngle = projDpo.angle(projNdp)*Constants::BIRD_MAX_TURN_FACTOR;
if (targetAngle > M_PI_2)
targetAngle = M_PI_2;
else if (targetAngle < -M_PI_2)
targetAngle = -M_PI_2;
turining += Constants::BIRD_TURN_FACTOR*(targetAngle-turining);
// Animation part
float animationNormalizedPosition = fmod(animationTime, Constants::BIRD_ANIMATION_MAX_TIME);
float animationTargetPosition = animationNormalizedPosition+Constants::BIRD_ANIMATION_SPEED;
float animationSpeedFactor = 1.0f;
float inclination = dp.angle({0,0,1});
if (inclination >= M_PI_2+M_PI_4){
animationTargetPosition = 0.6;
} else {
animationSpeedFactor = (M_PI_2+M_PI_4-inclination)/(M_PI_2+M_PI_4)*0.6+0.4;
animationSpeedFactor += (fabs(turining))/M_PI_2;
}
if (fabs(animationNormalizedPosition-animationTargetPosition) >= Constants::BIRD_ANIMATION_SPEED/2)
animationTime += Constants::BIRD_ANIMATION_SPEED*animationSpeedFactor;
}
vcl::vec3 Bird::getSpeed() {
return dp;
}
void Bird::setFutureSpeed(vcl::vec3 speed) {
ndp = speed;
}
void Bird::addFutureSpeed(vcl::vec3 speed) {
ndp += speed;
}
vcl::vec3 Bird::getFutureSpeed() {
return ndp;
}
void Bird::setPosition(vcl::vec3 pos) {
position = pos;
}
void Bird::stepSpeed() {
odp = dp;
dp = ndp;
}
void Bird::stepPosition() {
position += dp;
}
float Bird::getRotation() {
return turining;
}
| 25.587629 | 103 | 0.67083 | asilvaigor |
04d3d197efa085417590304d3cc73499fef2ac3c | 27,756 | cpp | C++ | Export/macos/obj/src/fracs/_Fraction/Fraction_Impl_.cpp | TrilateralX/TrilateralLimeTriangle | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | [
"MIT"
] | null | null | null | Export/macos/obj/src/fracs/_Fraction/Fraction_Impl_.cpp | TrilateralX/TrilateralLimeTriangle | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | [
"MIT"
] | null | null | null | Export/macos/obj/src/fracs/_Fraction/Fraction_Impl_.cpp | TrilateralX/TrilateralLimeTriangle | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.2.0-rc.1+cb30bd580
#include <hxcpp.h>
#ifndef INCLUDED_95f339a1d026d52c
#define INCLUDED_95f339a1d026d52c
#include "hxMath.h"
#endif
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_fracs_Fracs
#include <fracs/Fracs.h>
#endif
#ifndef INCLUDED_fracs__Fraction_Fraction_Impl_
#include <fracs/_Fraction/Fraction_Impl_.h>
#endif
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_32__new,"fracs._Fraction.Fraction_Impl_","_new",0x2a584cf7,"fracs._Fraction.Fraction_Impl_._new","fracs/Fraction.hx",32,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_46_optimize,"fracs._Fraction.Fraction_Impl_","optimize",0x00d44773,"fracs._Fraction.Fraction_Impl_.optimize","fracs/Fraction.hx",46,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_50_optimizeFraction,"fracs._Fraction.Fraction_Impl_","optimizeFraction",0xea05c495,"fracs._Fraction.Fraction_Impl_.optimizeFraction","fracs/Fraction.hx",50,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_55_toFloat,"fracs._Fraction.Fraction_Impl_","toFloat",0xab643c4b,"fracs._Fraction.Fraction_Impl_.toFloat","fracs/Fraction.hx",55,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_63_float,"fracs._Fraction.Fraction_Impl_","float",0xe96e3146,"fracs._Fraction.Fraction_Impl_.float","fracs/Fraction.hx",63,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_67_verbose,"fracs._Fraction.Fraction_Impl_","verbose",0x4e0301ac,"fracs._Fraction.Fraction_Impl_.verbose","fracs/Fraction.hx",67,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_71_fromString,"fracs._Fraction.Fraction_Impl_","fromString",0x6a8439f1,"fracs._Fraction.Fraction_Impl_.fromString","fracs/Fraction.hx",71,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_82_toString,"fracs._Fraction.Fraction_Impl_","toString",0x1c2a8b42,"fracs._Fraction.Fraction_Impl_.toString","fracs/Fraction.hx",82,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_98_fromFloat,"fracs._Fraction.Fraction_Impl_","fromFloat",0x17a7387c,"fracs._Fraction.Fraction_Impl_.fromFloat","fracs/Fraction.hx",98,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_119_firstFloat,"fracs._Fraction.Fraction_Impl_","firstFloat",0x56851b62,"fracs._Fraction.Fraction_Impl_.firstFloat","fracs/Fraction.hx",119,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_126_byDenominator,"fracs._Fraction.Fraction_Impl_","byDenominator",0xa7ebbeb9,"fracs._Fraction.Fraction_Impl_.byDenominator","fracs/Fraction.hx",126,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_138_all,"fracs._Fraction.Fraction_Impl_","all",0x2614464b,"fracs._Fraction.Fraction_Impl_.all","fracs/Fraction.hx",138,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_141_similarToFraction,"fracs._Fraction.Fraction_Impl_","similarToFraction",0x69a71b52,"fracs._Fraction.Fraction_Impl_.similarToFraction","fracs/Fraction.hx",141,0xf40fb512)
HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_147_similarToValue,"fracs._Fraction.Fraction_Impl_","similarToValue",0x124a8821,"fracs._Fraction.Fraction_Impl_.similarToValue","fracs/Fraction.hx",147,0xf40fb512)
namespace fracs{
namespace _Fraction{
void Fraction_Impl__obj::__construct() { }
Dynamic Fraction_Impl__obj::__CreateEmpty() { return new Fraction_Impl__obj; }
void *Fraction_Impl__obj::_hx_vtable = 0;
Dynamic Fraction_Impl__obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< Fraction_Impl__obj > _hx_result = new Fraction_Impl__obj();
_hx_result->__construct();
return _hx_result;
}
bool Fraction_Impl__obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x1a57794a;
}
::Dynamic Fraction_Impl__obj::_new(int numerator,int denominator, ::Dynamic __o_positive, ::Dynamic value){
::Dynamic positive = __o_positive;
if (::hx::IsNull(__o_positive)) positive = true;
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_32__new)
HXLINE( 34) bool numNeg = (numerator < 0);
HXLINE( 35) bool denoNeg = (denominator < 0);
HXLINE( 36) if (::hx::IsNull( value )) {
HXLINE( 36) if (( (bool)(positive) )) {
HXLINE( 36) value = (( (Float)(numerator) ) / ( (Float)(denominator) ));
}
else {
HXLINE( 36) value = (( (Float)(-(numerator)) ) / ( (Float)(denominator) ));
}
}
HXLINE( 37) bool _hx_tmp;
HXDLIN( 37) if (!(numNeg)) {
HXLINE( 37) _hx_tmp = denoNeg;
}
else {
HXLINE( 37) _hx_tmp = true;
}
HXDLIN( 37) if (_hx_tmp) {
HXLINE( 38) bool _hx_tmp;
HXDLIN( 38) if (numNeg) {
HXLINE( 38) _hx_tmp = denoNeg;
}
else {
HXLINE( 38) _hx_tmp = false;
}
HXDLIN( 38) if (!(_hx_tmp)) {
HXLINE( 38) positive = !(( (bool)(positive) ));
}
HXLINE( 39) if (numNeg) {
HXLINE( 39) numerator = -(numerator);
}
HXLINE( 40) if (denoNeg) {
HXLINE( 40) denominator = -(denominator);
}
}
HXLINE( 32) ::Dynamic this1 = ::Dynamic(::hx::Anon_obj::Create(4)
->setFixed(0,HX_("numerator",89,82,9c,c2),numerator)
->setFixed(1,HX_("positive",b9,a6,fa,ca),positive)
->setFixed(2,HX_("denominator",a6,25,84,eb),denominator)
->setFixed(3,HX_("value",71,7f,b8,31),value));
HXDLIN( 32) return this1;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(Fraction_Impl__obj,_new,return )
::Dynamic Fraction_Impl__obj::optimize( ::Dynamic this1){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_46_optimize)
HXDLIN( 46) Float f = ( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) );
HXDLIN( 46) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f);
HXDLIN( 46) Float dist = ::Math_obj::POSITIVE_INFINITY;
HXDLIN( 46) Float dif;
HXDLIN( 46) int l = arr->length;
HXDLIN( 46) Float fracFloat;
HXDLIN( 46) ::Dynamic frac;
HXDLIN( 46) ::Dynamic fracStore = arr->__get(0);
HXDLIN( 46) {
HXDLIN( 46) int _g = 0;
HXDLIN( 46) int _g1 = l;
HXDLIN( 46) while((_g < _g1)){
HXDLIN( 46) _g = (_g + 1);
HXDLIN( 46) int i = (_g - 1);
HXDLIN( 46) ::Dynamic frac = arr->__get(i);
HXDLIN( 46) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXDLIN( 46) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
else {
HXDLIN( 46) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
HXDLIN( 46) dif = ::Math_obj::abs((fracFloat - f));
HXDLIN( 46) if ((dif < dist)) {
HXDLIN( 46) dist = dif;
HXDLIN( 46) fracStore = frac;
}
}
}
HXDLIN( 46) return fracStore;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,optimize,return )
::Dynamic Fraction_Impl__obj::optimizeFraction( ::Dynamic this1){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_50_optimizeFraction)
HXDLIN( 50) Float f;
HXDLIN( 50) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXDLIN( 50) f = (( (Float)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
else {
HXDLIN( 50) f = (( (Float)(-(( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
HXDLIN( 50) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f);
HXDLIN( 50) Float dist = ::Math_obj::POSITIVE_INFINITY;
HXDLIN( 50) Float dif;
HXDLIN( 50) int l = arr->length;
HXDLIN( 50) Float fracFloat;
HXDLIN( 50) ::Dynamic frac;
HXDLIN( 50) ::Dynamic fracStore = arr->__get(0);
HXDLIN( 50) {
HXDLIN( 50) int _g = 0;
HXDLIN( 50) int _g1 = l;
HXDLIN( 50) while((_g < _g1)){
HXDLIN( 50) _g = (_g + 1);
HXDLIN( 50) int i = (_g - 1);
HXDLIN( 50) ::Dynamic frac = arr->__get(i);
HXDLIN( 50) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXDLIN( 50) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
else {
HXDLIN( 50) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
HXDLIN( 50) dif = ::Math_obj::abs((fracFloat - f));
HXDLIN( 50) if ((dif < dist)) {
HXDLIN( 50) dist = dif;
HXDLIN( 50) fracStore = frac;
}
}
}
HXDLIN( 50) return fracStore;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,optimizeFraction,return )
Float Fraction_Impl__obj::toFloat( ::Dynamic this1){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_55_toFloat)
HXDLIN( 55) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 56) return (( (Float)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
else {
HXLINE( 58) return (( (Float)(-(( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
HXLINE( 55) return ((Float)0.);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,toFloat,return )
Float Fraction_Impl__obj::_hx_float( ::Dynamic this1){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_63_float)
HXDLIN( 63) return ( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) );
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,_hx_float,return )
::String Fraction_Impl__obj::verbose( ::Dynamic this1){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_67_verbose)
HXDLIN( 67) ::String _hx_tmp = ( (::String)(((((HX_("{ numerator:",16,c9,1c,39) + this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) + HX_(", denominator: ",d8,6e,ff,e1)) + this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) + HX_(", positive: ",13,f9,b0,e4))) );
HXDLIN( 67) ::String _hx_tmp1 = ((_hx_tmp + ::Std_obj::string( ::Dynamic(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)))) + HX_(", value: ",63,80,38,d8));
HXDLIN( 67) return ( (::String)(((_hx_tmp1 + this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) + HX_(" }",5d,1c,00,00))) );
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,verbose,return )
::Dynamic Fraction_Impl__obj::fromString(::String val){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_71_fromString)
HXLINE( 72) int i = val.indexOf(HX_("/",2f,00,00,00),null());
HXLINE( 73) ::Dynamic frac;
HXDLIN( 73) if ((i != -1)) {
HXLINE( 74) int numerator = ( (int)(::Std_obj::parseInt(val.substr(0,i))) );
HXDLIN( 74) int denominator = ( (int)(::Std_obj::parseInt(val.substr((i + 1),val.length))) );
HXDLIN( 74) ::Dynamic positive = true;
HXDLIN( 74) ::Dynamic value = null();
HXDLIN( 74) bool numNeg = (numerator < 0);
HXDLIN( 74) bool denoNeg = (denominator < 0);
HXDLIN( 74) if (::hx::IsNull( value )) {
HXLINE( 74) if (( (bool)(positive) )) {
HXLINE( 74) value = (( (Float)(numerator) ) / ( (Float)(denominator) ));
}
else {
HXLINE( 74) value = (( (Float)(-(numerator)) ) / ( (Float)(denominator) ));
}
}
HXDLIN( 74) bool frac1;
HXDLIN( 74) if (!(numNeg)) {
HXLINE( 74) frac1 = denoNeg;
}
else {
HXLINE( 74) frac1 = true;
}
HXDLIN( 74) if (frac1) {
HXLINE( 74) bool frac;
HXDLIN( 74) if (numNeg) {
HXLINE( 74) frac = denoNeg;
}
else {
HXLINE( 74) frac = false;
}
HXDLIN( 74) if (!(frac)) {
HXLINE( 74) positive = !(( (bool)(positive) ));
}
HXDLIN( 74) if (numNeg) {
HXLINE( 74) numerator = -(numerator);
}
HXDLIN( 74) if (denoNeg) {
HXLINE( 74) denominator = -(denominator);
}
}
HXDLIN( 74) ::Dynamic this1 = ::Dynamic(::hx::Anon_obj::Create(4)
->setFixed(0,HX_("numerator",89,82,9c,c2),numerator)
->setFixed(1,HX_("positive",b9,a6,fa,ca),positive)
->setFixed(2,HX_("denominator",a6,25,84,eb),denominator)
->setFixed(3,HX_("value",71,7f,b8,31),value));
HXLINE( 73) frac = this1;
}
else {
HXLINE( 75) Float f = ::Std_obj::parseFloat(val);
HXDLIN( 75) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f);
HXDLIN( 75) Float dist = ::Math_obj::POSITIVE_INFINITY;
HXDLIN( 75) Float dif;
HXDLIN( 75) int l = arr->length;
HXDLIN( 75) Float fracFloat;
HXDLIN( 75) ::Dynamic frac1;
HXDLIN( 75) ::Dynamic fracStore = arr->__get(0);
HXDLIN( 75) {
HXLINE( 75) int _g = 0;
HXDLIN( 75) int _g1 = l;
HXDLIN( 75) while((_g < _g1)){
HXLINE( 75) _g = (_g + 1);
HXDLIN( 75) int i = (_g - 1);
HXDLIN( 75) ::Dynamic frac = arr->__get(i);
HXDLIN( 75) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 75) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
else {
HXLINE( 75) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
HXDLIN( 75) dif = ::Math_obj::abs((fracFloat - f));
HXDLIN( 75) if ((dif < dist)) {
HXLINE( 75) dist = dif;
HXDLIN( 75) fracStore = frac;
}
}
}
HXLINE( 73) frac = fracStore;
}
HXLINE( 78) return frac;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,fromString,return )
::String Fraction_Impl__obj::toString( ::Dynamic this1){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_82_toString)
HXLINE( 83) int n = ( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) );
HXLINE( 84) int d = ( (int)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) );
HXLINE( 85) ::String out;
HXDLIN( 85) if ((n == 0)) {
HXLINE( 85) out = HX_("0",30,00,00,00);
}
else {
HXLINE( 87) if ((n == d)) {
HXLINE( 85) out = HX_("1",31,00,00,00);
}
else {
HXLINE( 89) if ((d == 1)) {
HXLINE( 90) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 85) out = (HX_("",00,00,00,00) + n);
}
else {
HXLINE( 85) out = (HX_("-",2d,00,00,00) + n);
}
}
else {
HXLINE( 92) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 85) out = (((HX_("",00,00,00,00) + n) + HX_("/",2f,00,00,00)) + d);
}
else {
HXLINE( 85) out = (((HX_("-",2d,00,00,00) + n) + HX_("/",2f,00,00,00)) + d);
}
}
}
}
HXLINE( 94) return out;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,toString,return )
::Dynamic Fraction_Impl__obj::fromFloat(Float f){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_98_fromFloat)
HXLINE( 99) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f);
HXLINE( 100) Float dist = ::Math_obj::POSITIVE_INFINITY;
HXLINE( 101) Float dif;
HXLINE( 102) int l = arr->length;
HXLINE( 103) Float fracFloat;
HXLINE( 104) ::Dynamic frac;
HXLINE( 105) ::Dynamic fracStore = arr->__get(0);
HXLINE( 107) {
HXLINE( 107) int _g = 0;
HXDLIN( 107) int _g1 = l;
HXDLIN( 107) while((_g < _g1)){
HXLINE( 107) _g = (_g + 1);
HXDLIN( 107) int i = (_g - 1);
HXLINE( 108) ::Dynamic frac = arr->__get(i);
HXLINE( 109) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 109) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
else {
HXLINE( 109) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
HXLINE( 110) dif = ::Math_obj::abs((fracFloat - f));
HXLINE( 111) if ((dif < dist)) {
HXLINE( 112) dist = dif;
HXLINE( 113) fracStore = frac;
}
}
}
HXLINE( 116) return fracStore;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,fromFloat,return )
::Dynamic Fraction_Impl__obj::firstFloat(Float f){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_119_firstFloat)
HXLINE( 120) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f);
HXLINE( 121) ::Dynamic fracStore = arr->__get(0);
HXLINE( 122) return fracStore;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,firstFloat,return )
::String Fraction_Impl__obj::byDenominator( ::Dynamic this1,int val){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_126_byDenominator)
HXLINE( 127) int n = ( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) );
HXDLIN( 127) int d = ( (int)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) );
HXDLIN( 127) ::String out;
HXDLIN( 127) if ((n == 0)) {
HXLINE( 127) out = HX_("0",30,00,00,00);
}
else {
HXLINE( 127) if ((n == d)) {
HXLINE( 127) out = HX_("1",31,00,00,00);
}
else {
HXLINE( 127) if ((d == 1)) {
HXLINE( 127) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 127) out = (HX_("",00,00,00,00) + n);
}
else {
HXLINE( 127) out = (HX_("-",2d,00,00,00) + n);
}
}
else {
HXLINE( 127) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 127) out = (((HX_("",00,00,00,00) + n) + HX_("/",2f,00,00,00)) + d);
}
else {
HXLINE( 127) out = (((HX_("-",2d,00,00,00) + n) + HX_("/",2f,00,00,00)) + d);
}
}
}
}
HXDLIN( 127) ::String out1 = out;
HXLINE( 128) bool _hx_tmp;
HXDLIN( 128) bool _hx_tmp1;
HXDLIN( 128) if (::hx::IsNotEq( this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic),val )) {
HXLINE( 128) _hx_tmp1 = (out1 == HX_("0",30,00,00,00));
}
else {
HXLINE( 128) _hx_tmp1 = true;
}
HXDLIN( 128) if (!(_hx_tmp1)) {
HXLINE( 128) _hx_tmp = (out1 == HX_("1",31,00,00,00));
}
else {
HXLINE( 128) _hx_tmp = true;
}
HXDLIN( 128) if (!(_hx_tmp)) {
HXLINE( 130) int dom = ::Math_obj::round((( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) ) * ( (Float)(val) )));
HXLINE( 131) int numerator = dom;
HXDLIN( 131) int denominator = val;
HXDLIN( 131) ::Dynamic positive = true;
HXDLIN( 131) ::Dynamic value = null();
HXDLIN( 131) bool numNeg = (numerator < 0);
HXDLIN( 131) bool denoNeg = (denominator < 0);
HXDLIN( 131) if (::hx::IsNull( value )) {
HXLINE( 131) if (( (bool)(positive) )) {
HXLINE( 131) value = (( (Float)(numerator) ) / ( (Float)(denominator) ));
}
else {
HXLINE( 131) value = (( (Float)(-(numerator)) ) / ( (Float)(denominator) ));
}
}
HXDLIN( 131) bool _hx_tmp;
HXDLIN( 131) if (!(numNeg)) {
HXLINE( 131) _hx_tmp = denoNeg;
}
else {
HXLINE( 131) _hx_tmp = true;
}
HXDLIN( 131) if (_hx_tmp) {
HXLINE( 131) bool _hx_tmp;
HXDLIN( 131) if (numNeg) {
HXLINE( 131) _hx_tmp = denoNeg;
}
else {
HXLINE( 131) _hx_tmp = false;
}
HXDLIN( 131) if (!(_hx_tmp)) {
HXLINE( 131) positive = !(( (bool)(positive) ));
}
HXDLIN( 131) if (numNeg) {
HXLINE( 131) numerator = -(numerator);
}
HXDLIN( 131) if (denoNeg) {
HXLINE( 131) denominator = -(denominator);
}
}
HXDLIN( 131) ::Dynamic this2 = ::Dynamic(::hx::Anon_obj::Create(4)
->setFixed(0,HX_("numerator",89,82,9c,c2),numerator)
->setFixed(1,HX_("positive",b9,a6,fa,ca),positive)
->setFixed(2,HX_("denominator",a6,25,84,eb),denominator)
->setFixed(3,HX_("value",71,7f,b8,31),value));
HXDLIN( 131) ::Dynamic frac = this2;
HXLINE( 132) int n = ( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) );
HXDLIN( 132) int d = ( (int)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) );
HXDLIN( 132) ::String out;
HXDLIN( 132) if ((n == 0)) {
HXLINE( 132) out = HX_("0",30,00,00,00);
}
else {
HXLINE( 132) if ((n == d)) {
HXLINE( 132) out = HX_("1",31,00,00,00);
}
else {
HXLINE( 132) if ((d == 1)) {
HXLINE( 132) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 132) out = (HX_("",00,00,00,00) + n);
}
else {
HXLINE( 132) out = (HX_("-",2d,00,00,00) + n);
}
}
else {
HXLINE( 132) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 132) out = (((HX_("",00,00,00,00) + n) + HX_("/",2f,00,00,00)) + d);
}
else {
HXLINE( 132) out = (((HX_("-",2d,00,00,00) + n) + HX_("/",2f,00,00,00)) + d);
}
}
}
}
HXDLIN( 132) out1 = out;
}
HXLINE( 134) return out1;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Fraction_Impl__obj,byDenominator,return )
::Array< ::Dynamic> Fraction_Impl__obj::all(Float f){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_138_all)
HXDLIN( 138) return ::fracs::Fracs_obj::approximateFractions(f);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,all,return )
::Array< ::Dynamic> Fraction_Impl__obj::similarToFraction( ::Dynamic this1){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_141_similarToFraction)
HXLINE( 142) Float f;
HXDLIN( 142) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) {
HXLINE( 142) f = (( (Float)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
else {
HXLINE( 142) f = (( (Float)(-(( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ));
}
HXLINE( 143) return ::fracs::Fracs_obj::approximateFractions(f);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,similarToFraction,return )
::Array< ::Dynamic> Fraction_Impl__obj::similarToValue( ::Dynamic this1){
HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_147_similarToValue)
HXDLIN( 147) return ::fracs::Fracs_obj::approximateFractions(( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) ));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,similarToValue,return )
Fraction_Impl__obj::Fraction_Impl__obj()
{
}
bool Fraction_Impl__obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"all") ) { outValue = all_dyn(); return true; }
break;
case 4:
if (HX_FIELD_EQ(inName,"_new") ) { outValue = _new_dyn(); return true; }
break;
case 5:
if (HX_FIELD_EQ(inName,"float") ) { outValue = _hx_float_dyn(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"toFloat") ) { outValue = toFloat_dyn(); return true; }
if (HX_FIELD_EQ(inName,"verbose") ) { outValue = verbose_dyn(); return true; }
break;
case 8:
if (HX_FIELD_EQ(inName,"optimize") ) { outValue = optimize_dyn(); return true; }
if (HX_FIELD_EQ(inName,"toString") ) { outValue = toString_dyn(); return true; }
break;
case 9:
if (HX_FIELD_EQ(inName,"fromFloat") ) { outValue = fromFloat_dyn(); return true; }
break;
case 10:
if (HX_FIELD_EQ(inName,"fromString") ) { outValue = fromString_dyn(); return true; }
if (HX_FIELD_EQ(inName,"firstFloat") ) { outValue = firstFloat_dyn(); return true; }
break;
case 13:
if (HX_FIELD_EQ(inName,"byDenominator") ) { outValue = byDenominator_dyn(); return true; }
break;
case 14:
if (HX_FIELD_EQ(inName,"similarToValue") ) { outValue = similarToValue_dyn(); return true; }
break;
case 16:
if (HX_FIELD_EQ(inName,"optimizeFraction") ) { outValue = optimizeFraction_dyn(); return true; }
break;
case 17:
if (HX_FIELD_EQ(inName,"similarToFraction") ) { outValue = similarToFraction_dyn(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *Fraction_Impl__obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *Fraction_Impl__obj_sStaticStorageInfo = 0;
#endif
::hx::Class Fraction_Impl__obj::__mClass;
static ::String Fraction_Impl__obj_sStaticFields[] = {
HX_("_new",61,15,1f,3f),
HX_("optimize",dd,8c,18,1d),
HX_("optimizeFraction",ff,83,8c,53),
HX_("toFloat",21,12,1b,cf),
HX_("float",9c,c5,96,02),
HX_("verbose",82,d7,b9,71),
HX_("fromString",db,2d,74,54),
HX_("toString",ac,d0,6e,38),
HX_("fromFloat",d2,af,1f,b7),
HX_("firstFloat",4c,0f,75,40),
HX_("byDenominator",0f,99,e1,96),
HX_("all",21,f9,49,00),
HX_("similarToFraction",a8,d8,07,56),
HX_("similarToValue",0b,b9,73,3a),
::String(null())
};
void Fraction_Impl__obj::__register()
{
Fraction_Impl__obj _hx_dummy;
Fraction_Impl__obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("fracs._Fraction.Fraction_Impl_",98,50,12,83);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &Fraction_Impl__obj::__GetStatic;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(Fraction_Impl__obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< Fraction_Impl__obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = Fraction_Impl__obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = Fraction_Impl__obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace fracs
} // end namespace _Fraction
| 43.36875 | 292 | 0.60931 | TrilateralX |
04d5de7bf0de3f81eb9a1ed908f07980b15a5999 | 832 | hpp | C++ | SDEngine/include/Utility/Timing.hpp | xubury/SDEngine | 31e44fc5c78ce6b8f0c3b128fd5e0158150590e8 | [
"BSD-3-Clause"
] | null | null | null | SDEngine/include/Utility/Timing.hpp | xubury/SDEngine | 31e44fc5c78ce6b8f0c3b128fd5e0158150590e8 | [
"BSD-3-Clause"
] | 4 | 2021-12-10T05:01:49.000Z | 2022-03-19T10:16:14.000Z | SDEngine/include/Utility/Timing.hpp | xubury/SDEngine | 31e44fc5c78ce6b8f0c3b128fd5e0158150590e8 | [
"BSD-3-Clause"
] | null | null | null | #ifndef SD_TIMING_HPP
#define SD_TIMING_HPP
#include "Utility/Base.hpp"
#include <cstdint>
#include <queue>
#include <chrono>
namespace SD {
using ClockType = std::chrono::high_resolution_clock;
class SD_UTILITY_API Clock {
public:
Clock();
float GetElapsedMS() const;
// Restart the clock, and return elapsed millisecond.
float Restart();
private:
std::chrono::time_point<ClockType> m_lastTicks;
};
class SD_UTILITY_API FPSCounter {
public:
FPSCounter(uint8_t capacity);
FPSCounter(const FPSCounter &) = delete;
FPSCounter &operator=(const FPSCounter &) = delete;
float GetFPS() const;
float GetFrameTime() const;
void Probe();
private:
Clock m_clock;
std::deque<float> m_queue;
uint8_t m_capacity;
};
} // namespace SD
#endif /* SD_TIMING_HPP */
| 17.333333 | 57 | 0.6875 | xubury |
04d8921962bfed4a4e66aa1b8f2dc444f4b2c589 | 4,743 | cpp | C++ | basic-cpp/Stacks&Queues/BucketMeasures/src/main.cpp | gramai/school-related | 152d67b4e475c3ba7c9370d6de39b38fc453392d | [
"MIT"
] | null | null | null | basic-cpp/Stacks&Queues/BucketMeasures/src/main.cpp | gramai/school-related | 152d67b4e475c3ba7c9370d6de39b38fc453392d | [
"MIT"
] | null | null | null | basic-cpp/Stacks&Queues/BucketMeasures/src/main.cpp | gramai/school-related | 152d67b4e475c3ba7c9370d6de39b38fc453392d | [
"MIT"
] | null | null | null | #include <iostream>
#include <stack>
#define NMAX=10
using namespace std;
// A class is created to better implement the problem
class Bucket{
private:
stack <int> liter_list; // Is a stack where each element can be int(1)
int bucket_size;// Max size of bucket
public:
Bucket(int bucket_size){
this->bucket_size=bucket_size;
}
int getLiters(){
return liter_list.size();
}
void emptyBucket(){
liter_list.pop();
}
// Transfers from another bucket until target_bucket is full or donor_bucket is empty
void fillBucket(Bucket &donor_bucket){
while(liter_list.size()<bucket_size && !donor_bucket.isEmpty())
{donor_bucket.emptyBucket();
liter_list.push(1);
}
}
// Method only used for filling the 20 liters bucket
void fillBucket(){
while(liter_list.size()<bucket_size)
liter_list.push(1);
}
int getSize(){
return bucket_size;
}
bool isEmpty(){
return (liter_list.size()==0);
}
bool isFull(){
return (liter_list.size()==bucket_size);
}
};
// Returns state for all 3 buckets (L1, L2, L3)
void return_state(Bucket b1, Bucket b2, Bucket b3, int &state){
cout<<"State "<<state<<endl;
cout<<"Bucket with max capacity "<<b1.getSize()<<" l holds "<<b1.getLiters()<<" l of wine "<<endl;
cout<<"Bucket with max capacity "<<b2.getSize()<<" l holds "<<b2.getLiters()<<" l of wine "<<endl;
cout<<"Bucket with max capacity "<<b3.getSize()<<" l holds "<<b3.getLiters()<<" l of wine "<<endl;
cout<<endl;
state++;
}
// int no_of_liters is the number of the desired liters to measure
void measure_liters(int no_of_liters,Bucket &b8, Bucket &b5,Bucket &b20){
// Checks if any bucket contains the desired no_of_liters
int state=1;
while (b8.getLiters()!=no_of_liters && b5.getLiters()!=no_of_liters && b20.getLiters()!=no_of_liters ){
/*
The algorithm is a circular one and goes like this:
b20->b8->b5
Meaning that:
-1)b8 is filled from b20 only when b8 is empty
-2)b5 is filled from b8 every time b5 contains <5l of wine
-is the main element because the quantity will vary between b8 and b5
-3)b5 is emptied in b20 when b5 is full
-e.g. :b20=20, b8=0, b5=0; -> b20=12, b8=8, b5=0; ->b20=12, b8=3, b5=5;
->b20=17, b8=3, b5=0; ->b20=17, b8=0, b5=3; ... etc
*/
if(b8.isEmpty()){
b8.fillBucket(b20);
return_state(b8,b5,b20,state);
}
else if(b5.isEmpty()){
b5.fillBucket(b8);
return_state(b8,b5,b20,state);
}
else if(b5.isFull()){
b20.fillBucket(b5);
return_state(b8,b5,b20,state);
}
else if (!b5.isFull())
{b5.fillBucket(b8);
return_state(b8,b5,b20,state);
}
else{
cout<<"Other state, quitting"<<endl<<endl;
return;
}
}
if(b8.getLiters()==no_of_liters)
cout<<"Success! Measured "<<no_of_liters<<" l in Bucket with 8l max capacity "<<endl<<endl;
else if(b5.getLiters()==no_of_liters)
cout<<"Success! Measured "<<no_of_liters<<" l in Bucket with 5l max capacity "<<endl<<endl;
else{
cout<<"Success! Measured "<<no_of_liters<<" l in Bucket with 20l max capacity "<<endl<<endl;
}
}
void reset_state(Bucket &b1,Bucket &b2,Bucket &b3){
while(!b1.isEmpty() || !b2.isEmpty() || !b3.isEmpty()){
if(!b1.isEmpty())
b1.emptyBucket();
if(!b2.isEmpty())
b2.emptyBucket();
if(!b3.isEmpty())
b3.emptyBucket();
}
b3.fillBucket();
}
int main()
{
// I thought that it would be more interesting to be able to measure any quantity of liters
int no_of_liters=0; // inputs desired no. of liters to measure
bool entered=0; // checks if there existed a first attempt to insert no_of_lites
while(no_of_liters<1 || no_of_liters>20) //asks user to input a correct value of no_of_liters
{ if(entered==0){
cout<< "Insert number of desired liters to measure (1-20)"<<endl;
cin>>no_of_liters;
entered=1;
}
else{
cout<<"Please insert a number between 1 and 20 "<<endl;
cin>>no_of_liters;
}
}
// Create 3 buckets with max capacities of 8,5 and 20 liters
Bucket b8 = Bucket(8);
Bucket b5 = Bucket(5);
Bucket b20 = Bucket(20);
b20.fillBucket(); // fills the bucket with 20l max capacity
measure_liters(no_of_liters,b8,b5,b20);
}
| 32.710345 | 109 | 0.580223 | gramai |
3e20b87d157a78176c84ed496f2c412af7f8767c | 258 | cpp | C++ | LeetCode/100/26.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/100/26.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/100/26.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int left = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
if (!i or nums[i] != nums[i - 1]) {
nums[left++] = nums[i];
}
}
return left;
}
}; | 19.846154 | 43 | 0.468992 | K-ona |
3e239c5a87cad0a75b19d965eca5626f7b798aa3 | 1,385 | cpp | C++ | benchmarks/periodic_calls.cpp | serpent7776/reckless | 5ac98bd799a44aef9b89fbfae509b044a4d1032b | [
"MIT"
] | 450 | 2015-05-14T12:29:50.000Z | 2022-03-31T06:20:14.000Z | benchmarks/periodic_calls.cpp | sthagen/reckless | 0d013b66eaf4f8105dc107df70db0696c6464598 | [
"MIT"
] | 42 | 2015-05-14T16:57:50.000Z | 2021-11-01T08:41:18.000Z | benchmarks/periodic_calls.cpp | sthagen/reckless | 0d013b66eaf4f8105dc107df70db0696c6464598 | [
"MIT"
] | 63 | 2015-05-15T01:09:44.000Z | 2022-01-25T15:57:42.000Z | #ifdef RECKLESS_ENABLE_TRACE_LOG
#include <performance_log/trace_log.hpp>
#include <fstream>
#endif
#include <performance_log/performance_log.hpp>
#include <iostream>
#include <unistd.h>
#include LOG_INCLUDE
char c = 'A';
float pi = 3.1415;
int main()
{
unlink("log.txt");
performance_log::logger<4096, performance_log::rdtscp_cpuid_clock> performance_log;
{
LOG_INIT(6000);
performance_log::rdtscp_cpuid_clock::bind_cpu(0);
for(int i=0; i!=2500; ++i) {
usleep(1000);
struct timespec busywait_start;
clock_gettime(CLOCK_REALTIME, &busywait_start);
struct timespec busywait_end = busywait_start;
while( (busywait_end.tv_sec - busywait_start.tv_sec)*1000000 + busywait_end.tv_nsec - busywait_start.tv_nsec < 1000 )
clock_gettime(CLOCK_REALTIME, &busywait_end);
auto start = performance_log.start();
LOG(c, i, pi);
performance_log.stop(start);
}
performance_log::rdtscp_cpuid_clock::unbind_cpu();
LOG_CLEANUP();
}
for(auto sample : performance_log) {
std::cout << sample.start << ' ' << sample.stop << std::endl;
}
#ifdef RECKLESS_ENABLE_TRACE_LOG
std::ofstream trace_log("trace_log.txt", std::ios::trunc);
reckless::detail::g_trace_log.save(trace_log);
#endif
return 0;
}
| 26.634615 | 129 | 0.649819 | serpent7776 |
3e244890b34cc5a92d9857d949bad14876be4457 | 9,773 | cc | C++ | chrome/browser/ui/global_media_controls/presentation_request_notification_producer.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | chrome/browser/ui/global_media_controls/presentation_request_notification_producer.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | chrome/browser/ui/global_media_controls/presentation_request_notification_producer.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/global_media_controls/presentation_request_notification_producer.h"
#include <utility>
#include "base/unguessable_token.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/global_media_controls/media_notification_service.h"
#include "components/media_router/browser/media_router.h"
#include "components/media_router/browser/media_router_factory.h"
#include "components/media_router/browser/presentation/presentation_service_delegate_impl.h"
#include "components/media_router/common/providers/cast/cast_media_source.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
namespace {
base::WeakPtr<media_router::WebContentsPresentationManager>
GetActiveWebContentsPresentationManager() {
auto* browser = chrome::FindLastActive();
if (!browser)
return nullptr;
auto* tab_strip = browser->tab_strip_model();
if (!tab_strip)
return nullptr;
auto* web_contents = tab_strip->GetActiveWebContents();
if (!web_contents)
return nullptr;
return media_router::WebContentsPresentationManager::Get(web_contents);
}
content::WebContents* GetWebContentsFromPresentationRequest(
const content::PresentationRequest& request) {
auto* rfh = content::RenderFrameHost::FromID(request.render_frame_host_id);
return rfh ? content::WebContents::FromRenderFrameHost(rfh) : nullptr;
}
} // namespace
class PresentationRequestNotificationProducer::
PresentationRequestWebContentsObserver
: public content::WebContentsObserver {
public:
PresentationRequestWebContentsObserver(
content::WebContents* web_contents,
PresentationRequestNotificationProducer* notification_producer)
: content::WebContentsObserver(web_contents),
notification_producer_(notification_producer) {
DCHECK(notification_producer_);
}
private:
void WebContentsDestroyed() override {
notification_producer_->DeleteItemForPresentationRequest("Dialog closed.");
}
void NavigationEntryCommitted(
const content::LoadCommittedDetails& load_details) override {
notification_producer_->DeleteItemForPresentationRequest("Dialog closed.");
}
void RenderProcessGone(base::TerminationStatus status) override {
notification_producer_->DeleteItemForPresentationRequest("Dialog closed.");
}
PresentationRequestNotificationProducer* const notification_producer_;
};
PresentationRequestNotificationProducer::
PresentationRequestNotificationProducer(
MediaNotificationService* notification_service)
: notification_service_(notification_service),
container_observer_set_(this) {
notification_service_->AddObserver(this);
}
PresentationRequestNotificationProducer::
~PresentationRequestNotificationProducer() {
notification_service_->RemoveObserver(this);
}
base::WeakPtr<media_message_center::MediaNotificationItem>
PresentationRequestNotificationProducer::GetNotificationItem(
const std::string& id) {
if (item_ && item_->id() == id) {
return item_->GetWeakPtr();
} else {
return nullptr;
}
}
std::set<std::string>
PresentationRequestNotificationProducer::GetActiveControllableNotificationIds()
const {
return (item_ && !should_hide_) ? std::set<std::string>({item_->id()})
: std::set<std::string>();
}
void PresentationRequestNotificationProducer::OnItemShown(
const std::string& id,
MediaNotificationContainerImpl* container) {
if (container) {
container_observer_set_.Observe(id, container);
}
}
void PresentationRequestNotificationProducer::OnContainerDismissed(
const std::string& id) {
auto item = GetNotificationItem(id);
if (item) {
item->Dismiss();
DeleteItemForPresentationRequest("Dialog closed.");
}
}
void PresentationRequestNotificationProducer::OnStartPresentationContextCreated(
std::unique_ptr<media_router::StartPresentationContext> context) {
DCHECK(context);
const auto& request = context->presentation_request();
CreateItemForPresentationRequest(request, std::move(context));
}
content::WebContents*
PresentationRequestNotificationProducer::GetWebContents() {
return item_ ? GetWebContentsFromPresentationRequest(item_->request())
: nullptr;
}
base::WeakPtr<PresentationRequestNotificationItem>
PresentationRequestNotificationProducer::GetNotificationItem() {
return item_ ? item_->GetWeakPtr() : nullptr;
}
void PresentationRequestNotificationProducer::OnNotificationListChanged() {
ShowOrHideItem();
}
void PresentationRequestNotificationProducer::SetTestPresentationManager(
base::WeakPtr<media_router::WebContentsPresentationManager>
presentation_manager) {
test_presentation_manager_ = presentation_manager;
}
void PresentationRequestNotificationProducer::OnMediaDialogOpened() {
// At the point where this method is called, MediaNotificationService is
// in a state where it can't accept new notifications. As a workaround,
// we simply defer the handling of the event.
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
&PresentationRequestNotificationProducer::AfterMediaDialogOpened,
weak_factory_.GetWeakPtr(),
test_presentation_manager_
? test_presentation_manager_
: GetActiveWebContentsPresentationManager()));
}
void PresentationRequestNotificationProducer::OnMediaDialogClosed() {
// This event needs to be handled asynchronously the be absolutely certain
// it's handled later than a prior call to OnMediaDialogOpened().
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
&PresentationRequestNotificationProducer::AfterMediaDialogClosed,
weak_factory_.GetWeakPtr()));
}
void PresentationRequestNotificationProducer::AfterMediaDialogOpened(
base::WeakPtr<media_router::WebContentsPresentationManager>
presentation_manager) {
presentation_manager_ = presentation_manager;
// It's possible the presentation manager was deleted since the call to
// this method was scheduled.
if (!presentation_manager_)
return;
presentation_manager_->AddObserver(this);
// Handle any request that was created while we weren't watching, first
// making sure the dialog hasn't been closed since the we found out it was
// opening. This is the normal way notifications are created for a default
// presentation request.
if (presentation_manager_->HasDefaultPresentationRequest() &&
notification_service_->HasOpenDialog()) {
OnDefaultPresentationChanged(
&presentation_manager_->GetDefaultPresentationRequest());
}
}
void PresentationRequestNotificationProducer::AfterMediaDialogClosed() {
DeleteItemForPresentationRequest("Dialog closed.");
if (presentation_manager_)
presentation_manager_->RemoveObserver(this);
presentation_manager_ = nullptr;
}
void PresentationRequestNotificationProducer::OnMediaRoutesChanged(
const std::vector<media_router::MediaRoute>& routes) {
if (!routes.empty()) {
notification_service_->HideMediaDialog();
item_->Dismiss();
}
}
void PresentationRequestNotificationProducer::OnDefaultPresentationChanged(
const content::PresentationRequest* presentation_request) {
// NOTE: We only observe the presentation manager while the media control
// dialog is open, so this method is only handling the unusual case where
// the default presentation request is changed while the dialog is open.
// In the even more unusual case where the dialog is already open with a
// notification for a non-default request, we ignored changes in the
// default request.
if (!HasItemForNonDefaultRequest()) {
DeleteItemForPresentationRequest("Default presentation changed.");
if (presentation_request) {
CreateItemForPresentationRequest(*presentation_request, nullptr);
}
}
}
void PresentationRequestNotificationProducer::CreateItemForPresentationRequest(
const content::PresentationRequest& request,
std::unique_ptr<media_router::StartPresentationContext> context) {
presentation_request_observer_ =
std::make_unique<PresentationRequestWebContentsObserver>(
GetWebContentsFromPresentationRequest(request), this);
// This may replace an existing item, which is the right thing to do if
// we've reached this point.
item_.emplace(notification_service_, request, std::move(context));
ShowOrHideItem();
}
void PresentationRequestNotificationProducer::DeleteItemForPresentationRequest(
const std::string& message) {
if (!item_)
return;
const auto id{item_->id()};
item_.reset();
presentation_request_observer_.reset();
notification_service_->HideNotification(id);
}
void PresentationRequestNotificationProducer::ShowOrHideItem() {
if (!item_) {
should_hide_ = true;
return;
}
auto* web_contents = GetWebContentsFromPresentationRequest(item_->request());
bool new_visibility =
web_contents
? notification_service_->HasActiveNotificationsForWebContents(
web_contents)
: true;
if (should_hide_ == new_visibility)
return;
should_hide_ = new_visibility;
if (should_hide_) {
notification_service_->HideNotification(item_->id());
} else {
notification_service_->ShowNotification(item_->id());
}
}
| 35.930147 | 95 | 0.769569 | DamieFC |
3e275fe2ecb58bd94d4f90d23f99042a646a300b | 2,400 | cpp | C++ | source/pump.cpp | MuellerA/Led-Lamp | f54bd267e0e2b2d1d205f4bce3088e9081b22238 | [
"MIT"
] | null | null | null | source/pump.cpp | MuellerA/Led-Lamp | f54bd267e0e2b2d1d205f4bce3088e9081b22238 | [
"MIT"
] | null | null | null | source/pump.cpp | MuellerA/Led-Lamp | f54bd267e0e2b2d1d205f4bce3088e9081b22238 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// pump.cpp
// (c) Andreas Müller
// see LICENSE.md
////////////////////////////////////////////////////////////////////////////////
#include "ledMatrix.h"
////////////////////////////////////////////////////////////////////////////////
class Pump
{
public:
Pump(unsigned char mode) ;
void Update() ;
void Display() ;
void Config(unsigned char type, unsigned char value) ;
private:
unsigned char _mode ;
Rgb &_curRgb ;
Rgb _deltaRgb ;
Rgb _rgb[LedMatrix::kX/2] ;
unsigned char _brightness ;
unsigned char _state ;
} ;
static_assert(sizeof(Pump) < (RAMSIZE - 0x28), "not enough RAM") ;
////////////////////////////////////////////////////////////////////////////////
Pump::Pump(unsigned char mode) : _mode(mode), _curRgb(_rgb[LedMatrix::kX/2 - 1]), _brightness(0x7f), _state(0)
{
for (Rgb *iRgb = _rgb, *eRgb = _rgb + LedMatrix::kX/2 ; iRgb < eRgb ; ++iRgb)
iRgb->Clr(0x10) ;
_deltaRgb.Rnd(_brightness) ;
_deltaRgb.Sub(_curRgb) ;
_deltaRgb.DivX() ;
}
void Pump::Update()
{
if (_state == 0)
{
_deltaRgb.Rnd(_brightness) ;
_deltaRgb.Sub(_curRgb) ;
_deltaRgb.DivX() ;
}
if (_state < LedMatrix::kX)
{
for (unsigned char x2 = 0 ; x2 < LedMatrix::kX/2 - 1 ; ++x2)
_rgb[x2] = _rgb[x2+1] ;
_curRgb.Add(_deltaRgb) ;
}
else if (_state < LedMatrix::kX * 2)
{
for (unsigned char x2 = 0 ; x2 < LedMatrix::kX/2 - 1 ; ++x2)
_rgb[x2] = _rgb[x2+1] ;
}
if (++_state == LedMatrix::kX * 3)
_state = 0 ;
}
void Pump::Display()
{
for (unsigned short idx = 0 ; idx < LedMatrix::kSize ; ++idx)
{
switch (_mode)
{
case 1:
{
unsigned char x, y ;
LedMatrix::IdxToCoord(idx, x, y) ;
if (x >= LedMatrix::kX/2)
x = LedMatrix::kX-1 - x ;
if (y >= LedMatrix::kY/2)
y = LedMatrix::kY-1 - y ;
if (y < x)
x = y ;
_rgb[x].Send() ;
}
break ;
default:
{
_curRgb.Send() ;
}
break ;
}
}
}
void Pump::Config(unsigned char type, unsigned char value)
{
switch (type)
{
case LedMatrix::ConfigBrightness:
_brightness = value ;
break ;
case LedMatrix::ConfigForceRedraw:
break ;
}
}
////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////
| 21.428571 | 110 | 0.4625 | MuellerA |
3e2881dde342fe9a9f569feb0af115f140186669 | 3,034 | hpp | C++ | src/contrib/mlir/core/compiler.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/core/compiler.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/core/compiler.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
// NOTE: This file follows nGraph format style.
// Follows nGraph naming convention for public APIs only, else MLIR naming
// convention.
#pragma once
#include <mlir/IR/Builders.h>
#include <mlir/IR/Module.h>
#include <mlir/IR/Types.h>
#include <typeindex>
#include <unordered_map>
#include <vector>
#include "contrib/mlir/runtime/cpu/memory_manager.hpp"
#include "ngraph/check.hpp"
#include "ngraph/descriptor/tensor.hpp"
#include "ngraph/function.hpp"
#include "ngraph/log.hpp"
#include "ngraph/node.hpp"
#include "ngraph/op/experimental/compiled_kernel.hpp"
namespace ngraph
{
namespace runtime
{
namespace ngmlir
{
/// MLIR Compiler. Given an nGraph sub-graph, represented as CompiledKernel
/// node, it
/// translates the graph down to nGraph dialect and applies core optimizations.
///
/// The compiler owns the MLIR module until compilation is done. After that,
/// the module can be grabbed and plugged into MLIR backends.
class MLIRCompiler
{
public:
/// Initializes MLIR environment. It must be called only once.
static void init();
public:
MLIRCompiler(std::shared_ptr<ngraph::Function> function,
::mlir::MLIRContext& context);
/// Compiles a subgraph with MLIR
void compile();
::mlir::OwningModuleRef& get_module() { return m_module; }
private:
// Converts an nGraph sub-graph to MLIR nGraph dialect.
void buildNgDialectModule();
// Applies any nGraph dialect optimizations
void optimizeNgDialect();
private:
// Sub-graph to be compiled and executed with MLIR.
std::shared_ptr<ngraph::Function> m_function;
// MLIR context that holds all the MLIR information related to the sub-graph
// compilation.
::mlir::MLIRContext& m_context;
::mlir::OwningModuleRef m_module;
// Global initialization for MLIR compiler
static bool initialized;
};
}
}
}
| 35.694118 | 92 | 0.591628 | pqLee |
3e2b39c946cc069ab2d56deb068b83c15e9dbf80 | 7,561 | cpp | C++ | gym-cloth/render/ext/libzmq/tests/test_timers.cpp | ernovoseller/BC_switching_criteria | 44259dd17d14bc6bab05afb5df79943773508419 | [
"MIT"
] | null | null | null | gym-cloth/render/ext/libzmq/tests/test_timers.cpp | ernovoseller/BC_switching_criteria | 44259dd17d14bc6bab05afb5df79943773508419 | [
"MIT"
] | 7 | 2016-06-03T05:41:27.000Z | 2018-08-07T07:09:40.000Z | gym-cloth/render/ext/libzmq/tests/test_timers.cpp | ernovoseller/BC_switching_criteria | 44259dd17d14bc6bab05afb5df79943773508419 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file
This file is part of libzmq, the ZeroMQ core engine in C++.
libzmq is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
As a special exception, the Contributors give you permission to link
this library with independent modules to produce an executable,
regardless of the license terms of these independent modules, and to
copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the
terms and conditions of the license of that module. An independent
module is a module which is not derived from or based on this library.
If you modify this library, you must extend this exception to your
version of the library.
libzmq is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define __STDC_LIMIT_MACROS // to define SIZE_MAX with older compilers
#include "testutil.hpp"
#include "testutil_unity.hpp"
void setUp ()
{
}
void tearDown ()
{
}
void handler (int timer_id_, void *arg_)
{
(void) timer_id_; // Stop 'unused' compiler warnings
*((bool *) arg_) = true;
}
int sleep_and_execute (void *timers_)
{
int timeout = zmq_timers_timeout (timers_);
// Sleep methods are inaccurate, so we sleep in a loop until time arrived
while (timeout > 0) {
msleep (timeout);
timeout = zmq_timers_timeout (timers_);
}
return zmq_timers_execute (timers_);
}
void test_null_timer_pointers ()
{
void *timers = NULL;
TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_destroy (&timers));
// TODO this currently triggers an access violation
#if 0
TEST_ASSERT_FAILURE_ERRNO(EFAULT, zmq_timers_destroy (NULL));
#endif
const size_t dummy_interval = 100;
const int dummy_timer_id = 1;
TEST_ASSERT_FAILURE_ERRNO (
EFAULT, zmq_timers_add (timers, dummy_interval, &handler, NULL));
TEST_ASSERT_FAILURE_ERRNO (
EFAULT, zmq_timers_add (&timers, dummy_interval, &handler, NULL));
TEST_ASSERT_FAILURE_ERRNO (EFAULT,
zmq_timers_cancel (timers, dummy_timer_id));
TEST_ASSERT_FAILURE_ERRNO (EFAULT,
zmq_timers_cancel (&timers, dummy_timer_id));
TEST_ASSERT_FAILURE_ERRNO (
EFAULT, zmq_timers_set_interval (timers, dummy_timer_id, dummy_interval));
TEST_ASSERT_FAILURE_ERRNO (
EFAULT,
zmq_timers_set_interval (&timers, dummy_timer_id, dummy_interval));
TEST_ASSERT_FAILURE_ERRNO (EFAULT,
zmq_timers_reset (timers, dummy_timer_id));
TEST_ASSERT_FAILURE_ERRNO (EFAULT,
zmq_timers_reset (&timers, dummy_timer_id));
TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_timeout (timers));
TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_timeout (&timers));
TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_execute (timers));
TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_execute (&timers));
}
void test_corner_cases ()
{
void *timers = zmq_timers_new ();
TEST_ASSERT_NOT_NULL (timers);
const size_t dummy_interval = SIZE_MAX;
const int dummy_timer_id = 1;
// attempt to cancel non-existent timer
TEST_ASSERT_FAILURE_ERRNO (EINVAL,
zmq_timers_cancel (timers, dummy_timer_id));
// attempt to set interval of non-existent timer
TEST_ASSERT_FAILURE_ERRNO (
EINVAL, zmq_timers_set_interval (timers, dummy_timer_id, dummy_interval));
// attempt to reset non-existent timer
TEST_ASSERT_FAILURE_ERRNO (EINVAL,
zmq_timers_reset (timers, dummy_timer_id));
// attempt to add NULL handler
TEST_ASSERT_FAILURE_ERRNO (
EFAULT, zmq_timers_add (timers, dummy_interval, NULL, NULL));
const int timer_id = TEST_ASSERT_SUCCESS_ERRNO (
zmq_timers_add (timers, dummy_interval, handler, NULL));
// attempt to cancel timer twice
// TODO should this case really be an error? canceling twice could be allowed
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_cancel (timers, timer_id));
TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_cancel (timers, timer_id));
// timeout without any timers active
TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_timeout (timers));
// cleanup
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_destroy (&timers));
}
void test_timers ()
{
void *timers = zmq_timers_new ();
TEST_ASSERT_NOT_NULL (timers);
bool timer_invoked = false;
const unsigned long full_timeout = 100;
void *const stopwatch = zmq_stopwatch_start ();
const int timer_id = TEST_ASSERT_SUCCESS_ERRNO (
zmq_timers_add (timers, full_timeout, handler, &timer_invoked));
// Timer should not have been invoked yet
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers));
if (zmq_stopwatch_intermediate (stopwatch) < full_timeout) {
TEST_ASSERT_FALSE (timer_invoked);
}
// Wait half the time and check again
long timeout = TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_timeout (timers));
msleep (timeout / 2);
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers));
if (zmq_stopwatch_intermediate (stopwatch) < full_timeout) {
TEST_ASSERT_FALSE (timer_invoked);
}
// Wait until the end
TEST_ASSERT_SUCCESS_ERRNO (sleep_and_execute (timers));
TEST_ASSERT_TRUE (timer_invoked);
timer_invoked = false;
// Wait half the time and check again
timeout = TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_timeout (timers));
msleep (timeout / 2);
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers));
if (zmq_stopwatch_intermediate (stopwatch) < 2 * full_timeout) {
TEST_ASSERT_FALSE (timer_invoked);
}
// Reset timer and wait half of the time left
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_reset (timers, timer_id));
msleep (timeout / 2);
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers));
if (zmq_stopwatch_stop (stopwatch) < 2 * full_timeout) {
TEST_ASSERT_FALSE (timer_invoked);
}
// Wait until the end
TEST_ASSERT_SUCCESS_ERRNO (sleep_and_execute (timers));
TEST_ASSERT_TRUE (timer_invoked);
timer_invoked = false;
// reschedule
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_set_interval (timers, timer_id, 50));
TEST_ASSERT_SUCCESS_ERRNO (sleep_and_execute (timers));
TEST_ASSERT_TRUE (timer_invoked);
timer_invoked = false;
// cancel timer
timeout = TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_timeout (timers));
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_cancel (timers, timer_id));
msleep (timeout * 2);
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers));
TEST_ASSERT_FALSE (timer_invoked);
TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_destroy (&timers));
}
int main ()
{
setup_test_environment ();
UNITY_BEGIN ();
RUN_TEST (test_timers);
RUN_TEST (test_null_timer_pointers);
RUN_TEST (test_corner_cases);
return UNITY_END ();
}
| 33.90583 | 82 | 0.714059 | ernovoseller |
3e2c8a71eebd064e23fb673f96a6d5e7ea409572 | 8,915 | cpp | C++ | src/StatusBar.cpp | petterh/textedit | df59502fa5309834b2d2452af609ba6fb1dc97c2 | [
"MIT"
] | 6 | 2018-04-08T06:30:27.000Z | 2021-12-19T12:52:28.000Z | src/StatusBar.cpp | petterh/textedit | df59502fa5309834b2d2452af609ba6fb1dc97c2 | [
"MIT"
] | 32 | 2017-11-03T09:39:48.000Z | 2021-12-23T18:27:20.000Z | src/StatusBar.cpp | petterh/textedit | df59502fa5309834b2d2452af609ba6fb1dc97c2 | [
"MIT"
] | 1 | 2021-09-13T08:38:56.000Z | 2021-09-13T08:38:56.000Z | /*
* $Header: /Book/StatusBar.cpp 14 16.07.04 10:42 Oslph312 $
*
* NOTE: Both Toolbar and Statusbar are tailored to TextEdit.
* A more general approach would be to derive both from base classes.
*/
#include "precomp.h"
#include "Statusbar.h"
#include "MenuFont.h"
#include "HTML.h"
#include "InstanceSubclasser.h"
#include "formatMessage.h"
#include "formatNumber.h"
#include "graphics.h"
#include "utils.h"
#include "resource.h"
#ifndef SB_SETICON
#define SB_SETICON (WM_USER+15)
#endif
PRIVATE bool sm_bHighlight = false;
PRIVATE LRESULT CALLBACK statusbarParentSpy(
HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam );
PRIVATE InstanceSubclasser s_parentSubclasser( statusbarParentSpy );
/**
* Recalculates the sizes of the various status bar parts.
*/
PRIVATE void recalcParts( HWND hwndStatusbar, int nTotalWidth = -1 ) {
assert( IsWindow( hwndStatusbar ) );
if ( -1 == nTotalWidth ) {
const Rect rc = getWindowRect( hwndStatusbar );
nTotalWidth = rc.width();
}
const int nBorder = GetSystemMetrics( SM_CXEDGE );
const int nWidth =
nTotalWidth - GetSystemMetrics( SM_CXVSCROLL ) - nBorder - 1;
const int nExtra = 4 * nBorder;
const int nWidthUnicode =
measureString( _T( "Unicode" ) ).cx + nExtra;
const int nWidthPosition =
measureString( _T( "Ln 99,999 Col 999 100%" ) ).cx + nExtra;
const int nWidthToolbarButton = GetSystemMetrics(
MenuFont::isLarge() ? SM_CXICON : SM_CXSMICON );
const int nWidthIcon = nWidthToolbarButton + nExtra;
const int aParts[] = {
nWidth - nWidthPosition - nWidthUnicode - nWidthIcon,
nWidth - nWidthUnicode - nWidthIcon,
nWidth - nWidthIcon,
nWidth - 0, // If we use -1, we overflow into the sizing grip.
};
SNDMSG( hwndStatusbar, SB_SETPARTS,
dim( aParts ), reinterpret_cast< LPARAM >( aParts ) );
}
PRIVATE void drawItem( DRAWITEMSTRUCT *pDIS ) {
// This returns a pointer to the static
// szMessageBuffer used in setMessageV:
LPCTSTR pszText = reinterpret_cast< LPCTSTR >(
SNDMSG( pDIS->hwndItem, SB_GETTEXT, 0, 0 ) );
const int nSavedDC = SaveDC( pDIS->hDC );
if ( sm_bHighlight ) {
SetTextColor( pDIS->hDC, GetSysColor( COLOR_HIGHLIGHTTEXT ) );
SetBkColor ( pDIS->hDC, GetSysColor( COLOR_HIGHLIGHT ) );
fillSysColorSolidRect( pDIS->hDC,
&pDIS->rcItem, COLOR_HIGHLIGHT );
pDIS->rcItem.left += GetSystemMetrics( SM_CXEDGE );
} else {
SetTextColor( pDIS->hDC, GetSysColor( COLOR_BTNTEXT ) );
SetBkColor ( pDIS->hDC, GetSysColor( COLOR_BTNFACE ) );
}
const int nHeight = Rect( pDIS->rcItem ).height();
const int nExtra = nHeight - MenuFont::getHeight();
pDIS->rcItem.top += nExtra / 2 - 1;
pDIS->rcItem.left += GetSystemMetrics( SM_CXEDGE );
paintHTML( pDIS->hDC, pszText, &pDIS->rcItem,
GetWindowFont( pDIS->hwndItem ), PHTML_SINGLE_LINE );
verify( RestoreDC( pDIS->hDC, nSavedDC ) );
}
PRIVATE LRESULT CALLBACK statusbarParentSpy(
HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
const LRESULT lResult =
s_parentSubclasser.callOldProc( hwnd, msg, wParam, lParam );
if ( WM_SIZE == msg ) {
HWND hwndStatusbar =
s_parentSubclasser.getUserDataAsHwnd( hwnd );
assert( IsWindow( hwndStatusbar ) );
const int cx = LOWORD( lParam );
recalcParts( hwndStatusbar, cx );
SNDMSG( hwndStatusbar, WM_SIZE, wParam, lParam );
} else if ( WM_DRAWITEM == msg ) {
drawItem( reinterpret_cast< DRAWITEMSTRUCT * >( lParam ) );
}
return lResult;
}
Statusbar::Statusbar( HWND hwndParent, UINT uiID )
: m_hicon( 0 )
, m_nIndex( 0 )
, zoomPercentage( 100 )
{
assert( 0 != this );
const HINSTANCE hinst = getModuleHandle();
attach( CreateWindowEx(
0, STATUSCLASSNAME, _T( "" ),
SBARS_SIZEGRIP | WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, hwndParent, (HMENU) uiID, hinst, 0 ) );
assert( IsWindow( *this ) );
if ( !IsWindow( *this ) ) {
throwException( _T( "Unable to create status bar" ) );
}
onSettingChange( 0 ); // Sets the font and the parts.
verify( s_parentSubclasser.subclass( hwndParent, m_hwnd ) );
setMessage( IDS_READY );
}
Statusbar::~Statusbar() {
if ( 0 != m_hicon ) {
DestroyIcon( m_hicon );
}
}
void __cdecl Statusbar::setMessageV( LPCTSTR pszFmt, va_list vl ) {
// This *must* be a static buffer. Since the first pane is
// SBT_OWNERDRAW, the status bar control doesn't know that
// this is text; the lParam is merely 32 arbitrary bits of
// application data, and the status bar doesn't retain the
// text, just the pointer.
static TCHAR szMessageBuffer[ 512 ];
assert( isGoodStringPtr( pszFmt ) );
if ( isGoodStringPtr( pszFmt ) ) {
const String strMessage = formatMessageV( pszFmt, vl );
_tcsncpy_s( szMessageBuffer, strMessage.c_str(), _TRUNCATE );
} else {
_tcscpy_s( szMessageBuffer, _T( "Internal Error" ) );
}
int nPart = message_part | SBT_OWNERDRAW;
if ( sm_bHighlight ) {
nPart |= SBT_NOBORDERS; // SBT_POPOUT
// This invalidation is necessary for SBT_NOBORDERS.
// With SBT_POPOUT, it is not necessary.
Rect rc;
sendMessage( SB_GETRECT, message_part, reinterpret_cast< LPARAM >( &rc ) );
InvalidateRect( *this, &rc, TRUE );
}
setText( nPart, szMessageBuffer );
}
void __cdecl Statusbar::setMessage( LPCTSTR pszFmt, ... ) {
sm_bHighlight = false;
va_list vl;
va_start( vl, pszFmt );
setMessageV( pszFmt, vl );
va_end( vl );
}
void __cdecl Statusbar::setMessage( UINT idFmt, ... ) {
sm_bHighlight = false;
const String strFmt = loadString( idFmt );
va_list vl;
va_start( vl, idFmt );
setMessageV( strFmt.c_str(), vl );
va_end( vl );
}
void __cdecl Statusbar::setHighlightMessage( UINT idFmt, ... ) {
sm_bHighlight = true;
const String strFmt = loadString( idFmt );
va_list vl;
va_start( vl, idFmt );
setMessageV( strFmt.c_str(), vl );
va_end( vl );
}
void __cdecl Statusbar::setErrorMessage(
UINT idFlags, UINT idFmt, ... )
{
va_list vl;
va_start( vl, idFmt );
MessageBeep( idFlags );
const String strFmt = loadString( idFmt );
if ( IsWindowVisible( *this ) ) {
sm_bHighlight = true;
setMessageV( strFmt.c_str(), vl );
} else {
messageBoxV( GetParent( *this ), MB_OK | idFlags, strFmt.c_str(), vl );
}
va_end( vl );
}
void Statusbar::update( void ) {
#if 0 // TODO: Unit test of formatNumber
trace( _T( "testing formatNumber: %d = %s\n" ), 0, formatNumber( 0 ).c_str() );
trace( _T( "testing formatNumber: %d = %s\n" ), 123, formatNumber( 123 ).c_str() );
trace( _T( "testing formatNumber: %d = %s\n" ), 12345, formatNumber( 12345 ).c_str() );
trace( _T( "testing formatNumber: %d = %s\n" ), 1234567890, formatNumber( 1234567890 ).c_str() );
#endif
const String strLine = formatNumber( position.y + 1 );
const String strColumn = formatNumber( position.x + 1 );
const String strPos = formatMessage( IDS_POSITION, strLine.c_str(), strColumn.c_str() );
const String strZoom = formatMessage( _T( " %1!d!%%\t" ), this->zoomPercentage );
const String str = strPos + strZoom;
setText( position_part, str.c_str() );
const HWND hwndEditWnd = GetDlgItem( GetParent( *this ), IDC_EDIT );
if ( GetFocus() == hwndEditWnd ) {
setMessage( IDS_READY );
}
}
void Statusbar::update( const Point& updatedPosition ) {
this->position = updatedPosition;
update();
}
void Statusbar::update( const int updatedZoomPercentage ) {
this->zoomPercentage = updatedZoomPercentage;
update();
}
void Statusbar::setFileType( const bool isUnicode ) {
setText( filetype_part, isUnicode ? _T( "\tUnicode\t" ) : _T( "\tANSI\t" ) );
}
void Statusbar::setIcon( int nIndex ) {
const int nResource = MenuFont::isLarge() ? 121 : 120;
const HINSTANCE hinst = GetModuleHandle(_T("COMCTL32"));
const HIMAGELIST hImageList = ImageList_LoadImage(hinst,
MAKEINTRESOURCE(nResource),
0, 0, CLR_DEFAULT, IMAGE_BITMAP,
LR_DEFAULTSIZE | LR_LOADMAP3DCOLORS);
setIcon(hImageList, nIndex);
if (0 != hImageList) {
verify(ImageList_Destroy(hImageList));
}
}
void Statusbar::setIcon( HIMAGELIST hImageList, int nIndex ) {
if ( 0 != m_hicon ) {
DestroyIcon( m_hicon );
m_hicon = 0;
}
m_nIndex = nIndex;
if ( 0 != m_nIndex ) {
m_hicon = ImageList_GetIcon( hImageList, m_nIndex, ILD_NORMAL );
}
sendMessage( SB_SETICON, action_part, reinterpret_cast< LPARAM >( m_hicon ) );
UpdateWindow( *this );
}
void Statusbar::onSettingChange( LPCTSTR pszSection ) {
const HFONT hfont = MenuFont::getFont();
assert( 0 != hfont );
SetWindowFont( *this, hfont, true );
setIcon( m_nIndex );
recalcParts( *this );
}
// end of file
| 27.686335 | 100 | 0.654627 | petterh |
3e2f773e4ced7fe9781102528f0edfd009668136 | 7,427 | cpp | C++ | SysLib/Demand/Data/Trip_Length_Data.cpp | kravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | 2 | 2018-04-27T11:07:02.000Z | 2020-04-24T06:53:21.000Z | SysLib/Demand/Data/Trip_Length_Data.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | SysLib/Demand/Data/Trip_Length_Data.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | //*********************************************************
// Trip_Length_Data.cpp - trip length data class
//*********************************************************
#include "Trip_Length_Data.hpp"
//---------------------------------------------------------
// Trip_Length_Data constructor
//---------------------------------------------------------
Trip_Length_Data::Trip_Length_Data (void) : Class2_Index (0, 0)
{
Count (0);
}
//---------------------------------------------------------
// Trip_Length_Array constructor
//---------------------------------------------------------
Trip_Length_Array::Trip_Length_Array (int max_records) :
Class2_Array (sizeof (Trip_Length_Data), max_records), Static_Service ()
{
increment = 0;
output_flag = false;
}
//---- Add Trip ----
bool Trip_Length_Array::Add_Trip (int mode, int purpose1, int purpose2, int length, int count)
{
Trip_Length_Data *data_ptr, data_rec;
if (increment <= 0 || length < 0) return (false);
data_rec.Mode (mode);
if (purpose1 > purpose2) {
data_rec.Purpose1 (purpose2);
data_rec.Purpose2 (purpose1);
} else {
data_rec.Purpose1 (purpose1);
data_rec.Purpose2 (purpose2);
}
length /= increment;
if (length >= 0xFFFF) length = 0xFFFE;
data_rec.Increment (length);
data_ptr = (Trip_Length_Data *) Get (&data_rec);
if (data_ptr == NULL) {
data_ptr = New_Record (true);
if (data_ptr == NULL) return (false);
data_rec.Count (0);
if (!Add (&data_rec)) return (false);
}
data_ptr->Add_Count (count);
return (true);
}
//---- Open_Trip_Length_File ----
bool Trip_Length_Array::Open_Trip_Length_File (char *filename, char *label)
{
if (filename != NULL) {
output_flag = true;
exe->Print (1);
if (label == NULL) {
length_file.File_Type ("New Trip Length File");
} else {
length_file.File_Type (label);
}
length_file.File_Access (Db_Code::CREATE);
if (!length_file.Open (exe->Project_Filename (filename, exe->Extension ()))) {
exe->File_Error ("Creating New Trip Length File", length_file.Filename ());
return (false);
}
}
return (true);
}
//---- Write_Trip_Length_File ----
void Trip_Length_Array::Write_Trip_Length_File (void)
{
if (!output_flag) return;
int num_out;
Trip_Length_Data *data_ptr;
FILE *file;
exe->Show_Message ("Writing %s -- Record", length_file.File_Type ());
exe->Set_Progress ();
file = length_file.File ();
//---- write the header ----
fprintf (file, "MODE\tPURPOSE1\tPURPOSE2\tLENGTH\tTRIPS\n");
//---- write each record ----
num_out = 0;
for (data_ptr = First_Key (); data_ptr; data_ptr = Next_Key ()) {
exe->Show_Progress ();
fprintf (file, "%d\t%d\t%d\t%d\t%d\n", data_ptr->Mode (), data_ptr->Purpose1 (),
data_ptr->Purpose2 (), data_ptr->Increment () * increment, data_ptr->Count ());
num_out++;
}
exe->End_Progress ();
length_file.Close ();
exe->Print (2, "Number of %s Records = %d", length_file.File_Type (), num_out);
}
//
////---- Report ----
//
//void Trip_Length_Array::Report (int number, char *_title, char *_key1, char *_key2)
//{
// int size;
// Trip_Length_Data *data_ptr, total;
//
// //---- set header values ----
//
// keys = 0;
// if (_title != NULL) {
// size = (int) strlen (_title) + 1;
// title = new char [size];
// str_cpy (title, size, _title);
//
// exe->Show_Message (title);
// }
// if (_key1 != NULL) {
// size = (int) strlen (_key1) + 1;
// key1 = new char [size];
// str_cpy (key1, size, _key1);
// keys++;
// }
// if (_key2 != NULL) {
// size = (int) strlen (_key2) + 1;
// key2 = new char [size];
// str_cpy (key2, size, _key2);
// keys++;
// }
//
// //---- print the report ----
//
// exe->Header_Number (number);
//
// if (!exe->Break_Check (Num_Records () + 7)) {
// exe->Print (1);
// Header ();
// }
//
// for (data_ptr = First_Key (); data_ptr; data_ptr = Next_Key ()) {
// if (data_ptr->Count () == 0) continue;
//
// if (keys == 2) {
// exe->Print (1, "%3d-%-3d", (data_ptr->Group () >> 16), (data_ptr->Group () & 0x00FF));
// } else {
// exe->Print (1, "%5d ", data_ptr->Group ());
// }
//
// exe->Print (0, " %9d %8d %8d %8d %8d %8.2lf %8.2lf %8.2lf %8.2lf",
// data_ptr->Count (), (int) (data_ptr->Min_Distance () + 0.5),
// (int) (data_ptr->Max_Distance () + 0.5), (int) (data_ptr->Average_Distance () + 0.5),
// (int) (data_ptr->StdDev_Distance () + 0.5), data_ptr->Min_Time () / 60.0,
// data_ptr->Max_Time () / 60.0, data_ptr->Average_Time () / 60.0,
// data_ptr->StdDev_Time () / 60.0);
//
// if (total.Count () == 0) {
// total.Count (data_ptr->Count ());
// total.Distance (data_ptr->Distance ());
// total.Time (data_ptr->Time ());
// total.Distance_Sq (data_ptr->Distance_Sq ());
// total.Time_Sq (data_ptr->Time_Sq ());
//
// total.Min_Distance (data_ptr->Min_Distance ());
// total.Max_Distance (data_ptr->Max_Distance ());
//
// total.Min_Time (data_ptr->Min_Time ());
// total.Max_Time (data_ptr->Max_Time ());
// } else {
// total.Count (total.Count () + data_ptr->Count ());
// total.Distance (total.Distance () + data_ptr->Distance ());
// total.Time (total.Time () + data_ptr->Time ());
// total.Distance_Sq (total.Distance_Sq () + data_ptr->Distance_Sq ());
// total.Time_Sq (total.Time_Sq () + data_ptr->Time_Sq ());
//
// if (total.Min_Distance () > data_ptr->Min_Distance ()) total.Min_Distance (data_ptr->Min_Distance ());
// if (total.Max_Distance () < data_ptr->Max_Distance ()) total.Max_Distance (data_ptr->Max_Distance ());
//
// if (total.Min_Time () > data_ptr->Min_Time ()) total.Min_Time (data_ptr->Min_Time ());
// if (total.Max_Time () < data_ptr->Max_Time ()) total.Max_Time (data_ptr->Max_Time ());
// }
// }
// exe->Print (2, "Total %9d %8d %8d %8d %8d %8.2lf %8.2lf %8.2lf %8.2lf",
// total.Count (), (int) (total.Min_Distance () + 0.5), (int) (total.Max_Distance () + 0.5),
// (int) (total.Average_Distance () + 0.5), (int) (total.StdDev_Distance () + 0.5),
// total.Min_Time () / 60.0, total.Max_Time () / 60.0, total.Average_Time () / 60.0,
// total.StdDev_Time () / 60.0);
//
// exe->Header_Number (0);
//}
//
////---- Header ----
//
//void Trip_Length_Array::Header (void)
//{
// if (title != NULL) {
// exe->Print (1, title);
// } else {
// exe->Print (1, "Trip Length Summary Report");
// }
// if (keys < 2 || key1 == NULL) {
// exe->Print (2, "%19c", BLANK);
// } else {
// exe->Print (2, "%-7.7s%12c", key1, BLANK);
// }
// exe->Print (0, "------- Distance (meters) -------- --------- Time (minutes) ---------");
//
// if (keys == 2 && key2 != NULL) {
// exe->Print (1, "%-7.7s", key2);
// } else if (keys == 1 && key1 != NULL) {
// exe->Print (1, "%-7.7s", key1);
// } else {
// exe->Print (1, "Group ");
// }
// exe->Print (0, " Trips Minimum Maximum Average StdDev Minimum Maximum Average StdDev");
// exe->Print (1);
//}
//
///*********************************************|***********************************************
//
// [title]
//
// [key1] ------- Distance (meters) -------- --------- Time (minutes) ---------
// [key2] Trips Minimum Maximum Average StdDev Minimum Maximum Average StdDev
//
// ddd-ddd ddddddddd ddddddd ddddddd ddddddd ddddddd ffff.ff ffff.ff ffff.ff ffff.ff
//
// Total ddddddddd ddddddd ddddddd ddddddd ddddddd ffff.ff ffff.ff ffff.ff ffff.ff
//
//**********************************************|***********************************************/
| 29.355731 | 107 | 0.555271 | kravitz |
3e2f9520d1a6f948b0f0f5cfdbcdee95bb6006bc | 3,692 | cpp | C++ | src/blood.cpp | tilnewman/halloween | 7cea37e31b2e566be76707cd8dc48527cec95bc5 | [
"MIT"
] | null | null | null | src/blood.cpp | tilnewman/halloween | 7cea37e31b2e566be76707cd8dc48527cec95bc5 | [
"MIT"
] | null | null | null | src/blood.cpp | tilnewman/halloween | 7cea37e31b2e566be76707cd8dc48527cec95bc5 | [
"MIT"
] | null | null | null | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
//
// blood.cpp
//
#include "blood.hpp"
#include "context.hpp"
#include "info-region.hpp"
#include "level.hpp"
#include "random.hpp"
#include "screen-regions.hpp"
#include "settings.hpp"
#include "util.hpp"
namespace halloween
{
Blood::Blood()
: m_texture()
, m_textureCoords1()
, m_textureCoords2()
, m_isUsingFirstAnim(true)
, m_timePerFrame(0.05f)
, m_elapsedTimeSec(0.0f)
, m_textureIndex(0)
, m_sprite()
, m_isFinished(true)
{
// there are two blood splat animation in the same texture
m_textureCoords1.emplace_back(0, 0, 128, 128);
m_textureCoords1.emplace_back(128, 0, 128, 128);
m_textureCoords1.emplace_back(256, 0, 128, 128);
m_textureCoords1.emplace_back(384, 0, 128, 128);
m_textureCoords1.emplace_back(512, 0, 128, 128);
m_textureCoords1.emplace_back(640, 0, 128, 128);
m_textureCoords1.emplace_back(768, 0, 128, 128);
m_textureCoords1.emplace_back(896, 0, 128, 128);
m_textureCoords1.emplace_back(1024, 0, 128, 128);
m_textureCoords2.emplace_back(0, 128, 128, 128);
m_textureCoords2.emplace_back(128, 128, 128, 128);
m_textureCoords2.emplace_back(256, 128, 128, 128);
m_textureCoords2.emplace_back(384, 128, 128, 128);
m_textureCoords2.emplace_back(512, 128, 128, 128);
m_textureCoords2.emplace_back(640, 128, 128, 128);
m_textureCoords2.emplace_back(768, 128, 128, 128);
m_textureCoords2.emplace_back(896, 128, 128, 128);
m_textureCoords2.emplace_back(1024, 128, 128, 128);
}
void Blood::setup(const Settings & settings)
{
const std::string PATH = (settings.media_path / "image" / "blood.png").string();
m_texture.loadFromFile(PATH);
m_texture.setSmooth(true);
m_sprite.setTexture(m_texture);
}
void
Blood::start(Context & context, const sf::Vector2f & POSITION, const bool WILL_SPLASH_RIGHT)
{
m_isFinished = false;
m_elapsedTimeSec = 0.0f;
m_textureIndex = 0;
m_isUsingFirstAnim = context.random.boolean();
m_sprite.setPosition(POSITION);
if (m_isUsingFirstAnim)
{
m_sprite.setTextureRect(m_textureCoords1.at(0));
}
else
{
m_sprite.setTextureRect(m_textureCoords2.at(0));
}
if (WILL_SPLASH_RIGHT)
{
m_sprite.setScale(1.0f, 1.0f);
}
else
{
m_sprite.setScale(-1.0f, 1.0f);
}
}
void Blood::update(Context &, const float FRAME_TIME_SEC)
{
if (m_isFinished)
{
return;
}
m_elapsedTimeSec += FRAME_TIME_SEC;
if (m_elapsedTimeSec < m_timePerFrame)
{
return;
}
m_elapsedTimeSec -= m_timePerFrame;
++m_textureIndex;
if (m_textureIndex >= m_textureCoords1.size())
{
m_textureIndex = 0;
m_isFinished = true;
return;
}
if (m_isUsingFirstAnim)
{
m_sprite.setTextureRect(m_textureCoords1.at(m_textureIndex));
}
else
{
m_sprite.setTextureRect(m_textureCoords2.at(m_textureIndex));
}
}
void Blood::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
if (!m_isFinished)
{
target.draw(m_sprite, states);
}
}
} // namespace halloween
| 28.183206 | 100 | 0.596425 | tilnewman |
3e2fc78edccb4cd465baf813018cec64967a8d19 | 3,996 | cpp | C++ | src/GUI/Button.cpp | zachtepper/project-awful | 59e2e9261100a2b4449022725435d21b17c6f5b4 | [
"MIT"
] | null | null | null | src/GUI/Button.cpp | zachtepper/project-awful | 59e2e9261100a2b4449022725435d21b17c6f5b4 | [
"MIT"
] | null | null | null | src/GUI/Button.cpp | zachtepper/project-awful | 59e2e9261100a2b4449022725435d21b17c6f5b4 | [
"MIT"
] | null | null | null | #include "Button.hpp"
Button::Button( sf::Vector2f position, sf::Vector2f dimensions,
sf::Font* font, std::string text, unsigned character_size, bool hasBorder,
sf::Color text_idle_color, sf::Color text_hover_color, sf::Color text_active_color,
sf::Color idle_color, sf::Color hover_color, sf::Color active_color)
{
/*
while (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
continue;
}
*/
this->buttonState = BTN_IDLE;
this->setBackdrop(sf::Vector2f(dimensions.x, dimensions.y), idle_color, sf::Vector2f(position.x, position.y), active_color, 1);
this->setFont(*font);
this->setString(text);
this->setFillColor(text_idle_color);
this->setCharacterSize(character_size);
this->setPosition(position.x + ((dimensions.x - this->getGlobalBounds().width) / 2 - 1),
position.y + ((dimensions.y - character_size) / 2) - 5);
if (hasBorder) {
this->backdrop.setOutlineColor(sf::Color::Black);
this->setOutlineColor(sf::Color::Black);
}
// Update Private Variables
this->assignColors(text_idle_color, text_hover_color, text_active_color, idle_color, hover_color, active_color);
}
Button::~Button () {
while (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
continue;
}
}
const bool Button::isPressed() const
{
if ( this->buttonState == BTN_ACTIVE )
{
return true;
}
return false;
}
vector <sf::Color> Button::getStateColors (int state) {
vector <sf::Color> colors;
if (state == BTN_IDLE) {
colors.push_back(this->textIdleColor);
colors.push_back(this->idleColor);
} else if (state == BTN_HOVER) {
colors.push_back(this->textHoverColor);
colors.push_back(this->hoverColor);
} else {
colors.push_back(this->textActiveColor);
colors.push_back(this->activeColor);
}
return colors;
}
void Button::assignColors (sf::Color text_idle_color, sf::Color text_hover_color, sf::Color text_active_color,
sf::Color idle_color, sf::Color hover_color, sf::Color active_color) {
this->textIdleColor = text_idle_color;
this->textHoverColor = text_hover_color;
this->textActiveColor = text_active_color;
this->idleColor = idle_color;
this->hoverColor = hover_color;
this->activeColor = active_color;
}
void Button::update(const sf::Vector2f& mousePos)
{
// update booleans for hover and pressed
this->buttonState = BTN_IDLE;
if ( this->backdrop.getGlobalBounds().contains(mousePos) )
{
this->buttonState = BTN_HOVER;
if ( sf::Mouse::isButtonPressed(sf::Mouse::Left) )
{
this->buttonState = BTN_ACTIVE;
}
}
switch ( this->buttonState )
{
case BTN_IDLE:
this->backdrop.setFillColor(this->idleColor);
this->setFillColor(this->textIdleColor);
this->backdrop.setOutlineThickness(0);
this->setOutlineThickness(0);
break;
case BTN_HOVER:
this->backdrop.setFillColor(this->hoverColor);
this->setFillColor(this->textHoverColor);
this->backdrop.setOutlineThickness(1);
this->setOutlineThickness(1);
break;
case BTN_ACTIVE:
this->backdrop.setFillColor(this->activeColor);
this->setFillColor(this->textActiveColor);
this->backdrop.setOutlineThickness(1.5);
this->setOutlineThickness(0.5);
break;
default:
this->backdrop.setFillColor(sf::Color::Red);
this->setFillColor(sf::Color::Blue);
break;
}
}
void Button::render(sf::RenderTarget& target)
{
if (this->checkBackdrop()) {
target.draw(this->backdrop);
}
target.draw(*this);
}
| 30.738462 | 132 | 0.603103 | zachtepper |
3e3164a543c5bfcf7b189f965df4b1e64ba48649 | 195 | hpp | C++ | include/thread_pool.hpp | billsioros/thread-pool-cpp98 | 721ce58901504e73cf99696931f987578bccd8aa | [
"MIT"
] | null | null | null | include/thread_pool.hpp | billsioros/thread-pool-cpp98 | 721ce58901504e73cf99696931f987578bccd8aa | [
"MIT"
] | null | null | null | include/thread_pool.hpp | billsioros/thread-pool-cpp98 | 721ce58901504e73cf99696931f987578bccd8aa | [
"MIT"
] | null | null | null |
#pragma once
#include <cstddef>
namespace thread_pool
{
void create(std::size_t size);
void destroy();
void block();
void schedule(void (*task)(void *), void * args);
}
| 12.1875 | 53 | 0.610256 | billsioros |
3e332c89347c3b06f497a7d5e89efbb94bbbcb4a | 36,434 | cpp | C++ | opae-libs/tests/xfpga/test_enum_c.cpp | rchriste1/opae-sdk | a2b08cab139ebfb320a720bab98a6168748561a4 | [
"BSD-3-Clause"
] | null | null | null | opae-libs/tests/xfpga/test_enum_c.cpp | rchriste1/opae-sdk | a2b08cab139ebfb320a720bab98a6168748561a4 | [
"BSD-3-Clause"
] | null | null | null | opae-libs/tests/xfpga/test_enum_c.cpp | rchriste1/opae-sdk | a2b08cab139ebfb320a720bab98a6168748561a4 | [
"BSD-3-Clause"
] | null | null | null | // Copyright(c) 2017-2020, Intel Corporation
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Intel Corporation nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H
#include <json-c/json.h>
#include <opae/fpga.h>
#include <uuid/uuid.h>
#include <algorithm>
#include <array>
#include <cstdlib>
#include <fstream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <cstdarg>
#include <linux/ioctl.h>
#include "opae_drv.h"
#include "types_int.h"
#include "sysfs_int.h"
#include "mock/mock_opae.h"
extern "C" {
#include "fpga-dfl.h"
#include "token_list_int.h"
}
#include "xfpga.h"
extern "C" {
int xfpga_plugin_initialize(void);
int xfpga_plugin_finalize(void);
}
using namespace opae::testing;
int dfl_port_info(mock_object * m, int request, va_list argp){
int retval = -1;
errno = EINVAL;
UNUSED_PARAM(m);
UNUSED_PARAM(request);
struct dfl_fpga_port_info *pinfo = va_arg(argp, struct dfl_fpga_port_info *);
if (!pinfo) {
FPGA_MSG("pinfo is NULL");
goto out_EINVAL;
}
if (pinfo->argsz != sizeof(*pinfo)) {
FPGA_MSG("wrong structure size");
goto out_EINVAL;
}
pinfo->flags = 0;
pinfo->num_regions = 2;
pinfo->num_umsgs = 0;
retval = 0;
errno = 0;
out:
va_end(argp);
return retval;
out_EINVAL:
retval = -1;
errno = EINVAL;
goto out;
}
class enum_c_p : public mock_opae_p<2, xfpga_> {
protected:
enum_c_p() : filter_(nullptr) {}
virtual ~enum_c_p() {}
virtual void test_setup() override {
ASSERT_EQ(xfpga_plugin_initialize(), FPGA_OK);
ASSERT_EQ(xfpga_fpgaGetProperties(nullptr, &filter_), FPGA_OK);
num_matches_ = 0xc01a;
}
virtual void test_teardown() override {
EXPECT_EQ(fpgaDestroyProperties(&filter_), FPGA_OK);
token_cleanup();
xfpga_plugin_finalize();
}
// Need a concrete way to determine the number of fpgas on the system
// without relying on fpgaEnumerate() since that is the function that
// is under test.
int GetNumFpgas() {
if (platform_.mock_sysfs != nullptr) {
return platform_.devices.size();
}
int value;
std::string cmd =
"(ls -l /sys/class/fpga*/region*/*fme*/dev || "
"ls -l /sys/class/fpga*/*intel*) | (wc -l)";
ExecuteCmd(cmd, value);
return value;
}
int GetNumMatchedFpga () {
if (platform_.mock_sysfs != nullptr) {
return 1;
}
int matches = 0;
int socket_id;
int i;
for (i = 0; i < GetNumFpgas(); i++) {
std::string cmd = "cat /sys/class/fpga*/*" + std::to_string(i) +
"/*fme." + std::to_string(i) + "/socket_id";
ExecuteCmd(cmd, socket_id);
if (socket_id == (int)platform_.devices[0].socket_id) {
matches++;
}
}
return matches;
}
int GetMatchedGuidFpgas() {
if (platform_.mock_sysfs != nullptr) {
return platform_.devices.size();
}
int matches = 0;
std::string afu_id;
std::string afu_id_expected = platform_.devices[0].afu_guid;
afu_id_expected.erase(std::remove(afu_id_expected.begin(),
afu_id_expected.end(), '-'),
afu_id_expected.end());
transform(afu_id_expected.begin(), afu_id_expected.end(),
afu_id_expected.begin(), ::tolower);
int i;
for (i = 0; i < GetNumFpgas(); i++) {
std::string cmd = "cat /sys/class/fpga*/*" + std::to_string(i) +
"/*port." + std::to_string(i) + "/afu_id > output.txt";
EXPECT_EQ(std::system(cmd.c_str()), 0);
std::ifstream file("output.txt");
EXPECT_TRUE(file.is_open());
EXPECT_TRUE(std::getline(file, afu_id));
file.close();
EXPECT_EQ(unlink("output.txt"), 0);
if (afu_id == afu_id_expected) {
matches++;
}
}
return matches;
}
void ExecuteCmd(std::string cmd, int &value) {
std::string line;
std::string command = cmd + " > output.txt";
EXPECT_EQ(std::system(command.c_str()), 0);
std::ifstream file("output.txt");
ASSERT_TRUE(file.is_open());
EXPECT_TRUE(std::getline(file, line));
file.close();
EXPECT_EQ(std::system("rm output.txt"), 0);
value = std::stoi(line);
}
fpga_properties filter_;
uint32_t num_matches_;
};
/**
* @test nullfilter
*
* @brief When the filter is null and the number of filters
* is zero, the function returns all matches.
*/
TEST_P(enum_c_p, nullfilter) {
EXPECT_EQ(
xfpga_fpgaEnumerate(nullptr, 0, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas() * 2);
}
/**
* @test nullfilter_neg
*
* @brief When the filter is null but the number of filters
* is greater than zero, the function returns
* FPGA_INVALID_PARAM.
*/
TEST_P(enum_c_p, nullfilter_neg) {
EXPECT_EQ(
xfpga_fpgaEnumerate(nullptr, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_INVALID_PARAM);
}
/**
* @test nullmatches
*
* @brief When the number of matches parameter is null,
* the function returns FPGA_INVALID_PARAM.
*/
TEST_P(enum_c_p, nullmatches) {
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), NULL),
FPGA_INVALID_PARAM);
}
/**
* @test nulltokens
*
* @brief When the tokens parameter is null, the function
* returns FPGA_INVALID_PARAM.
*/
TEST_P(enum_c_p, nulltokens) {
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 0, NULL, tokens_.size(), &num_matches_),
FPGA_INVALID_PARAM);
}
/**
* @test object_type_accel
*
* @brief When the filter object type is set to
* FPGA_ACCELERATOR, the function returns the
* correct number of accelerator matches.
*/
TEST_P(enum_c_p, object_type_accel) {
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas());
}
/**
* @test object_type_dev
*
* @brief When the filter object type is set to FPGA_DEVICE,
* the function returns the correct number of device
* matches.
*/
TEST_P(enum_c_p, object_type_dev) {
EXPECT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas());
}
/**
* @test parent
*
* @brief When the filter parent is set to a previously found
* FPGA_DEVICE, the function returns the child resource.
*/
TEST_P(enum_c_p, parent) {
EXPECT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas());
ASSERT_EQ(fpgaClearProperties(filter_), FPGA_OK);
fpga_token token = nullptr;
EXPECT_EQ(fpgaPropertiesSetParent(filter_, tokens_[0]), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, &token, 1, &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 1);
ASSERT_NE(token, nullptr);
EXPECT_EQ(xfpga_fpgaDestroyToken(&token), FPGA_OK);
}
/**
* @test parent_neg
*
* @brief When the filter passed to fpgaEnumerate has a valid
* parent field set, but that parent is not found to be the
* parent of any device, fpgaEnumerate returns zero matches.
*/
TEST_P(enum_c_p, parent_neg) {
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK);
EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), 1, &num_matches_),
FPGA_OK);
EXPECT_GT(num_matches_, 0);
EXPECT_EQ(fpgaPropertiesSetParent(filter_, tokens_[0]), FPGA_OK);
EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, NULL, 0, &num_matches_), FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test segment
*
* @brief When the filter segment is set and it is valid,
* the function returns the number of resources that
* match that segment.
*/
TEST_P(enum_c_p, segment) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetSegment(filter_, device.segment), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas() * 2);
}
/**
* @test segment_neg
*
* @brief When the filter segment is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, segment_neg) {
ASSERT_EQ(fpgaPropertiesSetSegment(filter_, invalid_device_.segment), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test bus
*
* @brief When the filter bus is set and it is valid, the
* function returns the number of resources that
* match that bus.
*/
TEST_P(enum_c_p, bus) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetBus(filter_, device.bus), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 2);
}
/**
* @test bus_neg
*
* @brief When the filter bus is set and it is invalid,
* the function returns zero matches
*/
TEST_P(enum_c_p, bus_neg) {
ASSERT_EQ(fpgaPropertiesSetBus(filter_, invalid_device_.bus), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test device
*
* @brief When the filter device is set and it is valid,
* the function returns the number of resources that
* match that device.
*/
TEST_P(enum_c_p, device) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetDevice(filter_, device.device), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas() * 2);
}
/**
* @test device_neg
*
* @brief When the filter device is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, device_neg) {
ASSERT_EQ(fpgaPropertiesSetDevice(filter_, invalid_device_.device), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test function
*
* @brief When the filter function is set and it is valid,
* the function returns the number of resources that
* match that function.
*/
TEST_P(enum_c_p, function) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetFunction(filter_, device.function), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas() * 2 - device.num_vfs);
DestroyTokens();
for (int i = 0; i < device.num_vfs; ++i) {
num_matches_ = 0;
ASSERT_EQ(fpgaPropertiesSetFunction(filter_, device.function+i), FPGA_OK);
EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(),
&num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 1);
DestroyTokens();
}
}
/**
* @test function_neg
*
* @brief When the filter function is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, function_neg) {
ASSERT_EQ(fpgaPropertiesSetFunction(filter_, invalid_device_.function),
FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test socket_id_neg
*
* @brief When the filter socket_id is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, socket_id_neg) {
ASSERT_EQ(fpgaPropertiesSetSocketID(filter_, invalid_device_.socket_id),
FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test vendor_id
*
* @brief When the filter vendor_id is set and it is valid,
* the function returns the number of resources that
* match that vendor_id.
*/
TEST_P(enum_c_p, vendor_id) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetVendorID(filter_, device.vendor_id), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas() * 2);
}
/**
* @test vendor_id_neg
*
* @brief When the filter vendor_id is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, vendor_id_neg) {
ASSERT_EQ(fpgaPropertiesSetVendorID(filter_, invalid_device_.vendor_id),
FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test device_id
*
* @brief When the filter device_id is set and it is valid,
* the function returns the number of resources that
* match that device_id.
*/
TEST_P(enum_c_p, device_id) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetDeviceID(filter_, device.device_id), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, platform_.devices.size() * 2 - device.num_vfs);
DestroyTokens();
for (int i = 0; i < device.num_vfs; ++i) {
num_matches_ = 0;
ASSERT_EQ(fpgaPropertiesSetDeviceID(filter_, device.device_id+i), FPGA_OK);
EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(),
&num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 1);
DestroyTokens();
}
}
/**
* @test device_id_neg
*
* @brief When the filter device_id is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, device_id_neg) {
ASSERT_EQ(fpgaPropertiesSetDeviceID(filter_, invalid_device_.device_id),
FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test object_id_fme
*
* @brief When the filter object_id for fme is set and it is
* valid, the function returns the number of resources
* that match that object_id.
*/
TEST_P(enum_c_p, object_id_fme) {
ASSERT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
ASSERT_GT(num_matches_, 0);
fpga_properties prop;
uint64_t object_id;
EXPECT_EQ(xfpga_fpgaGetProperties(tokens_[0], &prop), FPGA_OK);
EXPECT_EQ(fpgaPropertiesGetObjectID(prop, &object_id), FPGA_OK);
EXPECT_EQ(fpgaDestroyProperties(&prop), FPGA_OK);
DestroyTokens();
ASSERT_EQ(fpgaPropertiesSetObjectID(filter_, object_id), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 1);
}
/**
* @test object_id_fme_neg
*
* @brief When the filter object_id for fme is set and it is
* invalid, the function returns zero matches.
*/
TEST_P(enum_c_p, object_id_fme_neg) {
ASSERT_EQ(fpgaPropertiesSetObjectID(filter_, invalid_device_.fme_object_id),
FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test object_id_port
*
* @brief When the filter port_id for port is set and it is
* valid, the function returns the number of resources
* that match that port_id.
*/
TEST_P(enum_c_p, object_id_port) {
ASSERT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
ASSERT_GT(num_matches_, 0);
fpga_properties prop;
uint64_t object_id;
EXPECT_EQ(xfpga_fpgaGetProperties(tokens_[0], &prop), FPGA_OK);
EXPECT_EQ(fpgaPropertiesGetObjectID(prop, &object_id), FPGA_OK);
EXPECT_EQ(fpgaDestroyProperties(&prop), FPGA_OK);
DestroyTokens();
EXPECT_EQ(fpgaPropertiesSetObjectID(filter_, object_id), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 1);
}
/**
* @test object_id_port_neg
*
* @brief When the filter object_id for port is set and it is
* invalid, the function returns zero matches.
*/
TEST_P(enum_c_p, object_id_port_neg) {
ASSERT_EQ(fpgaPropertiesSetObjectID(filter_, invalid_device_.port_object_id),
FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test num_errors_fme_neg
*
* @brief When the filter num_errors for fme is set and it is
* invalid, the function returns zero matches.
*/
TEST_P(enum_c_p, num_errors_fme_neg) {
ASSERT_EQ(fpgaPropertiesSetNumErrors(filter_, invalid_device_.fme_num_errors),
FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test num_errors_port_neg
*
* @brief When the filter num_errors for port is set and it is
* invalid, the function returns zero matches.
*/
TEST_P(enum_c_p, num_errors_port_neg) {
ASSERT_EQ(fpgaPropertiesSetNumErrors(filter_, invalid_device_.port_num_errors),
FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test guid_fme
*
* @brief When the filter guid for fme is set and it is
* valid, the function returns the number of resources
* that match that guid for fme.
*/
TEST_P(enum_c_p, guid_fme) {
auto device = platform_.devices[0];
fpga_guid fme_guid;
ASSERT_EQ(uuid_parse(device.fme_guid, fme_guid), 0);
ASSERT_EQ(fpgaPropertiesSetGUID(filter_, fme_guid), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, platform_.devices.size());
}
/**
* @test guid_fme_neg
*
* @brief When the filter guid for fme is set and it is
* invalid, the function returns zero matches.
*/
TEST_P(enum_c_p, guid_fme_neg) {
fpga_guid invalid_guid;
ASSERT_EQ(uuid_parse(invalid_device_.fme_guid, invalid_guid), 0);
ASSERT_EQ(fpgaPropertiesSetGUID(filter_, invalid_guid), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test guid_port
*
* @brief When the filter guid for port is set and it is
* valid, the function returns the number of resources
* that match that guid for port.
*/
TEST_P(enum_c_p, guid_port) {
auto device = platform_.devices[0];
fpga_guid afu_guid;
ASSERT_EQ(uuid_parse(device.afu_guid, afu_guid), 0);
ASSERT_EQ(fpgaPropertiesSetGUID(filter_, afu_guid), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetMatchedGuidFpgas());
}
/**
* @test guid_port_neg
*
* @brief When the filter guid for port is set and it is
* invalid, the function returns zero matches.
*/
TEST_P(enum_c_p, guid_port_neg) {
fpga_guid invalid_guid;
ASSERT_EQ(uuid_parse(invalid_device_.afu_guid, invalid_guid), 0);
ASSERT_EQ(fpgaPropertiesSetGUID(filter_, invalid_guid), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test clone_token
*
* @brief Given a valid source token and a valid destination,
* xfpga_fpgaCloneToken() returns FPGA_OK.
*/
TEST_P(enum_c_p, clone_token) {
EXPECT_EQ(
xfpga_fpgaEnumerate(nullptr, 0, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_GT(num_matches_, 0);
fpga_token src = tokens_[0];
fpga_token dst;
EXPECT_EQ(xfpga_fpgaCloneToken(src, &dst), FPGA_OK);
EXPECT_EQ(xfpga_fpgaDestroyToken(&dst), FPGA_OK);
}
/**
* @test clone_token_neg
*
* @brief Given an invalid source token or an invalid destination,
* xfpga_fpgaCloneToken() returns FPGA_INVALID_PARAM
*/
TEST_P(enum_c_p, clone_token_neg) {
EXPECT_EQ(
xfpga_fpgaEnumerate(nullptr, 0, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_GT(num_matches_, 0);
fpga_token src = tokens_[0];
fpga_token dst;
EXPECT_EQ(xfpga_fpgaCloneToken(NULL, &dst), FPGA_INVALID_PARAM);
EXPECT_EQ(xfpga_fpgaCloneToken(&src, NULL), FPGA_INVALID_PARAM);
}
/**
* @test destroy_token
*
* @brief Given a valid token, xfpga_fpgaDestroyToken() returns
* FPGA_OK.
*/
TEST_P(enum_c_p, destroy_token) {
fpga_token token;
ASSERT_EQ(xfpga_fpgaEnumerate(nullptr, 0, &token, 1, &num_matches_),
FPGA_OK);
ASSERT_GT(num_matches_, 0);
EXPECT_EQ(xfpga_fpgaDestroyToken(&token), FPGA_OK);
}
/**
* @test destroy_token_neg
*
* @brief Given a null or invalid token, xfpga_fpgaDestroyToken()
* returns FPGA_INVALID_PARAM.
*/
TEST_P(enum_c_p, destroy_token_neg) {
EXPECT_EQ(xfpga_fpgaDestroyToken(nullptr), FPGA_INVALID_PARAM);
_fpga_token *dummy = new _fpga_token;
memset(dummy, 0, sizeof(*dummy));
EXPECT_EQ(xfpga_fpgaDestroyToken((fpga_token *)&dummy), FPGA_INVALID_PARAM);
delete dummy;
}
/**
* @test num_slots
*
* @brief When the filter num_slots is set and it is valid,
* the function returns the number of resources that
* match that number of slots.
*/
TEST_P(enum_c_p, num_slots) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetNumSlots(filter_, device.num_slots), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas());
}
/**
* @test num_slots_neg
*
* @brief When the filter num_slots is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, num_slots_neg) {
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetNumSlots(filter_, invalid_device_.num_slots), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test bbs_id
*
* @brief When the filter bbs_id is set and it is valid,
* the function returns the number of resources that
* match that bbs_id.
*/
TEST_P(enum_c_p, bbs_id) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetBBSID(filter_, device.bbs_id), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, platform_.devices.size());
}
/**
* @test bbs_id_neg
*
* @brief When the filter bbs_id is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, bbs_id_neg) {
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetBBSID(filter_, invalid_device_.bbs_id), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test bbs_version
*
* @brief When the filter bbs_version is set and it is valid,
* the function returns the number of resources that
* match that bbs_version.
*/
TEST_P(enum_c_p, bbs_version) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetBBSVersion(filter_, device.bbs_version), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, platform_.devices.size());
}
/**
* @test bbs_version_neg
*
* @brief When the filter bbs_version is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, bbs_version_neg) {
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetBBSVersion(filter_, invalid_device_.bbs_version), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test accel_state
*
* @brief When the filter accelerator state is set and it is
* valid, the function returns the number of resources
* that match that accelerator state.
*/
TEST_P(enum_c_p, accel_state) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetAcceleratorState(filter_, device.state), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas());
}
/**
* @test accel_state_neg
*
* @brief When the filter accelerator state is set and it is
* invalid, the function returns zero matches.
*/
TEST_P(enum_c_p, state_neg) {
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetAcceleratorState(filter_, invalid_device_.state), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test num_mmio
*
* @brief When the filter num MMIO is set and it is valid,
* the function returns the number of resources that
* match that num MMIO.
*/
TEST_P(enum_c_p, num_mmio) {
auto device = platform_.devices[0];
system_->register_ioctl_handler(DFL_FPGA_PORT_GET_INFO, dfl_port_info);
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetNumMMIO(filter_, device.num_mmio), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas());
}
/**
* @test num_mmio_neg
*
* @brief When the filter num MMIO is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, num_mmio_neg) {
system_->register_ioctl_handler(DFL_FPGA_PORT_GET_INFO, dfl_port_info);
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetNumMMIO(filter_, invalid_device_.num_mmio), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test num_interrupts
*
* @brief When the filter num interrupts is set and it is valid,
* the function returns the number of resources that
* match that num interrupts.
*/
TEST_P(enum_c_p, num_interrupts) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetNumInterrupts(filter_, device.num_interrupts), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas());
}
/**
* @test num_interrupts_neg
*
* @brief When the filter num interrupts is set and it is invalid,
* the function returns zero matches.
*/
TEST_P(enum_c_p, num_interrupts_neg) {
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetNumInterrupts(filter_, invalid_device_.num_interrupts), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
}
/**
* @test num_filter_neg
*
* @brief When the num_filter parameter to fpgaEnumerate is zero,
* but the filter parameter is non-NULL, the function
* returns FPGA_INVALID_PARAM.
*/
TEST_P(enum_c_p, num_filter_neg) {
EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 0, tokens_.data(), 0, &num_matches_),
FPGA_INVALID_PARAM);
}
/**
* @test max_tokens
*
* @brief fpgaEnumerate honors the input max_tokens value by
* limiting the number of output entries written to the
* memory at match, even though more may exist.
*/
TEST_P(enum_c_p, max_tokens) {
uint32_t max_tokens = 1;
EXPECT_EQ(xfpga_fpgaEnumerate(NULL, 0, tokens_.data(), max_tokens, &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas() * 2);
EXPECT_NE(tokens_[0], nullptr);
EXPECT_EQ(tokens_[1], nullptr);
}
/**
* @test filter
*
* @brief fpgaEnumerate honors a "don't care" properties filter by
* returning all available tokens.
*/
TEST_P(enum_c_p, filter) {
EXPECT_EQ(FPGA_OK, xfpga_fpgaEnumerate(&filter_, 1, NULL, 0, &num_matches_));
EXPECT_EQ(num_matches_, GetNumFpgas() * 2);
}
/**
* @test get_guid
*
* @brief Given I have a system with at least one FPGA And I
* enumerate with a filter of objtype of FPGA_DEVICE When I
* get properties from the resulting token And I query the
* GUID from the properties Then the GUID is returned and
* the result is FPGA_OK.
*
*/
TEST_P(enum_c_p, get_guid) {
fpga_properties prop;
fpga_guid guid;
fpga_properties filterp = NULL;
ASSERT_EQ(xfpga_fpgaGetProperties(NULL, &filterp), FPGA_OK);
EXPECT_EQ(fpgaPropertiesSetObjectType(filterp, FPGA_DEVICE), FPGA_OK);
EXPECT_EQ(xfpga_fpgaEnumerate(&filterp, 1, tokens_.data(), 1, &num_matches_),
FPGA_OK);
EXPECT_GT(num_matches_, 0);
EXPECT_EQ(fpgaDestroyProperties(&filterp), FPGA_OK);
ASSERT_EQ(xfpga_fpgaGetProperties(tokens_[0], &prop), FPGA_OK);
EXPECT_EQ(fpgaPropertiesGetGUID(prop, &guid), FPGA_OK);
EXPECT_EQ(fpgaDestroyProperties(&prop), FPGA_OK);
}
INSTANTIATE_TEST_CASE_P(enum_c, enum_c_p,
::testing::ValuesIn(test_platform::platforms({ "dfl-n3000","dfl-d5005" })));
class enum_err_c_p : public enum_c_p {};
/**
* @test num_errors_fme
*
* @brief When the filter num_errors for fme is set and it is
* valid, the function returns the number of resources
* that match that number of errors for fme.
*/
TEST_P(enum_err_c_p, num_errors_fme) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE),
FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetNumErrors(filter_, device.fme_num_errors),
FPGA_OK);
EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(),
&num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas());
}
/**
* @test num_errors_port
*
* @brief When the filter num_errors for port is set and it is
* valid, the function returns the number of resources
* that match that number of errors for port.
*/
TEST_P(enum_err_c_p, num_errors_port) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR),
FPGA_OK);
ASSERT_EQ(fpgaPropertiesSetNumErrors(filter_, device.port_num_errors),
FPGA_OK);
EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(),
&num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumFpgas());
}
INSTANTIATE_TEST_CASE_P(enum_c, enum_err_c_p,
::testing::ValuesIn(test_platform::platforms({ "dfl-n3000","dfl-d5005" })));
class enum_socket_c_p : public enum_c_p {};
/**
* @test socket_id
*
* @brief When the filter socket_id is set and it is valid,
* the function returns the number of resources that
* match that socket_id.
*/
TEST_P(enum_socket_c_p, socket_id) {
auto device = platform_.devices[0];
ASSERT_EQ(fpgaPropertiesSetSocketID(filter_, device.socket_id), FPGA_OK);
EXPECT_EQ(
xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, GetNumMatchedFpga() * 2);
}
INSTANTIATE_TEST_CASE_P(enum_c, enum_socket_c_p,
::testing::ValuesIn(test_platform::platforms({ "dfl-n3000","dfl-d5005" })));
class enum_mock_only : public enum_c_p {};
/**
* @test remove_port
*
* @brief Given I have a system with at least one FPGA And I
* enumerate with a filter of objtype of FPGA_ACCELERATOR
* and I get one token for that accelerator
* When I remove the port device from the system
* And I enumerate again with the same filter
* Then I get zero tokens as the result.
*
*/
TEST_P(enum_mock_only, remove_port) {
fpga_properties filterp = NULL;
ASSERT_EQ(xfpga_fpgaGetProperties(NULL, &filterp), FPGA_OK);
EXPECT_EQ(fpgaPropertiesSetObjectType(filterp, FPGA_ACCELERATOR), FPGA_OK);
EXPECT_EQ(xfpga_fpgaEnumerate(&filterp, 1, tokens_.data(), 1, &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 1);
const char *sysfs_port = "/sys/class/fpga_region/region0/dfl-port.0";
EXPECT_EQ(system_->remove_sysfs_dir(sysfs_port), 0)
<< "error removing dfl-port.0: " << strerror(errno);
EXPECT_EQ(xfpga_fpgaEnumerate(&filterp, 1, tokens_.data(), 1, &num_matches_),
FPGA_OK);
EXPECT_EQ(num_matches_, 0);
EXPECT_EQ(fpgaDestroyProperties(&filterp), FPGA_OK);
}
INSTANTIATE_TEST_CASE_P(enum_c, enum_mock_only,
::testing::ValuesIn(test_platform::mock_platforms({ "dfl-n3000","dfl-d5005" })));
| 30.928693 | 107 | 0.67555 | rchriste1 |
3e3965470d3099d8c31ef370c8530da7722059d6 | 169 | cxx | C++ | StRoot/StJetMaker/tracks/StjTrackCutDca.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StJetMaker/tracks/StjTrackCutDca.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StJetMaker/tracks/StjTrackCutDca.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | // $Id: StjTrackCutDca.cxx,v 1.1 2008/11/27 07:09:32 tai Exp $
// Copyright (C) 2008 Tai Sakuma <sakuma@bnl.gov>
#include "StjTrackCutDca.h"
ClassImp(StjTrackCutDca)
| 24.142857 | 62 | 0.715976 | xiaohaijin |
3e3bbd7224a2358e0f6f532e04d84d981b361cc7 | 1,170 | cpp | C++ | booth.cpp | PRASAD-DANGARE/CPP | bf5ba5f87a229d88152fef80cb6a4d73bf578815 | [
"MIT"
] | null | null | null | booth.cpp | PRASAD-DANGARE/CPP | bf5ba5f87a229d88152fef80cb6a4d73bf578815 | [
"MIT"
] | null | null | null | booth.cpp | PRASAD-DANGARE/CPP | bf5ba5f87a229d88152fef80cb6a4d73bf578815 | [
"MIT"
] | null | null | null | /*
Description : Ticket Selling Booth
Function Date : 21 Nov 2020
Function Author : Prasad Dangare
Input : String,Integer
*/
#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
class ticketbooth
{
unsigned int no_people;
double totcash;
public:
ticketbooth()
{
no_people = 0;
totcash = 0.0;
}
void ticket()
{
no_people++;
totcash += 5;
}
void visited()
{
no_people++;
}
void display()
{
cout << "Total Number Of People " << no_people << endl
<<"Total Amount " << totcash << endl;
}
};
int main()
{
ticketbooth booth1;
int ch;
cout << "\n Press 1 For Visited " << endl
<< "\n Press 2 For Visited And Bought Ticket " << endl;
do
{
cout << "\n 1.Visited " << "\n";
cout << "2.Visited And Bought Ticket " << "\n";
cout << "3.Display" << "\n";
cout << "4.Exit" << "\n";
cin >> ch;
switch(ch)
{
case 1:booth1.visited();
break;
case 2:booth1.ticket();
break;
case 3:booth1.display();
break;
case 4:exit(0);
}
}while(ch<=4);
return 0;
} | 16.478873 | 59 | 0.528205 | PRASAD-DANGARE |
3e3d18964d0cbea8c9ca9770575265e7b935b368 | 9,084 | cpp | C++ | Project/Dev_class11_handout/Motor2D/j1Pathfinding.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | Project/Dev_class11_handout/Motor2D/j1Pathfinding.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | Project/Dev_class11_handout/Motor2D/j1Pathfinding.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | #include "j1Pathfinding.h"
#include "j1App.h"
#include "j1Textures.h"
#include "p2Log.h"
#include"Character.h"
#include"j1Map.h"
#include"j1Enemy.h"
#include "Brofiler/Brofiler.h"
///class Pathfinding ------------------
// Constructors =======================
j1Pathfinding::j1Pathfinding()
{
}
// Destructors ========================
j1Pathfinding::~j1Pathfinding()
{
}
//Game Loop ===========================
bool j1Pathfinding::Start()
{
//Generate map cluster abstraction
j1Timer timer;
//cluster_abstraction = new ClusterAbstraction(App->map, 10);
LOG("Cluster abstraction generated in %.3f", timer.ReadSec());
//Load debug tiles trexture
//path_texture = App->tex->Load("maps/path_tex.png");
return true;
}
bool j1Pathfinding::CleanUp()
{
RELEASE_ARRAY(path_nodes);
return true;
}
void j1Pathfinding::SetMap(uint width, uint height)
{
this->width = width;
this->height = height;
map_min_x = 0;
map_min_y = 0;
map_max_x = width;
map_max_y = height;
RELEASE_ARRAY(path_nodes);
int size = width*height;
path_nodes = new PathNode[size];
}
void j1Pathfinding::SetMapLimits(int position_x, int position_y, int width, int height)
{
map_min_x = position_x;
map_min_y = position_y;
map_max_x = position_x + width;
map_max_y = position_y + height;
}
//Functionality =======================
//Methods used during the paths creation to work with map data
bool j1Pathfinding::IsWalkable(const iPoint & destination) const
{
bool ret = false;
uchar t = GetTileAt(destination);
if (t)
int x = 0;
return (t == NOT_COLISION_ID);
}
bool j1Pathfinding::CheckBoundaries(const iPoint & pos) const
{
return (pos.x >= map_min_x && pos.x < map_max_x && pos.y >= map_min_y && pos.y < map_max_y);
}
uchar j1Pathfinding::GetTileAt(const iPoint & pos) const
{
if (CheckBoundaries(pos))
return GetValueMap(pos.x, pos.y);
return NOT_COLISION_ID;
}
uchar j1Pathfinding::GetValueMap(int x, int y) const
{
//In future we will have to adapt because with this enemies only can be in logic 0
return App->map->V_Colision[0]->data[(y*width) + x];
}
PathNode* j1Pathfinding::GetPathNode(int x, int y)
{
return &path_nodes[(y*width) + x];
}
std::vector<iPoint>* j1Pathfinding::SimpleAstar(const iPoint& origin, const iPoint& destination)
{
BROFILER_CATEGORY("A star", Profiler::Color::LightYellow);
int size = width*height;
std::fill(path_nodes, path_nodes + size, PathNode(-1, -1, iPoint(-1, -1), nullptr));
iPoint dest_point(destination.x, destination.y);
int ret = -1;
//iPoint mouse_position = App->map->FixPointMap(destination.x, destination.y);
/*iPoint map_origin = App->map->WorldToMap(origin.x, origin.y);
iPoint map_goal = App->map->WorldToMap(dest_point.x, dest_point.y);*/
/* if (map_origin == map_goal)
{
std::vector<iPoint>* path = new std::vector<iPoint>;
path->push_back(mouse_position);
return path;
}*/
if (IsWalkable(origin) && IsWalkable(dest_point))
{
ret = 1;
OpenList open;
PathNode* firstNode = GetPathNode(origin.x, origin.y);
firstNode->SetPosition(origin);
firstNode->g = 0;
firstNode->h = origin.DistanceManhattan(dest_point);
open.queue.push(firstNode);
PathNode* current = nullptr;
while (open.queue.size() != 0)
{
current = open.queue.top();
open.queue.top()->on_close = true;
open.queue.pop();
if (current->pos == dest_point)
{
std::vector<iPoint>* path = new std::vector<iPoint>;
last_path.clear();
path->push_back(dest_point);
iPoint mouse_cell = App->map->WorldToMap(dest_point.x, dest_point.y);
if (mouse_cell == current->pos)
current = GetPathNode(current->parent->pos.x, current->parent->pos.y);
for (; current->parent != nullptr; current = GetPathNode(current->parent->pos.x, current->parent->pos.y))
{
last_path.push_back(current->pos);
path->push_back({ current->pos.x, current->pos.y });
}
last_path.push_back(current->pos);
return path;
}
else
{
PathList neightbords;
current->FindWalkableAdjacents(&neightbords);
for (std::list<PathNode*>::iterator item = neightbords.list.begin(); item != neightbords.list.end(); item++) {
PathNode* temp = item._Mynode()->_Myval;
if (temp->on_close == true)
{
continue;
}
else if (temp->on_open == true)
{
int last_g_value = (int)temp->g;
temp->CalculateF(dest_point);
if (last_g_value <temp->g)
{
temp->parent = GetPathNode(current->pos.x, current->pos.y);
}
else {
temp->g = (float)last_g_value;
}
}
else
{
temp->on_open = true;
temp->CalculateF(dest_point);
open.queue.push(temp);
}
}
neightbords.list.clear();
}
}
}
return nullptr;
}
/// -----------------------------------
/// Struct PathNode -------------------
//Constructors ==============
PathNode::PathNode()
{
}
PathNode::PathNode(int g, int h, const iPoint & pos, const PathNode * parent) : g((float)g), h(h), pos(pos), parent(parent), on_close(false), on_open(false)
{
int x = 0;
}
PathNode::PathNode(const PathNode & node) : g(node.g), h(node.h), pos(node.pos), parent(node.parent)
{
int x = 0;
}
//Functionality =============
uint PathNode::FindWalkableAdjacents(PathList* list_to_fill) const
{
iPoint cell(0,0);
uint before = list_to_fill->list.size();
bool northClose = false, southClose = false, eastClose = false, westClose = false;
// south
cell.create(pos.x, pos.y + 1);
if (App->pathfinding->IsWalkable(cell))
{
PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y);
if (node->pos != cell) {
node->parent = this;
node->pos = cell;
}
list_to_fill->list.push_back(node);
}
else
{
southClose = true;
}
// north
cell.create(pos.x, pos.y - 1);
if (App->pathfinding->IsWalkable(cell))
{
PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y);
if (node->pos != cell) {
node->parent = this;
node->pos = cell;
}
list_to_fill->list.push_back(node);
}
else
{
northClose = true;
}
// east
cell.create(pos.x + 1, pos.y);
if (App->pathfinding->IsWalkable(cell))
{
PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y);
if (node->pos != cell) {
node->parent = this;
node->pos = cell;
}
list_to_fill->list.push_back(node);
}
else
{
eastClose = true;
}
// west
cell.create(pos.x - 1, pos.y);
if (App->pathfinding->IsWalkable(cell))
{
PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y);
if (node->pos != cell) {
node->parent = this;
node->pos = cell;
}
list_to_fill->list.push_back(node);
}
else
{
westClose = true;
}
return list_to_fill->list.size();
}
float PathNode::Score() const
{
return g + h;
}
int PathNode::CalculateF(const iPoint & destination)
{
g = parent->g + parent->pos.DistanceManhattan(pos);
h = pos.DistanceManhattan(destination) * 10;
return (int)g + h;
}
void PathNode::SetPosition(const iPoint & value)
{
pos = value;
}
//Operators =================
bool PathNode::operator==(const PathNode & node) const
{
return pos == node.pos;
}
bool PathNode::operator!=(const PathNode & node) const
{
return !operator==(node);
}
/// -----------------------------------
///Struct PathList --------------------
//Functionality =============
/*
std::list<PathNode>::iterator PathList::Find(const iPoint & point)
{
std::list<PathNode*>::iterator item = list.begin();
while (item != list.end())
{
if (item->pos == point) {
return item;
}
++item;
}
}
PathNode* PathList::GetNodeLowestScore() const
{
PathNode* ret = nullptr;
std::list<PathNode>::const_reverse_iterator item = list.crbegin();
float min = 65535;
while (item != list.crend())
{
if (item->Score() < min)
{
min = item->Score();
ret = &item.base()._Ptr->_Prev->_Myval;
}
++item;
}
return ret;
}*/
void j1Pathfinding::Move(Enemy * enemy, Character* player)
{
if (enemy->green_enemy_path.size()) {
static int i = 1;
int temp = enemy->green_enemy_path[enemy->green_enemy_path.size() - i].x;
int temp2 = enemy->green_enemy_path[enemy->green_enemy_path.size() - i].y;
int x = 0;
int y = 0;
x = x + (enemy->green_enemy_path[enemy->green_enemy_path.size()-i].x - enemy->tile_pos.x);
y = y + (enemy->green_enemy_path[enemy->green_enemy_path.size()- i].y - enemy->tile_pos.y);
/*
if (last_path.size() > 1) {
x = x + (last_path[i + 1].x - enemy->array_pos.x);
y = y + (last_path[i + 1].y - enemy->array_pos.y);
}*/
//enemy->actual_event = move;
//Change this
if (x >= 1) { x = 1; enemy->Enemy_Orientation = OrientationEnemy::right_enemy; }
if (x <= -1) { x = -1; enemy->Enemy_Orientation = OrientationEnemy::left_enemy; }
if (y >= 1) { y = 1; enemy->Enemy_Orientation = OrientationEnemy::down_enemy; }
if (y <= -1) { y = -1; enemy->Enemy_Orientation = OrientationEnemy::up_enemy; }
enemy->pos.x += x;
enemy->pos.y += y;
if (enemy->tile_pos == enemy->green_enemy_path[enemy->green_enemy_path.size()-i]) {
i++;
}
if (i == enemy->green_enemy_path.size() || enemy->tile_pos == player->tilepos) {
i = 0;
enemy->green_enemy_path.clear();
}
}
} | 22.597015 | 156 | 0.637274 | Guille1406 |
3e3d25562e2f85d6cd6a7bb75ef4bfdbe6595dbc | 422 | hpp | C++ | src/core/include/ngraph/op/mvn.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/core/include/ngraph/op/mvn.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/core/include/ngraph/op/mvn.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "ngraph/node.hpp"
#include "ngraph/op/op.hpp"
#include "openvino/op/mvn.hpp"
namespace ngraph {
namespace op {
namespace v0 {
using ov::op::v0::MVN;
} // namespace v0
using v0::MVN;
using ov::op::MVNEpsMode;
namespace v6 {
using ov::op::v6::MVN;
} // namespace v6
} // namespace op
} // namespace ngraph
| 16.88 | 44 | 0.684834 | ryanloney |
3e4172dd872dd230eb7dd91de73f369b65cfffbd | 32,165 | cpp | C++ | reseq/AdapterStats.cpp | schmeing/ReSeq | 053b8d1af635bf0019dc818b3eb0825023abd037 | [
"MIT"
] | 29 | 2020-07-18T22:04:45.000Z | 2021-12-22T16:48:53.000Z | reseq/AdapterStats.cpp | schmeing/ReSeq | 053b8d1af635bf0019dc818b3eb0825023abd037 | [
"MIT"
] | 15 | 2020-08-03T18:10:44.000Z | 2021-12-03T12:52:16.000Z | reseq/AdapterStats.cpp | schmeing/ReSequenceR | 053b8d1af635bf0019dc818b3eb0825023abd037 | [
"MIT"
] | 2 | 2021-03-08T15:09:21.000Z | 2021-03-25T14:14:43.000Z | #include "AdapterStats.h"
using reseq::AdapterStats;
#include <algorithm>
using std::max;
using std::max_element;
using std::min;
using std::sort;
#include <array>
using std::array;
#include <cmath>
using std::ceil;
#include <fstream>
using std::ifstream;
using std::ofstream;
#include <iterator>
using std::distance;
#include <list>
using std::list;
//include <string>
using std::string;
//include <vector>
using std::vector;
#include <utility>
using std::pair;
#include "reportingUtils.hpp"
//include <seqan/bam_io.h>
using seqan::BamAlignmentRecord;
using seqan::CharString;
using seqan::Dna;
using seqan::Dna5;
using seqan::DnaString;
using seqan::Exception;
using seqan::reverseComplement;
using seqan::StringSet;
#include <seqan/seq_io.h>
using seqan::readRecords;
using seqan::SeqFileIn;
#include "skewer/src/matrix.h"
//include "utilities.hpp"
using reseq::utilities::at;
using reseq::utilities::SetToMax;
inline reseq::uintSeqLen AdapterStats::GetStartPosOnReference(const BamAlignmentRecord &record){
uintSeqLen start_pos = record.beginPos;
if('S' == at(record.cigar, 0).operation){
if(at(record.cigar, 0).count < start_pos){
start_pos -= at(record.cigar, 0).count;
}
else{
start_pos = 0;
}
}
else if('H' == at(record.cigar, 0).operation){
if( 2 <= length(record.cigar) && 'S' == at(record.cigar, 1).operation){
if(at(record.cigar, 1).count < start_pos){
start_pos -= at(record.cigar, 1).count;
}
else{
start_pos = 0;
}
}
}
return start_pos;
}
reseq::uintReadLen AdapterStats::CountErrors(uintReadLen &last_error_pos, const BamAlignmentRecord &record, const Reference &reference){
uintReadLen num_errors(0), read_pos(0);
auto ref_pos = GetStartPosOnReference(record);
auto &ref_seq = reference.ReferenceSequence(record.rID);
for( const auto &cigar_element : record.cigar ){
switch( cigar_element.operation ){
case 'M':
case '=':
case 'X':
case 'S': // Treat soft-clipping as match, so that bwa and bowtie2 behave the same
for(auto i=cigar_element.count; i--; ){
if( ref_pos >= length(ref_seq) || at(ref_seq, ref_pos++) != at(record.seq, read_pos++) ){
if( !hasFlagRC(record) || !num_errors ){ // In case of a normal read always overwrite errors to get the last; in case of a reversed read stop after the first
last_error_pos = read_pos - 1;
}
++num_errors;
}
}
break;
case 'N':
case 'D':
// Deletions can be attributed to the base before or after the deletion, choose the one resulting in the lowest last_error_pos in the end (so shortest adapter required length)
if( hasFlagRC(record) ){
if( !num_errors ){
last_error_pos = read_pos;
}
}
else{
last_error_pos = read_pos-1;
}
num_errors += cigar_element.count;
ref_pos += cigar_element.count;
break;
case 'I':
// Insertions can be attributed to the first or last base of the insertion, choose the one resulting in the lowest last_error_pos in the end (so shortest adapter required length)
if( hasFlagRC(record) ){
if( !num_errors ){
last_error_pos = read_pos;
}
}
else{
last_error_pos = read_pos+cigar_element.count-1;
}
num_errors += cigar_element.count;
read_pos += cigar_element.count;
break;
default:
printErr << "Unknown cigar operation: " << cigar_element.operation << std::endl;
}
}
// Reverse position for normal reads to get them counted from the end of the read
if( !hasFlagRC(record) ){
last_error_pos = length(record.seq) - 1 - last_error_pos;
}
return num_errors;
}
bool AdapterStats::VerifyInsert(const CharString &read1, const CharString &read2, intSeqShift pos1, intSeqShift pos2){
if( 1 > pos1 || 1 > pos2){
return true;
}
if( pos1 == pos2 ){
uintReadLen matches(0), i2(0);
for(uintReadLen i1=pos1; i1--; ){
switch(at(read1, i1)){
case 'A':
if( 'T' == at(read2, i2) ){
++matches;
}
break;
case 'C':
if( 'G' == at(read2, i2) ){
++matches;
}
break;
case 'G':
if( 'C' == at(read2, i2) ){
++matches;
}
break;
case 'T':
if( 'A' == at(read2, i2) ){
++matches;
}
break;
}
++i2;
}
if(matches > pos1*95/100){
return true;
}
}
return false;
}
bool AdapterStats::AdaptersAmbigous(const seqan::DnaString &adaper1, const seqan::DnaString &adaper2, uintReadLen max_length){
auto compare_until = max( static_cast<uintReadLen>(max(length(adaper1), length(adaper2))), max_length );
uintReadLen num_diff = 0;
for( auto pos=compare_until; pos--; ){
if(at(adaper1, pos) != at(adaper2, pos)){
++num_diff;
}
}
return num_diff < 2+compare_until/10;
}
AdapterStats::AdapterStats(){
// Clear adapter_overrun_bases_
for( auto i = tmp_overrun_bases_.size(); i--; ){
tmp_overrun_bases_.at(i) = 0;
}
}
bool AdapterStats::LoadAdapters(const char *adapter_file, const char *adapter_matrix){
StringSet<CharString> ids;
StringSet<DnaString> seqs;
printInfo << "Loading adapters from: " << adapter_file << std::endl;
printInfo << "Loading adapter combination matrix from: " << adapter_matrix << std::endl;
try{
SeqFileIn seq_file_in(adapter_file);
readRecords(ids, seqs, seq_file_in);
}
catch(const Exception &e){
printErr << "Could not load adapter sequences: " << e.what() << std::endl;
return false;
}
vector<string> matrix;
matrix.resize(length(seqs));
ifstream matrix_file;
matrix_file.open(adapter_matrix);
uintAdapterId nline=0;
while( length(seqs) > nline && matrix_file.good() ){
getline(matrix_file, matrix.at(nline++));
}
matrix_file.close();
// Check if matrix fits to adapter file
bool error = false;
if(length(seqs) != nline ){
printErr << "Matrix has less rows than adapters loaded from file." << std::endl;
error = true;
}
matrix_file.get(); // Test if file is at the end
if( !matrix_file.eof() ){
printErr << "Matrix has more rows than adapters loaded from file." << std::endl;
error = true;
}
for( ; nline--; ){
if( length(seqs) > matrix.at(nline).size() ){
printErr << "Matrix row " << nline << " has less columns than adapters loaded from file." << std::endl;
error = true;
}
else if( length(seqs) < matrix.at(nline).size() ){
printErr << "Matrix row " << nline << " has more columns than adapters loaded from file." << std::endl;
error = true;
}
for(auto nchar = matrix.at(nline).size(); nchar--; ){
if( '0' != matrix.at(nline).at(nchar) && '1' != matrix.at(nline).at(nchar)){
printErr << "Not allowed character '" << matrix.at(nline).at(nchar) << "' in matrix at line " << nline << ", position " << nchar << std::endl;
error = true;
}
}
}
if(error){
return false;
}
// Get adapters that are allowed for first or second
array<vector<pair<DnaString, uintAdapterId>>, 2> adapter_list;
for(uintTempSeq seg=2; seg--; ){
adapter_list.at(seg).reserve(length(seqs));
}
for( nline = length(seqs); nline--; ){
for(auto nchar = length(seqs); nchar--; ){
if( '1' == matrix.at(nline).at(nchar) ){
// If one adapter pair has this adaptor as first, add it to first and continue with the next adapter
adapter_list.at(0).push_back({at(seqs, nline),nline});
break;
}
}
}
for(auto nchar = length(seqs); nchar--; ){
for( nline = length(seqs); nline--; ){
if( '1' == matrix.at(nline).at(nchar) ){
adapter_list.at(1).push_back({at(seqs, nchar),nchar});
break;
}
}
}
for(uintTempSeq seg=2; seg--; ){
// Also add reverse complement of adapters (as the direction is different depending on the sequencing machine Hiseq2000 vs. 4000)
adapter_list.at(seg).reserve(adapter_list.at(seg).size()*2);
for( uintAdapterId i=adapter_list.at(seg).size(); i--;){
adapter_list.at(seg).push_back(adapter_list.at(seg).at(i));
reverseComplement(adapter_list.at(seg).back().first);
adapter_list.at(seg).back().second += length(ids);
}
// Sort adapters by sequence (necessary for SolveAmbiguities function later) and fill the class variables
sort(adapter_list.at(seg));
seqs_.at(seg).reserve(adapter_list.at(seg).size());
names_.at(seg).reserve(adapter_list.at(seg).size());
for( auto &adapter : adapter_list.at(seg) ){
seqs_.at(seg).push_back(adapter.first);
if(adapter.second < length(ids)){
names_.at(seg).push_back((string(toCString(at(ids, adapter.second)))+"_f").c_str());
}
else{
names_.at(seg).push_back((string(toCString(at(ids, adapter.second-length(ids))))+"_r").c_str());
}
}
}
// Fill adapter_combinations_ with the valid combinations of both adapters
combinations_.clear();
combinations_.resize(adapter_list.at(0).size(), vector<bool>(adapter_list.at(1).size(), true) ); // Set all combinations by default to valid
for( auto adapter1 = adapter_list.at(0).size(); adapter1--; ){
for( auto adapter2 = adapter_list.at(1).size(); adapter2--; ){
if('0' == matrix.at( adapter_list.at(0).at(adapter1).second%length(ids) ).at( adapter_list.at(1).at(adapter2).second%length(ids) )){
// Combination not valid
combinations_.at(adapter1).at(adapter2) = false;
}
}
}
return true;
}
void AdapterStats::PrepareAdapterPrediction(){
if(0 == combinations_.size()){
for(uintTempSeq template_segment=2; template_segment--; ){
adapter_kmers_.at(template_segment).Prepare();
adapter_start_kmers_.at(template_segment).resize(adapter_kmers_.at(template_segment).counts_.size(), 0);
}
}
}
void AdapterStats::ExtractAdapterPart(const seqan::BamAlignmentRecord &record){
if(0 == combinations_.size()){
if( hasFlagUnmapped(record) || hasFlagNextUnmapped(record) ){
auto adapter_start = adapter_kmers_.at(hasFlagLast(record)).CountSequenceForward(record.seq, 0);
if( adapter_start >= 0 ){
++adapter_start_kmers_.at(hasFlagLast(record)).at(adapter_start);
}
}
else if( hasFlagRC(record) ){
if(record.beginPos <= record.pNext && record.beginPos+length(record.seq) > record.pNext){
uintReadLen clipped(0);
if('S' == at(record.cigar, 0).operation){
clipped = at(record.cigar, 0).count;
}
else if('H' == at(record.cigar, 0).operation){
clipped = at(record.cigar, 0).count;
if('S' == at(record.cigar, 1).operation){
clipped += at(record.cigar, 1).count;
}
}
auto adapter_start = adapter_kmers_.at(hasFlagLast(record)).CountSequenceReverse(record.seq, clipped + record.pNext-record.beginPos);
if( adapter_start >= 0 ){
++adapter_start_kmers_.at(hasFlagLast(record)).at(adapter_start);
}
}
}
else{
if(record.beginPos >= record.pNext && record.beginPos < record.pNext+length(record.seq)){
uintReadLen clipped(0);
if('S' == at(record.cigar, length(record.cigar)-1).operation){
clipped = at(record.cigar, length(record.cigar)-1).count;
}
else if('H' == at(record.cigar, length(record.cigar)-1).operation){
clipped = at(record.cigar, length(record.cigar)-1).count;
if('S' == at(record.cigar, length(record.cigar)-2).operation){
clipped += at(record.cigar, length(record.cigar)-2).count;
}
}
auto adapter_start = adapter_kmers_.at(hasFlagLast(record)).CountSequenceForward(record.seq, length(record.seq) - max(clipped, static_cast<uintReadLen>(record.beginPos - record.pNext)));
if( adapter_start >= 0 ){
++adapter_start_kmers_.at(hasFlagLast(record)).at(adapter_start);
}
}
}
}
}
bool AdapterStats::PredictAdapters(){
if(0 == combinations_.size()){
std::vector<bool> use_kmer;
uintBaseCall max_extension, second_highest;
auto base = adapter_kmers_.at(0).counts_.size() >> 2;
uintReadLen adapter_ext_pos(0);
ofstream myfile;
if(kAdapterSearchInfoFile){
myfile.open(kAdapterSearchInfoFile);
myfile << "template_segment, tries_left, position, kmer, counts" << std::endl;
}
for(uintTempSeq template_segment=2; template_segment--; ){
// Find start of adapter
use_kmer.clear();
use_kmer.resize(adapter_kmers_.at(template_segment).counts_.size(), true);
use_kmer.at(0) = false; // Ignore all A's as possible adapter
Kmer<kKmerLength>::intType excluded_kmer;
for(uintBaseCall nuc=3; --nuc; ){
excluded_kmer = nuc;
for(auto i=kKmerLength-1; i--; ){
excluded_kmer <<= 2;
excluded_kmer += nuc;
}
use_kmer.at(excluded_kmer) = false; // Ignore all C's/G's as possible adapter
}
use_kmer.at( adapter_kmers_.at(template_segment).counts_.size()-1 ) = false; // Ignore all T's as possible adapter
DnaString adapter;
reserve(adapter, 50);
bool found_adapter = false;
uintNumFits tries = 100;
while(!found_adapter && tries--){
Kmer<kKmerLength>::intType max_kmer = 1;
while(!use_kmer.at(max_kmer)){
++max_kmer;
}
for(Kmer<kKmerLength>::intType kmer = max_kmer+1; kmer < adapter_start_kmers_.at(template_segment).size(); ++kmer ){
if( use_kmer.at(kmer) && adapter_start_kmers_.at(template_segment).at(kmer) > adapter_start_kmers_.at(template_segment).at(max_kmer) ){
max_kmer = kmer;
}
}
use_kmer.at(max_kmer) = false; // Prevent endless circle
auto kmer = max_kmer;
resize(adapter, kKmerLength);
for(uintReadLen pos=kKmerLength; pos--; ){
at(adapter, pos) = kmer%4;
kmer >>= 2;
}
if(kAdapterSearchInfoFile){
// Sort kmers to get top 100
std::vector<std::pair<uintNucCount, Kmer<kKmerLength>::intType>> sorted_kmers;
sorted_kmers.reserve(adapter_start_kmers_.size());
for(Kmer<kKmerLength>::intType kmer = 0; kmer < adapter_start_kmers_.at(template_segment).size(); ++kmer ){
sorted_kmers.emplace_back(adapter_start_kmers_.at(template_segment).at(kmer), kmer);
}
sort(sorted_kmers.begin(),sorted_kmers.end());
string kmer_nucs;
kmer_nucs.resize(kKmerLength);
for(auto sk = sorted_kmers.size(); sk-- > sorted_kmers.size()-100; ){
myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Start, ";
kmer = sorted_kmers.at(sk).second;
for(uintReadLen pos=kKmerLength; pos--; ){
kmer_nucs.at(pos) = static_cast<Dna>(kmer%4);
kmer >>= 2;
}
myfile << kmer_nucs << ", " << sorted_kmers.at(sk).first << std::endl;
}
}
// Restore start cut
kmer = max_kmer;
if(kAdapterSearchInfoFile){
adapter_ext_pos = 0;
}
while(true){
kmer >>= 2;
if(kAdapterSearchInfoFile){
myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << ++adapter_ext_pos << ", A";
for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){
myfile << at(adapter, pos);
}
myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer) << std::endl;
myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << adapter_ext_pos << ", C";
for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){
myfile << at(adapter, pos);
}
myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer+base) << std::endl;
myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << adapter_ext_pos << ", G";
for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){
myfile << at(adapter, pos);
}
myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer+2*base) << std::endl;
myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << adapter_ext_pos << ", T";
for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){
myfile << at(adapter, pos);
}
myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer+3*base) << std::endl;
}
if( adapter_kmers_.at(template_segment).counts_.at(kmer+3*base) > adapter_kmers_.at(template_segment).counts_.at(kmer+2*base) ){
max_extension = 3;
second_highest = 2;
}
else{
max_extension = 2;
second_highest = 3;
}
for(uintBaseCall ext=2; ext--; ){
if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext*base) > adapter_kmers_.at(template_segment).counts_.at(kmer+max_extension*base) ){
second_highest = max_extension;
max_extension = ext;
}
else if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext*base) > adapter_kmers_.at(template_segment).counts_.at(kmer+second_highest*base) ){
second_highest = ext;
}
}
kmer += base*max_extension;
if( use_kmer.at(kmer) && adapter_kmers_.at(template_segment).counts_.at(kmer) > 100 && adapter_kmers_.at(template_segment).counts_.at(kmer) > 5*adapter_kmers_.at(template_segment).counts_.at(kmer-max_extension*base+second_highest*base) ){
insertValue(adapter, 0, static_cast<Dna>(max_extension) );
use_kmer.at(kmer) = false; // Prevent endless circle
}
else{
break;
}
}
// Extend adapter
kmer = max_kmer;
if(kAdapterSearchInfoFile){
adapter_ext_pos = 0;
}
while(true){
kmer <<= 2;
kmer %= adapter_kmers_.at(template_segment).counts_.size();
if(kAdapterSearchInfoFile){
myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << ++adapter_ext_pos << ", ";
for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){
myfile << at(adapter, pos);
}
myfile << "A, " << adapter_kmers_.at(template_segment).counts_.at(kmer) << std::endl;
myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << adapter_ext_pos << ", ";
for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){
myfile << at(adapter, pos);
}
myfile << "C, " << adapter_kmers_.at(template_segment).counts_.at(kmer+1) << std::endl;
myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << adapter_ext_pos << ", ";
for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){
myfile << at(adapter, pos);
}
myfile << "G, " << adapter_kmers_.at(template_segment).counts_.at(kmer+2) << std::endl;
myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << adapter_ext_pos << ", ";
for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){
myfile << at(adapter, pos);
}
myfile << "T, " << adapter_kmers_.at(template_segment).counts_.at(kmer+3) << std::endl;
}
if( adapter_kmers_.at(template_segment).counts_.at(kmer+3) > adapter_kmers_.at(template_segment).counts_.at(kmer+2) ){
max_extension = 3;
second_highest = 2;
}
else{
max_extension = 2;
second_highest = 3;
}
for(uintBaseCall ext=2; ext--; ){
if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext) > adapter_kmers_.at(template_segment).counts_.at(kmer+max_extension) ){
second_highest = max_extension;
max_extension = ext;
}
else if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext) > adapter_kmers_.at(template_segment).counts_.at(kmer+second_highest) ){
second_highest = ext;
}
}
kmer += max_extension;
if( use_kmer.at(kmer) && adapter_kmers_.at(template_segment).counts_.at(kmer) > 100 && adapter_kmers_.at(template_segment).counts_.at(kmer) > 5*adapter_kmers_.at(template_segment).counts_.at(kmer-max_extension+second_highest) ){
adapter += static_cast<Dna>(max_extension);
use_kmer.at(kmer) = false; // Prevent endless circle
}
else{
break;
}
}
// Remove A's at end
while(length(adapter) && 0 == back(adapter)){
eraseBack(adapter);
}
if( 30 > length(adapter) ){
printInfo << "Detected non-extendible sequence '" << adapter << "' as adapter for read " << static_cast<uintTempSeqPrint>(template_segment+1) << std::endl;
}
else if( 120 < length(adapter) ){
printErr << "Detected very long sequence '" << adapter << "' as adapter for read " << static_cast<uintTempSeqPrint>(template_segment+1) << ", which is likely part of the genome." << std::endl;
if(kAdapterSearchInfoFile){
myfile.close();
}
return false;
}
else{
printInfo << "Detected adapter " << static_cast<uintTempSeqPrint>(template_segment+1) << ": " << adapter << std::endl;
found_adapter = true;
}
}
if(!found_adapter){
printErr << "Only non-extendible sequences were found as adapter for read " << static_cast<uintTempSeqPrint>(template_segment+1) << std::endl;
if(kAdapterSearchInfoFile){
myfile.close();
}
return false;
}
seqs_.at(template_segment).push_back(adapter);
names_.at(template_segment).emplace_back(toCString(CharString(adapter)));
// Free memory
adapter_kmers_.at(template_segment).Clear();
adapter_start_kmers_.at(template_segment).clear();
adapter_start_kmers_.at(template_segment).shrink_to_fit();
}
if(kAdapterSearchInfoFile){
myfile.close();
}
combinations_.resize( 1, vector<bool>(1, true) ); // Set the single combinations to valid
}
return true;
}
void AdapterStats::PrepareAdapters(uintReadLen size_read_length, uintQual phred_quality_offset){
// Resize adapter vectors
tmp_counts_.resize(seqs_.at(0).size());
for( auto &dim1 : tmp_counts_ ){
dim1.resize(seqs_.at(1).size());
for( auto &dim2 : dim1 ){
dim2.resize(size_read_length);
for( auto &dim3 : dim2 ){
dim3.resize(size_read_length);
}
}
}
for(uintTempSeq seg=2; seg--; ){
tmp_start_cut_.at(seg).resize(seqs_.at(seg).size());
for( auto &dim1 : tmp_start_cut_.at(seg) ){
dim1.resize(size_read_length);
}
}
tmp_polya_tail_length_.resize(size_read_length);
// Prepare skewer matrix for adapter identification
skewer::cMatrix::InitParameters(skewer::TRIM_PE, 0.1, 0.03, phred_quality_offset, false); // 0.1 and 0.03 are the default values from the skewer software
for( auto &adapter : seqs_.at(0) ){
skewer::cMatrix::AddAdapter(skewer::cMatrix::firstAdapters, toCString(static_cast<CharString>(adapter)), length(adapter), skewer::TRIM_TAIL);
}
for( auto &adapter : seqs_.at(1) ){
skewer::cMatrix::AddAdapter(skewer::cMatrix::secondAdapters, toCString(static_cast<CharString>(adapter)), length(adapter), skewer::TRIM_TAIL);
}
skewer::cMatrix::CalculateIndices(combinations_, seqs_.at(0).size(), seqs_.at(1).size());
}
bool AdapterStats::Detect(uintReadLen &adapter_position_first, uintReadLen &adapter_position_second, const BamAlignmentRecord &record_first, const BamAlignmentRecord &record_second, const Reference &reference, bool properly_mapped){
bool search_adapters(true);
// Determine minimum adapter length
int i_min_overlap(0);
if( hasFlagUnmapped(record_first) || hasFlagUnmapped(record_second) ){
uintReadLen last_error_pos(kMinimumAdapterLengthUnmapped-1); // Case of both reads unmapped
if( (hasFlagUnmapped(record_first) || CountErrors(last_error_pos, record_first, reference)) && (hasFlagUnmapped(record_second) || CountErrors(last_error_pos, record_second, reference)) ){
i_min_overlap = last_error_pos+1; // +1 because it is a position starting at 0 and we need a length
}
else{
// In case one of the reads is a perfect match don't look for adapters
search_adapters = false;
}
}
else{
uintReadLen last_error_pos1, last_error_pos2;
if( CountErrors(last_error_pos1, record_first, reference) && CountErrors(last_error_pos2, record_second, reference) ){
i_min_overlap = max(last_error_pos1, last_error_pos2)+1; // A perfect matching piece cannot be an adapter, so adapter must be at least reach last error in both reads
}
else{
search_adapters = false;
}
}
if(search_adapters){
// Fill read1, read2 with first/second measured in sequencer(by fastq file) not by position in bam file and convert to measurement/fastq direction (not reference/bam direction)
const CharString *qual1, *qual2;
CharString read1, read2, reversed_qual;
if( hasFlagLast(record_second) ){
read1 = record_first.seq;
if( hasFlagRC(record_first) ){
reverseComplement(read1); // Reverses in place, so don't let it act on the record sequence itself
reversed_qual = record_first.qual;
reverse(reversed_qual);
qual1 = &reversed_qual;
}
else{
qual1 = &record_first.qual;
}
read2 = record_second.seq;
if( hasFlagRC(record_second) ){
reverseComplement(read2); // Reverses in place, so don't let it act on the record sequence itself
reversed_qual = record_second.qual;
reverse(reversed_qual);
qual2 = &reversed_qual;
}
else{
qual2 = &record_second.qual;
}
}
else{
read1 = record_second.seq;
if( hasFlagRC(record_second) ){
reverseComplement(read1); // Reverses in place, so don't let it act on the record sequence itself
reversed_qual = record_second.qual;
reverse(reversed_qual);
qual1 = &reversed_qual;
}
else{
qual1 = &record_second.qual;
}
read2 = record_first.seq;
if( hasFlagRC(record_first) ){
reverseComplement(read2); // Reverses in place, so don't let it act on the record sequence itself
reversed_qual = record_first.qual;
reverse(reversed_qual);
qual2 = &reversed_qual;
}
else{
qual2 = &record_first.qual;
}
}
auto index1 = skewer::cMatrix::findAdapter(toCString(read1), length(read1), reinterpret_cast<unsigned char *>(toCString(*qual1)), length(*qual1), i_min_overlap);
if( index1.bc-- ){ // Adapter has been detected for first read (bc is now index of adapter)
auto index2 = skewer::cMatrix::findAdapter2(toCString(read2), length(read2), reinterpret_cast<unsigned char *>(toCString(*qual2)), length(*qual2), i_min_overlap);
if( index2.bc-- && combinations_.at(index1.bc).at(index2.bc)){ // Adapter has been detected also for second read and it is a valid pair with the first
if( 2 > max(index1.pos,index2.pos) - min(index1.pos,index2.pos) ){ // Allow a single one-base indel in the insert between the adapters
if( properly_mapped || VerifyInsert(read1, read2, index1.pos, index2.pos) ){
// Stats that need to be aware of cut length
bool poly_a_tail = true;
uintReadLen poly_a_tail_length = 0;
for(uintReadLen pos=index1.pos + length(seqs_.at(0).at(index1.bc)); pos < length(read1); ++pos){
if(poly_a_tail){
if('A' == at(read1, pos)){
++poly_a_tail_length;
}
else{
poly_a_tail=false;
++tmp_polya_tail_length_.at(poly_a_tail_length);
}
}
if(!poly_a_tail){
++tmp_overrun_bases_.at(Dna5(at(read1, pos)));
}
}
poly_a_tail = true;
poly_a_tail_length = 0;
for(uintReadLen pos=index2.pos + length(seqs_.at(1).at(index2.bc)); pos < length(read2); ++pos){
if(poly_a_tail){
if('A' == at(read2, pos)){
++poly_a_tail_length;
}
else{
poly_a_tail=false;
++tmp_polya_tail_length_.at(poly_a_tail_length);
}
}
if(!poly_a_tail){
++tmp_overrun_bases_.at(Dna5(at(read2, pos)));
}
}
// If the read starts with an adapter note down if and how much it has been cut of at the beginning (position below 0) and set position to 0 for the further stats
if(1>index1.pos){
++tmp_start_cut_.at(0).at(index1.bc).at(-index1.pos);
index1.pos = 0;
}
if(1>index2.pos){
++tmp_start_cut_.at(1).at(index2.bc).at(-index2.pos);
index2.pos = 0;
}
// Set return values
if( hasFlagLast(record_first) ){
adapter_position_first = index2.pos;
adapter_position_second = index1.pos;
}
else{
adapter_position_first = index1.pos;
adapter_position_second = index2.pos;
}
// Fill in stats
++tmp_counts_.at(index1.bc).at(index2.bc).at(length(read1)-index1.pos).at(length(read2)-index2.pos);
return true;
}
}
}
}
}
// If no adapter where found fill in read length
adapter_position_first = length(record_first.seq);
adapter_position_second = length(record_second.seq);
return false;
}
void AdapterStats::Finalize(){
// Copy to final vectors
counts_.resize(tmp_counts_.size());
for( auto i = tmp_counts_.size(); i--; ){
counts_.at(i).resize(tmp_counts_.at(i).size());
for( auto j = tmp_counts_.at(i).size(); j--; ){
counts_.at(i).at(j).Acquire(tmp_counts_.at(i).at(j));
}
}
for(uintTempSeq seg=2; seg--; ){
start_cut_.at(seg).resize(tmp_start_cut_.at(seg).size());
for( auto i = tmp_start_cut_.at(seg).size(); i--; ){
start_cut_.at(seg).at(i).Acquire(tmp_start_cut_.at(seg).at(i));
}
}
polya_tail_length_.Acquire(tmp_polya_tail_length_);
for( auto i = tmp_overrun_bases_.size(); i--; ){
overrun_bases_.at(i) = tmp_overrun_bases_.at(i);
}
}
void AdapterStats::SumCounts(){
for(uintTempSeq seg=2; seg--; ){
count_sum_.at(seg).clear();
count_sum_.at(seg).resize(start_cut_.at(seg).size(), 0);
}
// Sum adapters starting from length where adapters are unambiguous (sorted by content: so simply first position that differs from adapter before and after)
uintFragCount sum;
uintReadLen first_diff_before_a1(0), first_diff_after_a1, first_diff_before_a2, first_diff_after_a2;
for( auto a1=counts_.size(); a1--; ){
first_diff_after_a1 = 0;
if(a1){ // Not last in loop
while(first_diff_after_a1 < min(length(seqs_.at(0).at(a1)), length(seqs_.at(0).at(a1-1))) && at(seqs_.at(0).at(a1), first_diff_after_a1) == at(seqs_.at(0).at(a1-1), first_diff_after_a1) ){
++first_diff_after_a1;
}
}
first_diff_before_a2 = 0;
for( auto a2=counts_.at(0).size(); a2--; ){ // All vectors i are the same length so we can simply take the length of 0
first_diff_after_a2 = 0;
if(a2){ // Not last in loop
while(first_diff_after_a2 < min(length(seqs_.at(1).at(a2)), length(seqs_.at(1).at(a2-1))) && at(seqs_.at(1).at(a2), first_diff_after_a2) == at(seqs_.at(1).at(a2-1), first_diff_after_a2) ){
++first_diff_after_a2;
}
}
sum = 0;
for( auto pos1 = max(max(first_diff_before_a1,first_diff_after_a1), static_cast<uintReadLen>(counts_.at(a1).at(a2).from())); pos1 < counts_.at(a1).at(a2).to(); ++pos1){
for( auto pos2 = max(max(first_diff_before_a2,first_diff_after_a2), static_cast<uintReadLen>(counts_.at(a1).at(a2).at(pos1).from())); pos2 < counts_.at(a1).at(a2).at(pos1).to(); ++pos2){
sum += counts_.at(a1).at(a2).at(pos1).at(pos2);
}
}
count_sum_.at(0).at(a1) += sum;
count_sum_.at(1).at(a2) += sum;
first_diff_before_a2 = first_diff_after_a2;
}
first_diff_before_a1 = first_diff_after_a1;
}
}
void AdapterStats::Shrink(){
for( auto &dim1 : counts_){
for( auto &adapter_pair : dim1){
ShrinkVect(adapter_pair);
}
}
}
void AdapterStats::PrepareSimulation(){
for(uintTempSeq seg=2; seg--; ){
significant_count_.at(seg).clear();
significant_count_.at(seg).resize(count_sum_.at(seg).size(), 0);
uintFragCount threshold = ceil(*max_element(count_sum_.at(seg).begin(), count_sum_.at(seg).end()) * kMinFractionOfMaximumForSimulation);
for(auto i=significant_count_.at(seg).size(); i--; ){
if(count_sum_.at(seg).at(i) < threshold){
significant_count_.at(seg).at(i) = 0;
}
else{
significant_count_.at(seg).at(i) = count_sum_.at(seg).at(i);
}
}
}
}
| 35.385039 | 244 | 0.649028 | schmeing |
3e444ee4d84ac1ec0a43e64b643324665c6eed0c | 28,688 | cpp | C++ | test/projection_test.cpp | seanyen/laser_geometry | c6915767ef66d8b2beb5dcbcc4356281654e84e2 | [
"BSD-3-Clause"
] | 2 | 2021-07-14T12:33:55.000Z | 2021-11-21T07:14:13.000Z | test/projection_test.cpp | seanyen/laser_geometry | c6915767ef66d8b2beb5dcbcc4356281654e84e2 | [
"BSD-3-Clause"
] | null | null | null | test/projection_test.cpp | seanyen/laser_geometry | c6915767ef66d8b2beb5dcbcc4356281654e84e2 | [
"BSD-3-Clause"
] | 1 | 2020-05-28T01:16:08.000Z | 2020-05-28T01:16:08.000Z | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtest/gtest.h>
#include "laser_geometry/laser_geometry.h"
#include "sensor_msgs/PointCloud.h"
#include <math.h>
#include <angles/angles.h>
#include "rostest/permuter.h"
#define PROJECTION_TEST_RANGE_MIN (0.23)
#define PROJECTION_TEST_RANGE_MAX (40.0)
class BuildScanException { };
sensor_msgs::LaserScan build_constant_scan(double range, double intensity,
double ang_min, double ang_max, double ang_increment,
ros::Duration scan_time)
{
if (((ang_max - ang_min) / ang_increment) < 0)
throw (BuildScanException());
sensor_msgs::LaserScan scan;
scan.header.stamp = ros::Time::now();
scan.header.frame_id = "laser_frame";
scan.angle_min = ang_min;
scan.angle_max = ang_max;
scan.angle_increment = ang_increment;
scan.scan_time = scan_time.toSec();
scan.range_min = PROJECTION_TEST_RANGE_MIN;
scan.range_max = PROJECTION_TEST_RANGE_MAX;
uint32_t i = 0;
for(; ang_min + i * ang_increment < ang_max; i++)
{
scan.ranges.push_back(range);
scan.intensities.push_back(intensity);
}
scan.time_increment = scan_time.toSec()/(double)i;
return scan;
};
class TestProjection : public laser_geometry::LaserProjection
{
public:
const boost::numeric::ublas::matrix<double>& getUnitVectors(double angle_min,
double angle_max,
double angle_increment,
unsigned int length)
{
return getUnitVectors_(angle_min, angle_max, angle_increment, length);
}
};
void test_getUnitVectors(double angle_min, double angle_max, double angle_increment, unsigned int length)
{
double tolerance = 1e-12;
TestProjection projector;
const boost::numeric::ublas::matrix<double> & mat = projector.getUnitVectors(angle_min, angle_max, angle_increment, length);
for (unsigned int i = 0; i < mat.size2(); i++)
{
EXPECT_NEAR(angles::shortest_angular_distance(atan2(mat(1,i), mat(0,i)),
angle_min + i * angle_increment),
0,
tolerance); // check expected angle
EXPECT_NEAR(1.0, mat(1,i)*mat(1,i) + mat(0,i)*mat(0,i), tolerance); //make sure normalized
}
}
#if 0
TEST(laser_geometry, getUnitVectors)
{
double min_angle = -M_PI/2;
double max_angle = M_PI/2;
double angle_increment = M_PI/180;
std::vector<double> min_angles, max_angles, angle_increments;
rostest::Permuter permuter;
min_angles.push_back(-M_PI);
min_angles.push_back(-M_PI/1.5);
min_angles.push_back(-M_PI/2);
min_angles.push_back(-M_PI/4);
min_angles.push_back(-M_PI/8);
min_angles.push_back(M_PI);
min_angles.push_back(M_PI/1.5);
min_angles.push_back(M_PI/2);
min_angles.push_back(M_PI/4);
min_angles.push_back(M_PI/8);
permuter.addOptionSet(min_angles, &min_angle);
max_angles.push_back(M_PI);
max_angles.push_back(M_PI/1.5);
max_angles.push_back(M_PI/2);
max_angles.push_back(M_PI/4);
max_angles.push_back(M_PI/8);
max_angles.push_back(-M_PI);
max_angles.push_back(-M_PI/1.5);
max_angles.push_back(-M_PI/2);
max_angles.push_back(-M_PI/4);
max_angles.push_back(-M_PI/8);
permuter.addOptionSet(max_angles, &max_angle);
angle_increments.push_back(M_PI/180); // one degree
angle_increments.push_back(M_PI/360); // half degree
angle_increments.push_back(M_PI/720); // quarter degree
angle_increments.push_back(-M_PI/180); // -one degree
angle_increments.push_back(-M_PI/360); // -half degree
angle_increments.push_back(-M_PI/720); // -quarter degree
permuter.addOptionSet(angle_increments, &angle_increment);
while (permuter.step())
{
if ((max_angle - min_angle) / angle_increment > 0.0)
{
unsigned int length = round((max_angle - min_angle)/ angle_increment);
try
{
test_getUnitVectors(min_angle, max_angle, angle_increment, length);
test_getUnitVectors(min_angle, max_angle, angle_increment, (max_angle - min_angle)/ angle_increment);
test_getUnitVectors(min_angle, max_angle, angle_increment, (max_angle - min_angle)/ angle_increment + 1);
}
catch (BuildScanException &ex)
{
if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception
FAIL();
}
}
//else
//printf("%f\n", (max_angle - min_angle) / angle_increment);
}
}
TEST(laser_geometry, projectLaser)
{
double tolerance = 1e-12;
laser_geometry::LaserProjection projector;
double min_angle = -M_PI/2;
double max_angle = M_PI/2;
double angle_increment = M_PI/180;
double range = 1.0;
double intensity = 1.0;
ros::Duration scan_time = ros::Duration(1/40);
ros::Duration increment_time = ros::Duration(1/400);
std::vector<double> ranges, intensities, min_angles, max_angles, angle_increments;
std::vector<ros::Duration> increment_times, scan_times;
rostest::Permuter permuter;
ranges.push_back(-1.0);
ranges.push_back(1.0);
ranges.push_back(2.0);
ranges.push_back(3.0);
ranges.push_back(4.0);
ranges.push_back(5.0);
ranges.push_back(100.0);
permuter.addOptionSet(ranges, &range);
intensities.push_back(1.0);
intensities.push_back(2.0);
intensities.push_back(3.0);
intensities.push_back(4.0);
intensities.push_back(5.0);
permuter.addOptionSet(intensities, &intensity);
min_angles.push_back(-M_PI);
min_angles.push_back(-M_PI/1.5);
min_angles.push_back(-M_PI/2);
min_angles.push_back(-M_PI/4);
min_angles.push_back(-M_PI/8);
permuter.addOptionSet(min_angles, &min_angle);
max_angles.push_back(M_PI);
max_angles.push_back(M_PI/1.5);
max_angles.push_back(M_PI/2);
max_angles.push_back(M_PI/4);
max_angles.push_back(M_PI/8);
permuter.addOptionSet(max_angles, &max_angle);
// angle_increments.push_back(-M_PI/180); // -one degree
angle_increments.push_back(M_PI/180); // one degree
angle_increments.push_back(M_PI/360); // half degree
angle_increments.push_back(M_PI/720); // quarter degree
permuter.addOptionSet(angle_increments, &angle_increment);
scan_times.push_back(ros::Duration(1/40));
scan_times.push_back(ros::Duration(1/20));
permuter.addOptionSet(scan_times, &scan_time);
while (permuter.step())
{
try
{
// printf("%f %f %f %f %f %f\n", range, intensity, min_angle, max_angle, angle_increment, scan_time.toSec());
sensor_msgs::LaserScan scan = build_constant_scan(range, intensity, min_angle, max_angle, angle_increment, scan_time);
sensor_msgs::PointCloud cloud_out;
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)1);
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)1);
projector.projectLaser(scan, cloud_out, -1.0);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)2);
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)2);
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)3);
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)4);
unsigned int valid_points = 0;
for (unsigned int i = 0; i < scan.ranges.size(); i++)
if (scan.ranges[i] <= PROJECTION_TEST_RANGE_MAX && scan.ranges[i] >= PROJECTION_TEST_RANGE_MIN)
valid_points ++;
EXPECT_EQ(valid_points, cloud_out.points.size());
for (unsigned int i = 0; i < cloud_out.points.size(); i++)
{
EXPECT_NEAR(cloud_out.points[i].x , (float)((double)(scan.ranges[i]) * cos((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance);
EXPECT_NEAR(cloud_out.points[i].y , (float)((double)(scan.ranges[i]) * sin((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance);
EXPECT_NEAR(cloud_out.points[i].z, 0, tolerance);
EXPECT_NEAR(cloud_out.channels[0].values[i], scan.intensities[i], tolerance);//intensity \todo determine this by lookup not hard coded order
EXPECT_NEAR(cloud_out.channels[1].values[i], i, tolerance);//index
EXPECT_NEAR(cloud_out.channels[2].values[i], scan.ranges[i], tolerance);//ranges
EXPECT_NEAR(cloud_out.channels[3].values[i], (float)i * scan.time_increment, tolerance);//timestamps
};
}
catch (BuildScanException &ex)
{
if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception
FAIL();
}
}
}
#endif
TEST(laser_geometry, projectLaser2)
{
double tolerance = 1e-12;
laser_geometry::LaserProjection projector;
double min_angle = -M_PI/2;
double max_angle = M_PI/2;
double angle_increment = M_PI/180;
double range = 1.0;
double intensity = 1.0;
ros::Duration scan_time = ros::Duration(1/40);
ros::Duration increment_time = ros::Duration(1/400);
std::vector<double> ranges, intensities, min_angles, max_angles, angle_increments;
std::vector<ros::Duration> increment_times, scan_times;
rostest::Permuter permuter;
ranges.push_back(-1.0);
ranges.push_back(1.0);
ranges.push_back(2.0);
ranges.push_back(3.0);
ranges.push_back(4.0);
ranges.push_back(5.0);
ranges.push_back(100.0);
permuter.addOptionSet(ranges, &range);
intensities.push_back(1.0);
intensities.push_back(2.0);
intensities.push_back(3.0);
intensities.push_back(4.0);
intensities.push_back(5.0);
permuter.addOptionSet(intensities, &intensity);
min_angles.push_back(-M_PI);
min_angles.push_back(-M_PI/1.5);
min_angles.push_back(-M_PI/2);
min_angles.push_back(-M_PI/4);
min_angles.push_back(-M_PI/8);
permuter.addOptionSet(min_angles, &min_angle);
max_angles.push_back(M_PI);
max_angles.push_back(M_PI/1.5);
max_angles.push_back(M_PI/2);
max_angles.push_back(M_PI/4);
max_angles.push_back(M_PI/8);
permuter.addOptionSet(max_angles, &max_angle);
// angle_increments.push_back(-M_PI/180); // -one degree
angle_increments.push_back(M_PI/180); // one degree
angle_increments.push_back(M_PI/360); // half degree
angle_increments.push_back(M_PI/720); // quarter degree
permuter.addOptionSet(angle_increments, &angle_increment);
scan_times.push_back(ros::Duration(1/40));
scan_times.push_back(ros::Duration(1/20));
permuter.addOptionSet(scan_times, &scan_time);
while (permuter.step())
{
try
{
// printf("%f %f %f %f %f %f\n", range, intensity, min_angle, max_angle, angle_increment, scan_time.toSec());
sensor_msgs::LaserScan scan = build_constant_scan(range, intensity, min_angle, max_angle, angle_increment, scan_time);
sensor_msgs::PointCloud2 cloud_out;
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4);
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4);
projector.projectLaser(scan, cloud_out, -1.0);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5);
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5);
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)6);
projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)7);
unsigned int valid_points = 0;
for (unsigned int i = 0; i < scan.ranges.size(); i++)
if (scan.ranges[i] <= PROJECTION_TEST_RANGE_MAX && scan.ranges[i] >= PROJECTION_TEST_RANGE_MIN)
valid_points ++;
EXPECT_EQ(valid_points, cloud_out.width);
uint32_t x_offset = 0;
uint32_t y_offset = 0;
uint32_t z_offset = 0;
uint32_t intensity_offset = 0;
uint32_t index_offset = 0;
uint32_t distance_offset = 0;
uint32_t stamps_offset = 0;
for (std::vector<sensor_msgs::PointField>::iterator f = cloud_out.fields.begin(); f != cloud_out.fields.end(); f++)
{
if (f->name == "x") x_offset = f->offset;
if (f->name == "y") y_offset = f->offset;
if (f->name == "z") z_offset = f->offset;
if (f->name == "intensity") intensity_offset = f->offset;
if (f->name == "index") index_offset = f->offset;
if (f->name == "distances") distance_offset = f->offset;
if (f->name == "stamps") stamps_offset = f->offset;
}
for (unsigned int i = 0; i < cloud_out.width; i++)
{
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + x_offset] , (float)((double)(scan.ranges[i]) * cos((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance);
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + y_offset] , (float)((double)(scan.ranges[i]) * sin((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance);
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + z_offset] , 0, tolerance);
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + intensity_offset] , scan.intensities[i], tolerance);//intensity \todo determine this by lookup not hard coded order
EXPECT_NEAR(*(uint32_t*)&cloud_out.data[i*cloud_out.point_step + index_offset], i, tolerance);//index
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + distance_offset], scan.ranges[i], tolerance);//ranges
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + stamps_offset], (float)i * scan.time_increment, tolerance);//timestamps
};
}
catch (BuildScanException &ex)
{
if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception
FAIL();
}
}
}
TEST(laser_geometry, transformLaserScanToPointCloud)
{
tf::Transformer tf;
double tolerance = 1e-12;
laser_geometry::LaserProjection projector;
double min_angle = -M_PI/2;
double max_angle = M_PI/2;
double angle_increment = M_PI/180;
double range = 1.0;
double intensity = 1.0;
ros::Duration scan_time = ros::Duration(1/40);
ros::Duration increment_time = ros::Duration(1/400);
std::vector<double> ranges, intensities, min_angles, max_angles, angle_increments;
std::vector<ros::Duration> increment_times, scan_times;
rostest::Permuter permuter;
ranges.push_back(-1.0);
ranges.push_back(1.0);
ranges.push_back(2.0);
ranges.push_back(3.0);
ranges.push_back(4.0);
ranges.push_back(5.0);
ranges.push_back(100.0);
permuter.addOptionSet(ranges, &range);
intensities.push_back(1.0);
intensities.push_back(2.0);
intensities.push_back(3.0);
intensities.push_back(4.0);
intensities.push_back(5.0);
permuter.addOptionSet(intensities, &intensity);
min_angles.push_back(-M_PI);
min_angles.push_back(-M_PI/1.5);
min_angles.push_back(-M_PI/2);
min_angles.push_back(-M_PI/4);
min_angles.push_back(-M_PI/8);
max_angles.push_back(M_PI);
max_angles.push_back(M_PI/1.5);
max_angles.push_back(M_PI/2);
max_angles.push_back(M_PI/4);
max_angles.push_back(M_PI/8);
permuter.addOptionSet(min_angles, &min_angle);
permuter.addOptionSet(max_angles, &max_angle);
angle_increments.push_back(-M_PI/180); // -one degree
angle_increments.push_back(M_PI/180); // one degree
angle_increments.push_back(M_PI/360); // half degree
angle_increments.push_back(M_PI/720); // quarter degree
permuter.addOptionSet(angle_increments, &angle_increment);
scan_times.push_back(ros::Duration(1/40));
scan_times.push_back(ros::Duration(1/20));
permuter.addOptionSet(scan_times, &scan_time);
while (permuter.step())
{
try
{
//printf("%f %f %f %f %f %f\n", range, intensity, min_angle, max_angle, angle_increment, scan_time.toSec());
sensor_msgs::LaserScan scan = build_constant_scan(range, intensity, min_angle, max_angle, angle_increment, scan_time);
scan.header.frame_id = "laser_frame";
sensor_msgs::PointCloud cloud_out;
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)1);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Intensity);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)1);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)2);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)2);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)3);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp);
EXPECT_EQ(cloud_out.channels.size(), (unsigned int)4);
unsigned int valid_points = 0;
for (unsigned int i = 0; i < scan.ranges.size(); i++)
if (scan.ranges[i] <= PROJECTION_TEST_RANGE_MAX && scan.ranges[i] >= PROJECTION_TEST_RANGE_MIN)
valid_points ++;
EXPECT_EQ(valid_points, cloud_out.points.size());
for (unsigned int i = 0; i < cloud_out.points.size(); i++)
{
EXPECT_NEAR(cloud_out.points[i].x , (float)((double)(scan.ranges[i]) * cos((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance);
EXPECT_NEAR(cloud_out.points[i].y , (float)((double)(scan.ranges[i]) * sin((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance);
EXPECT_NEAR(cloud_out.points[i].z, 0, tolerance);
EXPECT_NEAR(cloud_out.channels[0].values[i], scan.intensities[i], tolerance);//intensity \todo determine this by lookup not hard coded order
EXPECT_NEAR(cloud_out.channels[1].values[i], i, tolerance);//index
EXPECT_NEAR(cloud_out.channels[2].values[i], scan.ranges[i], tolerance);//ranges
EXPECT_NEAR(cloud_out.channels[3].values[i], (float)i * scan.time_increment, tolerance);//timestamps
};
}
catch (BuildScanException &ex)
{
if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception
FAIL();
}
}
}
TEST(laser_geometry, transformLaserScanToPointCloud2)
{
tf::Transformer tf;
tf2::BufferCore tf2;
double tolerance = 1e-12;
laser_geometry::LaserProjection projector;
double min_angle = -M_PI/2;
double max_angle = M_PI/2;
double angle_increment = M_PI/180;
double range = 1.0;
double intensity = 1.0;
ros::Duration scan_time = ros::Duration(1/40);
ros::Duration increment_time = ros::Duration(1/400);
std::vector<double> ranges, intensities, min_angles, max_angles, angle_increments;
std::vector<ros::Duration> increment_times, scan_times;
rostest::Permuter permuter;
ranges.push_back(-1.0);
ranges.push_back(1.0);
ranges.push_back(2.0);
ranges.push_back(3.0);
ranges.push_back(4.0);
ranges.push_back(5.0);
ranges.push_back(100.0);
permuter.addOptionSet(ranges, &range);
intensities.push_back(1.0);
intensities.push_back(2.0);
intensities.push_back(3.0);
intensities.push_back(4.0);
intensities.push_back(5.0);
permuter.addOptionSet(intensities, &intensity);
min_angles.push_back(-M_PI);
min_angles.push_back(-M_PI/1.5);
min_angles.push_back(-M_PI/2);
min_angles.push_back(-M_PI/4);
min_angles.push_back(-M_PI/8);
max_angles.push_back(M_PI);
max_angles.push_back(M_PI/1.5);
max_angles.push_back(M_PI/2);
max_angles.push_back(M_PI/4);
max_angles.push_back(M_PI/8);
permuter.addOptionSet(min_angles, &min_angle);
permuter.addOptionSet(max_angles, &max_angle);
angle_increments.push_back(-M_PI/180); // -one degree
angle_increments.push_back(M_PI/180); // one degree
angle_increments.push_back(M_PI/360); // half degree
angle_increments.push_back(M_PI/720); // quarter degree
permuter.addOptionSet(angle_increments, &angle_increment);
scan_times.push_back(ros::Duration(1/40));
scan_times.push_back(ros::Duration(1/20));
permuter.addOptionSet(scan_times, &scan_time);
while (permuter.step())
{
try
{
//printf("%f %f %f %f %f %f\n", range, intensity, min_angle, max_angle, angle_increment, scan_time.toSec());
sensor_msgs::LaserScan scan = build_constant_scan(range, intensity, min_angle, max_angle, angle_increment, scan_time);
scan.header.frame_id = "laser_frame";
sensor_msgs::PointCloud2 cloud_out;
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::None);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)3);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::None);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)3);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Intensity);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Intensity);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)6);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)6);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)7);
projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp);
EXPECT_EQ(cloud_out.fields.size(), (unsigned int)7);
EXPECT_EQ(cloud_out.is_dense, false);
unsigned int valid_points = 0;
for (unsigned int i = 0; i < scan.ranges.size(); i++)
if (scan.ranges[i] <= PROJECTION_TEST_RANGE_MAX && scan.ranges[i] >= PROJECTION_TEST_RANGE_MIN)
valid_points ++;
EXPECT_EQ(valid_points, cloud_out.width);
uint32_t x_offset = 0;
uint32_t y_offset = 0;
uint32_t z_offset = 0;
uint32_t intensity_offset = 0;
uint32_t index_offset = 0;
uint32_t distance_offset = 0;
uint32_t stamps_offset = 0;
for (std::vector<sensor_msgs::PointField>::iterator f = cloud_out.fields.begin(); f != cloud_out.fields.end(); f++)
{
if (f->name == "x") x_offset = f->offset;
if (f->name == "y") y_offset = f->offset;
if (f->name == "z") z_offset = f->offset;
if (f->name == "intensity") intensity_offset = f->offset;
if (f->name == "index") index_offset = f->offset;
if (f->name == "distances") distance_offset = f->offset;
if (f->name == "stamps") stamps_offset = f->offset;
}
for (unsigned int i = 0; i < cloud_out.width; i++)
{
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + x_offset] , (float)((double)(scan.ranges[i]) * cos((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance);
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + y_offset] , (float)((double)(scan.ranges[i]) * sin((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance);
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + z_offset] , 0, tolerance);
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + intensity_offset] , scan.intensities[i], tolerance);//intensity \todo determine this by lookup not hard coded order
EXPECT_NEAR(*(uint32_t*)&cloud_out.data[i*cloud_out.point_step + index_offset], i, tolerance);//index
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + distance_offset], scan.ranges[i], tolerance);//ranges
EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + stamps_offset], (float)i * scan.time_increment, tolerance);//timestamps
};
}
catch (BuildScanException &ex)
{
if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception
FAIL();
}
}
}
int main(int argc, char **argv){
ros::Time::init();
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 41.041488 | 263 | 0.72058 | seanyen |
3e4629739ad02c3678733e95fe64f9aa544d2627 | 3,633 | cpp | C++ | src/chat.cpp | Mart1250/biblepay | d53d04f74242596b104d360187268a50b845b82e | [
"MIT"
] | null | null | null | src/chat.cpp | Mart1250/biblepay | d53d04f74242596b104d360187268a50b845b82e | [
"MIT"
] | null | null | null | src/chat.cpp | Mart1250/biblepay | d53d04f74242596b104d360187268a50b845b82e | [
"MIT"
] | null | null | null | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chat.h"
#include "base58.h"
#include "clientversion.h"
#include "net.h"
#include "pubkey.h"
#include "timedata.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include "rpcpog.h"
#include <stdint.h>
#include <algorithm>
#include <map>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
map<uint256, CChat> mapChats;
CCriticalSection cs_mapChats;
void CChat::SetNull()
{
nVersion = 1;
nTime = 0;
nID = 0;
bPrivate = false;
nPriority = 0;
sPayload.clear();
sFromNickName.clear();
sToNickName.clear();
sDestination.clear();
}
std::string CChat::ToString() const
{
return strprintf(
"CChat(\n"
" nVersion = %d\n"
" nTime = %d\n"
" nID = %d\n"
" bPrivate = %d\n"
" nPriority = %d\n"
" sDestination = %s\n"
" sPayload = \"%s\"\n"
" sFromNickName= \"%s\"\n"
" sToNickName = \"%s\"\n"
")\n",
nVersion,
nTime,
nID,
bPrivate,
nPriority,
sDestination,
sPayload,
sFromNickName,
sToNickName);
}
std::string CChat::Serialized() const
{
return strprintf(
"%d<COL>%d<COL>%d<COL>%d<COL>%d<COL>%s<COL>%s<COL>%s<COL>%s",
nVersion,
nTime,
nID,
bPrivate,
nPriority,
sDestination,
sPayload,
sFromNickName,
sToNickName);
}
void CChat::Deserialize(std::string sData)
{
std::vector<std::string> vInput = Split(sData.c_str(),"<COL>");
if (vInput.size() > 7)
{
this->nVersion = cdbl(vInput[0], 0);
this->nTime = cdbl(vInput[1], 0);
this->nID = cdbl(vInput[2], 0);
this->bPrivate = (bool)(cdbl(vInput[3], 0));
this->nPriority = cdbl(vInput[4], 0);
this->sDestination = vInput[5];
this->sPayload = vInput[6];
this->sFromNickName = vInput[7];
this->sToNickName = vInput[8];
}
}
bool CChat::IsNull() const
{
return (nTime == 0);
}
uint256 CChat::GetHash() const
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << nTime;
ss << nPriority;
ss << sPayload;
ss << sFromNickName;
ss << sToNickName;
ss << sDestination;
return ss.GetHash();
}
bool CChat::RelayTo(CNode* pnode) const
{
if (pnode->nVersion == 0) return false;
// returns true if wasn't already contained in the set
if (pnode->setKnown.insert(GetHash()).second)
{
pnode->PushMessage(NetMsgType::CHAT, *this);
return true;
}
return false;
}
CChat CChat::getChatByHash(const uint256 &hash)
{
CChat retval;
{
LOCK(cs_mapChats);
map<uint256, CChat>::iterator mi = mapChats.find(hash);
if(mi != mapChats.end())
retval = mi->second;
}
return retval;
}
bool CChat::ProcessChat()
{
map<uint256, CChat>::iterator mi = mapChats.find(GetHash());
if(mi != mapChats.end()) return false;
// Never seen this chat record
mapChats.insert(make_pair(GetHash(), *this));
// Notify UI
std::string sNickName = GetArg("-nickname", "");
if (boost::iequals(sNickName, sToNickName) && sPayload == "<RING>" && bPrivate == true)
{
msPagedFrom = sFromNickName;
mlPaged++;
}
uiInterface.NotifyChatEvent(Serialized());
return true;
}
| 22.70625 | 88 | 0.613543 | Mart1250 |
3e46eb3d32a6c9436a26fded7473f982d169cfb2 | 432 | cpp | C++ | src/apps/AlexMachine/stateMachine/states/SteppingRight.cpp | TomMinuzzo/CSALEX2022 | 28513f5e60cee890913c0c5d63fd9e3fcdf4039c | [
"Apache-2.0"
] | null | null | null | src/apps/AlexMachine/stateMachine/states/SteppingRight.cpp | TomMinuzzo/CSALEX2022 | 28513f5e60cee890913c0c5d63fd9e3fcdf4039c | [
"Apache-2.0"
] | null | null | null | src/apps/AlexMachine/stateMachine/states/SteppingRight.cpp | TomMinuzzo/CSALEX2022 | 28513f5e60cee890913c0c5d63fd9e3fcdf4039c | [
"Apache-2.0"
] | null | null | null | #include "SteppingRight.h"
void SteppingRight::entry(void) {
spdlog::info(" Stepping RIGHT");
trajectoryGenerator->initialiseTrajectory(robot->getCurrentMotion(), Foot::Left, robot->getJointStates());
robot->startNewTraj();
robot->setCurrentState(AlexState::StepR);
}
void SteppingRight::during(void) {
robot->moveThroughTraj();
}
void SteppingRight::exit(void) {
spdlog::debug("EXITING STEPPING RIGHT");
}
| 28.8 | 110 | 0.719907 | TomMinuzzo |
3e48e3224d09c3dae1dfe91b8936decb5dfaa74e | 4,085 | cc | C++ | sdl_core/src/components/smart_objects/src/string_schema_item.cc | APCVSRepo/android_packet | 5d4237234656b777cd9b0cae4731afea51986582 | [
"BSD-3-Clause"
] | 4 | 2016-09-21T12:36:24.000Z | 2020-10-29T01:45:03.000Z | sdl_core/src/components/smart_objects/src/string_schema_item.cc | APCVSRepo/android_packet | 5d4237234656b777cd9b0cae4731afea51986582 | [
"BSD-3-Clause"
] | 7 | 2016-06-01T01:21:44.000Z | 2017-11-03T08:18:23.000Z | sdl_core/src/components/smart_objects/src/string_schema_item.cc | APCVSRepo/android_packet | 5d4237234656b777cd9b0cae4731afea51986582 | [
"BSD-3-Clause"
] | 8 | 2017-08-29T10:51:50.000Z | 2021-03-24T10:19:11.000Z | // Copyright (c) 2013, Ford Motor Company
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the
// distribution.
//
// Neither the name of the Ford Motor Company nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifdef MODIFY_FUNCTION_SIGN
#include <global_first.h>
#endif
#include "smart_objects/smart_object.h"
#include "smart_objects/string_schema_item.h"
#ifdef MODIFY_FUNCTION_SIGN
#ifdef OS_WIN32
#include "utils/global.h"
#endif
#endif
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
utils::SharedPtr<CStringSchemaItem> CStringSchemaItem::create(
const TSchemaItemParameter<size_t>& MinLength,
const TSchemaItemParameter<size_t>& MaxLength,
const TSchemaItemParameter<std::string>& DefaultValue) {
return new CStringSchemaItem(MinLength, MaxLength, DefaultValue);
}
Errors::eType CStringSchemaItem::validate(const SmartObject& Object) {
Errors::eType result = Errors::ERROR;
if (SmartType_String == Object.getType()) {
result = Errors::OK;
size_t minLength;
size_t maxLength;
#ifdef MODIFY_FUNCTION_SIGN
#ifdef OS_WIN32
std::string strIn = Object.asString();
wchar_string value;
Global::toUnicode(strIn, CP_UTF8, value);
#else
std::string value = Object.asString();
#endif
#else
std::string value = Object.asString();
#endif
if (true == mMinLength.getValue(minLength)) {
if (value.size() < minLength) {
result = Errors::INVALID_VALUE;
}
}
if (true == mMaxLength.getValue(maxLength)) {
if (value.size() > maxLength) {
result = Errors::OUT_OF_RANGE;
}
}
} else {
result = Errors::INVALID_VALUE;
}
return result;
}
bool CStringSchemaItem::setDefaultValue(SmartObject& Object) {
bool result = false;
std::string value;
if (true == mDefaultValue.getValue(value)) {
Object = value;
result = true;
}
return result;
}
void CStringSchemaItem::BuildObjectBySchema(const SmartObject& pattern_object,
SmartObject& result_object) {
if (SmartType_String == pattern_object.getType()) {
result_object = pattern_object;
} else {
bool result = setDefaultValue(result_object);
if (false == result) {
result_object = std::string("");
}
}
}
CStringSchemaItem::CStringSchemaItem(
const TSchemaItemParameter<size_t>& MinLength,
const TSchemaItemParameter<size_t>& MaxLength,
const TSchemaItemParameter<std::string>& DefaultValue)
: mMinLength(MinLength),
mMaxLength(MaxLength),
mDefaultValue(DefaultValue) {
}
} // namespace NsSmartObjects
} // namespace NsSmartDeviceLink
| 32.68 | 80 | 0.707711 | APCVSRepo |
3e49c8455ad03eb0ee43530510402b5ff5e0c931 | 43,621 | cpp | C++ | 099/graysvr/CClientUse.cpp | Jhobean/Source-Archive | ab24ba44ffd34c329accedb980699e94c196fceb | [
"Apache-2.0"
] | 2 | 2020-12-22T17:03:14.000Z | 2021-07-31T23:59:05.000Z | 099/graysvr/CClientUse.cpp | Jhobean/Source-Archive | ab24ba44ffd34c329accedb980699e94c196fceb | [
"Apache-2.0"
] | null | null | null | 099/graysvr/CClientUse.cpp | Jhobean/Source-Archive | ab24ba44ffd34c329accedb980699e94c196fceb | [
"Apache-2.0"
] | 4 | 2021-04-21T19:43:48.000Z | 2021-10-07T00:38:23.000Z | // CClientUse.cpp
// Copyright Menace Software (www.menasoft.com).
//
#include "graysvr.h" // predef header.
#include "cclient.h"
bool CClient::Cmd_Use_Item( CItem * pItem, bool fTestTouch )
{
// Assume we can see the target.
// called from Event_DoubleClick
if ( pItem == NULL )
return false;
if ( fTestTouch )
{
// CanTouch handles priv level compares for chars
if ( ! m_pChar->CanUse( pItem, false ))
{
if ( ! m_pChar->CanTouch( pItem ))
{
SysMessage(( m_pChar->IsStatFlag( STATF_DEAD )) ?
"Your ghostly hand passes through the object." :
"You can't reach that." );
return false;
}
SysMessage( "You can't use this where it is." );
return false;
}
}
CItemBase * pItemDef = pItem->Item_GetDef();
// Must equip the item ?
if ( pItemDef->IsTypeEquippable() && pItem->GetParent() != m_pChar )
{
DEBUG_CHECK( pItemDef->GetEquipLayer());
switch ( pItem->GetType())
{
case IT_LIGHT_LIT:
case IT_SPELLBOOK:
// can be equipped, but don't need to be
break;
case IT_LIGHT_OUT:
if ( ! pItem->IsItemInContainer())
break;
default:
if ( ! m_pChar->CanMove( pItem ) ||
! m_pChar->ItemEquip( pItem ))
{
SysMessage( "The item should be equipped to use." );
return false;
}
break;
}
}
SetTargMode();
m_Targ_UID = pItem->GetUID(); // probably already set anyhow.
m_tmUseItem.m_pParent = pItem->GetParent(); // Cheat Verify.
if ( pItem->OnTrigger( ITRIG_DCLICK, m_pChar ) == TRIGRET_RET_TRUE )
{
return true;
}
// Use types of items. (specific to client)
switch ( pItem->GetType() )
{
case IT_TRACKER:
{
DIR_TYPE dir = (DIR_TYPE) ( DIR_QTY + 1 ); // invalid value.
if ( ! m_pChar->Skill_Tracking( pItem->m_uidLink, dir ))
{
if ( pItem->m_uidLink.IsValidUID())
{
SysMessage( "You cannot locate your target" );
}
m_Targ_UID = pItem->GetUID();
addTarget( CLIMODE_TARG_LINK, "Who do you want to attune to ?" );
}
}
return true;
case IT_TRACK_ITEM: // 109 - track a id or type of item.
case IT_TRACK_CHAR: // 110 = track a char or range of char id's
// Track a type of item or creature.
{
// Look in the local area for this item or char.
}
break;
case IT_SHAFT:
case IT_FEATHER:
Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_bolts" ));
return true;
case IT_FISH_POLE: // Just be near water ?
addTarget( CLIMODE_TARG_USE_ITEM, "Where would you like to fish?", true );
return true;
case IT_DEED:
addTargetDeed( pItem );
return true;
case IT_METRONOME:
pItem->OnTick();
return true;
case IT_EQ_BANK_BOX:
case IT_EQ_VENDOR_BOX:
g_Log.Event( LOGL_WARN|LOGM_CHEAT,
"%x:Cheater '%s' is using 3rd party tools to open bank box\n",
m_Socket.GetSocket(), (LPCTSTR) GetAccount()->GetName());
return false;
case IT_CONTAINER_LOCKED:
case IT_SHIP_HOLD_LOCK:
if ( ! m_pChar->GetPackSafe()->ContentFindKeyFor( pItem ))
{
SysMessage( "This item is locked.");
if ( ! IsPriv( PRIV_GM ))
return false;
}
case IT_CORPSE:
case IT_SHIP_HOLD:
case IT_CONTAINER:
case IT_TRASH_CAN:
{
CItemContainer * pPack = dynamic_cast <CItemContainer *>(pItem);
if ( ! m_pChar->Skill_Snoop_Check( pPack ))
{
if ( ! addContainerSetup( pPack ))
return false;
}
}
return true;
case IT_GAME_BOARD:
if ( ! pItem->IsTopLevel())
{
SysMessage( "Can't open game board in a container" );
return false;
}
{
CItemContainer* pBoard = dynamic_cast <CItemContainer *>(pItem);
ASSERT(pBoard);
pBoard->Game_Create();
addContainerSetup( pBoard );
}
return true;
case IT_BBOARD:
addBulletinBoard( dynamic_cast<CItemContainer *>(pItem));
return true;
case IT_SIGN_GUMP:
// Things like grave stones and sign plaques.
// Need custom gumps.
{
GUMP_TYPE gumpid = pItemDef->m_ttContainer.m_gumpid;
if ( ! gumpid )
{
return false;
}
addGumpTextDisp( pItem, gumpid, pItem->GetName(),
( pItem->IsIndividualName()) ? pItem->GetName() : NULL );
}
return true;
case IT_BOOK:
case IT_MESSAGE:
case IT_EQ_NPC_SCRIPT:
case IT_EQ_MESSAGE:
if ( ! addBookOpen( pItem ))
{
SysMessage( "The book apears to be ruined!" );
}
return true;
case IT_STONE_GUILD:
case IT_STONE_TOWN:
case IT_STONE_ROOM:
// Guild and town stones.
{
CItemStone * pStone = dynamic_cast<CItemStone*>(pItem);
if ( pStone == NULL )
break;
pStone->Use_Item( this );
}
return true;
case IT_ADVANCE_GATE:
// Upgrade the player to the skills of the selected NPC script.
m_pChar->Use_AdvanceGate( pItem );
return true;
case IT_POTION:
if ( ! m_pChar->CanMove( pItem )) // locked down decoration.
{
SysMessage( "You can't move the item." );
return false;
}
if ( RES_GET_INDEX(pItem->m_itPotion.m_Type) == SPELL_Poison )
{
// ask them what they want to use the poison on ?
// Poisoning or poison self ?
addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to use this on?", false, true );
return true;
}
else if ( RES_GET_INDEX(pItem->m_itPotion.m_Type) == SPELL_Explosion )
{
// Throw explode potion.
if ( ! m_pChar->ItemPickup( pItem, 1 ))
return true;
m_tmUseItem.m_pParent = pItem->GetParent(); // Cheat Verify FIX.
addTarget( CLIMODE_TARG_USE_ITEM, "Where do you want to throw the potion?", true, true );
// Put the potion in our hand as well. (and set it's timer)
pItem->m_itPotion.m_tick = 4; // countdown to explode purple.
pItem->SetTimeout( TICK_PER_SEC );
pItem->m_uidLink = m_pChar->GetUID();
return true;
}
if ( m_pChar->Use_Drink( pItem ))
return true;
break;
case IT_ANIM_ACTIVE:
SysMessage( "The item is in use" );
return false;
case IT_CLOCK:
addObjMessage( m_pChar->GetTopSector()->GetLocalGameTime(), pItem );
return true;
case IT_SPAWN_CHAR:
SysMessage( "You negate the spawn" );
pItem->Spawn_KillChildren();
return true;
case IT_SPAWN_ITEM:
SysMessage( "You trigger the spawn." );
pItem->Spawn_OnTick( true );
return true;
case IT_SHRINE:
if ( m_pChar->OnSpellEffect( SPELL_Resurrection, m_pChar, 1000, pItem ))
return true;
SysMessage( "You have a feeling of holiness" );
return true;
case IT_SHIP_TILLER:
// dclick on tiller man.
pItem->Speak( "Arrg stop that.", 0, TALKMODE_SAY, FONT_NORMAL );
return true;
// A menu or such other action ( not instantanious)
case IT_WAND:
case IT_SCROLL: // activate the scroll.
return Cmd_Skill_Magery( (SPELL_TYPE)RES_GET_INDEX(pItem->m_itWeapon.m_spell), pItem );
case IT_RUNE:
// name the rune.
if ( ! m_pChar->CanMove( pItem, true ))
{
return false;
}
addPromptConsole( CLIMODE_PROMPT_NAME_RUNE, "What is the new name of the rune ?" );
return true;
case IT_CARPENTRY:
// Carpentry type tool
Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_carpentry" ));
return true;
// Solve for the combination of this item with another.
case IT_FORGE:
addTarget( CLIMODE_TARG_USE_ITEM, "Select ore to smelt." );
return true;
case IT_ORE:
// just use the nearest forge.
return m_pChar->Skill_Mining_Smelt( pItem, NULL );
case IT_INGOT:
return Cmd_Skill_Smith( pItem );
case IT_KEY:
case IT_KEYRING:
if ( pItem->GetTopLevelObj() != m_pChar && ! m_pChar->IsPriv(PRIV_GM))
{
SysMessage( "The key must be on your person" );
return false;
}
addTarget( CLIMODE_TARG_USE_ITEM, "Select item to use the key on.", false, true );
return true;
case IT_BANDAGE: // SKILL_HEALING, or SKILL_VETERINARY
addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to use this on?", false, false );
return true;
case IT_BANDAGE_BLOOD: // Clean the bandages.
case IT_COTTON: // use on a spinning wheel.
case IT_WOOL: // use on a spinning wheel.
case IT_YARN: // Use this on a loom.
case IT_THREAD: // Use this on a loom.
case IT_COMM_CRYSTAL:
case IT_SCISSORS:
case IT_LOCKPICK: // Use on a locked thing.
case IT_CARPENTRY_CHOP:
case IT_WEAPON_MACE_STAFF:
case IT_WEAPON_MACE_SMITH: // Can be used for smithing ?
case IT_WEAPON_MACE_SHARP: // war axe can be used to cut/chop trees.
case IT_WEAPON_SWORD: // 23 =
case IT_WEAPON_FENCE: // 24 = can't be used to chop trees.
case IT_WEAPON_AXE:
addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to use this on?", false, true );
return true;
case IT_MEAT_RAW:
case IT_FOOD_RAW:
addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to cook this on?" );
return true;
case IT_FISH:
SysMessage( "Use a knife to cut this up" );
return true;
case IT_TELESCOPE:
// Big telescope.
SysMessage( "Wow you can see the sky!" );
return true;
case IT_MAP:
case IT_MAP_BLANK:
if ( ! pItem->m_itMap.m_right && ! pItem->m_itMap.m_bottom )
{
Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_cartography" ));
}
else if ( ! IsPriv(PRIV_GM) && pItem->GetTopLevelObj() != m_pChar ) // must be on your person.
{
SysMessage( "You must possess the map to get a good look at it." );
}
else
{
addMap( dynamic_cast <CItemMap*>( pItem ));
}
return true;
case IT_CANNON_BALL:
{
CGString sTmp;
sTmp.Format( "What do you want to use the %s on?", (LPCTSTR) pItem->GetName());
addTarget( CLIMODE_TARG_USE_ITEM, sTmp );
}
return true;
case IT_CANNON_MUZZLE:
// Make sure the cannon is loaded.
if ( ! m_pChar->CanUse( pItem, false ))
return( false );
if ( ! ( pItem->m_itCannon.m_Load & 1 ))
{
addTarget( CLIMODE_TARG_USE_ITEM, "The cannon needs powder" );
return true;
}
if ( ! ( pItem->m_itCannon.m_Load & 2 ))
{
addTarget( CLIMODE_TARG_USE_ITEM, "The cannon needs shot" );
return true;
}
addTarget( CLIMODE_TARG_USE_ITEM, "Armed and ready. What is the target?", false, true );
return true;
case IT_CRYSTAL_BALL:
// Gaze into the crystal ball.
return true;
case IT_WEAPON_MACE_CROOK:
addTarget( CLIMODE_TARG_USE_ITEM, "What would you like to herd?", false, true );
return true;
case IT_SEED:
case IT_PITCHER_EMPTY:
{ // not a crime.
CGString sTmp;
sTmp.Format( "Where do you want to use the %s?", (LPCTSTR) pItem->GetName());
addTarget( CLIMODE_TARG_USE_ITEM, sTmp, true );
}
return true;
case IT_WEAPON_MACE_PICK:
{ // Mine at the location. (possible crime?)
CGString sTmp;
sTmp.Format( "Where do you want to use the %s?", (LPCTSTR) pItem->GetName());
addTarget( CLIMODE_TARG_USE_ITEM, sTmp, true, true );
}
return true;
case IT_SPELLBOOK:
addSpellbookOpen( pItem );
return true;
case IT_HAIR_DYE:
if (!m_pChar->LayerFind( LAYER_BEARD ) && !m_pChar->LayerFind( LAYER_HAIR ))
{
SysMessage("You have no hair to dye!");
return true;
}
Dialog_Setup( CLIMODE_DIALOG_HAIR_DYE, g_Cfg.ResourceGetIDType( RES_DIALOG, "d_HAIR_DYE" ), m_pChar );
return true;
case IT_DYE:
addTarget( CLIMODE_TARG_USE_ITEM, "Which dye vat will you use this on?" );
return true;
case IT_DYE_VAT:
addTarget( CLIMODE_TARG_USE_ITEM, "Select the object to use this on.", false, true );
return true;
case IT_MORTAR:
// If we have a mortar then do alchemy.
addTarget( CLIMODE_TARG_USE_ITEM, "What reagent you like to make a potion out of?" );
return true;
case IT_POTION_EMPTY:
if ( ! m_pChar->ContentFind(RESOURCE_ID(RES_TYPEDEF,IT_MORTAR)))
{
SysMessage( "You have no mortar and pestle." );
return( false );
}
addTarget( CLIMODE_TARG_USE_ITEM, "What reagent you like to make a potion out of?" );
return true;
case IT_REAGENT:
// Make a potion with this. (The best type we can)
if ( ! m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_MORTAR)))
{
SysMessage( "You have no mortar and pestle." );
return false;
}
Cmd_Skill_Alchemy( pItem );
return true;
// Put up menus to better decide what to do.
case IT_TINKER_TOOLS: // Tinker tools.
Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_tinker" ));
return true;
case IT_SEWING_KIT: // IT_SEWING_KIT Sew with materials we have on hand.
{
CGString sTmp;
sTmp.Format( "What do you want to use the %s on?", (LPCTSTR) pItem->GetName());
addTarget( CLIMODE_TARG_USE_ITEM, sTmp );
}
return true;
case IT_SCROLL_BLANK:
Cmd_Skill_Inscription();
return true;
default:
// An NPC could use it this way.
if ( m_pChar->Use_Item( pItem ))
return( true );
break;
}
SysMessage( "You can't think of a way to use that item.");
return( false );
}
void CClient::Cmd_EditItem( CObjBase * pObj, int iSelect )
{
// ARGS:
// iSelect == -1 = setup.
// m_Targ_Text = what are we doing to it ?
//
if ( pObj == NULL )
return;
CContainer * pContainer = dynamic_cast <CContainer *> (pObj);
if ( pContainer == NULL )
{
addGumpDialogProps( pObj->GetUID());
return;
}
if ( iSelect == 0 )
return; // cancelled.
if ( iSelect > 0 )
{
// We selected an item.
if ( iSelect >= COUNTOF(m_tmMenu.m_Item))
return;
if ( m_Targ_Text.IsEmpty())
{
addGumpDialogProps( m_tmMenu.m_Item );
}
else
{
OnTarg_Obj_Set( CGrayUID( m_tmMenu.m_Item ).ObjFind() );
}
return;
}
CMenuItem item; // Most as we want to display at one time.
item.m_sText.Format( "Contents of %s", (LPCTSTR) pObj->GetName());
int count=0;
for ( CItem * pItem = pContainer->GetContentHead(); pItem != NULL; pItem = pItem->GetNext())
{
if ( count >= COUNTOF( item ))
break;
m_tmMenu.m_Item = pItem->GetUID();
item.m_sText = pItem->GetName();
ITEMID_TYPE idi = pItem->GetDispID();
item.m_id = idi;
}
addItemMenu( CLIMODE_MENU_EDIT, item, count, pObj );
}
bool CClient::Cmd_CreateItem( ITEMID_TYPE id, bool fStatic )
{
// make an item near by.
m_tmAdd.m_id = id;
m_tmAdd.m_fStatic = fStatic;
return addTargetItems( CLIMODE_TARG_ADDITEM, m_tmAdd.m_id );
}
bool CClient::Cmd_CreateChar( CREID_TYPE id, SPELL_TYPE iSpell, bool fPet )
{
// make a creature near by. (GM or script used only)
// "ADDNPC"
// spell = SPELL_Summon
ASSERT(m_pChar);
m_tmSkillMagery.m_Spell = iSpell; // m_atMagery.m_Spell
m_tmSkillMagery.m_SummonID = id; // m_atMagery.m_SummonID
m_tmSkillMagery.m_fSummonPet = fPet;
if ( ! m_Targ_PrvUID.IsValidUID())
{
m_Targ_PrvUID = m_pChar->GetUID(); // what id this was already a scroll.
}
const CSpellDef * pSpellDef = g_Cfg.GetSpellDef( iSpell );
ASSERT( pSpellDef );
return addTargetChars( CLIMODE_TARG_SKILL_MAGERY, id, pSpellDef->IsSpellType( SPELLFLAG_HARM ));
}
bool CClient::Cmd_Skill_Menu( RESOURCE_ID_BASE rid, int iSelect )
{
// Build the skill menu for the curent active skill.
// Only list the things we have skill and ingrediants to make.
//
// ARGS:
// m_Targ_UID = the object used to get us here.
// rid = which menu ?
// iSelect = -2 = Just a test of the whole menu.,
// iSelect = -1 = 1st setup.
// iSelect = 0 = cancel
// iSelect = x = execute the selection.
//
// RETURN: false = fail/cancel the skill.
// m_tmMenu.m_Item = the menu entries.
ASSERT(m_pChar);
if ( iSelect == 0 || rid.GetResType() != RES_SKILLMENU )
return( false );
int iDifficulty = 0;
// Find section.
CResourceLock s;
if ( ! g_Cfg.ResourceLock( s, rid ))
{
return false;
}
// Get title line
if ( ! s.ReadKey())
return( false );
CMenuItem item;
if ( iSelect < 0 )
{
item.m_sText = s.GetKey();
if ( iSelect == -1 )
{
m_tmMenu.m_ResourceID = rid;
}
}
bool fSkip = false; // skip this if we lack resources or skill.
bool fSuccess = false;
int iOnCount = 0;
int iShowCount = 0;
bool fShowMenu = false; // are we showing a menu?
while ( s.ReadKeyParse())
{
if ( s.IsKeyHead( "ON", 2 ))
{
// a new option to look at.
fSkip = false;
iOnCount ++;
if ( iSelect < 0 ) // building up the list.
{
if ( iSelect < -1 && iShowCount >= 1 ) // just a test. so we are done.
{
return( true );
}
iShowCount ++;
if ( ! item.ParseLine( s.GetArgRaw(), NULL, m_pChar ))
{
// remove if the item is invalid.
iShowCount --;
fSkip = true;
continue;
}
if ( iSelect == -1 )
{
m_tmMenu.m_Item = iOnCount;
}
if ( iShowCount >= COUNTOF( item )-1 )
break;
}
else
{
if ( iOnCount > iSelect ) // we are done.
break;
}
continue;
}
if ( fSkip ) // we have decided we cant do this option.
continue;
if ( iSelect > 0 && iOnCount != iSelect ) // only interested in the selected option
continue;
// Check for a skill / non-consumables required.
if ( s.IsKey("TEST"))
{
CResourceQtyArray skills( s.GetArgStr());
if ( ! skills.IsResourceMatchAll(m_pChar))
{
iShowCount--;
fSkip = true;
}
continue;
}
if ( s.IsKey("TESTIF"))
{
m_pChar->ParseText( s.GetArgRaw(), m_pChar );
if ( ! s.GetArgVal())
{
iShowCount--;
fSkip = true;
}
continue;
}
// select to execute any entries here ?
if ( iOnCount == iSelect )
{
m_pChar->m_Act_Targ = m_Targ_UID;
// Execute command from script
TRIGRET_TYPE tRet = m_pChar->OnTriggerRun( s, TRIGRUN_SINGLE_EXEC, m_pChar );
if ( tRet == TRIGRET_RET_TRUE )
{
return( false );
}
fSuccess = true; // we are good. but continue til the end
}
else
{
ASSERT( iSelect < 0 );
if ( s.IsKey("SKILLMENU"))
{
// Test if there is anything in this skillmenu we can do.
if ( ! Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, s.GetArgStr()), iSelect-1 ))
{
iShowCount--;
fSkip = true;
}
else
{
fShowMenu = true;
ASSERT( ! fSkip );
}
continue;
}
if ( s.IsKey("MAKEITEM"))
{
// test if i can make this item using m_Targ_UID.
// There should ALWAYS be a valid id here.
if ( ! m_pChar->Skill_MakeItem( (ITEMID_TYPE) g_Cfg.ResourceGetIndexType( RES_ITEMDEF, s.GetArgS
tr()),
m_Targ_UID, SKTRIG_SELECT ))
{
iShowCount--;
fSkip = true;
}
continue;
}
}
}
if ( iSelect < -1 ) // just a test.
{
return( iShowCount ? true : false );
}
if ( iSelect > 0 ) // seems our resources disappeared.
{
if ( ! fSuccess )
{
SysMessage( "You can't make that." );
}
return( fSuccess );
}
if ( ! iShowCount )
{
SysMessage( "You can't make anything with what you have." );
return( false );
}
if ( iShowCount == 1 && fShowMenu )
{
// If there is just one menu then select it.
return( Cmd_Skill_Menu( rid, m_tmMenu.m_Item ));
}
addItemMenu( CLIMODE_MENU_SKILL, item, iShowCount );
return( true );
}
bool CClient::Cmd_Skill_Magery( SPELL_TYPE iSpell, CObjBase * pSrc )
{
// start casting a spell. prompt for target.
// pSrc = you the char.
// pSrc = magic object is source ?
static const TCHAR sm_Txt_Summon = "Where would you like to summon the creature ?";
// Do we have the regs ? etc.
ASSERT(m_pChar);
if ( ! m_pChar->Spell_CanCast( iSpell, true, pSrc, true ))
return false;
const CSpellDef * pSpellDef = g_Cfg.GetSpellDef( iSpell );
ASSERT(pSpellDef);
if ( g_Log.IsLogged( LOGL_TRACE ))
{
DEBUG_MSG(( "%x:Cast Spell %d='%s'\n", m_Socket.GetSocket(), iSpell, pSpellDef->GetName()));
}
SetTargMode();
m_tmSkillMagery.m_Spell = iSpell; // m_atMagery.m_Spell
m_Targ_UID = m_pChar->GetUID(); // default target.
m_Targ_PrvUID = pSrc->GetUID(); // source of the spell.
LPCTSTR pPrompt = "Select Target";
switch ( iSpell )
{
case SPELL_Recall:
pPrompt = "Select rune to recall from.";
break;
case SPELL_Blade_Spirit:
pPrompt = sm_Txt_Summon;
break;
case SPELL_Summon:
return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_summon" ));
case SPELL_Mark:
pPrompt = "Select rune to mark.";
break;
case SPELL_Gate_Travel: // gate travel
pPrompt = "Select rune to gate from.";
break;
case SPELL_Polymorph:
// polymorph creature menu.
if ( IsPriv(PRIV_GM))
{
pPrompt = "Select creature to polymorph.";
break;
}
return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_polymorph" ));
case SPELL_Earthquake:
// cast immediately with no targetting.
m_pChar->m_atMagery.m_Spell = SPELL_Earthquake;
m_pChar->m_Act_Targ = m_Targ_UID;
m_pChar->m_Act_TargPrv = m_Targ_PrvUID;
m_pChar->m_Act_p = m_pChar->GetTopPoint();
return( m_pChar->Skill_Start( SKILL_MAGERY ));
case SPELL_Resurrection:
pPrompt = "Select ghost to resurrect.";
break;
case SPELL_Vortex:
case SPELL_Air_Elem:
case SPELL_Daemon:
case SPELL_Earth_Elem:
case SPELL_Fire_Elem:
case SPELL_Water_Elem:
pPrompt = sm_Txt_Summon;
break;
// Necro spells
case SPELL_Summon_Undead: // Summon an undead
pPrompt = sm_Txt_Summon;
break;
case SPELL_Animate_Dead: // Corpse to zombie
pPrompt = "Choose a corpse";
break;
case SPELL_Bone_Armor: // Skeleton corpse to bone armor
pPrompt = "Chose a skeleton";
break;
}
addTarget( CLIMODE_TARG_SKILL_MAGERY, pPrompt,
! pSpellDef->IsSpellType( SPELLFLAG_TARG_OBJ | SPELLFLAG_TARG_CHAR ),
pSpellDef->IsSpellType( SPELLFLAG_HARM ));
return( true );
}
bool CClient::Cmd_Skill_Tracking( int track_sel, bool fExec )
{
// look around for stuff.
ASSERT(m_pChar);
if ( track_sel < 0 )
{
// Initial pre-track setup.
if ( m_pChar->m_pArea->IsFlag( REGION_FLAG_SHIP ) &&
! m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_SPY_GLASS)) )
{
SysMessage( "You need a Spyglass to use tracking here." );
return( false );
}
// Tacking (unlike other skills) is used during menu setup.
m_pChar->Skill_Fail( true ); // Kill previous skill.
CMenuItem item;
item.m_sText = "Tracking";
item.m_id = ITEMID_TRACK_HORSE;
item.m_sText = "Animals";
item.m_id = ITEMID_TRACK_OGRE;
item.m_sText = "Monsters";
item.m_id = ITEMID_TRACK_MAN;
item.m_sText = "Humans";
item.m_id = ITEMID_TRACK_MAN_NAKED;
item.m_sText = "Players";
item.m_id = ITEMID_TRACK_WISP;
item.m_sText = "Anything that moves";
m_tmMenu.m_Item = 0;
addItemMenu( CLIMODE_MENU_SKILL_TRACK_SETUP, item, 5 );
return( true );
}
if ( track_sel ) // Not Cancelled
{
ASSERT( ((WORD)track_sel) < COUNTOF( m_tmMenu.m_Item ));
if ( fExec )
{
// Tracking menu got us here. Start tracking the selected creature.
m_pChar->SetTimeout( 1*TICK_PER_SEC );
m_pChar->m_Act_Targ = m_tmMenu.m_Item; // selected UID
m_pChar->Skill_Start( SKILL_TRACKING );
return true;
}
bool fGM = IsPriv(PRIV_GM);
static const NPCBRAIN_TYPE sm_Track_Brain =
{
NPCBRAIN_QTY, // not used here.
NPCBRAIN_ANIMAL,
NPCBRAIN_MONSTER,
NPCBRAIN_HUMAN,
NPCBRAIN_NONE, // players
NPCBRAIN_QTY, // anything.
};
if ( track_sel >= COUNTOF(sm_Track_Brain))
track_sel = COUNTOF(sm_Track_Brain)-1;
NPCBRAIN_TYPE track_type = sm_Track_Brain;
CMenuItem item;
int count = 0;
item.m_sText = "Tracking";
m_tmMenu.m_Item = track_sel;
CWorldSearch AreaChars( m_pChar->GetTopPoint(), m_pChar->Skill_GetBase(SKILL_TRACKING)/20 + 10 );
while (true)
{
CChar * pChar = AreaChars.GetChar();
if ( pChar == NULL )
break;
if ( m_pChar == pChar )
continue;
if ( ! m_pChar->CanDisturb( pChar ))
continue;
CCharBase * pCharDef = pChar->Char_GetDef();
NPCBRAIN_TYPE basic_type = pChar->GetCreatureType();
if ( track_type != basic_type && track_type != NPCBRAIN_QTY )
{
if ( track_type != NPCBRAIN_NONE ) // no match.
{
continue;
}
// players
if ( ! pChar->m_pPlayer )
continue;
if ( ! fGM && basic_type != NPCBRAIN_HUMAN ) // can't track polymorphed person.
continue;
}
if ( ! fGM && ! pCharDef->Can( CAN_C_WALK )) // never moves or just swims.
continue;
count ++;
item.m_id = pCharDef->m_trackID;
item.m_sText = pChar->GetName();
m_tmMenu.m_Item = pChar->GetUID();
if ( count >= COUNTOF( item )-1 )
break;
}
if ( count )
{
// Some credit for trying.
m_pChar->Skill_UseQuick( SKILL_TRACKING, 20 + Calc_GetRandVal( 30 ));
addItemMenu( CLIMODE_MENU_SKILL_TRACK, item, count );
return( true );
}
else
{
// Some credit for trying.
m_pChar->Skill_UseQuick( SKILL_TRACKING, 10 + Calc_GetRandVal( 30 ));
}
}
// Tracking failed or was cancelled .
static LPCTSTR const sm_Track_FailMsg =
{
"Tracking Cancelled",
"You see no signs of animals to track.",
"You see no signs of monsters to track.",
"You see no signs of humans to track.",
"You see no signs of players to track.",
"You see no signs to track."
};
SysMessage( sm_Track_FailMsg );
return( false );
}
bool CClient::Cmd_Skill_Smith( CItem * pIngots )
{
ASSERT(m_pChar);
if ( pIngots == NULL || ! pIngots->IsType(IT_INGOT))
{
SysMessage( "You need ingots for smithing." );
return( false );
}
ASSERT( m_Targ_UID == pIngots->GetUID());
if ( pIngots->GetTopLevelObj() != m_pChar )
{
SysMessage( "The ingots must be on your person" );
return( false );
}
// must have hammer equipped.
CItem * pHammer = m_pChar->LayerFind( LAYER_HAND1 );
if ( pHammer == NULL || ! pHammer->IsType(IT_WEAPON_MACE_SMITH))
{
SysMessage( "You must weild a smith hammer of some sort." );
return( false );
}
// Select the blacksmith item type.
// repair items or make type of items.
if ( ! g_World.IsItemTypeNear( m_pChar->GetTopPoint(), IT_FORGE, 3 ))
{
SysMessage( "You must be near a forge to smith ingots" );
return( false );
}
// Select the blacksmith item type.
// repair items or make type of items.
return( Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU,"sm_blacksmith" )));
}
bool CClient::Cmd_Skill_Inscription()
{
// Select the scroll type to make.
// iSelect = -1 = 1st setup.
// iSelect = 0 = cancel
// iSelect = x = execute the selection.
// we should already be in inscription skill mode.
ASSERT(m_pChar);
CItem * pBlank = m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_SCROLL_BLANK));
if ( pBlank == NULL )
{
SysMessage( "You have no blank scrolls" );
return( false );
}
return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_inscription" ) );
}
bool CClient::Cmd_Skill_Alchemy( CItem * pReag )
{
// SKILL_ALCHEMY
if ( pReag == NULL )
return( false );
ASSERT(m_pChar);
if ( ! m_pChar->CanUse( pReag, true ))
return( false );
if ( ! pReag->IsType(IT_REAGENT))
{
// That is not a reagent.
SysMessage( "That is not a reagent." );
return( false );
}
// Find bottles to put potions in.
if ( ! m_pChar->ContentFind(RESOURCE_ID(RES_TYPEDEF,IT_POTION_EMPTY)))
{
SysMessage( "You have no bottles for your potion." );
return( false );
}
m_Targ_UID = pReag->GetUID();
// Put up a menu to decide formula ?
return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_alchemy" ));
}
bool CClient::Cmd_Skill_Cartography( int iLevel )
{
// select the map type.
ASSERT(m_pChar);
if ( m_pChar->Skill_Wait(SKILL_CARTOGRAPHY))
return( false );
if ( ! m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_MAP_BLANK)))
{
SysMessage( "You have no blank parchment to draw on" );
return( false );
}
return( Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_cartography" )));
}
bool CClient::Cmd_SecureTrade( CChar * pChar, CItem * pItem )
{
// Begin secure trading with a char. (Make the initial offer)
ASSERT(m_pChar);
// Trade window only if another PC.
if ( ! pChar->IsClient())
{
return( pChar->NPC_OnItemGive( m_pChar, pItem ));
}
// Is there already a trade window open for this client ?
CItem * pItemCont = m_pChar->GetContentHead();
for ( ; pItemCont != NULL; pItemCont = pItemCont->GetNext())
{
if ( ! pItemCont->IsType(IT_EQ_TRADE_WINDOW))
continue; // found it
CItem * pItemPartner = pItemCont->m_uidLink.ItemFind(); // counterpart trade window.
if ( pItemPartner == NULL )
continue;
CChar * pCharPartner = dynamic_cast <CChar*>( pItemPartner->GetParent());
if ( pCharPartner != pChar )
continue;
CItemContainer * pCont = dynamic_cast <CItemContainer *>( pItemCont );
ASSERT(pCont);
pCont->ContentAdd( pItem );
return( true );
}
// Open a new one.
CItemContainer* pCont1 = dynamic_cast <CItemContainer*> (CItem::CreateBase( ITEMID_Bulletin1 ));
ASSERT(pCont1);
pCont1->SetType( IT_EQ_TRADE_WINDOW );
CItemContainer* pCont2 = dynamic_cast <CItemContainer*> (CItem::CreateBase( ITEMID_Bulletin1 ));
ASSERT(pCont2);
pCont2->SetType( IT_EQ_TRADE_WINDOW );
pCont1->m_itEqTradeWindow.m_fCheck = false;
pCont1->m_uidLink = pCont2->GetUID();
pCont2->m_itEqTradeWindow.m_fCheck = false;
pCont2->m_uidLink = pCont1->GetUID();
m_pChar->LayerAdd( pCont1, LAYER_SPECIAL );
pChar->LayerAdd( pCont2, LAYER_SPECIAL );
CCommand cmd;
int len = sizeof(cmd.SecureTrade);
cmd.SecureTrade.m_Cmd = XCMD_SecureTrade;
cmd.SecureTrade.m_len = len;
cmd.SecureTrade.m_action = SECURE_TRADE_OPEN; // init
cmd.SecureTrade.m_UID = pChar->GetUID();
cmd.SecureTrade.m_UID1 = pCont1->GetUID();
cmd.SecureTrade.m_UID2 = pCont2->GetUID();
cmd.SecureTrade.m_fname = 1;
strcpy( cmd.SecureTrade.m_charname, pChar->GetName());
xSendPkt( &cmd, len );
cmd.SecureTrade.m_UID = m_pChar->GetUID();
cmd.SecureTrade.m_UID1 = pCont2->GetUID();
cmd.SecureTrade.m_UID2 = pCont1->GetUID();
strcpy( cmd.SecureTrade.m_charname, m_pChar->GetName());
pChar->GetClient()->xSendPkt( &cmd, len );
CPointMap pt( 30, 30, 9 );
pCont1->ContentAdd( pItem, pt );
return( true );
} | 37.997387 | 128 | 0.448683 | Jhobean |
3e4cfcfc136208f6fd1cee1a5de6a73ef1e68e7e | 4,302 | cpp | C++ | enhanced/java/jdktools/modules/jpda/src/main/native/jdwp/common/agent/commands/ArrayType.cpp | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 5 | 2017-03-08T20:32:39.000Z | 2021-07-10T10:12:38.000Z | enhanced/java/jdktools/modules/jpda/src/main/native/jdwp/common/agent/commands/ArrayType.cpp | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | null | null | null | enhanced/java/jdktools/modules/jpda/src/main/native/jdwp/common/agent/commands/ArrayType.cpp | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 4 | 2015-07-07T07:06:59.000Z | 2018-06-19T22:38:04.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Viacheslav G. Rybalov
*/
#include <string.h>
#include "ArrayType.h"
#include "PacketParser.h"
#include "ClassManager.h"
using namespace jdwp;
using namespace ArrayType;
void
ArrayType::NewInstanceHandler::Execute(JNIEnv *jni) throw(AgentException)
{
jclass cls = m_cmdParser->command.ReadReferenceTypeID(jni);
jint length = m_cmdParser->command.ReadInt();
JDWP_ASSERT(cls != 0);
char* signature = 0;
jvmtiError err;
JVMTI_TRACE(err, GetJvmtiEnv()->GetClassSignature(cls, &signature, 0));
JvmtiAutoFree afv1(signature);
if (err != JVMTI_ERROR_NONE) {
throw AgentException(err);
}
JDWP_TRACE_DATA("NewInstance: received: refTypeID=" << cls
<< ", length=" << length
<< ", signature=" << JDWP_CHECK_NULL(signature));
if ((signature == 0) || (strlen(signature) < 2)) {
throw AgentException(JDWP_ERROR_INVALID_OBJECT);
}
if(signature[0] != '[') {
throw AgentException(JDWP_ERROR_INVALID_ARRAY);
}
jarray arr = 0;
switch (signature[1]) {
case 'Z': {
JDWP_TRACE_DATA("NewInstance: new boolean array");
arr = jni->NewBooleanArray(length);
break;
}
case 'B': {
JDWP_TRACE_DATA("NewInstance: new byte array");
arr = jni->NewByteArray(length);
break;
}
case 'C': {
JDWP_TRACE_DATA("NewInstance: new char array");
arr = jni->NewCharArray(length);
break;
}
case 'S': {
JDWP_TRACE_DATA("NewInstance: new short array");
arr = jni->NewShortArray(length);
break;
}
case 'I': {
JDWP_TRACE_DATA("NewInstance: new int array");
arr = jni->NewIntArray(length);
break;
}
case 'J': {
JDWP_TRACE_DATA("NewInstance: new long array");
arr = jni->NewLongArray(length);
break;
}
case 'F': {
arr = jni->NewFloatArray(length);
JDWP_TRACE_DATA("NewInstance: new float array");
break;
}
case 'D': {
JDWP_TRACE_DATA("NewInstance: new double array");
arr = jni->NewDoubleArray(length);
break;
}
case 'L':
case '[': {
char* name = GetClassManager().GetClassName(&signature[1]);
JvmtiAutoFree jafn(name);
jobject loader;
JVMTI_TRACE(err, GetJvmtiEnv()->GetClassLoader(cls, &loader));
if (err != JVMTI_ERROR_NONE) {
throw AgentException(err);
}
jclass elementClass =
GetClassManager().GetClassForName(jni, name, loader);
JDWP_TRACE_DATA("NewInstance: new object array: "
"class=" << JDWP_CHECK_NULL(name));
arr = jni->NewObjectArray(length, elementClass, 0);
break;
}
default:
JDWP_TRACE_DATA("NewInstance: bad type signature: "
<< JDWP_CHECK_NULL(signature));
throw AgentException(JDWP_ERROR_INVALID_ARRAY);
}
GetClassManager().CheckOnException(jni);
if (arr == 0) {
throw AgentException(JDWP_ERROR_OUT_OF_MEMORY);
}
JDWP_TRACE_DATA("NewInstance: send: tag=" << JDWP_TAG_ARRAY
<< ", newArray=" << arr);
m_cmdParser->reply.WriteByte(JDWP_TAG_ARRAY);
m_cmdParser->reply.WriteArrayID(jni, arr);
}
| 33.348837 | 76 | 0.597164 | qinFamily |
3e501e3c663f32cc489b740f08f77dc1f38e4164 | 131 | cpp | C++ | 2DGame/logger.cpp | Cimera42/2DGame | 9135e3dbed8a909357d57e227ecaba885982e8dc | [
"MIT"
] | 3 | 2015-08-18T12:59:29.000Z | 2015-12-15T08:11:10.000Z | 2DGame/logger.cpp | Cimera42/2DGame | 9135e3dbed8a909357d57e227ecaba885982e8dc | [
"MIT"
] | null | null | null | 2DGame/logger.cpp | Cimera42/2DGame | 9135e3dbed8a909357d57e227ecaba885982e8dc | [
"MIT"
] | null | null | null | #include "logger.h"
//Mutex for cout
//Prevent interleaving of output
pthread_mutex_t coutMutex = PTHREAD_MUTEX_INITIALIZER;
| 21.833333 | 55 | 0.778626 | Cimera42 |
3e50b9799a853d48b3b61068cbf648b0b3befd2e | 3,793 | cpp | C++ | src/DNG/dng_memory.cpp | Jamaika1/pgm2dng | a3e31c3dd448f91b1562d1248ae340d0d20af68d | [
"MIT"
] | 7 | 2020-05-29T14:35:13.000Z | 2021-09-14T12:37:12.000Z | src/DNG/dng_memory.cpp | Jamaika1/pgm2dng | a3e31c3dd448f91b1562d1248ae340d0d20af68d | [
"MIT"
] | null | null | null | src/DNG/dng_memory.cpp | Jamaika1/pgm2dng | a3e31c3dd448f91b1562d1248ae340d0d20af68d | [
"MIT"
] | 3 | 2020-11-10T06:33:08.000Z | 2021-06-13T05:40:53.000Z | /*****************************************************************************/
// Copyright 2006 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in
// accordance with the terms of the Adobe license agreement accompanying it.
/*****************************************************************************/
/* $Id: //mondo/dng_sdk_1_4/dng_sdk/source/dng_memory.cpp#1 $ */
/* $DateTime: 2012/05/30 13:28:51 $ */
/* $Change: 832332 $ */
/* $Author: tknoll $ */
/*****************************************************************************/
#include "dng_memory.h"
#include "dng_bottlenecks.h"
#include "dng_exceptions.h"
/*****************************************************************************/
dng_memory_data::dng_memory_data ()
: fBuffer (NULL)
{
}
/*****************************************************************************/
dng_memory_data::dng_memory_data (uint32 size)
: fBuffer (NULL)
{
Allocate (size);
}
/*****************************************************************************/
dng_memory_data::~dng_memory_data ()
{
Clear ();
}
/*****************************************************************************/
void dng_memory_data::Allocate (uint32 size)
{
Clear ();
if (size)
{
fBuffer = (char*)malloc (size);
if (!fBuffer)
{
ThrowMemoryFull ();
}
}
}
/*****************************************************************************/
void dng_memory_data::Clear ()
{
if (fBuffer)
{
free (fBuffer);
fBuffer = NULL;
}
}
/*****************************************************************************/
dng_memory_block * dng_memory_block::Clone (dng_memory_allocator &allocator) const
{
uint32 size = LogicalSize ();
dng_memory_block * result = allocator.Allocate (size);
DoCopyBytes (Buffer (), result->Buffer (), size);
return result;
}
/*****************************************************************************/
class dng_malloc_block : public dng_memory_block
{
private:
void *fMalloc;
public:
dng_malloc_block (uint32 logicalSize);
virtual ~dng_malloc_block ();
private:
// Hidden copy constructor and assignment operator.
dng_malloc_block (const dng_malloc_block &block);
dng_malloc_block & operator= (const dng_malloc_block &block);
};
/*****************************************************************************/
dng_malloc_block::dng_malloc_block (uint32 logicalSize)
: dng_memory_block (logicalSize)
, fMalloc (NULL)
{
#if qLinux
int err = ::posix_memalign( (void **) &fMalloc, 16, (size_t) PhysicalSize() );
if (err)
{
ThrowMemoryFull ();
}
#else
fMalloc = (char*)malloc (PhysicalSize ());
if (!fMalloc)
{
ThrowMemoryFull ();
}
#endif
SetBuffer (fMalloc);
}
/*****************************************************************************/
dng_malloc_block::~dng_malloc_block ()
{
if (fMalloc)
{
free (fMalloc);
}
}
/*****************************************************************************/
dng_memory_block * dng_memory_allocator::Allocate (uint32 size)
{
dng_memory_block *result = new dng_malloc_block (size);
if (!result)
{
ThrowMemoryFull ();
}
return result;
}
/*****************************************************************************/
dng_memory_allocator gDefaultDNGMemoryAllocator;
/*****************************************************************************/
| 18.412621 | 83 | 0.403902 | Jamaika1 |
3e536848f7b174c034102c2ca9505d22729c1e55 | 2,251 | cc | C++ | foas/src/model/CommitJobRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | foas/src/model/CommitJobRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | foas/src/model/CommitJobRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/foas/model/CommitJobRequest.h>
using AlibabaCloud::Foas::Model::CommitJobRequest;
CommitJobRequest::CommitJobRequest() :
RoaServiceRequest("foas", "2018-11-11")
{
setResourcePath("/api/v2/projects/[projectName]/jobs/[jobName]/commit");
setMethod(HttpRequest::Method::Put);
}
CommitJobRequest::~CommitJobRequest()
{}
std::string CommitJobRequest::getProjectName()const
{
return projectName_;
}
void CommitJobRequest::setProjectName(const std::string& projectName)
{
projectName_ = projectName;
setParameter("ProjectName", projectName);
}
std::string CommitJobRequest::getRegionId()const
{
return regionId_;
}
void CommitJobRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setHeader("RegionId", regionId);
}
float CommitJobRequest::getMaxCU()const
{
return maxCU_;
}
void CommitJobRequest::setMaxCU(float maxCU)
{
maxCU_ = maxCU;
setBodyParameter("MaxCU", std::to_string(maxCU));
}
std::string CommitJobRequest::getConfigure()const
{
return configure_;
}
void CommitJobRequest::setConfigure(const std::string& configure)
{
configure_ = configure;
setBodyParameter("Configure", configure);
}
bool CommitJobRequest::getIsOnOff()const
{
return isOnOff_;
}
void CommitJobRequest::setIsOnOff(bool isOnOff)
{
isOnOff_ = isOnOff;
setBodyParameter("IsOnOff", isOnOff ? "true" : "false");
}
std::string CommitJobRequest::getJobName()const
{
return jobName_;
}
void CommitJobRequest::setJobName(const std::string& jobName)
{
jobName_ = jobName;
setParameter("JobName", jobName);
}
| 23.206186 | 75 | 0.730786 | iamzken |
3e55deb2f76b90a3e2244497e79be0b1d0a04be3 | 2,269 | cpp | C++ | src/framework/shared/irphandlers/pnp/um/fxpkgpdoum.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 994 | 2015-03-18T21:37:07.000Z | 2019-04-26T04:04:14.000Z | src/framework/shared/irphandlers/pnp/um/fxpkgpdoum.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 13 | 2019-06-13T15:58:03.000Z | 2022-02-18T22:53:35.000Z | src/framework/shared/irphandlers/pnp/um/fxpkgpdoum.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 350 | 2015-03-19T04:29:46.000Z | 2019-05-05T23:26:50.000Z | /*++
Copyright (c) Microsoft Corporation
Module Name:
FxPkgPdoUM.cpp
Abstract:
This module implements the Pnp package for Pdo devices.
Author:
Environment:
User mode only
Revision History:
--*/
#include "pnppriv.hpp"
#include <wdmguid.h>
// Tracing support
#if defined(EVENT_TRACING)
extern "C" {
#include "FxPkgPdoUM.tmh"
}
#endif
_Must_inspect_result_
NTSTATUS
FxPkgPdo::_PnpQueryResources(
__inout FxPkgPnp* This,
__inout FxIrp *Irp
)
{
return ((FxPkgPdo*) This)->PnpQueryResources(Irp);
}
_Must_inspect_result_
NTSTATUS
FxPkgPdo::PnpQueryResources(
__inout FxIrp *Irp
)
/*++
Routine Description:
This method is invoked in response to a Pnp QueryResources IRP. We return
the resources that the device is currently consuming.
Arguments:
Irp - a pointer to the FxIrp
Returns:
NTSTATUS
--*/
{
UNREFERENCED_PARAMETER(Irp);
ASSERTMSG("Not implemented for UMDF\n", FALSE);
return STATUS_NOT_IMPLEMENTED;
}
_Must_inspect_result_
NTSTATUS
FxPkgPdo::_PnpQueryResourceRequirements(
__inout FxPkgPnp* This,
__inout FxIrp *Irp
)
{
return ((FxPkgPdo*) This)->PnpQueryResourceRequirements(Irp);
}
_Must_inspect_result_
NTSTATUS
FxPkgPdo::PnpQueryResourceRequirements(
__inout FxIrp *Irp
)
/*++
Routine Description:
This method is invoked in response to a Pnp QueryResourceRequirements IRP.
We return the set (of sets) of possible resources that we could accept
which would allow our device to work.
Arguments:
Irp - a pointer to the FxIrp
Returns:
NTSTATUS
--*/
{
UNREFERENCED_PARAMETER(Irp);
ASSERTMSG("Not implemented for UMDF\n", FALSE);
return STATUS_NOT_IMPLEMENTED;
}
_Must_inspect_result_
NTSTATUS
FxPkgPdo::_PnpFilterResourceRequirements(
__inout FxPkgPnp* This,
__inout FxIrp *Irp
)
/*++
Routine Description:
Filter resource requirements for the PDO. A chance to further muck with
the resources assigned to the device.
Arguments:
This - the package
Irp - the request
Return Value:
NTSTATUS
--*/
{
UNREFERENCED_PARAMETER(This);
UNREFERENCED_PARAMETER(Irp);
ASSERTMSG("Not implemented for UMDF\n", FALSE);
return STATUS_NOT_IMPLEMENTED;
}
| 15.648276 | 78 | 0.710886 | IT-Enthusiast-Nepal |
3e5a9ac3ce4eb0cc5776558c3f36af24d3e0e635 | 9,821 | cpp | C++ | experimental-computer-system-oct/hardware/src/sys_processor.cpp | paulscottrobson/assorted-archives | 87ce21ef1556bed441fffbb5c4c3c11c06324385 | [
"MIT"
] | null | null | null | experimental-computer-system-oct/hardware/src/sys_processor.cpp | paulscottrobson/assorted-archives | 87ce21ef1556bed441fffbb5c4c3c11c06324385 | [
"MIT"
] | null | null | null | experimental-computer-system-oct/hardware/src/sys_processor.cpp | paulscottrobson/assorted-archives | 87ce21ef1556bed441fffbb5c4c3c11c06324385 | [
"MIT"
] | 1 | 2020-01-02T13:54:19.000Z | 2020-01-02T13:54:19.000Z | // *******************************************************************************************************************************
// *******************************************************************************************************************************
//
// Name: sys_processor.cpp
// Purpose: Processor Emulation.
// Created: 26th October 2015
// Author: Paul Robson (paul@robsons.org.uk)
//
// *******************************************************************************************************************************
// *******************************************************************************************************************************
#ifdef WINDOWS
#include <stdio.h>
#endif
#ifdef ARDUINO
#include <avr/pgmspace.h>
#endif
#include "sys_processor.h"
// *******************************************************************************************************************************
// Main Memory/CPU
// *******************************************************************************************************************************
static BYTE8 A,B,C,D,E,H,L,pszValue,carry,HaltFlag;
static BYTE8 interruptEnabled,MB,PCIX,interruptRequest;
static WORD16 temp16,MA,PCR[8],Cycles;
static BYTE8 ramMemory[RAMSIZE]; // RAM memory
// *******************************************************************************************************************************
// Memory read and write macros.
// *******************************************************************************************************************************
#define READ() if (MA < RAMSIZE) MB = ramMemory[MA]
#define WRITE() if (MA < RAMSIZE) ramMemory[MA] = MB
// *******************************************************************************************************************************
// I/O Port connections
// *******************************************************************************************************************************
#define INPORT00() { if (A & 0x02) interruptEnabled = A & 0x01;MB = 0x1; } // Port 00 : if bit 1 set enable int, return 1
#define INPORT01() MB = HWIReadKeyboard() // Port 01 : Keyboard in.
#define OUTPORT08() HWIWriteDisplay(MB) // Port 08 : Video Display
// *******************************************************************************************************************************
// Support Macros and Functions
// *******************************************************************************************************************************
#define CYCLES(n) Cycles += (n)
#define FETCH() { MA = PCTR;READ();PCTR = (PCTR + 1) & 07777; }
#define FETCHWORD() { MA = PCTR;READ();temp16 = MB;MA++;READ();MA = (MB << 8) | temp16; PCTR = (PCTR + 2) & 07777; }
#define JUMP() PCTR = MA & 0x3FFF
#define CALL() { PCIX = (PCIX + 1) & 7;PCTR = MA & 0x3FFF; }
#define RETURN() PCIX = (PCIX - 1) & 7;
static void _BinaryAdd(void) {
temp16 = A + MB + carry; // Calc result
carry = temp16 >> 8; // Get new carry
MB = temp16 & 0xFF; // Result in MB
}
static void _BinarySubtract(void){
temp16 = A - MB - carry; // Calc result
carry = (temp16 >> 8) & 1; // Get new borrow
MB = temp16 & 0xFF; // Result in MB
}
static BYTE8 _IsParityEven(BYTE8 n) {
BYTE8 isEven = -1; // 0 is even parity
while (n != 0) { // until all bits test
if (n & 1) isEven = !isEven; // each set bit toggles it
n = n >> 1;
}
return isEven;
}
// *******************************************************************************************************************************
// Built in image
// *******************************************************************************************************************************
#ifdef WINDOWS
static const BYTE8 __image[] = {
#include "__binary.h"
};
#endif
#ifdef ARDUINO
static const PROGMEM uint16_t __image[] = {
#include "__binary.h"
};
#endif
#include "__binary_size.h"
static BYTE8 isCLILoad = 0;
// *******************************************************************************************************************************
// Port interfaces
// *******************************************************************************************************************************
void CPUReset(void) {
A = B = C = D = E = H = L = pszValue = carry = HaltFlag = 0;
PCIX = 0;PCR[PCIX] = 0;Cycles = 0;interruptRequest = 0;interruptEnabled = 0;
HWIReset();
if (isCLILoad == 0) {
isCLILoad = 1;
for (WORD16 n = 0;n < BINARY_SIZE;n++) {
#ifdef WINDOWS
ramMemory[n] = __image[n];
#endif
#ifdef ARDUINO
ramMemory[n] = pgm_read_byte_far(__image+n);
#endif
}
}
}
// *******************************************************************************************************************************
// Request an interrupt
// *******************************************************************************************************************************
#include <stdio.h>
void CPUInterruptRequest(void) {
interruptRequest = 1;
}
// *******************************************************************************************************************************
// Execute a single phase.
// *******************************************************************************************************************************
#include "__8008_ports.h" // Hoover up any undefined ports.
BYTE8 CPUExecuteInstruction(void) {
if (interruptRequest != 0) { // Interrupted.
interruptRequest = 0; // Clear IRQ flag
if (interruptEnabled != 0) { // Is interrupt enabled.
HaltFlag = 0; // Clear Halt flag.
MA = 0;CALL(); // Do a RST 0.
return 0;
}
}
if (HaltFlag == 0) { // CPU is running (not halt)
FETCH(); // Fetch and execute
switch(MB) { // Do the selected opcode and phase.
#include "__8008_opcodes.h"
}
}
if (HaltFlag == 0 && Cycles < CYCLES_PER_FRAME) return 0; // Frame in progress, return 0.
if (HaltFlag != 0) Cycles = 0; // Fix up for HALT.
Cycles -= CYCLES_PER_FRAME; // Adjust cycle counter
HWIEndFrame(); // Hardware stuff.
return FRAME_RATE; // Return the frame rate for sync speed.
}
#ifdef INCLUDE_DEBUGGING_SUPPORT
// *******************************************************************************************************************************
// Get the step over breakpoint value
// *******************************************************************************************************************************
WORD16 CPUGetStepOverBreakpoint(void) {
BYTE8 opcode = CPURead(PCTR); // Read opcode.
if ((opcode & 0xC7) == 0x07) return ((PCTR+1) & 0x3FFF); // RST xx
if ((opcode & 0xC3) == 0x42) return ((PCTR+3) & 0x3FFF); // CALL xxxx (various calls)
return 0xFFFF;
}
// *******************************************************************************************************************************
// Run continuously till breakpoints / Halt.
// *******************************************************************************************************************************
BYTE8 CPUExecute(WORD16 break1,WORD16 break2) {
BYTE8 rate = 0;
while(1) {
rate = CPUExecuteInstruction(); // Execute one instruction phase.
if (rate != 0) { // If end of frame, return rate.
return rate;
}
if (PCTR == break1 || PCTR == break2) return 0;
} // Until hit a breakpoint or HLT.
}
// *******************************************************************************************************************************
// Load a binary file into RAM
// *******************************************************************************************************************************
void CPULoadBinary(char *fileName) {
FILE *f = fopen(fileName,"rb");
fread(ramMemory,RAMSIZE,1,f);
fclose(f);
isCLILoad = 1; // stop reset loading memory
}
// *******************************************************************************************************************************
// Gets a pointer to RAM memory
// *******************************************************************************************************************************
BYTE8 CPURead(WORD16 address) {
WORD16 _MA = MA;BYTE8 _MB = MB;BYTE8 result;
MA = address;READ();result = MB;
MA = _MA;MB = _MB;
return result;
}
// *******************************************************************************************************************************
// Retrieve a snapshot of the processor
// *******************************************************************************************************************************
static CPUSTATUS s; // Status area
CPUSTATUS *CPUGetStatus(void) {
int i;
s.a = A;s.b = B;s.c = C;s.d = D;s.e = E;s.h = H;s.l = L; // 8 bit registers
s.zFlag = (pszValue == 0);s.cFlag = (carry != 0);s.hFlag = (HaltFlag != 0); // Flags
s.pFlag = (_IsParityEven(pszValue) != 0);s.sFlag = ((pszValue & 0x80) != 0);
s.interruptEnabled = interruptEnabled;
s.cycles = Cycles; // Number of cycles.
for (i = 0;i < 8;i++) s.stack[i] = 0; // Clear stack.
s.pc = PCTR; // Save PC.
i = PCIX-1;s.stackDepth = 0; // Copy stack.
while (i >= 0) s.stack[s.stackDepth++] = PCR[i--];
s.hl = (s.h << 8) | s.l;s.m = CPURead(s.hl & 0x3FFF); // Helpers
return &s;
}
#endif
| 43.074561 | 130 | 0.341615 | paulscottrobson |
3e5d9777f4168f2ac148d2956b43a94afdbebd59 | 2,587 | hpp | C++ | RobWorkSim/src/rwsim/util/TargetConfigGraspPolicy.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | 1 | 2021-12-29T14:16:27.000Z | 2021-12-29T14:16:27.000Z | RobWorkSim/src/rwsim/util/TargetConfigGraspPolicy.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | RobWorkSim/src/rwsim/util/TargetConfigGraspPolicy.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | /********************************************************************************
* Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,
* Faculty of Engineering, University of Southern Denmark
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
#ifndef RWSIM_UTIL_TARGETCONFIGGRASPPOLICY_HPP_
#define RWSIM_UTIL_TARGETCONFIGGRASPPOLICY_HPP_
#include "GraspPolicy.hpp"
#include <rw/core/PropertyMap.hpp>
#include <rw/core/Ptr.hpp>
#include <rwlibs/simulation/SimulatedController.hpp>
namespace rwsim { namespace dynamics {
class DynamicDevice;
}} // namespace rwsim::dynamics
namespace rwsim { namespace util {
/**
* @brief This grasp policy will close the fingers of a device to a
* randomly choosen target position which is generated either from a
* predefined set of target configurations or from one of the
* selected hueristics.
*/
class TargetConfigGraspPolicy : public GraspPolicy
{
public:
typedef rw::core::Ptr< TargetConfigGraspPolicy > Ptr;
/**
* @brief constructor
* @param dev
* @return
*/
TargetConfigGraspPolicy (rwsim::dynamics::DynamicDevice* dev);
virtual ~TargetConfigGraspPolicy ();
void setDefaultSettings ();
static std::string getID () { return "TargetConfigGraspPolicy"; };
// inherited from GraspPolicy
virtual void reset (const rw::kinematics::State& state);
virtual rwlibs::simulation::SimulatedController::Ptr getController ();
virtual std::string getIdentifier () { return TargetConfigGraspPolicy::getID (); }
virtual rw::core::PropertyMap getSettings () { return _settings; };
virtual void applySettings ();
private:
rw::core::PropertyMap _settings;
rwsim::dynamics::DynamicDevice* _dev;
rwlibs::simulation::SimulatedController::Ptr _controller;
};
}} // namespace rwsim::util
#endif /* GRASPPOLICY_HPP_ */
| 33.166667 | 90 | 0.652107 | ZLW07 |
3e603daf47107cf447c0fc1bcc77e979f0d73b14 | 3,458 | cpp | C++ | framework/2DLayers/Sources/UI/UISprite.cpp | Daniel-Mietchen/kigs | 92ab6deaf3e947465781a400c5a791ee171876c8 | [
"MIT"
] | null | null | null | framework/2DLayers/Sources/UI/UISprite.cpp | Daniel-Mietchen/kigs | 92ab6deaf3e947465781a400c5a791ee171876c8 | [
"MIT"
] | null | null | null | framework/2DLayers/Sources/UI/UISprite.cpp | Daniel-Mietchen/kigs | 92ab6deaf3e947465781a400c5a791ee171876c8 | [
"MIT"
] | null | null | null | #include "UI/UISprite.h"
#include "TextureFileManager.h"
#include "Texture.h"
#include "AlphaMask.h"
//IMPLEMENT_AND_REGISTER_CLASS_INFO(UISprite, UISprite, 2DLayers);
IMPLEMENT_CLASS_INFO(UISprite)
UISprite::UISprite(const kstl::string& name, CLASS_NAME_TREE_ARG) :
UITexturedItem(name, PASS_CLASS_NAME_TREE_ARG)
, mTexture(*this, false, LABEL_AND_ID(Texture), "")
, mSprite(*this, false, LABEL_AND_ID(Sprite), "")
{
mSpriteSheet = 0;
mHasSprite = false;
}
UISprite::~UISprite()
{
}
//-----------------------------------------------------------------------------------------------------
//ReloadTexture
void UISprite::NotifyUpdate(const unsigned int labelid)
{
if (labelid == mIsEnabled.getLabelID())
{
if (!GetSons().empty())
{
kstl::set<Node2D*, Node2D::PriorityCompare> sons = GetSons();
kstl::set<Node2D*, Node2D::PriorityCompare>::iterator it = sons.begin();
kstl::set<Node2D*, Node2D::PriorityCompare>::iterator end = sons.end();
while (it != end)
{
(*it)->setValue(LABEL_TO_ID(IsEnabled), mIsEnabled);
it++;
}
}
}
else if (labelid == mTexture.getLabelID() && _isInit)
{
ChangeTexture();
}
else if (labelid == mSprite.getLabelID() && _isInit)
{
ChangeTexture();
}
UITexturedItem::NotifyUpdate(labelid);
}
void UISprite::InitModifiable()
{
if (_isInit)
return;
UITexturedItem::InitModifiable();
if (_isInit)
{
ChangeTexture();
mIsEnabled.changeNotificationLevel(Owner);
mTexture.changeNotificationLevel(Owner);
mSprite.changeNotificationLevel(Owner);
}
}
void UISprite::ChangeTexture()
{
mHasSprite = false;
const kstl::string& lTexName = mTexture.const_ref();
if (lTexName == "")
return;
auto& textureManager = KigsCore::Singleton<TextureFileManager>();
mSpriteSheet = textureManager->GetSpriteSheetTexture(lTexName);
SetTexture(mSpriteSheet->Get_Texture());
if (!mTexturePointer)
return;
mTexturePointer->Init();
const SpriteSheetFrame * f = mSpriteSheet->Get_Frame(mSprite);
if (f == nullptr)
return;
mHasSprite = true;
Point2D s, r;
mTexturePointer->GetSize(s.x, s.y);
mTexturePointer->GetRatio(r.x, r.y);
s /= r;
mUVMin.Set((kfloat)f->FramePos_X+0.5f, (kfloat)f->FramePos_Y+0.5f);
mUVMin /= s;
mUVMax.Set((kfloat)(f->FramePos_X+f->FrameSize_X-0.5f), (kfloat)(f->FramePos_Y+f->FrameSize_Y-0.5f));
mUVMax /= s;
//mUVMax = mUVMin + mUVMax;
// auto size
if ((((unsigned int)mSizeX) == 0) && (((unsigned int)mSizeY) == 0))
{
mSizeX = f->FrameSize_X;
mSizeY = f->FrameSize_Y;
}
}
bool UISprite::isAlpha(float X, float Y)
{
//Try to get mask
if (!mAlphaMask)
{
kstl::vector<ModifiableItemStruct> sons = getItems();
for (unsigned int i = 0; i < sons.size(); i++)
{
if (sons[i].mItem->isSubType("AlphaMask"))
{
mAlphaMask = sons[i].mItem;
break;
}
}
}
if (mAlphaMask)
{
return !mAlphaMask->CheckTo(X, Y);
}
return false;
}
void UISprite::SetTexUV(UIVerticesInfo * aQI)
{
if (mHasSprite)
{
kfloat ratioX, ratioY, sx, sy;
mTexturePointer->GetSize(sx, sy);
mTexturePointer->GetRatio(ratioX, ratioY);
kfloat dx = 0.5f / sx;
kfloat dy = 0.5f / sy;
VInfo2D::Data* buf = reinterpret_cast<VInfo2D::Data*>(aQI->Buffer());
aQI->Flag |= UIVerticesInfo_Texture;
// triangle strip order
buf[0].setTexUV(mUVMin.x + dx, mUVMin.y + dy);
buf[1].setTexUV(mUVMin.x + dx, mUVMax.y - dy);
buf[3].setTexUV(mUVMax.x - dx, mUVMax.y - dy);
buf[2].setTexUV(mUVMax.x - dx, mUVMin.y + dy);
}
} | 21.748428 | 103 | 0.656449 | Daniel-Mietchen |
3e60f0c93c5f3058bd47f74a589677c04595a867 | 185 | cpp | C++ | client/test/test.cpp | gary920209/LightDance-RPi | 41d3ef536f3874fd5dbe092f5c9be42f7204427d | [
"MIT"
] | 2 | 2020-11-14T17:13:55.000Z | 2020-11-14T17:42:39.000Z | client/test/test.cpp | gary920209/LightDance-RPi | 41d3ef536f3874fd5dbe092f5c9be42f7204427d | [
"MIT"
] | null | null | null | client/test/test.cpp | gary920209/LightDance-RPi | 41d3ef536f3874fd5dbe092f5c9be42f7204427d | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
string s;
cout << "Other Successfully initiated." << endl;
while (cin >> s)
cout << "Success " << s << endl;
} | 20.555556 | 52 | 0.567568 | gary920209 |
3e617d24eb2fce1d74a7555c8417b1541b47b226 | 2,489 | cpp | C++ | Chapter 5/5.34.cpp | root113/C-How-To-Program-Deitel | fe1ced3fb1efd88f00264cb03c873474e62ed450 | [
"Unlicense"
] | 4 | 2019-02-22T09:38:01.000Z | 2020-02-02T19:13:30.000Z | Chapter 5/5.34.cpp | root113/C-How-To-Program-Deitel | fe1ced3fb1efd88f00264cb03c873474e62ed450 | [
"Unlicense"
] | null | null | null | Chapter 5/5.34.cpp | root113/C-How-To-Program-Deitel | fe1ced3fb1efd88f00264cb03c873474e62ed450 | [
"Unlicense"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int getRandomNum( void );
void correctAnswer();
void wrongAnswer();
int answerTheQuestion( int, int );
void askQuestions( int );
int main()
{
srand( (time(NULL)) );
askQuestions(10);
return 0;
}
int getRandomNum()
{
int res = 1 + rand()%12;
return res;
}
void correctAnswer()
{
int response = getRandomNum();
switch(response) {
case 1: case 2: case 3:
printf("Very good!\n");
break;
case 4: case 5: case 6:
printf("Excellent!\n");
break;
case 7: case 8: case 9:
printf("Nice Work!\n");
break;
case 10: case 11: case 12:
printf("Keep up the good work!\n");
break;
default:
printf("Congrats!\n");
}
}
void wrongAnswer()
{
int response = getRandomNum();
switch(response) {
case 1: case 2: case 3:
printf("No. Please try again!\n");
break;
case 4: case 5: case 6:
printf("Wrong. Try once more!\n");
break;
case 7: case 8: case 9:
printf("Don't give up!\n");
break;
case 10: case 11: case 12:
printf("No. Keep trying!\n");
break;
default:
printf("So wrong, dude!\n");
}
}
int answerTheQuestion(int a, int b)
{
int guess;
int wrongGuesses = 0;
int correct=0;
int result = a*b;
do {
printf("What is %d x %d? ",a, b);
scanf("%d", &guess);
if(guess==result) {
correct = 1;
correctAnswer();
} else {
wrongAnswer();
wrongGuesses++;
}
} while(!correct);
return wrongGuesses;
}
void askQuestions(int n)
{
int i, a, b;
int wrong=0;
for(i=0; i<n; i++) {
a = getRandomNum();
b = getRandomNum();
wrong += answerTheQuestion(a, b);
}
float percentage = (10.0/(10.0 + wrong)) * 100.0;
if(percentage < 75.0) {
printf("\nOnly %.2f%% of your guesses were correct\n", percentage);
printf("Please ask your instructor for extra help\n");
}
else {
printf("\nCongratulations %.2f%% of your guesses were correct\n", percentage);
}
}
| 21.09322 | 87 | 0.470068 | root113 |
3e62b622fa9c7c742cb7339b55e218a652eac506 | 1,920 | cpp | C++ | fdbclient/AutoPublicAddress.cpp | TheBenCollins/foundationdb | e6950abae6914dab989ec00a4b4b648bb9d8af52 | [
"Apache-2.0"
] | null | null | null | fdbclient/AutoPublicAddress.cpp | TheBenCollins/foundationdb | e6950abae6914dab989ec00a4b4b648bb9d8af52 | [
"Apache-2.0"
] | null | null | null | fdbclient/AutoPublicAddress.cpp | TheBenCollins/foundationdb | e6950abae6914dab989ec00a4b4b648bb9d8af52 | [
"Apache-2.0"
] | null | null | null | /*
* AutoPublicAddress.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flow/Platform.h"
#include <algorithm>
#define BOOST_SYSTEM_NO_LIB
#define BOOST_DATE_TIME_NO_LIB
#define BOOST_REGEX_NO_LIB
#include "boost/asio.hpp"
#include "fdbclient/CoordinationInterface.h"
// Determine public IP address by calling the first coordinator.
IPAddress determinePublicIPAutomatically(ClusterConnectionString& ccs) {
try {
using namespace boost::asio;
io_service ioService;
ip::udp::socket socket(ioService);
ccs.resolveHostnamesBlocking();
const auto& coordAddr = ccs.coordinators()[0];
const auto boostIp = coordAddr.ip.isV6() ? ip::address(ip::address_v6(coordAddr.ip.toV6()))
: ip::address(ip::address_v4(coordAddr.ip.toV4()));
ip::udp::endpoint endpoint(boostIp, coordAddr.port);
socket.connect(endpoint);
IPAddress ip = coordAddr.ip.isV6() ? IPAddress(socket.local_endpoint().address().to_v6().to_bytes())
: IPAddress(socket.local_endpoint().address().to_v4().to_ulong());
socket.close();
return ip;
} catch (boost::system::system_error e) {
fprintf(stderr, "Error determining public address: %s\n", e.what());
throw bind_failed();
}
}
| 34.285714 | 103 | 0.7125 | TheBenCollins |
3e63a2481b8e9a04f9ed9679745bdf6c04cb6fb0 | 2,853 | hpp | C++ | library/src/blas1/rocblas_copy.hpp | zjunweihit/rocBLAS | c8bda2d15a7772d810810492ebed616eec0959a5 | [
"MIT"
] | null | null | null | library/src/blas1/rocblas_copy.hpp | zjunweihit/rocBLAS | c8bda2d15a7772d810810492ebed616eec0959a5 | [
"MIT"
] | 1 | 2019-09-26T01:51:09.000Z | 2019-09-26T18:09:56.000Z | library/src/blas1/rocblas_copy.hpp | mahmoodw/rocBLAS | 53b1271e4881ef7473b78e8783e4d55740e9b933 | [
"MIT"
] | null | null | null | /* ************************************************************************
* Copyright 2016-2019 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include "handle.h"
#include "logging.h"
#include "rocblas.h"
#include "utility.h"
template <typename T, typename U, typename V>
__global__ void copy_kernel(rocblas_int n,
const U xa,
ptrdiff_t shiftx,
rocblas_int incx,
rocblas_stride stridex,
V ya,
ptrdiff_t shifty,
rocblas_int incy,
rocblas_stride stridey)
{
ptrdiff_t tid = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
// bound
if(tid < n)
{
const T* x = load_ptr_batch(xa, hipBlockIdx_y, shiftx, stridex);
T* y = load_ptr_batch(ya, hipBlockIdx_y, shifty, stridey);
y[tid * incy] = x[tid * incx];
}
}
template <rocblas_int NB, typename T, typename U, typename V>
rocblas_status rocblas_copy_template(rocblas_handle handle,
rocblas_int n,
U x,
rocblas_int offsetx,
rocblas_int incx,
rocblas_stride stridex,
V y,
rocblas_int offsety,
rocblas_int incy,
rocblas_stride stridey,
rocblas_int batch_count)
{
// Quick return if possible.
if(n <= 0 || !batch_count)
return rocblas_status_success;
if(!x || !y)
return rocblas_status_invalid_pointer;
if(batch_count < 0)
return rocblas_status_invalid_size;
// in case of negative inc shift pointer to end of data for negative indexing tid*inc
ptrdiff_t shiftx = offsetx - ((incx < 0) ? ptrdiff_t(incx) * (n - 1) : 0);
ptrdiff_t shifty = offsety - ((incy < 0) ? ptrdiff_t(incy) * (n - 1) : 0);
int blocks = (n - 1) / NB + 1;
dim3 grid(blocks, batch_count);
dim3 threads(NB);
hipLaunchKernelGGL((copy_kernel<T>),
grid,
threads,
0,
handle->rocblas_stream,
n,
x,
shiftx,
incx,
stridex,
y,
shifty,
incy,
stridey);
return rocblas_status_success;
}
| 36.113924 | 89 | 0.416404 | zjunweihit |
3e63b5c5a2d70d42a9c0b6ff8e1e73da50f7dc83 | 4,523 | cpp | C++ | code/libImmCore/src/libCompression/basic/piBitInterlacer.cpp | andybak/IMM | c725dcb28a1638dea726381a7189c3b031967d58 | [
"Apache-2.0",
"MIT"
] | 33 | 2021-09-16T18:37:08.000Z | 2022-03-22T23:02:44.000Z | code/libImmCore/src/libCompression/basic/piBitInterlacer.cpp | andybak/IMM | c725dcb28a1638dea726381a7189c3b031967d58 | [
"Apache-2.0",
"MIT"
] | 5 | 2021-09-17T10:10:07.000Z | 2022-03-28T12:33:29.000Z | code/libImmCore/src/libCompression/basic/piBitInterlacer.cpp | andybak/IMM | c725dcb28a1638dea726381a7189c3b031967d58 | [
"Apache-2.0",
"MIT"
] | 5 | 2021-09-19T07:49:01.000Z | 2021-12-12T21:25:35.000Z | //
// Branched off piLibs (Copyright © 2015 Inigo Quilez, The MIT License), in 2015. See THIRD_PARTY_LICENSES.txt
//
#include <malloc.h>
#include "../../libBasics/piTypes.h"
#include "piBitInterlacer.h"
namespace ImmCore
{
namespace piBitInterlacer
{
BitStream::BitStream()
{
mBits = 0;
mState = 0;
}
bool BitStream::output(int bit, uint8_t *res)
{
mState |= (bit << mBits);
mBits++;
if (mBits == 8)
{
*res = mState;
mBits = 0;
mState = 0;
return true;
}
return false;
}
bool BitStream::flush(uint8_t *val)
{
if (mBits != 0)
{
*val = mState;
return true;
}
return false;
}
uint64_t interlace8(uint8_t *dst, const uint8_t *data, uint64_t numPoints, uint64_t numChannels, uint64_t numBits)
{
if (numPoints == 0) return 0;
// interlace all bits, sort bits from lower to higher bits across channels
uint64_t num = 0;
BitStream bit;
for (int b = 0; b < numBits; b++)
for (int j = 0; j < numChannels; j++)
for (int i = 0; i < numPoints; i++)
{
uint8_t res;
if (bit.output((data[numChannels*i + j] >> b) & 1, &res))
dst[num++] = res;
}
uint8_t res; if (bit.flush(&res)) dst[num++] = res;
// remove trailing zeroes
uint64_t len = 0;
for (int64_t i = num - 1; i >= 0; i--)
{
if (dst[i] != 0)
{
len = i + 1;
break;
}
}
return len;
}
uint64_t interlace16(uint8_t *dst, const uint16_t *data, uint64_t numPoints, uint64_t numChannels, uint64_t numBits)
{
if (numPoints == 0) return 0;
// interlace all bits, sort bits from lower to higher bits across channels
uint64_t num = 0;
BitStream bit;
for (int b = 0; b < numBits; b++)
for (int j = 0; j < numChannels; j++)
for (int i = 0; i < numPoints; i++)
{
uint8_t res;
if (bit.output((data[numChannels*i + j] >> b) & 1, &res))
dst[num++] = res;
}
uint8_t res; if (bit.flush(&res)) dst[num++] = res;
// remove trailing zeroes
uint64_t len = 0;
for (int64_t i = num - 1; i >= 0; i--)
{
if (dst[i] != 0)
{
len = i + 1;
break;
}
}
return len;
}
uint64_t interlace32(uint8_t *dst, const uint32_t *data, uint64_t numPoints, uint64_t numChannels, uint64_t numBits)
{
if (numPoints == 0) return 0;
// interlace all bits, sort bits from lower to higher bits across channels
uint64_t num = 0;
BitStream bit;
for (int b = 0; b < numBits; b++)
for (int j = 0; j < numChannels; j++)
for (int i = 0; i < numPoints; i++)
{
uint8_t res;
if (bit.output((data[numChannels*i + j] >> b) & 1, &res))
dst[num++] = res;
}
uint8_t res; if (bit.flush(&res)) dst[num++] = res;
// remove trailing zeroes
uint64_t len = 0;
for (int64_t i = num - 1; i >= 0; i--)
{
if (dst[i] != 0)
{
len = i + 1;
break;
}
}
return len;
}
void deinterlace8(const uint8_t *src, uint8_t *data, uint64_t numBytes, uint64_t numPoints, unsigned int numChannels, unsigned int numBits)
{
for (uint64_t i = 0, num = numPoints*numChannels; i < num; i++)
{
data[i] = 0;
}
unsigned int bit = 0;
unsigned int channel = 0;
uint64_t point = 0;
for (uint64_t i = 0; i < numBytes; i++)
{
const uint8_t byte = src[i];
for (int j = 0; j < 8; j++)
{
const int b = (byte >> j) & 1;
data[numChannels*point + channel] |= (b << bit);
point++;
if (point >= numPoints)
{
point = 0;
channel++;
if (channel >= numChannels)
{
channel = 0;
bit++;
if (bit >= numBits)
{
bit = 0;
return;
}
}
}
}
}
}
void deinterlace16(const uint8_t *src, uint16_t *data, uint64_t numBytes, uint64_t numPoints, unsigned int numChannels, unsigned int numBits)
{
for (uint64_t i = 0, num = numPoints*numChannels; i < num; i++)
{
data[i] = 0;
}
unsigned int bit = 0;
unsigned int channel = 0;
uint64_t point = 0;
for (uint64_t i = 0; i < numBytes; i++)
{
const uint8_t byte = src[i];
for (int j = 0; j < 8; j++)
{
const unsigned int b = (byte >> j) & 1;
data[numChannels*point + channel] |= (b << bit);
point++;
if (point >= numPoints)
{
point = 0;
channel++;
if (channel >= numChannels)
{
channel = 0;
bit++;
if (bit >= numBits)
{
bit = 0;
return;
}
}
}
}
}
}
}
}
| 20.282511 | 143 | 0.539244 | andybak |
3e6760be917a197de14d406bcd63405bba53c300 | 5,208 | cpp | C++ | frameworks/wm/test/unittest/window_option_impl_test.cpp | openharmony-gitee-mirror/graphic_standard | dc99aa91453f9133c16f488c6f071d7ef1936f2f | [
"Apache-2.0"
] | null | null | null | frameworks/wm/test/unittest/window_option_impl_test.cpp | openharmony-gitee-mirror/graphic_standard | dc99aa91453f9133c16f488c6f071d7ef1936f2f | [
"Apache-2.0"
] | null | null | null | frameworks/wm/test/unittest/window_option_impl_test.cpp | openharmony-gitee-mirror/graphic_standard | dc99aa91453f9133c16f488c6f071d7ef1936f2f | [
"Apache-2.0"
] | 1 | 2021-09-13T11:18:12.000Z | 2021-09-13T11:18:12.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "window_option_impl_test.h"
namespace OHOS {
void WindowOptionImplTest::SetUp()
{
}
void WindowOptionImplTest::TearDown()
{
}
void WindowOptionImplTest::SetUpTestCase()
{
}
void WindowOptionImplTest::TearDownTestCase()
{
}
namespace {
/*
* Feature: WindowOptionImpl Getter, Setter
* Function: WindowOptionImpl
* SubFunction: Getter, Setter
* FunctionPoints: WindowOptionImpl Getter, Setter
* EnvConditions: N/A
* CaseDescription: 1. Check Set and Get WindowType
* 2. Check Set and Get WindowMode
* 3. Check Set and Get Display
* 4. Check Set and Get ConsumerSurface
*/
HWTEST_F(WindowOptionImplTest, Create, testing::ext::TestSize.Level0)
{
WindowOptionImpl woi;
// 1. Check Set and Get WindowType
constexpr WindowType type1 = static_cast<WindowType>(0);
constexpr WindowType type2 = static_cast<WindowType>(1);
woi.SetWindowType(type1);
ASSERT_EQ(woi.GetWindowType(), type1) << "CaseDescription: "
<< "1. Check Set and Get WindowType (woi.GetWindowType() == type1)";
woi.SetWindowType(type2);
ASSERT_EQ(woi.GetWindowType(), type2) << "CaseDescription: "
<< "1. Check Set and Get WindowType (woi.GetWindowType() == type2)";
// 2. Check Set and Get WindowMode
constexpr WindowMode mode1 = static_cast<WindowMode>(0);
constexpr WindowMode mode2 = static_cast<WindowMode>(1);
woi.SetWindowMode(mode1);
ASSERT_EQ(woi.GetWindowMode(), mode1) << "CaseDescription: "
<< "2. Check Set and Get WindowMode (woi.GetWindowMode() == mode1)";
woi.SetWindowMode(mode2);
ASSERT_EQ(woi.GetWindowMode(), mode2) << "CaseDescription: "
<< "2. Check Set and Get WindowMode (woi.GetWindowMode() == mode2)";
// 3. Check Set and Get Display
constexpr int32_t display1 = 1;
constexpr int32_t display2 = 2;
woi.SetDisplay(display1);
ASSERT_EQ(woi.GetDisplay(), display1) << "CaseDescription: "
<< "3. Check Set and Get Display (woi.GetDisplay() == display1)";
woi.SetDisplay(display2);
ASSERT_EQ(woi.GetDisplay(), display2) << "CaseDescription: "
<< "3. Check Set and Get Display (woi.GetY() == display2)";
// 4. Check Set and Get ConsumerSurface
auto csurface1 = Surface::CreateSurfaceAsConsumer();
auto csurface2 = Surface::CreateSurfaceAsConsumer();
woi.SetConsumerSurface(csurface1);
ASSERT_EQ(woi.GetConsumerSurface(), csurface1) << "CaseDescription: "
<< "4. Check Set and Get ConsumerSurface (woi.GetConsumerSurface() == csurface1)";
woi.SetConsumerSurface(csurface2);
ASSERT_EQ(woi.GetConsumerSurface(), csurface2) << "CaseDescription: "
<< "4. Check Set and Get ConsumerSurface (woi.GetConsumerSurface() == csurface2)";
}
/*
* Feature: WindowOptionImpl Invalid Set
* Function: WindowOptionImpl
* SubFunction: Invalid Set
* FunctionPoints: WindowOptionImpl Invalid Set
* EnvConditions: N/A
* CaseDescription: 1. set invalid WindowType, check
* 2. set invalid WindowMode, check
* 3. set invalid Display, check
* 4. set invalid ConsumerSurface, check
*/
HWTEST_F(WindowOptionImplTest, InvalidSet, testing::ext::TestSize.Level0)
{
WindowOptionImpl woi;
// 1. set invalid WindowType, check
constexpr auto invalidWindowType = static_cast<WindowType>(-1);
ASSERT_EQ(woi.SetWindowType(invalidWindowType), WM_ERROR_INVALID_PARAM) << "CaseDescription: "
<< "1. set invalid WindowType, check (woi.SetWindowType() == WM_ERROR_INVALID_PARAM)";
// 2. set invalid WindowMode, check
constexpr auto invalidWindowMode = static_cast<WindowMode>(-1);
ASSERT_EQ(woi.SetWindowMode(invalidWindowMode), WM_ERROR_INVALID_PARAM) << "CaseDescription: "
<< "2. set invalid WindowMode, check (woi.SetWindowMode() == WM_ERROR_INVALID_PARAM)";
// 3. set invalid display, check
constexpr auto invalidDisplay = -1;
ASSERT_EQ(woi.SetDisplay(invalidDisplay), WM_ERROR_INVALID_PARAM) << "CaseDescription: "
<< "3. set invalid display, check (woi.SetDisplay() == WM_ERROR_INVALID_PARAM)";
// 4. set invalid consumerSurface, check
auto csurface = Surface::CreateSurfaceAsConsumer();
auto producer = csurface->GetProducer();
auto invalidConsumerSurface = Surface::CreateSurfaceAsProducer(producer);
ASSERT_EQ(woi.SetConsumerSurface(invalidConsumerSurface), WM_ERROR_INVALID_PARAM) << "CaseDescription: "
<< "4. set invalid consumerSurface, check (woi.SetConsumerSurface() == WM_ERROR_INVALID_PARAM)";
}
} // namespace
} // namespace OHOS
| 39.755725 | 108 | 0.701421 | openharmony-gitee-mirror |
3e6826654152115df8c0fc784ee1a1f39c51edf1 | 1,462 | hpp | C++ | streambox/Nexmark/NexmarkFilterEvaluator.hpp | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 3 | 2019-07-03T14:03:31.000Z | 2021-12-19T10:18:49.000Z | streambox/Nexmark/NexmarkFilterEvaluator.hpp | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | null | null | null | streambox/Nexmark/NexmarkFilterEvaluator.hpp | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | null | null | null | #ifndef NEXMARK_FILTER_EVALUATOR_HPP
#define NEXMARK_FILTER_EVALUATOR_HPP
#include "core/SingleInputTransformEvaluator.h"
#include "Nexmark/NexmarkFilter.hpp"
/* convert a stream of records to a stream of <NexmarkRecord> records */
template <typename InputT,
typename OutputT,
template<class> class BundleT_>
class NexmarkFilterEvaluator
: public SingleInputTransformEvaluator<NexmarkFilter<InputT, OutputT>,
BundleT_<InputT>, BundleT_<OutputT>
> {
using TransformT = NexmarkFilter<InputT, OutputT>;
using InputBundleT = BundleT_<InputT>;
using OutputBundleT = BundleT_<OutputT>;
public:
bool evaluateSingleInput (TransformT* trans,
shared_ptr<InputBundleT> input_bundle,
shared_ptr<OutputBundleT> output_bundle) override {
for (auto && it = input_bundle->begin(); it != input_bundle->end(); ++it) {
if(trans->do_map(*it)) {
output_bundle->add_record(*it);
}
}
trans->record_counter_.fetch_add(input_bundle->size(), std::memory_order_relaxed);
return true;
// return false;
}
NexmarkFilterEvaluator(int node)
: SingleInputTransformEvaluator<TransformT,
InputBundleT, OutputBundleT>(node) {}
};
#endif //NEXMARK_FILTER_EVALUATOR_HPP
| 34.809524 | 90 | 0.618331 | chenzongxiong |
3e6894e42d658ddbbde6d9446022b905eadec8c9 | 645 | hpp | C++ | Layer.hpp | kaitokidi/JacobsHack | 6662dc32a91a964f6080470627398bfa0f36573e | [
"MIT"
] | 4 | 2015-10-21T06:49:16.000Z | 2016-08-17T07:59:07.000Z | Layer.hpp | kaitokidi/JacobsHack | 6662dc32a91a964f6080470627398bfa0f36573e | [
"MIT"
] | null | null | null | Layer.hpp | kaitokidi/JacobsHack | 6662dc32a91a964f6080470627398bfa0f36573e | [
"MIT"
] | null | null | null | #ifndef LAYER_HPP
#define LAYER_HPP
#include "utils.hpp"
class Layer
{
public:
Layer();
Layer(float speed);
void setSpeed(float speed);
float getSpeed();
void setFactor(float factor);
float getFactor();
void setTexture(std::vector<sf::Texture>& textures, int qtty);/*, sf::Texture& texture2);*/
void draw(sf::RenderTarget* renderTarget, sf::Transform* t);
void update(float deltatime);
private:
float _speed, _factor;
std::vector<sf::Sprite> _sprites;
// sf::Sprite _sprite1;
// sf::Sprite _sprite2;
};
#endif // LAYER_HPP
| 18.428571 | 99 | 0.595349 | kaitokidi |
3e6a803a5a930e547d3fb28c014035b75ca34eee | 796 | cc | C++ | cpp/api/sspi/RevertSecurityContext.cc | giuliohome/node-expose-sspi | 344aac68e94f9b5a99bce42651bf669b415c92d8 | [
"ISC"
] | 90 | 2020-02-13T17:27:27.000Z | 2022-03-07T23:02:37.000Z | cpp/api/sspi/RevertSecurityContext.cc | giuliohome/node-expose-sspi | 344aac68e94f9b5a99bce42651bf669b415c92d8 | [
"ISC"
] | 76 | 2020-03-19T06:29:23.000Z | 2022-03-28T05:27:29.000Z | cpp/api/sspi/RevertSecurityContext.cc | giuliohome/node-expose-sspi | 344aac68e94f9b5a99bce42651bf669b415c92d8 | [
"ISC"
] | 20 | 2020-04-30T07:45:45.000Z | 2022-02-23T10:59:09.000Z | #include "../../misc.h"
namespace myAddon {
void e_RevertSecurityContext(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
if (info.Length() < 1) {
throw Napi::Error::New(
env,
"RevertSecurityContext: Wrong number of arguments. "
"RevertSecurityContext(serverContextHandle: string)");
}
Napi::String serverContextHandleString = info[0].As<Napi::String>();
CtxtHandle serverContextHandle =
SecHandleUtil::deserialize(serverContextHandleString.Utf8Value());
SECURITY_STATUS secStatus = RevertSecurityContext(&serverContextHandle);
if (secStatus != SEC_E_OK) {
throw Napi::Error::New(env, "Cannot RevertSecurityContext: secStatus = " +
plf::error_msg(secStatus));
}
}
} // namespace myAddon
| 30.615385 | 78 | 0.670854 | giuliohome |
3e6a80fe95718bf7f96b04325fdda25e6f9b9508 | 4,083 | cp | C++ | MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Alerts_Panels/CPrefsAlertsAttachment.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Alerts_Panels/CPrefsAlertsAttachment.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Alerts_Panels/CPrefsAlertsAttachment.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Source for CPrefsAlertsAttachment class
#include "CPrefsAlertsAttachment.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
#include "CSoundPopup.h"
#include "CTextFieldX.h"
#include <LCheckBox.h>
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Default constructor
CPrefsAlertsAttachment::CPrefsAlertsAttachment()
{
}
// Constructor from stream
CPrefsAlertsAttachment::CPrefsAlertsAttachment(LStream *inStream)
: CPrefsTabSubPanel(inStream)
{
}
// Default destructor
CPrefsAlertsAttachment::~CPrefsAlertsAttachment()
{
}
// O T H E R M E T H O D S ____________________________________________________________________________
// Get details of sub-panes
void CPrefsAlertsAttachment::FinishCreateSelf(void)
{
// Do inherited
CPrefsTabSubPanel::FinishCreateSelf();
mAttachmentAlert = (LCheckBox*) FindPaneByID(paneid_AttachmentAlert);
mAttachmentPlaySound = (LCheckBox*) FindPaneByID(paneid_AttachmentPlaySound);
mAttachmentSound = (CSoundPopup*) FindPaneByID(paneid_AttachmentSound);
mAttachmentSpeak = (LCheckBox*) FindPaneByID(paneid_AttachmentSpeak);
mAttachmentSpeakText = (CTextFieldX*) FindPaneByID(paneid_AttachmentSpeakText);
// Link controls to this window
UReanimator::LinkListenerToBroadcasters(this, this, RidL_CPrefsAlertsAttachmentBtns);
}
// Handle buttons
void CPrefsAlertsAttachment::ListenToMessage(
MessageT inMessage,
void *ioParam)
{
switch (inMessage)
{
case msg_AttachmentPlaySound:
if (*((long*) ioParam))
{
mAttachmentSound->Enable();
cdstring title;
mAttachmentSound->GetName(title);
::PlayNamedSound(title);
}
else
mAttachmentSound->Disable();
break;
case msg_AttachmentSound:
{
cdstring title;
mAttachmentSound->GetName(title);
::PlayNamedSound(title);
}
break;
case msg_AttachmentSpeak:
if (*((long*) ioParam))
mAttachmentSpeakText->Enable();
else
mAttachmentSpeakText->Disable();
break;
}
}
// Set prefs
void CPrefsAlertsAttachment::SetData(void* data)
{
CPreferences* copyPrefs = (CPreferences*) data;
StopListening();
const CNotification& attachment_notify = copyPrefs->mAttachmentNotification.GetValue();
mAttachmentAlert->SetValue(attachment_notify.DoShowAlert() ? 1 : 0);
mAttachmentPlaySound->SetValue(attachment_notify.DoPlaySound());
mAttachmentSound->SetName(attachment_notify.GetSoundID());
if (!attachment_notify.DoPlaySound())
mAttachmentSound->Disable();
mAttachmentSpeak->SetValue(attachment_notify.DoSpeakText() ? 1 : 0);
mAttachmentSpeakText->SetText(attachment_notify.GetTextToSpeak());
if (!attachment_notify.DoSpeakText())
mAttachmentSpeakText->Disable();
StartListening();
}
// Force update of prefs
void CPrefsAlertsAttachment::UpdateData(void* data)
{
CPreferences* copyPrefs = (CPreferences*) data;
// Make copy to look for changes
CNotification& attachment_notify = copyPrefs->mAttachmentNotification.Value();
CNotification attach_copy(attachment_notify);
attachment_notify.SetShowAlert(mAttachmentAlert->GetValue()==1);
attachment_notify.SetPlaySound(mAttachmentPlaySound->GetValue());
cdstring snd;
mAttachmentSound->GetName(snd);
attachment_notify.SetSoundID(snd);
attachment_notify.SetSpeakText(mAttachmentSpeak->GetValue());
attachment_notify.SetTextToSpeak(mAttachmentSpeakText->GetText());
// Set dirty if required
if (!(attach_copy == attachment_notify))
copyPrefs->mAttachmentNotification.SetDirty();
}
| 28.354167 | 104 | 0.76096 | mulberry-mail |
3e6cec3cd9e3d03d6046b98b98002361e3252263 | 2,097 | cpp | C++ | inference-engine/tests/functional/plugin/gpu/shared_tests_instances/single_layer_tests/non_max_suppression.cpp | Andruxin52rus/openvino | d824e371fe7dffb90e6d3d58e4e34adecfce4606 | [
"Apache-2.0"
] | 1 | 2022-01-19T15:36:45.000Z | 2022-01-19T15:36:45.000Z | inference-engine/tests/functional/plugin/gpu/shared_tests_instances/single_layer_tests/non_max_suppression.cpp | Andruxin52rus/openvino | d824e371fe7dffb90e6d3d58e4e34adecfce4606 | [
"Apache-2.0"
] | 27 | 2020-12-29T14:38:34.000Z | 2022-02-21T13:04:03.000Z | inference-engine/tests/functional/plugin/gpu/shared_tests_instances/single_layer_tests/non_max_suppression.cpp | mmakridi/openvino | 769bb7709597c14debdaa356dd60c5a78bdfa97e | [
"Apache-2.0"
] | 1 | 2021-07-28T17:30:46.000Z | 2021-07-28T17:30:46.000Z | // Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include "single_layer_tests/non_max_suppression.hpp"
#include "common_test_utils/test_constants.hpp"
using namespace LayerTestsDefinitions;
using namespace InferenceEngine;
using namespace ngraph;
const std::vector<InputShapeParams> inShapeParams = {
InputShapeParams{3, 100, 5},
InputShapeParams{1, 10, 50},
InputShapeParams{2, 50, 50}
};
const std::vector<int32_t> maxOutBoxPerClass = {5, 20};
const std::vector<float> threshold = {0.3f, 0.7f};
const std::vector<float> sigmaThreshold = {0.0f, 0.5f};
const std::vector<op::v5::NonMaxSuppression::BoxEncodingType> encodType = {op::v5::NonMaxSuppression::BoxEncodingType::CENTER,
op::v5::NonMaxSuppression::BoxEncodingType::CORNER};
const std::vector<bool> sortResDesc = {true, false};
const std::vector<element::Type> outType = {element::i32, element::i64};
const auto nmsParams = ::testing::Combine(::testing::ValuesIn(inShapeParams),
::testing::Combine(::testing::Values(Precision::FP32),
::testing::Values(Precision::I32),
::testing::Values(Precision::FP32)),
::testing::ValuesIn(maxOutBoxPerClass),
::testing::ValuesIn(threshold),
::testing::ValuesIn(threshold),
::testing::ValuesIn(sigmaThreshold),
::testing::ValuesIn(encodType),
::testing::ValuesIn(sortResDesc),
::testing::ValuesIn(outType),
::testing::Values(CommonTestUtils::DEVICE_GPU)
);
INSTANTIATE_TEST_CASE_P(smoke_NmsLayerTest, NmsLayerTest, nmsParams, NmsLayerTest::getTestCaseName);
| 48.767442 | 127 | 0.551264 | Andruxin52rus |
3e6df5d5553799540f4fb1fc9a85b8eac66e4035 | 53 | hpp | C++ | src/boost_mpl_aux__preprocessed_plain_and.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_aux__preprocessed_plain_and.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_aux__preprocessed_plain_and.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/aux_/preprocessed/plain/and.hpp>
| 26.5 | 52 | 0.792453 | miathedev |
3e710f3056c9ebcdae67b44afdbe1a11d0522df3 | 1,144 | cpp | C++ | src/topfd/dp/dp.cpp | toppic-suite/toppic-suite | b5f0851f437dde053ddc646f45f9f592c16503ec | [
"Apache-2.0"
] | 8 | 2018-05-23T14:37:31.000Z | 2022-02-04T23:48:38.000Z | src/topfd/dp/dp.cpp | toppic-suite/toppic-suite | b5f0851f437dde053ddc646f45f9f592c16503ec | [
"Apache-2.0"
] | 9 | 2019-08-31T08:17:45.000Z | 2022-02-11T20:58:06.000Z | src/topfd/dp/dp.cpp | toppic-suite/toppic-suite | b5f0851f437dde053ddc646f45f9f592c16503ec | [
"Apache-2.0"
] | 4 | 2018-04-25T01:39:38.000Z | 2020-05-20T19:25:07.000Z | //Copyright (c) 2014 - 2020, The Trustees of Indiana University.
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
#include "topfd/dp/dp.hpp"
namespace toppic {
Dp::Dp (DeconvDataPtr data_ptr, MatchEnvPtr2D &win_envs,
DpParaPtr dp_para_ptr, double score_error_tolerance):
data_ptr_(data_ptr),
dp_para_ptr_(dp_para_ptr),
score_error_tolerance_(score_error_tolerance),
win_envs_(win_envs) {
win_num_ = data_ptr_->getWinNum();
}
// add an envelope list to result list
void Dp::addEnv(MatchEnvPtrVec &result, MatchEnvPtrVec &prev_env) {
result.insert(result.end(), prev_env.begin(), prev_env.end());
}
}
| 32.685714 | 74 | 0.738636 | toppic-suite |
3e71219676943218c86f87e1c79384451f5e6a23 | 1,011 | cpp | C++ | 2021F/CS203/lab4/a.cpp | HeZean/SUSTech-Archive | 0c89d78f232fdef427ca17b7e508881b782d7826 | [
"MIT"
] | null | null | null | 2021F/CS203/lab4/a.cpp | HeZean/SUSTech-Archive | 0c89d78f232fdef427ca17b7e508881b782d7826 | [
"MIT"
] | null | null | null | 2021F/CS203/lab4/a.cpp | HeZean/SUSTech-Archive | 0c89d78f232fdef427ca17b7e508881b782d7826 | [
"MIT"
] | null | null | null | #include <iostream>
struct Node {
long coe;
int exp;
Node* next;
};
int main() {
int n, m;
scanf("%d %d", &n, &m);
Node head{0, INT32_MAX, nullptr};
Node* cur = &head;
while (n--) {
int coe, exp;
scanf("%d %d", &coe, &exp);
Node* node = new Node{coe, exp, nullptr};
cur->next = node;
cur = cur->next;
}
cur->next = new Node{0, INT32_MIN, nullptr};
cur = &head;
while (m--) {
int coe, exp;
scanf("%d %d", &coe, &exp);
while (cur->next && cur->next->exp >= exp) cur = cur->next;
if (cur->exp == exp)
cur->coe += coe;
else
cur->next = new Node{coe, exp, cur->next};
}
cur = head.next;
int cnt = 0;
while (cur->next) {
if (cur->coe) cnt++;
cur = cur->next;
}
printf("%d\n", cnt);
cur = head.next;
while (cur->next) {
if (cur->coe) printf("%ld %d\n", cur->coe, cur->exp);
cur = cur->next;
}
}
| 21.978261 | 67 | 0.452028 | HeZean |
3e72d34198999e3b3a6a63d8e956faa0ed81e275 | 474 | hpp | C++ | coalescing/common.hpp | cwpearson/nvidia-performance-tools | 90890e807ef9fc1532ee08938de6689444701686 | [
"MIT"
] | 51 | 2020-04-16T18:44:48.000Z | 2022-03-28T20:06:39.000Z | coalescing/common.hpp | cwpearson/nvidia-performance-tools | 90890e807ef9fc1532ee08938de6689444701686 | [
"MIT"
] | 3 | 2020-05-26T20:15:42.000Z | 2021-12-13T19:37:39.000Z | coalescing/common.hpp | cwpearson/nvidia-performance-tools | 90890e807ef9fc1532ee08938de6689444701686 | [
"MIT"
] | 3 | 2020-12-08T05:35:20.000Z | 2021-11-05T02:00:29.000Z | #pragma once
#include <chrono>
#ifdef __CUDACC__
inline void checkCuda(cudaError_t result, const char *file, const int line) {
if (result != cudaSuccess) {
fprintf(stderr, "%s@%d: CUDA Runtime Error(%d): %s\n", file, line,
int(result), cudaGetErrorString(result));
exit(-1);
}
}
#define CUDA_RUNTIME(stmt) checkCuda(stmt, __FILE__, __LINE__);
#endif
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::duration<float> Duration; | 26.333333 | 77 | 0.702532 | cwpearson |
3e74a3c7eb15f4f63d3047dd8653fb9be94c3a6f | 1,838 | cpp | C++ | src/MCPDAC.cpp | MajenkoLibraries/MCPDAC | 7c271022ced7db0b15b5bfaa904e4a3112780e67 | [
"BSD-3-Clause"
] | 11 | 2016-07-24T21:40:14.000Z | 2021-12-29T13:54:18.000Z | src/MCPDAC.cpp | MajenkoLibraries/MCPDAC | 7c271022ced7db0b15b5bfaa904e4a3112780e67 | [
"BSD-3-Clause"
] | 3 | 2015-08-15T13:03:43.000Z | 2018-05-11T13:26:33.000Z | src/MCPDAC.cpp | MajenkoLibraries/MCPDAC | 7c271022ced7db0b15b5bfaa904e4a3112780e67 | [
"BSD-3-Clause"
] | 8 | 2016-08-02T00:38:14.000Z | 2022-03-31T16:19:38.000Z | /***********************************************
* Microchip DAC library
* (c) 2012 Majenko Technologies
*
* This library is offered without any warranty as to
* fitness for purpose, either explicitly or implicitly
* implied.
***********************************************/
/*
* Microchip DAC library. This works with the MCP4822 chip and
* similar chips that work with the same protocol.
*/
#include <Arduino.h>
#include <SPI.h>
#include "MCPDAC.h"
MCPDACClass MCPDAC;
void MCPDACClass::begin()
{
this->begin(10);
}
void MCPDACClass::begin(uint8_t cspin)
{
this->ldac = false;
this->cspin = cspin;
pinMode(this->cspin,OUTPUT);
digitalWrite(this->cspin,HIGH);
SPI.begin();
}
void MCPDACClass::begin(uint8_t cspin, uint8_t ldacpin)
{
this->begin(cspin);
this->ldac = true;
this->ldacpin = ldacpin;
pinMode(this->ldacpin,OUTPUT);
digitalWrite(this->ldacpin,HIGH);
}
void MCPDACClass::setGain(bool chan, bool gain)
{
this->gain[chan] = gain;
}
void MCPDACClass::shutdown(bool chan, bool sd)
{
this->shdn[chan] = sd;
}
void MCPDACClass::setVoltage(bool chan, uint16_t mv)
{
this->value[chan] = mv;
this->updateRegister(chan);
}
void MCPDACClass::update()
{
if(this->ldac==false)
return;
digitalWrite(this->ldacpin,LOW);
digitalWrite(this->ldacpin,HIGH);
}
void MCPDACClass::updateRegister(bool chan)
{
uint16_t command = 0;
command |= (chan << REGAB); // set channel in register
command |= (!this->gain[chan] << REGGA); // set gain in register
command |= (!this->shdn[chan] << REGSHDN); // set shutdown in register
command |= (this->value[chan] & 0x0FFF); // set input data bits (strip everything greater than 12 bit)
SPI.setDataMode(SPI_MODE0);
digitalWrite(this->cspin,LOW);
SPI.transfer(command>>8);
SPI.transfer(command&0xFF);
digitalWrite(this->cspin,HIGH);
}
| 22.414634 | 106 | 0.658868 | MajenkoLibraries |
3e768ef280774aab172fbe3521b0be896c0ad6a6 | 3,916 | cpp | C++ | build/include/nodes/internal/moc_FlowView.cpp | similas/nodeeditor | 06efa504cc11de8f941308fe45e6e77030fcd295 | [
"BSD-3-Clause"
] | null | null | null | build/include/nodes/internal/moc_FlowView.cpp | similas/nodeeditor | 06efa504cc11de8f941308fe45e6e77030fcd295 | [
"BSD-3-Clause"
] | null | null | null | build/include/nodes/internal/moc_FlowView.cpp | similas/nodeeditor | 06efa504cc11de8f941308fe45e6e77030fcd295 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'FlowView.hpp'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.15.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../../../../include/nodes/internal/FlowView.hpp"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'FlowView.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.15.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_QtNodes__FlowView_t {
QByteArrayData data[5];
char stringdata0[57];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QtNodes__FlowView_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QtNodes__FlowView_t qt_meta_stringdata_QtNodes__FlowView = {
{
QT_MOC_LITERAL(0, 0, 17), // "QtNodes::FlowView"
QT_MOC_LITERAL(1, 18, 7), // "scaleUp"
QT_MOC_LITERAL(2, 26, 0), // ""
QT_MOC_LITERAL(3, 27, 9), // "scaleDown"
QT_MOC_LITERAL(4, 37, 19) // "deleteSelectedNodes"
},
"QtNodes::FlowView\0scaleUp\0\0scaleDown\0"
"deleteSelectedNodes"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QtNodes__FlowView[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 29, 2, 0x0a /* Public */,
3, 0, 30, 2, 0x0a /* Public */,
4, 0, 31, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void QtNodes::FlowView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<FlowView *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->scaleUp(); break;
case 1: _t->scaleDown(); break;
case 2: _t->deleteSelectedNodes(); break;
default: ;
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject QtNodes::FlowView::staticMetaObject = { {
QMetaObject::SuperData::link<QGraphicsView::staticMetaObject>(),
qt_meta_stringdata_QtNodes__FlowView.data,
qt_meta_data_QtNodes__FlowView,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *QtNodes::FlowView::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QtNodes::FlowView::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_QtNodes__FlowView.stringdata0))
return static_cast<void*>(this);
return QGraphicsView::qt_metacast(_clname);
}
int QtNodes::FlowView::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QGraphicsView::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 3;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 30.356589 | 97 | 0.624106 | similas |
3e77d2779e9191eec5c0f1c329de57d850a58178 | 3,593 | hpp | C++ | hpp/Compare.impl.hpp | Ivy233/simple_diff | 970bf8a0a624fc89b9c016fab44a87162feb2465 | [
"MIT"
] | 1 | 2021-11-30T07:47:52.000Z | 2021-11-30T07:47:52.000Z | hpp/Compare.impl.hpp | Ivy233/simple_diff | 970bf8a0a624fc89b9c016fab44a87162feb2465 | [
"MIT"
] | null | null | null | hpp/Compare.impl.hpp | Ivy233/simple_diff | 970bf8a0a624fc89b9c016fab44a87162feb2465 | [
"MIT"
] | null | null | null | /*
* File name: Compare.impl.hpp
* Description: 顶层类实现
* Author: 王锦润
* Version: 2
* Date: 2019.6.11
* History: 此程序被纳入git,可以直接使用git查询。
*/
//防卫式声明,必须要有
//就算没有重复包含也建议有,这是代码习惯
#ifndef _COMPARE_IMPL_HPP_
#define _COMPARE_IMPL_HPP_
#include "Compare.hpp"
/*
* Function: 构造函数
* Description: 构建文件夹,匹配并获得差异
* Input: 两个文件(夹)路径,cmd输入
* Calls: _M_link
*/
Compare::Compare(const string &_A, const string &_B, const bool *_cmds)
{
_M_need_merge = 0;
_M_folder[0] = new Folder(_A);
_M_folder[1] = new Folder(_B);
for (int i = 0; i < _M_cnt_cmds; i++)
_M_cmds[i] = _cmds[i]; //复制一份cmd,一个类对象一个cmd命令,方便后续窗口化管理
_M_link();
}
/*
* Function: 构造函数
* Description: 构建文件夹,匹配并获得差异,最后合并,忽视最初输入的cmd选项
* Input: 两个文件(夹)路径,cmd输入
* Calls: _M_link,_M_merge
*/
Compare::Compare(const string &_A, const string &_B, const string &_C)
{
_M_dir_merge = _C;
_M_need_merge = 1;
_M_folder[0] = new Folder(_A);
_M_folder[1] = new Folder(_B);
for (int i = 0; i < _M_cnt_cmds; i++)
_M_cmds[i] = 0;
_M_link();
_M_merge();
}
/*
* Function: _M_link
* Description: 匹配文件夹,对每一对匹配成功的进行LCS
*/
void Compare::_M_link()
{
_M_results.clear(); //清空
if (_M_folder[0]->_M_only_file && _M_folder[1]->_M_only_file) //如果都是单一文件,则无视文件名强制比较
_M_results.push_back(new LCS(
_M_folder[0]->_M_base_dir + _M_folder[0]->_M_ext_dirs[0],
_M_folder[1]->_M_base_dir + _M_folder[1]->_M_ext_dirs[0],
_M_cmds));
else
{
//取两者交集进行LCS比较
vector<string> diff_A_B;
//STL求交集
std::set_intersection(
_M_folder[0]->_M_ext_dirs.begin(), _M_folder[0]->_M_ext_dirs.end(),
_M_folder[1]->_M_ext_dirs.begin(), _M_folder[1]->_M_ext_dirs.end(),
std::inserter(_M_file_intersection, _M_file_intersection.begin()));
for (const string &ext_file : _M_file_intersection)
_M_results.push_back(new LCS(
_M_folder[0]->_M_base_dir + ext_file,
_M_folder[1]->_M_base_dir + ext_file, _M_cmds));
//在A但是不在B中,直接给出结果
std::set_difference(
_M_folder[0]->_M_ext_dirs.begin(), _M_folder[0]->_M_ext_dirs.end(),
_M_folder[1]->_M_ext_dirs.begin(), _M_folder[1]->_M_ext_dirs.end(),
std::inserter(diff_A_B, diff_A_B.begin())); //STL直接求差集
for (const string &ext_file : diff_A_B)
cout << "File in A but not in B: " << _M_folder[0]->_M_base_dir << ext_file << endl;
//在B但不在A中,直接给出结果
diff_A_B.clear(); //复用空间
std::set_difference(
_M_folder[1]->_M_ext_dirs.begin(), _M_folder[1]->_M_ext_dirs.end(),
_M_folder[0]->_M_ext_dirs.begin(), _M_folder[0]->_M_ext_dirs.end(),
std::inserter(diff_A_B, diff_A_B.begin())); //STL直接求差集
for (const string &ext_file : diff_A_B)
cout << "File not in A but in B: " << _M_folder[1]->_M_base_dir << ext_file << endl;
}
}
/*
* Function: _M_merge
* Description: 合并文件夹内部匹配的内容
*/
void Compare::_M_merge()
{
//单个文件则直接输出
if (_M_folder[0]->_M_only_file && _M_folder[1]->_M_only_file)
for (LCS *result : _M_results)
result->merge(_M_dir_merge);
//很多文件则依照公共路径一起输出
else
{
size_type siz = _M_results.size(); //公共集的大小
if (_M_dir_merge.back() != '/' || _M_dir_merge.back() != '\\')
_M_dir_merge.append("\\"); //防止最后路径d:\tmp\section之类
for (size_type i = 0; i < siz; i++)
_M_results[i]->merge(_M_dir_merge + _M_file_intersection[i]); //合并
}
}
#endif | 32.663636 | 96 | 0.605344 | Ivy233 |
3e78b937cffbc29f9cdd4aec16bf5bd676bc5a41 | 957 | cpp | C++ | tests-lit/tests/tutorials/hello-world/step-3-one-survived-mutation/sample.cpp | m42e/mull | 32c6416d1757ea19c345029ee7a83e5769f231ef | [
"Apache-2.0"
] | null | null | null | tests-lit/tests/tutorials/hello-world/step-3-one-survived-mutation/sample.cpp | m42e/mull | 32c6416d1757ea19c345029ee7a83e5769f231ef | [
"Apache-2.0"
] | null | null | null | tests-lit/tests/tutorials/hello-world/step-3-one-survived-mutation/sample.cpp | m42e/mull | 32c6416d1757ea19c345029ee7a83e5769f231ef | [
"Apache-2.0"
] | null | null | null | // clang-format off
/**
RUN: cd / && %clang_cxx %sysroot -fembed-bitcode -g -O0 %s -o %s.exe
RUN: cd %CURRENT_DIR
RUN: (unset TERM; %mull_cxx -linker=%clang_cxx -linker-flags="%sysroot" -mutators=cxx_ge_to_lt -mutators=cxx_ge_to_gt -ide-reporter-show-killed %s.exe 2>&1; test $? = 0) | %filecheck %s --dump-input=fail --strict-whitespace --match-full-lines
CHECK:[info] Killed mutants (1/2):
CHECK:{{^.*}}sample.cpp:15:11: warning: Killed: Replaced >= with < [cxx_ge_to_lt]{{$}}
CHECK:[info] Survived mutants (1/2):
CHECK:{{^.*}}sample.cpp:15:11: warning: Survived: Replaced >= with > [cxx_ge_to_gt]{{$}}
CHECK:[info] Mutation score: 50%
**/
bool valid_age(int age) {
if (age >= 21) {
return true;
}
return false;
}
int main() {
bool test1 = valid_age(25) == true;
if (!test1) {
/// test failed
return 1;
}
bool test2 = valid_age(20) == false;
if (!test2) {
/// test failed
return 1;
}
/// success
return 0;
}
| 25.864865 | 242 | 0.629049 | m42e |
3e79dce6c1b11bf64056f1e0572a00771408b00c | 21,980 | cpp | C++ | src/bin/mail_utils/mbox2mail.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/bin/mail_utils/mbox2mail.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/bin/mail_utils/mbox2mail.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2005-2009, Haiku Inc.
* This file may be used under the terms of the MIT License.
*
* Originally public domain written by Alexander G. M. Smith.
*/
/*! MboxToBeMail is a utility program that converts Unix mailbox (mbox) files
(the kind that Pine uses) into e-mail files for use with BeOS. It also
handles news files from rn and trn, which have messages very similar to mail
messages but with a different separator line. The input files store
multiple mail messages in text format separated by "From ..." lines or
"Article ..." lines. The output is a bunch of separate files, each one with
one message plus BeOS BFS attributes describing that message. For
convenience, all the messages that were from one file are put in a specified
directory.
*/
#include <ctype.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <Application.h>
#include <E-mail.h>
#include <StorageKit.h>
#include <SupportKit.h>
#include <MailMessage.h>
#include <mail_util.h>
extern const char* __progname;
static const char* kProgramName = __progname;
char InputPathName [B_PATH_NAME_LENGTH];
FILE *InputFile;
BDirectory OutputDir;
typedef enum StandardHeaderEnum
{
STD_HDR_DATE = 0, /* The Date: field. First one since it is numeric. */
STD_HDR_FROM, /* The whole From: field, including quotes and address. */
STD_HDR_TO, /* All the stuff in the To: field. */
STD_HDR_CC, /* All the CC: field (originally means carbon copy). */
STD_HDR_REPLY, /* Things in the reply-to: field. */
STD_HDR_SUBJECT, /* The Subject: field. */
STD_HDR_PRIORITY, /* The Priority: and related fields, usually "Normal". */
STD_HDR_STATUS, /* The BeOS mail Read / New status text attribute. */
STD_HDR_THREAD, /* The subject simplified. */
STD_HDR_NAME, /* The From address simplified into a plain name. */
STD_HDR_MAX
} StandardHeaderCodes;
const char *g_StandardAttributeNames [STD_HDR_MAX] =
{
B_MAIL_ATTR_WHEN,
B_MAIL_ATTR_FROM,
B_MAIL_ATTR_TO,
B_MAIL_ATTR_CC,
B_MAIL_ATTR_REPLY,
B_MAIL_ATTR_SUBJECT,
B_MAIL_ATTR_PRIORITY,
B_MAIL_ATTR_STATUS,
B_MAIL_ATTR_THREAD,
B_MAIL_ATTR_NAME
};
/******************************************************************************
* Global utility function to display an error message and return. The message
* part describes the error, and if ErrorNumber is non-zero, gets the string
* ", error code $X (standard description)." appended to it. If the message
* is NULL then it gets defaulted to "Something went wrong".
*/
static void DisplayErrorMessage (
const char *MessageString = NULL,
int ErrorNumber = 0,
const char *TitleString = NULL)
{
char ErrorBuffer [B_PATH_NAME_LENGTH + 80 /* error message */ + 80];
if (TitleString == NULL)
TitleString = "Error Message:";
if (MessageString == NULL)
{
if (ErrorNumber == 0)
MessageString = "No error, no message, why bother?";
else
MessageString = "Something went wrong";
}
if (ErrorNumber != 0)
{
sprintf (ErrorBuffer, "%s, error code $%X/%d (%s) has occured.",
MessageString, ErrorNumber, ErrorNumber, strerror (ErrorNumber));
MessageString = ErrorBuffer;
}
fputs (TitleString, stderr);
fputc ('\n', stderr);
fputs (MessageString, stderr);
fputc ('\n', stderr);
}
/******************************************************************************
* Determine if a line of text is the start of another message. Pine mailbox
* files have messages that start with a line that could say something like
* "From agmsmith@achilles.net Fri Oct 31 21:19:36 EST 1997" or maybe something
* like "From POPmail Mon Oct 20 21:12:36 1997" or in a more modern format,
* "From agmsmith@achilles.net Tue Sep 4 09:04:11 2001 -0400". I generalise it
* to "From blah Day MMM NN XX:XX:XX TZONE1 YYYY TZONE2". Blah is an e-mail
* address you can ignore (just treat it as a word separated by spaces). Day
* is a 3 letter day of the week. MMM is a 3 letter month name. NN is the two
* digit day of the week, has a leading space if the day is less than 10.
* XX:XX:XX is the time, the X's are digits. TZONE1 is the old style optional
* time zone of 3 capital letters. YYYY is the four digit year. TZONE2 is the
* optional modern time zone info, a plus or minus sign and 4 digits. Returns
* true if the line of text (ended with a NUL byte, no line feed or carriage
* returns at the end) is the start of a message.
*/
bool IsStartOfMailMessage (char *LineString)
{
char *StringPntr;
/* It starts with "From " */
if (memcmp ("From ", LineString, 5) != 0)
return false;
StringPntr = LineString + 4;
while (*StringPntr == ' ')
StringPntr++;
/* Skip over the e-mail address (or stop at the end of string). */
while (*StringPntr != ' ' && *StringPntr != 0)
StringPntr++;
while (*StringPntr == ' ')
StringPntr++;
/* Look for the 3 letter day of the week. */
if (memcmp (StringPntr, "Mon", 3) != 0 &&
memcmp (StringPntr, "Tue", 3) != 0 &&
memcmp (StringPntr, "Wed", 3) != 0 &&
memcmp (StringPntr, "Thu", 3) != 0 &&
memcmp (StringPntr, "Fri", 3) != 0 &&
memcmp (StringPntr, "Sat", 3) != 0 &&
memcmp (StringPntr, "Sun", 3) != 0)
{
printf ("False alarm, not a valid day of the week in \"%s\".\n",
LineString);
return false;
}
StringPntr += 3;
while (*StringPntr == ' ')
StringPntr++;
/* Look for the 3 letter month code. */
if (memcmp (StringPntr, "Jan", 3) != 0 &&
memcmp (StringPntr, "Feb", 3) != 0 &&
memcmp (StringPntr, "Mar", 3) != 0 &&
memcmp (StringPntr, "Apr", 3) != 0 &&
memcmp (StringPntr, "May", 3) != 0 &&
memcmp (StringPntr, "Jun", 3) != 0 &&
memcmp (StringPntr, "Jul", 3) != 0 &&
memcmp (StringPntr, "Aug", 3) != 0 &&
memcmp (StringPntr, "Sep", 3) != 0 &&
memcmp (StringPntr, "Oct", 3) != 0 &&
memcmp (StringPntr, "Nov", 3) != 0 &&
memcmp (StringPntr, "Dec", 3) != 0)
{
printf ("False alarm, not a valid month name in \"%s\".\n",
LineString);
return false;
}
StringPntr += 3;
while (*StringPntr == ' ')
StringPntr++;
/* Skip the day of the month. Require at least one digit. */
if (*StringPntr < '0' || *StringPntr > '9')
{
printf ("False alarm, not a valid day of the month number in \"%s\".\n",
LineString);
return false;
}
while (*StringPntr >= '0' && *StringPntr <= '9')
StringPntr++;
while (*StringPntr == ' ')
StringPntr++;
/* Check the time. Look for the sequence
digit-digit-colon-digit-digit-colon-digit-digit. */
if (StringPntr[0] < '0' || StringPntr[0] > '9' ||
StringPntr[1] < '0' || StringPntr[1] > '9' ||
StringPntr[2] != ':' ||
StringPntr[3] < '0' || StringPntr[3] > '9' ||
StringPntr[4] < '0' || StringPntr[4] > '9' ||
StringPntr[5] != ':' ||
StringPntr[6] < '0' || StringPntr[6] > '9' ||
StringPntr[7] < '0' || StringPntr[7] > '9')
{
printf ("False alarm, not a valid time value in \"%s\".\n",
LineString);
return false;
}
StringPntr += 8;
while (*StringPntr == ' ')
StringPntr++;
/* Look for the optional antique 3 capital letter time zone and skip it. */
if (StringPntr[0] >= 'A' && StringPntr[0] <= 'Z' &&
StringPntr[1] >= 'A' && StringPntr[1] <= 'Z' &&
StringPntr[2] >= 'A' && StringPntr[2] <= 'Z')
{
StringPntr += 3;
while (*StringPntr == ' ')
StringPntr++;
}
/* Look for the 4 digit year. */
if (StringPntr[0] < '0' || StringPntr[0] > '9' ||
StringPntr[1] < '0' || StringPntr[1] > '9' ||
StringPntr[2] < '0' || StringPntr[2] > '9' ||
StringPntr[3] < '0' || StringPntr[3] > '9')
{
printf ("False alarm, not a valid 4 digit year in \"%s\".\n",
LineString);
return false;
}
StringPntr += 4;
while (*StringPntr == ' ')
StringPntr++;
/* Look for the optional modern time zone and skip over it if present. */
if ((StringPntr[0] == '+' || StringPntr[0] == '-') &&
StringPntr[1] >= '0' && StringPntr[1] <= '9' &&
StringPntr[2] >= '0' && StringPntr[2] <= '9' &&
StringPntr[3] >= '0' && StringPntr[3] <= '9' &&
StringPntr[4] >= '0' && StringPntr[4] <= '9')
{
StringPntr += 5;
while (*StringPntr == ' ')
StringPntr++;
}
/* Look for end of string. */
if (*StringPntr != 0)
{
printf ("False alarm, extra stuff after the year/time zone in \"%s\".\n",
LineString);
return false;
}
return true;
}
/******************************************************************************
* Determine if a line of text is the start of a news article. TRN and RN news
* article save files have messages that start with a line that looks like
* "Article 11721 of rec.games.video.3do:". Returns true if the line of text
* (ended with a NUL byte, no line feed or carriage returns at the end) is the
* start of an article.
*/
bool IsStartOfUsenetArticle (char *LineString)
{
char *StringPntr;
/* It starts with "Article " */
if (memcmp ("Article ", LineString, 8) != 0)
return false;
StringPntr = LineString + 7;
while (*StringPntr == ' ')
StringPntr++;
/* Skip the article number. Require at least one digit. */
if (*StringPntr < '0' || *StringPntr > '9')
{
printf ("False alarm, not a valid article number in \"%s\".\n",
LineString);
return false;
}
while (*StringPntr >= '0' && *StringPntr <= '9')
StringPntr++;
while (*StringPntr == ' ')
StringPntr++;
/* Now it should have "of " */
if (memcmp ("of ", StringPntr, 3) != 0)
{
printf ("False alarm, article line \"of\" misssing in \"%s\".\n",
LineString);
return false;
}
StringPntr += 2;
while (*StringPntr == ' ')
StringPntr++;
/* Skip over the newsgroup name (no spaces) to the colon. */
while (*StringPntr != ':' && *StringPntr != ' ' && *StringPntr != 0)
StringPntr++;
if (StringPntr[0] != ':' || StringPntr[1] != 0)
{
printf ("False alarm, article doesn't end with a colon in \"%s\".\n",
LineString);
return false;
}
return true;
}
/******************************************************************************
* Saves the message text to a file in the output directory. The file name is
* derived from the message headers. Returns zero if successful, a negative
* error code if an error occured.
*/
status_t SaveMessage (BString &MessageText)
{
time_t DateInSeconds;
status_t ErrorCode;
BString FileName;
BString HeaderValues [STD_HDR_MAX];
int i;
int Length;
BEmailMessage MailMessage;
BFile OutputFile;
char TempString [80];
struct tm TimeFields;
BString UniqueFileName;
int32 Uniquer;
/* Remove blank lines from the end of the message (a pet peeve of mine), but
end the message with a single new line to avoid annoying text editors that
like to have it. */
i = MessageText.Length ();
while (i > 0 && (MessageText[i-1] == '\n' || MessageText[i-1] == '\r'))
i--;
MessageText.Truncate (i);
MessageText.Append ("\r\n");
/* Make a pretend file to hold the message, so the MDR library can use it. */
BMemoryIO FakeFile (MessageText.String (), MessageText.Length ());
/* Hand the message text off to the MDR library, which will parse it, extract
the subject, sender's name, and other attributes, taking into account the
character set headers. */
ErrorCode = MailMessage.SetToRFC822 (&FakeFile,
MessageText.Length (), false /* parse_now - decodes message body */);
if (ErrorCode != B_OK)
{
DisplayErrorMessage ("Mail library was unable to process a mail "
"message for some reason", ErrorCode);
return ErrorCode;
}
/* Get the values for the standard attributes. NULL if missing. */
HeaderValues [STD_HDR_TO] = MailMessage.To ();
HeaderValues [STD_HDR_FROM] = MailMessage.From ();
HeaderValues [STD_HDR_CC] = MailMessage.CC ();
HeaderValues [STD_HDR_DATE] = MailMessage.Date ();
HeaderValues [STD_HDR_REPLY] = MailMessage.ReplyTo ();
HeaderValues [STD_HDR_SUBJECT] = MailMessage.Subject ();
HeaderValues [STD_HDR_STATUS] = "Read";
if (MailMessage.Priority () != 3 /* Normal */)
{
sprintf (TempString, "%d", MailMessage.Priority ());
HeaderValues [STD_HDR_PRIORITY] = TempString;
}
HeaderValues[STD_HDR_THREAD] = HeaderValues[STD_HDR_SUBJECT];
SubjectToThread (HeaderValues[STD_HDR_THREAD]);
if (HeaderValues[STD_HDR_THREAD].Length() <= 0)
HeaderValues[STD_HDR_THREAD] = "No Subject";
HeaderValues[STD_HDR_NAME] = HeaderValues[STD_HDR_FROM];
extract_address_name (HeaderValues[STD_HDR_NAME]);
// Generate a file name for the incoming message.
FileName = HeaderValues [STD_HDR_THREAD];
if (FileName[0] == '.')
FileName.Prepend ("_"); // Avoid hidden files, starting with a dot.
// Convert the date into a year-month-day fixed digit width format, so that
// sorting by file name will give all the messages with the same subject in
// order of date.
DateInSeconds =
ParseDateWithTimeZone (HeaderValues[STD_HDR_DATE].String());
if (DateInSeconds == -1)
DateInSeconds = 0; /* Set it to the earliest time if date isn't known. */
localtime_r (&DateInSeconds, &TimeFields);
sprintf (TempString, "%04d%02d%02d%02d%02d%02d",
TimeFields.tm_year + 1900,
TimeFields.tm_mon + 1,
TimeFields.tm_mday,
TimeFields.tm_hour,
TimeFields.tm_min,
TimeFields.tm_sec);
FileName << " " << TempString << " " << HeaderValues[STD_HDR_NAME];
FileName.Truncate (240); // reserve space for the uniquer
// Get rid of annoying characters which are hard to use in the shell.
FileName.ReplaceAll('/','_');
FileName.ReplaceAll('\'','_');
FileName.ReplaceAll('"','_');
FileName.ReplaceAll('!','_');
FileName.ReplaceAll('<','_');
FileName.ReplaceAll('>','_');
while (FileName.FindFirst(" ") >= 0) // Remove multiple spaces.
FileName.Replace(" " /* Old */, " " /* New */, 1024 /* Count */);
Uniquer = 0;
UniqueFileName = FileName;
while (true)
{
ErrorCode = OutputFile.SetTo (&OutputDir,
const_cast<const char *> (UniqueFileName.String ()),
B_READ_WRITE | B_CREATE_FILE | B_FAIL_IF_EXISTS);
if (ErrorCode == B_OK)
break;
if (ErrorCode != B_FILE_EXISTS)
{
UniqueFileName.Prepend ("Unable to create file \"");
UniqueFileName.Append ("\" for writing a message to");
DisplayErrorMessage (UniqueFileName.String (), ErrorCode);
return ErrorCode;
}
Uniquer++;
UniqueFileName = FileName;
UniqueFileName << " " << Uniquer;
}
/* Write the message contents to the file, use the unchanged original one. */
ErrorCode = OutputFile.Write (MessageText.String (), MessageText.Length ());
if (ErrorCode < 0)
{
UniqueFileName.Prepend ("Error while writing file \"");
UniqueFileName.Append ("\"");
DisplayErrorMessage (UniqueFileName.String (), ErrorCode);
return ErrorCode;
}
/* Attach the attributes to the file. Save the MIME type first, otherwise
the live queries don't pick up the new file. Theoretically it would be
better to do it last so that other programs don't start reading the message
before the other attributes are set. */
OutputFile.WriteAttr ("BEOS:TYPE", B_MIME_STRING_TYPE, 0,
"text/x-email", 13);
OutputFile.WriteAttr (g_StandardAttributeNames[STD_HDR_DATE],
B_TIME_TYPE, 0, &DateInSeconds, sizeof (DateInSeconds));
/* Write out all the string based attributes. */
for (i = 1 /* The date was zero */; i < STD_HDR_MAX; i++)
{
if ((Length = HeaderValues[i].Length()) > 0)
OutputFile.WriteAttr (g_StandardAttributeNames[i], B_STRING_TYPE, 0,
HeaderValues[i].String(), Length + 1);
}
return 0;
}
int main (int argc, char** argv)
{
char ErrorMessage [B_PATH_NAME_LENGTH + 80];
bool HaveOldMessage = false;
int MessagesDoneCount = 0;
BString MessageText;
BApplication MyApp ("application/x-vnd.Haiku-mbox2mail");
int NextArgIndex;
char OutputDirectoryPathName [B_PATH_NAME_LENGTH];
status_t ReturnCode = -1;
bool SaveSeparatorLine = false;
char *StringPntr;
char TempString [102400];
if (argc <= 1)
{
printf ("%s is a utility for converting Pine e-mail\n",
argv[0]);
printf ("files (mbox files) to Mail e-mail files with attributes. It\n");
printf ("could well work with other Unix style mailbox files, and\n");
printf ("saved Usenet article files. Each message in the input\n");
printf ("mailbox is converted into a separate file. You can\n");
printf ("optionally specify a directory (will be created if needed) to\n");
printf ("put all the output files in, otherwise it scatters them into\n");
printf ("the current directory. The -s option makes it leave in the\n");
printf ("separator text line at the top of each message, the default\n");
printf ("is to lose it.\n\n");
printf ("Usage:\n\n");
printf ("%s [-s] InputFile [OutputDirectory]\n\n", kProgramName);
printf ("Public domain, by Alexander G. M. Smith.\n");
return -10;
}
NextArgIndex = 1;
if (strcmp (argv[NextArgIndex], "-s") == 0)
{
SaveSeparatorLine = true;
NextArgIndex++;
}
/* Try to open the input file. */
if (NextArgIndex >= argc)
{
ReturnCode = -20;
DisplayErrorMessage ("Missing the input file (mbox file) name argument.");
goto ErrorExit;
}
strncpy (InputPathName, argv[NextArgIndex], sizeof (InputPathName) - 1);
NextArgIndex++;
InputFile = fopen (InputPathName, "rb");
if (InputFile == NULL)
{
ReturnCode = errno;
sprintf (ErrorMessage, "Unable to open file \"%s\" for reading",
InputPathName);
DisplayErrorMessage (ErrorMessage, ReturnCode);
goto ErrorExit;
}
/* Try to make the output directory. First get its name. */
if (NextArgIndex < argc)
{
strncpy (OutputDirectoryPathName, argv[NextArgIndex],
sizeof (OutputDirectoryPathName) - 2
/* Leave space for adding trailing slash and NUL byte */);
NextArgIndex++;
}
else
strcpy (OutputDirectoryPathName, ".");
/* Remove trailing '/' characters from the output directory path. */
StringPntr =
OutputDirectoryPathName + (strlen (OutputDirectoryPathName) - 1);
while (StringPntr >= OutputDirectoryPathName)
{
if (*StringPntr != '/')
break;
StringPntr--;
}
*(++StringPntr) = 0;
if (StringPntr - OutputDirectoryPathName > 0 &&
strcmp (OutputDirectoryPathName, ".") != 0)
{
if (mkdir (OutputDirectoryPathName, 0777))
{
ReturnCode = errno;
if (ReturnCode != B_FILE_EXISTS)
{
sprintf (ErrorMessage, "Unable to make output directory \"%s\"",
OutputDirectoryPathName);
DisplayErrorMessage (ErrorMessage, ReturnCode);
goto ErrorExit;
}
}
}
/* Set the output BDirectory. */
ReturnCode = OutputDir.SetTo (OutputDirectoryPathName);
if (ReturnCode != B_OK)
{
sprintf (ErrorMessage, "Unable to set output BDirectory to \"%s\"",
OutputDirectoryPathName);
DisplayErrorMessage (ErrorMessage, ReturnCode);
goto ErrorExit;
}
printf ("Input file: \"%s\", Output directory: \"%s\", ",
InputPathName, OutputDirectoryPathName);
printf ("%ssaving separator text line at the top of each message. Working",
SaveSeparatorLine ? "" : "not ");
/* Extract a text message from the mail file. It starts with a line that
says "From blah Day MM NN XX:XX:XX YYYY TZONE". Blah is an e-mail address
you can ignore (just treat it as a word separated by spaces). Day is a 3
letter day of the week. MM is a 3 letter month name. NN is the two digit
day of the week, has a leading space if the day is less than 10. XX:XX:XX is
the time, the X's are digits. YYYY is the four digit year. TZONE is the
optional time zone info, a plus or minus sign and 4 digits. */
while (!feof (InputFile))
{
/* First read in one line of text. */
if (!fgets (TempString, sizeof (TempString), InputFile))
{
ReturnCode = errno;
if (ferror (InputFile))
{
sprintf (ErrorMessage,
"Error while reading from \"%s\"", InputPathName);
DisplayErrorMessage (ErrorMessage, ReturnCode);
goto ErrorExit;
}
break; /* No error, just end of file. */
}
/* Remove any trailing control characters (line feed usually, or CRLF).
Might also nuke trailing tabs too. Doesn't usually matter. The main thing
is to allow input files with both LF and CRLF endings (and even CR endings
if you come from the Macintosh world). */
StringPntr = TempString + strlen (TempString) - 1;
while (StringPntr >= TempString && *StringPntr < 32)
StringPntr--;
*(++StringPntr) = 0;
/* See if this is the start of a new message. */
if (IsStartOfUsenetArticle (TempString) ||
IsStartOfMailMessage (TempString))
{
if (HaveOldMessage)
{
if ((ReturnCode = SaveMessage (MessageText)) != 0)
goto ErrorExit;
putchar ('.');
fflush (stdout);
MessagesDoneCount++;
}
HaveOldMessage = true;
MessageText.SetTo (SaveSeparatorLine ? TempString : "");
}
else
{
/* Append the line to the current message text. */
if (MessageText.Length () > 0)
MessageText.Append ("\r\n"); /* Yes, BeMail expects CR/LF line ends. */
MessageText.Append (TempString);
}
}
/* Flush out the last message. */
if (HaveOldMessage)
{
if ((ReturnCode = SaveMessage (MessageText)) != 0)
goto ErrorExit;
putchar ('.');
MessagesDoneCount++;
}
printf (" Did %d messages.\n", MessagesDoneCount);
ReturnCode = 0;
ErrorExit:
if (InputFile != NULL)
fclose (InputFile);
OutputDir.Unset ();
return ReturnCode;
}
| 31.535151 | 79 | 0.629163 | Kirishikesan |
3e7a4e44ca7e1385d3b922bff4ded9006411e401 | 84 | cpp | C++ | 002_DESIGN_PATTERN/Abstract_Factory/Abstract_Factory/Wall.cpp | JooHyeon-Roh/Cpp | 09410fef092428739c1cad3f15faa4b5cf0b4b76 | [
"MIT"
] | null | null | null | 002_DESIGN_PATTERN/Abstract_Factory/Abstract_Factory/Wall.cpp | JooHyeon-Roh/Cpp | 09410fef092428739c1cad3f15faa4b5cf0b4b76 | [
"MIT"
] | null | null | null | 002_DESIGN_PATTERN/Abstract_Factory/Abstract_Factory/Wall.cpp | JooHyeon-Roh/Cpp | 09410fef092428739c1cad3f15faa4b5cf0b4b76 | [
"MIT"
] | null | null | null | #include "Wall.h"
CWall::CWall()
{
}
CWall::~CWall()
{
}
void CWall::Enter()
{
}
| 6 | 19 | 0.547619 | JooHyeon-Roh |
3e7b9b08a6abb87111adf9ccf8abab0884ea124a | 5,349 | cpp | C++ | cops/live/stitcher.cpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 115 | 2019-09-28T13:39:41.000Z | 2022-03-24T11:08:53.000Z | cops/live/stitcher.cpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 113 | 2019-10-08T23:51:29.000Z | 2021-12-12T06:47:38.000Z | cops/live/stitcher.cpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 44 | 2019-09-28T07:53:21.000Z | 2022-02-13T23:21:12.000Z | // This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#include "stitcher.hpp"
#include <fstream>
#include "lgedgeiter.hpp"
Live_stitcher::Live_stitcher(Stitch_pass_options &pack) {
std::ifstream invariant_file(pack.boundaries_name);
if (!invariant_file.good()) {
Pass::error(fmt::format("Live_stitcher: Error reading boundaries file {}", pack.boundaries_name));
return;
}
boundaries = Invariant_boundaries::deserialize(invariant_file);
invariant_file.close();
original = Lgraph::open(pack.osynth_lgdb, boundaries->top);
if (!original) {
Pass::error(fmt::format("Live_stitcher: I was not able to open original synthesized netlist {} in {}",
boundaries->top,
pack.osynth_lgdb));
}
}
void Live_stitcher::stitch(Lgraph *nsynth, const std::set<Net_ID> &diffs) {
std::map<Index_id, Index_id> nsynth2originalid;
std::map<Index_id, Index_id> inp2originalid;
std::map<Index_id, Index_id> out2originalid;
// add new cells
for (auto &idx : nsynth->fast()) {
if (nsynth->node_type_get(idx).op == GraphIO_Op) {
// FIXME: how to check if there are new global IOs?
// FIXME: how to check if I need to delete global IOs?
auto name = nsynth->get_node_wirename(idx);
if (original->has_graph_input(name)) {
inp2originalid[idx] = original->get_graph_input(name).get_idx();
} else if (original->has_graph_output(name)) {
out2originalid[idx] = original->get_graph_output(name).get_idx();
} else {
if (original->has_wirename(name)) {
inp2originalid[idx] = original->get_node_id(name);
} else {
// Pass::>error("Wire {} not found in original synthesized graph\n",name);
}
}
else {
Index_id nidx = original->create_node().get_nid();
nsynth2originalid[idx] = nidx;
switch (nsynth->node_type_get(idx).op) {
case TechMap_Op: original->node_tmap_set(nidx, nsynth->tmap_id_get(idx)); break;
case Join_Op:
case Pick_Op: original->node_type_set(nidx, nsynth->node_type_get(idx).op); break;
case U32Const_Op: original->node_u32type_set(nidx, nsynth->node_value_get(idx)); break;
case StrConst_Op: original->node_const_type_set(nidx, nsynth->node_const_value_get(idx)); break;
default: Pass::error("live.stitcher: unsupported synthesized type");
}
}
}
// connect new cells
for (auto &idx : nsynth->fast()) {
if (!nsynth->has_graph_output(idx)) {
for (auto &c : nsynth->inp_edges(idx)) {
// if driver is in the delta region
if (nsynth2originalid.find(nsynth->get_node(c.get_out_pin()).get_nid()) != nsynth2originalid.end()) {
auto dnode = original->get_node(nsynth2originalid[nsynth->get_node(c.get_out_pin()).get_nid()]);
auto snode = original->get_node(nsynth2originalid[nsynth->get_node(c.get_inp_pin()).get_nid()]);
auto dpin = dnode.setup_driver_pin(c.get_out_pin().get_pid());
auto spin = snode.setup_sink_pin(c.get_inp_pin().get_pid());
original->add_edge(dpin, spin);
} else {
if (inp2originalid.find(idx) != inp2originalid.end()) {
auto dnode = original->get_node(inp2originalid[idx]);
auto snode = original->get_node(nsynth2originalid[nsynth->get_node(c.get_inp_pin()).get_nid()]);
auto spin = snode.setup_sink_pin(c.get_inp_pin().get_pid());
auto dpin = dnode.setup_driver_pin(); // FIXME: is there a case where I need to consider the out pid?
original->add_edge(dpin, spin);
}
}
}
} else {
if (out2originalid.find(idx) != out2originalid.end()) {
// global output
// FIXME: I need to consider the inp PID
for (auto &c : nsynth->inp_edges(idx)) {
Node_pin dpin = original->get_node(nsynth2originalid[nsynth->get_node(c.get_out_pin()).get_nid()])
.setup_driver_pin(c.get_out_pin().get_pid());
Node_pin spin = original->get_node(out2originalid[idx]).setup_sink_pin(out2originalid[idx]);
original->add_edge(dpin, spin);
}
} else {
// invariant boundary
auto name = nsynth->get_node_wirename(idx);
if (!original->has_wirename(name))
continue;
Index_id oidx = original->get_node_id(name);
for (auto &edge : original->out_edges(oidx)) {
Node_pin dpin = original->get_node(nsynth2originalid[idx]).setup_driver_pin(edge.get_out_pin().get_pid());
original->add_edge(dpin, edge.get_inp_pin());
original->del_edge(edge);
}
}
}
}
// removed original graph
for (auto &diff : diffs) {
I(boundaries->invariant_cone_cells.find(diff) != boundaries->invariant_cone_cells.end());
for (auto &gate : boundaries->invariant_cone_cells[diff]) {
I(boundaries->gate_appearances.find(gate) != boundaries->gate_appearances.end());
boundaries->gate_appearances[gate]--;
if (boundaries->gate_appearances[gate] <= 0) {
// original->del_node(gate);
}
}
}
original->sync();
}
| 40.832061 | 118 | 0.621051 | jesec |
3e7ccc6a681a1c231e4b59721ccb012140da6ba9 | 3,882 | hpp | C++ | include/boost/sql/sqlite3/statement.hpp | purpleKarrot/async-db | 172124e5657e3085e8ac7729c4e578c0d766bf7b | [
"BSL-1.0"
] | 5 | 2016-09-19T01:02:33.000Z | 2019-10-23T07:15:00.000Z | include/boost/sql/sqlite3/statement.hpp | purpleKarrot/async-db | 172124e5657e3085e8ac7729c4e578c0d766bf7b | [
"BSL-1.0"
] | null | null | null | include/boost/sql/sqlite3/statement.hpp | purpleKarrot/async-db | 172124e5657e3085e8ac7729c4e578c0d766bf7b | [
"BSL-1.0"
] | null | null | null | /**************************************************************
* Copyright (c) 2008-2009 Daniel Pfeifer *
* *
* Distributed under the Boost Software License, Version 1.0. *
**************************************************************/
#ifndef BOOST_SQL_SQLITE3_STATEMENT_HPP
#define BOOST_SQL_SQLITE3_STATEMENT_HPP
#include <boost/sql/sqlite3/connection.hpp>
#include <boost/sql/sqlite3/detail/bind_params.hpp>
#include <boost/sql/sqlite3/detail/bind_result.hpp>
#include <boost/sql/sqlite3/detail/error.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/sql/detail/callable.hpp>
#include <boost/sql/detail/handler.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <string>
namespace boost
{
namespace sql
{
namespace sqlite3
{
template<typename Param, typename Result>
class statement
{
enum
{
param_count = mpl::size<Param>::value,
result_count = mpl::size<Result>::value
};
public:
statement(connection& c, const std::string& query) :
stmt(0), conn(c), query_str(query), prepared(false)
{
}
~statement()
{
sqlite3_finalize(stmt);
}
std::string error_message() const
{
return sqlite3_errmsg(conn.implementation());
}
void prepare(boost::system::error_code& error)
{
error.assign(sqlite3_prepare_v2(conn.implementation(),
query_str.c_str(), query_str.size(), &stmt, 0),
get_error_category());
if (error)
return;
BOOST_ASSERT(sqlite3_bind_parameter_count(stmt) == param_count);
BOOST_ASSERT(sqlite3_column_count(stmt) == result_count);
prepared = true;
}
void prepare()
{
boost::system::error_code error;
prepare(error);
if (error)
throw std::runtime_error(error_message());
}
template<typename Handler>
void async_prepare(Handler handler)
{
post(boost::bind(statement::prepare, this, _1), handler);
}
void execute(const Param& params, boost::system::error_code& error)
{
if (!prepared)
{
prepare(error);
if (error)
return;
}
error.assign(sqlite3_reset(stmt), get_error_category());
if (error)
return;
error.assign(detail::bind_params(stmt, params), get_error_category());
if (error)
return;
typedef int(*step_or_reset_function)(sqlite3_stmt*);
step_or_reset_function step_or_reset = //
sqlite3_column_count(stmt) ? sqlite3_reset : sqlite3_step;
error.assign(step_or_reset(stmt), get_error_category());
if (error.value() == SQLITE_DONE)
error = boost::system::error_code();
}
void execute(const Param& params)
{
boost::system::error_code error;
execute(params, error);
if (error)
throw std::runtime_error(error_message());
}
template<typename Handler>
void async_execute(const Param& params, Handler handler)
{
post(boost::bind(&statement::execute, this, params, _1), handler);
}
bool fetch(Result& result)
{
switch (sqlite3_step(stmt))
{
case SQLITE_ROW:
fusion::for_each(result, detail::bind_result(stmt));
return true;
case SQLITE_DONE:
sqlite3_reset(stmt);
return false;
case SQLITE_ERROR:
// SQLITE_ERROR is a generic error code.
// must call sqlite3_reset() to get the specific error message.
sqlite3_reset(stmt);
}
throw std::runtime_error(error_message());
}
// template<typename Handler>
// void async_fetch(Result& result, Handler handler)
// {
// post(boost::bind(statement::prepare, this, _1), handler);
// }
private:
template<typename Function, typename Callback>
void post(Function function, Callback callback)
{
conn.get_io_service().post(sql::detail::handler<Function, Callback>(
conn.get_io_service(), function, callback));
}
sqlite3_stmt* stmt;
connection& conn;
std::string query_str;
bool prepared;
};
} // end namespace sqlite3
} // end namespace sql
} // end namespace boost
#endif /*BOOST_SQL_SQLITE3_STATEMENT_HPP*/
| 23.245509 | 72 | 0.679289 | purpleKarrot |
3e7d513955fdfbaf8a2e691512a16bdbd4c986b2 | 14,658 | cpp | C++ | packages/worldModel/src/adapters/RTDB/RTDBInputAdapter.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 2 | 2021-01-15T13:27:19.000Z | 2021-08-04T08:40:52.000Z | packages/worldModel/src/adapters/RTDB/RTDBInputAdapter.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | null | null | null | packages/worldModel/src/adapters/RTDB/RTDBInputAdapter.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 5 | 2018-05-01T10:39:31.000Z | 2022-03-25T03:02:35.000Z | // Copyright 2018-2020 Erik Kouters (Falcons)
// SPDX-License-Identifier: Apache-2.0
/*
* RTDBInputAdapter.cpp
*
* Created on: Oct 27, 2018
* Author: Erik Kouters
*/
#include "int/adapters/RTDB/RTDBInputAdapter.hpp"
//
#include "falconsCommon.hpp" //getRobotNumber()
#include "cDiagnostics.hpp"
#include "tracing.hpp"
RTDBInputAdapter::RTDBInputAdapter()
{
TRACE_FUNCTION("");
// init data
_visionBallPossession = false;
_inPlay = robotStatusType::INVALID;
_ballAdmin = 0;
_robotAdmin = 0;
_obstacleAdmin = 0;
_myRobotId = getRobotNumber();
_rtdb = RtDB2Store::getInstance().getRtDB2(_myRobotId);
_robotDisplacementInitialized = false;
_uIDGenerator = identifierGenerator(_myRobotId);
}
RTDBInputAdapter::~RTDBInputAdapter()
{
}
void RTDBInputAdapter::setBallAdministrator(ballAdministrator *ballAdmin)
{
_ballAdmin = ballAdmin;
}
void RTDBInputAdapter::setObstacleAdministrator(obstacleAdministrator *obstacleAdmin)
{
_obstacleAdmin = obstacleAdmin;
}
void RTDBInputAdapter::setRobotAdministrator(robotAdministrator *robotAdmin)
{
_robotAdmin = robotAdmin;
}
void RTDBInputAdapter::updateConfig(T_CONFIG_WORLDMODELSYNC const &config)
{
_config = config;
}
template <typename T1>
T1 convertObjectRCSToFCS(T1 &objCandidate, Position2D &robotPos)
{
float camZ = objCandidate.cameraZ;
Position2D camRcs(objCandidate.cameraX, objCandidate.cameraY, objCandidate.cameraPhi);
Position2D camFcs = camRcs.transform_rcs2fcs(robotPos);
T1 measurementFCS = objCandidate;
measurementFCS.cameraX = camFcs.x;
measurementFCS.cameraY = camFcs.y;
measurementFCS.cameraZ = camZ;
measurementFCS.cameraPhi = camFcs.phi;
return measurementFCS;
}
bool RTDBInputAdapter::useVisionFromRobot(int robotId)
{
// get teamId belonging to given robotId
T_ROBOT_STATE robotState;
int r = _rtdbClient._rtdb.at(robotId)->get(ROBOT_STATE, &robotState, robotId);
if (r != RTDB2_SUCCESS)
{
return false;
}
teamIdType otherTeamId = robotState.teamId;
if (_config.useVisionFrom.find(otherTeamId) != std::string::npos)
{
// id found
return true;
}
return false;
}
void RTDBInputAdapter::getBallCandidates()
{
TRACE_FUNCTION("");
// only continue if valid loc
if (!_robotAdmin->inplay())
{
return;
}
// First put the Local FCS data to RTDB
T_BALL_CANDIDATES_FCS measurementsFcs;
int r = _rtdb->get(BALL_CANDIDATES, &_ballCandidates);
if (r == RTDB2_SUCCESS)
{
// convert camera position from RCS to FCS for each ball measurement
if (_ballCandidates.size())
{
robotClass_t pos = _robotAdmin->getLocalRobotPosition(_ballCandidates[0].timestamp);
Position2D robotPos(pos.getX(), pos.getY(), pos.getTheta());
for (auto it = _ballCandidates.begin(); it != _ballCandidates.end(); ++it)
{
ballMeasurement ballMeasFcs = convertObjectRCSToFCS(*it, robotPos);
measurementsFcs.push_back(ballMeasFcs);
}
}
if (_config.shareVision)
{
_rtdb->put(BALL_CANDIDATES_FCS, &measurementsFcs);
// clear measurements here so that when this is being stimulated all data can be read
// from rtdb instead of calculated
measurementsFcs.clear();
}
}
// Then get the Shared FCS data from RTDB
std::vector<int>::const_iterator it;
for (it = _rtdbClient._agentIds.begin(); it != _rtdbClient._agentIds.end(); ++it)
{
// skipping self is only needed when sharevision if false, as then the data will not be on rtdb
if (*it != _myRobotId || _config.shareVision)
{
// Skip if configured to ignore
if (!useVisionFromRobot(*it))
{
continue;
}
T_BALL_CANDIDATES_FCS sharedMeasurements;
r = _rtdbClient._rtdb.at(*it)->get(BALL_CANDIDATES_FCS, &sharedMeasurements, *it);
if (r == RTDB2_SUCCESS)
{
// Add sharedMeasurements to measurementsFcs
measurementsFcs.insert(measurementsFcs.end(), sharedMeasurements.begin(), sharedMeasurements.end());
}
}
}
// Finally, write measurements to the administrator
_ballAdmin->appendBallMeasurements(measurementsFcs);
}
void RTDBInputAdapter::getObstacleCandidates()
{
TRACE_FUNCTION("");
// only continue if valid loc
if (!_robotAdmin->inplay())
{
return;
}
int r = _rtdb->get(OBSTACLE_CANDIDATES, &_obstacleCandidates);
// First put the Local FCS candidates to RTDB for sharing with other robots
T_OBSTACLE_CANDIDATES_FCS measurementsFcs;
if (r == RTDB2_SUCCESS)
{
// convert camera position from RCS to FCS for each obstacle measurement
// while performing latency correction, assuming all obstacles have the same timestamp (TODO)
if (_obstacleCandidates.size())
{
robotClass_t pos = _robotAdmin->getLocalRobotPosition(_obstacleCandidates[0].timestamp);
Position2D robotPos(pos.getX(), pos.getY(), pos.getTheta());
int iter = 0;
for (auto it = _obstacleCandidates.begin(); it != _obstacleCandidates.end(); ++it)
{
obstacleMeasurement obstacleMeasFcs = convertObjectRCSToFCS(*it, robotPos);
measurementsFcs.push_back(obstacleMeasFcs);
iter++;
}
if (_config.shareVision)
{
_rtdb->put(OBSTACLE_CANDIDATES_FCS, &measurementsFcs);
// clear measurements here so that when this is being stimulated all data can be read
// from rtdb instead of calculated
measurementsFcs.clear();
}
}
}
// Then get the Shared FCS candidates from RTDB from other robots
std::vector<int>::const_iterator it;
for (it = _rtdbClient._agentIds.begin(); it != _rtdbClient._agentIds.end(); ++it)
{
// skipping self is only needed when sharevision if false, as then the data will not be on rtdb
if (*it != _myRobotId || _config.shareVision)
{
// Skip if configured to ignore
if (!useVisionFromRobot(*it))
{
continue;
}
T_OBSTACLE_CANDIDATES_FCS sharedMeasurements;
r = _rtdbClient._rtdb.at(*it)->get(OBSTACLE_CANDIDATES_FCS, &sharedMeasurements, *it);
if (r == RTDB2_SUCCESS)
{
// Add sharedMeasurements to measurementsFcs
measurementsFcs.insert(measurementsFcs.end(), sharedMeasurements.begin(), sharedMeasurements.end());
}
}
}
// Finally, write measurements to the administrator
_obstacleAdmin->appendObstacleMeasurements(measurementsFcs);
}
void RTDBInputAdapter::getLocalizationCandidates()
{
TRACE_FUNCTION("");
int r = _rtdb->get(LOCALIZATION_CANDIDATES, &_localizationCandidates, _myRobotId);
if (r != RTDB2_SUCCESS)
{
return;
}
// convert sharedType to WM internal type
std::vector<robotMeasurementClass_t> robotMeasurements;
T_LOCALIZATION_CANDIDATES::const_iterator it;
for (it = _localizationCandidates.begin(); it != _localizationCandidates.end(); ++it)
{
robotMeasurementClass_t robotMeas;
robotMeas.setID(it->identifier);
robotMeas.setTimestamp(it->timestamp);
robotMeas.setConfidence(it->confidence);
robotMeas.setCoordinateType(coordinateType::FIELD_COORDS);
robotMeas.setPosition(it->x, it->y, it->theta);
robotMeasurements.push_back(robotMeas);
}
if (r == RTDB2_SUCCESS)
{
// Write measurements to the administrator
_robotAdmin->appendRobotVisionMeasurements(robotMeasurements);
}
}
void RTDBInputAdapter::getVisionBallPossession()
{
TRACE_FUNCTION("");
RtDB2Item item;
int r = _rtdb->getItem(VIS_BALL_POSSESSION, item);
if (r != RTDB2_SUCCESS)
{
return;
}
// _visionBallPossession is only written when TRUE, so use age to determine ball possession
// ball possession when age < 500ms
_visionBallPossession = item.value<T_VIS_BALL_POSSESSION>();
if (_visionBallPossession && item.age() < 0.500)
{
_robotAdmin->setBallPossessionVision(true);
}
else
{
_robotAdmin->setBallPossessionVision(false);
}
}
void RTDBInputAdapter::getRobotDisplacement(rtime timeNow)
{
TRACE_FUNCTION("");
int ageMs = 0;
T_ROBOT_DISPLACEMENT_FEEDBACK newDisplacement;
int r = _rtdb->get(ROBOT_DISPLACEMENT_FEEDBACK, &newDisplacement, ageMs, _myRobotId);
if (r != RTDB2_SUCCESS)
{
return;
}
if (_robotDisplacementInitialized)
{
std::vector<robotDisplacementClass_t> displacements;
robotDisplacementClass_t displacement;
displacement.setID(_uIDGenerator.getUniqueID());
displacement.setTimestamp(rtime::now());
displacement.setCoordinateType(coordinateType::ROBOT_COORDS);
displacement.setDisplacementSource(displacementType::MOTORS);
displacement.setDeltaPosition(
newDisplacement.x - _prevRobotDisplacement.x,
newDisplacement.y - _prevRobotDisplacement.y,
newDisplacement.Rz - _prevRobotDisplacement.Rz);
displacements.push_back(displacement);
// tprintf("encoder displacement: dx=%7.3f dy=%7.3f dRz=%7.3f", displacement.getdX(), displacement.getdY(), displacement.getdTheta());
if(_robotAdmin != NULL)
{
_robotAdmin->appendRobotDisplacementMeasurements(displacements);
}
}
else
{
// The motors can have a big displacement when worldModel starts.
// Therefore we use the first tick to initialize _prevRobotDisplacement with the displacements in RTDB.
_robotDisplacementInitialized = true;
}
_prevRobotDisplacement = newDisplacement;
}
void RTDBInputAdapter::getRobotVelocity(rtime timeNow)
{
TRACE_FUNCTION("");
int r = _rtdb->get(ROBOT_VELOCITY_FEEDBACK, &_robotVelocity);
if (r != RTDB2_SUCCESS)
{
return;
}
std::vector<robotVelocityClass_t> velocities;
robotVelocityClass_t velocity;
velocity.setID(_uIDGenerator.getUniqueID());
velocity.setTimestamp(timeNow);
velocity.setCoordinateType(coordinateType::ROBOT_COORDS);
velocity.setDisplacementSource(displacementType::MOTORS);
velocity.setDeltaVelocity(
_robotVelocity.x,
_robotVelocity.y,
_robotVelocity.Rz);
velocities.push_back(velocity);
if(_robotAdmin != NULL)
{
_robotAdmin->appendRobotVelocityMeasurements(velocities);
}
//tprintf("encoder velocity : dx=%7.3f dy=%7.3f dRz=%7.3f", _robotVelocity.x, _robotVelocity.y, _robotVelocity.Rz);
}
void RTDBInputAdapter::enableInplayOverrule()
{
_inplayOverrule = true;
}
void RTDBInputAdapter::getInPlayState(rtime timeNow)
{
TRACE_FUNCTION("");
T_INPLAY_FEEDBACK currentInPlay;
if (_config.forceInplay == true || _inplayOverrule)
{
// testing override
currentInPlay = robotStatusEnum::INPLAY;
}
else
{
// regular behavior: get data from RTDB
int r = 0;
r = _rtdb->get(INPLAY_FEEDBACK, ¤tInPlay);
// check if we have OK data
if (r != RTDB2_SUCCESS)
{
return;
}
}
// convert to worldmodel's inplay type
robotStatusType wmInPlay = robotStatusType::INVALID;
switch(currentInPlay)
{
case robotStatusEnum::INPLAY:
{
wmInPlay = robotStatusType::INPLAY;
break;
}
case robotStatusEnum::OUTOFPLAY:
{
wmInPlay = robotStatusType::OUTOFPLAY;
break;
}
default:
{
TRACE_ERROR("Received unexpected robot status type %d", currentInPlay);
break;
}
}
// new state detected
if (_inPlay != wmInPlay)
{
_robotAdmin->setRobotStatus(_myRobotId, wmInPlay, timeNow);
// generate an event, for eventlogging on coach
if (wmInPlay == robotStatusType::INPLAY)
{
TRACE_INFO("switched to INPLAY");
}
else
{
TRACE_INFO("switched to OUTOFPLAY");
}
_inPlay = wmInPlay;
}
}
void RTDBInputAdapter::getBallHandlingBallPossession()
{
TRACE_FUNCTION("");
T_BALLHANDLERS_BALL_POSSESSION ballIsCaughtByBallHandlers;
int r = _rtdb->get(BALLHANDLERS_BALL_POSSESSION, &ballIsCaughtByBallHandlers);
if (r != RTDB2_SUCCESS)
{
return;
}
_robotAdmin->setBallPossessionBallHandlers(ballIsCaughtByBallHandlers);
}
void RTDBInputAdapter::getTeamMembers()
{
TRACE_FUNCTION("");
// check for NULL pointers
if ((_robotAdmin == NULL) || (_rtdb == NULL))
{
TRACE_ERROR("NULL pointer exception");
return;
}
// get data from teammembers
T_ROBOT_STATE robotRtdb;
for (int agent = 1; agent <= MAX_ROBOTS; ++agent)
{
// only process teammembers, not ourself
if (agent != _myRobotId)
{
int r = _rtdb->get(ROBOT_STATE, &robotRtdb, agent);
// require a successful GET but also data not too old (say from a previous session)
if (r == RTDB2_SUCCESS)
{
// convert to wm-internal struct robotClass_t
robotClass_t robot;
robot.setRobotID(agent);
robot.setTimestamp(robotRtdb.timestamp);
robot.setCoordinateType(coordinateType::FIELD_COORDS); // unused, TODO remove
robot.setCoordinates(robotRtdb.position.x, robotRtdb.position.y, robotRtdb.position.Rz);
robot.setVelocities(robotRtdb.velocity.x, robotRtdb.velocity.y, robotRtdb.velocity.Rz);
robot.setBallPossession(robotRtdb.hasBall);
// determine inplay status
robotStatusType status = robotStatusType::OUTOFPLAY;
if (robotRtdb.status == robotStatusEnum::INPLAY)
{
status = robotStatusType::INPLAY;
}
// feed to administrator
_robotAdmin->updateRobotPositionAndVelocity(robot);
_robotAdmin->setRobotStatus(robot.getRobotID(), status, robot.getTimestamp());
}
}
}
}
| 30.22268 | 142 | 0.640538 | Falcons-Robocup |
3e7f594166631fda651944638352170b813f1bff | 4,640 | cc | C++ | ThirdParty/webrtc/src/webrtc/modules/module_common_types_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 8 | 2018-12-27T14:57:13.000Z | 2021-04-07T07:03:15.000Z | ThirdParty/webrtc/src/webrtc/modules/module_common_types_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 1 | 2019-03-13T01:35:03.000Z | 2020-10-08T04:13:04.000Z | ThirdParty/webrtc/src/webrtc/modules/module_common_types_unittest.cc | JokeJoe8806/licode-windows | 2bfdaf6e87669df2b9960da50c6800bc3621b80b | [
"MIT"
] | 9 | 2018-12-28T11:45:12.000Z | 2021-05-11T02:15:31.000Z | /*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/interface/module_common_types.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace webrtc {
TEST(IsNewerSequenceNumber, Equal) {
EXPECT_FALSE(IsNewerSequenceNumber(0x0001, 0x0001));
}
TEST(IsNewerSequenceNumber, NoWrap) {
EXPECT_TRUE(IsNewerSequenceNumber(0xFFFF, 0xFFFE));
EXPECT_TRUE(IsNewerSequenceNumber(0x0001, 0x0000));
EXPECT_TRUE(IsNewerSequenceNumber(0x0100, 0x00FF));
}
TEST(IsNewerSequenceNumber, ForwardWrap) {
EXPECT_TRUE(IsNewerSequenceNumber(0x0000, 0xFFFF));
EXPECT_TRUE(IsNewerSequenceNumber(0x0000, 0xFF00));
EXPECT_TRUE(IsNewerSequenceNumber(0x00FF, 0xFFFF));
EXPECT_TRUE(IsNewerSequenceNumber(0x00FF, 0xFF00));
}
TEST(IsNewerSequenceNumber, BackwardWrap) {
EXPECT_FALSE(IsNewerSequenceNumber(0xFFFF, 0x0000));
EXPECT_FALSE(IsNewerSequenceNumber(0xFF00, 0x0000));
EXPECT_FALSE(IsNewerSequenceNumber(0xFFFF, 0x00FF));
EXPECT_FALSE(IsNewerSequenceNumber(0xFF00, 0x00FF));
}
TEST(IsNewerSequenceNumber, HalfWayApart) {
EXPECT_TRUE(IsNewerSequenceNumber(0x8000, 0x0000));
EXPECT_FALSE(IsNewerSequenceNumber(0x0000, 0x8000));
}
TEST(IsNewerTimestamp, Equal) {
EXPECT_FALSE(IsNewerTimestamp(0x00000001, 0x000000001));
}
TEST(IsNewerTimestamp, NoWrap) {
EXPECT_TRUE(IsNewerTimestamp(0xFFFFFFFF, 0xFFFFFFFE));
EXPECT_TRUE(IsNewerTimestamp(0x00000001, 0x00000000));
EXPECT_TRUE(IsNewerTimestamp(0x00010000, 0x0000FFFF));
}
TEST(IsNewerTimestamp, ForwardWrap) {
EXPECT_TRUE(IsNewerTimestamp(0x00000000, 0xFFFFFFFF));
EXPECT_TRUE(IsNewerTimestamp(0x00000000, 0xFFFF0000));
EXPECT_TRUE(IsNewerTimestamp(0x0000FFFF, 0xFFFFFFFF));
EXPECT_TRUE(IsNewerTimestamp(0x0000FFFF, 0xFFFF0000));
}
TEST(IsNewerTimestamp, BackwardWrap) {
EXPECT_FALSE(IsNewerTimestamp(0xFFFFFFFF, 0x00000000));
EXPECT_FALSE(IsNewerTimestamp(0xFFFF0000, 0x00000000));
EXPECT_FALSE(IsNewerTimestamp(0xFFFFFFFF, 0x0000FFFF));
EXPECT_FALSE(IsNewerTimestamp(0xFFFF0000, 0x0000FFFF));
}
TEST(IsNewerTimestamp, HalfWayApart) {
EXPECT_TRUE(IsNewerTimestamp(0x80000000, 0x00000000));
EXPECT_FALSE(IsNewerTimestamp(0x00000000, 0x80000000));
}
TEST(LatestSequenceNumber, NoWrap) {
EXPECT_EQ(0xFFFFu, LatestSequenceNumber(0xFFFF, 0xFFFE));
EXPECT_EQ(0x0001u, LatestSequenceNumber(0x0001, 0x0000));
EXPECT_EQ(0x0100u, LatestSequenceNumber(0x0100, 0x00FF));
EXPECT_EQ(0xFFFFu, LatestSequenceNumber(0xFFFE, 0xFFFF));
EXPECT_EQ(0x0001u, LatestSequenceNumber(0x0000, 0x0001));
EXPECT_EQ(0x0100u, LatestSequenceNumber(0x00FF, 0x0100));
}
TEST(LatestSequenceNumber, Wrap) {
EXPECT_EQ(0x0000u, LatestSequenceNumber(0x0000, 0xFFFF));
EXPECT_EQ(0x0000u, LatestSequenceNumber(0x0000, 0xFF00));
EXPECT_EQ(0x00FFu, LatestSequenceNumber(0x00FF, 0xFFFF));
EXPECT_EQ(0x00FFu, LatestSequenceNumber(0x00FF, 0xFF00));
EXPECT_EQ(0x0000u, LatestSequenceNumber(0xFFFF, 0x0000));
EXPECT_EQ(0x0000u, LatestSequenceNumber(0xFF00, 0x0000));
EXPECT_EQ(0x00FFu, LatestSequenceNumber(0xFFFF, 0x00FF));
EXPECT_EQ(0x00FFu, LatestSequenceNumber(0xFF00, 0x00FF));
}
TEST(LatestTimestamp, NoWrap) {
EXPECT_EQ(0xFFFFFFFFu, LatestTimestamp(0xFFFFFFFF, 0xFFFFFFFE));
EXPECT_EQ(0x00000001u, LatestTimestamp(0x00000001, 0x00000000));
EXPECT_EQ(0x00010000u, LatestTimestamp(0x00010000, 0x0000FFFF));
}
TEST(LatestTimestamp, Wrap) {
EXPECT_EQ(0x00000000u, LatestTimestamp(0x00000000, 0xFFFFFFFF));
EXPECT_EQ(0x00000000u, LatestTimestamp(0x00000000, 0xFFFF0000));
EXPECT_EQ(0x0000FFFFu, LatestTimestamp(0x0000FFFF, 0xFFFFFFFF));
EXPECT_EQ(0x0000FFFFu, LatestTimestamp(0x0000FFFF, 0xFFFF0000));
EXPECT_EQ(0x00000000u, LatestTimestamp(0xFFFFFFFF, 0x00000000));
EXPECT_EQ(0x00000000u, LatestTimestamp(0xFFFF0000, 0x00000000));
EXPECT_EQ(0x0000FFFFu, LatestTimestamp(0xFFFFFFFF, 0x0000FFFF));
EXPECT_EQ(0x0000FFFFu, LatestTimestamp(0xFFFF0000, 0x0000FFFF));
}
TEST(ClampToInt16, TestCases) {
EXPECT_EQ(0x0000, ClampToInt16(0x00000000));
EXPECT_EQ(0x0001, ClampToInt16(0x00000001));
EXPECT_EQ(0x7FFF, ClampToInt16(0x00007FFF));
EXPECT_EQ(0x7FFF, ClampToInt16(0x7FFFFFFF));
EXPECT_EQ(-0x0001, ClampToInt16(-0x00000001));
EXPECT_EQ(-0x8000, ClampToInt16(-0x8000));
EXPECT_EQ(-0x8000, ClampToInt16(-0x7FFFFFFF));
}
} // namespace webrtc
| 36.825397 | 71 | 0.794397 | JokeJoe8806 |
3e8061ee7533e989bc2a337b1a0e9729cd5c3e01 | 3,054 | hh | C++ | src/cpu/testers/rubytest/Check.hh | qianlong4526888/haha | 01baf923693873c11ae072ce4dde3d8f1d7b6239 | [
"BSD-3-Clause"
] | 31 | 2015-12-15T19:14:10.000Z | 2021-12-31T17:40:21.000Z | src/cpu/testers/rubytest/Check.hh | qianlong4526888/haha | 01baf923693873c11ae072ce4dde3d8f1d7b6239 | [
"BSD-3-Clause"
] | 5 | 2015-12-04T08:06:47.000Z | 2020-08-09T21:49:46.000Z | src/cpu/testers/rubytest/Check.hh | qianlong4526888/haha | 01baf923693873c11ae072ce4dde3d8f1d7b6239 | [
"BSD-3-Clause"
] | 21 | 2015-11-05T08:25:45.000Z | 2021-06-19T02:24:50.000Z | /*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* Copyright (c) 2009 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __CPU_RUBYTEST_CHECK_HH__
#define __CPU_RUBYTEST_CHECK_HH__
#include <iostream>
#include "cpu/testers/rubytest/RubyTester.hh"
#include "mem/protocol/RubyAccessMode.hh"
#include "mem/protocol/TesterStatus.hh"
#include "mem/ruby/common/Address.hh"
#include "mem/ruby/common/Global.hh"
class SubBlock;
const int CHECK_SIZE_BITS = 2;
const int CHECK_SIZE = (1 << CHECK_SIZE_BITS);
class Check
{
public:
Check(const Address& address, const Address& pc, int _num_writers,
int _num_readers, RubyTester* _tester);
void initiate(); // Does Action or Check or nether
void performCallback(NodeID proc, SubBlock* data, Cycles curTime);
const Address& getAddress() { return m_address; }
void changeAddress(const Address& address);
void print(std::ostream& out) const;
private:
void initiateFlush();
void initiatePrefetch();
void initiateAction();
void initiateCheck();
void pickValue();
void pickInitiatingNode();
void debugPrint();
TesterStatus m_status;
uint8_t m_value;
int m_store_count;
NodeID m_initiatingNode;
Address m_address;
Address m_pc;
RubyAccessMode m_access_mode;
int m_num_writers;
int m_num_readers;
RubyTester* m_tester_ptr;
};
inline std::ostream&
operator<<(std::ostream& out, const Check& obj)
{
obj.print(out);
out << std::flush;
return out;
}
#endif // __CPU_RUBYTEST_CHECK_HH__
| 33.56044 | 73 | 0.746562 | qianlong4526888 |
3e80868d61f6c0a06edc82eb9557b13b23b52905 | 1,690 | hpp | C++ | scsdk/c++/scsdk/standard_cyborg/algorithms/SparseICPWrapper.hpp | StandardCyborg/scsdk | 92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7 | [
"Apache-2.0"
] | 7 | 2020-11-26T01:07:26.000Z | 2021-12-14T07:45:19.000Z | scsdk/c++/scsdk/standard_cyborg/algorithms/SparseICPWrapper.hpp | StandardCyborg/scsdk | 92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7 | [
"Apache-2.0"
] | null | null | null | scsdk/c++/scsdk/standard_cyborg/algorithms/SparseICPWrapper.hpp | StandardCyborg/scsdk | 92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 Standard Cyborg
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
namespace standard_cyborg {
namespace sc3d {
class Geometry;
}
namespace math {
struct Mat3x4;
}
namespace algorithms {
struct SparseICPParameters {
bool use_penalty = false; /// if use_penalty then penalty method else ADMM or ALM (see max_inner)
double p = 1.0; /// p norm
double mu = 10.0; /// penalty weight
double alpha = 1.2; /// penalty increase factor
double max_mu = 1e5; /// max penalty
int max_icp = 100; /// max ICP iteration
int max_outer = 100; /// max outer iteration
int max_inner = 1; /// max inner iteration. If max_inner=1 then ADMM else ALM
double stop = 1e-5; /// stopping criteria
bool print_icpn = false; /// (debug) print ICP iteration
double outlierDeviationsThreshold = 1.0f; // The number of standard deviations outside of which a depth value being aligned is coinsidered an outlier
};
standard_cyborg::math::Mat3x4 SparseICPPointToPlane(const standard_cyborg::sc3d::Geometry& source, const standard_cyborg::sc3d::Geometry& target, const SparseICPParameters& pars);
}
}
| 34.489796 | 179 | 0.712426 | StandardCyborg |
3e81eef6789f12a9471266f36902585d12d47230 | 979 | cpp | C++ | N0504-Base-7/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N0504-Base-7/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N0504-Base-7/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | 2 | 2022-01-25T05:31:31.000Z | 2022-02-26T07:22:23.000Z | //
// main.cpp
// LeetCode-Solution
//
// Created by Loyio Hex on 3/7/22.
//
#include <iostream>
#include <chrono>
#include <vector>
using namespace std;
using namespace std::chrono;
class Solution {
public:
string convertToBase7(int num) {
if(num == 0){
return "0";
}
string res;
string negative = num < 0 ? "-" : "";
num = abs(num);
while(num){
res += to_string(num%7);
num = num/7;
}
reverse(res.begin(), res.end());
return negative+res;
}
};
int main(int argc, const char * argv[]) {
auto start = high_resolution_clock::now();
// Main Start
int num = -7;
Solution solution;
cout<< solution.convertToBase7(num);
// Main End
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << endl << "Runnig time : " << duration.count() << "ms;" << endl;
return 0;
}
| 19.58 | 74 | 0.551583 | loyio |
3e83fbf1a50a5bcb95581fece8933e56120375c7 | 1,137 | hpp | C++ | Piscines/CPP/rush01/includes/CPUInfoModule.hpp | SpeedFireSho/42-1 | 5d7ce17910794a28ca44d937651b961feadcff11 | [
"MIT"
] | 84 | 2020-10-13T14:50:11.000Z | 2022-01-11T11:19:36.000Z | Piscines/CPP/rush01/includes/CPUInfoModule.hpp | SpeedFireSho/42-1 | 5d7ce17910794a28ca44d937651b961feadcff11 | [
"MIT"
] | null | null | null | Piscines/CPP/rush01/includes/CPUInfoModule.hpp | SpeedFireSho/42-1 | 5d7ce17910794a28ca44d937651b961feadcff11 | [
"MIT"
] | 43 | 2020-09-10T19:26:37.000Z | 2021-12-28T13:53:55.000Z | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* CPUInfoModule.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jaleman <jaleman@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/15 18:52:02 by jaleman #+# #+# */
/* Updated: 2017/07/15 18:52:03 by jaleman ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CPUINFOMODULE_HPP
# define CPUINFOMODULE_HPP
class CPUInfoModule
{
CPUInfoModule(void);
CPUInfoModule(const CPUInfoModule &rhs);
~CPUInfoModule(void);
CPUInfoModule &operator= (const CPUInfoModule &rhs);
};
#endif
| 42.111111 | 80 | 0.252419 | SpeedFireSho |
3e8766ecbb6b48b5761dc1b7777c997c6eb7aae6 | 1,081 | cc | C++ | vos/gui/sub/gui/datarange/DataRangeAutoCmd.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 16 | 2020-10-21T05:56:26.000Z | 2022-03-31T10:02:01.000Z | vos/gui/sub/gui/datarange/DataRangeAutoCmd.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | null | null | null | vos/gui/sub/gui/datarange/DataRangeAutoCmd.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 2 | 2021-03-09T01:51:08.000Z | 2021-03-23T00:23:24.000Z | ////////////////////////////////////////////////////////////
// DataRangeAutoCmd.h: Set or clear automatic determination of
// data range in the image model.
///////////////////////////////////////////////////////////
#include "DataRangeAutoCmd.h"
#include "ImageData.h"
#include <stdint.h>
DataRangeAutoCmd::DataRangeAutoCmd(const char *name,int active,ImageData *image,
Boolean isMax)
: Cmd(name, active)
{
_image = image;
_isMax = isMax;
// Check current auto state.
if (isMax)
_value = (CmdValue) ((uintptr_t) _image->isMaxAuto());
else
_value = (CmdValue) ((uintptr_t) _image->isMinAuto());
_lastValue = _value;
newValue();
}
void DataRangeAutoCmd::doit()
{
if (_isMax) {
_lastValue = (CmdValue) ((uintptr_t) _image->isMaxAuto()); // save for undo
_image->setMaxAuto((_value != 0));
}
else {
_lastValue = (CmdValue) ((uintptr_t) _image->isMinAuto()); // save for undo
_image->setMinAuto((_value != 0));
}
}
void DataRangeAutoCmd::undoit()
{
_value = _lastValue;
newValue();
doit();
}
| 23.5 | 81 | 0.572618 | NASA-AMMOS |
3e8a7bd062a12fc5eb6e1ef04fb28d58c0dc7fd6 | 8,268 | cpp | C++ | src/polybench/POLYBENCH_3MM-Hip.cpp | ajpowelsnl/RAJAPerf | f44641695203cd3bd3058315f356359f1b492ea3 | [
"BSD-3-Clause"
] | null | null | null | src/polybench/POLYBENCH_3MM-Hip.cpp | ajpowelsnl/RAJAPerf | f44641695203cd3bd3058315f356359f1b492ea3 | [
"BSD-3-Clause"
] | null | null | null | src/polybench/POLYBENCH_3MM-Hip.cpp | ajpowelsnl/RAJAPerf | f44641695203cd3bd3058315f356359f1b492ea3 | [
"BSD-3-Clause"
] | null | null | null | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2017-21, Lawrence Livermore National Security, LLC
// and RAJA Performance Suite project contributors.
// See the RAJAPerf/COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "POLYBENCH_3MM.hpp"
#include "RAJA/RAJA.hpp"
#if defined(RAJA_ENABLE_HIP)
#include "common/HipDataUtils.hpp"
#include <iostream>
namespace rajaperf
{
namespace polybench
{
#define POLYBENCH_3MM_DATA_SETUP_HIP \
allocAndInitHipDeviceData(A, m_A, m_ni * m_nk); \
allocAndInitHipDeviceData(B, m_B, m_nk * m_nj); \
allocAndInitHipDeviceData(C, m_C, m_nj * m_nm); \
allocAndInitHipDeviceData(D, m_D, m_nm * m_nl); \
allocAndInitHipDeviceData(E, m_E, m_ni * m_nj); \
allocAndInitHipDeviceData(F, m_F, m_nj * m_nl); \
allocAndInitHipDeviceData(G, m_G, m_ni * m_nl);
#define POLYBENCH_3MM_TEARDOWN_HIP \
getHipDeviceData(m_G, G, m_ni * m_nl); \
deallocHipDeviceData(A); \
deallocHipDeviceData(B); \
deallocHipDeviceData(C); \
deallocHipDeviceData(D); \
deallocHipDeviceData(E); \
deallocHipDeviceData(F); \
deallocHipDeviceData(G);
__global__ void poly_3mm_1(Real_ptr E, Real_ptr A, Real_ptr B,
Index_type nj, Index_type nk)
{
Index_type i = blockIdx.y;
Index_type j = threadIdx.x;
POLYBENCH_3MM_BODY1;
for (Index_type k=0; k < nk; ++k) {
POLYBENCH_3MM_BODY2;
}
POLYBENCH_3MM_BODY3;
}
__global__ void poly_3mm_2(Real_ptr F, Real_ptr C, Real_ptr D,
Index_type nl, Index_type nm)
{
Index_type j = blockIdx.y;
Index_type l = threadIdx.x;
POLYBENCH_3MM_BODY4;
for (Index_type m=0; m < nm; ++m) {
POLYBENCH_3MM_BODY5;
}
POLYBENCH_3MM_BODY6;
}
__global__ void poly_3mm_3(Real_ptr G, Real_ptr E, Real_ptr F,
Index_type nl, Index_type nj)
{
Index_type i = blockIdx.y;
Index_type l = threadIdx.x;
POLYBENCH_3MM_BODY7;
for (Index_type j=0; j < nj; ++j) {
POLYBENCH_3MM_BODY8;
}
POLYBENCH_3MM_BODY9;
}
void POLYBENCH_3MM::runHipVariant(VariantID vid)
{
const Index_type run_reps = getRunReps();
POLYBENCH_3MM_DATA_SETUP;
if ( vid == Base_HIP ) {
POLYBENCH_3MM_DATA_SETUP_HIP;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
dim3 nblocks1(1, ni, 1);
dim3 nthreads_per_block1(nj, 1, 1);
hipLaunchKernelGGL((poly_3mm_1), dim3(nblocks1) , dim3(nthreads_per_block1), 0, 0,
E, A, B,
nj, nk);
hipErrchk( hipGetLastError() );
dim3 nblocks2(1, nj, 1);
dim3 nthreads_per_block2(nl, 1, 1);
hipLaunchKernelGGL((poly_3mm_2), dim3(nblocks2), dim3(nthreads_per_block2), 0, 0,
F, C, D,
nl, nm);
hipErrchk( hipGetLastError() );
dim3 nblocks3(1, ni, 1);
dim3 nthreads_per_block3(nl, 1, 1);
hipLaunchKernelGGL((poly_3mm_3), dim3(nblocks3), dim3(nthreads_per_block3), 0, 0,
G, E, F,
nl, nj);
hipErrchk( hipGetLastError() );
}
stopTimer();
POLYBENCH_3MM_TEARDOWN_HIP;
} else if (vid == Lambda_HIP) {
POLYBENCH_3MM_DATA_SETUP_HIP;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
auto poly_3mm_1_lambda = [=] __device__ (Index_type i, Index_type j) {
POLYBENCH_3MM_BODY1;
for (Index_type k=0; k < nk; ++k) {
POLYBENCH_3MM_BODY2;
}
POLYBENCH_3MM_BODY3;
};
dim3 nblocks1(1, ni, 1);
dim3 nthreads_per_block1(nj, 1, 1);
auto kernel1 = lambda_hip_kernel<RAJA::hip_block_y_direct, RAJA::hip_thread_x_direct, decltype(poly_3mm_1_lambda)>;
hipLaunchKernelGGL(kernel1,
nblocks1, nthreads_per_block1, 0, 0,
0, ni, 0, nj, poly_3mm_1_lambda);
hipErrchk( hipGetLastError() );
auto poly_3mm_2_lambda = [=] __device__ (Index_type j, Index_type l) {
POLYBENCH_3MM_BODY4;
for (Index_type m=0; m < nm; ++m) {
POLYBENCH_3MM_BODY5;
}
POLYBENCH_3MM_BODY6;
};
dim3 nblocks2(1, nj, 1);
dim3 nthreads_per_block2(nl, 1, 1);
auto kernel2 = lambda_hip_kernel<RAJA::hip_block_y_direct, RAJA::hip_thread_x_direct, decltype(poly_3mm_2_lambda)>;
hipLaunchKernelGGL(kernel2,
nblocks2, nthreads_per_block2, 0, 0,
0, nj, 0, nl, poly_3mm_2_lambda);
hipErrchk( hipGetLastError() );
auto poly_3mm_3_lambda = [=] __device__ (Index_type i, Index_type l) {
POLYBENCH_3MM_BODY7;
for (Index_type j=0; j < nj; ++j) {
POLYBENCH_3MM_BODY8;
}
POLYBENCH_3MM_BODY9;
};
dim3 nblocks3(1, ni, 1);
dim3 nthreads_per_block3(nl, 1, 1);
auto kernel3 = lambda_hip_kernel<RAJA::hip_block_y_direct, RAJA::hip_thread_x_direct, decltype(poly_3mm_3_lambda)>;
hipLaunchKernelGGL(kernel3,
nblocks3, nthreads_per_block3, 0, 0,
0, ni, 0, nl, poly_3mm_3_lambda);
hipErrchk( hipGetLastError() );
}
stopTimer();
POLYBENCH_3MM_TEARDOWN_HIP;
} else if (vid == RAJA_HIP) {
POLYBENCH_3MM_DATA_SETUP_HIP;
POLYBENCH_3MM_VIEWS_RAJA;
using EXEC_POL =
RAJA::KernelPolicy<
RAJA::statement::HipKernelAsync<
RAJA::statement::For<0, RAJA::hip_block_x_direct,
RAJA::statement::For<1, RAJA::hip_thread_y_direct,
RAJA::statement::Lambda<0, RAJA::Params<0>>,
RAJA::statement::For<2, RAJA::seq_exec,
RAJA::statement::Lambda<1, RAJA::Segs<0,1,2>, RAJA::Params<0>>
>,
RAJA::statement::Lambda<2, RAJA::Segs<0,1>, RAJA::Params<0>>
>
>
>
>;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
RAJA::kernel_param<EXEC_POL>(
RAJA::make_tuple(RAJA::RangeSegment{0, ni},
RAJA::RangeSegment{0, nj},
RAJA::RangeSegment{0, nk}),
RAJA::tuple<Real_type>{0.0},
[=] __device__ ( Real_type &dot) {
POLYBENCH_3MM_BODY1_RAJA;
},
[=] __device__ (Index_type i, Index_type j, Index_type k,
Real_type &dot) {
POLYBENCH_3MM_BODY2_RAJA;
},
[=] __device__ (Index_type i, Index_type j,
Real_type &dot) {
POLYBENCH_3MM_BODY3_RAJA;
}
);
RAJA::kernel_param<EXEC_POL>(
RAJA::make_tuple(RAJA::RangeSegment{0, nj},
RAJA::RangeSegment{0, nl},
RAJA::RangeSegment{0, nm}),
RAJA::tuple<Real_type>{0.0},
[=] __device__ ( Real_type &dot) {
POLYBENCH_3MM_BODY4_RAJA;
},
[=] __device__ (Index_type j, Index_type l, Index_type m,
Real_type &dot) {
POLYBENCH_3MM_BODY5_RAJA;
},
[=] __device__ (Index_type j, Index_type l,
Real_type &dot) {
POLYBENCH_3MM_BODY6_RAJA;
}
);
RAJA::kernel_param<EXEC_POL>(
RAJA::make_tuple(RAJA::RangeSegment{0, ni},
RAJA::RangeSegment{0, nl},
RAJA::RangeSegment{0, nj}),
RAJA::tuple<Real_type>{0.0},
[=] __device__ ( Real_type &dot) {
POLYBENCH_3MM_BODY7_RAJA;
},
[=] __device__ (Index_type i, Index_type l, Index_type j,
Real_type &dot) {
POLYBENCH_3MM_BODY8_RAJA;
},
[=] __device__ (Index_type i, Index_type l,
Real_type &dot) {
POLYBENCH_3MM_BODY9_RAJA;
}
);
}
stopTimer();
POLYBENCH_3MM_TEARDOWN_HIP;
} else {
std::cout << "\n POLYBENCH_3MM : Unknown Hip variant id = " << vid << std::endl;
}
}
} // end namespace polybench
} // end namespace rajaperf
#endif // RAJA_ENABLE_HIP
| 28.909091 | 121 | 0.572085 | ajpowelsnl |
3e8b64c8fca27b09782da4425693f1c179d193b0 | 3,613 | cpp | C++ | src/webots/vrml/WbMFDouble.cpp | awesome-archive/webots | 8e74fb8393d1e3a6540749afc492635c43f1b30f | [
"Apache-2.0"
] | 2 | 2019-07-12T13:47:44.000Z | 2019-08-17T02:53:54.000Z | src/webots/vrml/WbMFDouble.cpp | golbh/webots | 8e74fb8393d1e3a6540749afc492635c43f1b30f | [
"Apache-2.0"
] | null | null | null | src/webots/vrml/WbMFDouble.cpp | golbh/webots | 8e74fb8393d1e3a6540749afc492635c43f1b30f | [
"Apache-2.0"
] | 1 | 2019-07-13T17:58:04.000Z | 2019-07-13T17:58:04.000Z | // Copyright 1996-2018 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "WbMFDouble.hpp"
#include "WbToken.hpp"
#include "WbTokenizer.hpp"
#include "WbVrmlWriter.hpp"
void WbMFDouble::readAndAddItem(WbTokenizer *tokenizer, const QString &worldPath) {
mVector.append(tokenizer->nextToken()->toDouble());
}
void WbMFDouble::clear() {
if (mVector.size() > 0) {
mVector.clear();
emit changed();
}
}
void WbMFDouble::copyItemsTo(double values[], int max) const {
if (max == -1 || max > mVector.size())
max = mVector.size();
memcpy(values, mVector.constData(), max * sizeof(double));
}
void WbMFDouble::findMinMax(double *min, double *max) const {
if (mVector.isEmpty())
return;
*min = *max = mVector[0];
foreach (double d, mVector) {
*min = qMin(*min, d);
*max = qMax(*max, d);
}
}
void WbMFDouble::setItem(int index, double value) {
assert(index >= 0 && index < size());
if (mVector[index] != value) {
mVector[index] = value;
emit itemChanged(index);
emit changed();
}
}
void WbMFDouble::setAllItems(const double *values) {
const int size = mVector.size();
bool vectorHasChanged = false;
for (int index = 0; index < size; index++) {
if (mVector[index] != values[index]) {
mVector[index] = values[index];
emit itemChanged(index);
vectorHasChanged = true;
}
}
if (vectorHasChanged)
emit changed();
}
void WbMFDouble::multiplyAllItems(double factor) {
if (factor == 1.0)
return;
const int size = mVector.size();
for (int index = 0; index < size; index++) {
const double previousValue = mVector[index];
if (previousValue != 0.0) {
mVector[index] = factor * previousValue;
emit itemChanged(index);
}
}
emit changed();
}
void WbMFDouble::addItem(double value) {
mVector.append(value);
emit itemInserted(mVector.size() - 1);
emit changed();
}
void WbMFDouble::insertDefaultItem(int index) {
assert(index >= 0 && index <= size());
mVector.insert(mVector.begin() + index, defaultNewVariant().toDouble());
emit itemInserted(index);
emit changed();
}
void WbMFDouble::insertItem(int index, double value) {
assert(index >= 0 && index <= size());
mVector.insert(mVector.begin() + index, value);
emit itemInserted(index);
emit changed();
}
void WbMFDouble::removeItem(int index) {
assert(index >= 0 && index < size());
mVector.erase(mVector.begin() + index);
emit itemRemoved(index);
emit changed();
}
WbMFDouble &WbMFDouble::operator=(const WbMFDouble &other) {
if (mVector == other.mVector)
return *this;
mVector = other.mVector;
emit changed();
return *this;
}
bool WbMFDouble::equals(const WbValue *other) const {
const WbMFDouble *that = dynamic_cast<const WbMFDouble *>(other);
return that && *this == *that;
}
void WbMFDouble::copyFrom(const WbValue *other) {
const WbMFDouble *that = dynamic_cast<const WbMFDouble *>(other);
*this = *that;
}
bool WbMFDouble::smallSeparator(int i) const {
return (i % 10 != 0 || WbMultipleValue::smallSeparator(i)); // 10 integers per line
}
| 26.181159 | 86 | 0.671741 | awesome-archive |
3e8ca4c94ff58c69f52b41574bb5ea3ec93d959d | 1,553 | hpp | C++ | models/AI-Model-Zoo/caffe-xilinx/include/caffe/layers/cudnn_batch_norm_layer.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 848 | 2019-12-03T00:16:17.000Z | 2022-03-31T22:53:17.000Z | models/AI-Model-Zoo/caffe-xilinx/include/caffe/layers/cudnn_batch_norm_layer.hpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 656 | 2019-12-03T00:48:46.000Z | 2022-03-31T18:41:54.000Z | models/AI-Model-Zoo/caffe-xilinx/include/caffe/layers/cudnn_batch_norm_layer.hpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | #ifndef CAFFE_CUDNN_BATCH_NORM_LAYER_HPP_
#define CAFFE_CUDNN_BATCH_NORM_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/layers/batch_norm_layer.hpp"
namespace caffe {
#ifdef USE_CUDNN
template <typename Dtype>
class CuDNNBatchNormLayer : public BatchNormLayer<Dtype> {
public:
explicit CuDNNBatchNormLayer(const LayerParameter& param)
: BatchNormLayer<Dtype>(param), handles_setup_(false) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual ~CuDNNBatchNormLayer();
// Special method for batch norm layer
const Blob<Dtype>& GetSaveMean() const { return save_mean_;}
const Blob<Dtype>& GetSaveInvVar() const { return save_inv_var_;}
protected:
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
// cuDNN descriptors / handles
cudnnTensorDescriptor_t bottom_desc_, top_desc_;
cudnnTensorDescriptor_t scale_bias_mean_var_desc_;
cudnnBatchNormMode_t mode_;
Blob<Dtype> save_mean_, save_inv_var_;
bool handles_setup_;
shared_ptr<Blob<Dtype> > private_top_;
shared_ptr<Blob<Dtype> > private_bottom_;
};
#endif
} // namespace caffe
#endif // CAFFE_CUDNN_BATCH_NORM_LAYER_HPP_
| 29.865385 | 78 | 0.755312 | hito0512 |
3e8f42c0c5e2dc5056d9a7224973c90c72e28838 | 1,557 | cpp | C++ | source/Irrlicht/rtc/impl/verifiedtlstransport.cpp | MagicAtom/irrlicht-ce | b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d | [
"IJG"
] | null | null | null | source/Irrlicht/rtc/impl/verifiedtlstransport.cpp | MagicAtom/irrlicht-ce | b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d | [
"IJG"
] | null | null | null | source/Irrlicht/rtc/impl/verifiedtlstransport.cpp | MagicAtom/irrlicht-ce | b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d | [
"IJG"
] | null | null | null | /**
* Copyright (c) 2020 Paul-Louis Ageneau
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "verifiedtlstransport.hpp"
#include "common.hpp"
#if RTC_ENABLE_WEBSOCKET
namespace rtc::impl {
VerifiedTlsTransport::VerifiedTlsTransport(shared_ptr<TcpTransport> lower, string host,
certificate_ptr certificate, state_callback callback)
: TlsTransport(std::move(lower), std::move(host), std::move(certificate), std::move(callback)) {
#if USE_GNUTLS
PLOG_DEBUG << "Setting up TLS certificate verification";
gnutls_session_set_verify_cert(mSession, mHost->c_str(), 0);
#else
PLOG_DEBUG << "Setting up TLS certificate verification";
SSL_set_verify(mSsl, SSL_VERIFY_PEER, NULL);
SSL_set_verify_depth(mSsl, 4);
#endif
}
VerifiedTlsTransport::~VerifiedTlsTransport() {}
} // namespace rtc::impl
#endif
| 34.6 | 100 | 0.739884 | MagicAtom |
3e8fd59645d671523f3ae245584a7fe10e48a5ef | 346 | cc | C++ | src/pks/flow/test/Main.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | 1 | 2021-02-23T18:34:47.000Z | 2021-02-23T18:34:47.000Z | src/pks/flow/test/Main.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | src/pks/flow/test/Main.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | #include <UnitTest++.h>
#include "Teuchos_GlobalMPISession.hpp"
#include "VerboseObject_objs.hh"
#include "state_evaluators_registration.hh"
#include "wrm_flow_registration.hh"
int main(int argc, char *argv[])
{
int res = 0;
{
Teuchos::GlobalMPISession mpiSession(&argc, &argv);
res = UnitTest::RunAllTests();
}
return res;
}
| 18.210526 | 55 | 0.710983 | ajkhattak |
3e8fe50456914315af4f30b59c7229f4e01bb099 | 119 | cpp | C++ | ares/sfc/coprocessor/obc1/serialization.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/sfc/coprocessor/obc1/serialization.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | ares/sfc/coprocessor/obc1/serialization.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | auto OBC1::serialize(serializer& s) -> void {
s(ram);
s(status.address);
s(status.baseptr);
s(status.shift);
}
| 17 | 45 | 0.638655 | CasualPokePlayer |
3e92c5dca9298e99d41b3d6c905fdae5661588e3 | 1,271 | hpp | C++ | GLSL-Pipeline/Toolkits/include/System/Action.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | GLSL-Pipeline/Toolkits/include/System/Action.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | GLSL-Pipeline/Toolkits/include/System/Action.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <functional>
#include "DLL.hpp"
namespace System
{
/**
* \brief Encapsulates a method that has specified parameters and does not return a value.
* \tparam Args The type of the parameters of the method that this delegate encapsulates.
*/
template<typename ...Args>
class DLLExport Action final
{
public:
typedef std::function<void(Args...)> ActionType;
#pragma region Public Constructors
Action(ActionType action);
#pragma endregion
#pragma region Public Destructor
~Action();
#pragma endregion
#pragma region Public Instance Methods
void Invoke(Args&&... args);
#pragma endregion
private:
ActionType action;
};
#pragma region Public Constructors
template <typename ... Args>
Action<Args...>::Action(ActionType action)
{
this->action = action;
}
#pragma endregion
#pragma region Public Destructor
template <typename ... Args>
Action<Args...>::~Action() {}
#pragma endregion
#pragma region Public Instance Methods
template <typename ... Args>
void Action<Args...>::Invoke(Args&&... args)
{
if (&action != nullptr)
{
action(args...);
}
}
#pragma endregion
}
| 18.157143 | 94 | 0.631786 | GilFerraz |
3e9942ab0f2b963ee67db148deacdfce161447d1 | 2,188 | cc | C++ | flare/rpc/details/has_epollrdhup.cc | flare-rpc/flare-cpp | c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950 | [
"Apache-2.0"
] | 3 | 2022-01-23T17:55:24.000Z | 2022-03-23T12:55:18.000Z | flare/rpc/details/has_epollrdhup.cc | flare-rpc/flare-cpp | c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950 | [
"Apache-2.0"
] | null | null | null | flare/rpc/details/has_epollrdhup.cc | flare-rpc/flare-cpp | c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "flare/base/profile.h"
#if defined(FLARE_PLATFORM_LINUX)
#include <sys/epoll.h> // epoll_create
#include <sys/types.h> // socketpair
#include <sys/socket.h> // ^
#include "flare/base/fd_guard.h" // fd_guard
#include "flare/rpc/details/has_epollrdhup.h"
#ifndef EPOLLRDHUP
#define EPOLLRDHUP 0x2000
#endif
namespace flare::rpc {
static unsigned int check_epollrdhup() {
flare::base::fd_guard epfd(epoll_create(16));
if (epfd < 0) {
return 0;
}
flare::base::fd_guard fds[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, (int*)fds) < 0) {
return 0;
}
epoll_event evt = { static_cast<uint32_t>(EPOLLIN | EPOLLRDHUP | EPOLLET),
{ NULL }};
if (epoll_ctl(epfd, EPOLL_CTL_ADD, fds[0], &evt) < 0) {
return 0;
}
if (close(fds[1].release()) < 0) {
return 0;
}
epoll_event e;
int n;
while ((n = epoll_wait(epfd, &e, 1, -1)) == 0);
if (n < 0) {
return 0;
}
return (e.events & EPOLLRDHUP) ? EPOLLRDHUP : static_cast<EPOLL_EVENTS>(0);
}
extern const unsigned int has_epollrdhup = check_epollrdhup();
} // namespace flare::rpc
#else
namespace flare::rpc {
extern const unsigned int has_epollrdhup = false;
}
#endif // defined(FLARE_PLATFORM_LINUX)
| 30.388889 | 79 | 0.644424 | flare-rpc |
3e9a07746cfa9d86e5e733d2ccdf9beed64c1a60 | 6,354 | cpp | C++ | examples/11_locmesh/locsvcmesh/src/ServiceClient.cpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 70 | 2021-07-20T11:26:16.000Z | 2022-03-27T11:17:43.000Z | examples/11_locmesh/locsvcmesh/src/ServiceClient.cpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 32 | 2021-07-31T05:20:44.000Z | 2022-03-20T10:11:52.000Z | examples/11_locmesh/locsvcmesh/src/ServiceClient.cpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 40 | 2021-11-02T09:45:38.000Z | 2022-03-27T11:17:46.000Z | /************************************************************************
* \file ServiceClient.cpp
* \ingroup AREG Asynchronous Event-Driven Communication Framework examples
* \author Artak Avetyan
* \brief Collection of AREG SDK examples.
* This file contains simple implementation of service client to
* request message output
************************************************************************/
/************************************************************************
* Include files.
************************************************************************/
#include "ServiceClient.hpp"
#include "areg/trace/GETrace.h"
#include "areg/component/Component.hpp"
#include "areg/component/ComponentThread.hpp"
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_serviceConnected);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_onConnectedClientsUpdate);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_onRemainOutputUpdate);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_broadcastHelloClients);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_broadcastServiceUnavailable);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_responseHelloWorld);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_requestHelloWorldFailed);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_requestClientShutdownFailed);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_processTimer);
DEF_TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_ServiceClient);
const unsigned int ServiceClient::TIMEOUT_VALUE = 237;
ServiceClient::ServiceClient(const String & roleName, Component & owner)
: HelloWorldClientBase ( roleName, owner )
, IETimerConsumer ( )
, mTimer ( static_cast<IETimerConsumer &>(self()), timerName( owner ) )
, mID ( 0 )
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_ServiceClient);
TRACE_DBG("Client: roleName [ %s ] of service [ %s ] owner [ %s ] in thread [ %s ] has timer [ %s ]"
, roleName.getString()
, getServiceName().getString()
, owner.getRoleName().getString()
, owner.getMasterThread().getName().getString()
, mTimer.getName().getString());
TRACE_DBG("Proxy: [ %s ]", ProxyAddress::convAddressToPath(getProxy()->getProxyAddress()).getString());
}
bool ServiceClient::serviceConnected(bool isConnected, ProxyBase & proxy)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_serviceConnected);
bool result = HelloWorldClientBase::serviceConnected(isConnected, proxy);
TRACE_DBG("Proxy [ %s ] is [ %s ]"
, ProxyAddress::convAddressToPath(proxy.getProxyAddress()).getString()
, isConnected ? "connected" : "disconnected");
if (isConnected)
{
// dynamic subscribe.
notifyOnRemainOutputUpdate(true);
notifyOnBroadcastServiceUnavailable(true);
mTimer.startTimer(ServiceClient::TIMEOUT_VALUE);
}
else
{
mTimer.stopTimer();
// clear all subscriptions.
clearAllNotifications();
}
return result;
}
void ServiceClient::onConnectedClientsUpdate(const NEHelloWorld::ConnectionList & ConnectedClients, NEService::eDataStateType state)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_onConnectedClientsUpdate);
TRACE_DBG("Active client list of [ %s ] service is updated, active clients [ %d ], data is [ %s ]"
, getServiceRole().getString()
, ConnectedClients.getSize()
, NEService::getString(state));
}
void ServiceClient::onRemainOutputUpdate(short RemainOutput, NEService::eDataStateType state)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_onRemainOutputUpdate);
TRACE_DBG("Service [ %s ]: Remain greeting outputs [ %d ], data is [ %s ]", getServiceRole().getString(), RemainOutput, NEService::getString(state));
}
void ServiceClient::responseHelloWorld(const NEHelloWorld::sConnectedClient & clientInfo)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_responseHelloWorld);
TRACE_DBG("Service [ %s ]: Made output of [ %s ], client ID [ %d ]", getServiceRole().getString(), clientInfo.ccName.getString(), clientInfo.ccID);
ASSERT(clientInfo.ccName == mTimer.getName());
mID = clientInfo.ccID;
if (isNotificationAssigned(NEHelloWorld::eMessageIDs::MsgId_broadcastHelloClients) == false)
{
notifyOnBroadcastHelloClients(true);
notifyOnConnectedClientsUpdate(true);
}
}
void ServiceClient::broadcastHelloClients(const NEHelloWorld::ConnectionList & clientList)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_broadcastHelloClients);
TRACE_DBG("[ %d ] clients use service [ %s ]", clientList.getSize(), getServiceName().getString());
}
void ServiceClient::broadcastServiceUnavailable(void)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_broadcastServiceUnavailable);
TRACE_WARN("Service notify reached message output maximum, starting shutdown procedure");
requestClientShutdown(mID, mTimer.getName());
}
void ServiceClient::requestHelloWorldFailed(NEService::eResultType FailureReason)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_requestHelloWorldFailed);
TRACE_ERR("Request to output greetings failed with reason [ %s ]", NEService::getString(FailureReason));
}
void ServiceClient::requestClientShutdownFailed(NEService::eResultType FailureReason)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_requestClientShutdownFailed);
TRACE_ERR("Request to notify client shutdown failed with reason [ %s ]", NEService::getString(FailureReason));
}
void ServiceClient::processTimer(Timer & timer)
{
TRACE_SCOPE(examples_11_locsvcmesh_ServiceClient_processTimer);
ASSERT(&timer == &mTimer);
TRACE_DBG("Timer [ %s ] expired, send request to output message.", timer.getName().getString());
requestHelloWorld(timer.getName(), "");
}
inline String ServiceClient::timerName( Component & owner ) const
{
String result = "";
result += owner.getRoleName();
result += NECommon::DEFAULT_SPECIAL_CHAR.data();
result += getServiceRole();
result += NECommon::DEFAULT_SPECIAL_CHAR.data();
result += getServiceName();
return result;
}
| 42.644295 | 153 | 0.700661 | Ali-Nasrolahi |
3ea095a5175050b08de676cda6974a0c56422868 | 3,010 | cpp | C++ | dbms/programs/performance-test/ConfigPreprocessor.cpp | izebit/ClickHouse | 839acc948ec623fc1cb2dcf23dba86d8a81f992e | [
"Apache-2.0"
] | 1 | 2019-12-03T18:28:40.000Z | 2019-12-03T18:28:40.000Z | dbms/programs/performance-test/ConfigPreprocessor.cpp | izebit/ClickHouse | 839acc948ec623fc1cb2dcf23dba86d8a81f992e | [
"Apache-2.0"
] | null | null | null | dbms/programs/performance-test/ConfigPreprocessor.cpp | izebit/ClickHouse | 839acc948ec623fc1cb2dcf23dba86d8a81f992e | [
"Apache-2.0"
] | 1 | 2019-12-31T17:52:32.000Z | 2019-12-31T17:52:32.000Z | #include "ConfigPreprocessor.h"
#include <Core/Types.h>
#include <Poco/Path.h>
#include <regex>
namespace DB
{
std::vector<XMLConfigurationPtr> ConfigPreprocessor::processConfig(
const Strings & tests_tags,
const Strings & tests_names,
const Strings & tests_names_regexp,
const Strings & skip_tags,
const Strings & skip_names,
const Strings & skip_names_regexp) const
{
std::vector<XMLConfigurationPtr> result;
for (const auto & path : paths)
{
result.emplace_back(XMLConfigurationPtr(new XMLConfiguration(path)));
result.back()->setString("path", Poco::Path(path).absolute().toString());
}
/// Leave tests:
removeConfigurationsIf(result, FilterType::Tag, tests_tags, true);
removeConfigurationsIf(result, FilterType::Name, tests_names, true);
removeConfigurationsIf(result, FilterType::Name_regexp, tests_names_regexp, true);
/// Skip tests
removeConfigurationsIf(result, FilterType::Tag, skip_tags, false);
removeConfigurationsIf(result, FilterType::Name, skip_names, false);
removeConfigurationsIf(result, FilterType::Name_regexp, skip_names_regexp, false);
return result;
}
void ConfigPreprocessor::removeConfigurationsIf(
std::vector<XMLConfigurationPtr> & configs,
ConfigPreprocessor::FilterType filter_type,
const Strings & values,
bool leave) const
{
auto checker = [&filter_type, &values, &leave] (XMLConfigurationPtr & config)
{
if (values.size() == 0)
return false;
bool remove_or_not = false;
if (filter_type == FilterType::Tag)
{
Strings tags_keys;
config->keys("tags", tags_keys);
Strings tags(tags_keys.size());
for (size_t i = 0; i != tags_keys.size(); ++i)
tags[i] = config->getString("tags.tag[" + std::to_string(i) + "]");
for (const std::string & config_tag : tags)
{
if (std::find(values.begin(), values.end(), config_tag) != values.end())
remove_or_not = true;
}
}
if (filter_type == FilterType::Name)
{
remove_or_not = (std::find(values.begin(), values.end(), config->getString("name", "")) != values.end());
}
if (filter_type == FilterType::Name_regexp)
{
std::string config_name = config->getString("name", "");
auto regex_checker = [&config_name](const std::string & name_regexp)
{
std::regex pattern(name_regexp);
return std::regex_search(config_name, pattern);
};
remove_or_not = config->has("name") ? (std::find_if(values.begin(), values.end(), regex_checker) != values.end()) : false;
}
if (leave)
remove_or_not = !remove_or_not;
return remove_or_not;
};
auto new_end = std::remove_if(configs.begin(), configs.end(), checker);
configs.erase(new_end, configs.end());
}
}
| 33.076923 | 134 | 0.618937 | izebit |
3ea2676657baf94909ab0c33131c9da3eddbb632 | 7,324 | cpp | C++ | src/ai/weapons/missile.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 8 | 2018-04-03T23:06:33.000Z | 2021-12-28T18:04:19.000Z | src/ai/weapons/missile.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | null | null | null | src/ai/weapons/missile.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 1 | 2020-07-31T00:23:27.000Z | 2020-07-31T00:23:27.000Z | #include "missile.h"
#include "weapons.h"
#include "../../ObjManager.h"
#include "../../caret.h"
#include "../../trig.h"
#include "../../sound/sound.h"
#include "../../common/misc.h"
#include "../../game.h"
#include "../../player.h"
#include "../../autogen/sprites.h"
#define STATE_WAIT_RECOIL_OVER 1
#define STATE_RECOIL_OVER 2
#define STATE_MISSILE_CAN_EXPLODE 3
struct MissileSettings
{
int maxspeed; // max speed of missile
int hitrange; //
int lifetime; // number of boomflashes to create on impact
int boomrange; // max dist away to create the boomflashes
int boomdamage; // damage dealt by contact with a boomflash (AoE damage)
}
missile_settings[] =
{
// Level 1-3 regular missile
// maxspd hit, life, range, bmdmg
{0xA00, 16, 10, 16, 1},
{0xA00, 16, 15, 32, 1},
{0xA00, 16, 5, 40, 1},
// Level 1-3 super missile
// maxspd hit, life, range, bmdmg
{0x1400, 12, 10, 16, 2},
{0x1400, 12, 14, 32, 2},
{0x1400, 12, 6, 40, 2}
};
INITFUNC(AIRoutines)
{
AFTERMOVE(OBJ_MISSILE_SHOT, ai_missile_shot);
AFTERMOVE(OBJ_SUPERMISSILE_SHOT, ai_missile_shot);
ONTICK(OBJ_MISSILE_BOOM_SPAWNER, ai_missile_boom_spawner_tick);
AFTERMOVE(OBJ_MISSILE_BOOM_SPAWNER, ai_missile_boom_spawner);
}
/*
void c------------------------------() {}
*/
void ai_missile_shot(Object *o)
{
int index = o->shot.level + ((o->type == OBJ_SUPERMISSILE_SHOT) ? 3 : 0);
MissileSettings *settings = &missile_settings[index];
if (o->state == 0)
{
o->shot.damage = 0;
if (o->shot.level == 2)
{
// initialize wavey effect
o->xmark = o->x;
o->ymark = o->y;
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
// don't let it explode until the "recoil" effect is over.
o->state = STATE_WAIT_RECOIL_OVER;
// record position we were fired at (we won't explode until we pass it)
o->xmark2 = player->x;
o->ymark2 = player->y;
}
else
{
o->state = STATE_MISSILE_CAN_EXPLODE;
}
}
// accelerate according to current type and level of missile
// don't use LIMITX here as it can mess up recoil of level 3 super missiles
switch(o->shot.dir)
{
case RIGHT:
o->xinertia += o->shot.accel;
if (o->xinertia > settings->maxspeed) o->xinertia = settings->maxspeed;
break;
case LEFT:
o->xinertia -= o->shot.accel;
if (o->xinertia < -settings->maxspeed) o->xinertia = -settings->maxspeed;
break;
case UP:
o->yinertia -= o->shot.accel;
if (o->yinertia < -settings->maxspeed) o->yinertia = -settings->maxspeed;
break;
case DOWN:
o->yinertia += o->shot.accel;
if (o->yinertia > settings->maxspeed) o->yinertia = settings->maxspeed;
break;
}
// wavey effect for level 3
// (markx/y is used as a "speed" value here)
if (o->shot.level == 2)
{
if (o->shot.dir == LEFT || o->shot.dir == RIGHT)
{
if (o->y >= o->ymark) o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
else o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? 64 : 32;
o->yinertia += o->speed;
}
else
{
if (o->x >= o->xmark) o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
else o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? 64 : 32;
o->xinertia += o->speed;
}
}
// check if we hit an enemy
// level 3 missiles can not blow up while they are "recoiling"
// what we do is first wait until they're traveling in the direction
// they're pointing, then wait till they pass the player's original position.
switch(o->state)
{
case STATE_WAIT_RECOIL_OVER:
switch(o->shot.dir)
{
case LEFT: if (o->xinertia <= 0) o->state = STATE_RECOIL_OVER; break;
case RIGHT: if (o->xinertia >= 0) o->state = STATE_RECOIL_OVER; break;
case UP: if (o->yinertia <= 0) o->state = STATE_RECOIL_OVER; break;
case DOWN: if (o->yinertia >= 0) o->state = STATE_RECOIL_OVER; break;
}
if (o->state != STATE_RECOIL_OVER)
break;
case STATE_RECOIL_OVER:
switch(o->shot.dir)
{
case LEFT: if (o->x <= o->xmark2-(2 * CSFI)) o->state = STATE_MISSILE_CAN_EXPLODE; break;
case RIGHT: if (o->x >= o->xmark2+(2 * CSFI)) o->state = STATE_MISSILE_CAN_EXPLODE; break;
case UP: if (o->y <= o->ymark2-(2 * CSFI)) o->state = STATE_MISSILE_CAN_EXPLODE; break;
case DOWN: if (o->y >= o->ymark2+(2 * CSFI)) o->state = STATE_MISSILE_CAN_EXPLODE; break;
}
if (o->state != STATE_MISSILE_CAN_EXPLODE)
break;
case STATE_MISSILE_CAN_EXPLODE:
{
bool blow_up = false;
if (damage_enemies(o))
{
blow_up = true;
}
else
{ // check if we hit a wall
if (o->shot.dir==LEFT && o->blockl) blow_up = true;
else if (o->shot.dir==RIGHT && o->blockr) blow_up = true;
else if (o->shot.dir==UP && o->blocku) blow_up = true;
else if (o->shot.dir==DOWN && o->blockd) blow_up = true;
}
if (blow_up)
{
sound(SND_MISSILE_HIT);
// create the boom-spawner object for the flashes, smoke, and AoE damage
int y = o->CenterY();
if (o->shot.dir==LEFT || o->shot.dir==RIGHT) y-=3*CSFI;
Object *sp = CreateBullet(o->CenterX(), y, OBJ_MISSILE_BOOM_SPAWNER);
sp->shot.boomspawner.range = settings->hitrange;
sp->shot.boomspawner.booms_left = settings->lifetime;
sp->shot.damage = settings->boomdamage;
sp->shot.level = settings->boomdamage;
o->Delete();
return;
}
}
break;
}
if (--o->shot.ttl < 0)
shot_dissipate(o, EFFECT_STARPOOF);
// smoke trails
if (++o->timer > 2)
{
o->timer = 0;
Caret *trail = effect(o->CenterX() - o->xinertia, \
o->CenterY() - o->yinertia, EFFECT_SMOKETRAIL);
const int trailspd = 0x400;
switch(o->shot.dir)
{
case LEFT: trail->xinertia = trailspd; trail->y -= (2 * CSFI); break;
case RIGHT: trail->xinertia = -trailspd; trail->y -= (2 * CSFI); break;
case UP: trail->yinertia = trailspd; trail->x -= (1 * CSFI); break;
case DOWN: trail->yinertia = -trailspd; trail->x -= (1 * CSFI); break;
}
}
}
void ai_missile_boom_spawner(Object *o)
{
if (o->state == 0)
{
o->state = 1;
o->timer = 0;
o->xmark = o->x;
o->ymark = o->y;
// give us the same bounding box as the boomflash effects
o->sprite = SPR_BOOMFLASH;
o->invisible = true;
}
if (!(o->shot.boomspawner.booms_left % 3))
{
int range = 0;
switch (o->shot.level)
{
case 1:
range = 16;
break;
case 2:
range = 32;
break;
case 3:
range = 40;
break;
}
int x = o->CenterX() + (random(-range, range) * CSFI);
int y = o->CenterY() + (random(-range, range) * CSFI);
effect(x,y, EFFECT_BOOMFLASH);
missilehitsmoke(x,y, o->shot.boomspawner.range);
}
if (--o->shot.boomspawner.booms_left < 0)
o->Delete();
}
void ai_missile_boom_spawner_tick(Object *o)
{
damage_all_enemies_in_bb(o, FLAG_INVULNERABLE, o->CenterX(), o->CenterY(), o->shot.boomspawner.range);
}
static void missilehitsmoke(int x, int y, int range)
{
int smokex = x + (random(-range, range) * CSFI);
int smokey = y + (random(-range, range) * CSFI);
Object *smoke;
for(int i=0;i<2;i++)
{
smoke = CreateObject(smokex, smokey, OBJ_SMOKE_CLOUD);
smoke->sprite = SPR_MISSILEHITSMOKE;
vector_from_angle(random(0,255), random(0x100,0x3ff), &smoke->xinertia, &smoke->yinertia);
}
}
| 26.157143 | 103 | 0.613736 | sodomon2 |
3ea41a2181bd732662ee203b7d2535b29143d086 | 1,746 | hpp | C++ | modules/core/restructuring/include/nt2/core/functions/along.hpp | pbrunet/nt2 | 2aeca0f6a315725b335efd5d9dc95d72e10a7fb7 | [
"BSL-1.0"
] | 2 | 2016-09-14T00:23:53.000Z | 2018-01-14T12:51:18.000Z | modules/core/restructuring/include/nt2/core/functions/along.hpp | pbrunet/nt2 | 2aeca0f6a315725b335efd5d9dc95d72e10a7fb7 | [
"BSL-1.0"
] | null | null | null | modules/core/restructuring/include/nt2/core/functions/along.hpp | pbrunet/nt2 | 2aeca0f6a315725b335efd5d9dc95d72e10a7fb7 | [
"BSL-1.0"
] | null | null | null | //==============================================================================
// Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CORE_FUNCTIONS_ALONG_HPP_INCLUDED
#define NT2_CORE_FUNCTIONS_ALONG_HPP_INCLUDED
#include <nt2/include/functor.hpp>
/*!
* \ingroup core
* \defgroup core along
*
* \par Description
* Applies an index \c ind on \c expr along the \c i-th dimension
* by default \c i is the first non-singleton dimension of expr
*
* \par Header file
*
* \code
* #include <nt2/include/functions/along.hpp>
* \endcode
*
*
* \synopsis
*
* \code
* namespace boost::simd
* {
* template <class A0>
* typename meta::call<tag::along_(A0)>::type
* along(A0& expr, A1 const& ind, A2 const& i);
* }
* \endcode
*
* \param expr the expression to index
* \param ind the indexer
* \param i the dimension on which to index
*
* \return expr(_, ..., ind, ..., _) with \c ind at the \c i-th argument
*
*
**/
namespace nt2
{
namespace tag
{
struct along_ : ext::elementwise_<along_>
{
typedef ext::elementwise_<along_> parent;
};
}
NT2_FUNCTION_IMPLEMENTATION(nt2::tag::along_ , along, 2)
NT2_FUNCTION_IMPLEMENTATION_SELF(nt2::tag::along_ , along, 2)
NT2_FUNCTION_IMPLEMENTATION(nt2::tag::along_ , along, 3)
NT2_FUNCTION_IMPLEMENTATION_SELF(nt2::tag::along_ , along, 3)
}
#endif
| 26.454545 | 80 | 0.592784 | pbrunet |
3ea41cb0ef6c7267287783073d38fa2857e83765 | 16,310 | hpp | C++ | Software/STM32CubeDemo/RotaryEncoderWithDisplay/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/canvas/Circle.hpp | MitkoDyakov/RED | 3bacb4df47867bbbf23c3c02d0ea1f8faa8d5779 | [
"MIT"
] | 15 | 2021-09-21T13:55:54.000Z | 2022-03-08T14:05:39.000Z | Software/STM32CubeDemo/RotaryEncoderWithDisplay/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/canvas/Circle.hpp | DynamixYANG/Roendi | 2f6703d63922071fd0dfc8e4d2c9bba95ea04f08 | [
"MIT"
] | 7 | 2021-09-22T07:56:52.000Z | 2022-03-21T17:39:34.000Z | Software/STM32CubeDemo/RotaryEncoderWithDisplay/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/canvas/Circle.hpp | DynamixYANG/Roendi | 2f6703d63922071fd0dfc8e4d2c9bba95ea04f08 | [
"MIT"
] | 1 | 2022-03-07T07:51:50.000Z | 2022-03-07T07:51:50.000Z | /******************************************************************************
* Copyright (c) 2018(-2021) STMicroelectronics.
* All rights reserved.
*
* This file is part of the TouchGFX 4.17.0 distribution.
*
* This software is licensed under terms that can be found in the LICENSE file in
* the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
*******************************************************************************/
/**
* @file touchgfx/widgets/canvas/Circle.hpp
*
* Declares the touchgfx::Circle class.
*/
#ifndef TOUCHGFX_CIRCLE_HPP
#define TOUCHGFX_CIRCLE_HPP
#include <touchgfx/hal/Types.hpp>
#include <touchgfx/widgets/canvas/CWRUtil.hpp>
#include <touchgfx/widgets/canvas/Canvas.hpp>
#include <touchgfx/widgets/canvas/CanvasWidget.hpp>
namespace touchgfx
{
/**
* Simple widget capable of drawing a circle, or part of a circle (an arc). The Circle can be
* filled or be drawn as a simple line along the circumference of the circle. Several
* parameters of the circle can be changed: Center, radius, line width, line cap, start
* angle and end angle.
*
* @note Since the underlying CanwasWidgetRenderer only supports straight lines, the circle is
* drawn using many small straight lines segments. The granularity can be adjusted to
* match the requirements - large circles need more line segments, small circles need
* fewer line segments, to look smooth and round.
* @note All circle parameters are internally handled as CWRUtil::Q5 which means that floating
* point values are rounded down to a fixed number of binary digits, for example:
* @code
* Circle circle;
* circle.setCircle(1.1f, 1.1f, 0.9); // Will use (35/32, 35/32, 28/32) = (1.09375f, 1.09375f, 0.875f)
* int x, y, r;
* circle.getCenter(&x, &y); // Will return (1, 1)
* circle.getRadius(&r); // Will return 0
* @endcode.
*/
class Circle : public CanvasWidget
{
public:
Circle();
/**
* Sets the center and radius of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param x The x coordinate of center.
* @param y The y coordinate of center.
* @param r The radius.
*
* @see setCenter, setRadius
*
* @note The area containing the Circle is not invalidated.
*/
template <typename T>
void setCircle(const T x, const T y, const T r)
{
setCenter<T>(x, y);
setRadius<T>(r);
}
/**
* Sets the center and radius of the Circle.
*
* @param x The x coordinate of center.
* @param y The y coordinate of center.
* @param r The radius.
*
* @see setCenter, setRadius
*
* @note The area containing the Circle is not invalidated.
*/
void setCircle(const int16_t x, const int16_t y, const int16_t r)
{
setCircle<int>(x, y, r);
}
/**
* Sets the center of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param x The x coordinate of center.
* @param y The y coordinate of center.
*
* @see setRadius, setCircle, getCenter
*
* @note The area containing the Circle is not invalidated.
*/
template <typename T>
void setCenter(const T x, const T y)
{
this->circleCenterX = CWRUtil::toQ5(x);
this->circleCenterY = CWRUtil::toQ5(y);
}
/**
* Sets the center of the Circle.
*
* @param x The x coordinate of center.
* @param y The y coordinate of center.
*
* @see setRadius, setCircle, getCenter
*
* @note The area containing the Circle is not invalidated.
*/
void setCenter(const int16_t x, const int16_t y)
{
setCenter<int>(x, y);
}
/**
* Sets the center of the circle / arc in the middle of a pixel. Normally the coordinate is
* between pixel number x and x+1 horizontally and between pixel y and y+1 vertically. This
* function will set the center in the middle of the pixel by adding 0.5 to both x and y.
*
* @param x The x coordinate of the center of the circle.
* @param y The y coordinate of the center of the circle.
*/
void setPixelCenter(int x, int y)
{
int32_t half = (int32_t)CWRUtil::toQ5(1) / 2;
setCenter<CWRUtil::Q5>(CWRUtil::Q5((int32_t)CWRUtil::toQ5(x) + half), CWRUtil::Q5((int32_t)CWRUtil::toQ5(y) + half));
}
/**
* Gets the center coordinates of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] x The x coordinate of the center rounded down to the precision of T.
* @param [out] y The y coordinate of the center rounded down to the precision of T.
*
* @see setCenter
*/
template <typename T>
void getCenter(T& x, T& y) const
{
x = circleCenterX.to<T>();
y = circleCenterY.to<T>();
}
/**
* Sets the radius of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param r The radius.
*
* @see setCircle, setCenter, getRadius
*
* @note The area containing the Circle is not invalidated.
*/
template <typename T>
void setRadius(const T r)
{
this->circleRadius = CWRUtil::toQ5(r);
}
/**
* Gets the radius of the Circle.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] r The radius rounded down to the precision of T.
*/
template <typename T>
void getRadius(T& r) const
{
r = circleRadius.to<T>();
}
/**
* Sets the start and end angles in degrees of the Circle arc. 0 degrees is straight up
* (12 o'clock) and 90 degrees is to the left (3 o'clock). Any positive or negative
* degrees can be used to specify the part of the Circle to draw.
*
* @tparam T Generic type parameter, either int or float.
* @param startAngle The start degrees.
* @param endAngle The end degrees.
*
* @see getArc, updateArcStart, updateArcEnd, updateArc
*
* @note The area containing the Circle is not invalidated.
*/
template <typename T>
void setArc(const T startAngle, const T endAngle)
{
circleArcAngleStart = CWRUtil::toQ5(startAngle);
circleArcAngleEnd = CWRUtil::toQ5(endAngle);
}
/**
* Sets the start and end angles in degrees of the Circle arc. 0 degrees is straight up
* (12 o'clock) and 90 degrees is to the left (3 o'clock). Any positive or negative
* degrees can be used to specify the part of the Circle to draw.
*
* @param startAngle The start degrees.
* @param endAngle The end degrees.
*
* @see getArc, updateArcStart, updateArcEnd, updateArc
*
* @note The area containing the Circle is not invalidated.
*/
void setArc(const int16_t startAngle, const int16_t endAngle)
{
setArc<int>(startAngle, endAngle);
}
/**
* Gets the start and end angles in degrees for the circle arc.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] startAngle The start angle rounded down to the precision of T.
* @param [out] endAngle The end angle rounded down to the precision of T.
*
* @see setArc
*/
template <typename T>
void getArc(T& startAngle, T& endAngle) const
{
startAngle = circleArcAngleStart.to<T>();
endAngle = circleArcAngleEnd.to<T>();
}
/**
* Gets the start angle in degrees for the arc.
*
* @return The starting angle for the arc rounded down to an integer.
*
* @see getArc, setArc
*/
int16_t getArcStart() const
{
return circleArcAngleStart.to<int>();
}
/**
* Gets the start angle in degrees for the arc.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] angle The starting angle rounded down to the precision of T.
*
* @see getArc, setArc
*/
template <typename T>
void getArcStart(T& angle) const
{
angle = circleArcAngleStart.to<T>();
}
/**
* Gets the end angle in degrees for the arc.
*
* @return The end angle for the arc rounded down to an integer.
*
* @see getArc, setArc
*/
int16_t getArcEnd() const
{
return circleArcAngleEnd.to<int>();
}
/**
* Gets the end angle in degrees for the arc.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] angle The end angle rounded down to the precision of T.
*/
template <typename T>
void getArcEnd(T& angle) const
{
angle = circleArcAngleEnd.to<T>();
}
/**
* Updates the start angle in degrees for this Circle arc.
*
* @tparam T Generic type parameter, either int or float.
* @param startAngle The start angle in degrees.
*
* @see setArc, updateArcEnd, updateArc
*
* @note The area containing the updated Circle arc is invalidated.
*/
template <typename T>
void updateArcStart(const T startAngle)
{
CWRUtil::Q5 startAngleQ5 = CWRUtil::toQ5(startAngle);
if (circleArcAngleStart == startAngleQ5)
{
return;
}
Rect minimalRect = getMinimalRectForUpdatedStartAngle(startAngleQ5);
circleArcAngleStart = startAngleQ5;
invalidateRect(minimalRect);
}
/**
* Updates the end angle in degrees for this Circle arc.
*
* @tparam T Generic type parameter, either int or float.
* @param endAngle The end angle in degrees.
*
* @see setArc, updateArcStart, updateArc
*
* @note The area containing the updated Circle arc is invalidated.
*/
template <typename T>
void updateArcEnd(const T endAngle)
{
CWRUtil::Q5 endAngleQ5 = CWRUtil::toQ5(endAngle);
if (circleArcAngleEnd == endAngleQ5)
{
return;
}
Rect minimalRect = getMinimalRectForUpdatedEndAngle(endAngleQ5);
circleArcAngleEnd = endAngleQ5;
invalidateRect(minimalRect);
}
/**
* Updates the start and end angle in degrees for this Circle arc.
*
* @tparam T Generic type parameter, either int or float.
* @param startAngle The new start angle in degrees.
* @param endAngle The new end angle in degrees.
*
* @see setArc, getArc, updateArcStart, updateArcEnd
*
* @note The areas containing the updated Circle arcs are invalidated. As little as possible
* will be invalidated for best performance.
*/
template <typename T>
void updateArc(const T startAngle, const T endAngle)
{
updateArc(CWRUtil::toQ5(startAngle), CWRUtil::toQ5(endAngle));
}
/**
* Sets the line width for this Circle. If the line width is set to zero, the circle
* will be filled.
*
* @tparam T Generic type parameter, either int or float.
* @param width The width of the line measured in pixels.
*
* @note The area containing the Circle is not invalidated.
* @note if the new line with is smaller than the old width, the circle should be invalidated
* before updating the width to ensure that the old circle is completely erased.
*/
template <typename T>
void setLineWidth(const T width)
{
this->circleLineWidth = CWRUtil::toQ5(width);
}
/**
* Gets line width.
*
* @tparam T Generic type parameter, either int or float.
* @param [out] width The line width rounded down to the precision of T.
*
* @see setLineWidth
*/
template <typename T>
void getLineWidth(T& width) const
{
width = circleLineWidth.to<T>();
}
/**
* Sets precision of the Circle drawing function. The number given as precision is the
* number of degrees used as step counter when drawing the line fragments around the
* circumference of the circle, five being a reasonable value. Higher values results in
* less nice circles but faster rendering and possibly sufficient for very small
* circles. Large circles might require a precision smaller than five to make the edge
* of the circle look nice and smooth.
*
* @param precision The precision measured in degrees.
*
* @note The circle is not invalidated.
*/
void setPrecision(const int precision);
/**
* Gets the precision of the circle drawing function. The precision is the number of
* degrees used as step counter when drawing smaller line fragments around the
* circumference of the circle, the default being 5.
*
* @return The precision.
*
* @see setPrecision
*/
int getPrecision() const;
/**
* Sets the precision of the ends of the Circle arc. The precision is given in degrees
* where 180 is the default which results in a square ended arc (aka "butt cap"). 90
* will draw "an arrow head" and smaller values gives a round cap. Larger values of
* precision results in faster rendering of the circle.
*
* @param precision The new cap precision.
*
* @note The circle is not invalidated.
* @note The cap precision is not used if the circle is filled (if line width is zero) or when
* a full circle is drawn.
*/
void setCapPrecision(const int precision);
/**
* Gets the precision of the ends of the Circle arc.
*
* @return The cap precision in degrees.
*
* @see getCapPrecision
*/
int getCapPrecision() const;
virtual bool drawCanvasWidget(const Rect& invalidatedArea) const;
virtual Rect getMinimalRect() const;
/**
* Gets minimal rectangle containing a given circle arc using the set line width.
*
* @param arcStart The arc start.
* @param arcEnd The arc end.
*
* @return The minimal rectangle.
*/
Rect getMinimalRect(int16_t arcStart, int16_t arcEnd) const;
/**
* Gets minimal rectangle containing a given circle arc using the set line width.
*
* @param arcStart The arc start.
* @param arcEnd The arc end.
*
* @return The minimal rectangle.
*/
Rect getMinimalRect(CWRUtil::Q5 arcStart, CWRUtil::Q5 arcEnd) const;
protected:
/**
* Updates the start and end angle in degrees for this Circle arc.
*
* @param setStartAngleQ5 The new start angle in degrees.
* @param setEndAngleQ5 The new end angle in degrees.
*
* @see setArc, getArc, updateArcStart, updateArcEnd
*
* @note The areas containing the updated Circle arcs are invalidated. As little as possible
* will be invalidated for best performance.
*/
void updateArc(const CWRUtil::Q5 setStartAngleQ5, const CWRUtil::Q5 setEndAngleQ5);
private:
CWRUtil::Q5 circleCenterX;
CWRUtil::Q5 circleCenterY;
CWRUtil::Q5 circleRadius;
CWRUtil::Q5 circleArcAngleStart;
CWRUtil::Q5 circleArcAngleEnd;
CWRUtil::Q5 circleLineWidth;
uint8_t circleArcIncrement;
uint8_t circleCapArcIncrement;
void moveToAR2(Canvas& canvas, const CWRUtil::Q5& angle, const CWRUtil::Q5& r2) const;
void lineToAR2(Canvas& canvas, const CWRUtil::Q5& angle, const CWRUtil::Q5& r2) const;
void lineToXYAR2(Canvas& canvas, const CWRUtil::Q5& x, const CWRUtil::Q5& y, const CWRUtil::Q5& angle, const CWRUtil::Q5& r2) const;
void updateMinMaxAR(const CWRUtil::Q5& a, const CWRUtil::Q5& r2, CWRUtil::Q5& xMin, CWRUtil::Q5& xMax, CWRUtil::Q5& yMin, CWRUtil::Q5& yMax) const;
void updateMinMaxXY(const CWRUtil::Q5& xNew, const CWRUtil::Q5& yNew, CWRUtil::Q5& xMin, CWRUtil::Q5& xMax, CWRUtil::Q5& yMin, CWRUtil::Q5& yMax) const;
void calculateMinimalRect(CWRUtil::Q5 arcStart, CWRUtil::Q5 arcEnd, CWRUtil::Q5& xMin, CWRUtil::Q5& xMax, CWRUtil::Q5& yMin, CWRUtil::Q5& yMax) const;
Rect getMinimalRectForUpdatedStartAngle(const CWRUtil::Q5& startAngleQ5) const;
Rect getMinimalRectForUpdatedEndAngle(const CWRUtil::Q5& endAngleQ5) const;
};
} // namespace touchgfx
#endif // TOUCHGFX_CIRCLE_HPP
| 33.150407 | 156 | 0.633415 | MitkoDyakov |
3ea66c0035b7a7c05090e3317f1862b8f5d21564 | 53,873 | cc | C++ | proto/rpc.pb.cc | Phantomape/paxos | d88ab88fa5b6c7d74b508580729c4dea4de6f180 | [
"MIT"
] | null | null | null | proto/rpc.pb.cc | Phantomape/paxos | d88ab88fa5b6c7d74b508580729c4dea4de6f180 | [
"MIT"
] | 5 | 2018-05-30T03:09:10.000Z | 2018-06-02T22:56:05.000Z | proto/rpc.pb.cc | Phantomape/paxos | d88ab88fa5b6c7d74b508580729c4dea4de6f180 | [
"MIT"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: rpc.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "rpc.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace paxoskv {
class KVOperatorDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<KVOperator>
_instance;
} _KVOperator_default_instance_;
class KVDataDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<KVData>
_instance;
} _KVData_default_instance_;
class KVResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<KVResponse>
_instance;
} _KVResponse_default_instance_;
namespace protobuf_rpc_2eproto {
namespace {
::google::protobuf::Metadata file_level_metadata[3];
} // namespace
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField
const TableStruct::entries[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField
const TableStruct::aux[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
::google::protobuf::internal::AuxillaryParseTableField(),
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const
TableStruct::schema[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
};
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, key_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, value_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, version_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, operator__),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVOperator, sid_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVData, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVData, value_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVData, version_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVData, isdeleted_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVResponse, data_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVResponse, ret_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(KVResponse, master_nodeid_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(KVOperator)},
{ 10, -1, sizeof(KVData)},
{ 18, -1, sizeof(KVResponse)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&_KVOperator_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_KVData_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_KVResponse_default_instance_),
};
namespace {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"rpc.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3);
}
} // namespace
void TableStruct::InitDefaultsImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::internal::InitProtobufDefaults();
_KVOperator_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_KVOperator_default_instance_);_KVData_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_KVData_default_instance_);_KVResponse_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_KVResponse_default_instance_);_KVResponse_default_instance_._instance.get_mutable()->data_ = const_cast< ::paxoskv::KVData*>(
::paxoskv::KVData::internal_default_instance());
}
void InitDefaults() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
namespace {
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\trpc.proto\022\007paxoskv\"X\n\nKVOperator\022\013\n\003ke"
"y\030\001 \001(\t\022\r\n\005value\030\002 \001(\014\022\017\n\007version\030\003 \001(\004\022"
"\020\n\010operator\030\004 \001(\r\022\013\n\003sid\030\005 \001(\r\";\n\006KVData"
"\022\r\n\005value\030\001 \001(\014\022\017\n\007version\030\002 \001(\004\022\021\n\tisde"
"leted\030\003 \001(\010\"O\n\nKVResponse\022\035\n\004data\030\001 \001(\0132"
"\017.paxoskv.KVData\022\013\n\003ret\030\002 \001(\005\022\025\n\rmaster_"
"nodeid\030\003 \001(\0042\345\001\n\tKVService\0221\n\003Put\022\023.paxo"
"skv.KVOperator\032\023.paxoskv.KVResponse\"\000\0226\n"
"\010GetLocal\022\023.paxoskv.KVOperator\032\023.paxoskv"
".KVResponse\"\000\0227\n\tGetGlobal\022\023.paxoskv.KVO"
"perator\032\023.paxoskv.KVResponse\"\000\0224\n\006Delete"
"\022\023.paxoskv.KVOperator\032\023.paxoskv.KVRespon"
"se\"\000b\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 492);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"rpc.proto", &protobuf_RegisterTypes);
}
} // anonymous namespace
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_rpc_2eproto
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int KVOperator::kKeyFieldNumber;
const int KVOperator::kValueFieldNumber;
const int KVOperator::kVersionFieldNumber;
const int KVOperator::kOperatorFieldNumber;
const int KVOperator::kSidFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
KVOperator::KVOperator()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_rpc_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:paxoskv.KVOperator)
}
KVOperator::KVOperator(const KVOperator& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
key_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.key().size() > 0) {
key_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.key_);
}
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
}
::memcpy(&version_, &from.version_,
static_cast<size_t>(reinterpret_cast<char*>(&sid_) -
reinterpret_cast<char*>(&version_)) + sizeof(sid_));
// @@protoc_insertion_point(copy_constructor:paxoskv.KVOperator)
}
void KVOperator::SharedCtor() {
key_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&version_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&sid_) -
reinterpret_cast<char*>(&version_)) + sizeof(sid_));
_cached_size_ = 0;
}
KVOperator::~KVOperator() {
// @@protoc_insertion_point(destructor:paxoskv.KVOperator)
SharedDtor();
}
void KVOperator::SharedDtor() {
key_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVOperator::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* KVOperator::descriptor() {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const KVOperator& KVOperator::default_instance() {
protobuf_rpc_2eproto::InitDefaults();
return *internal_default_instance();
}
KVOperator* KVOperator::New(::google::protobuf::Arena* arena) const {
KVOperator* n = new KVOperator;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void KVOperator::Clear() {
// @@protoc_insertion_point(message_clear_start:paxoskv.KVOperator)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
key_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&version_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&sid_) -
reinterpret_cast<char*>(&version_)) + sizeof(sid_));
_internal_metadata_.Clear();
}
bool KVOperator::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:paxoskv.KVOperator)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string key = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_key()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->key().data(), static_cast<int>(this->key().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"paxoskv.KVOperator.key"));
} else {
goto handle_unusual;
}
break;
}
// bytes value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
goto handle_unusual;
}
break;
}
// uint64 version = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &version_)));
} else {
goto handle_unusual;
}
break;
}
// uint32 operator = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &operator__)));
} else {
goto handle_unusual;
}
break;
}
// uint32 sid = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &sid_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:paxoskv.KVOperator)
return true;
failure:
// @@protoc_insertion_point(parse_failure:paxoskv.KVOperator)
return false;
#undef DO_
}
void KVOperator::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:paxoskv.KVOperator)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string key = 1;
if (this->key().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->key().data(), static_cast<int>(this->key().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"paxoskv.KVOperator.key");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->key(), output);
}
// bytes value = 2;
if (this->value().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
2, this->value(), output);
}
// uint64 version = 3;
if (this->version() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(3, this->version(), output);
}
// uint32 operator = 4;
if (this->operator_() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(4, this->operator_(), output);
}
// uint32 sid = 5;
if (this->sid() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(5, this->sid(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:paxoskv.KVOperator)
}
::google::protobuf::uint8* KVOperator::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:paxoskv.KVOperator)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string key = 1;
if (this->key().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->key().data(), static_cast<int>(this->key().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"paxoskv.KVOperator.key");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->key(), target);
}
// bytes value = 2;
if (this->value().size() > 0) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
2, this->value(), target);
}
// uint64 version = 3;
if (this->version() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(3, this->version(), target);
}
// uint32 operator = 4;
if (this->operator_() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(4, this->operator_(), target);
}
// uint32 sid = 5;
if (this->sid() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(5, this->sid(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:paxoskv.KVOperator)
return target;
}
size_t KVOperator::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:paxoskv.KVOperator)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// string key = 1;
if (this->key().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->key());
}
// bytes value = 2;
if (this->value().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->value());
}
// uint64 version = 3;
if (this->version() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->version());
}
// uint32 operator = 4;
if (this->operator_() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->operator_());
}
// uint32 sid = 5;
if (this->sid() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->sid());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void KVOperator::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:paxoskv.KVOperator)
GOOGLE_DCHECK_NE(&from, this);
const KVOperator* source =
::google::protobuf::internal::DynamicCastToGenerated<const KVOperator>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:paxoskv.KVOperator)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:paxoskv.KVOperator)
MergeFrom(*source);
}
}
void KVOperator::MergeFrom(const KVOperator& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:paxoskv.KVOperator)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.key().size() > 0) {
key_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.key_);
}
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
}
if (from.version() != 0) {
set_version(from.version());
}
if (from.operator_() != 0) {
set_operator_(from.operator_());
}
if (from.sid() != 0) {
set_sid(from.sid());
}
}
void KVOperator::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:paxoskv.KVOperator)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void KVOperator::CopyFrom(const KVOperator& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:paxoskv.KVOperator)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool KVOperator::IsInitialized() const {
return true;
}
void KVOperator::Swap(KVOperator* other) {
if (other == this) return;
InternalSwap(other);
}
void KVOperator::InternalSwap(KVOperator* other) {
using std::swap;
key_.Swap(&other->key_);
value_.Swap(&other->value_);
swap(version_, other->version_);
swap(operator__, other->operator__);
swap(sid_, other->sid_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata KVOperator::GetMetadata() const {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// KVOperator
// string key = 1;
void KVOperator::clear_key() {
key_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& KVOperator::key() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.key)
return key_.GetNoArena();
}
void KVOperator::set_key(const ::std::string& value) {
key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.key)
}
#if LANG_CXX11
void KVOperator::set_key(::std::string&& value) {
key_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:paxoskv.KVOperator.key)
}
#endif
void KVOperator::set_key(const char* value) {
GOOGLE_DCHECK(value != NULL);
key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:paxoskv.KVOperator.key)
}
void KVOperator::set_key(const char* value, size_t size) {
key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:paxoskv.KVOperator.key)
}
::std::string* KVOperator::mutable_key() {
// @@protoc_insertion_point(field_mutable:paxoskv.KVOperator.key)
return key_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* KVOperator::release_key() {
// @@protoc_insertion_point(field_release:paxoskv.KVOperator.key)
return key_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVOperator::set_allocated_key(::std::string* key) {
if (key != NULL) {
} else {
}
key_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), key);
// @@protoc_insertion_point(field_set_allocated:paxoskv.KVOperator.key)
}
// bytes value = 2;
void KVOperator::clear_value() {
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& KVOperator::value() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.value)
return value_.GetNoArena();
}
void KVOperator::set_value(const ::std::string& value) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.value)
}
#if LANG_CXX11
void KVOperator::set_value(::std::string&& value) {
value_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:paxoskv.KVOperator.value)
}
#endif
void KVOperator::set_value(const char* value) {
GOOGLE_DCHECK(value != NULL);
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:paxoskv.KVOperator.value)
}
void KVOperator::set_value(const void* value, size_t size) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:paxoskv.KVOperator.value)
}
::std::string* KVOperator::mutable_value() {
// @@protoc_insertion_point(field_mutable:paxoskv.KVOperator.value)
return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* KVOperator::release_value() {
// @@protoc_insertion_point(field_release:paxoskv.KVOperator.value)
return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVOperator::set_allocated_value(::std::string* value) {
if (value != NULL) {
} else {
}
value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set_allocated:paxoskv.KVOperator.value)
}
// uint64 version = 3;
void KVOperator::clear_version() {
version_ = GOOGLE_ULONGLONG(0);
}
::google::protobuf::uint64 KVOperator::version() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.version)
return version_;
}
void KVOperator::set_version(::google::protobuf::uint64 value) {
version_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.version)
}
// uint32 operator = 4;
void KVOperator::clear_operator_() {
operator__ = 0u;
}
::google::protobuf::uint32 KVOperator::operator_() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.operator)
return operator__;
}
void KVOperator::set_operator_(::google::protobuf::uint32 value) {
operator__ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.operator)
}
// uint32 sid = 5;
void KVOperator::clear_sid() {
sid_ = 0u;
}
::google::protobuf::uint32 KVOperator::sid() const {
// @@protoc_insertion_point(field_get:paxoskv.KVOperator.sid)
return sid_;
}
void KVOperator::set_sid(::google::protobuf::uint32 value) {
sid_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVOperator.sid)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int KVData::kValueFieldNumber;
const int KVData::kVersionFieldNumber;
const int KVData::kIsdeletedFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
KVData::KVData()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_rpc_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:paxoskv.KVData)
}
KVData::KVData(const KVData& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
}
::memcpy(&version_, &from.version_,
static_cast<size_t>(reinterpret_cast<char*>(&isdeleted_) -
reinterpret_cast<char*>(&version_)) + sizeof(isdeleted_));
// @@protoc_insertion_point(copy_constructor:paxoskv.KVData)
}
void KVData::SharedCtor() {
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&version_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&isdeleted_) -
reinterpret_cast<char*>(&version_)) + sizeof(isdeleted_));
_cached_size_ = 0;
}
KVData::~KVData() {
// @@protoc_insertion_point(destructor:paxoskv.KVData)
SharedDtor();
}
void KVData::SharedDtor() {
value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVData::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* KVData::descriptor() {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const KVData& KVData::default_instance() {
protobuf_rpc_2eproto::InitDefaults();
return *internal_default_instance();
}
KVData* KVData::New(::google::protobuf::Arena* arena) const {
KVData* n = new KVData;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void KVData::Clear() {
// @@protoc_insertion_point(message_clear_start:paxoskv.KVData)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&version_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&isdeleted_) -
reinterpret_cast<char*>(&version_)) + sizeof(isdeleted_));
_internal_metadata_.Clear();
}
bool KVData::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:paxoskv.KVData)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes value = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
goto handle_unusual;
}
break;
}
// uint64 version = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &version_)));
} else {
goto handle_unusual;
}
break;
}
// bool isdeleted = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &isdeleted_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:paxoskv.KVData)
return true;
failure:
// @@protoc_insertion_point(parse_failure:paxoskv.KVData)
return false;
#undef DO_
}
void KVData::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:paxoskv.KVData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes value = 1;
if (this->value().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->value(), output);
}
// uint64 version = 2;
if (this->version() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(2, this->version(), output);
}
// bool isdeleted = 3;
if (this->isdeleted() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(3, this->isdeleted(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:paxoskv.KVData)
}
::google::protobuf::uint8* KVData::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:paxoskv.KVData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes value = 1;
if (this->value().size() > 0) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
1, this->value(), target);
}
// uint64 version = 2;
if (this->version() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(2, this->version(), target);
}
// bool isdeleted = 3;
if (this->isdeleted() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->isdeleted(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:paxoskv.KVData)
return target;
}
size_t KVData::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:paxoskv.KVData)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// bytes value = 1;
if (this->value().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->value());
}
// uint64 version = 2;
if (this->version() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->version());
}
// bool isdeleted = 3;
if (this->isdeleted() != 0) {
total_size += 1 + 1;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void KVData::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:paxoskv.KVData)
GOOGLE_DCHECK_NE(&from, this);
const KVData* source =
::google::protobuf::internal::DynamicCastToGenerated<const KVData>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:paxoskv.KVData)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:paxoskv.KVData)
MergeFrom(*source);
}
}
void KVData::MergeFrom(const KVData& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:paxoskv.KVData)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.value().size() > 0) {
value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_);
}
if (from.version() != 0) {
set_version(from.version());
}
if (from.isdeleted() != 0) {
set_isdeleted(from.isdeleted());
}
}
void KVData::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:paxoskv.KVData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void KVData::CopyFrom(const KVData& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:paxoskv.KVData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool KVData::IsInitialized() const {
return true;
}
void KVData::Swap(KVData* other) {
if (other == this) return;
InternalSwap(other);
}
void KVData::InternalSwap(KVData* other) {
using std::swap;
value_.Swap(&other->value_);
swap(version_, other->version_);
swap(isdeleted_, other->isdeleted_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata KVData::GetMetadata() const {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// KVData
// bytes value = 1;
void KVData::clear_value() {
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& KVData::value() const {
// @@protoc_insertion_point(field_get:paxoskv.KVData.value)
return value_.GetNoArena();
}
void KVData::set_value(const ::std::string& value) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:paxoskv.KVData.value)
}
#if LANG_CXX11
void KVData::set_value(::std::string&& value) {
value_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:paxoskv.KVData.value)
}
#endif
void KVData::set_value(const char* value) {
GOOGLE_DCHECK(value != NULL);
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:paxoskv.KVData.value)
}
void KVData::set_value(const void* value, size_t size) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:paxoskv.KVData.value)
}
::std::string* KVData::mutable_value() {
// @@protoc_insertion_point(field_mutable:paxoskv.KVData.value)
return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* KVData::release_value() {
// @@protoc_insertion_point(field_release:paxoskv.KVData.value)
return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void KVData::set_allocated_value(::std::string* value) {
if (value != NULL) {
} else {
}
value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set_allocated:paxoskv.KVData.value)
}
// uint64 version = 2;
void KVData::clear_version() {
version_ = GOOGLE_ULONGLONG(0);
}
::google::protobuf::uint64 KVData::version() const {
// @@protoc_insertion_point(field_get:paxoskv.KVData.version)
return version_;
}
void KVData::set_version(::google::protobuf::uint64 value) {
version_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVData.version)
}
// bool isdeleted = 3;
void KVData::clear_isdeleted() {
isdeleted_ = false;
}
bool KVData::isdeleted() const {
// @@protoc_insertion_point(field_get:paxoskv.KVData.isdeleted)
return isdeleted_;
}
void KVData::set_isdeleted(bool value) {
isdeleted_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVData.isdeleted)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int KVResponse::kDataFieldNumber;
const int KVResponse::kRetFieldNumber;
const int KVResponse::kMasterNodeidFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
KVResponse::KVResponse()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_rpc_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:paxoskv.KVResponse)
}
KVResponse::KVResponse(const KVResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_data()) {
data_ = new ::paxoskv::KVData(*from.data_);
} else {
data_ = NULL;
}
::memcpy(&master_nodeid_, &from.master_nodeid_,
static_cast<size_t>(reinterpret_cast<char*>(&ret_) -
reinterpret_cast<char*>(&master_nodeid_)) + sizeof(ret_));
// @@protoc_insertion_point(copy_constructor:paxoskv.KVResponse)
}
void KVResponse::SharedCtor() {
::memset(&data_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&ret_) -
reinterpret_cast<char*>(&data_)) + sizeof(ret_));
_cached_size_ = 0;
}
KVResponse::~KVResponse() {
// @@protoc_insertion_point(destructor:paxoskv.KVResponse)
SharedDtor();
}
void KVResponse::SharedDtor() {
if (this != internal_default_instance()) delete data_;
}
void KVResponse::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* KVResponse::descriptor() {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const KVResponse& KVResponse::default_instance() {
protobuf_rpc_2eproto::InitDefaults();
return *internal_default_instance();
}
KVResponse* KVResponse::New(::google::protobuf::Arena* arena) const {
KVResponse* n = new KVResponse;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void KVResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:paxoskv.KVResponse)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == NULL && data_ != NULL) {
delete data_;
}
data_ = NULL;
::memset(&master_nodeid_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&ret_) -
reinterpret_cast<char*>(&master_nodeid_)) + sizeof(ret_));
_internal_metadata_.Clear();
}
bool KVResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:paxoskv.KVResponse)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .paxoskv.KVData data = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_data()));
} else {
goto handle_unusual;
}
break;
}
// int32 ret = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &ret_)));
} else {
goto handle_unusual;
}
break;
}
// uint64 master_nodeid = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &master_nodeid_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:paxoskv.KVResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:paxoskv.KVResponse)
return false;
#undef DO_
}
void KVResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:paxoskv.KVResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .paxoskv.KVData data = 1;
if (this->has_data()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->data_, output);
}
// int32 ret = 2;
if (this->ret() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->ret(), output);
}
// uint64 master_nodeid = 3;
if (this->master_nodeid() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(3, this->master_nodeid(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:paxoskv.KVResponse)
}
::google::protobuf::uint8* KVResponse::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:paxoskv.KVResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .paxoskv.KVData data = 1;
if (this->has_data()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *this->data_, deterministic, target);
}
// int32 ret = 2;
if (this->ret() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->ret(), target);
}
// uint64 master_nodeid = 3;
if (this->master_nodeid() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(3, this->master_nodeid(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:paxoskv.KVResponse)
return target;
}
size_t KVResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:paxoskv.KVResponse)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// .paxoskv.KVData data = 1;
if (this->has_data()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->data_);
}
// uint64 master_nodeid = 3;
if (this->master_nodeid() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->master_nodeid());
}
// int32 ret = 2;
if (this->ret() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->ret());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void KVResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:paxoskv.KVResponse)
GOOGLE_DCHECK_NE(&from, this);
const KVResponse* source =
::google::protobuf::internal::DynamicCastToGenerated<const KVResponse>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:paxoskv.KVResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:paxoskv.KVResponse)
MergeFrom(*source);
}
}
void KVResponse::MergeFrom(const KVResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:paxoskv.KVResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_data()) {
mutable_data()->::paxoskv::KVData::MergeFrom(from.data());
}
if (from.master_nodeid() != 0) {
set_master_nodeid(from.master_nodeid());
}
if (from.ret() != 0) {
set_ret(from.ret());
}
}
void KVResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:paxoskv.KVResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void KVResponse::CopyFrom(const KVResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:paxoskv.KVResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool KVResponse::IsInitialized() const {
return true;
}
void KVResponse::Swap(KVResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void KVResponse::InternalSwap(KVResponse* other) {
using std::swap;
swap(data_, other->data_);
swap(master_nodeid_, other->master_nodeid_);
swap(ret_, other->ret_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata KVResponse::GetMetadata() const {
protobuf_rpc_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_rpc_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// KVResponse
// .paxoskv.KVData data = 1;
bool KVResponse::has_data() const {
return this != internal_default_instance() && data_ != NULL;
}
void KVResponse::clear_data() {
if (GetArenaNoVirtual() == NULL && data_ != NULL) delete data_;
data_ = NULL;
}
const ::paxoskv::KVData& KVResponse::data() const {
const ::paxoskv::KVData* p = data_;
// @@protoc_insertion_point(field_get:paxoskv.KVResponse.data)
return p != NULL ? *p : *reinterpret_cast<const ::paxoskv::KVData*>(
&::paxoskv::_KVData_default_instance_);
}
::paxoskv::KVData* KVResponse::mutable_data() {
if (data_ == NULL) {
data_ = new ::paxoskv::KVData;
}
// @@protoc_insertion_point(field_mutable:paxoskv.KVResponse.data)
return data_;
}
::paxoskv::KVData* KVResponse::release_data() {
// @@protoc_insertion_point(field_release:paxoskv.KVResponse.data)
::paxoskv::KVData* temp = data_;
data_ = NULL;
return temp;
}
void KVResponse::set_allocated_data(::paxoskv::KVData* data) {
delete data_;
data_ = data;
if (data) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:paxoskv.KVResponse.data)
}
// int32 ret = 2;
void KVResponse::clear_ret() {
ret_ = 0;
}
::google::protobuf::int32 KVResponse::ret() const {
// @@protoc_insertion_point(field_get:paxoskv.KVResponse.ret)
return ret_;
}
void KVResponse::set_ret(::google::protobuf::int32 value) {
ret_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVResponse.ret)
}
// uint64 master_nodeid = 3;
void KVResponse::clear_master_nodeid() {
master_nodeid_ = GOOGLE_ULONGLONG(0);
}
::google::protobuf::uint64 KVResponse::master_nodeid() const {
// @@protoc_insertion_point(field_get:paxoskv.KVResponse.master_nodeid)
return master_nodeid_;
}
void KVResponse::set_master_nodeid(::google::protobuf::uint64 value) {
master_nodeid_ = value;
// @@protoc_insertion_point(field_set:paxoskv.KVResponse.master_nodeid)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace paxoskv
// @@protoc_insertion_point(global_scope)
| 34.600514 | 168 | 0.700704 | Phantomape |
3ea6ff1bed0cae338b925ecd2f50e466b26bb90f | 786 | cpp | C++ | test/main.cpp | billsioros/cpp-builder | 16a12a30f78d9214311c6768d29178300331c6f6 | [
"MIT"
] | 3 | 2019-03-11T16:34:37.000Z | 2020-05-08T20:22:35.000Z | test/main.cpp | billsioros/cpp-builder | 16a12a30f78d9214311c6768d29178300331c6f6 | [
"MIT"
] | null | null | null | test/main.cpp | billsioros/cpp-builder | 16a12a30f78d9214311c6768d29178300331c6f6 | [
"MIT"
] | null | null | null |
#include <point.hpp>
#include <vector>
#include <iostream>
#if defined (__ARBITARY__)
#include <cstdlib>
#include <ctime>
#define rand01 (static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX))
#define frand(min, max) ((max - min) * rand01 + min)
#endif
#define SIZE (10UL)
int main()
{
std::vector<Point> points;
#if defined (__ARBITARY__)
std::srand(static_cast<unsigned>(std::time(nullptr)));
for (std::size_t i = 0UL; i < SIZE; i++)
points.emplace_back(frand(-10.0f, 10.0f), frand(-10.0f, 10.0f));
#else
for (std::size_t i = 0UL; i < SIZE; i++)
points.emplace_back(0.0f, 0.0f);
#endif
for (const auto& point : points)
std::cout << point << std::endl;
return 0;
}
| 21.243243 | 83 | 0.583969 | billsioros |
3ea9ac90846e2a08614dbdf1312acaaeb792fc77 | 204 | hpp | C++ | 01-brickbreaker/src/brickbreaker/Entity.hpp | fmenozzi/games | f52dbfaf9c7bea76ad91c9ab104ac9d05e0d4b36 | [
"MIT"
] | 2 | 2015-05-23T04:33:56.000Z | 2016-01-29T08:19:49.000Z | 01-brickbreaker/src/brickbreaker/Entity.hpp | fmenozzi/games | f52dbfaf9c7bea76ad91c9ab104ac9d05e0d4b36 | [
"MIT"
] | 2 | 2015-05-23T03:33:36.000Z | 2015-05-23T04:22:26.000Z | 01-brickbreaker/src/brickbreaker/Entity.hpp | fmenozzi/games | f52dbfaf9c7bea76ad91c9ab104ac9d05e0d4b36 | [
"MIT"
] | 2 | 2015-05-23T03:39:12.000Z | 2020-05-04T13:03:02.000Z | #pragma once
#include <SFML/Graphics.hpp>
class Entity
{
public:
bool destroyed{false};
virtual ~Entity() {}
virtual void update() {}
virtual void draw(sf::RenderWindow& mTarget) {}
}; | 15.692308 | 51 | 0.651961 | fmenozzi |
3eaaa8a7c5ea3cb3670d3bf86a69676fd620cf89 | 204 | cpp | C++ | Source/RegionGrowing/Algorithm/SpaceMapping.cpp | timdecode/InteractiveElementPalettes | ea5b7fcd78f8413aa9c770788259fbb944d4778d | [
"MIT"
] | 1 | 2018-09-05T20:55:42.000Z | 2018-09-05T20:55:42.000Z | Source/RegionGrowing/Algorithm/SpaceMapping.cpp | timdecode/InteractiveDiscreteElementPalettes | ea5b7fcd78f8413aa9c770788259fbb944d4778d | [
"MIT"
] | null | null | null | Source/RegionGrowing/Algorithm/SpaceMapping.cpp | timdecode/InteractiveDiscreteElementPalettes | ea5b7fcd78f8413aa9c770788259fbb944d4778d | [
"MIT"
] | null | null | null | //
// SpaceMapping.cpp
// RegionGrowing
//
// Created by Timothy Davison on 2015-09-10.
// Copyright © 2015 EpicGames. All rights reserved.
//
#include "RegionGrowing.h"
#include "SpaceMapping.hpp"
| 17 | 52 | 0.70098 | timdecode |
3eac724bf6a9bf906b2d34cd64acc5e02587c14b | 235 | cpp | C++ | src/blend2d/pipeline/piperuntime.cpp | Daxaker/blend2d | e8128b663d40f5a590f7690868be419d19c4f933 | [
"Zlib"
] | 63 | 2016-04-06T19:30:32.000Z | 2018-09-28T10:56:54.000Z | src/blend2d/pipeline/piperuntime.cpp | Daxaker/blend2d | e8128b663d40f5a590f7690868be419d19c4f933 | [
"Zlib"
] | 1 | 2018-07-29T17:31:30.000Z | 2018-10-08T18:32:07.000Z | src/blend2d/pipeline/piperuntime.cpp | Daxaker/blend2d | e8128b663d40f5a590f7690868be419d19c4f933 | [
"Zlib"
] | null | null | null | // This file is part of Blend2D project <https://blend2d.com>
//
// See blend2d.h or LICENSE.md for license and copyright information
// SPDX-License-Identifier: Zlib
#include "../api-build_p.h"
#include "../pipeline/piperuntime_p.h"
| 29.375 | 68 | 0.731915 | Daxaker |
3eacf107d174a21181edeca324594fd06fc1b4a7 | 1,980 | cpp | C++ | level_zero/tools/source/sysman/firmware/linux/os_firmware_imp_helper_prelim.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | level_zero/tools/source/sysman/firmware/linux/os_firmware_imp_helper_prelim.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | level_zero/tools/source/sysman/firmware/linux/os_firmware_imp_helper_prelim.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | /*
* Copyright (C) 2021-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "level_zero/tools/source/sysman/firmware/linux/os_firmware_imp.h"
const std::string iafPath = "device/";
const std::string iafDirectory = "iaf.";
const std::string pscbin_version = "/pscbin_version";
namespace L0 {
ze_result_t LinuxFirmwareImp::getFirmwareVersion(std::string fwType, zes_firmware_properties_t *pProperties) {
std::string fwVersion;
if (fwType == "PSC") {
std::string path;
path.clear();
std::vector<std::string> list;
// scans the directories present in /sys/class/drm/cardX/device/
ze_result_t result = pSysfsAccess->scanDirEntries(iafPath, list);
if (ZE_RESULT_SUCCESS != result) {
// There should be a device directory
return result;
}
for (const auto &entry : list) {
if (!iafDirectory.compare(entry.substr(0, iafDirectory.length()))) {
// device/iaf.X/pscbin_version, where X is the hardware slot number
path = iafPath + entry + pscbin_version;
}
}
if (path.empty()) {
// This device does not have a PSC Version
return ZE_RESULT_ERROR_NOT_AVAILABLE;
}
std::string pscVersion;
pscVersion.clear();
result = pSysfsAccess->read(path, pscVersion);
if (ZE_RESULT_SUCCESS != result) {
// not able to read PSC version from iaf.x
return result;
}
strncpy_s(static_cast<char *>(pProperties->version), ZES_STRING_PROPERTY_SIZE, pscVersion.c_str(), ZES_STRING_PROPERTY_SIZE);
return result;
}
ze_result_t result = pFwInterface->getFwVersion(fwType, fwVersion);
if (result == ZE_RESULT_SUCCESS) {
strncpy_s(static_cast<char *>(pProperties->version), ZES_STRING_PROPERTY_SIZE, fwVersion.c_str(), ZES_STRING_PROPERTY_SIZE);
}
return result;
}
} // namespace L0 | 35.357143 | 133 | 0.638889 | mattcarter2017 |
3eadd062b33b0c5fa6b004190c0220295624b71a | 2,221 | hpp | C++ | include/gui/pl_report.hpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | 4 | 2016-07-05T07:42:07.000Z | 2020-07-15T15:27:22.000Z | include/gui/pl_report.hpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | 1 | 2020-05-07T20:58:21.000Z | 2020-05-07T20:58:21.000Z | include/gui/pl_report.hpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2013 Matthew Harvey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GUARD_pl_report_hpp_03798236466850264
#define GUARD_pl_report_hpp_03798236466850264
#include "report.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <jewel/decimal.hpp>
#include <wx/gdicmn.h>
#include <unordered_map>
namespace dcm
{
// begin forward declarations
class DcmDatabaseConnection;
namespace gui
{
class ReportPanel;
// end forward declarations
class PLReport: public Report
{
public:
PLReport
( ReportPanel* p_parent,
wxSize const& p_size,
DcmDatabaseConnection& p_database_connection,
boost::optional<boost::gregorian::date> const& p_maybe_min_date,
boost::optional<boost::gregorian::date> const& p_maybe_max_date
);
PLReport(PLReport const&) = delete;
PLReport(PLReport&&) = delete;
PLReport& operator=(PLReport const&) = delete;
PLReport& operator=(PLReport&&) = delete;
virtual ~PLReport();
private:
virtual void do_generate() override;
/**
* @returns an initialized optional only if there is a max_date().
*/
boost::optional<int> maybe_num_days_in_period() const;
/**
* Displays "N/A" or the like if p_count is zero. Displays in
* current_row().
*/
void display_mean
( int p_column,
jewel::Decimal const& p_total = jewel::Decimal(0, 0),
int p_count = 0
);
void refresh_map();
void display_body();
typedef std::unordered_map<sqloxx::Id, jewel::Decimal> Map;
Map m_map;
}; // class PLReport
} // namespace gui
} // namespace dcm
#endif // GUARD_pl_report_hpp_03798236466850264
| 24.955056 | 75 | 0.700585 | skybaboon |
3eadf1dc6cd860b1a61bdd91a759d119bb8ae4bf | 1,310 | cc | C++ | peridot/lib/scoped_tmpfs/scoped_tmpfs.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 1 | 2019-10-09T10:50:57.000Z | 2019-10-09T10:50:57.000Z | peridot/lib/scoped_tmpfs/scoped_tmpfs.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 5 | 2020-09-06T09:02:06.000Z | 2022-03-02T04:44:22.000Z | peridot/lib/scoped_tmpfs/scoped_tmpfs.cc | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "peridot/lib/scoped_tmpfs/scoped_tmpfs.h"
#include <lib/fdio/fd.h>
#include <lib/fdio/fdio.h>
#include <lib/fdio/directory.h>
#include <lib/fsl/io/fd.h>
#include <src/lib/fxl/logging.h>
#include <lib/sync/completion.h>
#include <zircon/processargs.h>
namespace scoped_tmpfs {
namespace {
async_loop_config_t MakeConfig() {
async_loop_config_t result = kAsyncLoopConfigAttachToThread;
result.make_default_for_current_thread = false;
return result;
}
} // namespace
ScopedTmpFS::ScopedTmpFS() : config_(MakeConfig()), loop_(&config_) {
zx_status_t status = loop_.StartThread("tmpfs_thread");
FXL_CHECK(status == ZX_OK);
zx_handle_t root_handle;
status = memfs_create_filesystem(loop_.dispatcher(), &memfs_, &root_handle);
FXL_CHECK(status == ZX_OK);
root_fd_ = fsl::OpenChannelAsFileDescriptor(zx::channel(root_handle));
FXL_CHECK(root_fd_.is_valid());
}
ScopedTmpFS::~ScopedTmpFS() {
root_fd_.reset();
sync_completion_t unmounted;
memfs_free_filesystem(memfs_, &unmounted);
zx_status_t status = sync_completion_wait(&unmounted, ZX_SEC(3));
FXL_DCHECK(status == ZX_OK);
}
} // namespace scoped_tmpfs
| 29.772727 | 78 | 0.754962 | zhangpf |
3eb2b85c16cd6240ae45e722117965d60ada3733 | 11,947 | cpp | C++ | example/estimate_distance.cpp | hidmic/voxelized_geometry_tools | 5fd9d3e267411fa29c5aef4c809f7e47920a4e38 | [
"BSD-3-Clause"
] | null | null | null | example/estimate_distance.cpp | hidmic/voxelized_geometry_tools | 5fd9d3e267411fa29c5aef4c809f7e47920a4e38 | [
"BSD-3-Clause"
] | null | null | null | example/estimate_distance.cpp | hidmic/voxelized_geometry_tools | 5fd9d3e267411fa29c5aef4c809f7e47920a4e38 | [
"BSD-3-Clause"
] | null | null | null | #include <common_robotics_utilities/print.hpp>
#include <voxelized_geometry_tools/collision_map.hpp>
#include <voxelized_geometry_tools/signed_distance_field.hpp>
#include <voxelized_geometry_tools/ros_interface.hpp>
#include <ros/ros.h>
#include <visualization_msgs/MarkerArray.h>
#include <functional>
#include <common_robotics_utilities/conversions.hpp>
#include <common_robotics_utilities/color_builder.hpp>
void test_estimate_distance(
const std::function<void(
const visualization_msgs::MarkerArray&)>& display_fn)
{
const double res = 1.0; //0.125; //1.0;
const double size = 10.0;
const Eigen::Isometry3d origin_transform
= Eigen::Translation3d(0.0, 0.0, 0.0) * Eigen::Quaterniond(
Eigen::AngleAxisd(M_PI_4, Eigen::Vector3d::UnitZ()));
const common_robotics_utilities::voxel_grid::GridSizes map_sizes(res, size, size, 1.0);
auto map = voxelized_geometry_tools::CollisionMap(origin_transform, "world", map_sizes, voxelized_geometry_tools::CollisionCell(0.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(5.0, 5.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(5.0, 6.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(6.0, 5.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(6.0, 6.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(7.0, 7.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(2.0, 2.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(3.0, 2.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(4.0, 2.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(2.0, 3.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(2.0, 4.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
map.SetValue4d(origin_transform * Eigen::Vector4d(2.0, 7.0, 0.0, 1.0), voxelized_geometry_tools::CollisionCell(1.0));
const std_msgs::ColorRGBA collision_color = common_robotics_utilities::color_builder::MakeFromFloatColors<std_msgs::ColorRGBA>(1.0, 0.0, 0.0, 0.5);
const std_msgs::ColorRGBA free_color = common_robotics_utilities::color_builder::MakeFromFloatColors<std_msgs::ColorRGBA>(0.0, 0.0, 0.0, 0.0);
const std_msgs::ColorRGBA unknown_color = common_robotics_utilities::color_builder::MakeFromFloatColors<std_msgs::ColorRGBA>(0.0, 0.0, 0.0, 0.0);
const auto map_marker = voxelized_geometry_tools::ros_interface::ExportForDisplay(map, collision_color, free_color, unknown_color);
const auto sdf = map.ExtractSignedDistanceField(1e6, true, false, false).DistanceField();
const auto sdf_marker = voxelized_geometry_tools::ros_interface::ExportSDFForDisplay(sdf, 0.05f);
// Assemble a visualization_markers::Marker representation of the SDF to display in RViz
visualization_msgs::Marker distance_rep;
// Populate the header
distance_rep.header.frame_id = "world";
// Populate the options
distance_rep.ns = "estimated_distance_display";
distance_rep.id = 1;
distance_rep.type = visualization_msgs::Marker::CUBE_LIST;
distance_rep.action = visualization_msgs::Marker::ADD;
distance_rep.lifetime = ros::Duration(0.0);
distance_rep.frame_locked = false;
distance_rep.pose
= common_robotics_utilities::ros_conversions::EigenIsometry3dToGeometryPose(sdf.GetOriginTransform());
const double step = sdf.GetResolution() * 0.125 * 0.25;
distance_rep.scale.x = sdf.GetResolution() * step;// * 0.125;
distance_rep.scale.y = sdf.GetResolution() * step;// * 0.125;
distance_rep.scale.z = sdf.GetResolution() * 0.95;// * 0.125;// * 0.125;
// Add all the cells of the SDF to the message
double min_distance = 0.0;
double max_distance = 0.0;
// Add colors for all the cells of the SDF to the message
for (double x = 0; x < sdf.GetXSize(); x += step)
{
for (double y = 0; y < sdf.GetYSize(); y += step)
{
double z = 0.5;
//for (double z = 0; z <= sdf.GetZSize(); z += step)
{
const Eigen::Vector4d point(x, y, z, 1.0);
const Eigen::Vector4d point_in_grid_frame = origin_transform * point;
// Update minimum/maximum distance variables
const double distance
= sdf.EstimateDistance4d(point_in_grid_frame).Value();
if (distance > max_distance)
{
max_distance = distance;
}
if (distance < min_distance)
{
min_distance = distance;
}
}
}
}
std::cout << "Min dist " << min_distance << " Max dist " << max_distance << std::endl;
for (double x = 0; x < sdf.GetXSize(); x += step)
{
for (double y = 0; y < sdf.GetYSize(); y += step)
{
double z = 0.5;
//for (double z = 0; z <= sdf.GetZSize(); z += step)
{
const Eigen::Vector4d point(x, y, z, 1.0);
const Eigen::Vector4d point_in_grid_frame = origin_transform * point;
const double distance
= sdf.EstimateDistance4d(point_in_grid_frame).Value();
if (distance >= 0.0)
{
const std_msgs::ColorRGBA new_color
= common_robotics_utilities::color_builder::InterpolateHotToCold<std_msgs::ColorRGBA>(distance, 0.0, max_distance);
distance_rep.colors.push_back(new_color);
}
else
{
const std_msgs::ColorRGBA new_color
= common_robotics_utilities::color_builder::MakeFromFloatColors<std_msgs::ColorRGBA>(1.0, 0.0, 1.0, 1.0);
distance_rep.colors.push_back(new_color);
}
geometry_msgs::Point new_point;
new_point.x = x;
new_point.y = y;
new_point.z = z;
distance_rep.points.push_back(new_point);
}
}
}
visualization_msgs::MarkerArray markers;
markers.markers = {map_marker, sdf_marker, distance_rep};
// Make gradient markers
for (int64_t x_idx = 0; x_idx < sdf.GetNumXCells(); x_idx++)
{
for (int64_t y_idx = 0; y_idx < sdf.GetNumYCells(); y_idx++)
{
for (int64_t z_idx = 0; z_idx < sdf.GetNumZCells(); z_idx++)
{
const Eigen::Vector4d location
= sdf.GridIndexToLocation(x_idx, y_idx, z_idx);
const auto coarse_gradient = sdf.GetCoarseGradient4d(location, true);
const auto fine_gradient = sdf.GetFineGradient4d(location, sdf.GetResolution() * 0.125);
const auto autodiff_gradient = sdf.GetAutoDiffGradient4d(location);
if (coarse_gradient)
{
std::cout << "Coarse gradient " << common_robotics_utilities::print::Print(coarse_gradient.Value()) << std::endl;
const Eigen::Vector4d& gradient_vector = coarse_gradient.Value();
visualization_msgs::Marker gradient_rep;
// Populate the header
gradient_rep.header.frame_id = "world";
// Populate the options
gradient_rep.ns = "coarse_gradient";
gradient_rep.id = static_cast<int32_t>(sdf.HashDataIndex(x_idx, y_idx, z_idx));
gradient_rep.type = visualization_msgs::Marker::ARROW;
gradient_rep.action = visualization_msgs::Marker::ADD;
gradient_rep.lifetime = ros::Duration(0.0);
gradient_rep.frame_locked = false;
gradient_rep.pose
= common_robotics_utilities::ros_conversions::EigenIsometry3dToGeometryPose(Eigen::Isometry3d::Identity());
gradient_rep.points.push_back(common_robotics_utilities::ros_conversions::EigenVector4dToGeometryPoint(location));
gradient_rep.points.push_back(common_robotics_utilities::ros_conversions::EigenVector4dToGeometryPoint(location + gradient_vector));
gradient_rep.scale.x = sdf.GetResolution() * 0.06125;
gradient_rep.scale.y = sdf.GetResolution() * 0.125;
gradient_rep.scale.z = 0.0;
gradient_rep.color = common_robotics_utilities::color_builder::MakeFromFloatColors<std_msgs::ColorRGBA>(1.0, 0.5, 0.0, 1.0);
markers.markers.push_back(gradient_rep);
}
if (fine_gradient)
{
std::cout << "Fine gradient " << common_robotics_utilities::print::Print(fine_gradient.Value()) << std::endl;
const Eigen::Vector4d& gradient_vector = fine_gradient.Value();
visualization_msgs::Marker gradient_rep;
// Populate the header
gradient_rep.header.frame_id = "world";
// Populate the options
gradient_rep.ns = "fine_gradient";
gradient_rep.id = static_cast<int32_t>(sdf.HashDataIndex(x_idx, y_idx, z_idx));
gradient_rep.type = visualization_msgs::Marker::ARROW;
gradient_rep.action = visualization_msgs::Marker::ADD;
gradient_rep.lifetime = ros::Duration(0.0);
gradient_rep.frame_locked = false;
gradient_rep.pose
= common_robotics_utilities::ros_conversions::EigenIsometry3dToGeometryPose(Eigen::Isometry3d::Identity());
gradient_rep.points.push_back(common_robotics_utilities::ros_conversions::EigenVector4dToGeometryPoint(location));
gradient_rep.points.push_back(common_robotics_utilities::ros_conversions::EigenVector4dToGeometryPoint(location + gradient_vector));
gradient_rep.scale.x = sdf.GetResolution() * 0.06125;
gradient_rep.scale.y = sdf.GetResolution() * 0.125;
gradient_rep.scale.z = 0.0;
gradient_rep.color = common_robotics_utilities::color_builder::MakeFromFloatColors<std_msgs::ColorRGBA>(0.0, 0.5, 1.0, 1.0);
markers.markers.push_back(gradient_rep);
}
if (autodiff_gradient)
{
std::cout << "Autodiff gradient " << common_robotics_utilities::print::Print(autodiff_gradient.Value()) << std::endl;
const Eigen::Vector4d& gradient_vector = autodiff_gradient.Value();
visualization_msgs::Marker gradient_rep;
// Populate the header
gradient_rep.header.frame_id = "world";
// Populate the options
gradient_rep.ns = "autodiff_gradient";
gradient_rep.id = static_cast<int32_t>(sdf.HashDataIndex(x_idx, y_idx, z_idx));
gradient_rep.type = visualization_msgs::Marker::ARROW;
gradient_rep.action = visualization_msgs::Marker::ADD;
gradient_rep.lifetime = ros::Duration(0.0);
gradient_rep.frame_locked = false;
gradient_rep.pose
= common_robotics_utilities::ros_conversions::EigenIsometry3dToGeometryPose(Eigen::Isometry3d::Identity());
gradient_rep.points.push_back(common_robotics_utilities::ros_conversions::EigenVector4dToGeometryPoint(location));
gradient_rep.points.push_back(common_robotics_utilities::ros_conversions::EigenVector4dToGeometryPoint(location + gradient_vector));
gradient_rep.scale.x = sdf.GetResolution() * 0.06125;
gradient_rep.scale.y = sdf.GetResolution() * 0.125;
gradient_rep.scale.z = 0.0;
gradient_rep.color = common_robotics_utilities::color_builder::MakeFromFloatColors<std_msgs::ColorRGBA>(0.5, 0.0, 1.0, 1.0);
markers.markers.push_back(gradient_rep);
}
}
}
}
display_fn(markers);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "estimate_distance_test");
ros::NodeHandle nh;
ros::Publisher display_pub
= nh.advertise<visualization_msgs::MarkerArray>(
"display_test_voxel_grid", 1, true);
const std::function<void(const visualization_msgs::MarkerArray&)>& display_fn
= [&] (const visualization_msgs::MarkerArray& markers)
{
display_pub.publish(markers);
};
test_estimate_distance(display_fn);
ros::spin();
return 0;
}
| 53.573991 | 149 | 0.690131 | hidmic |
3eb4cab840da02016921d9de65efb32c1575deb1 | 10,006 | cpp | C++ | libcxx/test/libcxx/atomics/diagnose_invalid_memory_order.verify.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 605 | 2019-10-18T01:15:54.000Z | 2022-03-31T14:31:04.000Z | libcxx/test/libcxx/atomics/diagnose_invalid_memory_order.verify.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 3,180 | 2019-10-18T01:21:21.000Z | 2022-03-31T23:25:41.000Z | libcxx/test/libcxx/atomics/diagnose_invalid_memory_order.verify.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 275 | 2019-10-18T05:27:22.000Z | 2022-03-30T09:04:21.000Z | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// This test fails because diagnose_if doesn't emit all of the diagnostics
// when -fdelayed-template-parsing is enabled, like it is in MSVC mode.
// XFAIL: msvc
// REQUIRES: diagnose-if-support
// <atomic>
// Test that invalid memory order arguments are diagnosed where possible.
#include <atomic>
int main(int, char**) {
std::atomic<int> x(42);
volatile std::atomic<int>& vx = x;
int val1 = 1; ((void)val1);
int val2 = 2; ((void)val2);
// load operations
{
x.load(std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
x.load(std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
vx.load(std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
vx.load(std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
// valid memory orders
x.load(std::memory_order_relaxed);
x.load(std::memory_order_consume);
x.load(std::memory_order_acquire);
x.load(std::memory_order_seq_cst);
}
{
std::atomic_load_explicit(&x, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_load_explicit(&x, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_load_explicit(&vx, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_load_explicit(&vx, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
// valid memory orders
std::atomic_load_explicit(&x, std::memory_order_relaxed);
std::atomic_load_explicit(&x, std::memory_order_consume);
std::atomic_load_explicit(&x, std::memory_order_acquire);
std::atomic_load_explicit(&x, std::memory_order_seq_cst);
}
// store operations
{
x.store(42, std::memory_order_consume); // expected-warning {{memory order argument to atomic operation is invalid}}
x.store(42, std::memory_order_acquire); // expected-warning {{memory order argument to atomic operation is invalid}}
x.store(42, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
vx.store(42, std::memory_order_consume); // expected-warning {{memory order argument to atomic operation is invalid}}
vx.store(42, std::memory_order_acquire); // expected-warning {{memory order argument to atomic operation is invalid}}
vx.store(42, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
// valid memory orders
x.store(42, std::memory_order_relaxed);
x.store(42, std::memory_order_release);
x.store(42, std::memory_order_seq_cst);
}
{
std::atomic_store_explicit(&x, 42, std::memory_order_consume); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_store_explicit(&x, 42, std::memory_order_acquire); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_store_explicit(&x, 42, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_store_explicit(&vx, 42, std::memory_order_consume); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_store_explicit(&vx, 42, std::memory_order_acquire); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_store_explicit(&vx, 42, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
// valid memory orders
std::atomic_store_explicit(&x, 42, std::memory_order_relaxed);
std::atomic_store_explicit(&x, 42, std::memory_order_release);
std::atomic_store_explicit(&x, 42, std::memory_order_seq_cst);
}
// compare exchange weak
{
x.compare_exchange_weak(val1, val2, std::memory_order_seq_cst, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
x.compare_exchange_weak(val1, val2, std::memory_order_seq_cst, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
vx.compare_exchange_weak(val1, val2, std::memory_order_seq_cst, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
vx.compare_exchange_weak(val1, val2, std::memory_order_seq_cst, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
// valid memory orders
x.compare_exchange_weak(val1, val2, std::memory_order_seq_cst, std::memory_order_relaxed);
x.compare_exchange_weak(val1, val2, std::memory_order_seq_cst, std::memory_order_consume);
x.compare_exchange_weak(val1, val2, std::memory_order_seq_cst, std::memory_order_acquire);
x.compare_exchange_weak(val1, val2, std::memory_order_seq_cst, std::memory_order_seq_cst);
// Test that the cmpxchg overload with only one memory order argument
// does not generate any diagnostics.
x.compare_exchange_weak(val1, val2, std::memory_order_release);
}
{
std::atomic_compare_exchange_weak_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_compare_exchange_weak_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_compare_exchange_weak_explicit(&vx, &val1, val2, std::memory_order_seq_cst, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_compare_exchange_weak_explicit(&vx, &val1, val2, std::memory_order_seq_cst, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
// valid memory orders
std::atomic_compare_exchange_weak_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_relaxed);
std::atomic_compare_exchange_weak_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_consume);
std::atomic_compare_exchange_weak_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_acquire);
std::atomic_compare_exchange_weak_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_seq_cst);
}
// compare exchange strong
{
x.compare_exchange_strong(val1, val2, std::memory_order_seq_cst, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
x.compare_exchange_strong(val1, val2, std::memory_order_seq_cst, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
vx.compare_exchange_strong(val1, val2, std::memory_order_seq_cst, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
vx.compare_exchange_strong(val1, val2, std::memory_order_seq_cst, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
// valid memory orders
x.compare_exchange_strong(val1, val2, std::memory_order_seq_cst, std::memory_order_relaxed);
x.compare_exchange_strong(val1, val2, std::memory_order_seq_cst, std::memory_order_consume);
x.compare_exchange_strong(val1, val2, std::memory_order_seq_cst, std::memory_order_acquire);
x.compare_exchange_strong(val1, val2, std::memory_order_seq_cst, std::memory_order_seq_cst);
// Test that the cmpxchg overload with only one memory order argument
// does not generate any diagnostics.
x.compare_exchange_strong(val1, val2, std::memory_order_release);
}
{
std::atomic_compare_exchange_strong_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_compare_exchange_strong_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_compare_exchange_strong_explicit(&vx, &val1, val2, std::memory_order_seq_cst, std::memory_order_release); // expected-warning {{memory order argument to atomic operation is invalid}}
std::atomic_compare_exchange_strong_explicit(&vx, &val1, val2, std::memory_order_seq_cst, std::memory_order_acq_rel); // expected-warning {{memory order argument to atomic operation is invalid}}
// valid memory orders
std::atomic_compare_exchange_strong_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_relaxed);
std::atomic_compare_exchange_strong_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_consume);
std::atomic_compare_exchange_strong_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_acquire);
std::atomic_compare_exchange_strong_explicit(&x, &val1, val2, std::memory_order_seq_cst, std::memory_order_seq_cst);
}
return 0;
}
| 77.565891 | 202 | 0.722566 | LaudateCorpus1 |
3eb7436ee2e55d950e5d200c517d7b44d8b60767 | 23,471 | cpp | C++ | WebKit/Source/WebCore/platform/graphics/win/FontCacheWin.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 1 | 2019-06-18T06:52:54.000Z | 2019-06-18T06:52:54.000Z | WebKit/Source/WebCore/platform/graphics/win/FontCacheWin.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | WebKit/Source/WebCore/platform/graphics/win/FontCacheWin.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include <winsock2.h>
#include "FontCache.h"
#include "Font.h"
#include "SimpleFontData.h"
#include "UnicodeRange.h"
#include <mlang.h>
#include <windows.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/StringHash.h>
#if USE(CG)
#include <ApplicationServices/ApplicationServices.h>
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#endif
using std::min;
namespace WebCore
{
void FontCache::platformInit()
{
#if USE(CG)
wkSetUpFontCache(1536 * 1024 * 4); // This size matches Mac.
#endif
}
IMLangFontLink2* FontCache::getFontLinkInterface()
{
static IMultiLanguage *multiLanguage;
if (!multiLanguage) {
if (CoCreateInstance(CLSID_CMultiLanguage, 0, CLSCTX_ALL, IID_IMultiLanguage, (void**)&multiLanguage) != S_OK)
return 0;
}
static IMLangFontLink2* langFontLink;
if (!langFontLink) {
if (multiLanguage->QueryInterface(&langFontLink) != S_OK)
return 0;
}
return langFontLink;
}
static int CALLBACK metaFileEnumProc(HDC hdc, HANDLETABLE* table, CONST ENHMETARECORD* record, int tableEntries, LPARAM logFont)
{
if (record->iType == EMR_EXTCREATEFONTINDIRECTW) {
const EMREXTCREATEFONTINDIRECTW* createFontRecord = reinterpret_cast<const EMREXTCREATEFONTINDIRECTW*>(record);
*reinterpret_cast<LOGFONT*>(logFont) = createFontRecord->elfw.elfLogFont;
}
return true;
}
static int CALLBACK linkedFontEnumProc(CONST LOGFONT* logFont, CONST TEXTMETRIC* metrics, DWORD fontType, LPARAM hfont)
{
*reinterpret_cast<HFONT*>(hfont) = CreateFontIndirect(logFont);
return false;
}
static const Vector<String>* getLinkedFonts(String& family)
{
static HashMap<String, Vector<String>*> systemLinkMap;
Vector<String>* result = systemLinkMap.get(family);
if (result)
return result;
result = new Vector<String>;
systemLinkMap.set(family, result);
HKEY fontLinkKey;
if (FAILED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontLink\\SystemLink", 0, KEY_READ, &fontLinkKey)))
return result;
DWORD linkedFontsBufferSize = 0;
RegQueryValueEx(fontLinkKey, family.charactersWithNullTermination(), 0, NULL, NULL, &linkedFontsBufferSize);
WCHAR* linkedFonts = reinterpret_cast<WCHAR*>(malloc(linkedFontsBufferSize));
if (SUCCEEDED(RegQueryValueEx(fontLinkKey, family.charactersWithNullTermination(), 0, NULL, reinterpret_cast<BYTE*>(linkedFonts), &linkedFontsBufferSize))) {
unsigned i = 0;
unsigned length = linkedFontsBufferSize / sizeof(*linkedFonts);
while (i < length) {
while (i < length && linkedFonts[i] != ',')
i++;
i++;
unsigned j = i;
while (j < length && linkedFonts[j])
j++;
result->append(String(linkedFonts + i, j - i));
i = j + 1;
}
}
free(linkedFonts);
RegCloseKey(fontLinkKey);
return result;
}
static const Vector<DWORD, 4>& getCJKCodePageMasks()
{
// The default order in which we look for a font for a CJK character. If the user's default code page is
// one of these, we will use it first.
static const UINT CJKCodePages[] = {
932, /* Japanese */
936, /* Simplified Chinese */
950, /* Traditional Chinese */
949 /* Korean */
};
static Vector<DWORD, 4> codePageMasks;
static bool initialized;
if (!initialized) {
initialized = true;
IMLangFontLink2* langFontLink = fontCache()->getFontLinkInterface();
if (!langFontLink)
return codePageMasks;
UINT defaultCodePage;
DWORD defaultCodePageMask = 0;
if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_RETURN_NUMBER | LOCALE_IDEFAULTANSICODEPAGE, reinterpret_cast<LPWSTR>(&defaultCodePage), sizeof(defaultCodePage)))
langFontLink->CodePageToCodePages(defaultCodePage, &defaultCodePageMask);
if (defaultCodePage == CJKCodePages[0] || defaultCodePage == CJKCodePages[1] || defaultCodePage == CJKCodePages[2] || defaultCodePage == CJKCodePages[3])
codePageMasks.append(defaultCodePageMask);
for (unsigned i = 0; i < 4; ++i) {
if (defaultCodePage != CJKCodePages[i]) {
DWORD codePageMask;
langFontLink->CodePageToCodePages(CJKCodePages[i], &codePageMask);
codePageMasks.append(codePageMask);
}
}
}
return codePageMasks;
}
static bool currentFontContainsCharacter(HDC hdc, UChar character)
{
static Vector<char, 512> glyphsetBuffer;
glyphsetBuffer.resize(GetFontUnicodeRanges(hdc, 0));
GLYPHSET* glyphset = reinterpret_cast<GLYPHSET*>(glyphsetBuffer.data());
GetFontUnicodeRanges(hdc, glyphset);
// FIXME: Change this to a binary search.
unsigned i = 0;
while (i < glyphset->cRanges && glyphset->ranges[i].wcLow <= character)
i++;
return i && glyphset->ranges[i - 1].wcLow + glyphset->ranges[i - 1].cGlyphs > character;
}
static HFONT createMLangFont(IMLangFontLink2* langFontLink, HDC hdc, DWORD codePageMask, UChar character = 0)
{
HFONT MLangFont;
HFONT hfont = 0;
if (SUCCEEDED(langFontLink->MapFont(hdc, codePageMask, character, &MLangFont)) && MLangFont) {
LOGFONT lf;
GetObject(MLangFont, sizeof(LOGFONT), &lf);
langFontLink->ReleaseFont(MLangFont);
hfont = CreateFontIndirect(&lf);
}
return hfont;
}
const SimpleFontData* FontCache::getFontDataForCharacters(const Font& font, const UChar* characters, int length)
{
UChar character = characters[0];
SimpleFontData* fontData = 0;
HDC hdc = GetDC(0);
HFONT primaryFont = font.primaryFont()->fontDataForCharacter(character)->platformData().hfont();
HGDIOBJ oldFont = SelectObject(hdc, primaryFont);
HFONT hfont = 0;
if (IMLangFontLink2* langFontLink = getFontLinkInterface()) {
// Try MLang font linking first.
DWORD codePages = 0;
langFontLink->GetCharCodePages(character, &codePages);
if (codePages && findCharUnicodeRange(character) == cRangeSetCJK) {
// The CJK character may belong to multiple code pages. We want to
// do font linking against a single one of them, preferring the default
// code page for the user's locale.
const Vector<DWORD, 4>& CJKCodePageMasks = getCJKCodePageMasks();
unsigned numCodePages = CJKCodePageMasks.size();
for (unsigned i = 0; i < numCodePages && !hfont; ++i) {
hfont = createMLangFont(langFontLink, hdc, CJKCodePageMasks[i]);
if (hfont && !(codePages & CJKCodePageMasks[i])) {
// We asked about a code page that is not one of the code pages
// returned by MLang, so the font might not contain the character.
SelectObject(hdc, hfont);
if (!currentFontContainsCharacter(hdc, character)) {
DeleteObject(hfont);
hfont = 0;
}
SelectObject(hdc, primaryFont);
}
}
} else
hfont = createMLangFont(langFontLink, hdc, codePages, character);
}
// A font returned from MLang is trusted to contain the character.
bool containsCharacter = hfont;
if (!hfont) {
// To find out what font Uniscribe would use, we make it draw into a metafile and intercept
// calls to CreateFontIndirect().
HDC metaFileDc = CreateEnhMetaFile(hdc, NULL, NULL, NULL);
SelectObject(metaFileDc, primaryFont);
bool scriptStringOutSucceeded = false;
SCRIPT_STRING_ANALYSIS ssa;
// FIXME: If length is greater than 1, we actually return the font for the last character.
// This function should be renamed getFontDataForCharacter and take a single 32-bit character.
if (SUCCEEDED(ScriptStringAnalyse(metaFileDc, characters, length, 0, -1, SSA_METAFILE | SSA_FALLBACK | SSA_GLYPHS | SSA_LINK,
0, NULL, NULL, NULL, NULL, NULL, &ssa))) {
scriptStringOutSucceeded = SUCCEEDED(ScriptStringOut(ssa, 0, 0, 0, NULL, 0, 0, FALSE));
ScriptStringFree(&ssa);
}
HENHMETAFILE metaFile = CloseEnhMetaFile(metaFileDc);
if (scriptStringOutSucceeded) {
LOGFONT logFont;
logFont.lfFaceName[0] = 0;
EnumEnhMetaFile(0, metaFile, metaFileEnumProc, &logFont, NULL);
if (logFont.lfFaceName[0])
hfont = CreateFontIndirect(&logFont);
}
DeleteEnhMetaFile(metaFile);
}
String familyName;
const Vector<String>* linkedFonts = 0;
unsigned linkedFontIndex = 0;
while (hfont) {
SelectObject(hdc, hfont);
WCHAR name[LF_FACESIZE];
GetTextFace(hdc, LF_FACESIZE, name);
familyName = name;
if (containsCharacter || currentFontContainsCharacter(hdc, character))
break;
if (!linkedFonts)
linkedFonts = getLinkedFonts(familyName);
SelectObject(hdc, oldFont);
DeleteObject(hfont);
hfont = 0;
if (linkedFonts->size() <= linkedFontIndex)
break;
LOGFONT logFont;
logFont.lfCharSet = DEFAULT_CHARSET;
memcpy(logFont.lfFaceName, linkedFonts->at(linkedFontIndex).characters(), linkedFonts->at(linkedFontIndex).length() * sizeof(WCHAR));
logFont.lfFaceName[linkedFonts->at(linkedFontIndex).length()] = 0;
EnumFontFamiliesEx(hdc, &logFont, linkedFontEnumProc, reinterpret_cast<LPARAM>(&hfont), 0);
linkedFontIndex++;
}
if (hfont) {
if (!familyName.isEmpty()) {
FontPlatformData* result = getCachedFontPlatformData(font.fontDescription(), familyName);
if (result)
fontData = getCachedFontData(result, DoNotRetain);
}
SelectObject(hdc, oldFont);
DeleteObject(hfont);
}
ReleaseDC(0, hdc);
return fontData;
}
SimpleFontData* FontCache::getSimilarFontPlatformData(const Font& font)
{
return 0;
}
SimpleFontData* FontCache::fontDataFromDescriptionAndLogFont(const FontDescription& fontDescription, ShouldRetain shouldRetain, const LOGFONT& font, AtomicString& outFontFamilyName)
{
AtomicString familyName = String(font.lfFaceName, wcsnlen(font.lfFaceName, LF_FACESIZE));
SimpleFontData* fontData = getCachedFontData(fontDescription, familyName, false, shouldRetain);
if (fontData)
outFontFamilyName = familyName;
return fontData;
}
SimpleFontData* FontCache::getLastResortFallbackFont(const FontDescription& fontDescription, ShouldRetain shouldRetain)
{
DEFINE_STATIC_LOCAL(AtomicString, fallbackFontName, ());
if (!fallbackFontName.isEmpty())
return getCachedFontData(fontDescription, fallbackFontName, false, shouldRetain);
// FIXME: Would be even better to somehow get the user's default font here. For now we'll pick
// the default that the user would get without changing any prefs.
// Search all typical Windows-installed full Unicode fonts.
// Sorted by most to least glyphs according to http://en.wikipedia.org/wiki/Unicode_typefaces
// Start with Times New Roman also since it is the default if the user doesn't change prefs.
static AtomicString fallbackFonts[] = {
AtomicString("Times New Roman"),
AtomicString("Microsoft Sans Serif"),
AtomicString("Tahoma"),
AtomicString("Lucida Sans Unicode"),
AtomicString("Arial")
};
SimpleFontData* simpleFont;
for (size_t i = 0; i < WTF_ARRAY_LENGTH(fallbackFonts); ++i) {
if (simpleFont = getCachedFontData(fontDescription, fallbackFonts[i]), false, shouldRetain) {
fallbackFontName = fallbackFonts[i];
return simpleFont;
}
}
// Fall back to the DEFAULT_GUI_FONT if no known Unicode fonts are available.
if (HFONT defaultGUIFont = static_cast<HFONT>(GetStockObject(DEFAULT_GUI_FONT))) {
LOGFONT defaultGUILogFont;
GetObject(defaultGUIFont, sizeof(defaultGUILogFont), &defaultGUILogFont);
if (simpleFont = fontDataFromDescriptionAndLogFont(fontDescription, shouldRetain, defaultGUILogFont, fallbackFontName))
return simpleFont;
}
// Fall back to Non-client metrics fonts.
NONCLIENTMETRICS nonClientMetrics = {0};
nonClientMetrics.cbSize = sizeof(nonClientMetrics);
if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(nonClientMetrics), &nonClientMetrics, 0)) {
if (simpleFont = fontDataFromDescriptionAndLogFont(fontDescription, shouldRetain, nonClientMetrics.lfMessageFont, fallbackFontName))
return simpleFont;
if (simpleFont = fontDataFromDescriptionAndLogFont(fontDescription, shouldRetain, nonClientMetrics.lfMenuFont, fallbackFontName))
return simpleFont;
if (simpleFont = fontDataFromDescriptionAndLogFont(fontDescription, shouldRetain, nonClientMetrics.lfStatusFont, fallbackFontName))
return simpleFont;
if (simpleFont = fontDataFromDescriptionAndLogFont(fontDescription, shouldRetain, nonClientMetrics.lfCaptionFont, fallbackFontName))
return simpleFont;
if (simpleFont = fontDataFromDescriptionAndLogFont(fontDescription, shouldRetain, nonClientMetrics.lfSmCaptionFont, fallbackFontName))
return simpleFont;
}
ASSERT_NOT_REACHED();
return 0;
}
static LONG toGDIFontWeight(FontWeight fontWeight)
{
static LONG gdiFontWeights[] = {
FW_THIN, // FontWeight100
FW_EXTRALIGHT, // FontWeight200
FW_LIGHT, // FontWeight300
FW_NORMAL, // FontWeight400
FW_MEDIUM, // FontWeight500
FW_SEMIBOLD, // FontWeight600
FW_BOLD, // FontWeight700
FW_EXTRABOLD, // FontWeight800
FW_HEAVY // FontWeight900
};
return gdiFontWeights[fontWeight];
}
static inline bool isGDIFontWeightBold(LONG gdiFontWeight)
{
return gdiFontWeight >= FW_SEMIBOLD;
}
static LONG adjustedGDIFontWeight(LONG gdiFontWeight, const String& family)
{
static AtomicString lucidaStr("Lucida Grande");
if (equalIgnoringCase(family, lucidaStr)) {
if (gdiFontWeight == FW_NORMAL)
return FW_MEDIUM;
if (gdiFontWeight == FW_BOLD)
return FW_SEMIBOLD;
}
return gdiFontWeight;
}
struct MatchImprovingProcData {
MatchImprovingProcData(LONG desiredWeight, bool desiredItalic)
: m_desiredWeight(desiredWeight)
, m_desiredItalic(desiredItalic)
, m_hasMatched(false)
{
}
LONG m_desiredWeight;
bool m_desiredItalic;
bool m_hasMatched;
LOGFONT m_chosen;
};
static int CALLBACK matchImprovingEnumProc(CONST LOGFONT* candidate, CONST TEXTMETRIC* metrics, DWORD fontType, LPARAM lParam)
{
MatchImprovingProcData* matchData = reinterpret_cast<MatchImprovingProcData*>(lParam);
if (!matchData->m_hasMatched) {
matchData->m_hasMatched = true;
matchData->m_chosen = *candidate;
return 1;
}
if (!candidate->lfItalic != !matchData->m_chosen.lfItalic) {
if (!candidate->lfItalic == !matchData->m_desiredItalic)
matchData->m_chosen = *candidate;
return 1;
}
unsigned chosenWeightDeltaMagnitude = abs(matchData->m_chosen.lfWeight - matchData->m_desiredWeight);
unsigned candidateWeightDeltaMagnitude = abs(candidate->lfWeight - matchData->m_desiredWeight);
// If both are the same distance from the desired weight, prefer the candidate if it is further from regular.
if (chosenWeightDeltaMagnitude == candidateWeightDeltaMagnitude && abs(candidate->lfWeight - FW_NORMAL) > abs(matchData->m_chosen.lfWeight - FW_NORMAL)) {
matchData->m_chosen = *candidate;
return 1;
}
// Otherwise, prefer the one closer to the desired weight.
if (candidateWeightDeltaMagnitude < chosenWeightDeltaMagnitude)
matchData->m_chosen = *candidate;
return 1;
}
static HFONT createGDIFont(const AtomicString& family, LONG desiredWeight, bool desiredItalic, int size, bool synthesizeItalic)
{
HDC hdc = GetDC(0);
LOGFONT logFont;
logFont.lfCharSet = DEFAULT_CHARSET;
unsigned familyLength = min(family.length(), static_cast<unsigned>(LF_FACESIZE - 1));
memcpy(logFont.lfFaceName, family.characters(), familyLength * sizeof(UChar));
logFont.lfFaceName[familyLength] = 0;
logFont.lfPitchAndFamily = 0;
MatchImprovingProcData matchData(desiredWeight, desiredItalic);
EnumFontFamiliesEx(hdc, &logFont, matchImprovingEnumProc, reinterpret_cast<LPARAM>(&matchData), 0);
ReleaseDC(0, hdc);
if (!matchData.m_hasMatched)
return 0;
matchData.m_chosen.lfHeight = -size;
matchData.m_chosen.lfWidth = 0;
matchData.m_chosen.lfEscapement = 0;
matchData.m_chosen.lfOrientation = 0;
matchData.m_chosen.lfUnderline = false;
matchData.m_chosen.lfStrikeOut = false;
matchData.m_chosen.lfCharSet = DEFAULT_CHARSET;
#if USE(CG) || USE(CAIRO)
matchData.m_chosen.lfOutPrecision = OUT_TT_ONLY_PRECIS;
#else
matchData.m_chosen.lfOutPrecision = OUT_TT_PRECIS;
#endif
matchData.m_chosen.lfQuality = DEFAULT_QUALITY;
matchData.m_chosen.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
if (desiredItalic && !matchData.m_chosen.lfItalic && synthesizeItalic)
matchData.m_chosen.lfItalic = 1;
HFONT result = CreateFontIndirect(&matchData.m_chosen);
if (!result)
return 0;
HDC dc = GetDC(0);
SaveDC(dc);
SelectObject(dc, result);
WCHAR actualName[LF_FACESIZE];
GetTextFace(dc, LF_FACESIZE, actualName);
RestoreDC(dc, -1);
ReleaseDC(0, dc);
if (wcsicmp(matchData.m_chosen.lfFaceName, actualName)) {
DeleteObject(result);
result = 0;
}
return result;
}
struct TraitsInFamilyProcData {
TraitsInFamilyProcData(const AtomicString& familyName)
: m_familyName(familyName)
{
}
const AtomicString& m_familyName;
HashSet<unsigned> m_traitsMasks;
};
static int CALLBACK traitsInFamilyEnumProc(CONST LOGFONT* logFont, CONST TEXTMETRIC* metrics, DWORD fontType, LPARAM lParam)
{
TraitsInFamilyProcData* procData = reinterpret_cast<TraitsInFamilyProcData*>(lParam);
unsigned traitsMask = 0;
traitsMask |= logFont->lfItalic ? FontStyleItalicMask : FontStyleNormalMask;
traitsMask |= FontVariantNormalMask;
LONG weight = adjustedGDIFontWeight(logFont->lfWeight, procData->m_familyName);
traitsMask |= weight == FW_THIN ? FontWeight100Mask :
weight == FW_EXTRALIGHT ? FontWeight200Mask :
weight == FW_LIGHT ? FontWeight300Mask :
weight == FW_NORMAL ? FontWeight400Mask :
weight == FW_MEDIUM ? FontWeight500Mask :
weight == FW_SEMIBOLD ? FontWeight600Mask :
weight == FW_BOLD ? FontWeight700Mask :
weight == FW_EXTRABOLD ? FontWeight800Mask :
FontWeight900Mask;
procData->m_traitsMasks.add(traitsMask);
return 1;
}
void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
{
HDC hdc = GetDC(0);
LOGFONT logFont;
logFont.lfCharSet = DEFAULT_CHARSET;
unsigned familyLength = min(familyName.length(), static_cast<unsigned>(LF_FACESIZE - 1));
memcpy(logFont.lfFaceName, familyName.characters(), familyLength * sizeof(UChar));
logFont.lfFaceName[familyLength] = 0;
logFont.lfPitchAndFamily = 0;
TraitsInFamilyProcData procData(familyName);
EnumFontFamiliesEx(hdc, &logFont, traitsInFamilyEnumProc, reinterpret_cast<LPARAM>(&procData), 0);
copyToVector(procData.m_traitsMasks, traitsMasks);
ReleaseDC(0, hdc);
}
FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
{
bool isLucidaGrande = false;
static AtomicString lucidaStr("Lucida Grande");
if (equalIgnoringCase(family, lucidaStr))
isLucidaGrande = true;
bool useGDI = fontDescription.renderingMode() == AlternateRenderingMode && !isLucidaGrande;
// The logical size constant is 32. We do this for subpixel precision when rendering using Uniscribe.
// This masks rounding errors related to the HFONT metrics being different from the CGFont metrics.
// FIXME: We will eventually want subpixel precision for GDI mode, but the scaled rendering doesn't
// look as nice. That may be solvable though.
LONG weight = adjustedGDIFontWeight(toGDIFontWeight(fontDescription.weight()), family);
HFONT hfont = createGDIFont(family, weight, fontDescription.italic(),
fontDescription.computedPixelSize() * (useGDI ? 1 : 32), useGDI);
if (!hfont)
return 0;
if (isLucidaGrande)
useGDI = false; // Never use GDI for Lucida Grande.
LOGFONT logFont;
GetObject(hfont, sizeof(LOGFONT), &logFont);
bool synthesizeBold = isGDIFontWeightBold(weight) && !isGDIFontWeightBold(logFont.lfWeight);
bool synthesizeItalic = fontDescription.italic() && !logFont.lfItalic;
FontPlatformData* result = new FontPlatformData(hfont, fontDescription.computedPixelSize(), synthesizeBold, synthesizeItalic, useGDI);
#if USE(CG)
bool fontCreationFailed = !result->cgFont();
#elif USE(CAIRO)
bool fontCreationFailed = !result->scaledFont();
#endif
if (fontCreationFailed) {
// The creation of the CGFontRef failed for some reason. We already asserted in debug builds, but to make
// absolutely sure that we don't use this font, go ahead and return 0 so that we can fall back to the next
// font.
delete result;
DeleteObject(hfont);
return 0;
}
return result;
}
}
| 38.859272 | 181 | 0.688637 | JavaScriptTesting |
3ebb3209daa32a16689d01384a068c4e7484827e | 62,085 | cpp | C++ | src/js/vm/Stack.cpp | fengjixuchui/blazefox | d5c732ac7305a79fe20704c2d134c130f14eca83 | [
"MIT"
] | 149 | 2018-12-23T09:08:00.000Z | 2022-02-02T09:18:38.000Z | src/js/vm/Stack.cpp | fengjixuchui/blazefox | d5c732ac7305a79fe20704c2d134c130f14eca83 | [
"MIT"
] | null | null | null | src/js/vm/Stack.cpp | fengjixuchui/blazefox | d5c732ac7305a79fe20704c2d134c130f14eca83 | [
"MIT"
] | 56 | 2018-12-23T18:11:40.000Z | 2021-11-30T13:18:17.000Z | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "vm/Stack-inl.h"
#include <utility>
#include "gc/Marking.h"
#include "jit/BaselineFrame.h"
#include "jit/JitcodeMap.h"
#include "jit/JitRealm.h"
#include "jit/shared/CodeGenerator-shared.h"
#include "vm/Debugger.h"
#include "vm/JSContext.h"
#include "vm/Opcodes.h"
#include "jit/JSJitFrameIter-inl.h"
#include "vm/Compartment-inl.h"
#include "vm/EnvironmentObject-inl.h"
#include "vm/Interpreter-inl.h"
#include "vm/Probes-inl.h"
using namespace js;
using mozilla::ArrayLength;
using mozilla::DebugOnly;
using mozilla::Maybe;
/*****************************************************************************/
void
InterpreterFrame::initExecuteFrame(JSContext* cx, HandleScript script,
AbstractFramePtr evalInFramePrev,
const Value& newTargetValue, HandleObject envChain)
{
flags_ = 0;
script_ = script;
// newTarget = NullValue is an initial sentinel for "please fill me in from the stack".
// It should never be passed from Ion code.
RootedValue newTarget(cx, newTargetValue);
if (script->isDirectEvalInFunction()) {
FrameIter iter(cx);
if (newTarget.isNull() &&
iter.hasScript() &&
iter.script()->bodyScope()->hasOnChain(ScopeKind::Function))
{
newTarget = iter.newTarget();
}
} else if (evalInFramePrev) {
if (newTarget.isNull() &&
evalInFramePrev.hasScript() &&
evalInFramePrev.script()->bodyScope()->hasOnChain(ScopeKind::Function))
{
newTarget = evalInFramePrev.newTarget();
}
}
Value* dstvp = (Value*)this - 1;
dstvp[0] = newTarget;
envChain_ = envChain.get();
prev_ = nullptr;
prevpc_ = nullptr;
prevsp_ = nullptr;
evalInFramePrev_ = evalInFramePrev;
MOZ_ASSERT_IF(evalInFramePrev, isDebuggerEvalFrame());
if (script->isDebuggee()) {
setIsDebuggee();
}
#ifdef DEBUG
Debug_SetValueRangeToCrashOnTouch(&rval_, 1);
#endif
}
bool
InterpreterFrame::isNonGlobalEvalFrame() const
{
return isEvalFrame() && script()->bodyScope()->as<EvalScope>().isNonGlobal();
}
ArrayObject*
InterpreterFrame::createRestParameter(JSContext* cx)
{
MOZ_ASSERT(script()->hasRest());
unsigned nformal = callee().nargs() - 1, nactual = numActualArgs();
unsigned nrest = (nactual > nformal) ? nactual - nformal : 0;
Value* restvp = argv() + nformal;
return ObjectGroup::newArrayObject(cx, restvp, nrest, GenericObject,
ObjectGroup::NewArrayKind::UnknownIndex);
}
static inline void
AssertScopeMatchesEnvironment(Scope* scope, JSObject* originalEnv)
{
#ifdef DEBUG
JSObject* env = originalEnv;
for (ScopeIter si(scope); si; si++) {
if (si.kind() == ScopeKind::NonSyntactic) {
while (env->is<WithEnvironmentObject>() ||
env->is<NonSyntacticVariablesObject>() ||
(env->is<LexicalEnvironmentObject>() &&
!env->as<LexicalEnvironmentObject>().isSyntactic()))
{
MOZ_ASSERT(!IsSyntacticEnvironment(env));
env = &env->as<EnvironmentObject>().enclosingEnvironment();
}
} else if (si.hasSyntacticEnvironment()) {
switch (si.kind()) {
case ScopeKind::Function:
MOZ_ASSERT(env->as<CallObject>().callee().existingScriptNonDelazifying() ==
si.scope()->as<FunctionScope>().script());
env = &env->as<CallObject>().enclosingEnvironment();
break;
case ScopeKind::FunctionBodyVar:
case ScopeKind::ParameterExpressionVar:
MOZ_ASSERT(&env->as<VarEnvironmentObject>().scope() == si.scope());
env = &env->as<VarEnvironmentObject>().enclosingEnvironment();
break;
case ScopeKind::Lexical:
case ScopeKind::SimpleCatch:
case ScopeKind::Catch:
case ScopeKind::NamedLambda:
case ScopeKind::StrictNamedLambda:
MOZ_ASSERT(&env->as<LexicalEnvironmentObject>().scope() == si.scope());
env = &env->as<LexicalEnvironmentObject>().enclosingEnvironment();
break;
case ScopeKind::With:
MOZ_ASSERT(&env->as<WithEnvironmentObject>().scope() == si.scope());
env = &env->as<WithEnvironmentObject>().enclosingEnvironment();
break;
case ScopeKind::Eval:
case ScopeKind::StrictEval:
env = &env->as<VarEnvironmentObject>().enclosingEnvironment();
break;
case ScopeKind::Global:
MOZ_ASSERT(env->as<LexicalEnvironmentObject>().isGlobal());
env = &env->as<LexicalEnvironmentObject>().enclosingEnvironment();
MOZ_ASSERT(env->is<GlobalObject>());
break;
case ScopeKind::NonSyntactic:
MOZ_CRASH("NonSyntactic should not have a syntactic environment");
break;
case ScopeKind::Module: {
ModuleObject* module = &env->as<ModuleEnvironmentObject>().module();
MOZ_ASSERT_IF(module->maybeScript(),
module->script() == si.scope()->as<ModuleScope>().script());
env = &env->as<ModuleEnvironmentObject>().enclosingEnvironment();
break;
}
case ScopeKind::WasmInstance:
env = &env->as<WasmInstanceEnvironmentObject>().enclosingEnvironment();
break;
case ScopeKind::WasmFunction:
env = &env->as<WasmFunctionCallObject>().enclosingEnvironment();
break;
}
}
}
// In the case of a non-syntactic env chain, the immediate parent of the
// outermost non-syntactic env may be the global lexical env, or, if
// called from Debugger, a DebugEnvironmentProxy.
//
// In the case of a syntactic env chain, the outermost env is always a
// GlobalObject.
MOZ_ASSERT(env->is<GlobalObject>() || IsGlobalLexicalEnvironment(env) ||
env->is<DebugEnvironmentProxy>());
#endif
}
static inline void
AssertScopeMatchesEnvironment(InterpreterFrame* fp, jsbytecode* pc)
{
#ifdef DEBUG
// If we OOMed before fully initializing the environment chain, the scope
// and environment will definitely mismatch.
if (fp->script()->initialEnvironmentShape() && fp->hasInitialEnvironment()) {
AssertScopeMatchesEnvironment(fp->script()->innermostScope(pc), fp->environmentChain());
}
#endif
}
bool
InterpreterFrame::initFunctionEnvironmentObjects(JSContext* cx)
{
return js::InitFunctionEnvironmentObjects(cx, this);
}
bool
InterpreterFrame::prologue(JSContext* cx)
{
RootedScript script(cx, this->script());
MOZ_ASSERT(cx->interpreterRegs().pc == script->code());
MOZ_ASSERT(cx->realm() == script->realm());
if (isEvalFrame()) {
if (!script->bodyScope()->hasEnvironment()) {
MOZ_ASSERT(!script->strict());
// Non-strict eval may introduce var bindings that conflict with
// lexical bindings in an enclosing lexical scope.
RootedObject varObjRoot(cx, &varObj());
if (!CheckEvalDeclarationConflicts(cx, script, environmentChain(), varObjRoot)) {
return false;
}
}
return probes::EnterScript(cx, script, nullptr, this);
}
if (isGlobalFrame()) {
Rooted<LexicalEnvironmentObject*> lexicalEnv(cx);
RootedObject varObjRoot(cx);
if (script->hasNonSyntacticScope()) {
lexicalEnv = &extensibleLexicalEnvironment();
varObjRoot = &varObj();
} else {
lexicalEnv = &cx->global()->lexicalEnvironment();
varObjRoot = cx->global();
}
if (!CheckGlobalDeclarationConflicts(cx, script, lexicalEnv, varObjRoot)) {
// Treat this as a script entry, for consistency with Ion.
if (script->trackRecordReplayProgress()) {
mozilla::recordreplay::AdvanceExecutionProgressCounter();
}
return false;
}
return probes::EnterScript(cx, script, nullptr, this);
}
if (isModuleFrame()) {
return probes::EnterScript(cx, script, nullptr, this);
}
// At this point, we've yet to push any environments. Check that they
// match the enclosing scope.
AssertScopeMatchesEnvironment(script->enclosingScope(), environmentChain());
MOZ_ASSERT(isFunctionFrame());
if (callee().needsFunctionEnvironmentObjects() && !initFunctionEnvironmentObjects(cx)) {
return false;
}
MOZ_ASSERT_IF(isConstructing(),
thisArgument().isObject() || thisArgument().isMagic(JS_UNINITIALIZED_LEXICAL));
return probes::EnterScript(cx, script, script->functionNonDelazifying(), this);
}
void
InterpreterFrame::epilogue(JSContext* cx, jsbytecode* pc)
{
RootedScript script(cx, this->script());
MOZ_ASSERT(cx->realm() == script->realm());
probes::ExitScript(cx, script, script->functionNonDelazifying(), hasPushedGeckoProfilerFrame());
// Check that the scope matches the environment at the point of leaving
// the frame.
AssertScopeMatchesEnvironment(this, pc);
EnvironmentIter ei(cx, this, pc);
UnwindAllEnvironmentsInFrame(cx, ei);
if (isFunctionFrame()) {
if (!callee().isGenerator() &&
!callee().isAsync() &&
isConstructing() &&
thisArgument().isObject() &&
returnValue().isPrimitive())
{
setReturnValue(thisArgument());
}
return;
}
MOZ_ASSERT(isEvalFrame() || isGlobalFrame() || isModuleFrame());
}
bool
InterpreterFrame::checkReturn(JSContext* cx, HandleValue thisv)
{
MOZ_ASSERT(script()->isDerivedClassConstructor());
MOZ_ASSERT(isFunctionFrame());
MOZ_ASSERT(callee().isClassConstructor());
HandleValue retVal = returnValue();
if (retVal.isObject()) {
return true;
}
if (!retVal.isUndefined()) {
ReportValueError(cx, JSMSG_BAD_DERIVED_RETURN, JSDVG_IGNORE_STACK, retVal, nullptr);
return false;
}
if (thisv.isMagic(JS_UNINITIALIZED_LEXICAL)) {
return ThrowUninitializedThis(cx, this);
}
setReturnValue(thisv);
return true;
}
bool
InterpreterFrame::pushVarEnvironment(JSContext* cx, HandleScope scope)
{
return js::PushVarEnvironmentObject(cx, scope, this);
}
bool
InterpreterFrame::pushLexicalEnvironment(JSContext* cx, Handle<LexicalScope*> scope)
{
LexicalEnvironmentObject* env = LexicalEnvironmentObject::create(cx, scope, this);
if (!env) {
return false;
}
pushOnEnvironmentChain(*env);
return true;
}
bool
InterpreterFrame::freshenLexicalEnvironment(JSContext* cx)
{
Rooted<LexicalEnvironmentObject*> env(cx, &envChain_->as<LexicalEnvironmentObject>());
LexicalEnvironmentObject* fresh = LexicalEnvironmentObject::clone(cx, env);
if (!fresh) {
return false;
}
replaceInnermostEnvironment(*fresh);
return true;
}
bool
InterpreterFrame::recreateLexicalEnvironment(JSContext* cx)
{
Rooted<LexicalEnvironmentObject*> env(cx, &envChain_->as<LexicalEnvironmentObject>());
LexicalEnvironmentObject* fresh = LexicalEnvironmentObject::recreate(cx, env);
if (!fresh) {
return false;
}
replaceInnermostEnvironment(*fresh);
return true;
}
void
InterpreterFrame::trace(JSTracer* trc, Value* sp, jsbytecode* pc)
{
TraceRoot(trc, &envChain_, "env chain");
TraceRoot(trc, &script_, "script");
if (flags_ & HAS_ARGS_OBJ) {
TraceRoot(trc, &argsObj_, "arguments");
}
if (hasReturnValue()) {
TraceRoot(trc, &rval_, "rval");
}
MOZ_ASSERT(sp >= slots());
if (hasArgs()) {
// Trace the callee and |this|. When we're doing a moving GC, we
// need to fix up the callee pointer before we use it below, under
// numFormalArgs() and script().
TraceRootRange(trc, 2, argv_ - 2, "fp callee and this");
// Trace arguments.
unsigned argc = Max(numActualArgs(), numFormalArgs());
TraceRootRange(trc, argc + isConstructing(), argv_, "fp argv");
} else {
// Trace newTarget.
TraceRoot(trc, ((Value*)this) - 1, "stack newTarget");
}
JSScript* script = this->script();
size_t nfixed = script->nfixed();
size_t nlivefixed = script->calculateLiveFixed(pc);
if (nfixed == nlivefixed) {
// All locals are live.
traceValues(trc, 0, sp - slots());
} else {
// Trace operand stack.
traceValues(trc, nfixed, sp - slots());
// Clear dead block-scoped locals.
while (nfixed > nlivefixed) {
unaliasedLocal(--nfixed).setUndefined();
}
// Trace live locals.
traceValues(trc, 0, nlivefixed);
}
if (auto* debugEnvs = script->realm()->debugEnvs()) {
debugEnvs->traceLiveFrame(trc, this);
}
}
void
InterpreterFrame::traceValues(JSTracer* trc, unsigned start, unsigned end)
{
if (start < end) {
TraceRootRange(trc, end - start, slots() + start, "vm_stack");
}
}
static void
TraceInterpreterActivation(JSTracer* trc, InterpreterActivation* act)
{
for (InterpreterFrameIterator frames(act); !frames.done(); ++frames) {
InterpreterFrame* fp = frames.frame();
fp->trace(trc, frames.sp(), frames.pc());
}
}
void
js::TraceInterpreterActivations(JSContext* cx, JSTracer* trc)
{
for (ActivationIterator iter(cx); !iter.done(); ++iter) {
Activation* act = iter.activation();
if (act->isInterpreter()) {
TraceInterpreterActivation(trc, act->asInterpreter());
}
}
}
/*****************************************************************************/
// Unlike the other methods of this class, this method is defined here so that
// we don't have to #include jsautooplen.h in vm/Stack.h.
void
InterpreterRegs::setToEndOfScript()
{
sp = fp()->base();
}
/*****************************************************************************/
InterpreterFrame*
InterpreterStack::pushInvokeFrame(JSContext* cx, const CallArgs& args, MaybeConstruct constructing)
{
LifoAlloc::Mark mark = allocator_.mark();
RootedFunction fun(cx, &args.callee().as<JSFunction>());
RootedScript script(cx, fun->nonLazyScript());
Value* argv;
InterpreterFrame* fp = getCallFrame(cx, args, script, constructing, &argv);
if (!fp) {
return nullptr;
}
fp->mark_ = mark;
fp->initCallFrame(nullptr, nullptr, nullptr, *fun, script, argv, args.length(),
constructing);
return fp;
}
InterpreterFrame*
InterpreterStack::pushExecuteFrame(JSContext* cx, HandleScript script, const Value& newTargetValue,
HandleObject envChain, AbstractFramePtr evalInFrame)
{
LifoAlloc::Mark mark = allocator_.mark();
unsigned nvars = 1 /* newTarget */ + script->nslots();
uint8_t* buffer = allocateFrame(cx, sizeof(InterpreterFrame) + nvars * sizeof(Value));
if (!buffer) {
return nullptr;
}
InterpreterFrame* fp = reinterpret_cast<InterpreterFrame*>(buffer + 1 * sizeof(Value));
fp->mark_ = mark;
fp->initExecuteFrame(cx, script, evalInFrame, newTargetValue, envChain);
fp->initLocals();
return fp;
}
/*****************************************************************************/
JitFrameIter::JitFrameIter(const JitFrameIter& another)
{
*this = another;
}
JitFrameIter&
JitFrameIter::operator=(const JitFrameIter& another)
{
MOZ_ASSERT(this != &another);
act_ = another.act_;
mustUnwindActivation_ = another.mustUnwindActivation_;
if (isSome()) {
iter_.destroy();
}
if (!another.isSome()) {
return *this;
}
if (another.isJSJit()) {
iter_.construct<jit::JSJitFrameIter>(another.asJSJit());
} else {
MOZ_ASSERT(another.isWasm());
iter_.construct<wasm::WasmFrameIter>(another.asWasm());
}
return *this;
}
JitFrameIter::JitFrameIter(jit::JitActivation* act, bool mustUnwindActivation)
{
act_ = act;
mustUnwindActivation_ = mustUnwindActivation;
MOZ_ASSERT(act->hasExitFP(), "packedExitFP is used to determine if JSJit or wasm");
if (act->hasJSExitFP()) {
iter_.construct<jit::JSJitFrameIter>(act);
} else {
MOZ_ASSERT(act->hasWasmExitFP());
iter_.construct<wasm::WasmFrameIter>(act);
}
settle();
}
void
JitFrameIter::skipNonScriptedJSFrames()
{
if (isJSJit()) {
// Stop at the first scripted frame.
jit::JSJitFrameIter& frames = asJSJit();
while (!frames.isScripted() && !frames.done()) {
++frames;
}
settle();
}
}
bool
JitFrameIter::isSelfHostedIgnoringInlining() const
{
MOZ_ASSERT(!done());
if (isWasm()) {
return false;
}
return asJSJit().script()->selfHosted();
}
JS::Realm*
JitFrameIter::realm() const
{
MOZ_ASSERT(!done());
if (isWasm()) {
return asWasm().instance()->realm();
}
return asJSJit().script()->realm();
}
bool
JitFrameIter::done() const
{
if (!isSome()) {
return true;
}
if (isJSJit()) {
return asJSJit().done();
}
if (isWasm()) {
return asWasm().done();
}
MOZ_CRASH("unhandled case");
}
void
JitFrameIter::settle()
{
if (isJSJit()) {
const jit::JSJitFrameIter& jitFrame = asJSJit();
if (jitFrame.type() != jit::FrameType::WasmToJSJit) {
return;
}
// Transition from js jit frames to wasm frames: we're on the
// wasm-to-jit fast path. The current stack layout is as follows:
// (stack grows downward)
//
// [--------------------]
// [WASM FUNC ]
// [WASM JIT EXIT FRAME ]
// [JIT WASM ENTRY FRAME] <-- we're here.
//
// So prevFP points to the wasm jit exit FP, maintaing the invariant in
// WasmFrameIter that the first frame is an exit frame and can be
// popped.
wasm::Frame* prevFP = (wasm::Frame*) jitFrame.prevFp();
if (mustUnwindActivation_) {
act_->setWasmExitFP(prevFP);
}
iter_.destroy();
iter_.construct<wasm::WasmFrameIter>(act_, prevFP);
MOZ_ASSERT(!asWasm().done());
return;
}
if (isWasm()) {
const wasm::WasmFrameIter& wasmFrame = asWasm();
if (!wasmFrame.unwoundIonCallerFP()) {
return;
}
// Transition from wasm frames to jit frames: we're on the
// jit-to-wasm fast path. The current stack layout is as follows:
// (stack grows downward)
//
// [--------------------]
// [JIT FRAME ]
// [WASM JIT ENTRY FRAME] <-- we're here
//
// The wasm iterator has saved the previous jit frame pointer for us.
MOZ_ASSERT(wasmFrame.done());
uint8_t* prevFP = wasmFrame.unwoundIonCallerFP();
jit::FrameType prevFrameType = wasmFrame.unwoundIonFrameType();
if (mustUnwindActivation_) {
act_->setJSExitFP(prevFP);
}
iter_.destroy();
iter_.construct<jit::JSJitFrameIter>(act_, prevFrameType, prevFP);
MOZ_ASSERT(!asJSJit().done());
return;
}
}
void
JitFrameIter::operator++()
{
MOZ_ASSERT(isSome());
if (isJSJit()) {
const jit::JSJitFrameIter& jitFrame = asJSJit();
jit::JitFrameLayout* prevFrame = nullptr;
if (mustUnwindActivation_ && jitFrame.isScripted()) {
prevFrame = jitFrame.jsFrame();
}
++asJSJit();
if (prevFrame) {
// Unwind the frame by updating packedExitFP. This is necessary
// so that (1) debugger exception unwind and leave frame hooks
// don't see this frame when they use ScriptFrameIter, and (2)
// ScriptFrameIter does not crash when accessing an IonScript
// that's destroyed by the ionScript->decref call.
EnsureBareExitFrame(act_, prevFrame);
}
} else if (isWasm()) {
++asWasm();
} else {
MOZ_CRASH("unhandled case");
}
settle();
}
OnlyJSJitFrameIter::OnlyJSJitFrameIter(jit::JitActivation* act)
: JitFrameIter(act)
{
settle();
}
OnlyJSJitFrameIter::OnlyJSJitFrameIter(JSContext* cx)
: OnlyJSJitFrameIter(cx->activation()->asJit())
{
}
OnlyJSJitFrameIter::OnlyJSJitFrameIter(const ActivationIterator& iter)
: OnlyJSJitFrameIter(iter->asJit())
{
}
/*****************************************************************************/
void
FrameIter::popActivation()
{
++data_.activations_;
settleOnActivation();
}
bool
FrameIter::principalsSubsumeFrame() const
{
// If the caller supplied principals, only show frames which are
// subsumed (of the same origin or of an origin accessible) by these
// principals.
MOZ_ASSERT(!done());
if (!data_.principals_) {
return true;
}
JSSubsumesOp subsumes = data_.cx_->runtime()->securityCallbacks->subsumes;
if (!subsumes) {
return true;
}
return subsumes(data_.principals_, realm()->principals());
}
void
FrameIter::popInterpreterFrame()
{
MOZ_ASSERT(data_.state_ == INTERP);
++data_.interpFrames_;
if (data_.interpFrames_.done()) {
popActivation();
} else {
data_.pc_ = data_.interpFrames_.pc();
}
}
void
FrameIter::settleOnActivation()
{
MOZ_ASSERT(!data_.cx_->inUnsafeCallWithABI);
while (true) {
if (data_.activations_.done()) {
data_.state_ = DONE;
return;
}
Activation* activation = data_.activations_.activation();
if (activation->isJit()) {
data_.jitFrames_ = JitFrameIter(activation->asJit());
data_.jitFrames_.skipNonScriptedJSFrames();
if (data_.jitFrames_.done()) {
// It's possible to have an JitActivation with no scripted
// frames, for instance if we hit an over-recursion during
// bailout.
++data_.activations_;
continue;
}
data_.state_ = JIT;
nextJitFrame();
return;
}
MOZ_ASSERT(activation->isInterpreter());
InterpreterActivation* interpAct = activation->asInterpreter();
data_.interpFrames_ = InterpreterFrameIterator(interpAct);
// If we OSR'ed into JIT code, skip the interpreter frame so that
// the same frame is not reported twice.
if (data_.interpFrames_.frame()->runningInJit()) {
++data_.interpFrames_;
if (data_.interpFrames_.done()) {
++data_.activations_;
continue;
}
}
MOZ_ASSERT(!data_.interpFrames_.frame()->runningInJit());
data_.pc_ = data_.interpFrames_.pc();
data_.state_ = INTERP;
return;
}
}
FrameIter::Data::Data(JSContext* cx, DebuggerEvalOption debuggerEvalOption,
JSPrincipals* principals)
: cx_(cx),
debuggerEvalOption_(debuggerEvalOption),
principals_(principals),
state_(DONE),
pc_(nullptr),
interpFrames_(nullptr),
activations_(cx),
ionInlineFrameNo_(0)
{
}
FrameIter::Data::Data(const FrameIter::Data& other)
: cx_(other.cx_),
debuggerEvalOption_(other.debuggerEvalOption_),
principals_(other.principals_),
state_(other.state_),
pc_(other.pc_),
interpFrames_(other.interpFrames_),
activations_(other.activations_),
jitFrames_(other.jitFrames_),
ionInlineFrameNo_(other.ionInlineFrameNo_)
{
}
FrameIter::FrameIter(JSContext* cx, DebuggerEvalOption debuggerEvalOption)
: data_(cx, debuggerEvalOption, nullptr),
ionInlineFrames_(cx, (js::jit::JSJitFrameIter*) nullptr)
{
// settleOnActivation can only GC if principals are given.
JS::AutoSuppressGCAnalysis nogc;
settleOnActivation();
// No principals so we can see all frames.
MOZ_ASSERT_IF(!done(), principalsSubsumeFrame());
}
FrameIter::FrameIter(JSContext* cx, DebuggerEvalOption debuggerEvalOption,
JSPrincipals* principals)
: data_(cx, debuggerEvalOption, principals),
ionInlineFrames_(cx, (js::jit::JSJitFrameIter*) nullptr)
{
settleOnActivation();
// If we're not allowed to see this frame, call operator++ to skip this (and
// other) cross-origin frames.
if (!done() && !principalsSubsumeFrame()) {
++*this;
}
}
FrameIter::FrameIter(const FrameIter& other)
: data_(other.data_),
ionInlineFrames_(other.data_.cx_, isIonScripted() ? &other.ionInlineFrames_ : nullptr)
{
}
FrameIter::FrameIter(const Data& data)
: data_(data),
ionInlineFrames_(data.cx_, isIonScripted() ? &jsJitFrame() : nullptr)
{
MOZ_ASSERT(data.cx_);
if (isIonScripted()) {
while (ionInlineFrames_.frameNo() != data.ionInlineFrameNo_) {
++ionInlineFrames_;
}
}
}
void
FrameIter::nextJitFrame()
{
MOZ_ASSERT(data_.jitFrames_.isSome());
if (isJSJit()) {
if (jsJitFrame().isIonScripted()) {
ionInlineFrames_.resetOn(&jsJitFrame());
data_.pc_ = ionInlineFrames_.pc();
} else {
MOZ_ASSERT(jsJitFrame().isBaselineJS());
jsJitFrame().baselineScriptAndPc(nullptr, &data_.pc_);
}
return;
}
MOZ_ASSERT(isWasm());
data_.pc_ = nullptr;
}
void
FrameIter::popJitFrame()
{
MOZ_ASSERT(data_.state_ == JIT);
MOZ_ASSERT(data_.jitFrames_.isSome());
if (isJSJit() && jsJitFrame().isIonScripted() && ionInlineFrames_.more()) {
++ionInlineFrames_;
data_.pc_ = ionInlineFrames_.pc();
return;
}
++data_.jitFrames_;
data_.jitFrames_.skipNonScriptedJSFrames();
if (!data_.jitFrames_.done()) {
nextJitFrame();
} else {
data_.jitFrames_.reset();
popActivation();
}
}
FrameIter&
FrameIter::operator++()
{
while (true) {
switch (data_.state_) {
case DONE:
MOZ_CRASH("Unexpected state");
case INTERP:
if (interpFrame()->isDebuggerEvalFrame() &&
data_.debuggerEvalOption_ == FOLLOW_DEBUGGER_EVAL_PREV_LINK)
{
AbstractFramePtr eifPrev = interpFrame()->evalInFramePrev();
popInterpreterFrame();
while (!hasUsableAbstractFramePtr() || abstractFramePtr() != eifPrev) {
if (data_.state_ == JIT) {
popJitFrame();
} else {
popInterpreterFrame();
}
}
break;
}
popInterpreterFrame();
break;
case JIT:
popJitFrame();
break;
}
if (done() || principalsSubsumeFrame()) {
break;
}
}
return *this;
}
FrameIter::Data*
FrameIter::copyData() const
{
Data* data = data_.cx_->new_<Data>(data_);
if (!data) {
return nullptr;
}
if (data && isIonScripted()) {
data->ionInlineFrameNo_ = ionInlineFrames_.frameNo();
}
return data;
}
void*
FrameIter::rawFramePtr() const
{
switch (data_.state_) {
case DONE:
return nullptr;
case INTERP:
return interpFrame();
case JIT:
if (isJSJit()) {
return jsJitFrame().fp();
}
MOZ_ASSERT(isWasm());
return nullptr;
}
MOZ_CRASH("Unexpected state");
}
JS::Compartment*
FrameIter::compartment() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
case JIT:
return data_.activations_->compartment();
}
MOZ_CRASH("Unexpected state");
}
Realm*
FrameIter::realm() const
{
MOZ_ASSERT(!done());
if (hasScript()) {
return script()->realm();
}
return wasmInstance()->realm();
}
bool
FrameIter::isEvalFrame() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
return interpFrame()->isEvalFrame();
case JIT:
if (isJSJit()) {
if (jsJitFrame().isBaselineJS()) {
return jsJitFrame().baselineFrame()->isEvalFrame();
}
MOZ_ASSERT(!script()->isForEval());
return false;
}
MOZ_ASSERT(isWasm());
return false;
}
MOZ_CRASH("Unexpected state");
}
bool
FrameIter::isFunctionFrame() const
{
MOZ_ASSERT(!done());
switch (data_.state_) {
case DONE:
break;
case INTERP:
return interpFrame()->isFunctionFrame();
case JIT:
if (isJSJit()) {
if (jsJitFrame().isBaselineJS()) {
return jsJitFrame().baselineFrame()->isFunctionFrame();
}
return script()->functionNonDelazifying();
}
MOZ_ASSERT(isWasm());
return false;
}
MOZ_CRASH("Unexpected state");
}
JSAtom*
FrameIter::maybeFunctionDisplayAtom() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
case JIT:
if (isWasm()) {
return wasmFrame().functionDisplayAtom();
}
if (isFunctionFrame()) {
return calleeTemplate()->displayAtom();
}
return nullptr;
}
MOZ_CRASH("Unexpected state");
}
ScriptSource*
FrameIter::scriptSource() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
case JIT:
return script()->scriptSource();
}
MOZ_CRASH("Unexpected state");
}
const char*
FrameIter::filename() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
case JIT:
if (isWasm()) {
return wasmFrame().filename();
}
return script()->filename();
}
MOZ_CRASH("Unexpected state");
}
const char16_t*
FrameIter::displayURL() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
case JIT:
if (isWasm()) {
return wasmFrame().displayURL();
}
ScriptSource* ss = script()->scriptSource();
return ss->hasDisplayURL() ? ss->displayURL() : nullptr;
}
MOZ_CRASH("Unexpected state");
}
unsigned
FrameIter::computeLine(uint32_t* column) const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
case JIT:
if (isWasm()) {
return wasmFrame().computeLine(column);
}
return PCToLineNumber(script(), pc(), column);
}
MOZ_CRASH("Unexpected state");
}
bool
FrameIter::mutedErrors() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
case JIT:
if (isWasm()) {
return wasmFrame().mutedErrors();
}
return script()->mutedErrors();
}
MOZ_CRASH("Unexpected state");
}
bool
FrameIter::isConstructing() const
{
switch (data_.state_) {
case DONE:
break;
case JIT:
MOZ_ASSERT(isJSJit());
if (jsJitFrame().isIonScripted()) {
return ionInlineFrames_.isConstructing();
}
MOZ_ASSERT(jsJitFrame().isBaselineJS());
return jsJitFrame().isConstructing();
case INTERP:
return interpFrame()->isConstructing();
}
MOZ_CRASH("Unexpected state");
}
bool
FrameIter::ensureHasRematerializedFrame(JSContext* cx)
{
MOZ_ASSERT(isIon());
return !!activation()->asJit()->getRematerializedFrame(cx, jsJitFrame());
}
bool
FrameIter::hasUsableAbstractFramePtr() const
{
switch (data_.state_) {
case DONE:
return false;
case JIT:
if (isJSJit()) {
if (jsJitFrame().isBaselineJS()) {
return true;
}
MOZ_ASSERT(jsJitFrame().isIonScripted());
return !!activation()->asJit()->lookupRematerializedFrame(jsJitFrame().fp(),
ionInlineFrames_.frameNo());
}
MOZ_ASSERT(isWasm());
return wasmFrame().debugEnabled();
case INTERP:
return true;
}
MOZ_CRASH("Unexpected state");
}
AbstractFramePtr
FrameIter::abstractFramePtr() const
{
MOZ_ASSERT(hasUsableAbstractFramePtr());
switch (data_.state_) {
case DONE:
break;
case JIT: {
if (isJSJit()) {
if (jsJitFrame().isBaselineJS()) {
return jsJitFrame().baselineFrame();
}
MOZ_ASSERT(isIonScripted());
return activation()->asJit()->lookupRematerializedFrame(jsJitFrame().fp(),
ionInlineFrames_.frameNo());
}
MOZ_ASSERT(isWasm());
MOZ_ASSERT(wasmFrame().debugEnabled());
return wasmFrame().debugFrame();
}
case INTERP:
MOZ_ASSERT(interpFrame());
return AbstractFramePtr(interpFrame());
}
MOZ_CRASH("Unexpected state");
}
void
FrameIter::updatePcQuadratic()
{
switch (data_.state_) {
case DONE:
break;
case INTERP: {
InterpreterFrame* frame = interpFrame();
InterpreterActivation* activation = data_.activations_->asInterpreter();
// Look for the current frame.
data_.interpFrames_ = InterpreterFrameIterator(activation);
while (data_.interpFrames_.frame() != frame) {
++data_.interpFrames_;
}
// Update the pc.
MOZ_ASSERT(data_.interpFrames_.frame() == frame);
data_.pc_ = data_.interpFrames_.pc();
return;
}
case JIT:
if (jsJitFrame().isBaselineJS()) {
jit::BaselineFrame* frame = jsJitFrame().baselineFrame();
jit::JitActivation* activation = data_.activations_->asJit();
// activation's exitFP may be invalid, so create a new
// activation iterator.
data_.activations_ = ActivationIterator(data_.cx_);
while (data_.activations_.activation() != activation) {
++data_.activations_;
}
// Look for the current frame.
data_.jitFrames_ = JitFrameIter(data_.activations_->asJit());
while (!isJSJit() ||
!jsJitFrame().isBaselineJS() ||
jsJitFrame().baselineFrame() != frame)
{
++data_.jitFrames_;
}
// Update the pc.
MOZ_ASSERT(jsJitFrame().baselineFrame() == frame);
jsJitFrame().baselineScriptAndPc(nullptr, &data_.pc_);
return;
}
break;
}
MOZ_CRASH("Unexpected state");
}
void
FrameIter::wasmUpdateBytecodeOffset()
{
MOZ_RELEASE_ASSERT(isWasm(), "Unexpected state");
wasm::DebugFrame* frame = wasmFrame().debugFrame();
// Relookup the current frame, updating the bytecode offset in the process.
data_.jitFrames_ = JitFrameIter(data_.activations_->asJit());
while (wasmFrame().debugFrame() != frame) {
++data_.jitFrames_;
}
MOZ_ASSERT(wasmFrame().debugFrame() == frame);
}
JSFunction*
FrameIter::calleeTemplate() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
MOZ_ASSERT(isFunctionFrame());
return &interpFrame()->callee();
case JIT:
if (jsJitFrame().isBaselineJS()) {
return jsJitFrame().callee();
}
MOZ_ASSERT(jsJitFrame().isIonScripted());
return ionInlineFrames_.calleeTemplate();
}
MOZ_CRASH("Unexpected state");
}
JSFunction*
FrameIter::callee(JSContext* cx) const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
return calleeTemplate();
case JIT:
if (isIonScripted()) {
jit::MaybeReadFallback recover(cx, activation()->asJit(), &jsJitFrame());
return ionInlineFrames_.callee(recover);
}
MOZ_ASSERT(jsJitFrame().isBaselineJS());
return calleeTemplate();
}
MOZ_CRASH("Unexpected state");
}
bool
FrameIter::matchCallee(JSContext* cx, HandleFunction fun) const
{
RootedFunction currentCallee(cx, calleeTemplate());
// As we do not know if the calleeTemplate is the real function, or the
// template from which it would be cloned, we compare properties which are
// stable across the cloning of JSFunctions.
if (((currentCallee->flags() ^ fun->flags()) & JSFunction::STABLE_ACROSS_CLONES) != 0 ||
currentCallee->nargs() != fun->nargs())
{
return false;
}
// Use the same condition as |js::CloneFunctionObject|, to know if we should
// expect both functions to have the same JSScript. If so, and if they are
// different, then they cannot be equal.
RootedObject global(cx, &fun->global());
bool useSameScript = CanReuseScriptForClone(fun->realm(), currentCallee, global);
if (useSameScript &&
(currentCallee->hasScript() != fun->hasScript() ||
currentCallee->nonLazyScript() != fun->nonLazyScript()))
{
return false;
}
// If none of the previous filters worked, then take the risk of
// invalidating the frame to identify the JSFunction.
return callee(cx) == fun;
}
unsigned
FrameIter::numActualArgs() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
MOZ_ASSERT(isFunctionFrame());
return interpFrame()->numActualArgs();
case JIT:
if (isIonScripted()) {
return ionInlineFrames_.numActualArgs();
}
MOZ_ASSERT(jsJitFrame().isBaselineJS());
return jsJitFrame().numActualArgs();
}
MOZ_CRASH("Unexpected state");
}
unsigned
FrameIter::numFormalArgs() const
{
return script()->functionNonDelazifying()->nargs();
}
Value
FrameIter::unaliasedActual(unsigned i, MaybeCheckAliasing checkAliasing) const
{
return abstractFramePtr().unaliasedActual(i, checkAliasing);
}
JSObject*
FrameIter::environmentChain(JSContext* cx) const
{
switch (data_.state_) {
case DONE:
break;
case JIT:
if (isJSJit()) {
if (isIonScripted()) {
jit::MaybeReadFallback recover(cx, activation()->asJit(), &jsJitFrame());
return ionInlineFrames_.environmentChain(recover);
}
return jsJitFrame().baselineFrame()->environmentChain();
}
MOZ_ASSERT(isWasm());
return wasmFrame().debugFrame()->environmentChain();
case INTERP:
return interpFrame()->environmentChain();
}
MOZ_CRASH("Unexpected state");
}
bool
FrameIter::hasInitialEnvironment(JSContext *cx) const {
if (hasUsableAbstractFramePtr()) {
return abstractFramePtr().hasInitialEnvironment();
}
if (isWasm()) {
// See JSFunction::needsFunctionEnvironmentObjects().
return false;
}
MOZ_ASSERT(isJSJit() && isIonScripted());
bool hasInitialEnv = false;
jit::MaybeReadFallback recover(cx, activation()->asJit(), &jsJitFrame());
ionInlineFrames_.environmentChain(recover, &hasInitialEnv);
return hasInitialEnv;
}
CallObject&
FrameIter::callObj(JSContext* cx) const
{
MOZ_ASSERT(calleeTemplate()->needsCallObject());
MOZ_ASSERT(hasInitialEnvironment(cx));
JSObject* pobj = environmentChain(cx);
while (!pobj->is<CallObject>()) {
pobj = pobj->enclosingEnvironment();
}
return pobj->as<CallObject>();
}
bool
FrameIter::hasArgsObj() const
{
return abstractFramePtr().hasArgsObj();
}
ArgumentsObject&
FrameIter::argsObj() const
{
MOZ_ASSERT(hasArgsObj());
return abstractFramePtr().argsObj();
}
Value
FrameIter::thisArgument(JSContext* cx) const
{
MOZ_ASSERT(isFunctionFrame());
switch (data_.state_) {
case DONE:
break;
case JIT:
if (isIonScripted()) {
jit::MaybeReadFallback recover(cx, activation()->asJit(), &jsJitFrame());
return ionInlineFrames_.thisArgument(recover);
}
return jsJitFrame().baselineFrame()->thisArgument();
case INTERP:
return interpFrame()->thisArgument();
}
MOZ_CRASH("Unexpected state");
}
Value
FrameIter::newTarget() const
{
switch (data_.state_) {
case DONE:
break;
case INTERP:
return interpFrame()->newTarget();
case JIT:
MOZ_ASSERT(jsJitFrame().isBaselineJS());
return jsJitFrame().baselineFrame()->newTarget();
}
MOZ_CRASH("Unexpected state");
}
Value
FrameIter::returnValue() const
{
switch (data_.state_) {
case DONE:
break;
case JIT:
if (jsJitFrame().isBaselineJS()) {
return jsJitFrame().baselineFrame()->returnValue();
}
break;
case INTERP:
return interpFrame()->returnValue();
}
MOZ_CRASH("Unexpected state");
}
void
FrameIter::setReturnValue(const Value& v)
{
switch (data_.state_) {
case DONE:
break;
case JIT:
if (jsJitFrame().isBaselineJS()) {
jsJitFrame().baselineFrame()->setReturnValue(v);
return;
}
break;
case INTERP:
interpFrame()->setReturnValue(v);
return;
}
MOZ_CRASH("Unexpected state");
}
size_t
FrameIter::numFrameSlots() const
{
switch (data_.state_) {
case DONE:
break;
case JIT: {
if (isIonScripted()) {
return ionInlineFrames_.snapshotIterator().numAllocations() -
ionInlineFrames_.script()->nfixed();
}
jit::BaselineFrame* frame = jsJitFrame().baselineFrame();
return frame->numValueSlots() - jsJitFrame().script()->nfixed();
}
case INTERP:
MOZ_ASSERT(data_.interpFrames_.sp() >= interpFrame()->base());
return data_.interpFrames_.sp() - interpFrame()->base();
}
MOZ_CRASH("Unexpected state");
}
Value
FrameIter::frameSlotValue(size_t index) const
{
switch (data_.state_) {
case DONE:
break;
case JIT:
if (isIonScripted()) {
jit::SnapshotIterator si(ionInlineFrames_.snapshotIterator());
index += ionInlineFrames_.script()->nfixed();
return si.maybeReadAllocByIndex(index);
}
index += jsJitFrame().script()->nfixed();
return *jsJitFrame().baselineFrame()->valueSlot(index);
case INTERP:
return interpFrame()->base()[index];
}
MOZ_CRASH("Unexpected state");
}
#ifdef DEBUG
bool
js::SelfHostedFramesVisible()
{
static bool checked = false;
static bool visible = false;
if (!checked) {
checked = true;
char* env = getenv("MOZ_SHOW_ALL_JS_FRAMES");
visible = !!env;
}
return visible;
}
#endif
void
NonBuiltinFrameIter::settle()
{
if (!SelfHostedFramesVisible()) {
while (!done() && hasScript() && script()->selfHosted()) {
FrameIter::operator++();
}
}
}
void
NonBuiltinScriptFrameIter::settle()
{
if (!SelfHostedFramesVisible()) {
while (!done() && script()->selfHosted()) {
ScriptFrameIter::operator++();
}
}
}
ActivationEntryMonitor::ActivationEntryMonitor(JSContext* cx)
: cx_(cx), entryMonitor_(cx->entryMonitor)
{
cx->entryMonitor = nullptr;
}
Value
ActivationEntryMonitor::asyncStack(JSContext* cx)
{
RootedValue stack(cx, ObjectOrNullValue(cx->asyncStackForNewActivations()));
if (!cx->compartment()->wrap(cx, &stack)) {
cx->clearPendingException();
return UndefinedValue();
}
return stack;
}
ActivationEntryMonitor::ActivationEntryMonitor(JSContext* cx, InterpreterFrame* entryFrame)
: ActivationEntryMonitor(cx)
{
if (entryMonitor_) {
// The InterpreterFrame is not yet part of an Activation, so it won't
// be traced if we trigger GC here. Suppress GC to avoid this.
gc::AutoSuppressGC suppressGC(cx);
RootedValue stack(cx, asyncStack(cx));
const char* asyncCause = cx->asyncCauseForNewActivations;
if (entryFrame->isFunctionFrame()) {
entryMonitor_->Entry(cx, &entryFrame->callee(), stack, asyncCause);
} else {
entryMonitor_->Entry(cx, entryFrame->script(), stack, asyncCause);
}
}
}
ActivationEntryMonitor::ActivationEntryMonitor(JSContext* cx, jit::CalleeToken entryToken)
: ActivationEntryMonitor(cx)
{
if (entryMonitor_) {
// The CalleeToken is not traced at this point and we also don't want
// a GC to discard the code we're about to enter, so we suppress GC.
gc::AutoSuppressGC suppressGC(cx);
RootedValue stack(cx, asyncStack(cx));
const char* asyncCause = cx->asyncCauseForNewActivations;
if (jit::CalleeTokenIsFunction(entryToken)) {
entryMonitor_->Entry(cx_, jit::CalleeTokenToFunction(entryToken), stack, asyncCause);
} else {
entryMonitor_->Entry(cx_, jit::CalleeTokenToScript(entryToken), stack, asyncCause);
}
}
}
/*****************************************************************************/
jit::JitActivation::JitActivation(JSContext* cx)
: Activation(cx, Jit),
packedExitFP_(nullptr),
encodedWasmExitReason_(0),
prevJitActivation_(cx->jitActivation),
rematerializedFrames_(),
ionRecovery_(cx),
bailoutData_(nullptr),
lastProfilingFrame_(nullptr),
lastProfilingCallSite_(nullptr)
{
cx->jitActivation = this;
registerProfiling();
}
jit::JitActivation::~JitActivation()
{
if (isProfiling()) {
unregisterProfiling();
}
cx_->jitActivation = prevJitActivation_;
// All reocvered value are taken from activation during the bailout.
MOZ_ASSERT(ionRecovery_.empty());
// The BailoutFrameInfo should have unregistered itself from the
// JitActivations.
MOZ_ASSERT(!bailoutData_);
// Traps get handled immediately.
MOZ_ASSERT(!isWasmTrapping());
clearRematerializedFrames();
}
void
jit::JitActivation::setBailoutData(jit::BailoutFrameInfo* bailoutData)
{
MOZ_ASSERT(!bailoutData_);
bailoutData_ = bailoutData;
}
void
jit::JitActivation::cleanBailoutData()
{
MOZ_ASSERT(bailoutData_);
bailoutData_ = nullptr;
}
void
jit::JitActivation::removeRematerializedFrame(uint8_t* top)
{
if (!rematerializedFrames_) {
return;
}
if (RematerializedFrameTable::Ptr p = rematerializedFrames_->lookup(top)) {
RematerializedFrame::FreeInVector(p->value());
rematerializedFrames_->remove(p);
}
}
void
jit::JitActivation::clearRematerializedFrames()
{
if (!rematerializedFrames_) {
return;
}
for (RematerializedFrameTable::Enum e(*rematerializedFrames_); !e.empty(); e.popFront()) {
RematerializedFrame::FreeInVector(e.front().value());
e.removeFront();
}
}
jit::RematerializedFrame*
jit::JitActivation::getRematerializedFrame(JSContext* cx, const JSJitFrameIter& iter,
size_t inlineDepth)
{
MOZ_ASSERT(iter.activation() == this);
MOZ_ASSERT(iter.isIonScripted());
if (!rematerializedFrames_) {
rematerializedFrames_ = cx->make_unique<RematerializedFrameTable>(cx);
if (!rematerializedFrames_) {
return nullptr;
}
}
uint8_t* top = iter.fp();
RematerializedFrameTable::AddPtr p = rematerializedFrames_->lookupForAdd(top);
if (!p) {
RematerializedFrameVector frames(cx);
// The unit of rematerialization is an uninlined frame and its inlined
// frames. Since inlined frames do not exist outside of snapshots, it
// is impossible to synchronize their rematerialized copies to
// preserve identity. Therefore, we always rematerialize an uninlined
// frame and all its inlined frames at once.
InlineFrameIterator inlineIter(cx, &iter);
MaybeReadFallback recover(cx, this, &iter);
// Frames are often rematerialized with the cx inside a Debugger's
// realm. To recover slots and to create CallObjects, we need to
// be in the script's realm.
AutoRealmUnchecked ar(cx, iter.script()->realm());
if (!RematerializedFrame::RematerializeInlineFrames(cx, top, inlineIter, recover, frames)) {
return nullptr;
}
if (!rematerializedFrames_->add(p, top, std::move(frames))) {
ReportOutOfMemory(cx);
return nullptr;
}
// See comment in unsetPrevUpToDateUntil.
DebugEnvironments::unsetPrevUpToDateUntil(cx, p->value()[inlineDepth]);
}
return p->value()[inlineDepth];
}
jit::RematerializedFrame*
jit::JitActivation::lookupRematerializedFrame(uint8_t* top, size_t inlineDepth)
{
if (!rematerializedFrames_) {
return nullptr;
}
if (RematerializedFrameTable::Ptr p = rematerializedFrames_->lookup(top)) {
return inlineDepth < p->value().length() ? p->value()[inlineDepth] : nullptr;
}
return nullptr;
}
void
jit::JitActivation::removeRematerializedFramesFromDebugger(JSContext* cx, uint8_t* top)
{
// Ion bailout can fail due to overrecursion and OOM. In such cases we
// cannot honor any further Debugger hooks on the frame, and need to
// ensure that its Debugger.Frame entry is cleaned up.
if (!cx->realm()->isDebuggee() || !rematerializedFrames_) {
return;
}
if (RematerializedFrameTable::Ptr p = rematerializedFrames_->lookup(top)) {
for (uint32_t i = 0; i < p->value().length(); i++) {
Debugger::handleUnrecoverableIonBailoutError(cx, p->value()[i]);
}
RematerializedFrame::FreeInVector(p->value());
rematerializedFrames_->remove(p);
}
}
void
jit::JitActivation::traceRematerializedFrames(JSTracer* trc)
{
if (!rematerializedFrames_) {
return;
}
for (RematerializedFrameTable::Enum e(*rematerializedFrames_); !e.empty(); e.popFront()) {
e.front().value().trace(trc);
}
}
bool
jit::JitActivation::registerIonFrameRecovery(RInstructionResults&& results)
{
// Check that there is no entry in the vector yet.
MOZ_ASSERT(!maybeIonFrameRecovery(results.frame()));
if (!ionRecovery_.append(std::move(results))) {
return false;
}
return true;
}
jit::RInstructionResults*
jit::JitActivation::maybeIonFrameRecovery(JitFrameLayout* fp)
{
for (RInstructionResults* it = ionRecovery_.begin(); it != ionRecovery_.end(); ) {
if (it->frame() == fp) {
return it;
}
}
return nullptr;
}
void
jit::JitActivation::removeIonFrameRecovery(JitFrameLayout* fp)
{
RInstructionResults* elem = maybeIonFrameRecovery(fp);
if (!elem) {
return;
}
ionRecovery_.erase(elem);
}
void
jit::JitActivation::traceIonRecovery(JSTracer* trc)
{
for (RInstructionResults* it = ionRecovery_.begin(); it != ionRecovery_.end(); it++) {
it->trace(trc);
}
}
void
jit::JitActivation::startWasmTrap(wasm::Trap trap, uint32_t bytecodeOffset,
const wasm::RegisterState& state)
{
MOZ_ASSERT(!isWasmTrapping());
bool unwound;
wasm::UnwindState unwindState;
MOZ_RELEASE_ASSERT(wasm::StartUnwinding(state, &unwindState, &unwound));
MOZ_ASSERT(unwound == (trap == wasm::Trap::IndirectCallBadSig));
void* pc = unwindState.pc;
wasm::Frame* fp = unwindState.fp;
const wasm::Code& code = fp->tls->instance->code();
MOZ_RELEASE_ASSERT(&code == wasm::LookupCode(pc));
// If the frame was unwound, the bytecodeOffset must be recovered from the
// callsite so that it is accurate.
if (unwound) {
bytecodeOffset = code.lookupCallSite(pc)->lineOrBytecode();
}
setWasmExitFP(fp);
wasmTrapData_.emplace();
wasmTrapData_->resumePC = ((uint8_t*)state.pc) + jit::WasmTrapInstructionLength;
wasmTrapData_->unwoundPC = pc;
wasmTrapData_->trap = trap;
wasmTrapData_->bytecodeOffset = bytecodeOffset;
MOZ_ASSERT(isWasmTrapping());
}
void
jit::JitActivation::finishWasmTrap()
{
MOZ_ASSERT(isWasmTrapping());
packedExitFP_ = nullptr;
wasmTrapData_.reset();
MOZ_ASSERT(!isWasmTrapping());
}
InterpreterFrameIterator&
InterpreterFrameIterator::operator++()
{
MOZ_ASSERT(!done());
if (fp_ != activation_->entryFrame_) {
pc_ = fp_->prevpc();
sp_ = fp_->prevsp();
fp_ = fp_->prev();
} else {
pc_ = nullptr;
sp_ = nullptr;
fp_ = nullptr;
}
return *this;
}
void
Activation::registerProfiling()
{
MOZ_ASSERT(isProfiling());
cx_->profilingActivation_ = this;
}
void
Activation::unregisterProfiling()
{
MOZ_ASSERT(isProfiling());
MOZ_ASSERT(cx_->profilingActivation_ == this);
cx_->profilingActivation_ = prevProfiling_;
}
ActivationIterator::ActivationIterator(JSContext* cx)
: activation_(cx->activation_)
{
MOZ_ASSERT(cx == TlsContext.get());
}
ActivationIterator&
ActivationIterator::operator++()
{
MOZ_ASSERT(activation_);
activation_ = activation_->prev();
return *this;
}
JS::ProfilingFrameIterator::ProfilingFrameIterator(JSContext* cx, const RegisterState& state,
const Maybe<uint64_t>& samplePositionInProfilerBuffer)
: cx_(cx),
samplePositionInProfilerBuffer_(samplePositionInProfilerBuffer),
activation_(nullptr)
{
if (!cx->runtime()->geckoProfiler().enabled()) {
MOZ_CRASH("ProfilingFrameIterator called when geckoProfiler not enabled for runtime.");
}
if (!cx->profilingActivation()) {
return;
}
// If profiler sampling is not enabled, skip.
if (!cx->isProfilerSamplingEnabled()) {
return;
}
activation_ = cx->profilingActivation();
MOZ_ASSERT(activation_->isProfiling());
static_assert(sizeof(wasm::ProfilingFrameIterator) <= StorageSpace &&
sizeof(jit::JSJitProfilingFrameIterator) <= StorageSpace,
"ProfilingFrameIterator::storage_ is too small");
static_assert(alignof(void*) >= alignof(wasm::ProfilingFrameIterator) &&
alignof(void*) >= alignof(jit::JSJitProfilingFrameIterator),
"ProfilingFrameIterator::storage_ is too weakly aligned");
iteratorConstruct(state);
settle();
}
JS::ProfilingFrameIterator::~ProfilingFrameIterator()
{
if (!done()) {
MOZ_ASSERT(activation_->isProfiling());
iteratorDestroy();
}
}
void
JS::ProfilingFrameIterator::operator++()
{
MOZ_ASSERT(!done());
MOZ_ASSERT(activation_->isJit());
if (isWasm()) {
++wasmIter();
} else {
++jsJitIter();
}
settle();
}
void
JS::ProfilingFrameIterator::settleFrames()
{
// Handle transition frames (see comment in JitFrameIter::operator++).
if (isJSJit() && !jsJitIter().done() && jsJitIter().frameType() == jit::FrameType::WasmToJSJit) {
wasm::Frame* fp = (wasm::Frame*) jsJitIter().fp();
iteratorDestroy();
new (storage()) wasm::ProfilingFrameIterator(*activation_->asJit(), fp);
kind_ = Kind::Wasm;
MOZ_ASSERT(!wasmIter().done());
return;
}
if (isWasm() && wasmIter().done() && wasmIter().unwoundIonCallerFP()) {
uint8_t* fp = wasmIter().unwoundIonCallerFP();
iteratorDestroy();
// Using this ctor will skip the first ion->wasm frame, which is
// needed because the profiling iterator doesn't know how to unwind
// when the callee has no script.
new (storage()) jit::JSJitProfilingFrameIterator((jit::CommonFrameLayout*)fp);
kind_ = Kind::JSJit;
MOZ_ASSERT(!jsJitIter().done());
return;
}
}
void
JS::ProfilingFrameIterator::settle()
{
settleFrames();
while (iteratorDone()) {
iteratorDestroy();
activation_ = activation_->prevProfiling();
if (!activation_) {
return;
}
iteratorConstruct();
settleFrames();
}
}
void
JS::ProfilingFrameIterator::iteratorConstruct(const RegisterState& state)
{
MOZ_ASSERT(!done());
MOZ_ASSERT(activation_->isJit());
jit::JitActivation* activation = activation_->asJit();
// We want to know if we should start with a wasm profiling frame iterator
// or not. To determine this, there are three possibilities:
// - we've exited to C++ from wasm, in which case the activation
// exitFP low bit is tagged and we can test hasWasmExitFP().
// - we're in wasm code, so we can do a lookup on PC.
// - in all the other cases, we're not in wasm or we haven't exited from
// wasm.
if (activation->hasWasmExitFP() || wasm::InCompiledCode(state.pc)) {
new (storage()) wasm::ProfilingFrameIterator(*activation, state);
kind_ = Kind::Wasm;
return;
}
new (storage()) jit::JSJitProfilingFrameIterator(cx_, state.pc);
kind_ = Kind::JSJit;
}
void
JS::ProfilingFrameIterator::iteratorConstruct()
{
MOZ_ASSERT(!done());
MOZ_ASSERT(activation_->isJit());
jit::JitActivation* activation = activation_->asJit();
// The same reasoning as in the above iteratorConstruct variant applies
// here, except that it's even simpler: since this activation is higher up
// on the stack, it can only have exited to C++, through wasm or ion.
if (activation->hasWasmExitFP()) {
new (storage()) wasm::ProfilingFrameIterator(*activation);
kind_ = Kind::Wasm;
return;
}
auto* fp = (jit::ExitFrameLayout*) activation->jsExitFP();
new (storage()) jit::JSJitProfilingFrameIterator(fp);
kind_ = Kind::JSJit;
}
void
JS::ProfilingFrameIterator::iteratorDestroy()
{
MOZ_ASSERT(!done());
MOZ_ASSERT(activation_->isJit());
if (isWasm()) {
wasmIter().~ProfilingFrameIterator();
return;
}
jsJitIter().~JSJitProfilingFrameIterator();
}
bool
JS::ProfilingFrameIterator::iteratorDone()
{
MOZ_ASSERT(!done());
MOZ_ASSERT(activation_->isJit());
if (isWasm()) {
return wasmIter().done();
}
return jsJitIter().done();
}
void*
JS::ProfilingFrameIterator::stackAddress() const
{
MOZ_ASSERT(!done());
MOZ_ASSERT(activation_->isJit());
if (isWasm()) {
return wasmIter().stackAddress();
}
return jsJitIter().stackAddress();
}
Maybe<JS::ProfilingFrameIterator::Frame>
JS::ProfilingFrameIterator::getPhysicalFrameAndEntry(jit::JitcodeGlobalEntry* entry) const
{
void* stackAddr = stackAddress();
if (isWasm()) {
Frame frame;
frame.kind = Frame_Wasm;
frame.stackAddress = stackAddr;
frame.returnAddress = nullptr;
frame.activation = activation_;
frame.label = nullptr;
frame.endStackAddress = activation_->asJit()->jsOrWasmExitFP();
return mozilla::Some(frame);
}
MOZ_ASSERT(isJSJit());
// Look up an entry for the return address.
void* returnAddr = jsJitIter().returnAddressToFp();
jit::JitcodeGlobalTable* table = cx_->runtime()->jitRuntime()->getJitcodeGlobalTable();
if (samplePositionInProfilerBuffer_) {
*entry = table->lookupForSamplerInfallible(returnAddr, cx_->runtime(),
*samplePositionInProfilerBuffer_);
} else {
*entry = table->lookupInfallible(returnAddr);
}
MOZ_ASSERT(entry->isIon() || entry->isIonCache() || entry->isBaseline() || entry->isDummy());
// Dummy frames produce no stack frames.
if (entry->isDummy()) {
return mozilla::Nothing();
}
Frame frame;
frame.kind = entry->isBaseline() ? Frame_Baseline : Frame_Ion;
frame.stackAddress = stackAddr;
frame.returnAddress = returnAddr;
frame.activation = activation_;
frame.label = nullptr;
frame.endStackAddress = activation_->asJit()->jsOrWasmExitFP();
return mozilla::Some(frame);
}
uint32_t
JS::ProfilingFrameIterator::extractStack(Frame* frames, uint32_t offset, uint32_t end) const
{
if (offset >= end) {
return 0;
}
jit::JitcodeGlobalEntry entry;
Maybe<Frame> physicalFrame = getPhysicalFrameAndEntry(&entry);
// Dummy frames produce no stack frames.
if (physicalFrame.isNothing()) {
return 0;
}
if (isWasm()) {
frames[offset] = physicalFrame.value();
frames[offset].label = wasmIter().label();
return 1;
}
// Extract the stack for the entry. Assume maximum inlining depth is <64
const char* labels[64];
uint32_t depth = entry.callStackAtAddr(cx_->runtime(), jsJitIter().returnAddressToFp(),
labels, ArrayLength(labels));
MOZ_ASSERT(depth < ArrayLength(labels));
for (uint32_t i = 0; i < depth; i++) {
if (offset + i >= end) {
return i;
}
frames[offset + i] = physicalFrame.value();
frames[offset + i].label = labels[i];
}
return depth;
}
Maybe<JS::ProfilingFrameIterator::Frame>
JS::ProfilingFrameIterator::getPhysicalFrameWithoutLabel() const
{
jit::JitcodeGlobalEntry unused;
return getPhysicalFrameAndEntry(&unused);
}
bool
JS::ProfilingFrameIterator::isWasm() const
{
MOZ_ASSERT(!done());
return kind_ == Kind::Wasm;
}
bool
JS::ProfilingFrameIterator::isJSJit() const
{
return kind_ == Kind::JSJit;
}
| 27.617883 | 105 | 0.611774 | fengjixuchui |
3ebba1ab57bf72d57f2d7d43ebf86db0531aaf6a | 863 | cpp | C++ | analyzer/libs/z3/src/test/proof_checker.cpp | oslab-swrc/juxta | 481cd6f01e87790041a07379805968bcf57d75f4 | [
"MIT"
] | 23 | 2016-01-06T07:01:46.000Z | 2022-02-12T15:53:20.000Z | analyzer/libs/z3/src/test/proof_checker.cpp | oslab-swrc/juxta | 481cd6f01e87790041a07379805968bcf57d75f4 | [
"MIT"
] | 1 | 2019-04-02T00:42:29.000Z | 2019-04-02T00:42:29.000Z | analyzer/libs/z3/src/test/proof_checker.cpp | oslab-swrc/juxta | 481cd6f01e87790041a07379805968bcf57d75f4 | [
"MIT"
] | 16 | 2016-01-06T07:01:46.000Z | 2021-11-29T11:43:16.000Z | #include "proof_checker.h"
#include "ast_ll_pp.h"
void tst_checker1() {
ast_manager m(PGM_FINE);
expr_ref a(m);
proof_ref p1(m), p2(m), p3(m), p4(m);
bool result;
expr_ref_vector side_conditions(m);
a = m.mk_const(symbol("a"), m.mk_bool_sort());
p1 = m.mk_hypothesis(a.get());
p2 = m.mk_hypothesis(m.mk_not(a.get()));
ast_ll_pp(std::cout, m, p1.get());
ast_ll_pp(std::cout, m, p2.get());
proof* proofs[2] = { p1.get(), p2.get() };
p3 = m.mk_unit_resolution(2, proofs);
p4 = m.mk_lemma(p3.get(), a.get());
ast_ll_pp(std::cout, m, p4.get());
proof_checker checker(m);
p4 = m.mk_lemma(p3.get(), m.mk_or(a.get(), m.mk_not(a.get())));
ast_ll_pp(std::cout, m, p4.get());
result = checker.check(p4.get(), side_conditions);
SASSERT(result);
}
void tst_proof_checker() {
tst_checker1();
}
| 28.766667 | 67 | 0.606025 | oslab-swrc |