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
109
| 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
48.5k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5e00e943ee09893e9899159a58f9ce4aad05c0d7
| 300
|
cpp
|
C++
|
projects/tests/main.cpp
|
AnselmoGPP/SQL_tests
|
9ecfc9f386e4516c0f11948bfba796fb3821fa01
|
[
"MIT"
] | null | null | null |
projects/tests/main.cpp
|
AnselmoGPP/SQL_tests
|
9ecfc9f386e4516c0f11948bfba796fb3821fa01
|
[
"MIT"
] | null | null | null |
projects/tests/main.cpp
|
AnselmoGPP/SQL_tests
|
9ecfc9f386e4516c0f11948bfba796fb3821fa01
|
[
"MIT"
] | null | null | null |
/*
* https://www.geeksforgeeks.org/sql-using-c-c-and-sqlite/
* You can install SQLite library with "sudo apt-get install libsqlite3-dev"
*/
#include "auxiliar.hpp"
int main(int argc, char** argv)
{
open_DB();
create_DB();
//show_table(DB);
insert_and_delete();
select();
}
| 18.75
| 77
| 0.646667
|
AnselmoGPP
|
5e02cb452648e1cdacbba96b17d2a3c185f64586
| 723
|
cpp
|
C++
|
export.cpp
|
gonzavesc/convection_final
|
39732bd55b2412bddd65844a8fb1b1dd92acfc1f
|
[
"MIT"
] | null | null | null |
export.cpp
|
gonzavesc/convection_final
|
39732bd55b2412bddd65844a8fb1b1dd92acfc1f
|
[
"MIT"
] | null | null | null |
export.cpp
|
gonzavesc/convection_final
|
39732bd55b2412bddd65844a8fb1b1dd92acfc1f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath> //std::pow abs
#include <new>
#include <algorithm> //std::max
#include "read.hpp"
#include "initialize.hpp"
#include "export.hpp"
void exportarMatriu(const std::vector<std::vector<double>>& phi)
{
int i, jj, Nx, Ny;
std::ofstream output;
output.precision(17);
output.open("Matrix.dat");
Ny = phi.size() - 1;
Nx = phi[0].size() - 1;
for (i = 0; i <= Ny; i++)
{
for (jj = 0; jj <= Nx - 1; jj++)
{
output << phi[i][jj] << ", " ;
}
output << std::scientific << phi[i][Nx] << std::endl;
}
output.close();
}
| 20.083333
| 65
| 0.510373
|
gonzavesc
|
5e066777dfc60f0da529e4ab25352c5453c351a7
| 3,053
|
cpp
|
C++
|
lib/P2p/P2pNodeConfig.cpp
|
exploshot/qwc-test
|
5d5cad4c73e0a61eb76c5d6ceddc635a1b062325
|
[
"MIT"
] | null | null | null |
lib/P2p/P2pNodeConfig.cpp
|
exploshot/qwc-test
|
5d5cad4c73e0a61eb76c5d6ceddc635a1b062325
|
[
"MIT"
] | 2
|
2019-11-01T16:08:44.000Z
|
2019-11-27T23:41:19.000Z
|
lib/P2p/P2pNodeConfig.cpp
|
exploshot/qwc-test
|
5d5cad4c73e0a61eb76c5d6ceddc635a1b062325
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
// Copyright (c) 2018-2019, The TurtleCoin Developers
// Copyright (c) 2018-2020, The Qwertycoin Project
//
// This file is part of Qwertycoin.
//
// Qwertycoin 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 3 of the License, or
// (at your option) any later version.
//
// Qwertycoin 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 Qwertycoin. If not, see <http://www.gnu.org/licenses/>.
#include <Global/CryptoNoteConfig.h>
#include <P2p/P2pNetworks.h>
#include <P2p/P2pNodeConfig.h>
namespace CryptoNote {
namespace {
const std::chrono::nanoseconds P2P_DEFAULT_CONNECT_INTERVAL = std::chrono::seconds (2);
const size_t P2P_DEFAULT_CONNECT_RANGE = 20;
const size_t P2P_DEFAULT_PEERLIST_GET_TRY_COUNT = 10;
} // namespace
P2pNodeConfig::P2pNodeConfig()
: timedSyncInterval (std::chrono::seconds (P2P_DEFAULT_HANDSHAKE_INTERVAL)),
handshakeTimeout (std::chrono::milliseconds (P2P_DEFAULT_HANDSHAKE_INVOKE_TIMEOUT)),
connectInterval (P2P_DEFAULT_CONNECT_INTERVAL),
connectTimeout (std::chrono::milliseconds (P2P_DEFAULT_CONNECTION_TIMEOUT)),
networkId (QWERTYCOIN_NETWORK),
expectedOutgoingConnectionsCount (P2P_DEFAULT_CONNECTIONS_COUNT),
whiteListConnectionsPercent (P2P_DEFAULT_WHITELIST_CONNECTIONS_PERCENT),
peerListConnectRange (P2P_DEFAULT_CONNECT_RANGE),
peerListGetTryCount (P2P_DEFAULT_PEERLIST_GET_TRY_COUNT)
{
}
/*!
* getters
*/
std::chrono::nanoseconds P2pNodeConfig::getTimedSyncInterval() const
{
return timedSyncInterval;
}
std::chrono::nanoseconds P2pNodeConfig::getHandshakeTimeout() const
{
return handshakeTimeout;
}
std::chrono::nanoseconds P2pNodeConfig::getConnectInterval() const
{
return connectInterval;
}
std::chrono::nanoseconds P2pNodeConfig::getConnectTimeout() const
{
return connectTimeout;
}
size_t P2pNodeConfig::getExpectedOutgoingConnectionsCount() const
{
return expectedOutgoingConnectionsCount;
}
size_t P2pNodeConfig::getWhiteListConnectionsPercent() const
{
return whiteListConnectionsPercent;
}
boost::uuids::uuid P2pNodeConfig::getNetworkId() const
{
return networkId;
}
size_t P2pNodeConfig::getPeerListConnectRange() const
{
return peerListConnectRange;
}
size_t P2pNodeConfig::getPeerListGetTryCount() const
{
return peerListGetTryCount;
}
} // namespace CryptoNote
| 31.153061
| 95
| 0.715689
|
exploshot
|
5e06eb0afee9526ee4e51da536046355a08a1468
| 1,138
|
cc
|
C++
|
classes/employee_class.cc
|
fsande/IB-class-code-examples
|
b883cc66c4d5f945b170ff61725dcf38f444bea8
|
[
"MIT"
] | 4
|
2020-11-25T12:48:04.000Z
|
2021-01-07T01:52:40.000Z
|
classes/employee_class.cc
|
fsande/IB-class-code-examples
|
b883cc66c4d5f945b170ff61725dcf38f444bea8
|
[
"MIT"
] | null | null | null |
classes/employee_class.cc
|
fsande/IB-class-code-examples
|
b883cc66c4d5f945b170ff61725dcf38f444bea8
|
[
"MIT"
] | 17
|
2020-10-05T15:03:06.000Z
|
2021-10-04T09:26:09.000Z
|
/**
* Universidad de La Laguna
* Escuela Superior de Ingeniería y Tecnología
* Grado en Ingeniería Informática
* Informática Básica
*
* @author F. de Sande
* @date 25 Jun 2020
* @brief Employee class Example
* In addition to holding data, classes can also contain functions!
* Functions defined inside of a class are called member functions (or sometimes methods).
* Member functions can be defined inside or outside of the class definition.
* Here we define them inside the class for simplicity.
*
* @see https://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/
*/
#include <iostream>
#include <string>
class Employee {
public:
std::string name_{};
int id_{};
double wage_{};
/// Print employee information to the screen
void Print() {
std::cout << "Name: " << name_ <<
" Id: " << id_ <<
" Wage: " << wage_ << "€" << std::endl;
}
};
int main() {
/// Declare two employees
Employee alex { "Alex", 1, 2500.0};
Employee joe { "Joe", 2, 2225.0 };
/// Print out the employee information
alex.Print();
joe.Print();
return 0;
}
| 25.863636
| 98
| 0.636204
|
fsande
|
5e08004176cabb67070e0c82bb50e852daf299f0
| 393
|
cpp
|
C++
|
Machine_learning/Neuron.cpp
|
mdragojevic/machine-learning-algorithms
|
7c1917c137324e61eabfc3f936dc19b315d1aa7a
|
[
"Apache-2.0"
] | 1
|
2021-04-20T13:48:06.000Z
|
2021-04-20T13:48:06.000Z
|
Machine_learning/Neuron.cpp
|
mdragojevic/machine-learning-algorithms
|
7c1917c137324e61eabfc3f936dc19b315d1aa7a
|
[
"Apache-2.0"
] | null | null | null |
Machine_learning/Neuron.cpp
|
mdragojevic/machine-learning-algorithms
|
7c1917c137324e61eabfc3f936dc19b315d1aa7a
|
[
"Apache-2.0"
] | null | null | null |
/*
* Neuron.cpp
*
* Created on: May 12, 2016
* Author: marija
*/
#include "Neuron.h"
using namespace std;
vector<Edge_key> Neuron::in_edges_keys(){
vector<Edge_key> v;
for (auto elem: edges_in) {
v.push_back(elem.first);
}
return v;
}
vector<Edge_key> Neuron::out_edges_keys(){
vector<Edge_key> v;
for (auto elem: edges_out) {
v.push_back(elem.first);
}
return v;
}
| 14.555556
| 42
| 0.656489
|
mdragojevic
|
5e090349872eeb5ebfbacaa35cf9a186f6fea29c
| 11,401
|
cpp
|
C++
|
src/navier_stokes/SpongeLayerForceFunction.cpp
|
MSV-Project/IBAMR
|
3cf614c31bb3c94e2620f165ba967cba719c45ea
|
[
"BSD-3-Clause"
] | 2
|
2017-12-06T06:16:36.000Z
|
2021-03-13T12:28:08.000Z
|
src/navier_stokes/SpongeLayerForceFunction.cpp
|
MSV-Project/IBAMR
|
3cf614c31bb3c94e2620f165ba967cba719c45ea
|
[
"BSD-3-Clause"
] | null | null | null |
src/navier_stokes/SpongeLayerForceFunction.cpp
|
MSV-Project/IBAMR
|
3cf614c31bb3c94e2620f165ba967cba719c45ea
|
[
"BSD-3-Clause"
] | null | null | null |
// Filename: SpongeLayerForceFunction.cpp
// Created on 28 Oct 2011 by Boyce Griffith
//
// Copyright (c) 2002-2013, Boyce Griffith
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of New York University nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
/////////////////////////////// INCLUDES /////////////////////////////////////
#include <math.h>
#include <cmath>
#include <iosfwd>
#include <ostream>
#include <sstream>
#include "Box.h"
#include "BoxArray.h"
#include "CartesianPatchGeometry.h"
#include "CellData.h"
#include "CellIndex.h"
#include "Index.h"
#include "IntVector.h"
#include "Patch.h"
#include "PatchData.h"
#include "SAMRAI_config.h"
#include "SideData.h"
#include "SideGeometry.h"
#include "SideIndex.h"
#include "SpongeLayerForceFunction.h"
#include "Variable.h"
#include "VariableContext.h"
#include "ibamr/INSHierarchyIntegrator.h"
#include "ibamr/StokesSpecifications.h"
#include "ibamr/namespaces.h" // IWYU pragma: keep
#include "tbox/Array.h"
#include "tbox/Database.h"
#include "tbox/Utilities.h"
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
namespace
{
inline double
smooth_kernel(
const double r)
{
return std::abs(r) < 1.0 ? 0.5*(cos(M_PI*r)+1.0) : 0.0;
}// smooth_kernel
}
////////////////////////////// PUBLIC ///////////////////////////////////////
SpongeLayerForceFunction::SpongeLayerForceFunction(
const std::string& object_name,
const Pointer<Database> input_db,
const INSHierarchyIntegrator* fluid_solver,
Pointer<CartesianGridGeometry<NDIM> > grid_geometry)
: CartGridFunction(object_name),
d_forcing_enabled(SAMRAI::tbox::Array<bool>(NDIM)),
d_width(0.0),
d_fluid_solver(fluid_solver),
d_grid_geometry(grid_geometry)
{
if (input_db)
{
for (unsigned int location_index = 0; location_index < 2*NDIM; ++location_index)
{
for (unsigned int d = 0; d < NDIM; ++d) d_forcing_enabled[location_index][d] = false;
std::ostringstream forcing_enabled_stream;
forcing_enabled_stream << "forcing_enabled_" << location_index;
const std::string forcing_enabled_key = forcing_enabled_stream.str();
if (input_db->keyExists(forcing_enabled_key))
{
d_forcing_enabled[location_index] = input_db->getBoolArray(forcing_enabled_key);
}
std::ostringstream width_stream;
width_stream << "width_" << location_index;
const std::string width_key = width_stream.str();
if (input_db->keyExists(width_key))
{
d_width[location_index] = input_db->getDouble(width_key);
}
}
}
return;
}// SpongeLayerForceFunction
SpongeLayerForceFunction::~SpongeLayerForceFunction()
{
// intentionally blank
return;
}// ~SpongeLayerForceFunction
bool
SpongeLayerForceFunction::isTimeDependent() const
{
return true;
}// isTimeDependent
void
SpongeLayerForceFunction::setDataOnPatch(
const int data_idx,
Pointer<Variable<NDIM> > /*var*/,
Pointer<Patch<NDIM> > patch,
const double /*data_time*/,
const bool initial_time,
Pointer<PatchLevel<NDIM> > /*level*/)
{
Pointer<PatchData<NDIM> > f_data = patch->getPatchData(data_idx);
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(f_data);
#endif
Pointer<CellData<NDIM,double> > f_cc_data = f_data;
Pointer<SideData<NDIM,double> > f_sc_data = f_data;
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(f_cc_data || f_sc_data);
#endif
if (f_cc_data) f_cc_data->fillAll(0.0);
if (f_sc_data) f_sc_data->fillAll(0.0);
if (initial_time) return;
const int cycle_num = d_fluid_solver->getCurrentCycleNumber();
const double dt = d_fluid_solver->getCurrentTimeStepSize();
const double rho = d_fluid_solver->getStokesSpecifications()->getRho();
const double kappa = cycle_num >= 0 ? 0.5*rho/dt : 0.0;
Pointer<PatchData<NDIM> > u_current_data = patch->getPatchData(d_fluid_solver->getVelocityVariable(), d_fluid_solver->getCurrentContext());
Pointer<PatchData<NDIM> > u_new_data = patch->getPatchData(d_fluid_solver->getVelocityVariable(), d_fluid_solver->getNewContext() );
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(u_current_data);
#endif
if (f_cc_data) setDataOnPatchCell(f_data, u_current_data, u_new_data, kappa, patch);
if (f_sc_data) setDataOnPatchSide(f_data, u_current_data, u_new_data, kappa, patch);
return;
}// setDataOnPatch
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
void
SpongeLayerForceFunction::setDataOnPatchCell(
Pointer<CellData<NDIM,double> > F_data,
Pointer<CellData<NDIM,double> > U_current_data,
Pointer<CellData<NDIM,double> > U_new_data,
const double kappa,
Pointer<Patch<NDIM> > patch)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(F_data && U_current_data);
#endif
const int cycle_num = d_fluid_solver->getCurrentCycleNumber();
const Box<NDIM>& patch_box = patch->getBox();
Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();
const double* const dx = pgeom->getDx();
const double* const x_lower = pgeom->getXLower();
const double* const x_upper = pgeom->getXUpper();
const IntVector<NDIM>& ratio = pgeom->getRatio();
const Box<NDIM> domain_box = Box<NDIM>::refine(d_grid_geometry->getPhysicalDomain()[0],ratio);
for (unsigned int location_index = 0; location_index < 2*NDIM; ++location_index)
{
const unsigned int axis = location_index / 2;
const unsigned int side = location_index % 2;
const bool is_lower = side == 0;
for (unsigned int d = 0; d < NDIM; ++d)
{
if (d_forcing_enabled[location_index][d] && pgeom->getTouchesRegularBoundary(axis,side))
{
Box<NDIM> bdry_box = domain_box;
const int offset = static_cast<int>(d_width[location_index]/dx[axis]);
if (is_lower)
{
bdry_box.upper(axis) = domain_box.lower(axis)+offset;
}
else
{
bdry_box.lower(axis) = domain_box.upper(axis)-offset;
}
for (Box<NDIM>::Iterator b(bdry_box*patch_box); b; b++)
{
const Index<NDIM>& i = b();
const double U_current = U_current_data ? (*U_current_data)(i,d) : 0.0;
const double U_new = U_new_data ? (*U_new_data )(i,d) : 0.0;
const double U = (cycle_num > 0) ? 0.5*(U_new+U_current) : U_current;
const double x = x_lower[axis] + dx[axis]*(static_cast<double>(i(axis)-patch_box.lower(axis))+0.5);
const double x_bdry = (is_lower ? x_lower[axis] : x_upper[axis]);
(*F_data)(i,d) = smooth_kernel((x-x_bdry)/d_width[location_index])*kappa*(0.0 - U);
}
}
}
}
return;
}// setDataOnPatchCell
void
SpongeLayerForceFunction::setDataOnPatchSide(
Pointer<SideData<NDIM,double> > F_data,
Pointer<SideData<NDIM,double> > U_current_data,
Pointer<SideData<NDIM,double> > U_new_data,
const double kappa,
Pointer<Patch<NDIM> > patch)
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(F_data && U_current_data);
#endif
const int cycle_num = d_fluid_solver->getCurrentCycleNumber();
const Box<NDIM>& patch_box = patch->getBox();
Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();
const double* const dx = pgeom->getDx();
const double* const x_lower = pgeom->getXLower();
const double* const x_upper = pgeom->getXUpper();
const IntVector<NDIM>& ratio = pgeom->getRatio();
const Box<NDIM> domain_box = Box<NDIM>::refine(d_grid_geometry->getPhysicalDomain()[0],ratio);
for (unsigned int location_index = 0; location_index < 2*NDIM; ++location_index)
{
const unsigned int axis = location_index / 2;
const unsigned int side = location_index % 2;
const bool is_lower = side == 0;
for (unsigned int d = 0; d < NDIM; ++d)
{
if (d_forcing_enabled[location_index][d] && pgeom->getTouchesRegularBoundary(axis,side))
{
Box<NDIM> bdry_box = domain_box;
const int offset = static_cast<int>(d_width[location_index]/dx[axis]);
if (is_lower)
{
bdry_box.upper(axis) = domain_box.lower(axis)+offset;
}
else
{
bdry_box.lower(axis) = domain_box.upper(axis)-offset;
}
for (Box<NDIM>::Iterator b(SideGeometry<NDIM>::toSideBox(bdry_box*patch_box,d)); b; b++)
{
const Index<NDIM>& i = b();
const SideIndex<NDIM> i_s(i, d, SideIndex<NDIM>::Lower);
const double U_current = U_current_data ? (*U_current_data)(i_s) : 0.0;
const double U_new = U_new_data ? (*U_new_data )(i_s) : 0.0;
const double U = (cycle_num > 0) ? 0.5*(U_new+U_current) : U_current;
const double x = x_lower[axis] + dx[axis]*static_cast<double>(i(axis)-patch_box.lower(axis));
const double x_bdry = (is_lower ? x_lower[axis] : x_upper[axis]);
(*F_data)(i_s) = smooth_kernel((x-x_bdry)/d_width[location_index])*kappa*(0.0 - U);
}
}
}
}
return;
}// setDataOnPatchSide
/////////////////////////////// NAMESPACE ////////////////////////////////////
} // namespace IBAMR
//////////////////////////////////////////////////////////////////////////////
| 40.429078
| 143
| 0.620998
|
MSV-Project
|
5e0a42aad38a7a811b6ba4a5e302da48833f8c39
| 410
|
cpp
|
C++
|
qtorch/quant/quant_cpu/sim_helper.cpp
|
drcut/QPyTorch
|
63c293178e8ce9e6e5b218dee96536e9c4ad1e5c
|
[
"MIT"
] | null | null | null |
qtorch/quant/quant_cpu/sim_helper.cpp
|
drcut/QPyTorch
|
63c293178e8ce9e6e5b218dee96536e9c4ad1e5c
|
[
"MIT"
] | null | null | null |
qtorch/quant/quant_cpu/sim_helper.cpp
|
drcut/QPyTorch
|
63c293178e8ce9e6e5b218dee96536e9c4ad1e5c
|
[
"MIT"
] | null | null | null |
#include "quant_cpu.h"
#include <math.h>
#include <stdint.h>
void fixed_min_max(int wl, int fl, bool symmetric, float* t_min, float* t_max) {
int sigma = -fl;
*t_min = -ldexp(1.0, wl-fl-1);
*t_max = -*t_min-ldexp(1.0, sigma);
if (symmetric) *t_min = *t_min+ldexp(1.0, sigma);
}
float round(float a, float r, int sigma) {
a = ldexp(a, -sigma);
a = floor(a+r);
a = ldexp(a, sigma);
return a;
}
| 22.777778
| 80
| 0.619512
|
drcut
|
5e0c5360fe650ce6853900162562497ca5f773a8
| 350
|
cpp
|
C++
|
Protected_Stack/hash.cpp
|
Great1ng/Huawei_Tasks
|
21f855f30df9806f81d5cedf8cd314a633174be1
|
[
"CC0-1.0"
] | null | null | null |
Protected_Stack/hash.cpp
|
Great1ng/Huawei_Tasks
|
21f855f30df9806f81d5cedf8cd314a633174be1
|
[
"CC0-1.0"
] | null | null | null |
Protected_Stack/hash.cpp
|
Great1ng/Huawei_Tasks
|
21f855f30df9806f81d5cedf8cd314a633174be1
|
[
"CC0-1.0"
] | null | null | null |
#include "hash.h"
uint32_t OAT_Hash(const void* key, size_t len)
{
uint32_t hash = 0;
const byte* bytes = (const byte*)key;
for (size_t i = 0; i < len; i++) {
hash += bytes[i];
hash += hash << 10;
hash ^= hash >> 6;
}
hash += hash << 3;
hash ^= hash >> 11;
hash += hash << 15;
return hash;
}
| 19.444444
| 46
| 0.491429
|
Great1ng
|
5e106dd16214046776b1153f29af623dfcc8448d
| 692
|
cpp
|
C++
|
YorozuyaGSLib/source/_ANIMUSKEY.cpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
YorozuyaGSLib/source/_ANIMUSKEY.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
YorozuyaGSLib/source/_ANIMUSKEY.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
#include <_ANIMUSKEY.hpp>
START_ATF_NAMESPACE
char _ANIMUSKEY::CovDBKey()
{
using org_ptr = char (WINAPIV*)(struct _ANIMUSKEY*);
return (org_ptr(0x1401bf2e0L))(this);
};
bool _ANIMUSKEY::IsFilled()
{
using org_ptr = bool (WINAPIV*)(struct _ANIMUSKEY*);
return (org_ptr(0x14010e3a0L))(this);
};
void _ANIMUSKEY::LoadDBKey(char pl_byKey)
{
using org_ptr = void (WINAPIV*)(struct _ANIMUSKEY*, char);
(org_ptr(0x140120520L))(this, pl_byKey);
};
void _ANIMUSKEY::SetRelease()
{
using org_ptr = void (WINAPIV*)(struct _ANIMUSKEY*);
(org_ptr(0x140076350L))(this);
};
END_ATF_NAMESPACE
| 26.615385
| 66
| 0.622832
|
lemkova
|
5e179293ff7e7fcda4ad64c770f75334b2610b00
| 9,325
|
cpp
|
C++
|
src/lib/PVRTexture.cpp
|
keestux/tuxcap
|
6298d14ad4dc57fd142d4c5f0ee2fa42cdd42bee
|
[
"MIT-0"
] | 2
|
2017-10-10T20:44:49.000Z
|
2022-02-09T09:08:04.000Z
|
src/lib/PVRTexture.cpp
|
keestux/tuxcap
|
6298d14ad4dc57fd142d4c5f0ee2fa42cdd42bee
|
[
"MIT-0"
] | null | null | null |
src/lib/PVRTexture.cpp
|
keestux/tuxcap
|
6298d14ad4dc57fd142d4c5f0ee2fa42cdd42bee
|
[
"MIT-0"
] | 2
|
2017-11-23T13:23:30.000Z
|
2019-12-12T21:41:02.000Z
|
#include <assert.h>
#include "PVRTexture.h"
#include "Common.h"
#include "SexyAppBase.h"
#include "PakInterface.h"
#include "GLState.h"
#ifdef USE_OPENGLES
#include <SDL_opengles.h>
#else
#include <SDL_opengl.h>
#endif
enum
{
kPVRTextureFlagType565 = 2,
kPVRTextureFlagTypeOGL4444 = 16, // OGL_RGBA_4444
kPVRTextureFlagTypeOGL5551 = 17, // OGL_RGBA_5551
kPVRTextureFlagTypeOGL565 = 19, // OGL_RGB_565
kPVRTextureFlagTypePVRTC_2 = 24,
kPVRTextureFlagTypePVRTC_4 = 25,
};
#if TARGET_OS_IPHONE == 0
// FIXME. Get this from an include file. Perhaps PVRTexLib.h
// Values for glCompressedTexImage2D, from OpenGLES/ESn/glext.h
#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
#endif
#define PVR_TEXTURE_FLAG_TYPE_MASK 0xff
using namespace Sexy;
using namespace std;
typedef struct _PVRTexHeader
{
uint32_t headerLength;
uint32_t height;
uint32_t width;
uint32_t numMipmaps;
uint32_t flags;
uint32_t dataLength;
uint32_t bpp;
uint32_t bitmaskRed;
uint32_t bitmaskGreen;
uint32_t bitmaskBlue;
uint32_t bitmaskAlpha;
uint32_t pvrTag;
uint32_t numSurfs;
} PVRTexHeader;
static const char gPVRTexIdentifier[] = "PVR!";
PVRTexture::PVRTexture() :
mPVRTextureFlagType(0)
{
mImageData.clear();
mImageDataLength.clear();
}
PVRTexture::~PVRTexture()
{
for (size_t i = 0; i < mImageData.size(); i++) {
delete [] mImageData[i];
}
}
bool PVRTexture::unpackPVRData(uint8_t* data)
{
// Forget about endianness, just accept LE.
const PVRTexHeader * header = (const PVRTexHeader *)data;
// Sanity check
if (header->headerLength != sizeof(PVRTexHeader)) {
// TODO. Throw exception
return false;
}
if (header->pvrTag != *(uint32_t*)gPVRTexIdentifier) {
// TODO. Throw exception
return false;
}
mPVRTextureFlagType = header->flags & PVR_TEXTURE_FLAG_TYPE_MASK;
mHasAlpha = header->bitmaskAlpha != 0 ? true : false;
// We only accept a limited set of formats
switch (mPVRTextureFlagType) {
#if TARGET_OS_IPHONE
case kPVRTextureFlagTypePVRTC_4: //fallthrough
case kPVRTextureFlagTypePVRTC_2:
mPow2 = true;
mSquare = true;
break;
#endif
case kPVRTextureFlagType565: //fallthrough
case kPVRTextureFlagTypeOGL4444:
case kPVRTextureFlagTypeOGL5551:
case kPVRTextureFlagTypeOGL565:
mPow2 = false;
mSquare = true;
break;
default:
// Just return false, to signal caller "we failed to read"
return false;
}
mWidth = header->width;
mHeight = header->height;
// The following loop is to load MIPmaps, but we are (probably) just interested in the first.
int width = mWidth;
int height = mHeight;
uint32_t dataOffset = sizeof(PVRTexHeader);
int blockSize = 0;
int widthBlocks = 0;
int heightBlocks = 0;
int dataSize;
while (dataOffset < header->dataLength) {
// Do something
if (mPVRTextureFlagType == kPVRTextureFlagTypePVRTC_4) {
blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
widthBlocks = width / 4;
heightBlocks = height / 4;
// Clamp to minimum number of blocks
if (widthBlocks < 2)
widthBlocks = 2;
if (heightBlocks < 2)
heightBlocks = 2;
dataSize = widthBlocks * heightBlocks * ((blockSize * 4) / 8);
}
else if (mPVRTextureFlagType == kPVRTextureFlagTypePVRTC_2) {
blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
widthBlocks = width / 8;
heightBlocks = height / 4;
// Clamp to minimum number of blocks
if (widthBlocks < 2)
widthBlocks = 2;
if (heightBlocks < 2)
heightBlocks = 2;
dataSize = widthBlocks * heightBlocks * ((blockSize * 2) / 8);
}
else if (mPVRTextureFlagType == kPVRTextureFlagType565
|| mPVRTextureFlagType == kPVRTextureFlagTypeOGL565
|| mPVRTextureFlagType == kPVRTextureFlagTypeOGL4444
|| mPVRTextureFlagType == kPVRTextureFlagTypeOGL5551) {
dataSize = width * height * 2;
}
uint8_t * blob = new uint8_t[dataSize];
memcpy(blob, data + dataOffset, dataSize);
mImageData.push_back(blob);
mImageDataLength.push_back(dataSize);
dataOffset += dataSize;
width = std::max(width >> 1, 1);
height = std::max(height >> 1, 1);
}
return true;
}
bool PVRTexture::initWithContentsOfFile(const string& fname)
{
string myFname = gSexyAppBase->GetAppResourceFileName(fname);
PFILE* file = p_fopen(myFname.c_str(), "r");
if (file == NULL) {
// TODO. Throw exception
return false;
}
int size = p_size(file);
uint8_t* buffer = new uint8_t[size];
int res = p_fread((void*)buffer, sizeof(uint8_t), size * sizeof(*buffer), file);
if (size != res) {
p_fclose(file);
delete[] buffer;
// TODO. Throw exception
return false;
}
if (!unpackPVRData(buffer)) {
p_fclose(file);
delete [] buffer;
// Just return false, to signal caller "we failed to read"
return false;
}
p_fclose(file);
delete [] buffer;
return true;
}
// Copy 2 bytes per pixel into a newly allocated buffer
static uint8_t * get_rect_2(uint8_t * data, int width, int height, int x, int y, int w, int h)
{
int bpp = 2; // bytes per pixel
int dstlen = w * h * bpp;
uint8_t * dst = new uint8_t[dstlen];
memset(dst, 0, dstlen);
for (int j = 0; j < h && (y + j) < height; j++) {
uint8_t * srcrow = &data[((j + y) * width + x) * bpp];
int nrbytes = w * bpp;
if (x + w > width) {
nrbytes = (width - x) * bpp;
}
memcpy(&dst[(j * w * bpp)], srcrow, nrbytes);
}
return dst;
}
GLuint PVRTexture::CreateTexture(int x, int y, int w, int h)
{
// We only account for the first data image in the PVR (no MIPmaps)
if (mImageData.size() == 0) {
assert(0);
}
uint8_t * data = mImageData[0];
int datalength = mImageDataLength[0];
/* Create an OpenGL texture for thing */
GLuint texture;
GLint glerr;
glGenTextures(1, &texture);
GLState::getInstance()->bindTexture(GL_TEXTURE_2D, texture);
// These are the same as in MemoryImage::CreateTexture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_PRIORITY, 1);
GLenum internalFormat;
switch (mPVRTextureFlagType) {
case kPVRTextureFlagTypePVRTC_4:
if (!(x == 0 && y == 0)) {
// Not sure what to do here.
assert(0);
}
if (mHasAlpha)
internalFormat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
else
internalFormat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
glCompressedTexImage2D(GL_TEXTURE_2D, 0, internalFormat, w, h, 0, datalength, data);
break;
case kPVRTextureFlagTypePVRTC_2:
if (!(x == 0 && y == 0)) {
// Not sure what to do here.
assert(0);
}
if (mHasAlpha)
internalFormat = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
else
internalFormat = GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
glCompressedTexImage2D(GL_TEXTURE_2D, 0, internalFormat, w, h, 0, datalength, data);
break;
case kPVRTextureFlagType565:
case kPVRTextureFlagTypeOGL565:
{
// Copy the data for this rect
uint8_t * data2 = get_rect_2(data, mWidth, mHeight, x, y, w, h);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data2);
delete [] data2;
}
break;
case kPVRTextureFlagTypeOGL4444:
{
// Copy the data for this rect
uint8_t * data2 = get_rect_2(data, mWidth, mHeight, x, y, w, h);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data2);
delete [] data2;
}
break;
case kPVRTextureFlagTypeOGL5551:
{
// Copy the data for this rect
uint8_t * data2 = get_rect_2(data, mWidth, mHeight, x, y, w, h);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, data2);
delete [] data2;
}
break;
default:
assert(0);
break;
}
glerr = glGetError();
// TODO. Check error code.
return texture;
}
void PVRTexture::DoPurgeBits()
{
// This is called after CreateTexture
// Delete the data buffers
for (size_t i = 0; i < mImageData.size(); i++) {
delete [] mImageData[i];
}
mImageData.clear();
mImageDataLength.clear();
}
| 30.374593
| 100
| 0.621233
|
keestux
|
5e187d26864debd62bd8356a62b99f85b337be61
| 7,199
|
hpp
|
C++
|
src/Array.hpp
|
sk409/HPC2018
|
d189e7ff20f78e186b05079e5b4108fdbeccd890
|
[
"FSFAP"
] | null | null | null |
src/Array.hpp
|
sk409/HPC2018
|
d189e7ff20f78e186b05079e5b4108fdbeccd890
|
[
"FSFAP"
] | null | null | null |
src/Array.hpp
|
sk409/HPC2018
|
d189e7ff20f78e186b05079e5b4108fdbeccd890
|
[
"FSFAP"
] | null | null | null |
//------------------------------------------------------------------------------
/// @file
/// @author ハル研究所プログラミングコンテスト実行委員会
///
/// @copyright Copyright (c) 2018 HAL Laboratory, Inc.
/// @attention このファイルの利用は、同梱のREADMEにある
/// 利用条件に従ってください。
//------------------------------------------------------------------------------
#pragma once
//------------------------------------------------------------------------------
#include <array>
#include "Assert.hpp"
//------------------------------------------------------------------------------
namespace hpc {
/// 最大要素数を指定する可変長配列。
/// @note std::vector と違い、初期化時に std::array で最大数分のメモリを確保するため
/// このクラスから new , delete が呼ばれることはありません。
/// @attention TElement にはデストラクタを持つクラスを指定しないでください。
/// デストラクタは正しく呼び出されません。
template <typename TElement, int TCapacity>
class Array
{
public:
/// @name typedef
//@{
typedef std::array<TElement, TCapacity> ArrayType;
typedef typename ArrayType::iterator iterator;
typedef typename ArrayType::const_iterator const_iterator;
//@}
/// @name コンストラクタ/デストラクタ
//@{
/// コンストラクタ。
/// @note 最大要素数分のデフォルトコンストラクタが呼び出されます。
/// POD 型の場合は 0 で埋められます。
/// @attention 要素数が多い場合はパフォーマンスに注意してください。
inline Array();
/// 配列を与えて初期化するコンストラクタ。
/// @note TElement がデフォルトコンストラクタを持たない場合は
/// このコンストラクタを使わなければなりません。
/// @attention 要素数が多い場合はパフォーマンスに注意してください。
explicit inline Array(const ArrayType& aArray);
/// デストラクタ。
inline ~Array();
//@}
/// @name コンテンツ処理
//@{
/// 要素を配列の末尾に追加する。
/// @param aData 追加する要素。
inline void add(const TElement& aData);
/// 全ての要素を削除する。
inline void clear();
/// 指定位置の要素を削除し、配列を詰める。
/// @param aIndex 削除する要素の位置。
inline void erase(int aIndex);
/// 指定位置に末尾の要素をコピーし、末尾の要素を削除する。
/// @note オブジェクトの順序が保存されない代わりに、高速に要素を削除できます。
/// @param aIndex 削除する要素の位置。
inline void unstableFastErase(int aIndex);
//@}
/// @name 要素数
//@{
/// 格納されている要素数を取得する。
/// @note 戻り値の型が size_t ではないため、 size() と区別した名前を付けています。
inline int count() const;
/// 格納可能な最大要素数を取得する。
/// @note static const int でないのは、コンパイラによる挙動の違いを避けるためです。
inline int maxCount() const;
/// 配列が空かどうかを取得する。
inline bool isEmpty() const;
/// 配列が満杯かどうかを取得する。
inline bool isFull() const;
//@}
/// @name 要素アクセス
//@{
/// インデックス指定で要素を取得する。
/// @note インデックスの範囲チェックを行います。
/// @param aIndex アクセスしたい要素の位置。
inline TElement& operator[](const int aIndex);
/// インデックス指定で要素を取得する。
/// @note インデックスの範囲チェックを行います。
/// @param aIndex アクセスしたい要素の位置。
inline const TElement& operator[](const int aIndex) const;
//@}
/// @name イテレータ
//@{
/// begin イテレータを取得する。
inline iterator begin();
/// end イテレータを取得する。
inline iterator end();
/// begin イテレータを取得する。
inline const_iterator begin() const;
/// end イテレータを取得する。
inline const_iterator end() const;
//@}
private:
/// @name プライベートメンバ変数
//@{
ArrayType mContainer;
int mCount;
//@}
};
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
Array<TElement, TCapacity>::Array()
: mContainer()
, mCount(0)
{
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
Array<TElement, TCapacity>::Array(const ArrayType& aArray)
: mContainer(aArray)
, mCount(TCapacity)
{
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
Array<TElement, TCapacity>::~Array()
{
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
void Array<TElement, TCapacity>::add(const TElement& aData)
{
HPC_ASSERT(!isFull());
// 追加
mContainer[mCount] = aData;
++mCount;
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
void Array<TElement, TCapacity>::clear()
{
mCount = 0;
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
void Array<TElement, TCapacity>::erase(int aIndex)
{
HPC_ASSERT_MIN_TERM_I(aIndex, 0, count());
for (int i = aIndex; i < count() - 1; ++i) {
mContainer[i] = mContainer[i + 1];
}
--mCount;
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
void Array<TElement, TCapacity>::unstableFastErase(int aIndex)
{
HPC_ASSERT_MIN_TERM_I(aIndex, 0, count());
// 指定位置の要素に末尾の要素を上書き
mContainer[aIndex] = mContainer[count() - 1];
// 末尾の要素を捨てる
--mCount;
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
int Array<TElement, TCapacity>::count() const
{
return mCount;
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
int Array<TElement, TCapacity>::maxCount() const
{
return TCapacity;
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
bool Array<TElement, TCapacity>::isEmpty() const
{
return mCount == 0;
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
bool Array<TElement, TCapacity>::isFull() const
{
return mCount == TCapacity;
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
TElement& Array<TElement, TCapacity>::operator[](const int aIndex)
{
HPC_ASSERT_MIN_TERM_I(aIndex, 0, mCount);
return mContainer[aIndex];
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
const TElement& Array<TElement, TCapacity>::operator[](const int aIndex) const
{
HPC_ASSERT_MIN_TERM_I(aIndex, 0, mCount);
return mContainer[aIndex];
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
typename Array<TElement, TCapacity>::iterator Array<TElement, TCapacity>::begin()
{
return mContainer.begin();
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
typename Array<TElement, TCapacity>::iterator Array<TElement, TCapacity>::end()
{
return mContainer.begin() + mCount;
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
typename Array<TElement, TCapacity>::const_iterator Array<TElement, TCapacity>::begin() const
{
return mContainer.begin();
}
//------------------------------------------------------------------------------
template <typename TElement, int TCapacity>
typename Array<TElement, TCapacity>::const_iterator Array<TElement, TCapacity>::end() const
{
return mContainer.begin() + mCount;
}
} // namespace
// EOF
| 29.028226
| 93
| 0.51396
|
sk409
|
5e21e2988b51b400a27334c32236f4bb542a70db
| 3,012
|
cxx
|
C++
|
Porter5/scripts/Predict_BRNN/NNt.cxx
|
LifeWorks/SIEVE
|
8ba16402f0a15a0ae040d54cf2674e7d00ef4be0
|
[
"BSD-2-Clause"
] | null | null | null |
Porter5/scripts/Predict_BRNN/NNt.cxx
|
LifeWorks/SIEVE
|
8ba16402f0a15a0ae040d54cf2674e7d00ef4be0
|
[
"BSD-2-Clause"
] | null | null | null |
Porter5/scripts/Predict_BRNN/NNt.cxx
|
LifeWorks/SIEVE
|
8ba16402f0a15a0ae040d54cf2674e7d00ef4be0
|
[
"BSD-2-Clause"
] | null | null | null |
// NNt ver. 3.02 (27/11/2003)
//
// Copyright (C) Gianluca Pollastri 2003
#include "NNt.h"
NNt::NNt(istream& is)
{
is >> NO >> NH >> NI >> NIr >> which >> outp >> inp;
upper= new Layer_tanh(is);
if (outp)
upper->set_output(1);
upper->set_ninput(2);
lower=new Layer_tanh(is);
lower->set_ninput(inp);
int i;
NK=new int[NI];
NItot=0;
for (i=0; i<NI; i++) {
NK[i]=lower->get_NK()[i];
NItot += NK[i];
}
NK2=new int[NIr];
for (i=0; i<NIr; i++)
NK2[i]=lower->get_NK()[NI+i];
backprop=new double[NItot+NIr];
}
void
NNt::read(istream& is)
{
is >> NO >> NH >> NI >> NIr >> which >> outp >> inp;
upper->read(is);
if (outp)
upper->set_output(1);
upper->set_ninput(2);
lower->read(is);
lower->set_ninput(inp);
int i;
NItot =0;
for (i=0; i<NI; i++) {
NK[i]=lower->get_NK()[i];
NItot += NK[i];
}
for (i=0; i<NIr; i++)
NK2[i]=lower->get_NK()[NI+i];
}
void
NNt::forward(int* I)
{
lower->forward(I);
upper->forward(lower->out(),lower->out());
}
void
NNt::forward(double* I)
{
lower->forward(I);
upper->forward(lower->out(),lower->out());
}
void
NNt::forward(int* I1,double* I2)
{
lower->forward(I1,I2);
upper->forward(lower->out(),lower->out());
}
void
NNt::forward(double* I1,double* I2)
{
lower->forward(I1,I2);
upper->forward(lower->out(),lower->out());
}
double
NNt::backward(double* t, double weight)
{
double err=upper->backward(t,weight);
double BKD[1024];
for (int i=0;i<NH;i++)
BKD[i]=upper->back_out()[i];
lower->backward(BKD,weight);
if (inp==1)
for (int r=NItot;r<NItot+NIr;r++)
backprop[r]=lower->back_out()[r];
else if (inp==2)
for (int r=0;r<NItot+NIr;r++)
backprop[r]=lower->back_out()[r];
return err;
}
void
NNt::gradient(int* I, double* t)
{
upper->gradient();
lower->gradient(I);
}
void
NNt::gradient(double* I, double* t)
{
upper->gradient();
lower->gradient(I);
}
void
NNt::gradient(int* I1,double* I2, double* t)
{
upper->gradient();
lower->gradient(I1,I2);
}
void
NNt::gradient(double* I1,double* I2, double* t)
{
upper->gradient();
lower->gradient(I1,I2);
}
void
NNt::resetGradient()
{
lower->resetGradient();
upper->resetGradient();
}
void
NNt::updateWeights(double epsilon)
{
lower->updateWeights(epsilon);
upper->updateWeights(epsilon);
}
void
NNt::updateWeightsL1(double epsilon)
{
lower->updateWeightsL1(epsilon);
upper->updateWeightsL1(epsilon);
}
void
NNt::updateWeightsClipped(double epsilon)
{
lower->updateWeightsClipped(epsilon);
upper->updateWeightsClipped(epsilon);
}
void
NNt::initWeights(int seed)
{
lower->initWeights(seed);
upper->initWeights(seed);
}
void
NNt::write(ostream& os)
{
os << NO << " " << NH<< " " << NI<< " " << NIr <<" ";
os << which << " " << outp << " " << inp << "\n";
upper->write(os);
lower->write(os);
}
| 17.016949
| 56
| 0.570385
|
LifeWorks
|
5e22c0a9c4ebce38ccee3a665c2cce89646b12c1
| 920
|
hpp
|
C++
|
components/respawnWaves/ui/respawnTitle.hpp
|
Bubbus/CAyZ
|
d2e306243e0574c30326fcea2a342ed5b8feefdb
|
[
"Unlicense"
] | null | null | null |
components/respawnWaves/ui/respawnTitle.hpp
|
Bubbus/CAyZ
|
d2e306243e0574c30326fcea2a342ed5b8feefdb
|
[
"Unlicense"
] | 18
|
2020-08-11T20:26:00.000Z
|
2020-11-18T01:43:15.000Z
|
components/respawnWaves/ui/respawnTitle.hpp
|
Bubbus/CAyZ
|
d2e306243e0574c30326fcea2a342ed5b8feefdb
|
[
"Unlicense"
] | null | null | null |
#include "../ui_macros.hpp"
class CA2_RespawnTitle
{
idd = 13176;
movingEnable = false;
enableSimulation = true;
fadein = 1;
duration = 7;
fadeout = 3;
onLoad = "_this call f_fnc_respawnTitle_onLoad;";
class ControlsBackground
{
class WelcomeBack: CA2_DefaultText
{
idc = 1000;
style = ST_CENTER;
text = "Welcome back.";
font = "PuristaBold";
x = 9 * GUI_GRID_W + GUI_GRID_X;
y = 0.5 * GUI_GRID_H + GUI_GRID_Y;
w = 22 * GUI_GRID_W;
h = 2.5 * GUI_GRID_H;
sizeEx = 3 * GUI_GRID_H;
};
class InfoText: CA2_DefaultStructuredText
{
idc = IDC_RESPAWNTITLE_INFOTEXT;
text = "";
x = 8.5 * GUI_GRID_W + GUI_GRID_X;
y = 3.5 * GUI_GRID_H + GUI_GRID_Y;
w = 23 * GUI_GRID_W;
h = 4.5 * GUI_GRID_H;
};
};
};
| 20.909091
| 53
| 0.526087
|
Bubbus
|
5e22c6279cb882bd1bda4e5dd0fd48b87894b4e0
| 444
|
cpp
|
C++
|
baekjoon/9020/9020.cpp
|
3-24/Competitive-Programming
|
8cb3b85bf89db2c173cb0b136de27f2983f335fc
|
[
"MIT"
] | 1
|
2019-07-15T00:27:37.000Z
|
2019-07-15T00:27:37.000Z
|
baekjoon/9020/9020.cpp
|
3-24/Competitive-Programming
|
8cb3b85bf89db2c173cb0b136de27f2983f335fc
|
[
"MIT"
] | null | null | null |
baekjoon/9020/9020.cpp
|
3-24/Competitive-Programming
|
8cb3b85bf89db2c173cb0b136de27f2983f335fc
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <math.h>
int isPrime(int m){
if (m == 1){
return 0;
}
if (m==2){
return 1;
}
int t = (int)(pow(m,0.5));
for (int i=2;i<=t+1;i++){
if (!(m % i)){
return 0;
}
}
return 1;
}
int main(){
int T,n,i;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
for (i=n/2;i>1;i--){
if (isPrime(i) && isPrime(n-i)){
break;
}
}
printf("%d %d\n",i,n-i);
}
}
| 13.454545
| 38
| 0.40991
|
3-24
|
5e2779612420145b3146155819ab41d66199d001
| 2,274
|
hpp
|
C++
|
src/tests/test_subscriber.hpp
|
aaronchongth/ros2_tensorrt
|
e1947bc68d830168da833eac92dee402dad76908
|
[
"MIT"
] | 3
|
2019-02-22T17:21:01.000Z
|
2020-06-01T05:06:48.000Z
|
src/tests/test_subscriber.hpp
|
aaronchongth/ros2_tensorrt
|
e1947bc68d830168da833eac92dee402dad76908
|
[
"MIT"
] | null | null | null |
src/tests/test_subscriber.hpp
|
aaronchongth/ros2_tensorrt
|
e1947bc68d830168da833eac92dee402dad76908
|
[
"MIT"
] | 1
|
2020-06-01T04:23:00.000Z
|
2020-06-01T04:23:00.000Z
|
#pragma once
// STL
#include <chrono>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// ROS2
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/float32_multi_array.hpp"
using std::placeholders::_1;
using namespace std::chrono_literals;
// TensorRT
#include "tensorrt_base.hpp"
// CXXOPTS
#include "cxxopts/cxxopts.hpp"
namespace opt = cxxopts;
struct TestSubscriberConfig {
std::string node_name = "test_inference_results_node";
std::string sub_topic = "output_topic";
int gt_label = 281;
};
class TestSubscriber : public rclcpp::Node {
public:
explicit TestSubscriber(const TestSubscriberConfig &config)
: Node(config.node_name),
sub_topic_(config.sub_topic),
gt_class_(config.gt_label) {
test_array_subscriber_ =
this->create_subscription<std_msgs::msg::Float32MultiArray>(
sub_topic_,
std::bind(&TestSubscriber::test_array_callback, this, _1));
info_timer_ = this->create_wall_timer(
1000ms, std::bind(&TestSubscriber::info_timer_callback, this));
std::cout << "<STATUS> Test inference result subscriber initialized, ready "
"for callback inference."
<< std::endl;
}
private:
int gt_class_, pred_class_;
int n_messages_ = 0;
rclcpp::TimerBase::SharedPtr info_timer_;
std::string sub_topic_;
rclcpp::Subscription<std_msgs::msg::Float32MultiArray>::SharedPtr
test_array_subscriber_;
void test_array_callback(
const std_msgs::msg::Float32MultiArray::SharedPtr msg) {
// try to get topK results
int n_elems = msg->layout.dim[0].size;
std::vector<float> output(&(msg->data[0]), &(msg->data[0]) + 1000);
auto top = tensorrt_common::topK<float>(output, 1);
pred_class_ = top[0];
n_messages_++;
}
void info_timer_callback() {
std::cout << std::fixed << std::setprecision(2);
std::cout << "<TEST_RESULTS> Rate: "
<< static_cast<float>(1000.0 / n_messages_)
<< "Hz; Inference Classification: ";
n_messages_ = 0;
if (gt_class_ == pred_class_)
std::cout << "PASS" << std::endl;
else
std::cout << "FAILED, pred: " << pred_class_ << " gt: " << gt_class_
<< std::endl;
}
};
| 27.731707
| 80
| 0.658311
|
aaronchongth
|
5e28737df98468e85700f7e10073213004d1bb1d
| 13,393
|
cpp
|
C++
|
emerald/sph2d_box/iisph_pseudo_ap_ops.cpp
|
blackencino/emerald
|
3c4823dbdeff7c63007ff359d262608227f5433f
|
[
"Apache-2.0"
] | 3
|
2020-08-16T17:56:25.000Z
|
2021-02-25T21:55:39.000Z
|
emerald/sph2d_box/iisph_pseudo_ap_ops.cpp
|
blackencino/emerald
|
3c4823dbdeff7c63007ff359d262608227f5433f
|
[
"Apache-2.0"
] | null | null | null |
emerald/sph2d_box/iisph_pseudo_ap_ops.cpp
|
blackencino/emerald
|
3c4823dbdeff7c63007ff359d262608227f5433f
|
[
"Apache-2.0"
] | null | null | null |
#include <emerald/sph2d_box/iisph_ap_ops.h>
#include <emerald/sph_common/common.h>
#include <emerald/sph_common/kernels.h>
#include <emerald/util/format.h>
#include <fmt/format.h>
#include <algorithm>
#include <atomic>
#include <utility>
namespace emerald::sph2d_box {
using namespace emerald::sph_common;
using namespace emerald::util;
//------------------------------------------------------------------------------
void iisph_pseudo_ap_density_stars_and_pseudo_diagonals(
size_t const particle_count,
float const dt,
float const target_density,
float* const density_stars,
float* const pseudo_diagonals,
float const* const densities,
float const* const fluid_volumes,
V2f const* const fluid_velocities,
Neighborhood_pointers const fluid_neighborhood,
float const* const solid_volumes,
V2f const* const solid_velocities,
Neighborhood_pointers const solid_neighborhood) {
for_each_iota(particle_count, [=](auto const particle_index) {
auto const fluid_nbhd_count = fluid_neighborhood.counts[particle_index];
auto const solid_nbhd_count = solid_neighborhood.counts[particle_index];
if (!(fluid_nbhd_count + solid_nbhd_count)) {
density_stars[particle_index] = densities[particle_index];
pseudo_diagonals[particle_index] = 0.0f;
return;
}
auto const self_mass = fluid_volumes[particle_index] * target_density;
auto const self_density = densities[particle_index];
auto const self_velocity = fluid_velocities[particle_index];
V2f sum_m_gradw{0.0f, 0.0f};
float sum_m_gradw_dot_gradw = 0.0f;
float divergence = 0.0f;
// Loop over fluids
if (fluid_nbhd_count) {
auto const& nbhd_indices =
fluid_neighborhood.indices[particle_index];
auto const& nbhd_kernel_gradients =
fluid_neighborhood.kernel_gradients[particle_index];
for (uint8_t j = 0; j < fluid_nbhd_count; ++j) {
auto const neighbor_particle_index = nbhd_indices[j];
auto const grad_w = nbhd_kernel_gradients[j];
auto const neighbor_mass =
fluid_volumes[neighbor_particle_index] * target_density;
sum_m_gradw += neighbor_mass * grad_w;
sum_m_gradw_dot_gradw += neighbor_mass * grad_w.dot(grad_w);
auto const delta_vel =
self_velocity - fluid_velocities[neighbor_particle_index];
divergence += neighbor_mass * delta_vel.dot(grad_w);
}
}
// Loop over solids
if (solid_nbhd_count) {
auto const& nbhd_indices =
solid_neighborhood.indices[particle_index];
auto const& nbhd_kernel_gradients =
solid_neighborhood.kernel_gradients[particle_index];
for (uint8_t j = 0; j < solid_nbhd_count; ++j) {
auto const neighbor_particle_index = nbhd_indices[j];
auto const grad_w = nbhd_kernel_gradients[j];
auto const neighbor_mass =
solid_volumes[neighbor_particle_index] * target_density;
sum_m_gradw += neighbor_mass * grad_w;
auto const delta_vel =
self_velocity - solid_velocities[neighbor_particle_index];
divergence += neighbor_mass * delta_vel.dot(grad_w);
}
}
auto const numer =
-(sum_m_gradw.dot(sum_m_gradw) + self_mass * sum_m_gradw_dot_gradw);
auto const denom = sqr(self_density);
pseudo_diagonals[particle_index] =
safe_divide(numer, denom).value_or(0.0);
// auto const self_density_sqr = sqr(self_density);
// sum_m_gradw_dot_gradw *= self_mass;
// if (is_safe_divide(sum_m_gradw, self_density) &&
// is_safe_divide(sum_m_gradw_dot_gradw, self_density_sqr)) {
// sum_m_gradw /= self_density;
// sum_m_gradw_dot_gradw /= self_density_sqr;
// auto const aii =
// sum_m_gradw.dot(sum_m_gradw) + sum_m_gradw_dot_gradw;
// pseudo_diagonals[particle_index] = -aii;
// } else {
// pseudo_diagonals[particle_index] = 0.0f;
// }
density_stars[particle_index] = self_density + dt * divergence;
});
}
//------------------------------------------------------------------------------
static void iisph_pseudo_ap_compute_pseudo_pressure_displacements_partial(
size_t const particle_count,
bool const boundary,
float const target_density,
V2f* const pseudo_pressure_displacements,
float const* const pseudo_pressures,
float const* const densities,
float const* const neighbor_volumes,
Neighborhood_pointers const neighborhood) {
for_each_iota(particle_count, [=](auto const particle_index) {
auto const nbhd_count = neighborhood.counts[particle_index];
if (!nbhd_count) {
if (!boundary) {
pseudo_pressure_displacements[particle_index] = {0.0f, 0.0f};
}
return;
}
auto const self_pseudo_pressure = pseudo_pressures[particle_index];
auto const self_density = densities[particle_index];
auto const p_over_rho_sqr =
safe_divide(self_pseudo_pressure, sqr(self_density)).value_or(0.0f);
V2f pseudo_pressure_displacement{0.0f, 0.0f};
auto const& nbhd_indices = neighborhood.indices[particle_index];
auto const& nbhd_kernel_gradients =
neighborhood.kernel_gradients[particle_index];
if (boundary) {
auto const coeff = p_over_rho_sqr;
for (uint8_t j = 0; j < nbhd_count; ++j) {
auto const neighbor_particle_index = nbhd_indices[j];
auto const neighbor_mass =
target_density * neighbor_volumes[neighbor_particle_index];
auto const grad_w = nbhd_kernel_gradients[j];
pseudo_pressure_displacement +=
(-neighbor_mass * coeff) * grad_w;
}
} else {
for (uint8_t j = 0; j < nbhd_count; ++j) {
auto const neighbor_particle_index = nbhd_indices[j];
auto const neighbor_mass =
target_density * neighbor_volumes[neighbor_particle_index];
auto const grad_w = nbhd_kernel_gradients[j];
auto const neighbor_pseudo_pressure =
pseudo_pressures[neighbor_particle_index];
auto const neighbor_density =
densities[neighbor_particle_index];
auto const coeff =
p_over_rho_sqr +
safe_divide(neighbor_pseudo_pressure, sqr(neighbor_density))
.value_or(0.0f);
pseudo_pressure_displacement +=
(-neighbor_mass * coeff) * grad_w;
}
}
if (boundary) {
pseudo_pressure_displacements[particle_index] +=
pseudo_pressure_displacement;
} else {
pseudo_pressure_displacements[particle_index] =
pseudo_pressure_displacement;
}
});
}
void iisph_pseudo_ap_compute_pseudo_pressure_displacements(
size_t const particle_count,
float const target_density,
V2f* const pseudo_pressure_displacements,
float const* const pseudo_pressures,
float const* const densities,
float const* const fluid_volumes,
Neighborhood_pointers const fluid_neighborhood,
float const* const solid_volumes,
Neighborhood_pointers const solid_neighborhood) {
iisph_pseudo_ap_compute_pseudo_pressure_displacements_partial(
particle_count,
false,
target_density,
pseudo_pressure_displacements,
pseudo_pressures,
densities,
fluid_volumes,
fluid_neighborhood);
iisph_pseudo_ap_compute_pseudo_pressure_displacements_partial(
particle_count,
true,
target_density,
pseudo_pressure_displacements,
pseudo_pressures,
densities,
solid_volumes,
solid_neighborhood);
}
std::pair<float, float> iisph_pseudo_ap_iterate_pseudo_pressures_in_place(
size_t const particle_count,
float const target_density,
float const omega,
float* const pseudo_pressures,
float const* const density_stars,
V2f const* const pseudo_pressure_displacements,
float const* const pseudo_diagonals,
float const* const fluid_volumes,
Neighborhood_pointers const fluid_neighborhood,
float const* const solid_volumes,
Neighborhood_pointers const solid_neighborhood) {
if (!particle_count) { return {0.0f, 0.0f}; }
// Also computes the average density variation
std::atomic<uint64_t> integral_error_sum = 0;
std::atomic<float> error_max = 0.0f;
for_each_iota(
particle_count,
[=, &integral_error_sum, &error_max](auto const particle_index) {
auto const fluid_nbhd_count =
fluid_neighborhood.counts[particle_index];
auto const solid_nbhd_count =
solid_neighborhood.counts[particle_index];
if (!fluid_nbhd_count && !solid_nbhd_count) {
pseudo_pressures[particle_index] = 0.0f;
return;
}
// This is checking to see whether a sentinel value was set during
// the computation of the pseudo_diagonal. We'll check proper
// proportional safe divides below.
auto const pseudo_diagonal = pseudo_diagonals[particle_index];
if (pseudo_diagonal == 0.0f) {
pseudo_pressures[particle_index] = 0.0f;
return;
}
float Api = 0.0f;
auto const self_pseudo_pressure_displacement =
pseudo_pressure_displacements[particle_index];
if (fluid_nbhd_count) {
auto const& nbhd_indices =
fluid_neighborhood.indices[particle_index];
auto const& nbhd_kernel_gradients =
fluid_neighborhood.kernel_gradients[particle_index];
for (uint8_t j = 0; j < fluid_nbhd_count; ++j) {
auto const neighbor_particle_index = nbhd_indices[j];
auto const neighbor_mass =
target_density * fluid_volumes[neighbor_particle_index];
auto const grad_w = nbhd_kernel_gradients[j];
auto const neighbor_pseudo_pressure_displacement =
pseudo_pressure_displacements[neighbor_particle_index];
Api +=
neighbor_mass * ((self_pseudo_pressure_displacement -
neighbor_pseudo_pressure_displacement)
.dot(grad_w));
}
}
if (solid_nbhd_count) {
auto const& nbhd_indices =
solid_neighborhood.indices[particle_index];
auto const& nbhd_kernel_gradients =
solid_neighborhood.kernel_gradients[particle_index];
for (uint8_t j = 0; j < solid_nbhd_count; ++j) {
auto const neighbor_particle_index = nbhd_indices[j];
auto const neighbor_mass =
target_density * solid_volumes[neighbor_particle_index];
auto const grad_w = nbhd_kernel_gradients[j];
Api += neighbor_mass *
(self_pseudo_pressure_displacement.dot(grad_w));
}
}
auto const source = target_density - density_stars[particle_index];
auto const error = std::max(
0.0f, safe_divide(Api - source, target_density).value_or(0.0f));
// fmt::print("Error {}: {}\n", particle_index, error);
update_atomic_max(error_max, error);
integral_error_sum += static_cast<uint64_t>(error * 1000.0f);
auto const old_pseudo_pressure = pseudo_pressures[particle_index];
auto const numer = omega * (source - Api);
pseudo_pressures[particle_index] =
std::max(0.0f,
old_pseudo_pressure +
safe_divide(numer, pseudo_diagonal).value_or(0.0f));
});
auto const error_average_numer = static_cast<double>(integral_error_sum);
auto const error_average_denom = static_cast<double>(1000 * particle_count);
return {error_average_numer / error_average_denom, error_max};
}
//------------------------------------------------------------------------------
// Remember that this one is special! Don't replace it with the common version!!
void iisph_pseudo_ap_integrate_velocities_and_positions_in_place(
size_t const particle_count,
float const dt,
V2f* const velocities,
V2f* const positions,
V2f const* const pseudo_pressure_displacements) {
for_each_iota(particle_count, [=](auto const particle_index) {
auto const velocity_star = velocities[particle_index];
auto const old_position = positions[particle_index];
auto const displacement = pseudo_pressure_displacements[particle_index];
positions[particle_index] =
old_position + (dt * velocity_star) + displacement;
if (is_safe_divide(velocity_star, dt)) {
velocities[particle_index] = velocity_star + (displacement / dt);
}
});
}
} // namespace emerald::sph2d_box
| 38.82029
| 80
| 0.632121
|
blackencino
|
5e2a071b6c455f913520888845636eb180451cd2
| 1,815
|
hpp
|
C++
|
include/Lys/GUIModule/GUI_Manager_Loader.hpp
|
Tigole/Lys-Framework
|
c7a51261b78c69fbfd823c1d20617ef13ca83a39
|
[
"MIT"
] | null | null | null |
include/Lys/GUIModule/GUI_Manager_Loader.hpp
|
Tigole/Lys-Framework
|
c7a51261b78c69fbfd823c1d20617ef13ca83a39
|
[
"MIT"
] | null | null | null |
include/Lys/GUIModule/GUI_Manager_Loader.hpp
|
Tigole/Lys-Framework
|
c7a51261b78c69fbfd823c1d20617ef13ca83a39
|
[
"MIT"
] | null | null | null |
#ifndef _GUI_MANAGER_LOADER_HPP
#define _GUI_MANAGER_LOADER_HPP 1
#include <string>
#include <vector>
#include "GUI_Element.hpp"
/*
class GUI_Element;
class XMLFileLoader;
class GUI_Manager;
class XML_Element;
class GUI_Interface;
class GUI_Layout;
class GUI_Button;
class GUI_Manager_Interface_Loader
{
public:
~GUI_Manager_Interface_Loader();
void mt_Prepare(const std::string& file_name, XMLFileLoader& loader, GUI_Manager* target);
private:
bool mt_Load_Button(const XML_Element& button);
bool mt_Load_Interface(const XML_Element& element);
bool mt_Finalize_Interface(const XML_Element& element);
bool mt_Load_Layout(const XML_Element& layout);
bool mt_Load_Layout_Button(const XML_Element& button);
bool mt_Finalize_Layout(const XML_Element& layout);
bool mt_Load_Allocation(const XML_Element& element, sf::FloatRect& rect);
bool mt_Load_Margin(const XML_Element& element, sf::Vector2f& margin);
GUI_Button* mt_Load_Button_From_Element(const XML_Element& button, GUI_Element* owner);
GUI_Manager* m_target;
GUI_Interface* m_interface;
GUI_Layout* m_layout;
GameStateType m_game_state;
std::vector<GUI_Element*> m_elements;
};
class GUI_Manager_Style_Loader
{
public:
~GUI_Manager_Style_Loader();
void mt_Prepare(const std::string& file_name, XMLFileLoader& loader, GUI_Manager* target);
private:
bool mt_Load_Style(const XML_Element& style);
bool mt_Load_State(const XML_Element& state);
bool mt_Load_Text(const XML_Element& text);
bool mt_Load_Background(const XML_Element& background);
bool mt_Finalize_State(const XML_Element& state);
void mt_Load_Color(const XML_Element& element, sf::Color& color);
void mt_Reset_Style(void);
GUI_Manager* m_target;
std::string m_style_id;
GUI_Element_State m_state_id;
GUI_Style m_style;
};*/
#endif // !_GUI_MANAGER_LOADER_HPP
| 26.691176
| 91
| 0.80551
|
Tigole
|
5e2a49f2f5550ddf2f7e2988c65aadd5f9e5e175
| 3,815
|
cpp
|
C++
|
tc 160+/TheSoccerDivOne.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 3
|
2015-05-25T06:24:37.000Z
|
2016-09-10T07:58:00.000Z
|
tc 160+/TheSoccerDivOne.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | null | null | null |
tc 160+/TheSoccerDivOne.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 5
|
2015-05-25T06:24:40.000Z
|
2021-08-19T19:22:29.000Z
|
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <utility>
using namespace std;
int final;
int dp[50][201][201];
vector<int> A;
const int INF = 123456789;
int go(int p, int w, int d) {
if (p == (int)A.size()) {
return d<=w ? 1 : 0;
}
int &ret = dp[p][w][d];
if (ret != -1) {
return ret;
}
for (int i=0; i<=4; ++i) {
for (int j=0; i+j<=4; ++j) {
const int k = 4-i-j;
const int cur = A[p] + 3*i + j;
if (w>=k && cur<=final) {
for (int l=0; l<=j; ++l) {
if (l > d) {
break;
}
if (go(p+1, w+i-k, d-l+(j-l))) {
return (ret = 1);
}
}
}
}
}
return (ret = 0);
}
class TheSoccerDivOne {
public:
int find(vector <int> points) {
vector< pair<int, int> > v;
for (int i=0; i<(int)points.size(); ++i) {
v.push_back(make_pair(-points[i], i));
}
sort(v.begin(), v.end());
if (v[0].second == 0) {
return 1;
}
int me = -1;
for (int i=1; i<(int)v.size(); ++i) {
if (v[i].second == 0) {
me = i;
break;
}
}
int can_win = ((int)v.size() - me) * 4;
int j = 0;
final = points[0] + 12;
while (j<me && points[v[j].second]>final) {
++j;
can_win += 4;
}
A.clear();
for (int i=j; i<me; ++i) {
A.push_back(points[v[i].second]);
}
reverse(A.begin(), A.end());
while (A.size() > 0) {
memset(dp, 0xff, sizeof dp);
if (go(0, can_win, 0)) {
return me - (int)A.size() + 1;
}
A.pop_back();
can_win += 4;
}
return me + 1;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {5, 17}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(0, Arg1, find(Arg0)); }
void test_case_1() { int Arr0[] = {5, 18, 21, 19}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 4; verify_case(1, Arg1, find(Arg0)); }
void test_case_2() { int Arr0[] = {4, 1, 5}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(2, Arg1, find(Arg0)); }
void test_case_3() { int Arr0[] = {4, 16, 4, 16, 16}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(3, Arg1, find(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
TheSoccerDivOne ___test;
___test.run_test(-1);
}
// END CUT HERE
| 31.791667
| 309
| 0.448493
|
ibudiselic
|
5e33d169e46deaea1c4d0ad923b3c696fbc5db26
| 448
|
hpp
|
C++
|
pythran/pythonic/include/numpy/tri.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/include/numpy/tri.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/include/numpy/tri.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef PYTHONIC_INCLUDE_NUMPY_TRI_HPP
#define PYTHONIC_INCLUDE_NUMPY_TRI_HPP
#include "pythonic/utils/proxy.hpp"
#include "pythonic/types/numpy_type.hpp"
#include "pythonic/types/ndarray.hpp"
namespace pythonic
{
namespace numpy
{
template <class dtype = double>
types::ndarray<typename types::numpy_type<dtype>::type, 2>
tri(int N, int M = -1, int k = 0, dtype d = dtype());
PROXY_DECL(pythonic::numpy, tri)
}
}
#endif
| 20.363636
| 62
| 0.71875
|
artas360
|
5e3478a846f15ef07ed7c0713a61970053d2d62e
| 2,614
|
cpp
|
C++
|
Shaders/source/Camera.cpp
|
Cubes58/RenderEngine2.0
|
6585a105a8d849d5387a49d1d52db3f059a4128d
|
[
"MIT"
] | null | null | null |
Shaders/source/Camera.cpp
|
Cubes58/RenderEngine2.0
|
6585a105a8d849d5387a49d1d52db3f059a4128d
|
[
"MIT"
] | null | null | null |
Shaders/source/Camera.cpp
|
Cubes58/RenderEngine2.0
|
6585a105a8d849d5387a49d1d52db3f059a4128d
|
[
"MIT"
] | null | null | null |
#include "Camera.h"
Camera::Camera(const glm::vec3 &p_Position, const glm::vec3 &p_Up, const float &p_Yaw, const float &p_Pitch) :
m_Front(glm::vec3(0.0f, 0.0f, -1.0f)), m_MovementSpeed(s_Speed), m_MouseSensitivity(s_Sensitivity), m_Zoom(s_Zoom) {
m_Position = p_Position;
m_WorldUp = p_Up;
m_Yaw = p_Yaw;
m_Pitch = p_Pitch;
UpdateCameraVectors();
}
Camera::Camera(const float &p_XPosition, const float &p_YPosition, const float &p_ZPosition, const float &p_XUp, const float &p_YUp, const float &p_ZUp, const float &p_Yaw, const float &p_Pitch) :
m_Front(glm::vec3(0.0f, 0.0f, -1.0f)), m_MovementSpeed(s_Speed), m_MouseSensitivity(s_Sensitivity), m_Zoom(s_Zoom) {
m_Position = glm::vec3(p_XPosition, p_YPosition, p_ZPosition);
m_WorldUp = glm::vec3(p_XUp, p_YUp, p_ZUp);
m_Yaw = p_Yaw;
m_Pitch = p_Pitch;
UpdateCameraVectors();
}
glm::mat4 Camera::GetViewMatrix() {
return glm::lookAt(m_Position, m_Position + m_Front, m_Up);
}
void Camera::ProcessKeyboard(const CameraMovement &p_Direction, const float &p_DeltaTime) {
float velocity = m_MovementSpeed * p_DeltaTime;
if (m_EnableSpeedBoost)
velocity *= m_BoostSpeedMultiplayer;
if (p_Direction == CameraMovement::FORWARD)
m_Position += m_Front * velocity;
if (p_Direction == CameraMovement::BACKWARD)
m_Position -= m_Front * velocity;
if (p_Direction == CameraMovement::LEFT)
m_Position -= m_Right * velocity;
if (p_Direction == CameraMovement::RIGHT)
m_Position += m_Right * velocity;
if (p_Direction == CameraMovement::UP)
m_Position += m_Up * velocity;
if (p_Direction == CameraMovement::DOWN)
m_Position -= m_Up * velocity;
}
void Camera::ProcessMouseMovement(float p_XOffset, float p_YOffset, bool p_ContrainPitch) {
p_XOffset *= m_MouseSensitivity;
p_YOffset *= m_MouseSensitivity;
m_Yaw += (p_XOffset * -1); // Stop inversion of the mouse movement.
m_Pitch += p_YOffset;
NormalizeAngle();
UpdateCameraVectors();
}
void Camera::NormalizeAngle() {
if (this->m_Pitch > s_MaxPitchAngle)
this->m_Pitch = s_MaxPitchAngle;
if (this->m_Pitch < -s_MaxPitchAngle)
this->m_Pitch = -s_MaxPitchAngle;
if (this->m_Yaw < 0.0f)
this->m_Yaw += 360.0f;
}
void Camera::UpdateCameraVectors() {
glm::vec3 front;
front.x = -sin(glm::radians(m_Yaw)) * cos(glm::radians(m_Pitch));
front.y = sin(glm::radians(m_Pitch));
front.z = -cos(glm::radians(m_Yaw)) * cos(glm::radians(m_Pitch));
m_Front = glm::normalize(front);
glm::vec3 side;
side.x = cos(glm::radians(m_Yaw));
side.y = 0;
side.z = -sin(glm::radians(m_Yaw));
m_Right = glm::normalize(side);
m_Up = glm::normalize(glm::cross(m_Right, m_Front));
}
| 31.878049
| 196
| 0.721882
|
Cubes58
|
5e3d00b336cfaa7e53cb2dfd052121ea67eaa88e
| 5,195
|
hxx
|
C++
|
include/nifty/graph/undirected_graph_base.hxx
|
konopczynski/nifty
|
dc02ac60febaabfaf9b2ee5a854bb61436ebdc97
|
[
"MIT"
] | 38
|
2016-06-29T07:42:50.000Z
|
2021-12-09T09:25:25.000Z
|
include/nifty/graph/undirected_graph_base.hxx
|
tbullmann/nifty
|
00119fd4753817b931272d6d3120b6ebd334882a
|
[
"MIT"
] | 62
|
2016-07-27T16:07:53.000Z
|
2022-03-30T17:24:36.000Z
|
include/nifty/graph/undirected_graph_base.hxx
|
tbullmann/nifty
|
00119fd4753817b931272d6d3120b6ebd334882a
|
[
"MIT"
] | 20
|
2016-01-25T21:21:52.000Z
|
2021-12-09T09:25:16.000Z
|
#pragma once
#include <boost/iterator/transform_iterator.hpp>
#include "nifty/graph/graph_tags.hxx"
#include "nifty/graph/graph_maps.hxx"
#include "nifty/tools/const_iterator_range.hxx"
namespace nifty{
namespace graph{
// \cond SUPPRESS_DOXYGEN
namespace detail_undirected_graph_base{
template<class GRAPH, class TAG>
struct GraphItemGeneralization;
template<class GRAPH>
struct GraphItemGeneralization<GRAPH, EdgeTag>{
typedef typename GRAPH::ChildGraph ChildGraph;
typedef typename GRAPH:: template EdgeIterRange<ChildGraph> type;
static type items(const ChildGraph & g){
return g.edges();
}
static uint64_t numberOfItems(const ChildGraph & g){
return g.numberOfEdges();
}
};
template<class GRAPH>
struct GraphItemGeneralization<GRAPH, NodeTag>{
typedef typename GRAPH::ChildGraph ChildGraph;
typedef typename GRAPH:: template NodeIterRange<ChildGraph> type;
static type items(const ChildGraph & g){
return g.nodes();
}
static uint64_t numberOfItems(const ChildGraph & g){
return g.numberOfNodes();
}
};
} // end namespace detail_undirected_graph_base
// \endcond
template<
class CHILD_GRAPH,
class NODE_ITER,
class EDGE_ITER,
class ADJACENCY_ITER
>
class UndirectedGraphBase{
public:
typedef CHILD_GRAPH ChildGraph;
typedef UndirectedGraphBase<ChildGraph, NODE_ITER, EDGE_ITER, ADJACENCY_ITER> Self;
template<class T>
struct NodeMap : graph_maps::NodeMap<ChildGraph,T> {
using graph_maps::NodeMap<ChildGraph,T>::NodeMap;
};
template<class T>
struct EdgeMap : graph_maps::EdgeMap<ChildGraph,T> {
using graph_maps::EdgeMap<ChildGraph,T>::EdgeMap;
};
template<class _CHILD_GRAPH>
struct NodeIterRange : public tools::ConstIteratorRange<typename _CHILD_GRAPH::NodeIter>{
using tools::ConstIteratorRange<typename _CHILD_GRAPH::NodeIter>::ConstIteratorRange;
};
template<class _CHILD_GRAPH>
struct EdgeIterRange : public tools::ConstIteratorRange<typename _CHILD_GRAPH::EdgeIter>{
using tools::ConstIteratorRange<typename _CHILD_GRAPH::EdgeIter>::ConstIteratorRange;
};
template<class _CHILD_GRAPH>
struct AdjacencyIterRange : public tools::ConstIteratorRange<typename _CHILD_GRAPH::AdjacencyIter>{
using tools::ConstIteratorRange<typename _CHILD_GRAPH::AdjacencyIter>::ConstIteratorRange;
};
// For range based loops over all nodes
NodeIterRange<ChildGraph > nodes() const{
return NodeIterRange<ChildGraph>(_child().nodesBegin(),_child().nodesEnd());
}
// For range based loops over all edges
EdgeIterRange<ChildGraph > edges() const{
return EdgeIterRange<ChildGraph>(_child().edgesBegin(),_child().edgesEnd());
}
template<class TAG>
typename detail_undirected_graph_base::GraphItemGeneralization<Self,TAG>::type items()const{
return detail_undirected_graph_base::GraphItemGeneralization<Self,TAG>::items(_child());
}
// For range based loops over adjacency for one node
AdjacencyIterRange<ChildGraph > adjacency(const int64_t node) const{
return AdjacencyIterRange<ChildGraph>(_child().adjacencyBegin(node),_child().adjacencyEnd(node));
}
AdjacencyIterRange<ChildGraph > adjacencyIn(const int64_t node) const{
return _child().adjacency(node);
}
AdjacencyIterRange<ChildGraph > adjacencyOut(const int64_t node) const{
return _child().adjacency(node);
}
ADJACENCY_ITER adjacencyOutBegin(const int64_t node)const{
return _child().adjacencyBegin(node);
}
ADJACENCY_ITER adjacencyOutEnd(const int64_t node)const{
return _child().adjacencyEnd(node);
}
ADJACENCY_ITER adjacencyInBegin(const int64_t node)const{
return _child().adjacencyBegin(node);
}
ADJACENCY_ITER adjacencyInEnd(const int64_t node)const{
return _child().adjacencyEnd(node);
}
std::pair<int64_t,int64_t> uv(const int64_t edge)const{
const auto u = _child().u(edge);
const auto v = _child().v(edge);
return std::pair<int64_t, int64_t>(u, v);
}
template<class NODE_LABELS, class EDGE_LABELS>
void nodeLabelsToEdgeLabels(const NODE_LABELS & nodeLabels, EDGE_LABELS & edgeLabels){
_child().forEachEdge([&](const int64_t edge){
const auto uv = _child().uv(edge);
edgeLabels[edge] = nodeLabels[uv.first] != nodeLabels[uv.second] ? 1 : 0;
});
}
template<class F>
void forEachEdge(F && f)const{
for(auto edge : _child().edges()){
f(edge);
}
}
template<class F>
void forEachNode(F && f)const{
for(auto node : _child().nodes()){
f(node);
}
}
template<class F, class TAG>
void forEachItem(F && f)const{
for(auto item : _child(). template items<TAG>()){
f(item);
}
}
private:
ChildGraph & _child(){
return *static_cast<ChildGraph *>(this);
}
const ChildGraph & _child()const{
return *static_cast<const ChildGraph *>(this);
}
};
} // namespace nifty::graph
} // namespace nifty
//
| 28.543956
| 105
| 0.686044
|
konopczynski
|
5e3f0cfeb91442460e22332281013266bf622ddd
| 1,298
|
cpp
|
C++
|
Classes/Paddle.cpp
|
hrdk-dubal/arkanoid
|
c6edbe19a214a1ad9220e001f96c4f7b4e0e596b
|
[
"CC0-1.0"
] | null | null | null |
Classes/Paddle.cpp
|
hrdk-dubal/arkanoid
|
c6edbe19a214a1ad9220e001f96c4f7b4e0e596b
|
[
"CC0-1.0"
] | null | null | null |
Classes/Paddle.cpp
|
hrdk-dubal/arkanoid
|
c6edbe19a214a1ad9220e001f96c4f7b4e0e596b
|
[
"CC0-1.0"
] | null | null | null |
#include "Paddle.h"
USING_NS_CC;
Paddle::Paddle(const Vec2& init_position, const Size& size,
const float left_bound, const float right_bound) :
GameEntity(init_position, size),
m_left_bound(left_bound),
m_right_bound(right_bound),
m_horizontal_velocity(800.0f),
m_movement_direction(PaddleMovement::move_none)
{}
void Paddle::move(const PaddleMovement movement_direction)
{
m_movement_direction = movement_direction;
}
void Paddle::calculateMovement(const float dt)
{
if (m_movement_direction == PaddleMovement::move_none)
{
return;
}
const float effective_velocity = m_horizontal_velocity * int(m_movement_direction);
const float dx = effective_velocity * dt;
const Vec2 new_position = getPosition() + Vec2(dx, 0);
setPosition(new_position);
const Size half_paddle_size = m_size * 0.5f;
if (getPosition().x < m_left_bound + half_paddle_size.width)
{
const Vec2 new_position(m_left_bound + half_paddle_size.width, getPosition().y);
setPosition(new_position);
stopPaddle();
}
if (getPosition().x > m_right_bound - half_paddle_size.width)
{
const Vec2 new_position(m_right_bound - half_paddle_size.width, getPosition().y);
setPosition(new_position);
stopPaddle();
}
}
void Paddle::stopPaddle()
{
m_movement_direction = PaddleMovement::move_none;
}
| 24.961538
| 84
| 0.763482
|
hrdk-dubal
|
5e3f2e91b499db7033fa7ec1cf5c4a911da8578c
| 426
|
cc
|
C++
|
Math/1492.cc
|
guohaoqiang/leetcode
|
802447c029c36892e8dd7391c825bcfc7ac0fd0b
|
[
"MIT"
] | null | null | null |
Math/1492.cc
|
guohaoqiang/leetcode
|
802447c029c36892e8dd7391c825bcfc7ac0fd0b
|
[
"MIT"
] | null | null | null |
Math/1492.cc
|
guohaoqiang/leetcode
|
802447c029c36892e8dd7391c825bcfc7ac0fd0b
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int kthFactor(int n, int k) {
set<int> d;
for (int i=1; i<=sqrt(n); ++i){
if (n%i==0){
d.insert(i);
if (i<sqrt(n)){
d.insert(n/i);
}
}
}
if (d.size()<k) return -1;
auto it = d.begin();
while (--k>0){
it++;
}
return *it;
}
};
| 20.285714
| 39
| 0.316901
|
guohaoqiang
|
1e142af5d9f2de88ead5318a48a262942d6a4595
| 1,137
|
hpp
|
C++
|
cpp04/ex00/Cat.hpp
|
pgomez-a/42_CPP_Piscine
|
c350f5f3c2e4d332b13bfa632b36f9a4b7bc6ce1
|
[
"MIT"
] | null | null | null |
cpp04/ex00/Cat.hpp
|
pgomez-a/42_CPP_Piscine
|
c350f5f3c2e4d332b13bfa632b36f9a4b7bc6ce1
|
[
"MIT"
] | null | null | null |
cpp04/ex00/Cat.hpp
|
pgomez-a/42_CPP_Piscine
|
c350f5f3c2e4d332b13bfa632b36f9a4b7bc6ce1
|
[
"MIT"
] | null | null | null |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Cat.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pgomez-a <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/25 14:20:41 by pgomez-a #+# #+# */
/* Updated: 2021/10/25 14:20:42 by pgomez-a ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CAT_HPP
# define CAT_HPP
# include "Animal.hpp"
# include <iostream>
class Cat : public Animal
{
public:
Cat(void);
Cat(Cat const & cat);
~Cat(void);
Cat& operator=(Cat const & cat);
void makeSound(void) const;
};
#endif
| 35.53125
| 80
| 0.217238
|
pgomez-a
|
1e186e57effdf33a459d094e2b3211fa4b231bd1
| 1,191
|
cpp
|
C++
|
src/RxAnimatedWidget.cpp
|
Reverier-Xu/RxWidgets
|
080a795a69ca14e1c202fc6c26547787f56ee88c
|
[
"MIT"
] | null | null | null |
src/RxAnimatedWidget.cpp
|
Reverier-Xu/RxWidgets
|
080a795a69ca14e1c202fc6c26547787f56ee88c
|
[
"MIT"
] | null | null | null |
src/RxAnimatedWidget.cpp
|
Reverier-Xu/RxWidgets
|
080a795a69ca14e1c202fc6c26547787f56ee88c
|
[
"MIT"
] | null | null | null |
//
// Created by reverier on 2020/7/20.
//
#include "RxAnimatedWidget.h"
void RxAnimatedWidget::doFold() {
if (isFolded() && this->m_animation.state() == QPropertyAnimation::Stopped) {
this->m_animation.setStartValue(foldValue());
this->m_animation.setEndValue(unfoldValue());
this->m_animation.start();
this->setFolded(false);
} else if (this->m_animation.state() == QPropertyAnimation::Stopped) {
this->m_animation.setStartValue(unfoldValue());
this->m_animation.setEndValue(foldValue());
this->m_animation.start();
this->setFolded(true);
}
}
void RxAnimatedWidget::setCurrentAnimateValue(qreal val) {
this->m_currentAnimateValue = val;
if (this->isVertical())
this->setFixedHeight(val);
else this->setFixedWidth(val);
}
RxAnimatedWidget::RxAnimatedWidget(QWidget *parent) : QWidget(parent) {
this->setAttribute(Qt::WA_StyledBackground, true);
this->m_animation.setTargetObject(this);
this->m_animation.setPropertyName("currentAnimateValue");
this->m_animation.setDuration(500);
this->m_animation.setEasingCurve(QEasingCurve::InOutCubic);
this->setFolded(false);
}
| 33.083333
| 81
| 0.691856
|
Reverier-Xu
|
1e1dca32bf3aa1bbad3c34d359c367d49247f85e
| 1,764
|
cpp
|
C++
|
src/ThirdParty/yaml/util/sandbox.cpp
|
xiaomingfun/TmingEngine
|
b81b822a4771c07908e1a72f5118a34552579d9e
|
[
"Apache-2.0"
] | 27
|
2018-05-21T14:28:10.000Z
|
2021-12-31T03:12:35.000Z
|
src/ThirdParty/yaml/util/sandbox.cpp
|
xiaomingfun/TmingEngine
|
b81b822a4771c07908e1a72f5118a34552579d9e
|
[
"Apache-2.0"
] | 1
|
2019-05-28T15:27:52.000Z
|
2019-05-28T15:27:52.000Z
|
src/ThirdParty/yaml/util/sandbox.cpp
|
xiaomingfun/TmingEngine
|
b81b822a4771c07908e1a72f5118a34552579d9e
|
[
"Apache-2.0"
] | 13
|
2019-11-08T12:48:44.000Z
|
2022-01-04T04:13:33.000Z
|
#include <iostream>
#include "yaml-cpp/emitterstyle.h"
#include "yaml-cpp/eventhandler.h"
#include "yaml-cpp/yaml.h" // IWYU pragma: keep
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
// our data types //这个例子好像是取自开源游戏引擎ogre,随便说的
struct Vec3 { //位置坐标
float x, y, z;
};
struct Power { //招式,魔法
std::string name; //招式名字,如 葵花宝典
int damage; //伤害值
};
struct Monster { //怪兽
std::string name;
Vec3 position;
std::vector <Power> powers;
};
template<typename T>
void operator >> (const YAML::Node& node, T& i)
{
i = node.as<T>();
}
void operator >> (const YAML::Node& node, Vec3& v) {
node[0] >> v.x;
node[1] >> v.y;
node[2] >> v.z;
}
void operator >> (const YAML::Node& node, Power& power) {
node["name"] >> power.name;
node["damage"] >> power.damage;
}
void operator >> (const YAML::Node& node, Monster& monster) {
node["name"] >> monster.name;
node["position"] >> monster.position;
const YAML::Node& powers = node["powers"];
for(unsigned i=0;i<powers.size();i++) {
Power power;
powers[i] >> power;
monster.powers.push_back(power);
}
}
int main() //测试程序
{
// std::ifstream fin("/Users/blue/Desktop/Gitee/TmingEngine/src/Tools/example/test.yml"); // 读入yaml配置文件。
// YAML::Parser parser(fin); //yaml 分析输入的配文件。出错抛出YAML::ParserException
YAML::Node doc = YAML::LoadFile("/Users/blue/Desktop/Gitee/TmingEngine/src/Tools/example/test.yml");
for(unsigned i=0;i<doc.size();i++)
{//i的实际值是0,1,2 ;关联yaml 中三个大的struct:ogre,dragon,wizard
Monster monster;
doc[i]>> monster;
;
std::cout <<monster.name << "\n";
}
return 0;
}
| 24.164384
| 108
| 0.588435
|
xiaomingfun
|
1e22954003a9ea493d892599a25536aa070308cf
| 974
|
cpp
|
C++
|
Problems/geeksforgeeks/move-all-zeroes-to-end-of-array/main.cpp
|
grand87/timus
|
8edcae276ab74b68fff18da3722460f492534a8a
|
[
"MIT"
] | null | null | null |
Problems/geeksforgeeks/move-all-zeroes-to-end-of-array/main.cpp
|
grand87/timus
|
8edcae276ab74b68fff18da3722460f492534a8a
|
[
"MIT"
] | 1
|
2019-05-09T19:17:00.000Z
|
2019-05-09T19:17:00.000Z
|
Problems/geeksforgeeks/move-all-zeroes-to-end-of-array/main.cpp
|
grand87/timus
|
8edcae276ab74b68fff18da3722460f492534a8a
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
void readArray(int* data, int size) {
for (int i = 0; i < size; i++)
cin >> data[i];
}
void printArray(int* data, int size) {
for (int i = 0; i < size; i++)
cout << data[i] << " ";
cout << endl;
}
void solution(int* src, int* dst, int size) {
//move all zeros first
int offset = size - 1;
for (int i = 0; i < size; i++) {
if (src[i] == 0) {
dst[offset] = 0;
offset--;
}
}
offset = 0;
for (int i = 0; i < size; i++) {
if (src[i] != 0) {
dst[offset] = src[i];
offset++;
}
}
}
int buf[1000];
int bufMod[1000];
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
#endif
int t;
cin >> t;
for (int i = 0; i < t; i++) {
int n;
cin >> n;
readArray(buf, n);
solution(buf, bufMod, n);
printArray(bufMod, n);
}
return 0;
}
| 19.098039
| 45
| 0.454825
|
grand87
|
1e26155ac79d0b16a995ff7e1ffd5843c488c934
| 1,004
|
cpp
|
C++
|
src/strings.cpp
|
yasserhcn/cpp-building
|
6f5e61270b47f2750a1abdd94977ef2d6205b430
|
[
"MIT"
] | 1
|
2021-06-28T06:33:28.000Z
|
2021-06-28T06:33:28.000Z
|
src/strings.cpp
|
yasserhcn/cpp-building
|
6f5e61270b47f2750a1abdd94977ef2d6205b430
|
[
"MIT"
] | 2
|
2021-05-26T19:32:38.000Z
|
2021-11-14T12:15:17.000Z
|
src/strings.cpp
|
yasserhcn/cpp-building
|
6f5e61270b47f2750a1abdd94977ef2d6205b430
|
[
"MIT"
] | 1
|
2021-05-30T16:03:47.000Z
|
2021-05-30T16:03:47.000Z
|
#include <strings.hpp>
int getCharIndex(std::string text, char character, uint16_t occurence)
{
uint16_t stringLength = text.length();
bool found = false;
uint16_t timesFound = 0;
for (uint16_t i = 0; i < text.length(); i++)
{
if(text[i] == character){
if(timesFound == occurence){
return i;
}
timesFound++;
}
}
return -1;
}
int getOccurences(std::string text, char character){
int occ = 0;
for (int i = 0; i < text.length(); i++)
{
// branchless way of checking
occ += (text[i] == character);
}
return occ;
}
void removeLine(std::string *text, uint16_t removeIndex)
{
int nwlnIndex = -1;
for (uint16_t i = removeIndex; i < text->length(); i++)
{
if((*text)[i] == '\n'){
nwlnIndex = i;
break;
}
}
if(nwlnIndex > 0){
text->erase(removeIndex, nwlnIndex - removeIndex + 1);
}
}
| 20.08
| 70
| 0.50996
|
yasserhcn
|
1e289e63a6a9d45cfcba9589eb02aba18f3b35b6
| 2,998
|
hpp
|
C++
|
include/ensmallen_bits/problems/schaffer_function_n2_impl.hpp
|
ElianeBriand/ensmallen
|
0f634056d054d100b2a70cb8f15ea9fa38680d10
|
[
"BSL-1.0",
"BSD-3-Clause"
] | 1
|
2020-04-07T18:50:10.000Z
|
2020-04-07T18:50:10.000Z
|
include/ensmallen_bits/problems/schaffer_function_n2_impl.hpp
|
ElianeBriand/ensmallen
|
0f634056d054d100b2a70cb8f15ea9fa38680d10
|
[
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
include/ensmallen_bits/problems/schaffer_function_n2_impl.hpp
|
ElianeBriand/ensmallen
|
0f634056d054d100b2a70cb8f15ea9fa38680d10
|
[
"BSL-1.0",
"BSD-3-Clause"
] | 1
|
2019-01-16T16:21:59.000Z
|
2019-01-16T16:21:59.000Z
|
/**
* @file schaffer_function_n2_impl.hpp
* @author Suryoday Basak
*
* Implementation of Schaffer function N.2.
*
* ensmallen is free software; you may redistribute it and/or modify it under
* the terms of the 3-clause BSD license. You should have received a copy of
* the 3-clause BSD license along with ensmallen. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef ENSMALLEN_PROBLEMS_SCHAFFER_FUNCTION_N2_IMPL_HPP
#define ENSMALLEN_PROBLEMS_SCHAFFER_FUNCTION_N2_IMPL_HPP
// In case it hasn't been included yet.
#include "schaffer_function_n2.hpp"
namespace ens {
namespace test {
inline SchafferFunctionN2::SchafferFunctionN2() { /* Nothing to do here */ }
inline void SchafferFunctionN2::Shuffle() { /* Nothing to do here */ }
template<typename MatType>
typename MatType::elem_type SchafferFunctionN2::Evaluate(
const MatType& coordinates,
const size_t /* begin */,
const size_t /* batchSize */) const
{
// Convenience typedef.
typedef typename MatType::elem_type ElemType;
// For convenience; we assume these temporaries will be optimized out.
const ElemType x1 = coordinates(0);
const ElemType x2 = coordinates(1);
const ElemType objective = 0.5 + (std::pow(std::sin(std::pow(x1, 2) -
std::pow(x2, 2)), 2) - 0.5) / std::pow(1 + 0.001 *
(std::pow(x1, 2) + std::pow(x2, 2)), 2);
return objective;
}
template<typename MatType>
typename MatType::elem_type SchafferFunctionN2::Evaluate(
const MatType& coordinates) const
{
return Evaluate(coordinates, 0, NumFunctions());
}
template<typename MatType, typename GradType>
inline void SchafferFunctionN2::Gradient(const MatType& coordinates,
const size_t /* begin */,
GradType& gradient,
const size_t /* batchSize */) const
{
// Convenience typedef.
typedef typename MatType::elem_type ElemType;
// For convenience; we assume these temporaries will be optimized out.
const ElemType x1 = coordinates(0);
const ElemType x2 = coordinates(1);
// Aliases for different terms in the expression of the gradient
const ElemType x1Sq = x1 * x1;
const ElemType x2Sq = x2 * x2;
const ElemType sum1 = x1Sq - x2Sq;
const ElemType sinSum1 = sin(sum1);
const ElemType sum2 = 0.001 * (x1Sq + x2Sq) + 1;
const ElemType trigExpression = 4 * sinSum1 * cos(sum1);
const ElemType numerator1 = - 0.004 * (pow(sinSum1, 2) - 0.5);
const ElemType expr1 = numerator1 / pow(sum2, 3);
const ElemType expr2 = trigExpression / pow(sum2, 2);
gradient.set_size(2, 1);
gradient(0) = x1 * (expr1 + expr2);
gradient(1) = x2 * (expr1 - expr2);
}
template<typename MatType, typename GradType>
inline void SchafferFunctionN2::Gradient(const MatType& coordinates,
GradType& gradient)
{
Gradient(coordinates, 0, gradient, 1);
}
} // namespace test
} // namespace ens
#endif
| 32.586957
| 77
| 0.679787
|
ElianeBriand
|
1e30266497955f21d0d8a83583caa1bbfa7e56e3
| 2,057
|
hpp
|
C++
|
include/codegen/include/GlobalNamespace/FileBrowserModel_--c__DisplayClass0_0.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/GlobalNamespace/FileBrowserModel_--c__DisplayClass0_0.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/GlobalNamespace/FileBrowserModel_--c__DisplayClass0_0.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: FileBrowserModel
#include "GlobalNamespace/FileBrowserModel.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: FileBrowserItem
class FileBrowserItem;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: FileBrowserModel/<>c__DisplayClass0_0
class FileBrowserModel::$$c__DisplayClass0_0 : public ::Il2CppObject {
public:
// public FileBrowserItem[] items
// Offset: 0x10
::Array<GlobalNamespace::FileBrowserItem*>* items;
// public System.String direcotryPath
// Offset: 0x18
::Il2CppString* direcotryPath;
// public System.String[] extensions
// Offset: 0x20
::Array<::Il2CppString*>* extensions;
// public System.Action`1<FileBrowserItem[]> callback
// Offset: 0x28
System::Action_1<::Array<GlobalNamespace::FileBrowserItem*>*>* callback;
// System.Void <GetContentOfDirectory>b__0()
// Offset: 0xBED6D4
void $GetContentOfDirectory$b__0();
// System.Void <GetContentOfDirectory>b__1()
// Offset: 0xBED708
void $GetContentOfDirectory$b__1();
// public System.Void .ctor()
// Offset: 0xBED248
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static FileBrowserModel::$$c__DisplayClass0_0* New_ctor();
}; // FileBrowserModel/<>c__DisplayClass0_0
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::FileBrowserModel::$$c__DisplayClass0_0*, "", "FileBrowserModel/<>c__DisplayClass0_0");
#pragma pack(pop)
| 36.087719
| 126
| 0.706855
|
Futuremappermydud
|
1e392e1487de0e1ad9226a8ebed14593102c2795
| 2,532
|
cpp
|
C++
|
app/src/main/cpp/BluetoothBarcodeScannerHandler.cpp
|
alexkmbk/AndroidTinyToolsFor1C
|
dfb5f6e99a4150d36ac93fc56255057be7f1f5ac
|
[
"MIT"
] | 13
|
2020-04-30T12:09:55.000Z
|
2021-12-01T12:29:29.000Z
|
app/src/main/cpp/BluetoothBarcodeScannerHandler.cpp
|
alexkmbk/AndroidTinyToolsFor1C
|
dfb5f6e99a4150d36ac93fc56255057be7f1f5ac
|
[
"MIT"
] | 1
|
2021-11-15T03:22:20.000Z
|
2021-11-15T03:22:20.000Z
|
app/src/main/cpp/BluetoothBarcodeScannerHandler.cpp
|
alexkmbk/AndroidTinyToolsFor1C
|
dfb5f6e99a4150d36ac93fc56255057be7f1f5ac
|
[
"MIT"
] | 3
|
2020-11-14T20:00:35.000Z
|
2021-12-20T09:49:31.000Z
|
//
// Created by Alexey on 04.04.2021.
//
#include "BluetoothBarcodeScannerHandler.h"
#include <IAndroidComponentHelper.h>
#include "AddInDefBase.h"
#include "jnienv.h"
BluetoothBarcodeScannerHandler::~BluetoothBarcodeScannerHandler()
{
if (obj)
{
Stop(); // call to unregister broadcast receiver
JNIEnv *env = getJniEnv();
env->DeleteGlobalRef(obj);
env->DeleteGlobalRef(cc);
}
}
void BluetoothBarcodeScannerHandler::Start(IAddInDefBaseEx *cnn, IMemoryManager* iMemory, tVariant *paParams) {
m_iMemory = iMemory;
m_iConnect = cnn;
JNIEnv *jenv = getJniEnv();
IAndroidComponentHelper *helper = (IAndroidComponentHelper *) cnn->GetInterface(
eIAndroidComponentHelper);
if (helper) {
if (obj == NULL){
jclass ccloc = helper->FindClass((uint16_t *) u"com/alexkmbk/androidtinytools/BluetoothBarcodeScannerHandlerClass");
if (ccloc) {
cc = static_cast<jclass>(jenv->NewGlobalRef(ccloc));
jenv->DeleteLocalRef(ccloc);
jobject activity = helper->GetActivity();
// call of constructor for java class
jmethodID ctorID = jenv->GetMethodID(cc, "<init>", "(Landroid/app/Activity;Ljava/lang/String;J)V");
jstring jMACAddress = jenv->NewString(paParams[0].pwstrVal, paParams[0].wstrLen);
jobject objloc = jenv->NewObject(cc, ctorID, activity, jMACAddress, (jlong)this);
if (objloc)
{
obj = jenv->NewGlobalRef(objloc);
jenv->DeleteLocalRef(objloc);
}
jenv->DeleteLocalRef(activity);
}
}
if (obj != NULL)
jenv->CallVoidMethod(obj, jenv->GetMethodID(cc, "StartBluetoothBarcodeScannerHandler", "()V"));
}
}
void BluetoothBarcodeScannerHandler::Stop() {
if (obj != NULL)
{
JNIEnv* env = getJniEnv();
jmethodID methID = env->GetMethodID(cc, "StopBluetoothBarcodeScannerHandler", "()V");
env->CallVoidMethod(obj, methID);
if (obj != NULL){
env->DeleteLocalRef(obj);
obj = NULL;
}
}
}
void BluetoothBarcodeScannerHandler::IsConnected(tVariant *pvarRetValue) {
TV_VT(pvarRetValue) = VTYPE_BOOL;
bool IsConnected = false;
if (obj != NULL)
{
JNIEnv* env = getJniEnv();
jmethodID methID = env->GetMethodID(cc, "IsConnected", "()Z");
IsConnected = (bool)env->CallBooleanMethod(obj, methID);
}
pvarRetValue->bVal = IsConnected;
}
| 30.142857
| 124
| 0.622828
|
alexkmbk
|
1e39b4c62f3dc3ebcdb8cf536d896ea1e09edf14
| 9,540
|
cc
|
C++
|
util/coding/pb_writer.cc
|
romange/beeri
|
60718d0f3133fffdf1500f8844852a79c91d8351
|
[
"BSD-2-Clause"
] | 2
|
2015-01-07T06:34:25.000Z
|
2019-01-25T10:11:24.000Z
|
util/coding/pb_writer.cc
|
romange/beeri
|
60718d0f3133fffdf1500f8844852a79c91d8351
|
[
"BSD-2-Clause"
] | null | null | null |
util/coding/pb_writer.cc
|
romange/beeri
|
60718d0f3133fffdf1500f8844852a79c91d8351
|
[
"BSD-2-Clause"
] | 1
|
2019-01-25T10:11:28.000Z
|
2019-01-25T10:11:28.000Z
|
// Copyright 2013, Beeri 15. All rights reserved.
// Author: Roman Gershman (romange@gmail.com)
//
#include "util/coding/pb_writer.h"
#include "strings/strcat.h"
#include "strings/stringprintf.h"
#include "util/coding/varint.h"
#include "util/sinksource.h"
namespace util {
namespace coding {
namespace {
inline uint32 ByteSizeWithLength(uint32 v) {
return v + Varint::Length32(v);
}
inline Status AppendUInt32(uint32 v, Sink* sink) {
uint8 buf[Varint::kMax32];
uint8* end = Varint::Encode32(buf, v);
return sink->Append(strings::Slice(buf, end - buf));
}
Status SerializeEncoder(const vector<uint8>& vec, Sink* sink) {
VLOG(1) << "Serializing uint32 array with " << vec.size() << " bytes + "
<< Varint::Length32(vec.size());
Status status = AppendUInt32(vec.size(), sink);
status.AddError(sink->Append(vec));
return status;
}
inline Status SerializeBitArray(const BitArray& ba, Sink* sink) {
Status status = AppendUInt32(ba.ByteSize() + Varint::Length32(ba.size()), sink);
status.AddError(AppendUInt32(ba.size(), sink));
status.AddError(sink->Append(ba.slice()));
return status;
}
template<typename T> inline typename std::make_unsigned<T>::type
EncodeZigZag(T t) {
static_assert(std::is_same<T, int32>::value || std::is_same<T, int64>::value ||
std::is_same<T, uint64>::value || std::is_same<T, uint32>::value,
"Must be ints");
static constexpr int SHR = sizeof(T) * 8 - 1;
return std::is_signed<T>::value ? (t >> SHR) ^ (t << 1) : t;
}
} // namespace
PbFieldWriter::PbFieldWriter(const gpb::FieldDescriptor* fd) : fd_(fd) {
if (fd_->cpp_type() == PBFD::CPPTYPE_MESSAGE) {
msg_writer_.reset(new PbFieldWriterArray(fd_->message_type()));
}
}
#define HANDLE_REP(T, enc) { const auto& arr = refl->GetRepeatedField<T>(msg, fd_); \
for (T v : arr) \
enc.push_back(EncodeZigZag<T>(v)); }
void PbFieldWriter::Add(const gpb::Message& msg) {
const gpb::Reflection* refl = msg.GetReflection();
string tmp;
if (fd_->is_repeated()) {
uint32 sz = refl->FieldSize(msg, fd_);
arr_sizes_.push_back(sz);
switch (fd_->cpp_type()) {
case PBFD::CPPTYPE_INT32:
HANDLE_REP(int32, val_uint32_);
break;
case PBFD::CPPTYPE_UINT32:
HANDLE_REP(uint32, val_uint32_);
break;
case PBFD::CPPTYPE_INT64:
HANDLE_REP(int64, val_uint64_);
break;
case PBFD::CPPTYPE_UINT64:
/*{
const auto& arr = refl->GetRepeatedField<uint64>(msg, fd_);
for (auto v : arr) {
LOG(INFO) << v;
}
}*/
HANDLE_REP(uint64, val_uint64_);
break;
case PBFD::CPPTYPE_ENUM: {
const auto* enum_descr = refl->GetEnum(msg, fd_);
val_uint32_.push_back(EncodeZigZag<int>(enum_descr->number()));
}
break;
case PBFD::CPPTYPE_MESSAGE: {
const auto& arr = refl->GetRepeatedPtrField<gpb::Message>(msg, fd_);
for (const gpb::Message& m : arr) {
msg_writer_->Add(m);
}
}
break;
default:
LOG(FATAL) << "Not implemented " << fd_->cpp_type_name();
}
return;
}
if (!fd_->is_required()) {
bool exists = refl->HasField(msg, fd_);
has_bit_.Push(exists);
if (!exists)
return;
}
switch (fd_->cpp_type()) {
case PBFD::CPPTYPE_UINT32:
val_uint32_.push_back(refl->GetUInt32(msg, fd_));
break;
case PBFD::CPPTYPE_INT32:
val_uint32_.push_back(EncodeZigZag<int32>(refl->GetInt32(msg, fd_)));
break;
case PBFD::CPPTYPE_UINT64:
val_uint64_.push_back(refl->GetUInt64(msg, fd_));
break;
case PBFD::CPPTYPE_INT64:
val_uint64_.push_back(EncodeZigZag<int64>(refl->GetInt64(msg, fd_)));
break;
case PBFD::CPPTYPE_STRING: {
const string& str = refl->GetStringReference(msg, fd_, &tmp);
str_encoder_.Add(str);
}
break;
case PBFD::CPPTYPE_MESSAGE:
msg_writer_->Add(refl->GetMessage(msg, fd_));
break;
case PBFD::CPPTYPE_DOUBLE: {
double d = refl->GetDouble(msg, fd_);
char* ptr = reinterpret_cast<char*>(&d);
val_uint64_.push_back(*reinterpret_cast<uint64*>(ptr));
}
break;
case PBFD::CPPTYPE_BOOL:
val_bool_.Push(refl->GetBool(msg, fd_));
break;
default:
LOG(FATAL) << "Not implemented: " << fd_->cpp_type_name();
}
}
inline void Encode32(std::vector<uint32>* v, vector<uint8>* dest) {
if (v->empty())
return;
UInt32Encoder encoder;
encoder.Encode(*v, true);
encoder.Swap(dest);
std::vector<uint32>().swap(*v);
}
void PbFieldWriter::Finalize() {
UInt32Encoder encoder;
if (fd_->is_repeated()) {
Encode32(&arr_sizes_, &data_buf_[0]);
} else if (fd_->is_optional()) {
has_bit_.Finalize();
}
switch (fd_->cpp_type()) {
case PBFD::CPPTYPE_STRING:
str_encoder_.Finalize();
break;
case PBFD::CPPTYPE_UINT32: case PBFD::CPPTYPE_INT32: case PBFD::CPPTYPE_ENUM:
Encode32(&val_uint32_, &data_buf_[1]);
break;
case PBFD::CPPTYPE_UINT64: case PBFD::CPPTYPE_INT64: case PBFD::CPPTYPE_DOUBLE:
enc64_.Encode(val_uint64_, true);
std::vector<uint64>().swap(val_uint64_);
break;
case PBFD::CPPTYPE_BOOL:
val_bool_.Finalize();
break;
case PBFD::CPPTYPE_MESSAGE: // NOOP.
break;
default:
LOG(FATAL) << "Not implemented" << fd_->cpp_type_name();
}
}
uint32 PbFieldWriter::ByteSize() const {
uint32 size = 0;
if (fd_->is_repeated()) {
size += ByteSizeWithLength(data_buf_[0].size());
} else if (fd_->is_optional()) {
size += ByteSizeWithLength(has_bit_.ByteSize() + Varint::Length32(has_bit_.size()));
}
switch (fd_->cpp_type()) {
case PBFD::CPPTYPE_STRING:
size += str_encoder_.ByteSize();
break;
case PBFD::CPPTYPE_UINT32:
case PBFD::CPPTYPE_INT32:
case PBFD::CPPTYPE_ENUM:
size += data_buf_[1].size();
break;
case PBFD::CPPTYPE_UINT64:
case PBFD::CPPTYPE_INT64:
case PBFD::CPPTYPE_DOUBLE:
size += enc64_.ByteSize();
break;
case PBFD::CPPTYPE_BOOL:
size += ByteSizeWithLength(val_bool_.ByteSize() + Varint::Length32(val_bool_.size()));
break;
case PBFD::CPPTYPE_MESSAGE: // NOOP.
break;
default:
LOG(FATAL) << "Not implemented: " << fd_->cpp_type_name();
}
return size;
}
Status PbFieldWriter::SerializeTo(Sink* sink) const {
VLOG(1) << "Serializing field " << fd_->full_name();
if (fd_->is_repeated()) {
RETURN_IF_ERROR(SerializeEncoder(data_buf_[0], sink));
} else if (fd_->is_optional()) {
RETURN_IF_ERROR(SerializeBitArray(has_bit_, sink));
}
switch (fd_->cpp_type()) {
case PBFD::CPPTYPE_STRING:
VLOG(1) << "Serializing string with " << str_encoder_.ByteSize() << " total bytes.";
RETURN_IF_ERROR(str_encoder_.SerializeTo(sink));
break;
case PBFD::CPPTYPE_UINT32:
case PBFD::CPPTYPE_INT32:
case PBFD::CPPTYPE_ENUM:
RETURN_IF_ERROR(sink->Append(data_buf_[1]));
break;
case PBFD::CPPTYPE_UINT64:
case PBFD::CPPTYPE_INT64:
case PBFD::CPPTYPE_DOUBLE:
RETURN_IF_ERROR(enc64_.SerializeTo(sink));
break;
case PBFD::CPPTYPE_BOOL:
RETURN_IF_ERROR(SerializeBitArray(val_bool_, sink));
break;
case PBFD::CPPTYPE_MESSAGE: // NOOP.
break;
default:
LOG(FATAL) << "Not implemented: " << fd_->cpp_type_name();
}
return Status::OK;
}
void PbFieldWriter::VisitPreOrder(std::function<void(PbFieldWriter*)> cb) {
cb(this);
if (msg_writer_)
msg_writer_->VisitPreOrder(cb);
}
std::string PbFieldWriter::FieldName() const {
return fd_->full_name();
}
PbFieldWriterArray::PbFieldWriterArray(const gpb::Descriptor* descr) {
field_writer_.resize(descr->field_count());
for (int i = 0; i < descr->field_count(); ++i) {
const gpb::FieldDescriptor* fd = descr->field(i);
field_writer_[i] = new PbFieldWriter(fd);
}
}
PbFieldWriterArray::~PbFieldWriterArray() {
for (PbFieldWriter* v : field_writer_)
delete v;
}
PbBlockSerializer::PbBlockSerializer(const gpb::Descriptor* descr)
: desc_(descr), root_fields_(descr) {
root_fields_.VisitPreOrder([this](PbFieldWriter* writer) {
all_fields_.push_back(writer);
});
}
PbBlockSerializer::~PbBlockSerializer() {
}
void PbBlockSerializer::Add(const gpb::Message& msg) {
CHECK(!was_finalized_);
++size_;
root_fields_.Add(msg);
}
Status PbBlockSerializer::SerializeTo(Sink* sink) {
if (!was_finalized_) {
was_finalized_ = true;
for (PbFieldWriter* fw : all_fields_) {
fw->Finalize();
}
}
uint32 total_size = 0;
std::vector<uint32> field_sizes;
// msg count followed by all the fields' byte sizes.
field_sizes.push_back(size_);
for (PbFieldWriter* fw : all_fields_) {
VLOG(2) << "Field " << fw->FieldName() << ", size " << fw->ByteSize();
total_size += fw->ByteSize();
field_sizes.push_back(fw->ByteSize());
}
std::vector<uint8> fs_buf;
Encode32(&field_sizes, &fs_buf);
total_size += ByteSizeWithLength(fs_buf.size());
VLOG(1) << "Serialize all fields column sizes. Block size is " << total_size;
RETURN_IF_ERROR(SerializeEncoder(fs_buf, sink));
for (PbFieldWriter* fw : all_fields_) {
RETURN_IF_ERROR(fw->SerializeTo(sink));
}
return Status::OK;
}
std::string PbBlockSerializer::DebugStats() const {
string res;
for (const PbFieldWriter* fw : all_fields_) {
StrAppend(&res, fw->FieldName(), " size ", fw->ByteSize(), ", ");
}
return res;
}
} // namespace coding
} // namespace util
| 29.444444
| 92
| 0.647065
|
romange
|
1e405de2fe3425f0ca8bb3a565a7c34b177f89da
| 493
|
cpp
|
C++
|
[179] Largest Number/179.largest-number.cpp
|
Coolzyh/Leetcode
|
4abf685501427be0ce36b83016c4fa774cdf1a1a
|
[
"MIT"
] | null | null | null |
[179] Largest Number/179.largest-number.cpp
|
Coolzyh/Leetcode
|
4abf685501427be0ce36b83016c4fa774cdf1a1a
|
[
"MIT"
] | null | null | null |
[179] Largest Number/179.largest-number.cpp
|
Coolzyh/Leetcode
|
4abf685501427be0ce36b83016c4fa774cdf1a1a
|
[
"MIT"
] | null | null | null |
/*
* @lc app=leetcode id=179 lang=cpp
*
* [179] Largest Number
*/
// @lc code=start
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> arr;
for(auto i: nums)
arr.push_back(to_string(i));
sort(begin(arr), end(arr), [](string &s1, string &s2){ return s1+s2>s2+s1; });
string res;
for(auto s:arr)
res += s;
if (res[0] == '0') return "0";
return res;
}
};
// @lc code=end
| 20.541667
| 86
| 0.51927
|
Coolzyh
|
1e43ed73ea0649f6ccc6e0dc4cc9b77ee50bc051
| 916
|
hpp
|
C++
|
Core/SDLCommon.hpp
|
dvijayak/pen31ope
|
dc07e5f1405d668c8ab0b1514035d97b78744519
|
[
"MIT"
] | null | null | null |
Core/SDLCommon.hpp
|
dvijayak/pen31ope
|
dc07e5f1405d668c8ab0b1514035d97b78744519
|
[
"MIT"
] | null | null | null |
Core/SDLCommon.hpp
|
dvijayak/pen31ope
|
dc07e5f1405d668c8ab0b1514035d97b78744519
|
[
"MIT"
] | null | null | null |
#ifndef SDLCommon_hpp
#define SDLCommon_hpp
#include <cassert>
#include "SDL.h"
/// Smart lifetime containers of various structs
struct SDLSurface
{
SDLSurface(SDL_Surface* p) : m_resource(p)
{
assert(p != nullptr);
}
~SDLSurface()
{
SDL_FreeSurface(m_resource);
}
SDL_Surface* get() const { return m_resource; };
private:
SDL_Surface* m_resource;
};
struct SDLTexture
{
SDLTexture(SDL_Texture* p) : m_resource(p)
{
assert(p != nullptr);
}
~SDLTexture()
{
SDL_DestroyTexture(m_resource);
}
SDL_Texture* get() const { return m_resource; }
private:
SDL_Texture* m_resource;
};
/// Utils
#include "Color.hpp"
class SDLUtil
{
public:
static SDL_Color MakeSDLColor(ColorRGB c)
{
uint8_t r = c >> 24;
uint8_t g = (c >> 16) & 0x00FF;
uint8_t b = (c >> 8) & 0x0000FF;
return {r, g, b, 0xFF};
}
};
#endif
| 14.539683
| 51
| 0.616812
|
dvijayak
|
1e448c96dbfc0ae1403e6e4c04d4adc6ec7fd364
| 1,139
|
cpp
|
C++
|
client/src/core/webgl/GLUniform.cpp
|
jsonxr/blockworld
|
aa005b254e6796ca3c03bc6da4a15764ac4da2d5
|
[
"MIT"
] | null | null | null |
client/src/core/webgl/GLUniform.cpp
|
jsonxr/blockworld
|
aa005b254e6796ca3c03bc6da4a15764ac4da2d5
|
[
"MIT"
] | null | null | null |
client/src/core/webgl/GLUniform.cpp
|
jsonxr/blockworld
|
aa005b254e6796ca3c03bc6da4a15764ac4da2d5
|
[
"MIT"
] | null | null | null |
//
// Created by Jason Rowland on 2/11/22.
//
#include "GLUniform.h"
namespace app {
void GLUniform::apply() {
// Don't apply the uniform if it is what it is
if (current_value_ == value_) {
return;
}
// Uniform types
// https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGetActiveUniform.xhtml
switch (type) {
case GLType::kSampler2d: {
if (current_value_ != value_) {
}
break;
}
case GLType::kMat4f: {
const auto &value = std::get<mat4>(value_);
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(value));
break;
}
case GLType::kVec3f: {
const auto &value = std::get<vec3>(value_);
glUniform3f(location, value[0], value[1], value[2]);
break;
}
case GLType::kVec4f: {
const auto &value = std::get<vec4>(value_);
glUniform4f(location, value[0], value[1], value[2], value[3]);
break;
}
case GLType::kInt: {
auto value = std::get<int>(value_);
glUniform1i(location, value);
}
case GLType::kFloat:
default:
return;
}
current_value_ = value_;
}
} // namespace app
| 22.333333
| 87
| 0.599649
|
jsonxr
|
1e48ae2bbb7040d91a56918f030eedabb005fc33
| 13,585
|
cpp
|
C++
|
source/emptyexample/PhysicallyBasedRenderingExample.cpp
|
Daniel-Amadeus/PBR
|
653441f70331de571f92cb15e9baf9bacfee951f
|
[
"MIT"
] | 1
|
2015-11-20T11:41:24.000Z
|
2015-11-20T11:41:24.000Z
|
source/emptyexample/PhysicallyBasedRenderingExample.cpp
|
Daniel-Amadeus/PBR
|
653441f70331de571f92cb15e9baf9bacfee951f
|
[
"MIT"
] | null | null | null |
source/emptyexample/PhysicallyBasedRenderingExample.cpp
|
Daniel-Amadeus/PBR
|
653441f70331de571f92cb15e9baf9bacfee951f
|
[
"MIT"
] | null | null | null |
#include "PhysicallyBasedRenderingExample.h"
#include <glm/gtc/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glbinding/gl/enum.h>
#include <glbinding/gl/bitfield.h>
#include <globjects/globjects.h>
#include <globjects/logging.h>
#include <globjects/DebugMessage.h>
#include <globjects/Program.h>
#include <globjects/Texture.h>
#include <widgetzeug/make_unique.hpp>
#include <gloperate/base/RenderTargetType.h>
#include <gloperate/resources/ResourceManager.h>
#include <gloperate/primitives/Scene.h>
#include <gloperate/painter/TargetFramebufferCapability.h>
#include <gloperate/painter/ViewportCapability.h>
#include <gloperate/painter/PerspectiveProjectionCapability.h>
#include <gloperate/painter/CameraCapability.h>
#include <gloperate/painter/VirtualTimeCapability.h>
#include <gloperate/primitives/AdaptiveGrid.h>
#include <gloperate/primitives/Icosahedron.h>
using namespace gl;
using namespace glm;
using namespace globjects;
using widgetzeug::make_unique;
EmptyExample::EmptyExample(gloperate::ResourceManager & resourceManager)
: Painter(resourceManager)
, m_targetFramebufferCapability(addCapability(new gloperate::TargetFramebufferCapability()))
, m_viewportCapability(addCapability(new gloperate::ViewportCapability()))
, m_projectionCapability(addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability)))
, m_cameraCapability(addCapability(new gloperate::CameraCapability()))
{
setupPropertyGroup();
}
EmptyExample::~EmptyExample() = default;
void EmptyExample::setupPropertyGroup()
{
m_presetProperty = addProperty<Preset>("preset", this,
&EmptyExample::getPreset,
&EmptyExample::setPreset);
m_presetProperty->setStrings({
{ Preset::manual, "manual" },
{ Preset::gold, "gold" } });
//======= manual settings =======
m_manualSettingsPropertyGroup = addGroup("manualSettings");
m_programPresetProperty = m_manualSettingsPropertyGroup->addProperty<ProgramPreset>("ProgramPreset", this,
&EmptyExample::getProgramPreset,
&EmptyExample::setProgramPreset);
m_programPresetProperty->setStrings({
{ ProgramPreset::withoutEnvMap, "WithoutEnvMap" },
{ ProgramPreset::withEnvMap, "WithEnvMap" } });
//======= albedo color =======
m_albedoPresetProperty = m_manualSettingsPropertyGroup->addProperty<AlbedoPreset>("albedo", this,
&EmptyExample::albedoPreset,
&EmptyExample::setAlbedoPreset);
m_albedoPresetProperty->setStrings({
{ AlbedoPreset::color, "color" },
{ AlbedoPreset::metal, "metalTex" } });
m_albedoColorGroup = m_manualSettingsPropertyGroup->addGroup("albedoColor");
m_albedoColorGroup->addProperty<float>("albedoColorR", this,
&EmptyExample::albedoColorR, &EmptyExample::setAlbedoColorR)->setOptions({
{ "minimum", 0.0f },
{ "maximum", 1.0f },
{ "step", 0.1f },
{ "precision", 2u } });
m_albedoColorGroup->addProperty<float>("albedoColorG", this,
&EmptyExample::albedoColorG, &EmptyExample::setAlbedoColorG)->setOptions({
{ "minimum", 0.0f },
{ "maximum", 1.0f },
{ "step", 0.1f },
{ "precision", 2u } });
m_albedoColorGroup->addProperty<float>("albedoColorB", this,
&EmptyExample::albedoColorB, &EmptyExample::setAlbedoColorB)->setOptions({
{ "minimum", 0.0f },
{ "maximum", 1.0f },
{ "step", 0.1f },
{ "precision", 2u } });
m_microsurfaceProperty = m_manualSettingsPropertyGroup->addProperty<float>("microsurface", this,
&EmptyExample::microsurface, &EmptyExample::setMicrosurface);
m_microsurfaceProperty->setOptions({
{ "minimum", 0.0f },
{ "maximum", 1.0f },
{ "step", 0.1f },
{ "precision", 2u } });
//======= reflectivity =======
m_reflectivityGroup = m_manualSettingsPropertyGroup->addGroup("reflectivity");
m_reflectivityGroup->addProperty<float>("reflectivityR", this,
&EmptyExample::reflectivityR, &EmptyExample::setReflectivityR)->setOptions({
{ "minimum", 0.0f },
{ "maximum", 1.0f },
{ "step", 0.1f },
{ "precision", 2u } });
m_reflectivityGroup->addProperty<float>("reflectivityG", this,
&EmptyExample::reflectivityG, &EmptyExample::setReflectivityG)->setOptions({
{ "minimum", 0.0f },
{ "maximum", 1.0f },
{ "step", 0.1f },
{ "precision", 2u } });
m_reflectivityGroup->addProperty<float>("reflectivityB", this,
&EmptyExample::reflectivityB, &EmptyExample::setReflectivityB)->setOptions({
{ "minimum", 0.0f },
{ "maximum", 1.0f },
{ "step", 0.1f },
{ "precision", 2u } });
//======= normal map =======
m_normalMapPresetProperty = m_manualSettingsPropertyGroup->addProperty<NormalMapPreset>("normalMap", this,
&EmptyExample::normalMapPreset,
&EmptyExample::setNormalMapPreset);
m_normalMapPresetProperty->setStrings({
{ NormalMapPreset::none, "none" },
{ NormalMapPreset::metal, "metal" } });
/*m_manualSettingsPropertyGroup->addProperty<bool>("useNormalMap", this,
&EmptyExample::useNormalMap, &EmptyExample::setUseNormalMap);/**/
}
void EmptyExample::setupProjection()
{
static const auto zNear = 0.3f, zFar = 15.f, fovy = 50.f;
m_projectionCapability->setZNear(zNear);
m_projectionCapability->setZFar(zFar);
m_projectionCapability->setFovy(radians(fovy));
m_grid->setNearFar(zNear, zFar);
}
AlbedoPreset EmptyExample::albedoPreset() const
{
return m_albedoPreset;
}
void EmptyExample::setAlbedoPreset(AlbedoPreset preset)
{
m_albedoPreset = preset;
m_manualSettingsPropertyGroup->clear();
switch (m_albedoPreset)
{
case AlbedoPreset::color:
m_material.setAlbedo(m_material.albedoColor());
m_manualSettingsPropertyGroup->addProperty(m_programPresetProperty);
m_manualSettingsPropertyGroup->addProperty(m_albedoPresetProperty);
m_manualSettingsPropertyGroup->addProperty(m_albedoColorGroup);
m_manualSettingsPropertyGroup->addProperty(m_microsurfaceProperty);
m_manualSettingsPropertyGroup->addProperty(m_reflectivityGroup);
m_manualSettingsPropertyGroup->addProperty(m_normalMapPresetProperty);
break;
case AlbedoPreset::metal:
//m_material.setAlbedo(m_albedoColor);
m_material.setAlbedo(m_material.albedoTex());
m_manualSettingsPropertyGroup->addProperty(m_programPresetProperty);
m_manualSettingsPropertyGroup->addProperty(m_albedoPresetProperty);
m_manualSettingsPropertyGroup->addProperty(m_microsurfaceProperty);
m_manualSettingsPropertyGroup->addProperty(m_reflectivityGroup);
m_manualSettingsPropertyGroup->addProperty(m_normalMapPresetProperty);
break;
default:
break;
}
}
float EmptyExample::albedoColorR() const
{
return m_material.albedoColor().r;// m_albedoColor.r;
}
void EmptyExample::setAlbedoColorR(float red)
{
glm::vec3 color = m_material.albedoColor();
color[0] = red;
m_material.setAlbedo(color);
}
float EmptyExample::albedoColorG() const
{
return m_material.albedoColor().g;// m_albedoColor.g;
}
void EmptyExample::setAlbedoColorG(float green)
{
glm::vec3 color = m_material.albedoColor();
color[1] = green;
m_material.setAlbedo(color);
}
float EmptyExample::albedoColorB() const
{
return m_material.albedoColor().b;// m_albedoColor.b;
}
void EmptyExample::setAlbedoColorB(float blue)
{
glm::vec3 color = m_material.albedoColor();
color[2] = blue;
m_material.setAlbedo(color);
}
float EmptyExample::microsurface() const
{
return m_material.microsurface();// m_microsurface;
}
void EmptyExample::setMicrosurface(float newMicrosurface)
{
m_material.setMicrosurface(newMicrosurface);
}
float EmptyExample::reflectivityR() const
{
return m_reflectivity[0];
}
void EmptyExample::setReflectivityR(float red)
{
m_reflectivity[0] = red;
m_material.setReflectivity(m_reflectivity);
}
float EmptyExample::reflectivityG() const
{
return m_reflectivity[1];
}
void EmptyExample::setReflectivityG(float green)
{
m_reflectivity[1] = green;
m_material.setReflectivity(m_reflectivity);
}
float EmptyExample::reflectivityB() const
{
return m_reflectivity[2];
}
void EmptyExample::setReflectivityB(float blue)
{
m_reflectivity[2] = blue;
m_material.setReflectivity(m_reflectivity);
}
NormalMapPreset EmptyExample::normalMapPreset() const
{
return m_normalMapPreset;
}
void EmptyExample::setNormalMapPreset(NormalMapPreset preset)
{
m_normalMapPreset = preset;
switch (m_normalMapPreset)
{
case NormalMapPreset::none:
m_material.setNormalMap(nullptr);
break;
case NormalMapPreset::metal:
m_material.setNormalMap(m_normals);
break;
default:
break;
}
}
ProgramPreset EmptyExample::getProgramPreset() const
{
return m_programPreset;
}
void EmptyExample::setProgramPreset(ProgramPreset programPreset)
{
m_programPreset = programPreset;
switch (m_programPreset)
{
case ProgramPreset::withoutEnvMap:
m_material.setProgramByPreset(ProgramPreset::withoutEnvMap);
break;
case ProgramPreset::withEnvMap:
m_material.setProgramByPreset(ProgramPreset::withEnvMap);
break;
default:
break;
}
}
Preset EmptyExample::getPreset() const
{
return m_preset;
}
void EmptyExample::setPreset(Preset newPreset)
{
m_preset = newPreset;
clear();
addProperty(m_presetProperty);
PBRMaterial newMaterial = PBRMaterial();
switch (newPreset)
{
case Preset::manual:
newMaterial.copySettings(m_material);
m_material = newMaterial;
addProperty(m_manualSettingsPropertyGroup);
break;
case Preset::gold:
m_material = m_gold;
break;
default:
break;
}
}
void EmptyExample::onInitialize()
{
// create program
globjects::init();
#ifdef __APPLE__
Shader::clearGlobalReplacements();
Shader::globalReplace("#version 140", "#version 150");
debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif
m_grid = new gloperate::AdaptiveGrid{};
m_grid->setColor({0.6f, 0.6f, 0.6f});
m_icosahedron = new gloperate::Icosahedron{ 3 };
m_programWithEnv = new Program{};
m_programWithEnv->attach(
Shader::fromFile(GL_VERTEX_SHADER, "data/emptyexample/icosahedron_env.vert"),
Shader::fromFile(GL_FRAGMENT_SHADER, "data/emptyexample/icosahedron_env.frag")
);
m_programNoEnv = new Program{};
m_programNoEnv->attach(
Shader::fromFile(GL_VERTEX_SHADER, "data/emptyexample/icosahedron_noEnv.vert"),
Shader::fromFile(GL_FRAGMENT_SHADER, "data/emptyexample/icosahedron_noEnv.frag")
);
m_transformLocation = m_programNoEnv->getUniformLocation("transform");
m_eyeLocation = m_programNoEnv->getUniformLocation("a_eye");
m_programPreset = ProgramPreset::withEnvMap;
//std::cout << "m_eyeLocation = " << m_eyeLocation << std::endl;
m_icoTransform = glm::mat4x4();
m_icoTransform = glm::translate(m_icoTransform, glm::vec3(0.0f, 1.0f, 0.0f));
m_cameraCapability->setEye(glm::vec3(-1.2f, 2.1f, -2.8));
m_cameraCapability->setCenter(glm::vec3(0.9f, 0.5f, 2.0));
glClearColor(0.85f, 0.87f, 0.91f, 1.0f);
setupProjection();
m_albedoTex = m_resourceManager.load<globjects::Texture>("data/emptyexample/metal/MetalScratches_COLOR.png");
m_albedoTex->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
m_albedoTex->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);
m_normals = m_resourceManager.load<globjects::Texture>("data/emptyexample/metal/MetalScratches_NRM.png");
m_normals->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
m_normals->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);
m_envmap = m_resourceManager.load<globjects::Texture>("data/emptyexample/Panorama_0.png");
/*m_envmap->generateMipmap();
m_envmap->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
m_envmap->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
m_envmap->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
m_envmap->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);*/
//m_albedoColor = glm::vec3(0.22, 0.32, 0.50); //plastic
//m_albedoColor = glm::vec3(0.0, 0.0, 0.0); //gold
//setMicrosurface(0.46f); //plastic
setMicrosurface(0.86f); //gold
//m_reflectivity = glm::vec3(0.34, 0.41, 0.53);//plastic
m_reflectivity = glm::vec3(1.0, 0.86, 0.58);//gold
//m_useNormalMap = true;
//m_preset = preset::gold;
m_albedoPreset = AlbedoPreset::color;
m_normalMapPreset = NormalMapPreset::metal;
setPreset(Preset::gold);
m_gold = PBRMaterial(ProgramPreset::withEnvMap, m_envmap, m_normals, glm::vec3(0.0f, 0.0f, 0.0f), 0.86f, glm::vec3(1.0f, 0.86f, 0.58f));
}
void EmptyExample::onPaint()
{
globjects::ref_ptr<globjects::Program> program;
if (m_viewportCapability->hasChanged())
{
glViewport(
m_viewportCapability->x(),
m_viewportCapability->y(),
m_viewportCapability->width(),
m_viewportCapability->height());
m_viewportCapability->setChanged(false);
}
auto fbo = m_targetFramebufferCapability->framebuffer();
if (!fbo)
fbo = globjects::Framebuffer::defaultFBO();
fbo->bind(GL_FRAMEBUFFER);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
const auto transform = m_projectionCapability->projection() * m_cameraCapability->view();
const auto eye = m_cameraCapability->eye();
m_grid->update(eye, transform);
m_grid->draw();
switch (m_material.programPreset())
{
case ProgramPreset::withoutEnvMap:
m_material.setProgramByPreset(ProgramPreset::withoutEnvMap);
break;
case ProgramPreset::withEnvMap:
m_material.setProgramByPreset(ProgramPreset::withEnvMap);
break;
default:
break;
}
program = m_material.program();
program->use();
program->setUniform("projection", transform);
program->setUniform("transform", m_icoTransform);
program->setUniform(m_eyeLocation, m_cameraCapability->eye());
m_material.use();
m_icosahedron->draw();
program->release();
m_material.release();
Framebuffer::unbind(GL_FRAMEBUFFER);
}
| 29.027778
| 137
| 0.746264
|
Daniel-Amadeus
|
1e5295683ca853d509b5a4bd4557dfbefedf5bc5
| 1,610
|
cpp
|
C++
|
ReplaceSpaces.cpp
|
vibiu/SwordOfOffer
|
6daa7d108a4f043353d372e835a1f8923c933dcc
|
[
"BSD-3-Clause"
] | 1
|
2020-05-14T13:59:11.000Z
|
2020-05-14T13:59:11.000Z
|
ReplaceSpaces.cpp
|
vibiu/SwordOfOffer
|
6daa7d108a4f043353d372e835a1f8923c933dcc
|
[
"BSD-3-Clause"
] | null | null | null |
ReplaceSpaces.cpp
|
vibiu/SwordOfOffer
|
6daa7d108a4f043353d372e835a1f8923c933dcc
|
[
"BSD-3-Clause"
] | null | null | null |
#include <cstdio>
#include <cstring>
#include "ReplaceSpaces.h"
void ReplaceBlank(char str[], int length)
{
if (str == nullptr && length <= 0)
return;
/*originalLength 为字符串str的实际长度*/
int originalLength = 0;
int numberOfBlank = 0;
int i = 0;
while (str[i] != '\0')
{
++originalLength;
if (str[i] == ' ')
++numberOfBlank;
++i;
}
/*newLength 为把空格替换成'%20'之后的长度*/
int newLength = originalLength + numberOfBlank * 2;
if (newLength > length)
return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
{
if (str[indexOfOriginal] == ' ')
{
str[indexOfNew--] = '0';
str[indexOfNew--] = '2';
str[indexOfNew--] = '%';
}
else
{
str[indexOfNew--] = str[indexOfOriginal];
}
--indexOfOriginal;
}
}
void ReplaceSpacesTest(const char *testName, char str[], int length, const char expected[])
{
if (testName != nullptr)
printf("%s begins: ", testName);
ReplaceBlank(str, length);
if (expected == nullptr && str == nullptr)
printf("passed.\n");
else if (expected == nullptr && str != nullptr)
printf("failed.\n");
else if (strcmp(str, expected) == 0)
printf("passed.\n");
else
printf("failed.\n");
}
void ReplaceSpacesTest1()
{
const int length = 100;
char str[length] = "hello world";
ReplaceSpacesTest("Test1", str, length, "hello%20world");
}
| 22.361111
| 91
| 0.549689
|
vibiu
|
1e52e890ed966f619cab3c2b912d4c6bb0728065
| 37,325
|
cpp
|
C++
|
TiCore/parser/Lexer.cpp
|
vishalduggal/tijscore
|
0b20b5731766628109bdd2c657558de9d5a976ec
|
[
"MS-PL",
"Naumen",
"Condor-1.1",
"Apache-1.1"
] | null | null | null |
TiCore/parser/Lexer.cpp
|
vishalduggal/tijscore
|
0b20b5731766628109bdd2c657558de9d5a976ec
|
[
"MS-PL",
"Naumen",
"Condor-1.1",
"Apache-1.1"
] | null | null | null |
TiCore/parser/Lexer.cpp
|
vishalduggal/tijscore
|
0b20b5731766628109bdd2c657558de9d5a976ec
|
[
"MS-PL",
"Naumen",
"Condor-1.1",
"Apache-1.1"
] | null | null | null |
/**
* Appcelerator Titanium License
* This source code and all modifications done by Appcelerator
* are licensed under the Apache Public License (version 2) and
* are Copyright (c) 2009-2012 by Appcelerator, Inc.
*/
/*
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All Rights Reserved.
* Copyright (C) 2007 Cameron Zwarich (cwzwarich@uwaterloo.ca)
* Copyright (C) 2010 Zoltan Herczeg (zherczeg@inf.u-szeged.hu)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "Lexer.h"
#include "TiFunction.h"
#include "TiGlobalObjectFunctions.h"
#include "Identifier.h"
#include "NodeInfo.h"
#include "Nodes.h"
#include "dtoa.h"
#include <ctype.h>
#include <limits.h>
#include <string.h>
#include <wtf/Assertions.h>
using namespace WTI;
using namespace Unicode;
#include "JSParser.h"
#include "KeywordLookup.h"
#include "Lookup.h"
#include "Lexer.lut.h"
namespace TI {
enum CharacterType {
// Types for the main switch
// The first three types are fixed, and also used for identifying
// ASCII alpha and alphanumeric characters (see isIdentStart and isIdentPart).
CharacterIdentifierStart,
CharacterZero,
CharacterNumber,
CharacterInvalid,
CharacterLineTerminator,
CharacterExclamationMark,
CharacterOpenParen,
CharacterCloseParen,
CharacterOpenBracket,
CharacterCloseBracket,
CharacterComma,
CharacterColon,
CharacterQuestion,
CharacterTilde,
CharacterQuote,
CharacterDot,
CharacterSlash,
CharacterBackSlash,
CharacterSemicolon,
CharacterOpenBrace,
CharacterCloseBrace,
CharacterAdd,
CharacterSub,
CharacterMultiply,
CharacterModulo,
CharacterAnd,
CharacterXor,
CharacterOr,
CharacterLess,
CharacterGreater,
CharacterEqual,
// Other types (only one so far)
CharacterWhiteSpace,
};
// 128 ASCII codes
static const unsigned short typesOfASCIICharacters[128] = {
/* 0 - Null */ CharacterInvalid,
/* 1 - Start of Heading */ CharacterInvalid,
/* 2 - Start of Text */ CharacterInvalid,
/* 3 - End of Text */ CharacterInvalid,
/* 4 - End of Transm. */ CharacterInvalid,
/* 5 - Enquiry */ CharacterInvalid,
/* 6 - Acknowledgment */ CharacterInvalid,
/* 7 - Bell */ CharacterInvalid,
/* 8 - Back Space */ CharacterInvalid,
/* 9 - Horizontal Tab */ CharacterWhiteSpace,
/* 10 - Line Feed */ CharacterLineTerminator,
/* 11 - Vertical Tab */ CharacterWhiteSpace,
/* 12 - Form Feed */ CharacterWhiteSpace,
/* 13 - Carriage Return */ CharacterLineTerminator,
/* 14 - Shift Out */ CharacterInvalid,
/* 15 - Shift In */ CharacterInvalid,
/* 16 - Data Line Escape */ CharacterInvalid,
/* 17 - Device Control 1 */ CharacterInvalid,
/* 18 - Device Control 2 */ CharacterInvalid,
/* 19 - Device Control 3 */ CharacterInvalid,
/* 20 - Device Control 4 */ CharacterInvalid,
/* 21 - Negative Ack. */ CharacterInvalid,
/* 22 - Synchronous Idle */ CharacterInvalid,
/* 23 - End of Transmit */ CharacterInvalid,
/* 24 - Cancel */ CharacterInvalid,
/* 25 - End of Medium */ CharacterInvalid,
/* 26 - Substitute */ CharacterInvalid,
/* 27 - Escape */ CharacterInvalid,
/* 28 - File Separator */ CharacterInvalid,
/* 29 - Group Separator */ CharacterInvalid,
/* 30 - Record Separator */ CharacterInvalid,
/* 31 - Unit Separator */ CharacterInvalid,
/* 32 - Space */ CharacterWhiteSpace,
/* 33 - ! */ CharacterExclamationMark,
/* 34 - " */ CharacterQuote,
/* 35 - # */ CharacterInvalid,
/* 36 - $ */ CharacterIdentifierStart,
/* 37 - % */ CharacterModulo,
/* 38 - & */ CharacterAnd,
/* 39 - ' */ CharacterQuote,
/* 40 - ( */ CharacterOpenParen,
/* 41 - ) */ CharacterCloseParen,
/* 42 - * */ CharacterMultiply,
/* 43 - + */ CharacterAdd,
/* 44 - , */ CharacterComma,
/* 45 - - */ CharacterSub,
/* 46 - . */ CharacterDot,
/* 47 - / */ CharacterSlash,
/* 48 - 0 */ CharacterZero,
/* 49 - 1 */ CharacterNumber,
/* 50 - 2 */ CharacterNumber,
/* 51 - 3 */ CharacterNumber,
/* 52 - 4 */ CharacterNumber,
/* 53 - 5 */ CharacterNumber,
/* 54 - 6 */ CharacterNumber,
/* 55 - 7 */ CharacterNumber,
/* 56 - 8 */ CharacterNumber,
/* 57 - 9 */ CharacterNumber,
/* 58 - : */ CharacterColon,
/* 59 - ; */ CharacterSemicolon,
/* 60 - < */ CharacterLess,
/* 61 - = */ CharacterEqual,
/* 62 - > */ CharacterGreater,
/* 63 - ? */ CharacterQuestion,
/* 64 - @ */ CharacterInvalid,
/* 65 - A */ CharacterIdentifierStart,
/* 66 - B */ CharacterIdentifierStart,
/* 67 - C */ CharacterIdentifierStart,
/* 68 - D */ CharacterIdentifierStart,
/* 69 - E */ CharacterIdentifierStart,
/* 70 - F */ CharacterIdentifierStart,
/* 71 - G */ CharacterIdentifierStart,
/* 72 - H */ CharacterIdentifierStart,
/* 73 - I */ CharacterIdentifierStart,
/* 74 - J */ CharacterIdentifierStart,
/* 75 - K */ CharacterIdentifierStart,
/* 76 - L */ CharacterIdentifierStart,
/* 77 - M */ CharacterIdentifierStart,
/* 78 - N */ CharacterIdentifierStart,
/* 79 - O */ CharacterIdentifierStart,
/* 80 - P */ CharacterIdentifierStart,
/* 81 - Q */ CharacterIdentifierStart,
/* 82 - R */ CharacterIdentifierStart,
/* 83 - S */ CharacterIdentifierStart,
/* 84 - T */ CharacterIdentifierStart,
/* 85 - U */ CharacterIdentifierStart,
/* 86 - V */ CharacterIdentifierStart,
/* 87 - W */ CharacterIdentifierStart,
/* 88 - X */ CharacterIdentifierStart,
/* 89 - Y */ CharacterIdentifierStart,
/* 90 - Z */ CharacterIdentifierStart,
/* 91 - [ */ CharacterOpenBracket,
/* 92 - \ */ CharacterBackSlash,
/* 93 - ] */ CharacterCloseBracket,
/* 94 - ^ */ CharacterXor,
/* 95 - _ */ CharacterIdentifierStart,
/* 96 - ` */ CharacterInvalid,
/* 97 - a */ CharacterIdentifierStart,
/* 98 - b */ CharacterIdentifierStart,
/* 99 - c */ CharacterIdentifierStart,
/* 100 - d */ CharacterIdentifierStart,
/* 101 - e */ CharacterIdentifierStart,
/* 102 - f */ CharacterIdentifierStart,
/* 103 - g */ CharacterIdentifierStart,
/* 104 - h */ CharacterIdentifierStart,
/* 105 - i */ CharacterIdentifierStart,
/* 106 - j */ CharacterIdentifierStart,
/* 107 - k */ CharacterIdentifierStart,
/* 108 - l */ CharacterIdentifierStart,
/* 109 - m */ CharacterIdentifierStart,
/* 110 - n */ CharacterIdentifierStart,
/* 111 - o */ CharacterIdentifierStart,
/* 112 - p */ CharacterIdentifierStart,
/* 113 - q */ CharacterIdentifierStart,
/* 114 - r */ CharacterIdentifierStart,
/* 115 - s */ CharacterIdentifierStart,
/* 116 - t */ CharacterIdentifierStart,
/* 117 - u */ CharacterIdentifierStart,
/* 118 - v */ CharacterIdentifierStart,
/* 119 - w */ CharacterIdentifierStart,
/* 120 - x */ CharacterIdentifierStart,
/* 121 - y */ CharacterIdentifierStart,
/* 122 - z */ CharacterIdentifierStart,
/* 123 - { */ CharacterOpenBrace,
/* 124 - | */ CharacterOr,
/* 125 - } */ CharacterCloseBrace,
/* 126 - ~ */ CharacterTilde,
/* 127 - Delete */ CharacterInvalid,
};
Lexer::Lexer(TiGlobalData* globalData)
: m_isReparsing(false)
, m_globalData(globalData)
, m_keywordTable(TI::mainTable)
{
}
Lexer::~Lexer()
{
m_keywordTable.deleteTable();
}
ALWAYS_INLINE const UChar* Lexer::currentCharacter() const
{
ASSERT(m_code <= m_codeEnd);
return m_code;
}
ALWAYS_INLINE int Lexer::currentOffset() const
{
return currentCharacter() - m_codeStart;
}
void Lexer::setCode(const SourceCode& source, ParserArena& arena)
{
m_arena = &arena.identifierArena();
m_lineNumber = source.firstLine();
m_delimited = false;
m_lastToken = -1;
const UChar* data = source.provider()->data();
m_source = &source;
m_codeStart = data;
m_code = data + source.startOffset();
m_codeEnd = data + source.endOffset();
m_error = false;
m_atLineStart = true;
m_buffer8.reserveInitialCapacity(initialReadBufferCapacity);
m_buffer16.reserveInitialCapacity((m_codeEnd - m_code) / 2);
if (LIKELY(m_code < m_codeEnd))
m_current = *m_code;
else
m_current = -1;
ASSERT(currentOffset() == source.startOffset());
}
template <int shiftAmount, Lexer::ShiftType shouldBoundsCheck> ALWAYS_INLINE void Lexer::internalShift()
{
if (shouldBoundsCheck == DoBoundsCheck) {
// Faster than an if-else sequence
ASSERT(m_current != -1);
m_current = -1;
m_code += shiftAmount;
if (LIKELY(m_code < m_codeEnd))
m_current = *m_code;
} else {
m_code += shiftAmount;
m_current = *m_code;
}
}
ALWAYS_INLINE void Lexer::shift()
{
internalShift<1, DoBoundsCheck>();
}
ALWAYS_INLINE int Lexer::peek(int offset)
{
// Only use if necessary
ASSERT(offset > 0 && offset < 5);
const UChar* code = m_code + offset;
return (code < m_codeEnd) ? *code : -1;
}
int Lexer::getUnicodeCharacter()
{
int char1 = peek(1);
int char2 = peek(2);
int char3 = peek(3);
if (UNLIKELY(!isASCIIHexDigit(m_current) || !isASCIIHexDigit(char1) || !isASCIIHexDigit(char2) || !isASCIIHexDigit(char3)))
return -1;
int result = convertUnicode(m_current, char1, char2, char3);
shift();
shift();
shift();
shift();
return result;
}
void Lexer::shiftLineTerminator()
{
ASSERT(isLineTerminator(m_current));
int m_prev = m_current;
shift();
// Allow both CRLF and LFCR.
if (m_prev + m_current == '\n' + '\r')
shift();
++m_lineNumber;
}
ALWAYS_INLINE bool Lexer::lastTokenWasRestrKeyword() const
{
return m_lastToken == CONTINUE || m_lastToken == BREAK || m_lastToken == RETURN || m_lastToken == THROW;
}
static NEVER_INLINE bool isNonASCIIIdentStart(int c)
{
return category(c) & (Letter_Uppercase | Letter_Lowercase | Letter_Titlecase | Letter_Modifier | Letter_Other);
}
static inline bool isIdentStart(int c)
{
return isASCII(c) ? typesOfASCIICharacters[c] == CharacterIdentifierStart : isNonASCIIIdentStart(c);
}
static NEVER_INLINE bool isNonASCIIIdentPart(int c)
{
return category(c) & (Letter_Uppercase | Letter_Lowercase | Letter_Titlecase | Letter_Modifier | Letter_Other
| Mark_NonSpacing | Mark_SpacingCombining | Number_DecimalDigit | Punctuation_Connector);
}
static ALWAYS_INLINE bool isIdentPart(int c)
{
// Character types are divided into two groups depending on whether they can be part of an
// identifier or not. Those whose type value is less or equal than CharacterNumber can be
// part of an identifier. (See the CharacterType definition for more details.)
return isASCII(c) ? typesOfASCIICharacters[c] <= CharacterNumber : isNonASCIIIdentPart(c);
}
static inline int singleEscape(int c)
{
switch (c) {
case 'b':
return 0x08;
case 't':
return 0x09;
case 'n':
return 0x0A;
case 'v':
return 0x0B;
case 'f':
return 0x0C;
case 'r':
return 0x0D;
case '\\':
return '\\';
case '\'':
return '\'';
case '"':
return '"';
default:
return 0;
}
}
inline void Lexer::record8(int c)
{
ASSERT(c >= 0);
ASSERT(c <= 0xFF);
m_buffer8.append(static_cast<char>(c));
}
inline void Lexer::record16(UChar c)
{
m_buffer16.append(c);
}
inline void Lexer::record16(int c)
{
ASSERT(c >= 0);
ASSERT(c <= USHRT_MAX);
record16(UChar(static_cast<unsigned short>(c)));
}
template <bool shouldCreateIdentifier> ALWAYS_INLINE JSTokenType Lexer::parseIdentifier(JSTokenData* tokenData, unsigned lexType)
{
const ptrdiff_t remaining = m_codeEnd - m_code;
if ((remaining >= maxTokenLength) && !(lexType & IgnoreReservedWords)) {
JSTokenType keyword = parseKeyword<shouldCreateIdentifier>(tokenData);
if (keyword != IDENT) {
ASSERT((!shouldCreateIdentifier) || tokenData->ident);
return keyword;
}
}
const UChar* identifierStart = currentCharacter();
bool bufferRequired = false;
while (true) {
if (LIKELY(isIdentPart(m_current))) {
shift();
continue;
}
if (LIKELY(m_current != '\\'))
break;
// \uXXXX unicode characters.
bufferRequired = true;
if (identifierStart != currentCharacter())
m_buffer16.append(identifierStart, currentCharacter() - identifierStart);
shift();
if (UNLIKELY(m_current != 'u'))
return ERRORTOK;
shift();
int character = getUnicodeCharacter();
if (UNLIKELY(character == -1))
return ERRORTOK;
if (UNLIKELY(m_buffer16.size() ? !isIdentPart(character) : !isIdentStart(character)))
return ERRORTOK;
if (shouldCreateIdentifier)
record16(character);
identifierStart = currentCharacter();
}
int identifierLength;
const Identifier* ident = 0;
if (shouldCreateIdentifier) {
if (!bufferRequired)
identifierLength = currentCharacter() - identifierStart;
else {
if (identifierStart != currentCharacter())
m_buffer16.append(identifierStart, currentCharacter() - identifierStart);
identifierStart = m_buffer16.data();
identifierLength = m_buffer16.size();
}
ident = makeIdentifier(identifierStart, identifierLength);
tokenData->ident = ident;
} else
tokenData->ident = 0;
m_delimited = false;
if (LIKELY(!bufferRequired && !(lexType & IgnoreReservedWords))) {
ASSERT(shouldCreateIdentifier);
// Keywords must not be recognized if there was an \uXXXX in the identifier.
if (remaining < maxTokenLength) {
const HashEntry* entry = m_keywordTable.entry(m_globalData, *ident);
ASSERT((remaining < maxTokenLength) || !entry);
return entry ? static_cast<JSTokenType>(entry->lexerValue()) : IDENT;
}
return IDENT;
}
m_buffer16.resize(0);
return IDENT;
}
bool Lexer::isKeyword(const Identifier& ident)
{
return m_keywordTable.entry(m_globalData, ident);
}
template <bool shouldBuildStrings> ALWAYS_INLINE bool Lexer::parseString(JSTokenData* tokenData, bool strictMode)
{
int stringQuoteCharacter = m_current;
shift();
const UChar* stringStart = currentCharacter();
while (m_current != stringQuoteCharacter) {
if (UNLIKELY(m_current == '\\')) {
if (stringStart != currentCharacter() && shouldBuildStrings)
m_buffer16.append(stringStart, currentCharacter() - stringStart);
shift();
int escape = singleEscape(m_current);
// Most common escape sequences first
if (escape) {
if (shouldBuildStrings)
record16(escape);
shift();
} else if (UNLIKELY(isLineTerminator(m_current)))
shiftLineTerminator();
else if (m_current == 'x') {
shift();
if (isASCIIHexDigit(m_current) && isASCIIHexDigit(peek(1))) {
int prev = m_current;
shift();
if (shouldBuildStrings)
record16(convertHex(prev, m_current));
shift();
} else if (shouldBuildStrings)
record16('x');
} else if (m_current == 'u') {
shift();
int character = getUnicodeCharacter();
if (character != -1) {
if (shouldBuildStrings)
record16(character);
} else if (m_current == stringQuoteCharacter) {
if (shouldBuildStrings)
record16('u');
} else // Only stringQuoteCharacter allowed after \u
return false;
} else if (strictMode && isASCIIDigit(m_current)) {
// The only valid numeric escape in strict mode is '\0', and this must not be followed by a decimal digit.
int character1 = m_current;
shift();
if (character1 != '0' || isASCIIDigit(m_current))
return false;
if (shouldBuildStrings)
record16(0);
} else if (!strictMode && isASCIIOctalDigit(m_current)) {
// Octal character sequences
int character1 = m_current;
shift();
if (isASCIIOctalDigit(m_current)) {
// Two octal characters
int character2 = m_current;
shift();
if (character1 >= '0' && character1 <= '3' && isASCIIOctalDigit(m_current)) {
if (shouldBuildStrings)
record16((character1 - '0') * 64 + (character2 - '0') * 8 + m_current - '0');
shift();
} else {
if (shouldBuildStrings)
record16((character1 - '0') * 8 + character2 - '0');
}
} else {
if (shouldBuildStrings)
record16(character1 - '0');
}
} else if (m_current != -1) {
if (shouldBuildStrings)
record16(m_current);
shift();
} else
return false;
stringStart = currentCharacter();
continue;
}
// Fast check for characters that require special handling.
// Catches -1, \n, \r, 0x2028, and 0x2029 as efficiently
// as possible, and lets through all common ASCII characters.
if (UNLIKELY(((static_cast<unsigned>(m_current) - 0xE) & 0x2000))) {
// New-line or end of input is not allowed
if (UNLIKELY(isLineTerminator(m_current)) || UNLIKELY(m_current == -1))
return false;
// Anything else is just a normal character
}
shift();
}
if (currentCharacter() != stringStart && shouldBuildStrings)
m_buffer16.append(stringStart, currentCharacter() - stringStart);
if (shouldBuildStrings)
tokenData->ident = makeIdentifier(m_buffer16.data(), m_buffer16.size());
else
tokenData->ident = 0;
m_buffer16.resize(0);
return true;
}
ALWAYS_INLINE void Lexer::parseHex(double& returnValue)
{
// Optimization: most hexadecimal values fit into 4 bytes.
uint32_t hexValue = 0;
int maximumDigits = 7;
// Shift out the 'x' prefix.
shift();
do {
hexValue = (hexValue << 4) + toASCIIHexValue(m_current);
shift();
--maximumDigits;
} while (isASCIIHexDigit(m_current) && maximumDigits >= 0);
if (maximumDigits >= 0) {
returnValue = hexValue;
return;
}
// No more place in the hexValue buffer.
// The values are shifted out and placed into the m_buffer8 vector.
for (int i = 0; i < 8; ++i) {
int digit = hexValue >> 28;
if (digit < 10)
record8(digit + '0');
else
record8(digit - 10 + 'a');
hexValue <<= 4;
}
while (isASCIIHexDigit(m_current)) {
record8(m_current);
shift();
}
returnValue = parseIntOverflow(m_buffer8.data(), m_buffer8.size(), 16);
}
ALWAYS_INLINE bool Lexer::parseOctal(double& returnValue)
{
// Optimization: most octal values fit into 4 bytes.
uint32_t octalValue = 0;
int maximumDigits = 9;
// Temporary buffer for the digits. Makes easier
// to reconstruct the input characters when needed.
char digits[10];
do {
octalValue = octalValue * 8 + (m_current - '0');
digits[maximumDigits] = m_current;
shift();
--maximumDigits;
} while (isASCIIOctalDigit(m_current) && maximumDigits >= 0);
if (!isASCIIDigit(m_current) && maximumDigits >= 0) {
returnValue = octalValue;
return true;
}
for (int i = 9; i > maximumDigits; --i)
record8(digits[i]);
while (isASCIIOctalDigit(m_current)) {
record8(m_current);
shift();
}
if (isASCIIDigit(m_current))
return false;
returnValue = parseIntOverflow(m_buffer8.data(), m_buffer8.size(), 8);
return true;
}
ALWAYS_INLINE bool Lexer::parseDecimal(double& returnValue)
{
// Optimization: most decimal values fit into 4 bytes.
uint32_t decimalValue = 0;
// Since parseOctal may be executed before parseDecimal,
// the m_buffer8 may hold ascii digits.
if (!m_buffer8.size()) {
int maximumDigits = 9;
// Temporary buffer for the digits. Makes easier
// to reconstruct the input characters when needed.
char digits[10];
do {
decimalValue = decimalValue * 10 + (m_current - '0');
digits[maximumDigits] = m_current;
shift();
--maximumDigits;
} while (isASCIIDigit(m_current) && maximumDigits >= 0);
if (maximumDigits >= 0 && m_current != '.' && (m_current | 0x20) != 'e') {
returnValue = decimalValue;
return true;
}
for (int i = 9; i > maximumDigits; --i)
record8(digits[i]);
}
while (isASCIIDigit(m_current)) {
record8(m_current);
shift();
}
return false;
}
ALWAYS_INLINE void Lexer::parseNumberAfterDecimalPoint()
{
record8('.');
while (isASCIIDigit(m_current)) {
record8(m_current);
shift();
}
}
ALWAYS_INLINE bool Lexer::parseNumberAfterExponentIndicator()
{
record8('e');
shift();
if (m_current == '+' || m_current == '-') {
record8(m_current);
shift();
}
if (!isASCIIDigit(m_current))
return false;
do {
record8(m_current);
shift();
} while (isASCIIDigit(m_current));
return true;
}
ALWAYS_INLINE bool Lexer::parseMultilineComment()
{
while (true) {
while (UNLIKELY(m_current == '*')) {
shift();
if (m_current == '/') {
shift();
return true;
}
}
if (UNLIKELY(m_current == -1))
return false;
if (isLineTerminator(m_current))
shiftLineTerminator();
else
shift();
}
}
bool Lexer::nextTokenIsColon()
{
const UChar* code = m_code;
while (code < m_codeEnd && (isWhiteSpace(*code) || isLineTerminator(*code)))
code++;
return code < m_codeEnd && *code == ':';
}
JSTokenType Lexer::lex(JSTokenData* tokenData, JSTokenInfo* tokenInfo, unsigned lexType, bool strictMode)
{
ASSERT(!m_error);
ASSERT(m_buffer8.isEmpty());
ASSERT(m_buffer16.isEmpty());
JSTokenType token = ERRORTOK;
m_terminator = false;
start:
while (isWhiteSpace(m_current))
shift();
int startOffset = currentOffset();
if (UNLIKELY(m_current == -1))
return EOFTOK;
m_delimited = false;
CharacterType type;
if (LIKELY(isASCII(m_current)))
type = static_cast<CharacterType>(typesOfASCIICharacters[m_current]);
else if (isNonASCIIIdentStart(m_current))
type = CharacterIdentifierStart;
else if (isLineTerminator(m_current))
type = CharacterLineTerminator;
else
type = CharacterInvalid;
switch (type) {
case CharacterGreater:
shift();
if (m_current == '>') {
shift();
if (m_current == '>') {
shift();
if (m_current == '=') {
shift();
token = URSHIFTEQUAL;
break;
}
token = URSHIFT;
break;
}
if (m_current == '=') {
shift();
token = RSHIFTEQUAL;
break;
}
token = RSHIFT;
break;
}
if (m_current == '=') {
shift();
token = GE;
break;
}
token = GT;
break;
case CharacterEqual:
shift();
if (m_current == '=') {
shift();
if (m_current == '=') {
shift();
token = STREQ;
break;
}
token = EQEQ;
break;
}
token = EQUAL;
break;
case CharacterLess:
shift();
if (m_current == '!' && peek(1) == '-' && peek(2) == '-') {
// <!-- marks the beginning of a line comment (for www usage)
goto inSingleLineComment;
}
if (m_current == '<') {
shift();
if (m_current == '=') {
shift();
token = LSHIFTEQUAL;
break;
}
token = LSHIFT;
break;
}
if (m_current == '=') {
shift();
token = LE;
break;
}
token = LT;
break;
case CharacterExclamationMark:
shift();
if (m_current == '=') {
shift();
if (m_current == '=') {
shift();
token = STRNEQ;
break;
}
token = NE;
break;
}
token = EXCLAMATION;
break;
case CharacterAdd:
shift();
if (m_current == '+') {
shift();
token = (!m_terminator) ? PLUSPLUS : AUTOPLUSPLUS;
break;
}
if (m_current == '=') {
shift();
token = PLUSEQUAL;
break;
}
token = PLUS;
break;
case CharacterSub:
shift();
if (m_current == '-') {
shift();
if (m_atLineStart && m_current == '>') {
shift();
goto inSingleLineComment;
}
token = (!m_terminator) ? MINUSMINUS : AUTOMINUSMINUS;
break;
}
if (m_current == '=') {
shift();
token = MINUSEQUAL;
break;
}
token = MINUS;
break;
case CharacterMultiply:
shift();
if (m_current == '=') {
shift();
token = MULTEQUAL;
break;
}
token = TIMES;
break;
case CharacterSlash:
shift();
if (m_current == '/') {
shift();
goto inSingleLineComment;
}
if (m_current == '*') {
shift();
if (parseMultilineComment())
goto start;
goto returnError;
}
if (m_current == '=') {
shift();
token = DIVEQUAL;
break;
}
token = DIVIDE;
break;
case CharacterAnd:
shift();
if (m_current == '&') {
shift();
token = AND;
break;
}
if (m_current == '=') {
shift();
token = ANDEQUAL;
break;
}
token = BITAND;
break;
case CharacterXor:
shift();
if (m_current == '=') {
shift();
token = XOREQUAL;
break;
}
token = BITXOR;
break;
case CharacterModulo:
shift();
if (m_current == '=') {
shift();
token = MODEQUAL;
break;
}
token = MOD;
break;
case CharacterOr:
shift();
if (m_current == '=') {
shift();
token = OREQUAL;
break;
}
if (m_current == '|') {
shift();
token = OR;
break;
}
token = BITOR;
break;
case CharacterOpenParen:
token = OPENPAREN;
shift();
break;
case CharacterCloseParen:
token = CLOSEPAREN;
shift();
break;
case CharacterOpenBracket:
token = OPENBRACKET;
shift();
break;
case CharacterCloseBracket:
token = CLOSEBRACKET;
shift();
break;
case CharacterComma:
token = COMMA;
shift();
break;
case CharacterColon:
token = COLON;
shift();
break;
case CharacterQuestion:
token = QUESTION;
shift();
break;
case CharacterTilde:
token = TILDE;
shift();
break;
case CharacterSemicolon:
m_delimited = true;
shift();
token = SEMICOLON;
break;
case CharacterOpenBrace:
tokenData->intValue = currentOffset();
shift();
token = OPENBRACE;
break;
case CharacterCloseBrace:
tokenData->intValue = currentOffset();
m_delimited = true;
shift();
token = CLOSEBRACE;
break;
case CharacterDot:
shift();
if (!isASCIIDigit(m_current)) {
token = DOT;
break;
}
goto inNumberAfterDecimalPoint;
case CharacterZero:
shift();
if ((m_current | 0x20) == 'x' && isASCIIHexDigit(peek(1))) {
parseHex(tokenData->doubleValue);
token = NUMBER;
} else {
record8('0');
if (isASCIIOctalDigit(m_current)) {
if (parseOctal(tokenData->doubleValue)) {
if (strictMode)
goto returnError;
token = NUMBER;
}
}
}
// Fall through into CharacterNumber
case CharacterNumber:
if (LIKELY(token != NUMBER)) {
if (!parseDecimal(tokenData->doubleValue)) {
if (m_current == '.') {
shift();
inNumberAfterDecimalPoint:
parseNumberAfterDecimalPoint();
}
if ((m_current | 0x20) == 'e')
if (!parseNumberAfterExponentIndicator())
goto returnError;
// Null-terminate string for strtod.
m_buffer8.append('\0');
tokenData->doubleValue = WTI::strtod(m_buffer8.data(), 0);
}
token = NUMBER;
}
// No identifiers allowed directly after numeric literal, e.g. "3in" is bad.
if (UNLIKELY(isIdentStart(m_current)))
goto returnError;
m_buffer8.resize(0);
m_delimited = false;
break;
case CharacterQuote:
if (lexType & DontBuildStrings) {
if (UNLIKELY(!parseString<false>(tokenData, strictMode)))
goto returnError;
} else {
if (UNLIKELY(!parseString<true>(tokenData, strictMode)))
goto returnError;
}
shift();
m_delimited = false;
token = STRING;
break;
case CharacterIdentifierStart:
ASSERT(isIdentStart(m_current));
// Fall through into CharacterBackSlash.
case CharacterBackSlash:
if (lexType & DontBuildKeywords)
token = parseIdentifier<false>(tokenData, lexType);
else
token = parseIdentifier<true>(tokenData, lexType);
break;
case CharacterLineTerminator:
ASSERT(isLineTerminator(m_current));
shiftLineTerminator();
m_atLineStart = true;
m_terminator = true;
goto start;
case CharacterInvalid:
goto returnError;
default:
ASSERT_NOT_REACHED();
goto returnError;
}
m_atLineStart = false;
goto returnToken;
inSingleLineComment:
while (!isLineTerminator(m_current)) {
if (UNLIKELY(m_current == -1))
return EOFTOK;
shift();
}
shiftLineTerminator();
m_atLineStart = true;
m_terminator = true;
if (!lastTokenWasRestrKeyword())
goto start;
token = SEMICOLON;
m_delimited = true;
// Fall through into returnToken.
returnToken:
tokenInfo->line = m_lineNumber;
tokenInfo->startOffset = startOffset;
tokenInfo->endOffset = currentOffset();
m_lastToken = token;
return token;
returnError:
m_error = true;
return ERRORTOK;
}
bool Lexer::scanRegExp(const Identifier*& pattern, const Identifier*& flags, UChar patternPrefix)
{
ASSERT(m_buffer16.isEmpty());
bool lastWasEscape = false;
bool inBrackets = false;
if (patternPrefix) {
ASSERT(!isLineTerminator(patternPrefix));
ASSERT(patternPrefix != '/');
ASSERT(patternPrefix != '[');
record16(patternPrefix);
}
while (true) {
int current = m_current;
if (isLineTerminator(current) || current == -1) {
m_buffer16.resize(0);
return false;
}
shift();
if (current == '/' && !lastWasEscape && !inBrackets)
break;
record16(current);
if (lastWasEscape) {
lastWasEscape = false;
continue;
}
switch (current) {
case '[':
inBrackets = true;
break;
case ']':
inBrackets = false;
break;
case '\\':
lastWasEscape = true;
break;
}
}
pattern = makeIdentifier(m_buffer16.data(), m_buffer16.size());
m_buffer16.resize(0);
while (isIdentPart(m_current)) {
record16(m_current);
shift();
}
flags = makeIdentifier(m_buffer16.data(), m_buffer16.size());
m_buffer16.resize(0);
return true;
}
bool Lexer::skipRegExp()
{
bool lastWasEscape = false;
bool inBrackets = false;
while (true) {
int current = m_current;
if (isLineTerminator(current) || current == -1)
return false;
shift();
if (current == '/' && !lastWasEscape && !inBrackets)
break;
if (lastWasEscape) {
lastWasEscape = false;
continue;
}
switch (current) {
case '[':
inBrackets = true;
break;
case ']':
inBrackets = false;
break;
case '\\':
lastWasEscape = true;
break;
}
}
while (isIdentPart(m_current))
shift();
return true;
}
void Lexer::clear()
{
m_arena = 0;
Vector<char> newBuffer8;
m_buffer8.swap(newBuffer8);
Vector<UChar> newBuffer16;
m_buffer16.swap(newBuffer16);
m_isReparsing = false;
}
SourceCode Lexer::sourceCode(int openBrace, int closeBrace, int firstLine)
{
ASSERT(m_source->provider()->data()[openBrace] == '{');
ASSERT(m_source->provider()->data()[closeBrace] == '}');
return SourceCode(m_source->provider(), openBrace, closeBrace + 1, firstLine);
}
} // namespace TI
| 29.482622
| 129
| 0.538915
|
vishalduggal
|
1e63204323970519a2b4a87c02c96b6886b5ed48
| 8,654
|
cpp
|
C++
|
Interface/ViewModerate.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | 1
|
2016-05-22T21:28:29.000Z
|
2016-05-22T21:28:29.000Z
|
Interface/ViewModerate.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | null | null | null |
Interface/ViewModerate.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | null | null | null |
/*
ViewModerate.cpp
(c)2000 Palestar, Richard Lyle
*/
#include "Debug/Assert.h"
#include "Standard/Time.h"
#include "Interface/ViewModerate.h"
//----------------------------------------------------------------------------
IMPLEMENT_FACTORY( ViewModerate, WindowView::View );
REGISTER_FACTORY_KEY( ViewModerate, 4420985700173175596 );
ViewModerate::ViewModerate() : m_UpdateTime( 0 )
{
// Construct your view class
}
//----------------------------------------------------------------------------
void ViewModerate::onActivate()
{
GameDocument * pDoc = (GameDocument *)document();
ASSERT( pDoc );
// turn on moderator mode
pDoc->client()->setModerate( true );
// get current server info
pDoc->client()->sendServerStatus();
m_UpdateTime = 0.0f;
m_nLastUpdate = 0;
m_nLastBytesRecv = 0;
m_nLastBytesSent = 0;
//{{BEGIN_DATA_INIT
m_pTextStatus = WidgetCast<WindowText>( window()->findNode( "TextStatus" ) );
m_pChatEdit = WidgetCast<WindowEdit>( window()->findNode( "ChatEdit" ) );
m_pChatEditWindow = WidgetCast<NodeWindow>( window()->findNode( "ChatEditWindow" ) );
m_pListObjects = WidgetCast<WindowList>( window()->findNode( "ListObjects" ) );
m_pListServers = WidgetCast<WindowList>( window()->findNode( "ListServers" ) );
m_pListClients = WidgetCast<WindowList>( window()->findNode( "ListClients" ) );
m_pObserveWindow = WidgetCast<WindowObserve>( window()->findNode( "ObserveWindow" ) );
//END_DATA_INIT}}
m_pChatEditWindow->hideWindow();
m_pObserveWindow->setTargetMode( WindowObserve::LOCKED );
m_pObserveWindow->setCameraMode( WindowObserve::CHASE );
m_pListClients->addColumn( 150, WHITE ); // name
m_pListClients->addColumn( 100, WHITE ); // user id
m_pListClients->addColumn( 100, WHITE ); // latency
m_pListClients->addColumn( 100, WHITE ); // IP
m_pListServers->addColumn( 300, WHITE ); // name
m_pListServers->addColumn( 100, WHITE ); // clients
updateLists();
}
void ViewModerate::onDeactivate()
{
GameDocument * pDoc = (GameDocument *)document();
ASSERT( pDoc );
// turn off moderator mode
pDoc->client()->setModerate( false );
// clear lists
m_pListClients->removeAll();
m_pListServers->removeAll();
}
void ViewModerate::onUpdate( float t )
{
GameDocument * pDoc = (GameDocument *)document();
ASSERT( pDoc );
m_pChatEditWindow->setVisible( m_pChatEdit->editing() );
m_UpdateTime += t;
if ( m_UpdateTime > 10.0f )
{
m_UpdateTime = 0.0f;
// get updated server information
pDoc->client()->sendServerStatus();
// update the lists
updateLists();
}
}
bool ViewModerate::onMessage( const Message & msg )
{
//{{BEGIN_MSG_MAP
MESSAGE_MAP( WL_SELECT, 928967688, onListObjects);
MESSAGE_MAP( WB_BUTTONUP, 2992269568, onButtonRefresh);
MESSAGE_MAP( WB_BUTTONUP, 1501550643, onButtonExit);
MESSAGE_MAP( WE_EDITDONE, 3966988240, onChatEdit);
MESSAGE_MAP( WB_BUTTONUP, 597305866, onButtonConnect);
MESSAGE_MAP( WB_BUTTONUP, 2596805237, onButtonBan);
MESSAGE_MAP( WB_BUTTONUP, 1503097811, onButtonKick);
//END_MSG_MAP}}
switch( msg.message )
{
case HM_CHAR:
switch( msg.wparam )
{
case HK_RETURN:
m_pChatEditWindow->showWindow();
m_pChatEdit->onBeginEdit();
return true;
}
break;
}
return false;
}
//----------------------------------------------------------------------------
bool ViewModerate::onButtonKick(const Message & msg)
{
int selected = m_pListClients->selected();
if ( selected < 0 )
return false;
int i = m_pListClients->sortedItem( selected );
if ( i >= 0 && i < m_Status.clients.size() )
{
m_pChatEdit->setText( CharString().format("/kick @%u ", m_Status.clients[i].userId) );
m_pChatEdit->onBeginEdit();
}
return true;
}
bool ViewModerate::onButtonBan(const Message & msg)
{
int selected = m_pListClients->selected();
if ( selected < 0 )
return false;
int i = m_pListClients->sortedItem( selected );
if ( i >= 0 && i < m_Status.clients.size() )
{
m_pChatEdit->setText( CharString().format("/ban @%u ", m_Status.clients[i].userId) );
m_pChatEdit->onBeginEdit();
}
return true;
}
bool ViewModerate::onButtonConnect(const Message & msg)
{
GameDocument * pDoc = (GameDocument *)document();
ASSERT( pDoc );
int selected = m_pListServers->selected();
if ( selected < 0 )
return false;
int i = m_pListServers->sortedItem( selected );
if ( i >= 0 && i < m_Servers.size() )
{
// connect to the new server
pDoc->sendChat( CharString().format("/connect %u", m_Servers[i].id) );
// turn moderator mode on for the new server
pDoc->client()->setModerate( true );
// update the lists
updateLists();
}
return true;
}
bool ViewModerate::onChatEdit(const Message & msg)
{
GameDocument * pDoc = (GameDocument *)document();
ASSERT( pDoc );
CharString send( m_pChatEdit->text() );
if ( send.length() > 0 )
{
pDoc->sendChat( send );
m_pChatEdit->setText( "" );
}
return true;
}
bool ViewModerate::onButtonExit(const Message & msg)
{
document()->setScene( "Main" );
return true;
}
bool ViewModerate::onButtonRefresh(const Message & msg)
{
updateLists();
return true;
}
bool ViewModerate::onListObjects(const Message & msg)
{
int selected = m_pListObjects->selected();
if ( selected < 0 )
return false;
int i = m_pListObjects->sortedItem( selected );
if ( i >= 0 && i < m_Objects.size() )
m_pObserveWindow->setTarget( m_Objects[i] );
return true;
}
//----------------------------------------------------------------------------
void ViewModerate::updateLists()
{
GameDocument * pDoc = (GameDocument *)document();
ASSERT( pDoc );
// clear the lists
// get the latest server status
m_Status = pDoc->client()->serverStatus();
dword nSentBPS = 0;
dword nRecvBPS = 0;
dword nCurrentTime = Time::milliseconds();
dword nElapsed = nCurrentTime - m_nLastUpdate;
if ( nElapsed > 0 )
{
nSentBPS = ((m_Status.bytesSent - m_nLastBytesSent) * 1000) / nElapsed;
nRecvBPS = ((m_Status.bytesRecv - m_nLastBytesRecv) * 1000) / nElapsed;
}
m_nLastUpdate = Time::milliseconds();
m_nLastBytesRecv = m_Status.bytesRecv;
m_nLastBytesSent = m_Status.bytesSent;
CharString statusText;
statusText += CharString().format( "<b>%s</b>\nAddress: %s : %u\n\n", m_Status.name, m_Status.address, m_Status.port );
if ( m_Status.upTime > 0 )
{
statusText += CharString().format("Uptime: %2.2u:%2.2u:%2.2u\n", m_Status.upTime / 3600, (m_Status.upTime / 60) % 60, m_Status.upTime % 60);
statusText += CharString().format("Bytes Received: %u / %u bps\n", m_Status.bytesRecv, nRecvBPS );
statusText += CharString().format("Bytes Sent: %u / %u bps\n", m_Status.bytesSent, nSentBPS );
}
statusText += CharString().format("Clients: %u / %u\n", m_Status.clients.size(), m_Status.maxClients );
m_pTextStatus->setText( statusText );
int selected = m_pListClients->selected();
int highlighted = m_pListClients->highlighted();
m_pListClients->removeAllItems();
for(int i=0;i<m_Status.clients.size();i++)
{
GameClient::ClientStatus & client = m_Status.clients[ i ];
int item = m_pListClients->addItem( client.name );
m_pListClients->setItem( item, 1, CharString().format("%u", client.userId) );
m_pListClients->setItem( item, 2, CharString().format("%u ms", client.latency) );
m_pListClients->setItem( item, 3, client.address );
}
m_pListClients->setSelected( selected );
m_pListClients->setHighlighted( selected );
// get the latest server list
MetaClient * pMetaClient = pDoc->client()->metaClient();
ASSERT( pMetaClient );
if ( pMetaClient->connected() )
{
if ( pMetaClient->getServers( "", pMetaClient->gameId(), MetaClient::GAME_SERVER, m_Servers) > 0 )
{
selected = m_pListServers->selected();
highlighted = m_pListServers->highlighted();
m_pListServers->removeAllItems();
for(int i=0;i<m_Servers.size();i++)
{
int item = m_pListServers->addItem( m_Servers[i].name );
m_pListServers->setItem( item, 1, CharString().format("%u / %u", m_Servers[i].clients, m_Servers[i].maxClients) );
}
m_pListServers->setSelected( selected );
m_pListServers->setHighlighted( selected );
}
}
m_Objects.release();
selected = m_pListObjects->selected();
highlighted = m_pListObjects->highlighted();
m_pListObjects->removeAllItems();
GameContext * pContext = pDoc->context();
for(int z=0;z<pContext->zoneCount();z++)
{
NodeZone * pZone = pContext->zone( z );
for(int i=0;i<pZone->childCount();i++)
{
Noun * pNoun = WidgetCast<Noun>( pZone->child(i) );
if ( pNoun != NULL )
m_Objects.push( pNoun );
}
}
for(int i=0;i<m_Objects.size();i++)
m_pListObjects->addItem( m_Objects[i]->name() );
m_pListObjects->setSelected( selected );
m_pListObjects->setHighlighted( selected );
}
| 26.709877
| 142
| 0.670326
|
SnipeDragon
|
1e68c428f94ce7b69d6403b09fc237903bb8e571
| 858
|
cpp
|
C++
|
StudentResult.cpp
|
codesAliecc/hacktoberfest2021
|
2f3e5e318ab5834131c6aab75185a1b67e748b79
|
[
"Unlicense"
] | null | null | null |
StudentResult.cpp
|
codesAliecc/hacktoberfest2021
|
2f3e5e318ab5834131c6aab75185a1b67e748b79
|
[
"Unlicense"
] | null | null | null |
StudentResult.cpp
|
codesAliecc/hacktoberfest2021
|
2f3e5e318ab5834131c6aab75185a1b67e748b79
|
[
"Unlicense"
] | null | null | null |
#include<iostream>
using namespace std;
class Student
{
protected :
float id,m1,m2,m3;
char name[50];
public :
void getData()
{
cout<<"Enter Student Id : ";
cin>>id;
cout<<"Enter Student Name : ";
cin.ignore();
cin.getline(name,50);
//cin>>name;
cout<<"Enter Maths Mark : ";
cin>>m1;
cout<<"Enter Physics Mark : ";
cin>>m2;
cout<<"Enter Chemistry Mark : ";
cin>>m3;
}
};
class print : public Student
{
float t;
public :
void setData()
{
cout<<endl<<"Id : "<<id<<endl;
cout<<"Name : "<<name<<endl;
cout<<"Maths : "<<m1<<endl;
cout<<"Physics : "<<m2<<endl;
cout<<"Chemistry : "<<m3<<endl;
t = (m1 + m2+ m3) / 3;
cout<<"Total : "<<m1+m2+m3<<endl;
cout<<"Result : "<<t;
}
};
main()
{
print p;
p.getData();
p.setData();
}
| 13.619048
| 36
| 0.508159
|
codesAliecc
|
1e739cc70564a80af79c11371f40a0924150c994
| 4,127
|
cpp
|
C++
|
Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionPreferenceHelper.cpp
|
wyyrepo/MITK
|
d0837f3d0d44f477b888ec498e9a2ed407e79f20
|
[
"BSD-3-Clause"
] | 1
|
2021-11-20T08:19:27.000Z
|
2021-11-20T08:19:27.000Z
|
Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionPreferenceHelper.cpp
|
wyyrepo/MITK
|
d0837f3d0d44f477b888ec498e9a2ed407e79f20
|
[
"BSD-3-Clause"
] | null | null | null |
Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionPreferenceHelper.cpp
|
wyyrepo/MITK
|
d0837f3d0d44f477b888ec498e9a2ed407e79f20
|
[
"BSD-3-Clause"
] | null | null | null |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkNodeSelectionPreferenceHelper.h"
#include <internal/QmitkNodeSelectionConstants.h>
#include <berryIPreferencesService.h>
#include <berryIPreferences.h>
#include <berryIPreferencesService.h>
#include <berryPlatform.h>
#include "mitkExceptionMacro.h"
void mitk::PutVisibleDataStorageInspectors(const VisibleDataStorageInspectorMapType &inspectors)
{
berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService();
berry::IPreferences::Pointer prefNode =
prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str());
berry::IPreferences::Pointer visNode =
prefNode->Node(mitk::NodeSelectionConstants::VISIBLE_INSPECTORS_NODE_ID.c_str());
visNode->RemoveNode();
prefNode->Flush();
// new empty preset node
visNode = prefNode->Node(mitk::NodeSelectionConstants::VISIBLE_INSPECTORS_NODE_ID.c_str());
// store map in new node
for (const auto &inspector : inspectors)
{
std::ostringstream sstr;
sstr << inspector.first;
berry::IPreferences::Pointer aNode = visNode->Node(QString::fromStdString(sstr.str()));
aNode->Put(mitk::NodeSelectionConstants::VISIBLE_INSPECTOR_ID.c_str(), inspector.second.c_str());
aNode->Flush();
}
visNode->Flush();
}
mitk::VisibleDataStorageInspectorMapType mitk::GetVisibleDataStorageInspectors()
{
berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService();
berry::IPreferences::Pointer prefNode =
prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str());
berry::IPreferences::Pointer visNode =
prefNode->Node(mitk::NodeSelectionConstants::VISIBLE_INSPECTORS_NODE_ID.c_str());
typedef QStringList NamesType;
NamesType names = visNode->ChildrenNames();
VisibleDataStorageInspectorMapType visMap;
if (!names.empty())
{
for (NamesType::const_iterator pos = names.begin(); pos != names.end(); ++pos)
{
berry::IPreferences::Pointer aNode = visNode->Node(*pos);
if (aNode.IsNull())
{
mitkThrow() << "Error in preference interface. Cannot find preset node under given name. Name: "
<< (*pos).toStdString();
}
std::istringstream isstr(pos->toStdString());
unsigned int order = 0;
isstr >> order;
auto id = aNode->Get(mitk::NodeSelectionConstants::VISIBLE_INSPECTOR_ID.c_str(), "");
if (id.isEmpty())
{
mitkThrow() << "Error in preference interface. ID of visible inspector is not set. Inspector position: "
<< order;
}
visMap.insert(std::make_pair(order, id.toStdString()));
}
}
return visMap;
}
mitk::DataStorageInspectorIDType mitk::GetFavoriteDataStorageInspector()
{
berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService();
berry::IPreferences::Pointer prefNode =
prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str());
auto id = prefNode->Get(mitk::NodeSelectionConstants::FAVORITE_INSPECTOR_ID.c_str(), "");
mitk::DataStorageInspectorIDType result = id.toStdString();
return result;
}
void mitk::PutFavoriteDataStorageInspector(const DataStorageInspectorIDType &id)
{
berry::IPreferencesService *prefService = berry::Platform::GetPreferencesService();
berry::IPreferences::Pointer prefNode =
prefService->GetSystemPreferences()->Node(mitk::NodeSelectionConstants::ROOT_PREFERENCE_NODE_ID.c_str());
prefNode->Put(mitk::NodeSelectionConstants::FAVORITE_INSPECTOR_ID.c_str(), id.c_str());
prefNode->Flush();
}
| 33.282258
| 112
| 0.714078
|
wyyrepo
|
1e8103c29ba5679084051da068cd3736d6c2aab5
| 2,948
|
cpp
|
C++
|
number/test/sieve.stress.test.cpp
|
ankit6776/cplib-cpp
|
b9f8927a6c7301374c470856828aa1f5667d967b
|
[
"MIT"
] | 20
|
2021-06-21T00:18:54.000Z
|
2022-03-17T17:45:44.000Z
|
number/test/sieve.stress.test.cpp
|
ankit6776/cplib-cpp
|
b9f8927a6c7301374c470856828aa1f5667d967b
|
[
"MIT"
] | 56
|
2021-06-03T14:42:13.000Z
|
2022-03-26T14:15:30.000Z
|
number/test/sieve.stress.test.cpp
|
ankit6776/cplib-cpp
|
b9f8927a6c7301374c470856828aa1f5667d967b
|
[
"MIT"
] | 3
|
2019-12-11T06:45:45.000Z
|
2020-09-07T13:45:32.000Z
|
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A" // DUMMY
#include "../sieve.hpp"
#include "../modint_runtime.hpp"
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
struct Case {
int SIEVE_SIZE;
int MAX;
};
int euler_phi(int x) {
int ret = 0;
for (int d = 1; d <= x; d++) ret += (std::__gcd(d, x) == 1);
return ret;
}
void test_divisors(Case testcase) {
const Sieve sieve(testcase.SIEVE_SIZE);
for (int x = 1; x <= testcase.MAX; x++) {
auto divs = sieve.divisors(x);
std::vector<int> is_div(x + 1);
for (auto d : divs) is_div.at(d) = 1;
for (int y = 1; y <= x; y++) assert(is_div.at(y) == (x % y == 0));
}
cerr << "divisors(): passed" << endl;
}
void test_euler_of_divisors(Case testcase) {
const Sieve sieve(testcase.SIEVE_SIZE);
for (int x = 1; x <= testcase.MAX; x++) {
auto div2euler = sieve.euler_of_divisors(x);
for (auto de : div2euler) {
assert(euler_phi(de.first) == de.second);
assert(x % de.first == 0);
}
assert(div2euler.size() == sieve.divisors(x).size());
}
cerr << "euler_of_divisors(): passed" << endl;
}
void test_moebius_table(int HI) {
const Sieve sieve_hi(HI);
const auto answer = sieve_hi.GenerateMoebiusFunctionTable();
assert(int(answer.size()) == HI + 1);
for (int x = 1; x <= HI; x++) {
int ret = 1;
for (auto p : sieve_hi.primes) {
if (x % (p * p) == 0) ret = 0;
if (x % p == 0) ret *= -1;
}
assert(answer[x] == ret);
}
for (int x = 1; x <= HI - 1; x++) {
auto mu = Sieve(x).GenerateMoebiusFunctionTable();
assert(int(mu.size()) == x + 1);
for (int i = 0; i < x + 1; i++) assert(mu[i] == answer[i]);
}
cerr << "GenerateMoebiusFunctionTable(): passed" << endl;
}
void test_enumerate_kth_pows(int hi_sieve_size) {
for (int sieve_size = 1; sieve_size <= hi_sieve_size; sieve_size++) {
const Sieve sieve(sieve_size);
for (int nmax = 1; nmax <= sieve_size; nmax++) {
for (int p = 1; p <= 20; p++) {
using mint = ModIntRuntime;
mint::set_mod(p);
for (int k = 0; k < 10; k++) {
auto ret = sieve.enumerate_kth_pows<mint>(k, nmax);
assert(int(ret.size()) == nmax + 1);
for (int i = 0; i <= nmax; i++) assert(ret[i] == mint(i).pow(k));
}
}
}
}
cerr << "enumerate_kth_pows(): passed" << endl;
}
int main() {
std::vector<Case> cases{{31, 31 * 31}, {100, 1000}, {2, 4}};
for (auto testcase : cases) {
test_divisors(testcase);
test_euler_of_divisors(testcase);
}
test_moebius_table(1000);
test_enumerate_kth_pows(100);
puts("Hello World");
}
| 29.188119
| 93
| 0.536296
|
ankit6776
|
1e85316186abffe4885ac981844cf0a0423a2049
| 21,448
|
cpp
|
C++
|
src/serialloader.cpp
|
totalspectrum/PropLoader
|
23a037255f857dd45f3a2cb50ff68e83d8a7d483
|
[
"MIT"
] | null | null | null |
src/serialloader.cpp
|
totalspectrum/PropLoader
|
23a037255f857dd45f3a2cb50ff68e83d8a7d483
|
[
"MIT"
] | null | null | null |
src/serialloader.cpp
|
totalspectrum/PropLoader
|
23a037255f857dd45f3a2cb50ff68e83d8a7d483
|
[
"MIT"
] | 1
|
2018-12-01T04:43:09.000Z
|
2018-12-01T04:43:09.000Z
|
/* Propeller WiFi loader
Based on Jeff Martin's Pascal loader and Mike Westerfield's iOS loader.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include "serialprop2connection.h"
#include "loader.h"
#include "proploader.h"
#define MAX_BUFFER_SIZE 32768 /* The maximum buffer size. (BUG: git rid of this magic number) */
#define LENGTH_FIELD_SIZE 11 /* number of bytes in the length field */
// Propeller Download Stream Translator array. Index into this array using the "Binary Value" (usually 5 bits) to translate,
// the incoming bit size (again, usually 5), and the desired data element to retrieve (encoding = translation, bitCount = bit count
// actually translated.
// first index is the next 1-5 bits from the incoming bit stream
// second index is the number of bits in the first value
// the result is a structure containing the byte to output to encode some or all of the input bits
static struct {
uint8_t encoding; // encoded byte to output
uint8_t bitCount; // number of bits encoded by the output byte
} PDSTx[32][5] =
// *** 1-BIT *** *** 2-BIT *** *** 3-BIT *** *** 4-BIT *** *** 5-BIT ***
{ { /*%00000*/ {0xFE, 1}, /*%00000*/ {0xF2, 2}, /*%00000*/ {0x92, 3}, /*%00000*/ {0x92, 3}, /*%00000*/ {0x92, 3} },
{ /*%00001*/ {0xFF, 1}, /*%00001*/ {0xF9, 2}, /*%00001*/ {0xC9, 3}, /*%00001*/ {0xC9, 3}, /*%00001*/ {0xC9, 3} },
{ {0, 0}, /*%00010*/ {0xFA, 2}, /*%00010*/ {0xCA, 3}, /*%00010*/ {0xCA, 3}, /*%00010*/ {0xCA, 3} },
{ {0, 0}, /*%00011*/ {0xFD, 2}, /*%00011*/ {0xE5, 3}, /*%00011*/ {0x25, 4}, /*%00011*/ {0x25, 4} },
{ {0, 0}, {0, 0}, /*%00100*/ {0xD2, 3}, /*%00100*/ {0xD2, 3}, /*%00100*/ {0xD2, 3} },
{ {0, 0}, {0, 0}, /*%00101*/ {0xE9, 3}, /*%00101*/ {0x29, 4}, /*%00101*/ {0x29, 4} },
{ {0, 0}, {0, 0}, /*%00110*/ {0xEA, 3}, /*%00110*/ {0x2A, 4}, /*%00110*/ {0x2A, 4} },
{ {0, 0}, {0, 0}, /*%00111*/ {0xFA, 3}, /*%00111*/ {0x95, 4}, /*%00111*/ {0x95, 4} },
{ {0, 0}, {0, 0}, {0, 0}, /*%01000*/ {0x92, 3}, /*%01000*/ {0x92, 3} },
{ {0, 0}, {0, 0}, {0, 0}, /*%01001*/ {0x49, 4}, /*%01001*/ {0x49, 4} },
{ {0, 0}, {0, 0}, {0, 0}, /*%01010*/ {0x4A, 4}, /*%01010*/ {0x4A, 4} },
{ {0, 0}, {0, 0}, {0, 0}, /*%01011*/ {0xA5, 4}, /*%01011*/ {0xA5, 4} },
{ {0, 0}, {0, 0}, {0, 0}, /*%01100*/ {0x52, 4}, /*%01100*/ {0x52, 4} },
{ {0, 0}, {0, 0}, {0, 0}, /*%01101*/ {0xA9, 4}, /*%01101*/ {0xA9, 4} },
{ {0, 0}, {0, 0}, {0, 0}, /*%01110*/ {0xAA, 4}, /*%01110*/ {0xAA, 4} },
{ {0, 0}, {0, 0}, {0, 0}, /*%01111*/ {0xD5, 4}, /*%01111*/ {0xD5, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%10000*/ {0x92, 3} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%10001*/ {0xC9, 3} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%10010*/ {0xCA, 3} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%10011*/ {0x25, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%10100*/ {0xD2, 3} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%10101*/ {0x29, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%10110*/ {0x2A, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%10111*/ {0x95, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%11000*/ {0x92, 3} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%11001*/ {0x49, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%11010*/ {0x4A, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%11011*/ {0xA5, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%11100*/ {0x52, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%11101*/ {0xA9, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%11110*/ {0xAA, 4} },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, /*%11111*/ {0x55, 5} }
};
// After reset, the Propeller's exact clock rate is not known by either the host or the Propeller itself, so communication
// with the Propeller takes place based on a host-transmitted timing template that the Propeller uses to read the stream
// and generate the responses. The host first transmits the 2-bit timing template, then transmits a 250-bit Tx handshake,
// followed by 250 timing templates (one for each Rx handshake bit expected) which the Propeller uses to properly transmit
// the Rx handshake sequence. Finally, the host transmits another eight timing templates (one for each bit of the
// Propeller's version number expected) which the Propeller uses to properly transmit it's 8-bit hardware/firmware version
// number.
//
// After the Tx Handshake and Rx Handshake are properly exchanged, the host and Propeller are considered "connected," at
// which point the host can send a download command followed by image size and image data, or simply end the communication.
//
// PROPELLER HANDSHAKE SEQUENCE: The handshake (both Tx and Rx) are based on a Linear Feedback Shift Register (LFSR) tap
// sequence that repeats only after 255 iterations. The generating LFSR can be created in Pascal code as the following function
// (assuming FLFSR is pre-defined Byte variable that is set to ord('P') prior to the first call of IterateLFSR). This is
// the exact function that was used in previous versions of the Propeller Tool and Propellent software.
//
// function IterateLFSR: Byte;
// begin //Iterate LFSR, return previous bit 0
// Result := FLFSR and 0x01;
// FLFSR := FLFSR shl 1 and 0xFE or (FLFSR shr 7 xor FLFSR shr 5 xor FLFSR shr 4 xor FLFSR shr 1) and 1;
// end;
//
// The handshake bit stream consists of the lowest bit value of each 8-bit result of the LFSR described above. This LFSR
// has a domain of 255 combinations, but the host only transmits the first 250 bits of the pattern, afterwards, the Propeller
// generates and transmits the next 250-bits based on continuing with the same LFSR sequence. In this way, the host-
// transmitted (host-generated) stream ends 5 bits before the LFSR starts repeating the initial sequence, and the host-
// received (Propeller generated) stream that follows begins with those remaining 5 bits and ends with the leading 245 bits
// of the host-transmitted stream.
//
// For speed and compression reasons, this handshake stream has been encoded as tightly as possible into the pattern
// described below.
//
// The TxHandshake array consists of 209 bytes that are encoded to represent the required '1' and '0' timing template bits,
// 250 bits representing the lowest bit values of 250 iterations of the Propeller LFSR (seeded with ASCII 'P'), 250 more
// timing template bits to receive the Propeller's handshake response, and more to receive the version.
static uint8_t txHandshake[] = {
// First timing template ('1' and '0') plus first two bits of handshake ('0' and '1').
0x49,
// Remaining 248 bits of handshake...
0xAA,0x52,0xA5,0xAA,0x25,0xAA,0xD2,0xCA,0x52,0x25,0xD2,0xD2,0xD2,0xAA,0x49,0x92,
0xC9,0x2A,0xA5,0x25,0x4A,0x49,0x49,0x2A,0x25,0x49,0xA5,0x4A,0xAA,0x2A,0xA9,0xCA,
0xAA,0x55,0x52,0xAA,0xA9,0x29,0x92,0x92,0x29,0x25,0x2A,0xAA,0x92,0x92,0x55,0xCA,
0x4A,0xCA,0xCA,0x92,0xCA,0x92,0x95,0x55,0xA9,0x92,0x2A,0xD2,0x52,0x92,0x52,0xCA,
0xD2,0xCA,0x2A,0xFF,
// 250 timing templates ('1' and '0') to receive 250-bit handshake from Propeller.
// This is encoded as two pairs per byte; 125 bytes.
0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,
0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,
0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,
0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,
0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,
0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,
0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,
0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,0x29,
// 8 timing templates ('1' and '0') to receive 8-bit Propeller version; two pairs per byte; 4 bytes.
0x29,0x29,0x29,0x29};
// Shutdown command (0); 11 bytes.
static uint8_t shutdownCmd[] = {0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0xf2};
// Load RAM and Run command (1); 11 bytes.
static uint8_t loadRunCmd[] = {0xc9, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0xf2};
// Load RAM, Program EEPROM, and Shutdown command (2); 11 bytes.
static uint8_t programShutdownCmd[] = {0xca, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0xf2};
// Load RAM, Program EEPROM, and Run command (3); 11 bytes.
static uint8_t programRunCmd[] = {0x25, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0x92, 0xfe};
// The RxHandshake array consists of 125 bytes encoded to represent the expected 250-bit (125-byte @ 2 bits/byte) response
// of continuing-LFSR stream bits from the Propeller, prompted by the timing templates following the TxHandshake stream.
static uint8_t rxHandshake[] = {
0xEE,0xCE,0xCE,0xCF,0xEF,0xCF,0xEE,0xEF,0xCF,0xCF,0xEF,0xEF,0xCF,0xCE,0xEF,0xCF,
0xEE,0xEE,0xCE,0xEE,0xEF,0xCF,0xCE,0xEE,0xCE,0xCF,0xEE,0xEE,0xEF,0xCF,0xEE,0xCE,
0xEE,0xCE,0xEE,0xCF,0xEF,0xEE,0xEF,0xCE,0xEE,0xEE,0xCF,0xEE,0xCF,0xEE,0xEE,0xCF,
0xEF,0xCE,0xCF,0xEE,0xEF,0xEE,0xEE,0xEE,0xEE,0xEF,0xEE,0xCF,0xCF,0xEF,0xEE,0xCE,
0xEF,0xEF,0xEF,0xEF,0xCE,0xEF,0xEE,0xEF,0xCF,0xEF,0xCF,0xCF,0xCE,0xCE,0xCE,0xCF,
0xCF,0xEF,0xCE,0xEE,0xCF,0xEE,0xEF,0xCE,0xCE,0xCE,0xEF,0xEF,0xCF,0xCF,0xEE,0xEE,
0xEE,0xCE,0xCF,0xCE,0xCE,0xCF,0xCE,0xEE,0xEF,0xEE,0xEF,0xEF,0xCF,0xEF,0xCE,0xCE,
0xEF,0xCE,0xEE,0xCE,0xEF,0xCE,0xCE,0xEE,0xCF,0xCF,0xCE,0xCF,0xCF};
/* EncodeBytes
parameters:
inBytes is a pointer to a buffer of bytes to be encoded
inCount is the number of bytes in inBytes
outBytes is a pointer to a buffer to receive the encoded bytes
outSize is the size of the outBytes buffer
returns the number of bytes written to the outBytes buffer or -1 if the encoded data does not fit
*/
static int EncodeBytes(const uint8_t *inBytes, int inCount, uint8_t *outBytes, int outSize)
{
static uint8_t masks[] = { 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f };
int bitCount = inCount * 8;
int nextBit = 0;
int outCount = 0;
/* encode all bits in the input buffer */
while (nextBit < bitCount) {
int bits, bitsIn;
/* encode 5 bits or whatever remains in inBytes, whichever is smaller */
bitsIn = bitCount - nextBit;
if (bitsIn > 5)
bitsIn = 5;
/* extract the next 'bitsIn' bits from the input buffer */
bits = ((inBytes[nextBit / 8] >> (nextBit % 8)) | (inBytes[nextBit / 8 + 1] << (8 - (nextBit % 8)))) & masks[bitsIn];
/* make sure there is enough space in the output buffer */
if (outCount >= outSize)
return -1;
/* store the encoded value */
outBytes[outCount++] = PDSTx[bits][bitsIn - 1].encoding;
/* advance to the next group of bits */
nextBit += PDSTx[bits][bitsIn - 1].bitCount;
}
/* return the number of encoded bytes */
return outCount;
}
static uint8_t *GenerateIdentifyPacket(int *pLength)
{
uint8_t *packet;
int packetSize;
/* determine the size of the packet */
packetSize = sizeof(txHandshake) + sizeof(shutdownCmd);
/* allocate space for the full packet */
if (!(packet = (uint8_t *)malloc(packetSize)))
return NULL;
/* copy the handshake image and the command to the packet */
memcpy(packet, txHandshake, sizeof(txHandshake));
memcpy(packet + sizeof(txHandshake), shutdownCmd, sizeof(shutdownCmd));
/* return the packet and its length */
*pLength = packetSize;
return packet;
}
static uint8_t *GenerateLoaderPacket(const uint8_t *image, int imageSize, int *pLength, LoadType loadType)
{
int imageSizeInLongs = (imageSize + 3) / 4;
uint8_t encodedImage[MAX_BUFFER_SIZE * 8]; // worst case assuming one byte per bit encoding
int encodedImageSize, packetSize, cmdLen, tmp, i;
uint8_t *packet, *cmd, *p;
/* encode the image */
encodedImageSize = EncodeBytes(image, imageSize, encodedImage, sizeof(encodedImage));
if (encodedImageSize < 0)
return NULL;
/* select command */
switch (loadType) {
case ltShutdown:
cmd = shutdownCmd;
cmdLen = sizeof(shutdownCmd);
break;
case ltDownloadAndRun:
cmd = loadRunCmd;
cmdLen = sizeof(loadRunCmd);
break;
case ltDownloadAndProgram:
cmd = programShutdownCmd;
cmdLen = sizeof(programShutdownCmd);
break;
case ltDownloadAndProgramAndRun:
cmd = programRunCmd;
cmdLen = sizeof(programRunCmd);
break;
default:
return NULL;
}
/* determine the size of the packet */
packetSize = sizeof(txHandshake) + cmdLen + LENGTH_FIELD_SIZE + encodedImageSize;
/* allocate space for the full packet */
if (!(packet = (uint8_t *)malloc(packetSize)))
return NULL;
/* copy the handshake image and the command to the packet */
memcpy(packet, txHandshake, sizeof(txHandshake));
/* copy the command to the packet */
memcpy(packet + sizeof(txHandshake), cmd, cmdLen);
/* build the packet from the handshake data, the image length and the encoded image */
p = packet + sizeof(txHandshake) + cmdLen;
tmp = imageSizeInLongs;
for (i = 0; i < LENGTH_FIELD_SIZE; ++i) {
*p++ = 0x92 | (i == 10 ? 0x60 : 0x00) | (tmp & 1) | ((tmp & 2) << 2) | ((tmp & 4) << 4);
tmp >>= 3;
}
memcpy(p, encodedImage, encodedImageSize);
/* return the packet and its length */
*pLength = packetSize;
return packet;
}
int SerialPropConnection::identify(int *pVersion)
{
uint8_t packet2[MAX_BUFFER_SIZE]; // must be at least as big as maxDataSize()
int version, cnt, i;
uint8_t *packet;
int packetSize;
/* generate the identify packet */
if (!(packet = GenerateIdentifyPacket(&packetSize))) {
message("Failed to generate identify packet");
goto fail;
}
/* reset the Propeller */
generateResetSignal();
/* send the identify packet */
sendData(packet, packetSize);
/* send the verification packet (all timing templates) */
memset(packet2, 0xF9, maxDataSize());
sendData(packet2, maxDataSize());
/* receive the handshake response and the hardware version */
cnt = receiveDataExactTimeout(packet2, sizeof(rxHandshake) + 4, 2000);
if (cnt < 0)
goto fail;
/* verify the handshake response */
if (cnt != sizeof(rxHandshake) + 4 || memcmp(packet2, rxHandshake, sizeof(rxHandshake)) != 0) {
message("Handshake failed");
goto fail;
}
/* verify the hardware version */
version = 0;
for (i = sizeof(rxHandshake); i < cnt; ++i)
version = ((version >> 2) & 0x3F) | ((packet2[i] & 0x01) << 6) | ((packet2[i] & 0x20) << 2);
/* return successfully */
*pVersion = version;
return 0;
/* return failure */
fail:
disconnect();
return -1;
}
/* returns:
0 for success
-1 for fatal errors
-2 for errors where a lower baud rate might help
*/
int SerialPropConnection::loadImage(const uint8_t *image, int imageSize, uint8_t *response, int responseSize)
{
if (loadImage(image, imageSize, ltDownloadAndRun) != 0)
return -1;
return receiveDataExactTimeout(response, responseSize, 1000) == responseSize ? 0 : -2;
}
#define ACK_POLLING_INTERVAL 10
#define RAM_PROGRAMMING_RETRIES (10000 / ACK_POLLING_INTERVAL)
#define EEPROM_PROGRAMMING_RETRIES (5000 / ACK_POLLING_INTERVAL)
#define EEPROM_VERIFY_RETRIES (2000 / ACK_POLLING_INTERVAL)
int SerialPropConnection::loadImage(const uint8_t *image, int imageSize, LoadType loadType, int info)
{
uint8_t packet2[MAX_BUFFER_SIZE]; // must be at least as big as maxDataSize()
int packetSize, version, retries, cnt, i;
int loaderBaudRate;
uint8_t *packet;
if (!GetNumericConfigField(config(), "loader-baud-rate", &loaderBaudRate))
loaderBaudRate = DEF_LOADER_BAUDRATE;
/* use the loader baud rate */
if (setBaudRate(loaderBaudRate) != 0) {
nerror(ERROR_FAILED_TO_SET_BAUD_RATE);
return -1;
}
/* generate a loader packet */
if (!(packet = GenerateLoaderPacket(image, imageSize, &packetSize, loadType))) {
nerror(ERROR_INTERNAL_CODE_ERROR);
return -1;
}
/* reset the Propeller */
generateResetSignal();
/* send the packet including the image */
if (info)
nmessage(INFO_DOWNLOADING, portName());
sendData(packet, packetSize);
if (info)
nmessage(INFO_BYTES_SENT, (long)imageSize);
free(packet);
/* clock out the handshake response */
memset(packet2, 0xF9, sizeof(rxHandshake) + 4);
sendData(packet2, sizeof(rxHandshake) + 4);
/* receive the handshake response and the hardware version */
cnt = receiveDataExactTimeout(packet2, sizeof(rxHandshake) + 4, 2000);
/* verify the handshake response */
if (cnt != sizeof(rxHandshake) + 4 || memcmp(packet2, rxHandshake, sizeof(rxHandshake)) != 0) {
nmessage(ERROR_PROPELLER_NOT_FOUND, portName());
return -1;
}
/* verify the hardware version */
version = 0;
for (i = sizeof(rxHandshake); i < cnt; ++i)
version = ((version >> 2) & 0x3F) | ((packet2[i] & 0x01) << 6) | ((packet2[i] & 0x20) << 2);
if (version != 1) {
nmessage(ERROR_WRONG_PROPELLER_VERSION, version);
return -1;
}
if (info)
nmessage(INFO_VERIFYING_RAM);
/* receive the RAM verify response */
packet2[0] = 0xF9;
retries = RAM_PROGRAMMING_RETRIES;
do {
sendData(packet2, 1);
cnt = receiveDataExactTimeout(packet2, 1, 10);
} while (cnt <= 0 && --retries > 0);
/* check for timeout */
if (cnt <= 0) {
nmessage(ERROR_COMMUNICATION_LOST);
return -1;
}
/* verify the checksum response */
if (packet2[0] != 0xFE) {
//message("RAM checksum failed: expected 0xFE, got %02x", packet2[0]);
nmessage(ERROR_RAM_CHECKSUM_FAILED);
return -1;
}
/* handle EEPROM programming */
if (loadType == ltDownloadAndProgram || loadType == ltDownloadAndProgramAndRun) {
if (info)
nmessage(INFO_PROGRAMMING_EEPROM);
/* receive the EEPROM programming complete response */
packet2[0] = 0xF9;
retries = EEPROM_PROGRAMMING_RETRIES;
do {
sendData(packet2, 1);
cnt = receiveDataExactTimeout(packet2, 1, 10);
} while (cnt <= 0 && --retries > 0);
/* check for timeout */
if (cnt <= 0) {
nmessage(ERROR_COMMUNICATION_LOST);
return -1;
}
/* verify the checksum response */
if (packet2[0] != 0xFE) {
//message("EEPROM checksum failed: expected 0xFE, got %02x", packet2[0]);
nmessage(ERROR_EEPROM_CHECKSUM_FAILED);
return -1;
}
if (info)
nmessage(INFO_VERIFYING_EEPROM);
/* receive the EEPROM verify response */
packet2[0] = 0xF9;
retries = EEPROM_VERIFY_RETRIES;
do {
sendData(packet2, 1);
cnt = receiveDataExactTimeout(packet2, 1, 10);
} while (cnt <= 0 && --retries > 0);
/* check for timeout */
if (cnt <= 0) {
message("Timeout waiting for checksum");
nmessage(ERROR_COMMUNICATION_LOST);
return -1;
}
/* verify the checksum response */
if (packet2[0] != 0xFE) {
//message("EEPROM verify failed: expected 0xFE, got %02x", packet2[0]);
nmessage(ERROR_EEPROM_VERIFY_FAILED);
return -1;
}
}
/* return successfully */
return 0;
}
| 45.440678
| 131
| 0.57721
|
totalspectrum
|
1e86973f99cc3cc511e4ce33d08b3fd47e6191a5
| 1,857
|
cc
|
C++
|
compiler/emit/cast.cc
|
asoffer/icarus
|
5c9af79d1a39e14d95da1adacbdd7392908eedc5
|
[
"Apache-2.0"
] | null | null | null |
compiler/emit/cast.cc
|
asoffer/icarus
|
5c9af79d1a39e14d95da1adacbdd7392908eedc5
|
[
"Apache-2.0"
] | null | null | null |
compiler/emit/cast.cc
|
asoffer/icarus
|
5c9af79d1a39e14d95da1adacbdd7392908eedc5
|
[
"Apache-2.0"
] | null | null | null |
#include "ast/ast.h"
#include "compiler/compiler.h"
#include "compiler/emit/compiler_common.h"
#include "compiler/emit/copy_move_assignment.h"
#include "compiler/emit/initialize.h"
#include "ir/value/char.h"
namespace compiler {
void Compiler::EmitCopyInit(
ast::Cast const *node,
absl::Span<type::Typed<ir::RegOr<ir::addr_t>> const> to) {
ASSERT(to.size() == 1u);
auto t = context().qual_types(node)[0].type();
ir::PartialResultBuffer buffer;
EmitToBuffer(node, buffer);
CopyInitializationEmitter emitter(*this);
emitter(to[0], buffer);
}
void Compiler::EmitMoveInit(
ast::Cast const *node,
absl::Span<type::Typed<ir::RegOr<ir::addr_t>> const> to) {
ASSERT(to.size() == 1u);
auto t = context().qual_types(node)[0].type();
ir::PartialResultBuffer buffer;
EmitToBuffer(node, buffer);
MoveInitializationEmitter emitter(*this);
emitter(to[0], buffer);
}
void Compiler::EmitToBuffer(ast::Cast const *node,
ir::PartialResultBuffer &out) {
type::Type to_type = context().qual_types(node)[0].type();
EmitCast(*this, context().typed(node->expr()), to_type, out);
}
void Compiler::EmitMoveAssign(
ast::Cast const *node,
absl::Span<type::Typed<ir::RegOr<ir::addr_t>> const> to) {
ASSERT(to.size() == 1u);
auto t = context().qual_types(node)[0].type();
ir::PartialResultBuffer buffer;
EmitToBuffer(node, buffer);
MoveAssignmentEmitter emitter(*this);
emitter(to[0], type::Typed(buffer[0], t));
}
void Compiler::EmitCopyAssign(
ast::Cast const *node,
absl::Span<type::Typed<ir::RegOr<ir::addr_t>> const> to) {
ASSERT(to.size() == 1u);
auto t = context().qual_types(node)[0].type();
ir::PartialResultBuffer buffer;
EmitToBuffer(node, buffer);
CopyAssignmentEmitter emitter(*this);
emitter(to[0], type::Typed(buffer[0], t));
}
} // namespace compiler
| 30.442623
| 63
| 0.679052
|
asoffer
|
1e8b6488500802ad52922060845e8b86c8165431
| 1,761
|
cpp
|
C++
|
ImgReconstruction/Core/Structures/CImagePatch.cpp
|
SanCHEESE/ImgBlurRemoval
|
0d92eee97ed26a503ead9f4802025a2d73498fdd
|
[
"MIT"
] | 1
|
2016-01-06T16:03:52.000Z
|
2016-01-06T16:03:52.000Z
|
ImgReconstruction/Core/Structures/CImagePatch.cpp
|
SanCHEESE/ImgReconstruction
|
0d92eee97ed26a503ead9f4802025a2d73498fdd
|
[
"MIT"
] | null | null | null |
ImgReconstruction/Core/Structures/CImagePatch.cpp
|
SanCHEESE/ImgReconstruction
|
0d92eee97ed26a503ead9f4802025a2d73498fdd
|
[
"MIT"
] | null | null | null |
//
// CImagePatch.cpp
// ImgReconstruction
//
// Created by Alexander Bochkarev on 24.10.15.
// Copyright © 2015 Alexander Bochkarev. All rights reserved.
//
#include "CImagePatch.h"
#pragma mark - Public
double CImagePatch::BlurValue(const IBlurMeasurer *const measurer)
{
if (_blurValue < 0) {
_blurValue = measurer->Measure(_grayImage);
}
return _blurValue;
}
double CImagePatch::StandartDeviation()
{
if (_standartDeviation < 0) {
_standartDeviation = CalculateStandartDeviation();
}
return _standartDeviation;
}
uint64 CImagePatch::PHash()
{
if (!_pHashComputed) {
_pHash = utils::PHash(_binImage);
_pHashComputed = true;
}
return _pHash;
}
uint64 CImagePatch::AvgHash()
{
if (!_avgHashComputed) {
_avgHash = utils::AvgHash(_binImage);
_avgHashComputed = true;
}
return _avgHash;
}
std::ostream& operator<<(std::ostream& os, const CImagePatch& patch)
{
os << "Patch:\n";
os << "\tFrame:\n\t\t" << patch.GetFrame() << std::endl;
os << "\tBlur value:\n\t\t" << patch.GetBlurValue() << std::endl;
os << "\tStandart deviation:\n\t\t" << patch.GetStandartDeviation() << std::endl;
os << "\tGrey image:\n" << patch.GrayImage() << std::endl;
os << "\tBin image:\n" << patch.BinImage() << std::endl;
std::bitset<sizeof(uint64) * 8> phash(patch.GetPHash());
os << "\tPHash:\n\t\t" << phash << std::endl;
std::bitset<sizeof(uint64) * 8> avgHash(patch.GetAvgHash());
os << "\tAvgHash:\n\t\t" << avgHash << std::endl;
return os;
}
#pragma mark - Private
void CImagePatch::Initialize()
{
_blurValue = -1;
_standartDeviation = -1;
_pHashComputed = false;
_avgHashComputed = false;
}
double CImagePatch::CalculateStandartDeviation() const
{
return utils::StandartDeviation(_grayImage);
}
| 21.740741
| 82
| 0.670642
|
SanCHEESE
|
1e9054977208d2bcdab09a20d83ca43e05b79c79
| 739
|
cpp
|
C++
|
2nd/108_convert_sorted_array_to_binary_search_tree.cpp
|
buptlxb/leetcode
|
b641419de040801c4f54618d7ee26edcf10ee53c
|
[
"BSD-3-Clause"
] | null | null | null |
2nd/108_convert_sorted_array_to_binary_search_tree.cpp
|
buptlxb/leetcode
|
b641419de040801c4f54618d7ee26edcf10ee53c
|
[
"BSD-3-Clause"
] | null | null | null |
2nd/108_convert_sorted_array_to_binary_search_tree.cpp
|
buptlxb/leetcode
|
b641419de040801c4f54618d7ee26edcf10ee53c
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
typedef vector<int>::iterator Iter;
TreeNode* sortedArrayToBST(vector<int>& nums) {
return sortedArrayToBST(nums.begin(), nums.end());
}
TreeNode *sortedArrayToBST(Iter left, Iter right) {
if (left >= right)
return NULL;
Iter mid = left + (right-left)/2;
TreeNode *root = new TreeNode(*mid);
root->left = sortedArrayToBST(left, mid);
root->right = sortedArrayToBST(mid+1, right);
return root;
}
};
int main(void)
{
return 0;
}
| 21.735294
| 58
| 0.604871
|
buptlxb
|
1e91bae48ef799116cb21b267e3d405e7f84f398
| 1,007
|
hh
|
C++
|
elements/ctx/ipout.hh
|
regufo/fastclick
|
d56d31c722266ea5d0cfd31435e81ca10dda5e69
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
elements/ctx/ipout.hh
|
regufo/fastclick
|
d56d31c722266ea5d0cfd31435e81ca10dda5e69
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
elements/ctx/ipout.hh
|
regufo/fastclick
|
d56d31c722266ea5d0cfd31435e81ca10dda5e69
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
#ifndef MIDDLEBOX_IPOUT_HH
#define MIDDLEBOX_IPOUT_HH
#include <click/element.hh>
#include <click/ipelement.hh>
#include "ctxelement.hh"
CLICK_DECLS
/*
=c
IPOut()
=s middlebox
exit point of an IP path in the stack of the middlebox
=d
This element is the exit point of an IP path in the stack of the middlebox by which all
IP packets must go after their IP content has been processed. Each path containing a IPOut element
must also contain an IPIn element
=a IPIn */
class IPOut : public CTXElement, public IPElement
{
public:
/** @brief Construct an IPOut element
*/
IPOut() CLICK_COLD;
const char *class_name() const { return "IPOut"; }
const char *port_count() const { return PORTS_1_1; }
const char *processing() const { return PROCESSING_A_AH; }
int configure(Vector<String> &, ErrorHandler *) override CLICK_COLD;
void push_batch(int, PacketBatch*) override;
protected:
bool _readonly;
bool _checksum;
};
CLICK_ENDDECLS
#endif
| 21.425532
| 98
| 0.713009
|
regufo
|
1e993b6b27929f5f5f1f68041b10073d488789cc
| 2,601
|
cc
|
C++
|
4/4.04-threading-misc-histogram/solutions/instruction-05/main.cc
|
reble/HOW-Series-Labs
|
9e487be19ea8f16c8534825cb4cf9a31d8f0e93c
|
[
"MIT"
] | 29
|
2017-01-16T17:23:40.000Z
|
2022-01-21T13:56:24.000Z
|
4/4.04-threading-misc-histogram/solutions/instruction-05/main.cc
|
reble/HOW-Series-Labs
|
9e487be19ea8f16c8534825cb4cf9a31d8f0e93c
|
[
"MIT"
] | null | null | null |
4/4.04-threading-misc-histogram/solutions/instruction-05/main.cc
|
reble/HOW-Series-Labs
|
9e487be19ea8f16c8534825cb4cf9a31d8f0e93c
|
[
"MIT"
] | 20
|
2017-01-13T01:12:02.000Z
|
2021-04-13T15:54:37.000Z
|
#include <cstdio>
#include <omp.h>
#include <cmath>
#include "rngutil.h"
void HistogramReference(const float* age, int* const group, const int n,
const float group_width){
// Plain (scalar, sequentual) algorithm for computing the reference histogram
for (long i = 0; i < n; i++){
const int j = (int) floorf( age[i] / group_width );
group[j]++;
}
}
void Histogram(const float* age, int* const group, const int n, const float group_width,
const int m);
int main(int argv, char* argc[]){
const size_t n=1L<<27L;
const float max_age=99.999f;
const float group_width=20.0f;
const size_t m = (size_t) floorf(max_age/group_width + 0.1f);
const int nTrials=10;
const int skipTrials=2;
float* age = (float*) _mm_malloc(sizeof(int)*n, 64);
int group[m];
int ref_group[m];
// Initializing array of ages
printf("Initialization..."); fflush(stdout);
RNGutil rng;
const int size = rng.Size();
for (int i = 0; i < n; i += size) {
rng.SetBlock(&age[i]);
age[i:size] *= age[i:size]*max_age;
}
// Computing the "correct" answer
ref_group[:]=0;
HistogramReference(age, ref_group, n, group_width);
printf(" done.\n"); fflush(stdout);
printf("\033[1m%5s %10s %10s\033[0m\n", "Trial", "Time, s", "Values/s");
double perf=0.0, dperf=0.0;
for (int t=1; t<=nTrials; t++){
group[:] = 0;
const double t0 = omp_get_wtime();
Histogram(age, group, n, group_width, m);
const double t1 = omp_get_wtime();
const double HztoPerf = double(n);
if (t > skipTrials) {
perf += HztoPerf/(t1-t0);
dperf += HztoPerf*HztoPerf/((t1-t0)*(t1-t0));
}
printf("%5d %10.3e %10.2e %s\n",
t, (t1-t0), HztoPerf/(t1-t0), (t<=skipTrials?"*":""));
fflush(stdout);
for (int i=0; i<m; i++) {
if (fabs((double)(ref_group[i]-group[i])) > 1e-4*fabs((double)(ref_group[i]
+group[i]))) {
printf("Result is incorrect!\n");
for (int i=0; i<m; i++) printf(" (%d vs %d)", group[i], ref_group[i]);
}
}
fflush(stdout);
}
perf/=(double)(nTrials-skipTrials);
dperf=sqrt(dperf/(double)(nTrials-skipTrials)-perf*perf);
printf("---------------------------------------------------------\n");
printf("\033[1m%s %4s \033[42m%10.2e +- %.2e values/s\033[0m\n",
"Average performance:", "", perf, dperf);
printf("---------------------------------------------------------\n");
printf("* - warm-up, not included in average\n\n");
_mm_free(age);
}
| 31.719512
| 88
| 0.549404
|
reble
|
1e9ea077dae0f241513b7317596ba996c6db61dc
| 6,323
|
hpp
|
C++
|
include/cglass/object.hpp
|
Betterton-Lab/C-GLASS
|
56f7b93cd7383e4487b4c6ba5a1d8c556d9937cc
|
[
"BSD-3-Clause"
] | 4
|
2020-05-23T18:56:31.000Z
|
2022-01-13T04:06:50.000Z
|
include/cglass/object.hpp
|
Betterton-Lab/C-GLASS
|
56f7b93cd7383e4487b4c6ba5a1d8c556d9937cc
|
[
"BSD-3-Clause"
] | 5
|
2020-06-30T17:32:03.000Z
|
2021-04-02T20:18:33.000Z
|
include/cglass/object.hpp
|
Betterton-Lab/C-GLASS
|
56f7b93cd7383e4487b4c6ba5a1d8c556d9937cc
|
[
"BSD-3-Clause"
] | 2
|
2020-11-11T19:57:11.000Z
|
2021-03-18T01:55:37.000Z
|
#ifndef _CGLASS_OBJECT_H_
#define _CGLASS_OBJECT_H_
#include "auxiliary.hpp"
#include "interaction.hpp"
#include "rng.hpp"
#include <mutex>
class Object {
private:
int comp_id_;
static int _next_oid_;
static std::mutex _obj_mtx_;
void InitOID();
Object *comp_ptr_; // If part of a composite
protected:
int oid_;
static system_parameters *params_;
static SpaceBase *space_;
static int n_dim_;
static double delta_;
std::string name_;
species_id sid_;
obj_type type_ = obj_type::generic;
comp_type comp_type_ = comp_type::generic;
shape shape_ = shape::generic;
graph_struct g_;
RNG rng_;
draw_type draw_;
int n_contact_;
double position_[3];
double prev_position_[3];
double prev_orientation_[3];
double scaled_position_[3];
double orientation_[3];
double force_[3];
double torque_[3];
double dr_zero_[3];
double color_;
double diameter_;
double length_;
double p_energy_;
double dr_tot_;
double polar_order_;
double contact_number_;
bool interacting_;
bool is_mesh_;
bool is_comp_ = false;
bool has_overlap_;
bool fixed_ = false;
int n_anchored_;
bool interactor_update_;
std::vector<Object *> interactors_;
std::vector<object_interaction> ixs_;
void UpdateKMC();
public:
Object(unsigned long seed);
virtual ~Object() = default;
// kmcx parameter
int gid;
double length;
double radius;
double pos[3];
double direction[3];
// Static functions
static void SetParams(system_parameters *params);
static void SetSpace(SpaceBase *space);
static void SetNDim(int n_dim);
static void SetDelta(double delta);
static const double GetDelta();
static const int GetNextOID();
static void SetNextOID(const int next_oid);
// Trivial Set/Get functions
void SetSID(species_id sid);
void SetType(obj_type type);
void SetPosition(const double *const new_pos);
void SetScaledPosition(const double *const spos);
void SetOrientation(const double *const u);
void SetPrevPosition(const double *const ppos);
void SetPrevOrientation(const double *const pu);
void SetDiameter(double new_diameter);
void SetLength(double new_length);
virtual void AddForce(const double *const f);
void SubForce(const double *const f);
void SetForce(const double *const f);
virtual void AddTorque(const double *const t);
void SubTorque(const double *const t);
void SetTorque(const double *const t);
void AddPotential(const double p);
void AddPolarOrder(const double po);
void AddContactNumber(const double cn);
void SetInteractor(bool ix);
void IncrementNAnchored();
void DecrementNAnchored();
void ToggleIsMesh();
virtual void CalcPolarOrder();
virtual void ZeroPolarOrder();
species_id const GetSID();
obj_type const GetType();
comp_type const GetCompType();
shape const GetShape();
const std::string& GetName() const;
const int GetOID() const;
const int GetCompID() const;
const double *const GetPosition();
const double *const GetPrevPosition();
const double *const GetPrevOrientation();
const double *const GetScaledPosition();
const double *const GetOrientation();
virtual void GetAvgPosition(double *ap);
virtual void GetAvgOrientation(double *au);
virtual void SetAvgPosition();
const double GetDiameter();
const double GetLength();
const double *const GetForce();
const double *const GetTorque();
const double GetPotentialEnergy();
const double GetPolarOrder();
const double GetContactNumber();
const bool IsInteractor();
const bool IsMesh();
const bool IsFixed();
const int GetNAnchored();
const bool CheckInteractorUpdate();
void HasOverlap(bool overlap);
void SetOID(int oid);
void SetCompID(int cid);
void SetCompPtr(Object* comp);
// Virtual functions
virtual void Init(species_base_parameters *sparams) {}
virtual void InsertRandom(double buffer = -1);
virtual void InsertRandomOriented(const double *const u);
virtual void InsertAt(const double *const new_pos, const double *const u);
virtual void ZeroForce();
virtual void UpdatePeriodic();
virtual void UpdatePosition() {}
virtual void ResetPreviousPosition();
virtual void Draw(std::vector<graph_struct *> &graph_array);
virtual void SetColor(const double c, draw_type dtype);
virtual void ScalePosition();
virtual int GetCount();
virtual void GetInteractors(std::vector<Object *> &ix);
virtual const double *const GetInteractorPosition();
virtual const double *const GetInteractorPrevPosition();
virtual const double *const GetInteractorScaledPosition();
virtual const double *const GetInteractorOrientation();
virtual const double GetInteractorDiameter();
virtual const double GetInteractorLength();
virtual const double GetVolume();
virtual const double GetArea();
virtual void UpdateDrTot();
virtual const double GetDrTot();
virtual void ZeroDrTot();
virtual bool HasNeighbor(int other_id);
virtual void GiveInteraction(object_interaction ix);
virtual void ApplyInteractions();
virtual void FlagDuplicateInteractions();
virtual void GetInteractions(std::vector<object_interaction> &ixs);
virtual void CalcPCPosition(double s, double* pos);
virtual void ClearInteractions();
virtual void Cleanup();
// I/O functions
virtual void Report();
virtual void WritePosit(std::fstream &oposit);
virtual void ReadPosit(std::fstream &iposit);
virtual void WriteSpec(std::fstream &ospec);
virtual void ReadSpec(std::fstream &ispec);
virtual void ReadPositFromSpec(std::fstream &ispec);
virtual void WriteCheckpoint(std::fstream &ocheck);
virtual void WriteCheckpointHeader(std::fstream &ocheck);
virtual void ReadCheckpoint(std::fstream &icheck);
virtual void ReadCheckpointHeader(std::fstream &icheck);
virtual Object *GetCompPtr() { return comp_ptr_; }
// Convert binary data to text. Static to avoid needing to istantiate
// species members.
static void ConvertPosit(std::fstream &iposit, std::fstream &otext);
static void ConvertSpec(std::fstream &ispec, std::fstream &otext);
static void WritePositTextHeader(std::fstream &otext);
static void WriteSpecTextHeader(std::fstream &otext);
};
// void MinimumDistance(Object* o1, Object* o2, Interaction *ix, SpaceBase
// *space); void BoundaryConditions(Object * o1, SpaceBase *space);
#endif // _CGLASS_OBJECT_H_
| 32.761658
| 76
| 0.748853
|
Betterton-Lab
|
1ea1c3553cd2970df72c64157aa028f9ea0ed04e
| 1,672
|
cpp
|
C++
|
typekits/rtt_ros2_primitives_typekit/src/typekit/ros2_wstring_type.cpp
|
gborghesan/rtt_ros2_integration
|
6c03adc69e1bac3c8ad07d19e1814054f30f6936
|
[
"Apache-2.0"
] | 14
|
2020-06-12T14:48:40.000Z
|
2022-03-22T08:57:41.000Z
|
typekits/rtt_ros2_primitives_typekit/src/typekit/ros2_wstring_type.cpp
|
gborghesan/rtt_ros2_integration
|
6c03adc69e1bac3c8ad07d19e1814054f30f6936
|
[
"Apache-2.0"
] | 15
|
2020-06-12T15:57:09.000Z
|
2021-09-08T18:26:19.000Z
|
typekits/rtt_ros2_primitives_typekit/src/typekit/ros2_wstring_type.cpp
|
gborghesan/rtt_ros2_integration
|
6c03adc69e1bac3c8ad07d19e1814054f30f6936
|
[
"Apache-2.0"
] | 3
|
2020-12-02T09:11:23.000Z
|
2021-11-29T11:06:27.000Z
|
// Copyright 2020 Intermodalics BVBA
//
// 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 <vector>
#include "rtt/typekit/StdStringTypeInfo.hpp"
#include "rtt/types/PrimitiveSequenceTypeInfo.hpp"
#include "rtt/types/CArrayTypeInfo.hpp"
#include "rtt_ros2_primitives_typekit/Types.hpp"
// wstring
template class RTT::internal::DataSource<std::u16string>;
template class RTT::internal::AssignableDataSource<std::u16string>;
template class RTT::internal::AssignCommand<std::u16string>;
template class RTT::internal::ValueDataSource<std::u16string>;
template class RTT::internal::ConstantDataSource<std::u16string>;
template class RTT::internal::ReferenceDataSource<std::u16string>;
template class RTT::OutputPort<std::u16string>;
template class RTT::InputPort<std::u16string>;
template class RTT::Property<std::u16string>;
template class RTT::Attribute<std::u16string>;
template class RTT::Constant<std::u16string>;
template class RTT::types::StdBasicStringTypeInfo<std::u16string::value_type>;
template class RTT::types::PrimitiveSequenceTypeInfo<std::vector<std::u16string>>;
template class RTT::types::CArrayTypeInfo<RTT::types::carray<std::u16string>>;
| 42.871795
| 82
| 0.782297
|
gborghesan
|
1eb4122d810eb2f11aadd5686917f35715ea49ee
| 443
|
hpp
|
C++
|
etcd/v3/AsyncRangeResponse.hpp
|
siyuan0322/etcd-cpp-apiv3
|
1575c5b43a64f85f77897e9b5aad24e6523ea453
|
[
"BSD-3-Clause"
] | 139
|
2016-09-20T00:28:04.000Z
|
2020-09-27T15:05:11.000Z
|
etcd/v3/AsyncRangeResponse.hpp
|
siyuan0322/etcd-cpp-apiv3
|
1575c5b43a64f85f77897e9b5aad24e6523ea453
|
[
"BSD-3-Clause"
] | 85
|
2020-09-29T16:33:00.000Z
|
2022-03-30T01:23:23.000Z
|
etcd/v3/AsyncRangeResponse.hpp
|
siyuan0322/etcd-cpp-apiv3
|
1575c5b43a64f85f77897e9b5aad24e6523ea453
|
[
"BSD-3-Clause"
] | 63
|
2016-12-06T11:42:29.000Z
|
2020-09-24T06:15:49.000Z
|
#ifndef __ASYNC_RANGERESPONSE_HPP__
#define __ASYNC_RANGERESPONSE_HPP__
#include <grpc++/grpc++.h>
#include "proto/rpc.grpc.pb.h"
#include "etcd/v3/V3Response.hpp"
using grpc::ClientAsyncResponseReader;
using etcdserverpb::RangeResponse;
namespace etcdv3
{
class AsyncRangeResponse : public etcdv3::V3Response
{
public:
AsyncRangeResponse(){};
void ParseResponse(RangeResponse& resp, bool prefix=false);
};
}
#endif
| 19.26087
| 65
| 0.749436
|
siyuan0322
|
1ebd164712e7bf28bfc697ba4f4c7d352c39b043
| 407
|
cpp
|
C++
|
Wonderland/Wonderland/Editor/Support/Container/Array/BinaryArray.cpp
|
RodrigoHolztrattner/Wonderland
|
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
|
[
"MIT"
] | 3
|
2018-04-09T13:01:07.000Z
|
2021-03-18T12:28:48.000Z
|
Wonderland/Wonderland/Editor/Support/Container/Array/BinaryArray.cpp
|
RodrigoHolztrattner/Wonderland
|
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
|
[
"MIT"
] | null | null | null |
Wonderland/Wonderland/Editor/Support/Container/Array/BinaryArray.cpp
|
RodrigoHolztrattner/Wonderland
|
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
|
[
"MIT"
] | 1
|
2021-03-18T12:28:50.000Z
|
2021-03-18T12:28:50.000Z
|
///////////////////////////////////////////////////////////////////////////////
// Filename: BinaryArray.cpp
///////////////////////////////////////////////////////////////////////////////
#include "BinaryArray.h"
/*
BinaryArray::BinaryArray()
{
}
BinaryArray::BinaryArray(const BinaryArray& other)
{
}
BinaryArray::~BinaryArray()
{
}
bool BinaryArray::Initialize()
{
bool result;
return true;
}
*/
| 15.074074
| 79
| 0.425061
|
RodrigoHolztrattner
|
362ff630213f881d7daeb0020ec649211c637eac
| 392
|
hpp
|
C++
|
src/Scenes/CutScenes/controlsGuide.hpp
|
PierrickLP/PopHead
|
0c2ddd6d737f556b3f74b91b937b023c8e8010f0
|
[
"MIT"
] | null | null | null |
src/Scenes/CutScenes/controlsGuide.hpp
|
PierrickLP/PopHead
|
0c2ddd6d737f556b3f74b91b937b023c8e8010f0
|
[
"MIT"
] | null | null | null |
src/Scenes/CutScenes/controlsGuide.hpp
|
PierrickLP/PopHead
|
0c2ddd6d737f556b3f74b91b937b023c8e8010f0
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Scenes/cutScene.hpp"
namespace ph {
class GUI;
class SceneManager;
class ContolsGuide : public CutScene
{
public:
ContolsGuide(GameObject& root, GUI&, SceneManager&);
void update(const sf::Time delta);
private:
void closeCutscene();
private:
sf::Clock mTimeSinceLastSkipPress;
GUI& mGui;
SceneManager& mSceneManager;
unsigned int mTimesPressedSkip;
};
}
| 14
| 53
| 0.752551
|
PierrickLP
|
3636d19a3b258599c7b1cfec0f9cfbe41cc6078d
| 2,105
|
cpp
|
C++
|
src/guide/brush.cpp
|
rzvdaniel/GUI-
|
1501b54a038f7e3f66d683f125fa53d3ab73672c
|
[
"MIT"
] | 2
|
2017-06-16T19:27:55.000Z
|
2020-04-05T02:18:07.000Z
|
src/guide/brush.cpp
|
rzvdaniel/GUI-
|
1501b54a038f7e3f66d683f125fa53d3ab73672c
|
[
"MIT"
] | null | null | null |
src/guide/brush.cpp
|
rzvdaniel/GUI-
|
1501b54a038f7e3f66d683f125fa53d3ab73672c
|
[
"MIT"
] | 2
|
2019-09-03T19:23:20.000Z
|
2020-08-29T21:46:17.000Z
|
#define N_IMPLEMENTS TBrush
//-------------------------------------------------------------------
// brush.cpp
// (C) 2002 R.Predescu
//-------------------------------------------------------------------
#include "guide/brush.h"
#include "guide/debug.h"
//-------------------------------------------------------------------
// TBrush()
// 06-July-2002 rzv created
//-------------------------------------------------------------------
TBrush::TBrush()
{
Color = clWhite;
Style = bsSolid;
Texture = NULL;
TextureU = 1.0f;
TextureV = 1.0f;
TextureOffsetU = 0.0f;
TextureOffsetV = 0.0f;
}
//-------------------------------------------------------------------
// ~TBrush()
// 06-July-2002 rzv created
//-------------------------------------------------------------------
TBrush::~TBrush()
{
}
//-------------------------------------------------------------------
// ~SetTextureUV()
// 23-Jan-2003 rzv created
//-------------------------------------------------------------------
void TBrush::SetTextureUV(float U, float V)
{
TextureU = U;
TextureV = V;
}
//-------------------------------------------------------------------
// GetTextureUV()
// 23-Jan-2003 rzv created
//-------------------------------------------------------------------
void TBrush::GetTextureUV(float &U, float &V)
{
U = TextureU;
V = TextureV;
}
//-------------------------------------------------------------------
// SetTextureOffsetUV()
// 28-Oct-2003 rzv created
//-------------------------------------------------------------------
void TBrush::SetTextureOffsetUV(float U, float V)
{
TextureOffsetU = U;
TextureOffsetV = V;
}
//-------------------------------------------------------------------
// GetTextureOffsetUV()
// 28-Oct-2003 rzv created
//-------------------------------------------------------------------
void TBrush::GetTextureOffsetUV(float &U, float &V)
{
U = TextureOffsetU;
V = TextureOffsetV;
}
//-------------------------------------------------------------------
// EOF
//-------------------------------------------------------------------
| 27.697368
| 69
| 0.300238
|
rzvdaniel
|
363ee7b238945488b8c3af4f6004b8933e4c13eb
| 2,249
|
hpp
|
C++
|
pdatastructures/stacks/TMLinkedListFatStackByRef.hpp
|
pramalhe/durabletx
|
9ae79090e5cb20068c995f27c558414f78abc256
|
[
"MIT"
] | 9
|
2021-03-15T01:54:48.000Z
|
2022-03-05T03:00:44.000Z
|
pdatastructures/stacks/TMLinkedListFatStackByRef.hpp
|
pramalhe/durabletx
|
9ae79090e5cb20068c995f27c558414f78abc256
|
[
"MIT"
] | null | null | null |
pdatastructures/stacks/TMLinkedListFatStackByRef.hpp
|
pramalhe/durabletx
|
9ae79090e5cb20068c995f27c558414f78abc256
|
[
"MIT"
] | null | null | null |
/*
* Copyright 2017-2020
* Andreia Correia <andreia.veiga@unine.ch>
* Pedro Ramalhete <pramalhe@gmail.com>
* Pascal Felber <pascal.felber@unine.ch>
*
* This work is published under the MIT license. See LICENSE.txt
*/
#ifndef _TM_LINKED_LIST_FAT_STACK_BY_REF_H_
#define _TM_LINKED_LIST_FAT_STACK_BY_REF_H_
#include <string>
/**
* <h1> A Linked List stack (memory unbounded) with fat nodes for usage with STMs and PTMs </h1>
*
*/
template<typename T, typename TM, template <typename> class TMTYPE>
class TMLinkedListFatStackByRef : public TM::tmbase {
static const uint64_t NUM_ITEMS = 16-2; // 16 is faster than 32
private:
struct Node : public TM::tmbase {
TMTYPE<uint64_t> ih {1};
TMTYPE<T*> item[NUM_ITEMS];
TMTYPE<Node*> next {nullptr};
Node(T* userItem) {
item[0] = userItem;
}
};
TMTYPE<Node*> head {nullptr};
public:
TMLinkedListFatStackByRef() { }
~TMLinkedListFatStackByRef() {
TM::template updateTx([&] () {
while (pop() != nullptr); // Drain the stack
});
}
static std::string className() { return TM::className() + "-LinkedListFatStack"; }
// Always returns true
bool push(T* item) {
TM::template updateTx([&] () {
Node* lhead = head;
if (lhead == nullptr || lhead->ih == NUM_ITEMS) {
// Node is full or non-existant. Create a new node.
Node* newNode = TM::template tmNew<Node>(item);
newNode->next = lhead;
head = newNode;
} else {
lhead->item[lhead->ih] = item;
lhead->ih++;
}
});
return true;
}
T* pop() {
T* item = nullptr;
TM::template updateTx([&] () {
Node* lhead = head;
if (lhead == nullptr) return;
if (lhead->ih == 0) {
head = lhead->next;
TM::tmDelete(lhead);
}
lhead = head;
if (lhead == nullptr) return;
item = lhead->item[lhead->ih-1];
lhead->ih--;
});
return item;
}
};
#endif /* _TM_LINKED_LIST_FAT_STACK_BY_REF_H_ */
| 25.556818
| 96
| 0.538017
|
pramalhe
|
3642339adb15a3202c26163a12028b362eee29e5
| 1,041
|
cpp
|
C++
|
codeforces/A - Boredom/Wrong answer on test 5 (2).cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/A - Boredom/Wrong answer on test 5 (2).cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/A - Boredom/Wrong answer on test 5 (2).cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: Sep/26/2017 23:05
* solution_verdict: Wrong answer on test 5 language: GNU C++14
* run_time: 15 ms memory_used: 2400 KB
* problem: https://codeforces.com/contest/455/problem/A
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
long n,arr[100005],dp[100005][2];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n;
for(long i=1;i<=n;i++)
{
cin>>arr[i];
}
dp[1][1]=arr[1];
for(long i=2;i<=n;i++)
{
dp[i][1]=max(dp[i-1][0],dp[i-2][1])+arr[i];
dp[i][0]=max(dp[i-1][0],dp[i-1][1]);
}
cout<<max(dp[n][1],dp[n][0])<<endl;
return 0;
}
| 35.896552
| 111
| 0.365994
|
kzvd4729
|
364631312b328f1f2a996e08edd1097f95ac6942
| 2,034
|
hpp
|
C++
|
include/runner.hpp
|
pmqtt/purge
|
910d4b85e27235c66a6a3ca11059f27ce4d8f56a
|
[
"Apache-2.0"
] | null | null | null |
include/runner.hpp
|
pmqtt/purge
|
910d4b85e27235c66a6a3ca11059f27ce4d8f56a
|
[
"Apache-2.0"
] | null | null | null |
include/runner.hpp
|
pmqtt/purge
|
910d4b85e27235c66a6a3ca11059f27ce4d8f56a
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by Michael Burzan on 03.07.20.
//
#ifndef PURGE_RUNNER_HPP
#define PURGE_RUNNER_HPP
#include "test_registry.hpp"
#include "fuzzer.hpp"
#include <unistd.h>
#include <signal.h>
#include "log_book.hpp"
namespace purge{
class runner{
public:
runner(int argc,char **argv){
}
void run(){
for(auto & [key,test_item] : purge::test_registry::test_storage) {
//std::cout<<"Execute test:" <<key<<std::endl;
log_book_entry entry;
entry.test_name = key;
entry.line = std::to_string(test_item.first);
log_book::get_instance()->add_entry(entry);
test_item.second();
}
}
};
template<class CONTAINER>
void simple_fuzz_runner(const item_rule<typename CONTAINER::value_type> & rule,std::function<void(const CONTAINER &)> test_func){
purge::fuzzer_container<CONTAINER> fuzzer(rule);
for(int i =0; i < 1000; i++) {
auto value = fuzzer.next();
test_func(value);
}
}
template<class CONTAINER>
void fuzz_runner(const item_rule<typename CONTAINER::value_type> & rule,std::function<void(const CONTAINER &)> test_func){
purge::fuzzer_container<CONTAINER> fuzzer(rule);
for(int i = 0; i < 10000; i++) {
auto value = fuzzer.next();
int pid = fork();
if(pid == 0) {
fclose(stdout);
//fclose(stderr);
test_func(value);
exit(0);
}else{
int status;
waitpid(pid,&status,WUNTRACED | WCONTINUED);
if(WIFSIGNALED(status)){
std::cout<<"WTERMSIG:"<<WTERMSIG(status)<<std::endl;
if constexpr(std::is_same<decltype(value),std::string>::value)
std::cout<<" failed with value:'" << value << "'" << std::endl;
}
}
}
}
}
#endif //PURGE_RUNNER_HPP
| 31.78125
| 133
| 0.534907
|
pmqtt
|
36465069302a582c03b0c2a31274b34c71029d31
| 183
|
cpp
|
C++
|
f area.cpp
|
taareek/c-plus-plus
|
b9d04f710e9b2e65786618f8bbced4a56c149444
|
[
"Unlicense"
] | null | null | null |
f area.cpp
|
taareek/c-plus-plus
|
b9d04f710e9b2e65786618f8bbced4a56c149444
|
[
"Unlicense"
] | null | null | null |
f area.cpp
|
taareek/c-plus-plus
|
b9d04f710e9b2e65786618f8bbced4a56c149444
|
[
"Unlicense"
] | null | null | null |
#include<iostream>
using namespace std;
float areaOfcircle(float r){
float a=3.1416*r*r;
return a;
}
int main(){
float x,y;
cin>>x;
y=areaOfcircle(x);
cout<<"Area="<<y;
}
| 14.076923
| 29
| 0.63388
|
taareek
|
3646e5bd967401289d82609c5b89df583e24e4c9
| 5,122
|
hpp
|
C++
|
include/GuiCode/ui/components/text/TextDisplayer.hpp
|
KaixoCode/GuiCode
|
a332f74ac4007c0b381a05e45a27c61425827b83
|
[
"MIT"
] | 1
|
2022-03-31T20:25:44.000Z
|
2022-03-31T20:25:44.000Z
|
include/GuiCode/ui/components/text/TextDisplayer.hpp
|
KaixoCode/GuiCode
|
a332f74ac4007c0b381a05e45a27c61425827b83
|
[
"MIT"
] | null | null | null |
include/GuiCode/ui/components/text/TextDisplayer.hpp
|
KaixoCode/GuiCode
|
a332f74ac4007c0b381a05e45a27c61425827b83
|
[
"MIT"
] | null | null | null |
#pragma once
#include "GuiCode/pch.hpp"
#include "GuiCode/ui/components/panels/Panel.hpp"
#include "GuiCode/ui/components/text/TextContainer.hpp"
#include "GuiCode/ui/graphics/Graphics.hpp"
#include "GuiCode/ui/Clipboard.hpp"
// --------------------------------------------------------------------------
// ---------------------------- Text Displayer ------------------------------
// --------------------------------------------------------------------------
/**
* TextDisplayer displays text (wow surprising).
*/
class TextDisplayer : public Panel
{
public:
/**
* Wrap enum. Word wraps at words, and at character level if a word is longer than a line.
* Character wraps at any character. And None doesn't wrap at all.
*/
enum class Wrap
{
Word, Character, None
};
/**
* Constructor
*/
TextDisplayer();
void Update(const Vec4<int>& v) override;
void Render(CommandCollection& d) override;
/**
* Get the TextContainer.
* @return TextContainer
*/
auto Container() -> TextContainer& { return m_Container; }
/**
* Returns true if the mouse is dragging.
* @return true if dragging
*/
bool Dragging() { return m_Dragging; }
/**
* Converts an (x, y) position on this TextDisplayer to an index in
* the content of the TextContainer.
* @return index
*/
int PositionToIndex(const Vec2<int>& pos);
/**
* Converts an index in the TextContainer to an (x, y) position
* on this TextDisplayer.
* @return position
*/
Vec2<int> IndexToPosition(int index);
/**
* Set the horizontal alignment of the lines in this TextDisplayer.
* @param a alignment
*/
void AlignLines(Align a) { m_Align = a; }
/**
* Set the content of this container.
* @param c content
*/
void Content(const std::string& c)
{
if (c != m_Container.Content())
{
m_Container.Content(c);
RecalculateLines();
}
}
/**
* Set if this container is editable.
* @param a editable
*/
void Editable(bool e) { m_Container.Editable(e); }
/**
* Set the text color.
* @param c color
*/
void TextColor(Color c) { m_TextColor = c; }
/**
* Set the selection color.
* @param c color
*/
void SelectColor(Color c) { m_SelectColor = c; }
/**
* Set the text wrap mode.
* @param wrap wrap mode
*/
void TextWrap(Wrap wrap) { m_Wrap = wrap; }
/**
* Set the line height.
* @param h line height
*/
void LineHeight(int h) { m_LineHeight = h; };
/**
* Set the font and font size.
* @param f font
* @param size font size
*/
void Font(int f, float size) { m_Font = f, m_FontSize = size; };
/**
* Set the padding around the text.
* @param p padding
*/
void Padding(int p) { m_Padding = p; };
/**
* Get the current horizontal alignment of the text.
* @return text alignment
*/
auto AlignLines() const -> Align { return m_Align; }
/**
* Get the entire content of this container as a string.
* @return content
*/
auto Content() -> std::string& { return m_Container.Content(); }
/**
* Returns true when this text container is editable.
* @return true if editable
*/
bool Editable() const { return m_Container.Editable(); }
/**
* Get the text color.
* @return text color
*/
auto TextColor() const -> Color { return m_TextColor; }
/**
* Get the selection color.
* @return selection color
*/
auto SelectColor() const -> Color { return m_SelectColor; }
/**
* Get the current wrap mode.
* @return wrap
*/
auto TextWrap() const -> Wrap { return m_Wrap; }
/**
* Get the current line height.
* @return line height
*/
int LineHeight() const { return m_LineHeight; };
/**
* Get the current font.
* @return font
*/
int Font() const { return m_Font; };
/**
* Get the current font size.
* @return font size
*/
float FontSize() const { return m_FontSize; };
/**
* Get the current padding around the text.
* @return padding
*/
int Padding() const { return m_Padding; };
/**
* Set a placeholder string.
* @param p placeholder
*/
void Placeholder(const std::string& p) { m_Placeholder = p; }
/**
* Get the placeholder string.
* @return placeholder
*/
auto Placeholder() -> std::string& { return m_Placeholder; }
bool Focused() const override { return Panel::Focused(); }
void Focused(bool v) override { m_Timer = 60; Panel::Focused(v); }
void RecalculateLines();
protected:
TextContainer m_Container;
std::string m_Placeholder;
int m_LineHeight = 16,
m_FontSize = 14,
m_Padding = 2,
m_Font = Graphics::Fonts::Gidole14,
m_BiggestX = 0,
m_TypeX = 0,
m_Click = 0,
m_Timer = 60;
bool m_Shift = false,
m_Dragging = false;
Color m_TextColor{ 0, 0, 0, 255 },
m_SelectColor{ 128, 128, 255, 255 };
Align m_Align = Align::LEFT;
Vec2<int>
m_PressPos{ 0, 0 },
m_PrevSize{ 0, 0 };
Wrap m_Wrap = Wrap::Word;
std::vector<std::string_view> m_Lines;
std::vector<int> m_LineWidths;
void CalcLinesWordWrap();
void CalcLinesCharWrap();
void CalcLinesNoWrap();
void KeyTypeActions(Event::KeyTyped& e);
void CtrlTypeActions(Event::KeyTyped& e);
void ChangeIndexActions(Event::KeyPressed& e);
void UpdateTypeX();
};
| 21.165289
| 92
| 0.624756
|
KaixoCode
|
364997d340490443d43951bc6a6f595e9b534c9b
| 942
|
cpp
|
C++
|
cpp/segment_trees/combtree.cpp
|
petuhovskiy/Templates-CP
|
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
|
[
"MIT"
] | 8
|
2016-06-05T19:19:27.000Z
|
2019-05-14T10:33:37.000Z
|
cpp/segment_trees/combtree.cpp
|
petuhovskiy/Templates-CP
|
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
|
[
"MIT"
] | 2
|
2017-02-21T12:38:27.000Z
|
2018-01-28T20:05:00.000Z
|
cpp/segment_trees/combtree.cpp
|
petuhovskiy/Templates-CP
|
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
|
[
"MIT"
] | 6
|
2015-12-26T21:12:17.000Z
|
2022-03-26T21:40:17.000Z
|
class segtree{
struct e {
int a, b;
};
public:
int n; // array size
vector<e> t;
const e null_e = {-1000000000, -1000000000};
e combine(e l, e r) {
return (l.a > r.a) ? l : r;
}
void build(vector<e> &v) { // build the tree
for (int i = n; i < 2 * n; i++) t[i] = v[i - n];
for (int i = n - 1; i > 0; --i) t[i] = combine(t[i<<1], t[i<<1|1]);
}
void modify(int p, e value) { // set value at position p
for (t[p += n] = value; p >>= 1; ) t[p] = combine(t[p<<1], t[p<<1|1]);
}
e query(int l, int r) { // func on interval [l, r)
e ansl = null_e;
e ansr = null_e;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if (l&1) ansl = combine(ansl, t[l++]);
if (r&1) ansr = combine(t[--r], ansr);
}
return combine(ansl, ansr);
}
segtree(int n):n(n),t(){
t.resize(n << 1, null_e);
}
};
| 24.153846
| 78
| 0.430998
|
petuhovskiy
|
364c577baf700d8e7df5bd26b977225b7b10ee35
| 2,216
|
hpp
|
C++
|
Phasor/Common/tuple-iterate.hpp
|
ChadSki/Phasor
|
4a7f1d95cc8552714a550404b8e1b82347ceb3da
|
[
"MIT"
] | 7
|
2015-02-12T10:36:35.000Z
|
2021-11-23T18:22:14.000Z
|
Phasor/Common/tuple-iterate.hpp
|
th3w1zard1/Phasor
|
bd2594e8398fefcafe105eea4996a7f37516de68
|
[
"MIT"
] | 9
|
2015-01-09T02:15:02.000Z
|
2017-03-27T01:00:03.000Z
|
Phasor/Common/tuple-iterate.hpp
|
th3w1zard1/Phasor
|
bd2594e8398fefcafe105eea4996a7f37516de68
|
[
"MIT"
] | 8
|
2015-01-04T04:49:11.000Z
|
2021-01-15T10:04:07.000Z
|
#include <tuple>
namespace TupleHelpers {
template<std::size_t I, typename... Tp>
struct forward_comparator
{
static const bool value = (I < sizeof...(Tp));
static const std::size_t start = 0;
static const std::size_t next = I + 1;
};
template<std::size_t I, typename... Tp>
struct reverse_comparator
{
static const std::size_t start = sizeof...(Tp)-1;
static const std::size_t next = I - 1;
static const bool value = I >= 0 && I < sizeof...(Tp);
};
template<
template<std::size_t, typename...>class Comparator,
std::size_t I,
class F,
typename... Tp
>
inline typename std::enable_if<!Comparator<I, Tp...>::value>::type
citerate(const std::tuple<Tp...>&, F&)
{ }
template<
template<std::size_t, typename...>class Comparator,
std::size_t I,
class F,
typename... Tp
>
inline typename std::enable_if<Comparator<I, Tp...>::value>::type
citerate(const std::tuple<Tp...>& t, F& f)
{
typedef Comparator<I, Tp...> comparator;
f(std::get<I>(t));
citerate<Comparator, comparator::next, F, Tp...>(t, f);
}
// Helper for specifying start value
template<
template<std::size_t, typename...>class Comparator,
class F,
typename... Tp
>
inline void citerate(const std::tuple<Tp...>& t, F& f)
{
citerate<Comparator, Comparator<0, Tp...>::start, F, Tp...>(t, f);
}
// ---------------------------------------------------
// non-const versions
template<
template<std::size_t, typename...>class Comparator,
std::size_t I,
class F,
typename... Tp
>
inline typename std::enable_if<!Comparator<I, Tp...>::value>::type
iterate(std::tuple<Tp...>&, F&)
{ }
template<
template<std::size_t, typename...>class Comparator,
std::size_t I,
class F,
typename... Tp
>
inline typename std::enable_if<Comparator<I, Tp...>::value>::type
iterate(std::tuple<Tp...>& t, F& f)
{
typedef Comparator<I, Tp...> comparator;
f(std::get<I>(t));
iterate<Comparator, comparator::next, F, Tp...>(t, f);
}
// Helper for specifying start value
template<
template<std::size_t, typename...>class Comparator,
class F,
typename... Tp
>
inline void iterate(std::tuple<Tp...>& t, F& f)
{
iterate<Comparator, Comparator<0, Tp...>::start, F, Tp...>(t, f);
}
};
| 24.351648
| 68
| 0.625
|
ChadSki
|
364f15373315403bf861111cd69f5b2ab2044c36
| 159
|
cpp
|
C++
|
QTreplacer/TemplateWindow.cpp
|
alohaeee/QTreplacer
|
70eb2b67bfb36579020707eb053b82b7adaebcab
|
[
"MIT"
] | null | null | null |
QTreplacer/TemplateWindow.cpp
|
alohaeee/QTreplacer
|
70eb2b67bfb36579020707eb053b82b7adaebcab
|
[
"MIT"
] | null | null | null |
QTreplacer/TemplateWindow.cpp
|
alohaeee/QTreplacer
|
70eb2b67bfb36579020707eb053b82b7adaebcab
|
[
"MIT"
] | null | null | null |
#include "TemplateWindow.h"
TemplateWindow::TemplateWindow(QWidget *parent)
: QDialog(parent)
{
ui.setupUi(this);
}
TemplateWindow::~TemplateWindow()
{
}
| 12.230769
| 47
| 0.735849
|
alohaeee
|
3656c08e57539901d28206c55451cd28118110cf
| 8,359
|
cc
|
C++
|
Source/Plugins/SubsystemPlugins/BladeGraphics/source/Material.cc
|
OscarGame/blade
|
6987708cb011813eb38e5c262c7a83888635f002
|
[
"MIT"
] | 146
|
2018-12-03T08:08:17.000Z
|
2022-03-21T06:04:06.000Z
|
Source/Plugins/SubsystemPlugins/BladeGraphics/source/Material.cc
|
huangx916/blade
|
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
|
[
"MIT"
] | 1
|
2019-01-18T03:35:49.000Z
|
2019-01-18T03:36:08.000Z
|
Source/Plugins/SubsystemPlugins/BladeGraphics/source/Material.cc
|
huangx916/blade
|
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
|
[
"MIT"
] | 31
|
2018-12-03T10:32:43.000Z
|
2021-10-04T06:31:44.000Z
|
/********************************************************************
created: 2010/05/05
filename: Material.cc
author: Crazii
purpose:
*********************************************************************/
#include <BladePCH.h>
#include <Material.h>
#include <Technique.h>
#include <Pass.h>
namespace Blade
{
typedef Handle<Technique> TechHandle;
typedef Vector<TechHandle> TechniqueList;
typedef Set<Material::IListener*> MatListenerList;
typedef TStringMap<uint32> FlagMap;
namespace Impl
{
class MaterialDataImpl : public Allocatable
{
public:
TechniqueList mTechniqueList;
MatListenerList mListeners;
FlagMap mFlagMap;
};
}//namespace Impl
using namespace Impl;
const TString Material::MATERIAL_RESOURCE_TYPE = BTString("MaterialResource");
//////////////////////////////////////////////////////////////////////////
Material::Material(const TString& name)
:GraphicsResource(MATERIAL_RESOURCE_TYPE)
,mName(name)
,mActiveTech(NULL)
,mData( BLADE_NEW MaterialDataImpl() )
{
mData->mTechniqueList.reserve(4);
mNeedUpdate = true;
mHasCustomInstanceShaderConstants = false;
}
//////////////////////////////////////////////////////////////////////////
Material::~Material()
{
this->clearSubStates();
}
//////////////////////////////////////////////////////////////////////////
size_t Material::getTechniqueCount() const
{
return mData->mTechniqueList.size();
}
//////////////////////////////////////////////////////////////////////////
Technique* Material::getTechnique(index_t index) const
{
if( index < mData->mTechniqueList.size() )
{
TechniqueList::const_iterator i = mData->mTechniqueList.begin();
std::advance(i, (TechniqueList::difference_type)index);
return *i;
}
else
return NULL;
}
//////////////////////////////////////////////////////////////////////////
struct FnFindTechByName
{
FnFindTechByName(const TString& name) :mNameRef(name) {}
bool operator()(const Technique* pass) const
{
return pass->getName() == mNameRef;
}
const TString& mNameRef;
FnFindTechByName& operator=(FnFindTechByName&){return *this;}
};
Technique* Material::getTechnique(const TString& name) const
{
TechniqueList::const_iterator i = std::find_if(mData->mTechniqueList.begin(), mData->mTechniqueList.end(), FnFindTechByName(name) );
if( i != mData->mTechniqueList.end() )
return *i;
else
return NULL;
}
//////////////////////////////////////////////////////////////////////////
index_t Material::getTechniqueByProfile(const TString& name) const
{
TechniqueList::const_iterator highest = mData->mTechniqueList.end();
for( TechniqueList::const_iterator i = mData->mTechniqueList.begin(); i != mData->mTechniqueList.end(); ++i)
{
Technique* tech = *i;
if( tech->getProfile() <= name )
{
if( highest == mData->mTechniqueList.end() || (*highest)->getProfile() < (*i)->getProfile() )
highest = i;
}
}
return highest == mData->mTechniqueList.end() ? INVALID_INDEX : std::distance(mData->mTechniqueList.begin(), highest);
}
//////////////////////////////////////////////////////////////////////////
bool Material::addTechnique(Technique* tech)
{
if( tech == NULL )
return false;
if( tech->getParent() != NULL && tech->getParent() != this )
{
assert(false);
return false;
}
tech->setParent(this);
mData->mTechniqueList.push_back( TechHandle() );
TechHandle& hTech = *( mData->mTechniqueList.rbegin() );
hTech.bind( tech );
this->addSubState(tech);
if( mActiveTech == NULL )
mActiveTech = tech;
return true;
}
//////////////////////////////////////////////////////////////////////////
Technique* Material::setActiveTechnique(index_t index)
{
if( index < mData->mTechniqueList.size() )
{
Technique* tech = this->getTechnique(index);
if( mActiveTech != tech )
{
std::swap(tech, mActiveTech);
for(MatListenerList::const_iterator iter = mData->mListeners.begin(); iter != mData->mListeners.end(); ++iter)
(*iter)->onActivateTechnique(tech, mActiveTech);
}
return mActiveTech;
}
else
return NULL;
}
//////////////////////////////////////////////////////////////////////////
struct FnTechFind
{
FnTechFind(const TString& name) :mNameRef(name) {}
bool operator()(const Technique* tech) const
{
return tech->getName() == mNameRef;
}
const TString& mNameRef;
private:
FnTechFind& operator=(const FnTechFind&) {return *this;}
};
Technique* Material::setActiveTechnique(const TString& techName)
{
if(mData->mTechniqueList.size() == 0 )
{
mActiveTech = NULL;
return NULL;
}
TechniqueList::iterator i = std::find_if(mData->mTechniqueList.begin(), mData->mTechniqueList.end(), FnTechFind(techName) );
if( i == mData->mTechniqueList.end() )
return NULL;
else
{
if( mActiveTech != *i )
return this->setActiveTechnique( index_t(i- mData->mTechniqueList.begin()) );
return mActiveTech;
}
}
//////////////////////////////////////////////////////////////////////////
bool Material::setActiveTechnique(Technique* tech)
{
return tech != NULL && this->setActiveTechnique(tech->getName()) == tech;
}
//////////////////////////////////////////////////////////////////////////
Technique* Material::getActiveTechnique() const
{
return mActiveTech;
}
//////////////////////////////////////////////////////////////////////////
size_t Material::getMaxGroupCount() const
{
size_t group = 0;
for(TechniqueList::const_iterator i = mData->mTechniqueList.begin(); i != mData->mTechniqueList.end(); ++i)
group = std::max<size_t>(group, (*i)->getShaderGroupList().size());
return group;
}
//////////////////////////////////////////////////////////////////////////
bool Material::addListener(IListener* listener)
{
return listener != NULL && mData->mListeners.insert(listener).second;
}
//////////////////////////////////////////////////////////////////////////
bool Material::removeListener(IListener* listener)
{
return listener != NULL && mData->mListeners.erase(listener) == 1;
}
//////////////////////////////////////////////////////////////////////////
void Material::setTextureUniforms(const TStringParam& uniforms)
{
mTextureUniforms = uniforms;
mNeedUpdate = true;
}
//////////////////////////////////////////////////////////////////////////
void Material::setRenderProperty(const HRENDERPROPERTY& prop)
{
for (size_t i = 0; i < mData->mTechniqueList.size(); ++i)
{
Technique* tech = mData->mTechniqueList[i];
for (size_t j = 0; j < tech->getPassCount(); ++j)
{
Pass* pass = tech->getPass(j);
if (!pass->isUsingSharedRenderPropery())
//property shared among passes. TODO: clones
pass->getRenderProperty()->setProperty(prop);
}
}
}
//////////////////////////////////////////////////////////////////////////
void Material::removeAllTechniques()
{
mActiveTech = NULL;
mData->mTechniqueList.clear();
this->recalcLoadedCount();
}
//////////////////////////////////////////////////////////////////////////
void Material::onAllReady()
{
if( mNeedUpdate )
{
size_t customInstanceShaderConstants = 0;
//auto-create per-instance variable data storage
//and link sampler index to texture stages.
for(size_t i = 0; i < mData->mTechniqueList.size(); ++i)
{
const Technique* tech = mData->mTechniqueList[i];
assert(tech->isLoaded());
for(size_t j = 0; j < tech->getPassCount(); ++j)
{
const Pass* pass = tech->getPass(j);
assert(pass->isLoaded());
const SamplerState& samplers = pass->getSamplerState();
for(size_t k = 0; k < pass->getShaderOptionCount(); ++k)
{
const ShaderOption* option = pass->getShaderOption(k);
ShaderInstance* shaderInst = option->getShaderInstance();
assert(shaderInst->isLoaded());
shaderInst->linkSampler(mTextureUniforms, samplers);
customInstanceShaderConstants += shaderInst->getInstanceVaraibleCount();
}
}
}//for each technique
mNeedUpdate = false;
mHasCustomInstanceShaderConstants = customInstanceShaderConstants > 0;
}
}
//////////////////////////////////////////////////////////////////////////
void Material::onUnload()
{
ResourceStateGroup::onUnload();
mNeedUpdate = true;
}
}//namespace Blade
| 28.923875
| 134
| 0.552937
|
OscarGame
|
366b46b6fb069a24348123a8308e41dfba2380be
| 1,280
|
hpp
|
C++
|
src/interface/pid_controller/include/pid_controller/PidControllerNode.hpp
|
Nova-UTD/navigator
|
1db2c614f9c53fb012842b8653ae1bed58a7ffdf
|
[
"Apache-2.0"
] | 11
|
2021-11-26T14:06:51.000Z
|
2022-03-18T16:49:33.000Z
|
src/interface/pid_controller/include/pid_controller/PidControllerNode.hpp
|
Nova-UTD/navigator
|
1db2c614f9c53fb012842b8653ae1bed58a7ffdf
|
[
"Apache-2.0"
] | 222
|
2021-10-29T22:00:27.000Z
|
2022-03-29T20:56:34.000Z
|
src/interface/pid_controller/include/pid_controller/PidControllerNode.hpp
|
Voltron-UTD/vde
|
57e3c7e0363b82ccb875dbce34a8496c2ff1218a
|
[
"MIT"
] | 1
|
2021-08-13T08:30:25.000Z
|
2021-08-13T08:30:25.000Z
|
/*
* Package: pid_controller
* Filename: PidControllerNode.hpp
* Author: Joshua Williams
* Email: joshmackwilliams@protonmail.com
* Copyright: 2021, Voltron UTD
* License: MIT License
*/
#pragma once
#include <chrono>
#include <memory>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/float32.hpp"
#include "autoware_auto_msgs/msg/vehicle_control_command.hpp"
#include "pid_controller/PidController.hpp"
using namespace std::chrono_literals;
namespace Voltron {
namespace PidController {
class PidControllerNode : public rclcpp::Node {
public:
PidControllerNode();
virtual ~PidControllerNode();
private:
void update_target(const autoware_auto_msgs::msg::VehicleControlCommand::SharedPtr command);
void update_measurement(const std_msgs::msg::Float32::SharedPtr measurement);
void recalculate_output();
std::unique_ptr<PidController> controller;
typedef std::chrono::steady_clock clock_t;
clock_t clock;
clock_t::time_point last_update_time;
rclcpp::Publisher<std_msgs::msg::Float32>::SharedPtr steering_control_publisher;
rclcpp::Subscription<autoware_auto_msgs::msg::VehicleControlCommand>::
SharedPtr command_subscription;
rclcpp::Subscription<std_msgs::msg::Float32>::
SharedPtr measurement_subscription;
};
}
}
| 25.6
| 94
| 0.774219
|
Nova-UTD
|
366ef9fcc09a0efdda9ce10ffd956d70e25f4ab7
| 1,652
|
hpp
|
C++
|
bt-maxsat/staticset.hpp
|
Laakeri/phylogeny-aaai
|
4b97a6da97fc2be0e466c2197fbd4b51c036cb5f
|
[
"MIT"
] | 1
|
2019-06-28T23:24:57.000Z
|
2019-06-28T23:24:57.000Z
|
bt-maxsat/staticset.hpp
|
Laakeri/phylogeny-aaai
|
4b97a6da97fc2be0e466c2197fbd4b51c036cb5f
|
[
"MIT"
] | null | null | null |
bt-maxsat/staticset.hpp
|
Laakeri/phylogeny-aaai
|
4b97a6da97fc2be0e466c2197fbd4b51c036cb5f
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include "utils.hpp"
namespace triangulator {
// Interface
template<typename T>
class StaticSet {
public:
StaticSet();
explicit StaticSet(const std::vector<T>& values);
explicit StaticSet(const std::vector<std::pair<T, T> >& values);
void Init(const std::vector<T>& values);
void Init(const std::vector<std::pair<T, T> >& values);
int Rank(T value) const;
T Kth(int k) const;
int Size() const;
std::vector<T> Values() const;
private:
std::vector<T> values_;
};
// Implementation
template<typename T>
StaticSet<T>::StaticSet(const std::vector<T>& values) {
Init(values);
}
template<typename T>
StaticSet<T>::StaticSet() : StaticSet(std::vector<T>()) { }
template<typename T>
StaticSet<T>::StaticSet(const std::vector<std::pair<T, T> >& values) {
Init(values);
}
template<typename T>
void StaticSet<T>::Init(const std::vector<T>& values) {
values_ = values;
utils::SortAndDedup(values_);
}
template<typename T>
void StaticSet<T>::Init(const std::vector<std::pair<T, T> >& values) {
values_.clear();
for (const std::pair<T, T>& value : values) {
values_.push_back(value.first);
values_.push_back(value.second);
}
utils::SortAndDedup(values_);
}
template<typename T>
int StaticSet<T>::Rank(T value) const {
return std::lower_bound(values_.begin(), values_.end(), value) - values_.begin();
}
template<typename T>
T StaticSet<T>::Kth(int k) const {
return values_[k];
}
template<typename T>
int StaticSet<T>::Size() const {
return values_.size();
}
template<typename T>
std::vector<T> StaticSet<T>::Values() const {
return values_;
}
} // namespace triangulator
| 21.736842
| 83
| 0.685835
|
Laakeri
|
3671ea6fcfdda31058152b12367e6e59d7e292bf
| 2,459
|
cpp
|
C++
|
test/biquad_lp.cpp
|
ebai101/Q
|
92c3dc11714a56eb2c799f168875803109c95549
|
[
"MIT"
] | 2
|
2020-03-31T11:36:54.000Z
|
2021-05-27T04:30:00.000Z
|
test/biquad_lp.cpp
|
ebai101/Q
|
92c3dc11714a56eb2c799f168875803109c95549
|
[
"MIT"
] | null | null | null |
test/biquad_lp.cpp
|
ebai101/Q
|
92c3dc11714a56eb2c799f168875803109c95549
|
[
"MIT"
] | 1
|
2020-03-31T11:37:01.000Z
|
2020-03-31T11:37:01.000Z
|
/*=============================================================================
Copyright (c) 2014-2019 Joel de Guzman. All rights reserved.
Distributed under the MIT License [ https://opensource.org/licenses/MIT ]
=============================================================================*/
#include <q/support/literals.hpp>
#include <q/fx/biquad.hpp>
#include <q_io/audio_file.hpp>
#include <vector>
#include <string>
#include "notes.hpp"
namespace q = cycfi::q;
using namespace q::literals;
void process(std::string name, q::frequency base_freq)
{
////////////////////////////////////////////////////////////////////////////
// Read audio file
q::wav_reader src{"audio_files/" + name + ".wav"};
std::uint32_t const sps = src.sps();
std::vector<float> in(src.length());
src.read(in);
constexpr auto n_channels = 4;
std::vector<float> out(src.length() * n_channels);
// biquad lowpass filters
auto lp1 = q::lowpass{ base_freq * 2, sps, 0.51763809 };
auto lp2 = q::lowpass{ base_freq * 2, sps, 0.70710678 };
auto lp3 = q::lowpass{ base_freq * 2, sps, 1.9318517 };
for (auto i = 0; i != in.size(); ++i)
{
auto pos = i * n_channels;
auto ch1 = pos;
auto ch2 = pos+1;
auto ch3 = pos+2;
auto ch4 = pos+3;
auto s = in[i];
// Original signal
out[ch1] = s;
// Low pass filter 1
s = lp1(s);
out[ch2] = s * 3;
// Low pass filter 2
s = lp2(s);
out[ch3] = s * 3;
// Low pass filter 3
s = lp3(s);
out[ch4] = s * 4;
}
////////////////////////////////////////////////////////////////////////////
// Write to a wav file
q::wav_writer wav(
"results/biquad_lp_" + name + ".wav", n_channels, sps
);
wav.write(out);
}
int main()
{
using namespace notes;
process("-2a-F#", low_fs);
process("-1a-Low-B", low_b);
process("1a-Low-E", low_e);
process("1b-Low-E-12th", low_e);
process("2a-A", a);
process("2b-A-12th", a);
process("3a-D", d);
process("3b-D-12th", d);
process("4a-G", g);
process("4b-G-12th", g);
process("5a-B", b);
process("5b-B-12th", b);
process("6a-High-E", high_e);
process("6b-High-E-12th", high_e);
process("Tapping D", d);
process("Hammer-Pull High E", high_e);
process("Bend-Slide G", g);
process("GLines1", g);
process("GLines2", g);
process("GLines3", g);
process("GStaccato", g);
return 0;
}
| 25.091837
| 79
| 0.502237
|
ebai101
|
367bde2a543c36d892b932544bac13895b2f5243
| 369
|
hpp
|
C++
|
include/ng/engine/rendering/texture.hpp
|
mfurquim/csc486a
|
9af7ad3c6dac47bf3c73e890b4494d3b6263b05c
|
[
"MIT"
] | 1
|
2018-06-26T08:04:00.000Z
|
2018-06-26T08:04:00.000Z
|
include/ng/engine/rendering/texture.hpp
|
mfurquim/csc486a
|
9af7ad3c6dac47bf3c73e890b4494d3b6263b05c
|
[
"MIT"
] | null | null | null |
include/ng/engine/rendering/texture.hpp
|
mfurquim/csc486a
|
9af7ad3c6dac47bf3c73e890b4494d3b6263b05c
|
[
"MIT"
] | null | null | null |
#ifndef NG_TEXTURE_HPP
#define NG_TEXTURE_HPP
#include "ng/engine/rendering/textureformat.hpp"
#include <cstddef>
namespace ng
{
class ITexture
{
public:
virtual ~ITexture() = default;
virtual TextureFormat GetTextureFormat() const = 0;
virtual std::size_t WriteTextureData(void* buffer) const = 0;
};
} // end namespace ng
#endif // NG_TEXTURE_HPP
| 15.375
| 65
| 0.728997
|
mfurquim
|
367c880bc62714e14a74816c43e4fd394b70b36a
| 18,186
|
cpp
|
C++
|
blaise-lang-parser/src/blaise_parser_statement.cpp
|
sanelli/gasp
|
108700e8739534e9c152d7c8e2f1308917cf8611
|
[
"MIT"
] | null | null | null |
blaise-lang-parser/src/blaise_parser_statement.cpp
|
sanelli/gasp
|
108700e8739534e9c152d7c8e2f1308917cf8611
|
[
"MIT"
] | null | null | null |
blaise-lang-parser/src/blaise_parser_statement.cpp
|
sanelli/gasp
|
108700e8739534e9c152d7c8e2f1308917cf8611
|
[
"MIT"
] | null | null | null |
#include <memory>
#include <vector>
#include <string>
#include <sanelli/sanelli.hpp>
#include <gasp/blaise/parser/parser.hpp>
#include <gasp/blaise/ast.hpp>
using namespace std;
using namespace gasp::blaise;
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_statement(blaise_parser_context &context,
std::shared_ptr<ast::blaise_ast_statement_compund> parent)
{
std::shared_ptr<ast::blaise_ast_statement> statement = nullptr;
SANELLI_DEBUG("blaise-parser", "[ENTER] blaise_parser::parse_statement" << std::endl);
const auto token = context.peek_token();
const auto token_type = token.type();
auto match_ending_semicolon = true;
switch (token_type)
{
case blaise_token_type::IDENTIFIER:
{
const auto lookahead = context.peek_token(1);
const auto lookahead_type = lookahead.type();
switch (lookahead_type)
{
case blaise_token_type::LEFT_PARENTHESES:
statement = parse_subroutine_call_statement(context);
break;
case blaise_token_type::ASSIGNMENT: // Variable assignment
case blaise_token_type::LEFT_BRACKET: // Array assignement
statement = parse_assignamet_statement(context);
break;
default:
throw_parse_error_with_details(context, token.line(), token.column(), sanelli::make_string("Unexpected token '", token_type, "' found after indetifier."));
}
}
break;
case blaise_token_type::BEGIN:
statement = parse_compound_statement(context, parent);
match_ending_semicolon = false;
break;
case blaise_token_type::IF:
statement = parse_if_statement(context);
match_ending_semicolon = false;
break;
case blaise_token_type::FOR:
statement = parse_for_loop_statement(context);
match_ending_semicolon = false;
break;
case blaise_token_type::DO:
statement = parse_do_while_loop_statement(context);
break;
case blaise_token_type::WHILE:
statement = parse_while_loop_statement(context);
match_ending_semicolon = false;
break;
case blaise_token_type::REPEAT:
statement = parse_repeat_until_loop_statement(context);
break;
case blaise_token_type::SEMICOLON:
statement = parse_empty_statement(context);
match_ending_semicolon = false;
break;
case blaise_token_type::DELETE:
statement = parse_delete_statement(context);
break;
default:
throw_parse_error_with_details(context, token.line(), token.column(), sanelli::make_string("Unexpected token '", token_type, "' found."));
}
if (match_ending_semicolon)
match_token(context, blaise_token_type::SEMICOLON);
SANELLI_DEBUG("blaise-parser", "[EXIT] blaise_parser::parse_statement" << std::endl);
return statement;
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_compound_statement(blaise_parser_context &context, std::shared_ptr<ast::blaise_ast_statement_compund> parent)
{
SANELLI_DEBUG("blaise-parser", "[ENTER] blaise_parser::parse_compound_statement" << std::endl);
auto begin_token = context.peek_token();
match_token(context, blaise_token_type::BEGIN);
auto compund_statement = ast::make_compound_statement(begin_token);
if (parent != nullptr)
parent->push_back(compund_statement);
while (!is_token(context, blaise_token_type::END))
{
auto statement = parse_statement(context);
compund_statement->push_back(statement);
}
match_token(context, blaise_token_type::END);
SANELLI_DEBUG("blaise-parser", "[EXIT] blaise_parser::parse_compound_statement" << std::endl);
return compund_statement;
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_subroutine_call_statement(blaise_parser_context &context)
{
SANELLI_DEBUG("blaise-parser", "[ENTER] blaise_parser::parse_subroutine_call_statement" << std::endl);
auto identifier_token = context.peek_token();
match_token(context, blaise_token_type::IDENTIFIER);
match_token(context, blaise_token_type::LEFT_PARENTHESES);
vector<shared_ptr<ast::blaise_ast_expression>> expressions;
vector<std::shared_ptr<ast::blaise_ast_type>> types;
parse_subroutine_call_parameters(context, expressions, types);
match_token(context, blaise_token_type::RIGHT_PARENTHESES);
auto subroutine = context.module()->get_subroutine(identifier_token, types);
if (subroutine == nullptr)
throw_parse_error_with_details(context, identifier_token.line(), identifier_token.column(), sanelli::make_string("Cannot find function '", identifier_token.value(), "(", types, ")'"));
ast::introduce_cast_if_required(identifier_token, subroutine, expressions);
auto statement = ast::make_blaise_ast_statement_subroutine_call(identifier_token, subroutine, expressions);
SANELLI_DEBUG("blaise-parser", "[EXIT] blaise_parser::parse_subroutine_call_statement" << std::endl);
return statement;
}
void blaise_parser::parse_subroutine_call_parameters(blaise_parser_context &context,
std::vector<std::shared_ptr<ast::blaise_ast_expression>> &expressions,
std::vector<std::shared_ptr<ast::blaise_ast_type>> &types)
{
SANELLI_DEBUG("blaise-parser", "[ENTER] blaise_parser::parse_subroutine_call_parameters" << std::endl);
auto token_type = context.peek_token().type();
if (token_type != blaise_token_type::RIGHT_PARENTHESES)
do
{
auto expression = parse_expression(context);
expressions.push_back(expression);
types.push_back(expression->result_type());
if (is_token_and_match(context, blaise_token_type::COMMA))
continue;
else if (!is_token(context, blaise_token_type::RIGHT_PARENTHESES))
{
auto token = context.peek_token();
throw_parse_error_with_details(context, token.line(), token.column(), "expected ')' or ','.");
}
token_type = context.peek_token().type();
} while (token_type != blaise_token_type::RIGHT_PARENTHESES);
SANELLI_DEBUG("blaise-parser", "[EXIT] blaise_parser::parse_subroutine_call_parameters" << std::endl);
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_assignamet_statement(blaise_parser_context &context)
{
SANELLI_DEBUG("blaise-parser", "[ENTER] blaise_parser::parse_assignment" << std::endl);
auto identifier = context.peek_token();
match_token(context, blaise_token_type::IDENTIFIER);
auto variable = context.current_subroutine()->get_memory_location(identifier.value());
if (variable == nullptr)
throw_parse_error_with_details(context, identifier.line(), identifier.column(), sanelli::make_string("Variable ", identifier.value(), " does not exists in the context."));
if (variable->variable_type() == ast::blaise_ast_variable_type::CONSTANT)
throw_parse_error_with_details(context, identifier.line(), identifier.column(),
sanelli::make_string("Constant '", identifier.value(), "' cannot be assigned"));
std::shared_ptr<ast::blaise_ast_identifier> variable_identifier = nullptr;
if (is_token_and_match(context, blaise_token_type::LEFT_BRACKET))
{ // Assignment to array
std::vector<std::shared_ptr<ast::blaise_ast_expression>> indexing_expressions;
do {
auto index_token = context.peek_token();
auto indexing_expression = parse_expression(context);
auto integer_type = ast::make_plain_type(ast::blaise_ast_system_type::INTEGER);
if (!indexing_expression->result_type()->equals(integer_type) &&
!ast::blaise_ast_utility::can_auto_cast(indexing_expression->result_type(), integer_type))
{
throw_parse_error_with_details(context, indexing_expression->line(), indexing_expression->column(),
"Indexing expression must be an integer or a type that can be casted to an integer.");
}
indexing_expression = ast::introduce_cast_if_required(index_token, integer_type, indexing_expression);
indexing_expressions.push_back(indexing_expression);
is_token_and_match(context, blaise_token_type::COMMA);
} while(!is_token_and_match(context, blaise_token_type::RIGHT_BRACKET));
auto array_type = ast::blaise_ast_utility::as_array_type(variable->type());
if(array_type->dimensions() != indexing_expressions.size())
throw_parse_error_with_details(context, identifier.line(), identifier.column(),
sanelli::make_string("Number of dimensions (",indexing_expressions.size(),") while accessing array \"",
variable->name(),
"\" does not match type number of dimensions (",array_type->dimensions(),")"));
variable_identifier = ast::make_blaise_ast_array_identifier(identifier, variable, indexing_expressions);
}
else
{ // Standard variable identifier
variable_identifier = ast::make_blaise_ast_variable_identifier(identifier, variable);
}
match_token(context, blaise_token_type::ASSIGNMENT);
auto expression = parse_expression(context);
auto statement = ast::make_assignement_statement(identifier, variable_identifier, expression);
SANELLI_DEBUG("blaise-parser", "[EXIT] blaise_parser::parse_assignment" << std::endl);
return statement;
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_if_statement(blaise_parser_context &context)
{
SANELLI_DEBUG("blaise-parser", "[ENTER] blaise_parser::parse_if_statement" << std::endl);
auto reference = context.peek_token();
match_token(context, blaise_token_type::IF);
auto condition_reference = context.peek_token();
auto condition_expression = parse_expression(context);
match_token(context, blaise_token_type::THEN);
auto then_statement = parse_statement(context);
std::shared_ptr<ast::blaise_ast_statement> else_statement = nullptr;
if (is_token_and_match(context, blaise_token_type::ELSE))
else_statement = parse_statement(context);
condition_expression = ast::cast_to_boolean(condition_reference, condition_expression);
auto if_statement = ast::make_blaise_ast_statement_if(reference, condition_expression, then_statement, else_statement);
SANELLI_DEBUG("blaise-parser", "[EXIT] blaise_parser::parse_if_statement" << std::endl);
return if_statement;
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_for_loop_statement(blaise_parser_context &context)
{
auto integer_type = ast::make_plain_type(ast::blaise_ast_system_type::INTEGER);
auto loop_token = context.peek_token();
match_token(context, blaise_token_type::FOR);
auto identifier_token = context.peek_token();
match_token(context, blaise_token_type::IDENTIFIER);
auto variable = context.current_subroutine()->get_memory_location(identifier_token.value());
if (variable == nullptr)
throw_parse_error_with_details(context, identifier_token.line(), identifier_token.column(),
sanelli::make_string("Cannot find variable with name '", identifier_token.value(), "'"));
if (variable->variable_type() == ast::blaise_ast_variable_type::CONSTANT)
throw_parse_error_with_details(context, identifier_token.line(), identifier_token.column(),
sanelli::make_string("Cannot user constant '", identifier_token.value(), "' as for loop indexing"));
if (!ast::blaise_ast_utility::is_integer(variable->type()))
throw_parse_error_with_details(context, identifier_token.line(), identifier_token.column(),
sanelli::make_string("Cannot user variable '", identifier_token.value(), "': it must be of type 'integer'."));
auto variable_identifier = ast::make_blaise_ast_variable_identifier(identifier_token, variable);
match_token(context, blaise_token_type::FROM);
auto from_expression = parse_expression(context);
if (!ast::blaise_ast_utility::is_integer(from_expression->result_type()) && !ast::blaise_ast_utility::can_auto_cast(from_expression->result_type(), integer_type))
throw_parse_error_with_details(context, from_expression->line(), from_expression->column(),
"FROM expression must be integer.");
from_expression = ast::introduce_cast_if_required(loop_token, integer_type, from_expression);
match_token(context, blaise_token_type::TO);
auto to_expression = parse_expression(context);
if (!ast::blaise_ast_utility::is_integer(to_expression->result_type()) && !ast::blaise_ast_utility::can_auto_cast(to_expression->result_type(), integer_type))
throw_parse_error_with_details(context, to_expression->line(), to_expression->column(),
"TO expression must be integer.");
to_expression = ast::introduce_cast_if_required(loop_token, integer_type, to_expression);
std::shared_ptr<ast::blaise_ast_expression> step_expression;
if (is_token_and_match(context, blaise_token_type::STEP))
{
step_expression = parse_expression(context);
if (!ast::blaise_ast_utility::is_integer(step_expression->result_type()) && !ast::blaise_ast_utility::can_auto_cast(step_expression->result_type(), integer_type))
throw_parse_error_with_details(context, step_expression->line(), step_expression->column(),
"STEP expression must be integer.");
step_expression = ast::introduce_cast_if_required(loop_token, integer_type, step_expression);
}
auto body = parse_statement(context);
return ast::make_blaise_ast_statement_for_loop(loop_token, variable_identifier, from_expression, to_expression, step_expression, body);
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_while_loop_statement(blaise_parser_context &context)
{
auto boolean_type = ast::make_plain_type(ast::blaise_ast_system_type::BOOLEAN);
auto loop_token = context.peek_token();
match_token(context, blaise_token_type::WHILE);
auto condition = parse_expression(context);
if (!ast::blaise_ast_utility::is_boolean(condition->result_type()) && !ast::blaise_ast_utility::can_auto_cast(condition->result_type(), boolean_type))
throw_parse_error_with_details(context, condition->line(), condition->column(),
"Condition must be a boolean expression.");
condition = ast::introduce_cast_if_required(loop_token, boolean_type, condition);
auto body = parse_statement(context);
return ast::make_blaise_ast_statement_while_loop(loop_token, condition, body);
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_do_while_loop_statement(blaise_parser_context &context)
{
auto boolean_type = ast::make_plain_type(ast::blaise_ast_system_type::BOOLEAN);
auto loop_token = context.peek_token();
match_token(context, blaise_token_type::DO);
auto body = parse_statement(context);
match_token(context, blaise_token_type::WHILE);
auto condition = parse_expression(context);
if (!ast::blaise_ast_utility::is_boolean(condition->result_type()) && !ast::blaise_ast_utility::can_auto_cast(condition->result_type(), boolean_type))
throw_parse_error_with_details(context, condition->line(), condition->column(),
"Condition must be a boolean expression.");
condition = ast::introduce_cast_if_required(loop_token, boolean_type, condition);
return ast::make_blaise_ast_statement_dowhile_loop(loop_token, condition, body);
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_repeat_until_loop_statement(blaise_parser_context &context)
{
auto boolean_type = ast::make_plain_type(ast::blaise_ast_system_type::BOOLEAN);
auto loop_token = context.peek_token();
match_token(context, blaise_token_type::REPEAT);
auto body = parse_statement(context);
match_token(context, blaise_token_type::UNTIL);
auto condition = parse_expression(context);
if (!ast::blaise_ast_utility::is_boolean(condition->result_type()) && !ast::blaise_ast_utility::can_auto_cast(condition->result_type(), boolean_type))
throw_parse_error_with_details(context, condition->line(), condition->column(),
"Condition must be a boolean expression.");
condition = ast::introduce_cast_if_required(loop_token, boolean_type, condition);
return ast::make_blaise_ast_statement_repeatuntil_loop(loop_token, condition, body);
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_empty_statement(blaise_parser_context &context)
{
auto token = context.peek_token();
match_token(context, blaise_token_type::SEMICOLON);
return ast::make_empty_statement(token);
}
std::shared_ptr<ast::blaise_ast_statement> blaise_parser::parse_delete_statement(blaise_parser_context &context)
{
auto token = context.peek_token();
match_token(context, blaise_token_type::DELETE);
match_token(context, blaise_token_type::LEFT_PARENTHESES);
auto identifier_token = context.peek_token();
auto variable = context.current_subroutine()->get_memory_location(identifier_token.value());
auto variable_identifier = ast::make_blaise_ast_variable_identifier(identifier_token, variable);
if (variable->variable_type() == ast::blaise_ast_variable_type::CONSTANT)
throw_parse_error_with_details(context, token.line(), token.column(),
"Delete operator cannot be applied to constants.");
if (!ast::blaise_ast_utility::is_array(variable->type()))
throw_parse_error_with_details(context, token.line(), token.column(),
sanelli::make_string("Delete operator cannot be applied to variable of type ", ast::to_string(variable->type()), "."));
match_token(context, blaise_token_type::IDENTIFIER);
match_token(context, blaise_token_type::RIGHT_PARENTHESES);
return ast::make_delete_statement(token, variable_identifier);
}
| 50.657382
| 190
| 0.722479
|
sanelli
|
367db5ada7d5c0a638f7d080fabc7de490406c80
| 609
|
cpp
|
C++
|
ass3/SortContext.cpp
|
m-fahim/SortPatte
|
ec926507bd356d3bfb0045ae40470ea07a5924d2
|
[
"MS-PL"
] | null | null | null |
ass3/SortContext.cpp
|
m-fahim/SortPatte
|
ec926507bd356d3bfb0045ae40470ea07a5924d2
|
[
"MS-PL"
] | null | null | null |
ass3/SortContext.cpp
|
m-fahim/SortPatte
|
ec926507bd356d3bfb0045ae40470ea07a5924d2
|
[
"MS-PL"
] | null | null | null |
#include "StdAfx.h"
#include "SortContext.h"
#include "ConStratBubbleSort.h"
#include "ConStratInsertionSort.h"
SortContext::SortContext(void)
{
imp_strat = new ConStratBubbleSort();
}
int* SortContext::readVector( int v[], int n ) {
v = imp_strat->sort( v, n );
return v;
}
void SortContext::reqBS() {
destroyPointer();
imp_strat = new ConStratBubbleSort();
}
void SortContext::reqIS() {
destroyPointer();
imp_strat = new ConStratInsertionSort();
}
void SortContext::destroyPointer()
{
delete imp_strat;
}
SortContext::~SortContext(void)
{
delete imp_strat;
}
| 16.459459
| 48
| 0.681445
|
m-fahim
|
368117f9e6ffa935129390e05556435400fb2a64
| 981
|
cpp
|
C++
|
test/test_algs.cpp
|
bamceil/CLRS
|
d6dc1f73db5b1689b28f1d89dd3d6f514c23dcf5
|
[
"Apache-2.0"
] | null | null | null |
test/test_algs.cpp
|
bamceil/CLRS
|
d6dc1f73db5b1689b28f1d89dd3d6f514c23dcf5
|
[
"Apache-2.0"
] | null | null | null |
test/test_algs.cpp
|
bamceil/CLRS
|
d6dc1f73db5b1689b28f1d89dd3d6f514c23dcf5
|
[
"Apache-2.0"
] | null | null | null |
#include "algs.hpp"
#include <gtest/gtest.h>
#include <vector>
using namespace std;
using namespace CLRS;
TEST(HornerMulti, NonInput) {
vector<int> v;
EXPECT_EQ(0, horner_multiplication(v, 1));
}
TEST(HornerMulti, Xis0) {
vector<int> v{ 1, 2, 3 };
EXPECT_EQ(1, horner_multiplication(v, 0));
}
TEST(HornerMulti, RegularInput) {
vector<int> v{ 1, 2, 3, 4 };
EXPECT_EQ(142, horner_multiplication(v, 3));
}
TEST(MinMax, Empty) {
vector<int> v;
auto [minIdx, maxIdx] = min_max(v);
EXPECT_EQ(minIdx, -1);
EXPECT_EQ(maxIdx, -1);
}
TEST(MinMax, NoMax) {
vector<int> v{ 6 };
auto [minIdx, maxIdx] = min_max(v);
EXPECT_EQ(minIdx, 0);
EXPECT_EQ(maxIdx, -1);
}
TEST(MinMax, SimpleInput) {
vector<int> v{ 6, 1, 2, 5, 7 };
auto [minIdx, maxIdx] = min_max(v);
EXPECT_EQ(minIdx, 1);
EXPECT_EQ(maxIdx, 4);
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 20.020408
| 48
| 0.623853
|
bamceil
|
3687da1a16d7ef3bca5d2f25043e736dc0f8f061
| 2,668
|
cpp
|
C++
|
editor/source/widget/project_manager/widget_project_manager.cpp
|
skarab/coffee-master
|
6c3ff71b7f15735e41c9859b6db981b94414c783
|
[
"MIT"
] | null | null | null |
editor/source/widget/project_manager/widget_project_manager.cpp
|
skarab/coffee-master
|
6c3ff71b7f15735e41c9859b6db981b94414c783
|
[
"MIT"
] | null | null | null |
editor/source/widget/project_manager/widget_project_manager.cpp
|
skarab/coffee-master
|
6c3ff71b7f15735e41c9859b6db981b94414c783
|
[
"MIT"
] | null | null | null |
#include "widget/project_manager/widget_project_manager.h"
#include "widget/project_manager/widget_project_general.h"
#include "widget/project_manager/widget_project_plugins.h"
#include "widget/project_manager/deploy/widget_deploy_package.h"
#include "widget/project_manager/deploy/widget_deploy_desktop.h"
namespace coffee_editor
{
namespace widget
{
//-CONSTRUCTORS-------------------------------------------------------------------------------//
ProjectManager::ProjectManager() :
_TabControl(NULL)
{
}
//--------------------------------------------------------------------------------------------//
ProjectManager::~ProjectManager()
{
}
//-OPERATIONS---------------------------------------------------------------------------------//
void ProjectManager::Create()
{
ui::widget::Dialog::Create(
NULL,
basic::Vector2i(),
basic::Vector2i(410, 353));
SetTitleBarText("Project Manager");
_TabControl = COFFEE_New(ui::widget::TabControl);
_TabControl->Create(this, basic::Vector2i(), basic::Vector2i());
_TabControl->GetLayout().SetStyle(_TabControl->GetLayout().GetStyle()
| ui::LAYOUT_STYLE_Expand);
_TabControl->AddSeparator("Settings");
_TabControl->AddTab("General");
_TabControl->AddTab("Plugins");
_TabControl->AddSeparator("Deployment");
_TabControl->AddTab("Package");
_TabControl->AddTab("Desktop");
_TabControl->ActivateTab("General");
PositionToCenter();
}
//-EVENTS-------------------------------------------------------------------------------------//
COFFEE_BeginEventHandler(ProjectManager, ui::widget::Dialog)
COFFEE_RegisterEventHandler(ui::widget::TAB_CONTROL_EVENT_Activate, ui::widget::TabControl, OnActivateTab)
COFFEE_EndEventHandler()
//--------------------------------------------------------------------------------------------//
bool ProjectManager::OnActivateTab(shell::Event& event)
{
if (_TabControl->GetActiveTab()=="General")
(COFFEE_New(ProjectGeneral))->Create(&_TabControl->GetClientWindow());
else if (_TabControl->GetActiveTab()=="Plugins")
(COFFEE_New(ProjectPlugins))->Create(&_TabControl->GetClientWindow());
else if (_TabControl->GetActiveTab()=="Package")
(COFFEE_New(DeployPackage))->Create(&_TabControl->GetClientWindow());
else if (_TabControl->GetActiveTab()=="Desktop")
(COFFEE_New(DeployDesktop))->Create(&_TabControl->GetClientWindow());
return true;
}
}
}
| 35.573333
| 114
| 0.547976
|
skarab
|
3693e1d8a928f85c4d8adb01e22b58f8fbbc342a
| 346
|
cpp
|
C++
|
Chapter3/Excercise14.cpp
|
yapbenzet/absolute-c-plusplus
|
67adef6c177e7ef3c71406cd26cef2a944fd0d19
|
[
"MIT"
] | 1
|
2019-08-13T17:51:24.000Z
|
2019-08-13T17:51:24.000Z
|
Chapter3/Excercise14.cpp
|
yapbenzet/absolute-c-plusplus
|
67adef6c177e7ef3c71406cd26cef2a944fd0d19
|
[
"MIT"
] | null | null | null |
Chapter3/Excercise14.cpp
|
yapbenzet/absolute-c-plusplus
|
67adef6c177e7ef3c71406cd26cef2a944fd0d19
|
[
"MIT"
] | 1
|
2020-06-05T13:37:56.000Z
|
2020-06-05T13:37:56.000Z
|
#include <iostream>
using namespace std;
bool isAlphabet(char ch);
int main() {
cout << isAlphabet('1') << endl;
cout << isAlphabet('a') << endl;
cout << isAlphabet('A') << endl;
return 0;
}
bool isAlphabet(char ch) {
if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')) {
return true;
}
else {
return false;
}
}
| 15.727273
| 61
| 0.526012
|
yapbenzet
|
3697037b42d51e785f3812dc2bc5829c8335786f
| 2,590
|
hpp
|
C++
|
libraries/protocol/include/amalgam/protocol/operations.hpp
|
amalgam-blockchain/amalgam
|
eca6faf82fe906e85cc227a3182eb9bb0520bc52
|
[
"MIT"
] | null | null | null |
libraries/protocol/include/amalgam/protocol/operations.hpp
|
amalgam-blockchain/amalgam
|
eca6faf82fe906e85cc227a3182eb9bb0520bc52
|
[
"MIT"
] | null | null | null |
libraries/protocol/include/amalgam/protocol/operations.hpp
|
amalgam-blockchain/amalgam
|
eca6faf82fe906e85cc227a3182eb9bb0520bc52
|
[
"MIT"
] | null | null | null |
#pragma once
#include <amalgam/protocol/operation_util.hpp>
#include <amalgam/protocol/amalgam_operations.hpp>
#include <amalgam/protocol/amalgam_virtual_operations.hpp>
namespace amalgam { namespace protocol {
/** NOTE: do not change the order of any operations prior to the virtual operations
* or it will trigger a hardfork.
*/
typedef fc::static_variant<
transfer_operation,
transfer_to_vesting_operation,
withdraw_vesting_operation,
limit_order_create_operation,
limit_order_cancel_operation,
feed_publish_operation,
convert_operation,
account_create_operation,
account_update_operation,
witness_update_operation,
account_witness_vote_operation,
account_witness_proxy_operation,
custom_operation,
custom_json_operation,
set_withdraw_vesting_route_operation,
limit_order_create2_operation,
request_account_recovery_operation,
recover_account_operation,
change_recovery_account_operation,
escrow_transfer_operation,
escrow_dispute_operation,
escrow_release_operation,
escrow_approve_operation,
transfer_to_savings_operation,
transfer_from_savings_operation,
cancel_transfer_from_savings_operation,
custom_binary_operation,
decline_voting_rights_operation,
delegate_vesting_shares_operation,
witness_set_properties_operation,
tbd1_operation,
tbd2_operation,
tbd3_operation,
tbd4_operation,
tbd5_operation,
tbd6_operation,
tbd7_operation,
tbd8_operation,
tbd9_operation,
tbd10_operation,
/// virtual operations below this point
fill_convert_request_operation,
interest_operation,
fill_vesting_withdraw_operation,
fill_order_operation,
fill_transfer_from_savings_operation,
hardfork_operation,
return_vesting_delegation_operation,
producer_reward_operation,
clear_null_account_balance_operation
> operation;
bool is_market_operation( const operation& op );
bool is_virtual_operation( const operation& op );
} } // amalgam::protocol
AMALGAM_DECLARE_OPERATION_TYPE( amalgam::protocol::operation )
FC_REFLECT_TYPENAME( amalgam::protocol::operation )
| 32.375
| 86
| 0.66332
|
amalgam-blockchain
|
36a135c89bfec01566da62b48b3cf74791ff9706
| 37,093
|
cpp
|
C++
|
src/ripple/app/main/Application.cpp
|
ChainSQL/chainsqld
|
6af7eb0624c67776098250a39eae9f195d8a473a
|
[
"BSL-1.0"
] | 211
|
2017-12-11T03:11:37.000Z
|
2022-03-15T12:38:19.000Z
|
src/ripple/app/main/Application.cpp
|
ChainSQL/chainsqld
|
6af7eb0624c67776098250a39eae9f195d8a473a
|
[
"BSL-1.0"
] | 17
|
2017-12-18T07:22:06.000Z
|
2022-02-15T10:24:29.000Z
|
src/ripple/app/main/Application.cpp
|
ChainSQL/chainsqld
|
6af7eb0624c67776098250a39eae9f195d8a473a
|
[
"BSL-1.0"
] | 81
|
2017-12-11T03:09:21.000Z
|
2022-03-20T09:42:42.000Z
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/app/consensus/RCLValidations.h>
#include <ripple/app/ledger/InboundLedgers.h>
#include <ripple/app/ledger/InboundTransactions.h>
#include <ripple/app/ledger/LedgerMaster.h>
#include <ripple/app/ledger/LedgerToJson.h>
#include <ripple/app/ledger/OpenLedger.h>
#include <ripple/app/ledger/OrderBookDB.h>
#include <ripple/app/ledger/PendingSaves.h>
#include <ripple/app/ledger/TransactionMaster.h>
#include <ripple/app/main/Application.h>
#include <ripple/app/main/BasicApp.h>
#include <ripple/app/main/DBInit.h>
#include <ripple/app/main/GRPCServer.h>
#include <ripple/app/main/LoadManager.h>
#include <ripple/app/main/NodeIdentity.h>
#include <ripple/app/main/NodeStoreScheduler.h>
#include <ripple/app/misc/AmendmentTable.h>
#include <ripple/app/misc/HashRouter.h>
#include <ripple/app/misc/LoadFeeTrack.h>
#include <ripple/app/misc/NetworkOPs.h>
#include <ripple/app/misc/SHAMapStore.h>
#include <ripple/app/misc/TxQ.h>
#include <ripple/app/misc/ValidatorKeys.h>
#include <ripple/app/misc/ValidatorSite.h>
#include <ripple/app/paths/PathRequests.h>
#include <ripple/app/tx/apply.h>
#include <ripple/basics/ByteUtilities.h>
#include <ripple/basics/PerfLog.h>
#include <ripple/basics/ResolverAsio.h>
#include <ripple/basics/safe_cast.h>
#include <ripple/beast/asio/io_latency_probe.h>
#include <ripple/beast/core/LexicalCast.h>
#include <ripple/core/DatabaseCon.h>
#include <ripple/core/Stoppable.h>
#include <ripple/json/json_reader.h>
#include <ripple/nodestore/DatabaseShard.h>
#include <ripple/nodestore/DummyScheduler.h>
#include <ripple/overlay/Cluster.h>
#include <ripple/overlay/PeerReservationTable.h>
#include <ripple/overlay/make_Overlay.h>
#include <ripple/protocol/BuildInfo.h>
#include <ripple/protocol/Feature.h>
#include <ripple/protocol/Protocol.h>
#include <ripple/protocol/STParsedJSON.h>
#include <ripple/resource/Fees.h>
#include <ripple/shamap/NodeFamily.h>
#include <ripple/shamap/ShardFamily.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/system/error_code.hpp>
#include <condition_variable>
#include <cstring>
#include <fstream>
#include <iostream>
#include <mutex>
#include <openssl/evp.h>
#include <peersafe/app/misc/CACertSite.h>
#include <peersafe/app/misc/CertList.h>
#include <peersafe/app/misc/ContractHelper.h>
#include <peersafe/app/misc/StateManager.h>
#include <peersafe/app/misc/TxPool.h>
#include <peersafe/app/sql/TxStore.h>
#include <peersafe/app/storage/TableStorage.h>
#include <peersafe/app/table/TableStatusDBMySQL.h>
#include <peersafe/app/table/TableStatusDBSQLite.h>
#include <peersafe/app/table/TableSync.h>
#include <peersafe/app/table/TableTxAccumulator.h>
#include <peersafe/rpc/impl/TableAssistant.h>
#include <peersafe/schema/PeerManager.h>
#include <peersafe/schema/Schema.h>
#include <peersafe/schema/SchemaManager.h>
#include <peersafe/precompiled/PreContractFace.h>
#include <boost/optional.hpp>
#include <sstream>
#include <ripple/basics/Sustain.h>
namespace ripple {
// VFALCO TODO Move the function definitions into the class declaration
class ApplicationImp : public Application, public RootStoppable, public BasicApp
{
private:
class io_latency_sampler
{
private:
beast::insight::Event m_event;
beast::Journal m_journal;
beast::io_latency_probe<std::chrono::steady_clock> m_probe;
std::atomic<std::chrono::milliseconds> lastSample_;
public:
io_latency_sampler(
beast::insight::Event ev,
beast::Journal journal,
std::chrono::milliseconds interval,
boost::asio::io_service& ios)
: m_event(ev)
, m_journal(journal)
, m_probe(interval, ios)
, lastSample_{}
{
}
void
start()
{
m_probe.sample(std::ref(*this));
}
template <class Duration>
void
operator()(Duration const& elapsed)
{
using namespace std::chrono;
auto const lastSample = date::ceil<milliseconds>(elapsed);
lastSample_ = lastSample;
if (lastSample >= 10ms)
m_event.notify(lastSample);
if (lastSample >= 500ms)
{
JLOG(m_journal.warn())
<< "io_service latency = " << lastSample.count();
}
}
std::chrono::milliseconds
get() const
{
return lastSample_.load();
}
void
cancel()
{
m_probe.cancel();
}
void
cancel_async()
{
m_probe.cancel_async();
}
};
public:
std::shared_ptr<Config> config_;
std::unique_ptr<Logs> logs_;
beast::Journal m_journal;
std::unique_ptr<TimeKeeper> timeKeeper_;
std::unique_ptr<perf::PerfLog> perfLog_;
std::unique_ptr<CollectorManager> m_collectorManager;
std::pair<PublicKey, SecretKey> nodeIdentity_;
ValidatorKeys const validatorKeys_;
std::unique_ptr<Resource::Manager> m_resourceManager;
std::unique_ptr<NodeStoreScheduler> m_nodeStoreScheduler;
std::unique_ptr<JobQueue> m_jobQueue;
std::unique_ptr<ServerHandler> serverHandler_;
std::unique_ptr<LoadManager> m_loadManager;
std::unique_ptr<SchemaManager> m_schemaManager;
std::unique_ptr<Overlay> m_overlay;
Application::MutexType m_masterMutex;
ClosureCounter<void, boost::system::error_code const&> waitHandlerCounter_;
boost::asio::steady_timer sweepTimer_;
boost::asio::steady_timer entropyTimer_;
bool startTimers_;
boost::asio::signal_set m_signals;
std::condition_variable cv_;
std::mutex mut_;
bool isTimeToStop = false;
std::atomic<bool> checkSigs_;
std::unique_ptr<ResolverAsio> m_resolver;
io_latency_sampler m_io_latency_sampler;
std::unique_ptr<GRPCServer> grpcServer_;
std::unique_ptr <PreContractFace> m_preContractFace;
//--------------------------------------------------------------------------
static std::size_t
numberOfThreads(Config const& config)
{
#if RIPPLE_SINGLE_IO_SERVICE_THREAD
return 1;
#else
auto const cores = std::thread::hardware_concurrency();
// Use a single thread when running on under-provisioned systems
// or if we are configured to use minimal resources.
if ((cores == 1) || ((config.NODE_SIZE == 0) && (cores == 2)))
return 1;
// Otherwise, prefer two threads.
return 2;
#endif
}
//--------------------------------------------------------------------------
ApplicationImp(
std::shared_ptr<Config> config,
std::unique_ptr<Logs> logs,
std::unique_ptr<TimeKeeper> timeKeeper)
: RootStoppable("Application")
, BasicApp(numberOfThreads(*config))
, config_(config)
, logs_(std::move(logs))
, m_journal(logs_->journal("Application"))
, timeKeeper_(std::move(timeKeeper))
// PerfLog must be started before any other threads are launched.
, perfLog_(perf::make_PerfLog(
perf::setup_PerfLog(
config_->section("perf"),
config_->CONFIG_DIR),
*this,
logs_->journal("PerfLog"),
[this]() { signalStop(); }))
, m_collectorManager(CollectorManager::New(
config_->section(SECTION_INSIGHT),
logs_->journal("Collector")))
, validatorKeys_(*config_, m_journal)
, m_resourceManager(Resource::make_Manager(
m_collectorManager->collector(),
logs_->journal("Resource")))
, m_nodeStoreScheduler(std::make_unique<NodeStoreScheduler>(*this))
// The JobQueue has to come pretty early since
// almost everything is a Stoppable child of the JobQueue.
//
, m_jobQueue(std::make_unique<JobQueue>(
m_collectorManager->group("jobq"),
*m_nodeStoreScheduler,
logs_->journal("JobQueue"),
*logs_,
*perfLog_))
, serverHandler_(make_ServerHandler(
*this,
*this,
get_io_service(),
*m_jobQueue,
*m_resourceManager,
*m_collectorManager))
, m_loadManager(
make_LoadManager(*this, *this, logs_->journal("LoadManager")))
, m_schemaManager(std::make_unique<SchemaManager>(
*this,
logs_->journal("SchemaManager")))
, sweepTimer_(get_io_service())
, entropyTimer_(get_io_service())
, startTimers_(false)
, m_signals(get_io_service())
, checkSigs_(true)
, m_resolver(
ResolverAsio::New(get_io_service(), logs_->journal("Resolver")))
, m_io_latency_sampler(
m_collectorManager->collector()->make_event("ios_latency"),
logs_->journal("Application"),
std::chrono::milliseconds(100),
get_io_service())
, grpcServer_(std::make_unique<GRPCServer>(*this))
{
add(m_resourceManager.get());
//
// VFALCO - READ THIS!
//
// Do not start threads, open sockets, or do any sort of "real work"
// inside the constructor. Put it in onStart instead. Or if you must,
// put it in setup (but everything in setup should be moved to onStart
// anyway.
//
// The reason is that the unit tests require an Application object to
// be created. But we don't actually start all the threads, sockets,
// and services when running the unit tests. Therefore anything which
// needs to be stopped will not get stopped correctly if it is
// started in this constructor.
//
// VFALCO HACK
m_nodeStoreScheduler->setJobQueue(*m_jobQueue);
// add (m_ledgerMaster->getPropertySource ());
}
//--------------------------------------------------------------------------
bool
setup() override;
void
doStart(bool withTimers) override;
void
run() override;
bool
isShutdown() override;
void
signalStop() override;
bool
checkSigs() const override;
void
checkSigs(bool) override;
int
fdRequired() const override;
//--------------------------------------------------------------------------
Logs&
logs() override
{
return *logs_;
}
bool
hasSchema(SchemaID const& id /* = beast::zero */) override
{
if (m_schemaManager->contains(id))
return true;
else
return false;
}
Schema&
getSchema(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return *m_schemaManager->getSchema(id);
}
PeerManager&
peerManager(SchemaID const& id /* = beast::zero */) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->peerManager();
}
Config&
config(SchemaID const& id) override
{
if (id == beast::zero)
return *config_;
else
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->config();
}
}
CollectorManager&
getCollectorManager() override
{
return *m_collectorManager;
}
NodeStoreScheduler&
nodeStoreScheduler() override
{
return *m_nodeStoreScheduler;
}
Family&
getNodeFamily(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getNodeFamily();
}
Family*
getShardFamily(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getShardFamily();
}
TimeKeeper&
timeKeeper() override
{
return *timeKeeper_;
}
JobQueue&
getJobQueue() override
{
return *m_jobQueue;
}
Overlay&
overlay() override
{
return *m_overlay;
}
std::pair<PublicKey, SecretKey> const&
nodeIdentity() override
{
return nodeIdentity_;
}
TxStoreDBConn&
getTxStoreDBConn(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTxStoreDBConn();
}
PreContractFace& getPreContractFace() override
{
return *m_preContractFace;
}
TxStore&
getTxStore(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTxStore();
}
TableStatusDB&
getTableStatusDB(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTableStatusDB();
}
TableSync&
getTableSync(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTableSync();
}
TableStorage&
getTableStorage(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTableStorage();
}
TableAssistant&
getTableAssistant(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTableAssistant();
}
ContractHelper&
getContractHelper(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getContractHelper();
}
TableTxAccumulator&
getTableTxAccumulator(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTableTxAccumulator();
}
TxPool&
getTxPool(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTxPool();
}
StateManager&
getStateManager(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getStateManager();
}
virtual PublicKey const&
getValidationPublicKey() const override
{
return validatorKeys_.publicKey;
}
ValidatorKeys const&
getValidatorKeys() const override
{
return validatorKeys_;
}
ResolverAsio&
getResolver() override
{
return *m_resolver;
}
ServerHandler&
getServerHandler() override
{
return *serverHandler_;
}
SchemaManager&
getSchemaManager() override
{
return *m_schemaManager;
}
NetworkOPs&
getOPs(SchemaID const& id = beast::zero) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getOPs();
}
PeerReservationTable&
peerReservations(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->peerReservations();
}
boost::asio::io_service&
getIOService() override
{
return get_io_service();
}
std::chrono::milliseconds
getIOLatency() override
{
return m_io_latency_sampler.get();
}
LedgerMaster&
getLedgerMaster(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getLedgerMaster();
}
InboundLedgers&
getInboundLedgers(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getInboundLedgers();
}
InboundTransactions&
getInboundTransactions(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getInboundTransactions();
}
TaggedCache<uint256, AcceptedLedger>&
getAcceptedLedgerCache(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getAcceptedLedgerCache();
}
TransactionMaster&
getMasterTransaction(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getMasterTransaction();
}
perf::PerfLog&
getPerfLog() override
{
return *perfLog_;
}
NodeCache&
getTempNodeCache(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTempNodeCache();
}
NodeStore::Database&
getNodeStore(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getNodeStore();
}
NodeStore::DatabaseShard*
getShardStore(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getShardStore();
}
RPC::ShardArchiveHandler*
getShardArchiveHandler(SchemaID const& id, bool tryRecovery) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getShardArchiveHandler(
tryRecovery);
}
Application::MutexType&
getMasterMutex() override
{
return m_masterMutex;
}
LoadManager&
getLoadManager() override
{
return *m_loadManager;
}
Resource::Manager&
getResourceManager() override
{
return *m_resourceManager;
}
OrderBookDB&
getOrderBookDB(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getOrderBookDB();
}
PathRequests&
getPathRequests(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getPathRequests();
}
CachedSLEs&
cachedSLEs(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->cachedSLEs();
}
AmendmentTable&
getAmendmentTable(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getAmendmentTable();
}
LoadFeeTrack&
getFeeTrack(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getFeeTrack();
}
HashRouter&
getHashRouter(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getHashRouter();
}
RCLValidations&
getValidations(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getValidations();
}
ValidatorList&
validators(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->validators();
}
ValidatorSite&
validatorSites(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->validatorSites();
}
CertList&
certList(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->certList();
;
}
ManifestCache&
validatorManifests(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->validatorManifests();
}
ManifestCache&
publisherManifests(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->publisherManifests();
}
Cluster&
cluster(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->cluster();
}
SHAMapStore&
getSHAMapStore(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getSHAMapStore();
}
PendingSaves&
pendingSaves(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->pendingSaves();
}
AccountIDCache const&
accountIDCache(SchemaID const& id) const override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->accountIDCache();
}
OpenLedger&
openLedger(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->openLedger();
}
OpenLedger const&
openLedger(SchemaID const& id) const override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->openLedger();
}
TxQ&
getTxQ(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTxQ();
}
DatabaseCon&
getTxnDB(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getTxnDB();
}
DatabaseCon&
getLedgerDB(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getLedgerDB();
}
DatabaseCon&
getWalletDB(SchemaID const& id) override
{
assert(m_schemaManager->contains(id));
return m_schemaManager->getSchema(id)->getWalletDB();
}
bool
serverOkay(std::string& reason) override;
beast::Journal
journal(std::string const& name) override;
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Stoppable
//
void
onPrepare() override
{
}
void
onStart() override
{
JLOG(m_journal.info()) << "Application starting. Version is "
<< BuildInfo::getVersionString();
using namespace std::chrono_literals;
if (startTimers_)
{
setSweepTimer();
setEntropyTimer();
}
m_io_latency_sampler.start();
m_resolver->start();
}
// Called to indicate shutdown.
void
onStop() override
{
JLOG(m_journal.debug()) << "Application stopping";
m_io_latency_sampler.cancel_async();
// VFALCO Enormous hack, we have to force the probe to cancel
// before we stop the io_service queue or else it never
// unblocks in its destructor. The fix is to make all
// io_objects gracefully handle exit so that we can
// naturally return from io_service::run() instead of
// forcing a call to io_service::stop()
m_io_latency_sampler.cancel();
m_resolver->stop_async();
// NIKB This is a hack - we need to wait for the resolver to
// stop. before we stop the io_server_queue or weird
// things will happen.
m_resolver->stop();
{
boost::system::error_code ec;
sweepTimer_.cancel(ec);
if (ec)
{
JLOG(m_journal.error())
<< "Application: sweepTimer cancel error: " << ec.message();
}
ec.clear();
entropyTimer_.cancel(ec);
if (ec)
{
JLOG(m_journal.error())
<< "Application: entropyTimer cancel error: "
<< ec.message();
}
}
// Make sure that any waitHandlers pending in our timers are done
// before we declare ourselves stopped.
using namespace std::chrono_literals;
waitHandlerCounter_.join("Application", 1s, m_journal);
logs_->resetCallBack();
// foreach schema
for (auto iter = m_schemaManager->begin();
iter != m_schemaManager->end();
iter++)
{
auto schema = (*iter).second;
schema->doStop();
}
stopped();
}
//--------------------------------------------------------------------------
//
// PropertyStream
//
void
onWrite(beast::PropertyStream::Map& stream) override
{
}
//--------------------------------------------------------------------------
void
setSweepTimer()
{
// Only start the timer if waitHandlerCounter_ is not yet joined.
if (auto optionalCountedHandler = waitHandlerCounter_.wrap(
[this](boost::system::error_code const& e) {
if ((e.value() == boost::system::errc::success) &&
(!m_jobQueue->isStopped()))
{
m_jobQueue->addJob(
jtSWEEP, "sweep", [this](Job&) { doSweep(); });
}
// Recover as best we can if an unexpected error occurs.
if (e.value() != boost::system::errc::success &&
e.value() != boost::asio::error::operation_aborted)
{
// Try again later and hope for the best.
JLOG(m_journal.error())
<< "Sweep timer got error '" << e.message()
<< "'. Restarting timer.";
setSweepTimer();
}
}))
{
using namespace std::chrono;
sweepTimer_.expires_from_now(
seconds{config_->getValueFor(SizedItem::sweepInterval)});
sweepTimer_.async_wait(std::move(*optionalCountedHandler));
}
}
void
setEntropyTimer()
{
// Only start the timer if waitHandlerCounter_ is not yet joined.
if (auto optionalCountedHandler = waitHandlerCounter_.wrap(
[this](boost::system::error_code const& e) {
if (e.value() == boost::system::errc::success)
{
crypto_prng().mix_entropy();
setEntropyTimer();
}
// Recover as best we can if an unexpected error occurs.
if (e.value() != boost::system::errc::success &&
e.value() != boost::asio::error::operation_aborted)
{
// Try again later and hope for the best.
JLOG(m_journal.error())
<< "Entropy timer got error '" << e.message()
<< "'. Restarting timer.";
setEntropyTimer();
}
}))
{
using namespace std::chrono_literals;
entropyTimer_.expires_from_now(5min);
entropyTimer_.async_wait(std::move(*optionalCountedHandler));
}
}
void
doSweep()
{
// by ljl: foreach schema do sweep
for (auto iter = m_schemaManager->begin();
iter != m_schemaManager->end();
iter++)
{
auto schema = (*iter).second;
schema->doSweep();
}
// Set timer to do another sweep later.
setSweepTimer();
}
};
//------------------------------------------------------------------------------
// VFALCO TODO Break this function up into many small initialization segments.
// Or better yet refactor these initializations into RAII classes
// which are members of the Application object.
//
bool
ApplicationImp::setup()
{
if (!config_->standalone())
timeKeeper_->run(config_->SNTP_SERVERS);
auto schema_main = m_schemaManager->createSchemaMain(config_);
logs_->setCallBack(
[this](std::string const& s) -> void { this->getOPs().pubLogs(s); });
if (!schema_main->initBeforeSetup())
return false;
// VFALCO NOTE Unfortunately, in stand-alone mode some code still
// foolishly calls overlay(). When this is fixed we can
// move the instantiation inside a conditional:
//
// if (!config_.standalone())
m_overlay = make_Overlay(
*this,
setup_Overlay(*config_),
*m_jobQueue,
*serverHandler_,
*m_resourceManager,
*m_resolver,
getIOService(),
*config_,
m_collectorManager->collector());
add(*m_overlay); // add to PropertyStream
nodeIdentity_ = loadNodeIdentity(*this);
// VFALCO NOTE: 0 means use heuristics to determine the thread count.
m_jobQueue->setThreadCount(config_->WORKERS, config_->standalone());
grpcServer_->run();
// We want to intercept CTRL-C and the standard termination signal SIGTERM
// and terminate the process. This handler will NEVER be invoked twice.
//
// Note that async_wait is "one-shot": for each call, the handler will be
// invoked exactly once, either when one of the registered signals in the
// signal set occurs or the signal set is cancelled. Subsequent signals are
// effectively ignored (technically, they are queued up, waiting for a call
// to async_wait).
m_signals.add(SIGINT);
m_signals.add(SIGTERM);
m_signals.async_wait(
[this](boost::system::error_code const& ec, int signum) {
// Indicates the signal handler has been aborted; do nothing
if (ec == boost::asio::error::operation_aborted)
return;
JLOG(m_journal.info()) << "Received signal " << signum;
if (signum == SIGTERM || signum == SIGINT)
signalStop();
});
auto debug_log = config_->getDebugLogFile();
if (!debug_log.empty())
{
// Let debug messages go to the file but only WARNING or higher to
// regular output (unless verbose)
if (!logs_->open(debug_log))
std::cerr << "Can't open log file " << debug_log << '\n';
using namespace beast::severities;
if (logs_->threshold() > kDebug)
logs_->threshold(kDebug);
}
/*if (config().exists(SECTION_ENCRYPT_CARD_TYPE))
{
auto encryptCardType = config().section(SECTION_ENCRYPT_CARD_TYPE).lines().front();
if (encryptCardType == std::string("sjkCard"))
{
GmEncryptObj::hEType_ = GmEncryptObj::sjkCardType;
}
else if (encryptCardType == std::string("sdkey"))
{
GmEncryptObj::hEType_ = GmEncryptObj::sdkeyType;
}
else
{
GmEncryptObj::hEType_ = GmEncryptObj::unknown;
}
}*/
{
m_preContractFace = std::make_unique<PreContractFace>();
}
JLOG(m_journal.info()) << "process starting: "
<< BuildInfo::getFullVersionString();
if (numberOfThreads(*config_) < 2)
{
JLOG(m_journal.warn()) << "Limited to a single I/O service thread by "
"system configuration.";
}
// Optionally turn off logging to console.
logs_->silent(config_->silent());
if (!schema_main->setup())
return false;
{
try
{
auto setup = setup_ServerHandler(
*config_, beast::logstream{m_journal.error()});
setup.makeContexts();
serverHandler_->setup(setup, m_journal);
}
catch (std::exception const& e)
{
if (auto stream = m_journal.fatal())
{
stream << "Unable to setup server handler";
if (std::strlen(e.what()) > 0)
stream << ": " << e.what();
}
return false;
}
}
return true;
}
void
ApplicationImp::doStart(bool withTimers)
{
startTimers_ = withTimers;
prepare();
start();
}
void
ApplicationImp::run()
{
if (!config_->standalone())
{
// VFALCO NOTE This seems unnecessary. If we properly refactor the load
// manager then the deadlock detector can just always be
// "armed"
//
getLoadManager().activateDeadlockDetector();
}
{
std::unique_lock<std::mutex> lk{mut_};
cv_.wait(lk, [this] { return isTimeToStop; });
}
// Stop the server. When this returns, all
// Stoppable objects should be stopped.
JLOG(m_journal.info()) << "Received shutdown request";
stop(m_journal);
JLOG(m_journal.info()) << "Done.";
StopSustain();
}
void
ApplicationImp::signalStop()
{
// Unblock the main thread (which is sitting in run()).
// When we get C++20 this can use std::latch.
std::lock_guard lk{mut_};
if (!isTimeToStop)
{
isTimeToStop = true;
cv_.notify_all();
}
}
bool
ApplicationImp::isShutdown()
{
// from Stoppable mixin
return isStopped();
}
bool
ApplicationImp::checkSigs() const
{
return checkSigs_;
}
void
ApplicationImp::checkSigs(bool check)
{
checkSigs_ = check;
}
int
ApplicationImp::fdRequired() const
{
// Standard handles, config file, misc I/O etc:
int needed = 128;
// 2x the configured peer limit for peer connections:
needed += 2 * m_overlay->limit();
for (auto item : *m_schemaManager)
{
auto schema = item.second;
// the number of fds needed by the backend (internally
// doubled if online_delete is enabled).
if (schema->getShardStore())
needed += std::max(5, schema->getSHAMapStore().fdRequired());
}
// One fd per incoming connection a port can accept, or
// if no limit is set, assume it'll handle 256 clients.
for (auto const& p : serverHandler_->setup().ports)
needed += std::max(256, p.limit);
// The minimum number of file descriptors we need is 1024:
return std::max(1024, needed);
}
//------------------------------------------------------------------------------
bool
ApplicationImp::serverOkay(std::string& reason)
{
if (!config(beast::zero).ELB_SUPPORT)
return true;
if (isShutdown())
{
reason = "Server is shutting down";
return false;
}
if (getOPs(beast::zero).isNeedNetworkLedger())
{
reason = "Not synchronized with network yet";
return false;
}
if (getOPs(beast::zero).getOperatingMode() < OperatingMode::SYNCING)
{
reason = "Not synchronized with network";
return false;
}
if (!getLedgerMaster(beast::zero).isCaughtUp(reason))
return false;
if (getFeeTrack(beast::zero).isLoadedLocal())
{
reason = "Too much load";
return false;
}
if (getOPs(beast::zero).isAmendmentBlocked())
{
reason = "Server version too old";
return false;
}
return true;
}
beast::Journal
ApplicationImp::journal(std::string const& name)
{
return logs_->journal(name);
}
// VFALCO TODO clean this up since it is just a file holding a single member
// function definition
//------------------------------------------------------------------------------
Application::Application() : beast::PropertyStream::Source("app")
{
}
//------------------------------------------------------------------------------
std::unique_ptr<Application>
make_Application(
std::shared_ptr<Config> config,
std::unique_ptr<Logs> logs,
std::unique_ptr<TimeKeeper> timeKeeper)
{
return std::make_unique<ApplicationImp>(
std::move(config), std::move(logs), std::move(timeKeeper));
}
} // namespace ripple
| 28.754264
| 91
| 0.59464
|
ChainSQL
|
36a15c237fbef6a5896e962ab466e8ed33450e38
| 808
|
cpp
|
C++
|
ONI/qualification/17D/resolver.cpp
|
hacdias/cp
|
5a8ffbb0a8819189fc4308917db2c59548af76c9
|
[
"MIT"
] | 1
|
2017-02-12T20:58:39.000Z
|
2017-02-12T20:58:39.000Z
|
ONI/qualification/17D/resolver.cpp
|
hacdias/cp
|
5a8ffbb0a8819189fc4308917db2c59548af76c9
|
[
"MIT"
] | null | null | null |
ONI/qualification/17D/resolver.cpp
|
hacdias/cp
|
5a8ffbb0a8819189fc4308917db2c59548af76c9
|
[
"MIT"
] | null | null | null |
#include "avaliador.h"
#include "stdio.h"
#include "vector"
void luis(int N) {
string tentativa(N, '0');
int i = 0, wrong = adivinhar(tentativa);
for (i = 0; i < N; i++) {
if (wrong == 0) break;
tentativa[i] = '1';
if (adivinhar(tentativa) > wrong) {
tentativa[i] = '0';
} else {
wrong--;
}
}
}
vector<string> halfs;
void makeHalfs(string prefix, int n) {
if (n == 0) {
halfs.push_back(prefix);
return;
}
makeHalfs(prefix+'0', n-1);
makeHalfs(prefix+'1', n-1);
}
void vitor(int N) {
makeHalfs("", N);
int wrong = N;
unsigned int i = 0;
for(i=0; i < halfs.size() && wrong != 0; i++){
wrong = adivinhar(halfs[i]);
}
}
void resolver(int N, char C) {
if (C == 'L') {
return luis(N);
}
vitor(N);
}
| 15.245283
| 48
| 0.517327
|
hacdias
|
36a1963eccbaead70f29f8c9507497df0877636e
| 40,142
|
cpp
|
C++
|
mesh/Mesh.cpp
|
hsiaoairplane/3d-watermark-lsd
|
168df211b579fafc77a9bccba6ed54ae30a0ee23
|
[
"MIT"
] | 1
|
2018-07-20T02:44:11.000Z
|
2018-07-20T02:44:11.000Z
|
mesh/Mesh.cpp
|
hsiaoairplane/3d-watermark-lsd
|
168df211b579fafc77a9bccba6ed54ae30a0ee23
|
[
"MIT"
] | null | null | null |
mesh/Mesh.cpp
|
hsiaoairplane/3d-watermark-lsd
|
168df211b579fafc77a9bccba6ed54ae30a0ee23
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Mesh.h"
//#include "curvature_estimator.h"
#include <list>
#include <QFile>
#include <QString>
#include <q3cstring.h>
#include <QTextStream>
#include <QBuffer>
#include <omp.h>
const float Mesh::cm_colorWhite[3] = {0.95,0.95,0.95};
const float Mesh::cm_colorGray[3] = {0.5,0.5,0.5};
const float Mesh::cm_colorBlack[3] = {0.0,0.0,0.0};
Mesh::Mesh() :
//m_2dSearchStructure(NULL),
m_totalSurface(FLT_MAX)/*,
m_triangleSearch(NULL)*/
{
}
Mesh::~Mesh()
{
}
/*int Mesh::translatePart(int from, int to)
{
int count = 0;
for (Mesh::Facet_iterator it = facets_begin(); it!= facets_end(); ++it)
{
if (it->part() == from)
{
++count;
it->part(to);
}
}
return count;
}*/
double Mesh::computeTotalVolume()
{
vector<Point_3> points(3);
int index;
double totalVolume = 0.0;
Mesh::Facet_const_iterator fit = facets_begin();
Mesh::Facet_const_iterator fit_end = facets_end();
for (; fit != fit_end; fit++)
{
assert(fit->size() == 3);
index = 0;
Mesh::Halfedge_around_facet_const_circulator pHalfedge = fit->facet_begin();
Mesh::Halfedge_around_facet_const_circulator end = pHalfedge;
CGAL_For_all(pHalfedge, end)
{
points[index] = pHalfedge->vertex()->point();
index++;
}
double det = (points[1].x() - points[0].x()) * (points[2].y() - points[0].y()) - (points[2].x() - points[0].x()) * (points[1].y() - points[0].y());
double localVolume = (points[0].z() + points[1].z() + points[2].z()) * det;
totalVolume += localVolume;
}
return totalVolume;
}
void Mesh::computeTriangleArea()
{
double* edge_length = new double[3];
int index;
double sum;
for (Mesh::Facet_iterator fit = facets_begin(); fit != facets_end(); fit++)
{
assert(fit->size() == 3);
index = 0;
sum = 0;
Mesh::Halfedge_around_facet_circulator pHalfedge = fit->facet_begin();
Mesh::Halfedge_around_facet_circulator end = pHalfedge;
CGAL_For_all(pHalfedge,end)
{
sum += pHalfedge->length();
edge_length[index] = pHalfedge->length();
index++;
}
double s = sum / 2;
double ar = sqrt(s * (s - edge_length[0]) * (s - edge_length[1]) * (s - edge_length[2]));
fit->area(ar);
}
delete [] edge_length;
}
double Mesh::computeTriangleSurfaces()
{
m_totalSurface = 0.0;
for (Mesh::Facet_iterator it = facets_begin(); it != facets_end(); it++)
{
it->surface(sqrt(createTriangle(it->facet_begin()).squared_area()));
m_totalSurface += it->surface();
}
return m_totalSurface;
}
double Mesh::computeSurfaceTotal()
{
m_totalSurface = 0.0;
for (Mesh::Facet_iterator it = facets_begin(); it!= facets_end(); it++)
{
m_totalSurface += it->surface();
}
return m_totalSurface;
}
double Mesh::getSurfaceTotal()
{
return m_totalSurface;
}
void Mesh::compute2dSearchStructure()
{
//if (m_2dSearchStructure) return;
std::vector<Point_2_With_Vertex> points;
points.reserve(size_of_vertices());
NT_d p[2];
for(Mesh::Vertex_iterator it = vertices_begin();
it != vertices_end();
it++)
{
if (it->vertex_begin() != NULL) {
p[0] = it->point().x();
p[1] = it->point().y();
Point_2_With_Vertex pwv(2, p, p+2);
pwv.handle = it;
points.push_back(pwv);
}
}
//m_2dSearchStructure = new KDTree(points.begin(),points.end());
}
/*void Mesh::compute2dSearchStructure()
{
m_2dSearchStructure = new Enriched_point_set_2;
std::ofstream f("c:/temp/compute2d.txt");
f << "Computing 2d search structure on mesh with " << size_of_vertices() << std::endl << std::endl;
//fill search structure
int i=0;
for (Vertex_iterator it = vertices_begin(); it != vertices_end(); it++) {
Enriched_kernel::Point_2 p(it->point().x(), it->point().y());
f << "[" << i << "] Adding " <<
it->index() << " at point " <<
p[0] << "," << p[1];
Enriched_point_set_2::Vertex_handle p_vertex = m_2dSearchStructure->insert(p);
assert(p_vertex != NULL);
f << ", Is vertex handle null? " << (p_vertex == NULL) << std::endl;
if (p_vertex != NULL && it->index() >= 0) p_vertex->info() = it;
i++;
}
f << "=============================================" << std::endl;
f.close();
}*/
bool Mesh::findClosestOnMesh(
Enriched_kernel::Point_2 p,
Enriched_Mesh::Vertex_handle& closestVertex,
Enriched_Mesh::Facet_handle& containingFacet)
{
/*assert(m_2dSearchStructure != NULL);
NT_d p2[2]; p2[0] = p[0]; p2[1] = p[1];
Point_2_With_Vertex queryPoint(2,p2,p2+2);
std::vector<KDNeighborSearch::Point_with_distance> nearestNeighbors;
KDNeighborSearch searcher(
*m_2dSearchStructure, //kd-tree
queryPoint, //point to look for
KDEuclideanDistance(), //search type
6 );//number of query points
searcher.the_k_neighbors(std::back_inserter(nearestNeighbors));
bool foundContainingFacet = false;
for (int i=0; i<nearestNeighbors.size(); i++)
{
Vertex_handle v = nearestNeighbors[i].first->handle;
//for debug reasons
if (i==0) closestVertex = v;
Halfedge_around_vertex_circulator c = v->vertex_begin();
if (c != NULL ) do {
Enriched_kernel::Triangle_2 t = createTriangle2(c);
//if (t.orientation() == CGAL::RIGHT_TURN) t = t.opposite();
if (t.has_on_bounded_side(p) || t.has_on_boundary(p)) {
foundContainingFacet = true;
containingFacet = c->facet();
break;
}
} while (++c != v->vertex_begin());
if (foundContainingFacet) break;
}
if (foundContainingFacet) {
Point_3 p3(p[0],p[1],0.0);
float vdistance = FLT_MAX;
Halfedge_around_facet_circulator c = containingFacet->facet_begin();
do {
Enriched_kernel::Segment_3 s(p3, c->vertex()->point());
if (s.squared_length() < vdistance) {
vdistance = s.squared_length();
closestVertex = c->vertex();
}
} while (++c != containingFacet->facet_begin());
return true;
} else {
return false;
} */
return false;
}
/*bool Mesh::findClosestOnMesh(
Enriched_kernel::Point_3 p,
Enriched_Mesh::Vertex_handle& closestVertex,
Enriched_Mesh::Facet_handle& containingFacet)
{
assert(m_2dSearchStructure != NULL);
Enriched_kernel::Point_2 p2(p.x(),p.y());
std::list<Enriched_point_set_2::Vertex_handle> closest;
m_2dSearchStructure->nearest_neighbors(p2, 3, std::back_inserter(closest));
bool foundContainingFacet = false;
do {
Vertex_handle v = closest.front()->info();
closest.pop_front();
Halfedge_around_vertex_circulator c = v->vertex_begin();
do {
Enriched_kernel::Triangle_3 t = createTriangle(c);
if (t.has_on(p)) {
foundContainingFacet = true;
containingFacet = c->facet();
break;
}
} while (++c != v->vertex_begin());
} while (closest.size() > 0 && !foundContainingFacet);
if (foundContainingFacet) {
float vdistance = FLT_MAX;
Halfedge_around_facet_circulator c = containingFacet->facet_begin();
do {
Enriched_kernel::Segment_3 s(p, c->vertex()->point());
if (s.squared_length() < vdistance) {
vdistance = s.squared_length();
closestVertex = c->vertex();
}
} while (++c != containingFacet->facet_begin());
return true;
} else {
return false;
}
}*/
Enriched_kernel::Triangle_3 Mesh::createTriangle(const Mesh::Halfedge_handle& h)
{
if (h == NULL) {
return Enriched_kernel::Triangle_3();
}
Enriched_kernel::Triangle_3 t(
h->vertex()->point(),
h->next()->vertex()->point(),
h->next()->next()->vertex()->point());
return t;
}
Enriched_kernel::Triangle_2 Mesh::createTriangle2(const Mesh::Halfedge_handle& h)
{
Enriched_kernel::Point_2 p1(h->vertex()->point().x(),h->vertex()->point().y());
Enriched_kernel::Point_2 p2(h->next()->vertex()->point().x(),
h->next()->vertex()->point().y());
Enriched_kernel::Point_2 p3(h->next()->next()->vertex()->point().x(),
h->next()->next()->vertex()->point().y());
Enriched_kernel::Triangle_2 t(p1,p2,p3);
return t;
}
void Mesh::computeVertexFastindex()
{
if (m_fastIndexMap.size()) m_fastIndexMap.clear();
m_fastIndexMap.reserve(size_of_vertices());
for (Vertex_iterator it = vertices_begin(); it != vertices_end(); it++)
{
m_fastIndexMap.push_back(it);
}
}
void Mesh::computeFacetFastindex()
{
//if (m_fastFacetMap) return;
if (m_fastFacetMap.size()) m_fastFacetMap.clear();
int facetTag = 0;
m_fastFacetMap.reserve(size_of_facets());
for (Facet_iterator it = facets_begin(); it != facets_end(); it++) {
it->index(facetTag);
m_fastFacetMap.push_back(it);
facetTag++;
}
}
Enriched_Mesh::Vertex_handle Mesh::findVertex(const int index)
{
assert(m_fastIndexMap);
if (!m_fastIndexMap.size()) computeVertexFastindex();
if (index<0 || index>=m_fastIndexMap.size()) return Enriched_Mesh::Vertex_handle();
return m_fastIndexMap[index];
}
Enriched_Mesh::Facet_handle Mesh::findFacet(const int index)
{
assert(m_fastFacetMap);
if (!m_fastFacetMap.size()) computeFacetFastindex();
if (index<0 || index>=m_fastFacetMap.size()) return Enriched_Mesh::Facet_handle();
return m_fastFacetMap[index];
}
void Mesh::computeBoundingBox()
{
Enriched_kernel::FT xmin,xmax,ymin,ymax,zmin,zmax;
Enriched_Mesh::computeBoundingBox(xmin, xmax, ymin, ymax, zmin, zmax);
/*printf("xmax: %f\n", xmax);
printf("ymax: %f\n", ymax);
printf("zmax: %f\n", zmax);
printf("xmin: %f\n", xmin);
printf("ymin: %f\n", ymin);
printf("zmin: %f\n", zmin);*/
}
double Mesh::diagonalLength()
{
Enriched_kernel::FT xmin,xmax,ymin,ymax,zmin,zmax;
Enriched_Mesh::computeBoundingBox(xmin,xmax,ymin,ymax,zmin,zmax);
Point_3 m(xmin, ymin, zmin);
Point_3 M(xmax, ymax, zmax);
Vector_3 diag(m,M);
return sqrt(diag*diag);
}
Point_3 Mesh::centerOfMass()
{
Point_3 centerOfMass(0,0,0);
for (Mesh::Vertex_iterator v = this->vertices_begin();
v != this->vertices_end();
v++)
{
centerOfMass = centerOfMass + (v->point() - CGAL::ORIGIN);
}
unsigned int size = this->size_of_vertices();
m_computedCenterOfMass = Point_3(centerOfMass.x()/size, centerOfMass.y()/size, centerOfMass.z()/size);
return m_computedCenterOfMass;
}
Point_3 Mesh::polyCenterOfMass()
{
double c[3] = { 0.0, 0.0, 0.0 };
double centerWeight = 0.0;
for ( Mesh::Facet_iterator f = this->facets_begin(); f != this->facets_end(); ++f)
{
//Mesh::Facet_handle f = mesh->findFacet(m_facets[i]);
Mesh::Point_3 fcenter;
compute_facet_center(f, fcenter);
double facetSurface = f->surface();
c[0] += fcenter.x() * facetSurface;
c[1] += fcenter.y() * facetSurface;
c[2] += fcenter.z() * facetSurface;
centerWeight += facetSurface;
}
c[0] /= centerWeight;
c[1] /= centerWeight;
c[2] /= centerWeight;
return Mesh::Point_3(c[0], c[1], c[2]);
}
void Mesh::translate(const Vector_3& translateTo)
{
Enriched_kernel::Aff_transformation_3 transformation(CGAL::TRANSLATION, translateTo);
this->transform(transformation);
}
void Mesh::scale(const double& scaleBy)
{
Enriched_kernel::Aff_transformation_3 transformation(CGAL::SCALING, scaleBy);
this->transform(transformation);
}
void Mesh::transform(const Enriched_kernel::Aff_transformation_3 &transformation)
{
for (Mesh::Vertex_iterator ivertex = this->vertices_begin(); ivertex != this->vertices_end(); ivertex++)
{
ivertex->point() = ivertex->point().transform(transformation);
}
}
/*void Mesh::estimateCurvature()
{
std::cerr << "Estimate curvature tensor...";
double start = clock();
typedef CCurvature_estimator<typename Mesh,Enriched_kernel> Estimator;
Estimator estimator(this);
estimator.run(Estimator::ONE_RING);
double duration = (double)((clock()-start)/CLOCKS_PER_SEC);
std::cerr << "Estimate curvature tensor...done " << duration << " seconds" << std::endl;
}*/
Mesh::Vertex_handle Mesh::splitEdge(Mesh::Halfedge_handle h)
{
Point_3 p1 = h->vertex()->point();
Point_3 p2 = h->opposite()->vertex()->point();
Point_3 center((p1.x() + p2.x())/2,
(p1.y() + p2.y())/2,
(p1.z() + p2.z())/2);
//delete edge h
Mesh::Halfedge_handle g = this->join_facet(h);
//create a center vertex
g = this->create_center_vertex(g);
g->vertex()->point() = center;
return g->vertex();
}
void Mesh::splitEdges(std::vector<Mesh::Halfedge_handle> &halfEdges)
{
for (std::vector<Mesh::Halfedge_handle>::iterator it = halfEdges.begin();
it != halfEdges.end();
it++)
{
splitEdge(*it);
}
#ifdef _DEBUG
//check that all facets are of size 3
for ( Mesh::Facet_iterator f = this->facets_begin(); f != this->facets_end(); ++f){
//all facets must be of size 3
CGAL_assertion( f->size() == 3);
}
#endif
}
Mesh::Halfedge_handle Mesh::flipEdge(Mesh::Halfedge_handle h)
{
h = this->join_facet(h);
return this->split_facet(h->prev(), h->next());
}
void Mesh::flipEdges(std::vector<Mesh::Halfedge_handle> &halfEdges)
{
std::cout << "flipping " << halfEdges.size() << " edges"<<std::endl;
for (std::vector<Mesh::Halfedge_handle>::iterator it = halfEdges.begin();
it != halfEdges.end();
it++)
{
flipEdge(*it);
}
#ifdef _DEBUG
//check that all facets are of size 3
for ( Mesh::Facet_iterator f = this->facets_begin(); f != this->facets_end(); ++f){
//all facets must be of size 3
CGAL_assertion( f->size() == 3);
}
#endif
}
void Mesh::flipLongEdges()
{
//naive (slow) implementation
int flipCount = 0;
Mesh::Halfedge_handle edgeToFlip;
do
{
edgeToFlip = NULL;
double longest = 0;
for (Mesh::Edge_iterator h = this->edges_begin();
h != this->edges_end();
h++)
{
if (h->vertex()->degree() < 3
||
h->opposite()->vertex()->degree() < 3)
continue;
double edgeLenSquared = edgeLengthSquared(h);
if (edgeLenSquared > longest)
{
Vector_3 altVec = h->next()->vertex()->point() - h->opposite()->next()->vertex()->point();
double alternativeEdgeLenSquared = altVec*altVec;
if (edgeLenSquared > alternativeEdgeLenSquared)
{
longest = edgeLenSquared;
edgeToFlip = h;
}
}
}
if (edgeToFlip != NULL)
{
flipEdge(edgeToFlip);
flipCount++;
}
}
while(edgeToFlip != NULL);;
std::cerr << "flipped "<<flipCount<<" edges"<<std::endl;
}
void Mesh::flipEdgesAroundSmallTriangles()
{
//naive (slow) implementation
int flipCount = 0;
Mesh::Halfedge_handle edgeToFlip;
do
{
edgeToFlip = NULL;
double best = 0;
for (Mesh::Edge_iterator h = this->edges_begin();
h != this->edges_end();
h++)
{
if (h->vertex()->degree() < 3
||
h->opposite()->vertex()->degree() < 3)
continue;
Point_3 a = h->vertex()->point();
Point_3 b = h->next()->vertex()->point();
Point_3 c = h->opposite()->vertex()->point();
Point_3 d = h->opposite()->next()->vertex()->point();
Triangle_3 existing1(a,b,c);
Triangle_3 existing2(a,c,d);
double area1 = existing1.squared_area();
double area2 = existing2.squared_area();
double ratio1 = qMin(area1, area2) / qMax(area1,area2);
if (ratio1 > 0.1)
continue;
Triangle_3 alternative1(b,d,a);
Triangle_3 alternative2(b,d,c);
area1 = alternative1.squared_area();
area2 = alternative2.squared_area();
double ratio2 = qMin(area1, area2) / qMax(area1,area2);
if (ratio2 > ratio1 && (ratio2 * ratio1) > best)
{
best = ratio2 * ratio1;
edgeToFlip = h;
}
}
if (edgeToFlip != NULL)
{
flipEdge(edgeToFlip);
flipCount++;
}
}
while(edgeToFlip != NULL);;
std::cerr << "flipped "<<flipCount<<" edges"<<std::endl;
}
double maxAngleInTriangle(const Point_3 &a, const Point_3 &b, const Point_3 &c)
{
double ab = sqrt((b-a).squared_length());
double ac = sqrt((c-a).squared_length());
double bc = sqrt((b-c).squared_length());
double a1 = (b-a)*(c-a) / (ab*ac);
double a2 = (c-b)*(a-b) / (bc*ab);
double a3 = (a-c)*(b-c) / (ac*bc);
double angle = qMin(a1, qMin(a2,a3));
return angle;
}
void Mesh::flipEdgesAroundBigAngledTriangles()
{
//naive (slow) implementation
int flipCount = 0;
Mesh::Halfedge_handle edgeToFlip;
do
{
edgeToFlip = NULL;
double best = 0;
for (Mesh::Edge_iterator h = this->edges_begin();
h != this->edges_end();
h++)
{
if (h->vertex()->degree() < 3
||
h->opposite()->vertex()->degree() < 3)
continue;
Point_3 a = h->vertex()->point();
Point_3 b = h->next()->vertex()->point();
Point_3 c = h->opposite()->vertex()->point();
Point_3 d = h->opposite()->next()->vertex()->point();
double mAngle1 = maxAngleInTriangle(a,b,c);
double mAngle2 = maxAngleInTriangle(a,c,d);
//min, because we work with the cosine of the angle
double maxAngle = qMin(mAngle1, mAngle2);
mAngle1 = maxAngleInTriangle(a,b,d);
mAngle2 = maxAngleInTriangle(c,d,b);
if ((b-c)*(d-c) < 0
||
(b-a)*(d-a) < 0)
continue;
//min, because we work with the cosine of the angle
double maxAlternativeAngle = qMin(mAngle1, mAngle2);
if (maxAlternativeAngle > maxAngle)
{
edgeToFlip = h;
break;
}
}
if (edgeToFlip != NULL)
{
flipEdge(edgeToFlip);
flipCount++;
}
}
while(edgeToFlip != NULL);;
std::cerr << "flipped "<<flipCount<<" edges"<<std::endl;
}
double Mesh::edgeLengthSquared(Mesh::Halfedge_handle halfedge)
{
Vector_3 vec = halfedge->vertex()->point() - halfedge->prev()->vertex()->point();
return vec*vec;
}
void Mesh::triangulateFacet(Mesh::Facet_handle facet)
{
unsigned int facetSize = facet->size();
if (facetSize < 4)
return;
Mesh::Halfedge_handle splitStart = NULL, splitEnd = NULL;
Mesh::Halfedge_handle hStart = facet->halfedge();
Mesh::Halfedge_handle h = hStart;
float best = -1;
do
{
Mesh::Halfedge_handle g = h->next();
do
{
if (
g != h->next()
&&
h != g->next()
)
{
Enriched_kernel::Vector_3 dVec = g->vertex()->point() - h->vertex()->point();
float d = dVec*dVec;
//avoid illegal triangulations
bool illegalTriangulation = false;
if (g == h->next()->next()
&&
h->next()->opposite()->facet() == g->opposite()->facet())
illegalTriangulation = true;
else
if (h == g->next()->next()
&&
g->next()->opposite()->facet() == h->opposite()->facet())
illegalTriangulation = true;
else
if (h->vertex() == g->vertex())
illegalTriangulation = true;
if (!illegalTriangulation && (best == -1 || best > d))
{
splitStart = h;
splitEnd = g;
best = d;
}
}
g = g->next();
}
while (g != h);
h = h->next();
}
while (h != hStart);
if (best == -1)
{
//there is no way to triangulate the polygon, so add a center vertex instead
//find average of neighbouring vertices
float x=0,y=0,z=0;
Mesh::Halfedge_handle g = hStart;
do
{
Enriched_kernel::Point_3 p = g->vertex()->point();
x += p.x();
y += p.y();
z += p.z();
g = g->next();
}while (g != hStart);
Enriched_kernel::Point_3 center(x/facetSize,y/facetSize,z/facetSize);
//re-create a center vertex at middle of the polygon
g = this->create_center_vertex(hStart);
g->vertex()->point() = center;
}
else
{
Mesh::Halfedge_handle splitter = this->split_facet(splitStart, splitEnd);
Mesh::Halfedge_handle splitterOp = splitter->opposite();
triangulateFacet(splitter->facet());
triangulateFacet(splitterOp->facet());
}
}
void Mesh::removeVertex(Mesh::Vertex_handle vertex)
{
Mesh::Halfedge_handle h = vertex->halfedge();
Mesh::Halfedge_handle g = this->erase_center_vertex(h);
triangulateFacet(g->facet());
}
void Mesh::removeVertices(std::vector<Mesh::Vertex_handle> &vertices)
{
std::cout << "removing " << vertices.size() << " vertices" << std::endl;
for (unsigned int i=0; i<vertices.size(); i++)
{
removeVertex(vertices[i]);
}
#ifdef _DEBUG
//sanity checks
//check that all facets are of size 3
for ( Mesh::Facet_iterator f = this->facets_begin(); f != this->facets_end(); ++f){
//all facets must be of size 3
CGAL_assertion( f->size() == 3);
}
for ( Mesh::Vertex_iterator v = this->vertices_begin(); v != this->vertices_end(); ++v){
//all vertices must be of degree 3 or more
CGAL_assertion( v->degree() >= 3);
}
#endif
}
void Mesh::splitEdgesLongerThan(const double maxEdgeLength)
{
double M = maxEdgeLength * maxEdgeLength;
Mesh::Halfedge_handle best;
do{
//find the longest edge
double bestM = M;
best = NULL;
for ( Mesh::Edge_iterator h = this->edges_begin(); h != this->edges_end(); ++h)
{
//meet facet-join preconditions
if (h->vertex()->degree() < 3
||
h->opposite()->vertex()->degree() < 3)
continue;
double hVecLen = edgeLengthSquared(h);
if (hVecLen > bestM)
{
bestM = hVecLen;
best = h;
}
}
//split the longest edge (if found) - by adding a vertex t its center
if (best != NULL)
{
Enriched_kernel::Point_3 p1 = best->vertex()->point();
Enriched_kernel::Point_3 p2 = best->opposite()->vertex()->point();
Enriched_kernel::Point_3 center((p1.x() + p2.x())/2,
(p1.y() + p2.y())/2,
(p1.z() + p2.z())/2);
//delete edge h
Mesh::Halfedge_handle g = this->join_facet(best);
//create a center vertex
g = this->create_center_vertex(g);
g->vertex()->point() = center;
}
} while (best != NULL); //continue until no long edge is found
/* double len2 = len*len;
std::vector<Mesh::Halfedge_handle> edgesToSplit;
do
{
edgesToSplit.clear();
for (Mesh::Halfedge_iterator h = this->halfedges_begin();
h != this->halfedges_end();
h++)
{
//measure edge length
Vector_3 vec(h->vertex()->point(), h->prev()->vertex()->point());
int edgeLen = vec*vec;
//add the edge into the list
if (edgeLen > len2)
edgesToSplit.push_back(h);
}
splitEdges(edgesToSplit);
}
while (edgesToSplit.size() > 0);*/
}
void Mesh::createTetrahedron(const double radius, const Point_3 center)
{
double r = radius / 1.73205;
Point_3 a( r, r, r );
Point_3 b( -r, r, -r);
Point_3 c( -r, -r, r);
Point_3 d( r, -r, -r);
this->make_tetrahedron(a,b,c,d);
this->translate(center - CGAL::ORIGIN);
}
void Mesh::createCube(const double radius, const Point_3 center)
{
createSphere(radius, 1, center);
}
void Mesh::createSphere(const double radius, const unsigned int subDivisions, const Point_3 center)
{
createTetrahedron(radius);
std::vector<Mesh::Facet_handle> facetsToSubDiv;
std::vector<Mesh::Halfedge_handle> edgesToFlip;
for (unsigned int level = 0; level < subDivisions; level++)
{
facetsToSubDiv.clear();
edgesToFlip.clear();
//must put all faces into a vector
for (Mesh::Facet_iterator f = this->facets_begin();
f != this->facets_end();
f++)
facetsToSubDiv.push_back(f);
for (Mesh::Edge_iterator h = this->edges_begin();
h != this->edges_end();
h++)
edgesToFlip.push_back(h);
for (unsigned int i=0; i<facetsToSubDiv.size(); i++)
{
Mesh::Facet_handle f = facetsToSubDiv[i];
Point_3 center;
this->compute_facet_center(f,center);
Vector_3 rad(CGAL::ORIGIN, center);
double radLen = sqrt(rad*rad);
rad = radius * rad / radLen;
Mesh::Halfedge_handle h = f->halfedge();
Mesh::Halfedge_handle g = this->create_center_vertex(h);
g->vertex()->point() = CGAL::ORIGIN + rad;
}
flipEdges(edgesToFlip);
}
this->translate(center - CGAL::ORIGIN);
}
void Mesh::computeVolumeRangeOnFacets(double& minVal, double& maxVal)
{
minVal = FLT_MAX;
maxVal = -FLT_MAX;
Mesh::Facet_const_iterator it = facets_begin();
Mesh::Facet_const_iterator it_end = facets_end();
for (;it != it_end; it++)
{
if (it->volumeSDF()<minVal) minVal = it->volumeSDF();
if (it->volumeSDF()>maxVal) maxVal = it->volumeSDF();
}
}
void Mesh::averageVolume()
{
std::vector<double> avgVolume;
avgVolume.reserve(size_of_vertices());
for (Mesh::Vertex_iterator it = vertices_begin(); it != vertices_end(); it++)
{
Mesh::Halfedge_around_vertex_circulator c = it->vertex_begin();
double avg = 0;
double weights = 0.0;
do {
double weight = c->length();
weights += weight;
avg += weight * c->opposite()->vertex()->volumeSDF();
} while (++c != it->vertex_begin());
avg /= weights;
avg = (avg + it->volumeSDF()) / 2;
avgVolume.push_back(avg);
}
int index = 0;
for (Mesh::Vertex_iterator it = vertices_begin(); it != vertices_end(); it++)
{
it->volumeSDF(avgVolume[index]);
index++;
}
}
void Mesh::fillNormalizedFacetVolume()
{
const static float logModifier = 4.0;
const static double mulBy = 1 / logf(logModifier+1);
double minVolume = FLT_MAX;
double maxVolume = 0.0;
Mesh::Facet_iterator fit = facets_begin();
Mesh::Facet_iterator fit_end = facets_end();
for (; fit != fit_end; fit++)
{
if (fit->volumeSDF() < minVolume)
minVolume = fit->volumeSDF();
if (fit->volumeSDF() > maxVolume)
maxVolume = fit->volumeSDF();
}
//double range = (double) 1 / (maxVolume - minVolume);
double range = (double) 1 / computeTotalVolume();
fit = facets_begin();
for (; fit != fit_end; fit++)
{
float nvolume = (fit->volumeSDF() - minVolume) * range;
//nvolume = logf(nvolume * logModifier + 1) * mulBy;
fit->volumeNSDF() = nvolume;
}
}
void Mesh::fillNormalizedVertexVolume()
{
const float logModifier = 4.0;
const double mulBy = 1 / logf(logModifier+1);
double minVolume = FLT_MAX;
double maxVolume = 0.0;
Mesh::Vertex_iterator vit = vertices_begin();
Mesh::Vertex_iterator vit_end = vertices_end();
for (; vit != vit_end; vit++)
{
if (vit->volumeSDF() < minVolume) minVolume = vit->volumeSDF();
if (vit->volumeSDF() > maxVolume) maxVolume = vit->volumeSDF();
}
double range = (double) 1 / maxVolume;
//double range = (double) 1 / (maxVolume - minVolume);
//double range = (double) 1 / computeTotalVolume();
vit = vertices_begin();
for (; vit != vit_end; vit++)
{
double nvolume = vit->volumeSDF() * range;
//float nvolume = (vit->volumeSDF() - minVolume) * range;
//nvolume = logf(nvolume * logModifier + 1) * mulBy;
vit->volumeNSDF() = nvolume;
}
}
void Mesh::smoothVolume(const bool anisotropic, const float windowSize, const int iterations)
{
const static float reduced_weight = 0.3;
Mesh::Facet_iterator fit = facets_begin();
Mesh::Facet_iterator fit_end = facets_end();
for (; fit != fit_end; fit++)
{
double initialValue = fit->volumeSDF();
double initialNValue = fit->volumeNSDF();
for (int i=0;i<iterations;i++)
{
double smoothedValue = initialValue;
double smoothedNValue = initialNValue;
double weights = (initialValue==0.0 ? 0.0 : 1.0);
Mesh::Halfedge_around_facet_circulator c = fit->facet_begin();
do {
if (c->opposite()->facet() != NULL)
{
double sneighborVolume = c->opposite()->facet()->volumeSDF();
double sneighborNVolume = c->opposite()->facet()->volumeNSDF();
if ( !anisotropic || (sneighborNVolume - initialNValue) < windowSize)
{
smoothedValue += sneighborVolume * reduced_weight;
smoothedNValue += sneighborNVolume * reduced_weight;
weights += reduced_weight;
}
}
} while (++c != fit->facet_begin());
//fit->volumeSDF(safeDiv(smoothedValue, weights));
fit->volumeNSDF(safeDiv(smoothedNValue, weights));
initialValue = fit->volumeSDF();
initialNValue = fit->volumeNSDF();
}
}
}
Enriched_kernel::Segment_3 shortenRay(
const Enriched_kernel::Segment_3& ray,
const float distance)
{
Enriched_kernel::Vector_3 v = ray.to_vector();
v = v * 1/sqrt(v*v);
Enriched_kernel::Segment_3 s(ray[0], ray[0] + v * distance);
return s;
}
void Mesh::fillHoles()
{
//find one hole:
Mesh::Halfedge_handle holeEdge;
do
{
holeEdge = NULL;
Mesh::Halfedge_iterator h = this->halfedges_begin();
while (h != this->halfedges_end() && holeEdge == NULL)
{
if (h->facet() == NULL && h->is_border())
holeEdge = h;
h++;
}
//fill the hole
if (holeEdge != NULL)
{
holeEdge = this->fill_hole(holeEdge);
std::cerr << "filling hole of size "<<holeEdge->facet()->size()<<std::endl;
this->triangulateFacet(holeEdge->facet());
}
}
while (holeEdge != NULL); //repeat until no holes found
}
// superimpose vertices
void Mesh::superimpose_vertices()
{
::glBegin(GL_POINTS);
for(Point_iterator pPoint = points_begin();
pPoint != points_end();
pPoint++)
::glVertex3d(pPoint->x(),pPoint->y(),pPoint->z());
::glEnd(); // // end point assembly
}
// superimpose vertices
void Mesh::superimpose_spheres(double scale)
{
/*GLUquadricObj* pQuadric = gluNewQuadric();
::glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
for(Vertex_iterator pVertex = vertices_begin();
pVertex != vertices_end();
pVertex++)
{
if (m_renderingParams->m_renderModeVertices ==
RenderingParamsManager::RENDER_VERTICES_IMPORTANCE_ONLY &&
!pVertex->important())
continue;
if (!m_renderingParams->m_displayFiller && pVertex->index()==-1)
continue;
::glPushMatrix();
double radius = average_edge_length_around(pVertex);
::glTranslated(pVertex->point().x(),
pVertex->point().y(),
pVertex->point().z());
setSphereColor(pVertex);
::gluSphere(pQuadric,scale*radius*2,10,10);
::glPopMatrix();
}
gluDeleteQuadric(pQuadric);*/
}
// superimpose edges
void Mesh::superimpose_edges(
bool skip_ordinary_edges,
bool skip_control_edges,
bool voronoi_edge)
{
/*if (m_renderingParams->m_renderModeEdges == RenderingParamsManager::RENDER_EDGES_NONE)
::glBegin(GL_LINES);
for(Edge_iterator h = edges_begin();
h != edges_end();
h++)
{
// ignore this edges
if(skip_ordinary_edges && !h->control_edge())
continue;
// ignore control edges
if(skip_control_edges && h->control_edge())
continue;
if (m_renderingParams->m_renderModeEdges == RenderingParamsManager::RENDER_EDGES_ONLY_BOUNDARY &&
!h->is_border_edge())
{
continue;
}
if (m_renderingParams->m_renderModeEdges == RenderingParamsManager::RENDER_EDGES_CLUSTER_SEPERATION &&
((h->facet() != NULL && h->opposite()->facet() != NULL &&
h->facet()->cluster() == h->opposite()->facet()->cluster()) ||
(h->facet() == NULL || h->opposite()->facet() == NULL)
))
{
continue;
}
//ignore filler edges if setting is so...
if (!m_renderingParams->m_displayFiller &&
(h->vertex()->index() == -1 ||
h->opposite()->vertex()->index() == -1))
{
continue;
}
// assembly and draw line segment
if (m_renderingParams->m_renderModeEdges != RenderingParamsManager::RENDER_EDGES_NONE) {
setEdgeColor(h);
glBegin(GL_LINES);
}
const Point& p1 = h->prev()->vertex()->point();
const Point& p2 = h->vertex()->point();
::glVertex3d(p1[0],p1[1],p1[2]);
::glVertex3d(p2[0],p2[1],p2[2]);
if (m_renderingParams->m_renderModeEdges != RenderingParamsManager::RENDER_EDGES_NONE)
glEnd();
}
if (m_renderingParams->m_renderModeEdges == RenderingParamsManager::RENDER_EDGES_NONE)
::glEnd();*/
}
//draw facet
void Mesh::gl_draw_facet(Facet_handle pFacet,
bool smooth_shading,
bool use_normals)
{
/*
// one normal per face
if(use_normals && !smooth_shading)
{
const Facet::Normal_3& normal = pFacet->normal();
::glNormal3d(normal[0],normal[1],normal[2]);
}
bool highlightFacet = true;
bool fillerFacet = false;
int vcount = 0;
Halfedge_around_facet_circulator pHalfedge = pFacet->facet_begin();
if (pHalfedge != NULL)
do {
vcount++;
if (m_renderingParams->m_renderModeFacets == RenderingParamsManager::RENDER_FACETS_HIGHLIGHT_PATCH &&
pHalfedge->vertex()->distance() == FLT_MAX)
{
highlightFacet = false;
}
if (pHalfedge->vertex()->index() == -1)
fillerFacet = true;
} while(++pHalfedge != pFacet->facet_begin());
if (!m_renderingParams->m_displayFiller && fillerFacet)
return;
bool useGray = false;
if (m_renderingParams->m_renderModeFacets == RenderingParamsManager::RENDER_FACETS_DIFFERENCE_DISTANCE ||
m_renderingParams->m_renderModeFacets == RenderingParamsManager::RENDER_FACETS_TRIANGLE_ERROR)
useGray = true;
if (m_renderingParams->m_renderModeFacets == RenderingParamsManager::RENDER_FACETS_HIGHLIGHT_PATCH) {
if (highlightFacet) {
glColor3f(0.7,0.7,0.5);
} else {
glColor3ubv(m_renderingParams->m_meshColor);
}
}
pHalfedge = pFacet->facet_begin();
if (pHalfedge != NULL) do
{
// one normal per vertex
if(use_normals && smooth_shading)
{
const Facet::Normal_3& normal = pHalfedge->vertex()->normal();
::glNormal3d(normal[0],normal[1],normal[2]);
}
// polygon assembly is performed per vertex
const Point& point = pHalfedge->vertex()->point();
setFacetVertexColor(pFacet, pHalfedge, fillerFacet, vcount, useGray, painter);
::glVertex3d(point[0],point[1],point[2]);
}
while(++pHalfedge != pFacet->facet_begin());
*/
}
// draw using OpenGL commands (display lists)
void Mesh::gl_draw(
bool smooth_shading,
bool use_normals)
{
/*
Facet_iterator pFacet = facets_begin();
//find correct painter
int color[3];
FacetPainter* painter = NULL;
for (int i=0; i<m_facetPainters.size(); i++)
{
if (m_facetPainters[i]->queryColor(pFacet, pFacet->halfedge(), m_renderingParams->m_renderModeFacets, color) != -999)
{
painter = m_facetPainters[i];
break;
}
}
// draw polygons
for(;pFacet != facets_end();pFacet++)
{
// begin polygon assembly
::glBegin(GL_POLYGON);
gl_draw_facet(pFacet,smooth_shading,use_normals, painter);
::glEnd(); // end polygon assembly
}
glFlush();
*/
}
void Mesh::setIndexVertices()
{
int index = 0;
for(Vertex_iterator pVertex = vertices_begin();
pVertex != vertices_end();
pVertex++)
{
if (pVertex->index() >= 0)
pVertex->tag(index++);
}
}
void Mesh::writePatch(
const char *pFilename,
std::set<Halfedge_handle, HalfedgeCompare>& seamTree,
int seamLoops,
int saveMode /* = SAVEMODE_COMPLETE */,
bool saveFillerVertices /* = false */,
bool saveDebugInfo /* = false */)
{
std::ofstream stream(pFilename);
stream << saveMode << std::endl;
stream << m_radius << std::endl;
switch(saveMode) {
case SAVEMODE_COMPLETE:
stream << size_of_vertices() << ' ' << size_of_facets() << std::endl;
break;
case SAVEMODE_MINIMAL:
writeMinimalPatch(stream, seamTree, seamLoops, saveDebugInfo);
stream.close();
return;
break;
case SAVEMODE_NOCONNECTIVITY:
stream << size_of_vertices() << ' ' << size_of_facets() << std::endl;
break;
}
// output vertices
for(Vertex_iterator pVertex = vertices_begin();
pVertex != vertices_end();
pVertex++)
{
if (saveFillerVertices || pVertex->index() >= 0) {
const Point_3 p = pVertex->point();
stream << 'v' << ' ' << p.x() << ' ' <<
p.y() << ' ' <<
pVertex->index();
if (saveDebugInfo) {
stream << ' ' << pVertex->distance();
}
stream << std::endl;
}
}
// precompute vertex indices
this->setIndexVertices();
// output facets
for(Facet_iterator pFacet = facets_begin(); pFacet != facets_end(); pFacet++)
{
bool fillerFacet = false;
QString s("f");
Halfedge_around_facet_circulator pHalfedge = pFacet->facet_begin();
do {
s += " " + QString::number(pHalfedge->vertex()->tag());
if (!saveFillerVertices && pHalfedge->vertex()->index() == -1) {
fillerFacet = true;
break;
}
} while(++pHalfedge != pFacet->facet_begin());
if (!fillerFacet) {
stream << std::string(s.toAscii()) << std::endl;
}
}
stream.close();
}
void Mesh::writeMinimalPatch(
std::ofstream& stream,
halfedgeSet_t& seamTree,
int seamLoops,
bool saveDebugInfo)
{
std::map<int, float> index_distanceMap;
if (seamLoops == 1 && seamTree.size() == 0) {
for (Halfedge_iterator pHalfedge = border_halfedges_begin();
pHalfedge != halfedges_end();
pHalfedge++)
{
seamTree.insert(pHalfedge);
}
}
//save all unique indexes
for(Vertex_iterator pVertex = vertices_begin();
pVertex != vertices_end();
pVertex++)
{
if (pVertex->index() != -1)
index_distanceMap.insert(std::pair<int, float>(pVertex->index(), pVertex->distance()));
}
std::set<int> indexesOnBorderSet;
for (halfedgeSet_t::iterator it = seamTree.begin(); it != seamTree.end(); it++) {
indexesOnBorderSet.insert((*it)->vertex()->index());
indexesOnBorderSet.insert((*it)->opposite()->vertex()->index());
}
stream << index_distanceMap.size();
if (seamLoops != 1)
stream << ' ' << seamTree.size() << std::endl;
else
stream << " 0" << std::endl;
for (std::map<int, float>::iterator it = index_distanceMap.begin();
it!= index_distanceMap.end();
it++)
{
stream /*<< "v "*/ << it->first;
if (
indexesOnBorderSet.find(it->first) != indexesOnBorderSet.end())
stream << ' ' << it->second;
stream << std::endl;
}
if (seamLoops != 1)
for (halfedgeSet_t::iterator it = seamTree.begin(); it != seamTree.end(); it++) {
stream /*<< "h "*/ << (*it)->vertex()->index() << ' ' << (*it)->opposite()->vertex()->index() << std::endl;
}
return;
}
bool Mesh::saveVolume(const char* fileName, const bool saveForClustering)
{
Vertex_iterator vIt = vertices_begin();
QByteArray array;
//QBuffer buf( array );
//buf.open( QIODevice::WriteOnly );
QTextStream s( &array );
QString str;
for (Vertex_iterator it = vertices_begin(); it != vertices_end(); it++) {
if (saveForClustering) {
Point_3 p = it->point();
//normalize point
Point_3 newp(
(p.x() - xmin()) / (xmax() - xmin()),
(p.y() - ymin()) / (ymax() - ymin()),
(p.z() - zmin()) / (zmax() - zmin()));
str.sprintf("%f %f %f %f\n", newp[0], newp[1], newp[2], it->volumeSDF());
} else {
str.sprintf("%f\n", it->volumeSDF());
}
s << str;
}
// buf.close();
s.flush();
QFile f(QString::fromAscii(fileName));
if (!f.open(QIODevice::WriteOnly))
return false;
f.writeBlock(array);
f.close();
return true;
}
bool Mesh::loadVolume(const char* fileName)
{
if (!QFile::exists(fileName))
return false;
Vertex_iterator vIt = vertices_begin();
QFile f(QString::fromAscii(fileName));
if (f.open(QIODevice::ReadOnly))
{
QByteArray qba = f.readAll();
QTextIStream s(&qba);
while (!s.atEnd())
{
float volume = s.readLine().toFloat();
if (vIt != vertices_end())
{
if (volume==volume)
vIt->volumeSDF(volume);
else
vIt->volumeSDF(0.0);
vIt++;
}
else
{
break;
}
}
f.close();
return true;
}
else
{
return false;
}
}
void Mesh::reverseNormals()
{
Enriched_Mesh::Vertex_iterator vit = vertices_begin();
Enriched_Mesh::Vertex_iterator vit_end = vertices_end();
for (;vit != vit_end; vit++) {
vit->normal() = vit->normal()*(-1);
}
Enriched_Mesh::Facet_iterator fit = facets_begin();
Enriched_Mesh::Facet_iterator fit_end = facets_end();
for (;fit != fit_end; fit++) {
fit->normal() = fit->normal()*(-1);
}
}
Point_3 Mesh::getFacetCenter(const Enriched_Mesh::Facet_const_handle& f)
{
double x = 0.0;
double y = 0.0;
double z = 0.0;
Enriched_Mesh::Halfedge_around_facet_const_circulator c = f->facet_begin();
do {
Point_3 p = c->vertex()->point();
x += p.x();
y += p.y();
z += p.z();
} while (++c != f->facet_begin());
Point_3 center((double) x/3, (double) y/3, (double) z/3);
return center;
}
| 24.71798
| 150
| 0.625629
|
hsiaoairplane
|
36a8152cf10babe762c438e4d20942439155efe4
| 742
|
cpp
|
C++
|
unistats/main.cpp
|
goldim/unistats
|
e8dd54e46f84422d868c942367f0103949791ede
|
[
"MIT"
] | null | null | null |
unistats/main.cpp
|
goldim/unistats
|
e8dd54e46f84422d868c942367f0103949791ede
|
[
"MIT"
] | null | null | null |
unistats/main.cpp
|
goldim/unistats
|
e8dd54e46f84422d868c942367f0103949791ede
|
[
"MIT"
] | null | null | null |
#include <QtQml>
#include <QGuiApplication>
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QIcon>
#include <QQuickView>
#include <QQuickItem>
#include <QVariantMap>
#include <unistatscore/Config.h>
#include "controller.h"
int main(int argc, char *argv[])
{
std::string cfgPath = "/home/goldim/config.ini";
if (argc == 2)
{
cfgPath = argv[1];
}
// controller cr(cfgPath);
Config cfg(cfgPath);
controller cr(cfg);
QApplication app(argc, argv);
app.setWindowIcon(QIcon(":/appicon.png"));
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("_controller", &cr);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
| 22.484848
| 65
| 0.667116
|
goldim
|
36a8a9fc887b558c589bcbbe2501aa07f642ac82
| 5,220
|
hpp
|
C++
|
test/src/Common.hpp
|
rhymu8354/Discord
|
432cba20b202fc1f70862e463755117ce82ee745
|
[
"MIT"
] | null | null | null |
test/src/Common.hpp
|
rhymu8354/Discord
|
432cba20b202fc1f70862e463755117ce82ee745
|
[
"MIT"
] | null | null | null |
test/src/Common.hpp
|
rhymu8354/Discord
|
432cba20b202fc1f70862e463755117ce82ee745
|
[
"MIT"
] | null | null | null |
#pragma once
/**
* @file Common.hpp
*
* This module declares the common base class for test fixtures
* and mocks used to test the Discord library.
*
* © 2020 by Richard Walters
*/
#include <gtest/gtest.h>
#include <Discord/Gateway.hpp>
#include <future>
#include <Json/Value.hpp>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <Timekeeping/Clock.hpp>
#include <vector>
/**
* This is a fake WebSocket dependency which is used to test the Gateway
* class.
*/
struct MockWebSocket
: public Discord::WebSocket
{
// Properties
unsigned int closeCode = 0;
bool closed = false;
std::mutex mutex;
CloseCallback onClose;
ReceiveCallback onText;
std::promise< void > onTextRegistered;
std::vector< std::string > textSent;
size_t numTextsSentAwaiting = 0;
std::shared_ptr< std::promise< void > > allTextsSent;
// Methods
bool AwaitTexts(size_t numTexts);
void RemoteClose();
// Discord::WebSocket
virtual void Binary(std::string&& message) override;
virtual void Close(unsigned int code) override;
virtual void Text(std::string&& message) override;
virtual void RegisterBinaryCallback(ReceiveCallback&& onBinary) override;
virtual void RegisterCloseCallback(CloseCallback&& onClose) override;
virtual void RegisterTextCallback(ReceiveCallback&& onText) override;
};
/**
* This is a fake connections dependency which is used to test the Gateway
* class.
*/
struct MockConnections
: public Discord::Connections
{
// Types
struct ResourceRequestsWait {
size_t numRequests = 0;
std::promise< void > haveRequiredRequests;
};
struct ResourceRequestWithPromise {
ResourceRequest request;
std::promise< Response > responsePromise;
std::promise< void > canceled;
bool responded = false;
};
struct WebSocketRequestsWait {
size_t numRequests = 0;
std::promise< void > haveRequiredRequests;
};
struct WebSocketRequestWithPromise {
WebSocketRequest request;
std::promise< std::shared_ptr< Discord::WebSocket > > webSocketPromise;
std::promise< void > canceled;
bool responded = false;
};
// Properties
std::mutex mutex;
bool tornDown = false;
std::vector< std::shared_ptr< ResourceRequestWithPromise > > resourceRequests;
ResourceRequestsWait resourceRequestsWait;
std::vector< std::shared_ptr< WebSocketRequestWithPromise > > webSocketRequests;
WebSocketRequestsWait webSocketRequestsWait;
// Methods
bool ExpectSoon(
std::promise< void >& asyncResult,
std::unique_lock< decltype(mutex) >& lock
);
bool RequireResourceRequests(size_t numRequests);
bool RequireWebSocketRequests(size_t numRequests);
void RespondToResourceRequest(
size_t requestIndex,
Response&& response
);
void RespondToWebSocketRequest(
size_t requestIndex,
std::shared_ptr< MockWebSocket > webSocket
);
void TearDown();
// Discord::Connections
virtual ResourceRequestTransaction QueueResourceRequest(
const ResourceRequest& request
) override;
virtual WebSocketRequestTransaction QueueWebSocketRequest(
const WebSocketRequest& request
) override;
};
/**
* This is a fake clock which is used to test the Gateway class.
*/
struct MockClock
: public Timekeeping::Clock
{
// Properties
double currentTime = 0.0;
// Methods
// Timekeeping::Clock
virtual double GetCurrentTime() override;
};
/**
* This is the base class for test fixtures used to test the Discord library.
*/
struct CommonTextFixture
: public ::testing::Test
{
// Properties
/**
* This is the unit under test.
*/
std::future< bool > connected;
Discord::Gateway::Configuration configuration;
std::shared_ptr< MockConnections > connections = std::make_shared< MockConnections >();
int heartbeatIntervalMilliseconds = 45000;
Discord::Gateway gateway;
std::shared_ptr< MockClock > clock = std::make_shared< MockClock >();
std::shared_ptr< Timekeeping::Scheduler > scheduler = std::make_shared< Timekeeping::Scheduler >();
std::shared_ptr< MockWebSocket > webSocket = std::make_shared< MockWebSocket >();
// Methods
bool Connect(
const Discord::Gateway::Configuration& configuration,
const std::string webSocketEndpoint = "wss://gateway.discord.gg"
);
bool ConnectExpectingWebSocketEndpointRequestWithResponse(
const std::string& webSocketEndpointRequestResponse,
const Discord::Gateway::Configuration& configuration,
std::future< bool >& connected
);
bool ConnectWebSocket(
const Discord::Gateway::Configuration& configuration,
const std::string webSocketEndpoint = "wss://gateway.discord.gg"
);
void ExpectHeaders(
const std::vector< Discord::Connections::Header >& expected,
const std::vector< Discord::Connections::Header >& actual
);
void SendHello();
void SendHeartbeatAck();
// ::testing::Test
virtual void SetUp() override;
virtual void TearDown() override;
};
| 27.329843
| 103
| 0.685824
|
rhymu8354
|
36ab17849795475208de99810078b75fe616bd64
| 6,862
|
cpp
|
C++
|
src/ocv_test/ocv_test/src/OCV_main.cpp
|
mac-novice-pg2/tool_dev
|
c988b72f803f24a130e08ef8515ec282119e377f
|
[
"BSD-3-Clause"
] | null | null | null |
src/ocv_test/ocv_test/src/OCV_main.cpp
|
mac-novice-pg2/tool_dev
|
c988b72f803f24a130e08ef8515ec282119e377f
|
[
"BSD-3-Clause"
] | 1
|
2018-09-28T13:33:18.000Z
|
2018-09-28T13:33:18.000Z
|
src/ocv_test/ocv_test/src/OCV_main.cpp
|
mac-novice-pg2/tool_dev
|
c988b72f803f24a130e08ef8515ec282119e377f
|
[
"BSD-3-Clause"
] | null | null | null |
#include "pch.h"
#include "UI_input_result.h"
using namespace cv;
const int wait_time_def = 1000;
/**
ファイル操作
*/
void
OCV_file_open( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_FILE_OPEN *menu_input )
{
IplImage *my_img = cvLoadImage( menu_input->filename, CV_LOAD_IMAGE_COLOR );
if( my_img == NULL )
{
printf( "%sの読み込みに失敗しました。ファイルの有無を確認して下さい\n", menu_input->filename );
return;
}
// 画面描画
cvNamedWindow( ocv_param->img_name, CV_WINDOW_AUTOSIZE );
cvShowImage( ocv_param->img_name, my_img );
waitKey( wait_time_def ); // 再描画を促す
ocv_param->img_handler.is_open = true;
ocv_param->img_handler.img = my_img;
} // OCV_file_open()
void
OCV_file_close( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_FILE_CLOSE *menu_input )
{
destroyAllWindows();
if( ocv_param->img_handler.is_open )
{
cvReleaseImage( &( ocv_param->img_handler.img ) );
}
} // OCV_file_close()
void
OCV_file_save( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_FILE_SAVE *menu_input )
{
cvSaveImage( menu_input->filename, ocv_param->img_handler.img );
printf( "%sとして保存しました\n", menu_input->filename );
} // OCV_file_save()
/**
色変換
*/
void
OCV_color_change_mono( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_COLOR_CHG_MONO *menu_input )
{
IplImage *my_img = ocv_param->img_handler.img;
IplImage *img_gray = cvCreateImage( cvGetSize( my_img ), IPL_DEPTH_8U, 1 );
IplImage *img_aft = cvCreateImage( cvGetSize( my_img ), IPL_DEPTH_8U, 3 );
cvCvtColor( my_img, img_gray, CV_BGR2GRAY );
cvMerge( img_gray, img_gray, img_gray, NULL, img_aft );
cvReleaseImage( &img_gray );
cvShowImage( ocv_param->img_name, img_aft );
waitKey( wait_time_def ); // 再描画を促す
cvReleaseImage( &my_img );
ocv_param->img_handler.img = img_aft;
} // OCV_color_change_mono()
void
OCV_color_change_sepia( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_COLOR_CHG_SEPIA *menu_input )
{
const int sepia_hue = 22;
const int sepia_sat = 90;
IplImage *my_img = ocv_param->img_handler.img;
// 画像を生成する
CvSize img_size = cvGetSize( my_img );
IplImage *img_HSV = cvCreateImage( img_size, IPL_DEPTH_8U, 3 ); // HSV画像
IplImage *img_hue = cvCreateImage( img_size, IPL_DEPTH_8U, 1 ); // 色相(H)
IplImage *img_sat = cvCreateImage( img_size, IPL_DEPTH_8U, 1 ); // 彩度(S)
IplImage *img_val = cvCreateImage( img_size, IPL_DEPTH_8U, 1 ); // 明度(V)
IplImage *img_merge = cvCreateImage( img_size, IPL_DEPTH_8U, 3 ); // for merge
IplImage *img_aft = cvCreateImage( img_size, IPL_DEPTH_8U, 3 );
CvScalar cv_value_hue = cvScalar( sepia_hue );
CvScalar cv_value_sat = cvScalar( sepia_sat );
// 表色系変換( BGR -> HSV )
cvCvtColor( my_img, img_HSV, CV_BGR2HSV );
cvReleaseImage( &my_img );
// HSV画像 -> [Hue][Sat][Val]分解
cvSplit( img_HSV, img_hue, img_sat, img_val, NULL );
cvReleaseImage( &img_HSV );
cvSet( img_hue, cv_value_hue, NULL ); // Hueの値をセピア用の値へ
cvSet( img_sat, cv_value_sat, NULL ); // Satの値をセピア用の値へ
// [Hue][Sat][Val] => img_mergeとして統合
cvMerge( img_hue, img_sat, img_val, NULL, img_merge );
cvReleaseImage( &img_hue );
cvReleaseImage( &img_sat );
cvReleaseImage( &img_val );
// HSVからBGRに変換する
cvCvtColor( img_merge, img_aft, CV_HSV2BGR );
cvReleaseImage( &img_merge );
cvShowImage( ocv_param->img_name, img_aft );
cvWaitKey( wait_time_def );
cvReleaseImage( &my_img );
ocv_param->img_handler.img = img_aft;
} // OCV_color_change_sepia()
/**
回転
*/
void
OCV_rotate( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_ROTATE *menu_input )
{
IplImage *my_img = ocv_param->img_handler.img;
IplImage *img_aft = cvCreateImage( cvGetSize( my_img ), IPL_DEPTH_8U, 3 );
// 回転中心算出
CvPoint2D32f center = cvPoint2D32f( my_img->width / 2.0, my_img->height / 2.0 ); //回転中心
// 回転行列を生成する
CvMat *rotate_matrix = cvCreateMat( 2, 3, CV_32FC1 );
// 変換行列を求める
cv2DRotationMatrix( center, menu_input->angle, 1, rotate_matrix );
// 画像の拡大、縮小、回転を行う
cvWarpAffine( my_img, img_aft, rotate_matrix, CV_INTER_LINEAR | CV_WARP_FILL_OUTLIERS, cvScalarAll( 0 ) );
cvShowImage( ocv_param->img_name, img_aft );
cvWaitKey( wait_time_def );
cvReleaseImage( &my_img );
ocv_param->img_handler.img = img_aft;
} // OCV_rotate()
/**
変形
*/
void
OCV_zoom( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_ZOOM *menu_input )
{
IplImage *my_img = ocv_param->img_handler.img;
// ズーム後のサイズに合わせたイメージを作成する
IplImage *img_aft = cvCreateImage( cvSize(
( int )( my_img->width * menu_input->zoom_ratio_width ),
( int )( my_img->height * menu_input->zoom_ratio_height ) ),
IPL_DEPTH_8U, 3 );
cvResize( my_img, img_aft, CV_INTER_LINEAR );
cvShowImage( ocv_param->img_name, img_aft );
waitKey( wait_time_def ); // 再描画を促す
cvReleaseImage( &my_img );
ocv_param->img_handler.img = img_aft;
} // OCV_zoom()
void
OCV_resize( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_RESIZE *menu_input )
{
IplImage *my_img = ocv_param->img_handler.img;
// ズーム後のサイズに合わせたイメージを作成する
IplImage *img_aft = cvCreateImage( cvSize( menu_input->width, menu_input->height ), IPL_DEPTH_8U, 3 );
cvResize( my_img, img_aft, CV_INTER_LINEAR );
cvShowImage( ocv_param->img_name, img_aft );
waitKey( wait_time_def ); // 再描画を促す
cvReleaseImage( &my_img );
ocv_param->img_handler.img = img_aft;
} // OCV_resize()
void
OCV_trim( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_TRIM *menu_input )
{
IplImage *my_img = ocv_param->img_handler.img;
// トリミング用領域確保
int calc_width = menu_input->x_end - menu_input->x_start;
int calc_height = menu_input->y_end - menu_input->y_start;
IplImage *img_aft = cvCreateImage( cvSize( calc_width, calc_height ), IPL_DEPTH_8U, 3 );
// トリミング領域の中心点算出
CvPoint2D32f center;
center.x = ( menu_input->x_start + menu_input->x_end ) / 2;
center.y = ( menu_input->y_start + menu_input->y_end ) / 2;
cvGetRectSubPix( my_img, img_aft, center );
cvShowImage( ocv_param->img_name, img_aft );
waitKey( wait_time_def ); // 再描画を促す
cvReleaseImage( &my_img );
ocv_param->img_handler.img = img_aft;
} // OCV_trim()
void
OCV_Demo( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_ *menu_input )
{
IplImage *img_ptr = cvLoadImage( "red-panda-731987_960_720.jpg", CV_LOAD_IMAGE_COLOR );
if( img_ptr == nullptr )
{
printf( "画像ファイルが見つかりません\n" );
CV_Assert( 0 );
}
const char* window_name = "pic_windows";
cvNamedWindow( window_name );
cvShowImage( window_name, img_ptr );
cvWaitKey( wait_time_def );
cvDestroyAllWindows();
if( img_ptr )
{
cvReleaseImage( &img_ptr );
}
} // OCV_Demo()
void
OCV_Unknown( OCV_Param_T *ocv_param, eMENU_INPUT_RESULT_ *menu_input )
{
CV_Assert( 0 );
} // OCV_Unknown()
| 29.965066
| 110
| 0.688866
|
mac-novice-pg2
|
36ab2c668394ffec8d0d68e6640e43fd55cfd7e4
| 52,656
|
cpp
|
C++
|
EZOJ/Contests/1460/C.cpp
|
sshockwave/Online-Judge-Solutions
|
9d0bc7fd68c3d1f661622929c1cb3752601881d3
|
[
"MIT"
] | 6
|
2019-09-30T16:11:00.000Z
|
2021-11-01T11:42:33.000Z
|
EZOJ/Contests/1460/C.cpp
|
sshockwave/Online-Judge-Solutions
|
9d0bc7fd68c3d1f661622929c1cb3752601881d3
|
[
"MIT"
] | 4
|
2017-11-21T08:17:42.000Z
|
2020-07-28T12:09:52.000Z
|
EZOJ/Contests/1460/C.cpp
|
sshockwave/Online-Judge-Solutions
|
9d0bc7fd68c3d1f661622929c1cb3752601881d3
|
[
"MIT"
] | 4
|
2017-07-26T05:54:06.000Z
|
2020-09-30T13:35:38.000Z
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <cctype>
using namespace std;
typedef long long lint;
#define cout cerr
#define ni (next_num<int>())
template<class T>inline T next_num(){
T i=0;char c;
while(!isdigit(c=getchar())&&c!='-');
bool neg=c=='-';
neg?c=getchar():0;
while(i=i*10-'0'+c,isdigit(c=getchar()));
return neg?-i:i;
}
template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;}
template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;}
template<class T>inline void mset(T a,int v,int n){memset(a,v,n*sizeof(a[0]));}
const int N=1000010,O=998244353;
inline int fpow(int x,int n){
int a=1;
for(;n;n>>=1,x=(lint)x*x%O){
if(n&1){
a=(lint)a*x%O;
}
}
return a;
}
inline int inv_pow(int x){
return fpow(x,O-2);
}
namespace gmath{
const int N=5000010;
const int BS=200000,GS=5000;
int init_n;
int _fac[N],_ifac[N];
inline void main(int n){
apmin(n,N-1);
init_n=n;
_fac[0]=1;
for(int i=1;i<=n;i++){
_fac[i]=(lint)_fac[i-1]*i%O;
}
_ifac[n]=inv_pow(_fac[n]);
for(int i=n;i>=1;i--){
_ifac[i-1]=(lint)_ifac[i]*i%O;
}
}
int bfac[GS]={
1,638474417,876712294,949283602,187142323,373341033,70007868,501927483,796024455,542991096,45596018,283287674,596316874,417528165,191166323,834980587,914550501,688948565,104964765,393032085,623627864,982424362,446366139,407729297,330880448,428937595,897706118,536236563,860856448,945501487,442819817,57092875,14554181,511596111,142128101,499710224,406984354,372247494,788080221,634098066,833655840,62174429,217507999,826634010,531854347,83857087,391931702,60435539,346814021,201876905,
295201906,841028503,595254166,288961565,372617820,788488293,214785669,586941976,798836079,121559584,671639287,905745233,598047083,524126609,332670261,849315549,108180821,330441070,822163165,644097424,597398273,433824922,821516475,558211762,643537971,813259672,980160849,572408921,491147937,662387095,732727656,426783046,336239771,915978376,384818512,244038325,482374615,763456553,670866031,970700529,122642896,307259936,552245646,334904481,700983666,310517972,122041708,158837842,526576992,154265204,
160030060,545120840,594484528,125533240,932427947,483239722,888547621,159892150,204604906,953194755,683879839,710198568,40172755,230420112,590157392,712910418,853172441,199660950,89366316,958564551,384710263,193777777,252902665,629222215,513947030,433880730,305993854,844300169,150494228,12034969,844360005,736620499,880392466,621197845,316234919,513089677,600187555,162637844,695714167,580355949,101492974,190978288,622545330,630593004,159596479,959253371,446760507,188808028,19289865,438270265,
957629942,411489774,833415116,639147854,1858960,678615452,368475610,97606564,682682315,412424033,34035221,37308241,510346646,745591849,319020540,56734233,74617988,329751033,819215905,147266093,524027922,36811456,183951017,90677883,584237732,31729117,528753617,356071602,259079578,313473995,102311167,365600946,493073744,775455687,826897016,330331487,882716777,345961537,393771832,816774574,8332991,908086460,824079438,223282259,736669190,832392662,649905009,546421210,220312447,872186518,
545208507,526440874,564560841,901016661,820215494,594075875,630254812,497843223,451653192,281875122,318497156,281077520,391564011,985402237,281589650,859275605,350331071,110566178,929486824,82719024,300738984,340522732,805325367,223689578,40359077,767818091,906934019,216541952,658294019,303213536,864118508,997822898,348600216,835484573,573706739,878131539,195969604,73732226,756919022,619535652,316588744,178145620,401222720,940074300,885534177,812496962,722316264,348438629,575985717,599834990,
213689172,103783113,815021282,860400524,861687482,584871249,676542561,346129673,766275603,579782990,980836133,461343290,169564539,517235481,911472795,54096741,861375995,679025032,733542862,505796205,417876813,695843405,641311602,951286622,604948489,363266670,366263604,168044071,483981875,961681722,335481797,610724444,310772360,380699882,338568924,730839588,429184708,245641763,544232708,20274450,393495668,841337447,563955060,577941262,286164023,435793297,602069285,552383730,550046860,387930530,
760025067,885951502,401178749,851255079,19132477,811438469,584572864,72440788,918098612,204404247,720976283,255229675,333853788,977151551,119288377,650770098,947701400,464060630,315552202,744889435,586537547,456191643,333104526,4390399,292624291,117371703,988378684,984089998,234426668,331300777,566486504,911513273,800612279,582125752,283010644,749562308,858022481,684870615,909030347,68685886,708205284,701025199,995703398,863814074,828484950,932912293,464037975,462924258,411054570,449870191,
939830261,425865548,390266531,838670730,531580415,983699513,566538086,708853823,566766129,831192378,206579820,37308012,179888829,174920451,29923813,301188781,741829521,657979351,821511104,590730766,593164676,231588061,800834612,245884933,936704636,770845925,303004806,388137181,135272165,173112946,247687458,676146427,589312043,205628042,272876741,41047791,963120036,232528387,705428274,775817031,266419267,669489805,276979681,471733299,107060302,937835947,631026019,605154426,877328108,7362571,
506268060,522147012,347010609,897850418,570335076,6177705,771152172,713858514,178011904,689869762,936268003,193864340,666780762,699888911,676150645,166873118,922700952,666879233,380386949,760826274,443834893,725706872,443657887,735740462,905906528,328979964,72564175,197593783,486514627,226471935,470135404,497601756,382643551,366208505,800048116,954410105,171703479,749544729,934051883,186302178,117565665,28515366,556127188,165302301,517407446,832761782,129452649,393456657,173655801,925142654,
39806322,297193538,419427422,320214110,74672160,478922755,198854937,951720077,298024541,871933197,394880724,822553534,390632053,278310054,693543402,821825588,252104595,774273828,870541371,413412181,468705875,153029405,173049798,447426627,112732874,512554988,689071146,385605303,209873720,282897103,232240472,693187928,346011894,928693088,882275125,876497899,958225129,305917724,451486982,630091198,356048018,325679625,67310823,518026008,459335532,895187265,705767517,603655893,128774695,648690264,
808258749,134184555,506333429,501958182,375160961,575505950,393573130,88195602,827220611,748694047,68190615,214323896,281445790,156691339,916923649,939065335,276074031,822569548,11597655,326103418,552199946,298152608,439461455,314945688,738026177,694814243,671139951,623015619,752565984,717432981,385460530,711326704,555396846,317971426,726156597,529769387,554596291,898735222,603182133,15019057,640377761,216846033,233536009,338335716,695413992,916128300,582989351,486482314,392473715,157046045,
440133909,979645207,171001823,980701383,329609648,362216114,665296408,305452149,443404632,435848803,826373774,467041349,451783592,361204798,470555993,502324157,903147162,308057484,119542277,347833149,457648395,434959642,708454989,106943594,372490496,385510728,388387295,211933849,458819803,592329486,904737188,32004291,829555360,71505438,93458558,78988746,132150611,76680600,241322250,889907850,454565719,577443503,91306733,33396591,54296524,623828097,729012741,489271002,569749913,718586252,
686156489,214043693,561649640,521131116,322168493,713476044,745829775,528827131,445043596,115925492,63602402,267362755,302400315,923078390,40685739,570334625,425218947,300566622,154721591,975635122,681055904,560006512,39952100,991716635,548996041,222059821,925368876,912995247,83494668,474854801,477211096,257118263,498240557,945994695,297063515,343363294,922935675,212820659,810862062,276719840,833792655,758360114,772735541,877820275,984614775,461853093,148073889,770537802,186103548,229542528,
741797144,308010402,482353858,819735799,687077719,74731896,30003378,63710828,532365990,883977343,930484262,656311650,122275891,879154192,915887245,268372735,173770156,269873549,377742973,51275675,941222802,545484874,748280238,46486013,58593926,677432735,738257061,21881554,605854640,887710995,474842829,674783621,267726409,553978642,891554540,700451655,7073772,95183385,848867625,920632493,400176109,409080008,234032702,100988948,333528883,697644778,97522948,325275913,515496652,235673487,
390377694,262800898,45987398,897079383,57638961,790010794,30413416,115403281,517050512,692919799,360642718,461749160,76590405,13198445,567827302,505712943,935404028,567109428,424654706,577595408,946647976,882088760,383892745,658474566,145066889,339045014,288595133,220173083,809196985,488724138,715797300,812500088,390872748,198395437,209809677,251680896,139804320,677703055,663506382,695347814,70091750,292264493,306871020,494320490,766389361,40517433,367534638,25494329,923139353,249490179,
12629586,299070408,870843400,211756561,659238894,850635539,504698718,569606286,554227444,952543806,110877109,65118888,558805924,853457929,445252148,571935891,22129538,979023484,188912279,256281795,695965747,893757562,763080960,305074154,65231491,634938288,912911566,311587357,375993408,546541568,69072133,939152092,292698823,790020967,405540822,155093216,553969206,817359797,936036643,192543744,749696762,915495697,381995158,316762863,94140449,963086402,413126101,979485745,37563575,158394770,
544711799,311655841,933641832,243010205,963056710,724471925,602491279,371919617,802417742,619165135,334646013,624328585,232957550,214996303,162030595,574791029,886754778,38088885,326425271,333007835,722417626,211906626,484123887,743006309,283059531,377929821,590008446,14252420,558071312,848568426,743946412,409141798,248332941,796671445,832357368,988034679,631542916,162026842,678384283,172276641,405207112,409675070,182634135,829303789,951352281,18063742,368518581,988977552,737310856,960325981,
104121967,374544588,1884078,355808744,385892669,638607426,273169986,596868491,312790136,784653222,607304611,525479491,715745570,10606982,133670326,751377777,813926726,521733954,277617484,336265578,35834555,564087599,219065921,343961025,515203686,313632531,150286151,694163251,67384247,269647422,18058363,230943242,547708338,52161288,538224444,656121134,798823564,886184101,944959217,535498408,40763559,912779295,244779964,876020115,523124058,562910912,889316514,971894705,275052166,623016958,
495867250,565227944,376005807,204446673,141178261,48767038,457684273,933554548,127826711,742944255,210864657,487318395,951127803,209305987,319788637,659137294,976295813,561525552,183064490,527803521,715390025,54138287,873594068,817557371,821228911,865854329,18862495,430238957,667630300,462554005,324322857,189862383,863799064,638544070,700943861,388911184,109394926,35807478,250187515,850048805,286059202,595613028,498643547,357103141,351853877,636456178,312649497,655494525,245942980,839700535,
421290700,676412450,909702106,793598459,285843479,832276048,238607386,208830815,147954033,540440789,726437551,184348260,848435923,480584356,252862701,526417714,397798371,691522880,400731148,101133665,252522639,878164518,985130003,381270337,330583810,386147469,587766057,789544102,625975158,474173552,674313019,418033105,594767143,62163978,790870663,274769381,308013743,509456888,237717712,157045810,226519400,508818359,175635693,281117739,966318684,272047186,281918691,899835088,559379377,412419409,
117153405,32567116,955814250,699002119,177896584,712896591,767682626,641598662,503281057,758380660,486826649,808701139,511479298,498997878,806172108,119444874,144672106,221879805,993644796,699534338,338909703,867251263,722145963,549347798,186743862,18536028,319624670,253251894,718791946,632859338,41814114,536832412,448354377,777914764,692260461,245606459,773628426,107128109,973925075,5034412,140617938,455404299,794274468,380138257,327840352,250512392,994876440,598001182,311999258,394484143,
57084755,598687849,852238642,581475169,239270658,157807456,72355546,536114498,209498896,277096143,261113192,55917823,68847230,398487191,545023245,40258068,855448818,986549624,83919888,504174407,194807105,528902040,258157503,710487178,679847579,325341339,467945713,772086096,669569604,606089443,884328111,533760024,579210533,656709079,353885019,896332013,829392518,522716276,308491660,680599894,880836012,44551570,364866697,465201045,378473773,737358206,52859469,53140903,405642641,459387570,
202713771,365800865,192383808,848556095,301134762,785454372,530316421,950807601,413840829,760334679,399586250,41923036,656290745,726780130,699590035,485457499,690001441,111874163,308669338,566931363,640827004,325669309,975460780,684479442,967269373,546969497,388689701,932126951,721695220,399980339,749602473,472949993,518017122,147559016,549687820,159788463,247686020,470114481,256847336,932446869,159111724,872185857,545826250,662205150,461871193,218592929,13037169,143212400,696437508,191849336,
675932866,151889553,896456400,878703498,114186730,314795475,633895291,418918400,255290913,595884163,811539323,639511321,89805971,192443742,825671035,246883213,485041591,168382150,714976582,295898061,696818315,611070862,163789266,140289851,725068512,759880589,701148374,242300526,533042609,506130339,4302336,1294247,410992377,185688203,752958782,353070689,459320446,878306150,697876761,206837612,477909706,754669485,611607455,380493034,662830731,559289160,155312119,114532351,915834079,945274406,
79781699,298263705,778838607,335552400,529216101,878094972,952119381,219827639,861214371,152422062,840903973,647310099,552748497,119063763,158552943,367416824,888392797,916525439,748635378,550383403,973366814,75923430,83240752,976001238,828804575,848259019,745478018,114887925,937624887,265623514,462421750,366707320,367924553,846993133,923119693,667227759,174378703,418329548,738133676,562397423,897917455,319069390,40062090,423511585,296804580,81800722,114346841,342324676,566524382,152058535,
956276337,520288073,830957214,289941149,221190161,942686845,925752178,654416425,832452686,692205432,420541799,740157471,820977660,267169410,831220038,417005912,875493938,823166072,728454812,869087493,272641764,986020321,249103550,447660975,803704970,941778993,843439912,640250852,126594230,81752448,217214373,8090,815508153,467782330,888470703,192220616,987267463,124315590,174714168,973786025,267901132,889525490,660774027,125472848,951453479,50530621,220169704,437660856,19840397,183261403,
652678397,91600158,591116721,308306707,942859297,354880856,540319710,774130469,313241084,31357126,164289049,319954828,850416074,139084582,737388697,781023184,924217172,108168938,917861735,148278528,105376215,675211107,883051929,31018348,760049296,315094878,154159023,305067968,438727956,509624570,607856504,385731226,966925552,51871608,740994024,733905911,672734939,614085592,377057915,215945066,457743498,499872790,124061032,201506295,817586763,992735713,623503799,704564037,138937737,454349886,
35212756,559584236,518745177,504223570,218617689,231822660,457207833,125417985,487832784,404169214,276036750,84159058,784503697,206309646,396363623,734558079,731642996,994932386,354883510,436335309,424180850,289803077,364805944,902810120,172325720,433186147,288465914,715164617,657816003,481162304,308380947,148254302,434327440,613474447,884361465,18333316,254468146,558956496,816835037,211183995,12935086,796392703,721146367,884294368,142185445,351491725,640398562,953769884,977697357,346680870,
655645460,246888672,834595531,915915979,972255064,535812389,748283012,420850780,91321067,41972562,521902115,230370581,207305412,394878806,853009537,67016984,371104474,633565220,785313954,611448374,48682076,283884744,27542966,766466789,191863723,64748124,151779940,226249422,106855733,268575910,489360447,277752808,212604510,498320579,735304770,361275315,896425714,663194414,788340653,445854390,786336279,805765546,257110521,611105022,758611451,805161272,729706424,36746501,330158910,596485813,
468129309,200847921,552903430,961152460,556713989,645091350,981930399,710497961,62345483,217099119,887284732,315177010,503516862,357334986,718835852,913004502,599658875,118059173,487589844,292156157,358814684,907292236,247311789,116097054,863453020,281295633,812972737,643868500,121480868,951402810,328970139,85367035,633629166,362924216,396332115,395955130,818500778,125030221,181113364,499002150,164840186,541557314,853292312,565567804,704926294,820902807,423202591,82342424,339640455,811981711,
761699708,734504379,62253260,457345181,373779604,246274415,147864041,680611489,113395585,707383766,592331769,925077350,694680152,770548178,990398656,913846362,245336149,888597030,996402653,699500103,866682684,238167074,543944516,595457177,125581313,600130702,296697449,264897779,112728599,572041452,903837674,799112668,384136177,337833945,752221617,529462989,376051822,480450700,494248455,98214173,90612675,603913380,173972579,332899082,350613655,526540127,408884204,802830021,961731838,590160610,
533047427,759026369,346122597,195415572,236344704,110008879,481666406,873393028,131856714,594822806,674279751,145107528,59522583,136504873,669915134,801920753,159154238,44820432,541962510,220094258,645226926,727292827,747002087,777072334,389938970,676886948,713230928,391187840,231205897,972738828,752481486,415537153,65753788,690717789,564830671,474034007,564793640,236626833,600061073,380606083,457790341,205871960,323738297,23963426,621374593,166813684,770230548,723238432,118624235,243941307,
287671032,973559504,80453079,816071184,662038180,188118664,398253464,78969719,358919724,561161036,244731384,861375753,676552828,199341171,111010963,404032157,15007469,410891874,293421269,339843420,269766986,752732002,336959605,14244457,377684984,423996017,841787262,331579622,268243673,491000522,182948540,412033053,832405770,462579521,693558577,356801634,546702921,25142337,152513397,691739925,737863144,934346305,596451995,694568954,527495727,652014069,462143646,876006820,491763782,650203872,
206068022,878034127,193660195,463004387,19556326,504569410,551134448,416795012,459988396,10441940,919894484,122583813,394649223,922878353,419994315,593398649,604125596,278442527,519738858,929932476,963768176,456894764,721553288,481843872,202651936,882517476,846760390,498683337,976095170,15479729,702523597,772761299,325485607,336863451,309635269,949028249,538720983,884794485,745987221,624335538,128957299,489646786,789322533,659333765,509104842,171997372,922549537,394512677,77936000,386115493,
50865043,387304485,923800607,329505251,845328908,20937461,385258895,49018815,277896830,541222054,690959202,872646140,714787224,911100363,614764590,581356488,625646122,574488313,500694157,819184601,369182214,90081456,538177858,587194686,937991501,993580422,375354540,416654030,558823478,401984674,193500140,14261622,639095619,3524514,646925471,540665426,216988792,847764166,413162692,304116919,365786018,963018314,734767599,407132657,229130073,743731625,952322941,211523872,16441988,661637039,
144980423,477198733,840849387,421040574,150783281,979536721,805651582,172155857,547294476,696300165,773259009,577403674,649228679,726526329,802820829,617053935,677653860,453067135,131583878,305544461,247670131,176106281,632449155,929095498,593362809,843705280,644504208,239282036,758940975,242888980,30419459,162331951,869616430,959052755,791826050,985463402,962827274,795721179,930624835,122667284,261585206,516321755,852592530,390947948,69222814,237885042,737313828,835951835,389749648,587283246,
111276893,452997345,78828708,382938777,638584664,488166208,455856024,651142160,818863012,590612592,137660292,914306639,832413555,939806618,491319468,720784236,420320241,899336396,469676688,386626643,244467770,668695145,496733288,96791353,949582565,26368504,330290904,731332496,295027067,182188737,792857103,442171559,946989153,830308872,744842355,666885724,521344100,105160700,753055262,209908395,670313309,6285377,668715275,293075071,220131604,905683034,87247059,10563023,924835496,299223721,
259415897,361668463,971100089,226968298,760740402,512017253,440777209,99649743,519917946,739992246,826265493,58953454,476222250,824386193,97151070,111960112,219436620,687289480,391726954,604890028,633652060,591607843,247747483,678073819,815450593,918048438,242366855,48354316,219270256,498897396,516432938,85284531,56995494,979294232,914659468,386972415,854842065,754079663,642786658,458603790,996212724,838103435,876705126,365887989,817047628,610073831,949716511,289235445,803644094,882832171,
444094191,308045603,613338053,698025609,835786784,72480267,711468923,726172731,189972995,322888445,665038087,288851183,675202693,622429752,845794575,11584804,394994592,712810838,206029625,743809429,301029012,757033316,812819242,974559244,674180764,723617861,367711797,733215777,742398359,294876390,113763819,22035421,959486572,858559810,523005355,778259899,609124230,882672374,898089066,800576135,937766095,325993923,671629636,343145762,941601677,535448641,128638019,351097457,947031904,440740274,
593907889,858256620,651200723,94266795,417593196,783573565,299272677,715624485,635292517,83086894,673298635,984206523,542843971,504474428,359478109,599533244,134519312,904684853,659955603,881173342,655712590,450046291,735928439,194548795,972774406,173350007,287321583,739105020,376902792,784491092,868198597,394283085,648465952,443703262,690154031,169013813,16422871,458780403,337974759,146999583,585161712,367061625,594319722,854563647,568434953,697502214,618177955,738141043,542099463,248007459,
573994984,535084676,299174432,66628616,578943699,285943986,746900711,903903635,742314795,607883363,675831407,229731324,535915879,311480923,738290568,3134056,94704928,106243257,703692941,856066867,965907646,49633724,972242413,883520028,221925665,401920943,976270161,820696588,409911108,274832651,665949756,352639283,631573115,316896483,254970102,236277883,455338890,137768685,955911337,160454905,612745912,609520572,419254833,628030298,162620329,813282113,577741576,234193154,948010625,909727799,
892454686,157317951,174446986,853284937,187596630,901222267,700818032,516363789,911998295,975021362,624900982,117598902,556611288,637288257,552836752,927122298,886216966,439575442,871469759,980162121,686321335,352486390,365457908,385975035,845606909,84924870,965740114,459102643,558220791,412374155,927606072,908613773,650237056,93379555,878832641,506664166,768668589,34507081,614249794,220035602,353631992,258388385,192152781,739238802,422199459,165913238,908362104,350255133,255263058,322575358,
566073550,813032469,116007867,134035304,595475717,816674343,771449239,728556772,871861964,967916935,864877926,174031496,926829282,563096119,326549798,171259407,218872798,43745938,886925642,863565863,908752311,64716978,703211036,12775780,931947039,874007723,702731056,244643479,853945023,585315061,803597299,789916432,286374238,745768395,629141541,613676466,953559789,625414510,423855595,366145469,880336545,87335825,797531927,333734234,599650552,282280109,724671071,451165139,256297014,370248303,
128761001,117377529,255028448,895870714,440724648,58852065,308653660,281552118,455980650,953662571,474075900,795392505,281348468,71916322,255585641,434816091,664197732,185792743,222918487,828285082,364856903,169212958,548447756,911828063,644503498,149123648,718045173,630806417,972393845,862839484,388854780,736227254,832986400,916456297,573433356,314693916,511764402,663678493,515575336,428068270,423183826,567900378,153529304,378440984,70891382,419733481,642060086,706239578,753773333,437238788,
888483202,869729486,669908167,664990744,670313061,238933227,564423714,767739357,173199128,922377714,336564048,579196148,344355077,632912142,452390855,757103493,211287250,693195921,435745985,960268965,100189123,564150498,284209379,679960920,773087916,855479832,481827552,433802090,713277676,393934171,51370348,177090598,961178945,694093380,701651719,403061033,612179701,893262054,420881731,524045373,496971759,464400965,709844862,146178979,101615911,831753030,200986212,900026737,220987644,864484781,
251718753,269235518,498311664,734686163,387016592,272779384,844520957,130659604,7080469,661917973,683379259,968404926,805217854,203956360,259240348,488844621,155358248,7529639,447193381,381466282,881783783,194512089,252082398,679935071,359944674,659478190,544001661,441485312,502082022,323738429,445719559,755335634,360449440,329588615,750732621,740782647,347511077,206794321,901599231,372193140,546525906,98613054,109218884,303110828,298050489,985524427,443773412,128459410,590893716,86282010,
548033568,330887234,812956643,687294533,948511601,333772553,464112846,772333655,721084229,31835478,331916427,533592369,357347436,651001706,871975748,752533273,481515942,816679791,452722766,416273693,730387628,783543268,777115208,642920384,503085651,93829695,235070863,620014456,223341051,538597437,655989476,278056139,815903428,707971922,746721927,930661318,749801573,449409696,699287127,914153187,334885743,833938200,429759848,626291316,876302615,466041862,425565564,278985149,503803540,547723012,
428105027,868403596,217613784,411643260,474844534,888238707,392534750,803473052,922186089,22753517,232218076,346631241,760590919,510661570,893678582,769865249,917928671,810358415,539001034,983538502,730641039,967064402,474310493,701394315,995370356,616996159,798322301,76591944,891854924,239300981,231721356,302285242,474417140,102429294,218582540,326973501,921448953,918617007,772169831,501125854,426068899,247200193,626622487,228649440,660946303,722403656,715477049,671794162,198467931,643696492,
742756734,963103784,605152029,651545852,462660570,663270261,220884334,396881088,612760233,376483161,364187931,708582028,74340200,753818952,848867837,350431704,72059034,345111886,932474797,791216072,671823672,812319607,462569962,334451149,718995099,633125919,30988619,504541050,531213622,350378112,226166717,523443516,595389696,180591752,683141957,386814657,518422245,255692174,673365636,317446209,237594135,287092115,548832542,827056161,650760543,451479365,892157578,177978881,200411187,651780991,
546182474,203041679,269285553,866093357,688684808,119366536,667327485,458663531,80257141,313316312,465211069,35032685,541239751,917768447,256667636,605313606,168706957,182900375,750117193,33032014,728508871,464039832,933488501,696936931,503930295,249619035,269173385,196063152,855789313,218680834,663053607,810979765,637623901,47569040,889679555,900453742,630540173,219548125,811351181,447157254,48293872,252767931,958902297,681449865,296218814,229958401,853870159,452358286,125943352,439152913,
62402409,682301831,62801862,177076138,748259163,69570431,151191712,104676054,986063012,224735177,71921532,892227618,124164816,829872466,213177421,960467929,269013494,871688962,978059858,42926916,537087913,635832597,651741378,587610508,969123613,514588945,92440114,20660049,666765961,434279634,513856225,3907296,40501448,197524035,281871512,415497414,175477963,189098770,544177744,12585949,286592050,109328730,643691767,126621521,193241990,645469437,379407277,367253353,584459532,297457955,
102052166,205393297,23840954,896624036,217127017,163298189,8264903,44123638,116360014,880054954,873938719,194598855,758373441,502483692,459233410,617583886,196981656,454590544,166464286,492245792,986843080,812441428,80557198,369548829,936650186,962390239,433418091,105552005,20590957,242273101,580971332,840528210,886788488,501678118,497580226,665147020,803575161,762288537,355493809,419413452,88900164,990167611,673447603,179294895,901634007,89866970,492495082,128625385,509849185,575987650,
826426395,577256185,348974809,532070310,444568444,616059995,414194257,818744640,394411763,16232745,443012312,43908505,977026668,804019338,461389164,659160562,360211014,750462725,732686070,968896201,229855967,240982196,815178512,324741802,197991923,687413213,541144612,240107673,648599644,640036075,59809521,952962089,856505535,935796702,992905138,398599610,677556704,870177895,345181024,593682394,325666688,224925603,901456741,934223928,900203387,154765991,785527811,581404502,184139999,511100545,
159186619,972405939,426214511,226316709,399705618,210830877,945243221,199203725,811858592,714155454,386454418,631101690,34547625,681858171,160235707,84493735,645422849,526859451,248807068,709757129,974220646,268994020,250959694,148576677,19371682,820097297,233191193,846957266,580279368,318300447,2191828,848633697,935092683,506687987,901220987,481459931,539567484,743569393,282424433,26691239,729073424,860597736,475044977,177903321,24188730,551556379,436357857,735589161,792972519,614286794,
926316039,743034339,567854358,648437466,516167226,151357011,143068447,64707765,193691951,311273254,808637654,272522795,190701933,336563763,829880625,218058015,909075057,540927150,466246599,368855028,786112034,925898147,522559601,394220873,188514425,850407126,450378479,769707451,899612407,215311924,84202800,392017718,286251537,479544467,668806484,94214098,163976105,565857838,911406244,551435120,30019651,794424877,33218812,323151525,906613099,121701603,681384398,614217983,782493409,807101118,
176055335,567454212,853746420,8181284,444528833,865461951,286653714,355689698,54954215,866192723,553631971,838853823,921280696,387622807,426963589,286620803,63876447,949322705,361760886,351755097,984061713,820629354,983685054,889135077,965214778,888573766,419062603,732044144,913768172,995350063,302767023,526402934,70552638,447453679,171297128,977070668,368190929,981731104,225210951,636262729,110954576,647142829,191882124,772081349,562980566,83922475,60634971,579150121,312895656,212904780,
51568171,150274796,844462574,548478088,562983131,60949367,465284724,364394020,204715419,727814670,19533020,322226329,183566168,724333004,328063440,510592752,276171166,327928634,52458807,582501116,615419476,977524177,566574988,883205623,344382954,341370469,54122358,959181460,480158153,361934895,912573425,401918906,802684215,207544377,755652024,286207526,40174926,866739461,210824168,668830073,206707897,661720836,568479007,425142330,590246341,384156962,566396021,369414407,593320145,280606414,
414163604,706877618,878128430,411742951,761341407,193301813,465989488,548370000,8294322,949836834,749570167,379912287,57885333,442312776,187044007,366933789,688081744,322956817,419699361,851406178,11470970,16574381,396315381,949643886,228086005,600191572,750385636,41785937,849101706,219222295,391667731,436444811,105083968,158009352,656087823,328736286,473646076,53766182,257034880,584902453,30645366,827091129,89255697,808411380,507001848,215162519,692374171,121469295,507231913,113371283,
604947226,434264625,348763373,825243013,476935929,236199953,180707885,776822307,953526515,643293926,718439098,762617700,21874873,689689577,444935230,411423177,674797408,362026478,894030634,675610856,803407599,159242971,867608454,829317990,22554175,632441623,617679741,103113383,952628462,185446735,766760224,258447428,18653828,908749844,460774480,263006576,927429592,173685132,199348204,462348776,757681534,210505189,491698560,23370155,73507840,61082578,546791557,131196700,312895519,629521119,
681666415,767463094,352900288,142064581,329771568,947466395,188075141,975254295,309980833,618313851,12206799,37792560,941195987,575749846,133527905,659767098,726730059,978464016,51949427,75778666,933746852,218322651,140975223,182431188,446201733,978860867,863081148,784719440,897376809,195234529,59215985,494052526,921785397,207637164,288903997,161179205,87496483,410436352,320837890,574761275,439197472,312114682,963193528,254232494,377078580,259779111,123471668,720364313,898211399,250523733,
511621808,104401589,676568476,805430653,463263515,145770512,949841094,921085980,865596423,708180274,882749888,34421466,548465725,28277201,850756943,943124465,353052244,764676482,164147939,44273894,872053396,673013740,857553424,853104621,538664274,631078482,603216371,726262252,655407188,32843680,166861622,645817459,2573502,287526682,746744346,743415395,831928009,446508498,650675936,687752220,772287179,519795821,715948127,674418745,547498225,602427948,430682817,291573802,141075040,544375192,
924112080,385334046,122457246,707697400,534072066,385643091,707719861,896026294,654245223,458599137,794973480,143513653,413809004,341001400,915004119,883782693,202936283,506579349,678515194,927303505,869723371,905943705,225376470,322770518,214589039,805963889,134842161,282857686,391933828,344786236,313106351,926403195,481219197,223555385,1629499,262132854,134241631,813415337,870863860,487593718,400034567,994489646,411670648,941947566,519658145,488248149,342071802,255703671,720345751,480273999,
265769800,959554435,877283263,165910246,358859939,791715397,263553238,75187258,20591569,254623345,408753255,325742733,579224315,920778509,614310318,468381897,617209068,131146296,335001095,766268949,415812467,954507602,526825098,733227729,334226426,172922144,689116289,535405004,403406769,179969253,64404368,325451103,225526518,418067497,649367294,281500398,411753420,890805692,707787492,119743149,512318142,554603050,323708035,340819315,820453170,288791777,601404861,531223980,603644245,79767669,
955559118,776543549,372220074,253896843,860664276,242484726,11998264,559823889,694440076,304161303,536413695,269781682,429452935,512988139,16965043,205340854,289691664,3539578,201516782,116563013,707803527,887949257,424238422,232483446,255336791,576699812,943193558,542202517,170958045,704624663,218525078,642896614,581561783,342882080,984289287,875554190,349751626,242221317,461546440,166393488,46283078,215255086,62719106,656243352,286856802,833841915,379629428,384759575,605918083,127003478,
763148293,68866378,816889980,648103769,641544481,807722138,466178261,703351910,254364584,926419773,788080170,328101383,300255531,12272668,764588623,556901372,234501930,570935836,536663662,818239318,150896699,302703328,573048654,362191589,457760886,253151120,597554637,675114778,488712076,682666273,97856807,659315718,960720602,483066395,125217612,918256774,393453192,653799428,400574765,754407717,771557187,181366252,90432862,744965282,428394983,582547026,469528291,833100011,105941911,347140977,
472709375,971630730,769640186,250924244,619201192,911615063,455505101,664888038,522277438,806851596,743371401,684492244,295015721,297010667,935209969,641382840,828050164,865849321,746857728,605166278,446540967,347501384,935640947,909557571,74277182,184639537,259740169,437082669,680081455,492480060,157247760,717849831,421012936,539598789,686012810,775930891,47091425,642877651,337904334,294758097,939702814,634761317,289407955,697394913,994282435,499082462,373510154,614689006,817232406,228169720,
19536133,482493730,620838535,514470733,230157941,548753627,474022796,118113109,908934043,632727669,593243221,972494096,730606012,262131366,606099055,563850263,321448905,913053716,43517848,198766865,185475971,462639757,969237802,717327818,754075136,687419227,491401112,256738618,466415123,378938294,396799323,49348482,427810475,548266487,650084514,657976136,769842260,157654452,45589178,282635009,864535682,116075727,29550277,364392467,506466886,433009242,597572477,437247124,139292288,407711601,
860830935,888075117,706683328,960051373,846540019,33107339,897387201,535478788,484854818,557635493,517661450,294565899,162511342,217062483,205744478,467651311,104852699,619284159,921277985,356522734,812398757,975099999,931348671,850331416,922547157,202133852,911644448,185843982,974445050,213986666,431839017,971838121,565653344,782023267,548304623,709549400,655045473,905162165,520984268,902585392,99643620,976386449,351584221,447646372,565860686,773282878,939655476,765305740,423340934,632684135,
290471030,5250326,384359258,929815121,868617133,61134552,433879572,388051796,211234310,346771112,129206504,174671334,961617281,594139590,538485916,929147251,134088395,332481734,804218505,227575277,837008968,715146915,172165484,414513123,160338146,422332597,423389191,203272275,959400038,629800791,353775281,57259927,822018130,194909159,256644252,469563025,628803011,253303129,553500057,58621692,62265336,847264029,911205590,569138008,656402912,835064501,311060327,807745356,325963793,41770045,
851685235,972563943,26001836,997216722,960411173,21197005,410848505,696063419,636254864,544071078,264793769,928380405,630020964,739636779,944529132,326416680,493551735,767232757,315266012,232619872,118842991,507865868,346707363,672814693,223884498,84257200,458917832,138671553,249651962,433490648,763248924,683631995,783724274,323097426,806826405,687559609,678021435,863392583,916736917,865666964,150907932,472793431,962204141,326189693,390909379,401832452,207892461,539523756,659638846,196236775,
242726978,914688565,288282640,694053656,238224020,766752066,702430135,991301384,26327533,48486564,959173604,578270158,708446364,128348737,973395811,390269102,272450352,242912964,935396087,457085846,992293822,266144751,462441329,937839395,775234193,744816299,689343159,723962524,919211209,22646332,476631694,647844047,938060844,955870985,227655372,177284763,750185149,734597703,623256769,553131371,702429415,575284290,407468436,97510275,554701193,374065901,940057038,52138662,710567700,51855733,
169855231,802105912,600825502,422314327,634951777,629007616,684764381,651429746,668090293,583464731,719169602,116171569,616812432,194256847,937385045,564737074,339187908,709896143,691491630,933240841,475119050,580383542,769560352,863914044,614826778,714502830,330903187,287066722,708653625,89312601,40993711,453398410,985909263,301084497,500502656,820235888,863184644,442130280,598410600,883448504,749063595,666937879,341630268,662528510,742839013,239329111,687465785,568093082,477812264,849786046,
612759169,275968173,167565536,343568116,547413634,18591377,219622855,180185753,130492893,551027440,419142436,234744613,173657981,690071657,46219460,442202439,774014314,57953956,594749548,457967843,941600951,118999147,87259356,886460769,170661061,158013406,722587713,735915370,968020070,141775306,637073231,879975605,971483785,681248316,811059073,471564060,785513967,482003677,996872768,31109516,447222237,181002475,652981849,326727045,544563167,701248503,403761561,512560867,286769863,246661405,
599797734,182386413,817931081,548034568,732454403,577221870,565858314,869105192,632273904,576015405,69656699,840824428,543991636,568602651,637587950,51052704,164564338,756326079,938409154,173511054,6544303,607243022,582059008,932096551,135289050,10958310,639019927,457576033,955084773,150007855,554955500,661745248,366039506,547538118,112487365,943192237,143936312,663284735,886890211,944241793,192526269,150059187,304711582,421779097,978912218,897983911,71717720,367619635,35934197,601096360,
961628039,707365961,348991447,868093321,17532161,240232720,554915517,17028594,593450905,243203844,627280533,473830455,150029906,816617255,22691591,710239542,306093006,484500944,166787731,395829959,70255649,266006850,100549095,366830033,741557556,261743865,239580600,363963677,365610561,34907454,228474833,480542196,960130817,154977923,140260596,776408079,501529947,992387594,35596410,870341658,304180483,735069330,749448411,492517985,654256447,63607040,481760312,597887170,855437455,905730134,
953297493,302709049,19997707,796751284,864674001,758058902,784924146,670109418,426832104,983588375,395529997,256962216,823017060,988402373,362087694,156010331,563804127,699526705,569026004,92568710,825833840,893106215,627152463,607701910,242958210,539880795,782699783,900917749,649774792,568342979,234683685,235886641,802308798,348641178,907910635,52626619,48255822,900552967,987893927,104361415,751843490,143935578,659229224,692200743,274397653,116909119,128019192,956811939,342718238,368411962,
62806842,517517337,855038826,930711874,279150975,574857555,164854598,403636264,819869053,505965820,353417551,870735150,626316896,555340806,476520498,40061330,968603057,602650849,865021171,859223681,822203768,645007223,112455506,920327142,934433124,681051568,48663714,132654087,386398410,51991269,490913702,82627507,254146120,355967270,36134523,9322961,934786222,404719250,839561982,45758872,766631257,881129645,769619757,442215012,170653709,124794668,198591086,927360884,732614296,543042671,
37844313,51855,333073045,237673023,391716915,163524507,684629909,362492290,842392605,116266913,729108319,671156429,98647530,623235494,736921347,490867505,743583659,22588584,206033114,993777102,47035168,746673419,659938697,639817999,978979098,682765157,975967666,441342640,649650998,382710072,53842115,261162900,560212561,650559057,806117495,817965276,757172910,361846034,548742063,677001598,757179922,698000394,586082536,862833967,591385514,339238384,602488502,801059179,917006691,774884612,
909741023,362108083,297362352,329261613,112712901,150530547,559466893,561106230,668645110,175260501,158444563,2490351,540161396,224709594,107191713,140949492,675208713,347237043,660669524,508680213,993302799,65480284,74681400,218107369,738190542,551621442,573728725,320792950,37239095,342218055,137578883,664362197,865784575,178265160,526252940,475122706,677110174,632343006,854989312,777898568,443869843,856310131,403893323,204297308,367028173,605400098,555135257,41725719,357463998,576780728,
689361523,919298440,670553151,446079298,410683143,769596520,704489618,274782189,269198543,935632811,801661499,357745722,608706956,516540313,536047622,474900284,144772303,278617548,524252054,221839489,586624857,571648819,221630511,121548948,299878187,349960501,770454472,938724912,541215360,156144194,134084537,503400792,881102456,436417672,549737824,650564083,29286834,235687447,100476545,117313580,877097974,528576053,444374536,716853074,514265102,379857427,127513126,558473021,373626340,68250185,
887890124,641663342,601085617,79662192,727897980,159436401,713611864,440382648,106866216,265495921,133274277,494370766,397669108,150597819,441437965,986182139,262846984,790903732,684960847,415384560,729720334,888898363,138283489,140425007,346272300,568925901,506473247,651552450,967750442,167299594,459461496,717448863,305614829,364454432,272034045,499309445,632617040,265918139,627817019,876808621,493171177,93489779,120578663,890450820,788481986,460958750,750837047,209333992,744344879,675956768,
380694152,738411144,400483531,443372770,272841854,168836226,80856091,895638820,9030973,33857526,840160881,429075627,898884542,446132539,594952891,141116880,887244234,408240304,747979126,772878514,225064950,132205308,848643865,242709633,210312104,109618190,426428476,114138558,671453933,452787741,842341383,281150531,661930289,974999575,557481044,85305729,459545390,466207377,338060455,559633156,759273275,971242416,526610238,644745859,220396827,97369807,146278719,667016107,977004959,75935354,
669317759,79434494,234710504,557695235,199039337,766247510,297742086,239322577,986724034,224854739,829017039,815949583,801121834,855863254,576852688,550323884,197588605,176881479,312628197,723971571,261274540,416291211,691727676,170064248,982549733,918239352,869405324,103247629,847203458,686285715,29606025,144283037,913767172,861570108,911217059,870793828,173133127,377895863,100787304,882571148,293683814,253151884,276559944,503705146,760676118,378510746,227072228,641299773,435227659,912657076,
367270918,147905845,4717993,544520679,507400049,481292028,123229359,633569521,217967270,473079883,813097823,7917922,869804624,60712726,1323886,798448487,429188954,775379985,143686780,421616469,230791733,928875954,503119497,279595365,768951532,899305835,669777197,927685505,439490384,529253919,504040630,160697694,777376052,172172822,882012844,162510533,975676318,733746295,313004905,958599538,479367951,168229155,3109593,732766199,296607974,275282274,180559952,603605790,257216715,250289370,
806951470,251465520,532835032,236012568,335115381,462774647,749373624,144010412,913680176,25991992,56473153,988226999,720597117,994632301,789484878,184659008,12520664,470274726,328659970,918411588,905122161,282082004,603407505,827917393,393634553,664034750,200078516,189670650,685227047,29125900,109726629,140350889,956226452,35081131,499149637,59372704,406210712,748338482,815436688,29875950,325795100,368790861,499612338,922684200,110114569,486860143,210317316,929448376,107727990,395851051,
843736533,34935797,272689992,713102241,654354262,924723613,495983082,958586082,408035547,510375478,880348000,921793692,931246800,645137675,212376682,801252478,294483047,590790899,235492719,582972953,616515290,362638524,59888024,977410427,270627822,776142608,792517877,542517498,500843278,233136855,284803450,632013708,245830139,734808241,275882738,583439582,330987636,977079279,805263257,934715482,274826676,200050192,318804570,206267171,52173830,6018349,261005717,727851802,448877017,278662368,
377403437,585365260,503843697,494012498,789721035,244041569,177608217,248568082,71452646,206791960,527081707,24546255,881104891,39510823,942709850,544763288,947296371,422973562,647019022,645108650,708818585,20884194,739760068,421365014,191538961,354033051,830793308,522905943,247822034,851482456,904309832,959374639,432682187,881249020,125921431,589922898,94383709,69636250,962304054,353253741,673933870,279216826,540176481,122270842,142912291,682858433,474799091,705134856,549371805,79290685,
945260111,702459321,4452732,967321971,386350590,899893421,91003219,700999068,9710951,421519808,515264973,97159599,227425765,725376973,252615615,911685911,55821831,21017897,97573992,804582047,9527148,352213091,148392333,505666382,851224347,239480646,562169673,926298379,599653049,27383361,524126897,239363217,833334137,7294272,852509887,48259065,400220130,901025063,26157762,584522336,578214879,220208835,885262212,598860599,855195121,118677219,144113925,18357870,521665998,589726961,
786127243,464216717,699031255,475392745,669207238,869205770,524407684,220506673,689613149,675392702,923276513,269788265,326174225,979952097,647276845,937928886,498910857,893833404,199925060,277715119,802186160,661843515,634236890,521918578,589512887,12198440,727930564,909016338,186815700,844625140,638784295,571395090,810913393,468095035,212948578,34200904,31789240,495176721,260737477,19072020,758925811,767802285,51631665,768213688,178469309,185027790,812961070,373512090,579829591,336972956,
80918046,852661846,635154227,155121988,939076879,120604699,749790553,467731703,217093422,892345735,610456697,7073976,99462722,265184771,800766132,573601211,593440479,333275954,81856271,565443008,208296321,827361616,779029568,177771146,190664812,49743354,974903132,559021925,827297426,151983506,653691911,153563523,208004838,285447960,959051187,490750754,401229578,897457477,256850511,637864251,674335312,436100884,76803592,3853000,140445031,887877110,599605496,426307178,588827936,232303657,
875880304,810743443,871724533,877517411,910589926,308360096,469087458,421030271,431450710,536627530,414636410,351190937,196243872,78467030,979791243,886100267,45548202,290562055,819800516,647310799,8525751,147027819,621277355,965427816,857902646,636257427,822428251,110136096,271351399,412208982,558338775,880137836,665110057,620379712,35029149,500159951,520181428,507846755,676364255,532907954,696213291,437764076,958819736,598356365,607863542,97268896,81366014,190076128,235994905,509225188,
364983542,984763249,988186568,815263708,671775072,937928436,462276586,15617735,575979814,716074408,641582714,43223386,484133503,788277011,216264505,586211304,118053291,804978770,396173607,285503342,345265657,350830865,448295531,781466241,717726069,994704486,594948276,66092643,337582598,782005000,443549763,1857575,170060686,80107212,578592712,207259440,253794778,870452389,790970771,969044093,302122082,351825488,364379250,735140939,172068509,166055224,798556379,630159689,5834778,611847780,
623250998,363278779,316706342,456011036,802146866,239642551,779809871,947566216,243633104,823414817,476337075,184010266,354401895,724291290,215439868,283167364,322291721,548555495,518326875,523302092,211328914,899535612,73429101,228142667,702023379,68064804,18681956,180424314,649237321,535709399,950202136,284881122,657295852,496081589,71341341,187552679,263662830,878395784,386677355,950091752,18938709,240670526,764937268,474964853,565563914,646784245,305928504,22898235,632046454,740557827,
598764068,32053393,733885460,105673208,673802032,538505481,135290915,279789068,261132766,299063509,610424991,800849725,667912494,603099643,86000108,864445053,269828780,41911324,810733871,261890809,390248689,814884557,339995562,102502161,702046356,278395191,956401237,828666830,378996395,802342572,686098470,79280183,576919627,206967135,184879749,935957187,478670683,657591941,573876820,626210364,868529577,674323032,118527211,526346788,133301926,329970687,293643564,530177004,191006198,739430903,
804930040,389937453,421510690,141700633,753855318,84992079,822607020,805399558,47001928,155674715,474569269,499740540,611562716,998035629,243527772,810762228,395484213,206168289,531717493,182069742,573258936,962288073,647891059,702204245,579446652,756464212,765204592,985020200,138021221,64331023,155080225,342833436,717490096,342481697,710006812,286966169,391316764,641927336,163813173,740462510,283614605,899622638,80616080,175517384,370909756,19283401,687298872,157064143,960901741,385907919,
24257676,209256830,754870233,353984926,636108396,871831819,119030022,831447308,418707377,553133511,612689791,894289734,348390639,300032176,849678837,846988741,538695155,661674325,545346747,632299295,617120754,217413506,799227111,461818634,95589232,971716517,717332626,283301377,908635732,215519117,979541482,609569702,334115506,768506247,880030358,297910784,936363929,430482926,54140494,158892941,991087897,6259065,187967995,178449755,94381621,783825907,967476181,542594390,775344700,351129885,
214821357,403186186,37058828,479331293,794857307,689498189,996154431,515827111,667478516,129122497,405026419,545986228,787570970,835349499,631179322,946731704,969525034,914970365,34325677,367169218,609346370,776933649,886352257,264819293,522247532,707669156,188935494,374100193,144228432,508395411,457703127,993523725,674441346,670552581,49449063,957341187,312852149,149613423,943222257,217620728,980735523,871670064,348890847,395217883,392047058,649367684,452728181,61135796,364301153,614947888,
791011898,637177559,822514219,734641141,106407822,82098966,213660206,186657803,662340002,962319210,234729712,93288159,789399703,740142578,857115611,105002711,934255640,932265522,219067891,317534229,130614285,494713237,162497346,422802484,793227159,291032164,383800090,732355595,859336562,496923860,193188049,308576104,304967011,740333780,758659608,363211260,345749320,452975523,962333047,20506237,58108651,214310174,686459451,93745902,67085097,100756444,47718874,500250082,486479404,182655360,
954947696,221025605,278311425,884626024,972423996,346032213,849634242,301583949,363566630,669552680,863300806,109264234,643066127,533787471,118363506,36876722,632826195,305283648,71266483,531030730,622610957,338004522,463351805,886386745,520622939,289232396,578389263,188890371,107689716,120744822,667938985,693473107,287288499,526449301,558420898,734886266,956720795,379625426,204692655,257512433,395881057,589328566,380998177,841567207,634380967,417188702,825197119,637619258,806721716,596976612,
183092975,814214118,365901116,683165786,752224001,887586469,242045474,450694993,414738490,648533733,83334648,847357562,248289434,885439552,393617876,797819763,748730069,800880477,467700392,760302574,100176902,601113034,243707311,542351412,466611651,781587414,233814369,489612075,294205596,732075333,841864935,254466725,810746281,728806094,627013238,371674670,465280416,550239544,806669488,766317851,18247584,111700697,0,0,0,0,0,0,0,0
};
inline int fac(const int n){
if(n<=init_n)return _fac[n];
int a=bfac[n/BS];
for(int i=n/BS*BS+1;i<=n;i++){
a=(lint)a*i%O;
}
return a;
}
inline int C(int n,int k){
if(n<=init_n)return (lint)_fac[n]*_ifac[k]%O*_ifac[n-k]%O;
else return (lint)fac(n)*inv_pow((lint)fac(k)*fac(n-k)%O)%O;
}
}
int fac[N],pr[N],fs=0;
inline void pshpri(int pri,int e){
if(e==0)return;
int l=0,r=fs;
for(int p=1;p<=e;p++,l=r,r=fs){
for(int i=l;i<r;i++){
pr[fs]=i,fac[fs]=fac[i]*pri,fs++;
}
}
}
int n,m,k;
int g(int d,int rst){
if(k%d)return 0;
if(rst==0)return d;
const int p=fac[rst]/fac[pr[rst]];
int nr=rst%(rst-pr[rst]);
d*=fac[rst]/fac[nr];
return (g(d,nr)+O-g(d/p,nr))%O;
}
int f(int d_id,int rst){
const int &d=fac[d_id];
if(m%d)return 0;
if(rst==0){
const int e=n/d,j=m/d;
int ans=gmath::C(e,j);
if((m+j)&1){
ans=O-ans;
}
return (lint)ans*g(1,d_id)%O;
}
const int g=rst-pr[rst];
const int e=rst/g;
rst%=g;
lint ans=0;
for(int i=0;i<=e;i++,d_id+=g){
ans+=f(d_id,rst);
}
return ans%O;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("subset.in","r",stdin);
freopen("subset.out","w",stdout);
#endif
#ifdef PRE
{
using namespace gmath;
int a=1;
printf("\tint bfac[GS]={\n");
int cnt=0;
putchar('\t');
putchar('\t');
++cnt,printf("%d,",1);
for(int i=1;i<BS*GS;i++){
a=(lint)a*i%O;
if(i%BS==0){
++cnt,printf("%d,",a);
if(cnt%50==0){
putchar('\n');
putchar('\t');
putchar('\t');
}
}
}
printf("};\n");
return 0;
}
#endif
n=ni,m=ni,k=ni;
gmath::main(n);
fac[fs]=1,pr[fs]=0,fs++;
{//factorization
int t=n;
for(int i=2;i*i<=t;i++){
int e=0;
for(;t%i==0;t/=i,e++);
pshpri(i,e);
}
if(t!=1){
pshpri(t,1);
}
}
printf("%lld\n",(lint)f(0,fs-1)*inv_pow(n)%O);
return 0;
}
| 209.784861
| 502
| 0.875532
|
sshockwave
|
36ac8a548ef00ad9baec1e05e99343b41ddb2431
| 4,987
|
cpp
|
C++
|
pico_dsp-esp-idf/esp-idf_pico_dsp_setup/src/main.cpp
|
ohmic-net/pico_dsp
|
e3a66666fbcfd8d8ed30dfd6ac2c01b7fa23c3b2
|
[
"MIT"
] | 23
|
2021-08-06T22:44:27.000Z
|
2022-03-24T06:20:44.000Z
|
pico_dsp-esp-idf/esp-idf_pico_dsp_setup/src/main.cpp
|
ohmic-net/pico_dsp
|
e3a66666fbcfd8d8ed30dfd6ac2c01b7fa23c3b2
|
[
"MIT"
] | null | null | null |
pico_dsp-esp-idf/esp-idf_pico_dsp_setup/src/main.cpp
|
ohmic-net/pico_dsp
|
e3a66666fbcfd8d8ed30dfd6ac2c01b7fa23c3b2
|
[
"MIT"
] | 1
|
2021-08-19T10:37:36.000Z
|
2021-08-19T10:37:36.000Z
|
// Generates a 16bit sine wave for testing audio output over I2S with WM8978 codec,
// for PICO_DSP development board Originl Edition with 4MB Flash
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <stdio.h>
#include "driver/i2s.h"
#include "driver/gpio.h"
#include "esp_system.h"
#include "esp_sleep.h"
#include "driver/periph_ctrl.h"
#include <math.h>
#include "WM8978.h"
#define I2S_SAMPLE_RATE (32000) // I2S sample rate
#define WAVE_FREQ_HZ (200) // test waveform frequency
#define PI (3.14159265)
// Define 12S pins
#define I2S_BCLK 23 // Bit clock
#define I2S_LRC 25 // Left Right / WS Clock
#define I2S_DOUT 26
#define I2S_DIN 27
#define I2S_MCLKPIN 0 // MCLK
#define SAMPLES_PER_CYCLE (I2S_SAMPLE_RATE/WAVE_FREQ_HZ)
#define uS_TO_S_FACTOR 1000000 // Conversion factor uS to seconds
#define TIME_TO_SLEEP 10 // time in seconds to sleep for
extern "C" {
void app_main(void);
}
WM8978 wm8978; // create an instance of WM8978 class for the audio codec
void I2S_Init() {
i2s_config_t i2s_config = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_RX),
.sample_rate = I2S_SAMPLE_RATE,
.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // high interrupt priority
.dma_buf_count = 4,
.dma_buf_len = 40, // see below
.use_apll = true
};
i2s_pin_config_t pin_config = {
.bck_io_num = I2S_BCLK,
.ws_io_num = I2S_LRC,
.data_out_num = I2S_DOUT,
.data_in_num = I2S_DIN
};
i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL); // install the driver
i2s_set_pin(I2S_NUM_0, &pin_config); // port & pin config
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0_CLK_OUT1); // MCLK on GPIO0
REG_WRITE(PIN_CTRL, 0xFFFFFFF0);
i2s_set_sample_rates(I2S_NUM_0, I2S_SAMPLE_RATE); // set sample rate used for I2S TX and RX
}
//calculating buffer size; for 32Khz sample rate we create a 200Hz sine wave, every cycle needs 32000/200 = 160 samples
//(4-bytes or 8-bytes each sample) depending on bits_per_sample
//using 4 buffers, we need 40-samples per buffer
//if 2-channels, 16-bit each channel, total buffer is 160*4 = 640 bytes
//if 2-channels, 24/32-bit each channel, total buffer is 160*8 = 1280 bytes
static void sine_wave() { // function to generate sine wave
float freq = (WAVE_FREQ_HZ);
unsigned sample_rate = I2S_SAMPLE_RATE;
size_t buf_size = (SAMPLES_PER_CYCLE*8); // number of cycles to store in the buffer
printf("\r\n free mem=%d, written data=%d\n", esp_get_free_heap_size(), buf_size);
short *samples_sine = new short[buf_size]; // create buffer to store 16bit samples
for(int i=0; i<buf_size; ++i) {
samples_sine[i] = (pow(2,16)/2-1) * sin(PI*(freq/sample_rate)*i); // 16bit
uint value = 0;
value += samples_sine[i];
//printf("Samples_sine=%d\n", value); // comment out to print the samples data, only use one call to printf in the function
}
i2s_set_clk(I2S_NUM_0, I2S_SAMPLE_RATE, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_STEREO); // Set clock & bit width used for I2S RX and TX
// bit_clock BCK = sample rate * (number of channels) * bits_per_sample
// call the write function and pass the data buffer address and data length to it, write the data to the I2S DMA TX buffer
size_t i2s_bytes_write = 0;
i2s_write(I2S_NUM_0, samples_sine, buf_size, &i2s_bytes_write, portMAX_DELAY);
delete(samples_sine);
}
void app_main() {
I2S_Init(); // I2S config and driver install
wm8978.init(); // WM8978 codec initialisation
wm8978.addaCfg(1,1); // enable the adc and the dac
wm8978.inputCfg(0,0,0); // input config
wm8978.outputCfg(1,0); // output config
wm8978.spkVolSet(40); // speaker volume
wm8978.hpVolSet(40,40); // headphone volume
wm8978.sampleRate(1); // set sample rate to match I2S sample rate
wm8978.i2sCfg(2,0); // I2S format MSB, 16Bit
vTaskDelay(2000/portTICK_RATE_MS);
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
sine_wave(); // play test sine wave
uint8_t regval = wm8978.readReg(7);
printf("Register Value = %d \n", regval); // check register value
vTaskDelay(10000/portTICK_RATE_MS);
wm8978.sleep(1); // after 10 seconds, set the audio codec to standby mode
vTaskDelay(5000/portTICK_RATE_MS);
esp_deep_sleep_start(); // after another 5 seconds, enter deep sleep
}
| 40.877049
| 137
| 0.65751
|
ohmic-net
|
36afe3298f5f5307ee89dd9ccbf7c956cf701b32
| 1,182
|
cpp
|
C++
|
src/I2C/I2C_Ramps.cpp
|
David21NP/Ramps-1.4
|
b147e02ffe923455c2185bbec06e94092dc96c34
|
[
"MIT"
] | null | null | null |
src/I2C/I2C_Ramps.cpp
|
David21NP/Ramps-1.4
|
b147e02ffe923455c2185bbec06e94092dc96c34
|
[
"MIT"
] | null | null | null |
src/I2C/I2C_Ramps.cpp
|
David21NP/Ramps-1.4
|
b147e02ffe923455c2185bbec06e94092dc96c34
|
[
"MIT"
] | null | null | null |
#include "I2C_Ramps.h"
namespace Ramps_1_4
{
I2C_Ramps::I2C_Ramps(/* args */)
{
}
I2C_Ramps::~I2C_Ramps()
{
}
int8_t I2C_Ramps::readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data)
{
return I2Cdev::readBit(devAddr, regAddr, bitNum, data);
}
int8_t I2C_Ramps::readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data)
{
return I2Cdev::readBits(devAddr, regAddr, bitStart, length, data);
}
int8_t I2C_Ramps::readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data)
{
return I2Cdev::readByte(devAddr, regAddr, data);
}
bool I2C_Ramps::writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data)
{
return I2Cdev::writeBit(devAddr, regAddr, bitNum, data);
}
bool I2C_Ramps::writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data)
{
return I2Cdev::writeBits(devAddr, regAddr, bitStart, length, data);
}
bool I2C_Ramps::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data)
{
return I2Cdev::writeByte(devAddr, regAddr, data);
}
}
| 28.142857
| 113
| 0.670897
|
David21NP
|
a5e0c99eb59c9cebcba087cfac26f18e7c2c5d8b
| 2,810
|
cpp
|
C++
|
android/app/src/cpp/src/backend/cpu/CpuLaunchData.cpp
|
FlameSalamander/react-native-xmrig
|
6a6e3b301bd78b88459989f334d759f65e434082
|
[
"MIT"
] | 28
|
2021-05-11T03:28:57.000Z
|
2022-03-09T14:34:57.000Z
|
android/app/src/cpp/src/backend/cpu/CpuLaunchData.cpp
|
FlameSalamander/react-native-xmrig
|
6a6e3b301bd78b88459989f334d759f65e434082
|
[
"MIT"
] | 10
|
2021-05-16T19:50:31.000Z
|
2022-01-30T03:56:45.000Z
|
android/app/src/cpp/src/backend/cpu/CpuLaunchData.cpp
|
FlameSalamander/react-native-xmrig
|
6a6e3b301bd78b88459989f334d759f65e434082
|
[
"MIT"
] | 12
|
2021-07-19T22:14:58.000Z
|
2022-02-08T02:24:05.000Z
|
/* XMRig
* Copyright 2010 Jeff Garzik <jgarzik@pobox.com>
* Copyright 2012-2014 pooler <pooler@litecoinpool.org>
* Copyright 2014 Lucas Jones <https://github.com/lucasjones>
* Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet>
* Copyright 2016 Jay D Dee <jayddee246@gmail.com>
* Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt>
* Copyright 2018 Lee Clagett <https://github.com/vtnerd>
* Copyright 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "backend/cpu/CpuLaunchData.h"
#include "backend/common/Tags.h"
#include "backend/cpu/CpuConfig.h"
#include <algorithm>
xmrig::CpuLaunchData::CpuLaunchData(const Miner *miner, const Algorithm &algorithm, const CpuConfig &config, const CpuThread &thread, size_t threads) :
algorithm(algorithm),
assembly(config.assembly()),
astrobwtAVX2(config.astrobwtAVX2()),
hugePages(config.isHugePages()),
hwAES(config.isHwAES()),
yield(config.isYield()),
astrobwtMaxSize(config.astrobwtMaxSize()),
priority(config.priority()),
affinity(thread.affinity()),
miner(miner),
threads(threads),
intensity(std::min<uint32_t>(thread.intensity(), algorithm.maxIntensity()))
{
}
bool xmrig::CpuLaunchData::isEqual(const CpuLaunchData &other) const
{
return (algorithm.l3() == other.algorithm.l3()
&& assembly == other.assembly
&& hugePages == other.hugePages
&& hwAES == other.hwAES
&& intensity == other.intensity
&& priority == other.priority
&& affinity == other.affinity
);
}
xmrig::CnHash::AlgoVariant xmrig::CpuLaunchData::av() const
{
if (intensity <= 2) {
return static_cast<CnHash::AlgoVariant>(!hwAES ? (intensity + 2) : intensity);
}
return static_cast<CnHash::AlgoVariant>(!hwAES ? (intensity + 5) : (intensity + 2));
}
const char *xmrig::CpuLaunchData::tag()
{
return cpu_tag();
}
| 35.56962
| 151
| 0.66726
|
FlameSalamander
|
a5e4954925c8f03dbfa0105b4a2b009ec5cd79b6
| 1,612
|
cpp
|
C++
|
VNOJ/Data_Structures/IT_and_BIT/segtree_itds1.cpp
|
hoanghai1803/CP_Training
|
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
|
[
"MIT"
] | 4
|
2021-08-25T10:53:32.000Z
|
2021-09-30T03:25:50.000Z
|
VNOJ/Data_Structures/IT_and_BIT/segtree_itds1.cpp
|
hoanghai1803/CP_Training
|
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
|
[
"MIT"
] | null | null | null |
VNOJ/Data_Structures/IT_and_BIT/segtree_itds1.cpp
|
hoanghai1803/CP_Training
|
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
|
[
"MIT"
] | null | null | null |
// Author: __BruteForce__
#include <bits/stdc++.h>
using namespace std;
#define MAX_N 100005
#define oo INT_MAX
int n, q;
int arr[MAX_N];
multiset<int> ST[4 * MAX_N];
void build(int id, int L, int R) {
if (L == R) {
ST[id].insert(arr[L]);
return;
}
int M = (L + R) >> 1;
build(id * 2, L, M);
build(id * 2 + 1, M + 1, R);
for (int tmp = 0; tmp < 2; tmp++)
for (auto v: ST[id * 2 + tmp]) ST[id].insert(v);
}
void update(int id, int L, int R, int p, int v) {
if (p < L || R < p) return;
ST[id].erase(ST[id].find(arr[p]));
ST[id].insert(v);
if (L == R) return;
int M = (L + R) >> 1;
update(id * 2, L, M, p, v);
update(id * 2 + 1, M + 1, R, p, v);
}
int getMin(int id, int L, int R, int u, int v, int k) {
if (v < L || R < u) return +oo;
if (u <= L && R <= v) {
auto pos = ST[id].lower_bound(k);
if (pos != ST[id].end()) return *pos;
return +oo;
}
int M = (L + R) >> 1;
return min(getMin(id * 2, L, M, u, v, k), getMin(id * 2 + 1, M + 1, R, u, v, k));
}
int main() {
cin.tie(0)->sync_with_stdio(false);
cin >> n >> q;
for (int i = 1; i <= n; i++)
cin >> arr[i];
build(1, 1, n);
while (q--) {
int t;
cin >> t;
if (t == 1) {
int p, v;
cin >> p >> v;
update(1, 1, n, p, v);
arr[p] = v;
} else {
int u, v, k;
cin >> u >> v >> k;
int minVal = getMin(1, 1, n, u, v, k);
cout << (minVal == +oo ? -1 : minVal) << "\n";
}
}
}
| 22.388889
| 85
| 0.419975
|
hoanghai1803
|
a5e76676a5ed7850e20b7f312784702e161b6a53
| 2,605
|
cpp
|
C++
|
C++/maximum-number-of-occurrences-of-a-substring.cpp
|
jaiskid/LeetCode-Solutions
|
a8075fd69087c5463f02d74e6cea2488fdd4efd1
|
[
"MIT"
] | 3,269
|
2018-10-12T01:29:40.000Z
|
2022-03-31T17:58:41.000Z
|
C++/maximum-number-of-occurrences-of-a-substring.cpp
|
jaiskid/LeetCode-Solutions
|
a8075fd69087c5463f02d74e6cea2488fdd4efd1
|
[
"MIT"
] | 53
|
2018-12-16T22:54:20.000Z
|
2022-02-25T08:31:20.000Z
|
C++/maximum-number-of-occurrences-of-a-substring.cpp
|
jaiskid/LeetCode-Solutions
|
a8075fd69087c5463f02d74e6cea2488fdd4efd1
|
[
"MIT"
] | 1,236
|
2018-10-12T02:51:40.000Z
|
2022-03-30T13:30:37.000Z
|
// Time: O(n)
// Space: O(n)
// rolling hash (Rabin-Karp Algorithm)
class Solution {
public:
int maxFreq(string s, int maxLetters, int minSize, int maxSize) {
static const uint64_t M = 1000000007;
static const uint64_t p = 113;
uint64_t power = pow(p, minSize - 1, M), rolling_hash = 0;
int left = 0;
unordered_map<int, int> lookup;
unordered_map<char, int> count;
for (int right = 0; right < s.length(); ++right) {
++count[s[right]];
if (right - left + 1 > minSize) {
--count[s[left]];
rolling_hash = (rolling_hash + M - (s[left] * power) % M) % M;
if (!count[s[left]]) {
count.erase(s[left]);
}
++left;
}
rolling_hash = ((rolling_hash * p) % M + s[right]) % M;
if (right - left + 1 == minSize && count.size() <= maxLetters) {
++lookup[rolling_hash];
}
}
return lookup.empty()
? 0
: max_element(lookup.cbegin(), lookup.cend(),
[](const auto& a, const auto& b) {
return a.second < b.second;
})->second;
}
private:
uint64_t pow(uint64_t a,uint64_t b, uint64_t m) {
a %= m;
uint64_t result = 1;
while (b) {
if (b & 1) {
result = (result * a) % m;
}
a = (a * a) % m;
b >>= 1;
}
return result;
}
};
// Time: O(m * n), m = 26
// Space: O(m * n)
class Solution2 {
public:
int maxFreq(string s, int maxLetters, int minSize, int maxSize) {
unordered_map<string, int> lookup;
for (int right = minSize - 1; right < s.length(); ++right) {
const auto& word = s.substr(right - minSize + 1, minSize);
if (lookup.count(word)) {
++lookup[word];
} else if (unique_count(word) <= maxLetters) {
lookup[word] = 1;
}
}
return lookup.empty()
? 0
: max_element(lookup.cbegin(), lookup.cend(),
[](const auto& a, const auto& b) {
return a.second < b.second;
})->second;
}
private:
int unique_count(const string& word) {
unordered_set<char> lookup;
for (const auto& c : word) {
lookup.emplace(c);
}
return lookup.size();
}
};
| 31.011905
| 78
| 0.442994
|
jaiskid
|
a5e9f815995d942477cc232d90cdaa43e026103e
| 8,171
|
cpp
|
C++
|
oldies/bofsocketpoller.cpp
|
onbings/bofstd
|
366ff7f7d8871d5fa5785d5690d90506a7714ecc
|
[
"MIT"
] | null | null | null |
oldies/bofsocketpoller.cpp
|
onbings/bofstd
|
366ff7f7d8871d5fa5785d5690d90506a7714ecc
|
[
"MIT"
] | 1
|
2021-03-20T14:46:54.000Z
|
2021-03-20T14:47:10.000Z
|
oldies/bofsocketpoller.cpp
|
onbings/bofstd
|
366ff7f7d8871d5fa5785d5690d90506a7714ecc
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2015-2025, Onbings. All rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
* PURPOSE.
*
* This module implements the BofSocketPoller class.
*
* Author: Bernard HARMEL: onbings@dscloud.me
* Web: onbings.dscloud.me
* Revision: 1.0
*
* Rem: None
*
* History:
*
* V 1.00 Jan 05 2019 BHA : Initial release
*/
/*** Include files ***********************************************************/
#include <bofstd/BofSocketPoller.h>
BEGIN_BOF_NAMESPACE()
enum POLL_SOCKET_CMD
{
POLL_SOCKET_CMD_CANCEL_WAIT = 'C',
};
BofSocketPoller::BofSocketPoller(uint32_t _NbMaxSession_U32): BofThread()
{
BOF_SOCKET_PARAM BofSocketParam_X;
mErrorCode_E = BOFERR_INVALID_VALUE;
mBofSocketPollerParam_X = _rBofSocketPollerParam_X;
BOF_ASSERT(mBofSocketPollerParam_X.NbMaxSession_U32 != 0);
BOF_ASSERT(mBofSocketPollerParam_X.Listen != INVALID_SOCKET);
if ((mBofSocketPollerParam_X.NbMaxSession_U32) && (mBofSocketPollerParam_X.Listen != INVALID_SOCKET))
{
mErrorCode_E = LaunchBofProcessingThread(_rBofSocketServerParam_X.Name_S, false, 0, 0, 0, mBofSocketServerParam_X.ThreadPolicy_i, mBofSocketServerParam_X.ThreadPriority_i, POLL_TIMEOUT_IN_MS * 8);
BOF_ASSERT(mErrorCode_E == BOFERR_NO_ERROR);
if (mErrorCode_E == BOFERR_NO_ERROR)
{
}
mErrorCode_E = Bof_CreateMutex(mBofSocketPollerParam_X.Name_S + "_mtx", true, true, mMtx_X);
if (mErrorCode_E == BOFERR_NO_ERROR)
{
mErrorCode_E = BOFERR_NOT_ENOUGH_RESOURCE;
//Entry 0 is for listen socket, Entry 1 if for pipe interrupt and the next ones are for client socket: For each client you can have 2 poll socket: one for cmd and one for data
mpPollOp_X = new BOF_POLL_SOCKET[POLL_RESERVED_INDEX_MAX + (mBofSocketPollerParam_X.NbMaxSession_U32 * 2)];
BOF_ASSERT(mpPollOp_X != nullptr);
if (mpPollOp_X)
{
memset(mpPollOp_X, 0, sizeof(BOF_POLL_SOCKET)*(POLL_RESERVED_INDEX_MAX + _rBofSocketPollerParam_X.NbMaxSession_U32));
mpPollOp_X[POLL_RESERVED_INDEX_LISTEN].Fd = mBofSocketPollerParam_X.Listen;
mpPollOp_X[POLL_RESERVED_INDEX_LISTEN].Event_U16 = POLLIN;
BofSocketParam_X.BaseChannelParam_X.ChannelName_S = mBofSocketPollerParam_X.Name_S;
BofSocketParam_X.BaseChannelParam_X.Blocking_B = true; // _rBofSocketServerParam_X.Blocking_B;
BofSocketParam_X.BaseChannelParam_X.ListenBackLog_U32 = 0;
BofSocketParam_X.BaseChannelParam_X.RcvBufferSize_U32 = _rBofSocketPollerParam_X.NbMaxSession_U32 * 2;
BofSocketParam_X.BaseChannelParam_X.SndBufferSize_U32 = _rBofSocketPollerParam_X.NbMaxSession_U32 * 2;
BofSocketParam_X.NoDelay_B = true;
BofSocketParam_X.ReUseAddress_B = true;
BofSocketParam_X.BindIpAddress_S = "udp://127.0.0.1:" + std::to_string(mBofSocketPollerParam_X.LocalPortForCancellingWait_U16);
mErrorCode_E = BOFERR_NOT_ENOUGH_RESOURCE;
mpBofSocketForCancellingWait = new BofSocket(BofSocketParam_X);
if (mpBofSocketForCancellingWait)
{
mErrorCode_E = mpBofSocketForCancellingWait->LastErrorCode();
if (mErrorCode_E == BOFERR_NO_ERROR)
{
BOF_SOCKET_ADDRESS DstIpAddress; // (false, BOF_SOCK_TYPE::BOF_SOCK_UDP, BOF_PROTOCOL_TYPE::BOF_PROTOCOL_UDP, 127, 0, 0, 1, );
DstIpAddress = mpBofSocketForCancellingWait->GetSrcIpAddress();
mErrorCode_E = mpBofSocketForCancellingWait->SetDstIpAddress(DstIpAddress);
if (mErrorCode_E == BOFERR_NO_ERROR)
{
mpPollOp_X[POLL_RESERVED_INDEX_CANCEL].Fd = mpBofSocketForCancellingWait->GetSocketHandle();
mpPollOp_X[POLL_RESERVED_INDEX_CANCEL].Event_U16 = POLLIN;
mErrorCode_E = BOFERR_NO_ERROR;
}
}
}
}
}
}
}
BofSocketPoller::~BofSocketPoller()
{
BOF_SAFE_DELETE_ARRAY(mpPollOp_X);
BOF_SAFE_DELETE(mpBofSocketForCancellingWait);
Bof_DestroyMutex(mMtx_X);
}
BOFERR BofSocketPoller::LastErrorCode()
{
return mErrorCode_E;
}
BOFERR BofSocketPoller::AddToPollList(SOCKET _Socket, uint32_t &_rIndex_U32)
{
BOFERR Rts_E = BOFERR_INVALID_PARAM;
if (_Socket != INVALID_SOCKET)
{
Rts_E = BOFERR_NO_MORE_HANDLE;
Bof_LockMutex(mMtx_X);
if (mNbSessionPollOp_U32 < mBofSocketPollerParam_X.NbMaxSession_U32)
{
mpPollOp_X[POLL_RESERVED_INDEX_MAX + mNbSessionPollOp_U32].Fd = _Socket;
mpPollOp_X[POLL_RESERVED_INDEX_MAX + mNbSessionPollOp_U32].Event_U16 = POLLIN;
_rIndex_U32=mNbSessionPollOp_U32++;
Rts_E = BOFERR_NO_ERROR;
}
Bof_UnlockMutex(mMtx_X);
}
return Rts_E;
}
BOFERR BofSocketPoller::RemoveFromPollList(uint32_t _Index_U32)
{
BOFERR Rts_E = BOFERR_NOT_FOUND;
Bof_LockMutex(mMtx_X);
if (_Index_U32 < mNbSessionPollOp_U32)
{
if (_Index_U32 != mNbSessionPollOp_U32 - 1) //Not the last one
{
_Index_U32 += POLL_RESERVED_INDEX_MAX;
memmove(&mpPollOp_X[_Index_U32], &mpPollOp_X[_Index_U32 + 1], mNbSessionPollOp_U32 - _Index_U32);
}
mNbSessionPollOp_U32--;
Rts_E = BOFERR_NO_ERROR;
}
Bof_UnlockMutex(mMtx_X);
return Rts_E;
}
BOFERR BofSocketPoller::CancelPollWait()
{
BOFERR Rts_E = BOFERR_INIT;
uint8_t SocketCmd_U8;
uint32_t Nb_U32;
if (mpBofSocketForCancellingWait)
{
Nb_U32 = 1;
SocketCmd_U8 = POLL_SOCKET_CMD_CANCEL_WAIT;
Rts_E = mpBofSocketForCancellingWait->V_WriteData(0, Nb_U32, &SocketCmd_U8);
}
return Rts_E;
}
BOFERR BofSocketPoller::Poll(uint32_t _TimeoutInMs_U32, uint32_t &_rNbPollSet_U32, const BOF_POLL_SOCKET **_ppListOfPollOp_X)
{
BOFERR Rts_E= BOFERR_INVALID_PARAM;
uint8_t SocketCmd_U8;
uint32_t Nb_U32 = 1;
if (_ppListOfPollOp_X)
{
Rts_E = Bof_Poll(_TimeoutInMs_U32, POLL_RESERVED_INDEX_MAX + mNbSessionPollOp_U32, mpPollOp_X, _rNbPollSet_U32);
if (Rts_E == BOFERR_NO_ERROR)
{
*_ppListOfPollOp_X = mpPollOp_X;
if (_rNbPollSet_U32)
{
if (mpPollOp_X[POLL_RESERVED_INDEX_CANCEL].Revent_U16)
{
if (mpBofSocketForCancellingWait)
{
Nb_U32 = 1;
Rts_E = mpBofSocketForCancellingWait->V_ReadData(0, Nb_U32, &SocketCmd_U8);
}
else
{
Rts_E=BOFERR_READ;
}
}
}
}
}
return Rts_E;
}
BOFERR BofSocketPoller::SocketSessionStatistic(std::shared_ptr<BofSocketSession> _psSession, BOF_SOCKET_SESSION_STATISTIC &_rSocketSessionStatistic)
{
BOFERR Rts_E = BOFERR_NOT_FOUND;
auto const It = std::find_if(mSessionCollection.begin(), mSessionCollection.end(), [_psSession](BOF_SOCKET_SESSION Session_X) { return (Session_X.psSocketSession.get() == _psSession.get()); });
if (It != mSessionCollection.end())
{
Rts_E = BOFERR_NOT_AVAILABLE;
if (It->psSocketSession)
{
Rts_E = BOFERR_NO_ERROR;
_rSocketSessionStatistic = It->SocketSessionStatistic_X;
}
}
return Rts_E;
}
BOFERR BofSocketPoller::ResetSocketSessionStatistic(std::shared_ptr<BofSocketSession> _psSession)
{
BOFERR Rts_E = BOFERR_NOT_FOUND;
auto const It = std::find_if(mSessionCollection.begin(), mSessionCollection.end(), [_psSession](BOF_SOCKET_SESSION Session_X) { return (Session_X.psSocketSession.get() == _psSession.get()); });
if (It != mSessionCollection.end())
{
Rts_E = BOFERR_NOT_AVAILABLE;
if (It->psSocketSession)
{
Rts_E = BOFERR_NO_ERROR;
It->SocketSessionStatistic_X.Reset();
}
}
return Rts_E;
}
BOFERR BofSocketPoller::ResetAllSocketSessionStatistic()
{
BOFERR Rts_E = BOFERR_NO_ERROR;
LockThreadCriticalSection();
for (auto Session : mSessionCollection)
{
if (Session.psSocketSession)
{
Session.SocketSessionStatistic_X.Reset();
}
}
UnlockThreadCriticalSection();
return Rts_E;
}
END_BOF_NAMESPACE()
| 34.476793
| 201
| 0.70175
|
onbings
|
a5ea5a6963e0dbc28fa17d5afeacb4686d4231fb
| 3,640
|
cc
|
C++
|
src/SteppingAction.cc
|
ZiliasTheSaint/Interface
|
40b81b85be106a24796097c98de08baf515bd749
|
[
"BSD-3-Clause"
] | null | null | null |
src/SteppingAction.cc
|
ZiliasTheSaint/Interface
|
40b81b85be106a24796097c98de08baf515bd749
|
[
"BSD-3-Clause"
] | null | null | null |
src/SteppingAction.cc
|
ZiliasTheSaint/Interface
|
40b81b85be106a24796097c98de08baf515bd749
|
[
"BSD-3-Clause"
] | null | null | null |
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// D. Fulea, National Institute of Public Health Bucharest, Cluj-Napoca Regional Center, Romania
//
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "SteppingAction.hh"
#include "DetectorConstruction.hh"
#include "EventAction.hh"
#include "G4Step.hh"
#include "G4RunManager.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
SteppingAction::SteppingAction()
{
detector = (DetectorConstruction*)
G4RunManager::GetRunManager()->GetUserDetectorConstruction();
eventaction = (EventAction*)
G4RunManager::GetRunManager()->GetUserEventAction();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
SteppingAction::~SteppingAction()
{ }
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void SteppingAction::UserSteppingAction(const G4Step* aStep)
{
// get volume of the current step
G4VPhysicalVolume* volume
= aStep->GetPreStepPoint()->GetTouchableHandle()->GetVolume();
// collect energy and track length step by step
G4double edep = aStep->GetTotalEnergyDeposit();
G4double stepl = 0.;
if (aStep->GetTrack()->GetDefinition()->GetPDGCharge() != 0.)
stepl = aStep->GetStepLength();
G4ThreeVector pos = aStep->GetPreStepPoint()->GetPosition();
G4double posx = pos.x();//where we are;
//SCORE IT for EACH EVENT (statistic reasons)!!!!!!
if (volume == detector->GetAbsorber()) eventaction->AddAbs(edep,stepl,posx);
if (volume == detector->GetGap()) eventaction->AddGap(edep,stepl,posx);
//example of saving random number seed of this event, under condition
//// if (condition) G4RunManager::GetRunManager()->rndmSaveThisEvent();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| 43.855422
| 96
| 0.583242
|
ZiliasTheSaint
|
a5ebb02fcc679dda17722bd931bbc7f2d4a1139c
| 19,764
|
cpp
|
C++
|
apps/emotion/Sample.cpp
|
AaronTrip/hog2
|
96616b40f4173959b127011c76f3e649688e1a99
|
[
"MIT"
] | 5
|
2020-08-03T09:43:26.000Z
|
2022-01-11T08:28:30.000Z
|
apps/emotion/Sample.cpp
|
AaronTrip/hog2
|
96616b40f4173959b127011c76f3e649688e1a99
|
[
"MIT"
] | null | null | null |
apps/emotion/Sample.cpp
|
AaronTrip/hog2
|
96616b40f4173959b127011c76f3e649688e1a99
|
[
"MIT"
] | 7
|
2017-07-31T13:01:28.000Z
|
2021-05-16T10:15:49.000Z
|
/*
* $Id: sample.cpp,v 1.23 2006/11/01 23:33:56 nathanst Exp $
*
* sample.cpp
* hog
*
* Created by Nathan Sturtevant on 5/31/05.
* Copyright 2005 Nathan Sturtevant, University of Alberta. All rights reserved.
*
* This file is part of HOG.
*
* HOG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* HOG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HOG; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "Common.h"
#include "Sample.h"
#include "UnitSimulation.h"
#include "EpisodicSimulation.h"
#include "RandomUnits.h"
#include "AStar.h"
#include "TemplateAStar.h"
#include "GraphEnvironment.h"
#include "MapSectorAbstraction.h"
#include "GraphRefinementEnvironment.h"
#include "ScenarioLoader.h"
#include "Map2DHeading.h"
#include "GenericSearchUnit.h"
#include "Directional2DEnvironment.h"
bool mouseTracking = false;
bool runningSearch1 = false;
bool runningSearch2 = false;
int px1 = 0, py1 = 0, px2 = 0, py2 = 0;
int absType = 0;
int mazeSize = 20;
int gStepsPerFrame = 2;
double searchWeight = 0;
bool screenShot = false;
bool record = false;
std::vector<UnitSimulation<xyhLoc, xyhAct, Map2DHeading> *> unitSims;
TemplateAStar<graphState, graphMove, GraphEnvironment> astar;
TemplateAStar<xyhLoc, xyhAct, Map2DHeading> a1;
TemplateAStar<xyhLoc, xyhAct, Map2DHeading> a2;
Map2DHeading *ma1 = 0;
Map2DHeading *ma2 = 0;
std::vector<xyhLoc> path;
int main(int argc, char* argv[])
{
InstallHandlers();
RunHOGGUI(argc, argv);
}
/**
* This function is used to allocate the unit simulated that you want to run.
* Any parameters or other experimental setup can be done at this time.
*/
void CreateSimulation(int id)
{
Map *map;
if (gDefaultMap[0] == 0)
{
//ht_chantry.arl.map
// map = new Map("/Users/nathanst/hog2/maps/dao/lak503d.map");
//map = new Map("/Users/nathanst/hog2/maps/da2/ht_chantry.arl.map");
map = new Map("/Users/nathanst/hog2/maps/dao/den312d.map");
// map = new Map("/Users/nathanst/hog2/maps/local/verysmall.map");
//map = new Map("/Users/nathanst/hog2/maps/bgmaps/AR0011SR.map");
//map = new Map("/Users/nathanst/hog2/maps/rooms/8room_000.map");
//map = new Map("/Users/nathanst/hog2/maps/mazes/maze512-16-0.map");
//map = new Map("/Users/nathanst/hog2/maps/local/weight.map");
//map = new Map("weight.map");
// map = new Map(mazeSize, mazeSize);
// MakeMaze(map, 5);
// map->Scale(512, 512);
}
else {
map = new Map(gDefaultMap);
//map->Scale(512, 512);
}
map->SetTileSet(kWinter);
unitSims.resize(id+1);
unitSims[id] = new UnitSimulation<xyhLoc, xyhAct, Map2DHeading>(new Map2DHeading(map));
unitSims[id]->SetStepType(kMinTime);
SetNumPorts(id, 1);
}
/**
* Allows you to install any keyboard handlers needed for program interaction.
*/
void InstallHandlers()
{
InstallKeyboardHandler(MyDisplayHandler, "Toggle Abstraction", "Toggle display of the ith level of the abstraction", kAnyModifier, '0', '9');
InstallKeyboardHandler(MyDisplayHandler, "Cycle Abs. Display", "Cycle which group abstraction is drawn", kAnyModifier, 'q');
InstallKeyboardHandler(MyDisplayHandler, "Pause Simulation", "Pause simulation execution.", kNoModifier, 'p');
InstallKeyboardHandler(MyDisplayHandler, "Step Simulation", "If the simulation is paused, step forward .1 sec.", kNoModifier, 'o');
InstallKeyboardHandler(MyDisplayHandler, "Record", "Start/stop recording movie.", kNoModifier, 'r');
InstallKeyboardHandler(MyDisplayHandler, "Clear Units", "Clear all units.", kAnyModifier, '|');
InstallKeyboardHandler(MyDisplayHandler, "Change weight", "Change the search weight", kNoModifier, 'w');
InstallKeyboardHandler(MyDisplayHandler, "Rotate Compression", "Rotate Compression being shown in heuristic", kAnyModifier, '}');
InstallKeyboardHandler(MyDisplayHandler, "Rotate Displayed Heuristic", "Rotate which heuristic is shown", kAnyModifier, '{');
InstallKeyboardHandler(MyDisplayHandler, "Step Abs Type", "Increase abstraction type", kAnyModifier, ']');
InstallKeyboardHandler(MyDisplayHandler, "Step Abs Type", "Decrease abstraction type", kAnyModifier, '[');
InstallKeyboardHandler(MyPathfindingKeyHandler, "Mapbuilding Unit", "Deploy unit that paths to a target, building a map as it travels", kNoModifier, 'd');
InstallCommandLineHandler(MyCLHandler, "-makeMaze", "-makeMaze x-dim y-dim corridorsize filename", "Resizes map to specified dimensions and saves");
InstallCommandLineHandler(MyCLHandler, "-makeRoom", "-makeRoom x-dim y-dim roomSie filename", "Resizes map to specified dimensions and saves");
InstallCommandLineHandler(MyCLHandler, "-makeRandom", "-makeRandom x-dim y-dim %%obstacles [0-100] filename", "makes a randomly filled with obstacles");
InstallCommandLineHandler(MyCLHandler, "-resize", "-resize filename x-dim y-dim filename", "Resizes map to specified dimensions and saves");
InstallCommandLineHandler(MyCLHandler, "-map", "-map filename", "Selects the default map to be loaded.");
InstallCommandLineHandler(MyCLHandler, "-buildProblemSet", "-buildProblemSet filename", "Build problem set with the given map.");
InstallCommandLineHandler(MyCLHandler, "-problems", "-problems filename sectorMultiplier", "Selects the problem set to run.");
InstallCommandLineHandler(MyCLHandler, "-problems2", "-problems2 filename sectorMultiplier", "Selects the problem set to run.");
InstallCommandLineHandler(MyCLHandler, "-problems3", "-problems3 filename", "Selects the problem set to run.");
InstallCommandLineHandler(MyCLHandler, "-screen", "-screen <map>", "take a screenshot of the screen and then exit");
InstallCommandLineHandler(MyCLHandler, "-size", "-batch integer", "If size is set, we create a square maze with the x and y dimensions specified.");
InstallCommandLineHandler(MyCLHandler, "-reduceMap", "-reduceMap input output", "Find the largest connected component in map and reduce.");
InstallCommandLineHandler(MyCLHandler, "-highwayDimension", "-highwayDimension map radius", "Measure the highway dimension of a map.");
InstallCommandLineHandler(MyCLHandler, "-estimateDimension", "-estimateDimension map", "Estimate the dimension.");
InstallCommandLineHandler(MyCLHandler, "-estimateLongPath", "-estimateLongPath map", "Estimate the longest path in the map.");
InstallCommandLineHandler(MyCLHandler, "-testHeuristic", "-testHeuristic scenario", "measure the ratio of the heuristic to the optimal dist");
InstallWindowHandler(MyWindowHandler);
InstallMouseClickHandler(MyClickHandler);
}
void MyWindowHandler(unsigned long windowID, tWindowEventType eType)
{
if (eType == kWindowDestroyed)
{
printf("Window %ld destroyed\n", windowID);
RemoveFrameHandler(MyFrameHandler, windowID, 0);
delete unitSims[windowID];
unitSims[windowID] = 0;
runningSearch1 = false;
runningSearch2 = false;
mouseTracking = false;
}
else if (eType == kWindowCreated)
{
printf("Window %ld created\n", windowID);
InstallFrameHandler(MyFrameHandler, windowID, 0);
CreateSimulation(windowID);
SetNumPorts(windowID, 1);
}
}
void MyFrameHandler(unsigned long windowID, unsigned int viewport, void *)
{
if (viewport == 0)
{
unitSims[windowID]->StepTime(1.0/30.0);
}
unitSims[windowID]->OpenGLDraw();
if (mouseTracking)
{
glBegin(GL_LINES);
glColor3f(1.0f, 0.0f, 0.0f);
Map *m = unitSims[windowID]->GetEnvironment()->GetMap();
GLdouble x, y, z, r;
m->GetOpenGLCoord(px1, py1, x, y, z, r);
glVertex3f(x, y, z-3*r);
m->GetOpenGLCoord(px2, py2, x, y, z, r);
glVertex3f(x, y, z-3*r);
glEnd();
}
if ((ma1) && (viewport == 0)) // only do this once...
{
ma1->SetColor(0.0, 0.5, 0.0, 0.75);
if (runningSearch1 && !unitSims[windowID]->GetPaused())
{
ma1->SetColor(0.0, 0.0, 1.0, 0.75);
for (int x = 0; x < gStepsPerFrame*4; x++)
{
if (a1.DoSingleSearchStep(path))
{
printf("Solution: moves %d, length %f, %lld nodes, %u on OPEN\n",
(int)path.size(), ma1->GetPathLength(path), a1.GetNodesExpanded(),
a1.GetNumOpenItems());
runningSearch1 = false;
break;
}
}
}
a1.OpenGLDraw();
}
if (record)
{
static int cnt = 0;
char fname[255];
sprintf(fname, "/Users/nathanst/Movies/MIG/MIG%d%d%d", (cnt/100)%10, (cnt/10)%10, cnt%10);
SaveScreenshot(windowID, fname);
printf("Saved %s\n", fname);
cnt++;
}
}
int MyCLHandler(char *argument[], int maxNumArgs)
{
if (strcmp( argument[0], "-screen" ) == 0 )
{
if (maxNumArgs <= 1)
return 0;
screenShot = true;
strncpy(gDefaultMap, argument[1], 1024);
return 2;
}
if (strcmp( argument[0], "-map" ) == 0 )
{
if (maxNumArgs <= 1)
return 0;
strncpy(gDefaultMap, argument[1], 1024);
Map map(argument[1]);
map.Scale(512, 512);
map.Save(argument[2]);
//buildProblemSet();
//doExport();
exit(0);
return 2;
}
return 2; //ignore typos
}
void MyDisplayHandler(unsigned long windowID, tKeyboardModifier mod, char key)
{
switch (key)
{
case 'r':
if (record)
unitSims[windowID]->GetEnvironment()->drawWeights = true;
record = !record;
break;
case 'w':
if (searchWeight == 0)
searchWeight = 1.0;
else if (searchWeight == 1.0)
searchWeight = 10.0;
else if (searchWeight == 10.0)
searchWeight = 0;
break;
case '[': if (gStepsPerFrame >= 2) gStepsPerFrame /= 2; break;
case ']': gStepsPerFrame *= 2; break;
case '|': unitSims[windowID]->ClearAllUnits();
unitSims[windowID]->GetEnvironment()->ClearAllCosts(); break;
case '{':
break;
case '}':
break;
case 'q':
if (mod != kShiftDown)
SetActivePort(windowID, (GetActivePort(windowID)+1)%GetNumPorts(windowID));
else
{
SetNumPorts(windowID, 1+(GetNumPorts(windowID)%MAXPORTS));
}
break;
case 'p': unitSims[windowID]->SetPaused(!unitSims[windowID]->GetPaused()); break;
case 'o':
{
if (runningSearch1)
{
if (a1.DoSingleSearchStep(path))
{
printf("Solution: moves %d, length %f, %lld nodes\n",
(int)path.size(), ma1->GetPathLength(path), a1.GetNodesExpanded());
runningSearch1 = false;
}
}
if (runningSearch2)
{
if (a2.DoSingleSearchStep(path))
{
printf("Solution: moves %d, length %f, %lld nodes\n",
(int)path.size(), ma1->GetPathLength(path), a2.GetNodesExpanded());
runningSearch2 = false;
}
}
}
break;
default:
break;
}
}
void ExportGraph(Map *m, Map2DHeading *env);
void ExportGraph(Map *m);
void MyPathfindingKeyHandler(unsigned long windowID, tKeyboardModifier , char)
{
//ExportGraph(unitSims[windowID]->GetEnvironment()->GetMap(), unitSims[windowID]->GetEnvironment());
ExportGraph(unitSims[windowID]->GetEnvironment()->GetMap());
}
void ExportGraph(Map *m, Map2DHeading *env)
{
// export map as graph
typedef __gnu_cxx::hash_map<uint64_t, int, Hash64> HT;
HT table;
Graph *g = new Graph();
// build nodes
for (int x = 0; x < m->GetMapWidth(); x++)
{
for (int y = 0; y < m->GetMapHeight(); y++)
{
if (m->GetTerrainType(x, y) == kGround)
{
for (int h = 0; h < 8; h++)
{
xyhLoc l;
l.x = x;
l.y = y;
l.h = h;
table[env->GetStateHash(l)] = g->AddNode(new node("n"));
// std::cout << table[env->GetStateHash(l)] << " : " << l << std::endl;
}
}
}
}
// build edges
std::vector<xyhLoc> succ;
for (int x = 0; x < m->GetMapWidth(); x++)
{
for (int y = 0; y < m->GetMapHeight(); y++)
{
if (m->GetTerrainType(x, y) == kGround)
{
for (int h = 0; h < 8; h++)
{
xyhLoc l;
l.x = x;
l.y = y;
l.h = h;
env->GetSuccessors(l, succ);
int from = table[env->GetStateHash(l)];
int to;
for (unsigned int t = 0; t < succ.size(); t++)
{
to = table[env->GetStateHash(succ[t])];
g->AddEdge(new edge(from, to, env->GCost(l, succ[t])));
}
}
}
}
}
// export edges
printf("%d nodes %d edges\n", g->GetNumNodes(), g->GetNumEdges());
std::cout << "nodes:" << std::endl;
for (int x = 0; x < m->GetMapWidth(); x++)
{
for (int y = 0; y < m->GetMapHeight(); y++)
{
if (m->GetTerrainType(x, y) == kGround)
{
for (int h = 0; h < 8; h++)
{
xyhLoc l;
l.x = x;
l.y = y;
l.h = h;
std::cout << table[env->GetStateHash(l)] << "\t" << l.x << "\t" << l.y << std::endl;
// std::cout << table[env->GetStateHash(l)] << " : " << l << std::endl;
}
}
}
}
std::cout << "edges:" << std::endl;
for (unsigned int x = 0; x < g->GetNumEdges(); x++)
{
edge *e = g->GetEdge(x);
printf("%d\t%d\t%1.2f\n", e->getFrom(), e->getTo(), e->GetWeight());
}
}
void ExportGraph(Map *m)
{
Directional2DEnvironment *env = new Directional2DEnvironment(m, kVehicle, kOctileHeuristic);
// export map as graph
typedef __gnu_cxx::hash_map<uint64_t, int, Hash64> HT;
HT table;
Graph *g = new Graph();
// build nodes
for (int x = 0; x < m->GetMapWidth(); x++)
{
for (int y = 0; y < m->GetMapHeight(); y++)
{
if (m->GetTerrainType(x, y) == kGround)
{
for (int s = -1; s <= 3; s++)
{
for (int h = 0; h < 16; h++)
{
xySpeedHeading l;
l.x = x;
l.y = y;
l.rotation = h;
l.speed = s;
table[env->GetStateHash(l)] = g->AddNode(new node("n"));
// std::cout << table[env->GetStateHash(l)] << " : " << l << std::endl;
}
}
}
}
}
// build edges
std::vector<xySpeedHeading> succ;
for (int x = 0; x < m->GetMapWidth(); x++)
{
for (int y = 0; y < m->GetMapHeight(); y++)
{
if (m->GetTerrainType(x, y) == kGround)
{
for (int s = -1; s <= 3; s++)
{
for (int h = 0; h < 16; h++)
{
xySpeedHeading l;
l.x = x;
l.y = y;
l.rotation = h;
l.speed = s;
env->GetSuccessors(l, succ);
int from = table[env->GetStateHash(l)];
int to;
for (unsigned int t = 0; t < succ.size(); t++)
{
to = table[env->GetStateHash(succ[t])];
g->AddEdge(new edge(from, to, env->GCost(l, succ[t])));
}
}
}
}
}
}
// export edges
printf("%d nodes %d edges\n", g->GetNumNodes(), g->GetNumEdges());
std::cout << "nodes:" << std::endl;
for (int x = 0; x < m->GetMapWidth(); x++)
{
for (int y = 0; y < m->GetMapHeight(); y++)
{
if (m->GetTerrainType(x, y) == kGround)
{
for (int s = -1; s <= 3; s++)
{
for (int h = 0; h < 16; h++)
{
xySpeedHeading l;
l.x = x;
l.y = y;
l.rotation = h;
l.speed = s;
std::cout << table[env->GetStateHash(l)] << "\t" << l.x << "\t" << l.y << std::endl;
// std::cout << table[env->GetStateHash(l)] << " : " << l << std::endl;
}
}
}
}
}
std::cout << "edges:" << std::endl;
for (unsigned int x = 0; x < g->GetNumEdges(); x++)
{
edge *e = g->GetEdge(x);
printf("%d\t%d\t%1.2f\n", e->getFrom(), e->getTo(), e->GetWeight());
}
}
xyLoc queryLoc;
bool validQuery = false;
bool MyClickHandler(unsigned long windowID, int, int, point3d loc, tButtonType button, tMouseEventType mType)
{
// return false;
static point3d startLoc;
switch (button)
{
case kRightButton: printf("Right button\n"); break;
case kLeftButton: printf("Left button\n"); break;
case kMiddleButton: printf("Middle button\n"); break;
}
mouseTracking = false;
if ((button == kRightButton) && (mType == kMouseDown))
{
unitSims[windowID]->GetEnvironment()->GetMap()->GetPointFromCoordinate(loc, px1, py1);
xyhLoc t;
t.x = px1; t.y = py1; t.h = 4;
GenericSearchUnit<xyhLoc, xyhAct, Map2DHeading> *gsu;
gsu = new GenericSearchUnit<xyhLoc, xyhAct, Map2DHeading>(t, t, &a2);
unitSims[windowID]->AddUnit(gsu);
gsu->SetColor(0.0, 1.0, 0.0);
unitSims[windowID]->GetEnvironment()->SetCost(t, -1.0, 5);
printf("Added unit at (%d, %d)\n", px1, py1);
return true;
// if (validQuery == false)
// {
// validQuery = true;
// queryLoc.x = px1;
// queryLoc.y = py1;
// }
// else {
// // compute angle, assuming facing upwards at given location
// float heading = atan2(px1-queryLoc.x, py1-queryLoc.y);
// int conv = (360.0*heading/(2*3.1415)+180+270); // -90 for face left
// conv = conv%360;
// if (conv > 180)
// conv = 360-conv;
// printf("Relative heading: %d\n", conv);
// for (float P = -1; P <= 1; P += 0.5)
// {
// //float cost = (P<0)?((1.0-(float)conv/90.0)*(-P)):(((float)conv/90.0-1.0)*(P));
// float cost = -P*cos(2*3.1415*conv/360.0);
// printf("P : %1.2f C : %1.2f\n", P, cost);
// }
// }
//printf("Added heuristic at %d, %d\n", px1, px2);
return false;
}
if (button == kLeftButton)
{
switch (mType)
{
case kMouseDown:
unitSims[windowID]->GetEnvironment()->GetMap()->GetPointFromCoordinate(loc, px1, py1);
startLoc = loc;
//printf("Mouse down at (%d, %d)\n", px1, py1);
break;
case kMouseDrag:
mouseTracking = true;
unitSims[windowID]->GetEnvironment()->GetMap()->GetPointFromCoordinate(loc, px2, py2);
//printf("Mouse tracking at (%d, %d)\n", px2, py2);
break;
case kMouseUp:
{
if ((px1 == -1) || (px2 == -1))
break;
unitSims[windowID]->GetEnvironment()->GetMap()->GetPointFromCoordinate(loc, px2, py2);
//px1 = 128; py1 = 181; px2 = 430; py2 = 364; //128 181 430 364
printf("Searching from (%d, %d) to (%d, %d)\n", px1, py1, px2, py2);
if (ma1 == 0)
{
ma1 = new Map2DHeading(unitSims[windowID]->GetEnvironment()->GetMap());
}
if (ma2 == 0)
{
ma2 = new Map2DHeading(unitSims[windowID]->GetEnvironment()->GetMap());
}
a1.SetStopAfterGoal(true);
a2.SetStopAfterGoal(true);
//a2.SetWeight(1.8);
xyhLoc s1;
xyhLoc g1;
s1.x = px1; s1.y = py1; s1.h = 0;
g1.x = px2; g1.y = py2; g1.h = 4;
ma1->SetFourConnected();
a1.InitializeSearch(ma1, s1, g1, path);
a2.InitializeSearch(ma2, s1, g1, path);
runningSearch1 = false;
runningSearch2 = false;
// unitSims[windowID]->ClearAllUnits();
// unitSims[windowID]->GetEnvironment()->ClearAllCosts();
xyhLoc forbid = g1;
forbid.x-=1;
forbid.h =0;
unitSims[windowID]->GetEnvironment()->SetCost(forbid, -1.0, 10);
forbid.x+=15;
forbid.y+=5;
forbid.h =2+4;
//unitSims[windowID]->GetEnvironment()->SetCost(forbid, -0.2);
std::cout << "Avoiding target: " << forbid << std::endl;
// for (int x = -4; x < 2; x++)
// {
// forbid.x = g1.x+x;
// for (int y = -3; y <= 3; y++)
// {
// forbid.y = g1.y+y;
// if (x >= 0 && y == 0)
// continue;
// for (int rot = 0; rot < 8; rot++)
// {
// forbid.h = rot;
// unitSims[windowID]->GetEnvironment()->SetCost(forbid, 5.0);
// }
// }
// }
GenericSearchUnit<xyhLoc, xyhAct, Map2DHeading> *gsu;
gsu = new GenericSearchUnit<xyhLoc, xyhAct, Map2DHeading>(s1, g1, &a2);
gsu->SetSpeed(0.25);
unitSims[windowID]->AddUnit(gsu);
g1.h = 0;
g1.x -= 1;
gsu = new GenericSearchUnit<xyhLoc, xyhAct, Map2DHeading>(g1, g1, &a2);
unitSims[windowID]->AddUnit(gsu);
gsu->SetColor(0.0, 1.0, 0.0);
// gsu = new GenericSearchUnit<xyhLoc, xyhAct, Map2DHeading>(forbid, forbid, &a2);
// unitSims[windowID]->AddUnit(gsu);
// gsu->SetColor(0.0, 1.0, 0.0);
//(state &start, state &goal, GenericSearchAlgorithm<state,action,environment> *alg);
}
break;
}
return true;
}
return false;
}
| 30.73717
| 155
| 0.63302
|
AaronTrip
|
a5ee2069ca51a7a1a0cde7a8c051d7881e7a0e81
| 524
|
hpp
|
C++
|
gv_framework/component/gv_com_static_mesh.hpp
|
dragonsn/gv_game_engine
|
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
|
[
"MIT"
] | 2
|
2018-12-03T13:17:31.000Z
|
2020-04-08T07:00:02.000Z
|
gv_framework/component/gv_com_static_mesh.hpp
|
dragonsn/gv_game_engine
|
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
|
[
"MIT"
] | null | null | null |
gv_framework/component/gv_com_static_mesh.hpp
|
dragonsn/gv_game_engine
|
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
|
[
"MIT"
] | null | null | null |
namespace gv
{
gv_com_static_mesh::gv_com_static_mesh()
{
link_class(gv_com_static_mesh::static_class());
};
gv_com_static_mesh::~gv_com_static_mesh(){
};
bool gv_com_static_mesh::set_resource(gv_resource* resource)
{
gv_static_mesh* s_mesh = gvt_cast< gv_static_mesh >(resource);
if (!s_mesh)
return false;
gv_com_graphic::set_resource(s_mesh);
this->m_static_mesh = s_mesh;
return true;
};
GVM_IMP_CLASS(gv_com_static_mesh, gv_com_graphic)
GVM_VAR(gvt_ref_ptr< gv_static_mesh >, m_static_mesh)
GVM_END_CLASS
}
| 20.153846
| 63
| 0.788168
|
dragonsn
|
a5f2d4b4e3997f1a16e26a300803612ca4d8fe83
| 327
|
cpp
|
C++
|
Linked List/07_move_last_to_first.cpp
|
ritikrajdev/450DSA
|
a9efa8c8be781fd7b101407ac807a83b8a0929f4
|
[
"MIT"
] | null | null | null |
Linked List/07_move_last_to_first.cpp
|
ritikrajdev/450DSA
|
a9efa8c8be781fd7b101407ac807a83b8a0929f4
|
[
"MIT"
] | null | null | null |
Linked List/07_move_last_to_first.cpp
|
ritikrajdev/450DSA
|
a9efa8c8be781fd7b101407ac807a83b8a0929f4
|
[
"MIT"
] | null | null | null |
typedef LinkedListNode<int> Node;
LinkedListNode<int>* moveToFront(LinkedListNode<int> *head) {
if (!head->next)
return head;
Node* prev = 0;
Node* itr = head;
while (itr->next) {
prev = itr;
itr = itr->next;
}
prev->next = 0;
itr->next = head;
return itr;
}
| 17.210526
| 61
| 0.535168
|
ritikrajdev
|
a5f5f3104802acfce47beb45bd8c4a995b5056cb
| 18,952
|
cpp
|
C++
|
src/edit.cpp
|
sidtheprince/dokun
|
9aec583eac05e5e6db18a7df11b20df40a9dcf5d
|
[
"MIT"
] | 2
|
2018-10-01T18:13:51.000Z
|
2019-12-20T06:22:32.000Z
|
src/edit.cpp
|
sidtheprince/dokun
|
9aec583eac05e5e6db18a7df11b20df40a9dcf5d
|
[
"MIT"
] | null | null | null |
src/edit.cpp
|
sidtheprince/dokun
|
9aec583eac05e5e6db18a7df11b20df40a9dcf5d
|
[
"MIT"
] | null | null | null |
#include "../include/edit.h"
Edit::Edit() : color(160, 160, 160, 255), character_limit(20),
cursor(true), cursor_x(0), cursor_y(0), cursor_height(20), zoom_factor(0), multilined(false), num_newlines(0), label(nullptr),
// outline
outline(false),
outline_width(1.0),
outline_color(0, 0, 0, 255),
outline_antialiased(false),
// gradient
gradient(false),
gradient_color(color)
{
set_position(0, 0);
set_size(200, 20); // 150, 20
set_orientation(0);
}
/////////////
Edit::~Edit()
{}
/////////////
void Edit::append(const std::string& text)
{
set_text(get_text() + text);
}
/////////////
int Edit::append(lua_State *L)
{
return 0;
}
/////////////
void Edit::draw()
{
if(is_visible()) // is it visible?
{
if(is_active()) // is it disabled?
{}
// callbacks
on_hover();// if mouse over edit, change mouse to I-beam
//on_mousepress();// edit is pressed, set cursor at position_pressed
on_keypress();
on_backspace();
on_enter();
on_arrow_keys();
double x = get_position().x;
double y = get_position().y;
double angle = get_angle();
double scale_x = get_scale().x;
double scale_y = get_scale().y;
int width = get_width();
int height = get_height();
int red = get_color().x;
int green = get_color().y;
int blue = get_color().z;
int alpha = get_color().w;
void * font = (get_label() ? get_label()->get_font()->get_data() : nullptr);
Vector4 text_color = get_text_color();
// Draw edit
Renderer::draw_edit(get_text(), x, y, width, height, angle, scale_x, scale_y,
red, green, blue, alpha, multilined, cursor, cursor_x, cursor_y, cursor_height);
// Draw text
if(label) label->set_position(get_x() + label->get_relative_x(), get_y() + label->get_relative_y()); // label position stays the same - on the edit, but the cursor is the only thing that moves
// Callback
on_draw(); // draw children
}
}
/////////////
int Edit::draw(lua_State *L)
{
return 0;
}
/////////////
void Edit::cut()
{}
/////////////
int Edit::cut(lua_State *L)
{
return 0;
}
/////////////
void Edit::copy()
{}
/////////////
int Edit::copy(lua_State *L)
{
return 0;
}
/////////////
void Edit::paste()
{
#ifdef __windows__
if(!OpenClipboard(nullptr)) // open clipboard
{
return;
}
append( (const char *)GetClipboardData(CF_TEXT) );
#endif
}
/////////////
int Edit::paste(lua_State *L)
{
return 0;
}
/////////////
void Edit::undo()
{}
/////////////
int Edit::undo(lua_State *L)
{
return 0;
}
/////////////
void Edit::redo()
{}
/////////////
int Edit::redo(lua_State *L)
{
return 0;
}
/////////////
void Edit::select()
{}
/////////////
int Edit::select(lua_State *L)// (highlights specific text) or all
{
return 0;
}
/////////////
void select_all()
{}
/////////////
int select_all(lua_State *L)
{
return 0;
}
/////////////
void Edit::clear()
{}
/////////////
int Edit::clear(lua_State *L)// (std::string selected_text) or all
{
return 0;
}
/////////////
void Edit::clear_all()
{
get_label()->set_string("");
}
/////////////
int Edit::clear_all(lua_State *L)// (std::string selected_text) or all
{
return 0;
}
/////////////
void Edit::zoom(int value)
{}
/////////////
int Edit::zoom(lua_State *L)// -1 (zoom out), +1 (zoom in)
{
return 0;
}
/////////////
// SETTERS
/////////////
void Edit::set_color(int red, int green, int blue, int alpha) // base_color
{
color = Vector4(red, green, blue, alpha);
}
/////////////
void Edit::set_color(const Vector3& color)
{
set_color(color.x, color.y, color.z);
}
/////////////
void Edit::set_color(const Vector4& color)
{
set_color(color.x, color.y, color.z, color.w);
}
/////////////
int Edit::set_color(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_cursor(bool cursor)
{
(this)->cursor = cursor;
}
/////////////
int Edit::set_cursor(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_cursor_x(double x)
{
// cannot go past the width of the edit
if(x >= get_width()) {cursor_x = get_width();return;}
if(x <= 0) {cursor_x = 0;return; }
cursor_x = x;
}
/////////////
void Edit::set_cursor_y(double y)
{
cursor_y = y;
}
/////////////
void Edit::set_cursor_position(double x, double y)
{
set_cursor_x(x);
set_cursor_y(y);
}
/////////////
void Edit::set_cursor_position(const Vector2& position)
{
set_cursor_position(position.x, position.y);
}
/////////////
/////////////
int Edit::set_cursor_position(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_label(const Label& label)
{
this->label = &const_cast<Label&>(label);
this->label->set_parent(* this);
}
/////////////
int Edit::set_label(lua_State *L)
{
return 0;
}
/////////////
// TEXT-RELATED
/////////////
void Edit::set_text(const std::string& text)
{
std::string string0 (text);
if(string0.length() > get_character_limit()) // character limit has been reached. Character limit is user-defined but can NEVER exceed edit capacity
{
string0 = string0.erase(string0.length() - string0.length() + get_character_limit());
#ifdef DOKUN_DEBUG
std::cout << "Cannot exceed " << get_character_limit() << " character limit!" << std::endl;
#endif
return; // exit function
}
if(cursor_x >= get_width()) // cursor cannot go past edit
{
// keep label from going past edit. Set character limit to 50
if(!is_multilined()) {
string0.resize(get_capacity());
#ifdef DOKUN_DEBUG1
std::cout << "Text Edit can only hold " << get_capacity() << " characters based on its size!" << std::endl;
std::cout << "Characters in text: " << get_text().size() << std::endl;
#endif
}
if(is_multilined()) // if multilined=true, create a new line // a multilined editor
{
char last_char = String::get_last_character(string0);
// remove last (51th) chatracter
string0 = string0.erase(string0.length() - 1);//std::cout << last_char << " removed\n";
int char_height = label->get_font()->get_height();
// double the height of the edit
set_height(get_height() + char_height); // GOOD!
// add a newline in text (basically replaces last_char with a newline)
string0.append("\n"); num_newlines = num_newlines + 1;
// also append the last character
string0.append(String::to_string(last_char)); // finally append last (51th) character to the newline
// reset cursor x position - try to get location of newline
set_cursor_x(0);
// set cursor y position (bring it down)
set_cursor_y(cursor_y + char_height);
}
}
get_label()->set_string(string0);
}
/////////////
int Edit::set_text(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_font(const FONT& font)
{
get_label()->set_font(font); // set label font (if already exist)
}
/////////////
int Edit::set_font(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_text_color(int red, int green, int blue, int alpha)
{
label->set_color(red, green, blue, alpha);
}
/////////////
void Edit::set_text_color(const Vector3& color)
{
set_text_color(color.x, color.y, color.z);
}
/////////////
void Edit::set_text_color(const Vector4& color)
{
set_text_color(color.x, color.y, color.z, color.w);
}
/////////////
int Edit::set_text_color(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_text_size(int width, int height)
{
get_label()->set_size(width, height);
}
/////////////
int Edit::set_text_size(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_text_style(int style)
{
get_label()->set_style(style);
}
/////////////
int Edit::set_text_style(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_text_background_color(int red, int green, int blue, int alpha)
{
get_label()->set_background_color(red, green, blue, alpha);
}
/////////////
int Edit::set_text_background_color(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_character_limit(int limit)
{
this->character_limit = limit;
}
/////////////
int Edit::set_maximum_character(lua_State *L)
{
return 0;
}
/////////////
void Edit::set_multilined(bool multilined)
{
this->multilined = multilined;
}
/////////////
/////////////
/////////////
/////////////
// GETTERS
/////////////
Label * Edit::get_label()const
{
return label;
}
/////////////
int Edit::get_label(lua_State *L)
{
return 0;
}
/////////////
std::string Edit::get_text()const
{
return get_label()->get_string();
}
/////////////
int Edit::get_text(lua_State *L)
{
return 0;
}
/////////////
Vector4 Edit::get_color()const
{
return color;
}
/////////////
int Edit::get_color(lua_State *L)
{
return 0;
}
/////////////
int Edit::get_cursor_x() const
{
return cursor_x;
}
/////////////
int Edit::get_cursor_y() const
{
return cursor_y;
}
/////////////
Vector2 Edit::get_cursor_position()const
{
return Vector2(cursor_x, cursor_y);
}
/////////////
int Edit::get_cursor_position(lua_State *L)
{
return 0;
}
/////////////
FONT * Edit::get_font()const
{
return get_label()->get_font();
}
/////////////
int Edit::get_font(lua_State *L)
{
return 1;
}
/////////////
Vector4 Edit::get_text_color()const
{
return get_label()->get_color();
}
/////////////
int Edit::get_text_color(lua_State *L)
{
return 4;
}
/////////////
Vector2 Edit::get_text_size()const
{
return get_label()->get_size();
}
/////////////
int Edit::get_text_size(lua_State *L)
{
return 2;
}
/////////////
int Edit::get_text_style()const
{
return get_label()->get_style();
}
/////////////
int Edit::get_text_style(lua_State *L)
{
return 1;
}
/////////////
Vector4 Edit::get_text_background_color()const
{
return get_label()->get_background_color();
}
/////////////
int Edit::get_text_background_color(lua_State *L)
{
return 4;
}
/////////////
int Edit::get_character_limit()const
{
return character_limit;
}
/////////////
int Edit::get_capacity() const // returns the total number of characters an edit is able to hold
{
if(is_multilined()) return (get_width() / 10) * (get_height() / round(label->get_height()/*10*/));
return (get_width() / 10);
}
/////////////
int Edit::get_capacity(lua_State *L)
{
return 1;
}
/////////////
int Edit::get_horizontal_capacity() const // returns number of characters a non-multilined edit can hold. A width of 200 would mean a capacity of 20 characters
{
return (get_width() / 10);
}
/////////////
int Edit::get_horizontal_capacity(lua_State *L)
{
return 1;
}
/////////////
int Edit::get_vertical_capacity() const // returns number of newlines an edit is cabable of (based on its height and the height of the label)
{
return (get_height() / round(label->get_height()/*10*/)); // same as console and chatbox
}
/////////////
int Edit::get_vertical_capacity(lua_State *L)
{
return 1;
}
/////////////
/////////////
/////////////
bool Edit::is_multilined() const
{
return (multilined == true);
}
/////////////
/////////////
/////////////
void Edit::on_hover()
{
if(Mouse::is_over(get_position(), get_size()))
{
// change mouse cursor to I-beam
WINDOW * window = WINDOW::get_active();
if(window != nullptr)
{
#ifdef __windows__
HCURSOR ibeam = LoadCursor(nullptr, IDC_IBEAM);
//SetCursor(HCURSOR hCursor);//SetClassLong(window->get_handle(), GCL_HCURSOR, (DWORD)ibeam); // DWORD = unsigned long
#endif
#ifdef __gnu_linux__
#ifdef DOKUN_X11
Cursor cursor = XCreateFontCursor(window->get_display(), XC_xterm);
XDefineCursor(window->get_display(), window->get_handle(), cursor);
XFreeCursor(window->get_display(), cursor);
#endif
#endif
}
} else { // revert back to original mouse cursor
WINDOW * window = WINDOW::get_active();
if(window != nullptr)
{
#ifdef __windows__
HCURSOR arrow = LoadCursor(nullptr, IDC_ARROW);
//SetCursor(HCURSOR hCursor);//SetClassLong(window->get_handle(), GCL_HCURSOR, (DWORD)arrow);
#endif
#ifdef __gnu_linux__
#ifdef DOKUN_X11
Cursor cursor = XCreateFontCursor(window->get_display(), XC_left_ptr);
XDefineCursor(window->get_display(), window->get_handle(), cursor);
XFreeCursor(window->get_display(), cursor);
#endif
#endif
}
}
}
/////////////
void Edit::on_mousepress()
{
if(!Mouse::is_over(get_rect())) return; // mouse_not_over_edit, return
if(Mouse::is_over(get_position(), (get_text().size() * 10)+10)) // mouse_over_text
{
if(Mouse::is_pressed(1))
{
WINDOW * window = WINDOW::get_active();
if(window == nullptr) return;
double x = fabs((double)Mouse::get_position(*window).x - (double)(get_x() + cursor_x)); // abs() for int, fabs() for decimals//if(x < 0) x = -x; = makes negative numbers into a positive
set_cursor_position(round(x), cursor_y);//round to the nearest tenth//get_y() - Mouse::get_position(*window).y);//cursor_changed_by_mouse = true; // add chars to location of cursor : get_text().size() / cursor_x
}
}
}
/////////////
void Edit::on_keypress()
{
for(unsigned char key = 0; key < 128; key++) //if(Keyboard::is_down())
{
//char key = static_cast<char>(Keyboard::key);
if(Keyboard::is_pressed(key))
{
#ifdef DOKUN_DEBUG0
std::cout << key << " pressed\n";
#endif
//if(isascii(key)) { set_text(get_text() + std::to_string(int(key))); set_cursor_x(cursor_x + 10); return; }
// number or letter or punctuation or space
if(isalnum(key) || ispunct(key) || isspace(key))
{
// insert character in string //set_text(get_text() + String::to_string(key)); // old way of appending characters
std::string temp(get_text());
int string_index = ((cursor_x + 10) / 10) - 1; // get character at string_index (where cursor_x is) // add cursor_x to increment (10) before we increase cursor_x by 10.
temp.insert(string_index, String::to_string(key)); // insert character in between string (+10=advance_to_next_spot)
set_text(temp); // set text
//increment by 10 for each character
set_cursor_x(cursor_x + 10); // label_width does not give accurate results so DO NOT use! Use 10 instead.
// store character position (for later use)
if(character_data.size() >= get_character_limit()) return; // character_position_data must NOT exceed the number of characters in string! // if character limit has been reached, exit function (so character_data does not push_back more unnecessary characters ...)
int cursor_index = ((get_text().length() > get_character_limit()) ? -1 : cursor_x);//cursor_x;
character_data.push_back(std::make_tuple((char)key, cursor_index, string_index)); // save character's index in cursor and index in string
#ifdef DOKUN_DEBUG // print some cool stuff here ...
std::cout << "\"" << std::get<0>(character_data[character_data.size() - 1]) << "\": cursor_position= " << std::get<1>(character_data[character_data.size() - 1]) << " | position_in_string= " << std::get<2>(character_data[character_data.size() - 1]) << std::endl; // for debug + testing purposes
#endif
return;
}
}
}
}
/////////////
void Edit::on_backspace()
{
if(get_text().empty()) return; // empty string, return (so it does not crash engine)
#ifdef __windows__
if(Keyboard::is_pressed(0x08))
#endif
#ifdef __gnu_linux__
if(Keyboard::is_pressed(0xff08))
#endif
{
char last_char = String::get_last_character(label->get_string()); // get last character in text (before erasing it) // make sure text is not empty so you can operate on it (to prevent crash) if(get_text().empty()) return;
// erase last character in string //if(get_text().length() > 0) set_text(get_text().erase(get_text().length() - 1)); // old way of deleting characters
if(get_text().length() > 0)
{
int string_index = (cursor_x / 10) - 1; // get character at string_index - This will give you the character's position in the string (where cursor_x is at) // before deletion // string_index is probably causing seg fault
#ifdef DOKUN_DEBUG0
std::cout << "string_index of deleted character at cursor_x: " << string_index << std::endl;
#endif
std::string temp(get_text()); // copy of label_string
temp.erase(temp.begin() + string_index); // erase character at string_index
set_text(temp); // set text
// bring cursor_x back, on character deletion
set_cursor_x(cursor_x - 10);
// remove deleted character from data
character_data.erase(character_data.begin() + string_index); // if string_index=5. deletes 6th element
#ifdef DOKUN_DEBUG0
std::cout << "\"" << last_char << "\" deleted" << std::endl;
std::cout << "string_index of last character at cursor_x: " << (cursor_x / 10) - 1 << std::endl; // after deletion // returns "-1" if last_character does not exist (string is empty)
std::cout << "character_data size: " << ((character_data.empty()) ? 0 : character_data.size()) << std::endl;
#endif
}
////////////////////////////////////////////////////////////// temp
// This deals with cursor_y which is ONLY for multilined edit!
// if a newline is removed, decrease the size of the edit
if(last_char == '\n' && multilined) {
int char_height = label->get_font()->get_height();
set_height(get_height() - char_height);
// decrease num_newlines
num_newlines = num_newlines - 1;
// bring cursor_y back up (if erasing newline)
set_cursor_y(cursor_y - char_height);
}
// reset cursor position if text is empty
if(get_text ().empty()) set_cursor_position(0, 0);
// clear character_position_data if text is empty
if(get_text ().empty()) character_data.clear ();
}
}
/////////////
void Edit::on_enter()
{
#ifdef __windows__
if(Keyboard::is_pressed(0x0D))
#endif
#ifdef __gnu_linux__
if(Keyboard::is_pressed(0xff0d))
#endif
{
if(is_multilined()) // a multilined editor
{
int char_height = label->get_font()->get_height();
// double the height of the edit
set_height(get_height() + char_height); // GOOD!
// add a newline in text
set_text(get_text() + "\n");
num_newlines = num_newlines + 1;
// reset cursor x position - try to get location of newline
set_cursor_x(0);
// set cursor y position (bring it down)
set_cursor_y(cursor_y + char_height);
}
}
}
/////////////
void Edit::on_arrow_keys()
{
if(Keyboard::is_pressed(DOKUN_KEY_LEFT )) set_cursor_x(cursor_x - 10);
// prevent cursor_x from going beyond "end of string"
if(cursor_x < (label->get_string().size() * 10)) { if(Keyboard::is_pressed(DOKUN_KEY_RIGHT)) set_cursor_x(cursor_x + 10); } // <=
//if(Keyboard::is_pressed(DOKUN_KEY_UP))
//if(Keyboard::is_pressed(DOKUN_KEY_DOWN))
}
/////////////
// void Edit::on_left_mouse()
//{
// // show list
//}
/////////////
/////////////
/////////////
/////////////
/////////////
/////////////
/////////////
/////////////
/////////////
/////////////
/////////////
/////////////
int Edit::new_(lua_State *L)
{
lua_pushnil(L);
return 1;
}
/////////////
| 26.920455
| 297
| 0.610859
|
sidtheprince
|
a5fb229827c6a545b2a04c5907e9edfe400b6458
| 462
|
cpp
|
C++
|
Creational/AbstractFactory/TestHelloWorld.cpp
|
dodaydream/hello_world_in_design_patterns
|
525de263bf7b75cdaf2450a760ccc118ca0cddfd
|
[
"MIT"
] | null | null | null |
Creational/AbstractFactory/TestHelloWorld.cpp
|
dodaydream/hello_world_in_design_patterns
|
525de263bf7b75cdaf2450a760ccc118ca0cddfd
|
[
"MIT"
] | null | null | null |
Creational/AbstractFactory/TestHelloWorld.cpp
|
dodaydream/hello_world_in_design_patterns
|
525de263bf7b75cdaf2450a760ccc118ca0cddfd
|
[
"MIT"
] | null | null | null |
#include "HelloWorld.h"
int main()
{
AbstractHelloWorldFactory* factoryCJK = new ConcreteHelloWorldCJKFactory();
AbstractHelloWorldFactory* factoryLatin = new ConcreteHelloWorldLatinFactory();
HelloWorldLatin* helloEn = factoryLatin->createHelloWorldEn();
helloEn->sayHello();
HelloWorldCJK* helloJp = factoryCJK->createHelloWorldJp();
helloJp->sayHello();
HelloWorldCJK* helloZh = factoryCJK->createHelloWorldZh();
helloZh->sayHello();
return 0;
}
| 25.666667
| 80
| 0.781385
|
dodaydream
|
a5fca8bdc81d155e353b8d2657b983f9aa820a0f
| 3,125
|
hpp
|
C++
|
include/Datastructures.hpp
|
yuphin/Vortigen
|
155bc9e364560bf651d04e5b562f596ea4217796
|
[
"MIT"
] | 2
|
2021-07-15T15:45:40.000Z
|
2021-08-14T19:59:49.000Z
|
include/Datastructures.hpp
|
yuphin/Vortigen
|
155bc9e364560bf651d04e5b562f596ea4217796
|
[
"MIT"
] | null | null | null |
include/Datastructures.hpp
|
yuphin/Vortigen
|
155bc9e364560bf651d04e5b562f596ea4217796
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Utilities.hpp"
#include <vector>
/**
* @brief General 2D data structure around std::vector, in column
* major format.
*
*/
template <typename T> class Matrix {
public:
Matrix<T>() = default;
/**
* @brief Constructor with initial value
*
* @param[in] number of elements in x direction
* @param[in] number of elements in y direction
* @param[in] initial value for the elements
*
*/
Matrix<T>(int i_max, int j_max, Real init_val) : _imax(i_max), _jmax(j_max) {
_container.resize(i_max * j_max);
std::fill(_container.begin(), _container.end(), init_val);
}
/**
* @brief Constructor without an initial value.
*
* @param[in] number of elements in x direction
* @param[in] number of elements in y direction
*
*/
Matrix<T>(int i_max, int j_max) : _imax(i_max), _jmax(j_max) { _container.resize(i_max * j_max); }
/**
* @brief Element access and modify using index
*
* @param[in] x index
* @param[in] y index
* @param[out] reference to the value
*/
T &operator()(int i, int j) { return _container.at(_imax * j + i); }
/**
* @brief Element access using index
*
* @param[in] x index
* @param[in] y index
* @param[out] value of the element
*/
T operator()(int i, int j) const { return _container.at(_imax * j + i); }
/**
* @brief Pointer representation of underlying data
*
* @param[out] pointer to the beginning of the vector
*/
T *data() { return _container.data(); }
/**
* @brief Access of the size of the structure
*
* @param[out] size of the data structure
*/
size_t size() const { return _container.size(); }
/// get the given row of the matrix
std::vector<Real> get_row(int row) {
std::vector<T> row_data(_imax, -1);
for (int i = 0; i < _imax; ++i) {
row_data.at(i) = _container.at(i + _imax * row);
}
return row_data;
}
/// get the given column of the matrix
std::vector<Real> get_col(int col) {
std::vector<T> col_data(_jmax, -1);
for (int i = 0; i < _jmax; ++i) {
col_data.at(i) = _container.at(col + i * _imax);
}
return col_data;
}
/// set the given column of matrix to given vector
void set_col(const std::vector<Real> &vec, int col) {
for (int i = 0; i < _jmax; ++i) {
_container.at(col + i * _imax) = vec.at(i);
}
}
/// set the given row of matrix to given vector
void set_row(const std::vector<Real> &vec, int row) {
for (int i = 0; i < _imax; ++i) {
_container.at(i + row * _imax) = vec.at(i);
}
}
/// get the number of elements in x direction
int imax() const { return _imax; }
/// get the number of elements in y direction
int jmax() const { return _jmax; }
/// Number of elements in x direction
int _imax;
/// Number of elements in y direction
int _jmax;
/// Data container
std::vector<T> _container;
};
| 27.173913
| 102
| 0.56864
|
yuphin
|
a5fd3c208f99c5c3b596e032178c03dde55a504b
| 3,213
|
cpp
|
C++
|
products/BellHybrid/apps/common/src/widgets/BellBattery.cpp
|
buk7456/MuditaOS
|
06ef1e131b27b0f397cc615c96d51bede7050423
|
[
"BSL-1.0"
] | null | null | null |
products/BellHybrid/apps/common/src/widgets/BellBattery.cpp
|
buk7456/MuditaOS
|
06ef1e131b27b0f397cc615c96d51bede7050423
|
[
"BSL-1.0"
] | null | null | null |
products/BellHybrid/apps/common/src/widgets/BellBattery.cpp
|
buk7456/MuditaOS
|
06ef1e131b27b0f397cc615c96d51bede7050423
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include <common/data/BatteryUtils.hpp>
#include <common/widgets/BellBattery.hpp>
#include <Image.hpp>
namespace
{
constexpr auto entries = std::array<battery_utils::BatteryLevelEntry, 6>{{{{0, 9}, "bell_battery_empty"},
{{10, 19}, "bell_battery_lvl1"},
{{20, 39}, "bell_battery_lvl2"},
{{40, 69}, "bell_battery_lvl3"},
{{70, 95}, "bell_battery_lvl4"},
{{96, 100}, "bell_battery_lvl5"}}};
constexpr auto betteryFullLevel = 100;
constexpr auto lowBatteryLimit = 20;
} // namespace
namespace gui
{
BellBattery::BellBattery(Item *parent, uint32_t x, uint32_t y, uint32_t w, uint32_t h) : HBox(parent, x, y, w, h)
{
img = new Image(this, battery::battery_low, gui::ImageTypeSpecifier::W_M);
img->setAlignment(Alignment(Alignment::Horizontal::Left, Alignment::Vertical::Center));
img->setMargins(gui::Margins(0, 0, battery::image_right_margin, 0));
percentText = new TextFixedSize(this, 0, 0, 0, 0);
percentText->setMinimumSize(battery::percent_w, battery::percent_h);
percentText->setFont(battery::font_small);
percentText->setAlignment(Alignment(Alignment::Horizontal::Left, Alignment::Vertical::Center));
percentText->setEdges(RectangleEdge::None);
percentText->activeItem = false;
percentText->drawUnderline(false);
}
void BellBattery::update(const Store::Battery &batteryContext)
{
const auto image = battery_utils::getBatteryLevelImage(entries, batteryContext.level);
if (not image) {
return;
}
const auto level = batteryContext.level;
if (batteryContext.state == Store::Battery::State::Charging) {
img->set(battery::battery_charging, gui::ImageTypeSpecifier::W_M);
}
else {
img->set(image->data(), gui::ImageTypeSpecifier::W_M);
img->informContentChanged();
}
if (batteryPercentMode == BatteryPercentMode::Static || level < lowBatteryLimit ||
batteryContext.state == Store::Battery::State::Charging) {
percentText->setText(std::to_string(level) + "%");
percentText->setVisible(true);
}
else {
percentText->setVisible(false);
}
percentText->informContentChanged();
}
void BellBattery::setBatteryPercentMode(BatteryPercentMode mode)
{
batteryPercentMode = mode;
}
std::uint32_t BellBattery::getLevel()
{
auto percentTextStr = std::string(percentText->getText().c_str());
auto batteryLevelStr = percentTextStr.substr(0, percentTextStr.size() - 1);
return std::stoi(batteryLevelStr);
}
} // namespace gui
| 41.192308
| 117
| 0.572362
|
buk7456
|
a5fd9b659d33db977877753430beda1611ae5c26
| 7,078
|
cpp
|
C++
|
lib/AL_USDMaya/AL/usdmaya/fileio/translators/MeshTranslator.cpp
|
AlexSchwank/AL_USDMaya
|
99413e2c5d1c93e4c58a63ebc8b07e23cf072e86
|
[
"Apache-2.0"
] | null | null | null |
lib/AL_USDMaya/AL/usdmaya/fileio/translators/MeshTranslator.cpp
|
AlexSchwank/AL_USDMaya
|
99413e2c5d1c93e4c58a63ebc8b07e23cf072e86
|
[
"Apache-2.0"
] | null | null | null |
lib/AL_USDMaya/AL/usdmaya/fileio/translators/MeshTranslator.cpp
|
AlexSchwank/AL_USDMaya
|
99413e2c5d1c93e4c58a63ebc8b07e23cf072e86
|
[
"Apache-2.0"
] | null | null | null |
//
// Copyright 2017 Animal Logic
//
// 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 "AL/usd/utils/SIMD.h"
#include "AL/usdmaya/Metadata.h"
#include "AL/usdmaya/utils/Utils.h"
#include "AL/usdmaya/utils/MeshUtils.h"
#include "AL/usdmaya/fileio/ExportParams.h"
#include "AL/usdmaya/fileio/ImportParams.h"
#include "AL/usdmaya/fileio/AnimationTranslator.h"
#include "AL/usdmaya/fileio/translators/MeshTranslator.h"
#include "maya/MAnimUtil.h"
#include "maya/MColorArray.h"
#include "maya/MDagPath.h"
#include "maya/MDoubleArray.h"
#include "maya/MFnMesh.h"
#include "maya/MFloatArray.h"
#include "maya/MFloatPointArray.h"
#include "maya/MGlobal.h"
#include "maya/MIntArray.h"
#include "maya/MItMeshPolygon.h"
#include "maya/MItMeshVertex.h"
#include "maya/MObject.h"
#include "maya/MPlug.h"
#include "maya/MUintArray.h"
#include "maya/MVector.h"
#include "maya/MVectorArray.h"
#include "pxr/usd/usd/modelAPI.h"
#include "pxr/usd/usd/timeCode.h"
#include "pxr/usd/usdGeom/mesh.h"
#include <algorithm>
#include <cstring>
namespace AL {
namespace usdmaya {
namespace fileio {
namespace translators {
//----------------------------------------------------------------------------------------------------------------------
bool MeshTranslator::attributeHandled(const UsdAttribute& usdAttr)
{
const std::string& str = usdAttr.GetName().GetString();
const char* glimpse_prefix = "glimpse_";
if(!std::strncmp(glimpse_prefix, str.c_str(), 8))
{
return true;
}
return DagNodeTranslator::attributeHandled(usdAttr);
}
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
// Export
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
void MeshTranslator::copyNormalData(const MFnMesh& fnMesh, const UsdAttribute& normalsAttr, UsdTimeCode time)
{
MStatus status;
const uint32_t numNormals = fnMesh.numNormals();
VtArray<GfVec3f> normals(numNormals);
const float* normalsData = fnMesh.getRawNormals(&status);
if(status)
{
memcpy((GfVec3f*)normals.data(), normalsData, sizeof(float) * 3 * numNormals);
normalsAttr.Set(normals, time);
}
else
{
MGlobal::displayError(MString("Unable to access mesh normals on mesh: ") + fnMesh.fullPathName());
}
}
//----------------------------------------------------------------------------------------------------------------------
UsdPrim MeshTranslator::exportObject(UsdStageRefPtr stage, MDagPath path, const SdfPath& usdPath, const ExporterParams& params)
{
if(!params.m_meshes)
return UsdPrim();
UsdGeomMesh mesh = UsdGeomMesh::Define(stage, usdPath);
AL::usdmaya::utils::MeshExportContext context(path, mesh, params.m_timeCode, false, (AL::usdmaya::utils::MeshExportContext::CompactionLevel)params.m_compactionLevel);
if(context)
{
UsdAttribute pointsAttr = mesh.GetPointsAttr();
if (params.m_animTranslator && AnimationTranslator::isAnimatedMesh(path))
{
params.m_animTranslator->addMesh(path, pointsAttr);
}
if(params.m_meshPoints)
{
context.copyVertexData(context.timeCode());
}
if(params.m_meshConnects)
{
context.copyFaceConnectsAndPolyCounts();
}
if(params.m_meshHoles)
{
context.copyInvisibleHoles();
}
if(params.m_meshUvs)
{
context.copyUvSetData();
}
if(params.m_meshNormals)
{
context.copyNormalData(context.timeCode());
}
context.copyGlimpseTesselationAttributes();
if(params.m_meshColours)
{
context.copyColourSetData();
}
if(params.m_meshVertexCreases)
{
context.copyCreaseVertices();
}
if(params.m_meshEdgeCreases)
{
context.copyCreaseEdges();
}
// pick up any additional attributes attached to the mesh node (these will be added alongside the transform attributes)
if(params.m_dynamicAttributes)
{
UsdPrim prim = mesh.GetPrim();
DgNodeTranslator::copyDynamicAttributes(path.node(), prim);
}
}
return mesh.GetPrim();
}
//----------------------------------------------------------------------------------------------------------------------
UsdPrim MeshTranslator::exportUV(UsdStageRefPtr stage, MDagPath path, const SdfPath& usdPath, const ExporterParams& params)
{
UsdPrim overPrim = stage->OverridePrim(usdPath);
UsdGeomMesh mesh(overPrim);
AL::usdmaya::utils::MeshExportContext context(path, mesh, params.m_timeCode);
if (context)
{
context.copyUvSetData();
}
return overPrim;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus MeshTranslator::registerType()
{
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MObject MeshTranslator::createNode(const UsdPrim& from, MObject parent, const char* nodeType, const ImporterParams& params)
{
if(!params.m_meshes)
return MObject::kNullObj;
const UsdGeomMesh mesh(from);
bool parentUnmerged = false;
TfToken val;
if(from.GetParent().GetMetadata(AL::usdmaya::Metadata::mergedTransform, &val))
{
parentUnmerged = (val == AL::usdmaya::Metadata::unmerged);
}
MString dagName = from.GetName().GetString().c_str();
if(!parentUnmerged)
{
dagName += "Shape";
}
UsdTimeCode timeCode = params.m_forceDefaultRead ? UsdTimeCode::Default() : UsdTimeCode::EarliestTime();
AL::usdmaya::utils::MeshImportContext context(mesh, parent, dagName, timeCode);
context.applyVertexNormals();
context.applyHoleFaces();
context.applyVertexCreases();
context.applyEdgeCreases();
context.applyGlimpseSubdivParams();
context.applyGlimpseUserDataParams();
applyDefaultMaterialOnShape(context.getPolyShape());
context.applyPrimVars();
return context.getPolyShape();
}
//----------------------------------------------------------------------------------------------------------------------
} // translators
} // fileio
} // usdmaya
} // AL
//----------------------------------------------------------------------------------------------------------------------
| 33.230047
| 168
| 0.574032
|
AlexSchwank
|
570522b8202df3150b6378f538b8e0347f187b9f
| 3,673
|
cpp
|
C++
|
src/chain.cpp
|
jbaldwin/libchain
|
fcceaa141c4aa12abd588f1b9032c4a8c48fd0b4
|
[
"MIT"
] | 3
|
2020-09-03T20:05:24.000Z
|
2022-02-03T20:49:33.000Z
|
src/chain.cpp
|
jbaldwin/libchain
|
fcceaa141c4aa12abd588f1b9032c4a8c48fd0b4
|
[
"MIT"
] | 8
|
2020-11-12T18:13:19.000Z
|
2021-12-05T18:58:28.000Z
|
src/chain.cpp
|
jbaldwin/libchain
|
fcceaa141c4aa12abd588f1b9032c4a8c48fd0b4
|
[
"MIT"
] | null | null | null |
#include "chain/chain.hpp"
#include <cstring>
namespace chain::str
{
const std::stringstream g_ss_default_fmt{};
auto to_lower(std::string& data) -> void
{
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
}
auto to_lower_copy(std::string_view data) -> std::string
{
std::string copy{data};
to_lower(copy);
return copy;
}
auto to_upper(std::string& data) -> void
{
std::transform(data.begin(), data.end(), data.begin(), ::toupper);
}
auto to_upper_copy(std::string_view data) -> std::string
{
std::string copy{data};
to_upper(copy);
return copy;
}
auto trim_left(std::string& data) -> void
{
if (!data.empty())
{
auto found = std::find_if_not(data.begin(), data.end(), ::isspace);
// If the entire string is std::isspace just clear it.
if (found == data.end())
{
data.clear();
}
else
{
data.erase(data.begin(), found);
}
}
}
auto trim_left_view(std::string_view data) -> std::string_view
{
if (!data.empty())
{
std::size_t index = 0;
while (index < data.length())
{
if (!std::isspace(static_cast<unsigned char>(data[index])))
{
break;
}
else
{
++index;
}
}
data.remove_prefix(index);
}
return data;
}
auto trim_right(std::string& data) -> void
{
if (!data.empty())
{
auto found =
std::find_if_not(data.rbegin(), data.rend(), [](unsigned char ch) -> bool { return std::isspace(ch); });
if (found == data.rend())
{
data.clear();
}
else
{
data.erase(found.base(), data.end());
}
}
}
auto trim_right_view(std::string_view data) -> std::string_view
{
if (!data.empty())
{
int64_t index = static_cast<int64_t>(data.length() - 1);
while (index >= 0)
{
if (!std::isspace(static_cast<unsigned char>(data[static_cast<std::size_t>(index)])))
{
break;
}
else
{
--index;
}
}
data = data.substr(0, static_cast<std::size_t>(index + 1));
}
return data;
}
auto trim(std::string& data) -> void
{
trim_left(data);
trim_right(data);
}
auto trim_view(std::string_view data) -> std::string_view
{
return trim_left_view(trim_right_view(data));
}
auto is_int(std::string_view data) -> bool
{
// TODO These probably need stricter requirements to differentiate between
// an integer and a float.
if (data.find('.') != std::string_view::npos)
{
return false;
}
return to_number<int64_t>(data).has_value();
}
auto is_float(std::string_view data) -> bool
{
if (data.find('.') == std::string_view::npos)
{
return false;
}
return to_number<double>(std::string{data}).has_value();
}
auto is_number(std::string_view data) -> bool
{
return is_int(data) || is_float(std::string{data});
}
auto strerror(int errsv) -> std::string
{
// strerror_r appears to ignore passed in buffer args, manually copy
// the data from the returned error_ptr. The XSI complain version of this
// function would probably just work...
// TODO: might need some #defines to make this more portable for non-GNU.
constexpr std::size_t LEN = 256;
char buffer[LEN];
char* error_ptr = strerror_r(errsv, buffer, LEN);
return std::string{error_ptr, strnlen(error_ptr, LEN)};
}
} // namespace chain::str
| 22.126506
| 116
| 0.557582
|
jbaldwin
|
570551cfcef6fd9d71606302f379151674076a8d
| 28,211
|
cpp
|
C++
|
Source/FXT/Private/SFXTParent.cpp
|
Ocelot0/FXT
|
20cfd76f1900b6d4117690a0c1025f40be1f6a28
|
[
"MIT"
] | 1
|
2018-06-10T06:04:02.000Z
|
2018-06-10T06:04:02.000Z
|
Source/FXT/Private/SFXTParent.cpp
|
Ocelot0/FXT
|
20cfd76f1900b6d4117690a0c1025f40be1f6a28
|
[
"MIT"
] | 3
|
2018-06-09T12:59:28.000Z
|
2018-06-29T15:12:34.000Z
|
Source/FXT/Private/SFXTParent.cpp
|
Ocelot0/FXT
|
20cfd76f1900b6d4117690a0c1025f40be1f6a28
|
[
"MIT"
] | null | null | null |
//=================================================
// Written by Lee Gil Su
// Copyright 2018. Lee Gil Su. all rights reserved.
//=================================================
#include "SFXTParent.h"
#include "SlateOptMacros.h"
#include "FXTCore.h"
BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION
SFXTParent::~SFXTParent()
{
GEngine->OnLevelActorAdded().RemoveAll(this);
GEngine->OnLevelActorDeleted().RemoveAll(this);
FCoreDelegates::OnActorLabelChanged.RemoveAll(this);
FEditorDelegates::BeginPIE.RemoveAll(this);
FEditorDelegates::EndPIE.RemoveAll(this);
}
void SFXTParent::Construct(const FArguments& InArgs)
{
//*Delegate Binding
GEngine->OnLevelActorAdded().AddSP(this, &SFXTParent::OnLevelActorAdded);
GEngine->OnLevelActorDeleted().AddSP(this, &SFXTParent::OnLevelActorDeleted);
FCoreDelegates::OnActorLabelChanged.AddRaw(this, &SFXTParent::OnActorLabelChanged);
FEditorDelegates::BeginPIE.AddSP(this, &SFXTParent::OnBeginPIE);
FEditorDelegates::EndPIE.AddSP(this, &SFXTParent::OnEndPIE);
//*Visibility
auto Vis_EditChildList_Lam = [this] {
return bEditChildList ? EVisibility::Visible : EVisibility::Collapsed;
};
auto Vis_EditChildList_Attr = TAttribute<EVisibility>::Create(
TAttribute<EVisibility>::FGetter::CreateLambda(Vis_EditChildList_Lam));
//*Text attr
auto TXT_CurrentParent_Lam = [this] {
if (!FXTParentList->GetNumItemsSelected() == 1) return FXTC::T("Childs");
//Get selected parent actor
TArray<TSharedPtr<FXTParentListItemType>> SelectedParents = FXTParentList->GetSelectedItems();
return FXTC::T(SelectedParents[0].Get()->Label);
};
auto TXT_CurrentParent_Attr = TAttribute<FText>::Create(
TAttribute<FText>::FGetter::CreateLambda(TXT_CurrentParent_Lam));
//*Property
float ListViewWidth = 230.0f;
float TB_NewParentNameWidth = 200.0f;
float SB_NewParentOffsetWidth = 60.0f;
float InputBoxHeight = 20.0f;
ChildSlot
[
SNew(SBorder).BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")).Padding(2.f)[
SNew(SBox).VAlign(VAlign_Fill).HAlign(HAlign_Fill)[
SNew(SVerticalBox)
//*Tool pannel
+ SVerticalBox::Slot().AutoHeight()[
SNew(SVerticalBox)
+ SVerticalBox::Slot().AutoHeight().Padding(0.f, 0.f, 0.f, 2.f)[
SNew(SHorizontalBox)
//*Add Parent
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SFXTButton).OnClicked(this, &SFXTParent::OnClicked_CreateNewParent)
.bUseImage(true)
.Image(FXTStyle::Get().GetBrush("FXT.Icon20"))
.InitialColor(FXTStyle::Clr_Default())
.ToolTipText(FXTC::T(BTN_CREATEPARENT_TOOLTIP))
.ButtonStyle(&FEditorStyle::Get(), "EditorViewportToolBar.MenuButton")
]//-SHorizontalBox::Slot()
//*Add Parent option
+ SHorizontalBox::Slot().Padding(2.f, 2.f, 0.f, 0.f).MaxWidth(TB_NewParentNameWidth)[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()[
SNew(SVerticalBox) + SVerticalBox::Slot().MaxHeight(InputBoxHeight)[
SAssignNew(TB_NewParentName, SEditableTextBox)
.HintText(FXTC::T("Parent Name"))
.ToolTipText(FXTC::T(TB_NEWPARENTNAME_TOOLTIP))
]
]//-SHorizontalBox::Slot()
//reset custom name text box
+ SHorizontalBox::Slot().AutoWidth().Padding(FMargin(2.f, 0.f))[
SNew(SVerticalBox) +SVerticalBox::Slot().AutoHeight()[
SNew(SFXTButton).OnClicked(this, &SFXTParent::OnClicked_ResetCustomName)
.bUseImage(true)
.Image(FEditorStyle::GetBrush("PropertyWindow.DiffersFromDefault"))
.InitialColor(FXTStyle::Clr_Default())
.ButtonStyle(FEditorStyle::Get(), "NoBorder")
]//-SVerticalBox::Slot()
]//-SHorizontalBox::Slot()
]//-SHorizontalBox::Slot() ;AddparentOption
//*Spinbox : pineapple spawn location offset from view location
+ SHorizontalBox::Slot().Padding(3.f, 0.f).MaxWidth(SB_NewParentOffsetWidth)[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot().MaxWidth(16.f)[
SNew(SVerticalBox) + SVerticalBox::Slot().MaxHeight(16.f).VAlign(VAlign_Center)[
SNew(SImage).Image(FXTStyle::Get().GetBrush("EditorIcon.GenericLOD"))
]
]
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SVerticalBox) + SVerticalBox::Slot().MaxHeight(InputBoxHeight)[
SNew(SSpinBox<float>).ContentPadding(0.f)
.ToolTipText(FXTC::T(SB_NEWPARENTVIEWOFFSET_TOOLTIP))
.MinValue(100.f).MaxValue(350.f).Delta(10.f)
.Value(NewParentOffset)
.OnValueChanged(this, &SFXTParent::OVC_NewParentOffset)
]
]
]
//* Goto sequencer option
+ SHorizontalBox::Slot().Padding(2.f, 2.f, 0.f, 0.f).AutoWidth()[
SNew(SVerticalBox) +SVerticalBox::Slot().AutoHeight().Padding(0.f, 0.f, 0.f, 2.f)[
SNew(SHorizontalBox)
//Goto sequencer option
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SHorizontalBox) + SHorizontalBox::Slot().MaxWidth(16.f)[
SNew(SVerticalBox) + SVerticalBox::Slot().MaxHeight(16.f).VAlign(VAlign_Center)[
SNew(SImage).Image(FXTStyle::Get().GetBrush("RowIcon.LevelSequenceActor"))
]
]
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SVerticalBox) + SVerticalBox::Slot().MaxHeight(InputBoxHeight)[
//Open seq ed
SNew(SCheckBox).OnCheckStateChanged(this, &SFXTParent::CB_bGotoSeq_OpenSeqEditor)
.IsChecked(bGotoSeq_OpenSeqEditor ? ECheckBoxState::Checked : ECheckBoxState::Unchecked)
.ToolTipText(FXTC::T(CB_GOTOSEQOPENSEQ_TOOLTIP))
]
]
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SVerticalBox) + SVerticalBox::Slot().MaxHeight(InputBoxHeight)[
//Focus
SNew(SCheckBox).OnCheckStateChanged(this, &SFXTParent::CB_bGotoSeq_Focus)
.IsChecked(bGotoSeq_Focus ? ECheckBoxState::Checked : ECheckBoxState::Unchecked)
.ToolTipText(FXTC::T(CB_GOTOSEQFOCUS_TOOLTIP))
]
]
]//-SHorizontalBox::Slot() ;Goto sequencer option
]//-SVerticalBox::Slot() ;Row button option
]//-SHorizontalBox::Slot() ;Row button option
]//-SVerticalBox::Slot()
]//-SVerticalBox::Slot()
+ SVerticalBox::Slot()[
SNew(SHorizontalBox)
//*FXTParentList
+ SHorizontalBox::Slot().MaxWidth(ListViewWidth)[
SNew(SBorder).BorderImage(FEditorStyle::GetBrush("ToolPanel.DarkGroupBorder"))[
SAssignNew(FXTParentList, SListView<TSharedPtr<FXTParentListItemType>>)
.ListItemsSource(&FXTParentListItems)
.OnGenerateRow(this, &SFXTParent::OnGenerateRowFXTParentList)
.OnSelectionChanged(this, &SFXTParent::OnSelectionChangedFXTParentList)
.ItemHeight(14.f)
.SelectionMode(ESelectionMode::Single)
.HeaderRow(
SNew(SHeaderRow)+SHeaderRow::Column(FName(TEXT("AFXTParentList")))
[
SNew(SHorizontalBox)
//Header text
+ SHorizontalBox::Slot().HAlign(HAlign_Left).VAlign(VAlign_Center)[
SNew(STextBlock).Text(FXTC::T("AFXTParent")).TextStyle(FFXTStyle::GetTBStyle("ListViewText.Row"))
]
//Edit Child button
+ SHorizontalBox::Slot().HAlign(HAlign_Right)[
SNew(SFXTButton).OnClicked(this, &SFXTParent::OnClicked_EditChildList)
.Icon(FEditorFontGlyphs::Pencil)
.TextStyle(FFXTStyle::GetTBStyle("ListViewText.RowButton"))
.ToolTipText(FXTC::T(BTN_EDITCHILD_TOOLTIP))
]//-SHorizontalBox::Slot()
]//-SHeaderRow
)
]//-SBorder
]//-SHorizontalBox::Slot()
//*FXTChildList
+ SHorizontalBox::Slot().Padding(2.f, 0.f).MaxWidth(ListViewWidth)[
SNew(SBorder).Visibility(Vis_EditChildList_Attr).BorderImage(FEditorStyle::GetBrush("ToolPanel.DarkGroupBorder"))[
SAssignNew(ChildListView, SListView<TSharedPtr<FXTParentListItemType>>)
.ListItemsSource(&ChildListViewItems)
.OnGenerateRow(this, &SFXTParent::OnGenerateRowChildListView)
.OnSelectionChanged(this, &SFXTParent::OnSelectionChangedChildListView)
.ItemHeight(14.f)
.SelectionMode(ESelectionMode::None)
.HeaderRow(
SNew(SHeaderRow) + SHeaderRow::Column(FName(TEXT("AFXTParentList")))
[
SNew(SHorizontalBox)
//Header text
+ SHorizontalBox::Slot().HAlign(HAlign_Left).VAlign(VAlign_Center)[
SNew(STextBlock).Text(TXT_CurrentParent_Attr).TextStyle(FFXTStyle::GetTBStyle("ListViewText.Row"))
]//-SHorizontalBox::Slot()
//Reset Child list button
+ SHorizontalBox::Slot().HAlign(HAlign_Right)[
SNew(SFXTButton).OnClicked(this, &SFXTParent::OnClicked_ResetChildList)
.bUseImage(true)
.Image(FEditorStyle::GetBrush("PropertyWindow.Button_Clear"))
.InitialColor(FXTStyle::Clr_Default())
.ToolTipText(FXTC::T(BTN_RESETCHILDLIST_TOOLTIP))
]//-SHorizontalBox::Slot()
]//-SHeaderRow
)
]//-SBorder
]//-SHorizontalBox::Slot()
]//-SVerticalBox::Slot()
]//-SBox
]//-SBorder
];
//Update List
UpdateFXTParentList();
}
void SFXTParent::OnLevelActorAdded(AActor* InActor)
{
//Update List
UpdateFXTParentList();
}
void SFXTParent::OnLevelActorDeleted(AActor* InActor)
{
//Update List
UpdateFXTParentList();
//*Refresh child list for all parents
TArray<AFXTParent*> Parents;
FXTC::Itr<AFXTParent>(Parents);
for (AFXTParent* itr : Parents) {
itr->RefreshChildList();
}
}
void SFXTParent::OnActorLabelChanged(AActor* inActor)
{
//Update List
UpdateFXTParentList();
}
void SFXTParent::OnBeginPIE(const bool bBeginPIE)
{
}
void SFXTParent::OnEndPIE(const bool bEndPIE)
{
//Start Timer until PIE fully finish
GEditor->GetTimerManager().Get().SetTimer(
PIEFullyFinishTimerHandle, FTimerDelegate::CreateSP(this, &SFXTParent::OnFullyEndPIE), 0.03f, false, 0.03f);
}
void SFXTParent::OnFullyEndPIE()
{
//reset timer manager
GEditor->GetTimerManager()->ClearTimer(PIEFullyFinishTimerHandle);
UpdateFXTParentList();
}
FReply SFXTParent::OnClicked_CreateNewParent()
{
//Check name dupling
bool bNameDupling = false;
FString CustomName = TB_NewParentName->GetText().ToString();
if (!CustomName.IsEmpty()) {
TArray<AFXTParent*> AllParents;
FXTC::Itr<AFXTParent>(AllParents);
for (AFXTParent* itr : AllParents){
if (FXTC::chkA(itr) && itr->GetActorLabel() == CustomName) {
bNameDupling = true;
break;
}
}
}
FEditorViewportClient* client = (FEditorViewportClient*)GEditor->GetActiveViewport()->GetClient();
if (client && !bNameDupling) {
//Get spawn position
FVector EditorCameraDirection = client->GetViewRotation().Vector();
FVector EditorCameraPosition = client->GetViewLocation();
FVector SpawnLocation = EditorCameraPosition + (EditorCameraDirection * NewParentOffset);
FTransform SpawnTransform = FTransform();
SpawnTransform.SetLocation(SpawnLocation);
//Spawn actor
AFXTParent* SpawnedActor = FXTC::AddActor<AFXTParent>(SpawnTransform);
//Set Actor label
if (!CustomName.IsEmpty()) SpawnedActor->SetActorLabel(CustomName);
}
return FReply::Handled();
}
FReply SFXTParent::OnClicked_ResetCustomName()
{
TB_NewParentName->SetText(FXTC::T(""));
return FReply::Handled();
}
void SFXTParent::OVC_NewParentOffset(float NewValue)
{
NewParentOffset = NewValue;
}
void SFXTParent::CB_bGotoSeq_OpenSeqEditor(ECheckBoxState NewValue)
{
bGotoSeq_OpenSeqEditor = (NewValue == ECheckBoxState::Checked) ? true : false;
}
void SFXTParent::CB_bGotoSeq_Focus(ECheckBoxState NewValue)
{
bGotoSeq_Focus = (NewValue == ECheckBoxState::Checked) ? true : false;
}
TSharedRef<ITableRow> SFXTParent::OnGenerateRowFXTParentList(TSharedPtr<FXTParentListItemType> InItem, const TSharedRef<STableViewBase>& OwnerTable)
{
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(InItem.Get()->Label);
bool LastHidden = A->GetChildHidden();
//Num of childs
int32 NumOfChilds = A->GetNumOfChilds();
FText NumOfChildsTEXT = FXTC::T( "(" + FString::FromInt(NumOfChilds) + ")");
//Num of sequencer
TArray<ALevelSequenceActor*> LSAs;
A->GetActorsFromChildList<ALevelSequenceActor>(LSAs);
int32 NumOfSeq = LSAs.Num();
float LabelTextMaxWidth = 100.0f;
return SNew(STableRow< TSharedPtr<FXTParentListItemType> >, OwnerTable)
.Padding(2.f)
[
SNew(SHorizontalBox)
//Child set hidden Button
+ SHorizontalBox::Slot().AutoWidth().HAlign(HAlign_Left)[
SNew(SRowButton).OnClicked(this, &SFXTParent::OnClickedRB_ChildHiddenToggle).RowLabel(InItem.Get()->Label)
.Icon(LastHidden ? FEditorFontGlyphs::Eye_Slash : FEditorFontGlyphs::Eye)
.InitialToggleState(LastHidden)
.InitialColor(LastHidden ? FXTStyle::Clr_Hidden() : FXTStyle::Clr_Default())
.ToolTipText(FXTC::T(BTN_HIDDENTOGGLE_TOOLTIP))
]
//Label
+ SHorizontalBox::Slot().MaxWidth(LabelTextMaxWidth).AutoWidth().HAlign(HAlign_Fill).VAlign(VAlign_Center)[
SNew(STextBlock).Text(FXTC::T(InItem.Get()->Label)).TextStyle(FFXTStyle::GetTBStyle("ListViewText.Row"))
.ToolTipText(FXTC::T(InItem.Get()->Label))
]
//Num of childs
+ SHorizontalBox::Slot().Padding(2.f, 0.f).AutoWidth().HAlign(HAlign_Fill).VAlign(VAlign_Bottom)[
SNew(STextBlock).Visibility(NumOfChilds > 0 ? EVisibility::Visible : EVisibility::Collapsed)
.Text(NumOfChildsTEXT)
.Font(FEditorStyle::Get().GetFontStyle("FontAwesome.9"))
.ColorAndOpacity(FXTStyle::Clr_Hidden())
]
//Utility Buttons
+ SHorizontalBox::Slot().HAlign(HAlign_Right)[
SNew(SHorizontalBox)
//Add child button
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SRowButton).OnClicked(this, &SFXTParent::OnClickedRB_AddChild).RowLabel(InItem.Get()->Label)
.bUseImage(true)
.Image(FEditorStyle::GetBrush("PropertyWindow.Button_Use"))
.ToolTipText(FXTC::T(BTN_ADDCHILDFROMSELECTED_TOOLTIP))
]
//remove parent button
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SRowButton).OnClicked(this, &SFXTParent::OnClickedRB_DestroyParent).RowLabel(InItem.Get()->Label)
.bUseImage(true)
.Image(FEditorStyle::GetBrush("PropertyWindow.Button_Delete"))
.ToolTipText(FXTC::T(BTN_DESTROYPARENT_TOOLTIP))
]
//Goto button
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SRowButton).OnClicked(this, &SFXTParent::OnClickedRB_GotoParent).RowLabel(InItem.Get()->Label)
.bUseImage(true)
.Image(FEditorStyle::GetBrush("PropertyWindow.Button_Browse"))
.ToolTipText(FXTC::T(BTN_GOTOPARENT_TOOLTIP))
]
//Goto seq button
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SRowComboButton).RowLabel(InItem.Get()->Label)
.bUseImage(true)
.Image(FXTStyle::Get().GetBrush("FXT.GotoSeq"))
.InitialColor(NumOfSeq > 0 ? FXTStyle::Clr_Default() : FXTStyle::Clr_Hidden())
.ToolTipText(FXTC::T(BTN_GOTOSEQ_TOOLTIP))
.OnClicked(this, &SFXTParent::OnClickedRB_GotoSeq)
.OnUpdateSource(this, &SFXTParent::OUS_GotoSeq)
.OnItemSelect(this, &SFXTParent::OIS_GotoSeq)
]
]
];
}
void SFXTParent::UpdateFXTParentList()
{
if (FXTParentList.IsValid()) {
//Get all AFXTParents
TArray<AFXTParent*> AFXTParents;
FXTC::Itr<AFXTParent>(AFXTParents);
//Update Item source
FXTParentListItems.Empty();
if (AFXTParents.Num() > 0){
for (AFXTParent* itr : AFXTParents) {
FXTParentListItems.Add(MakeShareable(new FXTParentListItemType(itr)));
}
}
//Sort array
if (FXTParentListItems.Num() > 1) {
FXTParentListItems.Sort([](const TSharedPtr<FXTParentListItemType>& A, const TSharedPtr<FXTParentListItemType>& B) {
return FXTC::CompareNumeric(*A->Label, *B->Label) < 0;
});
}
//Last Selected
if (FXTParentList->GetNumItemsSelected() == 1) {
//*Get selected parent actor
TArray<TSharedPtr<FXTParentListItemType>> SelectedParents = FXTParentList->GetSelectedItems();
LastSelectedItemFXTParentList = SelectedParents[0];
}
else
{
LastSelectedItemFXTParentList = nullptr;
}
//Update Listview
FXTParentList->RequestListRefresh();
//*Reselect last selected with timer
GEditor->GetTimerManager().Get().SetTimer(
ReselectTimerHandleFXTParentList, FTimerDelegate::CreateSP(this, &SFXTParent::ReselectTimerFXTParentList), 0.01f, false, 0.01f);
}
}
void SFXTParent::ReselectTimerFXTParentList()
{
//close tiemr session
GEditor->GetTimerManager()->ClearTimer(ReselectTimerHandleFXTParentList);
if (LastSelectedItemFXTParentList.IsValid()) {
FString LSLabel = LastSelectedItemFXTParentList.Get()->Label;
for (TSharedPtr<FXTParentListItemType> itr : FXTParentListItems) {
if (itr.IsValid() && itr.Get()->Label == LSLabel) {
FXTParentList->SetItemSelection(itr, true, ESelectInfo::OnMouseClick);
break;
}
}
}
}
void SFXTParent::OnSelectionChangedFXTParentList(TSharedPtr<FXTParentListItemType> InItem, ESelectInfo::Type SelectInfo)
{
if (!InItem.IsValid()) {
//*clear child list view
UpdateChildListView();
return;
}
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(InItem.Get()->Label);
if (FXTC::chkA(A)) {
//*Update Child List View
UpdateChildListView();
}
}
FReply SFXTParent::OnClicked_EditChildList()
{
//toggle child list view visibility
bEditChildList = bEditChildList ? false : true;
return FReply::Handled();
}
FReply SFXTParent::OnClickedRB_ChildHiddenToggle(const TSharedRef<SRowButton>& outBTN)
{
//*Get actor of row
const FString& outLabel = outBTN.Get().GetRowLabel();
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(outLabel);
if (FXTC::chkA(A)) {
//*Get current button toggle state
bool ToggleState = outBTN.Get().GetToggleState();
//*Call function on actor
A->SetChildHidden(ToggleState);
//*Set eye icon by hidden state
outBTN.Get().SetIcon(outBTN.Get().GetToggleState() ? FEditorFontGlyphs::Eye_Slash : FEditorFontGlyphs::Eye);
//*Set icon color
outBTN.Get().SetIconColor(ToggleState ? FXTStyle::Clr_Hidden() : FXTStyle::Clr_Default());
}
return FReply::Handled();
}
FReply SFXTParent::OnClickedRB_GotoParent(const TSharedRef<SRowButton>& outBTN)
{
//get client for camera
FEditorViewportClient* client = (FEditorViewportClient*)GEditor->GetActiveViewport()->GetClient();
if (client) {
//*Get actor of row
const FString& outLabel = outBTN.Get().GetRowLabel();
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(outLabel);
if (FXTC::chkA(A)) {
//make camera destination
FVector Destination = A->GetActorLocation() - client->GetViewRotation().Vector() * 128.0f;
//Set editor camera location
client->SetViewLocation(Destination);
//select target actor
GEditor->SelectNone(true, true, true);
GEditor->SelectActor(A, true, true, true, true);
}
}
return FReply::Handled();
}
FReply SFXTParent::OnClickedRB_GotoSeq(const TSharedRef<SRowComboButton>& outBTN)
{
return FReply::Handled();
}
void SFXTParent::OUS_GotoSeq(TArray<TSharedPtr<FString>>& outItem, const TSharedRef<SRowComboButton>& outBTN)
{
//*Get actor of row
const FString& outLabel = outBTN.Get().GetRowLabel();
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(outLabel);
if (FXTC::chkA(A)) {
TArray<ALevelSequenceActor*> LSAs;
outItem.Empty();
if (A->GetActorsFromChildList<ALevelSequenceActor>(LSAs))
{
for (ALevelSequenceActor* i : LSAs) {
outItem.Add( MakeShareable(new FString(i->GetActorLabel())) );
}
}
}
}
void SFXTParent::OIS_GotoSeq(FString& outLabel)
{
ALevelSequenceActor* LSA = FXTC::GetActorByLabel<ALevelSequenceActor>(outLabel);
if (FXTC::chkA(LSA)) {
//select target actor
GEditor->SelectNone(true, true, true);
GEditor->SelectActor(LSA, true, true, true, true);
//get client for camera
if (bGotoSeq_Focus)
{
FEditorViewportClient* client = (FEditorViewportClient*)GEditor->GetActiveViewport()->GetClient();
if (client) {
//make camera destination
FVector Destination = LSA->GetActorLocation() - client->GetViewRotation().Vector() * 128.0f;
//Set editor camera location
client->SetViewLocation(Destination);
}
}
//open level sequence editor
if (bGotoSeq_OpenSeqEditor) {
UObject* LoadedObject = LSA->LevelSequence.TryLoad();
if (LoadedObject != nullptr) {
FAssetEditorManager::Get().OpenEditorForAsset(LoadedObject);
}
}
}
}
FReply SFXTParent::OnClickedRB_AddChild(const TSharedRef<SRowButton>& outBTN)
{
//*Get actor of row
const FString& outLabel = outBTN.Get().GetRowLabel();
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(outLabel);
//Add selected actor to child
if (FXTC::chkA(A)) {
A->AddChildFromSelectedActors();
//*Set Hidden
//*Get current button toggle state
bool ToggleState = A->GetChildHidden();
A->SetChildHidden(ToggleState);
//*Update list view
UpdateFXTParentList();
}
return FReply::Handled();
}
FReply SFXTParent::OnClickedRB_DestroyParent(const TSharedRef<SRowButton>& outBTN)
{
//*Get actor of row
const FString& outLabel = outBTN.Get().GetRowLabel();
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(outLabel);
//*Reset list
if (FXTC::chkA(A)) {
//* Warning Message popup
FText Message = FXTC::T(
"Destroy [" + A->GetActorLabel() + "]. Proceed? \n"
+ "Yes : Destroy only Parent \n"
+ "No : Abort \n"
+ "YesAll : Destroy Parent and all childs");
FText Title = FXTC::T("Confirm");
EAppReturnType::Type Dialogresult = FMessageDialog::Open(EAppMsgType::YesNoYesAll, Message, &Title);
//*Destroy parent and all childs
if (Dialogresult == EAppReturnType::YesAll)
{
FText Message = FXTC::T(
"Destroy [" + FString::FromInt(A->GetNumOfChilds()) + "] actors from [" + A->GetActorLabel() + "] Proceed?");
Dialogresult = FMessageDialog::Open(EAppMsgType::YesNo, Message, &Title);
if (Dialogresult == EAppReturnType::Yes) {
TArray<AActor*> DestroyList;
A->GetChildList(DestroyList);
//clear child array
A->ResetChildList();
//Destroy Child Actors
for (AActor* i : DestroyList) {
i->ConditionalBeginDestroy();
}
//Destroy Parent
A->ConditionalBeginDestroy();
//Update list view
UpdateFXTParentList();
}
}
//*Destroy parent only
if (Dialogresult == EAppReturnType::Yes)
{
//clear child array
A->ResetChildList();
//Destroy Parent
A->ConditionalBeginDestroy();
//Update list view
UpdateFXTParentList();
}
}
return FReply::Handled();
}
TSharedRef<ITableRow> SFXTParent::OnGenerateRowChildListView(TSharedPtr<FXTParentListItemType> InItem, const TSharedRef<STableViewBase>& OwnerTable)
{
//* Get Actor of Label
const FString& outLabel = InItem.Get()->Label;
AActor* A = FXTC::GetActorByLabel<AActor>(outLabel);
//Class Text
FString ClassStr = A->GetClass()->GetFName().ToString();
FText ClassText = FXTC::T(ClassStr);
//Get Icon Brush
FName IconBrushName = FName(*FString("RowIcon." + ClassStr));
const FSlateBrush* DefaultIconBrush = FXTStyle::Get().GetBrush("RowIcon.Default");
const FSlateBrush* IconBrush = FXTStyle::Get().GetBrush(IconBrushName);
bool bUseDefaultIconBrush = IconBrush->GetResourceName().ToString().Right(16) == "Checkerboard.png" ? true : false;
UE_LOG(LogTemp, Warning, TEXT("given[%s] result[%s]"), *IconBrushName.ToString(), *IconBrush->GetResourceName().ToString().Right(16));
return SNew(STableRow< TSharedPtr<FXTParentListItemType> >, OwnerTable)
.Padding(2.f)
[
SNew(SHorizontalBox)
//Icon
+ SHorizontalBox::Slot().Padding(1.0f, 0.0f).AutoWidth().HAlign(HAlign_Fill).VAlign(VAlign_Center)[
SNew(SImage)
.Image(bUseDefaultIconBrush ? DefaultIconBrush : IconBrush)
.ColorAndOpacity(FFXTStyle::Clr_Default())
.ToolTipText(ClassText)
]
//Label
+ SHorizontalBox::Slot().AutoWidth().HAlign(HAlign_Fill).VAlign(VAlign_Center)[
SNew(STextBlock).Text(FXTC::T(InItem.Get()->Label)).TextStyle(FFXTStyle::GetTBStyle("ListViewText.Row"))
]
//Utility Buttons
+ SHorizontalBox::Slot().HAlign(HAlign_Right)[
SNew(SHorizontalBox)
//remove child button
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SRowButton).OnClicked(this, &SFXTParent::OnClickedRB_RemoveChild).RowLabel(InItem.Get()->Label)
.bUseImage(true)
.Image(FEditorStyle::GetBrush("PropertyWindow.Button_Delete"))
.ToolTipText(FXTC::T(BTN_REMOVECHILD_TOOLTIP))
]
//goto child button
+ SHorizontalBox::Slot().AutoWidth()[
SNew(SRowButton).OnClicked(this, &SFXTParent::OnClickedRB_GotoChild).RowLabel(InItem.Get()->Label)
.bUseImage(true)
.Image(FEditorStyle::GetBrush("PropertyWindow.Button_Browse"))
.ToolTipText(FXTC::T(BTN_GOTOCHILD_TOOLTIP))
]
]
];
}
void SFXTParent::UpdateChildListView()
{
if (!ChildListView.IsValid()) return;
//*Reset list view when SourceParent nullptr
ChildListViewItems.Empty();
if (FXTParentList->GetNumItemsSelected() == 1) {
//*Get selected parent actor
TArray<TSharedPtr<FXTParentListItemType>> SelectedParents = FXTParentList->GetSelectedItems();
const FString& outLabel = SelectedParents[0].Get()->Label;
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(outLabel);
if (FXTC::chkA(A))
{
TArray<AActor*> inChildList;
A->GetChildList(inChildList);
if (inChildList.Num() > 0) {
for (AActor* itr : inChildList) {
ChildListViewItems.Add(MakeShareable(new FXTParentListItemType(itr)));
}
}
//Sort array
if (ChildListViewItems.Num() > 1) {
ChildListViewItems.Sort([](const TSharedPtr<FXTParentListItemType>& A, const TSharedPtr<FXTParentListItemType>& B) {
return FXTC::CompareNumeric(*A->Label, *B->Label) < 0;
});
}
}
}
ChildListView->RequestListRefresh();
}
void SFXTParent::OnSelectionChangedChildListView(TSharedPtr<FXTParentListItemType> InItem, ESelectInfo::Type SelectInfo)
{
}
FReply SFXTParent::OnClicked_ResetChildList()
{
if (!FXTParentList->GetNumItemsSelected() == 1) return FReply::Handled();
//*Get selected parent actor
TArray<TSharedPtr<FXTParentListItemType>> SelectedParents = FXTParentList->GetSelectedItems();
const FString& outLabel = SelectedParents[0].Get()->Label;
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(outLabel);
//*Reset list
if (FXTC::chkA(A) && A->GetNumOfChilds() > 0) {
//* Warning Message popup
FText Message = FXTC::T(
"Remove [" + FString::FromInt(A->GetNumOfChilds()) + "] childs from [" + A->GetActorLabel()
+ "].\n"
+ "It won't destroy actors, only remove reference from parent. Proceed?");
FText Title = FXTC::T("Confirm");
EAppReturnType::Type Dialogresult = FMessageDialog::Open(EAppMsgType::YesNo, Message, &Title);
if (Dialogresult == EAppReturnType::Yes)
{
A->ResetChildList();
//*Update list view
UpdateFXTParentList();
}
}
return FReply::Handled();
}
FReply SFXTParent::OnClickedRB_GotoChild(const TSharedRef<SRowButton>& outBTN)
{
//get client for camera
FEditorViewportClient* client = (FEditorViewportClient*)GEditor->GetActiveViewport()->GetClient();
if (client) {
//*Get actor of row
const FString& outLabel = outBTN.Get().GetRowLabel();
AActor* A = FXTC::GetActorByLabel<AActor>(outLabel);
if (FXTC::chkA(A)) {
//make camera destination
FVector Destination = A->GetActorLocation() - client->GetViewRotation().Vector() * 128.0f;
//Set editor camera location
client->SetViewLocation(Destination);
//select target actor
GEditor->SelectNone(true, true, true);
GEditor->SelectActor(A, true, true, true, true);
}
}
return FReply::Handled();
}
FReply SFXTParent::OnClickedRB_RemoveChild(const TSharedRef<SRowButton>& outBTN)
{
if (!FXTParentList->GetNumItemsSelected() == 1) return FReply::Handled();
//*Get selected parent actor
TArray<TSharedPtr<FXTParentListItemType>> SelectedParents = FXTParentList->GetSelectedItems();
const FString& outLabel = SelectedParents[0].Get()->Label;
AFXTParent* A = FXTC::GetActorByLabel<AFXTParent>(outLabel);
//*Remove child
if (FXTC::chkA(A)) {
const FString& TargetLabel = outBTN.Get().GetRowLabel();
A->RemoveChildByLabel(TargetLabel);
//*Update list view
UpdateFXTParentList();
}
return FReply::Handled();
}
END_SLATE_FUNCTION_BUILD_OPTIMIZATION
FXTParentListItemType::FXTParentListItemType(AFXTParent* InActor)
{
if (InActor) {
Label = InActor->GetActorLabel();
}
}
FXTParentListItemType::FXTParentListItemType(AActor* InActor)
{
if (InActor) {
Label = InActor->GetActorLabel();
}
}
| 32.613873
| 148
| 0.702988
|
Ocelot0
|
5705b4d778658ac0cd66fce65a230dd7b54e5768
| 1,243
|
cpp
|
C++
|
Source/NekoRun/Neko.cpp
|
SaiBalaji22/Neko-Runner
|
1dba4313b5d4f27e3c57e0d9a4da4c2344031f6e
|
[
"MIT"
] | null | null | null |
Source/NekoRun/Neko.cpp
|
SaiBalaji22/Neko-Runner
|
1dba4313b5d4f27e3c57e0d9a4da4c2344031f6e
|
[
"MIT"
] | null | null | null |
Source/NekoRun/Neko.cpp
|
SaiBalaji22/Neko-Runner
|
1dba4313b5d4f27e3c57e0d9a4da4c2344031f6e
|
[
"MIT"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "Neko.h"
#include "Kismet/GameplayStatics.h"
ANeko::ANeko()
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
void ANeko::BeginPlay()
{
Super::BeginPlay();
Player = UGameplayStatics::GetPlayerPawn(this,0);
IsPlayerDead = false;
}
void ANeko::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void ANeko::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
/*This input binding calls in-built Jump and Stop Jump function of the character class*/
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
PlayerInputComponent->BindAction("Slide", IE_Pressed, this, &ANeko::SlideDown);
PlayerInputComponent->BindAction("Slide", IE_Released, this, &ANeko::SlideUp);
}
void ANeko::SlideDown()
{
Crouch();
}
void ANeko::SlideUp()
{
UnCrouch();
}
| 17.263889
| 119
| 0.693484
|
SaiBalaji22
|
5706549bfd13416cbfcfdc3cfff6a336da43f969
| 4,714
|
hpp
|
C++
|
DifferentialEvolution.hpp
|
ianran/CUDADifferentialEvolution
|
ccde059ae52dd0a098752fcfa79602a195153060
|
[
"MIT"
] | 7
|
2017-07-31T06:34:20.000Z
|
2021-11-11T15:28:03.000Z
|
DifferentialEvolution.hpp
|
ianran/CUDADifferentialEvolution
|
ccde059ae52dd0a098752fcfa79602a195153060
|
[
"MIT"
] | null | null | null |
DifferentialEvolution.hpp
|
ianran/CUDADifferentialEvolution
|
ccde059ae52dd0a098752fcfa79602a195153060
|
[
"MIT"
] | null | null | null |
/* Copyright 2017 Ian Rankin
*
* 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.
*/
//
// DifferentialEvolution.hpp
//
// This class is a wrapper to make calls to the cuda differential evolution code easier to work with.
// It handles all of the internal memory allocation for the differential evolution and holds them
// as device memory for the GPU
//
// Example wrapper usage:
//
// float mins[3] = {0,-1,-3.14};
// float maxs[3] = {10,1,3.13};
//
// DifferentialEvolution minimizer(64,100, 3, 0.9, 0.5, mins, maxs);
//
// minimizer.fmin(NULL);
//
//////////////////////////////////////////////////////////////////////////////////////////////
// However if needed to pass arguements then an example usage is:
//
// // create the min and max bounds for the search space.
// float minBounds[2] = {-50, -50};
// float maxBounds[2] = {100, 200};
//
// // a random array or data that gets passed to the cost function.
// float arr[3] = {2.5, 2.6, 2.7};
//
// // data that is created in host, then copied to a device version for use with the cost function.
// struct data x;
// struct data *d_x;
// gpuErrorCheck(cudaMalloc(&x.arr, sizeof(float) * 3));
// unsigned long size = sizeof(struct data);
// gpuErrorCheck(cudaMalloc((void **)&d_x, size));
// x.v = 3;
// x.dim = 2;
// gpuErrorCheck(cudaMemcpy(x.arr, (void *)&arr, sizeof(float) * 3, cudaMemcpyHostToDevice));
//
// // Create the minimizer with a popsize of 192, 50 generations, Dimensions = 2, CR = 0.9, F = 2
// DifferentialEvolution minimizer(192,50, 2, 0.9, 0.5, minBounds, maxBounds);
//
// gpuErrorCheck(cudaMemcpy(d_x, (void *)&x, sizeof(struct data), cudaMemcpyHostToDevice));
//
// // get the result from the minimizer
// std::vector<float> result = minimizer.fmin(d_x);
//
#ifndef DifferentialEvolution_hpp
#define DifferentialEvolution_hpp
#include <stdio.h>
#include <vector>
#include <cuda_runtime.h>
#include "DifferentialEvolutionGPU.h"
///// IMPORTANT ////////
// This is a convienent place to put any structs that could be used to send
// data to the cost. Here is the struct for the example of passing arguements.
// I recommend you keep it here.
struct data {
float *arr;
float v;
int dim;
};
class DifferentialEvolution {
private:
float *d_target1;
float *d_target2;
float *d_cost;
float *d_mutant;
float *d_trial;
float *d_min;
float *d_max;
float *h_cost;
void *d_randStates;
int popSize;
int dim;
int CR;
int numGenerations;
float F;
public:
// Constructor for DifferentialEvolution
//
// @param PopulationSize - the number of agents the DE solver uses.
// @param NumGenerations - the number of generation the differential evolution solver uses.
// @param Dimensions - the number of dimesnions for the solution.
// @param crossoverConstant - the number of mutants allowed pass each generation CR in
// literature given in the range [0,1]
// @param mutantConstant - the scale on mutant changes (F in literature) given [0,2]
// default = 0.5
// @param func - the cost function to minimize.
DifferentialEvolution(int PopulationSize, int NumGenerations, int Dimensions,
float crossoverConstant, float mutantConstant,
float *minBounds, float *maxBounds);
// fmin
// wrapper to the cuda function C function for differential evolution.
// @param args - this a pointer to arguments for the cost function.
// This MUST point to device memory or NULL.
//
// @return the best set of parameters
std::vector<float> fmin(void *args);
};
#endif /* DifferentialEvolution_hpp */
| 35.712121
| 101
| 0.67692
|
ianran
|
5712095f71d6da5d32d03a1af772e7d2d39e7549
| 2,780
|
cpp
|
C++
|
Problems/leetcode/valid-sudoku/main.cpp
|
grand87/timus
|
8edcae276ab74b68fff18da3722460f492534a8a
|
[
"MIT"
] | null | null | null |
Problems/leetcode/valid-sudoku/main.cpp
|
grand87/timus
|
8edcae276ab74b68fff18da3722460f492534a8a
|
[
"MIT"
] | 1
|
2019-05-09T19:17:00.000Z
|
2019-05-09T19:17:00.000Z
|
Problems/leetcode/valid-sudoku/main.cpp
|
grand87/timus
|
8edcae276ab74b68fff18da3722460f492534a8a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <assert.h>
#include <utils.h>
using namespace std;
class Solution {
const char EMPTY_CELL = '.';
const int subs[9][2] = {
//Y X
{ 0, 0 },
{ 3, 0 },
{ 6, 0 },
{ 0, 3 },
{ 3, 3 },
{ 6, 3 },
{ 0, 6 },
{ 3, 6 },
{ 6, 6 },
};
public:
void readSudoku(vector<vector<char>>& board) const {
board.resize(9);
for (int r = 0; r < 9; r++) {
board[r].resize(9);
for (int c = 0; c < 9; c++) {
cin >> board[r][c];
}
}
}
bool isRowValid(const vector<vector<char>>& board, int row) {
bool mask[10] = { false };
for (int i = 0; i < 9; i++) {
if (board[row][i] != EMPTY_CELL) {
const int digit = board[row][i] - '0';
if (mask[digit])
return false;
mask[digit] = true;
}
}
return true;
}
bool isColValid(const vector<vector<char>>& board, int col) {
bool mask[10] = { false };
for (int i = 0; i < 9; i++) {
if (board[i][col] != EMPTY_CELL) {
const int digit = board[i][col] - '0';
if (mask[digit])
return false;
mask[digit] = true;
}
}
return true;
}
bool isSubMatrxiValid(const vector<vector<char>>& board, int row, int col) {
bool mask[10] = { false };
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (board[row + r][col + c] != EMPTY_CELL) {
const int digit = board[row + r][col + c] - '0';
if (mask[digit])
return false;
mask[digit] = true;
}
}
}
return true;
}
bool isValidSudoku(vector<vector<char>>& board) {
for (int r = 0; r < 9; r++) {
if (isRowValid(board, r) == false)
return false;
}
for (int r = 0; r < 9; r++) {
if (isColValid(board, r) == false)
return false;
}
for (int i = 0; i < 9; i++) {
if (isSubMatrxiValid(board, subs[i][0], subs[i][1]) == false)
return false;
}
return true;
}
};
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
#endif
int t = 0;
cin >> t;
for (int i = 0; i < t; i++) {
Solution s;
vector<vector<char>> board;
s.readSudoku(board);
cout << s.isValidSudoku(board);
}
}
| 23.166667
| 80
| 0.411511
|
grand87
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.